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
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
# dup_constants -- constants that more than one module of an environment declares, judged fail-closed
|
|
2
|
+
"""Find every constant name that occurs in the constant table of MORE THAN ONE module of a compiled Lean
|
|
3
|
+
environment, and refuse any such duplicate that is not provably one and the same constant.
|
|
4
|
+
|
|
5
|
+
Why: `importModules` merges the modules' tables and tolerates a duplicate name when the two copies
|
|
6
|
+
"subsume" each other (Lean.Environment `subsumesInfo`: same type, universe parameters and, for a
|
|
7
|
+
theorem, the same `all` list). The proof terms are NOT compared, so two modules may carry two different
|
|
8
|
+
proofs of one theorem name, and which copy `env.find?` returns depends on the import order. Lean itself
|
|
9
|
+
does this routinely for realized auxiliaries (`f.congr_simp`, `f.eq_1`, `match_n.congr_eq_n`,
|
|
10
|
+
`_unary.induct_unfolding`, ...) that every module using them re-creates. A review that reads one copy may
|
|
11
|
+
not be reading the one the kernel checked against.
|
|
12
|
+
|
|
13
|
+
How: `scripts/DupConstants.lean` imports the given modules exactly as `import` does (data only:
|
|
14
|
+
`loadExts := false`, no initializer runs), walks `env.header.moduleData` (the tables `importModules`
|
|
15
|
+
merged) and prints, per duplicate name, every owner's `ConstantInfo` compared field by field with
|
|
16
|
+
`Expr.equal` (binder names and annotations included) against the `env.find?` winner, the module whose
|
|
17
|
+
copy IS the winner (pointer identity), and the module `env.getModuleIdxFor?` records (the first owner;
|
|
18
|
+
not necessarily the winner's). The toolchain's `lean --run` runs it with a LEAN_PATH built from the
|
|
19
|
+
project's lake-manifest.json (git packages under packagesDir, with their subDir; path packages at their
|
|
20
|
+
dir; nothing escaping the project or through a symlink; `lake env` is not used: a lakefile.lean is
|
|
21
|
+
code), inside the same bwrap
|
|
22
|
+
sandbox lean-exercise uses unless --no-sandbox.
|
|
23
|
+
|
|
24
|
+
Verdict per duplicate (fail closed):
|
|
25
|
+
- accepted: every owner's copy equals the winner exactly (kind, type, value/proof, levelParams, `all`,
|
|
26
|
+
safety, reducibility hints, inductive/constructor/recursor shape), the winner's module and the recorded
|
|
27
|
+
owner are both among the owners, every owner's .olean is attributed, and there are exactly two owners
|
|
28
|
+
or the owner set is pinned with --allow-owners NAME=M1,M2,...;
|
|
29
|
+
- refused otherwise: `unequal` (with the differing fields per owner), `extra-owner` (a third owner, or an
|
|
30
|
+
owner set other than the pinned one), `unknown-owner` (no winner, the winner is no owner's copy, the
|
|
31
|
+
recorded owner is not an owner, or an .olean that cannot be attributed).
|
|
32
|
+
An incomplete probe (no final `done` line), a failed import (Lean's own "environment already contains")
|
|
33
|
+
or a missing .olean refuses the whole run. Nothing is whitelisted by name (generated and private names
|
|
34
|
+
are judged like any other), and counts are never added across owners or across scopes.
|
|
35
|
+
|
|
36
|
+
Scope: Lean's own library has duplicates of this kind (about a hundred in `Init`/`Std`/`Lean`, a few with
|
|
37
|
+
different proofs). `--scope project` (the default) judges the duplicates with at least one owner built by
|
|
38
|
+
the project itself; `packages` adds those with an owner in a Lake dependency; `all` judges the toolchain's
|
|
39
|
+
too. Duplicates outside the scope are still listed, with their verdicts, under `out_of_scope`; they do not
|
|
40
|
+
change the exit code.
|
|
41
|
+
|
|
42
|
+
Python API: `probe(project, modules, ...) -> (records, done)`, `judge(records, done, roots, scope=,
|
|
43
|
+
allow=) -> report`, `duplicate_constants(project, modules, ...) -> report`.
|
|
44
|
+
Command line: `python3 -m lean_pkg.dup_constants --repo DIR MOD [MOD ...] [--scope S]
|
|
45
|
+
[--allow-owners NAME=M1,M2] [--no-sandbox] [--json]`. Exit 0 every in-scope duplicate accepted, 1 any
|
|
46
|
+
refused (or the probe failed), 2 usage. Documented in docs/duplicate-constants.md.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
import argparse
|
|
52
|
+
import dataclasses
|
|
53
|
+
import json
|
|
54
|
+
import os
|
|
55
|
+
import pathlib
|
|
56
|
+
import subprocess
|
|
57
|
+
import sys
|
|
58
|
+
|
|
59
|
+
from . import build_scope
|
|
60
|
+
from . import comparator_receipt as cr
|
|
61
|
+
from . import exercise_forbid as fb
|
|
62
|
+
|
|
63
|
+
SCHEMA = "lean-pkg-dup-constants/1"
|
|
64
|
+
SCRIPT = pathlib.Path(__file__).with_name("scripts") / "DupConstants.lean"
|
|
65
|
+
PKG_LIB = pathlib.Path(".lake") / "build" / "lib" / "lean"
|
|
66
|
+
SCOPES = ("project", "packages", "all")
|
|
67
|
+
DEFAULT_TIMEOUT = 600.0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ProbeError(Exception):
|
|
71
|
+
"""The environment could not be read: the run is refused, never passed."""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclasses.dataclass
|
|
75
|
+
class Roots:
|
|
76
|
+
"""Where each origin's .olean files live, to attribute an owner module."""
|
|
77
|
+
project: pathlib.Path # <project>/.lake/build/lib/lean
|
|
78
|
+
packages: dict[str, pathlib.Path] # name -> <packagesDir>/<name>/.lake/build/lib/lean
|
|
79
|
+
toolchain: pathlib.Path | None # <toolchain prefix>/lib/lean
|
|
80
|
+
|
|
81
|
+
def origin(self, olean: str | None) -> str:
|
|
82
|
+
if not olean:
|
|
83
|
+
return "unknown"
|
|
84
|
+
p = pathlib.Path(olean).resolve()
|
|
85
|
+
if p.is_relative_to(self.project.resolve()):
|
|
86
|
+
return "project"
|
|
87
|
+
for name, d in self.packages.items():
|
|
88
|
+
if p.is_relative_to(d.resolve()):
|
|
89
|
+
return f"package:{name}"
|
|
90
|
+
if self.toolchain is not None and p.is_relative_to(self.toolchain.resolve()):
|
|
91
|
+
return "toolchain"
|
|
92
|
+
return "unknown"
|
|
93
|
+
|
|
94
|
+
def lean_path(self) -> list[pathlib.Path]:
|
|
95
|
+
return [self.project] + list(self.packages.values())
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
99
|
+
# The project: toolchain and LEAN_PATH, from lean-toolchain and lake-manifest.json (no lakefile is run)
|
|
100
|
+
|
|
101
|
+
def toolchain_prefix(toolchain: str) -> pathlib.Path:
|
|
102
|
+
tc = toolchain if ":" in toolchain else f"leanprover/lean4:{toolchain}"
|
|
103
|
+
return cr.elan_home() / "toolchains" / tc.replace("/", "--").replace(":", "---")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _inside(base: pathlib.Path, rel: str, what: str) -> pathlib.Path:
|
|
107
|
+
"""base/rel, refused when rel is absolute or leaves base (build_scope.norm_dir, the same lexical rule the
|
|
108
|
+
gate applies to lake-manifest.json path packages), or when any component on the way is a symlink or
|
|
109
|
+
the result resolves outside base."""
|
|
110
|
+
norm = build_scope.norm_dir(rel)
|
|
111
|
+
if norm is None:
|
|
112
|
+
raise ProbeError(f"{what}: {rel!r} is absolute or leaves {base}; refused")
|
|
113
|
+
d = base
|
|
114
|
+
for part in [x for x in norm.split("/") if x]:
|
|
115
|
+
d = d / part
|
|
116
|
+
if d.is_symlink():
|
|
117
|
+
raise ProbeError(f"{what}: {rel!r} goes through the symlink {d}; refused")
|
|
118
|
+
if not d.resolve().is_relative_to(base.resolve()):
|
|
119
|
+
raise ProbeError(f"{what}: {rel!r} resolves outside {base}; refused")
|
|
120
|
+
return d
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def manifest_packages(project: pathlib.Path) -> dict[str, pathlib.Path]:
|
|
124
|
+
"""{name: its .lake/build/lib/lean} for every package of the project's lake-manifest.json, read as data
|
|
125
|
+
(no lakefile is run): a `git` package at <packagesDir>/<name>[/<subDir>], a `path` package at its
|
|
126
|
+
`dir`, relative to the manifest's directory. The name is Lake's unescaped one (`«dep-x»` is checked out
|
|
127
|
+
as `dep-x`, build_scope.lake_dir_name); two entries that decode to the same name, a name that does not
|
|
128
|
+
decode, and a dir or subDir that is absolute, leaves its base or goes through a symlink are refused, as
|
|
129
|
+
is a package that is not checked out."""
|
|
130
|
+
man = project / "lake-manifest.json"
|
|
131
|
+
if not man.is_file():
|
|
132
|
+
return {}
|
|
133
|
+
try:
|
|
134
|
+
m = json.loads(man.read_text(encoding="utf-8"))
|
|
135
|
+
pkgs = m["packages"]
|
|
136
|
+
if not isinstance(pkgs, list):
|
|
137
|
+
raise TypeError("packages is not a list")
|
|
138
|
+
except (ValueError, KeyError, TypeError, OSError) as e:
|
|
139
|
+
raise ProbeError(f"{man}: not a Lake manifest ({e})") from None
|
|
140
|
+
pdir = _inside(project, m.get("packagesDir") or ".lake/packages", "lake-manifest.json packagesDir")
|
|
141
|
+
out: dict[str, pathlib.Path] = {}
|
|
142
|
+
for x in pkgs:
|
|
143
|
+
if not isinstance(x, dict) or not isinstance(x.get("name"), str) or not x["name"]:
|
|
144
|
+
raise ProbeError(f"{man}: a package entry without a name")
|
|
145
|
+
name, kind = build_scope.lake_dir_name(x["name"]), x.get("type")
|
|
146
|
+
if name is None or "/" in name or "\\" in name or name in (".", ".."):
|
|
147
|
+
raise ProbeError(f"{man}: package name {x['name']!r} is not a Lake package name")
|
|
148
|
+
if name in out:
|
|
149
|
+
raise ProbeError(f"{man}: package {name} is listed twice")
|
|
150
|
+
if kind == "path":
|
|
151
|
+
if not isinstance(x.get("dir"), str):
|
|
152
|
+
raise ProbeError(f"{man}: path package {name} has no dir")
|
|
153
|
+
d = _inside(project, x["dir"], f"path package {name} dir")
|
|
154
|
+
elif kind == "git":
|
|
155
|
+
d = _inside(pdir, name, f"git package {name}")
|
|
156
|
+
if x.get("subDir") is not None:
|
|
157
|
+
if not isinstance(x["subDir"], str):
|
|
158
|
+
raise ProbeError(f"{man}: git package {name} subDir is not a string")
|
|
159
|
+
d = _inside(d, x["subDir"], f"git package {name} subDir")
|
|
160
|
+
else:
|
|
161
|
+
raise ProbeError(f"{man}: package {name} has type {kind!r} (only git and path are read)")
|
|
162
|
+
if not d.is_dir():
|
|
163
|
+
raise ProbeError(f"dependency {name} is not checked out ({d}); build the project first")
|
|
164
|
+
out[name] = d / PKG_LIB
|
|
165
|
+
return out
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def project_roots(project: pathlib.Path, toolchain: str | None = None) -> tuple[Roots, pathlib.Path]:
|
|
169
|
+
"""(Roots, toolchain prefix) of a built Lake project."""
|
|
170
|
+
project = project.resolve()
|
|
171
|
+
if not project.is_dir():
|
|
172
|
+
raise ProbeError(f"{project}: not a directory")
|
|
173
|
+
if toolchain is None:
|
|
174
|
+
f = project / "lean-toolchain"
|
|
175
|
+
if not f.is_file():
|
|
176
|
+
raise ProbeError(f"{project}: no lean-toolchain (pass --toolchain)")
|
|
177
|
+
toolchain = f.read_text(encoding="utf-8").strip()
|
|
178
|
+
prefix = toolchain_prefix(toolchain)
|
|
179
|
+
if not os.access(prefix / "bin" / "lean", os.X_OK):
|
|
180
|
+
raise ProbeError(f"toolchain {toolchain} is not installed (`elan toolchain install {toolchain}`)")
|
|
181
|
+
packages = manifest_packages(project)
|
|
182
|
+
return Roots(project / PKG_LIB, packages, prefix / "lib" / "lean"), prefix
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
186
|
+
# The probe
|
|
187
|
+
|
|
188
|
+
def parse_probe(text: str) -> tuple[list[dict], dict | None]:
|
|
189
|
+
"""(duplicate records, the final `done` record or None) of the Lean script's output."""
|
|
190
|
+
records, done = [], None
|
|
191
|
+
for n, line in enumerate(text.splitlines(), 1):
|
|
192
|
+
if not line.strip():
|
|
193
|
+
continue
|
|
194
|
+
try:
|
|
195
|
+
obj = json.loads(line)
|
|
196
|
+
except ValueError:
|
|
197
|
+
raise ProbeError(f"probe output line {n} is not JSON: {line[:200]}") from None
|
|
198
|
+
if not isinstance(obj, dict):
|
|
199
|
+
raise ProbeError(f"probe output line {n} is not an object")
|
|
200
|
+
if done is not None:
|
|
201
|
+
raise ProbeError(f"probe output line {n} follows the final line")
|
|
202
|
+
if obj.get("done") is True:
|
|
203
|
+
done = obj
|
|
204
|
+
elif isinstance(obj.get("name"), str) and isinstance(obj.get("owners"), list):
|
|
205
|
+
records.append(obj)
|
|
206
|
+
else:
|
|
207
|
+
raise ProbeError(f"probe output line {n}: unknown record {sorted(obj)[:4]}")
|
|
208
|
+
return records, done
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def probe(project: pathlib.Path, modules: list[str], toolchain: str | None = None, sandboxed: bool = True,
|
|
212
|
+
timeout: float = DEFAULT_TIMEOUT) -> tuple[list[dict], dict | None, Roots]:
|
|
213
|
+
if not modules:
|
|
214
|
+
raise ProbeError("no module given")
|
|
215
|
+
for m in modules:
|
|
216
|
+
if not m or m.startswith("-") or any(c.isspace() for c in m):
|
|
217
|
+
raise ProbeError(f"not a module name: {m!r}")
|
|
218
|
+
roots, prefix = project_roots(project, toolchain)
|
|
219
|
+
for m in modules:
|
|
220
|
+
rel = pathlib.Path(*m.split(".")).with_suffix(".olean")
|
|
221
|
+
if not any((d / rel).is_file() for d in roots.lean_path()):
|
|
222
|
+
raise ProbeError(f"module {m} is not built (no {rel} on the project's LEAN_PATH): "
|
|
223
|
+
f"ownership cannot be determined; run `lake build` first")
|
|
224
|
+
env = {"PATH": f"{prefix / 'bin'}:/usr/bin:/bin", "LEAN_PATH": os.pathsep.join(map(str, roots.lean_path())),
|
|
225
|
+
"LEAN_ABORT_ON_PANIC": "1"}
|
|
226
|
+
cmd = [str(prefix / "bin" / "lean"), "--run", str(SCRIPT)] + modules
|
|
227
|
+
cwd = roots.project.parents[3]
|
|
228
|
+
if sandboxed:
|
|
229
|
+
readable = [prefix, cwd, SCRIPT.parent] + [d for d in roots.packages.values() if d.is_dir()]
|
|
230
|
+
cmd = fb.bwrap_args(readable, env, cwd) + cmd
|
|
231
|
+
run_env: dict[str, str] = {}
|
|
232
|
+
else:
|
|
233
|
+
run_env = {**os.environ, **env}
|
|
234
|
+
try:
|
|
235
|
+
p = subprocess.run(cmd, cwd=cwd, env=run_env, stdin=subprocess.DEVNULL, capture_output=True,
|
|
236
|
+
timeout=timeout, start_new_session=True)
|
|
237
|
+
except subprocess.TimeoutExpired:
|
|
238
|
+
raise ProbeError("the probe did not finish in time (--timeout)") from None
|
|
239
|
+
except OSError as e:
|
|
240
|
+
raise ProbeError(f"cannot run the probe: {e}") from None
|
|
241
|
+
out = p.stdout.decode("utf-8", "replace")
|
|
242
|
+
if p.returncode != 0:
|
|
243
|
+
err = p.stderr.decode("utf-8", "replace").strip() or out.strip()
|
|
244
|
+
tail = err.splitlines()[-1:] or [f"exit {p.returncode}"]
|
|
245
|
+
if "environment already contains" in err:
|
|
246
|
+
raise ProbeError(f"Lean refused the import itself (an unequal duplicate it cannot merge): {tail[0][:400]}")
|
|
247
|
+
raise ProbeError(f"the probe failed: {tail[0][:400]}")
|
|
248
|
+
records, done = parse_probe(out)
|
|
249
|
+
return records, done, roots
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
253
|
+
# The verdict
|
|
254
|
+
|
|
255
|
+
def parse_allow(items: list[str]) -> dict[str, frozenset[str]]:
|
|
256
|
+
allow: dict[str, frozenset[str]] = {}
|
|
257
|
+
for it in items:
|
|
258
|
+
name, sep, mods = it.partition("=")
|
|
259
|
+
owners = frozenset(m.strip() for m in mods.split(",") if m.strip())
|
|
260
|
+
if not sep or not name or len(owners) < 2:
|
|
261
|
+
raise ValueError(f"--allow-owners {it!r}: expected NAME=MOD1,MOD2[,...] (two or more modules)")
|
|
262
|
+
if name in allow:
|
|
263
|
+
raise ValueError(f"--allow-owners: {name} given twice")
|
|
264
|
+
allow[name] = owners
|
|
265
|
+
return allow
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def judge_one(rec: dict, roots: Roots, allow: dict[str, frozenset[str]]) -> dict:
|
|
269
|
+
owners = []
|
|
270
|
+
for o in rec["owners"]:
|
|
271
|
+
diffs = o.get("vsWinner")
|
|
272
|
+
owners.append({"module": o.get("module"), "origin": roots.origin(o.get("olean")),
|
|
273
|
+
"is_winner": bool(o.get("isWinner")), "kind": (o.get("constant") or {}).get("kind"),
|
|
274
|
+
"differences": diffs})
|
|
275
|
+
mods = [o["module"] for o in owners]
|
|
276
|
+
reasons: list[str] = []
|
|
277
|
+
differences: dict[str, list[str]] = {}
|
|
278
|
+
if rec.get("winner") is None:
|
|
279
|
+
reasons.append("unknown-owner: env.find? does not return this name")
|
|
280
|
+
elif rec.get("winnerModule") not in mods:
|
|
281
|
+
reasons.append("unknown-owner: the env.find? winner is none of the owners' copies")
|
|
282
|
+
if rec.get("recordedOwner") not in mods:
|
|
283
|
+
reasons.append(f"unknown-owner: env.getModuleIdxFor? records {rec.get('recordedOwner')!r}, not an owner")
|
|
284
|
+
for o in owners:
|
|
285
|
+
if o["origin"] == "unknown":
|
|
286
|
+
reasons.append(f"unknown-owner: the .olean of {o['module']} is outside the project, its packages "
|
|
287
|
+
f"and the toolchain")
|
|
288
|
+
if not isinstance(o["differences"], list):
|
|
289
|
+
reasons.append(f"unequal: {o['module']}'s copy could not be compared with the winner")
|
|
290
|
+
elif o["differences"]:
|
|
291
|
+
differences[o["module"]] = o["differences"]
|
|
292
|
+
if differences:
|
|
293
|
+
reasons.append("unequal: " + "; ".join(f"{m} differs from the winner in {', '.join(d)}"
|
|
294
|
+
for m, d in differences.items()))
|
|
295
|
+
if len(set(mods)) != len(mods):
|
|
296
|
+
reasons.append("extra-owner: one module lists the name twice")
|
|
297
|
+
pinned = allow.get(rec["name"])
|
|
298
|
+
if pinned is not None:
|
|
299
|
+
if frozenset(mods) != pinned:
|
|
300
|
+
extra, missing = sorted(set(mods) - pinned), sorted(pinned - set(mods))
|
|
301
|
+
reasons.append("extra-owner: owners differ from --allow-owners"
|
|
302
|
+
+ (f"; not pinned: {', '.join(extra)}" if extra else "")
|
|
303
|
+
+ (f"; pinned but absent: {', '.join(missing)}" if missing else ""))
|
|
304
|
+
elif len(mods) > 2:
|
|
305
|
+
reasons.append(f"extra-owner: {len(mods)} owners; more than two need --allow-owners "
|
|
306
|
+
f"{rec['name']}={','.join(mods)}")
|
|
307
|
+
origins = sorted({o["origin"] for o in owners})
|
|
308
|
+
return {"name": rec["name"], "verdict": "refused" if reasons else "accepted", "equal": not differences
|
|
309
|
+
and all(isinstance(o["differences"], list) for o in owners), "owners": owners,
|
|
310
|
+
"winner": rec.get("winnerModule"), "recorded_owner": rec.get("recordedOwner"),
|
|
311
|
+
"origins": origins, "differences": differences, "reasons": reasons}
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def in_scope(entry: dict, scope: str) -> bool:
|
|
315
|
+
if scope == "all":
|
|
316
|
+
return True
|
|
317
|
+
origins = entry["origins"]
|
|
318
|
+
if "unknown" in origins or "project" in origins:
|
|
319
|
+
return True
|
|
320
|
+
return scope == "packages" and any(o.startswith("package:") for o in origins)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def judge(records: list[dict], done: dict | None, roots: Roots, scope: str = "project",
|
|
324
|
+
allow: dict[str, frozenset[str]] | None = None, modules: list[str] | None = None) -> dict:
|
|
325
|
+
allow = allow or {}
|
|
326
|
+
if scope not in SCOPES:
|
|
327
|
+
raise ValueError(f"scope {scope!r}: one of {', '.join(SCOPES)}")
|
|
328
|
+
res: dict = {"schema": SCHEMA, "modules": modules or [], "scope": scope, "ok": False}
|
|
329
|
+
if done is None:
|
|
330
|
+
res.update(verdict="refused", detail="the probe output is incomplete (no final line): nothing is judged",
|
|
331
|
+
duplicates=[], out_of_scope=[], counts={})
|
|
332
|
+
return res
|
|
333
|
+
judged = [judge_one(r, roots, allow) for r in records]
|
|
334
|
+
mine = [e for e in judged if in_scope(e, scope)]
|
|
335
|
+
other = [e for e in judged if not in_scope(e, scope)]
|
|
336
|
+
stale = sorted(set(allow) - {e["name"] for e in judged})
|
|
337
|
+
counts = {"in_scope": {"accepted": sum(e["verdict"] == "accepted" for e in mine),
|
|
338
|
+
"refused": sum(e["verdict"] == "refused" for e in mine)},
|
|
339
|
+
"out_of_scope": {"accepted": sum(e["verdict"] == "accepted" for e in other),
|
|
340
|
+
"refused": sum(e["verdict"] == "refused" for e in other)},
|
|
341
|
+
"environment": {"modules": done.get("modules"), "constants": done.get("constants")}}
|
|
342
|
+
if done.get("duplicates") != len(records):
|
|
343
|
+
detail = (f"the probe reported {done.get('duplicates')} duplicates but printed {len(records)}: "
|
|
344
|
+
f"the output is inconsistent")
|
|
345
|
+
res.update(verdict="refused", detail=detail, duplicates=mine, out_of_scope=other, counts=counts)
|
|
346
|
+
return res
|
|
347
|
+
refused = [e["name"] for e in mine if e["verdict"] == "refused"]
|
|
348
|
+
if stale:
|
|
349
|
+
detail = f"--allow-owners names no duplicate: {', '.join(stale)} (a pin that matches nothing is refused)"
|
|
350
|
+
res.update(verdict="refused", detail=detail)
|
|
351
|
+
elif refused:
|
|
352
|
+
res.update(verdict="refused", detail=f"{len(refused)} in-scope duplicate(s) refused: "
|
|
353
|
+
+ ", ".join(refused[:10]) + (f" (and {len(refused) - 10} more)" if len(refused) > 10 else ""))
|
|
354
|
+
else:
|
|
355
|
+
res.update(ok=True, verdict="accepted",
|
|
356
|
+
detail=f"{len(mine)} in-scope duplicate(s), each exactly equal across its owners"
|
|
357
|
+
if mine else "no in-scope duplicate")
|
|
358
|
+
res.update(duplicates=mine, out_of_scope=other, counts=counts)
|
|
359
|
+
return res
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def duplicate_constants(project, modules: list[str], toolchain: str | None = None, sandboxed: bool = True,
|
|
363
|
+
scope: str = "project", allow: dict[str, frozenset[str]] | None = None,
|
|
364
|
+
timeout: float = DEFAULT_TIMEOUT) -> dict:
|
|
365
|
+
"""The full report for `modules` of the built project `project`; a probe failure is a refusal."""
|
|
366
|
+
try:
|
|
367
|
+
records, done, roots = probe(pathlib.Path(project), modules, toolchain, sandboxed, timeout)
|
|
368
|
+
except ProbeError as e:
|
|
369
|
+
return {"schema": SCHEMA, "modules": modules, "scope": scope, "ok": False, "verdict": "refused",
|
|
370
|
+
"detail": str(e), "duplicates": [], "out_of_scope": [], "counts": {}}
|
|
371
|
+
return judge(records, done, roots, scope, allow, modules)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
# ---------------------------------------------------------------------------------------------------------
|
|
375
|
+
# command line
|
|
376
|
+
|
|
377
|
+
PROGRAM = "python3 -m lean_pkg.dup_constants"
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def parser() -> argparse.ArgumentParser:
|
|
381
|
+
ap = argparse.ArgumentParser(
|
|
382
|
+
prog=PROGRAM, formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
383
|
+
description="Report every constant that more than one module of a built project's environment "
|
|
384
|
+
"declares, with its owners and the env.find? winner, and refuse any duplicate that is "
|
|
385
|
+
"not exactly equal (type, proof/value, universe parameters, `all`, safety, kind).",
|
|
386
|
+
epilog="examples:\n"
|
|
387
|
+
" python3 -m lean_pkg.dup_constants --repo . MyLib\n"
|
|
388
|
+
" python3 -m lean_pkg.dup_constants --repo . MyLib --allow-owners 'f.congr_simp=A,B,C'\n"
|
|
389
|
+
" python3 -m lean_pkg.dup_constants --repo . MyLib --scope all --json\n"
|
|
390
|
+
"exit codes: 0 every in-scope duplicate accepted, 1 any refused or the probe failed, 2 usage.\n"
|
|
391
|
+
"docs: https://lean-pkg.github.io/lean-pkg/duplicate-constants.html")
|
|
392
|
+
ap.add_argument("modules", nargs="+", metavar="MOD", help="the modules to import (e.g. the library root)")
|
|
393
|
+
ap.add_argument("--repo", dest="project", required=True, metavar="DIR",
|
|
394
|
+
help="the package checkout, a built Lake project")
|
|
395
|
+
ap.add_argument("--toolchain", metavar="TC", help="default: the project's lean-toolchain")
|
|
396
|
+
ap.add_argument("--scope", choices=SCOPES, default="project",
|
|
397
|
+
help="which duplicates are judged: those with an owner in the project (default), also in "
|
|
398
|
+
"its Lake packages, or all (the toolchain's included); the rest are only listed")
|
|
399
|
+
ap.add_argument("--allow-owners", action="append", default=[], metavar="NAME=M1,M2",
|
|
400
|
+
help="pin the exact owner set of one name (needed for three or more owners); repeatable")
|
|
401
|
+
ap.add_argument("--no-sandbox", action="store_true", help="read the .olean files without the bwrap sandbox")
|
|
402
|
+
ap.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, metavar="SECONDS")
|
|
403
|
+
ap.add_argument("--json", dest="json_out", action="store_true", help=f"JSON on stdout (schema {SCHEMA})")
|
|
404
|
+
from . import command_tree
|
|
405
|
+
command_tree.apply_program_flag_aliases(ap, PROGRAM)
|
|
406
|
+
return ap
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _line(e: dict) -> str:
|
|
410
|
+
owners = ", ".join(f"{o['module']}{' (winner)' if o['is_winner'] else ''}" for o in e["owners"])
|
|
411
|
+
return f" {e['verdict']}: {e['name']} [{owners}]" + "".join(f"\n {r}" for r in e["reasons"])
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def main(argv: list[str] | None = None) -> int:
|
|
415
|
+
from . import command_tree
|
|
416
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
417
|
+
args = parser().parse_args(argv)
|
|
418
|
+
try:
|
|
419
|
+
return _run(args)
|
|
420
|
+
finally: # the old-spelling note (--project), after the output
|
|
421
|
+
for line in command_tree.program_notes(argv, PROGRAM, args.json_out):
|
|
422
|
+
print(line, file=sys.stderr)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _run(args) -> int:
|
|
426
|
+
try:
|
|
427
|
+
allow = parse_allow(args.allow_owners)
|
|
428
|
+
except ValueError as e:
|
|
429
|
+
print(f"dup_constants: {e}", file=sys.stderr)
|
|
430
|
+
return 2
|
|
431
|
+
res = duplicate_constants(args.project, args.modules, args.toolchain, not args.no_sandbox, args.scope,
|
|
432
|
+
allow, args.timeout)
|
|
433
|
+
if args.json_out:
|
|
434
|
+
print(json.dumps(res, indent=2))
|
|
435
|
+
else:
|
|
436
|
+
print(f"{res['verdict']}: {res['detail']}")
|
|
437
|
+
for e in res["duplicates"]:
|
|
438
|
+
print(_line(e))
|
|
439
|
+
o = res.get("counts", {}).get("out_of_scope")
|
|
440
|
+
if o and (o["accepted"] or o["refused"]):
|
|
441
|
+
print(f"out of scope (--scope {res['scope']}): {o['accepted']} accepted, {o['refused']} refused; "
|
|
442
|
+
f"--json lists them")
|
|
443
|
+
print(f"{res['verdict']}: {res['detail']}")
|
|
444
|
+
return 0 if res["ok"] else 1
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
if __name__ == "__main__":
|
|
448
|
+
sys.exit(main())
|