From 96409250b90cafb55433d2a7b2bac11c791e8e08 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Mon, 9 Nov 2026 14:36:21 +0000 Subject: [PATCH 1/2] Add a vendored Mathlib subset checked against upstream lean/mathlib-subset vendors the Mathlib and Batteries declarations that the Lean packages use, from the same module paths as upstream Mathlib v4.35.0. lean/mathlib-subset-check compares the vendored declarations with upstream, and a new path-filtered Lean Mathlib Subset workflow runs it when the subset, the checker, the toolchain or the workflow change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/README.md | 11 +- .github/workflows/lean-mathlib-subset.yml | 65 ++++ .github/workflows/lean.yml | 10 +- lean/mathlib-subset-check/Main.lean | 291 ++++++++++++++++++ lean/mathlib-subset-check/lake-manifest.json | 117 +++++++ lean/mathlib-subset-check/lakefile.toml | 15 + lean/mathlib-subset-check/lean-toolchain | 1 + .../Batteries/Data/List/Basic.lean | 33 ++ .../Batteries/Data/List/Perm.lean | 59 ++++ lean/mathlib-subset/LICENSE | 201 ++++++++++++ .../Mathlib/Basic/SetLike/Basic.lean | 65 ++++ .../Mathlib/Data/Finset/Card.lean | 39 +++ .../Mathlib/Data/Finset/Dedup.lean | 26 ++ .../Mathlib/Data/Finset/Defs.lean | 63 ++++ .../Mathlib/Data/Finset/Empty.lean | 31 ++ .../Mathlib/Data/Finset/Erase.lean | 27 ++ .../Mathlib/Data/Finset/Filter.lean | 31 ++ .../Mathlib/Data/Finset/Fold.lean | 25 ++ .../Mathlib/Data/Finset/Insert.lean | 40 +++ .../Mathlib/Data/Finset/Lattice/Basic.lean | 42 +++ .../Mathlib/Data/Finset/Lattice/Fold.lean | 22 ++ .../Mathlib/Data/Finset/Max.lean | 49 +++ .../Mathlib/Data/Finset/SDiff.lean | 34 ++ .../Mathlib/Data/Finset/Sort.lean | 30 ++ .../Mathlib/Data/List/Dedup.lean | 43 +++ .../Mathlib/Data/List/Defs.lean | 26 ++ .../Mathlib/Data/List/Infix.lean | 11 + .../Mathlib/Data/List/Perm/Basic.lean | 27 ++ .../Mathlib/Data/List/Sort.lean | 94 ++++++ .../Mathlib/Data/Multiset/AddSub.lean | 38 +++ .../Mathlib/Data/Multiset/Dedup.lean | 21 ++ .../Mathlib/Data/Multiset/Defs.lean | 106 +++++++ .../Mathlib/Data/Multiset/Filter.lean | 24 ++ .../Mathlib/Data/Multiset/FinsetOps.lean | 47 +++ .../Mathlib/Data/Multiset/Fold.lean | 20 ++ .../Mathlib/Data/Multiset/MapFold.lean | 29 ++ .../Mathlib/Data/Multiset/Sort.lean | 24 ++ .../Mathlib/Data/Multiset/ZeroCons.lean | 35 +++ .../Mathlib/Data/Nat/Basic.lean | 28 ++ .../Mathlib/Data/Nat/Notation.lean | 16 + .../Mathlib/Data/Seq/Basic.lean | 30 ++ .../mathlib-subset/Mathlib/Data/Seq/Defs.lean | 84 +++++ .../Mathlib/Data/Set/Basic.lean | 23 ++ .../mathlib-subset/Mathlib/Data/Set/Defs.lean | 51 +++ .../Mathlib/Data/Stream/Defs.lean | 33 ++ lean/mathlib-subset/Mathlib/Init.lean | 9 + .../Mathlib/Logic/Function/Basic.lean | 34 ++ .../mathlib-subset/Mathlib/Logic/OpClass.lean | 18 ++ lean/mathlib-subset/Mathlib/Order/Basic.lean | 98 ++++++ .../Mathlib/Order/BoundedOrder/Basic.lean | 17 + .../Mathlib/Order/Defs/Lattice.lean | 81 +++++ .../Mathlib/Order/Defs/LinearOrder.lean | 92 ++++++ .../Mathlib/Order/Defs/PartialOrder.lean | 55 ++++ .../Mathlib/Order/Defs/Prop.lean | 14 + .../Mathlib/Order/Defs/Unbundled.lean | 14 + .../mathlib-subset/Mathlib/Order/Lattice.lean | 51 +++ lean/mathlib-subset/Mathlib/Order/MinMax.lean | 20 ++ .../Mathlib/Order/Notation.lean | 37 +++ .../Mathlib/Order/PropInstances.lean | 22 ++ .../Mathlib/Order/RelClasses.lean | 19 ++ .../Mathlib/Order/TypeTags.lean | 41 +++ .../mathlib-subset/Mathlib/Order/WithBot.lean | 152 +++++++++ lean/mathlib-subset/Mathlib/Tactic/Lemma.lean | 31 ++ .../Mathlib/Tactic/SetNotationForOrder.lean | 182 +++++++++++ .../Mathlib/Tactic/SplitIfs.lean | 34 ++ .../mathlib-subset/Mathlib/Tactic/Spread.lean | 84 +++++ .../Mathlib/Tactic/TypeStar.lean | 64 ++++ lean/mathlib-subset/README.md | 46 +++ lean/mathlib-subset/lake-manifest.json | 8 + lean/mathlib-subset/lakefile.toml | 18 ++ lean/mathlib-subset/lean-toolchain | 1 + scripts/lean-format-checks.sh | 3 +- 72 files changed, 3379 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/lean-mathlib-subset.yml create mode 100644 lean/mathlib-subset-check/Main.lean create mode 100644 lean/mathlib-subset-check/lake-manifest.json create mode 100644 lean/mathlib-subset-check/lakefile.toml create mode 120000 lean/mathlib-subset-check/lean-toolchain create mode 100644 lean/mathlib-subset/Batteries/Data/List/Basic.lean create mode 100644 lean/mathlib-subset/Batteries/Data/List/Perm.lean create mode 100644 lean/mathlib-subset/LICENSE create mode 100644 lean/mathlib-subset/Mathlib/Basic/SetLike/Basic.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Card.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Dedup.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Defs.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Empty.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Erase.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Filter.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Fold.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Insert.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Lattice/Basic.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Lattice/Fold.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Max.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/SDiff.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Finset/Sort.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/List/Dedup.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/List/Defs.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/List/Infix.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/List/Perm/Basic.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/List/Sort.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Multiset/AddSub.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Multiset/Dedup.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Multiset/Defs.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Multiset/Filter.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Multiset/FinsetOps.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Multiset/Fold.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Multiset/MapFold.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Multiset/Sort.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Multiset/ZeroCons.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Nat/Basic.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Nat/Notation.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Seq/Basic.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Seq/Defs.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Set/Basic.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Set/Defs.lean create mode 100644 lean/mathlib-subset/Mathlib/Data/Stream/Defs.lean create mode 100644 lean/mathlib-subset/Mathlib/Init.lean create mode 100644 lean/mathlib-subset/Mathlib/Logic/Function/Basic.lean create mode 100644 lean/mathlib-subset/Mathlib/Logic/OpClass.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/Basic.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/BoundedOrder/Basic.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/Defs/Lattice.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/Defs/LinearOrder.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/Defs/PartialOrder.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/Defs/Prop.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/Defs/Unbundled.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/Lattice.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/MinMax.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/Notation.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/PropInstances.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/RelClasses.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/TypeTags.lean create mode 100644 lean/mathlib-subset/Mathlib/Order/WithBot.lean create mode 100644 lean/mathlib-subset/Mathlib/Tactic/Lemma.lean create mode 100644 lean/mathlib-subset/Mathlib/Tactic/SetNotationForOrder.lean create mode 100644 lean/mathlib-subset/Mathlib/Tactic/SplitIfs.lean create mode 100644 lean/mathlib-subset/Mathlib/Tactic/Spread.lean create mode 100644 lean/mathlib-subset/Mathlib/Tactic/TypeStar.lean create mode 100644 lean/mathlib-subset/README.md create mode 100644 lean/mathlib-subset/lake-manifest.json create mode 100644 lean/mathlib-subset/lakefile.toml create mode 120000 lean/mathlib-subset/lean-toolchain diff --git a/.github/workflows/README.md b/.github/workflows/README.md index d3e4ffd82c05..3500c93e4b34 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -172,7 +172,7 @@ The `KV trace captures` job builds the `CCF_KV_TRACING` unit tests on Azure Linu The KV package job checks `lean/kv/replayer/check-fixtures.sh` against the KV fixtures. The dedicated replay job builds `kv-replay` separately to validate the captured traces; no replay executables are transferred between jobs. -After the build, `scripts/lean-format-checks.sh` checks every tracked `.lean` file with the pinned leanfmt dependency. +After the build, `scripts/lean-format-checks.sh` checks every tracked `.lean` file except the vendored Mathlib subset with the pinned leanfmt dependency. The workflow runs on pull requests that change `lean/`, any `.lean` file, the formatter script, or the workflow. It also runs on changes to the C++ sources and trace runners checked against the CCF consensus and KV models: `src/consensus/aft/`, the CCF consensus scenario tests, `src/kv/`, the public KV and transaction headers, and the KV trace runner. See the [local formatting commands](../../lean/disaster-recovery/README.md#formatting) to apply fixes. @@ -180,6 +180,15 @@ See the [local formatting commands](../../lean/disaster-recovery/README.md#forma File: `lean.yml` 3rd party dependencies: Mathlib and leanfmt (pinned in the Lake package), and elan. +# Lean Mathlib Subset + +Checks the declarations vendored in [`lean/mathlib-subset`](../../lean/mathlib-subset/README.md) against upstream Mathlib, using `lake exe mathlib-subset-check`. +Fetching upstream Mathlib is slow, so it is triggered only on pull requests that change the subset, its checker, the Lean toolchain, or this workflow. +It can also be run manually. + +File: `lean-mathlib-subset.yml` +3rd party dependencies: Mathlib (pinned in the subset checker) and elan. + # Vendored Dependency Verification Verifies that files under `3rdparty/` match the Git commits or release artifacts recorded in `cgmanifest.json`. Triggered on pull requests and pushes to `main` that change vendored sources, the manifest, the verifier, or this workflow. It can also be run manually. diff --git a/.github/workflows/lean-mathlib-subset.yml b/.github/workflows/lean-mathlib-subset.yml new file mode 100644 index 000000000000..4b83aa52eeba --- /dev/null +++ b/.github/workflows/lean-mathlib-subset.yml @@ -0,0 +1,65 @@ +name: "Lean Mathlib Subset" + +on: + pull_request: + paths: + - "lean/lean-toolchain" + - "lean/mathlib-subset/**" + - "lean/mathlib-subset-check/**" + - ".github/workflows/lean-mathlib-subset.yml" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: read-all + +jobs: + check: + name: Check vendored Mathlib subset + runs-on: [gha-vmss-d16av7-ci-b] + container: + image: ubuntu:26.04 + options: --user root + timeout-minutes: 60 + permissions: + contents: read + defaults: + run: + shell: bash + + steps: + - name: Install container prerequisites + run: | + set -euo pipefail + apt-get update + DEBIAN_FRONTEND=noninteractive apt-get install -y \ + ca-certificates git curl tar zstd build-essential libgmp-dev elan + echo "ELAN_HOME=$RUNNER_TEMP/elan" >> "$GITHUB_ENV" + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Install Lean + run: | + set -euo pipefail + git config --global --add safe.directory "$GITHUB_WORKSPACE" + elan run --install "$(cat lean/lean-toolchain)" lean --version + + - name: Build Mathlib subset + working-directory: lean/mathlib-subset + run: | + set -euo pipefail + lake build --wfail + + - name: Fetch upstream Mathlib + working-directory: lean/mathlib-subset-check + run: | + set -euo pipefail + lake exe cache get + + - name: Check subset against upstream Mathlib + working-directory: lean/mathlib-subset-check + run: | + set -euo pipefail + lake exe mathlib-subset-check ../mathlib-subset diff --git a/.github/workflows/lean.yml b/.github/workflows/lean.yml index 350340e4284c..1fc56a953678 100644 --- a/.github/workflows/lean.yml +++ b/.github/workflows/lean.yml @@ -322,7 +322,15 @@ jobs: python3 - <<'PY' import pathlib - expected = {"consensus", "common", "consistency", "disaster-recovery", "kv"} + expected = { + "consensus", + "common", + "consistency", + "disaster-recovery", + "kv", + "mathlib-subset", + "mathlib-subset-check", + } actual = {config.parent.name for config in pathlib.Path("lean").glob("*/lakefile.toml")} if actual != expected: raise SystemExit( diff --git a/lean/mathlib-subset-check/Main.lean b/lean/mathlib-subset-check/Main.lean new file mode 100644 index 000000000000..dbdaa13e3b2a --- /dev/null +++ b/lean/mathlib-subset-check/Main.lean @@ -0,0 +1,291 @@ +import Lean + +/-! +# Mathlib subset checker + +Checks that `lean/mathlib-subset` is a faithful subset of upstream Mathlib and Batteries, as +pinned by this package's `lake-manifest.json`. + +The subset and upstream environments are both imported from the same module names. Every +declaration from a subset module must then: + +* exist upstream, in the same module, with the same kind and number of universe parameters; +* have the same type and, for definitions, the same value, up to eta and universe parameter + names, after replacing every proof subterm with a placeholder (so the subset may prove + things differently); +* have the same reducibility, instance priority, and class/structure shape; +* depend only on the standard axioms. + +Theorems only need matching statements. Theorems with internal names (auxiliary proofs) and +generated equation lemmas are not compared. Other declarations with internal names (such as +matchers) need not exist upstream: a definition referring to one only matches if upstream +refers to an identically named, matching declaration. The values of metaprograms (definitions +whose upstream type mentions the `Lean` namespace) are not compared, since they only affect +elaboration and every elaborated term is itself checked; everything else about them is. + +Usage: `lake exe mathlib-subset-check ` +-/ + +open Lean Meta + +namespace MathlibSubsetCheck + +/-- Library roots of the subset package. -/ +def roots : List String := ["Mathlib", "Batteries"] + +def allowedAxioms : List Name := [``propext, ``Quot.sound, ``Classical.choice] + +/-- Module names of all `.lean` files under the subset's library roots. -/ +def subsetModules (dir : System.FilePath) : IO (Array Name) := do + let base := dir.components.length + let mut mods := #[] + for root in roots do + let rootDir := dir / root + unless ← rootDir.isDir do + continue + for p in ← rootDir.walkDir do + if p.extension == some "lean" then + let comps := (p.withExtension "").components.drop base + mods := mods.push <| comps.foldl .str .anonymous + return mods.qsort Name.lt + +def loadEnv (sp : SearchPath) (mods : Array Name) : IO Environment := do + searchPathRef.set sp + importModules (mods.map fun m => { module := m }) {} + +def runIn (env : Environment) (x : MetaM α) : IO α := + let ctx : Core.Context := + { fileName := "", fileMap := default, maxHeartbeats := 0 } + (x.run' {} {}).toIO' ctx { env } + +def moduleOf? (env : Environment) (n : Name) : Option Name := do + let idx ← env.getModuleIdxFor? n + env.header.moduleNames[idx.toNat]? + +/-- Replace every maximal proof subterm by a placeholder constant, and eta-reduce. -/ +def eraseProofs (e : Expr) : MetaM Expr := + Meta.transform e + (pre := + fun e => do + if e.isSort || e.isForall then return .continue + let isPrf ← + try + isProof e + catch _ => + pure false + return if isPrf then .done (mkConst `«proof») else .continue) + (post := fun e => return .done e.eta) + +/-- Attributes recorded in environment extensions. They are read from the imported module +data directly, because `importModules (loadExts := true)` would run the imported modules' +initializers, which cannot be done for both environments in one process. -/ +structure EnvAttrs where + instances : NameMap String := {} + reducibility : NameMap ReducibilityStatus := {} + classes : NameMap (Array Nat) := {} + +def envAttrs (env : Environment) : EnvAttrs := + Id.run do + let mut a : EnvAttrs := {} + for i in [0:env.header.moduleNames.size] do + for e in Meta.instanceExtension.ext.getModuleEntries env i (level := .private) do + let (e, scope) := + match e with + | .global e => (e, "") + | .scoped ns e => (e, s!" scoped in {ns}") + if let some n := e.globalName? then + a := { a with instances := a.instances.insert n s!"{e.priority}{scope}" } + for e in reducibilityExtraExt.ext.getModuleEntries env i (level := .private) do + match e with + | .global (n, r) | .scoped _ (n, r) => + a := { a with reducibility := a.reducibility.insert n r } + for e in classExtension.getModuleEntries env i (level := .private) do + a := { a with classes := a.classes.insert e.name e.outParams } + return a + +/-- Structural equality ignoring binder names and metadata, but not binder info. -/ +partial def same : Expr → Expr → Bool + | .mdata _ a, b => same a b + | a, .mdata _ b => same a b + | .app f a, .app g b => same f g && same a b + | .lam _ t b i, .lam _ t' b' i' => i == i' && same t t' && same b b' + | .forallE _ t b i, .forallE _ t' b' i' => i == i' && same t t' && same b b' + | .letE _ t v b _, .letE _ t' v' b' _ => same t t' && same v v' && same b b' + | .proj s i e, .proj s' i' e' => s == s' && i == i' && same e e' + | a, b => a == b + +/-- What is compared between the subset and upstream versions of a declaration. -/ +structure Summary where + module : Name + kind : String + numLevelParams : Nat + type : Expr + value? : Option Expr := none + shape : String := "" + attrs : String := "" +deriving Inhabited + +def summarize (attrs : EnvAttrs) (n : Name) : MetaM Summary := do + let env ← getEnv + let ci ← getConstInfo n + let module := (moduleOf? env n).getD .anonymous + -- Universe parameter names are irrelevant to users; only their number and order matter. + let levels := ci.levelParams.mapIdx fun i _ => mkLevelParam (.num `u i) + let normalize (e : Expr) := + return (← eraseProofs e).instantiateLevelParams ci.levelParams levels + let type ← normalize ci.type + let reducibility := attrs.reducibility.find? n |>.getD (getReducibilityStatusCore env n) + let attrs := + s!"reducibility={repr reducibility} instance={attrs.instances.find? n} \ + classOutParams={attrs.classes.find? n} \ + structureFields={if isStructure env n then toString (getStructureFields env n) else "-"}" + let base : Summary := + { module, kind := "", numLevelParams := ci.levelParams.length, type, attrs } + match ci with + | .defnInfo d => + let value ← normalize d.value + return { + base with + kind := "def", value? := some value, shape := s!"safety={repr d.safety}" + } + | .thmInfo _ => return { base with kind := "theorem" } + | .opaqueInfo o => + let value ← normalize o.value + return { + base with + kind := "opaque", value? := some value, shape := s!"unsafe={o.isUnsafe}" + } + | .inductInfo i => + return { + base with + kind := "inductive" + shape := + s!"params={i.numParams} indices={i.numIndices} all={i.all} ctors={i.ctors} \ + nested={i.numNested} rec={i.isRec} unsafe={i.isUnsafe} reflexive={i.isReflexive}" + } + | .ctorInfo c => + return { + base with + kind := "constructor" + shape := + s!"induct={c.induct} cidx={c.cidx} params={c.numParams} fields={c.numFields} \ + unsafe={c.isUnsafe}" + } + | .recInfo r => + return { + base with + kind := "recursor" + shape := s!"all={r.all} params={r.numParams} indices={r.numIndices} \ + motives={r.numMotives} minors={r.numMinors} k={r.k} unsafe={r.isUnsafe}" + } + | .quotInfo _ => return { base with kind := "quot" } + | .axiomInfo _ => return { base with kind := "axiom" } + +/-- Equation lemmas are generated on demand, in whichever module first needs them. -/ +def isGeneratedEqn : Name → Bool + | .str _ s => + Meta.isEqnReservedNameSuffix s + || s == Meta.unfoldThmSuffix + || s == Meta.eqUnfoldThmSuffix + | _ => false + +/-- Differences between the subset and upstream summaries of a declaration. -/ +def diff (sub up : Summary) : IO (List String) := do + let mut out := [] + if sub.module != up.module then + out := s!"declared in {sub.module}, but upstream in {up.module}" :: out + if sub.kind != up.kind then + return [s!"is a {sub.kind}, but upstream a {up.kind}"] + if sub.numLevelParams != up.numLevelParams then + out := + s!"has {sub.numLevelParams} universe parameters, but upstream {up.numLevelParams}" + :: out + if !same sub.type up.type then + out := + s!"type differs from upstream:\n subset: {sub.type}\n upstream: {up.type}" + :: out + match sub.value?, up.value? with + | some v, some v' => + if !same v v' then + out := s!"value differs from upstream:\n subset: {v}\n upstream: {v'}" :: out + | _, _ => pure () + if sub.shape != up.shape then + out := s!"shape `{sub.shape}` differs from upstream `{up.shape}`" :: out + if sub.kind != "theorem" && sub.attrs != up.attrs then + out := s!"attributes `{sub.attrs}` differ from upstream `{up.attrs}`" :: out + return out.reverse + +/-- Metaprograms only affect elaboration, so their values are not compared. -/ +def isMeta (type : Expr) : Bool := + type.getUsedConstants.any (·.getRoot == `Lean) + +def main (args : List String) : IO UInt32 := do + let [dir] := args + | + IO.eprintln "usage: mathlib-subset-check " + return 2 + let dir ← IO.FS.realPath dir + let mods ← subsetModules dir + if mods.isEmpty then + IO.eprintln s!"no modules found under {dir}" + return 2 + let modSet : NameSet := mods.foldl (·.insert ·) {} + let builtin ← getBuiltinSearchPath (← findSysroot) + -- The subset environment sees only the subset's build output and the Lean core. + let subEnv ← loadEnv ([dir / ".lake" / "build" / "lib" / "lean"] ++ builtin) mods + -- Upstream comes from `LEAN_PATH`, which `lake exe` sets to this package's dependencies. + let upEnv ← loadEnv (← addSearchPathFromEnv builtin) mods + let subAttrs := envAttrs subEnv + let upAttrs := envAttrs upEnv + let names := + subEnv.constants.map₁.fold (init := #[]) + fun acc n _ => + match moduleOf? subEnv n with + | some m => if modSet.contains m then acc.push n else acc + | none => acc + let names := names.qsort Name.lt + let mut errors : Array String := #[] + let mut checked := 0 + let mut metaprograms := 0 + let mut subsetOnly := 0 + for n in names do + let some ci := subEnv.find? n | unreachable! + let axioms ← runIn subEnv (collectAxioms n) + for ax in axioms do + unless allowedAxioms.contains ax do + errors := errors.push s!"{n}: depends on axiom {ax}" + let internal := n.isInternalDetail || isPrivateName n + if (internal || isGeneratedEqn n) && ci matches .thmInfo _ then + subsetOnly := subsetOnly + 1 + continue + unless upEnv.contains n do + if internal then + subsetOnly := subsetOnly + 1 + else + errors := errors.push s!"{n}: not found upstream" + continue + let mut sub ← runIn subEnv (summarize subAttrs n) + let mut up ← runIn upEnv (summarize upAttrs n) + -- The types are still compared, so this only applies if upstream is a metaprogram too. + if isMeta up.type then + sub := { sub with value? := none } + up := { up with value? := none } + metaprograms := metaprograms + 1 + for d in ← diff sub up do + errors := errors.push s!"{n}: {d}" + checked := checked + 1 + IO.println + s!"{mods.size} modules, {names.size} declarations: {checked} match upstream \ + ({metaprograms} metaprograms, values not compared), {subsetOnly} internal (not compared)" + if errors.isEmpty then + IO.println "OK" + return 0 + for e in errors do + IO.eprintln e + IO.eprintln s!"{errors.size} problems found" + return 1 + +end MathlibSubsetCheck + +def main (args : List String) : IO UInt32 := + MathlibSubsetCheck.main args diff --git a/lean/mathlib-subset-check/lake-manifest.json b/lean/mathlib-subset-check/lake-manifest.json new file mode 100644 index 000000000000..22a4648c9baa --- /dev/null +++ b/lean/mathlib-subset-check/lake-manifest.json @@ -0,0 +1,117 @@ +{ + "version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.35.0", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "4a174c490d8707121c4a9290800489f105d85e07", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.35.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "mathlib_subset_check", + "lakeDir": ".lake", + "fixedToolchain": false +} diff --git a/lean/mathlib-subset-check/lakefile.toml b/lean/mathlib-subset-check/lakefile.toml new file mode 100644 index 000000000000..cd3019ca89da --- /dev/null +++ b/lean/mathlib-subset-check/lakefile.toml @@ -0,0 +1,15 @@ +name = "mathlib_subset_check" +version = "0.1.0" +defaultTargets = ["mathlib-subset-check"] + +# The upstream that `../mathlib-subset` is checked against. Keep `rev` in sync with +# the version stated in `../mathlib-subset/README.md`. +[[require]] +name = "mathlib" +git = "https://github.com/leanprover-community/mathlib4.git" +rev = "v4.35.0" + +[[lean_exe]] +name = "mathlib-subset-check" +root = "Main" +supportInterpreter = true diff --git a/lean/mathlib-subset-check/lean-toolchain b/lean/mathlib-subset-check/lean-toolchain new file mode 120000 index 000000000000..6f68e61b3719 --- /dev/null +++ b/lean/mathlib-subset-check/lean-toolchain @@ -0,0 +1 @@ +../lean-toolchain \ No newline at end of file diff --git a/lean/mathlib-subset/Batteries/Data/List/Basic.lean b/lean/mathlib-subset/Batteries/Data/List/Basic.lean new file mode 100644 index 000000000000..2f1f0a474d78 --- /dev/null +++ b/lean/mathlib-subset/Batteries/Data/List/Basic.lean @@ -0,0 +1,33 @@ +/- +Copyright (c) 2016 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura +-/ +module + +public section +namespace List +/-- Computes the difference of `l₁` and `l₂`, by removing each element in `l₂` from `l₁`. -/ +@[expose] protected def diff {α} [BEq α] : List α → List α → List α + | l, [] => l + | l₁, a :: l₂ => if l₁.elem a then List.diff (l₁.erase a) l₂ else List.diff l₁ l₂ +open Option Nat +/-- +Constructs the union of two lists, by inserting the elements of `l₁` in reverse order to `l₂`. +As a result, `l₂` will always be a suffix, but only the last occurrence of each element in `l₁` +will be retained (but order will otherwise be preserved). +-/ +@[expose, inline] protected def union [BEq α] (l₁ l₂ : List α) : List α := foldr .insert l₂ l₁ + +instance [BEq α] : Union (List α) := ⟨List.union⟩ +/-- +`pwFilter R l` is a maximal sublist of `l` which is `Pairwise R`. +`pwFilter (·≠·)` is the erase duplicates function (cf. `eraseDups`), and `pwFilter (·<·)` finds +a maximal increasing subsequence in `l`. For example, +``` +pwFilter (·<·) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] +``` +-/ +@[expose] def pwFilter (R : α → α → Prop) [DecidableRel R] (l : List α) : List α := + l.foldr (fun x IH => if ∀ y ∈ IH, R x y then x :: IH else IH) [] + diff --git a/lean/mathlib-subset/Batteries/Data/List/Perm.lean b/lean/mathlib-subset/Batteries/Data/List/Perm.lean new file mode 100644 index 000000000000..135b108a6d98 --- /dev/null +++ b/lean/mathlib-subset/Batteries/Data/List/Perm.lean @@ -0,0 +1,59 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro +-/ +module + +public import Batteries.Data.List.Basic + +public section + +open Nat + +namespace List + +theorem Perm.diff_right [BEq α] [LawfulBEq α] (t : List α) (h : l₁ ~ l₂) : + l₁.diff t ~ l₂.diff t := by + induction t generalizing l₁ l₂ h with simp only [List.diff] + | nil => exact h + | cons x t ih => + simp only [elem_eq_mem, decide_eq_true_eq, Perm.mem_iff h] + split + · exact ih (h.erase _) + · exact ih h + +theorem Perm.diff_left [BEq α] [LawfulBEq α] (l : List α) (h : t₁ ~ t₂) : + l.diff t₁ = l.diff t₂ := by + induction h generalizing l with try simp [List.diff] + | cons x _ ih => apply ite_congr rfl <;> (intro; apply ih) + | swap x y => + if h : x = y then + simp [h] + else + simp [mem_erase_of_ne h, mem_erase_of_ne (Ne.symm h), erase_comm x y] + split <;> simp + | trans => simp only [*] + +theorem Perm.diff [BEq α] [LawfulBEq α] {l₁ l₂ t₁ t₂ : List α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : + l₁.diff t₁ ~ l₂.diff t₂ := + ht.diff_left l₂ ▸ hl.diff_right _ + +theorem Perm.union_right [BEq α] [LawfulBEq α] (t₁ : List α) (h : l₁ ~ l₂) : + l₁ ∪ t₁ ~ l₂ ∪ t₁ := by + induction h with + | nil => exact .refl _ + | cons a _ ih => exact ih.insert a + | swap => apply perm_insert_swap + | trans _ _ ih_1 ih_2 => exact ih_1.trans ih_2 + +theorem Perm.union_left [BEq α] [LawfulBEq α] (l : List α) (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ := by + induction l with + | nil => exact h + | cons _ _ ih => exact Perm.insert _ ih + +theorem Perm.union [BEq α] [LawfulBEq α] {l₁ l₂ t₁ t₂ : List α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : + l₁ ∪ t₁ ~ l₂ ∪ t₂ := + (p₁.union_right t₁).trans (p₂.union_left l₂) + +end List diff --git a/lean/mathlib-subset/LICENSE b/lean/mathlib-subset/LICENSE new file mode 100644 index 000000000000..8dada3edaf50 --- /dev/null +++ b/lean/mathlib-subset/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/lean/mathlib-subset/Mathlib/Basic/SetLike/Basic.lean b/lean/mathlib-subset/Mathlib/Basic/SetLike/Basic.lean new file mode 100644 index 000000000000..4aea5ca1a5dd --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Basic/SetLike/Basic.lean @@ -0,0 +1,65 @@ +/- +Copyright (c) 2021 Eric Wieser. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Eric Wieser +-/ +module + +public import Mathlib.Data.Set.Basic + +@[expose] public section +/-- A class to indicate that there is a canonical injection between `A` and `Set B`. + +This has the effect of giving terms of `A` elements of type `B` (through a `Membership` +instance) and a compatible coercion to `Type*` as a subtype. + +Note: if `SetLike.coe` is a projection, implementers should create a simp lemma such as +``` +@[simp] lemma mem_carrier {p : MySubobject X} : x ∈ p.carrier ↔ x ∈ (p : Set X) := Iff.rfl +``` +to normalize terms. + +If you declare an unbundled subclass of `SetLike`, for example: +``` +class MulMemClass (S : Type*) (M : Type*) [Mul M] [SetLike S M] where + ... +``` +Then you should *not* repeat the `outParam` declaration so `SetLike` will supply the value instead. +This ensures your subclass will not have issues with synthesis of the `[Mul M]` parameter starting +before the value of `M` is known. +-/ +class SetLike (A : Type*) (B : outParam Type*) where + /-- The coercion from a term of a `SetLike` to its corresponding `Set`. -/ + protected coe : A → Set B + /-- The coercion from a term of a `SetLike` to its corresponding `Set` is injective. -/ + coe_injective : Function.Injective coe +namespace SetLike +variable {A : Type*} {B : Type*} [i : SetLike A B] + +instance : CoeTC A (Set B) where coe := SetLike.coe +instance (priority := 100) instMembership : Membership B A := + ⟨fun p x => x ∈ (p : Set B)⟩ +end SetLike +section default +variable (A : Type*) {B : Type*} +/-- The order induced from a `Membership` instance by inclusion. + +An order defined this way automatically makes available an instance of `IsConcreteLE`. +-/ +@[reducible] def LE.ofMembership [Membership B A] : LE A where + le H K := ∀ ⦃x⦄, x ∈ H → x ∈ K +/-- The preorder induced from a `Membership` instance by inclusion. + +A preorder defined this way automatically makes available an instance of `IsConcreteLE`. +-/ +@[reducible] def Preorder.ofMembership [Membership B A] : Preorder A where + __ := LE.ofMembership A + le_refl _ _ h := h + le_trans _ _ _ h₁ h₂ _ h₃ := h₂ (h₁ h₃) +/-- The partial order induced from a `SetLike` instance by inclusion. +A partial order defined this way automatically makes available an instance of `IsConcreteLE`. +-/ +@[reducible] def PartialOrder.ofSetLike [SetLike A B] : PartialOrder A where + __ := Preorder.ofMembership A + __ := PartialOrder.lift (SetLike.coe : A → Set B) SetLike.coe_injective +end default diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Card.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Card.lean new file mode 100644 index 000000000000..b153e5237adf --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Card.lean @@ -0,0 +1,39 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad +-/ +module + +public import Mathlib.Data.Nat.Notation +public import Mathlib.Data.Finset.Erase +public import Mathlib.Data.Finset.Filter +public import Mathlib.Data.Finset.SDiff + +@[expose] public section +open Function Multiset Nat +variable {α β : Type*} +namespace Finset +variable {s t u : Finset α} {a b c : α} +/-- `s.card` is the number of elements of `s`, aka its cardinality. + +The notation `#s` can be accessed in the `Finset` locale. -/ +def card (s : Finset α) : ℕ := + Multiset.card s.1 +section Lattice +variable [DecidableEq α] +theorem inter_nonempty_of_card_lt_card_add_card (hts : t ⊆ s) (hus : u ⊆ s) + (hstu : s.card < t.card + u.card) : (t ∩ u).Nonempty := by + refine Classical.byContradiction fun empty => Nat.lt_irrefl _ (Nat.lt_of_lt_of_le hstu ?_) + obtain ⟨⟨ls⟩, ns⟩ := s + obtain ⟨⟨lt⟩, nt⟩ := t + obtain ⟨⟨lu⟩, nu⟩ := u + have disjoint : ∀ a ∈ lt, ∀ b ∈ lu, a ≠ b := fun a ha _ hb e => + empty ⟨a, show a ∈ lt.filter (· ∈ lu) by simpa [e] using And.intro (e ▸ ha) hb⟩ + have h := (List.nodup_append.2 ⟨nt, nu, disjoint⟩).length_le_of_subset fun a ha => + (List.mem_append.1 ha).elim (fun h => hts h) (fun h => hus h) + rw [List.length_append] at h + exact h +end Lattice +end Finset +open scoped Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Dedup.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Dedup.lean new file mode 100644 index 000000000000..cbb8e0309477 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Dedup.lean @@ -0,0 +1,26 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Defs +public import Mathlib.Data.Multiset.Dedup + +@[expose] public section +open Multiset Function +universe u +variable {α : Type*} {β : Type*} +namespace Multiset +variable [DecidableEq α] {s t : Multiset α} +/-- `toFinset s` removes duplicates from the multiset `s` to produce a finset. -/ +def toFinset (s : Multiset α) : Finset α := + ⟨_, nodup_dedup s⟩ +end Multiset +namespace List +variable [DecidableEq α] {l l' : List α} {a : α} {s : Finset α} +/-- `toFinset l` removes duplicates from the list `l` to produce a finset. -/ +def toFinset (l : List α) : Finset α := + Multiset.toFinset l +end List diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Defs.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Defs.lean new file mode 100644 index 000000000000..c8d0a6bc263d --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Defs.lean @@ -0,0 +1,63 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro +-/ +module + +public import Mathlib.Basic.SetLike.Basic +public import Mathlib.Data.Multiset.Defs + +@[expose] public section +open Multiset Subtype Function +universe u +variable {α : Type*} {β : Type*} +/-- `Finset α` is the type of finite sets of elements of `α`. It is implemented + as a multiset (a list up to permutation) which has no duplicate elements. -/ + +@[use_set_notation_for_order] +structure Finset (α : Type*) where + /-- The underlying multiset -/ + val : Multiset α + /-- `val` contains no duplicates -/ + nodup : Nodup val +namespace Finset +@[simp] +theorem val_inj {s t : Finset α} : s.1 = t.1 ↔ s = t := + ⟨fun h => by cases s; cases t; cases h; rfl, fun h => h ▸ rfl⟩ +instance decidableEq [DecidableEq α] : DecidableEq (Finset α) + | _, _ => decidable_of_iff _ val_inj +/-- Convert a finset to a set in the natural way. -/ +instance : SetLike (Finset α) α where + coe s := Set.ofPred fun a => a ∈ s.1 + coe_injective s₁ s₂ h := by + rcases s₁ with ⟨v₁, n₁⟩ + rcases s₂ with ⟨v₂, n₂⟩ + induction v₁ using Quot.ind + induction v₂ using Quot.ind + congr 1 + exact Quot.sound ((List.perm_ext_iff_of_nodup n₁ n₂).2 fun a => + iff_of_eq (congrArg (fun t : Set α => a ∈ t) h)) +@[simp] +theorem mem_val {a : α} {s : Finset α} : (a ∈ s.1) = (a ∈ s) := rfl +instance decidableMem [_h : DecidableEq α] (a : α) (s : Finset α) : Decidable (a ∈ s) := + Multiset.decidableMem _ _ +instance : PartialOrder (Finset α) := .ofSetLike (Finset α) +section DecidablePiExists +variable {s : Finset α} +instance decidableDforallFinset {p : ∀ a ∈ s, Prop} [_hp : ∀ (a) (h : a ∈ s), Decidable (p a h)] : + Decidable (∀ (a) (h : a ∈ s), p a h) := + Multiset.decidableDforallMultiset +instance instDecidableRelSubset [DecidableEq α] : DecidableRel (α := Finset α) (· ⊆ ·) := + fun _ _ ↦ decidableDforallFinset +instance decidableDExistsFinset {p : ∀ a ∈ s, Prop} [_hp : ∀ (a) (h : a ∈ s), Decidable (p a h)] : + Decidable (∃ (a : _) (h : a ∈ s), p a h) := + Multiset.decidableDexistsMultiset +instance decidableExistsAndFinset {p : α → Prop} [_hp : ∀ (a), Decidable (p a)] : + Decidable (∃ a ∈ s, p a) := + decidable_of_iff (∃ (a : _) (_ : a ∈ s), p a) + ⟨fun ⟨a, h, hp⟩ => ⟨a, h, hp⟩, fun ⟨a, h, hp⟩ => ⟨a, h, hp⟩⟩ +instance decidableExistsAndFinsetCoe {p : α → Prop} [DecidablePred p] : + Decidable (∃ a ∈ (s : Set α), p a) := decidableExistsAndFinset +end DecidablePiExists +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Empty.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Empty.lean new file mode 100644 index 000000000000..09ba7251b4db --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Empty.lean @@ -0,0 +1,31 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Defs +public import Mathlib.Data.Multiset.ZeroCons + +@[expose] public section +open Multiset Subtype +universe u +variable {α : Type*} +namespace Finset +/-- The property `s.Nonempty` expresses the fact that the finset `s` is not empty. It should be used +in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks +to the dot notation. -/ +protected def Nonempty (s : Finset α) : Prop := ∃ x : α, x ∈ s +instance decidableNonempty {s : Finset α} : Decidable s.Nonempty := + decidable_of_iff (∃ a ∈ s, true) + ⟨fun ⟨a, h, _⟩ => ⟨a, h⟩, fun ⟨a, h⟩ => ⟨a, h, rfl⟩⟩ +section Empty +variable {s : Finset α} +/-- The empty finset -/ +protected def empty : Finset α := + ⟨0, nodup_zero⟩ +instance : EmptyCollection (Finset α) := + ⟨Finset.empty⟩ +end Empty +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Erase.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Erase.lean new file mode 100644 index 000000000000..e9fe330d06e5 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Erase.lean @@ -0,0 +1,27 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Defs +public import Mathlib.Data.Multiset.Filter + +@[expose] public section +open Multiset +universe u +variable {α : Type*} +namespace Finset +section Erase +variable [DecidableEq α] {s t : Finset α} {a b : α} +/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are + not equal to `a`. -/ +def erase (s : Finset α) (a : α) : Finset α := + ⟨_, s.2.erase a⟩ +@[simp] +theorem mem_erase {a b : α} {s : Finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := by + obtain ⟨⟨l⟩, nd⟩ := s + exact List.Nodup.mem_erase_iff nd +end Erase +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Filter.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Filter.lean new file mode 100644 index 000000000000..a89acd45a09a --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Filter.lean @@ -0,0 +1,31 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Empty +public import Mathlib.Data.Multiset.Filter + +@[expose] public section +open Multiset Subtype Function +universe u +variable {α : Type*} {β : Type*} +namespace Finset +section Filter +variable (p : α → Prop) [DecidablePred p] {s t : Finset α} +/-- `Finset.filter p s` is the set of elements of `s` that satisfy `p`. + +For example, one can use `s.filter (· ∈ t)` to get the intersection of `s` with `t : Set α` +as a `Finset α` (when a `DecidablePred (· ∈ t)` instance is available). -/ +def filter (s : Finset α) : Finset α := + ⟨_, s.2.filter p⟩ +variable {p} +@[simp] +theorem mem_filter {s : Finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := by + obtain ⟨⟨l⟩, _⟩ := s + show a ∈ l.filter (fun x => decide (p x)) ↔ a ∈ l ∧ p a + simp +end Finset.Filter + diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Fold.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Fold.lean new file mode 100644 index 000000000000..00af5b04ef87 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Fold.lean @@ -0,0 +1,25 @@ +/- +Copyright (c) 2017 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Erase +public import Mathlib.Data.Finset.Filter +public import Mathlib.Data.Finset.SDiff +public import Mathlib.Data.Multiset.Fold + +@[expose] public section +namespace Finset +open Multiset +variable {α β γ : Type*} +section Fold +variable (op : β → β → β) [hc : Std.Commutative op] [ha : Std.Associative op] +/-- `fold op b f s` folds the commutative associative operation `op` over the + `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = f 1 + f 2 + f 3 + b`. -/ +def fold (b : β) (f : α → β) (s : Finset α) : β := + (s.1.map f).fold op b +variable {op} {f : α → β} {b : β} {s : Finset α} {a : α} +end Fold +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Insert.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Insert.lean new file mode 100644 index 000000000000..54c9b64bc126 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Insert.lean @@ -0,0 +1,40 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Dedup +public import Mathlib.Data.Finset.Empty +public import Mathlib.Data.Multiset.FinsetOps + +@[expose] public section +open Multiset Subtype Function +universe u +variable {α : Type*} {β : Type*} +namespace Finset +section Singleton +variable {s : Finset α} {a b : α} +/-- `{a} : Finset a` is the set `{a}` containing `a` and nothing else. + +This differs from `insert a ∅` in that it does not require a `DecidableEq` instance for `α`. +-/ +instance : Singleton α (Finset α) := + ⟨fun a => ⟨{a}, nodup_singleton a⟩⟩ +@[simp] +theorem mem_singleton {a b : α} : b ∈ ({a} : Finset α) ↔ b = a := by + show b ∈ [a] ↔ b = a + simp +end Singleton +section Insert +variable [DecidableEq α] {s t : Finset α} {a b : α} {f : α → β} +/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ +instance : Insert α (Finset α) := + ⟨fun a s => ⟨_, s.2.ndinsert a⟩⟩ +@[simp] +theorem mem_insert : a ∈ insert b s ↔ a = b ∨ a ∈ s := by + obtain ⟨⟨l⟩, _⟩ := s + exact List.mem_insert_iff +end Insert +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Lattice/Basic.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Lattice/Basic.lean new file mode 100644 index 000000000000..8b2db86b91b1 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Lattice/Basic.lean @@ -0,0 +1,42 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Defs +public import Mathlib.Data.Multiset.FinsetOps + +public section +open Multiset +universe u +variable {α : Type*} +namespace Finset +section Lattice +variable [DecidableEq α] {s s₁ s₂ t t₁ t₂ u v : Finset α} {a : α} +/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ +instance : Union (Finset α) := + ⟨fun s t => ⟨_, t.2.ndunion s.1⟩⟩ +@[simp] +theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := by + obtain ⟨⟨l₁⟩, n₁⟩ := s + obtain ⟨⟨l₂⟩, -⟩ := t + show a ∈ List.union l₁ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ + clear n₁ + induction l₁ with + | nil => simp [List.union] + | cons b l ih => simp_all [List.union, or_assoc] +/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ +instance : Inter (Finset α) := + ⟨fun s t => ⟨_, s.2.ndinter t.1⟩⟩ +@[simp] +theorem mem_inter {a : α} {s₁ s₂ : Finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := by + obtain ⟨⟨l₁⟩, _⟩ := s₁ + obtain ⟨⟨l₂⟩, _⟩ := s₂ + show a ∈ l₁.filter (· ∈ l₂) ↔ a ∈ l₁ ∧ a ∈ l₂ + simp +@[simp] lemma inter_subset_left : s₁ ∩ s₂ ⊆ s₁ := fun _ h ↦ (mem_inter.1 h).1 +@[simp] lemma inter_subset_right : s₁ ∩ s₂ ⊆ s₂ := fun _ h ↦ (mem_inter.1 h).2 +end Lattice +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Lattice/Fold.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Lattice/Fold.lean new file mode 100644 index 000000000000..beb1a84f6465 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Lattice/Fold.lean @@ -0,0 +1,22 @@ +/- +Copyright (c) 2018 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Card +public import Mathlib.Data.Finset.Fold +public import Mathlib.Order.WithBot + +@[expose] public section +open Function Multiset +variable {F α β γ ι : Type*} +namespace Finset +section Inf +variable [SemilatticeInf α] [OrderTop α] +/-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ +def inf (s : Finset β) (f : β → α) : α := + s.fold (· ⊓ ·) ⊤ f +end Inf +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Max.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Max.lean new file mode 100644 index 000000000000..688ec0a50c7e --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Max.lean @@ -0,0 +1,49 @@ +/- +Copyright (c) 2018 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Lattice.Fold + +@[expose] public section +open Function Multiset +variable {α β ι : Type*} +namespace Finset +section MaxMin +variable [LinearOrder α] +/-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, +and `⊤` otherwise. It belongs to `WithTop α`. If you want to get an element of `α`, see +`s.min'`. -/ +protected def min (s : Finset α) : WithTop α := + inf s WithTop.some +private theorem foldr_inf_some (l : List α) : + ((l.map WithTop.some).foldr (· ⊓ ·) ⊤ = ⊤ ∧ l = []) ∨ + ∃ a ∈ l, (l.map WithTop.some).foldr (· ⊓ ·) ⊤ = WithTop.some a := by + induction l with + | nil => exact .inl ⟨rfl, rfl⟩ + | cons b l ih => + refine .inr ?_ + rcases ih with ⟨h, _⟩ | ⟨y, hy, h⟩ + · exact ⟨b, List.mem_cons_self, by simp only [List.map_cons, List.foldr_cons, h]; rfl⟩ + · simp only [List.map_cons, List.foldr_cons, h] + show ∃ a ∈ b :: l, WithTop.some (min b y) = WithTop.some a + rw [LinearOrder.min_def] + split + · exact ⟨b, List.mem_cons_self, rfl⟩ + · exact ⟨y, List.mem_cons_of_mem _ hy, rfl⟩ +theorem min_of_nonempty {s : Finset α} (h : s.Nonempty) : ∃ a : α, s.min = a := by + obtain ⟨⟨l⟩, _⟩ := s + obtain ⟨x, hx⟩ := h + rcases foldr_inf_some l with ⟨_, rfl⟩ | ⟨a, _, h⟩ + · exact absurd hx List.not_mem_nil + · exact ⟨a, h⟩ +theorem mem_of_min {s : Finset α} : ∀ {a : α}, s.min = a → a ∈ s := by + obtain ⟨⟨l⟩, _⟩ := s + intro a (ha : (l.map WithTop.some).foldr (· ⊓ ·) ⊤ = WithTop.some a) + rcases foldr_inf_some l with ⟨h, _⟩ | ⟨b, hb, h⟩ + · exact absurd (h.symm.trans ha) nofun + · exact (Option.some.inj (h.symm.trans ha)) ▸ hb +end MaxMin +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/SDiff.lean b/lean/mathlib-subset/Mathlib/Data/Finset/SDiff.lean new file mode 100644 index 000000000000..ddca92935957 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/SDiff.lean @@ -0,0 +1,34 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Insert +public import Mathlib.Data.Finset.Lattice.Basic + +public section +open Multiset +universe u +variable {α : Type*} +namespace Finset +section Sdiff +variable [DecidableEq α] {s t u v : Finset α} {a b : α} +/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ +instance instSDiff : SDiff (Finset α) := + ⟨fun s₁ s₂ => ⟨s₁.1 - s₂.1, by + rcases s₁ with ⟨v₁, h₁⟩ + generalize s₂.1 = v₂ + induction v₁ using Quot.ind with | _ l₁ => + induction v₂ using Quot.ind with | _ l₂ => + show List.Nodup (l₁.diff l₂) + induction l₂ generalizing l₁ with + | nil => exact h₁ + | cons a l ih => + show List.Nodup (if l₁.elem a then (l₁.erase a).diff l else l₁.diff l) + split + · exact ih _ (List.Nodup.erase a h₁) + · exact ih _ h₁⟩⟩ +end Sdiff +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/Finset/Sort.lean b/lean/mathlib-subset/Mathlib/Data/Finset/Sort.lean new file mode 100644 index 000000000000..9fe05b2023ab --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Finset/Sort.lean @@ -0,0 +1,30 @@ +/- +Copyright (c) 2017 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Finset.Max +public import Mathlib.Data.Multiset.Sort + +@[expose] public section +namespace Finset +open Multiset Nat +variable {α β : Type*} +section sort +/-- `sort s` constructs a sorted list from the unordered set `s`. + (Uses merge sort algorithm.) -/ +def sort (s : Finset α) (r : α → α → Prop := by exact fun a b => a ≤ b) + [DecidableRel r] [IsTrans α r] [Std.Antisymm r] [Std.Total r] : List α := + Multiset.sort s.1 r +section +variable {m : Multiset α} {s : Finset α} +variable (r : α → α → Prop) [DecidableRel r] [IsTrans α r] [Std.Antisymm r] [Std.Total r] +@[simp] +theorem mem_sort {a : α} : a ∈ sort s r ↔ a ∈ s := by + obtain ⟨⟨l⟩, _⟩ := s + exact List.mem_mergeSort +end +end sort +end Finset diff --git a/lean/mathlib-subset/Mathlib/Data/List/Dedup.lean b/lean/mathlib-subset/Mathlib/Data/List/Dedup.lean new file mode 100644 index 000000000000..128f62a192ea --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/List/Dedup.lean @@ -0,0 +1,43 @@ +/- +Copyright (c) 2018 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.List.Defs + +public section + +universe u + +namespace List + +variable {α β : Type*} [DecidableEq α] + +theorem mem_dedup {a : α} {l : List α} : a ∈ dedup l ↔ a ∈ l := by + induction l generalizing a with + | nil => exact Iff.rfl + | cons x l ih => + show a ∈ (if ∀ y ∈ dedup l, x ≠ y then x :: dedup l else dedup l) ↔ a ∈ x :: l + split + · rw [mem_cons, mem_cons, ih] + · next h => + have hx : x ∈ l := + Classical.byContradiction fun hx => h fun y hy hxy => hx (hxy ▸ ih.1 hy) + rw [ih, mem_cons] + exact ⟨Or.inr, fun h' => h'.elim (fun e => e ▸ hx) id⟩ + +theorem nodup_dedup : ∀ l : List α, Nodup (dedup l) + | [] => Pairwise.nil + | x :: l => by + show Pairwise (· ≠ ·) (if ∀ y ∈ dedup l, x ≠ y then x :: dedup l else dedup l) + split + · exact pairwise_cons.2 ⟨‹_›, nodup_dedup l⟩ + · exact nodup_dedup l + +theorem Perm.dedup {l₁ l₂ : List α} (p : l₁ ~ l₂) : dedup l₁ ~ dedup l₂ := + (perm_ext_iff_of_nodup (nodup_dedup l₁) (nodup_dedup l₂)).2 fun _ => by + rw [mem_dedup, mem_dedup]; exact p.mem_iff + +end List diff --git a/lean/mathlib-subset/Mathlib/Data/List/Defs.lean b/lean/mathlib-subset/Mathlib/Data/List/Defs.lean new file mode 100644 index 000000000000..97778df6f35a --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/List/Defs.lean @@ -0,0 +1,26 @@ +/- +Copyright (c) 2014 Parikshit Khanna. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro +-/ +module + +public import Batteries.Data.List.Basic +public import Mathlib.Data.Set.Defs + +@[expose] public section +namespace List +open Nat +universe u v w x +variable {α β γ δ ε ζ : Type*} +/-- `dedup l` removes duplicates from `l` (taking only the last occurrence). +Defined as `pwFilter (≠)`. + +See also `eraseDups` which keeps the first occurrence instead: +``` +dedup [2, 0, 1, 0, 2, 0] = [1, 2, 0] +eraseDups [2, 0, 1, 0, 2, 0] = [2, 0, 1] +``` -/ +def dedup [DecidableEq α] : List α → List α := + pwFilter (· ≠ ·) +end List diff --git a/lean/mathlib-subset/Mathlib/Data/List/Infix.lean b/lean/mathlib-subset/Mathlib/Data/List/Infix.lean new file mode 100644 index 000000000000..455e8603a2f8 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/List/Infix.lean @@ -0,0 +1,11 @@ +/- +Copyright (c) 2017 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public section +namespace List +attribute [refl] prefix_refl suffix_refl infix_refl +end List diff --git a/lean/mathlib-subset/Mathlib/Data/List/Perm/Basic.lean b/lean/mathlib-subset/Mathlib/Data/List/Perm/Basic.lean new file mode 100644 index 000000000000..3f8b1ef7155f --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/List/Perm/Basic.lean @@ -0,0 +1,27 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro +-/ +module + +public import Batteries.Data.List.Basic +public import Mathlib.Logic.Function.Basic +public import Mathlib.Logic.OpClass +public import Mathlib.Order.Defs.Prop + +public section +namespace List + +variable {α β : Type*} + +theorem Perm.foldr_eq {f : α → β → β} {l₁ l₂ : List α} [lcomm : LeftCommutative f] (p : l₁ ~ l₂) : + ∀ b, foldr f b l₁ = foldr f b l₂ := by + intro b + induction p generalizing b with + | nil => rfl + | cons _ _ r => simp [r b] + | swap x y l => exact lcomm.left_comm y x _ + | trans _ _ r₁ r₂ => exact Eq.trans (r₁ b) (r₂ b) + +end List diff --git a/lean/mathlib-subset/Mathlib/Data/List/Sort.lean b/lean/mathlib-subset/Mathlib/Data/List/Sort.lean new file mode 100644 index 000000000000..1af75b99d5f3 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/List/Sort.lean @@ -0,0 +1,94 @@ +/- +Copyright (c) 2016 Jeremy Avigad. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Jeremy Avigad, Wrenna Robson +-/ +module + +public import Mathlib.Data.Nat.Notation +public import Mathlib.Data.List.Defs +public import Mathlib.Data.Set.Basic + +public section +namespace List +section sort +variable {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) +variable [DecidableRel r] [DecidableRel s] + +local infixl:50 " ≼ " => r +local infixl:50 " ≼ " => s +section InsertionSort +/-- `orderedInsert a l` inserts `a` into `l` at such that + `orderedInsert a l` is sorted if `l` is. -/ +def orderedInsert (a : α) : List α → List α + | [] => [a] + | b :: l => if a ≼ b then a :: b :: l else b :: orderedInsert a l +/-- `insertionSort l` returns `l` sorted using the insertion sort algorithm. -/ +def insertionSort : List α → List α := foldr (orderedInsert r) [] +section Correctness +theorem perm_orderedInsert (a) : ∀ l : List α, orderedInsert r a l ~ a :: l + | [] => Perm.refl _ + | b :: l => by + by_cases h : a ≼ b + · simp [orderedInsert, h] + · simpa [orderedInsert, h] using ((perm_orderedInsert a l).cons b).trans (Perm.swap a b l) +theorem perm_insertionSort (l : List α) : insertionSort r l ~ l := by + induction l with + | nil => exact Perm.refl _ + | cons b l ih => exact (perm_orderedInsert r b _).trans (ih.cons b) +variable {r} +section TotalAndTransitive +variable [Std.Total r] [IsTrans α r] +theorem Pairwise.orderedInsert (a : α) : ∀ l, Pairwise r l → Pairwise r (orderedInsert r a l) + | [], _ => pairwise_singleton _ a + | b :: l, h => by + unfold List.orderedInsert + split + · next h' => + refine pairwise_cons.2 ⟨fun c hc => ?_, h⟩ + rcases mem_cons.1 hc with hc | hc + · exact hc ▸ h' + · exact IsTrans.trans _ _ _ h' (rel_of_pairwise_cons h hc) + · next h' => + refine pairwise_cons.2 ⟨fun c hc => ?_, Pairwise.orderedInsert a l h.of_cons⟩ + rcases mem_cons.1 ((perm_orderedInsert r a l).mem_iff.1 hc) with hc | hc + · exact hc ▸ (Std.Total.total (r := r) b a).resolve_right h' + · exact rel_of_pairwise_cons h hc +variable (r) +/-- The list `List.insertionSort r l` is `List.Pairwise` with respect to `r`. -/ +theorem pairwise_insertionSort : ∀ l, Pairwise r (insertionSort r l) + | [] => Pairwise.nil + | a :: l => (pairwise_insertionSort l).orderedInsert a _ +end TotalAndTransitive +end Correctness +end InsertionSort +section MergeSort +section Correctness +section Antisymm +variable {r : α → α → Prop} [Std.Antisymm r] +/-- Variant of `Perm.eq_of_pairwise` using relation typeclasses. -/ +theorem Perm.eq_of_pairwise' {l₁ l₂ : List α} : + Pairwise r l₁ → Pairwise r l₂ → (hl : l₁ ~ l₂) → l₁ = l₂ := + Perm.eq_of_pairwise fun a b _ _ => Std.Antisymm.antisymm a b +end Antisymm +section TotalAndTransitive +variable {r} [Std.Total r] [IsTrans α r] +variable (r) +/-- Variant of `pairwise_mergeSort` using relation typeclasses. -/ +theorem pairwise_mergeSort' (l : List α) : Pairwise r (mergeSort l (r · ·)) := + (pairwise_mergeSort (le := (r · ·)) + (fun a b c h₁ h₂ => decide_eq_true (IsTrans.trans a b c (of_decide_eq_true h₁) + (of_decide_eq_true h₂))) + (fun a b => (Std.Total.total (r := r) a b).elim + (fun h => by simp [decide_eq_true h]) (fun h => by simp [decide_eq_true h])) + l).imp of_decide_eq_true +variable [Std.Antisymm r] +theorem mergeSort_eq_insertionSort (l : List α) : + mergeSort l (r · ·) = insertionSort r l := + ((mergeSort_perm l _).trans (perm_insertionSort r l).symm).eq_of_pairwise' + (pairwise_mergeSort' r l) (pairwise_insertionSort r l) +end TotalAndTransitive +end Correctness +end MergeSort +end sort +end List diff --git a/lean/mathlib-subset/Mathlib/Data/Multiset/AddSub.lean b/lean/mathlib-subset/Mathlib/Data/Multiset/AddSub.lean new file mode 100644 index 000000000000..48c8a48b45b9 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Multiset/AddSub.lean @@ -0,0 +1,38 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Batteries.Data.List.Perm +public import Mathlib.Data.Multiset.ZeroCons + +@[expose] public section +universe v +open List Nat +variable {α : Type*} {β : Type v} +namespace Multiset +section Erase +variable [DecidableEq α] {s t : Multiset α} {a b : α} +/-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ +def erase (s : Multiset α) (a : α) : Multiset α := + Quot.liftOn s (fun l => (l.erase a : Multiset α)) fun _l₁ _l₂ p => Quot.sound (p.erase a) +end Erase +section sub +variable [DecidableEq α] {s t u : Multiset α} {a : α} +/-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. +(note that it is truncated subtraction, so `count a (s - t) = 0` if `count a s ≤ count a t`). -/ +protected def sub (s t : Multiset α) : Multiset α := + (Quotient.liftOn₂ s t fun l₁ l₂ => (l₁.diff l₂ : Multiset α)) fun _v₁ _v₂ _w₁ _w₂ p₁ p₂ => + Quot.sound <| p₁.diff p₂ +instance : Sub (Multiset α) := ⟨.sub⟩ +end sub +section Nodup +theorem Nodup.erase [DecidableEq α] (a : α) {l} : Nodup l → Nodup (l.erase a) := + Quot.inductionOn l fun _ => List.Nodup.erase a +@[simp] +theorem nodup_singleton : ∀ a : α, Nodup ({a} : Multiset α) := + fun _ => List.nodup_cons.2 ⟨List.not_mem_nil, List.nodup_nil⟩ +end Nodup +end Multiset diff --git a/lean/mathlib-subset/Mathlib/Data/Multiset/Dedup.lean b/lean/mathlib-subset/Mathlib/Data/Multiset/Dedup.lean new file mode 100644 index 000000000000..6acf0933e790 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Multiset/Dedup.lean @@ -0,0 +1,21 @@ +/- +Copyright (c) 2017 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.List.Dedup +public import Mathlib.Data.Multiset.Filter + +@[expose] public section +namespace Multiset +open List +variable {α β : Type*} [DecidableEq α] +/-- `dedup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ +def dedup (s : Multiset α) : Multiset α := + Quot.liftOn s (fun l => (l.dedup : Multiset α)) fun _ _ p => Quot.sound p.dedup +@[simp] +theorem nodup_dedup (s : Multiset α) : Nodup (dedup s) := + Quot.ind (β := fun s => Nodup (dedup s)) List.nodup_dedup s +end Multiset diff --git a/lean/mathlib-subset/Mathlib/Data/Multiset/Defs.lean b/lean/mathlib-subset/Mathlib/Data/Multiset/Defs.lean new file mode 100644 index 000000000000..429ddee52b56 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Multiset/Defs.lean @@ -0,0 +1,106 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Nat.Notation +public import Mathlib.Data.List.Defs +public import Mathlib.Data.List.Perm.Basic +public import Mathlib.Data.Nat.Basic +public import Mathlib.Order.RelClasses + +@[expose] public section +universe v +open List Subtype Nat +variable {α : Type*} {β : Type v} +/-- `Multiset α` is the quotient of `List α` by list permutation. The result + is a type of finite sets with duplicates allowed. -/ +def Multiset.{u} (α : Type u) : Type u := + Quotient (List.isSetoid α) +namespace Multiset +/-- The quotient map from `List α` to `Multiset α`. -/ +@[coe] +def ofList : List α → Multiset α := + Quot.mk _ + +instance : Coe (List α) (Multiset α) := + ⟨ofList⟩ +instance [DecidableEq α] (l₁ l₂ : List α) : Decidable (l₁ ≈ l₂) := + inferInstanceAs (Decidable (l₁ ~ l₂)) +instance [DecidableEq α] (l₁ l₂ : List α) : Decidable ((isSetoid α).r l₁ l₂) := + inferInstanceAs (Decidable (l₁ ~ l₂)) +instance decidableEq [DecidableEq α] : DecidableEq (Multiset α) + | s₁, s₂ => Quotient.recOnSubsingleton₂ s₁ s₂ fun _ _ => decidable_of_iff' _ ⟨Quotient.exact, Quotient.sound⟩ +section Mem +/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ +def Mem (s : Multiset α) (a : α) : Prop := + Quot.liftOn s (fun l => a ∈ l) fun l₁ l₂ (e : l₁ ~ l₂) => propext e.mem_iff +instance : Membership α (Multiset α) := + ⟨Mem⟩ +instance decidableMem [DecidableEq α] (a : α) (s : Multiset α) : Decidable (a ∈ s) := + Quot.recOnSubsingleton s fun l ↦ inferInstanceAs (Decidable (a ∈ l)) +end Mem +/-- The cardinality of a multiset is the sum of the multiplicities + of all its elements, or simply the length of the underlying list. -/ +def card : Multiset α → ℕ := Quot.lift length fun _l₁ _l₂ => Perm.length_eq +/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset + `s` whose elements are all in the domain of `f`. -/ +nonrec def pmap {p : α → Prop} (f : ∀ a, p a → β) (s : Multiset α) : (∀ a ∈ s, p a) → Multiset β := + Quot.recOn s (fun l H => ↑(pmap f l H)) fun l₁ l₂ (pp : l₁ ~ l₂) => + funext fun H₂ : ∀ a ∈ l₂, p a => + have H₁ : ∀ a ∈ l₁, p a := fun a h => H₂ a (pp.subset h) + have : ∀ {s₂ e H}, @Eq.ndrec (Multiset α) l₁ (fun s => (∀ a ∈ s, p a) → Multiset β) + (fun _ => ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁) := by + intro s₂ e _; subst e; rfl + this.trans <| Quot.sound <| pp.pmap f +/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce + a multiset on `{x // x ∈ s}`. -/ +def attach (s : Multiset α) : Multiset { x // x ∈ s } := + pmap Subtype.mk s fun _a => id + +theorem mem_attach (s : Multiset α) : ∀ x, x ∈ s.attach := + Quot.inductionOn s fun _l => List.mem_attach _ +section Decidable +variable {m : Multiset α} +/-- If `p` is a decidable predicate, +so is the predicate that all elements of a multiset satisfy `p`. -/ +protected def decidableForallMultiset {p : α → Prop} [∀ a, Decidable (p a)] : + Decidable (∀ a ∈ m, p a) := + Quotient.recOnSubsingleton m fun l => decidable_of_iff (∀ a ∈ l, p a) Iff.rfl +instance decidableDforallMultiset {p : ∀ a ∈ m, Prop} [_hp : ∀ (a) (h : a ∈ m), Decidable (p a h)] : + Decidable (∀ (a) (h : a ∈ m), p a h) := + @decidable_of_iff _ _ + (Iff.intro (fun h a ha => h ⟨a, ha⟩ (mem_attach _ _)) fun h ⟨_a, _ha⟩ _ => h _ _) + (@Multiset.decidableForallMultiset _ m.attach (fun a => p a.1 a.2) _) +/-- If `p` is a decidable predicate, +so is the existence of an element in a multiset satisfying `p`. -/ +protected def decidableExistsMultiset {p : α → Prop} [DecidablePred p] : Decidable (∃ x ∈ m, p x) := + Quotient.recOnSubsingleton m fun l => decidable_of_iff (∃ a ∈ l, p a) Iff.rfl +instance decidableDexistsMultiset {p : ∀ a ∈ m, Prop} [_hp : ∀ (a) (h : a ∈ m), Decidable (p a h)] : + Decidable (∃ (a : _) (h : a ∈ m), p a h) := + @decidable_of_iff _ _ + (Iff.intro (fun ⟨⟨a, ha₁⟩, _, ha₂⟩ => ⟨a, ha₁, ha₂⟩) fun ⟨a, ha₁, ha₂⟩ => + ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩) + (@Multiset.decidableExistsMultiset { a // a ∈ m } m.attach (fun a => p a.1 a.2) _) +end Decidable +section Nodup +/-- `Nodup s` means that `s` has no duplicates, i.e. the multiplicity of + any element is at most 1. -/ +def Nodup (s : Multiset α) : Prop := + Quot.liftOn s List.Nodup fun _ _ p => propext p.nodup_iff +end Nodup +section SizeOf +/-- Defines a size for a multiset by referring to the size of the underlying list. + +This has to be defined before the definition of `Finset`, otherwise its automatically generated +`SizeOf` instance will be wrong. +-/ +protected noncomputable +def sizeOf [SizeOf α] (s : Multiset α) : ℕ := + (Quot.liftOn s SizeOf.sizeOf) fun _ _ => Perm.sizeOf_eq_sizeOf +noncomputable instance [SizeOf α] : SizeOf (Multiset α) := + ⟨Multiset.sizeOf⟩ +end SizeOf +end Multiset diff --git a/lean/mathlib-subset/Mathlib/Data/Multiset/Filter.lean b/lean/mathlib-subset/Mathlib/Data/Multiset/Filter.lean new file mode 100644 index 000000000000..1143d1cb4742 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Multiset/Filter.lean @@ -0,0 +1,24 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro, Rudy Peterson +-/ +module + +public import Mathlib.Data.Multiset.MapFold + +@[expose] public section +universe v +open List Subtype Nat Function +variable {α : Type*} {β : Type v} {γ : Type*} +namespace Multiset +section +variable (p : α → Prop) [DecidablePred p] +/-- `Filter p s` returns the elements in `s` (with the same multiplicities) + which satisfy `p`, and removes the rest. -/ +def filter (s : Multiset α) : Multiset α := + Quot.liftOn s (fun l => (List.filter p l : Multiset α)) fun _l₁ _l₂ h => Quot.sound <| h.filter p +end +theorem Nodup.filter (p : α → Prop) [DecidablePred p] {s} : Nodup s → Nodup (filter p s) := + Quot.inductionOn s fun _ => List.Pairwise.filter _ +end Multiset diff --git a/lean/mathlib-subset/Mathlib/Data/Multiset/FinsetOps.lean b/lean/mathlib-subset/Mathlib/Data/Multiset/FinsetOps.lean new file mode 100644 index 000000000000..1b7014066014 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Multiset/FinsetOps.lean @@ -0,0 +1,47 @@ +/- +Copyright (c) 2017 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Multiset.Dedup + +@[expose] public section +namespace Multiset +open List +variable {α : Type*} [DecidableEq α] {s : Multiset α} +/-- `ndinsert a s` is the lift of the list `insert` operation. This operation + does not respect multiplicities, unlike `cons`, but it is suitable as + an insert operation on `Finset`. -/ +def ndinsert (a : α) (s : Multiset α) : Multiset α := + Quot.liftOn s (fun l => (l.insert a : Multiset α)) fun _ _ p => Quot.sound (p.insert a) +/-- `ndunion s t` is the lift of the list `union` operation. This operation + does not respect multiplicities, unlike `s ∪ t`, but it is suitable as + a union operation on `Finset`. (`s ∪ t` would also work as a union operation + on finset, but this is more efficient.) -/ +def ndunion (s t : Multiset α) : Multiset α := + (Quotient.liftOn₂ s t fun l₁ l₂ => (l₁.union l₂ : Multiset α)) fun _ _ _ _ p₁ p₂ => + Quot.sound <| p₁.union p₂ +/-- `ndinter s t` is the lift of the list `∩` operation. This operation + does not respect multiplicities, unlike `s ∩ t`, but it is suitable as + an intersection operation on `Finset`. (`s ∩ t` would also work as an intersection operation + on finset, but this is more efficient.) -/ +def ndinter (s t : Multiset α) : Multiset α := + filter (· ∈ t) s +theorem Nodup.ndinsert (a : α) : Nodup s → Nodup (ndinsert a s) := + Quot.inductionOn s fun l h => by + show List.Nodup (l.insert a) + unfold List.insert + split + · exact h + · next hn => exact List.nodup_cons.2 ⟨by simpa using hn, h⟩ +theorem Nodup.ndunion (s : Multiset α) {t : Multiset α} : Nodup t → Nodup (ndunion s t) := + Quotient.inductionOn₂ s t fun l₁ l₂ h => by + show List.Nodup (List.foldr List.insert l₂ l₁) + induction l₁ with + | nil => exact h + | cons x l ih => exact Nodup.ndinsert (s := ((List.foldr List.insert l₂ l : List α) : Multiset α)) x ih +theorem Nodup.ndinter {s : Multiset α} (t : Multiset α) : Nodup s → Nodup (ndinter s t) := + Nodup.filter _ +end Multiset diff --git a/lean/mathlib-subset/Mathlib/Data/Multiset/Fold.lean b/lean/mathlib-subset/Mathlib/Data/Multiset/Fold.lean new file mode 100644 index 000000000000..1cdf4aa45064 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Multiset/Fold.lean @@ -0,0 +1,20 @@ +/- +Copyright (c) 2017 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Multiset.Dedup + +@[expose] public section +namespace Multiset +variable {α β : Type*} +section Fold +variable (op : α → α → α) [hc : Std.Commutative op] [ha : Std.Associative op] +/-- `fold op b s` folds a commutative associative operation `op` over + the multiset `s`. -/ +def fold : α → Multiset α → α := + foldr op +end Fold +end Multiset diff --git a/lean/mathlib-subset/Mathlib/Data/Multiset/MapFold.lean b/lean/mathlib-subset/Mathlib/Data/Multiset/MapFold.lean new file mode 100644 index 000000000000..7188bac7b496 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Multiset/MapFold.lean @@ -0,0 +1,29 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Multiset.AddSub +public import Mathlib.Data.Set.Basic + +@[expose] public section +universe v +open List Subtype Nat Function +variable {α : Type*} {β : Type v} {γ : Type*} +namespace Multiset +/-- `map f s` is the lift of the list `map` operation. The multiplicity + of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) + such that `f a = b`. -/ +def map (f : α → β) (s : Multiset α) : Multiset β := + Quot.liftOn s (fun l : List α => (l.map f : Multiset β)) fun _l₁ _l₂ p => Quot.sound (p.map f) +section foldr +/-- `foldr f H b s` is the lift of the list operation `foldr f b l`, + which folds `f` over the multiset. It is well defined when `f` is left-commutative, + that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ +def foldr (f : α → β → β) [LeftCommutative f] (b : β) (s : Multiset α) : β := + Quot.liftOn s (fun l => List.foldr f b l) fun _l₁ _l₂ p => p.foldr_eq b +variable (f : α → β → β) [LeftCommutative f] +end foldr +end Multiset diff --git a/lean/mathlib-subset/Mathlib/Data/Multiset/Sort.lean b/lean/mathlib-subset/Mathlib/Data/Multiset/Sort.lean new file mode 100644 index 000000000000..fe9fbcfab336 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Multiset/Sort.lean @@ -0,0 +1,24 @@ +/- +Copyright (c) 2017 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.List.Sort +public import Mathlib.Data.Multiset.Filter + +@[expose] public section +variable {α β : Type*} +namespace Multiset +open List +section sort +/-- `sort s` constructs a sorted list from the multiset `s`. + (Uses merge sort algorithm.) -/ +def sort (s : Multiset α) (r : α → α → Prop := by exact fun a b => a ≤ b) + [DecidableRel r] [IsTrans α r] [Std.Antisymm r] [Std.Total r] : List α := + Quot.liftOn s (mergeSort · (r · ·)) fun _ _ h => + ((mergeSort_perm _ _).trans <| h.trans (mergeSort_perm _ _).symm).eq_of_pairwise' (r := r) + (pairwise_mergeSort' _ _) (pairwise_mergeSort' _ _) +end sort +end Multiset diff --git a/lean/mathlib-subset/Mathlib/Data/Multiset/ZeroCons.lean b/lean/mathlib-subset/Mathlib/Data/Multiset/ZeroCons.lean new file mode 100644 index 000000000000..fadc6e1eb779 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Multiset/ZeroCons.lean @@ -0,0 +1,35 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Multiset.Defs +public import Mathlib.Order.BoundedOrder.Basic + +@[expose] public section +universe v +open List Subtype Nat +variable {α : Type*} {β : Type v} {γ : Type*} +namespace Multiset +/-- `0 : Multiset α` is the empty set -/ +protected def zero : Multiset α := + @nil α +instance : Zero (Multiset α) := + ⟨Multiset.zero⟩ +/-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ +def cons (a : α) (s : Multiset α) : Multiset α := + Quot.liftOn s (fun l => (a :: l : Multiset α)) fun _ _ p => Quot.sound (p.cons a) + +@[inherit_doc Multiset.cons] +infixr:67 " ::ₘ " => Multiset.cons +instance : Singleton α (Multiset α) := + ⟨fun a => a ::ₘ 0⟩ +section Nodup +variable {s : Multiset α} {a : α} +@[simp] +theorem nodup_zero : @Nodup α 0 := + Pairwise.nil +end Nodup +end Multiset diff --git a/lean/mathlib-subset/Mathlib/Data/Nat/Basic.lean b/lean/mathlib-subset/Mathlib/Data/Nat/Basic.lean new file mode 100644 index 000000000000..d5f229115961 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Nat/Basic.lean @@ -0,0 +1,28 @@ +/- +Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro +-/ +module + +public import Mathlib.Data.Nat.Notation +public import Mathlib.Order.Defs.LinearOrder +public import Mathlib.Order.Defs.Unbundled + +public section +open Function +namespace Nat +variable {a b c m n k : ℕ} +instance instLinearOrder : LinearOrder ℕ where + le := Nat.le + le_refl := @Nat.le_refl + le_trans := @Nat.le_trans + le_antisymm := @Nat.le_antisymm + le_total := @Nat.le_total + lt := Nat.lt + lt_iff_le_not_ge := @Nat.lt_iff_le_and_not_ge + toDecidableLT := inferInstance + toDecidableLE := inferInstance + toDecidableEq := inferInstance +instance : Preorder ℕ := inferInstance +end Nat diff --git a/lean/mathlib-subset/Mathlib/Data/Nat/Notation.lean b/lean/mathlib-subset/Mathlib/Data/Nat/Notation.lean new file mode 100644 index 000000000000..8c1377e58258 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Nat/Notation.lean @@ -0,0 +1,16 @@ +/- +Copyright (c) 2014 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Floris van Doorn, Leonardo de Moura +-/ +module + +public import Mathlib.Init + +/-! +# Notation `ℕ` for the natural numbers. +-/ + +public section + +@[inherit_doc] notation "ℕ" => Nat diff --git a/lean/mathlib-subset/Mathlib/Data/Seq/Basic.lean b/lean/mathlib-subset/Mathlib/Data/Seq/Basic.lean new file mode 100644 index 000000000000..45bba4869ecc --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Seq/Basic.lean @@ -0,0 +1,30 @@ +/- +Copyright (c) 2017 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Seq.Defs + +@[expose] public section + +universe u v w + +namespace Stream' + +namespace Seq + +variable {α : Type u} {β : Type v} {γ : Type w} + +section Map + +@[simp] +theorem map_get? (f : α → β) : ∀ s n, get? (map f s) n = (get? s n).map f + | ⟨_, _⟩, _ => rfl + +end Map + +end Seq + +end Stream' diff --git a/lean/mathlib-subset/Mathlib/Data/Seq/Defs.lean b/lean/mathlib-subset/Mathlib/Data/Seq/Defs.lean new file mode 100644 index 000000000000..508642c55405 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Seq/Defs.lean @@ -0,0 +1,84 @@ +/- +Copyright (c) 2017 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ +module + +public import Mathlib.Data.Nat.Notation +public import Batteries.Data.List.Basic +public import Mathlib.Data.Nat.Basic +public import Mathlib.Data.Stream.Defs +public import Mathlib.Logic.Function.Basic +public import Mathlib.Order.TypeTags + +@[expose] public section +namespace Stream' +universe u v w +/-- A stream `s : Option α` is a sequence if `s.get n = none` implies `s.get (n + 1) = none`. +-/ +def IsSeq {α : Type u} (s : Stream' (Option α)) : Prop := + ∀ {n : ℕ}, s n = none → s (n + 1) = none +/-- `Seq α` is the type of possibly infinite lists (referred here as sequences). + It is encoded as an infinite stream of options such that if `f n = none`, then + `f m = none` for all `m ≥ n`. -/ +def Seq (α : Type u) : Type u := + { f : Stream' (Option α) // f.IsSeq } +namespace Seq +variable {α : Type u} {β : Type v} {γ : Type w} +/-- Get the nth element of a sequence (if it exists) -/ +def get? : Seq α → ℕ → Option α := + Subtype.val +theorem le_stable (s : Seq α) {m n} (h : m ≤ n) : s.get? m = none → s.get? n = none := by + obtain ⟨f, al⟩ := s + induction h with | refl => exact id | step _ IH => exact fun h2 ↦ al (IH h2) +/-- The empty sequence -/ +def nil : Seq α := + ⟨Stream'.const none, fun {_} _ => rfl⟩ +@[simp] +theorem get?_nil (n : ℕ) : (@nil α).get? n = none := + rfl +/-- Prepend an element to a sequence -/ +def cons (a : α) (s : Seq α) : Seq α := + ⟨some a::s.1, by + intro n h + cases n with + | zero => contradiction + | succ n => exact s.2 h⟩ +@[simp] +theorem get?_cons_zero (a : α) (s : Seq α) : (cons a s).get? 0 = some a := + rfl +@[simp] +theorem get?_cons_succ (a : α) (s : Seq α) (n : ℕ) : (cons a s).get? (n + 1) = s.get? n := + rfl +/-- member definition for `Seq` -/ +protected def Mem (s : Seq α) (a : α) := + some a ∈ s.1 +instance : Membership α (Seq α) := + ⟨Seq.Mem⟩ +theorem get?_mem {s : Seq α} {n : ℕ} {x : α} (h : s.get? n = .some x) : x ∈ s := ⟨n, h.symm⟩ +theorem mem_iff_exists_get? {s : Seq α} {x : α} : x ∈ s ↔ ∃ i, some x = s.get? i := + ⟨fun ⟨i, h⟩ => ⟨i, h⟩, fun ⟨i, h⟩ => ⟨i, h⟩⟩ +/-- Embed a list as a sequence -/ +@[coe] +def ofList (l : List α) : Seq α := + ⟨(l[·]?), fun {n} h => by + rw [List.getElem?_eq_none_iff] at h ⊢ + exact Nat.le_succ_of_le h⟩ +@[simp] +theorem ofList_get? (l : List α) (n : ℕ) : (ofList l).get? n = l[n]? := + rfl +/-- Embed an infinite stream as a sequence -/ +@[coe] +def ofStream (s : Stream' α) : Seq α := + ⟨s.map some, fun {n} h => by contradiction⟩ +/-- Map a function over a sequence. -/ +def map (f : α → β) : Seq α → Seq β + | ⟨s, al⟩ => + ⟨s.map (Option.map f), fun {n} => by + dsimp [Stream'.map, Stream'.get] + cases e : s n with + | none => intro; rw [al e]; rfl + | some _ => intro h; contradiction⟩ +end Seq +end Stream' diff --git a/lean/mathlib-subset/Mathlib/Data/Set/Basic.lean b/lean/mathlib-subset/Mathlib/Data/Set/Basic.lean new file mode 100644 index 000000000000..88233fb42b46 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Set/Basic.lean @@ -0,0 +1,23 @@ +/- +Copyright (c) 2014 Jeremy Avigad. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Jeremy Avigad, Leonardo de Moura +-/ +module + +public import Mathlib.Order.PropInstances + +@[expose] public section +open Function +universe u v +namespace Set +variable {α : Type u} {s t : Set α} +instance instDistribLattice : DistribLattice (Set α) where + __ : DistribLattice (α → Prop) := inferInstance + le := (· ≤ ·) + lt := fun s t => s ⊆ t ∧ ¬t ⊆ s + sup := (· ∪ ·) + inf := (· ∩ ·) +end Set +open Set +variable {α : Type*} {s : Set α} diff --git a/lean/mathlib-subset/Mathlib/Data/Set/Defs.lean b/lean/mathlib-subset/Mathlib/Data/Set/Defs.lean new file mode 100644 index 000000000000..b18b62d53a3c --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Set/Defs.lean @@ -0,0 +1,51 @@ +/- +Copyright (c) 2016 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura +-/ +module + +public import Mathlib.Tactic.SetNotationForOrder + +@[expose] public section +universe u +variable {α : Type u} +/-- A set is a collection of elements of some type `α`. + +Although `Set` is defined as `α → Prop`, this is an implementation detail which should not be +relied on. Instead, `Set.ofPred` (also written `{x | p x}`) and membership of a set (`∈`) should be +used to convert between sets and predicates. +-/ +@[use_set_notation_for_order] +def Set (α : Type u) := α → Prop +/-- Turn a predicate `p : α → Prop` into a set, also written as `{x | p x}` -/ +@[implicit_reducible] +def Set.ofPred {α : Type u} (p : α → Prop) : Set α := + p +namespace Set +/-- Membership in a set -/ +@[implicit_reducible] +protected def Mem (s : Set α) (a : α) : Prop := + s a +instance : Membership α (Set α) := + ⟨Set.Mem⟩ +/-- The subset relation on sets. `s ⊆ t` means that all elements of `s` are elements of `t`. + +Note that you should **not** use this definition directly, but instead write `s ⊆ t`. -/ +protected def Subset (s₁ s₂ : Set α) := + ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂ +/-- We introduce `≤` before `⊆` to help the unifier when applying lattice theorems +to subset hypotheses. -/ +instance : LE (Set α) := + ⟨Set.Subset⟩ +/-- The union of two sets `s` and `t` is the set of elements contained in either `s` or `t`. + +Note that you should **not** use this definition directly, but instead write `s ∪ t`. -/ +protected def union (s₁ s₂ : Set α) : Set α := Set.ofPred fun a => a ∈ s₁ ∨ a ∈ s₂ +instance : Union (Set α) := ⟨Set.union⟩ +/-- The intersection of two sets `s` and `t` is the set of elements contained in both `s` and `t`. + +Note that you should **not** use this definition directly, but instead write `s ∩ t`. -/ +protected def inter (s₁ s₂ : Set α) : Set α := Set.ofPred fun a => a ∈ s₁ ∧ a ∈ s₂ +instance : Inter (Set α) := ⟨Set.inter⟩ +end Set diff --git a/lean/mathlib-subset/Mathlib/Data/Stream/Defs.lean b/lean/mathlib-subset/Mathlib/Data/Stream/Defs.lean new file mode 100644 index 000000000000..c6e2acbafd69 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Data/Stream/Defs.lean @@ -0,0 +1,33 @@ +/- +Copyright (c) 2015 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura +-/ +module + +public import Mathlib.Init +public import Mathlib.Data.Nat.Notation +@[expose] public section +universe u v w +variable {α : Type u} {β : Type v} {δ : Type w} +/-- A stream `Stream' α` is an infinite sequence of elements of `α`. -/ +def Stream' (α : Type u) := ℕ → α +namespace Stream' +/-- Prepend an element to a stream. -/ +def cons (a : α) (s : Stream' α) : Stream' α + | 0 => a + | n + 1 => s n + +@[inherit_doc] scoped infixr:67 " :: " => cons +/-- Get the `n`-th element of a stream. -/ +def get (s : Stream' α) (n : ℕ) : α := s n +/-- Proposition saying that at least one element of a stream satisfies a predicate. -/ +def Any (p : α → Prop) (s : Stream' α) := ∃ n, p (get s n) +/-- `a ∈ s` means that `a = Stream'.get n s` for some `n`. -/ +instance : Membership α (Stream' α) := + ⟨fun s a => Any (fun b => a = b) s⟩ +/-- Apply a function `f` to all elements of a stream `s`. -/ +def map (f : α → β) (s : Stream' α) : Stream' β := fun n => f (get s n) +/-- The constant stream: `Stream'.get n (Stream'.const a) = a`. -/ +def const (a : α) : Stream' α := fun _ => a +end Stream' diff --git a/lean/mathlib-subset/Mathlib/Init.lean b/lean/mathlib-subset/Mathlib/Init.lean new file mode 100644 index 000000000000..7ed3942344d1 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Init.lean @@ -0,0 +1,9 @@ +module + +public import Mathlib.Tactic.Lemma +public import Mathlib.Tactic.TypeStar + +/-! +The subset of upstream `Mathlib.Init` that the definitions here use: the `Type*` elaborator +and the `lemma` command. Upstream also imports Mathlib's linters, which are omitted. +-/ diff --git a/lean/mathlib-subset/Mathlib/Logic/Function/Basic.lean b/lean/mathlib-subset/Mathlib/Logic/Function/Basic.lean new file mode 100644 index 000000000000..1a86d50f1f81 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Logic/Function/Basic.lean @@ -0,0 +1,34 @@ +/- +Copyright (c) 2016 Johannes Hölzl. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Johannes Hölzl, Mario Carneiro +-/ +module + +public import Mathlib.Order.Defs.Unbundled + +@[expose] public section +universe u v + +namespace Function + +section Update + +variable {α : Sort u} {β : α → Sort v} [DecidableEq α] + +/-- Replacing the value of a function at a given point by a given value. -/ +@[grind] +def update (f : ∀ a, β a) (a' : α) (v : β a') (a : α) : β a := + if h : a = a' then Eq.ndrec v h.symm else f a + +@[simp] +theorem update_self (a : α) (v : β a) (f : ∀ a, β a) : update f a v a = v := + dite_eq_left rfl + +@[simp] +theorem update_of_ne {a a' : α} (h : a ≠ a') (v : β a') (f : ∀ a, β a) : update f a' v a = f a := + dite_eq_right h + +end Update + +end Function diff --git a/lean/mathlib-subset/Mathlib/Logic/OpClass.lean b/lean/mathlib-subset/Mathlib/Logic/OpClass.lean new file mode 100644 index 000000000000..9e64e09d8f46 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Logic/OpClass.lean @@ -0,0 +1,18 @@ +/- +Copyright (c) 2014 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura +-/ +module + +public import Mathlib.Init +public section +universe u v +variable {α : Sort u} {β : Sort v} +/-- `LeftCommutative op` where `op : α → β → β` says that `op` is a left-commutative operation, +i.e. `op a₁ (op a₂ b) = op a₂ (op a₁ b)`. -/ +class LeftCommutative (op : α → β → β) : Prop where + /-- A left-commutative operation satisfies `op a₁ (op a₂ b) = op a₂ (op a₁ b)`. -/ + left_comm : (a₁ a₂ : α) → (b : β) → op a₁ (op a₂ b) = op a₂ (op a₁ b) +instance {f : α → α → α} [hc : Std.Commutative f] [ha : Std.Associative f] : LeftCommutative f := + ⟨fun a b c ↦ by rw [← ha.assoc, hc.comm a, ha.assoc]⟩ diff --git a/lean/mathlib-subset/Mathlib/Order/Basic.lean b/lean/mathlib-subset/Mathlib/Order/Basic.lean new file mode 100644 index 000000000000..1a4bbbe4db5d --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/Basic.lean @@ -0,0 +1,98 @@ +/- +Copyright (c) 2014 Jeremy Avigad. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Jeremy Avigad, Mario Carneiro +-/ +module + +public import Mathlib.Logic.Function.Basic +public import Mathlib.Order.Defs.LinearOrder +public import Mathlib.Order.Defs.Prop +public import Mathlib.Order.Notation +public import Mathlib.Tactic.Spread + +@[expose] public section + +open Function + +section Preorder + +variable {α : Type*} [Preorder α] {a b c : α} + +theorem LE.le.trans : a ≤ b → b ≤ c → a ≤ c := le_trans + +theorem LT.lt.le : a < b → a ≤ b := fun h => (lt_iff_le_not_ge.1 h).1 + +theorem LE.le.trans_lt : a ≤ b → b < c → a < c := fun hab hbc => + lt_of_le_not_ge (le_trans hab (lt_iff_le_not_ge.1 hbc).1) + fun hca => (lt_iff_le_not_ge.1 hbc).2 (le_trans hca hab) + +theorem LT.lt.trans_le : a < b → b ≤ c → a < c := fun hab hbc => + lt_of_le_not_ge (le_trans (Preorder.lt_iff_le_not_ge _ _ |>.1 hab).1 hbc) + fun hca => (Preorder.lt_iff_le_not_ge _ _ |>.1 hab).2 (le_trans hbc hca) + +theorem LT.lt.trans : a < b → b < c → a < c := fun hab hbc => hab.trans_le hbc.le + +theorem LT.lt.ne : a < b → a ≠ b := fun h e => (lt_iff_le_not_ge.1 h).2 (by subst e; exact le_refl a) + +theorem LT.lt.ne' : b < a → a ≠ b := fun h e => (lt_iff_le_not_ge.1 h).2 (by subst e; exact le_refl a) + +theorem Eq.le : a = b → a ≤ b := fun e => by subst e; exact le_refl a + +theorem Eq.ge : a = b → b ≤ a := fun e => by subst e; exact le_refl a + +end Preorder + +variable {ι α β : Type*} {π : ι → Type*} + +instance Pi.preorder [∀ i, Preorder (π i)] : Preorder (∀ i, π i) where + __ := (inferInstance : LE (∀ i, π i)) + le_refl := fun a i ↦ le_refl (a i) + le_trans := fun _ _ _ h₁ h₂ i ↦ le_trans (h₁ i) (h₂ i) + +instance Pi.partialOrder [∀ i, PartialOrder (π i)] : PartialOrder (∀ i, π i) where + __ := Pi.preorder + le_antisymm := fun _ _ h1 h2 ↦ funext fun b ↦ le_antisymm (h1 b) (h2 b) + +/-- Pull back a `Preorder` instance along an injective function. + +See note [reducible non-instances]. -/ +abbrev Function.Injective.preorder [Preorder β] [LE α] [LT α] (f : α → β) + (le : ∀ {x y}, f x ≤ f y ↔ x ≤ y) (lt : ∀ {x y}, f x < f y ↔ x < y) : + Preorder α where + le_refl _ := le.1 <| le_refl _ + le_trans _ _ _ h₁ h₂ := le.1 <| le_trans (le.2 h₁) (le.2 h₂) + lt_iff_le_not_ge _ _ := by + rw [← le, ← le, ← lt, lt_iff_le_not_ge] + +/-- Pull back a `PartialOrder` instance along an injective function. + +See note [reducible non-instances]. -/ +abbrev Function.Injective.partialOrder [PartialOrder β] [LE α] [LT α] (f : α → β) + (hf : Function.Injective f) + (le : ∀ {x y}, f x ≤ f y ↔ x ≤ y) (lt : ∀ {x y}, f x < f y ↔ x < y) : + PartialOrder α where + __ := Function.Injective.preorder f le lt + le_antisymm _ _ h₁ h₂ := hf <| le_antisymm (le.2 h₁) (le.2 h₂) + + +/-- Transfer a `PartialOrder` on `β` to a `PartialOrder` on `α` using an injective +function `f : α → β`. + +See also `Function.Injective.partialOrder` when only the proof fields need to be transferred. + +See note [reducible non-instances]. -/ +abbrev PartialOrder.lift [PartialOrder β] (f : α → β) (inj : Injective f) : PartialOrder α := + letI _instLE : LE α := ⟨fun a b ↦ f a ≤ f b⟩ + letI _instLT : LT α := ⟨fun a b ↦ f a < f b⟩ + Function.Injective.partialOrder f inj .rfl .rfl + +section «Prop» + +instance Prop.partialOrder : PartialOrder Prop where + __ := Prop.le + le_refl _ := id + le_trans _ _ _ f g := g ∘ f + le_antisymm _ _ Hab Hba := propext ⟨Hab, Hba⟩ + +end «Prop» diff --git a/lean/mathlib-subset/Mathlib/Order/BoundedOrder/Basic.lean b/lean/mathlib-subset/Mathlib/Order/BoundedOrder/Basic.lean new file mode 100644 index 000000000000..232b28c0ab28 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/BoundedOrder/Basic.lean @@ -0,0 +1,17 @@ +/- +Copyright (c) 2017 Johannes Hölzl. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Johannes Hölzl +-/ +module + +public import Mathlib.Order.Basic + +@[expose] public section +universe u v +variable {α : Type u} {β : Type v} +/-- An order is an `OrderTop` if it has a greatest element. +We state this using a data mixin, holding the value of `⊤` and the greatest element constraint. -/ +class OrderTop (α : Type u) [LE α] extends Top α where + /-- `⊤` is the greatest element -/ + le_top : ∀ a : α, a ≤ ⊤ diff --git a/lean/mathlib-subset/Mathlib/Order/Defs/Lattice.lean b/lean/mathlib-subset/Mathlib/Order/Defs/Lattice.lean new file mode 100644 index 000000000000..344d84f70927 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/Defs/Lattice.lean @@ -0,0 +1,81 @@ +/- +Copyright (c) 2017 Johannes Hölzl. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Johannes Hölzl +-/ +module + +public import Mathlib.Order.Defs.PartialOrder +public import Mathlib.Order.Defs.Unbundled +public import Mathlib.Order.Notation + +@[expose] public section +universe u v +variable {α : Type u} {β : Type v} +/-- A `SemilatticeSup` is a join-semilattice, that is, a partial order + with a join (a.k.a. lub / least upper bound, sup / supremum) operation + `⊔` which is the least element larger than both factors. -/ +class SemilatticeSup (α : Type u) extends PartialOrder α where + /-- The binary supremum, used to derive `Max α` -/ + sup : α → α → α + /-- The supremum is an upper bound on the first argument -/ + protected le_sup_left : ∀ a b : α, a ≤ sup a b + /-- The supremum is an upper bound on the second argument -/ + protected le_sup_right : ∀ a b : α, b ≤ sup a b + /-- The supremum is the *least* upper bound -/ + protected sup_le : ∀ a b c : α, a ≤ c → b ≤ c → sup a b ≤ c +/-- A `SemilatticeInf` is a meet-semilattice, that is, a partial order + with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation + `⊓` which is the greatest element smaller than both factors. -/ +class SemilatticeInf (α : Type u) extends PartialOrder α where + /-- The binary infimum, used to derive `Min α` -/ + inf : α → α → α + /-- The infimum is a lower bound on the first argument -/ + protected inf_le_left : ∀ a b : α, inf a b ≤ a + /-- The infimum is a lower bound on the second argument -/ + protected inf_le_right : ∀ a b : α, inf a b ≤ b + /-- The infimum is the *greatest* lower bound -/ + protected le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ inf b c +instance SemilatticeSup.toMax [SemilatticeSup α] : Max α where max a b := SemilatticeSup.sup a b + +instance SemilatticeInf.toMin [SemilatticeInf α] : Min α where min a b := SemilatticeInf.inf a b + +section SemilatticeInf + +variable [SemilatticeInf α] {a b c d : α} + +theorem inf_comm (a b : α) : a ⊓ b = b ⊓ a := + le_antisymm (SemilatticeInf.le_inf _ _ _ (SemilatticeInf.inf_le_right _ _) (SemilatticeInf.inf_le_left _ _)) + (SemilatticeInf.le_inf _ _ _ (SemilatticeInf.inf_le_right _ _) (SemilatticeInf.inf_le_left _ _)) + +instance instCommutativeMin_mathlib : Std.Commutative (α := α) (· ⊓ ·) := ⟨inf_comm⟩ + +theorem inf_assoc (a b c : α) : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := by + have h₁ : a ⊓ b ⊓ c ≤ a := le_trans (SemilatticeInf.inf_le_left _ _) (SemilatticeInf.inf_le_left _ _) + have h₂ : a ⊓ b ⊓ c ≤ b := le_trans (SemilatticeInf.inf_le_left _ _) (SemilatticeInf.inf_le_right _ _) + have h₃ : a ⊓ (b ⊓ c) ≤ b := le_trans (SemilatticeInf.inf_le_right _ _) (SemilatticeInf.inf_le_left _ _) + have h₄ : a ⊓ (b ⊓ c) ≤ c := le_trans (SemilatticeInf.inf_le_right _ _) (SemilatticeInf.inf_le_right _ _) + exact le_antisymm + (SemilatticeInf.le_inf _ _ _ h₁ (SemilatticeInf.le_inf _ _ _ h₂ (SemilatticeInf.inf_le_right _ _))) + (SemilatticeInf.le_inf _ _ _ (SemilatticeInf.le_inf _ _ _ (SemilatticeInf.inf_le_left _ _) h₃) h₄) + +instance instAssociativeMin_mathlib : Std.Associative (α := α) (· ⊓ ·) := ⟨inf_assoc⟩ + +end SemilatticeInf + +/-- A lattice is a join-semilattice which is also a meet-semilattice. -/ +class Lattice (α : Type u) extends SemilatticeSup α, SemilatticeInf α +/-- A distributive lattice is a lattice that satisfies any of four +equivalent distributive properties (of `sup` over `inf` or `inf` over `sup`, +on the left or right). + +The definition here chooses `le_sup_inf`: `(x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)`. To prove distributivity +from the dual law, use `DistribLattice.ofInfSupLe`. + +A classic example of a distributive lattice +is the lattice of subsets of a set, and in fact this example is +generic in the sense that every distributive lattice is realizable +as a sublattice of a powerset lattice. -/ +class DistribLattice (α) extends Lattice α where + /-- The infimum distributes over the supremum -/ + protected le_sup_inf : ∀ x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ y ⊓ z diff --git a/lean/mathlib-subset/Mathlib/Order/Defs/LinearOrder.lean b/lean/mathlib-subset/Mathlib/Order/Defs/LinearOrder.lean new file mode 100644 index 000000000000..e43b78d05ce8 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/Defs/LinearOrder.lean @@ -0,0 +1,92 @@ +/- +Copyright (c) 2016 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura +-/ +module + +public import Mathlib.Order.Defs.PartialOrder +public import Mathlib.Tactic.SplitIfs + +@[expose] public section +variable {α : Type*} +section LinearOrder +/-- This attempts to prove that a given instance of `compare` is equal to `compareOfLessAndEq` by +introducing the arguments and trying the following approaches in order: + +1. seeing if `rfl` works +2. seeing if the `compare` at hand is nonetheless essentially `compareOfLessAndEq`, but, because of + implicit arguments, requires us to unfold the defs and split the `if`s in the definition of + `compareOfLessAndEq` +3. seeing if we can split by cases on the arguments, then see if the defs work themselves out + (useful when `compare` is defined via a `match` statement, as it is for `Bool`) +-/ +macro "compareOfLessAndEq_rfl" : tactic => + `(tactic| (intro a b; first | rfl | + (simp only [compare, compareOfLessAndEq]; split_ifs <;> rfl) | + (induction a <;> induction b <;> simp +decide only))) + +/-- A linear order is reflexive, transitive, antisymmetric and total relation `≤`. +We assume that every linear ordered type has decidable `(≤)`, `(<)`, and `(=)`. -/ +class LinearOrder (α : Type*) extends PartialOrder α, Min α, Max α, Ord α where + /-- A linear order is total. -/ + protected le_total (a b : α) : a ≤ b ∨ b ≤ a + /-- In a linearly ordered type, we assume the order relations are all decidable. -/ + toDecidableLE : DecidableLE α + /-- In a linearly ordered type, we assume the order relations are all decidable. -/ + toDecidableEq : DecidableEq α := @decidableEqOfDecidableLE _ _ toDecidableLE + /-- In a linearly ordered type, we assume the order relations are all decidable. -/ + toDecidableLT : DecidableLT α := @decidableLTOfDecidableLE _ _ toDecidableLE + min := fun a b => if a ≤ b then a else b + max := fun a b => if a ≤ b then b else a + /-- The minimum function is equivalent to the one you get from `minOfLe`. -/ + protected min_def : ∀ a b, min a b = if a ≤ b then a else b := by intros; rfl + /-- The minimum function is equivalent to the one you get from `maxOfLe`. -/ + protected max_def : ∀ a b, max a b = if a ≤ b then b else a := by intros; rfl + compare a b := compareOfLessAndEq a b + /-- Comparison via `compare` is equal to the canonical comparison given decidable `<` and `=`. -/ + compare_eq_compareOfLessAndEq : ∀ a b, compare a b = compareOfLessAndEq a b := by + compareOfLessAndEq_rfl + +variable [LinearOrder α] {a b c : α} + +attribute [instance_reducible, instance 900] LinearOrder.toDecidableLT +attribute [instance_reducible, instance 900] LinearOrder.toDecidableLE +attribute [instance_reducible, instance 900] LinearOrder.toDecidableEq + +lemma min_le_left (a b : α) : min a b ≤ a := by + rw [LinearOrder.min_def] + split + · exact Preorder.le_refl a + · exact (LinearOrder.le_total a b).resolve_left ‹_› + +lemma le_max_left (a b : α) : a ≤ max a b := by + rw [LinearOrder.max_def] + split + · assumption + · exact Preorder.le_refl a + +lemma min_le_right (a b : α) : min a b ≤ b := by + rw [LinearOrder.min_def] + split + · assumption + · exact Preorder.le_refl b + +lemma le_max_right (a b : α) : b ≤ max a b := by + rw [LinearOrder.max_def] + split + · exact Preorder.le_refl b + · exact (LinearOrder.le_total a b).resolve_left ‹_› + +lemma le_min (h₁ : c ≤ a) (h₂ : c ≤ b) : c ≤ min a b := by + rw [LinearOrder.min_def] + split <;> assumption + +lemma max_le (h₁ : a ≤ c) (h₂ : b ≤ c) : max a b ≤ c := by + rw [LinearOrder.max_def] + split <;> assumption + +lemma le_or_gt (a b : α) : a ≤ b ∨ b < a := + if h : a ≤ b then .inl h else .inr (lt_of_le_not_ge ((LinearOrder.le_total a b).resolve_left h) h) + +end LinearOrder diff --git a/lean/mathlib-subset/Mathlib/Order/Defs/PartialOrder.lean b/lean/mathlib-subset/Mathlib/Order/Defs/PartialOrder.lean new file mode 100644 index 000000000000..479f2fee6392 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/Defs/PartialOrder.lean @@ -0,0 +1,55 @@ +/- +Copyright (c) 2016 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura +-/ +module + +public import Mathlib.Init +@[expose] public section +variable {α : Type*} +section Preorder +/-- +A preorder is a reflexive, transitive relation `≤`. +In a preorder, `a < b` means `a ≤ b ∧ ¬b ≤ a`, and `<` is defined this way by default. +You can override this definition to set a better def-eq. +-/ +class Preorder (α : Type*) extends LE α, LT α where + protected le_refl : ∀ a : α, a ≤ a + protected le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c + lt := fun a b => a ≤ b ∧ ¬b ≤ a + protected lt_iff_le_not_ge : ∀ a b : α, a < b ↔ a ≤ b ∧ ¬b ≤ a := by intros; rfl +variable [Preorder α] {a b c : α} + +@[refl] lemma le_refl : ∀ a : α, a ≤ a := Preorder.le_refl + +lemma le_rfl : a ≤ a := le_refl a + +lemma le_trans : a ≤ b → b ≤ c → a ≤ c := Preorder.le_trans _ _ _ + +lemma lt_iff_le_not_ge : a < b ↔ a ≤ b ∧ ¬b ≤ a := Preorder.lt_iff_le_not_ge _ _ + +lemma lt_of_le_not_ge (hab : a ≤ b) (hba : ¬ b ≤ a) : a < b := lt_iff_le_not_ge.2 ⟨hab, hba⟩ + +/-- `<` is decidable if `≤` is. -/ +@[instance_reducible] +def decidableLTOfDecidableLE [DecidableLE α] : DecidableLT α := + fun _ _ => decidable_of_iff _ lt_iff_le_not_ge.symm + +end Preorder +section PartialOrder +/-- A partial order is a reflexive, transitive, antisymmetric relation `≤`. -/ +class PartialOrder (α : Type*) extends Preorder α where + protected le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b +variable [PartialOrder α] {a b : α} + +lemma le_antisymm : a ≤ b → b ≤ a → a = b := PartialOrder.le_antisymm _ _ + +/-- Equality is decidable if `≤` is. -/ +def decidableEqOfDecidableLE [DecidableLE α] : DecidableEq α + | a, b => + if hab : a ≤ b then + if hba : b ≤ a then isTrue (le_antisymm hab hba) else isFalse fun heq => hba (heq ▸ le_refl _) + else isFalse fun heq => hab (heq ▸ le_refl _) + +end PartialOrder diff --git a/lean/mathlib-subset/Mathlib/Order/Defs/Prop.lean b/lean/mathlib-subset/Mathlib/Order/Defs/Prop.lean new file mode 100644 index 000000000000..1d412c13f017 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/Defs/Prop.lean @@ -0,0 +1,14 @@ +/- +Copyright (c) 2016 Johannes Hölzl. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Johannes Hölzl, Yury Kudryashov +-/ +module + +public import Mathlib.Init +public section +instance Pi.hasLe {ι : Type*} {π : ι → Type*} [∀ i, LE (π i)] : LE (∀ i, π i) where + le x y := ∀ i, x i ≤ y i +/-- Propositions form a complete Boolean algebra, where the `≤` relation is given by implication. -/ +instance Prop.le : LE Prop := + ⟨(· → ·)⟩ diff --git a/lean/mathlib-subset/Mathlib/Order/Defs/Unbundled.lean b/lean/mathlib-subset/Mathlib/Order/Defs/Unbundled.lean new file mode 100644 index 000000000000..99cbac5c4f3a --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/Defs/Unbundled.lean @@ -0,0 +1,14 @@ +/- +Copyright (c) 2016 Microsoft Corporation. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Leonardo de Moura +-/ +module + +public import Mathlib.Data.Set.Defs + +@[expose] public section +/-- `IsTrans X r` means the binary relation `r` on `X` is transitive. -/ +class IsTrans (α : Sort*) (r : α → α → Prop) : Prop where + trans : ∀ a b c, r a b → r b c → r a c +variable {α : Sort*} {r : α → α → Prop} diff --git a/lean/mathlib-subset/Mathlib/Order/Lattice.lean b/lean/mathlib-subset/Mathlib/Order/Lattice.lean new file mode 100644 index 000000000000..59d297ca2e9e --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/Lattice.lean @@ -0,0 +1,51 @@ +/- +Copyright (c) 2017 Johannes Hölzl. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Johannes Hölzl +-/ +module + +public import Mathlib.Data.Nat.Basic +public import Mathlib.Order.Defs.Lattice +public import Mathlib.Order.RelClasses + +@[expose] public section +universe u v w + +instance (priority := 100) LinearOrder.toLattice {α : Type u} [LinearOrder α] : Lattice α where + sup := max + inf := min + le_sup_left := le_max_left; le_sup_right := le_max_right; sup_le _ _ _ := max_le + inf_le_left := min_le_left; inf_le_right := min_le_right; le_inf _ _ _ := le_min + +instance (priority := 100) instDistribLatticeOfLinearOrder {α : Type u} [LinearOrder α] : + DistribLattice α where + le_sup_inf x b c := by + show min (max x b) (max x c) ≤ max x (min b c) + rw [LinearOrder.min_def b c] + split + · exact min_le_left _ _ + · exact min_le_right _ _ + +namespace Pi + +variable {ι : Type*} {α' : ι → Type*} + +instance instSemilatticeSup [∀ i, SemilatticeSup (α' i)] : SemilatticeSup (∀ i, α' i) where + sup x y i := x i ⊔ y i + le_sup_left _ _ _ := SemilatticeSup.le_sup_left _ _ + le_sup_right _ _ _ := SemilatticeSup.le_sup_right _ _ + sup_le _ _ _ ac bc i := SemilatticeSup.sup_le _ _ _ (ac i) (bc i) + +instance instSemilatticeInf [∀ i, SemilatticeInf (α' i)] : SemilatticeInf (∀ i, α' i) where + inf x y i := x i ⊓ y i + inf_le_left _ _ _ := SemilatticeInf.inf_le_left _ _ + inf_le_right _ _ _ := SemilatticeInf.inf_le_right _ _ + le_inf _ _ _ ac bc i := SemilatticeInf.le_inf _ _ _ (ac i) (bc i) + +instance instLattice [∀ i, Lattice (α' i)] : Lattice (∀ i, α' i) where + +instance instDistribLattice [∀ i, DistribLattice (α' i)] : DistribLattice (∀ i, α' i) where + le_sup_inf _ _ _ _ := DistribLattice.le_sup_inf _ _ _ + +end Pi diff --git a/lean/mathlib-subset/Mathlib/Order/MinMax.lean b/lean/mathlib-subset/Mathlib/Order/MinMax.lean new file mode 100644 index 000000000000..884264fa8154 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/MinMax.lean @@ -0,0 +1,20 @@ +/- +Copyright (c) 2014 Jeremy Avigad. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Jeremy Avigad, Leonardo de Moura +-/ +module + +public import Mathlib.Order.Lattice + +public section +universe u v +variable {α : Type u} {β : Type v} +section +variable [LinearOrder α] {a b c d : α} +theorem max_choice (a b : α) : max a b = a ∨ max a b = b := by + rw [LinearOrder.max_def] + split + · exact .inr rfl + · exact .inl rfl +end diff --git a/lean/mathlib-subset/Mathlib/Order/Notation.lean b/lean/mathlib-subset/Mathlib/Order/Notation.lean new file mode 100644 index 000000000000..2e4aaa9b43b5 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/Notation.lean @@ -0,0 +1,37 @@ +/- +Copyright (c) 2017 Johannes Hölzl. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Johannes Hölzl, Yury Kudryashov, Yaël Dillies +-/ +module + +public import Mathlib.Init + +public section + +/-- +The supremum/join operation: `x ⊔ y`. It is notation for `max x y` +and should be used when the type is not a linear order. +-/ +syntax:68 term:68 " ⊔ " term:69 : term + +/-- +The infimum/meet operation: `x ⊓ y`. It is notation for `min x y` +and should be used when the type is not a linear order. +-/ +syntax:69 term:69 " ⊓ " term:70 : term + +macro_rules +| `($a ⊔ $b) => `(Max.max $a $b) +| `($a ⊓ $b) => `(Min.min $a $b) + +/-- Typeclass for the `⊤` (`\top`) notation -/ +@[ext] +class Top (α : Type*) where + /-- The top (`⊤`, `\top`) element -/ + top : α + +/-- The top (`⊤`, `\top`) element -/ +notation "⊤" => Top.top + +attribute [match_pattern] Top.top diff --git a/lean/mathlib-subset/Mathlib/Order/PropInstances.lean b/lean/mathlib-subset/Mathlib/Order/PropInstances.lean new file mode 100644 index 000000000000..487e7e59a642 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/PropInstances.lean @@ -0,0 +1,22 @@ +/- +Copyright (c) 2017 Johannes Hölzl. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Johannes Hölzl +-/ +module + +public import Mathlib.Order.BoundedOrder.Basic +public import Mathlib.Order.Lattice + +public section +/-- Propositions form a distributive lattice. -/ +instance Prop.instDistribLattice : DistribLattice Prop where + sup := Or + le_sup_left := @Or.inl + le_sup_right := @Or.inr + sup_le := fun _ _ _ => Or.rec + inf := And + inf_le_left := @And.left + inf_le_right := @And.right + le_inf := fun _ _ _ Hab Hac Ha => And.intro (Hab Ha) (Hac Ha) + le_sup_inf := fun _ _ _ => or_and_left.2 diff --git a/lean/mathlib-subset/Mathlib/Order/RelClasses.lean b/lean/mathlib-subset/Mathlib/Order/RelClasses.lean new file mode 100644 index 000000000000..ed4c5c6e3b09 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/RelClasses.lean @@ -0,0 +1,19 @@ +/- +Copyright (c) 2020 Jeremy Avigad. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Jeremy Avigad, Mario Carneiro, Yury Kudryashov +-/ +module + +public import Mathlib.Order.Basic + +@[expose] public section +universe u v + +variable {α : Type u} + +instance instIsTransLe [Preorder α] : IsTrans α (· ≤ ·) := + ⟨@le_trans _ _⟩ + +instance LE.total [LinearOrder α] : @Std.Total α (· ≤ ·) := + ⟨LinearOrder.le_total⟩ diff --git a/lean/mathlib-subset/Mathlib/Order/TypeTags.lean b/lean/mathlib-subset/Mathlib/Order/TypeTags.lean new file mode 100644 index 000000000000..cf451f93b522 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/TypeTags.lean @@ -0,0 +1,41 @@ +/- +Copyright (c) 2018 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro, Simon Hudon, Yury Kudryashov +-/ +module + +public import Mathlib.Order.Notation + +@[expose] public section +variable {α : Type*} + +/-- Attach `⊤` to a type. -/ +def WithTop (α : Type*) := Option α + +instance WithTop.instRepr [Repr α] : Repr (WithTop α) := + ⟨fun o _ => + match o with + | none => "⊤" + | some a => "↑" ++ repr a⟩ + +namespace WithTop + +/-- The canonical map from `α` into `WithTop α` -/ +@[coe, match_pattern] +def some : α → WithTop α := + Option.some + +instance coe : Coe α (WithTop α) := + ⟨some⟩ + +instance top : Top (WithTop α) := + ⟨none⟩ + +/-- Recursor for `WithTop` using the preferred forms `⊤` and `↑a`. -/ +@[elab_as_elim, induction_eliminator, cases_eliminator] +def recTopCoe {C : WithTop α → Sort*} (top : C ⊤) (coe : ∀ a : α, C a) : ∀ n : WithTop α, C n + | ⊤ => top + | (a : α) => coe a + +end WithTop diff --git a/lean/mathlib-subset/Mathlib/Order/WithBot.lean b/lean/mathlib-subset/Mathlib/Order/WithBot.lean new file mode 100644 index 000000000000..96af13fd7fc1 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Order/WithBot.lean @@ -0,0 +1,152 @@ +/- +Copyright (c) 2017 Johannes Hölzl. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Johannes Hölzl +-/ +module + +public import Mathlib.Order.BoundedOrder.Basic +public import Mathlib.Order.Lattice +public import Mathlib.Order.TypeTags + +@[expose] public section +variable {α β γ δ : Type*} + +namespace WithTop + +/-- Specialization of `Option.getD` to values in `WithTop α` that respects API boundaries. -/ +def untopD (d : α) (x : WithTop α) : α := + recTopCoe d id x + +@[simp] +theorem untopD_coe (d x : α) : untopD d (WithTop.some x) = x := + rfl + +@[simp] +theorem coe_inj {a b : α} : (WithTop.some a : WithTop α) = WithTop.some b ↔ a = b := + Option.some_inj + +end WithTop + +section LE + +variable [LE α] + +/-- The order on `WithTop`. -/ +protected inductive WithTop.LE : WithTop α → WithTop α → Prop + | protected le_top (x : WithTop α) : WithTop.LE x ⊤ + | protected coe_le_coe {a b : α} : a ≤ b → WithTop.LE a b + +/-- The order on `WithTop α`, defined by `x ≤ ⊤` and `a ≤ b → ↑a ≤ ↑b`. + +Equivalently, `x ≤ y` can be defined as `∀ b : α, y = ↑b → ∃ a : α, x = ↑a ∧ a ≤ b`, +see `le_iff_forall`. The definition as an inductive predicate is preferred since it +cannot be accidentally unfolded too far. -/ +instance (priority := 10) WithTop.instLE : LE (WithTop α) where le := WithTop.LE + +lemma WithTop.le_def {x y : WithTop α} : x ≤ y ↔ y = ⊤ ∨ ∃ a b : α, a ≤ b ∧ x = a ∧ y = b := by + dsimp [LE.le] + grind [WithTop.LE, LE.le_top, LE.coe_le_coe] + +end LE + +section LT + +variable [LT α] + +/-- The order on `WithTop`. -/ +protected inductive WithTop.LT [LT α] : WithTop α → WithTop α → Prop + | protected lt_top (a : α) : WithTop.LT a ⊤ + | protected coe_lt_coe {a b : α} : a < b → WithTop.LT a b + +/-- The order on `WithTop α`, defined by `↑a < ⊤` and `a < b → ↑a < ↑b`. + +Equivalently, `x < y` can be defined as `∃ a : α, x = ↑a ∧ ∀ b : α, y = ↑b → a < b`, +see `le_if_forall`. The definition as an inductive predicate is preferred since it +cannot be accidentally unfolded too far. -/ +instance (priority := 10) WithTop.instLT : LT (WithTop α) where lt := WithTop.LT + +lemma WithTop.lt_def {x y : WithTop α} : + x < y ↔ (∃ a : α, x = a) ∧ y = ⊤ ∨ ∃ a b : α, a < b ∧ x = a ∧ y = b := by + dsimp [LT.lt] + grind [WithTop.LT, LT.lt_top, LT.coe_lt_coe] + +end LT + +namespace WithTop + +instance instOrderTop [LE α] : OrderTop (WithTop α) where + le_top x := WithTop.LE.le_top x + +instance instPreorder [Preorder α] : Preorder (WithTop α) where + lt_iff_le_not_ge x y := by + constructor + · intro h + cases h with + | lt_top a => exact ⟨.le_top _, fun h' => nomatch h'⟩ + | coe_lt_coe hab => + refine ⟨.coe_le_coe (lt_iff_le_not_ge.1 hab).1, fun h' => ?_⟩ + cases h' with + | coe_le_coe hba => exact (lt_iff_le_not_ge.1 hab).2 hba + · intro ⟨h₁, h₂⟩ + cases h₁ with + | le_top x => + cases x with + | top => exact absurd (.le_top _) h₂ + | coe a => exact .lt_top a + | coe_le_coe hab => exact .coe_lt_coe (lt_iff_le_not_ge.2 ⟨hab, fun hba => h₂ (.coe_le_coe hba)⟩) + le_refl x := by + cases x with + | top => exact .le_top _ + | coe a => exact .coe_le_coe (le_refl a) + le_trans x y z hxy hyz := by + cases hyz with + | le_top => exact .le_top _ + | coe_le_coe hbc => + cases hxy with + | coe_le_coe hab => exact .coe_le_coe (le_trans hab hbc) + +instance instPartialOrder [PartialOrder α] : PartialOrder (WithTop α) where + le_antisymm x y hxy hyx := by + cases hxy with + | le_top => + cases hyx with + | le_top => rfl + | coe_le_coe hab => + cases hyx with + | coe_le_coe hba => rw [le_antisymm hab hba] + +instance semilatticeInf [SemilatticeInf α] : SemilatticeInf (WithTop α) where + inf + -- note this is `Option.merge`, but with the right defeq when unfolding + | ⊤, ⊤ => ⊤ + | (a : α), ⊤ => a + | ⊤, (b : α) => b + | (a : α), (b : α) => ↑(a ⊓ b) + inf_le_left x y := by + cases x <;> cases y + · exact .le_top _ + · exact .le_top _ + · exact .coe_le_coe (le_refl _) + · exact .coe_le_coe (SemilatticeInf.inf_le_left _ _) + inf_le_right x y := by + cases x <;> cases y + · exact .le_top _ + · exact .coe_le_coe (le_refl _) + · exact .le_top _ + · exact .coe_le_coe (SemilatticeInf.inf_le_right _ _) + le_inf x y z hxy hxz := by + cases hxy with + | le_top => + cases z + · exact .le_top _ + · exact hxz + | coe_le_coe hab => + cases hxz with + | le_top => exact .coe_le_coe hab + | coe_le_coe hac => exact .coe_le_coe (SemilatticeInf.le_inf _ _ _ hab hac) + +instance decidableEq [DecidableEq α] : DecidableEq (WithTop α) := + inferInstanceAs <| DecidableEq (Option α) + +end WithTop diff --git a/lean/mathlib-subset/Mathlib/Tactic/Lemma.lean b/lean/mathlib-subset/Mathlib/Tactic/Lemma.lean new file mode 100644 index 000000000000..9bae602d65ca --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Tactic/Lemma.lean @@ -0,0 +1,31 @@ +/- +Copyright (c) 2021 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro, Kyle Miller +-/ +module + +-- Upstream gets this through `Mathlib.Tactic.Linter.Header`. +public meta import Lean.Elab.Command + +/-! +# Support for `lemma` as a synonym for `theorem`. +-/ + +public meta section + +open Lean + +-- higher priority to override the one in Batteries +/-- `lemma` means the same as `theorem`. It is used to denote "less important" theorems -/ +syntax (name := lemma) (priority := default + 1) declModifiers + group("lemma " declId ppIndent(declSig) declVal) : command + +/-- Implementation of the `lemma` command, by macro expansion to `theorem`. -/ +@[macro «lemma»] def expandLemma : Macro := fun stx => + -- Not using a macro match, to be more resilient against changes to `lemma`. + -- This implementation ensures that any future changes to `theorem` are reflected in `lemma` + let stx := stx.modifyArg 1 fun stx => + let stx := stx.modifyArg 0 (mkAtomFrom · "theorem" (canonical := true)) + stx.setKind ``Parser.Command.theorem + pure <| stx.setKind ``Parser.Command.declaration diff --git a/lean/mathlib-subset/Mathlib/Tactic/SetNotationForOrder.lean b/lean/mathlib-subset/Mathlib/Tactic/SetNotationForOrder.lean new file mode 100644 index 000000000000..0a358c182175 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Tactic/SetNotationForOrder.lean @@ -0,0 +1,182 @@ +/- +Copyright (c) 2026 Jovan Gerbscheid. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Jovan Gerbscheid +-/ +module + +public meta import Lean.Elab.App +public import Mathlib.Init + +/-! +# Set notation for order operations + +Subset of upstream: the delaborators, the namespace linter and `to_set_notation` are omitted. + +This file allows the use of `⊆` notation while the underlying constant is `≤`. +Similarly for `⊂`/`<`, `⊇`/`≥` and `⊃`/`>`. + +A new copy of the `a ⊆ b` syntax is declared, which overwrites the original one. +To elaborate this notation, `a` and `b` are elaborated, and if the type of `a` and `b` is +tagged with `@[use_set_notation_for_order]`, `LE.le` is used instead of `Subset`. +A new delaborator for `LE.le` is also added so that `a ≤ b` prints as `a ⊆ b` whenever the type is +tagged with `@[use_set_notation_for_order]`. + +This tag is used for `Set`, `Finset`, `PSet` and `ZFSet`. It is not used for `Multiset` and `List`, +since they have both `≤` and `⊆` defined on them, with different meanings. +-/ + +/-- `UsesSetNotationForOrder` is used to track whether a type is tagged with +`@[use_set_notation_for_order]`. -/ +public class UsesSetNotationForOrder (α : Type*) + +meta section + +namespace Mathlib.Meta.SetNotationForOrder + +open Lean Meta Elab Term + +/-- Add an instance of `UsesSetNotationForOrder` for `declName`. -/ +def mkUsesSetNotationForOrderInstance (declName : Name) (kind : AttributeKind) : CoreM Unit := + MetaM.run' do + let cinfo ← getConstInfo declName + forallTelescope cinfo.type fun xs _ ↦ do + let instName := .str declName "instUsesSetNotationForOrder" + let app := mkAppN (.const declName (cinfo.levelParams.map .param)) xs + addDecl <| Declaration.defnDecl { + name := instName + levelParams := cinfo.levelParams + type := ← mkForallFVars xs <| ← mkAppM ``UsesSetNotationForOrder #[app] + value := ← mkLambdaFVars xs <| ← mkAppOptM ``UsesSetNotationForOrder.mk #[app] + hints := .regular 0 + safety := .safe } + registerInstance instName kind (eval_prio default) + +/-- The `@[use_set_notation_for_order]` attribute marks that order operations on the given type +should use set-style notation. For example, `⊆` for `≤` and `∪` for `⊔`. +This affects both elaboration and delaboration. -/ +initialize + registerBuiltinAttribute { + name := `use_set_notation_for_order + descr := "use set notation for order operations on this type" + add declName _stx kind := mkUsesSetNotationForOrderInstance declName kind } + +/-- Whether to use set notation for the given type or not. -/ +def useSetNotationFor (type : Expr) : MetaM Bool := do + return (← trySynthInstance (← mkAppM ``UsesSetNotationForOrder #[type])) matches .some _ + +/-! ## Elaboration -/ + +/-- Linter for ambiguous use of subset notation notation. -/ +register_option linter.setNotationForOrder : Bool := { + defValue := true + descr := "Linter for ambiguous use of subset notation notation" } + +/-- This relation is an implementation detail of the `⊆` elaborator. -/ +public opaque SubsetElabAux.{u} {α : Type u} : α → α → Prop + +/-- Elaborate a notation like `a ⊆ b` by elaborating `a` and `b`, and then deciding +based on their type whether to return `a ⊆ b` or `a ≤ b`. +Use `a ≤ b` whenever `useSetNotationFor` returns true for the type. +If the type is not known, elaboration of this term is postponed. + +We assume that `le` and `sub` are names for declarations of exactly the form +`decl.{u} {α : Type u} [Cls.{u} α] (a b : α) : Prop`, and that likewise `leCls` and `subCls` are +names for declarations of exactly the form `Cls.{u} (α : Type u) : Type u`. -/ +def elabSubsetLike (x y : Term) (le leCls sub subCls : Name) (expectedType? : Option Expr) : + TermElabM Expr := do + let rel ← `(SubsetElabAux $x $y) + let e ← elabApp rel expectedType? + let_expr f@SubsetElabAux α x y := e | throwError "unexpected result {e} when elaborating {rel}" + -- If the type cannot be determined yet, we postpone elaboration until it is known. + -- This behaviour is inspired by `resolveLValLoop` from the file `Lean.Elab.App`. + if ← isMVarApp α then + tryPostpone + synthesizeSyntheticMVarsUsingDefault + if ← isMVarApp α then + Linter.logLintIf linter.setNotationForOrder (← getRef) + m!"Ambiguous use of subset notation: the type is a metavariable.\n\ + Consider adding a type annotation, e.g. `(_ : Set _) ⊆ _`.\n\ + The term will elaborate to a different constant depending on \ + whether the type is tagged with `@[use_set_notation_for_order]`." + let (rel, cls) := if ← useSetNotationFor α then (le, leCls) else (sub, subCls) + let inst ← mkInstMVar <| .app (.const cls f.constLevels!) α + let rel := mkApp2 (.const rel f.constLevels!) α inst + -- Add the relation (e.g. `LE.le : Set Nat → Set Nat → Prop`) as a hover on the whole term + addTermInfo' (← getRef) rel (isDisplayableTerm := true) + return mkApp2 rel x y + +/-- Subset relation: `a ⊆ b`. +For types tagged with `@[use_set_notation_for_order]`, +the relation `LE.le` is used instead of `Subset`. +The hover info shows which one is used. -/ +syntax:50 (name := subsetStx') (priority := high) term:51 " ⊆ " term:51 : term + +/-- Strict subset relation: `a ⊂ b`. +For types tagged with `@[use_set_notation_for_order]`, +the relation `LT.lt` is used instead of `SSubset`. +The hover info shows which one is used. -/ +syntax:50 (name := ssubsetStx') (priority := high) term:51 " ⊂ " term:51 : term + +/-- Superset relation: `a ⊇ b`. +For types tagged with `@[use_set_notation_for_order]`, +the relation `GE.ge` is used instead of `Superset`. +The hover info shows which one is used. -/ +syntax:50 (name := supsetStx') (priority := high) term:51 " ⊇ " term:51 : term + +/-- Strict superset relation: `a ⊃ b`. +For types tagged with `@[use_set_notation_for_order]`, +the relation `GT.gt` is used instead of `SSuperset`. +The hover info shows which one is used. -/ +syntax:50 (name := ssupsetStx') (priority := high) term:51 " ⊃ " term:51 : term + +recommended_spelling "subset" for "⊆" in [subsetStx'] +recommended_spelling "ssubset" for "⊂" in [ssubsetStx'] +recommended_spelling "superset" for "⊇" in [supsetStx'] +recommended_spelling "ssuperset" for "⊃" in [ssupsetStx'] + +/-- Elaborator for `x ⊆ y` notation. -/ +@[term_elab subsetStx'] +public def elabSubsetStx' : TermElab + | `($x ⊆ $y), expectedType? => + elabSubsetLike x y ``LE.le ``LE ``Subset ``HasSubset expectedType? + | _, _ => throwUnsupportedSyntax + +/-- Elaborator for `x ⊂ y` notation. -/ +@[term_elab ssubsetStx'] +public def elabSSubsetStx' : TermElab + | `($x ⊂ $y), expectedType? => + elabSubsetLike x y ``LT.lt ``LT ``SSubset ``HasSSubset expectedType? + | _, _ => throwUnsupportedSyntax + +/-- Elaborator for `x ⊇ y` notation. -/ +@[term_elab supsetStx'] +public def elabSupsetStx' : TermElab + | `($x ⊇ $y), expectedType? => + elabSubsetLike x y ``GE.ge ``LE ``Superset ``HasSubset expectedType? + | _, _ => throwUnsupportedSyntax + +/-- Elaborator for `x ⊃ y` notation. -/ +@[term_elab ssupsetStx'] +public def elabSSupsetStx' : TermElab + | `($x ⊃ $y), expectedType? => + elabSubsetLike x y ``GT.gt ``LT ``SSuperset ``HasSSubset expectedType? + | _, _ => throwUnsupportedSyntax + +/-- Declare `∀ x ⊆ y, ...` as syntax for `∀ x, x ⊆ y → ...` and `∃ x ⊆ y, ...` as syntax for +`∃ x, x ⊆ y ∧ ...` -/ +binder_predicate (priority := high) x " ⊆ " y:term => `($x ⊆ $y) + +/-- Declare `∀ x ⊂ y, ...` as syntax for `∀ x, x ⊂ y → ...` and `∃ x ⊂ y, ...` as syntax for +`∃ x, x ⊂ y ∧ ...` -/ +binder_predicate (priority := high) x " ⊂ " y:term => `($x ⊂ $y) + +/-- Declare `∀ x ⊇ y, ...` as syntax for `∀ x, x ⊇ y → ...` and `∃ x ⊇ y, ...` as syntax for +`∃ x, x ⊇ y ∧ ...` -/ +binder_predicate (priority := high) x " ⊇ " y:term => `($x ⊇ $y) + +/-- Declare `∀ x ⊃ y, ...` as syntax for `∀ x, x ⊃ y → ...` and `∃ x ⊃ y, ...` as syntax for +`∃ x, x ⊃ y ∧ ...` -/ +binder_predicate (priority := high) x " ⊃ " y:term => `($x ⊃ $y) + +end Mathlib.Meta.SetNotationForOrder diff --git a/lean/mathlib-subset/Mathlib/Tactic/SplitIfs.lean b/lean/mathlib-subset/Mathlib/Tactic/SplitIfs.lean new file mode 100644 index 000000000000..9588605144e4 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Tactic/SplitIfs.lean @@ -0,0 +1,34 @@ +/- +Copyright (c) 2018 Gabriel Ebner. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Gabriel Ebner, David Renshaw +-/ +module + +public import Mathlib.Init + +/-! +Only the `split_ifs` syntax, which `compareOfLessAndEq_rfl` quotes; the tactic itself is omitted. +-/ + +public meta section + +namespace Mathlib.Tactic + +open Lean Elab.Tactic Parser.Tactic Lean.Meta + +/-- `split_ifs` splits the main goal in two goals for every if-then-else expression it contains, +by applying excluded middle to the condition. If the goal has the form `g (if p then x else y)`, +`split_ifs` will result in two goals `h✝ : p ⊢ g x` and `h✝ : ¬p ⊢ g y`. If there are multiple +if-then-else expressions, then `split_ifs` will split them all, starting with a top-most one whose +condition does not contain another if-then-else expression. + +* `split_ifs with h₁ h₂ h₃` names the introduced hypotheses. + Note that names are not reused across splits: on a goal of the form + `⊢ (if p then 1 else 2) + (if q then 3 else 4)`, use `split_ifs with hp hq hq` to name all + the hypotheses. +* `split_ifs at l` splits the if-then-else expressions at location(s) `l`. +-/ +syntax (name := splitIfs) "split_ifs" (location)? (" with" (ppSpace colGt binderIdent)+)? : tactic + +end Mathlib.Tactic diff --git a/lean/mathlib-subset/Mathlib/Tactic/Spread.lean b/lean/mathlib-subset/Mathlib/Tactic/Spread.lean new file mode 100644 index 000000000000..ec38047d49a4 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Tactic/Spread.lean @@ -0,0 +1,84 @@ +/- +Copyright (c) 2021 Gabriel Ebner. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Gabriel Ebner +-/ +module + +public meta import Lean.Elab.Binders +public import Mathlib.Init + +/-! +# Macro for spread syntax (`__ := instSomething`) in structures. +-/ + +public meta section + +open Lean Parser.Term Macro + +/- +This adds support for structure instance spread syntax. + +```lean +instance : Foo α where + __ := instSomething -- include fields from `instSomething` + +example : Foo α := { + __ := instSomething -- include fields from `instSomething` +} +``` +-/ + +/-- +Mathlib extension to preserve old behavior of structure instances. +We need to be able to `let` some implementation details that are still local instances. +Normally implementation detail fvars are not local instances, +but we need them to be implementation details so that `simp` will see them as "reducible" fvars. +-/ +syntax (name := letImplDetailStx) "let_impl_detail " ident " := " term "; " term : term + +open Lean Elab Term Meta + +@[term_elab letImplDetailStx, inherit_doc letImplDetailStx] +def elabLetImplDetail : TermElab := fun stx expectedType? => + match stx with + | `(let_impl_detail $id := $valStx; $body) => do + let val ← elabTerm valStx none + let type ← inferType val + trace[Elab.let.decl] "{id.getId} : {type} := {val}" + let result ← + withLetDecl id.getId (kind := .default) type val fun x => do + addLocalVarInfo id x + let lctx ← getLCtx + let lctx := lctx.modifyLocalDecl x.fvarId! fun decl => decl.setKind .implDetail + withLCtx lctx (← getLocalInstances) do + let body ← elabTermEnsuringType body expectedType? + let body ← instantiateMVars body + mkLetFVars #[x] body (usedLetOnly := false) + pure result + | _ => throwUnsupportedSyntax + +macro_rules +| `({ $[$srcs,* with]? $[$fields],* $[: $ty?]? }) => show MacroM Term from do + let mut spreads := #[] + let mut newFields := #[] + + for field in fields do + match field.1 with + | `(structInstField| $name:ident := $arg) => + if name.getId.eraseMacroScopes == `__ then do + spreads := spreads.push arg + else + newFields := newFields.push field + | _ => + throwUnsupported + + if spreads.isEmpty then throwUnsupported + + let spreadData ← withFreshMacroScope <| spreads.mapIdxM fun i spread => do + let n := Name.num `__spread i + return (mkIdent <| ← Macro.addMacroScope n, spread) + + let srcs := (srcs.map (·.getElems)).getD {} ++ spreadData.map Prod.fst + let body ← `({ $srcs,* with $[$newFields],* $[: $ty?]? }) + spreadData.foldrM (init := body) fun (id, val) body => `(let_impl_detail $id := $val; $body) diff --git a/lean/mathlib-subset/Mathlib/Tactic/TypeStar.lean b/lean/mathlib-subset/Mathlib/Tactic/TypeStar.lean new file mode 100644 index 000000000000..b3d3c51a86c4 --- /dev/null +++ b/lean/mathlib-subset/Mathlib/Tactic/TypeStar.lean @@ -0,0 +1,64 @@ +/- +Copyright (c) 2023 Kyle Miller. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Kyle Miller, Thomas R. Murrills +-/ +module + +-- Upstream gets this through `Mathlib.Tactic.Linter.Header`. +public meta import Lean.Elab.Command + +/-! +# Support for `Sort*` and `Type*`. + +These elaborate as `Sort u` and `Type u` with a fresh implicit universe variable `u`. +-/ + +public meta section + +namespace Lean.Elab.Term + +/-- +Given a `namePrefix` (`` `u`` by default), returns the first name out of `namePrefix_1`, +`namePrefix_2`, ... which does not appear in `usedLevelNames`. Note `mkFreshLevelName` does not +attempt to use `namePrefix` itself as a level name. +-/ +partial def mkFreshLevelName (usedLevelNames : List Name) (namePrefix : Name := `u) : Name := + go 1 +where + /-- Check if `namePrefix.appendIndexAfter n` is unused, else recurse with `n+1`. -/ + go n : Name := + let u := namePrefix.appendIndexAfter n + if usedLevelNames.contains u then go (n+1) else u + +/-- +Creates a fresh `Level` parameter which does not appear in the current state's `levelNames`, and +updates the state to include the new level parameter. + +By default, the new level parameter is of the form `u_i` and is included in the state as the most +recent level parameter (at the front of the list). + +Supplying a `namePrefix` will cause the new level parameter to be of the form `namePrefix_i`, with +`i` starting at `1`. + +The new level name can be inserted at a custom position in the list of level names by providing a +function `insert : List Name → Name → List Name` which will be called as +`insert currentLevelNames newLevelName`. It is expected that the result will contain the new level +name and still contain all current level names. +-/ +def mkFreshLevelParam (namePrefix : Name := `u) + (insert : List Name → Name → List Name := (·.cons)) : TermElabM Level := do + let levelNames ← getLevelNames + let u := mkFreshLevelName levelNames namePrefix + setLevelNames <| insert levelNames u + return mkLevelParam u + +/-- The syntax `variable (X Y ... Z : Sort*)` creates a new distinct implicit universe variable +for each variable in the sequence. -/ +elab "Sort*" : term => return .sort <| ← mkFreshLevelParam + +/-- The syntax `variable (X Y ... Z : Type*)` creates a new distinct implicit universe variable +`> 0` for each variable in the sequence. -/ +elab "Type*" : term => return .sort <| .succ <| ← mkFreshLevelParam + +end Lean.Elab.Term diff --git a/lean/mathlib-subset/README.md b/lean/mathlib-subset/README.md new file mode 100644 index 000000000000..d3f9a39d1510 --- /dev/null +++ b/lean/mathlib-subset/README.md @@ -0,0 +1,46 @@ +# Mathlib subset + +The `mathlib_subset` Lake package vendors the few [Mathlib](https://github.com/leanprover-community/mathlib4) and [Batteries](https://github.com/leanprover-community/batteries) declarations that the CCF Lean packages use, so that they do not depend on Mathlib itself. +Each file has the same path and module name as the upstream module it is taken from, but keeps only the definitions, instances, notation and theorems that CCF needs. +Theorems keep their upstream statements, but the subset may prove them differently, for example where an upstream proof needs modules that are not vendored or uses deprecated lemmas. +Lemmas that CCF needs but that are not upstream belong in the CCF packages, not here. + +## Upstream version + +The subset is taken from Mathlib `v4.35.0` and the Batteries revision that Mathlib pins. +The checker's [`lakefile.toml`](../mathlib-subset-check/lakefile.toml) and [`lake-manifest.json`](../mathlib-subset-check/lake-manifest.json) record these revisions. +The subset and the checker link their `lean-toolchain` files to the [Lean toolchain](../lean-toolchain) of the other packages. +Mathlib and Batteries are released under the Apache 2.0 license, a copy of which is in [`LICENSE`](LICENSE), and each file keeps its upstream copyright header. +The files also keep upstream formatting, so `scripts/lean-format-checks.sh` skips them. + +## Checking against upstream + +The [`mathlib-subset-check`](../mathlib-subset-check/Main.lean) package imports the subset and upstream Mathlib under the same module names, and requires the subset's declarations to match their upstream counterparts: the same module, kind and universe parameters, the same type, the same value for definitions after erasing proofs, and the same reducibility, instance priority and structure shape. +It also rejects axioms other than `propext`, `Classical.choice` and `Quot.sound`. +`Main.lean` documents the exact rules, including the internal declarations and metaprogram values that it does not compare. + +Run the check from the repository root: + +```sh +(cd lean/mathlib-subset && lake build --wfail) +cd lean/mathlib-subset-check +lake exe cache get +lake exe mathlib-subset-check ../mathlib-subset +``` + +`lake exe cache get` downloads upstream Mathlib and its prebuilt cache, about 7 GB on disk. +The CCF packages build the subset themselves, so this is only needed when changing the subset, the checker or the Lean toolchain. +The [Lean Mathlib Subset workflow](../../.github/workflows/lean-mathlib-subset.yml) runs the same commands on pull requests that change the subset, the checker, the Lean toolchain or the workflow. + +## Adding a declaration + +1. Find the module that declares it upstream, at the pinned version. + After `lake exe cache get`, the pinned sources are in `lean/mathlib-subset-check/.lake/packages/`. +2. Copy the declaration into the file with the same path here, creating the file with the upstream copyright header if needed. +3. Copy any declarations it uses that are not yet vendored, in the same way. +4. Give each file the upstream imports that are vendored. + Instances found during elaboration depend on what is imported, so other imports can produce a different term that the checker rejects. +5. Build the subset and run the checker. + +Mathlib releases target a single Lean release, so `lean/lean-toolchain` and the checker's Mathlib version change together. +To move to a new version, update `lean/lean-toolchain`, the `rev` in the checker's `lakefile.toml` and the version stated above, run `lake update` in `lean/mathlib-subset-check`, and copy the new upstream version of each declaration that the checker reports. diff --git a/lean/mathlib-subset/lake-manifest.json b/lean/mathlib-subset/lake-manifest.json new file mode 100644 index 000000000000..46d4c92b039e --- /dev/null +++ b/lean/mathlib-subset/lake-manifest.json @@ -0,0 +1,8 @@ +{ + "version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "mathlib_subset", + "lakeDir": ".lake", + "fixedToolchain": false +} diff --git a/lean/mathlib-subset/lakefile.toml b/lean/mathlib-subset/lakefile.toml new file mode 100644 index 000000000000..8f72a05831e3 --- /dev/null +++ b/lean/mathlib-subset/lakefile.toml @@ -0,0 +1,18 @@ +name = "mathlib_subset" +version = "0.1.0" +defaultTargets = ["Mathlib", "Batteries"] + +# The options Mathlib and Batteries are built with that affect elaboration. +[leanOptions] +autoImplicit = false +maxSynthPendingDepth = 3 + +[[lean_lib]] +name = "Mathlib" +globs = ["Mathlib.+"] + +[[lean_lib]] +name = "Batteries" +globs = ["Batteries.+"] +# Batteries keeps Lean's default. +leanOptions = {autoImplicit = true} diff --git a/lean/mathlib-subset/lean-toolchain b/lean/mathlib-subset/lean-toolchain new file mode 120000 index 000000000000..6f68e61b3719 --- /dev/null +++ b/lean/mathlib-subset/lean-toolchain @@ -0,0 +1 @@ +../lean-toolchain \ No newline at end of file diff --git a/scripts/lean-format-checks.sh b/scripts/lean-format-checks.sh index a8f3ac43eff3..495cef022a6c 100755 --- a/scripts/lean-format-checks.sh +++ b/scripts/lean-format-checks.sh @@ -36,7 +36,8 @@ for package in "${PACKAGES[@]}"; do fi # The disaster recovery package also checks Lean files outside lean/. if [ "$package" == "disaster-recovery" ]; then - PATHSPEC=("*.lean" ":(exclude)lean/consensus/*" ":(exclude)lean/consistency/*" ":(exclude)lean/kv/*") + # The vendored Mathlib subset keeps upstream formatting. + PATHSPEC=("*.lean" ":(exclude)lean/consensus/*" ":(exclude)lean/consistency/*" ":(exclude)lean/kv/*" ":(exclude)lean/mathlib-subset/*") else PATHSPEC=("lean/$package/*.lean") fi From b78572f56601e2b42a96531f968b0b4722301df4 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Mon, 9 Nov 2026 14:36:21 +0000 Subject: [PATCH 2/2] Use the vendored Mathlib subset in the Lean packages The packages now require lean/mathlib-subset instead of Mathlib, so CI and local setup no longer clone Mathlib or fetch its build cache. The proofs adopt the Mathlib-free rewrites from #8702 where they reduce what must be vendored. The kv and disaster-recovery packages drop the Batteries runLinter lint driver, which needed full Batteries; Lean's built-in linters still run. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/README.md | 10 +- .github/workflows/lean-package.yml | 6 - .github/workflows/lean.yml | 18 -- doc/build_apps/kv/semantics.rst | 1 - lean/common/README.md | 4 +- lean/common/lake-manifest.json | 106 +--------- lean/common/lakefile.toml | 6 +- lean/consensus/Consensus/Model/Node.lean | 9 +- lean/consensus/Consensus/Proofs/Direct.lean | 44 +++-- .../Consensus/Proofs/SafetyInvariant.lean | 184 +++++++++--------- .../consensus/Consensus/Proofs/Witnesses.lean | 6 +- lean/consensus/README.md | 1 - lean/consensus/lake-manifest.json | 108 +--------- lean/consensus/lakefile.toml | 5 - lean/consensus/replay/README.md | 1 - lean/consistency/README.md | 1 - .../consistency/Proofs/Invalidation.lean | 21 +- .../consistency/Proofs/Ordering.lean | 11 +- .../consistency/Proofs/Witnesses.lean | 6 +- lean/consistency/lake-manifest.json | 108 +--------- lean/consistency/lakefile.toml | 5 - .../DisasterRecovery/Proofs/Deadlock.lean | 17 +- .../DisasterRecovery/Proofs/Local.lean | 10 +- .../DisasterRecovery/Proofs/Safety.lean | 90 ++++----- lean/disaster-recovery/README.md | 14 +- lean/disaster-recovery/lake-manifest.json | 108 +--------- lean/disaster-recovery/lakefile.toml | 7 - lean/kv/README.md | 2 - lean/kv/lake-manifest.json | 108 +--------- lean/kv/lakefile.toml | 7 - 30 files changed, 235 insertions(+), 789 deletions(-) diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 3500c93e4b34..c39bf834879e 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -139,14 +139,16 @@ Runs Lean verification for the repository, with each package checked in an isola All five packages (consensus, common, consistency, disaster-recovery, and kv) run in one matrix. Package checks use the `gha-vmss-d16av7-ci` pool and trace replays use `gha-vmss-d16av7-ci-b`, both in Ubuntu 26.04 containers. Native trace captures remain on `gha-vmss-d16av7-ci-c` with Azure Linux containers, and the lightweight final gate uses GitHub-hosted Ubuntu. -Each matrix job caches its third-party dependency checkouts and build outputs, including Mathlib and (where used) leanfmt, using GitHub Actions caching. +Each matrix job caches its third-party dependency checkouts and build outputs, including (where used) leanfmt, using GitHub Actions caching. Caches are isolated by package and runner architecture and invalidated by changes to the Ubuntu version, Lean toolchain, package and common dependency manifests/configuration, or reusable workflow. -CCF package and common build outputs are not cached, and all verification steps still run, including Mathlib's upstream cache retrieval. +CCF package and common build outputs are not cached, and all verification steps still run. CCF consensus, KV, and consistency trace captures run in parallel with package checks. -Three independent trace-validation jobs each restore Mathlib caches, build their own replayer, download the corresponding capture artifacts, and replay the traces without depending on the package matrix. +Three independent trace-validation jobs each build their own replayer, download the corresponding capture artifacts, and replay the traces without depending on the package matrix. Consistency capture reuses the existing `consistency_trace_validation` e2e test, and its replay job also checks the consistency replay fixtures, including election and rollback traces. A final summary job requires every package and trace job to succeed. +The packages use only the Mathlib and Batteries declarations vendored in `lean/mathlib-subset`, rather than depending on Mathlib; the [Lean Mathlib Subset](#lean-mathlib-subset) workflow checks them against upstream. + The disaster recovery job builds the library and replayer with `lake build --wfail --fail-fast` and runs Lean's built-in linters with `lake lint` on Ubuntu 26.04 on relevant pull requests. Canonical behavior checks run with `#eval` when their test module is built, and assertion failures fail the build. The build includes both the human-reviewed model and system properties and the proof implementation files marked as generated for review purposes. @@ -178,7 +180,7 @@ It also runs on changes to the C++ sources and trace runners checked against the See the [local formatting commands](../../lean/disaster-recovery/README.md#formatting) to apply fixes. File: `lean.yml` -3rd party dependencies: Mathlib and leanfmt (pinned in the Lake package), and elan. +3rd party dependencies: leanfmt (pinned in the Lake packages), Mathlib (vendored subset), and elan. # Lean Mathlib Subset diff --git a/.github/workflows/lean-package.yml b/.github/workflows/lean-package.yml index bca41d6bcd50..35e0c08fa49c 100644 --- a/.github/workflows/lean-package.yml +++ b/.github/workflows/lean-package.yml @@ -62,12 +62,6 @@ jobs: path: lean/${{ inputs.package }}/.lake/packages key: lean-deps-v2-vmss-ubuntu-26.04-${{ runner.arch }}-${{ inputs.package }}-${{ hashFiles('lean/lean-toolchain', format('lean/{0}/lake-manifest.json', inputs.package), format('lean/{0}/lakefile.toml', inputs.package), 'lean/common/lake-manifest.json', 'lean/common/lakefile.toml', '.github/workflows/lean-package.yml') }} - - name: Restore Mathlib cache - working-directory: lean/${{ inputs.package }} - run: | - set -euo pipefail - lake exe cache get - - name: Build, kernel and axiom check working-directory: lean/${{ inputs.package }} run: | diff --git a/.github/workflows/lean.yml b/.github/workflows/lean.yml index 1fc56a953678..2844e66ee656 100644 --- a/.github/workflows/lean.yml +++ b/.github/workflows/lean.yml @@ -240,12 +240,6 @@ jobs: git config --global --add safe.directory "$GITHUB_WORKSPACE" elan run --install "$(cat lean/lean-toolchain)" lean --version - - name: Restore Mathlib cache - working-directory: lean/consensus - run: | - set -euo pipefail - lake exe cache get - - name: Build CCF consensus replay working-directory: lean/consensus run: | @@ -370,12 +364,6 @@ jobs: git config --global --add safe.directory "$GITHUB_WORKSPACE" elan run --install "$(cat lean/lean-toolchain)" lean --version - - name: Restore Mathlib cache - working-directory: lean/kv - run: | - set -euo pipefail - lake exe cache get - - name: Build KV replay working-directory: lean/kv run: | @@ -429,12 +417,6 @@ jobs: git config --global --add safe.directory "$GITHUB_WORKSPACE" elan run --install "$(cat lean/lean-toolchain)" lean --version - - name: Restore Mathlib cache - working-directory: lean/consistency - run: | - set -euo pipefail - lake exe cache get - - name: Build consistency replay working-directory: lean/consistency run: | diff --git a/doc/build_apps/kv/semantics.rst b/doc/build_apps/kv/semantics.rst index 38a9213a62f7..c4fbdbf89878 100644 --- a/doc/build_apps/kv/semantics.rst +++ b/doc/build_apps/kv/semantics.rst @@ -220,7 +220,6 @@ Lean is pinned by ``lean/kv/lean-toolchain`` and is independent of normal CCF bu .. code-block:: bash cd lean/kv - lake exe cache get lake build --wfail cd ../.. cmake -S . -B build-kv-trace -GNinja \ diff --git a/lean/common/README.md b/lean/common/README.md index ef6935d5874d..2927365f309a 100644 --- a/lean/common/README.md +++ b/lean/common/README.md @@ -17,10 +17,10 @@ The `ccf_common` Lake package exposes protocol-independent definitions in the `C ## Dependency imports -Specification proofs import the Mathlib tactics they need rather than the `Mathlib.Tactic` umbrella. +Specification proofs import the individual Mathlib modules they need from the vendored [Mathlib subset](../mathlib-subset/README.md), which keeps only the Mathlib and Batteries declarations that CCF uses. Their CCF declarations, theorem statements, exposed definitions, and required tactic support remain available, but importing a proof module or an assembled specification root does not promise to reexport unrelated Mathlib tactics or theory. `CCF.Execution` publicly imports `Mathlib.Data.Seq.Defs` and keeps `Mathlib.Data.Seq.Basic` private for its internal proofs. -Consumers that need other Mathlib facilities should import their defining modules explicitly. +Consumers that need other Mathlib facilities should import their defining modules explicitly, after adding them to the subset if necessary. The documented property entrypoints remain the public proof APIs; see the [CCF consensus protocol](../consensus/README.md#proofs), [consistency](../consistency/README.md#properties), and [disaster recovery](../disaster-recovery/README.md#properties) packages. Selective imports do not reduce the checked CCF roots or omit tests. diff --git a/lean/common/lake-manifest.json b/lean/common/lake-manifest.json index bc08dbd62fd4..f10f1e1e9dd1 100644 --- a/lean/common/lake-manifest.json +++ b/lean/common/lake-manifest.json @@ -3,111 +3,13 @@ "packagesDir": ".lake/packages", "packages": [ { - "url": "https://github.com/leanprover-community/mathlib4.git", - "type": "git", - "subDir": null, + "type": "path", "scope": "", - "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", - "name": "mathlib", + "name": "mathlib_subset", "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", "inherited": false, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/leanprover-community/plausible", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", - "name": "plausible", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/LeanSearchClient", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", - "name": "LeanSearchClient", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/import-graph", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", - "name": "importGraph", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/ProofWidgets4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", - "name": "proofwidgets", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/leanprover-community/aesop", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "4a174c490d8707121c4a9290800489f105d85e07", - "name": "aesop", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/quote4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", - "name": "Qq", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/batteries", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", - "name": "batteries", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover/lean4-cli", - "type": "git", - "subDir": null, - "scope": "leanprover", - "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", - "name": "Cli", - "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", - "inherited": true, + "dir": "../mathlib-subset", + "copy": false, "configFile": "lakefile.toml" } ], diff --git a/lean/common/lakefile.toml b/lean/common/lakefile.toml index d68fab29a20e..51bc50c9662a 100644 --- a/lean/common/lakefile.toml +++ b/lean/common/lakefile.toml @@ -24,6 +24,6 @@ supportInterpreter = true weakLinkArgs = ["-lLake"] [[require]] -name = "mathlib" -git = "https://github.com/leanprover-community/mathlib4.git" -rev = "v4.35.0" +name = "mathlib_subset" +path = "../mathlib-subset" +copy = false diff --git a/lean/consensus/Consensus/Model/Node.lean b/lean/consensus/Consensus/Model/Node.lean index 59ca2141162f..852226c3f766 100644 --- a/lean/consensus/Consensus/Model/Node.lean +++ b/lean/consensus/Consensus/Model/Node.lean @@ -5,7 +5,6 @@ public import Consensus.Model.Messages public import Consensus.Model.NodeState public import CCF.Capabilities public import Mathlib.Data.Finset.Sort -public import Mathlib.Order.Prod.Lex.Basic @[expose] public section @@ -59,18 +58,22 @@ Approximates `all_other_nodes`; unlike CCF, peers lost on rollback are not retai def eligiblePeers (state : NodeState) (self : NodeID) : Finset NodeID := (state.activeMembers ∪ state.retirementCompletedNodes).erase self +/-- Lexicographic order on successor ranks. -/ +def rankBelow (a b : Nat × Nat × Nat) : Bool := + decide (a.1 < b.1 \/ (a.1 = b.1 /\ Prod.lexLt a.2 b.2)) + /-- Maximize replication progress, latest active membership, then node ID. -/ def findSuccessor (state : NodeState) (self : NodeID) : Option NodeID := let configurations := state.activeConfigurations let rank node := - toLex (state.matchIndex node, toLex (latestMembershipIndex configurations node, node)) + (state.matchIndex node, latestMembershipIndex configurations node, node) let peers := (eligiblePeers state self).sort peers.foldl (fun best candidate => match best with | none => some candidate | some selected => - if rank selected < rank candidate then + if rankBelow (rank selected) (rank candidate) then some candidate else best) diff --git a/lean/consensus/Consensus/Proofs/Direct.lean b/lean/consensus/Consensus/Proofs/Direct.lean index 2bf88f2769d8..968a62433e83 100644 --- a/lean/consensus/Consensus/Proofs/Direct.lean +++ b/lean/consensus/Consensus/Proofs/Direct.lean @@ -1,7 +1,6 @@ module public import Consensus.Model -public import Mathlib.Tactic.SplitIfs import all Init.Control.State @@ -165,7 +164,7 @@ private theorem step_deliver network := removeOne envelope before.network ++ outputs.outgoing } := by simp only [Model.transitionSystem, lift, next, Model.protocol] at stepped - simp [Model.Node.step, Option.bind_eq_some_iff] at stepped + simp [Model.Node.step, Option.bind_eq_some_iff, guard] at stepped obtain ⟨queued, state, found, next, outputs, ran, rfl⟩ := stepped exact ⟨queued, state, next, outputs, found, ran, by simp [replaceNode]⟩ @@ -346,10 +345,10 @@ private lemma maxCommittableIndexPositiveIsSignature exact Or.inr headValid · by_cases bestLeHead : best <= head · right - simpa [max_eq_right bestLeHead] using headValid + simpa [Nat.max_eq_right bestLeHead] using headValid · right have headLeBest : head <= best := Nat.le_of_lt (Nat.lt_of_not_le bestLeHead) - simpa [max_eq_left headLeBest] using bestIsValid + simpa [Nat.max_eq_left headLeBest] using bestIsValid · simp [headValid, bestValid] have resultValid := foldValid (List.range (log.length + 1)) 0 (Or.inl rfl) @@ -382,14 +381,14 @@ private lemma signatureIndex_le_maxCommittableIndex induction values with | nil => intro best - exact le_rfl + exact Nat.le.refl | cons head tail inductionHypothesis => intro best - apply le_trans (b := choose best head) + apply Nat.le_trans (m := choose best head) · simp only [choose] split · exact Nat.le_max_left _ _ - · exact Nat.le_refl _ + · exact Nat.le.refl · exact inductionHypothesis (choose best head) have foldContains : forall (values : List Nat) (best : Nat), @@ -408,7 +407,7 @@ private lemma signatureIndex_le_maxCommittableIndex choose best index = max best index := by simp [choose, signature] rw [selected] - exact (le_max_right best index).trans (foldAboveStart tail (max best index)) + exact (Nat.le_max_right best index).trans (foldAboveStart tail (max best index)) · exact inductionHypothesis (choose best head) tailMember @@ -516,7 +515,9 @@ private lemma NodeState.recordCommit_commitIndex (node : NodeID) (state : NodeSt private lemma maxCommittableIndexUpTo_mono {left right : List Entry} (isPrefix : left <+: right) (frontier : Nat) : maxCommittableIndexUpTo left frontier <= maxCommittableIndexUpTo right frontier := - maxCommittableIndex_le_of_prefix (isPrefix.take frontier) + maxCommittableIndex_le_of_prefix + (List.prefix_take_iff.mpr + ⟨(List.take_prefix _ _).trans isPrefix, List.length_take_le _ _⟩) /-- The follower append loop changes only the log, commit and retirement fields, and may clear the role. -/ @@ -555,8 +556,8 @@ private lemma fromLeader_loop (self : NodeID) (limit : Nat) (entries : List Entr state.primaryKnown, by simp, Or.inl rfl, - le_rfl, - le_max_left _ _ + Nat.le.refl, + Nat.le_max_left _ _ ⟩ | cons entry entries ih => intro state @@ -828,12 +829,13 @@ private theorem CommitFrontier.advance {state : NodeState} state with log, commitIndex := max state.commitIndex (maxCommittableIndexUpTo log bound) } := by - refine ⟨max_le extends_.1 (maxCommittableIndexUpTo_le_length log bound), fun positive => ?_⟩ + refine ⟨Nat.max_le.mpr ⟨extends_.1, maxCommittableIndexUpTo_le_length log bound⟩, + fun positive => ?_⟩ simp only at positive ⊢ rcases Nat.le_total state.commitIndex (maxCommittableIndexUpTo log bound) with le | le - · rw [max_eq_right le] at positive ⊢ + · rw [Nat.max_eq_right le] at positive ⊢ exact maxCommittableIndexUpToPositiveIsSignature positive - · rw [max_eq_left le] at positive ⊢ + · rw [Nat.max_eq_left le] at positive ⊢ exact extends_.2 positive private theorem foldl_select_max (P : Nat -> Prop) [DecidablePred P] (values : List Nat) @@ -852,9 +854,9 @@ private theorem foldl_select_max (P : Nat -> Prop) [DecidablePred P] (values : L by_cases chosen : P head · rcases Nat.le_total init head with le | le · right - simp [chosen, max_eq_right le] + simp [chosen, Nat.max_eq_right le] · left - simp [chosen, max_eq_left le] + simp [chosen, Nat.max_eq_left le] · simp [chosen] · exact Or.inr holds @@ -1202,7 +1204,7 @@ private theorem Extends.committedLog {before after : NodeState} List.prefix_take_iff.mpr ⟨extended.2, (List.length_take_le _ _).trans extended.1⟩ private theorem Extends.refl (state : NodeState) : Extends state state := - ⟨le_rfl, List.take_prefix _ _⟩ + ⟨Nat.le.refl, List.take_prefix _ _⟩ private theorem Extends.trans {first second third : NodeState} (left : Extends first second) (right : Extends second third) @@ -1226,7 +1228,7 @@ private theorem Extends.of_log {before after : NodeState} private theorem Extends.append {state : NodeState} (entry : Entry) : Extends state { state with log := state.log ++ [entry] } := - ⟨le_rfl, (List.take_prefix _ _).trans (List.prefix_append _ _)⟩ + ⟨Nat.le.refl, (List.take_prefix _ _).trans (List.prefix_append _ _)⟩ end Consensus.Proofs.Direct @@ -1245,7 +1247,7 @@ private theorem Extends.fromLeader obtain ⟨retired, role, known, eq, -⟩ := Ledger.handleAppendEntiresFromPrimary_eq self state request rw [eq] - exact ⟨le_max_left _ _, (List.take_prefix _ _).trans (List.prefix_append _ _)⟩ + exact ⟨Nat.le_max_left _ _, (List.take_prefix _ _).trans (List.prefix_append _ _)⟩ private theorem Extends.handleAppendEntriesRequest (caps : Caps) (source : NodeID) : Keeps (Extends state) @@ -1280,7 +1282,7 @@ private theorem Extends.handleAppendEntriesRequest (caps : Caps) (source : NodeI primaryKnown := true, log := current.log.take (index - 1), isNewFollower := false } := Extends.of_prefix (count := index - 1) - (Nat.le_trans within (Nat.le_sub_of_add_le this)) (List.prefix_refl _) le_rfl + (Nat.le_trans within (Nat.le_sub_of_add_le this)) (List.prefix_refl _) Nat.le.refl exact Keeps.seq' fun _ => Keeps.pure' ((stepped.trans truncated).trans Extends.fromLeader) end AppendEntries @@ -1341,7 +1343,7 @@ private theorem Extends.becomePrimary (state : NodeState) } := by split · exact Extends.of_prefix (by unfold lastCommittableIndex; exact Nat.le_max_left _ _) - (List.prefix_refl _) le_rfl + (List.prefix_refl _) Nat.le.refl · exact Extends.of_log rfl rfl exact Keeps.bind' (Extends.advanced caps self _) fun _ kept => Keeps.seq' fun _ => Keeps.pure' (promoted.trans kept) diff --git a/lean/consensus/Consensus/Proofs/SafetyInvariant.lean b/lean/consensus/Consensus/Proofs/SafetyInvariant.lean index f5ae53169cd1..5e89e9c02a46 100644 --- a/lean/consensus/Consensus/Proofs/SafetyInvariant.lean +++ b/lean/consensus/Consensus/Proofs/SafetyInvariant.lean @@ -1,9 +1,10 @@ module public import Consensus.Model -public import Mathlib.Tactic.SplitIfs import all Init.Control.State +import Mathlib.Data.List.Infix +import Mathlib.Order.MinMax public import Consensus.Model.Node public import CCF.Execution @@ -975,13 +976,15 @@ variable [config : InitialConfiguration] private theorem initial_primary_iff (nonempty : INITIAL_CONFIGURATION.Nonempty) {node : NodeID} : INITIAL_CONFIGURATION.min = (node : WithTop NodeID) <-> node = INITIAL_PRIMARY := by - rw [INITIAL_PRIMARY, ← Finset.coe_min' nonempty, WithTop.untopD_coe, WithTop.coe_inj] + obtain ⟨least, found⟩ := Finset.min_of_nonempty nonempty + rw [INITIAL_PRIMARY, found, WithTop.untopD_coe, WithTop.coe_inj] exact eq_comm private theorem INITIAL_PRIMARY_mem (nonempty : INITIAL_CONFIGURATION.Nonempty) : INITIAL_PRIMARY ∈ INITIAL_CONFIGURATION := by - rw [INITIAL_PRIMARY, ← Finset.coe_min' nonempty, WithTop.untopD_coe] - exact Finset.min'_mem _ _ + obtain ⟨least, found⟩ := Finset.min_of_nonempty nonempty + rw [INITIAL_PRIMARY, found, WithTop.untopD_coe] + exact Finset.mem_of_min found private theorem GENESIS_configured : GENESIS.content.metadata.configuration.isSome := by simp [EntryContent.metadata] @@ -1043,7 +1046,7 @@ private theorem step_deliver network := removeOne envelope before.network ++ outputs.outgoing } := by simp only [Model.transitionSystem, lift, next, Model.protocol] at stepped - simp [Model.Node.step, Option.bind_eq_some_iff] at stepped + simp [Model.Node.step, Option.bind_eq_some_iff, guard] at stepped obtain ⟨queued, state, found, next, outputs, ran, rfl⟩ := stepped exact ⟨queued, state, next, outputs, found, ran, by simp [replaceNode]⟩ @@ -1252,10 +1255,10 @@ private lemma maxCommittableIndexPositiveIsSignature exact Or.inr headValid · by_cases bestLeHead : best <= head · right - simpa [max_eq_right bestLeHead] using headValid + simpa [Nat.max_eq_right bestLeHead] using headValid · right have headLeBest : head <= best := Nat.le_of_lt (Nat.lt_of_not_le bestLeHead) - simpa [max_eq_left headLeBest] using bestIsValid + simpa [Nat.max_eq_left headLeBest] using bestIsValid · simp [headValid, bestValid] have resultValid := foldValid (List.range (log.length + 1)) 0 (Or.inl rfl) @@ -1288,14 +1291,14 @@ private lemma signatureIndex_le_maxCommittableIndex induction values with | nil => intro best - exact le_rfl + exact Nat.le.refl | cons head tail inductionHypothesis => intro best - apply le_trans (b := choose best head) + apply Nat.le_trans (m := choose best head) · simp only [choose] split · exact Nat.le_max_left _ _ - · exact Nat.le_refl _ + · exact Nat.le.refl · exact inductionHypothesis (choose best head) have foldContains : forall (values : List Nat) (best : Nat), @@ -1314,7 +1317,7 @@ private lemma signatureIndex_le_maxCommittableIndex choose best index = max best index := by simp [choose, signature] rw [selected] - exact (le_max_right best index).trans (foldAboveStart tail (max best index)) + exact (Nat.le_max_right best index).trans (foldAboveStart tail (max best index)) · exact inductionHypothesis (choose best head) tailMember @@ -1459,7 +1462,9 @@ private lemma NodeState.recordCommit_commitIndex (node : NodeID) (state : NodeSt private lemma maxCommittableIndexUpTo_mono {left right : List Entry} (isPrefix : left <+: right) (frontier : Nat) : maxCommittableIndexUpTo left frontier <= maxCommittableIndexUpTo right frontier := - maxCommittableIndex_le_of_prefix (isPrefix.take frontier) + maxCommittableIndex_le_of_prefix + (List.prefix_take_iff.mpr + ⟨(List.take_prefix _ _).trans isPrefix, List.length_take_le _ _⟩) /-- The follower append loop changes only the log, commit and retirement fields, and may clear the role. -/ @@ -1498,8 +1503,8 @@ private lemma fromLeader_loop (self : NodeID) (limit : Nat) (entries : List Entr state.primaryKnown, by simp, Or.inl rfl, - le_rfl, - le_max_left _ _ + Nat.le.refl, + Nat.le_max_left _ _ ⟩ | cons entry entries ih => intro state @@ -2142,7 +2147,7 @@ private theorem acceptLog_eq {follower sender : List Entry} have senderOffset : sender.take (prev + offset) = sender.take prev ++ batch.take offset := by rw [List.take_add] congr 1 - conv_rhs => rw [batchEq] + conv => rhs; rw [batchEq] rw [List.take_take, Nat.min_eq_left (Nat.le_of_lt offBatch)] rw [takeLength, Nat.add_sub_cancel_left, keptAgree, senderOffset, List.append_assoc, List.take_append_drop, ← senderTake] @@ -2204,8 +2209,8 @@ private theorem acceptLog_eq {follower sender : List Entry} · have pos : 0 < follower.length := Nat.lt_of_le_of_lt (Nat.zero_le _) ahead have fs : follower.length <= sender.length := Nat.le_of_lt (Nat.lt_of_lt_of_le (Nat.lt_of_not_le long) batchBound) - have := aligned follower.length pos le_rfl fs (by - rw [termAt_eq pos le_rfl, termAt_eq pos fs] + have := aligned follower.length pos Nat.le.refl fs (by + rw [termAt_eq pos Nat.le.refl, termAt_eq pos fs] have eq : prev + (follower.length - 1 - prev) = follower.length - 1 := Nat.add_sub_of_le (Nat.le_sub_one_of_lt ahead) have lastLt : prev + (follower.length - 1 - prev) < follower.length := by @@ -2216,7 +2221,7 @@ private theorem acceptLog_eq {follower sender : List Entry} (Nat.lt_trans lastLt (Nat.lt_of_not_le long))) lastLt simpa only [eq] using this) - rwa [List.take_of_length_le le_rfl] at this + rwa [List.take_of_length_le Nat.le.refl] at this have differ : Not (follower.take (prev + batch.length) = sender.take (prev + batch.length)) := by intro same @@ -2233,7 +2238,7 @@ private theorem acceptLog_eq {follower sender : List Entry} rw [senderTake, List.take_append, List.length_take, Nat.min_eq_left prevSender, List.take_of_length_le (Nat.le_trans (List.length_take_le _ _) prevBound)] at viaTake exact viaTake - nth_rewrite 1 [followerEq] + rw (occs := .pos [1]) [followerEq] rw [List.append_assoc, List.take_append_drop, senderTake] private theorem mem_history_filterMap {log : List Entry} {start : Nat} @@ -2263,7 +2268,7 @@ private theorem configurationHistory_split (log : List Entry) (k : Nat) fun nodes => ({ index, nodes } : Configuration), ?_, ?_⟩ · unfold configurationHistory - conv_lhs => rw [split] + conv => lhs; rw [split] rw [List.zipIdx_append, List.filterMap_append] · intro configuration member have := mem_history_filterMap member @@ -2312,9 +2317,9 @@ private theorem length_filter_index_mono (configurations : List Configuration) : (configurations.filter fun configuration => configuration.index <= small).length <= (configurations.filter fun configuration => configuration.index <= large).length := by - apply List.Sublist.length_le - apply List.monotone_filter_right - intro configuration holds + simp only [← List.countP_eq_length_filter] + apply List.countP_mono_left + intro configuration _ holds simp at holds ⊢ exact Nat.le_trans holds le @@ -2397,7 +2402,7 @@ private theorem chosen_bound {configurations : List Configuration} · simp at positive · simp only [chosen, Nat.eq_zero_of_not_pos counted, Nat.zero_sub, List.getElem_cons_zero] rcases List.mem_cons.mp member with rfl | later - · exact le_rfl + · exact Nat.le.refl · exact ((List.pairwise_cons.mp sorted).1 other later).le /-- @@ -2419,7 +2424,8 @@ private theorem activeConfigurations_overlap {left right : List Entry} obtain ⟨leftRest, leftEq, leftLater⟩ := configurationHistory_split left k obtain ⟨rightRest, rightEq, rightLater⟩ := configurationHistory_split right k rw [agree] at leftEq - set common := configurationHistory (right.take k) + have sorted := configurationHistory_sorted (right.take k) + generalize configurationHistory (right.take k) = common at leftEq rightEq configured sorted ⊢ have commonPos : 0 < common.length := List.length_pos_iff.mpr configured have count : forall {log : List Entry} {rest commit}, configurationHistory log = common ++ rest @@ -2449,19 +2455,18 @@ private theorem activeConfigurations_overlap {left right : List Entry} rw [count leftEq leftLater leftLe, count rightEq rightLater rightLe] have leftBound := length_filter_le common leftCommit have rightBound := length_filter_le common rightCommit - have sorted := configurationHistory_sorted (right.take k) have last : common.length - 1 < common.length := Nat.sub_one_lt (Nat.ne_of_gt commonPos) rcases Nat.le_total leftCommit rightCommit with ordered | ordered · have mono := length_filter_index_mono common ordered have chosenLt := Nat.lt_of_le_of_lt (Nat.sub_le_sub_right rightBound 1) last refine ⟨common[_ - 1]'chosenLt, inDrop chosenLt leftEq (Nat.sub_le_sub_right mono 1), - inDrop chosenLt rightEq le_rfl, ?_⟩ + inDrop chosenLt rightEq Nat.le.refl, ?_⟩ rcases chosen_bound sorted rightCommit commonPos with within | first · exact Or.inl (within.trans (Nat.le_max_right _ _)) · exact Or.inr first · have mono := length_filter_index_mono common ordered have chosenLt := Nat.lt_of_le_of_lt (Nat.sub_le_sub_right leftBound 1) last - refine ⟨common[_ - 1]'chosenLt, inDrop chosenLt leftEq le_rfl, + refine ⟨common[_ - 1]'chosenLt, inDrop chosenLt leftEq Nat.le.refl, inDrop chosenLt rightEq (Nat.sub_le_sub_right mono 1), ?_⟩ rcases chosen_bound sorted leftCommit commonPos with within | first · exact Or.inl (within.trans (Nat.le_max_left _ _)) @@ -2671,12 +2676,13 @@ private theorem CommitFrontier.advance {state : NodeState} state with log, commitIndex := max state.commitIndex (maxCommittableIndexUpTo log bound) } := by - refine ⟨max_le extends_.1 (maxCommittableIndexUpTo_le_length log bound), fun positive => ?_⟩ + refine ⟨Nat.max_le.mpr ⟨extends_.1, maxCommittableIndexUpTo_le_length log bound⟩, + fun positive => ?_⟩ simp only at positive ⊢ rcases Nat.le_total state.commitIndex (maxCommittableIndexUpTo log bound) with le | le - · rw [max_eq_right le] at positive ⊢ + · rw [Nat.max_eq_right le] at positive ⊢ exact maxCommittableIndexUpToPositiveIsSignature positive - · rw [max_eq_left le] at positive ⊢ + · rw [Nat.max_eq_left le] at positive ⊢ exact extends_.2 positive private theorem foldl_select_max (P : Nat -> Prop) [DecidablePred P] (values : List Nat) @@ -2695,9 +2701,9 @@ private theorem foldl_select_max (P : Nat -> Prop) [DecidablePred P] (values : L by_cases chosen : P head · rcases Nat.le_total init head with le | le · right - simp [chosen, max_eq_right le] + simp [chosen, Nat.max_eq_right le] · left - simp [chosen, max_eq_left le] + simp [chosen, Nat.max_eq_left le] · simp [chosen] · exact Or.inr holds @@ -3031,7 +3037,7 @@ private theorem Extends.committedLog {before after : NodeState} List.prefix_take_iff.mpr ⟨extended.2, (List.length_take_le _ _).trans extended.1⟩ private theorem Extends.refl (state : NodeState) : Extends state state := - ⟨le_rfl, List.take_prefix _ _⟩ + ⟨Nat.le.refl, List.take_prefix _ _⟩ private theorem Extends.trans {first second third : NodeState} (left : Extends first second) (right : Extends second third) @@ -3055,7 +3061,7 @@ private theorem Extends.of_log {before after : NodeState} private theorem Extends.append {state : NodeState} (entry : Entry) : Extends state { state with log := state.log ++ [entry] } := - ⟨le_rfl, (List.take_prefix _ _).trans (List.prefix_append _ _)⟩ + ⟨Nat.le.refl, (List.take_prefix _ _).trans (List.prefix_append _ _)⟩ end Consensus.Proofs.Direct @@ -3074,7 +3080,7 @@ private theorem Extends.fromLeader obtain ⟨retired, role, known, eq, -⟩ := Ledger.handleAppendEntiresFromPrimary_eq self state request rw [eq] - exact ⟨le_max_left _ _, (List.take_prefix _ _).trans (List.prefix_append _ _)⟩ + exact ⟨Nat.le_max_left _ _, (List.take_prefix _ _).trans (List.prefix_append _ _)⟩ private theorem Extends.handleAppendEntriesRequest (caps : Caps) (source : NodeID) : Keeps (Extends state) @@ -3109,7 +3115,7 @@ private theorem Extends.handleAppendEntriesRequest (caps : Caps) (source : NodeI primaryKnown := true, log := current.log.take (index - 1), isNewFollower := false } := Extends.of_prefix (count := index - 1) - (Nat.le_trans within (Nat.le_sub_of_add_le this)) (List.prefix_refl _) le_rfl + (Nat.le_trans within (Nat.le_sub_of_add_le this)) (List.prefix_refl _) Nat.le.refl exact Keeps.seq' fun _ => Keeps.pure' ((stepped.trans truncated).trans Extends.fromLeader) end AppendEntries @@ -3170,7 +3176,7 @@ private theorem Extends.becomePrimary (state : NodeState) } := by split · exact Extends.of_prefix (by unfold lastCommittableIndex; exact Nat.le_max_left _ _) - (List.prefix_refl _) le_rfl + (List.prefix_refl _) Nat.le.refl · exact Extends.of_log rfl rfl exact Keeps.bind' (Extends.advanced caps self _) fun _ kept => Keeps.seq' fun _ => Keeps.pure' (promoted.trans kept) @@ -3553,7 +3559,7 @@ private theorem becomePrimary_sends (candidate : NodeState) have sentEq : leader.sentIndex peer = leader.log.length := by rw [advance.sentIndex, advance.log] simp [primaryState] - refine ⟨rfl, other, _, rfl, rfl, ?_, rfl, ?_, le_rfl⟩ <;> + refine ⟨rfl, other, _, rfl, rfl, ?_, rfl, ?_, Nat.le.refl⟩ <;> simp [makeAppendEntriesRequest, sentEq, messageEntries] · intro e member rcases List.mem_append.mp (by simpa using member) with old | new @@ -3744,7 +3750,7 @@ private theorem observe_bumping (before : NodeState) {message : Message} cases message <;> simp_all [Bumping, observeTerm, updateTerm, becomeAwareOfNewTerm, bumpedState] · refine Or.inr ⟨Nat.not_lt.mp bump, ?_⟩ - cases message <;> simp_all [Bumping, observeTerm, updateTerm] + cases message <;> simp_all [Bumping, observeTerm, updateTerm, Nat.not_lt_of_le] end Consensus.Proofs.Safety @@ -3788,7 +3794,7 @@ private theorem checkQuorum_summary (state : NodeState) (input : Input) refine Sends.bind' Sends.guard' fun _ sent ⟨⟨leader, _⟩, empty⟩ => Sends.pure' ?_ subst empty refine ⟨ - le_rfl, + Nat.le.refl, fun _ voted eq => eq, fun _ => Or.inl (by rw [leader]; simp), fun c => by simp at c, @@ -3831,7 +3837,7 @@ private theorem sendEntries_summary (state : NodeState) (destination : NodeID) simp [eligiblePeers] at peer; exact peer.1 refine ⟨ rfl, - ⟨other, rfl, le.trans bound, rfl, ?_, le_rfl⟩, + ⟨other, rfl, le.trans bound, rfl, ?_, Nat.le.refl⟩, by simp [leader], Or.inl ⟨leader, rfl⟩ ⟩ @@ -3853,7 +3859,7 @@ private theorem startElection_summary (state : NodeState) campaign_summary (fresh_campaign notNone rfl rfl rfl) result · refine Sends.bind' (broadcast_sends self _ _) fun _ sent requests => Sends.pure' ?_ simp only [List.append_nil] - refine ⟨le_rfl, fun _ voted eq => eq, fun _ => Or.inl notNone, fun c => by simp at c, + refine ⟨Nat.le.refl, fun _ voted eq => eq, fun _ => Or.inl notNone, fun c => by simp at c, fun c => by simp at c, fun c => by simp at c, Kind.same rfl rfl, fun e member => ?_⟩ obtain ⟨source, _, payload⟩ := requests e member refine ⟨source, ?_⟩ @@ -3877,7 +3883,7 @@ private theorem voteRequest_summary (before : NodeState) (source : NodeID) Event.receive source (Message.requestVoteRequest request) = (Event.receive source' message : Event) /\ Bumping message /\ message.term <= (bumpedState before request.term).currentTerm := - ⟨source, _, rfl, trivial, le_refl _⟩ + ⟨source, _, rfl, trivial, Nat.le.refl⟩ split <;> rename_i granted <;> simp only [decide_eq_true_eq] at granted · refine bumped_summary bump (by simp [bumpedState]) (by simp [bumpedState]) active (Kind.same rfl rfl) fun e member => ?_ @@ -3898,7 +3904,7 @@ private theorem voteRequest_summary (before : NodeState) (source : NodeID) /\ Bumping message /\ message.term <= before.currentTerm := ⟨source, _, rfl, trivial, le⟩ split <;> rename_i granted <;> simp only [decide_eq_true_eq] at granted - · refine ⟨le_rfl, fun _ voted votedEq => ?_, fun _ => Or.inr (Or.inr active), + · refine ⟨Nat.le.refl, fun _ voted votedEq => ?_, fun _ => Or.inr (Or.inr active), fun candidate => ⟨candidate, rfl, rfl, Or.inr ⟨candidate, rfl, ?_, fun voter member => Or.inl member⟩⟩, fun leader => Or.inl ⟨leader, rfl⟩, fun _ _ _ _ => Or.inl rfl, Kind.same rfl rfl, @@ -3933,7 +3939,7 @@ private theorem preVoteRequest_summary (before : NodeState) (source : NodeID) refine Sends.bind' (Sends.send _ _ _) fun _ sent eq => Sends.pure' ?_ <;> subst eq · refine bumped_summary bump (by simp [bumpedState]) (by simp [bumpedState]) - ⟨source, _, rfl, trivial, le_refl _⟩ (Kind.same rfl rfl) fun e member => ?_ + ⟨source, _, rfl, trivial, Nat.le.refl⟩ (Kind.same rfl rfl) fun e member => ?_ simp only [List.mem_singleton, List.append_nil] at member subst member exact ⟨rfl, rfl⟩ @@ -4001,7 +4007,7 @@ private theorem voteResponse_summary (before : NodeState) (source : NodeID) with ⟨bump, eq⟩ | ⟨le, eq⟩ <;> rw [eq] <;> simp only [handleRequestVoteResponse] · refine Sends.ite' (fun won => absurd won.1 (by simp [bumpedState])) fun _ => Sends.pure' (bumped_summary bump (by simp [bumpedState]) (by simp [bumpedState]) - ⟨source, _, rfl, trivial, le_refl _⟩ (Kind.same rfl rfl) (by simp)) + ⟨source, _, rfl, trivial, Nat.le.refl⟩ (Kind.same rfl rfl) (by simp)) · refine Sends.ite' (fun won => ?_) fun _ => Sends.pure' (quiet_summary rfl rfl rfl rfl rfl rfl rfl (fun empty => (empty rfl).elim) (by simp)) @@ -4033,7 +4039,7 @@ private theorem preVoteResponse_summary (before : NodeState) (source : NodeID) with ⟨bump, eq⟩ | ⟨le, eq⟩ <;> rw [eq] <;> simp only [handleRequestPreVoteResponse] · refine Sends.ite' (fun won => absurd won.1 (by simp [bumpedState])) fun _ => Sends.pure' (bumped_summary bump (by simp [bumpedState]) (by simp [bumpedState]) - ⟨source, _, rfl, trivial, le_refl _⟩ (Kind.same rfl rfl) (by simp)) + ⟨source, _, rfl, trivial, Nat.le.refl⟩ (Kind.same rfl rfl) (by simp)) · refine Sends.ite' (fun won => ?_) fun _ => Sends.pure' (quiet_summary rfl rfl rfl rfl rfl rfl rfl (fun empty => (empty rfl).elim) (by simp)) @@ -4206,8 +4212,10 @@ private theorem aeReply (self source : NodeID) (z : NodeState) (role : after.role = w.role \/ after.role = .none) (cand : after.role = .candidate -> after = w) => (⟨term.trans wTerm, voted.trans wVoted, matchEq.trans wMatch, - by rcases role with role | role <;> rw [role] <;> [rcases wRole with r | r; skip] <;> - simp [*], + by + rcases role with role | role <;> rw [role] + · rcases wRole with r | r <;> simp [*] + · simp [*], fun c => (cand c).trans (wCand (by rcases role with role | role <;> rw [role] at c · exact c @@ -4328,7 +4336,7 @@ private theorem appendEntriesRequest_summary (self : NodeID) (before : NodeState simp only [receive] rcases observe_bumping before (message := .appendEntriesRequest request) trivial with ⟨bump, eq⟩ | ⟨le, eq⟩ <;> rw [eq] - · refine Sends.mono (aeReply self source _ request (le_refl _)) fun after sent reply => ?_ + · refine Sends.mono (aeReply self source _ request (Nat.le.refl)) fun after sent reply => ?_ obtain ⟨kind, sends⟩ := aeReply_summary (before := before) (z := bumpedState before request.term) rfl rfl bump.le reply obtain ⟨term, _, _, role, _, _⟩ := reply @@ -4336,9 +4344,9 @@ private theorem appendEntriesRequest_summary (self : NodeID) (before : NodeState rcases role with eq | eq | eq <;> rw [eq] <;> simp [bumpedState] exact bumped_summary (term ▸ bump) (by rcases follower with f | f <;> simp [f]) (by rcases follower with f | f <;> simp [f]) - ⟨source, _, rfl, trivial, term ▸ le_refl _⟩ kind sends + ⟨source, _, rfl, trivial, term ▸ Nat.le.refl⟩ kind sends · refine Sends.mono (aeReply self source _ request le) fun after sent reply => ?_ - obtain ⟨kind, sends⟩ := aeReply_summary (before := before) rfl rfl le_rfl reply + obtain ⟨kind, sends⟩ := aeReply_summary (before := before) rfl rfl Nat.le.refl reply obtain ⟨term, voted, matchEq, role, cand, _⟩ := reply refine ⟨term.ge, fun _ voted' eq => voted ▸ eq, fun _ => Or.inr (Or.inr ⟨source, _, rfl, trivial, term ▸ le⟩), fun c => ?_, @@ -4360,7 +4368,7 @@ private theorem BatchState.push {self : NodeID} {before state : NodeState} obtain ⟨⟨entries, sentIndex, rfl, terms⟩, beats⟩ := batch refine ⟨ ⟨entries ++ [{ term := before.currentTerm, content }], sentIndex, by simp, ?_⟩, - fun e member => (beats e member).extend (List.prefix_append _ _) le_rfl + fun e member => (beats e member).extend (List.prefix_append _ _) Nat.le.refl ⟩ intro entry member rcases List.mem_append.mp member with old | new @@ -4393,7 +4401,7 @@ private theorem appendEntry_batch (self : NodeID) (before : NodeState) subst member' have added := (Finset.mem_sort _).mp member have other : Not (peer = self) := (Finset.mem_erase.mp added).1 - refine ⟨rfl, other, _, rfl, rfl, ?_, ?_, ?_, le_rfl⟩ <;> + refine ⟨rfl, other, _, rfl, rfl, ?_, ?_, ?_, Nat.le.refl⟩ <;> simp only [makeAppendEntriesRequest, ite_eq_left added, messageEntries] <;> simp · have batch : BatchState self before { before with @@ -4425,7 +4433,7 @@ private theorem sendEntries_batch (self : NodeID) (before state : NodeState) · simp only [eq, List.mem_singleton] at new subst e have other : Not (destination = self) := (Finset.mem_erase.mp peer).1 - exact ⟨rfl, other, _, rfl, rfl, le.trans bound, rfl, List.take_prefix _ _, le_rfl⟩ + exact ⟨rfl, other, _, rfl, rfl, le.trans bound, rfl, List.take_prefix _ _, Nat.le.refl⟩ private theorem appendBatch_summary (self : NodeID) (state : NodeState) (contents : List AppendEntryInput) @@ -4634,7 +4642,7 @@ private theorem Seen.cons {current : Model.State} {rest : History} private theorem suffix_comparable {α : Type} {first second whole : List α} (left : first <:+ whole) (right : second <:+ whole) : first <:+ second \/ second <:+ first := by - rcases le_total first.length second.length with le | le + rcases Nat.le_total first.length second.length with le | le · exact Or.inl (List.suffix_of_suffix_length_le left right le) · exact Or.inr (List.suffix_of_suffix_length_le right left le) @@ -4729,7 +4737,8 @@ private theorem inv_initial : Inv [initial] := by · intro node state now active rw [stateOf now] at active ⊢ simp only [initialLocal] at active ⊢ - split_ifs at active ⊢ <;> simp_all [BOOTSTRAP_TERM] + by_cases primary : node = INITIAL_PRIMARY <;> by_cases member : node ∈ INITIAL_CONFIGURATION + <;> simp_all [BOOTSTRAP_TERM] · intro node state earlier now seen rw [stateOf now, initial_seen initialized seen] · intro node state earlier candidate now seen voted @@ -4751,7 +4760,8 @@ private theorem inv_initial : Inv [initial] := by · intro node state now candidate rw [stateOf now] at candidate simp only [initialLocal] at candidate - split_ifs at candidate + by_cases primary : node = INITIAL_PRIMARY <;> by_cases member : node ∈ INITIAL_CONFIGURATION + <;> simp [primary, member] at candidate · intro after before rest node term log commit suffix have := suffix.length_le simp at this @@ -4911,7 +4921,7 @@ private theorem termAt_mono {log : List Entry} exact Nat.zero_le _ rw [termAt_eq positive (le.trans bound), termAt_eq (Nat.lt_of_lt_of_le positive le) bound] rcases Nat.eq_or_lt_of_le le with rfl | lt - · exact le_rfl + · exact Nat.le.refl · exact List.pairwise_iff_getElem.mp sorted _ _ _ _ (Nat.sub_lt_sub_right (Nat.succ_le_of_lt positive) lt) @@ -4949,7 +4959,7 @@ private theorem take_signature {log : List Entry} {index : Nat} (signature : isSignatureAt log index = true) : isSignatureAt (log.take index) (log.take index).length = true := by rw [List.length_take, Nat.min_eq_left (signature_bound signature)] - exact isSignatureAt_take_of_le le_rfl signature + exact isSignatureAt_take_of_le Nat.le.refl signature private theorem Led.two_le {history : History} {node : NodeID} {term : Nat} (led : Led history node term) @@ -5099,7 +5109,7 @@ private theorem Committed.signature {history : History} {term : Nat} _⟩ := committed.shape refine ⟨take_signature signature, ?_, led.two_le⟩ rw [List.length_take, Nat.min_eq_left (signature_bound signature), - termAt_take le_rfl, termEq] + termAt_take Nat.le.refl, termEq] /-- A part committed in a term is in every later leader log. -/ private theorem committed_in_canon {history : History} (complete : Completeness history) @@ -5142,7 +5152,7 @@ private theorem committed_comparable {history : History} · exact comparable_of_prefix (List.take_prefix _ _) ((List.take_prefix _ _).trans sub) · exact comparable_of_prefix (committed_in_canon complete mono committed canon' lt) (List.take_prefix _ _) - rcases le_total first second with le | le + rcases Nat.le_total first second with le | le · exact inCanon leftCommitted rightCommitted le · exact (inCanon rightCommitted leftCommitted le).symm @@ -5177,7 +5187,7 @@ private theorem Wins.facts {self : NodeID} {before' : NodeState} {event : Event} rw [← this] exact quorum rcases advance with rfl | ⟨log, term, voted, matchEq, _, _, lt, _, role⟩ - · exact ⟨rfl, rfl, rfl, fun _ => rfl, Or.inl rfl, le_rfl⟩ + · exact ⟨rfl, rfl, rfl, fun _ => rfl, Or.inl rfl, Nat.le.refl⟩ · refine ⟨log, term, voted, fun peer => by rw [matchEq]; rfl, ?_, ?_⟩ · rcases role with role | role · exact Or.inl role @@ -5386,11 +5396,11 @@ private theorem vals_upToDate {state : NodeState} (term : Nat) : voteLogUpToDate state (vals term state.log state.commitIndex) := by have mono : maxCommittableTerm state.log <= termAt state.log (max state.commitIndex (maxCommittableIndex state.log)) := - termAt_mono sorted (le_max_right _ _) - (max_le frontier (maxCommittableIndexBounded state.log)) + termAt_mono sorted (Nat.le_max_right _ _) + (Nat.max_le.mpr ⟨frontier, maxCommittableIndexBounded state.log⟩) rcases Nat.lt_or_eq_of_le mono with lt | eq · exact Or.inl lt - · exact Or.inr ⟨eq.symm, le_max_right _ _⟩ + · exact Or.inr ⟨eq.symm, Nat.le_max_right _ _⟩ end Consensus.Proofs.Safety @@ -5573,7 +5583,7 @@ private theorem term_mono : TermMono (after :: before :: rest) := by rcases c.now_after now with ⟨rfl, rfl⟩ | ⟨different, old⟩ · rcases c.seen_after seen with seen | ⟨_, rfl⟩ · exact (c.inv.term_mono c.actor c.pre earlier c.pre_now seen).trans c.term_le - · exact le_rfl + · exact Nat.le.refl · rcases c.seen_after seen with seen | ⟨same, _⟩ · exact c.inv.term_mono node state earlier old seen · exact absurd same different @@ -5690,7 +5700,7 @@ private theorem wins_elect (wins : Wins c.actor c.pre c.event c.post) · rw [candidateLog] exact take_prefix_take _ (by simp only [lastCommittableIndex, candidateLog] - exact le_max_right _ _) + exact Nat.le_max_right _ _) · rw [candidateLog] exact List.take_prefix _ _ · intro voter mem @@ -5864,9 +5874,9 @@ private theorem core {small large : History} (within : small <:+ large) have partLength : (state.log.take index).length = index := by rw [List.length_take, Nat.min_eq_left indexLe] have partSignature : isSignatureAt (state.log.take index) index = true := - isSignatureAt_take_of_le le_rfl signature + isSignatureAt_take_of_le Nat.le.refl signature have partTerm : termAt (state.log.take index) index = term := by - rw [termAt_take le_rfl, termAtIndex] + rw [termAt_take Nat.le.refl, termAtIndex] have ackerTake : acker.log.take index = state.log.take index := (take_of_prefix_length ackerLog partLength).symm have ackerTerm' : termAt acker.log index = term := by @@ -5893,11 +5903,11 @@ private theorem core {small large : History} (within : small <:+ large) exact this -- The election's last committable position. simp only [voteLogUpToDate, vals] at upToDate - set j := max commit (maxCommittableIndex log) with jEq + generalize jEq : max commit (maxCommittableIndex log) = j at upToDate ⊢ have two : 2 <= term := by have := leaderLed.two_le exact this - have jBound : j <= log.length := max_le frontier (maxCommittableIndexBounded log) + have jBound : j <= log.length := jEq ▸ Nat.max_le.mpr ⟨frontier, maxCommittableIndexBounded log⟩ have termGe : term <= termAt log j := upToDate.elim (fun gt => Nat.le_trans maxTermGe (Nat.le_of_lt gt)) (fun eq => Nat.le_trans maxTermGe (Nat.le_of_eq eq.1.symm)) @@ -5936,8 +5946,8 @@ private theorem core {small large : History} (within : small <:+ large) have mono := termAt_mono partSorted short.le partLength.ge have atJ : termAt (state.log.take index) j = termAt log j := by rw [← termAt_of_prefix sub (Nat.le_of_lt (Nat.lt_of_lt_of_eq short partLength.symm)), - ← termAt_take (n := j) le_rfl, ← anchoredTake, - termAt_take le_rfl] + ← termAt_take (n := j) Nat.le.refl, ← anchoredTake, + termAt_take Nat.le.refl] rw [atJ, partTerm] at mono exact Nat.lt_irrefl _ (Nat.lt_of_lt_of_le above mono) · exact viaAnchor long (Nat.le_trans long anchoredLength) @@ -5983,13 +5993,13 @@ private theorem agree_or_contained {α : Type} {state log : List α} \/ exists k, state.take k = log.take k /\ base <= k /\ commit <= k := by rcases le_or_gt commit base with le | lt · exact Or.inr ⟨base, take_of_prefix_length (low le) - (List.length_take_of_le (Nat.le_trans baseLe indexLe)), le_rfl, le⟩ + (List.length_take_of_le (Nat.le_trans baseLe indexLe)), Nat.le.refl, le⟩ · obtain ⟨part, inPart, comparable⟩ := high lt have commitLength : (log.take commit).length = commit := List.length_take_of_le frontier have partLong : commit <= part.length := commitLength ▸ inPart.length_le have indexLength : (state.take index).length = index := List.length_take_of_le indexLe rcases le_or_gt commit index with le | short - · refine Or.inr ⟨commit, ?_, lt.le, le_rfl⟩ + · refine Or.inr ⟨commit, ?_, lt.le, Nat.le.refl⟩ calc state.take commit = (state.take index).take commit := by rw [List.take_take, Nat.min_eq_left le] @@ -6116,7 +6126,7 @@ private theorem new_old_unique {node other : NodeID} {term commit : Nat} quorum', granted'⟩ := elect' have agreement : exists k, log.take k = log'.take k /\ commit <= k /\ commit' <= k := by rcases Nat.le_total commit' commit with le | le - · refine ⟨commit, ?_, le_rfl, le⟩ + · refine ⟨commit, ?_, Nat.le.refl, le⟩ rcases c.elect_backed after before rest node term log commit (List.suffix_refl _) elect with zero | ⟨_, part, committed, below, inPart⟩ · rw [zero, List.take_zero, List.take_zero] @@ -6125,7 +6135,7 @@ private theorem new_old_unique {node other : NodeID} {term commit : Nat} (Nat.lt_of_le_of_lt below (Nat.sub_lt (Nat.lt_of_lt_of_le (Nat.zero_lt_succ 2) three) Nat.one_pos)) exact take_of_prefix_length (inPart.trans this) (List.length_take_of_le frontier) - · refine ⟨commit', ?_, le, le_rfl⟩ + · refine ⟨commit', ?_, le, Nat.le.refl⟩ rcases c.inv.elect_backed a b r other term log' commit' suffix elect' with zero | ⟨_, part, committed, below, inPart⟩ · rw [zero, List.take_zero, List.take_zero] @@ -6268,7 +6278,7 @@ private theorem anchor : Anchor (after :: before :: rest) := by c.inv.anchor c.actor c.pre index c.pre_now positive within have same := take_eq_take_of_comparable comparable within bound have termSame : termAt c.post.log index = termAt c.pre.log index := by - rw [← termAt_take (n := index) le_rfl, ← same, termAt_take le_rfl] + rw [← termAt_take (n := index) Nat.le.refl, ← same, termAt_take Nat.le.refl] rw [termSame, ← same] exact ⟨log, canon.mono c.suffix_tail, length, take⟩ rcases c.post_log with sub | ⟨entries, log, terms, leader, term, notCandidate⟩ @@ -6291,7 +6301,7 @@ private theorem anchor : Anchor (after :: before :: rest) := by obtain ⟨_, _, rfl⟩ := canon.1.nonempty obtain ⟨anchored, anchoredCanon, length, take⟩ := c.anchors _ suffix (List.cons_ne_nil _ _) source sender index canon.1 positive - (bound.trans (by simp)) + (bound.trans (by simp [Nat.min_le_right])) refine ⟨anchored, ?_, length, ?_⟩ · rw [termAt_take short] exact anchoredCanon.mono (suffix.trans c.suffix_tail) @@ -6319,7 +6329,7 @@ private theorem new_in_elected {leader : NodeID} {state : NodeState} have partSignature := take_signature signature have two : 2 <= state.currentTerm := leaderLed.two_le intro later - induction later using Nat.strong_induction_on with + induction later using Nat.strongRecOn with | _ later ih => intro node log commit elected lt obtain ⟨a, b, r, electSuffix, elect⟩ := elected @@ -6383,7 +6393,7 @@ private theorem new_in_elected {leader : NodeID} {state : NodeState} have leaderCanon : Canon (after :: before :: rest) state.currentTerm state.log := ⟨_, List.suffix_refl _, leader, state, ⟨leaderNow, rfl, leaderRole, leaderLed⟩, rfl⟩ - rcases lt_trichotomy earlier state.currentTerm with lower | rfl | higher + rcases Nat.lt_trichotomy earlier state.currentTerm with lower | rfl | higher · obtain ⟨log'', commit'', elected''⟩ := leaderLed.elected (Nat.lt_of_le_of_lt (committed.signature).2.2 lower) have inLog := c.old_complete (committed.mono innerH) elected'' lower @@ -6554,7 +6564,7 @@ private theorem advance_backed {middle : NodeState} · rw [zero] at step exact .fresh step · exact .chained step backing le within - exact Or.inr ⟨_, _, committed, le_rfl, List.prefix_refl _⟩ + exact Or.inr ⟨_, _, committed, Nat.le.refl, List.prefix_refl _⟩ private theorem pre_backed (agree : c.post.log.take c.pre.commitIndex = c.pre.log.take c.pre.commitIndex) @@ -6737,7 +6747,7 @@ private theorem accept_persist {source : NodeID} {request : AppendEntriesRequest (termAt_le_of_mem (fun entry mem => c.inv.terms c.actor c.pre c.pre_now entry (inPre.subset mem)) _).trans c.term_le rcases Nat.lt_or_ge (termAt part part.length) c.post.currentTerm with lower | upper - · exact Or.inr ⟨c.post.currentTerm, sender.log, lower, le_rfl, + · exact Or.inr ⟨c.post.currentTerm, sender.log, lower, Nat.le.refl, senderCanon.mono c.suffix_tail, inSender⟩ · exfalso obtain ⟨log, logCanon, length, take⟩ := @@ -6745,7 +6755,7 @@ private theorem accept_persist {source : NodeID} {request : AppendEntriesRequest have partEq : c.pre.log.take part.length = part := (List.prefix_iff_eq_take.mp inPre).symm have termEq : termAt c.pre.log part.length = c.post.currentTerm := by - have := termAt_take (log := c.pre.log) (le_refl part.length) + have := termAt_take (log := c.pre.log) (Nat.le_refl part.length) rw [partEq] at this exact this.symm.trans (Nat.le_antisymm termLe upper) rw [termEq] at logCanon @@ -6798,7 +6808,7 @@ private theorem persist : Persist (after :: before :: rest) := by · have termEq : termAt (earlier.log.take index) (earlier.log.take index).length = termAt earlier.log index := by rw [List.length_take, Nat.min_eq_left (signature_bound signature), - termAt_take le_rfl] + termAt_take Nat.le.refl] rw [← termEq] exact c.persist_pre (take_signature signature) inPre · exact Or.inr ⟨later, log, lt, le.trans c.term_le, canon.mono c.suffix_tail, missing⟩ diff --git a/lean/consensus/Consensus/Proofs/Witnesses.lean b/lean/consensus/Consensus/Proofs/Witnesses.lean index e689cb089e00..4a56d4a977b5 100644 --- a/lean/consensus/Consensus/Proofs/Witnesses.lean +++ b/lean/consensus/Consensus/Proofs/Witnesses.lean @@ -9,7 +9,7 @@ import all Mathlib.Data.List.Sort meta import Lean.Elab.Tactic.Basic meta import Lean.Meta.Tactic.AuxLemma -public import Mathlib.Tactic.SplitIfs +public meta import Lean.Elab.Tactic.ElabTerm namespace Consensus.Proofs.Config end Consensus.Proofs.Config @@ -704,7 +704,7 @@ public lemma election_safety_witness (start_initial (by decide) (by decide)) stemRun election_cycle (by simp [electionCycle]) - le_rfl + Nat.le.refl (by rw [List.take_length]; exact stemRun), mem_of_nodeState leftFound, mem_of_nodeState rightFound, @@ -735,7 +735,7 @@ public lemma committed_frontier_is_signature_witness (start_initial (by decide) (by decide)) stemRun single_cycle (by simp [singleCycle]) - le_rfl + Nat.le.refl (by rw [List.take_length]; exact stemRun), member_of_nodeState _, by decide diff --git a/lean/consensus/README.md b/lean/consensus/README.md index 3011a02dfb5b..84bbee017cf1 100644 --- a/lean/consensus/README.md +++ b/lean/consensus/README.md @@ -31,7 +31,6 @@ There are no liveness properties or fairness assumptions. Install Lean via [elan](https://lean-lang.org/install/), then run from this directory: ```sh -lake exe cache get lake build --wfail --fail-fast lake exe check-imports lake lint diff --git a/lean/consensus/lake-manifest.json b/lean/consensus/lake-manifest.json index 402931fc84a4..b8a850631a2e 100644 --- a/lean/consensus/lake-manifest.json +++ b/lean/consensus/lake-manifest.json @@ -14,18 +14,6 @@ "inherited": false, "configFile": "lakefile.toml" }, - { - "url": "https://github.com/leanprover-community/mathlib4.git", - "type": "git", - "subDir": null, - "scope": "", - "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", - "name": "mathlib", - "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", - "inherited": false, - "configFile": "lakefile.lean" - }, { "type": "path", "scope": "", @@ -37,99 +25,13 @@ "configFile": "lakefile.toml" }, { - "url": "https://github.com/leanprover-community/plausible", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", - "name": "plausible", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/LeanSearchClient", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", - "name": "LeanSearchClient", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/import-graph", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", - "name": "importGraph", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/ProofWidgets4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", - "name": "proofwidgets", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/leanprover-community/aesop", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "4a174c490d8707121c4a9290800489f105d85e07", - "name": "aesop", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/quote4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", - "name": "Qq", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/batteries", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", - "name": "batteries", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover/lean4-cli", - "type": "git", - "subDir": null, - "scope": "leanprover", - "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", - "name": "Cli", + "type": "path", + "scope": "", + "name": "mathlib_subset", "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", "inherited": true, + "dir": "../common/../mathlib-subset", + "copy": false, "configFile": "lakefile.toml" } ], diff --git a/lean/consensus/lakefile.toml b/lean/consensus/lakefile.toml index dc9dc470e288..443c7237c28d 100644 --- a/lean/consensus/lakefile.toml +++ b/lean/consensus/lakefile.toml @@ -10,11 +10,6 @@ name = "ccf_common" path = "../common" copy = false -[[require]] -name = "mathlib" -git = "https://github.com/leanprover-community/mathlib4.git" -rev = "v4.35.0" - [[require]] name = "leanfmt" git = "https://github.com/duckki/leanfmt.git" diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 2f091cc6b9b9..58a3ae69c272 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -10,7 +10,6 @@ The Lean version is [pinned](../../lean-toolchain). From `lean/consensus`, build the validator and validate a saved trace: ```sh -lake exe cache get lake build --wfail consensus-replay ./.lake/build/bin/consensus-replay path/to/trace.ndjson ``` diff --git a/lean/consistency/README.md b/lean/consistency/README.md index 4966682c8b5e..1b99f95eefda 100644 --- a/lean/consistency/README.md +++ b/lean/consistency/README.md @@ -53,7 +53,6 @@ Proof modules follow the shared [dependency import contract](../common/README.md Install Lean through [elan](https://lean-lang.org/install/), then run from this package directory: ```sh -lake exe cache get lake check --inadvisably-no-sandbox lake exe check-imports lake lint diff --git a/lean/consistency/consistency/Proofs/Invalidation.lean b/lean/consistency/consistency/Proofs/Invalidation.lean index 34ea7fe99530..83a164b545f5 100644 --- a/lean/consistency/consistency/Proofs/Invalidation.lean +++ b/lean/consistency/consistency/Proofs/Invalidation.lean @@ -568,7 +568,7 @@ private theorem snapshots_reachable {state : State} (found : at? branches branch = some ledger) (last : ledger.getLast? = some entry) (tx : TxContent) : Snapshot branches .ro tx (writes ledger) ⟨entry.view, ledger.length⟩ := by - have snapshot := snapshot_source branches anchored found (at_last last) .ro tx (by simp only [reduceCtorEq, IsEmpty.forall_iff]) + have snapshot := snapshot_source branches anchored found (at_last last) .ro tx (by simp only [reduceCtorEq, forall_false]) simpa only [List.take_length] using snapshot have step_snapshots (before after : State) (action : Action) (anchored : Anchored before.branches) @@ -634,7 +634,8 @@ private theorem anchored_prefix (branches : List (List Entry)) refine ⟨origin, originFound, ?_⟩ have bound : seqno ≤ (ledger.take seqno).length := by simp only [List.length_take, Nat.min_eq_left (at_bounds atEntry).2, Std.le_refl] - simpa only [List.take_take, min_self] using (take_of_prefix isPrefix seqno bound).symm + simpa only [List.take_take, Nat.min_self] + using (take_of_prefix isPrefix seqno bound).symm private theorem frontier_bound (history : List Event) {txid : TxID} (member : txid ∈ statusIDs history .committed) @@ -884,7 +885,7 @@ private theorem committed_views {state : State} refine ⟨ ordered ledger (List.mem_of_getElem? found), by - simp only [List.pairwise_cons, List.not_mem_nil, IsEmpty.forall_iff, implies_true, List.Pairwise.nil, and_self], + simp only [List.pairwise_cons, List.not_mem_nil, forall_false, implies_true, List.Pairwise.nil, and_self], ?_ ⟩ intro left member right singleton @@ -1011,7 +1012,7 @@ private theorem separated_snoc (history : List Event) (event : Event) · exact newInvalid invalid currentInvalid committed oldCommit sameView · rcases (status_ids_snoc _ _ _ _).mp invalidKnown with oldInvalid | currentInvalid · exact newCommit committed currentCommit invalid oldInvalid sameView - · simp_all only [Event.status.injEq, and_true, forall_eq', reduceCtorEq, and_false, IsEmpty.forall_iff, implies_true] + · simp_all only [Event.status.injEq, and_true, forall_eq', reduceCtorEq, and_false, forall_false, implies_true] private theorem separated_invalidate (state : State) (separated : Separated state.history) (anchored : Anchored state.branches) (current : Current state.branches state.history) @@ -1039,7 +1040,7 @@ private theorem separated_invalidate (state : State) (separated : Separated stat have frontier := Nat.le_trans bound (frontier_bound state.history known) simp only [mayInvalidate, last_of_at latestFound, ge_iff_le, actual, invalidView, bne_self_eq_false, Bool.and_false, gt_iff_lt, Nat.not_lt.mpr frontier, decide_false, Bool.false_and, Bool.or_self] apply separated_snoc _ _ separated - · simp only [Event.status.injEq, reduceCtorEq, and_false, IsEmpty.forall_iff, implies_true] + · simp only [Event.status.injEq, reduceCtorEq, and_false, forall_false, implies_true] · intro _ same cases same intro committed known sameView @@ -1064,7 +1065,7 @@ private theorem separated_reachable {state : State} · intro _ same cases same exact allowed - · simp only [Event.status.injEq, reduceCtorEq, and_false, IsEmpty.forall_iff, implies_true] + · simp only [Event.status.injEq, reduceCtorEq, and_false, forall_false, implies_true] have step_separated (before after : State) (action : Action) (separated : Separated before.history) (anchored : Anchored before.branches) (current : Current before.branches before.history) @@ -1301,7 +1302,7 @@ private theorem unique_reachable {state : State} : UniqueWrites (appendEntry state branch ⟨branch, none⟩).branches := by obtain ⟨ledger, found⟩ := active_ledger state active apply unique_modify _ unique _ ledger _ found - simp only [reduceCtorEq, ne_eq, IsEmpty.forall_iff, implies_true] + simp only [reduceCtorEq, ne_eq, forall_false, implies_true] have elected_location (branches : List (List Entry)) {target : List Entry} (targetMember : target ∈ branches) (count : Nat) {ledger : List Entry} (member : ledger ∈ branches ++ [target.take count]) {seqno : Nat} {entry : Entry} @@ -1389,7 +1390,7 @@ private theorem clean_snoc (branches : List (List Entry)) (history : List Event) · exact newInvalid invalid newInvalidated committed oldCommit · rcases (status_ids_snoc _ _ _ _).mp invalidKnown with oldInvalid | newInvalidated · exact newCommit committed newCommitted invalid oldInvalid - · simp_all only [Event.status.injEq, and_true, forall_eq', reduceCtorEq, and_false, IsEmpty.forall_iff, implies_true] + · simp_all only [Event.status.injEq, and_true, forall_eq', reduceCtorEq, and_false, forall_false, implies_true] private theorem origin_entry_in_branch (branches : List (List Entry)) (anchored : Anchored branches) {branch : Nat} {ledger origin : List Entry} @@ -1414,7 +1415,7 @@ private theorem clean_invalidate (state : State) (allowed : mayInvalidate state txid = true) : Clean state.branches (state.history ++ [Event.status txid .invalid]) := by apply clean_snoc _ _ _ clean - · simp only [Event.status.injEq, reduceCtorEq, and_false, IsEmpty.forall_iff, implies_true] + · simp only [Event.status.injEq, reduceCtorEq, and_false, forall_false, implies_true] · intro _ same cases same intro committed known origin originFound entry entryFound bound sameView @@ -1483,7 +1484,7 @@ private theorem clean_reachable {state : State} endpointFound view originFound entryFound bound have denied := allowed invalid known bound simp only [actual, sameView, BEq.rfl, Bool.true_eq_false] at denied - · simp only [Event.status.injEq, reduceCtorEq, and_false, IsEmpty.forall_iff, implies_true] + · simp only [Event.status.injEq, reduceCtorEq, and_false, forall_false, implies_true] have step_clean (before after : State) (action : Action) (clean : Clean before.branches before.history) (anchored : Anchored before.branches) (current : Current before.branches before.history) diff --git a/lean/consistency/consistency/Proofs/Ordering.lean b/lean/consistency/consistency/Proofs/Ordering.lean index 07bf24c1db9d..595c023a3d65 100644 --- a/lean/consistency/consistency/Proofs/Ordering.lean +++ b/lean/consistency/consistency/Proofs/Ordering.lean @@ -348,7 +348,7 @@ private theorem requests_reachable {state : State} constructor · intro index kind tx found rcases lookup_snoc found with ⟨_, old⟩ | ⟨rfl, rfl⟩ - · exact lt_of_lt_of_le (invariant.1 _ _ _ old) monotonic + · exact Nat.lt_of_lt_of_le (invariant.1 _ _ _ old) monotonic · simp only [next_request_snoc, Nat.lt_add_one] · intro left right leftKind rightKind leftTx rightTx first second same rcases lookup_snoc first with ⟨_, oldLeft⟩ | ⟨lastLeft, newLeft⟩ @@ -844,7 +844,7 @@ private theorem snapshots_reachable {state : State} (found : at? branches branch = some ledger) (last : ledger.getLast? = some entry) (tx : TxContent) : Snapshot branches .ro tx (writes ledger) ⟨entry.view, ledger.length⟩ := by - have snapshot := snapshot_source branches anchored found (at_last last) .ro tx (by simp only [reduceCtorEq, IsEmpty.forall_iff]) + have snapshot := snapshot_source branches anchored found (at_last last) .ro tx (by simp only [reduceCtorEq, forall_false]) simpa only [List.take_length] using snapshot have step_snapshots (before after : State) (action : Action) (anchored : Anchored before.branches) @@ -946,7 +946,8 @@ private theorem anchored_prefix (branches : List (List Entry)) refine ⟨origin, originFound, ?_⟩ have bound : seqno ≤ (ledger.take seqno).length := by simp only [List.length_take, Nat.min_eq_left (at_bounds atEntry).2, Std.le_refl] - simpa only [List.take_take, min_self] using (take_of_prefix isPrefix seqno bound).symm + simpa only [List.take_take, Nat.min_self] + using (take_of_prefix isPrefix seqno bound).symm private theorem frontier_bound (history : List Event) {txid : TxID} (member : txid ∈ statusIDs history .committed) @@ -1267,7 +1268,7 @@ private theorem committed_views {state : State} refine ⟨ ordered ledger (List.mem_of_getElem? found), by - simp only [List.pairwise_cons, List.not_mem_nil, IsEmpty.forall_iff, implies_true, List.Pairwise.nil, and_self], + simp only [List.pairwise_cons, List.not_mem_nil, forall_false, implies_true, List.Pairwise.nil, and_self], ?_ ⟩ intro left member right singleton @@ -1541,7 +1542,7 @@ theorem committed_rw_ordered_serializable have sameSeq : left.seqno = right.seqno := Nat.le_antisymm (Nat.le_of_not_lt (fun lt => ordered (Or.inr ⟨sameView.symm, lt⟩))) notLater - exact different (congrArg₂ TxID.mk sameView sameSeq) + exact different (congr (congrArg TxID.mk sameView) sameSeq) have through_entry {α : Type} {xs : List α} {index : Nat} {value : α} (found : at? xs index = some value) : xs.take index = xs.take (index - 1) ++ [value] := by diff --git a/lean/consistency/consistency/Proofs/Witnesses.lean b/lean/consistency/consistency/Proofs/Witnesses.lean index c99370de09ec..2331bec893dd 100644 --- a/lean/consistency/consistency/Proofs/Witnesses.lean +++ b/lean/consistency/consistency/Proofs/Witnesses.lean @@ -289,12 +289,12 @@ private theorem causal_reachable {state : State} (tx : TxContent) : Causal (history ++ [Event.request kind tx]) := by apply causal_snoc history _ causal - simp only [reduceCtorEq, IsEmpty.forall_iff, implies_true] + simp only [reduceCtorEq, forall_false, implies_true] have causal_status (history : List Event) (causal : Causal history) (txid : TxID) (status : Status) : Causal (history ++ [Event.status txid status]) := by apply causal_snoc history _ causal - simp only [reduceCtorEq, IsEmpty.forall_iff, implies_true] + simp only [reduceCtorEq, forall_false, implies_true] have causal_response (history : List Event) (causal : Causal history) {requestIndex : Nat} {kind : TxType} {tx : TxContent} (observed : List TxContent) (txid : TxID) (found : at? history requestIndex = some (.request kind tx)) @@ -391,7 +391,7 @@ private theorem requests_reachable {state : State} constructor · intro index kind tx found rcases lookup_snoc found with ⟨_, old⟩ | ⟨rfl, rfl⟩ - · exact lt_of_lt_of_le (invariant.1 _ _ _ old) monotonic + · exact Nat.lt_of_lt_of_le (invariant.1 _ _ _ old) monotonic · simp only [next_request_snoc, Nat.lt_add_one] · intro left right leftKind rightKind leftTx rightTx first second same rcases lookup_snoc first with ⟨_, oldLeft⟩ | ⟨lastLeft, newLeft⟩ diff --git a/lean/consistency/lake-manifest.json b/lean/consistency/lake-manifest.json index bfa17c9e300e..ef12cdbc6514 100644 --- a/lean/consistency/lake-manifest.json +++ b/lean/consistency/lake-manifest.json @@ -14,18 +14,6 @@ "inherited": false, "configFile": "lakefile.toml" }, - { - "url": "https://github.com/leanprover-community/mathlib4.git", - "type": "git", - "subDir": null, - "scope": "", - "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", - "name": "mathlib", - "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", - "inherited": false, - "configFile": "lakefile.lean" - }, { "type": "path", "scope": "", @@ -37,99 +25,13 @@ "configFile": "lakefile.toml" }, { - "url": "https://github.com/leanprover-community/plausible", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", - "name": "plausible", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/LeanSearchClient", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", - "name": "LeanSearchClient", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/import-graph", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", - "name": "importGraph", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/ProofWidgets4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", - "name": "proofwidgets", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/leanprover-community/aesop", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "4a174c490d8707121c4a9290800489f105d85e07", - "name": "aesop", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/quote4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", - "name": "Qq", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/batteries", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", - "name": "batteries", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover/lean4-cli", - "type": "git", - "subDir": null, - "scope": "leanprover", - "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", - "name": "Cli", + "type": "path", + "scope": "", + "name": "mathlib_subset", "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", "inherited": true, + "dir": "../common/../mathlib-subset", + "copy": false, "configFile": "lakefile.toml" } ], diff --git a/lean/consistency/lakefile.toml b/lean/consistency/lakefile.toml index a528b4d1c88f..bf116aefea5f 100644 --- a/lean/consistency/lakefile.toml +++ b/lean/consistency/lakefile.toml @@ -10,11 +10,6 @@ name = "ccf_common" path = "../common" copy = false -[[require]] -name = "mathlib" -git = "https://github.com/leanprover-community/mathlib4.git" -rev = "v4.35.0" - [[require]] name = "leanfmt" git = "https://github.com/duckki/leanfmt.git" diff --git a/lean/disaster-recovery/DisasterRecovery/Proofs/Deadlock.lean b/lean/disaster-recovery/DisasterRecovery/Proofs/Deadlock.lean index 613cba4182c9..7b2dca2356b3 100644 --- a/lean/disaster-recovery/DisasterRecovery/Proofs/Deadlock.lean +++ b/lean/disaster-recovery/DisasterRecovery/Proofs/Deadlock.lean @@ -3,7 +3,6 @@ module public import DisasterRecovery.Model import all Init.Control.State -import Aesop import Mathlib.Tactic.Lemma @[expose] public section @@ -67,7 +66,7 @@ private theorem advance_ready (config : Local.Config) (state : NodeState) | split at transition all_goals cases gossip : maximumGossip state.gossips <;> cases chosen : state.chosen <;> - simp_all [Ready, Capabilities.record] <;> aesop + simp_all [Ready, Capabilities.record] <;> grind private theorem advance_or_reject_ready (config : Local.Config) (state fallback : NodeState) (source : Location) (reason : String) @@ -113,34 +112,34 @@ private theorem step_ready (config : Local.Config) (state : NodeState) simp [Local.step, phase, StateT.run, Option.bind_eq_some_iff, Option.map_eq_some_iff] at transition all_goals first - | solve | aesop + | solve | grind | cases chosen : state.chosen <;> simp_all [Option.bind_eq_some_iff, Option.map_eq_some_iff, Capabilities.record] - <;> aesop + <;> grind | receiveGossip sender txid validation => cases validation <;> simp only [Local.step] at transition · split at transition · simp [rejected, Capabilities.record] at transition - aesop + grind · exact advance_or_reject_ready config _ state source _ (by simpa [Ready] using ready) ready after effects transition · simp [rejected, Capabilities.record] at transition - aesop + grind | receiveVote sender validation => cases validation <;> simp only [Local.step] at transition · exact advance_or_reject_ready config _ state source _ (by simpa [Ready] using ready) ready after effects transition · simp [rejected, Capabilities.record] at transition - aesop + grind | receiveIAmOpen sender validation => cases validation <;> simp only [Local.step] at transition · cases phase : state.phase <;> simp only [phase] at transition all_goals first | exact advance_or_reject_ready config _ state source _ (by simp [Ready]) ready after effects transition - | simp [rejected, Capabilities.record] at transition; aesop + | simp [rejected, Capabilities.record] at transition; grind · simp [rejected, Capabilities.record] at transition - aesop + grind @[local simp] private theorem effect_lift {S A : Type} (a : Option A) (s : S) diff --git a/lean/disaster-recovery/DisasterRecovery/Proofs/Local.lean b/lean/disaster-recovery/DisasterRecovery/Proofs/Local.lean index dbf488b3ee39..6426de9916b0 100644 --- a/lean/disaster-recovery/DisasterRecovery/Proofs/Local.lean +++ b/lean/disaster-recovery/DisasterRecovery/Proofs/Local.lean @@ -43,9 +43,10 @@ private lemma validStep_run {config : Model.Config} s.action).run {} = some (s.after, s.effects) := by - simpa [MultiNodeTransitionSystem.Protocol.ValidStep, Model.protocol, StateT.run, - Option.bind_eq_some_iff, Option.map_eq_some_iff] - using valid + simp [MultiNodeTransitionSystem.Protocol.ValidStep, Model.protocol, StateT.run, + Option.bind_eq_some_iff, Option.map_eq_some_iff] at valid + obtain ⟨_, _, ⟨_, found, rfl, rfl⟩, stepped⟩ := valid + exact ⟨_, found, stepped⟩ lemma gossip_freezes_after_choice : forall (config : Model.Config), @@ -94,8 +95,7 @@ private lemma quorum_advance_opens (config : Config) (state : NodeState) simp [empty, voteQuorum] at quorum simp [advance, phase, quorum, nonempty] cases timeout <;> - simp [Capabilities.record, advanceTimeoutLane, advanceTimeoutState, - ] + simp [Capabilities.record, advanceTimeoutLane, advanceTimeoutState, and_assoc] lemma quorum_step_opens : forall (config : Model.Config), diff --git a/lean/disaster-recovery/DisasterRecovery/Proofs/Safety.lean b/lean/disaster-recovery/DisasterRecovery/Proofs/Safety.lean index e5f1bdd056ff..f3ba75ebaa72 100644 --- a/lean/disaster-recovery/DisasterRecovery/Proofs/Safety.lean +++ b/lean/disaster-recovery/DisasterRecovery/Proofs/Safety.lean @@ -2,10 +2,7 @@ module public import DisasterRecovery.Properties.Utils public import CCF.Execution -public import Mathlib.Order.Basic public import DisasterRecovery.Model -public import Mathlib.Data.Finset.Card -public import Mathlib.Tactic.CasesM import all Init.Control.State @@ -840,9 +837,9 @@ private lemma valid_path {system : TransitionSystem} {trace : Execution.Trace sy private lemma max_isSome {trace : Stream'.Seq State} {first second : Nat} (firstIn : (trace.get? first).isSome) (secondIn : (trace.get? second).isSome) : (trace.get? (max first second)).isSome := by - rcases le_total first second with le | le - · rwa [max_eq_right le] - · rwa [max_eq_left le] + rcases Nat.le_total first second with le | le + · rwa [Nat.max_eq_right le] + · rwa [Nat.max_eq_left le] /-- Finitely many trace positions all lie at or before one trace position after `start`. -/ private lemma exists_bound {α : Type} {trace : Stream'.Seq State} {P : α -> Nat -> Prop} @@ -855,7 +852,7 @@ private lemma exists_bound {α : Type} {trace : Stream'.Seq State} {P : α -> Na /\ start <= bound /\ forall item, item ∈ items -> exists index, index <= bound /\ P item index := by induction items with - | nil => exact ⟨start, startIn, le_rfl, by simp⟩ + | nil => exact ⟨start, startIn, Nat.le_refl _, by simp⟩ | cons head tail ih => obtain ⟨headIndex, headIn, headHolds⟩ := indexed head (by simp) obtain ⟨bound, boundIn, startLe, bounded⟩ := @@ -863,13 +860,13 @@ private lemma exists_bound {α : Type} {trace : Stream'.Seq State} {P : α -> Na refine ⟨ max headIndex bound, max_isSome headIn boundIn, - startLe.trans (le_max_right _ _), + Nat.le_trans startLe (Nat.le_max_right _ _), fun item member => ?_ ⟩ rcases List.mem_cons.mp member with rfl | member - · exact ⟨headIndex, le_max_left _ _, headHolds⟩ + · exact ⟨headIndex, Nat.le_max_left _ _, headHolds⟩ · obtain ⟨index, le, holds⟩ := bounded item member - exact ⟨index, le.trans (le_max_right _ _), holds⟩ + exact ⟨index, Nat.le_trans le (Nat.le_max_right _ _), holds⟩ end DisasterRecovery.Proofs.Trace @@ -2875,30 +2872,15 @@ private lemma quorum_lists_intersect (firstQuorum : expected.length / 2 + 1 <= first.length) (secondQuorum : expected.length / 2 + 1 <= second.length) : exists value, value ∈ first /\ value ∈ second := by - classical - by_contra noShared - push Not at noShared - have disjoint : Disjoint first.toFinset second.toFinset := - Finset.disjoint_left.mpr (by - intro value firstMember secondMember - exact noShared value - (List.mem_toFinset.mp firstMember) - (List.mem_toFinset.mp secondMember)) - have unionSubset : - first.toFinset ∪ second.toFinset ⊆ expected.toFinset := by - intro value membership - rw [Finset.mem_union] at membership - rw [List.mem_toFinset] - exact membership.elim - (fun member => - firstSubset value (List.mem_toFinset.mp member)) - (fun member => - secondSubset value (List.mem_toFinset.mp member)) - have unionCard := Finset.card_le_card unionSubset - rw [Finset.card_union_of_disjoint disjoint, - List.toFinset_card_of_nodup firstNodup, - List.toFinset_card_of_nodup secondNodup] at unionCard - have expectedCard := List.toFinset_card_le expected + apply Classical.byContradiction + intro noShared + have nodup : (first ++ second).Nodup := + List.nodup_append.mpr ⟨firstNodup, secondNodup, + fun value firstMember _ secondMember same => + noShared ⟨value, firstMember, same ▸ secondMember⟩⟩ + have bound := nodup.length_le_of_subset (l₂ := expected) fun value member => + (List.mem_append.mp member).elim (firstSubset value) (secondSubset value) + rw [List.length_append] at bound omega private lemma quorum_opener_unique @@ -3008,9 +2990,10 @@ private lemma validStep_run {config : Model.Config} s.action).run {} = some (s.after, s.effects) := by - simpa [MultiNodeTransitionSystem.Protocol.ValidStep, Model.protocol, StateT.run, - Option.bind_eq_some_iff, Option.map_eq_some_iff] - using valid + simp [MultiNodeTransitionSystem.Protocol.ValidStep, Model.protocol, StateT.run, + Option.bind_eq_some_iff, Option.map_eq_some_iff] at valid + obtain ⟨_, _, ⟨_, found, rfl, rfl⟩, stepped⟩ := valid + exact ⟨_, found, stepped⟩ end DisasterRecovery.Proofs.Local @@ -3555,18 +3538,15 @@ private lemma up_to_date_with_quorum_of_voters exact List.mem_of_find?_eq_some found let eligible := config.recovered.filter fun (_, voter) => decide (Properties.LogUpToDate candidate voter) - have subset : voters.toFinset ⊆ (eligible.map Prod.fst).toFinset := by + have subset : voters ⊆ eligible.map Prod.fst := by intro voter member - obtain ⟨txid, recovered, earlier⟩ := fresh voter (List.mem_toFinset.mp member) - apply List.mem_toFinset.mpr + obtain ⟨txid, recovered, earlier⟩ := fresh voter member apply List.mem_map.mpr refine ⟨(voter, txid), List.mem_filter.mpr ⟨mem_of_recoveredTxID recovered, ?_⟩, rfl⟩ exact decide_eq_true earlier - have count := Finset.card_le_card subset - rw [List.toFinset_card_of_nodup nodup] at count - have bound := List.toFinset_card_le (eligible.map Prod.fst) - rw [List.length_map] at bound - exact threshold.trans (count.trans bound) + have count := nodup.length_le_of_subset subset + rw [List.length_map] at count + exact Nat.le_trans threshold count end DisasterRecovery.Proofs.Committed @@ -3614,7 +3594,7 @@ private lemma step_lifts (config : Model.Config) have member := List.mem_of_find?_eq_some selected have key : entry.1 = node := beq_iff_eq.mp (List.find?_some (p := fun entry : Location × NodeState => entry.1 == node) selected) - conv_rhs => rw [← List.map_id nodes] + conv => rhs; rw [← List.map_id nodes] apply List.map_congr_left intro other membership split @@ -3778,7 +3758,7 @@ private theorem model_initial_lifts (config : Model.Config) (state : Model.State (state.nodes.map Prod.fst).map (fun node => (node, initialNode node)) = state.nodes := by rw [List.map_map] - conv_rhs => rw [← List.map_id state.nodes] + conv => rhs; rw [← List.map_id state.nodes] apply List.map_congr_left intro entry member have initialized := nodes entry member @@ -4759,12 +4739,12 @@ lemma full_gossip_preserves_commit obtain ⟨voter, voted⟩ := Observed.reachable_opening_has_vote openingReachable _ openingPresent opening obtain ⟨final, finalMember, evolves⟩ := - trace_node_final linked (le_max_right _ _) openFound.symm present + trace_node_final linked (Nat.le_max_right _ _) openFound.symm present have invariant := reachable_quorum_invariant linked.reachable obtain ⟨envelope, sent, _, target, vote⟩ := invariant.votesSent _ finalMember voter (evolves.votes voted) have complete := - sent_vote_full_gossip linked (le_max_left _ _) gossipFound.symm full sent vote + sent_vote_full_gossip linked (Nat.le_max_left _ _) gossipFound.symm full sent vote obtain ⟨selected, txid, choice, maximum⟩ := invariant.sentVotesSelected envelope sent vote have wf := reachable_well_formed linked.reachable have selectedEq : selected = envelope.target := @@ -4879,12 +4859,8 @@ private lemma quorum_notification_final_votes {config : Model.Config} have nodup := (reachable_quorum_invariant openingReachable).votesNodup _ openingPresent have threshold := Observed.reachable_quorum_thresholds openingReachable _ openingPresent opened obtain ⟨final, finalMember, evolves⟩ := trace_node_final linked le inTrace present - have subset : current.votes.toFinset ⊆ final.votes.toFinset := by - intro voter member - exact List.mem_toFinset.mpr (evolves.votes (List.mem_toFinset.mp member)) - have count := Finset.card_le_card subset - rw [List.toFinset_card_of_nodup nodup] at count - exact ⟨final, finalMember, threshold.trans (count.trans (List.toFinset_card_le _))⟩ + have count := nodup.length_le_of_subset fun _ member => evolves.votes member + exact ⟨final, finalMember, Nat.le_trans threshold count⟩ end DisasterRecovery.Proofs.Gossip @@ -4906,9 +4882,9 @@ lemma quorum_opener_unique (Trace.max_isSome (Option.isSome_iff_exists.mpr ⟨_, firstFound⟩) (Option.isSome_iff_exists.mpr ⟨_, secondFound⟩)) obtain ⟨firstState, firstMember, firstThreshold⟩ := - Gossip.quorum_notification_final_votes linked (le_max_left _ _) first + Gossip.quorum_notification_final_votes linked (Nat.le_max_left _ _) first obtain ⟨secondState, secondMember, secondThreshold⟩ := - Gossip.quorum_notification_final_votes linked (le_max_right _ _) second + Gossip.quorum_notification_final_votes linked (Nat.le_max_right _ _) second exact Observed.current_quorum_unique_of_thresholds linked.reachable (firstOpener, firstState) (secondOpener, secondState) firstMember secondMember firstThreshold secondThreshold diff --git a/lean/disaster-recovery/README.md b/lean/disaster-recovery/README.md index 39c2191a93fa..b6bf80f6adc2 100644 --- a/lean/disaster-recovery/README.md +++ b/lean/disaster-recovery/README.md @@ -81,12 +81,10 @@ Eventual-progress and fairness properties are out of scope. Run the following commands from this directory: ```console -lake exe cache get lake build --wfail --fail-fast lake exe check-imports lake build CCF lake lint -lake exe runLinter --no-build CCF DisasterRecovery replayer.Main ./replayer/check-fixtures.sh lake check --inadvisably-no-sandbox ``` @@ -103,7 +101,7 @@ Lean's internal-module and collection-variable naming conventions, and its debug The package also sets `autoImplicit = false`, requiring declaration headers to bind their parameters explicitly rather than silently introducing undeclared names. This applies to ordinary Lake builds as well as CI. -The model, proofs, tests, and replayer use Lean's module system, as required by the Mathlib dependency. +The model, proofs, tests, and replayer use Lean's module system, as required by the vendored Mathlib subset. The properties entrypoint publicly imports the model types and property helpers used by its statements, while its implementation imports remain private. Proof modules and the assembled root follow the shared [dependency import contract](../common/README.md#dependency-imports); import additional Mathlib facilities explicitly rather than relying on incidental reexports. `@[expose] public section` keeps definitions used by cross-module proofs transparent; runtime-only helpers remain private. @@ -111,8 +109,6 @@ Proof modules and the assembled root follow the shared [dependency import contra Proofs that evaluate upstream implementations use narrowly scoped `import all` directives to retain access to those definitions. -`runLinter` uses Mathlib's declaration-lint driver, including the slow checks, over every module imported by `CCF.lean`, `DisasterRecovery.lean`, and `replayer.Main`. -It lints our declarations rather than dependencies, and findings fail the command. The package's default targets are the complete library and the replayer executable. Canonical scenario and state-enumeration checks run with `#eval` when `Tests/CanonicalTests.lean` is built, and assertion failures fail the build. Their runner is namespaced, leaving the replayer as the only `main` entrypoint so both targets can be checked together. @@ -130,12 +126,12 @@ Additional bundled checkers are not enabled. The [Lean workflow](../../.github/workflows/lean.yml) checks `consensus`, `common`, `consistency`, `disaster-recovery`, and `kv` in one matrix with fail-fast disabled, using the same [package workflow](../../.github/workflows/lean-package.yml). Each invocation has its own checkout and writable build directories, including `common/.lake`, because the packages reference `../common` without copying it. -Mathlib cache setup precedes kernel and axiom checking, which precedes import/architecture checking, formatting, linting, and package-specific fixtures. +Kernel and axiom checking precedes import/architecture checking, formatting, linting, and package-specific fixtures. Common receives its own kernel, import, and lint checks; the disaster-recovery formatting selector also covers common and tracked Lean files outside `lean/`. Recovery schema validation, positive/negative replay fixtures, and viewer dump generation run in the disaster-recovery job. Native CCF consensus and KV captures run independently of package checking. -The [CCF consensus replay job](../consensus/replay/README.md#ci-captures-and-replay) and the KV replay job each wait only for their corresponding native captures, restore Mathlib caches, and build their own replay executable without depending on the package matrix. +The [CCF consensus replay job](../consensus/replay/README.md#ci-captures-and-replay) and the KV replay job each wait only for their corresponding native captures and build their own replay executable without depending on the package matrix. The final check retains the name `Lean models and proofs` and requires all package checks, captures, and replay to succeed. Failed, cancelled, skipped, or missing prerequisites cannot yield a successful gate; a cancelled workflow may cancel the gate itself. The gate also rejects package inventory drift. @@ -149,7 +145,7 @@ To update a tool dependency without changing the toolchain, run `lake update --k ## Formatting -Install Lean via [elan](https://lean-lang.org/install/) and run `lake exe cache get` from this directory before the first formatting check. +Install Lean via [elan](https://lean-lang.org/install/) before the first formatting check. From the repository root, check every tracked `.lean` file: ```console @@ -164,5 +160,5 @@ scripts/lean-format-checks.sh -f The script builds the model's imported modules and runs the pinned leanfmt dependency. The Lean CI workflow runs the same check after the proof checks. -Files outside `lean/` are included; untracked files and downloaded dependencies are excluded. +Files outside `lean/` are included; untracked files, downloaded dependencies and the vendored Mathlib subset are excluded. Add new Lean files to Git before running the check. diff --git a/lean/disaster-recovery/lake-manifest.json b/lean/disaster-recovery/lake-manifest.json index bfb8d6162ece..15090075e675 100644 --- a/lean/disaster-recovery/lake-manifest.json +++ b/lean/disaster-recovery/lake-manifest.json @@ -14,18 +14,6 @@ "inherited": false, "configFile": "lakefile.toml" }, - { - "url": "https://github.com/leanprover-community/mathlib4.git", - "type": "git", - "subDir": null, - "scope": "", - "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", - "name": "mathlib", - "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", - "inherited": false, - "configFile": "lakefile.lean" - }, { "type": "path", "scope": "", @@ -37,99 +25,13 @@ "configFile": "lakefile.toml" }, { - "url": "https://github.com/leanprover-community/plausible", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", - "name": "plausible", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/LeanSearchClient", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", - "name": "LeanSearchClient", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/import-graph", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", - "name": "importGraph", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/ProofWidgets4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", - "name": "proofwidgets", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/leanprover-community/aesop", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "4a174c490d8707121c4a9290800489f105d85e07", - "name": "aesop", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/quote4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", - "name": "Qq", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/batteries", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", - "name": "batteries", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover/lean4-cli", - "type": "git", - "subDir": null, - "scope": "leanprover", - "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", - "name": "Cli", + "type": "path", + "scope": "", + "name": "mathlib_subset", "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", "inherited": true, + "dir": "../common/../mathlib-subset", + "copy": false, "configFile": "lakefile.toml" } ], diff --git a/lean/disaster-recovery/lakefile.toml b/lean/disaster-recovery/lakefile.toml index 4629b84dbd4b..e6316b5c059c 100644 --- a/lean/disaster-recovery/lakefile.toml +++ b/lean/disaster-recovery/lakefile.toml @@ -2,8 +2,6 @@ name = "disaster_recovery" version = "0.1.0" moreLeanArgs = ["-DwarningAsError=true"] builtinLint = true -lintDriver = "batteries/runLinter" -lintDriverArgs = ["--no-build", "CCF", "DisasterRecovery", "replayer.Main"] defaultTargets = [ "DisasterRecovery", "disaster-recovery-replay", @@ -23,11 +21,6 @@ name = "ccf_common" path = "../common" copy = false -[[require]] -name = "mathlib" -git = "https://github.com/leanprover-community/mathlib4.git" -rev = "v4.35.0" - [[require]] name = "leanfmt" git = "https://github.com/duckki/leanfmt.git" diff --git a/lean/kv/README.md b/lean/kv/README.md index 0977a08f1660..3329ef29c6a8 100644 --- a/lean/kv/README.md +++ b/lean/kv/README.md @@ -202,12 +202,10 @@ Rejections remain diagnostic evidence and must not be hidden by reseeding state Run the following commands from this directory: ```console -lake exe cache get lake build --wfail --fail-fast lake exe check-imports lake build CCF lake lint -lake exe runLinter --no-build CCF Kv replayer.Main lake check --inadvisably-no-sandbox ./replayer/check-fixtures.sh ``` diff --git a/lean/kv/lake-manifest.json b/lean/kv/lake-manifest.json index 2c579ab5d978..deaf74fb2a2e 100644 --- a/lean/kv/lake-manifest.json +++ b/lean/kv/lake-manifest.json @@ -14,18 +14,6 @@ "inherited": false, "configFile": "lakefile.toml" }, - { - "url": "https://github.com/leanprover-community/mathlib4.git", - "type": "git", - "subDir": null, - "scope": "", - "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", - "name": "mathlib", - "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", - "inherited": false, - "configFile": "lakefile.lean" - }, { "type": "path", "scope": "", @@ -37,99 +25,13 @@ "configFile": "lakefile.toml" }, { - "url": "https://github.com/leanprover-community/plausible", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", - "name": "plausible", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/LeanSearchClient", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", - "name": "LeanSearchClient", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/import-graph", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", - "name": "importGraph", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/ProofWidgets4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", - "name": "proofwidgets", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/leanprover-community/aesop", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "4a174c490d8707121c4a9290800489f105d85e07", - "name": "aesop", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/quote4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", - "name": "Qq", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/batteries", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", - "name": "batteries", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover/lean4-cli", - "type": "git", - "subDir": null, - "scope": "leanprover", - "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", - "name": "Cli", + "type": "path", + "scope": "", + "name": "mathlib_subset", "manifestFile": "lake-manifest.json", - "inputRev": "v4.35.0", "inherited": true, + "dir": "../common/../mathlib-subset", + "copy": false, "configFile": "lakefile.toml" } ], diff --git a/lean/kv/lakefile.toml b/lean/kv/lakefile.toml index dbcf4c29aea3..d7c6bd7cb07b 100644 --- a/lean/kv/lakefile.toml +++ b/lean/kv/lakefile.toml @@ -2,8 +2,6 @@ name = "kv" version = "0.1.0" moreLeanArgs = ["-DwarningAsError=true"] builtinLint = true -lintDriver = "batteries/runLinter" -lintDriverArgs = ["--no-build", "CCF", "Kv", "replayer.Main"] defaultTargets = [ "Kv", "kv-replay", @@ -23,11 +21,6 @@ name = "ccf_common" path = "../common" copy = false -[[require]] -name = "mathlib" -git = "https://github.com/leanprover-community/mathlib4.git" -rev = "v4.35.0" - [[require]] name = "leanfmt" git = "https://github.com/duckki/leanfmt.git"