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.
- lean_pkg/__init__.py +3 -0
- lean_pkg/adapters/__init__.py +148 -0
- lean_pkg/adapters/github.py +65 -0
- lean_pkg/adapters/leansearch.py +68 -0
- lean_pkg/adapters/loogle.py +45 -0
- lean_pkg/adapters/palomar.py +170 -0
- lean_pkg/adapters/reservoir.py +127 -0
- lean_pkg/anchor.py +678 -0
- lean_pkg/audit.py +716 -0
- lean_pkg/binding_file.py +446 -0
- lean_pkg/blueprint.py +213 -0
- lean_pkg/build_scope.py +282 -0
- lean_pkg/ci_github.py +917 -0
- lean_pkg/claim_axioms.py +421 -0
- lean_pkg/claims.py +1155 -0
- lean_pkg/claims_mark.py +197 -0
- lean_pkg/cli.py +5208 -0
- lean_pkg/cli_parser.py +768 -0
- lean_pkg/command_tree.py +615 -0
- lean_pkg/comparator_config.py +990 -0
- lean_pkg/comparator_contracts.py +382 -0
- lean_pkg/comparator_receipt.py +2854 -0
- lean_pkg/comparator_stage.py +623 -0
- lean_pkg/comparator_types.py +830 -0
- lean_pkg/container.py +172 -0
- lean_pkg/core.py +1570 -0
- lean_pkg/coverage.py +1278 -0
- lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
- lean_pkg/data/toolchain-advisories.yaml +77 -0
- lean_pkg/data/upgrade-breaking.yaml +20 -0
- lean_pkg/data/verify-workflow-pins.yaml +14 -0
- lean_pkg/deps_closure.py +512 -0
- lean_pkg/deps_fill.py +445 -0
- lean_pkg/dup_constants.py +448 -0
- lean_pkg/exercise.py +828 -0
- lean_pkg/exercise_forbid.py +288 -0
- lean_pkg/export_paths.py +77 -0
- lean_pkg/extract.py +1172 -0
- lean_pkg/extract_decls.py +501 -0
- lean_pkg/extract_ledger.py +1408 -0
- lean_pkg/extract_summary.py +132 -0
- lean_pkg/extract_types.py +502 -0
- lean_pkg/extract_write.py +138 -0
- lean_pkg/formalization.py +1078 -0
- lean_pkg/formalization_kept.py +182 -0
- lean_pkg/fresh_repo.py +709 -0
- lean_pkg/gate.py +2141 -0
- lean_pkg/headline.py +211 -0
- lean_pkg/help_topics.py +442 -0
- lean_pkg/holes.py +289 -0
- lean_pkg/host_routes.py +376 -0
- lean_pkg/hypotheses.py +788 -0
- lean_pkg/index.py +1749 -0
- lean_pkg/json_stdout.py +48 -0
- lean_pkg/lake_hygiene.py +289 -0
- lean_pkg/lean_diag.py +280 -0
- lean_pkg/lean_scan.py +1300 -0
- lean_pkg/ledger.py +582 -0
- lean_pkg/next_step.py +510 -0
- lean_pkg/page.py +1831 -0
- lean_pkg/page_html.py +153 -0
- lean_pkg/palomar.py +316 -0
- lean_pkg/palomar_check.py +1027 -0
- lean_pkg/port_modules.py +677 -0
- lean_pkg/prior_art.py +286 -0
- lean_pkg/producer.py +212 -0
- lean_pkg/producer_skew.py +208 -0
- lean_pkg/public_safety.py +1487 -0
- lean_pkg/publish.py +402 -0
- lean_pkg/rebase.py +984 -0
- lean_pkg/receipt.py +2385 -0
- lean_pkg/receipt_check.py +1064 -0
- lean_pkg/receipt_ci.py +660 -0
- lean_pkg/receipt_systemd.py +890 -0
- lean_pkg/recommended.py +232 -0
- lean_pkg/report.py +727 -0
- lean_pkg/reservoir.py +203 -0
- lean_pkg/scaffold.py +588 -0
- lean_pkg/schemas/formalization-0.4.schema.json +344 -0
- lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
- lean_pkg/scripts/ClaimAxioms.lean +47 -0
- lean_pkg/scripts/ContractsOnly.lean +300 -0
- lean_pkg/scripts/DupConstants.lean +149 -0
- lean_pkg/scripts/HypProbe.lean +257 -0
- lean_pkg/scripts/comparator-check.sh +396 -0
- lean_pkg/scripts/verify-comparator.sh +135 -0
- lean_pkg/seal_bundle.py +647 -0
- lean_pkg/search.py +865 -0
- lean_pkg/site_profiles/easley.yaml +10 -0
- lean_pkg/site_profiles/github-actions.yaml +12 -0
- lean_pkg/sites.py +225 -0
- lean_pkg/stacks.py +373 -0
- lean_pkg/statements_module.py +217 -0
- lean_pkg/templates/Apache-2.0.txt +202 -0
- lean_pkg/toolchain_advisories.py +225 -0
- lean_pkg/upgrade.py +706 -0
- lean_pkg/verify.py +495 -0
- lean_pkg-0.25.0.dist-info/METADATA +93 -0
- lean_pkg-0.25.0.dist-info/RECORD +103 -0
- lean_pkg-0.25.0.dist-info/WHEEL +5 -0
- lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
- lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
- lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/exercise.py
ADDED
|
@@ -0,0 +1,828 @@
|
|
|
1
|
+
# lean-exercise -- judge a learner's Lean solution against a Challenge with `lake comparator`.
|
|
2
|
+
"""lean-exercise: judge a Solution file against a Challenge file, one theorem at a time.
|
|
3
|
+
|
|
4
|
+
Registry-free and read-only: no registry, event log, git, receipt or lease is ever opened. The only
|
|
5
|
+
writes go to a fresh temporary directory (removed afterwards unless --keep DIR). The learner's code is
|
|
6
|
+
built only by `lake comparator`, inside its bwrap sandbox, unless --no-sandbox is given, and then the
|
|
7
|
+
verdict is a self-check, never a grade. Mathlib-free unless --project names a prebuilt Mathlib project,
|
|
8
|
+
whose packages are then bound read-only into the sandbox (never downloaded). `batch` judges a directory of
|
|
9
|
+
Solutions into one CSV row each. Results are never registry evidence.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import csv
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import pathlib
|
|
19
|
+
import re
|
|
20
|
+
import shlex
|
|
21
|
+
import shutil
|
|
22
|
+
import signal
|
|
23
|
+
import subprocess
|
|
24
|
+
import sys
|
|
25
|
+
import tempfile
|
|
26
|
+
import time
|
|
27
|
+
|
|
28
|
+
from . import build_scope
|
|
29
|
+
from . import comparator_receipt as cr
|
|
30
|
+
from . import exercise_forbid as fb
|
|
31
|
+
from . import lean_scan
|
|
32
|
+
from .deps_closure import header_imports
|
|
33
|
+
from .palomar_check import has_module_header
|
|
34
|
+
from .audit import parse_lean_toolchain
|
|
35
|
+
from .core import scrubbed_env
|
|
36
|
+
|
|
37
|
+
SCHEMA = "exercise-check/1"
|
|
38
|
+
BATCH_SCHEMA = "exercise-batch/1"
|
|
39
|
+
FLOOR = cr.TOOLCHAIN_FLOOR # v4.35.0-rc2: the first toolchain with `lake comparator`
|
|
40
|
+
DEFAULT_TIMEOUT = 600
|
|
41
|
+
STD_AXIOMS = ("propext", "Quot.sound", "Classical.choice")
|
|
42
|
+
# A Challenge may only state theorems: comparator compares definitions by type alone, so a definition
|
|
43
|
+
# the Solution must supply could be replaced by any term of that type. Shared definitions go in --defs.
|
|
44
|
+
DEF_KEYWORDS = ("def", "abbrev", "structure", "class", "instance", "inductive", "opaque", "axiom",
|
|
45
|
+
"irreducible_def")
|
|
46
|
+
IMPORT_OK = re.compile(r"^(Init|Std|Lean)(\.|$)")
|
|
47
|
+
PASS_LINE = "Your solution is okay!"
|
|
48
|
+
VERDICTS = ("accepted", "statement_mismatch", "illegal_axiom", "forbidden_constant", "kernel_rejected",
|
|
49
|
+
"build_error", "missing", "timeout", "tool_error")
|
|
50
|
+
FORBID_SCOPES = ("solution", "all")
|
|
51
|
+
NO_SANDBOX_WARN = ("WARN: --no-sandbox: the Solution's code {} UNSANDBOXED on this machine, with your "
|
|
52
|
+
"user's rights. This verdict is a self-check only: never use it to grade someone else's "
|
|
53
|
+
"work. Run without --no-sandbox on Linux (or WSL2) for a sandboxed check.")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Refusal(Exception):
|
|
57
|
+
"""Usage or host refusal: exit 2, nothing written (or the temporary directory removed)."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def sha256(p: pathlib.Path) -> str:
|
|
61
|
+
return hashlib.sha256(p.read_bytes()).hexdigest()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
65
|
+
# Reading the exercise (no Lean involved)
|
|
66
|
+
|
|
67
|
+
def _masked(text: str) -> str:
|
|
68
|
+
return lean_scan._mask(text)[0] # comments and strings blanked, newlines kept
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def imports(text: str) -> list[str]:
|
|
72
|
+
"""The header's imports, module-system forms included (`public import X`, `meta import X`,
|
|
73
|
+
`import all X`): a bare `^import` match missed those, so a `public import Mathlib` passed the checks."""
|
|
74
|
+
return header_imports(text)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
_BOUNDARY = re.compile(r"^(namespace|section|end|open|variable|universe|set_option|attribute|#|@\[|"
|
|
78
|
+
r"private|protected|public|meta|noncomputable|theorem|lemma|def|abbrev|structure|class|"
|
|
79
|
+
r"instance|inductive|opaque|axiom|example|macro|syntax|notation|infix|prefix|postfix)\b",
|
|
80
|
+
re.M)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def scan(text: str) -> list[dict]:
|
|
84
|
+
"""Every declaration: {name, keyword, line, private, sorry}; `sorry` when the masked source from
|
|
85
|
+
the declaration to the next top-level command mentions the `sorry` keyword."""
|
|
86
|
+
masked = _masked(text)
|
|
87
|
+
lines = masked.split("\n")
|
|
88
|
+
decls = lean_scan.declarations(text)
|
|
89
|
+
starts = sorted({d[0] for d in decls} | {i + 1 for i, ln in enumerate(lines) if _BOUNDARY.match(ln)})
|
|
90
|
+
out = []
|
|
91
|
+
for line, kw, qual, _doc, src, _written in decls:
|
|
92
|
+
nxt = next((s for s in starts if s > line), len(lines) + 1)
|
|
93
|
+
body = "\n".join(lines[line - 1:nxt - 1])
|
|
94
|
+
out.append({"name": qual, "keyword": kw, "line": line,
|
|
95
|
+
"private": bool(re.match(r"^\s*(@\[[^\]]*\]\s*)*private\b", src)),
|
|
96
|
+
"sorry": bool(re.search(r"(?<![\w.'])sorry(?![\w'])", body))})
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def read_lean(path: str, what: str) -> tuple[pathlib.Path, str]:
|
|
101
|
+
p = pathlib.Path(path)
|
|
102
|
+
if not p.is_file():
|
|
103
|
+
raise Refusal(f"{what} {path}: not a file")
|
|
104
|
+
if p.suffix != ".lean":
|
|
105
|
+
raise Refusal(f"{what} {path}: expected a .lean file")
|
|
106
|
+
try:
|
|
107
|
+
return p, p.read_bytes().decode("utf-8")
|
|
108
|
+
except UnicodeDecodeError:
|
|
109
|
+
raise Refusal(f"{what} {path}: not UTF-8") from None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def check_imports(text: str, what: str, has_defs: bool, mathlib: bool = False) -> None:
|
|
113
|
+
for mod in imports(text):
|
|
114
|
+
if IMPORT_OK.match(mod) or (has_defs and mod == "Defs"):
|
|
115
|
+
continue
|
|
116
|
+
if mod == "Defs":
|
|
117
|
+
raise Refusal(f"{what} imports Defs but no --defs FILE was given")
|
|
118
|
+
if mod.split(".")[0] == "Mathlib":
|
|
119
|
+
if mathlib:
|
|
120
|
+
continue
|
|
121
|
+
raise Refusal(f"{what} imports {mod}: Mathlib needs --project DIR, a project whose "
|
|
122
|
+
f"lake-manifest.json pins Mathlib and whose Mathlib is already built")
|
|
123
|
+
ok = "Init, Std, Lean" + (", Mathlib" if mathlib else "") + (" and Defs" if has_defs else "")
|
|
124
|
+
raise Refusal(f"{what} imports {mod}: only {ok} can be imported (the exercise is judged as a "
|
|
125
|
+
f"standalone project)")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
_DEF_CMD = re.compile(r"^\s*(?:@\[[^\]]*\]\s*)*(?:(?:private|protected|public|meta|noncomputable|partial|"
|
|
129
|
+
r"unsafe|scoped|local|nonrec)\s+)*(" + "|".join(DEF_KEYWORDS) + r")\b")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def plan_theorems(challenge: str, requested: str | None) -> list[str]:
|
|
133
|
+
decls = scan(challenge)
|
|
134
|
+
defs = [d for d in decls if d["keyword"] in DEF_KEYWORDS]
|
|
135
|
+
seen = {d["line"] for d in defs}
|
|
136
|
+
for i, ln in enumerate(_masked(challenge).split("\n"), 1): # anonymous instances have no name to scan
|
|
137
|
+
m = _DEF_CMD.match(ln)
|
|
138
|
+
if m and i not in seen:
|
|
139
|
+
defs.append({"keyword": m.group(1), "name": "(anonymous)", "line": i})
|
|
140
|
+
if defs:
|
|
141
|
+
names = ", ".join(f"{d['keyword']} {d['name']} (line {d['line']})" for d in defs[:5])
|
|
142
|
+
raise Refusal(f"the Challenge declares {names}: comparator compares a definition by its type only, "
|
|
143
|
+
f"so a Solution could supply any other term of that type. Put shared definitions in "
|
|
144
|
+
f"a Defs.lean passed with --defs FILE and imported by both files")
|
|
145
|
+
theorems = [d for d in decls if d["keyword"] in ("theorem", "lemma")]
|
|
146
|
+
if requested is not None:
|
|
147
|
+
names = [n.strip() for n in requested.split(",") if n.strip()]
|
|
148
|
+
if not names:
|
|
149
|
+
raise Refusal("--theorems is empty")
|
|
150
|
+
known = {d["name"]: d for d in theorems}
|
|
151
|
+
unknown = [n for n in names if n not in known]
|
|
152
|
+
if unknown:
|
|
153
|
+
raise Refusal(f"--theorems {', '.join(unknown)}: not a theorem or lemma of the Challenge "
|
|
154
|
+
f"(fully qualified; found: {', '.join(known) or 'none'})")
|
|
155
|
+
chosen = [known[n] for n in dict.fromkeys(names)]
|
|
156
|
+
else:
|
|
157
|
+
chosen = [d for d in theorems if d["sorry"]]
|
|
158
|
+
if not chosen:
|
|
159
|
+
raise Refusal("the Challenge has no theorem or lemma whose proof is `sorry`; state each exercise "
|
|
160
|
+
"as `theorem name ... := by sorry` (or name them with --theorems)")
|
|
161
|
+
private = [d["name"] for d in chosen if d["private"]]
|
|
162
|
+
if private:
|
|
163
|
+
raise Refusal(f"private theorem(s) {', '.join(private)}: a private name cannot be judged; drop `private`")
|
|
164
|
+
return [d["name"] for d in chosen]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def plan_axioms(value: str | None) -> list[str]:
|
|
168
|
+
if value is None:
|
|
169
|
+
return list(STD_AXIOMS)
|
|
170
|
+
axioms = [a.strip() for a in value.split(",") if a.strip()]
|
|
171
|
+
extra = [a for a in axioms if a not in STD_AXIOMS]
|
|
172
|
+
if extra:
|
|
173
|
+
raise Refusal(f"--axioms {', '.join(extra)}: v1 permits only a subset of the standard axioms "
|
|
174
|
+
f"{', '.join(STD_AXIOMS)}, so a grader cannot accidentally permit a cheat")
|
|
175
|
+
return list(dict.fromkeys(axioms))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
179
|
+
# Host and toolchain (read-only)
|
|
180
|
+
|
|
181
|
+
def host_report() -> dict:
|
|
182
|
+
return cr.host_checks()
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def platform_hint() -> str:
|
|
186
|
+
if sys.platform == "darwin" or sys.platform.startswith("win"):
|
|
187
|
+
return ("the sandbox needs Linux (bwrap): run inside WSL2 or a Linux machine, or pass --no-sandbox "
|
|
188
|
+
"to self-check your own code only")
|
|
189
|
+
return ("on Ubuntu 24.04 bwrap is blocked by AppArmor by default (docs/comparator.md, Host requirements "
|
|
190
|
+
"per mechanism); --no-sandbox runs a self-check of your own code only")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def host_preflight(no_sandbox: bool) -> str:
|
|
194
|
+
"""'sandboxed' or 'self-check-only'; a refusal lists the failing host lines."""
|
|
195
|
+
if no_sandbox:
|
|
196
|
+
return "self-check-only"
|
|
197
|
+
res = host_report()
|
|
198
|
+
by = {c["item"]: c for c in res["checks"]}
|
|
199
|
+
failing = [f"{i}: {by[i]['detail']}" for i in ("kernel", "bwrap") if i in by and by[i]["level"] == "fail"]
|
|
200
|
+
if failing:
|
|
201
|
+
raise Refusal("this host cannot run the sandboxed judge:\n " + "\n ".join(failing)
|
|
202
|
+
+ f"\nhint: {platform_hint()}")
|
|
203
|
+
return "sandboxed"
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def toolchain_dir(toolchain: str) -> pathlib.Path:
|
|
207
|
+
return cr.elan_home() / "toolchains" / toolchain.replace("/", "--").replace(":", "---")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def installed_toolchains() -> list[str]:
|
|
211
|
+
d = cr.elan_home() / "toolchains"
|
|
212
|
+
try:
|
|
213
|
+
names = sorted(x.name for x in d.iterdir() if x.is_dir())
|
|
214
|
+
except OSError:
|
|
215
|
+
return []
|
|
216
|
+
return [n.replace("---", ":").replace("--", "/") for n in names]
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def resolve(toolchain: str | None) -> tuple[str, pathlib.Path, pathlib.Path]:
|
|
220
|
+
"""(toolchain, its prefix, elan's lake): the --toolchain, else the newest installed >= FLOOR."""
|
|
221
|
+
install = f"elan toolchain install leanprover/lean4:{FLOOR}"
|
|
222
|
+
floor = parse_lean_toolchain(FLOOR)
|
|
223
|
+
eb = cr.elan_bin()
|
|
224
|
+
if eb is None:
|
|
225
|
+
raise Refusal(f"elan not found ({cr.elan_home() / 'bin' / 'elan'}); install elan, then `{install}`")
|
|
226
|
+
if toolchain:
|
|
227
|
+
tc = toolchain if ":" in toolchain else f"leanprover/lean4:{toolchain}"
|
|
228
|
+
key = parse_lean_toolchain(tc)
|
|
229
|
+
if key is None or key < floor:
|
|
230
|
+
raise Refusal(f"--toolchain {toolchain}: lean-exercise needs a release toolchain {FLOOR} or later "
|
|
231
|
+
f"(the first with `lake comparator`); `{install}`")
|
|
232
|
+
if not toolchain_dir(tc).is_dir():
|
|
233
|
+
raise Refusal(f"toolchain {tc} is not installed; `elan toolchain install {tc}`")
|
|
234
|
+
else:
|
|
235
|
+
ok = [t for t in installed_toolchains() if (parse_lean_toolchain(t) or (0,)) >= floor]
|
|
236
|
+
if not ok:
|
|
237
|
+
raise Refusal(f"no installed toolchain is {FLOOR} or later (`lake comparator` ships from {FLOOR}); "
|
|
238
|
+
f"`{install}`")
|
|
239
|
+
tc = max(ok, key=parse_lean_toolchain)
|
|
240
|
+
prefix = toolchain_dir(tc)
|
|
241
|
+
missing = [t for t in cr.TOOLCHAIN_TOOLS if not os.access(prefix / "bin" / t, os.X_OK)]
|
|
242
|
+
if missing:
|
|
243
|
+
raise Refusal(f"toolchain {tc} does not bundle {', '.join(missing)}; `{install}`")
|
|
244
|
+
return tc, prefix, eb / "lake"
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
248
|
+
# --project: a prebuilt Mathlib project whose packages the sandbox reads (read-only, never downloaded)
|
|
249
|
+
|
|
250
|
+
PKG_LIB = pathlib.Path(".lake") / "build" / "lib" / "lean"
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def load_project(path: str) -> dict:
|
|
254
|
+
"""{root, toolchain, packages (real path), binds, requires, manifest, lean_path} of a --project DIR:
|
|
255
|
+
lean-toolchain + lake-manifest.json pinning mathlib, every package checked out and Mathlib built."""
|
|
256
|
+
root = pathlib.Path(path)
|
|
257
|
+
if not root.is_dir():
|
|
258
|
+
raise Refusal(f"--project {path}: not a directory")
|
|
259
|
+
tc_file, man_file = root / "lean-toolchain", root / "lake-manifest.json"
|
|
260
|
+
for f in (tc_file, man_file):
|
|
261
|
+
if not f.is_file():
|
|
262
|
+
raise Refusal(f"--project {path}: no {f.name} (the project must pin its toolchain and Mathlib)")
|
|
263
|
+
toolchain = tc_file.read_text(encoding="utf-8").strip()
|
|
264
|
+
try:
|
|
265
|
+
man = json.loads(man_file.read_text(encoding="utf-8"))
|
|
266
|
+
pkgs = man["packages"]
|
|
267
|
+
assert isinstance(pkgs, list) and all(isinstance(x, dict) and "name" in x for x in pkgs)
|
|
268
|
+
except (ValueError, KeyError, AssertionError, OSError):
|
|
269
|
+
raise Refusal(f"--project {path}: lake-manifest.json is not a Lake manifest") from None
|
|
270
|
+
if not any(x["name"] == "mathlib" for x in pkgs):
|
|
271
|
+
raise Refusal(f"--project {path}: lake-manifest.json has no mathlib package")
|
|
272
|
+
pdir = root / (man.get("packagesDir") or ".lake/packages")
|
|
273
|
+
hint = "run `lake exe cache get` (or `lake build`) in the project first: judging never downloads"
|
|
274
|
+
if not pdir.is_dir():
|
|
275
|
+
raise Refusal(f"--project {path}: {pdir.name}/ is missing; {hint}")
|
|
276
|
+
real = pdir.resolve()
|
|
277
|
+
binds, lean_path = [real], []
|
|
278
|
+
for x in pkgs:
|
|
279
|
+
if x.get("type") != "git":
|
|
280
|
+
raise Refusal(f"--project {path}: dependency {x['name']} is a {x.get('type')} dependency; only "
|
|
281
|
+
f"git dependencies (as Mathlib's are) are supported")
|
|
282
|
+
dname = build_scope.lake_dir_name(x.get("name"))
|
|
283
|
+
if dname is None or "/" in dname or "\\" in dname or dname in (".", ".."):
|
|
284
|
+
raise Refusal(f"--project {path}: dependency name {x.get('name')!r} is not a Lake package name")
|
|
285
|
+
d = real / dname
|
|
286
|
+
if not d.is_dir():
|
|
287
|
+
raise Refusal(f"--project {path}: dependency {dname} is not checked out; {hint}")
|
|
288
|
+
rd = d.resolve()
|
|
289
|
+
if not rd.is_relative_to(real):
|
|
290
|
+
binds.append(rd)
|
|
291
|
+
lean_path.append(rd / PKG_LIB)
|
|
292
|
+
if not (real / "mathlib" / PKG_LIB / "Mathlib.olean").is_file():
|
|
293
|
+
raise Refusal(f"--project {path}: Mathlib is not built (no Mathlib.olean); {hint}")
|
|
294
|
+
return {"root": root.resolve(), "toolchain": toolchain, "packages": real, "binds": binds,
|
|
295
|
+
"requires": [x for x in pkgs if not x.get("inherited")], "manifest": man, "lean_path": lean_path}
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def require_toml(pkg: dict) -> str:
|
|
299
|
+
"""A lakefile.toml [[require]] matching the manifest entry, so Lake takes the pinned checkout as is."""
|
|
300
|
+
q = json.dumps
|
|
301
|
+
out = [f"\n[[require]]\nname = {q(pkg['name'])}"]
|
|
302
|
+
out.append(f"scope = {q(pkg['scope'])}" if pkg.get("scope") else f"git = {q(pkg['url'])}")
|
|
303
|
+
if pkg.get("inputRev"):
|
|
304
|
+
out.append(f"rev = {q(pkg['inputRev'])}")
|
|
305
|
+
if pkg.get("subDir"):
|
|
306
|
+
out.append(f"subDir = {q(pkg['subDir'])}")
|
|
307
|
+
return "\n".join(out) + "\n"
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
# `lake comparator` passes its whole bwrap command line through COMPARATOR_BWRAP. This wrapper binds the
|
|
311
|
+
# project's packages read-only into each sandbox (they sit under a home directory the sandbox covers) and
|
|
312
|
+
# drops --share-net, so even dependency resolution has no network. It fails closed on an unexpected line.
|
|
313
|
+
WRAPPER = """#!/bin/sh
|
|
314
|
+
# lean-exercise --project: bind the prebuilt packages read-only; no sandbox gets a network.
|
|
315
|
+
done=0; prev2=; prev1=
|
|
316
|
+
for a in "$@"; do
|
|
317
|
+
shift
|
|
318
|
+
if [ "$done" = 0 ] && [ "$a" = --share-net ]; then continue; fi
|
|
319
|
+
if [ "$done" = 0 ] && [ "$a" = -- ] && [ "$prev2" = --chdir ]; then
|
|
320
|
+
set -- "$@" {binds}
|
|
321
|
+
done=1
|
|
322
|
+
fi
|
|
323
|
+
set -- "$@" "$a"; prev2=$prev1; prev1=$a
|
|
324
|
+
done
|
|
325
|
+
if [ "$done" = 0 ]; then
|
|
326
|
+
echo "lean-exercise: unexpected bwrap command line from lake comparator; refusing to run it" >&2
|
|
327
|
+
exit 125
|
|
328
|
+
fi
|
|
329
|
+
exec {bwrap} "$@"
|
|
330
|
+
"""
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def real_bwrap() -> str:
|
|
334
|
+
bw = os.environ.get("COMPARATOR_BWRAP") or "bwrap"
|
|
335
|
+
found = shutil.which(bw)
|
|
336
|
+
if found is None:
|
|
337
|
+
raise Refusal(f"{bw} not found: `lake comparator` sandboxes with bwrap (package bubblewrap)")
|
|
338
|
+
return os.path.abspath(found)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def write_wrapper(work: pathlib.Path, binds: list[pathlib.Path]) -> pathlib.Path:
|
|
342
|
+
|
|
343
|
+
args = " ".join(f"--ro-bind {shlex.quote(str(b))} {shlex.quote(str(b))}" for b in binds)
|
|
344
|
+
p = work / "bwrap-wrapper.sh"
|
|
345
|
+
p.write_text(WRAPPER.format(binds=args, bwrap=shlex.quote(real_bwrap())), encoding="utf-8")
|
|
346
|
+
p.chmod(0o755)
|
|
347
|
+
return p
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
351
|
+
# The temporary project
|
|
352
|
+
|
|
353
|
+
MANIFEST = {"version": "1.2.0", "packagesDir": ".lake/packages", "packages": [], "name": "exercise",
|
|
354
|
+
"lakeDir": ".lake", "fixedToolchain": False}
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def write_project(work: pathlib.Path, toolchain: str, prefix: pathlib.Path, files: dict[str, pathlib.Path],
|
|
358
|
+
theorems: list[str], axioms: list[str], project: dict | None = None) -> list[pathlib.Path]:
|
|
359
|
+
"""lean-toolchain, lakefile.toml, lake-manifest.json, the .lean files byte for byte, and one comparator
|
|
360
|
+
configuration per theorem (cfg/<i>.json); returns the configuration paths. With a --project, the
|
|
361
|
+
lakefile requires its direct dependencies, the manifest pins them as the project's does, and
|
|
362
|
+
.lake/packages is a link to the project's (bound read-only by the wrapper)."""
|
|
363
|
+
(work / "lean-toolchain").write_text(toolchain + "\n", encoding="utf-8")
|
|
364
|
+
libs = "".join(f'\n[[lean_lib]]\nname = "{m}"\n' for m in files)
|
|
365
|
+
reqs = "".join(require_toml(x) for x in project["requires"]) if project else ""
|
|
366
|
+
(work / "lakefile.toml").write_text(f'name = "exercise"\n{reqs}{libs}', encoding="utf-8")
|
|
367
|
+
manifest = dict(MANIFEST)
|
|
368
|
+
if project:
|
|
369
|
+
manifest["packages"] = project["manifest"]["packages"]
|
|
370
|
+
(work / ".lake").mkdir(exist_ok=True)
|
|
371
|
+
(work / ".lake" / "packages").symlink_to(project["packages"], target_is_directory=True)
|
|
372
|
+
(work / "lake-manifest.json").write_text(json.dumps(manifest, indent=1) + "\n", encoding="utf-8")
|
|
373
|
+
for mod, src in files.items():
|
|
374
|
+
shutil.copyfile(src, work / f"{mod}.lean")
|
|
375
|
+
(work / "cfg").mkdir()
|
|
376
|
+
(work / "lake-cache").mkdir()
|
|
377
|
+
cfgs = []
|
|
378
|
+
for i, name in enumerate(theorems, 1):
|
|
379
|
+
cfg = {"challenge_module": "Challenge", "solution_module": "Solution", "theorem_names": [name],
|
|
380
|
+
"definition_names": [], "permitted_axioms": axioms,
|
|
381
|
+
"external_kernels": {"nanoda": [str(prefix / "bin" / "nanoda_bin")],
|
|
382
|
+
"con-ron": [str(prefix / "bin" / "con-ron")]}}
|
|
383
|
+
p = work / "cfg" / f"{i}.json"
|
|
384
|
+
p.write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
|
|
385
|
+
cfgs.append(p)
|
|
386
|
+
return cfgs
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
390
|
+
# Judging and reading the verdict
|
|
391
|
+
|
|
392
|
+
def judge(lake: pathlib.Path, work: pathlib.Path, cfg: pathlib.Path, toolchain: str, timeout: float,
|
|
393
|
+
no_sandbox: bool, wrapper: pathlib.Path | None = None) -> tuple[int | None, str, float]:
|
|
394
|
+
"""(exit code or None on timeout, merged output, seconds)."""
|
|
395
|
+
env = scrubbed_env()
|
|
396
|
+
env.update({"PATH": os.pathsep.join([str(lake.parent), env.get("PATH", "")]), "ELAN_TOOLCHAIN": toolchain,
|
|
397
|
+
"LAKE_ARTIFACT_CACHE": "false", "LAKE_CACHE_DIR": str(work / "lake-cache")})
|
|
398
|
+
if wrapper is not None:
|
|
399
|
+
env["COMPARATOR_BWRAP"] = str(wrapper)
|
|
400
|
+
cmd = [str(lake), "comparator", "--config", str(cfg)] + (["--inadvisably-no-sandbox"] if no_sandbox else [])
|
|
401
|
+
t0 = time.monotonic()
|
|
402
|
+
p = subprocess.Popen(cmd, cwd=work, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
|
403
|
+
stderr=subprocess.STDOUT, start_new_session=True)
|
|
404
|
+
try:
|
|
405
|
+
out, _ = p.communicate(timeout=timeout)
|
|
406
|
+
rc = p.returncode
|
|
407
|
+
except subprocess.TimeoutExpired:
|
|
408
|
+
try:
|
|
409
|
+
os.killpg(p.pid, signal.SIGKILL)
|
|
410
|
+
except OSError:
|
|
411
|
+
pass
|
|
412
|
+
out, _ = p.communicate()
|
|
413
|
+
rc = None
|
|
414
|
+
return rc, out.decode("utf-8", errors="replace"), time.monotonic() - t0
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _quoted(line: str, marker: str) -> str:
|
|
418
|
+
m = re.search(re.escape(marker) + r"\s*'([^']*)'", line)
|
|
419
|
+
return m.group(1) if m else ""
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
# Lean's module system (`module` first): a declaration is private unless it is inside `public section`
|
|
423
|
+
# or marked `public`, and `lake comparator` cannot export a private constant ("not found in environment").
|
|
424
|
+
PRIVATE_HINT = ("in a `module` file a theorem is private unless it is inside `public section ... end` or "
|
|
425
|
+
"declared `public theorem`")
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def classify(rc: int | None, out: str, solution_module: bool = False) -> dict:
|
|
429
|
+
"""{verdict, detail, axiom?, kernels} from the exit code and the marker lines of `lake comparator`.
|
|
430
|
+
`solution_module`: the Solution starts with `module`, so a `missing` theorem may only be private."""
|
|
431
|
+
lines = out.splitlines()
|
|
432
|
+
kernels = [m.group(1) for ln in lines for m in [re.match(r"^(.+?) kernel accepts the solution$", ln)] if m]
|
|
433
|
+
kernels = ["lean" if k == "Lean default" else k for k in kernels]
|
|
434
|
+
res = {"kernels": kernels}
|
|
435
|
+
if rc is None:
|
|
436
|
+
return {**res, "verdict": "timeout", "detail": "the judge did not finish in time (--timeout)"}
|
|
437
|
+
if rc == 0 and PASS_LINE in lines:
|
|
438
|
+
return {**res, "verdict": "accepted", "detail": PASS_LINE}
|
|
439
|
+
for ln in lines:
|
|
440
|
+
if "Illegal axiom detected:" in ln:
|
|
441
|
+
ax = _quoted(ln, "Illegal axiom detected:")
|
|
442
|
+
detail = ("uses sorry" if ax == "sorryAx" else
|
|
443
|
+
"uses native_decide (Lean.ofReduceBool)" if "native_decide" in ax or "ofReduceBool" in ax
|
|
444
|
+
else f"uses the axiom {ax}")
|
|
445
|
+
return {**res, "verdict": "illegal_axiom", "axiom": "sorry" if ax == "sorryAx" else ax,
|
|
446
|
+
"detail": detail}
|
|
447
|
+
if re.search(r"do not match|don't match|does not match between challenge|"
|
|
448
|
+
r"Solution constant is not a theorem", ln):
|
|
449
|
+
return {**res, "verdict": "statement_mismatch", "detail": ln.removeprefix("error: ").strip()}
|
|
450
|
+
if re.search(r"not found in solution|Constant \S+ not found in environment", ln):
|
|
451
|
+
# Exported before the Solution was built: the Challenge's own constant is missing (a private
|
|
452
|
+
# theorem of a `module` Challenge). That is the exercise's fault, not the learner's.
|
|
453
|
+
if "not found in environment" in ln and not any(x.startswith("Building Solution") for x in lines):
|
|
454
|
+
return {**res, "verdict": "tool_error",
|
|
455
|
+
"detail": f"the Challenge does not export this theorem; {PRIVATE_HINT}"}
|
|
456
|
+
detail = "the Solution does not declare this theorem"
|
|
457
|
+
return {**res, "verdict": "missing",
|
|
458
|
+
"detail": f"{detail} (or does not make it public: {PRIVATE_HINT})" if solution_module else detail}
|
|
459
|
+
if "kernel rejected the solution" in ln:
|
|
460
|
+
return {**res, "verdict": "kernel_rejected", "detail": ln.strip()}
|
|
461
|
+
if "error: build failed" in lines or any(ln.startswith("Some required targets logged failures") for ln in lines):
|
|
462
|
+
solution_started = any(ln.startswith("Building Solution") for ln in lines)
|
|
463
|
+
first = next((ln.removeprefix("error: ") for ln in lines
|
|
464
|
+
if re.match(r"^error: (Challenge|Solution|Defs)\.lean:\d+:\d+:", ln)), "")
|
|
465
|
+
if not solution_started or first.startswith(("Challenge.lean", "Defs.lean")):
|
|
466
|
+
return {**res, "verdict": "tool_error", "detail": "the Challenge (or Defs) does not build: " + first}
|
|
467
|
+
return {**res, "verdict": "build_error", "detail": first or "the Solution does not build"}
|
|
468
|
+
tail = next((ln.strip() for ln in reversed(lines) if ln.strip()), "no output")
|
|
469
|
+
return {**res, "verdict": "tool_error", "detail": f"exit {rc}: {tail[:300]}"}
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def redact(text: str, work: pathlib.Path) -> str:
|
|
473
|
+
return text.replace(str(work), "<workdir>").replace(str(pathlib.Path.home()), "~")
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
477
|
+
# The command
|
|
478
|
+
|
|
479
|
+
def make_workdir(keep: str | None) -> pathlib.Path:
|
|
480
|
+
if keep:
|
|
481
|
+
p = pathlib.Path(keep)
|
|
482
|
+
if p.exists() and (not p.is_dir() or any(p.iterdir())):
|
|
483
|
+
raise Refusal(f"--keep {keep}: must not exist or be an empty directory")
|
|
484
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
485
|
+
return p.resolve()
|
|
486
|
+
base = os.environ.get("TMPDIR") or os.environ.get("XDG_STATE_HOME") or None
|
|
487
|
+
return pathlib.Path(tempfile.mkdtemp(prefix="lean-exercise-", dir=base)).resolve()
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def full_toolchain(tc: str) -> str:
|
|
491
|
+
return tc if ":" in tc else f"leanprover/lean4:{tc}"
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def plan_forbid(args) -> dict | None:
|
|
495
|
+
prefixes = [x.strip() for x in args.forbid or []]
|
|
496
|
+
exact = [x.strip() for x in args.forbid_exact or []]
|
|
497
|
+
bad = [x for x in prefixes + exact if not x or any(c.isspace() for c in x)]
|
|
498
|
+
if bad:
|
|
499
|
+
raise Refusal(f"--forbid / --forbid-exact {bad[0]!r}: a constant name or name prefix, no spaces")
|
|
500
|
+
if not prefixes and not exact:
|
|
501
|
+
if args.forbid_scope != "solution":
|
|
502
|
+
raise Refusal("--forbid-scope needs --forbid PREFIX or --forbid-exact NAME")
|
|
503
|
+
return None
|
|
504
|
+
return {"prefixes": list(dict.fromkeys(prefixes)), "exact": list(dict.fromkeys(exact)),
|
|
505
|
+
"scope": args.forbid_scope}
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def prepare(args) -> dict:
|
|
509
|
+
"""Everything shared by every Solution: the exercise, the host, the toolchain, --project, --forbid."""
|
|
510
|
+
if args.mathlib:
|
|
511
|
+
raise Refusal("--mathlib is not a flag: pass --project DIR, a project that pins and has built Mathlib")
|
|
512
|
+
if args.timeout <= 0:
|
|
513
|
+
raise Refusal("--timeout must be positive")
|
|
514
|
+
project = load_project(args.project) if args.project else None
|
|
515
|
+
challenge_p, challenge = read_lean(args.challenge, "--challenge")
|
|
516
|
+
files = {"Challenge": challenge_p}
|
|
517
|
+
if args.defs:
|
|
518
|
+
defs_p, defs = read_lean(args.defs, "--defs")
|
|
519
|
+
check_imports(defs, "--defs", False, bool(project))
|
|
520
|
+
if any(d["sorry"] for d in scan(defs)):
|
|
521
|
+
raise Refusal("--defs: the shared definitions must not use sorry")
|
|
522
|
+
files["Defs"] = defs_p
|
|
523
|
+
check_imports(challenge, "the Challenge", bool(args.defs), bool(project))
|
|
524
|
+
theorems = plan_theorems(challenge, args.theorems)
|
|
525
|
+
axioms = plan_axioms(args.axioms)
|
|
526
|
+
forbid = plan_forbid(args)
|
|
527
|
+
trust = host_preflight(args.no_sandbox)
|
|
528
|
+
requested = args.toolchain
|
|
529
|
+
if project:
|
|
530
|
+
if requested and full_toolchain(requested) != full_toolchain(project["toolchain"]):
|
|
531
|
+
raise Refusal(f"--toolchain {requested}: the --project pins {project['toolchain']}, and its "
|
|
532
|
+
f"Mathlib is built with that one")
|
|
533
|
+
requested = project["toolchain"]
|
|
534
|
+
toolchain, prefix, lake = resolve(requested)
|
|
535
|
+
return {"challenge_p": challenge_p, "files": files, "theorems": theorems, "axioms": axioms,
|
|
536
|
+
"forbid": forbid, "trust": trust, "toolchain": toolchain, "prefix": prefix, "lake": lake,
|
|
537
|
+
"project": project, "no_sandbox": args.no_sandbox, "timeout": args.timeout,
|
|
538
|
+
"has_defs": bool(args.defs)}
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def read_solution(plan: dict, path: str) -> tuple[pathlib.Path, str]:
|
|
542
|
+
solution_p, solution = read_lean(path, "--solution")
|
|
543
|
+
check_imports(solution, "the Solution", plan["has_defs"], bool(plan["project"]))
|
|
544
|
+
return solution_p, solution
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def forbidden(plan: dict, work: pathlib.Path, solution: str, names: list[str]) -> dict[str, list[dict]]:
|
|
548
|
+
"""{theorem: [{constant, via}]} from a sandboxed export of the built Solution (exercise_forbid)."""
|
|
549
|
+
fz, project = plan["forbid"], plan["project"]
|
|
550
|
+
scratch = work / "forbid"
|
|
551
|
+
scratch.mkdir(exist_ok=True)
|
|
552
|
+
lean_path = [work / PKG_LIB] + (project["lean_path"] if project else [])
|
|
553
|
+
readable = project["binds"] if project else []
|
|
554
|
+
sandboxed = not plan["no_sandbox"]
|
|
555
|
+
lits = [fb.literal(tuple(n.split("."))) for n in names]
|
|
556
|
+
if None in lits:
|
|
557
|
+
raise fb.ExportError("a judged theorem name cannot be passed to leanexport")
|
|
558
|
+
out = scratch / "solution.ndjson"
|
|
559
|
+
fb.run_export(plan["prefix"], lean_path, readable, work, ["Solution"], lits, out, sandboxed, plan["timeout"])
|
|
560
|
+
ex = fb.read_export(out)
|
|
561
|
+
classify = fb.library_classifier(plan["prefix"], lean_path, readable, work, imports(solution), "Solution",
|
|
562
|
+
scratch, sandboxed, plan["timeout"])
|
|
563
|
+
return {n: fb.find_forbidden(ex, n, fz["prefixes"], fz["exact"], fz["scope"], classify) for n in names}
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def judge_solution(plan: dict, solution_p: pathlib.Path, solution: str, keep: str | None = None) -> dict:
|
|
567
|
+
files = dict(plan["files"])
|
|
568
|
+
files["Solution"] = solution_p
|
|
569
|
+
theorems, toolchain = plan["theorems"], plan["toolchain"]
|
|
570
|
+
work = make_workdir(keep)
|
|
571
|
+
rows: list[dict] = []
|
|
572
|
+
logs: list[str] = []
|
|
573
|
+
try:
|
|
574
|
+
cfgs = write_project(work, toolchain, plan["prefix"], files, theorems, plan["axioms"], plan["project"])
|
|
575
|
+
wrapper = write_wrapper(work, plan["project"]["binds"]) if plan["project"] and not plan["no_sandbox"] \
|
|
576
|
+
else None
|
|
577
|
+
stop = None
|
|
578
|
+
for i, (name, cfg) in enumerate(zip(theorems, cfgs, strict=False), 1):
|
|
579
|
+
if stop is not None:
|
|
580
|
+
rows.append({"name": name, "verdict": stop, "detail": "not judged: the build failed above",
|
|
581
|
+
"kernels": [], "seconds": 0.0})
|
|
582
|
+
continue
|
|
583
|
+
print(f"judging {name} ({i}/{len(theorems)}) ...", file=sys.stderr)
|
|
584
|
+
rc, out, secs = judge(plan["lake"], work, cfg, toolchain, plan["timeout"], plan["no_sandbox"], wrapper)
|
|
585
|
+
(work / "cfg" / f"{i}.log").write_text(out, encoding="utf-8")
|
|
586
|
+
logs.append(f"== {name}: lake comparator (exit {rc})\n" + redact(out, work))
|
|
587
|
+
row = classify(rc, out, has_module_header(solution))
|
|
588
|
+
row["detail"] = redact(row["detail"], work)
|
|
589
|
+
rows.append({"name": name, **row, "seconds": round(secs, 1)})
|
|
590
|
+
if row["verdict"] == "build_error" or row["detail"].startswith("the Challenge (or Defs) does not build"):
|
|
591
|
+
stop = row["verdict"]
|
|
592
|
+
judged = [r for r in rows if r["verdict"] == "accepted"]
|
|
593
|
+
if plan["forbid"] and judged:
|
|
594
|
+
print(f"checking forbidden constants ({len(judged)} theorem(s)) ...", file=sys.stderr)
|
|
595
|
+
try:
|
|
596
|
+
hits = forbidden(plan, work, solution, [r["name"] for r in judged])
|
|
597
|
+
except fb.ExportError as e:
|
|
598
|
+
for r in judged:
|
|
599
|
+
r.update(verdict="tool_error", detail=redact(f"the forbidden-constant check failed: {e}", work),
|
|
600
|
+
kernels=[])
|
|
601
|
+
logs.append(f"== forbidden-constant check failed: {redact(str(e), work)}")
|
|
602
|
+
else:
|
|
603
|
+
for r in judged:
|
|
604
|
+
h = hits[r["name"]]
|
|
605
|
+
logs.append(f"== {r['name']}: forbidden constants reached: "
|
|
606
|
+
+ (", ".join(x["constant"] for x in h) or "none"))
|
|
607
|
+
if h:
|
|
608
|
+
via = f" (through {' -> '.join(h[0]['via'])})" if h[0]["via"] else ""
|
|
609
|
+
more = f" and {len(h) - 1} more" if len(h) > 1 else ""
|
|
610
|
+
r.update(verdict="forbidden_constant", constant=h[0]["constant"],
|
|
611
|
+
constants=[x["constant"] for x in h],
|
|
612
|
+
detail=f"uses the forbidden constant {h[0]['constant']}{via}{more}")
|
|
613
|
+
finally:
|
|
614
|
+
if not keep:
|
|
615
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
616
|
+
accepted = sum(r["verdict"] == "accepted" for r in rows)
|
|
617
|
+
res = {"schema": SCHEMA, "ok": accepted == len(rows), "trust": plan["trust"], "toolchain": toolchain,
|
|
618
|
+
"mechanism": "toolchain", "challenge_sha256": sha256(plan["challenge_p"]),
|
|
619
|
+
"solution_sha256": sha256(solution_p), "permitted_axioms": plan["axioms"], "theorems": rows,
|
|
620
|
+
"summary": {"accepted": accepted, "total": len(rows)}, "kept": str(work) if keep else None}
|
|
621
|
+
if plan["project"]:
|
|
622
|
+
res["mathlib"] = True
|
|
623
|
+
if plan["forbid"]:
|
|
624
|
+
res["forbid"] = plan["forbid"]
|
|
625
|
+
res["_logs"] = logs
|
|
626
|
+
return res
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def check(args) -> dict:
|
|
630
|
+
plan = prepare(args)
|
|
631
|
+
solution_p, solution = read_solution(plan, args.solution)
|
|
632
|
+
if args.no_sandbox:
|
|
633
|
+
print(NO_SANDBOX_WARN.format("runs"), file=sys.stderr)
|
|
634
|
+
res = judge_solution(plan, solution_p, solution, args.keep)
|
|
635
|
+
if args.no_sandbox:
|
|
636
|
+
print(NO_SANDBOX_WARN.format("ran"), file=sys.stderr)
|
|
637
|
+
res.pop("_logs")
|
|
638
|
+
return res
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
642
|
+
# batch: a directory of Solutions, one CSV row each
|
|
643
|
+
|
|
644
|
+
def batch(args) -> dict:
|
|
645
|
+
if args.no_sandbox:
|
|
646
|
+
raise Refusal("batch grades other people's work: --no-sandbox is refused (use `check --no-sandbox` "
|
|
647
|
+
"on your own Solution)")
|
|
648
|
+
src = pathlib.Path(args.solutions)
|
|
649
|
+
if not src.is_dir():
|
|
650
|
+
raise Refusal(f"--solutions {args.solutions}: not a directory")
|
|
651
|
+
sols = sorted(p for p in src.iterdir() if p.suffix == ".lean" and p.is_file())
|
|
652
|
+
if not sols:
|
|
653
|
+
raise Refusal(f"--solutions {args.solutions}: no .lean files in it")
|
|
654
|
+
out_csv, logs_dir = pathlib.Path(args.csv), pathlib.Path(args.logs)
|
|
655
|
+
if out_csv.exists():
|
|
656
|
+
raise Refusal(f"--csv {args.csv}: already exists (choose a new path; nothing is overwritten)")
|
|
657
|
+
if logs_dir.exists() and (not logs_dir.is_dir() or any(logs_dir.iterdir())):
|
|
658
|
+
raise Refusal(f"--logs {args.logs}: must not exist or be an empty directory")
|
|
659
|
+
plan = prepare(args)
|
|
660
|
+
logs_dir.mkdir(parents=True, exist_ok=True)
|
|
661
|
+
names = plan["theorems"]
|
|
662
|
+
header = ["file", "sha256", "result", "accepted", "total"] + names + ["detail"]
|
|
663
|
+
files_out = []
|
|
664
|
+
with open(out_csv, "x", newline="", encoding="utf-8") as fh:
|
|
665
|
+
w = csv.writer(fh)
|
|
666
|
+
w.writerow(header)
|
|
667
|
+
for n, sp in enumerate(sols, 1):
|
|
668
|
+
print(f"[{n}/{len(sols)}] {sp.name}", file=sys.stderr)
|
|
669
|
+
log = [f"lean-exercise batch: {sp.name}"]
|
|
670
|
+
try:
|
|
671
|
+
solution_p, solution = read_solution(plan, str(sp))
|
|
672
|
+
except Refusal as e:
|
|
673
|
+
row = {"file": sp.name, "sha256": sha256(sp), "result": "refused", "accepted": 0,
|
|
674
|
+
"total": len(names), "detail": str(e).replace(str(sp), sp.name)}
|
|
675
|
+
verdicts = ["refused"] * len(names)
|
|
676
|
+
log.append(f"REFUSED: {row['detail']}")
|
|
677
|
+
else:
|
|
678
|
+
res = judge_solution(plan, solution_p, solution)
|
|
679
|
+
verdicts = [r["verdict"] for r in res["theorems"]]
|
|
680
|
+
bad = [f"{r['name']}: {r['verdict']}: {r['detail']}" for r in res["theorems"]
|
|
681
|
+
if r["verdict"] != "accepted"]
|
|
682
|
+
row = {"file": sp.name, "sha256": res["solution_sha256"], "result": "pass" if res["ok"] else "fail",
|
|
683
|
+
"accepted": res["summary"]["accepted"], "total": res["summary"]["total"],
|
|
684
|
+
"detail": "; ".join(bad)}
|
|
685
|
+
log += [render(res)] + res["_logs"]
|
|
686
|
+
w.writerow([row["file"], row["sha256"], row["result"], row["accepted"], row["total"]] + verdicts
|
|
687
|
+
+ [row["detail"]])
|
|
688
|
+
fh.flush()
|
|
689
|
+
(logs_dir / f"{sp.stem}.log").write_text("\n".join(log) + "\n", encoding="utf-8")
|
|
690
|
+
files_out.append({**row, "verdicts": dict(zip(names, verdicts, strict=False))})
|
|
691
|
+
passed = sum(f["result"] == "pass" for f in files_out)
|
|
692
|
+
return {"schema": BATCH_SCHEMA, "ok": passed == len(files_out), "trust": plan["trust"],
|
|
693
|
+
"toolchain": plan["toolchain"], "theorems": names, "csv": str(out_csv), "logs": str(logs_dir),
|
|
694
|
+
"files": files_out, "summary": {"passed": passed, "total": len(files_out)}}
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def render_batch(res: dict) -> str:
|
|
698
|
+
s = res["summary"]
|
|
699
|
+
head = f"{'PASS' if res['ok'] else 'FAIL'}: {s['passed']}/{s['total']} Solution(s) pass ({res['trust']}, {res['toolchain']})"
|
|
700
|
+
out = [head] + [f"{f['result']:<8} {f['file']}: {f['accepted']}/{f['total']}"
|
|
701
|
+
+ (f" -- {f['detail']}" if f["detail"] else "") for f in res["files"]]
|
|
702
|
+
out += [f"csv: {res['csv']}", f"logs: {res['logs']}", head]
|
|
703
|
+
return "\n".join(out)
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def render(res: dict) -> str:
|
|
707
|
+
s = res["summary"]
|
|
708
|
+
head = (f"{'PASS' if res['ok'] else 'FAIL'}: {s['accepted']}/{s['total']} theorem(s) accepted "
|
|
709
|
+
f"({res['trust']}, {res['toolchain']})")
|
|
710
|
+
out = [head]
|
|
711
|
+
for r in res["theorems"]:
|
|
712
|
+
extra = f" [{', '.join(r['kernels'])}]" if r["kernels"] else ""
|
|
713
|
+
out.append(f"{r['verdict']:<18} {r['name']}: {r['detail']}{extra} ({r['seconds']}s)")
|
|
714
|
+
if res.get("kept"):
|
|
715
|
+
out.append(f"kept: {res['kept']}")
|
|
716
|
+
if res["trust"] != "sandboxed":
|
|
717
|
+
out.append("self-check only: the Solution ran unsandboxed (--no-sandbox)")
|
|
718
|
+
out.append(head)
|
|
719
|
+
return "\n".join(out)
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
EXAMPLES = """\
|
|
723
|
+
examples:
|
|
724
|
+
lean-exercise check --challenge Challenge.lean --solution Solution.lean
|
|
725
|
+
lean-exercise check --challenge C.lean --solution S.lean --theorems add_zero',two_mul --json
|
|
726
|
+
lean-exercise check --challenge C.lean --solution S.lean --defs Defs.lean --axioms propext
|
|
727
|
+
lean-exercise check --challenge C.lean --solution S.lean --project ~/course-mathlib \\
|
|
728
|
+
--forbid MeasurableSpace.DynkinSystem. --forbid-exact MeasurableSpace.induction_on_inter
|
|
729
|
+
lean-exercise batch --challenge C.lean --solutions submissions/ --csv grades.csv --logs logs/ \\
|
|
730
|
+
--project ~/course-mathlib
|
|
731
|
+
|
|
732
|
+
exit codes: 0 every theorem accepted (batch: every Solution), 1 a theorem rejected (or the judge failed),
|
|
733
|
+
2 usage or host refusal.
|
|
734
|
+
docs: https://lean-pkg.github.io/lean-pkg/exercise.html"""
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
class _Parser(argparse.ArgumentParser):
|
|
738
|
+
json_requested = False
|
|
739
|
+
|
|
740
|
+
def error(self, message):
|
|
741
|
+
if _Parser.json_requested:
|
|
742
|
+
print(json.dumps({"ok": False, "error": message, "usage": True}))
|
|
743
|
+
super().error(message)
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _common(c) -> None:
|
|
747
|
+
c.add_argument("--challenge", required=True, metavar="FILE", help="the Challenge .lean (theorems := by sorry)")
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def _options(c) -> None:
|
|
751
|
+
c.add_argument("--theorems", metavar="a,b", help="judge only these (fully qualified) Challenge theorems")
|
|
752
|
+
c.add_argument("--axioms", metavar="a,b",
|
|
753
|
+
help="permitted axioms, a subset of propext,Quot.sound,Classical.choice (default: all three)")
|
|
754
|
+
c.add_argument("--defs", metavar="FILE", help="shared definitions, module Defs, imported by both files")
|
|
755
|
+
c.add_argument("--project", metavar="DIR",
|
|
756
|
+
help="a Lake project whose lean-toolchain and lake-manifest.json pin Mathlib, built already "
|
|
757
|
+
"(`lake exe cache get`): allows `import Mathlib...`; its packages are bound read-only "
|
|
758
|
+
"into the sandbox, and nothing is downloaded")
|
|
759
|
+
c.add_argument("--forbid", action="append", metavar="PREFIX",
|
|
760
|
+
help="reject a theorem whose proof depends on a constant whose name starts with PREFIX "
|
|
761
|
+
"(repeatable; computed on the compiled environment, through the Solution's helpers)")
|
|
762
|
+
c.add_argument("--forbid-exact", action="append", metavar="NAME",
|
|
763
|
+
help="as --forbid, for exactly this constant (repeatable)")
|
|
764
|
+
c.add_argument("--forbid-scope", choices=FORBID_SCOPES, default="solution",
|
|
765
|
+
help="solution (default): follow the Solution's own declarations, report library constants "
|
|
766
|
+
"they use; all: follow library constants too")
|
|
767
|
+
c.add_argument("--toolchain", metavar="T",
|
|
768
|
+
help=f"Lean toolchain (default: the --project's, else the newest installed, {FLOOR} or later)")
|
|
769
|
+
c.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, metavar="S",
|
|
770
|
+
help=f"seconds per theorem (default {DEFAULT_TIMEOUT})")
|
|
771
|
+
c.add_argument("--mathlib", action="store_true", help=argparse.SUPPRESS) # refused: --project DIR
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def parser() -> argparse.ArgumentParser:
|
|
775
|
+
fmt = argparse.RawDescriptionHelpFormatter
|
|
776
|
+
ap = _Parser(prog="lean-exercise", formatter_class=fmt,
|
|
777
|
+
description="Judge a Lean exercise Solution against its Challenge with `lake comparator`.",
|
|
778
|
+
epilog=EXAMPLES)
|
|
779
|
+
sub = ap.add_subparsers(dest="verb", metavar="{check,batch}", required=True)
|
|
780
|
+
c = sub.add_parser("check", formatter_class=fmt, epilog=EXAMPLES,
|
|
781
|
+
help="judge each sorry'd theorem of the Challenge against the Solution",
|
|
782
|
+
description="Judge each sorry'd theorem of the Challenge against the Solution, one "
|
|
783
|
+
"`lake comparator` run per theorem, in its bwrap sandbox. Registry-free; "
|
|
784
|
+
"writes only a temporary directory. Mathlib only with --project DIR.")
|
|
785
|
+
_common(c)
|
|
786
|
+
c.add_argument("--solution", required=True, metavar="FILE", help="the Solution .lean to judge")
|
|
787
|
+
_options(c)
|
|
788
|
+
c.add_argument("--keep", metavar="DIR", help="build in DIR (absent or empty) and keep it")
|
|
789
|
+
c.add_argument("--no-sandbox", action="store_true",
|
|
790
|
+
help="run without the bwrap sandbox: the Solution runs as you; a self-check of your OWN "
|
|
791
|
+
"code only, never a grade (trust: self-check-only)")
|
|
792
|
+
c.add_argument("--json", dest="json_out", action="store_true", help=f"JSON on stdout (schema {SCHEMA})")
|
|
793
|
+
b = sub.add_parser("batch", formatter_class=fmt, epilog=EXAMPLES,
|
|
794
|
+
help="judge every .lean file of a directory: one CSV row and one log per file",
|
|
795
|
+
description="Judge every Solution (*.lean, not recursive) in a directory as `check` "
|
|
796
|
+
"would, sandboxed (--no-sandbox is refused), each in its own fresh "
|
|
797
|
+
"project. Writes one CSV row per file (identified by its file name only) "
|
|
798
|
+
"and one log per file. Registry-free.")
|
|
799
|
+
_common(b)
|
|
800
|
+
b.add_argument("--solutions", required=True, metavar="DIR", help="the directory of Solution .lean files")
|
|
801
|
+
b.add_argument("--csv", required=True, metavar="FILE", help="the CSV to write (must not exist)")
|
|
802
|
+
b.add_argument("--logs", required=True, metavar="DIR", help="per-file logs <stem>.log (absent or empty)")
|
|
803
|
+
_options(b)
|
|
804
|
+
b.add_argument("--no-sandbox", action="store_true", help=argparse.SUPPRESS) # refused in batch
|
|
805
|
+
b.add_argument("--json", dest="json_out", action="store_true", help=f"JSON on stdout (schema {BATCH_SCHEMA})")
|
|
806
|
+
return ap
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def main(argv: list[str] | None = None) -> int:
|
|
810
|
+
raw = list(sys.argv[1:] if argv is None else argv)
|
|
811
|
+
_Parser.json_requested = "--json" in raw
|
|
812
|
+
args = parser().parse_args(raw)
|
|
813
|
+
try:
|
|
814
|
+
res = batch(args) if args.verb == "batch" else check(args)
|
|
815
|
+
except Refusal as e:
|
|
816
|
+
if args.json_out:
|
|
817
|
+
print(json.dumps({"ok": False, "error": str(e), "usage": True}, indent=2))
|
|
818
|
+
print(f"lean-exercise: {e}", file=sys.stderr)
|
|
819
|
+
return 2
|
|
820
|
+
if args.json_out:
|
|
821
|
+
print(json.dumps(res, indent=2))
|
|
822
|
+
else:
|
|
823
|
+
print(render_batch(res) if args.verb == "batch" else render(res))
|
|
824
|
+
return 0 if res["ok"] else 1
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
if __name__ == "__main__":
|
|
828
|
+
sys.exit(main())
|