agent-formal-verify 0.4.11 → 0.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGES.md +140 -0
- package/README.md +5 -3
- package/package.json +2 -1
- package/skills/formal-verify/SKILL.md +11 -13
- package/skills/formal-verify/examples/kani-template/src/lib.rs +5 -6
- package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +10 -45
- package/skills/formal-verify/examples/tla-template/BoundedQueue.matrix +16 -13
- package/skills/formal-verify/examples/tla-template/BoundedQueue.mutations +92 -14
- package/skills/formal-verify/examples/tla-template/BoundedQueue.tla +169 -28
- package/skills/formal-verify/references/evidence.md +1 -1
- package/skills/formal-verify/references/helpers.md +5 -4
- package/skills/formal-verify/references/lean-brief.md +2 -2
- package/skills/formal-verify/references/rust-brief.md +59 -7
- package/skills/formal-verify/references/setup.md +24 -8
- package/skills/formal-verify/references/tla-brief.md +2 -2
- package/skills/formal-verify/scripts/baseline.py +564 -66
- package/skills/formal-verify/scripts/kani-check.sh +3 -1
- package/skills/formal-verify/scripts/kani.py +130 -54
- package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
- package/skills/formal-verify/scripts/lean-check.sh +6 -243
- package/skills/formal-verify/scripts/lean.py +484 -0
- package/skills/formal-verify/scripts/lean_mutations.py +195 -0
- package/skills/formal-verify/scripts/lean_records.py +25 -0
- package/skills/formal-verify/scripts/mutate.py +81 -195
- package/skills/formal-verify/scripts/processes.py +266 -0
- package/skills/formal-verify/scripts/python-tools.sh +15 -0
- package/skills/formal-verify/scripts/runner.py +56 -0
- package/skills/formal-verify/scripts/setup.sh +18 -19
- package/skills/formal-verify/scripts/storage.py +207 -0
- package/skills/formal-verify/scripts/sync.py +401 -0
- package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
- package/skills/formal-verify/scripts/tlc.py +423 -116
- package/skills/formal-verify/scripts/{tlc-trace.py → tlc_trace.py} +16 -10
- package/skills/setup/SKILL.md +1 -1
- package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
- package/skills/formal-verify/scripts/lean-statements.py +0 -161
- package/skills/formal-verify/scripts/lean-tools.sh +0 -24
- package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
-- Copyright (c) 2026 Michael Denyer
|
|
2
|
+
-- SPDX-License-Identifier: GPL-3.0-only
|
|
3
|
+
-- Read Lean's own record of a model, through the target project's pinned Lake environment.
|
|
4
|
+
-- audit [--freeze] <module-list> import the built modules and print a record of each declaration
|
|
5
|
+
-- (STATEMENT), any added axiom (AXIOMS), each property's witness
|
|
6
|
+
-- check (WITNESS) and the count (AUDITED), for lean-check.sh
|
|
7
|
+
-- analyze <source.lean> elaborate one source without building it and print its declarations,
|
|
8
|
+
-- checks and errors as one AFV_LEAN JSON line, for the mutation runner
|
|
9
|
+
-- Both describe a statement in the same position-free form, so a frozen record and a mutation agree on
|
|
10
|
+
-- whether a statement changed.
|
|
11
|
+
import Lean
|
|
12
|
+
|
|
13
|
+
open Lean in
|
|
14
|
+
private def hasTheoremParent (env : Environment) : Name → Bool
|
|
15
|
+
| .anonymous => false
|
|
16
|
+
| .str parent _ | .num parent _ =>
|
|
17
|
+
(match env.find? parent with | some (.thmInfo _) => true | _ => false) || hasTheoremParent env parent
|
|
18
|
+
|
|
19
|
+
private def body? : Lean.ConstantInfo → Option Lean.Expr
|
|
20
|
+
| .defnInfo v => some v.value
|
|
21
|
+
| .opaqueInfo v => some v.value
|
|
22
|
+
| _ => none
|
|
23
|
+
|
|
24
|
+
-- Lean 4.20 numbers hygienic names (binders, universe parameters, the helpers that deriving
|
|
25
|
+
-- adds) and abstracted proofs across the whole module, so each type and value is recorded
|
|
26
|
+
-- without those numbers: adding a declaration above it must not change it.
|
|
27
|
+
private def unhygienic (n : Lean.Name) : Lean.Name :=
|
|
28
|
+
if n.hasMacroScopes then .anonymous else n
|
|
29
|
+
|
|
30
|
+
-- A name keeps its macro scopes in a prefix when Lean adds a suffix to a hygienic name, as in a helper's match_1.
|
|
31
|
+
private def erased (n : Lean.Name) : Lean.Name :=
|
|
32
|
+
if n.hasMacroScopes then n.eraseMacroScopes else match n with
|
|
33
|
+
| .str p s => .str (erased p) s
|
|
34
|
+
| .num p i => .num (erased p) i
|
|
35
|
+
| n => n
|
|
36
|
+
|
|
37
|
+
private def levelFree : Lean.Level → Lean.Level
|
|
38
|
+
| .succ l => .succ (levelFree l)
|
|
39
|
+
| .max a b => .max (levelFree a) (levelFree b)
|
|
40
|
+
| .imax a b => .imax (levelFree a) (levelFree b)
|
|
41
|
+
| .param n => .param n.eraseMacroScopes
|
|
42
|
+
| l => l
|
|
43
|
+
|
|
44
|
+
-- Lean shares one match helper among the matches of the same shape in a module, so a declaration added
|
|
45
|
+
-- above can change which helper a match uses, and the splitter that the split tactic uses with it. A record
|
|
46
|
+
-- names every helper alike, and each declaration Lean derives from a helper by its suffix, and carries
|
|
47
|
+
-- their content.
|
|
48
|
+
private def shown (env : Lean.Environment) (n : Lean.Name) : Lean.Name :=
|
|
49
|
+
if Lean.Meta.isMatcherCore env n then `_match else match n with
|
|
50
|
+
| .str p s => if Lean.Meta.isMatcherCore env ((Lean.privateToUserName? p).getD p) then .str `_match s else erased n
|
|
51
|
+
| _ => erased n
|
|
52
|
+
|
|
53
|
+
private def abstractedProof : Lean.Name → Bool
|
|
54
|
+
| .str _ s => s.startsWith "_proof_" && s.length > 7 && (s.drop 7).all Char.isDigit
|
|
55
|
+
| _ => false
|
|
56
|
+
|
|
57
|
+
-- A shared match helper takes its binder names from whichever match Lean made it for, and Lean 4.20 passes
|
|
58
|
+
-- them on to the alternatives of a match that uses it, so neither records binder names.
|
|
59
|
+
private partial def nameless : Lean.Expr → Lean.Expr
|
|
60
|
+
| .lam _ t b i => .lam .anonymous (nameless t) (nameless b) i
|
|
61
|
+
| .forallE _ t b i => .forallE .anonymous (nameless t) (nameless b) i
|
|
62
|
+
| .letE _ t v b d => .letE .anonymous (nameless t) (nameless v) (nameless b) d
|
|
63
|
+
| .app f a => .app (nameless f) (nameless a)
|
|
64
|
+
| .mdata m e => .mdata m (nameless e)
|
|
65
|
+
| .proj s i e => .proj s i (nameless e)
|
|
66
|
+
| e => e
|
|
67
|
+
|
|
68
|
+
private partial def positionFree (env : Lean.Environment) : Lean.Expr → Lean.Expr
|
|
69
|
+
| .lam n t b i => .lam (unhygienic n) (positionFree env t) (positionFree env b) i
|
|
70
|
+
| .forallE n t b i => .forallE (unhygienic n) (positionFree env t) (positionFree env b) i
|
|
71
|
+
| .letE n t v b d => .letE (unhygienic n) (positionFree env t) (positionFree env v) (positionFree env b) d
|
|
72
|
+
| e@(.app f a) => match e.getAppFn with
|
|
73
|
+
| head@(.const n _) =>
|
|
74
|
+
if (shown env n).getRoot == `_match then
|
|
75
|
+
Lean.mkAppN (positionFree env head) (e.getAppArgs.map (positionFree env ∘ nameless))
|
|
76
|
+
else .app (positionFree env f) (positionFree env a)
|
|
77
|
+
| _ => .app (positionFree env f) (positionFree env a)
|
|
78
|
+
| .mdata m e => .mdata m (positionFree env e)
|
|
79
|
+
| .proj s i e => .proj s i (positionFree env e)
|
|
80
|
+
| .sort l => .sort (levelFree l)
|
|
81
|
+
| .const n ls => if abstractedProof (erased n) then .const `_proof [] else .const (shown env n) (ls.map levelFree)
|
|
82
|
+
| e => e
|
|
83
|
+
|
|
84
|
+
-- A recursive body can sit in an auxiliary: _f for structural recursion, _unary or _mutual
|
|
85
|
+
-- for well-founded recursion, and _unsafe_rec for the code that runs, the only body a partial def has.
|
|
86
|
+
-- Lean appends the suffix after a hygienic name's macro scopes, where ++ would put it before them.
|
|
87
|
+
private def auxBodies (env : Lean.Environment) (name : Lean.Name) : List (String × Lean.Expr) :=
|
|
88
|
+
["_f", "_unary", "_mutual", "_unsafe_rec"].filterMap fun aux => ((env.find? (.str name aux)).bind body?).map (aux, ·)
|
|
89
|
+
|
|
90
|
+
-- The constants an expression uses that keep selects, one per use, in the order they occur.
|
|
91
|
+
private partial def usesOf (keep : Lean.Name → Bool) : Lean.Expr → Array Lean.Name
|
|
92
|
+
| .const n _ => if keep n then #[n] else #[]
|
|
93
|
+
| .app f a => usesOf keep f ++ usesOf keep a
|
|
94
|
+
| .lam _ t b _ | .forallE _ t b _ => usesOf keep t ++ usesOf keep b
|
|
95
|
+
| .letE _ t v b _ => usesOf keep t ++ usesOf keep v ++ usesOf keep b
|
|
96
|
+
| .mdata _ e | .proj _ _ e => usesOf keep e
|
|
97
|
+
| _ => #[]
|
|
98
|
+
|
|
99
|
+
-- What a record shows of a constant with no record of its own: its type, its value and its auxiliaries' bodies.
|
|
100
|
+
private def parts (env : Lean.Environment) (n : Lean.Name) (info : Lean.ConstantInfo) : List Lean.Expr :=
|
|
101
|
+
info.type :: (body? info).toList ++ (auxBodies env n).map (·.2)
|
|
102
|
+
|
|
103
|
+
private def content (env : Lean.Environment) (n : Lean.Name) : String :=
|
|
104
|
+
match env.find? n with
|
|
105
|
+
| some info =>
|
|
106
|
+
let shape := if (shown env n).getRoot == `_match then nameless else id
|
|
107
|
+
reprStr ((parts env n info).map (positionFree env ∘ shape))
|
|
108
|
+
| none => ""
|
|
109
|
+
|
|
110
|
+
-- A record names every match helper alike and lists each helper's content once, so it adds the content of the
|
|
111
|
+
-- helper at each use, in order: two expressions that use the same helpers at different places then differ,
|
|
112
|
+
-- while a helper renamed differs not. Expressions that use no match helper get nothing added.
|
|
113
|
+
private def atUses (env : Lean.Environment) (exprs : List Lean.Expr) : String :=
|
|
114
|
+
let uses := exprs.foldl (fun acc e => acc ++ usesOf (fun n => (shown env n).getRoot == `_match) e) #[]
|
|
115
|
+
if uses.isEmpty then "" else reprStr (uses.toList.map (content env))
|
|
116
|
+
|
|
117
|
+
private partial def levelUses : Lean.Level → Array Lean.Name
|
|
118
|
+
| .succ l => levelUses l
|
|
119
|
+
| .max a b | .imax a b => levelUses a ++ levelUses b
|
|
120
|
+
| .param n => #[n]
|
|
121
|
+
| _ => #[]
|
|
122
|
+
|
|
123
|
+
private partial def paramUses : Lean.Expr → Array Lean.Name
|
|
124
|
+
| .sort l => levelUses l
|
|
125
|
+
| .const _ ls => ls.foldl (· ++ levelUses ·) #[]
|
|
126
|
+
| .app f a => paramUses f ++ paramUses a
|
|
127
|
+
| .lam _ t b _ | .forallE _ t b _ => paramUses t ++ paramUses b
|
|
128
|
+
| .letE _ t v b _ => paramUses t ++ paramUses v ++ paramUses b
|
|
129
|
+
| .mdata _ e | .proj _ _ e => paramUses e
|
|
130
|
+
| _ => #[]
|
|
131
|
+
|
|
132
|
+
-- Two universe parameters look alike in a record when their names differ only in macro scopes, as a macro-made
|
|
133
|
+
-- `u` and the user's own `u` do. When a declaration has two such parameters, its record adds which one sits at
|
|
134
|
+
-- each use in the expressions it shows, in order, by its place in the declaration's parameter list.
|
|
135
|
+
-- A declaration whose parameters all look different gets nothing added.
|
|
136
|
+
private def levelsAlike (levels : List Lean.Name) (exprs : List Lean.Expr) : String :=
|
|
137
|
+
let alike := levels.filter fun l => (levels.filter (·.eraseMacroScopes == l.eraseMacroScopes)).length > 1
|
|
138
|
+
if alike.isEmpty then "" else
|
|
139
|
+
let uses := exprs.foldl (fun acc e => acc ++ (paramUses e).filter alike.contains) #[]
|
|
140
|
+
s!"\nlevels alike: {reprStr (uses.toList.map fun n => (levels.findIdx? (· == n)).getD 0)}"
|
|
141
|
+
|
|
142
|
+
-- A hygienic constant or a match helper has no record of its own, so a record that refers to one carries its
|
|
143
|
+
-- type and value, and those of the hygienic constants and helpers they refer to in turn, each once.
|
|
144
|
+
-- Proofs stay out, as in every record.
|
|
145
|
+
-- Two constants look alike in a record when their names differ only in macro scopes, as two macro-made `a`s do,
|
|
146
|
+
-- or a macro-made `a` and the user's own. When the expressions a record shows use two such constants, it adds
|
|
147
|
+
-- which one sits at each use, in order: its place among the constants the record carries, or the name of one with
|
|
148
|
+
-- a record of its own.
|
|
149
|
+
-- A record that uses no two constants alike gets nothing added.
|
|
150
|
+
open Lean in
|
|
151
|
+
private def followed (env : Environment) (roots : List Expr) : String := Id.run do
|
|
152
|
+
let unrecorded (e : Expr) := e.getUsedConstants.filter fun c => shown env c != c && !abstractedProof (erased c)
|
|
153
|
+
let named (c : Name) := (shown env c).getRoot != `_match && !abstractedProof (erased c)
|
|
154
|
+
let mut queue := roots.foldl (fun acc e => acc ++ unrecorded e) #[]
|
|
155
|
+
let mut uses := roots.foldl (fun acc e => acc ++ usesOf named e) #[]
|
|
156
|
+
let mut seen : Array Name := #[]
|
|
157
|
+
let mut out := atUses env roots
|
|
158
|
+
let mut i := 0
|
|
159
|
+
while i < queue.size do
|
|
160
|
+
let n := queue[i]!
|
|
161
|
+
i := i + 1
|
|
162
|
+
if seen.contains n then continue
|
|
163
|
+
seen := seen.push n
|
|
164
|
+
let some info := env.find? n | continue
|
|
165
|
+
out := out ++ s!"\n{shown env n}: {content env n}" ++ atUses env (parts env n info)
|
|
166
|
+
++ levelsAlike info.levelParams (parts env n info)
|
|
167
|
+
for e in parts env n info do
|
|
168
|
+
queue := queue ++ unrecorded e
|
|
169
|
+
uses := uses ++ usesOf named e
|
|
170
|
+
let distinct := uses.foldl (fun acc c => if acc.contains c then acc else acc.push c) #[]
|
|
171
|
+
let alike := distinct.filter fun c => distinct.any fun d => d != c && shown env d == shown env c
|
|
172
|
+
if alike.isEmpty then return out
|
|
173
|
+
let which (c : Name) := match seen.findIdx? (· == c) with
|
|
174
|
+
| some k => toString k
|
|
175
|
+
| none => c.toString
|
|
176
|
+
return out ++ s!"\nalike: {reprStr ((uses.filter alike.contains).toList.map which)}"
|
|
177
|
+
|
|
178
|
+
-- A statement's identity when the mutation runner compares an original theorem, example or #guard with its
|
|
179
|
+
-- mutated copy: the frozen record's form of its type, without binder names, which change no statement.
|
|
180
|
+
private def statementKey (env : Lean.Environment) (levels : List Lean.Name) (type : Lean.Expr) : String :=
|
|
181
|
+
reprStr (levels.map (·.eraseMacroScopes), nameless (positionFree env type)) ++ followed env [type] ++ levelsAlike levels [type]
|
|
182
|
+
|
|
183
|
+
private def oneLine (s : String) : String :=
|
|
184
|
+
(s.foldl (fun (acc, gap) c =>
|
|
185
|
+
if c.isWhitespace then (acc, true) else ((if gap then acc.push ' ' else acc).push c, false)) ("", false)).1
|
|
186
|
+
|
|
187
|
+
open Lean Meta in
|
|
188
|
+
private def witnessLine (property : ConstantInfo) (witness? : Option ConstantInfo) : MetaM String :=
|
|
189
|
+
forallTelescope property.type fun xs _ => do
|
|
190
|
+
let name := property.name
|
|
191
|
+
let binders ← xs.mapM fun x => return (x, ← inferType x)
|
|
192
|
+
let hyps ← binders.filterM fun (_, type) => isProp type
|
|
193
|
+
if hyps.isEmpty then return s!"WITNESS no-hypotheses {name}"
|
|
194
|
+
let proofs := hyps.map (·.1.fvarId!)
|
|
195
|
+
for (x, type) in binders do
|
|
196
|
+
if type.hasAnyFVar proofs.contains then
|
|
197
|
+
return s!"WITNESS unavailable {name}: the type of {← ppExpr x} uses the proof of a hypothesis"
|
|
198
|
+
let vars := binders.filter fun (x, _) => !proofs.contains x.fvarId!
|
|
199
|
+
let all := hyps.pop.foldr (fun (_, hyp) rest => mkAnd hyp rest) hyps.back!.2
|
|
200
|
+
-- Explicit binders printed with their types let the statement be copied into the model.
|
|
201
|
+
let expected ← vars.foldrM (fun (x, type) body => do
|
|
202
|
+
mkAppM ``Exists #[.lam (← x.fvarId!.getUserName) type (body.abstract #[x]) .default]) all
|
|
203
|
+
let shown := oneLine (← withOptions (·.setBool `pp.funBinderTypes true) (ppExpr expected)).pretty
|
|
204
|
+
let some witness := witness? | return s!"WITNESS absent {name}: no theorem {name}.witness states {shown}"
|
|
205
|
+
let levels ← mkFreshLevelMVars property.levelParams.length
|
|
206
|
+
if ← isDefEq witness.type (expected.instantiateLevelParams property.levelParams levels) then
|
|
207
|
+
return s!"WITNESS checked {name}"
|
|
208
|
+
return s!"WITNESS failed {name}: {name}.witness must state {shown}"
|
|
209
|
+
|
|
210
|
+
open Lean Elab Command in
|
|
211
|
+
private def audit (freezing : Bool) : CommandElabM Unit := do
|
|
212
|
+
let env ← getEnv
|
|
213
|
+
let modules := (env.imports.map (·.module)).erase `Lean
|
|
214
|
+
for module in env.header.moduleNames do IO.println s!"IMPORTED {module.toString (escape := false)}"
|
|
215
|
+
let standard : Array Name := #[``propext, ``Classical.choice, ``Quot.sound]
|
|
216
|
+
let names := env.constants.fold (fun acc name info => if info matches .axiomInfo _ then acc else acc.push name) #[]
|
|
217
|
+
let mut audited := 0
|
|
218
|
+
let mut theorems : Array (Name × Name × ModuleIdx) := #[]
|
|
219
|
+
for name in names do
|
|
220
|
+
let some idx := env.getModuleIdxFor? name | continue
|
|
221
|
+
unless modules.contains env.header.moduleNames[idx.toNat]! do continue
|
|
222
|
+
if ((privateToUserName? name).getD name).isInternal then continue
|
|
223
|
+
audited := audited + 1
|
|
224
|
+
let extra := (← collectAxioms name).filter (!standard.contains ·)
|
|
225
|
+
let extra := if freezing then extra.filter (· != ``sorryAx) else extra
|
|
226
|
+
unless extra.isEmpty do IO.println s!"AXIOMS '{name}' depends on axioms: {extra}"
|
|
227
|
+
let userName := (privateToUserName? name).getD name
|
|
228
|
+
if userName.isInternalDetail && hasTheoremParent env name && (← findDeclarationRanges? name).isNone then continue
|
|
229
|
+
-- Lean generates a reserved name, such as an equation lemma, only when a proof uses it.
|
|
230
|
+
if isReservedName env name then continue
|
|
231
|
+
-- Its check misses the equations of a private definition's matcher.
|
|
232
|
+
if let .str parent _ := name then
|
|
233
|
+
if Meta.isMatcherCore env parent && (← findDeclarationRanges? name).isNone then continue
|
|
234
|
+
if Meta.isMatcherCore env name then continue
|
|
235
|
+
let info := (env.find? name).get!
|
|
236
|
+
let kind := match info with
|
|
237
|
+
| .thmInfo _ => "theorem"
|
|
238
|
+
| .defnInfo _ => "definition"
|
|
239
|
+
| .opaqueInfo _ => "opaque"
|
|
240
|
+
| .inductInfo _ => "inductive"
|
|
241
|
+
| .ctorInfo _ => "constructor"
|
|
242
|
+
| .recInfo _ => "recursor"
|
|
243
|
+
| .quotInfo _ => "quotient"
|
|
244
|
+
| .axiomInfo _ => "axiom"
|
|
245
|
+
let value := match body? info with
|
|
246
|
+
| some v =>
|
|
247
|
+
let auxes := auxBodies env name
|
|
248
|
+
let bodies := auxes.foldl (init := reprStr (positionFree env v)) fun acc (aux, auxBody) =>
|
|
249
|
+
acc ++ s!"\n{aux}: {reprStr (positionFree env auxBody)}"
|
|
250
|
+
toJson (bodies ++ followed env (v :: auxes.map (·.2)) ++ levelsAlike info.levelParams (v :: auxes.map (·.2)))
|
|
251
|
+
| none => Json.null
|
|
252
|
+
let pp ← liftTermElabM <| Meta.ppExpr info.type
|
|
253
|
+
let record := Json.mkObj [
|
|
254
|
+
("module", toJson env.header.moduleNames[idx.toNat]!.toString),
|
|
255
|
+
("name", toJson userName.toString), ("kind", toJson kind),
|
|
256
|
+
("typeExpr", toJson (reprStr (info.levelParams.map (·.eraseMacroScopes), positionFree env info.type) ++ followed env [info.type]
|
|
257
|
+
++ levelsAlike info.levelParams [info.type])),
|
|
258
|
+
("valueExpr", value), ("type", toJson pp.pretty)]
|
|
259
|
+
IO.println s!"STATEMENT {record.compress}"
|
|
260
|
+
if info matches .thmInfo _ then theorems := theorems.push (name, userName, idx)
|
|
261
|
+
for (name, userName, idx) in theorems.qsort (·.1.toString < ·.1.toString) do
|
|
262
|
+
let pairedWitness := match userName with
|
|
263
|
+
| .str parent "witness" => theorems.any fun (_, user, owner) => owner == idx && user == parent
|
|
264
|
+
| _ => false
|
|
265
|
+
if name != userName || pairedWitness then continue
|
|
266
|
+
if env.isProjectionFn name || Meta.isInstanceCore env name then continue
|
|
267
|
+
if (← findDeclarationRanges? name).isNone then continue
|
|
268
|
+
let witness? := theorems.find? fun (_, user, owner) => owner == idx && user == userName ++ `witness
|
|
269
|
+
let line ← liftTermElabM <| tryCatchRuntimeEx
|
|
270
|
+
(witnessLine (env.find? name).get! (witness?.bind (env.find? ·.1)))
|
|
271
|
+
fun error => return s!"WITNESS unavailable {name}: {oneLine (← error.toMessageData.toString)}"
|
|
272
|
+
IO.println line
|
|
273
|
+
IO.println s!"AUDITED {audited} declarations"
|
|
274
|
+
|
|
275
|
+
open Lean Elab Command
|
|
276
|
+
|
|
277
|
+
private def point (p : Position) : Json := toJson (p.line, p.column)
|
|
278
|
+
|
|
279
|
+
-- An example's statement is the type of the local Lean binds for its header, and
|
|
280
|
+
-- a guard's is its term. Closing over the local context removes the ids of
|
|
281
|
+
-- section variables, which shift when an earlier command changes.
|
|
282
|
+
private def statement (trees : PersistentArray InfoTree) (check : Syntax) : IO Json := do
|
|
283
|
+
let isExample := check.isOfKind ``Parser.Command.example
|
|
284
|
+
let target := if isExample then check else check[1]
|
|
285
|
+
let wanted (ti : TermInfo) := ti.stx.getPos? == target.getPos? &&
|
|
286
|
+
(if isExample then ti.stx.isOfKind ``Parser.Command.declId && ti.expr.isFVar
|
|
287
|
+
else ti.stx.getTailPos? == target.getTailPos?)
|
|
288
|
+
let found := trees.foldl (init := none) fun found tree => found <|> tree.foldInfo (init := none)
|
|
289
|
+
fun ctx info found => found <|> match info with
|
|
290
|
+
| .ofTermInfo ti => if wanted ti then some (ctx, ti) else none
|
|
291
|
+
| _ => none
|
|
292
|
+
let some (ctx, ti) := found | return Json.null
|
|
293
|
+
ctx.runMetaM ti.lctx do
|
|
294
|
+
let e ← instantiateMVars (← if isExample then Meta.inferType ti.expr else pure ti.expr)
|
|
295
|
+
let xs := ti.lctx.foldl (init := #[]) fun xs decl =>
|
|
296
|
+
if decl.isImplementationDetail then xs else xs.push decl.toExpr
|
|
297
|
+
let e ← Meta.mkLambdaFVars xs e
|
|
298
|
+
let env ← getEnv
|
|
299
|
+
return if e.hasFVar || e.hasMVar then Json.null else toJson (statementKey env [] e)
|
|
300
|
+
|
|
301
|
+
private def declarations (instances : Array (Nat × Nat)) : CommandElabM (Array Json) := do
|
|
302
|
+
let env ← getEnv
|
|
303
|
+
let fileMap ← getFileMap
|
|
304
|
+
let names := env.constants.fold (fun acc name _ =>
|
|
305
|
+
if env.isImportedConst name then acc else acc.push name) #[]
|
|
306
|
+
let mut result := #[]
|
|
307
|
+
for name in names do
|
|
308
|
+
let some ranges ← findDeclarationRanges? name | continue
|
|
309
|
+
let pos := (fileMap.ofPosition ranges.selectionRange.pos).byteIdx
|
|
310
|
+
-- Local and scoped instances may no longer be registered in the final environment.
|
|
311
|
+
let instanceDecl := Meta.isInstanceCore env name || instances.any fun (start, tail) =>
|
|
312
|
+
start ≤ pos && pos < tail
|
|
313
|
+
let info := (env.find? name).get!
|
|
314
|
+
result := result.push <| Json.mkObj [
|
|
315
|
+
("name", toJson ((privateToUserName? name).getD name).toString),
|
|
316
|
+
("private", toJson (privateToUserName? name).isSome),
|
|
317
|
+
("theorem", toJson ((info matches .thmInfo _) && !env.isProjectionFn name && !instanceDecl)),
|
|
318
|
+
("type", toJson (statementKey env info.levelParams info.type)),
|
|
319
|
+
("start", point ranges.range.pos), ("end", point ranges.range.endPos)]
|
|
320
|
+
return result
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
-- Print the errors in a message log to stderr, and say whether there were any.
|
|
324
|
+
private def printErrors (log : Lean.MessageLog) : IO Bool := do
|
|
325
|
+
let errors := log.toList.filter (·.severity == .error)
|
|
326
|
+
for msg in errors do
|
|
327
|
+
IO.eprint (← msg.toString)
|
|
328
|
+
return !errors.isEmpty
|
|
329
|
+
|
|
330
|
+
open Lean Elab in
|
|
331
|
+
unsafe def runAudit (freezing : Bool) (moduleList : String) : IO UInt32 := do
|
|
332
|
+
let modules ← IO.FS.lines moduleList
|
|
333
|
+
-- Types print as they would in a file that opens these namespaces, which the frozen records keep.
|
|
334
|
+
let text := String.join ((#["Lean"] ++ modules).toList.map (s!"import {·}\n")) ++ "open Lean Elab Command\n"
|
|
335
|
+
let inputCtx := Parser.mkInputContext text "<audit>"
|
|
336
|
+
let (header, parserState, messages) ← Parser.parseHeader inputCtx
|
|
337
|
+
let (env, messages) ← processHeader header {} messages inputCtx
|
|
338
|
+
-- An import that fails, such as two modules that declare one name, stops the audit with Lean's error.
|
|
339
|
+
if ← printErrors messages then return 1
|
|
340
|
+
let state ← IO.processCommands inputCtx parserState (Command.mkState env messages {})
|
|
341
|
+
if ← printErrors state.commandState.messages then return 1
|
|
342
|
+
let (_, state) ← (Frontend.runCommandElabM (audit freezing)).run { inputCtx } |>.run state
|
|
343
|
+
return if ← printErrors state.commandState.messages then 1 else 0
|
|
344
|
+
|
|
345
|
+
open Lean Elab Command in
|
|
346
|
+
unsafe def analyze (path : String) : IO UInt32 := do
|
|
347
|
+
let inputCtx := Parser.mkInputContext (← IO.FS.readFile path) path
|
|
348
|
+
let (header, parserState, messages) ← Parser.parseHeader inputCtx
|
|
349
|
+
let (env, messages) ← processHeader header {} messages inputCtx
|
|
350
|
+
let state ← IO.processCommands inputCtx parserState (Command.mkState env messages {})
|
|
351
|
+
let mut commands := #[]
|
|
352
|
+
let mut instances := #[]
|
|
353
|
+
for stx in state.commands do
|
|
354
|
+
if let some instanceStx := stx.find? (·.isOfKind ``Parser.Command.instance) then
|
|
355
|
+
if let (some start, some tail) := (instanceStx.getPos?, instanceStx.getTailPos?) then
|
|
356
|
+
instances := instances.push (start.byteIdx, tail.byteIdx)
|
|
357
|
+
let some start := stx.getPos? | continue
|
|
358
|
+
let some tail := stx.getTailPos? | continue
|
|
359
|
+
let propertyStx := stx.find? fun cmd =>
|
|
360
|
+
cmd.isOfKind ``Parser.Command.guardCmd || cmd.isOfKind ``Parser.Command.example
|
|
361
|
+
let property := match propertyStx with
|
|
362
|
+
| some cmd => if cmd.isOfKind ``Parser.Command.guardCmd then "#guard" else "example"
|
|
363
|
+
| none => ""
|
|
364
|
+
let propertyStart := (propertyStx.bind Syntax.getPos?).getD start
|
|
365
|
+
let propertyEnd := (propertyStx.bind Syntax.getTailPos?).getD tail
|
|
366
|
+
commands := commands.push <| Json.mkObj [
|
|
367
|
+
("property", toJson property),
|
|
368
|
+
("statement", toJson (← propertyStx.mapM (statement state.commandState.infoState.trees))),
|
|
369
|
+
("start", point (inputCtx.fileMap.toPosition propertyStart)),
|
|
370
|
+
("end", point (inputCtx.fileMap.toPosition propertyEnd))]
|
|
371
|
+
let (decls, _) ← (Frontend.runCommandElabM (declarations instances)).run { inputCtx } |>.run state
|
|
372
|
+
let mut errors := #[]
|
|
373
|
+
for msg in state.commandState.messages.toList do
|
|
374
|
+
if msg.severity == .error then errors := errors.push (← msg.toJson)
|
|
375
|
+
IO.println <| "AFV_LEAN " ++ (Json.mkObj [
|
|
376
|
+
("declarations", toJson decls), ("commands", toJson commands),
|
|
377
|
+
("errors", toJson errors)]).compress
|
|
378
|
+
return 0
|
|
379
|
+
|
|
380
|
+
unsafe def main (args : List String) : IO UInt32 := do
|
|
381
|
+
enableInitializersExecution
|
|
382
|
+
Lean.initSearchPath (← Lean.findSysroot)
|
|
383
|
+
match args with
|
|
384
|
+
| ["audit", moduleList] => runAudit false moduleList
|
|
385
|
+
| ["audit", "--freeze", moduleList] => runAudit true moduleList
|
|
386
|
+
| ["analyze", path] => analyze path
|
|
387
|
+
| _ => throw <| IO.userError "usage: lean-analysis.lean audit [--freeze] <module-list> | analyze <source.lean>"
|
|
@@ -1,251 +1,14 @@
|
|
|
1
1
|
#!/bin/bash
|
|
2
2
|
# Copyright (c) 2026 Michael Denyer
|
|
3
3
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
4
|
-
# Builds a Lean 4 model with Lake
|
|
5
|
-
# module. Fails when the build fails, a declaration uses sorry or rests on an
|
|
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.
|
|
13
|
-
# Named files limit the check to those sources, so agents that share a project
|
|
14
|
-
# can each check their own model; a run without them checks the whole project.
|
|
15
|
-
# Needs a pin of Lean 4.20.0 or later, the first whose Lake builds a module by
|
|
16
|
-
# its source path.
|
|
4
|
+
# Builds and audits a Lean 4 model with Lake; lean.py describes the checks.
|
|
17
5
|
#
|
|
18
6
|
# Usage: lean-check.sh <lake-project-dir> [--freeze] [<file.lean> ...]
|
|
19
7
|
# A file is absolute or relative to the project.
|
|
20
|
-
set -
|
|
8
|
+
set -euo pipefail
|
|
21
9
|
[ "$#" -gt 0 ] || { echo "usage: lean-check.sh <lake-project-dir> [--freeze] [<file.lean> ...]"; exit 2; }
|
|
22
|
-
dir=$1
|
|
23
|
-
shift
|
|
24
|
-
freeze=0
|
|
25
|
-
if [ "${1-}" = "--freeze" ]; then freeze=1; shift; fi
|
|
26
|
-
for arg; do
|
|
27
|
-
[[ $arg != --* ]] || { echo "usage: --freeze must precede source files"; exit 2; }
|
|
28
|
-
done
|
|
29
10
|
HERE=$(cd "$(dirname "$0")" && pwd)
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
toolchain=$(lean_ready_pin "$dir") || { status=$?; echo "$toolchain"; exit "$status"; }
|
|
35
|
-
|
|
36
|
-
work=$(mktemp -d)
|
|
37
|
-
trap 'rm -rf "$work"' EXIT
|
|
38
|
-
log=$work/build.log
|
|
39
|
-
command -v python3 > /dev/null || { echo "UNAVAILABLE python3 is required to check frozen Lean statements; install Python 3"; exit 3; }
|
|
40
|
-
# Lake builds a module named by its source path and rejects a path that no
|
|
41
|
-
# library owns, so naming every source leaves no file unchecked. Its query
|
|
42
|
-
# command prints the .olean of each, which names the modules to audit without
|
|
43
|
-
# picking up a module left in the build directory by a deleted source.
|
|
44
|
-
sources=()
|
|
45
|
-
scope=$dir
|
|
46
|
-
if [ "$#" -gt 0 ]; then
|
|
47
|
-
scope="$dir ($* only)"
|
|
48
|
-
for src; do
|
|
49
|
-
[[ $src == /* ]] || src=$dir/$src
|
|
50
|
-
[ -f "$src" ] || { echo "FAIL $src does not exist"; exit 1; }
|
|
51
|
-
sources+=("$src")
|
|
52
|
-
done
|
|
53
|
-
else
|
|
54
|
-
if [ "$freeze" -eq 0 ]; then
|
|
55
|
-
python3 "$HERE/lean-statements.py" orphans "$dir" > "$work/orphans.out"
|
|
56
|
-
orphan_status=$?
|
|
57
|
-
if [ "$orphan_status" -ne 0 ]; then
|
|
58
|
-
echo "FAIL $scope: frozen model sources are missing or their records are invalid"
|
|
59
|
-
cat "$work/orphans.out"
|
|
60
|
-
exit "$orphan_status"
|
|
61
|
-
fi
|
|
62
|
-
fi
|
|
63
|
-
while IFS= read -r src; do sources+=("$src"); done \
|
|
64
|
-
< <(find "$dir" -name '*.lean' -not -path "$dir/.lake/*" -not -name lakefile.lean | sort)
|
|
65
|
-
[ "${#sources[@]}" -gt 0 ] || { echo "FAIL $dir has no .lean file to check"; exit 1; }
|
|
66
|
-
fi
|
|
67
|
-
elan run "$toolchain" lake --dir "$dir" query "${sources[@]/%/:olean}" > "$work/oleans" 2> "$log"
|
|
68
|
-
status=$?
|
|
69
|
-
# Lean quotes sorry with backticks or straight quotes depending on the version.
|
|
70
|
-
sorry='^(warning|error): .*: declaration uses .sorry.'
|
|
71
|
-
sorries=$(grep -cE "$sorry" "$log")
|
|
72
|
-
|
|
73
|
-
# The audit imports those modules and collects the axioms under each of their
|
|
74
|
-
# declarations, so it needs no #print axioms line in the model. It skips the
|
|
75
|
-
# compiler's auxiliary declarations, which older pins store with opaque
|
|
76
|
-
# placeholders that would read as axioms.
|
|
77
|
-
audit_status=0
|
|
78
|
-
: > "$work/audit.out"
|
|
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"
|
|
84
|
-
{
|
|
85
|
-
echo "import Lean"
|
|
86
|
-
sed 's|^|import |' "$work/modules"
|
|
87
|
-
cat << 'EOF'
|
|
88
|
-
open Lean in
|
|
89
|
-
private def hasTheoremParent (env : Environment) : Name → Bool
|
|
90
|
-
| .anonymous => false
|
|
91
|
-
| .str parent _ | .num parent _ =>
|
|
92
|
-
(match env.find? parent with | some (.thmInfo _) => true | _ => false) || hasTheoremParent env parent
|
|
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
|
-
|
|
121
|
-
open Lean Elab Command in
|
|
122
|
-
#eval show CommandElabM Unit from do
|
|
123
|
-
let env ← getEnv
|
|
124
|
-
let freezing := (← IO.getEnv "AFV_FREEZE") == some "1"
|
|
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)}"
|
|
127
|
-
let standard : Array Name := #[``propext, ``Classical.choice, ``Quot.sound]
|
|
128
|
-
let names := env.constants.fold (fun acc name info => if info matches .axiomInfo _ then acc else acc.push name) #[]
|
|
129
|
-
let mut audited := 0
|
|
130
|
-
let mut theorems : Array (Name × Name × ModuleIdx) := #[]
|
|
131
|
-
for name in names do
|
|
132
|
-
let some idx := env.getModuleIdxFor? name | continue
|
|
133
|
-
unless modules.contains env.header.moduleNames[idx.toNat]! do continue
|
|
134
|
-
if ((privateToUserName? name).getD name).isInternal then continue
|
|
135
|
-
audited := audited + 1
|
|
136
|
-
let extra := (← collectAxioms name).filter (!standard.contains ·)
|
|
137
|
-
let extra := if freezing then extra.filter (· != ``sorryAx) else extra
|
|
138
|
-
unless extra.isEmpty do IO.println s!"AXIOMS '{name}' depends on axioms: {extra}"
|
|
139
|
-
let userName := (privateToUserName? name).getD name
|
|
140
|
-
if userName.isInternalDetail && hasTheoremParent env name && (← findDeclarationRanges? name).isNone then continue
|
|
141
|
-
let info := (env.find? name).get!
|
|
142
|
-
let kind := match info with
|
|
143
|
-
| .thmInfo _ => "theorem"
|
|
144
|
-
| .defnInfo _ => "definition"
|
|
145
|
-
| .opaqueInfo _ => "opaque"
|
|
146
|
-
| .inductInfo _ => "inductive"
|
|
147
|
-
| .ctorInfo _ => "constructor"
|
|
148
|
-
| .recInfo _ => "recursor"
|
|
149
|
-
| .quotInfo _ => "quotient"
|
|
150
|
-
| .axiomInfo _ => "axiom"
|
|
151
|
-
let value := match info with
|
|
152
|
-
| .defnInfo v => toJson (reprStr v.value)
|
|
153
|
-
| .opaqueInfo v => toJson (reprStr v.value)
|
|
154
|
-
| _ => Json.null
|
|
155
|
-
let pp ← liftTermElabM <| Meta.ppExpr info.type
|
|
156
|
-
let record := Json.mkObj [
|
|
157
|
-
("module", toJson env.header.moduleNames[idx.toNat]!.toString),
|
|
158
|
-
("name", toJson userName.toString), ("kind", toJson kind),
|
|
159
|
-
("typeExpr", toJson (reprStr (info.levelParams, info.type))),
|
|
160
|
-
("valueExpr", value), ("type", toJson pp.pretty)]
|
|
161
|
-
IO.println s!"STATEMENT {record.compress}"
|
|
162
|
-
if info matches .thmInfo _ then theorems := theorems.push (name, userName, idx)
|
|
163
|
-
for (name, userName, idx) in theorems.qsort (·.1.toString < ·.1.toString) do
|
|
164
|
-
let pairedWitness := match userName with
|
|
165
|
-
| .str parent "witness" => theorems.any fun (_, user, owner) => owner == idx && user == parent
|
|
166
|
-
| _ => false
|
|
167
|
-
if name != userName || pairedWitness then continue
|
|
168
|
-
if env.isProjectionFn name || Meta.isInstanceCore env name then continue
|
|
169
|
-
if (← findDeclarationRanges? name).isNone then continue
|
|
170
|
-
let witness? := theorems.find? fun (_, user, owner) => owner == idx && user == userName ++ `witness
|
|
171
|
-
let line ← liftTermElabM <| tryCatchRuntimeEx
|
|
172
|
-
(witnessLine (env.find? name).get! (witness?.bind (env.find? ·.1)))
|
|
173
|
-
fun error => return s!"WITNESS unavailable {name}: {oneLine (← error.toMessageData.toString)}"
|
|
174
|
-
IO.println line
|
|
175
|
-
IO.println s!"AUDITED {audited} declarations"
|
|
176
|
-
EOF
|
|
177
|
-
} > "$work/Audit.lean"
|
|
178
|
-
AFV_FREEZE=$freeze elan run "$toolchain" lake --dir "$dir" env lean "$work/Audit.lean" > "$work/audit.out" 2>&1
|
|
179
|
-
audit_status=$?
|
|
180
|
-
grep -qE '^AUDITED [0-9]+ declarations$' "$work/audit.out" || audit_status=1
|
|
181
|
-
if grep -q '^AUDITED 0 declarations$' "$work/audit.out"; then
|
|
182
|
-
frozen=0
|
|
183
|
-
for src in "${sources[@]}"; do
|
|
184
|
-
[ ! -f "${src%.lean}.statements" ] || frozen=1
|
|
185
|
-
done
|
|
186
|
-
[ "$freeze" -eq 0 ] && [ "$frozen" -eq 1 ] || audit_status=1
|
|
187
|
-
fi
|
|
188
|
-
fi
|
|
189
|
-
axioms=$(grep -c '^AXIOMS ' "$work/audit.out")
|
|
190
|
-
|
|
191
|
-
if [ "$status" -ne 0 ] || { [ "$freeze" -eq 0 ] && [ "$sorries" -ne 0 ]; } || [ "$axioms" -ne 0 ] || [ "$audit_status" -ne 0 ]; then
|
|
192
|
-
echo "FAIL $scope: $sorries unfinished proofs (sorry), $axioms declarations on an added axiom, lake exit $status"
|
|
193
|
-
grep -E "$sorry" "$log"
|
|
194
|
-
grep '^AXIOMS ' "$work/audit.out"
|
|
195
|
-
[ "$status" -eq 0 ] || grep -v '^[[:space:]]*$' "$log" | tail -40
|
|
196
|
-
! grep -q '^error: unknown module source path' "$log" \
|
|
197
|
-
|| echo "no library owns that file; import it from a built module or move it out of the project"
|
|
198
|
-
! grep -qE "^error: (unknown command 'query'|invalid script spec)" "$log" \
|
|
199
|
-
|| echo "$toolchain cannot build a module by its source path; pin Lean 4.20.0 or later"
|
|
200
|
-
if [ "$audit_status" -ne 0 ]; then
|
|
201
|
-
echo "the axiom audit did not run or found no declarations:"
|
|
202
|
-
grep -v -e '^[[:space:]]*$' -e '^IMPORTED ' "$work/audit.out" | tail -40
|
|
203
|
-
! grep -q 'environment already contains' "$work/audit.out" \
|
|
204
|
-
|| echo "two modules declare the same name; put each model in a namespace of its own"
|
|
205
|
-
fi
|
|
206
|
-
exit 1
|
|
207
|
-
fi
|
|
208
|
-
mode=check
|
|
209
|
-
[ "$freeze" -eq 0 ] || mode=freeze
|
|
210
|
-
python3 "$HERE/lean-statements.py" "$mode" "$toolchain" "$work/audit.out" "$work/modules" "${sources[@]}" > "$work/statements.out"
|
|
211
|
-
statement_status=$?
|
|
212
|
-
if [ "$statement_status" -ne 0 ]; then
|
|
213
|
-
echo "FAIL $scope: frozen statements differ or could not be checked"
|
|
214
|
-
cat "$work/statements.out"
|
|
215
|
-
exit "$statement_status"
|
|
216
|
-
fi
|
|
217
|
-
cat "$work/statements.out"
|
|
218
|
-
# #eval output arrives as info blocks that can span lines.
|
|
219
|
-
grep -v '^[[:space:]]*$' "$log"
|
|
220
|
-
[ "$freeze" -eq 0 ] || exit 0
|
|
221
|
-
|
|
222
|
-
witnesses() { grep -c "^WITNESS $1 " "$work/audit.out"; }
|
|
223
|
-
failed=$(witnesses failed)
|
|
224
|
-
[ "$failed" -eq 0 ] || echo "FAIL $scope: $failed witnesses do not state their property's hypotheses"
|
|
225
|
-
grep '^WITNESS ' "$work/audit.out"
|
|
226
|
-
[ "$failed" -eq 0 ] || exit 1
|
|
227
|
-
|
|
228
|
-
# The build trusts a declaration that a command adds to the environment without
|
|
229
|
-
# a kernel check. leanchecker replays every declaration of the built modules
|
|
230
|
-
# through the kernel and rejects it. Use its exact-module replayer rather than
|
|
231
|
-
# its CLI's prefix search, which also finds deleted sources' cached objects.
|
|
232
|
-
# A named module rests on the project modules it imports, so replay those too.
|
|
233
|
-
replay=unavailable
|
|
234
|
-
if [ -x "$(elan run "$toolchain" lean --print-prefix)/bin/leanchecker" ]; then
|
|
235
|
-
cp "$work/modules" "$work/replay-modules"
|
|
236
|
-
while IFS= read -r module; do
|
|
237
|
-
[ ! -f "$dir/.lake/build/lib/lean/${module//.//}.olean" ] || printf '%s\n' "$module" >> "$work/replay-modules"
|
|
238
|
-
done < <(sed -n 's/^IMPORTED //p' "$work/audit.out")
|
|
239
|
-
sort -u "$work/replay-modules" -o "$work/replay-modules"
|
|
240
|
-
replay=passed
|
|
241
|
-
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
|
|
242
|
-
fi
|
|
243
|
-
case $replay in
|
|
244
|
-
passed) echo "REPLAYED $(grep -c '^replaying ' "$work/replay.out") modules through the Lean kernel" ;;
|
|
245
|
-
failed)
|
|
246
|
-
echo "FAIL $scope: kernel replay rejected a built module"
|
|
247
|
-
cat "$work/replay.out"
|
|
248
|
-
exit 1 ;;
|
|
249
|
-
unavailable) echo "UNAVAILABLE kernel replay: $toolchain ships no leanchecker" ;;
|
|
250
|
-
esac
|
|
251
|
-
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"
|
|
11
|
+
# shellcheck source=skills/formal-verify/scripts/python-tools.sh
|
|
12
|
+
source "$HERE/python-tools.sh"
|
|
13
|
+
require_python || exit 3
|
|
14
|
+
exec python3 "$HERE/lean.py" check "$@"
|