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,421 @@
1
+ # claim_axioms -- the axioms of every claim, read from the built environment and judged fail-closed
2
+ """Per-claim axioms read from the BUILT environment, for every claim in claims.yaml (not only the theorems an
3
+ author chose to `#print axioms`).
4
+
5
+ Why: the lower-tier receipt's `axioms` field is parsed from `#print axioms` text in the verify log, and the
6
+ log only holds the declarations the package's Axioms file prints. A claim nobody printed was never checked.
7
+ The Equational Theories Project runs `Lean.collectAxioms` on every counted result inside Lean; this is the
8
+ same check, done by a small program after the build so no package depends on a lean-pkg Lean library.
9
+
10
+ How: `scripts/ClaimAxioms.lean` imports the package's modules exactly as `import` does (data only:
11
+ `loadExts := false`, so no axiom list cached in an .olean is read and every body is walked) and runs core
12
+ Lean's `collectAxioms` on every claim name, printing one line per name into the verify log:
13
+ claim-axioms: NAME AX1,AX2,... (sorted; `none` for no axiom)
14
+ claim-missing: NAME (no such constant in the environment)
15
+ claim-axioms-done: N (the last line; N = the number of names)
16
+ The program runs as `lean --run` with the LEAN_PATH the script printed (`lake env printenv LEAN_PATH`;
17
+ the template checks it for shadowing first). The lower-tier verify scripts (`receipt slurm --template`, the `verify.sh` that `lean-pkg new` writes) run it
18
+ after the build through `job_sh()` below, with the claim names taken from claims.yaml (every claim, of every
19
+ kind and status; block-style YAML). The lines land in the verify log before the seal, so the log seal
20
+ (`verify-log-sha256`) covers them: an edited line breaks the seal.
21
+
22
+ Verdict (`judge`, used by `receipt slurm|systemd`, the receipt key `claim_axioms`, `gate` and `receipt check`):
23
+ the lines must be complete (one final `claim-axioms-done: N` line, N lines before it, no name twice, nothing
24
+ malformed) and every claim in claims.yaml committed at the receipt's commit must have a line.
25
+ Refused: a missing claim, a claim depending on `sorryAx`, a name whose `#print axioms` output in the same log
26
+ names an axiom its claim-axioms line does not, an unchecked claim. The walk is the verdict: a `#print axioms`
27
+ output naming FEWER axioms (the module system can give it a narrower view of a structure type) is a check
28
+ line, not a refusal. A claim using an axiom beyond propext,
29
+ Classical.choice and Quot.sound is listed under `nonstandard`; `gate` refuses it unless the package's
30
+ gate.axioms_allowed lists it, exactly as for the receipt's `axioms`. A log with no claim-axioms line at all
31
+ (an older verify script) gives a receipt without the key, valid as before.
32
+
33
+ Python API: `parse(text)`, `printed_axioms(text)`, `required_claims(claims_bytes)`, `judge(text, required)`,
34
+ `summary_problems(summary, allowed)`, `probe(project, names, modules=None, ...)`.
35
+ Command line: `python3 -m lean_pkg.claim_axioms --repo DIR [NAME ...] [--module M ...] [--no-sandbox]
36
+ [--json]` (no NAME: every claim of DIR/claims.yaml) prints the probe's lines (or the judgement with --json).
37
+ Exit 0 every claim passes, 1 any refused or the probe failed, 2 usage. Documented in docs/receipts.md.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import argparse
43
+ import json
44
+ import os
45
+ import pathlib
46
+ import re
47
+ import subprocess
48
+ import sys
49
+
50
+ import yaml
51
+
52
+ SCRIPT = pathlib.Path(__file__).with_name("scripts") / "ClaimAxioms.lean"
53
+ STANDARD = ("propext", "Quot.sound", "Classical.choice")
54
+ SORRY = "sorryAx"
55
+ AXIOMS_KEY, MISSING_KEY, DONE_KEY = "claim-axioms", "claim-missing", "claim-axioms-done"
56
+ _LINE = re.compile(r"^(claim-axioms|claim-missing|claim-axioms-done):[ \t]*(.*?)[ \t]*\r?$")
57
+ _AXIOM_NAME = re.compile(r"^[^\s,]+$")
58
+ # `#print axioms` output (Lean.Elab.Print): 'NAME' depends on axioms: [A, B] / 'NAME' does not depend on any axioms
59
+ _PRINTED_RE = re.compile(r"'(\S+)' depends on axioms:\s*\[([^\]]*)\]")
60
+ _PRINTED_NONE_RE = re.compile(r"'(\S+)' does not depend on any axioms")
61
+ DEFAULT_TIMEOUT = 1800.0
62
+
63
+
64
+ def _no_universe(name: str) -> str:
65
+ return re.sub(r"\.\{[^{}]*\}$", "", name)
66
+
67
+
68
+ def claim_lines(text: str) -> list[str]:
69
+ """The log's claim-axioms, claim-missing and claim-axioms-done lines, as written (a redaction that alters
70
+ one is refused, as for every line the receipt reads)."""
71
+ return [line.rstrip("\r") for line in text.splitlines() if _LINE.match(line)]
72
+
73
+
74
+ def parse(text: str) -> tuple[list[tuple[str, list[str] | None]], int | None, list[str]]:
75
+ """([(name, sorted axioms, or None for a missing name)], the done count or None, problems)."""
76
+ records: list[tuple[str, list[str] | None]] = []
77
+ seen: set[str] = set()
78
+ done: int | None = None
79
+ problems: list[str] = []
80
+ for n, raw in enumerate(text.splitlines(), 1):
81
+ m = _LINE.match(raw)
82
+ if not m:
83
+ continue
84
+ key, value = m.group(1), m.group(2)
85
+ if done is not None:
86
+ problems.append(f"verify log line {n}: a `{key}:` line after `{DONE_KEY}:`")
87
+ continue
88
+ if key == DONE_KEY:
89
+ if not re.fullmatch(r"\d+", value):
90
+ problems.append(f"verify log line {n}: `{DONE_KEY}:` is not a count: {value!r}")
91
+ done = -1
92
+ else:
93
+ done = int(value)
94
+ continue
95
+ if key == MISSING_KEY:
96
+ name, axioms = value, None
97
+ if not name:
98
+ problems.append(f"verify log line {n}: `{MISSING_KEY}:` names no declaration: {value!r}")
99
+ continue
100
+ else:
101
+ parts = value.rsplit(None, 1)
102
+ if len(parts) != 2:
103
+ problems.append(f"verify log line {n}: `{AXIOMS_KEY}:` is not `NAME AXIOMS`: {value!r}")
104
+ continue
105
+ name, ax = parts
106
+ if ax == "none":
107
+ axioms = []
108
+ else:
109
+ axioms = [_no_universe(a) for a in ax.split(",")]
110
+ if not all(_AXIOM_NAME.match(a) for a in axioms):
111
+ problems.append(f"verify log line {n}: `{AXIOMS_KEY}:` has a malformed axiom list: {ax!r}")
112
+ continue
113
+ axioms = sorted(set(axioms))
114
+ if name in seen:
115
+ problems.append(f"verify log: {name} has more than one claim-axioms/claim-missing line")
116
+ continue
117
+ seen.add(name)
118
+ records.append((name, axioms))
119
+ return records, done, problems
120
+
121
+
122
+ def printed_axioms(text: str) -> dict[str, set[str]]:
123
+ """name -> axioms, from the log's own `#print axioms` output (Lean wraps a long list: newlines joined)."""
124
+ flat = text.replace("\r", "").replace("\n", " ")
125
+ out: dict[str, set[str]] = {}
126
+ for m in _PRINTED_RE.finditer(flat):
127
+ out.setdefault(m.group(1), set()).update(
128
+ _no_universe(a) for a in re.split(r"[,\s]+", m.group(2)) if a)
129
+ for m in _PRINTED_NONE_RE.finditer(flat):
130
+ out.setdefault(m.group(1), set())
131
+ return out
132
+
133
+
134
+ def required_claims(claims_bytes: bytes | None) -> tuple[list[str], list[str]]:
135
+ """(the decl of every claim of a claims.yaml, of any kind and status, problems). No file: ([], [])."""
136
+ if claims_bytes is None:
137
+ return [], []
138
+ try:
139
+ data = yaml.safe_load(claims_bytes.decode("utf-8"))
140
+ except (UnicodeDecodeError, yaml.YAMLError) as e:
141
+ return [], [f"claims.yaml is not readable YAML ({e.__class__.__name__}): the claims to check are unknown"]
142
+ claims = data.get("claims") if isinstance(data, dict) else None
143
+ if claims is None:
144
+ return [], []
145
+ if not isinstance(claims, list):
146
+ return [], ["claims.yaml: `claims` is not a list: the claims to check are unknown"]
147
+ out: list[str] = []
148
+ for c in claims:
149
+ if not isinstance(c, dict):
150
+ continue
151
+ decl = c.get("decl")
152
+ if isinstance(decl, str) and decl.strip() and decl.strip() not in out:
153
+ out.append(decl.strip())
154
+ return out, []
155
+
156
+
157
+ def judge(text: str, required: list[str] | None) -> tuple[dict | None, list[str], list[str]]:
158
+ """(the receipt's `claim_axioms` summary or None when the log has no claim line, refusals, check lines).
159
+ `required`: the claims that must be checked (None: no claims.yaml requirement is applied)."""
160
+ records, done, problems = parse(text)
161
+ if not records and done is None and not problems:
162
+ return None, [], []
163
+ refusals = list(problems)
164
+ if done is None:
165
+ refusals.append(f"verify log: claim-axioms lines but no final `{DONE_KEY}:` line: the probe did not "
166
+ f"finish (or the log was cut)")
167
+ elif not problems and done != len(records):
168
+ refusals.append(f"verify log: `{DONE_KEY}: {done}` but {len(records)} claim line(s): the output is "
169
+ f"inconsistent")
170
+ checked = {name: axs for name, axs in records}
171
+ missing = [name for name, axs in records if axs is None]
172
+ if missing:
173
+ refusals.append(f"claim axioms: {len(missing)} claim(s) not in the built environment: "
174
+ f"{', '.join(missing[:10])}" + (" ..." if len(missing) > 10 else "")
175
+ + " (a decl must be the fully qualified name of a declaration the build compiles)")
176
+ sorried = [name for name, axs in records if axs and SORRY in axs]
177
+ if sorried:
178
+ refusals.append(f"claim axioms: {len(sorried)} claim(s) depend on sorryAx: {', '.join(sorried[:10])}")
179
+ nonstandard = [{"decl": name, "axioms": [a for a in axs if a not in STANDARD]}
180
+ for name, axs in records if axs and any(a not in STANDARD for a in axs)]
181
+ if required is not None:
182
+ unchecked = [d for d in required if d not in checked]
183
+ if unchecked:
184
+ refusals.append(f"claim axioms: {len(unchecked)} claim(s) in claims.yaml have no claim-axioms line: "
185
+ f"{', '.join(unchecked[:10])}" + (" ..." if len(unchecked) > 10 else "")
186
+ + " (the job's claims reader read block-style YAML; every claim must be checked)")
187
+ # The environment walk is the verdict. `#print axioms` naming an axiom the walk did not find means the walk
188
+ # missed something (or the log was altered): refused. `#print axioms` naming FEWER axioms is the safe
189
+ # direction and is reported, not refused: under the Lean module system `#print axioms` on a structure type
190
+ # can read a narrower view than the walk, which visits every body (`loadExts := false`).
191
+ printed = printed_axioms(text)
192
+ narrower = []
193
+ for name, axs in records:
194
+ if axs is None or name not in printed:
195
+ continue
196
+ extra = printed[name] - set(axs)
197
+ if extra:
198
+ refusals.append(f"claim axioms: {name}: its `#print axioms` output in the same log names "
199
+ f"{sorted(extra)}, which the environment walk did not find (the environment gives "
200
+ f"{axs or 'none'}, `#print axioms` {sorted(printed[name]) or 'none'}); the two disagree")
201
+ elif printed[name] != set(axs):
202
+ narrower.append(name)
203
+ n = sum(1 for _, axs in records if axs is not None)
204
+ summary = {"checked": n, "nonstandard": nonstandard, "missing": missing}
205
+ lines = []
206
+ if not refusals:
207
+ both = sorted(set(checked) & set(printed))
208
+ agree = len(both) - len(narrower)
209
+ lines.append(f"✓ claim axioms: {n} claim(s) read from the built environment (collectAxioms)"
210
+ + (", every claim in claims.yaml" if required else "")
211
+ + (f"; {agree} agree with their #print axioms output" if agree else ""))
212
+ for name in narrower:
213
+ axs = checked[name]
214
+ lines.append(f" claim axioms: {name}: `#print axioms` names fewer axioms "
215
+ f"({sorted(printed[name]) or 'none'}) than the environment walk ({axs}); the walk is "
216
+ f"the verdict (the module system can give `#print axioms` a narrower view)")
217
+ return summary, refusals, lines
218
+
219
+
220
+ def summary_problems(summary, allowed) -> list[str]:
221
+ """What gate refuses in a receipt's `claim_axioms` key: a malformed key, a missing claim, sorryAx, or an
222
+ axiom outside `allowed` (gate.axioms_allowed, default the standard three)."""
223
+ if not isinstance(summary, dict):
224
+ return ["claim_axioms must be an object {checked, nonstandard, missing}"]
225
+ out = []
226
+ checked, nonstd, missing = summary.get("checked"), summary.get("nonstandard"), summary.get("missing")
227
+ if isinstance(checked, bool) or not isinstance(checked, int) or checked < 0:
228
+ out.append(f"claim_axioms.checked must be a non-negative integer, got {checked!r}")
229
+ if not isinstance(missing, list) or not all(isinstance(m, str) for m in missing):
230
+ out.append("claim_axioms.missing must be a list of declaration names")
231
+ elif missing:
232
+ out.append(f"claim_axioms: claim(s) not in the built environment: {missing[:10]}")
233
+ if not isinstance(nonstd, list) or not all(
234
+ isinstance(e, dict) and isinstance(e.get("decl"), str) and isinstance(e.get("axioms"), list)
235
+ and all(isinstance(a, str) for a in e["axioms"]) for e in nonstd):
236
+ out.append("claim_axioms.nonstandard must be a list of {decl, axioms}")
237
+ else:
238
+ allowed = set(allowed) - {SORRY}
239
+ bad = [f"{e['decl']} ({', '.join(a for a in e['axioms'] if a not in allowed)})" for e in nonstd
240
+ if any(a not in allowed for a in e["axioms"])]
241
+ if bad:
242
+ out.append(f"claim_axioms: claim(s) use axioms outside the allowed set {sorted(allowed)}: "
243
+ f"{'; '.join(bad[:10])}")
244
+ return out
245
+
246
+
247
+ # ---------------------------------------------------------------------------------------------------------
248
+ # The job side: a shell block for the verify scripts (the template and verify.sh embed the Lean program)
249
+
250
+ AWK_CLAIMS = r"""function val(s) {
251
+ sub(/^[A-Za-z_]+:[ \t]*/, "", s); sub(/[ \t]+#.*$/, "", s); sub(/[ \t\r]+$/, "", s)
252
+ if (s ~ /^".*"$/ || s ~ /^'.*'$/) s = substr(s, 2, length(s) - 2)
253
+ return s
254
+ }
255
+ function flush() { if (decl != "") print decl "\t" file; decl = ""; file = "" }
256
+ BEGIN { item = -1; key = -1 }
257
+ /^[ \t]*#/ || /^[ \t\r]*$/ { next }
258
+ /^claims:/ { inl = 1; next }
259
+ inl && /^[^ \t-]/ { flush(); inl = 0 }
260
+ !inl { next }
261
+ {
262
+ match($0, /^ */); ind = RLENGTH; rest = substr($0, ind + 1)
263
+ if (rest ~ /^- /) {
264
+ if (item < 0) item = ind
265
+ if (ind == item) { flush(); match(rest, /^- +/); ind = ind + RLENGTH; rest = substr(rest, RLENGTH + 1); key = ind }
266
+ }
267
+ if (ind == key) {
268
+ if (rest ~ /^decl:/) decl = val(rest)
269
+ else if (rest ~ /^file:/) file = val(rest)
270
+ }
271
+ }
272
+ END { flush() }"""
273
+
274
+
275
+ def job_sh() -> str:
276
+ """Shell functions for a verify script: `claim_axioms_run LOG DIR LEAN_PATH` appends the probe's lines for
277
+ every claim of ./claims.yaml (nothing when there is no claims.yaml; `claim-axioms-done: 0` when it lists
278
+ none) to LOG, writing the Lean program under DIR; it runs `$RUN env LEAN_PATH=... lean --run` (RUN may be
279
+ empty) with the LEAN_PATH the script already printed (and, in the template, checked for shadowing), never
280
+ under `lake env`."""
281
+ lean = SCRIPT.read_text(encoding="utf-8")
282
+ return ("# Per-claim axioms read from the built environment (lean-pkg's ClaimAxioms.lean, core Lean only):\n"
283
+ "# `claim-axioms: NAME AXIOMS` / `claim-missing: NAME` for every claim of claims.yaml, then\n"
284
+ "# `claim-axioms-done: N`. The receipt refuses a missing or unchecked claim and sorryAx.\n"
285
+ "claims_decls() {\n awk '" + AWK_CLAIMS.replace("'", "'\\''") + "' \"$1\"\n}\n"
286
+ "claim_axioms_run() {\n"
287
+ " [ -f claims.yaml ] || return 0\n"
288
+ " local pairs names mods\n"
289
+ " pairs=$(claims_decls claims.yaml)\n"
290
+ " if [ -z \"$pairs\" ]; then echo \"claim-axioms-done: 0\" >>\"$1\"; return 0; fi\n"
291
+ " names=$(printf '%s\\n' \"$pairs\" | cut -f1)\n"
292
+ " mods=$(printf '%s\\n' \"$pairs\" | cut -f2 | grep '\\.lean$' | sed -e 's/\\.lean$//' -e 's|/|.|g'"
293
+ " | sort -u || true)\n"
294
+ " mkdir -p \"$2\"\n"
295
+ " cat >\"$2/ClaimAxioms.lean\" <<'LEAN_PKG_CLAIM_AXIOMS'\n" + lean + "LEAN_PKG_CLAIM_AXIOMS\n"
296
+ " # shellcheck disable=SC2086 # one word per module and per name\n"
297
+ " ${RUN:-} env LEAN_PATH=\"$3\" lean --run \"$2/ClaimAxioms.lean\" $mods -- $names >>\"$1\" 2>&1\n"
298
+ "}\n")
299
+
300
+
301
+ # ---------------------------------------------------------------------------------------------------------
302
+ # The local probe (tests, and an author's own check before a job)
303
+
304
+ def modules_of_claims(claims_bytes: bytes | None) -> list[str]:
305
+ """The modules the claims' `file`s are (`A/B.lean` -> `A.B`), in order, for the import."""
306
+ try:
307
+ data = yaml.safe_load(claims_bytes.decode("utf-8")) if claims_bytes else None
308
+ except (UnicodeDecodeError, yaml.YAMLError):
309
+ return []
310
+ claims = data.get("claims") if isinstance(data, dict) else None
311
+ out: list[str] = []
312
+ for c in claims if isinstance(claims, list) else []:
313
+ f = c.get("file") if isinstance(c, dict) else None
314
+ if isinstance(f, str) and f.endswith(".lean"):
315
+ m = f[:-len(".lean")].replace("/", ".")
316
+ if m not in out:
317
+ out.append(m)
318
+ return out
319
+
320
+
321
+ def probe(project, names: list[str], modules: list[str], toolchain: str | None = None, sandboxed: bool = True,
322
+ timeout: float = DEFAULT_TIMEOUT) -> str:
323
+ """Run ClaimAxioms.lean on the built project (the toolchain, LEAN_PATH and bwrap sandbox dup_constants uses);
324
+ its stdout, the lines a verify log holds. A failure raises dup_constants.ProbeError."""
325
+ from . import dup_constants as dc
326
+ from . import exercise_forbid as fb
327
+ if not names or not modules:
328
+ raise dc.ProbeError("no claim name or no module given")
329
+ for x in [*names, *modules]:
330
+ if not x or x.startswith("-") or any(c.isspace() for c in x):
331
+ raise dc.ProbeError(f"not a Lean name: {x!r}")
332
+ roots, prefix = dc.project_roots(pathlib.Path(project), toolchain)
333
+ for m in modules:
334
+ rel = pathlib.Path(*m.split(".")).with_suffix(".olean")
335
+ if not any((d / rel).is_file() for d in roots.lean_path()):
336
+ raise dc.ProbeError(f"module {m} is not built (no {rel} on the project's LEAN_PATH); run `lake build`")
337
+ env = {"PATH": f"{prefix / 'bin'}:/usr/bin:/bin", "LEAN_PATH": os.pathsep.join(map(str, roots.lean_path())),
338
+ "LEAN_ABORT_ON_PANIC": "1"}
339
+ cmd = [str(prefix / "bin" / "lean"), "--run", str(SCRIPT), *modules, "--", *names]
340
+ cwd = roots.project.parents[3]
341
+ if sandboxed:
342
+ readable = [prefix, cwd, SCRIPT.parent] + [d for d in roots.packages.values() if d.is_dir()]
343
+ cmd = fb.bwrap_args(readable, env, cwd) + cmd
344
+ run_env: dict[str, str] = {}
345
+ else:
346
+ run_env = {**os.environ, **env}
347
+ try:
348
+ p = subprocess.run(cmd, cwd=cwd, env=run_env, stdin=subprocess.DEVNULL, capture_output=True,
349
+ timeout=timeout, start_new_session=True)
350
+ except subprocess.TimeoutExpired:
351
+ raise dc.ProbeError("the probe did not finish in time (--timeout)") from None
352
+ except OSError as e:
353
+ raise dc.ProbeError(f"cannot run the probe: {e}") from None
354
+ out = p.stdout.decode("utf-8", "replace")
355
+ if p.returncode != 0:
356
+ err = p.stderr.decode("utf-8", "replace").strip() or out.strip()
357
+ raise dc.ProbeError(f"the probe failed: {(err.splitlines()[-1:] or [f'exit {p.returncode}'])[0][:400]}")
358
+ return out
359
+
360
+
361
+ PROGRAM = "python3 -m lean_pkg.claim_axioms"
362
+
363
+
364
+ def main(argv: list[str] | None = None) -> int:
365
+ ap = argparse.ArgumentParser(
366
+ prog=PROGRAM, formatter_class=argparse.RawDescriptionHelpFormatter,
367
+ description="Read the axioms of every claim from a built project's environment (core Lean's "
368
+ "collectAxioms) and judge them as the lower-tier receipt does: a missing claim, sorryAx or an "
369
+ "unchecked claim refuses; an axiom beyond propext, Quot.sound, Classical.choice is listed.",
370
+ epilog="examples:\n"
371
+ " python3 -m lean_pkg.claim_axioms --repo .\n"
372
+ " python3 -m lean_pkg.claim_axioms --repo . MyLib.main_thm --module MyLib --json\n"
373
+ "exit codes: 0 every claim passes, 1 any refused or the probe failed, 2 usage.\n"
374
+ "docs: https://lean-pkg.github.io/lean-pkg/receipts.html")
375
+ ap.add_argument("names", nargs="*", metavar="NAME", help="default: every claim of DIR/claims.yaml")
376
+ ap.add_argument("--repo", dest="project", required=True, metavar="DIR",
377
+ help="the package checkout, a built Lake project")
378
+ ap.add_argument("--module", action="append", default=[], metavar="MOD",
379
+ help="a module to import (default: the claims' files); repeatable")
380
+ ap.add_argument("--toolchain", metavar="TC", help="default: the project's lean-toolchain")
381
+ ap.add_argument("--no-sandbox", action="store_true", help="read the .olean files without the bwrap sandbox")
382
+ ap.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, metavar="SECONDS")
383
+ ap.add_argument("--json", dest="json_out", action="store_true", help="the judgement as JSON on stdout")
384
+ from . import command_tree
385
+ command_tree.apply_program_flag_aliases(ap, PROGRAM)
386
+ argv = sys.argv[1:] if argv is None else list(argv)
387
+ args = ap.parse_args(argv)
388
+ try:
389
+ return _run(args)
390
+ finally: # the old-spelling note (--project), after the output
391
+ for line in command_tree.program_notes(argv, PROGRAM, args.json_out):
392
+ print(line, file=sys.stderr)
393
+
394
+
395
+ def _run(args) -> int:
396
+ from . import dup_constants as dc
397
+ claims_path = pathlib.Path(args.project) / "claims.yaml"
398
+ blob = claims_path.read_bytes() if claims_path.is_file() else None
399
+ required, problems = required_claims(blob)
400
+ names = args.names or required
401
+ modules = args.module or modules_of_claims(blob)
402
+ try:
403
+ text = probe(args.project, names, modules, args.toolchain, not args.no_sandbox, args.timeout)
404
+ except dc.ProbeError as e:
405
+ print(f"claim_axioms: refused: {e}", file=sys.stderr)
406
+ return 1
407
+ summary, refusals, lines = judge(text, None if args.names else required)
408
+ refusals = problems + refusals
409
+ if args.json_out:
410
+ print(json.dumps({"ok": not refusals, "claim_axioms": summary, "refusals": refusals}, indent=2))
411
+ else:
412
+ sys.stdout.write(text)
413
+ for r in refusals:
414
+ print(f"claim_axioms: ✗ {r}", file=sys.stderr)
415
+ for line in lines:
416
+ print(f"claim_axioms: {line}", file=sys.stderr)
417
+ return 0 if not refusals else 1
418
+
419
+
420
+ if __name__ == "__main__":
421
+ sys.exit(main())