import Lean/-!# My own check scriptThis script repeats the logic of the standalone comparator program of`leanprover/comparator` at commit `865edc14486c3388e9225daa971da8e157488c3e`(files `Main.lean`, `Comparator/Compare.lean`, `Comparator/Axioms.lean`).It loads two module environments in one process and it compares the constants.Usage: `lake env lean --run Check/Check.lean CHALLENGE_MODULE SOLUTION_MODULE THEOREM [THEOREM ...]`The file `Check/Check.lean` of my sunflower check (desk task 428) is the origin.The files `Check/Check.lean` of my Hirsch check and of my matrix exponent checkare the same script. This file is that script with a change of this comment only.-/open Leanderiving instance BEq for Lean.QuotKindderiving instance BEq for Lean.QuotValderiving instance BEq for Lean.InductiveValderiving instance BEq for Lean.ConstantInfonamespace Check/-- Same as `Comparator.runForUsedConsts`. -/def runForUsedConsts [Monad m] (info : ConstantInfo) (f : Name → m Unit) : m Unit := doinfo.type.getUsedConstants.forM ff info.nameif let some val := info.value? (allowOpaque := true) thenval.getUsedConstants.forM fmatch info with| .axiomInfo .. | .quotInfo .. | .defnInfo .. | .thmInfo .. | .opaqueInfo .. => return ()| .inductInfo info =>info.ctors.forM finfo.all.forM f| .ctorInfo info =>f info.induct| .recInfo info =>info.rules.forM fun rule => dof rule.ctorrule.rhs.getUsedConstants.forM f/-- The same names as `runForUsedConsts`, as an array without a monad. -/def usedNames (info : ConstantInfo) : Array Name :=let base := info.type.getUsedConstants.push info.namelet base :=match info.value? (allowOpaque := true) with| some v => base ++ v.getUsedConstants| none => basematch info with| .inductInfo i => base ++ (i.ctors ++ i.all).toArray| .ctorInfo c => base.push c.induct| .recInfo r => base ++ (r.rules.map (fun rule => rule.rhs.getUsedConstants.push rule.ctor)).toArray.flatten| _ => base/-- Same list as `Comparator.primitiveTargets`. -/def primitiveTargets : Array Name :=#[``Nat.add, ``Nat.sub, ``Nat.mul, ``Nat.pow, ``Nat.gcd, ``Nat.div, ``Nat.mod, ``Nat.beq, ``Nat.ble,``Nat.land, ``Nat.lor, ``Nat.xor, ``Nat.shiftLeft, ``Nat.shiftRight, ``String.ofList, ``Char.ofNat,``List, ``eagerReduce, ``Nat, ``String, ``String.mk, ``Char, ``optParam, ``autoParam, ``semiOutParam,``outParam]def legalAxioms : Array Name := #[``propext, ``Quot.sound, ``Classical.choice]/-- Name of the module that declares a constant. -/def moduleOf (env : Environment) (n : Name) : Name :=match env.getModuleIdxFor? n with| some idx => env.header.moduleNames[idx]!| none => .anonymous/-- Group name of a module: `Mathlib`, `OAI`, `Init`, other. -/def originOf (module : Name) : String :=let root := module.getRoot.toStringmatch root with| "OAI" | "Mathlib" | "Init" | "Lean" | "Std" | "Batteries" | "Qq" | "Aesop" | "Lemmata"| "FixedPointTheorems" | "ProofWidgets" | "ImportGraph" | "Plausible" | "LeanSearchClient" | "Cli"| "ComparatorChallenges" =>root| _ => "other:" ++ rootdef kindOf : ConstantInfo → String| .axiomInfo _ => "axiom"| .defnInfo _ => "definition"| .thmInfo _ => "theorem"| .opaqueInfo _ => "opaque"| .quotInfo _ => "quot"| .inductInfo _ => "inductive"| .ctorInfo _ => "constructor"| .recInfo _ => "recursor"def countBy (env : Environment) (map : Std.HashMap Name ConstantInfo) :Std.HashMap String Nat × Std.HashMap String Nat × NameSet := Id.run dolet mut perKind : Std.HashMap String Nat := {}let mut perOrigin : Std.HashMap String Nat := {}let mut ownModules : NameSet := {}for (n, ci) in map.toList doperKind := perKind.alter (kindOf ci) (fun c => some (c.getD 0 + 1))let mod := moduleOf env nlet origin := originOf modperOrigin := perOrigin.alter origin (fun c => some (c.getD 0 + 1))if origin == "OAI" || origin == "Lemmata" || origin == "FixedPointTheorems" thenownModules := ownModules.insert mod(perKind, perOrigin, ownModules)def sorted (m : Std.HashMap String Nat) : List (String × Nat) :=(m.toList.mergeSort (fun a b => a.1 < b.1))/-! ### Part 1: the statement match, same logic as `Comparator.compareAt` -/namespace Comparestructure Context wherechallenge : Environmentsolution : EnvironmentdefinitionTargets : NameSettheoremTargets : NameSetstructure State whereworklist : Array Name := #[]checked : NameSet := {}compared : Nat := 0perOrigin : Std.HashMap String Nat := {}abbrev M := ReaderT Context (StateRefT State IO)def addWorklist (n : Name) : M Unit := doif !(← get).checked.contains n thenmodify fun s => { s with worklist := s.worklist.push n }def addRelevantConsts (info : ConstantInfo) : M Unit := dorunForUsedConsts info addWorklist/-- Mark a constant as checked and count it. -/def record (origin : String) (target : Name) (s : State) : State :={ s with checked := s.checked.insert target, compared := s.compared + 1, perOrigin := s.perOrigin.alter origin (fun c => some ((c.getD 0) + 1)) }partial def loop : M Unit := doif (← get).worklist.isEmpty thenreturn ()let target := (← get).worklist.back!modify fun s => { s with worklist := s.worklist.pop }if (← get).checked.contains target thenloopelselet some challengeConst := (← read).challenge.find? target| throw <| IO.userError s!"Const not found in challenge '{target}'"let some solutionConst := (← read).solution.find? target| throw <| IO.userError s!"Const not found in solution '{target}'"if (← read).definitionTargets.contains solutionConst.name|| (← read).theoremTargets.contains solutionConst.name thensolutionConst.type.getUsedConstants.forM addWorklistelseif challengeConst != solutionConst thenthrow <| IO.userError s!"Const does not match between challenge and target '{target}'"addRelevantConsts solutionConstlet origin := originOf (moduleOf (← read).solution target)modify (record origin target)loopend Comparedef compareAt (challenge solution : Environment) (theoremTargets definitionTargets : Array Name) :IO (Compare.State × Array Name) := dolet mut worklist := primitiveTargetslet mut used : Array Name := #[]for target in theoremTargets dolet some challengeConst := challenge.find? target| throw <| IO.userError s!"Const not found in challenge: '{target}'"let some solutionConst := solution.find? target| throw <| IO.userError s!"Const not found in solution: '{target}'"let (challengeVal, solutionVal) ←match challengeConst, solutionConst with| .thmInfo cc, .thmInfo sc => pure (cc.toConstantVal, sc.toConstantVal)| .axiomInfo cc, .axiomInfo sc => pure (cc.toConstantVal, sc.toConstantVal)| _, _ => throw <| IO.userError s!"Challenge and solution constant kind don't match: '{target}'"IO.println s!"--- {target}"IO.println s!"kind in challenge: {kindOf challengeConst}; kind in solution: {kindOf solutionConst}"IO.println s!"level parameters: {challengeVal.levelParams}"if challengeVal != solutionVal thenIO.println "challenge type:"IO.println (toString challengeVal.type)IO.println "solution type:"IO.println (toString solutionVal.type)throw <| IO.userError s!"Challenge and solution theorem statement do not match: '{target}'"IO.println s!"theorem record is the same in both environments: {target}"IO.println " constants that the statement uses (name; module in challenge; module in solution):"let statementUsed := challengeVal.type.getUsedConstantsfor n in statementUsed doIO.println s!" {n}; {moduleOf challenge n}; {moduleOf solution n}"if !used.contains n thenused := used.push nworklist := worklist ++ statementUsedlet ctx : Compare.Context :={ challenge := challenge, solution := solution,definitionTargets := NameSet.ofArray definitionTargets,theoremTargets := NameSet.ofArray theoremTargets }let initialState : Compare.State := { worklist := worklist, checked := {} }let (_, st) ← StateRefT'.run (ReaderT.run Compare.loop ctx) initialStatereturn (st, used)/-! ### Part 2: the axioms, same logic as `Comparator.checkAxioms` -/def closure (env : Environment) (roots : Array Name) : IO (Std.HashMap Name ConstantInfo) := dolet mut map : Std.HashMap Name ConstantInfo := {}let mut work := rootswhile work.size > 0 dolet name := work[work.size - 1]!work := work.popif map.contains name thencontinuelet some ci := env.find? name| throw <| IO.userError s!"Constant not found: '{name}'"map := map.insert name cifor n in usedNames ci doif !map.contains n thenwork := work.push nreturn mapdef checkAxioms (env : Environment) (roots : Array Name) (legal : Array Name) :IO (Std.HashMap Name ConstantInfo × Array Name) := dolet map ← closure env rootslet mut axioms : Array Name := #[]for (_n, ci) in map.toList doif let .axiomInfo info := ci thenif !legal.contains info.name thenthrow <| IO.userError s!"Illegal axiom detected: '{info.name}'"if !axioms.contains info.name thenaxioms := axioms.push info.namereturn (map, axioms)/-! ### Part 3: the kernel replay, same logic as `Comparator.runBuiltinKernel` -/def replaySolution (origConstMap : Std.HashMap Name ConstantInfo) : IO Unit := dolet env ← Lean.mkEmptyEnvironmentlet mut kernelEnv := env.toKernelEnvIO.println s!"initial kernel environment has {kernelEnv.constants.toList.length} constants"IO.println s!" Nat.add is in it: {kernelEnv.find? ``Nat.add |>.isSome}; Nat is in it: {kernelEnv.find? ``Nat |>.isSome}; Quot is in it: {kernelEnv.find? ``Quot |>.isSome}"let quotTargets : Array Name := #[`Quot.mk, `Quot.lift, `Quot.ind]let kernelConstMap := quotTargets.foldl (init := origConstMap) (·.erase ·)trykernelEnv ← Lean.Kernel.Environment.replay kernelConstMap kernelEnvIO.println "Lean default kernel accepts the solution"catch e =>IO.println "Lean default kernel rejects the solution"throw elet verifyTargets := #[`Quot] ++ quotTargetsfor quotTarget in verifyTargets doif let some info := origConstMap[quotTarget]? thenlet some info' := kernelEnv.find? quotTarget| throw <| IO.userError s!"Could not find quotient constant in final kernel env: {quotTarget}"if info != info' thenthrow <| IO.userError s!"Quotient constant mismatch on: {quotTarget}"IO.println "quotient constants agree"-- Extra check of mine: each constant of the closure is in the kernel environment with the same record.let mut different : Array Name := #[]let mut unsafeOrPartial : Array Name := #[]let mut replayed : Nat := 0for (n, ci) in origConstMap.toList doif ci.isUnsafe || ci.isPartial thenunsafeOrPartial := unsafeOrPartial.push nelsereplayed := replayed + 1if kernelEnv.find? n != some ci thendifferent := different.push nIO.println s!"closure size: {origConstMap.size}; of which unsafe or partial: {unsafeOrPartial.size}; constants different after the replay: {different.size}"if unsafeOrPartial.size > 0 thenIO.println s!" unsafe or partial: {unsafeOrPartial.take 20}"if different.size > 0 thenIO.println s!" different: {different.take 20}"throw <| IO.userError "Some constants are different after the replay"/-! ### Main -/def main (args : List String) : IO Unit := dolet challengeMod :: solutionMod :: targets := args| throw <| IO.userError "usage: Check.lean CHALLENGE_MODULE SOLUTION_MODULE THEOREM [THEOREM ...]"let theoremTargets := targets.toArray.map (·.toName)let definitionTargets : Array Name := #[]let t0 ← IO.monoMsNowlet challenge ← importModules #[{ module := challengeMod.toName }] {}let t1 ← IO.monoMsNowlet solution ← importModules #[{ module := solutionMod.toName }] {}let t2 ← IO.monoMsNowIO.println s!"challenge module {challengeMod}: {challenge.constants.toList.length} constants, {challenge.header.moduleNames.size} imported modules, {t1 - t0} ms"IO.println s!"solution module {solutionMod}: {solution.constants.toList.length} constants, {solution.header.moduleNames.size} imported modules, {t2 - t1} ms"IO.println s!"theorem targets ({theoremTargets.size}): {theoremTargets.toList}"IO.println "===== part 1: statement match ====="let (st, used) ← compareAt challenge solution theoremTargets definitionTargetsIO.println s!"the {theoremTargets.size} statements use {used.size} different constants; compared in the closure: {st.compared} constants; all records are the same"IO.println s!" by library: {sorted st.perOrigin}"IO.println "===== part 2: axioms ====="let (map, axioms) ← checkAxioms solution (theoremTargets ++ legalAxioms ++ primitiveTargets) legalAxiomsIO.println s!"axioms in the closure of the {theoremTargets.size} theorems: {axioms.toList}"let (perKind, perOrigin, ownModules) := countBy solution mapIO.println s!"closure of the {theoremTargets.size} theorems in the solution environment: {map.size} constants"IO.println s!" by kind: {sorted perKind}"IO.println s!" by library: {sorted perOrigin}"IO.println s!" modules of the claimant library that declare at least one of them: {ownModules.size}"IO.println "===== part 3: kernel replay ====="let t3 ← IO.monoMsNowreplaySolution maplet t4 ← IO.monoMsNowIO.println s!"replay time: {t4 - t3} ms"IO.println "ALL THREE CHECKS PASS"end Check/-- The program needs `main` in the root namespace for `lean --run`. -/def main : List String → IO Unit := Check.main