diff --git a/LeanPy/Kernel.lean b/LeanPy/Kernel.lean index c2547e5..7554594 100644 --- a/LeanPy/Kernel.lean +++ b/LeanPy/Kernel.lean @@ -107,7 +107,7 @@ def allDecls (_ : Unit) : IO String := do match (← envRef.get) with | some env => let r ← IO.mkRef (#[] : Array String) - env.constants.forM (fun n _ => do r.modify (·.push (toString n))) + env.constants.forM (fun n _ => do r.modify (·.push (n.toString (escape := false)))) let acc ← r.get return "\n".intercalate acc.qsort.toList | none => return "" @@ -117,7 +117,7 @@ def catalogPy (_ : Unit) : IO String := do match (← envRef.get) with | some env => let names := envCatalog env - let strs := names.map toString + let strs := names.map (·.toString (escape := false)) return "\n".intercalate strs.qsort.toList | none => return "" @@ -127,22 +127,31 @@ def search (needle : String) : IO String := do | some env => let r ← IO.mkRef (#[] : Array String) env.constants.forM fun n _ => do - let s := toString n + let s := n.toString (escape := false) if needle.isEmpty || ((s.splitOn needle).length > 1) then r.modify (·.push s) let acc ← r.get return "\n".intercalate acc.qsort.toList | none => return "" +/-- A declaration name from Python: escaped (`Foo.«a b»`, as `String.toName` +reads it) or unescaped, as the kernel ops now return names (`Foo.a b`, split +on dots). -/ +def parseName (s : String) : Name := + let n := s.toName + if n.isAnonymous && !s.isEmpty then + (s.splitOn ".").foldl Name.str .anonymous + else n + @[python "leanpy_kernel_decl_exists"] def declExists (name : String) : IO Bool := do match (← envRef.get) with - | some env => return (env.find? name.toName).isSome + | some env => return (env.find? (parseName name)).isSome | none => return false @[python "leanpy_kernel_decl_type"] def declType (name : String) : IO String := runCore do - let n := name.toName + let n := parseName name match (← getEnv).find? n with | none => return "" | some info => @@ -150,7 +159,7 @@ def declType (name : String) : IO String := runCore do @[python "leanpy_kernel_decl_value"] def declValue (name : String) : IO String := runCore do - let n := name.toName + let n := parseName name match (← getEnv).find? n with | none => return "" | some info => @@ -162,23 +171,23 @@ def declValue (name : String) : IO String := runCore do def moduleOfNameStr (name : String) : IO String := do match (← envRef.get) with | some env => - match module_of_name env name.toName with - | some n => return toString n + match module_of_name env (parseName name) with + | some n => return n.toString (escape := false) | none => return "" | none => return "" @[python "leanpy_kernel_is_internal_name_str"] def isInternalNameStr (name : String) : IO Bool := - return isNameInternal name.toName + return isNameInternal (parseName name) @[python "leanpy_kernel_decl_axioms"] def declAxioms (name : String) : IO String := runCore do let env ← getEnv - let n := name.toName + let n := parseName name if env.find? n |>.isNone then return "" let axioms ← collectAxioms n - let names := axioms.map toString |>.qsort + let names := axioms.map (·.toString (escape := false)) |>.qsort return "\n".intercalate names.toList /-! ## Elaboration -/ @@ -660,23 +669,95 @@ def frontendFindSourcePath (moduleName : String) : IO String := do return p.toString catch e => return s!"" +/-- Set up the frontend for `source` against `env`. A header (`module`, +`prelude`, `import …`) is skipped when every module it imports is already in +`env`; otherwise this throws, naming the missing modules. (Before, the header +was parsed as commands, failed, and the error was dropped: empty output.) -/ +def frontendContextState (env : Environment) (source : String) (fileName : String) : + IO (Elab.Frontend.Context × Elab.Frontend.State × MessageLog) := do + let inputCtx := Parser.mkInputContext source fileName + let (header, parserState, headerMsgs) ← Parser.parseHeader inputCtx + let hstx : Elab.HeaderSyntax := header + let missing := (hstx.imports (includeInit := false)).filter + fun i => (env.getModuleIdx? i.module).isNone + unless missing.isEmpty do + let ms := missing.toList.map (·.module.toString (escape := false)) + throw <| IO.userError s!"the source imports modules not in the loaded environment: {", ".intercalate ms}; load them first (Kernel.load)" + let commandState := Elab.Command.mkState env {} {} + let ctx : Elab.Frontend.Context := { inputCtx } + let st : Elab.Frontend.State := { + commandState := { commandState with infoState.enabled := true }, + parserState, + cmdPos := parserState.pos } + return (ctx, st, headerMsgs) + +/-- Run `f` on each command of `source` against `env`: its results and the +environment after the last command. -/ +def frontendRun (env : Environment) (source : String) (fileName : String) + (f : Pantograph.Frontend.CompilationStep → IO α) : + IO (List α × Environment × MessageLog) := do + let (ctx, st, headerMsgs) ← frontendContextState env source fileName + let m : Pantograph.Frontend.FrontendM (List α) := + Pantograph.Frontend.mapCompilationSteps fun step => do f step + let (results, st') ← (m.run {} |>.run ctx |>.run st) + return (results, st'.commandState.env, headerMsgs) + /-- Process a single Lean source string against the current environment. -Returns a newline-separated list of constants defined per command. -/ +Returns a newline-separated list of constants defined per command (names +unescaped), commands separated by `\n---\n`; `` on failure. -/ @[python "leanpy_kernel_frontend_process"] def frontendProcess (source : String) : IO String := do match (← envRef.get) with | none => return "no environment loaded" | some env => try - let (fctx, fstate) ← Pantograph.Frontend.createContextStateFromFile source "" (env? := some env) {} - let m : Pantograph.Frontend.FrontendM (List String) := - Pantograph.Frontend.mapCompilationSteps fun step => do - let names ← step.newConstants - return "\n".intercalate (names.toList.map toString) - let (steps, _) ← (m.run {} |>.run fctx |>.run fstate) + let (steps, _, _) ← frontendRun env source "" fun step => do + let names ← step.newConstants + return "\n".intercalate (names.toList.map (·.toString (escape := false))) return "\n---\n".intercalate steps catch e => return s!"" +/-- A message as JSON: severity, its range (1-based lines, 0-based columns, +in the processed source) and its text. -/ +def messageJson (m : Message) : IO Json := do + let severity := match m.severity with + | .error => "error" | .warning => "warning" | .information => "information" + let endPos := m.endPos.getD m.pos + return Json.mkObj [ + ("severity", severity), ("line", m.pos.line), ("column", m.pos.column), + ("endLine", endPos.line), ("endColumn", endPos.column), + ("text", ← m.data.toString)] + +/-- Process `source` against the current environment, returning JSON: +`{"error", "header": [messages], "commands": [{"line", "constants", +"messages"}]}`, `error` null unless the source could not be processed (no +environment, an import not loaded); elaboration errors are messages. With `inheritEnv`, the active environment becomes the one +after the source, so later calls (`process`, `decl_type`, `decl_axioms`, +`goal_create`, …) see its declarations; on an exception it is unchanged. -/ +@[python "leanpy_kernel_frontend_process_json"] +def frontendProcessJson (source : String) (inheritEnv : Bool) : IO String := do + match (← envRef.get) with + | none => + return (Json.mkObj [("error", "no environment loaded"), + ("header", Json.arr #[]), ("commands", Json.arr #[])]).compress + | some env => + try + let (cmds, env', headerMsgs) ← frontendRun env source "" fun step => do + let names ← step.newConstants + let msgs ← step.msgs.mapM messageJson + let line := (step.fileMap.toPosition (step.stx.getPos?.getD 0)).line + return Json.mkObj [ + ("line", line), + ("constants", toJson ((names.toList.map (·.toString (escape := false))).toArray.qsort (· < ·))), + ("messages", Json.arr msgs.toArray)] + let header ← headerMsgs.toList.mapM messageJson + if inheritEnv then envRef.set (some env') + return (Json.mkObj [("error", Json.null), + ("header", Json.arr header.toArray), ("commands", Json.arr cmds.toArray)]).compress + catch e => + return (Json.mkObj [("error", e.toString), + ("header", Json.arr #[]), ("commands", Json.arr #[])]).compress + /-- Collect all `sorry` positions in the source as a draftable goal state. Returns the goal state pretty-printed (for now). -/ @[python "leanpy_kernel_frontend_collect_sorrys"] @@ -685,7 +766,7 @@ def frontendCollectSorrys (source : String) : IO (Option GoalState × String) := | none => return (none, "no environment loaded") | some env => try - let (fctx, fstate) ← Pantograph.Frontend.createContextStateFromFile source "" (env? := some env) {} + let (fctx, fstate, _) ← frontendContextState env source "" let m : Pantograph.Frontend.FrontendM (List Pantograph.Frontend.InfoWithContext) := do let xss ← Pantograph.Frontend.mapCompilationSteps fun step => Pantograph.Frontend.collectSorrys step return xss.flatten diff --git a/examples/kernel/README.md b/examples/kernel/README.md index b2c98ac..f7f7149 100644 --- a/examples/kernel/README.md +++ b/examples/kernel/README.md @@ -23,6 +23,27 @@ The bridge imports `LeanPy.Kernel` and `LeanPy.Export`. It does not import the `LeanPy` umbrella or request a Regex archive, although building the existing LeanPy static library still builds its Regex dependency. +## Elaborating source against the project + +`Kernel.elaborate(source, inherit_env=False)` processes Lean commands against +the loaded environment and returns a `ProcessResult`: per command the +constants it added (names unescaped) and Lean's messages (`severity`, `line`, +`column`, `end_line`, `end_column`, `text`), plus `ok`, `errors` and `error`. +A header (`module`, `import …`) is skipped when its imports are loaded, and is +an `error` naming the missing modules otherwise. With `inherit_env=True` the +declarations persist: later `elaborate`, `decl_type`, `decl_axioms` and goal +calls see them, so a translator can elaborate and check one fragment at a time. + +```python +r = kernel.elaborate("def x : Nat := 1", inherit_env=True) +assert r.ok, "\n".join(map(str, r.errors)) +print(kernel.decl_type("x")) +``` + +The runtime is the toolchain of the project `LeanLibrary.from_lake` loads, +whatever the current directory; `LEANPY_TOOLCHAIN`, `LEANPY_LEAN_PREFIX` or +`lean_py.utils.set_toolchain` override it. + ## Temporary dependency workaround Regex `v4.34.0-rc1` triggers a Lean 4.35 `grind` panic in diff --git a/lean_py/_parse.py b/lean_py/_parse.py index c5d2cc3..a63a20d 100644 --- a/lean_py/_parse.py +++ b/lean_py/_parse.py @@ -70,7 +70,7 @@ def find_lean_header() -> Path: """Locate lean.h via the active Lean toolchain. Strategy: - 1. Ask `lean --print-prefix` for the toolchain sysroot, look for + 1. Ask `utils.lean_prefix` for the toolchain sysroot, look for `/include/lean/lean.h`. This is the canonical location and works regardless of whether elan, lakefile, or a manual install picked the toolchain. @@ -87,11 +87,12 @@ def find_lean_header() -> Path: return cand try: - prefix = subprocess.check_output(["lean", "--print-prefix"], text=True).strip() - header = Path(prefix) / "include" / "lean" / "lean.h" + from lean_py.utils import lean_include_dir # independent of the cwd + + header = lean_include_dir() / "lean" / "lean.h" if header.exists(): return header - except (FileNotFoundError, subprocess.CalledProcessError): + except (FileNotFoundError, RuntimeError): pass toolchain_file = Path(__file__).parent.parent / "lean-toolchain" diff --git a/lean_py/kernel.py b/lean_py/kernel.py index 39f8763..f6ef160 100644 --- a/lean_py/kernel.py +++ b/lean_py/kernel.py @@ -28,8 +28,9 @@ from __future__ import annotations +import json from collections.abc import Iterable -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any @@ -67,6 +68,87 @@ def parse(cls, encoded: str, kernel: Kernel, raw_state: Any) -> TacticResult: return cls(status, messages, state) +@dataclass(frozen=True) +class Message: + """A Lean message: severity (``"error"``, ``"warning"``, + ``"information"``), its range in the processed source (1-based lines, + 0-based columns) and its text.""" + + severity: str + line: int + column: int + end_line: int + end_column: int + text: str + + @classmethod + def from_json(cls, d: dict) -> Message: + return cls(d["severity"], d["line"], d["column"], d["endLine"], d["endColumn"], d["text"]) + + def __str__(self) -> str: + return f"{self.line}:{self.column}: {self.severity}: {self.text}" + + +@dataclass(frozen=True) +class Command: + """One command of a processed source: the line it starts on, the + constants it added (names unescaped) and its messages.""" + + line: int + constants: list[str] + messages: list[Message] + + +@dataclass(frozen=True) +class ProcessResult: + """The result of :meth:`Kernel.elaborate`. + + Attributes: + commands: each command's constants and messages, in order. + header: messages from parsing the source's header, if any. + error: why the source could not be processed at all (no environment + loaded, an imported module not loaded), else ``None``. + """ + + commands: list[Command] = field(default_factory=list) + header: list[Message] = field(default_factory=list) + error: str | None = None + + @property + def messages(self) -> list[Message]: + """Every message, the header's first.""" + return [*self.header, *(m for c in self.commands for m in c.messages)] + + @property + def errors(self) -> list[Message]: + """The messages of severity ``"error"``.""" + return [m for m in self.messages if m.severity == "error"] + + @property + def constants(self) -> list[str]: + """Every constant the source added, in command order.""" + return [n for c in self.commands for n in c.constants] + + @property + def ok(self) -> bool: + """Processed, with no error message.""" + return self.error is None and not self.errors + + @classmethod + def from_json(cls, encoded: str) -> ProcessResult: + d = json.loads(encoded) + return cls( + [ + Command( + c["line"], list(c["constants"]), [Message.from_json(m) for m in c["messages"]] + ) + for c in d["commands"] + ], + [Message.from_json(m) for m in d["header"]], + d["error"], + ) + + class GoalState: """Opaque handle to a Lean ``GoalState``. Methods dispatch back into the underlying Lean library.""" @@ -381,10 +463,28 @@ def find_source_path(self, module_name: str) -> str: def process(self, source: str) -> str: """Process Lean source code against the current environment. - Returns a multi-line string of new constants per command, separated by - ``\\n---\\n``.""" + Returns a multi-line string of new constants per command (names + unescaped), separated by ``\\n---\\n``, or ````. A header + (``module``, ``import …``) is skipped when its imports are loaded and + is an error otherwise. Messages are dropped: see :meth:`elaborate`.""" return self._lib.leanpy_kernel_frontend_process(source) + def elaborate(self, source: str, *, inherit_env: bool = False) -> ProcessResult: + """Process Lean source code against the current environment, keeping + Lean's messages. + + A header (``module``, ``prelude``, ``import …``) is skipped when every + module it imports is already loaded; otherwise ``error`` names the + missing modules and nothing is elaborated. With ``inherit_env=True`` + the active environment becomes the one after the source, so later + calls (``elaborate``, ``decl_type``, ``decl_axioms``, ``goal_create``, + …) see its declarations. A declaration that fails to elaborate is + still added (with ``sorryAx``) and reported; check ``ok`` / ``errors``. + """ + return ProcessResult.from_json( + self._lib.leanpy_kernel_frontend_process_json(source, inherit_env) + ) + def collect_sorrys(self, source: str) -> tuple[GoalState | None, str]: """Extract all `sorry` placeholders in ``source`` as a draftable :class:`GoalState`. Returns ``(state, message)`` — state is ``None`` if @@ -407,4 +507,4 @@ def expr_proj_to_app(self, src: str) -> str: return self._lib.leanpy_kernel_delab_expr_proj_to_app(src) -__all__ = ["Kernel", "GoalState", "TacticResult"] +__all__ = ["Command", "GoalState", "Kernel", "Message", "ProcessResult", "TacticResult"] diff --git a/lean_py/library.py b/lean_py/library.py index 22419fb..df122cd 100644 --- a/lean_py/library.py +++ b/lean_py/library.py @@ -25,7 +25,7 @@ import subprocess import sys from collections.abc import Callable -from ctypes import POINTER, c_uint8, c_void_p +from ctypes import POINTER, c_double, c_uint8, c_void_p from pathlib import Path from typing import Any @@ -34,7 +34,17 @@ from lean_py.lean_ffi import get_lean_ffi from lean_py.marshal import LeanInductiveValue, Marshaller, TypeWrapper, _CtorMeta from lean_py.registry import FuncInfo, LibraryRegistry, TypeInfo -from lean_py.utils import lean_lib_dir, run_command, shared_lib_extension +from lean_py.utils import ( + PREFIX_ENV, + bundle_dir, + lean_lib_dir, + lean_prefix, + pinned_toolchain, + run_command, + set_toolchain, + shared_lib_extension, + toolchain_of, +) def _list_init_symbols(dylib: Path) -> list[str]: @@ -277,6 +287,10 @@ def _wrapper(*args): if isinstance(w.ctype, type) and issubclass(w.ctype, ctypes._Pointer): # Convert pointer args to raw pointer values to match cfn.argtypes. v = ctypes.cast(v, c_void_p).value if v is not None else 0 + elif w.ctype is c_double: + # A top-level Float is passed by value; `to_lean` boxes it for + # nested (generic) positions only. + v = float(a) elif w.ctype in (c_uint8, ctypes.c_uint16) and not isinstance(v, int): # Enum/Bool: `to_lean` produces a boxed scalar pointer so it # round-trips through nested struct fields, but a top-level @@ -289,6 +303,8 @@ def _wrapper(*args): if return_is_pointer: result_ptr = ctypes.cast(c_void_p(result_raw), LObjPtr) return rwrap.from_lean(result_ptr) + if rwrap.ctype is c_double: + return float(result_raw) # a top-level Float comes back by value return rwrap.from_lean(result_raw) _wrapper.__name__ = finfo.exportName @@ -326,6 +342,11 @@ def from_lake( lake_path = Path(lake_dir).resolve() if not lake_path.is_dir(): raise FileNotFoundError(f"not a Lake project directory: {lake_path}") + # The runtime must be the project's toolchain, whatever the cwd: pin + # it unless the caller already has (`utils.set_toolchain`, the env). + if pinned_toolchain() is None and not os.environ.get(PREFIX_ENV): + if toolchain := toolchain_of(lake_path): + set_toolchain(toolchain) if build: run_command(["lake", "build"], cwd=lake_path) @@ -417,6 +438,11 @@ def __init__(self, dylib_path: str | os.PathLike, library_name: str): self.path = Path(dylib_path) self.name = library_name self.ffi = get_lean_ffi() + # Lean code that asks for its sysroot (`Lean.findSysroot`, e.g. the + # kernel's `init_search`) runs `lean --print-prefix` from the cwd + # unless LEAN_SYSROOT is set: point it at the runtime just loaded. + if bundle_dir() is None: + os.environ.setdefault("LEAN_SYSROOT", str(lean_prefix())) # Ensure the dylib can resolve its @rpath references to Lean's runtime. _ensure_rpath(self.path) # Use `PyDLL` so that ctypes does NOT release the GIL when calling diff --git a/lean_py/utils.py b/lean_py/utils.py index 1849683..766433f 100644 --- a/lean_py/utils.py +++ b/lean_py/utils.py @@ -38,10 +38,65 @@ def lean_toolchain_version() -> str: return out +PREFIX_ENV = "LEANPY_LEAN_PREFIX" +"""An explicit toolchain sysroot (what ``lean --print-prefix`` prints).""" + +TOOLCHAIN_ENV = "LEANPY_TOOLCHAIN" +"""An explicit toolchain, e.g. ``leanprover/lean4:v4.35.0``, for elan.""" + +_pinned: str | None = None + + +def toolchain_of(path: str | os.PathLike) -> str | None: + """The toolchain a ``lean-toolchain`` file names, given the file or the + directory holding it; ``None`` if there is none.""" + p = Path(path) + f = p / "lean-toolchain" if p.is_dir() else p + return f.read_text().strip() if f.is_file() else None + + +def set_toolchain(toolchain: str | os.PathLike | None) -> None: + """Pin the toolchain :func:`lean_prefix` resolves: a toolchain name, or a + ``lean-toolchain`` file or the directory holding one (``None`` unpins). + + Takes effect for the runtime only if it has not been loaded yet (the + first :class:`~lean_py.LeanLibrary` loads it, and it cannot change in a + process).""" + global _pinned + if toolchain is None: + _pinned = None + else: + p = Path(toolchain) + _pinned = toolchain_of(p) if p.exists() else str(toolchain) + lean_prefix.cache_clear() + + +def pinned_toolchain() -> str | None: + """The toolchain pinned by :func:`set_toolchain` or ``LEANPY_TOOLCHAIN``.""" + return _pinned or os.environ.get(TOOLCHAIN_ENV) or None + + @lru_cache(maxsize=1) def lean_prefix() -> Path: - """Return the path printed by `lean --print-prefix`.""" - return Path(run_command(["lean", "--print-prefix"])) + """The Lean toolchain's sysroot, independent of the current directory. + + In order: ``LEANPY_LEAN_PREFIX``; the toolchain pinned by + :func:`set_toolchain` or ``LEANPY_TOOLCHAIN`` (or elan's own + ``ELAN_TOOLCHAIN``); lean.py's own ``lean-toolchain`` when it runs from a + checkout; else ``lean --print-prefix`` as elan resolves it from the + current directory (the old behaviour). A toolchain is resolved by + running ``lean --print-prefix`` with ``ELAN_TOOLCHAIN`` set, which elan + honours over any ``lean-toolchain`` file. + """ + if explicit := os.environ.get(PREFIX_ENV): + return Path(explicit) + toolchain = ( + pinned_toolchain() + or os.environ.get("ELAN_TOOLCHAIN") + or toolchain_of(Path(__file__).resolve().parent.parent) + ) + env = None if toolchain is None else {**os.environ, "ELAN_TOOLCHAIN": toolchain} + return Path(run_command(["lean", "--print-prefix"], env=env)) def bundle_dir() -> Path | None: diff --git a/tests/lean/TestLib.lean b/tests/lean/TestLib.lean index 9f8b514..d23ae14 100644 --- a/tests/lean/TestLib.lean +++ b/tests/lean/TestLib.lean @@ -320,4 +320,9 @@ def powInt (base : Int) (exp : Int) : IO Int := do init () (← Py.pow (← Py.ofInt64 base) (← Py.ofInt64 exp)).toInt +/-- A top-level Float in and out, beside a Nat and an Array Float. -/ +@[python "py_float_affine"] +def floatAffine (x : Float) (k : Nat) (ys : Array Float) : Float := + x * k.toFloat + ys.foldl (· + ·) 0 + #export_python_registry "TestLib" diff --git a/tests/test_kernel_process.py b/tests/test_kernel_process.py new file mode 100644 index 0000000..e348daa --- /dev/null +++ b/tests/test_kernel_process.py @@ -0,0 +1,160 @@ +"""Tests for `Kernel.elaborate` and the frontend fixes: Lean's messages kept, +`inherit_env` persisting declarations across calls, a source header skipped +(or refused, naming the missing modules), names returned unescaped, and +`lean_prefix` independent of the current directory.""" + +from __future__ import annotations + +import os + +import pytest + +from lean_py import utils +from lean_py.kernel import Kernel, ProcessResult + + +@pytest.fixture(scope="module") +def kernel(example_lib) -> Kernel: + k = Kernel(example_lib) + if not k.is_loaded(): + k.init_search("") + k.load(["Init"]) + return k + + +# ---------------------------------------------------------------------- +# (a) messages and inherit_env +# ---------------------------------------------------------------------- + + +def test_elaborate_reports_constants_per_command(kernel): + r = kernel.elaborate("def kpA : Nat := 1\ntheorem kpB : kpA = 1 := rfl\n") + assert isinstance(r, ProcessResult) + assert r.ok and r.error is None and r.errors == [] + assert [c.constants for c in r.commands] == [["kpA"], ["kpB"]] + assert [c.line for c in r.commands] == [1, 2] + + +def test_elaborate_keeps_error_messages_with_positions(kernel): + r = kernel.elaborate('def kpC : Nat := 1\ndef kpD : Nat := "no"\n') + assert not r.ok + (err,) = r.errors + assert err.severity == "error" and err.line == 2 + assert "String" in err.text or "mismatch" in err.text + # the failed declaration is still added (with sorryAx), as before + assert "kpD" in r.constants + + +def test_elaborate_keeps_information_messages(kernel): + r = kernel.elaborate("#check (1 : Nat)\n") + assert r.ok + (m,) = r.messages + assert m.severity == "information" and "Nat" in m.text + + +def test_without_inherit_env_declarations_do_not_persist(kernel): + r = kernel.elaborate("def kpTransient : Nat := 5\n") + assert r.ok + assert not kernel.decl_exists("kpTransient") + + +def test_inherit_env_persists_declarations_across_calls(kernel): + r = kernel.elaborate("def kpKept : Nat := 7\n", inherit_env=True) + assert r.ok + assert kernel.decl_exists("kpKept") + assert "Nat" in kernel.decl_type("kpKept") + r2 = kernel.elaborate("theorem kpKeptEq : kpKept = 7 := rfl\n", inherit_env=True) + assert r2.ok, r2.errors + assert kernel.decl_axioms("kpKeptEq") == [] # rfl: no axioms, no sorry + assert kernel.elaborate("example : kpKept = 7 := kpKeptEq\n").ok + + +def test_inherit_env_with_errors_still_persists_what_elaborated(kernel): + r = kernel.elaborate("def kpGood : Nat := 1\ndef kpBad : Nat := true\n", inherit_env=True) + assert not r.ok + assert kernel.decl_exists("kpGood") + + +# ---------------------------------------------------------------------- +# (b) the header +# ---------------------------------------------------------------------- + + +def test_a_header_of_loaded_imports_is_skipped(kernel): + r = kernel.elaborate("import Init\n\ndef kpH : Nat := 2\n") + assert r.ok and r.constants == ["kpH"] + assert "kpH2" in kernel.process("import Init\ndef kpH2 : Nat := 3\n") + + +def test_a_module_header_is_skipped(kernel): + r = kernel.elaborate("module\nimport Init\n\ndef kpM : Nat := 4\n") + assert r.ok and r.constants == ["kpM"] + + +def test_a_header_importing_an_unloaded_module_is_an_error(kernel): + r = kernel.elaborate("import Definitely.Not.Loaded\ndef kpX : Nat := 1\n") + assert not r.ok and r.commands == [] + assert r.error is not None and "Definitely.Not.Loaded" in r.error + out = kernel.process("import Definitely.Not.Loaded\ndef kpX : Nat := 1\n") + assert out.startswith("