agent-formal-verify 0.4.14 → 0.4.16
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 +26 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +1 -1
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +3 -3
- package/skills/formal-verify/references/setup.md +3 -3
- package/skills/formal-verify/scripts/baseline.py +52 -21
- package/skills/formal-verify/scripts/kani.py +13 -4
- package/skills/formal-verify/scripts/kani_reader.py +36 -6
- 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 +34 -1
- package/skills/formal-verify/scripts/sync.py +5 -4
- package/skills/formal-verify/scripts/tlc.py +18 -4
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changes
|
|
2
2
|
|
|
3
|
+
## 0.4.16 - Kani harness and helper bodies in the baseline
|
|
4
|
+
|
|
5
|
+
`scripts/baseline.py` now also records the body of each free function other than a harness in a Kani module that holds a harness, or in a module under one, as the item `body <function>`, written as a harness body is. The template's `inputs()` in `mod proofs` is such a function, so changing its `let window: u16 = kani::any();` to `let window: u16 = 1;`, or weakening a predicate that a `kani::assume` in a harness calls, prints `CHANGED`. Before this change, the record read such a function only for its assumptions, covers and stubs, so both printed `UNCHANGED`. A production function outside those modules, such as the template's `claim`, is not recorded, so a production fix still prints `UNCHANGED`. A harness at the root of a file puts every free function in the file in the record. The record still reads a method in an `impl` or trait block, such as an `impl kani::Arbitrary`, and a function outside the modules that hold harnesses, only for their assumptions, covers and stubs. A record made before this change prints `CHANGED` once, with the line `previous baseline did not record the functions beside its harnesses`, when the file has such a function; check each one against the original revision, then record the file again.
|
|
6
|
+
|
|
7
|
+
`scripts/baseline.py` now keeps a `kani::cover!` call in the recorded body of its harness when the cover's condition can run code: when it holds a call, a block, an index, `?`, `return`, `break`, `continue`, `await` or `yield`. Adding such a cover prints `CHANGED`, with the cover under `new:`. Before this change, the record left every cover out of the body, so adding `kani::cover!(if window > 1 { return } else { true });` before the template's assertion skipped that assertion for every window of 2 while `compare` printed `UNCHANGED`. A cover whose condition only reads and compares values, such as `kani::cover!(state.next == 3, "three")`, is still left out, so adding one is still allowed. A record that holds a harness with a cover that can run code prints `CHANGED` once, with the cover under `new:`; record the file again.
|
|
8
|
+
|
|
9
|
+
`scripts/baseline.py` now records the body of each Kani harness as the item `body <harness>`, without comments, without its `kani::cover!` calls and without whitespace except where two tokens would otherwise join, so weakening an assertion, changing how the harness builds its inputs with `kani::any()`, `kani::any_where` or `kani::assume`, or changing the conditions around an assertion prints `CHANGED`. Re-indenting or rewrapping the body, or editing its comments, leaves it unchanged, and adding a `kani::cover!` whose condition cannot run code is still allowed. A trailing comma that a formatter adds or removes prints `CHANGED`. Before this change, the record held a harness's name, attributes and guards but not its body, so weakening `assert!(invariant(window, after))` to `assert!(invariant(window, after) || window > 1)` printed `UNCHANGED`, while the same weakening of a TLA+ property printed `CHANGED`. Every record that holds a Kani harness prints `CHANGED` once, with the line `previous baseline did not record harness bodies`; check each harness body against the original revision, then record the file again.
|
|
10
|
+
|
|
11
|
+
## 0.4.15 - Kani generator types in the baseline, locked baseline updates and a checked Lean replay
|
|
12
|
+
|
|
13
|
+
`scripts/baseline.py` now records the whole `kani::any_where` call in a harness, with its explicit type arguments and its predicate, so changing `kani::any_where::<u16, _>(...)` to `kani::any_where::<u8, _>(...)` prints `CHANGED`. Before this change, the record held the predicate alone, so narrowing a generator's type printed `UNCHANGED`. A record made with 0.4.14 that holds an `any_where` predicate prints `CHANGED` once. Older records used one form for a plain assumption and a generator's predicate, so check the harness's assumptions and generator types against the revision the record was made from before you record the file again.
|
|
14
|
+
|
|
15
|
+
`scripts/baseline.py record` and `move` now lock a file named `.<record>.lock` beside the record while they read and replace it, so runs that update the same record at the same time keep every entry. Before this change, two runs could read the same old record, and the later write dropped the entry that the earlier one added.
|
|
16
|
+
|
|
17
|
+
`scripts/lean-check.sh` now fails with `FAIL <scope>: cannot locate <toolchain> for kernel replay (lean --print-prefix exit <n>)`, followed by the tool's output, when it cannot find the pinned toolchain's `bin/lean`. Before this change, a failed lookup reported kernel replay as unavailable, and the check passed without replay.
|
|
18
|
+
|
|
19
|
+
`scripts/lean-check.sh` now checks a module named `lakefile.lean` below the project root, such as `Model/lakefile.lean`, and leaves out only the project's own Lake configuration. Before this change, it skipped every file with that name, so a failing theorem in one passed the whole-project check.
|
|
20
|
+
|
|
21
|
+
`scripts/sync.py` now picks the files that can define each `--name` from the `--source` files and their rename history only, so the result no longer depends on the order of the names. Before this change, a file found while searching one name could become a definition candidate for a later name.
|
|
22
|
+
|
|
23
|
+
`scripts/tlc-matrix.sh` now prints a `FAIL` line, `malformed constant '<token>' in run '<label>': expected Name=Value`, for a run whose constants hold a token without a name or a value, such as `N=` or a bare word, and `scripts/baseline.py record` rejects the matrix. Before this change, the runner wrote such a token into TLC's configuration.
|
|
24
|
+
|
|
25
|
+
`scripts/mutate.py` now keeps one mutated source in memory at a time. On a 1,035,022-byte source with 64 mutations, its planner's peak fell from 66,260,062 bytes to 16,238 bytes. When the temporary directory lies inside a Rust crate's workspace, the Rust runner now leaves its own work directory out of the workspace copy that it stages for each mutation.
|
|
26
|
+
|
|
27
|
+
`references/setup.md` now says how Pi, OpenCode and Antigravity run the `setup` skill, and its CI example runs Kani on a crate at the repository root, where the Rust brief puts each harness. `docs/reference.md` now gives the steps to update the plugin in Antigravity.
|
|
28
|
+
|
|
3
29
|
## 0.4.14 - an HTML report of TLC runs, and Kani baselines that say what they did not read or check
|
|
4
30
|
|
|
5
31
|
`scripts/tlc-matrix.sh` writes a self-contained HTML report when `TLC_HTML_REPORT` names a path. The report has a table of the runs and, for each failing or `reach` witness trace, a state chain to step through, the variables each step changed, and the trace as Mermaid `stateDiagram-v2` source to copy. It loads nothing over the network. The matrix runner checks the path after Java and TLC and before the first run, and replaces the file in one step. A written report leaves the printed lines and the exit status as they are without a report. A path where the report cannot be written prints an `UNAVAILABLE TLC_HTML_REPORT=...` line and exits with status 3. If the write fails after the runs, the runner prints that line and exits with status 1 when a run failed and 3 otherwise. `scripts/tlc_report.py` builds the report from the traces that `scripts/tlc_trace.py` now parses. The Mermaid labels keep the trace's TLA+ text: each character that Mermaid reads as syntax, such as `{`, `:` or `"`, is written as a Mermaid entity code, such as `#123;`, which Mermaid draws as that character. So are the space in words that Mermaid reads anywhere on a line, such as `direction LR`, and the first bracket of `[[fork]]`, `[[join]]` or `[[choice]]`, and a U+FEFF, which Mermaid reads as whitespace, so a state, transition or lasso label that holds them is kept. The last step of a liveness counter-example that ends in stuttering, which TLC prints as `State N: Stuttering` with no variables, lists the variables of the state it repeats. A matrix file name that is not valid UTF-8 shows U+FFFD in the report in place of the bytes that cannot be decoded. The table row of a failing run with a trace shows, beside the link to the trace, the lines that the matrix runner prints under the run.
|
package/package.json
CHANGED
|
@@ -89,7 +89,7 @@ Name the brief file and leave its text out of the prompt. The [TLA+ brief](refer
|
|
|
89
89
|
|
|
90
90
|
An agent writes only its own files, `tla/<Name>.tla`, `.matrix` and `.mutations`, `lean/Model/<Name>.lean`, `.mutations` and `.statements`, or the `#[cfg(kani)]` harness module in the production file that defines its Rust function and the `.mutations` file beside it, so parallel agents share none. Give one agent every Rust target in one production file. An existing Lean project keeps its layout and must pin Lean 4.20.0 or later. A Kani harness that an earlier run wrote in a crate of its own moves into its production file when the Rust brief's "Moving a harness" section allows, so it gets an agent even when it passes; otherwise its agent edits it and its `.mutations` file in place.
|
|
91
91
|
|
|
92
|
-
When the agents have reported, delete each moved harness's old file, and its crate, workspace entry and CI steps once they hold nothing else. Then rerun every check in this thread: the matrix runner on each matrix file, the Lean checker on the whole project without a file name, the Rust checker on each crate, and the mutation runner on each mutations file. Take each verdict from these runs, not from an agent's report. For a moved harness, first run `baseline.py move` as the [helper reference](references/helpers.md) says. Then run `python3 <skill-dir>/scripts/baseline.py compare <record-file>`. It exits 1 and prints CHANGED with the changed parts when a recorded property, fairness condition, matrix line, `.statements` record, Kani cover or stub changed, a Kani harness was removed, renamed, no longer compiles or had its `cfg` guards changed on a route the record reads, or a Kani assumption was added or changed. Accept a move only as that reference says. Also read `git diff` for each model that existed before this run, for the changes the record does not cover, such as a theorem newly marked `private`, a new guard in a TLA+ action, or a
|
|
92
|
+
When the agents have reported, delete each moved harness's old file, and its crate, workspace entry and CI steps once they hold nothing else. Then rerun every check in this thread: the matrix runner on each matrix file, the Lean checker on the whole project without a file name, the Rust checker on each crate, and the mutation runner on each mutations file. Take each verdict from these runs, not from an agent's report. For a moved harness, first run `baseline.py move` as the [helper reference](references/helpers.md) says. Then run `python3 <skill-dir>/scripts/baseline.py compare <record-file>`. It exits 1 and prints CHANGED with the changed parts when a recorded property, fairness condition, matrix line, `.statements` record, Kani harness or helper body, cover or stub changed, a Kani harness was removed, renamed, no longer compiles or had its `cfg` guards changed on a route the record reads, or a Kani assumption was added or changed. Accept a move only as that reference says. Also read `git diff` for each model that existed before this run, for the changes the record does not cover, such as a theorem newly marked `private`, a new guard in a TLA+ action, or a narrowed input in a Kani helper outside the harness's module. Each such change needs the evidence its row cites, a specification correction accepted below, or for a re-freeze another reason the Lean brief permits. Revert any change without it and give the model back to its agent with the reason. Run the comparison again until it exits 0. Report each file that prints `NOT CHECKED` as not checked against Kani.
|
|
93
93
|
|
|
94
94
|
Accept a specification correction when a reviewer finding, a missed mutation, an UNCOVERED result with source evidence, or a checked witness demonstrates a gap in the old statement. Read the old and proposed guarantees against the callers, record the evidence and decision in the target's row, and permit the corresponding re-freeze even when production code is unchanged. The correction must preserve the intended guarantee or strengthen it over the intended inputs. A broken proof alone does not justify changing a statement. A weaker guarantee or a new assumption excluding shipped inputs needs evidence of an intentional production contract change or the user's explicit agreement. Rerun all checks after the accepted correction and re-freeze. Then run `baseline.py record <record-file>` again on that model's file, and add the previous and new digests it prints to the row.
|
|
95
95
|
|
|
@@ -12,7 +12,7 @@ Include the matching meaning from this table where each kind of evidence first a
|
|
|
12
12
|
| A bounded search passes | Every input up to the stated bound was tried. |
|
|
13
13
|
| Mutations detected | Deliberate bugs were planted in copies of the model, and the checks caught each one. For Lean, this shows that existing proofs fail, not that the mutated statements are false. |
|
|
14
14
|
| Past fix detected | The checks fail on the behaviour before a recorded bug fix. For Lean, report proof sensitivity separately from whether a checked counterexample establishes that the property rules out that bug. |
|
|
15
|
-
| Specification unchanged | The baseline comparison preserved each recorded run's inputs and checks, reach check's selected inputs, property and fairness definition, action subscript such as `vars`, statement record, qualified Kani harness name with its `should_panic` and `unwind` attributes and the `cfg` attributes that can switch it off on each route the record reads,
|
|
15
|
+
| Specification unchanged | The baseline comparison preserved each recorded run's inputs and checks, reach check's selected inputs, property and fairness definition, action subscript such as `vars`, statement record, qualified Kani harness name with its `should_panic` and `unwind` attributes and the `cfg` attributes that can switch it off on each route the record reads, function-owned assumption, cover and stub, and body of each Kani harness and of each function in a module that holds one, such as an input helper, including its assertions, input construction and the conditions around its assertions, apart from comments, layout and covers whose conditions cannot run code. It does not cover the body of a method in an `impl` or trait block or of a function outside those modules, apart from its assumptions, covers and stubs, or the `cfg` attributes on a route that its record value lists under `unread(...)`; `git diff` does. |
|
|
16
16
|
| UNAVAILABLE | The tool could not run. This target was not checked; give the printed remedy. |
|
|
17
17
|
| reproduced | A deterministic test or race-detector run fails on the production code. |
|
|
18
18
|
| reachable at shipped settings | The shipped constants and callers permit the counter-example, but no production reproduction has confirmed it yet. |
|
|
@@ -24,8 +24,8 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
|
|
|
24
24
|
- An indented `not checked against Kani: <reason>` line: Kani is missing or the harness file's Cargo package does not compile, so the entry holds what the file's text shows alone.
|
|
25
25
|
- Output of `compare <record-file>`, which exits 1 when a recorded file changed. Each indented line under `CHANGED` counts as a change, except the `not checked against Kani at record, ...` line and the lines under it:
|
|
26
26
|
- `UNCHANGED <file>`, `CHANGED <file>` or `NOT CHECKED <file>` for each recorded file, then `SUMMARY <n> unchanged, <m> changed`, which ends with `, <k> not checked` when a file printed `NOT CHECKED`.
|
|
27
|
-
- An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values. A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness.
|
|
28
|
-
- An indented `added <item>`, which only a new Kani assumption or stub prints.
|
|
27
|
+
- An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values. A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness. The item `body <function>` holds, for a harness and for each other free function in a module that holds a harness or under one, such as an input helper, the text between the function's braces without comments, without each `kani::cover!` call whose condition cannot run code, which is an item of its own, and without whitespace except one space where two tokens would otherwise join, such as `{let(window,state)=inputs();...}`. Re-indenting or rewrapping the body leaves it unchanged, but a trailing comma that a formatter adds or removes changes it. A cover whose condition holds a call, a block, an index, `?`, `return`, `break`, `continue`, `await` or `yield` can return early or change a value before an assertion, so it stays in the body, and adding one changes the body. Accept such a change when the `new:` value differs from the `old:` value only by the added cover and its condition only reads values, then record the file again. A record made before bodies were recorded prints `previous baseline did not record harness bodies` once, and one made before the other functions' bodies were recorded prints `previous baseline did not record the functions beside its harnesses` once. For those records, check each harness body against the original revision before recording the file again.
|
|
28
|
+
- An indented `added <item>`, which only a new Kani assumption or stub prints. A `kani::any_where` assumption includes the complete call, including explicit type arguments. Older records used one representation for plain assumptions and generator predicates. For those records, check the assumptions and generator types against the original revision before recording the file again.
|
|
29
29
|
- In a TLA+ module where a local `INSTANCE` introduces substitutions, or that has an indented definition outside a `LET` or a column-0 definition inside one, the helper compares the complete text of each local module it loaded, with comments removed, so a change to a definition that no property uses also needs review. So does a column-0 definition whose header the helper cannot read, such as an infix operator, which it records with the operators it references, whether or not a property references it.
|
|
30
30
|
- An indented `file is missing`: the recorded file no longer exists.
|
|
31
31
|
- An indented `not compiled harness <name>`: Kani compiles a stored harness on no route, such as when `Cargo.toml` drops a default feature that a route's `cfg` needs.
|
|
@@ -34,7 +34,7 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
|
|
|
34
34
|
- `FAIL baseline: <reason>` exits 1, and a `usage:` line exits 2. `record` fails this way for a file it cannot read, such as a harness file that no route the record reads reaches or a Kani form the record cannot read, where `compare` prints an indented `FAIL` under `CHANGED`. Both fail this way for an unsupported or malformed record file.
|
|
35
35
|
- Cannot see:
|
|
36
36
|
- In TLA+, the actions that `Spec` names under `[][...]_vars`, `WF_` or `SF_`. It does follow the subscript of those forms and of `<<A>>_vars`, such as `vars`, in every definition it follows, and it follows an operator that `Spec` names outside those forms, such as a fairness definition, into its actions.
|
|
37
|
-
- In Kani, a
|
|
37
|
+
- In Kani, the body of a method in an `impl` or trait block, such as an `impl kani::Arbitrary`, and of a function outside the modules that hold harnesses, apart from their assumptions, covers and stubs; read `git diff` for those.
|
|
38
38
|
- A route that the record cannot read: a `mod` declaration or `include!` inside a macro like `cfg_if!`, including a `mod $name;` that a macro builds, or inside a block such as a function body, a `#[path]` or `include!` whose path it cannot read, or a file on the way that fails to parse. It cannot tell where such a route leads, so `record` prints `route not read: <reason>`, which names the file and, except for a file that fails to parse, the line, for each one in the harness file's crates. It adds each to every harness's value as `unread(<file>: <route>; ...)`, with the file relative to the harness file's directory. Adding or removing such a route prints `CHANGED`. It does not record the route's guards, and Kani's check fails only when the route gives the harness another module path, so a guard changed on it can print no `CHANGED` line; read `git diff` for it. When no route that it reads reaches the file, `record` fails and names each of them.
|
|
39
39
|
- A Kani harness file outside any Cargo package is read from its text alone, so neither `record` nor `compare` asks Kani which harnesses it compiles.
|
|
40
40
|
- `baseline.py move <record-file> <old file> <new file>` moves a model's record entry to the file the model moved to, reading the record alone, so a later `compare` checks the new file against what the old one specified, including the harnesses that Kani compiled. For a Kani harness moved into a module of its production file, add `--module <old module> <new module>`, each relative to its file, with `crate` for the file's root, such as `--module crate proofs` for harnesses that sat at the old crate's root, even when the production file is `src/queue.rs`. When the new file already has an entry, the two are merged, and an item in both fails the move. It prints `MOVED <old> -> <new>`. Accept a move when `compare` prints `UNCHANGED`, or `NOT CHECKED` for an entry that `record` could not check against Kani, and `git diff` shows the old file's harness lines in the new module with only their indentation changed, plus the `use crate as <name>;` line and the `#[cfg(kani)] mod proofs` lines around them. When the production file's crate has a route that the record cannot read, `compare` prints a `changed harness` line for each moved harness whose `new:` value only adds an `unread(...)` note to its `old:` value; accept those too, then record the new file again. Any other change, such as an edited assertion, needs the evidence its row cites.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Tool setup
|
|
2
2
|
|
|
3
|
-
Run `/agent-formal-verify:setup` once to prepare Java, Python, TLC, elan, Lean, Rust and Kani. In Codex, request this plugin's `setup` skill. The [setup skill](../../setup/SKILL.md) prepares all three verification tools independently of any repository and reuses existing runtimes and caches.
|
|
3
|
+
Run `/agent-formal-verify:setup` once to prepare Java, Python, TLC, elan, Lean, Rust and Kani. In Codex, request this plugin's `setup` skill. In Pi, use `/skill:setup`. In OpenCode or Antigravity, request the `setup` skill. The [setup skill](../../setup/SKILL.md) prepares all three verification tools independently of any repository and reuses existing runtimes and caches.
|
|
4
4
|
|
|
5
5
|
The formal-verify skill selects tools from the current repository on every invocation. It reuses prepared tools and installs a missing Lean toolchain through the setup helper when a Lean pin changes. Repository changes do not require the user to rerun the full setup.
|
|
6
6
|
|
|
@@ -98,6 +98,6 @@ Install the chosen runtime and the pinned TLC JAR, and for Rust the pinned Kani,
|
|
|
98
98
|
- run: python3 .formal-verify/skills/formal-verify/scripts/mutate.py "$GITHUB_WORKSPACE/lean/Model/Name.mutations"
|
|
99
99
|
- run: cargo install --locked kani-verifier --version 0.68.0 && cargo kani setup
|
|
100
100
|
- run: bash .formal-verify/skills/formal-verify/scripts/setup.sh rust
|
|
101
|
-
- run: bash .formal-verify/skills/formal-verify/scripts/kani-check.sh "$GITHUB_WORKSPACE
|
|
102
|
-
- run: python3 .formal-verify/skills/formal-verify/scripts/mutate.py "$GITHUB_WORKSPACE/
|
|
101
|
+
- run: bash .formal-verify/skills/formal-verify/scripts/kani-check.sh "$GITHUB_WORKSPACE"
|
|
102
|
+
- run: python3 .formal-verify/skills/formal-verify/scripts/mutate.py "$GITHUB_WORKSPACE/src/lib.mutations"
|
|
103
103
|
```
|
|
@@ -20,7 +20,9 @@ change, and so is an added item whose kind narrows what is checked.
|
|
|
20
20
|
#[path], with each route in the file's crates that the record cannot read, such as a mod
|
|
21
21
|
declaration inside a macro, and each kani::assume, kani::any_where, kani::cover! and
|
|
22
22
|
#[kani::stub] with its owning free function, under inline modules. Unsupported owners fail. Added covers and harnesses are allowed.
|
|
23
|
-
Added assumes and stubs are changes.
|
|
23
|
+
Added assumes and stubs are changes. Also the body of each harness and of each other free function in
|
|
24
|
+
a module that holds a harness, or under one, without its comments, the kani::cover! calls whose
|
|
25
|
+
conditions cannot run code, and the whitespace that a reformat can change.
|
|
24
26
|
In a Cargo package, also the recorded harnesses that Kani compiles from the file; Kani must give
|
|
25
27
|
each harness it compiles there a module path that a route the record reads gives, and a harness
|
|
26
28
|
that no longer compiles is a change.
|
|
@@ -39,10 +41,12 @@ OLD to sit under NEW. Exit codes: 0 unchanged, 1 changed or a record or model
|
|
|
39
41
|
file that fails to parse, 2 usage error.
|
|
40
42
|
"""
|
|
41
43
|
import argparse
|
|
44
|
+
import fcntl
|
|
42
45
|
import hashlib
|
|
43
46
|
import json
|
|
44
47
|
import re
|
|
45
48
|
import sys
|
|
49
|
+
from contextlib import contextmanager
|
|
46
50
|
from pathlib import Path
|
|
47
51
|
|
|
48
52
|
sys.dont_write_bytecode = True
|
|
@@ -257,10 +261,10 @@ def tla_surface(path):
|
|
|
257
261
|
for task in tasks:
|
|
258
262
|
if task.reach:
|
|
259
263
|
surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
|
|
260
|
-
{"run": collapse(task.run.label), "constants":
|
|
264
|
+
{"run": collapse(task.run.label), "constants": task.run.constants})
|
|
261
265
|
specs[task.spec].add(task.reach.operator)
|
|
262
266
|
else:
|
|
263
|
-
run = surface.add(f"run {task.spec} {collapse(task.run.label)}",
|
|
267
|
+
run = surface.add(f"run {task.spec} {collapse(task.run.label)}", task.run.constants)
|
|
264
268
|
for check in task.checks:
|
|
265
269
|
for name in check.names:
|
|
266
270
|
surface.add(f"check {task.spec} {check.kind} {name} | [{run}]")
|
|
@@ -315,6 +319,11 @@ class TlaKind:
|
|
|
315
319
|
return model_entry(self.name, joined(entry["surface"], new, existing))
|
|
316
320
|
|
|
317
321
|
|
|
322
|
+
def may_omit_generator_types(entry):
|
|
323
|
+
# Older entries used the same keys for plain assumptions and generator predicates.
|
|
324
|
+
return not entry.get("generator_types") and any(key.startswith("assume ") for key in entry["surface"])
|
|
325
|
+
|
|
326
|
+
|
|
318
327
|
class KaniKind:
|
|
319
328
|
"""Record, compare and move the harnesses, assumptions, covers and stubs of a Kani file, checked against what Kani compiles."""
|
|
320
329
|
|
|
@@ -326,6 +335,8 @@ class KaniKind:
|
|
|
326
335
|
def entry(self, path):
|
|
327
336
|
surface = kani_surface(path, self.reader)
|
|
328
337
|
entry = model_entry(self.name, surface)
|
|
338
|
+
entry["generator_types"] = True
|
|
339
|
+
entry["helper_bodies"] = True
|
|
329
340
|
notes = [f" route not read: {route.message}" for route in self.reader.unread(path)]
|
|
330
341
|
# A harness that no longer compiles is recorded from its text alone; compare asks Kani again.
|
|
331
342
|
try:
|
|
@@ -341,6 +352,13 @@ class KaniKind:
|
|
|
341
352
|
def changes(self, entry, path):
|
|
342
353
|
surface = kani_surface(path, self.reader)
|
|
343
354
|
lines = differences(entry["surface"], surface, ("assume", "stub"))
|
|
355
|
+
if may_omit_generator_types(entry):
|
|
356
|
+
lines.insert(0, " previous baseline stored assumptions without distinguishing any_where input types; review the original assumptions and record this file again")
|
|
357
|
+
if any(name.startswith("harness ") and "body " + name.removeprefix("harness ") not in entry["surface"] for name in entry["surface"]):
|
|
358
|
+
lines.insert(0, " previous baseline did not record harness bodies; review each harness body against the original revision and record this file again")
|
|
359
|
+
# A record's keys cannot show whether it read the functions beside its harnesses, so the entry says so.
|
|
360
|
+
if not entry.get("helper_bodies") and any(name.startswith("body ") and "harness " + name.removeprefix("body ") not in surface for name in surface):
|
|
361
|
+
lines.insert(0, " previous baseline did not record the functions beside its harnesses; review each of them against the original revision and record this file again")
|
|
344
362
|
unchecked = (" not checked against Kani at record, so compare cannot tell a harness that "
|
|
345
363
|
"stopped compiling from one that never compiled")
|
|
346
364
|
try:
|
|
@@ -361,7 +379,8 @@ class KaniKind:
|
|
|
361
379
|
def valid(self, entry):
|
|
362
380
|
compiled = entry.get("compiled", [])
|
|
363
381
|
return (isinstance(compiled, list) and all(isinstance(name, str) for name in compiled)
|
|
364
|
-
and isinstance(entry.get("partial", False), bool))
|
|
382
|
+
and isinstance(entry.get("partial", False), bool) and isinstance(entry.get("generator_types", False), bool)
|
|
383
|
+
and isinstance(entry.get("helper_bodies", False), bool))
|
|
365
384
|
|
|
366
385
|
def moved(self, entry, module, new, existing):
|
|
367
386
|
surface, compiled = entry["surface"], entry.get("compiled")
|
|
@@ -377,6 +396,10 @@ class KaniKind:
|
|
|
377
396
|
partial = partial or other is None or existing.get("partial", False)
|
|
378
397
|
compiled = None if compiled is None and other is None else [*(other or []), *(compiled or [])]
|
|
379
398
|
result = model_entry(self.name, surface)
|
|
399
|
+
if not any(may_omit_generator_types(part) for part in (entry, existing) if part is not None):
|
|
400
|
+
result["generator_types"] = True
|
|
401
|
+
if all(part.get("helper_bodies") for part in (entry, existing) if part is not None):
|
|
402
|
+
result["helper_bodies"] = True
|
|
380
403
|
if compiled is not None:
|
|
381
404
|
result["compiled"] = sorted(compiled)
|
|
382
405
|
if partial:
|
|
@@ -418,8 +441,16 @@ def read_record(path, kinds):
|
|
|
418
441
|
return models
|
|
419
442
|
|
|
420
443
|
|
|
421
|
-
|
|
444
|
+
@contextmanager
|
|
445
|
+
def locked_models(path, kinds):
|
|
446
|
+
"""Lock a stable sibling across the read and replacement of a record."""
|
|
422
447
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
448
|
+
with path.with_name(f".{path.name}.lock").open("a") as lock:
|
|
449
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
450
|
+
yield read_record(path, kinds) if path.exists() else {}
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def write_record(path, models):
|
|
423
454
|
runner.atomic_write(path, json.dumps({"format": FORMAT, "models": models}, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
|
|
424
455
|
|
|
425
456
|
|
|
@@ -430,13 +461,14 @@ def record(record_path, files):
|
|
|
430
461
|
if file.suffix not in by_suffix:
|
|
431
462
|
print(f"usage: {file} has no model surface; expected one of {', '.join(by_suffix)}")
|
|
432
463
|
return 2
|
|
433
|
-
models = read_record(record_path, kinds) if record_path.exists() else {}
|
|
434
464
|
updates, notes = {}, {}
|
|
435
465
|
for file in files:
|
|
436
466
|
model = str(file.resolve())
|
|
437
467
|
updates[model], note = by_suffix[file.suffix].entry(file.resolve())
|
|
438
468
|
if note:
|
|
439
469
|
notes[model] = note
|
|
470
|
+
with locked_models(record_path, kinds) as models:
|
|
471
|
+
write_record(record_path, {**models, **updates})
|
|
440
472
|
for model, entry in updates.items():
|
|
441
473
|
print(f"RECORDED {model} {entry['digest']}")
|
|
442
474
|
previous = models.get(model, {}).get("digest")
|
|
@@ -444,7 +476,6 @@ def record(record_path, files):
|
|
|
444
476
|
print(f" previous {previous}")
|
|
445
477
|
if model in notes:
|
|
446
478
|
print(notes[model])
|
|
447
|
-
write_record(record_path, {**models, **updates})
|
|
448
479
|
return 0
|
|
449
480
|
|
|
450
481
|
|
|
@@ -467,21 +498,21 @@ def renamed(surface, old_module, new_module):
|
|
|
467
498
|
|
|
468
499
|
def move(record_path, old_file, new_file, module):
|
|
469
500
|
kinds = model_kinds()
|
|
470
|
-
models = read_record(record_path, kinds) if record_path.is_file() else {}
|
|
471
501
|
old, new = str(old_file.resolve()), str(new_file.resolve())
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
502
|
+
with locked_models(record_path, kinds) as models:
|
|
503
|
+
if old not in models:
|
|
504
|
+
print(f"usage: {old} has no record entry; record it before the move")
|
|
505
|
+
return 2
|
|
506
|
+
kind = kinds[models[old]["kind"]]
|
|
507
|
+
if new_file.suffix != kind.suffix:
|
|
508
|
+
print(f"usage: {new} is not a {kind.name} model file")
|
|
509
|
+
return 2
|
|
510
|
+
if module and not kind.renames:
|
|
511
|
+
print("usage: --module applies only to a Kani harness file")
|
|
512
|
+
return 2
|
|
513
|
+
entry = models.pop(old)
|
|
514
|
+
models[new] = kind.moved(entry, module, new, models.get(new))
|
|
515
|
+
write_record(record_path, models)
|
|
485
516
|
print(f"MOVED {old} -> {new}")
|
|
486
517
|
return 0
|
|
487
518
|
|
|
@@ -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):
|
|
@@ -13,10 +13,10 @@ sys.dont_write_bytecode = True
|
|
|
13
13
|
import kani
|
|
14
14
|
import runner
|
|
15
15
|
import storage
|
|
16
|
-
from rust_source import RustSource, after_closing, rust_masks
|
|
16
|
+
from rust_source import RustSource, after_closing, normalized, rust_masks
|
|
17
17
|
from surface import Surface, collapse
|
|
18
18
|
|
|
19
|
-
KANI_KEY = re.compile(r"(harness |(?:assume|cover|stub) .* in )(\S+)( #\d+)?", re.DOTALL)
|
|
19
|
+
KANI_KEY = re.compile(r"(harness |body |(?:assume|cover|stub) .* in )(\S+)( #\d+)?", re.DOTALL)
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
class RustFunction(NamedTuple):
|
|
@@ -93,7 +93,7 @@ def rust_functions(mask):
|
|
|
93
93
|
KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
|
|
94
94
|
MACROS = (
|
|
95
95
|
("assume", re.compile(r"\bkani\s*::\s*assume\s*\(")),
|
|
96
|
-
("
|
|
96
|
+
("any_where", re.compile(r"\bkani\s*::\s*any_where\s*(?:::\s*<[^<>]*(?:<[^<>]*>[^<>]*)*>\s*)?\(")),
|
|
97
97
|
("cover", re.compile(r"\bkani\s*::\s*cover\s*!\s*\(")),
|
|
98
98
|
("stub", re.compile(KANI_ATTRIBUTE + r"stub\s*\(")),
|
|
99
99
|
)
|
|
@@ -101,6 +101,8 @@ PROOF = re.compile(KANI_ATTRIBUTE + r"proof(?:_for_contract\s*\([^)]*\))?\s*\)?\
|
|
|
101
101
|
HARNESS_ATTRIBUTE = re.compile(r"kani::(?:should_panic(?:\(\)|\[\]|\{\})?|unwind(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}))")
|
|
102
102
|
KANI_TOKEN = re.compile(r"\bkani\s*::\s*(?:assume|any_where|cover|stub|proof|should_panic|unwind)\w*\b")
|
|
103
103
|
ATTRIBUTE = re.compile(r"#\s*(!\s*)?\[")
|
|
104
|
+
STATEMENT_END = re.compile(r"\s*;")
|
|
105
|
+
RUNS_CODE = re.compile(r"[(\[{?]|\b(?:return|break|continue|await|yield)\b")
|
|
104
106
|
INNER_ATTRIBUTE = re.compile(r"[\s\ufeff]*#\s*!\s*\[")
|
|
105
107
|
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
108
|
|
|
@@ -495,27 +497,55 @@ def kani_surface(path, reader):
|
|
|
495
497
|
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
498
|
|
|
497
499
|
surface = Surface()
|
|
498
|
-
spans, read = [], []
|
|
500
|
+
spans, read, covers = [], [], []
|
|
499
501
|
for kind, pattern in MACROS:
|
|
500
502
|
for match in pattern.finditer(mask):
|
|
501
503
|
end = after_closing(mask, match.end() - 1)
|
|
502
504
|
read.append((match.start(), end))
|
|
503
|
-
|
|
505
|
+
# 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 not RUNS_CODE.search(mask, match.end(), end - 1):
|
|
507
|
+
covers.append((match.start(), end))
|
|
508
|
+
# The generator's explicit type arguments constrain its domain alongside its predicate.
|
|
509
|
+
if kind == "any_where":
|
|
510
|
+
item_kind, expression = "assume", text[match.start():end]
|
|
511
|
+
else:
|
|
512
|
+
item_kind, expression = kind, text[match.end():end - 1]
|
|
513
|
+
argument = rust_masks(expression)
|
|
504
514
|
owner = owner_at(match.start(), attribute=kind == "stub").name
|
|
505
|
-
spans.append((match.start(), f"{
|
|
515
|
+
spans.append((match.start(), f"{item_kind} {collapse(argument.uncommented, argument.literals)} in {owner}", ""))
|
|
506
516
|
# Kani refuses these attributes on a function that is not a harness, so only a harness's are recorded.
|
|
507
517
|
attributes = {}
|
|
508
518
|
for start, end in applied_attributes(mask):
|
|
509
519
|
if HARNESS_ATTRIBUTE.fullmatch(item := re.sub(r"\s+", "", mask[start:end])):
|
|
510
520
|
read.append((start, end))
|
|
511
521
|
attributes.setdefault(owner_at(start, attribute=True), []).append(item)
|
|
522
|
+
def body(function):
|
|
523
|
+
# Each cover is an item of its own, so an added cover leaves the body as it was.
|
|
524
|
+
kept, start = [], function.body
|
|
525
|
+
for begin, end in covers:
|
|
526
|
+
if function.body < begin < function.end:
|
|
527
|
+
kept.append(text[start:begin])
|
|
528
|
+
start = semicolon.end() if (semicolon := STATEMENT_END.match(mask, end)) else end
|
|
529
|
+
kept.append(text[start:function.end])
|
|
530
|
+
return normalized(" ".join(kept))
|
|
531
|
+
|
|
532
|
+
harnesses = []
|
|
512
533
|
for match in PROOF.finditer(mask):
|
|
513
534
|
read.append(match.span())
|
|
514
535
|
harness = owner_at(match.start(), attribute=True)
|
|
536
|
+
harnesses.append(harness)
|
|
515
537
|
enclosing = sorted((item for item in functions + modules if item.start <= harness.start and harness.end <= item.end), key=lambda item: item.start)
|
|
516
538
|
guards = cfg_guards(source, [(0, 0, -1)] + [(item.start, item.keyword, item.body) for item in enclosing])
|
|
517
539
|
value = " ".join(filter(None, (declared, guards, *sorted(attributes.get(harness, ())), unread)))
|
|
518
540
|
spans.append((match.start(), f"harness {harness.name}", value))
|
|
541
|
+
spans.append((harness.body, f"body {harness.name}", body(harness)))
|
|
542
|
+
# A function in a module that holds a harness, or under one, such as an input helper, is part of what it checks.
|
|
543
|
+
scopes = {max((module for module in modules if module.start <= harness.start < module.end), key=lambda module: module.start, default=None)
|
|
544
|
+
for harness in harnesses}
|
|
545
|
+
for function in functions:
|
|
546
|
+
nested = any(other.body < function.start < other.end for other in functions)
|
|
547
|
+
if function not in harnesses and not nested and any(scope is None or scope.start <= function.start < scope.end for scope in scopes):
|
|
548
|
+
spans.append((function.body, f"body {function.name}", body(function)))
|
|
519
549
|
for token in KANI_TOKEN.finditer(mask):
|
|
520
550
|
if not any(start <= token.start() < end for start, end in read):
|
|
521
551
|
line = mask.count("\n", 0, token.start()) + 1
|
|
@@ -148,15 +148,18 @@ def step(command, *, merge=True, env=None):
|
|
|
148
148
|
return 127, "", f"cannot run {command[0]}: {error}\n"
|
|
149
149
|
|
|
150
150
|
|
|
151
|
-
def
|
|
152
|
-
"""
|
|
153
|
-
|
|
151
|
+
def project_files(project):
|
|
152
|
+
"""Find model sources and orphan records in the same walk, outside the root Lake build directory."""
|
|
153
|
+
sources, records = set(), []
|
|
154
154
|
for top, directories, names in os.walk(project):
|
|
155
|
-
found += [os.path.join(top, name) for name in directories + names
|
|
156
|
-
if name.endswith(".lean") and name != "lakefile.lean"]
|
|
157
155
|
if top == project and ".lake" in directories:
|
|
158
156
|
directories.remove(".lake")
|
|
159
|
-
|
|
157
|
+
for name in directories + names:
|
|
158
|
+
if name.endswith(".lean") and (top != project or name != "lakefile.lean"):
|
|
159
|
+
sources.add(os.path.join(top, name))
|
|
160
|
+
elif name.endswith(".statements"):
|
|
161
|
+
records.append(Path(top, name))
|
|
162
|
+
return sorted(sources), sorted(path for path in records if str(path.with_suffix(".lean")) not in sources)
|
|
160
163
|
|
|
161
164
|
|
|
162
165
|
def layout(objects, search_path):
|
|
@@ -205,18 +208,14 @@ def records_by_name(modules, module):
|
|
|
205
208
|
return records
|
|
206
209
|
|
|
207
210
|
|
|
208
|
-
def check_orphans(
|
|
209
|
-
"""Report every record
|
|
210
|
-
|
|
211
|
-
for path in sorted(project.rglob("*.statements")):
|
|
212
|
-
if ".lake" in path.relative_to(project).parts or path.with_suffix(".lean").is_file():
|
|
213
|
-
continue
|
|
211
|
+
def check_orphans(orphans, out):
|
|
212
|
+
"""Report every record without a model source in the project."""
|
|
213
|
+
for path in orphans:
|
|
214
214
|
record = read_record(path)
|
|
215
215
|
out(f"FROZEN {path}: source file is missing")
|
|
216
216
|
for declaration in record["declarations"]:
|
|
217
217
|
out(f"FROZEN {declaration['name']}: statement changed (source deleted)")
|
|
218
|
-
|
|
219
|
-
return int(failed)
|
|
218
|
+
return int(bool(orphans))
|
|
220
219
|
|
|
221
220
|
|
|
222
221
|
def freeze_statements(toolchain, modules, sources, out):
|
|
@@ -313,14 +312,14 @@ def checked(project, toolchain, files, freeze, out, work):
|
|
|
313
312
|
out(f"FAIL {source} does not exist")
|
|
314
313
|
return 1
|
|
315
314
|
else:
|
|
315
|
+
sources, orphans = project_files(project)
|
|
316
316
|
if not freeze:
|
|
317
|
-
status, output = statements(lambda sink: check_orphans(
|
|
317
|
+
status, output = statements(lambda sink: check_orphans(orphans, sink))
|
|
318
318
|
if status:
|
|
319
319
|
out(f"FAIL {scope}: frozen model sources are missing or their records are invalid")
|
|
320
320
|
for line in output:
|
|
321
321
|
out(line)
|
|
322
322
|
return status
|
|
323
|
-
sources = project_sources(project)
|
|
324
323
|
if not sources:
|
|
325
324
|
out(f"FAIL {project} has no .lean file to check")
|
|
326
325
|
return 1
|
|
@@ -409,12 +408,17 @@ def checked(project, toolchain, files, freeze, out, work):
|
|
|
409
408
|
# replays every declaration of the built modules through the kernel and rejects it. Use its exact-module
|
|
410
409
|
# replayer rather than its CLI's prefix search, which also finds deleted sources' cached objects. A named
|
|
411
410
|
# module rests on the project modules it imports, so replay those too.
|
|
412
|
-
prefix =
|
|
413
|
-
lambda process: process.communicate()[0], stdout=subprocess.PIPE,
|
|
414
|
-
encoding="utf-8", errors="replace")
|
|
411
|
+
status, prefix, errors = step(["elan", "run", toolchain, "lean", "--print-prefix"], merge=False)
|
|
415
412
|
prefix = prefix.rstrip("\n")
|
|
413
|
+
compiler = os.path.join(prefix, "bin", "lean")
|
|
414
|
+
if status or not os.path.isabs(prefix) or not os.path.isfile(compiler) or not os.access(compiler, os.X_OK):
|
|
415
|
+
out(f"FAIL {scope}: cannot locate {toolchain} for kernel replay (lean --print-prefix exit {status})")
|
|
416
|
+
for line in lines(errors) + lines(prefix):
|
|
417
|
+
out(line)
|
|
418
|
+
return 1
|
|
416
419
|
replay = "unavailable"
|
|
417
|
-
|
|
420
|
+
# The replayer imports LeanChecker. The installed CLI marks support even if its execute bit was lost.
|
|
421
|
+
if os.path.lexists(f"{prefix}/bin/leanchecker"):
|
|
418
422
|
imported = [line.removeprefix("IMPORTED ") for line in audit if line.startswith("IMPORTED ")]
|
|
419
423
|
replayed = set(modules) | {module for module in imported
|
|
420
424
|
if any((library / (module.replace(".", "/") + ".olean")).is_file() for library in libraries)}
|
|
@@ -89,13 +89,13 @@ def _command_sites(source, commands, edit_start, edit_end):
|
|
|
89
89
|
yield (cmd["property"], site), cmd, first
|
|
90
90
|
|
|
91
91
|
|
|
92
|
-
def _compare_commands(model, before, mutation, after):
|
|
93
|
-
start = mutation.
|
|
92
|
+
def _compare_commands(model, before, mutation, source, after):
|
|
93
|
+
start = mutation.start
|
|
94
94
|
end = start + len(mutation.new)
|
|
95
95
|
originals = {}
|
|
96
96
|
for site, cmd, _ in _command_sites(mutation.original, before, start, start + len(mutation.old)):
|
|
97
97
|
originals.setdefault(site, []).append(cmd["statement"])
|
|
98
|
-
commands = list(_command_sites(
|
|
98
|
+
commands = list(_command_sites(source, after, start, end))
|
|
99
99
|
counts = Counter(site for site, _, _ in commands)
|
|
100
100
|
line_shift = mutation.old.count("\n") - mutation.new.count("\n")
|
|
101
101
|
edit_line = mutation.original.count("\n", 0, start) + 1
|
|
@@ -139,10 +139,9 @@ class OriginalChecks:
|
|
|
139
139
|
self._theorems = {(decl["name"], decl["type"]) for decl in theorems}
|
|
140
140
|
self._commands = original["commands"]
|
|
141
141
|
|
|
142
|
-
def _theorem_checks(self, declarations, mutation):
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
edit_end = _position(mutation.source, start + len(mutation.new))
|
|
142
|
+
def _theorem_checks(self, declarations, mutation, source):
|
|
143
|
+
edit_start = _position(source, mutation.start)
|
|
144
|
+
edit_end = _position(source, mutation.start + len(mutation.new))
|
|
146
145
|
theorems = [decl for decl in declarations if decl["theorem"]]
|
|
147
146
|
names = {decl["name"] for decl in theorems}
|
|
148
147
|
for decl in theorems:
|
|
@@ -156,12 +155,12 @@ class OriginalChecks:
|
|
|
156
155
|
problem = ""
|
|
157
156
|
yield _Check(decl["start"], decl["end"], "theorem " + name, problem, _is_witness(name, names))
|
|
158
157
|
|
|
159
|
-
def broken_checks(self, mutation, copy, analysis):
|
|
158
|
+
def broken_checks(self, mutation, source, copy, analysis):
|
|
160
159
|
"""Return the original checks that fail, or raise ValueError if any error cannot be attributed."""
|
|
161
160
|
if not analysis["errors"]:
|
|
162
161
|
return []
|
|
163
|
-
theorems = list(self._theorem_checks(analysis["declarations"], mutation))
|
|
164
|
-
commands = list(_compare_commands(self._path, self._commands, mutation, analysis["commands"]))
|
|
162
|
+
theorems = list(self._theorem_checks(analysis["declarations"], mutation, source))
|
|
163
|
+
commands = list(_compare_commands(self._path, self._commands, mutation, source, analysis["commands"]))
|
|
165
164
|
failed = []
|
|
166
165
|
for error in analysis["errors"]:
|
|
167
166
|
position = [error["pos"]["line"], error["pos"]["column"]]
|
|
@@ -189,7 +188,8 @@ def prepare(model, project):
|
|
|
189
188
|
|
|
190
189
|
def check(mutation, work):
|
|
191
190
|
copy = work / model.name
|
|
192
|
-
|
|
193
|
-
|
|
191
|
+
source = mutation.apply()
|
|
192
|
+
copy.write_text(source, encoding="utf-8")
|
|
193
|
+
return original.broken_checks(mutation, source, copy, _analyze(copy, project, pin))
|
|
194
194
|
|
|
195
195
|
return original.targets, check
|
|
@@ -93,7 +93,10 @@ class Mutation:
|
|
|
93
93
|
old: str
|
|
94
94
|
new: str
|
|
95
95
|
original: str
|
|
96
|
-
|
|
96
|
+
start: int
|
|
97
|
+
|
|
98
|
+
def apply(self):
|
|
99
|
+
return "".join((self.original[:self.start], self.new, self.original[self.start + len(self.old):]))
|
|
97
100
|
|
|
98
101
|
|
|
99
102
|
class Verdict(Enum):
|
|
@@ -135,7 +138,7 @@ def parse(path):
|
|
|
135
138
|
|
|
136
139
|
|
|
137
140
|
def make_mutation(label, directives, model, text, language):
|
|
138
|
-
"""
|
|
141
|
+
"""Validate one mutation and locate its edit in the original model."""
|
|
139
142
|
lines = {keyword: [rest for word, rest in directives if word == keyword] for keyword in DIRECTIVES}
|
|
140
143
|
for keyword in SINGLE:
|
|
141
144
|
if len(lines[keyword]) > 1:
|
|
@@ -147,17 +150,18 @@ def make_mutation(label, directives, model, text, language):
|
|
|
147
150
|
if lines["only"] and not language.takes_only:
|
|
148
151
|
stop(f"mutation '{label}': {language.name} mutations do not support 'only'")
|
|
149
152
|
old = "\n".join(lines["-"])
|
|
150
|
-
|
|
151
|
-
if
|
|
153
|
+
start = text.find(old) if old else -1
|
|
154
|
+
if start < 0 or text.find(old, start + len(old)) >= 0:
|
|
155
|
+
count = text.count(old) if old else 0
|
|
152
156
|
stop(f"mutation '{label}': its - text occurs {count} times in {model}, want 1")
|
|
153
157
|
detects, only = (lines[keyword][0].strip() if lines[keyword] else "" for keyword in SINGLE)
|
|
154
158
|
new = "\n".join(lines["+"])
|
|
155
|
-
return Mutation(label, detects, only, old, new, text,
|
|
159
|
+
return Mutation(label, detects, only, old, new, text, start)
|
|
156
160
|
|
|
157
161
|
|
|
158
162
|
def check_tla(plan, checker, mutation, work):
|
|
159
163
|
try:
|
|
160
|
-
detection = plan.check(checker, mutation.detects, mutation.only, mutation.
|
|
164
|
+
detection = plan.check(checker, mutation.detects, mutation.only, mutation.apply(), work)
|
|
161
165
|
except ValueError as error:
|
|
162
166
|
return Result(Verdict.ERROR, str(error))
|
|
163
167
|
covers = frozenset({mutation.detects})
|
|
@@ -178,9 +182,9 @@ def check_lean(broken_checks, mutation, work):
|
|
|
178
182
|
|
|
179
183
|
def check_rust(model, project, verifier, bounds, sources, mutation, work):
|
|
180
184
|
"""Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness."""
|
|
181
|
-
copy = sources.stage(project, work
|
|
185
|
+
copy = sources.stage(project, work)
|
|
182
186
|
covers = frozenset({mutation.detects})
|
|
183
|
-
(copy / model.relative_to(project)).write_text(mutation.
|
|
187
|
+
(copy / model.relative_to(project)).write_text(mutation.apply(), encoding="utf-8")
|
|
184
188
|
# Cargo resolves configuration from cwd, including paths outside the copied packages.
|
|
185
189
|
outcome = kani.verify(copy, work, verifier, mutation.detects, bounds[mutation.detects].unwind, cwd=project)
|
|
186
190
|
if outcome.verdict is kani.Verdict.PASS:
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# Copyright (c) 2026 Michael Denyer
|
|
2
2
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
3
|
-
"""Read Rust source text: blank its comments and string contents, and find where a bracketed span
|
|
3
|
+
"""Read Rust source text: blank its comments and string contents, compact its whitespace, and find where a bracketed span
|
|
4
|
+
ends."""
|
|
4
5
|
import re
|
|
5
6
|
from typing import NamedTuple
|
|
6
7
|
|
|
@@ -64,6 +65,38 @@ def rust_masks(source):
|
|
|
64
65
|
return RustSource("".join(text), "".join(mask), literals)
|
|
65
66
|
|
|
66
67
|
|
|
68
|
+
# A `#` joins a word into a raw identifier or string, such as `r#x`.
|
|
69
|
+
WORD = re.compile(r"[\w#]")
|
|
70
|
+
# A character that can join a neighbour into one token, as `<<`, `&&` and `..=` do.
|
|
71
|
+
OPERATOR = frozenset("!%&*+-./:<=>^|")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def normalized(source):
|
|
75
|
+
"""Return Rust source without comments and without the whitespace outside literals that a reformat can change.
|
|
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
|
+
"""
|
|
80
|
+
lexed = rust_masks(source)
|
|
81
|
+
text = lexed.uncommented
|
|
82
|
+
inside = {i for start, end in lexed.literals for i in range(start, end)}
|
|
83
|
+
|
|
84
|
+
def kind(i):
|
|
85
|
+
if i in inside or WORD.match(text, i):
|
|
86
|
+
return "word"
|
|
87
|
+
return "operator" if text[i] in OPERATOR else None
|
|
88
|
+
|
|
89
|
+
def space(run):
|
|
90
|
+
if run.start() in inside:
|
|
91
|
+
return run[0]
|
|
92
|
+
if run.start() == 0 or run.end() == len(text):
|
|
93
|
+
return ""
|
|
94
|
+
left = kind(run.start() - 1)
|
|
95
|
+
return " " if left and left == kind(run.end()) else ""
|
|
96
|
+
|
|
97
|
+
return re.sub(r"\s+", space, text)
|
|
98
|
+
|
|
99
|
+
|
|
67
100
|
def after_closing(mask, opener):
|
|
68
101
|
closer = {"(": ")", "[": "]", "{": "}"}[mask[opener]]
|
|
69
102
|
depth = 0
|
|
@@ -370,19 +370,20 @@ def main():
|
|
|
370
370
|
print(f"FAIL --source {source} is {path}, which no commit in {root} has")
|
|
371
371
|
return 1
|
|
372
372
|
sources.append(str(path.relative_to(root)))
|
|
373
|
-
|
|
373
|
+
source_paths = renamed(root, sync, sources)
|
|
374
|
+
paths = set(source_paths)
|
|
374
375
|
excluded = [f":(exclude){path}" for path in relative if path not in sources]
|
|
375
|
-
suffixes = {Path(path).suffix.lower() for path in
|
|
376
|
+
suffixes = {Path(path).suffix.lower() for path in source_paths}
|
|
376
377
|
missing = []
|
|
377
378
|
for name in arguments.name:
|
|
378
379
|
found = git(root, "grep", "-l", "-z", "-w", "-F", "-e", name, "--", ".", *excluded, check=False)
|
|
379
380
|
if found.returncode > 1:
|
|
380
381
|
raise RuntimeError(f"git grep for {name} failed: {found.stderr.strip()}")
|
|
381
|
-
roles = {file: role(file,
|
|
382
|
+
roles = {file: role(file, source_paths, suffixes) for file in found.stdout.split("\0") if file}
|
|
382
383
|
if not any(kind == "defines" and in_code(root, file, name) for file, kind in roles.items()):
|
|
383
384
|
missing.append(name)
|
|
384
385
|
files = [*roles, *held(root, sync, name, [".", *excluded])]
|
|
385
|
-
paths.update(file for file in files if role(file,
|
|
386
|
+
paths.update(file for file in files if role(file, source_paths, suffixes))
|
|
386
387
|
for path in sorted(paths):
|
|
387
388
|
print(f"PATH {path}")
|
|
388
389
|
for name in missing:
|
|
@@ -88,7 +88,11 @@ class Reach:
|
|
|
88
88
|
@dataclass(frozen=True)
|
|
89
89
|
class Run:
|
|
90
90
|
label: str
|
|
91
|
-
|
|
91
|
+
bindings: tuple[tuple[str, str], ...]
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def constants(self):
|
|
95
|
+
return " ".join(f"{name}={value}" for name, value in self.bindings)
|
|
92
96
|
|
|
93
97
|
|
|
94
98
|
@dataclass(frozen=True)
|
|
@@ -96,6 +100,16 @@ class Malformed:
|
|
|
96
100
|
message: str
|
|
97
101
|
|
|
98
102
|
|
|
103
|
+
def _parse_run(label, constants):
|
|
104
|
+
bindings = []
|
|
105
|
+
for token in constants.split():
|
|
106
|
+
name, _, value = token.partition("=")
|
|
107
|
+
if not name or not value:
|
|
108
|
+
return Malformed(f"malformed constant {token!r} in run {label!r}: expected Name=Value")
|
|
109
|
+
bindings.append((name, value))
|
|
110
|
+
return Run(label, tuple(bindings))
|
|
111
|
+
|
|
112
|
+
|
|
99
113
|
def _directives(lines):
|
|
100
114
|
"""Yield each directive of a matrix in file order, with a Malformed in place of a line it rejects."""
|
|
101
115
|
seen_spec = False
|
|
@@ -131,7 +145,7 @@ def _directives(lines):
|
|
|
131
145
|
elif not seen_spec:
|
|
132
146
|
yield Malformed(f"run '{label.rstrip()}' before any spec line")
|
|
133
147
|
else:
|
|
134
|
-
yield
|
|
148
|
+
yield _parse_run(label.rstrip(), constants)
|
|
135
149
|
else:
|
|
136
150
|
yield Malformed(f"unknown directive: {line}")
|
|
137
151
|
|
|
@@ -513,7 +527,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
513
527
|
spec, run = task.spec, task.run
|
|
514
528
|
operator = task.reach.operator if task.reach else ""
|
|
515
529
|
name = Path(spec).name.removesuffix(".tla")
|
|
516
|
-
run_constants = run.constants
|
|
530
|
+
run_constants = run.constants
|
|
517
531
|
run_checks = tuple(check.line for check in task.checks)
|
|
518
532
|
if not (matrix_dir / spec).is_file():
|
|
519
533
|
return Result(Outcome.MISSING, name, run.label, detail=spec, constants=run_constants, checks=run_checks)
|
|
@@ -525,7 +539,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
|
|
|
525
539
|
dest.write_text(source, encoding="utf-8")
|
|
526
540
|
else:
|
|
527
541
|
dest.write_bytes(module.read_bytes())
|
|
528
|
-
constants = "".join(f" {
|
|
542
|
+
constants = "".join(f" {name} = {value}\n" for name, value in run.bindings)
|
|
529
543
|
config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
|
|
530
544
|
if not task.check_deadlock:
|
|
531
545
|
config += "CHECK_DEADLOCK FALSE\n"
|