agent-formal-verify 0.4.8 → 0.4.10
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 +34 -0
- package/package.json +1 -1
- package/skills/formal-verify/SKILL.md +15 -7
- package/skills/formal-verify/examples/kani-template/src/lib.rs +6 -0
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.lean +16 -4
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.mutations +1 -1
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +14 -0
- package/skills/formal-verify/references/lean-brief.md +22 -5
- package/skills/formal-verify/references/rust-brief.md +5 -3
- package/skills/formal-verify/references/setup.md +1 -1
- package/skills/formal-verify/references/tla-brief.md +1 -1
- package/skills/formal-verify/scripts/baseline.py +472 -0
- package/skills/formal-verify/scripts/kani.py +37 -0
- package/skills/formal-verify/scripts/lean-check.sh +88 -9
- package/skills/formal-verify/scripts/lean-mutations.lean +95 -0
- package/skills/formal-verify/scripts/lean-replay.lean +19 -0
- package/skills/formal-verify/scripts/lean-statements.py +61 -39
- package/skills/formal-verify/scripts/lean-tools.sh +9 -0
- package/skills/formal-verify/scripts/mutate.py +259 -158
- package/skills/formal-verify/scripts/tlc-matrix.sh +4 -167
- package/skills/formal-verify/scripts/tlc.py +328 -0
|
@@ -3,8 +3,13 @@
|
|
|
3
3
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
4
|
# Builds a Lean 4 model with Lake, then audits every declaration of every built
|
|
5
5
|
# module. Fails when the build fails, a declaration uses sorry or rests on an
|
|
6
|
-
# axiom beyond propext, Classical.choice and Quot.sound,
|
|
7
|
-
#
|
|
6
|
+
# axiom beyond propext, Classical.choice and Quot.sound, no Lake library owns a
|
|
7
|
+
# .lean file in the project, a theorem named <Property>.witness does not state
|
|
8
|
+
# that the hypotheses of <Property> hold together, or the pin's leanchecker
|
|
9
|
+
# rejects a built module on kernel replay. Otherwise prints the build output,
|
|
10
|
+
# a WITNESS line for each property and PASS. A property without a witness
|
|
11
|
+
# passes, and so does a pin that ships no leanchecker; the PASS line counts the
|
|
12
|
+
# first and reports the replay as unavailable for the second.
|
|
8
13
|
# Named files limit the check to those sources, so agents that share a project
|
|
9
14
|
# can each check their own model; a run without them checks the whole project.
|
|
10
15
|
# Needs a pin of Lean 4.20.0 or later, the first whose Lake builds a module by
|
|
@@ -26,9 +31,7 @@ HERE=$(cd "$(dirname "$0")" && pwd)
|
|
|
26
31
|
dir=$(cd "$dir" && pwd)
|
|
27
32
|
# shellcheck source=skills/formal-verify/scripts/lean-tools.sh
|
|
28
33
|
source "$HERE/lean-tools.sh"
|
|
29
|
-
toolchain=$(
|
|
30
|
-
lean_pin_ready "$toolchain" \
|
|
31
|
-
|| { echo "UNAVAILABLE $toolchain is not ready; run bash $HERE/setup.sh lean $dir"; exit 3; }
|
|
34
|
+
toolchain=$(lean_ready_pin "$dir") || { status=$?; echo "$toolchain"; exit "$status"; }
|
|
32
35
|
|
|
33
36
|
work=$(mktemp -d)
|
|
34
37
|
trap 'rm -rf "$work"' EXIT
|
|
@@ -74,9 +77,13 @@ sorries=$(grep -cE "$sorry" "$log")
|
|
|
74
77
|
audit_status=0
|
|
75
78
|
: > "$work/audit.out"
|
|
76
79
|
if [ "$status" -eq 0 ]; then
|
|
80
|
+
# The module of each source, in source order, for the audit's imports and the frozen records.
|
|
81
|
+
unexpected=$(grep -v '/\.lake/build/lib/lean/.*\.olean$' "$work/oleans")
|
|
82
|
+
[ -z "$unexpected" ] || { echo "FAIL $scope: cannot identify the module of $unexpected"; exit 1; }
|
|
83
|
+
sed -e 's|^.*/\.lake/build/lib/lean/||' -e 's|\.olean$||' -e 's|/|.|g' "$work/oleans" > "$work/modules"
|
|
77
84
|
{
|
|
78
85
|
echo "import Lean"
|
|
79
|
-
sed
|
|
86
|
+
sed 's|^|import |' "$work/modules"
|
|
80
87
|
cat << 'EOF'
|
|
81
88
|
open Lean in
|
|
82
89
|
private def hasTheoremParent (env : Environment) : Name → Bool
|
|
@@ -84,14 +91,43 @@ private def hasTheoremParent (env : Environment) : Name → Bool
|
|
|
84
91
|
| .str parent _ | .num parent _ =>
|
|
85
92
|
(match env.find? parent with | some (.thmInfo _) => true | _ => false) || hasTheoremParent env parent
|
|
86
93
|
|
|
94
|
+
private def oneLine (s : String) : String :=
|
|
95
|
+
(s.foldl (fun (acc, gap) c =>
|
|
96
|
+
if c.isWhitespace then (acc, true) else ((if gap then acc.push ' ' else acc).push c, false)) ("", false)).1
|
|
97
|
+
|
|
98
|
+
open Lean Meta in
|
|
99
|
+
private def witnessLine (property : ConstantInfo) (witness? : Option ConstantInfo) : MetaM String :=
|
|
100
|
+
forallTelescope property.type fun xs _ => do
|
|
101
|
+
let name := property.name
|
|
102
|
+
let binders ← xs.mapM fun x => return (x, ← inferType x)
|
|
103
|
+
let hyps ← binders.filterM fun (_, type) => isProp type
|
|
104
|
+
if hyps.isEmpty then return s!"WITNESS no-hypotheses {name}"
|
|
105
|
+
let proofs := hyps.map (·.1.fvarId!)
|
|
106
|
+
for (x, type) in binders do
|
|
107
|
+
if type.hasAnyFVar proofs.contains then
|
|
108
|
+
return s!"WITNESS unavailable {name}: the type of {← ppExpr x} uses the proof of a hypothesis"
|
|
109
|
+
let vars := binders.filter fun (x, _) => !proofs.contains x.fvarId!
|
|
110
|
+
let all := hyps.pop.foldr (fun (_, hyp) rest => mkAnd hyp rest) hyps.back!.2
|
|
111
|
+
-- Explicit binders printed with their types let the statement be copied into the model.
|
|
112
|
+
let expected ← vars.foldrM (fun (x, type) body => do
|
|
113
|
+
mkAppM ``Exists #[.lam (← x.fvarId!.getUserName) type (body.abstract #[x]) .default]) all
|
|
114
|
+
let shown := oneLine (← withOptions (·.setBool `pp.funBinderTypes true) (ppExpr expected)).pretty
|
|
115
|
+
let some witness := witness? | return s!"WITNESS absent {name}: no theorem {name}.witness states {shown}"
|
|
116
|
+
let levels ← mkFreshLevelMVars property.levelParams.length
|
|
117
|
+
if ← isDefEq witness.type (expected.instantiateLevelParams property.levelParams levels) then
|
|
118
|
+
return s!"WITNESS checked {name}"
|
|
119
|
+
return s!"WITNESS failed {name}: {name}.witness must state {shown}"
|
|
120
|
+
|
|
87
121
|
open Lean Elab Command in
|
|
88
122
|
#eval show CommandElabM Unit from do
|
|
89
123
|
let env ← getEnv
|
|
90
124
|
let freezing := (← IO.getEnv "AFV_FREEZE") == some "1"
|
|
91
125
|
let modules := (env.imports.map (·.module)).erase `Lean
|
|
126
|
+
for module in env.header.moduleNames do IO.println s!"IMPORTED {module.toString (escape := false)}"
|
|
92
127
|
let standard : Array Name := #[``propext, ``Classical.choice, ``Quot.sound]
|
|
93
128
|
let names := env.constants.fold (fun acc name info => if info matches .axiomInfo _ then acc else acc.push name) #[]
|
|
94
129
|
let mut audited := 0
|
|
130
|
+
let mut theorems : Array (Name × Name × ModuleIdx) := #[]
|
|
95
131
|
for name in names do
|
|
96
132
|
let some idx := env.getModuleIdxFor? name | continue
|
|
97
133
|
unless modules.contains env.header.moduleNames[idx.toNat]! do continue
|
|
@@ -122,6 +158,19 @@ open Lean Elab Command in
|
|
|
122
158
|
("typeExpr", toJson (reprStr (info.levelParams, info.type))),
|
|
123
159
|
("valueExpr", value), ("type", toJson pp.pretty)]
|
|
124
160
|
IO.println s!"STATEMENT {record.compress}"
|
|
161
|
+
if info matches .thmInfo _ then theorems := theorems.push (name, userName, idx)
|
|
162
|
+
for (name, userName, idx) in theorems.qsort (·.1.toString < ·.1.toString) do
|
|
163
|
+
let pairedWitness := match userName with
|
|
164
|
+
| .str parent "witness" => theorems.any fun (_, user, owner) => owner == idx && user == parent
|
|
165
|
+
| _ => false
|
|
166
|
+
if name != userName || pairedWitness then continue
|
|
167
|
+
if env.isProjectionFn name || Meta.isInstanceCore env name then continue
|
|
168
|
+
if (← findDeclarationRanges? name).isNone then continue
|
|
169
|
+
let witness? := theorems.find? fun (_, user, owner) => owner == idx && user == userName ++ `witness
|
|
170
|
+
let line ← liftTermElabM <| tryCatchRuntimeEx
|
|
171
|
+
(witnessLine (env.find? name).get! (witness?.bind (env.find? ·.1)))
|
|
172
|
+
fun error => return s!"WITNESS unavailable {name}: {oneLine (← error.toMessageData.toString)}"
|
|
173
|
+
IO.println line
|
|
125
174
|
IO.println s!"AUDITED {audited} declarations"
|
|
126
175
|
EOF
|
|
127
176
|
} > "$work/Audit.lean"
|
|
@@ -149,7 +198,7 @@ if [ "$status" -ne 0 ] || { [ "$freeze" -eq 0 ] && [ "$sorries" -ne 0 ]; } || [
|
|
|
149
198
|
|| echo "$toolchain cannot build a module by its source path; pin Lean 4.20.0 or later"
|
|
150
199
|
if [ "$audit_status" -ne 0 ]; then
|
|
151
200
|
echo "the axiom audit did not run or found no declarations:"
|
|
152
|
-
grep -v '^[[:space:]]*$' "$work/audit.out" | tail -40
|
|
201
|
+
grep -v -e '^[[:space:]]*$' -e '^IMPORTED ' "$work/audit.out" | tail -40
|
|
153
202
|
! grep -q 'environment already contains' "$work/audit.out" \
|
|
154
203
|
|| echo "two modules declare the same name; put each model in a namespace of its own"
|
|
155
204
|
fi
|
|
@@ -157,7 +206,7 @@ if [ "$status" -ne 0 ] || { [ "$freeze" -eq 0 ] && [ "$sorries" -ne 0 ]; } || [
|
|
|
157
206
|
fi
|
|
158
207
|
mode=check
|
|
159
208
|
[ "$freeze" -eq 0 ] || mode=freeze
|
|
160
|
-
python3 "$HERE/lean-statements.py" "$mode" "$toolchain" "$work/audit.out" "$work/
|
|
209
|
+
python3 "$HERE/lean-statements.py" "$mode" "$toolchain" "$work/audit.out" "$work/modules" "${sources[@]}" > "$work/statements.out"
|
|
161
210
|
statement_status=$?
|
|
162
211
|
if [ "$statement_status" -ne 0 ]; then
|
|
163
212
|
echo "FAIL $scope: frozen statements differ or could not be checked"
|
|
@@ -168,4 +217,34 @@ cat "$work/statements.out"
|
|
|
168
217
|
# #eval output arrives as info blocks that can span lines.
|
|
169
218
|
grep -v '^[[:space:]]*$' "$log"
|
|
170
219
|
[ "$freeze" -eq 0 ] || exit 0
|
|
171
|
-
|
|
220
|
+
|
|
221
|
+
witnesses() { grep -c "^WITNESS $1 " "$work/audit.out"; }
|
|
222
|
+
failed=$(witnesses failed)
|
|
223
|
+
[ "$failed" -eq 0 ] || echo "FAIL $scope: $failed witnesses do not state their property's hypotheses"
|
|
224
|
+
grep '^WITNESS ' "$work/audit.out"
|
|
225
|
+
[ "$failed" -eq 0 ] || exit 1
|
|
226
|
+
|
|
227
|
+
# The build trusts a declaration that a command adds to the environment without
|
|
228
|
+
# a kernel check. leanchecker replays every declaration of the built modules
|
|
229
|
+
# through the kernel and rejects it. Use its exact-module replayer rather than
|
|
230
|
+
# its CLI's prefix search, which also finds deleted sources' cached objects.
|
|
231
|
+
# A named module rests on the project modules it imports, so replay those too.
|
|
232
|
+
replay=unavailable
|
|
233
|
+
if [ -x "$(elan run "$toolchain" lean --print-prefix)/bin/leanchecker" ]; then
|
|
234
|
+
cp "$work/modules" "$work/replay-modules"
|
|
235
|
+
while IFS= read -r module; do
|
|
236
|
+
[ ! -f "$dir/.lake/build/lib/lean/${module//.//}.olean" ] || printf '%s\n' "$module" >> "$work/replay-modules"
|
|
237
|
+
done < <(sed -n 's/^IMPORTED //p' "$work/audit.out")
|
|
238
|
+
sort -u "$work/replay-modules" -o "$work/replay-modules"
|
|
239
|
+
replay=passed
|
|
240
|
+
AFV_REPLAY_MODULES="$work/replay-modules" elan run "$toolchain" lake --dir "$dir" env lean "$HERE/lean-replay.lean" > "$work/replay.out" 2>&1 || replay=failed
|
|
241
|
+
fi
|
|
242
|
+
case $replay in
|
|
243
|
+
passed) echo "REPLAYED $(grep -c '^replaying ' "$work/replay.out") modules through the Lean kernel" ;;
|
|
244
|
+
failed)
|
|
245
|
+
echo "FAIL $scope: kernel replay rejected a built module"
|
|
246
|
+
cat "$work/replay.out"
|
|
247
|
+
exit 1 ;;
|
|
248
|
+
unavailable) echo "UNAVAILABLE kernel replay: $toolchain ships no leanchecker" ;;
|
|
249
|
+
esac
|
|
250
|
+
echo "PASS $scope: $(grep '^AUDITED ' "$work/audit.out" | cut -d' ' -f2) declarations checked, no unfinished proof (sorry), no added axiom, kernel replay $replay, $(witnesses checked) witnesses checked, $(witnesses absent) absent, $(witnesses unavailable) unavailable, $(witnesses no-hypotheses) properties without hypotheses"
|
|
@@ -0,0 +1,95 @@
|
|
|
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
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
-- Copyright (c) 2026 Michael Denyer
|
|
2
|
+
-- SPDX-License-Identifier: GPL-3.0-only
|
|
3
|
+
-- Replay exact modules with the pin's checker, without its CLI's prefix search.
|
|
4
|
+
import LeanChecker
|
|
5
|
+
|
|
6
|
+
open Lean
|
|
7
|
+
|
|
8
|
+
unsafe def replayModules : IO Unit := do
|
|
9
|
+
initSearchPath (← findSysroot)
|
|
10
|
+
let some path ← IO.getEnv "AFV_REPLAY_MODULES"
|
|
11
|
+
| throw <| IO.userError "AFV_REPLAY_MODULES must name a module list"
|
|
12
|
+
for module in (← IO.FS.lines path) do
|
|
13
|
+
IO.println s!"replaying {module}"
|
|
14
|
+
try replayFromImports module.toName
|
|
15
|
+
catch error =>
|
|
16
|
+
IO.eprintln s!"leanchecker found a problem in {module}"
|
|
17
|
+
throw error
|
|
18
|
+
|
|
19
|
+
#eval replayModules
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
4
|
"""Store or check declaration fingerprints emitted by the Lean audit."""
|
|
5
5
|
|
|
6
|
+
import argparse
|
|
6
7
|
import hashlib
|
|
7
8
|
import json
|
|
8
9
|
import sys
|
|
@@ -28,6 +29,16 @@ def declarations(audit):
|
|
|
28
29
|
return modules
|
|
29
30
|
|
|
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
|
+
|
|
31
42
|
def read_record(path):
|
|
32
43
|
record = json.loads(path.read_text(encoding="utf-8"))
|
|
33
44
|
if not isinstance(record, dict) or record.get("format") != 1:
|
|
@@ -62,36 +73,38 @@ def check_orphans(project):
|
|
|
62
73
|
return int(failed)
|
|
63
74
|
|
|
64
75
|
|
|
65
|
-
def
|
|
66
|
-
|
|
67
|
-
return check_orphans(Path(sys.argv[2]))
|
|
68
|
-
mode, toolchain, audit, oleans, *sources = sys.argv[1:]
|
|
69
|
-
modules = declarations(Path(audit))
|
|
70
|
-
paths = Path(oleans).read_text(encoding="utf-8").splitlines()
|
|
71
|
-
if len(paths) != len(sources):
|
|
72
|
-
raise ValueError("Lake did not return one module per source")
|
|
76
|
+
def freeze(toolchain, modules, sources):
|
|
77
|
+
"""Record every source's statements, writing none unless all of them can be recorded."""
|
|
73
78
|
pending = []
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
if mode != "freeze" and not path.exists():
|
|
78
|
-
continue
|
|
79
|
-
marker = "/.lake/build/lib/lean/"
|
|
80
|
-
if marker not in olean or not olean.endswith(".olean"):
|
|
81
|
-
raise ValueError(f"cannot identify module from {olean}")
|
|
82
|
-
module = olean.rsplit(marker, 1)[1].removesuffix(".olean").replace("/", ".")
|
|
83
|
-
current = {}
|
|
84
|
-
for record in modules.get(module, []):
|
|
85
|
-
if record["name"] in current:
|
|
86
|
-
raise ValueError(f"ambiguous declaration identity {record['name']} in {module}")
|
|
87
|
-
current[record["name"]] = record
|
|
88
|
-
if mode == "freeze" and not current:
|
|
79
|
+
for module, source in sources:
|
|
80
|
+
records = records_by_name(modules, module)
|
|
81
|
+
if not records:
|
|
89
82
|
raise ValueError(f"no declaration records for {source}")
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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():
|
|
94
106
|
continue
|
|
107
|
+
records = records_by_name(modules, module)
|
|
95
108
|
frozen = read_record(path)
|
|
96
109
|
if frozen["toolchain"] != toolchain:
|
|
97
110
|
print(f"FROZEN {path}: toolchain changed from {frozen['toolchain']} to {toolchain}; review and run --freeze")
|
|
@@ -101,7 +114,7 @@ def main():
|
|
|
101
114
|
raise ValueError(f"{path}: expected module {module}, found {frozen['module']}")
|
|
102
115
|
changed = 0
|
|
103
116
|
for old in frozen["declarations"]:
|
|
104
|
-
new =
|
|
117
|
+
new = records.get(old["name"])
|
|
105
118
|
if new is not None and all(old[key] == new[key] for key in ("kind", "typeHash", "valueHash")):
|
|
106
119
|
continue
|
|
107
120
|
changed += 1
|
|
@@ -113,20 +126,29 @@ def main():
|
|
|
113
126
|
if changed == len(frozen["declarations"]):
|
|
114
127
|
print(f"FROZEN {path}: every recorded declaration changed; review the model and toolchain before --freeze")
|
|
115
128
|
failed |= changed > 0
|
|
116
|
-
for path, contents in pending:
|
|
117
|
-
temporary = None
|
|
118
|
-
try:
|
|
119
|
-
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as stream:
|
|
120
|
-
temporary = Path(stream.name)
|
|
121
|
-
stream.write(contents)
|
|
122
|
-
temporary.replace(path)
|
|
123
|
-
finally:
|
|
124
|
-
if temporary is not None:
|
|
125
|
-
temporary.unlink(missing_ok=True)
|
|
126
|
-
print(f"FROZEN {path}: statements recorded; proofs not checked")
|
|
127
129
|
return int(failed)
|
|
128
130
|
|
|
129
131
|
|
|
132
|
+
def main():
|
|
133
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
134
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
135
|
+
commands.add_parser("orphans", help="report records whose source file is gone").add_argument("project", type=Path)
|
|
136
|
+
for name, purpose in (("freeze", "record each source's statements"), ("check", "compare each recorded source's statements")):
|
|
137
|
+
command = commands.add_parser(name, help=purpose)
|
|
138
|
+
command.add_argument("toolchain")
|
|
139
|
+
command.add_argument("audit", type=Path, help="the audit's output, with its STATEMENT lines")
|
|
140
|
+
command.add_argument("module_names", type=Path, help="the module of each source, one per line in source order")
|
|
141
|
+
command.add_argument("sources", nargs="+", type=Path)
|
|
142
|
+
arguments = parser.parse_args()
|
|
143
|
+
if arguments.command == "orphans":
|
|
144
|
+
return check_orphans(arguments.project)
|
|
145
|
+
names = arguments.module_names.read_text(encoding="utf-8").splitlines()
|
|
146
|
+
if len(names) != len(arguments.sources):
|
|
147
|
+
raise ValueError("Lake did not return one module per source")
|
|
148
|
+
action = freeze if arguments.command == "freeze" else check
|
|
149
|
+
return action(arguments.toolchain, declarations(arguments.audit), zip(names, arguments.sources))
|
|
150
|
+
|
|
151
|
+
|
|
130
152
|
if __name__ == "__main__":
|
|
131
153
|
try:
|
|
132
154
|
sys.exit(main())
|
|
@@ -13,3 +13,12 @@ lean_pin() {
|
|
|
13
13
|
lean_pin_ready() {
|
|
14
14
|
elan run "$1" lake --version > /dev/null 2>&1
|
|
15
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
|
+
}
|