agent-formal-verify 0.4.13 → 0.4.15
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 +32 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +10 -10
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +32 -3
- package/skills/formal-verify/references/setup.md +4 -4
- package/skills/formal-verify/references/tla-brief.md +1 -1
- package/skills/formal-verify/scripts/baseline.py +187 -636
- package/skills/formal-verify/scripts/kani.py +13 -4
- package/skills/formal-verify/scripts/kani_reader.py +597 -0
- package/skills/formal-verify/scripts/lean.py +24 -20
- package/skills/formal-verify/scripts/lean_mutations.py +12 -12
- package/skills/formal-verify/scripts/mutate.py +12 -8
- package/skills/formal-verify/scripts/rust_source.py +74 -0
- package/skills/formal-verify/scripts/surface.py +27 -0
- package/skills/formal-verify/scripts/sync.py +10 -9
- package/skills/formal-verify/scripts/tlc.py +107 -16
- package/skills/formal-verify/scripts/tlc_report.py +516 -0
- package/skills/formal-verify/scripts/tlc_trace.py +97 -0
|
@@ -86,17 +86,26 @@ class CrateSources:
|
|
|
86
86
|
roots: set
|
|
87
87
|
outputs: set
|
|
88
88
|
|
|
89
|
-
def stage(self, crate,
|
|
89
|
+
def stage(self, crate, work):
|
|
90
90
|
"""Copy local packages in their relative layout, omitting Cargo's build directories."""
|
|
91
91
|
anchor = Path(os.path.commonpath(self.roots))
|
|
92
|
+
work = work.resolve()
|
|
93
|
+
# Other mutations can stage into the same workspace-local temporary root.
|
|
94
|
+
(work / "CACHEDIR.TAG").write_text("Signature: 8a477f597d28d172789f06886806bc55\n", encoding="ascii")
|
|
95
|
+
destination = work / "source"
|
|
92
96
|
|
|
93
97
|
def ignore(directory, names):
|
|
94
98
|
# Cargo tags each build directory, including one left behind after the target directory moved.
|
|
95
99
|
# A dangling symlink, such as an editor's lock file, is skipped here because copytree's
|
|
96
100
|
# ignore_dangling_symlinks reaches only the top directory before Python 3.10.
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
101
|
+
directory = Path(directory).resolve()
|
|
102
|
+
skipped = []
|
|
103
|
+
for name in names:
|
|
104
|
+
path = directory / name
|
|
105
|
+
if (name == ".git" or path == work or path in self.outputs or (path / "CACHEDIR.TAG").is_file()
|
|
106
|
+
or path.is_symlink() and (not path.exists() or path.resolve().is_relative_to(work))):
|
|
107
|
+
skipped.append(name)
|
|
108
|
+
return skipped
|
|
100
109
|
|
|
101
110
|
for root in self.roots:
|
|
102
111
|
if self.roots.isdisjoint(root.parents):
|
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
# Copyright (c) 2026 Michael Denyer
|
|
2
|
+
# SPDX-License-Identifier: GPL-3.0-only
|
|
3
|
+
"""Read a Kani harness file's surface, the routes that lead to it from its crate roots, and what Kani compiles from it."""
|
|
4
|
+
import functools
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import NamedTuple
|
|
11
|
+
|
|
12
|
+
sys.dont_write_bytecode = True
|
|
13
|
+
import kani
|
|
14
|
+
import runner
|
|
15
|
+
import storage
|
|
16
|
+
from rust_source import RustSource, after_closing, rust_masks
|
|
17
|
+
from surface import Surface, collapse
|
|
18
|
+
|
|
19
|
+
KANI_KEY = re.compile(r"(harness |(?:assume|cover|stub) .* in )(\S+)( #\d+)?", re.DOTALL)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RustFunction(NamedTuple):
|
|
23
|
+
name: str
|
|
24
|
+
start: int
|
|
25
|
+
keyword: int
|
|
26
|
+
body: int
|
|
27
|
+
end: int
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
RUST_ITEM = re.compile(r"\b(fn|mod)\s+((?:r#)?\w+)\b")
|
|
31
|
+
INCLUDE = re.compile(r"\binclude\s*!$")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def rust_functions(mask):
|
|
35
|
+
"""Locate free functions, inline modules, out-of-line `mod name;` declarations and `include!(...)` items outside
|
|
36
|
+
function bodies; leave macro and other item bodies opaque.
|
|
37
|
+
|
|
38
|
+
A declaration's or an include's body is its `;`.
|
|
39
|
+
"""
|
|
40
|
+
functions, modules, opaque, declarations, includes, counts = [], [], [], [], [], {}
|
|
41
|
+
|
|
42
|
+
def add_include(boundary, header, stop, in_body):
|
|
43
|
+
if not in_body and (include := INCLUDE.search(header)):
|
|
44
|
+
semicolon = re.compile(r"\s*;").match(mask, stop)
|
|
45
|
+
includes.append(RustFunction("include", boundary, boundary + include.start(), semicolon.end() - 1 if semicolon else stop - 1, stop))
|
|
46
|
+
|
|
47
|
+
def walk(start, end, namespace=(), in_function=False, in_body=False):
|
|
48
|
+
i, boundary, item = start, start, None
|
|
49
|
+
while i < end:
|
|
50
|
+
if match := RUST_ITEM.match(mask, i):
|
|
51
|
+
item = (match[1], match[2], match.start())
|
|
52
|
+
i = match.end()
|
|
53
|
+
elif mask[i] in "([":
|
|
54
|
+
stop = after_closing(mask, i)
|
|
55
|
+
header = mask[boundary:i].rstrip()
|
|
56
|
+
if header.endswith("!"):
|
|
57
|
+
opaque.append((i, stop))
|
|
58
|
+
add_include(boundary, header, stop, in_body)
|
|
59
|
+
i = stop
|
|
60
|
+
elif mask[i] == "{":
|
|
61
|
+
stop = after_closing(mask, i)
|
|
62
|
+
header = mask[boundary:i].rstrip()
|
|
63
|
+
macro = header.endswith("!") or bool(re.search(r"\bmacro_rules\s*!\s*\w+\s*$", header))
|
|
64
|
+
if item and not macro:
|
|
65
|
+
kind, name, keyword = item
|
|
66
|
+
qualified = (*namespace, name)
|
|
67
|
+
if kind == "fn":
|
|
68
|
+
owner = "::".join(qualified)
|
|
69
|
+
counts[owner] = counts.get(owner, 0) + 1
|
|
70
|
+
suffix = f"[{counts[owner]}]" if counts[owner] > 1 else ""
|
|
71
|
+
functions.append(RustFunction(owner + suffix, boundary, keyword, i, stop))
|
|
72
|
+
else:
|
|
73
|
+
modules.append(RustFunction("::".join(qualified), boundary, keyword, i, stop))
|
|
74
|
+
walk(i + 1, stop - 1, qualified, kind == "fn", in_body or kind == "fn")
|
|
75
|
+
elif in_function and not macro and not re.search(r"\b(?:impl|trait|struct|enum|union|extern|macro)\b", header):
|
|
76
|
+
walk(i + 1, stop - 1, namespace, True, True)
|
|
77
|
+
else:
|
|
78
|
+
opaque.append((i, stop))
|
|
79
|
+
add_include(boundary, header, stop, in_body)
|
|
80
|
+
i = boundary = stop
|
|
81
|
+
item = None
|
|
82
|
+
else:
|
|
83
|
+
if mask[i] == ";":
|
|
84
|
+
if item and item[0] == "mod" and not in_body:
|
|
85
|
+
declarations.append(RustFunction("::".join((*namespace, item[1])), boundary, item[2], i, i + 1))
|
|
86
|
+
boundary, item = i + 1, None
|
|
87
|
+
i += 1
|
|
88
|
+
|
|
89
|
+
walk(0, len(mask))
|
|
90
|
+
return functions, modules, opaque, declarations, includes
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
|
|
94
|
+
MACROS = (
|
|
95
|
+
("assume", re.compile(r"\bkani\s*::\s*assume\s*\(")),
|
|
96
|
+
("any_where", re.compile(r"\bkani\s*::\s*any_where\s*(?:::\s*<[^<>]*(?:<[^<>]*>[^<>]*)*>\s*)?\(")),
|
|
97
|
+
("cover", re.compile(r"\bkani\s*::\s*cover\s*!\s*\(")),
|
|
98
|
+
("stub", re.compile(KANI_ATTRIBUTE + r"stub\s*\(")),
|
|
99
|
+
)
|
|
100
|
+
PROOF = re.compile(KANI_ATTRIBUTE + r"proof(?:_for_contract\s*\([^)]*\))?\s*\)?\s*\]")
|
|
101
|
+
HARNESS_ATTRIBUTE = re.compile(r"kani::(?:should_panic(?:\(\)|\[\]|\{\})?|unwind(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}))")
|
|
102
|
+
KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof|should_panic|unwind)\w*\b")
|
|
103
|
+
ATTRIBUTE = re.compile(r"#\s*(!\s*)?\[")
|
|
104
|
+
INNER_ATTRIBUTE = re.compile(r"[\s\ufeff]*#\s*!\s*\[")
|
|
105
|
+
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")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def applies_cfg(attribute):
|
|
109
|
+
"""Return whether a compact `cfg_attr(predicate, attribute, ...)` applies a cfg or a module path in its own
|
|
110
|
+
attribute list."""
|
|
111
|
+
arguments, depth, start = [], 0, len("cfg_attr(")
|
|
112
|
+
for i in range(start, len(attribute) - 1):
|
|
113
|
+
depth += (attribute[i] in "([{") - (attribute[i] in ")]}")
|
|
114
|
+
if attribute[i] == "," and not depth:
|
|
115
|
+
arguments.append(attribute[start:i])
|
|
116
|
+
start = i + 1
|
|
117
|
+
arguments.append(attribute[start:-1])
|
|
118
|
+
return any(argument.startswith(("cfg(", "path=")) or argument.startswith("cfg_attr(") and applies_cfg(argument) for argument in arguments[1:])
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def outer_attributes(source, start, keyword):
|
|
122
|
+
"""Yield the contents of each top-level outer attribute between start and keyword; skip inner attributes."""
|
|
123
|
+
mask = source.without_comments_or_strings
|
|
124
|
+
while attribute := ATTRIBUTE.search(mask, start, keyword):
|
|
125
|
+
opener = attribute.end() - 1
|
|
126
|
+
start = after_closing(mask, opener)
|
|
127
|
+
if not attribute[1]:
|
|
128
|
+
yield rust_masks(source.uncommented[opener + 1:start - 1])
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
CFG_ATTR_KANI = re.compile(r"\s*cfg_attr\s*\(\s*kani\s*,")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def applied_attributes(mask):
|
|
135
|
+
"""Yield the span of each attribute that an outer attribute in mask applies when Kani compiles it: the whole
|
|
136
|
+
attribute, or each argument after the condition of a `#[cfg_attr(kani, ...)]`."""
|
|
137
|
+
for attribute in ATTRIBUTE.finditer(mask):
|
|
138
|
+
if attribute[1]:
|
|
139
|
+
continue
|
|
140
|
+
opener = attribute.end() - 1
|
|
141
|
+
close = after_closing(mask, opener) - 1
|
|
142
|
+
if (condition := CFG_ATTR_KANI.match(mask, opener + 1, close)) is None:
|
|
143
|
+
yield opener + 1, close
|
|
144
|
+
continue
|
|
145
|
+
start, depth = condition.end(), 0
|
|
146
|
+
for i in range(start, close):
|
|
147
|
+
depth += (mask[i] in "([{") - (mask[i] in ")]}")
|
|
148
|
+
if depth < 0 or mask[i] == "," and not depth:
|
|
149
|
+
yield start, i
|
|
150
|
+
if depth < 0:
|
|
151
|
+
break
|
|
152
|
+
start = i + 1
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def cfg_guards(source, items):
|
|
156
|
+
"""Return the cfg attributes other than cfg(kani), and the cfg_attr ones whose attribute list applies a cfg or a
|
|
157
|
+
module path, on each (start, keyword, body) item, between its start and its fn or mod keyword, and at the start
|
|
158
|
+
of its body.
|
|
159
|
+
|
|
160
|
+
A body of -1 stands for the file, which has only inner attributes, and a body at a `;` for an out-of-line `mod`
|
|
161
|
+
declaration, which has none. An attribute nested inside another attribute's tokens is not read.
|
|
162
|
+
"""
|
|
163
|
+
text, mask = source.uncommented, source.without_comments_or_strings
|
|
164
|
+
guards = []
|
|
165
|
+
|
|
166
|
+
def read(attribute):
|
|
167
|
+
compact = re.sub(r"\s+", "", attribute.without_comments_or_strings)
|
|
168
|
+
if compact.startswith("cfg(") and compact != "cfg(kani)" or compact.startswith("cfg_attr(") and applies_cfg(compact):
|
|
169
|
+
guards.append(collapse(attribute.uncommented, attribute.literals))
|
|
170
|
+
|
|
171
|
+
for start, keyword, body in items:
|
|
172
|
+
if body >= 0:
|
|
173
|
+
for attribute in outer_attributes(source, start, keyword):
|
|
174
|
+
read(attribute)
|
|
175
|
+
if body >= 0 and mask[body] == ";":
|
|
176
|
+
continue
|
|
177
|
+
inner = body + 1
|
|
178
|
+
while attribute := INNER_ATTRIBUTE.match(mask, inner):
|
|
179
|
+
opener = attribute.end() - 1
|
|
180
|
+
inner = after_closing(mask, opener)
|
|
181
|
+
read(rust_masks(text[opener + 1:inner - 1]))
|
|
182
|
+
return " ".join(guards)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
PATH_ATTRIBUTE = re.compile(r"\bpath\s*=\s*")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def module_paths(source, item, file):
|
|
189
|
+
"""Return the paths that `#[path = "..."]` sets on a module item, and those that a cfg_attr may set."""
|
|
190
|
+
paths, conditional = [], []
|
|
191
|
+
for attribute in outer_attributes(source, item.start, item.keyword):
|
|
192
|
+
compact = re.sub(r"\s+", "", attribute.without_comments_or_strings)
|
|
193
|
+
if not compact.startswith(("path=", "cfg_attr(")):
|
|
194
|
+
continue
|
|
195
|
+
for setting in PATH_ATTRIBUTE.finditer(attribute.without_comments_or_strings):
|
|
196
|
+
value = string_value(next((attribute.uncommented[begin:end] for begin, end in attribute.literals if begin == setting.end()), ""))
|
|
197
|
+
if value is None:
|
|
198
|
+
# The item starts at the boundary after the previous item, or at the start of the file or a module
|
|
199
|
+
# body, so count from its own first token, after any inner attributes.
|
|
200
|
+
mask, first = source.without_comments_or_strings, item.start
|
|
201
|
+
while inner := INNER_ATTRIBUTE.match(mask, first):
|
|
202
|
+
first = after_closing(mask, inner.end() - 1)
|
|
203
|
+
first = re.compile(r"[\s]*").match(mask, first).end()
|
|
204
|
+
line = mask.count("\n", 0, first) + 1
|
|
205
|
+
raise ValueError(f"{file}:{line}: cannot read the path in '{collapse(attribute.uncommented, attribute.literals)}'; write it as a string without escapes")
|
|
206
|
+
(paths if compact.startswith("path=") else conditional).append(value)
|
|
207
|
+
return paths, conditional
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def string_value(literal):
|
|
211
|
+
"""Return the value of a Rust string literal without escapes, or None."""
|
|
212
|
+
plain = re.fullmatch(r'r(#*)"(.*)"\1', literal, re.DOTALL) or re.fullmatch(r'"([^"\\]*)"', literal)
|
|
213
|
+
return plain[plain.lastindex] if plain else None
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class RustFile(NamedTuple):
|
|
217
|
+
source: RustSource
|
|
218
|
+
modules: list
|
|
219
|
+
declarations: list
|
|
220
|
+
includes: list
|
|
221
|
+
# Each (position, route) that the route reader does not follow: a `mod <name>;` or `include!(...)` inside a macro,
|
|
222
|
+
# a function body or another block such as `const _: () = { ... }`.
|
|
223
|
+
hidden: list
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
HIDDEN_ROUTE = re.compile(r"\bmod\s+(?:\$\w+|(?:r#)?\w+)\s*;|\binclude\s*!\s*[(\[{]")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def parse_rust(path):
|
|
230
|
+
source = rust_masks(path.read_text(encoding="utf-8"))
|
|
231
|
+
mask = source.without_comments_or_strings
|
|
232
|
+
functions, modules, opaque, declarations, includes = rust_functions(mask)
|
|
233
|
+
hidden = {}
|
|
234
|
+
for start, end in opaque + [(function.body, function.end) for function in functions]:
|
|
235
|
+
for match in HIDDEN_ROUTE.finditer(mask, start, end):
|
|
236
|
+
stop = match.end() - 1 if match[0].startswith("mod") else after_closing(mask, match.end() - 1)
|
|
237
|
+
route = rust_masks(source.uncommented[match.start():stop])
|
|
238
|
+
hidden[match.start()] = collapse(route.uncommented, route.literals)
|
|
239
|
+
return RustFile(source, modules, declarations, includes, sorted(hidden.items()))
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def enclosing_modules(parsed, item):
|
|
243
|
+
return sorted((module for module in parsed.modules if module.start <= item.start < module.end), key=lambda module: module.start)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def module_files(file, owner, parsed, declaration):
|
|
247
|
+
"""Yield each file that an out-of-line `mod` declaration in file may load, by rustc's rules, and whether that
|
|
248
|
+
file owns its directory, as a crate root, a mod.rs or a `#[path]` file does."""
|
|
249
|
+
states = [(file.parent, file.parent if owner else file.parent / file.stem)]
|
|
250
|
+
for module in enclosing_modules(parsed, declaration):
|
|
251
|
+
paths, conditional = module_paths(parsed.source, module, file)
|
|
252
|
+
name = module.name.rsplit("::", 1)[-1].removeprefix("r#")
|
|
253
|
+
states = [(child, child) for directory, prefix in states for child in ([] if paths else [prefix / name]) + [directory / path for path in paths + conditional]]
|
|
254
|
+
paths, conditional = module_paths(parsed.source, declaration, file)
|
|
255
|
+
name = declaration.name.rsplit("::", 1)[-1].removeprefix("r#")
|
|
256
|
+
for directory, prefix in states:
|
|
257
|
+
if not paths:
|
|
258
|
+
yield prefix / f"{name}.rs", False
|
|
259
|
+
yield prefix / name / "mod.rs", True
|
|
260
|
+
for path in paths + conditional:
|
|
261
|
+
yield directory / path, True
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def crate_roots(path):
|
|
265
|
+
"""Return the crate roots whose module trees may hold path, and those of them that Cargo names, or None for a
|
|
266
|
+
file in no crate.
|
|
267
|
+
|
|
268
|
+
They are the lib.rs and main.rs in the nearest directory above path that holds either and, in the Cargo package
|
|
269
|
+
of the nearest directory above path with a Cargo.toml, Cargo's target files and each `.rs` path that Cargo.toml
|
|
270
|
+
names.
|
|
271
|
+
"""
|
|
272
|
+
marker = next((folder for folder in path.parents if (folder / "lib.rs").is_file() or (folder / "main.rs").is_file()), None)
|
|
273
|
+
package = next((folder for folder in path.parents if (folder / "Cargo.toml").is_file()), None)
|
|
274
|
+
if marker is None and package is None:
|
|
275
|
+
return None
|
|
276
|
+
markers = [marker / "lib.rs", marker / "main.rs"] if marker else []
|
|
277
|
+
named = []
|
|
278
|
+
if package:
|
|
279
|
+
named += [package / "src/lib.rs", package / "src/main.rs"]
|
|
280
|
+
for folder in ("src/bin", "tests", "examples", "benches"):
|
|
281
|
+
named += sorted((package / folder).glob("*.rs")) + sorted((package / folder).glob("*/main.rs"))
|
|
282
|
+
manifest = (package / "Cargo.toml").read_text(encoding="utf-8")
|
|
283
|
+
named += [package / file for file in re.findall(r"""\bpath\s*=\s*["']([^"']+\.rs)["']""", manifest)]
|
|
284
|
+
return tuple(dict.fromkeys(root.resolve() for root in markers + named if root.is_file())), {root.resolve() for root in named}
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
CONCAT = re.compile(r"(?:\w+\s*::\s*)*concat\s*!\s*[(\[{]")
|
|
288
|
+
MANIFEST_DIR = re.compile(r'(?:\w+\s*::\s*)*env\s*!\s*[(\[{]\s*"CARGO_MANIFEST_DIR"\s*,?\s*[)\]}]')
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def include_path(argument, file, package):
|
|
292
|
+
"""Return the file that the argument of an `include!` in file names, or None when the argument is neither a
|
|
293
|
+
string without escapes nor a `concat!` of such strings and `env!("CARGO_MANIFEST_DIR")`, which is package,
|
|
294
|
+
the directory of the Cargo.toml of the crate being compiled.
|
|
295
|
+
|
|
296
|
+
Raises:
|
|
297
|
+
ValueError: The argument uses `env!("CARGO_MANIFEST_DIR")` and package is None.
|
|
298
|
+
"""
|
|
299
|
+
argument = argument.strip()
|
|
300
|
+
if (value := string_value(argument)) is not None:
|
|
301
|
+
return file.parent / value
|
|
302
|
+
mask = rust_masks(argument).without_comments_or_strings
|
|
303
|
+
if not (concat := CONCAT.match(mask)) or after_closing(mask, concat.end() - 1) != len(mask):
|
|
304
|
+
return None
|
|
305
|
+
parts, start, depth = [], concat.end(), 0
|
|
306
|
+
for i in range(start, len(mask) - 1):
|
|
307
|
+
depth += (mask[i] in "([{") - (mask[i] in ")]}")
|
|
308
|
+
if mask[i] == "," and not depth:
|
|
309
|
+
parts.append(argument[start:i].strip())
|
|
310
|
+
start = i + 1
|
|
311
|
+
parts.append(argument[start:-1].strip())
|
|
312
|
+
pieces = []
|
|
313
|
+
for part in filter(None, parts):
|
|
314
|
+
if (value := string_value(part)) is not None:
|
|
315
|
+
pieces.append(value)
|
|
316
|
+
elif MANIFEST_DIR.fullmatch(part):
|
|
317
|
+
if package is None:
|
|
318
|
+
raise ValueError('no Cargo.toml above the crate root sets env!("CARGO_MANIFEST_DIR"), so the record cannot tell which file it reads')
|
|
319
|
+
pieces.append(str(package))
|
|
320
|
+
else:
|
|
321
|
+
return None
|
|
322
|
+
return file.parent / "".join(pieces)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
class Route(NamedTuple):
|
|
326
|
+
"""A route to a Kani harness file: its crate root, the guards on its steps, outermost first, and the module path
|
|
327
|
+
that it gives the file's items, "" at a crate root."""
|
|
328
|
+
root: Path
|
|
329
|
+
guards: str
|
|
330
|
+
module: str
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
class Unread(NamedTuple):
|
|
334
|
+
"""A route that the route reader cannot read: the file that holds it, the route as the record names it, without a
|
|
335
|
+
line number, and the message that names its line and why."""
|
|
336
|
+
file: Path
|
|
337
|
+
route: str
|
|
338
|
+
message: str
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
class RouteReader:
|
|
342
|
+
"""Read the routes that lead to Kani harness files from their crate roots.
|
|
343
|
+
|
|
344
|
+
It parses each file and walks each crate's module tree once, so make one per run: it does not see a file that
|
|
345
|
+
changes after it has read it.
|
|
346
|
+
"""
|
|
347
|
+
|
|
348
|
+
def __init__(self):
|
|
349
|
+
self.parsed, self.trees = {}, {}
|
|
350
|
+
|
|
351
|
+
def parse(self, path):
|
|
352
|
+
if path not in self.parsed:
|
|
353
|
+
self.parsed[path] = parse_rust(path)
|
|
354
|
+
return self.parsed[path]
|
|
355
|
+
|
|
356
|
+
def module_tree(self, roots):
|
|
357
|
+
"""Return the module declarations that lead to each file the crate roots reach, as {file: {(declarer,
|
|
358
|
+
declaration)}}, and two Unread lists: each reached file, declaration and `include!` that could not be read, and
|
|
359
|
+
each route in RustFile.hidden of a reached file.
|
|
360
|
+
|
|
361
|
+
An `include!("...")` item outside function bodies leads to the file it names, relative to the including file,
|
|
362
|
+
which declares modules as a file that owns its directory does, whatever inline modules hold the include.
|
|
363
|
+
"""
|
|
364
|
+
if roots not in self.trees:
|
|
365
|
+
edges, broken, hidden, seen, scanned = {}, [], [], set(), set()
|
|
366
|
+
work = [(root, True, next((folder for folder in root.parents if (folder / "Cargo.toml").is_file()), None)) for root in roots]
|
|
367
|
+
while work:
|
|
368
|
+
file, owner, package = work.pop()
|
|
369
|
+
if (file, owner, package) in seen:
|
|
370
|
+
continue
|
|
371
|
+
seen.add((file, owner, package))
|
|
372
|
+
try:
|
|
373
|
+
parsed = self.parse(file)
|
|
374
|
+
except ValueError as error:
|
|
375
|
+
broken.append(Unread(file, "a file it cannot parse", f"{file}: {error}"))
|
|
376
|
+
continue
|
|
377
|
+
for position, route in [] if file in scanned else parsed.hidden:
|
|
378
|
+
line = parsed.source.without_comments_or_strings.count("\n", 0, position) + 1
|
|
379
|
+
hidden.append(Unread(file, f"{route} in a macro or block", f"{file}:{line}: {route} is inside a macro or block"))
|
|
380
|
+
scanned.add(file)
|
|
381
|
+
for declaration in parsed.declarations:
|
|
382
|
+
try:
|
|
383
|
+
targets = list(module_files(file, owner, parsed, declaration))
|
|
384
|
+
except ValueError as error:
|
|
385
|
+
broken.append(Unread(file, f"mod {declaration.name} under a path it cannot read", str(error)))
|
|
386
|
+
continue
|
|
387
|
+
for target, owns in targets:
|
|
388
|
+
if target.is_file():
|
|
389
|
+
target = target.resolve()
|
|
390
|
+
edges.setdefault(target, set()).add((file, declaration))
|
|
391
|
+
work.append((target, owns, package))
|
|
392
|
+
for include in parsed.includes:
|
|
393
|
+
invocation = rust_masks(parsed.source.uncommented[include.keyword:include.end])
|
|
394
|
+
line = parsed.source.without_comments_or_strings.count("\n", 0, include.keyword) + 1
|
|
395
|
+
shown = collapse(invocation.uncommented, invocation.literals)
|
|
396
|
+
try:
|
|
397
|
+
target = include_path(invocation.uncommented[invocation.without_comments_or_strings.index("!") + 1:].strip()[1:-1], file, package)
|
|
398
|
+
except ValueError as error:
|
|
399
|
+
broken.append(Unread(file, shown, f"{file}:{line}: cannot read the path in '{shown}': {error}"))
|
|
400
|
+
continue
|
|
401
|
+
if target is None:
|
|
402
|
+
broken.append(Unread(file, shown, f"{file}:{line}: cannot read the path in '{shown}'; write it as a string without escapes, or as concat! of such strings and env!(\"CARGO_MANIFEST_DIR\")"))
|
|
403
|
+
elif target.is_file():
|
|
404
|
+
target = target.resolve()
|
|
405
|
+
edges.setdefault(target, set()).add((file, include))
|
|
406
|
+
work.append((target, True, package))
|
|
407
|
+
self.trees[roots] = edges, broken, hidden
|
|
408
|
+
return self.trees[roots]
|
|
409
|
+
|
|
410
|
+
def unread(self, path):
|
|
411
|
+
"""Return the routes in path's crates that the reader cannot read, sorted by message. The reader cannot tell
|
|
412
|
+
where such a route leads, so any of them may lead to path."""
|
|
413
|
+
if (crates := crate_roots(path)) is None:
|
|
414
|
+
return []
|
|
415
|
+
_, broken, hidden = self.module_tree(crates[0])
|
|
416
|
+
# The tree reads a file once for each way it is reached, so a broken entry can repeat.
|
|
417
|
+
return sorted([*{entry.message: entry for entry in broken}.values(), *hidden], key=lambda entry: entry.message)
|
|
418
|
+
|
|
419
|
+
def routes(self, path):
|
|
420
|
+
"""Return the routes that lead to path from its crate roots, sorted. A crate root is one route without guards,
|
|
421
|
+
since its own crate always compiles it, unless it is a lib.rs or main.rs that Cargo does not name and another
|
|
422
|
+
file declares, which makes it a module. A file in no crate is one such route too, as Kani compiles it alone.
|
|
423
|
+
|
|
424
|
+
It follows each out-of-line `mod` declaration from the crate roots by rustc's rules, including
|
|
425
|
+
`#[path = "..."]` and each path that a cfg_attr may set, and each `include!("...")` item outside function
|
|
426
|
+
bodies. It does not expand macros, so a declaration that a macro holds or builds is not a route it reads;
|
|
427
|
+
`compiled_problems` checks those against the harnesses that Kani compiles.
|
|
428
|
+
|
|
429
|
+
Raises:
|
|
430
|
+
ValueError: No route that it reads reaches path. The message names each reached file, declaration and
|
|
431
|
+
`include!` that it could not read.
|
|
432
|
+
"""
|
|
433
|
+
if (crates := crate_roots(path)) is None:
|
|
434
|
+
return [Route(path, "", "")]
|
|
435
|
+
roots, named = crates
|
|
436
|
+
edges, broken, _ = self.module_tree(roots)
|
|
437
|
+
if path in roots and path not in edges:
|
|
438
|
+
return [Route(path, "", "")]
|
|
439
|
+
if path not in edges:
|
|
440
|
+
unread = "".join(f"; {entry.message}" for entry in broken)
|
|
441
|
+
raise ValueError(f"{path}: no module declaration that the record can read leads to this file from a crate root; declare it with `mod <name>;` or `#[path = \"...\"]` outside macros and function bodies, in a file that a crate root reaches{unread}")
|
|
442
|
+
|
|
443
|
+
def walk(file, visiting):
|
|
444
|
+
root = file in named or file in roots and all(declarer == file for declarer, _ in edges.get(file, ()))
|
|
445
|
+
found = [Route(file, "", "")] if root else []
|
|
446
|
+
for declarer, declaration in edges.get(file, ()):
|
|
447
|
+
if declarer in visiting:
|
|
448
|
+
continue
|
|
449
|
+
parsed = self.parse(declarer)
|
|
450
|
+
enclosing = enclosing_modules(parsed, declaration)
|
|
451
|
+
items = [(0, 0, -1)] + [(module.start, module.keyword, module.body) for module in enclosing] + [(declaration.start, declaration.keyword, declaration.body)]
|
|
452
|
+
guards = cfg_guards(parsed.source, items)
|
|
453
|
+
# An included file's items sit in the modules around the include!; a declared file's in its module.
|
|
454
|
+
local = (enclosing[-1].name if enclosing else "") if declaration in parsed.includes else declaration.name
|
|
455
|
+
found += [Route(route.root, " ".join(filter(None, (route.guards, guards))), "::".join(filter(None, (route.module, local))))
|
|
456
|
+
for route in walk(declarer, visiting | {declarer})]
|
|
457
|
+
return found
|
|
458
|
+
|
|
459
|
+
return sorted(walk(path, {path}))
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def route_label(path, routes):
|
|
463
|
+
"""Return the guards that routes give path's items, as the record holds them: one route's own guards, or for more
|
|
464
|
+
than one route `routes(...)` with each route as its crate root's path relative to path's directory, a colon and
|
|
465
|
+
its guards, or `unguarded` for a route without any, sorted and separated by `; `."""
|
|
466
|
+
found = sorted((os.path.relpath(route.root, path.parent), route.guards) for route in routes)
|
|
467
|
+
if len(found) == 1:
|
|
468
|
+
return found[0][1]
|
|
469
|
+
labelled = "; ".join(f"{root}: {guards or 'unguarded'}" for root, guards in found)
|
|
470
|
+
return f"routes({labelled})"
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def unread_label(path, unread):
|
|
474
|
+
"""Return the record's note for the Unread routes that may lead to path: `unread(...)` with each as its file's path
|
|
475
|
+
relative to path's directory, a colon and the route, sorted and separated by `; `, or "" for none."""
|
|
476
|
+
found = sorted(f"{os.path.relpath(entry.file, path.parent)}: {entry.route}" for entry in unread)
|
|
477
|
+
return f"unread({'; '.join(found)})" if found else ""
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def kani_surface(path, reader):
|
|
481
|
+
source = rust_masks(path.read_text(encoding="utf-8"))
|
|
482
|
+
text, mask = source.uncommented, source.without_comments_or_strings
|
|
483
|
+
if renaming := RENAMING_IMPORT.search(mask):
|
|
484
|
+
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")
|
|
485
|
+
functions, modules, opaque, _, _ = rust_functions(mask)
|
|
486
|
+
declared = route_label(path, reader.routes(path))
|
|
487
|
+
unread = unread_label(path, reader.unread(path))
|
|
488
|
+
|
|
489
|
+
def owner_at(position, *, attribute=False):
|
|
490
|
+
if not any(start <= position < end for start, end in opaque):
|
|
491
|
+
for function in reversed(functions):
|
|
492
|
+
if function.start <= position < function.end and (position < function.body if attribute else position > function.body):
|
|
493
|
+
return function
|
|
494
|
+
line = mask.count("\n", 0, position) + 1
|
|
495
|
+
raise ValueError(f"{path}:{line}: cannot identify a function owner; write Kani forms in free functions under inline modules, outside macro definitions and impl or trait bodies")
|
|
496
|
+
|
|
497
|
+
surface = Surface()
|
|
498
|
+
spans, read = [], []
|
|
499
|
+
for kind, pattern in MACROS:
|
|
500
|
+
for match in pattern.finditer(mask):
|
|
501
|
+
end = after_closing(mask, match.end() - 1)
|
|
502
|
+
read.append((match.start(), end))
|
|
503
|
+
# The generator's explicit type arguments constrain its domain alongside its predicate.
|
|
504
|
+
if kind == "any_where":
|
|
505
|
+
item_kind, expression = "assume", text[match.start():end]
|
|
506
|
+
else:
|
|
507
|
+
item_kind, expression = kind, text[match.end():end - 1]
|
|
508
|
+
argument = rust_masks(expression)
|
|
509
|
+
owner = owner_at(match.start(), attribute=kind == "stub").name
|
|
510
|
+
spans.append((match.start(), f"{item_kind} {collapse(argument.uncommented, argument.literals)} in {owner}", ""))
|
|
511
|
+
# Kani refuses these attributes on a function that is not a harness, so only a harness's are recorded.
|
|
512
|
+
attributes = {}
|
|
513
|
+
for start, end in applied_attributes(mask):
|
|
514
|
+
if HARNESS_ATTRIBUTE.fullmatch(item := re.sub(r"\s+", "", mask[start:end])):
|
|
515
|
+
read.append((start, end))
|
|
516
|
+
attributes.setdefault(owner_at(start, attribute=True), []).append(item)
|
|
517
|
+
for match in PROOF.finditer(mask):
|
|
518
|
+
read.append(match.span())
|
|
519
|
+
harness = owner_at(match.start(), attribute=True)
|
|
520
|
+
enclosing = sorted((item for item in functions + modules if item.start <= harness.start and harness.end <= item.end), key=lambda item: item.start)
|
|
521
|
+
guards = cfg_guards(source, [(0, 0, -1)] + [(item.start, item.keyword, item.body) for item in enclosing])
|
|
522
|
+
value = " ".join(filter(None, (declared, guards, *sorted(attributes.get(harness, ())), unread)))
|
|
523
|
+
spans.append((match.start(), f"harness {harness.name}", value))
|
|
524
|
+
for token in KANI_TOKEN.finditer(mask):
|
|
525
|
+
if not any(start <= token.start() < end for start, end in read):
|
|
526
|
+
line = mask.count("\n", 0, token.start()) + 1
|
|
527
|
+
raise ValueError(f"{path}:{line}: '{collapse(token[0])}' is in a form the record cannot read; write kani::assume(...), kani::any_where(...), kani::cover!(...), #[kani::stub(...)], #[kani::proof], #[kani::should_panic] or #[kani::unwind(...)], alone or under #[cfg_attr(kani, ...)]")
|
|
528
|
+
for _, item, guards in sorted(spans):
|
|
529
|
+
surface.add(item, guards)
|
|
530
|
+
return surface
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
@functools.cache
|
|
534
|
+
def checker():
|
|
535
|
+
return kani.Kani()
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
@functools.cache
|
|
539
|
+
def compiled_in(package):
|
|
540
|
+
"""Return each harness that Kani compiles in the Cargo package at package.
|
|
541
|
+
|
|
542
|
+
Raises:
|
|
543
|
+
ValueError: Kani is not installed, or cannot compile the package.
|
|
544
|
+
"""
|
|
545
|
+
try:
|
|
546
|
+
with tempfile.TemporaryDirectory(prefix="baseline-kani-", dir=storage.ensure_temp_root()) as work:
|
|
547
|
+
return tuple(kani.compiled(package, Path(work), checker()))
|
|
548
|
+
except (kani.CheckError, runner.Unavailable) as error:
|
|
549
|
+
raise ValueError(f"cannot ask Kani which harnesses it compiles in {package}: {error}") from error
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
# A closure or a `const _` block puts an anonymous segment in Kani's name for a harness inside it.
|
|
553
|
+
ANONYMOUS = re.compile(r"\{\w+#\d+\}|_")
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def item_path(name):
|
|
557
|
+
return "::".join(part.removeprefix("r#") for part in name.split("::") if not ANONYMOUS.fullmatch(part))
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def route_owner(name, modules, owners):
|
|
561
|
+
"""Return the owner in owners, keyed by item_path, that Kani's harness name gives under one of modules, or None.
|
|
562
|
+
|
|
563
|
+
The name must start with the module path itself. Anonymous segments are dropped only after it, since no route
|
|
564
|
+
that the record reads runs through a closure or a `const _` block.
|
|
565
|
+
"""
|
|
566
|
+
parts = [part.removeprefix("r#") for part in name.split("::")]
|
|
567
|
+
for module in modules:
|
|
568
|
+
prefix = [part.removeprefix("r#") for part in module.split("::")] if module else []
|
|
569
|
+
if parts[:len(prefix)] == prefix and (owner := owners.get(item_path("::".join(parts[len(prefix):])))):
|
|
570
|
+
return owner
|
|
571
|
+
return None
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def compiled_problems(path, surface, reader, recorded=None):
|
|
575
|
+
"""Return the lines on which the harnesses that Kani compiles from path disagree with surface and recorded, and
|
|
576
|
+
surface's harnesses that it compiles, as `harness <owner>` items, or None for them when no Cargo package holds
|
|
577
|
+
path.
|
|
578
|
+
|
|
579
|
+
Each harness that Kani compiles from path must be one of surface's harnesses under the module path of a route
|
|
580
|
+
that the record reads. A harness in recorded that Kani compiles on no route is a harness that was switched off.
|
|
581
|
+
|
|
582
|
+
Raises:
|
|
583
|
+
ValueError: Kani is not installed, or cannot compile the package.
|
|
584
|
+
"""
|
|
585
|
+
package = next((folder for folder in path.parents if (folder / "Cargo.toml").is_file()), None)
|
|
586
|
+
if package is None:
|
|
587
|
+
return [f" not compiled {item}" for item in recorded or ()], None
|
|
588
|
+
names = {harness.name for harness in compiled_in(package) if harness.source == path}
|
|
589
|
+
modules = {route.module for route in reader.routes(path)}
|
|
590
|
+
owners = {re.sub(r"\[\d+\]$", "", KANI_KEY.fullmatch(item)[2]) for item in surface if item.startswith("harness ")}
|
|
591
|
+
found = {name: route_owner(name, modules, {item_path(owner): owner for owner in owners}) for name in names}
|
|
592
|
+
lines = [f" FAIL Kani compiles {name} from this file, but no route that the record reads gives that name; declare "
|
|
593
|
+
"the module with `mod <name>;` or `#[path = \"...\"]` outside macros and function bodies"
|
|
594
|
+
for name, owner in sorted(found.items()) if owner is None]
|
|
595
|
+
compiled = sorted({f"harness {owner}" for owner in found.values() if owner is not None})
|
|
596
|
+
lines += [f" not compiled {item}" for item in sorted(set(recorded or ()) - set(compiled))]
|
|
597
|
+
return lines, compiled
|