| /- | |
| Copyright (c) 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. | |
| Released under Apache 2.0 license as described in the file LICENSE. | |
| Authors: Leonardo de Moura | |
| -/ | |
| module | |
| prelude | |
| public import Lean.Meta.Sorry | |
| public import Lean.Util.CollectAxioms | |
| public import Lean.OriginalConstKind | |
| public import Lean.AutoDecl | |
| import Lean.Linter.Init | |
| import Lean.Compiler.MetaAttr | |
| import Lean.Util.RecDepth | |
| import Init.Data.Queue | |
| import all Lean.OriginalConstKind -- for accessing `privateConstKindsExt` | |
| public section | |
| namespace Lean | |
| /-- Converts `maxRecDepth` for the kernel, mapping values that do not fit in `USize` to `0` (unlimited). -/ | |
| private def kernelMaxRecDepth (opts : Options) : USize := | |
| let max := maxRecDepth.get opts | |
| if max < USize.size then max.toUSize else 0 | |
| /-- Adds given declaration to the environment, respecting `debug.skipKernelTC`. -/ | |
| def Kernel.Environment.addDecl (env : Environment) (opts : Options) (decl : Declaration) | |
| (cancelTk? : Option IO.CancelToken := none) : Except Exception Environment := | |
| if debug.skipKernelTC.get opts then | |
| addDeclWithoutChecking env decl | |
| else | |
| addDeclCore env (Core.getMaxHeartbeats opts).toUSize (kernelMaxRecDepth opts) decl cancelTk? | |
| private def Environment.addDeclAux (env : Environment) (opts : Options) (decl : Declaration) | |
| (cancelTk? : Option IO.CancelToken := none) : Except Kernel.Exception Environment := | |
| env.addDeclCore (Core.getMaxHeartbeats opts).toUSize (kernelMaxRecDepth opts) decl cancelTk? | |
| (!debug.skipKernelTC.get opts) (nonblocking := Elab.async.get opts) | |
| open Linter in | |
| /-- | |
| Saves the state of `Lean.Option`s associated with environment linters into `envLinterSnapshotExt` | |
| -/ | |
| def snapshotEnvLinterOptions (declName : Name) : CoreM Unit := do | |
| let envLinterOpts ← envLinterOptionsRef.get | |
| unless envLinterOpts.isEmpty do | |
| let linterOptions ← getLinterOptions | |
| unless ← isAutoDeclOrPrivate_Internal declName do | |
| let mut snapshot : NameMap Bool := {} | |
| for opt in envLinterOpts do | |
| snapshot := snapshot.insert opt.name (getLinterValue opt linterOptions) | |
| modifyEnv (envLinterSnapshotExt.insert · declName snapshot) | |
| private def isNamespaceName : Name → Bool | |
| | .str .anonymous _ => true | |
| | .str p _ => isNamespaceName p | |
| | _ => false | |
| private def registerNamePrefixes (env : Environment) (name : Name) : Environment := | |
| -- namespaces are based on the un-encoded name (`isNamespaceName` is false for any private name) | |
| let name := privateToUserName name | |
| match name with | |
| | .str _ s => | |
| if s.front == '_' then | |
| -- Do not register namespaces that only contain internal declarations. | |
| env | |
| else | |
| go env name | |
| | _ => env | |
| where go env | |
| | .str p _ => if isNamespaceName p then go (env.registerNamespace p) p else env | |
| | _ => env | |
| /-- If `warn.sorry` is set to true, then, so long as the message log does not already have any errors, | |
| declarations with `sorryAx` generate the "declaration uses `sorry`" warning. -/ | |
| register_builtin_option warn.sorry : Bool := { | |
| defValue := true | |
| descr := "warn about uses of `sorry` in declarations added to the environment" | |
| } | |
| /-- | |
| If the `warn.sorry` option is set to true and there are no errors in the log already, | |
| logs a warning if the declaration uses `sorry`. | |
| -/ | |
| def warnIfUsesSorry (decl : Declaration) : CoreM Unit := do | |
| if warn.sorry.get (← getOptions) then | |
| if !(← MonadLog.hasErrors) && decl.hasSorry then | |
| -- Find an actual sorry expression to use for `sorry`. | |
| -- That way the user can hover over it to see its type and use "go to definition" if it is a labeled sorry. | |
| let findSorry : StateRefT (Array (Bool × MessageData)) MetaM Unit := decl.forEachSorryM fun s => do | |
| let s' ← addMessageContext s | |
| modify fun arr => arr.push (s.isSyntheticSorry, s') | |
| let (_, sorries) ← findSorry |>.run #[] |>.run' | |
| -- Prefer reporting a synthetic sorry. | |
| -- These can appear without logged errors if `decl` is referring to declarations with elaboration errors; | |
| -- that's where a user should direct their focus. | |
| if let some (_, s) := sorries.find? (·.1) <|> sorries[0]? then | |
| logWarning <| .tagged `hasSorry m!"declaration uses `{s}`" | |
| else | |
| -- This case should not happen, but it ensures a warning will get logged no matter what. | |
| logWarning <| .tagged `hasSorry m!"declaration uses `sorry`" | |
| register_builtin_option Elab.persistentSignatures : Bool := { | |
| defValue := true | |
| descr := "mark the types of declarations as persistent when they are added to the environment, \ | |
| which stops reference counting on them, in particular from multiple threads at once, but means \ | |
| they are never deallocated; the language server turns this off by default" | |
| } | |
| /-- Marks `type`, the type of a constant about to be added, as persistent if so configured. -/ | |
| def markSignaturePersistent (type : Expr) : CoreM Unit := do | |
| if Elab.persistentSignatures.get (← getOptions) then | |
| discard <| unsafe Runtime.markPersistent type | |
| /-- Applies `markSignaturePersistent` to the types of all constants given in `decl`. -/ | |
| private def markSignaturesPersistent (decl : Declaration) : CoreM Unit := do | |
| match decl with | |
| | .axiomDecl d => markSignaturePersistent d.type | |
| | .defnDecl d => markSignaturePersistent d.type | |
| | .thmDecl d => markSignaturePersistent d.type | |
| | .opaqueDecl d => markSignaturePersistent d.type | |
| | .mutualDefnDecl ds => ds.forM (markSignaturePersistent ·.type) | |
| | .inductDecl _ _ types _ => | |
| for type in types do | |
| markSignaturePersistent type.type | |
| type.ctors.forM (markSignaturePersistent ·.type) | |
| | .quotDecl => pure () | |
| /-- | |
| Maximum number of declarations the kernel checks at the same time. A check holds on to its reduction | |
| caches until it is done, so the memory of concurrent checks adds up. | |
| -/ | |
| private def maxParallelKernelChecks : Nat := 4 | |
| private structure KernelCheckSlots where | |
| /-- Number of slots in use. -/ | |
| used : Nat := 0 | |
| /-- Checks waiting for a slot, each resolved by the check that hands its slot over. -/ | |
| waiting : Std.Queue (IO.Promise Unit) := .empty | |
| private instance : Inhabited KernelCheckSlots := ⟨{}⟩ | |
| private builtin_initialize kernelCheckSlotsRef : IO.Ref KernelCheckSlots ← IO.mkRef {} | |
| /-- Returns a task that finishes when a kernel check slot has been reserved for the caller. -/ | |
| private def acquireKernelCheckSlot : BaseIO (Task Unit) := do | |
| let promise ← IO.Promise.new | |
| let wait ← kernelCheckSlotsRef.modifyGet fun s => | |
| if s.used < maxParallelKernelChecks then | |
| (false, { s with used := s.used + 1 }) | |
| else | |
| (true, { s with waiting := s.waiting.enqueue promise }) | |
| if wait then | |
| return promise.resultD () | |
| else | |
| return .pure () | |
| /-- Releases a slot from `acquireKernelCheckSlot`, handing it to the next waiting check if any. -/ | |
| private def releaseKernelCheckSlot : BaseIO Unit := do | |
| let next? ← kernelCheckSlotsRef.modifyGet fun s => | |
| match s.waiting.dequeue? with | |
| | some (promise, waiting) => (some promise, { s with waiting }) | |
| | none => (none, { s with used := s.used - 1 }) | |
| if let some promise := next? then | |
| promise.resolve () | |
| builtin_initialize | |
| registerTraceClass `addDecl | |
| /-- | |
| Records that `declName` is about to be added as a declaration of kind `kind` that is exported as a | |
| different kind; see `getOriginalConstKind?`. `addDecl` does this by itself, so this function is | |
| needed only where `addDecl` is run on a different environment branch, in order to make the | |
| information available on the current branch early. | |
| -/ | |
| def recordOriginalConstKind (env : Environment) (declName : Name) (kind : ConstantKind) : | |
| Environment := | |
| privateConstKindsExt.insert env declName kind | |
| private def addDeclCore (decl : Declaration) (forceExpose : Bool) : CoreM Unit := | |
| withTraceNode `addDecl (fun _ => return m!"adding declarations {decl.getNames}") do | |
| markSignaturesPersistent decl | |
| -- register namespaces for newly added constants; this used to be done by the kernel itself | |
| -- but that is incompatible with moving it to a separate task | |
| -- NOTE: we do not use `getTopLevelNames` here so that inductive types are registered as | |
| -- namespaces | |
| modifyEnv (decl.getNames.foldl registerNamePrefixes) | |
| -- convert `Declaration` to `ConstantInfo` to use as a preliminary value in the environment until | |
| -- kernel checking has finished; not all cases are supported yet | |
| let mut exportedInfo? := none | |
| let (name, info, kind) ← match decl with | |
| | .thmDecl thm => | |
| if !forceExpose && (← getEnv).header.isModule then | |
| trace[addDecl] "exporting theorem {thm.name} as axiom" | |
| exportedInfo? := some <| .axiomInfo { thm with isUnsafe := false } | |
| pure (thm.name, .thmInfo thm, .thm) | |
| | .defnDecl defn | .mutualDefnDecl [defn] => | |
| if !forceExpose && (← getEnv).header.isModule && !(← getEnv).isExporting then | |
| trace[addDecl] "exporting definition {defn.name} as axiom" | |
| exportedInfo? := some <| .axiomInfo { defn with isUnsafe := defn.safety != .safe } | |
| pure (defn.name, .defnInfo defn, .defn) | |
| | .opaqueDecl op => | |
| if !forceExpose && (← getEnv).header.isModule && !(← getEnv).isExporting then | |
| trace[addDecl] "exporting opaque {op.name} as axiom" | |
| exportedInfo? := some <| .axiomInfo { op with } | |
| pure (op.name, .opaqueInfo op, .opaque) | |
| | .axiomDecl ax => pure (ax.name, .axiomInfo ax, .axiom) | |
| | _ => | |
| trace[addDecl] "no matching async adding rules, adding synchronously" | |
| doAdd | |
| -- the kernel generates further constants for inductive types | |
| for n in decl.getNames do | |
| if let some info := (← getEnv).find? n then | |
| markSignaturePersistent info.type | |
| return | |
| -- Check early so we can avoid related env ext panics that would happen before the check in the | |
| -- kernel. | |
| if (← getEnv).containsOnBranch name then | |
| throwKernelException <| .alreadyDeclared (← getEnv).toKernelEnv name | |
| if decl.getTopLevelNames.all isPrivateName then | |
| if (← ResolveName.backward.privateInPublic.getM) then | |
| trace[addDecl] "private decl under `privateInPublic`, exporting as is" | |
| exportedInfo? := some info | |
| else | |
| trace[addDecl] "not exporting private declaration at all" | |
| exportedInfo? := none | |
| else | |
| -- preserve original constant kind in extension if different from exported one | |
| if exportedInfo?.isSome then | |
| -- may already have been done by `recordOriginalConstKind` | |
| if (privateConstKindsExt.find? (asyncMode := .local) (← getEnv) name).isNone then | |
| modifyEnv (privateConstKindsExt.insert · name kind) | |
| else | |
| trace[addDecl] "no matching exporting rules, exporting as is" | |
| exportedInfo? := some info | |
| let env ← getEnv | |
| -- no environment extension changes to report after kernel checking; ensures we do not | |
| -- accidentally wait for this snapshot when querying extension states | |
| let async ← env.addConstAsync (reportExts := false) name kind | |
| (exportedKind? := exportedInfo?.map (.ofConstantInfo)) | |
| -- report preliminary constant info immediately | |
| async.commitConst async.asyncEnv (some info) (exportedInfo? <|> info) | |
| setEnv async.mainEnv | |
| let doAddAndCommit := do | |
| setEnv async.asyncEnv | |
| try | |
| doAdd | |
| finally | |
| async.commitCheckEnv (← getEnv) | |
| if Elab.async.get (← getOptions) then | |
| let cancelTk ← IO.CancelToken.new | |
| -- Kernel diagnostics are accumulated in the resulting kernel environment, so we need to keep it. | |
| let t ← if Kernel.isDiagnosticsEnabled env then | |
| let checkAct ← Core.wrapAsyncAsSnapshot (cancelTk? := cancelTk) fun _ => doAddAndCommit | |
| BaseIO.mapTask checkAct env.checked | |
| else | |
| -- Check against `uncheckedKernelEnv` so that we do not wait for preceding checks, and in turn | |
| -- let following checks proceed by committing an unchecked version of the declaration right | |
| -- away. | |
| let opts ← getOptions | |
| let okPromise ← IO.Promise.new | |
| let checkAct ← Core.wrapAsyncAsSnapshot (cancelTk? := cancelTk) fun _ => do | |
| setEnv async.asyncEnv.useUncheckedKernelEnv | |
| try | |
| doCheck | |
| okPromise.resolve true | |
| catch ex => | |
| okPromise.resolve false | |
| throw ex | |
| let slot ← acquireKernelCheckSlot | |
| let t ← BaseIO.bindTask slot fun _ => | |
| BaseIO.mapTask (t := env.uncheckedKernelEnv) fun kenv => do | |
| let r ← checkAct kenv | |
| releaseKernelCheckSlot | |
| return r | |
| -- A theorem is represented by its signature in `uncheckedKernelEnv`; see `addConstAsync`. | |
| let unchecked := if decl matches .thmDecl .. then env.uncheckedKernelEnv else | |
| env.uncheckedKernelEnv.map (sync := true) fun kenv => | |
| kenv.addDeclWithoutChecking decl |>.toOption.getD kenv | |
| let checked := okPromise.result?.bind (sync := true) fun ok? => | |
| env.checked.bind (sync := true) fun kenv => | |
| if ok? == some true then | |
| .pure <| kenv.addDeclWithoutChecking decl |>.toOption.getD kenv | |
| else | |
| Task.spawn fun _ => addAsAxiomKernel opts kenv | |
| async.commitKernelEnvs async.asyncEnv unchecked checked | |
| pure t | |
| -- Do not display reporting range; most uses of `addDecl` are for registering auxiliary decls | |
| -- users should not worry about and other callers can add a separate task with ranges | |
| -- themselves, see `MutualDef`. | |
| Core.logSnapshotTask { stx? := none, reportingRange := .skip, task := t, cancelTk? := cancelTk } | |
| else | |
| try | |
| doAddAndCommit | |
| finally | |
| setEnv async.mainEnv | |
| where | |
| doCheck := do | |
| profileitM Exception "type checking" (← getOptions) do | |
| withTraceNode `Kernel (fun _ => return m!"typechecking declarations {decl.getTopLevelNames}") do | |
| warnIfUsesSorry decl | |
| let env ← (← getEnv).addDeclAux (← getOptions) decl (← read).cancelTk? | |
| |> ofExceptKernelException | |
| setEnv env | |
| doAdd := do | |
| try | |
| doCheck | |
| catch ex => | |
| -- avoid follow-up errors by (trying to) add broken decl as axiom | |
| addAsAxiom | |
| throw ex | |
| addAsAxiom := do | |
| for fallbackDecl in fallbackDecls do | |
| try | |
| let env ← (← getEnv).addDeclAux (← getOptions) fallbackDecl (← read).cancelTk? | |
| |> ofExceptKernelException | |
| setEnv env | |
| return | |
| catch _ => pure () | |
| /-- Like `addAsAxiom` for the kernel environment only. -/ | |
| addAsAxiomKernel (opts : Options) (kenv : Kernel.Environment) : Kernel.Environment := Id.run do | |
| for fallbackDecl in fallbackDecls do | |
| if let .ok kenv := kenv.addDecl opts fallbackDecl then | |
| return kenv | |
| return kenv | |
| /-- | |
| Axioms to try adding in place of `decl` if it fails to check: one with the given type for | |
| def/theorem, otherwise one with type `sorry`. | |
| -/ | |
| fallbackDecls : List Declaration := | |
| let typed := match decl with | |
| | .defnDecl d | .thmDecl d => | |
| [.axiomDecl { name := d.name, levelParams := d.levelParams, type := d.type, isUnsafe := false }] | |
| | _ => [] | |
| typed ++ decl.getNames.map fun n => .axiomDecl { | |
| name := n, levelParams := [] | |
| type := mkApp2 (mkConst ``sorryAx [1]) (mkSort 0) (mkConst ``true), isUnsafe := false | |
| } | |
| /-- | |
| Adds the given declaration to the environment's private scope, deriving a suitable presentation in | |
| the public scope if under the module system and if the declaration is not private. If `forceExpose` | |
| is true, exposes the declaration body, i.e. preserves the full representation in the public scope, | |
| independently of `Environment.isExporting` and even for theorems. | |
| -/ | |
| def addDecl (decl : Declaration) (forceExpose := false) : CoreM Unit := do | |
| addDeclCore decl forceExpose | |
| discard <| decl.getTopLevelNames.mapM snapshotEnvLinterOptions | |
| def addAndCompile (decl : Declaration) (logCompileErrors : Bool := true) | |
| (markMeta : Bool := false) : CoreM Unit := do | |
| addDecl decl | |
| if markMeta then | |
| for n in decl.getNames do | |
| modifyEnv (Lean.markMeta · n) | |
| compileDecl decl (logErrors := logCompileErrors) | |
| end Lean |