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,677 @@
1
+ # lean-pkg palomar port-modules -- plan (and apply) the mechanical port to Lean's module system
2
+ """`lean-pkg palomar port-modules NAME [--dry-run | --write] [--agent A] [--json]`.
3
+
4
+ Palomar requires every tracked `.lean` file to begin with `module` (`palomar check`:
5
+ `source.module_required`). This command plans the mechanical part of that port for the package's
6
+ tracked `.lean` files at HEAD (git objects, never the working tree) and, with `--write`, applies it to
7
+ a clean package directory (`git status -- <package dir>`: a modified or untracked path inside it refuses;
8
+ paths elsewhere in the repository do not, since the port writes only inside the package; #392). It never
9
+ commits, never builds and never writes the registry. Untracked `.lean` files of the package are not read;
10
+ the report names them (`untracked_lean`), so "nothing to port" is never said over files it did not read.
11
+
12
+ Per file that is not module-headed yet:
13
+
14
+ - `module` is inserted as the first command, after any leading blanks and ordinary comments (a module
15
+ docstring `/-! -/` or a doc comment `/-- -/` is a command, so `module` goes before it);
16
+ - each header `import X` becomes `public import X`; `meta import X` becomes `public meta import X`;
17
+ `import all X`, `private ...` and `public ...` forms are kept (`public import all` is never written:
18
+ Lean rejects it);
19
+ - the body after the header (after module docstrings that follow the imports) is wrapped in
20
+ `public section` ... `end`; when the file leaves a `namespace`/`section` open at the end, no `end`
21
+ is appended (the section then closes at the end of the file) and the imbalance is reported.
22
+
23
+ A file already module-headed is skipped (so a second run is a no-op). A `prelude` file is refused with
24
+ a reason (it does not import `Init`; port it by hand). Not auto-fixed, reported as `review`:
25
+ definitions whose body other files unfold (`unfold`, `delta`, `simp [d]`, `rw [d]`, `d.eq_def`, or a
26
+ line that mentions `d` with `rfl`/`decide`), which need `@[expose]`; `private` declarations (a private
27
+ name in a public statement is an unknown identifier in a module); `#eval`, `native_decide` and
28
+ `initialize`, whose code from other modules needs a `meta import`; imports of a module that is not
29
+ module-headed (a module cannot import a non-module); scope imbalance.
30
+
31
+ Verified on Lean v4.35.0-rc2 (see tests/test_port_modules.py and docs/comparator.md, "The module
32
+ header"). Excluded: `.lake/`, `lake-packages/`, nested Lake projects (a directory with its own
33
+ lakefile) and `path` dependencies of lake-manifest.json; `lakefile.lean` is exempt."""
34
+
35
+ from __future__ import annotations
36
+
37
+ import difflib
38
+ import json
39
+ import os
40
+ import pathlib
41
+ import re
42
+ import tempfile
43
+
44
+ from . import core
45
+ from . import lean_scan
46
+ from .palomar_check import Tree, has_module_header
47
+
48
+ EXCLUDED_DIRS = (".git", ".lake", "lake-packages")
49
+ EXEMPT_FILES = ("lakefile.lean",)
50
+ LAKEFILES = ("lakefile.lean", "lakefile.toml")
51
+ _HEADER_MODIFIERS = ("public", "private", "meta")
52
+ _NAME = re.compile(r"(?:«[^»\n]*»|[^\s«».\-/()\[\]{}:,]+)(?:\.(?:«[^»\n]*»|[^\s«».\-/()\[\]{}:,]+))*")
53
+ _SCOPE = re.compile(r"(?<![\w.'])(namespace|section|mutual|end)(?![\w.'!?])")
54
+ _REWRITE_TACTICS = r"(?:simp|simp_all|dsimp|simp_rw|rw|rwa|erw|rewrite|nth_rewrite|nth_rw|norm_num|field_simp|" \
55
+ r"simp_arith|unfold_let)\??(?:\s+only)?"
56
+ _DEFEQ = re.compile(r"(?<![\w.'])(rfl|decide|native_decide|show|change)(?![\w.'])")
57
+ _EVAL = re.compile(r"(?m)^\s*#eval\b|(?<![\w.'])native_decide(?![\w.'])")
58
+ _INIT = re.compile(r"(?m)^\s*(?:@\[[^\]]*\]\s*)?(?:(?:private|public|meta)\s+)*(?:builtin_)?initialize\b")
59
+ _TOKEN = re.compile(r"(?:«[^»\n]*»|[^\W\d][\w'!?]*)(?:\.(?:«[^»\n]*»|[^\W\d][\w'!?]*))*")
60
+ REVIEW_CAP = 5 # reference lines listed per definition
61
+
62
+
63
+ # ------------------------------------------------------------------------------------------- scanning
64
+
65
+ def _skip_plain(text: str, i: int) -> int:
66
+ """Past blanks (space, CR, LF) and ordinary comments, as Lean's header parser reads them (a plain
67
+ `/-` opener reads one character past it; `/--` and `/-!` are commands and stop the skip)."""
68
+ n = len(text)
69
+ while i < n:
70
+ c = text[i]
71
+ if c in " \r\n\t":
72
+ i += 1
73
+ elif text.startswith("--", i):
74
+ j = text.find("\n", i + 2)
75
+ i = n if j < 0 else j + 1
76
+ elif text.startswith("/-", i) and not text.startswith(("/--", "/-!"), i):
77
+ i += 3
78
+ depth = 1
79
+ while depth and i < n:
80
+ if text.startswith("/-", i):
81
+ depth, i = depth + 1, i + 2
82
+ elif text.startswith("-/", i):
83
+ depth, i = depth - 1, i + 2
84
+ else:
85
+ i += 1
86
+ if depth:
87
+ return -1 # an unterminated comment
88
+ else:
89
+ break
90
+ return i
91
+
92
+
93
+ def _block_end(text: str, i: int) -> int:
94
+ """The index after the (nested) block comment opening at text[i]; -1 when unterminated."""
95
+ depth, j, n = 1, i + 2, len(text)
96
+ while j < n and depth:
97
+ if text.startswith("/-", j):
98
+ depth, j = depth + 1, j + 2
99
+ elif text.startswith("-/", j):
100
+ depth, j = depth - 1, j + 2
101
+ else:
102
+ j += 1
103
+ return j if not depth else -1
104
+
105
+
106
+ def parse_header(text: str) -> dict:
107
+ """{first, imports[{start, end, mods, all, name}], end, prelude}: `first` is where `module` goes,
108
+ `end` the index after the last header command (== first when there is no import)."""
109
+ first = _skip_plain(text, 0)
110
+ if first < 0:
111
+ return {"error": "an unterminated block comment before the first command"}
112
+ imports, pos, last_end, prelude = [], first, first, False
113
+ m0 = re.compile(r"module(?![\w.'!?])").match(text, first)
114
+ if m0: # an already module-headed file (re-read after a port)
115
+ pos = last_end = m0.end()
116
+ while True:
117
+ p = _skip_plain(text, pos)
118
+ if p < 0:
119
+ break
120
+ start, mods, q = p, [], p
121
+ while True:
122
+ m = re.compile(r"[A-Za-z_]+").match(text, q)
123
+ if not m or m.group(0) not in _HEADER_MODIFIERS:
124
+ break
125
+ mods.append(m.group(0))
126
+ q = _skip_plain(text, m.end())
127
+ if q < 0:
128
+ break
129
+ if q < 0:
130
+ break
131
+ m = re.compile(r"[A-Za-z_]+(?![\w.'])").match(text, q)
132
+ if m and m.group(0) == "prelude" and not mods and not imports:
133
+ prelude = True
134
+ pos = last_end = m.end()
135
+ continue
136
+ if not m or m.group(0) != "import":
137
+ break
138
+ q = _skip_plain(text, m.end())
139
+ is_all = False
140
+ m2 = re.compile(r"all(?![\w.'])").match(text, q) if q >= 0 else None
141
+ if m2:
142
+ is_all, q = True, _skip_plain(text, m2.end())
143
+ m3 = _NAME.match(text, q) if q >= 0 else None
144
+ if not m3:
145
+ break
146
+ imports.append({"start": start, "end": m3.end(), "mods": mods, "all": is_all, "name": m3.group(0)})
147
+ pos = last_end = m3.end()
148
+ return {"first": first, "imports": imports, "end": last_end, "prelude": prelude}
149
+
150
+
151
+ def scope_balance(text: str) -> tuple[list[str], int]:
152
+ """(scopes still open at the end of the file, count of `end` with no open scope), over the text with
153
+ comments and strings blanked. A heuristic: `namespace`/`section`/`mutual` open, `end` closes."""
154
+ masked, _docs = lean_scan._mask(text)
155
+ stack: list[str] = []
156
+ extra = 0
157
+ for m in _SCOPE.finditer(masked):
158
+ w = m.group(1)
159
+ eol = masked.find("\n", m.end())
160
+ rest = masked[m.end():eol if eol >= 0 else len(masked)]
161
+ if w == "end":
162
+ if stack:
163
+ stack.pop()
164
+ else:
165
+ extra += 1
166
+ elif w == "namespace":
167
+ nm = rest.split()
168
+ stack.append("namespace " + (nm[0] if nm else "?"))
169
+ else:
170
+ nm = rest.split()
171
+ stack.append(w + (" " + nm[0] if w == "section" and nm and _NAME.fullmatch(nm[0]) else ""))
172
+ return stack, extra
173
+
174
+
175
+ def _line_of(text: str, pos: int) -> int:
176
+ return text.count("\n", 0, pos) + 1
177
+
178
+
179
+ # ------------------------------------------------------------------------------------------ the port
180
+
181
+ def port_text(text: str) -> dict:
182
+ """The port of one non-module file: {status port|refused, text, reason, edits[], reviews[]}."""
183
+ bom = text.startswith("")
184
+ if bom:
185
+ text = text[1:]
186
+ nl = "\r\n" if "\r\n" in text else "\n"
187
+ h = parse_header(text)
188
+ if "error" in h:
189
+ return {"status": "refused", "reason": h["error"], "edits": [], "reviews": []}
190
+ if h["prelude"]:
191
+ return {"status": "refused", "edits": [], "reviews": [],
192
+ "reason": "a `prelude` file (it does not import Init): port it by hand, `module` before "
193
+ "`prelude` (Lean v4.35.0-rc2 rejects `prelude` then `module`), then check its imports"}
194
+ inserts: list[tuple[int, int, str]] = [] # (pos, order, text)
195
+ edits: list[str] = []
196
+ inserts.append((h["first"], 0, "module" + nl + nl))
197
+ edits.append("insert `module` as the first command")
198
+ rewritten = 0
199
+ for imp in h["imports"]:
200
+ if "public" in imp["mods"] or "private" in imp["mods"] or imp["all"]:
201
+ continue # kept as written (never `public import all`)
202
+ inserts.append((imp["start"], 1, "public "))
203
+ rewritten += 1
204
+ if rewritten:
205
+ edits.append(f"{rewritten} import(s) -> public import")
206
+ kept = len(h["imports"]) - rewritten
207
+ if kept:
208
+ edits.append(f"{kept} import(s) kept as written (`import all`, `private` or `public` forms)")
209
+ # where `public section` goes: after the imports and any module docstrings that follow them
210
+ anchor = h["end"] if h["imports"] else None
211
+ q, n = h["end"], len(text)
212
+ while q < n:
213
+ p = _skip_plain(text, q)
214
+ if p < 0 or p >= n:
215
+ break
216
+ if text.startswith("/-!", p):
217
+ e = _block_end(text, p)
218
+ if e < 0:
219
+ break
220
+ anchor, q = e, e
221
+ continue
222
+ break
223
+ if anchor is None:
224
+ inserts.append((h["first"], 2, "public section" + nl + nl))
225
+ else:
226
+ eol = text.find("\n", anchor)
227
+ tail = text[anchor:eol if eol >= 0 else n]
228
+ if tail.strip() and not tail.strip().startswith("--"):
229
+ inserts.append((anchor, 2, nl + nl + "public section" + nl + nl))
230
+ elif eol < 0:
231
+ inserts.append((n, 2, nl + nl + "public section" + nl))
232
+ else:
233
+ gap = "" if text.startswith(("\n", "\r\n"), eol + 1) or eol + 1 >= n else nl
234
+ inserts.append((eol + 1, 2, nl + "public section" + nl + gap))
235
+ reviews: list[dict] = []
236
+ stack, extra = scope_balance(text[h["end"]:])
237
+ if stack or extra:
238
+ what = []
239
+ if stack:
240
+ what.append(f"{len(stack)} scope(s) still open at the end of the file ({', '.join(stack)})")
241
+ if extra:
242
+ what.append(f"{extra} `end` with no open scope")
243
+ reviews.append({"code": "scope-balance", "line": None,
244
+ "detail": "; ".join(what) + ": no trailing `end` appended (`public section` closes at "
245
+ "the end of the file); balance the scopes by hand if you want one"})
246
+ edits.append("wrap the body in `public section` (no trailing `end`: scopes unbalanced)")
247
+ else:
248
+ body_end = text.rstrip(" \r\n\t")
249
+ inserts.append((len(text), 3, ("" if text.endswith("\n") else nl) + nl + "end" + nl
250
+ if body_end else "end" + nl))
251
+ edits.append("wrap the body in `public section` ... `end`")
252
+ out = text
253
+ for pos, _o, ins in sorted(inserts, key=lambda t: (t[0], t[1]), reverse=True):
254
+ out = out[:pos] + ins + out[pos:]
255
+ if bom:
256
+ edits.append("remove the byte-order mark (Lean's header parser does not skip it)")
257
+ if not has_module_header(out):
258
+ return {"status": "refused", "edits": [], "reviews": [],
259
+ "reason": "the port did not produce a module header (report this as a lean-pkg bug)"}
260
+ return {"status": "port", "text": out, "edits": edits, "reviews": reviews}
261
+
262
+
263
+ def file_reviews(text: str) -> list[dict]:
264
+ """Per-file review items that do not depend on other files."""
265
+ out = []
266
+ masked, _docs = lean_scan._mask(text)
267
+ for line, kw, qual, _doc, src, _w in lean_scan.declarations(text):
268
+ head = src.split(kw, 1)[0] if kw in src else src
269
+ if re.search(r"(?<![\w.])private(?![\w.])", head):
270
+ out.append({"code": "private", "line": line,
271
+ "detail": f"private {kw} {qual}: inside a module a private name is not visible in a "
272
+ f"public statement (`Unknown identifier`); fine when only proofs use it"})
273
+ for m in _EVAL.finditer(masked):
274
+ what = "#eval" if "#eval" in m.group(0) else "native_decide"
275
+ out.append({"code": "meta", "line": _line_of(text, m.start()),
276
+ "detail": f"{what}: evaluating a definition from another module needs `public meta import` "
277
+ f"of it (Lean: `Invalid meta definition ... not accessible here`)"})
278
+ for m in _INIT.finditer(masked):
279
+ out.append({"code": "meta", "line": _line_of(text, m.start()),
280
+ "detail": "initialize: code it runs from other modules needs a `meta import`; review"})
281
+ return out
282
+
283
+
284
+ def _ref_kinds(masked_line: str, comp: str, qual: str) -> str | None:
285
+ """How a masked source line uses the definition (last component `comp`): "unfold", "defeq" or None."""
286
+ word = r"(?<![\w.'])(?:" + re.escape(qual) + "|" + re.escape(comp) + r")(?![\w'!?])"
287
+ if not re.search(word, masked_line):
288
+ return None
289
+ if re.search(word + r"\.(?:eq_def|eq_unfold|eq_\d+)\b", masked_line):
290
+ return "unfold"
291
+ if re.search(r"(?<![\w.'])(?:unfold|delta)\s+(?:[\w.'«»]+\s+)*?" + word, masked_line):
292
+ return "unfold"
293
+ if re.search(r"(?<![\w.'])" + _REWRITE_TACTICS + r"\s*\[[^\]]*" + word, masked_line):
294
+ return "unfold"
295
+ if _DEFEQ.search(masked_line):
296
+ return "defeq"
297
+ return None
298
+
299
+
300
+ def expose_reviews(files: dict[str, str]) -> list[dict]:
301
+ """Definitions (keyword `def`, not `@[expose]`) another file unfolds: [{decl, file, line, refs[]}].
302
+ `abbrev` and instances are exposed already (checked on v4.35.0-rc2); a file that has
303
+ `@[expose] public section` exposes every definition in it."""
304
+ defs = []
305
+ masked = {p: lean_scan._mask(t)[0] for p, t in files.items()}
306
+ for path, text in files.items():
307
+ whole = "@[expose] public section" in masked[path]
308
+ lines = text.splitlines()
309
+ for line, kw, qual, _doc, src, written in lean_scan.declarations(text):
310
+ if kw != "def" or whole:
311
+ continue
312
+ prev = lines[line - 2] if line >= 2 else ""
313
+ if "expose" in src.split("def", 1)[0] or re.search(r"@\[[^\]]*\bexpose\b", prev):
314
+ continue
315
+ defs.append((path, line, qual, lean_scan.last_component(written)))
316
+ by_comp: dict[str, list[int]] = {}
317
+ for k, (_p, _l, _q, comp) in enumerate(defs):
318
+ by_comp.setdefault(comp, []).append(k)
319
+ found: list[list[dict]] = [[] for _ in defs]
320
+ if by_comp:
321
+ for other, mt in masked.items(): # one pass per line: tokens against the definition names
322
+ for i, ml in enumerate(mt.split("\n"), 1):
323
+ hits = {c for tok in _TOKEN.findall(ml) for c in tok.split(".") if c in by_comp}
324
+ for c in hits:
325
+ for k in by_comp[c]:
326
+ if defs[k][0] == other:
327
+ continue # the defining module sees its own bodies
328
+ how = _ref_kinds(ml, c, defs[k][2])
329
+ if how:
330
+ found[k].append({"file": other, "line": i, "how": how})
331
+ out = []
332
+ for (path, line, qual, comp), refs in zip(defs, found, strict=False):
333
+ if refs:
334
+ strong = any(r["how"] == "unfold" for r in refs)
335
+ out.append({"code": "expose", "decl": qual, "file": path, "line": line, "likely": strong,
336
+ "refs": refs[:REVIEW_CAP], "ref_count": len(refs),
337
+ "detail": f"def {qual} is {'unfolded' if strong else 'possibly reduced (rfl/decide)'} in "
338
+ f"{len({r['file'] for r in refs})} other file(s): add `@[expose]` before `def` "
339
+ f"(or `@[expose] public section` in {path}); without it `unfold`, `rfl`, "
340
+ f"`simp [{comp}]` and `decide` fail across modules"})
341
+ return out
342
+
343
+
344
+ # ---------------------------------------------------------------------------------------- the package
345
+
346
+ def _excluded_dirs(tree: Tree, prefix: str, repo: pathlib.Path) -> list[str]:
347
+ """Package-relative directories that are other Lake projects: a nested lakefile, or a `path`
348
+ dependency of lake-manifest.json inside the package."""
349
+ out = set()
350
+ for p in tree.entries:
351
+ if not p.startswith(prefix):
352
+ continue
353
+ rel = p[len(prefix):]
354
+ if "/" in rel and rel.rsplit("/", 1)[1] in LAKEFILES:
355
+ out.add(rel.rsplit("/", 1)[0])
356
+ blob = tree.blob(prefix + "lake-manifest.json")
357
+ if blob:
358
+ try:
359
+ doc = json.loads(blob)
360
+ except ValueError:
361
+ doc = {}
362
+ for pk in doc.get("packages") or [] if isinstance(doc, dict) else []:
363
+ if isinstance(pk, dict) and pk.get("type") == "path" and isinstance(pk.get("dir"), str):
364
+ d = os.path.normpath(pk["dir"]).replace(os.sep, "/")
365
+ if d not in (".", "") and not d.startswith(".."):
366
+ out.add(d)
367
+ return sorted(out)
368
+
369
+
370
+ def _module_file(mod: str) -> str:
371
+ return "/".join(lean_scan.split_name(mod) or [mod]).replace("«", "").replace("»", "") + ".lean"
372
+
373
+
374
+ def _is_excluded(rel: str, vendored: list[str]) -> bool:
375
+ """A package-relative path under .git/, .lake/, lake-packages/ or another Lake project."""
376
+ return bool(set(rel.split("/")[:-1]) & set(EXCLUDED_DIRS)) or any(rel.startswith(d + "/") for d in vendored)
377
+
378
+
379
+ def _package_lean(tree: Tree, prefix: str, vendored: list[str]) -> tuple[list[str], list[str], int, list[str]]:
380
+ """(the package's .lean blobs, excluded .lean paths, .lean files outside the package, symlinks), all
381
+ package-relative, from the tree at HEAD."""
382
+ lean, excluded, outside, links = [], [], 0, []
383
+ for p, (mode, kind, _sha) in sorted(tree.entries.items()):
384
+ if not p.endswith(".lean"):
385
+ continue
386
+ if not p.startswith(prefix):
387
+ outside += 1
388
+ continue
389
+ rel = p[len(prefix):]
390
+ if _is_excluded(rel, vendored):
391
+ excluded.append(rel)
392
+ continue
393
+ if rel.split("/")[-1] in EXEMPT_FILES:
394
+ continue
395
+ if mode == "120000":
396
+ links.append(rel)
397
+ continue
398
+ if kind == "blob":
399
+ lean.append(rel)
400
+ return lean, excluded, outside, links
401
+
402
+
403
+ def untracked_lean(repo: pathlib.Path, vendored: list[str]) -> list[str]:
404
+ """The package's untracked, not ignored `.lean` files (package-relative; the plan's exclusions apply,
405
+ and a directory with its own untracked lakefile is another Lake project): port-modules reads HEAD, so
406
+ these are not read (#392). [] when the status cannot be read."""
407
+ p = core.git(repo, "ls-files", "-z", "--others", "--exclude-standard", "--", ".")
408
+ if p.returncode != 0:
409
+ return []
410
+ paths = [x for x in p.stdout.split("\0") if x]
411
+ nested = sorted({x.rsplit("/", 1)[0] for x in paths if "/" in x and x.rsplit("/", 1)[1] in LAKEFILES})
412
+ return sorted(x for x in paths if x.endswith(".lean") and x.split("/")[-1] not in EXEMPT_FILES
413
+ and not _is_excluded(x, [*vendored, *nested]))
414
+
415
+
416
+ def non_module_imports(repo: pathlib.Path) -> list[dict]:
417
+ """At HEAD: each import, in a module-headed `.lean` file of the package, of a package file that is not
418
+ module-headed (Lean: `cannot import non-module`; `palomar port-modules` ports the target). The same file
419
+ set and header parser as the plan. [{file, line, module, target}], package-relative paths (#392)."""
420
+ head = core.git_head(repo)
421
+ if head is None:
422
+ raise core.Fail(f"{repo} is not a git checkout with a commit")
423
+ tree = Tree(repo, head)
424
+ prefix = tree.prefix
425
+ lean, _excluded, _outside, _links = _package_lean(tree, prefix, _excluded_dirs(tree, prefix, repo))
426
+ blobs = tree.blobs([prefix + r for r in lean])
427
+ texts = {}
428
+ for rel in lean:
429
+ try:
430
+ texts[rel] = blobs.get(prefix + rel, b"").decode("utf-8")
431
+ except UnicodeDecodeError:
432
+ continue
433
+ out = []
434
+ for rel, text in sorted(texts.items()):
435
+ if not has_module_header(text):
436
+ continue
437
+ for imp in parse_header(text).get("imports", []):
438
+ target = _module_file(imp["name"])
439
+ if target in texts and not has_module_header(texts[target]):
440
+ out.append({"file": rel, "line": _line_of(text, imp["start"]), "module": imp["name"],
441
+ "target": target})
442
+ return out
443
+
444
+
445
+ def plan(pkg: dict, repo: pathlib.Path) -> dict:
446
+ name = pkg["name"]
447
+ head = core.git_head(repo)
448
+ if head is None:
449
+ raise core.Fail(f"{name}: {repo} is not a git checkout with a commit")
450
+ tree = Tree(repo, head)
451
+ prefix = tree.prefix
452
+ vendored = _excluded_dirs(tree, prefix, repo)
453
+ lean, excluded, outside, links = _package_lean(tree, prefix, vendored)
454
+ blobs = tree.blobs([prefix + r for r in lean])
455
+ files, texts, new_texts = [], {}, {}
456
+ for rel in lean:
457
+ raw = blobs.get(prefix + rel, b"")
458
+ try:
459
+ text = raw.decode("utf-8")
460
+ except UnicodeDecodeError:
461
+ files.append({"path": rel, "action": "refused", "reason": "not UTF-8", "edits": [], "reviews": []})
462
+ continue
463
+ texts[rel] = text
464
+ if has_module_header(text):
465
+ files.append({"path": rel, "action": "skip", "reason": "already module-headed", "edits": [],
466
+ "reviews": []})
467
+ continue
468
+ r = port_text(text)
469
+ entry = {"path": rel, "action": r["status"], "reason": r.get("reason"), "edits": r["edits"],
470
+ "reviews": r["reviews"]}
471
+ if r["status"] == "port":
472
+ new_texts[rel] = r["text"]
473
+ entry["reviews"] = r["reviews"] + file_reviews(r["text"]) # lines of the ported file
474
+ files.append(entry)
475
+ for rel in links:
476
+ files.append({"path": rel, "action": "refused", "reason": "a symlink (Palomar rejects symlinked .lean "
477
+ "files; replace it with the file)", "edits": [], "reviews": []})
478
+ files.sort(key=lambda f: f["path"])
479
+ # imports of a module that will not be module-headed
480
+ deps_root = repo / ".lake" / "packages"
481
+ by_path = {f["path"]: f for f in files}
482
+ for rel, new in new_texts.items():
483
+ for imp in parse_header(new)["imports"]:
484
+ target = _module_file(imp["name"])
485
+ if target in by_path:
486
+ if by_path[target]["action"] == "refused":
487
+ by_path[rel]["reviews"].append({
488
+ "code": "imports-non-module", "line": _line_of(new, imp["start"]),
489
+ "detail": f"imports {imp['name']}, which stays non-module ({by_path[target]['reason']}); "
490
+ f"a module cannot import a non-module: port it first"})
491
+ continue
492
+ if target in excluded:
493
+ by_path[rel]["reviews"].append({
494
+ "code": "imports-non-module", "line": _line_of(new, imp["start"]),
495
+ "detail": f"imports {imp['name']} from an excluded directory; it must be module-headed too"})
496
+ continue
497
+ if deps_root.is_dir():
498
+ for dep in sorted(deps_root.iterdir()):
499
+ f = dep / target
500
+ if f.is_file():
501
+ try:
502
+ dep_text = f.read_text(encoding="utf-8")
503
+ except (OSError, UnicodeDecodeError):
504
+ break
505
+ if not has_module_header(dep_text):
506
+ by_path[rel]["reviews"].append({
507
+ "code": "imports-non-module", "line": _line_of(new, imp["start"]),
508
+ "detail": f"imports {imp['name']} from the dependency {dep.name}, which is not "
509
+ f"module-headed: a module cannot import it (update the dependency)"})
510
+ break
511
+ ported_view = {rel: new_texts.get(rel, t) for rel, t in texts.items()}
512
+ expose = expose_reviews(ported_view)
513
+ for e in expose:
514
+ if e["file"] in by_path:
515
+ by_path[e["file"]]["reviews"].append({k: e[k] for k in ("code", "line", "detail", "decl", "likely",
516
+ "refs", "ref_count")})
517
+ for f in files:
518
+ f["reviews"].sort(key=lambda r: (r.get("line") or 0, r["code"]))
519
+ diff = "".join(
520
+ "".join(difflib.unified_diff(texts[rel].splitlines(keepends=True), new_texts[rel].splitlines(keepends=True),
521
+ fromfile=f"a/{prefix}{rel}", tofile=f"b/{prefix}{rel}"))
522
+ for rel in sorted(new_texts))
523
+ counts = {a: sum(f["action"] == a for f in files) for a in ("port", "skip", "refused")}
524
+ counts["review"] = sum(len(f["reviews"]) for f in files)
525
+ return {"commit": head, "project_path": prefix.rstrip("/") or ".", "files": files, "counts": counts,
526
+ "expose": expose, "excluded": excluded, "vendored_dirs": vendored, "outside_package": outside,
527
+ "diff": diff, "untracked_lean": untracked_lean(repo, vendored), "_new": new_texts}
528
+
529
+
530
+ # ------------------------------------------------------------------------------------------- writing
531
+
532
+ def dirty_paths(repo: pathlib.Path, extra: list[str] | None = None) -> list[str]:
533
+ """Modified, staged or untracked paths in the package directory `repo` (and `extra`, package-relative
534
+ paths it would write, inside it anyway), as `git status --porcelain` prints them (repository-relative).
535
+ Paths elsewhere in the repository do not count: the port writes only inside the package (#392)."""
536
+ p = core.git(repo, "status", "--porcelain", "--untracked-files=normal", "--", ".", *(extra or []))
537
+ if p.returncode != 0:
538
+ raise core.Fail(f"cannot read the working-tree status of {repo}")
539
+ return [ln[3:] for ln in p.stdout.splitlines() if ln.strip()]
540
+
541
+
542
+ def _write_atomic(path: pathlib.Path, text: str) -> None:
543
+ mode = path.stat().st_mode & 0o7777 if path.exists() else 0o644
544
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".lean-pkg-port-")
545
+ try:
546
+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh:
547
+ fh.write(text)
548
+ os.chmod(tmp, mode)
549
+ os.replace(tmp, path)
550
+ except BaseException:
551
+ if os.path.exists(tmp):
552
+ os.unlink(tmp)
553
+ raise
554
+
555
+
556
+ def follow_ups(pkg: dict, name: str, written: int, expose: list[dict]) -> list[str]:
557
+ out = ["lake build # in the checkout: the port changes every ported file's interface"]
558
+ if expose:
559
+ out.append(f"review the {len(expose)} `@[expose]` candidate(s) above, then lake build again")
560
+ out.append(f"lean-pkg palomar check {name} # after you commit: it reads git objects, not the working tree")
561
+ out.append("git diff; commit the port yourself (lean-pkg never commits it)")
562
+ if (pkg.get("gate") or {}).get("receipt"):
563
+ out.append(f"{name} is gated: the sources changed, so the gate receipt no longer binds the new commit; "
564
+ f"run a new gate (and comparator receipt) at it")
565
+ return out
566
+
567
+
568
+ def run_port(reg: dict, name: str, write: bool, agent: str | None) -> tuple[list[str], dict, int]:
569
+ pkg = core.get_pkg(reg, name)
570
+ repo = core.repo_path(pkg)
571
+ if not repo.is_dir():
572
+ raise core.Fail(f"{name}: local_path does not exist: {repo}")
573
+ rep = plan(pkg, repo)
574
+ new = rep.pop("_new")
575
+ c = rep["counts"]
576
+ refused = [f for f in rep["files"] if f["action"] == "refused"]
577
+ scope = rep["project_path"]
578
+ payload = {"ok": not refused, "name": name, "dry_run": not write, "written": [], **rep, "clean_scope": scope,
579
+ "follow_ups": []}
580
+ untracked = rep["untracked_lean"]
581
+ if write:
582
+ if refused:
583
+ raise core.Fail(f"{name}: {len(refused)} file(s) cannot be ported mechanically; nothing written:\n"
584
+ + "\n".join(f" {f['path']}: {f['reason']}" for f in refused))
585
+ if new:
586
+ core.refuse_invalid_lease(name, pkg.get("lease"))
587
+ lease = pkg.get("lease")
588
+ if core.lease_live(lease, core.dt.datetime.now(core.dt.timezone.utc)) and agent != lease.get("agent"):
589
+ raise core.Fail(f"{name}: lease held by {lease.get('agent')} — pass --agent {lease.get('agent')}; "
590
+ f"nothing written")
591
+ dirty = dirty_paths(repo, sorted(new))
592
+ if dirty:
593
+ where = ("the working tree of " + str(repo) if scope == "." else
594
+ f"the package directory {scope}/ of the repository at {repo}")
595
+ raise core.Fail(f"{name}: {where} is not clean ({len(dirty)} path(s); checked: {scope}); "
596
+ f"--write needs it clean so the port is the only change there; commit or stash "
597
+ f"first, nothing written:\n" + "\n".join(f" {p}" for p in dirty[:20]))
598
+ if core.git_head(repo) != rep["commit"]:
599
+ raise core.Fail(f"{name}: HEAD moved during the plan; nothing written (run again)")
600
+ for rel in sorted(new):
601
+ _write_atomic(repo / rel, new[rel])
602
+ payload["written"].append(rel)
603
+ payload["follow_ups"] = follow_ups(pkg, name, len(new), rep["expose"]) if new else []
604
+ head = (f"{name}: port-modules at {rep['commit'][:12]}: {c['port']} file(s) to port, {c['skip']} already "
605
+ f"module-headed, {c['refused']} refused, {c['review']} review item(s)")
606
+ idle = " — nothing to port at HEAD" + (f" ({len(untracked)} untracked .lean file(s) not read)" if untracked
607
+ else "")
608
+ if write:
609
+ head += f" — {len(payload['written'])} file(s) written (not committed)" if new else idle
610
+ else:
611
+ head += " (dry run: nothing written)" if new or refused else idle + " (dry run)"
612
+ lines = [head]
613
+ if untracked:
614
+ lines.append(f" {len(untracked)} untracked .lean file(s) under {scope}/ not read (port-modules reads "
615
+ f"HEAD): commit them first")
616
+ lines += [f" {u}" for u in untracked[:20]] + ([f" ... and {len(untracked) - 20} more"]
617
+ if len(untracked) > 20 else [])
618
+ mark = {"port": "PORT", "skip": "skip", "refused": "✗"}
619
+ for f in rep["files"]:
620
+ if f["action"] == "skip" and not f["reviews"]:
621
+ continue
622
+ lines.append(f" {mark[f['action']]:4} {f['path']}" + (f": {f['reason']}" if f.get("reason") else ""))
623
+ for e in f["edits"]:
624
+ lines.append(f" - {e}")
625
+ for r in f["reviews"]:
626
+ at = f":{r['line']}" if r.get("line") else ""
627
+ lines.append(f" review [{r['code']}]{at} {r['detail']}")
628
+ for ref in r.get("refs") or []:
629
+ lines.append(f" used at {ref['file']}:{ref['line']} ({ref['how']})")
630
+ if c["skip"]:
631
+ lines.append(f" ({c['skip']} already module-headed file(s) skipped)")
632
+ if rep["excluded"]:
633
+ lines.append(f" excluded (not this package's sources): {len(rep['excluded'])} .lean file(s) under "
634
+ + ", ".join(sorted({*(d + '/' for d in rep['vendored_dirs']),
635
+ *(p.split('/')[0] + '/' for p in rep['excluded']
636
+ if p.split('/')[0] in EXCLUDED_DIRS)})))
637
+ if rep["outside_package"]:
638
+ lines.append(f" {rep['outside_package']} .lean file(s) of the repository lie outside the package and are "
639
+ f"not touched; palomar check judges the whole repository")
640
+ if rep["diff"] and not write:
641
+ lines.append("")
642
+ lines.append(rep["diff"].rstrip("\n"))
643
+ if payload["follow_ups"]:
644
+ lines.append("next:")
645
+ lines += [f" {s}" for s in payload["follow_ups"]]
646
+ elif not write and new:
647
+ lines.append(f"next: lean-pkg palomar port-modules {name} --write (a clean package directory, {scope}/; "
648
+ f"never commits)")
649
+ if len(lines) > 12:
650
+ lines.append(head)
651
+ return lines, payload, 0 if not refused else 1
652
+
653
+
654
+ def cmd_port_modules(args) -> int:
655
+ reg = core.load_registry(core.registry_path(args))
656
+ lines, payload, rc = run_port(reg, args.name, bool(args.write), args.agent)
657
+ if getattr(args, "json_out", False):
658
+ core.print_json(payload)
659
+ else:
660
+ print("\n".join(lines))
661
+ return rc
662
+
663
+
664
+ def add_parser(psub, add_json) -> None:
665
+ p = psub.add_parser("port-modules", help="plan (dry run, default) or --write the mechanical port of the "
666
+ "package's tracked .lean files to Lean's module system; never commits")
667
+ p.add_argument("name")
668
+ g = p.add_mutually_exclusive_group()
669
+ g.add_argument("--dry-run", action="store_true", help="the default: print the per-file plan and the unified "
670
+ "diff; write nothing")
671
+ g.add_argument("--write", action="store_true", help="apply the plan to a clean package directory (a dirty or "
672
+ "untracked path inside it is refused; paths elsewhere in "
673
+ "the repository are not checked); never commits, never "
674
+ "writes the registry")
675
+ p.add_argument("--agent", default=None, help="with --write: the lease holder, when the package is leased")
676
+ add_json(p)
677
+ p.set_defaults(fn=cmd_port_modules, palomar_fn="port-modules")