perf: type check constants from nested realizations only once This PR makes the kernel type check a constant created by a nested realization only once. For example, the equation theorems of a function request the equations of its `match`, and the kernel checked each of those theorems twice, or three times when they requested further theorems themselves. Generating the equations of a `String → Nat` function with 128 literal alternatives is about 25% faster. It also fixes repeated error messages: a kernel error in such a constant was reported once per nesting level, and is now reported once. A realization runs with the kernel disabled, and `Environment.realizeConst` type checks its constants when the result is added to the environment that requested it. When that environment belongs to another realization, the constants are also part of the result of that realization and were checked again when it was added to its own requester. `realizeConst` now adds them without type checking when the requester is itself realizing (`env.isRealizing`), so the only check is the one in the outermost requester. The new test `realizeConstNestedKernelCheck.lean` creates an ill-typed theorem in a realization nested at depth 2 and at depth 3: the kernel still rejects it, and the `declaration type mismatch` error, which was printed 2 and 3 times, is printed once. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
diff --git a/src/Lean/Environment.lean b/src/Lean/Environment.lean index 297985f..cead352 100644 --- a/src/Lean/Environment.lean +++ b/src/Lean/Environment.lean
@@ -3042,9 +3042,20 @@ allRealizations.insert c.constInfo.name c } where + /-- + Returns `kenv` extended with the constants `consts`. + + - `doCheck = true`: the kernel type checks each constant before adding it to `kenv`. + - `doCheck = false`: each constant is added to `kenv` as is. The kernel does not look at it. + + `oldEnv` and `newEnv` are not modified, and no constant is read from them. They are the kernel + environments from before and after the code that created `consts` ran, and are only used to copy + the changes that this code made to the environment extensions. + -/ replayKernel (oldEnv newEnv : Kernel.Environment) (exts : Array (EnvExtension EnvExtensionState)) (consts : List AsyncConst) - (kenv : Kernel.Environment) : Except Kernel.Exception Kernel.Environment := do + (kenv : Kernel.Environment) (doCheck := true) : + Except Kernel.Exception Kernel.Environment := do let mut kenv := kenv -- replay extensions first in case kernel checking needs them (`IR.declMapExt`) for ext in exts do @@ -3077,7 +3088,13 @@ return panic! s!"{c.constInfo.name} must be definition/theorem" -- realized kernel additions cannot be interrupted - which would be bad anyway as they can be -- reused between snapshots - kenv ← ofExcept <| kenv.addDeclCore 0 0 decl none + kenv ← ofExcept <| + if doCheck then + -- Type check `decl`, and then add it. + kenv.addDeclCore 0 0 decl none + else + -- Add `decl` without type checking it. + kenv.addDeclWithoutChecking decl return kenv /-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`. @@ -3172,7 +3189,17 @@ /-- Realization results, to be replayed onto other branches. -/ private structure RealizeConstResult where newConsts : VisibilityMap (List AsyncConst) - replayKernel : Kernel.Environment → Task (Except Kernel.Exception Kernel.Environment) + /-- + `replayKernel doCheck kenv` returns `kenv` extended with the constants `newConsts`. + + - `doCheck = true`: the kernel type checks each constant before adding it to `kenv`. + - `doCheck = false`: each constant is added to `kenv` as is. The kernel does not look at it. + + It also applies to `kenv` the changes that the realization made to the environment extensions. + The result is a `Task` because it waits for the kernel environments of the realization. + -/ + replayKernel : (doCheck : Bool) → Kernel.Environment → + Task (Except Kernel.Exception Kernel.Environment) dyn : Dynamic deriving Nonempty, TypeName @@ -3218,10 +3245,11 @@ -- CI build. let oldChecked := realizeEnv.checked let newChecked := realizeEnv'.checked - let replayKernel := fun kenv => + let replayKernel := fun doCheck kenv => oldChecked.bind (sync := true) fun oldKEnv => newChecked.map fun newKEnv => replayConsts.replayKernel (skipExisting := true) oldKEnv newKEnv exts newPrivateConsts kenv + doCheck let res : RealizeConstResult := { newConsts.private := newPrivateConsts newConsts.public := newPublicConsts @@ -3251,8 +3279,23 @@ else consts.add c } + /- + Add the constants of the realization to `kenv`, the kernel environment of `env` + (`env.checked` is a task that produces it). + `env` is the environment that requested the realization. There are two cases. + + 1. `env.isRealizing` is `false`: the request did not come from inside another realization. + The kernel type checks the constants here. + + 2. `env.isRealizing` is `true`: the request came from inside another realization `R`, and `env` + is the environment `R` is running in. The constants are added to `kenv` without type + checking. + The kernel type checks them later: when `R` finishes, its result contains every constant + added to `env` while `R` ran (see `newPrivateConsts` above), including the ones added here, + and this code runs again for the environment that requested `R`. + -/ checked := (← BaseIO.bindTask (t := env.checked) (sync := true) fun kenv => - BaseIO.mapTask (t := res.replayKernel kenv) fun + BaseIO.mapTask (t := res.replayKernel (doCheck := !env.isRealizing) kenv) fun | .ok kenv' => return kenv' | .error e => do exPromise.resolve e
diff --git a/tests/elab/realizeConstNestedKernelCheck.lean b/tests/elab/realizeConstNestedKernelCheck.lean new file mode 100644 index 0000000..13a6545 --- /dev/null +++ b/tests/elab/realizeConstNestedKernelCheck.lean
@@ -0,0 +1,72 @@ +import Lean +/-! +Constants created by a realization nested in another realization are type checked by the kernel +exactly once: when the result of the outermost realization is added to the environment that +requested it. In particular, an ill-typed constant is still rejected, and the error is reported once. +-/ +open Lean Meta + +/-- Adds the theorem `name : type := value`. -/ +def addThm (name : Name) (type value : Expr) : MetaM Unit := + addDecl <| .thmDecl { name, levelParams := [], type, value } + +/-- Returns `true` if `name` is in the kernel environment. -/ +def inKernelEnv (name : Name) : MetaM Bool := + return ((← getEnv).toKernelEnv.find? name).isSome + +/-! Well-typed theorems created at depths 1, 2 and 3 are added to the kernel environment. -/ + +def ok := 1 + +/-- info: [true, true, true] -/ +#guard_msgs in +run_meta do + realizeConst ``ok `ok.l1 do + realizeConst ``ok `ok.l2 do + realizeConst ``ok `ok.l3 do + addThm `ok.l3 (mkConst ``True) (mkConst ``True.intro) + addThm `ok.l2 (mkConst ``True) (mkConst ``True.intro) + addThm `ok.l1 (mkConst ``True) (mkConst ``True.intro) + logInfo m!"{[← inKernelEnv `ok.l1, ← inKernelEnv `ok.l2, ← inKernelEnv `ok.l3]}" + +/-! An ill-typed theorem created at depth 2 is rejected. -/ + +def bad2 := 1 + +/-- +info: [false, false] +--- +error: (kernel) declaration type mismatch, 'bad2.l2' has type + True +but it is expected to have type + False +-/ +#guard_msgs in +run_meta do + realizeConst ``bad2 `bad2.l1 do + realizeConst ``bad2 `bad2.l2 do + addThm `bad2.l2 (mkConst ``False) (mkConst ``True.intro) + addThm `bad2.l1 (mkConst ``True) (mkConst ``True.intro) + logInfo m!"{[← inKernelEnv `bad2.l1, ← inKernelEnv `bad2.l2]}" + +/-! An ill-typed theorem created at depth 3 is rejected. -/ + +def bad3 := 1 + +/-- +info: [false, false, false] +--- +error: (kernel) declaration type mismatch, 'bad3.l3' has type + True +but it is expected to have type + False +-/ +#guard_msgs in +run_meta do + realizeConst ``bad3 `bad3.l1 do + realizeConst ``bad3 `bad3.l2 do + realizeConst ``bad3 `bad3.l3 do + addThm `bad3.l3 (mkConst ``False) (mkConst ``True.intro) + addThm `bad3.l2 (mkConst ``True) (mkConst ``True.intro) + addThm `bad3.l1 (mkConst ``True) (mkConst ``True.intro) + logInfo m!"{[← inKernelEnv `bad3.l1, ← inKernelEnv `bad3.l2, ← inKernelEnv `bad3.l3]}"