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,217 @@
1
+ # lean-pkg statements module -- the one trusted module of `Prop` definitions a Challenge may import
2
+ """The statements module of a package with conditional claims (proposal 0003, #320, #369).
3
+
4
+ A conditional claim names its hypotheses (`hypotheses: [Hyp.A]` in claims.yaml), and the discharge rule
5
+ compares Challenge types without unfolding, so the Challenge must name `Hyp.A` itself. That needs one module
6
+ of `Prop` definitions that the Challenge and the Solution both import. The maintainer's decision on #320:
7
+ a Challenge may import one declared, trusted statements module; the page links it; `palomar check` warns.
8
+
9
+ The declaration is the optional top-level key of claims.yaml (claims/1, additive)::
10
+
11
+ schema: claims/1
12
+ package: demo
13
+ statements_module: Demo.Statements # exactly one Lean module name
14
+ claims: [...]
15
+
16
+ claims.yaml holds it because it is the file that names the hypotheses, it is read at the commit every
17
+ check binds, and it is lean-pkg's own file (a comparator configuration takes only Palomar's six keys).
18
+
19
+ Two checks:
20
+
21
+ - `key_errors(value)` (the schema, in `claims.validate_claims`): one module name, not a list, not a path,
22
+ not a module of Mathlib or Lean core, and one that Lake can map to a file in the package.
23
+ - `problems(read, module, commit)` (at a commit: `claims sync`, `claims check NAME`, the gate's claims
24
+ check): the module's file is committed in the package at that commit, imports only Mathlib (and the
25
+ modules Mathlib brings in), and holds only `Prop` definitions: each declaration a `def`, `abbrev`,
26
+ `inductive` or `structure` whose written type ends in `Prop`, with no theorem, lemma, axiom, opaque, instance, example,
27
+ `sorry` or other command beyond namespace, section, open, universe, variable and set_option. This is a
28
+ text check by lean-pkg's scanner (`lean_scan.decl_spans`), not Lean's elaborator: it reads what is
29
+ written, so a reader must still read the module, which is part of the trusted statement.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import re
35
+
36
+ from . import core
37
+ from . import lean_scan
38
+
39
+ KEY = "statements_module"
40
+ # Module roots a Challenge may import without a declaration: Mathlib, and what Mathlib brings in (the same
41
+ # list comparator_types.VOCAB_ROOTS uses to tell Mathlib vocabulary from project definitions).
42
+ VOCAB_ROOTS = ("Init", "Std", "Lean", "Mathlib", "Batteries", "Aesop", "Qq", "ProofWidgets", "Plausible",
43
+ "ImportGraph", "LeanSearchClient")
44
+ DEF_KINDS = ("def", "abbrev", "inductive", "structure")
45
+ CONTEXT_KINDS = ("module", "prelude", "import", "namespace", "section", "end", "open", "universe", "variable",
46
+ "set_option")
47
+ TEXT_CHECK = "a text check by lean-pkg's scanner, not Lean's elaborator"
48
+ _SORRY = re.compile(r"(?<![\w'.!?«])sorry(?![\w'!?])")
49
+ _WHERE = re.compile(r"where(?![\w'!?])")
50
+ _INSTANCE_ATTR = re.compile(r"@\[[^\]]*\binstance\b")
51
+ _OPEN = {"(": ")", "[": "]", "{": "}", "⦃": "⦄", "⟨": "⟩"}
52
+ _CLOSE = set(_OPEN.values())
53
+
54
+
55
+ def root(module: str) -> str:
56
+ parts = lean_scan.split_name(module) or [module]
57
+ p = parts[0]
58
+ return p[1:-1] if p.startswith("«") and p.endswith("»") else p
59
+
60
+
61
+ def is_vocabulary(module: str) -> bool:
62
+ """A module of Mathlib, Lean core or a library Mathlib brings in: never a module of the package."""
63
+ return root(module) in VOCAB_ROOTS
64
+
65
+
66
+ def key_errors(v) -> list[str]:
67
+ """The schema errors of a `statements_module` value ([] when it is one well-formed module name)."""
68
+ where = KEY
69
+ if isinstance(v, list):
70
+ return [f"{where} names exactly one module, got a list of {len(v)}: a package has one statements "
71
+ f"module (put every hypothesis in it)"]
72
+ if not isinstance(v, str) or not v.strip():
73
+ return [f"{where} must be one Lean module name such as Demo.Statements, got {v!r} (omit the key when "
74
+ f"the package has no statements module)"]
75
+ if v.endswith(".lean") or "/" in v or "\\" in v:
76
+ return [f"{where} must be a Lean module name (Demo.Statements), not a path, got {v!r}"]
77
+ if v == "TODO" or not lean_scan.is_name(v):
78
+ return [f"{where} must be a Lean module name such as Demo.Statements, got {v!r}"]
79
+ if lean_scan.module_file(v) is None:
80
+ return [f"{where} {v!r} does not name a file inside the package (an empty, `.` or `..` component)"]
81
+ if is_vocabulary(v):
82
+ return [f"{where} {v!r} is a module of {root(v)}, not of the package: a Challenge imports Mathlib "
83
+ f"without a declaration; the statements module is the package's own"]
84
+ return []
85
+
86
+
87
+ def declared(doc) -> str | None:
88
+ """The declared module of a loaded claims document when the key is well formed, else None."""
89
+ v = doc.get(KEY) if isinstance(doc, dict) else None
90
+ return v if isinstance(v, str) and not key_errors(v) else None
91
+
92
+
93
+ def _depth0(code: str, stop) -> int:
94
+ """The index of the first position at bracket depth 0 where `stop(code, i)` holds, else -1."""
95
+ depth = 0
96
+ i = 0
97
+ while i < len(code):
98
+ ch = code[i]
99
+ if ch == "«":
100
+ j = code.find("»", i + 1)
101
+ i = len(code) if j < 0 else j + 1
102
+ continue
103
+ if ch in _OPEN:
104
+ depth += 1
105
+ elif ch in _CLOSE:
106
+ depth -= 1
107
+ elif depth == 0 and stop(code, i):
108
+ return i
109
+ i += 1
110
+ return -1
111
+
112
+
113
+ def written_type(code: str) -> str | None:
114
+ """The type a declaration's header writes after its last top-level `:` (comments blanked), or None."""
115
+ def ends(c: str, i: int) -> bool:
116
+ if c.startswith(":=", i) or c[i] == "|": # a value, a constructor or an equation arm
117
+ return True
118
+ return _WHERE.match(c, i) is not None and (i == 0 or not (c[i - 1].isalnum() or c[i - 1] in "_'.!?»"))
119
+ end = _depth0(code, ends)
120
+ head = code if end < 0 else code[:end]
121
+ colons = []
122
+ depth = 0
123
+ for i, ch in enumerate(head):
124
+ if ch in _OPEN:
125
+ depth += 1
126
+ elif ch in _CLOSE:
127
+ depth -= 1
128
+ elif depth == 0 and ch == ":" and not head.startswith(":=", i):
129
+ colons.append(i)
130
+ return " ".join(head[colons[-1] + 1:].split()) if colons else None
131
+
132
+
133
+ def is_prop_type(t: str | None) -> bool:
134
+ """`Prop`, or a function type whose last top-level arrow target is `Prop` (`ℕ → Prop`)."""
135
+ if not t:
136
+ return False
137
+ last = t
138
+ for arrow in ("→", "->"):
139
+ k = _rfind_depth0(last, arrow)
140
+ if k >= 0:
141
+ last = last[k + len(arrow):]
142
+ return last.strip() == "Prop"
143
+
144
+
145
+ def _rfind_depth0(s: str, sub: str) -> int:
146
+ found, depth = -1, 0
147
+ for i, ch in enumerate(s):
148
+ if ch in _OPEN:
149
+ depth += 1
150
+ elif ch in _CLOSE:
151
+ depth -= 1
152
+ elif depth == 0 and s.startswith(sub, i):
153
+ found = i
154
+ return found
155
+
156
+
157
+ def content_problems(text: str, module: str, rel: str) -> list[str]:
158
+ """What the scanner finds in the module's text beyond `Prop` definitions; [] when it finds nothing."""
159
+ try:
160
+ decls, context = lean_scan.decl_spans(text, module)
161
+ except lean_scan.ScanError as e:
162
+ return [f"{rel}: lean-pkg's text scanner cannot read it ({e}); a statements module must be one it can "
163
+ f"read"]
164
+ out: list[tuple[int, str]] = []
165
+ for m in lean_scan.header_imports(text):
166
+ if not is_vocabulary(m):
167
+ out.append((0, f"{rel} imports {m}: a statements module imports Mathlib (and Lean core) only"))
168
+ for s in context:
169
+ if s.kind not in CONTEXT_KINDS:
170
+ out.append((s.start, f"{rel} line {s.start}: `{s.kind}` command: a statements module holds only Prop "
171
+ f"definitions (and namespace, section, open, universe, variable, set_option)"))
172
+ for s in decls:
173
+ what = f"{s.kind} {', '.join(s.names)}" if s.names else f"an anonymous {s.kind}"
174
+ if s.kind not in DEF_KINDS:
175
+ out.append((s.start, f"{rel} line {s.start}: {what}: a statements module holds only Prop definitions "
176
+ f"(no theorem, lemma, axiom, opaque, instance or example)"))
177
+ continue
178
+ if _INSTANCE_ATTR.search(s.code):
179
+ out.append((s.start, f"{rel} line {s.start}: {what} has an instance attribute: a statements module "
180
+ f"holds no instance"))
181
+ if _SORRY.search(s.code):
182
+ out.append((s.start, f"{rel} line {s.start}: {what} uses sorry: a hypothesis is a definition, never "
183
+ f"a sorry"))
184
+ t = written_type(s.code)
185
+ if not is_prop_type(t):
186
+ out.append((s.start, f"{rel} line {s.start}: {what} is not a Prop definition (its written type is "
187
+ f"{('`' + t + '`') if t else 'missing'}, not `Prop` or `... → Prop`)"))
188
+ return [msg for _line, msg in sorted(out, key=lambda x: x[0])]
189
+
190
+
191
+ def problems(read, module: str, commit: str) -> list[str]:
192
+ """The refusals of a declared, well-formed module at `commit`: `read(rel)` returns the text of a file
193
+ committed in the package there, or None."""
194
+ rel = lean_scan.module_file(module) or module
195
+ text = read(rel)
196
+ if text is None:
197
+ return [f"{KEY} {module}: {rel} is not committed in the package at {commit[:12]} (untracked files do "
198
+ f"not count)"]
199
+ found = content_problems(text, module, rel)
200
+ return [f"{KEY} {module}: {p} ({TEXT_CHECK})" for p in found]
201
+
202
+
203
+ def at_commit(repo, claims_rel: str, commit: str) -> tuple[str | None, list[str]]:
204
+ """(declared module or None, its problems) from the claims file committed at `commit`; (None, []) when
205
+ the file or the key is absent, or the file cannot be read (the schema check reports that)."""
206
+ from . import claims as claims_mod
207
+ raw = core.git_show_bytes(repo, claims_rel, commit)
208
+ if raw is None:
209
+ return None, []
210
+ try:
211
+ doc = claims_mod.load_claims_text(raw.decode("utf-8", errors="replace"), claims_rel)
212
+ except core.Fail:
213
+ return None, []
214
+ mod = declared(doc)
215
+ if mod is None:
216
+ return None, []
217
+ return mod, problems(claims_mod._reader(repo, commit), mod, commit)
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,225 @@
1
+ # lean-pkg toolchain advisories -- Lean toolchains with a known kernel or runtime soundness bug
2
+ """The shipped list `data/toolchain-advisories.yaml` (schema `lean-pkg-toolchain-advisories/1`) and the
3
+ match of a toolchain string against it (issue #237).
4
+
5
+ A receipt made on an affected toolchain is weaker evidence than one made on the fixed release, so `gate`
6
+ (and `gate --check`), `receipt check` and `palomar check` print one WARN line per matching advisory and add
7
+ `toolchain_advisories[]` to their JSON. They never refuse because of it: the proofs may well be fine, and
8
+ independent kernel replay (comparator with nanoda) mitigates several of these bugs.
9
+
10
+ The file, validated strictly when loaded (closed key sets; any problem raises AdvisoryError):
11
+
12
+ schema: lean-pkg-toolchain-advisories/1
13
+ advisories: # a non-empty list
14
+ - id: TEXT # unique; lower case letters, digits, '.', '-'
15
+ summary: TEXT # one paragraph, what the bug lets through
16
+ affected:
17
+ below: vX.Y.Z # every release or rc that sorts below this one (required)
18
+ also: [vX.Y.Z-rcN, ...] # releases at or above `below` that lack the fix anyway (optional)
19
+ nightlies_through: DATE # nightly-YYYY-MM-DD dated on or before DATE (optional)
20
+ fixed_in: vX.Y.Z # the first stable release with the fix; it must not be affected
21
+ links: [https://..., ...] # primary sources: the release notes, the lean4 issue and pull request
22
+ date_added: YYYY-MM-DD
23
+
24
+ Toolchain strings: `[leanprover/lean4:]vX.Y.Z[-rcN]` (a release; an rc sorts before its release), and
25
+ `leanprover/lean4:nightly-YYYY-MM-DD` or `leanprover/lean4-nightly:nightly-YYYY-MM-DD` (a nightly). Anything
26
+ else (a channel name such as `stable`, a pull-request toolchain, a local build) matches no advisory.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import datetime
32
+ import functools
33
+ import pathlib
34
+ import re
35
+
36
+ SCHEMA = "lean-pkg-toolchain-advisories/1"
37
+ DATA_PATH = pathlib.Path(__file__).resolve().parent / "data" / "toolchain-advisories.yaml"
38
+ TOP_KEYS = ("schema", "advisories")
39
+ ENTRY_KEYS = ("id", "summary", "affected", "fixed_in", "links", "date_added")
40
+ AFFECTED_KEYS = ("below", "also", "nightlies_through")
41
+ AFFECTED_REQUIRED = ("below",)
42
+ _ID_RE = re.compile(r"^[a-z0-9][a-z0-9.\-]*$")
43
+ _RELEASE_RE = re.compile(r"^(?:leanprover/lean4:)?v(\d+)\.(\d+)\.(\d+)(?:-rc(\d+))?$")
44
+ _NIGHTLY_RE = re.compile(r"^leanprover/lean4(?:-nightly)?:nightly-(\d{4}-\d{2}-\d{2})$")
45
+ _VERSION_RE = re.compile(r"^v\d+\.\d+\.\d+(?:-rc\d+)?$")
46
+
47
+
48
+ class AdvisoryError(ValueError):
49
+ """The advisories file is malformed (raised by load())."""
50
+
51
+
52
+ def release_key(text) -> tuple[int, int, int, int, int] | None:
53
+ """Sort key of `[leanprover/lean4:]vX.Y.Z[-rcN]`, else None: (X, Y, Z, 0, N) for an rc, (X, Y, Z, 1, 0)
54
+ for the release, so an rc sorts before its release (the same order as audit.parse_lean_toolchain)."""
55
+ m = _RELEASE_RE.match(str(text or "").strip())
56
+ if not m:
57
+ return None
58
+ major, minor, patch, rc = m.groups()
59
+ return (int(major), int(minor), int(patch)) + ((0, int(rc)) if rc is not None else (1, 0))
60
+
61
+
62
+ def nightly_date(text) -> datetime.date | None:
63
+ m = _NIGHTLY_RE.match(str(text or "").strip())
64
+ if not m:
65
+ return None
66
+ try:
67
+ return datetime.date.fromisoformat(m.group(1))
68
+ except ValueError:
69
+ return None
70
+
71
+
72
+ def _date(value, where: str) -> datetime.date:
73
+ if isinstance(value, datetime.datetime):
74
+ raise AdvisoryError(f"{where}: {value!r} is not a date (YYYY-MM-DD)")
75
+ if isinstance(value, datetime.date):
76
+ return value
77
+ if isinstance(value, str):
78
+ try:
79
+ return datetime.date.fromisoformat(value)
80
+ except ValueError:
81
+ pass
82
+ raise AdvisoryError(f"{where}: {value!r} is not a date (YYYY-MM-DD)")
83
+
84
+
85
+ def _version(value, where: str, stable: bool = False) -> str:
86
+ if not isinstance(value, str) or not _VERSION_RE.match(value):
87
+ raise AdvisoryError(f"{where}: {value!r} is not a Lean version vX.Y.Z[-rcN]")
88
+ if stable and "-rc" in value:
89
+ raise AdvisoryError(f"{where}: {value!r} is a release candidate; name the first stable release")
90
+ return value
91
+
92
+
93
+ def _closed(d, keys: tuple[str, ...], required: tuple[str, ...], where: str) -> dict:
94
+ if not isinstance(d, dict):
95
+ raise AdvisoryError(f"{where}: expected a mapping, got {type(d).__name__}")
96
+ unknown = sorted(str(k) for k in d if k not in keys)
97
+ if unknown:
98
+ raise AdvisoryError(f"{where}: unknown key(s) {', '.join(unknown)} (allowed: {', '.join(keys)})")
99
+ missing = [k for k in required if k not in d]
100
+ if missing:
101
+ raise AdvisoryError(f"{where}: missing key(s) {', '.join(missing)}")
102
+ return d
103
+
104
+
105
+ def validate(doc) -> list[dict]:
106
+ """The advisories of a parsed file, normalized (dates as YYYY-MM-DD strings, `also` always a list,
107
+ `nightlies_through` None when absent); AdvisoryError on the first problem."""
108
+ _closed(doc, TOP_KEYS, TOP_KEYS, "toolchain advisories")
109
+ if doc["schema"] != SCHEMA:
110
+ raise AdvisoryError(f"toolchain advisories: schema {doc['schema']!r} is not {SCHEMA!r}")
111
+ entries = doc["advisories"]
112
+ if not isinstance(entries, list) or not entries:
113
+ raise AdvisoryError("toolchain advisories: `advisories` must be a non-empty list")
114
+ out, seen = [], set()
115
+ for i, e in enumerate(entries):
116
+ where = f"advisories[{i}]"
117
+ _closed(e, ENTRY_KEYS, ENTRY_KEYS, where)
118
+ aid = e["id"]
119
+ if not isinstance(aid, str) or not _ID_RE.match(aid):
120
+ raise AdvisoryError(f"{where}.id: {aid!r} is not lower case letters, digits, '.' and '-'")
121
+ if aid in seen:
122
+ raise AdvisoryError(f"{where}.id: {aid!r} is not unique")
123
+ seen.add(aid)
124
+ where = f"advisory {aid}"
125
+ summary = e["summary"]
126
+ if not isinstance(summary, str) or not summary.strip() or "\n" in summary.strip():
127
+ raise AdvisoryError(f"{where}.summary: a non-empty, one-paragraph string is required")
128
+ links = e["links"]
129
+ if not isinstance(links, list) or not links:
130
+ raise AdvisoryError(f"{where}.links: a non-empty list of https URLs is required")
131
+ for u in links:
132
+ if not isinstance(u, str) or not re.match(r"^https://[^\s<>()\[\]`|]+$", u):
133
+ raise AdvisoryError(f"{where}.links: {u!r} is not an https URL")
134
+ if len(set(links)) != len(links):
135
+ raise AdvisoryError(f"{where}.links: a link is listed twice")
136
+ aff = _closed(e["affected"], AFFECTED_KEYS, AFFECTED_REQUIRED, f"{where}.affected")
137
+ below = _version(aff["below"], f"{where}.affected.below")
138
+ also = aff.get("also", [])
139
+ if not isinstance(also, list):
140
+ raise AdvisoryError(f"{where}.affected.also: expected a list of Lean versions")
141
+ also = [_version(v, f"{where}.affected.also") for v in also]
142
+ if len(set(also)) != len(also):
143
+ raise AdvisoryError(f"{where}.affected.also: a version is listed twice")
144
+ for v in also:
145
+ if release_key(v) < release_key(below):
146
+ raise AdvisoryError(f"{where}.affected.also: {v} sorts below {below} and is affected already")
147
+ nightly = aff.get("nightlies_through")
148
+ nightly = _date(nightly, f"{where}.affected.nightlies_through").isoformat() if nightly is not None else None
149
+ fixed = _version(e["fixed_in"], f"{where}.fixed_in", stable=True)
150
+ entry = {"id": aid, "summary": " ".join(summary.split()), "fixed_in": fixed, "links": list(links),
151
+ "date_added": _date(e["date_added"], f"{where}.date_added").isoformat(),
152
+ "affected": {"below": below, "also": also, "nightlies_through": nightly}}
153
+ if affected(entry, fixed):
154
+ raise AdvisoryError(f"{where}.fixed_in: {fixed} is itself affected by the `affected` rule")
155
+ out.append(entry)
156
+ return out
157
+
158
+
159
+ def load_file(path: pathlib.Path) -> list[dict]:
160
+ import yaml
161
+ try:
162
+ doc = yaml.safe_load(pathlib.Path(path).read_text(encoding="utf-8"))
163
+ except (OSError, UnicodeDecodeError, yaml.YAMLError) as e:
164
+ raise AdvisoryError(f"toolchain advisories {path}: unreadable ({e})") from None
165
+ return validate(doc)
166
+
167
+
168
+ @functools.lru_cache(maxsize=None)
169
+ def _load_cached(path: str) -> tuple[dict, ...]:
170
+ return tuple(load_file(pathlib.Path(path)))
171
+
172
+
173
+ def load() -> list[dict]:
174
+ """The shipped advisories (validated; cached per path)."""
175
+ return list(_load_cached(str(DATA_PATH)))
176
+
177
+
178
+ def affected(entry: dict, toolchain) -> bool:
179
+ """True when the toolchain string falls under the entry's `affected` rule."""
180
+ aff = entry["affected"]
181
+ key = release_key(toolchain)
182
+ if key is not None:
183
+ return key < release_key(aff["below"]) or any(key == release_key(v) for v in aff["also"])
184
+ day = nightly_date(toolchain)
185
+ if day is not None and aff["nightlies_through"]:
186
+ return day <= datetime.date.fromisoformat(aff["nightlies_through"])
187
+ return False
188
+
189
+
190
+ def matches(toolchain, advisories: list[dict] | None = None) -> list[dict]:
191
+ """The JSON view of every advisory the toolchain string is affected by, in file order:
192
+ {id, toolchain, summary, fixed_in, links, date_added}. An empty or unparsed toolchain matches none."""
193
+ tc = str(toolchain or "").strip()
194
+ if not tc:
195
+ return []
196
+ return [{"id": e["id"], "toolchain": tc, "summary": e["summary"], "fixed_in": e["fixed_in"],
197
+ "links": list(e["links"]), "date_added": e["date_added"]}
198
+ for e in (load() if advisories is None else advisories) if affected(e, tc)]
199
+
200
+
201
+ def warn_line(view: dict) -> str:
202
+ """One WARN line for a matching advisory: the advisory, the toolchain, the fixed release, the link."""
203
+ return (f"WARN: toolchain advisory {view['id']}: {view['toolchain']} has a known Lean soundness bug, "
204
+ f"fixed in {view['fixed_in']}; {view['links'][0]} (a warning, not a refusal; a receipt made on "
205
+ f"{view['fixed_in']} or later is stronger evidence)")
206
+
207
+
208
+ def lookup(toolchains) -> tuple[list[dict], str | None]:
209
+ """(matches, problem) for one or more toolchain strings (duplicates collapse). A malformed shipped file
210
+ never breaks a command: it yields no matches and a WARN line naming the problem."""
211
+ if isinstance(toolchains, str) or toolchains is None:
212
+ toolchains = [toolchains]
213
+ try:
214
+ out: list[dict] = []
215
+ for tc in dict.fromkeys(str(t or "").strip() for t in toolchains):
216
+ out += matches(tc)
217
+ except AdvisoryError as e:
218
+ return [], f"WARN: toolchain advisories could not be read ({e})"
219
+ return out, None
220
+
221
+
222
+ def warn_lines(toolchains) -> tuple[list[dict], list[str]]:
223
+ """(matches, the WARN lines to print): one line per match, or the one line naming a read problem."""
224
+ found, problem = lookup(toolchains)
225
+ return found, ([problem] if problem else [warn_line(v) for v in found])