import Lean /-! # My own check script This 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 file `Check/Check.lean` of my Hirsch check is the same script. This file is that script with a change of this comment only. -/ open Lean deriving instance BEq for Lean.QuotKind deriving instance BEq for Lean.QuotVal deriving instance BEq for Lean.InductiveVal deriving instance BEq for Lean.ConstantInfo namespace Check /-- Same as `Comparator.runForUsedConsts`. -/ def runForUsedConsts [Monad m] (info : ConstantInfo) (f : Name → m Unit) : m Unit := do info.type.getUsedConstants.forM f f info.name if let some val := info.value? (allowOpaque := true) then val.getUsedConstants.forM f match info with | .axiomInfo .. | .quotInfo .. | .defnInfo .. | .thmInfo .. | .opaqueInfo .. => return () | .inductInfo info => info.ctors.forM f info.all.forM f | .ctorInfo info => f info.induct | .recInfo info => info.rules.forM fun rule => do f rule.ctor rule.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.name let base := match info.value? (allowOpaque := true) with | some v => base ++ v.getUsedConstants | none => base match 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.toString match root with | "OAI" | "Mathlib" | "Init" | "Lean" | "Std" | "Batteries" | "Qq" | "Aesop" | "Lemmata" | "FixedPointTheorems" | "ProofWidgets" | "ImportGraph" | "Plausible" | "LeanSearchClient" | "Cli" | "ComparatorChallenges" => root | _ => "other:" ++ root def 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 do let mut perKind : Std.HashMap String Nat := {} let mut perOrigin : Std.HashMap String Nat := {} let mut ownModules : NameSet := {} for (n, ci) in map.toList do perKind := perKind.alter (kindOf ci) (fun c => some (c.getD 0 + 1)) let mod := moduleOf env n let origin := originOf mod perOrigin := perOrigin.alter origin (fun c => some (c.getD 0 + 1)) if origin == "OAI" || origin == "Lemmata" || origin == "FixedPointTheorems" then ownModules := 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 Compare structure Context where challenge : Environment solution : Environment definitionTargets : NameSet theoremTargets : NameSet structure State where worklist : Array Name := #[] checked : NameSet := {} compared : Nat := 0 perOrigin : Std.HashMap String Nat := {} abbrev M := ReaderT Context (StateRefT State IO) def addWorklist (n : Name) : M Unit := do if !(← get).checked.contains n then modify fun s => { s with worklist := s.worklist.push n } def addRelevantConsts (info : ConstantInfo) : M Unit := do runForUsedConsts 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 := do if (← get).worklist.isEmpty then return () let target := (← get).worklist.back! modify fun s => { s with worklist := s.worklist.pop } if (← get).checked.contains target then loop else let 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 then solutionConst.type.getUsedConstants.forM addWorklist else if challengeConst != solutionConst then throw <| IO.userError s!"Const does not match between challenge and target '{target}'" addRelevantConsts solutionConst let origin := originOf (moduleOf (← read).solution target) modify (record origin target) loop end Compare def compareAt (challenge solution : Environment) (theoremTargets definitionTargets : Array Name) : IO (Compare.State × Array Name) := do let mut worklist := primitiveTargets let mut used : Array Name := #[] for target in theoremTargets do let 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 then IO.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.getUsedConstants for n in statementUsed do IO.println s!" {n}; {moduleOf challenge n}; {moduleOf solution n}" if !used.contains n then used := used.push n worklist := worklist ++ statementUsed let 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) initialState return (st, used) /-! ### Part 2: the axioms, same logic as `Comparator.checkAxioms` -/ def closure (env : Environment) (roots : Array Name) : IO (Std.HashMap Name ConstantInfo) := do let mut map : Std.HashMap Name ConstantInfo := {} let mut work := roots while work.size > 0 do let name := work[work.size - 1]! work := work.pop if map.contains name then continue let some ci := env.find? name | throw <| IO.userError s!"Constant not found: '{name}'" map := map.insert name ci for n in usedNames ci do if !map.contains n then work := work.push n return map def checkAxioms (env : Environment) (roots : Array Name) (legal : Array Name) : IO (Std.HashMap Name ConstantInfo × Array Name) := do let map ← closure env roots let mut axioms : Array Name := #[] for (_n, ci) in map.toList do if let .axiomInfo info := ci then if !legal.contains info.name then throw <| IO.userError s!"Illegal axiom detected: '{info.name}'" if !axioms.contains info.name then axioms := axioms.push info.name return (map, axioms) /-! ### Part 3: the kernel replay, same logic as `Comparator.runBuiltinKernel` -/ def replaySolution (origConstMap : Std.HashMap Name ConstantInfo) : IO Unit := do let env ← Lean.mkEmptyEnvironment let mut kernelEnv := env.toKernelEnv IO.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 ·) try kernelEnv ← Lean.Kernel.Environment.replay kernelConstMap kernelEnv IO.println "Lean default kernel accepts the solution" catch e => IO.println "Lean default kernel rejects the solution" throw e let verifyTargets := #[`Quot] ++ quotTargets for quotTarget in verifyTargets do if let some info := origConstMap[quotTarget]? then let some info' := kernelEnv.find? quotTarget | throw <| IO.userError s!"Could not find quotient constant in final kernel env: {quotTarget}" if info != info' then throw <| 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 := 0 for (n, ci) in origConstMap.toList do if ci.isUnsafe || ci.isPartial then unsafeOrPartial := unsafeOrPartial.push n else replayed := replayed + 1 if kernelEnv.find? n != some ci then different := different.push n IO.println s!"closure size: {origConstMap.size}; of which unsafe or partial: {unsafeOrPartial.size}; constants different after the replay: {different.size}" if unsafeOrPartial.size > 0 then IO.println s!" unsafe or partial: {unsafeOrPartial.take 20}" if different.size > 0 then IO.println s!" different: {different.take 20}" throw <| IO.userError "Some constants are different after the replay" /-! ### Main -/ def main (args : List String) : IO Unit := do let 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.monoMsNow let challenge ← importModules #[{ module := challengeMod.toName }] {} let t1 ← IO.monoMsNow let solution ← importModules #[{ module := solutionMod.toName }] {} let t2 ← IO.monoMsNow IO.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 definitionTargets IO.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) legalAxioms IO.println s!"axioms in the closure of the {theoremTargets.size} theorems: {axioms.toList}" let (perKind, perOrigin, ownModules) := countBy solution map IO.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.monoMsNow replaySolution map let t4 ← IO.monoMsNow IO.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