lean-pkg 0.25.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lean_pkg/__init__.py +3 -0
- lean_pkg/adapters/__init__.py +148 -0
- lean_pkg/adapters/github.py +65 -0
- lean_pkg/adapters/leansearch.py +68 -0
- lean_pkg/adapters/loogle.py +45 -0
- lean_pkg/adapters/palomar.py +170 -0
- lean_pkg/adapters/reservoir.py +127 -0
- lean_pkg/anchor.py +678 -0
- lean_pkg/audit.py +716 -0
- lean_pkg/binding_file.py +446 -0
- lean_pkg/blueprint.py +213 -0
- lean_pkg/build_scope.py +282 -0
- lean_pkg/ci_github.py +917 -0
- lean_pkg/claim_axioms.py +421 -0
- lean_pkg/claims.py +1155 -0
- lean_pkg/claims_mark.py +197 -0
- lean_pkg/cli.py +5208 -0
- lean_pkg/cli_parser.py +768 -0
- lean_pkg/command_tree.py +615 -0
- lean_pkg/comparator_config.py +990 -0
- lean_pkg/comparator_contracts.py +382 -0
- lean_pkg/comparator_receipt.py +2854 -0
- lean_pkg/comparator_stage.py +623 -0
- lean_pkg/comparator_types.py +830 -0
- lean_pkg/container.py +172 -0
- lean_pkg/core.py +1570 -0
- lean_pkg/coverage.py +1278 -0
- lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
- lean_pkg/data/toolchain-advisories.yaml +77 -0
- lean_pkg/data/upgrade-breaking.yaml +20 -0
- lean_pkg/data/verify-workflow-pins.yaml +14 -0
- lean_pkg/deps_closure.py +512 -0
- lean_pkg/deps_fill.py +445 -0
- lean_pkg/dup_constants.py +448 -0
- lean_pkg/exercise.py +828 -0
- lean_pkg/exercise_forbid.py +288 -0
- lean_pkg/export_paths.py +77 -0
- lean_pkg/extract.py +1172 -0
- lean_pkg/extract_decls.py +501 -0
- lean_pkg/extract_ledger.py +1408 -0
- lean_pkg/extract_summary.py +132 -0
- lean_pkg/extract_types.py +502 -0
- lean_pkg/extract_write.py +138 -0
- lean_pkg/formalization.py +1078 -0
- lean_pkg/formalization_kept.py +182 -0
- lean_pkg/fresh_repo.py +709 -0
- lean_pkg/gate.py +2141 -0
- lean_pkg/headline.py +211 -0
- lean_pkg/help_topics.py +442 -0
- lean_pkg/holes.py +289 -0
- lean_pkg/host_routes.py +376 -0
- lean_pkg/hypotheses.py +788 -0
- lean_pkg/index.py +1749 -0
- lean_pkg/json_stdout.py +48 -0
- lean_pkg/lake_hygiene.py +289 -0
- lean_pkg/lean_diag.py +280 -0
- lean_pkg/lean_scan.py +1300 -0
- lean_pkg/ledger.py +582 -0
- lean_pkg/next_step.py +510 -0
- lean_pkg/page.py +1831 -0
- lean_pkg/page_html.py +153 -0
- lean_pkg/palomar.py +316 -0
- lean_pkg/palomar_check.py +1027 -0
- lean_pkg/port_modules.py +677 -0
- lean_pkg/prior_art.py +286 -0
- lean_pkg/producer.py +212 -0
- lean_pkg/producer_skew.py +208 -0
- lean_pkg/public_safety.py +1487 -0
- lean_pkg/publish.py +402 -0
- lean_pkg/rebase.py +984 -0
- lean_pkg/receipt.py +2385 -0
- lean_pkg/receipt_check.py +1064 -0
- lean_pkg/receipt_ci.py +660 -0
- lean_pkg/receipt_systemd.py +890 -0
- lean_pkg/recommended.py +232 -0
- lean_pkg/report.py +727 -0
- lean_pkg/reservoir.py +203 -0
- lean_pkg/scaffold.py +588 -0
- lean_pkg/schemas/formalization-0.4.schema.json +344 -0
- lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
- lean_pkg/scripts/ClaimAxioms.lean +47 -0
- lean_pkg/scripts/ContractsOnly.lean +300 -0
- lean_pkg/scripts/DupConstants.lean +149 -0
- lean_pkg/scripts/HypProbe.lean +257 -0
- lean_pkg/scripts/comparator-check.sh +396 -0
- lean_pkg/scripts/verify-comparator.sh +135 -0
- lean_pkg/seal_bundle.py +647 -0
- lean_pkg/search.py +865 -0
- lean_pkg/site_profiles/easley.yaml +10 -0
- lean_pkg/site_profiles/github-actions.yaml +12 -0
- lean_pkg/sites.py +225 -0
- lean_pkg/stacks.py +373 -0
- lean_pkg/statements_module.py +217 -0
- lean_pkg/templates/Apache-2.0.txt +202 -0
- lean_pkg/toolchain_advisories.py +225 -0
- lean_pkg/upgrade.py +706 -0
- lean_pkg/verify.py +495 -0
- lean_pkg-0.25.0.dist-info/METADATA +93 -0
- lean_pkg-0.25.0.dist-info/RECORD +103 -0
- lean_pkg-0.25.0.dist-info/WHEEL +5 -0
- lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
- lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
- lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/lean_scan.py
ADDED
|
@@ -0,0 +1,1300 @@
|
|
|
1
|
+
# lean-pkg lean_scan -- a small Lean 4 source scanner for search and claims
|
|
2
|
+
"""Lean names and declaration headers, without Lean.
|
|
3
|
+
|
|
4
|
+
`split_name` / `last_component` split a dotted Lean name, keeping a «guillemet-quoted» component
|
|
5
|
+
whole (`Demo.«a.b»` is two components). `declarations(text)` lists the declarations of a Lean file
|
|
6
|
+
with their fully qualified names: it skips nested `/- ... -/` block comments, `--` line comments and
|
|
7
|
+
string literals, attaches a `/-- ... -/` docstring to the declaration after it (on the same line or
|
|
8
|
+
across attribute lines), reads attributes with strings and nested brackets, modifiers
|
|
9
|
+
(`private`, `public`, `noncomputable`, `local`, ...), `instance (priority := n)`, `class inductive`,
|
|
10
|
+
`class abbrev` and «» names, and tracks `namespace` / `section` / `mutual` ... `end` as Lean does, one
|
|
11
|
+
scope per name component (`end B` after `namespace A.B` leaves `A` open). A line inside a syntax quotation
|
|
12
|
+
`` `(...) `` is syntax being built, not a command. It is a scanner for search, not a parser: a
|
|
13
|
+
declaration it cannot read is missed, never invented from a comment.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
|
|
21
|
+
KEYWORDS = ("theorem", "lemma", "def", "structure", "class", "instance", "abbrev", "inductive",
|
|
22
|
+
"axiom", "opaque", "irreducible_def")
|
|
23
|
+
# `public` and `meta` are module-system modifiers (Lean v4.35: `public theorem`, `@[expose] public section`,
|
|
24
|
+
# `public meta def`).
|
|
25
|
+
MODIFIERS = ("private", "protected", "noncomputable", "partial", "unsafe", "nonrec", "scoped", "local",
|
|
26
|
+
"public", "meta")
|
|
27
|
+
_IDENT_PART = r"(?:«[^»\n]*»|[^\s:({\[⦃«».,@)}\]⦄]+)"
|
|
28
|
+
_NAME = re.compile(_IDENT_PART + r"(?:\." + _IDENT_PART + r")*")
|
|
29
|
+
_WORD = re.compile(r"[A-Za-z_][A-Za-z0-9_']*")
|
|
30
|
+
_PRIORITY = re.compile(r"\(\s*priority\s*:=")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def split_name(name: str) -> list[str] | None:
|
|
34
|
+
"""The components of a dotted Lean name, a «quoted» component kept whole with its guillemets;
|
|
35
|
+
None when the name is malformed (an unclosed «, an empty component, whitespace outside «»)."""
|
|
36
|
+
parts, cur, i, s = [], "", 0, str(name)
|
|
37
|
+
while i < len(s):
|
|
38
|
+
ch = s[i]
|
|
39
|
+
if ch == "«":
|
|
40
|
+
j = s.find("»", i + 1)
|
|
41
|
+
if j < 0:
|
|
42
|
+
return None
|
|
43
|
+
cur += s[i:j + 1]
|
|
44
|
+
i = j + 1
|
|
45
|
+
continue
|
|
46
|
+
if ch == "»" or ch.isspace():
|
|
47
|
+
return None
|
|
48
|
+
if ch == ".":
|
|
49
|
+
if not cur:
|
|
50
|
+
return None
|
|
51
|
+
parts.append(cur)
|
|
52
|
+
cur = ""
|
|
53
|
+
else:
|
|
54
|
+
cur += ch
|
|
55
|
+
i += 1
|
|
56
|
+
if not cur:
|
|
57
|
+
return None
|
|
58
|
+
parts.append(cur)
|
|
59
|
+
return parts
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def last_component(name: str) -> str:
|
|
63
|
+
"""The last component of a Lean name (`Demo.«a.b»` -> `«a.b»`); the name itself when malformed."""
|
|
64
|
+
parts = split_name(name)
|
|
65
|
+
return parts[-1] if parts else str(name)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def occurs(component: str, text: str) -> bool:
|
|
69
|
+
"""Does a name component occur in the text? `«foo»` also counts as `foo` (the quotes are optional
|
|
70
|
+
for a plain identifier), and `«foo bar»` only with its guillemets."""
|
|
71
|
+
if component in text:
|
|
72
|
+
return True
|
|
73
|
+
if component.startswith("«") and component.endswith("»"):
|
|
74
|
+
inner = component[1:-1]
|
|
75
|
+
return bool(inner) and not any(ch.isspace() or ch in ".«»" for ch in inner) and inner in text
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def is_name(name) -> bool:
|
|
80
|
+
return isinstance(name, str) and split_name(name.strip()) is not None and name == name.strip()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# --------------------------------------------------------------------------
|
|
84
|
+
# masking: comments and strings become spaces (newlines kept), docstrings are remembered
|
|
85
|
+
|
|
86
|
+
def _mask(text: str) -> tuple[str, list[tuple[int, int, str]]]:
|
|
87
|
+
"""(text with comments, docstrings and string literals blanked, [(start, end, docstring text)])."""
|
|
88
|
+
out = list(text)
|
|
89
|
+
docs: list[tuple[int, int, str]] = []
|
|
90
|
+
n, i = len(text), 0
|
|
91
|
+
|
|
92
|
+
def blank(a: int, b: int) -> None:
|
|
93
|
+
for k in range(a, b):
|
|
94
|
+
if out[k] != "\n":
|
|
95
|
+
out[k] = " "
|
|
96
|
+
|
|
97
|
+
while i < n:
|
|
98
|
+
ch = text[i]
|
|
99
|
+
if ch == "«": # a quoted name is literal text
|
|
100
|
+
j = text.find("»", i + 1)
|
|
101
|
+
i = n if j < 0 else j + 1
|
|
102
|
+
continue
|
|
103
|
+
if text.startswith("/-", i):
|
|
104
|
+
is_doc = text.startswith("/--", i) and not text.startswith("/--/", i)
|
|
105
|
+
depth, j = 1, i + 2
|
|
106
|
+
while j < n and depth:
|
|
107
|
+
if text.startswith("/-", j):
|
|
108
|
+
depth, j = depth + 1, j + 2
|
|
109
|
+
elif text.startswith("-/", j):
|
|
110
|
+
depth, j = depth - 1, j + 2
|
|
111
|
+
else:
|
|
112
|
+
j += 1
|
|
113
|
+
if is_doc:
|
|
114
|
+
docs.append((i, j, " ".join(text[i:j].split())))
|
|
115
|
+
blank(i, j)
|
|
116
|
+
i = j
|
|
117
|
+
continue
|
|
118
|
+
if text.startswith("--", i):
|
|
119
|
+
j = text.find("\n", i)
|
|
120
|
+
j = n if j < 0 else j
|
|
121
|
+
blank(i, j)
|
|
122
|
+
i = j
|
|
123
|
+
continue
|
|
124
|
+
if ch == '"' or (ch == "r" and re.match(r'r#*"', text[i:i + 8]) and
|
|
125
|
+
(i == 0 or not (text[i - 1].isalnum() or text[i - 1] in "_'."))):
|
|
126
|
+
if ch == "r":
|
|
127
|
+
hashes = len(re.match(r"r(#*)", text[i:]).group(1))
|
|
128
|
+
close = '"' + "#" * hashes
|
|
129
|
+
j = text.find(close, i + 2 + hashes)
|
|
130
|
+
j = n if j < 0 else j + len(close)
|
|
131
|
+
else:
|
|
132
|
+
j = i + 1
|
|
133
|
+
while j < n and text[j] != '"':
|
|
134
|
+
j += 2 if text[j] == "\\" else 1
|
|
135
|
+
j = min(n, j + 1)
|
|
136
|
+
blank(i, j)
|
|
137
|
+
i = j
|
|
138
|
+
continue
|
|
139
|
+
if ch == "'" and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] in "_'!?»")):
|
|
140
|
+
m = re.match(r"'(?:\\[^\n]+?|[^\\\n])'", text[i:i + 12])
|
|
141
|
+
if m:
|
|
142
|
+
blank(i, i + m.end())
|
|
143
|
+
i += m.end()
|
|
144
|
+
continue
|
|
145
|
+
i += 1
|
|
146
|
+
return "".join(out), docs
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _skip_ws(s: str, i: int) -> int:
|
|
150
|
+
while i < len(s) and s[i].isspace():
|
|
151
|
+
i += 1
|
|
152
|
+
return i
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _balanced(s: str, i: int) -> int:
|
|
156
|
+
"""The index after the bracket group opening at s[i] (strings already blanked); len(s) if unclosed."""
|
|
157
|
+
pairs = {"[": "]", "(": ")", "{": "}", "⦃": "⦄"}
|
|
158
|
+
stack = [pairs[s[i]]]
|
|
159
|
+
j = i + 1
|
|
160
|
+
while j < len(s) and stack:
|
|
161
|
+
c = s[j]
|
|
162
|
+
if c in pairs:
|
|
163
|
+
stack.append(pairs[c])
|
|
164
|
+
elif c == stack[-1]:
|
|
165
|
+
stack.pop()
|
|
166
|
+
j += 1
|
|
167
|
+
return j
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _scope_name(s: str, i: int) -> tuple[str | None, int]:
|
|
171
|
+
"""An optional name after `namespace` / `section` / `end`, on the same line."""
|
|
172
|
+
j = i
|
|
173
|
+
while j < len(s) and s[j] in " \t":
|
|
174
|
+
j += 1
|
|
175
|
+
m = _NAME.match(s, j)
|
|
176
|
+
if m and m.group(0) not in KEYWORDS:
|
|
177
|
+
return m.group(0), m.end()
|
|
178
|
+
return None, i
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _quotations(masked: str) -> list[tuple[int, int]]:
|
|
182
|
+
"""[(start, end)] of the syntax quotations `` `(...) `` and `` `(cat| ...) `` of the masked text,
|
|
183
|
+
outermost only (an antiquotation `$(...)` and a nested quotation lie inside one). The text between
|
|
184
|
+
is syntax being built, not commands: a `theorem` or `namespace` line there declares nothing. An
|
|
185
|
+
unclosed quotation is left out, so a malformed file reads as it did before."""
|
|
186
|
+
out: list[tuple[int, int]] = []
|
|
187
|
+
i = masked.find("`(")
|
|
188
|
+
while i >= 0:
|
|
189
|
+
stack, j = [")"], i + 2
|
|
190
|
+
pairs = {"[": "]", "(": ")", "{": "}", "⦃": "⦄"}
|
|
191
|
+
while j < len(masked) and stack:
|
|
192
|
+
ch = masked[j]
|
|
193
|
+
if ch == "«": # a quoted name is literal text
|
|
194
|
+
k = masked.find("»", j + 1)
|
|
195
|
+
j = len(masked) if k < 0 else k + 1
|
|
196
|
+
continue
|
|
197
|
+
if ch in pairs:
|
|
198
|
+
stack.append(pairs[ch])
|
|
199
|
+
elif ch == stack[-1]:
|
|
200
|
+
stack.pop()
|
|
201
|
+
j += 1
|
|
202
|
+
if stack:
|
|
203
|
+
break
|
|
204
|
+
out.append((i, j))
|
|
205
|
+
i = masked.find("`(", j)
|
|
206
|
+
return out
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _after_in_prefix(masked: str, i: int) -> int | None:
|
|
210
|
+
"""When masked[i] starts a prefix command (`open X in`, `variable (p) in`, `set_option o v in`, any of
|
|
211
|
+
_IN_WORDS) whose `in` is followed on the same line by more text, the index of that text; else None
|
|
212
|
+
(no prefix, or an `in` that ends its line: the command it prefixes starts the next line, which is
|
|
213
|
+
read as its own line). The `in` is the first one at bracket depth zero on the line, as `_head` reads it."""
|
|
214
|
+
m = _HASH_WORD.match(masked, i) if masked.startswith("#", i) else _WORD.match(masked, i)
|
|
215
|
+
if not m or m.group(0) not in _IN_WORDS:
|
|
216
|
+
return None
|
|
217
|
+
eol = masked.find("\n", m.end())
|
|
218
|
+
eol = len(masked) if eol < 0 else eol
|
|
219
|
+
depth, k = 0, m.end()
|
|
220
|
+
while k < eol:
|
|
221
|
+
ch = masked[k]
|
|
222
|
+
if ch == "«":
|
|
223
|
+
close = masked.find("»", k + 1, eol)
|
|
224
|
+
if close < 0:
|
|
225
|
+
return None
|
|
226
|
+
k = close + 1
|
|
227
|
+
continue
|
|
228
|
+
if ch in _BRACKETS:
|
|
229
|
+
depth += 1
|
|
230
|
+
elif ch in _CLOSERS:
|
|
231
|
+
depth -= 1
|
|
232
|
+
elif depth == 0 and ch == "i" and _IN.match(masked, k) and \
|
|
233
|
+
not (masked[k - 1].isalnum() or masked[k - 1] in "_'.!?«»"):
|
|
234
|
+
rest = k + 2
|
|
235
|
+
while rest < eol and masked[rest] in " \t":
|
|
236
|
+
rest += 1
|
|
237
|
+
return rest if rest < eol else None
|
|
238
|
+
k += 1
|
|
239
|
+
return None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def declarations(text: str) -> list[tuple[int, str, str, str | None, str, str]]:
|
|
243
|
+
"""(line, keyword, qualified name, docstring or None, stripped source line, name as written) for every
|
|
244
|
+
declaration. `class inductive` and `class abbrev` report keyword `class`; an anonymous instance is left
|
|
245
|
+
out; a `_root_.` name is not prefixed with the namespace. Scopes are kept one name component at a
|
|
246
|
+
time, as Lean keeps them; a keyword on a line inside a syntax quotation declares nothing."""
|
|
247
|
+
masked, docs = _mask(text)
|
|
248
|
+
lines = text.splitlines()
|
|
249
|
+
starts, off = [], 0
|
|
250
|
+
for ln in masked.split("\n"):
|
|
251
|
+
starts.append(off)
|
|
252
|
+
off += len(ln) + 1
|
|
253
|
+
doc_by_end = sorted(docs, key=lambda d: d[1])
|
|
254
|
+
scopes: list[tuple[str, str | None]] = [] # (kind, one name component or None), as Lean keeps them
|
|
255
|
+
out = []
|
|
256
|
+
consumed = 0
|
|
257
|
+
line_of = _line_index(starts)
|
|
258
|
+
quotes = _quotations(masked)
|
|
259
|
+
qi = 0
|
|
260
|
+
for st in starts:
|
|
261
|
+
if st < consumed:
|
|
262
|
+
continue
|
|
263
|
+
c = st
|
|
264
|
+
while c < len(masked) and masked[c] in " \t":
|
|
265
|
+
c += 1
|
|
266
|
+
while qi < len(quotes) and quotes[qi][1] <= c:
|
|
267
|
+
qi += 1
|
|
268
|
+
if qi < len(quotes) and quotes[qi][0] < c: # inside a syntax quotation
|
|
269
|
+
continue
|
|
270
|
+
i, prefixed = c, False
|
|
271
|
+
while (nxt := _after_in_prefix(masked, i)) is not None: # `variable (p) in protected lemma ...`
|
|
272
|
+
i, prefixed = nxt, True
|
|
273
|
+
while masked.startswith("@[", i): # attributes, across lines
|
|
274
|
+
i = _skip_ws(masked, _balanced(masked, i + 1))
|
|
275
|
+
words_seen = []
|
|
276
|
+
while True:
|
|
277
|
+
m = _WORD.match(masked, i)
|
|
278
|
+
if not m:
|
|
279
|
+
break
|
|
280
|
+
w = m.group(0)
|
|
281
|
+
if w in MODIFIERS:
|
|
282
|
+
words_seen.append(w)
|
|
283
|
+
i = _skip_ws(masked, m.end())
|
|
284
|
+
while masked.startswith("@[", i):
|
|
285
|
+
i = _skip_ws(masked, _balanced(masked, i + 1))
|
|
286
|
+
continue
|
|
287
|
+
break
|
|
288
|
+
m = _WORD.match(masked, i)
|
|
289
|
+
if not m:
|
|
290
|
+
continue
|
|
291
|
+
w, after = m.group(0), m.end()
|
|
292
|
+
if after < len(masked) and not masked[after].isspace():
|
|
293
|
+
continue
|
|
294
|
+
if prefixed and w not in KEYWORDS:
|
|
295
|
+
continue # `open X in` before a term, a tactic or a scope
|
|
296
|
+
if w == "namespace" and not words_seen:
|
|
297
|
+
name, consumed = _scope_name(masked, after)
|
|
298
|
+
if name:
|
|
299
|
+
scopes.extend(("namespace", comp) for comp in (split_name(name) or [name]))
|
|
300
|
+
continue
|
|
301
|
+
if w == "section":
|
|
302
|
+
name, consumed = _scope_name(masked, after)
|
|
303
|
+
scopes.extend(("section", comp) for comp in ((split_name(name) or [name]) if name else [None]))
|
|
304
|
+
continue
|
|
305
|
+
if w == "mutual" and not words_seen:
|
|
306
|
+
scopes.append(("mutual", None))
|
|
307
|
+
continue
|
|
308
|
+
if w == "end" and not words_seen:
|
|
309
|
+
name, consumed = _scope_name(masked, after)
|
|
310
|
+
# Lean keeps one scope per name component: `end B` after `namespace A.B` closes `B` only,
|
|
311
|
+
# `end A.B` closes both, a bare `end` closes one anonymous scope. A mismatched `end` (an
|
|
312
|
+
# error in Lean) still closes as many scopes as it names, never more than are open.
|
|
313
|
+
count = len(split_name(name) or [name]) if name else 1
|
|
314
|
+
del scopes[max(0, len(scopes) - count):]
|
|
315
|
+
continue
|
|
316
|
+
if w not in KEYWORDS:
|
|
317
|
+
continue
|
|
318
|
+
kw = w
|
|
319
|
+
j = _skip_ws(masked, after)
|
|
320
|
+
if kw == "class":
|
|
321
|
+
m2 = _WORD.match(masked, j)
|
|
322
|
+
if m2 and m2.group(0) in ("inductive", "abbrev"):
|
|
323
|
+
j = _skip_ws(masked, m2.end())
|
|
324
|
+
if kw == "instance" and _PRIORITY.match(masked, j):
|
|
325
|
+
j = _skip_ws(masked, _balanced(masked, j))
|
|
326
|
+
m3 = _NAME.match(masked, j)
|
|
327
|
+
if not m3 or m3.group(0) in KEYWORDS or m3.group(0) in ("where", "extends", "with"):
|
|
328
|
+
consumed = j
|
|
329
|
+
continue
|
|
330
|
+
written = m3.group(0)
|
|
331
|
+
consumed = m3.end()
|
|
332
|
+
parts = split_name(written) or [written]
|
|
333
|
+
if parts[0] == "_root_":
|
|
334
|
+
qual = ".".join(parts[1:]) or written
|
|
335
|
+
else:
|
|
336
|
+
ns = [comp for kind, comp in scopes if kind == "namespace"]
|
|
337
|
+
qual = ".".join(ns + parts)
|
|
338
|
+
line = line_of(m.start())
|
|
339
|
+
doc = None
|
|
340
|
+
inside = [d for a, b, d in doc_by_end if c <= a and b <= m.start()] if prefixed else []
|
|
341
|
+
if inside: # `open X in` / attributes, then the docstring
|
|
342
|
+
doc = inside[-1]
|
|
343
|
+
for _a, b, d in ([] if inside else reversed(doc_by_end)):
|
|
344
|
+
if b <= c and not masked[b:c].strip():
|
|
345
|
+
doc = d
|
|
346
|
+
break
|
|
347
|
+
if b <= c:
|
|
348
|
+
break
|
|
349
|
+
src = lines[line - 1].strip() if line - 1 < len(lines) else ""
|
|
350
|
+
out.append((line, kw, qual, doc, src, written))
|
|
351
|
+
return out
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _line_index(starts: list[int]):
|
|
355
|
+
import bisect
|
|
356
|
+
|
|
357
|
+
def line_of(pos: int) -> int:
|
|
358
|
+
return bisect.bisect_right(starts, pos)
|
|
359
|
+
return line_of
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
# --------------------------------------------------------------------------
|
|
363
|
+
# declaration spans for the extraction ledger (proposal 0009, method text/1): comments stripped,
|
|
364
|
+
# declarations split at top-level commands, names mapped, text normalized. Library only; the
|
|
365
|
+
# functions above keep their behavior.
|
|
366
|
+
|
|
367
|
+
class ScanError(ValueError):
|
|
368
|
+
"""A file whose comment, string or bracket structure (or command layout) the span splitter cannot
|
|
369
|
+
read. The file is refused whole, never half split."""
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
class MapError(ValueError):
|
|
373
|
+
"""A namespace or rename map that is malformed or ambiguous (a duplicate, a no-op, a chain or a
|
|
374
|
+
cycle)."""
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _lex(text: str) -> list[tuple[int, int, str]]:
|
|
378
|
+
"""[(start, end, kind)] of the non-code regions of a Lean file, kinds `comment` (`--` and `/- -/`,
|
|
379
|
+
nested), `doc` (`/-- -/`), `moddoc` (`/-! -/`), `string` and `char`. The same reading as `_mask`
|
|
380
|
+
(a «quoted» name is literal text, so `«a -- b»` holds no comment), but strict: an unclosed block
|
|
381
|
+
comment, string literal or «» name raises ScanError instead of running to the end of the file."""
|
|
382
|
+
out: list[tuple[int, int, str]] = []
|
|
383
|
+
n, i = len(text), 0
|
|
384
|
+
while i < n:
|
|
385
|
+
ch = text[i]
|
|
386
|
+
if ch == "«":
|
|
387
|
+
j = text.find("»", i + 1)
|
|
388
|
+
if j < 0:
|
|
389
|
+
raise ScanError(f"line {text.count(chr(10), 0, i) + 1}: an unclosed « name")
|
|
390
|
+
i = j + 1
|
|
391
|
+
continue
|
|
392
|
+
if text.startswith("/-", i):
|
|
393
|
+
if text.startswith("/--", i) and not text.startswith("/--/", i):
|
|
394
|
+
kind = "doc"
|
|
395
|
+
elif text.startswith("/-!", i):
|
|
396
|
+
kind = "moddoc"
|
|
397
|
+
else:
|
|
398
|
+
kind = "comment"
|
|
399
|
+
depth, j = 1, i + 2
|
|
400
|
+
while j < n and depth:
|
|
401
|
+
if text.startswith("/-", j):
|
|
402
|
+
depth, j = depth + 1, j + 2
|
|
403
|
+
elif text.startswith("-/", j):
|
|
404
|
+
depth, j = depth - 1, j + 2
|
|
405
|
+
else:
|
|
406
|
+
j += 1
|
|
407
|
+
if depth:
|
|
408
|
+
raise ScanError(f"line {text.count(chr(10), 0, i) + 1}: an unclosed /- comment")
|
|
409
|
+
out.append((i, j, kind))
|
|
410
|
+
i = j
|
|
411
|
+
continue
|
|
412
|
+
if text.startswith("--", i):
|
|
413
|
+
j = text.find("\n", i)
|
|
414
|
+
j = n if j < 0 else j
|
|
415
|
+
out.append((i, j, "comment"))
|
|
416
|
+
i = j
|
|
417
|
+
continue
|
|
418
|
+
if ch == '"' or (ch == "r" and re.match(r'r#*"', text[i:i + 8]) and
|
|
419
|
+
(i == 0 or not (text[i - 1].isalnum() or text[i - 1] in "_'."))):
|
|
420
|
+
if ch == "r":
|
|
421
|
+
hashes = len(re.match(r"r(#*)", text[i:]).group(1))
|
|
422
|
+
close = '"' + "#" * hashes
|
|
423
|
+
j = text.find(close, i + 2 + hashes)
|
|
424
|
+
if j < 0:
|
|
425
|
+
raise ScanError(f"line {text.count(chr(10), 0, i) + 1}: an unclosed raw string")
|
|
426
|
+
j += len(close)
|
|
427
|
+
else:
|
|
428
|
+
j = i + 1
|
|
429
|
+
while j < n and text[j] != '"':
|
|
430
|
+
j += 2 if text[j] == "\\" else 1
|
|
431
|
+
if j >= n:
|
|
432
|
+
raise ScanError(f"line {text.count(chr(10), 0, i) + 1}: an unclosed string literal")
|
|
433
|
+
j += 1
|
|
434
|
+
out.append((i, j, "string"))
|
|
435
|
+
i = j
|
|
436
|
+
continue
|
|
437
|
+
if ch == "'" and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] in "_'!?»")):
|
|
438
|
+
m = re.match(r"'(?:\\[^\n]+?|[^\\\n])'", text[i:i + 12])
|
|
439
|
+
if m:
|
|
440
|
+
out.append((i, i + m.end(), "char"))
|
|
441
|
+
i += m.end()
|
|
442
|
+
continue
|
|
443
|
+
i += 1
|
|
444
|
+
return out
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _blank(text: str, regions: list[tuple[int, int, str]], kinds: tuple[str, ...]) -> str:
|
|
448
|
+
out = list(text)
|
|
449
|
+
for a, b, kind in regions:
|
|
450
|
+
if kind in kinds:
|
|
451
|
+
for k in range(a, b):
|
|
452
|
+
if out[k] != "\n":
|
|
453
|
+
out[k] = " "
|
|
454
|
+
return "".join(out)
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
_COMMENT_KINDS = ("comment", "doc", "moddoc")
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def strip_comments(text: str) -> str:
|
|
461
|
+
"""The text with every comment blanked: `--` line comments, nested `/- -/` block comments, docstrings
|
|
462
|
+
`/-- -/` and module docs `/-! -/`. Each comment character becomes a space and every newline stays,
|
|
463
|
+
so the result has the same length, lines and columns as the input. String and character literals and
|
|
464
|
+
«» names are kept as written, so a `--` or `/-` inside them is not a comment. Raises ScanError for an
|
|
465
|
+
unclosed block comment, string literal or «» name."""
|
|
466
|
+
return _blank(text, _lex(text), _COMMENT_KINDS)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
# commands that start a span, beyond the declaration KEYWORDS and `example`
|
|
470
|
+
_SCOPE_WORDS = ("namespace", "section", "end", "mutual")
|
|
471
|
+
_HEADER_WORDS = ("import", "module", "prelude")
|
|
472
|
+
_CONTEXT_WORDS = ("open", "variable", "universe", "set_option", "attribute", "export", "initialize",
|
|
473
|
+
"builtin_initialize", "notation", "notation3", "infix", "infixl", "infixr", "prefix",
|
|
474
|
+
"postfix", "macro", "macro_rules", "syntax", "elab", "elab_rules", "declare_syntax_cat",
|
|
475
|
+
"omit", "include", "alias", "run_cmd", "run_elab", "run_meta", "assert_not_exists",
|
|
476
|
+
"assert_not_imported", "add_decl_doc", "library_note", "register_simp_attr",
|
|
477
|
+
"initialize_simps_projections", "suppress_compilation", "unseal", "seal", "simproc",
|
|
478
|
+
"simproc_decl", "dsimproc", "binder_predicate", "unif_hint", "deriving") + _HEADER_WORDS
|
|
479
|
+
# commands that may prefix another with `in` (`open Foo in`, `set_option x v in`)
|
|
480
|
+
_IN_WORDS = ("open", "set_option", "variable", "omit", "include", "attribute", "unseal", "#guard_msgs")
|
|
481
|
+
_HASH_WORD = re.compile(r"#[A-Za-z_][A-Za-z0-9_']*")
|
|
482
|
+
# an unknown command: a lowercase snake_case word at column 0 (`name_poly_vars`, `register_hint`)
|
|
483
|
+
_COMMAND_WORD = re.compile(r"[a-z][a-z0-9_]*(?=[ \t\n]|$)")
|
|
484
|
+
_OPEN_ENDS = ("by", "fun", "then", "else", "do", "from", "with", "at", "in", "where", "calc", "have", "show",
|
|
485
|
+
"match", "if", "let", "using", "λ")
|
|
486
|
+
_CONTINUATIONS = _OPEN_ENDS + ("deriving", "termination_by", "decreasing_by", "extends", "nomatch",
|
|
487
|
+
"nofun", "partial_fixpoint", "rfl", "sorry", "trivial", "simp", "exact", "intro",
|
|
488
|
+
"omega", "decide", "assumption", "constructor", "rw", "apply", "refine", "cases",
|
|
489
|
+
"induction", "rcases", "obtain", "aesop", "grind", "norm_num", "linarith")
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _command_word(masked: str, i: int) -> str | None:
|
|
493
|
+
"""The word at masked[i] when it can be a command lean_scan does not know: lowercase snake_case, and
|
|
494
|
+
not a word that continues a declaration (`where`, `deriving`) or a common term or tactic."""
|
|
495
|
+
m = _COMMAND_WORD.match(masked, i)
|
|
496
|
+
return m.group(0) if m and m.group(0) not in _CONTINUATIONS else None
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _complete(line: str) -> bool:
|
|
500
|
+
"""Does the previous line look finished, so a column-0 word after it starts a new command (rather than
|
|
501
|
+
continuing a term, as `alias foo :=` followed by a name at column 0 does)?"""
|
|
502
|
+
line = line.rstrip()
|
|
503
|
+
if not line:
|
|
504
|
+
return True
|
|
505
|
+
m = re.search(r"[\w'!?]+$", line)
|
|
506
|
+
if m and m.group(0) in _OPEN_ENDS:
|
|
507
|
+
return False
|
|
508
|
+
return line[-1].isalnum() or line[-1] in ")]}⟩'!?»_"
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
_IN = re.compile(r"(?<![\w'.!?«])in(?![\w'!?])")
|
|
512
|
+
_BRACKETS = {"(": ")", "[": "]", "{": "}", "⦃": "⦄", "⟨": "⟩"}
|
|
513
|
+
_CLOSERS = {v: k for k, v in _BRACKETS.items()}
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _name_end(masked: str, i: int) -> int:
|
|
517
|
+
"""The index after the «» name opening at masked[i]."""
|
|
518
|
+
j = masked.find("»", i + 1)
|
|
519
|
+
if j < 0:
|
|
520
|
+
raise ScanError(f"line {masked.count(chr(10), 0, i) + 1}: an unclosed « name")
|
|
521
|
+
return j + 1
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _line_depths(masked: str, starts: list[int]) -> list[int]:
|
|
525
|
+
"""The bracket depth at the start of each line of the masked text (strings and comments blanked);
|
|
526
|
+
ScanError on a closer that does not match, or a bracket left open at the end."""
|
|
527
|
+
depths: list[int] = []
|
|
528
|
+
stack: list[tuple[str, int]] = []
|
|
529
|
+
li, n, i = 0, len(masked), 0
|
|
530
|
+
while i < n:
|
|
531
|
+
while li < len(starts) and starts[li] <= i:
|
|
532
|
+
depths.append(len(stack))
|
|
533
|
+
li += 1
|
|
534
|
+
c = masked[i]
|
|
535
|
+
if c == "«":
|
|
536
|
+
i = _name_end(masked, i)
|
|
537
|
+
continue
|
|
538
|
+
if c in _BRACKETS:
|
|
539
|
+
stack.append((_BRACKETS[c], i))
|
|
540
|
+
elif c in _CLOSERS:
|
|
541
|
+
if not stack or stack[-1][0] != c:
|
|
542
|
+
raise ScanError(f"line {masked.count(chr(10), 0, i) + 1}: an unmatched {c!r}")
|
|
543
|
+
stack.pop()
|
|
544
|
+
i += 1
|
|
545
|
+
while li < len(starts):
|
|
546
|
+
depths.append(len(stack))
|
|
547
|
+
li += 1
|
|
548
|
+
if stack:
|
|
549
|
+
raise ScanError(f"line {masked.count(chr(10), 0, stack[-1][1]) + 1}: "
|
|
550
|
+
f"an unclosed {masked[stack[-1][1]]!r}")
|
|
551
|
+
return depths
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _skip_group(masked: str, i: int) -> int:
|
|
555
|
+
"""The index after the bracket group opening at masked[i] (structure already checked)."""
|
|
556
|
+
j = _balanced(masked, i)
|
|
557
|
+
if j > len(masked) or (j == len(masked) and masked[j - 1] != _BRACKETS.get(masked[i])):
|
|
558
|
+
raise ScanError(f"line {masked.count(chr(10), 0, i) + 1}: an unclosed {masked[i]!r}")
|
|
559
|
+
return j
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _head(masked: str, c: int):
|
|
563
|
+
"""Read the command that starts at masked[c]: None when it is no command (a continuation line), else
|
|
564
|
+
(class, word, word position, word end), class `decl`, `scope`, `context` or `bad` (attributes or
|
|
565
|
+
modifiers before something that is not a declaration)."""
|
|
566
|
+
i, prefixed = c, False
|
|
567
|
+
while masked.startswith("@[", i):
|
|
568
|
+
i = _skip_ws(masked, _skip_group(masked, i + 1))
|
|
569
|
+
prefixed = True
|
|
570
|
+
while True:
|
|
571
|
+
m = _WORD.match(masked, i)
|
|
572
|
+
if not m or m.group(0) not in MODIFIERS:
|
|
573
|
+
break
|
|
574
|
+
i, prefixed = m.end(), True
|
|
575
|
+
i = _skip_ws(masked, i)
|
|
576
|
+
if m.group(0) == "scoped" and masked.startswith("[", i): # `scoped[NS] notation`
|
|
577
|
+
i = _skip_ws(masked, _skip_group(masked, i))
|
|
578
|
+
while masked.startswith("@[", i):
|
|
579
|
+
i = _skip_ws(masked, _skip_group(masked, i + 1))
|
|
580
|
+
m = _HASH_WORD.match(masked, i) if masked.startswith("#", i) else _WORD.match(masked, i)
|
|
581
|
+
if not m:
|
|
582
|
+
return ("bad", None, i, i) if prefixed else None
|
|
583
|
+
w, after = m.group(0), m.end()
|
|
584
|
+
spaced = after >= len(masked) or masked[after].isspace() or (w == "instance" and masked[after] == "(")
|
|
585
|
+
if w in KEYWORDS or w == "example":
|
|
586
|
+
if spaced:
|
|
587
|
+
return ("decl", w, i, after)
|
|
588
|
+
return ("bad", w, i, after) if prefixed else None
|
|
589
|
+
if w in _SCOPE_WORDS:
|
|
590
|
+
if w != "section" and prefixed:
|
|
591
|
+
return ("bad", w, i, after)
|
|
592
|
+
return ("scope", w, i, after)
|
|
593
|
+
if w == "deriving":
|
|
594
|
+
m2 = _WORD.match(masked, _skip_ws(masked, after))
|
|
595
|
+
if not (m2 and m2.group(0) == "instance"):
|
|
596
|
+
return ("bad", w, i, after) if prefixed else None # a `deriving` clause stays with its declaration
|
|
597
|
+
if w in _CONTEXT_WORDS or w.startswith("#"):
|
|
598
|
+
if w in _IN_WORDS:
|
|
599
|
+
eol = masked.find("\n", after)
|
|
600
|
+
eol = len(masked) if eol < 0 else eol
|
|
601
|
+
depth, k = 0, after
|
|
602
|
+
while k < eol:
|
|
603
|
+
ch = masked[k]
|
|
604
|
+
if ch == "«":
|
|
605
|
+
k = _name_end(masked, k)
|
|
606
|
+
continue
|
|
607
|
+
if ch in _BRACKETS:
|
|
608
|
+
depth += 1
|
|
609
|
+
elif ch in _CLOSERS:
|
|
610
|
+
depth -= 1
|
|
611
|
+
elif depth == 0 and ch == "i" and _IN.match(masked, k) and \
|
|
612
|
+
(k == 0 or not (masked[k - 1].isalnum() or masked[k - 1] in "_'.!?«»")):
|
|
613
|
+
rest = _skip_ws(masked, k + 2)
|
|
614
|
+
if rest >= len(masked):
|
|
615
|
+
raise ScanError(f"line {masked.count(chr(10), 0, k) + 1}: `{w} ... in` with nothing after")
|
|
616
|
+
inner = _head(masked, rest)
|
|
617
|
+
if inner is not None and inner[0] == "scope":
|
|
618
|
+
return ("bad", inner[1], inner[2], inner[3])
|
|
619
|
+
return inner # None: `open X in tactic`, a continuation
|
|
620
|
+
k += 1
|
|
621
|
+
return ("context", w, i, after)
|
|
622
|
+
return ("bad", w, i, after) if prefixed else None
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
@dataclass(frozen=True)
|
|
626
|
+
class Span:
|
|
627
|
+
"""One top-level command of a Lean file, as `decl_spans` reads it.
|
|
628
|
+
|
|
629
|
+
key: the qualified name of a declaration; `mutual(a, b)` for a mutual block (its qualified names
|
|
630
|
+
sorted); `instance#k@Module` or `example#k@Module` for the k-th anonymous instance or example of
|
|
631
|
+
the module (k from 1); for a context command, its command word (`open`, `variable`, `end`, ...).
|
|
632
|
+
kind: the keyword (`class` for `class inductive`), `mutual`, or the context command word.
|
|
633
|
+
names: the qualified names it declares (empty for an anonymous instance, an example or a context
|
|
634
|
+
command). start, end: its first and last line (1-based, inclusive; comment-only lines after it are
|
|
635
|
+
left out). scope: the namespace components open at its start. text: its source lines as written.
|
|
636
|
+
code: the same lines with comments blanked (`strip_comments`); on the first line, a comment before
|
|
637
|
+
the command (an inline docstring) is dropped and the line's own indentation kept. doc: the docstring
|
|
638
|
+
just before it, whitespace collapsed, or None."""
|
|
639
|
+
|
|
640
|
+
key: str
|
|
641
|
+
kind: str
|
|
642
|
+
names: tuple[str, ...]
|
|
643
|
+
start: int
|
|
644
|
+
end: int
|
|
645
|
+
scope: tuple[str, ...]
|
|
646
|
+
text: str
|
|
647
|
+
code: str
|
|
648
|
+
doc: str | None
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def decl_spans(text: str, module: str = "") -> tuple[list[Span], list[Span]]:
|
|
652
|
+
"""(declarations, context): the top-level commands of a Lean file, split into spans.
|
|
653
|
+
|
|
654
|
+
A span starts at each top-level command (bracket depth zero) whose line is indented at most as far
|
|
655
|
+
as the current declaration's keyword line; after a context command, any line may start one. The
|
|
656
|
+
commands are the KEYWORDS plus `example`, `namespace` / `section` / `end` / `mutual`, `open`,
|
|
657
|
+
`variable`, `universe`, `set_option`, `attribute`, `export`, `initialize`, `deriving instance`, the
|
|
658
|
+
notation, macro and syntax commands, `#...` commands, the module header (`module`, `prelude`,
|
|
659
|
+
`import`) and a few Mathlib commands (`alias`, `omit`, `include`, ...). Attributes, modifiers and a
|
|
660
|
+
preceding `open ... in` / `set_option ... in` belong to the command they prefix; an `open X in`
|
|
661
|
+
followed by a tactic (inside a proof, even at column 0) is not a command. `where`, `deriving`,
|
|
662
|
+
`termination_by`, `decreasing_by` and `|` lines stay with their declaration.
|
|
663
|
+
|
|
664
|
+
Declarations are keyed as in `Span`, with the namespace tracking of `declarations()` (the two agree
|
|
665
|
+
on every name). A `mutual ... end` block is one span. Every other command is a context span.
|
|
666
|
+
|
|
667
|
+
Raises ScanError, never returning a partial split, for: an unclosed comment, string or «» name; an
|
|
668
|
+
unmatched or unclosed bracket; text before the first command; attributes or modifiers before
|
|
669
|
+
something that is not a declaration; a declaration whose name cannot be read; a duplicate key; an
|
|
670
|
+
`end` that does not match the innermost open scope (or with none open); a command inside a `mutual`
|
|
671
|
+
block other than a declaration; a `mutual` block left open; a line at column 0 after a context
|
|
672
|
+
command that is not a command."""
|
|
673
|
+
regions = _lex(text)
|
|
674
|
+
code_all = _blank(text, regions, _COMMENT_KINDS)
|
|
675
|
+
masked = _blank(text, regions, _COMMENT_KINDS + ("string", "char"))
|
|
676
|
+
docs = sorted((a, b, " ".join(text[a:b].split())) for a, b, kind in regions if kind == "doc")
|
|
677
|
+
raw_lines = text.split("\n")
|
|
678
|
+
code_lines = code_all.split("\n")
|
|
679
|
+
m_lines = masked.split("\n")
|
|
680
|
+
starts, off = [], 0
|
|
681
|
+
for ln in m_lines:
|
|
682
|
+
starts.append(off)
|
|
683
|
+
off += len(ln) + 1
|
|
684
|
+
depths = _line_depths(masked, starts)
|
|
685
|
+
line_of = _line_index(starts)
|
|
686
|
+
suffix = f"@{module}" if module else ""
|
|
687
|
+
|
|
688
|
+
decls: list[Span] = []
|
|
689
|
+
context: list[Span] = []
|
|
690
|
+
scopes: list[tuple[str, str | None]] = [] # (kind, one name component or None), as Lean keeps them
|
|
691
|
+
ordinals = {"instance": 0, "example": 0}
|
|
692
|
+
seen: set[str] = set()
|
|
693
|
+
cur: dict | None = None
|
|
694
|
+
consumed = 0
|
|
695
|
+
prev_line = ""
|
|
696
|
+
|
|
697
|
+
def ns() -> tuple[str, ...]:
|
|
698
|
+
return tuple(comp for kind, comp in scopes if kind == "namespace")
|
|
699
|
+
|
|
700
|
+
def doc_before(c: int, pos: int) -> str | None:
|
|
701
|
+
inside = [d for a, b, d in docs if c <= a and b <= pos]
|
|
702
|
+
if inside: # `open X in` / attributes, then the docstring
|
|
703
|
+
return inside[-1]
|
|
704
|
+
for _a, b, d in reversed(docs):
|
|
705
|
+
if b <= c:
|
|
706
|
+
return d if not masked[b:c].strip() else None
|
|
707
|
+
return None
|
|
708
|
+
|
|
709
|
+
def close() -> None:
|
|
710
|
+
nonlocal cur
|
|
711
|
+
if cur is None:
|
|
712
|
+
return
|
|
713
|
+
a, b = cur["start"], cur["last"]
|
|
714
|
+
code = code_lines[a:b + 1]
|
|
715
|
+
col = cur["col"]
|
|
716
|
+
if code and not code[0][:col].strip():
|
|
717
|
+
raw = raw_lines[a]
|
|
718
|
+
indent = raw[:len(raw) - len(raw.lstrip())]
|
|
719
|
+
code[0] = indent[:col] + code[0][col:]
|
|
720
|
+
if cur["kind"] == "mutual":
|
|
721
|
+
if cur["open"]:
|
|
722
|
+
raise ScanError(f"line {a + 1}: a mutual block is never closed")
|
|
723
|
+
names = tuple(sorted(cur["names"]))
|
|
724
|
+
key = "mutual(" + ", ".join(names) + ")"
|
|
725
|
+
else:
|
|
726
|
+
names = tuple(cur["names"])
|
|
727
|
+
key = cur["key"]
|
|
728
|
+
span = Span(key, cur["kind"], names, a + 1, b + 1, cur["scope"], "\n".join(raw_lines[a:b + 1]),
|
|
729
|
+
"\n".join(code), cur["doc"])
|
|
730
|
+
(decls if cur["decl"] else context).append(span)
|
|
731
|
+
cur = None
|
|
732
|
+
|
|
733
|
+
def decl_key(kw: str, pos: int, after: int, lineno: int) -> tuple[str, list[str], int]:
|
|
734
|
+
"""(key, [qualified name] or [], end of the name), as declarations() reads the name."""
|
|
735
|
+
j = _skip_ws(masked, after)
|
|
736
|
+
if kw == "class":
|
|
737
|
+
m2 = _WORD.match(masked, j)
|
|
738
|
+
if m2 and m2.group(0) in ("inductive", "abbrev"): # `class abbrev`: Mathlib's
|
|
739
|
+
j = _skip_ws(masked, m2.end())
|
|
740
|
+
if kw == "instance" and _PRIORITY.match(masked, j):
|
|
741
|
+
j = _skip_ws(masked, _skip_group(masked, j))
|
|
742
|
+
m3 = _NAME.match(masked, j) if kw != "example" else None
|
|
743
|
+
if not m3 or m3.group(0) in KEYWORDS or m3.group(0) in ("where", "extends", "with"):
|
|
744
|
+
if kw not in ("instance", "example"):
|
|
745
|
+
raise ScanError(f"line {lineno}: the name of this {kw} cannot be read")
|
|
746
|
+
ordinals[kw] += 1
|
|
747
|
+
return f"{kw}#{ordinals[kw]}{suffix}", [], j
|
|
748
|
+
written = m3.group(0)
|
|
749
|
+
parts = split_name(written)
|
|
750
|
+
if parts is None:
|
|
751
|
+
raise ScanError(f"line {lineno}: the name {written!r} is malformed")
|
|
752
|
+
qual = ".".join(parts[1:]) if parts[0] == "_root_" and len(parts) > 1 else ".".join(ns() + tuple(parts))
|
|
753
|
+
return qual, [qual], m3.end()
|
|
754
|
+
|
|
755
|
+
def claim(key: str, lineno: int) -> None:
|
|
756
|
+
if key in seen:
|
|
757
|
+
raise ScanError(f"line {lineno}: {key} is declared twice")
|
|
758
|
+
seen.add(key)
|
|
759
|
+
|
|
760
|
+
for k, mline in enumerate(m_lines):
|
|
761
|
+
st = starts[k]
|
|
762
|
+
if not mline.strip():
|
|
763
|
+
continue
|
|
764
|
+
if st < consumed or depths[k] > 0:
|
|
765
|
+
if cur is not None:
|
|
766
|
+
cur["last"] = k
|
|
767
|
+
prev_line = mline
|
|
768
|
+
continue
|
|
769
|
+
raw = raw_lines[k]
|
|
770
|
+
indent = len(raw) - len(raw.lstrip())
|
|
771
|
+
c = st + len(mline) - len(mline.lstrip())
|
|
772
|
+
thr = cur["thr"] if cur is not None else None
|
|
773
|
+
head = _head(masked, c)
|
|
774
|
+
if thr is not None and indent > thr and not (head and head[0] in ("decl", "scope")):
|
|
775
|
+
cur["last"], prev_line = k, mline # deeper: part of the declaration, unless it
|
|
776
|
+
continue # opens with a declaration or scope keyword
|
|
777
|
+
in_mutual = cur is not None and cur["kind"] == "mutual" and cur["open"]
|
|
778
|
+
if head is not None and head[0] == "bad" and cur is not None and indent > 0:
|
|
779
|
+
head = None # `unsafe Foo.init` inside a term
|
|
780
|
+
if head is not None and head[0] == "bad":
|
|
781
|
+
if in_mutual or not _command_word(masked, head[2]):
|
|
782
|
+
raise ScanError(f"line {k + 1}: attributes or modifiers before something that is not a "
|
|
783
|
+
f"declaration")
|
|
784
|
+
head = ("context", _command_word(masked, head[2]), head[2], head[2])
|
|
785
|
+
elif head is None:
|
|
786
|
+
m_cmd = _command_word(masked, c)
|
|
787
|
+
if cur is None:
|
|
788
|
+
if not m_cmd:
|
|
789
|
+
raise ScanError(f"line {k + 1}: text outside any command")
|
|
790
|
+
elif in_mutual or not (m_cmd and indent == 0 and _complete(prev_line)):
|
|
791
|
+
cur["last"], prev_line = k, mline
|
|
792
|
+
continue
|
|
793
|
+
head = ("context", m_cmd, c, c) # a command lean_scan does not know
|
|
794
|
+
cls, w, pos, after = head
|
|
795
|
+
lineno = line_of(pos)
|
|
796
|
+
kw_raw = raw_lines[lineno - 1]
|
|
797
|
+
kw_indent = len(kw_raw) - len(kw_raw.lstrip())
|
|
798
|
+
prev_line = mline
|
|
799
|
+
if in_mutual:
|
|
800
|
+
if cls == "context":
|
|
801
|
+
cur["last"] = k # `variable` inside `mutual` stays in it
|
|
802
|
+
consumed = after
|
|
803
|
+
continue
|
|
804
|
+
if cls == "decl":
|
|
805
|
+
key, names, consumed = decl_key(w, pos, after, lineno)
|
|
806
|
+
claim(key, lineno)
|
|
807
|
+
cur["names"].extend(names or [key])
|
|
808
|
+
cur["thr"], cur["last"] = kw_indent, k
|
|
809
|
+
continue
|
|
810
|
+
if cls == "scope" and w == "end":
|
|
811
|
+
name, consumed = _scope_name(masked, after)
|
|
812
|
+
if name is not None:
|
|
813
|
+
raise ScanError(f"line {lineno}: `end {name}` closes a mutual block")
|
|
814
|
+
if not cur["names"]:
|
|
815
|
+
raise ScanError(f"line {lineno}: an empty mutual block")
|
|
816
|
+
scopes.pop()
|
|
817
|
+
cur["open"], cur["last"] = False, k
|
|
818
|
+
close()
|
|
819
|
+
continue
|
|
820
|
+
raise ScanError(f"line {lineno}: a {w} command inside a mutual block")
|
|
821
|
+
close()
|
|
822
|
+
cur = {"start": k, "last": k, "col": c - st, "scope": ns(), "doc": doc_before(c, pos), "names": [],
|
|
823
|
+
"kind": w, "key": w, "decl": False, "thr": None, "open": False}
|
|
824
|
+
if cls == "decl":
|
|
825
|
+
key, names, consumed = decl_key(w, pos, after, lineno)
|
|
826
|
+
claim(key, lineno)
|
|
827
|
+
cur.update(key=key, names=names, decl=True, thr=kw_indent)
|
|
828
|
+
elif cls == "scope":
|
|
829
|
+
consumed = after
|
|
830
|
+
if w == "mutual":
|
|
831
|
+
scopes.append(("mutual", None))
|
|
832
|
+
cur.update(decl=True, open=True, doc=None)
|
|
833
|
+
elif w == "namespace":
|
|
834
|
+
name, consumed = _scope_name(masked, after)
|
|
835
|
+
if name is None or split_name(name) is None:
|
|
836
|
+
raise ScanError(f"line {lineno}: a namespace with no readable name")
|
|
837
|
+
scopes.extend(("namespace", comp) for comp in split_name(name))
|
|
838
|
+
elif w == "section":
|
|
839
|
+
name, consumed = _scope_name(masked, after)
|
|
840
|
+
if name is not None and split_name(name) is None:
|
|
841
|
+
raise ScanError(f"line {lineno}: a section with no readable name")
|
|
842
|
+
scopes.extend(("section", comp) for comp in (split_name(name) if name else [None]))
|
|
843
|
+
else: # end: closes one scope per component
|
|
844
|
+
name, consumed = _scope_name(masked, after)
|
|
845
|
+
if name is not None and split_name(name) is None:
|
|
846
|
+
raise ScanError(f"line {lineno}: `end {name}` is not a name")
|
|
847
|
+
comps = list(_canon(split_name(name))) if name is not None else [None]
|
|
848
|
+
top = scopes[len(scopes) - len(comps):] if len(comps) <= len(scopes) else None
|
|
849
|
+
if not top or [comp if comp is None else _canon([comp])[0] for _k, comp in top] != comps or \
|
|
850
|
+
any(k_ == "mutual" for k_, _c in top):
|
|
851
|
+
opened = ".".join(comp for _k, comp in scopes if comp) or "nothing"
|
|
852
|
+
raise ScanError(f"line {lineno}: `end{' ' + name if name else ''}` does not close the "
|
|
853
|
+
f"innermost open scope (open: {opened})")
|
|
854
|
+
del scopes[len(scopes) - len(comps):]
|
|
855
|
+
else:
|
|
856
|
+
consumed = after
|
|
857
|
+
if cur is not None and cur["kind"] == "mutual" and cur["open"]:
|
|
858
|
+
raise ScanError(f"line {cur['start'] + 1}: a mutual block is never closed")
|
|
859
|
+
close()
|
|
860
|
+
return decls, context
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
def normalize(text: str) -> str:
|
|
864
|
+
"""The text for hashing: trailing whitespace stripped from each line, blank lines dropped, and the
|
|
865
|
+
indentation common to all lines removed, relative indentation kept (Lean layout is semantic). Pure
|
|
866
|
+
and idempotent; no trailing newline."""
|
|
867
|
+
lines = [ln.rstrip() for ln in text.replace("\r\n", "\n").split("\n")]
|
|
868
|
+
lines = [ln for ln in lines if ln]
|
|
869
|
+
if not lines:
|
|
870
|
+
return ""
|
|
871
|
+
lead = [ln[:len(ln) - len(ln.lstrip())] for ln in lines]
|
|
872
|
+
common = lead[0]
|
|
873
|
+
for p in lead[1:]:
|
|
874
|
+
while not p.startswith(common):
|
|
875
|
+
common = common[:-1]
|
|
876
|
+
return "\n".join(ln[len(common):] for ln in lines)
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def collapse_whitespace(text: str) -> str:
|
|
880
|
+
"""The text with every whitespace run collapsed to one space and the ends stripped: the second hash
|
|
881
|
+
of text/1, behind `whitespace_only` (a hint, never a pass)."""
|
|
882
|
+
return " ".join(text.split())
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
# identifiers (port_modules._TOKEN): dotted names, a «quoted» component whole
|
|
886
|
+
_TOKEN = re.compile(r"(?:«[^»\n]*»|[^\W\d][\w'!?]*)(?:\.(?:«[^»\n]*»|[^\W\d][\w'!?]*))*")
|
|
887
|
+
_PLAIN = re.compile(r"[^\W\d][\w'!?]*\Z")
|
|
888
|
+
_NS_POSITION = ("namespace", "section", "end", "open", "export")
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
def _canon(parts) -> tuple[str, ...]:
|
|
892
|
+
"""Name components compared as Lean does: `«foo»` is `foo` when the quotes are optional."""
|
|
893
|
+
return tuple(p[1:-1] if p.startswith("«") and p.endswith("»") and _PLAIN.match(p[1:-1]) else p
|
|
894
|
+
for p in parts)
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def _scope_parts(scope) -> tuple[str, ...]:
|
|
898
|
+
if isinstance(scope, str):
|
|
899
|
+
if not scope:
|
|
900
|
+
return ()
|
|
901
|
+
parts = split_name(scope)
|
|
902
|
+
if parts is None:
|
|
903
|
+
raise MapError(f"the scope {scope!r} is not a Lean name")
|
|
904
|
+
return _canon(parts)
|
|
905
|
+
return _canon(tuple(scope))
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def _map_pairs(pairs, what: str) -> list[tuple[tuple[str, ...], list[str], str, str]]:
|
|
909
|
+
items = list(pairs.items()) if hasattr(pairs, "items") else list(pairs)
|
|
910
|
+
out = []
|
|
911
|
+
for item in items:
|
|
912
|
+
if not (isinstance(item, (tuple, list)) and len(item) == 2):
|
|
913
|
+
raise MapError(f"{what}: {item!r} is not a (from, to) pair")
|
|
914
|
+
old, new = item
|
|
915
|
+
for name in (old, new):
|
|
916
|
+
if not is_name(name) or (split_name(name) or [""])[0] == "_root_":
|
|
917
|
+
raise MapError(f"{what}: {name!r} is not a Lean name")
|
|
918
|
+
out.append((_canon(split_name(old)), split_name(new), old, new))
|
|
919
|
+
return out
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
class _NameMap:
|
|
923
|
+
def __init__(self, namespaces, renames):
|
|
924
|
+
self.ns = _map_pairs(namespaces, "namespace map")
|
|
925
|
+
self.renames = _map_pairs(renames, "rename map")
|
|
926
|
+
for what, pairs in (("namespace map", self.ns), ("rename map", self.renames)):
|
|
927
|
+
seen: dict[tuple[str, ...], str] = {}
|
|
928
|
+
for key, new, old, _new_w in pairs:
|
|
929
|
+
if key in seen:
|
|
930
|
+
raise MapError(f"{what}: {old} is mapped twice")
|
|
931
|
+
if key == _canon(new):
|
|
932
|
+
raise MapError(f"{what}: {old} is mapped to itself")
|
|
933
|
+
seen[key] = old
|
|
934
|
+
tos: dict[tuple[str, ...], str] = {}
|
|
935
|
+
froms = {key for key, *_ in self.renames}
|
|
936
|
+
for _key, new, old, new_w in self.renames:
|
|
937
|
+
cn = _canon(new)
|
|
938
|
+
if cn in tos:
|
|
939
|
+
raise MapError(f"rename map: {tos[cn]} and {old} are both renamed to {new_w}")
|
|
940
|
+
tos[cn] = old
|
|
941
|
+
if cn in froms:
|
|
942
|
+
raise MapError(f"rename map: {old} -> {new_w} chains into another rename (ambiguous)")
|
|
943
|
+
self.rename = {key: new for key, new, _o, _n in self.renames}
|
|
944
|
+
self.ns_sorted = sorted(((key, new) for key, new, _o, _n in self.ns), key=lambda kv: -len(kv[0]))
|
|
945
|
+
|
|
946
|
+
def ns_map(self, parts: list[str], inclusive: bool) -> list[str] | None:
|
|
947
|
+
"""The namespace map applied to a name as written: the longest old prefix (the whole name too
|
|
948
|
+
when inclusive) replaced; None when no prefix matches."""
|
|
949
|
+
cp = _canon(parts)
|
|
950
|
+
for key, new in self.ns_sorted:
|
|
951
|
+
if cp[:len(key)] == key and (len(cp) > len(key) or inclusive):
|
|
952
|
+
return list(new) + list(parts[len(key):])
|
|
953
|
+
return None
|
|
954
|
+
|
|
955
|
+
def full(self, parts: list[str]) -> list[str]:
|
|
956
|
+
"""The new name of an old fully qualified name: its rename, else the namespace map, else itself."""
|
|
957
|
+
new = self.rename.get(_canon(parts))
|
|
958
|
+
if new is not None:
|
|
959
|
+
return list(new)
|
|
960
|
+
return self.ns_map(parts, False) or list(parts)
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
def _relative(parts: list[str], scope: tuple[str, ...]) -> list[str]:
|
|
964
|
+
"""A fully qualified name written relative to a scope: the longest leading run of scope components
|
|
965
|
+
it shares is dropped, keeping at least its last component."""
|
|
966
|
+
cp, j = _canon(parts), 0
|
|
967
|
+
while j < len(scope) and j < len(cp) - 1 and cp[j] == scope[j]:
|
|
968
|
+
j += 1
|
|
969
|
+
return list(parts[j:])
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def apply_map(text: str, namespaces=(), renames=(), *, src_scope=(), tgt_scope=None, declared=()) -> str:
|
|
973
|
+
"""The text with the namespace and rename maps applied to its identifiers, in one simultaneous pass.
|
|
974
|
+
|
|
975
|
+
`namespaces` and `renames` are mappings or (old, new) pairs of Lean names; rename keys are old fully
|
|
976
|
+
qualified names, and a rename takes precedence over the namespace map for its name. `src_scope` is the
|
|
977
|
+
namespace open where the text stands in the source (a dotted name or components, `Span.scope`);
|
|
978
|
+
`tgt_scope` the target's, by default the namespace map applied to `src_scope`. `declared` optionally
|
|
979
|
+
lists the old fully qualified names that exist, so a relative name resolves as Lean resolves it.
|
|
980
|
+
|
|
981
|
+
Only whole identifiers outside strings, character literals and comments are rewritten, never part of
|
|
982
|
+
a longer identifier, and never a name after `.` (a field or `.ctor` notation). For each identifier t:
|
|
983
|
+
- after `namespace`, `section`, `end`, `open` or `export` (and the further names of an `open`), the
|
|
984
|
+
namespace map applies to t as written, t itself included;
|
|
985
|
+
- else, for each namespace S' enclosing the text, innermost first, if S'.t is a renamed old name (or
|
|
986
|
+
is in `declared`), t becomes that name's new name written relative to the target scope;
|
|
987
|
+
- else, t written fully qualified (or `_root_.t`): a renamed old name becomes its new name, and a name
|
|
988
|
+
that starts with an old namespace and `.` gets the namespace map;
|
|
989
|
+
- else t is kept.
|
|
990
|
+
A dotted identifier is matched whole: `foo.mp` is not rewritten by a rename of `foo`.
|
|
991
|
+
|
|
992
|
+
Raises MapError for a malformed map, a name mapped twice or to itself, two names renamed to one, or a
|
|
993
|
+
rename chain or cycle (`A=B`, `B=C`), and ScanError for an unclosed comment, string or «» name."""
|
|
994
|
+
nm = _NameMap(namespaces, renames)
|
|
995
|
+
src = _scope_parts(src_scope)
|
|
996
|
+
tgt = _scope_parts(tgt_scope) if tgt_scope is not None else _canon(nm.ns_map(list(src), True) or src)
|
|
997
|
+
known = {_canon(split_name(d)) for d in declared if is_name(d)}
|
|
998
|
+
masked = _blank(text, _lex(text), _COMMENT_KINDS + ("string", "char"))
|
|
999
|
+
out: list[str] = []
|
|
1000
|
+
last, ns_run, prev_end = 0, False, -1
|
|
1001
|
+
for m in _TOKEN.finditer(masked):
|
|
1002
|
+
a, b, tok = m.start(), m.end(), m.group(0)
|
|
1003
|
+
gap = masked[prev_end:a] if prev_end >= 0 else "\n"
|
|
1004
|
+
in_run = ns_run and gap.strip() == "" and "\n" not in gap
|
|
1005
|
+
prev_end = b
|
|
1006
|
+
prev = masked[a - 1] if a else ""
|
|
1007
|
+
if prev and (prev.isalnum() or prev in "_'!?.»«"):
|
|
1008
|
+
ns_run = False # inside a longer identifier, or after `.`
|
|
1009
|
+
continue
|
|
1010
|
+
parts = split_name(tok)
|
|
1011
|
+
if parts is None or tok in ("in", "hiding", "renaming"):
|
|
1012
|
+
ns_run = False
|
|
1013
|
+
continue
|
|
1014
|
+
if in_run:
|
|
1015
|
+
ns_run = True # `open A B`, `open scoped A`
|
|
1016
|
+
new = None if tok == "scoped" else nm.ns_map(parts, True)
|
|
1017
|
+
elif tok in _NS_POSITION:
|
|
1018
|
+
ns_run = True
|
|
1019
|
+
continue
|
|
1020
|
+
else:
|
|
1021
|
+
ns_run = False
|
|
1022
|
+
new = _resolve(nm, parts, src, tgt, known)
|
|
1023
|
+
if new is not None:
|
|
1024
|
+
rendered = ".".join(new)
|
|
1025
|
+
if rendered != tok:
|
|
1026
|
+
out.append(text[last:a])
|
|
1027
|
+
out.append(rendered)
|
|
1028
|
+
last = b
|
|
1029
|
+
out.append(text[last:])
|
|
1030
|
+
return "".join(out)
|
|
1031
|
+
|
|
1032
|
+
|
|
1033
|
+
def _resolve(nm: _NameMap, parts: list[str], src: tuple[str, ...], tgt: tuple[str, ...], known) -> list[str] | None:
|
|
1034
|
+
"""The new spelling of one identifier (see apply_map), or None to keep it."""
|
|
1035
|
+
cp = _canon(parts)
|
|
1036
|
+
if cp[0] == "_root_":
|
|
1037
|
+
if len(parts) < 2:
|
|
1038
|
+
return None
|
|
1039
|
+
rest = parts[1:]
|
|
1040
|
+
new = nm.rename.get(_canon(rest))
|
|
1041
|
+
if new is None:
|
|
1042
|
+
new = nm.ns_map(rest, False)
|
|
1043
|
+
return None if new is None else ["_root_"] + list(new)
|
|
1044
|
+
for i in range(len(src), 0, -1):
|
|
1045
|
+
cand = list(src[:i]) + list(parts)
|
|
1046
|
+
cc = _canon(cand)
|
|
1047
|
+
if cc in nm.rename or cc in known:
|
|
1048
|
+
return _relative(nm.full(cand), tgt)
|
|
1049
|
+
new = nm.rename.get(cp)
|
|
1050
|
+
if new is not None:
|
|
1051
|
+
return list(new)
|
|
1052
|
+
return nm.ns_map(parts, False)
|
|
1053
|
+
|
|
1054
|
+
|
|
1055
|
+
# --------------------------------------------------------------------------
|
|
1056
|
+
# the statement of one theorem, as written (the verification page shows it beside the paper's)
|
|
1057
|
+
|
|
1058
|
+
STATEMENT_MAX_CHARS = 3000
|
|
1059
|
+
STATEMENT_MAX_LINES = 40
|
|
1060
|
+
_TOP_LINE = re.compile(r"\n(?:\||where\b|@\[|#[a-z]|(?:" + "|".join(KEYWORDS + MODIFIERS) +
|
|
1061
|
+
r"|end|namespace|section|open|variable|universe)\b)")
|
|
1062
|
+
|
|
1063
|
+
|
|
1064
|
+
# Statement-level words the proof boundary depends on. Each `let` / `letI` / `have` / `haveI` (and `let_fun`)
|
|
1065
|
+
# opener at bracket depth zero owns exactly one later `:=`, its value; only a `:=` no opener is waiting for ends
|
|
1066
|
+
# the statement. `match` and `fun` (or `λ`) allow `| pattern =>` alternatives on their own lines. A word that can hide a
|
|
1067
|
+
# statement-level `:=` the scanner does not track (a tactic block, `calc` steps, `do` reassignments) makes the
|
|
1068
|
+
# statement unreadable: None, never a prefix.
|
|
1069
|
+
_VALUE_OPENERS = ("let", "letI", "have", "haveI", "let_fun")
|
|
1070
|
+
_ALT_OPENERS = ("match", "fun")
|
|
1071
|
+
_UNSURE_WORDS = ("by", "calc", "do")
|
|
1072
|
+
_KEYWORD_AT = re.compile(r"(?<![\w'.!?«@])(" + "|".join(_VALUE_OPENERS + _ALT_OPENERS + _UNSURE_WORDS) +
|
|
1073
|
+
r")(?![\w'!?])")
|
|
1074
|
+
_EQUATION_ARM = re.compile(r"[ \t]*\|")
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def _arm_line(masked: str, i: int) -> bool:
|
|
1078
|
+
"""Is the line starting after the newline at masked[i] a `| pattern => ...` alternative: it opens with
|
|
1079
|
+
`|` and holds `=>` outside brackets (an absolute value line such as `|x| ≤ 1` has no `=>`)?"""
|
|
1080
|
+
if not _EQUATION_ARM.match(masked, i + 1):
|
|
1081
|
+
return False
|
|
1082
|
+
eol = masked.find("\n", i + 1)
|
|
1083
|
+
line = masked[i + 1:len(masked) if eol < 0 else eol]
|
|
1084
|
+
depth = 0
|
|
1085
|
+
for k, c in enumerate(line):
|
|
1086
|
+
if c in "([{⦃⟨":
|
|
1087
|
+
depth += 1
|
|
1088
|
+
elif c in ")]}⦄⟩":
|
|
1089
|
+
depth -= 1
|
|
1090
|
+
elif depth == 0 and line.startswith("=>", k):
|
|
1091
|
+
return True
|
|
1092
|
+
return False
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
def statement(text: str, qual: str, decls: list | None = None) -> str | None:
|
|
1096
|
+
"""The source text of the theorem or lemma whose fully qualified name is `qual`, from its keyword up
|
|
1097
|
+
to (not including) the `:=` that starts its proof; None when the file has no such declaration, has it
|
|
1098
|
+
more than once, its statement has no such `:=` (an equation-compiler or `where` form), or the statement
|
|
1099
|
+
is longer than STATEMENT_MAX_LINES lines / STATEMENT_MAX_CHARS characters.
|
|
1100
|
+
|
|
1101
|
+
The proof's `:=` is the first one outside every bracket that no `let`, `letI`, `have`, `haveI` or
|
|
1102
|
+
`let_fun` of the statement is waiting for: each such opener outside brackets owns exactly one later
|
|
1103
|
+
bracket-free `:=` (its value), so `theorem t :\n let n : Nat := 1\n n = 1 := by rfl` keeps its let
|
|
1104
|
+
value and its conclusion. Binder defaults (`{k : Nat := 3}`) and named arguments sit inside brackets.
|
|
1105
|
+
Where the scanner cannot be sure the statement is whole it returns None, never a prefix: a `by`, `calc`
|
|
1106
|
+
or `do` outside brackets before the proof's `:=`, a `| pattern =>` alternative line with no `match` or
|
|
1107
|
+
`fun` before it (an equation-compiler form), or a new top-level line.
|
|
1108
|
+
|
|
1109
|
+
Comments inside the statement (`/- ... -/`, nested as in Lean, and `--` to the end of the line) are kept
|
|
1110
|
+
as written: the brackets and the `:=` are found in the masked text, where comments and string literals
|
|
1111
|
+
are blanks, so a `:=`, a bracket or a `-/` inside a comment or a string never ends or unbalances the
|
|
1112
|
+
statement; a «quoted» name is skipped whole. A scanner, not a parser: when in doubt it returns None and
|
|
1113
|
+
the page links the file instead of showing a guess. `decls` is `declarations(text)` when the caller has
|
|
1114
|
+
it."""
|
|
1115
|
+
hits = [d for d in (declarations(text) if decls is None else decls)
|
|
1116
|
+
if d[1] in ("theorem", "lemma") and d[2] == qual]
|
|
1117
|
+
if len(hits) != 1:
|
|
1118
|
+
return None
|
|
1119
|
+
masked, _docs = _mask(text)
|
|
1120
|
+
starts, off = [], 0
|
|
1121
|
+
for ln in masked.split("\n"):
|
|
1122
|
+
starts.append(off)
|
|
1123
|
+
off += len(ln) + 1
|
|
1124
|
+
line = hits[0][0]
|
|
1125
|
+
m = re.compile(r"\b" + hits[0][1] + r"\b").search(masked, starts[line - 1])
|
|
1126
|
+
if not m:
|
|
1127
|
+
return None
|
|
1128
|
+
pairs = {"[": "]", "(": ")", "{": "}", "⦃": "⦄", "⟨": "⟩"}
|
|
1129
|
+
stack: list[str] = []
|
|
1130
|
+
pending = 0 # openers still waiting for their `:=`
|
|
1131
|
+
alternatives = False # a `match` / `fun` seen: `| p =>` lines belong to it
|
|
1132
|
+
i, end = m.end(), None
|
|
1133
|
+
limit = min(len(masked), m.start() + STATEMENT_MAX_CHARS)
|
|
1134
|
+
while i < limit:
|
|
1135
|
+
c = masked[i]
|
|
1136
|
+
if c == "«": # a quoted name is one token
|
|
1137
|
+
j = masked.find("»", i + 1)
|
|
1138
|
+
if j < 0:
|
|
1139
|
+
return None
|
|
1140
|
+
i = j + 1
|
|
1141
|
+
continue
|
|
1142
|
+
if c in pairs:
|
|
1143
|
+
stack.append(pairs[c])
|
|
1144
|
+
elif stack and c == stack[-1]:
|
|
1145
|
+
stack.pop()
|
|
1146
|
+
elif not stack and masked.startswith(":=", i):
|
|
1147
|
+
if pending:
|
|
1148
|
+
pending -= 1
|
|
1149
|
+
i += 2
|
|
1150
|
+
continue
|
|
1151
|
+
end = i
|
|
1152
|
+
break
|
|
1153
|
+
elif not stack and c == "\n":
|
|
1154
|
+
if _TOP_LINE.match(masked, i):
|
|
1155
|
+
return None # a new top-level line before any `:=`
|
|
1156
|
+
if not alternatives and _arm_line(masked, i):
|
|
1157
|
+
return None # an equation-compiler alternative: no statement `:=`
|
|
1158
|
+
elif not stack and c == "λ":
|
|
1159
|
+
alternatives = True
|
|
1160
|
+
elif not stack:
|
|
1161
|
+
w = _KEYWORD_AT.match(masked, i)
|
|
1162
|
+
if w and (i == 0 or not (masked[i - 1].isalnum() or masked[i - 1] in "_'.!?«@")):
|
|
1163
|
+
word = w.group(1)
|
|
1164
|
+
if word in _UNSURE_WORDS:
|
|
1165
|
+
return None
|
|
1166
|
+
if word in _VALUE_OPENERS:
|
|
1167
|
+
pending += 1
|
|
1168
|
+
else:
|
|
1169
|
+
alternatives = True
|
|
1170
|
+
i = w.end()
|
|
1171
|
+
continue
|
|
1172
|
+
i += 1
|
|
1173
|
+
if end is None:
|
|
1174
|
+
return None
|
|
1175
|
+
out = text[m.start():end].rstrip()
|
|
1176
|
+
lines = out.split("\n")
|
|
1177
|
+
if len(lines) > STATEMENT_MAX_LINES:
|
|
1178
|
+
return None
|
|
1179
|
+
first = text[starts[line - 1]:m.start()] # the keyword line's indentation: strip it
|
|
1180
|
+
base = len(first) - len(first.lstrip())
|
|
1181
|
+
return "\n".join([lines[0]] + [x[base:] if x[:base].strip() == "" else x.lstrip() for x in lines[1:]])
|
|
1182
|
+
|
|
1183
|
+
|
|
1184
|
+
# --------------------------------------------------------------------------
|
|
1185
|
+
# a statement declared in a module the Challenge imports (an umbrella Challenge.lean holds only imports)
|
|
1186
|
+
|
|
1187
|
+
IMPORT_MAX_DEPTH = 32 # import edges followed from the root module
|
|
1188
|
+
IMPORT_MAX_FILES = 1000 # package files read in one closure
|
|
1189
|
+
_HEADER_MODIFIERS = ("public", "private", "meta")
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
def header_imports(text: str) -> list[str]:
|
|
1193
|
+
"""The modules a Lean 4 file imports, as written («» kept): its header is an optional `module` and
|
|
1194
|
+
`prelude`, then `[public|private] [meta] import [all] Name` commands, comments anywhere; the first
|
|
1195
|
+
other token ends it."""
|
|
1196
|
+
masked, _docs = _mask(text)
|
|
1197
|
+
out: list[str] = []
|
|
1198
|
+
i, after_import, started = _skip_ws(masked, 0), False, False
|
|
1199
|
+
while i < len(masked):
|
|
1200
|
+
m = _NAME.match(masked, i)
|
|
1201
|
+
if not m:
|
|
1202
|
+
break
|
|
1203
|
+
tok = m.group(0)
|
|
1204
|
+
i = _skip_ws(masked, m.end())
|
|
1205
|
+
if after_import:
|
|
1206
|
+
if tok == "all":
|
|
1207
|
+
continue
|
|
1208
|
+
out.append(tok)
|
|
1209
|
+
after_import = False
|
|
1210
|
+
elif tok in ("module", "prelude") and not started:
|
|
1211
|
+
continue
|
|
1212
|
+
elif tok in _HEADER_MODIFIERS or tok == "import":
|
|
1213
|
+
started, after_import = True, tok == "import"
|
|
1214
|
+
else:
|
|
1215
|
+
break
|
|
1216
|
+
return out
|
|
1217
|
+
|
|
1218
|
+
|
|
1219
|
+
def module_file(module: str) -> str | None:
|
|
1220
|
+
"""Lake's source path of a module of the package, `A.B.C` -> `A/B/C.lean` (a «quoted» component is one
|
|
1221
|
+
path component); None when the name is malformed or a component could leave the package directory
|
|
1222
|
+
(empty, `.`, `..`, a path separator, a NUL)."""
|
|
1223
|
+
parts = split_name(module)
|
|
1224
|
+
if not parts:
|
|
1225
|
+
return None
|
|
1226
|
+
comps = []
|
|
1227
|
+
for p in parts:
|
|
1228
|
+
c = p[1:-1] if p.startswith("«") and p.endswith("»") else p
|
|
1229
|
+
if not c or c in (".", "..") or any(ch in c for ch in "/\\\0") or c != c.strip():
|
|
1230
|
+
return None
|
|
1231
|
+
comps.append(c)
|
|
1232
|
+
return "/".join(comps) + ".lean"
|
|
1233
|
+
|
|
1234
|
+
|
|
1235
|
+
def import_closure(read, root: str) -> tuple[list[tuple[str, str]], bool]:
|
|
1236
|
+
"""([(path, text)] of the package's own files in the import closure of module `root`, the root first),
|
|
1237
|
+
complete. `read(path)` returns the text of a file committed in the package, or None (not committed, or
|
|
1238
|
+
outside the package, such as Mathlib's modules: their imports are not followed). Breadth first, each
|
|
1239
|
+
file once (cycle-safe); complete is False when a module name cannot be a package path, or the walk
|
|
1240
|
+
stopped at IMPORT_MAX_DEPTH or IMPORT_MAX_FILES with imports left to read."""
|
|
1241
|
+
out: list[tuple[str, str]] = []
|
|
1242
|
+
seen: set[str] = set()
|
|
1243
|
+
complete = True
|
|
1244
|
+
frontier = [root]
|
|
1245
|
+
depth = 0
|
|
1246
|
+
while frontier:
|
|
1247
|
+
nxt: list[str] = []
|
|
1248
|
+
for module in frontier:
|
|
1249
|
+
rel = module_file(module)
|
|
1250
|
+
if rel is None:
|
|
1251
|
+
complete = False
|
|
1252
|
+
continue
|
|
1253
|
+
if rel in seen:
|
|
1254
|
+
continue
|
|
1255
|
+
seen.add(rel)
|
|
1256
|
+
if len(out) >= IMPORT_MAX_FILES:
|
|
1257
|
+
return out, False
|
|
1258
|
+
text = read(rel)
|
|
1259
|
+
if text is None:
|
|
1260
|
+
continue
|
|
1261
|
+
out.append((rel, text))
|
|
1262
|
+
nxt += header_imports(text)
|
|
1263
|
+
if nxt and depth >= IMPORT_MAX_DEPTH:
|
|
1264
|
+
return out, False
|
|
1265
|
+
frontier, depth = nxt, depth + 1
|
|
1266
|
+
return out, complete
|
|
1267
|
+
|
|
1268
|
+
|
|
1269
|
+
class DeclarationIndex:
|
|
1270
|
+
"""The declarations of a module's import closure within the package, read once; `statement(qual)`
|
|
1271
|
+
finds the one file that declares `qual` and copies its statement from there."""
|
|
1272
|
+
|
|
1273
|
+
def __init__(self, read, root: str):
|
|
1274
|
+
self.files, self.complete = import_closure(read, root)
|
|
1275
|
+
self._decls: dict[str, list] = {}
|
|
1276
|
+
self.by_name: dict[str, list[tuple[str, int, str]]] = {}
|
|
1277
|
+
for rel, text in self.files:
|
|
1278
|
+
ds = declarations(text)
|
|
1279
|
+
self._decls[rel] = ds
|
|
1280
|
+
for d in ds:
|
|
1281
|
+
self.by_name.setdefault(d[2], []).append((rel, d[0], d[1]))
|
|
1282
|
+
self._text = dict(self.files)
|
|
1283
|
+
|
|
1284
|
+
def statement(self, qual: str) -> dict:
|
|
1285
|
+
"""{file, line, text, reason}: the declaring file and the keyword's line, with the copied statement;
|
|
1286
|
+
text None and a reason when the closure is incomplete, the name is declared in no file or in more
|
|
1287
|
+
than one, it is not a theorem or lemma, or `statement` refuses it. When the name is not declared
|
|
1288
|
+
anywhere, file is the root module's file and line None."""
|
|
1289
|
+
root = self.files[0][0] if self.files else None
|
|
1290
|
+
hits = self.by_name.get(qual) or []
|
|
1291
|
+
if not self.complete:
|
|
1292
|
+
return {"file": root, "line": None, "text": None, "reason": "the import closure was not read in full"}
|
|
1293
|
+
if not hits:
|
|
1294
|
+
return {"file": root, "line": None, "text": None, "reason": "declared in no file of the closure"}
|
|
1295
|
+
if len(hits) > 1:
|
|
1296
|
+
return {"file": root, "line": None, "text": None, "reason": "declared more than once"}
|
|
1297
|
+
rel, line, kw = hits[0]
|
|
1298
|
+
text = statement(self._text[rel], qual, self._decls[rel]) if kw in ("theorem", "lemma") else None
|
|
1299
|
+
return {"file": rel, "line": line, "text": text,
|
|
1300
|
+
"reason": None if text is not None else "the statement could not be copied"}
|