Lean / Reader
Lean reader

lp-check-script.lean

314 lines22 declarationsno sorryimports Lean
  1. import Lean
  2. /-!
  3. # My own check script
  4. This script repeats the logic of the standalone comparator program of
  5. `leanprover/comparator` at commit `865edc14486c3388e9225daa971da8e157488c3e`
  6. (files `Main.lean`, `Comparator/Compare.lean`, `Comparator/Axioms.lean`).
  7. It loads two module environments in one process and it compares the constants.
  8. Usage: `lake env lean --run Check/Check.lean CHALLENGE_MODULE SOLUTION_MODULE THEOREM [THEOREM ...]`
  9. The file `Check/Check.lean` of my sunflower check (desk task 428) is the origin.
  10. The files `Check/Check.lean` of my Hirsch check and of my matrix exponent check
  11. are the same script. This file is that script with a change of this comment only.
  12. -/
  13. open Lean
  14. deriving instance BEq for Lean.QuotKind
  15. deriving instance BEq for Lean.QuotVal
  16. deriving instance BEq for Lean.InductiveVal
  17. deriving instance BEq for Lean.ConstantInfo
  18. namespace Check
  19. /-- Same as `Comparator.runForUsedConsts`. -/
  20. def runForUsedConsts [Monad m] (info : ConstantInfo) (f : Name → m Unit) : m Unit := do
  21. info.type.getUsedConstants.forM f
  22. f info.name
  23. if let some val := info.value? (allowOpaque := true) then
  24. val.getUsedConstants.forM f
  25. match info with
  26. | .axiomInfo .. | .quotInfo .. | .defnInfo .. | .thmInfo .. | .opaqueInfo .. => return ()
  27. | .inductInfo info =>
  28. info.ctors.forM f
  29. info.all.forM f
  30. | .ctorInfo info =>
  31. f info.induct
  32. | .recInfo info =>
  33. info.rules.forM fun rule => do
  34. f rule.ctor
  35. rule.rhs.getUsedConstants.forM f
  36. /-- The same names as `runForUsedConsts`, as an array without a monad. -/
  37. def usedNames (info : ConstantInfo) : Array Name :=
  38. let base := info.type.getUsedConstants.push info.name
  39. let base :=
  40. match info.value? (allowOpaque := true) with
  41. | some v => base ++ v.getUsedConstants
  42. | none => base
  43. match info with
  44. | .inductInfo i => base ++ (i.ctors ++ i.all).toArray
  45. | .ctorInfo c => base.push c.induct
  46. | .recInfo r => base ++ (r.rules.map (fun rule => rule.rhs.getUsedConstants.push rule.ctor)).toArray.flatten
  47. | _ => base
  48. /-- Same list as `Comparator.primitiveTargets`. -/
  49. def primitiveTargets : Array Name :=
  50. #[
  51. ``Nat.add, ``Nat.sub, ``Nat.mul, ``Nat.pow, ``Nat.gcd, ``Nat.div, ``Nat.mod, ``Nat.beq, ``Nat.ble,
  52. ``Nat.land, ``Nat.lor, ``Nat.xor, ``Nat.shiftLeft, ``Nat.shiftRight, ``String.ofList, ``Char.ofNat,
  53. ``List, ``eagerReduce, ``Nat, ``String, ``String.mk, ``Char, ``optParam, ``autoParam, ``semiOutParam,
  54. ``outParam
  55. ]
  56. def legalAxioms : Array Name := #[``propext, ``Quot.sound, ``Classical.choice]
  57. /-- Name of the module that declares a constant. -/
  58. def moduleOf (env : Environment) (n : Name) : Name :=
  59. match env.getModuleIdxFor? n with
  60. | some idx => env.header.moduleNames[idx]!
  61. | none => .anonymous
  62. /-- Group name of a module: `Mathlib`, `OAI`, `Init`, other. -/
  63. def originOf (module : Name) : String :=
  64. let root := module.getRoot.toString
  65. match root with
  66. | "OAI" | "Mathlib" | "Init" | "Lean" | "Std" | "Batteries" | "Qq" | "Aesop" | "Lemmata"
  67. | "FixedPointTheorems" | "ProofWidgets" | "ImportGraph" | "Plausible" | "LeanSearchClient" | "Cli"
  68. | "ComparatorChallenges" =>
  69. root
  70. | _ => "other:" ++ root
  71. def kindOf : ConstantInfo → String
  72. | .axiomInfo _ => "axiom"
  73. | .defnInfo _ => "definition"
  74. | .thmInfo _ => "theorem"
  75. | .opaqueInfo _ => "opaque"
  76. | .quotInfo _ => "quot"
  77. | .inductInfo _ => "inductive"
  78. | .ctorInfo _ => "constructor"
  79. | .recInfo _ => "recursor"
  80. def countBy (env : Environment) (map : Std.HashMap Name ConstantInfo) :
  81. Std.HashMap String Nat × Std.HashMap String Nat × NameSet := Id.run do
  82. let mut perKind : Std.HashMap String Nat := {}
  83. let mut perOrigin : Std.HashMap String Nat := {}
  84. let mut ownModules : NameSet := {}
  85. for (n, ci) in map.toList do
  86. perKind := perKind.alter (kindOf ci) (fun c => some (c.getD 0 + 1))
  87. let mod := moduleOf env n
  88. let origin := originOf mod
  89. perOrigin := perOrigin.alter origin (fun c => some (c.getD 0 + 1))
  90. if origin == "OAI" || origin == "Lemmata" || origin == "FixedPointTheorems" then
  91. ownModules := ownModules.insert mod
  92. (perKind, perOrigin, ownModules)
  93. def sorted (m : Std.HashMap String Nat) : List (String × Nat) :=
  94. (m.toList.mergeSort (fun a b => a.1 < b.1))
  95. /-! ### Part 1: the statement match, same logic as `Comparator.compareAt` -/
  96. namespace Compare
  97. structure Context where
  98. challenge : Environment
  99. solution : Environment
  100. definitionTargets : NameSet
  101. theoremTargets : NameSet
  102. structure State where
  103. worklist : Array Name := #[]
  104. checked : NameSet := {}
  105. compared : Nat := 0
  106. perOrigin : Std.HashMap String Nat := {}
  107. abbrev M := ReaderT Context (StateRefT State IO)
  108. def addWorklist (n : Name) : M Unit := do
  109. if !(← get).checked.contains n then
  110. modify fun s => { s with worklist := s.worklist.push n }
  111. def addRelevantConsts (info : ConstantInfo) : M Unit := do
  112. runForUsedConsts info addWorklist
  113. /-- Mark a constant as checked and count it. -/
  114. def record (origin : String) (target : Name) (s : State) : State :=
  115. { s with checked := s.checked.insert target, compared := s.compared + 1, perOrigin := s.perOrigin.alter origin (fun c => some ((c.getD 0) + 1)) }
  116. partial def loop : M Unit := do
  117. if (← get).worklist.isEmpty then
  118. return ()
  119. let target := (← get).worklist.back!
  120. modify fun s => { s with worklist := s.worklist.pop }
  121. if (← get).checked.contains target then
  122. loop
  123. else
  124. let some challengeConst := (← read).challenge.find? target
  125. | throw <| IO.userError s!"Const not found in challenge '{target}'"
  126. let some solutionConst := (← read).solution.find? target
  127. | throw <| IO.userError s!"Const not found in solution '{target}'"
  128. if (← read).definitionTargets.contains solutionConst.name
  129. || (← read).theoremTargets.contains solutionConst.name then
  130. solutionConst.type.getUsedConstants.forM addWorklist
  131. else
  132. if challengeConst != solutionConst then
  133. throw <| IO.userError s!"Const does not match between challenge and target '{target}'"
  134. addRelevantConsts solutionConst
  135. let origin := originOf (moduleOf (← read).solution target)
  136. modify (record origin target)
  137. loop
  138. end Compare
  139. def compareAt (challenge solution : Environment) (theoremTargets definitionTargets : Array Name) :
  140. IO (Compare.State × Array Name) := do
  141. let mut worklist := primitiveTargets
  142. let mut used : Array Name := #[]
  143. for target in theoremTargets do
  144. let some challengeConst := challenge.find? target
  145. | throw <| IO.userError s!"Const not found in challenge: '{target}'"
  146. let some solutionConst := solution.find? target
  147. | throw <| IO.userError s!"Const not found in solution: '{target}'"
  148. let (challengeVal, solutionVal) ←
  149. match challengeConst, solutionConst with
  150. | .thmInfo cc, .thmInfo sc => pure (cc.toConstantVal, sc.toConstantVal)
  151. | .axiomInfo cc, .axiomInfo sc => pure (cc.toConstantVal, sc.toConstantVal)
  152. | _, _ => throw <| IO.userError s!"Challenge and solution constant kind don't match: '{target}'"
  153. IO.println s!"--- {target}"
  154. IO.println s!"kind in challenge: {kindOf challengeConst}; kind in solution: {kindOf solutionConst}"
  155. IO.println s!"level parameters: {challengeVal.levelParams}"
  156. if challengeVal != solutionVal then
  157. IO.println "challenge type:"
  158. IO.println (toString challengeVal.type)
  159. IO.println "solution type:"
  160. IO.println (toString solutionVal.type)
  161. throw <| IO.userError s!"Challenge and solution theorem statement do not match: '{target}'"
  162. IO.println s!"theorem record is the same in both environments: {target}"
  163. IO.println " constants that the statement uses (name; module in challenge; module in solution):"
  164. let statementUsed := challengeVal.type.getUsedConstants
  165. for n in statementUsed do
  166. IO.println s!" {n}; {moduleOf challenge n}; {moduleOf solution n}"
  167. if !used.contains n then
  168. used := used.push n
  169. worklist := worklist ++ statementUsed
  170. let ctx : Compare.Context :=
  171. { challenge := challenge, solution := solution,
  172. definitionTargets := NameSet.ofArray definitionTargets,
  173. theoremTargets := NameSet.ofArray theoremTargets }
  174. let initialState : Compare.State := { worklist := worklist, checked := {} }
  175. let (_, st) ← StateRefT'.run (ReaderT.run Compare.loop ctx) initialState
  176. return (st, used)
  177. /-! ### Part 2: the axioms, same logic as `Comparator.checkAxioms` -/
  178. def closure (env : Environment) (roots : Array Name) : IO (Std.HashMap Name ConstantInfo) := do
  179. let mut map : Std.HashMap Name ConstantInfo := {}
  180. let mut work := roots
  181. while work.size > 0 do
  182. let name := work[work.size - 1]!
  183. work := work.pop
  184. if map.contains name then
  185. continue
  186. let some ci := env.find? name
  187. | throw <| IO.userError s!"Constant not found: '{name}'"
  188. map := map.insert name ci
  189. for n in usedNames ci do
  190. if !map.contains n then
  191. work := work.push n
  192. return map
  193. def checkAxioms (env : Environment) (roots : Array Name) (legal : Array Name) :
  194. IO (Std.HashMap Name ConstantInfo × Array Name) := do
  195. let map ← closure env roots
  196. let mut axioms : Array Name := #[]
  197. for (_n, ci) in map.toList do
  198. if let .axiomInfo info := ci then
  199. if !legal.contains info.name then
  200. throw <| IO.userError s!"Illegal axiom detected: '{info.name}'"
  201. if !axioms.contains info.name then
  202. axioms := axioms.push info.name
  203. return (map, axioms)
  204. /-! ### Part 3: the kernel replay, same logic as `Comparator.runBuiltinKernel` -/
  205. def replaySolution (origConstMap : Std.HashMap Name ConstantInfo) : IO Unit := do
  206. let env ← Lean.mkEmptyEnvironment
  207. let mut kernelEnv := env.toKernelEnv
  208. IO.println s!"initial kernel environment has {kernelEnv.constants.toList.length} constants"
  209. 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}"
  210. let quotTargets : Array Name := #[`Quot.mk, `Quot.lift, `Quot.ind]
  211. let kernelConstMap := quotTargets.foldl (init := origConstMap) (·.erase ·)
  212. try
  213. kernelEnv ← Lean.Kernel.Environment.replay kernelConstMap kernelEnv
  214. IO.println "Lean default kernel accepts the solution"
  215. catch e =>
  216. IO.println "Lean default kernel rejects the solution"
  217. throw e
  218. let verifyTargets := #[`Quot] ++ quotTargets
  219. for quotTarget in verifyTargets do
  220. if let some info := origConstMap[quotTarget]? then
  221. let some info' := kernelEnv.find? quotTarget
  222. | throw <| IO.userError s!"Could not find quotient constant in final kernel env: {quotTarget}"
  223. if info != info' then
  224. throw <| IO.userError s!"Quotient constant mismatch on: {quotTarget}"
  225. IO.println "quotient constants agree"
  226. -- Extra check of mine: each constant of the closure is in the kernel environment with the same record.
  227. let mut different : Array Name := #[]
  228. let mut unsafeOrPartial : Array Name := #[]
  229. let mut replayed : Nat := 0
  230. for (n, ci) in origConstMap.toList do
  231. if ci.isUnsafe || ci.isPartial then
  232. unsafeOrPartial := unsafeOrPartial.push n
  233. else
  234. replayed := replayed + 1
  235. if kernelEnv.find? n != some ci then
  236. different := different.push n
  237. IO.println s!"closure size: {origConstMap.size}; of which unsafe or partial: {unsafeOrPartial.size}; constants different after the replay: {different.size}"
  238. if unsafeOrPartial.size > 0 then
  239. IO.println s!" unsafe or partial: {unsafeOrPartial.take 20}"
  240. if different.size > 0 then
  241. IO.println s!" different: {different.take 20}"
  242. throw <| IO.userError "Some constants are different after the replay"
  243. /-! ### Main -/
  244. def main (args : List String) : IO Unit := do
  245. let challengeMod :: solutionMod :: targets := args
  246. | throw <| IO.userError "usage: Check.lean CHALLENGE_MODULE SOLUTION_MODULE THEOREM [THEOREM ...]"
  247. let theoremTargets := targets.toArray.map (·.toName)
  248. let definitionTargets : Array Name := #[]
  249. let t0 ← IO.monoMsNow
  250. let challenge ← importModules #[{ module := challengeMod.toName }] {}
  251. let t1 ← IO.monoMsNow
  252. let solution ← importModules #[{ module := solutionMod.toName }] {}
  253. let t2 ← IO.monoMsNow
  254. IO.println s!"challenge module {challengeMod}: {challenge.constants.toList.length} constants, {challenge.header.moduleNames.size} imported modules, {t1 - t0} ms"
  255. IO.println s!"solution module {solutionMod}: {solution.constants.toList.length} constants, {solution.header.moduleNames.size} imported modules, {t2 - t1} ms"
  256. IO.println s!"theorem targets ({theoremTargets.size}): {theoremTargets.toList}"
  257. IO.println "===== part 1: statement match ====="
  258. let (st, used) ← compareAt challenge solution theoremTargets definitionTargets
  259. IO.println s!"the {theoremTargets.size} statements use {used.size} different constants; compared in the closure: {st.compared} constants; all records are the same"
  260. IO.println s!" by library: {sorted st.perOrigin}"
  261. IO.println "===== part 2: axioms ====="
  262. let (map, axioms) ← checkAxioms solution (theoremTargets ++ legalAxioms ++ primitiveTargets) legalAxioms
  263. IO.println s!"axioms in the closure of the {theoremTargets.size} theorems: {axioms.toList}"
  264. let (perKind, perOrigin, ownModules) := countBy solution map
  265. IO.println s!"closure of the {theoremTargets.size} theorems in the solution environment: {map.size} constants"
  266. IO.println s!" by kind: {sorted perKind}"
  267. IO.println s!" by library: {sorted perOrigin}"
  268. IO.println s!" modules of the claimant library that declare at least one of them: {ownModules.size}"
  269. IO.println "===== part 3: kernel replay ====="
  270. let t3 ← IO.monoMsNow
  271. replaySolution map
  272. let t4 ← IO.monoMsNow
  273. IO.println s!"replay time: {t4 - t3} ms"
  274. IO.println "ALL THREE CHECKS PASS"
  275. end Check
  276. /-- The program needs `main` in the root namespace for `lean --run`. -/
  277. def main : List String → IO Unit := Check.main