agent-formal-verify 0.4.8 → 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.
@@ -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 theorem no mutation breaks
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 itself; a failing #guard does not cover it. Private
21
- theorems are proof helpers and need no mutation. Exits 1 on a MISSED or
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 or a definition that
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 dataclasses import dataclass, field
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
- LEAN_PROPERTY = ("theorem", "lemma", "example", "#guard")
55
- LEAN_DECLARATION = re.compile(r"^(?:@\[.*?\] |private |protected |noncomputable )*((?:theorem|lemma|def|abbrev|instance|example|structure|inductive)\b(?: [^\s:(\[{]+)?|#guard.*|#eval.*)")
56
- # Fails the same way as lean-check.sh when the pin is not ready, without installing it.
57
- LEAN = """source "$1/lean-tools.sh"
58
- toolchain=$(lean_pin "$2") || { status=$?; echo "$toolchain"; exit "$status"; }
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: list = field(default_factory=list)
70
- new: list = field(default_factory=list)
71
- failed: 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()
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
- if not path.is_file():
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(Mutation(rest.strip()))
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 ("detects", "only"):
92
- setattr(mutations[-1], keyword, rest.strip())
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,156 @@ def parse(path):
99
127
  return mutations
100
128
 
101
129
 
102
- def mutated(model, mutation):
103
- 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["-"])
104
143
  count = text.count(old) if old else 0
105
144
  if count != 1:
106
- stop(f"mutation '{mutation.label}': its - text occurs {count} times in {model}, want 1")
107
- 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))
108
149
 
109
150
 
110
- def matrix_of(spec):
111
- """Return property kinds, reach directives by operator, and run lines for spec."""
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(mutated(spec, mutation), encoding="utf-8")
142
- matrix = work / spec.with_suffix(".matrix").name
143
- checks = reaches.get(mutation.detects, [f"check {kind} {mutation.detects}"])
144
- matrix.write_text("\n".join([f"spec {spec.name}", *checks, *runs]) + "\n", encoding="utf-8")
145
- command = ["bash", str(HERE / "tlc-matrix.sh"), str(matrix), *([mutation.only] if mutation.only else [])]
146
- done = subprocess.run(command, capture_output=True, text=True, check=False)
147
- if done.returncode == 3:
148
- return "UNAVAILABLE", done.stdout + done.stderr
149
- if done.returncode == 0:
150
- return "MISSED", ""
151
- if mutation.detects in reaches:
152
- prefix = f"FAIL {spec.stem} reach {mutation.detects.removeprefix('reach:')} "
153
- suffix = ": the model never reaches this state"
154
- for line in done.stdout.splitlines():
155
- if line.startswith(prefix) and line.endswith(suffix):
156
- label = line[len(prefix):-len(suffix)]
157
- return "DETECTED", f"{mutation.detects} fails in run '{label}' (the model never reaches this state)"
158
- return "ERROR", done.stdout + done.stderr
159
- # A deadlock stops the system for good, so it breaks a temporal property but no invariant.
160
- signs = ["violated"] + (["Deadlock reached"] if kind.startswith("PROPERT") else [])
161
- for line in done.stdout.splitlines():
162
- if line.startswith("FAIL ") and any(sign in line for sign in signs):
163
- run, _, error = line.removeprefix(f"FAIL {spec.stem} ").partition(": Error: ")
164
- return "DETECTED", f"{mutation.detects} fails in run '{run}' ({error.rstrip('.')})"
165
- return "ERROR", done.stdout + done.stderr
166
-
167
-
168
- def check_lean(model, project, mutation, work):
169
- """Return (verdict, detail) from Lean on the mutated module."""
170
- source, copy = mutated(model, mutation), work / model.name
171
- copy.write_text(source, encoding="utf-8")
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 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)],
173
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)
174
198
  output = done.stdout + done.stderr
175
- if done.returncode == 3:
176
- return "UNAVAILABLE", done.stdout + done.stderr
177
- if done.returncode == 0:
178
- return "MISSED", ""
179
- lines, failed = source.splitlines(), []
180
- for match in re.finditer(rf"^{re.escape(str(copy))}:(\d+):\d+: error", output, re.MULTILINE):
181
- for line in reversed(lines[:int(match[1])]):
182
- if declaration := LEAN_DECLARATION.match(line):
183
- if declaration[1] not in failed:
184
- failed.append(declaration[1])
185
- break
186
- if not failed or not all(name.startswith(LEAN_PROPERTY) for name in failed):
187
- return "ERROR", output
188
- mutation.failed = failed
189
- return "DETECTED", "fails " + "; ".join(failed)
190
-
191
-
192
- def check_rust(model, project, verifier, bounds, mutation, work):
193
- """Return (verdict, detail) from Kani on the named harness in a mutated copy of the crate."""
194
- copy = work / "crate"
195
- shutil.copytree(project, copy, ignore=shutil.ignore_patterns("target", ".git"))
196
- (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")
197
274
  outcome = kani.verify(copy, work, verifier, mutation.detects, bounds[mutation.detects])
198
275
  if outcome.verdict is kani.Verdict.PASS:
199
- return "MISSED", ""
276
+ return Result(Verdict.MISSED, covers=covers)
200
277
  if outcome.verdict is kani.Verdict.REFUTED:
201
- return "DETECTED", "; ".join(outcome.failures)
202
- 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)
203
280
 
204
281
 
205
282
  def project_root(model, *markers):
@@ -207,40 +284,60 @@ def project_root(model, *markers):
207
284
 
208
285
 
209
286
  def tla_runner(spec, mutations):
210
- 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)}
211
301
  for mutation in mutations:
212
302
  if mutation.detects not in kinds and mutation.detects not in reaches:
213
- stop(f"mutation '{mutation.label}': detects '{mutation.detects}', which {spec.with_suffix('.matrix')} does not check")
214
- 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)
215
310
 
216
311
 
217
- def lean_theorems(model):
218
- """Return the public theorems of model that its .statements file records, as check_lean names them."""
312
+ def frozen_theorems(model):
313
+ """Return the theorem names the model's .statements record holds."""
219
314
  record = model.with_suffix(".statements")
220
315
  if not record.is_file():
221
316
  stop(f"{record} is missing; freeze the model with lean-check.sh --freeze before checking its mutations")
222
- frozen = [entry["name"] for entry in json.loads(record.read_text(encoding="utf-8"))["declarations"]
223
- if entry["kind"] == "theorem"]
224
- theorems = set()
225
- for line in model.read_text(encoding="utf-8").splitlines():
226
- declaration = LEAN_DECLARATION.match(line)
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
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}")
234
322
 
235
323
 
236
324
  def lean_runner(model, mutations):
325
+ """Target the frozen theorems that Lean finds public in the source, including their namespaces."""
237
326
  project = project_root(model, "lakefile.toml", "lakefile.lean")
238
327
  if project is None:
239
328
  stop(f"{model} is in no Lake project")
240
- for mutation in mutations:
241
- if mutation.detects:
242
- stop(f"mutation '{mutation.label}': Lean mutations take no detects line; the runner names the theorems that fail")
243
- return lean_theorems(model), 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)
244
341
 
245
342
 
246
343
  def rust_runner(model, mutations):
@@ -255,47 +352,52 @@ def rust_runner(model, mutations):
255
352
  with tempfile.TemporaryDirectory(prefix="formal-kani-discover-") as temporary:
256
353
  try:
257
354
  bounds = kani.discover(project, Path(temporary), verifier)
355
+ sources = verifier.source_roots(project, Path(temporary))
258
356
  except kani.CheckError as error:
259
357
  stop(str(error))
260
358
  for mutation in mutations:
261
359
  if mutation.detects not in bounds:
262
360
  stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
263
- if mutation.only:
264
- stop("Rust mutations do not support 'only'")
265
- return set(bounds), partial(check_rust, model, project, verifier, bounds)
361
+ return set(bounds), partial(check_rust, model, project, verifier, bounds, sources)
266
362
 
267
363
 
268
- # Each runner validates the mutations, then returns the names they must cover and a check for one mutation.
364
+ # Each runner checks the names the mutations detect, then returns the names they must cover and a check for one mutation.
269
365
  # A TLA+ or Rust mutation covers the name it detects; a Lean mutation covers the theorems that fail on it.
270
- RUNNERS = {".tla": tla_runner, ".lean": lean_runner, ".rs": rust_runner}
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
+ }
271
371
 
272
372
 
273
373
  def main():
274
374
  if len(sys.argv) != 2:
275
375
  stop("usage: mutate.py <Name.mutations>", 2)
276
376
  path = Path(sys.argv[1]).resolve()
277
- mutations = parse(path)
278
- 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]
279
380
  model = next((model for model in models if model.is_file()), None)
280
381
  if model is None:
281
382
  stop(f"no {', '.join(model.name for model in models[:-1])} or {models[-1].name} beside {path}")
282
- 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)
283
386
 
284
- detected = 0
387
+ detected, covered = 0, set()
285
388
  for mutation in mutations:
286
389
  with tempfile.TemporaryDirectory() as work:
287
- verdict, detail = check(mutation, Path(work))
288
- if verdict == "UNAVAILABLE":
289
- print(detail.strip())
290
- sys.exit(3)
291
- if verdict == "ERROR":
292
- stop(f"mutation '{mutation.label}' did not reach a verdict:\n{detail.strip()}")
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))
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 ""))
296
396
  uncovered = sorted(targets - covered)
297
397
  for name in uncovered:
298
398
  print(f"UNCOVERED {name}")
399
+ if model.suffix == ".lean":
400
+ print(LEAN_NOTE)
299
401
  print(f"SUMMARY {detected} of {len(mutations)} mutations detected"
300
402
  + (f", {len(uncovered)} properties without a mutation" if uncovered else ""))
301
403
  sys.exit(0 if detected == len(mutations) and not uncovered else 1)