Documentation

Lean.Environment

Note [Environment Branches] #

The kernel environment type Lean.Kernel.Environment enforces a linear order on the addition of declarations: addDeclCore takes an environment and returns a new one, assuming type checking succeeded. On the other hand, the metaprogramming-level Lean.Environment wrapper must allow for branching environment transformations so that multiple declarations can be elaborated concurrently while still being able to access information about preceding declarations that have also been branched out as soon as they are available.

The basic function to introduce such branches is addConstAsync, which takes an environment and returns a structure containing two environments: one for the "main" branch that can be used in further branching and eventually contains all the declarations of the file and one for the "async" branch that can be used concurrently to the main branch to elaborate and add the declaration for which the branch was introduced. Branches are "joined" back together implicitly via the kernel environment, which as mentioned cannot be changed concurrently: when the main branch first tries to access it, evaluation is blocked until the kernel environment on the async branch is complete. Thus adding two declarations A and B concurrently can be visualized like this:

o addConstAsync A
|\
| \
|  \
o addConstAsync B
|\   \
| \   o elaborate A
|  \  |
|   o elaborate B
|   | |
|   | o addDeclCore A
|   |/
|   o addDeclCore B
|  /
| /
|/
o .olean serialization calls Environment.toKernelEnv

While each edge represents a Lean.Environment that has its own view of the state of the module, the kernel environment really lives only in the right-most path, with all other paths merely holding an unfulfilled Task representing it and where forcing that task leads to the back-edges joining paths back together.

Opaque environment extension state.

@[reducible, inline]
Equations
instance Lean.instGetElemArrayModuleIdxLtNatToNatSize {α : Type u_1} :
GetElem (Array α) ModuleIdx α fun (a : Array α) (i : ModuleIdx) => i.toNat < a.size
Equations
Equations
Equations
Equations

A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk. Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean files are compacted regions.

Equations
@[extern lean_compacted_region_is_memory_mapped]
@[extern lean_compacted_region_free]

Free a compacted region and its contents. No live references to the contents may exist at the time of invocation.

Opaque persistent environment extension entry.

Content of a .olean file. We use compact.cpp to generate the image of this object in disk.

Instances For
Equations

Environment fields that are not used often.

  • trustLevel : UInt32

    The trust level used by the kernel. For example, the kernel assumes imported constants are type correct when the trust level is greater than zero.

  • mainModule : Name

    Name of the module being compiled.

  • imports : Array Import

    Direct imports

  • Compacted regions for all imported modules. Objects in compacted memory regions do no require any memory management.

  • moduleNames : Array Name

    Name of all imported modules (directly and indirectly). The index of a module name in the array equals the ModuleIdx for the same module.

  • moduleData : Array ModuleData

    Module data for all imported modules.

Instances For
  • unfoldCounter : PHashMap Name Nat

    Number of times each declaration has been unfolded by the kernel.

  • enabled : Bool

    If enabled = true, kernel records declarations that have been unfolded.

Instances For

An environment stores declarations provided by the user. The kernel currently supports different kinds of declarations such as definitions, theorems, and inductive families. Each has a unique identifier (i.e., Name), and can be parameterized by a sequence of universe parameters. A constant in Lean is just a reference to a ConstantInfo object. The main task of the kernel is to type check these declarations and refuse type incorrect ones. The kernel does not allow declarations containing metavariables and/or free variables to be added to an environment. Environments are never destructively updated.

The environment also contains a collection of extensions. For example, the simp theorems declared by users are stored in an environment extension. Users can declare new extensions using meta-programming.

  • constants : ConstMap

    Mapping from constant name to ConstantInfo. It contains all constants (definitions, theorems, axioms, etc) that have been already type checked by the kernel.

  • quotInit : Bool

    quotInit = true if the command init_quot has already been executed for the environment, and Quot declarations have been added to the environment. When the flag is set, the type checker can assume that the Quot declarations in the environment have indeed been added by the kernel and not by the user.

  • diagnostics : Diagnostics

    Diagnostic information collected during kernel execution.

    Remark: We store kernel diagnostic information in an environment field to simplify the interface with the kernel implemented in C/C++. Thus, we can only track declarations in methods, such as addDecl, which return a new environment. Kernel.isDefEq and Kernel.whnf do not update the statistics. We claim this is ok since these methods are mainly used for debugging.

  • const2ModIdx : Std.HashMap Name ModuleIdx

    Mapping from constant name to module (index) where constant has been declared. Recall that a Lean file has a header where previously compiled modules can be imported. Each imported module has a unique ModuleIdx. Many extensions use the ModuleIdx to efficiently retrieve information stored in imported modules.

    Remark: this mapping also contains auxiliary constants, created by the code generator, that are not in the field constants. These auxiliary constants are invisible to the Lean kernel and elaborator. Only the code generator uses them.

  • Environment extensions. It also includes user-defined extensions.

  • extraConstNames : Lean.NameSet

    Constant names to be saved in the field extraConstNames at ModuleData. It contains auxiliary declaration names created by the code generator which are not in constants. When importing modules, we want to insert them at const2ModIdx.

  • The header contains additional information that is set at import time.

Instances For

Exceptions that can be raised by the kernel when type checking new declarations.

Instances For
@[export lean_environment_find]
Equations
@[extern lean_add_decl]

Type check given declaration and add it to the environment

@[extern lean_add_decl_without_checking]

Add declaration to kernel without type checking it.

WARNING This function is meant for temporarily working around kernel performance issues. It compromises soundness because, for example, a buggy tactic may produce an invalid proof, and the kernel will not catch it if the new option is set to true.

Enables/disables kernel diagnostics.

Equations
  • One or more equations did not get rendered due to their size.
Equations
  • One or more equations did not get rendered due to their size.
@[export lean_kernel_record_unfold]
Equations
  • One or more equations did not get rendered due to their size.
@[export lean_kernel_get_diag]
Equations
@[export lean_kernel_set_diag]
Equations
  • One or more equations did not get rendered due to their size.
@[reducible, inline, deprecated Lean.Kernel.Exception (since := "2024-12-12")]
Equations

ConstantInfo variant that allows for asynchronous filling of components via tasks.

  • name : Name

    The declaration name, known immediately.

  • The kind of the constant, known immediately.

  • The "signature" including level params and type, potentially filled asynchronously.

  • constInfo : Task ConstantInfo

    The final, complete constant info, potentially filled asynchronously.

Instances For

Constant info and environment extension states eventually resulting from async elaboration.

Equations

Elaboration-specific extension of Kernel.Environment that adds tracking of asynchronously elaborated declarations.

  • checkedWithoutAsync : Kernel.Environment

    Kernel environment not containing any asynchronously elaborated declarations. Also stores environment extension state for the current branch of the environment.

    Ignoring extension state, this is guaranteed to be some prior version of checked that is eagerly available. Thus we prefer taking information from it instead of checked whenever possible.

  • Kernel environment task that is fulfilled when all asynchronously elaborated declarations are finished, containing the resulting environment. Also collects the environment extension state of all environment branches that contributed contained declarations.

  • asyncConsts : Lean.AsyncConsts✝

    Container of asynchronously elaborated declarations. For consistency, updateBaseAfterKernelAdd makes sure this contains constants added even synchronously, i.e. this is a superset of checkedWithoutAsync except for imported constants.

  • Information about this asynchronous branch of the environment, if any.

  • realizedImportedConsts? : Option Lean.RealizationContext✝

    Realized constants belonging to imported declarations. Must be initialized by calling enableRealizationsForImports.

  • Realized constants belonging to local declarations. This is a map from local declarations, which need to be registered synchronously using enableRealizationsForConst, to their realization context incl. a ref of realized constants.

Instances For
@[export lean_elab_environment_of_kernel_env]
Equations
  • One or more equations did not get rendered due to their size.
@[export lean_elab_environment_to_kernel_env]
Equations

Checks whether the given declaration name may potentially added, or have been added, to the current environment branch, which is the case either if this is the main branch or if the declaration name is a suffix (modulo privacy and hygiene information) of the top-level declaration name for which this branch was created.

This function should always be checked before modifying an AsyncMode.async environment extension to ensure findStateAsync will be able to find the modification from other branches.

Equations
def Lean.Environment.addDeclCore (env : Environment) (maxHeartbeats : USize) (decl : Declaration) (cancelTk? : Option IO.CancelToken) (doCheck : Bool := true) :

Adds given declaration to the environment, type checking it unless doCheck is false.

This is a plumbing function for the implementation of Lean.addDecl, most users should use it instead.

Equations
  • One or more equations did not get rendered due to their size.

Mapping from constant name to ConstantInfo. It contains all constants (definitions, theorems, axioms, etc) that have been already type checked by the kernel.

Equations

Mapping from constant name to module (index) where constant has been declared. Recall that a Lean file has a header where previously compiled modules can be imported. Each imported module has a unique ModuleIdx. Many extensions use the ModuleIdx to efficiently retrieve information stored in imported modules.

Remark: this mapping also contains auxiliary constants, created by the code generator, that are not in the field constants. These auxiliary constants are invisible to the Lean kernel and elaborator. Only the code generator uses them.

Equations

Save an extra constant name that is used to populate const2ModIdx when we import .olean files. We use this feature to save in which module an auxiliary declaration created by the code generator has been created.

Equations
  • One or more equations did not get rendered due to their size.

Looks up the given declaration name in the environment, avoiding forcing any in-progress elaboration tasks.

Equations
  • One or more equations did not get rendered due to their size.

Looks up the given declaration name in the environment, avoiding forcing any in-progress elaboration tasks for declaration bodies (which are not accessible from ConstantVal).

Equations
  • One or more equations did not get rendered due to their size.

Allows realizeConst calls for imported declarations in all derived environment branches. Realizations will run using the given environment and options to ensure deterministic results. This function should be called directly after setMainModule to ensure that all realized constants use consistent private prefixes.

Equations
  • One or more equations did not get rendered due to their size.

Allows realizeConst calls for the given declaration in all derived environment branches. Realizations will run using the given environment and options to ensure deterministic results. Note that while we check that the function isn't called too early, i.e. before the declaration is actually added to the environment, we cannot automatically check that it isn't called too late, i.e. before all environment extensions that may be relevant to realizations have been set. We do check that we are not calling it from a different branch than c was added on, which would be definitely too late.

Equations
  • One or more equations did not get rendered due to their size.

Looks up the given declaration name in the environment, blocking on the corresponding elaboration task if not yet complete.

Equations
  • One or more equations did not get rendered due to their size.

Returns debug output about the asynchronous state of the environment.

Equations
  • One or more equations did not get rendered due to their size.

Returns debug output about the synchronous state of the environment.

Equations
  • One or more equations did not get rendered due to their size.

Result of Lean.Environment.promiseChecked.

Starts an asynchronous modification of the kernel environment. The environment is split into a "main" branch that will block on access to the kernel environment until PromiseCheckedResult.commitChecked has been called on the "async" environment branch.

Equations
  • One or more equations did not get rendered due to their size.

Commits the kernel environment of the given environment back to the main branch.

Equations
  • One or more equations did not get rendered due to their size.

Result of Lean.Environment.addConstAsync which is necessary to complete the asynchronous addition.

def Lean.Environment.addConstAsync (env : Environment) (constName : Name) (kind : ConstantKind) (reportExts checkMayContain : Bool := true) :

Starts the asynchronous addition of a constant to the environment. The environment is split into a "main" branch that holds a reference to the constant to be added but will block on access until the corresponding information has been added on the "async" environment branch and committed there; see the respective fields of AddConstAsyncResult as well as the [Environment Branches] note for more information.

Equations
  • One or more equations did not get rendered due to their size.

Commits the signature of the constant to the main environment branch. The declaration name must match the name originally given to addConstAsync. It is optional to call this function but can help in unblocking corresponding accesses to the constant on the main branch.

Equations
  • One or more equations did not get rendered due to their size.

Commits the full constant info to the main environment branch. If info? is none, it is taken from the given environment. The declaration name and kind must match the original values given to addConstAsync. The signature must match the previous commitSignature call, if any.

Equations
  • One or more equations did not get rendered due to their size.

Assuming Lean.addDecl has been run for the constant to be added on the async environment branch, commits the full constant info from that call to the main environment, waits for the final kernel environment resulting from the addDecl call, and commits it to the main branch as well, unblocking kernel additions there. All commitConst preconditions apply.

Equations
  • One or more equations did not get rendered due to their size.
Equations
  • One or more equations did not get rendered due to their size.
Equations
Equations
  • One or more equations did not get rendered due to their size.
Equations

Async access mode for environment extensions used in EnvironmentExtension.get/set/modifyState. Depending on their specific uses, extensions may opt out of the strict sync access mode in order to avoid blocking parallel elaboration and/or to optimize accesses. The access mode is set at environment extension registration time but can be overriden at EnvironmentExtension.getState in order to weaken it for specific accesses.

In all modes, the state stored into the .olean file for persistent environment extensions is the result of getState called on the main environment branch at the end of the file, i.e. it encompasses all modifications for all modes but local.

  • sync : AsyncMode

    Default access mode, writing and reading the extension state to/from the full checked environment. This mode ensures the observed state is identical independently of whether or how parallel elaboration is used but getState will block on all prior environment branches by waiting for checked. setState and modifyState do not block.

    While a safe default, any extension that reasonably could be used in parallel elaboration contexts should opt for a weaker mode to avoid blocking unless there is no way to access the correct state without waiting for all prior environment branches, in which case its data management should be restructured if at all possible.

  • local : AsyncMode

    Accesses only the state of the current environment branch. Modifications on other branches are not visible and are ultimately discarded except for the main branch. Provides the fastest accessors, will never block.

    This mode is particularly suitable for extensions where state does not escape from lexical scopes even without parallelism, e.g. ScopedEnvExtensions when setting local entries.

  • mainOnly : AsyncMode

    Like local but panics when trying to modify the state on anything but the main environment branch. For extensions that fulfill this requirement, all modes functionally coincide but this is the safest and most efficient choice in that case, preventing accidental misuse.

    This mode is suitable for extensions that are modified only at the command elaboration level before any environment forks in the command, and in particular for extensions that are modified only at the very beginning of the file.

  • async : AsyncMode

    Accumulates modifications in the checked environment like sync, but getState will panic instead of blocking. Instead findStateAsync should be used, which will access the state of the environment branch corresponding to the passed declaration name, if any, or otherwise the state of the current branch. In other words, at most one environment branch will be blocked on instead of all prior branches. The local state can still be accessed by calling getState with mode local explicitly.

    This mode is suitable for extensions with map-like state where the key uniquely identifies the top-level declaration where it could have been set, e.g. because the key on modification is always the surrounding declaration's name. Any calls to modifyState/setState should assert asyncMayContain with that key to ensure state is never accidentally stored in a branch where it cannot be found by findStateAsync. In particular, this mode is closest to how the environment's own constant map works which asserts the same predicate on modification and provides findAsync? for block-avoiding access.

Instances For
@[reducible, inline]
abbrev Lean.ReplayFn (σ : Type) :
Equations
structure Lean.EnvExtension (σ : Type) :

Environment extension, can only be generated by registerEnvExtension that allocates a unique index for this extension into each environment's extension state's array.

  • idx : Nat
  • mkInitial : IO σ
  • asyncMode : AsyncMode
  • replay? : Option (ReplayFn σ)

    Optional function that, given state before and after realization and newly added constants, replays this change onto a state from another (derived) environment. This function is used only when making changes to an extension inside a realizeConst call, in which case it must be present.

Instances For
Equations

User-defined environment extensions are declared using the initialize command. This command is just syntax sugar for the init attribute. When we import lean modules, the vector stored at envExtensionsRef may increase in size because of user-defined environment extensions. When this happens, we must adjust the size of the env.extensions. This method is invoked when processing imports.

Equations
def Lean.EnvExtension.modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σσ) :

Applies the given function to the extension state. See AsyncMode for details on how modifications from different environment branches are reconciled.

Note that in modes sync and async, f will be called twice, on the local and on the checked state.

Equations
  • One or more equations did not get rendered due to their size.
def Lean.EnvExtension.setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) :

Sets the extension state to the given value. See AsyncMode for details on how modifications from different environment branches are reconciled.

Equations
@[implemented_by _private.Lean.Environment.0.Lean.EnvExtension.getStateUnsafe]
opaque Lean.EnvExtension.getState {σ : Type} [Inhabited σ] (ext : EnvExtension σ) (env : Environment) (asyncMode : AsyncMode := ext.asyncMode) :
σ

Returns the current extension state. See AsyncMode for details on how modifications from different environment branches are reconciled. Panics if the extension is marked as async; see its documentation for more details. Overriding the extension's default AsyncMode is usually not recommended and should be considered only for important optimizations.

@[implemented_by _private.Lean.Environment.0.Lean.EnvExtension.findStateAsyncUnsafe]
opaque Lean.EnvExtension.findStateAsync {σ : Type} [Inhabited σ] (ext : EnvExtension σ) (env : Environment) (declPrefix : Name) :
σ

Returns the final extension state on the environment branch corresponding to the passed declaration name, if any, or otherwise the state on the current branch. In other words, at most one environment branch will be blocked on.

def Lean.registerEnvExtension {σ : Type} (mkInitial : IO σ) (replay? : Option (ReplayFn σ) := none) (asyncMode : EnvExtension.AsyncMode := EnvExtension.AsyncMode.mainOnly) :

Environment extensions can only be registered during initialization. Reasons: 1- Our implementation assumes the number of extensions does not change after an environment object is created. 2- We do not use any synchronization primitive to access envExtensionsRef.

Note that by default, extension state is not stored in .olean files and will not propagate across imports. For that, you need to register a persistent environment extension.

Equations
  • One or more equations did not get rendered due to their size.
@[export lean_mk_empty_environment]
def Lean.mkEmptyEnvironment (trustLevel : UInt32 := 0) :
Equations
  • One or more equations did not get rendered due to their size.
Instances For
structure Lean.PersistentEnvExtension (α β σ : Type) :

An environment extension with support for storing/retrieving entries from a .olean file.

  • α is the type of the entries that are stored in .olean files.
  • β is the type of values used to update the state.
  • σ is the actual state.

For most extensions, α and β coincide. α and ‵β` do not coincide for extensions where the data used to update the state contains elements which cannot be stored in files (for example, closures).

During elaboration of a module, state of type σ can be both read and written. When elaboration is complete, the state of type σ is converted to serialized state of type Array α by exportEntriesFn. To read the current module's state, use PersistentEnvExtension.getState. To modify it, use PersistentEnvExtension.addEntry, with an addEntryFn that performs the appropriate modification.

When a module is loaded, the values saved by all of its dependencies for this PersistentEnvExtension are available as an Array (Array α) via the environment extension, with one array per transitively imported module. The state of type σ used in the current module can be initialized from these imports by specifying a suitable addImportedFn. The addImportedFn runs at the beginning of elaboration for every module, so it's usually better for performance to query the array of imported modules directly, because only a fraction of imported entries is usually queried during elaboration of a module.

The most typical pattern for using PersistentEnvExtension is to set σ to a datatype such as NameMap that efficiently tracks data for the current module. Then, in exportEntriesFn, this type is converted to an array of pairs, sorted by the key. Given ext : PersistentEnvExtension α β σ and env : Environment, the complete array of imported entries sorted by module index can be obtained using (ext.toEnvExtension.getState env).importedEntries. To query the extension for some constant name n, first use env.getModuleIdxFor? n. If it returns none, look up n in the current module's state (the NameMap). If it returns some idx, use ext.getModuleEntries env idx to get the array of entries for n's defining module, and query it using Array.binSearch. This pattern imposes a constraint that the extension can only track metadata that is declared in the same module as the definition to which it applies; relaxing this restriction can make queries slower due to needing to search all modules. If it is necessary to search all modules, it is usually better to initialize the state of type σ once from all imported entries and choose a more efficient search datastructure for it.

Note that addEntryFn is not in IO. This is intentional, and allows us to write simple functions such as

def addAlias (env : Environment) (a : Name) (e : Name) : Environment :=
aliasExtension.addEntry env (a, e)

without using IO. We have many functions like addAlias.

Instances For
Equations
  • One or more equations did not get rendered due to their size.
def Lean.PersistentEnvExtension.addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) :
Equations
  • One or more equations did not get rendered due to their size.

Get the current state of the given extension in the given environment.

Equations
def Lean.PersistentEnvExtension.setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) :

Set the current state of the given extension in the given environment.

Equations
def Lean.PersistentEnvExtension.modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σσ) :

Modify the state of the given extension in the given environment by applying the given function.

Equations
def Lean.PersistentEnvExtension.findStateAsync {α β σ : Type} [Inhabited σ] (ext : PersistentEnvExtension α β σ) (env : Environment) (declPrefix : Name) :
σ

Returns the final extension state on the environment branch corresponding to the passed declaration name, if any, or otherwise the state on the current branch. In other words, at most one environment branch will be blocked on.

Equations
Equations
  • One or more equations did not get rendered due to their size.
@[implemented_by Lean.registerPersistentEnvExtensionUnsafe]
@[specialize #[]]
def Lean.mkStateFromImportedEntries {α σ : Type} (addEntryFn : σασ) (initState : σ) (as : Array (Array α)) :
σ
Equations
Equations
  • One or more equations did not get rendered due to their size.

Get the list of values used to update the state of the given SimplePersistentEnvExtension in the current file.

Equations

Get the current state of the given SimplePersistentEnvExtension.

Equations

Set the current state of the given SimplePersistentEnvExtension. This change is not persisted across files.

Equations

Modify the state of the given extension in the given environment by applying the given function. This change is not persisted across files.

Equations

Returns the final extension state on the environment branch corresponding to the passed declaration name, if any, or otherwise the state on the current branch. In other words, at most one environment branch will be blocked on.

Equations

Environment extension for tagging declarations. Declarations must only be tagged in the module where they were declared.

Equations
Instances For
def Lean.mkTagDeclarationExtension (name : Name := by exact decl_name%) :
Equations
  • One or more equations did not get rendered due to their size.
Equations
  • One or more equations did not get rendered due to their size.
Equations
  • One or more equations did not get rendered due to their size.

Environment extension for mapping declarations to values. Declarations must only be inserted into the mapping in the module where they were declared.

Equations
Instances For
def Lean.mkMapDeclarationExtension {α : Type} (name : Name := by exact decl_name%) :
Equations
  • One or more equations did not get rendered due to their size.
def Lean.MapDeclarationExtension.insert {α : Type} (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) (val : α) :
Equations
  • One or more equations did not get rendered due to their size.
Equations
  • One or more equations did not get rendered due to their size.
Equations
  • One or more equations did not get rendered due to their size.
@[extern lean_save_module_data]
opaque Lean.saveModuleData (fname : System.FilePath) (mod : Name) (data : ModuleData) :
@[extern lean_read_module_data]
@[noinline, export lean_environment_free_regions]

Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in particular, env should be the last reference to any Environment derived from these imports.

Equations
Equations
  • One or more equations did not get rendered due to their size.
@[export lean_write_module]
Equations
def Lean.mkExtNameMap (startingAt : Nat) :

Construct a mapping from persistent extension name to extension index at the array of persistent extensions. We only consider extensions starting with index >= startingAt.

Equations
  • One or more equations did not get rendered due to their size.
@[extern 2 lean_update_env_attributes]

"Forward declaration" needed for updating the attribute table with user-defined attributes. User-defined attributes are declared using the initialize command. The initialize command is just syntax sugar for the init attribute. The init attribute is initialized after the attributeExtension is initialized. We cannot change the order since the init attribute is an attribute, and requires this extension. The attributeExtension initializer uses attributeMapRef to initialize the attribute mapping. When we a new user-defined attribute declaration is imported, attributeMapRef is updated. Later, we set this method with code that adds the user-defined attributes that were imported after we initialized attributeExtension.

@[extern 1 lean_get_num_attributes]

"Forward declaration" for retrieving the number of builtin attributes.

def Lean.throwAlreadyImported {α : Type} (s : ImportState) (const2ModIdx : Std.HashMap Name ModuleIdx) (modIdx : Nat) (cname : Name) :
IO α
Equations
  • One or more equations did not get rendered due to their size.
@[inline]
def Lean.ImportStateM.run {α : Type} (x : ImportStateM α) (s : ImportState := { moduleNameSet := , moduleNames := #[], moduleData := #[], regions := #[] }) :
Equations
def Lean.finalizeImport (s : ImportState) (imports : Array Import) (opts : Options) (trustLevel : UInt32 := 0) (leakEnv : Bool := false) :

Construct environment from importModulesCore results.

If leakEnv is true, we mark the environment as persistent, which means it will not be freed. We set this when the object would survive until the end of the process anyway. In exchange, RC updates are avoided, which is especially important when they would be atomic because the environment is shared across threads (potentially, storing it in an IO.Ref is sufficient for marking it as such).

Equations
  • One or more equations did not get rendered due to their size.
@[export lean_import_modules]
def Lean.importModules (imports : Array Import) (opts : Options) (trustLevel : UInt32 := 0) (plugins : Array System.FilePath := #[]) (leakEnv : Bool := false) :
Equations
  • One or more equations did not get rendered due to their size.
unsafe def Lean.withImportModules {α : Type} (imports : Array Import) (opts : Options) (trustLevel : UInt32 := 0) (act : EnvironmentIO α) :
IO α

Create environment object from imports and free compacted regions after calling act. No live references to the environment object or imported objects may exist after act finishes.

Equations

Environment extension for tracking all namespace declared by users.

Enables/disables kernel diagnostics.

Equations

Return true if n is the name of a namespace in env.

Equations

Return a set containing all namespaces in env.

Equations
@[export lean_display_stats]
Equations
  • One or more equations did not get rendered due to their size.
@[extern lean_eval_const]
unsafe opaque Lean.Environment.evalConst (α : Type u_1) (env : Environment) (opts : Options) (constName : Name) :

Evaluate the given declaration under the given environment to a value of the given type. This function is only safe to use if the type matches the declaration's type in the environment and if enableInitializersExecution has been used before importing any modules.

unsafe def Lean.Environment.evalConstCheck (α : Type) (env : Environment) (opts : Options) (typeName constName : Name) :

Like evalConst, but first check that constName indeed is a declaration of type typeName. Note that this function cannot guarantee that typeName is in fact the name of the type α.

Equations
  • One or more equations did not get rendered due to their size.
Equations
  • One or more equations did not get rendered due to their size.

Plumbing function for Lean.Meta.realizeConst; see documentation there.

Equations
  • One or more equations did not get rendered due to their size.
Equations
  • One or more equations did not get rendered due to their size.

Kernel API #

@[extern lean_kernel_is_def_eq]

Kernel isDefEq predicate. We use it mainly for debugging purposes. Recall that the kernel type checker does not support metavariables. When implementing automation, consider using the MetaM methods.

Equations
@[extern lean_kernel_whnf]

Kernel WHNF function. We use it mainly for debugging purposes. Recall that the kernel type checker does not support metavariables. When implementing automation, consider using the MetaM methods.

@[extern lean_kernel_check]

Kernel typecheck function. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the MetaM methods.

@[always_inline]
Equations
def Lean.mkDefinitionValInferrringUnsafe {m : TypeType} [Monad m] [MonadEnv m] (name : Name) (levelParams : List Name) (type value : Expr) (hints : ReducibilityHints) :

Constructs a DefinitionVal, inferring the unsafe field

Equations
  • One or more equations did not get rendered due to their size.
Equations
  • One or more equations did not get rendered due to their size.