agent-formal-verify 0.4.5 → 0.4.9

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