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
|
@@ -11,17 +11,23 @@ per mutation:
|
|
|
11
11
|
DETECTED <label>: <what failed> the mutated model fails as it should
|
|
12
12
|
MISSED <label> the mutated model still passes
|
|
13
13
|
UNCOVERED <Property> a TLA+ property or Rust harness no mutation
|
|
14
|
-
targets, or a Lean
|
|
14
|
+
targets, or a Lean proof no mutation breaks
|
|
15
15
|
|
|
16
16
|
A TLA+ mutation is checked against the property or reach operator it names,
|
|
17
17
|
using the matrix runs. A Lean mutation is elaborated in the project, the mutated
|
|
18
18
|
module alone, and reported with the theorems, lemmas, examples and #guard
|
|
19
19
|
lines that fail. Every public theorem recorded in the model's .statements file
|
|
20
|
-
must fail on some mutation
|
|
21
|
-
|
|
20
|
+
must have its proof fail on some mutation; a failing #guard does not cover it.
|
|
21
|
+
Errors in a theorem, example or #guard count only when the unmutated model has
|
|
22
|
+
the same statement as Lean elaborates it; renaming a definition that a statement
|
|
23
|
+
names, for example, changes that statement and gives the mutation no verdict.
|
|
24
|
+
Lean reports fully qualified theorem names from elaborated declarations.
|
|
25
|
+
This measures proof sensitivity, not whether a mutated statement is false or
|
|
26
|
+
its hypotheses can hold. Private theorems are proof helpers and need no mutation. Exits 1 on a MISSED or
|
|
22
27
|
UNCOVERED line, when a Lean model has no .statements file, or when a mutated
|
|
23
|
-
model fails for another reason, such as a syntax error
|
|
24
|
-
no longer compiles
|
|
28
|
+
model fails for another reason, such as a syntax error, a definition that
|
|
29
|
+
no longer compiles or a Lean theorem, example or #guard whose statement the
|
|
30
|
+
mutation changes.
|
|
25
31
|
|
|
26
32
|
Mutations file (a line starting with # is a comment):
|
|
27
33
|
mutation <label> starts a mutation
|
|
@@ -32,43 +38,68 @@ Mutations file (a line starting with # is a comment):
|
|
|
32
38
|
consecutive lines must occur exactly once
|
|
33
39
|
+ <text> a line of the replacement; none deletes the text
|
|
34
40
|
|
|
41
|
+
A TLA+ or Rust mutation needs one detects line, and a Lean mutation takes
|
|
42
|
+
none. The runner reads every mutation and applies it to the model's text
|
|
43
|
+
before it runs any tool, so a malformed mutation stops the run first.
|
|
44
|
+
|
|
35
45
|
Usage: mutate.py <Name.mutations>
|
|
36
46
|
The environment settings of tlc-matrix.sh apply to TLA+ mutations.
|
|
37
47
|
"""
|
|
38
48
|
import json
|
|
39
|
-
import re
|
|
40
49
|
import shutil
|
|
41
50
|
import subprocess
|
|
42
51
|
import sys
|
|
43
52
|
import tempfile
|
|
44
|
-
from
|
|
53
|
+
from collections.abc import Callable
|
|
54
|
+
from dataclasses import dataclass
|
|
55
|
+
from enum import Enum
|
|
45
56
|
from functools import partial
|
|
57
|
+
from os.path import commonpath
|
|
46
58
|
from pathlib import Path
|
|
47
59
|
|
|
48
|
-
# Importing kani must not write __pycache__ into the skill directory.
|
|
60
|
+
# Importing kani and tlc must not write __pycache__ into the skill directory.
|
|
49
61
|
sys.dont_write_bytecode = True
|
|
50
62
|
|
|
51
63
|
import kani
|
|
64
|
+
import tlc
|
|
52
65
|
|
|
53
66
|
HERE = Path(__file__).resolve().parent
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
lean_pin_ready "$toolchain" || { echo "UNAVAILABLE $toolchain is not ready; run bash $1/setup.sh lean $2"; exit 3; }
|
|
60
|
-
elan run "$toolchain" lake --dir "$2" env lean "$3"
|
|
61
|
-
"""
|
|
67
|
+
LEAN_NOTE = "NOTE Lean detections mean existing proofs fail, not that theorem statements are false or hypotheses satisfiable."
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
DIRECTIVES = ("detects", "only", "-", "+")
|
|
71
|
+
SINGLE = ("detects", "only")
|
|
62
72
|
|
|
63
73
|
|
|
64
|
-
@dataclass
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class Language:
|
|
76
|
+
name: str
|
|
77
|
+
needs_detects: bool
|
|
78
|
+
takes_only: bool
|
|
79
|
+
runner: Callable
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
65
83
|
class Mutation:
|
|
66
84
|
label: str
|
|
67
|
-
detects: str
|
|
68
|
-
only: str
|
|
69
|
-
old:
|
|
70
|
-
new:
|
|
71
|
-
|
|
85
|
+
detects: str
|
|
86
|
+
only: str
|
|
87
|
+
old: str
|
|
88
|
+
new: str
|
|
89
|
+
source: str
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Verdict(Enum):
|
|
93
|
+
DETECTED = "DETECTED"
|
|
94
|
+
MISSED = "MISSED"
|
|
95
|
+
ERROR = "ERROR"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class Result:
|
|
100
|
+
verdict: Verdict
|
|
101
|
+
detail: str = ""
|
|
102
|
+
covers: frozenset = frozenset()
|
|
72
103
|
|
|
73
104
|
|
|
74
105
|
def stop(message, status=1):
|
|
@@ -77,21 +108,18 @@ def stop(message, status=1):
|
|
|
77
108
|
|
|
78
109
|
|
|
79
110
|
def parse(path):
|
|
80
|
-
|
|
81
|
-
stop(f"{path} does not exist")
|
|
111
|
+
"""Return each mutation's label with its directives as (keyword, rest) pairs, in file order."""
|
|
82
112
|
mutations = []
|
|
83
113
|
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
|
|
84
114
|
if not line.strip() or line.startswith("#"):
|
|
85
115
|
continue
|
|
86
116
|
keyword, _, rest = line.partition(" ")
|
|
87
117
|
if keyword == "mutation":
|
|
88
|
-
mutations.append(
|
|
118
|
+
mutations.append((rest.strip(), []))
|
|
89
119
|
elif not mutations:
|
|
90
120
|
stop(f"{path}:{number}: '{line}' before any mutation line")
|
|
91
|
-
elif keyword in
|
|
92
|
-
|
|
93
|
-
elif keyword in ("-", "+"):
|
|
94
|
-
(mutations[-1].old if keyword == "-" else mutations[-1].new).append(rest)
|
|
121
|
+
elif keyword in DIRECTIVES:
|
|
122
|
+
mutations[-1][1].append((keyword, rest))
|
|
95
123
|
else:
|
|
96
124
|
stop(f"{path}:{number}: unknown directive: {line}")
|
|
97
125
|
if not mutations:
|
|
@@ -99,107 +127,155 @@ def parse(path):
|
|
|
99
127
|
return mutations
|
|
100
128
|
|
|
101
129
|
|
|
102
|
-
def
|
|
103
|
-
|
|
130
|
+
def make_mutation(label, directives, model, text, language):
|
|
131
|
+
"""Check one mutation's directives against its language and apply it to the model's text."""
|
|
132
|
+
lines = {keyword: [rest for word, rest in directives if word == keyword] for keyword in DIRECTIVES}
|
|
133
|
+
for keyword in SINGLE:
|
|
134
|
+
if len(lines[keyword]) > 1:
|
|
135
|
+
stop(f"mutation '{label}' has two {keyword} lines")
|
|
136
|
+
if lines["detects"] and not language.needs_detects:
|
|
137
|
+
stop(f"mutation '{label}': {language.name} mutations take no detects line; the runner names the theorems that fail")
|
|
138
|
+
if language.needs_detects and not lines["detects"]:
|
|
139
|
+
stop(f"mutation '{label}' has no detects line")
|
|
140
|
+
if lines["only"] and not language.takes_only:
|
|
141
|
+
stop(f"mutation '{label}': {language.name} mutations do not support 'only'")
|
|
142
|
+
old = "\n".join(lines["-"])
|
|
104
143
|
count = text.count(old) if old else 0
|
|
105
144
|
if count != 1:
|
|
106
|
-
stop(f"mutation '{
|
|
107
|
-
|
|
145
|
+
stop(f"mutation '{label}': its - text occurs {count} times in {model}, want 1")
|
|
146
|
+
detects, only = (lines[keyword][0].strip() if lines[keyword] else "" for keyword in SINGLE)
|
|
147
|
+
new = "\n".join(lines["+"])
|
|
148
|
+
return Mutation(label, detects, only, old, new, text.replace(old, new))
|
|
108
149
|
|
|
109
150
|
|
|
110
|
-
def
|
|
111
|
-
"""
|
|
112
|
-
matrix, kinds, reaches, runs, ours = spec.with_suffix(".matrix"), {}, {}, [], False
|
|
113
|
-
if not matrix.is_file():
|
|
114
|
-
stop(f"{matrix} is missing; mutations use its checks and runs")
|
|
115
|
-
for line in matrix.read_text(encoding="utf-8").splitlines():
|
|
116
|
-
keyword, _, rest = line.split("#")[0].strip().partition(" ")
|
|
117
|
-
if keyword == "spec":
|
|
118
|
-
ours = rest.strip() == spec.name
|
|
119
|
-
elif ours and keyword == "check":
|
|
120
|
-
parts = rest.split()
|
|
121
|
-
if len(parts) < 2 or parts[0] not in ("INVARIANT", "INVARIANTS", "PROPERTY", "PROPERTIES"):
|
|
122
|
-
stop(f"{matrix}: malformed check '{rest}'")
|
|
123
|
-
kind, *names = parts
|
|
124
|
-
kinds.update(dict.fromkeys(names, kind))
|
|
125
|
-
elif ours and keyword == "run":
|
|
126
|
-
runs.append(f"run {rest}")
|
|
127
|
-
elif ours and keyword == "reach":
|
|
128
|
-
operator, bar, label = rest.partition("|")
|
|
129
|
-
operator = operator.strip()
|
|
130
|
-
if not bar or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", operator) or not label.strip():
|
|
131
|
-
stop(f"{matrix}: malformed reach '{rest}'")
|
|
132
|
-
reaches.setdefault(f"reach:{operator}", []).append(f"reach {rest}")
|
|
133
|
-
return kinds, reaches, runs
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
def check_tla(spec, kinds, reaches, runs, mutation, work):
|
|
137
|
-
"""Return (verdict, detail) from the mutation's property or reach checks."""
|
|
138
|
-
kind = kinds.get(mutation.detects, "")
|
|
151
|
+
def check_tla(spec, checker, kinds, section, mutation, work):
|
|
152
|
+
"""Run the mutated spec through tlc-matrix.sh's runner with only the mutation's check; it covers the name it detects."""
|
|
139
153
|
for module in spec.parent.glob("*.tla"):
|
|
140
154
|
(work / module.name).write_text(module.read_text(encoding="utf-8"), encoding="utf-8")
|
|
141
|
-
(work / spec.name).write_text(
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
if
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
done = subprocess.run(["bash", "-c", LEAN, "bash", str(HERE), str(project), str(copy)],
|
|
155
|
+
(work / spec.name).write_text(mutation.source, encoding="utf-8")
|
|
156
|
+
kind, covers = kinds.get(mutation.detects, ""), frozenset({mutation.detects})
|
|
157
|
+
if kind:
|
|
158
|
+
checks = [tlc.Check(f"{kind} {mutation.detects}", kind, (mutation.detects,))]
|
|
159
|
+
else:
|
|
160
|
+
checks = [d for d in section if isinstance(d, tlc.Reach) and f"reach:{d.operator}" == mutation.detects]
|
|
161
|
+
results = []
|
|
162
|
+
runner = tlc.Runner(checker, work, mutation.only, results.append, work)
|
|
163
|
+
for task in tlc.execution_plan([tlc.Spec(spec.name), *checks, *(d for d in section if isinstance(d, tlc.Run))]):
|
|
164
|
+
runner.check(task)
|
|
165
|
+
if runner.runs_total == 0:
|
|
166
|
+
return Result(Verdict.ERROR, f"no run matches '{mutation.only}'")
|
|
167
|
+
if not runner.failed:
|
|
168
|
+
return Result(Verdict.MISSED, covers=covers)
|
|
169
|
+
if kind:
|
|
170
|
+
# A deadlock stops the system for good, so it breaks a temporal property but no invariant.
|
|
171
|
+
signs = ["violated"] + (["Deadlock reached"] if kind.startswith("PROPERT") else [])
|
|
172
|
+
for result in results:
|
|
173
|
+
if result.outcome is tlc.Outcome.FAIL and any(sign in result.detail for sign in signs):
|
|
174
|
+
error = result.detail.removeprefix("Error: ").rstrip(".")
|
|
175
|
+
return Result(Verdict.DETECTED, f"{mutation.detects} fails in run '{result.label}' ({error})", covers)
|
|
176
|
+
else:
|
|
177
|
+
for result in results:
|
|
178
|
+
if result.outcome is tlc.Outcome.UNREACHED:
|
|
179
|
+
return Result(Verdict.DETECTED, f"{mutation.detects} fails in run '{result.label}' (the model never reaches this state)", covers)
|
|
180
|
+
return Result(Verdict.ERROR, "\n".join(line for result in results for line in tlc.render(result)))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def lean_toolchain(project):
|
|
184
|
+
"""Return the project's Lean pin once it is ready; lean-tools.sh owns the check and its remedy."""
|
|
185
|
+
done = subprocess.run(["bash", "-c", 'source "$1/lean-tools.sh" && lean_ready_pin "$2"', "bash", str(HERE), str(project)],
|
|
173
186
|
capture_output=True, text=True, check=False)
|
|
187
|
+
if done.returncode:
|
|
188
|
+
print(done.stdout.strip())
|
|
189
|
+
sys.exit(done.returncode)
|
|
190
|
+
return done.stdout.strip()
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def lean_analysis(model, project, toolchain):
|
|
194
|
+
"""Get Lean's declaration identities and error positions, never infer them from source text."""
|
|
195
|
+
done = subprocess.run(["elan", "run", toolchain, "lake", "--dir", str(project), "env", "lean", "--run",
|
|
196
|
+
str(HERE / "lean-mutations.lean"), str(model)], capture_output=True, text=True, check=False)
|
|
174
197
|
output = done.stdout + done.stderr
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
return "
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
def
|
|
193
|
-
"""
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
198
|
+
records = [line.removeprefix("AFV_LEAN ") for line in done.stdout.splitlines() if line.startswith("AFV_LEAN ")]
|
|
199
|
+
if done.returncode != 0 or len(records) != 1:
|
|
200
|
+
stop(f"Lean declaration analysis did not complete:\n{output.strip()}")
|
|
201
|
+
try:
|
|
202
|
+
analysis = json.loads(records[0])
|
|
203
|
+
for field in ("declarations", "commands", "errors"):
|
|
204
|
+
if not isinstance(analysis[field], list):
|
|
205
|
+
raise TypeError(f"{field} must be a list")
|
|
206
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
207
|
+
stop(f"invalid Lean declaration analysis: {error}")
|
|
208
|
+
return analysis
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def contains(item, position):
|
|
212
|
+
return item["start"] <= position < item["end"]
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def original_location(model, mutation, position):
|
|
216
|
+
"""Map an unchanged command back across the one replacement; label inserted commands explicitly."""
|
|
217
|
+
original, old, new = model.read_text(encoding="utf-8"), mutation.old, mutation.new
|
|
218
|
+
start = original.index(old)
|
|
219
|
+
offset = sum(len(line) + 1 for line in mutation.source.split("\n")[:position[0] - 1]) + position[1]
|
|
220
|
+
if offset < start:
|
|
221
|
+
original_offset, suffix = offset, ""
|
|
222
|
+
elif offset >= start + len(new):
|
|
223
|
+
original_offset, suffix = offset + len(old) - len(new), ""
|
|
224
|
+
else:
|
|
225
|
+
original_offset, suffix = start, " (mutation replacement)"
|
|
226
|
+
line = original.count("\n", 0, original_offset) + 1
|
|
227
|
+
return f"{model}:{line}{suffix}"
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def is_witness(name, declarations):
|
|
231
|
+
parent, _, last = name.rpartition(".")
|
|
232
|
+
return last == "witness" and any(decl["theorem"] and decl["name"] == parent for decl in declarations)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def check_lean(model, project, toolchain, unmutated_statements, mutation, work):
|
|
236
|
+
"""Attribute every error to an elaborated theorem, or else a guard/example command, whose statement the unmutated model also has; the mutation covers those."""
|
|
237
|
+
copy = work / model.name
|
|
238
|
+
copy.write_text(mutation.source, encoding="utf-8")
|
|
239
|
+
analysis = lean_analysis(copy, project, toolchain)
|
|
240
|
+
if not analysis["errors"]:
|
|
241
|
+
return Result(Verdict.MISSED)
|
|
242
|
+
failed = []
|
|
243
|
+
for error in analysis["errors"]:
|
|
244
|
+
position = [error["pos"]["line"], error["pos"]["column"]]
|
|
245
|
+
where = f"{error['fileName']}:{position[0]}:{position[1]}: {error['data']}"
|
|
246
|
+
checks = [("theorem " + decl["name"], (decl["name"], decl["type"]))
|
|
247
|
+
for decl in analysis["declarations"] if decl["theorem"] and contains(decl, position)]
|
|
248
|
+
if not checks:
|
|
249
|
+
checks = [(f"{cmd['property']} at {original_location(model, mutation, cmd['start'])}",
|
|
250
|
+
(cmd["property"], cmd["statement"]))
|
|
251
|
+
for cmd in analysis["commands"] if cmd["property"] and contains(cmd, position)]
|
|
252
|
+
for name, key in checks:
|
|
253
|
+
if key not in unmutated_statements:
|
|
254
|
+
return Result(Verdict.ERROR, f"{name}: the mutation changes its statement, "
|
|
255
|
+
f"so this error does not show its proof or check failing\n{where}")
|
|
256
|
+
if error["fileName"] != str(copy) or not checks:
|
|
257
|
+
return Result(Verdict.ERROR, where)
|
|
258
|
+
failed.extend(name for name, (property, _) in checks
|
|
259
|
+
if name not in failed and not is_witness(property, analysis["declarations"]))
|
|
260
|
+
if not failed:
|
|
261
|
+
return Result(Verdict.MISSED)
|
|
262
|
+
return Result(Verdict.DETECTED, "proof/check fails: " + "; ".join(failed), frozenset(failed))
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def check_rust(model, project, verifier, bounds, sources, mutation, work):
|
|
266
|
+
"""Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness."""
|
|
267
|
+
anchor = Path(commonpath(sources))
|
|
268
|
+
for source in sources:
|
|
269
|
+
if not any(parent in sources for parent in source.parents):
|
|
270
|
+
shutil.copytree(source, work / "source" / source.relative_to(anchor), ignore=shutil.ignore_patterns("target", ".git"))
|
|
271
|
+
copy, covers = work / "source" / project.relative_to(anchor), frozenset({mutation.detects})
|
|
272
|
+
(copy / model.relative_to(project)).write_text(mutation.source, encoding="utf-8")
|
|
197
273
|
outcome = kani.verify(copy, work, verifier, mutation.detects, bounds[mutation.detects])
|
|
198
274
|
if outcome.verdict is kani.Verdict.PASS:
|
|
199
|
-
return
|
|
275
|
+
return Result(Verdict.MISSED, covers=covers)
|
|
200
276
|
if outcome.verdict is kani.Verdict.REFUTED:
|
|
201
|
-
return
|
|
202
|
-
return
|
|
277
|
+
return Result(Verdict.DETECTED, "; ".join(outcome.failures), covers)
|
|
278
|
+
return Result(Verdict.ERROR, "\n".join(outcome.failures) + "\n" + outcome.output)
|
|
203
279
|
|
|
204
280
|
|
|
205
281
|
def project_root(model, *markers):
|
|
@@ -207,40 +283,60 @@ def project_root(model, *markers):
|
|
|
207
283
|
|
|
208
284
|
|
|
209
285
|
def tla_runner(spec, mutations):
|
|
210
|
-
|
|
286
|
+
"""Take the checks, reach operators and runs of spec's section of its matrix, and check TLC once."""
|
|
287
|
+
matrix = spec.with_suffix(".matrix")
|
|
288
|
+
if not matrix.is_file():
|
|
289
|
+
stop(f"{matrix} is missing; mutations use its checks and runs")
|
|
290
|
+
section, ours = [], False
|
|
291
|
+
for directive in tlc.directives(tlc.read_raw(matrix).split("\n")):
|
|
292
|
+
if isinstance(directive, tlc.Malformed):
|
|
293
|
+
stop(f"{matrix}: {directive.message}")
|
|
294
|
+
if isinstance(directive, tlc.Spec):
|
|
295
|
+
ours = (matrix.parent / directive.path).resolve() == spec
|
|
296
|
+
elif ours:
|
|
297
|
+
section.append(directive)
|
|
298
|
+
kinds = {name: d.kind for d in section if isinstance(d, tlc.Check) for name in d.names}
|
|
299
|
+
reaches = {f"reach:{d.operator}" for d in section if isinstance(d, tlc.Reach)}
|
|
211
300
|
for mutation in mutations:
|
|
212
301
|
if mutation.detects not in kinds and mutation.detects not in reaches:
|
|
213
|
-
stop(f"mutation '{mutation.label}': detects '{mutation.detects}', which {
|
|
214
|
-
|
|
302
|
+
stop(f"mutation '{mutation.label}': detects '{mutation.detects}', which {matrix} does not check")
|
|
303
|
+
try:
|
|
304
|
+
checker = tlc.Tlc()
|
|
305
|
+
except tlc.Unavailable as error:
|
|
306
|
+
print(error)
|
|
307
|
+
sys.exit(3)
|
|
308
|
+
return set(kinds), partial(check_tla, spec, checker, kinds, section)
|
|
215
309
|
|
|
216
310
|
|
|
217
|
-
def
|
|
218
|
-
"""Return the
|
|
311
|
+
def frozen_theorems(model):
|
|
312
|
+
"""Return the theorem names the model's .statements record holds."""
|
|
219
313
|
record = model.with_suffix(".statements")
|
|
220
314
|
if not record.is_file():
|
|
221
315
|
stop(f"{record} is missing; freeze the model with lean-check.sh --freeze before checking its mutations")
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
if not declaration or not declaration[1].startswith(("theorem ", "lemma ")) or "private " in line[:declaration.start(1)]:
|
|
228
|
-
continue
|
|
229
|
-
# The record holds full names and the source the name inside its namespace.
|
|
230
|
-
name = declaration[1].partition(" ")[2]
|
|
231
|
-
if any(full == name or full.endswith("." + name) for full in frozen):
|
|
232
|
-
theorems.add(declaration[1])
|
|
233
|
-
return theorems
|
|
316
|
+
try:
|
|
317
|
+
return {entry["name"] for entry in json.loads(record.read_text(encoding="utf-8"))["declarations"]
|
|
318
|
+
if entry["kind"] == "theorem"}
|
|
319
|
+
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
320
|
+
stop(f"invalid statements record {record}: {error}")
|
|
234
321
|
|
|
235
322
|
|
|
236
323
|
def lean_runner(model, mutations):
|
|
324
|
+
"""Target the frozen theorems that Lean finds public in the source, including their namespaces."""
|
|
237
325
|
project = project_root(model, "lakefile.toml", "lakefile.lean")
|
|
238
326
|
if project is None:
|
|
239
327
|
stop(f"{model} is in no Lake project")
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
328
|
+
frozen = frozen_theorems(model)
|
|
329
|
+
toolchain = lean_toolchain(project)
|
|
330
|
+
analysis = lean_analysis(model, project, toolchain)
|
|
331
|
+
if analysis["errors"]:
|
|
332
|
+
stop(f"unmutated Lean model does not elaborate: {analysis['errors'][0]['data']}")
|
|
333
|
+
targets = {"theorem " + decl["name"] for decl in analysis["declarations"]
|
|
334
|
+
if decl["theorem"] and not decl["private"] and decl["name"] in frozen
|
|
335
|
+
and not is_witness(decl["name"], analysis["declarations"])}
|
|
336
|
+
statements = {(decl["name"], decl["type"]) for decl in analysis["declarations"] if decl["theorem"]}
|
|
337
|
+
statements |= {(cmd["property"], cmd["statement"]) for cmd in analysis["commands"]
|
|
338
|
+
if cmd["property"] and cmd["statement"] is not None}
|
|
339
|
+
return targets, partial(check_lean, model, project, toolchain, statements)
|
|
244
340
|
|
|
245
341
|
|
|
246
342
|
def rust_runner(model, mutations):
|
|
@@ -255,47 +351,52 @@ def rust_runner(model, mutations):
|
|
|
255
351
|
with tempfile.TemporaryDirectory(prefix="formal-kani-discover-") as temporary:
|
|
256
352
|
try:
|
|
257
353
|
bounds = kani.discover(project, Path(temporary), verifier)
|
|
354
|
+
sources = verifier.source_roots(project, Path(temporary))
|
|
258
355
|
except kani.CheckError as error:
|
|
259
356
|
stop(str(error))
|
|
260
357
|
for mutation in mutations:
|
|
261
358
|
if mutation.detects not in bounds:
|
|
262
359
|
stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
|
|
263
|
-
|
|
264
|
-
stop("Rust mutations do not support 'only'")
|
|
265
|
-
return set(bounds), partial(check_rust, model, project, verifier, bounds)
|
|
360
|
+
return set(bounds), partial(check_rust, model, project, verifier, bounds, sources)
|
|
266
361
|
|
|
267
362
|
|
|
268
|
-
# Each runner
|
|
363
|
+
# Each runner checks the names the mutations detect, then returns the names they must cover and a check for one mutation.
|
|
269
364
|
# A TLA+ or Rust mutation covers the name it detects; a Lean mutation covers the theorems that fail on it.
|
|
270
|
-
|
|
365
|
+
LANGUAGES = {
|
|
366
|
+
".tla": Language("TLA+", needs_detects=True, takes_only=True, runner=tla_runner),
|
|
367
|
+
".lean": Language("Lean", needs_detects=False, takes_only=False, runner=lean_runner),
|
|
368
|
+
".rs": Language("Rust", needs_detects=True, takes_only=False, runner=rust_runner),
|
|
369
|
+
}
|
|
271
370
|
|
|
272
371
|
|
|
273
372
|
def main():
|
|
274
373
|
if len(sys.argv) != 2:
|
|
275
374
|
stop("usage: mutate.py <Name.mutations>", 2)
|
|
276
375
|
path = Path(sys.argv[1]).resolve()
|
|
277
|
-
|
|
278
|
-
|
|
376
|
+
if not path.is_file():
|
|
377
|
+
stop(f"{path} does not exist")
|
|
378
|
+
models = [path.with_suffix(suffix) for suffix in LANGUAGES]
|
|
279
379
|
model = next((model for model in models if model.is_file()), None)
|
|
280
380
|
if model is None:
|
|
281
381
|
stop(f"no {', '.join(model.name for model in models[:-1])} or {models[-1].name} beside {path}")
|
|
282
|
-
|
|
382
|
+
language, text = LANGUAGES[model.suffix], model.read_text(encoding="utf-8")
|
|
383
|
+
mutations = [make_mutation(label, directives, model, text, language) for label, directives in parse(path)]
|
|
384
|
+
targets, check = language.runner(model, mutations)
|
|
283
385
|
|
|
284
|
-
detected = 0
|
|
386
|
+
detected, covered = 0, set()
|
|
285
387
|
for mutation in mutations:
|
|
286
388
|
with tempfile.TemporaryDirectory() as work:
|
|
287
|
-
|
|
288
|
-
if verdict
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
detected += verdict == "DETECTED"
|
|
294
|
-
print(f"{verdict} {mutation.label}" + (f": {detail}" if detail else ""))
|
|
295
|
-
covered = {mutation.detects for mutation in mutations}.union(*(mutation.failed for mutation in mutations))
|
|
389
|
+
result = check(mutation, Path(work))
|
|
390
|
+
if result.verdict is Verdict.ERROR:
|
|
391
|
+
stop(f"mutation '{mutation.label}' did not reach a verdict:\n{result.detail.strip()}")
|
|
392
|
+
detected += result.verdict is Verdict.DETECTED
|
|
393
|
+
covered |= result.covers
|
|
394
|
+
print(f"{result.verdict.value} {mutation.label}" + (f": {result.detail}" if result.detail else ""))
|
|
296
395
|
uncovered = sorted(targets - covered)
|
|
297
396
|
for name in uncovered:
|
|
298
397
|
print(f"UNCOVERED {name}")
|
|
398
|
+
if model.suffix == ".lean":
|
|
399
|
+
print(LEAN_NOTE)
|
|
299
400
|
print(f"SUMMARY {detected} of {len(mutations)} mutations detected"
|
|
300
401
|
+ (f", {len(uncovered)} properties without a mutation" if uncovered else ""))
|
|
301
402
|
sys.exit(0 if detected == len(mutations) and not uncovered else 1)
|