agent-formal-verify 0.4.12 → 0.4.14
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.
- package/CHANGES.md +150 -0
- package/README.md +5 -3
- package/package.json +2 -1
- package/skills/formal-verify/SKILL.md +17 -19
- package/skills/formal-verify/examples/kani-template/src/lib.rs +5 -6
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +10 -45
- package/skills/formal-verify/examples/tla-template/BoundedQueue.matrix +16 -13
- package/skills/formal-verify/examples/tla-template/BoundedQueue.mutations +92 -14
- package/skills/formal-verify/examples/tla-template/BoundedQueue.tla +169 -28
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +33 -3
- package/skills/formal-verify/references/lean-brief.md +2 -2
- package/skills/formal-verify/references/rust-brief.md +58 -6
- package/skills/formal-verify/references/setup.md +23 -7
- package/skills/formal-verify/references/tla-brief.md +3 -3
- package/skills/formal-verify/scripts/baseline.py +290 -261
- package/skills/formal-verify/scripts/kani-check.sh +3 -1
- package/skills/formal-verify/scripts/kani.py +127 -59
- package/skills/formal-verify/scripts/kani_reader.py +592 -0
- package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
- package/skills/formal-verify/scripts/lean-check.sh +6 -243
- package/skills/formal-verify/scripts/lean.py +484 -0
- package/skills/formal-verify/scripts/lean_mutations.py +195 -0
- package/skills/formal-verify/scripts/lean_records.py +25 -0
- package/skills/formal-verify/scripts/mutate.py +81 -195
- package/skills/formal-verify/scripts/processes.py +266 -0
- package/skills/formal-verify/scripts/python-tools.sh +15 -0
- package/skills/formal-verify/scripts/runner.py +56 -0
- package/skills/formal-verify/scripts/rust_source.py +74 -0
- package/skills/formal-verify/scripts/setup.sh +18 -19
- package/skills/formal-verify/scripts/storage.py +207 -0
- package/skills/formal-verify/scripts/surface.py +27 -0
- package/skills/formal-verify/scripts/sync.py +401 -0
- package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
- package/skills/formal-verify/scripts/tlc.py +501 -117
- package/skills/formal-verify/scripts/tlc_report.py +516 -0
- package/skills/formal-verify/scripts/tlc_trace.py +167 -0
- package/skills/setup/SKILL.md +1 -1
- package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
- package/skills/formal-verify/scripts/lean-statements.py +0 -161
- package/skills/formal-verify/scripts/lean-tools.sh +0 -24
- package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
- package/skills/formal-verify/scripts/tlc-trace.py +0 -64
|
@@ -13,66 +13,51 @@ change, and so is an added item whose kind narrows what is checked.
|
|
|
13
13
|
and the normalized definitions of Spec,
|
|
14
14
|
of each operator a check or reach line names, and of the operators those
|
|
15
15
|
reference through local EXTENDS. Local INSTANCE substitutions retain their whole module tree.
|
|
16
|
-
.rs Kani. Each qualified harness name
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
.rs Kani. Each qualified harness name with its #[kani::should_panic] and
|
|
17
|
+
#[kani::unwind(...)] attributes and the #[cfg(...)] attributes other
|
|
18
|
+
than cfg(kani), and the #[cfg_attr(..., cfg(...))] ones, on it, its enclosing
|
|
19
|
+
items, the file and each out-of-line mod declaration that leads to the file from a crate root, through
|
|
20
|
+
#[path], with each route in the file's crates that the record cannot read, such as a mod
|
|
21
|
+
declaration inside a macro, and each kani::assume, kani::any_where, kani::cover! and
|
|
22
|
+
#[kani::stub] with its owning free function, under inline modules. Unsupported owners fail. Added covers and harnesses are allowed.
|
|
19
23
|
Added assumes and stubs are changes.
|
|
24
|
+
In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
|
|
25
|
+
each harness it compiles there a module path that a route the record reads gives, and a harness
|
|
26
|
+
that no longer compiles is a change.
|
|
20
27
|
|
|
21
28
|
Usage:
|
|
22
29
|
baseline.py record <record-file> <model-file>... record these files, keep the other entries
|
|
23
30
|
baseline.py compare <record-file> exit 1 when a recorded file changed
|
|
31
|
+
baseline.py move <record-file> <old> <new> [--module OLD NEW]
|
|
32
|
+
compare old's entry with new from now on
|
|
24
33
|
|
|
25
34
|
Compare prints UNCHANGED or CHANGED per file, indented lines for each item that
|
|
26
|
-
changed, and a SUMMARY line.
|
|
27
|
-
|
|
35
|
+
changed, and a SUMMARY line. It prints NOT CHECKED for an unchanged Kani file in a
|
|
36
|
+
Cargo package that record could not check against Kani. Move prints MOVED; it reads only the record, never
|
|
37
|
+
the new file, and with --module renames the recorded Kani owners under module
|
|
38
|
+
OLD to sit under NEW. Exit codes: 0 unchanged, 1 changed or a record or model
|
|
39
|
+
file that fails to parse, 2 usage error.
|
|
28
40
|
"""
|
|
29
41
|
import argparse
|
|
30
42
|
import hashlib
|
|
31
|
-
import importlib.util
|
|
32
43
|
import json
|
|
33
44
|
import re
|
|
34
45
|
import sys
|
|
35
|
-
import tempfile
|
|
36
46
|
from pathlib import Path
|
|
37
|
-
from typing import NamedTuple
|
|
38
47
|
|
|
39
48
|
sys.dont_write_bytecode = True
|
|
40
49
|
|
|
50
|
+
import runner
|
|
41
51
|
import tlc
|
|
52
|
+
from kani_reader import KANI_KEY, RouteReader, compiled_problems, kani_surface
|
|
53
|
+
from lean_records import read_record as read_lean_record
|
|
54
|
+
from surface import STRING, Surface, collapse
|
|
42
55
|
|
|
43
|
-
HERE = Path(__file__).resolve().parent
|
|
44
56
|
FORMAT = 2
|
|
45
|
-
NARROWING = {"lean": (), "tla": (), "kani": ("assume", "stub")}
|
|
46
|
-
KINDS = {".statements": "lean", ".matrix": "tla", ".rs": "kani"}
|
|
47
|
-
STRING = re.compile(r'"(?:\\.|[^"\\])*"', re.DOTALL)
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def collapse(text, literals=None):
|
|
51
|
-
if literals is None:
|
|
52
|
-
literals = (match.span() for match in STRING.finditer(text))
|
|
53
|
-
parts, end = [], 0
|
|
54
|
-
for start, stop in literals:
|
|
55
|
-
parts.extend((re.sub(r"\s+", " ", text[end:start]), text[start:stop]))
|
|
56
|
-
end = stop
|
|
57
|
-
parts.append(re.sub(r"\s+", " ", text[end:]))
|
|
58
|
-
return "".join(parts).strip()
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
class Surface(dict):
|
|
62
|
-
def add(self, name, value=""):
|
|
63
|
-
candidate, count = name, 1
|
|
64
|
-
while candidate in self:
|
|
65
|
-
count += 1
|
|
66
|
-
candidate = f"{name} #{count}"
|
|
67
|
-
self[candidate] = value
|
|
68
|
-
return candidate
|
|
69
57
|
|
|
70
58
|
|
|
71
59
|
def lean_surface(path):
|
|
72
|
-
|
|
73
|
-
module = importlib.util.module_from_spec(spec)
|
|
74
|
-
spec.loader.exec_module(module)
|
|
75
|
-
record = module.read_record(path)
|
|
60
|
+
record = read_lean_record(path)
|
|
76
61
|
surface = Surface()
|
|
77
62
|
surface.add("toolchain", record["toolchain"])
|
|
78
63
|
for entry in record["declarations"]:
|
|
@@ -80,6 +65,12 @@ def lean_surface(path):
|
|
|
80
65
|
return surface
|
|
81
66
|
|
|
82
67
|
|
|
68
|
+
def tla_text(text):
|
|
69
|
+
"""Columns can group TLA+ conjunctions and disjunctions across lines."""
|
|
70
|
+
lines = [line.rstrip() for line in text.splitlines() if line.strip()]
|
|
71
|
+
return "\n".join(lines) if len(lines) > 1 else collapse("".join(lines))
|
|
72
|
+
|
|
73
|
+
|
|
83
74
|
def blank_tla_comments(text):
|
|
84
75
|
out, i = [], 0
|
|
85
76
|
while i < len(text):
|
|
@@ -90,7 +81,7 @@ def blank_tla_comments(text):
|
|
|
90
81
|
out.append(string[0])
|
|
91
82
|
i = string.end()
|
|
92
83
|
elif text.startswith("(*", i):
|
|
93
|
-
depth = 0
|
|
84
|
+
start, depth = i, 0
|
|
94
85
|
while i < len(text):
|
|
95
86
|
if text.startswith("(*", i):
|
|
96
87
|
depth += 1
|
|
@@ -101,9 +92,9 @@ def blank_tla_comments(text):
|
|
|
101
92
|
if not depth:
|
|
102
93
|
break
|
|
103
94
|
else:
|
|
104
|
-
out.append("\n" if text[i] == "\n" else "")
|
|
105
95
|
i += 1
|
|
106
|
-
|
|
96
|
+
# A following token keeps its source column, even after a nested comment.
|
|
97
|
+
out.append(re.sub(r"[^\s]", " ", text[start:i]))
|
|
107
98
|
elif text.startswith("\\*", i):
|
|
108
99
|
end = text.find("\n", i)
|
|
109
100
|
i = len(text) if end < 0 else end
|
|
@@ -117,14 +108,40 @@ def blank_tla_comments(text):
|
|
|
117
108
|
DEFINITION = re.compile(r"(?:LOCAL\s+)?(\w*[A-Za-z]\w*)\s*(?:\((?:[^()]|\([^()]*\))*\)|\[(?:[^\[\]]|\[[^\[\]]*\])*\])?\s*==")
|
|
118
109
|
MODULE_LEVEL = re.compile(r"-{4,}|={4,}|(?:EXTENDS|VARIABLES?|CONSTANTS?|ASSUME|ASSUMPTION|AXIOM|THEOREM|LEMMA|PROPOSITION|COROLLARY|INSTANCE|RECURSIVE|USE|HIDE)\b")
|
|
119
110
|
IDENTIFIER = re.compile(r"\w*[A-Za-z]\w*")
|
|
120
|
-
SUBSCRIPT = r"_(
|
|
111
|
+
SUBSCRIPT = r"_(\w+|<<[^>]*>>)"
|
|
121
112
|
SPEC_ACTIONS = re.compile(rf"\[\]\[[^\]]*\]{SUBSCRIPT}|[WS]F{SUBSCRIPT}\s*\([^()]*\)")
|
|
113
|
+
# The prefix that joins a subscript, such as vars in WF_vars, [A]_vars or <<A>>_vars, to one token.
|
|
114
|
+
SUBSCRIPT_PREFIX = re.compile(r"\b[WS]F_|\]_|>>_")
|
|
122
115
|
|
|
123
116
|
|
|
124
117
|
def begins_in_column_zero(line):
|
|
125
118
|
return line[:1].strip() != ""
|
|
126
119
|
|
|
127
120
|
|
|
121
|
+
DEFINITION_TOKENS = re.compile(r"\b(?:LET|IN)\b|(?<!=)==(?!=)")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def has_unplaced_definition(code):
|
|
125
|
+
"""Return whether a definition can lie outside the column-0 headers that tla_definitions splits on.
|
|
126
|
+
|
|
127
|
+
An indented `==` inside an open LET defines a LET-local operator. Any other indented `==`, a line
|
|
128
|
+
that starts with `==`, or a column-0 header while a LET is open can define a module operator.
|
|
129
|
+
"""
|
|
130
|
+
open_lets = 0
|
|
131
|
+
for line in code.split("\n"):
|
|
132
|
+
indented = not begins_in_column_zero(line)
|
|
133
|
+
if open_lets and not indented and ("==" in line or MODULE_LEVEL.match(line)):
|
|
134
|
+
return True
|
|
135
|
+
for token in DEFINITION_TOKENS.finditer(line):
|
|
136
|
+
if token[0] == "LET":
|
|
137
|
+
open_lets += 1
|
|
138
|
+
elif token[0] == "IN":
|
|
139
|
+
open_lets = max(open_lets - 1, 0)
|
|
140
|
+
elif not open_lets and (indented or token.start() == 0):
|
|
141
|
+
return True
|
|
142
|
+
return False
|
|
143
|
+
|
|
144
|
+
|
|
128
145
|
def tla_definitions(text):
|
|
129
146
|
found, unreadable, name, lines = {}, set(), None, []
|
|
130
147
|
for line in text.split("\n"):
|
|
@@ -133,7 +150,7 @@ def tla_definitions(text):
|
|
|
133
150
|
header = None if match or MODULE_LEVEL.match(line) or "==" not in line else collapse(line.partition("==")[0])
|
|
134
151
|
if match or header or MODULE_LEVEL.match(line):
|
|
135
152
|
if name:
|
|
136
|
-
found[name] =
|
|
153
|
+
found[name] = tla_text("\n".join(lines))
|
|
137
154
|
name, lines = (match[1] if match else header), ([line] if match or header else [])
|
|
138
155
|
if header:
|
|
139
156
|
unreadable.add(header)
|
|
@@ -141,7 +158,7 @@ def tla_definitions(text):
|
|
|
141
158
|
if name:
|
|
142
159
|
lines.append(line)
|
|
143
160
|
if name:
|
|
144
|
-
found[name] =
|
|
161
|
+
found[name] = tla_text("\n".join(lines))
|
|
145
162
|
return found, unreadable
|
|
146
163
|
|
|
147
164
|
|
|
@@ -167,8 +184,7 @@ def tla_module_surface(directory, spec, operators):
|
|
|
167
184
|
text = blank_tla_comments(tlc.read_raw(directory / path))
|
|
168
185
|
texts[path] = text
|
|
169
186
|
code = STRING.sub('""', text)
|
|
170
|
-
|
|
171
|
-
if path != root and re.search(r"(?m)^(?:[ \t].*)?(?<!=)==(?!=)", code):
|
|
187
|
+
if has_unplaced_definition(code):
|
|
172
188
|
whole_modules = True
|
|
173
189
|
scope = {}
|
|
174
190
|
for group in EXTENDS.findall(code):
|
|
@@ -188,7 +204,7 @@ def tla_module_surface(directory, spec, operators):
|
|
|
188
204
|
scope[name] = key
|
|
189
205
|
required.update((path, name) for name in unreadable)
|
|
190
206
|
scopes[path] = scope
|
|
191
|
-
exports[path] = {name: key for name, key in scope.items() if not
|
|
207
|
+
exports[path] = {name: key for name, key in scope.items() if not re.match(r"LOCAL\s", bodies[key])}
|
|
192
208
|
visiting.remove(path)
|
|
193
209
|
return exports[path]
|
|
194
210
|
|
|
@@ -205,7 +221,7 @@ def tla_module_surface(directory, spec, operators):
|
|
|
205
221
|
if whole_modules:
|
|
206
222
|
# Preserve substitutions and dependencies whose operator scope cannot be resolved.
|
|
207
223
|
for path, text in texts.items():
|
|
208
|
-
surface[f"module text {spec} | {path}"] =
|
|
224
|
+
surface[f"module text {spec} | {path}"] = tla_text(text)
|
|
209
225
|
return surface
|
|
210
226
|
|
|
211
227
|
seen = set()
|
|
@@ -216,27 +232,28 @@ def tla_module_surface(directory, spec, operators):
|
|
|
216
232
|
seen.add(key)
|
|
217
233
|
owner, name = key
|
|
218
234
|
surface[f"definition {owner} {name}"] = bodies[key]
|
|
219
|
-
body =
|
|
235
|
+
header, _, body = bodies[key].partition("==")
|
|
236
|
+
body = STRING.sub('""', body)
|
|
220
237
|
if key == scopes[root]["Spec"]:
|
|
221
|
-
|
|
238
|
+
# Keep the subscript, such as vars: it decides which steps may stutter and what fairness requires.
|
|
239
|
+
body = SPEC_ACTIONS.sub(lambda form: f" {form[1] or form[2]} ", body)
|
|
240
|
+
body = SUBSCRIPT_PREFIX.sub(" ", body)
|
|
241
|
+
if "[" in header:
|
|
242
|
+
# A function definition such as F[x \in S] == ... references S in its header.
|
|
243
|
+
body = f"{header} {body}"
|
|
222
244
|
required.update(scopes[owner][word] for word in IDENTIFIER.findall(body) if word in scopes[owner])
|
|
223
245
|
return surface
|
|
224
246
|
|
|
225
247
|
|
|
226
248
|
def tla_surface(path):
|
|
227
249
|
surface = Surface()
|
|
250
|
+
surface.add("TLA+ layout version", 1)
|
|
228
251
|
specs = {}
|
|
229
|
-
|
|
230
|
-
tasks =
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
for directive in parsed:
|
|
235
|
-
if isinstance(directive, tlc.Spec):
|
|
236
|
-
if not directive.path:
|
|
237
|
-
raise ValueError(f"{path}: spec line has no path")
|
|
238
|
-
surface.add(f"spec {directive.path}")
|
|
239
|
-
specs.setdefault(directive.path, set())
|
|
252
|
+
plan = tlc.MatrixPlan(path)
|
|
253
|
+
tasks = plan.checked_tasks()
|
|
254
|
+
for spec in plan.specs:
|
|
255
|
+
surface.add(f"spec {spec}")
|
|
256
|
+
specs.setdefault(spec, set())
|
|
240
257
|
for task in tasks:
|
|
241
258
|
if task.reach:
|
|
242
259
|
surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
|
|
@@ -256,237 +273,227 @@ def tla_surface(path):
|
|
|
256
273
|
return surface
|
|
257
274
|
|
|
258
275
|
|
|
259
|
-
class
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
i = 0
|
|
277
|
-
while i < len(source):
|
|
278
|
-
if source.startswith("//", i):
|
|
279
|
-
end = source.find("\n", i)
|
|
280
|
-
end = len(source) if end < 0 else end
|
|
281
|
-
blank(i, end, both=True)
|
|
282
|
-
i = end
|
|
283
|
-
elif source.startswith("/*", i):
|
|
284
|
-
depth, start = 0, i
|
|
285
|
-
while i < len(source):
|
|
286
|
-
if source.startswith("/*", i):
|
|
287
|
-
depth, i = depth + 1, i + 2
|
|
288
|
-
elif source.startswith("*/", i):
|
|
289
|
-
depth, i = depth - 1, i + 2
|
|
290
|
-
if not depth:
|
|
291
|
-
break
|
|
292
|
-
else:
|
|
293
|
-
i += 1
|
|
294
|
-
blank(start, i, both=True)
|
|
295
|
-
elif raw := re.compile(r'(?<!\w)[bc]?r(#*)"').match(source, i):
|
|
296
|
-
close = source.find('"' + raw[1], raw.end())
|
|
297
|
-
content_end = len(source) if close < 0 else close
|
|
298
|
-
blank(raw.end(), content_end, both=False)
|
|
299
|
-
i = content_end + 1 + len(raw[1])
|
|
300
|
-
literals.append((raw.start(), min(i, len(source))))
|
|
301
|
-
elif source[i] == '"':
|
|
302
|
-
opening = i
|
|
303
|
-
start = i = i + 1
|
|
304
|
-
while i < len(source) and source[i] != '"':
|
|
305
|
-
i += 2 if source[i] == "\\" else 1
|
|
306
|
-
blank(start, min(i, len(source)), both=False)
|
|
307
|
-
i += 1
|
|
308
|
-
literals.append((opening, min(i, len(source))))
|
|
309
|
-
elif char := re.compile(r"'(?:\\.[^']*|[^'\\])'").match(source, i):
|
|
310
|
-
blank(char.start() + 1, char.end() - 1, both=False)
|
|
311
|
-
i = char.end()
|
|
312
|
-
literals.append(char.span())
|
|
313
|
-
else:
|
|
314
|
-
i += 1
|
|
315
|
-
return RustSource("".join(text), "".join(mask), literals)
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
def after_closing(mask, opener):
|
|
319
|
-
closer = {"(": ")", "[": "]", "{": "}"}[mask[opener]]
|
|
320
|
-
depth = 0
|
|
321
|
-
for i in range(opener, len(mask)):
|
|
322
|
-
depth += (mask[i] == mask[opener]) - (mask[i] == closer)
|
|
323
|
-
if not depth:
|
|
324
|
-
return i + 1
|
|
325
|
-
raise ValueError(f"unbalanced {mask[opener]} at offset {opener}")
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
class RustFunction(NamedTuple):
|
|
329
|
-
name: str
|
|
330
|
-
start: int
|
|
331
|
-
body: int
|
|
332
|
-
end: int
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b")
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
def rust_functions(mask):
|
|
339
|
-
"""Locate free functions under inline modules; leave macro and other item bodies opaque."""
|
|
340
|
-
functions, opaque, counts = [], [], {}
|
|
341
|
-
|
|
342
|
-
def walk(start, end, namespace=(), in_function=False):
|
|
343
|
-
i, boundary, item = start, start, None
|
|
344
|
-
while i < end:
|
|
345
|
-
if match := RUST_ITEM.match(mask, i):
|
|
346
|
-
item = (match[1], match[2])
|
|
347
|
-
i = match.end()
|
|
348
|
-
elif mask[i] in "([":
|
|
349
|
-
stop = after_closing(mask, i)
|
|
350
|
-
if mask[boundary:i].rstrip().endswith("!"):
|
|
351
|
-
opaque.append((i, stop))
|
|
352
|
-
i = stop
|
|
353
|
-
elif mask[i] == "{":
|
|
354
|
-
stop = after_closing(mask, i)
|
|
355
|
-
header = mask[boundary:i].rstrip()
|
|
356
|
-
macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
|
|
357
|
-
if item and not macro:
|
|
358
|
-
kind, name = item
|
|
359
|
-
qualified = (*namespace, name)
|
|
360
|
-
if kind == "fn":
|
|
361
|
-
owner = "::".join(qualified)
|
|
362
|
-
counts[owner] = counts.get(owner, 0) + 1
|
|
363
|
-
suffix = f"[{counts[owner]}]" if counts[owner] > 1 else ""
|
|
364
|
-
functions.append(RustFunction(owner + suffix, boundary, i, stop))
|
|
365
|
-
walk(i + 1, stop - 1, qualified, kind == "fn")
|
|
366
|
-
elif in_function and not macro and not re.search(r"\b(?:impl|trait|struct|enum|union|extern|macro)\b", header):
|
|
367
|
-
walk(i + 1, stop - 1, namespace, True)
|
|
368
|
-
else:
|
|
369
|
-
opaque.append((i, stop))
|
|
370
|
-
i = boundary = stop
|
|
371
|
-
item = None
|
|
372
|
-
else:
|
|
373
|
-
if mask[i] == ";":
|
|
374
|
-
boundary, item = i + 1, None
|
|
375
|
-
i += 1
|
|
376
|
-
|
|
377
|
-
walk(0, len(mask))
|
|
378
|
-
return functions, opaque
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
|
|
382
|
-
MACROS = (
|
|
383
|
-
("assume", re.compile(r"\bkani\s*::\s*assume\s*\(")),
|
|
384
|
-
("assume", re.compile(r"\bkani\s*::\s*any_where\s*(?:::\s*<[^<>]*(?:<[^<>]*>[^<>]*)*>\s*)?\(")),
|
|
385
|
-
("cover", re.compile(r"\bkani\s*::\s*cover\s*!\s*\(")),
|
|
386
|
-
("stub", re.compile(KANI_ATTRIBUTE + r"stub\s*\(")),
|
|
387
|
-
)
|
|
388
|
-
PROOF = re.compile(KANI_ATTRIBUTE + r"proof(?:_for_contract\s*\([^)]*\))?\s*\)?\s*\]")
|
|
389
|
-
KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof)\w*\b")
|
|
390
|
-
RENAMING_IMPORT = re.compile(r"\buse\s+[^;]*?(?<![\w:])(?:::\s*)?kani\b[^;]*?(?:\bas\b|\*|\b(?:assume|any_where|cover|stub|proof)\w*\b)|\bextern\s+crate\s+kani\s+as\b")
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
def kani_surface(path):
|
|
394
|
-
source = rust_masks(path.read_text(encoding="utf-8"))
|
|
395
|
-
text, mask = source.uncommented, source.without_comments_or_strings
|
|
396
|
-
if renaming := RENAMING_IMPORT.search(mask):
|
|
397
|
-
raise ValueError(f"{path}: '{collapse(renaming[0])}' brings a Kani assumption, cover, stub or harness attribute in under another name; write each as kani::<name> so the record can read it")
|
|
398
|
-
functions, opaque = rust_functions(mask)
|
|
399
|
-
|
|
400
|
-
def owner_at(position, *, attribute=False):
|
|
401
|
-
if not any(start <= position < end for start, end in opaque):
|
|
402
|
-
for function in reversed(functions):
|
|
403
|
-
if function.start <= position < function.end and (position < function.body if attribute else position > function.body):
|
|
404
|
-
return function.name
|
|
405
|
-
line = mask.count("\n", 0, position) + 1
|
|
406
|
-
raise ValueError(f"{path}:{line}: cannot identify a function owner; write Kani forms in free functions under inline modules, outside macro definitions and impl or trait bodies")
|
|
276
|
+
class LeanKind:
|
|
277
|
+
"""Record, compare and move the toolchain and declarations of a Lean statements file."""
|
|
278
|
+
|
|
279
|
+
name, suffix, renames = "lean", ".statements", False
|
|
280
|
+
|
|
281
|
+
def entry(self, path):
|
|
282
|
+
return model_entry(self.name, lean_surface(path)), None
|
|
283
|
+
|
|
284
|
+
def changes(self, entry, path):
|
|
285
|
+
return differences(entry["surface"], lean_surface(path), ()), []
|
|
286
|
+
|
|
287
|
+
def valid(self, entry):
|
|
288
|
+
return True
|
|
289
|
+
|
|
290
|
+
def moved(self, entry, module, new, existing):
|
|
291
|
+
return model_entry(self.name, joined(entry["surface"], new, existing))
|
|
407
292
|
|
|
408
|
-
surface = Surface()
|
|
409
|
-
spans, read = [], []
|
|
410
|
-
for kind, pattern in MACROS:
|
|
411
|
-
for match in pattern.finditer(mask):
|
|
412
|
-
end = after_closing(mask, match.end() - 1)
|
|
413
|
-
read.append((match.start(), end))
|
|
414
|
-
argument = rust_masks(text[match.end():end - 1])
|
|
415
|
-
owner = owner_at(match.start(), attribute=kind == "stub")
|
|
416
|
-
spans.append((match.start(), f"{kind} {collapse(argument.uncommented, argument.literals)} in {owner}"))
|
|
417
|
-
for match in PROOF.finditer(mask):
|
|
418
|
-
read.append(match.span())
|
|
419
|
-
spans.append((match.start(), f"harness {owner_at(match.start(), attribute=True)}"))
|
|
420
|
-
for token in KANI_TOKEN.finditer(mask):
|
|
421
|
-
if not any(start <= token.start() < end for start, end in read):
|
|
422
|
-
line = mask.count("\n", 0, token.start()) + 1
|
|
423
|
-
raise ValueError(f"{path}:{line}: '{collapse(token[0])}' is in a form the record cannot read; write kani::assume(...), kani::any_where(...), kani::cover!(...), #[kani::stub(...)] or #[kani::proof], alone or under #[cfg_attr(kani, ...)]")
|
|
424
|
-
for _, item in sorted(spans):
|
|
425
|
-
surface.add(item)
|
|
426
|
-
return surface
|
|
427
293
|
|
|
294
|
+
class TlaKind:
|
|
295
|
+
"""Record, compare and move the checks of a TLA+ matrix and the specs it runs."""
|
|
428
296
|
|
|
429
|
-
|
|
297
|
+
name, suffix, renames = "tla", ".matrix", False
|
|
298
|
+
|
|
299
|
+
def entry(self, path):
|
|
300
|
+
return model_entry(self.name, tla_surface(path)), None
|
|
301
|
+
|
|
302
|
+
def changes(self, entry, path):
|
|
303
|
+
old, new = entry["surface"], tla_surface(path)
|
|
304
|
+
lines = []
|
|
305
|
+
if not any(name.startswith("imports ") for name in old):
|
|
306
|
+
lines.append(" previous baseline did not track imported modules; review and record this matrix again")
|
|
307
|
+
if "TLA+ layout version" not in old:
|
|
308
|
+
lines.append(" previous baseline did not preserve TLA+ layout; review and record this matrix again")
|
|
309
|
+
return lines + differences(old, new, ()), []
|
|
310
|
+
|
|
311
|
+
def valid(self, entry):
|
|
312
|
+
return True
|
|
313
|
+
|
|
314
|
+
def moved(self, entry, module, new, existing):
|
|
315
|
+
return model_entry(self.name, joined(entry["surface"], new, existing))
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
class KaniKind:
|
|
319
|
+
"""Record, compare and move the harnesses, assumptions, covers and stubs of a Kani file, checked against what Kani compiles."""
|
|
320
|
+
|
|
321
|
+
name, suffix, renames = "kani", ".rs", True
|
|
322
|
+
|
|
323
|
+
def __init__(self):
|
|
324
|
+
self.reader = RouteReader()
|
|
325
|
+
|
|
326
|
+
def entry(self, path):
|
|
327
|
+
surface = kani_surface(path, self.reader)
|
|
328
|
+
entry = model_entry(self.name, surface)
|
|
329
|
+
notes = [f" route not read: {route.message}" for route in self.reader.unread(path)]
|
|
330
|
+
# A harness that no longer compiles is recorded from its text alone; compare asks Kani again.
|
|
331
|
+
try:
|
|
332
|
+
problems, names = compiled_problems(path, surface, self.reader)
|
|
333
|
+
except ValueError as error:
|
|
334
|
+
return entry, "\n".join([*notes, f" not checked against Kani: {error}"])
|
|
335
|
+
if problems:
|
|
336
|
+
raise ValueError(f"{path}: " + "; ".join(problem.strip().removeprefix("FAIL ") for problem in problems))
|
|
337
|
+
if names is not None:
|
|
338
|
+
entry["compiled"] = names
|
|
339
|
+
return entry, "\n".join(notes) or None
|
|
340
|
+
|
|
341
|
+
def changes(self, entry, path):
|
|
342
|
+
surface = kani_surface(path, self.reader)
|
|
343
|
+
lines = differences(entry["surface"], surface, ("assume", "stub"))
|
|
344
|
+
unchecked = (" not checked against Kani at record, so compare cannot tell a harness that "
|
|
345
|
+
"stopped compiling from one that never compiled")
|
|
346
|
+
try:
|
|
347
|
+
problems, names = compiled_problems(path, surface, self.reader, entry.get("compiled"))
|
|
348
|
+
except ValueError as error:
|
|
349
|
+
if "compiled" in entry:
|
|
350
|
+
return [*lines, f" FAIL {error}"], []
|
|
351
|
+
return lines, [unchecked, f" {error}"]
|
|
352
|
+
if names is None or "compiled" in entry and not entry.get("partial"):
|
|
353
|
+
return lines + problems, []
|
|
354
|
+
# Name each recorded harness that Kani does not compile now; a harness behind a feature that is not a
|
|
355
|
+
# default never compiles, so this cannot count as a change.
|
|
356
|
+
recorded = {"harness " + re.sub(r"\[\d+\]$", "", KANI_KEY.fullmatch(item)[2])
|
|
357
|
+
for item in entry["surface"] if item.startswith("harness ") and item in surface}
|
|
358
|
+
missing = sorted(recorded - set(names) - set(entry.get("compiled", ())))
|
|
359
|
+
return lines + problems, [unchecked, *(f" not compiled now {item}" for item in missing)]
|
|
360
|
+
|
|
361
|
+
def valid(self, entry):
|
|
362
|
+
compiled = entry.get("compiled", [])
|
|
363
|
+
return (isinstance(compiled, list) and all(isinstance(name, str) for name in compiled)
|
|
364
|
+
and isinstance(entry.get("partial", False), bool))
|
|
365
|
+
|
|
366
|
+
def moved(self, entry, module, new, existing):
|
|
367
|
+
surface, compiled = entry["surface"], entry.get("compiled")
|
|
368
|
+
if module:
|
|
369
|
+
surface = renamed(surface, *module)
|
|
370
|
+
compiled = compiled and list(renamed(dict.fromkeys(compiled), *module))
|
|
371
|
+
surface = joined(surface, new, existing)
|
|
372
|
+
partial = compiled is None or entry.get("partial", False)
|
|
373
|
+
if existing is not None:
|
|
374
|
+
# The merged list keeps the harnesses of each entry checked against Kani at record, and is partial when
|
|
375
|
+
# either entry was not checked.
|
|
376
|
+
other = existing.get("compiled") if existing["kind"] == self.name else None
|
|
377
|
+
partial = partial or other is None or existing.get("partial", False)
|
|
378
|
+
compiled = None if compiled is None and other is None else [*(other or []), *(compiled or [])]
|
|
379
|
+
result = model_entry(self.name, surface)
|
|
380
|
+
if compiled is not None:
|
|
381
|
+
result["compiled"] = sorted(compiled)
|
|
382
|
+
if partial:
|
|
383
|
+
result["partial"] = True
|
|
384
|
+
return result
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def model_kinds():
|
|
388
|
+
"""Return a fresh adapter for each model kind, by the name a record entry gives as its kind."""
|
|
389
|
+
return {kind.name: kind for kind in (LeanKind(), TlaKind(), KaniKind())}
|
|
430
390
|
|
|
431
391
|
|
|
432
392
|
def digest(surface):
|
|
433
393
|
return hashlib.sha256(json.dumps(surface, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
|
|
434
394
|
|
|
435
395
|
|
|
436
|
-
def
|
|
396
|
+
def model_entry(kind, surface):
|
|
397
|
+
return {"kind": kind, "digest": digest(surface), "surface": surface}
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def joined(surface, new, existing):
|
|
401
|
+
"""Add the items that the entry existing records for the file new, which must not repeat an item of surface."""
|
|
402
|
+
if existing is None:
|
|
403
|
+
return surface
|
|
404
|
+
if overlap := surface.keys() & existing["surface"].keys():
|
|
405
|
+
raise ValueError(f"{new} already records {', '.join(sorted(overlap))}")
|
|
406
|
+
return {**existing["surface"], **surface}
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def read_record(path, kinds):
|
|
437
410
|
record = json.loads(path.read_text(encoding="utf-8"))
|
|
438
411
|
models = record.get("models") if isinstance(record, dict) else None
|
|
439
412
|
if not isinstance(models, dict) or record.get("format") != FORMAT:
|
|
440
413
|
raise ValueError(f"{path}: unsupported record format; run record with a new record file")
|
|
441
414
|
for model, entry in models.items():
|
|
442
|
-
if not isinstance(entry, dict) or entry.get("kind") not in
|
|
415
|
+
if (not isinstance(entry, dict) or entry.get("kind") not in kinds or not isinstance(entry.get("surface"), dict)
|
|
416
|
+
or not kinds[entry["kind"]].valid(entry)):
|
|
443
417
|
raise ValueError(f"{path}: malformed entry for {model}")
|
|
444
418
|
return models
|
|
445
419
|
|
|
446
420
|
|
|
447
421
|
def write_record(path, models):
|
|
448
422
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
449
|
-
|
|
450
|
-
try:
|
|
451
|
-
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as stream:
|
|
452
|
-
temporary = Path(stream.name)
|
|
453
|
-
stream.write(json.dumps({"format": FORMAT, "models": models}, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
|
|
454
|
-
temporary.replace(path)
|
|
455
|
-
finally:
|
|
456
|
-
if temporary is not None:
|
|
457
|
-
temporary.unlink(missing_ok=True)
|
|
423
|
+
runner.atomic_write(path, json.dumps({"format": FORMAT, "models": models}, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
|
|
458
424
|
|
|
459
425
|
|
|
460
426
|
def record(record_path, files):
|
|
427
|
+
kinds = model_kinds()
|
|
428
|
+
by_suffix = {kind.suffix: kind for kind in kinds.values()}
|
|
461
429
|
for file in files:
|
|
462
|
-
if file.suffix not in
|
|
463
|
-
print(f"usage: {file} has no model surface; expected one of {', '.join(
|
|
430
|
+
if file.suffix not in by_suffix:
|
|
431
|
+
print(f"usage: {file} has no model surface; expected one of {', '.join(by_suffix)}")
|
|
464
432
|
return 2
|
|
465
|
-
models = read_record(record_path) if record_path.exists() else {}
|
|
466
|
-
updates = {}
|
|
433
|
+
models = read_record(record_path, kinds) if record_path.exists() else {}
|
|
434
|
+
updates, notes = {}, {}
|
|
467
435
|
for file in files:
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
436
|
+
model = str(file.resolve())
|
|
437
|
+
updates[model], note = by_suffix[file.suffix].entry(file.resolve())
|
|
438
|
+
if note:
|
|
439
|
+
notes[model] = note
|
|
471
440
|
for model, entry in updates.items():
|
|
472
441
|
print(f"RECORDED {model} {entry['digest']}")
|
|
473
442
|
previous = models.get(model, {}).get("digest")
|
|
474
443
|
if previous and previous != entry["digest"]:
|
|
475
444
|
print(f" previous {previous}")
|
|
445
|
+
if model in notes:
|
|
446
|
+
print(notes[model])
|
|
476
447
|
write_record(record_path, {**models, **updates})
|
|
477
448
|
return 0
|
|
478
449
|
|
|
479
450
|
|
|
480
|
-
def
|
|
451
|
+
def renamed(surface, old_module, new_module):
|
|
452
|
+
"""Rewrite each Kani owner under old_module to sit under new_module, where `crate` is the file's root."""
|
|
453
|
+
old, new = ([] if path == "crate" else path.split("::") for path in (old_module, new_module))
|
|
454
|
+
result = {}
|
|
455
|
+
for name, value in surface.items():
|
|
456
|
+
if (item := KANI_KEY.fullmatch(name)) is None:
|
|
457
|
+
raise ValueError(f"cannot rename the recorded item '{name}', which is not a Kani harness, assume, cover or stub")
|
|
458
|
+
head, owner, duplicate = item.groups()
|
|
459
|
+
parts = owner.split("::")
|
|
460
|
+
if parts[:len(old)] == old:
|
|
461
|
+
owner = "::".join(new + parts[len(old):])
|
|
462
|
+
result[f"{head}{owner}{duplicate or ''}"] = value
|
|
463
|
+
if len(result) != len(surface):
|
|
464
|
+
raise ValueError(f"renaming {old_module} to {new_module} merges recorded items")
|
|
465
|
+
return result
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def move(record_path, old_file, new_file, module):
|
|
469
|
+
kinds = model_kinds()
|
|
470
|
+
models = read_record(record_path, kinds) if record_path.is_file() else {}
|
|
471
|
+
old, new = str(old_file.resolve()), str(new_file.resolve())
|
|
472
|
+
if old not in models:
|
|
473
|
+
print(f"usage: {old} has no record entry; record it before the move")
|
|
474
|
+
return 2
|
|
475
|
+
kind = kinds[models[old]["kind"]]
|
|
476
|
+
if new_file.suffix != kind.suffix:
|
|
477
|
+
print(f"usage: {new} is not a {kind.name} model file")
|
|
478
|
+
return 2
|
|
479
|
+
if module and not kind.renames:
|
|
480
|
+
print("usage: --module applies only to a Kani harness file")
|
|
481
|
+
return 2
|
|
482
|
+
entry = models.pop(old)
|
|
483
|
+
models[new] = kind.moved(entry, module, new, models.get(new))
|
|
484
|
+
write_record(record_path, models)
|
|
485
|
+
print(f"MOVED {old} -> {new}")
|
|
486
|
+
return 0
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def differences(old, new, narrowing):
|
|
481
490
|
lines = []
|
|
482
|
-
if kind == "tla" and not any(name.startswith("imports ") for name in old):
|
|
483
|
-
lines.append(" previous baseline did not track imported modules; review and record this matrix again")
|
|
484
491
|
for name in old:
|
|
485
492
|
if name not in new:
|
|
486
493
|
lines.append(f" removed {name}")
|
|
487
494
|
elif old[name] != new[name]:
|
|
488
495
|
lines += [f" changed {name}", f" old: {old[name]}", f" new: {new[name]}"]
|
|
489
|
-
lines += [f" added {name}" for name in new if name not in old and name.split(" ", 1)[0] in
|
|
496
|
+
lines += [f" added {name}" for name in new if name not in old and name.split(" ", 1)[0] in narrowing]
|
|
490
497
|
return lines
|
|
491
498
|
|
|
492
499
|
|
|
@@ -494,21 +501,30 @@ def compare(record_path):
|
|
|
494
501
|
if not record_path.is_file():
|
|
495
502
|
print(f"usage: record file {record_path} does not exist; run record first")
|
|
496
503
|
return 2
|
|
497
|
-
|
|
498
|
-
|
|
504
|
+
kinds = model_kinds()
|
|
505
|
+
models = read_record(record_path, kinds)
|
|
506
|
+
changed = unchecked = 0
|
|
499
507
|
for model, entry in models.items():
|
|
500
508
|
try:
|
|
501
509
|
if not Path(model).is_file():
|
|
502
|
-
lines = [" file is missing"]
|
|
510
|
+
lines, notes = [" file is missing"], []
|
|
503
511
|
else:
|
|
504
|
-
lines =
|
|
512
|
+
lines, notes = kinds[entry["kind"]].changes(entry, Path(model))
|
|
505
513
|
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
506
|
-
lines = [f" FAIL {error}"]
|
|
514
|
+
lines, notes = [f" FAIL {error}"], []
|
|
507
515
|
changed += bool(lines)
|
|
508
|
-
|
|
516
|
+
unchecked += bool(notes) and not lines
|
|
509
517
|
if lines:
|
|
510
|
-
|
|
511
|
-
|
|
518
|
+
status = "CHANGED"
|
|
519
|
+
elif notes:
|
|
520
|
+
status = "NOT CHECKED"
|
|
521
|
+
else:
|
|
522
|
+
status = "UNCHANGED"
|
|
523
|
+
print(f"{status} {model}")
|
|
524
|
+
if lines or notes:
|
|
525
|
+
print("\n".join(lines + notes))
|
|
526
|
+
not_checked = f", {unchecked} not checked" if unchecked else ""
|
|
527
|
+
print(f"SUMMARY {len(models) - changed - unchecked} unchanged, {changed} changed{not_checked}")
|
|
512
528
|
return int(changed > 0)
|
|
513
529
|
|
|
514
530
|
|
|
@@ -519,15 +535,28 @@ def main():
|
|
|
519
535
|
recording.add_argument("record_file", type=Path)
|
|
520
536
|
recording.add_argument("models", nargs="+", type=Path)
|
|
521
537
|
commands.add_parser("compare", help="compare every recorded model with its file").add_argument("record_file", type=Path)
|
|
538
|
+
moving = commands.add_parser("move", help="move a model's recorded entry to the file it moved to")
|
|
539
|
+
moving.add_argument("record_file", type=Path)
|
|
540
|
+
moving.add_argument("old_file", type=Path)
|
|
541
|
+
moving.add_argument("new_file", type=Path)
|
|
542
|
+
moving.add_argument("--module", nargs=2, metavar=("OLD", "NEW"),
|
|
543
|
+
help="the Kani harnesses moved from module OLD to NEW; crate names the file's root")
|
|
522
544
|
arguments = parser.parse_args()
|
|
523
545
|
if arguments.command == "record":
|
|
524
546
|
return record(arguments.record_file, arguments.models)
|
|
547
|
+
if arguments.command == "move":
|
|
548
|
+
return move(arguments.record_file, arguments.old_file, arguments.new_file, arguments.module)
|
|
525
549
|
return compare(arguments.record_file)
|
|
526
550
|
|
|
527
551
|
|
|
528
|
-
|
|
552
|
+
def guarded_main():
|
|
529
553
|
try:
|
|
530
|
-
|
|
554
|
+
return main()
|
|
531
555
|
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
532
556
|
print(f"FAIL baseline: {error}")
|
|
533
|
-
|
|
557
|
+
return 1
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
if __name__ == "__main__":
|
|
561
|
+
# The runner turns a stopping signal into an exception, so Kani's work directory is removed before the exit.
|
|
562
|
+
runner.run(guarded_main)
|