agent-formal-verify 0.4.11 → 0.4.13
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 +140 -0
- package/README.md +5 -3
- package/package.json +2 -1
- package/skills/formal-verify/SKILL.md +11 -13
- package/skills/formal-verify/examples/kani-template/src/lib.rs +5 -6
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +10 -45
- package/skills/formal-verify/examples/tla-template/BoundedQueue.matrix +16 -13
- package/skills/formal-verify/examples/tla-template/BoundedQueue.mutations +92 -14
- package/skills/formal-verify/examples/tla-template/BoundedQueue.tla +169 -28
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +5 -4
- package/skills/formal-verify/references/lean-brief.md +2 -2
- package/skills/formal-verify/references/rust-brief.md +59 -7
- package/skills/formal-verify/references/setup.md +24 -8
- package/skills/formal-verify/references/tla-brief.md +2 -2
- package/skills/formal-verify/scripts/baseline.py +564 -66
- package/skills/formal-verify/scripts/kani-check.sh +3 -1
- package/skills/formal-verify/scripts/kani.py +130 -54
- package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
- package/skills/formal-verify/scripts/lean-check.sh +6 -243
- package/skills/formal-verify/scripts/lean.py +484 -0
- package/skills/formal-verify/scripts/lean_mutations.py +195 -0
- package/skills/formal-verify/scripts/lean_records.py +25 -0
- package/skills/formal-verify/scripts/mutate.py +81 -195
- package/skills/formal-verify/scripts/processes.py +266 -0
- package/skills/formal-verify/scripts/python-tools.sh +15 -0
- package/skills/formal-verify/scripts/runner.py +56 -0
- package/skills/formal-verify/scripts/setup.sh +18 -19
- package/skills/formal-verify/scripts/storage.py +207 -0
- package/skills/formal-verify/scripts/sync.py +401 -0
- package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
- package/skills/formal-verify/scripts/tlc.py +423 -116
- package/skills/formal-verify/scripts/{tlc-trace.py → tlc_trace.py} +16 -10
- package/skills/setup/SKILL.md +1 -1
- package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
- package/skills/formal-verify/scripts/lean-statements.py +0 -161
- package/skills/formal-verify/scripts/lean-tools.sh +0 -24
- package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright (c) 2026 Michael Denyer
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
+
"""List the commits an existing model has not been synced with, and the paths its covered code has had since.
|
|
5
|
+
|
|
6
|
+
SYNC <commit> <reason> the commit the model was last synced at, or SYNC none
|
|
7
|
+
PATH <path> a path the covered code has had since that commit
|
|
8
|
+
MISSING <name>: <commits> a covered name that git grep finds in no file that could define it,
|
|
9
|
+
with the commits since the sync that added or removed it
|
|
10
|
+
READ <command> the git log command that shows every commit to read
|
|
11
|
+
|
|
12
|
+
The sync commit is the header's `Source read at <commit>` when that commit is in HEAD's
|
|
13
|
+
history, and otherwise the last commit that changed the model files; the SYNC line then says
|
|
14
|
+
why the header's commit was not used. When a model file is also a --source, such as a Rust file
|
|
15
|
+
with its Kani harness, that fallback counts only a commit that changed the code of its
|
|
16
|
+
#[cfg(kani)] items and none of its other code, whatever it did to the other model files,
|
|
17
|
+
following each source back through its renames along the renaming commit's parents, so not into a branch merged after the
|
|
18
|
+
rename. A merge never counts, but a rename made in one is followed into each of its parents, under the old path
|
|
19
|
+
that git finds against that parent, or else against the first parent with one; parents with different old paths get
|
|
20
|
+
a walk each, read together newest commit first, and a commit two walks reach under the same paths counts once.
|
|
21
|
+
SYNC none follows when none of the last 100 commits of the model files it reads qualifies, and adds that it did not
|
|
22
|
+
follow a rename into a branch merged after it when such a branch changed the old path, each parent read under another
|
|
23
|
+
parent's old path that it does not hold, and each source that a merge holds under no path git finds renamed to it,
|
|
24
|
+
which the walk stops following there. Each source path is followed through every rename since
|
|
25
|
+
the sync commit in both directions. Each name adds the files where git grep finds it as a whole
|
|
26
|
+
word now, outside the model files that are not also a --source, such as a Kani harness kept
|
|
27
|
+
apart from the production code, and outside documents, such as README, and TLA+ and Lean files,
|
|
28
|
+
which cannot define it, unless a source path has the same extension. A name in none of the remaining files,
|
|
29
|
+
or only in files with no extension and data files such as .json, .yml or .html, which seldom define it,
|
|
30
|
+
or only in the comments and strings of Rust files, is MISSING. Each name also adds, under the same rules, the files where a commit since the sync
|
|
31
|
+
added or removed it as a whole word, which git log -S finds, renames included. A path that held
|
|
32
|
+
the code only under another name, such as code renamed as it moved, is not found, nor is one
|
|
33
|
+
whose commits all kept the number of times the name appears. Exits 1 outside a git
|
|
34
|
+
repository, for a source path that no commit has, or when git grep fails.
|
|
35
|
+
|
|
36
|
+
Usage: sync.py <model file>... [--source <path>]... [--name <name>]...
|
|
37
|
+
"""
|
|
38
|
+
import argparse
|
|
39
|
+
import functools
|
|
40
|
+
import heapq
|
|
41
|
+
import itertools
|
|
42
|
+
import re
|
|
43
|
+
import shlex
|
|
44
|
+
import subprocess
|
|
45
|
+
import sys
|
|
46
|
+
from pathlib import Path
|
|
47
|
+
|
|
48
|
+
sys.dont_write_bytecode = True
|
|
49
|
+
import baseline
|
|
50
|
+
|
|
51
|
+
HEADER = re.compile(r"Source read at ([0-9a-fA-F]{7,40})\b")
|
|
52
|
+
# Documents and model files mention covered names but cannot define them, unless a source has the same extension.
|
|
53
|
+
NO_DEFINITIONS = {".md", ".markdown", ".rst", ".txt", ".adoc", ".org", ".tex", ".csv", ".tla", ".cfg", ".lean", ".statements",
|
|
54
|
+
".matrix", ".mutations"}
|
|
55
|
+
# Nor can a document with no extension.
|
|
56
|
+
DOCUMENT_NAMES = {"README", "CHANGELOG", "CHANGES", "HISTORY", "NEWS", "TODO", "AUTHORS", "CONTRIBUTORS", "COPYING",
|
|
57
|
+
"LICENSE", "NOTICE", "CODEOWNERS"}
|
|
58
|
+
# Other files with no extension and data formats can hold code, such as a Makefile or a CI workflow, but seldom the
|
|
59
|
+
# definition of a covered name, so they are read but do not keep a name from being MISSING.
|
|
60
|
+
SELDOM_DEFINE = {"", ".html", ".htm", ".ipynb", ".json", ".yaml", ".yml", ".toml", ".xml", ".svg"}
|
|
61
|
+
# #[cfg(kani)] on an item, past any other attributes and its visibility; on a field or a variant it is production code.
|
|
62
|
+
KANI_CFG = re.compile(
|
|
63
|
+
r"#\s*\[\s*cfg\s*\(\s*kani\s*\)\s*\](?=(?:\s*#\s*\[[^\]]*\])*\s*(?:pub\s*(?:\([^)]*\))?\s*)?"
|
|
64
|
+
r"(?:mod|fn|impl|use|const|static|struct|enum|union|trait|type|unsafe|extern|async|macro_rules)\b)"
|
|
65
|
+
)
|
|
66
|
+
# The fallback reads at most this many commits of the model files, since each costs a parse of the file twice.
|
|
67
|
+
FALLBACK_COMMITS = 100
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@functools.cache
|
|
71
|
+
def rust_code(path):
|
|
72
|
+
"""Return a Rust file's text with its comments and strings blanked, or None when it cannot be read."""
|
|
73
|
+
try:
|
|
74
|
+
return baseline.rust_masks(path.read_text(encoding="utf-8", errors="replace")).without_comments_or_strings
|
|
75
|
+
except OSError:
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def in_code(root, file, name):
|
|
80
|
+
"""Whether name occurs as a whole word outside the comments and strings of a Rust file; True for another file.
|
|
81
|
+
|
|
82
|
+
The reader is Rust's lexer, with nested block comments and raw strings, which would hide code in a language
|
|
83
|
+
whose comments and strings differ, such as an unclosed `/*` inside a C comment, so only Rust files are read.
|
|
84
|
+
"""
|
|
85
|
+
code = rust_code(root / file) if Path(file).suffix.lower() == ".rs" else None
|
|
86
|
+
return code is None or re.search(rf"(?<![A-Za-z0-9_]){re.escape(name)}(?![A-Za-z0-9_])", code) is not None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def role(file, paths, suffixes):
|
|
90
|
+
"""Return "defines" for a file that may define a covered name it holds, "uses" for one that may only use it, or None."""
|
|
91
|
+
path = Path(file)
|
|
92
|
+
suffix = path.suffix.lower()
|
|
93
|
+
if file in paths or suffix in suffixes:
|
|
94
|
+
return "defines"
|
|
95
|
+
if suffix in NO_DEFINITIONS or not suffix and path.name.upper() in DOCUMENT_NAMES:
|
|
96
|
+
return None
|
|
97
|
+
return "uses" if suffix in SELDOM_DEFINE else "defines"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def git(root, *arguments, check=True):
|
|
101
|
+
done = subprocess.run(["git", "-C", str(root), *arguments], capture_output=True, text=True, check=False)
|
|
102
|
+
if check and done.returncode:
|
|
103
|
+
raise RuntimeError(f"git {' '.join(arguments)} failed: {done.stderr.strip()}")
|
|
104
|
+
return done
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@functools.cache
|
|
108
|
+
def split_harness(text):
|
|
109
|
+
"""Return the code of the #[cfg(kani)] items in Rust text and the code outside them, without comments or blank lines."""
|
|
110
|
+
source = baseline.rust_masks(text)
|
|
111
|
+
mask, spans = source.without_comments_or_strings, []
|
|
112
|
+
for found in KANI_CFG.finditer(mask):
|
|
113
|
+
if spans and found.start() < spans[-1][1]:
|
|
114
|
+
continue
|
|
115
|
+
at = found.end()
|
|
116
|
+
while at < len(mask) and mask[at] not in "{;":
|
|
117
|
+
at = baseline.after_closing(mask, at) if mask[at] in "([" else at + 1
|
|
118
|
+
end = baseline.after_closing(mask, at) if at < len(mask) and mask[at] == "{" else at + 1
|
|
119
|
+
spans.append((found.start(), end))
|
|
120
|
+
starts = [0] + [end for _, end in spans]
|
|
121
|
+
ends = [start for start, _ in spans] + [len(mask)]
|
|
122
|
+
|
|
123
|
+
def code(parts):
|
|
124
|
+
return [line.rstrip() for part in parts for line in part.splitlines() if line.strip()]
|
|
125
|
+
|
|
126
|
+
return code(source.uncommented[a:b] for a, b in spans), code(source.uncommented[a:b] for a, b in zip(starts, ends))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def renamed_from(root, *trees):
|
|
130
|
+
"""Map each path that a commit, or the diff between two trees, renamed to its path before."""
|
|
131
|
+
fields = git(root, "diff-tree", "-M", "-r", "--no-commit-id", "--name-status", "--diff-filter=R", "-z", *trees).stdout.split("\0")
|
|
132
|
+
return {fields[at + 2]: fields[at + 1] for at in range(len(fields) - 2) if re.fullmatch(r"R[0-9]*", fields[at])}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def changed_only_harness(root, commit, models, sources):
|
|
136
|
+
"""Whether commit changed the #[cfg(kani)] items of a model file that is also a source, and no code outside them.
|
|
137
|
+
|
|
138
|
+
Also returns, for each parent of commit, each source that commit renamed mapped to its path in that parent,
|
|
139
|
+
so the caller can follow them. A merge never counts, since it joins code that the harness was not written
|
|
140
|
+
against, but a source that it holds and none of its parents does maps, in each parent, to the path that git
|
|
141
|
+
finds renamed to it against that parent, or to None.
|
|
142
|
+
"""
|
|
143
|
+
parents = git(root, "rev-parse", f"{commit}^@").stdout.split()
|
|
144
|
+
if len(parents) > 1:
|
|
145
|
+
absent = {path for path in sources if not git(root, "cat-file", "-e", f"{commit}:{path}", check=False).returncode
|
|
146
|
+
and all(git(root, "cat-file", "-e", f"{parent}:{path}", check=False).returncode for parent in parents)}
|
|
147
|
+
if not absent:
|
|
148
|
+
return False, {}
|
|
149
|
+
renames = {}
|
|
150
|
+
for parent in parents:
|
|
151
|
+
found = renamed_from(root, parent, commit)
|
|
152
|
+
renames[parent] = {new: found.get(new) for new in absent}
|
|
153
|
+
return False, renames
|
|
154
|
+
touched = set(git(root, "diff-tree", "--root", "--no-commit-id", "--name-only", "-r", "-z", commit, "--", *models).stdout.split("\0")) - {""}
|
|
155
|
+
befores = {path: git(root, "show", f"{commit}^:{path}", check=False) for path in touched & set(sources)}
|
|
156
|
+
renames = {}
|
|
157
|
+
if any(before.returncode for before in befores.values()):
|
|
158
|
+
olds = {new: old for new, old in renamed_from(root, commit).items() if new in befores}
|
|
159
|
+
befores.update({path: git(root, "show", f"{commit}^:{old}", check=False) for path, old in olds.items()})
|
|
160
|
+
renames = {parents[0]: olds} if olds else {}
|
|
161
|
+
# A commit that changed only another model file never synced the harness in a source, so only a harness edit counts.
|
|
162
|
+
changed = False
|
|
163
|
+
for path, before in befores.items():
|
|
164
|
+
after = git(root, "show", f"{commit}:{path}", check=False)
|
|
165
|
+
if before.returncode or after.returncode:
|
|
166
|
+
return False, renames
|
|
167
|
+
try:
|
|
168
|
+
(old_harness, old_code), (new_harness, new_code) = split_harness(before.stdout), split_harness(after.stdout)
|
|
169
|
+
except ValueError:
|
|
170
|
+
return False, renames
|
|
171
|
+
if old_code != new_code:
|
|
172
|
+
return False, renames
|
|
173
|
+
changed = changed or old_harness != new_harness
|
|
174
|
+
return changed, renames
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def missed_branch(root, rename, olds, read):
|
|
178
|
+
"""Whether HEAD has a commit of olds not in read, outside rename's history and not after it, so on a branch merged since."""
|
|
179
|
+
commits = git(root, "rev-list", "--full-history", "--no-merges", "HEAD", f"^{rename}", "--", *olds).stdout.split()
|
|
180
|
+
return any(commit not in read and git(root, "merge-base", "--is-ancestor", rename, commit, check=False).returncode == 1
|
|
181
|
+
for commit in commits)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class Walk:
|
|
185
|
+
"""A git log of the model files from some starting commits, read one commit at a time and fetched in pages."""
|
|
186
|
+
|
|
187
|
+
def __init__(self, root, starts, paths, sources):
|
|
188
|
+
# The pathspec stays as given, so each page of the log continues the one before it.
|
|
189
|
+
self.root, self.starts, self.pathspec, self.paths, self.sources = root, starts, paths, paths, sources
|
|
190
|
+
self.pending, self.skip, self.more = [], 0, True
|
|
191
|
+
|
|
192
|
+
def next(self, size):
|
|
193
|
+
"""Return the committer time and hash of the next commit, fetching up to size commits, or None at the end."""
|
|
194
|
+
if not self.pending and self.more:
|
|
195
|
+
fields = git(self.root, "log", f"--skip={self.skip}", f"-{size + 1}", "--format=%ct %H", *self.starts, "--", *self.pathspec).stdout.split()
|
|
196
|
+
self.pending = list(zip(map(int, fields[::2]), fields[1::2]))[:size]
|
|
197
|
+
self.more = len(fields) > 2 * size
|
|
198
|
+
self.skip += len(self.pending)
|
|
199
|
+
return self.pending[0] if self.pending else None
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def sync_commit(root, models, shared):
|
|
203
|
+
"""Return the sync commit and where it came from, or (None, reason); shared are the models also given as --source."""
|
|
204
|
+
unused = []
|
|
205
|
+
for model in models:
|
|
206
|
+
text = model.read_text(encoding="utf-8", errors="replace")
|
|
207
|
+
found = HEADER.search(text)
|
|
208
|
+
if found and git(root, "merge-base", "--is-ancestor", found[1], "HEAD", check=False).returncode == 0:
|
|
209
|
+
return git(root, "rev-parse", found[1]).stdout.strip(), f"from the Source read at line in {model.name}"
|
|
210
|
+
if found:
|
|
211
|
+
unused.append(f"the Source read at commit {found[1]} in {model.name} is not in HEAD's history")
|
|
212
|
+
elif "Source read at" in text:
|
|
213
|
+
unused.append(f"the Source read at line in {model.name} names no commit hash")
|
|
214
|
+
relative = [str(model.relative_to(root)) for model in models]
|
|
215
|
+
if shared:
|
|
216
|
+
names = ", ".join(model.name for model in shared)
|
|
217
|
+
sources = [str(model.relative_to(root)) for model in shared]
|
|
218
|
+
# git log does not follow a rename, so a walk starts again at the renaming commit's parents under the old path.
|
|
219
|
+
# Parents that hold a source under different old paths get a walk each. The walks are read together, newest
|
|
220
|
+
# commit first, as one git log reads every parent of a rename whose old path they share, so the first commit
|
|
221
|
+
# that qualifies is the latest, and a commit that two walks reach under the same paths is read once. A branch
|
|
222
|
+
# merged after the rename is not followed back past it, a parent that git finds no rename against is read under
|
|
223
|
+
# another parent's old path, and a source that a merge holds under no path git finds renamed to it is no longer
|
|
224
|
+
# followed, and SYNC none says so.
|
|
225
|
+
queue, order, done, left, unread = [], itertools.count(), {}, FALLBACK_COMMITS, False
|
|
226
|
+
followed, unseen, stopped = {}, {}, {}
|
|
227
|
+
|
|
228
|
+
def add(walk):
|
|
229
|
+
nonlocal unread
|
|
230
|
+
if not left:
|
|
231
|
+
unread = unread or bool(walk.pending) or walk.more
|
|
232
|
+
elif head := walk.next(left):
|
|
233
|
+
heapq.heappush(queue, (-head[0], next(order), walk))
|
|
234
|
+
|
|
235
|
+
add(Walk(root, ["HEAD"], relative, sources))
|
|
236
|
+
while queue and left:
|
|
237
|
+
walk = heapq.heappop(queue)[2]
|
|
238
|
+
commit = walk.pending.pop(0)[1]
|
|
239
|
+
key = (commit, tuple(walk.paths), tuple(walk.sources))
|
|
240
|
+
if key not in done:
|
|
241
|
+
left -= 1
|
|
242
|
+
found, renames = changed_only_harness(root, commit, walk.paths, walk.sources)
|
|
243
|
+
if found:
|
|
244
|
+
return commit, "; ".join([f"from the last commit of the model files that changed no production code in {names}", *unused])
|
|
245
|
+
news = {new for olds in renames.values() for new in olds}
|
|
246
|
+
lost = [new for new in news if not any(olds[new] for olds in renames.values())]
|
|
247
|
+
stopped.update(dict.fromkeys((commit, path) for path in lost))
|
|
248
|
+
paths, sources = ([path for path in group if path not in lost] for group in (walk.paths, walk.sources))
|
|
249
|
+
firsts = {new: next(olds[new] for olds in renames.values() if olds[new]) for new in news - set(lost)}
|
|
250
|
+
if firsts:
|
|
251
|
+
groups = {}
|
|
252
|
+
for parent, olds in renames.items():
|
|
253
|
+
mapping = {new: olds[new] or firsts[new] for new in firsts}
|
|
254
|
+
unseen.update(dict.fromkeys((commit, parent, mapping[new], new) for new in firsts if not olds[new]
|
|
255
|
+
and git(root, "cat-file", "-e", f"{parent}:{mapping[new]}", check=False).returncode))
|
|
256
|
+
groups.setdefault(tuple(sorted(mapping.items())), []).append(parent)
|
|
257
|
+
for group_key, parents in groups.items():
|
|
258
|
+
mapping = dict(group_key)
|
|
259
|
+
add(Walk(root, parents, *([mapping.get(path, path) for path in group] for group in (paths, sources))))
|
|
260
|
+
followed[(commit, tuple(sorted({old for olds in renames.values() for old in olds.values() if old})))] = None
|
|
261
|
+
done[key] = paths, sources, bool(firsts) or not sources
|
|
262
|
+
walk.paths, walk.sources, ends = done[key]
|
|
263
|
+
if not ends:
|
|
264
|
+
add(walk)
|
|
265
|
+
read = f"the last {FALLBACK_COMMITS} commits of the model files" if unread or queue else "the model files"
|
|
266
|
+
reasons = [f"no commit of {read} changed only the #[cfg(kani)] items of {names}"]
|
|
267
|
+
reasons += [f"it did not follow the rename of {', '.join(olds)} in {rename} into a branch merged after it"
|
|
268
|
+
for rename, olds in followed if missed_branch(root, rename, olds, {commit for commit, _, _ in done})]
|
|
269
|
+
reasons += [f"it read the parent {parent} of the merge {merge} under {old}, which that parent does not hold, since git finds no rename to {new} against it"
|
|
270
|
+
for merge, parent, old, new in unseen]
|
|
271
|
+
reasons += [f"it stopped following {path} at the merge {merge}, since none of its parents has {path} and git finds no rename to it"
|
|
272
|
+
for merge, path in stopped]
|
|
273
|
+
return None, "; ".join([*reasons, *unused])
|
|
274
|
+
last = git(root, "log", "-1", "--format=%H", "--", *relative).stdout.strip()
|
|
275
|
+
if last:
|
|
276
|
+
return last, "; ".join(["from the last commit of the model files", *unused])
|
|
277
|
+
return None, "; ".join(["the model files have no commit and no Source read at line in HEAD's history", *unused])
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def renamed(root, sync, paths):
|
|
281
|
+
"""Add every path that the renames since sync connect to one of paths."""
|
|
282
|
+
# -m diffs a merge against each parent, so a rename made in a merge connects its paths too.
|
|
283
|
+
fields = git(root, "log", "-m", "-M", "--diff-filter=R", "--name-status", "--format=", "-z", f"{sync}..HEAD").stdout.split("\0")
|
|
284
|
+
fields = [field.lstrip("\n") for field in fields]
|
|
285
|
+
pairs = [(fields[at + 1], fields[at + 2]) for at in range(len(fields) - 2) if re.fullmatch(r"R[0-9]*", fields[at])]
|
|
286
|
+
paths = set(paths)
|
|
287
|
+
grown = True
|
|
288
|
+
while grown:
|
|
289
|
+
grown = False
|
|
290
|
+
for old, new in pairs:
|
|
291
|
+
if (old in paths) != (new in paths):
|
|
292
|
+
paths |= {old, new}
|
|
293
|
+
grown = True
|
|
294
|
+
return paths
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def held(root, sync, name, pathspec):
|
|
298
|
+
"""Return the files where a commit since sync added or removed name as a whole word."""
|
|
299
|
+
# One log lists each such commit, its parents and the files where the raw count of name changed, and a few greps
|
|
300
|
+
# read those files at each commit and its first parent. Without --no-renames, a rename that keeps the name's
|
|
301
|
+
# count pairs the old path with the new one and -S skips both. A path holds no NUL, so the two NULs before each
|
|
302
|
+
# header mark it, and -z puts one newline before the header's first path.
|
|
303
|
+
log = git(root, "log", "--no-renames", "--no-textconv", "-S", name, "--format=%x00%x00%H %P", "--name-only", "-z",
|
|
304
|
+
f"{sync}..HEAD", "--", *pathspec).stdout
|
|
305
|
+
changed = {}
|
|
306
|
+
for entry in re.split("\0\0+", log)[1:]:
|
|
307
|
+
header, _, names = entry.partition("\0")
|
|
308
|
+
commit, *parents = header.split()
|
|
309
|
+
# A root commit, such as one of a history merged in, changed nothing since the sync.
|
|
310
|
+
for revision in (commit, parents[0]) if parents else ():
|
|
311
|
+
changed.setdefault(revision, set()).update(file for file in names.removeprefix("\n").split("\0") if file)
|
|
312
|
+
files = set()
|
|
313
|
+
for revisions, paths in batches(changed):
|
|
314
|
+
found = git(root, "grep", "-l", "-z", "-w", "-F", "-e", name, *revisions, "--", *(f":(literal){path}" for path in paths), check=False)
|
|
315
|
+
if found.returncode > 1:
|
|
316
|
+
raise RuntimeError(f"git grep for {name} failed: {found.stderr.strip()}")
|
|
317
|
+
hits = (hit.partition(":") for hit in found.stdout.split("\0") if hit)
|
|
318
|
+
files.update(file for revision, _, file in hits if file in changed[revision])
|
|
319
|
+
return files
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def batches(changed, limit=100_000):
|
|
323
|
+
"""Yield revisions and paths to grep together, each group within limit bytes of arguments.
|
|
324
|
+
|
|
325
|
+
A revision's paths are split across groups when they do not fit in one, as at a commit that is the parent of
|
|
326
|
+
several listed commits.
|
|
327
|
+
"""
|
|
328
|
+
revisions, paths, size = set(), set(), 0
|
|
329
|
+
for revision, files in changed.items():
|
|
330
|
+
for path in sorted(files):
|
|
331
|
+
grown = (revision not in revisions) * (len(revision) + 1) + (path not in paths) * (len(path.encode()) + 12)
|
|
332
|
+
if paths and size + grown > limit:
|
|
333
|
+
yield sorted(revisions), sorted(paths)
|
|
334
|
+
revisions, paths, size = set(), set(), 0
|
|
335
|
+
grown = len(revision) + 1 + len(path.encode()) + 12
|
|
336
|
+
revisions.add(revision)
|
|
337
|
+
paths.add(path)
|
|
338
|
+
size += grown
|
|
339
|
+
if paths:
|
|
340
|
+
yield sorted(revisions), sorted(paths)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def main():
|
|
344
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
345
|
+
parser.add_argument("models", nargs="+", type=Path)
|
|
346
|
+
parser.add_argument("--source", action="append", default=[], help="a source file the model's header names")
|
|
347
|
+
parser.add_argument("--name", action="append", default=[], help="a function or shared variable the model covers")
|
|
348
|
+
arguments = parser.parse_args()
|
|
349
|
+
models = [model.resolve() for model in arguments.models]
|
|
350
|
+
for model in models:
|
|
351
|
+
if not model.is_file():
|
|
352
|
+
print(f"FAIL {model} does not exist")
|
|
353
|
+
return 1
|
|
354
|
+
found = git(models[0].parent, "rev-parse", "--show-toplevel", check=False)
|
|
355
|
+
if found.returncode:
|
|
356
|
+
print(f"FAIL {models[0]} is in no git repository")
|
|
357
|
+
return 1
|
|
358
|
+
root = Path(found.stdout.strip())
|
|
359
|
+
relative = [str(model.relative_to(root)) for model in models]
|
|
360
|
+
given = {(Path.cwd() / source).resolve() for source in arguments.source}
|
|
361
|
+
sync, reason = sync_commit(root, models, [model for model in models if model in given])
|
|
362
|
+
if sync is None:
|
|
363
|
+
print(f"SYNC none: {reason}; compare the model with the code in full")
|
|
364
|
+
return 0
|
|
365
|
+
print(f"SYNC {sync} {reason}")
|
|
366
|
+
sources = []
|
|
367
|
+
for source in arguments.source:
|
|
368
|
+
path = (Path.cwd() / source).resolve()
|
|
369
|
+
if root not in path.parents or not git(root, "log", "-1", "--format=%H", "--", str(path.relative_to(root))).stdout:
|
|
370
|
+
print(f"FAIL --source {source} is {path}, which no commit in {root} has")
|
|
371
|
+
return 1
|
|
372
|
+
sources.append(str(path.relative_to(root)))
|
|
373
|
+
paths = renamed(root, sync, sources)
|
|
374
|
+
excluded = [f":(exclude){path}" for path in relative if path not in sources]
|
|
375
|
+
suffixes = {Path(path).suffix.lower() for path in paths}
|
|
376
|
+
missing = []
|
|
377
|
+
for name in arguments.name:
|
|
378
|
+
found = git(root, "grep", "-l", "-z", "-w", "-F", "-e", name, "--", ".", *excluded, check=False)
|
|
379
|
+
if found.returncode > 1:
|
|
380
|
+
raise RuntimeError(f"git grep for {name} failed: {found.stderr.strip()}")
|
|
381
|
+
roles = {file: role(file, paths, suffixes) for file in found.stdout.split("\0") if file}
|
|
382
|
+
if not any(kind == "defines" and in_code(root, file, name) for file, kind in roles.items()):
|
|
383
|
+
missing.append(name)
|
|
384
|
+
files = [*roles, *held(root, sync, name, [".", *excluded])]
|
|
385
|
+
paths.update(file for file in files if role(file, paths, suffixes))
|
|
386
|
+
for path in sorted(paths):
|
|
387
|
+
print(f"PATH {path}")
|
|
388
|
+
for name in missing:
|
|
389
|
+
removed = git(root, "log", "-S", name, "--format=%h", f"{sync}..HEAD", "--", *sorted(paths)).stdout.split()
|
|
390
|
+
print(f"MISSING {name}: " + (" ".join(removed) if removed else "no commit since the sync removed it"))
|
|
391
|
+
if paths:
|
|
392
|
+
print("READ " + shlex.join(["git", "-C", str(root), "log", "-p", f"{sync}..HEAD", "--", *sorted(paths)]))
|
|
393
|
+
return 0
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
if __name__ == "__main__":
|
|
397
|
+
try:
|
|
398
|
+
sys.exit(main())
|
|
399
|
+
except (RuntimeError, ValueError) as error:
|
|
400
|
+
print(f"FAIL {error}")
|
|
401
|
+
sys.exit(1)
|
|
@@ -5,5 +5,7 @@
|
|
|
5
5
|
# runner and documents the matrix file and its environment settings.
|
|
6
6
|
# Usage: tlc-matrix.sh <matrix-file> [label-substring]
|
|
7
7
|
[ "$#" -ge 1 ] && [ "$#" -le 2 ] || { echo "usage: tlc-matrix.sh <matrix-file> [label-substring]"; exit 2; }
|
|
8
|
-
|
|
8
|
+
# shellcheck source=skills/formal-verify/scripts/python-tools.sh
|
|
9
|
+
source "$(dirname "$0")/python-tools.sh"
|
|
10
|
+
require_python || exit 3
|
|
9
11
|
exec python3 "$(dirname "$0")/tlc.py" "$@"
|