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,1408 @@
1
+ # lean-pkg-extract ledger / recheck -- the declaration-level extraction ledger (proposal 0009, stage S2)
2
+ """lean-pkg-extract ledger and recheck: a tool-made record that a library ported by hand from private
3
+ modules is faithful, declaration by declaration, to the source at a named commit (proposal 0009, #329).
4
+
5
+ `ledger` reads the source modules at COMMIT and the target modules at TARGET_COMMIT (git objects only,
6
+ never a working tree), splits each into declarations (`lean_scan.decl_spans`), applies the namespace
7
+ and rename maps to the source side (`lean_scan.apply_map`), and compares the normalized texts by SHA-256
8
+ (method `text/1`). Every source declaration is IDENTICAL, DIFFERS, DROPPED (declared with `--drop`) or
9
+ MISSING; every target declaration with no source is NEW. MISSING, an undeclared NEW and a DIFFERS not
10
+ listed in `--allow-differs` are failures. When nothing fails, the ledger (`lean-pkg-extract-ledger/1`) is
11
+ written once to `--ledger PATH`, which must lie outside SRC and outside the target, and must not exist.
12
+
13
+ `recheck` reads a ledger strictly, recomputes it from its own recorded map (at the recorded commits, or
14
+ at `--commit` / `--target-commit`), and fails when the recomputation fails or, at the recorded commits,
15
+ differs from the ledger in any field.
16
+
17
+ `--method types` (method `types/1`, stage S4) adds the elaborated types: `--emit-script DIR` writes two
18
+ Lean programs and `--from-output` reads what they printed (extract_types.py); a text DIFFERS whose
19
+ statement's types are equal no longer fails, and an IDENTICAL text whose types differ does.
20
+
21
+ The ledger is evidence: never rewritten, read by every later release, and read by no gate, page or
22
+ index. It names private source paths and names; keep it out of anything published.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import hashlib
28
+ import json
29
+ import os
30
+ import pathlib
31
+ import posixpath
32
+ import re
33
+
34
+ from . import export_paths as xp
35
+ from . import extract as ex
36
+ from . import lean_scan
37
+
38
+ EXTRACT_LEDGER_SCHEMA = "lean-pkg-extract-ledger/1"
39
+ METHOD_TEXT = "text/1"
40
+ METHOD_TYPES = "types/1"
41
+ METHODS = (METHOD_TEXT, METHOD_TYPES)
42
+ VERDICTS = ("IDENTICAL", "DROPPED", "DIFFERS", "NEW", "MISSING")
43
+ TOTAL_KEYS = VERDICTS + ("weakened",)
44
+ CONTEXT_VERDICTS = ("IDENTICAL", "DIFFERS")
45
+ DECL_KINDS = frozenset(lean_scan.KEYWORDS) | {"example", "mutual"}
46
+ LEDGER_KEYS = ("schema", "method", "ok", "source", "target", "map", "entries", "context", "warnings", "totals")
47
+ SIDE_KEYS = ("commit", "lean_toolchain", "lake_manifest_sha256", "modules")
48
+ MODULE_KEYS = ("path", "module", "blob", "sha256")
49
+ MAP_KEYS = ("modules", "namespaces", "renames", "drops", "new", "allow_differs")
50
+ PAIR_KEYS = ("from", "to")
51
+ REASON_KEYS = ("decl", "reason")
52
+ ENTRY_KEYS = ("kind", "source", "target", "source_module", "target_module", "verdict", "source_raw_sha256",
53
+ "source_sha256", "target_sha256", "whitespace_only", "doc_changed", "reason")
54
+ # method types/1 only (optional keys within /1, proposal 0009 S4): per entry, the SHA-256 of each side's
55
+ # elaborated-type serialization (null when the entry is not compared: one side absent, or an anonymous
56
+ # instance or example) and whether a text DIFFERS was cleared because the types are equal; per ledger, the
57
+ # Lean build and the hashes of the two programs that printed them.
58
+ TYPES_ENTRY_KEYS = ("source_type_sha256", "target_type_sha256", "types_cleared")
59
+ TYPES_KEYS = ("lean", "lean_githash", "source_script_sha256", "target_script_sha256")
60
+ CONTEXT_KEYS = ("source_module", "target_module", "verdict", "source_sha256", "target_sha256", "reason")
61
+ LAKEFILES = ("lakefile.toml", "lakefile.lean")
62
+ CONTEXT_PREFIX = "context@"
63
+ HEX64 = re.compile(r"[0-9a-f]{64}")
64
+ OID = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
65
+ SCHEMA_RE = re.compile(r"lean-pkg-extract-ledger/(\d+)")
66
+ FUTURE_METHOD = re.compile(r"(text|types)/\d+")
67
+ PRIVATE = "PRIVATE: source names and paths; keep this list out of anything published"
68
+
69
+
70
+ def _sha(text: str) -> str:
71
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
72
+
73
+
74
+ def _canon(name: str) -> tuple[str, ...] | None:
75
+ parts = lean_scan.split_name(name)
76
+ return None if parts is None else lean_scan._canon(parts)
77
+
78
+
79
+ # ----------------------------------------------------------------------------------------------------
80
+ # the input: flags (or an @argsfile) and, for recheck, the ledger's recorded map
81
+
82
+ def _split_outside_names(value: str, sep: str) -> tuple[str, str] | None:
83
+ """(head, tail) split at the first `sep` outside a «quoted» name, or None."""
84
+ inside = False
85
+ for i, ch in enumerate(value):
86
+ if ch == "«":
87
+ inside = True
88
+ elif ch == "»":
89
+ inside = False
90
+ elif ch == sep and not inside:
91
+ return value[:i], value[i + 1:]
92
+ return None
93
+
94
+
95
+ def empty_spec() -> dict:
96
+ return {k: [] for k in MAP_KEYS}
97
+
98
+
99
+ def parse_spec(args, refusals: list[str]) -> dict:
100
+ """The map from the flags; every malformed value is a refusal (and left out)."""
101
+ spec = empty_spec()
102
+ for v in args.from_module or []:
103
+ path, sep, mod = v.rpartition(":")
104
+ if not sep or not path or not mod:
105
+ refusals.append(f"--from-module {v!r}: expected SRC/Path.lean:New.Module")
106
+ continue
107
+ spec["modules"].append((path, mod))
108
+ for flag, attr, key in (("--namespace", "namespace", "namespaces"), ("--rename", "rename", "renames")):
109
+ for v in getattr(args, attr) or []:
110
+ pair = _split_outside_names(v, "=")
111
+ if pair is None or not pair[0] or not pair[1]:
112
+ refusals.append(f"{flag} {v!r}: expected OLD=NEW")
113
+ continue
114
+ spec[key].append(pair)
115
+ for flag, attr, key in (("--drop", "drop", "drops"), ("--new", "new", "new"),
116
+ ("--allow-differs", "allow_differs", "allow_differs")):
117
+ for v in getattr(args, attr) or []:
118
+ pair = _split_outside_names(v, ":")
119
+ if pair is None or not pair[0]:
120
+ refusals.append(f"{flag} {v!r}: expected NAME:REASON (a one-line reason is required)")
121
+ continue
122
+ spec[key].append((pair[0], pair[1]))
123
+ return spec
124
+
125
+
126
+ def spec_from_map(m: dict) -> dict:
127
+ return {"modules": [(x["from"], x["to"]) for x in m["modules"]],
128
+ "namespaces": [(x["from"], x["to"]) for x in m["namespaces"]],
129
+ "renames": [(x["from"], x["to"]) for x in m["renames"]],
130
+ "drops": [(x["decl"], x["reason"]) for x in m["drops"]],
131
+ "new": [(x["decl"], x["reason"]) for x in m["new"]],
132
+ "allow_differs": [(x["decl"], x["reason"]) for x in m["allow_differs"]]}
133
+
134
+
135
+ def map_record(spec: dict) -> dict:
136
+ return {"modules": [{"from": a, "to": b} for a, b in sorted(spec["modules"])],
137
+ "namespaces": [{"from": a, "to": b} for a, b in sorted(spec["namespaces"])],
138
+ "renames": [{"from": a, "to": b} for a, b in sorted(spec["renames"])],
139
+ "drops": [{"decl": a, "reason": b} for a, b in sorted(spec["drops"])],
140
+ "new": [{"decl": a, "reason": b} for a, b in sorted(spec["new"])],
141
+ "allow_differs": [{"decl": a, "reason": b} for a, b in sorted(spec["allow_differs"])]}
142
+
143
+
144
+ def check_spec(spec: dict, refusals: list[str]) -> None:
145
+ """Refusals that need no source: reasons, duplicates, module names, the map's own consistency."""
146
+ for flag, key in (("--drop", "drops"), ("--new", "new"), ("--allow-differs", "allow_differs")):
147
+ seen = set()
148
+ for decl, reason in spec[key]:
149
+ if not ex._reason(reason):
150
+ refusals.append(f"{flag} {decl}: the reason must be one non-empty line")
151
+ if decl in seen:
152
+ refusals.append(f"{flag} {decl}: named twice")
153
+ seen.add(decl)
154
+ both = {d for d, _ in spec["drops"]} & {d for d, _ in spec["allow_differs"]}
155
+ for d in sorted(both):
156
+ refusals.append(f"{d}: both dropped (--drop) and allowed to differ (--allow-differs)")
157
+ froms, tos = {}, {}
158
+ for path, mod in spec["modules"]:
159
+ why = xp.bad_rel_path(path)
160
+ if why:
161
+ refusals.append(f"--from-module {path}:{mod}: the source path {why}")
162
+ elif not path.endswith(".lean"):
163
+ refusals.append(f"--from-module {path}:{mod}: the source path is not a .lean file")
164
+ if not lean_scan.is_name(mod) or lean_scan.module_file(mod) is None or \
165
+ (lean_scan.split_name(mod) or [""])[0] == "_root_":
166
+ refusals.append(f"--from-module {path}:{mod}: the target module {mod!r} is not a Lean module name")
167
+ elif lean_scan._canon(lean_scan.split_name(mod))[0] in _reserved():
168
+ refusals.append(f"--from-module {path}:{mod}: the target module's root {mod.split('.')[0]!r} is the "
169
+ f"root namespace of Lean or a Mathlib dependency; choose another")
170
+ if path in froms:
171
+ refusals.append(f"--from-module {path}: the source module is mapped twice")
172
+ if mod in tos:
173
+ refusals.append(f"--from-module {path}:{mod}: the target module {mod} is also the target of {tos[mod]}")
174
+ froms.setdefault(path, mod)
175
+ tos.setdefault(mod, path)
176
+ if not spec["modules"]:
177
+ refusals.append("no --from-module: name at least one SRC/Path.lean:New.Module")
178
+ try:
179
+ lean_scan.apply_map("", spec["namespaces"], spec["renames"])
180
+ except lean_scan.MapError as e:
181
+ refusals.append(f"invalid map: {e}")
182
+
183
+
184
+ def _reserved() -> set[str]:
185
+ from .scaffold import RESERVED_MODULES
186
+ return set(RESERVED_MODULES)
187
+
188
+
189
+ # ----------------------------------------------------------------------------------------------------
190
+ # reading one side at its commit
191
+
192
+ def _lake_root(path: str, tree: dict) -> str:
193
+ """The nearest directory above `path` holding a Lake configuration file ("" for the top)."""
194
+ d = posixpath.dirname(path)
195
+ while d:
196
+ if any(f"{d}/{f}" in tree for f in LAKEFILES):
197
+ return d
198
+ d = posixpath.dirname(d)
199
+ return ""
200
+
201
+
202
+ def _module_name(path: str, root: str) -> str:
203
+ rel = path[len(root) + 1:] if root else path
204
+ return rel[:-len(".lean")].replace("/", ".")
205
+
206
+
207
+ class Tree:
208
+ """One side's files: `tree` maps a path to {"mode", "type", "oid", "size"} as `ex.ls_tree` does,
209
+ `read(oids)` returns {oid: bytes} as `ex.read_blobs` does, and `label` names the side in messages."""
210
+
211
+ def __init__(self, tree: dict, read, label: str):
212
+ self.tree, self.read, self.label = tree, read, label
213
+
214
+
215
+ def git_tree(repo, commit: str) -> Tree:
216
+ """A side read from git objects at commit."""
217
+ return Tree(ex.ls_tree(repo, commit), lambda oids: ex.read_blobs(repo, oids), commit[:12])
218
+
219
+
220
+ def blob_oid(data: bytes, object_format: str = "sha1") -> str:
221
+ """The git blob id of data, as `git hash-object` computes it in a repository of object_format."""
222
+ h = hashlib.sha256() if object_format == "sha256" else hashlib.sha1()
223
+ h.update(b"blob %d\0" % len(data))
224
+ h.update(data)
225
+ return h.hexdigest()
226
+
227
+
228
+ def files_tree(files: dict[str, bytes], label: str, object_format: str = "sha1") -> Tree:
229
+ """A side held in memory (`decls` before anything is committed): every file a regular blob."""
230
+ tree = {p: {"mode": "100644", "type": "blob", "oid": blob_oid(b, object_format), "size": len(b)}
231
+ for p, b in files.items()}
232
+ by_oid = {tree[p]["oid"]: b for p, b in files.items()}
233
+ return Tree(tree, lambda oids: {o: by_oid[o] for o in oids if o in by_oid}, label)
234
+
235
+
236
+ def _pins(t: Tree, root: str, role: str, warnings: list[str]) -> tuple[str | None, str | None, dict]:
237
+ """(lean-toolchain text, lake-manifest.json sha256, {package: rev}) of the Lake package at root."""
238
+ where = f"{root}/" if root else ""
239
+ tree = t.tree
240
+ tc_ent, lm_ent = tree.get(where + "lean-toolchain"), tree.get(where + "lake-manifest.json")
241
+ blobs = t.read([e["oid"] for e in (tc_ent, lm_ent) if e])
242
+ tc = blobs.get(tc_ent["oid"]) if tc_ent else None
243
+ lm = blobs.get(lm_ent["oid"]) if lm_ent else None
244
+ toolchain = tc.decode("utf-8", "replace").strip() if tc is not None else None
245
+ if toolchain is None:
246
+ warnings.append(f"{role}: no {where}lean-toolchain beside the modules; toolchains are not compared")
247
+ revs: dict = {}
248
+ if lm is None:
249
+ warnings.append(f"{role}: no {where}lake-manifest.json beside the modules; dependencies are not compared")
250
+ return toolchain, None, revs
251
+ doc, _err = ex.load_json_strict(lm, "lake-manifest.json")
252
+ for p in (doc.get("packages") if isinstance(doc, dict) else None) or []:
253
+ if isinstance(p, dict) and isinstance(p.get("name"), str):
254
+ revs[p["name"]] = p.get("rev")
255
+ return toolchain, hashlib.sha256(lm).hexdigest(), revs
256
+
257
+
258
+ def _side(t: Tree, paths: list[str], role: str, refusals: list[str], warnings: list[str]):
259
+ """{path: text} of the modules of one side (refusals for missing, non-file, unreadable ones), the
260
+ module records, and the pins."""
261
+ tree = t.tree
262
+ ok_paths = []
263
+ for path in paths:
264
+ ent = tree.get(path)
265
+ if ent is None:
266
+ refusals.append(f"{role} {path}: missing at {t.label}")
267
+ elif ent["mode"] in (ex.SYMLINK, ex.GIT_LINK) or ent["type"] != "blob":
268
+ refusals.append(f"{role} {path}: not a regular file at {t.label}")
269
+ else:
270
+ ok_paths.append(path)
271
+ blobs = t.read([tree[p]["oid"] for p in ok_paths])
272
+ texts, records = {}, []
273
+ roots = sorted({_lake_root(p, tree) for p in ok_paths})
274
+ for path in ok_paths:
275
+ b = blobs.get(tree[path]["oid"])
276
+ if b is None:
277
+ refusals.append(f"{role} {path}: blob {tree[path]['oid'][:12]} is not in the object store (partial clone?)")
278
+ continue
279
+ try:
280
+ texts[path] = b.decode("utf-8")
281
+ except UnicodeDecodeError:
282
+ refusals.append(f"{role} {path}: not UTF-8")
283
+ continue
284
+ records.append({"path": path, "module": None, "blob": tree[path]["oid"],
285
+ "sha256": hashlib.sha256(b).hexdigest()})
286
+ root = roots[0] if roots else ""
287
+ if len(roots) > 1:
288
+ warnings.append(f"{role}: the modules lie in {len(roots)} Lake packages; the pins are read from "
289
+ f"{roots[0] or 'the repository top'}")
290
+ pins = _pins(t, root, role, warnings)
291
+ return tree, texts, records, pins
292
+
293
+
294
+ def _target_path(module: str, tree: dict) -> tuple[str | None, str | None]:
295
+ """(path, None) of a target module's file, or (None, why)."""
296
+ want = lean_scan.module_file(module)
297
+ if want is None:
298
+ return None, "not a module name"
299
+ if want in tree:
300
+ return want, None
301
+ cands = sorted(p for p in tree if p.endswith("/" + want))
302
+ if len(cands) == 1:
303
+ return cands[0], None
304
+ if cands:
305
+ return None, f"ambiguous: {', '.join(cands)}"
306
+ return None, f"no file {want} (or */{want})"
307
+
308
+
309
+ # ----------------------------------------------------------------------------------------------------
310
+ # the comparison (method text/1)
311
+
312
+ class _Unit:
313
+ """One declaration span of one side."""
314
+
315
+ def __init__(self, span, module: str):
316
+ self.span, self.module = span, module
317
+ self.key, self.kind, self.names = span.key, span.kind, span.names
318
+
319
+
320
+ def _lookup(units: list[_Unit]) -> dict:
321
+ out = {}
322
+ for u in units:
323
+ out.setdefault(u.key, u)
324
+ for n in u.names:
325
+ out.setdefault(n, u)
326
+ return out
327
+
328
+
329
+ def _weakenable(method: str) -> tuple[str, ...]:
330
+ """The entry verdicts an --allow-differs reason can stand on: under types/1 also an IDENTICAL text
331
+ whose elaborated types differ."""
332
+ return ("DIFFERS", "IDENTICAL") if method == METHOD_TYPES else ("DIFFERS",)
333
+
334
+
335
+ def _zero_totals() -> dict:
336
+ return {k: 0 for k in TOTAL_KEYS}
337
+
338
+
339
+ def skeleton(spec: dict, method: str = METHOD_TEXT) -> dict:
340
+ side = {"commit": None, "lean_toolchain": None, "lake_manifest_sha256": None, "modules": []}
341
+ return {"schema": EXTRACT_LEDGER_SCHEMA, "method": method, "ok": False, "source": dict(side),
342
+ "target": dict(side), "map": map_record(spec), "entries": [], "context": [], "warnings": [],
343
+ "totals": _zero_totals()}
344
+
345
+
346
+ def compute(src_repo, src_commit: str, tgt_repo, tgt_commit: str | None, spec: dict,
347
+ refusals: list[str], target: Tree | None = None, *, method: str = METHOD_TEXT,
348
+ types: dict | None = None, names_out: dict | None = None) -> tuple[dict, list[str]]:
349
+ """(ledger, failures): the text/1 comparison of the mapped source modules at src_commit with the
350
+ target modules at tgt_commit (or, for `decls`, with the in-memory `target`, tgt_commit None). Input
351
+ problems are appended to refusals.
352
+
353
+ With method types/1, `types` maps a paired entry's source key to (source type sha256, target type
354
+ sha256, statement?) as `extract_types.bind` reads them from the programs' outputs (None: not yet run,
355
+ every entry uncompared); `names_out`, when given, receives {source key: (source names, target names)}
356
+ of every paired entry, which `extract_types.plan` turns into the programs."""
357
+ led = skeleton(spec, method)
358
+ led["source"]["commit"], led["target"]["commit"] = src_commit, tgt_commit
359
+ warnings: list[str] = []
360
+ check_spec(spec, refusals)
361
+ modules = sorted(spec["modules"])
362
+ src_tree, src_texts, src_recs, src_pins = _side(git_tree(src_repo, src_commit),
363
+ [p for p, _ in modules if not xp.bad_rel_path(p)],
364
+ "source", refusals, warnings)
365
+ tgt = target if target is not None else git_tree(tgt_repo, tgt_commit)
366
+ tgt_tree = tgt.tree
367
+ tgt_paths: dict[str, str] = {}
368
+ for path, mod in modules:
369
+ tp, why = _target_path(mod, tgt_tree)
370
+ if tp is None:
371
+ refusals.append(f"target module {mod} (from {path}): {why} at {tgt.label}")
372
+ else:
373
+ tgt_paths[mod] = tp
374
+ _t, tgt_texts, tgt_recs, tgt_pins = _side(tgt, sorted(set(tgt_paths.values())), "target", refusals, warnings)
375
+ src_root = {p: _lake_root(p, src_tree) for p in src_texts}
376
+ src_mod = {p: _module_name(p, src_root[p]) for p in src_texts}
377
+ tgt_mod_of_path = {tp: m for m, tp in tgt_paths.items()}
378
+ for r in src_recs:
379
+ r["module"] = src_mod[r["path"]]
380
+ for r in tgt_recs:
381
+ r["module"] = tgt_mod_of_path[r["path"]]
382
+ led["source"].update(lean_toolchain=src_pins[0], lake_manifest_sha256=src_pins[1],
383
+ modules=sorted(src_recs, key=lambda r: r["path"]))
384
+ led["target"].update(lean_toolchain=tgt_pins[0], lake_manifest_sha256=tgt_pins[1],
385
+ modules=sorted(tgt_recs, key=lambda r: r["path"]))
386
+ if src_pins[0] is not None and tgt_pins[0] is not None and src_pins[0] != tgt_pins[0]:
387
+ warnings.append(f"lean-toolchain differs: source {src_pins[0]}, target {tgt_pins[0]} (the same text may "
388
+ f"elaborate differently)")
389
+ for name in sorted(set(src_pins[2]) & set(tgt_pins[2])):
390
+ a, b = src_pins[2][name], tgt_pins[2][name]
391
+ if a != b:
392
+ warnings.append(f"lake-manifest.json: dependency {name} is at {str(a)[:12]} in the source and "
393
+ f"{str(b)[:12]} in the target (the same text may elaborate differently)")
394
+ led["warnings"] = sorted(set(warnings))
395
+
396
+ # split both sides; an unreadable file is refused whole
397
+ pairs = [] # (source path, source module, target module, target path)
398
+ for path, mod in modules:
399
+ if path in src_texts and mod in tgt_paths and tgt_paths[mod] in tgt_texts:
400
+ pairs.append((path, src_mod[path], mod, tgt_paths[mod]))
401
+ split: dict[tuple[str, str], tuple] = {}
402
+ for path, smod, tmod, tpath in pairs:
403
+ for role, p, m, texts in (("source", path, smod, src_texts), ("target", tpath, tmod, tgt_texts)):
404
+ try:
405
+ split[(role, p)] = lean_scan.decl_spans(texts[p], m)
406
+ except lean_scan.ScanError as e:
407
+ refusals.append(f"{role} {p}: cannot be split into declarations ({e}); text/1 refuses the file "
408
+ f"whole")
409
+ if refusals:
410
+ return led, []
411
+
412
+ src_units: list[_Unit] = []
413
+ tgt_units: list[_Unit] = []
414
+ src_ctx: dict[str, list] = {}
415
+ tgt_ctx: dict[str, list] = {}
416
+ mod_map = {}
417
+ for path, smod, tmod, tpath in pairs:
418
+ decls, ctx = split[("source", path)]
419
+ src_units += [_Unit(s, smod) for s in decls]
420
+ src_ctx[smod] = ctx
421
+ decls, ctx = split[("target", tpath)]
422
+ tgt_units += [_Unit(s, tmod) for s in decls]
423
+ tgt_ctx[tmod] = ctx
424
+ mod_map[smod] = tmod
425
+ for role, units in (("source", src_units), ("target", tgt_units)):
426
+ seen: dict[str, str] = {}
427
+ for u in units:
428
+ for n in u.names or (u.key,):
429
+ if n in seen and seen[n] != u.module:
430
+ refusals.append(f"{role}: {n} is declared in both {seen[n]} and {u.module}")
431
+ seen.setdefault(n, u.module)
432
+
433
+ ns, rn = spec["namespaces"], spec["renames"]
434
+ declared = sorted({n for u in src_units for n in u.names})
435
+ src_names = {_canon(n) for n in declared}
436
+
437
+ def mapped_name(n: str) -> str:
438
+ return lean_scan.apply_map(n, ns, rn)
439
+
440
+ def mapped_key(u: _Unit) -> str:
441
+ if not u.names: # instance#k@Src.A -> instance#k@New.A
442
+ return u.key.split("@", 1)[0] + "@" + mod_map[u.module]
443
+ if u.kind == "mutual":
444
+ return "mutual(" + ", ".join(sorted(mapped_name(n) for n in u.names)) + ")"
445
+ return mapped_name(u.names[0])
446
+
447
+ # staleness: every map entry must act on something
448
+ for old, _new in ns:
449
+ c = _canon(old)
450
+ if c is not None and not any(s[:len(c)] == c and len(s) > len(c) for s in src_names):
451
+ refusals.append(f"--namespace {old}={_new}: stale, no source declaration lies under {old}")
452
+ for old, _new in rn:
453
+ if _canon(old) not in src_names:
454
+ refusals.append(f"--rename {old}={_new}: stale, {old} is not a source declaration")
455
+ src_look, tgt_look = _lookup(src_units), _lookup(tgt_units)
456
+ dropped: dict[int, str] = {}
457
+ for decl, reason in spec["drops"]:
458
+ u = src_look.get(decl)
459
+ if u is None:
460
+ refusals.append(f"--drop {decl}: stale, not a source declaration of the mapped modules")
461
+ else:
462
+ dropped[id(u)] = reason
463
+ allowed: dict[int, str] = {}
464
+ allowed_ctx: dict[str, str] = {}
465
+ for decl, reason in spec["allow_differs"]:
466
+ if decl.startswith(CONTEXT_PREFIX) and decl[len(CONTEXT_PREFIX):] in mod_map:
467
+ allowed_ctx[decl[len(CONTEXT_PREFIX):]] = reason
468
+ continue
469
+ u = src_look.get(decl)
470
+ if u is None:
471
+ refusals.append(f"--allow-differs {decl}: stale, not a source declaration of the mapped modules "
472
+ f"(a module's context rows are {CONTEXT_PREFIX}<source module>)")
473
+ else:
474
+ allowed[id(u)] = reason
475
+ try:
476
+ keys = [(u, mapped_key(u)) for u in src_units]
477
+ except (lean_scan.MapError, lean_scan.ScanError) as e:
478
+ refusals.append(f"invalid map: {e}")
479
+ return led, []
480
+ by_key: dict[str, _Unit] = {}
481
+ for u, k in keys:
482
+ if k in by_key:
483
+ refusals.append(f"{by_key[k].key} and {u.key} both map to {k} in the target (a rename or namespace "
484
+ f"collision)")
485
+ by_key.setdefault(k, u)
486
+ tgt_by_key = {u.key: u for u in tgt_units}
487
+ for u, k in keys:
488
+ if id(u) in dropped and k in tgt_by_key:
489
+ refusals.append(f"--drop {u.key}: dropped, yet present in the target as {k} "
490
+ f"({tgt_by_key[k].module})")
491
+ # a dropped declaration still referenced by a kept one (best effort: identifiers resolved as apply_map does)
492
+ drop_names = [n for u in src_units if id(u) in dropped for n in u.names]
493
+ if drop_names:
494
+ sentinel = {n: f"lean_pkg_dropped_{i}" for i, n in enumerate(drop_names)}
495
+ back = {v: k for k, v in sentinel.items()}
496
+ for u in src_units:
497
+ if id(u) in dropped:
498
+ continue
499
+ probe = lean_scan.apply_map(u.span.code, (), sentinel.items(), src_scope=u.span.scope, declared=declared)
500
+ hits = sorted({back[t] for t in re.findall(r"lean_pkg_dropped_\d+", probe) if t in back})
501
+ for n in hits:
502
+ refusals.append(f"--drop {n}: still referenced by {u.key}, which is kept (best effort: an "
503
+ f"identifier that resolves to it)")
504
+ if refusals:
505
+ return led, []
506
+
507
+ entries, failures = [], []
508
+ used: set[str] = set()
509
+ typed = method == METHOD_TYPES
510
+ for u, k in keys:
511
+ mapped = lean_scan.apply_map(u.span.code, ns, rn, src_scope=u.span.scope, declared=declared)
512
+ raw_n, src_n = lean_scan.normalize(u.span.code), lean_scan.normalize(mapped)
513
+ row = {"kind": u.kind, "source": u.key, "target": k, "source_module": u.module,
514
+ "target_module": mod_map[u.module], "verdict": None, "source_raw_sha256": _sha(raw_n),
515
+ "source_sha256": _sha(src_n), "target_sha256": None, "whitespace_only": False,
516
+ "doc_changed": False, "reason": None}
517
+ if typed:
518
+ row.update(source_type_sha256=None, target_type_sha256=None, types_cleared=False)
519
+ t = tgt_by_key.get(k)
520
+ if t is None:
521
+ if id(u) in dropped:
522
+ row.update(verdict="DROPPED", reason=dropped[id(u)])
523
+ else:
524
+ row["verdict"] = "MISSING"
525
+ failures.append(f"MISSING {u.key}: expected {k} in the target, not found (drop it with "
526
+ f"--drop {u.key}:REASON if that is deliberate)")
527
+ entries.append(row)
528
+ continue
529
+ used.add(k)
530
+ tgt_n = lean_scan.normalize(t.span.code)
531
+ row.update(target_module=t.module, target_sha256=_sha(tgt_n), doc_changed=u.span.doc != t.span.doc)
532
+ if names_out is not None and u.names and t.names:
533
+ names_out[u.key] = (tuple(sorted(u.names, key=mapped_name)), tuple(sorted(t.names)))
534
+ ty = (types or {}).get(u.key) if typed else None
535
+ if ty is not None:
536
+ row.update(source_type_sha256=ty[0], target_type_sha256=ty[1])
537
+ if ty is not None and _sha(src_n) == row["target_sha256"] and ty[0] != ty[1]:
538
+ row["verdict"] = "IDENTICAL" # the false negative types/1 exists to catch
539
+ if id(u) in allowed:
540
+ row["reason"] = allowed[id(u)]
541
+ else:
542
+ failures.append(f"IDENTICAL {u.key} -> {k} (types differ): the texts are equal but the elaborated "
543
+ f"types are not (a name resolves to another constant, or the context differs); "
544
+ f"disclose it with --allow-differs {u.key}:REASON if deliberate")
545
+ elif _sha(src_n) == row["target_sha256"]:
546
+ row["verdict"] = "IDENTICAL"
547
+ if id(u) in allowed and not (typed and types is None): # types/1: stale only once the types are in
548
+ refusals.append(f"--allow-differs {u.key}: stale, the declaration is IDENTICAL"
549
+ + (" and so are its elaborated types" if ty is not None else ""))
550
+ elif ty is not None and ty[0] == ty[1]:
551
+ row["verdict"] = "DIFFERS"
552
+ row["whitespace_only"] = lean_scan.collapse_whitespace(src_n) == lean_scan.collapse_whitespace(tgt_n)
553
+ if ty[2]:
554
+ row["types_cleared"] = True # DIFFERS (types equal): the statement is the source's
555
+ if id(u) in allowed:
556
+ refusals.append(f"--allow-differs {u.key}: stale, the elaborated types are equal, which "
557
+ f"clears the text difference under types/1")
558
+ elif id(u) in allowed:
559
+ row["reason"] = allowed[id(u)]
560
+ else:
561
+ failures.append(f"DIFFERS {u.key} -> {k} (types equal): the types are equal but it is a definition, "
562
+ f"whose value types/1 does not compare (disclose it with --allow-differs "
563
+ f"{u.key}:REASON if deliberate)")
564
+ else:
565
+ row["verdict"] = "DIFFERS"
566
+ row["whitespace_only"] = lean_scan.collapse_whitespace(src_n) == lean_scan.collapse_whitespace(tgt_n)
567
+ if id(u) in allowed:
568
+ row["reason"] = allowed[id(u)]
569
+ else:
570
+ hint = " (whitespace only)" if row["whitespace_only"] else ""
571
+ if ty is not None:
572
+ hint += " (types differ)"
573
+ failures.append(f"DIFFERS {u.key} -> {k}{hint}: the mapped source text and the target text "
574
+ f"differ (disclose it with --allow-differs {u.key}:REASON if deliberate)")
575
+ entries.append(row)
576
+ for u, k in keys:
577
+ if id(u) in allowed and k not in tgt_by_key:
578
+ refusals.append(f"--allow-differs {u.key}: stale, the declaration is not in the target")
579
+ declared_new = {}
580
+ for decl, reason in spec["new"]:
581
+ t = tgt_look.get(decl)
582
+ if t is None:
583
+ refusals.append(f"--new {decl}: stale, not a declaration of the target modules")
584
+ elif t.key in used:
585
+ refusals.append(f"--new {decl}: stale, it has a source counterpart")
586
+ else:
587
+ declared_new[t.key] = reason
588
+ for t in tgt_units:
589
+ if t.key in used:
590
+ continue
591
+ row = {"kind": t.kind, "source": None, "target": t.key, "source_module": None, "target_module": t.module,
592
+ "verdict": "NEW", "source_raw_sha256": None, "source_sha256": None,
593
+ "target_sha256": _sha(lean_scan.normalize(t.span.code)), "whitespace_only": False,
594
+ "doc_changed": False, "reason": declared_new.get(t.key)}
595
+ if typed:
596
+ row.update(source_type_sha256=None, target_type_sha256=None, types_cleared=False)
597
+ if row["reason"] is None:
598
+ failures.append(f"NEW {t.key} ({t.module}): a target declaration with no source counterpart "
599
+ f"(declare it with --new {t.key}:REASON)")
600
+ entries.append(row)
601
+
602
+ context = []
603
+ for smod in sorted(mod_map):
604
+ tmod = mod_map[smod]
605
+
606
+ def joined(spans, mapped):
607
+ parts = []
608
+ for c in spans:
609
+ if c.kind in lean_scan._HEADER_WORDS:
610
+ continue
611
+ code = lean_scan.apply_map(c.code, ns, rn, src_scope=c.scope, declared=declared) if mapped else c.code
612
+ parts.append(lean_scan.normalize(code))
613
+ return "\n".join(p for p in parts if p)
614
+ a, b = _sha(joined(src_ctx[smod], True)), _sha(joined(tgt_ctx[tmod], False))
615
+ row = {"source_module": smod, "target_module": tmod, "verdict": "IDENTICAL" if a == b else "DIFFERS",
616
+ "source_sha256": a, "target_sha256": b, "reason": None}
617
+ if a != b:
618
+ if smod in allowed_ctx:
619
+ row["reason"] = allowed_ctx[smod]
620
+ else:
621
+ failures.append(f"context DIFFERS {smod} -> {tmod}: the module's other commands (open, variable, "
622
+ f"universe, set_option, namespace, notation, ...) differ after mapping (disclose "
623
+ f"it with --allow-differs {CONTEXT_PREFIX}{smod}:REASON if deliberate)")
624
+ elif smod in allowed_ctx:
625
+ refusals.append(f"--allow-differs {CONTEXT_PREFIX}{smod}: stale, the context rows are IDENTICAL")
626
+ context.append(row)
627
+
628
+ totals = _zero_totals()
629
+ for e in entries:
630
+ totals[e["verdict"]] += 1
631
+ totals["weakened"] = sum(1 for e in entries if e["verdict"] in _weakenable(method) and e["reason"] is not None) + \
632
+ sum(1 for c in context if c["verdict"] == "DIFFERS" and c["reason"] is not None)
633
+ led.update(entries=entries, context=context, totals=totals)
634
+ led["ok"] = not failures and not refusals
635
+ return led, failures
636
+
637
+
638
+ # ----------------------------------------------------------------------------------------------------
639
+ # reading a ledger back: strict
640
+
641
+ def _hex64_or_none(v) -> bool:
642
+ return v is None or (isinstance(v, str) and bool(HEX64.fullmatch(v)))
643
+
644
+
645
+ def _str_or_none(v) -> bool:
646
+ return v is None or isinstance(v, str)
647
+
648
+
649
+ def ledger_keys(method: str) -> tuple[str, ...]:
650
+ return LEDGER_KEYS + ("types",) if method == METHOD_TYPES else LEDGER_KEYS
651
+
652
+
653
+ def entry_keys(method: str) -> tuple[str, ...]:
654
+ return ENTRY_KEYS + TYPES_ENTRY_KEYS if method == METHOD_TYPES else ENTRY_KEYS
655
+
656
+
657
+ def _validate_types(obj: dict, refusals: list[str]) -> None:
658
+ """The keys method types/1 adds: the `types` block, and each entry's type hashes, coherent with its
659
+ verdict (a ledger is written only when nothing fails)."""
660
+ tb = obj["types"]
661
+ if ex._keys(tb, TYPES_KEYS, TYPES_KEYS, "ledger.types", refusals):
662
+ for k in ("lean", "lean_githash"):
663
+ if not isinstance(tb[k], str):
664
+ refusals.append(f"ledger.types.{k}: not a string")
665
+ for k in ("source_script_sha256", "target_script_sha256"):
666
+ if not (isinstance(tb[k], str) and HEX64.fullmatch(tb[k])):
667
+ refusals.append(f"ledger.types.{k}: not a SHA-256")
668
+ for i, e in enumerate(obj["entries"]):
669
+ w = f"ledger.entries[{i}]"
670
+ a, b, cleared = e["source_type_sha256"], e["target_type_sha256"], e["types_cleared"]
671
+ if not (_hex64_or_none(a) and _hex64_or_none(b)):
672
+ refusals.append(f"{w}: source_type_sha256 and target_type_sha256 must be SHA-256 or null")
673
+ continue
674
+ if not isinstance(cleared, bool):
675
+ refusals.append(f"{w}.types_cleared: not a boolean")
676
+ continue
677
+ if (a is None) != (b is None) or (a is not None and e["verdict"] not in ("IDENTICAL", "DIFFERS")):
678
+ refusals.append(f"{w}: type hashes on one side only, or on a {e['verdict']} entry")
679
+ elif cleared and not (e["verdict"] == "DIFFERS" and a is not None and a == b and e["reason"] is None):
680
+ refusals.append(f"{w}.types_cleared: true, but it is not a DIFFERS with equal types and no reason")
681
+ elif a is not None and a != b and e["reason"] is None:
682
+ refusals.append(f"{w}: the elaborated types differ and no reason allows it; a ledger is written "
683
+ f"only when nothing fails, so this one was edited")
684
+ elif e["verdict"] == "IDENTICAL" and e["reason"] is not None and (a is None or a == b):
685
+ refusals.append(f"{w}: an IDENTICAL entry carries a reason, but its types are not shown to differ")
686
+
687
+
688
+ def validate_ledger(obj, refusals: list[str]) -> dict | None:
689
+ """The ledger when it is a valid lean-pkg-extract-ledger/1 with method text/1 or types/1, else None
690
+ (refusals say why). Exact keys everywhere (types/1 adds its own), closed enums, consistent totals."""
691
+ n0 = len(refusals)
692
+ if not isinstance(obj, dict):
693
+ refusals.append("ledger: not a JSON object")
694
+ return None
695
+ schema = obj.get("schema")
696
+ if schema != EXTRACT_LEDGER_SCHEMA:
697
+ m = SCHEMA_RE.fullmatch(schema) if isinstance(schema, str) else None
698
+ if m and int(m.group(1)) > 1:
699
+ refusals.append(f"ledger: schema {schema} is newer than this lean-pkg reads ({EXTRACT_LEDGER_SCHEMA}): "
700
+ f"upgrade lean-pkg")
701
+ else:
702
+ refusals.append(f"ledger: unknown schema {schema!r} (expected {EXTRACT_LEDGER_SCHEMA})")
703
+ return None
704
+ method = obj.get("method")
705
+ if method not in METHODS:
706
+ if "method" not in obj:
707
+ ex._keys(obj, LEDGER_KEYS, LEDGER_KEYS, "ledger", refusals)
708
+ elif isinstance(method, str) and FUTURE_METHOD.fullmatch(method):
709
+ refusals.append(f"ledger: method {method} is not known to this lean-pkg (it reads "
710
+ f"{' and '.join(METHODS)}): upgrade lean-pkg")
711
+ else:
712
+ refusals.append(f"ledger: unknown method {method!r}")
713
+ return None
714
+ if not ex._keys(obj, ledger_keys(method), ledger_keys(method), "ledger", refusals):
715
+ return None
716
+ if obj["ok"] is not True:
717
+ refusals.append("ledger: ok is not true; the tool writes a ledger only when nothing fails, so this one "
718
+ "was edited")
719
+ for role in ("source", "target"):
720
+ side = obj[role]
721
+ if not ex._keys(side, SIDE_KEYS, SIDE_KEYS, f"ledger.{role}", refusals):
722
+ continue
723
+ c = side["commit"]
724
+ if not ((isinstance(c, str) and ex.HEX40.fullmatch(c)) or (c is None and role == "target")):
725
+ refusals.append(f"ledger.{role}.commit: not a full 40-hex commit: {c!r}")
726
+ if not _str_or_none(side["lean_toolchain"]):
727
+ refusals.append(f"ledger.{role}.lean_toolchain: not a string or null")
728
+ if not _hex64_or_none(side["lake_manifest_sha256"]):
729
+ refusals.append(f"ledger.{role}.lake_manifest_sha256: not a SHA-256 or null")
730
+ if not isinstance(side["modules"], list):
731
+ refusals.append(f"ledger.{role}.modules: not a list")
732
+ continue
733
+ for i, r in enumerate(side["modules"]):
734
+ w = f"ledger.{role}.modules[{i}]"
735
+ if ex._keys(r, MODULE_KEYS, MODULE_KEYS, w, refusals):
736
+ if not (isinstance(r["path"], str) and isinstance(r["module"], str)):
737
+ refusals.append(f"{w}: path and module must be strings")
738
+ if not (isinstance(r["blob"], str) and OID.fullmatch(r["blob"])):
739
+ refusals.append(f"{w}.blob: not a git object id")
740
+ if not (isinstance(r["sha256"], str) and HEX64.fullmatch(r["sha256"])):
741
+ refusals.append(f"{w}.sha256: not a SHA-256")
742
+ m = obj["map"]
743
+ if ex._keys(m, MAP_KEYS, MAP_KEYS, "ledger.map", refusals):
744
+ for key in MAP_KEYS:
745
+ rows = m[key]
746
+ want = PAIR_KEYS if key in ("modules", "namespaces", "renames") else REASON_KEYS
747
+ if not isinstance(rows, list):
748
+ refusals.append(f"ledger.map.{key}: not a list")
749
+ continue
750
+ for i, r in enumerate(rows):
751
+ w = f"ledger.map.{key}[{i}]"
752
+ if ex._keys(r, want, want, w, refusals) and not all(isinstance(r[k], str) for k in want):
753
+ refusals.append(f"{w}: every value must be a string")
754
+ entries = obj["entries"]
755
+ if not isinstance(entries, list):
756
+ refusals.append("ledger.entries: not a list")
757
+ entries = []
758
+ for i, e in enumerate(entries):
759
+ w = f"ledger.entries[{i}]"
760
+ if not ex._keys(e, entry_keys(method), entry_keys(method), w, refusals):
761
+ continue
762
+ if e["verdict"] not in VERDICTS:
763
+ refusals.append(f"{w}.verdict: {e['verdict']!r} is not one of {', '.join(VERDICTS)}")
764
+ if e["kind"] not in DECL_KINDS:
765
+ refusals.append(f"{w}.kind: {e['kind']!r} is not a declaration kind")
766
+ for k in ("source", "target", "source_module", "target_module", "reason"):
767
+ if not _str_or_none(e[k]):
768
+ refusals.append(f"{w}.{k}: not a string or null")
769
+ for k in ("source_raw_sha256", "source_sha256", "target_sha256"):
770
+ if not _hex64_or_none(e[k]):
771
+ refusals.append(f"{w}.{k}: not a SHA-256 or null")
772
+ for k in ("whitespace_only", "doc_changed"):
773
+ if not isinstance(e[k], bool):
774
+ refusals.append(f"{w}.{k}: not a boolean")
775
+ context = obj["context"]
776
+ if not isinstance(context, list):
777
+ refusals.append("ledger.context: not a list")
778
+ context = []
779
+ for i, c in enumerate(context):
780
+ w = f"ledger.context[{i}]"
781
+ if not ex._keys(c, CONTEXT_KEYS, CONTEXT_KEYS, w, refusals):
782
+ continue
783
+ if c["verdict"] not in CONTEXT_VERDICTS:
784
+ refusals.append(f"{w}.verdict: {c['verdict']!r} is not IDENTICAL or DIFFERS")
785
+ for k in ("source_sha256", "target_sha256"):
786
+ if not (isinstance(c[k], str) and HEX64.fullmatch(c[k])):
787
+ refusals.append(f"{w}.{k}: not a SHA-256")
788
+ for k in ("source_module", "target_module"):
789
+ if not isinstance(c[k], str):
790
+ refusals.append(f"{w}.{k}: not a string")
791
+ if not _str_or_none(c["reason"]):
792
+ refusals.append(f"{w}.reason: not a string or null")
793
+ if not (isinstance(obj["warnings"], list) and all(isinstance(x, str) for x in obj["warnings"])):
794
+ refusals.append("ledger.warnings: not a list of strings")
795
+ t = obj["totals"]
796
+ if ex._keys(t, TOTAL_KEYS, TOTAL_KEYS, "ledger.totals", refusals):
797
+ if not all(type(t[k]) is int and t[k] >= 0 for k in TOTAL_KEYS):
798
+ refusals.append("ledger.totals: every count must be a non-negative integer")
799
+ elif len(refusals) == n0:
800
+ want = _zero_totals()
801
+ for e in entries:
802
+ want[e["verdict"]] += 1
803
+ want["weakened"] = sum(1 for r in entries if r["verdict"] in _weakenable(method) and r["reason"]) + \
804
+ sum(1 for r in context if r["verdict"] == "DIFFERS" and r["reason"])
805
+ if want != t:
806
+ refusals.append(f"ledger.totals: {t} does not count the entries ({want})")
807
+ if method == METHOD_TYPES and len(refusals) == n0:
808
+ _validate_types(obj, refusals)
809
+ return obj if len(refusals) == n0 else None
810
+
811
+
812
+ def _diff(a, b, path: str, out: list[str]) -> None:
813
+ """Field paths where a (recorded) and b (recomputed) differ."""
814
+ if isinstance(a, dict) and isinstance(b, dict):
815
+ for k in sorted(set(a) | set(b)):
816
+ _diff(a.get(k), b.get(k), f"{path}.{k}", out)
817
+ elif isinstance(a, list) and isinstance(b, list):
818
+ if len(a) != len(b):
819
+ out.append(f"{path}: {len(a)} recorded, {len(b)} recomputed")
820
+ for i, (x, y) in enumerate(zip(a, b, strict=False)):
821
+ _diff(x, y, f"{path}[{i}]", out)
822
+ elif a != b:
823
+ out.append(f"{path}: recorded {a!r}, recomputed {b!r}")
824
+
825
+
826
+ def drift(old: dict, new: dict) -> list[str]:
827
+ """What changed between the recorded ledger and a recomputation at other commits (informational)."""
828
+ out = []
829
+ o = {e["source"] or "NEW " + e["target"]: e for e in old["entries"]}
830
+ n = {e["source"] or "NEW " + e["target"]: e for e in new["entries"]}
831
+ for k in sorted(set(o) | set(n)):
832
+ a, b = o.get(k), n.get(k)
833
+ if a is None:
834
+ out.append(f"{k}: not in the ledger, now {b['verdict']}")
835
+ elif b is None:
836
+ out.append(f"{k}: in the ledger ({a['verdict']}), no longer present")
837
+ else:
838
+ changed = [f for f in ("source_raw_sha256", "target_sha256", "source_type_sha256", "target_type_sha256")
839
+ if a.get(f) != b.get(f)]
840
+ if a["verdict"] != b["verdict"]:
841
+ changed.append(f"verdict {a['verdict']} -> {b['verdict']}")
842
+ if changed:
843
+ out.append(f"{k}: " + ", ".join(changed))
844
+ for side in ("source", "target"):
845
+ om = {r["path"]: r["blob"] for r in old[side]["modules"]}
846
+ nm = {r["path"]: r["blob"] for r in new[side]["modules"]}
847
+ for p in sorted(set(om) | set(nm)):
848
+ if om.get(p) != nm.get(p):
849
+ out.append(f"{side} module {p}: blob {str(om.get(p))[:12]} -> {str(nm.get(p))[:12]}")
850
+ return out
851
+
852
+
853
+ # ----------------------------------------------------------------------------------------------------
854
+ # output
855
+
856
+ def _counts(led: dict) -> str:
857
+ t = led["totals"]
858
+ ctx = led["context"]
859
+ cd = sum(1 for c in ctx if c["verdict"] == "DIFFERS")
860
+ typed = ""
861
+ if led["method"] == METHOD_TYPES:
862
+ rows = [e for e in led["entries"] if e.get("source_type_sha256") is not None]
863
+ diff = sum(1 for e in rows if e["source_type_sha256"] != e["target_type_sha256"])
864
+ cleared = sum(1 for e in rows if e["types_cleared"])
865
+ typed = f"; types: {len(rows)} compared, {diff} differ, {cleared} cleared a text difference"
866
+ return (f"{t['IDENTICAL']} identical, {t['DROPPED']} dropped, {t['DIFFERS']} differs, {t['NEW']} new, "
867
+ f"{t['MISSING']} missing, {t['weakened']} weakened; {len(ctx)} context row(s) ({cd} differ); "
868
+ f"{len(led['warnings'])} warning(s){typed}")
869
+
870
+
871
+ def verdict(verb: str, out: dict) -> str:
872
+ led = out
873
+ progs = out.get("programs")
874
+ if out["refusals"]:
875
+ head = f"{verb}: REFUSED ({len(out['refusals'])} refusal(s))"
876
+ elif progs is not None:
877
+ head = f"{verb}: PROGRAMS WRITTEN" if progs["written"] else f"{verb}: OK"
878
+ elif out["failures"]:
879
+ head = f"{verb}: FAILED ({len(out['failures'])} failure(s))"
880
+ else:
881
+ head = f"{verb}: OK"
882
+ src = led["source"]["commit"] or "unresolved"
883
+ tgt = led["target"]["commit"] or "unresolved"
884
+ tail = ""
885
+ if progs is not None:
886
+ pending = f"; {len(out['failures'])} text failure(s) the types may settle" if out["failures"] else ""
887
+ tail = (f"; {len(progs['files'])} program(s) written to {progs['dir']}, {progs['count']} declaration(s) to "
888
+ f"compare{pending}; nothing else written" if progs["written"] else "; nothing written")
889
+ elif verb == "ledger":
890
+ tail = f"; written to {out['ledger_path']}" if out["written"] else "; nothing written"
891
+ elif verb == "decls":
892
+ o = out["output"]
893
+ if o["written"]:
894
+ init = ", git initialized" if o["git_init"] else ""
895
+ tail = (f"; {len(o['files'])} file(s) written to {o['dir']}{init}, nothing committed; ledger written "
896
+ f"to {out['ledger_path']}")
897
+ elif o["dry_run"] and out["ok"]:
898
+ tail = f"; dry run: {len(o['files'])} file(s) would be written to {o['dir']}, nothing written"
899
+ else:
900
+ tail = "; nothing written"
901
+ tgt = "not committed" if out["ok"] else tgt
902
+ if out.get("public_summary") is not None:
903
+ tail = (f"; public summary written to {out['public_summary_path']}" if out["public_summary"]["written"]
904
+ else "; public summary not written")
905
+ return f"{head} ({led['method']}): {_counts(led)}; source {src}, target {tgt}{tail}"
906
+
907
+
908
+ def _entry_label(e: dict) -> str:
909
+ """The verdict as shown: under types/1 with the types' verdict beside a text verdict it changes."""
910
+ a, b = e.get("source_type_sha256"), e.get("target_type_sha256")
911
+ if a is None:
912
+ return e["verdict"]
913
+ if e["verdict"] == "DIFFERS":
914
+ return "DIFFERS (types equal)" if a == b else "DIFFERS (types differ)"
915
+ return "IDENTICAL (types differ)" if a != b else e["verdict"]
916
+
917
+
918
+ def render(verb: str, out: dict) -> str:
919
+ lines = [verdict(verb, out)]
920
+ typed = out["method"] == METHOD_TYPES
921
+ if out["refusals"]:
922
+ lines.append("refusals:")
923
+ lines += [f" - {r}" for r in out["refusals"]]
924
+ if out["failures"]:
925
+ lines.append("text failures (types/1 may clear a statement's DIFFERS):" if out.get("programs") else "failures:")
926
+ lines += [f" - {r}" for r in out["failures"]]
927
+ if out.get("drift"):
928
+ lines.append("drift since the ledger:")
929
+ lines += [f" - {r}" for r in out["drift"]]
930
+ if out["warnings"]:
931
+ lines.append("warnings (reported, not refused):")
932
+ lines += [f" - {w}" for w in out["warnings"]]
933
+ progs = out.get("programs")
934
+ if progs and progs["written"]:
935
+ lines.append(f"programs ({PRIVATE}): run each in its checkout, clean and at the commit shown, after "
936
+ f"`lake build` of its modules, and pass both outputs to --from-output:")
937
+ for side, f in zip(("source", "target"), progs["files"], strict=True):
938
+ lines.append(f" {side}: lake env lean --run {f} > {side}.out (script_sha256 {progs[side + '_script_sha256']})")
939
+ if out["entries"]:
940
+ lines.append(f"entries ({PRIVATE}):")
941
+ for e in out["entries"]:
942
+ if e["verdict"] == "NEW":
943
+ what = f"{e['target']} ({e['target_module']})"
944
+ else:
945
+ what = f"{e['source']} -> {e['target']}"
946
+ notes = []
947
+ if e["reason"] is not None:
948
+ label = {"DROPPED": "dropped", "NEW": "declared", "DIFFERS": "allowed", "IDENTICAL": "allowed"}[e["verdict"]]
949
+ notes.append(f"{label}: {e['reason']}")
950
+ if e["whitespace_only"]:
951
+ notes.append("whitespace only")
952
+ if e["doc_changed"]:
953
+ notes.append("docstring changed")
954
+ if typed and e.get("types_cleared"):
955
+ notes.append("cleared: the statement's elaborated type is the source's")
956
+ elif typed and e["verdict"] in ("IDENTICAL", "DIFFERS") and e["source"] is not None and \
957
+ e.get("source_type_sha256") is None and out.get("types"):
958
+ notes.append("types not compared (no constant name)")
959
+ lines.append(f" {_entry_label(e):<9} {e['kind']:<9} {what}" + (f" ({'; '.join(notes)})" if notes else ""))
960
+ if out["context"]:
961
+ lines.append("context rows (each module's other commands, after mapping):")
962
+ for c in out["context"]:
963
+ note = f" (allowed: {c['reason']})" if c["reason"] is not None else ""
964
+ lines.append(f" {c['verdict']:<9} {c['source_module']} -> {c['target_module']}{note}")
965
+ if out["source"]["modules"] or out["target"]["modules"]:
966
+ lines.append(f"modules ({PRIVATE}):")
967
+ for role in ("source", "target"):
968
+ side = out[role]
969
+ pin = f"; lean-toolchain {side['lean_toolchain']}" if side["lean_toolchain"] else ""
970
+ at = side["commit"] or ("not committed" if verb == "decls" and role == "target" else "unresolved")
971
+ lines.append(f" {role} at {at}{pin}")
972
+ lines += [f" {r['path']} ({r['module']}) blob {r['blob']} sha256 {r['sha256']}" for r in side["modules"]]
973
+ if typed and out.get("types"):
974
+ tb = out["types"]
975
+ lines.append(f"types: Lean {tb['lean']} ({tb['lean_githash']}); programs source {tb['source_script_sha256']}, "
976
+ f"target {tb['target_script_sha256']}")
977
+ lines.append("totals: " + ", ".join(f"{k} {v}" for k, v in out["totals"].items()))
978
+ ps_ = (out.get("public_summary") or {}).get("public_safety")
979
+ if ps_ is not None:
980
+ lines.append(f"public-safety of the public summary: {ps_['block_hits']} blocking, {ps_['warn_hits']} warn-only")
981
+ lines.append(verdict(verb, out))
982
+ return "\n".join(lines)
983
+
984
+
985
+ def ledger_json(led: dict) -> str:
986
+ return json.dumps({k: led[k] for k in ledger_keys(led["method"])}, indent=2, sort_keys=True,
987
+ ensure_ascii=False) + "\n"
988
+
989
+
990
+ def public_json(out: dict) -> str:
991
+ return json.dumps({k: v for k, v in out.items() if k not in ("ledger_path", "public_summary_path")}, indent=2,
992
+ sort_keys=True, ensure_ascii=False) + "\n"
993
+
994
+
995
+ # ----------------------------------------------------------------------------------------------------
996
+ # the verbs
997
+
998
+ def _inside(p: pathlib.Path, roots) -> bool:
999
+ return any(r is not None and (p == r or r in p.parents) for r in roots)
1000
+
1001
+
1002
+ def ledger_path_refusals(arg: str, src_roots, target_roots, target_where: str) -> list[str]:
1003
+ """Why --ledger PATH cannot be written: inside SRC (its work tree or git directory), inside the target
1004
+ (`target_where` names it), a symlink, existing, or in a missing directory. Shared by ledger and decls."""
1005
+ refusals = []
1006
+ ledger = pathlib.Path(arg).expanduser()
1007
+ lp = ledger.parent.resolve() / ledger.name
1008
+ if _inside(lp, src_roots):
1009
+ refusals.append(f"--ledger {arg}: inside the source repository; the ledger names private source "
1010
+ f"paths and lean-pkg-extract leaves SRC unchanged, so write it outside SRC (copy it into "
1011
+ f"SRC's notes/ by hand to keep it there)")
1012
+ if _inside(lp, target_roots):
1013
+ refusals.append(f"--ledger {arg}: {target_where}; the ledger is private and never enters the exported "
1014
+ f"tree, so write it outside the target")
1015
+ if ledger.is_symlink():
1016
+ refusals.append(f"--ledger {arg}: a symlink; name a new regular file")
1017
+ elif ledger.exists():
1018
+ refusals.append(f"--ledger {arg}: exists; a ledger is evidence and is never overwritten, so "
1019
+ f"record to a new path")
1020
+ elif not lp.parent.is_dir():
1021
+ refusals.append(f"--ledger {arg}: its directory does not exist")
1022
+ return refusals
1023
+
1024
+
1025
+ def script_dir_refusals(arg: str, src_roots, target_roots) -> list[str]:
1026
+ """Why --emit-script DIR cannot be written: inside SRC or the target, a symlink, existing, or in a
1027
+ missing directory. The source program names private source declarations."""
1028
+ refusals = []
1029
+ d = pathlib.Path(arg).expanduser()
1030
+ dp = d.parent.resolve() / d.name
1031
+ if _inside(dp, src_roots):
1032
+ refusals.append(f"--emit-script {arg}: inside the source repository, which lean-pkg-extract leaves "
1033
+ f"unchanged; write the programs outside SRC (they run from anywhere: lake env lean --run "
1034
+ f"DIR/source.lean)")
1035
+ if _inside(dp, target_roots):
1036
+ refusals.append(f"--emit-script {arg}: inside the target repository; the source program names private "
1037
+ f"source declarations, so write the programs outside the target")
1038
+ if d.is_symlink():
1039
+ refusals.append(f"--emit-script {arg}: a symlink; name a new directory")
1040
+ elif d.exists():
1041
+ refusals.append(f"--emit-script {arg}: exists; name a new directory")
1042
+ elif not dp.parent.is_dir():
1043
+ refusals.append(f"--emit-script {arg}: its parent directory does not exist")
1044
+ return refusals
1045
+
1046
+
1047
+ def _method_mode(args, method: str | None) -> str | None:
1048
+ """'emit', 'read' or None (text/1) for the flags of `ledger` (method from --method) or `recheck` (the
1049
+ ledger's method; refusals there are its own). Usage errors exit 2."""
1050
+ emit, read = getattr(args, "emit_script", None), getattr(args, "from_output", None)
1051
+ if emit and read:
1052
+ raise ex.Usage("--emit-script and --from-output are two steps: write the programs first, run them, then "
1053
+ "read their outputs")
1054
+ if method is None: # recheck: the ledger decides
1055
+ return "emit" if emit else ("read" if read else None)
1056
+ if method == METHOD_TEXT:
1057
+ if emit or read:
1058
+ raise ex.Usage(f"{'--emit-script' if emit else '--from-output'} needs --method types (text/1 runs no Lean)")
1059
+ return None
1060
+ if not (emit or read):
1061
+ raise ex.Usage("--method types needs --emit-script DIR (write the Lean programs) or --from-output "
1062
+ "SOURCE.out TARGET.out (read what they printed); lean-pkg does not run Lean")
1063
+ return "emit" if emit else "read"
1064
+
1065
+
1066
+ def _types_compute(repo, c: str, tdir, t: str, spec: dict, refusals: list[str], mode: str,
1067
+ args) -> tuple[dict, list[str], dict | None]:
1068
+ """(ledger, failures, programs record or None) of method types/1: the text comparison and the
1069
+ programs (mode emit, written to --emit-script DIR when nothing is refused), or the programs' outputs
1070
+ read back, bound to this ledger and folded into its entries (mode read)."""
1071
+ from . import extract_types as xt
1072
+ names: dict = {}
1073
+ led, failures = compute(repo, c, tdir, t, spec, refusals, method=METHOD_TYPES, names_out=names)
1074
+ led["types"] = None
1075
+ if refusals:
1076
+ return led, failures, None
1077
+ items, progs = xt.programs(led, names)
1078
+ if mode == "emit":
1079
+ d = pathlib.Path(args.emit_script).expanduser()
1080
+ rec = {"dir": args.emit_script, "files": [str(d / xt.SCRIPT_FILES[s]) for s in xt.SIDES],
1081
+ "count": len(items), "written": False,
1082
+ "source_script_sha256": progs["source"][1], "target_script_sha256": progs["target"][1]}
1083
+ try:
1084
+ d.mkdir()
1085
+ for s in xt.SIDES:
1086
+ with open(d / xt.SCRIPT_FILES[s], "x", encoding="utf-8") as f:
1087
+ f.write(progs[s][0])
1088
+ rec["written"] = True
1089
+ except OSError as e:
1090
+ refusals.append(f"--emit-script {args.emit_script}: cannot be written ({e.strerror or e})")
1091
+ return led, failures, rec
1092
+ outputs = xt.load_outputs(args.from_output, refusals)
1093
+ if refusals:
1094
+ return led, failures, None
1095
+ warns: list[str] = []
1096
+ types = xt.bind(outputs, items, progs, led, refusals, warns)
1097
+ if types is None:
1098
+ return led, failures, None
1099
+ led, failures = compute(repo, c, tdir, t, spec, refusals, method=METHOD_TYPES, types=types)
1100
+ led["types"] = xt.types_block(outputs, progs)
1101
+ led["warnings"] = sorted(set(led["warnings"]) | set(warns))
1102
+ return led, failures, None
1103
+
1104
+
1105
+ def run_ledger(args) -> tuple[dict, int]:
1106
+ repo = pathlib.Path(args.repo).expanduser()
1107
+ tdir = pathlib.Path(args.target).expanduser()
1108
+ method = METHOD_TYPES if args.method == "types" else METHOD_TEXT
1109
+ mode = _method_mode(args, method)
1110
+ if args.ledger is None and mode != "emit":
1111
+ raise ex.Usage("--ledger PATH is required (only --emit-script writes no ledger)")
1112
+ top, gitdir = ex._src_top(repo)
1113
+ ttop, tgitdir = ex._src_top(tdir, "--target")
1114
+ refusals: list[str] = []
1115
+ spec = parse_spec(args, refusals)
1116
+ if mode == "emit":
1117
+ refusals += script_dir_refusals(args.emit_script, (top, gitdir), (ttop, tgitdir))
1118
+ else:
1119
+ refusals += ledger_path_refusals(args.ledger, (top, gitdir), (ttop, tgitdir), "inside the target repository")
1120
+ c = ex.resolve_commit(repo, args.commit)
1121
+ t = ex.resolve_commit(tdir, args.target_commit or "HEAD")
1122
+ if not c:
1123
+ refusals.append(f"--commit {args.commit!r} is not a commit of the source repository")
1124
+ if not t:
1125
+ refusals.append(f"--target-commit {args.target_commit or 'HEAD'!r} is not a commit of the target repository")
1126
+ progs = None
1127
+ if c and t and mode is not None:
1128
+ led, failures, progs = _types_compute(repo, c, tdir, t, spec, refusals, mode, args)
1129
+ elif c and t:
1130
+ led, failures = compute(repo, c, tdir, t, spec, refusals)
1131
+ else:
1132
+ check_spec(spec, refusals)
1133
+ led, failures = skeleton(spec, method), []
1134
+ led["source"]["commit"], led["target"]["commit"] = c, t
1135
+ if method == METHOD_TYPES:
1136
+ led["types"] = None
1137
+ out = _output(led, refusals, failures)
1138
+ if mode == "emit":
1139
+ out["programs"] = progs or {"dir": args.emit_script, "files": [], "count": 0, "written": False,
1140
+ "source_script_sha256": None, "target_script_sha256": None}
1141
+ out["ok"] = not out["refusals"] and out["programs"]["written"]
1142
+ out["ledger_path"] = args.ledger
1143
+ return out, (0 if out["ok"] else 1)
1144
+ if out["ok"]:
1145
+ try:
1146
+ with open(pathlib.Path(args.ledger).expanduser(), "x", encoding="utf-8") as f:
1147
+ f.write(ledger_json(led))
1148
+ out["written"] = True
1149
+ except OSError as e:
1150
+ out["refusals"].append(f"--ledger {args.ledger}: cannot be written ({e.strerror or e})")
1151
+ out["ok"] = False
1152
+ out["ledger_path"] = args.ledger
1153
+ return out, (0 if out["ok"] else 1)
1154
+
1155
+
1156
+ def _output(led: dict, refusals: list[str], failures: list[str]) -> dict:
1157
+ out = dict(led)
1158
+ out["refusals"] = sorted(set(refusals))
1159
+ out["failures"] = failures
1160
+ out["ok"] = not refusals and not failures
1161
+ out["written"] = False
1162
+ return out
1163
+
1164
+
1165
+ def run_recheck(args) -> tuple[dict, int]:
1166
+ """recheck, and with --public-summary PATH the summary of a passing recheck (extract_summary.py)."""
1167
+ summ = getattr(args, "public_summary", None)
1168
+ if getattr(args, "include_source_commit", False) and summ is None:
1169
+ raise ex.Usage("--include-source-commit adds the source commit to the public summary; pass "
1170
+ "--public-summary PATH")
1171
+ if summ is not None and getattr(args, "emit_script", None):
1172
+ raise ex.Usage("--public-summary summarizes a recheck, and --emit-script only writes the Lean programs; "
1173
+ "pass it with --from-output, once the programs have run")
1174
+ state: dict = {}
1175
+ out, rc = _recheck(args, state)
1176
+ if summ is None:
1177
+ return out, rc
1178
+ from . import extract_summary as xs
1179
+ rec = {"written": False, "sha256": None, "include_source_commit": bool(args.include_source_commit),
1180
+ "public_safety": None}
1181
+ if out["ok"]:
1182
+ text = xs.summary_json(xs.summary(out, state["data"], state["same"], args.include_source_commit))
1183
+ scan, refs = xs.write(summ, text, state["top"], state["top"] or state["gitdir"])
1184
+ rec["public_safety"] = scan
1185
+ if refs:
1186
+ out["refusals"] = sorted(set(out["refusals"]) | set(refs))
1187
+ out["ok"], rc = False, 1
1188
+ else:
1189
+ rec.update(written=True, sha256=_sha(text))
1190
+ out["public_summary"] = rec
1191
+ out["public_summary_path"] = summ
1192
+ return out, rc
1193
+
1194
+
1195
+ def _recheck(args, state: dict) -> tuple[dict, int]:
1196
+ repo = pathlib.Path(args.repo).expanduser()
1197
+ tdir = pathlib.Path(args.target).expanduser()
1198
+ _method_mode(args, None)
1199
+ top, gitdir = ex._src_top(repo)
1200
+ ttop, tgitdir = ex._src_top(tdir, "--target")
1201
+ refusals: list[str] = []
1202
+ state.update(top=top, gitdir=gitdir, same=False)
1203
+ if getattr(args, "public_summary", None) is not None:
1204
+ from . import extract_summary as xs
1205
+ refusals += xs.path_refusals(args.public_summary, (top, gitdir))
1206
+ path = pathlib.Path(args.ledger).expanduser()
1207
+ stored = None
1208
+ try:
1209
+ data = path.read_bytes() if path.is_file() else None
1210
+ except OSError:
1211
+ data = None
1212
+ state["data"] = data
1213
+ if data is None:
1214
+ refusals.append(f"--ledger {args.ledger}: not a readable regular file")
1215
+ else:
1216
+ raw, err = ex.load_json_strict(data, "ledger")
1217
+ if err:
1218
+ refusals.append(err)
1219
+ else:
1220
+ stored = validate_ledger(raw, refusals)
1221
+ if stored is None:
1222
+ led = skeleton(empty_spec())
1223
+ return _output(led, refusals, []) | {"drift": []}, 1
1224
+ method = stored["method"]
1225
+ mode = _method_mode(args, None)
1226
+ if method == METHOD_TEXT and mode is not None:
1227
+ refusals.append(f"{'--emit-script' if mode == 'emit' else '--from-output'}: the ledger's method is "
1228
+ f"{METHOD_TEXT}, which runs no Lean program; recheck it without the flag")
1229
+ elif method == METHOD_TYPES and mode is None:
1230
+ refusals.append(f"the ledger's method is {METHOD_TYPES}: lean-pkg cannot recompute elaborated types without "
1231
+ f"Lean, so recheck needs the outputs of its programs: --emit-script DIR, run the two "
1232
+ f"programs, then --from-output SOURCE.out TARGET.out")
1233
+ elif mode == "emit":
1234
+ refusals += script_dir_refusals(args.emit_script, (top, gitdir), (ttop, tgitdir))
1235
+ spec = spec_from_map(stored["map"])
1236
+ c_arg = args.commit or stored["source"]["commit"]
1237
+ t_arg = args.target_commit or stored["target"]["commit"]
1238
+ c = ex.resolve_commit(repo, c_arg)
1239
+ t = ex.resolve_commit(tdir, t_arg) if t_arg else None
1240
+ if not c:
1241
+ refusals.append(f"source commit {c_arg} ({'--commit' if args.commit else 'the ledger'}) is not a commit "
1242
+ f"of the source repository")
1243
+ if not t_arg:
1244
+ refusals.append("the ledger records no target commit (target.commit is null): pass --target-commit")
1245
+ elif not t:
1246
+ refusals.append(f"target commit {t_arg} ({'--target-commit' if args.target_commit else 'the ledger'}) is "
1247
+ f"not a commit of the target repository")
1248
+ if not (c and t) or refusals:
1249
+ led = skeleton(spec, method)
1250
+ if method == METHOD_TYPES:
1251
+ led["types"] = None
1252
+ led["source"]["commit"], led["target"]["commit"] = c, t
1253
+ return _output(led, refusals, []) | {"drift": []}, 1
1254
+ if method == METHOD_TYPES:
1255
+ led, failures, progs = _types_compute(repo, c, tdir, t, spec, refusals, mode, args)
1256
+ else:
1257
+ led, failures = compute(repo, c, tdir, t, spec, refusals)
1258
+ progs = None
1259
+ out = _output(led, refusals, failures)
1260
+ if mode == "emit":
1261
+ out["programs"] = progs or {"dir": args.emit_script, "files": [], "count": 0, "written": False,
1262
+ "source_script_sha256": None, "target_script_sha256": None}
1263
+ out["ok"] = not out["refusals"] and out["programs"]["written"]
1264
+ out["drift"] = []
1265
+ return out, (0 if out["ok"] else 1)
1266
+ same = c == stored["source"]["commit"] and (stored["target"]["commit"] in (None, t))
1267
+ state["same"] = same
1268
+ if same and not refusals:
1269
+ want = {k: led[k] for k in ledger_keys(method)}
1270
+ recorded = dict(stored)
1271
+ if recorded["target"]["commit"] is None:
1272
+ recorded = dict(recorded, target=dict(recorded["target"], commit=t))
1273
+ diffs: list[str] = []
1274
+ _diff(recorded, want, "ledger", diffs)
1275
+ out["drift"] = diffs
1276
+ if diffs:
1277
+ shown = "; ".join(diffs[:10]) + (f"; ... ({len(diffs) - 10} more)" if len(diffs) > 10 else "")
1278
+ out["refusals"].append(f"the ledger does not match a recomputation at its own commits ({len(diffs)} "
1279
+ f"field(s) differ, so it was edited or the sources' git objects changed): {shown}")
1280
+ out["ok"] = False
1281
+ else:
1282
+ out["drift"] = drift(stored, led) if not refusals else []
1283
+ return out, (0 if out["ok"] else 1)
1284
+
1285
+
1286
+ def _types_flags(p, verb: str) -> None:
1287
+ p.add_argument("--emit-script", dest="emit_script", metavar="DIR",
1288
+ help="method types/1, step 1: write the Lean programs DIR/source.lean and DIR/target.lean "
1289
+ "(DIR new, outside SRC and the target) and nothing else; run each in its checkout with "
1290
+ "`lake env lean --run` and keep its stdout" + (" (--ledger is not needed)" if verb == "ledger"
1291
+ else ""))
1292
+ p.add_argument("--from-output", dest="from_output", nargs="+", metavar="OUT",
1293
+ help="method types/1, step 2: the two programs' outputs (source and target, any order), read "
1294
+ "strictly and bound to this ledger's commits and programs")
1295
+
1296
+
1297
+ def add_parsers(sub, parser_cls, fmt) -> None:
1298
+ """The `ledger` and `recheck` subparsers of lean-pkg-extract (both read @ARGSFILE)."""
1299
+ led_ex = """\
1300
+ examples:
1301
+ lean-pkg-extract ledger --repo ~/paper --commit HEAD --target ~/newlib \\
1302
+ --from-module Paper/Bounds.lean:NewLib.Bounds --namespace Paper.Bounds=NewLib.Bounds \\
1303
+ --rename Paper.Bounds.main=NewLib.Bounds.main_bound --drop 'Paper.Bounds.scratch:exploration only' \\
1304
+ --ledger ~/ledgers/newlib-1.json
1305
+ lean-pkg-extract ledger @ledger-args.txt --json
1306
+ lean-pkg-extract ledger @ledger-args.txt --method types --emit-script ~/ledgers/newlib-types
1307
+ lean-pkg-extract ledger @ledger-args.txt --method types --from-output source.out target.out
1308
+
1309
+ @ARGSFILE: one argument per line; a line `--flag value` is the flag and the rest of the line (so a reason
1310
+ may hold spaces); blank lines and lines starting with # are skipped.
1311
+ exit codes: 0 every declaration accounted for (ledger written; with --emit-script: the programs written),
1312
+ 1 refused or failing (nothing written), 2 usage.
1313
+ docs: https://lean-pkg.github.io/lean-pkg/extract.html#declaration-level-extraction-ledger"""
1314
+ p = sub.add_parser("ledger", formatter_class=fmt, epilog=led_ex, fromfile_prefix_chars="@",
1315
+ help="record an extraction ledger: a hand-ported target compared, declaration by "
1316
+ "declaration, with the source at COMMIT",
1317
+ description="Compare the target modules at TARGET_COMMIT with the source modules at COMMIT, "
1318
+ "declaration by declaration (method text/1: comments stripped, the namespace "
1319
+ "and rename maps applied, normalized text hashed), and, when nothing fails, "
1320
+ f"write the ledger ({EXTRACT_LEDGER_SCHEMA}) to --ledger PATH, once. Reads "
1321
+ "git objects only; writes nothing else. --method types adds the elaborated "
1322
+ "types (types/1) in two steps, since lean-pkg runs no Lean: --emit-script "
1323
+ "writes two Lean programs, and --from-output reads what they printed.")
1324
+ p.add_argument("--repo", required=True, metavar="SRC", help="the source git repository (its top directory)")
1325
+ p.add_argument("--commit", required=True, metavar="COMMIT", help="the source commit; recorded as a full SHA")
1326
+ p.add_argument("--target", required=True, metavar="TDIR", help="the target git repository (its top directory)")
1327
+ p.add_argument("--target-commit", metavar="T", help="the target commit (default: HEAD)")
1328
+ p.add_argument("--from-module", action="append", required=True, metavar="SRC/Path.lean:New.Module",
1329
+ help="a source module and the target module it was ported to (repeatable, at least one)")
1330
+ p.add_argument("--namespace", action="append", metavar="OLD.Ns=NEW.Ns",
1331
+ help="a namespace prefix map (repeatable; the longest prefix wins)")
1332
+ p.add_argument("--rename", action="append", metavar="OLD.qual=NEW.qual",
1333
+ help="a declaration renamed, fully qualified (repeatable; takes precedence over --namespace)")
1334
+ p.add_argument("--drop", action="append", metavar="OLD.qual:REASON",
1335
+ help="a source declaration left out of the target on purpose, with a one-line reason")
1336
+ p.add_argument("--new", action="append", metavar="NEW.qual:REASON",
1337
+ help="a target declaration with no source counterpart, declared, with a one-line reason")
1338
+ p.add_argument("--allow-differs", action="append", dest="allow_differs", metavar="OLD.qual:REASON",
1339
+ help=f"a disclosed difference, counted as weakened ({CONTEXT_PREFIX}<source module> for a "
1340
+ f"module's context rows)")
1341
+ p.add_argument("--ledger", metavar="PATH",
1342
+ help="where to write the ledger: a new file outside SRC and outside the target (required, "
1343
+ "except with --emit-script)")
1344
+ p.add_argument("--method", choices=("text", "types"), default="text",
1345
+ help="the comparison method: text (text/1, the default) or types (types/1: also the "
1346
+ "elaborated types, through --emit-script and --from-output)")
1347
+ _types_flags(p, "ledger")
1348
+ p.add_argument("--json", dest="json_out", action="store_true",
1349
+ help="JSON on stdout: the ledger plus refusals, failures and written (and programs, with "
1350
+ "--emit-script)")
1351
+ rc_ex = """\
1352
+ examples:
1353
+ lean-pkg-extract recheck --ledger ~/ledgers/newlib-1.json --repo ~/paper --target ~/newlib
1354
+ lean-pkg-extract recheck --ledger ~/ledgers/newlib-1.json --repo ~/paper --target ~/newlib --commit main
1355
+ lean-pkg-extract recheck --ledger ~/ledgers/newlib-types.json --repo ~/paper --target ~/newlib \\
1356
+ --from-output source.out target.out
1357
+ lean-pkg-extract recheck --ledger ~/ledgers/newlib-1.json --repo ~/paper --target ~/newlib \\
1358
+ --public-summary ~/newlib/EXTRACTION.json
1359
+
1360
+ exit codes: 0 the ledger holds (at its commits: recomputed byte for byte; at other commits: nothing fails;
1361
+ with --emit-script: the programs written; with --public-summary: the summary written), 1 refused or
1362
+ failing (no summary written), 2 usage.
1363
+ docs: https://lean-pkg.github.io/lean-pkg/extract.html#rechecking-a-ledger"""
1364
+ r = sub.add_parser("recheck", formatter_class=fmt, epilog=rc_ex, fromfile_prefix_chars="@",
1365
+ help="re-verify an extraction ledger against the source and the target",
1366
+ description="Read a ledger strictly and recompute it from its own recorded map. At the "
1367
+ "recorded commits every field must match; at a newer --commit or "
1368
+ "--target-commit nothing may fail, and what changed is listed as drift. "
1369
+ "Writes nothing, except the public summary on request. A types/1 ledger needs --from-output (its programs' outputs "
1370
+ "at the commits rechecked; --emit-script writes the programs).")
1371
+ r.add_argument("--ledger", required=True, metavar="PATH", help=f"the ledger ({EXTRACT_LEDGER_SCHEMA})")
1372
+ r.add_argument("--repo", required=True, metavar="SRC", help="the source git repository (its top directory)")
1373
+ r.add_argument("--target", required=True, metavar="TDIR", help="the target git repository (its top directory)")
1374
+ r.add_argument("--commit", metavar="COMMIT", help="the source commit (default: the ledger's source.commit)")
1375
+ r.add_argument("--target-commit", metavar="T",
1376
+ help="the target commit (default: the ledger's target.commit; required when it is null)")
1377
+ _types_flags(r, "recheck")
1378
+ r.add_argument("--public-summary", dest="public_summary", metavar="PATH",
1379
+ help="when the recheck passes, also write its public summary (lean-pkg-extract-ledger-summary/1: "
1380
+ "target names, verdicts, hashes and totals, no source path or name) to PATH, a new file "
1381
+ "outside SRC (inside the target is allowed), after a public-safety scan")
1382
+ r.add_argument("--include-source-commit", dest="include_source_commit", action="store_true",
1383
+ help="with --public-summary: record the source commit in the summary (left out by default, "
1384
+ "since it may be private)")
1385
+ r.add_argument("--json", dest="json_out", action="store_true",
1386
+ help="JSON on stdout: the recomputed ledger plus refusals, failures, drift and written (and "
1387
+ "public_summary, with --public-summary)")
1388
+
1389
+
1390
+ def run(args) -> tuple[str, int]:
1391
+ """(stdout text, exit code) of `ledger` or `recheck`; ex.Usage propagates (exit 2)."""
1392
+ out, rc = (run_ledger if args.verb == "ledger" else run_recheck)(args)
1393
+ if args.json_out:
1394
+ return public_json(out), rc
1395
+ return render(args.verb, out) + "\n", rc
1396
+
1397
+
1398
+ def argsfile_requests_json(raw: list[str]) -> bool:
1399
+ """Whether an @ARGSFILE on the command line holds --json (so a usage error answers in JSON)."""
1400
+ for a in raw:
1401
+ if a.startswith("@") and len(a) > 1:
1402
+ try:
1403
+ text = pathlib.Path(os.path.expanduser(a[1:])).read_text(encoding="utf-8", errors="replace")
1404
+ except OSError:
1405
+ continue
1406
+ if any(line.strip() == "--json" for line in text.splitlines()):
1407
+ return True
1408
+ return False