agent-formal-verify 0.4.12 → 0.4.14
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 +150 -0
- package/README.md +5 -3
- package/package.json +2 -1
- package/skills/formal-verify/SKILL.md +17 -19
- 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 +33 -3
- package/skills/formal-verify/references/lean-brief.md +2 -2
- package/skills/formal-verify/references/rust-brief.md +58 -6
- package/skills/formal-verify/references/setup.md +23 -7
- package/skills/formal-verify/references/tla-brief.md +3 -3
- package/skills/formal-verify/scripts/baseline.py +290 -261
- package/skills/formal-verify/scripts/kani-check.sh +3 -1
- package/skills/formal-verify/scripts/kani.py +127 -59
- package/skills/formal-verify/scripts/kani_reader.py +592 -0
- 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/rust_source.py +74 -0
- package/skills/formal-verify/scripts/setup.sh +18 -19
- package/skills/formal-verify/scripts/storage.py +207 -0
- package/skills/formal-verify/scripts/surface.py +27 -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 +501 -117
- package/skills/formal-verify/scripts/tlc_report.py +516 -0
- package/skills/formal-verify/scripts/tlc_trace.py +167 -0
- 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
- package/skills/formal-verify/scripts/tlc-trace.py +0 -64
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright (c) 2026 Michael Denyer
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
+
"""Reduce the error trace in a TLC log to what each step changed.
|
|
5
|
+
|
|
6
|
+
Reads a TLC log (a file argument or stdin), finds the behaviour TLC prints
|
|
7
|
+
for an invariant violation, a deadlock or a temporal counter-example, and
|
|
8
|
+
prints one block per state: its number and action, then only the variables
|
|
9
|
+
whose value differs from the previous state. The first state prints every
|
|
10
|
+
variable. A "Back to state" line (a liveness lasso) is printed as is.
|
|
11
|
+
Exits 1 when the log holds no trace.
|
|
12
|
+
|
|
13
|
+
Usage: tlc_trace.py [tlc.log]
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
import sys
|
|
19
|
+
from contextlib import nullcontext
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
|
|
22
|
+
START = ("The behavior up to this point is", "constitutes a counter-example")
|
|
23
|
+
INITIAL_MARKER = "is violated by the initial state:"
|
|
24
|
+
STATE = re.compile(r"^State (\d+): <?(.*?)>?$")
|
|
25
|
+
LASSO = re.compile(r"^Back to state (\d+)(?::\s*<?(.*?)>?)?$")
|
|
26
|
+
LOCATION = re.compile(r" line \d+, col \d+ to line \d+, col \d+ of module \w+$")
|
|
27
|
+
# TLC omits the leading conjunction when the spec has one variable.
|
|
28
|
+
VAR = re.compile(r"^(?:/\\ )?(\w+) = (.*)$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class VarDiff:
|
|
33
|
+
name: str
|
|
34
|
+
old: str | None
|
|
35
|
+
new: str
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Step:
|
|
40
|
+
number: int
|
|
41
|
+
action: str
|
|
42
|
+
values: tuple[tuple[str, str], ...]
|
|
43
|
+
changed: tuple[VarDiff, ...]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Lasso:
|
|
48
|
+
target: int
|
|
49
|
+
action: str
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class Trace:
|
|
54
|
+
steps: tuple[Step, ...]
|
|
55
|
+
lasso: Lasso | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _build_step(number, action, values, prev):
|
|
59
|
+
# TLC prints a stuttering step, "State N: Stuttering", with no variables: it repeats the state before it.
|
|
60
|
+
items = tuple((values or prev or {}).items())
|
|
61
|
+
if prev is None:
|
|
62
|
+
diffs = tuple(VarDiff(name, None, val) for name, val in items)
|
|
63
|
+
else:
|
|
64
|
+
diffs = tuple(VarDiff(name, prev.get(name), val) for name, val in items if prev.get(name) != val)
|
|
65
|
+
return Step(number, action, items, diffs)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _parse_initial(lines) -> Trace | None:
|
|
69
|
+
values, var = {}, None
|
|
70
|
+
for line in lines:
|
|
71
|
+
if m := VAR.match(line):
|
|
72
|
+
var = m[1]
|
|
73
|
+
values[var] = m[2]
|
|
74
|
+
elif var and line.startswith(" "):
|
|
75
|
+
values[var] += "\n" + line
|
|
76
|
+
else:
|
|
77
|
+
break
|
|
78
|
+
return Trace((_build_step(1, "Initial predicate", values, None),)) if values else None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _parse_standard(lines) -> Trace | None:
|
|
82
|
+
steps, prev, current, var, lasso = [], None, None, None, None
|
|
83
|
+
for line in lines:
|
|
84
|
+
if m := STATE.match(line):
|
|
85
|
+
if current is not None:
|
|
86
|
+
steps.append(_build_step(current[0], current[1], current[2], prev))
|
|
87
|
+
prev = current[2] or prev
|
|
88
|
+
current, var = (int(m[1]), LOCATION.sub("", m[2]), {}), None
|
|
89
|
+
elif m := LASSO.match(line):
|
|
90
|
+
if current is not None:
|
|
91
|
+
steps.append(_build_step(current[0], current[1], current[2], prev))
|
|
92
|
+
current = None
|
|
93
|
+
lasso = Lasso(int(m[1]), LOCATION.sub("", m[2] or ""))
|
|
94
|
+
break
|
|
95
|
+
elif current is not None and (m := VAR.match(line)):
|
|
96
|
+
var = m[1]
|
|
97
|
+
current[2][var] = m[2]
|
|
98
|
+
elif current is not None and var and line.startswith(" "):
|
|
99
|
+
current[2][var] += "\n" + line
|
|
100
|
+
elif current is not None:
|
|
101
|
+
steps.append(_build_step(current[0], current[1], current[2], prev))
|
|
102
|
+
prev, current, var = current[2] or prev, None, None
|
|
103
|
+
if line.strip():
|
|
104
|
+
break
|
|
105
|
+
elif steps and line.strip():
|
|
106
|
+
break
|
|
107
|
+
if current is not None:
|
|
108
|
+
steps.append(_build_step(current[0], current[1], current[2], prev))
|
|
109
|
+
return Trace(tuple(steps), lasso) if steps else None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def parse(lines) -> Trace | None:
|
|
113
|
+
"""Parse the first TLC error trace into a Trace, or return None when absent."""
|
|
114
|
+
stripped = (line.rstrip("\r\n") for line in lines)
|
|
115
|
+
for line in stripped:
|
|
116
|
+
if any(marker in line for marker in START):
|
|
117
|
+
return _parse_standard(stripped)
|
|
118
|
+
if INITIAL_MARKER in line:
|
|
119
|
+
return _parse_initial(stripped)
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def states(lines):
|
|
124
|
+
"""Yield (title, {var: value}) per state of the first error trace."""
|
|
125
|
+
lines = (line.rstrip("\n") for line in lines)
|
|
126
|
+
# any() stops on the marker line, so the loop below resumes just after it.
|
|
127
|
+
if not any(marker in line for line in lines for marker in START):
|
|
128
|
+
return
|
|
129
|
+
title, values, var = None, {}, None
|
|
130
|
+
for line in lines:
|
|
131
|
+
if m := STATE.match(line):
|
|
132
|
+
title, values, var = f"state {m[1]}: {LOCATION.sub('', m[2])}", {}, None
|
|
133
|
+
elif line.startswith("Back to state"):
|
|
134
|
+
yield line, {}
|
|
135
|
+
elif title and (m := VAR.match(line)):
|
|
136
|
+
var = m[1]
|
|
137
|
+
values[var] = m[2]
|
|
138
|
+
elif title and var and line.startswith(" "):
|
|
139
|
+
values[var] += "\n" + line
|
|
140
|
+
elif title:
|
|
141
|
+
yield title, values
|
|
142
|
+
title = None
|
|
143
|
+
if title:
|
|
144
|
+
yield title, values
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def reduce(lines):
|
|
148
|
+
"""Return the printed lines of the first error trace, or None when the log holds no trace."""
|
|
149
|
+
out, prev, found = [], {}, False
|
|
150
|
+
for title, values in states(lines):
|
|
151
|
+
found = True
|
|
152
|
+
out.append(f"--- {title}")
|
|
153
|
+
out += [f" {var} = {value}" for var, value in values.items() if prev.get(var) != value]
|
|
154
|
+
prev = values or prev
|
|
155
|
+
return "\n".join(out).split("\n") if found else None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def main():
|
|
159
|
+
with (open(sys.argv[1], encoding="utf-8") if len(sys.argv) > 1 else nullcontext(sys.stdin)) as src:
|
|
160
|
+
reduced = reduce(src)
|
|
161
|
+
if reduced is None:
|
|
162
|
+
sys.exit(1)
|
|
163
|
+
print("\n".join(reduced))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
if __name__ == "__main__":
|
|
167
|
+
main()
|
package/skills/setup/SKILL.md
CHANGED
|
@@ -8,7 +8,7 @@ description: "Prepare all shared tools for the agent-formal-verify plugin: Java,
|
|
|
8
8
|
Prepare the complete shared toolset once, independently of any repository. Verification selects TLA+, Lean and Kani from each repository's current targets. A global plugin installation uses the same tools across repositories.
|
|
9
9
|
|
|
10
10
|
1. Read [tool setup](../formal-verify/references/setup.md) for pinned versions and environment settings. Inspect the operating system and existing runtimes. Reuse installed prerequisites and tool caches.
|
|
11
|
-
2. Ensure a working JDK, Python 3
|
|
11
|
+
2. Ensure a working JDK, Python 3.9 or later, elan, Rust, the pinned Kani and the pinned TLC JAR are available. Install missing prerequisites through the user's existing package manager or the upstream documented installer, following their installation constraints. Obtain `tla2tools.jar` from the TLA+ release that `scripts/tlc.py` pins and save it at the path the helper names; the helper verifies its SHA256 and downloads nothing itself. If no suitable installation method is available, or the user has not allowed installation, report the missing prerequisites and their installation instructions.
|
|
12
12
|
|
|
13
13
|
Install the Kani version from tool setup with Cargo, then run `cargo kani setup`. The plugin's helpers verify it without installing or downloading it.
|
|
14
14
|
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
-- Copyright (c) 2026 Michael Denyer
|
|
2
|
-
-- SPDX-License-Identifier: GPL-3.0-only
|
|
3
|
-
-- Elaborate one source and report declaration identities, ranges and errors.
|
|
4
|
-
-- Run through the target project's pinned Lake environment, without building it.
|
|
5
|
-
import Lean
|
|
6
|
-
|
|
7
|
-
open Lean Elab Command
|
|
8
|
-
|
|
9
|
-
private def point (p : Position) : Json := toJson (p.line, p.column)
|
|
10
|
-
|
|
11
|
-
-- Older Lean numbers anonymous binders by a file-wide hygiene counter, so an
|
|
12
|
-
-- edit to an earlier command renames them without changing the statement.
|
|
13
|
-
private partial def unnamed (e : Expr) : Expr := e.replace fun
|
|
14
|
-
| .forallE _ t b bi => some (.forallE .anonymous (unnamed t) (unnamed b) bi)
|
|
15
|
-
| .lam _ t b bi => some (.lam .anonymous (unnamed t) (unnamed b) bi)
|
|
16
|
-
| _ => none
|
|
17
|
-
|
|
18
|
-
-- An example's statement is the type of the local Lean binds for its header, and
|
|
19
|
-
-- a guard's is its term. Closing over the local context removes the ids of
|
|
20
|
-
-- section variables, which shift when an earlier command changes.
|
|
21
|
-
private def statement (trees : PersistentArray InfoTree) (check : Syntax) : IO Json := do
|
|
22
|
-
let isExample := check.isOfKind ``Parser.Command.example
|
|
23
|
-
let target := if isExample then check else check[1]
|
|
24
|
-
let wanted (ti : TermInfo) := ti.stx.getPos? == target.getPos? &&
|
|
25
|
-
(if isExample then ti.stx.isOfKind ``Parser.Command.declId && ti.expr.isFVar
|
|
26
|
-
else ti.stx.getTailPos? == target.getTailPos?)
|
|
27
|
-
let found := trees.foldl (init := none) fun found tree => found <|> tree.foldInfo (init := none)
|
|
28
|
-
fun ctx info found => found <|> match info with
|
|
29
|
-
| .ofTermInfo ti => if wanted ti then some (ctx, ti) else none
|
|
30
|
-
| _ => none
|
|
31
|
-
let some (ctx, ti) := found | return Json.null
|
|
32
|
-
ctx.runMetaM ti.lctx do
|
|
33
|
-
let e ← instantiateMVars (← if isExample then Meta.inferType ti.expr else pure ti.expr)
|
|
34
|
-
let xs := ti.lctx.foldl (init := #[]) fun xs decl =>
|
|
35
|
-
if decl.isImplementationDetail then xs else xs.push decl.toExpr
|
|
36
|
-
let e ← Meta.mkLambdaFVars xs e
|
|
37
|
-
return if e.hasFVar || e.hasMVar then Json.null else toJson (reprStr (unnamed e))
|
|
38
|
-
|
|
39
|
-
private def declarations (instances : Array (Nat × Nat)) : CommandElabM (Array Json) := do
|
|
40
|
-
let env ← getEnv
|
|
41
|
-
let fileMap ← getFileMap
|
|
42
|
-
let names := env.constants.fold (fun acc name _ =>
|
|
43
|
-
if env.isImportedConst name then acc else acc.push name) #[]
|
|
44
|
-
let mut result := #[]
|
|
45
|
-
for name in names do
|
|
46
|
-
let some ranges ← findDeclarationRanges? name | continue
|
|
47
|
-
let pos := (fileMap.ofPosition ranges.selectionRange.pos).byteIdx
|
|
48
|
-
-- Local and scoped instances may no longer be registered in the final environment.
|
|
49
|
-
let instanceDecl := Meta.isInstanceCore env name || instances.any fun (start, tail) =>
|
|
50
|
-
start ≤ pos && pos < tail
|
|
51
|
-
let info := (env.find? name).get!
|
|
52
|
-
result := result.push <| Json.mkObj [
|
|
53
|
-
("name", toJson ((privateToUserName? name).getD name).toString),
|
|
54
|
-
("private", toJson (privateToUserName? name).isSome),
|
|
55
|
-
("theorem", toJson (info.isTheorem && !env.isProjectionFn name && !instanceDecl)),
|
|
56
|
-
("type", toJson (reprStr (info.levelParams, unnamed info.type))),
|
|
57
|
-
("start", point ranges.range.pos), ("end", point ranges.range.endPos)]
|
|
58
|
-
return result
|
|
59
|
-
|
|
60
|
-
unsafe def main (args : List String) : IO UInt32 := do
|
|
61
|
-
let [path] := args | throw <| IO.userError "usage: lean-mutations.lean <source.lean>"
|
|
62
|
-
enableInitializersExecution
|
|
63
|
-
initSearchPath (← findSysroot)
|
|
64
|
-
let inputCtx := Parser.mkInputContext (← IO.FS.readFile path) path
|
|
65
|
-
let (header, parserState, messages) ← Parser.parseHeader inputCtx
|
|
66
|
-
let (env, messages) ← processHeader header {} messages inputCtx
|
|
67
|
-
let state ← IO.processCommands inputCtx parserState (Command.mkState env messages {})
|
|
68
|
-
let mut commands := #[]
|
|
69
|
-
let mut instances := #[]
|
|
70
|
-
for stx in state.commands do
|
|
71
|
-
if let some instanceStx := stx.find? (·.isOfKind ``Parser.Command.instance) then
|
|
72
|
-
if let (some start, some tail) := (instanceStx.getPos?, instanceStx.getTailPos?) then
|
|
73
|
-
instances := instances.push (start.byteIdx, tail.byteIdx)
|
|
74
|
-
let some start := stx.getPos? | continue
|
|
75
|
-
let some tail := stx.getTailPos? | continue
|
|
76
|
-
let propertyStx := stx.find? fun cmd =>
|
|
77
|
-
cmd.isOfKind ``Parser.Command.guardCmd || cmd.isOfKind ``Parser.Command.example
|
|
78
|
-
let property := match propertyStx with
|
|
79
|
-
| some cmd => if cmd.isOfKind ``Parser.Command.guardCmd then "#guard" else "example"
|
|
80
|
-
| none => ""
|
|
81
|
-
let propertyStart := (propertyStx.bind Syntax.getPos?).getD start
|
|
82
|
-
let propertyEnd := (propertyStx.bind Syntax.getTailPos?).getD tail
|
|
83
|
-
commands := commands.push <| Json.mkObj [
|
|
84
|
-
("property", toJson property),
|
|
85
|
-
("statement", toJson (← propertyStx.mapM (statement state.commandState.infoState.trees))),
|
|
86
|
-
("start", point (inputCtx.fileMap.toPosition propertyStart)),
|
|
87
|
-
("end", point (inputCtx.fileMap.toPosition propertyEnd))]
|
|
88
|
-
let (decls, _) ← (Frontend.runCommandElabM (declarations instances)).run { inputCtx } |>.run state
|
|
89
|
-
let mut errors := #[]
|
|
90
|
-
for msg in state.commandState.messages.toList do
|
|
91
|
-
if msg.severity == .error then errors := errors.push (← msg.toJson)
|
|
92
|
-
IO.println <| "AFV_LEAN " ++ (Json.mkObj [
|
|
93
|
-
("declarations", toJson decls), ("commands", toJson commands),
|
|
94
|
-
("errors", toJson errors)]).compress
|
|
95
|
-
return 0
|
|
@@ -1,161 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# Copyright (c) 2026 Michael Denyer
|
|
3
|
-
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
-
"""Store or check declaration fingerprints emitted by the Lean audit."""
|
|
5
|
-
|
|
6
|
-
import argparse
|
|
7
|
-
import hashlib
|
|
8
|
-
import json
|
|
9
|
-
import sys
|
|
10
|
-
import tempfile
|
|
11
|
-
from pathlib import Path
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
def fingerprint(expression):
|
|
15
|
-
return hashlib.sha256(expression.encode("utf-8")).hexdigest()
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def declarations(audit):
|
|
19
|
-
modules = {}
|
|
20
|
-
for line in audit.read_text(encoding="utf-8").splitlines():
|
|
21
|
-
if not line.startswith("STATEMENT "):
|
|
22
|
-
continue
|
|
23
|
-
raw = json.loads(line.removeprefix("STATEMENT "))
|
|
24
|
-
record = {key: raw[key] for key in ("name", "kind", "type")}
|
|
25
|
-
record["type"] = " ".join(record["type"].split())
|
|
26
|
-
record["typeHash"] = fingerprint(raw["typeExpr"])
|
|
27
|
-
record["valueHash"] = None if raw["valueExpr"] is None else fingerprint(raw["valueExpr"])
|
|
28
|
-
modules.setdefault(raw["module"], []).append(record)
|
|
29
|
-
return modules
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
def records_by_name(modules, module):
|
|
33
|
-
"""Return the module's audited records by name, refusing two declarations with one name."""
|
|
34
|
-
records = {}
|
|
35
|
-
for record in modules.get(module, []):
|
|
36
|
-
if record["name"] in records:
|
|
37
|
-
raise ValueError(f"ambiguous declaration identity {record['name']} in {module}")
|
|
38
|
-
records[record["name"]] = record
|
|
39
|
-
return records
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def read_record(path):
|
|
43
|
-
record = json.loads(path.read_text(encoding="utf-8"))
|
|
44
|
-
if not isinstance(record, dict) or record.get("format") != 1:
|
|
45
|
-
raise ValueError(f"{path}: unsupported statements format")
|
|
46
|
-
if not isinstance(record.get("toolchain"), str) or not isinstance(record.get("module"), str):
|
|
47
|
-
raise TypeError(f"{path}: missing toolchain or module")
|
|
48
|
-
entries = record.get("declarations")
|
|
49
|
-
if not isinstance(entries, list) or not entries:
|
|
50
|
-
raise ValueError(f"{path}: missing declarations")
|
|
51
|
-
seen = set()
|
|
52
|
-
for entry in entries:
|
|
53
|
-
if not isinstance(entry, dict) or not all(isinstance(entry.get(key), str) for key in ("name", "kind", "type", "typeHash")):
|
|
54
|
-
raise ValueError(f"{path}: malformed declaration")
|
|
55
|
-
if "valueHash" not in entry or entry["valueHash"] is not None and not isinstance(entry["valueHash"], str):
|
|
56
|
-
raise ValueError(f"{path}: malformed value hash")
|
|
57
|
-
if entry["name"] in seen:
|
|
58
|
-
raise ValueError(f"{path}: duplicate declaration {entry['name']}")
|
|
59
|
-
seen.add(entry["name"])
|
|
60
|
-
return record
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
def check_orphans(project):
|
|
64
|
-
failed = False
|
|
65
|
-
for path in sorted(project.rglob("*.statements")):
|
|
66
|
-
if ".lake" in path.relative_to(project).parts or path.with_suffix(".lean").is_file():
|
|
67
|
-
continue
|
|
68
|
-
record = read_record(path)
|
|
69
|
-
print(f"FROZEN {path}: source file is missing")
|
|
70
|
-
for declaration in record["declarations"]:
|
|
71
|
-
print(f"FROZEN {declaration['name']}: statement changed (source deleted)")
|
|
72
|
-
failed = True
|
|
73
|
-
return int(failed)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
def freeze(toolchain, modules, sources):
|
|
77
|
-
"""Record every source's statements, writing none unless all of them can be recorded."""
|
|
78
|
-
pending = []
|
|
79
|
-
for module, source in sources:
|
|
80
|
-
records = records_by_name(modules, module)
|
|
81
|
-
if not records:
|
|
82
|
-
raise ValueError(f"no declaration records for {source}")
|
|
83
|
-
record = {"format": 1, "toolchain": toolchain, "module": module,
|
|
84
|
-
"declarations": [records[name] for name in sorted(records)]}
|
|
85
|
-
pending.append((source.with_suffix(".statements"), json.dumps(record, ensure_ascii=False, indent=2) + "\n"))
|
|
86
|
-
for path, contents in pending:
|
|
87
|
-
temporary = None
|
|
88
|
-
try:
|
|
89
|
-
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as stream:
|
|
90
|
-
temporary = Path(stream.name)
|
|
91
|
-
stream.write(contents)
|
|
92
|
-
temporary.replace(path)
|
|
93
|
-
finally:
|
|
94
|
-
if temporary is not None:
|
|
95
|
-
temporary.unlink(missing_ok=True)
|
|
96
|
-
print(f"FROZEN {path}: statements recorded; proofs not checked")
|
|
97
|
-
return 0
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
def check(toolchain, modules, sources):
|
|
101
|
-
"""Compare every recorded source's statements with the audit; a source without a record passes."""
|
|
102
|
-
failed = False
|
|
103
|
-
for module, source in sources:
|
|
104
|
-
path = source.with_suffix(".statements")
|
|
105
|
-
if not path.exists():
|
|
106
|
-
continue
|
|
107
|
-
records = records_by_name(modules, module)
|
|
108
|
-
frozen = read_record(path)
|
|
109
|
-
if frozen["toolchain"] != toolchain:
|
|
110
|
-
print(f"FROZEN {path}: toolchain changed from {frozen['toolchain']} to {toolchain}; review and run --freeze")
|
|
111
|
-
failed = True
|
|
112
|
-
continue
|
|
113
|
-
if frozen["module"] != module:
|
|
114
|
-
raise ValueError(f"{path}: expected module {module}, found {frozen['module']}")
|
|
115
|
-
changed = 0
|
|
116
|
-
for old in frozen["declarations"]:
|
|
117
|
-
if old["kind"] == "opaque" and old["valueHash"] is None:
|
|
118
|
-
print(f"FROZEN {old['name']}: opaque body was not recorded; review the definition and run --freeze")
|
|
119
|
-
failed = True
|
|
120
|
-
continue
|
|
121
|
-
new = records.get(old["name"])
|
|
122
|
-
if new is not None and all(old[key] == new[key] for key in ("kind", "typeHash", "valueHash")):
|
|
123
|
-
continue
|
|
124
|
-
changed += 1
|
|
125
|
-
print(f"FROZEN {old['name']}: statement changed")
|
|
126
|
-
print(f" old: {old['type']}")
|
|
127
|
-
print(f" new: {new['type'] if new else '(deleted)'}")
|
|
128
|
-
if new and old["valueHash"] != new["valueHash"]:
|
|
129
|
-
print(" definition value changed")
|
|
130
|
-
if changed == len(frozen["declarations"]):
|
|
131
|
-
print(f"FROZEN {path}: every recorded declaration changed; review the model and toolchain before --freeze")
|
|
132
|
-
failed |= changed > 0
|
|
133
|
-
return int(failed)
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
def main():
|
|
137
|
-
parser = argparse.ArgumentParser(description=__doc__)
|
|
138
|
-
commands = parser.add_subparsers(dest="command", required=True)
|
|
139
|
-
commands.add_parser("orphans", help="report records whose source file is gone").add_argument("project", type=Path)
|
|
140
|
-
for name, purpose in (("freeze", "record each source's statements"), ("check", "compare each recorded source's statements")):
|
|
141
|
-
command = commands.add_parser(name, help=purpose)
|
|
142
|
-
command.add_argument("toolchain")
|
|
143
|
-
command.add_argument("audit", type=Path, help="the audit's output, with its STATEMENT lines")
|
|
144
|
-
command.add_argument("module_names", type=Path, help="the module of each source, one per line in source order")
|
|
145
|
-
command.add_argument("sources", nargs="+", type=Path)
|
|
146
|
-
arguments = parser.parse_args()
|
|
147
|
-
if arguments.command == "orphans":
|
|
148
|
-
return check_orphans(arguments.project)
|
|
149
|
-
names = arguments.module_names.read_text(encoding="utf-8").splitlines()
|
|
150
|
-
if len(names) != len(arguments.sources):
|
|
151
|
-
raise ValueError("Lake did not return one module per source")
|
|
152
|
-
action = freeze if arguments.command == "freeze" else check
|
|
153
|
-
return action(arguments.toolchain, declarations(arguments.audit), zip(names, arguments.sources))
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
if __name__ == "__main__":
|
|
157
|
-
try:
|
|
158
|
-
sys.exit(main())
|
|
159
|
-
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
160
|
-
print(f"FAIL statements: {error}")
|
|
161
|
-
sys.exit(1)
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
#!/bin/bash
|
|
2
|
-
# Copyright (c) 2026 Michael Denyer
|
|
3
|
-
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
-
# Shared Lean pin lookup; sourcing this file installs nothing.
|
|
5
|
-
|
|
6
|
-
# Prints the toolchain pin of the Lake project in $1.
|
|
7
|
-
lean_pin() {
|
|
8
|
-
[ -f "$1/lean-toolchain" ] || { echo "FAIL $1 has no lean-toolchain pin"; return 1; }
|
|
9
|
-
command -v elan > /dev/null || { echo "UNAVAILABLE elan is not on PATH; install elan from https://github.com/leanprover/elan"; return 3; }
|
|
10
|
-
tr -d '\r\n' < "$1/lean-toolchain"
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
lean_pin_ready() {
|
|
14
|
-
elan run "$1" lake --version > /dev/null 2>&1
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
# Prints the pin of the Lake project in $1 when it is ready to run, or why not.
|
|
18
|
-
lean_ready_pin() {
|
|
19
|
-
local toolchain status
|
|
20
|
-
toolchain=$(lean_pin "$1") || { status=$?; echo "$toolchain"; return "$status"; }
|
|
21
|
-
lean_pin_ready "$toolchain" \
|
|
22
|
-
|| { echo "UNAVAILABLE $toolchain is not ready; run bash $(dirname "${BASH_SOURCE[0]}")/setup.sh lean $1"; return 3; }
|
|
23
|
-
echo "$toolchain"
|
|
24
|
-
}
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
#!/bin/bash
|
|
2
|
-
# Copyright (c) 2026 Michael Denyer
|
|
3
|
-
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
-
# Shared tool pin and prerequisite checks; nothing here downloads.
|
|
5
|
-
TLA_VERSION=v1.7.4
|
|
6
|
-
TLA_SHA256=936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88
|
|
7
|
-
TLA_RELEASE=https://github.com/tlaplus/tlaplus/releases/tag/$TLA_VERSION
|
|
8
|
-
JAVA=${JAVA:-java}
|
|
9
|
-
TLC_CACHE=${TLC_CACHE:-$HOME/.cache/tla}
|
|
10
|
-
TLC_JAR_SUPPLIED=${TLC_JAR:+yes}
|
|
11
|
-
TLC_JAR=${TLC_JAR:-$TLC_CACHE/tla2tools-$TLA_VERSION.jar}
|
|
12
|
-
|
|
13
|
-
require_tlc_runtime() {
|
|
14
|
-
if ! "$JAVA" -version > /dev/null 2>&1; then
|
|
15
|
-
echo "UNAVAILABLE $JAVA has no runtime; install a JDK and set JAVA to its java binary"
|
|
16
|
-
return 3
|
|
17
|
-
fi
|
|
18
|
-
command -v python3 > /dev/null || { echo "UNAVAILABLE python3 is not on PATH; install Python 3"; return 3; }
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
check_tlc_jar() {
|
|
22
|
-
local jar=$1 got
|
|
23
|
-
[ -f "$jar" ] || { echo "UNAVAILABLE $jar is missing; save tla2tools.jar from $TLA_RELEASE there, or set TLC_JAR"; return 3; }
|
|
24
|
-
if command -v sha256sum > /dev/null; then
|
|
25
|
-
got=$(sha256sum "$jar") || { echo "UNAVAILABLE cannot hash $jar with sha256sum; check its permissions"; return 3; }
|
|
26
|
-
elif command -v shasum > /dev/null; then
|
|
27
|
-
got=$(shasum -a 256 "$jar") || { echo "UNAVAILABLE cannot hash $jar with shasum; check its permissions"; return 3; }
|
|
28
|
-
else
|
|
29
|
-
echo "UNAVAILABLE install sha256sum or shasum to verify TLC"
|
|
30
|
-
return 3
|
|
31
|
-
fi
|
|
32
|
-
got=${got%% *}
|
|
33
|
-
[ "$got" = "$TLA_SHA256" ] || { echo "UNAVAILABLE $jar has sha256 $got, want $TLA_SHA256"; return 3; }
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
# A JAR the user supplies is trusted; the cached one must match the pin.
|
|
37
|
-
tlc_jar_ready() {
|
|
38
|
-
local probe
|
|
39
|
-
if [ -n "$TLC_JAR_SUPPLIED" ]; then
|
|
40
|
-
[ -f "$TLC_JAR" ] || { echo "UNAVAILABLE supplied TLC_JAR $TLC_JAR does not exist"; return 3; }
|
|
41
|
-
else
|
|
42
|
-
check_tlc_jar "$TLC_JAR" || return $?
|
|
43
|
-
fi
|
|
44
|
-
probe=$("$JAVA" -cp "$TLC_JAR" tlc2.TLC -help 2>&1) \
|
|
45
|
-
|| [[ $probe == *"TLC - provides model checking"* ]] \
|
|
46
|
-
|| { echo "UNAVAILABLE tlc2.TLC cannot run from $TLC_JAR; save a working JAR from $TLA_RELEASE or set TLC_JAR"; echo "$probe"; return 3; }
|
|
47
|
-
}
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# Copyright (c) 2026 Michael Denyer
|
|
3
|
-
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
-
"""Reduce the error trace in a TLC log to what each step changed.
|
|
5
|
-
|
|
6
|
-
Reads a TLC log (a file argument or stdin), finds the behaviour TLC prints
|
|
7
|
-
for an invariant violation, a deadlock or a temporal counter-example, and
|
|
8
|
-
prints one block per state: its number and action, then only the variables
|
|
9
|
-
whose value differs from the previous state. The first state prints every
|
|
10
|
-
variable. A "Back to state" line (a liveness lasso) is printed as is.
|
|
11
|
-
Exits 1 when the log holds no trace.
|
|
12
|
-
|
|
13
|
-
Usage: tlc-trace.py [tlc.log]
|
|
14
|
-
"""
|
|
15
|
-
import re
|
|
16
|
-
import sys
|
|
17
|
-
from contextlib import nullcontext
|
|
18
|
-
|
|
19
|
-
START = ("The behavior up to this point is", "constitutes a counter-example")
|
|
20
|
-
STATE = re.compile(r"^State (\d+): <?(.*?)>?$")
|
|
21
|
-
LOCATION = re.compile(r" line \d+, col \d+ to line \d+, col \d+ of module \w+$")
|
|
22
|
-
# TLC omits the leading conjunction when the spec has one variable.
|
|
23
|
-
VAR = re.compile(r"^(?:/\\ )?(\w+) = (.*)$")
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
def states(lines):
|
|
27
|
-
"""Yield (title, {var: value}) per state of the first error trace."""
|
|
28
|
-
lines = (line.rstrip("\n") for line in lines)
|
|
29
|
-
# any() stops on the marker line, so the loop below resumes just after it.
|
|
30
|
-
if not any(marker in line for line in lines for marker in START):
|
|
31
|
-
return
|
|
32
|
-
title, values, var = None, {}, None
|
|
33
|
-
for line in lines:
|
|
34
|
-
if m := STATE.match(line):
|
|
35
|
-
title, values, var = f"state {m[1]}: {LOCATION.sub('', m[2])}", {}, None
|
|
36
|
-
elif line.startswith("Back to state"):
|
|
37
|
-
yield line, {}
|
|
38
|
-
elif title and (m := VAR.match(line)):
|
|
39
|
-
var = m[1]
|
|
40
|
-
values[var] = m[2]
|
|
41
|
-
elif title and var and line.startswith(" "):
|
|
42
|
-
values[var] += "\n" + line
|
|
43
|
-
elif title:
|
|
44
|
-
yield title, values
|
|
45
|
-
title = None
|
|
46
|
-
if title:
|
|
47
|
-
yield title, values
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def main():
|
|
51
|
-
with (open(sys.argv[1], encoding="utf-8") if len(sys.argv) > 1 else nullcontext(sys.stdin)) as src:
|
|
52
|
-
prev, found = {}, False
|
|
53
|
-
for title, values in states(src):
|
|
54
|
-
found = True
|
|
55
|
-
print(f"--- {title}")
|
|
56
|
-
for var, value in values.items():
|
|
57
|
-
if prev.get(var) != value:
|
|
58
|
-
print(f" {var} = {value}")
|
|
59
|
-
prev = values or prev
|
|
60
|
-
sys.exit(0 if found else 1)
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
if __name__ == "__main__":
|
|
64
|
-
main()
|