lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,48 @@
1
+ """`--json` keeps stdout for the JSON document alone (data on stdout, chatter on stderr).
2
+
3
+ A command that streams progress while it works (stage lines, judge output, warnings) runs that work
4
+ under `chatter_to_stderr()` and prints its JSON document after the block. Inside the block both the
5
+ Python-level `sys.stdout` and file descriptor 1 point at stderr, so a `print()` without
6
+ `file=sys.stderr`, a log echoed to `sys.stdout`, and a child process that inherits fd 1 all land on
7
+ stderr; `json.loads(stdout)` then parses what the caller captured.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import os
14
+ import sys
15
+ from typing import Iterator
16
+
17
+
18
+ @contextlib.contextmanager
19
+ def chatter_to_stderr(active: bool = True) -> Iterator[None]:
20
+ """While active, send everything written to stdout (Python and fd 1) to stderr; restore after."""
21
+ if not active:
22
+ yield
23
+ return
24
+ for stream in (sys.stdout, sys.stderr):
25
+ try:
26
+ stream.flush()
27
+ except (OSError, ValueError):
28
+ pass
29
+ saved = None
30
+ try:
31
+ saved = os.dup(1)
32
+ os.dup2(2, 1)
33
+ except OSError: # no fd 1 or fd 2 (a closed descriptor): Python-level only
34
+ if saved is not None:
35
+ os.close(saved)
36
+ saved = None
37
+ try:
38
+ with contextlib.redirect_stdout(sys.stderr):
39
+ yield
40
+ finally:
41
+ for stream in (sys.stdout, sys.stderr):
42
+ try:
43
+ stream.flush()
44
+ except (OSError, ValueError):
45
+ pass
46
+ if saved is not None:
47
+ os.dup2(saved, 1)
48
+ os.close(saved)
@@ -0,0 +1,289 @@
1
+ # lean-pkg lake hygiene -- what a Lake build log and LEAN_PATH must show before a receipt trusts them
2
+ """Two Lake behaviours that can make a verification log say less than it seems to (checked against the Lake
3
+ and Lean sources of v4.35.0-rc2):
4
+
5
+ 1. The local artifact cache. A package reads Lake's artifact cache unless it is switched off
6
+ (`Package.isArtifactCacheReadable`: the package's own `enableArtifactCache`, else the workspace's, which is
7
+ LAKE_ARTIFACT_CACHE and then the root package's setting, else true; a package lakefile's
8
+ `enableArtifactCache = true` wins over LAKE_ARTIFACT_CACHE=false). The cache lives in LAKE_CACHE_DIR, else
9
+ under the toolchain or ~/.cache/lake; LAKE_CACHE_DIR="" does not disable it (the root's .lake/cache is used).
10
+ `--no-cache` / LAKE_NO_CACHE govern downloads only. A module restored from it is reported `Reused` and its
11
+ `declaration uses sorry` warning is not printed, so a sorry count scraped from the log can read 0. Lake
12
+ prints such a job (`<icon> [i/n] Reused M`, also `Replayed`, `Unpacked`) only when it has output or with
13
+ `-v`, so the defence is a fresh, empty LAKE_CACHE_DIR with LAKE_ARTIFACT_CACHE=false and a fresh tree; a
14
+ log that still shows a root-package module Reused, Replayed or Unpacked is refused (`cache_reuse_problems`).
15
+ A `Replayed` line for a module the log already showed `Built` is not a restore: a later `lake lean FILE`
16
+ re-prints the stored warnings of the modules it imports (`restored_jobs`). Only an earlier `Built`
17
+ exonerates; a cache line before the module's `Built`, or with none, still counts.
18
+
19
+ 2. LEAN_PATH order. Lake's `Workspace.leanPath` lists the root package's lib directory LAST, and Lean's
20
+ `SearchPath.findWithExt` takes the FIRST entry holding `<R>/` or `<R>.olean` for a module whose root
21
+ component is R. A dependency whose build directory holds `<R>/...` therefore serves its own module to
22
+ `lake env lean FILE` (and to anything else started under `lake env`). `lake build` and `lake lean FILE` pass
23
+ explicit module paths and are not affected. `shadow_hits` names every LEAN_PATH entry, other than the root
24
+ package's own lib directory, that holds a root namespace of the root package.
25
+
26
+ SHADOW_CHECK_SH is the same check as a shell function; `receipt slurm --template`, comparator-check.sh and
27
+ verify-comparator.sh carry it verbatim (tests/test_lake_hygiene.py compares the copies)."""
28
+
29
+ from __future__ import annotations
30
+
31
+ import os
32
+ import pathlib
33
+ import re
34
+ import subprocess
35
+ import tomllib
36
+
37
+ CACHE_VERBS = ("Reused", "Replayed", "Unpacked")
38
+ _ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
39
+ # Lake's job line (Lake/Build/Run.lean reportJob): `<icon> [i/n][ (Optional)] <verb> <caption>[ (time)]`.
40
+ JOB_LINE_RE = re.compile(r"\[\d+/\d+\](?: \(Optional\))? (Built|Reused|Replayed|Unpacked|Fetched|Ran|Canceled|"
41
+ r"Building|Reusing|Replaying|Unpacking|Fetching|Running) (\S+)")
42
+ # The template's markers around the build command; the audit after it (`lake lean`) replays the modules it
43
+ # imports, which is not a restored build.
44
+ BUILD_BEGIN, BUILD_END = "lean-pkg-build: begin", "lean-pkg-build: end"
45
+ ROOT_LIB_DIR = pathlib.PurePosixPath(".lake") / "build" / "lib" / "lean"
46
+ LEAN_PATH_TIMEOUT = 600
47
+
48
+
49
+ def strip_ansi(text: str) -> str:
50
+ return _ANSI_RE.sub("", text)
51
+
52
+
53
+ def build_section(text: str) -> str:
54
+ """The part of a log between the template's build markers (the first begin, the following end), or the
55
+ whole log when it has none."""
56
+ lines = text.splitlines()
57
+ try:
58
+ i = next(n for n, x in enumerate(lines) if x.strip() == BUILD_BEGIN)
59
+ except StopIteration:
60
+ return text
61
+ j = next((n for n in range(i + 1, len(lines)) if lines[n].strip() == BUILD_END), len(lines))
62
+ return "\n".join(lines[i + 1:j]) + "\n"
63
+
64
+
65
+ def job_lines(text: str) -> list[tuple[str, str]]:
66
+ """[(verb, target)] of Lake's job lines in a log; a target's `:facet` suffix is dropped."""
67
+ out = []
68
+ for m in JOB_LINE_RE.finditer(strip_ansi(text)):
69
+ out.append((m.group(1), m.group(2).split(":", 1)[0]))
70
+ return out
71
+
72
+
73
+ def restored_jobs(jobs) -> list[tuple[str, str]]:
74
+ """The distinct (verb, target) cache jobs (CACHE_VERBS) of [(verb, target)], in log order, for which no
75
+ EARLIER `Built` line names the same target. A module compiled in this log and later shown `Replayed` had
76
+ its stored warnings re-printed (a `lake lean FILE` importing it), it was not restored; a cache line with no
77
+ earlier `Built` (before it, or none at all) still counts."""
78
+ built: set[str] = set()
79
+ out: list[tuple[str, str]] = []
80
+ for verb, target in jobs:
81
+ if verb == "Built":
82
+ built.add(target)
83
+ elif verb in CACHE_VERBS and target not in built and (verb, target) not in out:
84
+ out.append((verb, target))
85
+ return out
86
+
87
+
88
+ def _first_component(name: str) -> str | None:
89
+ name = name.strip().strip("`").strip()
90
+ if not name:
91
+ return None
92
+ if name.startswith("«"):
93
+ end = name.find("»")
94
+ return name[1:end] if end > 0 else None
95
+ first = re.split(r"[.]", name, maxsplit=1)[0]
96
+ return first if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_'!?]*", first) else None
97
+
98
+
99
+ def lakefile_roots(toml_text: str | None = None, lean_text: str | None = None) -> set[str]:
100
+ """The root namespaces (first name component) of every lean_lib's name, roots and globs in a
101
+ lakefile.toml / lakefile.lean. Over-inclusive on purpose (a lib name is kept even when `roots` replaces
102
+ it): a namespace listed here is only ever a reason to look closer."""
103
+ names: list[str] = []
104
+ if toml_text is not None:
105
+ try:
106
+ data = tomllib.loads(toml_text)
107
+ except (ValueError, TypeError):
108
+ data = None
109
+ libs = data.get("lean_lib") if isinstance(data, dict) else None
110
+ for lib in libs if isinstance(libs, list) else []:
111
+ if not isinstance(lib, dict):
112
+ continue
113
+ for key in ("name", "roots", "globs"):
114
+ v = lib.get(key)
115
+ for x in v if isinstance(v, list) else [v]:
116
+ if isinstance(x, str):
117
+ names.append(x)
118
+ if lean_text is not None:
119
+ names += [m.group(1) for m in re.finditer(r"\blean_lib\s+(«[^»]+»|[A-Za-z_][A-Za-z0-9_.'!?]*)", lean_text)]
120
+ for m in re.finditer(r"\b(?:roots|globs)\s*:=\s*#\[(.*?)\]", lean_text, re.S):
121
+ names += re.findall(r"`(«[^»]+»|[A-Za-z_][A-Za-z0-9_.'!?«»]*)", m.group(1))
122
+ return {c for c in map(_first_component, names) if c}
123
+
124
+
125
+ def tracked_lean_files(paths) -> list[str]:
126
+ """The package-relative `.lean` sources among tracked paths, less the lakefile and anything under .lake/."""
127
+ return [p for p in paths if p.endswith(".lean") and p != "lakefile.lean" and not p.startswith(".lake/")]
128
+
129
+
130
+ def fallback_roots(lean_files) -> set[str]:
131
+ """Top-level names of the tracked Lean sources (X.lean -> X, X/Y.lean -> X): the roots when the lakefile
132
+ names none."""
133
+ out = set()
134
+ for p in lean_files:
135
+ top = p.split("/", 1)[0]
136
+ top = top[:-len(".lean")] if top.endswith(".lean") else top
137
+ c = _first_component(top)
138
+ if c:
139
+ out.add(c)
140
+ return out
141
+
142
+
143
+ def package_roots(lakefile_toml: str | None, lakefile_lean: str | None, lean_files) -> set[str]:
144
+ return lakefile_roots(lakefile_toml, lakefile_lean) or fallback_roots(lean_files)
145
+
146
+
147
+ def is_root_module(module: str, lean_files, roots: set[str]) -> bool:
148
+ """A module of the root package: its source `A/B/C.lean` is tracked (at the package root or under a source
149
+ directory), or its first component is a root namespace."""
150
+ rel = module.replace(".", "/") + ".lean"
151
+ if any(p == rel or p.endswith("/" + rel) for p in lean_files):
152
+ return True
153
+ return _first_component(module) in roots
154
+
155
+
156
+ def cache_reuse_problems(text: str, lean_files, roots: set[str]) -> tuple[list[str], list[str]]:
157
+ """(refusals, checks) for a build log: root-package modules Lake restored instead of compiling (inside the
158
+ template's build markers when present; a cache line after the module's own `Built` is a warning replay,
159
+ restored_jobs), and the template's own cache declarations when present."""
160
+ refusals, checks = [], []
161
+ section = build_section(text)
162
+ restored = [(verb, target) for verb, target in restored_jobs(job_lines(section))
163
+ if is_root_module(target, lean_files, roots)]
164
+ if restored:
165
+ shown = ", ".join(f"{t} ({v})" for v, t in restored[:8]) + (
166
+ f" (+{len(restored) - 8} more)" if len(restored) > 8 else "")
167
+ refusals.append(f"verify log: Lake restored root-package module(s) instead of compiling them: {shown}; a "
168
+ f"restored module's `declaration uses sorry` warning need not be printed, so the sorry scan "
169
+ f"is unsound; rebuild from a fresh tree (no .lake/build) with LAKE_CACHE_DIR a fresh empty "
170
+ f"directory and LAKE_ARTIFACT_CACHE=false")
171
+ else:
172
+ checks.append("✓ lake: no root-package module shown Reused, Replayed or Unpacked in the build log")
173
+ for line in strip_ansi(text).splitlines():
174
+ m = re.match(r"^lake-artifact-cache:[ \t]*(.*?)[ \t]*$", line)
175
+ if m and m.group(1).lower() not in ("false", "0"):
176
+ refusals.append(f"verify log: `lake-artifact-cache: {m.group(1)}`; a fresh build needs "
177
+ f"LAKE_ARTIFACT_CACHE=false")
178
+ return refusals, checks
179
+
180
+
181
+ # --------------------------------------------------------------------------
182
+ # LEAN_PATH shadowing
183
+
184
+ def _same_dir(a: str, b: pathlib.Path) -> bool:
185
+ try:
186
+ return os.path.realpath(a) == os.path.realpath(b)
187
+ except OSError:
188
+ return False
189
+
190
+
191
+ def shadow_hits(lean_path, project: pathlib.Path, roots: set[str]) -> list[str]:
192
+ """The `<entry>/<R>` (directory) or `<entry>/<R>.olean` / `.ilean` paths, for every LEAN_PATH entry other
193
+ than the root package's own .lake/build/lib/lean, that hold a root namespace R of the root package."""
194
+ own = pathlib.Path(project) / ROOT_LIB_DIR
195
+ entries = lean_path.split(os.pathsep) if isinstance(lean_path, str) else list(lean_path)
196
+ hits = []
197
+ for entry in entries:
198
+ if not entry or _same_dir(entry, own):
199
+ continue
200
+ base = pathlib.Path(entry)
201
+ if not base.is_absolute():
202
+ base = pathlib.Path(project) / base
203
+ for r in sorted(roots):
204
+ for cand in (base / r, base / f"{r}.olean", base / f"{r}.ilean"):
205
+ if (cand.is_dir() if cand.name == r else cand.exists()) and str(cand) not in hits:
206
+ hits.append(str(cand))
207
+ return hits
208
+
209
+
210
+ def lean_path(project: pathlib.Path, lake: str, env: dict | None = None,
211
+ preexec=None) -> tuple[str | None, str | None]:
212
+ """(LEAN_PATH as `lake env` sets it, error)."""
213
+ try:
214
+ p = subprocess.run([lake, "env", "printenv", "LEAN_PATH"], cwd=project, env=env, capture_output=True,
215
+ text=True, timeout=LEAN_PATH_TIMEOUT, stdin=subprocess.DEVNULL, preexec_fn=preexec)
216
+ except (OSError, subprocess.TimeoutExpired) as e:
217
+ return None, f"`lake env printenv LEAN_PATH` could not run: {e}"
218
+ if p.returncode != 0:
219
+ return None, (f"`lake env printenv LEAN_PATH` exited {p.returncode}: "
220
+ f"{(p.stderr or p.stdout).strip().splitlines()[-1:] or 'no output'}")
221
+ return p.stdout.strip(), None
222
+
223
+
224
+ def module_roots(modules) -> set[str]:
225
+ """The root namespaces of module names (A.B.C -> A)."""
226
+ return {c for c in map(_first_component, modules) if c}
227
+
228
+
229
+ def project_roots(project: pathlib.Path, tracked) -> set[str]:
230
+ def read(name: str) -> str | None:
231
+ try:
232
+ return (pathlib.Path(project) / name).read_text(encoding="utf-8")
233
+ except (OSError, UnicodeDecodeError):
234
+ return None
235
+ return package_roots(read("lakefile.toml"), read("lakefile.lean"), tracked_lean_files(tracked))
236
+
237
+
238
+ SHADOW_HINT = ("a dependency's build directory comes before the root package's on LEAN_PATH (Lake lists the root "
239
+ "last) and Lean loads <R>/ from the first entry holding it, so `lake env lean` would read that "
240
+ "copy; remove it (or rename the root namespace) and rebuild")
241
+
242
+
243
+ # The shell copy (begin/end lines included). Needs bash; reads lakefile.toml / lakefile.lean in the current
244
+ # directory. Usage: `lake_shadow_check "$(lake env printenv LEAN_PATH)"`: prints `lean-path-shadow: <path>` per
245
+ # hit and returns 1, else prints `lean-path-shadow: none (<n> entries, roots <R,...>)`.
246
+ SHADOW_CHECK_SH = r"""# >>> lean-pkg lake_shadow_check (keep identical in every copy; see lean_pkg/lake_hygiene.py)
247
+ lake_root_namespaces() {
248
+ local found
249
+ found=$(
250
+ {
251
+ if [ -f lakefile.toml ]; then
252
+ awk '/^[[:space:]]*\[/ { lib = ($0 ~ /^[[:space:]]*\[\[[[:space:]]*lean_lib[[:space:]]*\]\]/) }
253
+ lib && /^[[:space:]]*(name|roots|globs)[[:space:]]*=/' lakefile.toml | grep -oE '"[^"]+"' | tr -d '"'
254
+ fi
255
+ if [ -f lakefile.lean ]; then
256
+ grep -oE 'lean_lib[[:space:]]+(«[^»]+»|[A-Za-z_][A-Za-z0-9_.]*)' lakefile.lean | awk '{print $2}'
257
+ tr '\n' ' ' < lakefile.lean | grep -oE '(roots|globs)[[:space:]]*:=[[:space:]]*#\[[^]]*\]' \
258
+ | grep -oE '`[^]`[:space:],)]+' | tr -d '`'
259
+ fi
260
+ } 2>/dev/null | sed -e 's/^«\([^»]*\)».*$/\1/' -e 's/[.].*$//' | grep -E '^[A-Za-z_]' | sort -u || true
261
+ )
262
+ if [ -z "$found" ]; then
263
+ found=$(find . -path ./.lake -prune -o -name '*.lean' ! -path ./lakefile.lean -print 2>/dev/null \
264
+ | sed -e 's|^\./||' -e 's|/.*$||' -e 's|\.lean$||' | grep -E '^[A-Za-z_]' | sort -u || true)
265
+ fi
266
+ printf '%s\n' "$found"
267
+ }
268
+ lake_shadow_check() {
269
+ local own entry r n=0 hits=0 roots
270
+ local -a entries
271
+ own="$(pwd -P)/.lake/build/lib/lean"
272
+ roots=$(lake_root_namespaces)
273
+ IFS=: read -r -a entries <<<"${1:-}"
274
+ for entry in "${entries[@]}"; do
275
+ [ -n "$entry" ] || continue
276
+ n=$((n + 1))
277
+ if [ "$(cd "$entry" 2>/dev/null && pwd -P)" = "$own" ]; then continue; fi
278
+ for r in $roots; do
279
+ if [ -d "$entry/$r" ] || [ -e "$entry/$r.olean" ] || [ -e "$entry/$r.ilean" ]; then
280
+ echo "lean-path-shadow: $entry/$r"
281
+ hits=$((hits + 1))
282
+ fi
283
+ done
284
+ done
285
+ if [ "$hits" -gt 0 ]; then return 1; fi
286
+ echo "lean-path-shadow: none ($n entries, roots $(printf '%s' "$roots" | paste -sd, -))"
287
+ }
288
+ # <<< lean-pkg lake_shadow_check
289
+ """
lean_pkg/lean_diag.py ADDED
@@ -0,0 +1,280 @@
1
+ # lean_diag -- parse Lean and Lake diagnostics strictly, for negative tests
2
+ """Parse the diagnostics in a Lean or Lake output log, and check that a file failed for exactly one
3
+ expected reason.
4
+
5
+ A negative test (a file that must fail) passes for the wrong reason surprisingly often: a harness that
6
+ looks for `error:` misses Lean's coded errors (`T.lean:6:8: error(lean.synthInstanceFailed): ...`),
7
+ counts a `sorry` warning or a build summary as the failure, or accepts a typo's `Unknown identifier`
8
+ where a missing instance was meant. This module reads every form Lean 4 and Lake print:
9
+
10
+ - `lean FILE`: `FILE:L:C: error: msg`, `FILE:L:C: error(lean.code): msg`, `warning:`, `info:`
11
+ - `lake build`: `error: FILE:L:C: msg` (Lake drops the error code), `warning: ...`, and its own
12
+ summaries `error: Lean exited with code 1`, `error: build failed`
13
+ - `lean --json FILE`: one JSON object per message (`severity`, `kind` = `lean.code._namedError`, `data`)
14
+
15
+ Messages may span several lines; every line up to the next diagnostic or Lake status line belongs to the
16
+ message before it. ANSI colour codes are removed. Nothing here runs Lean.
17
+
18
+ Python API: `parse(text) -> list[Diagnostic]`, `expect(text_or_diags, message=, code=, file=, line=)`
19
+ -> dict (`ok`, `verdict`, `detail`, `counts`, `matched`, `errors`).
20
+ Command line: `python3 -m lean_pkg.lean_diag LOG [--error-code CODE] [--error-message TEXT] [--file F]
21
+ [--line N] [--json]` (LOG `-` is stdin). Exit 0 the expected error and nothing else, 1 not, 2 usage.
22
+ Documented in docs/negative-tests.md.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import dataclasses
29
+ import json
30
+ import re
31
+ import sys
32
+
33
+ SCHEMA = "lean-pkg-lean-diag/1"
34
+ SEVERITIES = ("error", "warning", "info")
35
+ _SEV = r"(?P<sev>error|warning|info)(?:\((?P<code>[A-Za-z_][A-Za-z0-9_.']*)\))?"
36
+ _POS = r"(?P<file>.+?):(?P<line>\d+):(?P<col>\d+)"
37
+ LEAN_HEAD = re.compile(rf"^{_POS}: {_SEV}:(?: (?P<msg>.*))?$")
38
+ LAKE_HEAD = re.compile(rf"^{_SEV}: {_POS}:(?: (?P<msg>.*))?$")
39
+ BARE_HEAD = re.compile(rf"^{_SEV}:(?: (?P<msg>.*))?$")
40
+ # Lake's own status lines: they end a message and are not diagnostics
41
+ LAKE_STATUS = re.compile(r"^(?:[✖✔⚠ℹ]\s*)?\[\d+/\d+\]\s|^trace: |^Build completed successfully|"
42
+ r"^Some required targets logged failures:")
43
+ # the build-failure summaries a failing build adds after the real errors
44
+ CONSEQUENCE = re.compile(r"^(?:Lean exited with code \d+|build failed|"
45
+ r"external command [`'\"]?\S+?[`'\"]? exited with code \d+)$")
46
+ SORRY = re.compile(r"declaration uses ['`]sorry['`]")
47
+ ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
48
+ NAMED_ERROR = "._namedError"
49
+
50
+
51
+ @dataclasses.dataclass
52
+ class Diagnostic:
53
+ severity: str # error | warning | info
54
+ message: str # the whole message, continuation lines included
55
+ code: str | None = None # e.g. lean.synthInstanceFailed; None when uncoded or the form drops it
56
+ file: str | None = None
57
+ line: int | None = None
58
+ column: int | None = None
59
+ form: str = "lean" # lean | lake | json | bare (no position)
60
+ consequence: bool = False # a build-failure summary (Lean exited with code N, build failed)
61
+
62
+ @property
63
+ def sorry(self) -> bool:
64
+ return bool(SORRY.search(self.message))
65
+
66
+ def where(self) -> str:
67
+ pos = f"{self.file}:{self.line}:{self.column}" if self.file else "(no position)"
68
+ sev = f"{self.severity}({self.code})" if self.code else self.severity
69
+ return f"{pos} {sev}"
70
+
71
+ def as_dict(self) -> dict:
72
+ d = dataclasses.asdict(self)
73
+ d["sorry"] = self.sorry
74
+ return d
75
+
76
+
77
+ def _norm_file(f: str) -> str:
78
+ while f.startswith("./"):
79
+ f = f[2:]
80
+ return f
81
+
82
+
83
+ def _json_diag(line: str) -> Diagnostic | None:
84
+ try:
85
+ obj = json.loads(line)
86
+ except ValueError:
87
+ return None
88
+ if not (isinstance(obj, dict) and obj.get("severity") in SEVERITIES and isinstance(obj.get("data"), str)):
89
+ return None
90
+ kind = obj.get("kind")
91
+ code = kind[:-len(NAMED_ERROR)] if isinstance(kind, str) and kind.endswith(NAMED_ERROR) else None
92
+ pos = obj.get("pos") if isinstance(obj.get("pos"), dict) else {}
93
+ f = obj.get("fileName")
94
+ return Diagnostic(severity=obj["severity"], message=obj["data"], code=code,
95
+ file=_norm_file(f) if isinstance(f, str) else None,
96
+ line=pos.get("line"), column=pos.get("column"), form="json")
97
+
98
+
99
+ def parse(text: str) -> list[Diagnostic]:
100
+ """Every diagnostic in a Lean / Lake log, in order. Lines before the first diagnostic, Lake status
101
+ lines and the target list after `Some required targets logged failures:` are not diagnostics."""
102
+ out: list[Diagnostic] = []
103
+ cur: Diagnostic | None = None
104
+ for raw in ANSI.sub("", text).split("\n"):
105
+ line = raw.rstrip("\r").rsplit("\r", 1)[-1] # a terminal shows what follows the last \r
106
+ if line.startswith("{") and (d := _json_diag(line)):
107
+ out.append(d)
108
+ cur = None
109
+ continue
110
+ m, form = LEAN_HEAD.match(line), "lean"
111
+ if not m:
112
+ m, form = LAKE_HEAD.match(line), "lake"
113
+ if m:
114
+ cur = Diagnostic(severity=m["sev"], message=m["msg"] or "", code=m["code"],
115
+ file=_norm_file(m["file"]), line=int(m["line"]), column=int(m["col"]), form=form)
116
+ out.append(cur)
117
+ continue
118
+ m = BARE_HEAD.match(line)
119
+ if m:
120
+ msg = m["msg"] or ""
121
+ cur = Diagnostic(severity=m["sev"], message=msg, code=m["code"], form="bare",
122
+ consequence=m["sev"] == "error" and bool(CONSEQUENCE.match(msg.strip())))
123
+ out.append(cur)
124
+ continue
125
+ if LAKE_STATUS.match(line):
126
+ cur = None
127
+ continue
128
+ if cur is not None:
129
+ cur.message += "\n" + line
130
+ for d in out:
131
+ d.message = d.message.rstrip("\n")
132
+ return out
133
+
134
+
135
+ def _ws(s: str) -> str:
136
+ return " ".join(s.split())
137
+
138
+
139
+ def counts(diags: list[Diagnostic]) -> dict:
140
+ errs = [d for d in diags if d.severity == "error" and not d.consequence]
141
+ warns = [d for d in diags if d.severity == "warning"]
142
+ return {"errors": len(errs), "coded_errors": sum(1 for d in errs if d.code),
143
+ "uncoded_errors": sum(1 for d in errs if not d.code),
144
+ "unpositioned_errors": sum(1 for d in errs if d.file is None),
145
+ "sorry_errors": sum(1 for d in errs if d.sorry),
146
+ "warnings": len(warns), "sorry_warnings": sum(1 for d in warns if d.sorry),
147
+ "infos": sum(1 for d in diags if d.severity == "info"),
148
+ "build_failure_summaries": sum(1 for d in diags if d.consequence)}
149
+
150
+
151
+ def matches(d: Diagnostic, message: str | None = None, code: str | None = None, file: str | None = None,
152
+ line: int | None = None) -> bool:
153
+ if code is not None and d.code != code:
154
+ return False
155
+ if message is not None and _ws(message) not in _ws(d.message):
156
+ return False
157
+ if file is not None:
158
+ f = _norm_file(file)
159
+ if d.file is None or not (d.file == f or d.file.endswith("/" + f)):
160
+ return False
161
+ return line is None or d.line == line
162
+
163
+
164
+ def expect(log: str | list[Diagnostic], message: str | None = None, code: str | None = None,
165
+ file: str | None = None, line: int | None = None) -> dict:
166
+ """Did the log fail with exactly one error, the expected one? `message` is a substring of the
167
+ message (whitespace collapsed on both sides), `code` the exact error name (`lean.synthInstanceFailed`),
168
+ `file` the file (a path suffix), `line` its line. At least one of message and code is required.
169
+
170
+ verdicts: expected (ok) | no-error (nothing failed) | wrong-reason (errors, none the expected one; or
171
+ only a build-failure summary) | extra-errors (the expected error and others)."""
172
+ if message is None and code is None:
173
+ raise ValueError("expect: give the expected message, the expected code, or both")
174
+ diags = parse(log) if isinstance(log, str) else list(log)
175
+ c = counts(diags)
176
+ errs = [d for d in diags if d.severity == "error" and not d.consequence]
177
+ hit = [d for d in errs if matches(d, message, code, file, line)]
178
+ want = " ".join(x for x in (f"code {code}" if code else "", f"message {message!r}" if message else "",
179
+ f"in {file}" if file else "", f"at line {line}" if line is not None else "") if x)
180
+ res = {"schema": SCHEMA, "ok": False, "expected": {"message": message, "code": code, "file": file, "line": line},
181
+ "counts": c, "matched": [d.as_dict() for d in hit], "errors": [d.as_dict() for d in errs]}
182
+ if not errs:
183
+ if c["build_failure_summaries"]:
184
+ res.update(verdict="wrong-reason", detail="the build failed, but the log holds no Lean error, only "
185
+ "a build-failure summary (did the build run at all?)")
186
+ elif c["sorry_warnings"]:
187
+ res.update(verdict="no-error", detail=f"no error: the file only uses sorry ({c['sorry_warnings']} "
188
+ "warning(s)), which compiles; expected " + want)
189
+ else:
190
+ res.update(verdict="no-error", detail="no error: the file compiled; expected " + want)
191
+ elif not hit:
192
+ first = errs[0]
193
+ why = f"{len(errs)} error(s), none with {want}; the first is {first.where()}: {_ws(first.message)[:200]}"
194
+ if code and not any(d.code for d in errs) and any(d.form == "lake" for d in errs):
195
+ why += ("; this is Lake's output, which drops error codes: match by message, or run `lake env lean "
196
+ "FILE` (or `lean --json`), which keeps them")
197
+ res.update(verdict="wrong-reason", detail=why)
198
+ elif len(errs) > 1:
199
+ others = [d.where() for d in errs if not any(d is h for h in hit)]
200
+ res.update(verdict="extra-errors", detail=f"{len(hit)} of {len(errs)} error(s) match {want}; also: "
201
+ + ", ".join(others[:10]) + (f" (and {len(others) - 10} more)" if len(others) > 10 else ""))
202
+ else:
203
+ res.update(ok=True, verdict="expected", detail=f"exactly one error, the expected one: {hit[0].where()}")
204
+ return res
205
+
206
+
207
+ def summary_line(c: dict) -> str:
208
+ return (f"errors {c['errors']} (coded {c['coded_errors']}, uncoded {c['uncoded_errors']}, unpositioned "
209
+ f"{c['unpositioned_errors']}, sorry {c['sorry_errors']}), warnings {c['warnings']} "
210
+ f"(sorry {c['sorry_warnings']}), infos {c['infos']}, build-failure summaries "
211
+ f"{c['build_failure_summaries']}")
212
+
213
+
214
+ # ----------------------------------------------------------------------------------------------------
215
+ # command line
216
+
217
+ def parser() -> argparse.ArgumentParser:
218
+ ap = argparse.ArgumentParser(
219
+ prog="python3 -m lean_pkg.lean_diag", formatter_class=argparse.RawDescriptionHelpFormatter,
220
+ description="Count the coded and uncoded errors, warnings and sorry warnings in a Lean or Lake log, "
221
+ "and check that it failed with exactly one expected error. Reads the log only.",
222
+ epilog="examples:\n"
223
+ " lake env lean Controls/NoInstance.lean > out.log 2>&1; python3 -m lean_pkg.lean_diag out.log "
224
+ "--error-code lean.synthInstanceFailed\n"
225
+ " python3 -m lean_pkg.lean_diag build.log --error-message 'failed to synthesize' --file Bad.lean\n"
226
+ " python3 -m lean_pkg.lean_diag out.log # counts only\n"
227
+ "exit codes: 0 the expected error and no other (or counts only), 1 not, 2 usage.\n"
228
+ "docs: https://lean-pkg.github.io/lean-pkg/negative-tests.html")
229
+ ap.add_argument("log", metavar="LOG", help="the Lean or Lake output (stdout and stderr together); - for stdin")
230
+ ap.add_argument("--error-code", metavar="CODE", help="the exact error name, e.g. lean.synthInstanceFailed")
231
+ ap.add_argument("--error-message", metavar="TEXT", help="a substring of the expected error's message "
232
+ "(whitespace collapsed)")
233
+ ap.add_argument("--file", metavar="F", help="the expected error's file (a path suffix)")
234
+ ap.add_argument("--line", type=int, metavar="N", help="the expected error's line")
235
+ ap.add_argument("--json", dest="json_out", action="store_true", help=f"JSON on stdout (schema {SCHEMA})")
236
+ return ap
237
+
238
+
239
+ def main(argv: list[str] | None = None) -> int:
240
+ args = parser().parse_args(argv)
241
+ try:
242
+ if args.log == "-":
243
+ text = sys.stdin.read()
244
+ else:
245
+ with open(args.log, encoding="utf-8", errors="replace") as fh:
246
+ text = fh.read()
247
+ except OSError as e:
248
+ print(f"lean_diag: {args.log}: {e.strerror or e}", file=sys.stderr)
249
+ return 2
250
+ if args.error_code is None and args.error_message is None:
251
+ if args.file is not None or args.line is not None:
252
+ print("lean_diag: --file and --line need --error-code or --error-message", file=sys.stderr)
253
+ return 2
254
+ diags = parse(text)
255
+ c = counts(diags)
256
+ if args.json_out:
257
+ print(json.dumps({"schema": SCHEMA, "counts": c, "diagnostics": [d.as_dict() for d in diags]}, indent=2))
258
+ else:
259
+ print(summary_line(c))
260
+ for d in diags:
261
+ print(f" {d.where()}: {_ws(d.message)[:160]}")
262
+ return 0
263
+ res = expect(text, message=args.error_message, code=args.error_code, file=args.file, line=args.line)
264
+ if args.json_out:
265
+ print(json.dumps(res, indent=2))
266
+ else:
267
+ head = f"{res['verdict']}: {res['detail']}"
268
+ print(head)
269
+ print(summary_line(res["counts"]))
270
+ for d in res["errors"]:
271
+ mark = "*" if d in res["matched"] else " "
272
+ pos = f"{d['file']}:{d['line']}:{d['column']}" if d["file"] else "(no position)"
273
+ sev = f"error({d['code']})" if d["code"] else "error"
274
+ print(f" {mark} {pos} {sev}: {_ws(d['message'])[:160]}")
275
+ print(head)
276
+ return 0 if res["ok"] else 1
277
+
278
+
279
+ if __name__ == "__main__":
280
+ sys.exit(main())