agent-formal-verify 0.4.8 → 0.4.10
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 +34 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +15 -7
- package/skills/formal-verify/examples/kani-template/src/lib.rs +6 -0
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.lean +16 -4
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.mutations +1 -1
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +14 -0
- package/skills/formal-verify/references/lean-brief.md +22 -5
- package/skills/formal-verify/references/rust-brief.md +5 -3
- package/skills/formal-verify/references/setup.md +1 -1
- package/skills/formal-verify/references/tla-brief.md +1 -1
- package/skills/formal-verify/scripts/baseline.py +472 -0
- package/skills/formal-verify/scripts/kani.py +37 -0
- package/skills/formal-verify/scripts/lean-check.sh +88 -9
- package/skills/formal-verify/scripts/lean-mutations.lean +95 -0
- package/skills/formal-verify/scripts/lean-replay.lean +19 -0
- package/skills/formal-verify/scripts/lean-statements.py +61 -39
- package/skills/formal-verify/scripts/lean-tools.sh +9 -0
- package/skills/formal-verify/scripts/mutate.py +259 -158
- package/skills/formal-verify/scripts/tlc-matrix.sh +4 -167
- package/skills/formal-verify/scripts/tlc.py +328 -0
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright (c) 2026 Michael Denyer
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
+
"""Record what each model specifies before agents edit it, and compare it afterwards.
|
|
5
|
+
|
|
6
|
+
A model's surface is a mapping from item name to a canonical value. Every tool
|
|
7
|
+
uses one rule to compare surfaces: a removed item or a changed value is a
|
|
8
|
+
change, and so is an added item whose kind narrows what is checked.
|
|
9
|
+
|
|
10
|
+
.statements Lean. The toolchain, and each declaration's kind, type hash and value hash.
|
|
11
|
+
Added declarations are allowed.
|
|
12
|
+
.matrix TLA+. Each run's effective checks and each reach check's selected inputs,
|
|
13
|
+
and the normalized definitions of Spec,
|
|
14
|
+
of each operator a check or reach line names, and of the operators those
|
|
15
|
+
reference, in the spec each section names. Spec is not followed into its actions.
|
|
16
|
+
.rs Kani. Each qualified harness name, and each kani::assume, kani::any_where,
|
|
17
|
+
kani::cover! and #[kani::stub] with its owning free function, under inline
|
|
18
|
+
modules. Unsupported owners fail. Added covers and harnesses are allowed.
|
|
19
|
+
Added assumes and stubs are changes.
|
|
20
|
+
|
|
21
|
+
Usage:
|
|
22
|
+
baseline.py record <record-file> <model-file>... record these files, keep the other entries
|
|
23
|
+
baseline.py compare <record-file> exit 1 when a recorded file changed
|
|
24
|
+
|
|
25
|
+
Compare prints UNCHANGED or CHANGED per file, indented lines for each item that
|
|
26
|
+
changed, and a SUMMARY line. Exit codes: 0 unchanged, 1 changed or a record or
|
|
27
|
+
model file that fails to parse, 2 usage error.
|
|
28
|
+
"""
|
|
29
|
+
import argparse
|
|
30
|
+
import hashlib
|
|
31
|
+
import importlib.util
|
|
32
|
+
import json
|
|
33
|
+
import re
|
|
34
|
+
import sys
|
|
35
|
+
import tempfile
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import NamedTuple
|
|
38
|
+
|
|
39
|
+
sys.dont_write_bytecode = True
|
|
40
|
+
|
|
41
|
+
import tlc
|
|
42
|
+
|
|
43
|
+
HERE = Path(__file__).resolve().parent
|
|
44
|
+
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
|
+
|
|
70
|
+
|
|
71
|
+
def lean_surface(path):
|
|
72
|
+
spec = importlib.util.spec_from_file_location("lean_statements", HERE / "lean-statements.py")
|
|
73
|
+
module = importlib.util.module_from_spec(spec)
|
|
74
|
+
spec.loader.exec_module(module)
|
|
75
|
+
record = module.read_record(path)
|
|
76
|
+
surface = Surface()
|
|
77
|
+
surface.add("toolchain", record["toolchain"])
|
|
78
|
+
for entry in record["declarations"]:
|
|
79
|
+
surface.add(f"declaration {entry['name']}", f"{entry['kind']} {entry['typeHash']} {entry['valueHash'] or '-'}")
|
|
80
|
+
return surface
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def blank_tla_comments(text):
|
|
84
|
+
out, i = [], 0
|
|
85
|
+
while i < len(text):
|
|
86
|
+
if text[i] == '"':
|
|
87
|
+
string = STRING.match(text, i)
|
|
88
|
+
if string is None:
|
|
89
|
+
raise ValueError("unterminated TLA+ string")
|
|
90
|
+
out.append(string[0])
|
|
91
|
+
i = string.end()
|
|
92
|
+
elif text.startswith("(*", i):
|
|
93
|
+
depth = 0
|
|
94
|
+
while i < len(text):
|
|
95
|
+
if text.startswith("(*", i):
|
|
96
|
+
depth += 1
|
|
97
|
+
i += 2
|
|
98
|
+
elif text.startswith("*)", i):
|
|
99
|
+
depth -= 1
|
|
100
|
+
i += 2
|
|
101
|
+
if not depth:
|
|
102
|
+
break
|
|
103
|
+
else:
|
|
104
|
+
out.append("\n" if text[i] == "\n" else "")
|
|
105
|
+
i += 1
|
|
106
|
+
out.append(" ")
|
|
107
|
+
elif text.startswith("\\*", i):
|
|
108
|
+
end = text.find("\n", i)
|
|
109
|
+
i = len(text) if end < 0 else end
|
|
110
|
+
out.append(" ")
|
|
111
|
+
else:
|
|
112
|
+
out.append(text[i])
|
|
113
|
+
i += 1
|
|
114
|
+
return "".join(out)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
DEFINITION = re.compile(r"(?:LOCAL\s+)?(\w*[A-Za-z]\w*)\s*(?:\((?:[^()]|\([^()]*\))*\)|\[(?:[^\[\]]|\[[^\[\]]*\])*\])?\s*==")
|
|
118
|
+
MODULE_LEVEL = re.compile(r"-{4,}|={4,}|(?:EXTENDS|VARIABLES?|CONSTANTS?|ASSUME|ASSUMPTION|AXIOM|THEOREM|LEMMA|PROPOSITION|COROLLARY|INSTANCE|RECURSIVE|USE|HIDE)\b")
|
|
119
|
+
IDENTIFIER = re.compile(r"\w*[A-Za-z]\w*")
|
|
120
|
+
SUBSCRIPT = r"_(?:\w+|<<[^>]*>>)"
|
|
121
|
+
SPEC_ACTIONS = re.compile(rf"\[\]\[[^\]]*\]{SUBSCRIPT}|[WS]F{SUBSCRIPT}\s*\([^()]*\)")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def begins_in_column_zero(line):
|
|
125
|
+
return line[:1].strip() != ""
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def tla_definitions(text):
|
|
129
|
+
found, unreadable, name, lines = {}, set(), None, []
|
|
130
|
+
for line in blank_tla_comments(text).split("\n"):
|
|
131
|
+
if begins_in_column_zero(line):
|
|
132
|
+
match = DEFINITION.match(line)
|
|
133
|
+
header = None if match or MODULE_LEVEL.match(line) or "==" not in line else collapse(line.partition("==")[0])
|
|
134
|
+
if match or header or MODULE_LEVEL.match(line):
|
|
135
|
+
if name:
|
|
136
|
+
found[name] = collapse(" ".join(lines))
|
|
137
|
+
name, lines = (match[1] if match else header), ([line] if match or header else [])
|
|
138
|
+
if header:
|
|
139
|
+
unreadable.add(header)
|
|
140
|
+
continue
|
|
141
|
+
if name:
|
|
142
|
+
lines.append(line)
|
|
143
|
+
if name:
|
|
144
|
+
found[name] = collapse(" ".join(lines))
|
|
145
|
+
return found, unreadable
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def tla_closure(definitions, roots):
|
|
149
|
+
seen, pending = set(), list(roots)
|
|
150
|
+
while pending:
|
|
151
|
+
name = pending.pop()
|
|
152
|
+
if name in seen:
|
|
153
|
+
continue
|
|
154
|
+
seen.add(name)
|
|
155
|
+
body = definitions[name].partition("==")[2]
|
|
156
|
+
if name == "Spec":
|
|
157
|
+
body = SPEC_ACTIONS.sub(" ", body)
|
|
158
|
+
pending += [word for word in IDENTIFIER.findall(body) if word in definitions and word != name]
|
|
159
|
+
return seen
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def tla_surface(path):
|
|
163
|
+
surface = Surface()
|
|
164
|
+
specs = {}
|
|
165
|
+
parsed = list(tlc.directives(tlc.read_raw(path).split("\n")))
|
|
166
|
+
tasks = list(tlc.execution_plan(parsed))
|
|
167
|
+
errors = ["; ".join(tlc.render(task)) for task in tasks if isinstance(task, tlc.Result)]
|
|
168
|
+
if errors:
|
|
169
|
+
raise ValueError(f"{path}: {'; '.join(errors)}")
|
|
170
|
+
for directive in parsed:
|
|
171
|
+
if isinstance(directive, tlc.Spec):
|
|
172
|
+
if not directive.path:
|
|
173
|
+
raise ValueError(f"{path}: spec line has no path")
|
|
174
|
+
surface.add(f"spec {directive.path}")
|
|
175
|
+
specs.setdefault(directive.path, set())
|
|
176
|
+
for task in tasks:
|
|
177
|
+
if task.reach:
|
|
178
|
+
surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
|
|
179
|
+
{"run": collapse(task.run.label), "constants": collapse(task.run.constants)})
|
|
180
|
+
specs[task.spec].add(task.reach.operator)
|
|
181
|
+
else:
|
|
182
|
+
run = surface.add(f"run {task.spec} {collapse(task.run.label)}", collapse(task.run.constants))
|
|
183
|
+
for check in task.checks:
|
|
184
|
+
for name in check.names:
|
|
185
|
+
surface.add(f"check {task.spec} {check.kind} {name} | [{run}]")
|
|
186
|
+
specs[task.spec].update(check.names)
|
|
187
|
+
for spec, operators in specs.items():
|
|
188
|
+
source = path.parent / spec
|
|
189
|
+
if not source.is_file():
|
|
190
|
+
raise ValueError(f"{path}: spec {spec} not found")
|
|
191
|
+
definitions, unreadable = tla_definitions(tlc.read_raw(source))
|
|
192
|
+
for name in sorted({"Spec", *operators}):
|
|
193
|
+
if name not in definitions:
|
|
194
|
+
raise ValueError(f"{path}: {name} is named in the {spec} section but {source} does not define it")
|
|
195
|
+
for name in sorted(tla_closure(definitions, {"Spec", *operators, *unreadable})):
|
|
196
|
+
surface[f"definition {spec} {name}"] = definitions[name]
|
|
197
|
+
return surface
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class RustSource(NamedTuple):
|
|
201
|
+
uncommented: str
|
|
202
|
+
without_comments_or_strings: str
|
|
203
|
+
literals: list
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def rust_masks(source):
|
|
207
|
+
text, mask = list(source), list(source)
|
|
208
|
+
literals = []
|
|
209
|
+
|
|
210
|
+
def blank(start, end, *, both):
|
|
211
|
+
for i in range(start, end):
|
|
212
|
+
if source[i] != "\n":
|
|
213
|
+
mask[i] = " "
|
|
214
|
+
if both:
|
|
215
|
+
text[i] = " "
|
|
216
|
+
|
|
217
|
+
i = 0
|
|
218
|
+
while i < len(source):
|
|
219
|
+
if source.startswith("//", i):
|
|
220
|
+
end = source.find("\n", i)
|
|
221
|
+
end = len(source) if end < 0 else end
|
|
222
|
+
blank(i, end, both=True)
|
|
223
|
+
i = end
|
|
224
|
+
elif source.startswith("/*", i):
|
|
225
|
+
depth, start = 0, i
|
|
226
|
+
while i < len(source):
|
|
227
|
+
if source.startswith("/*", i):
|
|
228
|
+
depth, i = depth + 1, i + 2
|
|
229
|
+
elif source.startswith("*/", i):
|
|
230
|
+
depth, i = depth - 1, i + 2
|
|
231
|
+
if not depth:
|
|
232
|
+
break
|
|
233
|
+
else:
|
|
234
|
+
i += 1
|
|
235
|
+
blank(start, i, both=True)
|
|
236
|
+
elif raw := re.compile(r'(?<!\w)[bc]?r(#*)"').match(source, i):
|
|
237
|
+
close = source.find('"' + raw[1], raw.end())
|
|
238
|
+
content_end = len(source) if close < 0 else close
|
|
239
|
+
blank(raw.end(), content_end, both=False)
|
|
240
|
+
i = content_end + 1 + len(raw[1])
|
|
241
|
+
literals.append((raw.start(), min(i, len(source))))
|
|
242
|
+
elif source[i] == '"':
|
|
243
|
+
opening = i
|
|
244
|
+
start = i = i + 1
|
|
245
|
+
while i < len(source) and source[i] != '"':
|
|
246
|
+
i += 2 if source[i] == "\\" else 1
|
|
247
|
+
blank(start, min(i, len(source)), both=False)
|
|
248
|
+
i += 1
|
|
249
|
+
literals.append((opening, min(i, len(source))))
|
|
250
|
+
elif char := re.compile(r"'(?:\\.[^']*|[^'\\])'").match(source, i):
|
|
251
|
+
blank(char.start() + 1, char.end() - 1, both=False)
|
|
252
|
+
i = char.end()
|
|
253
|
+
literals.append(char.span())
|
|
254
|
+
else:
|
|
255
|
+
i += 1
|
|
256
|
+
return RustSource("".join(text), "".join(mask), literals)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def after_closing(mask, opener):
|
|
260
|
+
closer = {"(": ")", "[": "]", "{": "}"}[mask[opener]]
|
|
261
|
+
depth = 0
|
|
262
|
+
for i in range(opener, len(mask)):
|
|
263
|
+
depth += (mask[i] == mask[opener]) - (mask[i] == closer)
|
|
264
|
+
if not depth:
|
|
265
|
+
return i + 1
|
|
266
|
+
raise ValueError(f"unbalanced {mask[opener]} at offset {opener}")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class RustFunction(NamedTuple):
|
|
270
|
+
name: str
|
|
271
|
+
start: int
|
|
272
|
+
body: int
|
|
273
|
+
end: int
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b")
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def rust_functions(mask):
|
|
280
|
+
"""Locate free functions under inline modules; leave macro and other item bodies opaque."""
|
|
281
|
+
functions, opaque, counts = [], [], {}
|
|
282
|
+
|
|
283
|
+
def walk(start, end, namespace=(), in_function=False):
|
|
284
|
+
i, boundary, item = start, start, None
|
|
285
|
+
while i < end:
|
|
286
|
+
if match := RUST_ITEM.match(mask, i):
|
|
287
|
+
item = (match[1], match[2])
|
|
288
|
+
i = match.end()
|
|
289
|
+
elif mask[i] in "([":
|
|
290
|
+
stop = after_closing(mask, i)
|
|
291
|
+
if mask[boundary:i].rstrip().endswith("!"):
|
|
292
|
+
opaque.append((i, stop))
|
|
293
|
+
i = stop
|
|
294
|
+
elif mask[i] == "{":
|
|
295
|
+
stop = after_closing(mask, i)
|
|
296
|
+
header = mask[boundary:i].rstrip()
|
|
297
|
+
macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
|
|
298
|
+
if item and not macro:
|
|
299
|
+
kind, name = item
|
|
300
|
+
qualified = (*namespace, name)
|
|
301
|
+
if kind == "fn":
|
|
302
|
+
owner = "::".join(qualified)
|
|
303
|
+
counts[owner] = counts.get(owner, 0) + 1
|
|
304
|
+
suffix = f"[{counts[owner]}]" if counts[owner] > 1 else ""
|
|
305
|
+
functions.append(RustFunction(owner + suffix, boundary, i, stop))
|
|
306
|
+
walk(i + 1, stop - 1, qualified, kind == "fn")
|
|
307
|
+
elif in_function and not macro and not re.search(r"\b(?:impl|trait|struct|enum|union|extern|macro)\b", header):
|
|
308
|
+
walk(i + 1, stop - 1, namespace, True)
|
|
309
|
+
else:
|
|
310
|
+
opaque.append((i, stop))
|
|
311
|
+
i = boundary = stop
|
|
312
|
+
item = None
|
|
313
|
+
else:
|
|
314
|
+
if mask[i] == ";":
|
|
315
|
+
boundary, item = i + 1, None
|
|
316
|
+
i += 1
|
|
317
|
+
|
|
318
|
+
walk(0, len(mask))
|
|
319
|
+
return functions, opaque
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
|
|
323
|
+
MACROS = (
|
|
324
|
+
("assume", re.compile(r"\bkani\s*::\s*assume\s*\(")),
|
|
325
|
+
("assume", re.compile(r"\bkani\s*::\s*any_where\s*(?:::\s*<[^<>]*(?:<[^<>]*>[^<>]*)*>\s*)?\(")),
|
|
326
|
+
("cover", re.compile(r"\bkani\s*::\s*cover\s*!\s*\(")),
|
|
327
|
+
("stub", re.compile(KANI_ATTRIBUTE + r"stub\s*\(")),
|
|
328
|
+
)
|
|
329
|
+
PROOF = re.compile(KANI_ATTRIBUTE + r"proof(?:_for_contract\s*\([^)]*\))?\s*\)?\s*\]")
|
|
330
|
+
KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof)\w*\b")
|
|
331
|
+
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")
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def kani_surface(path):
|
|
335
|
+
source = rust_masks(path.read_text(encoding="utf-8"))
|
|
336
|
+
text, mask = source.uncommented, source.without_comments_or_strings
|
|
337
|
+
if renaming := RENAMING_IMPORT.search(mask):
|
|
338
|
+
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")
|
|
339
|
+
functions, opaque = rust_functions(mask)
|
|
340
|
+
|
|
341
|
+
def owner_at(position, *, attribute=False):
|
|
342
|
+
if not any(start <= position < end for start, end in opaque):
|
|
343
|
+
for function in reversed(functions):
|
|
344
|
+
if function.start <= position < function.end and (position < function.body if attribute else position > function.body):
|
|
345
|
+
return function.name
|
|
346
|
+
line = mask.count("\n", 0, position) + 1
|
|
347
|
+
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")
|
|
348
|
+
|
|
349
|
+
surface = Surface()
|
|
350
|
+
spans, read = [], []
|
|
351
|
+
for kind, pattern in MACROS:
|
|
352
|
+
for match in pattern.finditer(mask):
|
|
353
|
+
end = after_closing(mask, match.end() - 1)
|
|
354
|
+
read.append((match.start(), end))
|
|
355
|
+
argument = rust_masks(text[match.end():end - 1])
|
|
356
|
+
owner = owner_at(match.start(), attribute=kind == "stub")
|
|
357
|
+
spans.append((match.start(), f"{kind} {collapse(argument.uncommented, argument.literals)} in {owner}"))
|
|
358
|
+
for match in PROOF.finditer(mask):
|
|
359
|
+
read.append(match.span())
|
|
360
|
+
spans.append((match.start(), f"harness {owner_at(match.start(), attribute=True)}"))
|
|
361
|
+
for token in KANI_TOKEN.finditer(mask):
|
|
362
|
+
if not any(start <= token.start() < end for start, end in read):
|
|
363
|
+
line = mask.count("\n", 0, token.start()) + 1
|
|
364
|
+
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, ...)]")
|
|
365
|
+
for _, item in sorted(spans):
|
|
366
|
+
surface.add(item)
|
|
367
|
+
return surface
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
SURFACES = {"lean": lean_surface, "tla": tla_surface, "kani": kani_surface}
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def digest(surface):
|
|
374
|
+
return hashlib.sha256(json.dumps(surface, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def read_record(path):
|
|
378
|
+
record = json.loads(path.read_text(encoding="utf-8"))
|
|
379
|
+
models = record.get("models") if isinstance(record, dict) else None
|
|
380
|
+
if not isinstance(models, dict) or record.get("format") != FORMAT:
|
|
381
|
+
raise ValueError(f"{path}: unsupported record format; run record with a new record file")
|
|
382
|
+
for model, entry in models.items():
|
|
383
|
+
if not isinstance(entry, dict) or entry.get("kind") not in SURFACES or not isinstance(entry.get("surface"), dict):
|
|
384
|
+
raise ValueError(f"{path}: malformed entry for {model}")
|
|
385
|
+
return models
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def write_record(path, models):
|
|
389
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
390
|
+
temporary = None
|
|
391
|
+
try:
|
|
392
|
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as stream:
|
|
393
|
+
temporary = Path(stream.name)
|
|
394
|
+
stream.write(json.dumps({"format": FORMAT, "models": models}, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
|
|
395
|
+
temporary.replace(path)
|
|
396
|
+
finally:
|
|
397
|
+
if temporary is not None:
|
|
398
|
+
temporary.unlink(missing_ok=True)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def record(record_path, files):
|
|
402
|
+
for file in files:
|
|
403
|
+
if file.suffix not in KINDS:
|
|
404
|
+
print(f"usage: {file} has no model surface; expected one of {', '.join(KINDS)}")
|
|
405
|
+
return 2
|
|
406
|
+
models = read_record(record_path) if record_path.exists() else {}
|
|
407
|
+
updates = {}
|
|
408
|
+
for file in files:
|
|
409
|
+
kind = KINDS[file.suffix]
|
|
410
|
+
surface = SURFACES[kind](file.resolve())
|
|
411
|
+
updates[str(file.resolve())] = {"kind": kind, "digest": digest(surface), "surface": surface}
|
|
412
|
+
for model, entry in updates.items():
|
|
413
|
+
print(f"RECORDED {model} {entry['digest']}")
|
|
414
|
+
previous = models.get(model, {}).get("digest")
|
|
415
|
+
if previous and previous != entry["digest"]:
|
|
416
|
+
print(f" previous {previous}")
|
|
417
|
+
write_record(record_path, {**models, **updates})
|
|
418
|
+
return 0
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def differences(kind, old, new):
|
|
422
|
+
lines = []
|
|
423
|
+
for name in old:
|
|
424
|
+
if name not in new:
|
|
425
|
+
lines.append(f" removed {name}")
|
|
426
|
+
elif old[name] != new[name]:
|
|
427
|
+
lines += [f" changed {name}", f" old: {old[name]}", f" new: {new[name]}"]
|
|
428
|
+
lines += [f" added {name}" for name in new if name not in old and name.split(" ", 1)[0] in NARROWING[kind]]
|
|
429
|
+
return lines
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def compare(record_path):
|
|
433
|
+
if not record_path.is_file():
|
|
434
|
+
print(f"usage: record file {record_path} does not exist; run record first")
|
|
435
|
+
return 2
|
|
436
|
+
models = read_record(record_path)
|
|
437
|
+
changed = 0
|
|
438
|
+
for model, entry in models.items():
|
|
439
|
+
try:
|
|
440
|
+
if not Path(model).is_file():
|
|
441
|
+
lines = [" file is missing"]
|
|
442
|
+
else:
|
|
443
|
+
lines = differences(entry["kind"], entry["surface"], SURFACES[entry["kind"]](Path(model)))
|
|
444
|
+
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
445
|
+
lines = [f" FAIL {error}"]
|
|
446
|
+
changed += bool(lines)
|
|
447
|
+
print(f"{'CHANGED' if lines else 'UNCHANGED'} {model}")
|
|
448
|
+
if lines:
|
|
449
|
+
print("\n".join(lines))
|
|
450
|
+
print(f"SUMMARY {len(models) - changed} unchanged, {changed} changed")
|
|
451
|
+
return int(changed > 0)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def main():
|
|
455
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
456
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
457
|
+
recording = commands.add_parser("record", help="record or update the entries for these model files")
|
|
458
|
+
recording.add_argument("record_file", type=Path)
|
|
459
|
+
recording.add_argument("models", nargs="+", type=Path)
|
|
460
|
+
commands.add_parser("compare", help="compare every recorded model with its file").add_argument("record_file", type=Path)
|
|
461
|
+
arguments = parser.parse_args()
|
|
462
|
+
if arguments.command == "record":
|
|
463
|
+
return record(arguments.record_file, arguments.models)
|
|
464
|
+
return compare(arguments.record_file)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
if __name__ == "__main__":
|
|
468
|
+
try:
|
|
469
|
+
sys.exit(main())
|
|
470
|
+
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
471
|
+
print(f"FAIL baseline: {error}")
|
|
472
|
+
sys.exit(1)
|
|
@@ -66,6 +66,7 @@ class Kani:
|
|
|
66
66
|
if any(home.glob("*.tar.gz")):
|
|
67
67
|
raise Unavailable(f"incomplete Kani setup at {home}; finish cargo kani setup before checking")
|
|
68
68
|
self.driver = bundle / "bin/kani-driver"
|
|
69
|
+
self.cargo = bundle / "toolchain/bin/cargo"
|
|
69
70
|
self.env = os.environ | {
|
|
70
71
|
"KANI_HOME": str(home),
|
|
71
72
|
"RUSTUP_TOOLCHAIN": str((bundle / "toolchain").resolve()),
|
|
@@ -95,6 +96,42 @@ class Kani:
|
|
|
95
96
|
except OSError as error:
|
|
96
97
|
raise CheckError(f"cannot execute Kani: {error}") from error
|
|
97
98
|
|
|
99
|
+
def source_roots(self, crate, work):
|
|
100
|
+
"""Find each local package's workspace, including transitive and optional path dependencies."""
|
|
101
|
+
pending, visited, roots = {crate}, set(), set()
|
|
102
|
+
while pending:
|
|
103
|
+
directory = pending.pop()
|
|
104
|
+
if directory in visited:
|
|
105
|
+
continue
|
|
106
|
+
visited.add(directory)
|
|
107
|
+
try:
|
|
108
|
+
done = subprocess.run(
|
|
109
|
+
[str(self.cargo), "metadata", *(["--no-deps"] if directory != crate else []),
|
|
110
|
+
"--format-version", "1", "--manifest-path", str(directory / "Cargo.toml")],
|
|
111
|
+
cwd=work, env=self.env, capture_output=True, text=True, check=False)
|
|
112
|
+
except OSError as error:
|
|
113
|
+
raise CheckError(f"cannot read Cargo metadata: {error}") from error
|
|
114
|
+
if done.returncode:
|
|
115
|
+
raise CheckError(f"Cargo metadata failed for {directory}:\n{done.stdout}{done.stderr}")
|
|
116
|
+
try:
|
|
117
|
+
report = json.loads(done.stdout)
|
|
118
|
+
if report["version"] != 1:
|
|
119
|
+
raise CheckError("unsupported Cargo metadata version")
|
|
120
|
+
paths = [Path(report["workspace_root"]), directory]
|
|
121
|
+
for package in report["packages"]:
|
|
122
|
+
if package["source"] is not None:
|
|
123
|
+
continue
|
|
124
|
+
paths.append(Path(package["manifest_path"]).parent)
|
|
125
|
+
paths.extend(Path(dependency["path"]) for dependency in package["dependencies"] if "path" in dependency)
|
|
126
|
+
if not all(path.is_absolute() for path in paths):
|
|
127
|
+
raise CheckError("Cargo metadata returned a relative source path")
|
|
128
|
+
roots.add(paths[0].resolve())
|
|
129
|
+
roots.add(directory)
|
|
130
|
+
pending.update(path.resolve() for path in paths[2:])
|
|
131
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
132
|
+
raise CheckError(f"malformed Cargo metadata: {error}") from error
|
|
133
|
+
return roots
|
|
134
|
+
|
|
98
135
|
|
|
99
136
|
def invoke(crate, work, kani, *arguments):
|
|
100
137
|
return kani.run("--manifest-path", str(crate / "Cargo.toml"),
|