logicaffeine_verify/error.rs
1//! Verification error types with Socratic error messages.
2//!
3//! ## Philosophy
4//!
5//! Errors in this module follow the Socratic method: they guide users toward
6//! understanding rather than simply reporting failures. Each error type includes:
7//!
8//! - A clear description of what went wrong
9//! - Context about why it matters
10//! - Guidance on how to address the issue
11//! - When available, a concrete counterexample
12//!
13//! ## Error Categories
14//!
15//! | Category | Error Types | User Action |
16//! |----------|-------------|-------------|
17//! | Logic | `ContradictoryAssertion`, `BoundsViolation`, `RefinementViolation` | Fix the logical issue |
18//! | Solver | `SolverUnknown`, `SolverError` | Simplify or restructure |
19//! | Termination | `TerminationViolation` | Add decreasing variant |
20
21use std::fmt;
22
23/// Result type for verification operations.
24pub type VerificationResult<T = ()> = Result<T, VerificationError>;
25
26/// A verification error with Socratic explanation.
27///
28/// Each error includes contextual information to help users understand
29/// and fix the issue.
30///
31/// # Fields
32///
33/// - `kind`: Categorizes the error type
34/// - `span`: Source location (byte offsets) where the error occurred
35/// - `explanation`: Human-readable context explaining why verification failed
36/// - `counterexample`: Concrete variable assignments that demonstrate the failure
37#[derive(Debug)]
38pub struct VerificationError {
39 /// The category of verification error.
40 pub kind: VerificationErrorKind,
41 /// Optional source span as `(start, end)` byte offsets.
42 pub span: Option<(usize, usize)>,
43 /// Human-readable explanation of why verification failed.
44 pub explanation: String,
45 /// Concrete witness showing a failing case, when available.
46 pub counterexample: Option<CounterExample>,
47}
48
49/// The category of verification error.
50///
51/// Each variant represents a distinct failure mode with specific remediation steps.
52#[derive(Debug, Clone, PartialEq)]
53pub enum VerificationErrorKind {
54 /// An assertion that can never be true.
55 ///
56 /// Z3 proved that no interpretation satisfies the assertion.
57 ///
58 /// **Common causes:**
59 /// - Conflicting constraints (e.g., `x > 5` and `x < 3`)
60 /// - Logical contradictions in premises
61 /// - Impossible refinement type predicates
62 ///
63 /// **Action:** Review your assumptions for conflicts.
64 ContradictoryAssertion,
65
66 /// A variable violates its declared bounds.
67 ///
68 /// The verifier found a possible value that falls outside the
69 /// declared constraint.
70 ///
71 /// **Action:** Either tighten the constraint or add assumptions
72 /// that rule out the violating value.
73 BoundsViolation {
74 /// The variable that violated its bounds.
75 var: String,
76 /// The constraint that was expected.
77 expected: String,
78 /// The value that violated the constraint.
79 found: String,
80 },
81
82 /// A refinement type predicate is not satisfied.
83 ///
84 /// The value being assigned does not satisfy the predicate
85 /// in the refinement type definition.
86 ///
87 /// **Action:** Ensure the value meets the refinement predicate,
88 /// or add assumptions that constrain the value appropriately.
89 RefinementViolation {
90 /// The name of the refinement type.
91 type_name: String,
92 },
93
94 /// Z3 returned unknown (timeout or undecidable).
95 ///
96 /// The solver could not determine validity within the timeout period,
97 /// or the problem is undecidable.
98 ///
99 /// **Action:** Simplify the assertion or add more constraining assumptions.
100 SolverUnknown,
101
102 /// Z3 initialization or internal error.
103 ///
104 /// An unexpected error occurred in the Z3 solver.
105 ///
106 /// **Action:** Check that Z3 is properly installed and configured.
107 SolverError {
108 /// The error message from Z3.
109 message: String,
110 },
111
112 /// Loop termination cannot be proven.
113 ///
114 /// The verifier could not prove that the loop variant strictly decreases
115 /// on each iteration while remaining non-negative.
116 ///
117 /// **Action:** Ensure your variant expression decreases by at least 1
118 /// on each iteration and has a lower bound.
119 TerminationViolation {
120 /// The variant expression that should decrease.
121 variant: String,
122 /// Why termination could not be proven.
123 reason: String,
124 },
125}
126
127/// A counterexample showing concrete values that falsify an assertion.
128///
129/// When Z3 finds that an assertion is not valid, it produces a model
130/// (set of variable assignments) that makes the negation of the assertion true.
131/// This counterexample helps users understand exactly why verification failed.
132///
133/// # Example Interpretation
134///
135/// If verifying `x > 5` fails with counterexample `x = 3`, this means:
136/// - The solver found that `x = 3` is a possible value
137/// - With `x = 3`, the assertion `x > 5` is false
138/// - Therefore the assertion is not universally valid
139#[derive(Debug, Clone)]
140pub struct CounterExample {
141 /// Variable assignments that make the assertion false.
142 ///
143 /// Each tuple contains `(variable_name, value_as_string)`.
144 pub assignments: Vec<(String, String)>,
145}
146
147impl fmt::Display for CounterExample {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 for (var, val) in &self.assignments {
150 write!(f, "{} = {}", var, val)?;
151 if self.assignments.len() > 1 {
152 write!(f, ", ")?;
153 }
154 }
155 Ok(())
156 }
157}
158
159impl fmt::Display for VerificationError {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 match &self.kind {
162 VerificationErrorKind::ContradictoryAssertion => {
163 writeln!(f, "This assertion can never be true.")?;
164 writeln!(f)?;
165 writeln!(f, "{}", self.explanation)?;
166 if let Some(ce) = &self.counterexample {
167 writeln!(f)?;
168 writeln!(f, "Counter-example: {}", ce)?;
169 }
170 }
171 VerificationErrorKind::BoundsViolation {
172 var,
173 expected,
174 found,
175 } => {
176 writeln!(f, "Value '{}' violates its constraint.", var)?;
177 writeln!(f)?;
178 writeln!(f, "Expected: {}", expected)?;
179 writeln!(f, "But found possible value: {}", found)?;
180 }
181 VerificationErrorKind::RefinementViolation { type_name } => {
182 writeln!(f, "Value does not satisfy refinement type '{}'.", type_name)?;
183 writeln!(f)?;
184 writeln!(f, "{}", self.explanation)?;
185 }
186 VerificationErrorKind::SolverUnknown => {
187 writeln!(
188 f,
189 "The solver could not determine if the assertion is valid."
190 )?;
191 writeln!(f)?;
192 writeln!(f, "This may be due to complexity or timeout.")?;
193 }
194 VerificationErrorKind::SolverError { message } => {
195 writeln!(f, "Solver error: {}", message)?;
196 }
197 VerificationErrorKind::TerminationViolation { variant, reason } => {
198 writeln!(f, "Cannot prove loop terminates.")?;
199 writeln!(f)?;
200 writeln!(
201 f,
202 "Variant '{}' does not strictly decrease: {}",
203 variant, reason
204 )?;
205 }
206 }
207 Ok(())
208 }
209}
210
211impl std::error::Error for VerificationError {}
212
213impl VerificationError {
214 // ---- Logic Errors ----
215
216 /// Create a contradictory assertion error.
217 ///
218 /// Use when Z3 proves the negation of an assertion is satisfiable.
219 pub fn contradiction(
220 explanation: impl Into<String>,
221 counterexample: Option<CounterExample>,
222 ) -> Self {
223 Self {
224 kind: VerificationErrorKind::ContradictoryAssertion,
225 span: None,
226 explanation: explanation.into(),
227 counterexample,
228 }
229 }
230
231 /// Create a bounds violation error.
232 ///
233 /// Use when a variable's value falls outside its declared constraint.
234 pub fn bounds_violation(
235 var: impl Into<String>,
236 expected: impl Into<String>,
237 found: impl Into<String>,
238 ) -> Self {
239 Self {
240 kind: VerificationErrorKind::BoundsViolation {
241 var: var.into(),
242 expected: expected.into(),
243 found: found.into(),
244 },
245 span: None,
246 explanation: String::new(),
247 counterexample: None,
248 }
249 }
250
251 /// Create a refinement type violation error.
252 ///
253 /// Use when a value does not satisfy its refinement type predicate.
254 pub fn refinement_violation(
255 type_name: impl Into<String>,
256 explanation: impl Into<String>,
257 ) -> Self {
258 Self {
259 kind: VerificationErrorKind::RefinementViolation {
260 type_name: type_name.into(),
261 },
262 span: None,
263 explanation: explanation.into(),
264 counterexample: None,
265 }
266 }
267
268 // ---- Solver Errors ----
269
270 /// Create a solver unknown error.
271 ///
272 /// Use when Z3 cannot determine satisfiability (timeout or undecidable).
273 pub fn solver_unknown() -> Self {
274 Self {
275 kind: VerificationErrorKind::SolverUnknown,
276 span: None,
277 explanation: String::new(),
278 counterexample: None,
279 }
280 }
281
282 /// Create a solver error.
283 ///
284 /// Use when Z3 encounters an internal error or configuration issue.
285 pub fn solver_error(message: impl Into<String>) -> Self {
286 Self {
287 kind: VerificationErrorKind::SolverError {
288 message: message.into(),
289 },
290 span: None,
291 explanation: String::new(),
292 counterexample: None,
293 }
294 }
295
296 // ---- Termination Errors ----
297
298 /// Create a termination violation error.
299 ///
300 /// Use when loop termination cannot be proven via the variant expression.
301 pub fn termination_violation(variant: impl Into<String>, reason: impl Into<String>) -> Self {
302 Self {
303 kind: VerificationErrorKind::TerminationViolation {
304 variant: variant.into(),
305 reason: reason.into(),
306 },
307 span: None,
308 explanation: String::new(),
309 counterexample: None,
310 }
311 }
312
313 // ---- Builder Methods ----
314
315 /// Set the source span for this error.
316 ///
317 /// Spans are byte offsets `(start, end)` into the source text.
318 pub fn with_span(mut self, start: usize, end: usize) -> Self {
319 self.span = Some((start, end));
320 self
321 }
322}