blob: f1151c4279cc8129f6f592018cf2676f4efb656c [file]
/-
Copyright (c) 2024 Lean FRO, LLC. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Henrik Böving
-/
module
prelude
import Lean.Meta.Tactic.BVDecide.Reflect.SatAtBVLogical
import Std.Tactic.BVDecide.Normalize.Prop
public import Lean.Meta.Tactic.BVDecide.Normalize.Enums
public import Std.Tactic.BVDecide.Bitblast.BVExpr.Basic
public import Std.Sat.AIG.Basic
/-!
This module contains the implementation of counterexample recovery and explanation.
-/
namespace Lean.Meta.Tactic.BVDecide
open Std.Tactic.BVDecide
/--
Given:
- `aig`: The AIG that was used to produce the CNF.
- `assignments`: A model for the CNF as provided by a SAT solver.
- `atomsAssignment`: The mapping of the reflection monad from atom indices to `Expr`.
Reconstruct bit by bit which value expression must have had which `BitVec` value and return all
expression - pair values.
-/
public def reconstructCounterExample (aig : Std.Sat.AIG BVBit) (assignment : Array (Bool × Nat))
(atomsAssignment : Std.HashMap Nat (Nat × Expr × Bool)) :
Array (Expr × Bool × BVExpr.PackedBitVec) := Id.run do
let mut sparseMap : Std.HashMap Nat (Std.TreeMap Nat Bool) := {}
for (decl, idx) in aig.decls.zipIdx do
let .atom bitVar := decl | continue
/-
The CNF variable of an AIG node is the index of the node and the node of an atom doubles as
the variable of the atom. We assume that a variable can be found at its index as CaDiCal prints
them in order.
Note that cadical will report an assignment for all literals up to the maximum literal from the
CNF. So even if variable or AIG bits below the maximum literal did not occur in the CNF they
will still occur in the assignment that cadical reports.
There is one crucial thing to consider in addition: If the highest literal that ended up in the
CNF does not represent the highest variable bit not all variable bits show up in the assignment.
For this situation we do the same as cadical for literals that did not show up in the CNF:
set them to true.
-/
let varSet := if h : idx < assignment.size then assignment[idx].fst else true
let mut bitMap := sparseMap.getD bitVar.var {}
bitMap := bitMap.insert bitVar.idx varSet
sparseMap := sparseMap.insert bitVar.var bitMap
let mut finalMap := #[]
for (bitVecVar, bitMap) in sparseMap do
let mut value : Nat := 0
let mut currentBit := 0
for (bitIdx, bitValue) in bitMap do
assert! bitIdx == currentBit
if bitValue then
value := value ||| (1 <<< currentBit)
currentBit := currentBit + 1
let (_, atomExpr, synthetic) := atomsAssignment[bitVecVar]!
finalMap := finalMap.push (atomExpr, synthetic, ⟨BitVec.ofNat currentBit value⟩)
-- There might exist atoms that have not been encoded into CNF, we fill them with 0s
for (atomId, (width, atomExpr, synthetic)) in atomsAssignment do
if sparseMap.contains atomId then continue
finalMap := finalMap.push (atomExpr, synthetic, ⟨BitVec.ofNat width 0⟩)
return finalMap
/--
A counter example generated from the bitblaster.
-/
public structure CounterExample where
/--
The goal in which to interpret this counter example.
-/
goal : MVarId
/--
The set of unused but potentially relevant hypotheses. Useful for diagnosing spurious counter
examples.
-/
unusedHypotheses : Std.HashSet Normalize.Hyp
/--
The actual counter example as a list of equations denoted as `expr = value` pairs.
-/
equations : Array (Expr × BVExpr.PackedBitVec)
/--
Some of the expressions in the equations may be function atoms that were used by the UF theory
solver. We want to inform the user that these are not just ordinary uninterpeted symbols.
-/
functionAtoms : Array Expr
/--
The result of a spurious counter example diagnosis.
-/
structure Diagnosis where
uninterpretedSymbols : Std.HashSet Expr := {}
functionSymbols : Array Expr := {}
functionSymbolSet : Std.HashSet Expr := {}
unusedRelevantHypotheses : Std.HashSet Normalize.Hyp := {}
derivedEquations : Array (Expr × Expr) := #[]
abbrev DiagnosisM : Type → Type := ReaderT CounterExample <| StateRefT Diagnosis MetaM
namespace DiagnosisM
def run (x : DiagnosisM Unit) (counterExample : CounterExample) : MetaM Diagnosis := do
counterExample.goal.withContext do
let (_, issues) ← ReaderT.run x counterExample |>.run {}
return issues
@[inline]
def unusedHyps : DiagnosisM (Std.HashSet Normalize.Hyp) := do
return (← read).unusedHypotheses
@[inline]
def equations : DiagnosisM (Array (Expr × BVExpr.PackedBitVec)) := do
return (← read).equations
@[inline]
def addUninterpretedSymbol (e : Expr) : DiagnosisM Unit :=
modify fun s => { s with uninterpretedSymbols := s.uninterpretedSymbols.insert e }
@[inline]
def addFunctionSymbol (e : Expr) : DiagnosisM Unit :=
modify fun s =>
{ s with
functionSymbolSet := s.functionSymbolSet.insert e,
functionSymbols := s.functionSymbols.push e
}
@[inline]
def isFunctionSymbol (e : Expr) : DiagnosisM Bool :=
return (← get).functionSymbolSet.contains e
@[inline]
def addUnusedRelevantHypothesis (hyp : Normalize.Hyp) : DiagnosisM Unit :=
modify fun s => { s with unusedRelevantHypotheses := s.unusedRelevantHypotheses.insert hyp }
@[inline]
def addDerivedEquation (var : Expr) (value : Expr) : DiagnosisM Unit :=
modify fun s => { s with derivedEquations := s.derivedEquations.push (var, value) }
def checkRelevantHypsUsed (fvar : FVarId) : DiagnosisM Unit := do
for hyp in ← unusedHyps do
if hyp.type.containsFVar fvar then
addUnusedRelevantHypothesis hyp
/--
Diagnose spurious counter examples, currently this checks:
- Whether uninterpreted symbols were used
- Whether all hypotheses which contain any variable that was bitblasted were included
-/
def diagnose : DiagnosisM Unit := do
for funAtom in (← read).functionAtoms do
addFunctionSymbol funAtom
for (var, value) in ← equations do
let (var, value) ← transformEquation var value
addDerivedEquation var value
match var with
| .fvar fvarId => checkRelevantHypsUsed fvarId
| _ =>
if ← isFunctionSymbol var then continue
addUninterpretedSymbol var
where
transformEquation (var : Expr) (value : BVExpr.PackedBitVec) : DiagnosisM (Expr × Expr) := do
if var.isFVar then
return (var, toExpr value.bv)
else
match_expr var with
| BitVec.ofBool x =>
return (x, toExpr <| value.bv == 1)
| Std.Tactic.BVDecide.BitVec.ofProp x =>
return (x, mkConst (if value.bv == 1 then ``True else ``False))
| UInt8.toBitVec x =>
if h : value.w = 8 then
return (x, toExpr <| UInt8.ofBitVec (h ▸ value.bv))
else
throwError m!"Value for UInt8 was not 8 bits but {value.w} bits"
| UInt16.toBitVec x =>
if h : value.w = 16 then
return (x, toExpr <| UInt16.ofBitVec (h ▸ value.bv))
else
throwError m!"Value for UInt16 was not 16 bits but {value.w} bits"
| UInt32.toBitVec x =>
if h : value.w = 32 then
return (x, toExpr <| UInt32.ofBitVec (h ▸ value.bv))
else
throwError m!"Value for UInt32 was not 32 bits but {value.w} bits"
| UInt64.toBitVec x =>
if h : value.w = 64 then
return (x, toExpr <| UInt64.ofBitVec (h ▸ value.bv))
else
throwError m!"Value for UInt64 was not 64 bits but {value.w} bits"
| USize.toBitVec32 x _ =>
if value.w = 32 then
return (x, toExpr <| USize.ofNat value.bv.toNat)
else
throwError m!"Value for USize was not 32 bits but {value.w} bits"
| USize.toBitVec64 x _ =>
if value.w = 64 then
return (x, toExpr <| USize.ofNat value.bv.toNat)
else
throwError m!"Value for USize was not 64 bits but {value.w} bits"
| Int8.toBitVec x =>
if h : value.w = 8 then
return (x, toExpr <| Int8.ofBitVec (h ▸ value.bv))
else
throwError m!"Value for Int8 was not 8 bits but {value.w} bits"
| Int16.toBitVec x =>
if h : value.w = 16 then
return (x, toExpr <| Int16.ofBitVec (h ▸ value.bv))
else
throwError m!"Value for Int16 was not 16 bits but {value.w} bits"
| Int32.toBitVec x =>
if h : value.w = 32 then
return (x, toExpr <| Int32.ofBitVec (h ▸ value.bv))
else
throwError m!"Value for Int32 was not 32 bits but {value.w} bits"
| Int64.toBitVec x =>
if h : value.w = 64 then
return (x, toExpr <| Int64.ofBitVec (h ▸ value.bv))
else
throwError m!"Value for Int64 was not 64 bits but {value.w} bits"
| ISize.toBitVec32 x _ =>
if value.w = 32 then
return (x, toExpr <| ISize.ofInt value.bv.toInt)
else
throwError m!"Value for ISize was not 32 bits but {value.w} bits"
| ISize.toBitVec64 x _ =>
if value.w = 64 then
return (x, toExpr <| ISize.ofInt value.bv.toInt)
else
throwError m!"Value for ISize was not 64 bits but {value.w} bits"
| _ =>
match var with
| .app (.const fn levels) arg =>
if let some p := Normalize.enumToBitVecType? (← getEnv) fn then
let .inductInfo inductiveInfo ← getConstInfo p | unreachable!
let ctors := inductiveInfo.ctors
let enumVal := mkConst ctors[value.bv.toNat]! levels
return (arg, enumVal)
else
return (var, toExpr value.bv)
| _ => return (var, toExpr value.bv)
end DiagnosisM
def functionExplainer (d : Diagnosis) : Option MessageData := do
guard !d.functionSymbols.isEmpty
let symList := d.functionSymbols.toList
let mut m := m!"The prover used the following expressions as uninterpreted functions:"
for e in symList do
m := m ++ m!"\n - {e}"
return m
def theoryExplainers : List (Diagnosis → Option MessageData) :=
[functionExplainer]
def uninterpretedExplainer (d : Diagnosis) : Option MessageData := do
guard !d.uninterpretedSymbols.isEmpty
let symList := d.uninterpretedSymbols.toList
let mut m := m!"It abstracted the following unsupported expressions as opaque variables:"
for e in symList do
m := m ++ m!"\n - {e}"
return m
def unusedRelevantHypothesesExplainer (d : Diagnosis) : Option MessageData := do
guard !d.unusedRelevantHypotheses.isEmpty
let hyps := d.unusedRelevantHypotheses.toList
let mut m := m!"The following potentially relevant hypotheses could not be used:"
for hyp in hyps do
m := m ++ m!"\n - {hyp.type} derived via {hyp.source}"
return m
def spuriousExplainers : List (Diagnosis → Option MessageData) :=
[uninterpretedExplainer, unusedRelevantHypothesesExplainer]
public def explainCounterExampleQuality (counterExample : CounterExample) : MetaM MessageData := do
let diagnosis ← DiagnosisM.run DiagnosisM.diagnose counterExample
let theoryExplanations := theoryExplainers.foldl (init := #[]) fun acc explainer =>
if let some m := explainer diagnosis then acc.push m else acc
let spuriorsExplanations := spuriousExplainers.foldl (init := #[]) fun acc explainer =>
if let some m := explainer diagnosis then acc.push m else acc
let mut err := m!""
if !theoryExplanations.isEmpty then
err := err ++ theoryExplanations.foldl (init := m!"") (fun acc exp => acc ++ m!"- " ++ exp ++ m!"\n")
if spuriorsExplanations.isEmpty then
err := err ++ m!"The prover found a counterexample, consider the following assignment:\n"
else
err := err ++ m!"The prover found a potentially spurious counterexample:\n"
err := err ++ spuriorsExplanations.foldl (init := m!"") (fun acc exp => acc ++ m!"- " ++ exp ++ m!"\n")
err := err ++ m!"Consider the following assignment:\n"
err := diagnosis.derivedEquations.foldl (init := err) fun error (var, value) => error ++ m!"{var} = {value}\n"
return err
end Lean.Meta.Tactic.BVDecide