agent-formal-verify 0.4.17 → 0.4.19
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 +39 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +6 -13
- package/skills/formal-verify/references/counter-examples.md +10 -0
- package/skills/formal-verify/references/evidence.md +2 -1
- package/skills/formal-verify/references/helpers.md +19 -7
- package/skills/formal-verify/references/setup.md +17 -4
- package/skills/formal-verify/references/tla-brief.md +16 -6
- package/skills/formal-verify/scripts/baseline.py +35 -6
- package/skills/formal-verify/scripts/kani.py +14 -8
- package/skills/formal-verify/scripts/kani_reader.py +64 -24
- package/skills/formal-verify/scripts/lean_mutations.py +8 -5
- package/skills/formal-verify/scripts/mutate.py +30 -16
- package/skills/formal-verify/scripts/processes.py +1 -1
- package/skills/formal-verify/scripts/rust_source.py +26 -15
- package/skills/formal-verify/scripts/tlc.py +170 -65
- package/skills/formal-verify/scripts/tlc_report.py +17 -10
- package/skills/setup/SKILL.md +1 -1
|
@@ -79,6 +79,7 @@ class CargoMetadata:
|
|
|
79
79
|
workspace: Path
|
|
80
80
|
target: Path
|
|
81
81
|
packages: tuple
|
|
82
|
+
local_build_script: bool
|
|
82
83
|
|
|
83
84
|
|
|
84
85
|
def tag_cache(directory):
|
|
@@ -90,6 +91,7 @@ def tag_cache(directory):
|
|
|
90
91
|
class CrateSources:
|
|
91
92
|
roots: set
|
|
92
93
|
outputs: set
|
|
94
|
+
local_build_script: bool = False
|
|
93
95
|
|
|
94
96
|
def stage(self, crate, work):
|
|
95
97
|
"""Copy local packages in their relative layout, omitting Cargo's build directories."""
|
|
@@ -171,13 +173,13 @@ class Kani:
|
|
|
171
173
|
except OSError as error:
|
|
172
174
|
raise CheckError(f"cannot execute Kani: {error}") from error
|
|
173
175
|
|
|
174
|
-
def cargo_metadata(self, crate, resolve=False):
|
|
176
|
+
def cargo_metadata(self, crate, resolve=False, *, cwd=None):
|
|
175
177
|
"""Read package declarations; resolve only when finding the full local source graph."""
|
|
176
178
|
try:
|
|
177
179
|
done = processes.run_captured(
|
|
178
180
|
[str(self.cargo), "metadata", *([] if resolve else ["--no-deps"]), "--format-version", "1",
|
|
179
181
|
"--manifest-path", str(crate / "Cargo.toml")],
|
|
180
|
-
cwd=crate, env=self.env)
|
|
182
|
+
cwd=cwd or crate, env=self.env)
|
|
181
183
|
except OSError as error:
|
|
182
184
|
raise CheckError(f"cannot read Cargo metadata: {error}") from error
|
|
183
185
|
if done.returncode:
|
|
@@ -189,13 +191,16 @@ class Kani:
|
|
|
189
191
|
workspace = Path(report["workspace_root"])
|
|
190
192
|
target = Path(report["target_directory"])
|
|
191
193
|
packages = []
|
|
194
|
+
local_build_script = False
|
|
192
195
|
for package in report["packages"]:
|
|
193
196
|
if package["source"] is None:
|
|
197
|
+
if any("custom-build" in item["kind"] for item in package["targets"]):
|
|
198
|
+
local_build_script = True
|
|
194
199
|
packages.append(Path(package["manifest_path"]).parent)
|
|
195
200
|
packages.extend(Path(dep["path"]) for dep in package["dependencies"] if "path" in dep)
|
|
196
201
|
if not all(path.is_absolute() for path in (workspace, target, *packages)):
|
|
197
202
|
raise CheckError("Cargo metadata returned a relative source path")
|
|
198
|
-
return CargoMetadata(workspace, target, tuple(packages))
|
|
203
|
+
return CargoMetadata(workspace, target, tuple(packages), local_build_script)
|
|
199
204
|
except (ValueError, KeyError, TypeError) as error:
|
|
200
205
|
raise CheckError(f"malformed Cargo metadata: {error}") from error
|
|
201
206
|
|
|
@@ -209,6 +214,7 @@ class Kani:
|
|
|
209
214
|
continue
|
|
210
215
|
visited.add(directory)
|
|
211
216
|
metadata = self.cargo_metadata(directory, resolve=directory == crate)
|
|
217
|
+
sources.local_build_script |= metadata.local_build_script
|
|
212
218
|
sources.roots.update((metadata.workspace.resolve(), directory))
|
|
213
219
|
sources.outputs.add(metadata.target.parent.resolve() / metadata.target.name)
|
|
214
220
|
pending.update(path.resolve() for path in metadata.packages)
|
|
@@ -232,15 +238,15 @@ def read_json(path):
|
|
|
232
238
|
raise CheckError(f"missing or invalid Kani report {path.name}: {error}") from error
|
|
233
239
|
|
|
234
240
|
|
|
235
|
-
def compiled(crate, work, kani):
|
|
241
|
+
def compiled(crate, work, kani, *, cwd=None):
|
|
236
242
|
"""Return each proof harness that Kani compiles in crate's targets, one per target that compiles it.
|
|
237
243
|
|
|
238
244
|
It compiles harness metadata without `list`, which writes into the source directory.
|
|
239
245
|
"""
|
|
240
246
|
if not (crate / "Cargo.toml").is_file():
|
|
241
247
|
raise CheckError(f"{crate}/Cargo.toml is missing")
|
|
242
|
-
workspace = kani.cargo_metadata(crate).workspace
|
|
243
|
-
done = invoke(crate, work, kani, "--only-codegen", label="discovery")
|
|
248
|
+
workspace = kani.cargo_metadata(crate, cwd=cwd).workspace
|
|
249
|
+
done = invoke(crate, work, kani, "--only-codegen", cwd=cwd, label="discovery")
|
|
244
250
|
if done.returncode:
|
|
245
251
|
output = done.stdout + done.stderr
|
|
246
252
|
if "error[E0658]" in output:
|
|
@@ -266,10 +272,10 @@ def compiled(crate, work, kani):
|
|
|
266
272
|
return found
|
|
267
273
|
|
|
268
274
|
|
|
269
|
-
def discover(crate, work, kani):
|
|
275
|
+
def discover(crate, work, kani, *, cwd=None):
|
|
270
276
|
"""Return the checker's harnesses in crate by name: each `#[kani::proof]` with its unwind bound and source."""
|
|
271
277
|
harnesses = {}
|
|
272
|
-
for harness in compiled(crate, work, kani):
|
|
278
|
+
for harness in compiled(crate, work, kani, cwd=cwd):
|
|
273
279
|
if harness.attributes.get("kind") != "Proof":
|
|
274
280
|
continue
|
|
275
281
|
bound = harness.attributes.get("unwind_value")
|
|
@@ -16,7 +16,8 @@ import storage
|
|
|
16
16
|
from rust_source import RustSource, after_closing, normalized, rust_masks
|
|
17
17
|
from surface import Surface, collapse
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
# A method's owner holds spaces, such as `proofs::<impl kani::Arbitrary for State>::any`.
|
|
20
|
+
KANI_KEY = re.compile(r"(harness |body |(?:assume|cover|stub) .* in )(.+?)( #\d+)?", re.DOTALL)
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
class RustFunction(NamedTuple):
|
|
@@ -25,30 +26,38 @@ class RustFunction(NamedTuple):
|
|
|
25
26
|
keyword: int
|
|
26
27
|
body: int
|
|
27
28
|
end: int
|
|
29
|
+
method: bool = False
|
|
28
30
|
|
|
29
31
|
|
|
30
|
-
RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b")
|
|
32
|
+
RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b|\b(impl|trait)\b")
|
|
31
33
|
INCLUDE = re.compile(r"\binclude\s*!$")
|
|
32
34
|
|
|
33
35
|
|
|
34
|
-
def rust_functions(
|
|
35
|
-
"""Locate free functions, inline modules, out-of-line
|
|
36
|
-
function bodies; leave macro and
|
|
36
|
+
def rust_functions(source):
|
|
37
|
+
"""Locate free functions, methods in `impl` and trait blocks outside function bodies, inline modules, out-of-line
|
|
38
|
+
`mod name;` declarations and `include!(...)` items outside function bodies and those blocks; leave macro and
|
|
39
|
+
other item bodies opaque, and return the `impl` and trait blocks apart.
|
|
37
40
|
|
|
38
|
-
A
|
|
41
|
+
A method's name puts its block's header between angle brackets, such as `proofs::<impl kani::Arbitrary for
|
|
42
|
+
State>::any`. A declaration's or an include's body is its `;`.
|
|
39
43
|
"""
|
|
40
|
-
|
|
44
|
+
mask = source.without_comments_or_strings
|
|
45
|
+
functions, modules, opaque, declarations, includes, blocks, counts = [], [], [], [], [], [], {}
|
|
41
46
|
|
|
42
47
|
def add_include(boundary, header, stop, in_body):
|
|
43
48
|
if not in_body and (include := INCLUDE.search(header)):
|
|
44
49
|
semicolon = re.compile(r"\s*;").match(mask, stop)
|
|
45
50
|
includes.append(RustFunction("include", boundary, boundary + include.start(), semicolon.end() - 1 if semicolon else stop - 1, stop))
|
|
46
51
|
|
|
47
|
-
def walk(start, end, namespace=(), in_function=False, in_body=False):
|
|
52
|
+
def walk(start, end, namespace=(), in_function=False, in_body=False, in_block=False):
|
|
48
53
|
i, boundary, item = start, start, None
|
|
49
54
|
while i < end:
|
|
50
55
|
if match := RUST_ITEM.match(mask, i):
|
|
51
|
-
item
|
|
56
|
+
# An `impl` after a pending item, such as `fn f() -> impl Trait`, is a type, not a block.
|
|
57
|
+
if match[3] is None:
|
|
58
|
+
item = (match[1], match[2], match.start())
|
|
59
|
+
elif item is None and not in_body:
|
|
60
|
+
item = (match[3], None, match.start())
|
|
52
61
|
i = match.end()
|
|
53
62
|
elif mask[i] in "([":
|
|
54
63
|
stop = after_closing(mask, i)
|
|
@@ -61,14 +70,22 @@ def rust_functions(mask):
|
|
|
61
70
|
stop = after_closing(mask, i)
|
|
62
71
|
header = mask[boundary:i].rstrip()
|
|
63
72
|
macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
|
|
64
|
-
if item and
|
|
73
|
+
if item and item[0] in ("impl", "trait"):
|
|
74
|
+
# A braced const argument in the header ends before the next generic argument or closing angle.
|
|
75
|
+
if re.compile(r"\s*[,>]").match(mask, stop):
|
|
76
|
+
i = stop
|
|
77
|
+
continue
|
|
78
|
+
# A block's items are no module's items, so an include! or mod in it is no route.
|
|
79
|
+
blocks.append((i, stop))
|
|
80
|
+
walk(i + 1, stop - 1, (*namespace, f"<{normalized(source.uncommented[item[2]:i])}>"), in_body=True, in_block=True)
|
|
81
|
+
elif item and not macro:
|
|
65
82
|
kind, name, keyword = item
|
|
66
83
|
qualified = (*namespace, name)
|
|
67
84
|
if kind == "fn":
|
|
68
85
|
owner = "::".join(qualified)
|
|
69
86
|
counts[owner] = counts.get(owner, 0) + 1
|
|
70
87
|
suffix = f"[{counts[owner]}]" if counts[owner] > 1 else ""
|
|
71
|
-
functions.append(RustFunction(owner + suffix, boundary, keyword, i, stop))
|
|
88
|
+
functions.append(RustFunction(owner + suffix, boundary, keyword, i, stop, method=in_block))
|
|
72
89
|
else:
|
|
73
90
|
modules.append(RustFunction("::".join(qualified), boundary, keyword, i, stop))
|
|
74
91
|
walk(i + 1, stop - 1, qualified, kind == "fn", in_body or kind == "fn")
|
|
@@ -87,7 +104,7 @@ def rust_functions(mask):
|
|
|
87
104
|
i += 1
|
|
88
105
|
|
|
89
106
|
walk(0, len(mask))
|
|
90
|
-
return functions, modules, opaque, declarations, includes
|
|
107
|
+
return functions, modules, opaque, declarations, includes, blocks
|
|
91
108
|
|
|
92
109
|
|
|
93
110
|
KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
|
|
@@ -102,11 +119,28 @@ HARNESS_ATTRIBUTE = re.compile(r"kani::(?:should_panic(?:\(\)|\[\]|\{\})?|unwind
|
|
|
102
119
|
KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof|should_panic|unwind)\w*\b")
|
|
103
120
|
ATTRIBUTE = re.compile(r"#\s*(!\s*)?\[")
|
|
104
121
|
STATEMENT_END = re.compile(r"\s*;")
|
|
105
|
-
|
|
122
|
+
# The mask blanks character contents. String comparisons can call stubbed library code.
|
|
123
|
+
SCALAR_LITERAL = r"""(?:true|false|-?[0-9]\w*(?:\.[0-9]\w*)?(?:[eE][+-][0-9_]+)?|b?'\s*')"""
|
|
124
|
+
LITERAL_COMPARISON = re.compile(rf"{SCALAR_LITERAL}\s*(?:==|!=|<=|>=|<|>)\s*{SCALAR_LITERAL}")
|
|
125
|
+
BOOLEAN_NAME = re.compile(r"(?:r#)?[^\W\d]\w*")
|
|
106
126
|
INNER_ATTRIBUTE = re.compile(r"[\s\ufeff]*#\s*!\s*\[")
|
|
107
127
|
RENAMING_IMPORT = re.compile(r"\buse\s+[^;]*?(?<![\w:])(?:::\s*)?kani\b[^;]*?(?:\bas\b|\*|\b(?:assume|any_where|cover|stub|proof|should_panic|unwind)\w*\b)|\bextern\s+crate\s+kani\s+as\b")
|
|
108
128
|
|
|
109
129
|
|
|
130
|
+
def inert_cover(arguments):
|
|
131
|
+
"""Only omit conditions that cannot call an overloaded Rust operator or access a field via Deref."""
|
|
132
|
+
condition = arguments.partition(",")[0].strip()
|
|
133
|
+
if not condition:
|
|
134
|
+
return True
|
|
135
|
+
for part in re.split(r"&&|\|\|", condition):
|
|
136
|
+
operand = part.strip()
|
|
137
|
+
if operand in ("return", "break", "continue", "yield"):
|
|
138
|
+
return False
|
|
139
|
+
if not BOOLEAN_NAME.fullmatch(operand) and not LITERAL_COMPARISON.fullmatch(operand):
|
|
140
|
+
return False
|
|
141
|
+
return True
|
|
142
|
+
|
|
143
|
+
|
|
110
144
|
def applies_cfg(attribute):
|
|
111
145
|
"""Return whether a compact `cfg_attr(predicate, attribute, ...)` applies a cfg or a module path in its own
|
|
112
146
|
attribute list."""
|
|
@@ -231,9 +265,9 @@ HIDDEN_ROUTE = re.compile(r"\bmod\s+(?:\$\w+|(?:r#)?\w+)\s*;|\binclude\s*!\s*[(\
|
|
|
231
265
|
def parse_rust(path):
|
|
232
266
|
source = rust_masks(path.read_text(encoding="utf-8"))
|
|
233
267
|
mask = source.without_comments_or_strings
|
|
234
|
-
functions, modules, opaque, declarations, includes = rust_functions(
|
|
268
|
+
functions, modules, opaque, declarations, includes, blocks = rust_functions(source)
|
|
235
269
|
hidden = {}
|
|
236
|
-
for start, end in opaque + [(function.body, function.end) for function in functions]:
|
|
270
|
+
for start, end in opaque + blocks + [(function.body, function.end) for function in functions]:
|
|
237
271
|
for match in HIDDEN_ROUTE.finditer(mask, start, end):
|
|
238
272
|
stop = match.end() - 1 if match[0].startswith("mod") else after_closing(mask, match.end() - 1)
|
|
239
273
|
route = rust_masks(source.uncommented[match.start():stop])
|
|
@@ -484,7 +518,7 @@ def kani_surface(path, reader):
|
|
|
484
518
|
text, mask = source.uncommented, source.without_comments_or_strings
|
|
485
519
|
if renaming := RENAMING_IMPORT.search(mask):
|
|
486
520
|
raise ValueError(f"{path}: '{collapse(renaming[0])}' brings a Kani assumption, cover, stub, harness or harness attribute in under another name; write each as kani::<name> so the record can read it")
|
|
487
|
-
functions, modules, opaque, _
|
|
521
|
+
functions, modules, opaque, *_ = rust_functions(source)
|
|
488
522
|
declared = route_label(path, reader.routes(path))
|
|
489
523
|
unread = unread_label(path, reader.unread(path))
|
|
490
524
|
|
|
@@ -492,9 +526,12 @@ def kani_surface(path, reader):
|
|
|
492
526
|
if not any(start <= position < end for start, end in opaque):
|
|
493
527
|
for function in reversed(functions):
|
|
494
528
|
if function.start <= position < function.end and (position < function.body if attribute else position > function.body):
|
|
529
|
+
# The record reads a harness, its attributes and its stubs only on a free function.
|
|
530
|
+
if attribute and function.method:
|
|
531
|
+
break
|
|
495
532
|
return function
|
|
496
533
|
line = mask.count("\n", 0, position) + 1
|
|
497
|
-
raise ValueError(f"{path}:{line}: cannot identify a function owner; write Kani forms in free functions under inline modules, outside macro definitions and
|
|
534
|
+
raise ValueError(f"{path}:{line}: cannot identify a function owner; write Kani forms in free functions under inline modules or in methods of impl or trait blocks outside function bodies, outside macro definitions, and put Kani attributes on free functions")
|
|
498
535
|
|
|
499
536
|
surface = Surface()
|
|
500
537
|
spans, read, covers = [], [], []
|
|
@@ -503,7 +540,7 @@ def kani_surface(path, reader):
|
|
|
503
540
|
end = after_closing(mask, match.end() - 1)
|
|
504
541
|
read.append((match.start(), end))
|
|
505
542
|
# A cover whose condition can run code, such as a call or a `return`, can change what its harness checks.
|
|
506
|
-
if kind == "cover" and
|
|
543
|
+
if kind == "cover" and inert_cover(mask[match.end():end - 1]):
|
|
507
544
|
covers.append((match.start(), end))
|
|
508
545
|
# The generator's explicit type arguments constrain its domain alongside its predicate.
|
|
509
546
|
if kind == "any_where":
|
|
@@ -519,9 +556,9 @@ def kani_surface(path, reader):
|
|
|
519
556
|
if HARNESS_ATTRIBUTE.fullmatch(item := re.sub(r"\s+", "", mask[start:end])):
|
|
520
557
|
read.append((start, end))
|
|
521
558
|
attributes.setdefault(owner_at(start, attribute=True), []).append(item)
|
|
522
|
-
def body(function):
|
|
559
|
+
def body(function, start):
|
|
523
560
|
# Each cover is an item of its own, so an added cover leaves the body as it was.
|
|
524
|
-
kept
|
|
561
|
+
kept = []
|
|
525
562
|
for begin, end in covers:
|
|
526
563
|
if function.body < begin < function.end:
|
|
527
564
|
kept.append(text[start:begin])
|
|
@@ -538,14 +575,17 @@ def kani_surface(path, reader):
|
|
|
538
575
|
guards = cfg_guards(source, [(0, 0, -1)] + [(item.start, item.keyword, item.body) for item in enclosing])
|
|
539
576
|
value = " ".join(filter(None, (declared, guards, *sorted(attributes.get(harness, ())), unread)))
|
|
540
577
|
spans.append((match.start(), f"harness {harness.name}", value))
|
|
541
|
-
spans.append((harness.body, f"body {harness.name}", body(harness)))
|
|
578
|
+
spans.append((harness.body, f"body {harness.name}", body(harness, harness.body)))
|
|
542
579
|
# A function in a module that holds a harness, or under one, such as an input helper, is part of what it checks.
|
|
543
580
|
scopes = {max((module for module in modules if module.start <= harness.start < module.end), key=lambda module: module.start, default=None)
|
|
544
581
|
for harness in harnesses}
|
|
582
|
+
recorded_end = 0
|
|
545
583
|
for function in functions:
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
584
|
+
if function.start >= recorded_end and any(scope is None or scope.start <= function.start < scope.end for scope in scopes):
|
|
585
|
+
# Functions arrive in source order. A recorded outer body already includes its local items.
|
|
586
|
+
recorded_end = function.end
|
|
587
|
+
if function not in harnesses:
|
|
588
|
+
spans.append((function.body, f"body {function.name}", body(function, function.start)))
|
|
549
589
|
for token in KANI_TOKEN.finditer(mask):
|
|
550
590
|
if not any(start <= token.start() < end for start, end in read):
|
|
551
591
|
line = mask.count("\n", 0, token.start()) + 1
|
|
@@ -39,11 +39,14 @@ def _checked_record(model, project):
|
|
|
39
39
|
return record
|
|
40
40
|
|
|
41
41
|
|
|
42
|
-
def _analyze(model, project, toolchain):
|
|
43
|
-
"""Get Lean's declaration identities and error positions, never infer them from source text.
|
|
42
|
+
def _analyze(model, project, toolchain, label):
|
|
43
|
+
"""Get Lean's declaration identities and error positions, never infer them from source text.
|
|
44
|
+
|
|
45
|
+
While Lean runs, report the elapsed time on stderr as '[lean] <label>: <N>s elapsed'.
|
|
46
|
+
"""
|
|
44
47
|
done = processes.run_captured(["elan", "run", toolchain, "lake", "--dir", str(project), "env", "lean", "--run",
|
|
45
48
|
str(HERE / "lean-analysis.lean"), "analyze", str(model)],
|
|
46
|
-
encoding="utf-8", errors="replace")
|
|
49
|
+
label=f"[lean] {label}", encoding="utf-8", errors="replace")
|
|
47
50
|
output = done.stdout + done.stderr
|
|
48
51
|
records = [line.removeprefix("AFV_LEAN ") for line in done.stdout.splitlines() if line.startswith("AFV_LEAN ")]
|
|
49
52
|
if done.returncode != 0 or len(records) != 1:
|
|
@@ -184,12 +187,12 @@ def prepare(model, project):
|
|
|
184
187
|
record = _checked_record(model, project)
|
|
185
188
|
pin = record["toolchain"]
|
|
186
189
|
frozen = {entry["name"] for entry in record["declarations"] if entry["kind"] == "theorem"}
|
|
187
|
-
original = OriginalChecks(model, frozen, _analyze(model, project, pin))
|
|
190
|
+
original = OriginalChecks(model, frozen, _analyze(model, project, pin, "unmutated model"))
|
|
188
191
|
|
|
189
192
|
def check(mutation, work):
|
|
190
193
|
copy = work / model.name
|
|
191
194
|
source = mutation.apply()
|
|
192
195
|
copy.write_text(source, encoding="utf-8")
|
|
193
|
-
return original.broken_checks(mutation, source, copy, _analyze(copy, project, pin))
|
|
196
|
+
return original.broken_checks(mutation, source, copy, _analyze(copy, project, pin, f"mutation {mutation.label}"))
|
|
194
197
|
|
|
195
198
|
return original.targets, check
|
|
@@ -113,6 +113,13 @@ class Result:
|
|
|
113
113
|
covers: frozenset = frozenset()
|
|
114
114
|
|
|
115
115
|
|
|
116
|
+
@dataclass(frozen=True)
|
|
117
|
+
class Prepared:
|
|
118
|
+
targets: set
|
|
119
|
+
check: Callable
|
|
120
|
+
summary_suffix: str = ""
|
|
121
|
+
|
|
122
|
+
|
|
116
123
|
def stop(message, status=1):
|
|
117
124
|
print(f"FAIL {message}")
|
|
118
125
|
sys.exit(status)
|
|
@@ -184,10 +191,15 @@ def check_lean(broken_checks, mutation, work):
|
|
|
184
191
|
def check_rust(model, project, verifier, bounds, sources, kani_work, mutation, work):
|
|
185
192
|
"""Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness.
|
|
186
193
|
|
|
187
|
-
|
|
188
|
-
|
|
194
|
+
A local build script can both save an absolute source path and generate files inside the source tree.
|
|
195
|
+
It must run for each fresh copy. Otherwise preserve the paths of both source and target for Cargo.
|
|
189
196
|
"""
|
|
190
|
-
|
|
197
|
+
if sources.local_build_script:
|
|
198
|
+
kani_work = work
|
|
199
|
+
else:
|
|
200
|
+
kani.tag_cache(work)
|
|
201
|
+
(kani_work / "source").rename(work / "previous")
|
|
202
|
+
copy = sources.stage(project, kani_work)
|
|
191
203
|
covers = frozenset({mutation.detects})
|
|
192
204
|
(copy / model.relative_to(project)).write_text(mutation.apply(), encoding="utf-8")
|
|
193
205
|
# Cargo resolves configuration from cwd, including paths outside the copied packages.
|
|
@@ -220,13 +232,14 @@ def tla_runner(spec, mutations, run):
|
|
|
220
232
|
plan.selected(mutation.detects, mutation.only)
|
|
221
233
|
except ValueError as error:
|
|
222
234
|
stop(f"mutation '{mutation.label}': {error}")
|
|
223
|
-
checker = tlc.
|
|
235
|
+
checker = tlc.engine()
|
|
224
236
|
with tempfile.TemporaryDirectory(prefix="formal-tlc-originals-", dir=storage.ensure_temp_root()) as temporary:
|
|
237
|
+
print(f"ENGINE {checker.label}", flush=True)
|
|
225
238
|
try:
|
|
226
239
|
plan.check_originals(checker, [(mutation.detects, mutation.only) for mutation in mutations], Path(temporary))
|
|
227
240
|
except ValueError as error:
|
|
228
241
|
stop(str(error))
|
|
229
|
-
return plan.properties, partial(check_tla, plan, checker)
|
|
242
|
+
return Prepared(plan.properties, partial(check_tla, plan, checker), checker.summary_suffix)
|
|
230
243
|
|
|
231
244
|
|
|
232
245
|
def lean_runner(model, mutations, run):
|
|
@@ -235,7 +248,7 @@ def lean_runner(model, mutations, run):
|
|
|
235
248
|
if project is None:
|
|
236
249
|
stop(f"{model} is in no Lake project")
|
|
237
250
|
targets, broken_checks = lean_mutations.prepare(model, project)
|
|
238
|
-
return targets, partial(check_lean, broken_checks)
|
|
251
|
+
return Prepared(targets, partial(check_lean, broken_checks))
|
|
239
252
|
|
|
240
253
|
|
|
241
254
|
def rust_runner(model, mutations, run):
|
|
@@ -245,25 +258,25 @@ def rust_runner(model, mutations, run):
|
|
|
245
258
|
stop(f"{model} is in no Rust crate")
|
|
246
259
|
verifier = kani.Kani()
|
|
247
260
|
work = Path(run.enter_context(tempfile.TemporaryDirectory(prefix="formal-kani-", dir=storage.ensure_temp_root())))
|
|
248
|
-
# A temporary root inside the crate holds this directory while the mutations stage copies of the crate.
|
|
249
|
-
kani.tag_cache(work)
|
|
250
261
|
try:
|
|
251
|
-
bounds = kani.discover(project, work, verifier)
|
|
252
262
|
sources = verifier.crate_sources(project)
|
|
263
|
+
copy = sources.stage(project, work)
|
|
264
|
+
bounds = kani.discover(copy, work, verifier, cwd=project)
|
|
253
265
|
for mutation in mutations:
|
|
254
266
|
if mutation.detects not in bounds:
|
|
255
267
|
stop(f"mutation '{mutation.label}': unknown harness '{mutation.detects}'")
|
|
256
268
|
selected = {mutation.detects for mutation in mutations}
|
|
257
269
|
kani.reject_should_panic(bounds, sorted(selected))
|
|
258
270
|
for name in sorted(selected):
|
|
259
|
-
outcome = kani.verify(
|
|
271
|
+
outcome = kani.verify(copy, work, verifier, name, bounds[name].unwind, cwd=project)
|
|
260
272
|
if outcome.verdict is not kani.Verdict.PASS:
|
|
261
273
|
stop(f"unmutated Rust harness '{name}' did not pass: "
|
|
262
274
|
+ "; ".join(outcome.failures) + "\n" + outcome.output)
|
|
263
275
|
except kani.CheckError as error:
|
|
264
276
|
stop(str(error))
|
|
265
|
-
|
|
266
|
-
|
|
277
|
+
staged_model = copy / model.relative_to(project)
|
|
278
|
+
targets = {name for name, harness in bounds.items() if harness.source == staged_model} | selected
|
|
279
|
+
return Prepared(targets, partial(check_rust, model, project, verifier, bounds, sources, work))
|
|
267
280
|
|
|
268
281
|
|
|
269
282
|
# Each runner checks the names the mutations detect and that the unmutated model passes the checks they select,
|
|
@@ -296,26 +309,27 @@ def main():
|
|
|
296
309
|
language, text = LANGUAGES[model.suffix], model.read_text(encoding="utf-8")
|
|
297
310
|
mutations = [make_mutation(label, directives, model, text, language) for label, directives in parse(path)]
|
|
298
311
|
with contextlib.ExitStack() as run:
|
|
299
|
-
|
|
312
|
+
prepared = language.runner(model, mutations, run)
|
|
300
313
|
storage.warn_runtime()
|
|
301
314
|
temp_root = storage.ensure_temp_root()
|
|
302
315
|
|
|
303
316
|
detected, covered = 0, set()
|
|
304
317
|
for mutation in mutations:
|
|
305
318
|
with tempfile.TemporaryDirectory(dir=temp_root) as work:
|
|
306
|
-
result = check(mutation, Path(work))
|
|
319
|
+
result = prepared.check(mutation, Path(work))
|
|
307
320
|
if result.verdict is Verdict.ERROR:
|
|
308
321
|
stop(f"mutation '{mutation.label}' did not reach a verdict:\n{result.detail.strip()}")
|
|
309
322
|
detected += result.verdict is Verdict.DETECTED
|
|
310
323
|
covered |= result.covers
|
|
311
324
|
print(f"{result.verdict.value} {mutation.label}" + (f": {result.detail}" if result.detail else ""), flush=True)
|
|
312
|
-
uncovered = sorted(targets - covered)
|
|
325
|
+
uncovered = sorted(prepared.targets - covered)
|
|
313
326
|
for name in uncovered:
|
|
314
327
|
print(f"UNCOVERED {name}")
|
|
315
328
|
if model.suffix == ".lean":
|
|
316
329
|
print(LEAN_NOTE)
|
|
317
330
|
print(f"SUMMARY {detected} of {len(mutations)} mutations detected"
|
|
318
|
-
+ (f", {len(uncovered)} properties without a mutation" if uncovered else "")
|
|
331
|
+
+ (f", {len(uncovered)} properties without a mutation" if uncovered else "")
|
|
332
|
+
+ prepared.summary_suffix)
|
|
319
333
|
return 0 if detected == len(mutations) and not uncovered else 1
|
|
320
334
|
|
|
321
335
|
|
|
@@ -231,7 +231,7 @@ def guarded(command, body, **kwargs):
|
|
|
231
231
|
|
|
232
232
|
def communicate(process, label=None):
|
|
233
233
|
"""Return process.communicate(); with a label, write '<label>: <N>s elapsed' to stderr while the process runs."""
|
|
234
|
-
if label is None:
|
|
234
|
+
if label is None or sys.stderr is None:
|
|
235
235
|
return process.communicate()
|
|
236
236
|
start = time.monotonic()
|
|
237
237
|
next_report = start + PROGRESS_DELAY
|
|
@@ -67,32 +67,43 @@ def rust_masks(source):
|
|
|
67
67
|
|
|
68
68
|
# A `#` joins a word into a raw identifier or string, such as `r#x`.
|
|
69
69
|
WORD = re.compile(r"[\w#]")
|
|
70
|
-
#
|
|
71
|
-
|
|
70
|
+
# Include comment openers: removing the space in a division followed by a dereference would start a comment.
|
|
71
|
+
COMPOUND = {"==", "!=", "<=", ">=", "&&", "||", "+=", "-=", "*=", "/=", "%=", "^=", "&=", "|=",
|
|
72
|
+
"<<", ">>", "<<=", ">>=", "->", "=>", "::", "..", "...", "..=", "//", "/*"}
|
|
73
|
+
PUNCTUATION = re.compile("|".join(re.escape(op) for op in sorted(COMPOUND, key=len, reverse=True)) + r"|[!%&*+./:<=>^|-]")
|
|
74
|
+
MACRO_GROUP = re.compile(r"(?:\bmacro_rules\s*!\s*\w+\s*|\b\w+\s*!\s*)[({\[]|#\s*!?\s*\[")
|
|
72
75
|
|
|
73
76
|
|
|
74
77
|
def normalized(source):
|
|
75
|
-
"""
|
|
76
|
-
|
|
77
|
-
One space stays between two word characters, literals or `#`, so `r #x` stays apart from `r#x`, and between two
|
|
78
|
-
operator characters, so `& &x` stays apart from `&&x`.
|
|
79
|
-
"""
|
|
78
|
+
"""Compact Rust source while keeping literals, token boundaries and punctuation spacing inside macro inputs."""
|
|
80
79
|
lexed = rust_masks(source)
|
|
81
80
|
text = lexed.uncommented
|
|
82
81
|
inside = {i for start, end in lexed.literals for i in range(start, end)}
|
|
83
82
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
83
|
+
mask = lexed.without_comments_or_strings
|
|
84
|
+
punctuation = {match.end(): match[0] for match in PUNCTUATION.finditer(mask)}
|
|
85
|
+
# A procedural macro sees joint punctuation even when Rust has no compound operator for it.
|
|
86
|
+
macro_spaces = set()
|
|
87
|
+
end = 0
|
|
88
|
+
while match := MACRO_GROUP.search(mask, end):
|
|
89
|
+
end = after_closing(mask, match.end() - 1)
|
|
90
|
+
macro_spaces.update(run.start() for run in re.compile(r"\s+").finditer(mask, match.end(), end))
|
|
91
|
+
|
|
92
|
+
def word(i):
|
|
93
|
+
return i in inside or WORD.match(text, i)
|
|
88
94
|
|
|
89
95
|
def space(run):
|
|
90
|
-
|
|
96
|
+
start, end = run.span()
|
|
97
|
+
if start in inside:
|
|
91
98
|
return run[0]
|
|
92
|
-
if
|
|
99
|
+
if start == 0 or end == len(text):
|
|
93
100
|
return ""
|
|
94
|
-
|
|
95
|
-
|
|
101
|
+
if word(start - 1) and word(end):
|
|
102
|
+
return " "
|
|
103
|
+
left = punctuation.get(start)
|
|
104
|
+
if left and (left + text[end] in COMPOUND or start in macro_spaces and PUNCTUATION.match(mask, end)):
|
|
105
|
+
return " "
|
|
106
|
+
return ""
|
|
96
107
|
|
|
97
108
|
return re.sub(r"\s+", space, text)
|
|
98
109
|
|