From ddb5c1d19c9cbc85cb60e47b681d3656e6c4f06d Mon Sep 17 00:00:00 2001 From: Simon Guilloud Date: Thu, 19 Nov 2026 23:49:01 +0100 Subject: [PATCH 1/3] add ADTs ported to lcf --- .../main/scala/lisa/SetTheoryLibrary.scala | 2 +- .../lisa/maths/SetTheory/Base/Subset.scala | 9 + .../lisa/maths/SetTheory/Base/Union.scala | 42 + .../SetTheory/Cardinal/UniverseRank.scala | 120 +- .../SetTheory/Functions/BasicTheorems.scala | 11 + .../Functions/Operations/Restriction.scala | 37 + .../lisa/maths/SetTheory/Functions/Pi.scala | 2 +- .../maths/SetTheory/Functions/Sigma.scala | 31 +- .../maths/SetTheory/Ordinals/Integer.scala | 676 +++++++ .../Ordinals/TransfiniteRecursion.scala | 83 +- .../maths/SetTheory/Types/ADT/Frontend.scala | 502 ----- .../maths/SetTheory/Types/ADT/Functions.scala | 136 -- .../maths/SetTheory/Types/ADT/Helpers.scala | 1005 ---------- .../maths/SetTheory/Types/ADT/Tactics.scala | 177 -- .../maths/SetTheory/Types/ADT/Typed.scala | 263 --- .../maths/SetTheory/Types/ADT/Untyped.scala | 1659 ----------------- .../maths/SetTheory/Types/ADT/package.scala | 212 +-- .../lisa/maths/SetTheory/Types/Tactics.scala | 273 ++- .../maths/SetTheory/Types/TypingRules.scala | 16 + .../SetTheory/Types/TypingTheorems.scala | 19 + .../SetTheory/Types/TypecheckSuite.scala | 9 +- .../scala/lisa/utils/prooflib/Library.scala | 7 + .../lisa/utils/prooflib/ProofHelpers.scala | 42 +- .../scala/lisa/utils/prooflib/Theorem.scala | 12 + 24 files changed, 1250 insertions(+), 4095 deletions(-) delete mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Frontend.scala delete mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Functions.scala delete mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Helpers.scala delete mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Tactics.scala delete mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Typed.scala delete mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Untyped.scala diff --git a/lisa-sets/src/main/scala/lisa/SetTheoryLibrary.scala b/lisa-sets/src/main/scala/lisa/SetTheoryLibrary.scala index 59d4b734e..0efaae548 100644 --- a/lisa-sets/src/main/scala/lisa/SetTheoryLibrary.scala +++ b/lisa-sets/src/main/scala/lisa/SetTheoryLibrary.scala @@ -12,7 +12,7 @@ object SetTheoryLibrary extends lisa.utils.prooflib.Library { type Proof = lisa.utils.prooflib.Proof - given lisa.utils.prooflib.Library = this + given given_Library: SetTheoryLibrary.type = this /** * A class is nothing more than a first-order formula with a free diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Base/Subset.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Base/Subset.scala index b9e1b79c9..2755d7a31 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Base/Subset.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Base/Subset.scala @@ -169,4 +169,13 @@ object Subset extends lisa.Main { thenHave(thesis) by Substitute(singleton.definition) } + /** + * Theorem --- A superset of a non-empty set is non-empty. + */ + val supersetNotEmpty = Theorem((x ⊆ y, !(x === ∅)) |- !(y === ∅)) { + val subst = have(y === ∅ |- y === ∅) by Hypothesis + have((x ⊆ ∅, y === ∅) |- (x === ∅)) by Tautology.from(rightEmpty) + have((x ⊆ y, y === ∅) |- (x === ∅)) by Congruence.from(subst, lastStep) + } + } diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Base/Union.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Base/Union.scala index b1732c91e..cf2189d5e 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Base/Union.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Base/Union.scala @@ -226,4 +226,46 @@ object Union extends lisa.Main { thenHave(thesis) by Extensionality } + /** + * Theorem --- The unary union is monotonic: if `x ⊆ y` then `⋃x ⊆ ⋃y`. + */ + val unaryMonotonic = Theorem(x ⊆ y |- ⋃(x) ⊆ ⋃(y)) { + have(z ∈ b /\ b ∈ x |- z ∈ b /\ b ∈ x) by Hypothesis + thenHave((x ⊆ y) /\ z ∈ b /\ b ∈ x |- b ∈ x) by Weakening + + have(x ⊆ y |- forall(b, (b ∈ x) ==> (b ∈ y))) by Tautology.from(subsetAxiom of (x := x, y := y)) + thenHave(x ⊆ y |- (b ∈ x) ==> (b ∈ y)) by InstantiateForall(b) + + have((x ⊆ y) /\ (b ∈ x) |- b ∈ y) by Tautology.from(lastStep) + have((x ⊆ y) /\ z ∈ b /\ b ∈ x |- b ∈ y) by Tautology.from(lastStep) + + have((x ⊆ y) /\ z ∈ b /\ b ∈ x |- z ∈ b /\ b ∈ y) by Tautology.from(lastStep) + thenHave((x ⊆ y) /\ z ∈ b /\ b ∈ x |- exists(a, z ∈ a /\ a ∈ y)) by RightExists + thenHave(z ∈ b /\ b ∈ x |- (x ⊆ y) ==> exists(a, z ∈ a /\ a ∈ y)) by Tautology + thenHave(exists(b, z ∈ b /\ b ∈ x) |- (x ⊆ y) ==> exists(a, z ∈ a /\ a ∈ y)) by LeftExists + have(z ∈ ⋃(x) |- (x ⊆ y) ==> exists(a, z ∈ a /\ a ∈ y)) by + Tautology.from(lastStep, ⋃.definition of (x := x, y := b, z := z)) + have(z ∈ ⋃(x) |- (x ⊆ y) ==> z ∈ ⋃(y)) by + Tautology.from(lastStep, ⋃.definition of (x := y, y := b, z := z)) + have(x ⊆ y |- z ∈ ⋃(x) ==> z ∈ ⋃(y)) by Tautology.from(lastStep) + thenHave(x ⊆ y |- forall(z, z ∈ ⋃(x) ==> z ∈ ⋃(y))) by RightForall + have(thesis) by Tautology.from(lastStep, Subset.definition of (x := ⋃(x), y := ⋃(y))) + } + + /** + * Theorem --- `∅` is a left identity for `∪`: `∅ ∪ x === x`. + */ + val leftNeutral = Theorem(∅ ∪ x === x) { + have(∅ ⊆ x) by Tautology.from(Subset.leftEmpty of (x := x)) + val incl1 = have(∅ ∪ x ⊆ x) by Tautology.from( + lastStep, + Subset.reflexivity of (x := x), + leftUnionSubset of (x := ∅, y := x, z := x) + ) + + have(x ⊆ (∅ ∪ x)) by Tautology.from(rightSubset of (x := ∅, y := x)) + + have(thesis) by Tautology.from(incl1, lastStep, Subset.antisymmetry of (x := ∅ ∪ x, y := x)) + } + } diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Cardinal/UniverseRank.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Cardinal/UniverseRank.scala index ce12103c6..fefd0c534 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Cardinal/UniverseRank.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Cardinal/UniverseRank.scala @@ -1,11 +1,23 @@ package lisa.maths.SetTheory.Cardinal -import lisa.maths.SetTheory.Ordinals.Ordinal._ +import lisa.maths.Quantifiers.existsEpsilon +import lisa.maths.SetTheory.Base.Predef.{_, given} +import lisa.maths.SetTheory.Order.Predef._ +import lisa.maths.SetTheory.Order.WellOrders.WellOrder +import lisa.maths.SetTheory.Ordinals.Ordinal +import lisa.maths.SetTheory.Ordinals.Ordinal.comparability +import lisa.maths.SetTheory.Ordinals.Ordinal.elementOfOrdinal +import lisa.maths.SetTheory.Ordinals.Ordinal.ordinal +import lisa.maths.SetTheory.Ordinals.TransitiveSet +import lisa.maths.SetTheory.Relations.BasicTheorems +import lisa.maths.SetTheory.Relations.Examples.MembershipRelation +import lisa.maths.SetTheory.Relations.Predef._ import Universe._ object UniverseRank extends lisa.Main: - private val x, k = variable[Ind] + private val x, y, z, k, a, S = variable[Ind] + private val α, β, γ = variable[Ind] private val U, U1, U2 = variable[Ind] /** @@ -22,12 +34,112 @@ object UniverseRank extends lisa.Main: val level = DEF(λ(U, ε(k, ∀(x, x ∈ k <=> (x ∈ U /\ ordinal(x)))))) /** - * The level of a Universe is an Ordinal (actually an Inaccessible Cardinal). + * Membership in the set of ordinals contained in U. + */ + val levelMembership = Theorem( + x ∈ level(U) <=> (x ∈ U /\ ordinal(x)) + ) { + def property(k: Expr[Ind]) = ∀(x, x ∈ k <=> (x ∈ U /\ ordinal(x))) + have(∃(k, property(k))) by Restate.from(comprehensionSchema of (y := U, φ := λ(x, ordinal(x)))) + thenHave(property(ε(k, property(k)))) by Tautology.fromLastStep(existsEpsilon of (x := k, P := λ(k, property(k)))) + thenHave(∀(x, x ∈ level(U) <=> (x ∈ U /\ ordinal(x)))) by Substitute(level.definition) + thenHave(thesis) by InstantiateForall(x) + } + + /** + * The ordinals contained in a universe form an ordinal. */ val levelIsOrdinal = Theorem( isUniverse(U) ==> ordinal(level(U)) ) { - sorry + assume(isUniverse(U)) + val L = level(U) + val r = MembershipRelation.membershipRelation(L) + + val transitiveLevel = have(TransitiveSet.transitiveSet(L)) subproof { + have((x ∈ y, y ∈ L) |- x ∈ L) subproof { + assume(x ∈ y) + assume(y ∈ L) + val yOrdinal = have(ordinal(y)) by Tautology.from(levelMembership of (x := y)) + val yInU = have(y ∈ U) by Tautology.from(levelMembership of (x := y)) + val ySubsetU = have(y ⊆ U) by Tautology.from(yInU, universeTransitivity of (x := y)) + val xInU = have(x ∈ U) by Tautology.from(ySubsetU, Subset.membership of (x := y, y := U, z := x)) + val xOrdinal = have(ordinal(x)) by Tautology.from(yOrdinal, elementOfOrdinal of (α := y, β := x)) + have(thesis) by Tautology.from(xInU, xOrdinal, levelMembership) + } + thenHave(x ∈ y /\ (y ∈ L) ==> x ∈ L) by Restate + thenHave(∀(x, ∀(y, x ∈ y /\ (y ∈ L) ==> x ∈ L))) by Generalize + thenHave(thesis) by Substitute(TransitiveSet.transitiveSet.definition of (A := L)) + } + + val transitiveRelation = have(transitive(r)(L)) subproof { + have((x ∈ L, y ∈ L, z ∈ L) |- ((x, y) ∈ r) /\ ((y, z) ∈ r) ==> ((x, z) ∈ r)) by Tautology.from( + levelMembership of (x := z), + Ordinal.transitivity of (α := x, β := y, γ := z), + MembershipRelation.membership of (A := L), + MembershipRelation.membership of (x := y, y := z, A := L), + MembershipRelation.membership of (x := x, y := z, A := L) + ) + val implication = (x ∈ L) ==> ((y ∈ L) ==> ((z ∈ L) ==> (((x, y) ∈ r) /\ ((y, z) ∈ r) ==> ((x, z) ∈ r)))) + thenHave(implication) by Restate + thenHave(∀(x, ∀(y, ∀(z, implication)))) by Generalize + thenHave(∀(x ∈ L, ∀(y ∈ L, ∀(z ∈ L, ((x, y) ∈ r) /\ ((y, z) ∈ r) ==> ((x, z) ∈ r))))) by Tableau + thenHave(thesis) by Substitute(transitive.definition of (R := r, X := L)) + } + + val totalRelation = have(total(r)(L)) subproof { + have((x ∈ L, y ∈ L) |- ((x, y) ∈ r) \/ ((y, x) ∈ r) \/ (x === y)) by Tautology.from( + levelMembership, + levelMembership of (x := y), + comparability of (α := x, β := y), + MembershipRelation.membership of (A := L), + MembershipRelation.membership of (x := y, y := x, A := L) + ) + val implication = (x ∈ L) ==> ((y ∈ L) ==> (((x, y) ∈ r) \/ ((y, x) ∈ r) \/ (x === y))) + thenHave(implication) by Restate + thenHave(∀(x, ∀(y, implication))) by Generalize + thenHave(∀(x ∈ L, ∀(y ∈ L, ((x, y) ∈ r) \/ ((y, x) ∈ r) \/ (x === y)))) by Tableau + thenHave(thesis) by Substitute(total.definition of (R := r, X := L)) + } + + val foundedRelation = have(wellFounded(r)(L)) subproof { + have((S ⊆ L, S ≠ ∅) |- ∃(a, minimal(a)(S)(r))) subproof { + assume(S ⊆ L) + assume(S ≠ ∅) + val foundation = have(∃(a, a ∈ S /\ ∀(x, x ∈ S ==> x ∉ a))) by Tautology.from(axiomOfFoundation of (x := S)) + have((a ∈ S, ∀(x, x ∈ S ==> x ∉ a)) |- minimal(a)(S)(r)) subproof { + assume(a ∈ S) + assume(∀(x, x ∈ S ==> x ∉ a)) + thenHave(x ∈ S ==> x ∉ a) by InstantiateForall(x) + thenHave(x ∈ S ==> (x, a) ∉ r) by Tautology.fromLastStep(MembershipRelation.membership of (x := x, y := a, A := L)) + thenHave(∀(x, x ∈ S ==> (x, a) ∉ r)) by RightForall + thenHave(a ∈ S /\ ∀(x, x ∈ S ==> (x, a) ∉ r)) by Tautology + thenHave(thesis) by Substitute(minimal.definition of (a := a, A := S, < := r)) + } + thenHave((a ∈ S, ∀(x, x ∈ S ==> x ∉ a)) |- ∃(a, minimal(a)(S)(r))) by RightExists + thenHave(a ∈ S /\ ∀(x, x ∈ S ==> x ∉ a) |- ∃(a, minimal(a)(S)(r))) by Restate + thenHave(∃(a, a ∈ S /\ ∀(x, x ∈ S ==> x ∉ a)) |- ∃(a, minimal(a)(S)(r))) by LeftExists + have(thesis) by Cut(foundation, lastStep) + } + thenHave((S ⊆ L) /\ (S ≠ ∅) ==> ∃(a, minimal(a)(S)(r))) by Restate + thenHave(∀(S, (S ⊆ L) /\ (S ≠ ∅) ==> ∃(a, minimal(a)(S)(r)))) by Generalize + thenHave(thesis) by Substitute(wellFounded.definition of (R := r, X := L)) + } + + have(ordinal(L)) by Tautology.from( + transitiveLevel, + transitiveRelation, + totalRelation, + foundedRelation, + MembershipRelation.irreflexivity of (A := L), + MembershipRelation.isRelation of (A := L), + BasicTheorems.relationOnIsRelation of (R := r, X := L), + strictPartialOrder.definition of (A := L, < := r), + strictTotalOrder.definition of (A := L, < := r), + WellOrder.wellOrder.definition of (A := L, < := r), + ordinal.definition of (α := L) + ) + thenHave(thesis) by Restate } /** diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/BasicTheorems.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/BasicTheorems.scala index f917c29db..5e354bdaf 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/BasicTheorems.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/BasicTheorems.scala @@ -1046,4 +1046,15 @@ object BasicTheorems extends lisa.Main { have(thesis) by Tautology.from(`==>`, `<==`) } + /** + * Theorem --- A function with a non-empty domain is non-empty. + */ + val nonEmptyDomain = Theorem(!(dom(h) === ∅) |- !(h === ∅)) { + val domEmpty = have(dom(∅) === ∅) by Restate.from( + lisa.maths.SetTheory.Relations.Examples.EmptyRelation.emptyDomain + ) + have(h === ∅ |- dom(h) === ∅) by Congruence.from(domEmpty) + have(thesis) by Tautology.from(lastStep) + } + } diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Operations/Restriction.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Operations/Restriction.scala index 36db39636..c1fd0c5cd 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Operations/Restriction.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Operations/Restriction.scala @@ -371,4 +371,41 @@ object Restriction extends lisa.Main { have(z ∈ (f ↾ A) <=> z ∈ (g ↾ A)) by Tautology.from(fwd, bwd) thenHave(thesis) by Extensionality } + + /** + * Theorem --- If `x` is in both the domain of `f` and the restriction set `d`, + * then `f ↾ d` is non-empty. + */ + val notEmpty = Theorem( + (function(f), x ∈ dom(f), x ∈ d) |- !((f ↾ d) === ∅) + ) { + assume(function(f), x ∈ dom(f), x ∈ d) + have(x ∈ (dom(f) ∩ d)) by Tautology.from(Intersection.membership of (z := x, x := dom(f), y := d)) + val inRestrictedDomain = thenHave(x ∈ dom(f ↾ d)) by Substitute(domain of (A := d)) + have(thesis) by Tautology.from( + inRestrictedDomain, + EmptySet.setWithElementNonEmpty of (x := x, y := dom(f ↾ d)), + BasicTheorems.nonEmptyDomain of (h := f ↾ d) + ) + } + + /** + * Theorem --- Restriction is monotonic in the restriction set: if `x ⊆ y` + * then `f ↾ x ⊆ f ↾ y`. + */ + val setMonotonic = Theorem( + x ⊆ y |- (f ↾ x) ⊆ (f ↾ y) + ) { + have((x ⊆ y, z ∈ (f ↾ x)) |- z ∈ (f ↾ y)) by Tautology.from( + Subset.membership of (z := fst(z)), + membership of (A := x, z := z), + membership of (A := y, z := z) + ) + thenHave(x ⊆ y |- (z ∈ (f ↾ x)) ==> (z ∈ (f ↾ y))) by Tautology + thenHave(x ⊆ y |- forall(z, (z ∈ (f ↾ x)) ==> (z ∈ (f ↾ y)))) by RightForall + have(thesis) by Tautology.from( + lastStep, + lisa.maths.SetTheory.Base.Subset.definition of (x := f ↾ x, y := f ↾ y) + ) + } } diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Pi.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Pi.scala index 102b151fe..2782a3068 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Pi.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Pi.scala @@ -58,7 +58,7 @@ object Pi extends lisa.Main { */ extension (a: Expr[Ind]) { infix def ->:(b: Expr[Ind]): Expr[Ind] = - Pi(a)(λ(x, b)) + Pi(a)(λ(x.freshRename(Seq(b)), b)) } object `->:`: def unapply(e: Expr[?]): Option[(Expr[Ind], Expr[Ind])] = diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Sigma.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Sigma.scala index 6064cc1c5..38ff97a97 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Sigma.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/Sigma.scala @@ -25,7 +25,7 @@ object Sigma extends lisa.Main { * * `Σ(A, B) = {(a, b) | a ∈ A, b ∈ B(a) }` */ - val Σ = DEF(λ(A, λ(B, { x ∈ (A × { B(a) | a ∈ A }) | snd(x) ∈ B(fst(x)) }))) + val Σ = DEF(λ(A, λ(B, { x ∈ (A × ⋃({ B(a) | a ∈ A })) | snd(x) ∈ B(fst(x)) }))) /** * Theorem --- The dependent sum on the empty set is ∅. @@ -33,7 +33,7 @@ object Sigma extends lisa.Main { val emptySet = Theorem( Σ(∅)(B) === ∅ ) { - val W = { B(a) | a ∈ ∅ } + val W = ⋃({ B(a) | a ∈ ∅ }) have(z ∈ { x ∈ (∅ × W) | snd(x) ∈ B(fst(x)) } <=> z ∈ (∅ × W) /\ (snd(z) ∈ B(fst(z)))) by Comprehension.apply thenHave(z ∈ Σ(∅)(B) <=> z ∈ (∅ × W) /\ (snd(z) ∈ B(fst(z)))) by Substitute(Σ.definition of (A := ∅)) thenHave(z ∈ Σ(∅)(B) <=> z ∈ ∅ /\ (snd(z) ∈ B(fst(z)))) by Substitute(CartesianProduct.leftEmpty of (B := W)) @@ -47,7 +47,32 @@ object Sigma extends lisa.Main { val membership = Theorem( (a, b) ∈ Σ(A)(B) <=> (a ∈ A) /\ (b ∈ B(a)) ) { - sorry + val fibers = { B(x) | x ∈ A } + val bound = A × ⋃(fibers) + val expanded = have( + (a, b) ∈ { x ∈ bound | snd(x) ∈ B(fst(x)) } <=> + ((a, b) ∈ bound) /\ (snd(a, b) ∈ B(fst(a, b))) + ) by Comprehension.apply + val projections = have(snd(a, b) ∈ B(fst(a, b)) <=> b ∈ B(a)) by Congruence.from( + Pair.pairFst of (x := a, y := b), + Pair.pairSnd of (x := a, y := b) + ) + val pairInBound = CartesianProduct.pairMembership of (x := a, y := b, A := A, B := ⋃(fibers)) + val inFiberUnion = have((a ∈ A, b ∈ B(a)) |- b ∈ ⋃(fibers)) subproof { + assume(a ∈ A) + assume(b ∈ B(a)) + have(a ∈ A /\ (B(a) === B(a))) by Tautology + thenHave(∃(x ∈ A, B(x) === B(a))) by RightExists + val fiberMember = thenHave(B(a) ∈ fibers) by Tautology.fromLastStep( + Replacement.membership of (F := λ(x, B(x)), y := B(a)) + ) + have(B(a) ∈ fibers /\ b ∈ B(a)) by Tautology.from(fiberMember) + thenHave(∃(x, x ∈ fibers /\ b ∈ x)) by RightExists + thenHave(thesis) by Tautology.fromLastStep(unionAxiom of (x := fibers, z := b)) + } + have((a, b) ∈ { x ∈ bound | snd(x) ∈ B(fst(x)) } <=> (a ∈ A) /\ (b ∈ B(a))) by + Tautology.from(expanded, projections, pairInBound, inFiberUnion) + thenHave(thesis) by Substitute(Σ.definition) } } diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/Integer.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/Integer.scala index 2ed983c92..1540be9fc 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/Integer.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/Integer.scala @@ -1,5 +1,15 @@ package lisa.maths.SetTheory.Ordinals +import lisa.maths.Quantifiers.existsEpsilon +import lisa.maths.SetTheory.Base.EmptySet +import lisa.maths.SetTheory.Base.FoundationAxiom +import lisa.maths.SetTheory.Base.Singleton +import lisa.maths.SetTheory.Base.Subset +import lisa.maths.SetTheory.Base.Union +import lisa.maths.SetTheory.Base.Union.∪ +import lisa.maths.SetTheory.Ordinals.TransfiniteInduction.transfiniteInductionCases +import lisa.maths.SetTheory.SetTheory + import Ordinal._ /** @@ -11,8 +21,15 @@ import Ordinal._ */ object Integer extends lisa.Main { + private val a, b = variable[Ind] + private val A = variable[Ind] + private val k, n, m = variable[Ind] private val x = variable[Ind] private val α, β = variable[Ind] + private val y, z = variable[Ind] + private val γ, λ_ = variable[Ind] + private val φ = variable[Ind >>: Prop] + private val P = variable[Ind >>: Prop] /** * Definition --- An ordinal `α` is an integer if and only if all its predecessors are zero or successors. @@ -26,4 +43,663 @@ object Integer extends lisa.Main { */ val ω = DEF(ε(x, ∀(α, α ∈ x <=> integer(α)))) + /** + * Membership in a successor is membership in its predecessor or equality to it. + */ + val succMembership = Theorem((k ∈ S(n)) <=> (k ∈ n) \/ (k === n)) { + have(k ∈ (n ∪ Singleton.singleton(n)) <=> (k ∈ n) \/ (k === n)) by Tautology.from( + Union.membership of (x := n, y := Singleton.singleton(n), z := k), + Singleton.membership of (x := n, y := k) + ) + thenHave(thesis) by Substitute(S.definition of (α := n)) + } + + /** + * A set belongs to its own successor. + */ + val selfInSuccessor = Lemma(n ∈ S(n)) { + have(thesis) by Tautology.from(succMembership of (k := n)) + } + + /** + * Lemma --- The empty set (zero) is an integer. + */ + private val zeroIsInteger = Theorem( + integer(∅) + ) { + have(β <= ∅ |- (β ∈ ∅) \/ (β === ∅)) by Tautology + have(β ∈ ∅ |- ()) by Tautology.from(EmptySet.definition of (x := β)) + have(β <= ∅ |- β === ∅) by Tautology.from(lastStep, lastStep) + thenHave((β <= ∅) ==> (β === ∅) \/ successorOrdinal(β)) by Tautology + thenHave(∀(β, (β <= ∅) ==> (β === ∅) \/ successorOrdinal(β))) by RightForall + thenHave(thesis) by Substitute(integer.definition of (α := ∅)) + } + + /** + * Theorem --- Every integer is an ordinal. + */ + val integerIsOrdinal = Theorem( + integer(α) |- ordinal(α) + ) { + assume(integer(α)) + thenHave(∀(β, β <= α ==> (β === ∅) \/ successorOrdinal(β))) by + Substitute(integer.definition) + thenHave((α <= α) ==> (α === ∅) \/ successorOrdinal(α)) by InstantiateForall(α) + val splitFact = have((α === ∅) \/ successorOrdinal(α)) by Tautology.from(lastStep) + + val zeroCase = have(α === ∅ |- ordinal(α)) by Congruence.from(Ordinal.zeroOrdinal) + + val succCase = have(successorOrdinal(α) |- ordinal(α)) subproof { + assume(successorOrdinal(α)) + val succWitness = + thenHave(∃(γ, ordinal(γ) /\ (α === S(γ)))) by + Substitute(successorOrdinal.definition) + have((α === S(γ)) |- ordinal(γ) ==> ordinal(S(γ))) by Tautology.from( + Ordinal.sucessorIsOrdinal of (α := γ) + ) + have(α === S(γ) |- ordinal(γ) ==> ordinal(α)) by Congruence.from(lastStep) + thenHave(ordinal(γ) /\ (α === S(γ)) |- ordinal(α)) by Tautology + val ordFromWitness = + thenHave(∃(γ, ordinal(γ) /\ (α === S(γ))) |- ordinal(α)) by LeftExists + + have(thesis) by Cut(succWitness, ordFromWitness) + } + + val splitCases = have((α === ∅) \/ successorOrdinal(α) |- ordinal(α)) by LeftOr(zeroCase, succCase) + have(thesis) by Cut(splitFact, splitCases) + } + + /** + * Lemma --- The successor of an integer is an integer. + */ + private val integerSuccessor = Theorem( + integer(α) |- integer(S(α)) + ) { + assume(integer(α)) + + val splitCases = have(β <= S(α) |- (β ∈ α) \/ (β === α) \/ (β === S(α))) by + Tautology.from(succMembership of (k := β, n := α)) + + val intAll = have(∀(β, β <= α ==> (β === ∅) \/ successorOrdinal(β))) by + Tautology.from(integer.definition) + val intAtBeta = have(β <= α ==> (β === ∅) \/ successorOrdinal(β)) by InstantiateForall(β)(intAll) + + val inAlphaCase = have(β ∈ α |- (β === ∅) \/ successorOrdinal(β)) by + Tautology.from(intAtBeta) + + val intAtAlpha = have(α <= α ==> (α === ∅) \/ successorOrdinal(α)) by InstantiateForall(α)(intAll) + have((α === ∅) \/ successorOrdinal(α)) by Tautology.from(intAtAlpha) + val eqAlphaCase = have((β === α) |- (β === ∅) \/ successorOrdinal(β)) by + Congruence.from(lastStep) + + val eqSuccCase = have((β === S(α)) |- (β === ∅) \/ successorOrdinal(β)) subproof { + assume(β === S(α)) + val ordAlpha = have(ordinal(α)) by Tautology.from(integerIsOrdinal) + have(S(α) === S(α)) by Restate + have(ordinal(α) /\ (S(α) === S(α))) by Tautology.from(ordAlpha, lastStep) + thenHave(∃(γ, ordinal(γ) /\ (S(α) === S(γ)))) by RightExists + have(successorOrdinal(S(α))) by Tautology.from( + lastStep, + successorOrdinal.definition of (α := S(α)) + ) + thenHave((β === S(α)) |- successorOrdinal(β)) by Congruence + have(thesis) by Tautology.from(lastStep) + } + + val splitToGoal = have( + (β ∈ α) \/ (β === α) \/ (β === S(α)) |- (β === ∅) \/ successorOrdinal(β) + ) by Tautology.from(inAlphaCase, eqAlphaCase, eqSuccCase) + + have(β <= S(α) |- (β === ∅) \/ successorOrdinal(β)) by Cut(splitCases, splitToGoal) + thenHave((β <= S(α)) ==> (β === ∅) \/ successorOrdinal(β)) by RightImplies + thenHave(∀(β, (β <= S(α)) ==> (β === ∅) \/ successorOrdinal(β))) by RightForall + thenHave(thesis) by Substitute(integer.definition of (α := S(α))) + } + + /** + * Every element of an integer is an integer. + */ + val integerHereditary = Theorem((integer(α), β ∈ α) |- integer(β)) { + assume(integer(α), β ∈ α) + val memberCase = have(γ ∈ β |- γ ∈ α) by Tautology.from( + integerIsOrdinal, + Ordinal.transitivity of (α := γ, β := β, γ := α) + ) + val equalityCase = have(γ === β |- γ ∈ α) by Congruence + val belowAlpha = have(γ <= β |- γ <= α) by Tautology.from(memberCase, equalityCase) + + have(∀(γ, γ <= α ==> (γ === ∅) \/ successorOrdinal(γ))) by Tautology.from(integer.definition) + thenHave(γ <= α ==> (γ === ∅) \/ successorOrdinal(γ)) by InstantiateForall(γ) + have(γ <= β ==> (γ === ∅) \/ successorOrdinal(γ)) by Tautology.from(lastStep, belowAlpha) + thenHave(∀(γ, γ <= β ==> (γ === ∅) \/ successorOrdinal(γ))) by RightForall + thenHave(thesis) by Substitute(integer.definition of (α := β)) + } + + /** + * If a successor is an integer, its predecessor is an integer. + */ + private val integerPredecessor = Theorem(integer(S(α)) |- integer(α)) { + have(thesis) by Tautology.from( + integerHereditary of (α := S(α), β := α), + selfInSuccessor of (n := α) + ) + } + + /** + * Lemma --- Every integer belongs to any inductive set. + */ + private val integerInInductive = Lemma( + (SetTheory.inductive(y), integer(α)) |- α ∈ y + ) { + def PInt(t: Expr[Ind]): Expr[Prop] = integer(t) ==> t ∈ y + + val zeroCase = have(SetTheory.inductive(y) |- PInt(∅)) subproof { + assume(SetTheory.inductive(y)) + have(∅ ∈ y) by Tautology.from(SetTheory.inductive.definition of (x := y)) + have(integer(∅) ==> (∅ ∈ y)) by Tautology.from(lastStep) + have(thesis) by Tautology.from(lastStep) + } + + val succEq = have(SetTheory.successor(β) === S(β)) by + Congruence.from(SetTheory.successor.definition of (x := β), S.definition of (α := β)) + + val succCase = have( + SetTheory.inductive(y) |- ∀(β, ordinal(β) /\ PInt(β) ==> PInt(S(β))) + ) subproof { + assume(SetTheory.inductive(y)) + have(ordinal(β) /\ PInt(β) |- PInt(S(β))) subproof { + assume(ordinal(β) /\ PInt(β)) + val ih = have(PInt(β)) by Tautology + assume(integer(S(β))) + val predInt = have(integer(β)) by Tautology.from(integerPredecessor of (α := β)) + val betaInY = have(β ∈ y) by Tautology.from(ih, predInt) + val succAll = have(∀(γ, γ ∈ y ==> SetTheory.successor(γ) ∈ y)) by + Tautology.from(SetTheory.inductive.definition of (x := y)) + val succAtBeta = have((β ∈ y) ==> SetTheory.successor(β) ∈ y) by InstantiateForall(β)(succAll) + val succClosure = have((β ∈ y) ==> (S(β) ∈ y)) by + Congruence.from(succAtBeta, succEq) + val succInY = have(S(β) ∈ y) by Tautology.from(succClosure, betaInY) + have(S(β) ∈ y) by Restate.from(succInY) + have((SetTheory.inductive(y), ordinal(β) /\ PInt(β)) |- integer(S(β)) ==> (S(β) ∈ y)) by + Tautology.from(lastStep) + have(thesis) by Tautology.from(lastStep) + } + thenHave(ordinal(β) /\ PInt(β) ==> PInt(S(β))) by Restate + thenHave(thesis) by RightForall + } + + val limitCase = have( + SetTheory.inductive(y) |- ∀(λ_, limitOrdinal(λ_) ==> (∀(β ∈ λ_, PInt(β)) ==> PInt(λ_))) + ) subproof { + assume(SetTheory.inductive(y)) + have(limitOrdinal(λ_) ==> (∀(β ∈ λ_, PInt(β)) ==> PInt(λ_))) subproof { + assume(limitOrdinal(λ_)) + assume(∀(β ∈ λ_, PInt(β))) + assume(integer(λ_)) + + have(integer(λ_) |- integer(λ_)) by Restate + thenHave(integer(λ_) |- ∀(β, β <= λ_ ==> (β === ∅) \/ successorOrdinal(β))) by + Substitute(integer.definition of (α := λ_)) + val intAtSelf = thenHave(integer(λ_) |- λ_ <= λ_ ==> (λ_ === ∅) \/ successorOrdinal(λ_)) by + InstantiateForall(λ_) + + val selfLeq = have((λ_ ∈ λ_) \/ (λ_ === λ_)) by Tautology + val intSplit = have( + (limitOrdinal(λ_), ∀(β ∈ λ_, PInt(β)), integer(λ_), SetTheory.inductive(y)) |- + (λ_ === ∅) \/ successorOrdinal(λ_) + ) by + Tautology.from(intAtSelf, selfLeq) + + val notSplit = have(limitOrdinal(λ_) |- ¬((λ_ === ∅) \/ successorOrdinal(λ_))) by + Tautology.from(limitOrdinal.definition of (α := λ_)) + + have((limitOrdinal(λ_), ∀(β ∈ λ_, PInt(β)), integer(λ_), SetTheory.inductive(y)) |- ()) by + Tautology.from(intSplit, notSplit) + have((limitOrdinal(λ_), ∀(β ∈ λ_, PInt(β)), integer(λ_)) |- λ_ ∈ y) by Tautology.from(lastStep) + have((limitOrdinal(λ_), ∀(β ∈ λ_, PInt(β))) |- integer(λ_) ==> (λ_ ∈ y)) by + Tautology.from(lastStep) + have(thesis) by Tautology.from(lastStep) + } + thenHave(thesis) by RightForall + } + + val ordCases = have(SetTheory.inductive(y) |- ∀(β, ordinal(β) ==> PInt(β))) by + Tautology.from( + zeroCase, + succCase, + limitCase, + transfiniteInductionCases of (P := λ(β, PInt(β))) + ) + + val atAlpha = have(SetTheory.inductive(y) |- ordinal(α) ==> PInt(α)) by + InstantiateForall(α)(ordCases) + + val alphaOrd = have((SetTheory.inductive(y), integer(α)) |- ordinal(α)) by + Tautology.from(integerIsOrdinal) + + val alphaP = have((SetTheory.inductive(y), integer(α)) |- PInt(α)) by + Tautology.from(alphaOrd, atAlpha) + + have(thesis) by Tautology.from(alphaP) + } + + /** + * Lemma --- Characterization of membership in `ω`: `α ∈ ω ⇔ integer(α)`. + */ + val omegaCharacterization = Lemma(∀(α, α ∈ ω <=> integer(α))) { + def Q(s: Expr[Ind]): Expr[Prop] = ∀(α, α ∈ s <=> integer(α)) + def R(i: Expr[Ind], s: Expr[Ind]): Expr[Prop] = ∀(β, β ∈ s <=> (β ∈ i) /\ integer(β)) + + val i = variable[Ind] + val s = variable[Ind] + + val existsQFromInductive = have(SetTheory.inductive(i) |- ∃(x, Q(x))) subproof { + assume(SetTheory.inductive(i)) + + val existsR = have(∃(s, R(i, s))) by + Weakening(lisa.maths.SetTheory.Base.Comprehension.existence of (y := i, φ := λ(β, integer(β)))) + + val epsSet: Expr[Ind] = ε(s, R(i, s)) + val rAtEps = have(R(i, epsSet)) by + Tautology.from(existsR, existsEpsilon of (x := s, P := λ(s, R(i, s)))) + + val rAtBeta = have(β ∈ epsSet <=> (β ∈ i) /\ integer(β)) by + InstantiateForall(β)(rAtEps) + + val forward = have(β ∈ epsSet ==> integer(β)) by Tautology.from( + rAtBeta + ) + + val inInductive = have(integer(β) ==> β ∈ i) by + Tautology.from(integerInInductive of (y := i, α := β)) + + val backward = have(integer(β) ==> β ∈ epsSet) by Tautology.from( + rAtBeta, + inInductive + ) + + have(β ∈ epsSet <=> integer(β)) by Tautology.from(forward, backward) + thenHave(∀(β, β ∈ epsSet <=> integer(β))) by RightForall + thenHave(∃(x, Q(x))) by RightExists + have(thesis) by Tautology.from(lastStep) + } + + val existsQ = have(∃(x, Q(x))) by Cut( + SetTheory.inductiveSetExists, { + have(∃(i, SetTheory.inductive(i)) |- ∃(x, Q(x))) by LeftExists(existsQFromInductive) + lastStep + } + ) + + val qAtEpsilon = have(Q(ε(x, Q(x)))) by + Tautology.from(existsQ, existsEpsilon of (x := x, P := λ(x, Q(x)))) + + val omegaEqEpsilon = have(ω === ε(x, Q(x))) by Congruence.from(ω.definition) + have(Q(ε(x, Q(x)))) by Restate.from(qAtEpsilon) + val qAtOmega = thenHave(Q(ω)) by Substitute(omegaEqEpsilon) + + have(thesis) by Tautology.from(qAtOmega) + } + + /** + * Theorem --- Every element of `ω` is an ordinal. + */ + val elementIsOrdinal = Theorem(α ∈ ω |- ordinal(α)) { + have(α ∈ ω |- integer(α)) by InstantiateForall(α)(omegaCharacterization) + have(thesis) by Tautology.from(lastStep, integerIsOrdinal) + } + + /** + * Comparability --- any two elements of `ω` are comparable by membership. + */ + val comparability = Theorem((m ∈ ω, n ∈ ω) |- (m === n) \/ (m ∈ n) \/ (n ∈ m)) { + val mOrd = have(m ∈ ω |- ordinal(m)) by Restate.from(elementIsOrdinal of (α := m)) + val nOrd = have(n ∈ ω |- ordinal(n)) by Restate.from(elementIsOrdinal of (α := n)) + have(thesis) by Tautology.from(mOrd, nOrd, Ordinal.comparability of (α := m, β := n)) + } + + /** + * Bridge theorem --- Successor closure of `ω`. + */ + val omegaSuccessor = Theorem( + α ∈ ω |- S(α) ∈ ω + ) { + have(α ∈ ω |- integer(α)) by InstantiateForall(α)(omegaCharacterization) + val st1 = have(α ∈ ω |- integer(S(α))) by Tautology.from(lastStep, integerSuccessor) + have(integer(S(α)) |- S(α) ∈ ω) by InstantiateForall(S(α))(omegaCharacterization) + have(thesis) by Tautology.from(lastStep, st1) + } + + /** + * Bridge theorem --- Predecessor closure of `ω` for successors. + */ + val omegaPredecessor = Theorem( + S(α) ∈ ω |- α ∈ ω + ) { + have(S(α) ∈ ω |- integer(S(α))) by InstantiateForall(S(α))(omegaCharacterization) + val st1 = have(S(α) ∈ ω |- integer(α)) by Tautology.from(lastStep, integerPredecessor) + have(integer(α) |- α ∈ ω) by InstantiateForall(α)(omegaCharacterization) + have(thesis) by Tautology.from(lastStep, st1) + } + + /** + * Bridge theorem --- Every nonzero natural is a S of a natural. + */ + val nonZeroOmegaHasPredecessor = Theorem( + (α ∈ ω, α =/= ∅) |- ∃(β, β ∈ ω /\ (α === S(β))) + ) { + assume(α ∈ ω) + assume(α =/= ∅) + + val alphaIsInteger = have(integer(α)) by InstantiateForall(α)(omegaCharacterization) + val intPreds = have(∀(β, β <= α ==> (β === ∅) \/ successorOrdinal(β))) by + Substitute(integer.definition.of(α := α))(alphaIsInteger) + val succSplit = have((α === ∅) \/ successorOrdinal(α)) by Tautology.from( + have(α <= α ==> (α === ∅) \/ successorOrdinal(α)) by InstantiateForall(α)(intPreds) + ) + val succOrdinalAtAlpha = have(successorOrdinal(α)) by Tautology.from(succSplit, have(!(α === ∅)) by Tautology) + + val succWitness = have(∃(γ, ordinal(γ) /\ (α === S(γ)))) by Tautology.from( + succOrdinalAtAlpha, + have(successorOrdinal(α) ==> ∃(γ, ordinal(γ) /\ (α === S(γ)))) by + Tautology.from(successorOrdinal.definition.of(α := α)) + ) + + val omegaWitnessBranch = have((ordinal(γ) /\ (α === S(γ))) |- ∃(β, β ∈ ω /\ (α === S(β)))) subproof { + assume(ordinal(γ) /\ (α === S(γ))) + val alphaEqSucc = have(α === S(γ)) by Tautology + val succInOmega = have(S(γ) ∈ ω) by Congruence.from(have(α ∈ ω) by Tautology, alphaEqSucc) + val gammaInOmega = have(γ ∈ ω) by Tautology.from( + succInOmega, + omegaPredecessor.of(α := γ) + ) + have(γ ∈ ω /\ (α === S(γ))) by Tautology.from(gammaInOmega, alphaEqSucc) + thenHave(∃(β, β ∈ ω /\ (α === S(β)))) by RightExists + } + val omegaWitness = have(∃(γ, ordinal(γ) /\ (α === S(γ))) |- ∃(β, β ∈ ω /\ (α === S(β)))) by + LeftExists.withParameters(ordinal(γ) /\ (α === S(γ)), γ)(omegaWitnessBranch) + + have(thesis) by Cut(succWitness, omegaWitness) + } + + /** + * Bridge theorem --- Induction on `ω` with S `S`. + */ + val omegaInduction = Theorem( + (P(∅), ∀(α, α ∈ ω ==> (P(α) ==> P(S(α))))) |- ∀(α, α ∈ ω ==> P(α)) + ) { + def Q(t: Expr[Ind]): Expr[Prop] = t ∈ ω ==> P(t) + val succStepAssumption = ∀(γ, γ ∈ ω ==> (P(γ) ==> P(S(γ)))) + + assume(P(∅)) + assume(succStepAssumption) + + val qZero = have(P(∅) |- Q(∅)) subproof { + val zeroChar = have(∅ ∈ ω <=> integer(∅)) by InstantiateForall(∅)(omegaCharacterization) + val zeroInOmega = have(∅ ∈ ω) by Tautology.from( + zeroIsInteger, + zeroChar + ) + have(thesis) by Tautology.from(zeroInOmega) + } + + val qSucc = have(succStepAssumption |- ∀(α, ordinal(α) /\ Q(α) ==> Q(S(α)))) subproof { + val hyp = ordinal(α) /\ Q(α) + have(hyp |- Q(α)) by Tautology + + have(S(α) ∈ ω |- α ∈ ω) by Tautology.from(omegaPredecessor) + thenHave((S(α) ∈ ω, Q(α)) |- P(α)) by Tautology + + have(succStepAssumption |- succStepAssumption) by Hypothesis + thenHave(succStepAssumption |- α ∈ ω ==> (P(α) ==> P(S(α)))) by InstantiateForall(α) + val stepAlpha = lastStep + have((succStepAssumption, S(α) ∈ ω, Q(α)) |- P(S(α))) by Tautology.from( + stepAlpha, + omegaPredecessor of (α := α) + ) + thenHave((succStepAssumption, hyp, S(α) ∈ ω) |- P(S(α))) by Tautology + have((succStepAssumption, hyp) |- S(α) ∈ ω ==> P(S(α))) by Tautology.from(lastStep) + thenHave((succStepAssumption, hyp) |- Q(S(α))) by Restate + have(succStepAssumption |- hyp ==> Q(S(α))) by Tautology.from(lastStep) + thenHave(thesis) by Generalize + } + + val qZeroFact = have(Q(∅)) by Tautology.from(qZero) + val qSuccFact = have(∀(α, ordinal(α) /\ Q(α) ==> Q(S(α)))) by Tautology.from(qSucc) + + val qLimit = have(∀(λ_, limitOrdinal(λ_) ==> (∀(β ∈ λ_, Q(β)) ==> Q(λ_)))) subproof { + val h1 = limitOrdinal(λ_) + val h2 = ∀(β ∈ λ_, Q(β)) + + val lambdaChar = have(λ_ ∈ ω <=> integer(λ_)) by InstantiateForall(λ_)(omegaCharacterization) + have((λ_ ∈ ω) |- integer(λ_)) by Tautology.from( + lambdaChar + ) + thenHave((λ_ ∈ ω) |- ∀(β, β <= λ_ ==> (β === ∅) \/ successorOrdinal(β))) by + Substitute(integer.definition of (α := λ_)) + thenHave(λ_ ∈ ω |- λ_ <= λ_ ==> (λ_ === ∅) \/ successorOrdinal(λ_)) by InstantiateForall(λ_) + val step1 = lastStep + have(λ_ <= λ_) by Tautology + have(λ_ ∈ ω |- (λ_ === ∅) \/ successorOrdinal(λ_)) by Tautology.from(lastStep, step1) + val step2 = lastStep + + have(h1 |- ¬((λ_ === ∅) \/ successorOrdinal(λ_))) by Tautology.from( + limitOrdinal.definition of (α := λ_) + ) + + have((h1, λ_ ∈ ω) |- ()) by Tautology.from(lastStep, step2) + thenHave((h1, h2) |- λ_ ∈ ω ==> P(λ_)) by Tautology + thenHave((h1) ==> (h2 ==> Q(λ_))) by Tautology + thenHave(thesis) by RightForall + } + + have(∀(α, ordinal(α) ==> Q(α))) by Tautology.from( + transfiniteInductionCases of (P := λ(α, Q(α))), + qZeroFact, + qSuccFact, + qLimit + ) + + val st1 = thenHave(ordinal(α) ==> Q(α)) by InstantiateForall(α) + have(α ∈ ω ==> ordinal(α)) by Tautology.from(elementIsOrdinal) + have(α ∈ ω ==> Q(α)) by Tautology.from(lastStep, st1) + thenHave(α ∈ ω ==> P(α)) by Tautology + thenHave(forall(α, α ∈ ω ==> P(α))) by RightForall + thenHave(thesis) by Tautology + } + + /** + * Lemma --- The successor is injective: `n = m ⇔ S(n) = S(m)`. + */ + val successorInjectivity = Lemma((n === m) <=> (S(n) === S(m))) { + val forward = have(n === m |- S(n) === S(m)) by Congruence + val backward = have(S(n) === S(m) |- n === m) subproof { + assume(S(n) === S(m)) + val nInSuccessor = have(n ∈ S(m)) by Congruence.from(selfInSuccessor) + val mInSuccessor = have(m ∈ S(n)) by Congruence.from(selfInSuccessor of (n := m)) + have(thesis) by Tautology.from( + nInSuccessor, + mInSuccessor, + succMembership of (k := n, n := m), + succMembership of (k := m), + FoundationAxiom.membershipAsymmetric of (x := n, y := m) + ) + } + have(thesis) by Tautology.from(forward, backward) + } + + /** + * Lemma --- A successor is never empty: `S(n) ≠ ∅`. + */ + val zeroIsNotSucc = Lemma(!(S(n) === ∅)) { + have(thesis) by Tautology.from(selfInSuccessor, EmptySet.setWithElementNonEmpty of (x := n, y := S(n))) + } + + /** + * Lemma --- A set is a subset of its successor: `n ⊆ S(n)`. + */ + val subsetSuccessor = Lemma(n ⊆ S(n)) { + have(n ⊆ (n ∪ Singleton.singleton(n))) by Restate.from(Union.leftSubset of (x := n, y := Singleton.singleton(n))) + thenHave(thesis) by Substitute(S.definition of (α := n)) + } + + /** + * Lemma --- Zero is a natural number: `∅ ∈ ω`. + */ + val emptyInOmega = Lemma(∅ ∈ ω) { + have(∅ ∈ ω <=> integer(∅)) by InstantiateForall(∅)(omegaCharacterization) + have(thesis) by Tautology.from(lastStep, zeroIsInteger) + } + + /** + * Lemma --- `ω` is non-empty. + */ + val omegaNotEmpty = Lemma(!(ω === ∅))( + have(thesis) by Tautology.from( + emptyInOmega, + EmptySet.setWithElementNonEmpty of (x := ∅, y := ω) + ) + ) + + /** + * Lemma --- `ω` is closed under successor and predecessor: `n ∈ ω ⇔ S(n) ∈ ω`. + */ + val successorInOmega = Lemma(n ∈ ω <=> S(n) ∈ ω) { + val toS = have(n ∈ ω |- S(n) ∈ ω) by Restate.from(omegaSuccessor of (α := n)) + val fromS = have(S(n) ∈ ω |- n ∈ ω) by + Restate.from(omegaPredecessor of (α := n)) + have(thesis) by Tautology.from(toS, fromS) + } + + /** + * Lemma --- Induction over `ω`: if `P(∅)` holds and `P` is preserved by the + * successor on `ω`, then `P` holds on all of `ω`. + */ + val omegaSuccessorInduction = omegaInduction + + /** + * Lemma --- `ω` is downward closed (transitive): any element of an element of + * `ω` is itself in `ω`. + */ + val omegaDownwardClosed = Lemma(y ∈ ω |- x ∈ y ==> x ∈ ω) { + val yCharacterization = have(y ∈ ω <=> integer(y)) by InstantiateForall(y)(omegaCharacterization) + val xCharacterization = have(x ∈ ω <=> integer(x)) by InstantiateForall(x)(omegaCharacterization) + have(thesis) by Tautology.from(yCharacterization, xCharacterization, integerHereditary of (α := y, β := x)) + } + + /** + * Lemma --- `ω` is closed under binary union: if `a, b ∈ ω` then `a ∪ b ∈ ω`. + */ + val unionInOmega = Lemma((a ∈ ω /\ b ∈ ω) |- (a ∪ b) ∈ ω) { + assume(a ∈ ω, b ∈ ω) + val equalCase = have(a === b |- (a ∪ b) ∈ ω) by + Congruence.from(Union.idempotence of (x := b)) + + val leftCase = have(a ∈ b |- (a ∪ b) ∈ ω) subproof { + assume(a ∈ b) + have(TransitiveSet.transitiveSet(b)) by + Tautology.from(elementIsOrdinal of (α := b), ordinal.definition of (α := b)) + val included = have(a ⊆ b) by + Tautology.from(lastStep, TransitiveSet.elementIsSubset of (x := a, A := b)) + have((a ∪ b) ⊆ b) by Tautology.from( + included, + Subset.reflexivity of (x := b), + Union.leftUnionSubset of (x := a, y := b, z := b) + ) + have((a ∪ b) === b) by Tautology.from( + lastStep, + Union.rightSubset of (x := a, y := b), + Subset.antisymmetry of (x := a ∪ b, y := b) + ) + have(thesis) by Congruence.from(lastStep) + } + val rightCase = have(b ∈ a |- (a ∪ b) ∈ ω) by + Congruence.from(leftCase of (a := b, b := a), Union.commutativity of (x := a, y := b)) + + have(thesis) by Tautology.from(comparability of (m := a, n := b), equalCase, leftCase, rightCase) + } + + /** + * Lemma --- `ω` is inhabited: `∃n. n ∈ ω`. + */ + val existsInOmega = Lemma(exists(n, n ∈ ω)) { + have(thesis) by RightExists(emptyInOmega) + } + + /** + * Theorem --- Every element of `ω` is a transitive set. + */ + val elementsTransitive = Theorem((n ∈ ω) |- TransitiveSet.transitiveSet(n)) { + val ordN = have(n ∈ ω |- ordinal(n)) by Restate.from(elementIsOrdinal of (α := n)) + have(thesis) by Tautology.from(ordN, ordinal.definition of (α := n)) + } + + /** + * Theorem --- A subset of `S(n)` is either all of it or a subset of `n`. + */ + val subsetBelowSucc = Theorem((m ∈ ω, n ∈ ω, m ⊆ S(n)) |- (m === S(n)) \/ (m ⊆ n)) { + val mInN = assume(m ∈ ω) + val nInN = assume(n ∈ ω) + val mSubSn = assume(m ⊆ S(n)) + + val SnInN = have(S(n) ∈ ω) by + Tautology.from(nInN, successorInOmega of (n := n)) + + val cmp = have( + (m === S(n)) \/ (m ∈ S(n)) \/ (S(n) ∈ m) + ) by Tautology.from( + mInN, + SnInN, + comparability of (m := m, n := S(n)) + ) + + val caseEq = have( + m === S(n) |- (m === S(n)) \/ (m ⊆ n) + ) by Tautology + + val caseIn = have( + m ∈ S(n) |- (m === S(n)) \/ (m ⊆ n) + ) subproof { + val mInSn = assume(m ∈ S(n)) + val split = have((m ∈ n) \/ (m === n)) by Tautology.from( + mInSn, + succMembership.of(k := m, n := n) + ) + + val fromIn = have(m ∈ n |- m ⊆ n) subproof { + val mInNCase = assume(m ∈ n) + val nTrans = have(TransitiveSet.transitiveSet(n)) by + Tautology.from(nInN, elementsTransitive.of(n := n)) + have(m ⊆ n) by Tautology.from( + mInNCase, + nTrans, + TransitiveSet.elementIsSubset.of(A := n, x := m) + ) + } + + val fromEq = have(m === n |- m ⊆ n) by + Congruence.from(Subset.reflexivity of (x := n)) + + have(m ⊆ n) by Tautology.from(split, fromIn, fromEq) + thenHave(thesis) by Tautology + } + + val caseGt = have( + S(n) ∈ m |- (m === S(n)) \/ (m ⊆ n) + ) subproof { + val SnInM = assume(S(n) ∈ m) + val SnInSn = have(S(n) ∈ S(n)) by Tautology.from( + mSubSn, + SnInM, + Subset.membership of (x := m, y := S(n), z := S(n)) + ) + have(thesis) by Tautology.from( + SnInSn, + FoundationAxiom.selfNonInclusion of (x := S(n)) + ) + } + + have(thesis) by Tautology.from(cmp, caseEq, caseIn, caseGt) + } + } diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/TransfiniteRecursion.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/TransfiniteRecursion.scala index ff897c7db..fcd60fe3c 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/TransfiniteRecursion.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/TransfiniteRecursion.scala @@ -9,14 +9,13 @@ import InitialSegment._ import MembershipRelation._ /** - * Transfinite recursion is a process for creating a class-function by recursion - * over the ordinals, as the limit of a sequence of set functions. + * Constructs functions by recursion over an ordinal. */ object TransfiniteRecursion extends lisa.Main { private val α, β = variable[Ind] private val A, < = variable[Ind] - private val F = variable[Ind >>: Ind >>: Ind] + private val F, Func = variable[Ind >>: Ind >>: Ind] private val G = variable[Ind] extension (f: Expr[Ind]) { @@ -24,37 +23,71 @@ object TransfiniteRecursion extends lisa.Main { } /** - * Transfinite recursion --- Given any `F : V -> V`, there exists a unique - * `G : On -> V` such that for all ordinals `α`, `G(α) = F(G↾α)`. - * - * To state the theorem schema inside ZFC, we show that for any ordinal `α`, - * there exists a unique function `g_α` defined by recursion over `α`. - * We obtain the desired class-function `G` by setting `G(β) = g_α(β)` for any `α > β`. + * The function obtained by well-ordered recursion on ordinal membership. */ - val transfiniteRecursion = Theorem( - ordinal(α) |- ∃(G, ∀(β ∈ α, G(β) === F(β)(G ↾ β))) + val transfiniteRecursionFunction = DEF( + λ(Func, λ(α, WellOrderedRecursion.recursiveFunctionOn(Func)(α)(membershipRelation(α)))) + ) + + /** + * The constructed function has domain `α` and satisfies the transfinite recurrence. + */ + val transfiniteRecursionFunctionSpec = Theorem( + ordinal(α) |- + (functionOn(transfiniteRecursionFunction(Func)(α))(α) /\ ∀( + β ∈ α, + transfiniteRecursionFunction(Func)(α)(β) === + Func(β)(transfiniteRecursionFunction(Func)(α) ↾ β) + )) ) { assume(ordinal(α)) - - // Since `∈_α` is a well-order on `α`, we apply well-ordered recursion. - val wellOrderedRecursion = have(∃(G, ∀(β, β ∈ α ==> (G(β) === F(β)(G ↾ initialSegment(β)(α)(membershipRelation(α))))))) by Tautology.from( + val witness = WellOrderedRecursion.recursiveFunctionOn(Func)(α)(membershipRelation(α)) + val rec = transfiniteRecursionFunction(Func)(α) + val recDefinition = transfiniteRecursionFunction.definition.of(Func := Func, α := α) + val witnessSpec = have( + functionOn(witness)(α) /\ + ∀(β ∈ α, witness(β) === Func(β)(witness ↾ initialSegment(β)(α)(membershipRelation(α)))) + ) by Tautology.from( ordinal.definition, - WellOrderedRecursion.existence of (A := α, < := membershipRelation(α)) + WellOrderedRecursion.recursiveFunctionOnSpec.of(A := α, < := membershipRelation(α), Func := Func) ) - // It remains to replace `initialSegment(β, α, <)` with `β` under the binders. - have((G(β) === F(β)(G ↾ initialSegment(β)(α)(membershipRelation(α))), β ∈ α) |- (G(β) === F(β)(G ↾ β))) by Congruence.from(Ordinal.ordinalInitialSegment) - thenHave(β ∈ α ==> (G(β) === F(β)(G ↾ initialSegment(β)(α)(membershipRelation(α)))) |- β ∈ α ==> (G(β) === F(β)(G ↾ β))) by Tautology - thenHave(∀(β, β ∈ α ==> (G(β) === F(β)(G ↾ initialSegment(β)(α)(membershipRelation(α))))) |- β ∈ α ==> (G(β) === F(β)(G ↾ β))) by LeftForall - thenHave(∀(β, β ∈ α ==> (G(β) === F(β)(G ↾ initialSegment(β)(α)(membershipRelation(α))))) |- ∀(β, β ∈ α ==> (G(β) === F(β)(G ↾ β)))) by RightForall - thenHave(∀(β, β ∈ α ==> (G(β) === F(β)(G ↾ initialSegment(β)(α)(membershipRelation(α))))) |- ∃(G, ∀(β, β ∈ α ==> (G(β) === F(β)(G ↾ β))))) by RightExists - thenHave(∃(G, ∀(β, β ∈ α ==> (G(β) === F(β)(G ↾ initialSegment(β)(α)(membershipRelation(α)))))) |- ∃(G, ∀(β, β ∈ α ==> (G(β) === F(β)(G ↾ β))))) by LeftExists + val witnessFunOn = have(functionOn(witness)(α)) by Weakening(witnessSpec) + val recFunOn = have(functionOn(rec)(α)) by Congruence.from(witnessFunOn, recDefinition) + val witnessEquations = have( + ∀(β ∈ α, witness(β) === Func(β)(witness ↾ initialSegment(β)(α)(membershipRelation(α)))) + ) by Weakening(witnessSpec) + val equation = have(β ∈ α |- rec(β) === Func(β)(rec ↾ β)) subproof { + assume(β ∈ α) + val witnessAtBeta = have( + witness(β) === Func(β)(witness ↾ initialSegment(β)(α)(membershipRelation(α))) + ) by InstantiateForall(β)(witnessEquations) + have(thesis) by Congruence.from(witnessAtBeta, Ordinal.ordinalInitialSegment, recDefinition) + } + have(β ∈ α ==> (rec(β) === Func(β)(rec ↾ β))) by Restate.from(equation) + val recEquations = thenHave(∀(β ∈ α, rec(β) === Func(β)(rec ↾ β))) by RightForall + have(thesis) by RightAnd(recFunOn, recEquations) + } - have(thesis) by Cut(wellOrderedRecursion, lastStep) + /** + * A function on `α` satisfying the transfinite recurrence exists. + */ + val transfiniteRecursionWithFunctionOn = Theorem( + ordinal(α) |- ∃(G, functionOn(G)(α) /\ ∀(β ∈ α, G(β) === Func(β)(G ↾ β))) + ) { + have(transfiniteRecursionFunctionSpec.statement) by Restate.from(transfiniteRecursionFunctionSpec) + thenHave(thesis) by RightExists } /** - * Definition --- Returns the function obtained by transfinite recursion of `F` until `α`. + * Transfinite recursion supplies a function satisfying the recurrence at every point of `α`. */ - val transfiniteRecursionFunction = DEF(λ(F, λ(α, ε(G, ∀(β, β ∈ α ==> (G(β) === F(β)(G ↾ β))))))) + val transfiniteRecursion = Theorem( + ordinal(α) |- ∃(G, ∀(β ∈ α, G(β) === F(β)(G ↾ β))) + ) { + val rec = transfiniteRecursionFunction(F)(α) + have(ordinal(α) |- ∀(β ∈ α, rec(β) === F(β)(rec ↾ β))) by + Weakening(transfiniteRecursionFunctionSpec.of(Func := F)) + thenHave(thesis) by RightExists + } } diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Frontend.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Frontend.scala deleted file mode 100644 index a3adb1367..000000000 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Frontend.scala +++ /dev/null @@ -1,502 +0,0 @@ -package lisa.maths.SetTheory.Types.ADT - -/** - * This object provides a DSL for defining algebraic data types (ADTs) and functions over ADT in Lisa. - * For usage examples, please refer to the documentation of the package or the reference manual. - */ -object ADTSyntax { - /* - - import ADTDefinitions.* - import lisa.maths.settheory.SetTheory.{*, given} - - /** Builder for defining a constructor specification. - * - * @param param the parameters of the constructor - */ - case class ConstructorBuilder(private val param: Seq[ConstructorArgument]) { - - /** The number of arguments the constructor takes - */ - def size: Int = param.length - - /** Merges the parameters of two constructors. - * - * @param b the other constructor - */ - infix def ++(b: ConstructorBuilder): ConstructorBuilder = ConstructorBuilder(param ++ b.param.toSeq) - - /** Converts this constructor into an ADT with a single constructor. - */ - def toADTBuilder = ADTBuilder(Seq(this)) - - /** Combines two constructors into an ADT. - * - * @param b the other constructor - */ - infix def |(b: ConstructorBuilder): ADTBuilder = this | b.toADTBuilder - - /** Adds this constructor to an ADT. - * - * @param b the ADT to which the constructor is added - */ - infix def |(b: ADTBuilder): ADTBuilder = toADTBuilder | b - - /** Outputs the [[UntypedConstructor]] associated with this builder. - * - * @param name the name of the constructor - */ - def build(variables1: Seq[Variable[Ind]], variables2: Seq[Variable[Ind]]): SyntacticConstructor = SyntacticConstructor(param, variables1, variables2) - } - - /** Companion object for the [[ConstructorBuilder]] class. - */ - object ConstructorBuilder { - - /** Creates an empty [[ConstructorBuilder]]. - */ - def empty: ConstructorBuilder = ConstructorBuilder(Seq.empty) - } - - trait ConstructorConverter[T] { - - /** Converts a value into a [[ConstructorBuilder]]. - */ - def apply(t: T): ConstructorBuilder - } - - /** Converts a value into a [[ConstructorBuilder]]. - * - * @param any the value to convert - * @param c the converter that is used for the conversion - */ - private def any_to_const[T](any: T)(using c: ConstructorConverter[T]): ConstructorBuilder = c(any) - - given unit_to_const: ConstructorConverter[Unit] with { - - /** Converts a unit value into a constructor taking no arguments. - */ - override def apply(u: Unit): ConstructorBuilder = ConstructorBuilder.empty - } - - given empty_to_const: ConstructorConverter[EmptyTuple] with { - - /** Converts an empty tuple into a constructor taking no arguments. - */ - override def apply(t: EmptyTuple): ConstructorBuilder = ConstructorBuilder.empty - } - - given term_to_const[T <: Expr[Ind]]: ConstructorConverter[T] with { - - /** Converts a term into a constructor taking one non inductive argument. - */ - override def apply(t: T): ConstructorBuilder = ConstructorBuilder(Seq(GroundType(t))) - } - - given adt_to_const[N <: Arity]: ConstructorConverter[ADT[N]] with { - - /** Converts an ADT into a constructor taking one inductive argument. - */ - override def apply(a: ADT[N]): ConstructorBuilder = ConstructorBuilder(Seq(Self)) - } - - given adt_tuple_to_const[N <: Arity, T <: Tuple](using ConstructorConverter[T]): ConstructorConverter[ADT[N] *: T] with { - - /** Converts a tuple prepended with a type into a constructor taking an argument and whose other arguments are deduced from - * applying recursively the conversion to the tuple. - */ - override def apply(t: ADT[N] *: T): ConstructorBuilder = - any_to_const(t.head) ++ any_to_const(t.tail) - } - - given term_tuple_to_const[H <: Expr[Ind], T <: Tuple](using ConstructorConverter[T]): ConstructorConverter[H *: T] with { - - /** Converts a tuple prepended with a type into a constructor taking an argument and whose other arguments are deduced from - * applying recursively the conversion to the tuple. - */ - override def apply(t: H *: T): ConstructorBuilder = - any_to_const(t.head) ++ any_to_const(t.tail) - } - - extension [T1](left: T1)(using c1: ConstructorConverter[T1]) - /** Converts two values into constructors and combines them into an ADT. - * - * @param right the other value to convert - * @param c2 the implicit converter for the second value - */ - infix def |[T2](right: T2)(using c2: ConstructorConverter[T2]): ADTBuilder = any_to_const(left) | any_to_const(right) - - /** Builder for defining ADT specifications. - * - * @param constructors the builders for each constructor of the ADT. - */ - case class ADTBuilder(private val constructors: Seq[ConstructorBuilder]) { - - /** The number of constructors in the ADT. - */ - def size: Int = constructors.length - - /** Combines this ADT with another one. - * - * @param b the other ADT - */ - infix def |(b: ADTBuilder): ADTBuilder = ADTBuilder(constructors ++ b.constructors) - - /** Adds a constructor to this ADT. - * - * @param b the constructor to add - */ - infix def |(b: ConstructorBuilder): ADTBuilder = this | b.toADTBuilder - - /** Converts a value into a constructor and adds it to this ADT. - * - * @param t the value to convert - * @param c the implicit converter - */ - infix def |[T](t: T)(using c: ConstructorConverter[T]): ADTBuilder = this | any_to_const(t) - - /** Outputs the corresponding ADT and its constructors. - * - * @tparam N the number of type variables appearing in the specification of the ADT - * @param typeVariables the type variables of the ADT - * @param names the names of the constructors and of the ADT - */ - def build[N <: Arity](typeVariables: Variable[Ind] ** N, names: Seq[String]): (ADT[N], constructors[N]) = - - val trimmedNames = (if size == 0 then names else names.tail).take(size + 1) - require( - trimmedNames.length == constructors.length + 1, - s"The number of new identifiers for constructors must match the given specification.\nNew identifiers: ${names.length - 1}, number of constructors: ${constructors.length}." - ) - - val typeVarsSet = typeVariables.toSeq.toSet - val syntacticCons = constructors.map(c => c.build(nFreshIds(c.size, typeVarsSet, base = "x"), nFreshIds(c.size, typeVarsSet, base = "y"))) - val syntacticADT = SyntacticADT[N](trimmedNames.head, syntacticCons, typeVariables) - val semanticCons = trimmedNames.tail.zip(syntacticCons).map(SemanticConstructor(_, _, syntacticADT)) - val semanticADT = SemanticADT[N](syntacticADT, semanticCons) - val cons = semanticCons.map(Constructor(_)) - (ADT[N](semanticADT, cons), new constructors[N](cons*)) - - } - - /** Companion object for the [[ADTBuilder]] class. - */ - object ADTBuilder { - - /** Creates an empty [[ADTBuilder]]. - */ - def empty: ADTBuilder = ADTBuilder(Seq.empty) - - /** Creates an empty [[ADTBuilder]]. - */ - def | = empty - } - - /** Builder for defining polymorphic ADT specifications. - * - * @tparam N the number of type variables of the ADT - * @param typeVariable the type variables of the ADT - * @param specification the builder for ADT - */ - case class PolymorphicADTBuilder[N <: Arity](typeVariables: Variable[Ind] ** N, specification: ADTBuilder) { - - /** Outputs the corresponding ADT and its constructors. - * - * @param names the names of the constructors and of the ADT - */ - def build(names: Seq[String]) = specification.build(typeVariables, names) - - /** Adds a constructor to the ADT specification - * - * @param b the builder of the constructor - */ - def |(b: ConstructorBuilder): PolymorphicADTBuilder[N] = PolymorphicADTBuilder(typeVariables, specification | b) - - /** Adds a constructor to the ADT specification - * - * @param t the value to be converted into a constructor - */ - def |[T](t: T)(using ConstructorConverter[T]): PolymorphicADTBuilder[N] = |(any_to_const(t)) - } - - // Syntactic sugar for polymorphic ADT Builders - - extension (u: Unit) - def -->(builder: ADTBuilder): PolymorphicADTBuilder[0] = PolymorphicADTBuilder[0](**(), builder) - def -->(builder: ConstructorBuilder): PolymorphicADTBuilder[0] = -->(builder.toADTBuilder) - def -->[T](t: T)(using ConstructorConverter[T]): PolymorphicADTBuilder[0] = -->(any_to_const(t)) - - extension (v: Variable[Ind]) - def -->(builder: ADTBuilder): PolymorphicADTBuilder[1] = PolymorphicADTBuilder[1](**(v), builder) - def -->(builder: ConstructorBuilder): PolymorphicADTBuilder[1] = -->(builder.toADTBuilder) - def -->[T](t: T)(using ConstructorConverter[T]): PolymorphicADTBuilder[1] = -->(any_to_const(t)) - - extension (v: (Variable[Ind], Variable[Ind])) - def -->(builder: ADTBuilder): PolymorphicADTBuilder[2] = PolymorphicADTBuilder[2](**(v._1, v._2), builder) - def -->(builder: ConstructorBuilder): PolymorphicADTBuilder[2] = -->(builder.toADTBuilder) - def -->[T](t: T)(using ConstructorConverter[T]): PolymorphicADTBuilder[2] = -->(any_to_const(t)) - - extension (v: (Variable[Ind], Variable[Ind], Variable[Ind])) - def -->(builder: ADTBuilder): PolymorphicADTBuilder[3] = PolymorphicADTBuilder[3](**(v._1, v._2, v._3), builder) - def -->(builder: ConstructorBuilder): PolymorphicADTBuilder[3] = -->(builder.toADTBuilder) - def -->[T](t: T)(using ConstructorConverter[T]): PolymorphicADTBuilder[3] = -->(any_to_const(t)) - - extension (v: (Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind])) - def -->(builder: ADTBuilder): PolymorphicADTBuilder[4] = PolymorphicADTBuilder[4](**(v._1, v._2, v._3, v._4), builder) - def -->(builder: ConstructorBuilder): PolymorphicADTBuilder[4] = -->(builder.toADTBuilder) - def -->[T](t: T)(using ConstructorConverter[T]): PolymorphicADTBuilder[4] = -->(any_to_const(t)) - - extension (v: (Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind])) - def -->(builder: ADTBuilder): PolymorphicADTBuilder[5] = PolymorphicADTBuilder[5](**(v._1, v._2, v._3, v._4, v._5), builder) - def -->(builder: ConstructorBuilder): PolymorphicADTBuilder[5] = -->(builder.toADTBuilder) - def -->[T](t: T)(using ConstructorConverter[T]): PolymorphicADTBuilder[5] = -->(any_to_const(t)) - - /** Lists all constructors of this ADT. - */ - case class constructors[N <: Arity](cons: Constructor[N]*) - - /** Companion object for the [[constructors]] class. - */ - object constructors { - def unapplySeq[N <: Arity](adt: ADT[N]): Seq[Constructor[N]] = adt.constructors - } - - /** Contains useful macros for ADT UI - */ - object Macro { - import scala.quoted._ - - /** Extract all the scala identifiers defined in the same line or after an expression. - * - * @param e the expression around which the names are extracted - */ - inline def extractNames[T](e: T): Seq[String] = ${ extractNames('{ e }) } - - /** Macro implementing [[this.extractNames]]. - * - * @param e the quoted expression around which the names are extracted - */ - private def extractNames[T](using Quotes)(e: Expr[T]): Expr[Seq[String]] = - - import quotes.reflect._ - - val subscope = Symbol.spliceOwner.owner.owner.owner - val scope = subscope.owner - val tree = scope.tree - - case class traverser(s: Symbol) extends TreeTraverser { - var reachedADT: Boolean = false - var constructorNames: Seq[String] = Seq.empty[String] - - override def traverseTree(tree: Tree)(owner: Symbol): Unit = tree match - case v: ValDef => - if !reachedADT then - if v.symbol == s then - constructorNames = constructorNames :+ v.symbol.name - reachedADT = true - else constructorNames = constructorNames :+ v.symbol.name - - super.traverseTree(tree)(owner) - case _ => super.traverseTree(tree)(owner) - } - - val trav = traverser(subscope) - trav.traverseTree(tree)(scope) - Expr(trav.constructorNames) - } - - /** Syntax to define Algebraic Data Types - */ - object define { - - /** Extracts the constructors from an ADT. - * - * @param adt the ADT - * @return a tuple containing the ADT and its constructors - */ - private def extractConstructors[N <: Arity](adt: ADT[N]): (ADT[N], constructors[N]) = (adt, constructors(adt.constructors*)) - - /** Outputs a polymorphic ADT and constructors from a user specification - * Needs to be inline in order to fetch the name of the ADT and the constructor. - * - * @param builder the builder user for specifying the ADT - */ - inline def unapply[N <: Arity](builder: PolymorphicADTBuilder[N]): (ADT[N], constructors[N]) = builder.build(Macro.extractNames(builder)) - - /** Outputs a (non polymorphic) ADT and constructors from a user specification. - * Needs to be inline in order to fetch the name of the ADT and the constructor. - * - * @param builder the builder user for specifying the ADT - */ - inline def unapply(builder: ADTBuilder): (ADT[0], constructors[0]) = unapply[0](() --> builder) - - /** Returns an ADT containing only one constructor out of a user specification. - * Needs to be inline in order to fetch the name of the ADT and the constructor. - * - * @param builder the builder of the unique constructor of the ADT - */ - private inline def unapply(builder: ConstructorBuilder): (ADT[0], constructors[0]) = unapply(builder.toADTBuilder) - - /** Returns an ADT isomorphic to a given type. It has only one constructor taking as only argument an element of - * the provided type. - * Needs to be inline in order to fetch the name of the ADT and the constructor. - * - * @param t type given by the user - */ - inline def unapply(t: Expr[Ind]): (ADT[0], constructors[0]) = unapply(term_to_const(t)) - - /** Returns the unit type. This is an ADT containing only one value and hence having only one - * constructor (non-inductive and taking no arguments). - * Needs to be inline in order to fetch the name of the ADT and the constructor. - * - * @param u user specification indicating that they want to generate the unit type - */ - inline def unapply(u: Unit): (ADT[0], constructors[0]) = unapply(unit_to_const(u)) - - /** Returns a product type (also known as tuple). This is an ADT containing only one constructor. - * Generally its arguments are non inductive as the opposite would lead to the empty type. - * Needs to be inline in order to fetch the name of the ADT and the constructor. - * - * @param t user specification of the tuple - */ - inline def unapply[N <: Arity, T <: Tuple](t: (ADT[N] | Expr[Ind]) *: T)(using ConstructorConverter[T]): (ADT[0], constructors[0]) = - t.head match - case a: ADT[N] => unapply(adt_tuple_to_const(a *: t.tail)) - case term: Expr[Ind] => unapply(any_to_const(term *: t.tail)) - } - - /** Converts an ADT with no type variables into a term. - */ - given adt_to_term: Conversion[ADT[0], Expr[Ind]] = _.applyUnsafe(**()) - - /** Converts a function over an ADT with no type variables into a term (i.e a set function). - */ - given fun_to_term: Conversion[ADTFunction[0], Expr[Ind]] = _.applyUnsafe(**()) - - /** Converts a constructor with no type variables into a term (i.e a set function). - */ - given constructor_to_term: Conversion[Constructor[0], Expr[Ind]] = _.applyUnsafe(**()) - - /** Mutable data structure that registers the patterns that have been filled inside a pattern matching syntax. - * - * @tparam N the type variables of the ADT - * @param comp the complementary information stored in the builder - */ - class CaseBuilder[N <: Arity, T, R](val comp: R) { - - /** The underlying mutable map between patterns and the body of the corresponding cases. For each - * patterns stores the variables that have been used to represent its arguments. - */ - private val underlying = scala.collection.mutable.Map[Constructor[N], (Seq[Variable[Ind]], T)]() - - /** Adds a case to the pattern matching - * - * @param cons the pattern / constructor - * @param value the value next to the variables that are used for the pattern's arguments - */ - def +=(cons: Constructor[N], value: (Seq[Variable[Ind]], T)) = underlying += (cons -> value) - - /** Checks if the cases of a pattern matching are valid. Specifically, it checks that: - * - All constructors are covered - * - There are no extra cases - * - The number of variables provided by the user matches the arity of the constructor - * - * @param adt the ADT over which the pattern matching is performed - * @return an error message if the pattern matching is invalid, None otherwise - */ - def isValid(adt: ADT[N]): Option[String] = - val constructors = adt.constructors.toSet - val casesConstructors = underlying.keySet.toSet - - val constructorsMinusCases = constructors -- casesConstructors - val casesMinusConstructors = casesConstructors -- constructors - - // STEP 1: Check that all constructors are covered - if !constructorsMinusCases.isEmpty then Some(s"Case for ${constructorsMinusCases.head.name} is missing.") - // STEP 2: Check that there are no extra cases - else if !casesMinusConstructors.isEmpty then Some(s"${casesMinusConstructors.head.name} is not a constructor of ${adt.name}.") - else - underlying.keys.foldLeft[Option[String]](None)((acc, c) => - val vars = underlying(c)._1.toSet - // STEP 3: Check that for each case the number of variables provided by the user matches the arity of the constructor - acc.orElse(Some(s"Case ${c.name}: ${vars.size} variables were provided whereas the arity of ${c.name} is ${c.arity}.").filter(_ => vars.size != c.underlying.arity)) - ) - - /** Outputs an immutable map out of the underlying mutable one - */ - def build: Map[Constructor[N], (Seq[Variable[Ind]], T)] = underlying.toMap - } - - /** Case of a a pattern matching syntax - * - * @param cons the pattern / constructor - * @param vars variables that are used to represent the arguments of the constructor - */ - case class Case[N <: Arity](cons: Constructor[N], vars: Variable[Ind]*) { - - /** Used in the context of an induction proof. Adds the subproof corresponding to this case into a builder. - * - * @see [[Induction]] - * - * @param proof the outer scope of the induction proof - * @param line the line at which this case is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param file the file in which this case is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param builder the builder of the induction proof - * @param subproof the proof of the case (possibly using the induction hypothesis) - */ - def subproof(using proof: Proof, line: sourcecode.Line, file: sourcecode.File, builder: CaseBuilder[N, proof.ProofStep, (Sequent, Seq[Expr[Ind]], Variable[Ind])])( - subproof: proof.InnerProof ?=> Unit - ): Unit = - val (bot, args, adtVar) = builder.comp - val prop = bot.right.head - val consTerm = appSeq(cons.underlying.term(args))(vars) - val subst = adtVar -> consTerm - - val assumptions = - (wellTypedSet(cons.underlying.semanticSignature(vars).map(p => (p._1, p._2.substitute(cons.underlying.typeVariablesSeq.zip(args).map(SubstPair(_, _))*)))) - ++ - cons.underlying.syntacticSignature(vars).filter(_._2 == Self).map((v, _) => prop.substitute(adtVar -> v))) - - // val botWithAssumptions = bot.substitute(subst) ++ ((assumptions ++ proof.getAssumptions) |- ()) - val botWithAssumptions = bot.substitute(subst) ++ (assumptions |- ()) - - val iProof: proof.InnerProof = new proof.InnerProof(Some(botWithAssumptions)) - subproof(using iProof) - val proofStep = (new SUBPROOF(using proof)(None)(iProof)).judgement.validate(line, file).asInstanceOf[proof.ProofStep] - - def subproofWithExtraStep: proof.ProofTacticJudgement = TacticSubproof { ip ?=> - val fullSeq = Tautology(using lisa.SetTheoryLibrary, ip)(proofStep)(botWithAssumptions) - if fullSeq.isValid then fullSeq.validate(line, file) - else return proof.InvalidProofTactic(s"Proof of case ${cons.name} is invalid.\nExpected: ${botWithAssumptions}.") - } - - builder += (cons, (vars, subproofWithExtraStep.validate(line, file))) - - /** Used in the context of a function definition. Adds the body of the case to a builder. - * - * @param body the body of this case - * @param builder the builder for the function definition - */ - def apply(body: Expr[Ind])(using builder: CaseBuilder[N, Expr[Ind], Unit]) = builder += (cons, (vars, body)) - } - - /** Defines a function over an ADT - * - * @param adt the domain of this function - * @param returnType the return type of this function - * @param name the name of this functions - * @param cases the definition of the function for each constructor - */ - def fun[N <: Arity](adt: ADT[N], returnType: Expr[Ind])(using name: sourcecode.Name)(cases: CaseBuilder[N, Expr[Ind], Unit] ?=> Unit): ADTFunction[N] = { - val builder = CaseBuilder[N, Expr[Ind], Unit](()) - cases(using builder) - builder.isValid(adt) match - case None => - ADTFunction(SemanticFunction[N](name.value, adt.underlying, builder.build.map((k, v) => (k.underlying, v)), returnType), adt) - case Some(msg) => throw IllegalArgumentException(msg) - } - - */ -} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Functions.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Functions.scala deleted file mode 100644 index 4771369bb..000000000 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Functions.scala +++ /dev/null @@ -1,136 +0,0 @@ -/** - * Defines set theoretic functions over Algebraic Data Types - */ - -package lisa.maths.SetTheory.Types.ADT - -/* -import lisa.maths.SetTheory.SetTheory.{_, given} -import lisa.maths.SetTheory.Functions.|=> -import lisa.maths.SetTheory.Types.TypeSystem.:: -import lisa.maths.SetTheory.Types.TypeSystem._ - -import ADTDefinitions.* -import Helpers.* -import Helpers.{/\, ===, \/} - -/** - * Set theoretic interpretation of a function over an ADT. - * - * @tparam N the number of type variables of the domain of this function - * @param name the name of this function - * @param adt the domain of this function - * @param cases the body of this function for each constructor - * @param returnType the codomain of this function - * @param line the line at which this function is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param file the file in which this function is defined. Usually fetched automatically by the compiler. - * Used for error reporting - */ -class SemanticFunction[N <: Arity](name: String, adt: SemanticADT[N], cases: Map[SemanticConstructor[N], (Seq[Variable], Expr[Ind])], returnType: Expr[Ind])(using line: sourcecode.Line, file: sourcecode.File) { - - /** - * Map binding each constructor to a theorem stating that the case is well typed. - */ - private val checkReturnType: Map[SemanticConstructor[N], THM] = - (for c <- cases.keys yield - val (vars, body) = cases(c) - c -> Lemma(wellTyped(c.semanticSignature(vars)) |- body :: returnType) { - have(thesis) by TypeChecker.prove - } - ).toMap - - /** - * Type variables appearing in this function's domain. - */ - val typeVariables: Variable ** N = adt.typeVariables - - /** - * Sequence of type variables appearing in this function's domain. - */ - val typeVariablesSeq: Seq[Variable] = adt.typeVariablesSeq - - /** - * Number of type variables appearing in this function. - */ - val typeArity: N = adt.typeArity - - /** - * Full name of this function. That is the name of the function prefixed by the name of the ADT. - */ - val fullName = s"$name" - // val fullName = s"${adt.name}/$name" - - val typ = adt.term |=> returnType - - /** - * Definition of this function. - * - * Formally it is the only function whose domain is the ADT and such that for each constructor c f * (c * x1 * ... * xn) = case(c, x1, ..., xn) - */ - private val untypedDefinition = (f :: typ) /\ simplify(/\(cases.map((c, caseDef) => - val (vars, body) = caseDef - forallSeq(vars, wellTypedFormula(c.semanticSignature(vars)) ==> (f * c.appliedTerm(vars) === body)) - ))) - - /** - * Lemma --- Uniqueness of this function. - */ - private val uniqueness = Axiom(existsOne(f, untypedDefinition)) - - /** - * Set theoretic definition of the constructor. - */ - private val classFunction = FunctionDefinition(fullName, line.value, file.value)(typeVariablesSeq, f, untypedDefinition, uniqueness).label - - /** - * Identifier of this function. - */ - val id: Identifier = classFunction.id - - /** - * Function where type variables are instantiated with schematic symbols. - */ - val term = classFunction.applySeq(typeVariablesSeq) - - /** - * Lemma --- The body of this function correpsonds to the cases provided by the user. - * - * `for each constructor c, ∀x1, ..., xn. f * (c * x1 * ... * xn) = case(c, x1, ..., xn)` - */ - val shortDefinition = cases.map((c, caseDef) => - val (vars, body) = caseDef - c -> Lemma(simplify(wellTypedFormula(c.semanticSignature(vars))) ==> (term * c.appliedTerm(vars) === body)) { - have(forall(f, (term === f) <=> untypedDefinition)) by Exact(classFunction.definition) - thenHave((term === term) <=> (term :: typ) /\ (/\(cases.map((c, caseDef) => { - val (vars, body) = caseDef - forallSeq(vars, wellTypedFormula(c.semanticSignature(vars)) ==> (term * c.appliedTerm(vars) === body)) - })))) by InstantiateForall(term) - thenHave(forallSeq(vars, wellTypedFormula(c.semanticSignature(vars)) ==> (term * c.appliedTerm(vars) === body))) by Weakening - vars.foldLeft(lastStep)((l, _) => - lastStep.statement.right.head match - case Forall(v, phi) => thenHave(phi) by InstantiateForall(v) - case _ => throw UnreachableException - ) - } - ) - - /** - * Lemma --- Introduction rule - * - * `f : ADT -> T` - * - * where `T` is the return type of this function - */ - val intro = Lemma(forallSeq(typeVariablesSeq, term :: typ)) { - have(forall(f, (term === f) <=> untypedDefinition)) by Exact(classFunction.definition) - thenHave((term === term) <=> (term :: typ) /\ (/\(cases.map((c, caseDef) => { - val (vars, body) = caseDef - forallSeq(vars, /\(wellTyped(c.semanticSignature(vars))) ==> (term * c.appliedTerm(vars) === body)) - })))) by InstantiateForall(term) - thenHave(term :: typ) by Weakening - thenHave(thesis) by QuantifiersIntro(typeVariablesSeq) - } -} - - */ diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Helpers.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Helpers.scala deleted file mode 100644 index 15101290e..000000000 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Helpers.scala +++ /dev/null @@ -1,1005 +0,0 @@ -package lisa.maths.SetTheory.Types.ADT - -/* - /** - * Tactic that proves every goal of the form: - * - * ` ... |- ..., ∀x1, ..., xn. P(x), ...` - * - * ` ..., ∀x1, ..., xn . P(x), ... |- ...` - * - * ` ... |- ..., ∃x1, ..., xn. P(x), ...` - * - * ` ..., ∃x1, ..., xn . P(x), ... |- ...` - * - * given a proof of the sequents without quantification. - */ -object QuantifiersIntro extends lisa.utils.prooflib.ProofTacticLib.ProofTactic { - - import lisa.utils.prooflib.SimpleDeducedSteps.Restate - import lisa.utils.prooflib.BasicStepTactic.* - import lisa.utils.fol.FOL.* - - /** - * Executes the tactic on a specific goal. - * - * @param lib the library that is currently being used - * @param proof the ongoing proof in which the tactic is called - * @param vars the variables that needs to be quantified - * @param fact the proof of the sequent without quantification - * @param bot the statement to prove - */ - def apply(using lib: lisa.utils.prooflib.Library, proof: lib.Proof)(vars: Seq[Variable])(fact: proof.Fact)(bot: Sequent): proof.ProofTacticJudgement = - TacticSubproof { sp ?=> - if vars.isEmpty then - lib.have(bot) by Restate.from(fact) - else - val diff: Sequent = bot -- fact.statement - - diff match - case Sequent(s, _) if s.size == 1 => - val diffRest = bot.left -- s - val f = s.head - val fWithoutQuant = (fact.statement.left -- diffRest).head - f match - case ∀(_, _) => - vars.foldRight[(sp.Fact, Expr[Prop])](fact, fWithoutQuant)( (v, acc) => - val (accFact, accFormula) = acc - val newFormula = ∀(v, accFormula) - (lib.have(diffRest + newFormula |- bot.right) by LeftForall(accFact), newFormula) - ) - case ∃(_, _) => - vars.foldRight[(sp.Fact, Expr[Prop])](fact, fWithoutQuant)( (v, acc) => - val (accFact, accFormula) = acc - val newFormula = ∃(v, accFormula) - (lib.have(diffRest + newFormula |- bot.right) by LeftExists(accFact), newFormula) - ) - case _ => return proof.InvalidProofTactic(s"The formula that changed is not quantified: $f.") - case Sequent(_, s) if s.size == 1 => - val diffRest = bot.right -- s - val f = s.head - val fWithoutQuant = (fact.statement.right -- diffRest).head - f match - case ∀(_, _) => - vars.foldRight[(sp.Fact, Expr[Prop])](fact, fWithoutQuant)( (v, acc) => - val (accFact, accFormula) = acc - val newFormula = forall(v, accFormula) - (lib.have(bot.left |- diffRest + newFormula) by RightForall(accFact), newFormula) - ) - case ∃(_, _) => - vars.foldRight[(sp.Fact, Expr[Prop])](fact, fWithoutQuant)( (v, acc) => - val (accFact, accFormula) = acc - val newFormula = exists(v, accFormula) - (lib.have(bot.left |- diffRest + newFormula) by RightExists(accFact), newFormula) - ) - case _ => return proof.InvalidProofTactic(s"The formula that changed is not quantified: $f.") - case Sequent(s1, s2) if s1.isEmpty && s2.isEmpty => lib.have(bot) by Restate.from(fact) - case _ => return proof.InvalidProofTactic("Two or more formulas in the sequent have changed.") - - - } -} - -/** - * General purpose helpers. - */ -private [adt] object Helpers { - - import lisa.utils.fol.FOL.{*, given} - - /** - * Benchmarks a block of code. - * - * @param name the name of the benchmark - * @param f the block of code to benchmark - * @return the result of the block of code and prints how long it took to execute - */ - def benchmark[T](name: String)(f: => T): T = { - val before = System.nanoTime - - val res = f - - val totalTime = (System.nanoTime - before) / 1000000 - - println(s"$name time: $totalTime ms") - - res - } - - /** - * Exception thrown when code that should not be accessed is reached. - */ - object UnreachableException extends Exception("This code should not be accessed. If you see this message, please report it to the library maintainers.") - - // ********************* - // * FIRST ORDER LOGIC * - // ********************* - - val a = variable[Ind] - val b = variable[Ind] - val c = variable[Ind] - val d = variable[Ind] - - val f = variable[Ind] - val g = variable[Ind] - val h = variable[Ind] - - val n = variable[Ind] - val m = variable[Ind] - - val p = variable[Prop] - val p1 = variable[Prop] - val p2 = variable[Prop] - val p3 = variable[Prop] - val p4 = variable[Prop] - - val q1 = variable[Prop] - val q2 = variable[Prop] - - val r = variable[Ind] - val s = variable[Ind] - val t = variable[Ind] - - val x = variable[Ind] - val y = variable[Ind] - val z = variable[Ind] - - val Q = variable[Ind >>: Prop] - val P, P2 = variable[Ind >>: Ind >>: Prop] - val schemPred = variable[Ind >>: Prop] - - /** - * Formula representing whether two sequences of terms are pairwise equal. - * - * @param s2 the sequence to compare with - */ - extension (s1: Seq[Expr[Ind]]) def ===(s2: Seq[Expr[Ind]]): Expr[Prop] = /\(s1.zip(s2).map(_ === _)) - - /** - * Disjunction of a sequence of formulas. - * - * @param s the formulas to which the disjunction is applied - */ - def \/(s: Iterable[Expr[Prop]]): Expr[Prop] = - if s.isEmpty then False - else s.fold(False)(_ \/ _) - - /** - * Conjunction of a sequence of formulas. - * - * @param s the formulas to which the conjunction is applied - */ - def /\(s: Iterable[Expr[Prop]]): Expr[Prop] = - if s.isEmpty then True - else s.fold(True)(_ /\ _) - - /** - * Repeats existential quantification over a sequence of variables. - * - * @param vars the variables to quantify over - * @param f the formula to which the quantifiers are applied - * @return the quantified formula - */ - def existsSeq(vars: Seq[Variable[Ind]], f: Expr[Prop]): Expr[Prop] = - vars.foldRight(f)(∃(_, _)) - - /** - * Repeats universal quantification over a sequence of variables. - * - * @param vars the variables to quantify over - * @param f the formula to which the quantifiers are applied - * @return the quantified formula - */ - def forallSeq(vars: Seq[Variable[Ind]], f: Expr[Prop]): Expr[Prop] = - vars.foldRight(f)(∀(_, _)) - - /** - * Simplifies a formula by removing True and False constants. - * - * @param f the formula to simplify - */ - def simplify(f: Expr[Prop]): Expr[Prop] = - f match - case ⊥ \/ φ => simplify(φ) - case φ \/ ⊥ => simplify(φ) - case φ \/ ψ => simplify(φ) \/ simplify(ψ) - case ⊤ /\ φ => simplify(φ) - case φ /\ ⊤ => simplify(φ) - case φ /\ ψ => simplify(φ) /\ simplify(ψ) - case ⊤ ==> φ => simplify(φ) - case φ ==> ψ => simplify(φ) ==> simplify(ψ) - case _ => f -} - -/** - * Definitions and helper functions for ADT. - */ -private[adt] object ADTDefinitions { - - import lisa.maths.SetTheory.Base.Predef.* - import lisa.maths.SetTheory.Function.* - import lisa.maths.SetTheory.Ordinal.* - import lisa.maths.settheory.types.TypeSystem.* - import Helpers.{/\} - - import Functions.* - import Restriction.* - - /** - * The specification of a constructor can either contain terms or a self reference, i.e. a reference to the ADT itself. - */ - trait ConstructorArgument { - /** - * Returns the term associated to a constructor argument, or in case it is a self reference, returns the term associated to the ADT. - * - * @param arg the constructor argument - * @param adt the term representing the ADT - */ - def getOrElse(adt: Expr[Ind]): Expr[Ind] = - this match { - case Self => adt - case GroundType(term) => term - } - - /** - * Substitutes the type variables of a constructor argument. - */ - def substitute(p: SubstPair*): ConstructorArgument = - this match - case Self => Self - case GroundType(t) => GroundType(t.substitute(p*)) - } - - /** - * A symbol for self reference - */ - case object Self extends ConstructorArgument - - /** - * Syntactic represenation of a term - * - * @param t the underlying term - */ - case class GroundType(t: Expr[Ind]) extends ConstructorArgument - - /** - * Shorthand for the union of the range of a function. - * - * @param f the function - */ - def unionRange(f: Expr[Ind]) = ⋃(range(f)) - - /** - * Shorthand for the range of a restricted function. - * - * @param f the function - * @param n the domain to which the function is restricted - */ - def restrRange(f: Expr[Ind], n: Expr[Ind]) = range(f↾n) - - /** - * Applies a sequence of arguments to a function. - * - * @param f the function - * @param args the arguments to apply - */ - def appSeq(f: Expr[Ind])(args: Seq[Expr[Ind]]): Expr[Ind] = args.foldLeft(f)(_ * _) - - /** - * Converts an integer to the associated ordinal. - * - * @param n the integer to convert - */ - def toTerm(n: Int): Expr[Ind] = - require(n >= 0, "n must be a non-negative integer") - if n == 0 then ∅ - else Ordinal.S(toTerm(n - 1)) - - /** - * Returns a sequence of formulas asserting that all terms of a sequence are well-typed. - * - * @param s the terms and their respective types - */ - def wellTyped(s: Seq[(Expr[Ind], Expr[Ind])]): Seq[Expr[Prop]] = s.map(_ :: _) - - /** - * Returns a sequence of formulas asserting that all terms of a sequence are well-typed with respect to the - * specification of a constructor. - * - * @param s the terms and their respective type - * @param orElse the term to use in case of a self reference - */ - def wellTyped(s: Seq[(Expr[Ind], ConstructorArgument)])(orElse: Expr[Ind]): Seq[Expr[Prop]] = s.map((t, arg) => t :: arg.getOrElse(orElse)) - - /** - * Returns a set of formulas asserting that all terms of a sequence are well-typed. - * - * @param s the terms and their respective types - */ - def wellTypedSet(s: Seq[(Expr[Ind], Expr[Ind])]): Set[Expr[Prop]] = wellTyped(s).toSet - - /** - * Returns a set of formulas asserting that all terms of a sequence are well-typed with respect to the - * specification of a constructor. - * - * @param s the terms and their respective type - * @param orElse the term to use in case of a self reference - */ - def wellTypedSet(s: Seq[(Expr[Ind], ConstructorArgument)])(orElse: Expr[Ind]): Set[Expr[Prop]] = wellTyped(s)(orElse).toSet - - /** - * Returns a formula asserting that all terms of a sequence are well-typed. - * - * @param s the terms and their respective types - */ - def wellTypedFormula(s: Seq[(Expr[Ind], Expr[Ind])]): Expr[Prop] = /\ (wellTyped(s)) - - /** - * Returns a formula asserting that all terms of a sequence are well-typed with respect to the - * specification of a constructor. - * - * @param s the terms and their respective type - * @param orElse the term to use in case of a self reference - */ - def wellTypedFormula(s: Seq[(Expr[Ind], ConstructorArgument)])(orElse: Expr[Ind]): Expr[Prop] = /\ (wellTyped(s)(orElse)) - -} - - -/** - * List of external set theoretic theorems needed for proofs about ADT. - * Some of these theorems are not yet implemented in the library and - * will be added in the future. - */ -private [adt] object ADTHelperTheorems extends lisa.Main { - - import lisa.maths.SetTheory.Base.Predef.{*, given} - import lisa.maths.SetTheory.Function.* - import lisa.maths.Quantifiers.{existentialEquivalenceDistribution, onePointRule, - existentialConjunctionWithClosedFormula} - import ADTDefinitions.* - import Helpers.* - - // ********************* - // * FIRST ORDER LOGIC * - // ********************* - - /** - * Lemma --- Alternative statement of transitivity of equality. - */ - val altEqualityTransitivity = Lemma((x === y, y === z) |- x === z) { - have(thesis) by Congruence - } - - /** - * Lemma --- Transitivity of equivalence. - */ - val equivalenceRewriting = Lemma((p1 <=> p2, p2 <=> p3) |- p1 <=> p3) { - have(thesis) by Tautology - } - - /** - * Lemma --- Modus ponens for equivalence. - */ - val equivalenceApply = Lemma((p1 <=> p2, p1) |- p2) { - have(thesis) by Tautology - } - - /** - * Lemma --- Top level existential quantifiers can be swapped. - */ - val existentialSwap = Lemma(∃(x, ∃(y, P2(x)(y))) <=> ∃(y, ∃(x, P2(x)(y)))) { - have(thesis) by Tableau - } - - /** - * Lemma --- Modus ponens for reversed equivalence. - */ - val equivalenceRevApply = Lemma((p2 <=> p1, p1) |- p2) { - have(thesis) by Tautology - } - - /** - * Lemma --- If a statement is equivalent to the conjunction of two other statements, and one of them is true, then it can be removed from the equivalence. - */ - val equivalenceAnd = Lemma((p2, p1 <=> (p2 /\ p3)) |- p1 <=> p3) { - have(thesis) by Tautology - } - - /** - * Lemma --- If two formulas are equivalent then adding a disjunction on their right side preserves the equivalence. - */ - val rightAndEquivalence = Lemma(p1 <=> p2 |- (p1 /\ p) <=> (p2 /\ p)) { - have(thesis) by Tautology - } - - /** - * Lemma --- If two formulas are equivalent then adding an implication on their left side preserves the equivalence. - */ - val impliesEquivalence = Lemma((p1 <=> p2, p3 <=> p4) |- (p1 ==> p3) <=> (p2 ==> p4)) { - have(thesis) by Tautology - } - - /** - * Lemma --- If two formulas are equivalent then adding an implication on their left side preserves the equivalence. - */ - val leftImpliesEquivalenceWeak = Lemma(p1 <=> p2 |- (p ==> p1) <=> (p ==> p2)) { - have(thesis) by Tautology - } - - /** - * Lemma --- Implication distributes over equivalence. - */ - val leftImpliesEquivalenceStrong = Lemma(p ==> (p1 <=> p2) |- (p ==> p1) <=> (p ==> p2)) { - have(thesis) by Tautology - } - - /** - * Lemma --- If there exists a unique element satisfying a predicate, then all - * other elements satisfying the predicate are equal to it. - */ - val existsOneUniqueness = Lemma((∃!(x, P(x)), P(x), P(y)) |- x === y) { - sorry - } - - // ******************* - // * NATURAL NUMBERS * - // ******************* - - // Natural numbers - val N = Constant("N") - addSymbol(N) - - /** - * Lemma --- 0 is a natural number. - * - * `0 ∈ N` - */ - val zeroIsNat = Lemma(∅ ∈ N) { - sorry - } - - /** - * Lemma --- The natural numbers are not empty. - * - * `N != ∅` - */ - val natNotEmpty = Lemma(!(N === ∅)) { - have(thesis) by Cut(zeroIsNat, setWithElementNonEmpty of (y := ∅, x := N)) - } - - /** - * Lemma --- There exists a natural number. - * - * `∃n ∈ N` - */ - val existsNat = Lemma(exists(n, in(n, N))) { - have(thesis) by RightExists(zeroIsNat) - } - - /** - * Lemma --- Successor is an injective function. - * - * `n = m <=> n + 1 = m + 1` - */ - val successorInjectivity = Lemma((n === m) <=> (successor(n) === successor(m))) { - sorry - } - - /** - * Lemma --- A term is a natural number if and only if its successor is a natural number. - * - * `n ∈ N <=> n + 1 ∈ N` - */ - val successorIsNat = Lemma(in(n, N) <=> in(successor(n), N)) { - sorry - } - - /** - * Lemma --- Any number is smaller than its successor - * - * `∀n ∈ N. n < n + 1` - */ - val inSuccessor = Lemma(in(n, successor(n))) { - val uniomAxiomForward = have(exists(y, in(y, unorderedPair(n, singleton(n))) /\ in(n, y)) |- in(n, union(unorderedPair(n, singleton(n))))) by Cut( - unionAxiom of (x := unorderedPair(n, singleton(n)), z := n), - equivalenceRevApply of (p1 := exists(y, in(y, unorderedPair(n, singleton(n))) /\ in(n, y)), p2 := in(n, union(unorderedPair(n, singleton(n))))) - ) - have(in(singleton(n), unorderedPair(n, singleton(n))) /\ in(n, singleton(n))) by RightAnd( - secondElemInPair of (x := n, y := singleton(n)), - singletonHasNoExtraElements of (x := n, y := n) - ) - thenHave(exists(y, in(y, unorderedPair(n, singleton(n))) /\ in(n, y))) by RightExists - have(in(n, union(unorderedPair(n, singleton(n))))) by Cut(lastStep, uniomAxiomForward) - thenHave(union(unorderedPair(n, singleton(n))) === successor(n) |- in(n, successor(n))) by RightSubstEq.withParametersSimple( - List((union(unorderedPair(n, singleton(n))), successor(n))), - lambda(s, in(n, s)) - ) - have(thesis) by Cut(successor.shortDefinition of (x := n), lastStep) - } - - /** - * Lemma --- 0 is not the successor of any natural number. - * - * `∀n ∈ N. n + 1 != 0` - */ - val zeroIsNotSucc = Lemma(!(successor(n) === ∅)) { - have(thesis) by Cut(inSuccessor, setWithElementNonEmpty of (y := n, x := successor(n))) - } - - /** - * Lemma --- A number is smaller or equal than another number if and only if it is strictly smaller than its successor. - * - * `m <= n <=> m < n + 1` - */ - val natSubset = Lemma(in(n, N) |- subset(m, n) <=> in(m, successor(n))) { - sorry - } - - /** - * Lemma --- The intersection of a natural number with the set of natural numbers is the number itself. - * - * `n ∩ N = n` - */ - val intersectionNat = Lemma(in(n, N) |- setIntersection(n, N) === n) { - sorry - } - - /** - * Lemma --- If a number is smaller or equal than a natural number, then it is also a natural number. - * - * `m <= n, n ∈ N |- m ∈ N` - */ - val subsetIsNat = Lemma(subset(a, b) |- in(b, N) ==> in(a, N)) { - sorry - } - - /** - * Lemma --- Induction principle for natural numbers - * - * `P(0), ∀n ∈ N. P(n) => P(n + 1) |- ∀n ∈ N. P(n)` - */ - val natInduction = Lemma((P(∅), forall(m, in(m, N) ==> (P(m) ==> P(successor(m))))) |- forall(n, in(n, N) ==> P(n))) { - sorry - } - - /** - * Lemma --- Every number is smaller or equal than its successor. - * - * `n <= n + 1` - */ - val subsetSuccessor = Lemma(subset(n, successor(n))) { - have(setUnion(n, singleton(n)) === union(unorderedPair(n, singleton(n))) |- subset(n, union(unorderedPair(n, singleton(n))))) by RightSubstEq.withParametersSimple( - List((setUnion(n, singleton(n)), union(unorderedPair(n, singleton(n))))), - lambda(s, subset(n, s)) - )(unionSubsetFirst of (a := n, b := singleton(n))) - have(subset(n, union(unorderedPair(n, singleton(n))))) by Cut(setUnion.shortDefinition of (x := n, y := singleton(n)), lastStep) - thenHave(successor(n) === union(unorderedPair(n, singleton(n))) |- subset(n, successor(n))) by RightSubstEq.withParametersSimple( - List((successor(n), union(unorderedPair(n, singleton(n))))), - lambda(s, subset(n, s)) - ) - have(thesis) by Cut(successor.shortDefinition of (x := n), lastStep) - } - - // ************* - // * FUNCTIONS * - // ************* - - /** - * Lemma --- Range introduction and elimination rules. If en element is in the image of a function, then it has a preimage inside its domain. - * - * `functional(f) |- y ⊆ Im(f) <=> ∃x ∈ Dom(f). f(x) = y` - */ - val functionRangeMembership = Lemma(functional(f) |- in(y, relationRange(f)) <=> ∃(x, in(x, relationDomain(f)) /\ (app(f, x) === y))) { - sorry - } - - /** - * Lemma --- The restriction of a function is still a function. - * - * `functional(f) |- functional(f|x)` - */ - val functionalRestrictedFunction = Lemma(functional(f) |- functional(restrictedFunction(f, x))) { - sorry - } - - /** - * Lemma --- If an element is in the image of a restricted function, then it has a preimage inside its domain. - * - * `functional(f) |- y ⊆ Im(f) <=> ∃x ∈ d ∩ Dom(f). f|d(x) = y` - */ - val restrictedFunctionRangeMembership = Lemma(functional(f) |- in(y, relationRange(restrictedFunction(f, d))) <=> ∃(x, in(x, d ∩ relationDomain(f)) /\ (app(restrictedFunction(f, d), x) === y))) { - have(functional(f) |- in(y, relationRange(restrictedFunction(f, d))) <=> ∃(x, in(x, relationDomain(restrictedFunction(f, d))) /\ (app(restrictedFunction(f, d), x) === y))) by Cut( - functionalRestrictedFunction of (x := d), - functionRangeMembership of (f := restrictedFunction(f, d)) - ) - thenHave(functional(f) |- in(y, relationRange(restrictedFunction(f, d))) <=> ∃(x, in(x, d ∩ relationDomain(f)) /\ (app(restrictedFunction(f, d), x) === y))) by Substitution.ApplyRules( - restrictedFunctionDomain of (x := d) - ) - } - - /** - * Lemma --- Characterization of the union of the range of a function. - * - * `∪ Im(h) = {z | ∃n ∈ Dom(h). z ∈ h(n)}` - */ - val unionRangeMembership = Lemma(functional(h) |- in(z, unionRange(h)) <=> exists(n, in(n, relationDomain(h)) /\ in(z, app(h, n)))) { - val iffAfterAnd = have(functional(h) |- (y ∈ relationRange(h) /\ z ∈ y) <=> ∃(m, m ∈ relationDomain(h) /\ (app(h, m) === y)) /\ z ∈ y) by Cut( - functionRangeMembership of (f := h), - rightAndEquivalence of (p1 := y ∈ relationRange(h), p2 := ∃(m, m ∈ relationDomain(h) /\ (app(h, m) === y)), p := z ∈ y) - ) - have(functional(h) |- (y ∈ relationRange(h) /\ z ∈ y) <=> ∃(m, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y)) by Apply(equivalenceRewriting).on( - iffAfterAnd, - existentialConjunctionWithClosedFormula of (P := lambda(m, m ∈ relationDomain(h) /\ (app(h, m) === y)), p := z ∈ y) - ) - - thenHave(functional(h) |- ∀(y, (y ∈ relationRange(h) /\ z ∈ y) <=> ∃(m, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y))) by RightForall - - val beforeExSwap = have(functional(h) |- ∃(y, y ∈ relationRange(h) /\ z ∈ y) <=> ∃(y, ∃(m, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y))) by Cut( - lastStep, - existentialEquivalenceDistribution of ( - P := lambda(y, y ∈ relationRange(h) /\ z ∈ y), - Q := lambda(y, ∃(m, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y)) - ) - ) - - have(∃(y, ∃(m, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y)) <=> ∃(m, ∃(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y)))) subproof { - - have(m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y <=> m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y)) by Restate - thenHave(forall(y, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y <=> m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y))) by RightForall - have(∃(y, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y) <=> ∃(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y))) by Cut( - lastStep, - existentialEquivalenceDistribution of ( - P := lambda(y, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y), - Q := lambda(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y)) - ) - ) - thenHave(forall(m, ∃(y, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y) <=> ∃(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y)))) by RightForall - have(∃(m, ∃(y, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y)) <=> ∃(m, ∃(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y)))) by Cut( - lastStep, - existentialEquivalenceDistribution of ( - P := lambda(y, ∃(y, m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y)), - Q := lambda(y, ∃(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y))) - ) - ) - have(thesis) by Apply(equivalenceRewriting).on(lastStep, existentialSwap of (P2 := λ(y, λ(m,m ∈ relationDomain(h) /\ (app(h, m) === y) /\ z ∈ y)))) - } - - val introM = - have(functional(h) |- ∃(y, y ∈ relationRange(h) /\ z ∈ y) <=> ∃(m, ∃(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y)))) by Apply(equivalenceRewriting).on(beforeExSwap, lastStep) - - have( - ∀(m, (∃(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y))) <=> (m ∈ relationDomain(h) /\ z ∈ app(h, m))) - ) by RightForall(onePointRule of (P := lambda(y, m ∈ relationDomain(h) /\ z ∈ y), y := app(h, m))) - - have( - ∃(m, (∃(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y)))) <=> ∃(m, m ∈ relationDomain(h) /\ z ∈ app(h, m)) - ) by Cut( - lastStep, - existentialEquivalenceDistribution of ( - P := lambda(m, ∃(y, m ∈ relationDomain(h) /\ z ∈ y /\ (app(h, m) === y))), - Q := lambda(m, m ∈ relationDomain(h) /\ z ∈ app(h, m)) - ) - ) - - have(functional(h) |- ∃(y, y ∈ relationRange(h) /\ z ∈ y) <=> ∃(m, m ∈ relationDomain(h) /\ z ∈ app(h, m))) by Apply(equivalenceRewriting).on( - introM, - lastStep - ) - - have(thesis) by Apply(equivalenceRewriting).on( - lastStep, - unionAxiom.asInstanceOf - ) - } - - // ************* - // * EMPTYNESS * - // ************* - - /** - * Lemma --- The union of the empty set is the empty set. - * - * `∪ ∅ = ∅` - */ - val unionEmpty = Lemma(union(∅) === ∅) { - sorry - } - - /** - * Lemma --- Restricting the domain of a function to the empty set yields the empty set. - * - * `h|∅ = ∅` - */ - val restrictedFunctionEmptyDomain = Lemma(restrictedFunction(h, ∅) === ∅) { - sorry - } - - /** - * Lemma --- If the domain of a function is non empty, then the function is non empty as well. - * - * `Dom(h) != ∅ |- h != ∅` - */ - val nonEmptyDomain = Lemma(!(relationDomain(h) === ∅) |- !(h === ∅)) { - sorry - } - - /** - * Lemma --- A superset of a non empty set is non empty. - * - * `x ⊆ y, x != ∅ |- y != ∅` - */ - val subsetNotEmpty = Lemma((subset(x, y), !(x === ∅)) |- !(y === ∅)) { - val subst = have(y === ∅ |- y === ∅) by Hypothesis - have((subset(x, ∅), y === ∅) |- (x === ∅)) by Apply(equivalenceApply of (p1 := subset(x, ∅))).on(emptySetIsItsOwnOnlySubset.asInstanceOf) - thenHave((subset(x, y), y === ∅) |- (x === ∅)) by Substitution.ApplyRules(subst) - } - - /** - * Theorem --- The range of the empty relation is empty. - * - * `range(∅) = ∅` - * - */ - val rangeEmpty = Theorem(relationRange(∅) === ∅) { - import lisa.maths.settheory.SetTheory - - have(!in(SetTheory.pair(a, t), ∅)) by Exact(emptySetAxiom) - thenHave(forall(a, !in(SetTheory.pair(a, t), ∅))) by RightForall - val s0 = thenHave(!exists(a, in(SetTheory.pair(a, t), ∅))) by Restate - - have(!in(t, ∅)) by Exact(emptySetAxiom) - have(in(t, ∅) <=> exists(a, in(SetTheory.pair(a, t), ∅))) by Tautology.from(lastStep, s0) - val defRHS = thenHave(forall(t, in(t, ∅) <=> exists(a, in(SetTheory.pair(a, t), ∅)))) by RightForall - - have((relationRange(∅) === ∅) <=> forall(t, in(t, ∅) <=> exists(a, in(SetTheory.pair(a, t), ∅)))) by InstantiateForall(∅)( - relationRange.definition of (r := ∅, z := ∅) - ) - have(relationRange(∅) === ∅) by Tautology.from(defRHS, lastStep) - } - - - /** - * Lemma --- The range of the empty function is empty. - * - * `Im(∅) = ∅` - */ - val unionRangeEmpty = Lemma(unionRange(∅) === ∅) { - have(unionRange(∅) === unionRange(∅)) by RightRefl - thenHave(unionRange(∅) === union(∅)) by Substitution.ApplyRules(rangeEmpty) - thenHave(thesis) by Substitution.ApplyRules(EmptySet.union) - } - - /** - * Lemma --- If a function and a domain are non empty, then restricting this function to this - * domain yields a non empty set. - * - * `h != ∅, d != ∅ |- h|d != ∅` - */ - val restrictedFunctionNotEmpty = Lemma((!(h === ∅), !(d === ∅)) |- !(restrictedFunction(h, d) === ∅)) { - sorry - } - - // **************** - // * MONOTONICITY * - // **************** - - /** - * Lemma --- Union is a monotonic operation with respect to set inclusion. - * - * `x ⊆ y |- ∪ x ⊆ ∪ y` - */ - val unionMonotonic = Lemma(subset(x, y) |- subset(union(x), union(y))) { - sorry - } - - /** - * Lemma --- Range is a monotonic operation with respect to set inclusion. - * - * `f ⊆ g |- Im(f) ⊆ Im(g)` - */ - val rangeMonotonic = Lemma(subset(f, g) |- subset(relationRange(f), relationRange(g))) { - sorry - } - - /** - * Lemma --- The union of the range is a monotonic operation with respect to set inclusion. - * - * `f ⊆ g |- ∪ Im(f) ⊆ ∪ Im(g)` - */ - val unionRangeMonotonic = Lemma(subset(f, g) |- subset(unionRange(f), unionRange(g))) { - have(thesis) by Apply(unionMonotonic).on(rangeMonotonic.asInstanceOf) - } - - /** - * Lemma --- If two implications are true then disjuncting on both sides is also a valid implication. - */ - val disjunctionsImplies = Lemma((p1 ==> p2, q1 ==> q2) |- (p1 \/ q1) ==> (p2 \/ q2)) { - - val right = have((p1 ==> p2, q1 ==> q2, p1) |- p2 \/ q2) by Restate - val left = have((p1 ==> p2, q1 ==> q2, q1) |- p2 \/ q2) by Restate - - have((p1 ==> p2, q1 ==> q2, p1 \/ q1) |- p2 \/ q2) by LeftOr(left, right) - } - - /** - * Lemma --- If a class function F (whose representation is P) is monotonic then with respect to set inclusion, then S -> F(S) ∪ S is also - * a monotonic function. - * - * `s ⊆ t, F(s) ⊆ F(t) |- F(s) ∪ s ⊆ F(t) ∪ t` - */ - val unionPreimageMonotonic = Lemma((subset(s, t), P(s) ==> P(t)) |- (P(s) \/ in(x, s)) ==> (P(t) \/ in(x, t))) { - have(subset(s, t) |- forall(z, in(z, s) ==> in(z, t))) by Cut( - subsetAxiom of (x := s, y := t), - equivalenceApply of (p1 := subset(s, t), p2 := forall(z, in(z, s) ==> in(z, t))) - ) - thenHave(subset(s, t) |- in(x, s) ==> in(x, t)) by InstantiateForall(x) - have(thesis) by Cut(lastStep, disjunctionsImplies of (p1 := in(x, s), p2 := in(x, t), q1 := P(s), q2 := P(t))) - } - - /** - * Lemma --- Resticting a function to a smaller domain yields a subset of the original function. - * - * `x ⊆ y |- f|x ⊆ f|y` - */ - val restrictedFunctionDomainMonotonic = Lemma(subset(x, y) |- subset(restrictedFunction(f, x), restrictedFunction(f, y))) { - sorry - } - - // ******************* - // * SPECIFIC LEMMAS * - // ******************* - - /** - * Lemma --- Characterization of the union of the range of a cumulative function restricted to the successor of a natural number. - * - * `cumulative(h) and Dom(h) = N |- ∪ Im(h|n + 1) = h(n)` - */ - val unionRangeCumulativeRestrictedFunction = - Lemma((functional(h), relationDomain(h) === N, in(n, N), ∀(m, subset(m, n) ==> subset(app(h, m), app(h, n)))) |- unionRange(restrictedFunction(h, successor(n))) === app(h, n)) { - - val domainSubset = have(in(n, N) |- setIntersection(successor(n), N) === successor(n)) by Apply(intersectionNat).on(equivalenceApply of (p1 := in(n, N)), successorIsNat.asInstanceOf) - - have(functional(h) |- (y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃(m, m ∈ (successor(n) ∩ relationDomain(h)) /\ (app(restrictedFunction(h, successor(n)), m) === y)) /\ z ∈ y) by Cut( - restrictedFunctionRangeMembership of (f := h, d := successor(n)), - rightAndEquivalence of (p1 := y ∈ restrRange(h, successor(n)), p2 := ∃(m, m ∈ (successor(n) ∩ relationDomain(h)) /\ (app(restrictedFunction(h, successor(n)), m) === y)), p := z ∈ y) - ) - - thenHave( - (functional(h), relationDomain(h) === N) |- (y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃(m, m ∈ (successor(n) ∩ N) /\ (app(restrictedFunction(h, successor(n)), m) === y)) /\ z ∈ y - ) by RightSubstEq.withParametersSimple( - List((relationDomain(h), N)), - lambda(s, (y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃(m, m ∈ (successor(n) ∩ s) /\ (app(restrictedFunction(h, successor(n)), m) === y)) /\ z ∈ y) - ) - - thenHave( - (functional(h), in(n, N), relationDomain(h) === N, successor(n) ∩ N === successor(n)) |- (y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃( - m, - m ∈ (successor(n) ∩ N) /\ (app(restrictedFunction(h, successor(n)), m) === y) - ) /\ z ∈ y - ) by Weakening - - thenHave( - (functional(h), in(n, N), relationDomain(h) === N, successor(n) ∩ N === successor(n)) |- (y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃( - m, - m ∈ successor(n) /\ (app(restrictedFunction(h, successor(n)), m) === y) - ) /\ z ∈ y - ) by RightSubstEq.withParametersSimple( - List((successor(n) ∩ N, successor(n))), - lambda(s, (y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃(m, m ∈ s /\ (app(restrictedFunction(h, successor(n)), m) === y)) /\ z ∈ y) - ) - - have( - (functional(h), in(n, N), relationDomain(h) === N) |- (y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃(m, m ∈ successor(n) /\ (app(restrictedFunction(h, successor(n)), m) === y)) /\ z ∈ y - ) by Cut(domainSubset, lastStep) - - have( - (functional(h), in(n, N), relationDomain(h) === N) |- (y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃(m, m ∈ successor(n) /\ (app(restrictedFunction(h, successor(n)), m) === y) /\ z ∈ y) - ) by Apply(equivalenceRewriting).on( - lastStep, - existentialConjunctionWithClosedFormula of (P := lambda(m, m ∈ successor(n) /\ (app(restrictedFunction(h, successor(n)), m) === y)), p := z ∈ y) - ) - - thenHave( - (functional(h), in(n, N), relationDomain(h) === N) |- ∀( - y, - (y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃(m, m ∈ successor(n) /\ (app(restrictedFunction(h, successor(n)), m) === y) /\ z ∈ y) - ) - ) by RightForall - - have( - (functional(h), in(n, N), relationDomain(h) === N) |- ∃(y, y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃( - y, - ∃(m, m ∈ successor(n) /\ (app(restrictedFunction(h, successor(n)), m) === y) /\ z ∈ y) - ) - ) by Cut( - lastStep, - existentialEquivalenceDistribution of ( - P := lambda(y, y ∈ restrRange(h, successor(n)) /\ z ∈ y), - Q := lambda(y, ∃(m, m ∈ successor(n) /\ (app(restrictedFunction(h, successor(n)), m) === y) /\ z ∈ y)) - ) - ) - - val introM = - thenHave( - (functional(h), in(n, N), relationDomain(h) === N) |- ∃(y, y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃( - m, - ∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y)) - ) - ) by Tableau - - have((∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y))) <=> (m ∈ successor(n) /\ z ∈ app(restrictedFunction(h, successor(n)), m))) by Exact( - onePointRule of (P := lambda(y, m ∈ successor(n) /\ z ∈ y)) - ) - - thenHave(m ∈ successor(n) |- (∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y))) <=> (m ∈ successor(n) /\ z ∈ app(h, m))) by Substitution.ApplyRules( - restrictedFunctionApplication - ) - thenHave((∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y))) <=> (m ∈ successor(n) /\ z ∈ app(h, m))) by Tableau - - thenHave(subset(m, n) <=> m ∈ successor(n) |- (∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y))) <=> (subset(m, n) /\ z ∈ app(h, m))) by RightSubstIff - .withParametersSimple( - List((m ∈ successor(n), subset(m, n))), - lambda(p, (∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y))) <=> (p /\ z ∈ app(h, m))) - ) - - have(in(n, N) |- (∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y))) <=> (subset(m, n) /\ z ∈ app(h, m))) by Cut(natSubset, lastStep) - - thenHave( - in(n, N) |- ∀(m, (∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y))) <=> (subset(m, n) /\ z ∈ app(h, m))) - ) by RightForall - - have( - in(n, N) |- ∃(m, (∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y)))) <=> ∃(m, subset(m, n) /\ z ∈ app(h, m)) - ) by Cut( - lastStep, - existentialEquivalenceDistribution of ( - P := lambda(m, ∃(y, m ∈ successor(n) /\ z ∈ y /\ (app(restrictedFunction(h, successor(n)), m) === y))), - Q := lambda(m, subset(m, n) /\ z ∈ app(h, m)) - ) - ) - - have((functional(h), in(n, N), relationDomain(h) === N) |- ∃(y, y ∈ restrRange(h, successor(n)) /\ z ∈ y) <=> ∃(m, subset(m, n) /\ z ∈ app(h, m))) by Apply(equivalenceRewriting).on( - introM, - lastStep - ) - - val unionIsExists = - have((functional(h), in(n, N), relationDomain(h) === N) |- z ∈ unionRange(restrictedFunction(h, successor(n))) <=> ∃(m, subset(m, n) /\ z ∈ app(h, m))) by Apply(equivalenceRewriting).on( - lastStep, - unionAxiom.asInstanceOf - ) - - val cumulativeAssumption = ∀(m, subset(m, n) ==> subset(app(h, m), app(h, n))) - - have(cumulativeAssumption |- ∃(m, subset(m, n) /\ z ∈ app(h, m)) <=> z ∈ app(h, n)) subproof { - val seq1 = have(z ∈ app(h, n) |- z ∈ app(h, n)) by Hypothesis - have(z ∈ app(h, n) |- subset(n, n) /\ z ∈ app(h, n)) by RightAnd(seq1, subsetReflexivity of (x := n)) - thenHave(z ∈ app(h, n) |- ∃(m, subset(m, n) /\ z ∈ app(h, m))) by RightExists - val backward = thenHave(cumulativeAssumption |- z ∈ app(h, n) ==> ∃(m, subset(m, n) /\ z ∈ app(h, m))) by Weakening - - have(cumulativeAssumption |- cumulativeAssumption) by Hypothesis - thenHave(cumulativeAssumption |- subset(m, n) ==> subset(app(h, m), app(h, n))) by InstantiateForall(m) - have((cumulativeAssumption, subset(m, n), z ∈ app(h, m)) |- forall(z, z ∈ app(h, m) ==> z ∈ app(h, n))) by Apply(equivalenceApply).on( - lastStep, - subsetAxiom - ) - thenHave((cumulativeAssumption, subset(m, n) /\ z ∈ app(h, m)) |- z ∈ app(h, n)) by InstantiateForall(z) - thenHave((cumulativeAssumption, ∃(m, subset(m, n) /\ z ∈ app(h, m))) |- z ∈ app(h, n)) by LeftExists - val forward = thenHave(cumulativeAssumption |- ∃(m, subset(m, n) /\ z ∈ app(h, m)) ==> z ∈ app(h, n)) by RightImplies - - have(thesis) by RightIff(forward, backward) - } - - have((functional(h), in(n, N), relationDomain(h) === N, cumulativeAssumption) |- (z ∈ unionRange(restrictedFunction(h, successor(n)))) <=> z ∈ app(h, n)) by Apply(equivalenceRewriting).on( - unionIsExists, - lastStep - ) - thenHave((functional(h), in(n, N), relationDomain(h) === N, cumulativeAssumption) |- ∀(z, z ∈ unionRange(restrictedFunction(h, successor(n))) <=> z ∈ app(h, n))) by RightForall - - have(thesis) by Apply(equivalenceApply).on(lastStep, extensionalityAxiom.asInstanceOf) - } - -} - - */ diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Tactics.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Tactics.scala deleted file mode 100644 index a65660483..000000000 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Tactics.scala +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Defines a set of tactics to reason on Algebraic Data Types - */ - -package lisa.maths.settheory.types.adt - -/* -import lisa.maths.settheory.SetTheory.{*, given} -import ADTDefinitions.* -import Helpers.* - -/** - * Tactic performing a structural induction proof over an algebraic data type. - * - * ===Usage=== - * {{{ - * have(forall(x, x :: adt => P(x)) /*or*/ x :: adt |- P(x)) by Induction(x, adt) { - * Case(c1, x1, ..., xn) subproof { - * // proof of P(xi) /\ ... P(xj) => P(c1(x1, ..., xn)) - * } - * ... - * Case(cm, x1, ..., xk) subproof { - * // proof of P(xi) /\ ... P(xj) => P(c1(x1, ..., xn')) - * } - * } - * }}} - * - * x and adt are inferred from the context if not provided by the user. - * - * Supports only 1 formula on the right hand side of the sequent. - * @param expectedVar the variable on which the induction is performed - * @param expectedADT the algebraic data type on which the induction is performed - */ -class Induction[M <: Arity](expectedVar: Option[Variable], expectedADT: Option[ADT[M]]) extends lisa.utils.prooflib.ProofTacticLib.ProofTactic { - - /** - * Given a proof of the claim for each case (possibly using the induction hypothesis), - * reassemble them to generate a proof of the claim of the form - * `∀x. x :: adt => P(x)` - * - * @param proof the proof in which the induction is performed - * @param cases the proofs of the claim for each case in addition to the variables used by the user - * @param inductionVariable the variable over which the induction is performed - * @param adt the algebraic data type to perform induction on - * @param prop the property to prove //TODO: Change to a lambda expression (Scala 3.4.2) - */ - private def proveForallPredicate[N <: Arity](using proof: lisa.SetTheoryLibrary.Proof)(cases: Map[Constructor[N], (Seq[Variable], proof.Fact)], inductionVariable: Variable, adt: ADT[N], typeVariablesSubst: Seq[Expr[Ind]], propFun: Expr[Ind] => Expr[Prop], context: Set[Expr[Prop]]): proof.Fact = - - val prop = λ(x, propFun(x)) - val typeVariablesSubstPairs = adt.typeVariables.toSeq.zip(typeVariablesSubst).map(SubstPair(_, _)) - val instTerm = adt(typeVariablesSubst*) - - adt.constructors.foldLeft[proof.Fact](adt.induction.of((typeVariablesSubstPairs :+ (P := prop))*)) ( (acc, c) => - val inductiveCaseProof = cases(c)._1.zip(c.underlying.underlying.specification.map(_.substitute(typeVariablesSubstPairs*))).foldRight[proof.Fact](cases(c)._2) ( (el, acc2) => - val (v, ty) = el - val accRight: Expr[Prop] = acc2.statement.right.head - ty match - case Self => - have((acc2.statement - accRight) by Weakening(acc2) - thenHave((lastStep.statement - (prop(v) ==> accRight)) by Weakening - thenHave(lastStep.statement.left |- forall(v, v :: instTerm ==> (prop(v) ==> accRight))) by RightForall - case GroundType(t)=> - thenHave((acc2.statement - accRight) by Weakening - thenHave(lastStep.statement.left |- forall(v, v :: t ==> accRight)) by RightForall - ) - acc.statement.right.head match - case Implies(trueInd, rest) => - // println(s"Case: ${c.fullName}") - // println(isSame(trueInd, inductiveCaseProof.statement.right.head)) - // println(inductiveCaseProof.statement) - // println(" + ") - // println(acc.statement) - // println(" = ") - // println((acc.statement.left ++ inductiveCaseProof.statement.left) |- rest) - have((acc.statement.left ++ inductiveCaseProof.statement.left) |- rest) by Sorry//Cut(inductiveCaseProof, acc) - case _ => throw UnreachableException - ) - thenHave(context |- forall(inductionVariable, inductionVariable :: instTerm ==> prop(inductionVariable))) by Tautology //Change - - - - /** - * Infers the variable, the ADT and the arguments of the ADT from a formula of the form `x :: ADT(T1, ..., Tn)`. - * - * @param f the formula to infer these elements from - */ - def inferArguments(f: Expr[Prop]): Option[(Variable, ADT[?], Seq[Expr[Ind]])] = - def checkFoundArguments(foundVar: Variable, foundADT: ADT[?], args: Seq[Expr[Ind]]): Option[(Variable, ADT[?], Seq[Expr[Ind]])] = - (expectedVar, expectedADT) match - case (Some(v), _) if v != foundVar => None - case (_, Some(a)) if a != foundADT => None - case _ => Some((foundVar, foundADT, args)) - - f match - case TypeAssignment(Variable(id), ADT(foundADT, args)) => - checkFoundArguments(Variable(id), foundADT, args) - case AppliedPredicate(in, Seq[Expr[Ind]](Variable(id), ADT(foundADT, args))) => - checkFoundArguments(Variable(id), foundADT, args) - case _ => - None - - /** - * Infers the variable, the ADT and the arguments of the ADT from a set of formula - * containing one is of the form `x :: ADT(T1, ..., Tn)`. - * - * @param s the set of formula to infer these elements from - */ - def inferArguments(s: Set[Expr[Prop]]): Option[(Variable, ADT[?], Seq[Expr[Ind]])] = - s.foldLeft[Option[(Variable, ADT[?], Seq[Expr[Ind]])]](None)((acc, prem) => - acc.orElse(inferArguments(prem)) - ) - - /** - * Infers the variable, the ADT and the arguments of the ADT from a sequent whose one of the premises - * is of the form `x :: ADT(T1, ..., Tn)`. - * - * @param seq the sequent to infer these elements from - */ - def inferArguments(seq: Sequent): Option[(Variable, ADT[?], Seq[Expr[Ind]], Option[Expr[Prop]])] = - inferArguments(seq.left).map(p => (p._1, p._2, p._3, None)) - .orElse( - seq.right.head match - case Forall(x, Implies(assignment, prop)) => - inferArguments(assignment).filter(p => p._1 == x).map(p => (p._1, p._2, p._3, Some(prop))) - case _ => None - ) - - /** - * Given a proof of the claim for each case (possibly using the induction hypothesis), - * reassemble the subproofs to generate a proof of the claim for every element of the ADT. - * - * @tparam N the arity of the ADT - * @param proof the scope in which the induction is performed - * @param cases the cases to prove. A [[CaseBuilder]] is a mutable data structure that register every case that - * has been added to the tactic. - * @param bot the claim - */ - def apply[N <: Arity](using proof: lisa.SetTheoryLibrary.Proof)(cases: ADTSyntax.CaseBuilder[N, proof.ProofStep, (Sequent, Seq[Expr[Ind]], Variable)] ?=> Unit)(bot: Sequent): proof.ProofTacticJudgement = - inferArguments(bot) match - case Some((inferedVar, inferedADT, inferedArgs, inferedProp)) => - - val prop = inferedProp.getOrElse(bot.right.head) - val propFunction = (t: Expr[Ind]) => inferedProp.getOrElse(bot.right.head).substitute(inferedVar -> t) - val assignment = inferedVar :: inferedADT(inferedArgs*) - val context = (if inferedProp.isDefined then bot else bot -<< assignment).left - val builder = ADTSyntax.CaseBuilder[N, proof.ProofStep, (Sequent, Seq[Expr[Ind]], Variable)]((context |- prop, inferedArgs, inferedVar)) - cases(using builder) - - builder.isValid(inferedADT.asInstanceOf[ADT[N]]) match - case None => - TacticSubproof { sp ?=> - proveForallPredicate(using sp)(builder.build, inferedVar, inferedADT.asInstanceOf[ADT[N]], inferedArgs, propFunction, context) - if !inferedProp.isDefined then - lastStep.statement.right.head match - case Forall(_, phi) => - thenHave(context |- phi) by InstantiateForall(inferedVar) - case _ => throw UnreachableException - - thenHave(bot) by Tautology - } - case Some(msg) => proof.InvalidProofTactic(msg) - - case None => proof.InvalidProofTactic("No variable typed with the ADT found in the context.") - -} - -/** - * Companion object for the [[Induction]] tactic class. - */ -object Induction { - def apply()(using proof: lisa.SetTheoryLibrary.Proof) = new Induction(None, None) - def apply[N <: Arity](adt: ADT[N])(using proof: lisa.SetTheoryLibrary.Proof) = new Induction(None, Some(adt)) - def apply(v: Variable)(using proof: lisa.SetTheoryLibrary.Proof) = new Induction(Some(v), None) - def apply[N <: Arity](v: Variable, adt: ADT[N])(using proof: lisa.SetTheoryLibrary.Proof) = new Induction(Some(v), Some(adt)) -} - - */ diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Typed.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Typed.scala deleted file mode 100644 index 1bbf15be0..000000000 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Typed.scala +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Gives a type theoretic interpretation to algebraic data types and functions over them. - */ - -package lisa.maths.SetTheory.Types.ADT - -/* -import lisa.maths.settheory.SetTheory.{_, given} -import lisa.maths.settheory.types.TypeLib.any -import lisa.maths.settheory.types.TypeSystem.FunctionalClass -import lisa.maths.settheory.types.TypeSystem.TypedConstantFunctional - -/** Type theoretic interpretation of a constructor, that is a function whose type is - * - * `c :: ∀X1, ..., Xn. T1 -> ... -> Tn -> ADT - * - * @tparam N the number of type variables appearing in the definition of this constructor's ADT - * @param line the line at which this constructor is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param file the file in which this constructor is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param underlying the set theoretic underlying constructor - */ -class Constructor[N <: Arity] private[adt] (using line: sourcecode.Line, file: sourcecode.File)( - private[adt] val underlying: SemanticConstructor[N] -) extends TypedConstantFunctional[N]( - underlying.fullName, - underlying.typeArity, - FunctionalClass(Seq.fill(underlying.typeArity)(any), underlying.typeVariablesSeq, underlying.typ, underlying.typeArity), - underlying.intro - ) { - - /** Name of the constructor - * - * e.g `list/cons` or `list/nil` - */ - val name = underlying.fullName - - /** Theorem --- Introduction rule - * - * `c :: ∀X1, ..., Xn. T1 -> ... -> Tn -> ADT - * - * where `c` is this constructor, `ADT` the ADT it belongs to and `T1, ..., Tn` the domains of the constructor's arguments. - * X1, ..., Xn are the type variables of the ADT. - */ - val intro = - THM(underlying.intro.statement, s"${name} introduction rule", line.value, file.value, Theorem) { - have(underlying.intro) - } - - /** Theorem --- Injectivity - * - * ` c(x1, ..., xn) = c(y1, ..., yn) <=> x1 = y1 /\ ... /\ xn = yn` - */ - lazy val injectivity = - THM(underlying.injectivity.statement, s"${name} injectivity", line.value, file.value, Theorem) { - have(underlying.injectivity) - } - - /** Type variables appearing in the signature of this constructor - */ - val typeVariables: Variable ** N = underlying.typeVariables -} - -/** Type theoretic polymorphic inductive datatype. Comes with a structural induction schema, injection and pattern matching. - * - * @tparam N the number of type variables appearing in the definition of this ADT - * @param line the line at which this ADT is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param file the file in which this ADT is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param underlying - * @param constructors - */ -class ADT[N <: Arity] private[adt] (using line: sourcecode.Line, file: sourcecode.File)( - private[adt] val underlying: SemanticADT[N], - private[adt] val constructors: Seq[Constructor[N]] -) { - - /** Name of this ADT - */ - val name = underlying.name - - /** Identifier of this ADT. - */ - val id: Identifier = underlying.id - ADT.identifiersToADT.addOne(id -> this) - - /** Theorem --- Structural induction principle - * - * e.g. `P(nil) => (∀x :: T, l :: list(T). P(l) => P(cons(x, l)))) => ∀l :: list(T). P(l)` - */ - lazy val induction = - THM(underlying.induction.statement, s"${name} structural induction principle", line.value, file.value, Theorem) { - have(underlying.induction) - } - - /** Theorem --- Elimination rules (Pattern Matching) - * - * `x :: ADT |- ∃ x1, ..., xn. x = c1 * x1 * ... * xn \/ ... \/ ∃ x1, ..., xn'. x = cm * x1 * ... * xn' - * - * Every term of this ADT is an instance of one of its constructors. - * - * e.g. `∀l :: list(T). l = nil \/ ∃x, xs. l = cons(x, xs)` - */ - lazy val elim = - THM(underlying.elim.statement, s"${name} elimination rule", line.value, file.value, Theorem) { - have(underlying.elim) - } - - /** Theorem --- Injectivity - * - * ` c1 * x1 * ... * xn != c2 * y1 * ... * ym` - * - * Instances of different constructors are different. - * - * e.g. `cons(x, l) != nil` - * - * @param c1 the first constructor - * @param c2 the second constructor - */ - def injectivity(c1: Constructor[N], c2: Constructor[N]) = - val injectivityLemma = underlying.injectivity(c1.underlying, c2.underlying) - THM(injectivityLemma.statement, s"${c1.name}-${c2.name} injectivity", line.value, file.value, Theorem) { - have(injectivityLemma) - } - - /** Type variables appearing in the signature of this ADT - */ - val typeVariables: Variable ** N = underlying.typeVariables - - /** Instantiate the type variables of this ADT with given types. - * Checks the arity at runtime. - * - * @param args the types to instantiate the type variables with - */ - def applyUnsafe(args: Term ** N): Term = underlying.term(args.toSeq) - - /** Instantiate the type variables of this ADT with given types. - * Checks the arity at runtime. - * - * @param args the types to instantiate the type variables with - */ - def applySeq(args: Seq[Term]): Term = underlying.term(args) - - /** Instantiate the type variables of this ADT with given types. - * Checks the arity at runtime. - * - * TODO: wait Scala 3.4.2 to remove this method and extend Term ** N |-> Term instead - * - * @param args the types to instantiate the type variables with - */ - def apply(args: Term*): Term = underlying.term(args) -} - -private object ADT { - - /** Global map from object identifiers to ADTs - */ - private val identifiersToADT: scala.collection.mutable.Map[Identifier, ADT[?]] = scala.collection.mutable.Map.empty - - /** Checks if a label is an ADT, and returns it if it is the case. - * - * @param l the label to check - */ - def unapply(l: Label[?]): Option[ADT[?]] = getADT(l.id) - - /** Checks if a term is an instance of an ADT and if it is the case, returns - * the appropriate instances of the type variables. - * - * @param term the term to check - */ - def unapply(obj: Term): Option[(ADT[?], Seq[Term])] = - obj match - case l: Label[?] => - val lwidened: Label[?] = l - unapply(lwidened).map((_, Seq.empty)) - case AppliedFunctional(l, args) => unapply(l).map((_, args)) - case _ => None - - /** Checks if a class is an instance of an ADT and if it is the case, returns - * the appropriate instances of the type variables. - * - * @param c the class to check - */ - def unapply(c: Class): Option[(ADT[?], Seq[Term])] = - c match - case t: Term => unapply(t) - case _ => None - - /** Returns the ADT associated with an identifier. - * - * @param id the identifier of the ADT - */ - def getADT(id: Identifier): Option[ADT[?]] = identifiersToADT.get(id) -} - -/** Type theoretic function over algebraic data types. Its definition is the direct sum of the definitions of its constructors. - * Comes with introduction and elimination rules. - * - * @constructor gives a type theoretic interpretation to a set theoretic function over an ADT - * @tparam N the number of type variables appearing in the definition of this function's domain - * @param line the line at which this ADT is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param file the file in which this ADT is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param underlying the underlying set theoretic function - * @param adt the domain of this function - */ -private class ADTFunction[N <: Arity](using line: sourcecode.Line, file: sourcecode.File)( - private val underlying: SemanticFunction[N], - private val adt: ADT[N] -) extends TypedConstantFunctional[N]( - underlying.fullName, - underlying.typeArity, - FunctionalClass(Seq.fill(underlying.typeArity)(any), underlying.typeVariablesSeq, underlying.typ, underlying.typeArity), - underlying.intro - ) { - - /** Name of the function - * - * e.g. list/length - */ - val name = underlying.fullName - - /** Theorem --- Elimination rules - * - * `f * (c * x1 * ... * xn) = case(c, x1, ..., xn)` - * - * That is, when this function is applied to a constructor, it returns the corresponding case. - */ - val elim: Map[Constructor[N], THM] = adt.constructors - .map(c => - ( - c, - THM(underlying.shortDefinition(c.underlying).statement, s"${name} elimination rule: ${c.name} case", line.value, file.value, Theorem) { - have(underlying.shortDefinition(c.underlying)) - } - ) - ) - .toMap - - /** Alias for [[this.elim]] - */ - val shortDefinition: Map[Constructor[N], THM] = elim - - /** Theorem --- Introduction rule - * - * `∀X1, ..., Xn. f(X1, ..., Xn) : ADT(X1, ..., Xn) -> T` - * - * where `f` is this function, `ADT` the ADT it takes argument and `T` its return type. - */ - val intro: THM = - THM(underlying.intro.statement, s"${name} introduction rule", line.value, file.value, Theorem) { - have(underlying.intro) - } - - /** Type variables in the signature of the function - */ - val typeVariables: Variable ** N = underlying.typeVariables -} - - */ diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Untyped.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Untyped.scala deleted file mode 100644 index 66d4d140a..000000000 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/Untyped.scala +++ /dev/null @@ -1,1659 +0,0 @@ -/** - * This file implements tactics to generate polymorphic set theoretic inductive algebraic data types (or ADT) and prove properties about them. - * An algebraic data type is the least set closed under introduction rules, also known as constructors. - * A constructor takes arguments as input that can either belong to other types (non inductive arguments) - * or to the ADT itself (inductive arguments). - * - * An example of algebraic data type is the type of singly linked lists: - * - * list ::= nil() | cons(head: T, tail: list) - */ - -package lisa.maths.SetTheory.Types.ADT - -/* -import lisa.maths.settheory.SetTheory.{*, given} -import lisa.maths.SetTheory.Function.* -import Helpers.* -import Helpers.{/\, \/, ===} -import ADTDefinitions.* -import ADTHelperTheorems as ADTThm -import ADTThm.N -import lisa.maths.SetTheory.Function.|=> -import lisa.maths.settheory.types.TypeSystem.{::} -import lisa.maths.Quantifiers.{universalEquivalenceDistribution} -import lisa.utils.fol.FOL.Variable - -/** Helpers for constructors - */ -private object Constructors { - - /** Global counter used to uniquely identify constructors and thereby avoid structural subtyping. - */ - var tagCounter = 0 -} - -/** Syntactic set theoretical interpretation of a constructor for an algebraic data type. - * In set theory, a constructor is a tuple containing the arguments it has been applied to, in addition to a tag - * uniquely identifying it. - * - * E.g. `cons(1, nil())` is represented as `(tagcons, (1, ((tagnil, ∅), ∅)))` - * - * Constructors injectivity is proved within this class. - * - * @constructor creates a new constructor out of a user specification - * @param specification types that the constructor takes as arguments - * @param variables1 variables used to represent the arguments of the constructor - * @param variables2 alternative set of variables to avoid capture issues - */ -private class SyntacticConstructor( - val specification: Seq[ConstructorArgument], - val variables1: Seq[Variable[Ind]], - val variables2: Seq[Variable[Ind]] -) { - - /** Unique identifier of this constructor - */ - val tag: Int = Constructors.tagCounter - Constructors.tagCounter = Constructors.tagCounter + 1 - - /** Term representation of the tag of this constructor - */ - val tagTerm: Expr[Ind] = toTerm(tag) - - /** Sequence of variables used to represent the arguments of the constructor - */ - val variables: Seq[Variable[Ind]] = variables1 - - /** Number of arguments that this constructor takes - */ - val arity: Int = specification.length - - /** Sequence of variables of the constructor with their respective domains. - */ - val signature1: Seq[(Variable[Ind], ConstructorArgument)] = variables1.zip(specification) - - /** Alternative sequence of variables of the constructor with their respective domains. - */ - val signature2: Seq[(Variable[Ind], ConstructorArgument)] = variables2.zip(specification) - - /** Sequence of variables of the constructor with their respective domains. - */ - val signature: Seq[(Variable[Ind], ConstructorArgument)] = signature1 - - /** Internally, an instance of this constructor is represented as a list. - * The first element of this list is the tag of this constructor. - * The following elements are its arguments. We represent lists as chained - * pairs followed by the empty set. - * - * e.g. cons(1, nil()) --> (tagcons, (1, ((tagnil, ∅), ∅))) - * - * @param args the arguments of this instance of the constructor - */ - def term(args: Seq[Expr[Ind]]): Expr[Ind] = pair(tagTerm, subterm(args)) - - /** Internal representation of an instance of this constructor in which arguments are schematic variables. - */ - val term1: Expr[Ind] = term(variables1) - - /** Internal representation of an instance of this constructor in which arguments are an alternative set of schematic variables. - */ - val term2: Expr[Ind] = term(variables2) - - /** Internal representation of an instance of this constructor in which arguments are schematic variables. - */ - val term: Expr[Ind] = term1 - - /** Internal representation of an instance of this constructor without the tag - * - * @param args the arguments of this instance of the constructor - * - * @see [[this.term]] - */ - def subterm(args: Seq[Expr[Ind]]): Expr[Ind] = args.foldRight[Expr[Ind]](∅)(pair(_, _)) - - /** Internal representation of an instance of this constructor without the tag, in which arguments are schematic variables. - */ - val subterm1: Expr[Ind] = subterm(variables1) - - /** Internal representation of an instance of this constructor without the tag, in which arguments are an alternative set - * of schematic variables. - */ - val subterm2: Expr[Ind] = subterm(variables2) - - /** Internal representation of an instance of this constructor without the tag, in which arguments are schematic variables. - */ - val subterm: Expr[Ind] = subterm1 - - /** Theorem --- Injectivity of constructors. - * - * Two instances of this constructor are equal if and only if all of their arguments are pairwise equal - * - * e.g. cons(head1, tail1) === cons(head2, tail2) <=> head1 === head2 /\ tail1 === tail2 - */ - lazy val injectivity = - if arity == 0 then - Lemma(term1 === term2) { - have(thesis) by RightRefl - } - else - Lemma((term1 === term2) <=> (variables1 === variables2)) { - - // STEP 1: Get rid of the tag using pair extensionality - have((term1 === term2) <=> (subterm1 === subterm2)) by Restate.from(Pair.extensionality of (a := tagTerm, b := subterm1, c := tagTerm, d := subterm2)) - - // STEP 2: Repeat pair extensionality until all variables have been pulled out of the term - variables1 - .zip(variables2) - .foldLeft(Seq.empty[Variable[Ind]], variables1, Seq.empty[Variable[Ind]], variables2, lastStep)((acc, v) => - - // pulledVars1 are the variables that have been pulled out of the left term - // remainingVars1 are the variables that are still in the left term - // pulledVars2 are the variables that have been pulled out of the right term - // remainingVars2 are the variables that are still in the right term - val (pulledVars1, remainingVars1, pulledVars2, remainingVars2, previousFact) = acc - - // v1 and v2 are the variables that are being pulled out - val (v1, v2) = v - - val updatedPulledVars1 = pulledVars1 :+ v1 - val updatedPulledVars2 = pulledVars2 :+ v2 - val updatedRemainingVars1 = remainingVars1.tail - val updatedRemainingVars2 = remainingVars2.tail - - val subsubterm1 = subterm(updatedRemainingVars1) - val subsubterm2 = subterm(updatedRemainingVars2) - - have( - (pair(v1, subsubterm1) === pair(v2, subsubterm2)) <=> - ((v1 === v2) /\ (subsubterm1 === subsubterm2)) - ) by Restate.from(Pair.extensionality of (a := v1, b := subsubterm1, c := v2, d := subsubterm2)) - have( - ((pulledVars1 === pulledVars2) /\ (pair(v1, subsubterm1) === pair(v2, subsubterm2))) <=> - ((pulledVars1 === pulledVars2) /\ (v1 === v2) /\ (subsubterm1 === subsubterm2)) - ) by Cut( - lastStep, - ADTThm.rightAndEquivalence of (p := pulledVars1 === pulledVars2, p1 := pair(v1, subsubterm1) === pair(v2, subsubterm2), p2 := (v1 === v2) /\ (subsubterm1 === subsubterm2)) - ) - val newFact = have( - (term1 === term2) <=> - ((updatedPulledVars1 === updatedPulledVars2) /\ (subsubterm1 === subsubterm2)) - ) by Apply(ADTThm.equivalenceRewriting).on(lastStep, previousFact) - - (updatedPulledVars1, updatedRemainingVars1, updatedPulledVars2, updatedRemainingVars2, newFact) - ) - } - -} - -/** Syntactic set theoretical interpretation of an algebraic data type. That is the least set closed under [[SyntacticConstructor]]. - * - * E.g. list is the smallest set containing nil and closed under the syntactic operation cons. - * - * Injectivity between different constructors, introduction rules and structural induction are proved within this class. - * - * @constructor creates a new algebraic data type out of a user specification. - * @param line the line at which the ADT is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param file the file in which the ADT is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param name the name of the ADT - * @param constructors constructors of the ADT - * @param typeVariables type variables used in the definition of this ADT - */ -private class SyntacticADT[N <: Arity](using line: sourcecode.Line, file: sourcecode.File)( - val name: String, - val constructors: Seq[SyntacticConstructor], - val typeVariables: Variable[Ind] ** N -) { - - /** Sequence of type variables used in the definition of this ADT - */ - val typeVariablesSeq: Seq[Variable[Ind]] = typeVariables.toSeq - - /** Number of type variables used in the definition of this ADT - */ - val typeArity: N = typeVariablesSeq.length.asInstanceOf[N] - - // *************** - // * INJECTIVITY * - // *************** - - /** Theorem --- Injectivity of constructors. - * - * Two instances of different construcors are always different. - * - * e.g. Nil != Cons(head, tail) - */ - def injectivity(c1: SyntacticConstructor, c2: SyntacticConstructor) = - require(c1.tag != c2.tag, "The given constructors must be different.") - - Lemma(!(c1.term1 === c2.term2)) { - - // STEP 0: Caching - val tagTerm1: Expr[Ind] = c1.tagTerm - val tagTerm2: Expr[Ind] = c2.tagTerm - - // STEP 1: Prove that the tags are different - val diffTag = have(!(tagTerm1 === tagTerm2)) subproof { - - // STEP 1.1: Order the tags - val minTag: Int = Math.min(c1.tag, c2.tag) - val maxTag: Int = Math.max(c1.tag, c2.tag) - - val start = have(tagTerm1 === tagTerm2 |- toTerm(maxTag) === toTerm(minTag)) by Restate - - // STEP 1.2: Apply successor injectivity to both tags until one becomes 0 - (1 to minTag).foldLeft(start)((fact, i) => - val midMaxTag = toTerm(maxTag - i) - val midMinTag = toTerm(minTag - i) - have(successor(midMaxTag) === successor(midMinTag) |- midMaxTag === midMinTag) by Cut( - ADTThm.successorInjectivity of (n := midMaxTag, m := midMinTag), - ADTThm.equivalenceApply of (p1 := successor(midMaxTag) === successor(midMinTag), p2 := midMaxTag === midMinTag) - ) - have(tagTerm1 === tagTerm2 |- midMaxTag === midMinTag) by Cut(fact, lastStep) - ) - - val chainInjectivity = thenHave(!(toTerm(maxTag - minTag) === ∅) |- !(tagTerm1 === tagTerm2)) by Restate - - // STEP 1.3: Conclude using the fact that 0 is not the successor of any number - have(!(toTerm(maxTag - minTag) === ∅)) by Exact(ADTThm.zeroIsNotSucc) - have(thesis) by Cut(lastStep, chainInjectivity) - } - - // STEP 2: Prove that the terms are different if the tags are different - have(c1.term1 === c2.term2 |- (tagTerm1 === tagTerm2) /\ (c1.subterm1 === c2.subterm2)) by Apply(ADTThm.equivalenceRevApply).on( - Pair.extensionality of (a := tagTerm1, b := c1.subterm1, c := tagTerm2, d := c2.subterm2) - ) - thenHave(!(tagTerm1 === tagTerm2) |- !(c1.term1 === c2.term2)) by Weakening - - // STEP 3: Conclude - have(!(c1.term1 === c2.term2)) by Cut(diffTag, lastStep) - } - - // ************************* - // * INTRODUCTION FUNCTION * - // ************************* - - /** Formula describing whether the variables of a constructor belongs to their respective domain or s when they are self-referencing. - * - * @param c The considered constructor - * @param s The set of elements in which self-referencing variables of the constructor are. - */ - private def constructorVarsInDomain(c: SyntacticConstructor, s: Expr[Ind]): Expr[Prop] = wellTypedFormula(c.signature)(s) - - /** Formula describing whether an element x is an instance of a specific constructor. - * - * @param c The constructor we want to check if x is an instance of - * @param x The element we want to check if it is an instance of c - * @param s The set of elements in which self-referencing arguments of the constructor are. - */ - private def isConstructor(c: SyntacticConstructor, x: Expr[Ind], s: Expr[Ind]): Expr[Prop] = - existsSeq(c.variables2, wellTypedFormula(c.signature2)(s) /\ (x === c.term2)) - - /** Formula describing whether an element x is an instance of one of this ADT's constructors. - * - * @param x The element we want to check if it is an instance of some constructor. - * @param s The set of elements in which self-referencing arguments of the constructor are. - */ - private def isConstructor(x: Expr[Ind], s: Expr[Ind]): Expr[Prop] = \/(constructors.map(c => isConstructor(c, x, s))) - - /** The introduction (class) function applies this ADT's constructors to the argument to given to it. - * It then adds to elements of the resulting set to the one given in argument. For example, if all arguments of the - * constructors were self-referencing we would have: - * - * introductionFunction(s) = {y | y = c(x1, ..., xn) for some c ∈ constructors and x1, ..., xn ∈ s} ∪ s - * - * In order to avoid introducing a new symbol in the theory, we describe this function with a predicate. - * - * @param s the argument of this function, i.e. set of elements on which the constructors are applied - * @param y the element we want to check if it is in the image of s under the introduction function. - * - * @return a formula describing whether y ∈ introductionFunction(s) - * - * @note The existence of the image of the introduction function is guaranteed by the union and replacement axioms. Moreover, it is not necessary to compute the union with s. It however simplifies further proofs. See [[this.heightSuccessorStrong]] for a proof of the equivalence of the two definitions. - */ - private def isInIntroductionFunctionImage(s: Expr[Ind])(y: Expr[Ind]): Expr[Prop] = isConstructor(y, s) \/ in(y, s) - - /** Lemma --- The introduction function is monotonic with respect to set inclusion. - * - * `s ⊆ t |- introductionFunction(s) ⊆ introductionFunction(t)` - */ - private val introductionFunctionMononotic = Lemma(subset(s, t) |- isInIntroductionFunctionImage(s)(x) ==> isInIntroductionFunctionImage(t)(x)) { - // In the rest of the proof we assume that s ⊆ t - - // STEP 0: Caching predicates that are often used - val subsetST = subset(s, t) - val isConstructorXS = isConstructor(x, s) - val isConstructorXT = isConstructor(x, t) - - // STEP 1: Prove x ∈ s implies x ∈ t - have(subsetST |- forall(z, in(z, s) ==> in(z, t))) by Apply(ADTThm.equivalenceApply of (p1 := subsetST)).on(subsetAxiom.asInstanceOf) - val subsetElimination = thenHave(subsetST |- in(z, s) ==> in(z, t)) by InstantiateForall(z) - - // STEP 2: For each constructor, prove that if x is an instance of that constructor with self referencing arguments in s - // then it is also an instance of some constructor with self referencing arguments in t - val isConstructorXSImpliesT = - for c <- constructors yield - // STEP 2.0: Caching predicates that are often used - // TODO change identifier - val labelEq = x === c.term2 - val isConstructorCXS = isConstructor(c, x, s) - val isConstructorCXT = isConstructor(c, x, t) - val varsWellTypedS = wellTypedFormula(c.signature2)(s) - val varsWellTypedT = wellTypedFormula(c.signature2)(t) - - if c.arity == 0 then have((subsetST, isConstructorCXS) |- isConstructorXT) by Restate - else - // STEP 2.1: Prove that we can expand the domain of the (quantified) variables of the constructor - val andSeq = - for (v, ty) <- c.signature2 yield have((subsetST, varsWellTypedS) |- in(v, ty.getOrElse(t))) by Weakening(subsetElimination of (z := v)) - val expandingDomain = have((subsetST, varsWellTypedS) |- varsWellTypedT) by RightAnd(andSeq*) - val weakeningLabelEq = have(labelEq |- labelEq) by Hypothesis - have((subsetST, varsWellTypedS, labelEq) |- varsWellTypedT /\ labelEq) by RightAnd(expandingDomain, weakeningLabelEq) - - // STEP 2.2: Prove that x stays an instance of this constructor if we expand the domain of the variables - thenHave((subsetST, varsWellTypedS, labelEq) |- isConstructorCXT) by QuantifiersIntro(c.variables2) - thenHave((subsetST, varsWellTypedS /\ labelEq) |- isConstructorCXT) by LeftAnd - thenHave((subsetST, isConstructorCXS) |- isConstructorCXT) by QuantifiersIntro(c.variables2) - - // STEP 2.3: Weaken the conclusion to some constructor instead of a specific one - thenHave((subsetST, isConstructorCXS) |- isConstructorXT) by Weakening - - // STEP 3: Prove that this holds for any constructor - // ? Steps 2 and 3 can be merged and optimized through the repeated use of an external theorem like [[ADTHelperTheorems.unionPreimageMonotonic]] - if constructors.isEmpty then have((subsetST, isConstructorXS) |- isConstructorXT) by Restate - else have((subsetST, isConstructorXS) |- isConstructorXT) by LeftOr(isConstructorXSImpliesT*) - - // STEP 4: Prove the thesis by showing that making the union with the function argument does not change the monotonicity - thenHave(subsetST |- isConstructorXS ==> isConstructorXT) by RightImplies - have(thesis) by Cut(lastStep, ADTThm.unionPreimageMonotonic of (P := lambda(s, isConstructorXS))) - } - - /** Lemma --- Every constructor is in the image of the introduction function. - * - * `For every c ∈ constructors, xi ∈ s, ..., xj ∈ s |- c(x1, ..., xn) ∈ introductionFunction(s)` - */ - private val constructorIsInIntroductionFunction = constructors - .map(c => - // Caching - val constructorVarsInDomainCS = constructorVarsInDomain(c, s) - - c -> Lemma(constructorVarsInDomainCS |- isInIntroductionFunctionImage(s)(c.term)) { - - have(constructorVarsInDomainCS |- constructorVarsInDomainCS /\ (c.term === c.term)) by Restate - - // Replace each variable on the LHS of the equality by a quantified variable and then introduce an existential quantifier - (c.variables2).foldRight((c.variables1, List[Variable[Ind]]()))((v, acc) => - - // At each step remove a variable and add a quantified one - val oldVariables = acc._1.init - val newVariables = v :: acc._2 - val vars = oldVariables ++ newVariables - - thenHave(constructorVarsInDomainCS |- existsSeq(newVariables, wellTypedFormula(vars.zip(c.specification))(s) /\ (c.term(vars) === c.term))) by RightExists - - (oldVariables, newVariables) - ) - - thenHave(constructorVarsInDomainCS |- isInIntroductionFunctionImage(s)(c.term)) by Weakening - } - ) - .toMap - - // ********************************** - // * EXTENDED INTRODUCTION FUNCTION * - // ********************************** - - /** The extended introduction (class) function takes a function f as an argument instead of set. - * - If f is not empty, it calls the introduction function on the union of the ranges of the function. Since f will - * always be cumulative by assumption, this is equivalent as passing as argument the broadest set among the ranges of f. - * - If the function is empty, it returns the empty set. - * - * This class function is in a suited format to be used within the transfinite recursion theorem, which will be called to - * construct the height function. - * - * @see [[this.heightFunctionUniqueness]] - * - * @param f the function given as argument to the extended introduction function - * @param x the element we want to check if it is in the image of f under the extended introduction function - * @return a formula describing whether x ∈ extendedIntroductionFunction(f) - */ - private def isInExtendedIntroductionFunctionImage(f: Expr[Ind])(x: Expr[Ind]): Expr[Prop] = !(f === ∅) /\ isInIntroductionFunctionImage(unionRange(f))(x) - - /** Lemma --- The extended introduction function is monotonic with respect to set inclusion. - * - * `f ⊆ g |- extendedIntroductionFunction(f) ⊆ extendedIntroductionFunction(g)` - */ - private val extendedIntroductionFunctionMonotonic = Lemma(subset(f, g) |- isInExtendedIntroductionFunctionImage(f)(x) ==> isInExtendedIntroductionFunctionImage(g)(x)) { - - // STEP 0: Caching - val introFunUnionRangeF = isInIntroductionFunctionImage(unionRange(f))(x) - val introFunUnionRangeG = isInIntroductionFunctionImage(unionRange(g))(x) - - // STEP 1: Instantiate monotonicity of the introduction function for the union of the ranges of f and g - have(subset(f, g) |- introFunUnionRangeF ==> introFunUnionRangeG) by Cut( - ADTThm.unionRangeMonotonic, - introductionFunctionMononotic of (s := unionRange(f), t := unionRange(g)) - ) - val left = thenHave((subset(f, g), introFunUnionRangeF) |- introFunUnionRangeG) by Restate - - // STEP 2: Conclude by applying the conjuction on both sides - have((subset(f, g), !(f === ∅), introFunUnionRangeF) |- isInExtendedIntroductionFunctionImage(g)(x)) by RightAnd(left, ADTThm.subsetNotEmpty of (x := f, y := g)) - } - - // ******************* - // * HEIGHT FUNCTION * - // ******************* - - /** The height function assigns to each natural number the set of elements of the ADT of that height or below. - * The set of terms with height 0 is empty. Non inductive constructors have height one. - * The height of an instance of an inductive constructor is the maximum height of its arguments plus one. - * The height function is guaranteed to exists and is unique. - * - * @see [[this.heightFunctionUniqueness]] - * - * @param g the function we want to know if it is the height function - * - * @return a formula that is true if and only if g is the height function - */ - private def isTheHeightFunction(h: Expr[Ind]): Expr[Prop] = - functional(h) /\ (relationDomain(h) === N) /\ forall(n, in(n, N) ==> forall(x, in(x, app(h, n)) <=> isInExtendedIntroductionFunctionImage(restrictedFunction(h, n))(x))) - - // Caching - private val fIsTheHeightFunction: Expr[Prop] = isTheHeightFunction(f) - private val hIsTheHeightFunction: Expr[Prop] = isTheHeightFunction(h) - - /** Lemma --- There exists a unique height function for this ADT. - * - * `∃!h. h = height` - * - * TODO: Prove this using transfinite recursion - */ - private val heightFunUniqueness = Axiom(existsOne(h, hIsTheHeightFunction)) - - /** Lemma --- The height function exists. - * - * `∃h. h = height` - */ - private val heightFunctionExistence = Lemma(exists(h, hIsTheHeightFunction)) { - have(thesis) by Apply(lisa.maths.Quantifiers.existsOneImpliesExists of (P := lambda(h, hIsTheHeightFunction))).on(heightFunUniqueness.asInstanceOf) - } - - /** Lemma --- If two functions are the height function then they are the same. - * - * `f = height /\ h = height => f = h` - */ - private val heightFunctionUniqueness2 = Lemma((fIsTheHeightFunction, hIsTheHeightFunction) |- f === h) { - have(thesis) by Cut(heightFunUniqueness, ADTThm.existsOneUniqueness of (P := lambda(h, hIsTheHeightFunction), x := f, y := h)) - } - - /** Lemma --- The height function is not empty. - * - * `height ≠ ∅` - */ - private val heightFunctionNonEmpty = Lemma(hIsTheHeightFunction |- !(h === ∅)) { - // The proof goes by contradiction. If the height function is empty then its domain is empty as well. - // This would imply that the set of natural numbers is empty, which is a contradiction. - have(N === ∅ |- ()) by Restate.from(ADTThm.natNotEmpty) - thenHave((relationDomain(h) === ∅, relationDomain(h) === N, relationDomain(h) === relationDomain(h)) |- ()) by LeftSubstEq.withParametersSimple( - List((relationDomain(h), ∅), (relationDomain(h), N)), - lambda((x, y), y === x) - ) - thenHave((relationDomain(h) === N, relationDomain(h) === relationDomain(h)) |- !(relationDomain(h) === ∅)) by RightNot - have(thesis) by Apply(ADTThm.nonEmptyDomain).on(lastStep) - } - - /** Lemma --- The set of elements of height n or below is the image of the extended introduction function under the height - * function restricted to n (consequence of transfinite recursion). - * - * `height(n) = extendedIntroductionFunction(height | n)` - */ - private val heightApplication = Lemma((hIsTheHeightFunction, in(n, N)) |- in(x, app(h, n)) <=> isInExtendedIntroductionFunctionImage(restrictedFunction(h, n))(x)) { - - // Caching - val extendedIntroFunRestrictedFunM = isInExtendedIntroductionFunctionImage(restrictedFunction(h, n))(x) - val heightFunApplicationDef = forall(n, in(n, N) ==> forall(x, in(x, app(h, n)) <=> extendedIntroFunRestrictedFunM)) - - // Nothing fancy, just instantiations and restates - have(heightFunApplicationDef |- heightFunApplicationDef) by Hypothesis - thenHave(heightFunApplicationDef |- in(n, N) ==> forall(x, in(x, app(h, n)) <=> extendedIntroFunRestrictedFunM)) by InstantiateForall(n) - thenHave((heightFunApplicationDef, in(n, N)) |- forall(x, in(x, app(h, n)) <=> extendedIntroFunRestrictedFunM)) by Restate - thenHave((heightFunApplicationDef, in(n, N)) |- in(x, app(h, n)) <=> extendedIntroFunRestrictedFunM) by InstantiateForall(x) - thenHave(thesis) by Weakening - } - - /** Lemma --- The height function is monotonic - * - * `n <= m => height(n) ⊆ height(m)` - * - * TODO: Try to pull out - */ - private val heightMonotonic = Lemma((hIsTheHeightFunction, in(n, N), subset(m, n)) |- subset(app(h, m), app(h, n))) { - - // STEP 0: Caching - val extendedIntroFunRestrictedFunM = isInExtendedIntroductionFunctionImage(restrictedFunction(h, m))(x) - - // STEP 1: Unfold the definition of height(m) - have((hIsTheHeightFunction, in(n, N), subset(m, n)) |- in(x, app(h, m)) <=> extendedIntroFunRestrictedFunM) by Apply(heightApplication).on(ADTThm.subsetIsNat.asInstanceOf) - val unfoldHeightApplicationM = have((hIsTheHeightFunction, in(n, N), subset(m, n), in(x, app(h, m))) |- extendedIntroFunRestrictedFunM) by Cut( - lastStep, - ADTThm.equivalenceRevApply of (p1 := in(x, app(h, m)), p2 := extendedIntroFunRestrictedFunM) - ) - - // STEP 2: Use the monotonicity of the extended introduction function - have(subset(m, n) |- extendedIntroFunRestrictedFunM ==> isInExtendedIntroductionFunctionImage(restrictedFunction(h, n))(x)) by Cut( - ADTThm.restrictedFunctionDomainMonotonic of (x := m, y := n, f := h), - extendedIntroductionFunctionMonotonic of (f := restrictedFunction(h, m), g := restrictedFunction(h, n)) - ) - have((hIsTheHeightFunction, in(n, N), subset(m, n), extendedIntroFunRestrictedFunM) |- in(x, app(h, n))) by Apply(ADTThm.equivalenceRevApply).on(lastStep, heightApplication.asInstanceOf) - - // STEP 3: Fold the definition of subset - have((hIsTheHeightFunction, in(n, N), subset(m, n), in(x, app(h, m))) |- in(x, app(h, n))) by Cut(unfoldHeightApplicationM, lastStep) - thenHave((hIsTheHeightFunction, in(n, N), subset(m, n)) |- in(x, app(h, m)) ==> in(x, app(h, n))) by RightImplies - thenHave((hIsTheHeightFunction, in(n, N), subset(m, n)) |- forall(x, in(x, app(h, m)) ==> in(x, app(h, n)))) by RightForall - have(thesis) by Apply(ADTThm.equivalenceRevApply).on(lastStep, subsetAxiom.asInstanceOf) - } - - /** Lemma --- There is no element of height 0 in the ADT. - * - * `!∃x ∈ adt. height(x) = 0` - */ - private val heightZero = Lemma(hIsTheHeightFunction |- !in(x, app(h, ∅))) { - - // This is due to the fact that the extended introduction function is the empty set when the function is empty - // (which happens when the height is set to 0). - have(hIsTheHeightFunction |- in(x, app(h, ∅)) <=> isInExtendedIntroductionFunctionImage(restrictedFunction(h, ∅))(x)) by Cut(ADTThm.zeroIsNat, heightApplication of (n := ∅)) - thenHave((restrictedFunction(h, ∅) === ∅, hIsTheHeightFunction) |- !in(x, app(h, ∅))) by - RightSubstEq.withParametersSimple( - List((restrictedFunction(h, ∅), ∅)), - lambda(s, in(x, app(h, ∅)) <=> isInExtendedIntroductionFunctionImage(s)(x)) - ) - have(thesis) by Cut(ADTThm.restrictedFunctionEmptyDomain, lastStep) - } - - /** Lemma --- The set of elements of height n + 1 is the set of elements of height n to which the introduction function is applied. - * - * `height(n + 1) = introductionFunction(height(n))` - */ - private val heightSuccessorWeak = Lemma((hIsTheHeightFunction, in(n, N)) |- in(x, app(h, successor(n))) <=> isInIntroductionFunctionImage(app(h, n))(x)) { - - // STEP 1: Prove that the restriction of height to n + 1 is not empty - val restrHeightNotEmpty: Expr[Prop] = !(restrictedFunction(h, successor(n)) === ∅) - have(!(h === ∅) |- restrHeightNotEmpty) by Cut(ADTThm.zeroIsNotSucc, ADTThm.restrictedFunctionNotEmpty of (d := successor(n))) - val restrHeightNotEmptyLemma = have(hIsTheHeightFunction |- restrHeightNotEmpty) by Cut(heightFunctionNonEmpty, lastStep) - - // STEP 2: Use the fact that if the function is cumulative then ∪ range(height | n + 1) = height(n) to conclude the proof - have((hIsTheHeightFunction, in(n, N)) |- subset(m, n) ==> subset(app(h, m), app(h, n))) by RightImplies(heightMonotonic) - thenHave((hIsTheHeightFunction, in(n, N)) |- forall(m, subset(m, n) ==> subset(app(h, m), app(h, n)))) by RightForall - val unionRangeRestr = have((hIsTheHeightFunction, in(n, N)) |- unionRange(restrictedFunction(h, successor(n))) === app(h, n)) by Apply(ADTThm.unionRangeCumulativeRestrictedFunction).on(lastStep) - - have((hIsTheHeightFunction, in(n, N)) |- in(x, app(h, successor(n))) <=> isInExtendedIntroductionFunctionImage(restrictedFunction(h, successor(n)))(x)) by Apply(heightApplication).on( - ADTThm.equivalenceApply of (p1 := in(n, N)), - ADTThm.successorIsNat.asInstanceOf - ) - - thenHave( - (hIsTheHeightFunction, in(n, N), unionRange(restrictedFunction(h, successor(n))) === app(h, n)) |- - in(x, app(h, successor(n))) <=> restrHeightNotEmpty /\ isInIntroductionFunctionImage(app(h, n))(x) - ) by - RightSubstEq.withParametersSimple( - List((unionRange(restrictedFunction(h, successor(n))), app(h, n))), - lambda(s, in(x, app(h, successor(n))) <=> (restrHeightNotEmpty /\ isInIntroductionFunctionImage(s)(x))) - ) - - have((hIsTheHeightFunction, in(n, N)) |- in(x, app(h, successor(n))) <=> restrHeightNotEmpty /\ isInIntroductionFunctionImage(app(h, n))(x)) by Cut(unionRangeRestr, lastStep) - - have((hIsTheHeightFunction, in(n, N), restrHeightNotEmpty) |- in(x, app(h, successor(n))) <=> isInIntroductionFunctionImage(app(h, n))(x)) by Apply( - ADTThm.equivalenceAnd of (p2 := restrHeightNotEmpty) - ) - .on(lastStep) - - have(thesis) by Cut(restrHeightNotEmptyLemma, lastStep) - } - - // ******** - // * TERM * - // ******** - - /** Formula describing this ADT's term, i.e. the set of all its instances. - * It equal to the union of all the terms that have a height. - * - * `adt = ∪ height(n) = {x | ∃n ∈ N. x ∈ height(n)}` - * - * @param adt the set chracterizing this ADT - */ - private def termDefinition(adt: Expr[Ind]): Expr[Prop] = forall(t, in(t, adt) <=> forall(h, hIsTheHeightFunction ==> in(t, unionRange(h)))) - - /** Lemma --- There exists a unique set satisfying the definition of this ADT - * - * `∃!z. z = ADT - */ - private val termExistence = Lemma(existsOne(z, termDefinition(z))) { - - // STEP 0: Caching - val termDefinitionRight = forall(h, hIsTheHeightFunction ==> in(t, unionRange(h))) - val inUnionRangeF = in(t, unionRange(f)) - - // STEP 1: Prove that there exists a term satisfying the definition of this ADT. - // Specifically, this term is the union of all the terms with a height. - have(exists(z, termDefinition(z))) subproof { - - // STEP 1.1: Prove the forward implication of the definition, using the uniqueness of the height function - have(inUnionRangeF |- inUnionRangeF) by Hypothesis - thenHave((f === h, inUnionRangeF) |- in(t, unionRange(h))) by RightSubstEq.withParametersSimple( - List((f, h)), - lambda(f, inUnionRangeF) - ) - have((fIsTheHeightFunction, hIsTheHeightFunction, inUnionRangeF) |- in(t, unionRange(h))) by Cut(heightFunctionUniqueness2, lastStep) - thenHave((fIsTheHeightFunction, inUnionRangeF) |- hIsTheHeightFunction ==> in(t, unionRange(h))) by RightImplies - thenHave((fIsTheHeightFunction, inUnionRangeF) |- termDefinitionRight) by RightForall - val forward = thenHave(fIsTheHeightFunction |- inUnionRangeF ==> termDefinitionRight) by RightImplies - - // STEP 1.2: Prove the backward implication of the definition - have(termDefinitionRight |- termDefinitionRight) by Hypothesis - thenHave(termDefinitionRight |- fIsTheHeightFunction ==> inUnionRangeF) by InstantiateForall(f) - val backward = thenHave(fIsTheHeightFunction |- termDefinitionRight ==> inUnionRangeF) by Restate - - // STEP 1.3: Use the existence of the height function to prove the existence of this ADT - have(fIsTheHeightFunction |- inUnionRangeF <=> termDefinitionRight) by RightIff(forward, backward) - thenHave(fIsTheHeightFunction |- forall(t, inUnionRangeF <=> termDefinitionRight)) by RightForall - - thenHave(fIsTheHeightFunction |- exists(z, forall(t, in(t, z) <=> termDefinitionRight))) by RightExists - thenHave(exists(f, fIsTheHeightFunction) |- exists(z, forall(t, in(t, z) <=> termDefinitionRight))) by LeftExists - have(thesis) by Cut(heightFunctionExistence, lastStep) - } - - // STEP 2: Conclude using the extension by definition - - have(thesis) by Cut(lastStep, uniqueByExtension of (schemPred := lambda(t, termDefinitionRight))) - } - - /** Class function defining the ADT. Takes as parameters the type variables of the ADT and return the set of all its instances. - */ - val polymorphicTerm = FunctionDefinition[N](name, line.value, file.value)(typeVariablesSeq, z, termDefinition(z), termExistence).label - - /** The set of all instances of the ADT where the type variables are not instantiated (i.e. are kept variable). - */ - val term = polymorphicTerm.applySeq(typeVariablesSeq) - - /** Definition of this ADT's term. - */ - private val termDefinition: Expr[Prop] = termDefinition(term) - - /** Lemma --- This ADT satisfies its definition. - * - * `adt = ∪ height(n)` - */ - private val termSatisfiesDefinition = Lemma(termDefinition) { - have(thesis) by InstantiateForall(term)(polymorphicTerm.definition) - } - - // ************************* - // * TYPING / INTRODUCTION * - // ************************* - - /** Lemma --- Every element of this ADT has a height. Conversely, if an element has a height, it is in this ADT. - * - * ` x ∈ ADT <=> ∃n ∈ N. x ∈ height(n)` - * - * TODO: Split into two lemmas - */ - private val termHasHeight = Lemma(hIsTheHeightFunction |- in(x, term) <=> ∃(n, in(n, N) /\ in(x, app(h, n)))) { - - // STEP 0 : Instantiate the definition of this ADT and recover the forward and backward implications - val termDefinition = have(in(x, term) <=> forall(h, hIsTheHeightFunction ==> in(x, unionRange(h)))) by InstantiateForall(x)(termSatisfiesDefinition) - val termDefinitionForward = have(in(x, term) |- forall(h, hIsTheHeightFunction ==> in(x, unionRange(h)))) by Cut( - termDefinition, - ADTThm.equivalenceApply of (p1 := in(x, term), p2 := forall(h, hIsTheHeightFunction ==> in(x, unionRange(h)))) - ) - val termDefinitionBackward = have(forall(h, hIsTheHeightFunction ==> in(x, unionRange(h))) |- in(x, term)) by Cut( - termDefinition, - ADTThm.equivalenceRevApply of (p2 := in(x, term), p1 := forall(h, hIsTheHeightFunction ==> in(x, unionRange(h)))) - ) - - // STEP 1 : Prove that an element is in this ADT if and only if it is in one of the images of the height function. - have(hIsTheHeightFunction |- in(x, term) <=> in(x, unionRange(h))) subproof { - - // STEP 1.1 : Forward implication - have(forall(h, hIsTheHeightFunction ==> in(x, unionRange(h))) |- forall(h, hIsTheHeightFunction ==> in(x, unionRange(h)))) by Hypothesis - thenHave(forall(h, hIsTheHeightFunction ==> in(x, unionRange(h))) |- hIsTheHeightFunction ==> in(x, unionRange(h))) by InstantiateForall(h) - thenHave((forall(h, hIsTheHeightFunction ==> in(x, unionRange(h))), hIsTheHeightFunction) |- in(x, unionRange(h))) by Restate - - val forward = have(hIsTheHeightFunction |- in(x, term) ==> in(x, unionRange(h))) by Apply(lastStep).on(termDefinitionForward) - - // STEP 1.2 : Backward implication, follows from uniqueness of the height function - have(in(x, unionRange(h)) |- in(x, unionRange(h))) by Hypothesis - thenHave((f === h, in(x, unionRange(h))) |- in(x, unionRange(f))) by RightSubstEq.withParametersSimple(List((f, h)), lambda(h, in(x, unionRange(h)))) - have((fIsTheHeightFunction, hIsTheHeightFunction, in(x, unionRange(h))) |- in(x, unionRange(f))) by Cut(heightFunctionUniqueness2, lastStep) - thenHave((hIsTheHeightFunction, in(x, unionRange(h))) |- fIsTheHeightFunction ==> in(x, unionRange(f))) by RightImplies - thenHave((hIsTheHeightFunction, in(x, unionRange(h))) |- forall(f, fIsTheHeightFunction ==> in(x, unionRange(f)))) by RightForall - have((hIsTheHeightFunction, in(x, unionRange(h))) |- in(x, term)) by Cut(lastStep, termDefinitionBackward) - val backward = thenHave(hIsTheHeightFunction |- in(x, unionRange(h)) ==> in(x, term)) by RightImplies - - have(thesis) by RightIff(forward, backward) - } - - // STEP 2: Conclude by instantiating the union range membership lemma - have(hIsTheHeightFunction |- in(x, term) <=> ∃(n, in(n, relationDomain(h)) /\ in(x, app(h, n)))) by Apply(ADTThm.equivalenceRewriting).on(ADTThm.unionRangeMembership.asInstanceOf, lastStep) - - thenHave((hIsTheHeightFunction, relationDomain(h) === N) |- in(x, term) <=> ∃(n, in(n, N) /\ in(x, app(h, n)))) by RightSubstEq.withParametersSimple( - List((relationDomain(h), N)), - lambda(z, in(x, term) <=> ∃(n, in(n, z) /\ in(x, app(h, n)))) - ) - } - - /** Lemma --- Every element of this ADT has a height. Conversely, if an element has a height, it is in this ADT. - * - * ` xi, ..., xj ∈ ADT <=> ∃n ∈ N. xi, ..., xj ∈ height(n)` - * - * TODO: Work this out - * TODO: Split into two lemmas - */ - private val termsHaveHeight = constructors - .map(c => - c -> Lemma(hIsTheHeightFunction |- (constructorVarsInDomain(c, term) <=> ∃(n, in(n, N) /\ constructorVarsInDomain(c, app(h, n))))) { - - if c.variables.isEmpty then have(thesis) by Weakening(ADTThm.existsNat) - else - - // STEP 1: Backward implication - - val backward = have(hIsTheHeightFunction |- ∃(n, in(n, N) /\ constructorVarsInDomain(c, app(h, n))) ==> constructorVarsInDomain(c, term)) subproof { - val andSeq = for (v, ty) <- c.signature yield ty match - case Self => - val termHasHeightBackward = have((hIsTheHeightFunction, exists(n, in(n, N) /\ in(v, app(h, n)))) |- in(v, term)) by Cut( - termHasHeight of (x := v), - ADTThm.equivalenceRevApply of (p1 := ∃(n, in(n, N) /\ in(v, app(h, n))), p2 := in(v, term)) - ) - - have((in(n, N) /\ in(v, app(h, n))) |- in(n, N) /\ in(v, app(h, n))) by Restate - thenHave((in(n, N) /\ in(v, app(h, n))) |- exists(n, in(n, N) /\ in(v, app(h, n)))) by RightExists - have((hIsTheHeightFunction, in(n, N) /\ in(v, app(h, n))) |- in(v, term)) by Cut(lastStep, termHasHeightBackward) - thenHave((hIsTheHeightFunction, in(n, N) /\ constructorVarsInDomain(c, app(h, n))) |- in(v, term)) by Weakening - case GroundType(t) => - have((hIsTheHeightFunction, in(n, N) /\ constructorVarsInDomain(c, app(h, n))) |- in(v, t)) by Restate - - have((hIsTheHeightFunction, in(n, N) /\ constructorVarsInDomain(c, app(h, n))) |- constructorVarsInDomain(c, term)) by RightAnd(andSeq*) - thenHave((hIsTheHeightFunction, exists(n, in(n, N) /\ constructorVarsInDomain(c, app(h, n)))) |- constructorVarsInDomain(c, term)) by LeftExists - } - - // STEP 2: Forward implication - - val forward = have(hIsTheHeightFunction |- constructorVarsInDomain(c, term) ==> ∃(n, in(n, N) /\ constructorVarsInDomain(c, app(h, n)))) subproof { - val nSeq: Seq[Variable[Ind]] = (0 until c.variables.size).map(i => Variable[Ind](s"n$i")) - val max = if c.arity == 0 then ∅ else nSeq.reduce[Expr[Ind]](setUnion(_, _)) - - val maxInN = have(/\(nSeq.map(n => in(n, N))) |- in(max, N)) by Sorry - - val andSeq = for ((v, ty), ni) <- c.signature.zip(nSeq) yield - val niInMax = have(subset(ni, max)) by Sorry - - ty match - case Self => - have((hIsTheHeightFunction, in(max, N), subset(ni, max)) |- subset(app(h, ni), app(h, max))) by Restate.from(heightMonotonic of (m := ni, n := max)) - have((hIsTheHeightFunction, /\(nSeq.map(n => in(n, N)))) |- subset(app(h, ni), app(h, max))) by Sorry // Apply(lastStep).on(Seq(maxInN, niInMax), excluding = nSeq) - have((hIsTheHeightFunction, /\(nSeq.map(n => in(n, N)))) |- forall(z, in(z, app(h, ni)) ==> in(z, app(h, max)))) by Apply(ADTThm.equivalenceApply) - .on(Seq(lastStep, subsetAxiom), excluding = nSeq) - thenHave((hIsTheHeightFunction, /\(nSeq.map(n => in(n, N)))) |- in(v, app(h, ni)) ==> in(v, app(h, max))) by InstantiateForall(v) - thenHave((hIsTheHeightFunction, /\(nSeq.map(n => in(n, N))), in(v, app(h, ni))) |- in(v, app(h, max))) by Restate - case GroundType(t) => - have((/\(nSeq.map(n => in(n, N))), hIsTheHeightFunction, in(v, t)) |- in(v, t)) by Restate - - have((/\(nSeq.map(n => in(n, N))), hIsTheHeightFunction, in(v, ty.getOrElse(app(h, ni)))) |- in(max, N) /\ in(v, ty.getOrElse(app(h, max)))) by RightAnd(maxInN, lastStep) - thenHave(nSeq.map(n => in(n, N) /\ in(v, ty.getOrElse(app(h, n)))).toSet + hIsTheHeightFunction |- in(max, N) /\ in(v, ty.getOrElse(app(h, max)))) by Weakening - thenHave(nSeq.map(n => in(n, N) /\ in(v, ty.getOrElse(app(h, n)))).toSet + hIsTheHeightFunction |- ∃(n, in(n, N) /\ in(v, ty.getOrElse(app(h, n))))) by RightExists - - sorry - } - - // STEP 3: Conclude - have(thesis) by RightIff(forward, backward) - } - ) - .toMap - - /** Lemma --- If all inductive arguments of a constructor have height below n then the instance of - * this constructor has height below n + 1. - * - * ` xi, ..., xj ∈ height(n) |- c(x1, ..., xn) ∈ height(n + 1)` - */ - private val heightConstructor = constructors - .map(c => - c -> Lemma((hIsTheHeightFunction, in(n, N), constructorVarsInDomain(c, app(h, n))) |- in(c.term, app(h, successor(n)))) { - - // Caching - val constructorInIntroFunHeight = isInIntroductionFunctionImage(app(h, n))(c.term) - - // Chaining the lemma on the elements of height n + 1 and the one on constructors being in the image of the introduction function - have((hIsTheHeightFunction, in(n, N), constructorInIntroFunHeight) |- in(c.term, app(h, successor(n)))) by Cut( - heightSuccessorWeak of (x := c.term), - ADTThm.equivalenceRevApply of (p1 := constructorInIntroFunHeight, p2 := in(c.term, app(h, successor(n)))) - ) - have((hIsTheHeightFunction, in(n, N), constructorVarsInDomain(c, app(h, n))) |- in(c.term, app(h, successor(n)))) by Cut(constructorIsInIntroductionFunction(c) of (s := app(h, n)), lastStep) - } - ) - .toMap - - /** Lemma --- If all inductive arguments of a constructor are in this ADT, and the non inductive ones in their respective domain, - * then the instance of this constructor is in this ADT as well. Also known as introduction rules. - * - * ` xi, ..., xj ∈ ADT |- c(x1, ..., xn) ∈ ADT` - */ - val intro = constructors - .map(c => { - c -> - Lemma(simplify(constructorVarsInDomain(c, term)) |- simplify(in(c.term, term))) { - // STEP 0: Instantiate the forward direction of termsHaveHeight. - val termsHaveHeightForward = have((hIsTheHeightFunction, constructorVarsInDomain(c, term)) |- ∃(n, in(n, N) /\ constructorVarsInDomain(c, app(h, n)))) by Cut( - termsHaveHeight(c), - ADTThm.equivalenceApply of (p1 := constructorVarsInDomain(c, term), p2 := exists(n, in(n, N) /\ constructorVarsInDomain(c, app(h, n)))) - ) - - // STEP 1: Prove that if an instance of a constructor has height n + 1 then it is in this ADT. - val left = have(in(n, N) |- in(successor(n), N)) by Cut(ADTThm.successorIsNat, ADTThm.equivalenceApply of (p1 := in(n, N), p2 := in(successor(n), N))) - val right = have(in(c.term, app(h, successor(n))) |- in(c.term, app(h, successor(n)))) by Hypothesis - have((in(n, N), in(c.term, app(h, successor(n)))) |- in(successor(n), N) /\ in(c.term, app(h, successor(n)))) by RightAnd(left, right) - thenHave((in(n, N), in(c.term, app(h, successor(n)))) |- exists(m, in(m, N) /\ in(c.term, app(h, m)))) by RightExists - have((hIsTheHeightFunction, in(n, N), in(c.term, app(h, successor(n)))) |- in(c.term, term)) by Apply(ADTThm.equivalenceRevApply).on(lastStep, termHasHeight.asInstanceOf) - - // STEP 2: Prove that if the inductive arguments of the constructor have height then the instance of the constructor is in the ADT. - have((hIsTheHeightFunction, in(n, N), constructorVarsInDomain(c, app(h, n))) |- in(c.term, term)) by Cut(heightConstructor(c), lastStep) - - // STEP 3: Prove that if the inductive arguments of the constructor are in the ADT then they have a height and therefore - // the instance of the constructor is in the ADT. - thenHave((hIsTheHeightFunction, in(n, N) /\ constructorVarsInDomain(c, app(h, n))) |- in(c.term, term)) by LeftAnd - thenHave((hIsTheHeightFunction, exists(n, in(n, N) /\ constructorVarsInDomain(c, app(h, n)))) |- in(c.term, term)) by LeftExists - have((hIsTheHeightFunction, constructorVarsInDomain(c, term)) |- in(c.term, term)) by Cut(termsHaveHeightForward, lastStep) - - // STEP 4: Remove lingering assumptions - thenHave((exists(h, hIsTheHeightFunction), constructorVarsInDomain(c, term)) |- in(c.term, term)) by LeftExists - have(constructorVarsInDomain(c, term) |- in(c.term, term)) by Cut(heightFunctionExistence, lastStep) - } - }) - .toMap - - // ************************ - // * STRUCTURAL INDUCTION * - // ************************ - - /** Lemma --- An element has height n + 1 if and only if it is the instance of some constructor with inductive arguments of height n. - * - * ` x ∈ height(n + 1) <=> x = c(x1, ..., xn) for some c and xi, ..., xj ∈ height(n)` - */ - private lazy val heightSuccessorStrong = Lemma((hIsTheHeightFunction, in(n, N)) |- in(x, app(h, successor(n))) <=> isConstructor(x, app(h, n))) { - val forward = have((hIsTheHeightFunction, in(n, N)) |- isInIntroductionFunctionImage(app(h, n))(x) ==> isConstructor(x, app(h, n))) subproof { - - def inductionFormula(n: Expr[Ind]): Expr[Prop] = isInIntroductionFunctionImage(app(h, n))(x) ==> isConstructor(x, app(h, n)) - val inductionFormulaN: Expr[Prop] = inductionFormula(n) - val inductionFormulaSuccN: Expr[Prop] = inductionFormula(successor(n)) - - // STEP 1.1 : Base case - val isContructorXHEmptySet = isConstructor(x, app(h, ∅)) - val baseCaseLeft = have(isContructorXHEmptySet |- isContructorXHEmptySet) by Hypothesis - val baseCaseRight = have((hIsTheHeightFunction, in(x, app(h, ∅))) |- ()) by Restate.from(heightZero) - have((hIsTheHeightFunction, isInIntroductionFunctionImage(app(h, ∅))(x)) |- isContructorXHEmptySet) by LeftOr(baseCaseLeft, baseCaseRight) - thenHave(hIsTheHeightFunction |- isInIntroductionFunctionImage(app(h, ∅))(x) ==> isContructorXHEmptySet) by RightImplies - val inductiveCaseRemaining = have((hIsTheHeightFunction, forall(n, in(n, N) ==> (inductionFormulaN ==> inductionFormulaSuccN))) |- forall(n, in(n, N) ==> inductionFormulaN)) by Cut( - lastStep, - ADTThm.natInduction of (P := lambda(n, inductionFormulaN)) - ) - - // STEP 1.2: Unfolding the definition of subset - have(subset(app(h, n), app(h, successor(n))) |- forall(z, in(z, app(h, n)) ==> in(z, app(h, successor(n))))) by Cut( - subsetAxiom of (x := app(h, n), y := app(h, successor(n))), - ADTThm.equivalenceApply of (p1 := subset(app(h, n), app(h, successor(n))), p2 := forall(z, in(z, app(h, n)) ==> in(z, app(h, successor(n))))) - ) - val subsetElimination = thenHave(subset(app(h, n), app(h, successor(n))) |- in(y, app(h, n)) ==> in(y, app(h, successor(n)))) by InstantiateForall(y) - - // STEP 1.3 : Use monotonicity to prove that y ∈ height(n) => y ∈ height(n + 1) - have(in(n, N) |- in(successor(n), N)) by Cut(ADTThm.successorIsNat, ADTThm.equivalenceApply of (p1 := in(n, N), p2 := in(successor(n), N))) - have((hIsTheHeightFunction, in(n, N), subset(n, successor(n))) |- subset(app(h, n), app(h, successor(n)))) by Cut(lastStep, heightMonotonic of (n := successor(n), m := n)) - have((hIsTheHeightFunction, in(n, N)) |- subset(app(h, n), app(h, successor(n)))) by Cut(ADTThm.subsetSuccessor, lastStep) - val liftHeight = have((hIsTheHeightFunction, in(n, N)) |- in(y, app(h, n)) ==> in(y, app(h, successor(n)))) by Cut(lastStep, subsetElimination) - - // STEP 1.4 : Generalize the above result to show that if for some c, x = c(x1, ..., xn) with xi, ..., xj ∈ height(n) - // then for some c', x = c'(x1, ..., xn) with xi, ..., xj ∈ height(n + 1). - - // Caching - val isConstructorXHN = isConstructor(x, app(h, n)) - val isConstructorXHSuccN = isConstructor(x, app(h, successor(n))) - val liftConstructorHeight = - if constructors.size == 0 then have((hIsTheHeightFunction, in(n, N), isConstructorXHN) |- isConstructorXHSuccN) by Restate - else - val liftConstructorHeightOrSequence = - for c <- constructors yield - - // Caching - val isConstructorCXHN = isConstructor(c, x, app(h, n)) - val isConstructorCXHSuccN = isConstructor(c, x, app(h, successor(n))) - val constructorVarsInHN = constructorVarsInDomain(c, app(h, n)) - val constructorVarsInHSuccN = constructorVarsInDomain(c, app(h, successor(n))) - - if c.arity == 0 then have((hIsTheHeightFunction, in(n, N), isConstructorCXHN) |- isConstructorCXHSuccN) by Restate - else - val liftHeightAndSequence = - for (v, ty) <- c.signature - yield have((hIsTheHeightFunction, in(n, N), constructorVarsInHN) |- in(v, ty.getOrElse(app(h, successor(n))))) by Weakening(liftHeight of (y := v)) - - val left = have((hIsTheHeightFunction, in(n, N), constructorVarsInHN) |- constructorVarsInHSuccN) by RightAnd(liftHeightAndSequence*) - val right = have(x === c.term |- x === c.term) by Hypothesis - - have((hIsTheHeightFunction, in(n, N), constructorVarsInHN, (x === c.term)) |- constructorVarsInHSuccN /\ (x === c.term)) by RightAnd( - left, - right - ) - thenHave((hIsTheHeightFunction, in(n, N), constructorVarsInHN /\ (x === c.term)) |- constructorVarsInHSuccN /\ (x === c.term)) by LeftAnd - thenHave((hIsTheHeightFunction, in(n, N), constructorVarsInHN /\ (x === c.term)) |- isConstructorCXHSuccN) by QuantifiersIntro(c.variables) - thenHave((hIsTheHeightFunction, in(n, N), isConstructorCXHN) |- isConstructorCXHSuccN) by QuantifiersIntro(c.variables) - - thenHave((hIsTheHeightFunction, in(n, N), isConstructorCXHN) |- isConstructorXHSuccN) by Weakening - - have((hIsTheHeightFunction, in(n, N), isConstructorXHN) |- isConstructorXHSuccN) by LeftOr(liftConstructorHeightOrSequence*) - - // STEP 1.5: Show that x ∈ introductionFunction(height(n + 1)) => for some c, x = c(x1, ..., xn) - // with xi, ..., xj ∈ height(n + 1). - val heightSuccessorWeakForward = have((hIsTheHeightFunction, in(n, N), in(x, app(h, successor(n)))) |- isInIntroductionFunctionImage(app(h, n))(x)) by Cut( - heightSuccessorWeak, - ADTThm.equivalenceApply of (p1 := in(x, app(h, successor(n))), p2 := isInIntroductionFunctionImage(app(h, n))(x)) - ) - have((inductionFormulaN, isInIntroductionFunctionImage(app(h, n))(x)) |- isConstructorXHN) by Restate - have((hIsTheHeightFunction, in(n, N), in(x, app(h, successor(n))), inductionFormulaN) |- isConstructorXHN) by Cut(heightSuccessorWeakForward, lastStep) - val right = have((hIsTheHeightFunction, in(n, N), in(x, app(h, successor(n))), inductionFormulaN) |- isConstructorXHSuccN) by Cut(lastStep, liftConstructorHeight) - val left = have(isConstructorXHSuccN |- isConstructorXHSuccN) by Hypothesis - have((hIsTheHeightFunction, in(n, N), inductionFormulaN, isInIntroductionFunctionImage(app(h, successor(n)))(x)) |- isConstructorXHSuccN) by LeftOr(left, right) - - // STEP 1.6: Conclude - thenHave((hIsTheHeightFunction, in(n, N), inductionFormulaN) |- inductionFormulaSuccN) by RightImplies - thenHave((hIsTheHeightFunction, in(n, N)) |- inductionFormulaN ==> inductionFormulaSuccN) by RightImplies - thenHave(hIsTheHeightFunction |- in(n, N) ==> (inductionFormulaN ==> inductionFormulaSuccN)) by RightImplies - thenHave(hIsTheHeightFunction |- forall(n, in(n, N) ==> (inductionFormulaN ==> inductionFormulaSuccN))) by RightForall - have(hIsTheHeightFunction |- forall(n, in(n, N) ==> inductionFormulaN)) by Cut(lastStep, inductiveCaseRemaining) - thenHave(hIsTheHeightFunction |- in(n, N) ==> inductionFormulaN) by InstantiateForall(n) - } - - // STEP 2: Prove the backward implication - val backward = have((hIsTheHeightFunction, in(n, N)) |- isConstructor(x, app(h, n)) ==> isInIntroductionFunctionImage(app(h, n))(x)) by Restate - - // STEP 3: Conclude - have((hIsTheHeightFunction, in(n, N)) |- isInIntroductionFunctionImage(app(h, n))(x) <=> isConstructor(x, app(h, n))) by RightIff(forward, backward) - have(thesis) by Apply(ADTThm.equivalenceRewriting).on(lastStep, heightSuccessorWeak.asInstanceOf) - } - - /** Generates the structural inductive case for a given constructor. - * - * @param c the constructor - */ - lazy val inductiveCase: Map[SyntacticConstructor, Expr[Prop]] = constructors - .map(c => - c -> c.signature.foldRight[Expr[Prop]](P(c.term))((el, fc) => - val (v, ty) = el - ty match - case Self => forall(v, in(v, term) ==> (P(v) ==> fc)) - case GroundType(t) => forall(v, in(v, t) ==> fc) - ) - ) - .toMap - - /** Lemma --- Structural induction principle for this ADT. - * - * `base cases => inductive cases => ∀x ∈ ADT. P(x)` - */ - lazy val induction = Lemma(constructors.foldRight[Expr[Prop]](forall(x, in(x, term) ==> P(x)))((c, f) => inductiveCase(c) ==> f)) { - - // List of cases to prove for structural induction to hold - val structuralInductionPreconditions: Expr[Prop] = /\(constructors.map(inductiveCase)) - - // We want to prove the claim by induction on the height of n, i.e. prove that for any - // n in N, P holds. - def inductionFormula(n: Expr[Ind]): Expr[Prop] = forall(x, in(x, app(h, n)) ==> P(x)) - val inductionFormulaN: Expr[Prop] = inductionFormula(n) - - // STEP 1: Prove the base case - have(hIsTheHeightFunction |- in(x, app(h, ∅)) ==> P(x)) by Weakening(heightZero) - val zeroCase = thenHave(hIsTheHeightFunction |- inductionFormula(∅)) by RightForall - - val inductiveCaseRemaining = have((hIsTheHeightFunction, forall(n, in(n, N) ==> (inductionFormulaN ==> inductionFormula(successor(n))))) |- forall(n, in(n, N) ==> inductionFormulaN)) by Cut( - zeroCase, - ADTThm.natInduction of (P := lambda(n, inductionFormulaN)) - ) - - // STEP 2: Prove the inductive case - val succCase = have((hIsTheHeightFunction, structuralInductionPreconditions) |- forall(n, in(n, N) ==> (inductionFormulaN ==> inductionFormula(successor(n))))) subproof { - - // STEP 2.1 : Prove that if the x = c(x1, ..., xn) for some c and xi, ..., xj ∈ height(n) then P(x) holds. - val isConstructorImpliesP = have((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N), inductionFormulaN, isConstructor(x, app(h, n))) |- P(x)) subproof { - - if constructors.isEmpty then have(thesis) by Restate - else - val orSeq = - (for c <- constructors yield - - // Caching - val constructorPrecondition = inductiveCase(c) - val constructorVarsInHN = constructorVarsInDomain(c, app(h, n)) - val constructorVarsInHNEx = ∃(n, in(n, N) /\ constructorVarsInDomain(c, app(h, n))) - val constructorVarsInTerm = constructorVarsInDomain(c, term) - - // STEP 2.1.1: Prove that if xi, ..., xj ∈ height(n) then xi, ..., xj ∈ ADT. - val constructorQuantVarsInHNToTerm = have((hIsTheHeightFunction, in(n, N), constructorVarsInHN) |- constructorVarsInTerm) subproof { - have((hIsTheHeightFunction, in(n, N), constructorVarsInHN) |- in(n, N) /\ constructorVarsInHN) by Restate - val consVarL = thenHave((hIsTheHeightFunction, in(n, N), constructorVarsInHN) |- constructorVarsInHNEx) by RightExists - have((constructorVarsInTerm <=> constructorVarsInHNEx, constructorVarsInHNEx) |- constructorVarsInTerm) by Restate.from( - ADTThm.equivalenceRevApply of (p1 := constructorVarsInTerm, p2 := constructorVarsInHNEx) - ) - have((hIsTheHeightFunction, constructorVarsInHNEx) |- constructorVarsInTerm) by Cut( - termsHaveHeight(c), - lastStep - ) - have(thesis) by Cut(consVarL, lastStep) - } - - // STEP 2.1.2: Prove that if xi, ..., xj ∈ height(n) then P(c(x1, ..., xn)). - have((hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, constructorVarsInHN) |- constructorPrecondition) by Restate - - c.signature - .foldLeft(lastStep)((fact, el) => - val (v, ty) = el - - fact.statement.right.head match - case Forall(_, factCclWithoutForall) => - thenHave((hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, constructorVarsInHN) |- factCclWithoutForall) by InstantiateForall(v) - - factCclWithoutForall match - case Implies(membership, subformula) => - ty match - case Self => - subformula match - case Implies(hypothesis, subSubFormula) => - val proofSubSubFormula = thenHave( - (hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, constructorVarsInTerm, constructorVarsInHN, P(v)) |- subSubFormula - ) by Weakening - - have(inductionFormulaN |- inductionFormulaN) by Hypothesis - thenHave(inductionFormulaN |- in(v, app(h, n)) ==> P(v)) by InstantiateForall(v) - thenHave((inductionFormulaN, constructorVarsInHN) |- P(v)) by Weakening - - have((hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, constructorVarsInTerm, constructorVarsInHN) |- subSubFormula) by Cut( - lastStep, - proofSubSubFormula - ) - have((hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, constructorVarsInHN) |- subSubFormula) by Cut( - constructorQuantVarsInHNToTerm, - lastStep - ) - - case _ => throw UnreachableException - - case GroundType(t) => - thenHave((hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, constructorVarsInHN) |- subformula) by Restate - case _ => throw UnreachableException - case _ => throw UnreachableException - ) - - thenHave((hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, constructorVarsInHN) |- P(c.term)) by Restate - - // STEP 2.1.3: Prove that if xi, ..., xj ∈ height(n) then P(x). - thenHave((hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, constructorVarsInHN, x === c.term) |- P(x)) by RightSubstEq - .withParametersSimple(List((x, c.term)), lambda(x, P(x))) - - thenHave((hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, constructorVarsInHN /\ (x === c.term)) |- P(x)) by LeftAnd - - thenHave((hIsTheHeightFunction, constructorPrecondition, in(n, N), inductionFormulaN, isConstructor(c, x, app(h, n))) |- P(x)) by QuantifiersIntro(c.variables) - thenHave((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N), inductionFormulaN, isConstructor(c, x, app(h, n))) |- P(x)) by Weakening - ).toSeq - - have((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N), inductionFormulaN, isConstructor(x, app(h, n))) |- P(x)) by LeftOr(orSeq*) - } - - // STEP 2.2: Prove that if x ∈ height(n + 1) then P(x) holds. - have((hIsTheHeightFunction, in(n, N), in(x, app(h, successor(n)))) |- isConstructor(x, app(h, n))) by Cut( - heightSuccessorStrong, - ADTThm.equivalenceApply of (p1 := in(x, app(h, successor(n))), p2 := isConstructor(x, app(h, n))) - ) - have((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N), inductionFormulaN, in(x, app(h, successor(n)))) |- P(x)) by Cut(lastStep, isConstructorImpliesP) - - // STEP 2.3: Conclude - thenHave((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N), inductionFormulaN) |- in(x, app(h, successor(n))) ==> P(x)) by RightImplies - - thenHave((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N), inductionFormulaN) |- inductionFormula(successor(n))) by RightForall - thenHave((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N)) |- inductionFormulaN ==> inductionFormula(successor(n))) by RightImplies - thenHave((hIsTheHeightFunction, structuralInductionPreconditions) |- in(n, N) ==> (inductionFormulaN ==> inductionFormula(successor(n)))) by RightImplies - thenHave(thesis) by RightForall - } - - // STEP 3: Conclude - - have((hIsTheHeightFunction, structuralInductionPreconditions) |- forall(n, in(n, N) ==> inductionFormulaN)) by Cut(lastStep, inductiveCaseRemaining) - thenHave((hIsTheHeightFunction, structuralInductionPreconditions) |- in(n, N) ==> inductionFormulaN) by InstantiateForall(n) - thenHave((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N)) |- inductionFormulaN) by Restate - thenHave((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N)) |- in(x, app(h, n)) ==> P(x)) by InstantiateForall(x) - thenHave((hIsTheHeightFunction, structuralInductionPreconditions, in(n, N) /\ in(x, app(h, n))) |- P(x)) by Restate - val exImpliesP = thenHave((hIsTheHeightFunction, structuralInductionPreconditions, exists(n, in(n, N) /\ in(x, app(h, n)))) |- P(x)) by LeftExists - have((hIsTheHeightFunction, in(x, term)) |- exists(n, in(n, N) /\ in(x, app(h, n)))) by Cut( - termHasHeight, - ADTThm.equivalenceApply of (p1 := in(x, term), p2 := exists(n, in(n, N) /\ in(x, app(h, n)))) - ) - - have((hIsTheHeightFunction, structuralInductionPreconditions, in(x, term)) |- P(x)) by Cut(lastStep, exImpliesP) - thenHave((exists(h, hIsTheHeightFunction), structuralInductionPreconditions, in(x, term)) |- P(x)) by LeftExists - have((structuralInductionPreconditions, in(x, term)) |- P(x)) by Cut(heightFunctionExistence, lastStep) - thenHave(structuralInductionPreconditions |- in(x, term) ==> P(x)) by RightImplies - thenHave(structuralInductionPreconditions |- forall(x, in(x, term) ==> P(x))) by RightForall - } - -} - -/** Semantic set theoretical interpretation of a constructor for an algebraic data type. - * That is a function from the arguments' domains to the set of instances of the algebraic data type. - * - * `c : T1 -> ... -> Tn -> ADT` - * - * Since polymorphism is supported, this function is parametrized by the type variables appearing inside - * the specification of the ADT. In this sense, a constructor is a class function whose parameters are - * type variables and whose body is the set theoretic function detailed above. With polymorphism, the signature - * thus becomes: - * - * `c(X1, ..., Xn) : T1(X1, ..., Xn) -> ... -> Tn(X1, ..., Xn) -> ADT(X1, ..., Xn)` - * - * Injectivity and introduction rule are proven within this class. - * - * @constructor generates a class function for this constructor - * @param line the line at which this constructor is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param file the file in which this constructor is defined. Usually fetched automatically by the compiler. - * Used for error reporting - * @param name the name of this constructor - * @param underlying the syntactic constructor - * @param adt the algebraic data type to which this constructor belongs - */ -private class SemanticConstructor[N <: Arity](using line: sourcecode.Line, file: sourcecode.File)( - val name: String, - val underlying: SyntacticConstructor, - val adt: SyntacticADT[N] -) { - - /** Full name of this constructor, i.e. concatenation of the ADT name and this constructor name. - */ - val fullName: String = s"${adt.name}/${name}" - - /** Type variables that may appear in the signature of this constructor. - */ - val typeVariables: Variable[Ind] ** N = adt.typeVariables - - /** Sequence of type variables that may appear in the signature of this constructor. - */ - val typeVariablesSeq: Seq[Variable[Ind]] = adt.typeVariablesSeq - - /** Number of type variables in the signature of this constructor. - */ - val typeArity: N = adt.typeArity - - /** Variables used for constructor arguments. - */ - val variables: Seq[Variable[Ind]] = underlying.variables - - /** Variables used for constructor arguments. - */ - val variables1: Seq[Variable[Ind]] = underlying.variables1 - - /** Alternative set of variables used for constructor arguments. - */ - val variables2: Seq[Variable[Ind]] = underlying.variables2 - - /** Set of variables for this constructor with their respective domain or a - * special symbol in case the domain is the ADT. - * - * @param vars variables - */ - def syntacticSignature(vars: Seq[Variable[Ind]]): Seq[(Variable[Ind], ConstructorArgument)] = - vars.zip(underlying.specification) - - /** Variables of this constructor with their respective domain or a special symbol in case the domain is the ADT. - */ - val syntacticSignature: Seq[(Variable[Ind], ConstructorArgument)] = underlying.signature - - /** Constructor arguments with their respective domains. - * - * @param vars this constructor arguments - */ - def semanticSignature(vars: Seq[Variable[Ind]]): Seq[(Variable[Ind], Expr[Ind])] = vars.zip(underlying.specification.map(_.getOrElse(adt.term))) - - /** Variables of this constructor with their respective domains. - */ - val semanticSignature: Seq[(Variable[Ind], Expr[Ind])] = semanticSignature(variables) - - /** Variables of this constructor with their respective domains. - */ - val semanticSignature1: Seq[(Variable[Ind], Expr[Ind])] = semanticSignature - - /** Alternative set of variables of this constructor with their respective domain. - */ - val semanticSignature2: Seq[(Variable[Ind], Expr[Ind])] = semanticSignature(variables2) - - /** Type of this constructor. - */ - val typ: Expr[Ind] = semanticSignature.unzip._2.foldRight[Expr[Ind]](adt.term)((a, b) => a |=> b) - - /** Arity of this constructor. - */ - val arity: Int = variables.size - - /** Internal representation of this constructor (i.e. as a tuple). - */ - val structuralTerm: Expr[Ind] = underlying.term - - /** Internal representation of this constructor (i.e. as a tuple). - */ - val structuralTerm1: Expr[Ind] = underlying.term1 - - /** Internal representation of this constructor (i.e. as a tuple) with an alternative set of variables. - */ - val structuralTerm2: Expr[Ind] = underlying.term2 - - /** Definition of this constructor. - * - * Formally it is the only function whose codomain is the ADT such that for all variables x1 :: S1, ...,xn :: Sn - * c * x1 * ... * xn = (tagc, (x1, (..., (xn, ∅)...)) - */ - private val untypedDefinition = (c :: typ) /\ forallSeq(variables, wellTypedFormula(semanticSignature) ==> (appSeq(c)(variables) === structuralTerm)) - - /** Lemma --- Uniqueness of this constructor. - * - * ` ∃!c. c ∈ T1 -> ... -> Tn -> ADT /\ ∀x1, ..., xn. c * x1 * ...* xn = (tagc, (x1, (..., (xn, ∅)...))` - */ - private val uniqueness = Axiom(existsOne(c, untypedDefinition)) - - /** Class function representing this constructor - */ - private val classFunction = FunctionDefinition[N](fullName, line.value, file.value)(typeVariablesSeq, c, untypedDefinition, uniqueness).label - - /** Identifier of this constructor. - */ - val id: Identifier = classFunction.id - - /** This constructor in which type variables are instantiated. - * - * @param args the instances of this constructor's type variables - */ - def term(args: Seq[Expr[Ind]]): Expr[Ind] = classFunction.applySeq(args) - - /** Constructor where type variables are instantiated with schematic variables. - */ - private val term: Expr[Ind] = term(typeVariablesSeq) - - /** Constructor where type variables are instantiated with schematic variables and arguments instantiated. - * - * @param args the instances of this constructor arguments - */ - def appliedTerm(args: Seq[Expr[Ind]]): Expr[Ind] = appSeq(term)(args) - - /** Constructor where type variables and arguments are instantiated with schematic variables. - */ - val appliedTerm: Expr[Ind] = appliedTerm(variables) - - /** Constructor where type variables and arguments are instantiated with schematic variables. - */ - val appliedTerm1: Expr[Ind] = appliedTerm - - /** Constructor where type variables and arguments are instantiated with schematic variables. - * Arguments variables are however drawn from an alternative set of variables. - */ - val appliedTerm2: Expr[Ind] = appliedTerm(variables2) - - /** Lemma --- This constructor is equal to its internal representation. - * - * `∀x1, ..., xn. c * x1 * ... * xn = (tagc, (x1, (..., (xn, ∅)...))` - */ - val shortDefinition = Lemma(forallSeq(variables, wellTypedFormula(semanticSignature) ==> (appliedTerm === structuralTerm))) { - have(forall(c, (term === c) <=> untypedDefinition)) by Exact(classFunction.definition) - thenHave((term === term) <=> ((term :: typ) /\ forallSeq(variables, wellTypedFormula(semanticSignature) ==> (appliedTerm === structuralTerm)))) by InstantiateForall(term) - thenHave(thesis) by Weakening - } - - /** Lemma --- Introduction rule for this constructor. - * - * `∀A1, ..., Am. c(X1, ..., Xm) ∈ T1(X1, ..., Xm) -> ... -> Tn(X1, ..., Xm) -> ADT(X1, ..., Xm)` - * - * where Ai are the type variables of the ADT and Ti are domains of this constructor arguments. - * - * e.g. `∀T. nil(T) ∈ list(T)` and `∀T. cons(T) ∈ T -> list(T) -> list(T)` - */ - val intro = Lemma(forallSeq(typeVariablesSeq, term :: typ)) { - have(forall(c, (term === c) <=> untypedDefinition)) by Exact(classFunction.definition) - thenHave((term === term) <=> ((term :: typ) /\ forallSeq(variables, wellTypedFormula(semanticSignature) ==> (appliedTerm === structuralTerm)))) by InstantiateForall(term) - thenHave(term :: typ) by Weakening - thenHave(thesis) by QuantifiersIntro(typeVariablesSeq) - } - - /** Theorem --- Injectivity of constructors. - * - * Two instances of this constructor are equal if and only if all of their arguments are pairwise equal - * - * e.g. Cons(head1, tail1) === Cons(head2, tail2) <=> head1 === head2 /\ tail1 === tail2 - */ - lazy val injectivity = - val vars1WellTyped: Set[Expr[Prop]] = wellTypedSet(semanticSignature1) - val vars2WellTyped: Set[Expr[Prop]] = wellTypedSet(semanticSignature2) - - if arity == 0 then - Lemma(appliedTerm1 === appliedTerm2) { - have(thesis) by RightRefl - } - else - Lemma(vars1WellTyped ++ vars2WellTyped |- simplify((appliedTerm1 === appliedTerm2) <=> (variables1 === variables2))) { - - have(forallSeq(variables1, wellTypedFormula(semanticSignature1) ==> (appliedTerm1 === structuralTerm1))) by Restate.from(shortDefinition) - - variables1.foldLeft(lastStep)((fact, v) => - fact.statement.right.head match - case Forall(_, phi) => thenHave(phi) by InstantiateForall(v) - case _ => throw UnreachableException - ) - val tappTerm1Def = thenHave(vars1WellTyped |- appliedTerm1 === structuralTerm1) by Restate - - // println(forallSeq(variables1, wellTypedFormula(semanticSignature1) ==> (appliedTerm1 === structuralTerm1))) - // println(forallSeq(variables2, wellTypedFormula(semanticSignature2) ==> (appliedTerm2 === structuralTerm))) - have(forallSeq(variables2, wellTypedFormula(semanticSignature2) ==> (appliedTerm2 === structuralTerm2))) by Restate.from(shortDefinition) - - variables2.foldLeft(lastStep)((fact, v) => - fact.statement.right.head match - case Forall(_, phi) => thenHave(phi) by InstantiateForall(v) - case _ => throw UnreachableException - ) - val tappTerm2Def = thenHave(vars2WellTyped |- appliedTerm2 === structuralTerm2) by Restate - - val s0 = have(vars2WellTyped + (appliedTerm1 === appliedTerm2) |- appliedTerm1 === structuralTerm2) by Cut( - tappTerm2Def, - ADTThm.altEqualityTransitivity of (x := appliedTerm1, y := appliedTerm2, z := structuralTerm2) - ) - have(vars1WellTyped + (appliedTerm1 === structuralTerm2) |- structuralTerm1 === structuralTerm2) by Cut( - tappTerm1Def, - ADTThm.altEqualityTransitivity of (x := structuralTerm1, y := appliedTerm1, z := structuralTerm2) - ) - have((vars1WellTyped ++ vars2WellTyped) + (appliedTerm1 === appliedTerm2) |- structuralTerm1 === structuralTerm2) by Cut(s0, lastStep) - val forward = thenHave(vars1WellTyped ++ vars2WellTyped |- (appliedTerm1 === appliedTerm2) ==> (structuralTerm1 === structuralTerm2)) by RightImplies - - val s1 = have(vars1WellTyped + (structuralTerm1 === structuralTerm2) |- appliedTerm1 === structuralTerm2) by Cut( - tappTerm1Def, - ADTThm.altEqualityTransitivity of (x := appliedTerm1, y := structuralTerm1, z := structuralTerm2) - ) - have(vars2WellTyped + (appliedTerm1 === structuralTerm2) |- appliedTerm1 === appliedTerm2) by Cut( - tappTerm2Def, - ADTThm.altEqualityTransitivity of (x := appliedTerm1, y := structuralTerm2, z := appliedTerm2) - ) - have((vars1WellTyped ++ vars2WellTyped) + (structuralTerm1 === structuralTerm2) |- appliedTerm1 === appliedTerm2) by Cut(s1, lastStep) - val backward = thenHave(vars1WellTyped ++ vars2WellTyped |- (structuralTerm1 === structuralTerm2) ==> (appliedTerm1 === appliedTerm2)) by RightImplies - - val definitionUnfolding = have(vars1WellTyped ++ vars2WellTyped |- (appliedTerm1 === appliedTerm2) <=> (structuralTerm1 === structuralTerm2)) by RightIff(forward, backward) - have((appliedTerm1 === appliedTerm2) <=> (structuralTerm1 === structuralTerm2) |- (appliedTerm1 === appliedTerm2) <=> /\(variables1.zip(variables2).map(_ === _))) by Sorry - Cut( - underlying.injectivity, - ADTThm.equivalenceRewriting of (p1 := (appliedTerm1 === appliedTerm2), p2 := (structuralTerm1 === structuralTerm2), p3 := /\(variables1.zip(variables2).map(_ === _))) - ) - have(thesis) by Cut(definitionUnfolding, lastStep) - } - - /** Case generated by this constructor when performing a proof by induction - */ - lazy val inductiveCase: Expr[Prop] = - syntacticSignature.foldRight[Expr[Prop]](P(appliedTerm1))((el, fc) => - val (v, typ) = el - typ match - case Self => forall(v, v :: adt.term ==> (P(v) ==> fc)) - case GroundType(t) => forall(v, v :: t ==> fc) - ) -} - -/** Semantic set theoretical interpretation of an algebraic data type. That is the least set closed under [[SemanticConstructor]]. - * - * E.g. list is the smallest set containing nil and closed under the cons function. - * - * Injectivity between different constructors, structural induction and elimination rule are proved within this class. - * - * @constructor generates a semantic interpretation for this ADT out of a syntactic one - * @param underlying the syntactic representation of this ADT - * @param constructors constructors of this ADT - */ -private class SemanticADT[N <: Arity]( - val underlying: SyntacticADT[N], - val constructors: Seq[SemanticConstructor[N]] -) { - - /** Name of this ADT. - */ - val name: String = underlying.name - - /** Identifier of this ADT. - */ - val id: Identifier = underlying.polymorphicTerm.id - - /** Type variables of this ADT. - */ - val typeVariables: Variable[Ind] ** N = underlying.typeVariables - - /** Sequence of type variables of this ADT. - */ - val typeVariablesSeq: Seq[Variable[Ind]] = underlying.typeVariablesSeq - - /** Number of type variables in this ADT. - */ - val typeArity: N = underlying.typeArity - - /** Term representing this ADT where type variables are instantiated with given arguments. - * - * @param args the instances of this ADT type variables - */ - def term(args: Seq[Expr[Ind]]) = underlying.polymorphicTerm.applySeq(args) - - /** Term representing this ADT where type variables are instantiated with schematic variables. - */ - val term: Expr[Ind] = underlying.term - - /** Theorem --- Injectivity of constructors. - * - * Two instances of different construcors are always different. - * - * e.g. Nil != Cons(head, tail) - */ - def injectivity(c1: SemanticConstructor[N], c2: SemanticConstructor[N]) = - - val vars1WellTyped: Set[Expr[Prop]] = wellTypedSet(c1.semanticSignature1) - val vars2WellTyped: Set[Expr[Prop]] = wellTypedSet(c2.semanticSignature2) - - Lemma(vars1WellTyped ++ vars2WellTyped |- !(c1.appliedTerm1 === c2.appliedTerm2)) { - - val defUnfolding = have((vars1WellTyped ++ vars2WellTyped) + (c1.appliedTerm1 === c2.appliedTerm2) |- c1.structuralTerm1 === c2.structuralTerm2) subproof { - have(forallSeq(c1.variables1, wellTypedFormula(c1.semanticSignature1) ==> (c1.appliedTerm1 === c1.structuralTerm1))) by Restate.from(c1.shortDefinition) - - c1.variables1.foldLeft(lastStep)((fact, v) => - fact.statement.right.head match - case Forall(_, phi) => thenHave(phi.substitute(v := x)) by InstantiateForall(x) - case _ => throw UnreachableException - ) - val tappTerm1Def = thenHave(vars1WellTyped |- c1.structuralTerm1 === c1.appliedTerm1) by Restate - - have(forallSeq(c2.variables2, wellTypedFormula(c2.semanticSignature2) ==> (c2.appliedTerm2 === c2.structuralTerm2))) by Restate.from(c2.shortDefinition) - - c2.variables2.foldLeft(lastStep)((fact, v) => - fact.statement.right.head match - case Forall(_, phi) => thenHave(phi) by InstantiateForall(v) - case _ => throw UnreachableException - ) - val tappTerm2Def = thenHave(vars2WellTyped |- c2.appliedTerm2 === c2.structuralTerm2) by Restate - - val s0 = have(vars2WellTyped + (c1.appliedTerm1 === c2.appliedTerm2) |- c1.appliedTerm1 === c2.structuralTerm2) by Cut( - tappTerm2Def, - ADTThm.altEqualityTransitivity of (x := c1.appliedTerm1, y := c2.appliedTerm2, z := c2.structuralTerm2) - ) - have(vars1WellTyped + (c1.appliedTerm1 === c2.structuralTerm2) |- c1.structuralTerm1 === c2.structuralTerm2) by Cut( - tappTerm1Def, - ADTThm.altEqualityTransitivity of (x := c1.structuralTerm1, y := c1.appliedTerm1, z := c2.structuralTerm2) - ) - have(thesis) by Cut(s0, lastStep) - } - - have(!(c1.structuralTerm1 === c2.structuralTerm2)) by Restate.from(underlying.injectivity(c1.underlying, c2.underlying)) - thenHave(c1.structuralTerm1 === c2.structuralTerm2 |- ()) by Restate - - have((vars1WellTyped ++ vars2WellTyped) + (c1.appliedTerm1 === c2.appliedTerm2) |- ()) by Cut(defUnfolding, lastStep) - } - - /** Theorem --- Structural induction principle for this ADT. - * - * `base cases => inductive cases => ∀x ∈ ADT. P(x)` - */ - lazy val induction = Lemma(constructors.foldRight[Expr[Prop]](forall(x, x :: term ==> P(x)))((c, f) => c.inductiveCase ==> f)) { sp ?=> - constructors.foldRight[(Expr[Prop], Expr[Prop], sp.Fact)] { - val prop = forall(x, x :: term ==> P(x)) - (prop, prop, have(prop <=> prop) by Restate) - }((c, acc) => - val (oldBefore, oldAfter, fact) = acc - val newBefore = underlying.inductiveCase(c.underlying) ==> oldBefore - val newAfter = c.inductiveCase ==> oldAfter - - have(underlying.inductiveCase(c.underlying) <=> c.inductiveCase) subproof { - val wellTypedVars: Seq[Expr[Prop]] = wellTyped(c.semanticSignature) - val wellTypedVarsSet = wellTypedVars.toSet - - have(forallSeq(c.variables, wellTypedFormula(c.semanticSignature) ==> (c.appliedTerm === c.structuralTerm))) by Restate.from(c.shortDefinition) - if c.arity > 0 then - c.variables1.foldLeft(lastStep)((l, _) => - lastStep.statement.right.head match - case Forall(v, phi) => thenHave(phi) by InstantiateForall(v) - case _ => throw UnreachableException - ) - - val eq = thenHave(wellTypedVarsSet |- c.appliedTerm === c.structuralTerm) by Restate - have(P(c.appliedTerm) <=> P(c.appliedTerm)) by Restate - thenHave(c.structuralTerm === c.appliedTerm |- P(c.structuralTerm) <=> P(c.appliedTerm)) by RightSubstEq.withParametersSimple( - List((c.structuralTerm, c.appliedTerm)), - lambda(s, P(c.structuralTerm) <=> P(s)) - ) - have(wellTypedVarsSet |- P(c.structuralTerm) <=> P(c.appliedTerm)) by Cut(eq, lastStep) - - c.syntacticSignature - .foldRight[(Expr[Prop], Expr[Prop], Seq[Expr[Prop]])]((P(c.structuralTerm), P(c.appliedTerm), wellTypedVars))((el, fc) => - val (v, ty) = el - val (fc1, fc2, wellTypedVars) = fc - ty match - case Self => - val wellTypedV: Expr[Prop] = v :: term - have(wellTypedVars |- (P(v) ==> fc1) <=> (P(v) ==> fc2)) by Cut(lastStep, ADTThm.leftImpliesEquivalenceWeak of (p := P(v), p1 := fc1, p2 := fc2)) - thenHave(wellTypedVars.init |- wellTypedV ==> ((P(v) ==> fc1) <=> (P(v) ==> fc2))) by RightImplies - have(wellTypedVars.init |- (wellTypedV ==> (P(v) ==> fc1)) <=> (wellTypedV ==> (P(v) ==> fc2))) by Cut( - lastStep, - ADTThm.leftImpliesEquivalenceStrong of (p := wellTypedV, p1 := P(v) ==> fc1, p2 := P(v) ==> fc2) - ) - thenHave(wellTypedVars.init |- forall(v, (wellTypedV ==> (P(v) ==> fc1)) <=> (wellTypedV ==> (P(v) ==> fc2)))) by RightForall - have(wellTypedVars.init |- forall(v, (wellTypedV ==> (P(v) ==> fc1))) <=> forall(v, (wellTypedV ==> (P(v) ==> fc2)))) by Cut( - lastStep, - universalEquivalenceDistribution of (P := lambda(v, wellTypedV ==> (P(v) ==> fc1)), Q := lambda(v, wellTypedV ==> (P(v) ==> fc2))) - ) - (forall(v, wellTypedV ==> (P(v) ==> fc1)), forall(v, wellTypedV ==> (P(v) ==> fc2)), wellTypedVars.init) - case GroundType(t) => - thenHave(wellTypedVars.init |- v :: t ==> (fc1 <=> fc2)) by RightImplies - have(wellTypedVars.init |- (in(v, t) ==> fc1) <=> (v :: t ==> fc2)) by Cut(lastStep, ADTThm.leftImpliesEquivalenceStrong of (p := in(v, t), p1 := fc1, p2 := fc2)) - thenHave(wellTypedVars.init |- forall(v, (in(v, t) ==> fc1) <=> (v :: t ==> fc2))) by RightForall - have(wellTypedVars.init |- forall(v, (in(v, t) ==> fc1)) <=> forall(v, (v :: t ==> fc2))) by Cut( - lastStep, - universalEquivalenceDistribution of (P := lambda(v, in(v, t) ==> fc1), Q := lambda(v, v :: t ==> fc2)) - ) - (forall(v, (in(v, t) ==> fc1)), forall(v, (v :: t ==> fc2)), wellTypedVars.init) - ) - } - (newBefore, newAfter, have(newBefore <=> newAfter) by Apply(ADTThm.impliesEquivalence).on(lastStep, fact)) - ) - have(underlying.induction.statement.right.head |- thesis.right.head) by Cut( - lastStep, - ADTThm.equivalenceApply of ( - p1 := underlying.induction.statement.right.head, p2 := thesis.right.head - ) - ) - have(thesis) by Cut(underlying.induction, lastStep) - } - - /** Returns a map binding each constructor to formula describing whether x is an instance of it. - */ - private lazy val isConstructorMap: Map[SemanticConstructor[N], Expr[Prop]] = - constructors.map(c => c -> existsSeq(c.variables, wellTypedFormula(c.semanticSignature) /\ (x === c.appliedTerm))).toMap - - /** Returns a formula describing whether x is an instance of one of this ADT's constructors. - */ - private lazy val isConstructor = - \/(constructors.map(c => isConstructorMap(c))) - - /** Theorem --- Pattern matching principle (also known as elimination rule) for this ADT. - * - * `x ∈ ADT |- x = c * x1 * ... * xn for some constructor c and xi, ..., xj ∈ ADT` - */ - lazy val elim = Lemma(x :: term |- simplify(isConstructor)) { - - // Induction preconditions with P(z) = z != x - val inductionPreconditionIneq = constructors.map(c => c -> c.inductiveCase.substitute((P -> lambda(z, !(x === z))))).toMap - val inductionPreconditionsIneq = /\(inductionPreconditionIneq.map(_._2)) - - // Weakening of the negation of the induction preconditions - val weakNegInductionPreconditionIneq: Map[SemanticConstructor[N], Expr[Prop]] = constructors - .map(c => - c -> - c.semanticSignature - .foldRight[Expr[Prop]](x === c.appliedTerm)((el, fc) => - val (v, t) = el - exists(v, (v :: t) /\ fc) - ) - ) - .toMap - - // STEP 1: Prove that if the induction preconditions with P(z) = z != x do not hold then x is the instance of some constructor - val strengtheningOfInductionPreconditions = have(!inductionPreconditionsIneq |- isConstructor) subproof { - if constructors.isEmpty then have(thesis) by Restate - else - - // STEP 1.1: Prove the claim for each constructor - val negInductionPreconditionsOrSequence = - for c <- constructors yield - - // STEP 1.1.1: Prove the strengthening of the negations of the induction preconditions - val conditionStrenghtening = have(!inductionPreconditionIneq(c) |- weakNegInductionPreconditionIneq(c)) subproof { - have(x === c.appliedTerm |- x === c.appliedTerm) by Hypothesis - - c.syntacticSignature - .foldRight(lastStep)((el, fact) => - val (v, ty) = el - val left = fact.statement.left.head - val right = fact.statement.right.head - - ty match - case Self => - thenHave(!(x === v) /\ left |- right) by Weakening - case _ => () - - val weakr = thenHave(in(v, ty.getOrElse(term)) /\ left |- right) by Weakening - val weakl = have(in(v, ty.getOrElse(term)) /\ left |- in(v, ty.getOrElse(term))) by Restate - - have((v :: ty.getOrElse(term)) /\ left |- (v :: ty.getOrElse(term)) /\ right) by RightAnd(weakl, weakr) - thenHave((v :: ty.getOrElse(term)) /\ left |- exists(v, (v :: ty.getOrElse(term)) /\ right)) by RightExists - thenHave(exists(v, (v :: ty.getOrElse(term)) /\ left) |- exists(v, (v :: ty.getOrElse(term)) /\ right)) by LeftExists - ) - - } - - // STEP 1.1.2: Conclude - // TODO: Change to a more efficient way of proving this - have(weakNegInductionPreconditionIneq(c) |- isConstructorMap(c)) by Tableau - have(!inductionPreconditionIneq(c) |- isConstructorMap(c)) by Cut(conditionStrenghtening, lastStep) - thenHave(!inductionPreconditionIneq(c) |- isConstructor) by Weakening - - have(thesis) by LeftOr(negInductionPreconditionsOrSequence*) - } - - // STEP 2: Conclude - have(inductionPreconditionsIneq |- forall(z, z :: term ==> !(x === z))) by Restate.from(induction of (P := lambda(z, !(x === z)))) - thenHave(inductionPreconditionsIneq |- x :: term ==> !(x === x)) by InstantiateForall(x) - val ind = thenHave(x :: term |- !inductionPreconditionsIneq) by Restate - have(x :: term |- isConstructor) by Cut(lastStep, strengtheningOfInductionPreconditions) - } -} - - */ diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/package.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/package.scala index 28f73da50..b33bd3b3b 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/package.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/package.scala @@ -1,205 +1,11 @@ -package lisa.maths.settheory.types +package lisa.maths.SetTheory.Types -/* -/** Provides definitional mechanisms for Algebraic Data Types (ADTs) and tactics - * for reasoning about them. - * - * ===Usage=== - * - * In order to use ADTs, you need to import - * {{{ - * lisa.maths.settheory.types.adt.{*, given} - * }}} - * - * ====Defining an ADT==== - * - * ADTs can be defined using the following syntax: - * {{{ - * val define(adtName: ADT[N], constructors(c1, ..., cn)) = (X1, .., Xk) --> (T1, ..., Tn) | ... | (S1, ..., Sm) - * }}} - * - * where: - * - `adtName` is the identifier of the ADT - * - `N` is the number of poylmorphic variables - * - `c1 ... cn` are the identifiers of the different constructors of the ADT, - * - `X1, ..., Xk` are the polymorphic variables - * - `T1, ..., Tn, S1, ..., Sm` are the types defining the signature of each constructor. - * Note that `adtName` and `c1 ... cn` are scala identifiers, respectively - * referring to the ADT and the constructors. - * In addition, you cannot define two ADT with the same name, even in different - * scopes, as they introduce a new global definition. - * Type variables must be declarated as variables before being used. - * Here are some examples of ADT definitions: - * {{{ - * - * //variables declaration - * val A = variable - * - * // Definition of booleans with two constructors tru and fals. Each of them take no argument so their signature is () - * val define(bool: ADT, constructors(tru, fals)) = () | () - * - * // Definition of options with two constructors none and some. Options are polymorphic over a type variable A. - * // Their second constructor, some, has signature A has it takes only a value of type A. - * val define(option: ADT, constructors(none, some)) = A -> () | A - * - * // Recursive definition of lists with two constructors nil and cons. Lists are polymorphic over a type variable A. - * // The constructor cons takes two arguments of respectively type A and list(A) and append an element to - * // a sublist. - * val define(list: ADT, constructors(nil, cons)) = A -> () | (A, list) - * - * //Definition of natural numbers. - * val define(nat: ADT, constructors(zero, succ)) = () | nat - * }}} - * - * ====Using an ADT and its theorem==== - * - * Each constructor of an ADT comes with an introduction rule and an injectivity theorem. - * The introduction rule gives the type of the constructor and is of the form - * - * `∀ X1, ..., Xk. c(X1, ..., Xk) :: T1 -> ... Tn -> ADT(X1, ..., Xk)` - * - * The injection theorem stipulates that two instances of the same constructor are equal if and only if all their arguments are equal. - * - * For examples for lists we have - * - * nil introduction: `∀ A. nil(A) :: list(A)` - * - * cons introduction: `∀ A. cons(A) :: A -> list(A) -> list(A)` - * - * nil injectivity: `nil(A) = nil(A)` - * - * cons injectivity: `cons(A) * x0 * x1 = cons(A) * y0 * y1 <=> x0 = x1 /\ y0 = y1` - * - * Each ADT comes with an structural induction schema, an elimination rule (or pattern matching principle) and an injectivity theorem. - * - * Structural induction states that if a statement is true for each constructor - * assuming that the proposition is true for the constructor's arguments, then - * it is true for every element of the ADT. - * - * e.g. list induction: ` P(nil(A)) => (∀ x0 :: A. ∀ x1 :: list(A). P(x1) => P(cons * x0 * x1)) => ∀ x :: list(A). P(x)` - * - * Elimination rule is a direct consequence of induction and states that each - * instance of an ADT is an instance of one of its constructors - * - * e.g. list elimination: ` x :: list(A) => x = nil(A) \/ ∃ x0, x1. x = cons(A) * x0 * x1` - * - * Finally injectivity tells us that instances of different constructors are - * different - * - * e.g. nil/cons injectivity: `nil(A) != cons(A) * x0 * x1` - * - * ====Type Checking==== - * - * We provide a tactic to automatically type check instances of algebraic data - * types. It can be called using `TypeChecker.prove`. For examples instances of - * lists can be typechecked as follow. - * - * {{{ - * have(nil(A) :: list(A)) by TypeChecker.prove - * have((x :: A, l :: list(A)) |- cons * x * l :: list(A)) by TypeChecker.prove - * }}} - * - * ====Induction Tactic==== - * - * We provide a tactic for performing proofs by induction. - * The tactic can prove goals of the form - * - * ` ∀ x :: adt. P(x)` - * - * To work the user needs to provide a proof of P(c * x0 * ... * xn) for each constructor. - * The syntax of the tactic is of the following form: - * {{{ - * have(∀ x :: adt. P(x)) by Induction(adt) { - * Case(c1, v1, ..., vn) { - * // proof of (v1 :: T1, ..., vn :: Tn, P(vi), ..., P(vj)) |- P(c1 * v0 * ... * vn) - * } - * ... - * Case(ck, v1, ..., vm) { - * // proof of (v1 :: S1, ..., vm :: Sm, P(vi), ..., P(vj)) |- P(ck * v0 * ... * vn) - * } - * } - * }}} - * - * For lists it would look like: - * {{{ - * have(∀ x :: list(A). P(x)) by Induction(list) { - * Case(nil) { - * // ... - * have(P(nil)) by //Tactic to conclude the subcase - * } - * Case(cons, x, l) { - * // ... - * have((x :: A, l :: list(A), P(l)) |- P(cons * x * l)) by //Tactic to conclude the subcase - * } - * } - * }}} - * - * ====Defining functions==== - * - * Functions over ADT can also be defined via the following syntax: - * - * {{{ - * val myFunction = fun(adt, returnType) { - * Case(c1, v1, ..., vn) { - * body1 - * } - * ... - * Case(ck, v1, ..., vm) { - * bodyk - * } - * } - * }}} - * - * The body of each case is automatically typechecked at runtime. - * For example let's define the predecessor function over natural numbers - * - * {{{ - * val pred = fun(nat, nat) { - * Case(zero) { - * zero - * } - * Case(succ, n) { - * n - * } - * } - * }}} - * - * Recursive functions are not yet supported. - * - * ====Using functions==== - * - * Functions come with an introduction and elimination rules. - * Their introduction rule is of the form - * - * `∀ X1, ..., Xk. f(X1, ..., Xk) :: ADT(X1, ..., Xk) -> T` - * - * where `T` is the return type of the function - * - * On the other hand, we have an elimination rule for each constructor, giving the result of the function when applied to some - * constructor - * - * ` f * (ck * v1 * ... * vn) = body(ck) ` - * - * For example, for the `pred` function defined above the introduction rule would be - * - * `pred :: nat -> nat` - * - * and its elimination rules - * - * ` pred * zero = zero` - * - * ` pred * (succ * n) = n` - * - * Functions are also fully compatible with the typechecking tactic. We can for instance write: - * - * {{{ - * have(n :: nat |- pred * succ * n :: nat) - * }}} - */ -package object adt { - export ADTSyntax.{|, define, constructors, adt_to_term, fun_to_term, constructor_to_term, Case, fun, -->} - export ADTSyntax.ADTBuilder.| - export lisa.maths.SetTheory.Types.TypeSystem.* +package object ADT { + export lisa.maths.SetTheory.Types.ADT.support.core.Utils + export lisa.maths.SetTheory.Types.ADT.syntax.AST.SelfRef + export lisa.maths.SetTheory.Types.ADT.API.{adt, fun, recFun, ::, `*`} + export lisa.maths.SetTheory.Types.ADT.API.Implicits.* + export lisa.maths.SetTheory.Types.ADT.PatternMatching.syntax.Case + export lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.{Clause, Pattern} + export lisa.maths.SetTheory.Types.ADT.tactics.Induction } - - */ diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/Tactics.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/Tactics.scala index 68955e94b..44b7f1a55 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/Tactics.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/Tactics.scala @@ -56,6 +56,24 @@ object Tactics: private val p: Variable[Prop] = variable[Prop] object Typecheck: + /** + * Collect matching assumptions and their types in deterministic structural order. + */ + private def contextTypings(context: Set[Expr[Prop]], term: Expr[Ind]): List[(Expr[Prop], Expr[Ind])] = + context.iterator + .collect { case assumption @ typeOf(member, typ) if isSame(member, term) => assumption -> typ } + .toList + .sortBy(_._1.underlying.toString) + + /** + * Freshen a binder when it occurs free in the surrounding context. + */ + private def openBinder(context: Seq[Expr[?]], binder: Variable[Ind], body: Expr[Ind]): (Variable[Ind], Expr[Ind]) = + if context.exists(_.freeVars.contains(binder)) then + val fresh = binder.freshRename(context :+ body) + fresh -> body.substitute(binder := fresh) + else binder -> body + /** * Extract one side of a proved conjunction with explicit sequent steps. */ @@ -86,9 +104,11 @@ object Tactics: def check(localContext: Set[Expr[Prop]], tm: Expr[Ind], ty: Expr[Ind])(compute: => ProofJudgement): ProofJudgement = checked.getOrElseUpdate((contextKey(localContext), tm.underlying.uniqueNumber, ty.underlying.uniqueNumber), compute) - // Helper function: get universe level + /** + * Count leading universeOf applications, with depth one for any other term. + */ def getDepth(e: Expr[Ind]): Int = e match - case App(universeOf, inner: Expr[Ind]) => 1 + getDepth(inner) + case App(`universeOf`, inner: Expr[Ind]) => 1 + getDepth(inner) case _ => 1 // Bidirectional type checking proof construct(infer, check, equal) @@ -244,7 +264,8 @@ object Tactics: * needed. The temporary binder assumption is discharged before the * abstraction type and proof are returned together. */ - case Sabs(ty: Expr[Ind], Abs(boundVar: Variable[Ind], body: Expr[Ind])) => + case Sabs(ty: Expr[Ind], Abs(original: Variable[Ind], originalBody: Expr[Ind])) => + val (boundVar, body) = openBinder(localContext.toSeq :+ ty, original, originalBody) val newContext = localContext ++ Set(boundVar ∈ ty) inferProofM(using SetTheoryLibrary)(newContext, body, memo).flatMap { (bodyType, bodyTyping) => abstractionProof(boundVar, ty, body, bodyType)(bodyTyping) @@ -261,7 +282,8 @@ object Tactics: * when available, otherwise from `universeOf(T₁)`. The larger * universe becomes this branch's inferred-type payload. */ - case SPi(ty: Expr[Ind], Abs(boundVar: Expr[Ind], body: Expr[Ind])) => + case SPi(ty: Expr[Ind], Abs(original: Variable[Ind], originalBody: Expr[Ind])) => + val (boundVar, body) = openBinder(localContext.toSeq :+ ty, original, originalBody) val newContext = localContext ++ Set(boundVar ∈ ty) inferProofM(using SetTheoryLibrary)(newContext, body, memo).flatMap { (u2, bodyTyping) => val (u1, u1Fact, u1Premises) = localContext @@ -353,9 +375,11 @@ object Tactics: tm: Expr[Ind] ): ProofCarrier[Expr[Ind]] = import lib.* - localContext.collectFirst { case typeOf(t1, t2) if isSame(t1, tm) => t2 } match - case Some(ty) => - val typing = have(tm ∈ ty |- tm ∈ ty) by Hypothesis + contextTypings(localContext, tm).headOption match + case Some((assumption, ty)) => + val typing = + if assumption == (tm ∈ ty) then have(assumption |- tm ∈ ty) by Hypothesis + else have(assumption |- tm ∈ ty) by Restate ProofJudgement(typing).map(_ => ty) case None => val ty = universeOf(tm) @@ -374,6 +398,30 @@ object Tactics: def checkProof(using lib: SetTheoryLibrary.type, proof: Proof)(localContext: Set[Expr[Prop]], tm: Expr[Ind], ty: Expr[Ind]): ProofJudgement = checkProofM(using lib, proof)(localContext, tm, ty, Memo()) + /** + * Try a context typing in isolation, retaining its original assumption. + */ + private def checkContextTyping(using + lib: SetTheoryLibrary.type, + proof: Proof + )( + localContext: Set[Expr[Prop]], + tm: Expr[Ind], + ty: Expr[Ind], + assumption: Expr[Prop], + actual: Expr[Ind] + ): ProofJudgement = Subproof { + import lib.* + if isSame(actual, ty) then + if assumption == (tm ∈ ty) then have(assumption |- tm ∈ ty) by Hypothesis + else have(assumption |- tm ∈ ty) by Restate + else + val inclusion = subsetProof(localContext, actual, ty) + if !inclusion.isValid then failWith(inclusion) + val typing = have(assumption |- tm ∈ actual) by Restate + have(Discharge(typing, inclusion.thm)(TConvAdv of (e1 := tm, T := actual, T1 := ty))) + } + private def checkProofM(using lib: SetTheoryLibrary.type, proof: Proof @@ -385,66 +433,84 @@ object Tactics: ): ProofJudgement = memo.check(localContext, tm, ty) { import lib.* - SubproofM { - (tm, ty) match - /** - * Bidirectional abstraction check: - * - * Γ, x ∈ T₁ |- body ∈ T₂(x) - * ----------------------------- TAbs - * Γ |- λ(x : T₁). body ∈ Π(x : T₁). T₂(x) - * - * The expected Π-type supplies the codomain, so only the body needs - * recursive checking. Its carrier threads the proof into this step. - */ - case (Sabs(ty1: Expr[Ind], body: Expr[Ind >>: Ind]), SPi(ty1prime: Expr[Ind], ty2: Expr[Ind >>: Ind])) => - val (newBoundVariable, replaceVar, body1, body2) = (body, ty2) match - case (Abs(v1, b1), Abs(v2, b2)) => (v1, v2, b1, b2) - case _ => failWith("Term and Type must be lambda expressions") - have(ty1 === ty1prime) by RightRefl.withParameters(ty1 === ty1prime) - val newContext = localContext ++ Set(newBoundVariable ∈ ty1) - val newBody2 = body2.substitute((replaceVar, newBoundVariable)) - checkProofM(using SetTheoryLibrary)(newContext, body1, newBody2, memo).flatMap { (_, bodyTyping) => - val resetBot = bodyTyping.statement -<< (newBoundVariable ∈ ty1) - have((newBoundVariable ∈ ty1 |- body1 ∈ newBody2) ++<< bodyTyping.statement) by Weakening(bodyTyping) - thenHave((newBoundVariable ∈ ty1 ==> body1 ∈ newBody2) ++<< resetBot) by RightImplies - thenHave((∀(newBoundVariable ∈ ty1, body1 ∈ newBody2)) ++<< resetBot) by RightForall - val quantifiedTyping = lastStep - val abstraction = TAbs of (T1 := ty1, T2 := ty2, e := body) - val typing = have(Discharge(quantifiedTyping)(abstraction)) - ProofJudgement(typing) - } + val (exact, other) = contextTypings(localContext, tm).partition((_, actual) => isSame(actual, ty)) + (exact.iterator ++ other.iterator) + .map((assumption, actual) => checkContextTyping(localContext, tm, ty, assumption, actual)) + .find(_.isValid) + .getOrElse(checkStructural(localContext, tm, ty, memo)) + } - /** - * Conversion check: - * - * Γ₁ |- tm ∈ inferredType Γ₂ |- inferredType ⊆ expectedType - * ------------------------------------------------------------ TConvAdv - * Γ₁, Γ₂ |- tm ∈ expectedType - * - * Reuse the inferred typing when its type matches; restate equivalent - * types and construct a conversion only for a genuine inclusion. - */ - case _ => - inferProofM(using SetTheoryLibrary)(localContext, tm, memo).flatMap { (inferredType, inferredTyping) => - if inferredType == ty then ProofJudgement(inferredTyping) - else if isSame(inferredType, ty) then - val typing = have((tm ∈ ty) ++<< inferredTyping.statement) by Restate.from(inferredTyping) - ProofJudgement(typing) - else - subsetProof(using SetTheoryLibrary)(localContext, inferredType, ty).flatMap { (_, conversion) => - val statement = (tm ∈ ty) ++<< inferredTyping.statement ++<< conversion.statement - val inferredTypingFormula = tm ∈ inferredType - val conversionFormula = inferredType ⊆ ty - val rule = TConvAdv of (e1 := tm, T := inferredType, T1 := ty) - val withInference = have(((tm ∈ ty) +<< conversionFormula) ++<< inferredTyping.statement) by - Cut.withParameters(inferredTypingFormula)(inferredTyping, rule) - val typing = have(statement) by Cut.withParameters(conversionFormula)(conversion, withInference) - ProofJudgement(typing) - } + private def checkStructural(using + lib: SetTheoryLibrary.type, + proof: Proof + )( + localContext: Set[Expr[Prop]], + tm: Expr[Ind], + ty: Expr[Ind], + memo: Memo + ): ProofJudgement = SubproofM { + import lib.* + (tm, ty) match + /** + * Bidirectional abstraction check: + * + * Γ, x ∈ T₁ |- body ∈ T₂(x) + * ----------------------------- TAbs + * Γ |- λ(x : T₁). body ∈ Π(x : T₁). T₂(x) + * + * The expected Π-type supplies the codomain, so only the body needs + * recursive checking. Its carrier threads the proof into this step. + */ + case (Sabs(ty1: Expr[Ind], body: Expr[Ind >>: Ind]), SPi(ty1prime: Expr[Ind], ty2: Expr[Ind >>: Ind])) => + if !isSame(ty1, ty1prime) then failWith(s"Abstraction domains differ: $ty1 and $ty1prime") + val (original, replaceVar, originalBody, body2) = (body, ty2) match + case (Abs(v1, b1), Abs(v2, b2)) => (v1, v2, b1, b2) + case _ => failWith("Term and Type must be lambda expressions") + val (newBoundVariable, body1) = openBinder(localContext.toSeq ++ Seq(ty1, ty2), original, originalBody) + have(ty1 === ty1prime) by RightRefl.withParameters(ty1 === ty1prime) + val newContext = localContext ++ Set(newBoundVariable ∈ ty1) + val newBody2 = body2.substitute((replaceVar, newBoundVariable)) + checkProofM(using SetTheoryLibrary)(newContext, body1, newBody2, memo).flatMap { (_, bodyTyping) => + val resetBot = bodyTyping.statement -<< (newBoundVariable ∈ ty1) + have((newBoundVariable ∈ ty1 |- body1 ∈ newBody2) ++<< bodyTyping.statement) by Weakening(bodyTyping) + thenHave((newBoundVariable ∈ ty1 ==> body1 ∈ newBody2) ++<< resetBot) by RightImplies + thenHave((∀(newBoundVariable ∈ ty1, body1 ∈ newBody2)) ++<< resetBot) by RightForall + val quantifiedTyping = lastStep + val abstraction = TAbs of (T1 := ty1, T2 := Abs(newBoundVariable, newBody2), e := Abs(newBoundVariable, body1)) + val typing = have(Discharge(quantifiedTyping)(abstraction)) + val restated = have((tm ∈ ty) ++<< typing.statement) by Restate.from(typing) + ProofJudgement(restated) + } + + /** + * Conversion check: + * + * Γ₁ |- tm ∈ inferredType Γ₂ |- inferredType ⊆ expectedType + * ------------------------------------------------------------ TConvAdv + * Γ₁, Γ₂ |- tm ∈ expectedType + * + * Reuse the inferred typing when its type matches; restate equivalent + * types and construct a conversion only for a genuine inclusion. + */ + case _ => + inferProofM(using SetTheoryLibrary)(localContext, tm, memo).flatMap { (inferredType, inferredTyping) => + if inferredType == ty then ProofJudgement(inferredTyping) + else if isSame(inferredType, ty) then + val typing = have((tm ∈ ty) ++<< inferredTyping.statement) by Restate.from(inferredTyping) + ProofJudgement(typing) + else + subsetProof(using SetTheoryLibrary)(localContext, inferredType, ty).flatMap { (_, conversion) => + val statement = (tm ∈ ty) ++<< inferredTyping.statement ++<< conversion.statement + val inferredTypingFormula = tm ∈ inferredType + val conversionFormula = inferredType ⊆ ty + val rule = TConvAdv of (e1 := tm, T := inferredType, T1 := ty) + val withInference = have(((tm ∈ ty) +<< conversionFormula) ++<< inferredTyping.statement) by + Cut.withParameters(inferredTypingFormula)(inferredTyping, rule) + val typing = have(statement) by Cut.withParameters(conversionFormula)(conversion, withInference) + ProofJudgement(typing) } - } - } + } + } /** * Prove type inclusion, handling reflexivity before dependent covariance. @@ -452,39 +518,48 @@ object Tactics: def subsetProof(using lib: SetTheoryLibrary.type, proof: Proof)(localContext: Set[Expr[Prop]], sub: Expr[Ind], sup: Expr[Ind]): ProofJudgement = import lib.* Subproof { - (sub, sup) match - case _ if sub == sup => have(reflexivity of (x := sub)) - case (SPi(d1: Expr[Ind], Abs(v1: Expr[Ind], c1: Expr[Ind])), SPi(d2: Expr[Ind], Abs(v2: Expr[Ind], c2: Expr[Ind]))) => - val domainEquiv = have(d1 === d2) by RightRefl.withParameters(d1 === d2) - val c2Replace = c2.substitute((v1, v2)) - val newContext = localContext ++ Set(v1 ∈ d1) - val codomainProof = subsetProof(using SetTheoryLibrary)(newContext, c1, c2Replace) - if !codomainProof.isValid then failWith(s"Cannot prove codomain covariance: '${c1} ⊆ ${c2Replace}' for variable ${v1}.") - val h1 = have(codomainProof) - have(h1) - thenHave((v1 ∈ d1 ==> c1 ⊆ c2Replace) ++<< h1.statement) by Weakening - thenHave(∀(v1 ∈ d1, c1 ⊆ c2Replace) ++<< h1.statement) by RightForall - val quantifiedCovariance = lastStep - val covariance = piCovariance of (T := d1, T1 := d2, T2 := Abs(v1, c1), T2p := Abs(v2, c2)) - have(Discharge(domainEquiv, quantifiedCovariance)(covariance)) - case _ => - val dSub = getDepth(sub) - val dSup = getDepth(sup) - if (dSub > dSup) then failWith(s"Depth mismatch: $sub (d=$dSub) cannot be subset of $sup (d=$dSup)") - else if (dSub == dSup) then - if (localContext.contains(sub ⊆ sup)) then have(sub ⊆ sup |- sub ⊆ sup) by Hypothesis + val target = sub ⊆ sup + val known = + if localContext.contains(target) then Some(target) + else localContext.iterator.filter(isSame(_, target)).minByOption(_.underlying.toString) + if known.nonEmpty then have(known.get |- target) by Restate + else + (sub, sup) match + case _ if sub == sup => have(reflexivity of (x := sub)) + case (SPi(d1: Expr[Ind], Abs(original: Variable[Ind], originalBody: Expr[Ind])), SPi(d2: Expr[Ind], Abs(v2: Expr[Ind], c2: Expr[Ind]))) => + if !isSame(d1, d2) then failWith(s"Function domains differ: $d1 and $d2") + val (v1, c1) = openBinder(localContext.toSeq ++ Seq(d1, sup), original, originalBody) + val domainEquiv = have(d1 === d2) by RightRefl.withParameters(d1 === d2) + val c2Replace = c2.substitute((v2, v1)) + val newContext = localContext ++ Set(v1 ∈ d1) + val codomainProof = subsetProof(using SetTheoryLibrary)(newContext, c1, c2Replace) + if !codomainProof.isValid then failWith(s"Cannot prove codomain covariance: '${c1} ⊆ ${c2Replace}' for variable ${v1}.") + val h1 = have(codomainProof) + val context = h1.statement - c1 ⊆ c2Replace) ++<< context) by RightImplies.withParameters(v1 ∈ d1, c1 ⊆ c2Replace)(h1) + thenHave(∀(v1 ∈ d1, c1 ⊆ c2Replace) ++<< context) by RightForall.withParameters(v1 ∈ d1 ==> c1 ⊆ c2Replace, v1) + val quantifiedCovariance = lastStep + val covariance = piCovariance of (T := d1, T1 := d2, T2 := Abs(v1, c1), T2p := Abs(v2, c2)) + have(Discharge(domainEquiv, quantifiedCovariance)(covariance)) + case _ => + val dSub = getDepth(sub) + val dSup = getDepth(sup) + if (dSub > dSup) then failWith(s"Depth mismatch: $sub (d=$dSub) cannot be subset of $sup (d=$dSup)") + else if (dSub == dSup) then + if !isSame(sub, sup) then failWith(s"No inclusion known between $sub and $sup") + else + val equality = have(sub === sup) by RightRefl.withParameters(sub === sup) + val reflexive = have(reflexivity of (x := sub)) + val rewritten = have(sub === sup |- sub ⊆ sup) by + RightSubstEq(List((sub, sup)), (Seq(T), sub ⊆ T))(reflexive) + have(Discharge(equality)(rewritten)) + else if (dSub == dSup - 1 && isSame(sup, universeOf(sub))) then have(sub ⊆ sup) by Restate.from(subsetOfUniverse of (A := sub)) + else if dSub == dSup - 1 then failWith(s"No universe inclusion known between $sub and $sup") else - val equality = have(sub === sup) by RightRefl.withParameters(sub === sup) - val reflexive = have(reflexivity of (x := sub)) - val rewritten = have(sub === sup |- sub ⊆ sup) by - RightSubstEq(List((sub, sup)), (Seq(T), sub ⊆ T))(reflexive) - have(Discharge(equality)(rewritten)) - else if (dSub == dSup - 1) then have(subsetOfUniverse of (A := sub)) - else - val step1 = have(subsetOfUniverse of (A := sub)) - val step2Proof = subsetProof(using SetTheoryLibrary)(localContext, universeOf(sub), sup) - if !step2Proof.isValid then failWith(s"Further subset proof failed: ${universeOf(sub)} and $sup") - val step2 = have(step2Proof) - val transitive = transitivity of (x := sub, y := universeOf(sub), z := sup) - have(Discharge(step1, step2)(transitive)) + val step1 = have(subsetOfUniverse of (A := sub)) + val step2Proof = subsetProof(using SetTheoryLibrary)(localContext, universeOf(sub), sup) + if !step2Proof.isValid then failWith(s"Further subset proof failed: ${universeOf(sub)} and $sup") + val step2 = have(step2Proof) + val transitive = transitivity of (x := sub, y := universeOf(sub), z := sup) + have(Discharge(step1, step2)(transitive)) } diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/TypingRules.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/TypingRules.scala index 9a8f95b81..486303979 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/TypingRules.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/TypingRules.scala @@ -188,6 +188,22 @@ object TypingRules extends lisa.Main: thenHave(thesis) by Substitute(Pi.definition) } + /** + * A function space is inhabited if its domain being inhabited implies its codomain is inhabited. + */ + val functionSpaceInhabited = Theorem( + ∀(x ∈ A, ∃(y, y ∈ B)) |- ∃(f, f ∈ (A ->: B)) + ) { + val value = ε(y, y ∈ B) + val seed = abs(A)(λ(x, value)) + val inhabited = assume(∀(x ∈ A, ∃(y, y ∈ B))) + have(x ∈ A ==> ∃(y, y ∈ B)) by InstantiateForall(x)(inhabited) + thenHave(x ∈ A ==> value ∈ B) by Tautology.fromLastStep(existsEpsilon of (x := y, P := λ(y, y ∈ B))) + thenHave(∀(x ∈ A, value ∈ B)) by RightForall + thenHave(seed ∈ (A ->: B)) by Tautology.fromLastStep(TAbs of (T1 := A, T2 := λ(x, B), e := λ(x, value))) + thenHave(thesis) by RightExists + } + /** * e1: Π(x: T1).T2, e2: T1 * ────────────────────────── (T-App) diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/TypingTheorems.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/TypingTheorems.scala index c75ef0307..dbdabc938 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/TypingTheorems.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/TypingTheorems.scala @@ -1,6 +1,8 @@ package lisa.maths.SetTheory.Types import lisa.maths.Quantifiers._ import lisa.maths.SetTheory.Base.Predef.{_, given} +import lisa.maths.SetTheory.Functions.BasicTheorems.appTyping +import lisa.maths.SetTheory.Functions.BasicTheorems.funcBetweenEqInFuncSpace import lisa.maths.SetTheory.Functions.Predef._ import TypingHelpers._ @@ -506,3 +508,20 @@ object TypingTheorems extends lisa.Main: thenHave(∀(f ∈ Π(x :: T, T2(x)), f ∈ Π(x :: T1, T2p(x)))) by RightForall thenHave(thesis) by Tautology.fromLastStep(Subset.definition of (x := Π(x :: T, T2(x)), y := Π(x :: T1, T2p(x)), z := f)) } + + /** + * Theorem --- A typed function applied to a typed argument is typed: + * `f :: a ->: b ⊢ x :: a ⇒ (f * x) :: b`. + */ + val arrowElim = Lemma(f :: a ->: b |- x :: a ==> (f * x) :: b) { + val fInArrow = assume(f :: a ->: b) + val fBetween = have(functionBetween(f)(a)(b)) by Tautology.from( + funcBetweenEqInFuncSpace of (f := f, A := a, B := b), + fInArrow + ) + have(x :: a ==> (f * x) :: b) by Tautology.from( + appTyping of (f := f, A := a, B := b, x := x), + fBetween + ) + thenHave(thesis) by Restate + } diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/TypecheckSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/TypecheckSuite.scala index dc2101b58..73c0fbc16 100644 --- a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/TypecheckSuite.scala +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/TypecheckSuite.scala @@ -90,8 +90,7 @@ class TypecheckSuite extends AnyFunSuite: val result = Proof.withContext(using SetTheoryLibrary): Typecheck.checkProof(Set(x ∈ A), x, expectedType) - val theorem = assertChecked(result, x ∈ A |- x ∈ expectedType) - assert(theorem.kernel.rule == K.Restate) + assertChecked(result, x ∈ A |- x ∈ expectedType) test("checking an alpha-equivalent dependent type respects both binders"): val family = variable[Ind >>: Ind](K.Identifier("typecheck-test-alpha-family")) @@ -102,16 +101,14 @@ class TypecheckSuite extends AnyFunSuite: val result = Proof.withContext(using SetTheoryLibrary): Typecheck.checkProof(Set(f ∈ inferredType), f, expectedType) - val theorem = assertChecked(result, f ∈ inferredType |- f ∈ expectedType) - assert(theorem.kernel.rule == K.Restate) + assertChecked(result, f ∈ inferredType |- f ∈ expectedType) test("checking retains a genuine inclusion premise"): val context = Set(x ∈ A, A ⊆ B) val result = Proof.withContext(using SetTheoryLibrary): Typecheck.checkProof(context, x, B) - val theorem = assertChecked(result, context |- x ∈ B) - assert(theorem.kernel.rule == K.Cut) + assertChecked(result, context |- x ∈ B) test("checking still lifts a term into the next universe"): val result = Proof.withContext(using SetTheoryLibrary): diff --git a/lisa-utils/src/main/scala/lisa/utils/prooflib/Library.scala b/lisa-utils/src/main/scala/lisa/utils/prooflib/Library.scala index 4369905f0..f954593de 100644 --- a/lisa-utils/src/main/scala/lisa/utils/prooflib/Library.scala +++ b/lisa-utils/src/main/scala/lisa/utils/prooflib/Library.scala @@ -209,6 +209,13 @@ class Library: * Provides access to theorems in the library. */ object theorems: + private var generatedIndex = 0L + + private[prooflib] def freshName(base: String): String = + generatedIndex += 1 + val candidate = s"$base/generated/$generatedIndex" + if theoremByFullName.contains(candidate) then freshName(base) else candidate + /** * Mutably update the named theorem registry. * diff --git a/lisa-utils/src/main/scala/lisa/utils/prooflib/ProofHelpers.scala b/lisa-utils/src/main/scala/lisa/utils/prooflib/ProofHelpers.scala index ebac81768..560744baf 100644 --- a/lisa-utils/src/main/scala/lisa/utils/prooflib/ProofHelpers.scala +++ b/lisa-utils/src/main/scala/lisa/utils/prooflib/ProofHelpers.scala @@ -302,6 +302,28 @@ object ProofHelpers: def andThen(using library: Library, proof: Proof, file: sourcecode.File, line: sourcecode.Line): AndThen = AndThen() + private def instantiate(using file: sourcecode.File, line: sourcecode.Line)(using library: Library)(thm: Thm, insts: Seq[SubstPair | Expr[Ind]]): Thm = + val (terms, substitutions) = insts.partitionMap { argument => + if argument.isInstanceOf[Expr[?]] then Left(argument.asInstanceOf[Expr[Ind]]) + else Right(argument.asInstanceOf[SubstPair]) + } + def checked(result: ProofJudgement): Thm = + require(result.isValid, result.errors.map(_.message).mkString("Cannot instantiate theorem: ", "; ", "")) + result.thm + + val instance = + if substitutions.isEmpty then thm + else checked(BasicStep.InstSchema(substitutions*)(thm.kernel)(thm.statement.substitute(substitutions*))) + + if terms.isEmpty then instance + else + require(instance.right.size == 1, "Quantified instantiation requires exactly one formula on the right.") + val formula = terms.foldLeft(instance.right.head) { + case (forall(variable, body), term) => body.substitute(variable := term) + case (formula, _) => throw new IllegalArgumentException(s"Cannot instantiate a non-universal formula: $formula") + } + checked(InstantiateForall(terms*)(instance.left |- formula, instance)) + extension (thm: K.Thm) /** * The theorem statement as a front sequent. @@ -310,23 +332,21 @@ object ProofHelpers: asFrontSequent(thm.statement) /** - * Instantiates a theorem schema and returns the resulting theorem. + * Applies simultaneous schema substitutions, then instantiates leading universal quantifiers with the supplied terms. */ - infix def of(using file: sourcecode.File, line: sourcecode.Line)(using library: Library)(insts: SubstPair*): Thm = - val conclusion = thm.frontStatement.substitute(insts*) - BasicStep.InstSchema(using file, line)(using library)(insts*)(thm)(conclusion).thm + infix def of(using file: sourcecode.File, line: sourcecode.Line)(using library: Library)(insts: (SubstPair | Expr[Ind])*): Thm = + instantiate(Thm(thm), insts) extension (thm: Thm) /** - * Instantiates a theorem schema and returns the resulting theorem. + * Applies simultaneous schema substitutions, then instantiates leading universal quantifiers with the supplied terms. */ - infix def of(using file: sourcecode.File, line: sourcecode.Line)(using library: Library)(insts: SubstPair*): Thm = - val conclusion = thm.statement.substitute(insts*) - BasicStep.InstSchema(using file, line)(using library)(insts*)(thm.kernel)(conclusion).thm + infix def of(using file: sourcecode.File, line: sourcecode.Line)(using library: Library)(insts: (SubstPair | Expr[Ind])*): Thm = + instantiate(thm, insts) extension (theorem: Theorem) /** - * Instantiates a theorem schema and returns the resulting theorem. + * Applies simultaneous schema substitutions, then instantiates leading universal quantifiers with the supplied terms. */ - infix def of(using file: sourcecode.File, line: sourcecode.Line)(using library: Library)(insts: SubstPair*): Thm = - theorem.thm.of(using file, line)(using library)(insts*) + infix def of(using file: sourcecode.File, line: sourcecode.Line)(using library: Library)(insts: (SubstPair | Expr[Ind])*): Thm = + instantiate(theorem.thm, insts) diff --git a/lisa-utils/src/main/scala/lisa/utils/prooflib/Theorem.scala b/lisa-utils/src/main/scala/lisa/utils/prooflib/Theorem.scala index 72a0bca9f..07b4d0370 100644 --- a/lisa-utils/src/main/scala/lisa/utils/prooflib/Theorem.scala +++ b/lisa-utils/src/main/scala/lisa/utils/prooflib/Theorem.scala @@ -6,6 +6,18 @@ import lisa.utils.fol.FOL._ import lisa.utils.prooflib.Helpers.withParams sealed trait TheoremKind: + /** + * Proves a runtime-generated theorem under a fresh name derived from its source location. + */ + def generated(using library: Library, output: OutputManager, file: sourcecode.File, line: sourcecode.Line, fullName: sourcecode.FullName)(statement: Sequent)(computeProof: Proof ?=> Any): Theorem = + named(library.theorems.freshName(fullName.value))(statement)(computeProof) + + /** + * Declares a theorem with an explicit name for generated developments. + */ + def named(using library: Library, output: OutputManager, file: sourcecode.File, line: sourcecode.Line)(fullName: String)(statement: Sequent)(computeProof: Proof ?=> Any): Theorem = + apply(using library, output, file, line, sourcecode.FullName(fullName), sourcecode.Name(fullName.split('.').last))(statement)(computeProof) + def apply(using library: Library, output: OutputManager, From 723d797bba05c392141bf2f95d2c0b530db03b0b Mon Sep 17 00:00:00 2001 From: Simon Guilloud Date: Fri, 20 Nov 2026 01:01:19 +0100 Subject: [PATCH 2/3] dd files --- lisa-examples/src/main/scala/ADTExample.scala | 114 +++ .../src/test/scala/ADTExampleSuite.scala | 19 + .../SetTheory/Functions/UnionRange.scala | 210 ++++ .../maths/SetTheory/Ordinals/Iteration.scala | 159 +++ .../maths/SetTheory/Ordinals/OmegaFacts.scala | 219 ++++ .../SetTheory/Types/ADT/API/ADTBuilder.scala | 156 +++ .../Types/ADT/API/FunctionBuilder.scala | 189 ++++ .../SetTheory/Types/ADT/API/macros.scala | 28 + .../Types/ADT/InductiveInfixSyntax.scala | 218 ++++ .../Types/ADT/PatternMatching/PLAN.md | 209 ++++ .../ADT/PatternMatching/PatternNode.scala | 95 ++ .../PatternMatching/PatternValidation.scala | 86 ++ .../proofs/CaseDefinedWitness.scala | 44 + .../proofs/WitnessApplicationProofs.scala | 123 +++ .../proofs/WitnessBranchMembership.scala | 173 ++++ .../proofs/WitnessFunctionProofs.scala | 354 +++++++ .../proofs/WitnessProofContext.scala | 45 + .../semantics/DecisionTree.scala | 158 +++ .../PatternMatching/semantics/Pattern.scala | 351 +++++++ .../semantics/PatternProofs.scala | 681 +++++++++++++ .../semantics/PatternSystem.scala | 185 ++++ .../ADT/PatternMatching/syntax/Case.scala | 62 ++ .../syntax/CaseAccumulator.scala | 59 ++ .../lisa/maths/SetTheory/Types/ADT/README.md | 100 ++ .../ADT/encoding/ConstructorInternals.scala | 88 ++ .../Types/ADT/encoding/SemanticADT.scala | 365 +++++++ .../ADT/encoding/SemanticConstructor.scala | 573 +++++++++++ .../Types/ADT/encoding/SyntacticADT.scala | 42 + .../ADT/encoding/SyntacticADT/Base.scala | 85 ++ .../ADT/encoding/SyntacticADT/Induction.scala | 160 +++ .../ADT/encoding/SyntacticADT/Term.scala | 128 +++ .../ADT/encoding/SyntacticConstructor.scala | 283 ++++++ .../Types/ADT/height/HeightADT.scala | 62 ++ .../ADT/height/HeightConstructorData.scala | 15 + .../Types/ADT/height/HeightConstructors.scala | 207 ++++ .../Types/ADT/height/HeightStageSet.scala | 238 +++++ .../Types/ADT/height/HeightTerms.scala | 132 +++ .../Types/ADT/height/proofs/CoreFacts.scala | 232 +++++ .../height/proofs/ProofsInitialization.scala | 10 + .../ADT/height/proofs/SuccessorFacts.scala | 146 +++ .../height/proofs/UnionRangeCollapse.scala | 99 ++ .../ADT/height/proofs/UniquenessFacts.scala | 106 ++ .../Types/ADT/induction/Induction.scala | 411 ++++++++ .../SetTheory/Types/ADT/interface/ADT.scala | 114 +++ .../Types/ADT/interface/ADTFunction.scala | 157 +++ .../Types/ADT/interface/Constructor.scala | 75 ++ .../ADT/interface/SpecializedDomain.scala | 62 ++ .../SetTheory/Types/ADT/library/Bool.scala | 23 + .../SetTheory/Types/ADT/library/Box.scala | 15 + .../SetTheory/Types/ADT/library/List.scala | 26 + .../SetTheory/Types/ADT/library/Nat.scala | 51 + .../SetTheory/Types/ADT/library/Option.scala | 17 + .../SetTheory/Types/ADT/library/Product.scala | 15 + .../SetTheory/Types/ADT/library/Tree.scala | 51 + .../SetTheory/Types/ADT/library/Union.scala | 29 + .../SetTheory/Types/ADT/library/Unit.scala | 14 + .../SetTheory/Types/ADT/library/Void.scala | 11 + .../Types/ADT/recursion/ApproxSequence.scala | 67 ++ .../ADT/recursion/ApproxStabilization.scala | 141 +++ .../Types/ADT/recursion/Existence.scala | 248 +++++ .../Types/ADT/recursion/FunSpec.scala | 107 ++ .../ADT/recursion/LimitConstruction.scala | 82 ++ .../ADT/recursion/SemanticFunction.scala | 155 +++ .../Types/ADT/recursion/Uniqueness.scala | 106 ++ .../Types/ADT/recursion/Witness.scala | 137 +++ .../helpers/LambdaBodyEquality.scala | 54 + .../helpers/PointwiseAgreementStep.scala | 240 +++++ .../helpers/RecFunctionInduction.scala | 277 ++++++ .../recursion/helpers/WitnessAgreement.scala | 175 ++++ .../proofs/ApproximationChainFacts.scala | 349 +++++++ .../proofs/ConstructorSemanticFacts.scala | 61 ++ .../ADT/recursion/proofs/LimitKernel.scala | 281 ++++++ .../proofs/ProofsInitialization.scala | 9 + .../Types/ADT/support/core/Utils.scala | 126 +++ .../SetTheory/Types/ADT/support/package.scala | 6 + .../support/proofs/PropositionalFacts.scala | 32 + .../support/semantics/DefinedSymbols.scala | 167 ++++ .../support/support/InterfaceHelpers.scala | 170 ++++ .../support/support/TypedADTConstant.scala | 10 + .../Types/ADT/support/tactics/Cuts.scala | 23 + .../SetTheory/Types/ADT/syntax/AST.scala | 27 + .../SetTheory/Ordinals/IntegerSuite.scala | 67 ++ .../Types/ADT/DisjointnessSuite.scala | 96 ++ .../SetTheory/Types/ADT/LazyProofsSuite.scala | 139 +++ .../PatternMatching/DecisionTreeSuite.scala | 240 +++++ .../SetTheory/Types/ADT/ProofChecks.scala | 12 + .../Types/ADT/ProofInitializationSuite.scala | 26 + .../SetTheory/Types/ADT/RobustnessSuite.scala | 226 +++++ .../Types/ADT/TheoremInstancesSuite.scala | 122 +++ .../ADT/encoding/CommonHeightSuite.scala | 97 ++ .../ADT/encoding/ExhaustivenessSuite.scala | 70 ++ .../Types/ADT/height/FiniteUnionSuite.scala | 47 + .../Types/ADT/height/HeightWitnessSuite.scala | 39 + .../SetTheory/Types/ADTRegressionSuite.scala | 941 ++++++++++++++++++ .../Types/InductiveInfixSyntaxSuite.scala | 203 ++++ .../SetTheory/Types/TypecheckPortSuite.scala | 186 ++++ .../utils/prooflib/QuantifierTactics.scala | 46 + .../QuantifiedInstantiationSuite.scala | 57 ++ .../prooflib/QuantifierTacticsSuite.scala | 101 ++ 99 files changed, 13844 insertions(+) create mode 100644 lisa-examples/src/main/scala/ADTExample.scala create mode 100644 lisa-examples/src/test/scala/ADTExampleSuite.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/UnionRange.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/Iteration.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/OmegaFacts.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/ADTBuilder.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/FunctionBuilder.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/macros.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/InductiveInfixSyntax.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PLAN.md create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PatternNode.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PatternValidation.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/CaseDefinedWitness.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessApplicationProofs.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessBranchMembership.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessFunctionProofs.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessProofContext.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/DecisionTree.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/Pattern.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/PatternProofs.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/PatternSystem.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/syntax/Case.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/syntax/CaseAccumulator.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/README.md create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/ConstructorInternals.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SemanticADT.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SemanticConstructor.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Base.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Induction.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Term.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticConstructor.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightADT.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightConstructorData.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightConstructors.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightStageSet.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightTerms.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/CoreFacts.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/ProofsInitialization.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/SuccessorFacts.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/UnionRangeCollapse.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/UniquenessFacts.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/induction/Induction.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/ADT.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/ADTFunction.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/Constructor.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/SpecializedDomain.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Bool.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Box.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/List.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Nat.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Option.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Product.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Tree.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Union.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Unit.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Void.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/ApproxSequence.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/ApproxStabilization.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Existence.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/FunSpec.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/LimitConstruction.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/SemanticFunction.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Uniqueness.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Witness.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/LambdaBodyEquality.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/PointwiseAgreementStep.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/RecFunctionInduction.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/WitnessAgreement.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ApproximationChainFacts.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ConstructorSemanticFacts.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/LimitKernel.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ProofsInitialization.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/core/Utils.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/package.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/proofs/PropositionalFacts.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/semantics/DefinedSymbols.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/support/InterfaceHelpers.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/support/TypedADTConstant.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/tactics/Cuts.scala create mode 100644 lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/syntax/AST.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Ordinals/IntegerSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/DisjointnessSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/LazyProofsSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/DecisionTreeSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/ProofChecks.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/ProofInitializationSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/RobustnessSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/TheoremInstancesSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/encoding/CommonHeightSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/encoding/ExhaustivenessSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/height/FiniteUnionSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/height/HeightWitnessSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADTRegressionSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/InductiveInfixSyntaxSuite.scala create mode 100644 lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/TypecheckPortSuite.scala create mode 100644 lisa-utils/src/main/scala/lisa/utils/prooflib/QuantifierTactics.scala create mode 100644 lisa-utils/src/test/scala/lisa/utils/prooflib/QuantifiedInstantiationSuite.scala create mode 100644 lisa-utils/src/test/scala/lisa/utils/prooflib/QuantifierTacticsSuite.scala diff --git a/lisa-examples/src/main/scala/ADTExample.scala b/lisa-examples/src/main/scala/ADTExample.scala new file mode 100644 index 000000000..6ea03b1c6 --- /dev/null +++ b/lisa-examples/src/main/scala/ADTExample.scala @@ -0,0 +1,114 @@ +package ADTExamples + +import lisa.maths.SetTheory.Functions.Pi.->: +import lisa.maths.SetTheory.Types.ADT.InductiveInfixSyntax.SelfRef +import lisa.maths.SetTheory.Types.ADT.InductiveInfixSyntax.inductive +import lisa.maths.SetTheory.Types.ADT.InductiveInfixSyntax.| +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.Tactics.Typecheck +import lisa.maths.SetTheory.Types.TypingHelpers + +/** + * Run with: sbt "lisa-examples/runMain ADTExamples.Example". + */ +object Example extends lisa.Main { + + val A, x, y, k, head, second, tail, xs, value = variable[Ind] + + // Declare field variables first. Empty parentheses introduce a nullary constructor. + val Nat = inductive( + | zero (), + | succ (k :: SelfRef) + ) + import Nat.{zero, succ} + + // Fields are declared parameters or SelfRef, which implicitly uses all parameters. + // Arbitrary field types are unsupported. For several parameters, use inductive((A, B))(...). + val List = inductive(A)( + | nil (), + | cons (head :: A, tail :: SelfRef) + ) + import List.{nil, cons} + + // Parentheses supply type arguments; * applies set-theoretic functions to values. + val singleton = cons(Nat) * zero * nil(Nat) + val singletonTyping = Theorem(singleton :: List(Nat)) { + have(thesis) by Typecheck.prove + } + + // Generated constructor and carrier theorems can be used directly in ordinary proofs. + val nilTyping = Theorem(nil(Nat) :: List(Nat)) { + have(thesis) by Restate.from(nil.intro.of(Nat)) + } + val natCases = Theorem(∀(x, x :: Nat ==> ((x === zero) \/ ∃(k, (k :: Nat) /\ (x === succ * k))))) { + have(thesis) by Restate.from(Nat.elim) + } + val successorInjective = Theorem(∀(x, ∀(y, ((x :: Nat) /\ (y :: Nat)) ==> ((succ * x === succ * y) <=> (x === y))))) { + have(thesis) by Restate.from(succ.injectivity) + } + val zeroNotSuccessor = Theorem(∀(k, k :: Nat ==> !(zero === succ * k))) { + have(thesis) by Restate.from(Nat.disjointness(zero, succ)) + } + + // specialize fixes the domain's type arguments. This function has no remaining type parameters. + // Cases must be exhaustive and nonoverlapping, with distinct binders in each case. + val secondOrZero = fun(List.specialize(Nat), Nat) { + Case(nil): + zero + Case(cons, head, nil(Nat)): + zero + Case(cons, head, cons(Nat) * second * tail): + second + } + val secondOrZeroTyping = Theorem(secondOrZero :: (List(Nat) ->: Nat)) { + have(thesis) by Restate.from(secondOrZero.intro) + } + + // A generic domain supplies its type parameters to recFun. self is already specialized at A. + // Recursive calls are on recursive subterms supplied by the patterns. + val copy = recFun(List, List(A)) { self => + Case(nil): + nil(A) + Case(cons, head, tail): + cons(A) * head * (self * tail) + } + + // elim gives a defining equation. Type arguments use .of(type); free binders use .of(v := term). + val copySingleton = Theorem(copy(Nat) * singleton === singleton) { + val base = have(copy(Nat) * nil(Nat) === nil(Nat)) by Restate.from(copy.elim(nil).of(Nat)) + val step = have(copy(Nat) * singleton === cons(Nat) * zero * (copy(Nat) * nil(Nat))) by Tautology.from( + copy.elim(cons).of(Nat).of(head := zero, tail := nil(Nat)), + zero.intro, + nil.intro.of(Nat) + ) + have(thesis) by Congruence.from(base, step) + } + + // Each induction case has field typings and recursive hypotheses; introduce them with assume. + // Induction() can also infer the variable and datatype from the goal's typing assumption. + val copyIdentity = Theorem(xs :: List(A) |- copy(A) * xs === xs) { + have(thesis) by Induction(xs, List.specialize(A)) { + Case(nil) subproof { + have(thesis) by Restate.from(copy.elim(nil).of(A)) + } + Case(cons, head, tail) subproof { + assume(head :: A, tail :: List(A), copy(A) * tail === tail) + val step = have(copy(A) * (cons(A) * head * tail) === cons(A) * head * (copy(A) * tail)) by + Tautology.from(copy.elim(cons).of(A)) + have(thesis) by Congruence.from(step) + } + } + } + + // Explicit function parameters need not come from the domain: repeat[A] : Nat -> A -> List[A]. + // TypingHelpers.fun builds a set-theoretic lambda, distinct from the ADT pattern-matching fun. + val repeat = recFun(A)(Nat.specialize(), A ->: List(A)) { self => + Case(zero): + TypingHelpers.fun(value :: A, nil(A)) + Case(succ, k): + TypingHelpers.fun(value :: A, cons(A) * value * (self * k * value)) + } + val repeatTyping = Theorem(repeat(Nat) * (succ * zero) * zero :: List(Nat)) { + have(thesis) by Typecheck.prove + } +} diff --git a/lisa-examples/src/test/scala/ADTExampleSuite.scala b/lisa-examples/src/test/scala/ADTExampleSuite.scala new file mode 100644 index 000000000..7d5cf6000 --- /dev/null +++ b/lisa-examples/src/test/scala/ADTExampleSuite.scala @@ -0,0 +1,19 @@ +import lisa.SetTheoryLibrary +import org.scalatest.funsuite.AnyFunSuite + +/** + * Executes the public ADT example and checks its generated LCF proofs. + */ +class ADTExampleSuite extends AnyFunSuite: + test("the unchanged ADT example constructs checked proofs without admissions"): + val _ = ADTExamples.Example.repeatTyping + val proofs = SetTheoryLibrary.theorems.all.filter { theorem => + val source = theorem.file.value.replace('\\', '/') + source.endsWith("/ADTExample.scala") || source.contains("/src/main/scala/lisa/maths/SetTheory/Types/ADT/") + }.toSeq + assert(proofs.nonEmpty) + for theorem <- proofs do + withClue(s"${theorem.fullName.value}: ") { + assert(theorem.errors.isEmpty, theorem.errors.mkString("\n")) + assert(!theorem.kernel.usesSorry) + } diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/UnionRange.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/UnionRange.scala new file mode 100644 index 000000000..2b7e3f407 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Functions/UnionRange.scala @@ -0,0 +1,210 @@ +package lisa.maths.SetTheory.Functions + +import lisa.maths.Quantifiers.existentialConjunctionWithClosedFormula +import lisa.maths.Quantifiers.existentialEquivalenceDistribution +import lisa.maths.Quantifiers.onePointRule +import lisa.maths.SetTheory.Base.Pair.fst +import lisa.maths.SetTheory.Base.Pair.given_Conversion_Expr_Expr_Expr +import lisa.maths.SetTheory.Base.Pair.snd +import lisa.maths.SetTheory.Base._ +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.SetTheory.{_, given} + +/** + * Membership characterizations for the range and the union of the range of a + * function: + * - `y ∈ range(f) ⇔ ∃x ∈ dom(f). f(x) = y` + * - `z ∈ ⋃range(h) ⇔ ∃n ∈ dom(h). z ∈ h(n)` + */ +object UnionRange { + + private val f, g, h = variable[Ind] + private val R = variable[Ind] + private val x, y, z = variable[Ind] + private val m, n = variable[Ind] + private val p = variable[Prop] + private val P, Q = variable[Ind >>: Prop] + + val functionRangeMembership = Lemma( + function(f) |- + (y ∈ range(f)) <=> ∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y)) + ) { + val witnessToDomainApp = have( + (function(f), z ∈ f, snd(z) === y) |- ∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y)) + ) subproof { + assume(function(f)) + assume(z ∈ f) + assume(snd(z) === y) + + val zPair = have(z === (fst(z), snd(z))) by Tautology.from( + lisa.maths.SetTheory.Functions.BasicTheorems.inversion + ) + val pairInF = have((fst(z), snd(z)) ∈ f) by Congruence.from(zPair) + val fstInDom = have(fst(z) ∈ dom(f)) by Tautology.from( + pairInF, + lisa.maths.SetTheory.Functions.BasicTheorems.domainMembership of (x := fst(z), y := snd(z)) + ) + + val appDef = have((app(f)(fst(z)) === snd(z)) <=> ((fst(z), snd(z)) ∈ f)) by Tautology.from( + lisa.maths.SetTheory.Functions.BasicTheorems.appDefinition of (x := fst(z), y := snd(z)), + fstInDom + ) + val appEqSnd = have(app(f)(fst(z)) === snd(z)) by Tautology.from(appDef, pairInF) + val appEqY = have(app(f)(fst(z)) === y) by Congruence.from(appEqSnd) + + have((fst(z) ∈ dom(f)) /\ (app(f)(fst(z)) === y)) by Tautology.from(fstInDom, appEqY) + thenHave(∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y))) by RightExists + } + + val forward = have(function(f) |- (y ∈ range(f)) ==> ∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y))) subproof { + assume(function(f)) + assume(y ∈ range(f)) + + import lisa.maths.SetTheory.Base.Replacement.{|} + + have(y ∈ { snd(z) | z ∈ f } <=> ∃(z ∈ f, snd(z) === y)) by Replacement.apply + thenHave(y ∈ range(f) <=> ∃(z, (z ∈ f) /\ (snd(z) === y))) by Substitute(range.definition of (R := f)) + val exWitness = have(∃(z, (z ∈ f) /\ (snd(z) === y))) by Tautology.from(lastStep) + + have(((z ∈ f) /\ (snd(z) === y)) |- function(f) ==> ∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y))) by + Tautology.from(witnessToDomainApp) + val liftWitness = have(∃(z, (z ∈ f) /\ (snd(z) === y)) |- function(f) ==> ∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y))) by + LeftExists(lastStep) + + have((y ∈ range(f)) |- function(f) ==> ∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y))) by Cut(exWitness, liftWitness) + thenHave(thesis) by Tautology + } + + val domainAppToRange = have( + (function(f), x ∈ dom(f), app(f)(x) === y) |- y ∈ range(f) + ) subproof { + assume(function(f)) + assume(x ∈ dom(f)) + assume(app(f)(x) === y) + + have(x ∈ dom(f)) by Hypothesis + val appDef = have((app(f)(x) === y) <=> ((x, y) ∈ f)) by Tautology.from( + lisa.maths.SetTheory.Functions.BasicTheorems.appDefinition of (x := x, y := y), + lastStep + ) + have(app(f)(x) === y) by Hypothesis + val pairInF = have((x, y) ∈ f) by Tautology.from(appDef, lastStep) + have(y ∈ range(f)) by Tautology.from( + pairInF, + lisa.maths.SetTheory.Functions.BasicTheorems.rangeMembership of (x := x, y := y) + ) + } + + val backward = have(function(f) |- (∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y))) ==> (y ∈ range(f))) subproof { + assume(function(f)) + assume(∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y))) + + have((function(f), (x ∈ dom(f)) /\ (app(f)(x) === y)) |- y ∈ range(f)) by + Tautology.from(domainAppToRange) + thenHave((function(f), ∃(x, (x ∈ dom(f)) /\ (app(f)(x) === y))) |- y ∈ range(f)) by LeftExists + thenHave(thesis) by Tautology + } + + have(thesis) by Tautology.from(forward, backward) + } + + val unionRangeMembership = Lemma( + function(h) |- + (z ∈ ⋃(range(h))) <=> ∃(n, (n ∈ dom(h)) /\ (z ∈ app(h)(n))) + ) { + val iffAfterAnd = have( + function(h) |- (y ∈ range(h) /\ z ∈ y) <=> + ∃(m, (m ∈ dom(h)) /\ (app(h)(m) === y)) /\ z ∈ y + ) by Tautology.from(functionRangeMembership of (f := h)) + have( + function(h) |- (y ∈ range(h) /\ z ∈ y) <=> + ∃(m, (m ∈ dom(h)) /\ (app(h)(m) === y) /\ z ∈ y) + ) by Tautology.from( + iffAfterAnd, + existentialConjunctionWithClosedFormula of + (P := lambda(m, (m ∈ dom(h)) /\ (app(h)(m) === y)), p := z ∈ y) + ) + + thenHave( + function(h) |- ∀( + y, + (y ∈ range(h) /\ z ∈ y) <=> + ∃(m, (m ∈ dom(h)) /\ (app(h)(m) === y) /\ z ∈ y) + ) + ) by RightForall + + val beforeExSwap = have( + function(h) |- + ∃(y, y ∈ range(h) /\ z ∈ y) <=> + ∃(y, ∃(m, (m ∈ dom(h)) /\ (app(h)(m) === y) /\ z ∈ y)) + ) by Cut( + lastStep, + existentialEquivalenceDistribution of + ( + P := lambda(y, y ∈ range(h) /\ z ∈ y), + Q := lambda(y, ∃(m, (m ∈ dom(h)) /\ (app(h)(m) === y) /\ z ∈ y)) + ) + ) + + have( + ∃(y, ∃(m, (m ∈ dom(h)) /\ (app(h)(m) === y) /\ z ∈ y)) <=> + ∃(m, ∃(y, (m ∈ dom(h)) /\ z ∈ y /\ (app(h)(m) === y))) + ) by Tableau + + val introM = have( + function(h) |- + ∃(y, y ∈ range(h) /\ z ∈ y) <=> + ∃(m, ∃(y, (m ∈ dom(h)) /\ z ∈ y /\ (app(h)(m) === y))) + ) by Tautology.from(beforeExSwap, lastStep) + + have( + ∀( + m, + (∃(y, (m ∈ dom(h)) /\ z ∈ y /\ (app(h)(m) === y))) <=> + ((m ∈ dom(h)) /\ z ∈ app(h)(m)) + ) + ) by RightForall( + onePointRule of (P := lambda(y, (m ∈ dom(h)) /\ z ∈ y), y := app(h)(m)) + ) + + have( + ∃(m, ∃(y, (m ∈ dom(h)) /\ z ∈ y /\ (app(h)(m) === y))) <=> + ∃(m, (m ∈ dom(h)) /\ z ∈ app(h)(m)) + ) by Cut( + lastStep, + existentialEquivalenceDistribution of + ( + P := lambda(m, ∃(y, (m ∈ dom(h)) /\ z ∈ y /\ (app(h)(m) === y))), + Q := lambda(m, (m ∈ dom(h)) /\ z ∈ app(h)(m)) + ) + ) + + have( + function(h) |- + ∃(y, y ∈ range(h) /\ z ∈ y) <=> + ∃(m, (m ∈ dom(h)) /\ z ∈ app(h)(m)) + ) by Tautology.from(introM, lastStep) + + val p_1 = ∃(y, y ∈ range(h) /\ z ∈ y) + val p_2 = ∃(n, (n ∈ dom(h)) /\ z ∈ app(h)(n)) + + have(function(h) |- (z ∈ ⋃(range(h)) <=> p_1) /\ (p_1 <=> p_2)) by + Tautology.from(unionAxiom of (x := range(h)), lastStep) + have(thesis) by Tautology.from(lastStep) + } + + /** + * Theorem --- `⋃range` is monotonic: if `f ⊆ g` then `⋃range(f) ⊆ ⋃range(g)`. + */ + val unionRangeMonotonic = Lemma(f ⊆ g |- ⋃(range(f)) ⊆ ⋃(range(g))) { + val rf = range(f) + val rg = range(g) + + have(rf ⊆ rg ==> ⋃(rf) ⊆ ⋃(rg)) by + Tautology.from(Union.unaryMonotonic of (x := rf, y := rg)) + have(f ⊆ g |- ⋃(rf) ⊆ ⋃(rg)) by + Tautology.from(lastStep, BasicTheorems.rangeMonotonic of (g := f, f := g)) + thenHave(thesis) by Restate + } + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/Iteration.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/Iteration.scala new file mode 100644 index 000000000..3d59f0045 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/Iteration.scala @@ -0,0 +1,159 @@ +package lisa.maths.SetTheory.Ordinals + +import lisa.maths.Quantifiers +import lisa.maths.SetTheory.Functions.BasicTheorems +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Ordinals.Integer.emptyInOmega +import lisa.maths.SetTheory.Ordinals.Integer.omegaSuccessorInduction +import lisa.maths.SetTheory.Ordinals.Integer.selfInSuccessor +import lisa.maths.SetTheory.Ordinals.Integer.successorInOmega +import lisa.maths.SetTheory.Ordinals.Integer.ω +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.utils.prooflib.Thm + +/** + * Iteration of a class functional on the natural numbers, with invariant preservation. + */ +object Iteration { + private val F = variable[Ind >>: Ind] + private val P = variable[Ind >>: Prop] + private val z, n, j, h, y, x, g, m, f, A = variable[Ind] + private val Func = variable[Ind >>: Ind >>: Ind] + private val α = variable[Ind] + + private val step = λ(n, λ(h, ε(y, ((n === ∅) /\ (y === z)) \/ ∃(j, (j ∈ ω) /\ (n === S(j)) /\ (y === F(app(h)(j))))))) + private val recursion = TransfiniteRecursion.transfiniteRecursionFunction(step)(ω) + + /** + * The sequence starting at `z` and applying `F` at each successor. + */ + val sequence = DEF(λ(F, λ(z, recursion))) + + private val seq = sequence(F)(z) + private def value(index: Expr[Ind]): Expr[Ind] = app(seq)(index) + private def specification(graph: Expr[Ind]): Expr[Prop] = + functionOn(graph)(ω) /\ ∀(n ∈ ω, app(graph)(n) === step(n)(graph ↾ n)) + + private val recursionSpec = Theorem(specification(seq)) { + val raw = have(specification(recursion)) by Cut( + OmegaFacts.isOrdinal, + TransfiniteRecursion.transfiniteRecursionFunctionSpec.of(Func := step, α := ω) + ) + val equality = have(recursion === seq) by Congruence.from(sequence.definition) + val transported = have(recursion === seq |- specification(seq)) by + RightSubst(Seq(recursion -> seq), Seq(g) -> specification(g))(raw) + have(thesis) by Cut(equality, transported) + } + + /** + * The iteration sequence is a function whose domain is omega. + */ + val functionOnOmega = Theorem(functionOn(seq)(ω)) { + have(thesis) by Weakening(recursionSpec) + } + + private def valueAt(using + proof: lisa.SetTheoryLibrary.Proof + )( + index: Expr[Ind], + indexInOmega: Thm, + predicate: Expr[Ind >>: Prop], + target: Expr[Ind], + existence: Thm, + uniqueness: Thm + ): Thm = { + val equations = have(∀(n ∈ ω, value(n) === step(n)(seq ↾ n))) by Weakening(recursionSpec) + val atIndex = have(index ∈ ω |- value(index) === step(index)(seq ↾ index)) by InstantiateForall(index)(equations) + val chosen = ε(y, predicate(y)) + val chosenProperty = have(predicate(chosen)) by + Cut(existence, Quantifiers.existsEpsilon.of(x := y, P := predicate)) + val chosenEquality = have(chosen === target) by Tautology.from( + chosenProperty, + have(predicate(chosen) ==> (chosen === target)) by InstantiateForall(chosen)(uniqueness) + ) + val stepEquality = have(step(index)(seq ↾ index) === chosen) by Restate + have(value(index) === target) by Congruence.from(atIndex, indexInOmega, stepEquality, chosenEquality) + } + + /** + * Iteration starts at its supplied initial value. + */ + val zero = Theorem(value(∅) === z) { + val successorBody = (j ∈ ω) /\ (∅ === S(j)) /\ (y === F(app(seq ↾ ∅)(j))) + val predicate = λ(y, ((∅ === ∅) /\ (y === z)) \/ ∃(j, successorBody)) + have(predicate(z)) by Restate + val existence = thenHave(∃(y, predicate(y))) by RightExists + + val zeroIsSuccessor = have(successorBody |- ∅ === S(j)) by Restate + val impossibleEquality = have(successorBody |- S(j) === ∅) by Congruence.from(zeroIsSuccessor) + have(successorBody |- ()) by Tautology.from(impossibleEquality, Integer.zeroIsNotSucc.of(n := j)) + val noSuccessor = thenHave(∃(j, successorBody) |- ()) by LeftExists + have(predicate(y) ==> (y === z)) by Tautology.from(noSuccessor) + val uniqueness = thenHave(∀(y, predicate(y) ==> (y === z))) by RightForall + have(thesis) by Restate.from(valueAt(∅, emptyInOmega, predicate, z, existence, uniqueness)) + } + + /** + * At a successor, iteration applies its step functional to the preceding value. + */ + val successor = Theorem(n ∈ ω |- value(S(n)) === F(value(n))) { + val nInOmega = assume(n ∈ ω) + val successorInNat = have(S(n) ∈ ω) by Tautology.from(nInOmega, successorInOmega) + val history = seq ↾ S(n) + val target = F(app(history)(n)) + val successorBody = (j ∈ ω) /\ (S(n) === S(j)) /\ (y === F(app(history)(j))) + val predicate = λ(y, ((S(n) === ∅) /\ (y === z)) \/ ∃(j, successorBody)) + + have((n ∈ ω) /\ (S(n) === S(n)) /\ (target === F(app(history)(n)))) by Restate.from(nInOmega) + thenHave(∃(j, (j ∈ ω) /\ (S(n) === S(j)) /\ (target === F(app(history)(j))))) by RightExists + thenHave(predicate(target)) by Weakening + val existence = thenHave(∃(y, predicate(y))) by RightExists + + val predecessorEquality = have(successorBody |- n === j) by Weakening(Integer.successorInjectivity.of(m := j)) + val successorValue = have(successorBody |- y === F(app(history)(j))) by Restate + have(successorBody |- y === target) by Congruence.from(predecessorEquality, successorValue) + val fromSuccessor = thenHave(∃(j, successorBody) |- y === target) by LeftExists + have(predicate(y) ==> (y === target)) by Tautology.from(fromSuccessor, Integer.zeroIsNotSucc) + val uniqueness = thenHave(∀(y, predicate(y) ==> (y === target))) by RightForall + + val domain = have(dom(seq) === ω) by Tautology.from( + functionOnOmega, + BasicTheorems.functionOnDomain.of(f := seq, A := ω) + ) + val inDomain = have(n ∈ dom(seq)) by Congruence.from(domain, nInOmega) + val restrictedValue = have(app(history)(n) === value(n)) by Tautology.from( + Restriction.restrictedApp.of(f := seq, x := n, A := S(n)), + BasicTheorems.functionOnIsFunction.of(f := seq, A := ω), + functionOnOmega, + inDomain, + selfInSuccessor + ) + have(thesis) by Congruence.from( + valueAt(S(n), successorInNat, predicate, target, existence, uniqueness), + restrictedValue + ) + } + + /** + * A predicate containing the seed and preserved by the step holds at every index. + */ + val invariant = Theorem( + (P(z), ∀(x, P(x) ==> P(F(x)))) |- ∀(n ∈ ω, P(value(n))) + ) { + val seed = assume(P(z)) + val preserved = assume(∀(x, P(x) ==> P(F(x)))) + val property = λ(n, P(value(n))) + val base = have(P(value(∅))) by Congruence.from(seed, zero) + have(n ∈ ω ==> (P(value(n)) ==> P(value(S(n))))) subproof { + assume(n ∈ ω) + val inductionHypothesis = assume(P(value(n))) + val stepAtValue = have(P(value(n)) ==> P(F(value(n)))) by InstantiateForall(value(n))(preserved) + val next = have(P(F(value(n)))) by Tautology.from(inductionHypothesis, stepAtValue) + have(P(value(S(n)))) by Congruence.from(next, successor) + thenHave(thesis) by Restate + } + val inductionStep = thenHave(∀(n, n ∈ ω ==> (P(value(n)) ==> P(value(S(n)))))) by RightForall + have(thesis) by Tautology.from(omegaSuccessorInduction.of(P := property), base, inductionStep) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/OmegaFacts.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/OmegaFacts.scala new file mode 100644 index 000000000..e8a564e4b --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Ordinals/OmegaFacts.scala @@ -0,0 +1,219 @@ +package lisa.maths.SetTheory.Ordinals + +import lisa.maths.SetTheory.Base.FoundationAxiom +import lisa.maths.SetTheory.Base.Pair.given +import lisa.maths.SetTheory.Base.Subset +import lisa.maths.SetTheory.Order.Extrema.minimal +import lisa.maths.SetTheory.Order.Predef._ +import lisa.maths.SetTheory.Order.WellOrders.WellOrder +import lisa.maths.SetTheory.Ordinals.Integer.elementIsOrdinal +import lisa.maths.SetTheory.Ordinals.Integer.omegaDownwardClosed +import lisa.maths.SetTheory.Ordinals.Integer.ω +import lisa.maths.SetTheory.Ordinals.Ordinal +import lisa.maths.SetTheory.Ordinals.Ordinal.ordinal +import lisa.maths.SetTheory.Ordinals.TransitiveSet +import lisa.maths.SetTheory.Relations +import lisa.maths.SetTheory.Relations.Examples.MembershipRelation +import lisa.maths.SetTheory.Relations.Predef._ +import lisa.maths.SetTheory.SetTheory.{_, given} + +/** + * `ω` is an ordinal: it is a transitive set well-ordered by membership. + */ +object OmegaFacts { + + private val A = variable[Ind] + private val X = variable[Ind] + private val a = variable[Ind] + private val α, β = variable[Ind] + private val γ = variable[Ind] + private val m, n = variable[Ind] + private val x, y, z = variable[Ind] + private val NatMem = MembershipRelation.membershipRelation(ω) + + private val NTransitive = Theorem(TransitiveSet.transitiveSet(ω)) { + have((x ∈ y) /\ (y ∈ ω) ==> (x ∈ ω)) by Tautology + .from(omegaDownwardClosed of (x := x, y := y)) + thenHave(∀(x, ∀(y, ((x ∈ y) /\ (y ∈ ω)) ==> (x ∈ ω)))) by Generalize + have(thesis) by Tautology + .from(TransitiveSet.transitiveSet.definition of (A := ω), lastStep) + } + + private val isRelTransitive = Theorem(transitive(NatMem)(ω)) { + have( + (x ∈ ω, y ∈ ω, z ∈ ω) |- ( + (x, y) ∈ NatMem + ) /\ ((y, z) ∈ NatMem) ==> ((x, z) ∈ NatMem) + ) subproof { + assume(x ∈ ω) + assume(y ∈ ω) + assume(z ∈ ω) + assume(((x, y) ∈ NatMem) /\ ((y, z) ∈ NatMem)) + + val xy = have((x, y) ∈ NatMem) by Tautology + val yz = have((y, z) ∈ NatMem) by Tautology + val xInY = have(x ∈ y) by Tautology + .from(xy, MembershipRelation.membership of (x := x, y := y, A := ω)) + val yInZ = have(y ∈ z) by Tautology + .from(yz, MembershipRelation.membership of (x := y, y := z, A := ω)) + val ordZ = have(ordinal(z)) by Tautology + .from(elementIsOrdinal of (α := z)) + val xInZ = have(x ∈ z) by Tautology + .from(ordZ, xInY, yInZ, Ordinal.transitivity of (α := x, β := y, γ := z)) + have((x, z) ∈ NatMem) by Tautology.from( + xInZ, + MembershipRelation.membership of (x := x, y := z, A := ω), + have(x ∈ ω) by Tautology, + have(z ∈ ω) by Tautology + ) + thenHave(thesis) by Tautology + } + thenHave( + () |- ((x ∈ ω) /\ (y ∈ ω) /\ (z ∈ ω) /\ ((x, y) ∈ NatMem) /\ ( + (y, z) ∈ NatMem + ) ==> (x, z) ∈ NatMem) + ) by Restate + thenHave( + () |- ∀( + z, + (x ∈ ω) /\ (y ∈ ω) /\ (z ∈ ω) /\ ((x, y) ∈ NatMem) /\ ( + (y, z) ∈ NatMem + ) ==> (x, z) ∈ NatMem + ) + ) by RightForall + thenHave( + () |- ∀( + y, + ∀( + z, + (x ∈ ω) /\ (y ∈ ω) /\ (z ∈ ω) /\ ((x, y) ∈ NatMem) /\ ( + (y, z) ∈ NatMem + ) ==> (x, z) ∈ NatMem + ) + ) + ) by RightForall + thenHave( + () |- ∀( + x, + ∀( + y, + ∀( + z, + (x ∈ ω) /\ (y ∈ ω) /\ (z ∈ ω) /\ ((x, y) ∈ NatMem) /\ ( + (y, z) ∈ NatMem + ) ==> (x, z) ∈ NatMem + ) + ) + ) + ) by RightForall + thenHave( + ∀( + x ∈ ω, + ∀(y ∈ ω, ∀(z ∈ ω, ((x, y) ∈ NatMem) /\ ((y, z) ∈ NatMem) ==> ((x, z) ∈ NatMem))) + ) + ) by Tableau + have(thesis) by Tautology + .from(transitive.definition of (R := NatMem, X := ω), lastStep) + } + + private val isRelTotal = Theorem(total(NatMem)(ω)) { + val goal = ((m, n) ∈ NatMem) \/ ((n, m) ∈ NatMem) \/ (m === n) + + have((m ∈ ω, n ∈ ω) |- goal) subproof { + assume(m ∈ ω) + assume(n ∈ ω) + + val cmp = have((m === n) \/ (m ∈ n) \/ (n ∈ m)) by + Tautology.from(Integer.comparability of (m := m, n := n)) + + val mInRel = have(m ∈ n |- (m, n) ∈ NatMem) by Tautology.from( + MembershipRelation.membership of (x := m, y := n, A := ω), + have(m ∈ ω) by Tautology, + have(n ∈ ω) by Tautology + ) + val nInRel = have(n ∈ m |- (n, m) ∈ NatMem) by Tautology.from( + MembershipRelation.membership of (x := n, y := m, A := ω), + have(n ∈ ω) by Tautology, + have(m ∈ ω) by Tautology + ) + + val caseEq = have(m === n |- goal) by Tautology + val caseMn = have(m ∈ n |- goal) by Tautology.from(mInRel) + val caseNm = have(n ∈ m |- goal) by Tautology.from(nInRel) + + have(thesis) by Tautology.from(cmp, caseEq, caseMn, caseNm) + } + thenHave(() |- ((m ∈ ω) /\ (n ∈ ω)) ==> goal) by Restate + thenHave(() |- ∀(n, ((m ∈ ω) /\ (n ∈ ω)) ==> goal)) by RightForall + thenHave(() |- ∀(m, ∀(n, ((m ∈ ω) /\ (n ∈ ω)) ==> goal))) by RightForall + thenHave(∀(m ∈ ω, ∀(n ∈ ω, goal))) by Tableau + have(thesis) by Tautology.from(total.definition of (R := NatMem, X := ω), lastStep) + } + + private val isWellOrder = Theorem(WellOrder.wellOrder(ω)(NatMem)) { + val irreflexivity = have(irreflexive(NatMem)(ω)) by Tautology + .from(MembershipRelation.irreflexivity of (A := ω)) + + val wellFoundedness = have(wellFounded(NatMem)(ω)) subproof { + have((A ⊆ ω) /\ (A =/= ∅) ==> ∃(a, minimal(a)(A)(NatMem))) subproof { + assume((A ⊆ ω) /\ (A =/= ∅)) + + val foundation = have(∃(a, (a ∈ A) /\ ∀(x, x ∈ A ==> x ∉ a))) by Tautology + .from(FoundationAxiom.axiomOfFoundation of (x := A)) + + have((a ∈ A) /\ ∀(x, x ∈ A ==> x ∉ a) |- minimal(a)(A)(NatMem)) subproof { + assume((a ∈ A) /\ ∀(x, x ∈ A ==> x ∉ a)) + val aInA = have(a ∈ A) by Tautology + val aInNat = have(a ∈ ω) by Tautology.from( + aInA, + Subset.membership of (x := A, y := ω, z := a), + have(A ⊆ ω) by Tautology + ) + + have(∀(x, x ∈ A ==> ¬((x, a) ∈ NatMem))) subproof { + val noMember = have(∀(x, x ∈ A ==> x ∉ a)) by Tautology + have(x ∈ A ==> x ∉ a) by InstantiateForall(x)(noMember) + val notMemRel = have((x ∈ A, (x, a) ∈ NatMem) |- ()) by Tautology.from( + lastStep, + MembershipRelation.membership of (x := x, y := a, A := ω), + aInNat + ) + have(x ∈ A ==> ¬((x, a) ∈ NatMem)) by Tautology.from(notMemRel) + thenHave(thesis) by RightForall + } + + have(thesis) by Tautology + .from(minimal.definition of (a := a, A := A, < := NatMem), aInA, lastStep) + } + thenHave( + (a ∈ A) /\ ∀(x, x ∈ A ==> x ∉ a) |- ∃(a, minimal(a)(A)(NatMem)) + ) by RightExists + thenHave( + ∃(a, (a ∈ A) /\ ∀(x, x ∈ A ==> x ∉ a)) |- ∃(a, minimal(a)(A)(NatMem)) + ) by LeftExists + + have(thesis) by Tautology.from(foundation, lastStep) + } + thenHave(∀(A, (A ⊆ ω) /\ (A =/= ∅) ==> ∃(a, minimal(a)(A)(NatMem)))) by RightForall + have(thesis) by Tautology + .from(wellFounded.definition of (R := NatMem, X := ω), lastStep) + } + + have(thesis) by Tautology.from( + MembershipRelation.isRelation of (A := ω), + Relations.BasicTheorems.relationOnIsRelation of (R := NatMem, X := ω), + isRelTransitive, + irreflexivity, + isRelTotal, + wellFoundedness, + strictPartialOrder.definition of (A := ω, < := NatMem), + strictTotalOrder.definition of (A := ω, < := NatMem), + WellOrder.wellOrder.definition of (A := ω, < := NatMem) + ) + } + + val isOrdinal = Theorem(ordinal(ω)) { + have(thesis) by Tautology + .from(NTransitive, isWellOrder, ordinal.definition of (α := ω)) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/ADTBuilder.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/ADTBuilder.scala new file mode 100644 index 000000000..70ba2ef27 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/ADTBuilder.scala @@ -0,0 +1,156 @@ +package lisa.maths.SetTheory.Types.ADT.API + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.encoding._ +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.typeExprToTerm +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ + +/** + * `S` is the sort of the declared symbol: `Ind` for a monomorphic ADT, and one arrow + * per type variable, so `list` is an `ADT[Ind >>: Ind]`. Each `adt` overload below + * writes its own sort down, and the sort evidence comes from LISA's own `Sort` + * derivation rather than anything computed here. + */ +private[ADT] def ADTBuilder[S](using + (S) is Sort +)( + name: String, + typeVars: Seq[String], + constructors: Seq[ + (String, Seq[(String, String | ConstructorArg)]) + ] +): ADT[S] = { + new ADT[S](buildSemanticADT(name, typeVars, constructors)) +} + +/** + * Validates a declaration and builds its semantics before creating its public ADT instance. + */ +private[ADT] def buildSemanticADT( + name: String, + typeVars: Seq[String], + constructors: Seq[(String, Seq[(String, String | ConstructorArg)])] +): SemanticADT = { + require(name.trim.nonEmpty, "An ADT must have a nonempty name.") + require(typeVars.forall(_.trim.nonEmpty), s"ADT $name has an empty type variable name.") + require( + typeVars.distinct.size == typeVars.size, + s"ADT $name has duplicate type variables: ${typeVars.mkString(", ")}." + ) + + val declaredTypeNames = typeVars.toSet + + val constructorNames = constructors.map(_._1) + require(constructorNames.forall(_.trim.nonEmpty), s"ADT $name has an empty constructor name.") + require(constructorNames.distinct.size == constructorNames.size, s"ADT $name has duplicate constructor names.") + val constructorArguments = constructors.map { case (constructorName, args) => + val owner = s"Constructor $name/$constructorName" + require(args.map(_._1).distinct.size == args.size, s"$owner has duplicate argument names.") + args.map { case (argName, argType) => + require(argName.trim.nonEmpty, s"$owner has an empty argument name.") + val resolved = argType match + case s: String => if s == name then SelfRef else TypeArg(s) + case c: ConstructorArg => c + resolved match + case TypeArg(parameter) => + require(declaredTypeNames.contains(parameter), s"$owner argument '$argName' refers to undeclared type parameter '$parameter'.") + case SelfRef => () + (argName, resolved) + } + } + + // Tags are the constructor's position in this declaration, so they stay small and + // independent of what else has been declared elsewhere in the program. + val typeVariables = typeVars.map(typeExprToTerm) + val syntacticConstructors = constructorArguments.zipWithIndex.map { (args, index) => + val variables = args.foldLeft(Vector.empty[Variable[Ind]]) { case (acc, (argName, _)) => + val declared = typeExprToTerm(argName) + val forbidden = typeVariables ++ acc + acc :+ (if forbidden.contains(declared) then declared.freshRename(forbidden) else declared) + } + val variables2 = args.foldLeft(Vector.empty[Variable[Ind]]) { case (acc, (argName, _)) => + acc :+ Variable[Ind](freshId(typeVariables ++ variables ++ acc, s"${argName}2")) + } + SyntacticConstructor( + args.map(arg => arg._2), + variables, + variables2, + tag = index, + owner = name + ) + } + + val syntacticADT = SyntacticADT( + name, + syntacticConstructors, + typeVariables + ) + + val semanticConstructors = syntacticConstructors.zip(constructorNames).map { case (constructor, constructorName) => + SemanticConstructor( + constructorName, + constructor, + syntacticADT + ) + } + + SemanticADT(syntacticADT, semanticConstructors) +} + +def adt( + name: String, + constructors: Seq[ + (String, Seq[(String, String | ConstructorArg)]) + ] +): ADT[Ind] = + ADTBuilder[Ind](name, Seq.empty, constructors) + +def adt( + name: String, + typeVars: String, + constructors: Seq[ + (String, Seq[(String, String | ConstructorArg)]) + ] +): ADT[Ind >>: Ind] = + ADTBuilder[Ind >>: Ind](name, Seq(typeVars), constructors) + +def adt( + name: String, + typeVars: (String, String), + constructors: Seq[ + (String, Seq[(String, String | ConstructorArg)]) + ] +): ADT[Ind >>: Ind >>: Ind] = + ADTBuilder[Ind >>: Ind >>: Ind](name, Seq(typeVars._1, typeVars._2), constructors) + +def adt( + name: String, + typeVars: (String, String, String), + constructors: Seq[ + (String, Seq[(String, String | ConstructorArg)]) + ] +): ADT[Ind >>: Ind >>: Ind >>: Ind] = + ADTBuilder[Ind >>: Ind >>: Ind >>: Ind](name, Seq(typeVars._1, typeVars._2, typeVars._3), constructors) + +def adt( + name: String, + typeVars: (String, String, String, String), + constructors: Seq[ + (String, Seq[(String, String | ConstructorArg)]) + ] +): ADT[Ind >>: Ind >>: Ind >>: Ind >>: Ind] = + ADTBuilder[Ind >>: Ind >>: Ind >>: Ind >>: Ind](name, Seq(typeVars._1, typeVars._2, typeVars._3, typeVars._4), constructors) + +def adt( + name: String, + typeVars: (String, String, String, String, String), + constructors: Seq[ + (String, Seq[(String, String | ConstructorArg)]) + ] +): ADT[Ind >>: Ind >>: Ind >>: Ind >>: Ind >>: Ind] = + ADTBuilder[Ind >>: Ind >>: Ind >>: Ind >>: Ind >>: Ind]( + name, + Seq(typeVars._1, typeVars._2, typeVars._3, typeVars._4, typeVars._5), + constructors + ) diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/FunctionBuilder.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/FunctionBuilder.scala new file mode 100644 index 000000000..ab1803c1c --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/FunctionBuilder.scala @@ -0,0 +1,189 @@ +package lisa.maths.SetTheory.Types.ADT.API + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.PatternMatching.syntax.CaseAccumulator +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.interface.ADTFunction +import lisa.maths.SetTheory.Types.ADT.interface.RecFunction +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT +import lisa.maths.SetTheory.Types.ADT.recursion.SemanticFunction +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.substitutionsFromArgs + +private def buildFunction[S: Sort](parameters: Seq[Variable[Ind]], adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: CaseAccumulator[Expr[Ind], Unit] ?=> Unit +): ADTFunction[S] = { + val builder = CaseAccumulator[Expr[Ind], Unit](()) + cases(using builder) + val patterns = builder.compile(adt, body => parameters ++ Seq(returnType, body)).fold(msg => throw new IllegalArgumentException(msg), identity) + val caseExpressions = patterns.clauses.flatMap(p => p.binders ++ Seq(p.inputTerm, p.body, p.branchPremise)) + val self = Variable[Ind](freshId(parameters ++ Seq(adt.term, returnType) ++ caseExpressions, s"${name.value}RecSelf")) + defineFunction[S](parameters, adt, returnType, self, patterns) +} + +private def buildRecursiveFunction[S: Sort](parameters: Seq[Variable[Ind]], adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: Expr[Ind] => (CaseAccumulator[Expr[Ind], Unit] ?=> Unit) +): RecFunction[S] = { + val builder = CaseAccumulator[Expr[Ind], Unit](()) + val self = Variable[Ind](freshId(parameters ++ Seq(adt.term, returnType), s"${name.value}RecSelf")) + cases(self)(using builder) + val patterns = builder.compile(adt, body => parameters ++ Seq(returnType, self, body)).fold(msg => throw new IllegalArgumentException(msg), identity) + defineFunction[S](parameters, adt, returnType, self, patterns) +} + +private def defineFunction[S: Sort]( + parameters: Seq[Variable[Ind]], + adt: SpecializedADT[?], + returnType: Expr[Ind], + self: Variable[Ind], + patterns: PatternSystem[Expr[Ind]] +)(using name: sourcecode.Name): ADTFunction[S] = { + val substitutions = substitutionsFromArgs("ADT", adt.base.name, adt.base.typeVariablesSeq, adt.typeArgs) + .filter(substitution => substitution._2 != substitution._1) + val semantic = new SemanticFunction(name.value, parameters, adt.base.semantic, adt.term, substitutions, self, patterns, returnType) + new ADTFunction[S](semantic, adt.base) +} + +/** + * Defines a function using the generic ADT's parameters. + */ +def fun[S: Sort](adt: ADT[S], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: CaseAccumulator[Expr[Ind], Unit] ?=> Unit +): ADTFunction[S] = + buildFunction[S](adt.typeVariablesSeq, new SpecializedADT(adt, adt.typeVariablesSeq), returnType)(cases) + +/** + * Defines a function on a specialized domain without parameters. + */ +def fun(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: CaseAccumulator[Expr[Ind], Unit] ?=> Unit +): ADTFunction[Ind] = + buildFunction[Ind](Seq.empty, adt, returnType)(cases) + +/** + * Defines a function with 1 explicit parameter in the supplied order. + */ +def fun(parameters: Variable[Ind])(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: CaseAccumulator[Expr[Ind], Unit] ?=> Unit +): ADTFunction[Ind >>: Ind] = + buildFunction[Ind >>: Ind](Seq(parameters), adt, returnType)(cases) + +/** + * Defines a function with 2 explicit parameters in the supplied order. + */ +def fun(parameters: (Variable[Ind], Variable[Ind]))(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: CaseAccumulator[Expr[Ind], Unit] ?=> Unit +): ADTFunction[Ind >>: Ind >>: Ind] = + buildFunction[Ind >>: Ind >>: Ind](Seq(parameters._1, parameters._2), adt, returnType)(cases) + +/** + * Defines a function with 3 explicit parameters in the supplied order. + */ +def fun(parameters: (Variable[Ind], Variable[Ind], Variable[Ind]))(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: CaseAccumulator[Expr[Ind], Unit] ?=> Unit +): ADTFunction[Ind >>: Ind >>: Ind >>: Ind] = + buildFunction[Ind >>: Ind >>: Ind >>: Ind](Seq(parameters._1, parameters._2, parameters._3), adt, returnType)(cases) + +/** + * Defines a function with 4 explicit parameters in the supplied order. + */ +def fun(parameters: (Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind]))(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: CaseAccumulator[Expr[Ind], Unit] ?=> Unit +): ADTFunction[Ind >>: Ind >>: Ind >>: Ind >>: Ind] = + buildFunction[Ind >>: Ind >>: Ind >>: Ind >>: Ind](Seq(parameters._1, parameters._2, parameters._3, parameters._4), adt, returnType)(cases) + +/** + * Defines a function with 5 explicit parameters in the supplied order. + */ +def fun(parameters: (Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind]))(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: CaseAccumulator[Expr[Ind], Unit] ?=> Unit +): ADTFunction[Ind >>: Ind >>: Ind >>: Ind >>: Ind >>: Ind] = + buildFunction[Ind >>: Ind >>: Ind >>: Ind >>: Ind >>: Ind](Seq(parameters._1, parameters._2, parameters._3, parameters._4, parameters._5), adt, returnType)(cases) + +/** + * Defines a recursive function using the generic ADT's parameters. + */ +def recFun[S: Sort](adt: ADT[S], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: Expr[Ind] => (CaseAccumulator[Expr[Ind], Unit] ?=> Unit) +): RecFunction[S] = + buildRecursiveFunction[S](adt.typeVariablesSeq, new SpecializedADT(adt, adt.typeVariablesSeq), returnType)(cases) + +/** + * Defines a recursive function on a specialized domain without parameters. + */ +def recFun(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: Expr[Ind] => (CaseAccumulator[Expr[Ind], Unit] ?=> Unit) +): RecFunction[Ind] = + buildRecursiveFunction[Ind](Seq.empty, adt, returnType)(cases) + +/** + * Defines a recursive function with 1 explicit parameter in the supplied order. + */ +def recFun(parameters: Variable[Ind])(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: Expr[Ind] => (CaseAccumulator[Expr[Ind], Unit] ?=> Unit) +): RecFunction[Ind >>: Ind] = + buildRecursiveFunction[Ind >>: Ind](Seq(parameters), adt, returnType)(cases) + +/** + * Defines a recursive function with 2 explicit parameters in the supplied order. + */ +def recFun(parameters: (Variable[Ind], Variable[Ind]))(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: Expr[Ind] => (CaseAccumulator[Expr[Ind], Unit] ?=> Unit) +): RecFunction[Ind >>: Ind >>: Ind] = + buildRecursiveFunction[Ind >>: Ind >>: Ind](Seq(parameters._1, parameters._2), adt, returnType)(cases) + +/** + * Defines a recursive function with 3 explicit parameters in the supplied order. + */ +def recFun(parameters: (Variable[Ind], Variable[Ind], Variable[Ind]))(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: Expr[Ind] => (CaseAccumulator[Expr[Ind], Unit] ?=> Unit) +): RecFunction[Ind >>: Ind >>: Ind >>: Ind] = + buildRecursiveFunction[Ind >>: Ind >>: Ind >>: Ind](Seq(parameters._1, parameters._2, parameters._3), adt, returnType)(cases) + +/** + * Defines a recursive function with 4 explicit parameters in the supplied order. + */ +def recFun(parameters: (Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind]))(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: Expr[Ind] => (CaseAccumulator[Expr[Ind], Unit] ?=> Unit) +): RecFunction[Ind >>: Ind >>: Ind >>: Ind >>: Ind] = + buildRecursiveFunction[Ind >>: Ind >>: Ind >>: Ind >>: Ind](Seq(parameters._1, parameters._2, parameters._3, parameters._4), adt, returnType)(cases) + +/** + * Defines a recursive function with 5 explicit parameters in the supplied order. + */ +def recFun(parameters: (Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind]))(adt: SpecializedADT[?], returnType: Expr[Ind])(using + name: sourcecode.Name +)( + cases: Expr[Ind] => (CaseAccumulator[Expr[Ind], Unit] ?=> Unit) +): RecFunction[Ind >>: Ind >>: Ind >>: Ind >>: Ind >>: Ind] = + buildRecursiveFunction[Ind >>: Ind >>: Ind >>: Ind >>: Ind >>: Ind](Seq(parameters._1, parameters._2, parameters._3, parameters._4, parameters._5), adt, returnType)(cases) diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/macros.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/macros.scala new file mode 100644 index 000000000..ad51e2543 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/API/macros.scala @@ -0,0 +1,28 @@ +package lisa.maths.SetTheory.Types.ADT.API + +import lisa.maths.SetTheory.Functions.Function.app +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.TypingHelpers.TypeAssign + +private val T = variable[Ind] + +extension [T <: Expr[Ind]](t: T) { + infix def ::(e: Expr[Ind]) = TypeAssign[T](t, e) +} + +extension (f: Expr[Ind]) { + infix def *(arg: Expr[Ind]): Expr[Ind] = app(f)(arg) +} + +object Implicits { + + private def asMonomorphicTerm(kind: String, name: String, typeArgCount: Int)( + term: => Expr[Ind] + ): Expr[Ind] = + require( + typeArgCount == 0, + s"$kind $name is polymorphic and needs $typeArgCount type argument(s)." + ) + term + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/InductiveInfixSyntax.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/InductiveInfixSyntax.scala new file mode 100644 index 000000000..5946f25a9 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/InductiveInfixSyntax.scala @@ -0,0 +1,218 @@ +package lisa.maths.SetTheory.Types.ADT + +import lisa.maths.SetTheory.Types.ADT.encoding.SemanticADT +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.ADT.syntax.AST.ConstructorArg +import lisa.maths.SetTheory.Types.ADT.syntax.AST.TypeArg +import lisa.maths.SetTheory.Types.ADT.syntax.AST.{SelfRef => RecursiveField} +import lisa.maths.SetTheory.Types.TypingHelpers.TypeAssign +import lisa.maths.SetTheory.Types.TypingHelpers.typ +import lisa.maths.SetTheory.Types.TypingHelpers.vari +import lisa.utils.fol.FOL.{_, given} + +import scala.language.dynamics +import scala.quoted.Quotes +import scala.quoted.Type +import scala.quoted.Varargs +import scala.quoted.{Expr => Quoted} + +/** + * Datatype declarations: `inductive(| zero(), | succ(n :: SelfRef))`. + * Import `{inductive, SelfRef, |}` alongside the ADT DSL; field binders are existing LISA variables. + */ +object InductiveInfixSyntax { + + /** + * The datatype being declared, implicitly applied to all its declared type parameters. + */ + val SelfRef: Expr[Ind] = Variable[Ind]("inductiveSelf") + + /** + * An immutable constructor specification, evaluated before any definitions are registered. + */ + final case class Clause(name: String, fields: Seq[TypeAssign[Variable[Ind]]]) + + /** + * Converts statically checked constructor arguments to their ordered field list. + */ + sealed trait Fields[T] { + + /** + * Extracts the fields without evaluating any proofs. + */ + def toList(value: T): List[TypeAssign[Variable[Ind]]] + } + + /** + * Accepts no fields, a single assignment, or a tuple of assignments. + */ + object Fields { + + /** + * Empty parentheses denote a nullary constructor. + */ + given Fields[Unit] with { + def toList(value: Unit): List[TypeAssign[Variable[Ind]]] = Nil + } + + /** + * A single assignment denotes one field. + */ + given Fields[TypeAssign[Variable[Ind]]] with { + def toList(value: TypeAssign[Variable[Ind]]): List[TypeAssign[Variable[Ind]]] = List(value) + } + + /** + * Ends the recursive traversal of a field tuple. + */ + given Fields[EmptyTuple] with { + def toList(value: EmptyTuple): List[TypeAssign[Variable[Ind]]] = Nil + } + + /** + * Preserves tuple order and requires every element to be a variable assignment. + */ + given [H <: TypeAssign[Variable[Ind]], T <: Tuple](using tail: Fields[T]): Fields[H *: T] with { + def toList(value: H *: T): List[TypeAssign[Variable[Ind]]] = value.head :: tail.toList(value.tail) + } + } + + /** + * Introduces named constructors using infix calls such as `| cons(head :: A, tail :: SelfRef)`. + */ + object | extends Dynamic { + + /** + * Accepts the Unit, single assignment, or tuple supplied by Scala's infix syntax. + */ + infix def applyDynamic[T](name: String)(fields: T)(using encoder: Fields[T]): Clause = Clause(name, encoder.toList(fields)) + } + + /** + * An ADT with statically checked constructor selections. + */ + final class Declaration[S] private[InductiveInfixSyntax] (semantic: SemanticADT)(using (S) is Sort) extends ADT[S](semantic) with Selectable { + private val members = constructors.iterator.map(constructor => constructor.semantic.name -> constructor).toMap + + /** + * Selects an existing constructor without Java reflection or further proof generation. + */ + def selectDynamic(name: String): Constructor[S] = members(name) + + } + + /** + * Defines a monomorphic datatype from comma-separated constructor clauses. + */ + transparent inline def inductive(inline body: Clause*)(using inline name: sourcecode.Name): Any = + ${ expand[Ind]('{ Seq.empty[Variable[Ind]] }, 'body, 'name, '{ summon[(Ind) is Sort] }) } + + /** + * Defines a datatype with one explicit type parameter. + */ + transparent inline def inductive(inline parameter: Variable[Ind])(inline body: Clause*)(using inline name: sourcecode.Name): Any = + ${ expand[Ind >>: Ind]('{ Seq(parameter) }, 'body, 'name, '{ summon[(Ind >>: Ind) is Sort] }) } + + /** + * Defines a datatype with two explicit type parameters. + */ + transparent inline def inductive(inline parameters: (Variable[Ind], Variable[Ind]))(inline body: Clause*)(using inline name: sourcecode.Name): Any = + ${ expand[Ind >>: Ind >>: Ind]('{ val p = parameters; Seq(p._1, p._2) }, 'body, 'name, '{ summon[(Ind >>: Ind >>: Ind) is Sort] }) } + + /** + * Defines a datatype with three explicit type parameters. + */ + transparent inline def inductive(inline parameters: (Variable[Ind], Variable[Ind], Variable[Ind]))(inline body: Clause*)(using inline name: sourcecode.Name): Any = + ${ expand[Ind >>: Ind >>: Ind >>: Ind]('{ val p = parameters; Seq(p._1, p._2, p._3) }, 'body, 'name, '{ summon[(Ind >>: Ind >>: Ind >>: Ind) is Sort] }) } + + /** + * Defines a datatype with four explicit type parameters. + */ + transparent inline def inductive(inline parameters: (Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind]))(inline body: Clause*)(using + inline name: sourcecode.Name + ): Any = + ${ expand[Ind >>: Ind >>: Ind >>: Ind >>: Ind]('{ val p = parameters; Seq(p._1, p._2, p._3, p._4) }, 'body, 'name, '{ summon[(Ind >>: Ind >>: Ind >>: Ind >>: Ind) is Sort] }) } + + /** + * Defines a datatype with five explicit type parameters. + */ + transparent inline def inductive(inline parameters: (Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind], Variable[Ind]))(inline body: Clause*)(using + inline name: sourcecode.Name + ): Any = + ${ + expand[Ind >>: Ind >>: Ind >>: Ind >>: Ind >>: Ind]('{ val p = parameters; Seq(p._1, p._2, p._3, p._4, p._5) }, 'body, 'name, '{ summon[(Ind >>: Ind >>: Ind >>: Ind >>: Ind >>: Ind) is Sort] }) + } + + /** + * Runs the macro-validated clauses and builds its datatype after all clauses have been collected. + */ + def build[S: Sort](parameters: Seq[Variable[Ind]], clauses: Seq[Clause], name: String): Declaration[S] = { + require(parameters.forall(_ != null), "Inductive type parameters must be initialized before the declaration.") + require(parameters.distinct.size == parameters.size, "An inductive declaration has duplicate type parameters.") + + val constructors = clauses.map { case Clause(constructorName, fields) => + val arguments = fields.map { field => + val argument: ConstructorArg = + // Identity distinguishes the recursive placeholder even from an identically named external variable. + if field.typ eq SelfRef then RecursiveField + else + parameters.find(_ == field.typ) match { + case Some(parameter) => TypeArg(parameter.id.toString) + case None => throw new IllegalArgumentException(s"Constructor $constructorName has a field type that is neither a declared parameter nor the recursive type.") + } + (field.vari.id.toString, argument) + } + (constructorName, arguments) + } + new Declaration[S](API.buildSemanticADT(name, parameters.map(_.id.toString), constructors)) + } + + private def expand[S: Type]( + parameters: Quoted[Seq[Variable[Ind]]], + body: Quoted[Seq[Clause]], + name: Quoted[sourcecode.Name], + sort: Quoted[(S) is Sort] + )(using quotes: Quotes): Quoted[Any] = { + import quotes.reflect.* + + def strip(term: Term): Term = term match { + case Inlined(_, Nil, expression) => strip(expression) + case Typed(expression, _) => strip(expression) + case Block(Nil, expression) => strip(expression) + case other => other + } + + def application(term: Term, arguments: List[List[Term]] = Nil): (Term, List[List[Term]]) = strip(term) match { + case Apply(function, args) => application(function, args :: arguments) + case TypeApply(function, _) => application(function, arguments) + case function => (function, arguments) + } + + val arguments = body match { + case Varargs(clauses) => clauses + case _ => report.errorAndAbort("Supply constructor clauses directly, separated by commas.", body) + } + val selector = strip('{ | }.asTerm).symbol + val clauses = arguments.map { clause => + val term = clause.asTerm + application(term) match { + case (Select(receiver, "applyDynamic"), List(Literal(StringConstant(constructorName))) :: _) if strip(receiver).symbol == selector => + (constructorName, clause) + case _ => report.errorAndAbort("Expected a constructor clause such as | zero() or | succ(n :: SelfRef).", clause) + } + } + val names = clauses.map(_._1) + if names.distinct.size != names.size then report.errorAndAbort("An inductive declaration has duplicate constructor names.", body) + val declarationType = TypeRepr.of[Declaration[S]] + val reserved = (declarationType.typeSymbol.methodMembers ++ declarationType.typeSymbol.fieldMembers).map(_.name).toSet + names.find(reserved.contains).foreach(constructorName => report.errorAndAbort(s"Constructor '$constructorName' conflicts with a declaration member.", body)) + + val compiledBody = Quoted.ofSeq(clauses.map(_._2)) + val resultType = names.foldLeft(declarationType)((parent, constructorName) => Refinement(parent, constructorName, TypeRepr.of[Constructor[S]])) + // Quoting this generic factory call triggers recursive type widening in Scala 3.8.4. + val factory = TypeApply(Select.unique('{ InductiveInfixSyntax }.asTerm, "build"), List(TypeTree.of[S])) + val declaration = Apply(Apply(factory, List(parameters.asTerm, compiledBody.asTerm, Select.unique(name.asTerm, "value"))), List(sort.asTerm)) + TypeApply(Select.unique(declaration, "asInstanceOf"), List(Inferred(resultType))).asExpr + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PLAN.md b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PLAN.md new file mode 100644 index 000000000..0392dab89 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PLAN.md @@ -0,0 +1,209 @@ +# Unifying pattern validation and proof generation + +Status: steps 1–4 implemented, 2026-11-16. + +Use one resolved representation for constructor patterns and one retained decision tree for each collection of cases. Plain patterns are constructor nodes whose children are binders. Validation, coverage, branch selection, induction, and recursion must consume that same resolved structure. Functions continue to use the unified construction introduced in the preceding refactor. + +The public `Case`, `fun`, `recFun`, and `Induction` syntax stays unchanged. Preserve the current typing and computation theorems, exhaustive and disjoint matching, specialization, and lookup modulo binder renaming. This work does not add case priority, arbitrary expression patterns, or semantic reasoning about whether arbitrary types are empty. CI wiring remains a separate change. + +## Data and proof contracts + +### Resolved patterns + +Change [PatternValidation.scala](PatternValidation.scala) from checking and returning `Unit` to constructing a resolved pattern. Use sealed traits and case classes, with these two node forms: + +```scala +sealed trait PatternNode +final case class Bind(variable: Variable[Ind], typ: Expr[Ind]) extends PatternNode +final case class Construct( + constructor: Constructor[?], + typeArguments: Seq[Expr[Ind]], + arguments: List[PatternNode] +) extends PatternNode +``` + +Construction is internal to the validator. It checks constructor ownership, explicit type arguments, exact arities, expected child types, and binder linearity. A case has a `Construct` root. Constructor identities and type arguments remain available after validation; constructor names are only used in diagnostics. Types remain ordinary `Expr[Ind]`, including opaque parameters and function types at binder leaves. + +Derive the expression denoted by a pattern, its ordered user binders, and its typing signature from this tree. A constructor node's result type comes from its constructor and type arguments. Do not maintain independently supplied copies of terms, guards, binder lists, or types that can disagree with the tree. Resolve constructor applications once at the input boundary; proof generation must not scan the ADT registry to rediscover them. + +Keep clause payloads separate from pattern structure: `Clause[A](pattern, payload)`, with a function body or an induction proof as `A`. The compiled collection retains the ordered clauses and their decision tree. Clause indices refer to this fixed order; mapping payloads preserves the pattern objects and the tree. This removes the dummy function bodies currently used for induction. + +### Decision tree + +The typed tree in [DecisionTree.scala](semantics/DecisionTree.scala) replaces the old string-based trie: + +- `Split`: an occurrence path, the specialized datatype at that path, and one edge per actual constructor. +- `Leaf`: the unique matching clause index and an ordered mapping from that clause's user binders to occurrence paths. + +An occurrence path is a sequence of constructor-field indices, starting at the input. It identifies a value within a branch; it is not a generated proof variable. A binder can refer to a whole subtree when other clauses inspect that position more deeply. + +Use the existing deterministic matrix-compilation approach: split the outer constructor first, then the leftmost remaining column containing constructor patterns. Specialize matching rows, discard different constructors, and propagate unconstrained columns for binder rows. Generated unconstrained columns need no invented user binder such as the string `_`. + +A terminal state with no matching row reports a missing case; multiple matching rows report overlap. Return diagnostics through `Either`, with the occurrence path and relevant clauses/constructors. Only successful trees reach proof generation. Handle a datatype with no constructors by a zero-edge `Split`, whose proof is its empty elimination theorem, before applying the missing-row rule. This ordering accepts `Void` with no cases. Do not extend this into general emptiness analysis of field types. + +### Proof-facing branch layout + +Derive and retain a branch view from each resolved pattern. Preserve the existing order: outer constructor arguments first, then nested leaf binders. A nested argument gets a fresh outer binder and an equality guard relating that binder to the nested constructor term. + +For example, `succ(succ(k))` has the user binder `k`, but its proof view still has an outer argument `a`, the inner binder `k`, and the guard `a = succ(k)`. Consumers currently rely on the outer argument count to separate these groups. Keep this layout while replacing their implementations. + +The view supplies the current input term, typing assumptions, guard equalities, and existential witness order. It is derived once, with fresh names, and reused by the induction callback and final assembly. Generated proof eigenvariables and `proof.Fact` values remain local to each proof traversal. Freshening must account for ambient assumptions, the goal, clause binders, type arguments, and any function self-reference. + +Induction hypotheses continue to follow the constructor signature's immediate `SelfRef` fields. Nested recursive agreement points additionally carry their field paths; each descent must be justified through the applicable `SelfRef` fields. A payload whose instantiated type happens to equal the domain does not acquire an induction hypothesis or height bound from that equality alone. + +## Implementation sequence + +### 1. Return and retain resolved patterns + +Implemented in [PatternNode.scala](PatternNode.scala), the resolver, and the unified [Pattern.scala](semantics/Pattern.scala). Both function and induction compilation retain the resolved patterns; proof generation no longer reparses pattern expressions. + +1. Add the two node forms and derived operations, preferably alongside the existing [Pattern.scala](semantics/Pattern.scala), keeping the file layout small. +2. Replace `validateCase` with a resolver returning the constructor-rooted tree. Reuse the existing strict application decoder and diagnostics. +3. Make [CaseAccumulator.scala](syntax/CaseAccumulator.scala) retain resolved cases once the domain is known. For functions, resolve the collected raw cases during compilation. +4. In [Case.subproof](syntax/Case.scala), resolve the case before executing its callback and store that same resolved pattern with the resulting proof. Final induction compilation must not parse the case again. +5. Derive the current plain/nested branch views from these nodes as temporary adapters. Replace the `Pat` and `RPat` parsers and migrate expression rendering, typed-binder collection, constructor typing, and case lookup to the resolved nodes. + +Per-case validation must precede an induction callback. Whole-collection coverage and overlap checks still occur after collection under the existing DSL; do not claim to validate future cases before their callbacks are supplied. + +Completion check: no parser inside proof generation; constructor specialization and arbitrary binder types survive resolution. Existing lookup tests still distinguish type arguments and preserve a bijection of value binders. Existing invalid-case tests still reject malformed input before its induction callback runs. + +### 2. Compile and retain one typed decision tree + +Implemented in [DecisionTree.scala](semantics/DecisionTree.scala). The accumulator compiles plain and nested clauses through the same coverage/overlap analysis and stores its tree on `PatternSystem`. The old trie and duplicate collection-validation checks are removed. + +1. Replace `NestedTrie.compile/buildTree` with a compiler consuming the resolved clauses and specialized domain. Keep compiler and tree declarations together, for example in `semantics/DecisionTree.scala`. +2. Carry actual constructor references, specialized column types, occurrence paths, and binder assignments through compilation. Never compare constructors or binders through their printed names. +3. Run coverage and overlap analysis once. Store the successful tree on the compiled collection; render diagnostics from the same analysis. +4. Compile plain and nested cases through this path. Remove the separate top-level missing/duplicate-case algorithms once equivalent diagnostics come from the common compiler. +5. Preserve the original clause order and payload attachment even when the tree groups cases by constructor. + +Completion check: one retained tree describes every accepted collection, including `Void` with no cases. Tests cover gaps, overlap, splits in multiple argument positions, and constructor identity across different datatypes. No definitions or proof generation are needed to decide these checks. + +### 3. Reconstruct coverage and branch selection from the tree + +Implemented in [PatternProofs.scala](semantics/PatternProofs.scala), used by the unified pattern system. Coverage traverses the retained root; branch selection traverses the known constructor's subtree using the original clause indices. Leaves use recorded binder paths, including whole-subtree binders. Split witnesses are fresh against the proof context and pattern variables, and empty splits use the datatype's elimination theorem. The independent proof matrix and split-selection logic are removed. + +The new whole-subtree regression also exposed a disjointness bug: clauses guarding different fields were compared by guard-list index. Guards are now aligned by their argument position before looking for different constructors. + +1. Replace the independent `RowP`/`ColP`, `switchIdx`, and matrix-specialization logic in [PatternProofs.scala](semantics/PatternProofs.scala) with recursion over the retained `Split` and `Leaf` nodes. +2. At each split, instantiate the recorded datatype's elimination theorem, introduce fresh typed field witnesses, and extend the local occurrence-to-expression environment and path equalities. +3. At each leaf, use the recorded binder assignments and the derived branch view to prove the selected clause's existing coverage disjunct. Supply outer synthetic binders and inner witnesses in their established order. +4. Prove whole-domain coverage from the root. Prove `branchSelectionFor` using the subtree of the known outer constructor, starting with its arguments and input equality already available. Do not compile a second matrix for branch selection. +5. Keep zero-constructor elimination explicit and keep all intermediate facts within their current proof scopes. Use Lisa's frontend tactics; the generated proofs remain kernel checked. + +Completion check: coverage and branch-selection statements retain their current shape, with equality guards and existential typing assumptions intact. The proof generator contains no choice of split column or reconstruction of clause rows. The recursion witness construction continues to consume these theorems unchanged. + +### 4. Unify branch semantics and migrate consumers + +Implemented with one body-independent `Pattern`, `Clause[A]` for the attached payload, and `PatternSystem[A]` for the compiled collection. Induction retains its proof payload directly; function bodies are instantiated through `PatternSystem.map`, which shares the same patterns, decision tree, and theorem caches. The constructor/nested adapters, their downcasts, and the separate induction-branch representation are removed. Proof helpers now live in [PatternProofs.scala](semantics/PatternProofs.scala). + +Nested recursive binders carry field paths derived only through `SelfRef` fields. Height descent follows these paths; specializing a payload to an ADT does not turn it into a recursive argument. Freshening uses payload/context expressions during construction without retaining those expressions in the body-independent pattern. + +1. Replace `ConstructorPattern`, `NestedConstructorPattern`, and their two pattern systems with one branch implementation and one compiled collection. Keep the existing `Pattern`-facing methods as derived operations while migrating consumers. +2. Move constructor typing, injectivity, incompatibility, and case matching onto the resolved tree. Use constructor injectivity along common paths and disjointness at a differing constructor. These operations need no separate pattern AST or decision-tree compilation. +3. Update [CaseAccumulator.scala](syntax/CaseAccumulator.scala) and [Induction.scala](../induction/Induction.scala) to attach proof payloads to resolved branches directly. Remove dummy `∅` bodies, rediscovery of interface constructors, and duplicate coverage checks. +4. Replace recursive guard reparsing with traversal of recorded field paths. Update [PointwiseAgreementStep.scala](../recursion/helpers/PointwiseAgreementStep.scala), which serves stabilization and uniqueness, and preserve the immediate/inner binder distinction used by [Witness.targetInhabited](../recursion/Witness.scala). +5. Update function specifications, graph-witness proofs, and the public function wrapper to consume the unified clauses. Keep body-independent coverage/selection data shared when substituting the recursive self-reference into bodies. +6. Remove temporary adapters, `ConstructorHeadPattern` downcasts, the plain/nested dispatch in the accumulator, and unused guard representations. Fold the surviving proof routines into a common `semantics/PatternProofs.scala` or an equivalently small arrangement. + +Completion check: all functions and induction cases use one pattern implementation. No independently stored pattern terms or guards are reparsed to recover structure. Preserve the public DSL and theorem contracts; introduce no new distinction between ordinary and recursive functions. + +## Validation and completion + +Use the existing [ADTRegressionSuite.scala](../../../../../../../../test/scala/lisa/maths/SetTheory/Types/ADTRegressionSuite.scala), currently 68 tests, the six compiler/contract tests in [DecisionTreeSuite.scala](../../../../../../../../test/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/DecisionTreeSuite.scala), and the existing ADT examples. Preserve coverage of specialization, independent function parameters, opaque/function payloads, nested recursion, ambient induction assumptions, invalid declarations, and binder-renamed equation lookup. + +Step 2's tests cover empty splits, source clause indices and binder order, whole-subtree binder paths, nested specialization, missing cases, overlap in both declaration orders, and distinct datatypes with matching short constructor names. Compilation is also checked to leave definition and ADT registration unchanged. + +Validated after step 2: all 4 compiler tests, all 63 ADT regression tests, all 16 examples, and both proof initializers executed successfully. `git diff --check` passed. + +Step 3 adds computation and induction regressions for whole-subtree bindings, reordered cases, and ambient variables named like the old proof placeholders. All 4 compiler tests, all 65 ADT regressions, all 16 examples, and both proof initializers executed successfully; `git diff --check` passed. + +Step 4 adds tests for shared pattern/tree/theorem identities after payload mapping, recursive field-path filtering, two nested recursive binders, and absence of induction hypotheses for specialized payloads. All 6 compiler/contract tests, all 67 ADT regressions, all 16 examples, and both proof initializers executed successfully; `git diff --check` passed. + +Focused regressions cover the following boundaries: + +- Nested cases split two different fields of one constructor; execute computations and induction assembly. +- Several nested recursive binders exercise height descent, existence, and uniqueness. +- A payload specialized to an ADT type receives no recursive hypothesis solely because of that type. Check the branch assumptions as well as successful nonrecursive use. +- User or ambient variables named like `scrutX`, `fv0`, `bsf0`, and generated constructor arguments do not get captured. +- Constructor identities remain distinct across datatypes with matching short constructor names; rigid type arguments survive binder-renamed lookup. +- Clause reordering preserves the intended equation lookup and payload association. Mapping bodies preserves the compiled pattern structure and coverage proof. +- Empty-ADT coverage succeeds through the common compiler; nested gaps and overlaps fail before definition registration. Existing invalid-induction tests still prove that the offending callback is never entered. + +For each migration stage, execute the relevant regression proofs. Before considering the refactor complete, run these commands sequentially: + +```text +sbt "lisa-sets/testOnly lisa.maths.SetTheory.Types.ADT.PatternMatching.DecisionTreeSuite" +sbt "lisa-sets/testOnly lisa.maths.SetTheory.Types.ADTRegressionSuite" +sbt "lisa-examples/runMain ADTExamples.RunAll" +``` + +Compilation alone is insufficient. The latter command executes all 16 examples and both proof initializers. Check generated theorems for admitted proofs as in the existing tests, and finish with `git diff --check`. + +The implementation has one resolver, one decision-tree compiler, and proof routines consuming their output. The string pattern AST, `RPat`, duplicate parsers, the second splitting algorithm, and separate plain/nested implementations are removed. Theorem caches belong to the compiled collection and are shared when its payloads are mapped; proof facts remain scoped to their proofs. + +## Follow-up: direct functionality and lazy disjointness + +Constructor disjointness is cached on demand. Each unordered pair has one proof from the encoding; the reverse orientation follows by symmetry. The public ADT and semantic callers share these proofs, and only requested public theorem wrappers are registered. + +[WitnessFunctionProofs.scala](proofs/WitnessFunctionProofs.scala) proves functionality directly over the existing clause graph. Two fresh witness tuples are reused under independent branch quantifiers, and small branch-decomposition facts are shared across comparisons. Identical instantiated bodies agree immediately. Otherwise, equal inputs from the same clause yield equal binders by pattern injectivity, then equal outputs by explicit simultaneous substitution, including lambda-valued outputs. Different clauses use cached pattern incompatibility. Both witness tuples are closed existentially, and the resulting pair statements are combined against the existing graph-membership disjunction. + +Only unordered clause pairs generate agreement lemmas. Reverse pairs use output-swapped theorem instances without registering extra wrappers. The older conversion between named and canonical graph branches, separate body-equality theorem map, and nested existential proof scaffolding are removed. This remains quadratic in clause count; the decision tree continues to drive coverage and branch selection. + +The expanded subtree-relation approach was removed after measurement: despite reducing emitted lemmas, transporting entire subtree formulas made the eight-clause example slower (1.99 s versus 1.09 s for the older direct proof, medians of three local samples). The implementation now has one graph-functionality proof, with no second relation or graph-to-tree bridge. A generic split-lemma prototype would need to demonstrate better construction time and kernel-proof size before replacing it. + +Validated by executing 68 ADT regressions, 6 compiler/contract tests, 3 disjointness tests, all 16 examples, and both proof initializers. These include reordered eight-clause computations, lambda-valued bodies, whole-subtree binders, empty domains, and theorem-cache identity. The independent cross-constructor binder-capture failure recorded in `AGENTS_adt.md` was subsequently fixed. + +### Direct-proof measurements, 2026-11-16 + +The simplified functionality implementation is 359 lines, compared with 685 in the old direct implementation; the extra subtree-relation and bridge files are removed. Canonical closed branch formulas are defined once by `Clause.caseMembership` and reused by graph construction and proof statements. + +The following are medians of three warmed function-construction samples, using the same lazy disjointness cache and a 3 GB JVM heap in both implementations. Nested cases inspect all Boolean combinations; payload cases return an unconstrained pattern-bound value, so their same-clause proofs require injectivity and substitution. Wide cases use flat enumerations. Kernel steps sum the checked theorem certificates registered during construction, including nested subproof containers but excluding imported proofs already counted elsewhere. Temporary counters were removed after measurement. + +| Function | Old time | Simplified time | Old kernel steps | Simplified kernel steps | +|---|---:|---:|---:|---:| +| Nested, 2 clauses | 0.094 s | 0.070 s | 3,873 | 3,646 | +| Nested, 4 clauses | 0.304 s | 0.281 s | 9,945 | 8,863 | +| Nested, 8 clauses | 0.940 s | 0.888 s | 27,121 | 22,710 | +| Nested, 16 clauses | 4.591 s | 4.625 s | 85,812 | 66,199 | +| Payload, 4 clauses | 0.331 s | 0.324 s | 10,647 | 11,332 | +| Payload, 8 clauses | 1.203 s | 1.076 s | 30,727 | 31,227 | +| Wide, 2 constructors | 0.112 s | 0.080 s | 3,829 | 3,714 | +| Wide, 4 constructors | 0.130 s | 0.106 s | 6,209 | 5,874 | +| Wide, 8 constructors | 0.215 s | 0.195 s | 12,135 | 10,958 | + +These small samples show roughly preserved or improved runtime, not a universal speedup. Kernel-proof size decreases for constant-result cases but increases slightly for the payload cases. Pairwise comparison remains quadratic. The temporary harness is `target/ADTScalingBenchmark.scala`; raw results are in `target/adt-scaling-{matrix,selected}.log`. + +### Follow-up: reuse theorem instances, 2026-11-16 + +Height adapters now instantiate shared theorems with `.of` inside the consuming proof. The three constructor height lemmas are cached generic schemas. Empty or identity substitutions return the original theorem; other substitution lists retain their simultaneous, last-assignment-wins semantics. Type-substitution validation is unchanged. The unused `UniqueCharacterizedSymbol` layer is removed; `UniqueDefinedSymbol.fromParts` retains the existence and uniqueness construction without generating the unused characterization theorem. + +Executed 82 tests, all 16 examples, and both proof initializers. The five new `TheoremInstancesSuite` tests check identity reuse, substitution semantics, separate proof contexts, shared constructor schemas, and invalid substitutions. Repeated specialization registers no new theorems once the schemas exist. + +The same warmed construction harness gives the following medians of three samples. The baseline is the preceding `selected` run, not an alternating before/after measurement. Counts include all kernel theorem registrations during each construction. + +| Function | Previous theorems | Current theorems | Previous time | Current time | +|---|---:|---:|---:|---:| +| Nested, 2 clauses | 99 | 61 | 0.070 s | 0.100 s | +| Nested, 4 clauses | 139 | 111 | 0.281 s | 0.245 s | +| Nested, 8 clauses | 269 | 241 | 0.888 s | 0.907 s | +| Nested, 16 clauses | 673 | 645 | 4.625 s | 4.921 s | +| Payload, 4 clauses | 155 | 127 | 0.324 s | 0.341 s | +| Payload, 8 clauses | 329 | 301 | 1.076 s | 1.190 s | +| Wide, 2 constructors | 99 | 61 | 0.080 s | 0.074 s | +| Wide, 4 constructors | 161 | 103 | 0.106 s | 0.162 s | +| Wide, 8 constructors | 303 | 205 | 0.195 s | 0.192 s | + +Registration counts decrease in every case; runtime does not consistently improve. Kernel steps also depend on where instantiations are performed: wide-eight decreases from 10,958 to 9,604, while payload-eight increases from 31,227 to 32,365. Raw results are in `target/adt-scaling-instances.log`. Temporary counters were removed, and the five instance tests were executed again with the restored kernel source. + +### Follow-up: shared helpers and constructor lookup + +`HeightStageSet` and `HeightTerms` share one finite-union implementation and one lazy subset schema. Component-inclusion proofs start at the requested component, preserve ambient assumptions, and reject absent components. Seven unused specialization helpers and their stale imports are removed. The old coverage and nullary-pattern machinery was already removed by the pattern refactor. + +The ADT registry indexes constructor identifiers by owner and position. Pattern resolution uses this index and initializes only the requested owner's constructor wrappers, stored in a vector. Arity, specialization, and ownership checks remain unchanged. The new tests cover finite-union edge cases, theorem reuse, lookup misses, distinct constructor identities, and lazy initialization of unrelated wrappers. + +Validated by executing all 86 tests, all 16 examples, and both proof initializers. `git diff --check` passed. Runtime effects were not benchmarked for this cleanup. + +The follow-up freshness fixes share generated variables across each function declaration, keep canonical constructor tuples fresh against parameters and case bodies, and instantiate type and value substitutions simultaneously. Constructor predicates are capture-avoiding formula templates; induction also freshens its property binder and constructor witnesses against the ambient context. Pattern input typing reuses the constructor's application theorem. + +Recursive body equality now abstracts the exact recursive-call occurrences and applies one simultaneous equality substitution through the whole body. This handles nested lambdas without separate cases for binder depth. `RobustnessSuite` adds 37 executed regressions covering the reported captures, specialized domains, nested recursion, and two or three nested lambdas. All 123 ADT tests, all 16 examples, and both proof initializers pass. `git diff --check` is clean. diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PatternNode.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PatternNode.scala new file mode 100644 index 000000000..0c0f58e84 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PatternNode.scala @@ -0,0 +1,95 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.appSeq + +/** + * A resolved constructor pattern with its specialized types and value binders. + */ +private[ADT] sealed trait PatternNode { + + /** + * The set containing values matched by this node. + */ + def typ: Expr[Ind] + + /** + * The constructor expression represented by this node. + */ + def term: Expr[Ind] + + /** + * The value binders and their types, in occurrence order. + */ + def typingSignature: Seq[(Variable[Ind], Expr[Ind])] + + /** + * The value binders, in occurrence order. + */ + final def binders: Seq[Variable[Ind]] = typingSignature.map(_._1) + + /** + * Renames value binders while preserving rigid type arguments and binder types. + */ + def renameBinders(renaming: Map[Variable[Ind], Variable[Ind]]): PatternNode +} + +/** + * The two forms of resolved patterns. + */ +private[ADT] object PatternNode { + + /** + * A value binder with its expected type. + */ + final case class Bind private[PatternMatching] (variable: Variable[Ind], typ: Expr[Ind]) extends PatternNode { + + /** + * The expression bound at this position. + */ + def term: Expr[Ind] = variable + + /** + * This binder and its expected type. + */ + def typingSignature: Seq[(Variable[Ind], Expr[Ind])] = Seq(variable -> typ) + + /** + * Renames this value binder without substituting in its type. + */ + def renameBinders(renaming: Map[Variable[Ind], Variable[Ind]]): Bind = + copy(variable = renaming.getOrElse(variable, variable)) + } + + /** + * A constructor application with its explicit type arguments and resolved children. + */ + final case class Construct private[PatternMatching] ( + constructor: Constructor[?], + typeArguments: Seq[Expr[Ind]], + arguments: List[PatternNode] + ) extends PatternNode { + + /** + * The specialized datatype returned by the constructor. + */ + lazy val typ: Expr[Ind] = constructor.adt.termAt(typeArguments) + + /** + * The constructor applied to its type arguments and child expressions. + */ + lazy val term: Expr[Ind] = appSeq(constructor.semantic.term(typeArguments))(arguments.map(_.term)) + + /** + * All child binders and their types, from left to right. + */ + lazy val typingSignature: Seq[(Variable[Ind], Expr[Ind])] = arguments.flatMap(_.typingSignature) + + /** + * Renames child value binders while preserving the constructor's type arguments. + */ + def renameBinders(renaming: Map[Variable[Ind], Variable[Ind]]): Construct = + copy(arguments = arguments.map(_.renameBinders(renaming))) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PatternValidation.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PatternValidation.scala new file mode 100644 index 000000000..665d09ea0 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/PatternValidation.scala @@ -0,0 +1,86 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT +import lisa.maths.SetTheory.Types.TypingHelpers + +/** + * Resolves constructor patterns without generating proofs or registering definitions. + */ +private[PatternMatching] object PatternValidation { + + /** + * Separates a set application into its head and ordered value arguments. + */ + def peelApp(term: Expr[Ind]): (Expr[Ind], List[Expr[Ind]]) = { + @annotation.tailrec + def loop(current: Expr[Ind], args: List[Expr[Ind]]): (Expr[Ind], List[Expr[Ind]]) = + TypingHelpers.`*`.unapply(current) match + case Some((head, arg)) => loop(head, arg :: args) + case None => (current, args) + loop(term, Nil) + } + + /** + * Decodes a fully applied registered constructor, preserving its explicit type arguments. + */ + def constructorApplication(term: Expr[Ind]): Either[String, (Constructor[?], Seq[Expr[Ind]], List[Expr[Ind]])] = { + val (head, args) = peelApp(term) + head match + case Multiapp(symbol: Constant[?] @unchecked, typeArgs) => + ADT.getConstructor(symbol.id) match + case None => Left(s"Unsupported pattern $term: expected a variable or a constructor application.") + case Some(constructor) => + if typeArgs.size != constructor.typeVariablesSeq.size then Left(s"Constructor ${constructor.name} expects ${constructor.typeVariablesSeq.size} type argument(s), got ${typeArgs.size}.") + else if !typeArgs.forall(_.sort == summon[(Ind) is Sort].underlying) then Left(s"Constructor ${constructor.name} requires type arguments of sort Ind.") + else if args.size != constructor.semantic.arity then Left(s"Constructor ${constructor.name} expects ${constructor.semantic.arity} value argument(s), got ${args.size}.") + else Right((constructor, typeArgs.asInstanceOf[Seq[Expr[Ind]]], args)) + case _ => Left(s"Unsupported pattern $term: expected a variable or a constructor application.") + } + + /** + * Resolves one case while checking ownership, specialization, arities, and binder linearity. + */ + def resolveCase(constructor: Constructor[?], args: Seq[Expr[Ind]], domain: SpecializedADT[?]): Either[String, PatternNode.Construct] = + new Resolver().constructor(constructor, domain.typeArgs, args, domain.term, s"Case ${constructor.name}") + + private final class Resolver { + private val binders = scala.collection.mutable.HashSet.empty[Variable[Ind]] + + def node(term: Expr[Ind], expectedType: Expr[Ind], path: String): Either[String, PatternNode] = term match + case v: Variable[Ind] @unchecked => + Either.cond(binders.add(v), PatternNode.Bind(v, expectedType), s"$path: repeated pattern binder $v.") + case _ => + constructorApplication(term).left.map(error => s"$path: $error").flatMap { (cons, typeArgs, values) => + constructor(cons, typeArgs, values, expectedType, path) + } + + def constructor( + cons: Constructor[?], + typeArgs: Seq[Expr[Ind]], + values: Seq[Expr[Ind]], + expectedType: Expr[Ind], + path: String + ): Either[String, PatternNode.Construct] = + ADT.unapply(expectedType) match + case None => Left(s"$path: cannot match constructor ${cons.name} at non-ADT type $expectedType.") + case Some((adt, _)) if adt.id != cons.adt.id => + Left(s"$path: ${cons.name} is not a constructor of $expectedType.") + case _ if !isSame(cons.adt.termAt(typeArgs), expectedType) => + Left(s"$path: constructor type arguments give ${cons.adt.termAt(typeArgs)}, expected $expectedType.") + case _ if values.size != cons.semantic.arity => + Left(s"$path: expected ${cons.semantic.arity} value argument(s), got ${values.size}.") + case _ => + val substitutions = cons.typeVariablesSeq.zip(typeArgs).map((v, arg) => v := arg) + val arguments = List.newBuilder[PatternNode] + val children = values.iterator.zip(cons.semantic.semanticSignature).zipWithIndex + while children.hasNext do + val ((value, (_, typ)), index) = children.next() + node(value, typ.substitute(substitutions*), s"$path argument ${index + 1}") match + case Left(error) => return Left(error) + case Right(argument) => arguments += argument + Right(PatternNode.Construct(cons, typeArgs, arguments.result())) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/CaseDefinedWitness.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/CaseDefinedWitness.scala new file mode 100644 index 000000000..5a4677482 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/CaseDefinedWitness.scala @@ -0,0 +1,44 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.proofs + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.encoding._ +import lisa.utils.prooflib.Thm + +/** + * Shared semantic witness construction for ADT functions. + * + * A case-defined witness is a relation `W ⊆ A × T` described by semantic branches. + * This class factors the common proof layer used by ordinary semantic + * functions and recursive witness relations: + * - branch-wise witness membership + * - relation-betweenness + * - totality and single-valuedness + * - uniqueness of outputs + * - function typing + * - witness application equations on branch inputs + * + * Clients provide the ADT-specific ingredients: + * - the witness term and its `DEF` equation + * - the branch bodies and the `caseMembership` predicate + * - return-type checks for each branch body + * - optional ambient assumptions required to type the branch bodies + * + * When `contextPremises` is empty, exported theorems are plain formulas. When it is + * non-empty, theorems are wrapped under the conjunction of these premises. + */ +final class CaseDefinedWitness( + protected val adt: SemanticADT, + protected val argType: Expr[Ind], + protected val patternMatching: PatternSystem[Expr[Ind]], + protected val returnType: Expr[Ind], + protected val typ: Expr[Ind], + protected val witness: Expr[Ind], + protected val witnessDef: Thm, + protected val witnessBound: Expr[Ind], + protected val pairWitness: Variable[Ind], + protected val caseMembership: Expr[Ind] => Expr[Prop], + protected val checkReturnType: Map[Clause[Expr[Ind]], Thm], + protected val contextPremises: Seq[Expr[Prop]] = Seq.empty +) extends WitnessApplicationProofs diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessApplicationProofs.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessApplicationProofs.scala new file mode 100644 index 000000000..fa1419a46 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessApplicationProofs.scala @@ -0,0 +1,123 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.proofs + +import lisa.maths.SetTheory.Functions.BasicTheorems +import lisa.maths.SetTheory.Functions.Function +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.prooflib.BasicStep.Restate +import lisa.utils.prooflib.InstantiateForallSeq +import lisa.utils.prooflib.QuantifiersIntro + +private[proofs] trait WitnessApplicationProofs extends WitnessFunctionProofs { + + val witnessCaseByPattern: Map[Clause[Expr[Ind]], Theorem] = + patternMatching.clauses + .map(pattern => + val vars = pattern.binders + val body = pattern.body + pattern -> (Lemma.generated( + contextualize( + forallSeq( + vars, + pattern.branchPremiseAt(vars) ==> (witness * pattern.inputTermAt(vars) === body) + ) + ) + ) { + val contextHyp = + if contextPremises.isEmpty then None else Some(assume(contextPremise)) + val wellTypedArgs = pattern.branchPremiseAt(vars) + val pairTerm = pair(pattern.inputTermAt(vars), body) + + val membershipSchema = + if contextPremises.isEmpty then + have(witnessMembership(pattern).statement.right.head) by + Tautology.from(witnessMembership(pattern)) + lastStep + else + witnessMembership(pattern).statement.right.head match + case _ ==> consequent => + have(consequent) by Tautology.from(witnessMembership(pattern), contextHyp.get) + lastStep + case _ => throw UnreachableException + val instantiatedMembership = have( + wellTypedArgs ==> pairTerm ∈ witness + ) by InstantiateForallSeq(vars)(membershipSchema) + val pairInWitness = have(wellTypedArgs |- pairTerm ∈ witness) by + Tautology.from(instantiatedMembership) + + val witnessBetween = + if contextPremises.isEmpty then + have(Function.functionBetween(witness)(argType)(returnType)) by Tautology.from( + BasicTheorems.funcBetweenEqInFuncSpace of ( + f := witness, + A := argType, + B := returnType + ), + witnessHasType + ) + else + have(witness :: typ) by Tautology.from(witnessHasType, contextHyp.get) + have(Function.functionBetween(witness)(argType)(returnType)) by Tautology.from( + BasicTheorems.funcBetweenEqInFuncSpace of ( + f := witness, + A := argType, + B := returnType + ), + lastStep + ) + val witnessIsFunction = have(Function.function(witness)) by Tautology.from( + BasicTheorems.functionBetweenIsFunction of ( + f := witness, + A := argType, + B := returnType + ), + witnessBetween + ) + val witnessDomain = have(Function.dom(witness) === argType) by Tautology.from( + BasicTheorems.functionBetweenDomain of ( + f := witness, + A := argType, + B := returnType + ), + witnessBetween + ) + + val inputTyping = have(wellTypedArgs |- pattern.inputTermAt(vars) :: argType) by + Tautology.from(pattern.inputTypingAt(vars, argType)) + val inputInDomain = have(wellTypedArgs |- pattern.inputTermAt(vars) ∈ Function.dom(witness)) by + Congruence.from(inputTyping, witnessDomain) + + val appEq = have( + wellTypedArgs |- (witness * pattern.inputTermAt(vars) === body) <=> (pairTerm ∈ witness) + ) by Tautology.from( + BasicTheorems.appDefinition of ( + f := witness, + x := pattern.inputTermAt(vars), + y := body + ), + witnessIsFunction, + inputInDomain + ) + + have(wellTypedArgs |- (witness * pattern.inputTermAt(vars) === body)) by + Tautology.from(appEq, pairInWitness) + thenHave(wellTypedArgs ==> (witness * pattern.inputTermAt(vars) === body)) by + RightImplies.withParameters(wellTypedArgs, witness * pattern.inputTermAt(vars) === body) + val core = thenHave( + forallSeq( + vars, + pattern.branchPremiseAt(vars) ==> (witness * pattern.inputTermAt(vars) === body) + ) + ) by QuantifiersIntro(vars) + + if contextPremises.isEmpty then have(thesis) by Restate.from(core) + else have(thesis) by Tautology.from(contextHyp.get, core) + }) + ) + .toMap + + def witnessCase(pattern: Clause[Expr[Ind]]): Theorem = + witnessCaseByPattern(pattern) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessBranchMembership.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessBranchMembership.scala new file mode 100644 index 000000000..5b8c7446d --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessBranchMembership.scala @@ -0,0 +1,173 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.proofs + +import lisa.maths.SetTheory.Base.CartesianProduct +import lisa.maths.SetTheory.Base.Comprehension +import lisa.maths.SetTheory.Base.Symbols.φ +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.prooflib.BasicStep.Cut +import lisa.utils.prooflib.BasicStep.Restate +import lisa.utils.prooflib.InstantiateForallSeq +import lisa.utils.prooflib.QuantifiersIntro + +private[proofs] trait WitnessBranchMembership extends WitnessProofContext { + + /** + * Expands witness membership once for use in the branch and functionality proofs. + */ + protected val witnessMembershipExpanded: Theorem = Lemma.generated( + ∀( + inputTerm, + ∀( + outputTerm, + pair(inputTerm, outputTerm) ∈ witness <=> + (pair(inputTerm, outputTerm) ∈ witnessBound /\ caseMembership(pair(inputTerm, outputTerm))) + ) + ) + ) { + val pairTerm = pair(inputTerm, outputTerm) + + have( + pairTerm ∈ witnessBody <=> (pairTerm ∈ witnessBound /\ caseMembership(pairTerm)) + ) by Restate.from( + Comprehension.membership of ( + x := pairTerm, + y := witnessBound, + φ := λ(pairWitness, caseMembership(pairWitness)) + ) + ) + + val pointwise = have( + pairTerm ∈ witness <=> + (pairTerm ∈ witnessBound /\ caseMembership(pairTerm)) + ) by Congruence.from(witnessDef, lastStep) + + have(thesis) by QuantifiersIntro(Seq(inputTerm, outputTerm))(pointwise) + } + + val witnessMembershipByPattern: Map[Clause[Expr[Ind]], Theorem] = + patternMatching.clauses + .map(pattern => { + val vars = pattern.binders + val body = pattern.body + pattern -> (Lemma.generated( + contextualize( + forallSeq( + vars, + pattern.branchPremiseAt(vars) ==> pair(pattern.inputTermAt(vars), body) ∈ witness + ) + ) + ) { + val contextHyp = + if contextPremises.isEmpty then None else Some(assume(contextPremise)) + val wellTypedArgs = pattern.branchPremiseAt(vars) + val wellTypedPremises = pattern.typingPremisesAt(vars) + val pairTerm = pair(pattern.inputTermAt(vars), body) + + def proveAvailablePremise(required: Expr[Prop]) = + if required == wellTypedArgs then have(wellTypedArgs |- required) by Hypothesis + else if wellTypedPremises.contains(required) then + have(wellTypedArgs |- required) by Weakening( + have(wellTypedArgs |- wellTypedArgs) by Hypothesis + ) + else + contextPremises + .find(_ == required) + .getOrElse( + throw IllegalArgumentException( + s"Unsupported typing premise in CaseDefinedWitness: $required" + ) + ) + val hyp = contextHyp.getOrElse( + throw IllegalArgumentException( + s"Premise $required requires a non-empty contextual assumption." + ) + ) + have(wellTypedArgs |- required) by Weakening(hyp) + + val inputTyping = have(wellTypedArgs |- pattern.inputTermAt(vars) :: argType) by + Tautology.from(pattern.inputTypingAt(vars, argType)) + + val outputTypingPremises = + checkReturnType(pattern).statement.left.toSeq + val outputTypingFacts = outputTypingPremises.map(proveAvailablePremise) + val outputTyping = have(wellTypedArgs |- body :: returnType) by Tautology.from( + (checkReturnType(pattern) +: outputTypingFacts)* + ) + + val pairInBound = have(wellTypedArgs |- pairTerm ∈ witnessBound) by Tautology.from( + CartesianProduct.pairMembership of ( + A := argType, + B := returnType, + x := pattern.inputTermAt(vars), + y := body + ), + inputTyping, + outputTyping + ) + + val baseCaseBody = + pattern.freshBranchPremise /\ (pairTerm === pair(pattern.freshInputTerm, pattern.bodyAtFreshVars2)) + + val fullyInstantiatedCaseBody = + baseCaseBody.substitute(pattern.variables2.zip(vars).map((from, to) => from := to)*) + + val ownBranchAtCurrentVars = have( + wellTypedArgs |- fullyInstantiatedCaseBody + ) by RightAnd( + have(wellTypedArgs |- wellTypedArgs) by Hypothesis, + have(wellTypedArgs |- pairTerm === pair(pattern.inputTermAt(vars), body)) by RightRefl + ) + + val inOwnCaseBranchRaw = + pattern.variables2.indices.reverse.foldLeft(ownBranchAtCurrentVars)((fact, idx) => + val quantifiedVar = pattern.variables2(idx) + val witnessVar = vars(idx) + val priorSubst = + pattern.variables2.take(idx).zip(vars.take(idx)).map((from, to) => from := to) + val phi = existsSeq( + pattern.variables2.drop(idx + 1), + baseCaseBody.substitute(priorSubst*) + ) + have(wellTypedArgs |- ∃(quantifiedVar, phi)) by + RightExists.withParameters(phi, quantifiedVar, witnessVar)(fact) + ) + + val ownCaseToMembership = have( + inOwnCaseBranchRaw.statement.right.head |- caseMembership(pairTerm) + ) by Restate + + val rawCaseMembership = have(wellTypedArgs |- caseMembership(pairTerm)) by + Cut(inOwnCaseBranchRaw, ownCaseToMembership) + + val membershipSchema = have(witnessMembershipExpanded.statement.right.head) by Weakening(witnessMembershipExpanded) + val witnessMembershipEq = have( + wellTypedArgs |- pairTerm ∈ witness <=> + (pairTerm ∈ witnessBound /\ caseMembership(pairTerm)) + ) by InstantiateForallSeq(Seq(pattern.inputTermAt(vars), body))(membershipSchema) + + val pairInBoundAndCase = + have(wellTypedArgs |- pairTerm ∈ witnessBound /\ caseMembership(pairTerm)) by + RightAnd(pairInBound, rawCaseMembership) + + have(wellTypedArgs |- pairTerm ∈ witness) by + Tautology.from(witnessMembershipEq, pairInBoundAndCase) + thenHave(wellTypedArgs ==> (pairTerm ∈ witness)) by + RightImplies.withParameters(wellTypedArgs, pairTerm ∈ witness) + + thenHave( + forallSeq( + vars, + pattern.branchPremiseAt(vars) ==> pair(pattern.inputTermAt(vars), body) ∈ witness + ) + ) by QuantifiersIntro(vars) + thenHave(thesis) by Restate + }) + }) + .toMap + + def witnessMembership(pattern: Clause[Expr[Ind]]): Theorem = + witnessMembershipByPattern(pattern) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessFunctionProofs.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessFunctionProofs.scala new file mode 100644 index 000000000..b20426ea6 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessFunctionProofs.scala @@ -0,0 +1,354 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.proofs + +import lisa.maths.Quantifiers.existsOneAlternativeDefinition +import lisa.maths.Quantifiers.∃! +import lisa.maths.SetTheory.Base.Comprehension +import lisa.maths.SetTheory.Base.Pair +import lisa.maths.SetTheory.Base.Symbols.X +import lisa.maths.SetTheory.Base.Symbols.Y +import lisa.maths.SetTheory.Base.Symbols.φ +import lisa.maths.SetTheory.Functions.BasicTheorems +import lisa.maths.SetTheory.Functions.Function +import lisa.maths.SetTheory.Relations.Relation.R +import lisa.maths.SetTheory.Relations.Relation.relationBetween +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.prooflib.BasicStep.LeftExists +import lisa.utils.prooflib.BasicStep.Restate +import lisa.utils.prooflib.BasicStep.RightForall +import lisa.utils.prooflib.InstantiateForall +import lisa.utils.prooflib.InstantiateForallSeq +import lisa.utils.prooflib.QuantifiersIntro + +private[proofs] trait WitnessFunctionProofs extends WitnessBranchMembership { + + private val witnessMembershipByCases: Theorem = { + val witnessInPattern = pair(inputTerm, outputTerm) ∈ witness ==> patternMatching.caseMembership(pair(inputTerm, outputTerm)) + Lemma.generated( + ∀(inputTerm ∈ argType, ∀(outputTerm, witnessInPattern)) + ) { + val expandedAtInput = have( + ∀( + outputTerm, + pair(inputTerm, outputTerm) ∈ witness <=> + (pair(inputTerm, outputTerm) ∈ witnessBound /\ caseMembership(pair(inputTerm, outputTerm))) + ) + ) by InstantiateForall(inputTerm)(witnessMembershipExpanded) + + val pointwise = have( + (inputTerm ∈ argType) |- ∀(outputTerm, witnessInPattern) + ) subproof { + assume(inputTerm ∈ argType) + val witnessExpanded = have( + pair(inputTerm, outputTerm) ∈ witness <=> + (pair(inputTerm, outputTerm) ∈ witnessBound /\ caseMembership(pair(inputTerm, outputTerm))) + ) by InstantiateForall(outputTerm)(expandedAtInput) + + val caseMembershipInvariant = have(∀(pairWitness, caseMembership(pairWitness) <=> patternCaseMembership(pairWitness))) by Restate + val invariantAtPair = have( + caseMembership(pair(inputTerm, outputTerm)) <=> patternCaseMembership(pair(inputTerm, outputTerm)) + ) by InstantiateForall(pair(inputTerm, outputTerm))(caseMembershipInvariant) + + have(witnessInPattern) by Tautology.from(witnessExpanded, invariantAtPair) + thenHave(thesis) by RightForall + } + + have( + (inputTerm ∈ argType) ==> ∀(outputTerm, witnessInPattern) + ) by RightImplies(pointwise) + thenHave(thesis) by Generalize + } + } + + private val witnessTotality: Theorem = { + Lemma.generated( + contextualize( + ∀(inputTerm ∈ argType, ∃(outputTerm, pair(inputTerm, outputTerm) ∈ witness)) + ) + ) { + if contextPremises.nonEmpty then assume(contextPremise) + + val branchExistenceFacts = patternMatching.clauses.map(pattern => + + val membershipSchema = + if contextPremises.isEmpty then have(witnessMembership(pattern).statement.right.head) by Tautology.from(witnessMembership(pattern)) + else + witnessMembership(pattern).statement.right.head match + case _ ==> consequent => + have(consequent) by Tautology.from(witnessMembership(pattern)) + case _ => throw UnreachableException + val freshMembership = have( + pattern.freshBranchPremise ==> pair(pattern.freshInputTerm, pattern.bodyAtFreshVars2) ∈ witness + ) by InstantiateForallSeq(pattern.variables2)(membershipSchema) + + val freshPairInWitness = have( + pattern.freshBranchPremise |- pair(pattern.freshInputTerm, pattern.bodyAtFreshVars2) ∈ witness + ) by Restate.from(freshMembership) + + have( + (pattern.freshBranchPremise, (inputTerm === pattern.freshInputTerm)) |- pair(inputTerm, pattern.bodyAtFreshVars2) ∈ witness + ) by Congruence.from(freshPairInWitness) + have( + (pattern.freshBranchPremise /\ (inputTerm === pattern.freshInputTerm)) |- pair(inputTerm, pattern.bodyAtFreshVars2) ∈ witness + ) by Restate.from(lastStep) + + val directBranch = thenHave( + (pattern.freshBranchPremise /\ (inputTerm === pattern.freshInputTerm)) |- ∃(outputTerm, pair(inputTerm, outputTerm) ∈ witness) + ) by RightExists + + val liftedBranch = + pattern.variables2.reverse.foldLeft(directBranch)((fact, v) => have(∃(v, fact.statement.left.head) |- ∃(outputTerm, pair(inputTerm, outputTerm) ∈ witness)) by LeftExists(fact)) + have( + existsSeq( + pattern.variables2, + pattern.freshBranchPremise /\ (inputTerm === pattern.freshInputTerm) + ) |- ∃(outputTerm, pair(inputTerm, outputTerm) ∈ witness) + ) by Restate.from(liftedBranch) + ) + + val coverageToWitness = + have(simplify(patternMatching.caseCoverage(inputTerm)) |- ∃(outputTerm, pair(inputTerm, outputTerm) ∈ witness)) by + Tautology.from(branchExistenceFacts*) + + have( + (inputTerm ∈ argType) ==> simplify(patternMatching.caseCoverage(inputTerm)) + ) by InstantiateForall(inputTerm)(patternMatching.coverage) + val coveredInput = thenHave( + (inputTerm ∈ argType) |- simplify(patternMatching.caseCoverage(inputTerm)) + ) by Restate + + have((inputTerm ∈ argType) |- ∃(outputTerm, pair(inputTerm, outputTerm) ∈ witness)) by + Cut(coveredInput, coverageToWitness) + val pointwise = thenHave( + (inputTerm ∈ argType) ==> ∃(outputTerm, pair(inputTerm, outputTerm) ∈ witness) + ) by RightImplies + + have(∀(inputTerm ∈ argType, ∃(outputTerm, pair(inputTerm, outputTerm) ∈ witness))) by RightForall(pointwise) + thenHave(thesis) by Restate + } + } + + /** + * One clause at an independent tuple of graph witnesses. + */ + private final case class GraphBranch(clause: Clause[Expr[Ind]], variables: Seq[Variable[Ind]]) { + val premise: Expr[Prop] = clause.branchPremiseAt(variables) + val input: Expr[Ind] = clause.inputTermAt(variables) + val body: Expr[Ind] = clause.bodyAt(variables) + def member(result: Expr[Ind]): Expr[Prop] = + premise /\ (pair(inputTerm, result) === pair(input, body)) + // Keep theorem boundaries identical to the graph's canonical branch formulas. + def quantified(result: Expr[Ind]): Expr[Prop] = clause.caseMembership(pair(inputTerm, result)) + + // These small facts are reused across all comparisons involving this branch. + lazy val conditions: Theorem = Lemma.generated(member(outputTerm) |- premise) { + have(thesis) by Tautology + } + lazy val inputEquality: Theorem = Lemma.generated(member(outputTerm) |- inputTerm === input) { + have(thesis) by Tautology.from(Pair.extensionality.of(a := inputTerm, b := outputTerm, c := input, d := body)) + } + lazy val outputEquality: Theorem = Lemma.generated(member(outputTerm) |- outputTerm === body) { + have(thesis) by Tautology.from(Pair.extensionality.of(a := inputTerm, b := outputTerm, c := input, d := body)) + } + } + + private val graphFunctionality: Theorem = { + val clauses = patternMatching.clauses + val forbidden: Seq[Expr[?]] = clauses.flatMap(clause => + clause.binders ++ clause.variables1 ++ clause.variables2 ++ + Seq(clause.body, clause.branchPremise, clause.specializedAdtTerm) + ) ++ Seq(inputTerm, outputTerm, alternateOutputTerm) + val allocated = collection.mutable.ArrayBuffer.empty[Variable[Ind]] + val arity = clauses.map(_.binders.size).maxOption.getOrElse(0) + def freshTuple(): Seq[Variable[Ind]] = + (0 until arity).map { _ => + val variable = Variable[Ind](freshId(forbidden ++ allocated, "graphArgument" + allocated.size)) + allocated += variable + variable + } + // Branch witnesses are bound independently; only the two compared tuples must differ. + val firstTuple = freshTuple() + val secondTuple = freshTuple() + val first = clauses.map(clause => GraphBranch(clause, firstTuple.take(clause.binders.size))) + val second = clauses.map(clause => GraphBranch(clause, secondTuple.take(clause.binders.size))) + val equality = outputTerm === alternateOutputTerm + + def compare(left: GraphBranch, right: GraphBranch, sameClause: Boolean): Theorem = + Lemma.generated((left.quantified(outputTerm), right.quantified(alternateOutputTerm)) |- equality) { + val direct = have((left.member(outputTerm), right.member(alternateOutputTerm)) |- equality) subproof { + assume(left.member(outputTerm)) + assume(right.member(alternateOutputTerm)) + if left.body == right.body then + val leftOutput = have(outputTerm === left.body) by Weakening(left.outputEquality) + val rightOutput = have(alternateOutputTerm === right.body) by Weakening(right.outputEquality.of(outputTerm := alternateOutputTerm)) + have(equality) by Congruence.from(leftOutput, rightOutput) + else + val leftTyped = have(left.premise) by Weakening(left.conditions) + val rightTyped = have(right.premise) by Weakening(right.conditions.of(outputTerm := alternateOutputTerm)) + val leftInput = have(inputTerm === left.input) by Weakening(left.inputEquality) + val rightInput = have(inputTerm === right.input) by Weakening(right.inputEquality.of(outputTerm := alternateOutputTerm)) + val inputsEqual = have(left.input === right.input) by Congruence.from(leftInput, rightInput) + + if sameClause then + val source = have(left.clause.injectivity.statement.right.head) by Tautology.from(left.clause.injectivity) + val injectivity = have( + (left.premise /\ right.premise) ==> + simplify((left.input === right.input) <=> (left.variables === right.variables)) + ) by InstantiateForallSeq(left.variables ++ right.variables)(source) + val pairs = left.variables.zip(right.variables) + val equations = pairs.map((from, to) => from === to) + val argumentsEqual = equations.map(equation => have(equation) by Tautology.from(injectivity, leftTyped, rightTyped, inputsEqual)) + val reflexive = have(left.body === left.body) by RightRefl + // The known substitution also works when the body contains lambdas. + val transported = have(equations.toSet |- left.body === right.body) by + RightSubst(pairs, (right.variables, left.body === right.body))(reflexive) + val bodiesEqual = have(left.body === right.body) by Tautology.from((transported +: argumentsEqual)*) + val leftOutput = have(outputTerm === left.body) by Weakening(left.outputEquality) + val rightOutput = have(alternateOutputTerm === right.body) by Weakening(right.outputEquality.of(outputTerm := alternateOutputTerm)) + have(equality) by Congruence.from(leftOutput, bodiesEqual, rightOutput) + else + val renaming = + left.clause.variables1.zip(left.variables).map((from, to) => from := to) ++ + right.clause.variables2.zip(right.variables).map((from, to) => from := to) + val incompatible = patternMatching.incompatible(left.clause.pattern, right.clause.pattern) + have(equality) by Tautology.from(incompatible.of(renaming*), leftTyped, rightTyped, inputsEqual) + } + val leftClosed = existsSeq(left.variables, left.member(outputTerm)) + val rightClosed = existsSeq(right.variables, right.member(alternateOutputTerm)) + val leftLifted = have((leftClosed, right.member(alternateOutputTerm)) |- equality) by + QuantifiersIntro(left.variables)(direct) + val bothLifted = have((leftClosed, rightClosed) |- equality) by QuantifiersIntro(right.variables)(leftLifted) + have(thesis) by Restate.from(bothLifted) + } + + val agreements = (for + i <- clauses.indices + j <- i until clauses.size + yield (i, j) -> compare(first(i), second(j), i == j)).toMap + + val firstCases = patternMatching.caseMembership(pair(inputTerm, outputTerm)) + val secondCases = patternMatching.caseMembership(pair(inputTerm, alternateOutputTerm)) + Lemma.generated((firstCases, secondCases) |- equality) { + val rows = clauses.indices.map { i => + val facts = clauses.indices.map[Thm] { j => + if i <= j then agreements((i, j)) + else agreements((j, i)).of(outputTerm := alternateOutputTerm, alternateOutputTerm := outputTerm) + } + have((first(i).quantified(outputTerm), secondCases) |- equality) by Tautology.from(facts*) + } + have(thesis) by Tautology.from(rows*) + } + } + + private val witnessSingleValued: Theorem = { + val bothOutputs = pair(inputTerm, outputTerm) ∈ witness /\ pair(inputTerm, alternateOutputTerm) ∈ witness + val equality = outputTerm === alternateOutputTerm + val allOutputs = ∀(outputTerm, ∀(alternateOutputTerm, bothOutputs ==> equality)) + + Lemma.generated(∀(inputTerm ∈ argType, allOutputs)) { + have(inputTerm ∈ argType ==> allOutputs) subproof { + assume(inputTerm ∈ argType) + val atInput = have( + inputTerm ∈ argType ==> ∀(outputTerm, pair(inputTerm, outputTerm) ∈ witness ==> patternMatching.caseMembership(pair(inputTerm, outputTerm))) + ) by InstantiateForall(inputTerm)(witnessMembershipByCases) + val graphMembership = have(∀(outputTerm, pair(inputTerm, outputTerm) ∈ witness ==> patternMatching.caseMembership(pair(inputTerm, outputTerm)))) by Tautology.from(atInput) + + have(bothOutputs ==> equality) subproof { + assume(bothOutputs) + val first = have( + pair(inputTerm, outputTerm) ∈ witness ==> patternMatching.caseMembership(pair(inputTerm, outputTerm)) + ) by InstantiateForall(outputTerm)(graphMembership) + val second = have( + pair(inputTerm, alternateOutputTerm) ∈ witness ==> patternMatching.caseMembership(pair(inputTerm, alternateOutputTerm)) + ) by InstantiateForall(alternateOutputTerm)(graphMembership) + have(equality) by Tautology.from(first, second, graphFunctionality) + } + thenHave(allOutputs) by QuantifiersIntro(Seq(outputTerm, alternateOutputTerm)) + } + thenHave(thesis) by RightForall + } + } + + private val witnessUniqueValue: Theorem = { + Lemma.generated( + contextualize( + ∀(inputTerm ∈ argType, ∃!(outputTerm, pair(inputTerm, outputTerm) ∈ witness)) + ) + ) { + + val pointwisePredicate = (out: Expr[Ind]) => pair(inputTerm, out) ∈ witness + val totalityAtInput = + if contextPremises.isEmpty then + have((inputTerm ∈ argType) ==> ∃(outputTerm, pointwisePredicate(outputTerm))) by + InstantiateForall(inputTerm)(witnessTotality) + else + assume(contextPremise) + witnessTotality.statement.right.head match + case _ ==> consequent => + have(consequent) by Restate.from(witnessTotality) + thenHave((inputTerm ∈ argType) ==> ∃(outputTerm, pointwisePredicate(outputTerm))) by + InstantiateForall(inputTerm) + case _ => throw UnreachableException + val singleValuedAtInput = have( + (inputTerm ∈ argType) ==> ∀( + outputTerm, + ∀( + alternateOutputTerm, + (pointwisePredicate(outputTerm) /\ pointwisePredicate(alternateOutputTerm)) ==> + (outputTerm === alternateOutputTerm) + ) + ) + ) by InstantiateForall(inputTerm)(witnessSingleValued) + + val pointwiseUnique = have( + (inputTerm ∈ argType) ==> ∃!(outputTerm, pointwisePredicate(outputTerm)) + ) by Tautology.from( + existsOneAlternativeDefinition of (P := λ(outputTerm, pointwisePredicate(outputTerm))), + totalityAtInput, + singleValuedAtInput + ) + + val core = have( + ∀(inputTerm, (inputTerm ∈ argType) ==> ∃!(outputTerm, pointwisePredicate(outputTerm))) + ) by RightForall(pointwiseUnique) + + have(thesis) by Restate.from(core) + } + } + + val witnessHasType: Theorem = { + Lemma.generated(contextualize(witness :: typ)) { + if !contextPremises.isEmpty then assume(contextPremise) + + have(witnessBody ⊆ witnessBound) by Tautology.from( + Comprehension.subset of ( + y := witnessBound, + φ := λ(pairWitness, caseMembership(pairWitness)) + ) + ) + val subsetBound = have(witness ⊆ witnessBound) by Congruence.from(lastStep, witnessDef) + + have(thesis) by Tautology.from( + BasicTheorems.funcBetweenEqInFuncSpace of ( + f := witness, + A := argType, + B := returnType + ), + Function.functionBetween.definition of ( + f := witness, + A := argType, + B := returnType + ), + relationBetween.definition of ( + R := witness, + X := argType, + Y := returnType + ), + subsetBound, + witnessUniqueValue + ) + } + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessProofContext.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessProofContext.scala new file mode 100644 index 000000000..e8506ef8f --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessProofContext.scala @@ -0,0 +1,45 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.proofs + +import lisa.maths.SetTheory.Base.Comprehension.| +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.encoding._ +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.utils.prooflib.Thm + +private[proofs] trait WitnessProofContext { + + protected val adt: SemanticADT + protected val argType: Expr[Ind] + protected val patternMatching: PatternSystem[Expr[Ind]] + protected val returnType: Expr[Ind] + protected val typ: Expr[Ind] + protected val witness: Expr[Ind] + protected val witnessDef: Thm + protected val witnessBound: Expr[Ind] + protected val pairWitness: Variable[Ind] + protected val caseMembership: Expr[Ind] => Expr[Prop] + protected val checkReturnType: Map[Clause[Expr[Ind]], Thm] + protected val contextPremises: Seq[Expr[Prop]] + + protected val inputTerm: Variable[Ind] = variable[Ind] + protected val outputTerm: Variable[Ind] = variable[Ind] + protected val alternateOutputTerm: Variable[Ind] = variable[Ind] + + protected val witnessBody: Expr[Ind] = { pairWitness ∈ witnessBound | caseMembership(pairWitness) } + + protected val patternCaseMembership: Expr[Ind] => Expr[Prop] = + patternMatching.caseMembership + + require( + caseMembership(pairWitness) == patternCaseMembership(pairWitness), + "CaseDefinedWitness expects caseMembership to coincide with patternMatching.caseMembership." + ) + + protected val contextPremise: Expr[Prop] = seqAnd(contextPremises) + + protected def contextualize(formula: Expr[Prop]): Expr[Prop] = + if contextPremises.isEmpty then formula else simplify(contextPremise ==> formula) + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/DecisionTree.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/DecisionTree.scala new file mode 100644 index 000000000..a2a8c92c8 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/DecisionTree.scala @@ -0,0 +1,158 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternNode +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternNode.Bind +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternNode.Construct +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT + +/** + * A disjoint, exhaustive case analysis over resolved constructor patterns. + */ +private[ADT] sealed trait DecisionTree + +/** + * Compiles and renders the typed case analysis retained by a pattern system. + */ +private[ADT] object DecisionTree { + + /** + * A sequence of constructor-field indices starting at the matched input. + */ + type Occurrence = List[Int] + + /** + * Inspects a value of the given specialized datatype, with one branch per constructor. + */ + final case class Split( + occurrence: Occurrence, + domain: SpecializedADT[?], + branches: Vector[(Constructor[?], DecisionTree)] + ) extends DecisionTree + + /** + * Selects a source clause and assigns its binders in their original order. + */ + final case class Leaf( + clauseIndex: Int, + bindings: Vector[(Variable[Ind], Occurrence)] + ) extends DecisionTree + + private final case class Column(occurrence: Occurrence, typ: Expr[Ind]) + private final case class Row( + patterns: List[Option[PatternNode]], + clauseIndex: Int, + bindings: Vector[(Variable[Ind], Occurrence)] + ) + + /** + * Checks exhaustiveness and disjointness while compiling the clauses in source order. + */ + def compile(domain: SpecializedADT[?], clauses: Seq[Construct]): Either[String, DecisionTree] = { + val rows = clauses.zipWithIndex.map { (pattern, index) => + Row(List(Some(pattern)), index, Vector.empty) + }.toList + new Compiler(clauses).split(List(Column(Nil, domain.term)), rows, 0, domain) + } + + private final class Compiler(clauses: Seq[Construct]) { + def split( + columns: List[Column], + rows: List[Row], + index: Int, + domain: SpecializedADT[?] + ): Either[String, DecisionTree] = { + val column = columns(index) + val substitutions = domain.base.typeVariablesSeq.zip(domain.typeArgs).map((v, arg) => v := arg) + val branches = Vector.newBuilder[(Constructor[?], DecisionTree)] + val constructors = domain.base.constructors.iterator + // An empty datatype produces an empty split even when there are no rows. + while constructors.hasNext do + val constructor = constructors.next() + val children = constructor.semantic.semanticSignature.zipWithIndex.map { case ((_, typ), field) => + Column(column.occurrence :+ field, typ.substitute(substitutions*)) + }.toList + val nextColumns = columns.patch(index, children, 1) + val nextRows = rows.flatMap { row => + row.patterns(index) match + case Some(Construct(head, _, arguments)) if head.id == constructor.id => + Some(row.copy(patterns = row.patterns.patch(index, arguments.map(Some(_)), 1))) + case Some(_: Construct) => None + case binder => + val bindings = binder match + case Some(Bind(v, _)) => row.bindings :+ (v -> column.occurrence) + case _ => row.bindings + Some( + row.copy( + patterns = row.patterns.patch(index, List.fill(children.size)(None), 1), + bindings = bindings + ) + ) + } + if nextRows.isEmpty then + val location = occurrenceName(column.occurrence) + return Left(s"Case for ${constructor.name} is missing at $location; the patterns are not exhaustive.") + descend(nextColumns, nextRows, column.occurrence) match + case Left(error) => return Left(error) + case Right(tree) => branches += constructor -> tree + Right(Split(column.occurrence, domain, branches.result())) + } + + private def descend(columns: List[Column], rows: List[Row], lastSplit: Occurrence): Either[String, DecisionTree] = { + val index = columns.indices.find { i => + rows.exists(_.patterns(i).exists(_.isInstanceOf[Construct])) + } + index match + case Some(i) => + ADT.unapply(columns(i).typ) match + case Some((adt, arguments)) => split(columns, rows, i, new SpecializedADT(adt, arguments)) + case None => Left(s"Cannot inspect a constructor at ${occurrenceName(columns(i).occurrence)} of type ${columns(i).typ}.") + case None => + rows match + case scala.collection.immutable.::(row, Nil) => + val remaining = columns.zip(row.patterns).collect { case (column, Some(Bind(v, _))) => + v -> column.occurrence + } + val positions = (row.bindings ++ remaining).toMap + val bindings = clauses(row.clauseIndex).binders.map(v => v -> positions(v)).toVector + Right(Leaf(row.clauseIndex, bindings)) + case Nil => Left(s"A case is missing at ${occurrenceName(lastSplit)}; the patterns are not exhaustive.") + case _ => + val matched = rows.map(row => clauses(row.clauseIndex)) + val unconditional = matched.forall(_.arguments.forall(_.isInstanceOf[Bind])) + val prefix = + if unconditional then s"Overlapping unconditional cases for ${matched.head.constructor.name}. " + else "" + Left(s"${prefix}Clauses ${rows.map(_.clauseIndex).mkString(", ")} overlap at ${occurrenceName(lastSplit)}.") + } + } + + /** + * Renders an occurrence for diagnostics. + */ + def occurrenceName(occurrence: Occurrence): String = + if occurrence.isEmpty then "x" else "x." + occurrence.mkString(".") + + /** + * Renders a resolved pattern without using names as constructor identities. + */ + def showPattern(pattern: PatternNode): String = pattern match + case Bind(v, _) => v.toString + case Construct(constructor, _, Nil) => constructor.name + case Construct(constructor, _, arguments) => s"${constructor.name}(${arguments.map(showPattern).mkString(", ")})" + + /** + * Renders the retained tree with its constructor branches and source-clause bindings. + */ + def render(tree: DecisionTree, indent: String = ""): String = tree match + case Leaf(index, bindings) => + val assignments = bindings.map((v, path) => s"$v = ${occurrenceName(path)}").mkString(", ") + s"${indent}clause $index${if bindings.isEmpty then "" else s" {$assignments}"}" + case Split(occurrence, domain, branches) => + val children = branches.map { (constructor, child) => + s"$indent ${constructor.name}:\n${render(child, indent + " ")}" + } + (s"${indent}split ${occurrenceName(occurrence)} : ${domain.term}" +: children).mkString("\n") +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/Pattern.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/Pattern.scala new file mode 100644 index 000000000..6ba9e7d89 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/Pattern.scala @@ -0,0 +1,351 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics + +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternNode +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternNode.Bind +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternNode.Construct +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternValidation +import lisa.maths.SetTheory.Types.ADT.encoding.SemanticConstructor +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.TypeSubstitution +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.instantiatedSemanticSignature +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.syntax.AST.SelfRef +import lisa.maths.SetTheory.Types.TypingHelpers.:: +import lisa.utils.prooflib.Thm + +/** + * A nested argument and the outer binder representing it in proofs. + */ +private[ADT] final case class BranchGuard(position: Int, binder: Variable[Ind], pattern: PatternNode) { + + /** + * The constructor term represented by the resolved argument. + */ + def guardTerm: Expr[Ind] = pattern.term +} + +/** + * The body-independent proof view of one resolved constructor pattern. + */ +final class Pattern private ( + private[ADT] val resolved: Construct, + val topBinders: Seq[Variable[Ind]], + avoid: Seq[Expr[?]] +) { + + /** + * The semantic constructor at the root. + */ + def semanticConstructor: SemanticConstructor = resolved.constructor.semantic + + /** + * The specialized datatype matched by this pattern. + */ + def specializedAdtTerm: Expr[Ind] = resolved.typ + + /** + * The diagnostic name of the outer constructor. + */ + def name: String = semanticConstructor.name + + /** + * The number of outer constructor arguments. + */ + def arity: Int = semanticConstructor.arity + + /** + * The constructor parameters specialized by the resolved root. + */ + lazy val typeSubstitutions: Seq[TypeSubstitution] = + semanticConstructor.typeVariablesSeq.zip(resolved.typeArguments).collect { case (v, arg) if v != arg => v := arg } + + /** + * Nested arguments paired with their synthetic outer binders. + */ + private[ADT] val guards: Seq[BranchGuard] = resolved.arguments.zipWithIndex.collect { case (pattern: Construct, i) => + BranchGuard(i, topBinders(i), pattern) + } + + private val innerTyped = guards.flatMap(_.pattern.typingSignature) + + /** + * User binders below the outer constructor arguments. + */ + val innerBinders: Seq[Variable[Ind]] = innerTyped.map(_._1) + + /** + * The specialized types of the nested user binders. + */ + val innerTypes: Seq[Expr[Ind]] = innerTyped.map(_._2) + + /** + * Outer argument binders followed by nested user binders. + */ + val binders: Seq[Variable[Ind]] = topBinders ++ innerBinders + + private val (outerVariables1, outerVariables2) = { + val forbidden = avoid ++ resolved.typeArguments ++ semanticConstructor.typeVariablesSeq ++ + semanticConstructor.variables1 ++ semanticConstructor.variables2 + val first = semanticConstructor.variables1.foldLeft(Vector.empty[Variable[Ind]]) { (vars, variable) => + vars :+ Variable[Ind](freshId(forbidden ++ vars, variable.id.name)) + } + val second = semanticConstructor.variables2.foldLeft(Vector.empty[Variable[Ind]]) { (vars, variable) => + vars :+ Variable[Ind](freshId(forbidden ++ first ++ vars, variable.id.name)) + } + (first, second) + } + + private val (innerVariables1, innerVariables2) = { + val forbidden = avoid ++ resolved.typeArguments ++ Seq(resolved.term, resolved.typ) ++ + binders ++ outerVariables1 ++ outerVariables2 + val first = innerBinders.indices.foldLeft(Vector.empty[Variable[Ind]]) { (vars, i) => + vars :+ Variable[Ind](freshId(forbidden ++ vars, s"$name/inner1$i")) + } + val second = innerBinders.indices.foldLeft(Vector.empty[Variable[Ind]]) { (vars, i) => + vars :+ Variable[Ind](freshId(forbidden ++ first ++ vars, s"$name/inner2$i")) + } + (first, second) + } + + /** + * The first canonical tuple of outer and inner proof variables. + */ + val variables1: Seq[Variable[Ind]] = outerVariables1 ++ innerVariables1 + + /** + * The second canonical tuple of outer and inner proof variables. + */ + val variables2: Seq[Variable[Ind]] = outerVariables2 ++ innerVariables2 + + /** + * The outer constructor applied to the supplied outer argument variables. + */ + def inputTermAt(vars: Seq[Variable[Ind]]): Expr[Ind] = + appSeq(semanticConstructor.term(resolved.typeArguments))(vars.take(arity)) + + /** + * The outer constructor term at the collected case binders. + */ + def inputTerm: Expr[Ind] = inputTermAt(binders) + + /** + * The outer constructor term at the first canonical tuple. + */ + def inputTerm1: Expr[Ind] = inputTermAt(variables1) + + /** + * The outer constructor term at the second canonical tuple. + */ + def inputTerm2: Expr[Ind] = inputTermAt(variables2) + + /** + * The input term used by branch theorem consumers. + */ + def freshInputTerm: Expr[Ind] = inputTerm2 + + /** + * The specialized types of the supplied outer and inner variables. + */ + def typingSignatureAt(vars: Seq[Variable[Ind]]): Seq[(Variable[Ind], Expr[Ind])] = + val (top, inner) = vars.splitAt(arity) + instantiatedSemanticSignature(semanticConstructor.semanticSignature(top), typeSubstitutions) ++ inner.zip(innerTypes) + + /** + * The typing assumptions for the supplied variable tuple. + */ + def typingPremisesAt(vars: Seq[Variable[Ind]]): Set[Expr[Prop]] = wellTypedSet(typingSignatureAt(vars)) + + /** + * The conjunction of typing assumptions for the supplied tuple. + */ + def typingFormulaAt(vars: Seq[Variable[Ind]]): Expr[Prop] = wellTypedFormula(typingSignatureAt(vars)) + + /** + * The typing assumptions at the collected case binders. + */ + def typingPremises: Set[Expr[Prop]] = typingPremisesAt(binders) + + /** + * The typing conjunction at the collected case binders. + */ + def typingFormula: Expr[Prop] = typingFormulaAt(binders) + + /** + * The typing conjunction at the second canonical tuple. + */ + def freshTypingFormula: Expr[Prop] = typingFormulaAt(variables2) + + /** + * Renames guard value binders while keeping their type arguments rigid. + */ + private[ADT] def guardsAt(vars: Seq[Variable[Ind]]): Seq[BranchGuard] = + val renaming = binders.zip(vars).toMap + guards.map(guard => BranchGuard(guard.position, vars(guard.position), guard.pattern.renameBinders(renaming))) + + /** + * The guards at the second canonical tuple. + */ + private[ADT] lazy val freshGuards: Seq[BranchGuard] = guardsAt(variables2) + + /** + * The guard conjunction at the supplied variables. + */ + def branchConditionAt(vars: Seq[Variable[Ind]]): Expr[Prop] = + seqAnd(guardsAt(vars).map(guard => guard.binder === guard.guardTerm)) + + /** + * The guard conjunction at the collected case binders. + */ + lazy val branchCondition: Expr[Prop] = branchConditionAt(binders) + + /** + * The guard conjunction at the second canonical tuple. + */ + lazy val freshBranchCondition: Expr[Prop] = branchConditionAt(variables2) + + /** + * The typing and guard assumptions at the supplied variables. + */ + def branchPremiseAt(vars: Seq[Variable[Ind]]): Expr[Prop] = + simplify(typingFormulaAt(vars) /\ branchConditionAt(vars)) + + /** + * The typing and guard assumptions at the collected case binders. + */ + def branchPremise: Expr[Prop] = branchPremiseAt(binders) + + /** + * The typing and guard assumptions at the first canonical tuple. + */ + def branchPremise1: Expr[Prop] = branchPremiseAt(variables1) + + /** + * The typing and guard assumptions at the second canonical tuple. + */ + def freshBranchPremise: Expr[Prop] = branchPremiseAt(variables2) + + /** + * The branch-selection condition before binding the inner witnesses. + */ + def branchSelectionBody(term: Expr[Ind]): Expr[Prop] = + val condition = freshBranchCondition /\ (term === freshInputTerm) + if innerBinders.isEmpty then condition + else wellTypedFormula(typingSignatureAt(variables2).drop(arity)) /\ condition + + /** + * The branch-selection condition with all inner witnesses bound. + */ + def branchSelectionDisjunct(term: Expr[Ind]): Expr[Prop] = + existsSeq(variables2.drop(arity), branchSelectionBody(term)) + + /** + * Matches a constructor case modulo bijective renaming of its value binders. + */ + def matchesConstructorCase(constructor: SemanticConstructor, args: Seq[Expr[Ind]]): Boolean = + if semanticConstructor != constructor || args.size != arity then false + else + val renaming = collection.mutable.Map.empty[Variable[Ind], Variable[Ind]] + val renamedBinders = collection.mutable.Set.empty[Variable[Ind]] + def matches(pattern: PatternNode, query: PatternNode): Boolean = (pattern, query) match + case (Bind(from, _), Bind(to, _)) => + renaming.get(from) match + case Some(mapped) => mapped == to + case None if renamedBinders.add(to) => + renaming(from) = to + true + case _ => false + case (Construct(c, types, children), Construct(d, otherTypes, otherChildren)) => + c.id == d.id && types == otherTypes && children.size == otherChildren.size && + children.zip(otherChildren).forall((p, q) => matches(p, q)) + case _ => false + val domain = new SpecializedADT(resolved.constructor.adt, resolved.typeArguments) + PatternValidation.resolveCase(resolved.constructor, args, domain).exists(query => matches(resolved, query)) + + /** + * Instantiates typing of the outer constructor application at the supplied arguments. + */ + def inputTypingAt(vars: Seq[Variable[Ind]], adtTerm: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + require(adtTerm == specializedAdtTerm, "Pattern.inputTypingAt expects the compiled specialized datatype.") + PatternProofs.inputTyping(this, vars.take(arity)) + + /** + * Proves injectivity of all outer and inner pattern binders under the branch premises. + */ + lazy val injectivity: Theorem = + if innerBinders.isEmpty then PatternProofs.constructorInjectivity(this) + else PatternProofs.injectivityCaseShape(this) + + private val recursivePaths: Map[Variable[Ind], List[Int]] = + def collect(node: PatternNode, path: List[Int]): Seq[(Variable[Ind], List[Int])] = node match + case Bind(v, _) => if path.length >= 2 then Seq(v -> path) else Seq.empty + case Construct(c, _, children) => + children.zip(c.semantic.syntacticSignature).zipWithIndex.flatMap { + case ((child, (_, SelfRef)), index) => collect(child, path :+ index) + case _ => Seq.empty + } + val freshening = binders.zip(variables2).toMap + collect(resolved, Nil).map((v, path) => freshening(v) -> path).toMap + + /** + * Nested binders reached only through recursive constructor fields. + */ + def recursiveAgreementPoints(recursiveType: Expr[Ind]): Seq[Variable[Ind]] = + if recursiveType == specializedAdtTerm then variables2.drop(arity).filter(recursivePaths.contains) + else Seq.empty + + /** + * Proves a nested recursive binder lies below the current height using its recorded field path. + */ + def recursiveAgreementPointInHeight(using + proof: lisa.SetTheoryLibrary.Proof, + line: sourcecode.Line, + file: sourcecode.File + )( + target: Variable[Ind], + recursiveType: Expr[Ind], + heightFun: Expr[Ind], + hValid: Thm, + currentIndex: Expr[Ind], + currentIndexInN: Thm, + argsTypedAtHeight: Thm, + leafTyping: Thm, + patternGuard: Thm + ): Thm = + require(recursiveAgreementPoints(recursiveType).contains(target), s"Pattern $name does not expose $target as a recursive agreement point.") + val path = recursivePaths(target) + val guard = freshGuards.find(_.position == path.head).get + val binderInHeight = have(guard.binder ∈ app(heightFun)(currentIndex)) by Tautology.from(argsTypedAtHeight) + val guardEq = have(guard.binder === guard.guardTerm) by Tautology.from(patternGuard) + val guardInHeight = have(guard.guardTerm ∈ app(heightFun)(currentIndex)) by Congruence.from(binderInHeight, guardEq) + PatternProofs.descendToBinder( + heightFun, + hValid, + currentIndex, + currentIndexInN, + leafTyping, + guard.pattern, + path.tail, + guardInHeight, + target + ) +} + +/** + * Constructs the proof view after the pattern has been resolved and validated. + */ +object Pattern { + + /** + * Builds outer proof binders fresh against the declaration and its ambient context. + */ + private[ADT] def fromResolved(root: Construct, avoid: Seq[Expr[?]] = Seq.empty): Pattern = + val forbidden = avoid ++ Seq(root.term, root.typ) ++ root.typeArguments ++ root.binders + val top = root.arguments.zipWithIndex.foldLeft(Vector.empty[Variable[Ind]]) { + case (vars, (Bind(v, _), _)) => vars :+ v + case (vars, (_, i)) => + vars :+ Variable[Ind](freshId(forbidden ++ vars, root.constructor.semantic.name + s"/arg$i")) + } + new Pattern(root, top, avoid) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/PatternProofs.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/PatternProofs.scala new file mode 100644 index 000000000..151b40720 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/PatternProofs.scala @@ -0,0 +1,681 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics + +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Ordinals.Integer.nonZeroOmegaHasPredecessor +import lisa.maths.SetTheory.Ordinals.Integer.subsetSuccessor +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternNode +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternNode.Bind +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternNode.Construct +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.DecisionTree.Leaf +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.DecisionTree.Occurrence +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.DecisionTree.Split +import lisa.maths.SetTheory.Types.ADT.encoding.SemanticConstructor +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.instantiate +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.proofs.PropositionalFacts.altEqualityTransitivity +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.prooflib.BasicStep.LeftExists +import lisa.utils.prooflib.BasicStep.LeftOr +import lisa.utils.prooflib.BasicStep.Restate +import lisa.utils.prooflib.BasicStep.RightExists +import lisa.utils.prooflib.BasicStep.RightForall +import lisa.utils.prooflib.InstantiateForall +import lisa.utils.prooflib.InstantiateForallSeq +import lisa.utils.prooflib.QuantifiersIntro +import lisa.utils.prooflib.Thm + +/** + * Coverage, branch selection, and incompatibility proofs using resolved patterns. + */ +private[ADT] object PatternProofs { + + /** + * The type of a pattern node, including opaque types at variable leaves. + */ + type Ty = Expr[Ind] + + private def childTypes(c: Constructor[?], targs: Seq[Expr[Ind]]): Seq[Ty] = + val subst = c.semantic.typeVariablesSeq.zip(targs).map((v, a) => v := a) + c.semantic.semanticSignature2.map { case (_, tyTerm) => + tyTerm.substitute(subst*) + } + + private def renderCase(pp: Pattern): String = + DecisionTree.showPattern(pp.resolved) + + private def instantiatePrefix(formula: Expr[Prop], args: Seq[Expr[Ind]]): Expr[Prop] = + args.foldLeft(formula) { (current, arg) => + current match + case forall(qv, phi) => phi.substitute(qv := arg) + case _ => current + } + + private def instAll(thm: Theorem, terms: Seq[Expr[Ind]])(using proof: lisa.SetTheoryLibrary.Proof): Unit = + val source = have(thm.statement.right.head) by Tautology.from(thm) + val instantiated = instantiatePrefix(source.statement.right.head, terms) + have(instantiated) by InstantiateForallSeq(terms)(source) + + /** + * Proves typing of a resolved pattern from its binder typings. + */ + private def typing(using + proof: lisa.SetTheoryLibrary.Proof + )( + pattern: PatternNode, + premises: Seq[Thm] = Seq.empty + ): Thm = + val goal = pattern.term :: pattern.typ + pattern match + case Bind(_, _) => have(goal) by Tautology.from(premises*) + case Construct(constructor, typeArgs, arguments) => + val argumentFacts = arguments.map(argument => typing(argument, premises)) + val substitutions = + constructor.typeVariablesSeq.zip(typeArgs).map((v, term) => v := term) ++ + constructor.semantic.variables.zip(arguments.map(_.term)).map((v, term) => v := term) + val introduction: Thm = + if substitutions.isEmpty then constructor.introApp else constructor.introApp.of(substitutions*) + have(goal) by Tautology.from((introduction +: argumentFacts)*) + + private def renderAlignedGuards( + p1: Pattern, + p2: Pattern + ): String = + val byPos1 = p1.guards.map(g => g.position -> g.pattern).toMap + val byPos2 = p2.guards.map(g => g.position -> g.pattern).toMap + val sharedPositions = byPos1.keySet.intersect(byPos2.keySet).toSeq.sorted + if sharedPositions.isEmpty then "none" + else + sharedPositions + .map { pos => + val left = DecisionTree.showPattern(byPos1(pos)) + val right = DecisionTree.showPattern(byPos2(pos)) + s"arg $pos: $left vs $right" + } + .mkString("; ") + + def divergePath(p: PatternNode, q: PatternNode): Option[List[Int]] = (p, q) match + case (Construct(c, _, _), Construct(d, _, _)) if c.id != d.id => Some(Nil) + case (Construct(_, _, as), Construct(_, _, bs)) => + as.lazyZip(bs) + .zipWithIndex + .iterator + .map { case ((a, b), i) => divergePath(a, b).map(i :: _) } + .collectFirst { case Some(path) => path } + case _ => None + + // The disjointness theorem for two constructors of the same ADT. Only needed to + // capture the ADT's arity so the two constructors line up. Like `injectivity`, the + // result is closed over the ADT's type variables, so callers instantiate it by + // passing the type arguments ahead of the constructor arguments. + private def crossInj(adt: ADT[?], c: Constructor[?], d: Constructor[?]): Theorem = + adt match + case a: ADT[n] => + a.disjointness(c.asInstanceOf[Constructor[n]], d.asInstanceOf[Constructor[n]]) + + // The top constructor's injectivity for a pattern, specialized to its type args. + // (Used directly so it is unaffected by a pattern's overridden `injectivity`.) + def constructorInjectivity(pp: Pattern): Theorem = + val base = pp.semanticConstructor.injectivity + if pp.typeSubstitutions.isEmpty then base + else + Lemma.generated(base.statement.substitute(pp.typeSubstitutions*)) { + have(thesis) by Restate.from(base.of(pp.typeSubstitutions*)) + } + + // ════════════════════════════════════════════════════════════════════════ + // Disjointness: binderTypings |- ¬(pattern_i === pattern_j) + // ════════════════════════════════════════════════════════════════════════ + // TODO:??? factorize with injectEq (see also incompatibleProof) + def incompatibleProof(p: PatternNode, q: PatternNode): Theorem = + val path = divergePath(p, q).getOrElse( + throw new IllegalArgumentException("incompatibleProof: patterns are compatible (overlap).") + ) + val tp = p.term + val tq = q.term + val typedHyps = wellTypedSet(p.typingSignature ++ q.typingSignature).toSeq + + Lemma.generated((typedHyps |- !(tp === tq))) { sp ?=> + typedHyps.foreach(h => assume(h)) + + def typings(args: List[PatternNode]): Seq[Thm] = args.map(typing(_)) + + // Leaves `¬(termOf(p) === termOf(q))` as the latest fact. + def disprove(p: PatternNode, q: PatternNode, path: List[Int]): Unit = + val tpc = p.term; val tqc = q.term + (p, q) match + case (Construct(c, targs, as), Construct(d, _, bs)) if path.isEmpty => + // cross-constructor injectivity: typed ⇒ ¬(c(..) === d(..)) + instAll(crossInj(c.adt, c, d), targs ++ as.map(_.term) ++ bs.map(_.term)) + val injInst = lastStep + val argTypings = typings(as) ++ typings(bs) + have(!(tpc === tqc)) by Tautology.from((injInst +: argTypings)*) + case (Construct(c, targs, as), Construct(_, _, bs)) => + val i = path.head + disprove(as(i), bs(i), path.tail) + val argDiseq = lastStep + // same-head injectivity: typed ⇒ ((c(as) === c(bs)) <=> (as === bs)) + instAll(c.injectivity, targs ++ as.map(_.term) ++ bs.map(_.term)) + val injInst = lastStep + val argTypings = typings(as) ++ typings(bs) + have(!(tpc === tqc)) by Tautology.from((injInst +: argDiseq +: argTypings)*) + case _ => throw new IllegalArgumentException("disprove: malformed path.") + + disprove(p, q, path) + have(thesis) by Tautology.from(lastStep) + } + + private def proveByCongruence(using proof: lisa.SetTheoryLibrary.Proof)(formula: Expr[Prop], eqFacts: List[Thm]): Thm = + formula match + case lhs /\ rhs => + val leftFact = proveByCongruence(lhs, eqFacts) + val rightFact = proveByCongruence(rhs, eqFacts) + have(formula) by RightAnd(leftFact, rightFact) + case _ => + have(formula) by Congruence.from(eqFacts*) + + private def finishCoverLeaf( + variables: Seq[Variable[Ind]], + witnesses: Seq[Expr[Ind]], + body: Expr[Prop], + condition: Expr[Prop], + inputEquality: Expr[Prop], + equalities: List[Expr[Prop]], + goal: Expr[Prop] + )(using proof: lisa.SetTheoryLibrary.Proof): Unit = + val substitutions = variables.zip(witnesses).map((v, term) => v := term) + val equalityFacts = equalities.map(eq => have(eq) by Restate) + val guardFact = proveByCongruence(condition.substitute(substitutions*), equalityFacts) + val inputFact = have(inputEquality.substitute(substitutions*)) by Congruence.from(equalityFacts*) + have(body.substitute(substitutions*)) by Tautology.from(guardFact, inputFact) + for i <- variables.indices.reverse do + val quantified = existsSeq( + variables.drop(i), + body.substitute(variables.take(i).zip(witnesses.take(i)).map((v, term) => v := term)*) + ) + thenHave(quantified) by RightExists + have(goal) by Tautology.from(lastStep) + + // Occurrence values and equality formulas survive descent; proof facts stay in their local subproof. + private def coverTree( + tree: DecisionTree, + values: Map[Occurrence, Expr[Ind]], + equalities: List[Expr[Prop]], + goal: Expr[Prop], + avoid: Seq[Expr[?]] + )( + leaf: (Leaf, Map[Occurrence, Expr[Ind]], List[Expr[Prop]]) => lisa.SetTheoryLibrary.Proof ?=> Unit + )(using proof: lisa.SetTheoryLibrary.Proof): Unit = tree match + case selected: Leaf => leaf(selected, values, equalities) + case Split(occurrence, domain, branches) => + val value = values(occurrence) + val forbidden = avoid ++ proof.assumptions ++ values.values ++ Seq(goal, domain.term) + val cases = branches.map { (constructor, subtree) => + val arguments = (0 until constructor.semantic.arity).foldLeft(Vector.empty[Variable[Ind]]) { (args, i) => + args :+ Variable[Ind](freshId(forbidden ++ args, s"caseArg$i")) + } + val equation = value === appSeq(constructor.semantic.term(domain.typeArgs))(arguments) + val premise = wellTypedFormula(arguments.zip(childTypes(constructor, domain.typeArgs))) /\ equation + val childValues = values ++ arguments.zipWithIndex.map((arg, i) => (occurrence :+ i) -> arg) + val branch = have(premise |- goal) subproof { + assume(premise) + coverTree(subtree, childValues, equalities :+ equation, goal, avoid)(leaf) + } + val quantified = existsSeq(arguments, premise) + val fact = have(quantified |- goal) by QuantifiersIntro(arguments)(branch) + (quantified, fact) + } + val disjunction = seqOr(cases.map(_._1)) + val elimination: Thm = if domain.typeArgs.isEmpty then domain.base.elim else domain.base.elim.of(domain.typeArgs*) + val instantiated = have(value :: domain.term ==> disjunction) by InstantiateForall(value)(elimination) + val exhaustive = have(disjunction) by Tautology.from(instantiated) + if cases.isEmpty then have(goal) by Tautology.from(exhaustive) + else + val combined = + if cases.size == 1 then have(disjunction |- goal) by Restate.from(cases.head._2) + else have(disjunction |- goal) by LeftOr((cases.map(_._2)).map(_.kernel)) + have(goal) by Tautology.from(exhaustive, combined) + + private def rootSplit(tree: DecisionTree): Split = tree match + case root: Split if root.occurrence.isEmpty => root + case _ => throw new IllegalArgumentException("A compiled pattern system must split its input at the root.") + + private def patternVariables(patterns: Seq[Pattern]): Seq[Expr[?]] = + patterns.flatMap(p => p.binders ++ p.variables2 ++ Seq(p.resolved.term, p.specializedAdtTerm)) + + private def innerWitnesses( + pattern: Pattern, + leaf: Leaf, + values: Map[Occurrence, Expr[Ind]] + ): Seq[Expr[Ind]] = + val positions = leaf.bindings.toMap + pattern.binders.drop(pattern.arity).map(v => values(positions(v))) + + /** + * Proves whole-domain coverage by traversing the retained tree. + */ + def coverageCaseShape(tree: DecisionTree, patterns: Seq[Pattern]): Theorem = + val root = rootSplit(tree) + val avoid = patternVariables(patterns) :+ root.domain.term + val input = Variable[Ind](freshId(avoid, "scrutX")) + val disjuncts = patterns.map(p => existsSeq(p.variables2, p.freshBranchPremise /\ (input === p.freshInputTerm))) + val goal = simplify(seqOr(disjuncts)) + Lemma.generated(∀(input :: root.domain.term, goal)) { + have(input :: root.domain.term ==> goal) subproof { + assume(input :: root.domain.term) + coverTree(root, Map(Nil -> input), Nil, goal, avoid) { (leaf, values, equalities) => + val pattern = patterns(leaf.clauseIndex) + val witnesses = (0 until pattern.arity).map(i => values(List(i))) ++ innerWitnesses(pattern, leaf, values) + val equation = input === pattern.freshInputTerm + finishCoverLeaf(pattern.variables2, witnesses, pattern.freshBranchPremise /\ equation, pattern.freshBranchCondition, equation, equalities, goal) + } + } + thenHave(thesis) by RightForall + } + + /** + * Proves branch selection from the retained subtree of the known outer constructor. + */ + def branchSelectionForCaseShape( + tree: DecisionTree, + constructor: SemanticConstructor, + term: Expr[Ind], + patterns: Seq[Pattern] + ): Theorem = + val root = rootSplit(tree) + val (head, subtree) = root.branches + .find(_._1.semantic == constructor) + .getOrElse( + throw new IllegalArgumentException(s"Constructor ${constructor.name} does not belong to this pattern system.") + ) + val selected = patterns.filter(_.semanticConstructor == constructor) + val top = selected.head.variables2.take(constructor.arity) + val typing = wellTypedFormula(top.zip(childTypes(head, root.domain.typeArgs))) + val inputEquality = term === appSeq(constructor.term(root.domain.typeArgs))(top) + val goal = seqOr(selected.map(_.branchSelectionDisjunct(term))) + val values: Map[Occurrence, Expr[Ind]] = Map(Nil -> term) ++ top.zipWithIndex.map((v, i) => List(i) -> v) + val avoid = patternVariables(patterns) ++ Seq(term, root.domain.term) + Lemma.generated(forallSeq(top, (typing /\ inputEquality) ==> goal)) { + have((typing /\ inputEquality) ==> goal) subproof { + assume(typing) + assume(inputEquality) + coverTree(subtree, values, List(inputEquality), goal, avoid) { (leaf, values, equalities) => + val pattern = patterns(leaf.clauseIndex) + finishCoverLeaf( + pattern.variables2.drop(pattern.arity), + innerWitnesses(pattern, leaf, values), + pattern.branchSelectionBody(term), + pattern.freshBranchCondition, + term === pattern.freshInputTerm, + equalities, + goal + ) + } + } + have(thesis) by QuantifiersIntro(top)(lastStep) + } + + // ════════════════════════════════════════════════════════════════════════ + // Disjointness in the trait shape: + // (p1.branchPremise1 ∧ p2.freshBranchPremise) ⟹ ¬(p1.inputTerm1 = p2.inputTerm2) + // Same outer structure as the existing nullary `incompatible`; the final + // guard-term disequality uses the recursive divergence peel instead. + // ════════════════════════════════════════════════════════════════════════ + def incompatibleCaseShape(p1: Pattern, p2: Pattern): Theorem = + incompatibleCaseShapeN(p1, p2) + + private[semantics] def sameHeadGuardEquality( + p1: Pattern, + p2: Pattern, + guard1: BranchGuard, + guard2: BranchGuard + ): Theorem = + Lemma.generated( + (p1.branchPremise1 /\ p2.freshBranchPremise /\ (p1.inputTerm1 === p2.inputTerm2)) ==> + (guard1.guardTerm === guard2.guardTerm) + ) { + val branch = assume(p1.branchPremise1 /\ p2.freshBranchPremise /\ (p1.inputTerm1 === p2.inputTerm2)) + val branch1Typed = have(p1.branchPremise1) by Tautology.from(branch) + val branch2Typed = have(p2.freshBranchPremise) by Tautology.from(branch) + val inputsEqual = have(p1.inputTerm1 === p2.inputTerm2) by Tautology.from(branch) + + val ctorInj = constructorInjectivity(p1) + val injectivitySchema = have(ctorInj.statement.right.head) by Tautology.from(ctorInj) + val arguments = p1.variables1.take(p1.arity) ++ p2.variables2.take(p2.arity) + val injectivityAtVars = have(instantiatePrefix(injectivitySchema.statement.right.head, arguments)) by + InstantiateForallSeq(arguments)(injectivitySchema) + + val guardedArgsEqual = have(guard1.binder === guard2.binder) by + Tautology.from(injectivityAtVars, branch1Typed, branch2Typed, inputsEqual) + val guard1Eq = have(guard1.binder === guard1.guardTerm) by Tautology.from(branch1Typed) + val guard2Eq = have(guard2.binder === guard2.guardTerm) by Tautology.from(branch2Typed) + val guard1EqRev = have(guard1.guardTerm === guard1.binder) by Congruence.from(guard1Eq) + val guard1ToGuard2Binder = + have(guard1.guardTerm === guard2.binder) by Tautology.from( + altEqualityTransitivity of (x := guard1.guardTerm, y := guard1.binder, z := guard2.binder), + guard1EqRev, + guardedArgsEqual + ) + have(thesis) by Tautology.from( + altEqualityTransitivity of (x := guard1.guardTerm, y := guard2.binder, z := guard2.guardTerm), + guard1ToGuard2Binder, + guard2Eq + ) + } + + private def incompatibleCaseShapeN( + p1: Pattern, + p2: Pattern + ): Theorem = + if p1.semanticConstructor != p2.semanticConstructor then + // different top constructors — `¬(c1(top1) = c2(top2))` from cross injectivity. + { + val adt = p1.resolved.constructor.adt + val targs = p1.resolved.typeArguments + val c1 = p1.resolved.constructor + val c2 = p2.resolved.constructor + val top1 = p1.variables1.take(p1.arity).map(x => x: Expr[Ind]) + val top2 = p2.variables2.take(p2.arity).map(x => x: Expr[Ind]) + Lemma.generated((p1.branchPremise1 /\ p2.freshBranchPremise) ==> !(p1.inputTerm1 === p2.inputTerm2)) { + val branch = assume(p1.branchPremise1 /\ p2.freshBranchPremise) + val b1 = have(p1.branchPremise1) by Tautology.from(branch) + val b2 = have(p2.freshBranchPremise) by Tautology.from(branch) + val inj = crossInj(adt, c1, c2) + val fact0 = have(inj.statement.right.head) by Tautology.from(inj) + val instArgs = targs ++ top1 ++ top2 + val target = instantiatePrefix(fact0.statement.right.head, instArgs) + val fact = have(target) by InstantiateForallSeq(instArgs)(fact0) + have(!(p1.inputTerm1 === p2.inputTerm2)) by Tautology.from(fact, b1, b2) + } + } else + val guards1 = p1.guardsAt(p1.variables1) + val guards2 = p2.freshGuards.map(guard => guard.position -> guard).toMap + val selectedGuards = guards1.iterator + .flatMap(guard => guards2.get(guard.position).map(guard -> _)) + .collectFirst { + case (guard1, guard2) if divergePath(guard1.pattern, guard2.pattern).nonEmpty => + (guard1, guard2) + } + .getOrElse( + throw new IllegalArgumentException( + s"""incompatibleCaseShape rejected two overlapping nested cases for constructor ${p1.semanticConstructor.name}. + |case 1: ${renderCase(p1)} + |case 2: ${renderCase(p2)} + |No divergent aligned guard pair was found, so the two cases still overlap. + |Aligned guarded positions: ${renderAlignedGuards(p1, p2)} + |""".stripMargin + ) + ) + val (guard1, guard2) = selectedGuards + + { + Lemma.generated( + (p1.branchPremise1 /\ p2.freshBranchPremise) ==> !(p1.inputTerm1 === p2.inputTerm2) + ) { sp ?=> + { + // --- outer structure (mirrors the existing incompatible) --- + val branch = assume(p1.branchPremise1 /\ p2.freshBranchPremise) + assume(p1.inputTerm1 === p2.inputTerm2) + val inputsEqual = have(p1.inputTerm1 === p2.inputTerm2) by Hypothesis + + val commonEquality = sameHeadGuardEquality(p1, p2, guard1, guard2) + val guardTermsEqual = have(guard1.guardTerm === guard2.guardTerm) by Tautology.from(commonEquality, branch, inputsEqual) + + // the new part: guard terms are distinct by the recursive peel + val rp1 = guard1.pattern; val rp2 = guard2.pattern + val guardDisequalityKernel = incompatibleProof(rp1, rp2) + val guardTypingFacts = + wellTypedSet(rp1.typingSignature ++ rp2.typingSignature).toSeq.map(h => have(h) by Tautology.from(branch)) + val guardDisequality = have(!(guard1.guardTerm === guard2.guardTerm)) by + Tautology.from((guardDisequalityKernel +: guardTypingFacts)*) + + have(thesis) by Tautology.from(guardTermsEqual, guardDisequality) + } + } + } + + // ════════════════════════════════════════════════════════════════════════ + // Pattern-level injectivity (well-definedness), the shape `samePatternBody + // Equality` consumes: + // ∀(v1 ++ v2). (branchPremise(v1) ∧ branchPremise(v2)) + // ⟹ ((inputTerm(v1) = inputTerm(v2)) ⇔ (v1 === v2)) + // Forward direction uses the top constructor injectivity plus a recursive + // injective descent through the guard term (the mirror of `disprove`). + // ════════════════════════════════════════════════════════════════════════ + def injectivityCaseShape(pp: Pattern): Theorem = + val v1 = pp.variables1.toList; val v2 = pp.variables2.toList + val ar = pp.arity + val (top1, _) = v1.splitAt(ar); val (top2, _) = v2.splitAt(ar) + val A = pp.inputTermAt(v1) === pp.inputTermAt(v2) + val seqEqV = seqEq(v1, v2) + val bp1 = pp.branchPremiseAt(v1); val bp2 = pp.branchPremiseAt(v2) + val guards1 = pp.guardsAt(pp.variables1) + val guards2 = pp.freshGuards + val topInjThm: Theorem = constructorInjectivity(pp) + + Lemma.generated(forallSeq(v1 ++ v2, (bp1 /\ bp2) ==> simplify(A <=> seqEqV))) { + // From `termOf(rp1) = termOf(rp2)` derive the leaf (inner-binder) equalities, + // indexed by the exact binder pair they justify. + def injectEq(using + proof: lisa.SetTheoryLibrary.Proof + )( + rp1: PatternNode, + rp2: PatternNode, + eqFact: Thm + ): Map[(Variable[Ind], Variable[Ind]), Thm] = + (rp1, rp2) match + case (Bind(vl, _), Bind(vr, _)) => Map((vl, vr) -> eqFact) + case (Construct(c, targs, as1), Construct(_, _, as2)) => + val t1 = as1.map(_.term) + val t2 = as2.map(_.term) + instAll(c.injectivity, targs ++ t1 ++ t2) + val injInst = lastStep + val tys = as1.map(typing(_)) ++ as2.map(typing(_)) + as1.indices.toList.foldLeft(Map.empty[(Variable[Ind], Variable[Ind]), Thm]) { (acc, i) => + val argEq = have(t1(i) === t2(i)) by Tautology.from((injInst +: eqFact +: tys)*) + acc ++ injectEq(as1(i), as2(i), argEq) + } + case _ => throw new IllegalArgumentException("injectEq: mismatched guard structure.") + + def topBinderEqualities(using proof: lisa.SetTheoryLibrary.Proof)(topEq: Thm): Map[(Variable[Ind], Variable[Ind]), Thm] = + top1 + .zip(top2) + .map { (left, right) => + val eqFact: Thm = have((left: Expr[Ind]) === (right: Expr[Ind])) by Tautology.from(topEq) + (left, right) -> eqFact + } + .toMap + + def orderedBinderEqualities(using + proof: lisa.SetTheoryLibrary.Proof + )( + topEqMap: Map[(Variable[Ind], Variable[Ind]), Thm], + leafEqMap: Map[(Variable[Ind], Variable[Ind]), Thm] + ): Seq[Thm] = + v1.zip(v2).map { (left, right) => + topEqMap + .get((left, right)) + .orElse(leafEqMap.get((left, right))) + .getOrElse( + throw new IllegalArgumentException( + s"injectivityCaseShape: missing equality proof for binder pair (${left}, ${right}). \n ${topEqMap.keys} \n ${leafEqMap.keys}" + ) + ) + } + + have((bp1 /\ bp2) ==> simplify(A <=> seqEqV)) subproof { + assume(bp1); assume(bp2) + val typed1 = have(pp.typingFormulaAt(v1)) by Tautology + val typed2 = have(pp.typingFormulaAt(v2)) by Tautology + + val fwd = have(A ==> seqEqV) subproof { branchProof ?=> + assume(A) + // top constructor injectivity at the (identity) top variables + instAll(topInjThm, top1.map(x => x: Expr[Ind]) ++ top2.map(x => x: Expr[Ind])) + val topInj = lastStep + val topEq = have(seqEq(top1, top2)) by Tautology.from(topInj, typed1, typed2) + val leafEqMap = guards1.zip(guards2).foldLeft(Map.empty[(Variable[Ind], Variable[Ind]), Thm]) { case (acc, (guard1, guard2)) => + require( + guard1.position == guard2.position, + s"injectivityCaseShape: guard positions do not align (${guard1.position} vs ${guard2.position})." + ) + // guard terms equal: g(inner1) = guard1.binder = guard2.binder = g(inner2) + val gb = have(guard1.binder === guard2.binder) by Tautology.from(topEq) + val g1 = have(guard1.binder === guard1.guardTerm) by Tautology + val g2 = have(guard2.binder === guard2.guardTerm) by Tautology + val g1r = have(guard1.guardTerm === guard1.binder) by Congruence.from(g1) + val g1b2 = have(guard1.guardTerm === guard2.binder) by Tautology.from(altEqualityTransitivity of (x := guard1.guardTerm, y := guard1.binder, z := guard2.binder), g1r, gb) + val guardEq = have(guard1.guardTerm === guard2.guardTerm) by Tautology.from(altEqualityTransitivity of (x := guard1.guardTerm, y := guard2.binder, z := guard2.guardTerm), g1b2, g2) + acc ++ injectEq( + guard1.pattern, + guard2.pattern, + guardEq + ) + } + val topEqMap = topBinderEqualities(topEq) + val componentEqs = orderedBinderEqualities(topEqMap, leafEqMap) + have(seqEqV) by Tautology.from(componentEqs*) + } + val bwd = have(seqEqV ==> A) subproof { + assume(seqEqV) + val topEqs = top1.zip(top2).map((a, b) => have((a: Expr[Ind]) === (b: Expr[Ind])) by Tautology) + have(A) by Congruence.from(topEqs*) + } + have(simplify(A <=> seqEqV)) by Tautology.from(fwd, bwd) + } + have(thesis) by QuantifiersIntro(v1 ++ v2)(lastStep) + } + + /** + * Instantiates typing of a resolved root constructor at supplied value arguments. + */ + def inputTyping(pattern: Pattern, variables: Seq[Variable[Ind]])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + require(variables.size == pattern.arity, "Constructor typing requires one value per argument.") + val substitutions = pattern.typeSubstitutions ++ pattern.semanticConstructor.variables.zip(variables).map((from, to) => from := to) + instantiate(pattern.resolved.constructor.introApp, substitutions) + + /** + * Follows a validated recursive field path to prove the target's height bound. + */ + def descendToBinder(using + proof: lisa.SetTheoryLibrary.Proof, + line: sourcecode.Line, + file: sourcecode.File + )( + heightFun: Expr[Ind], + hValid: Thm, + currentIndex: Expr[Ind], + currentIndexInN: Thm, + leafTyping: Thm, + currentPat: PatternNode, + path: List[Int], + currentInHeight: Thm, + target: Variable[Ind] + ): Thm = + currentPat match + case Bind(v, _) => + if path.nonEmpty || v != target then throw new IllegalArgumentException(s"Asked to descend to $target but reached unrelated binder $v.") + currentInHeight + + case Construct(c, targs, args) => + require(path.nonEmpty && c.semantic.syntacticSignature(path.head)._2 == SelfRef, "Height descent must follow recursive constructor fields.") + val currentAdt = c.adt + val predVar = Variable[Ind](freshId(proof.assumptions ++ Seq(currentIndex, target, heightFun, currentPat.term, currentPat.typ), "predVar")) + val currentTerm = currentPat.term + val levelSubsts = currentAdt.semantic.typeVariablesSeq.zip(targs).map((v, a) => v := a) + val currentInZero = { + have(!(currentTerm ∈ app(heightFun)(∅))) by Tautology.from( + hValid, + currentAdt.semantic.height.zeroAt(levelSubsts, Seq(h := heightFun, x := currentTerm)) + ) + } + + val currentIndexNonZero = have(currentIndex =/= ∅) subproof { + val currentIsZero = assume(currentIndex === ∅) + have(thesis) by Congruence.from(currentInHeight, currentInZero, currentIsZero) + } + + val predecessorTheoremAtIndex = have( + (currentIndex ∈ N, currentIndex =/= ∅) |- ∃(predVar, predVar ∈ N /\ (currentIndex === S(predVar))) + ) by Tautology.from( + nonZeroOmegaHasPredecessor.of(α := currentIndex, β := predVar) + ) + have(currentIndex =/= ∅ |- ∃(predVar, predVar ∈ N /\ (currentIndex === S(predVar)))) subproof { + assume(currentIndex =/= ∅) + have(thesis) by Tautology.from(currentIndexInN, predecessorTheoremAtIndex) + } + val predWitnessAtIndex = have(∃(predVar, predVar ∈ N /\ (currentIndex === S(predVar)))) by Cut( + currentIndexNonZero, + lastStep + ) + + have( + (predVar ∈ N /\ (currentIndex === S(predVar))) |- target ∈ app(heightFun)(currentIndex) + ) subproof { + assume(predVar ∈ N /\ (currentIndex === S(predVar))) + val currentEqSucc = have(currentIndex === S(predVar)) by Tautology + val predInN = have(predVar ∈ N) by Tautology + + val currentInSuccPred = have(currentTerm ∈ app(heightFun)(S(predVar))) by Congruence.from( + currentInHeight, + currentEqSucc + ) + + val argTerms: Seq[Expr[Ind]] = args.map(_.term) + val argTypings = args.map(argument => typing(argument, Seq(leafTyping))) + val semanticSubsts = c.semantic.typeVariablesSeq.zip(targs).map((v, a) => v := a) + val semanticSigAtArgs = + argTerms.zip(c.semantic.semanticSignature2.map(_._2.substitute(semanticSubsts*).asInstanceOf[Expr[Ind]])) + val argsTypedSemantic = { have(wellTypedFormula(semanticSigAtArgs)) by Tautology.from(argTypings*) } + val heightSigAtArgs = argTerms.zip(c.semantic.syntacticSignature).map { + case (term, (_, SelfRef)) => term -> app(heightFun)(predVar) + case (term, (_, TypeArg(name))) => term -> typeExprToTerm(name).substitute(semanticSubsts*).asInstanceOf[Expr[Ind]] + } + val recursiveAtPred = c.semantic.recursiveArgInHeightAt(semanticSubsts, argTerms)(heightFun, predVar) + val childTypingsAtPred = { + have(wellTypedFormula(heightSigAtArgs)) by Tautology.from( + hValid, + predInN, + argsTypedSemantic, + currentInSuccPred, + recursiveAtPred + ) + } + + val childIdx = path.head + val childTerm = argTerms(childIdx) + val childInPred = have(childTerm ∈ app(heightFun)(predVar)) by Tautology.from(childTypingsAtPred) + val innerAtPred = descendToBinder( + heightFun = heightFun, + hValid = hValid, + currentIndex = predVar, + currentIndexInN = predInN, + leafTyping = leafTyping, + currentPat = args(childIdx), + path = path.tail, + currentInHeight = childInPred, + target = target + ) + + val predSubSucc = have(predVar ⊆ S(predVar)) by Tautology.from(subsetSuccessor.of(n := predVar)) + val predSubCurrent = have(predVar ⊆ currentIndex) by Congruence.from(predSubSucc, currentEqSucc) + { + have(target ∈ app(heightFun)(currentIndex)) by Tautology.from( + hValid, + currentIndexInN, + predInN, + predSubCurrent, + innerAtPred, + currentAdt.semantic.height.membershipMonotonicAt(levelSubsts, Seq(h := heightFun, n := currentIndex, m := predVar, x := target)) + ) + } + } + val fromPredWitness = thenHave( + ∃(predVar, predVar ∈ N /\ (currentIndex === S(predVar))) |- target ∈ app(heightFun)(currentIndex) + ) by LeftExists + have(target ∈ app(heightFun)(currentIndex)) by Cut(predWitnessAtIndex, fromPredWitness) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/PatternSystem.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/PatternSystem.scala new file mode 100644 index 000000000..be84e0445 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/semantics/PatternSystem.scala @@ -0,0 +1,185 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.encoding.SemanticConstructor +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.instantiate +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.utils.prooflib.Thm + +/** + * A resolved branch paired with its function body or induction proof. + */ +final case class Clause[A](pattern: Pattern, payload: A) { + export pattern.* + + /** + * Changes the payload while retaining the exact pattern and its binders. + */ + def map[B](f: A => B): Clause[B] = Clause(pattern, f(payload)) + + /** + * The expression carried by a function clause. + */ + def body(using ev: A =:= Expr[Ind]): Expr[Ind] = ev(payload) + + /** + * Instantiates the body at the supplied binder values. + */ + def bodySubstituted(substitutions: Seq[(Variable[Ind], Expr[Ind])])(using A =:= Expr[Ind]): Expr[Ind] = + body.substitute(substitutions.map((v, term) => v := term)*) + + /** + * Instantiates the body at the supplied proof variables. + */ + def bodyAt(vars: Seq[Variable[Ind]])(using A =:= Expr[Ind]): Expr[Ind] = + bodySubstituted(binders.zip(vars)) + + /** + * The body at the second tuple of proof variables. + */ + def bodyAtFreshVars2(using A =:= Expr[Ind]): Expr[Ind] = bodyAt(variables2) + + /** + * Membership in this clause's graph, with its witnesses existentially bound. + */ + private[ADT] def caseMembership(value: Expr[Ind])(using A =:= Expr[Ind]): Expr[Prop] = + existsSeq(variables2, freshBranchPremise /\ (value === pair(freshInputTerm, bodyAtFreshVars2))) +} + +/** + * Ordered clauses with one validated tree and shared pattern theorems. + */ +final class PatternSystem[A] private ( + val clauses: Seq[Clause[A]], + private val proofs: PatternSystem.Proofs +) { + + /** + * The specialized datatype matched by the clauses. + */ + def domain: SpecializedADT[?] = proofs.domain + + /** + * The branch patterns in source order. + */ + def patterns: Seq[Pattern] = proofs.patterns + + /** + * The retained tree, whose leaf indices refer to the source clause order. + */ + private[ADT] def decisionTree: DecisionTree = proofs.decisionTree + + /** + * Changes payloads without recompiling patterns or regenerating their theorems. + */ + def map[B](f: A => B): PatternSystem[B] = + new PatternSystem(clauses.map(_.map(f)), proofs) + + /** + * The constructors of the matched datatype. + */ + def constructors: Seq[SemanticConstructor] = domain.base.semantic.constructors + + /** + * Selects clauses headed by the given constructor, retaining source order. + */ + def clausesFor(constructor: SemanticConstructor): Seq[Clause[A]] = + clauses.filter(_.semanticConstructor == constructor) + + /** + * Membership in the graph described by function clauses. + */ + def caseMembership(value: Expr[Ind])(using A =:= Expr[Ind]): Expr[Prop] = + seqOr(clauses.map(_.caseMembership(value))) + + /** + * The disjunction asserting that some pattern matches the input. + */ + def caseCoverage(term: Expr[Ind]): Expr[Prop] = + seqOr(patterns.map(pattern => existsSeq(pattern.variables2, pattern.freshBranchPremise /\ (term === pattern.freshInputTerm)))) + + /** + * Every member of the domain matches a clause. + */ + def coverage: Theorem = proofs.coverage + + /** + * The cached branch-selection theorem with a schematic input. + */ + private[ADT] def branchSelectionSchema(constructor: SemanticConstructor): Theorem = + proofs.branchSelectionCache.getOrElseUpdate( + constructor, + PatternProofs.branchSelectionForCaseShape(decisionTree, constructor, proofs.selectionInput, patterns) + ) + + /** + * Instantiates branch selection for a known constructor without rebuilding its proof. + */ + def branchSelectionFor(constructor: SemanticConstructor, term: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + instantiate(branchSelectionSchema(constructor), Seq(proofs.selectionInput := term)) + + /** + * Distinct clauses cannot match the same input. + */ + def incompatible(first: Pattern, second: Pattern): Theorem = + proofs.incompatibleCache.getOrElseUpdate((first, second), PatternProofs.incompatibleCaseShape(first, second)) + + /** + * The pattern theorems collected for inspection. + */ + lazy val debugTheorems: Seq[(String, Theorem)] = { + val selectors = constructors.map { constructor => + ("branchSelectionFor(" + constructor.name + ")", branchSelectionSchema(constructor)) + } + val incompatibilities = patterns.zipWithIndex.flatMap { (first, index) => + patterns.drop(index + 1).zipWithIndex.map { (second, offset) => + ("incompatible(" + index + "," + (index + offset + 1) + ")", incompatible(first, second)) + } + } + ("coverage", coverage) +: (selectors ++ incompatibilities) + } + + /** + * Prints the retained tree and its pattern theorems. + */ + lazy val debugDump: Unit = { + println(DecisionTree.render(decisionTree)) + debugTheorems.foreach((label, theorem) => println("[" + label + "] " + theorem.statement)) + } +} + +/** + * Compiles collections of clauses and owns their body-independent proof caches. + */ +object PatternSystem { + private final class Proofs( + val domain: SpecializedADT[?], + val patterns: Seq[Pattern], + val decisionTree: DecisionTree + ) { + lazy val coverage: Theorem = PatternProofs.coverageCaseShape(decisionTree, patterns) + val incompatibleCache = collection.mutable.Map.empty[(Pattern, Pattern), Theorem] + val selectionInput = Variable[Ind]( + freshId( + patterns.flatMap(p => p.binders ++ p.variables2 ++ Seq(p.resolved.term, p.specializedAdtTerm)) :+ domain.term, + "branchInput" + ) + ) + val branchSelectionCache = collection.mutable.Map.empty[SemanticConstructor, Theorem] + } + + /** + * Validates the collection once before any pattern theorems are constructed. + */ + def compile[A](domain: SpecializedADT[?], clauses: Seq[Clause[A]]): Either[String, PatternSystem[A]] = { + val ordered = clauses.toVector + ordered.find(clause => clause.resolved.constructor.adt.id != domain.base.id || !isSame(clause.specializedAdtTerm, domain.term)) match + case Some(clause) => Left("Pattern " + clause.name + " was compiled for " + clause.specializedAdtTerm + ", expected " + domain.term + ".") + case None => + val patterns = ordered.map(_.pattern) + DecisionTree.compile(domain, patterns.map(_.resolved)).map { tree => + new PatternSystem(ordered, new Proofs(domain, patterns, tree)) + } + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/syntax/Case.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/syntax/Case.scala new file mode 100644 index 000000000..0e0d88aa6 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/syntax/Case.scala @@ -0,0 +1,62 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.syntax + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternValidation +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Pattern +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT +import lisa.utils.prooflib.Thm + +case class Case(cons: Constructor[?], args: Expr[Ind]*) { + + /** + * Used in the context of an induction proof. Adds the subproof corresponding to this + * case into a builder. + * + * Concrete terms are compiled to fresh binders plus equality assumptions, so nested + * constructor-headed patterns such as `cons(tru, tl)` are accepted here as well. + * + * @see [[lisa.maths.SetTheory.Types.ADT.tactics.Induction]] + */ + def subproof(using + proof: Proof, + line: sourcecode.Line, + file: sourcecode.File, + builder: CaseAccumulator[Thm, (Sequent, SpecializedADT[?], Variable[Ind])] + )(subproof: Proof ?=> Any): Unit = + val (bot, adt, adtVar) = builder.comp + val resolved = PatternValidation.resolveCase(cons, args, adt).fold(message => throw new IllegalArgumentException(message), identity) + val pattern = Pattern.fromResolved( + resolved, + bot.left.toSeq ++ bot.right.toSeq :+ adtVar + ) + val vars = pattern.topBinders + val prop = bot.right.head + val consTerm = pattern.inputTerm + val subst = adtVar -> consTerm + + val assumptions = pattern.typingPremises + ++ cons.semantic + .recursiveBinders(vars) + .map(v => prop.substitute(adtVar -> v)) + ++ pattern.guards.map(guard => guard.binder === guard.guardTerm) + + val botWithAssumptions = bot.substitute(subst) ++ (assumptions |- ()) + + val caseProof = have(botWithAssumptions) subproof { + subproof(using summon[Proof]) + } + builder.addResolved(pattern, caseProof) + + /** + * Used in the context of a function definition. Adds the body of the case to a + * builder. + * + * Arguments may be binder variables or concrete terms (nested patterns). + * + * @param body the body of this case + * @param builder the builder for the function definition + */ + def apply(body: Expr[Ind])(using builder: CaseAccumulator[Expr[Ind], Unit]): Unit = + builder += (cons, args, body) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/syntax/CaseAccumulator.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/syntax/CaseAccumulator.scala new file mode 100644 index 000000000..7de5d69c3 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/syntax/CaseAccumulator.scala @@ -0,0 +1,59 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching.syntax + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.PatternValidation +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Pattern +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT + +/** + * Collects cases and retains their resolved patterns and proof-facing binders. + */ +class CaseAccumulator[T, R](val comp: R) { + + private sealed trait Entry + private final case class Raw(constructor: Constructor[?], arguments: Seq[Expr[Ind]], payload: T) extends Entry + private final case class Prepared(clause: Clause[T]) extends Entry + + private val underlying = scala.collection.mutable.ArrayBuffer.empty[Entry] + + /** + * Collects a function case until its domain is known. + */ + def +=(cons: Constructor[?], args: Seq[Expr[Ind]], value: T): Unit = + underlying += Raw(cons, args, value) + + /** + * Retains the exact pattern view used to construct an induction case's assumptions. + */ + private[syntax] def addResolved(pattern: Pattern, value: T): Unit = + underlying += Prepared(Clause(pattern, value)) + + /** + * Resolves remaining cases and compiles their shared pattern structure without changing payloads. + */ + def compile(adt: SpecializedADT[?], avoid: T => Seq[Expr[?]] = _ => Seq.empty): Either[String, PatternSystem[T]] = { + val sharedAvoid = underlying.toSeq.flatMap { + case Raw(_, _, payload) => avoid(payload) + case Prepared(clause) => avoid(clause.payload) + } + val clauses = Vector.newBuilder[Clause[T]] + var index = 0 + while index < underlying.size do + val resolved = underlying(index) match + case Raw(constructor, arguments, payload) => + PatternValidation.resolveCase(constructor, arguments, adt).map { root => + Clause(Pattern.fromResolved(root, sharedAvoid), payload) + } + case Prepared(clause) => Right(clause) + resolved match + case Left(error) => return Left(error) + case Right(clause) => + underlying(index) = Prepared(clause) + clauses += clause + index += 1 + PatternSystem.compile(adt, clauses.result()) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/README.md b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/README.md new file mode 100644 index 000000000..ef67c3afa --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/README.md @@ -0,0 +1,100 @@ +# ADT: algebraic data types over set theory + +ADT provides declarations of polymorphic algebraic data types, functions defined by pattern matching, and structural induction. Its encoding and generated proofs are checked by LISA's kernel without admitted proofs. + +## Declaring a datatype and a function + +Import the public DSL and declare pattern variables explicitly. This example defines natural numbers and a nonrecursive predecessor function: + +```scala +import lisa.maths.SetTheory.Types.ADT.* +import lisa.maths.SetTheory.Types.ADT.InductiveInfixSyntax.{inductive, SelfRef, |} + +object Example extends lisa.Main { + val previous = variable[Ind] + val Nat = inductive( + | zero(), + | succ(previous :: SelfRef) + ) + import Nat.{zero, succ} + + val pred = fun(Nat, Nat) { + Case(zero): + zero + Case(succ, previous): + previous + } +} +``` + +The generated theorems are available through the corresponding objects: `succ.injectivity`, `Nat.induction`, `Nat.elim`, `pred.intro`, and `pred.elim(succ)`. Distinct constructors have a disjointness theorem, obtained with `Nat.disjointness(zero, succ)`. + +The complete datatype is built before `inductive` returns, so it can be used immediately. The explicit import distinguishes this `inductive` from the set-theoretic predicate with the same name. + +`fun` and `recFun` share the same construction using height-indexed approximants. `recFun` additionally supplies a self-reference to the case-building function. Both support nested patterns; cases must be exhaustive and nonoverlapping. The self-contained [example](../../../../../../../../../lisa-examples/src/main/scala/ADTExample.scala) demonstrates declarations, specialization, nested patterns, polymorphic and higher-order recursion, typing, computation, and induction. + +## Parameters and declaration syntax + +Use existing LISA variables for type parameters and field binders: + +```scala +import lisa.maths.SetTheory.Types.ADT.* +import lisa.maths.SetTheory.Types.ADT.InductiveInfixSyntax.{inductive, SelfRef, |} + +val A, head, tail = variable[Ind] +val List = inductive(A)( + | nil(), + | cons(head :: A, tail :: SelfRef) +) +``` + +Use `()` for nullary constructors and commas between clauses. Every field must be a variable assignment, such as `head :: A`. `SelfRef` denotes the recursive type, implicitly applied to all declared parameters in order; it takes no arguments. Omit `(A)` for a monomorphic datatype, or use `inductive((A, B))(...)` for several parameters, up to five. `inductive()` defines an empty datatype. Supply clauses directly; declare variables and helpers outside the declaration. + +The result is an actual `ADT[S]` and therefore an `Expr[S]`, with statically checked constructor names exposed through `Selectable`. Constructor selections use a cached map without Java reflection. Names that conflict with inherited ADT or expression members, such as `induction`, `elim`, or `id`, are rejected at compile time. + +`List.cons(Nat) * Nat.zero * List.nil(Nat)` supplies a type argument followed by value arguments. Field types must be declared parameters or `SelfRef`. Arbitrary type expressions, nested recursive occurrences, and non-uniform recursion are unsupported. Constructor arguments and pattern binders must have distinct names within their respective declarations or cases; internal proof variables are chosen independently of their names. + +## Explicit builder + +The explicit `adt` builder remains available for programmatically assembled declarations: + +`adt(name, "A", constructors)` declares one type parameter; overloads accept tuples of up to five names. The Scala parameter of `ADT[S]` is the LISA sort of the symbol: `ADT[Ind]` for a monomorphic datatype and `ADT[Ind >>: Ind]` for one type parameter. Use `adt.specialize(typeArgs*)` when defining a function on a particular specialization. Functions can also declare their own parameters, independently of the domain's parameters, through `fun(parameters)(specializedDomain, returnType)` and `recFun(parameters)(specializedDomain, returnType)`. + +In the explicit builder, constructor fields have one of two forms: + +- `SelfRef` refers directly to the datatype being declared. +- `TypeArg("A")` refers to a declared type parameter. Import it from `lisa.maths.SetTheory.Types.ADT.syntax.AST` when using this explicit form. + +A string naming the datatype is shorthand for `SelfRef`; a string naming a parameter is shorthand for `TypeArg`. This builder uses the `SelfRef` marker from `syntax.AST`, also exported by `ADT`, rather than the expression placeholder imported from `InductiveInfixSyntax`. + +## Package structure + +| Folder | Role | +|---|---| +| [InductiveInfixSyntax.scala](InductiveInfixSyntax.scala) | Datatype declarations with typed fields and statically checked constructor names. | +| [API/](API/) | `adt`, `fun`, and `recFun` builders. | +| [syntax/](syntax/) | Constructor field syntax: `ConstructorArg`, `TypeArg`, and `SelfRef`. | +| [interface/](interface/) | User-facing `ADT`, `Constructor`, and `ADTFunction` wrappers; `RecFunction` is an alias. | +| [encoding/](encoding/) | Set-theoretic carriers, constructors, injectivity, and induction. | +| [height/](height/) | Height stages and their well-foundedness proofs. | +| [PatternMatching/](PatternMatching/) | `Case`, validated patterns, decision trees, and shared branch proofs. | +| [recursion/](recursion/) | Function specifications, graph witnesses, approximants, existence, and uniqueness. | +| [induction/](induction/) | The `Induction` tactic. | +| [support/](support/) | Shared proof utilities and symbol-definition helpers. | +| [library/](library/) | Prebuilt natural numbers, lists, trees, Booleans, options, products, unions, boxes, unit, and void. | + +The public package exports the DSL, `SelfRef`, `Case`, `Pattern`, `Clause`, and `Induction`. General iteration, ordinal, function, and set lemmas used by the encoding live in the corresponding set-theory library modules. Quantifier tactics live in `lisa-utils`. + +## Testing + +Run these commands from the repository root: + +```text +sbt "lisa-utils/testOnly lisa.utils.prooflib.QuantifierTacticsSuite" +sbt "lisa-sets/testOnly lisa.maths.SetTheory.Types.ADTRegressionSuite lisa.maths.SetTheory.Types.ADT.* lisa.maths.SetTheory.Ordinals.IntegerSuite" +sbt "lisa-sets/testOnly lisa.maths.SetTheory.Types.InductiveInfixSyntaxSuite" +sbt "lisa-examples/runMain ADTExamples.Example" +sbt "lisa-examples/testOnly ADTExampleSuite" +``` + +The regression suites cover successful declarations and proofs, invalid inputs, specialization, nested patterns, binder freshness, theorem reuse, and lazy proof construction. `ProofInitializationSuite` executes the shared height and recursion proofs. `ADTExampleSuite` runs the example and checks its recorded LCF errors and `Sorry` dependencies; compilation alone does not execute these proofs. diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/ConstructorInternals.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/ConstructorInternals.scala new file mode 100644 index 000000000..f544ed88b --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/ConstructorInternals.scala @@ -0,0 +1,88 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.SetTheory.Functions.Pi.->: +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers +import lisa.maths.SetTheory.Types.TypingHelpers.:: +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.maths.SetTheory.Types.TypingRules.BetaReduction +import lisa.maths.SetTheory.Types.TypingRules.TAbs +import lisa.utils.prooflib.BasicStep.RightForall +import lisa.utils.prooflib.QuantifiersIntro +import lisa.utils.prooflib.Thm + +/** + * Constructs the curried constructor encoding and proves its typing and equations. + */ +private[encoding] final class ConstructorInternals( + adt: SyntacticADT, + underlying: SyntacticConstructor, + semanticSignature: Seq[(Variable[Ind], Expr[Ind])], + variables: Seq[Variable[Ind]], + structuralTerm: Expr[Ind], + typ: Expr[Ind] +) { + private val abstractions = semanticSignature.scanRight(structuralTerm) { case ((v, domain), body) => + TypingHelpers.fun(v :: domain, body) + } + private val suffixTypes = semanticSignature.scanRight(adt.term) { case ((_, domain), codomain) => + domain ->: codomain + } + + /** + * The constructor's curried set-theoretic lambda, or its value when nullary. + */ + val witness: Expr[Ind] = abstractions.head + + /** + * The explicit encoding has the declared constructor type. + */ + val witnessTyping: Theorem = Lemma.generated(witness :: typ) { sp ?=> + val T1 = variable[Ind] + val T2, e = variable[Ind >>: Ind] + + def proveTyping(index: Int): Thm = { + val prefixTyping = wellTypedFormula(semanticSignature.take(index)) + if index == variables.size then have(prefixTyping |- abstractions(index) :: suffixTypes(index)) by Restate.from(adt.intro(underlying)) + else + val next = proveTyping(index + 1) + val (v, domain) = semanticSignature(index) + val body = abstractions(index + 1) + val codomain = suffixTypes(index + 1) + have(prefixTyping |- v ∈ domain ==> body ∈ codomain) by Restate.from(next) + val universallyTyped = thenHave(prefixTyping |- ∀(v ∈ domain, body ∈ codomain)) by RightForall + have(prefixTyping |- abstractions(index) :: suffixTypes(index)) by + Cut(universallyTyped, TAbs of (T1 := domain, T2 := λ(v, codomain), e := λ(v, body))) + } + + have(thesis) by Restate.from(proveTyping(0)) + } + + /** + * Applying the encoding to well-typed arguments yields its tagged tuple. + */ + val witnessEquations: Theorem = Lemma.generated( + forallSeq( + variables, + wellTypedFormula(semanticSignature) ==> (appSeq(witness)(variables) === structuralTerm) + ) + ) { + val T = variable[Ind] + val e = variable[Ind >>: Ind] + val e2 = variable[Ind] + + val betas = semanticSignature.indices.map { k => + val (v, domain) = semanticSignature(k) + val wNext = abstractions(k + 1) + have(wellTypedFormula(semanticSignature) |- abstractions(k) * v === wNext) by + Tautology.from(BetaReduction of (T := domain, e := λ(v, wNext), e2 := v)) + } + have(wellTypedFormula(semanticSignature) |- (appSeq(witness)(variables) === structuralTerm)) by Congruence.from(betas*) + + thenHave(wellTypedFormula(semanticSignature) ==> (appSeq(witness)(variables) === structuralTerm)) by + Restate + + thenHave(thesis) by QuantifiersIntro(variables) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SemanticADT.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SemanticADT.scala new file mode 100644 index 000000000..da8d3948d --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SemanticADT.scala @@ -0,0 +1,365 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.Quantifiers.universalEquivalenceDistribution +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.TypeSubstitution +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.instantiate +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.normalizeTypeSubstitutions +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.proofs.PropositionalFacts._ +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ +import lisa.maths.SetTheory.Types.TypingHelpers.:: +import lisa.utils.fol.FOL.SubstPair +import lisa.utils.prooflib.BasicStep.Restate +import lisa.utils.prooflib.BasicStep.RightForall +import lisa.utils.prooflib.InstantiateForall +import lisa.utils.prooflib.Thm + +/** + * Semantic set theoretical interpretation of an algebraic data type. That is the least + * set closed under [[SemanticConstructor]]. + * + * E.g. list is the smallest set containing nil and closed under the cons function. + * + * Injectivity between different constructors, structural induction and elimination rule + * are proved within this class. + * + * Exported semantic lemmas are kept in formula form. Type variables and the induction + * predicate remain schematic, while value arguments are explicitly quantified. + * + * @constructor generates a semantic interpretation for this ADT out of a syntactic one + * @param underlying the syntactic representation of this ADT + * @param constructors constructors of this ADT + */ +class SemanticADT( + underlying: SyntacticADT, + val constructors: Seq[SemanticConstructor] +) { + + /** + * Height predicates and theorem instances with simultaneous type and value substitutions. + */ + final class HeightAdapter private[SemanticADT] () { + + /** + * The unspecialized height predicate. + */ + def predicate(h: Expr[Ind]): Expr[Prop] = underlying.isHeight(h) + private lazy val heightArgument = Variable[Ind](freshId(typeVariablesSeq, s"$name/heightArgument")) + + /** + * Specializes the height predicate without substituting inside its argument. + */ + def predicateAt(substitutions: Seq[TypeSubstitution])(h: Expr[Ind]): Expr[Prop] = + predicate(heightArgument).substitute((substitutions :+ (heightArgument := h))*) + + /** + * The datatype's general height function. + */ + val function: Expr[Ind] = underlying.height + + private def specialize(base: Theorem, substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + instantiate(base, normalizeTypeSubstitutions("ADT", name, typeVariablesSeq, substitutions) ++ valueSubstitutions) + + /** + * Instantiates validity of the height function in the current proof. + */ + def validAt(substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair] = Seq.empty)(using proof: lisa.SetTheoryLibrary.Proof): Thm = + specialize(underlying.heightValid, substitutions, valueSubstitutions) + + /** + * Instantiates existence of a height function in the current proof. + */ + def existsAt(substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair] = Seq.empty)(using proof: lisa.SetTheoryLibrary.Proof): Thm = + specialize(underlying.heightExists, substitutions, valueSubstitutions) + + /** + * Instantiates monotonicity of height stages in the current proof. + */ + def monotonicAt(substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair] = Seq.empty)(using proof: lisa.SetTheoryLibrary.Proof): Thm = + specialize(underlying.heightMonotonic, substitutions, valueSubstitutions) + + /** + * Instantiates emptiness of the zero height stage in the current proof. + */ + def zeroAt(substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair] = Seq.empty)(using proof: lisa.SetTheoryLibrary.Proof): Thm = + specialize(underlying.heightZero, substitutions, valueSubstitutions) + + /** + * Instantiates preservation of stage membership in the current proof. + */ + def membershipMonotonicAt(substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair] = Seq.empty)(using proof: lisa.SetTheoryLibrary.Proof): Thm = + specialize(underlying.heightMembershipMonotonic, substitutions, valueSubstitutions) + + /** + * Instantiates inclusion in the successor stage in the current proof. + */ + def successorInclusionAt(substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair] = Seq.empty)(using proof: lisa.SetTheoryLibrary.Proof): Thm = + specialize(underlying.heightSuccessorInclusion, substitutions, valueSubstitutions) + + /** + * Instantiates the successor-stage characterization in the current proof. + */ + def successorStrongAt(substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair] = Seq.empty)(using proof: lisa.SetTheoryLibrary.Proof): Thm = + specialize(underlying.heightSuccessorStrong, substitutions, valueSubstitutions) + + /** + * Instantiates existence of a height for a datatype member in the current proof. + */ + def termHasHeightAt(substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair] = Seq.empty)(using proof: lisa.SetTheoryLibrary.Proof): Thm = + specialize(underlying.termHasHeight, substitutions, valueSubstitutions) + + /** + * Instantiates a common height for a syntactic constructor's arguments. + */ + def termsHaveHeightAt(c: SyntacticConstructor, heightFunction: Expr[Ind], substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair] = Seq.empty)(using + proof: lisa.SetTheoryLibrary.Proof + ): Thm = + underlying.termsHaveHeight(c, heightFunction, normalizeTypeSubstitutions("ADT", name, typeVariablesSeq, substitutions) ++ valueSubstitutions) + + /** + * Instantiates a common height for a semantic constructor's arguments. + */ + def termsHaveHeightAt(c: SemanticConstructor, heightFunction: Expr[Ind], substitutions: Seq[TypeSubstitution])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + termsHaveHeightAt(c.underlying, heightFunction, substitutions) + + /** + * Instantiates type and value parameters of a semantic constructor's common-height theorem together. + */ + def termsHaveHeightAt(c: SemanticConstructor, heightFunction: Expr[Ind], substitutions: Seq[TypeSubstitution], valueSubstitutions: Seq[SubstPair])(using + proof: lisa.SetTheoryLibrary.Proof + ): Thm = + termsHaveHeightAt(c.underlying, heightFunction, substitutions, valueSubstitutions) + } + + val height = HeightAdapter() + + /** + * Name of this ADT. + */ + val name: String = underlying.name + + /** + * Identifier of this ADT. + */ + val id: Identifier = underlying.polymorphicTerm.id + + /** + * Type variables of this ADT. + */ + + /** + * Sequence of type variables of this ADT. + */ + val typeVariablesSeq: Seq[Variable[Ind]] = underlying.typeVariablesSeq + + /** + * Number of type variables in this ADT. + */ + + /** + * Term representing this ADT where type variables are instantiated with given + * arguments. + * + * @param args the instances of this ADT type variables + */ + def term(args: Seq[Expr[Ind]]) = underlying.termAt(args) + + /** + * Term representing this ADT where type variables are instantiated with schematic + * variables. + */ + val term: Expr[Ind] = underlying.term + + /** + * Returns cached disjointness, with the first constructor's arguments quantified first. + */ + def disjointness(c1: SemanticConstructor, c2: SemanticConstructor): Theorem = + require( + constructors.contains(c1) && constructors.contains(c2) && c1 != c2, + s"Disjointness requires two distinct constructors of $name." + ) + c1.disjointnessSchema(c2) + + /** + * Theorem --- Structural induction principle for this ADT. + * + * `base cases => inductive cases => ∀x ∈ ADT. P(x)` + */ + lazy val induction = Lemma.generated( + constructors.foldRight[Expr[Prop]](forall(x, x :: term ==> P(x)))((c, f) => c.inductiveCase ==> f) + ) { sp ?=> + constructors.foldRight[(Expr[Prop], Expr[Prop], Thm)] { + val prop = forall(x, x :: term ==> P(x)) + (prop, prop, have(prop <=> prop) by Restate) + }((c, acc) => + val (oldBefore, oldAfter, fact) = acc + val newBefore = underlying.inductiveCase(c.underlying) ==> oldBefore + val newAfter = c.inductiveCase ==> oldAfter + + have(underlying.inductiveCase(c.underlying) <=> c.inductiveCase) subproof { + val wellTypedVars: Seq[Expr[Prop]] = wellTyped(c.semanticSignature) + val wellTypedVarsSet = wellTypedVars.toSet + + have( + forallSeq( + c.variables, + wellTypedFormula(c.semanticSignature) ==> (c.appliedTerm === c.structuralTerm) + ) + ) by Restate.from(c.shortDefinition) + if c.arity > 0 then + c.variables1.foldLeft(lastStep)((_, _) => + lastStep.statement.right.head match + case forall(v, phi) => thenHave(phi) by InstantiateForall(v) + case _ => throw UnreachableException + ) + + val eq = thenHave(wellTypedVarsSet |- c.appliedTerm === c.structuralTerm) by + Restate + have(P(c.appliedTerm) <=> P(c.appliedTerm)) by Restate + thenHave( + c.structuralTerm === c.appliedTerm |- P(c.structuralTerm) <=> P(c.appliedTerm) + ) by Congruence + have(wellTypedVarsSet |- P(c.structuralTerm) <=> P(c.appliedTerm)) by + Cut(eq, lastStep) + + c.syntacticSignature.foldRight[(Expr[Prop], Expr[Prop], Seq[Expr[Prop]])]( + (P(c.structuralTerm), P(c.appliedTerm), wellTypedVars) + )((el, fc) => + val (v, ty) = el + val (fc1, fc2, wellTypedVars) = fc + ty match + case SelfRef => + val wellTypedV: Expr[Prop] = v :: term + have(wellTypedVars |- (P(v) ==> fc1) <=> (P(v) ==> fc2)) by Cut( + lastStep, + leftImpliesEquivalenceWeak of (p := P(v), p1 := fc1, p2 := fc2) + ) + thenHave( + wellTypedVars.init |- wellTypedV ==> ((P(v) ==> fc1) <=> (P(v) ==> fc2)) + ) by RightImplies + have( + wellTypedVars.init |- (wellTypedV ==> (P(v) ==> fc1)) <=> + (wellTypedV ==> (P(v) ==> fc2)) + ) by Cut( + lastStep, + leftImpliesEquivalenceStrong of + (p := wellTypedV, p1 := P(v) ==> fc1, p2 := P(v) ==> fc2) + ) + thenHave( + wellTypedVars.init |- forall( + v, + (wellTypedV ==> (P(v) ==> fc1)) <=> (wellTypedV ==> (P(v) ==> fc2)) + ) + ) by RightForall + have( + wellTypedVars.init |- + forall(v, wellTypedV ==> (P(v) ==> fc1)) <=> + forall(v, wellTypedV ==> (P(v) ==> fc2)) + ) by Cut( + lastStep, + universalEquivalenceDistribution of + ( + P := lambda(v, wellTypedV ==> (P(v) ==> fc1)), + Q := lambda(v, wellTypedV ==> (P(v) ==> fc2)) + ) + ) + ( + forall(v, wellTypedV ==> (P(v) ==> fc1)), + forall(v, wellTypedV ==> (P(v) ==> fc2)), + wellTypedVars.init + ) + // case RegularArg(t_) => + case TypeArg(typeName) => + val t = typeExprToTerm(typeName) + thenHave(wellTypedVars.init |- v :: t ==> (fc1 <=> fc2)) by RightImplies + have(wellTypedVars.init |- (v ∈ t ==> fc1) <=> (v :: t ==> fc2)) by Cut( + lastStep, + leftImpliesEquivalenceStrong of (p := v ∈ t, p1 := fc1, p2 := fc2) + ) + thenHave( + wellTypedVars.init |- forall(v, (v ∈ t ==> fc1) <=> (v :: t ==> fc2)) + ) by RightForall + have( + wellTypedVars.init |- + forall(v, v ∈ t ==> fc1) <=> forall(v, v :: t ==> fc2) + ) by Cut( + lastStep, + universalEquivalenceDistribution of + (P := lambda(v, v ∈ t ==> fc1), Q := lambda(v, v :: t ==> fc2)) + ) + (forall(v, v ∈ t ==> fc1), forall(v, v :: t ==> fc2), wellTypedVars.init) + ) + have(thesis) by Restate.from(lastStep) + } + val newFact = have(newBefore <=> newAfter) by Tautology.from(lastStep, fact) + (newBefore, newAfter, newFact) + ) + have(underlying.induction.statement.right.head |- thesis.right.head) by Cut( + lastStep, + equivalenceApply of ( + p1 := underlying.induction.statement.right.head, + p2 := thesis.right.head + ) + ) + have(thesis) by Cut(underlying.induction, lastStep) + } + + /** + * Returns a map binding each constructor to formula describing whether x is an + * instance of it. + */ + private lazy val isConstructorMap: Map[SemanticConstructor, Expr[Prop]] = + constructors + .map(c => + c -> existsSeq( + c.variables2, + wellTypedFormula(c.semanticSignature2) /\ (x === c.appliedTerm2) + ) + ) + .toMap + + /** + * Returns a formula describing whether x is an instance of one of this ADT's + * constructors. + */ + private lazy val isConstructor = seqOr(constructors.map(c => isConstructorMap(c))) + + /** + * Theorem --- Pattern matching principle (also known as elimination rule) for this + * ADT. + * + * `∀x. x ∈ ADT ==> x = c * x1 * ... * xn for some constructor c and xi, ..., xj ∈ ADT` + */ + lazy val elim = Lemma.generated(forall(x, x :: term ==> simplify(isConstructor))) { sp ?=> + val property = lambda(x, isConstructor) + val cases = constructors.map { c => + val typings = wellTypedSet(c.semanticSignature) + val branch = isConstructorMap(c).substitute(x := c.appliedTerm) + + // Supply this constructor's arguments as witnesses for its own disjunct. + def introduceWitnesses(formula: Expr[Prop], arguments: List[Expr[Ind]]): Thm = arguments match + case Nil => have(typings |- formula) by Restate + case scala.collection.immutable.::(argument, rest) => + formula match + case exists(v, body) => + val premise = introduceWitnesses(body.substitute(v := argument), rest) + have(typings |- formula) by RightExists.withParameters(body, v, argument)(premise) + case _ => throw UnreachableException + + val witness = introduceWitnesses(branch, c.variables.toList) + val constructorCase = have(typings |- isConstructor.substitute(x := c.appliedTerm)) by Weakening(witness) + + // Abstract the typed arguments; recursive induction hypotheses are unused. + c.syntacticSignature.foldRight[Thm](constructorCase) { case ((v, ty), fact) => + val withHypothesis = ty match + case SelfRef => have(fact.statement.left |- isConstructor.substitute(x := v) ==> fact.statement.right.head) by Weakening(fact) + case TypeArg(_) => fact + val typing = v :: ty.getOrElse(term) + val implication = have((withHypothesis.statement.left - typing) |- typing ==> withHypothesis.statement.right.head) by Restate.from(withHypothesis) + have(implication.statement.left |- forall(v, implication.statement.right.head)) by RightForall(implication) + } + } + have(thesis) by Tautology.from((Seq[Thm](induction of (P := property)) ++ cases)*) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SemanticConstructor.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SemanticConstructor.scala new file mode 100644 index 000000000..35a350216 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SemanticConstructor.scala @@ -0,0 +1,573 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.SetTheory.Base.Pair +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.TypeSubstitution +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.instantiate +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.normalizeTypeSubstitutions +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.proofs.PropositionalFacts.altEqualityTransitivity +import lisa.maths.SetTheory.Types.ADT.support.semantics.DefinedSymbol +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ +import lisa.maths.SetTheory.Types.TypingHelpers.:: +import lisa.utils.prooflib.InstantiateForallSeq +import lisa.utils.prooflib.QuantifiersIntro +import lisa.utils.prooflib.Thm + +/** + * Semantic set theoretical interpretation of a constructor for an algebraic data type. + * That is a function from the arguments' domains to the set of instances of the + * algebraic data type. + * + * `c : T1 -> ... -> Tn -> ADT` + * + * Since polymorphism is supported, this function is parametrized by the type variables + * appearing inside the specification of the ADT. In this sense, a constructor is a class + * function whose parameters are type variables and whose body is the set theoretic + * function detailed above. With polymorphism, the signature thus becomes: + * + * `c(X1, ..., Xn) : T1(X1, ..., Xn) -> ... -> Tn(X1, ..., Xn) -> ADT(X1, ..., Xn)` + * + * Injectivity, constructor equations, and typing are proven within this class. + * + * Exported semantic lemmas are kept in formula form. Type variables remain schematic, + * while constructor arguments are explicitly quantified. + * + * @constructor generates a class function for this constructor + * @param line the line at which this constructor is defined. Usually fetched + * automatically by the compiler. Used for error reporting + * @param file the file in which this constructor is defined. Usually fetched + * automatically by the compiler. Used for error reporting + * @param name the name of this constructor + * @param underlying the syntactic constructor + * @param adt the algebraic data type to which this constructor belongs + */ +class SemanticConstructor(using line: sourcecode.Line, file: sourcecode.File)( + val name: String, + private[encoding] val underlying: SyntacticConstructor, + private val adt: SyntacticADT +) { + + /** + * Full name of this constructor, i.e. concatenation of the ADT name and this + * constructor name. + */ + val fullName: String = s"${adt.name}/${name}" + + override def toString: String = fullName + + /** + * Type variables that may appear in the signature of this constructor. + */ + + /** + * Sequence of type variables that may appear in the signature of this constructor. + */ + val typeVariablesSeq: Seq[Variable[Ind]] = adt.typeVariablesSeq + + /** + * Number of type variables in the signature of this constructor. + */ + + /** + * Variables used for constructor arguments. + */ + val variables: Seq[Variable[Ind]] = underlying.variables + + /** + * Variables used for constructor arguments. + */ + val variables1: Seq[Variable[Ind]] = underlying.variables1 + + /** + * Alternative set of variables used for constructor arguments. + */ + val variables2: Seq[Variable[Ind]] = underlying.variables2 + + /** + * Set of variables for this constructor with their respective domain or a special + * symbol in case the domain is the ADT. + * + * @param vars variables + */ + def syntacticSignature(vars: Seq[Variable[Ind]]): Seq[(Variable[Ind], ConstructorArg)] = + vars.zip(underlying.specification) + + /** + * Variables of this constructor with their respective domain or a special symbol in + * case the domain is the ADT. + */ + val syntacticSignature: Seq[(Variable[Ind], ConstructorArg)] = underlying.signature + + /** + * Constructor arguments with their respective domains. + * + * @param vars this constructor arguments + */ + def semanticSignature(vars: Seq[Variable[Ind]]): Seq[(Variable[Ind], Expr[Ind])] = vars + .zip(underlying.specification.map(_.getOrElse(adt.term))) + + /** + * Variables of this constructor with their respective domains. + */ + val semanticSignature: Seq[(Variable[Ind], Expr[Ind])] = semanticSignature(variables) + + /** + * Variables of this constructor with their respective domains. + */ + val semanticSignature1: Seq[(Variable[Ind], Expr[Ind])] = semanticSignature + + /** + * Alternative set of variables of this constructor with their respective domain. + */ + val semanticSignature2: Seq[(Variable[Ind], Expr[Ind])] = semanticSignature(variables2) + + def heightTypingFormula(heightSet: Expr[Ind]): Expr[Prop] = + wellTypedFormula(underlying.signature2)(heightSet) + + def branchPremiseAtHeight(heightSet: Expr[Ind], term: Expr[Ind]): Expr[Prop] = + heightTypingFormula(heightSet) /\ (term === structuralTerm2) + + def branchAtHeight(heightSet: Expr[Ind], term: Expr[Ind]): Expr[Prop] = + existsSeq(variables2, branchPremiseAtHeight(heightSet, term)) + + /** + * Constructor arguments whose domain is the ADT itself, i.e. the recursive + * positions, taken from `vars`. + */ + def recursiveBinders(vars: Seq[Variable[Ind]]): Seq[Variable[Ind]] = + syntacticSignature(vars).collect { case (v, SelfRef) => v } + + def selfRefVariables2: Seq[Variable[Ind]] = recursiveBinders(variables2) + + val typ: Expr[Ind] = + semanticSignature.unzip._2.foldRight[Expr[Ind]](adt.term)((a, b) => (a ->: b)) + + val adtName: String = adt.name + val adtTerm: Expr[Ind] = adt.term + + /** + * Arity of this constructor. + */ + val arity: Int = variables.size + + /** + * Internal representation of this constructor (i.e. as a tuple). + */ + private[encoding] val structuralTerm: Expr[Ind] = underlying.term + + /** + * Internal representation of this constructor (i.e. as a tuple). + */ + private[encoding] val structuralTerm1: Expr[Ind] = underlying.term1 + + /** + * Internal representation of this constructor (i.e. as a tuple) with an alternative + * set of variables. + */ + private[encoding] val structuralTerm2: Expr[Ind] = underlying.term2 + + private val internals = new ConstructorInternals( + adt = adt, + underlying = underlying, + semanticSignature = semanticSignature, + variables = variables, + structuralTerm = structuralTerm, + typ = typ + ) + + /** + * Defines the constructor directly as its curried encoding. + */ + private val definedClassFunction = new DefinedSymbol( + name = fullName, + parametersSeq = typeVariablesSeq, + body = internals.witness + ) + + val id = definedClassFunction.id + + /** + * This constructor in which type variables are instantiated. + * + * @param args the instances of this constructor's type variables + */ + def term(args: Seq[Expr[Ind]]): Expr[Ind] = definedClassFunction.term(args) + + /** + * Constructor where type variables are instantiated with schematic variables. + */ + private val term: Expr[Ind] = definedClassFunction.term + + private val constructorDefinition: Theorem = Lemma.generated(term === internals.witness) { + have(thesis) by Congruence.from(definedClassFunction.definition) + } + + /** + * Constructor where type variables are instantiated with schematic variables and + * arguments instantiated. + * + * @param args the instances of this constructor arguments + */ + def appliedTerm(args: Seq[Expr[Ind]]): Expr[Ind] = appSeq(term)(args) + + /** + * Constructor where type variables and arguments are instantiated with schematic + * variables. + */ + val appliedTerm: Expr[Ind] = appliedTerm(variables) + + /** + * Constructor where type variables and arguments are instantiated with schematic + * variables. + */ + val appliedTerm1: Expr[Ind] = appliedTerm + + /** + * Constructor where type variables and arguments are instantiated with schematic + * variables. Arguments variables are however drawn from an alternative set of + * variables. + */ + val appliedTerm2: Expr[Ind] = appliedTerm(variables2) + + // –––– Theorems –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– + + /** + * Lemma --- This constructor is equal to its internal representation. + * + * `∀x1, ..., xn. c * x1 * ... * xn = (tagc, (x1, (..., (xn, ∅)...))` + */ + val shortDefinition = Lemma.named(s"${fullName}/shortDefinition")( + forallSeq( + variables, + wellTypedFormula(semanticSignature) ==> (appliedTerm === structuralTerm) + ) + ) { + have(thesis) by Substitute(constructorDefinition)(internals.witnessEquations) + } + + /** + * Lemma --- Introduction rule for this constructor. + * + * `c(X1, ..., Xm) ∈ T1(X1, ..., Xm) -> ... -> Tn(X1, ..., Xm) -> ADT(X1, ..., Xm)` + * + * Type variables remain schematic at the semantic layer. + */ + val intro = Lemma.named(s"${fullName}/intro")(term :: typ) { + have(thesis) by Congruence.from(constructorDefinition, internals.witnessTyping) + } + + private val disjointnessSchemas = scala.collection.mutable.Map.empty[SemanticConstructor, Theorem] + private val disjointnessInstances = scala.collection.mutable.Map.empty[SemanticConstructor, Theorem] + private lazy val declarationIndex = adt.constructors.indexOf(underlying) + + /** + * Caches each orientation, proving only the declaration-order orientation from the encoding. + */ + private[encoding] def disjointnessSchema(other: SemanticConstructor): Theorem = { + require( + (adt eq other.adt) && underlying != other.underlying && declarationIndex >= 0 && other.declarationIndex >= 0, + s"Disjointness requires two distinct constructors of ${adt.name}." + ) + disjointnessSchemas.getOrElseUpdate( + other, { + val avoided = typeVariablesSeq ++ variables1 ++ variables2 ++ other.variables1 ++ other.variables2 + val args = (0 until arity + other.arity).foldLeft(Vector.empty[Variable[Ind]]) { (allocated, i) => + allocated :+ Variable[Ind](freshId(avoided ++ allocated, s"disjointArgument$i")) + } + val (leftArgs, rightArgs) = args.splitAt(arity) + val leftTerm = appliedTerm(leftArgs) + val rightTerm = other.appliedTerm(rightArgs) + val leftTyping = wellTypedFormula(semanticSignature(leftArgs)) + val rightTyping = wellTypedFormula(other.semanticSignature(rightArgs)) + val typed = simplify(leftTyping /\ rightTyping) + val body = typed ==> !(leftTerm === rightTerm) + + Lemma.generated(forallSeq(args, body)) { + if declarationIndex < other.declarationIndex then + val leftDefinition = have(leftTyping ==> (leftTerm === underlying.term(leftArgs))) by + InstantiateForallSeq(leftArgs)(shortDefinition) + val rightDefinition = have(rightTyping ==> (rightTerm === other.underlying.term(rightArgs))) by + InstantiateForallSeq(rightArgs)(other.shortDefinition) + val structuralDisequality = have(!(underlying.term(leftArgs) === other.underlying.term(rightArgs))) by + Tautology.from( + Pair.extensionality.of(a := underlying.tagTerm, b := underlying.subterm(leftArgs), c := other.underlying.tagTerm, d := other.underlying.subterm(rightArgs)), + underlying.tagDisequality(other.underlying) + ) + have(body) subproof { + assume(typed) + val left = have(leftTerm === underlying.term(leftArgs)) by Tautology.from(leftDefinition) + val right = have(rightTerm === other.underlying.term(rightArgs)) by Tautology.from(rightDefinition) + have(!(leftTerm === rightTerm)) by Congruence.from(left, right, structuralDisequality) + } + else + val reverse = have(typed ==> !(rightTerm === leftTerm)) by + InstantiateForallSeq(rightArgs ++ leftArgs)(other.disjointnessSchema(this)) + have(body) subproof { + assume(typed) + have(!(rightTerm === leftTerm)) by Tautology.from(reverse) + thenHave(!(leftTerm === rightTerm)) by Congruence + } + thenHave(thesis) by QuantifiersIntro(args) + } + } + ) + } + + /** + * Returns cached disjointness at this constructor's first and the other's second argument tuple. + */ + def disjointness(other: SemanticConstructor): Theorem = { + val schema = disjointnessSchema(other) + disjointnessInstances.getOrElseUpdate( + other, + Lemma.generated( + (wellTypedFormula(semanticSignature1) /\ wellTypedFormula(other.semanticSignature2)) ==> + !(appliedTerm1 === other.appliedTerm2) + ) { + have(thesis) by InstantiateForallSeq(variables1 ++ other.variables2)(schema) + } + ) + } + + /** + * Theorem --- Injectivity of constructors. + * + * Two instances of this constructor are equal if and only if all of their arguments + * are pairwise equal + * + * e.g. Cons(head1, tail1) === Cons(head2, tail2) <=> head1 === head2 /\ tail1 === + * tail2 + */ + lazy val injectivity = { + + val lemmaName = if typeVariablesSeq.isEmpty then s"$fullName/injectivity" else s"$fullName/semantic/injectivity" + if arity == 0 then Lemma.named(lemmaName)(appliedTerm1 === appliedTerm2) { have(thesis) by RightRefl } + else + val typedAssumption = + simplify(wellTypedFormula(semanticSignature1 ++ semanticSignature2)) + Lemma.named(lemmaName)( + forallSeq( + variables1 ++ variables2, + typedAssumption ==> simplify((appliedTerm1 === appliedTerm2) <=> (variables1 === variables2)) + ) + ) { + + val vars1WellTyped: Set[Expr[Prop]] = wellTypedSet(semanticSignature1) + val vars2WellTyped: Set[Expr[Prop]] = wellTypedSet(semanticSignature2) + + // Both applications reduce to their structural terms once the arguments are well-typed. + have(wellTypedFormula(semanticSignature1) ==> (appliedTerm1 === structuralTerm1)) by + InstantiateForallSeq(variables1)(shortDefinition) + val tappTerm1Def = thenHave(vars1WellTyped |- appliedTerm1 === structuralTerm1) by Restate + + have(wellTypedFormula(semanticSignature2) ==> (appliedTerm2 === structuralTerm2)) by + InstantiateForallSeq(variables2)(shortDefinition) + val tappTerm2Def = thenHave(vars2WellTyped |- appliedTerm2 === structuralTerm2) by Restate + + val definitionUnfolding = have( + vars1WellTyped ++ vars2WellTyped |- (appliedTerm1 === appliedTerm2) <=> + (structuralTerm1 === structuralTerm2) + ) by Congruence.from(tappTerm2Def, tappTerm1Def) + + have( + (appliedTerm1 === appliedTerm2) <=> (structuralTerm1 === structuralTerm2) |- + (appliedTerm1 === appliedTerm2) <=> seqEq(variables1, variables2) + ) by Congruence.from(underlying.injectivity) + + val equalityCharacterization = have( + vars1WellTyped ++ vars2WellTyped |- + simplify((appliedTerm1 === appliedTerm2) <=> (variables1 === variables2)) + ) by Cut(definitionUnfolding, lastStep) + + have(typedAssumption ==> simplify((appliedTerm1 === appliedTerm2) <=> (variables1 === variables2))) by + Restate.from(equalityCharacterization) + thenHave(thesis) by QuantifiersIntro(variables1 ++ variables2) + } + } + + /** + * Case generated by this constructor when performing a proof by induction + */ + val inductiveCase: Expr[Prop] = syntacticSignature + .foldRight[Expr[Prop]](P(appliedTerm1)) { (el, fc) => + val (v, typ) = el + typ match + case SelfRef => forall(v, (v :: adt.term) ==> (P(v) ==> fc)) + case TypeArg(name) => forall(v, (v :: typeExprToTerm(name)) ==> fc) + } + + // –––– Exported semantic theorems –––––––––––––––––––––––––––––––––––––––––– + + private val heightArgument = Variable[Ind](freshId(typeVariablesSeq ++ variables1 ++ variables2, s"$fullName/heightArgument")) + private val indexArgument = Variable[Ind](freshId(typeVariablesSeq ++ variables1 ++ variables2 :+ heightArgument, s"$fullName/indexArgument")) + private val termArgument = Variable[Ind](freshId(typeVariablesSeq ++ variables1 ++ variables2 ++ Seq(heightArgument, indexArgument), s"$fullName/termArgument")) + + private lazy val semanticTypingFromHeight: Theorem = { + val heightFun = heightArgument + val n = indexArgument + Lemma.generated( + (adt.isHeight(heightFun), n ∈ N, heightTypingFormula(app(heightFun)(n))) |- + wellTypedFormula(semanticSignature2) + ) { + assume(adt.isHeight(heightFun)) + assume(n ∈ N) + assume(heightTypingFormula(app(heightFun)(n))) + + have((n ∈ N) /\ heightTypingFormula(app(heightFun)(n))) by Restate + val exTypedAtHeight = thenHave( + ∃(k, (k ∈ N) /\ heightTypingFormula(app(heightFun)(k))) + ) by RightExists + + have(thesis) by Tautology.from( + adt.termsHaveHeight(underlying, heightFun, underlying.variables.zip(underlying.variables2).map((from, to) => from := to)), + exTypedAtHeight + ) + } + } + + private lazy val appliedEqualityFromStructural: Theorem = { + val heightFun = heightArgument + val n = indexArgument + val term0 = termArgument + Lemma.generated( + (adt.isHeight(heightFun), n ∈ N, branchPremiseAtHeight(app(heightFun)(n), term0)) |- + (term0 === appliedTerm2) + ) { + assume(adt.isHeight(heightFun)) + assume(n ∈ N) + assume(branchPremiseAtHeight(app(heightFun)(n), term0)) + + val shortBase = have(shortDefinition.statement.right.head) by Tautology.from(shortDefinition) + val shortAtVars2 = have(wellTypedFormula(semanticSignature2) ==> (appliedTerm2 === structuralTerm2)) by + InstantiateForallSeq(variables2)(shortBase) + have(term0 === appliedTerm2) by Tautology.from( + altEqualityTransitivity of (x := term0, y := structuralTerm2, z := appliedTerm2), + shortAtVars2, + semanticTypingFromHeight + ) + } + } + + private lazy val recursiveArgInHeight: Theorem = { + val heightFun = heightArgument + val heightIndex = indexArgument + Lemma.generated( + (adt.isHeight(heightFun), heightIndex ∈ N, wellTypedFormula(semanticSignature1), appliedTerm1 ∈ app(heightFun)(S(heightIndex))) |- + wellTypedFormula(underlying.signature1)(app(heightFun)(heightIndex)) + ) { + val hValid = assume(adt.isHeight(heightFun)) + val nInN = assume(heightIndex ∈ N) + assume(wellTypedFormula(semanticSignature1)) + val appliedInSucc = assume(appliedTerm1 ∈ app(heightFun)(S(heightIndex))) + + // The application equals the structural term once the arguments are well-typed. + val shortBase = have(shortDefinition.statement.right.head) by Tautology.from(shortDefinition) + have(wellTypedFormula(semanticSignature1) ==> (appliedTerm1 === structuralTerm1)) by + InstantiateForallSeq(variables1)(shortBase) + val appliedEqStructural = have(appliedTerm1 === structuralTerm1) by Restate.from(lastStep) + + val structuralInSucc = have(structuralTerm1 ∈ app(heightFun)(S(heightIndex))) by Congruence.from( + appliedEqStructural, + appliedInSucc + ) + + val constructorBranches = adt.constructors.map { other => + // Distinct fresh names per argument: `variable[Ind]` derives its identifier + // from the enclosing val (`branchVars`), so `.map(_ => variable[Ind])` would + // give every argument the *same* identifier — collapsing e.g. `cons(a)(b)` + // into `cons(branchVars)(branchVars)` and breaking the injectivity/Congruence + // reasoning below for any constructor of arity ≥ 2. + val branchVars = other.variables2.indices.map(i => Variable[Ind](s"branchVar$i")).toSeq + val branchSubsts = other.variables2.zip(branchVars).map { case (v, fresh) => v := fresh } + val branchSignature = branchVars.zip(other.signature2.map(_._2)) + val branchTerm = other.term2.substitute(branchSubsts*).asInstanceOf[Expr[Ind]] + val branchBody = + wellTypedFormula(branchSignature)(app(heightFun)(heightIndex)) /\ + (structuralTerm1 === branchTerm) + val branch = existsSeq(branchVars, branchBody) + + val directBranch = if other == underlying then + val transportedTyping = syntacticSignature.zipWithIndex.map { case ((v1, arg), idx) => + val v2 = branchVars(idx) + val vEq = have(branchBody |- v1 === v2) by Weakening(underlying.injectivity.of(branchSubsts*)) + // `argsTypedAtHeight` is a conjunction of all argument typings; Congruence + // only inspects top-level hypotheses, so first split out *this* argument's + // typing with Tautology, then transport it across `v1 = v2`. + arg match + case lisa.maths.SetTheory.Types.ADT.syntax.AST.SelfRef => + val v2Typed = have(branchBody |- v2 ∈ app(heightFun)(heightIndex)) by Restate + have(branchBody |- v1 ∈ app(heightFun)(heightIndex)) by Congruence.from(v2Typed, vEq) + case lisa.maths.SetTheory.Types.ADT.syntax.AST.TypeArg(name) => + val v2Typed = have(branchBody |- v2 ∈ typeExprToTerm(name)) by Restate + have(branchBody |- v1 ∈ typeExprToTerm(name)) by Congruence.from(v2Typed, vEq) + } + have(branchBody |- wellTypedFormula(underlying.signature1)(app(heightFun)(heightIndex))) by + Tautology.from(transportedTyping*) + else + have(branchBody |- wellTypedFormula(underlying.signature1)(app(heightFun)(heightIndex))) by + Tautology.from(underlying.disjointness(other).of(branchSubsts*)) + + val rawBranch = branchVars.reverse.foldLeft(directBranch -> branchBody) { case ((fact, premise), v) => + val wrappedPremise = ∃(v, premise) + val lifted = have(fact.statement - from := to) + instantiate(semanticTypingFromHeight, normalized ++ valueSubstitutions ++ Seq(heightArgument := heightFun, indexArgument := n)) + } + + /** + * Instantiates the predecessor-stage bound for recursive arguments in the current proof. + */ + def recursiveArgInHeightAt( + substitutions: Seq[TypeSubstitution], + arguments: Seq[Expr[Ind]] = variables2 + )(heightFun: Expr[Ind], heightIndex: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = { + require(arguments.size == arity, s"Constructor $fullName expects $arity arguments, received ${arguments.size}.") + val normalized = normalizeTypeSubstitutions("constructor", fullName, typeVariablesSeq, substitutions) + val valueSubstitutions = variables1.zip(arguments).map((from, to) => from := to) + instantiate(recursiveArgInHeight, normalized ++ valueSubstitutions ++ Seq(heightArgument := heightFun, indexArgument := heightIndex)) + } + + /** + * Instantiates the equality between a structural term and its constructor application. + */ + def appliedEqualityFromStructuralAt( + substitutions: Seq[TypeSubstitution], + arguments: Seq[Expr[Ind]] = variables2 + )(heightFun: Expr[Ind], n: Expr[Ind], term0: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = { + require(arguments.size == arity, s"Constructor $fullName expects $arity arguments, received ${arguments.size}.") + val normalized = normalizeTypeSubstitutions("constructor", fullName, typeVariablesSeq, substitutions) + val valueSubstitutions = variables2.zip(arguments).map((from, to) => from := to) + instantiate(appliedEqualityFromStructural, normalized ++ valueSubstitutions ++ Seq(heightArgument := heightFun, indexArgument := n, termArgument := term0)) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT.scala new file mode 100644 index 000000000..99522ba6d --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT.scala @@ -0,0 +1,42 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.SetTheory.SetTheory._ + +/** + * Syntactic set theoretical interpretation of an algebraic data type. That is the least + * set closed under [[SyntacticConstructor]]. + * + * E.g. list is the smallest set containing nil and closed under the syntactic operation + * cons. + * + * Injectivity between different constructors, introduction rules and structural + * induction are proved within this class. + * + * ADT encoding is split into multiple traits (ordered by dependency): + * - `SyntacticADTBase`: shared logical encodings and core predicates. + * - `SyntacticADTInjectivity`: disjointness/injectivity of constructors. + * - `SyntacticADTHeight`: introduction-image lemmas plus height-function characterization and monotonicity. + * - `SyntacticADTTerm`: term definition from heights and introduction lemmas. + * - `SyntacticADTInduction`: structural induction principle. + * - `SyntacticADT`: concrete ADT class wiring those layers together. + * + * @constructor creates a new algebraic data type out of a user specification. + * @param line the line at which the ADT is defined. Usually fetched automatically by the + * compiler. Used for error reporting + * @param file the file in which the ADT is defined. Usually fetched automatically by the + * compiler. Used for error reporting + * @param name the name of the ADT + * @param constructors constructors of the ADT + * @param typeVariables type variables used in the definition of this ADT + */ +class SyntacticADT(using line: sourcecode.Line, file: sourcecode.File)( + val name: String, + val constructors: Seq[SyntacticConstructor], + val typeVariablesSeq: Seq[Variable[Ind]] +) extends SyntacticADTInduction { + + protected final def sourceLine: sourcecode.Line = line + + protected final def sourceFile: sourcecode.File = file + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Base.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Base.scala new file mode 100644 index 000000000..ca439feed --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Base.scala @@ -0,0 +1,85 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.height.HeightADT +import lisa.maths.SetTheory.Types.ADT.height.HeightConstructorData +import lisa.maths.SetTheory.Types.ADT.height.HeightConstructors +import lisa.maths.SetTheory.Types.ADT.height.HeightStageSet +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.semantics.DefinedSymbol + +private[encoding] trait SyntacticADTBase { + this: SyntacticADT => + + protected inline final def app(f: Expr[Ind], x: Expr[Ind]): Expr[Ind] = lisa.maths.SetTheory.Functions.Predef.app(f)(x) + + protected def sourceLine: sourcecode.Line + protected def sourceFile: sourcecode.File + + private val predicateSubject = Variable[Ind](freshId(typeVariablesSeq ++ constructors.flatMap(_.variables2), "constructorSubject")) + private val predicateDomain = Variable[Ind](freshId(typeVariablesSeq ++ constructors.flatMap(_.variables2) :+ predicateSubject, "constructorDomain")) + private val constructorPredicates = constructors.map(c => c -> existsSeq(c.variables2, wellTypedFormula(c.signature2)(predicateDomain) /\ (predicateSubject === c.term2))).toMap + + def constructorVarsInDomain( + c: SyntacticConstructor, + s: Expr[Ind] + ): Expr[Prop] = wellTypedFormula(c.signature)(s) + + /** + * Describes a constructor instance without capturing the supplied subject or domain. + */ + def isConstructor( + c: SyntacticConstructor, + x: Expr[Ind], + s: Expr[Ind] + ): Expr[Prop] = + constructorPredicates(c).substitute(predicateSubject := x, predicateDomain := s) + + def isConstructor(x: Expr[Ind], s: Expr[Ind]): Expr[Prop] = + seqOr(constructors.map(c => isConstructor(c, x, s))) + + val isConstructor: Expr[Ind >>: Ind >>: Prop] = λ(predicateSubject, λ(predicateDomain, isConstructor(predicateSubject, predicateDomain))) + + def inIntroImage(s: Expr[Ind])(y: Expr[Ind]): Expr[Prop] = + isConstructor(y, s) \/ (y ∈ s) + + protected val heightConstructorData = constructors.map(c => + HeightConstructorData( + variables = c.variables2, + signature = c.signature2, + subterm = c.subterm2, + tagTerm = c.tagTerm + ) + ) + + protected val heightTHY = + HeightADT(name, typeVariablesSeq, isConstructor) + private val heightStageSet = + HeightStageSet(name, typeVariablesSeq, heightTHY, heightConstructorData, isConstructor) + protected val heightConstructorsTHY = + HeightConstructors(heightTHY, heightConstructorData, heightStageSet, isConstructor) + + def isHeight(h: Expr[Ind]): Expr[Prop] = heightTHY.isHeight(h) + val heightExists = heightStageSet.heightExists + val heightUniqueness = heightConstructorsTHY.heightUniqueness + lazy val heightExistsOne = heightConstructorsTHY.heightExistsOne + val heightZero = heightTHY.heightZero + val heightMonotonic = heightConstructorsTHY.heightMonotonic + val heightMembershipMonotonic = heightConstructorsTHY.heightMembershipMonotonic + val heightSuccessorInclusion = heightConstructorsTHY.heightSuccessorInclusion + val heightSuccessorWeak = heightConstructorsTHY.heightSuccessorWeak + val heightSuccessorStrong = heightConstructorsTHY.heightSuccessorStrong + + private val definedClassFunction = new DefinedSymbol( + name = s"${name}/heightFun", + parametersSeq = typeVariablesSeq, + body = heightStageSet.height + ) + + def heightAt(args: Seq[Expr[Ind]]): Expr[Ind] = definedClassFunction.term(args) + val height: Expr[Ind] = definedClassFunction.term + val heightValid = Lemma.generated(isHeight(height)) { + have(thesis) by Congruence.from(heightStageSet.heightValid, definedClassFunction.definition) + } + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Induction.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Induction.scala new file mode 100644 index 000000000..1fe727f37 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Induction.scala @@ -0,0 +1,160 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.SetTheory.Base.Pair.given +import lisa.maths.SetTheory.Ordinals.Integer.omegaSuccessorInduction +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.proofs.PropositionalFacts._ +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ +import lisa.utils.prooflib.BasicStep.Restate +import lisa.utils.prooflib.QuantifiersIntro + +private[encoding] trait SyntacticADTInduction extends SyntacticADTTerm { + this: SyntacticADT => + + lazy val inductiveCase: Map[SyntacticConstructor, Expr[Prop]] = constructors + .map(c => + c -> c.signature.foldRight[Expr[Prop]](P(c.term))((el, fc) => + val (v, ty) = el + ty match + case SelfRef => forall(v, v ∈ term ==> (P(v) ==> fc)) + case TypeArg(typeName) => forall(v, v ∈ typeExprToTerm(typeName) ==> fc) + ) + ) + .toMap + + lazy val induction = ( + Lemma.named(if typeVariablesSeq.isEmpty then s"$name/induction" else s"$name/encoding/induction")( + constructors.foldRight[Expr[Prop]](forall(x, x ∈ term ==> P(x)))((c, f) => inductiveCase(c) ==> f) + ) { + // The per-constructor inductive hypotheses the caller must supply, bundled together. + val preconditions: Expr[Prop] = seqAnd(constructors.map(inductiveCase)) + + // `stage(k)` states that every element of the height-`k` approximation satisfies P. + // We prove the goal by ordinary induction over `k ∈ N` on this predicate. + def stage(k: Expr[Ind]): Expr[Prop] = forall(x, x ∈ app(h, k) ==> P(x)) + val stageN: Expr[Prop] = stage(n) + + // --- Base case: the height-0 approximation is empty, so `stage(∅)` holds vacuously. --- + have(isHeight(h) |- x ∈ app(h, ∅) ==> P(x)) by Weakening(heightZero) + val baseCase = thenHave(isHeight(h) |- stage(∅)) by RightForall + + // Reduce the goal to the successor step: given the base case, ordinary induction over N + // leaves only `stage(n) ==> stage(S(n))` to prove. + val successorReduction = have( + (isHeight(h), forall(n, n ∈ N ==> (stageN ==> stage(S(n))))) |- + forall(n, n ∈ N ==> stageN) + ) by Tautology.from(baseCase, omegaSuccessorInduction of (P := λ(n, stageN))) + + // --- Successor step: `stage(n) ==> stage(S(n))`. --- + val successorStep = have( + (isHeight(h), preconditions) |- forall(n, n ∈ N ==> (stageN ==> stage(S(n)))) + ) subproof { + // `n ∈ N` and `stage(n)` are carried explicitly (via `ctx`) since the closing + // steps discharge them; only the permanent hypotheses are assumed. + assume(isHeight(h), preconditions) + + // An element of the height-`S(n)` approximation is an instance `c(args)` of some + // constructor whose arguments live in the height-`n` approximation. We show that any + // such instance satisfies P. + def ctx(extra: Expr[Prop]*): Seq[Expr[Prop]] = + Seq(isHeight(h), preconditions, n ∈ N, stageN) ++ extra + + val instanceSatisfiesP = have(ctx(isConstructor(x, app(h, n))) |- P(x)) subproof { + if constructors.isEmpty then have(thesis) by Restate + else + val perConstructor = constructors.map { c => + val argsInStage = wellTypedFormula(c.signature2)(app(h, n)) + val argsInTerm = wellTypedFormula(c.signature2)(term) + + // (1) Arguments living in the height-`n` approximation also live in the whole ADT. + val argsInTermFromStage = have((isHeight(h), n ∈ N, argsInStage) |- argsInTerm) subproof { + assume(isHeight(h), n ∈ N, argsInStage) + val conjuncts = c.signature2.map { (v, ty) => + ty match + case SelfRef => + val vHasHeight = (∃(n, n ∈ N /\ x ∈ app(h, n))).substitute(x := v) + have(n ∈ N /\ (v ∈ app(h, n))) by Restate + thenHave(vHasHeight) by RightExists + have(v ∈ term) by Tautology.from(termHasHeight of (x := v), lastStep) + case TypeArg(typeName) => + have(v ∈ typeExprToTerm(typeName)) by Restate + } + if conjuncts.isEmpty then have(thesis) by Restate + else have(thesis) by RightAnd((conjuncts).map(_.kernel)) + } + + // (2) Discharging the constructor's inductive hypothesis yields `P(c(args))`. + // The membership hypotheses are taken from (1); the `P` hypotheses from `stage(n)`. + def cCtx(extra: Expr[Prop]*): Seq[Expr[Prop]] = + Seq(isHeight(h), inductiveCase(c), n ∈ N, stageN) ++ extra + + val pOnInstance = have(cCtx(argsInStage) |- P(c.term2)) subproof { + assume(isHeight(h), inductiveCase(c), n ∈ N, stageN, argsInStage) + have(inductiveCase(c)) by Restate + c.signature2.foldLeft(lastStep) { (fact, el) => + val (v, ty) = el + fact.statement.right.head match + case forall(boundVar, body) => + val instantiated = body.substitute(boundVar := v) + thenHave(instantiated) by InstantiateForall(v) + (instantiated, ty) match + case (implies(_, implies(_, conclusion)), SelfRef) => + val dischargeMembership = thenHave((argsInTerm, P(v)) |- conclusion) by Weakening + have(stageN |- stageN) by Hypothesis + thenHave(stageN |- v ∈ app(h, n) ==> P(v)) by InstantiateForall(v) + thenHave((stageN, argsInStage) |- P(v)) by Weakening + have(argsInTerm |- conclusion) by Cut(lastStep, dischargeMembership) + have(conclusion) by Cut(argsInTermFromStage, lastStep) + case (implies(_, conclusion), TypeArg(_)) => + thenHave(conclusion) by Restate + case _ => throw UnreachableException + case _ => throw UnreachableException + } + thenHave(thesis) by Restate + } + + // (3) Rewrite `c(args)` to `x`, then repack the arguments into the existential. + have(cCtx(argsInStage, x === c.term2) |- P(x)) by Congruence.from(pOnInstance) + thenHave(cCtx(argsInStage /\ (x === c.term2)) |- P(x)) by LeftAnd + thenHave(cCtx(isConstructor(c, x, app(h, n))) |- P(x)) by QuantifiersIntro(c.variables2) + thenHave(ctx(isConstructor(c, x, app(h, n))) |- P(x)) by Weakening + } + + have(ctx(isConstructor(x, app(h, n))) |- P(x)) by LeftOr((perConstructor).map(_.kernel)) + } + + // The height-`S(n)` approximation is exactly the constructor instances over height `n`. + have((isHeight(h), n ∈ N, x ∈ app(h, S(n))) |- isConstructor(x, app(h, n))) by + Cut(heightSuccessorStrong, equivalenceApply of (p1 := x ∈ app(h, S(n)), p2 := isConstructor(x, app(h, n)))) + have(ctx(x ∈ app(h, S(n))) |- P(x)) by Cut(lastStep, instanceSatisfiesP) + thenHave(ctx() |- x ∈ app(h, S(n)) ==> P(x)) by RightImplies + thenHave(ctx() |- stage(S(n))) by RightForall + thenHave((isHeight(h), preconditions, n ∈ N) |- stageN ==> stage(S(n))) by RightImplies + thenHave((isHeight(h), preconditions) |- n ∈ N ==> (stageN ==> stage(S(n)))) by RightImplies + thenHave(thesis) by RightForall + } + + // --- Conclusion: every element of `term` has some height `n`, hence satisfies P. --- + have((isHeight(h), preconditions) |- forall(n, n ∈ N ==> stageN)) by + Cut(successorStep, successorReduction) + thenHave((isHeight(h), preconditions) |- n ∈ N ==> stageN) by InstantiateForall(n) + thenHave((isHeight(h), preconditions, n ∈ N) |- stageN) by Restate + thenHave((isHeight(h), preconditions, n ∈ N) |- x ∈ app(h, n) ==> P(x)) by InstantiateForall(x) + thenHave((isHeight(h), preconditions, n ∈ N /\ x ∈ app(h, n)) |- P(x)) by Restate + val heightImpliesP = thenHave( + (isHeight(h), preconditions, exists(n, n ∈ N /\ x ∈ app(h, n))) |- P(x) + ) by LeftExists + + have((isHeight(h), x ∈ term) |- exists(n, n ∈ N /\ x ∈ app(h, n))) by + Cut(termHasHeight, equivalenceApply of (p1 := x ∈ term, p2 := exists(n, n ∈ N /\ x ∈ app(h, n)))) + have((isHeight(h), preconditions, x ∈ term) |- P(x)) by Cut(lastStep, heightImpliesP) + thenHave((exists(h, isHeight(h)), preconditions, x ∈ term) |- P(x)) by LeftExists + have((preconditions, x ∈ term) |- P(x)) by Cut(heightExists, lastStep) + thenHave(preconditions |- x ∈ term ==> P(x)) by RightImplies + thenHave(preconditions |- forall(x, x ∈ term ==> P(x))) by RightForall + thenHave(thesis) by Restate + } + ) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Term.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Term.scala new file mode 100644 index 000000000..64dd06e0c --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticADT/Term.scala @@ -0,0 +1,128 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.SetTheory.Functions.Predef.range +import lisa.maths.SetTheory.Ordinals.Integer.successorInOmega +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.height.HeightTerms +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.instantiate +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.proofs.PropositionalFacts._ +import lisa.maths.SetTheory.Types.ADT.support.semantics.DefinedSymbol +import lisa.utils.fol.FOL.SubstPair +import lisa.utils.prooflib.BasicStep.Restate +import lisa.utils.prooflib.Thm + +private[encoding] trait SyntacticADTTerm extends SyntacticADTBase { + this: SyntacticADT => + + private val definedClassFunction = new DefinedSymbol( + name = s"${name}/term", + parametersSeq = typeVariablesSeq, + body = ⋃(range(height)) + ) + + val polymorphicTerm: Constant[?] = definedClassFunction.symbol + + polymorphicTerm.printAs(args => + if args.isEmpty then s"${name}/term[${typeVariablesSeq.mkString(",")}]" + else s"${name}/term[${args.mkString(",")}]" + ) + + def termAt(args: Seq[Expr[Ind]]): Expr[Ind] = definedClassFunction.term(args) + + val term: Expr[Ind] = termAt(typeVariablesSeq) + + /** + * The carrier is the union of the stages of any valid height function. + */ + private val termEqualsUnion: Theorem = Lemma.generated(isHeight(h) |- term === ⋃(range(h))) { + val sameHeight = have(isHeight(h) |- height === h) by Cut(heightValid, heightUniqueness.of(f := height)) + have(thesis) by Congruence.from(sameHeight, definedClassFunction.definition) + } + + private val heightTermsTHY = HeightTerms( + heightTHY, + heightConstructorsTHY, + heightConstructorData, + term, + termEqualsUnion + ) + + val termHasHeight = heightTermsTHY.termHasHeight + private val commonHeightTheorems = constructors + .zip(heightConstructorData) + .map((c, data) => c -> heightTermsTHY.termsHaveHeight(data)) + .toMap + + /** + * Instantiates common height with a separate height function, composing argument and parameter substitutions. + */ + private[encoding] def termsHaveHeight(c: SyntacticConstructor, heightFunction: Expr[Ind], substitutions: Seq[SubstPair] = Seq.empty)(using proof: lisa.SetTheoryLibrary.Proof): Thm = { + val renaming = c.variables2.zip(c.variables).map((from, to) => from := to.substitute(substitutions*)) + // The schema's h denotes the height function; a field named h is handled by argument renaming. + val remaining = substitutions.filterNot(substitution => c.variables2.contains(substitution._1) || substitution._1 == h) + instantiate(commonHeightTheorems(c), remaining ++ renaming :+ (h := heightFunction)) + } + + val intro = constructors + .map(c => + c -> Lemma.generated( + simplify(constructorVarsInDomain(c, term)) |- simplify(c.term ∈ term) + ) { + val context = typeVariablesSeq ++ c.variables1 ++ c.variables2 :+ term + val heightFunction = Variable[Ind](freshId(context, "h")) + val stage = Variable[Ind](freshId(context :+ heightFunction, "n")) + val otherStage = Variable[Ind](freshId(context ++ Seq(heightFunction, stage), "m")) + val argsInTerm = constructorVarsInDomain(c, term) + val argsInStageN = constructorVarsInDomain(c, app(heightFunction, stage)) + + // If the arguments all live in the ADT, they share a common height `stage`. + val argsShareHeight = have((isHeight(heightFunction), argsInTerm) |- ∃(stage, stage ∈ N /\ argsInStageN)) by Cut( + termsHaveHeight(c, heightFunction), + equivalenceApply of (p1 := argsInTerm, p2 := exists(stage, stage ∈ N /\ argsInStageN)) + ) + + // An instance sitting in approximation `S(stage)` has a height, hence lies in the ADT. + val succInN = have(stage ∈ N |- S(stage) ∈ N) by Cut(successorInOmega.of(n := stage), equivalenceApply of (p1 := stage ∈ N, p2 := S(stage) ∈ N)) + have((stage ∈ N, c.term ∈ app(heightFunction, S(stage))) |- S(stage) ∈ N /\ c.term ∈ app(heightFunction, S(stage))) by RightAnd( + succInN, + have(c.term ∈ app(heightFunction, S(stage)) |- c.term ∈ app(heightFunction, S(stage))) by Hypothesis + ) + thenHave((stage ∈ N, c.term ∈ app(heightFunction, S(stage))) |- exists(otherStage, otherStage ∈ N /\ c.term ∈ app(heightFunction, otherStage))) by RightExists + val instanceInTerm = have((isHeight(heightFunction), stage ∈ N, c.term ∈ app(heightFunction, S(stage))) |- c.term ∈ term) by + Congruence.from(lastStep, termHasHeight of (x := c.term, h := heightFunction)) + + // An element of the introduction image over approximation `stage` sits in approximation `S(stage)`. + val instanceInIntroImage = inIntroImage(app(heightFunction, stage))(c.term) + val imageInSuccessor = have((isHeight(heightFunction), stage ∈ N, instanceInIntroImage) |- c.term ∈ app(heightFunction, S(stage))) by Cut( + heightSuccessorWeak of (x := c.term, h := heightFunction, n := stage), + equivalenceRevApply of (p1 := instanceInIntroImage, p2 := c.term ∈ app(heightFunction, S(stage))) + ) + + // Height-`stage` arguments witness that the instance is in that introduction image. + have(argsInStageN |- argsInStageN /\ (c.term === c.term)) by Restate + c.variables2.foldRight((c.variables1, List[Variable[Ind]]()))((v, acc) => + val oldVariables = acc._1.init + val newVariables = v :: acc._2 + val vars = oldVariables ++ newVariables + thenHave( + argsInStageN |- existsSeq(newVariables, wellTypedFormula(vars.zip(c.specification))(app(heightFunction, stage)) /\ (c.term(vars) === c.term)) + ) by RightExists + (oldVariables, newVariables) + ) + thenHave(argsInStageN |- instanceInIntroImage) by Weakening + have((isHeight(heightFunction), stage ∈ N, argsInStageN) |- c.term ∈ app(heightFunction, S(stage))) by Cut(lastStep, imageInSuccessor) + + // Chain everything: height-`stage` arguments ⟹ instance in the ADT, then discharge the + // existential height witness and the existence of a height function. + have((isHeight(heightFunction), stage ∈ N, argsInStageN) |- c.term ∈ term) by Cut(lastStep, instanceInTerm) + thenHave((isHeight(heightFunction), stage ∈ N /\ argsInStageN) |- c.term ∈ term) by LeftAnd + thenHave((isHeight(heightFunction), exists(stage, stage ∈ N /\ argsInStageN)) |- c.term ∈ term) by LeftExists + have((isHeight(heightFunction), argsInTerm) |- c.term ∈ term) by Cut(argsShareHeight, lastStep) + thenHave((exists(heightFunction, isHeight(heightFunction)), argsInTerm) |- c.term ∈ term) by LeftExists + have(argsInTerm |- c.term ∈ term) by Cut(heightExists, lastStep) + } + ) + .toMap +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticConstructor.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticConstructor.scala new file mode 100644 index 000000000..c9e5be100 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticConstructor.scala @@ -0,0 +1,283 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.SetTheory.Base.Pair +import lisa.maths.SetTheory.Ordinals.Integer.successorInjectivity +import lisa.maths.SetTheory.Ordinals.Integer.zeroIsNotSucc +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.proofs.PropositionalFacts.equivalenceApply +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ + +/** + * Syntactic set theoretical interpretation of a constructor for an algebraic data type. + * In set theory, a constructor is a tuple containing the arguments it has been applied + * to, in addition to a tag identifying it among the constructors of its own ADT. + * + * E.g. `cons(1, nil())` is represented as `(tagcons, (1, ((tagnil, ∅), ∅)))` + * + * Tags are local to an ADT: they are the constructor's index in the declaration, so + * they stay small and the encoding of an ADT does not depend on what else has been + * declared. The flip side is that constructors of *different* ADTs may share a tag, + * and two nullary constructors of different ADTs have the same representation; only + * [[disjointness]] within one ADT is meaningful. + * + * Constructors injectivity is proved within this class. + * + * @constructor creates a new constructor out of a user specification + * @param specification types that the constructor takes as arguments + * @param variables1 variables used to represent the arguments of the constructor + * @param tag index of this constructor among the constructors of its ADT + * @param owner name of the ADT this constructor belongs to, used to qualify the names + * of the theorems proved here + */ +class SyntacticConstructor( + val specification: Seq[ConstructorArg], + val variables1: Seq[Variable[Ind]], + val variables2: Seq[Variable[Ind]], + val tag: Int, + val owner: String +) { + + require(tag >= 0, s"Constructor tag of $owner must be non-negative, got $tag.") + + private def toTerm(n: Int): Expr[Ind] = + require(n >= 0, "n must be a non-negative integer") + if n == 0 then ∅ else S(toTerm(n - 1)) + + /** + * Term representation of the tag of this constructor + */ + val tagTerm: Expr[Ind] = toTerm(tag) + + /** + * Sequence of variables used to represent the arguments of the constructor + */ + val variables: Seq[Variable[Ind]] = variables1 + + /** + * Number of arguments that this constructor takes + */ + val arity: Int = specification.length + + /** + * Sequence of type parameters of this constructor + */ + val typeParameters: Seq[Variable[Ind]] = specification.collect { case TypeArg(name) => + typeExprToTerm(name) + } + + /** + * Sequence of variables of the constructor with their respective domains. + */ + val signature1: Seq[(Variable[Ind], ConstructorArg)] = variables1.zip(specification) + + /** + * Alternative sequence of variables of the constructor with their respective domains. + */ + val signature2: Seq[(Variable[Ind], ConstructorArg)] = variables2.zip(specification) + + /** + * Sequence of variables of the constructor with their respective domains. + */ + val signature: Seq[(Variable[Ind], ConstructorArg)] = signature1 + + /** + * Internally, an instance of this constructor is represented as a list. The first + * element of this list is the tag of this constructor. The following elements are its + * arguments. We represent lists as chained pairs followed by the empty set. + * + * e.g. cons(1, nil()) --> (tagcons, (1, ((tagnil, ∅), ∅))) + * + * @param args the arguments of this instance of the constructor + */ + def term(args: Seq[Expr[Ind]]): Expr[Ind] = pair(tagTerm, subterm(args)) + + /** + * Internal representation of an instance of this constructor in which arguments are + * schematic variables. + */ + val term1: Expr[Ind] = term(variables1) + + /** + * Internal representation of an instance of this constructor in which arguments are an + * alternative set of schematic variables. + */ + val term2: Expr[Ind] = term(variables2) + + /** + * Internal representation of an instance of this constructor in which arguments are + * schematic variables. + */ + val term: Expr[Ind] = term1 + + /** + * Internal representation of an instance of this constructor without the tag + * + * @param args the arguments of this instance of the constructor + * + * @see [[this.term]] + */ + def subterm(args: Seq[Expr[Ind]]): Expr[Ind] = args.foldRight[Expr[Ind]](∅)(pair(_, _)) + + /** + * Internal representation of an instance of this constructor without the tag, in which + * arguments are schematic variables. + */ + val subterm1: Expr[Ind] = subterm(variables1) + + /** + * Internal representation of an instance of this constructor without the tag, in which + * arguments are an alternative set of schematic variables. + */ + val subterm2: Expr[Ind] = subterm(variables2) + + /** + * Internal representation of an instance of this constructor without the tag, in which + * arguments are schematic variables. + */ + val subterm: Expr[Ind] = subterm1 + + /** + * Theorem --- Injectivity of constructors. + * + * Two instances of this constructor are equal if and only if all of their arguments + * are pairwise equal + * + * e.g. cons(head1, tail1) === cons(head2, tail2) <=> head1 === head2 /\ tail1 === + * tail2 + */ + lazy val injectivity = + if arity == 0 then + Lemma.named(s"$owner/const${tag}_injectivity")(term1 === term2) { + have(thesis) by RightRefl + } + else + Lemma.named(s"$owner/const${tag}_injectivity")( + (term1 === term2) <=> seqEq(variables1, variables2) + ) { + + // STEP 1: Get rid of the tag using pair extensionality + have((term1 === term2) <=> (subterm1 === subterm2)) by + Congruence.from(Pair.extensionality of (a := tagTerm, b := subterm1, c := tagTerm, d := subterm2)) + + // STEP 2: Repeat pair extensionality until all variables have been pulled out of the term + variables1 + .zip(variables2) + .foldLeft( + Seq.empty[Variable[Ind]], + variables1, + Seq.empty[Variable[Ind]], + variables2, + lastStep + )((acc, v) => + + // pulledVars1 are the variables that have been pulled out of the left term + // remainingVars1 are the variables that are still in the left term + // pulledVars2 are the variables that have been pulled out of the right term + // remainingVars2 are the variables that are still in the right term + val (pulledVars1, remainingVars1, pulledVars2, remainingVars2, previousFact) = + acc + + // v1 and v2 are the variables that are being pulled out + val (v1, v2) = v + + val updatedPulledVars1 = pulledVars1 :+ v1 + val updatedPulledVars2 = pulledVars2 :+ v2 + val updatedRemainingVars1 = remainingVars1.tail + val updatedRemainingVars2 = remainingVars2.tail + + val subsubterm1 = subterm(updatedRemainingVars1) + val subsubterm2 = subterm(updatedRemainingVars2) + + have( + (pair(v1, subsubterm1) === pair(v2, subsubterm2)) <=> + ((v1 === v2) /\ (subsubterm1 === subsubterm2)) + ) by + Restate.from(Pair.extensionality of (a := v1, b := subsubterm1, c := v2, d := subsubterm2)) + have( + (seqEq(pulledVars1, pulledVars2) /\ + (pair(v1, subsubterm1) === pair(v2, subsubterm2))) <=> + (seqEq(pulledVars1, pulledVars2) /\ (v1 === v2) /\ + (subsubterm1 === subsubterm2)) + ) by Tautology.from(lastStep) + val newFact = have( + (term1 === term2) <=> + (seqEq(updatedPulledVars1, updatedPulledVars2) /\ + (subsubterm1 === subsubterm2)) + ) by Tautology.from(previousFact, lastStep) + + ( + updatedPulledVars1, + updatedRemainingVars1, + updatedPulledVars2, + updatedRemainingVars2, + newFact + ) + ) + } + + /** + * Tags identify constructors within one ADT, so the tag terms of two distinct + * constructors of the same ADT are provably different. + * + * The tags are concrete naturals `S^tag(∅)`; peeling `min(tag, other.tag)` + * successors via injectivity reduces the equality to `S^(maxTag - minTag)(∅) = ∅`, + * which is false. + */ + private[encoding] def tagDisequality(other: SyntacticConstructor): Theorem = { + val minTag = Math.min(tag, other.tag) + val maxTag = Math.max(tag, other.tag) + Lemma.generated(!(tagTerm === other.tagTerm)) { + val start = have(tagTerm === other.tagTerm |- toTerm(maxTag) === toTerm(minTag)) by Congruence + (1 to minTag).foldLeft(start)((fact, i) => + val midMaxTag = toTerm(maxTag - i) + val midMinTag = toTerm(minTag - i) + have( + S(midMaxTag) === S(midMinTag) |- midMaxTag === midMinTag + ) by Cut( + successorInjectivity of (n := midMaxTag, m := midMinTag), + equivalenceApply of ( + p1 := S(midMaxTag) === S(midMinTag), + p2 := midMaxTag === midMinTag + ) + ) + have(tagTerm === other.tagTerm |- midMaxTag === midMinTag) by Cut(fact, lastStep) + ) + val chainInjectivity = + thenHave(!(toTerm(maxTag - minTag) === ∅) |- !(tagTerm === other.tagTerm)) by Restate + have(toTerm(maxTag - minTag) =/= ∅) by Restate.from( + zeroIsNotSucc of (n := toTerm(maxTag - minTag - 1)) + ) + have(thesis) by Cut(lastStep, chainInjectivity) + } + } + + /** + * Theorem --- Disjointness of distinct constructors. + * + * Two instances of distinct constructors of the same ADT are never equal, because + * their tags differ. This is the structural counterpart of [[injectivity]], phrased + * over the internal tuple encoding [[term]]. + * + * Since tags are ADT-local, this is only meaningful within one ADT: two constructors + * of different ADTs may legitimately share a tag and even a representation. + * + * e.g. nil =/= cons(head)(tail) + */ + def disjointness(other: SyntacticConstructor): Theorem = { + require(this != other, "disjointness requires two distinct constructors.") + require( + tag != other.tag, + s"disjointness requires two constructors of the same ADT, but $owner#$tag and " + + s"${other.owner}#${other.tag} share a tag; tags are only unique within an ADT." + ) + Lemma.generated(!(term1 === other.term2)) { + have(thesis) by Tautology.from( + Pair.extensionality of (a := tagTerm, b := subterm1, c := other.tagTerm, d := other.subterm2), + tagDisequality(other) + ) + } + } + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightADT.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightADT.scala new file mode 100644 index 000000000..e79148438 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightADT.scala @@ -0,0 +1,62 @@ +package lisa.maths.SetTheory.Types.ADT.height + +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.height.proofs.SuccessorFacts +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.semantics.DefinedProperty + +final class HeightADT( + name: String, + typeVariablesSeq: Seq[Variable[Ind]], + isConstructor: Expr[Ind >>: Ind >>: Prop] +) { + + protected inline final def app(f: Expr[Ind], x: Expr[Ind]): Expr[Ind] = + lisa.maths.SetTheory.Functions.Predef.app(f)(x) + + def inIntroImage(s: Expr[Ind])(y: Expr[Ind]): Expr[Prop] = + isConstructor(y)(s) \/ (y ∈ s) + + def inExtIntroImage(f: Expr[Ind])(x: Expr[Ind]): Expr[Prop] = + (f =/= ∅) /\ inIntroImage(⋃(range(f)))(x) + + def isHeightCore(h: Expr[Ind]): Expr[Prop] = + function(h) /\ + (dom(h) === N) /\ + ∀(n ∈ N, ∀(x, x ∈ app(h, n) <=> inExtIntroImage(h ↾ n)(x))) + + // `isHeight` is an *opaque* defined predicate `${name}/isHeight[typeVars](h)` whose + // definition unfolds to `isHeightCore(h)`. Keeping it opaque stops tactics (Tautology) + // and the kernel checker from decomposing the ~400-char `isHeightCore` conjunction + private val isHeightSym = DefinedProperty( + s"$name/isHeight", + typeVariablesSeq, + h, + isHeightCore + ) + + def isHeight(h: Expr[Ind]): Expr[Prop] = isHeightSym.term #@ h + + /** + * Unfold `isHeight(h)` to its core conjunction. + */ + private[ADT] val heightIsCore = isHeightSym.unfold + + /** + * Fold the core conjunction back into the opaque `isHeight(h)`. + */ + private[ADT] val coreIsHeight = isHeightSym.fold + + /** + * Lemma --- There is no element of height 0 in the ADT. + * + * `!∃x ∈ adt. height(x) = 0` + */ + val heightZero = Lemma.generated(isHeight(h) |- !(x ∈ app(h, ∅))) { + have(thesis) by Cut( + heightIsCore, + SuccessorFacts.heightZeroAt(isConstructor, h, x) + ) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightConstructorData.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightConstructorData.scala new file mode 100644 index 000000000..b18d03308 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightConstructorData.scala @@ -0,0 +1,15 @@ +package lisa.maths.SetTheory.Types.ADT.height + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.pair +import lisa.maths.SetTheory.Types.ADT.syntax.AST.ConstructorArg + +final case class HeightConstructorData( + variables: Seq[Variable[Ind]], + signature: Seq[(Variable[Ind], ConstructorArg)], + subterm: Expr[Ind], + tagTerm: Expr[Ind] +) { + val arity: Int = signature.length + val term = pair(tagTerm, subterm) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightConstructors.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightConstructors.scala new file mode 100644 index 000000000..d43ca05bf --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightConstructors.scala @@ -0,0 +1,207 @@ +package lisa.maths.SetTheory.Types.ADT.height + +import lisa.maths.Quantifiers.existsOneAlternativeDefinition +import lisa.maths.Quantifiers.∃! +import lisa.maths.SetTheory.Base.Pair.given +import lisa.maths.SetTheory.Base.Subset +import lisa.maths.SetTheory.Ordinals.Integer.subsetSuccessor +import lisa.maths.SetTheory.Ordinals.Integer.successorInOmega +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.height.proofs.CoreFacts +import lisa.maths.SetTheory.Types.ADT.height.proofs.SuccessorFacts +import lisa.maths.SetTheory.Types.ADT.height.proofs.UniquenessFacts +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.tactics.Cuts +import lisa.utils.prooflib.QuantifiersIntro + +final class HeightConstructors( + base: HeightADT, + constructors: Seq[HeightConstructorData], + heightStageSet: HeightStageSet, + isConstructor: Expr[Ind >>: Ind >>: Prop] +) { + + protected inline final def app(f: Expr[Ind], x: Expr[Ind]): Expr[Ind] = + lisa.maths.SetTheory.Functions.Predef.app(f)(x) + + private def inIntroImage(s: Expr[Ind])(y: Expr[Ind]): Expr[Prop] = + base.inIntroImage(s)(y) + + /** + * Lemma --- If two functions are the height function then they are the same. + * + * `f = height /\ h = height => f = h` + */ + val heightUniqueness = Lemma.generated((base.isHeight(f), base.isHeight(h)) |- f === h) { + + have(thesis) by Cuts(UniquenessFacts.uniquenessAt(isConstructor, f, h))( + introFunctionMonoHyp, + base.heightIsCore of (h := f), + base.heightIsCore of (h := h) + ) + } + + lazy val heightExistsOne = Lemma.generated(∃!(h, base.isHeight(h))) { + + val existencePart = have(∃(h, base.isHeight(h))) by + Restate.from(heightStageSet.heightExists of (h := h)) + + have(base.isHeight(f) /\ base.isHeight(h) ==> (f === h)) by + Restate.from(heightUniqueness) + val uniquenessAll = thenHave( + ∀(f, ∀(h, base.isHeight(f) /\ base.isHeight(h) ==> (f === h))) + ) by Generalize + + have( + ∃(h, base.isHeight(h)) /\ + ∀(f, ∀(h, base.isHeight(f) /\ base.isHeight(h) ==> (f === h))) + ) by RightAnd(existencePart, uniquenessAll) + + thenHave(thesis) by Substitute( + existsOneAlternativeDefinition of (x := h, P := λ(h, base.isHeight(h))) + ) + } + + /** + * Lemma --- The introduction function is monotonic with respect to set inclusion. + * + * `s ⊆ t |- introductionFunction(s) ⊆ introductionFunction(t)` + * + * Derived from `isConstructorMonoHyp` (the concrete `isConstructor` monotonicity) plus + * subset elimination for the membership disjunct: `inIntroImage` is just + * `isConstructor(x)(s) \/ x ∈ s`, so monotonicity of each disjunct lifts to the whole. + * This avoids re-proving the constructor-by-constructor argument that already lives in + * `isConstructorMonoHyp`. + */ + private lazy val introFunctionMonoHyp: Theorem = Lemma.generated( + CoreFacts.introFunctionMono.substitute(CoreFacts.isConstructor := isConstructor) + ) { + val ctorMono = have(s ⊆ t |- isConstructor(x)(s) ==> isConstructor(x)(t)) by Cut( + isConstructorMonoHyp, + CoreFacts.isConstructorMonotonic.of(CoreFacts.isConstructor := isConstructor) + ) + have(s ⊆ t |- forall(z, z ∈ s ==> z ∈ t)) by + Congruence.from(subsetAxiom of (x := s, y := t)) + val memMono = thenHave(s ⊆ t |- x ∈ s ==> x ∈ t) by InstantiateForall(x) + + have(s ⊆ t |- inIntroImage(s)(x) ==> inIntroImage(t)(x)) by + Tautology.from(ctorMono, memMono) + thenHave(s ⊆ t |- forall(x, inIntroImage(s)(x) ==> inIntroImage(t)(x))) by RightForall + + thenHave(s ⊆ t ==> forall(x, inIntroImage(s)(x) ==> inIntroImage(t)(x))) by RightImplies + thenHave(thesis) by Generalize + } + + private lazy val isConstructorMonoHyp: Theorem = Lemma.generated( + CoreFacts.isConstructorMono.substitute(CoreFacts.isConstructor := isConstructor) + ) { + val subsetST = s ⊆ t + val isConstructorXS = isConstructor(x)(s) + val isConstructorXT = isConstructor(x)(t) + + val isConstructorXSImpliesT = + for c <- constructors yield + val labelEq = x === c.term + val isConstructorCXS = heightStageSet.constructorPredicate(c, x, s) + val isConstructorCXT = heightStageSet.constructorPredicate(c, x, t) + val varsWellTypedS = wellTypedFormula(c.signature)(s) + val varsWellTypedT = wellTypedFormula(c.signature)(t) + + if c.arity == 0 then have((subsetST, isConstructorCXS) |- isConstructorXT) by Restate + else + have(s ⊆ t |- forall(z, z ∈ s ==> z ∈ t)) by + Congruence.from(subsetAxiom of (x := s, y := t)) + val subsetElimination = thenHave(s ⊆ t |- z ∈ s ==> z ∈ t) by + InstantiateForall(z) + val andSeq = + for (v, ty) <- c.signature + yield have((subsetST, varsWellTypedS) |- v ∈ ty.getOrElse(t)) by + Weakening(subsetElimination of (z := v)) + val expandingDomain = have((subsetST, varsWellTypedS) |- varsWellTypedT) by + RightAnd((andSeq).map(_.kernel)) + val weakeningLabelEq = have(labelEq |- labelEq) by Hypothesis + have((subsetST, varsWellTypedS, labelEq) |- varsWellTypedT /\ labelEq) by + RightAnd(expandingDomain, weakeningLabelEq) + + thenHave((subsetST, varsWellTypedS, labelEq) |- isConstructorCXT) by + QuantifiersIntro(c.variables) + thenHave((subsetST, varsWellTypedS /\ labelEq) |- isConstructorCXT) by LeftAnd + thenHave((subsetST, isConstructorCXS) |- isConstructorCXT) by + QuantifiersIntro(c.variables) + thenHave((subsetST, isConstructorCXS) |- isConstructorXT) by Weakening + + val constructorBranch = + if constructors.isEmpty then have((subsetST, isConstructorXS) |- isConstructorXT) by Restate + else + have((subsetST, isConstructorXS) |- isConstructorXT) by + LeftOr((isConstructorXSImpliesT).map(_.kernel)) + + have(s ⊆ t ==> (isConstructor(x)(s) ==> isConstructor(x)(t))) by Restate.from(constructorBranch) + thenHave(thesis) by Generalize + } + + /** + * Lemma --- The height function is monotonic. + */ + val heightMonotonic = Lemma.generated( + (base.isHeight(h), n ∈ N, m ∈ N, m ⊆ n) |- app(h, m) ⊆ app(h, n) + ) { + have(thesis) by Cuts(CoreFacts.heightMonotonicAt(isConstructor, h, n, m))( + base.heightIsCore, + introFunctionMonoHyp + ) + } + + val heightMembershipMonotonic = Lemma.generated( + (base.isHeight(h), n ∈ N, m ∈ N, m ⊆ n, x ∈ app(h, m)) |- x ∈ app(h, n) + ) { + assume(base.isHeight(h), n ∈ N, m ∈ N, m ⊆ n, x ∈ app(h, m)) + + val hSubset = have(app(h, m) ⊆ app(h, n)) by Weakening(heightMonotonic) + + have(x ∈ app(h, m) ==> x ∈ app(h, n)) by Cut( + hSubset, + Subset.membership of (x := app(h, m), y := app(h, n), z := x) + ) + thenHave(thesis) by Restate + } + + val heightSuccessorInclusion = Lemma.generated( + (base.isHeight(h), n ∈ N, x ∈ app(h, n)) |- x ∈ app(h, S(n)) + ) { + assume(base.isHeight(h)) + val nInN = assume(n ∈ N) + assume(x ∈ app(h, n)) + val succInN = have(S(n) ∈ N) by Substitute(successorInOmega of (n := n))(nInN) + have(x ∈ app(h, S(n))) by Cuts(heightMembershipMonotonic of (m := n, n := S(n)))( + succInN, + subsetSuccessor of (n := n) + ) + thenHave(thesis) by Restate + } + + /** + * Lemma --- The set of elements of height n + 1 is the introduction image of height n. + */ + val heightSuccessorWeak = Lemma.generated( + (base.isHeight(h), n ∈ N) |- + x ∈ app(h, S(n)) <=> inIntroImage(app(h, n))(x) + ) { + have(thesis) by Cuts(SuccessorFacts.heightSuccessorWeakAt(isConstructor, h, n, x))( + base.heightIsCore, + introFunctionMonoHyp + ) + } + + private[ADT] lazy val heightSuccessorStrong = Lemma.generated( + (base.isHeight(h), n ∈ N) |- + x ∈ app(h, S(n)) <=> isConstructor(x)(app(h, n)) + ) { + have(thesis) by Cuts(SuccessorFacts.heightSuccessorStrongAt(isConstructor, h, n, x))( + base.heightIsCore, + introFunctionMonoHyp, + isConstructorMonoHyp + ) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightStageSet.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightStageSet.scala new file mode 100644 index 000000000..04ef93ec1 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightStageSet.scala @@ -0,0 +1,238 @@ +package lisa.maths.SetTheory.Types.ADT.height + +import lisa.maths.SetTheory.Base.CartesianProduct +import lisa.maths.SetTheory.Base.CartesianProduct.× +import lisa.maths.SetTheory.Base.Comprehension +import lisa.maths.SetTheory.Base.Comprehension.| +import lisa.maths.SetTheory.Base.Pair.given +import lisa.maths.SetTheory.Base.Singleton +import lisa.maths.SetTheory.Base.Subset +import lisa.maths.SetTheory.Base.Union +import lisa.maths.SetTheory.Base.Union.∪ +import lisa.maths.SetTheory.Functions.Predef.range +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.height.FiniteUnion.memberSubsetOfUnionList +import lisa.maths.SetTheory.Types.ADT.height.FiniteUnion.unionList +import lisa.maths.SetTheory.Types.ADT.height.proofs.CoreFacts +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.semantics.DefinedSymbol +import lisa.maths.SetTheory.Types.ADT.support.tactics.Cuts +import lisa.maths.SetTheory.Types.ADT.syntax.AST.ConstructorArg +import lisa.utils.prooflib.QuantifiersIntro +import lisa.utils.prooflib.Thm + +/** + * Builds finite unions and proves inclusion of their components. + */ +private[height] object FiniteUnion { + + /** + * Forms a left-nested union, starting with the empty set. + */ + def unionList(elems: Seq[Expr[Ind]]): Expr[Ind] = + elems.foldLeft[Expr[Ind]](∅)(_ ∪ _) + + private lazy val subsetOfUnion = Lemma.generated(x ⊆ y |- x ⊆ (y ∪ z)) { + val yInUnion = have(y ⊆ (y ∪ z)) by Restate.from(Union.leftSubset of (x := y, y := z)) + have(thesis) by Cut(yInUnion, Subset.transitivity of (x := x, y := y, z := y ∪ z)) + } + + /** + * Proves that a listed component is included in the union, rejecting absent components. + */ + def memberSubsetOfUnionList(elems: Seq[Expr[Ind]], member: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = { + val index = elems.indexOf(member) + require(index >= 0, s"Finite union does not contain the requested component $member.") + val prefix = unionList(elems.take(index)) + val initialUnion = prefix ∪ member + val initial = have(member ⊆ initialUnion) by Weakening(Union.rightSubset of (x := prefix, y := member)) + elems.iterator + .drop(index + 1) + .foldLeft[(Expr[Ind], Thm)]((initialUnion, initial)) { case ((union, inclusion), next) => + val extended = union ∪ next + val step = have(member ⊆ extended) by Cut(inclusion, subsetOfUnion of (x := member, y := union, z := next)) + (extended, step) + } + ._2 + } +} + +final class HeightStageSet( + name: String, + typeVariablesSeq: Seq[Variable[Ind]], + base: HeightADT, + constructors: Seq[HeightConstructorData], + isConstructor: Expr[Ind >>: Ind >>: Prop] +) { + private val φ = variable[Ind >>: Prop] + private val predicateSubject = Variable[Ind](freshId(constructors.flatMap(_.variables) :+ isConstructor, "constructorSubject")) + private val predicateDomain = Variable[Ind](freshId(constructors.flatMap(_.variables) ++ Seq(isConstructor, predicateSubject), "constructorDomain")) + private val constructorPredicates = constructors.map(c => c -> existsSeq(c.variables, wellTypedFormula(c.signature)(predicateDomain) /\ (predicateSubject === c.term))).toMap + + /** + * Describes one constructor branch without capturing the supplied subject or domain. + */ + private[height] def constructorPredicate( + c: HeightConstructorData, + x: Expr[Ind], + s: Expr[Ind] + ): Expr[Prop] = + constructorPredicates(c).substitute(predicateSubject := x, predicateDomain := s) + + private val unionRangeF = ⋃(range(f)) + + private def domainOf(ty: ConstructorArg): Expr[Ind] = ty.getOrElse(unionRangeF) + + private def subProduct(sig: Seq[(Variable[Ind], ConstructorArg)]): Expr[Ind] = + sig.foldRight[Expr[Ind]](Singleton.singleton(∅)) { case ((_, ty), acc) => domainOf(ty) × acc } + + private def ctorProduct(c: HeightConstructorData): Expr[Ind] = + Singleton.singleton(c.tagTerm) × subProduct(c.signature) + + private val seedElems = unionRangeF +: constructors.map(ctorProduct) + private val bound = unionList(seedElems) + private val stageBody = { x ∈ bound | base.inExtIntroImage(f)(x) } + private val definedStage = new DefinedSymbol( + name = s"$name/stageSet", + parametersSeq = typeVariablesSeq, + body = λ(f, stageBody) + ) + private val stageSetTerm: Expr[Ind >>: Ind] = definedStage.term + + private val stageSetSpecInst: Theorem = Lemma.generated( + CoreFacts.stageSetSpec.substitute(CoreFacts.stageSet := stageSetTerm, CoreFacts.isConstructor := isConstructor) + ) { + + // Bounding strategy (plain ZF, no Tarski universe): every constructor term + // c.term = (tagTerm, (v₁, (… , (vₖ, ∅)))) + // lies in the iterated cartesian product matching its pairing shape, + // ctorProduct(c) = {tagTerm} × (D₁ × (… × (Dₖ × {∅}))), Dᵢ = ty.getOrElse(⋃range f), + // which is a set by Replacement/Union (no large-cardinal assumption). The stage is then + // carved out of bound = ⋃range f ∪ ctorProduct(c₁) ∪ … ∪ ctorProduct(cₘ) by Separation. + // Each constructor term lives in its product, given its arguments are well-typed in ⋃range f. + def constructorTermInProduct(c: HeightConstructorData)(using + proof: lisa.SetTheoryLibrary.Proof + ): Thm = { + val typedArgs = wellTypedFormula(c.signature)(unionRangeF) + val emptyInSeed = have(∅ ∈ Singleton.singleton(∅)) by + Restate.from(Singleton.membership of (x := ∅, y := ∅)) + // Build the nested-pair subterm right-to-left, threading membership in the matching product. + val emptySet: Expr[Ind] = ∅ + val subBuild = c.signature.reverse.foldLeft((emptySet, Singleton.singleton(∅), emptyInSeed)) { case ((curSub, curProd, curFact), (v, ty)) => + val d = domainOf(ty) + val vInD = have(typedArgs |- v ∈ d) by Restate + val pairFact = have(typedArgs |- pair(v, curSub) ∈ (d × curProd)) by + Cuts(CartesianProduct.membershipSufficientCondition of (x := v, A := d, y := curSub, B := curProd))(vInD, curFact) + (pair(v, curSub), d × curProd, pairFact) + } + val subtermInProduct = have(typedArgs |- c.subterm ∈ subProduct(c.signature)) by + Restate.from(subBuild._3) + + val tagInSingleton = have(c.tagTerm ∈ Singleton.singleton(c.tagTerm)) by + Restate.from(Singleton.membership of (x := c.tagTerm, y := c.tagTerm)) + // `c.term == (tagTerm, subterm)`; pair them inside `{tagTerm} × subProduct`. + have(typedArgs |- c.term ∈ ctorProduct(c)) by Cuts( + CartesianProduct.membershipSufficientCondition of + (x := c.tagTerm, A := Singleton.singleton(c.tagTerm), y := c.subterm, B := subProduct(c.signature)) + )(tagInSingleton, subtermInProduct) + } + + val unionRangeSubsetBound = have(unionRangeF ⊆ bound) by + Restate.from(memberSubsetOfUnionList(seedElems, unionRangeF)) + + val constructorOnlyCase = + if constructors.isEmpty then + // With no constructors `isConstructor(x)(·)` is `False`, so the implication holds vacuously. + have(isConstructor(x)(unionRangeF) |- x ∈ bound) by Restate + else + val branches = constructors.map(c => + val typedEq = wellTypedFormula(c.signature)(unionRangeF) /\ (x === c.term) + val termInProductFact = constructorTermInProduct(c) + val prodSubsetBound = have(ctorProduct(c) ⊆ bound) by + Restate.from(memberSubsetOfUnionList(seedElems, ctorProduct(c))) + val branch = have(typedEq |- x ∈ bound) subproof { + val xEqTerm = have(typedEq |- x === c.term) by Restate + val typedArgsFact = have(typedEq |- wellTypedFormula(c.signature)(unionRangeF)) by Restate + // The constructor term lives in its product, itself a subset of `bound`; rewrite `x` to it. + val termInProd = have(typedEq |- c.term ∈ ctorProduct(c)) by Cut(typedArgsFact, termInProductFact) + val termInBound = have(typedEq |- c.term ∈ bound) by Tautology.from( + termInProd, + prodSubsetBound, + Subset.membership of (x := ctorProduct(c), y := bound, z := c.term) + ) + have(typedEq |- x ∈ bound <=> c.term ∈ bound) by Congruence.from(xEqTerm) + have(thesis) by Substitute(lastStep)(termInBound) + } + have(constructorPredicate(c, x, unionRangeF) |- x ∈ bound) by + QuantifiersIntro(c.variables)(branch) + ) + have(isConstructor(x)(unionRangeF) |- x ∈ bound) by + LeftOr((branches).map(_.kernel)) + + val constructorCaseToBound = have( + (base.inExtIntroImage(f)(x), isConstructor(x)(unionRangeF)) |- x ∈ bound + ) by Weakening(constructorOnlyCase) + + val membershipInBound = have(x ∈ unionRangeF |- x ∈ bound) by Tautology.from( + unionRangeSubsetBound, + Subset.membership of (x := unionRangeF, y := bound, z := x) + ) + val membershipCaseToBound = have( + (base.inExtIntroImage(f)(x), x ∈ unionRangeF) |- x ∈ bound + ) by Weakening(membershipInBound) + + val extIntroInBound = have(base.inExtIntroImage(f)(x) |- x ∈ bound) subproof { + // `inExtIntroImage` unfolds to `(f ≠ ∅) ∧ (isConstructor(x)(⋃f) ∨ x ∈ ⋃f)`; split the disjunction. + val introBranch = have(base.inExtIntroImage(f)(x) |- isConstructor(x)(unionRangeF) \/ (x ∈ unionRangeF)) by Restate + have((base.inExtIntroImage(f)(x), isConstructor(x)(unionRangeF) \/ (x ∈ unionRangeF)) |- x ∈ bound) by + LeftOr(constructorCaseToBound, membershipCaseToBound) + have(thesis) by Cut(introBranch, lastStep) + } + + val stageBodyMembership = have(x ∈ stageBody <=> x ∈ bound /\ base.inExtIntroImage(f)(x)) by + Restate.from( + Comprehension.membership of (x := x, y := bound, φ := λ(x, base.inExtIntroImage(f)(x))) + ) + + val stageMembership = have(x ∈ stageBody <=> base.inExtIntroImage(f)(x)) by + Tautology.from(stageBodyMembership, extIntroInBound) + val stageEquality = have(stageBody === stageSetTerm(f)) by Restate.from(definedStage.definition) + val replacement = Variable[Ind](freshId(Seq(stageBody, stageSetTerm, base.inExtIntroImage(f)(x)), "stageReplacement")) + val namedMembership = have((stageBody === stageSetTerm(f)) |- (x ∈ stageSetTerm(f) <=> base.inExtIntroImage(f)(x))) by + RightSubst( + Seq(stageBody -> stageSetTerm(f)), + Seq(replacement) -> (x ∈ replacement <=> base.inExtIntroImage(f)(x)) + )(stageMembership) + have(x ∈ stageSetTerm(f) <=> base.inExtIntroImage(f)(x)) by Cut(stageEquality, namedMembership) + thenHave(∀(x, x ∈ stageSetTerm(f) <=> base.inExtIntroImage(f)(x))) by RightForall + thenHave(∀(f, ∀(x, x ∈ stageSetTerm(f) <=> base.inExtIntroImage(f)(x)))) by + RightForall + thenHave(thesis) by Restate + } + + /** + * The height function built from the explicit stage operation. + */ + val height: Expr[Ind] = CoreFacts.heightFunctionAt(stageSetTerm) + + /** + * The constructed function satisfies the height recurrence. + */ + val heightValid: Theorem = Lemma.generated(base.isHeight(height)) { + val coreForm = CoreFacts.isHeightCore(height).substitute(CoreFacts.isConstructor := isConstructor) + val core = have(coreForm) by Cut( + stageSetSpecInst, + CoreFacts.heightFunctionSpecAt(stageSetTerm, isConstructor) + ) + have(thesis) by Cut(core, base.coreIsHeight.of(h := height)) + } + + /** + * A height function exists, witnessed by the constructed function. + */ + val heightExists: Theorem = Lemma.generated(∃(h, base.isHeight(h))) { + have(base.isHeight(height)) by Restate.from(heightValid) + thenHave(thesis) by RightExists + } + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightTerms.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightTerms.scala new file mode 100644 index 000000000..5675aba69 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/HeightTerms.scala @@ -0,0 +1,132 @@ +package lisa.maths.SetTheory.Types.ADT.height + +import lisa.maths.Quantifiers.existsEpsilon +import lisa.maths.SetTheory.Base.Union.∪ +import lisa.maths.SetTheory.Base._ +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Functions.UnionRange.unionRangeMembership +import lisa.maths.SetTheory.Ordinals.Integer.emptyInOmega +import lisa.maths.SetTheory.Ordinals.Integer.unionInOmega +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.height.FiniteUnion.memberSubsetOfUnionList +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.tactics.Cuts +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ +import lisa.utils.prooflib.Thm + +/** + * Relates carrier membership and constructor argument typing to finite height stages. + */ +final class HeightTerms( + base: HeightADT, + constructorsTheory: HeightConstructors, + constructors: Seq[HeightConstructorData], + term: Expr[Ind], + termEqualsUnion: Theorem +) { + + protected inline final def app(f: Expr[Ind], x: Expr[Ind]): Expr[Ind] = + lisa.maths.SetTheory.Functions.Predef.app(f)(x) + + private def constructorVarsInDomain( + c: HeightConstructorData, + s: Expr[Ind] + ): Expr[Prop] = wellTypedFormula(c.signature)(s) + + /** + * Characterizes carrier membership by membership in some finite stage. + */ + val termHasHeight = Lemma.generated( + base.isHeight(h) |- x ∈ term <=> ∃(n, n ∈ N /\ x ∈ app(h, n)) + ) { + // Unfold isHeight(h) to extract function(h) and dom(h) === N. + val hFunction = have(base.isHeight(h) |- function(h)) by Weakening(base.heightIsCore) + val hDom = have(base.isHeight(h) |- dom(h) === N) by Weakening(base.heightIsCore) + + // Membership in ⋃range(h) unfolds to an existential over the domain of h. + val unionMem = + have(base.isHeight(h) |- x ∈ ⋃(range(h)) <=> ∃(n, n ∈ dom(h) /\ x ∈ app(h, n))) by + Cut(hFunction, unionRangeMembership of (z := x)) + + // Rewrite the carrier and the domain using their defining equalities. + val termExistsDom = + have(base.isHeight(h) |- x ∈ term <=> ∃(n, n ∈ dom(h) /\ x ∈ app(h, n))) by + Substitute(termEqualsUnion)(unionMem) + have(thesis) by Substitute(hDom)(termExistsDom) + } + + /** + * Gives every constructor's arguments a common stage, keeping payload typing unchanged. + */ + val termsHaveHeight = constructors.map { c => + c -> Lemma.generated( + base.isHeight(h) |- + (constructorVarsInDomain(c, term) <=> + ∃(n, n ∈ N /\ constructorVarsInDomain(c, app(h, n)))) + ) { + val recursiveArgs = c.signature.collect { case (v, SelfRef) => v } + val payloadTyping = seqAnd(c.signature.collect { case (v, ty: TypeArg) => v ∈ ty.getOrElse(term) }) + val atTerm = constructorVarsInDomain(c, term) + val atStage = n ∈ N /\ constructorVarsInDomain(c, app(h, n)) + + val backward = have(base.isHeight(h) |- ∃(n, atStage) ==> atTerm) subproof { + val recursiveAtTerm = recursiveArgs.map { v => + have((base.isHeight(h), atStage) |- n ∈ N /\ v ∈ app(h, n)) by Restate + thenHave((base.isHeight(h), atStage) |- ∃(n, n ∈ N /\ v ∈ app(h, n))) by RightExists + have((base.isHeight(h), atStage) |- v ∈ term) by + Substitute(termHasHeight of (x := v))(lastStep) + } + val payloads = have((base.isHeight(h), atStage) |- payloadTyping) by Restate + have((base.isHeight(h), atStage) |- atTerm) by RightAnd(((payloads +: recursiveAtTerm)).map(_.kernel)) + thenHave((base.isHeight(h), ∃(n, atStage)) |- atTerm) by LeftExists + } + + val forward = have(base.isHeight(h) |- atTerm ==> ∃(n, atStage)) subproof { sp ?=> + // Only recursive fields need stage witnesses. Payload types do not depend on the stage. + val witnesses = recursiveArgs.map { v => + val exStage = ∃(n, n ∈ N /\ v ∈ app(h, n)) + val existsStage = have((base.isHeight(h), atTerm) |- exStage) by + Substitute(termHasHeight of (x := v))(have((base.isHeight(h), atTerm) |- v ∈ term) by Restate) + val wh = ε(n, n ∈ N /\ v ∈ app(h, n)) + val whProp = have(exStage |- wh ∈ N /\ v ∈ app(h, wh)) by + Restate.from(existsEpsilon of (x := n, P := λ(n, n ∈ N /\ v ∈ app(h, n)))) + val whBoth = have((base.isHeight(h), atTerm) |- wh ∈ N /\ v ∈ app(h, wh)) by Cut(existsStage, whProp) + val whInNat = have((base.isHeight(h), atTerm) |- wh ∈ N) by Weakening(whBoth) + val whBody = have((base.isHeight(h), atTerm) |- v ∈ app(h, wh)) by Weakening(whBoth) + (v, wh, whInNat, whBody) + } + + // The empty union gives stage zero for constructors with no recursive fields. + val stages = witnesses.map(_._2) + val zeroInNat = have((base.isHeight(h), atTerm) |- ∅ ∈ N) by Weakening(emptyInOmega) + val (commonStage, commonInNat) = witnesses.foldLeft[(Expr[Ind], Thm)]((∅, zeroInNat)) { case ((previous, previousInNat), (_, wh, whInNat, _)) => + val next = previous ∪ wh + val unionStep = have((previous ∈ N, wh ∈ N) |- next ∈ N) by + Restate.from(unionInOmega of (a := previous, b := wh)) + val step = have((base.isHeight(h), atTerm, wh ∈ N) |- next ∈ N) by + Cut(previousInNat, unionStep) + val nextInNat = have((base.isHeight(h), atTerm) |- next ∈ N) by Cut(whInNat, step) + (next, nextInNat) + } + + val recursiveAtCommon = witnesses.map { (v, wh, whInNat, whBody) => + val included = have(wh ⊆ commonStage) by Restate.from(memberSubsetOfUnionList(stages, wh)) + have((base.isHeight(h), atTerm) |- v ∈ app(h, commonStage)) by + Cuts(constructorsTheory.heightMembershipMonotonic of (x := v, m := wh, n := commonStage))( + commonInNat, + whInNat, + included, + whBody + ) + } + val payloads = have((base.isHeight(h), atTerm) |- payloadTyping) by Restate + have((base.isHeight(h), atTerm) |- commonStage ∈ N /\ constructorVarsInDomain(c, app(h, commonStage))) by + RightAnd(((commonInNat +: payloads +: recursiveAtCommon)).map(_.kernel)) + thenHave((base.isHeight(h), atTerm) |- ∃(n, atStage)) by RightExists + } + + have(thesis) by RightIff(forward, backward) + } + }.toMap + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/CoreFacts.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/CoreFacts.scala new file mode 100644 index 000000000..72037309a --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/CoreFacts.scala @@ -0,0 +1,232 @@ +package lisa.maths.SetTheory.Types.ADT.height.proofs + +import lisa.maths.SetTheory.Base.Subset.supersetNotEmpty +import lisa.maths.SetTheory.Functions.BasicTheorems.functionOnDomain +import lisa.maths.SetTheory.Functions.BasicTheorems.functionOnIsFunction +import lisa.maths.SetTheory.Functions.Operations.Restriction.setMonotonic +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Functions.UnionRange.unionRangeMonotonic +import lisa.maths.SetTheory.Ordinals.OmegaFacts +import lisa.maths.SetTheory.Ordinals.Ordinal.ordinal +import lisa.maths.SetTheory.Ordinals.TransfiniteRecursion +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.utils.prooflib.Thm + +private[height] object CoreFacts { + + protected inline final def app(f: Expr[Ind], x: Expr[Ind]): Expr[Ind] = + lisa.maths.SetTheory.Functions.Predef.app(f)(x) + + val isConstructor = variable[Ind >>: Ind >>: Prop] + val stageSet = variable[Ind >>: Ind] + + def inIntroImage(s: Expr[Ind])(y: Expr[Ind]): Expr[Prop] = + isConstructor(y)(s) \/ (y ∈ s) + + def inExtIntroImage(f: Expr[Ind])(x: Expr[Ind]): Expr[Prop] = + (f =/= ∅) /\ inIntroImage(⋃(range(f)))(x) + + def isHeightCore(h: Expr[Ind]): Expr[Prop] = + function(h) /\ + (dom(h) === N) /\ + ∀(n ∈ N, ∀(x, x ∈ app(h, n) <=> inExtIntroImage(h ↾ n)(x))) + + val introFunctionMono: Expr[Prop] = + ∀(s, ∀(t, s ⊆ t ==> ∀(x, inIntroImage(s)(x) ==> inIntroImage(t)(x)))) + + val isConstructorMono: Expr[Prop] = + ∀(s, ∀(t, ∀(x, s ⊆ t ==> (isConstructor(x)(s) ==> isConstructor(x)(t))))) + + val stageSetSpec: Expr[Prop] = + ∀(f, ∀(x, x ∈ stageSet(f) <=> inExtIntroImage(f)(x))) + + private val stepFunction: Expr[Ind >>: Ind >>: Ind] = λ(n, stageSet) + private val heightFunction: Expr[Ind] = TransfiniteRecursion.transfiniteRecursionFunction(stepFunction)(N) + + private val heightFunctionSpec = Lemma(stageSetSpec |- isHeightCore(heightFunction)) { + val Func = variable[Ind >>: Ind >>: Ind] + val stepFunc = stepFunction + val recFun = heightFunction + assume(stageSetSpec) + + val recSpec0 = have( + ordinal(N) |- + functionOn(recFun)(N) /\ + ∀(n ∈ N, app(recFun, n) === stepFunc(n)(recFun ↾ n)) + ) by Tautology.from( + TransfiniteRecursion.transfiniteRecursionFunctionSpec.of(Func := stepFunc, α := N) + ) + val recSpec = have( + functionOn(recFun)(N) /\ ∀(n ∈ N, app(recFun, n) === stepFunc(n)(recFun ↾ n)) + ) by Cut(OmegaFacts.isOrdinal, recSpec0) + + have( + ∀(n ∈ N, app(recFun, n) === stepFunc(n)(recFun ↾ n)) + ) by Weakening(recSpec) + val recEq0 = thenHave( + n ∈ N |- app(recFun, n) === stepFunc(n)(recFun ↾ n) + ) by InstantiateForall(n) + + val stepEq = have( + stepFunc(n)(recFun ↾ n) === stageSet(recFun ↾ n) + ) by Restate + + val stageSetSpecFact = have(stageSetSpec) by Hypothesis + val stageSpecAtRec = have( + ∀(x, x ∈ stageSet(recFun ↾ n) <=> inExtIntroImage(recFun ↾ n)(x)) + ) by InstantiateForall(recFun ↾ n)(stageSetSpecFact) + + val stageMemEq = have( + x ∈ stageSet(recFun ↾ n) <=> inExtIntroImage(recFun ↾ n)(x) + ) by InstantiateForall(x)(stageSpecAtRec) + + have( + n ∈ N |- x ∈ app(recFun, n) <=> inExtIntroImage(recFun ↾ n)(x) + ) by Congruence.from(recEq0, stepEq, stageMemEq) + val stageChar = thenHave( + n ∈ N |- + ∀(x, x ∈ app(recFun, n) <=> inExtIntroImage(recFun ↾ n)(x)) + ) by RightForall + + have( + n ∈ N ==> ∀(x, x ∈ app(recFun, n) <=> inExtIntroImage(recFun ↾ n)(x)) + ) by RightImplies(stageChar) + val stageAll = thenHave( + ∀(n ∈ N, ∀(x, x ∈ app(recFun, n) <=> inExtIntroImage(recFun ↾ n)(x))) + ) by RightForall + + val isFunOn = have(functionOn(recFun)(N)) by Weakening(recSpec) + val isFun = have(function(recFun)) by Cut(isFunOn, functionOnIsFunction of (f := recFun, A := N)) + val isDomN = have(dom(recFun) === N) by Cut(isFunOn, functionOnDomain of (f := recFun, A := N)) + + have(isHeightCore(recFun)) by RightAnd( + isFun, + isDomN, + stageAll + ) + + thenHave(thesis) by Restate + } + + private lazy val heightExists = Lemma(stageSetSpec |- exists(h, isHeightCore(h))) { + have(stageSetSpec |- isHeightCore(heightFunction)) by Restate.from(heightFunctionSpec) + thenHave(thesis) by RightExists + } + + val isConstructorMonotonic = Lemma( + (isConstructorMono, s ⊆ t) |- isConstructor(x)(s) ==> isConstructor(x)(t) + ) { + have(isConstructorMono |- isConstructorMono) by Hypothesis + thenHave(isConstructorMono |- ∀(t, ∀(x, s ⊆ t ==> (isConstructor(x)(s) ==> isConstructor(x)(t))))) by + InstantiateForall(s) + thenHave(isConstructorMono |- ∀(x, s ⊆ t ==> (isConstructor(x)(s) ==> isConstructor(x)(t)))) by + InstantiateForall(t) + thenHave(isConstructorMono |- s ⊆ t ==> (isConstructor(x)(s) ==> isConstructor(x)(t))) by + InstantiateForall(x) + thenHave(thesis) by Restate + } + + private val extIntroMonotonic = Lemma( + (introFunctionMono, f ⊆ g) |- + inExtIntroImage(f)(x) ==> + inExtIntroImage(g)(x) + ) { + val introUnionF = inIntroImage(⋃(range(f)))(x) + val introUnionG = inIntroImage(⋃(range(g)))(x) + assume(introFunctionMono, f ⊆ g) + + val introMono = have(introFunctionMono) by Hypothesis + have((⋃(range(f)) ⊆ ⋃(range(g))) ==> ∀(x, introUnionF ==> introUnionG)) by InstantiateForall(⋃(range(f)), ⋃(range(g)))(introMono) + thenHave((⋃(range(f)) ⊆ ⋃(range(g))) |- ∀(x, introUnionF ==> introUnionG)) by Restate + have(f ⊆ g |- ∀(x, introUnionF ==> introUnionG)) by + Cut(unionRangeMonotonic, lastStep) + thenHave(introUnionF ==> introUnionG) by + InstantiateForall(x) + val left = thenHave((introFunctionMono, f ⊆ g, introUnionF) |- introUnionG) by Restate + + have( + (f =/= ∅, introUnionF) |- inExtIntroImage(g)(x) + ) by RightAnd(left, supersetNotEmpty of (x := f, y := g)) + } + + val heightApplication = Lemma( + (isHeightCore(h), n ∈ N) |- (x ∈ app(h, n)) <=> inExtIntroImage(h ↾ n)(x) + ) { + val extIntroResM = inExtIntroImage(h ↾ n)(x) + val heightFunApplicationDef = ∀(n ∈ N, ∀(x, (x ∈ app(h, n)) <=> extIntroResM)) + + val hyp = assume(isHeightCore(h), n ∈ N) + + have(heightFunApplicationDef) by Weakening(hyp) + thenHave( + n ∈ N ==> ∀(x, (x ∈ app(h, n)) <=> extIntroResM) + ) by InstantiateForall(n) + thenHave( + ∀(x, (x ∈ app(h, n)) <=> extIntroResM) + ) by Restate + thenHave( + (x ∈ app(h, n)) <=> extIntroResM + ) by InstantiateForall(x) + thenHave(thesis) by Restate + } + + private[proofs] val heightMonotonic = Lemma( + (introFunctionMono, isHeightCore(h), n ∈ N, m ∈ N, m ⊆ n) |- + app(h, m) ⊆ app(h, n) + ) { + assume(introFunctionMono, isHeightCore(h), n ∈ N, m ∈ N, m ⊆ n) + val extIntroResM = inExtIntroImage(h ↾ m)(x) + val extIntroResN = inExtIntroImage(h ↾ n)(x) + + have(extIntroResM ==> extIntroResN) by Cut( + setMonotonic of (x := m, y := n, f := h), + extIntroMonotonic of (f := h ↾ m, g := h ↾ n) + ) + have((x ∈ app(h, m)) ==> (x ∈ app(h, n))) by + Substitute(heightApplication of (n := m), heightApplication)(lastStep) + thenHave(∀(x, (x ∈ app(h, m)) ==> (x ∈ app(h, n)))) by RightForall + + have(thesis) by Congruence.from( + lastStep, + subsetAxiom of (x := app(h, m), y := app(h, n)) + ) + } + + def heightExistsAt( + stageSet0: Expr[Ind >>: Ind], + isConstructor0: Expr[Ind >>: Ind >>: Prop] + )(using proof: lisa.SetTheoryLibrary.Proof): Thm = + heightExists.of(stageSet := stageSet0, isConstructor := isConstructor0) + + /** + * Returns the explicit height function for a stage operation. + */ + def heightFunctionAt(stageSet0: Expr[Ind >>: Ind]): Expr[Ind] = + heightFunction.substitute(stageSet := stageSet0) + + /** + * Instantiates the specification of the constructed height function. + */ + def heightFunctionSpecAt( + stageSet0: Expr[Ind >>: Ind], + isConstructor0: Expr[Ind >>: Ind >>: Prop] + )(using proof: lisa.SetTheoryLibrary.Proof): Thm = + heightFunctionSpec.of(stageSet := stageSet0, isConstructor := isConstructor0) + + def heightMonotonicAt( + isConstructor0: Expr[Ind >>: Ind >>: Prop], + h0: Expr[Ind], + n0: Expr[Ind], + m0: Expr[Ind] + )(using proof: lisa.SetTheoryLibrary.Proof): Thm = + heightMonotonic.of(isConstructor := isConstructor0, h := h0, n := n0, m := m0) + + def initialize(): Unit = { + val _ = heightFunctionSpec + val _ = isConstructorMonotonic + val _ = extIntroMonotonic + val _ = heightApplication + val _ = heightMonotonic + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/ProofsInitialization.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/ProofsInitialization.scala new file mode 100644 index 000000000..4e3355ca9 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/ProofsInitialization.scala @@ -0,0 +1,10 @@ +package lisa.maths.SetTheory.Types.ADT.height.proofs + +object ProofsInitialization { + + def initialize(): Unit = { + CoreFacts.initialize() + SuccessorFacts.initialize() + UniquenessFacts.initialize() + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/SuccessorFacts.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/SuccessorFacts.scala new file mode 100644 index 000000000..80a9da5a0 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/SuccessorFacts.scala @@ -0,0 +1,146 @@ +package lisa.maths.SetTheory.Types.ADT.height.proofs + +import lisa.maths.SetTheory.Functions.Operations.Restriction.emptyRestriction +import lisa.maths.SetTheory.Functions.Operations.Restriction.notEmpty +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Ordinals.Integer.emptyInOmega +import lisa.maths.SetTheory.Ordinals.Integer.omegaSuccessorInduction +import lisa.maths.SetTheory.Ordinals.Integer.selfInSuccessor +import lisa.maths.SetTheory.Ordinals.Integer.subsetSuccessor +import lisa.maths.SetTheory.Ordinals.Integer.successorInOmega +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.height.proofs.CoreFacts._ +import lisa.maths.SetTheory.Types.ADT.height.proofs.UnionRangeCollapse.unionRangeCollapse +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.tactics.Cuts +import lisa.utils.prooflib.Thm + +private[height] object SuccessorFacts { + + protected inline final def app(f: Expr[Ind], x: Expr[Ind]): Expr[Ind] = + lisa.maths.SetTheory.Functions.Predef.app(f)(x) + + val heightZero = Lemma(isHeightCore(h) |- !(x ∈ app(h, ∅))) { + have( + isHeightCore(h) |- + x ∈ app(h, ∅) <=> + inExtIntroImage(h ↾ ∅)(x) + ) by Tautology.from(emptyInOmega, CoreFacts.heightApplication.of(n := ∅)) + thenHave( + (h ↾ ∅ === ∅, isHeightCore(h)) |- !(x ∈ app(h, ∅)) + ) by RightSubst( + List((h ↾ ∅, ∅)), + (Seq(s), x ∈ app(h, ∅) <=> inExtIntroImage(s)(x)) + ) + have(thesis) by Cut(emptyRestriction of (f := h), lastStep) + } + + val heightSuccessorWeak = Lemma( + (introFunctionMono, isHeightCore(h), n ∈ N) |- + x ∈ app(h, S(n)) <=> inIntroImage(app(h, n))(x) + ) { + val heightResNonEmpty: Expr[Prop] = !(h ↾ S(n) === ∅) + + assume(introFunctionMono, isHeightCore(h), n ∈ N) + + val nInNFact = have(n ∈ N) by Hypothesis + val domEq = have(dom(h) === N) by Restate + val nInDomH = have(n ∈ dom(h)) by Congruence.from(nInNFact, domEq) + + val hIsFunc = have(function(h)) by Restate + + have(heightResNonEmpty) by + Cuts(notEmpty of (f := h, x := n, d := S(n)))(hIsFunc, nInDomH, selfInSuccessor) + val heightResNonEmptyLemma = have(heightResNonEmpty <=> ⊤) by + Restate.from(lastStep) + + have(m ∈ N ==> (m ⊆ n ==> app(h, m) ⊆ app(h, n))) by + Restate.from(CoreFacts.heightMonotonic) + val monotonicityForall = thenHave( + ∀(m ∈ N, (m ⊆ n ==> app(h, m) ⊆ app(h, n))) + ) by RightForall + val unionRangeRes = have( + ⋃(range(h ↾ S(n))) === app(h, n) + ) by Cuts(unionRangeCollapse)( + hIsFunc, + domEq, + monotonicityForall + ) + + val succIsNatStep = have(S(n) ∈ N) by Weakening(successorInOmega) + + have( + S(n) ∈ N |- x ∈ app(h, S(n)) <=> inExtIntroImage(h ↾ S(n))(x) + ) by Weakening(CoreFacts.heightApplication.of(n := S(n))) + have( + x ∈ app(h, S(n)) <=> inExtIntroImage(h ↾ S(n))(x) + ) by Cut(succIsNatStep, lastStep) + + have( + x ∈ app(h, S(n)) <=> (⊤ /\ inIntroImage(app(h, n))(x)) + ) by Congruence.from(lastStep, unionRangeRes, heightResNonEmptyLemma) + + have(thesis) by Restate.from(lastStep) + } + + val heightSuccessorStrong = Lemma( + (isConstructorMono, introFunctionMono, isHeightCore(h), n ∈ N) |- + x ∈ app(h, S(n)) <=> isConstructor(x)(app(h, n)) + ) { + assume(isConstructorMono, introFunctionMono, isHeightCore(h)) + + def introImageIsConstructor(k: Expr[Ind]): Expr[Prop] = + inIntroImage(app(h, k))(x) ==> isConstructor(x)(app(h, k)) + + val base = have(introImageIsConstructor(∅)) by Tautology.from(heightZero) + have(n ∈ N ==> (introImageIsConstructor(n) ==> introImageIsConstructor(S(n)))) subproof { + assume(n ∈ N) + val inclusion = have(app(h, n) ⊆ app(h, S(n))) by Tautology.from( + CoreFacts.heightMonotonic.of(m := n, n := S(n)), + subsetSuccessor, + successorInOmega + ) + val constructorMonotonicity = have(isConstructor(x)(app(h, n)) ==> isConstructor(x)(app(h, S(n)))) by + Tautology.from(inclusion, CoreFacts.isConstructorMonotonic.of(s := app(h, n), t := app(h, S(n)))) + have(thesis) by Tautology.from(constructorMonotonicity, heightSuccessorWeak) + } + val step = thenHave(∀(n ∈ N, introImageIsConstructor(n) ==> introImageIsConstructor(S(n)))) by RightForall + have(∀(n ∈ N, introImageIsConstructor(n))) by Tautology.from( + base, + step, + omegaSuccessorInduction of (P := λ(n, introImageIsConstructor(n))) + ) + thenHave(n ∈ N ==> introImageIsConstructor(n)) by InstantiateForall(n) + have(thesis) by Tautology.from(lastStep, heightSuccessorWeak) + } + + def heightZeroAt( + isConstructor0: Expr[Ind >>: Ind >>: Prop], + h0: Expr[Ind], + x0: Expr[Ind] + )(using proof: lisa.SetTheoryLibrary.Proof): Thm = + heightZero.of(isConstructor := isConstructor0, h := h0, x := x0) + + def heightSuccessorWeakAt( + isConstructor0: Expr[Ind >>: Ind >>: Prop], + h0: Expr[Ind], + n0: Expr[Ind], + x0: Expr[Ind] + )(using proof: lisa.SetTheoryLibrary.Proof): Thm = + heightSuccessorWeak.of(isConstructor := isConstructor0, h := h0, n := n0, x := x0) + + def heightSuccessorStrongAt( + isConstructor0: Expr[Ind >>: Ind >>: Prop], + h0: Expr[Ind], + n0: Expr[Ind], + x0: Expr[Ind] + )(using proof: lisa.SetTheoryLibrary.Proof): Thm = + heightSuccessorStrong.of(isConstructor := isConstructor0, h := h0, n := n0, x := x0) + + def initialize(): Unit = { + val _ = heightZero + val _ = heightSuccessorWeak + val _ = heightSuccessorStrong + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/UnionRangeCollapse.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/UnionRangeCollapse.scala new file mode 100644 index 000000000..d22b892b0 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/UnionRangeCollapse.scala @@ -0,0 +1,99 @@ +package lisa.maths.SetTheory.Types.ADT.height.proofs + +import lisa.maths.SetTheory.Base.Intersection.∩ +import lisa.maths.SetTheory.Base._ +import lisa.maths.SetTheory.Functions.Operations.Restriction +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Functions.UnionRange.unionRangeMembership +import lisa.maths.SetTheory.Ordinals.Integer.elementsTransitive +import lisa.maths.SetTheory.Ordinals.Integer.selfInSuccessor +import lisa.maths.SetTheory.Ordinals.Integer.succMembership +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.Ordinals.TransitiveSet +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ + +/** + * Collapses the union of a monotone height sequence through its last stage. + */ +object UnionRangeCollapse { + + private val natSubset = Lemma((n ∈ N, m ∈ S(n)) |- m ⊆ n) { + val memberCase = have((n ∈ N, m ∈ n) |- m ⊆ n) by + Tautology.from(elementsTransitive, TransitiveSet.elementIsSubset of (x := m, A := n)) + val equalCase = have(m === n |- m ⊆ n) by Congruence.from(Subset.reflexivity of (x := n)) + have(thesis) by Tautology.from(memberCase, equalCase, succMembership of (k := m)) + } + + /** + * A monotone sequence on ω contains every earlier value in its last value. + */ + val unionRangeCollapse = Lemma( + ( + function(h), + dom(h) === N, + n ∈ N, + forall(m, m ∈ N ==> (m ⊆ n ==> app(h)(m) ⊆ app(h)(n))) + ) |- ⋃(range(h ↾ S(n))) === app(h)(n) + ) { + val hFunction = assume(function(h)) + assume(dom(h) === N) + assume(n ∈ N) + val cumulative = assume(∀(m, m ∈ N ==> (m ⊆ n ==> app(h)(m) ⊆ app(h)(n)))) + val restricted = h ↾ S(n) + val witness = m ∈ dom(restricted) /\ z ∈ app(restricted)(m) + + val restrictedFunction = have(function(restricted)) by + Tautology.from(hFunction, Restriction.isFunction of (f := h, A := S(n))) + val unionMembership = have(z ∈ ⋃(range(restricted)) <=> ∃(m, witness)) by + Tautology.from(restrictedFunction, unionRangeMembership of (h := restricted, n := m)) + val restrictedDomain = have(dom(restricted) === N ∩ S(n)) by + Congruence.from(Restriction.domain of (f := h, A := S(n))) + val domainMembership = have(m ∈ dom(restricted) <=> (m ∈ N /\ m ∈ S(n))) by + Congruence.from(restrictedDomain, Intersection.membership of (z := m, x := N, y := S(n))) + + val witnessToValue = have(witness |- z ∈ app(h)(n)) subproof { + assume(witness) + val mInNat = have(m ∈ N) by Tautology.from(domainMembership) + val mInSuccessor = have(m ∈ S(n)) by Tautology.from(domainMembership) + val mInDomain = have(m ∈ dom(h)) by Congruence.from(mInNat) + val restrictedValue = have(app(restricted)(m) === app(h)(m)) by Tautology.from( + Restriction.restrictedApp of (f := h, x := m, A := S(n)), + hFunction, + mInDomain, + mInSuccessor + ) + val zInRestrictedValue = have(z ∈ app(restricted)(m)) by Tautology + val zInValue = have(z ∈ app(h)(m)) by Congruence.from(restrictedValue, zInRestrictedValue) + val cumulativeAtM = have(m ∈ N ==> (m ⊆ n ==> app(h)(m) ⊆ app(h)(n))) by InstantiateForall(m)(cumulative) + have(app(h)(m) ⊆ app(h)(n)) by Tautology.from(cumulativeAtM, natSubset, mInNat, mInSuccessor) + have(thesis) by Tautology.from( + lastStep, + zInValue, + Subset.membership of (x := app(h)(m), y := app(h)(n), z := z) + ) + } + val fromExists = have(∃(m, witness) |- z ∈ app(h)(n)) by LeftExists(witnessToValue) + val forward = have(z ∈ ⋃(range(restricted)) |- z ∈ app(h)(n)) by Tautology.from(unionMembership, fromExists) + + val backward = have(z ∈ app(h)(n) |- z ∈ ⋃(range(restricted))) subproof { + assume(z ∈ app(h)(n)) + val nInDomain = have(n ∈ dom(h)) by Congruence + val nInRestrictedDomain = have(n ∈ dom(restricted)) by + Tautology.from(domainMembership of (m := n), selfInSuccessor) + val restrictedValue = have(app(restricted)(n) === app(h)(n)) by Tautology.from( + Restriction.restrictedApp of (f := h, x := n, A := S(n)), + hFunction, + nInDomain, + selfInSuccessor + ) + have(z ∈ app(restricted)(n)) by Congruence.from(restrictedValue) + thenHave(n ∈ dom(restricted) /\ z ∈ app(restricted)(n)) by Tautology.fromLastStep(nInRestrictedDomain) + thenHave(∃(m, witness)) by RightExists + have(thesis) by Tautology.from(lastStep, unionMembership) + } + + have(z ∈ ⋃(range(restricted)) <=> z ∈ app(h)(n)) by Tautology.from(forward, backward) + thenHave(thesis) by Extensionality + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/UniquenessFacts.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/UniquenessFacts.scala new file mode 100644 index 000000000..c0cd1a463 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/height/proofs/UniquenessFacts.scala @@ -0,0 +1,106 @@ +package lisa.maths.SetTheory.Types.ADT.height.proofs + +import lisa.maths.SetTheory.Base.Extensionality +import lisa.maths.SetTheory.Functions.BasicTheorems.extensionality +import lisa.maths.SetTheory.Functions.BasicTheorems.functionOnIffFunctionWithDomain +import lisa.maths.SetTheory.Functions.Function.dom +import lisa.maths.SetTheory.Functions.Function.function +import lisa.maths.SetTheory.Functions.Function.functionOn +import lisa.maths.SetTheory.Ordinals.Integer.omegaSuccessorInduction +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.tactics.Cuts +import lisa.utils.prooflib.Thm + +private[height] object UniquenessFacts { + + protected inline final def app(f: Expr[Ind], x: Expr[Ind]): Expr[Ind] = + lisa.maths.SetTheory.Functions.Predef.app(f)(x) + + private def stageEq(k: Expr[Ind]): Expr[Prop] = app(f, k) === app(g, k) + private val stageEqN = stageEq(n) + private val stageEqSuccN = stageEq(S(n)) + + private val zeroCase = Lemma( + (CoreFacts.introFunctionMono, CoreFacts.isHeightCore(f), CoreFacts.isHeightCore(g)) |- stageEq(∅) + ) { + assume(CoreFacts.introFunctionMono, CoreFacts.isHeightCore(f), CoreFacts.isHeightCore(g)) + // x ∉ app(f, ∅) and x ∉ app(g, ∅), so both memberships are equivalent (both false). + val contraF = have(x ∈ app(f, ∅) |- ()) by LeftNot(SuccessorFacts.heightZero.of(h := f)) + have(x ∈ app(f, ∅) |- x ∈ app(g, ∅)) by Weakening(contraF) + val fwd = thenHave(x ∈ app(f, ∅) ==> x ∈ app(g, ∅)) by RightImplies + val contraG = have(x ∈ app(g, ∅) |- ()) by LeftNot(SuccessorFacts.heightZero.of(h := g)) + have(x ∈ app(g, ∅) |- x ∈ app(f, ∅)) by Weakening(contraG) + val bwd = thenHave(x ∈ app(g, ∅) ==> x ∈ app(f, ∅)) by RightImplies + have((x ∈ app(f, ∅)) <=> (x ∈ app(g, ∅))) by RightIff(fwd, bwd) + thenHave(thesis) by Extensionality + } + + private val succCase = Lemma( + (CoreFacts.introFunctionMono, CoreFacts.isHeightCore(f), CoreFacts.isHeightCore(g), n ∈ N, stageEqN) |- stageEqSuccN + ) { + assume(CoreFacts.introFunctionMono, CoreFacts.isHeightCore(f), CoreFacts.isHeightCore(g), n ∈ N, stageEqN) + + // heightSuccessorWeak rewrites each membership at S(n) to the intro-image at n; the assumed + // stageEqN (app(f, n) === app(g, n)) makes those intro-images equal by congruence closure. + have(x ∈ app(f, S(n)) <=> x ∈ app(g, S(n))) by Congruence.from( + SuccessorFacts.heightSuccessorWeak.of(h := f), + SuccessorFacts.heightSuccessorWeak.of(h := g) + ) + thenHave(thesis) by Extensionality + } + + val uniqueness = Lemma( + (CoreFacts.introFunctionMono, CoreFacts.isHeightCore(f), CoreFacts.isHeightCore(g)) |- f === g + ) { + + assume(CoreFacts.introFunctionMono, CoreFacts.isHeightCore(f), CoreFacts.isHeightCore(g)) + + // Inductive step, packaged as a bounded ∀. + have(n ∈ N ==> (stageEqN ==> stageEqSuccN)) by Restate.from(succCase) + val stepForall = thenHave(∀(n, n ∈ N ==> (stageEqN ==> stageEqSuccN))) by RightForall + + // ω-induction: from stageEq(∅) (zeroCase) and the step, get ∀ n ∈ N, app(f, n) === app(g, n). + val inductionInstance = have( + (stageEq(∅), ∀(n, n ∈ N ==> (stageEqN ==> stageEqSuccN))) |- ∀(n, n ∈ N ==> stageEqN) + ) by Weakening(omegaSuccessorInduction of (P := λ(n, stageEqN))) + val allStageEq = have(∀(n, n ∈ N ==> stageEqN)) by Cuts(inductionInstance)( + zeroCase, + stepForall + ) + + // f and g are functions on N (isHeightCore gives function(·) ∧ dom(·) === N). + val fProps = have(function(f) /\ (dom(f) === N)) by Restate + have((function(f) /\ (dom(f) === N)) |- functionOn(f)(N)) by Weakening( + functionOnIffFunctionWithDomain of (f := f, A := N) + ) + val fOnN = have(functionOn(f)(N)) by Cut(fProps, lastStep) + + val gProps = have(function(g) /\ (dom(g) === N)) by Restate + have((function(g) /\ (dom(g) === N)) |- functionOn(g)(N)) by Weakening( + functionOnIffFunctionWithDomain of (f := g, A := N) + ) + val gOnN = have(functionOn(g)(N)) by Cut(gProps, lastStep) + + // Functional extensionality on N. + have(thesis) by Cuts(extensionality of (f := f, g := g, A := N))( + allStageEq, + fOnN, + gOnN + ) + } + + def uniquenessAt( + isConstructor0: Expr[Ind >>: Ind >>: Prop], + f0: Expr[Ind], + g0: Expr[Ind] + )(using proof: lisa.SetTheoryLibrary.Proof): Thm = + uniqueness.of(CoreFacts.isConstructor := isConstructor0, f := f0, g := g0) + + def initialize(): Unit = { + val _ = zeroCase + val _ = succCase + val _ = uniqueness + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/induction/Induction.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/induction/Induction.scala new file mode 100644 index 000000000..adf6978a5 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/induction/Induction.scala @@ -0,0 +1,411 @@ +package lisa.maths.SetTheory.Types.ADT.tactics + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.PatternMatching.syntax.CaseAccumulator +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ +import lisa.maths.SetTheory.Types.TypingHelpers.:: +import lisa.maths.SetTheory.Types.TypingHelpers.TypeAssign +import lisa.utils.prooflib.BasicStep.RightForall +import lisa.utils.prooflib.BasicStep.RightImplies +import lisa.utils.prooflib.InstantiateForallSeq +import lisa.utils.prooflib.ProofJudgement +import lisa.utils.prooflib.Subproof +import lisa.utils.prooflib.Thm + +/** + * Tactic performing a structural induction proof over an algebraic data type. + * + * ===Usage=== + * {{{ + * have(forall(x, x :: adt => P(x)) /*or*/ x :: adt |- P(x)) by Induction(x, adt) { + * Case(c1, x1, ..., xn) subproof { + * // proof of P(xi) /\ ... P(xj) => P(c1(x1, ..., xn)) + * } + * ... + * Case(cm, x1, ..., xk) subproof { + * // proof of P(xi) /\ ... P(xj) => P(c1(x1, ..., xn')) + * } + * } + * }}} + * + * x and adt are inferred from the context if not provided by the user. + * + * Supports only 1 formula on the right hand side of the sequent. + * @param expectedVar the variable on which the induction is performed + * @param expectedADT the algebraic data type on which the induction is performed + */ +class Induction( + expectedVar: Option[Variable[Ind]], + expectedADT: Option[SpecializedADT[?]] +) { + + private def typeSubstitutionMap(adt: SpecializedADT[?]): Map[String, Expr[Ind]] = + adt.base.typeVariablesSeq.map(_.id.toString).zip(adt.typeArgs).toMap + + private def instantiateForallSeq(formula: Expr[Prop], args: Seq[Expr[Ind]]): Expr[Prop] = + args.foldLeft(formula) { (current, arg) => + current match + case forall(v, phi) => phi.substitute(v := arg).asInstanceOf[Expr[Prop]] + case _ => current + } + + private def caseHypotheses( + constructor: Constructor[?], + adt: SpecializedADT[?], + binders: Seq[Variable[Ind]], + prop: Expr[Ind >>: Prop] + ): Seq[(Variable[Ind], Seq[Expr[Prop]])] = + val specializedTypeArgs = typeSubstitutionMap(adt) + constructor.semantic.syntacticSignature(binders).map { + case (v, SelfRef) => v -> Seq(v :: adt.term, prop(v)) + case (v, TypeArg(typeName)) => + val t = specializedTypeArgs.getOrElse(typeName, typeExprToTerm(typeName)) + v -> Seq(v :: t) + } + + // forall interleaved per binder + private def abstractConstructorCase(using + proof: lisa.SetTheoryLibrary.Proof + )( + rawCaseProof: Thm, + binders: Seq[Variable[Ind]], + constructor: Constructor[?], + adt: SpecializedADT[?], + prop: Expr[Ind >>: Prop] + ): Thm = + caseHypotheses(constructor, adt, binders, prop).foldRight[Thm](rawCaseProof) { case ((v, hyps), acc) => + val withImpls = hyps.foldRight[Thm](acc) { (h, a) => + val accRight = a.statement.right.head + have((a.statement - accRight) by Weakening(a) + } + have(withImpls.statement.left |- forall(v, withImpls.statement.right.head)) by RightForall(withImpls) + } + + // all foralls out front + private def normalizeConstructorCase(using + proof: lisa.SetTheoryLibrary.Proof + )( + rawCaseProof: Thm, + binders: Seq[Variable[Ind]], + assumptions: Seq[Expr[Prop]], + context: Set[Expr[Prop]] + ): Thm = + val lifted = have(context |- seqAnd(assumptions) ==> rawCaseProof.statement.right.head) by Tautology.from(rawCaseProof) + binders.reverse.foldLeft[Thm](lifted) { (acc2, binder) => + have(acc2.statement.left |- forall(binder, acc2.statement.right.head)) by RightForall(acc2) + } + + /** + * Proves the inductive case for a single constructor, in the shape expected by the + * ADT induction principle: `forall(args, typing /\ inductionHypotheses ==> P(c(args)))`. + * + * Each branch carries a payload proving the property for its pattern (possibly under a + * guard, when several branches share the constructor, e.g. `cons(tru, tl)` vs + * `cons(fals, tl)`). The branch payloads are normalized, instantiated at the + * constructor's variables and fresh inner witnesses. Branch selection discharges the + * existential guards by case analysis. The combined generic-case proof is abstracted into + * the quantified, hypothesis-laden form the induction principle consumes. + * + * @tparam N the arity of the ADT + * @param proof the scope in which the case is proven + * @param constructor the constructor whose case is being established + * @param branches the compiled branches for `constructor`, each with its payload proof + * @param patternSystem the compiled pattern system, used for guard selection + * @param adt the (specialized) ADT being inducted over + * @param prop the property as a lambda (`λt. P(t)`) + * @param context the ambient hypotheses carried through every case + */ + private def buildBranchProof(using + proof: lisa.SetTheoryLibrary.Proof + )( + constructor: Constructor[?], + branches: Seq[Clause[Thm]], + patternSystem: PatternSystem[?], + adt: SpecializedADT[?], + prop: Expr[Ind >>: Prop], + context: Set[Expr[Prop]] + ): Thm = + val forbidden = context.toSeq ++ Seq(prop, adt.term) ++ branches.flatMap(_.binders) + val vars = constructor.semantic.variables2.foldLeft(Vector.empty[Variable[Ind]]) { (fresh, variable) => + fresh :+ Variable[Ind](freshId(forbidden ++ fresh, variable.id.name)) + } + val inputTerm = constructor.semantic + .appliedTerm(vars) + .substitute(adt.base.typeVariablesSeq.zip(adt.typeArgs).map((v, a) => v := a)*) + .asInstanceOf[Expr[Ind]] + val hyps = caseHypotheses(constructor, adt, vars, prop) + val typingAssumptions = hyps.map(_._2.head) + val recursiveAssumptions = hyps.collect { case (_, Seq(_, ih)) => ih } + val genericGoal = prop(inputTerm) + + val localContext = context ++ typingAssumptions ++ recursiveAssumptions + val guardedImplications = branches.map { branch => + val (topBinders, innerBinders) = branch.binders.splitAt(constructor.semantic.arity) + val innerTyping = branch.typingSignatureAt(branch.binders).drop(constructor.semantic.arity).map((v, typ) => v :: typ) + val assumptions = caseHypotheses(constructor, adt, topBinders, prop).flatMap(_._2) ++ innerTyping :+ branch.branchCondition + val abstracted = normalizeConstructorCase(branch.payload, branch.binders, assumptions, context) + val innerVars = innerBinders.foldLeft(Vector.empty[Variable[Ind]]) { (acc, binder) => + acc :+ Variable[Ind](freshId(localContext.toSeq ++ Seq(genericGoal) ++ vars ++ acc, binder.id.name)) + } + val arguments = vars ++ innerVars + val instantiated = have(context |- instantiateForallSeq(abstracted.statement.right.head, arguments)) by + InstantiateForallSeq(arguments)(abstracted) + val substitutions = branch.binders.zip(arguments).map((from, to) => from := to) + val guard = seqAnd(innerTyping :+ branch.branchCondition).substitute(substitutions*) + val guarded = have((localContext + guard) |- genericGoal) by Tautology.from(instantiated) + + // Inner pattern variables are witnesses supplied by branch selection. + val (selection, selectedProof) = innerVars.foldRight((guard, guarded: Thm)) { case (v, (condition, fact)) => + val existential = ∃(v, condition) + val lifted = have((localContext + existential) |- genericGoal) by LeftExists(fact) + (existential, lifted) + } + have(localContext |- selection ==> genericGoal) by RightImplies.withParameters(selection, genericGoal)(selectedProof) + } + val selectorSchema = patternSystem.branchSelectionFor(constructor.semantic, inputTerm) + val selectorAtConstructor = have(instantiateForallSeq(selectorSchema.statement.right.head, vars)) by + InstantiateForallSeq(vars)(selectorSchema) + val branchGuardDisjunction = selectorAtConstructor.statement.right.head match + case _ ==> consequent => have(localContext |- consequent) by Tautology.from(selectorAtConstructor) + case _ => throw UnreachableException + val genericCaseProof = have(localContext |- genericGoal) by Tautology.from((branchGuardDisjunction +: guardedImplications)*) + + abstractConstructorCase(genericCaseProof, vars, constructor, adt, prop) + + /** + * Given a proof of the claim for each case (possibly using the induction hypothesis), + * reassemble the subproofs to generate a proof of the claim for every element of the + * ADT. + * + * @tparam N the arity of the ADT + * @param proof the scope in which the induction is performed + * @param cases the cases to prove. A [[CaseAccumulator]] is a mutable data structure + * that register every case that has been added to the tactic. + * @param bot the claim + */ + def apply(using + proof: lisa.SetTheoryLibrary.Proof + )( + cases: CaseAccumulator[ + Thm, + (Sequent, SpecializedADT[?], Variable[Ind]) + ] ?=> Unit + )(bot: Sequent): ProofJudgement = { + if bot.right.size != 1 then return invalidTactic("Induction requires exactly one formula on the right of its goal.") + + Induction.inferArguments(bot, expectedVar, expectedADT) match + case Some((inferedVar, inferedADT, inferedProp)) => + + val body: Expr[Prop] = inferedProp.getOrElse(bot.right.head) + val propertyVar = Variable[Ind](freshId(bot.left.toSeq ++ bot.right.toSeq :+ inferedADT.term, "t")) + val prop: Expr[Ind >>: Prop] = λ(propertyVar, body.substitute(inferedVar -> propertyVar)) + + val assignment = inferedVar :: inferedADT.term + + val missingTypingAssumption = + inferedProp.isEmpty && + !bot.left.contains(assignment) && + bot.freeVars.contains(inferedVar) + + if missingTypingAssumption then + invalidTactic( + s"Induction on variable '$inferedVar' over ADT '${inferedADT.name}' requires the typing assumption '$assignment' in the goal context. " + + s"Current goal is '$bot'. Add '( $assignment ) |- ...', or restate the goal as a universally quantified statement " + + s"'|- forall($inferedVar, $assignment ==> P($inferedVar))'." + ) + else + val context = (if inferedProp.isDefined then bot else bot -<< assignment).left + val builder = + CaseAccumulator[Thm, (Sequent, SpecializedADT[?], Variable[Ind])]( + (context |- body, inferedADT, inferedVar) + ) + cases(using builder) + + val compiledBranchSystem = builder.compile(inferedADT) + + compiledBranchSystem match + case Right(branchSystem) => buildInductionProof(bot, inferedVar, inferedProp, body, prop, context, branchSystem) + case Left(msg) => invalidTactic(msg) + + case None => + invalidTactic("No variable typed with the ADT found in the context.") + } + + /** + * Assembles the whole induction proof from an already-compiled branch system. + * + * Instantiates the ADT induction principle at `prop`, discharges every constructor case + * with [[buildBranchProof]], chains the results to obtain `forall(inferedVar, + * inferedVar :: adt ==> body)`, then derives the original goal `bot` — instantiating the + * universal quantifier when the goal was stated in typed-context form rather than + * quantified form. + * + * @tparam N the arity of the ADT + * @param proof the scope in which the induction is performed + * @param bot the claim to conclude + * @param inferedVar the induction variable + * @param inferedProp the property body when the goal is universally quantified, `None` + * for the typed-context form `x :: adt |- P(x)` (drives the final instantiation step) + * @param body the property to establish (`P(inferedVar)`) + * @param prop the property as a lambda (`λt. body[inferedVar := t]`) + * @param context the ambient hypotheses (the goal minus the typing assumption) + * @param branchSystem the compiled per-constructor branches with their payload proofs + */ + private def buildInductionProof(using + proof: lisa.SetTheoryLibrary.Proof + )( + bot: Sequent, + inferedVar: Variable[Ind], + inferedProp: Option[Expr[Prop]], + body: Expr[Prop], + prop: Expr[Ind >>: Prop], + context: Set[Expr[Prop]], + branchSystem: PatternSystem[Thm] + ): ProofJudgement = Subproof { sp ?=> + + val specializedADT = branchSystem.domain + val typeVariablesSubstPairs = + specializedADT.base.typeVariablesSeq.zip(specializedADT.typeArgs).map(SubstPair(_, _)) + val instantiatedInduction = have( + specializedADT.base.semantic.induction.statement.substitute((typeVariablesSubstPairs :+ (P := prop))*) + ) by Restate.from( + specializedADT.base.semantic.induction.of((typeVariablesSubstPairs :+ (P := prop))*) + ) + + specializedADT.base.constructors.foldLeft[Thm](instantiatedInduction)((acc, constructor) => + val branchPairs = branchSystem + .clausesFor(constructor.semantic) + .map( + _.map(payload => have(payload.statement) by Restate.from(payload): Thm) + ) + val inductiveCaseProof = buildBranchProof(using sp)( + constructor, + branchPairs, + branchSystem, + specializedADT, + prop, + context + ) + acc.statement.right.head match + case implies(_, rest) => + have((acc.statement.left ++ inductiveCaseProof.statement.left) |- rest) by + Tautology.from(acc, inductiveCaseProof) + case _ => throw UnreachableException + ) + thenHave( + context |- ∀(inferedVar :: specializedADT.term, body) + ) by Restate + if !inferedProp.isDefined then + lastStep.statement.right.head match + case forall(_, phi) => thenHave(context |- phi) by InstantiateForall(inferedVar) + case _ => throw UnreachableException + thenHave(bot) by Restate + } +} + +object Induction { + + /** + * Reconciles the variable/ADT recovered from the goal with the ones the user + * may have supplied explicitly. Returns [[None]] on a mismatch. + */ + private def checkFoundArguments( + expectedVar: Option[Variable[Ind]], + expectedADT: Option[SpecializedADT[?]], + foundVar: Variable[Ind], + foundADT: SpecializedADT[?] + ): Option[(Variable[Ind], SpecializedADT[?])] = (expectedVar, expectedADT) match + case (Some(v), _) if v != foundVar => None + case (_, Some(a)) if a.base != foundADT.base || a.typeArgs != foundADT.typeArgs => None + case _ => Some((foundVar, foundADT)) + + /** + * Infers the variable, the ADT and the arguments of the ADT from a formula of the form + * `x :: ADT(T1, ..., Tn)`. + * + * @param f the formula to infer these elements from + */ + private def inferArgumentsExpr( + f: Expr[Prop], + expectedVar: Option[Variable[Ind]], + expectedADT: Option[SpecializedADT[?]] + ): Option[(Variable[Ind], SpecializedADT[?])] = + f match + case TypeAssign(Variable[Ind](id), typeTerm) => + inferADTFromTypeTerm(typeTerm) + .flatMap(foundADT => checkFoundArguments(expectedVar, expectedADT, Variable[Ind](id), foundADT)) + case _ => None + + /** + * Reads a typing term such as `ADT(T1, ..., Tn)` back into the ADT it names and the + * terms it is applied to. The head symbol is matched by identity and the arguments are + * kept as they stand, so nothing is reconstructed from a name. + */ + private def inferADTFromTypeTerm(typeTerm: Expr[Ind]): Option[SpecializedADT[?]] = + val (head, args) = unfoldAllApp(typeTerm) + head match + case c: Constant[?] @unchecked => + ADT.getADT(c.id).map(_.specialize(args.map(_.asInstanceOf[Expr[Ind]])*)) + case _ => None + + /** + * Infers the variable, the ADT and the (optional) property body of an induction goal. + * Returns `None` unless the goal has exactly one conclusion. + * + * It looks, in order, for: + * 1. a typing premise `x :: ADT(...)` on the left of the sequent, + * 2. a universally quantified goal `|- forall(x, x :: ADT(...) ==> P(x))`, + * 3. the variable/ADT supplied explicitly to the tactic (the fallback used by + * calls such as `Induction(x, nat)` when no typing is present in the goal). + * + * @param seq the sequent to infer these elements from + * @param expectedVar the variable supplied explicitly to the tactic, if any + * @param expectedADT the ADT supplied explicitly to the tactic, if any + */ + def inferArguments( + seq: Sequent, + expectedVar: Option[Variable[Ind]], + expectedADT: Option[SpecializedADT[?]] + ): Option[(Variable[Ind], SpecializedADT[?], Option[Expr[Prop]])] = + if seq.right.size != 1 then None + else + seq.left + .foldLeft[Option[(Variable[Ind], SpecializedADT[?])]](None)((acc, prem) => acc.orElse(inferArgumentsExpr(prem, expectedVar, expectedADT))) + .map(p => (p._1, p._2, None)) + .orElse( + seq.right.head match + case forall(x, implies(assignment, prop)) => + inferArgumentsExpr(assignment, expectedVar, expectedADT) + .filter(p => p._1 == x) + .map(p => (p._1, p._2, Some(prop))) + case _ => None + ) + .orElse( + (expectedVar, expectedADT) match + case (Some(v), Some(a)) => Some((v, a, None)) + case _ => None + ) + + def apply() = new Induction(None, None) + + def apply(adt: ADT[?]) = + new Induction(None, Some(adt.specialize(adt.typeVariablesSeq*))) + + def apply(adt: SpecializedADT[?]) = + new Induction(None, Some(adt)) + + def apply(v: Variable[Ind]) = + new Induction(Some(v), None) + + def apply(v: Variable[Ind], adt: ADT[?]) = + new Induction(Some(v), Some(adt.specialize(adt.typeVariablesSeq*))) + + def apply(v: Variable[Ind], adt: SpecializedADT[?]) = + new Induction(Some(v), Some(adt)) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/ADT.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/ADT.scala new file mode 100644 index 000000000..84c096b8f --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/ADT.scala @@ -0,0 +1,114 @@ +package lisa.maths.SetTheory.Types.ADT.interface + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.encoding.SemanticADT +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.generalTheorem +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.renderAppliedSymbol +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.typeExprToTerm +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ +import lisa.utils.prooflib.Thm + +class ADT[S](using val line: sourcecode.Line, val file: sourcecode.File, sort: (S) is Sort)( + val semantic: SemanticADT +) extends Constant[S](semantic.id) { + + printAs(args => renderAppliedSymbol(semantic.name, semantic.typeVariablesSeq.size, args)) + + val name: String = semantic.name + val typeVariablesSeq: Seq[Variable[Ind]] = semantic.typeVariablesSeq + + /** + * Applies exactly the declared type arguments and returns a set. + */ + def termAt(args: Seq[Expr[Ind]]): Expr[Ind] = + require(args.size == typeVariablesSeq.size, s"ADT $name expects ${typeVariablesSeq.size} type argument(s), got ${args.size}.") + (this #@@ args).asInstanceOf[Expr[Ind]] + + val term: Expr[Ind] = termAt(typeVariablesSeq) + + ADT.register(this) + + lazy val constructors: Seq[Constructor[S]] = + semantic.constructors.iterator.map[Constructor[S]](c => new Constructor[S](c, this)).toVector + + /** + * The structural induction principle, closed over this ADT's type variables. + * Instantiate at type arguments with `of`, e.g. `list.induction of nat`. + */ + lazy val induction: Theorem = + generalTheorem(name, typeVariablesSeq, "induction", semantic.induction) + + /** + * Every inhabitant is a constructor applied to typed arguments. Instantiate with `of`. + */ + lazy val elim: Theorem = + generalTheorem(name, typeVariablesSeq, "elimination", semantic.elim) + + private val disjointnessThms = scala.collection.mutable.Map.empty[(Constructor[S], Constructor[S]), Theorem] + + /** + * Instances of two distinct constructors are never equal. Instantiate with `of`. + */ + def disjointness(c1: Constructor[S], c2: Constructor[S]): Theorem = + require( + (c1.adt eq this) && (c2.adt eq this) && constructors.contains(c1) && constructors.contains(c2) && c1 != c2, + s"$name has no disjointness between ${c1.name} and ${c2.name}; they must be two distinct constructors of $name." + ) + disjointnessThms.getOrElseUpdate( + (c1, c2), + generalTheorem( + name, + typeVariablesSeq, + s"${c1.semantic.name}-${c2.semantic.name}/disjointness", + semantic.disjointness(c1.semantic, c2.semantic) + ) + ) + + def applySeq(args: Seq[Expr[Ind]]): Expr[Ind] = termAt(args) + + def apply(args: Expr[Ind]*): Expr[Ind] = termAt(args) + + def specialize(args: Expr[Ind]*): SpecializedADT[S] = + new SpecializedADT[S](this, args) +} + +object ADT { + private val namesToADT: scala.collection.mutable.Map[String, ADT[?]] = + scala.collection.mutable.Map.empty + + private val idsToADT: scala.collection.mutable.Map[Identifier, ADT[?]] = + scala.collection.mutable.Map.empty + + private val constructorOwners: scala.collection.mutable.Map[Identifier, (ADT[?], Int)] = + scala.collection.mutable.Map.empty + + private def register(adt: ADT[?]): Unit = { + namesToADT.update(adt.name, adt) + idsToADT.update(adt.id, adt) + adt.semantic.constructors.zipWithIndex.foreach { (constructor, index) => + constructorOwners.update(constructor.id, (adt, index)) + } + } + + def unapply(obj: Expr[Ind]): Option[(ADT[?], Seq[Expr[Ind]])] = + obj match + case c: Constant[?] @unchecked => + getADT(c.id).map((_, Seq.empty)) + case Multiapp(head, args) => + head match + case c: Constant[?] @unchecked => getADT(c.id).map((_, args.asInstanceOf[Seq[Expr[Ind]]])) + case _ => None + + def getADT(name: String): Option[ADT[?]] = namesToADT.get(name) + + def getADT(id: Identifier): Option[ADT[?]] = idsToADT.get(id) + + /** + * Looks up a constructor by identifier, initializing only its owner's constructor wrappers. + */ + // Here private[ADT] would refer to this object rather than the enclosing package. + private[Types] def getConstructor(id: Identifier): Option[Constructor[?]] = + constructorOwners.get(id).map((adt, index) => adt.constructors(index)) + + def allADTs: Iterable[ADT[?]] = namesToADT.values +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/ADTFunction.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/ADTFunction.scala new file mode 100644 index 000000000..3ee41ee23 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/ADTFunction.scala @@ -0,0 +1,157 @@ +package lisa.maths.SetTheory.Types.ADT.interface + +import lisa.maths.SetTheory.Functions.Function.app +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.syntax.Case +import lisa.maths.SetTheory.Types.ADT.recursion.SemanticFunction +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.generalTheorem +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.introAppTheorem +import lisa.maths.SetTheory.Types.ADT.support.TypedADTConstant +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.renderAppliedSymbol +import lisa.maths.SetTheory.Types.TypingHelpers.:: +import lisa.maths.SetTheory.Types.TypingHelpers.FunctionalClass +import lisa.utils.prooflib.Thm + +/** + * A typed function with its typing theorem and pattern equations. + */ +final class ADTFunction[S](using + val line: sourcecode.Line, + val file: sourcecode.File, + sort: (S) is Sort +)( + val semantic: SemanticFunction, + val adt: ADT[?] +) extends TypedADTConstant[S]( + semantic.id, + FunctionalClass( + List.fill(semantic.typeVariablesSeq.size)(None), + semantic.typeVariablesSeq.toList, + semantic.typ + ), + ADTFunction.typingJustification(semantic) + ) { + + private val introAppVariable: Variable[Ind] = + Variable[Ind](freshId(semantic.typeVariablesSeq :+ semantic.typ, "functionArg")) + + printAs(args => renderAppliedSymbol(semantic.name, semantic.typeVariablesSeq.size, args)) + + val name: String = semantic.name + val typeVariablesSeq: Seq[Variable[Ind]] = semantic.typeVariablesSeq + val term: Expr[Ind] = termAt(typeVariablesSeq) + + lazy val argType: Expr[Ind] = semantic.argType + lazy val returnType: Expr[Ind] = semantic.returnType + lazy val functionType: Expr[Ind] = semantic.typ + private lazy val patterns: Seq[Clause[Expr[Ind]]] = semantic.clauses + + private lazy val patternIndices: Map[Clause[Expr[Ind]], Int] = + patterns.zipWithIndex.toMap + + private def eliminationSuffix(pattern: Clause[Expr[Ind]]): String = { + val index = patternIndices.getOrElse( + pattern, + throw new IllegalArgumentException(s"Pattern ${pattern.name} does not belong to function $name.") + ) + s"elimination/${pattern.name}/$index" + } + + /** + * The applied form of [[intro]]. A derived statement rather than an instance, so it is + * proved once over the type variables; instantiate with `of (A := nat)`. + */ + lazy val introApp: Theorem = introAppTheorem( + displayName = name, + baseTheorem = semantic.intro, + headTerm = termAt(typeVariablesSeq), + headType = semantic.typ, + assumptions = Set(introAppVariable :: semantic.argType), + typingArgs = Seq(introAppVariable -> semantic.argType), + conclusion = app(termAt(typeVariablesSeq))(introAppVariable) :: semantic.returnType + ) + + /** + * The defining equation of every branch at once. Instantiate with `of`. + */ + lazy val elimTotal: Theorem = + generalTheorem(name, typeVariablesSeq, "eliminationTotal", semantic.elimTotal) + + private val elimByPatternThms = scala.collection.mutable.Map.empty[Clause[Expr[Ind]], Theorem] + private val elimByConstThms = scala.collection.mutable.Map.empty[Constructor[?], Theorem] + private lazy val patternsByConstructor = patterns.groupBy(_.semanticConstructor) + + /** + * The defining equation of one branch. Instantiate with `of`. + */ + def elimByPattern(pattern: Clause[Expr[Ind]]): Theorem = + elimByPatternThms.getOrElseUpdate( + pattern, + generalTheorem(name, typeVariablesSeq, eliminationSuffix(pattern), semantic.elimByPattern(pattern)) + ) + + /** + * The defining equations of every branch covering one constructor. Instantiate with `of`. + */ + def elimByConst(constructor: Constructor[?]): Theorem = + elimByConstThms.getOrElseUpdate( + constructor, { + require( + (constructor.adt eq adt) && adt.constructors.contains(constructor), + s"${constructor.name} is not a constructor of function $name's domain." + ) + patternsByConstructor(constructor.semantic) match + case Seq(pattern) => elimByPattern(pattern) + case _ => generalTheorem(name, typeVariablesSeq, s"elimination/${constructor.semantic.name}", semantic.elimByConst(constructor.semantic)) + } + ) + + def elim: Theorem = elimTotal + + def elim(pattern: Clause[Expr[Ind]]): Theorem = elimByPattern(pattern) + + def elim(constructor: Constructor[?]): Theorem = elimByConst(constructor) + + def elim(c: Case): Theorem = elimByPattern(patternFor(c)) + + /** + * Order- and binder-name-independent lookup of the branch matching `c`. + * + * The case is matched against the registered patterns by constructor identity + * plus its concrete (guard) arguments, so it does not depend on the order in + * which the branches were declared. + */ + def patternFor(c: Case): Clause[Expr[Ind]] = + patterns + .collectFirst { case p if p.matchesConstructorCase(c.cons.semantic, c.args) => p } + .getOrElse( + throw new IllegalArgumentException( + s"No branch of $name matches case ${c.cons.name}(${c.args.mkString(", ")})." + ) + ) + + /** + * Applies exactly the declared type arguments and returns the set-theoretic function. + */ + def termAt(args: Seq[Expr[Ind]]): Expr[Ind] = + require(args.size == typeVariablesSeq.size, s"Function $name expects ${typeVariablesSeq.size} type argument(s), got ${args.size}.") + (this #@@ args).asInstanceOf[Expr[Ind]] + + def applySeq(args: Seq[Expr[Ind]]): Expr[Ind] = termAt(args) + + def apply(args: Expr[Ind]*): Expr[Ind] = termAt(args) +} + +object ADTFunction { + private def typingJustification(using + line: sourcecode.Line, + file: sourcecode.File + )(semantic: SemanticFunction): Theorem = + generalTheorem(semantic.name, semantic.typeVariablesSeq, "introduction", semantic.intro) +} + +/** + * The same function interface, retained for existing recursive-function annotations. + */ +type RecFunction[S] = ADTFunction[S] diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/Constructor.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/Constructor.scala new file mode 100644 index 000000000..51dca52d4 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/Constructor.scala @@ -0,0 +1,75 @@ +package lisa.maths.SetTheory.Types.ADT.interface + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.encoding.SemanticConstructor +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.generalTheorem +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.introAppTheorem +import lisa.maths.SetTheory.Types.ADT.support.TypedADTConstant +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.renderAppliedSymbol +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.wellTypedSet +import lisa.maths.SetTheory.Types.TypingHelpers.:: +import lisa.maths.SetTheory.Types.TypingHelpers.FunctionalClass + +final class Constructor[S](using val line: sourcecode.Line, val file: sourcecode.File, sort: (S) is Sort)( + val semantic: SemanticConstructor, + val adt: ADT[S] +) extends TypedADTConstant[S]( + semantic.id, + FunctionalClass( + List.fill(semantic.typeVariablesSeq.size)(None), + semantic.typeVariablesSeq.toList, + semantic.typ + ), + Constructor.typingJustification(semantic) + ) { + + printAs(args => renderAppliedSymbol(semantic.fullName, semantic.typeVariablesSeq.size, args)) + + val name: String = semantic.fullName + val typeVariablesSeq: Seq[Variable[Ind]] = semantic.typeVariablesSeq + val term: Expr[Ind] = termAt(typeVariablesSeq) + + /** + * The curried form of [[intro]]. A genuinely derived statement, so it is proved once + * over the type variables rather than closed over them; instantiate with + * `of (A := nat)`. + */ + lazy val introApp: Theorem = introAppTheorem( + displayName = name, + baseTheorem = semantic.intro, + headTerm = termAt(typeVariablesSeq), + headType = semantic.typ, + assumptions = wellTypedSet(semantic.semanticSignature), + typingArgs = semantic.semanticSignature, + conclusion = semantic.appliedTerm :: adt.term + ) + + /** + * Two instances of this constructor are equal exactly when their arguments are. + * Instantiate with `of`. + */ + lazy val injectivity: Theorem = + generalTheorem(name, typeVariablesSeq, "injectivity", semantic.injectivity) + + /** + * Applies exactly the declared type arguments and returns the set-theoretic constructor. + */ + def termAt(args: Seq[Expr[Ind]]): Expr[Ind] = + require(args.size == typeVariablesSeq.size, s"Constructor $name expects ${typeVariablesSeq.size} type argument(s), got ${args.size}.") + (this #@@ args).asInstanceOf[Expr[Ind]] + + def applySeq(args: Seq[Expr[Ind]]): Expr[Ind] = termAt(args) + + def apply(args: Expr[Ind]*): Expr[Ind] = termAt(args) + + def specialize(args: Expr[Ind]*): SpecializedConstructor[S] = + new SpecializedConstructor[S](this, args) +} + +object Constructor { + private def typingJustification(using + line: sourcecode.Line, + file: sourcecode.File + )(semantic: SemanticConstructor): Theorem = + generalTheorem(semantic.fullName, semantic.typeVariablesSeq, "introduction", semantic.intro) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/SpecializedDomain.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/SpecializedDomain.scala new file mode 100644 index 000000000..e7786354c --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/interface/SpecializedDomain.scala @@ -0,0 +1,62 @@ +package lisa.maths.SetTheory.Types.ADT.interface + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.appSeq +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.renderAppliedSymbol + +object SpecializedADT { + given adtToSpecialized[S](using sourcecode.Line, sourcecode.File): Conversion[ADT[S], SpecializedADT[S]] = + adt => new SpecializedADT[S](adt, adt.typeVariablesSeq) +} + +/** + * User-facing instantiated view of a constructor. + * + * This is intentionally only an interface wrapper for now. The semantic specialized + * domain layer can be introduced later if the recursive/proof internals need it. + */ +final class SpecializedConstructor[S](using + val line: sourcecode.Line, + val file: sourcecode.File +)( + val base: Constructor[S], + val typeArgs: Seq[Expr[Ind]] +) { + + val name: String = base.name + val fullName: String = base.semantic.fullName + val typeVariables: Seq[Variable[Ind]] = base.typeVariablesSeq + val term: Expr[Ind] = base.termAt(typeArgs) + + def applySeq(args: Seq[Expr[Ind]]): Expr[Ind] = appSeq(term)(args) + + def apply(args: Expr[Ind]*): Expr[Ind] = applySeq(args) + + override def toString: String = + renderAppliedSymbol(base.semantic.fullName, base.typeVariablesSeq.size, typeArgs) +} + +/** + * User-facing instantiated view of an ADT. + * + * This wrapper mirrors the non-specialized `ADT` API and gives a place to attach a + * future specialized semantic domain if needed. + */ +final class SpecializedADT[S](using + val line: sourcecode.Line, + val file: sourcecode.File +)( + val base: ADT[S], + val typeArgs: Seq[Expr[Ind]] +) { + + val name: String = base.name + val typeVariables: Seq[Variable[Ind]] = base.typeVariablesSeq + val term: Expr[Ind] = base.termAt(typeArgs) + + lazy val constructors: Seq[SpecializedConstructor[S]] = + base.constructors.map(c => new SpecializedConstructor[S](c, typeArgs)) + + override def toString: String = + renderAppliedSymbol(base.name, base.typeVariablesSeq.size, typeArgs) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Bool.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Bool.scala new file mode 100644 index 000000000..2dd59ca5d --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Bool.scala @@ -0,0 +1,23 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.Types.ADT._ + +val bool = adt( + name = "bool", + constructors = Seq( + ("tru", Seq.empty), + ("fals", Seq.empty) + ) +) +val tru = bool.constructors(0) +val fals = bool.constructors(1) + +lazy val not = recFun(bool, bool) { _ => + Case(tru): + fals + Case(fals): + tru +} + +object Bool: + export lisa.maths.SetTheory.Types.ADT.library.{bool, tru, fals, not} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Box.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Box.scala new file mode 100644 index 000000000..8ddc8b08a --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Box.scala @@ -0,0 +1,15 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.Types.ADT._ + +val box = adt( + name = "box", + typeVars = "A", + constructors = Seq( + ("pack", Seq(("x", "A"))) + ) +) +val pack = box.constructors(0) + +object Box: + export lisa.maths.SetTheory.Types.ADT.library.{box, pack} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/List.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/List.scala new file mode 100644 index 000000000..53a658cde --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/List.scala @@ -0,0 +1,26 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.syntax.AST.SelfRef + +val listLengthHead = variable[Ind] +val listLengthTail = variable[Ind] + +lazy val list = adt( + name = "list", + typeVars = "A", + constructors = Seq(("nil", Seq.empty), ("cons", Seq(("head", "A"), ("tail", SelfRef)))) +) +lazy val nil = list.constructors(0) +lazy val cons = list.constructors(1) + +lazy val length = recFun(list, nat) { self => + Case(nil): + zero + Case(cons, listLengthHead, listLengthTail): + succ * (self * listLengthTail) +} + +object List: + export lisa.maths.SetTheory.Types.ADT.library.{list, nil, cons, length, listLengthHead, listLengthTail} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Nat.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Nat.scala new file mode 100644 index 000000000..574bff61d --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Nat.scala @@ -0,0 +1,51 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.Functions.Pi.->: +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.syntax.AST.SelfRef +import lisa.maths.SetTheory.Types.TypingHelpers + +val natPredN = variable[Ind] +val natDoubleN = variable[Ind] +val natAddN = variable[Ind] +val natAddRight = variable[Ind] + +val nat = adt( + name = "nat", + constructors = Seq( + ("zero", Seq.empty), + ("succ", Seq(("k", SelfRef))) + ) +) +val zero = nat.constructors(0) +val succ = nat.constructors(1) + +lazy val pred = recFun(nat, nat) { _ => + Case(zero): + zero + Case(succ, natPredN): + natPredN +} + +lazy val double = recFun(nat, nat) { self => + Case(zero): + zero + Case(succ, natDoubleN): + succ * (succ * (self * natDoubleN)) +} + +private val natEndo = nat.term ->: nat.term + +lazy val add = recFun(nat, natEndo) { self => + Case(zero): + TypingHelpers.fun(natAddRight :: nat.term, natAddRight) + Case(succ, natAddN): + TypingHelpers.fun( + natAddRight :: nat.term, + succ * ((self * natAddN) * natAddRight) + ) +} + +object Nat: + export lisa.maths.SetTheory.Types.ADT.library.{nat, zero, succ, pred, double, add, natPredN, natDoubleN, natAddN, natAddRight} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Option.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Option.scala new file mode 100644 index 000000000..ec4d92081 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Option.scala @@ -0,0 +1,17 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.Types.ADT._ + +val option = adt( + name = "option", + typeVars = "T", + constructors = Seq( + ("some", Seq(("x", "T"))), + ("none", Seq.empty) + ) +) +val some = option.constructors(0) +val none = option.constructors(1) + +object Option: + export lisa.maths.SetTheory.Types.ADT.library.{option, some, none} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Product.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Product.scala new file mode 100644 index 000000000..22690d2d7 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Product.scala @@ -0,0 +1,15 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.Types.ADT._ + +val product = adt( + name = "product", + typeVars = ("A", "B"), + constructors = Seq( + ("pair", Seq(("x", "A"), ("y", "B"))) + ) +) +val pair = product.constructors(0) + +object Product: + export lisa.maths.SetTheory.Types.ADT.library.{product, pair} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Tree.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Tree.scala new file mode 100644 index 000000000..448e132d2 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Tree.scala @@ -0,0 +1,51 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.syntax.AST.SelfRef + +val treeLeafValue = variable[Ind] +val treeNodeLeft = variable[Ind] +val treeNodeRight = variable[Ind] + +lazy val tree = adt( + name = "tree", + typeVars = "A", + constructors = Seq( + ("leaf", Seq.empty), + ("node", Seq(("value", "A"), ("left", SelfRef), ("right", SelfRef))) + ) +) +lazy val leaf = tree.constructors(0) +lazy val node = tree.constructors(1) + +lazy val size = recFun(tree, nat) { self => + Case(leaf): + zero + Case(node, treeLeafValue, treeNodeLeft, treeNodeRight): + succ * (add * (self * treeNodeLeft) * (self * treeNodeRight)) +} + +lazy val leafCount = recFun(tree, nat) { self => + Case(leaf): + succ * zero + Case(node, treeLeafValue, treeNodeLeft, treeNodeRight): + add * (self * treeNodeLeft) * (self * treeNodeRight) +} + +lazy val mirror = recFun(tree, tree.term) { self => + Case(leaf): + leaf.term + Case(node, treeLeafValue, treeNodeLeft, treeNodeRight): + node.term * treeLeafValue * (self * treeNodeRight) * (self * treeNodeLeft) +} + +lazy val isEmpty = fun(tree, bool) { + Case(leaf): + tru + Case(node, treeLeafValue, treeNodeLeft, treeNodeRight): + fals +} + +object Tree: + export lisa.maths.SetTheory.Types.ADT.library.{tree, leaf, node, size, leafCount, mirror, isEmpty, treeLeafValue, treeNodeLeft, treeNodeRight} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Union.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Union.scala new file mode 100644 index 000000000..e9248b60a --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Union.scala @@ -0,0 +1,29 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT._ + +val unionLeft = variable[Ind] +val unionRight = variable[Ind] + +val union = adt( + name = "union", + typeVars = ("A", "B"), + constructors = Seq( + ("inl", Seq(("x", "A"))), + ("inr", Seq(("y", "B"))) + ) +) +val inl = union.constructors(0) +val inr = union.constructors(1) + +// lazy val isLeft = recFun(union, bool) { _ => +lazy val isLeft = fun(union, bool) { + Case(inl, unionLeft): + tru + Case(inr, unionRight): + fals +} + +object Union: + export lisa.maths.SetTheory.Types.ADT.library.{union, inl, inr, isLeft, unionLeft, unionRight} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Unit.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Unit.scala new file mode 100644 index 000000000..eabcd8403 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Unit.scala @@ -0,0 +1,14 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.Types.ADT._ + +val unit = adt( + name = "unit", + constructors = Seq( + ("star", Seq.empty) + ) +) +val star = unit.constructors(0) + +object Unit: + export lisa.maths.SetTheory.Types.ADT.library.{unit, star} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Void.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Void.scala new file mode 100644 index 000000000..c7b470469 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/library/Void.scala @@ -0,0 +1,11 @@ +package lisa.maths.SetTheory.Types.ADT.library + +import lisa.maths.SetTheory.Types.ADT._ + +val void = adt( + name = "void", + constructors = Seq.empty +) + +object Void: + export lisa.maths.SetTheory.Types.ADT.library.{void} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/ApproxSequence.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/ApproxSequence.scala new file mode 100644 index 000000000..e6d1ae943 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/ApproxSequence.scala @@ -0,0 +1,67 @@ +package lisa.maths.SetTheory.Types.ADT.recursion + +import lisa.maths.Quantifiers +import lisa.maths.SetTheory.Functions.Predef.app +import lisa.maths.SetTheory.Ordinals.Iteration +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.maths.SetTheory.Types.TypingRules.functionSpaceInhabited + +/** + * Iterates the witness operator from a typed seed to construct the approximant sequence. + */ +private[recursion] final class ApproxSequence(val spec: FunSpec, val recWitness: Witness) { + private val f0 = spec.proofVariable("f0") + private val nVar = spec.proofVariable("nVar") + private val valueVar = spec.proofVariable("iterationValue") + private val F = variable[Ind >>: Ind] + private val P = variable[Ind >>: Prop] + private val z = variable[Ind] + + private val seedExists = Lemma.generated(∃(f0, f0 :: spec.typ)) { + have(thesis) by Tautology.from(recWitness.targetInhabited, functionSpaceInhabited.of(A := spec.argType, B := spec.returnType)) + } + private val g0 = ε(f0, f0 :: spec.typ) + private val initial = recWitness(g0) + private val step = λ(valueVar, recWitness(valueVar)) + private val sequence = Iteration.sequence(step)(initial) + + /** + * The approximant at the supplied natural-number index. + */ + def G(n: Expr[Ind]): Expr[Ind] = app(sequence)(n) + + /** + * Each successor approximant is obtained by applying the witness operator. + */ + val approxSucc: Theorem = Lemma.generated(∀(nVar ∈ N, G(S(nVar)) === recWitness(G(nVar)))) { + have(nVar ∈ N |- G(S(nVar)) === recWitness(G(nVar))) by Restate.from( + Iteration.successor.of(F := step, z := initial, n := nVar) + ) + thenHave(nVar ∈ N ==> (G(S(nVar)) === recWitness(G(nVar)))) by RightImplies + thenHave(thesis) by RightForall + } + + /** + * Every approximant has the function's declared type. + */ + val approxHasType: Theorem = Lemma.generated(∀(nVar ∈ N, G(nVar) :: spec.typ)) { + val g0Typed = have(g0 :: spec.typ) by + Cut(seedExists, Quantifiers.existsEpsilon.of(x := f0, P := λ(f0, f0 :: spec.typ))) + val initialTyped = have(initial :: spec.typ) by Tautology.from( + g0Typed, + recWitness.witnessHasType.of(spec.selfPlaceholder := g0) + ) + have((valueVar :: spec.typ) ==> (recWitness(valueVar) :: spec.typ)) by Restate.from( + recWitness.witnessHasType.of(spec.selfPlaceholder := valueVar) + ) + val preserved = thenHave(∀(valueVar, (valueVar :: spec.typ) ==> (recWitness(valueVar) :: spec.typ))) by RightForall + have(thesis) by Tautology.from( + initialTyped, + preserved, + Iteration.invariant.of(F := step, z := initial, P := λ(valueVar, valueVar :: spec.typ)) + ) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/ApproxStabilization.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/ApproxStabilization.scala new file mode 100644 index 000000000..572eee1f6 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/ApproxStabilization.scala @@ -0,0 +1,141 @@ +package lisa.maths.SetTheory.Types.ADT.recursion + +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Ordinals.Integer.omegaSuccessorInduction +import lisa.maths.SetTheory.Ordinals.Integer.successorInOmega +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.prooflib.BasicStep.Cut +import lisa.utils.prooflib.BasicStep.RightForall +import lisa.utils.prooflib.Thm + +/** + * Approximant stabilization. + * + * Proves stabilization of the approximant sequence: + * + * stabilization : ∀n ∈ ω, ∀a ∈ h(n), G(n)(a) = G(Succ(n))(a) + * + * Exports: + * - [[stabilization]] + */ +private[recursion] final class ApproxStabilization( + val spec: FunSpec, + val recWitness: Witness, + val approxSeq: ApproxSequence, + val witnessAgreement: helpers.WitnessAgreement +) { + + private val nVar = spec.proofVariable("nVar") + private val a = spec.proofVariable("a") + import approxSeq.G + + /** + * Instantiates a `∀(x ∈ N, φ(x))` theorem at `m` and discharges the `m ∈ N` premise, + * yielding `φ(m)`. `consequent` is the expected `φ(m)`. + */ + private def instantiateAt(using + proof: lisa.SetTheoryLibrary.Proof + )( + forallThm: Theorem, + m: Expr[Ind], + mInN: Thm, + consequent: Expr[Prop] + ): Thm = { + val impl = have((m ∈ N) ==> consequent) by InstantiateForall(m)(forallThm) + have(consequent) by Tautology.from(mInN, impl) + } + + // ───────────────────────────────────────────────────────────────────────── + // Lemma D — stabilization + // ∀n ∈ ω, ∀a ∈ h(n), G(n)(a) = G(Succ(n))(a) + // ───────────────────────────────────────────────────────────────────────── + + val stabilization: Theorem = ( + Lemma.generated( + ∀(nVar ∈ N, ∀(a ∈ app(spec.heightFun)(nVar), app(G(nVar))(a) === app(G(S(nVar)))(a))) + ) { + val prop = λ(nVar, ∀(a ∈ app(spec.heightFun)(nVar), app(G(nVar))(a) === app(G(S(nVar)))(a))) + + val hValid = have(spec.isHeightPred(spec.heightFun)) by Weakening(spec.heightFunValid) + + val noElemAtEmpty = have(!(a ∈ app(spec.heightFun)(∅))) by Cut( + hValid, + spec.heightZero(a) + ) + + have(a ∈ app(spec.heightFun)(∅) |- app(G(∅))(a) === app(G(S(∅)))(a)) by + Tautology.from(noElemAtEmpty) + thenHave( + (a ∈ app(spec.heightFun)(∅)) ==> (app(G(∅))(a) === app(G(S(∅)))(a)) + ) by RightImplies + thenHave( + ∀(a, (a ∈ app(spec.heightFun)(∅)) ==> (app(G(∅))(a) === app(G(S(∅)))(a))) + ) by RightForall + val base = thenHave(prop(∅)) by Restate + + val goalAtA = app(G(S(nVar)))(a) === app(G(S(S(nVar))))(a) + val pointwiseAtSucc = have( + ((nVar ∈ N), prop(nVar), (a ∈ app(spec.heightFun)(S(nVar)))) |- goalAtA + ) subproof { + val nInN = assume(nVar ∈ N) + val ih = assume(prop(nVar)) + val aInHeightSucc = assume(a ∈ app(spec.heightFun)(S(nVar))) + + val succInN = have(S(nVar) ∈ N) by + Tautology.from(nInN, successorInOmega.of(n := nVar)) + + // approxSucc glue: G(Succ n) = W(G n), G(Succ Succ n) = W(G(Succ n)). + val gSuccAtAIsWitness = have(app(G(S(nVar)))(a) === app(recWitness(G(nVar)))(a)) by + Congruence.from(instantiateAt(approxSeq.approxSucc, nVar, nInN, G(S(nVar)) === recWitness(G(nVar)))) + + val witnessSuccAtARev = have( + app(recWitness(G(S(nVar))))(a) === app(G(S(S(nVar))))(a) + ) by Congruence.from( + instantiateAt( + approxSeq.approxSucc, + S(nVar), + succInN, + G(S(S(nVar))) === recWitness(G(S(nVar))) + ) + ) + + // The induction hypothesis `ih = prop(n)` is exactly the slice-agreement premise of + // WitnessAgreement.witnessAgreementAtSucc at leftFun := G(n), rightFun := G(Succ n). + // Chain: G(Sn)(a) === W(Gn)(a) === W(G(Sn))(a) === G(SSn)(a), with the + // middle link supplied by the witness agreement and the rest as bridges. + have(thesis) by Restate.from( + witnessAgreement.witnessesAgreeAt( + lhs = G(nVar), + rhs = G(S(nVar)), + index = nVar, + lhsTyped = instantiateAt(approxSeq.approxHasType, nVar, nInN, G(nVar) :: spec.typ), + rhsTyped = instantiateAt(approxSeq.approxHasType, S(nVar), succInN, G(S(nVar)) :: spec.typ), + indexInN = nInN, + sliceAgreement = ih, + pointInHeightSucc = aInHeightSucc, + goal = goalAtA, + bridges = Seq(gSuccAtAIsWitness, witnessSuccAtARev) + ) + ) + } + + have(((nVar ∈ N), prop(nVar)) |- (a ∈ app(spec.heightFun)(S(nVar))) ==> goalAtA) by + Restate.from(pointwiseAtSucc) + have( + ((nVar ∈ N), prop(nVar)) |- + ∀(a ∈ app(spec.heightFun)(S(nVar)), goalAtA) + ) by RightForall(lastStep) + have((nVar ∈ N) ==> (prop(nVar) ==> prop(S(nVar)))) by Restate.from(lastStep) + val step = have(∀(nVar ∈ N, prop(nVar) ==> prop(S(nVar)))) by RightForall(lastStep) + + val P = variable[Ind >>: Prop] + have(∀(nVar, (nVar ∈ N) ==> prop(nVar))) by + Tautology.from(omegaSuccessorInduction of (P := prop), base, step) + thenHave(thesis) by Restate + } + ) + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Existence.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Existence.scala new file mode 100644 index 000000000..a41bf3f9f --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Existence.scala @@ -0,0 +1,248 @@ +package lisa.maths.SetTheory.Types.ADT.recursion + +import lisa.maths.SetTheory.Functions.BasicTheorems.funcBetweenEqInFuncSpace +import lisa.maths.SetTheory.Functions.BasicTheorems.functionalExtentionality +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Ordinals.Integer.subsetSuccessor +import lisa.maths.SetTheory.Ordinals.Integer.successorInOmega +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.recursion.proofs.ApproximationChainFacts +import lisa.maths.SetTheory.Types.ADT.recursion.proofs.LimitKernel +import lisa.maths.SetTheory.Types.ADT.support.core.Utils +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.tactics.Cuts +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.fol.FOL.SubstPair +import lisa.utils.prooflib.Thm + +/** + * Layer 3 — Existence without circularity. + * + * Delegates approximant construction to [[ApproxSequence]] and stabilization lemmas + * to [[ApproxStabilization]], then proves: + * + * limitIsFixedPoint : W(limitFun) = limitFun + * fixedPointExists : ∃f :: A→T, W(f) = f + * defAtFixedPoint : (f :: A→T) ∧ W(f) = f ⊢ Def(f) + * witnessExists : ∃f, Def(f) + * + * Exported: + * - [[witnessExists]] — ∃f, Def(f) + */ +private[recursion] final class Existence( + val spec: FunSpec, + val recWitness: Witness, + val approxSeq: ApproxSequence, + val approxStab: ApproxStabilization, + val limitConstruction: LimitConstruction, + val witnessAgreement: helpers.WitnessAgreement +) { + + private val a = spec.proofVariable("a") + private val f = spec.proofVariable("f") + private def heightMembershipMonotonic(using proof: lisa.SetTheoryLibrary.Proof)(substitutions: Seq[SubstPair]): Thm = + spec.adt.height.membershipMonotonicAt(spec.typeSubstitutions, substitutions) + + import approxSeq.G + import spec.{heightFun, heightFunValid} + import approxStab.stabilization + import limitConstruction.{limitFun, limitHasType, limitIndex} + + private val pointParam = spec.proofVariable("pointParam") + private val indexParam = spec.proofVariable("indexParam") + private val approximantFamily = λ(indexParam, G(indexParam)) + private val chosenIndexFamily = λ(pointParam, limitIndex(pointParam)) + + // ───────────────────────────────────────────────────────────────────────── + // Lemma F — limitIsFixedPoint: W(limitFun) = limitFun + // ───────────────────────────────────────────────────────────────────────── + + private val limitIsFixedPoint: Theorem = (Lemma.generated(recWitness(limitFun) === limitFun) { + + val funTyping = have((f :: spec.typ) |- functionBetween(f)(spec.argType)(spec.returnType)) by Weakening( + funcBetweenEqInFuncSpace of (Utils.f := f, A := spec.argType, B := spec.returnType) + ) + val limitBetween = have(functionBetween(limitFun)(spec.argType)(spec.returnType)) by Cut( + limitHasType, + funTyping of (f := limitFun) + ) + val witnessAtLimitBetween = have(functionBetween(recWitness(limitFun))(spec.argType)(spec.returnType)) by Cuts( + funTyping of (f := recWitness(limitFun)) + )( + have((limitFun :: spec.typ) |- (recWitness(limitFun) :: spec.typ)) by Restate.from( + recWitness.witnessHasType.of(spec.selfPlaceholder := limitFun) + ), + limitHasType + ) + + val pointwiseGoal = app(recWitness(limitFun))(a) === app(limitFun)(a) + + have((a ∈ spec.argType) ==> pointwiseGoal) subproof { + val aInArgType = assume(a ∈ spec.argType) + + // ── Height index for a ────────────────────────────────────────────────── + val indexWitness = have( + (limitIndex(a) ∈ N) /\ (a ∈ app(heightFun)(limitIndex(a))) + ) by Cuts( + LimitKernel.limitIndexWitnessAt(spec.argType, heightFun, chosenIndexFamily, a) + )( + spec.adt.height.termHasHeightAt(spec.typeSubstitutions, Seq(x := a, h := heightFun)), + heightFunValid, + aInArgType + ) + + val n0 = limitIndex(a) + val indexInN = have(n0 ∈ N) by Weakening(indexWitness) + val aInHeightN0 = have(a ∈ app(heightFun)(n0)) by Weakening(indexWitness) + + val succN0InN = have(S(n0) ∈ N) by Cut( + indexInN, + have((n0 ∈ N) |- (S(n0) ∈ N)) by Weakening(successorInOmega.of(n := n0)) + ) + + // a ∈ h(S(n0)) + val aInHeightSuccN0 = have(a ∈ app(heightFun)(S(n0))) by Cuts( + spec.adt.height.successorInclusionAt(spec.typeSubstitutions, Seq(h := heightFun, n := n0, x := a)) + )(heightFunValid, indexInN, aInHeightN0) + + // ── G(n0) type and stabilization chain ───────────────────────────────── + val approxAtN0Inst = have(n0 ∈ N ==> (G(n0) :: spec.typ)) by InstantiateForall(n0)(approxSeq.approxHasType) + val approxSuccAtN0Impl = have(n0 ∈ N ==> (G(S(n0)) === recWitness(G(n0)))) by + InstantiateForall(n0)(approxSeq.approxSucc) + val gN0HasType = have(G(n0) :: spec.typ) by Cut( + indexInN, + have((n0 ∈ N) |- (G(n0) :: spec.typ)) by Restate.from(approxAtN0Inst) + ) + val gSuccN0EqWitness = have(G(S(n0)) === recWitness(G(n0))) by Cut( + indexInN, + have((n0 ∈ N) |- (G(S(n0)) === recWitness(G(n0)))) by Restate.from(approxSuccAtN0Impl) + ) + + // G(n0)(a) = G(Succ(n0))(a) via approximantsAgreeFromSubset (avoids capture of `a` in stabilization) + val stabAtAFact = have(app(G(n0))(a) === app(G(S(n0)))(a)) by Cuts( + ApproximationChainFacts.approximantsAgreeFromSubsetAt( + heightFun, + approximantFamily, + n0, + S(n0), + a, + stabilization, + heightMembershipMonotonic, + heightFunValid + ) + )( + indexInN, + succN0InN, + subsetSuccessor.of(n := n0), + aInHeightN0 + ) + val gN0AtAEqWitness = have(app(recWitness(G(n0)))(a) === app(G(n0))(a)) by + Congruence.from(stabAtAFact, gSuccN0EqWitness) + + // ── Witness agreement at a via the shared WitnessAgreement lemma ──────── + // limitFun and G(n0) agree on the height slice h(n0): at each point the + // limit value is the stabilized approximant value G(n0). This is exactly + // the slice-agreement premise of WitnessAgreement.witnessAgreementAtSucc. + val sliceVar = spec.proofVariable("sliceVar") + + val limitEqApprox = have( + (sliceVar ∈ app(heightFun)(n0)) ==> (app(limitFun)(sliceVar) === app(G(n0))(sliceVar)) + ) by Cuts( + LimitKernel.limitAtHeightAt( + spec.argType, + heightFun, + limitFun, + approximantFamily, + chosenIndexFamily, + sliceVar, + n0, + stabilization, + heightMembershipMonotonic, + heightFunValid + ) + )( + spec.adt.height.termHasHeightAt(spec.typeSubstitutions, Seq(x := sliceVar, h := heightFun)), + heightFunValid, + indexInN + ) + + val limitAtAEqGN0 = have(app(limitFun)(a) === app(G(n0))(a)) by Cut( + aInHeightN0, + have((a ∈ app(heightFun)(n0)) |- (app(limitFun)(a) === app(G(n0))(a))) by Restate.from( + limitEqApprox of (sliceVar := a) + ) + ) + val sliceAgreement = have( + ∀(sliceVar ∈ app(heightFun)(n0), app(limitFun)(sliceVar) === app(G(n0))(sliceVar)) + ) by RightForall(limitEqApprox) + + // ∀x ∈ h(Succ n0), W(limitFun)(x) = W(G(n0))(x). + // n0 = limitIndex(a) mentions the free variable `a`, so we must not rebind + // `a` here: take the lemma's conclusion verbatim (its bound variable is + // already renamed away from `a`) and instantiate it at `a`. + // Chain: W(limit)(a) === W(G(n0))(a) === G(n0)(a) === limit(a), with the + // first link supplied by the witness agreement and the rest as bridges. + have(pointwiseGoal) by Restate.from( + witnessAgreement.witnessesAgreeAt( + lhs = limitFun, + rhs = G(n0), + index = n0, + lhsTyped = limitHasType, + rhsTyped = gN0HasType, + indexInN = indexInN, + sliceAgreement = sliceAgreement, + pointInHeightSucc = aInHeightSuccN0, + goal = pointwiseGoal, + bridges = Seq(gN0AtAEqWitness, limitAtAEqGN0) + ) + ) + } + + val forallPointwise = thenHave(∀(a, (a ∈ spec.argType) ==> pointwiseGoal)) by RightForall + + have( + (functionBetween(recWitness(limitFun))(spec.argType)(spec.returnType), functionBetween(limitFun)(spec.argType)(spec.returnType), ∀(a, (a ∈ spec.argType) ==> pointwiseGoal)) |- (recWitness( + limitFun + ) === limitFun) + ) by Restate.from( + functionalExtentionality of (Utils.f := recWitness(limitFun), g := limitFun, A := spec.argType, B := spec.returnType) + ) + have(recWitness(limitFun) === limitFun) by Cuts(lastStep)( + witnessAtLimitBetween, + limitBetween, + forallPointwise + ) + thenHave(thesis) by Restate + }) + + // ───────────────────────────────────────────────────────────────────────── + // witnessExists: ∃f, Def(f) + // ───────────────────────────────────────────────────────────────────────── + + val witnessExists: Theorem = Lemma.generated(∃(f, spec.definitionAt(f))) { + + val wfEqF = have(recWitness(f) === f |- recWitness(f) === f) by Hypothesis + val fTyped = have(spec.typeConstraint(f) |- spec.typeConstraint(f)) by Hypothesis + + val caseFacts = spec.patternMatching.clauses + .map(pattern => + + val body = pattern.body.substitute(spec.selfPlaceholder := f) + val witnessCaseSchema = recWitness.witnessCase(pattern).of(spec.selfPlaceholder := f) + + val allForalls = have( + spec.typeConstraint(f) |- forallSeq(pattern.binders, pattern.branchPremise ==> (recWitness(f) * pattern.inputTerm === body)) + ) by Tautology.from(witnessCaseSchema) + + have((spec.typeConstraint(f), recWitness(f) === f) |- spec.patternConstraint(pattern, f)) by Substitute(wfEqF)(allForalls) + ) + .toSeq + + have((spec.typeConstraint(f), recWitness(f) === f) |- spec.equationConstraint(f)) by Tautology.from(caseFacts*) + have((spec.typeConstraint(f), recWitness(f) === f) |- spec.definitionAt(f)) by RightAnd(fTyped, lastStep) + have(spec.definitionAt(limitFun)) by Cuts(lastStep of (f := limitFun))(limitHasType, limitIsFixedPoint) + thenHave(thesis) by RightExists + + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/FunSpec.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/FunSpec.scala new file mode 100644 index 000000000..608d6ec75 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/FunSpec.scala @@ -0,0 +1,107 @@ +package lisa.maths.SetTheory.Types.ADT.recursion + +import lisa.maths.SetTheory.Functions.Pi.->: +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.encoding._ +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.TypeSubstitution +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.specializeTerm +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.prooflib.Thm + +/** + * The parameters, cases, and defining predicate of a function. + */ +final class FunSpec( + val functionName: String, + val typeVariablesSeq: Seq[Variable[Ind]], + val adt: SemanticADT, + val argType: Expr[Ind], + val typeSubstitutions: Seq[TypeSubstitution], + val selfPlaceholder: Variable[Ind], + val patternMatching: PatternSystem[Expr[Ind]], + val returnType: Expr[Ind] +) { + val cases: Seq[Clause[Expr[Ind]]] = patternMatching.clauses + val typ: Expr[Ind] = argType ->: returnType + + /** + * Checks parameter scope before constructing any function definitions or proofs. + */ + private def validateParameters(): Unit = { + require(typeVariablesSeq.distinct.size == typeVariablesSeq.size, s"Function $functionName has duplicate parameters.") + val parameters = typeVariablesSeq.toSet + cases.foreach { pattern => + val shadowed = pattern.binders.filter(v => parameters.contains(v) || v == selfPlaceholder) + require(shadowed.isEmpty, s"Function $functionName: pattern ${pattern.name} shadows a parameter or recursive self-reference: ${shadowed.mkString(", ")}.") + } + val branchVariables = cases.flatMap { pattern => + (pattern.typingFormula.freeVars ++ pattern.branchCondition.freeVars ++ pattern.inputTerm.freeVars ++ pattern.body.freeVars) -- pattern.binders + } + val undeclared = (typ.freeVars ++ branchVariables) -- parameters - selfPlaceholder + require(undeclared.isEmpty, s"Function $functionName has undeclared free variables: ${undeclared.toSeq.map(_.toString).sorted.mkString(", ")}.") + } + + validateParameters() + + private val proofVariables = collection.mutable.Map.empty[String, Variable[Ind]] + private val proofContext: Seq[Expr[?]] = typeVariablesSeq ++ Seq(typ, selfPlaceholder) ++ + adt.constructors.flatMap(constructor => constructor.variables1 ++ constructor.variables2) ++ cases.flatMap { pattern => + pattern.binders ++ pattern.variables1 ++ pattern.variables2 ++ + Seq(pattern.typingFormula, pattern.branchCondition, pattern.inputTerm, pattern.body) + } + + /** + * Shares proof variables fresh against the declaration and the other generated variables. + */ + private[recursion] def proofVariable(name: String): Variable[Ind] = + proofVariables.getOrElseUpdate(name, Variable[Ind](freshId(proofContext ++ proofVariables.values, name))) + + def typeConstraint(fVar: Expr[Ind]): Expr[Prop] = + fVar :: typ + + def patternConstraint(pattern: Clause[Expr[Ind]], fVar: Expr[Ind]): Expr[Prop] = + forallSeq( + pattern.binders, + pattern.branchPremise ==> (selfPlaceholder * pattern.inputTerm === pattern.body) + ).substitute(selfPlaceholder := fVar) + + def equationConstraint(fVar: Expr[Ind]): Expr[Prop] = + simplify(seqAnd(cases.map(pattern => patternConstraint(pattern, fVar)))) + + /** + * The defining predicate, stated about the recursive self-reference. + */ + lazy val definitionFormula: Expr[Prop] = + typeConstraint(selfPlaceholder) /\ equationConstraint(selfPlaceholder) + + /** + * The defining predicate specialized to the candidate `fVar`. + */ + def definitionAt(fVar: Expr[Ind]): Expr[Prop] = + definitionFormula.substitute(selfPlaceholder := fVar) + + /** + * The height predicate specialized to this function's domain. + */ + def isHeightPred(hh: Expr[Ind]): Expr[Prop] = + adt.height.predicateAt(typeSubstitutions)(hh) + + /** + * The domain's specialized height function. + */ + val heightFun: Expr[Ind] = specializeTerm(adt.height.function, typeSubstitutions) + + /** + * Validity of the domain's specialized height function. + */ + def heightFunValid(using proof: lisa.SetTheoryLibrary.Proof): Thm = adt.height.validAt(typeSubstitutions) + + /** + * The height function starts with the empty stage. + */ + def heightZero(point: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + adt.height.zeroAt(typeSubstitutions, Seq(h := heightFun, x := point)) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/LimitConstruction.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/LimitConstruction.scala new file mode 100644 index 000000000..a1ad674be --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/LimitConstruction.scala @@ -0,0 +1,82 @@ +package lisa.maths.SetTheory.Types.ADT.recursion + +import lisa.maths.Quantifiers +import lisa.maths.SetTheory.Functions.Function.abs +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.maths.SetTheory.Types.TypingRules.TAbs +import lisa.maths.SetTheory.Types.TypingRules.TApp + +/** + * Chooses a sufficient height for each input to construct the typed limit function. + */ +private[recursion] final class LimitConstruction( + val spec: FunSpec, + val approxSeq: ApproxSequence, + val approxStab: ApproxStabilization +) { + private val nVar = spec.proofVariable("nVar") + private val a = spec.proofVariable("a") + private val typePoint = spec.proofVariable("typePoint") + import approxSeq.G + import spec.{heightFun, heightFunValid, isHeightPred} + + private val indexAtPoint = ε(nVar, (nVar ∈ N) /\ (a ∈ app(heightFun)(nVar))) + + /** + * A natural-number height containing the supplied input when it belongs to the domain. + */ + def limitIndex(point: Expr[Ind]): Expr[Ind] = + indexAtPoint.substitute(a := point) + + /** + * Evaluates each input using an approximant at its chosen height. + */ + val limitFun: Expr[Ind] = + abs(spec.argType)(λ(a, app(G(limitIndex(a)))(a))) + + /** + * The limit has the function's declared type. + */ + val limitHasType: Theorem = Lemma.generated(limitFun :: spec.typ) { + val T1, e1, e2 = variable[Ind] + val T2, e = variable[Ind >>: Ind] + val hValid = have(isHeightPred(heightFun)) by Restate.from(heightFunValid) + + have(a ∈ spec.argType |- app(G(limitIndex(a)))(a) ∈ spec.returnType) subproof { + val aInArgType = assume(a ∈ spec.argType) + val hasSomeHeight = have( + ∃(nVar, (nVar ∈ N) /\ (a ∈ app(heightFun)(nVar))) + ) by Tautology.from( + hValid, + aInArgType, + spec.adt.height.termHasHeightAt(spec.typeSubstitutions, Seq(x := a, h := heightFun)) + ) + val indexWitness = have( + (limitIndex(a) ∈ N) /\ (a ∈ app(heightFun)(limitIndex(a))) + ) by Cut( + hasSomeHeight, + Quantifiers.existsEpsilon.of( + x := nVar, + P := λ(nVar, (nVar ∈ N) /\ (a ∈ app(heightFun)(nVar))) + ) + ) + val approxAtIndex = have(limitIndex(a) ∈ N ==> (G(limitIndex(a)) :: spec.typ)) by + InstantiateForall(limitIndex(a))(approxSeq.approxHasType) + val approxTyped = have(G(limitIndex(a)) :: spec.typ) by Tautology.from(indexWitness, approxAtIndex) + have(thesis) by Tautology.from( + approxTyped, + aInArgType, + TApp.of(T1 := spec.argType, T2 := λ(typePoint, spec.returnType), e1 := G(limitIndex(a)), e2 := a) + ) + } + thenHave(a ∈ spec.argType ==> app(G(limitIndex(a)))(a) ∈ spec.returnType) by Restate + val everyValueTyped = thenHave(∀(a ∈ spec.argType, app(G(limitIndex(a)))(a) ∈ spec.returnType)) by RightForall + have(thesis) by Cut( + everyValueTyped, + TAbs.of(T1 := spec.argType, T2 := λ(typePoint, spec.returnType), e := λ(a, app(G(limitIndex(a)))(a))) + ) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/SemanticFunction.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/SemanticFunction.scala new file mode 100644 index 000000000..dfdf7ce97 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/SemanticFunction.scala @@ -0,0 +1,155 @@ +package lisa.maths.SetTheory.Types.ADT.recursion + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.encoding._ +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.TypeSubstitution +import lisa.maths.SetTheory.Types.ADT.support.UniqueDefinedSymbol +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers._ + +/** + * Constructs a function by recursion and proves its typing and case equations. + */ +final class SemanticFunction( + val name: String, + val typeVariablesSeq: Seq[Variable[Ind]], + adt: SemanticADT, + val argType: Expr[Ind], + typeSubstitutions: Seq[TypeSubstitution], + selfPlaceholder: Variable[Ind], + patternMatching: PatternSystem[Expr[Ind]], + val returnType: Expr[Ind] +) { + private val spec = new FunSpec(name, typeVariablesSeq, adt, argType, typeSubstitutions, selfPlaceholder, patternMatching, returnType) + private val witness = new Witness(spec) + private val approxSeq = new ApproxSequence(spec, witness) + private val witnessAgreement = new helpers.WitnessAgreement(spec, witness) + private val approxStab = new ApproxStabilization(spec, witness, approxSeq, witnessAgreement) + private val limitConstruction = new LimitConstruction(spec, approxSeq, approxStab) + private val existence = new Existence(spec, witness, approxSeq, approxStab, limitConstruction, witnessAgreement) + private val uniqueness = new Uniqueness(spec) + + /** + * The function's set-theoretic type. + */ + val typ: Expr[Ind] = spec.typ + + /** + * Defines the unique function satisfying the typing and case equations. + */ + private val definedClassFunction: UniqueDefinedSymbol = + UniqueDefinedSymbol.fromParts( + name = name, + typeVariablesSeq = typeVariablesSeq, + witnessVar = spec.proofVariable("f"), + comparisonVariables = uniqueness.comparisonVariables, + definitionAt = spec.definitionAt + )(existence.witnessExists, uniqueness.pointwiseUniqueness) + + val id: Identifier = definedClassFunction.id + + val term: Expr[Ind] = definedClassFunction.term + + def term(args: Seq[Expr[Ind]]): Expr[Ind] = definedClassFunction.term(args) + + /** + * Instantiates the bodies while sharing the compiled clauses and their proof caches. + */ + val cases: PatternSystem[Expr[Ind]] = patternMatching.map(_.substitute(selfPlaceholder := term)) + + /** + * The defining clauses of the completed function in source order. + */ + val clauses: Seq[Clause[Expr[Ind]]] = cases.clauses + + private lazy val clauseIndices = clauses.zipWithIndex.toMap + private lazy val clausesByConstructor = clauses.groupBy(_.semanticConstructor) + private val shortDefinitions = scala.collection.mutable.Map.empty[Clause[Expr[Ind]], Theorem] + private val constructorDefinitions = scala.collection.mutable.Map.empty[SemanticConstructor, Theorem] + + private def equation(pattern: Clause[Expr[Ind]]): Expr[Prop] = + simplify(pattern.branchPremise ==> (term * pattern.inputTerm === pattern.body)) + + /** + * Proves and caches the requested clause equation. + */ + def shortDefinition(pattern: Clause[Expr[Ind]]): Theorem = + shortDefinitions.getOrElseUpdate( + pattern, { + val index = clauseIndices.getOrElse( + pattern, + throw new IllegalArgumentException(s"Pattern ${pattern.name} does not belong to function $name.") + ) + Lemma.named(s"$name/case/$index")(equation(pattern)) { + have(forallSeq(pattern.binders, pattern.branchPremise ==> (term * pattern.inputTerm === pattern.body))) by + Weakening(definedClassFunction.definitionFact) + pattern.binders.foreach { _ => + lastStep.statement.right.head match + case forall(v, phi) => thenHave(phi) by InstantiateForall(v) + case _ => throw UnreachableException + } + thenHave(thesis) by Restate + } + } + ) + + /** + * Returns the cached equation of one clause. + */ + def elimByPattern(pattern: Clause[Expr[Ind]]): Theorem = + shortDefinition(pattern) + + private def combinedDefinition(patterns: Seq[Clause[Expr[Ind]]], suffix: String): Theorem = + patterns match + case Seq(pattern) => shortDefinition(pattern) + case _ => + Lemma.named(s"$name/$suffix")(seqAnd(patterns.map(equation))) { + have(thesis) by Tautology.from(patterns.map(shortDefinition)*) + } + + /** + * Caches one constructor's equations, reusing the branch theorem for a single clause. + */ + def elimByConst(constructor: SemanticConstructor): Theorem = + constructorDefinitions.getOrElseUpdate( + constructor, { + val patterns = clausesByConstructor.getOrElse( + constructor, + throw new IllegalArgumentException(s"No pattern registered for constructor ${constructor.name}.") + ) + combinedDefinition(patterns, s"constructor/${constructor.name}") + } + ) + + /** + * Returns the cached equation of one clause. + */ + def elim(pattern: Clause[Expr[Ind]]): Theorem = + elimByPattern(pattern) + + /** + * Returns the cached equations covering one constructor. + */ + def elim(constructor: SemanticConstructor): Theorem = + elimByConst(constructor) + + /** + * Returns the cached equations covering one constructor. + */ + def shortDefinition(constructor: SemanticConstructor): Theorem = + elimByConst(constructor) + + /** + * The conjunction of the short defining equations of all clauses. + */ + lazy val elimTotal: Theorem = combinedDefinition(clauses, "cases") + + /** + * Typing introduction: the defined symbol inhabits its function type. + */ + val intro: Theorem = Lemma.generated(term :: typ) { + have(thesis) by Weakening(definedClassFunction.definitionFact) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Uniqueness.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Uniqueness.scala new file mode 100644 index 000000000..708507142 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Uniqueness.scala @@ -0,0 +1,106 @@ +package lisa.maths.SetTheory.Types.ADT.recursion + +import lisa.maths.SetTheory.Functions.BasicTheorems +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.recursion.helpers.PatternSchemas +import lisa.maths.SetTheory.Types.ADT.recursion.helpers.RecFunctionInduction +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.A +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.B +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.f +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.g +import lisa.maths.SetTheory.Types.ADT.support.semantics.DefinedProperty +import lisa.maths.SetTheory.Types.ADT.support.tactics.Cuts +import lisa.maths.SetTheory.Types.TypingHelpers._ + +private[recursion] final class Uniqueness( + spec: FunSpec +) { + + private val adt = spec.adt + private val argType = spec.argType + + /** + * The fresh candidates compared by the uniqueness theorem. + */ + val comparisonVariables: (Variable[Ind], Variable[Ind]) = (spec.proofVariable("x"), spec.proofVariable("y")) + private val (x, y) = comparisonVariables + + private def patternSchemas(functionHead: Expr[Ind]): PatternSchemas = + spec.cases.map(pattern => pattern -> (pattern.binders, spec.patternConstraint(pattern, functionHead))).toMap + + // Keep the defining predicate opaque in ambient assumptions; unfold it only + // when deriving a clause equation. + private val defVar = spec.proofVariable("defVar") + private val defSym = DefinedProperty( + s"${spec.functionName}/def", + spec.typeVariablesSeq, + defVar, + spec.definitionAt + ) + private def Def(v: Expr[Ind]): Expr[Prop] = defSym.term #@ v + + private val pointwiseAgreement: Theorem = + val xDefFormula = spec.definitionAt(x) + val yDefFormula = spec.definitionAt(y) + val pointInput = spec.proofVariable("pointInput") + Lemma.generated( + xDefFormula /\ yDefFormula |- ∀(pointInput, pointInput ∈ argType ==> (x * pointInput === y * pointInput)) + ) { + + val pointwiseCoreLemma = RecFunctionInduction.pointwiseUniquenessAt( + adt = adt, + patternMatching = spec.patternMatching, + argType = argType, + typeSubstitutions = spec.typeSubstitutions, + inductionVariable = pointInput, + assumptions = Set(Def(x), Def(y)), + propertyAt = t => x * t === y * t, + xFun = x, + yFun = y, + xDefinitionFormula = xDefFormula, + yDefinitionFormula = yDefFormula, + xPatternSchemas = patternSchemas(x), + yPatternSchemas = patternSchemas(y), + definitionProperty = defSym + ) + + // Fold the two defining formulas to discharge the opaque hypotheses. + val hyp = assume(xDefFormula /\ yDefFormula) + + val xDefinition = have(xDefFormula) by Weakening(hyp) + val defX = have(Def(x)) by Cut(xDefinition, defSym.foldAt(x)) + val yDefinition = have(yDefFormula) by Weakening(hyp) + val defY = have(Def(y)) by Cut(yDefinition, defSym.foldAt(y)) + + have(thesis) by Cuts(pointwiseCoreLemma)(defX, defY) + } + + /** + * Any two solutions of the defining predicate are equal. + */ + lazy val pointwiseUniqueness: Theorem = + val xDef = spec.definitionAt(x) + val yDef = spec.definitionAt(y) + Lemma.generated(xDef /\ yDef ==> (x === y)) { + + have(thesis) by Tautology.from( + BasicTheorems.functionalExtentionality of ( + f := x, + g := y, + A := spec.argType, + B := spec.returnType + ), + BasicTheorems.funcBetweenEqInFuncSpace of ( + f := x, + A := spec.argType, + B := spec.returnType + ), + BasicTheorems.funcBetweenEqInFuncSpace of ( + f := y, + A := spec.argType, + B := spec.returnType + ), + pointwiseAgreement + ) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Witness.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Witness.scala new file mode 100644 index 000000000..174bdcf7f --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Witness.scala @@ -0,0 +1,137 @@ +package lisa.maths.SetTheory.Types.ADT.recursion + +import lisa.maths.SetTheory.Base.CartesianProduct.× +import lisa.maths.SetTheory.Base.Comprehension.| +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.proofs.CaseDefinedWitness +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.support.DefinedSymbol +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.Tactics.Typecheck +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.prooflib.InstantiateForallSeq +import lisa.utils.prooflib.Thm + +/** + * The case-defined graph W(g), with g supplying the recursive calls. + */ +private[recursion] final class Witness(spec: FunSpec) { + private val pairWitness = spec.proofVariable("pairWitness") + private val witnessBound = spec.argType × spec.returnType + private val caseMembership: Expr[Ind] => Expr[Prop] = spec.patternMatching.caseMembership + private val witnessClass = new DefinedSymbol( + name = s"${spec.functionName}/witness", + parametersSeq = spec.typeVariablesSeq :+ spec.selfPlaceholder, + body = { pairWitness ∈ witnessBound | caseMembership(pairWitness) } + ) + + /** + * The graph's defining equality. + */ + val witnessDef: Thm = witnessClass.definition + + /** + * Instantiates the graph with a candidate recursive function. + */ + def apply(g: Expr[Ind]): Expr[Ind] = + witnessClass.term.substitute(spec.selfPlaceholder := g) + + /** + * The typing assumption on the candidate recursive function. + */ + val typingPremise: Expr[Prop] = spec.selfPlaceholder :: spec.typ + + private val basePatterns: Set[Clause[Expr[Ind]]] = spec.adt.constructors + .filter(_.selfRefVariables2.isEmpty) + .flatMap(spec.patternMatching.clausesFor) + .toSet + + private val checkReturnType: Map[Clause[Expr[Ind]], Thm] = + spec.cases.map { pattern => + val premises = if basePatterns.contains(pattern) then Set.empty[Expr[Prop]] else Set(typingPremise) + pattern -> Lemma + .generated((pattern.typingPremises ++ premises) |- (pattern.body :: spec.returnType)) { + have(thesis) by Typecheck.prove(using lisa.SetTheoryLibrary, summon[Proof]) + } + .thm + }.toMap + + private lazy val witnessSemantics = new CaseDefinedWitness( + adt = spec.adt, + argType = spec.argType, + patternMatching = spec.patternMatching, + returnType = spec.returnType, + typ = spec.typ, + witness = witnessClass.term, + witnessDef = witnessDef, + witnessBound = witnessBound, + pairWitness = pairWitness, + caseMembership = caseMembership, + checkReturnType = checkReturnType, + contextPremises = Seq(typingPremise) + ) + + /** + * The graph has the declared function type under the candidate's typing assumption. + */ + lazy val witnessHasType: Theorem = witnessSemantics.witnessHasType + + /** + * The graph satisfies the given case equation. + */ + def witnessCase(pattern: Clause[Expr[Ind]]): Theorem = witnessSemantics.witnessCase(pattern) + + /** + * An input provides a target inhabitant, by induction on the input ADT. + */ + val targetInhabited: Theorem = { + val point = spec.proofVariable("input") + val value = spec.proofVariable("inhabitant") + val inhabited = ∃(value, value :: spec.returnType) + val predicate = λ(point, inhabited) + + Lemma.generated(∀(point, point :: spec.argType ==> inhabited)) { + val cases = spec.adt.constructors.map { constructor => + val inductiveCase = constructor.inductiveCase.substitute(spec.typeSubstitutions*).substitute(P := predicate) + have(inductiveCase) subproof { + if constructor.selfRefVariables2.nonEmpty then + // Any recursive argument supplies the same constant induction hypothesis. + have(thesis) by Tautology + else + val patterns = spec.patternMatching.clausesFor(constructor) + val vars = patterns.head.variables2.take(constructor.arity) + val input = constructor.appliedTerm(vars).substitute(spec.typeSubstitutions*) + val typing = constructor.semanticSignature(vars).map((v, t) => v :: t.substitute(spec.typeSubstitutions*)) + val branches = patterns.map { pattern => + val guard = pattern.branchSelectionBody(input) + val branch = have((typing.toSet + guard) |- inhabited) subproof { + have(pattern.freshTypingFormula |- pattern.bodyAtFreshVars2 :: spec.returnType) by Restate.from( + checkReturnType(pattern).of(pattern.binders.zip(pattern.variables2).map((from, to) => from := to)*) + ) + thenHave(pattern.freshTypingFormula |- inhabited) by RightExists + thenHave(thesis) by Tautology + } + val (selection, selected) = pattern.variables2.drop(pattern.arity).foldRight((guard, branch)) { case (v, (condition, fact)) => + val existential = ∃(v, condition) + val lifted = have((typing.toSet + existential) |- inhabited) by LeftExists(fact) + (existential, lifted) + } + have(typing.toSet |- selection ==> inhabited) by RightImplies.withParameters(selection, inhabited)(selected) + } + val alternatives = seqOr(patterns.map(_.branchSelectionDisjunct(input))) + val selector = have((seqAnd(typing) /\ (input === input)) ==> alternatives) by + InstantiateForallSeq(vars)(spec.patternMatching.branchSelectionFor(constructor, input)) + val combined = have(typing.toSet |- inhabited) by Tautology.from((selector +: branches)*) + val abstracted = vars.zip(typing).foldRight(combined) { case ((v, assumption), fact) => + val implication = have((fact.statement - fact.statement.right.head) by Restate.from(fact) + have(implication.statement.left |- ∀(v, implication.statement.right.head)) by RightForall(implication) + } + have(thesis) by Restate.from(abstracted) + } + } + have(thesis) by Tautology.from((cases :+ spec.adt.induction.of(spec.typeSubstitutions*).of(P := predicate))*) + } + } + + private val _ = witnessSemantics +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/LambdaBodyEquality.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/LambdaBodyEquality.scala new file mode 100644 index 000000000..83a253bbd --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/LambdaBodyEquality.scala @@ -0,0 +1,54 @@ +package lisa.maths.SetTheory.Types.ADT.recursion.helpers + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.tactics.Cuts +import lisa.utils.prooflib.BasicStep.RightSubst +import lisa.utils.prooflib.Thm + +/** + * Transports recursive-call equalities through branch bodies, including nested binders. + */ +private[recursion] object LambdaBodyEquality { + + /** + * Proves body equality by simultaneous substitution of the available recursive-call equalities. + */ + def prove(using + proof: lisa.SetTheoryLibrary.Proof + )( + assumptions: Set[Expr[Prop]], + leftBody: Expr[Ind], + rightBody: Expr[Ind], + equalityFacts: Seq[Thm] + ): Thm = + if leftBody == rightBody then have(assumptions |- leftBody === rightBody) by RightRefl + else if equalityFacts.nonEmpty then + val equalities = equalityFacts + .map { fact => + require(fact.statement.right.size == 1, "A recursive-call equality must have exactly one conclusion.") + val formula = fact.statement.right.head + asIndEquality(formula) match + case Some(pair) => pair -> fact + case None => throw IllegalArgumentException(s"Expected a recursive-call equality, got $formula.") + } + .distinctBy(_._1) + val pairs = equalities.map(_._1) + val reserved: Seq[Expr[?]] = Seq(leftBody, rightBody) ++ assumptions ++ + equalityFacts.flatMap(fact => fact.statement.left ++ fact.statement.right) + val firstHole = freshId(reserved, "recursiveValue") + val holes = pairs.indices.map(i => Variable[Ind](Identifier(firstHole.name, firstHole.no + i))) + // Expr.rewrite abstracts exact call occurrences without capturing variables under binders. + val template = pairs.zip(holes).foldLeft(leftBody) { case (body, ((left, _), hole)) => + body.rewrite(left, hole) + } + val equations = pairs.map((left, right) => left === right).toSet + val refl = have(leftBody === leftBody) by RightRefl + val transported = have((assumptions ++ equations) |- leftBody === rightBody) by + RightSubst(pairs, holes -> (leftBody === template))(refl) + have(assumptions |- leftBody === rightBody) by Cuts(transported)(equalities.map(_._2)*) + else + throw IllegalArgumentException( + s"Cannot prove body equality without recursive equalities: $leftBody vs $rightBody." + ) + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/PointwiseAgreementStep.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/PointwiseAgreementStep.scala new file mode 100644 index 000000000..aea7823b9 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/PointwiseAgreementStep.scala @@ -0,0 +1,240 @@ +package lisa.maths.SetTheory.Types.ADT.recursion.helpers + +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.recursion.proofs.ConstructorSemanticFacts.SpecializedConstructorFacts +import lisa.maths.SetTheory.Types.ADT.recursion.proofs.ConstructorSemanticFacts.constructorBranchAtHeight +import lisa.maths.SetTheory.Types.ADT.recursion.proofs.ConstructorSemanticFacts.constructorDisjunctionAtHeight +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.tactics.Cuts +import lisa.utils.prooflib.InstantiateForallSeq +import lisa.utils.prooflib.Thm + +/** + * Shared structural core of a "pointwise agreement at the S height" + * proof — the step shape common to [[WitnessAgreement.witnessAgreementAtSucc]] + * and the inductive step of `RecFunctionInduction.pointwiseUniquenessAt`. + * + * It performs the height decomposition, per-constructor branch selection, + * existential unbinding and case assembly that prove + * + * ∀ a ∈ h(Succ currentIndex), goalEqAt + * + * and, for each selected pattern, the full per-pattern agreement proof: + * recursive-argument agreements (direct and nested), body equality, and the + * closing congruence. The only genuinely function-specific input — how to + * obtain, for one side, the case body and the `goalFun * input === body` + * equation — is delegated to [[PatternCaseEquations]]. + */ +private[recursion] object PointwiseAgreementStep { + + /** + * Function-specific per-pattern ingredients consumed by [[pointwiseAgreementOnSucc]]. + * + * Every method that builds proof facts is `(using proof)` so that, when the + * orchestration invokes it inside a constructor's / pattern's subproof, its `proof` + * binds to that subproof's inner proof. Facts are therefore re-derived there (the + * implementations `assume` the ambient hypotheses, which is idempotent) rather than + * captured from an enclosing proof, which cannot lift into the abstract `proof`. + * + * - `sliceLeft`/`sliceRight` — the functions the slice-agreement hypothesis relates + * (recursion threads through these); the case bodies substitute them. + * - `recursiveType` — locates and types the nested recursive agreement points. + * - `sliceAgreement` — the `∀(v ∈ h(currentIndex), sliceLeft(v) === sliceRight(v))` hypothesis. + * - `bodyEqAssumptions` — the assumption set under which body equality is proved + * (kept atomic to control proof cost). + * - `caseEquation` — for one side, the case body (with `slice` substituted) and the + * equation `goalFun * input === body`, where `goalFun` is determined by the side. + */ + trait PatternCaseEquations { + def recursiveType: Expr[Ind] + def sliceLeft: Expr[Ind] + def sliceRight: Expr[Ind] + def sliceAgreement(using proof: lisa.SetTheoryLibrary.Proof): Thm + def bodyEqAssumptions(using + proof: lisa.SetTheoryLibrary.Proof + )( + pattern: Clause[Expr[Ind]], + patternGuard: Thm + ): Set[Expr[Prop]] + def caseEquation(using + proof: lisa.SetTheoryLibrary.Proof + )( + pattern: Clause[Expr[Ind]], + slice: Expr[Ind], + patternPremise: Thm, + patternGuard: Thm, + bodyEqAssumptions: Set[Expr[Prop]] + ): (Expr[Ind], Thm) + } + + private def agreementAt(using + proof: lisa.SetTheoryLibrary.Proof + )( + heightFun: Expr[Ind], + currentIndex: Expr[Ind], + leftFun: Expr[Ind], + rightFun: Expr[Ind], + agreeForall: Thm, + point: Expr[Ind], + pointInHeight: Thm + ): Thm = { + val pIn: Expr[Prop] = point ∈ app(heightFun)(currentIndex) + val pEq: Expr[Prop] = app(leftFun)(point) === app(rightFun)(point) + val atPoint = have(pIn ==> pEq) by InstantiateForall(point)(agreeForall) + + val viaImpl = have((atPoint.statement.left + pIn) |- pEq) by Weakening(atPoint) + have((atPoint.statement.left ++ pointInHeight.statement.left) |- pEq) by Cut(pointInHeight, viaImpl) + } + + def pointwiseAgreementOnSucc(using + proof: lisa.SetTheoryLibrary.Proof + )( + patternMatching: PatternSystem[Expr[Ind]], + heightFun: Expr[Ind], + constructorsAt: Seq[SpecializedConstructorFacts], + ambientTerm: Variable[Ind], + currentIndex: Expr[Ind], + currentIndexInN: Thm, + hValid: Thm, + heightSuccStrong: Thm, + goalEqAt: Expr[Prop] + )( + caseEqs: PatternCaseEquations + ): Thm = { + val pointwiseAtSucc = + have((ambientTerm ∈ app(heightFun)(S(currentIndex))) ==> goalEqAt) subproof { + val aInHeightOrd = assume(ambientTerm ∈ app(heightFun)(S(currentIndex))) + + val constructorDisjunction = + constructorDisjunctionAtHeight(constructorsAt, app(heightFun)(currentIndex), ambientTerm) + + // `heightSuccStrong` instantiated at the point gives the membership/constructor + // biconditional; discharge its two side conditions by Cut, then rewrite the + // height-membership hypothesis through it to land on the constructor disjunction. + val heightSuccIff = have( + (ambientTerm ∈ app(heightFun)(S(currentIndex))) <=> constructorDisjunction + ) by Cuts(heightSuccStrong)( + hValid, + currentIndexInN + ) + val decomposeAtA = have(constructorDisjunction) by Substitute(heightSuccIff)(aInHeightOrd) + + val branchEqualities = constructorsAt.map { sc => + val c = sc.underlying + val constructorPatterns = patternMatching.clausesFor(c) + val branchPremise = sc.branchPremiseAtHeight(app(heightFun)(currentIndex), ambientTerm) + + val directBranch = have(branchPremise |- goalEqAt) subproof { + assume(branchPremise) + + val argsTypedAtHeight = have(sc.heightTypingFormula(app(heightFun)(currentIndex))) by Restate + val argsTypedSemantic = have(wellTypedFormula(sc.semanticSignature2)) by + Cuts(sc.semanticTypingFromHeight(heightFun, currentIndex))(hValid, currentIndexInN, argsTypedAtHeight) + val aEqApplied = have(ambientTerm === sc.appliedTerm2) by + Cuts(sc.appliedEqualityFromStructural(heightFun, currentIndex, ambientTerm))(hValid, currentIndexInN) + + // Agreements at the constructor's direct self-referential arguments, derived + // from the slice-agreement hypothesis; reused inside every pattern subproof. + val sliceAgreement = caseEqs.sliceAgreement + val selfArgEqualities = sc.selfRefVariables2.map(v => + val vInHeight = have(v ∈ app(heightFun)(currentIndex)) by Weakening(argsTypedAtHeight) + agreementAt(heightFun, currentIndex, caseEqs.sliceLeft, caseEqs.sliceRight, sliceAgreement, v, vInHeight) + ) + + // The per-pattern agreement proof, shared between the witness and uniqueness + // steps; only `caseEqs.caseEquation` (how `goalFun * input === body` is obtained + // for each side) is function-specific. + val rawEqFor = (pattern: Clause[Expr[Ind]]) => + have(pattern.branchSelectionBody(ambientTerm) |- goalEqAt) subproof { + val selectedPattern = assume(pattern.branchSelectionBody(ambientTerm)) + val patternGuard = have(pattern.freshBranchCondition) by Weakening(selectedPattern) + val inputEq = have(ambientTerm === pattern.freshInputTerm) by Weakening(selectedPattern) + have(pattern.freshTypingFormula) by Tautology.from(argsTypedSemantic) + val patternPremiseConj = have(pattern.freshTypingFormula /\ pattern.freshBranchCondition) by + RightAnd(lastStep, patternGuard) + val patternPremise = have(pattern.freshBranchPremise) by Weakening(patternPremiseConj) + + val innerAgreements = pattern.recursiveAgreementPoints(caseEqs.recursiveType).map { point => + val pointInHeight = pattern.pattern.recursiveAgreementPointInHeight( + target = point, + recursiveType = caseEqs.recursiveType, + heightFun = heightFun, + hValid = hValid, + currentIndex = currentIndex, + currentIndexInN = currentIndexInN, + argsTypedAtHeight = argsTypedAtHeight, + leafTyping = patternPremise, + patternGuard = patternGuard + ) + agreementAt(heightFun, currentIndex, caseEqs.sliceLeft, caseEqs.sliceRight, sliceAgreement, point, pointInHeight) + } + + val bodyEqAssumptions = caseEqs.bodyEqAssumptions(pattern, patternGuard) + val (leftBody, leftEq) = caseEqs.caseEquation(pattern, caseEqs.sliceLeft, patternPremise, patternGuard, bodyEqAssumptions) + val (rightBody, rightEq) = caseEqs.caseEquation(pattern, caseEqs.sliceRight, patternPremise, patternGuard, bodyEqAssumptions) + val bodyEq = LambdaBodyEquality.prove(bodyEqAssumptions, leftBody, rightBody, selfArgEqualities ++ innerAgreements) + val agreement = have((bodyEqAssumptions + pattern.branchSelectionBody(ambientTerm)) |- goalEqAt) by + Congruence.from(inputEq, leftEq, rightEq, bodyEq) + have(thesis) by Restate.from(agreement) + } + + val selectionSchema = patternMatching.branchSelectionFor(c, ambientTerm) + val selectionSchemaInContext = have(selectionSchema.statement.right.head) by + Weakening(selectionSchema) + val selectionAtCtorVars = have( + (wellTypedFormula(sc.semanticSignature2) /\ (ambientTerm === sc.appliedTerm2)) |- + seqOr(constructorPatterns.map(pattern => pattern.branchSelectionDisjunct(ambientTerm))) + ) by InstantiateForallSeq(sc.variables2)(selectionSchemaInContext) + val selectionConjunction = have( + wellTypedFormula(sc.semanticSignature2) /\ (ambientTerm === sc.appliedTerm2) + ) by RightAnd(argsTypedSemantic, aEqApplied) + val selectedBranch = have( + seqOr(constructorPatterns.map(pattern => pattern.branchSelectionDisjunct(ambientTerm))) + ) by Cut(selectionConjunction, selectionAtCtorVars) + + val patternEqualities = constructorPatterns.map { pattern => + val rawEq = rawEqFor(pattern) + pattern.variables2 + .drop(pattern.arity) + .reverse + .foldLeft( + (pattern.branchSelectionBody(ambientTerm), rawEq) + ) { case ((body, _), v) => + val quantified = ∃(v, body) + (quantified, thenHave(quantified |- goalEqAt) by LeftExists) + } + ._2 + } + + val branchesToGoal = + have(selectedBranch.statement.right.head |- goalEqAt) by Tautology.from(patternEqualities*) + + have(goalEqAt) by Cut(selectedBranch, branchesToGoal) + } + + val rawBranch = sc.variables2.reverse.foldLeft(directBranch -> branchPremise) { case ((fact, premise), v) => + val wrappedPremise = ∃(v, premise) + val lifted = have(fact.statement - goalEqAt) by + RightImplies.withParameters(ambientTerm ∈ app(heightFun)(S(currentIndex)), goalEqAt) + } + + have((ambientTerm ∈ app(heightFun)(S(currentIndex))) ==> goalEqAt) by Restate.from(pointwiseAtSucc) + thenHave(∀(ambientTerm ∈ app(heightFun)(S(currentIndex)), goalEqAt)) by RightForall + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/RecFunctionInduction.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/RecFunctionInduction.scala new file mode 100644 index 000000000..c108138dd --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/RecFunctionInduction.scala @@ -0,0 +1,277 @@ +package lisa.maths.SetTheory.Types.ADT.recursion.helpers + +import lisa.maths.SetTheory.Ordinals.Integer.omegaSuccessorInduction +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.encoding._ +import lisa.maths.SetTheory.Types.ADT.recursion.proofs.ConstructorSemanticFacts.specializedConstructors +import lisa.maths.SetTheory.Types.ADT.recursion.proofs.LimitKernel +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.TypeSubstitution +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.specializeTerm +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.semantics.DefinedProperty +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.prooflib.BasicStep.Cut +import lisa.utils.prooflib.BasicStep.LeftExists +import lisa.utils.prooflib.BasicStep.Restate +import lisa.utils.prooflib.BasicStep.Weakening +import lisa.utils.prooflib.Thm + +/** + * Quantified clause formulas paired with their ordered binders. + */ +private[recursion] type PatternSchemas = + Map[Clause[Expr[Ind]], (Seq[Variable[Ind]], Expr[Prop])] + +/** + * Recognizes equality between set-valued expressions. + */ +private[recursion] def asIndEquality(formula: Expr[Prop]): Option[(Expr[Ind], Expr[Ind])] = formula match + case App(App(eqFun, lhs: Expr[Ind]), rhs: Expr[Ind]) if eqFun == equality => Some((lhs, rhs)) + case _ => None + +private[recursion] object RecFunctionInduction { + + private inline def app(f: Expr[Ind])(x: Expr[Ind]): Expr[Ind] = + lisa.maths.SetTheory.Functions.Predef.app(f)(x) + + private def requireSchemaCoverage( + patternMatching: PatternSystem[Expr[Ind]], + schemas: PatternSchemas, + schemaLabel: String + ): Unit = { + val expectedPatterns = patternMatching.clauses.toSet + require( + schemas.keySet == expectedPatterns, + s"$schemaLabel: pattern schemas do not cover the pattern system." + ) + patternMatching.clauses.foreach(pattern => + val (vars, _) = schemas(pattern) + require( + vars.length == pattern.binders.length, + s"$schemaLabel: pattern schema for ${pattern.name} has arity ${vars.length}, expected ${pattern.binders.length}." + ) + ) + } + + private def caseEqualityAtBranch(using + proof: lisa.SetTheoryLibrary.Proof + )( + contextAssumptions: Set[Expr[Prop]], + definition: Expr[Prop], + schema: (Seq[Variable[Ind]], Expr[Prop]), + branchVars: Seq[Variable[Ind]], + branchPremise: Thm, + defUnfold: Thm, + functionHead: Expr[Ind], + inputTerm: Expr[Ind], + errorContext: String + ): (Expr[Ind], Thm) = { + val (caseVars, caseSchemaFormula) = schema + // Unfold the defining predicate only for this clause, keeping the other assumptions atomic. + val definitionFact = have(contextAssumptions |- definition) by Weakening(defUnfold) + val schemaFromDefinition = have(definition |- caseSchemaFormula) by Tautology + val caseSchema = have(contextAssumptions |- caseSchemaFormula) by + Cut.withParameters(definition)(definitionFact, schemaFromDefinition) + + require( + caseVars.length == branchVars.length, + s"$errorContext: schema arity mismatch (${caseVars.length} vs ${branchVars.length})." + ) + + val schemaAtBranch = branchVars.foldLeft(caseSchema) { (fact, argument) => + fact.statement.right.head match + case forall(v, phi) => + val instantiated = phi.substitute(v := argument) + have(fact.statement.left |- instantiated) by InstantiateForall(argument)(fact) + case _ => throw UnreachableException + } + val atBranch = schemaAtBranch.statement.right.head match + case antecedent ==> consequent => + require( + simplify(antecedent) == simplify(branchPremise.statement.right.head), + s"$errorContext: schema antecedent does not match branch premise." + ) + + val premiseAsAnte = have(branchPremise.statement.left |- antecedent) by Restate.from(branchPremise) + val viaImpl = have((schemaAtBranch.statement.left + antecedent) |- consequent) by Weakening(schemaAtBranch) + val combined = have((schemaAtBranch.statement.left ++ branchPremise.statement.left) |- consequent) by Cut(premiseAsAnte, viaImpl) + have(contextAssumptions |- consequent) by Weakening(combined) + case equalityFormula => + have(contextAssumptions |- equalityFormula) by Restate.from(schemaAtBranch) + + val applied = functionHead * inputTerm + asIndEquality(atBranch.statement.right.head) match + case Some((lhs, rhs)) if lhs == applied => + (rhs, atBranch) + case Some((lhs, rhs)) if rhs == applied => + (lhs, have(atBranch.statement.left |- (applied === lhs)) by Congruence.from(atBranch)) + case _ => + throw IllegalArgumentException( + s"$errorContext: expected an equality with `$applied` on one side, got ${atBranch.statement.right.head}." + ) + } + + /** + * Proves pointwise equality from two instances of the defining property by height induction. + */ + def pointwiseUniquenessAt( + adt: SemanticADT, + patternMatching: PatternSystem[Expr[Ind]], + argType: Expr[Ind], + typeSubstitutions: Seq[TypeSubstitution], + inductionVariable: Variable[Ind], + assumptions: Set[Expr[Prop]], + propertyAt: Expr[Ind] => Expr[Prop], + xFun: Expr[Ind], + yFun: Expr[Ind], + xDefinitionFormula: Expr[Prop], + yDefinitionFormula: Expr[Prop], + xPatternSchemas: PatternSchemas, + yPatternSchemas: PatternSchemas, + definitionProperty: DefinedProperty + ): Theorem = { + requireSchemaCoverage(patternMatching, xPatternSchemas, "pointwiseUniquenessAt/x") + requireSchemaCoverage(patternMatching, yPatternSchemas, "pointwiseUniquenessAt/y") + + val pointwiseGoal = ∀(inductionVariable, inductionVariable ∈ argType ==> propertyAt(inductionVariable)) + + Lemma.generated(assumptions |- pointwiseGoal) { + // Keep the defining hypotheses available in nested branch proofs. + assumptions.foreach(a => assume(a)) + val heightFun = specializeTerm(adt.height.function, typeSubstitutions) + val constructorsAt = specializedConstructors(patternMatching, typeSubstitutions) + val reserved: Seq[Expr[?]] = + Seq(argType, heightFun, inductionVariable, pointwiseGoal, xFun, yFun, xDefinitionFormula, yDefinitionFormula) ++ assumptions ++ + patternMatching.clauses.flatMap(pattern => Seq(pattern.body, pattern.freshBranchPremise, pattern.freshInputTerm) ++ pattern.binders ++ pattern.variables2) + val nVar = Variable[Ind](freshId(reserved, "nVar")) + val slicePoint = inductionVariable + val P = λ(nVar, ∀(slicePoint ∈ app(heightFun)(nVar), propertyAt(slicePoint))) + + val hValid = have(adt.height.predicateAt(typeSubstitutions)(heightFun)) by + Weakening(adt.height.validAt(typeSubstitutions)) + + val noElemAtEmpty = have(!(slicePoint ∈ app(heightFun)(∅))) by Cut( + hValid, + adt.height.zeroAt(typeSubstitutions, Seq(h := heightFun, x := slicePoint)) + ) + + val base = have(P(∅)) subproof { + have(slicePoint ∈ app(heightFun)(∅) |- propertyAt(slicePoint)) by + Tautology.from(noElemAtEmpty) + thenHave((slicePoint ∈ app(heightFun)(∅)) ==> propertyAt(slicePoint)) by RightImplies + thenHave(∀(slicePoint, (slicePoint ∈ app(heightFun)(∅)) ==> propertyAt(slicePoint))) by RightForall + thenHave(thesis) by Restate + } + + val step = { + have((nVar ∈ N) ==> (P(nVar) ==> P(S(nVar)))) subproof { + val nInN = assume(nVar ∈ N) + assume(P(nVar)) + // Reuse branch assembly, supplying each candidate's defining equation. + PointwiseAgreementStep.pointwiseAgreementOnSucc( + patternMatching = patternMatching, + heightFun = heightFun, + constructorsAt = constructorsAt, + ambientTerm = slicePoint, + currentIndex = nVar, + currentIndexInN = nInN, + hValid = hValid, + heightSuccStrong = adt.height.successorStrongAt(typeSubstitutions, Seq(h := heightFun, n := nVar, x := slicePoint)), + goalEqAt = propertyAt(slicePoint) + )(new PointwiseAgreementStep.PatternCaseEquations { + val recursiveType: Expr[Ind] = argType + val sliceLeft: Expr[Ind] = xFun + val sliceRight: Expr[Ind] = yFun + + // This callback runs inside a nested branch proof. + def sliceAgreement(using proof: lisa.SetTheoryLibrary.Proof): Thm = + have( + ∀(slicePoint, (slicePoint ∈ app(heightFun)(nVar)) ==> propertyAt(slicePoint)) + ) by Restate.from(assume(P(nVar))) + + def bodyEqAssumptions(using + proof: lisa.SetTheoryLibrary.Proof + )( + pattern: Clause[Expr[Ind]], + patternGuard: Thm + ): Set[Expr[Prop]] = { + val baseContext = Set[Expr[Prop]]( + slicePoint ∈ app(heightFun)(S(nVar)), + P(nVar), + nVar ∈ N, + pattern.branchSelectionBody(slicePoint) + ) + if simplify(pattern.freshBranchCondition) == ⊤ then baseContext + else baseContext + pattern.freshBranchCondition + } + + def caseEquation(using + proof: lisa.SetTheoryLibrary.Proof + )( + pattern: Clause[Expr[Ind]], + slice: Expr[Ind], + patternPremise: Thm, + patternGuard: Thm, + bodyEqAssumptions: Set[Expr[Prop]] + ): (Expr[Ind], Thm) = { + val (definition, schema, side) = + if (slice == xFun) then (xDefinitionFormula, xPatternSchemas(pattern), "x") + else (yDefinitionFormula, yPatternSchemas(pattern), "y") + caseEqualityAtBranch( + contextAssumptions = assumptions ++ bodyEqAssumptions, + definition = definition, + schema = schema, + branchVars = pattern.variables2, + branchPremise = patternPremise, + defUnfold = definitionProperty.unfoldAt(slice), + functionHead = slice, + inputTerm = pattern.freshInputTerm, + errorContext = s"pointwiseUniquenessAt/$side/${pattern.name}" + ) + } + }) + } + thenHave(∀(nVar, (nVar ∈ N) ==> (P(nVar) ==> P(S(nVar))))) by RightForall + + } + + val theoremP = variable[Ind >>: Prop]("P") + val allHeights = have(∀(nVar, (nVar ∈ N) ==> P(nVar))) by + Tautology.from(omegaSuccessorInduction of (theoremP := P, m := nVar, n := nVar), base, step) + have(inductionVariable ∈ argType ==> propertyAt(inductionVariable)) subproof { + val inArg = assume(inductionVariable ∈ argType) + val someHeight = have(∃(nVar, (nVar ∈ N) /\ (inductionVariable ∈ app(heightFun)(nVar)))) by + Tautology.from( + hValid, + inArg, + adt.height.termHasHeightAt(typeSubstitutions, Seq(x := inductionVariable, h := heightFun)), + LimitKernel.pointHasSomeHeightAt(argType, heightFun, inductionVariable) + ) + + have((nVar ∈ N) /\ (inductionVariable ∈ app(heightFun)(nVar)) |- propertyAt(inductionVariable)) subproof { + assume((nVar ∈ N) /\ (inductionVariable ∈ app(heightFun)(nVar))) + val nInN = have(nVar ∈ N) by Tautology + val pointInHeight = have(inductionVariable ∈ app(heightFun)(nVar)) by Tautology + val sliceAgreement = have(P(nVar)) by Tautology.from( + nInN, + have(nVar ∈ N ==> P(nVar)) by InstantiateForall(nVar)(allHeights) + ) + val agreementAtN = have((inductionVariable ∈ app(heightFun)(nVar)) ==> propertyAt(inductionVariable)) by + InstantiateForall(inductionVariable)( + have(∀(slicePoint, (slicePoint ∈ app(heightFun)(nVar)) ==> propertyAt(slicePoint))) by + Restate.from(sliceAgreement) + ) + have(propertyAt(inductionVariable)) by Tautology.from(nInN, pointInHeight, agreementAtN) + } + val fromExists = thenHave(∃(nVar, (nVar ∈ N) /\ (inductionVariable ∈ app(heightFun)(nVar))) |- propertyAt(inductionVariable)) by + LeftExists + have(propertyAt(inductionVariable)) by Cut(someHeight, fromExists) + } + thenHave(∀(inductionVariable, inductionVariable ∈ argType ==> propertyAt(inductionVariable))) by RightForall + thenHave(thesis) by Restate + } + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/WitnessAgreement.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/WitnessAgreement.scala new file mode 100644 index 000000000..61e4fb0c2 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/helpers/WitnessAgreement.scala @@ -0,0 +1,175 @@ +package lisa.maths.SetTheory.Types.ADT.recursion.helpers + +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.recursion.FunSpec +import lisa.maths.SetTheory.Types.ADT.recursion.Witness +import lisa.maths.SetTheory.Types.ADT.recursion.proofs.ConstructorSemanticFacts.specializedConstructors +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.prooflib.BasicStep.Cut +import lisa.utils.prooflib.BasicStep.Weakening +import lisa.utils.prooflib.InstantiateForallSeq +import lisa.utils.prooflib.Thm + +private[recursion] final class WitnessAgreement( + val spec: FunSpec, + val recWitness: Witness +) { + + private val leftFun = spec.proofVariable("leftFun") + private val rightFun = spec.proofVariable("rightFun") + private val nVar = spec.proofVariable("nVar") + private val vVar = spec.proofVariable("vVar") + private val a = spec.proofVariable("a") + + private val heightFun: Expr[Ind] = spec.heightFun + private def heightFunValid(using proof: lisa.SetTheoryLibrary.Proof): Thm = spec.heightFunValid + private val constructorsAt = specializedConstructors(spec.patternMatching, spec.typeSubstitutions) + + private val agreeOnSlice = ∀(vVar ∈ app(heightFun)(nVar), app(leftFun)(vVar) === app(rightFun)(vVar)) + + private val witnessAgreementAtSucc: Theorem = ( + Lemma.generated( + ( + leftFun :: spec.typ, + rightFun :: spec.typ, + nVar ∈ N, + agreeOnSlice + ) |- ∀(a ∈ app(heightFun)(S(nVar)), app(recWitness(leftFun))(a) === app(recWitness(rightFun))(a)) + ) { + have(thesis) subproof { + assume(leftFun :: spec.typ) + assume(rightFun :: spec.typ) + val nInN = assume(nVar ∈ N) + assume(agreeOnSlice) + + val hValid = have(spec.isHeightPred(heightFun)) by Weakening(heightFunValid) + + val goalW = app(recWitness(leftFun))(a) === app(recWitness(rightFun))(a) + + // Orchestration (height decomposition + branch selection + per-pattern assembly) + // is shared with the uniqueness step via PointwiseAgreementStep; only the + // witness-specific case equation `recWitness(slice) * input === body` is supplied + // here, via the [[PatternCaseEquations]] callback below. + val agreementAtSucc = PointwiseAgreementStep.pointwiseAgreementOnSucc( + patternMatching = spec.patternMatching, + heightFun = heightFun, + constructorsAt = constructorsAt, + ambientTerm = a, + currentIndex = nVar, + currentIndexInN = nInN, + hValid = hValid, + heightSuccStrong = spec.adt.height.successorStrongAt(spec.typeSubstitutions, Seq(h := heightFun, n := nVar, x := a)), + goalEqAt = goalW + )(new PointwiseAgreementStep.PatternCaseEquations { + val recursiveType: Expr[Ind] = spec.argType + val sliceLeft: Expr[Ind] = leftFun + val sliceRight: Expr[Ind] = rightFun + + // Each method re-`assume`s the ambient hypotheses (idempotent) since it runs in a + // nested proof, not the enclosing lemma proof. + def sliceAgreement(using proof: lisa.SetTheoryLibrary.Proof): Thm = + have( + ∀(vVar, (vVar ∈ app(heightFun)(nVar)) ==> (app(leftFun)(vVar) === app(rightFun)(vVar))) + ) by Restate.from(assume(agreeOnSlice)) + + // Witness case equations carry their own contexts, so body equality needs no extra + // ambient assumptions. + def bodyEqAssumptions(using + proof: lisa.SetTheoryLibrary.Proof + )( + pattern: Clause[Expr[Ind]], + patternGuard: Thm + ): Set[Expr[Prop]] = Set.empty + + def caseEquation(using + proof: lisa.SetTheoryLibrary.Proof + )( + pattern: Clause[Expr[Ind]], + slice: Expr[Ind], + patternPremise: Thm, + patternGuard: Thm, + bodyEqAssumptions: Set[Expr[Prop]] + ): (Expr[Ind], Thm) = { + val selfTyped = assume(slice :: spec.typ) + val body = pattern.body + .substitute(spec.selfPlaceholder := slice) + .substitute(pattern.binders.zip(pattern.variables2).map((from, to) => from := to)*) + + val witnessSchema = recWitness.witnessCase(pattern).of(spec.selfPlaceholder := slice) + val witnessBase = witnessSchema.statement.right.head match + case _ ==> consequent => + have(consequent) by Tautology.from(witnessSchema, selfTyped) + case _ => throw UnreachableException + + val witnessAtVars = have( + pattern.freshBranchPremise ==> (recWitness(slice) * pattern.freshInputTerm === body) + ) by InstantiateForallSeq(pattern.variables2)(witnessBase) + + val instantiateWitness = witnessAtVars.statement.right.head match + case _ ==> consequent => + val premise = pattern.freshBranchPremise + val viaImpl = have((witnessAtVars.statement.left + premise) |- consequent) by + Weakening(witnessAtVars) + have((witnessAtVars.statement.left ++ patternPremise.statement.left) |- consequent) by + Cut(patternPremise, viaImpl) + case _ => throw UnreachableException + (body, instantiateWitness) + } + }) + + have(thesis) by Restate.from(agreementAtSucc) + } + } + ) + + /** + * Specializes [[witnessAgreementAtSucc]] to the ambient point `a` and chains the + * resulting witness agreement `app(recWitness(lhs))(a) === app(recWitness(rhs))(a)` + * through the caller-supplied `bridges` to prove the equation `goal`. + * + * `goal` is the endpoint equation to prove; `bridges` are the remaining equalities + * that, together with the derived witness agreement, connect its two sides. A + * single `Congruence` closes the chain from those equality facts, so the bridges + * need no particular order or orientation. + * + * This packages both the four-step witness-agreement ritual (instantiate the + * lemma, discharge its premises, instantiate the `∀` at `a`, discharge the height + * membership) and the equational chaining shared by the limit step in `Existence` + * and the successor step in `ApproxStabilization`. + */ + def witnessesAgreeAt(using + proof: lisa.SetTheoryLibrary.Proof + )( + lhs: Expr[Ind], + rhs: Expr[Ind], + index: Expr[Ind], + lhsTyped: Thm, + rhsTyped: Thm, + indexInN: Thm, + sliceAgreement: Thm, + pointInHeightSucc: Thm, + goal: Expr[Prop], + bridges: Seq[Thm] + ): Thm = { + val lemma = witnessAgreementAtSucc.of(leftFun := lhs, rightFun := rhs, nVar := index) + val agreeOnSucc = have(lemma.statement.right.head) by Tautology.from( + lemma, + lhsTyped, + rhsTyped, + indexInN, + sliceAgreement + ) + val impl = have( + (a ∈ app(heightFun)(S(index))) ==> (app(recWitness(lhs))(a) === app(recWitness(rhs))(a)) + ) by InstantiateForall(a)(agreeOnSucc) + val witnessesAgreeAtA = have( + app(recWitness(lhs))(a) === app(recWitness(rhs))(a) + ) by Tautology.from(impl, pointInHeightSucc) + + have(goal) by Congruence.from((bridges :+ witnessesAgreeAtA)*) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ApproximationChainFacts.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ApproximationChainFacts.scala new file mode 100644 index 000000000..f2305b8b2 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ApproximationChainFacts.scala @@ -0,0 +1,349 @@ +package lisa.maths.SetTheory.Types.ADT.recursion.proofs + +import lisa.maths.SetTheory.Base.Subset +import lisa.maths.SetTheory.Base.Union +import lisa.maths.SetTheory.Base.Union.∪ +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Ordinals.Integer.omegaSuccessorInduction +import lisa.maths.SetTheory.Ordinals.Integer.subsetBelowSucc +import lisa.maths.SetTheory.Ordinals.Integer.unionInOmega +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.proofs.PropositionalFacts.altEqualityTransitivity +import lisa.maths.SetTheory.Types.ADT.support.proofs.PropositionalFacts.equivalenceApply +import lisa.utils.fol.FOL.SubstPair +import lisa.utils.prooflib.BasicStep.Cut +import lisa.utils.prooflib.BasicStep.RightForall +import lisa.utils.prooflib.BasicStep.RightImplies +import lisa.utils.prooflib.Thm + +private[recursion] object ApproximationChainFacts { + + private val heightFun = variable[Ind] + private val G = variable[Ind >>: Ind] + + private val nVar = variable[Ind] + private val mVar = variable[Ind] + private val uVar = variable[Ind] + private val upperVar = variable[Ind] + private val lowerVar = variable[Ind] + private val pointVar = variable[Ind] + private val stabVar = variable[Ind] + + private val stabilizationFormula = + ∀(stabVar, (stabVar ∈ N) ==> ∀(pointVar, (pointVar ∈ app(heightFun)(stabVar)) ==> (app(G(stabVar))(pointVar) === app(G(S(stabVar)))(pointVar)))) + + private val heightMembershipMonotonicFormula = + ∀( + upperVar, + (upperVar ∈ N) ==> ∀(lowerVar, (lowerVar ∈ N) ==> ∀(pointVar, (pointVar ∈ app(heightFun)(lowerVar)) ==> ((lowerVar ⊆ upperVar) ==> (pointVar ∈ app(heightFun)(upperVar))))) + ) + + private[proofs] def stabilizationSchema(heightFun0: Expr[Ind], G0: Expr[Ind >>: Ind]): Expr[Prop] = + stabilizationFormula.substitute(heightFun := heightFun0, G := G0) + + private[proofs] def heightMembershipMonotonicSchema(heightFun0: Expr[Ind]): Expr[Prop] = + heightMembershipMonotonicFormula.substitute(heightFun := heightFun0) + + private val approximantsAgreeFromSubset: Theorem = ( + Lemma( + ( + stabilizationSchema(heightFun, G), + heightMembershipMonotonicSchema(heightFun), + nVar ∈ N, + mVar ∈ N, + nVar ⊆ mVar, + a ∈ app(heightFun)(nVar) + ) |- app(G(nVar))(a) === app(G(mVar))(a) + ) { + val stabilization = assume(stabilizationSchema(heightFun, G)) + val heightMonotonic = assume(heightMembershipMonotonicSchema(heightFun)) + val nInN = assume(nVar ∈ N) + val mInN = assume(mVar ∈ N) + val nSubM = assume(nVar ⊆ mVar) + val aInHn = assume(a ∈ app(heightFun)(nVar)) + + val propM = λ( + uVar, + (nVar ⊆ uVar) ==> ( + (a ∈ app(heightFun)(nVar)) ==> (app(G(nVar))(a) === app(G(uVar))(a)) + ) + ) + + val base = have(propM(∅)) subproof { + have((nVar ⊆ ∅) ==> ((a ∈ app(heightFun)(nVar)) ==> (app(G(nVar))(a) === app(G(∅))(a)))) subproof { + val nSubEmpty = assume(nVar ⊆ ∅) + + have(nVar === ∅) by Tautology.from( + nSubEmpty, + Subset.rightEmpty of (x := nVar), + equivalenceApply of (p1 := nVar ⊆ ∅, p2 := nVar === ∅) + ) + thenHave(nVar === ∅) by Restate + thenHave(app(G(nVar))(a) === app(G(∅))(a)) by Congruence + thenHave(thesis) by Restate + } + thenHave(thesis) by Restate + } + + val step = have(∀(uVar, (uVar ∈ N) ==> (propM(uVar) ==> propM(S(uVar))))) subproof { + have((uVar ∈ N) ==> (propM(uVar) ==> propM(S(uVar)))) subproof { + val uInNStep = assume(uVar ∈ N) + val ih = assume(propM(uVar)) + + val goalAtSucc = have(propM(S(uVar))) subproof { + have( + (nVar ⊆ S(uVar)) ==> ( + (a ∈ app(heightFun)(nVar)) ==> (app(G(nVar))(a) === app(G(S(uVar)))(a)) + ) + ) subproof { + val nSubSuccU = assume(nVar ⊆ S(uVar)) + val aInHeightN = assume(a ∈ app(heightFun)(nVar)) + + val split = have((nVar === S(uVar)) \/ (nVar ⊆ uVar)) by Tautology.from( + nInN, + uInNStep, + nSubSuccU, + subsetBelowSucc.of(m := nVar, n := uVar) + ) + + val caseEq = have( + nVar === S(uVar) |- app(G(nVar))(a) === app(G(S(uVar)))(a) + ) by Congruence + + val caseSub = have( + nVar ⊆ uVar |- app(G(nVar))(a) === app(G(S(uVar)))(a) + ) subproof { + val nSubUCase = assume(nVar ⊆ uVar) + val eqNu = have(app(G(nVar))(a) === app(G(uVar))(a)) by Tautology.from( + ih, + nSubUCase, + aInHeightN + ) + + val heightMonoAtUpper = have( + (uVar ∈ N) ==> ∀(lowerVar, (lowerVar ∈ N) ==> ∀(pointVar, (pointVar ∈ app(heightFun)(lowerVar)) ==> ((lowerVar ⊆ uVar) ==> (pointVar ∈ app(heightFun)(uVar))))) + ) by InstantiateForall(uVar)(heightMonotonic) + val heightMonoUpper = have( + ∀(lowerVar, (lowerVar ∈ N) ==> ∀(pointVar, (pointVar ∈ app(heightFun)(lowerVar)) ==> ((lowerVar ⊆ uVar) ==> (pointVar ∈ app(heightFun)(uVar))))) + ) by Tautology.from(uInNStep, heightMonoAtUpper) + val heightMonoAtNInst = have( + (nVar ∈ N) ==> ∀(pointVar, (pointVar ∈ app(heightFun)(nVar)) ==> ((nVar ⊆ uVar) ==> (pointVar ∈ app(heightFun)(uVar)))) + ) by InstantiateForall(nVar)(heightMonoUpper) + val heightMonoAtPoint = have( + ∀(pointVar, (pointVar ∈ app(heightFun)(nVar)) ==> ((nVar ⊆ uVar) ==> (pointVar ∈ app(heightFun)(uVar)))) + ) by Tautology.from(nInN, heightMonoAtNInst) + val heightMonoAtA = have( + (a ∈ app(heightFun)(nVar)) ==> ((nVar ⊆ uVar) ==> (a ∈ app(heightFun)(uVar))) + ) by InstantiateForall(a)(heightMonoAtPoint) + + val aInHu = have(a ∈ app(heightFun)(uVar)) by Tautology.from( + aInHeightN, + nSubUCase, + heightMonoAtA + ) + + val stabAtU = have( + (uVar ∈ N) ==> ∀(pointVar, (pointVar ∈ app(heightFun)(uVar)) ==> (app(G(uVar))(pointVar) === app(G(S(uVar)))(pointVar))) + ) by InstantiateForall(uVar)(stabilization) + val stabU = have( + ∀(pointVar, (pointVar ∈ app(heightFun)(uVar)) ==> (app(G(uVar))(pointVar) === app(G(S(uVar)))(pointVar))) + ) by Tautology.from(uInNStep, stabAtU) + val stabAtA = have( + (a ∈ app(heightFun)(uVar)) ==> (app(G(uVar))(a) === app(G(S(uVar)))(a)) + ) by InstantiateForall(a)(stabU) + val eqUSu = have(app(G(uVar))(a) === app(G(S(uVar)))(a)) by + Tautology.from(aInHu, stabAtA) + + have(thesis) by Tautology.from( + altEqualityTransitivity of ( + x := app(G(nVar))(a), + y := app(G(uVar))(a), + z := app(G(S(uVar)))(a) + ), + eqNu, + eqUSu + ) + } + + have(app(G(nVar))(a) === app(G(S(uVar)))(a)) by + Tautology.from(split, caseEq, caseSub) + have( + (a ∈ app(heightFun)(nVar)) ==> (app(G(nVar))(a) === app(G(S(uVar)))(a)) + ) by Tautology.from(lastStep) + thenHave(thesis) by Restate + } + thenHave(thesis) by Restate + } + + val imp = have(propM(uVar) ==> propM(S(uVar))) by Tautology.from(goalAtSucc) + have(thesis) by Tautology.from(imp) + } + thenHave(thesis) by RightForall + } + + val P = variable[Ind >>: Prop] + val indInst = have( + (propM(∅), ∀(uVar, (uVar ∈ N) ==> (propM(uVar) ==> propM(S(uVar))))) |- + ∀(uVar, (uVar ∈ N) ==> propM(uVar)) + ) by Weakening(omegaSuccessorInduction of (P := propM)) + val all = have(∀(uVar, (uVar ∈ N) ==> propM(uVar))) by + Tautology.from(base, step, indInst) + val atM = have(mVar ∈ N ==> propM(mVar)) by InstantiateForall(mVar)(all) + val propAtM = have(propM(mVar)) by Tautology.from(mInN, atM) + + have(app(G(nVar))(a) === app(G(mVar))(a)) by Tautology.from(propAtM, nSubM, aInHn) + thenHave(thesis) by Restate + } + ) + + private[proofs] val approximantsAgreeAcrossHeights: Theorem = ( + Lemma( + ( + stabilizationSchema(heightFun, G), + heightMembershipMonotonicSchema(heightFun), + nVar ∈ N, + mVar ∈ N, + a ∈ app(heightFun)(nVar), + a ∈ app(heightFun)(mVar) + ) |- app(G(nVar))(a) === app(G(mVar))(a) + ) { + val stabilization = assume(stabilizationSchema(heightFun, G)) + val heightMonotonic = assume(heightMembershipMonotonicSchema(heightFun)) + val nInN = assume(nVar ∈ N) + val mInN = assume(mVar ∈ N) + val aInHn = assume(a ∈ app(heightFun)(nVar)) + val aInHm = assume(a ∈ app(heightFun)(mVar)) + + val upperInN = have((nVar ∪ mVar) ∈ N) by Tautology.from( + nInN, + mInN, + unionInOmega.of(a := nVar, b := mVar) + ) + + val nSubUpper = have(nVar ⊆ (nVar ∪ mVar)) by + Tautology.from(Union.leftSubset of (x := nVar, y := mVar)) + val mSubUpper = have(mVar ⊆ (nVar ∪ mVar)) by + Tautology.from(Union.rightSubset of (x := nVar, y := mVar)) + + val eqNUpper = have(app(G(nVar))(a) === app(G(nVar ∪ mVar))(a)) by Tautology.from( + stabilization, + heightMonotonic, + nInN, + upperInN, + nSubUpper, + aInHn, + approximantsAgreeFromSubset.of(nVar := nVar, mVar := nVar ∪ mVar) + ) + val eqMUpper = have(app(G(mVar))(a) === app(G(nVar ∪ mVar))(a)) by Tautology.from( + stabilization, + heightMonotonic, + mInN, + upperInN, + mSubUpper, + aInHm, + approximantsAgreeFromSubset.of(nVar := mVar, mVar := nVar ∪ mVar) + ) + val eqUpperM = have(app(G(nVar ∪ mVar))(a) === app(G(mVar))(a)) by + Congruence.from(eqMUpper) + + have(app(G(nVar))(a) === app(G(mVar))(a)) by Tautology.from( + altEqualityTransitivity of ( + x := app(G(nVar))(a), + y := app(G(nVar ∪ mVar))(a), + z := app(G(mVar))(a) + ), + eqNUpper, + eqUpperM + ) + thenHave(thesis) by Restate + } + ) + + private[proofs] def heightMembershipMonotonicSchemaAt(using + proof: lisa.SetTheoryLibrary.Proof + )( + heightFun0: Expr[Ind], + heightMembershipMonotonic0: Seq[SubstPair] => Thm, + isHeightPredFact: Thm + ): Thm = { + val context = Seq(heightFun0) ++ isHeightPredFact.statement.left ++ isHeightPredFact.statement.right + val upperVar = Variable[Ind](freshId(context, "upperVar")) + val lowerVar = Variable[Ind](freshId(context, "lowerVar")) + val pointVar = Variable[Ind](freshId(context, "pointVar")) + val monoAtVars = have( + (upperVar ∈ N, lowerVar ∈ N, lowerVar ⊆ upperVar, pointVar ∈ app(heightFun0)(lowerVar)) |- pointVar ∈ app(heightFun0)(upperVar) + ) by Cut( + isHeightPredFact, + heightMembershipMonotonic0(Seq(h := heightFun0, n := upperVar, m := lowerVar, x := pointVar)) + ) + + val monoImp = have( + (upperVar ∈ N, lowerVar ∈ N, pointVar ∈ app(heightFun0)(lowerVar)) |- (lowerVar ⊆ upperVar) ==> (pointVar ∈ app(heightFun0)(upperVar)) + ) by RightImplies(monoAtVars) + + val monoPointImp = have( + (upperVar ∈ N, lowerVar ∈ N) |- (pointVar ∈ app(heightFun0)(lowerVar)) ==> ((lowerVar ⊆ upperVar) ==> (pointVar ∈ app(heightFun0)(upperVar))) + ) by RightImplies(monoImp) + + val monoForallA = have( + (upperVar ∈ N, lowerVar ∈ N) |- ∀(pointVar, (pointVar ∈ app(heightFun0)(lowerVar)) ==> ((lowerVar ⊆ upperVar) ==> (pointVar ∈ app(heightFun0)(upperVar)))) + ) by RightForall(monoPointImp) + + val monoImpM = have( + (upperVar ∈ N) |- (lowerVar ∈ N) ==> ∀(pointVar, (pointVar ∈ app(heightFun0)(lowerVar)) ==> ((lowerVar ⊆ upperVar) ==> (pointVar ∈ app(heightFun0)(upperVar)))) + ) by RightImplies(monoForallA) + + val monoForallM = have( + (upperVar ∈ N) |- ∀(lowerVar, (lowerVar ∈ N) ==> ∀(pointVar, (pointVar ∈ app(heightFun0)(lowerVar)) ==> ((lowerVar ⊆ upperVar) ==> (pointVar ∈ app(heightFun0)(upperVar))))) + ) by RightForall(monoImpM) + + val monoImpU = have( + (upperVar ∈ N) ==> ∀(lowerVar, (lowerVar ∈ N) ==> ∀(pointVar, (pointVar ∈ app(heightFun0)(lowerVar)) ==> ((lowerVar ⊆ upperVar) ==> (pointVar ∈ app(heightFun0)(upperVar))))) + ) by RightImplies(monoForallM) + + have(heightMembershipMonotonicSchema(heightFun0)) by RightForall(monoImpU) + } + + def approximantsAgreeFromSubsetAt(using + proof: lisa.SetTheoryLibrary.Proof + )( + heightFun0: Expr[Ind], + G0: Expr[Ind >>: Ind], + n0: Expr[Ind], + m0: Expr[Ind], + point0: Expr[Ind], + stabilization0: Thm, + heightMembershipMonotonic: Seq[SubstPair] => Thm, + heightFunValid: Thm + ): Thm = + val heightMembershipMonotonic0 = heightMembershipMonotonicSchemaAt( + heightFun0, + heightMembershipMonotonic, + heightFunValid + ) + have( + (n0 ∈ N, m0 ∈ N, n0 ⊆ m0, point0 ∈ app(heightFun0)(n0)) |- app(G0(n0))(point0) === app(G0(m0))(point0) + ) by Tautology.from( + stabilization0, + heightMembershipMonotonic0, + approximantsAgreeFromSubset.of(heightFun := heightFun0, G := G0, nVar := n0, mVar := m0, a := point0) + ) + + def approximantsAgreeAcrossHeightsAt(using + proof: lisa.SetTheoryLibrary.Proof + )( + heightFun0: Expr[Ind], + G0: Expr[Ind >>: Ind], + n0: Expr[Ind], + m0: Expr[Ind], + point0: Expr[Ind] + ): Thm = + approximantsAgreeAcrossHeights.of(heightFun := heightFun0, G := G0, nVar := n0, mVar := m0, a := point0) + + def initialize(): Unit = { + val _ = approximantsAgreeFromSubset + val _ = approximantsAgreeAcrossHeights + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ConstructorSemanticFacts.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ConstructorSemanticFacts.scala new file mode 100644 index 000000000..7cbdd0308 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ConstructorSemanticFacts.scala @@ -0,0 +1,61 @@ +package lisa.maths.SetTheory.Types.ADT.recursion.proofs + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.encoding.SemanticConstructor +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.TypeSubstitution +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.instantiatedSemanticSignature +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.utils.prooflib.Thm + +private[recursion] object ConstructorSemanticFacts { + + final case class SpecializedConstructorFacts( + underlying: SemanticConstructor, + typeSubstitutions: Seq[TypeSubstitution], + variables2: Seq[Variable[Ind]] + ) { + private val heightArgument = Variable[Ind](freshId(underlying.typeVariablesSeq ++ underlying.variables2, s"${underlying.fullName}/heightArgument")) + private val termArgument = Variable[Ind](freshId(underlying.typeVariablesSeq ++ underlying.variables2 :+ heightArgument, s"${underlying.fullName}/termArgument")) + private val substitutions = typeSubstitutions ++ underlying.variables2.zip(variables2).map((from, to) => from := to) + + def name: String = underlying.name + def selfRefVariables2: Seq[Variable[Ind]] = underlying.recursiveBinders(variables2) + def semanticSignature2: Seq[(Variable[Ind], Expr[Ind])] = + instantiatedSemanticSignature(underlying.semanticSignature(variables2), typeSubstitutions) + def heightTypingFormula(heightSet: Expr[Ind]): Expr[Prop] = + underlying.heightTypingFormula(heightArgument).substitute((substitutions :+ (heightArgument := heightSet))*) + def branchPremiseAtHeight(heightSet: Expr[Ind], term: Expr[Ind]): Expr[Prop] = + underlying.branchPremiseAtHeight(heightArgument, termArgument).substitute((substitutions ++ Seq(heightArgument := heightSet, termArgument := term))*) + def branchAtHeight(heightSet: Expr[Ind], term: Expr[Ind]): Expr[Prop] = + existsSeq(variables2, branchPremiseAtHeight(heightSet, term)) + def appliedTerm2: Expr[Ind] = + underlying.appliedTerm2.substitute(substitutions*) + def semanticTypingFromHeight(heightFun: Expr[Ind], n: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + underlying.semanticTypingFromHeightAt(typeSubstitutions, variables2)(heightFun, n) + def appliedEqualityFromStructural(heightFun: Expr[Ind], n: Expr[Ind], term0: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + underlying.appliedEqualityFromStructuralAt(typeSubstitutions, variables2)(heightFun, n, term0) + } + + def specializedConstructors( + patterns: PatternSystem[?], + typeSubstitutions: Seq[TypeSubstitution] + ): Seq[SpecializedConstructorFacts] = + patterns.constructors.map { constructor => + SpecializedConstructorFacts(constructor, typeSubstitutions, patterns.clausesFor(constructor).head.variables2.take(constructor.arity)) + } + + def constructorBranchAtHeight( + c: SpecializedConstructorFacts, + heightSet: Expr[Ind], + term: Expr[Ind] + ): Expr[Prop] = + c.branchAtHeight(heightSet, term) + + def constructorDisjunctionAtHeight( + constructors: Seq[SpecializedConstructorFacts], + heightSet: Expr[Ind], + term: Expr[Ind] + ): Expr[Prop] = + seqOr(constructors.map(c => constructorBranchAtHeight(c, heightSet, term))) +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/LimitKernel.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/LimitKernel.scala new file mode 100644 index 000000000..ebbcae054 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/LimitKernel.scala @@ -0,0 +1,281 @@ +package lisa.maths.SetTheory.Types.ADT.recursion.proofs + +import lisa.maths.Quantifiers +import lisa.maths.SetTheory.Functions.Function.abs +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.support.proofs.PropositionalFacts.altEqualityTransitivity +import lisa.maths.SetTheory.Types.TypingRules.BetaReduction +import lisa.utils.fol.FOL.SubstPair +import lisa.utils.prooflib.Thm + +private[recursion] object LimitKernel { + + private val argType = variable[Ind] + private val heightFun = variable[Ind] + private val limitFun = variable[Ind] + private val G = variable[Ind >>: Ind] + private val limitIndex = variable[Ind >>: Ind] + + private val pointVar = variable[Ind] + private val nVar = variable[Ind] + private val mVar = variable[Ind] + + private val pointHeightFormula = + (pointVar ∈ argType) <=> ∃(nVar, nVar ∈ N /\ pointVar ∈ app(heightFun)(nVar)) + + private val limitIndexFormula = + limitIndex(pointVar) === ε(nVar, (nVar ∈ N) /\ (pointVar ∈ app(heightFun)(nVar))) + + private val limitFunFormula = + limitFun === abs(argType)(λ(pointVar, app(G(limitIndex(pointVar)))(pointVar))) + + def pointHeightCharAt(argType0: Expr[Ind], heightFun0: Expr[Ind], point0: Expr[Ind]): Expr[Prop] = + pointHeightFormula.substitute(argType := argType0, heightFun := heightFun0, pointVar := point0) + + def limitIndexWitnessAt(heightFun0: Expr[Ind], limitIndex0: Expr[Ind >>: Ind], point0: Expr[Ind]): Expr[Prop] = + (limitIndex0(point0) ∈ N) /\ (point0 ∈ app(heightFun0)(limitIndex0(point0))) + + private def limitIndexDefinitionAt(heightFun0: Expr[Ind], limitIndex0: Expr[Ind >>: Ind], point0: Expr[Ind]): Expr[Prop] = + limitIndexFormula.substitute(heightFun := heightFun0, limitIndex := limitIndex0, pointVar := point0) + + def limitFunDefinition( + argType0: Expr[Ind], + limitFun0: Expr[Ind], + G0: Expr[Ind >>: Ind], + limitIndex0: Expr[Ind >>: Ind] + ): Expr[Prop] = + limitFunFormula.substitute(argType := argType0, limitFun := limitFun0, G := G0, limitIndex := limitIndex0) + + private val pointHasSomeHeight: Theorem = Lemma( + (pointHeightCharAt(argType, heightFun, pointVar), pointVar ∈ argType) |- ∃(nVar, (nVar ∈ N) /\ (pointVar ∈ app(heightFun)(nVar))) + ) { + val pointHeightChar = assume(pointHeightCharAt(argType, heightFun, pointVar)) + val pointInArgType = assume(pointVar ∈ argType) + have(thesis) by Tautology.from( + pointInArgType, + pointHeightChar + ) + } + + private val heightMembershipImpliesInArgType: Theorem = Lemma( + (pointHeightCharAt(argType, heightFun, pointVar), nVar ∈ N, pointVar ∈ app(heightFun)(nVar)) |- pointVar ∈ argType + ) { + val pointHeightChar = assume(pointHeightCharAt(argType, heightFun, pointVar)) + val indexInN = assume(nVar ∈ N) + val pointInHeight = assume(pointVar ∈ app(heightFun)(nVar)) + + val pointHasHeight = have( + ∃(mVar, (mVar ∈ N) /\ (pointVar ∈ app(heightFun)(mVar))) + ) subproof { + have((nVar ∈ N) /\ (pointVar ∈ app(heightFun)(nVar))) by Tautology.from(indexInN, pointInHeight) + thenHave(thesis) by RightExists + } + + have(pointVar ∈ argType) by Tautology.from( + pointHasHeight, + pointHeightChar + ) + thenHave(thesis) by Restate + } + + private val limitIndexWitness: Theorem = Lemma( + ( + pointHeightCharAt(argType, heightFun, pointVar), + limitIndexDefinitionAt(heightFun, limitIndex, pointVar), + pointVar ∈ argType + ) |- limitIndexWitnessAt(heightFun, limitIndex, pointVar) + ) { + val pointHeightChar = assume(pointHeightCharAt(argType, heightFun, pointVar)) + val limitIndexDef = assume(limitIndexDefinitionAt(heightFun, limitIndex, pointVar)) + val pointInArgType = assume(pointVar ∈ argType) + val pointHasSomeHeightInst = have( + (pointHeightCharAt(argType, heightFun, pointVar), pointVar ∈ argType) |- + ∃(nVar, (nVar ∈ N) /\ (pointVar ∈ app(heightFun)(nVar))) + ) by Restate.from(pointHasSomeHeight) + val pointHasHeight = have( + ∃(nVar, (nVar ∈ N) /\ (pointVar ∈ app(heightFun)(nVar))) + ) by Tautology.from(pointHeightChar, pointInArgType, pointHasSomeHeightInst) + + val epsilonWitness = have( + (ε(nVar, (nVar ∈ N) /\ (pointVar ∈ app(heightFun)(nVar))) ∈ N) /\ + (pointVar ∈ app(heightFun)(ε(nVar, (nVar ∈ N) /\ (pointVar ∈ app(heightFun)(nVar))))) + ) by Tautology.from( + pointHasHeight, + Quantifiers.existsEpsilon.of( + x := nVar, + P := λ(nVar, (nVar ∈ N) /\ (pointVar ∈ app(heightFun)(nVar))) + ) + ) + + have(thesis) by Congruence.from(limitIndexDef, epsilonWitness) + } + + private val limitValueAtIndex: Theorem = Lemma( + (limitFunDefinition(argType, limitFun, G, limitIndex), pointVar ∈ argType) |- + app(limitFun)(pointVar) === app(G(limitIndex(pointVar)))(pointVar) + ) { + val T, e2 = variable[Ind] + val e = variable[Ind >>: Ind] + val pointInArgType = assume(pointVar ∈ argType) + val limitDef = assume(limitFunDefinition(argType, limitFun, G, limitIndex)) + + val betaAtPoint = have( + app(abs(argType)(λ(pointVar, app(G(limitIndex(pointVar)))(pointVar))))(pointVar) === + app(G(limitIndex(pointVar)))(pointVar) + ) by Tautology.from( + pointInArgType, + BetaReduction of ( + T := argType, + e := λ(pointVar, app(G(limitIndex(pointVar)))(pointVar)), + e2 := pointVar + ) + ) + + have(thesis) by Congruence.from(limitDef, betaAtPoint) + } + + private val limitAtHeight: Theorem = Lemma( + ( + pointHeightCharAt(argType, heightFun, pointVar), + limitIndexDefinitionAt(heightFun, limitIndex, pointVar), + limitFunDefinition(argType, limitFun, G, limitIndex), + ApproximationChainFacts.stabilizationSchema(heightFun, G), + ApproximationChainFacts.heightMembershipMonotonicSchema(heightFun), + nVar ∈ N, + pointVar ∈ app(heightFun)(nVar) + ) |- app(limitFun)(pointVar) === app(G(nVar))(pointVar) + ) { + val pointHeightChar = assume(pointHeightCharAt(argType, heightFun, pointVar)) + val limitIndexDef = assume(limitIndexDefinitionAt(heightFun, limitIndex, pointVar)) + val limitDef = assume(limitFunDefinition(argType, limitFun, G, limitIndex)) + val stabSchema = assume(ApproximationChainFacts.stabilizationSchema(heightFun, G)) + val monoSchema = assume(ApproximationChainFacts.heightMembershipMonotonicSchema(heightFun)) + val indexInN = assume(nVar ∈ N) + val pointInHeight = assume(pointVar ∈ app(heightFun)(nVar)) + val heightMembershipInst = have( + (pointHeightCharAt(argType, heightFun, pointVar), nVar ∈ N, pointVar ∈ app(heightFun)(nVar)) |- pointVar ∈ argType + ) by Tautology.from(heightMembershipImpliesInArgType) + val limitValueAtIndexInst = have( + (limitFunDefinition(argType, limitFun, G, limitIndex), pointVar ∈ argType) |- + app(limitFun)(pointVar) === app(G(limitIndex(pointVar)))(pointVar) + ) by Tautology.from(limitValueAtIndex) + val limitIndexWitnessInst = have( + ( + pointHeightCharAt(argType, heightFun, pointVar), + limitIndexDefinitionAt(heightFun, limitIndex, pointVar), + pointVar ∈ argType + ) |- limitIndexWitnessAt(heightFun, limitIndex, pointVar) + ) by Tautology.from(limitIndexWitness) + + val pointInArgType = have(pointVar ∈ argType) by Tautology.from( + pointHeightChar, + indexInN, + pointInHeight, + heightMembershipInst + ) + + val limitAtIndex = have(app(limitFun)(pointVar) === app(G(limitIndex(pointVar)))(pointVar)) by Tautology.from( + limitDef, + pointInArgType, + limitValueAtIndexInst + ) + + val indexWitness = have(limitIndexWitnessAt(heightFun, limitIndex, pointVar)) by Tautology.from( + pointHeightChar, + limitIndexDef, + pointInArgType, + limitIndexWitnessInst + ) + val limitIndexInN = have(limitIndex(pointVar) ∈ N) by Tautology.from(indexWitness) + val pointInLimitHeight = have(pointVar ∈ app(heightFun)(limitIndex(pointVar))) by Tautology.from(indexWitness) + + val agreeAtHeight = have(app(G(limitIndex(pointVar)))(pointVar) === app(G(nVar))(pointVar)) by + Tautology.from( + ApproximationChainFacts.approximantsAgreeAcrossHeightsAt(heightFun, G, limitIndex(pointVar), nVar, pointVar), + stabSchema, + monoSchema, + limitIndexInN, + indexInN, + pointInLimitHeight, + pointInHeight + ) + + have(app(limitFun)(pointVar) === app(G(nVar))(pointVar)) by Tautology.from( + altEqualityTransitivity of ( + x := app(limitFun)(pointVar), + y := app(G(limitIndex(pointVar)))(pointVar), + z := app(G(nVar))(pointVar) + ), + limitAtIndex, + agreeAtHeight + ) + thenHave(thesis) by Restate + } + + def pointHasSomeHeightAt(argType0: Expr[Ind], heightFun0: Expr[Ind], point0: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + pointHasSomeHeight.of(argType := argType0, heightFun := heightFun0, pointVar := point0) + + def limitIndexWitnessAt( + argType0: Expr[Ind], + heightFun0: Expr[Ind], + limitIndex0: Expr[Ind >>: Ind], + point0: Expr[Ind] + )(using proof: lisa.SetTheoryLibrary.Proof): Thm = + limitIndexWitness.of( + argType := argType0, + heightFun := heightFun0, + limitIndex := limitIndex0, + pointVar := point0 + ) + + def limitAtHeightAt(using + proof: lisa.SetTheoryLibrary.Proof + )( + argType0: Expr[Ind], + heightFun0: Expr[Ind], + limitFun0: Expr[Ind], + G0: Expr[Ind >>: Ind], + limitIndex0: Expr[Ind >>: Ind], + point0: Expr[Ind], + n0: Expr[Ind], + stabilization0: Theorem, + heightMembershipMonotonic: Seq[SubstPair] => Thm, + heightFunValid: Thm + ): Thm = + val monoSchema = ApproximationChainFacts.heightMembershipMonotonicSchemaAt( + heightFun0, + heightMembershipMonotonic, + heightFunValid + ) + have( + ( + pointHeightCharAt(argType0, heightFun0, point0), + limitIndexDefinitionAt(heightFun0, limitIndex0, point0), + limitFunDefinition(argType0, limitFun0, G0, limitIndex0), + n0 ∈ N, + point0 ∈ app(heightFun0)(n0) + ) |- app(limitFun0)(point0) === app(G0(n0))(point0) + ) by Tautology.from( + limitAtHeight.of( + argType := argType0, + heightFun := heightFun0, + limitFun := limitFun0, + G := G0, + limitIndex := limitIndex0, + pointVar := point0, + nVar := n0 + ), + stabilization0, + monoSchema + ) + + def initialize(): Unit = { + val _ = pointHasSomeHeight + val _ = heightMembershipImpliesInArgType + val _ = limitIndexWitness + val _ = limitValueAtIndex + val _ = limitAtHeight + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ProofsInitialization.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ProofsInitialization.scala new file mode 100644 index 000000000..0c985664b --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/proofs/ProofsInitialization.scala @@ -0,0 +1,9 @@ +package lisa.maths.SetTheory.Types.ADT.recursion.proofs + +object ProofsInitialization { + + def initialize(): Unit = { + LimitKernel.initialize() + ApproximationChainFacts.initialize() + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/core/Utils.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/core/Utils.scala new file mode 100644 index 000000000..83385e52c --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/core/Utils.scala @@ -0,0 +1,126 @@ +package lisa.maths.SetTheory.Types.ADT.support.core + +import lisa.maths.SetTheory.Base.Pair +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.syntax.AST._ +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.fol.FOL.Variable +import lisa.utils.fol.FOL.{Expr => FExpr} +import lisa.utils.fol.FOL.{Ind => FInd} +import lisa.utils.fol.FOL.{Prop => FProp} + +private object SchematicVariables { + + // Variables + val a, b, c, d = variable[Ind] + val f, g = variable[Ind] + val k, n, m = variable[Ind] + val r, s, t = variable[Ind] + val x, y, z = variable[Ind] + val α, β = variable[Ind] + + val h = variable[Ind] + + val A, B = variable[Ind] + + // Propositions + val p, p1, p2, p3, p4 = variable[Prop] + val q1, q2 = variable[Prop] + + // Predicates + val P, Q = variable[Ind >>: Prop] + val schemPred = variable[Ind >>: Prop] + val P2 = variable[Ind >>: Ind >>: Prop] + + // Constants + val N: Expr[Ind] = lisa.maths.SetTheory.Ordinals.Integer.ω + +} + +object Utils { + + export SchematicVariables.* + object UnreachableException + extends Exception( + "This code should not be accessed. If you see this message, please report it to the library maintainers." + ) + + def pair(x: Expr[Ind], y: Expr[Ind]): Expr[Ind] = + Pair.pair(x)(y) + + // Syntactic sugar for sequences + + def appSeq(f: Expr[Ind])(args: Seq[Expr[Ind]]): Expr[Ind] = + Option(args).getOrElse(Seq.empty).foldLeft(f)(_ * _) + + def renderAppliedSymbol(name: String, typeArgCount: Int, args: Seq[Expr[?]]): String = + val (typeArgs, valueArgs) = args.splitAt(typeArgCount) + val head = + if typeArgCount == 0 then name + else s"$name[${typeArgs.mkString(",")}]" + valueArgs.foldLeft(head)((acc, arg) => s"$acc($arg)") + + def seqOr(s: Iterable[Expr[Prop]]): Expr[Prop] = s + .reduceOption(_ \/ _) + .getOrElse(False: Expr[Prop]) + + def seqAnd(s: Iterable[Expr[Prop]]): Expr[Prop] = s + .reduceOption(_ /\ _) + .getOrElse(True: Expr[Prop]) + + def seqEq(s1: Seq[Expr[Ind]], s2: Seq[Expr[Ind]]): Expr[Prop] = + seqAnd(s1.zip(s2).map((a, b) => a === b)) + + extension (s1: Seq[Expr[Ind]]) + def ===(s2: Seq[Expr[Ind]]): Expr[Prop] = + seqEq(s1, s2) + + def existsSeq(vars: Seq[Variable[FInd]], formula: FExpr[FProp]): FExpr[FProp] = + vars.foldRight(formula)(∃(_, _)) + + def forallSeq(vars: Seq[Variable[FInd]], formula: FExpr[FProp]): FExpr[FProp] = + vars.foldRight(formula)(∀(_, _)) + + // Some useful functions + + def simplify(formula: Expr[Prop]): Expr[Prop] = formula match + case ⊥ \/ phi => simplify(phi) + case phi \/ ⊥ => simplify(phi) + case phi \/ psi => simplify(phi) \/ simplify(psi) + case ⊤ /\ phi => simplify(phi) + case phi /\ ⊤ => simplify(phi) + case phi /\ psi => simplify(phi) /\ simplify(psi) + case ⊤ ==> phi => simplify(phi) + case phi ==> psi => simplify(phi) ==> simplify(psi) + case _ => formula + + extension (arg: ConstructorArg) + def getOrElse(adt: Expr[Ind]): Expr[Ind] = arg match + case SelfRef => adt + case TypeArg(name) => typeExprToTerm(name) + + /** + * Reconstructs a declared parameter, preserving its numeric freshness suffix. + */ + def typeExprToTerm(name: String): Variable[Ind] = + val separator = name.lastIndexOf(Identifier.counterSeparator) + val index = if separator < 0 then None else name.substring(separator + 1).toIntOption.filter(_ >= 0) + val id = index.fold(Identifier(name))(n => Identifier(name.substring(0, separator), n)) + Variable[Ind](id) + + // Well-typedness predicates + + def wellTyped(s: Seq[(Expr[Ind], Expr[Ind])]): Seq[Expr[Prop]] = s.map(_ :: _) + + def wellTyped(s: Seq[(Expr[Ind], ConstructorArg)])(orElse: Expr[Ind]): Seq[Expr[Prop]] = + s.map((t, arg) => t :: arg.getOrElse(orElse)) + + def wellTypedSet(s: Seq[(Expr[Ind], Expr[Ind])]): Set[Expr[Prop]] = wellTyped(s).toSet + + def wellTypedFormula(s: Seq[(Expr[Ind], Expr[Ind])]): Expr[Prop] = seqAnd(wellTyped(s)) + + def wellTypedFormula(s: Seq[(Expr[Ind], ConstructorArg)])( + orElse: Expr[Ind] + ): Expr[Prop] = seqAnd(wellTyped(s)(orElse)) + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/package.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/package.scala new file mode 100644 index 000000000..9dab91660 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/package.scala @@ -0,0 +1,6 @@ +package lisa.maths.SetTheory.Types.ADT + +package object support { + export lisa.maths.SetTheory.Types.ADT.support.core.Utils + export lisa.maths.SetTheory.Types.ADT.support.semantics.{DefinedSymbol, DefinedProperty, UniqueDefinedSymbol} +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/proofs/PropositionalFacts.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/proofs/PropositionalFacts.scala new file mode 100644 index 000000000..166282986 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/proofs/PropositionalFacts.scala @@ -0,0 +1,32 @@ +package lisa.maths.SetTheory.Types.ADT.support.proofs + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ + +/** + * Generic propositional, equivalence and equality lemmas, split out of the + * former `UsefulTheorems` grab-bag. + */ +object PropositionalFacts { + + val equivalenceApply = Lemma((p1 <=> p2, p1) |- p2) { + have(thesis) by Tautology + } + + val equivalenceRevApply = Lemma((p2 <=> p1, p1) |- p2) { + have(thesis) by Tautology + } + + val altEqualityTransitivity = + Lemma((x === y, y === z) |- x === z)(have(thesis) by Congruence) + + val equivalenceRewriting = + Lemma((p1 <=> p2, p2 <=> p3) |- (p1 <=> p3))(have(thesis) by Tautology) + + val leftImpliesEquivalenceWeak = + Lemma(p1 <=> p2 |- (p ==> p1) <=> (p ==> p2))(have(thesis) by Tautology) + + val leftImpliesEquivalenceStrong = + Lemma(p ==> (p1 <=> p2) |- (p ==> p1) <=> (p ==> p2))(have(thesis) by Tautology) + +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/semantics/DefinedSymbols.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/semantics/DefinedSymbols.scala new file mode 100644 index 000000000..b9f8eb8f5 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/semantics/DefinedSymbols.scala @@ -0,0 +1,167 @@ +package lisa.maths.SetTheory.Types.ADT.support.semantics + +import lisa.maths.Quantifiers.existsOneAlternativeDefinition +import lisa.maths.Quantifiers.existsOneEpsilon +import lisa.maths.Quantifiers.∃! +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.utils.prooflib.BasicStep.RightForall +import lisa.utils.prooflib.Thm + +/** + * Defines a symbol by abstracting its body over the supplied parameters. + */ +class DefinedSymbol[S]( + protected val name: String, + protected val parametersSeq: Seq[Variable[Ind]], + protected val body: Expr[S] +) { + + protected val classFunction: Constant[?] = { + val classFunctionExpr: Expr[?] = lisa.utils.fol.FOL.Abs.apply( + xs = parametersSeq, + t = body + ) + type T + given T is lisa.utils.fol.FOL.Sort = + lisa.utils.fol.FOL.unsafeSortEvidence(classFunctionExpr.sort) + DEF(using name = name)(classFunctionExpr.asInstanceOf[Expr[T]]) + } + classFunction.printAs(args => renderAppliedSymbol(name, parametersSeq.size, args)) + + val symbol: Constant[?] = classFunction + val definition: Thm = classFunction.definition + val id: Identifier = classFunction.id + + /** + * Instantiates every declared parameter, preserving the body's result sort. + */ + def term(args: Seq[Expr[Ind]]): Expr[S] = + require(args.size == parametersSeq.size, s"Symbol $name expects ${parametersSeq.size} parameter argument(s), got ${args.size}.") + (classFunction #@@ args).asInstanceOf[Expr[S]] + + val term: Expr[S] = term(parametersSeq) + +} + +/** + * Defines a parameterized predicate with folding and unfolding proofs at arbitrary arguments. + */ +class DefinedProperty( + name: String, + typeVariablesSeq: Seq[Variable[Ind]], + bodyVar: Variable[Ind], + bodyAt: Expr[Ind] => Expr[Prop] +) extends DefinedSymbol[Ind >>: Prop](name, typeVariablesSeq, λ(bodyVar, bodyAt(bodyVar))) { + + private val (appliedPredicate, definingFormula) = definition.statement.right.head match + case lhs <=> rhs => (lhs, rhs) + case other => throw IllegalStateException(s"$name.definition is expected to be an `<=>`, got: $other") + + /** + * Derives the defining formula from the applied predicate. + */ + lazy val unfold: Theorem = Lemma.generated(appliedPredicate |- definingFormula) { have(thesis) by Tautology.from(definition) } + + /** + * Derives the applied predicate from its defining formula. + */ + lazy val fold: Theorem = Lemma.generated(definingFormula |- appliedPredicate) { have(thesis) by Tautology.from(definition) } + + /** + * Instantiates the unfolding direction in the current proof. + */ + def unfoldAt(arg: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + if arg == bodyVar then unfold else unfold.of(bodyVar := arg) + + /** + * Instantiates the folding direction in the current proof. + */ + def foldAt(arg: Expr[Ind])(using proof: lisa.SetTheoryLibrary.Proof): Thm = + if arg == bodyVar then fold else fold.of(bodyVar := arg) + +} + +/** + * Defines an epsilon-selected symbol and proves its defining predicate from unique existence. + */ +class UniqueDefinedSymbol( + name: String, + typeVariablesSeq: Seq[Variable[Ind]], + witnessVar: Variable[Ind], + definitionAt: Expr[Ind] => Expr[Prop] +)( + uniqueness: Theorem +) extends DefinedSymbol[Ind](name, typeVariablesSeq, ε(witnessVar, definitionAt(witnessVar))) { + + private val witnessDefinition: Expr[Prop] = definitionAt(witnessVar) + + private val classTermIsEpsilon: Theorem = Lemma.generated(term === ε(witnessVar, witnessDefinition)) { + have(thesis) by Congruence.from(definition) + } + + /** + * The selected term satisfies its defining predicate. + */ + val definitionFact: Theorem = Lemma.generated(definitionAt(term)) { + val epsilonWitness = ε(witnessVar, witnessDefinition) + + val definitionAtEpsilon = have(definitionAt(epsilonWitness)) by Tautology.from( + uniqueness, + existsOneEpsilon of (x := witnessVar, P := λ(witnessVar, witnessDefinition)) + ) + val epsilonEqTerm = have(epsilonWitness === term) by Congruence.from(classTermIsEpsilon) + + val definitionAtEpsilonWithEq = + have((epsilonWitness === term) |- definitionAt(epsilonWitness)) by + Weakening(definitionAtEpsilon) + + val replacementVar = Variable[Ind](freshId(Seq(witnessDefinition, epsilonWitness, term) ++ typeVariablesSeq, "replacementVar")) + val definitionAtTerm = + have((epsilonWitness === term) |- definitionAt(term)) by + RightSubst( + List((epsilonWitness, term)), + (Seq(replacementVar), definitionAt(replacementVar)) + )(definitionAtEpsilonWithEq) + + have(thesis) by Tautology.from(epsilonEqTerm, definitionAtTerm) + } +} + +/** + * Builds epsilon-selected symbols from their existence and uniqueness proofs. + */ +object UniqueDefinedSymbol { + + /** + * Defines a unique witness from separate existence and pointwise-uniqueness proofs. + */ + def fromParts( + name: String, + typeVariablesSeq: Seq[Variable[Ind]], + witnessVar: Variable[Ind], + comparisonVariables: (Variable[Ind], Variable[Ind]), + definitionAt: Expr[Ind] => Expr[Prop] + )( + existence: Theorem, + pointwiseUniqueness: Theorem + ): UniqueDefinedSymbol = { + val (left, right) = comparisonVariables + new UniqueDefinedSymbol(name, typeVariablesSeq, witnessVar, definitionAt)( + Lemma.generated(∃!(witnessVar, definitionAt(witnessVar))) { + have(∀(right, definitionAt(left) /\ definitionAt(right) ==> (left === right))) by + RightForall(pointwiseUniqueness) + val uniquenessAll = thenHave( + ∀(left, ∀(right, definitionAt(left) /\ definitionAt(right) ==> (left === right))) + ) by RightForall + + val altDef = existsOneAlternativeDefinition of (x := witnessVar, P := λ(witnessVar, definitionAt(witnessVar))) + + have( + ∃(witnessVar, definitionAt(witnessVar)) /\ ∀(left, ∀(right, definitionAt(left) /\ definitionAt(right) ==> (left === right))) + ) by RightAnd(existence, uniquenessAll) + thenHave(thesis) by Substitute(altDef) + } + ) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/support/InterfaceHelpers.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/support/InterfaceHelpers.scala new file mode 100644 index 000000000..a13e99112 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/support/InterfaceHelpers.scala @@ -0,0 +1,170 @@ +package lisa.maths.SetTheory.Types.ADT.support + +import lisa.maths.SetTheory.Functions.Function.app +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.UnreachableException +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.a +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.b +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.f +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.forallSeq +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.x +import lisa.maths.SetTheory.Types.TypingHelpers.:: +import lisa.maths.SetTheory.Types.TypingTheorems.arrowElim +import lisa.utils.fol.FOL.SubstPair +import lisa.utils.prooflib.QuantifiersIntro +import lisa.utils.prooflib.Thm + +object InterfaceHelpers { + + type TypeSubstitution = SubstPair { type S = Ind } + + /** + * Validates type substitutions and orders them by the owner's declared parameters. + */ + def normalizeTypeSubstitutions( + ownerKind: String, + ownerName: String, + typeVariables: Seq[Variable[Ind]], + substitutions: Seq[TypeSubstitution] + ): Seq[TypeSubstitution] = { + val allowed = typeVariables.toSet + val byVariable = scala.collection.mutable.Map.empty[Variable[Ind], Expr[Ind]] + + substitutions.foreach { substitution => + val variable = substitution._1 + val value = substitution._2 + require( + allowed.contains(variable), + s"$ownerKind $ownerName cannot substitute non-type variable $variable." + ) + byVariable.get(variable) match + case Some(previous) => + require( + previous == value, + s"$ownerKind $ownerName received incompatible substitutions for $variable." + ) + case None => byVariable.update(variable, value) + } + + typeVariables.flatMap(variable => byVariable.get(variable).map(value => variable := value)) + } + + def substitutionsFromArgs( + ownerKind: String, + ownerName: String, + typeVariables: Seq[Variable[Ind]], + args: Seq[Expr[Ind]] + ): Seq[TypeSubstitution] = { + require( + args.size == typeVariables.size, + s"$ownerKind $ownerName expects ${typeVariables.size} type argument(s), got ${args.size}." + ) + typeVariables.zip(args).map((variable, arg) => variable := arg) + } + + def specializeTerm(term: Expr[Ind], substitutions: Seq[TypeSubstitution]): Expr[Ind] = + term.substitute(substitutions*) + + def formulaOf(statement: Sequent, owner: String): Expr[Prop] = { + require( + statement.left.isEmpty && statement.right.size == 1, + s"$owner expects a single-formula theorem statement, got $statement." + ) + statement.right.head + } + + def instantiatedSemanticSignature( + signature: Seq[(Variable[Ind], Expr[Ind])], + substitutions: Seq[TypeSubstitution] + ): Seq[(Variable[Ind], Expr[Ind])] = + signature.map((variable, typ) => variable -> specializeTerm(typ, substitutions)) + + def proveAppliedTyping(using + proof: lisa.SetTheoryLibrary.Proof + )( + headTyping: Thm, + headTerm: Expr[Ind], + headType: Expr[Ind], + args: Seq[(Variable[Ind], Expr[Ind])] + ): Thm = + args + .foldLeft[(Thm, Expr[Ind], Expr[Ind])]((headTyping, headTerm, headType)) { case ((accFact, accTerm, accType), (argument, _)) => + accType match + case domainType ->: codomainType => + val argumentTyping = assume(argument :: domainType) + val appliedTerm = app(accTerm)(argument) + val nextFact = have(appliedTerm :: codomainType) by Tautology.from( + accFact, + arrowElim of ( + f := accTerm, + a := domainType, + b := codomainType, + x := argument + ), + argumentTyping + ) + (nextFact, appliedTerm, codomainType) + case _ => throw UnreachableException + } + ._1 + + /** + * Closes a theorem over the type parameters, returning the original when there are none. + */ + def generalTheorem(using + line: sourcecode.Line, + file: sourcecode.File + )( + displayName: String, + typeVariables: Seq[Variable[Ind]], + suffix: String, + baseTheorem: Theorem + ): Theorem = + if typeVariables.isEmpty then baseTheorem + else + val theoremName = s"$displayName/$suffix" + Theorem.named(theoremName)(forallSeq(typeVariables, formulaOf(baseTheorem.statement, theoremName))) { + have(baseTheorem.statement) by Restate.from(baseTheorem) + thenHave(thesis) by QuantifiersIntro(typeVariables) + } + + /** + * Instantiates a theorem in the current proof, preserving the original for identity substitutions. + */ + def instantiate(using + proof: lisa.SetTheoryLibrary.Proof + )( + baseTheorem: Theorem, + substitutions: Seq[SubstPair] + ): Thm = { + if substitutions.forall(substitution => substitution._1 == substitution._2) then baseTheorem + else baseTheorem.of(substitutions*) + } + + /** + * Derives typing for the symbol applied to its arguments, under their typing assumptions. + */ + def introAppTheorem(using + line: sourcecode.Line, + file: sourcecode.File + )( + displayName: String, + baseTheorem: Theorem, + headTerm: Expr[Ind], + headType: Expr[Ind], + assumptions: Set[Expr[Prop]], + typingArgs: Seq[(Variable[Ind], Expr[Ind])], + conclusion: Expr[Prop] + ): Theorem = + Theorem.named(s"$displayName/introApp")(assumptions |- conclusion) { + have(baseTheorem.statement) by Restate.from(baseTheorem) + val appliedTyping = proveAppliedTyping( + headTyping = lastStep, + headTerm = headTerm, + headType = headType, + args = typingArgs + ) + have(thesis) by Tautology.from(appliedTyping) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/support/TypedADTConstant.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/support/TypedADTConstant.scala new file mode 100644 index 000000000..a936092f0 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/support/TypedADTConstant.scala @@ -0,0 +1,10 @@ +package lisa.maths.SetTheory.Types.ADT.support + +import lisa.maths.SetTheory.SetTheory._ +import lisa.maths.SetTheory.Types.TypingHelpers.FunctionalClass +import lisa.maths.SetTheory.Types.TypingHelpers.TypedConstantFunctional + +/** + * Retains the named typing theorem alongside the proof used by the typechecker. + */ +abstract class TypedADTConstant[S: Sort](id: Identifier, typ: FunctionalClass, val intro: Theorem) extends TypedConstantFunctional[S](id, typ, intro.thm) diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/tactics/Cuts.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/tactics/Cuts.scala new file mode 100644 index 000000000..c9930eed4 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/support/tactics/Cuts.scala @@ -0,0 +1,23 @@ +package lisa.maths.SetTheory.Types.ADT.support.tactics + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.utils.prooflib.ProofJudgement +import lisa.utils.prooflib.Subproof +import lisa.utils.prooflib.Thm + +/** + * Discharges matching premises with cuts and checks the final sequent. + */ +object Cuts { + def apply(using proof: Proof, line: sourcecode.Line, file: sourcecode.File)(main: Thm)(sideFacts: Thm*)(bot: Sequent): ProofJudgement = Subproof { + val combined = sideFacts.foldLeft(main) { (acc, fact) => + fact.right.find(r => acc.left.exists(l => isSame(l, r))) match + case None => acc + case Some(formula) => + val left = fact.left ++ acc.left.filterNot(isSame(_, formula)) + val right = fact.right.filterNot(isSame(_, formula)) ++ acc.right + have(left |- right) by Cut.withParameters(formula)(fact, acc) + } + have(bot) by Weakening(combined) + } +} diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/syntax/AST.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/syntax/AST.scala new file mode 100644 index 000000000..8773838b9 --- /dev/null +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/syntax/AST.scala @@ -0,0 +1,27 @@ +package lisa.maths.SetTheory.Types.ADT.syntax + +/** + * Core syntax for ADT v2. Kept backend-agnostic on purpose. + */ +object AST { + + sealed trait ConstructorArg + + /** + * A regular argument with a type, e.g. "head: A" in cons:(A, self) . + */ + // final case class RegularArg(tpe: TypeExpr) extends ConstructorArg { + // override def toString: String = tpe.toString + // } + final case class TypeArg(name: String) extends ConstructorArg { + override def toString: String = name + } + + /** + * A recursive reference to the ADT being defined, e.g. "self" in cons:(A, self) . + */ + case object SelfRef extends ConstructorArg { + override def toString: String = "self" + } + +} diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Ordinals/IntegerSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Ordinals/IntegerSuite.scala new file mode 100644 index 000000000..acf712875 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Ordinals/IntegerSuite.scala @@ -0,0 +1,67 @@ +package lisa.maths.SetTheory.Ordinals + +import lisa.maths.SetTheory.Ordinals.Integer.emptyInOmega +import lisa.maths.SetTheory.Ordinals.Integer.integer +import lisa.maths.SetTheory.Ordinals.Integer.integerHereditary +import lisa.maths.SetTheory.Ordinals.Integer.omegaDownwardClosed +import lisa.maths.SetTheory.Ordinals.Integer.omegaInduction +import lisa.maths.SetTheory.Ordinals.Integer.omegaPredecessor +import lisa.maths.SetTheory.Ordinals.Integer.omegaSuccessorInduction +import lisa.maths.SetTheory.Ordinals.Integer.subsetSuccessor +import lisa.maths.SetTheory.Ordinals.Integer.succMembership +import lisa.maths.SetTheory.Ordinals.Integer.successorInjectivity +import lisa.maths.SetTheory.Ordinals.Integer.zeroIsNotSucc +import lisa.maths.SetTheory.Ordinals.Integer.ω +import lisa.maths.SetTheory.Ordinals.Ordinal.S +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Executes integer closure proofs and successor laws for arbitrary sets. + */ +class IntegerSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private val α, β, x, y, z, n, m, k = variable[Ind] + private val P = variable[Ind >>: Prop] + + test("successor laws need no ordinal or natural-number assumptions"): + val membership = Theorem(z ∈ S(x) <=> (z ∈ x) \/ (z === x)) { + have(thesis) by Restate.from(succMembership.of(k := z, n := x)) + } + val injectivity = Theorem(S(x) === S(y) |- x === y) { + have(thesis) by Weakening(successorInjectivity.of(n := x, m := y)) + } + val nonempty = Theorem(!(S(x) === ∅)) { + have(thesis) by Restate.from(zeroIsNotSucc.of(n := x)) + } + val inclusion = Theorem(x ⊆ S(x)) { + have(thesis) by Restate.from(subsetSuccessor.of(n := x)) + } + assert(!membership.hasErrorsOrSorry && !injectivity.hasErrorsOrSorry && !nonempty.hasErrorsOrSorry && !inclusion.hasErrorsOrSorry) + + test("integer membership is hereditary through two levels"): + val checked = Theorem((integer(α), x ∈ α, y ∈ x) |- integer(y)) { + val first = have((integer(α), x ∈ α) |- integer(x)) by + Restate.from(integerHereditary.of(β := x)) + have(thesis) by Tautology.from(first, integerHereditary.of(α := x, β := y)) + } + assert(!checked.hasErrorsOrSorry) + + test("omega contains zero and is closed under elements and predecessor"): + val downward = Theorem((y ∈ ω, x ∈ y) |- x ∈ ω) { + have(thesis) by Restate.from(omegaDownwardClosed) + } + val predecessor = Theorem(S(x) ∈ ω |- x ∈ ω) { + have(thesis) by Restate.from(omegaPredecessor.of(α := x)) + } + assert(!emptyInOmega.hasErrorsOrSorry && !downward.hasErrorsOrSorry && !predecessor.hasErrorsOrSorry) + + test("both induction names expose the same proof and schema"): + val expected = (P(∅), ∀(m, m ∈ ω ==> (P(m) ==> P(S(m))))) |- ∀(n, n ∈ ω ==> P(n)) + assert(omegaSuccessorInduction eq omegaInduction) + assert(isSameSequent(omegaSuccessorInduction.statement, expected)) + assert(!omegaSuccessorInduction.hasErrorsOrSorry) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/DisjointnessSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/DisjointnessSuite.scala new file mode 100644 index 000000000..741a2021b --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/DisjointnessSuite.scala @@ -0,0 +1,96 @@ +package lisa.maths.SetTheory.Types.ADT + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.library.bool +import lisa.maths.SetTheory.Types.ADT.library.nat +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Checks lazy disjointness generation, symmetry, and constructor ownership. + */ +class DisjointnessSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private val x, y, z = variable[Ind] + + test("a requested pair registers no unrelated disjointness and reuses each cached theorem"): + val declaration = adt( + "disjointnessDemand", + "A", + Seq( + ("empty", Seq.empty), + ("one", Seq(("item", "A"))), + ("two", Seq(("left", "A"), ("right", "A"))), + ("unused", Seq.empty) + ) + ) + val Seq(empty, one, two, unused) = declaration.constructors: @unchecked + val requested = declaration.disjointness(two, one) + for first <- declaration.constructors; second <- declaration.constructors if first != second do + val name = s"${declaration.name}/${first.semantic.name}-${second.semantic.name}/disjointness" + assert(lisa.SetTheoryLibrary.theorems.getFull(name).isDefined == (first == two && second == one)) + + val semantic = declaration.semantic.disjointness(two.semantic, one.semantic) + val instance = two.semantic.disjointness(one.semantic) + val last = lisa.SetTheoryLibrary.theorems.all.size + assert(declaration.disjointness(two, one) eq requested) + assert(declaration.semantic.disjointness(two.semantic, one.semantic) eq semantic) + assert(two.semantic.disjointness(one.semantic) eq instance) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + assert(!requested.hasErrorsOrSorry && !semantic.hasErrorsOrSorry && !instance.hasErrorsOrSorry) + + val reverse = declaration.disjointness(one, two) + val forwardApplication = Theorem.generated((x :: nat, y :: nat, z :: nat) |- !(two(nat) * x * y === one(nat) * z)) { + have(thesis) by Tautology.from(requested.of(nat, x, y, z)) + } + val reverseApplication = Theorem.generated((x :: bool, y :: bool, z :: bool) |- !(one(bool) * x === two(bool) * y * z)) { + have(thesis) by Tautology.from(reverse.of(bool, x, y, z)) + } + assert(!forwardApplication.hasErrorsOrSorry && !reverseApplication.hasErrorsOrSorry) + + val nullary = declaration.disjointness(empty, unused) + val nullaryReverse = declaration.disjointness(unused, empty) + val nullaryApplications = Theorem.generated(!(empty(nat) === unused(nat)) /\ !(unused(bool) === empty(bool))) { + have(thesis) by Tautology.from(nullary.of(nat), nullaryReverse.of(bool)) + } + assert(!nullaryApplications.hasErrorsOrSorry) + + test("schema binders are fresh against declared argument and type parameter names"): + val declaration = adt( + "disjointnessBinders", + "disjointArgument0", + Seq( + ("one", Seq(("disjointArgument1", "disjointArgument0"))), + ("two", Seq(("disjointArgument2", "disjointArgument0"), ("disjointArgument3", "disjointArgument0"))) + ) + ) + val Seq(one, two) = declaration.constructors: @unchecked + val reverse = declaration.disjointness(two, one) + val forward = declaration.disjointness(one, two) + val applications = Theorem.generated( + (x :: nat, y :: nat, z :: nat) |- + (!(two(nat) * x * y === one(nat) * z) /\ !(one(nat) * x === two(nat) * y * z)) + ) { + have(thesis) by Tautology.from(reverse.of(nat, x, y, z), forward.of(nat, x, y, z)) + } + assert(!applications.hasErrorsOrSorry) + + test("equal and foreign constructors are rejected before proving anything"): + val declaration = adt("disjointnessOwner", "A", Seq(("left", Seq.empty), ("right", Seq.empty))) + val foreign = adt("disjointnessForeign", "A", Seq(("foreign", Seq.empty))).constructors.head + val first = declaration.constructors.head + val last = lisa.SetTheoryLibrary.theorems.all.size + val language = lisa.SetTheoryLibrary.theory.language.toSet + + intercept[IllegalArgumentException](declaration.disjointness(first, first)) + intercept[IllegalArgumentException](declaration.disjointness(first, foreign)) + intercept[IllegalArgumentException](declaration.semantic.disjointness(first.semantic, first.semantic)) + intercept[IllegalArgumentException](declaration.semantic.disjointness(first.semantic, foreign.semantic)) + intercept[IllegalArgumentException](first.semantic.disjointness(first.semantic)) + intercept[IllegalArgumentException](first.semantic.disjointness(foreign.semantic)) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + assert(lisa.SetTheoryLibrary.theory.language.toSet == language) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/LazyProofsSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/LazyProofsSuite.scala new file mode 100644 index 000000000..a870c7a0e --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/LazyProofsSuite.scala @@ -0,0 +1,139 @@ +package lisa.maths.SetTheory.Types.ADT + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.library.bool +import lisa.maths.SetTheory.Types.ADT.library.cons +import lisa.maths.SetTheory.Types.ADT.library.list +import lisa.maths.SetTheory.Types.ADT.library.nil +import lisa.maths.SetTheory.Types.ADT.library.tru +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Checks that proof accessors build only requested theorems and retain their results. + */ +class LazyProofsSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private val A, head, tail, inner = variable[Ind] + private def registered(name: String): Boolean = lisa.SetTheoryLibrary.theorems.getFull(name).isDefined + + test("induction and each constructor's injectivity are deferred until requested"): + val declaration = adt( + "lazyProofDatatype", + "A", + Seq( + ("leaf", Seq("value" -> "A")), + ("node", Seq("left" -> SelfRef, "right" -> SelfRef)) + ) + ) + val Seq(leaf, node) = declaration.constructors: @unchecked + assert(!registered(s"${declaration.name}/induction")) + assert(!registered(s"${leaf.name}/injectivity")) + assert(!registered(s"${node.name}/injectivity")) + + val leafInjectivity = leaf.injectivity + assert(!leafInjectivity.hasErrorsOrSorry) + assert(registered(s"${leaf.name}/injectivity")) + assert(!registered(s"${node.name}/injectivity")) + assert(!registered(s"${declaration.name}/induction")) + + val induction = declaration.induction + val nodeInjectivity = node.injectivity + val elimination = declaration.elim + assert(!induction.hasErrorsOrSorry && !nodeInjectivity.hasErrorsOrSorry && !elimination.hasErrorsOrSorry) + assert(registered(s"${declaration.name}/induction")) + assert(registered(s"${node.name}/injectivity")) + val last = lisa.SetTheoryLibrary.theorems.all.size + assert(declaration.induction eq induction) + assert(leaf.injectivity eq leafInjectivity) + assert(node.injectivity eq nodeInjectivity) + assert(declaration.elim eq elimination) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + + test("single-clause constructor access reuses that branch without forcing other equations"): + val lazySimpleEquations = fun(A)(list.specialize(A), list(A)) { + Case(nil): + nil(A) + Case(cons, head, tail): + nil(A) + } + val clauses = lazySimpleEquations.semantic.clauses + def semanticEquation(index: Int) = s"${lazySimpleEquations.name}/case/$index" + assert(clauses.indices.forall(i => !registered(semanticEquation(i)))) + assert(!registered(s"${lazySimpleEquations.name}/cases")) + assert(!registered(s"${lazySimpleEquations.name}/eliminationTotal")) + + val requested = lazySimpleEquations.elim(cons) + assert(requested eq lazySimpleEquations.elim(clauses(1))) + assert(lazySimpleEquations.semantic.elim(cons.semantic) eq lazySimpleEquations.semantic.elim(clauses(1))) + assert(registered(semanticEquation(1))) + assert(!registered(semanticEquation(0))) + assert(!registered(s"${lazySimpleEquations.name}/elimination/nil/0")) + assert(!registered(s"${lazySimpleEquations.name}/cases")) + assert(!registered(s"${lazySimpleEquations.name}/eliminationTotal")) + + val nullary = lazySimpleEquations.elim(nil) + val total = lazySimpleEquations.elimTotal + assert(registered(semanticEquation(0))) + assert(registered(s"${lazySimpleEquations.name}/elimination/nil/0")) + assert(registered(s"${lazySimpleEquations.name}/cases")) + assert(registered(s"${lazySimpleEquations.name}/eliminationTotal")) + assert(!requested.hasErrorsOrSorry && !nullary.hasErrorsOrSorry && !total.hasErrorsOrSorry) + val last = lisa.SetTheoryLibrary.theorems.all.size + assert(lazySimpleEquations.elim(cons) eq requested) + assert(lazySimpleEquations.elimTotal eq total) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + + test("nested constructor groups force only their clauses and reject foreign requests without proofs"): + val lazyNestedEquations = fun(A)(list.specialize(A), list(A)) { + Case(nil): + nil(A) + Case(cons, head, nil(A)): + nil(A) + Case(cons, head, cons(A) * tail * inner): + nil(A) + } + val clauses = lazyNestedEquations.semantic.clauses + val branch = lazyNestedEquations.elim(clauses(1)) + assert(!registered(s"${lazyNestedEquations.name}/case/0")) + assert(!registered(s"${lazyNestedEquations.name}/case/2")) + val group = lazyNestedEquations.elim(cons) + assert(registered(s"${lazyNestedEquations.name}/constructor/cons")) + assert(!registered(s"${lazyNestedEquations.name}/cases")) + assert(registered(s"${lazyNestedEquations.name}/case/2")) + assert(!registered(s"${lazyNestedEquations.name}/case/0")) + assert(!registered(s"${lazyNestedEquations.name}/elimination/cons/2")) + assert(!branch.hasErrorsOrSorry && !group.hasErrorsOrSorry) + + val foreignConstructor = tru + val foreignClause = clauses.head.copy(payload = bool: Expr[Ind]) + val last = lisa.SetTheoryLibrary.theorems.all.size + assert(lazyNestedEquations.elim(clauses(1)) eq branch) + assert(lazyNestedEquations.elim(cons) eq group) + intercept[IllegalArgumentException](lazyNestedEquations.elim(foreignClause)) + intercept[IllegalArgumentException](lazyNestedEquations.semantic.elim(foreignClause)) + intercept[IllegalArgumentException](lazyNestedEquations.elim(foreignConstructor)) + intercept[IllegalArgumentException](lazyNestedEquations.semantic.elim(foreignConstructor.semantic)) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + clauses.foreach(clause => assert(!lazyNestedEquations.elim(clause).hasErrorsOrSorry)) + assert(!lazyNestedEquations.elimTotal.hasErrorsOrSorry) + assert(registered(s"${lazyNestedEquations.name}/case/0")) + assert(registered(s"${lazyNestedEquations.name}/elimination/cons/2")) + assert(registered(s"${lazyNestedEquations.name}/constructor/cons")) + assert(registered(s"${lazyNestedEquations.name}/cases")) + + test("empty datatypes and functions retain their lazy total theorems"): + val empty = adt("lazyEmptyDatatype", Seq.empty) + assert(!registered(s"${empty.name}/induction")) + val lazyEmptyFunction = fun(empty, ∅) {} + val total = lazyEmptyFunction.elimTotal + assert(!empty.induction.hasErrorsOrSorry && !empty.elim.hasErrorsOrSorry) + assert(registered(s"${empty.name}/induction")) + assert(!lazyEmptyFunction.intro.hasErrorsOrSorry && !total.hasErrorsOrSorry) + val last = lisa.SetTheoryLibrary.theorems.all.size + assert(lazyEmptyFunction.elimTotal eq total) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/DecisionTreeSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/DecisionTreeSuite.scala new file mode 100644 index 000000000..d1f5ae6a7 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/DecisionTreeSuite.scala @@ -0,0 +1,240 @@ +package lisa.maths.SetTheory.Types.ADT.PatternMatching + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Clause +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.DecisionTree +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.DecisionTree.Leaf +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.DecisionTree.Split +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.Pattern +import lisa.maths.SetTheory.Types.ADT.PatternMatching.semantics.PatternSystem +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT +import lisa.maths.SetTheory.Types.ADT.library.bool +import lisa.maths.SetTheory.Types.ADT.library.box +import lisa.maths.SetTheory.Types.ADT.library.cons +import lisa.maths.SetTheory.Types.ADT.library.fals +import lisa.maths.SetTheory.Types.ADT.library.list +import lisa.maths.SetTheory.Types.ADT.library.nat +import lisa.maths.SetTheory.Types.ADT.library.nil +import lisa.maths.SetTheory.Types.ADT.library.pack +import lisa.maths.SetTheory.Types.ADT.library.product +import lisa.maths.SetTheory.Types.ADT.library.succ +import lisa.maths.SetTheory.Types.ADT.library.tru +import lisa.maths.SetTheory.Types.ADT.library.void +import lisa.maths.SetTheory.Types.ADT.library.zero +import lisa.maths.SetTheory.Types.ADT.library.{pair => productPair} +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Checks the typed case analysis and source bindings retained for proof reconstruction. + */ +class DecisionTreeSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private val A, hd, hd2, tl, tl2, xs, x = variable[Ind] + + private def compileTree(domain: SpecializedADT[?], constructor: Constructor[?], cases: Seq[Seq[Expr[Ind]]]): DecisionTree = + val clauses = cases.map { args => + PatternValidation.resolveCase(constructor, args, domain).fold(error => fail(error), pattern => pattern) + } + DecisionTree.compile(domain, clauses).fold(error => fail(error), tree => tree) + + private def leaves(tree: DecisionTree): Vector[Leaf] = tree match + case leaf: Leaf => Vector(leaf) + case Split(_, _, branches) => branches.flatMap((_, child) => leaves(child)) + + test("constructor lookup preserves ownership and specialization without initializing unrelated wrappers"): + val targetType = nat.term + val first = adt("constructorIndexFirst", "A", Seq(("empty", Seq.empty), ("pack", Seq(("value", "A"))))) + val other = adt("constructorIndexOther", "A", Seq(("pack", Seq(("value", "A"))))) + val firstId = first.semantic.constructors(1).id + val otherId = other.semantic.constructors.head.id + val firstIntro = "constructorIndexFirst/pack/introduction" + val otherIntro = "constructorIndexOther/pack/introduction" + assert(lisa.SetTheoryLibrary.theorems.getFull(firstIntro).isEmpty) + assert(lisa.SetTheoryLibrary.theorems.getFull(otherIntro).isEmpty) + + val beforeLookup = lisa.SetTheoryLibrary.theorems.all.size + assert(ADT.getConstructor(other.id).isEmpty) + assert(PatternValidation.constructorApplication(other(targetType)).isLeft) + assert(lisa.SetTheoryLibrary.theorems.all.size == beforeLookup) + + val constructor = ADT.getConstructor(firstId).getOrElse(fail("Registered constructor was not found.")) + assert(constructor.adt eq first) + assert(constructor eq first.constructors(1)) + assert(lisa.SetTheoryLibrary.theorems.getFull(firstIntro).isDefined) + assert(lisa.SetTheoryLibrary.theorems.getFull(otherIntro).isEmpty) + + val afterLookup = lisa.SetTheoryLibrary.theorems.all.size + val (decoded, typeArgs, valueArgs) = PatternValidation + .constructorApplication(constructor(targetType) * x) + .fold(error => fail(error), identity) + assert(decoded eq constructor) + assert(typeArgs == Seq(targetType) && valueArgs == List(x)) + assert(ADT.getConstructor(firstId).exists(_ eq constructor)) + assert(lisa.SetTheoryLibrary.theorems.all.size == afterLookup) + assert(lisa.SetTheoryLibrary.theorems.getFull(otherIntro).isEmpty) + + val otherConstructor = ADT.getConstructor(otherId).getOrElse(fail("Second constructor was not found.")) + assert(otherConstructor.adt eq other) + assert(otherConstructor.id != constructor.id) + assert(PatternValidation.resolveCase(otherConstructor, Seq(x), first.specialize(targetType)).isLeft) + + test("an empty datatype retains an exhaustive split with no branches"): + val domain = void.specialize() + val tree = DecisionTree.compile(domain, Seq.empty).fold(error => fail(error), tree => tree) + tree match + case Split(path, actualDomain, branches) => + assert(path.isEmpty) + assert(actualDomain.base.id == void.id) + assert(actualDomain.typeArgs.isEmpty) + assert(branches.isEmpty) + case _ => fail("An empty datatype must retain its empty case analysis.") + + test("reordered clauses retain their source indices and ordered bindings across multiple fields"): + val domain = product.specialize(list(bool), list(bool)) + val constructor = productPair + val cases: Seq[Seq[Expr[Ind]]] = Seq( + Seq(cons(bool) * hd * tl, cons(bool) * hd2 * tl2), + Seq(nil(bool), nil(bool)), + Seq(nil(bool), cons(bool) * hd2 * tl2), + Seq(cons(bool) * hd * tl, nil(bool)) + ) + val language = lisa.SetTheoryLibrary.theory.language.toSet + val last = lisa.SetTheoryLibrary.theorems.all.size + val registered = ADT.allADTs.toSet + val tree = compileTree(domain, constructor, cases) + assert( + leaves(tree).sortBy(_.clauseIndex) == Vector( + Leaf(0, Vector(hd -> List(0, 0), tl -> List(0, 1), hd2 -> List(1, 0), tl2 -> List(1, 1))), + Leaf(1, Vector.empty), + Leaf(2, Vector(hd2 -> List(1, 0), tl2 -> List(1, 1))), + Leaf(3, Vector(hd -> List(0, 0), tl -> List(0, 1))) + ) + ) + assert(lisa.SetTheoryLibrary.theory.language.toSet == language) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + assert(ADT.allADTs.toSet == registered) + + test("a binder retains its whole subtree when other disjoint clauses inspect that subtree"): + val domain = product.specialize(list(bool), bool) + val tree = compileTree( + domain, + productPair, + Seq( + Seq(xs, tru), + Seq(nil(bool), fals), + Seq(cons(bool) * hd * tl, fals) + ) + ) + val expected = Map( + 0 -> Vector(xs -> List(0)), + 1 -> Vector.empty, + 2 -> Vector(hd -> List(0, 0), tl -> List(0, 1)) + ) + val selected = leaves(tree) + assert(selected.map(_.clauseIndex).toSet == expected.keySet) + selected.foreach(leaf => assert(leaf.bindings == expected(leaf.clauseIndex))) + + test("nested splits retain the constructor identity and explicit type arguments at each occurrence"): + val domain = box.specialize(box(A)) + val tree = compileTree(domain, pack, Seq(Seq(pack(A) * x))) + tree match + case Split(rootPath, rootDomain, Vector((outer, Split(innerPath, innerDomain, Vector((inner, leaf: Leaf)))))) => + assert(rootPath.isEmpty) + assert(rootDomain.base.id == box.id) + assert(rootDomain.typeArgs == Seq(box(A))) + assert(innerPath == List(0)) + assert(innerDomain.base.id == box.id) + assert(innerDomain.typeArgs == Seq(A)) + assert(outer.id == pack.id && inner.id == pack.id) + assert(leaf == Leaf(0, Vector(x -> List(0, 0)))) + case _ => fail("Expected one specialized box split at each of the two constructor occurrences.") + + test("mapping clause bodies shares resolved patterns, decision trees, and body-independent proofs"): + val domain = nat.specialize() + val successor = Pattern.fromResolved(PatternValidation.resolveCase(succ, Seq(x), domain).fold(error => fail(error), identity)) + val base = Pattern.fromResolved(PatternValidation.resolveCase(zero, Seq.empty, domain).fold(error => fail(error), identity)) + val system = PatternSystem + .compile(domain, Seq(Clause(successor, x: Expr[Ind]), Clause(base, zero: Expr[Ind]))) + .fold(error => fail(error), identity) + val coverage = system.coverage + val selection = system.branchSelectionSchema(succ.semantic) + val incompatibility = system.incompatible(successor, base) + val mapped = system.map(body => succ * body) + + assert(mapped.clauses.map(_.payload) == Seq(succ * x, succ * zero)) + assert(mapped.patterns.zip(system.patterns).forall((left, right) => left eq right)) + assert(mapped.decisionTree eq system.decisionTree) + assert(mapped.coverage eq coverage) + assert(mapped.branchSelectionSchema(succ.semantic) eq selection) + assert(mapped.incompatible(successor, base) eq incompatibility) + assert(!coverage.hasErrorsOrSorry && !selection.hasErrorsOrSorry && !incompatibility.hasErrorsOrSorry) + + test("branch selection reuses one schema across inputs without capturing type or pattern variables"): + val parameter = Variable[Ind]("branchInput") + val domain = list.specialize(parameter) + val shapes = Seq( + nil -> Seq.empty[Expr[Ind]], + cons -> Seq(hd, nil(parameter)), + cons -> Seq(hd, cons(parameter) * hd2 * tl2) + ) + val patterns = shapes.map { (constructor, args) => + Pattern.fromResolved(PatternValidation.resolveCase(constructor, args, domain).fold(error => fail(error), identity)) + } + val system = PatternSystem + .compile(domain, patterns.map(pattern => Clause(pattern, zero: Expr[Ind]))) + .fold(error => fail(error), identity) + val schema = system.branchSelectionSchema(cons.semantic) + val schematicInputs = schema.statement.freeTermVars - parameter + assert(schematicInputs.size == 1) + val input = schematicInputs.head + val innerBinder = patterns.last.variables2.last + val conflictingTerm = cons(parameter) * innerBinder * nil(parameter) + val checked = Theorem.generated(True) { proof ?=> + val last = lisa.SetTheoryLibrary.theorems.all.size + for subject <- Seq(xs, conflictingTerm, input) do + val instance = system.branchSelectionFor(cons.semantic, subject) + val statement = instance.statement + assert(statement.freeTermVars.contains(parameter)) + assert(subject.freeTermVars.subsetOf(statement.freeTermVars)) + have(statement) by Restate.from(instance) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + have(thesis) by Restate + } + assert(!checked.hasErrorsOrSorry) + assert(system.map(identity).branchSelectionSchema(cons.semantic) eq schema) + val foreign = tru.semantic + val last = lisa.SetTheoryLibrary.theorems.all.size + intercept[IllegalArgumentException](system.branchSelectionSchema(foreign)) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + + test("constructor input typing specializes the existing theorem without registering wrappers"): + val domain = list.specialize(A) + val pattern = Pattern.fromResolved(PatternValidation.resolveCase(cons, Seq(hd, tl), domain).fold(error => fail(error), identity)) + val introduction = cons.introApp + val checked = Theorem.generated(True) { + val last = lisa.SetTheoryLibrary.theorems.all.size + for head <- Seq(x, A) do + val instance = pattern.inputTypingAt(Seq(head, xs), list(A)) + have((head :: A, xs :: list(A)) |- cons(A) * head * xs :: list(A)) by Restate.from(instance) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + have(thesis) by Restate + } + assert(!introduction.hasErrorsOrSorry && !checked.hasErrorsOrSorry) + + test("nested recursive agreement points require SelfRef fields throughout their paths"): + val recursive = Pattern.fromResolved( + PatternValidation.resolveCase(succ, Seq(succ * x), nat.specialize()).fold(error => fail(error), identity) + ) + val payload = Pattern.fromResolved( + PatternValidation.resolveCase(pack, Seq(succ * x), box.specialize(nat)).fold(error => fail(error), identity) + ) + assert(recursive.recursiveAgreementPoints(nat) == recursive.variables2.drop(recursive.arity)) + assert(recursive.recursiveAgreementPoints(nat).size == 1) + assert(payload.recursiveAgreementPoints(nat).isEmpty) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/ProofChecks.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/ProofChecks.scala new file mode 100644 index 000000000..af423fac3 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/ProofChecks.scala @@ -0,0 +1,12 @@ +package lisa.maths.SetTheory.Types.ADT + +import lisa.utils.prooflib.Theorem +import lisa.utils.prooflib.Thm + +/** + * Checks both front errors and kernel admission dependencies in generated proofs. + */ +object ProofChecks: + extension (theorem: Theorem) def hasErrorsOrSorry: Boolean = theorem.errors.nonEmpty || theorem.kernel.usesSorry + + extension (theorem: Thm) def hasErrorsOrSorry: Boolean = theorem.kernel.usesSorry diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/ProofInitializationSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/ProofInitializationSuite.scala new file mode 100644 index 000000000..cc38a59d4 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/ProofInitializationSuite.scala @@ -0,0 +1,26 @@ +package lisa.maths.SetTheory.Types.ADT + +import lisa.SetTheoryLibrary +import lisa.maths.SetTheory.Cardinal.UniverseRank +import lisa.maths.SetTheory.Functions.Sigma +import org.scalatest.funsuite.AnyFunSuite + +/** + * Executes the shared ADT proofs, including lemmas not forced by a small declaration. + */ +class ProofInitializationSuite extends AnyFunSuite: + test("initialize height and recursion proofs without errors or admissions"): + height.proofs.ProofsInitialization.initialize() + recursion.proofs.ProofsInitialization.initialize() + val generated = SetTheoryLibrary.theorems.all.filter(_.file.value.replace('\\', '/').contains("/src/main/scala/lisa/maths/SetTheory/Types/ADT/")).toSeq + assert(generated.nonEmpty) + for theorem <- generated do + withClue(s"${theorem.fullName.value}: ") { + assert(theorem.errors.isEmpty, theorem.errors.mkString("\n")) + assert(!theorem.kernel.usesSorry) + } + + test("execute the repaired dependent-sum and universe-level proofs"): + for theorem <- Seq(Sigma.membership, UniverseRank.levelIsOrdinal) do + assert(theorem.errors.isEmpty, theorem.errors.mkString("\n")) + assert(!theorem.kernel.usesSorry) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/RobustnessSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/RobustnessSuite.scala new file mode 100644 index 000000000..e7c74ed06 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/RobustnessSuite.scala @@ -0,0 +1,226 @@ +package lisa.maths.SetTheory.Types.ADT + +import lisa.maths.SetTheory.Functions.Pi.->: +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.library.bool +import lisa.maths.SetTheory.Types.ADT.library.cons +import lisa.maths.SetTheory.Types.ADT.library.list +import lisa.maths.SetTheory.Types.ADT.library.nat +import lisa.maths.SetTheory.Types.ADT.library.nil +import lisa.maths.SetTheory.Types.ADT.library.succ +import lisa.maths.SetTheory.Types.ADT.library.tru +import lisa.maths.SetTheory.Types.ADT.library.zero +import lisa.maths.SetTheory.Types.Tactics +import lisa.maths.SetTheory.Types.TypingHelpers +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Exercises binder collisions and recursive equality beneath nested abstractions. + */ +class RobustnessSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private val ignored, point, inner, u, v = variable[Ind] + + for name <- Seq("n", "m", "h") do + test(s"constructor field $name is independent of carrier and height proof variables"): + val A = variable[Ind] + val field = Variable[Ind](name) + val declaration = adt( + s"robustConstructor/$name", + "A", + Seq( + ("leaf", Seq((name, "A"))), + ("branch", Seq((name, SelfRef), ("other", SelfRef))) + ) + ) + val Seq(leaf, branch) = declaration.constructors: @unchecked + val defined = recFun(declaration, declaration(A))(using sourcecode.Name(s"robustConstructorCopy/$name")) { self => + Case(leaf, field): + leaf(A) * field + Case(branch, field, inner): + branch(A) * (self * field) * (self * inner) + } + val leafValue = leaf(bool) * tru + val typing = Theorem.generated(branch(bool) * leafValue * leafValue :: declaration(bool)) { + have(thesis) by Tactics.Typecheck.prove + } + val computation = Theorem.generated(defined(bool) * leafValue === leafValue) { + have(thesis) by Tautology.from(defined.elim(leaf).of(bool).of(field := tru), tru.intro) + } + assert(!typing.hasErrorsOrSorry && !computation.hasErrorsOrSorry && !defined.intro.hasErrorsOrSorry) + assert(!declaration.elim.hasErrorsOrSorry && !declaration.induction.hasErrorsOrSorry) + assert(!leaf.injectivity.hasErrorsOrSorry && !branch.injectivity.hasErrorsOrSorry) + assert(!declaration.disjointness(leaf, branch).hasErrorsOrSorry) + + test("formerly reserved names and suffixed names can coexist in one constructor"): + val names = Seq("n", "n1", "n2", "m", "m1", "h", "h1", "h2") + val declaration = adt( + "robustConstructorHeightNames", + "A", + Seq( + ("leaf", names.map(_ -> "A")), + ("branch", names.map(_ -> SelfRef)) + ) + ) + val Seq(leaf, branch) = declaration.constructors: @unchecked + assert(!leaf.intro.hasErrorsOrSorry && !branch.intro.hasErrorsOrSorry) + assert(!leaf.injectivity.hasErrorsOrSorry && !branch.injectivity.hasErrorsOrSorry) + assert(!declaration.elim.hasErrorsOrSorry && !declaration.induction.hasErrorsOrSorry) + assert(!declaration.disjointness(leaf, branch).hasErrorsOrSorry) + + for name <- Seq( + "f0", + "nVar", + "kVar", + "jVar", + "hist", + "yVar", + "a", + "f", + "x", + "y", + "h", + "defVar", + "pointParam", + "indexParam", + "sliceVar", + "pointInput", + "leftFun", + "rightFun", + "vVar", + "pairWitness", + "k1", + "k2" + ) + do + test(s"function parameter $name remains free throughout proof construction"): + val parameter = Variable[Ind](name) + val defined = fun(parameter)(nat.specialize(), list(parameter))(using sourcecode.Name(s"robustParameter/$name")) { + Case(zero): + nil(parameter) + Case(succ, ignored): + nil(parameter) + } + val computation = Theorem.generated(defined(bool) * (succ * zero) === nil(bool)) { + have(thesis) by Tautology.from(defined.elim(succ).of(bool).of(ignored := zero), zero.intro) + } + assert(!defined.intro.hasErrorsOrSorry && !computation.hasErrorsOrSorry) + + test("recursive functions preserve a type parameter named like the seed binder"): + val parameter = Variable[Ind]("f0") + val robustRecursiveParameter = recFun(parameter)(nat.specialize(), list(parameter)) { self => + Case(zero): + nil(parameter) + Case(succ, ignored): + self * ignored + } + val computation = Theorem.generated(robustRecursiveParameter(bool) * (succ * zero) === robustRecursiveParameter(bool) * zero) { + have(thesis) by Tautology.from(robustRecursiveParameter.elim(succ).of(bool).of(ignored := zero), zero.intro) + } + assert(!robustRecursiveParameter.intro.hasErrorsOrSorry && !computation.hasErrorsOrSorry) + + for name <- Seq("x", "h", "nVar", "head1", "head2", "tail1", "tail2") do + test(s"specialized domain parameter $name is distinct from height and constructor variables"): + val parameter = Variable[Ind](name) + val defined = fun(parameter)(list.specialize(parameter), list(parameter))(using sourcecode.Name(s"robustDomain/$name")) { + Case(nil): + nil(parameter) + Case(cons, u, v): + nil(parameter) + } + val computation = Theorem.generated(defined(bool) * nil(bool) === nil(bool)) { + have(thesis) by Tautology.from(defined.elim(nil).of(bool)) + } + assert(!defined.intro.hasErrorsOrSorry && !computation.hasErrorsOrSorry) + + test("specialization preserves a value binder named like the original type parameter"): + val parameter = Variable[Ind]("robustElement") + val sourceParameter = list.typeVariablesSeq.head + val robustSourceParameter = fun(parameter)(list.specialize(parameter), list(parameter)) { + Case(nil): + nil(parameter) + Case(cons, sourceParameter, inner): + cons(parameter) * sourceParameter * inner + } + val input = cons(bool) * tru * nil(bool) + val computation = Theorem.generated(robustSourceParameter(bool) * input === input) { + have(thesis) by Tautology.from( + robustSourceParameter.elim(cons).of(bool).of(sourceParameter := tru, inner := nil(bool)), + tru.intro, + nil.intro.of(bool) + ) + } + assert(!robustSourceParameter.intro.hasErrorsOrSorry && !computation.hasErrorsOrSorry) + + test("nested recursion preserves a type parameter named like a constructor argument"): + val parameter = Variable[Ind]("head2") + val robustNestedParameter = recFun(parameter)(list.specialize(parameter), list(parameter)) { self => + Case(nil): + nil(parameter) + Case(cons, u, nil(parameter)): + nil(parameter) + Case(cons, u, cons(parameter) * v * inner): + self * inner + } + val tail = cons(bool) * tru * nil(bool) + val input = cons(bool) * tru * tail + val branch = robustNestedParameter.patternFor(Case(cons, u, cons(parameter) * v * inner)) + val computation = Theorem.generated(robustNestedParameter(bool) * input === robustNestedParameter(bool) * nil(bool)) { + val tailTyped = have(tail :: list(bool)) by Tactics.Typecheck.prove + have(thesis) by Tautology.from( + robustNestedParameter.elim(branch).of(bool).of(u := tru, branch.topBinders(1) := tail, v := tru, inner := nil(bool)), + tru.intro, + nil.intro.of(bool), + tailTyped + ) + } + assert(!robustNestedParameter.intro.hasErrorsOrSorry && !computation.hasErrorsOrSorry) + + test("constructor predicates do not capture another constructor's arguments"): + val declaration = adt( + "robustCarrierCapture", + "A", + Seq( + ("one", Seq(("x2", "A"))), + ("two", Seq(("x", "A"), ("y", "A"))) + ) + ) + val Seq(one, two) = declaration.constructors: @unchecked + assert(!one.intro.hasErrorsOrSorry && !two.intro.hasErrorsOrSorry) + assert(!one.injectivity.hasErrorsOrSorry && !two.injectivity.hasErrorsOrSorry) + assert(!declaration.elim.hasErrorsOrSorry && !declaration.disjointness(one, two).hasErrorsOrSorry) + + for depth <- Seq(2, 3) do + test(s"recursive body equality works beneath $depth nested lambdas"): + val binders = (0 until depth).map(i => Variable[Ind](s"robustLambdaArg$i")) + def abstractions(body: Expr[Ind]): Expr[Ind] = + binders.foldRight(body)((binder, innerBody) => TypingHelpers.fun(binder :: nat.term, innerBody)) + def applications(head: Expr[Ind]): Expr[Ind] = binders.foldLeft(head)(_ * _) + val resultType = binders.foldRight(nat.term: Expr[Ind])((_, typ) => nat.term ->: typ) + val defined = recFun(nat, resultType)(using sourcecode.Name(s"robustNestedLambdas$depth")) { self => + Case(zero): + abstractions(zero) + Case(succ, ignored): + abstractions(succ * applications(self * ignored)) + } + val computation = Theorem.generated(defined * (succ * zero) === abstractions(succ * applications(defined * zero))) { + have(thesis) by Tautology.from(defined.elim(succ).of(ignored := zero), zero.intro) + } + assert(!defined.intro.hasErrorsOrSorry && !computation.hasErrorsOrSorry) + + for ambient <- Seq(succ.semantic.variables2.head, Variable[Ind]("t")) do + test(s"induction preserves the ambient variable ${ambient.id}"): + val premise = ambient === zero + val checked = Theorem.generated((point :: nat, premise) |- premise) { + have(thesis) by Induction(point, nat) { + Case(zero) subproof { have(thesis) by Hypothesis } + Case(succ, zero) subproof { have(thesis) by Hypothesis } + Case(succ, succ * inner) subproof { have(thesis) by Hypothesis } + } + } + assert(!checked.hasErrorsOrSorry) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/TheoremInstancesSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/TheoremInstancesSuite.scala new file mode 100644 index 000000000..90e8f76a1 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/TheoremInstancesSuite.scala @@ -0,0 +1,122 @@ +package lisa.maths.SetTheory.Types.ADT + +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT.library.bool +import lisa.maths.SetTheory.Types.ADT.library.cons +import lisa.maths.SetTheory.Types.ADT.library.list +import lisa.maths.SetTheory.Types.ADT.library.nat +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.TypeSubstitution +import lisa.maths.SetTheory.Types.ADT.support.InterfaceHelpers.instantiate +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.N +import lisa.maths.SetTheory.Types.ADT.support.core.Utils.wellTypedFormula +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Checks that specialized facts reuse their schemas without registering theorem wrappers. + */ +class TheoremInstancesSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private val x, y, z, h, g, n, m = variable[Ind] + + test("empty and identity instantiation return the original theorem"): + val base = Theorem.generated(x === y |- x === y) { + have(thesis) by Hypothesis + } + val checked = Theorem.generated(base.statement) { + val before = lisa.SetTheoryLibrary.theorems.all.size + val empty = instantiate(base, Seq.empty) + val identity = instantiate(base, Seq(x := x, y := y)) + assert(empty.asInstanceOf[AnyRef] eq base.thm) + assert(identity.asInstanceOf[AnyRef] eq base.thm) + assert(lisa.SetTheoryLibrary.theorems.all.size == before) + have(thesis) by Restate.from(identity) + } + assert(!checked.hasErrorsOrSorry) + + test("one substitution list remains simultaneous while chained instances remain sequential"): + val base = Theorem.generated(x === y |- x === y) { + have(thesis) by Hypothesis + } + val checked = Theorem.generated(y === z |- y === z) { + val before = lisa.SetTheoryLibrary.theorems.all.size + val simultaneous = instantiate(base, Seq(x := y, y := z)) + val sequential = instantiate(base, Seq(x := y)).of(y := z) + val lastWins = instantiate(base, Seq(x := z, x := x)) + assert(simultaneous.statement.left == Set(y === z)) + assert(sequential.statement.left == Set(z === z)) + assert(lastWins.statement.left == Set(x === y)) + assert(lisa.SetTheoryLibrary.theorems.all.size == before) + have(z === z |- z === z) by Restate.from(sequential) + have(base.statement) by Restate.from(lastWins) + have(thesis) by Restate.from(simultaneous) + } + assert(!checked.hasErrorsOrSorry) + + test("height validity specializes in separate proofs without registering wrappers"): + val height = list.semantic.height + val parameter = list.typeVariablesSeq.head + for target <- Seq(bool, nat) do + val substitutions: Seq[TypeSubstitution] = Seq(parameter := target) + val heightFunction = height.function.substitute(substitutions*) + val checked = Theorem.generated(height.predicateAt(substitutions)(heightFunction)) { + val base = height.validAt(Seq.empty) + val identity = height.validAt(Seq(parameter := parameter)) + assert(base.asInstanceOf[AnyRef] eq identity.asInstanceOf[AnyRef]) + val before = lisa.SetTheoryLibrary.theorems.all.size + val specialized = height.validAt(substitutions) + val repeated = height.validAt(substitutions) + assert(specialized.statement == repeated.statement) + assert(lisa.SetTheoryLibrary.theorems.all.size == before) + have(thesis) by Restate.from(repeated) + } + assert(!checked.hasErrorsOrSorry) + + test("constructor height schemas are shared across arguments and proof contexts"): + val constructor = cons.semantic + val height = list.semantic.height + val parameter = list.typeVariablesSeq.head + for target <- Seq(bool, nat) do + val substitutions: Seq[TypeSubstitution] = Seq(parameter := target) + val stageTyping = constructor.heightTypingFormula(app(h)(n)).substitute(substitutions*) + val resultTyping = wellTypedFormula(constructor.semanticSignature2).substitute(substitutions*) + val checked = Theorem.generated((height.predicateAt(substitutions)(h), n ∈ N, stageTyping) |- resultTyping) { + def exercise(using proof: lisa.SetTheoryLibrary.Proof): Unit = + val typing = constructor.semanticTypingFromHeightAt(substitutions)(h, n) + val equality = constructor.appliedEqualityFromStructuralAt(substitutions)(h, n, x) + val recursive = constructor.recursiveArgInHeightAt(substitutions)(h, n) + for fact <- Seq(typing, equality, recursive) do have(fact.statement) by Restate.from(fact) + + val before = lisa.SetTheoryLibrary.theorems.all.size + val repeated = Seq( + constructor.semanticTypingFromHeightAt(substitutions)(g, m), + constructor.appliedEqualityFromStructuralAt(substitutions)(g, m, y), + constructor.recursiveArgInHeightAt(substitutions)(g, m) + ) + assert(lisa.SetTheoryLibrary.theorems.all.size == before) + for fact <- repeated do have(fact.statement) by Restate.from(fact) + have(thesis) by Restate.from(typing) + exercise + } + assert(!checked.hasErrorsOrSorry) + + test("specialized accessors still reject invalid type substitutions before proving anything"): + val height = list.semantic.height + val constructor = cons.semantic + val parameter = list.typeVariablesSeq.head + val foreign = Variable[Ind]("theoremInstanceForeign") + val boolType = bool + val natType = nat + val checked = Theorem.generated(x === x) { + val before = lisa.SetTheoryLibrary.theorems.all.size + intercept[IllegalArgumentException](height.validAt(Seq(foreign := foreign))) + intercept[IllegalArgumentException](height.zeroAt(Seq(parameter := boolType, parameter := natType))) + intercept[IllegalArgumentException](constructor.semanticTypingFromHeightAt(Seq(foreign := foreign))(h, n)) + assert(lisa.SetTheoryLibrary.theorems.all.size == before) + have(thesis) by RightRefl + } + assert(!checked.hasErrorsOrSorry) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/encoding/CommonHeightSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/encoding/CommonHeightSuite.scala new file mode 100644 index 000000000..243f61026 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/encoding/CommonHeightSuite.scala @@ -0,0 +1,97 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.SetTheory.Functions.Predef.app +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT.support.core.Utils._ +import lisa.maths.SetTheory.Types.ADT.syntax.AST.ConstructorArg +import lisa.maths.SetTheory.Types.ADT.syntax.AST.SelfRef +import lisa.maths.SetTheory.Types.ADT.syntax.AST.TypeArg +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Executes the common-height proof for each combination of recursive and payload fields. + */ +class CommonHeightSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private def checkCommonHeight(name: String, fields: Seq[ConstructorArg]): Unit = + val A, B = variable[Ind] + val variables = fields.indices.map(i => Variable[Ind](s"field$i")) + val alternatives = fields.indices.map(i => Variable[Ind](s"otherField$i")) + val constructor = new SyntacticConstructor(fields, variables, alternatives, 0, name) + val declaration = new SyntacticADT(name, Seq(constructor), Seq(A, B)) + val expected = declaration.isHeight(h) |- ( + declaration.constructorVarsInDomain(constructor, declaration.term) <=> + ∃(n, n ∈ N /\ declaration.constructorVarsInDomain(constructor, app(h)(n))) + ) + val theorem = Theorem.generated(expected) { + val before = lisa.SetTheoryLibrary.theorems.all.size + val commonHeight = declaration.termsHaveHeight(constructor, h) + assert(lisa.SetTheoryLibrary.theorems.all.size == before) + have(thesis) by Restate.from(commonHeight) + } + assert(!theorem.hasErrorsOrSorry) + assert(!declaration.intro(constructor).hasErrorsOrSorry) + + test("nullary constructors have a common height"): + checkCommonHeight("commonHeightNullary", Seq.empty) + + test("payload-only constructors have a common height without recursive fields"): + checkCommonHeight("commonHeightPayloads", Seq(TypeArg("A"), TypeArg("B"), TypeArg("A"), TypeArg("B"))) + + test("interleaved payload and recursive fields share a common height"): + checkCommonHeight("commonHeightMixed", Seq(TypeArg("A"), SelfRef, TypeArg("B"), SelfRef, TypeArg("A"))) + + test("several recursive fields share a common height"): + checkCommonHeight("commonHeightRecursive", Seq(SelfRef, SelfRef, SelfRef)) + + test("argument renaming preserves simultaneous type, argument, and height substitutions"): + val A, payload, recursive, otherPayload, otherRecursive = variable[Ind] + val name = "commonHeightSimultaneous" + val constructor = new SyntacticConstructor( + Seq(TypeArg("A"), SelfRef), + Seq(payload, recursive), + Seq(otherPayload, otherRecursive), + 0, + name + ) + val declaration = new SyntacticADT(name, Seq(constructor), Seq(A)) + val schema = declaration.isHeight(h) |- ( + declaration.constructorVarsInDomain(constructor, declaration.term) <=> + ∃(n, n ∈ N /\ declaration.constructorVarsInDomain(constructor, app(h)(n))) + ) + val substitutions = Seq(A := recursive, payload := A, recursive := otherPayload, h := otherRecursive) + val checked = Theorem.generated(schema.substitute(substitutions*)) { + val before = lisa.SetTheoryLibrary.theorems.all.size + val instance = declaration.termsHaveHeight(constructor, otherRecursive, substitutions) + assert(lisa.SetTheoryLibrary.theorems.all.size == before) + have(thesis) by Restate.from(instance) + } + assert(!checked.hasErrorsOrSorry) + + test("height witnesses stay distinct from fields and their indexed variants"): + val A, heightWitness, stageWitness, payload = variable[Ind] + val variables = Seq(h, Variable[Ind](Identifier("h", 1)), n, Variable[Ind](Identifier("n", 1)), m, Variable[Ind](Identifier("m", 1))) + val alternatives = variables.indices.map(i => Variable[Ind](s"argument$i")) + val name = "commonHeightFreshWitnesses" + val constructor = new SyntacticConstructor( + Seq(TypeArg("A")) ++ Seq.fill(variables.size - 1)(SelfRef), + variables, + alternatives, + 0, + name + ) + val declaration = new SyntacticADT(name, Seq(constructor), Seq(A)) + def fieldsIn(domain: Expr[Ind]): Expr[Prop] = + declaration.constructorVarsInDomain(constructor, domain).substitute(h := payload) + val checked = Theorem.generated( + declaration.isHeight(heightWitness) |- ( + fieldsIn(declaration.term) <=> ∃(stageWitness, stageWitness ∈ N /\ fieldsIn(app(heightWitness)(stageWitness))) + ) + ) { + have(thesis) by Restate.from(declaration.termsHaveHeight(constructor, heightWitness, Seq(h := payload))) + } + assert(!checked.hasErrorsOrSorry && !declaration.intro(constructor).hasErrorsOrSorry) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/encoding/ExhaustivenessSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/encoding/ExhaustivenessSuite.scala new file mode 100644 index 000000000..d2dba7089 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/encoding/ExhaustivenessSuite.scala @@ -0,0 +1,70 @@ +package lisa.maths.SetTheory.Types.ADT.encoding + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.library.nat +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Executes constructor exhaustiveness for empty, payload, and recursive datatypes. + */ +class ExhaustivenessSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private val subject, a, b, left, right = variable[Ind] + + test("an empty datatype has no inhabitants"): + val declaration = adt("exhaustivenessEmpty", Seq.empty) + val checked = Theorem.generated(subject :: declaration |- False) { + have(thesis) by Restate.from(declaration.elim.of(subject)) + } + assert(!declaration.semantic.elim.hasErrorsOrSorry && !checked.hasErrorsOrSorry) + + test("a nullary datatype exhausts exactly its constructors"): + val declaration = adt("exhaustivenessNullary", Seq("off" -> Seq.empty, "on" -> Seq.empty)) + val Seq(off, on) = declaration.constructors: @unchecked + val checked = Theorem.generated(subject :: declaration |- (subject === off) \/ (subject === on)) { + have(thesis) by Restate.from(declaration.elim.of(subject)) + } + assert(!checked.hasErrorsOrSorry) + + test("mixed constructor cases retain every payload and recursive typing"): + val declaration = adt( + "exhaustivenessMixed", + "A", + Seq( + "empty" -> Seq.empty, + "payload" -> Seq("first" -> "A", "second" -> "A"), + "node" -> Seq("left" -> SelfRef, "right" -> SelfRef) + ) + ) + val Seq(empty, payload, node) = declaration.constructors: @unchecked + val carrier = declaration(nat) + val expected = (subject === empty(nat)) \/ + ∃(a, ∃(b, ((a :: nat) /\ (b :: nat)) /\ (subject === payload(nat) * a * b))) \/ + ∃(left, ∃(right, ((left :: carrier) /\ (right :: carrier)) /\ (subject === node(nat) * left * right))) + val checked = Theorem.generated(subject :: carrier |- expected) { + have(thesis) by Restate.from(declaration.elim.of(nat, subject)) + } + assert(!checked.hasErrorsOrSorry) + + test("constructor witnesses do not capture the subject or another constructor's arguments"): + val declaration = adt( + "exhaustivenessCapture", + "A", + Seq( + "one" -> Seq("x2" -> "A"), + "two" -> Seq("x" -> "A", "y" -> "A") + ) + ) + val Seq(one, two) = declaration.constructors: @unchecked + val x2 = Variable[Ind]("x2") + val expected = ∃(a, (a :: nat) /\ (x2 === one(nat) * a)) \/ + ∃(a, ∃(b, ((a :: nat) /\ (b :: nat)) /\ (x2 === two(nat) * a * b))) + val checked = Theorem.generated(x2 :: declaration(nat) |- expected) { + have(thesis) by Restate.from(declaration.elim.of(nat, x2)) + } + assert(!checked.hasErrorsOrSorry) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/height/FiniteUnionSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/height/FiniteUnionSuite.scala new file mode 100644 index 000000000..5caecc2c5 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/height/FiniteUnionSuite.scala @@ -0,0 +1,47 @@ +package lisa.maths.SetTheory.Types.ADT.height + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Checks finite-union inclusion proofs and reuse of their shared schema. + */ +class FiniteUnionSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private val x, y, z = variable[Ind] + + test("component inclusion handles every position, duplicates, and the empty set"): + val components: Seq[Expr[Ind]] = Seq(x, ∅, y, x, z) + for elems <- Seq(components, Seq[Expr[Ind]](∅), Seq(x)); member <- elems.distinct do + val checked = Theorem.generated(x === y |- member ⊆ FiniteUnion.unionList(elems)) { + lisa.utils.prooflib.ProofHelpers.assume(x === y) + val inclusion = FiniteUnion.memberSubsetOfUnionList(elems, member) + have(thesis) by Weakening(inclusion) + } + assert(!checked.hasErrorsOrSorry) + + test("missing components are rejected, including the implicit empty seed"): + val checked = Theorem.generated(x === x) { + intercept[IllegalArgumentException](FiniteUnion.memberSubsetOfUnionList(Seq.empty, x)) + intercept[IllegalArgumentException](FiniteUnion.memberSubsetOfUnionList(Seq(x, y), z)) + intercept[IllegalArgumentException](FiniteUnion.memberSubsetOfUnionList(Seq(x, y), ∅)) + have(thesis) by RightRefl + } + assert(!checked.hasErrorsOrSorry) + + test("component proofs reuse the subset schema across proof contexts"): + for elems <- Seq(Seq(x, y, z), Seq(z, x, y)) do + val checked = Theorem.generated(elems.head ⊆ FiniteUnion.unionList(elems)) { + val first = FiniteUnion.memberSubsetOfUnionList(elems, elems.head) + val before = lisa.SetTheoryLibrary.theorems.all.size + for member <- elems do + val inclusion = FiniteUnion.memberSubsetOfUnionList(elems, member) + have(inclusion.statement) by Restate.from(inclusion) + assert(lisa.SetTheoryLibrary.theorems.all.size == before) + have(thesis) by Restate.from(first) + } + assert(!checked.hasErrorsOrSorry) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/height/HeightWitnessSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/height/HeightWitnessSuite.scala new file mode 100644 index 000000000..cd705cddb --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADT/height/HeightWitnessSuite.scala @@ -0,0 +1,39 @@ +package lisa.maths.SetTheory.Types.ADT.height + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT.encoding.SyntacticADT +import lisa.maths.SetTheory.Types.ADT.encoding.SyntacticConstructor +import lisa.maths.SetTheory.Types.ADT.syntax.AST.SelfRef +import lisa.maths.SetTheory.Types.ADT.syntax.AST.TypeArg +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Executes the height specification and retained existence and uniqueness theorems. + */ +class HeightWitnessSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private def checkHeightProofs(declaration: SyntacticADT): Unit = + assert(!declaration.heightValid.hasErrorsOrSorry) + assert(!declaration.heightExists.hasErrorsOrSorry) + assert(!declaration.heightUniqueness.hasErrorsOrSorry) + assert(!declaration.heightExistsOne.hasErrorsOrSorry) + + test("retain height existence and uniqueness for an empty datatype"): + checkHeightProofs(new SyntacticADT("heightWitnessEmpty", Seq.empty, Seq.empty)) + + test("retain height existence and uniqueness with payload and recursive fields"): + val A, payload1, tail1, payload2, tail2 = variable[Ind] + val name = "heightWitnessList" + val empty = new SyntacticConstructor(Seq.empty, Seq.empty, Seq.empty, 0, name) + val cons = new SyntacticConstructor( + Seq(TypeArg("A"), SelfRef), + Seq(payload1, tail1), + Seq(payload2, tail2), + 1, + name + ) + checkHeightProofs(new SyntacticADT(name, Seq(empty, cons), Seq(A))) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADTRegressionSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADTRegressionSuite.scala new file mode 100644 index 000000000..2f95040ec --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/ADTRegressionSuite.scala @@ -0,0 +1,941 @@ +package lisa.maths.SetTheory.Types + +import lisa.maths.SetTheory.Functions.Pi.->: +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.interface.ADTFunction +import lisa.maths.SetTheory.Types.ADT.interface.RecFunction +import lisa.maths.SetTheory.Types.ADT.interface.SpecializedADT +import lisa.maths.SetTheory.Types.ADT.library.bool +import lisa.maths.SetTheory.Types.ADT.library.box +import lisa.maths.SetTheory.Types.ADT.library.cons +import lisa.maths.SetTheory.Types.ADT.library.fals +import lisa.maths.SetTheory.Types.ADT.library.list +import lisa.maths.SetTheory.Types.ADT.library.nat +import lisa.maths.SetTheory.Types.ADT.library.nil +import lisa.maths.SetTheory.Types.ADT.library.pack +import lisa.maths.SetTheory.Types.ADT.library.product +import lisa.maths.SetTheory.Types.ADT.library.succ +import lisa.maths.SetTheory.Types.ADT.library.tru +import lisa.maths.SetTheory.Types.ADT.library.void +import lisa.maths.SetTheory.Types.ADT.library.zero +import lisa.maths.SetTheory.Types.ADT.library.{pair => productPair} +import lisa.maths.SetTheory.Types.ADT.library.{union => unionType} +import lisa.maths.SetTheory.Types.ADT.support.semantics.DefinedSymbol +import lisa.maths.SetTheory.Types.ADT.syntax.AST.ConstructorArg +import lisa.maths.SetTheory.Types.ADT.syntax.AST.TypeArg +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Executes generated ADT proofs for specialization, nested patterns, and binder hygiene. + */ +class ADTRegressionSuite extends AnyFunSuite: + private given OutputManager = new StringOutputManager + + private val A, hd, hd2, tl, k, q = variable[Ind] + + test("declare ordinary function parameters independently of a monomorphic domain"): + val B = variable[Ind] + val regressionEmptyLists: ADTFunction[Ind >>: Ind] = fun(B)(nat, list(B)) { + Case(zero): + nil(B) + Case(succ, k): + nil(B) + } + assert(regressionEmptyLists.typeVariablesSeq == Seq(B)) + assert(regressionEmptyLists.sort == list.sort) + assert(!regressionEmptyLists.intro.hasErrorsOrSorry) + val typing = Theorem.generated(regressionEmptyLists(bool) :: (nat ->: list(bool))) { + have(thesis) by Restate.from(regressionEmptyLists.intro.of(bool)) + } + val computation = Theorem.generated(regressionEmptyLists(bool) * zero === nil(bool)) { + have(thesis) by Restate.from(regressionEmptyLists.elim(zero).of(bool)) + } + assert(!typing.hasErrorsOrSorry && !computation.hasErrorsOrSorry) + + test("declare recursive function parameters independently of a monomorphic domain"): + val B = variable[Ind] + val regressionRecursiveEmptyLists: RecFunction[Ind >>: Ind] = recFun(B)(nat, list(B)) { self => + Case(zero): + nil(B) + Case(succ, k): + self * k + } + assert(regressionRecursiveEmptyLists.typeVariablesSeq == Seq(B)) + assert(!regressionRecursiveEmptyLists.intro.hasErrorsOrSorry) + val computation = Theorem.generated(regressionRecursiveEmptyLists(bool) * (succ * zero) === nil(bool)) { + val step = have(regressionRecursiveEmptyLists(bool) * (succ * zero) === regressionRecursiveEmptyLists(bool) * zero) by + Tautology.from(regressionRecursiveEmptyLists.elim(succ).of(bool).of(k := zero), zero.intro) + have(thesis) by Congruence.from(step, regressionRecursiveEmptyLists.elim(zero).of(bool)) + } + assert(!computation.hasErrorsOrSorry) + + test("preserve explicit parameter order and distinct input and output parameters"): + val B = variable[Ind] + val regressionDifferentTypes: ADTFunction[Ind >>: Ind >>: Ind] = fun((B, A))(list.specialize(A), list(B)) { + Case(nil): + nil(B) + Case(cons, hd, tl): + nil(B) + } + val regressionDifferentTypesRec: RecFunction[Ind >>: Ind >>: Ind] = recFun((B, A))(list.specialize(A), list(B)) { self => + Case(nil): + nil(B) + Case(cons, hd, tl): + self * tl + } + assert(regressionDifferentTypes.typeVariablesSeq == Seq(B, A)) + assert(regressionDifferentTypesRec.typeVariablesSeq == Seq(B, A)) + assert(regressionDifferentTypes.sort == unionType.sort) + val typing = Theorem.generated(regressionDifferentTypes(bool, nat) :: (list(nat) ->: list(bool))) { + have(thesis) by Tactics.Typecheck.prove + } + val recursiveTyping = Theorem.generated(regressionDifferentTypesRec(bool, nat) :: (list(nat) ->: list(bool))) { + have(thesis) by Tactics.Typecheck.prove + } + assert(!typing.hasErrorsOrSorry && !recursiveTyping.hasErrorsOrSorry) + + test("specializing the domain does not rewrite an independent parameter with the same name"): + val regressionIndependentA = fun(A)(list.specialize(bool), list(A)) { + Case(nil): + nil(A) + Case(cons, hd, tl): + nil(A) + } + val regressionIndependentARec = recFun(A)(list.specialize(bool), list(A)) { self => + Case(nil): + nil(A) + Case(cons, hd, nil(bool)): + nil(A) + Case(cons, hd, cons(bool) * hd2 * tl): + self * tl + } + val computation = Theorem.generated(regressionIndependentA(nat) * nil(bool) === nil(nat)) { + have(thesis) by Restate.from(regressionIndependentA.elim(nil).of(nat)) + } + val recursiveComputation = Theorem.generated(regressionIndependentARec(nat) * nil(bool) === nil(nat)) { + have(thesis) by Restate.from(regressionIndependentARec.elim(nil).of(nat)) + } + assert(!computation.hasErrorsOrSorry && !recursiveComputation.hasErrorsOrSorry) + + test("preserve parameters in nested patterns and recursion on compound specialized domains"): + val regressionParametricNestedUnbox = recFun(A)(box.specialize(list(A)), list(A)) { _ => + Case(pack, nil(A)): + nil(A) + Case(pack, cons(A) * hd * tl): + tl + } + assert(!regressionParametricNestedUnbox.intro.hasErrorsOrSorry) + assert(!regressionParametricNestedUnbox.elim(Case(pack, cons(A) * hd * tl)).hasErrorsOrSorry) + val regressionListsLength = recFun(A)(list.specialize(list(A)), nat) { self => + Case(nil): + zero + Case(cons, hd, tl): + succ * (self * tl) + } + val computation = Theorem.generated(regressionListsLength(bool) * (cons(list(bool)) * nil(bool) * nil(list(bool))) === succ * zero) { + val step = have( + regressionListsLength(bool) * (cons(list(bool)) * nil(bool) * nil(list(bool))) === succ * (regressionListsLength(bool) * nil(list(bool))) + ) by Tautology.from(regressionListsLength.elim(cons).of(bool).of(hd := nil(bool), tl := nil(list(bool))), nil.intro.of(bool), nil.intro.of(list(bool))) + have(thesis) by Congruence.from(step, regressionListsLength.elim(nil).of(bool)) + } + assert(!computation.hasErrorsOrSorry) + + test("allow a partially specialized domain with fewer function parameters"): + val inl = unionType.constructors(0) + val inr = unionType.constructors(1) + val regressionPartialSpecialization: ADTFunction[Ind >>: Ind] = fun(A)(unionType.specialize(bool, A), bool) { + Case(inl, hd): + hd + Case(inr, hd): + fals + } + val typing = Theorem.generated(regressionPartialSpecialization(nat) :: (unionType(bool, nat) ->: bool)) { + have(thesis) by Restate.from(regressionPartialSpecialization.intro.of(nat)) + } + assert(!typing.hasErrorsOrSorry) + + test("reject undeclared return type parameters before proof generation"): + val B = variable[Ind] + val ordinary = intercept[IllegalArgumentException] { + val regressionUndeclaredReturn = fun(nat, list(B)) { + Case(zero): + nil(B) + Case(succ, k): + nil(B) + } + } + val recursive = intercept[IllegalArgumentException] { + val regressionUndeclaredReturnRec = recFun(nat, list(B)) { self => + Case(zero): + nil(B) + Case(succ, k): + self * k + } + } + for error <- Seq(ordinary, recursive) do assert(error.getMessage.contains("undeclared free variables: B")) + + test("reject undeclared body variables, duplicate parameters, and parameter shadowing"): + val B = variable[Ind] + val body = intercept[IllegalArgumentException] { + val regressionUndeclaredBody = fun(nat, nat) { + Case(zero): + B + Case(succ, k): + zero + } + } + assert(body.getMessage.contains("undeclared free variables: B")) + val duplicate = intercept[IllegalArgumentException] { + val regressionDuplicateParameters = fun((B, B))(nat, list(B)) { + Case(zero): + nil(B) + Case(succ, k): + nil(B) + } + } + assert(duplicate.getMessage.contains("duplicate parameters")) + val shadow = intercept[IllegalArgumentException] { + val regressionShadowedParameter = fun(A)(box.specialize(A), A) { + Case(pack, A): + A + } + } + assert(shadow.getMessage.contains("shadows a parameter")) + + private def checkTypeArgumentArity(arguments: Seq[Expr[Ind]], applications: Seq[Seq[Expr[Ind]] => Expr[Ind]]): Unit = + for application <- applications do + assert(application(arguments).sort == nat.sort) + val invalidArguments = Seq(arguments.dropRight(1), arguments :+ nat).filter(_.size != arguments.size) + for invalid <- invalidArguments do + val error = intercept[IllegalArgumentException](application(invalid)) + assert(error.getMessage.contains(s"expects ${arguments.size}")) + assert(error.getMessage.contains(s"got ${invalid.size}")) + + test("check type argument arity in ADT applications and specializations"): + for datatype <- Seq(nat, list, unionType) do + checkTypeArgumentArity( + datatype.typeVariablesSeq.map(_ => nat), + Seq( + datatype.termAt, + datatype.applySeq, + args => datatype(args*), + args => datatype.specialize(args*).term + ) + ) + + test("check constructor type arguments while allowing curried value application"): + for constructor <- Seq(succ, cons, unionType.constructors.head) do + checkTypeArgumentArity( + constructor.typeVariablesSeq.map(_ => nat), + Seq( + constructor.termAt, + constructor.applySeq, + args => constructor(args*), + args => constructor.specialize(args*).term + ) + ) + val partiallyApplied = cons.specialize(nat)(zero) + assert(partiallyApplied.sort == nat.sort) + val typing = Theorem.generated(partiallyApplied :: (list(nat) ->: list(nat))) { + have(thesis) by Tactics.Typecheck.prove + } + assert(!typing.hasErrorsOrSorry) + + test("check defined symbol parameters independently of the result sort"): + val value = new DefinedSymbol("regressionArityValue", Seq(A), A) + val proposition = new DefinedSymbol("regressionArityProposition", Seq(A), A === A) + val predicate = new DefinedSymbol("regressionArityPredicate", Seq(A), λ(hd, hd ∈ A)) + val closed = new DefinedSymbol("regressionArityClosed", Seq.empty, ∅) + for (symbol, arguments, resultSort) <- Seq( + (value, Seq(nat), A.sort), + (proposition, Seq(nat), (A === A).sort), + (predicate, Seq(nat), λ(hd, hd ∈ A).sort), + (closed, Seq.empty, ∅.sort) + ) + do + assert(symbol.term(arguments).sort == resultSort) + for invalid <- Seq(arguments.dropRight(1), arguments :+ nat).filter(_.size != arguments.size) do + val error = intercept[IllegalArgumentException](symbol.term(invalid)) + assert(error.getMessage.contains(s"expects ${arguments.size}")) + assert(error.getMessage.contains(s"got ${invalid.size}")) + + test("look up nested equations independently of binder names"): + val regressionNestedPredecessor = fun(nat, nat) { + Case(zero): + zero + Case(succ, zero): + zero + Case(succ, succ * k): + k + } + checkTypeArgumentArity( + Seq.empty, + Seq( + regressionNestedPredecessor.termAt, + regressionNestedPredecessor.applySeq, + args => regressionNestedPredecessor(args*), + regressionNestedPredecessor.semantic.term + ) + ) + val original = regressionNestedPredecessor.elim(Case(succ, succ * k)) + val renamed = regressionNestedPredecessor.elim(Case(succ, succ * q)) + assert(renamed == original) + assert(!renamed.hasErrorsOrSorry) + val outer = regressionNestedPredecessor.patternFor(Case(succ, succ * q)).binders.head + val computation = Theorem.generated(q :: nat |- regressionNestedPredecessor * (succ * (succ * q)) === q) { + lisa.utils.prooflib.ProofHelpers.assume(q :: nat) + have(succ * q :: nat) by Tactics.Typecheck.prove + have(thesis) by Tautology.from(lastStep, renamed.of(k := q, outer := succ * q)) + } + assert(!computation.hasErrorsOrSorry) + + for query <- Seq( + Case(pack, succ * q), + Case(succ, pack(nat) * q), + Case(succ, succ * (succ * q)), + Case(succ, succ), + Case(succ, succ * q * hd) + ) + do intercept[IllegalArgumentException](regressionNestedPredecessor.elim(query)) + + test("preserve type arguments and a bijection of all pattern binders during lookup"): + val regressionLookupList = fun(list, nat) { + Case(nil): + zero + Case(cons, hd, nil(A)): + zero + Case(cons, hd, cons(A) * hd2 * tl): + succ * zero + } + val original = regressionLookupList.elim(Case(cons, hd, cons(A) * hd2 * tl)) + assert(regressionLookupList.elim(Case(cons, k, cons(A) * q * hd)) == original) + assert(regressionLookupList.elim(Case(cons, hd2, cons(A) * hd * tl)) == original) + assert(!original.hasErrorsOrSorry) + + val B = variable[Ind] + for query <- Seq( + Case(cons, k, cons(B) * q * hd), + Case(cons, k, cons(bool) * q * hd), + Case(cons, hd, cons(A) * hd * tl), + Case(cons, k, cons(A) * q * q), + Case(cons, k, cons(A) * q), + Case(cons, k, cons(A) * q * hd * tl), + Case(nil, k) + ) + do intercept[IllegalArgumentException](regressionLookupList.elim(query)) + + test("construct a polymorphic recursion seed from a data-carrying constructor"): + val regressionRecursiveUnbox = recFun(box, A) { _ => + Case(pack, hd): + hd + } + assert(!regressionRecursiveUnbox.intro.hasErrorsOrSorry) + val computation = Theorem.generated(hd :: A |- regressionRecursiveUnbox(A) * (pack(A) * hd) === hd) { + have(thesis) by Restate.from(regressionRecursiveUnbox.elim(pack).of(A)) + } + assert(!computation.hasErrorsOrSorry) + + test("construct a recursion seed with empty domain and codomain"): + val regressionEmptyUnbox = recFun(box.specialize(∅), ∅) { _ => + Case(pack, hd): + hd + } + assert(!regressionEmptyUnbox.intro.hasErrorsOrSorry) + assert(!regressionEmptyUnbox.elim(pack).hasErrorsOrSorry) + + test("recurse on trees whose leaves carry the only target inhabitant"): + val tree = adt( + "regressionSeedTree", + "A", + Seq( + ("leaf", Seq(("value", "A"))), + ("node", Seq(("left", "regressionSeedTree"), ("right", "regressionSeedTree"))) + ) + ) + val leaf = tree.constructors(0) + val node = tree.constructors(1) + val regressionLeftmost = recFun(tree, A) { self => + Case(leaf, hd): + hd + Case(node, k, q): + self * k + } + assert(!regressionLeftmost.intro.hasErrorsOrSorry) + assert(!regressionLeftmost.elim(leaf).hasErrorsOrSorry) + assert(!regressionLeftmost.elim(node).hasErrorsOrSorry) + + test("construct a recursion seed through nested base patterns"): + val regressionNestedUnbox = recFun(box.specialize(list(bool)), list(bool)) { _ => + Case(pack, nil(bool)): + nil(bool) + Case(pack, cons(bool) * hd * tl): + tl + } + assert(!regressionNestedUnbox.intro.hasErrorsOrSorry) + assert(!regressionNestedUnbox.elim(Case(pack, cons(bool) * hd * tl)).hasErrorsOrSorry) + + test("recurse through several nested binders of the same constructor"): + val tree = adt( + "regressionNestedBinary", + Seq( + ("leaf", Seq.empty), + ("node", Seq(("left", "regressionNestedBinary"), ("right", "regressionNestedBinary"))) + ) + ) + val leaf = tree.constructors(0) + val node = tree.constructors(1) + val regressionNestedBranches = recFun(tree, tree) { self => + Case(leaf): + leaf + Case(node, leaf, tl): + self * tl + Case(node, node * k * q, tl): + node * (self * k) * (self * q) + } + val pairOfLeaves = node * leaf * leaf + val query = Case(node, node * k * q, tl) + val pattern = regressionNestedBranches.patternFor(query) + val witnesses: Seq[Expr[Ind]] = Seq(pairOfLeaves, leaf, leaf, leaf) + val substitutions = pattern.binders.zip(witnesses).map((v, term) => v := term) + val computation = Theorem.generated(regressionNestedBranches * (node * pairOfLeaves * leaf) === pairOfLeaves) { + val pairTyped = have(pairOfLeaves :: tree) by Tactics.Typecheck.prove + val step = have( + regressionNestedBranches * (node * pairOfLeaves * leaf) === + node * (regressionNestedBranches * leaf) * (regressionNestedBranches * leaf) + ) by Tautology.from(regressionNestedBranches.elim(query).of(substitutions*), pairTyped, leaf.intro) + have(thesis) by Congruence.from(step, regressionNestedBranches.elim(leaf)) + } + assert(!computation.hasErrorsOrSorry && !regressionNestedBranches.intro.hasErrorsOrSorry) + + test("specializing a payload to an ADT does not introduce an induction hypothesis"): + var checked = false + val reflexivity = Theorem.generated(k :: box(nat) |- k === k) { + have(thesis) by Induction(k, box.specialize(nat)) { + Case(pack, hd) subproof { + assert(thesis.left.exists(isSame(_, hd :: nat))) + assert(!thesis.left.exists(isSame(_, hd === hd))) + checked = true + have(thesis) by Tautology + } + } + } + assert(checked && !reflexivity.hasErrorsOrSorry) + + test("define recursion from Void into the empty set"): + val regressionVoidRecursion = recFun(void, ∅) { _ => () } + assert(!regressionVoidRecursion.intro.hasErrorsOrSorry) + + test("define recursion with only recursive constructors and an empty target"): + val loop = adt("regressionSeedLoop", Seq(("again", Seq(("tail", "regressionSeedLoop"))))) + val again = loop.constructors.head + val regressionEmptyRecursion = recFun(loop, ∅) { self => + Case(again, k): + self * k + } + assert(!regressionEmptyRecursion.intro.hasErrorsOrSorry) + assert(!regressionEmptyRecursion.elim(again).hasErrorsOrSorry) + + test("define an ordinary function with empty domain and codomain"): + val regressionOrdinaryEmptyUnbox = fun(box.specialize(∅), ∅) { + Case(pack, hd): + hd + } + val typing = Theorem.generated(regressionOrdinaryEmptyUnbox :: (box(∅) ->: ∅)) { + have(thesis) by Tactics.Typecheck.prove + } + val computation = Theorem.generated(hd :: ∅ |- regressionOrdinaryEmptyUnbox * (pack(∅) * hd) === hd) { + have(thesis) by Restate.from(regressionOrdinaryEmptyUnbox.elim(pack)) + } + assert(!typing.hasErrorsOrSorry && !computation.hasErrorsOrSorry) + + test("define an ordinary function from Void into the empty set"): + val regressionOrdinaryVoid = fun(void, ∅) { () } + val typing = Theorem.generated(regressionOrdinaryVoid :: (void ->: ∅)) { + have(thesis) by Tactics.Typecheck.prove + } + assert(!typing.hasErrorsOrSorry) + assert(!regressionOrdinaryVoid.elimTotal.hasErrorsOrSorry) + + test("freshen the hidden self-reference against ordinary pattern binders"): + val payload = Variable[Ind]("regressionHiddenSelfRecSelf") + val regressionHiddenSelf = fun(box.specialize(nat), nat) { + Case(pack, payload): + payload + } + val computation = Theorem.generated(regressionHiddenSelf * (pack(nat) * zero) === zero) { + have(thesis) by Tautology.from(regressionHiddenSelf.elim(pack).of(payload := zero), zero.intro) + } + assert(!computation.hasErrorsOrSorry) + + test("do not interpret an undeclared ordinary body variable as recursive self-reference"): + val unbound = Variable[Ind]("regressionHiddenFreeRecSelf") + rejectWithoutRegistration("undeclared free variables: regressionHiddenFreeRecSelf") { + val regressionHiddenFree = fun(nat, nat) { + Case(zero): + unbound + Case(succ, k): + zero + } + } + + test("define a plain function on a specialized ADT"): + val regressionUnbox = fun(box.specialize(bool), bool) { + Case(pack, hd): + hd + } + checkTypeArgumentArity( + Seq.empty, + Seq( + regressionUnbox.termAt, + regressionUnbox.applySeq, + args => regressionUnbox(args*), + regressionUnbox.semantic.term + ) + ) + assert(!regressionUnbox.intro.hasErrorsOrSorry) + assert(regressionUnbox.typeVariablesSeq.isEmpty) + val computation = Theorem.generated(regressionUnbox * (pack(bool) * tru) === tru) { + have(thesis) by Tautology.from(regressionUnbox.elim(pack).of(hd := tru), tru.intro) + } + assert(!computation.hasErrorsOrSorry) + + test("define a recursive function with plain specialized patterns"): + val regressionLength = recFun(list.specialize(bool), nat) { self => + Case(nil): + zero + Case(cons, hd, tl): + succ * (self * tl) + } + checkTypeArgumentArity( + Seq.empty, + Seq( + regressionLength.termAt, + regressionLength.applySeq, + args => regressionLength(args*), + regressionLength.semantic.term + ) + ) + assert(!regressionLength.intro.hasErrorsOrSorry) + assert(!regressionLength.elim(cons).hasErrorsOrSorry) + assert(regressionLength.elim(Case(cons, k, q)) == regressionLength.elim(Case(cons, hd, tl))) + for args <- Seq(Seq(hd), Seq(hd, tl, k), Seq(hd, hd)) do intercept[IllegalArgumentException](regressionLength.elim(Case(cons, args*))) + + test("allow opaque type parameters at nested pattern leaves"): + val regressionListShape = fun(list, nat) { + Case(nil): + zero + Case(cons, hd, nil(A)): + zero + Case(cons, hd, cons(A) * hd2 * tl): + zero + } + assert(!regressionListShape.intro.hasErrorsOrSorry) + assert(!regressionListShape.elim(Case(cons, hd, cons(A) * hd2 * tl)).hasErrorsOrSorry) + + test("allow function types at nested pattern leaves"): + val regressionFunctionListShape = fun(list.specialize(nat ->: nat), nat) { + Case(nil): + zero + Case(cons, hd, nil(nat ->: nat)): + zero + Case(cons, hd, cons(nat ->: nat) * hd2 * tl): + zero + } + assert(!regressionFunctionListShape.intro.hasErrorsOrSorry) + + test("recurse through a nested pattern with opaque payloads"): + val regressionNestedLength = recFun(list, nat) { self => + Case(nil): + zero + Case(cons, hd, nil(A)): + succ * zero + Case(cons, hd, cons(A) * hd2 * tl): + succ * (succ * (self * tl)) + } + assert(!regressionNestedLength.intro.hasErrorsOrSorry) + assert(!regressionNestedLength.elim(Case(cons, hd, cons(A) * hd2 * tl)).hasErrorsOrSorry) + assert( + regressionNestedLength.elim(Case(cons, k, cons(A) * q * hd)) == + regressionNestedLength.elim(Case(cons, hd, cons(A) * hd2 * tl)) + ) + + test("retain different specializations of a repeated nested constructor"): + val regressionDoubleUnbox = fun(A)(box.specialize(box(A)), A) { + Case(pack, pack(A) * hd): + hd + } + val original = regressionDoubleUnbox.elim(Case(pack, pack(A) * hd)) + assert(regressionDoubleUnbox.elim(Case(pack, pack(A) * q)) == original) + val B = variable[Ind] + intercept[IllegalArgumentException](regressionDoubleUnbox.elim(Case(pack, pack(B) * q))) + intercept[IllegalArgumentException](regressionDoubleUnbox.elim(Case(pack, pack(box(A)) * q))) + val outer = regressionDoubleUnbox.patternFor(Case(pack, pack(A) * hd)).binders.head + val computation = Theorem.generated(hd :: A |- regressionDoubleUnbox(A) * (pack(box(A)) * (pack(A) * hd)) === hd) { + lisa.utils.prooflib.ProofHelpers.assume(hd :: A) + have(pack(A) * hd :: box(A)) by Tactics.Typecheck.prove + have(thesis) by Tautology.from(lastStep, original.of(A).of(outer := pack(A) * hd)) + } + assert(!regressionDoubleUnbox.intro.hasErrorsOrSorry && !computation.hasErrorsOrSorry) + + test("preserve case bodies when nested cases inspect both constructor fields"): + val regressionSecondBoolean = fun(product.specialize(bool, bool), bool) { + Case(productPair, fals, tru): + tru + Case(productPair, tru, fals): + fals + Case(productPair, tru, tru): + tru + Case(productPair, fals, fals): + fals + } + for (left, right) <- Seq((fals, tru), (tru, fals), (tru, tru), (fals, fals)) do + val query = Case(productPair, left, right) + val binders = regressionSecondBoolean.patternFor(query).binders + val equation = regressionSecondBoolean.elim(query) + val computation = Theorem.generated(regressionSecondBoolean * (productPair(bool, bool) * left * right) === right) { + have(thesis) by Tautology.from(equation.of(binders(0) := left, binders(1) := right), tru.intro, fals.intro) + } + assert(!computation.hasErrorsOrSorry) + + test("prove all computations of an eight-leaf decision tree with reordered clauses"): + val booleans: Seq[Expr[Ind]] = Seq(fals, tru) + val cases = Seq((1, 1, 1), (0, 0, 0), (1, 0, 1), (0, 1, 0), (1, 1, 0), (0, 0, 1), (1, 0, 0), (0, 1, 1)) + val regressionBooleanParity = fun(product.specialize(bool, product(bool, bool)), bool) { + cases.foreach { (first, second, third) => + Case(productPair, booleans(first), productPair(bool, bool) * booleans(second) * booleans(third))( + booleans((first + second + third) % 2) + ) + } + } + for (first, second, third) <- cases.reverse do + val left = booleans(first) + val right = productPair(bool, bool) * booleans(second) * booleans(third) + val expected = booleans((first + second + third) % 2) + val query = Case(productPair, left, right) + val binders = regressionBooleanParity.patternFor(query).binders + val equation = regressionBooleanParity.elim(query) + val computation = Theorem.generated(regressionBooleanParity * (productPair(bool, product(bool, bool)) * left * right) === expected) { + val rightTyped = have(right :: product(bool, bool)) by Tactics.Typecheck.prove + have(thesis) by Tautology.from(equation.of(binders(0) := left, binders(1) := right), rightTyped, tru.intro, fals.intro) + } + assert(!computation.hasErrorsOrSorry) + assert(!regressionBooleanParity.intro.hasErrorsOrSorry) + + test("retain a fresh outer binder across nested induction callbacks and assembly"): + val inner = Variable[Ind]("succ/arg0") + val premise = variable[Prop] + val contextual = Theorem.generated((k :: nat, premise) |- premise) { + have(thesis) by Induction(k, nat) { + Case(succ, succ * inner) subproof { have(thesis) by Hypothesis } + Case(zero) subproof { have(thesis) by Hypothesis } + Case(succ, zero) subproof { have(thesis) by Hypothesis } + } + } + assert(!contextual.hasErrorsOrSorry) + + test("reconstruct whole-subtree binders after other clauses inspect the same field"): + val elementType = Variable[Ind]("fv0") + val xs = Variable[Ind]("scrutX") + val tail = Variable[Ind]("bsf0") + val regressionWholeSubtree = fun(elementType)(product.specialize(list(elementType), bool), list(elementType)) { + Case(productPair, cons(elementType) * hd * tail, fals): + tail + Case(productPair, xs, tru): + xs + Case(productPair, nil(elementType), fals): + nil(elementType) + } + val empty = nil(bool) + val singleton = cons(bool) * tru * empty + val checks: Seq[(Case, Expr[Ind], Expr[Ind], Seq[Expr[Ind]], Expr[Ind])] = Seq( + (Case(productPair, xs, tru), empty, tru, Seq(empty, tru), empty), + (Case(productPair, xs, tru), singleton, tru, Seq(singleton, tru), singleton), + (Case(productPair, nil(elementType), fals), empty, fals, Seq(empty, fals), empty), + (Case(productPair, cons(elementType) * hd * tail, fals), singleton, fals, Seq(singleton, fals, tru, empty), empty) + ) + for (query, input, flag, witnesses, result) <- checks do + val pattern = regressionWholeSubtree.patternFor(query) + val equation = regressionWholeSubtree.elim(query) + val substitutions = pattern.binders.zip(witnesses).map((v, term) => v := term) + val computation = Theorem.generated(regressionWholeSubtree(bool) * (productPair(list(bool), bool) * input * flag) === result) { + val emptyTyped = have(empty :: list(bool)) by Tactics.Typecheck.prove + val singletonTyped = have(singleton :: list(bool)) by Tactics.Typecheck.prove + have(thesis) by Tautology.from(equation.of(bool).of(substitutions*), emptyTyped, singletonTyped, tru.intro, fals.intro) + } + assert(!computation.hasErrorsOrSorry) + assert(!regressionWholeSubtree.intro.hasErrorsOrSorry) + + test("assemble reordered multi-field induction with whole-subtree binders and ambient variables"): + val scrutinee = Variable[Ind]("scrutX") + val elementType = Variable[Ind]("bsf0") + val ambient = Variable[Ind]("fv0") + val xs = variable[Ind] + val premise = ambient === elementType + val contextual = Theorem.generated((scrutinee :: product(list(elementType), bool), premise) |- premise) { + have(thesis) by Induction(scrutinee, product.specialize(list(elementType), bool)) { + Case(productPair, cons(elementType) * hd * tl, fals) subproof { have(thesis) by Hypothesis } + Case(productPair, xs, tru) subproof { have(thesis) by Hypothesis } + Case(productPair, nil(elementType), fals) subproof { have(thesis) by Hypothesis } + } + } + assert(!contextual.hasErrorsOrSorry) + + test("assemble nontrivial induction with inner pattern binders"): + val arg = Variable[Ind]("succ/arg0") + val nonzero = Theorem.generated(k :: nat |- !(succ * k === zero)) { + have(thesis) by Induction(k, nat) { + Case(zero) subproof { + have(zero :: nat) by Tactics.Typecheck.prove + have(thesis) by Tautology.from(lastStep, nat.disjointness(succ, zero).of(zero)) + } + Case(succ, zero) subproof { + lisa.utils.prooflib.ProofHelpers.assume(arg :: nat) + have(succ * arg :: nat) by Tactics.Typecheck.prove + have(thesis) by Tautology.from(lastStep, nat.disjointness(succ, zero).of(succ * arg)) + } + Case(succ, succ * q) subproof { + lisa.utils.prooflib.ProofHelpers.assume(arg :: nat) + have(succ * arg :: nat) by Tactics.Typecheck.prove + have(thesis) by Tautology.from(lastStep, nat.disjointness(succ, zero).of(succ * arg)) + } + } + } + assert(!nonzero.hasErrorsOrSorry) + + test("retain ambient assumptions during nested induction"): + val premise = variable[Prop] + val contextual = Theorem.generated((k :: nat, premise) |- premise) { + have(thesis) by Induction(k, nat) { + Case(zero) subproof { have(thesis) by Hypothesis } + Case(succ, zero) subproof { have(thesis) by Hypothesis } + Case(succ, succ * q) subproof { have(thesis) by Hypothesis } + } + } + assert(!contextual.hasErrorsOrSorry) + + test("eliminate several inner binders with opaque types during induction"): + val arg = Variable[Ind]("cons/arg1") + val membership = Theorem.generated(k :: list(A) |- k :: list(A)) { + have(thesis) by Induction(k, list.specialize(A)) { + Case(nil) subproof { have(thesis) by Tautology.from(nil.intro.of(A)) } + Case(cons, hd, nil(A)) subproof { + have(thesis) by Tautology.from(cons.introApp.of(cons.semantic.variables(0) := hd, cons.semantic.variables(1) := arg)) + } + Case(cons, hd, cons(A) * hd2 * tl) subproof { + have(thesis) by Tautology.from(cons.introApp.of(cons.semantic.variables(0) := hd, cons.semantic.variables(1) := arg)) + } + } + } + assert(!membership.hasErrorsOrSorry) + + test("freshen constructor proof placeholders against argument names"): + val regressionC = adt("regressionC", "A", Seq(("wrap", Seq(("c", "A"))))) + assert(!regressionC.constructors.head.intro.hasErrorsOrSorry) + assert(!regressionC.constructors.head.injectivity.hasErrorsOrSorry) + + test("freshen constructor extensionality variables against argument names"): + val regressionPoints = adt("regressionPoints", "A", Seq(("wrap", Seq(("curriedfn", "A"), ("pointarg0", "A"))))) + assert(!regressionPoints.constructors.head.intro.hasErrorsOrSorry) + assert(!regressionPoints.constructors.head.injectivity.hasErrorsOrSorry) + + test("keep the two constructor argument tuples disjoint"): + val regressionCopies = adt("regressionCopies", "A", Seq(("wrap", Seq(("c", "A"), ("c2", "A"))))) + val constructor = regressionCopies.constructors.head + assert(constructor.semantic.variables.toSet.intersect(constructor.semantic.variables2.toSet).isEmpty) + assert(!constructor.intro.hasErrorsOrSorry) + assert(!constructor.injectivity.hasErrorsOrSorry) + + test("keep constructor binders distinct from type parameters"): + val regressionParameter = adt("regressionParameter", "A", Seq(("wrap", Seq(("A", "A"))))) + assert(!regressionParameter.constructors.head.intro.hasErrorsOrSorry) + assert(!regressionParameter.constructors.head.injectivity.hasErrorsOrSorry) + + for argName <- Seq("a", "b", "d", "f", "g", "k", "r", "s", "t", "x", "y", "z", "α", "β") do + test(s"constructor argument $argName does not capture proof variables"): + val declaration = adt(s"regressionName/$argName", "A", Seq(("wrap", Seq((argName, "A"))))) + assert(!declaration.constructors.head.intro.hasErrorsOrSorry) + assert(!declaration.constructors.head.injectivity.hasErrorsOrSorry) + + private def rejectWithoutRegistration(message: String)(declaration: => Any): Unit = + val language = lisa.SetTheoryLibrary.theory.language.toSet + val last = lisa.SetTheoryLibrary.theorems.all.size + val registered = ADT.allADTs.toSet + val error = intercept[IllegalArgumentException](declaration) + assert(error.getMessage.contains(message), error.getMessage) + assert(lisa.SetTheoryLibrary.theory.language.toSet == language) + assert(lisa.SetTheoryLibrary.theorems.all.size == last) + assert(ADT.allADTs.toSet == registered) + + test("reject undeclared ADT parameters through both argument forms and allow corrected declarations"): + val invalidTypes: Seq[String | ConstructorArg] = Seq("Missing", TypeArg("Missing")) + for (invalid, index) <- invalidTypes.zipWithIndex do + val name = s"regressionUndeclaredADT$index" + rejectWithoutRegistration("argument 'value' refers to undeclared type parameter 'Missing'") { + adt(name, "A", Seq(("wrap", Seq(("value", invalid))))) + } + assert(ADT.getADT(name).isEmpty) + val corrected = adt(name, "A", Seq(("wrap", Seq(("value", TypeArg("A")))))) + assert(!corrected.constructors.head.intro.hasErrorsOrSorry) + + test("validate all constructor names and binders before generating proofs"): + rejectWithoutRegistration("duplicate constructor names") { + adt("regressionDuplicateConstructors", Seq(("wrap", Seq.empty), ("wrap", Seq.empty))) + } + rejectWithoutRegistration("regressionLateDuplicate/second has duplicate argument names") { + adt("regressionLateDuplicate", "A", Seq(("first", Seq.empty), ("second", Seq(("value", "A"), ("value", "A"))))) + } + rejectWithoutRegistration("empty constructor name") { + adt("regressionEmptyConstructor", Seq((" ", Seq.empty))) + } + rejectWithoutRegistration("empty argument name") { + adt("regressionEmptyArgument", "A", Seq(("wrap", Seq(("", "A"))))) + } + rejectWithoutRegistration("empty type variable name") { + adt("regressionEmptyParameter", "", Seq.empty) + } + rejectWithoutRegistration("duplicate type variables") { + adt("regressionDuplicateADTParameters", ("A", "A"), Seq.empty) + } + rejectWithoutRegistration("nonempty name") { + adt("", Seq.empty) + } + + private def rejectFunctionCases(domain: SpecializedADT[?], cases: Seq[Case], message: String): Unit = + rejectWithoutRegistration(message) { + val regressionInvalidFunctionCases = fun(domain, nat) { + cases.foreach(c => c(zero)) + } + } + rejectWithoutRegistration(message) { + val regressionInvalidRecursiveCases = recFun(domain, nat) { _ => + cases.foreach(c => c(zero)) + } + } + + test("reject wrong constructors and exact outer and nested arity mismatches"): + val cases = Seq( + Case(tru) -> "is not a constructor", + Case(succ) -> "expected 1 value argument(s), got 0", + Case(succ, k, q) -> "expected 1 value argument(s), got 2", + Case(succ, succ) -> "argument 1: Constructor nat/succ expects 1 value argument(s), got 0", + Case(succ, succ * k * q) -> "expects 1 value argument(s), got 2", + Case(succ, zero * k) -> "expects 0 value argument(s), got 1", + Case(succ, tru) -> "argument 1: bool/tru is not a constructor" + ) + for (invalid, message) <- cases do rejectFunctionCases(nat, Seq(Case(zero), invalid), message) + + test("reject unsupported nested expressions instead of interpreting them as binders"): + for term <- Seq(∅, k * q) do rejectFunctionCases(nat, Seq(Case(zero), Case(succ, term)), "argument 1: Unsupported pattern") + + test("check nested constructor specialization and preserve opaque binder types"): + rejectFunctionCases(list.specialize(bool), Seq(Case(nil), Case(cons, hd, nil(nat))), "argument 2: constructor type arguments") + rejectFunctionCases(list.specialize(bool), Seq(Case(nil), Case(cons, hd, nil.asInstanceOf[Expr[Ind]])), "expects 1 type argument(s), got 0") + rejectFunctionCases(list.specialize(A), Seq(Case(nil), Case(cons, zero, tl)), "argument 1: cannot match constructor nat/zero at non-ADT type A") + rejectFunctionCases(list.specialize(nat ->: nat), Seq(Case(nil), Case(cons, zero, tl)), "at non-ADT type") + + test("reject repeated binders across outer and nested pattern arguments"): + val cases = Seq(Case(cons, hd, hd), Case(cons, hd, cons(bool) * hd * tl), Case(cons, hd, cons(bool) * tl * tl)) + for invalid <- cases do rejectFunctionCases(list.specialize(bool), Seq(Case(nil), invalid), "repeated pattern binder") + + test("reject missing and overlapping unconditional cases before proof generation"): + rejectFunctionCases(nat, Seq(Case(zero)), "Case for nat/succ is missing") + rejectFunctionCases(nat, Seq(Case(zero), Case(zero), Case(succ, k)), "Overlapping unconditional cases for nat/zero") + + test("reject missing nested constructor combinations before registering functions"): + rejectFunctionCases(nat, Seq(Case(zero), Case(succ, zero)), "missing") + rejectFunctionCases( + product.specialize(bool, bool), + Seq( + Case(productPair, tru, tru), + Case(productPair, fals, tru), + Case(productPair, fals, fals) + ), + "missing" + ) + + test("reject overlapping nested cases independently of clause order"): + val cases = Seq(Case(nil), Case(cons, hd, nil(bool)), Case(cons, hd, tl)) + for ordered <- Seq(cases, cases.reverse) do rejectFunctionCases(list.specialize(bool), ordered, "overlap") + + test("distinguish nested constructors with the same short names in different datatypes"): + val leftType = adt("regressionDecisionLeft", Seq(("off", Seq.empty), ("on", Seq.empty))) + val rightType = adt("regressionDecisionRight", Seq(("off", Seq.empty), ("on", Seq.empty))) + val leftOff = leftType.constructors(0) + val leftOn = leftType.constructors(1) + val rightOff = rightType.constructors(0) + val rightOn = rightType.constructors(1) + val regressionDistinctConstructors = fun(product.specialize(leftType, rightType), bool) { + Case(productPair, leftOn, rightOff): + fals + Case(productPair, leftOff, rightOn): + tru + Case(productPair, leftOn, rightOn): + tru + Case(productPair, leftOff, rightOff): + fals + } + for (left, right, result) <- Seq( + (leftOff, rightOff, fals), + (leftOff, rightOn, tru), + (leftOn, rightOff, fals), + (leftOn, rightOn, tru) + ) + do + val query = Case(productPair, left, right) + val binders = regressionDistinctConstructors.patternFor(query).binders + val equation = regressionDistinctConstructors.elim(query) + val computation = Theorem.generated(regressionDistinctConstructors * (productPair(leftType, rightType) * left * right) === result) { + have(thesis) by Tautology.from(equation.of(binders(0) := left, binders(1) := right), left.intro, right.intro) + } + assert(!computation.hasErrorsOrSorry) + assert(!regressionDistinctConstructors.intro.hasErrorsOrSorry) + + for (description, conclusions) <- Seq( + "empty" -> Set.empty[Expr[Prop]], + "multiple" -> Set(k === k, k === q) + ) + do + test(s"reject induction goals with $description conclusions before invoking case callbacks"): + val checked = Theorem.generated(k === k) { proof ?=> + for assumptions <- Seq(Set.empty[Expr[Prop]], Set(k :: nat)) do + val goal = Sequent(assumptions, conclusions) + assert(Induction.inferArguments(goal, None, None).isEmpty) + assert(Induction.inferArguments(goal, Some(k), Some(nat.specialize())).isEmpty) + for tactic <- Seq(Induction(), Induction(k, nat)) do + var entered = false + val result = tactic { entered = true }(goal) + assert(!result.isValid) + assert(result.errors.exists(_.message.contains("exactly one formula on the right"))) + assert(!entered) + have(thesis) by RightRefl + } + assert(!checked.hasErrorsOrSorry) + + test("validate induction patterns before executing their subproofs"): + val cases = Seq( + Case(tru) -> "is not a constructor", + Case(nil, hd) -> "expected 0 value argument(s), got 1", + Case(cons, hd, hd) -> "repeated pattern binder", + Case(cons, hd, nil(nat)) -> "constructor type arguments", + Case(cons, hd, ∅) -> "Unsupported pattern" + ) + val validation = Theorem.generated(k :: list(bool) |- k === k) { + for (invalid, message) <- cases do + var entered = false + rejectWithoutRegistration(message) { + have(thesis) by Induction(k, list.specialize(bool)) { + invalid subproof { + entered = true + have(thesis) by Tautology + } + } + } + assert(!entered) + have(thesis) by Tautology + } + assert(!validation.hasErrorsOrSorry) diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/InductiveInfixSyntaxSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/InductiveInfixSyntaxSuite.scala new file mode 100644 index 000000000..900065a26 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/InductiveInfixSyntaxSuite.scala @@ -0,0 +1,203 @@ +package lisa.maths.SetTheory.Types + +import lisa.maths.SetTheory.SetTheory.{_, given} +import lisa.maths.SetTheory.Types.ADT.InductiveInfixSyntax.SelfRef +import lisa.maths.SetTheory.Types.ADT.InductiveInfixSyntax.inductive +import lisa.maths.SetTheory.Types.ADT.InductiveInfixSyntax.| +import lisa.maths.SetTheory.Types.ADT.ProofChecks._ +import lisa.maths.SetTheory.Types.ADT._ +import lisa.maths.SetTheory.Types.ADT.interface.ADT +import lisa.maths.SetTheory.Types.ADT.interface.Constructor +import lisa.maths.SetTheory.Types.Tactics.Typecheck +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Executes the comma-separated frontend without postfix imports or infix-warning suppression. + */ +class InductiveInfixSyntaxSuite extends AnyFunSuite { + private given OutputManager = new StringOutputManager + + private val A, B, C, D, E, n, head, tail, x, xs, y, z = variable[Ind] + + private val InfixNat = inductive( + | zero (), + | succ (n :: SelfRef) + ) + + private val InfixList = inductive(A)( + | nil (), + | cons (head :: A, tail :: SelfRef) + ) + + test("constructor names, binders, and sorts survive infix declarations") { + val nat: ADT[Ind] = InfixNat + val successor: Constructor[Ind] = InfixNat.succ + val list: ADT[Ind >>: Ind] = InfixList + val cons: Constructor[Ind >>: Ind] = InfixList.cons + assert(nat.name == "InfixNat") + assert(nat.constructors.map(_.semantic.name) == Seq("zero", "succ")) + assert(successor.semantic.variables == Seq(n)) + assert(cons.semantic.variables == Seq(head, tail)) + assert(list.typeVariablesSeq == Seq(A)) + assert(InfixNat.zero eq InfixNat.zero) + assertDoesNotCompile("InfixNat.zeor") + assertDoesNotCompile("val invalid: Expr[Ind] = InfixList") + assertDoesNotCompile("val invalid: Expr[Ind] = InfixList.nil") + } + + test("declarations are expressions and the registered owners of their constructors") { + summon[InductiveInfixSyntax.Declaration[Ind] <:< ADT[Ind]] + summon[InductiveInfixSyntax.Declaration[Ind] <:< Expr[Ind]] + summon[InductiveInfixSyntax.Declaration[Ind >>: Ind] <:< Expr[Ind >>: Ind]] + val nat: Expr[Ind] = InfixNat + val list: Expr[Ind >>: Ind] = InfixList + assert(nat eq InfixNat) + assert(list eq InfixList) + assert(ADT.getADT(InfixNat.id).exists(_ eq InfixNat)) + assert(ADT.getADT(InfixList.name).exists(_ eq InfixList)) + assert(InfixNat.zero.adt eq InfixNat) + assert(InfixList.cons.adt eq InfixList) + assert(InfixNat.constructors.head eq InfixNat.zero) + } + + test("typing and generated constructor theorems execute") { + val singleton = InfixList.cons(InfixNat) * InfixNat.zero * InfixList.nil(InfixNat) + val typing = Theorem.generated(singleton :: InfixList(InfixNat)) { + have(thesis) by Typecheck.prove + } + assert(!typing.hasErrorsOrSorry) + assert(!InfixNat.succ.injectivity.hasErrorsOrSorry) + assert(!InfixNat.disjointness(InfixNat.zero, InfixNat.succ).hasErrorsOrSorry) + assert(!InfixNat.elim.hasErrorsOrSorry && !InfixList.induction.hasErrorsOrSorry) + } + + test("recursive definitions, computation, and induction use the generated members") { + val infixListCopy = recFun(InfixList, InfixList(A)) { self => + Case(InfixList.nil): + InfixList.nil(A) + Case(InfixList.cons, head, tail): + InfixList.cons(A) * head * (self * tail) + } + val computation = Theorem.generated(infixListCopy(A) * InfixList.nil(A) === InfixList.nil(A)) { + have(thesis) by Restate.from(infixListCopy.elim(InfixList.nil).of(A)) + } + val identity = Theorem.generated(xs :: InfixList(A) |- infixListCopy(A) * xs === xs) { + have(thesis) by Induction(xs, InfixList.specialize(A)) { + Case(InfixList.nil) subproof { + have(thesis) by Restate.from(infixListCopy.elim(InfixList.nil).of(A)) + } + Case(InfixList.cons, head, tail) subproof { + lisa.maths.SetTheory.SetTheory.assume(head :: A, tail :: InfixList(A), infixListCopy(A) * tail === tail) + val step = have(infixListCopy(A) * (InfixList.cons(A) * head * tail) === InfixList.cons(A) * head * (infixListCopy(A) * tail)) by + Tautology.from(infixListCopy.elim(InfixList.cons).of(A)) + have(thesis) by Congruence.from(step) + } + } + } + assert(!computation.hasErrorsOrSorry && !identity.hasErrorsOrSorry && !infixListCopy.intro.hasErrorsOrSorry) + } + + test("field tuples preserve order and recursive fields use every parameter") { + val InfixTree = inductive((A, B))( + | leaf (head :: A, tail :: B), + | node (x :: SelfRef, y :: SelfRef, z :: SelfRef) + ) + assert(InfixTree.typeVariablesSeq == Seq(A, B)) + assert(InfixTree.node.semantic.variables == Seq(x, y, z)) + val leaf = InfixTree.leaf(InfixNat, InfixNat) * InfixNat.zero * InfixNat.zero + val typing = Theorem.generated(InfixTree.node(InfixNat, InfixNat) * leaf * leaf * leaf :: InfixTree(InfixNat, InfixNat)) { + have(thesis) by Typecheck.prove + } + assert(!typing.hasErrorsOrSorry) + } + + test("empty declarations and all supported parameter arities retain their sorts") { + val InfixEmpty = inductive() + val InfixEmpty3 = inductive((A, B, C))() + val InfixEmpty4 = inductive((A, B, C, D))() + val InfixEmpty5 = inductive((A, B, C, D, E))() + val three: ADT[Ind >>: Ind >>: Ind >>: Ind] = InfixEmpty3 + val four: ADT[Ind >>: Ind >>: Ind >>: Ind >>: Ind] = InfixEmpty4 + val five: ADT[Ind >>: Ind >>: Ind >>: Ind >>: Ind >>: Ind] = InfixEmpty5 + assert(three.typeVariablesSeq == Seq(A, B, C)) + assert(four.typeVariablesSeq == Seq(A, B, C, D)) + assert(five.typeVariablesSeq == Seq(A, B, C, D, E)) + assert(!InfixEmpty.elim.hasErrorsOrSorry && !five.elim.hasErrorsOrSorry) + } + + test("invalid fields and constructor names are rejected at compile time") { + assertDoesNotCompile("inductive(| same(), | same())") + assertDoesNotCompile("inductive(| induction())") + assertDoesNotCompile("inductive(| elim())") + assertDoesNotCompile("inductive(| constructors())") + assertDoesNotCompile("inductive(| name())") + assertDoesNotCompile("inductive(| id())") + assertDoesNotCompile("inductive(| sort())") + assertDoesNotCompile("inductive(| apply())") + assertDoesNotCompile("inductive(| selectDynamic())") + assertDoesNotCompile("inductive(| bad(42))") + assertDoesNotCompile("inductive(A)(| bad(head :: A, 42))") + assertDoesNotCompile("inductive(A)(| bad(head :: A, ()))") + assertDoesNotCompile("inductive(| bad(InfixNat.zero :: SelfRef))") + assertDoesNotCompile("inductive(if true then | yes() else | no())") + assertDoesNotCompile("inductive(|.applyDynamic(n.toString)(()))") + assertDoesNotCompile("inductive(A)(| bad(x :: SelfRef(A)))") + } + + test("duplicate binders and undeclared or duplicate parameters fail before proof construction") { + intercept[IllegalArgumentException] { + val InfixDuplicateFields = inductive(| pair (x :: SelfRef, x :: SelfRef)) + } + intercept[IllegalArgumentException] { + val InfixUndeclaredType = inductive(A)(| bad (x :: B)) + } + intercept[IllegalArgumentException] { + val InfixDuplicateParameters = inductive((A, A))(| empty ()) + } + } + + test("recursive markers remain distinct from identically named type parameters") { + val parameter = Variable[Ind]("inductiveSelf") + val InfixMarkerList = inductive(parameter)( + | nil (), + | cons (head :: parameter, tail :: SelfRef) + ) + val value = InfixMarkerList.cons(InfixNat) * InfixNat.zero * InfixMarkerList.nil(InfixNat) + val typing = Theorem.generated(value :: InfixMarkerList(InfixNat)) { + have(thesis) by Typecheck.prove + } + assert(!typing.hasErrorsOrSorry) + } + + test("indexed type parameters retain their identity") { + val indexed = Variable[Ind](Identifier("A", 1)) + val InfixIndexedBox = inductive(indexed)(| box (x :: indexed)) + assert(InfixIndexedBox.typeVariablesSeq == Seq(indexed)) + val typing = Theorem.generated(x :: indexed |- InfixIndexedBox.box(indexed) * x :: InfixIndexedBox(indexed)) { + have(thesis) by Typecheck.prove + } + assert(!typing.hasErrorsOrSorry) + } + + test("indexed field binders retain their identity") { + val indexed = Variable[Ind](Identifier("x", 1)) + val InfixIndexedField = inductive(A)(| box (indexed :: A)) + assert(InfixIndexedField.box.semantic.variables == Seq(indexed)) + val typing = Theorem.generated(indexed :: A |- InfixIndexedField.box(A) * indexed :: InfixIndexedField(A)) { + have(thesis) by Typecheck.prove + } + assert(!typing.hasErrorsOrSorry) + } + + test("declarations can be used during their enclosing object's initialization") { + object Enclosing { + val InfixLocalNat = inductive(| zero (), | succ (n :: SelfRef)) + val typing = Theorem.generated(InfixLocalNat.succ * InfixLocalNat.zero :: InfixLocalNat) { + have(thesis) by Typecheck.prove + } + } + assert(!Enclosing.typing.hasErrorsOrSorry) + } +} diff --git a/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/TypecheckPortSuite.scala b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/TypecheckPortSuite.scala new file mode 100644 index 000000000..452aa13d9 --- /dev/null +++ b/lisa-sets/src/test/scala/lisa/maths/SetTheory/Types/TypecheckPortSuite.scala @@ -0,0 +1,186 @@ +package lisa.maths.SetTheory.Types + +import lisa.SetTheoryLibrary +import lisa.SetTheoryLibrary._ +import lisa.maths.SetTheory.Cardinal.Predef.universeOf +import lisa.maths.SetTheory.Functions.Predef._ +import lisa.maths.SetTheory.Types.Tactics.Typecheck +import lisa.maths.SetTheory.Types.TypingHelpers._ +import lisa.utils.fol.FOL._ +import lisa.utils.prooflib.Exports._ +import lisa.utils.prooflib.OutputManager +import lisa.utils.prooflib.Proof +import lisa.utils.prooflib.StringOutputManager +import org.scalatest.funsuite.AnyFunSuite + +/** + * Exercise the typing regressions ported from typingv2 through the LCF front. + */ +class TypecheckPortSuite extends AnyFunSuite: + private given SetTheoryLibrary.type = SetTheoryLibrary + private given OutputManager = new StringOutputManager + + private val A, B, f, x, y = variable[Ind] + private val family = variable[Ind >>: Ind] + + private def check(context: Set[Expr[Prop]], term: Expr[Ind], typ: Expr[Ind], expected: Sequent): Unit = + val result = Proof.withContext(using SetTheoryLibrary): + Typecheck.checkProof(context, term, typ) + assert(result.isValid, result.errors.map(_.message).mkString("\n")) + assert(result.thm.statement == expected) + assert(!result.thm.kernel.usesSorry) + + private def reject(context: Set[Expr[Prop]], term: Expr[Ind], typ: Expr[Ind]): Unit = + val result = Proof.withContext(using SetTheoryLibrary): + Typecheck.checkProof(context, term, typ) + assert(!result.isValid) + + test("reuse exact typing without dropping its premise"): + check(Set(x ∈ A, y ∈ B), x, A, x ∈ A |- x ∈ A) + + test("reuse an exact dependent function type"): + val typ = Pi(A)(λ(x, family(x))) + check(Set(f ∈ typ), f, typ, f ∈ typ |- f ∈ typ) + + test("restate beta-equivalent types while retaining the inferred premise"): + val typ = λ(y, y)(A) + check(Set(x ∈ A), x, typ, x ∈ A |- x ∈ typ) + + test("restate alpha-equivalent dependent types"): + val inferred = Pi(A)(λ(x, family(x))) + val expected = Pi(A)(λ(y, family(y))) + check(Set(f ∈ inferred), f, expected, f ∈ inferred |- f ∈ expected) + + test("retain a genuine inclusion premise"): + val context = Set(x ∈ A, A ⊆ B) + check(context, x, B, context |- x ∈ B) + + test("retain universe lifting"): + check(Set(x ∈ A), x, universeOf(A), x ∈ A |- x ∈ universeOf(A)) + + test("construct covariance only for different function types"): + check(Set(f ∈ (A ->: B)), f, A ->: universeOf(B), f ∈ (A ->: B) |- f ∈ (A ->: universeOf(B))) + + test("type an application with explicit cuts"): + val context = Set(f ∈ (A ->: B), x ∈ A) + check(context, f * x, B, context |- (f * x) ∈ B) + + test("infer a lambda without retaining its bound variable assumption"): + val context = Set(f ∈ (A ->: B)) + check(context, abs(A)(λ(x, f * x)), A ->: B, context |- abs(A)(λ(x, f * x)) ∈ (A ->: B)) + + test("reject unrelated types and missing typing premises"): + reject(Set(x ∈ A), x, B) + reject(Set(y ∈ A), x, A) + reject(Set(x ∈ A), x, universeOf(B)) + + test("reject invalid applications and abstraction domains"): + reject(Set(f ∈ (A ->: B), x ∈ B), f * x, B) + reject(Set(f ∈ A, x ∈ A), f * x, B) + reject(Set(f ∈ (A ->: B)), abs(A)(λ(x, f * x)), B ->: B) + + test("reuse repeated subterms without leaking subproof-local references"): + val combine = variable[Ind] + val context = Set(combine ∈ (B ->: B ->: B), f ∈ (A ->: B), x ∈ A) + val term = combine * (f * x) * (f * x) + check(context, term, B, context |- term ∈ B) + + test("align distinct dependent covariance binders"): + val from = Pi(A)(λ(x, family(x))) + val to = Pi(A)(λ(y, universeOf(family(y)))) + check(Set(f ∈ from), f, to, f ∈ from |- f ∈ to) + + test("discharge universe formation with explicit conjuncts and cuts"): + val goal = () |- (A ->: A) ∈ universeOf(A) + val result = Proof.withContext(using SetTheoryLibrary): + Typecheck.prove(goal) + assert(result.isValid, result.errors.map(_.message).mkString("\n")) + assert(result.thm.statement == goal) + assert(!result.thm.kernel.usesSorry) + + test("freshen nested binders that shadow a different type assignment"): + val term = abs(A)(λ(x, abs(B)(λ(x, x)))) + check(Set.empty, term, A ->: B ->: B, () |- term ∈ (A ->: B ->: B)) + + test("keep free variables in the outer typing context distinct from binders"): + val term = abs(A)(λ(x, y)) + val context = Set(y ∈ family(x)) + check(context, term, A ->: family(x), context |- term ∈ (A ->: family(x))) + + test("keep function-arrow codomains independent of their hidden binder"): + assert((A ->: family(x)).freeVars.contains(x)) + + test("freshen a binder that shadows a free variable in its domain"): + val term = abs(x)(λ(x, x)) + check(Set.empty, term, x ->: x, () |- term ∈ (x ->: x)) + + test("count only leading universeOf applications in universe depth"): + val bases = List(A, family(A), family(universeOf(A)), f * x, Pi(A)(λ(x, family(x))), abs(A)(λ(x, x))) + bases.foreach { base => + assert(Typecheck.getDepth(base) == 1, s"Unexpected universe depth for $base") + assert(Typecheck.getDepth(universeOf(base)) == 2) + assert(Typecheck.getDepth(universeOf(universeOf(base))) == 3) + } + + test("use an inclusion from a compound type without a spurious depth mismatch"): + val context = Set(x ∈ family(A), family(A) ⊆ B) + check(context, x, B, context |- x ∈ B) + + test("prefer an exact context typing over a convertible alternative"): + List(x ∈ A, x ∈ B, A ⊆ B).permutations.foreach { assumptions => + check(assumptions.toSet, x, B, x ∈ B |- x ∈ B) + } + + test("use assumed typings of structured terms before reconstructing them"): + List(f * x, abs(A)(λ(x, x)), Pi(A)(λ(x, family(x)))).foreach { term => + val assumption = term ∈ B + check(Set(assumption), term, B, assumption |- assumption) + } + val theorem = Theorem((f * x) ∈ B |- (f * x) ∈ B) { + have(thesis) by Typecheck.prove + } + assert(theorem.errors.isEmpty) + assert(!theorem.kernel.usesSorry) + + test("retain the original equivalent member assumption through lookup and subsumption"): + val assumedTerm = abs(A)(λ(x, x)) + val term = abs(A)(λ(y, y)) + val assumption = assumedTerm ∈ family(A) + check(Set(assumption), term, family(A), assumption |- term ∈ family(A)) + val context = Set(assumption, family(A) ⊆ B) + check(context, term, B, context |- term ∈ B) + + test("try every context typing for subsumption without retaining failed candidates"): + val C = variable[Ind] + val types = List(A, B, universeOf(A)) + val typings = types.map(x ∈ _).toSet + types.foreach { actual => + val inclusion = actual ⊆ C + val required = Set(x ∈ actual, inclusion) + check(typings + inclusion, x, C, required |- x ∈ C) + } + reject(typings, x, C) + + test("fall back to structural typing after context candidates fail"): + val term = f * x + val required = Set(f ∈ (A ->: B), x ∈ A) + check(required + (term ∈ family(A)), term, B, required |- term ∈ B) + + test("use assumed inclusions before universe depth checks or function decomposition"): + val deep = universeOf(A) + val universeContext = Set(x ∈ deep, deep ⊆ B) + check(universeContext, x, B, universeContext |- x ∈ B) + reject(Set(x ∈ deep), x, B) + + val from = Pi(A)(λ(y, family(y))) + val to = Pi(B)(λ(y, family(y))) + val inclusion = Pi(A)(λ(x, family(x))) ⊆ Pi(B)(λ(x, family(x))) + val functionContext = Set(f ∈ from, inclusion) + check(functionContext, f, to, functionContext |- f ∈ to) + reject(Set(f ∈ from), f, to) + + test("keep ambient assumptions out of explicit context lookup"): + val result = Proof.withContext(using SetTheoryLibrary): + lisa.utils.prooflib.ProofHelpers.assume(x ∈ B, A ⊆ B) + Typecheck.checkProof(Set(x ∈ A), x, B) + assert(!result.isValid) diff --git a/lisa-utils/src/main/scala/lisa/utils/prooflib/QuantifierTactics.scala b/lisa-utils/src/main/scala/lisa/utils/prooflib/QuantifierTactics.scala new file mode 100644 index 000000000..f686d4168 --- /dev/null +++ b/lisa-utils/src/main/scala/lisa/utils/prooflib/QuantifierTactics.scala @@ -0,0 +1,46 @@ +package lisa.utils.prooflib + +import lisa.utils.fol.FOL.{_, given} +import lisa.utils.prooflib.ProofHelpers._ +import lisa.utils.prooflib.TacticHelpers.failWith + +/** + * Instantiates a sequence of universal binders while preserving the premise context. + */ +object InstantiateForallSeq: + def apply(using Library, sourcecode.File, sourcecode.Line)(args: Seq[Expr[Ind]])(fact: Thm)(bot: Sequent): ProofJudgement = + if fact.right.size != 1 then ProofCarrier(Set(SoftError("InstantiateForallSeq requires exactly one right-hand formula.", summon[sourcecode.File], summon[sourcecode.Line])), bot, None, ()) + else if args.isEmpty then BasicStep.Weakening(bot, fact.kernel) + else InstantiateForall(args*)(bot, fact) + +/** + * Introduces a sequence of quantifiers around one formula on either side of a sequent. + */ +object QuantifiersIntro: + def apply(using Library, sourcecode.File, sourcecode.Line)(vars: Seq[Variable[Ind]])(fact: Thm)(bot: Sequent): ProofJudgement = Subproof { + val added = bot -- fact.statement + val removed = fact.statement -- bot + if vars.isEmpty || (added.left.isEmpty && added.right.isEmpty && removed.left.isEmpty && removed.right.isEmpty) then have(bot) by BasicStep.Restate.from(fact) + else + val onLeft = added.left.size == 1 && removed.left.size == 1 && added.right.isEmpty && removed.right.isEmpty + val onRight = added.right.size == 1 && removed.right.size == 1 && added.left.isEmpty && removed.left.isEmpty + if !onLeft && !onRight then failWith("QuantifiersIntro requires exactly one formula to be replaced on the same side.") + val source = if onLeft then removed.left.head else removed.right.head + val target = if onLeft then added.left.head else added.right.head + val (quantify, step): ((Variable[Ind], Expr[Prop]) => Expr[Prop], (Sequent, Thm) => ProofJudgement) = + (onLeft, target) match + case (true, forall(_, _)) => ((v, body) => forall(v, body), (s: Sequent, t: Thm) => BasicStep.LeftForall(s, t.kernel)) + case (true, exists(_, _)) => ((v, body) => exists(v, body), (s: Sequent, t: Thm) => BasicStep.LeftExists(s, t.kernel)) + case (false, forall(_, _)) => ((v, body) => forall(v, body), (s: Sequent, t: Thm) => BasicStep.RightForall(s, t.kernel)) + case (false, exists(_, _)) => ((v, body) => exists(v, body), (s: Sequent, t: Thm) => BasicStep.RightExists(s, t.kernel)) + case _ => failWith("QuantifiersIntro requires a quantified target formula.") + val (result, _) = vars.foldRight((fact, source)) { case (variable, (current, formula)) => + val quantified = quantify(variable, formula) + val conclusion = + if onLeft then (fact.left - source + quantified) |- fact.right + else fact.left |- (fact.right - source + quantified) + val next = have(conclusion) by (goal => step(goal, current)) + (next, quantified) + } + have(bot) by BasicStep.Restate.from(result) + } diff --git a/lisa-utils/src/test/scala/lisa/utils/prooflib/QuantifiedInstantiationSuite.scala b/lisa-utils/src/test/scala/lisa/utils/prooflib/QuantifiedInstantiationSuite.scala new file mode 100644 index 000000000..da3add898 --- /dev/null +++ b/lisa-utils/src/test/scala/lisa/utils/prooflib/QuantifiedInstantiationSuite.scala @@ -0,0 +1,57 @@ +package lisa.utils.prooflib + +import lisa.utils.fol.FOL.{_, given} +import lisa.utils.prooflib.ProofHelpers._ +import org.scalatest.funsuite.AnyFunSuite + +/** + * Checks quantified instantiation through the public theorem shorthand. + */ +class QuantifiedInstantiationSuite extends AnyFunSuite: + private given Library = new Library + private given OutputManager = new StringOutputManager + private val x, y, a, b = variable[Ind] + private val P = variable[Ind >>: Ind >>: Prop] + + private def assertProved(theorem: Thm, expected: Sequent): Unit = + assert(theorem.statement == expected) + assert(!theorem.kernel.usesSorry) + + test("instantiate named, front and kernel theorems while retaining assumptions"): + val formula = forall(x, forall(y, P(x)(y))) + val named = Theorem(formula |- formula) { + have(thesis) by BasicStep.Hypothesis + } + assert(named.errors.isEmpty) + for result <- Seq(named.of(a, b), named.thm.of(a, b), named.kernel.of(a, b)) do assertProved(result, formula |- P(a)(b)) + + test("partial instantiation avoids capturing a later bound variable"): + val formula = forall(x, forall(y, P(x)(y))) + val source = BasicStep.Hypothesis(formula |- formula).thm + val partial = source.of(y) + assert(partial.right.head.freeVars.contains(y)) + assertProved(partial.of(a), formula |- P(y)(a)) + + test("mixed arguments apply simultaneous substitutions before quantified instantiation"): + val formula = forall(x, P(a)(x)) + val source = BasicStep.Hypothesis(formula |- formula).thm + for arguments <- Seq(Seq(a := b, b := a, a), Seq(a, b := a, a := b)) do assertProved(source.of(arguments*), forall(x, P(b)(x)) |- P(b)(a)) + assertProved(source.of(a := b, b := a).of(a), forall(x, P(b)(x)) |- P(b)(a)) + + test("empty instantiation retains the original theorem"): + val source = BasicStep.Hypothesis(P(a)(b) |- P(a)(b)).thm + assert(source.of() eq source) + + test("invalid quantified arguments fail rather than returning an admitted theorem"): + val formula = forall(x, P(x)(b)) + val source = BasicStep.Hypothesis(formula |- formula).thm + intercept[IllegalArgumentException](source.of(a, b)) + intercept[IllegalArgumentException](source.of(a).of(b)) + val multiple = BasicStep.Hypothesis(formula |- (formula, P(a)(b))).thm + intercept[IllegalArgumentException](multiple.of(a)) + + test("instantiation preserves an existing sorry dependency"): + val source = BasicStep.Sorry(() |- forall(x, P(x)(b))).thm + val instance = source.of(a) + assert(instance.statement == (() |- P(a)(b))) + assert(instance.kernel.usesSorry) diff --git a/lisa-utils/src/test/scala/lisa/utils/prooflib/QuantifierTacticsSuite.scala b/lisa-utils/src/test/scala/lisa/utils/prooflib/QuantifierTacticsSuite.scala new file mode 100644 index 000000000..c52059935 --- /dev/null +++ b/lisa-utils/src/test/scala/lisa/utils/prooflib/QuantifierTacticsSuite.scala @@ -0,0 +1,101 @@ +package lisa.utils.prooflib + +import lisa.utils.fol.FOL.{_, given} +import lisa.utils.prooflib.ProofHelpers._ +import org.scalatest.funsuite.AnyFunSuite + +/** + * Checks quantifier tactics through LCF proof carriers, including invalid inputs. + */ +class QuantifierTacticsSuite extends AnyFunSuite: + private given Library = new Library + private given OutputManager = new StringOutputManager + private val x, y = variable[Ind] + private val p = variable[Ind >>: Ind >>: Prop] + private val formula = forall(x, forall(y, p(x)(y))) + private val source = BasicStep.Hypothesis(formula |- formula).thm + + private def assertProved(result: ProofJudgement, expected: Sequent): Unit = + assert(result.isValid, result.errors.mkString("\n")) + assert(result.thm.statement == expected) + assert(!result.thm.kernel.usesSorry) + + test("preserve assumptions through capture-avoiding instantiation and empty arguments"): + for (args, conclusion) <- Seq(Seq(y, x) -> p(y)(x), Seq.empty[Expr[Ind]] -> formula) do + val goal = formula |- conclusion + assertProved(InstantiateForallSeq(args)(source)(goal), goal) + + test("instantiate under unrelated ambient assumptions"): + val reflexivity = Theorem.generated(forall(x, x === x)) { + have(x === x) by BasicStep.RightRefl + thenHave(thesis) by BasicStep.RightForall + } + for args <- Seq(Seq.empty[Expr[Ind]], Seq(y)) do + val goal = p(x)(y) |- (if args.isEmpty then forall(x, x === x) else y === y) + val checked = Theorem.generated(goal) { + ProofHelpers.assume(p(x)(y)) + have(thesis) by InstantiateForallSeq(args)(reflexivity) + } + assertProved(checked.judgement, goal) + + test("reject multiple conclusions and excess arguments"): + val multiple = BasicStep.Hypothesis(formula |- (formula, p(x)(y))).thm + assert(!InstantiateForallSeq(Seq(x))(multiple)(formula |- p(x)(y)).isValid) + assert(!InstantiateForallSeq(Seq(x, y, x))(source)(formula |- p(x)(y)).isValid) + + test("introduce universal quantifiers while preserving assumptions"): + val specialized = source.of(x, y) + assertProved(QuantifiersIntro(Seq(x, y))(specialized)(source.statement), source.statement) + + test("reject quantification of a variable free in the remaining context"): + val atom = p(x)(y) + val identity = BasicStep.Hypothesis(atom |- atom).thm + assert(!QuantifiersIntro(Seq(x, y))(identity)(atom |- formula).isValid) + + test("require exactly one formula replaced on one side"): + val atom = p(x)(y) + val other = variable[Prop] + val identity = BasicStep.Hypothesis(atom |- atom).thm + val twoPremises = BasicStep.Hypothesis((atom, other) |- atom).thm + val twoConclusions = BasicStep.Hypothesis(atom |- (atom, other)).thm + val quantified = forall(x, atom) + for (fact, goal) <- Seq( + identity -> ((atom, quantified) |- atom), + identity -> (atom |- (atom, quantified)), + twoPremises -> (quantified |- atom), + twoConclusions -> (atom |- quantified), + identity -> (quantified |- quantified) + ) + do assert(!QuantifiersIntro(Seq(x))(fact)(goal).isValid) + + test("left introduction preserves other conclusions"): + val atom = p(x)(y) + val other = variable[Prop] + val identity = BasicStep.Hypothesis(atom |- (atom, other)).thm + val goal = forall(x, atom) |- (atom, other) + assertProved(QuantifiersIntro(Seq(x))(identity)(goal), goal) + + test("introduce existential quantifiers on either side"): + val atom = p(x)(y) + val identity = BasicStep.Hypothesis(atom |- atom).thm + val rightGoal = atom |- exists(x, exists(y, atom)) + assertProved(QuantifiersIntro(Seq(x, y))(identity)(rightGoal), rightGoal) + val tautology = BasicStep.Hypothesis((atom, p(y)(x)) |- p(y)(x)).thm + val leftGoal = (exists(x, atom), p(y)(x)) |- p(y)(x) + assert(!QuantifiersIntro(Seq(x))(tautology)(leftGoal).isValid) + + test("explicit theorem names retain their proof and registry entry"): + val named = Theorem.named("generated/example")(x === x) { + have(thesis) by BasicStep.RightRefl + } + assertProved(named.judgement, () |- x === x) + assert(summon[Library].theorems.getFull("generated/example").contains(named)) + + test("generated theorems from the same source retain distinct registry entries"): + val generated = (1 to 2).map { _ => + Lemma.generated(x === x) { have(thesis) by BasicStep.RightRefl } + } + assert(generated.map(_.fullName.value).distinct.size == 2) + for theorem <- generated do + assertProved(theorem.judgement, () |- x === x) + assert(summon[Library].theorems.getFull(theorem.fullName.value).contains(theorem)) From 3642c5fa357ea8b02b4fd3086486bec9f44f785c Mon Sep 17 00:00:00 2001 From: Sankalp Gambhir Date: Fri, 20 Nov 2026 09:58:56 +0100 Subject: [PATCH 3/3] scala{fix,fmt} --- .../Types/ADT/PatternMatching/proofs/WitnessFunctionProofs.scala | 1 - .../SetTheory/Types/ADT/encoding/SyntacticConstructor.scala | 1 - .../lisa/maths/SetTheory/Types/ADT/induction/Induction.scala | 1 - .../lisa/maths/SetTheory/Types/ADT/recursion/Existence.scala | 1 - 4 files changed, 4 deletions(-) diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessFunctionProofs.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessFunctionProofs.scala index b20426ea6..b81859512 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessFunctionProofs.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/PatternMatching/proofs/WitnessFunctionProofs.scala @@ -71,7 +71,6 @@ private[proofs] trait WitnessFunctionProofs extends WitnessBranchMembership { if contextPremises.nonEmpty then assume(contextPremise) val branchExistenceFacts = patternMatching.clauses.map(pattern => - val membershipSchema = if contextPremises.isEmpty then have(witnessMembership(pattern).statement.right.head) by Tautology.from(witnessMembership(pattern)) else diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticConstructor.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticConstructor.scala index c9e5be100..cc80dcbd8 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticConstructor.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/encoding/SyntacticConstructor.scala @@ -171,7 +171,6 @@ class SyntacticConstructor( variables2, lastStep )((acc, v) => - // pulledVars1 are the variables that have been pulled out of the left term // remainingVars1 are the variables that are still in the left term // pulledVars2 are the variables that have been pulled out of the right term diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/induction/Induction.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/induction/Induction.scala index adf6978a5..0f5781970 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/induction/Induction.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/induction/Induction.scala @@ -268,7 +268,6 @@ class Induction( context: Set[Expr[Prop]], branchSystem: PatternSystem[Thm] ): ProofJudgement = Subproof { sp ?=> - val specializedADT = branchSystem.domain val typeVariablesSubstPairs = specializedADT.base.typeVariablesSeq.zip(specializedADT.typeArgs).map(SubstPair(_, _)) diff --git a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Existence.scala b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Existence.scala index a41bf3f9f..f8051e1d4 100644 --- a/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Existence.scala +++ b/lisa-sets/src/main/scala/lisa/maths/SetTheory/Types/ADT/recursion/Existence.scala @@ -227,7 +227,6 @@ private[recursion] final class Existence( val caseFacts = spec.patternMatching.clauses .map(pattern => - val body = pattern.body.substitute(spec.selfPlaceholder := f) val witnessCaseSchema = recWitness.witnessCase(pattern).of(spec.selfPlaceholder := f)