Skip to main content

logicaffeine_verify/
ir.rs

1//! Verification IR (Intermediate Representation)
2//!
3//! A lightweight AST for Z3 verification that decouples from the main Logicaffeine AST.
4//! This avoids circular dependencies: logicaffeine depends on logicaffeine_verify,
5//! so logicaffeine_verify cannot depend on logicaffeine.
6//!
7//! ## Usage
8//!
9//! Build expressions using the [`VerifyExpr`] constructors:
10//!
11//! ```
12//! use logicaffeine_verify::{VerifyExpr, VerifyOp, VerifyType};
13//!
14//! // Build: x > 5 && y < 10
15//! let expr = VerifyExpr::and(
16//!     VerifyExpr::gt(VerifyExpr::var("x"), VerifyExpr::int(5)),
17//!     VerifyExpr::lt(VerifyExpr::var("y"), VerifyExpr::int(10)),
18//! );
19//! ```
20//!
21//! ## Encoding Strategy
22//!
23//! Complex types (modals, temporals, predicates) become uninterpreted functions.
24//! Z3 reasons about their structure without semantic understanding.
25//!
26//! For example, given `Possible(A) -> Possible(B)` and `Possible(A)`, Z3 deduces `Possible(B)`.
27
28use serde::{Deserialize, Serialize};
29
30/// Type declarations for verification variables.
31///
32/// Each type maps to a Z3 sort:
33///
34/// | VerifyType | Z3 Sort | Usage |
35/// |------------|---------|-------|
36/// | `Int` | `IntSort` | Numeric constraints, bounds checking |
37/// | `Bool` | `BoolSort` | Logical propositions |
38/// | `Object` | Uninterpreted | Entities (people, objects, propositions) |
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub enum VerifyType {
41    /// Integer type, maps to Z3 `IntSort`.
42    Int,
43    /// Boolean type, maps to Z3 `BoolSort`.
44    Bool,
45    /// Opaque object type for entities, maps to an uninterpreted sort.
46    Object,
47    /// Fixed-width bitvector, maps to Z3 `BitVecSort(n)`.
48    BitVector(u32),
49    /// Array type (index → element), maps to Z3 `ArraySort`.
50    Array(Box<VerifyType>, Box<VerifyType>),
51    /// Real number type, maps to Z3 `RealSort` (IEEE 1800-2023).
52    Real,
53}
54
55/// Binary operations in the verification IR.
56///
57/// Operations are grouped by category:
58/// - **Arithmetic**: `Add`, `Sub`, `Mul`, `Div` (Int × Int → Int)
59/// - **Comparison**: `Eq`, `Neq`, `Gt`, `Lt`, `Gte`, `Lte` (Int × Int → Bool)
60/// - **Logic**: `And`, `Or`, `Implies` (Bool × Bool → Bool)
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62pub enum VerifyOp {
63    // ---- Arithmetic (Int × Int → Int) ----
64    /// Addition.
65    Add,
66    /// Subtraction.
67    Sub,
68    /// Multiplication.
69    Mul,
70    /// Integer division (Euclidean, matching Z3's `div`).
71    Div,
72    /// Floor division (`a // b`) — the quotient rounded toward negative infinity, exactly.
73    /// Encoded as `to_int(to_real(a) / to_real(b))` (Z3's `to_int` is the floor function),
74    /// which is precise across every sign combination — unlike [`VerifyOp::Div`], whose
75    /// Euclidean rounding only coincides with floor when the divisor is positive.
76    FloorDiv,
77
78    // ---- Comparison (Int × Int → Bool) ----
79    /// Equality.
80    Eq,
81    /// Inequality.
82    Neq,
83    /// Greater than.
84    Gt,
85    /// Less than.
86    Lt,
87    /// Greater than or equal.
88    Gte,
89    /// Less than or equal.
90    Lte,
91
92    // ---- Logic (Bool × Bool → Bool) ----
93    /// Conjunction.
94    And,
95    /// Disjunction.
96    Or,
97    /// Material implication.
98    Implies,
99}
100
101/// Bitvector operations for hardware verification.
102///
103/// These map directly to Z3's bitvector theory operations.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
105pub enum BitVecOp {
106    // ---- Bitwise ----
107    And,
108    Or,
109    Xor,
110    Not,
111
112    // ---- Shift ----
113    Shl,
114    Shr,
115    /// Arithmetic shift right (sign-extending).
116    AShr,
117
118    // ---- Arithmetic ----
119    Add,
120    Sub,
121    Mul,
122    /// Signed division, truncating toward zero (matches Rust `i64` `/`).
123    SDiv,
124    /// Signed remainder, sign following the dividend (matches Rust `i64` `%`).
125    SRem,
126
127    // ---- Comparison ----
128    /// Unsigned less than.
129    ULt,
130    /// Signed less than.
131    SLt,
132    /// Unsigned less than or equal.
133    ULe,
134    /// Signed less than or equal.
135    SLe,
136    /// Bitvector equality.
137    Eq,
138}
139
140/// Expression AST for verification.
141///
142/// This IR is designed to be easily encodable into Z3 ASTs.
143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
144pub enum VerifyExpr {
145    /// Integer literal
146    Int(i64),
147
148    /// Boolean literal
149    Bool(bool),
150
151    /// Variable reference
152    Var(String),
153
154    /// Binary operation
155    Binary {
156        op: VerifyOp,
157        left: Box<VerifyExpr>,
158        right: Box<VerifyExpr>,
159    },
160
161    /// Logical negation
162    Not(Box<VerifyExpr>),
163
164    /// Universal quantifier: forall x: T. P(x)
165    ForAll {
166        vars: Vec<(String, VerifyType)>,
167        body: Box<VerifyExpr>,
168    },
169
170    /// Existential quantifier: exists x: T. P(x)
171    Exists {
172        vars: Vec<(String, VerifyType)>,
173        body: Box<VerifyExpr>,
174    },
175
176    /// Uninterpreted function application (the "catch-all")
177    ///
178    /// Used for predicates, modals, temporals, etc. that we can't
179    /// directly encode semantically. Z3 treats these as opaque functions
180    /// and reasons about them structurally.
181    ///
182    /// Examples:
183    /// - `Mortal(socrates)` -> `Apply { name: "Mortal", args: [Var("socrates")] }`
184    /// - `Possible(P)` -> `Apply { name: "Possible", args: [P] }`
185    Apply { name: String, args: Vec<VerifyExpr> },
186
187    /// Uninterpreted INT-valued function application: `Int^n → Int`.
188    ///
189    /// For function symbols in TERM position — `sum(a, b)` (the Link-lattice
190    /// join ⊕), `GovernmentOf(x)`, `has(x, y)` — where [`VerifyExpr::Apply`]
191    /// (which encodes as `Int^n → Bool`) would be ill-sorted.
192    ApplyInt { name: String, args: Vec<VerifyExpr> },
193
194    // ---- Bitvector operations (hardware verification) ----
195    /// Bitvector constant with explicit width.
196    BitVecConst { width: u32, value: u64 },
197
198    /// Bitvector binary operation.
199    BitVecBinary {
200        op: BitVecOp,
201        left: Box<VerifyExpr>,
202        right: Box<VerifyExpr>,
203    },
204
205    /// Bitvector bit extraction: operand\[high:low\].
206    BitVecExtract {
207        high: u32,
208        low: u32,
209        operand: Box<VerifyExpr>,
210    },
211
212    /// Bitvector concatenation.
213    BitVecConcat(Box<VerifyExpr>, Box<VerifyExpr>),
214
215    // ---- Temporal (BMC encoding) ----
216    /// Expression evaluated at a specific state (for BMC unrolling).
217    AtState {
218        state: Box<VerifyExpr>,
219        expr: Box<VerifyExpr>,
220    },
221
222    /// State transition relation: from → to.
223    Transition {
224        from: Box<VerifyExpr>,
225        to: Box<VerifyExpr>,
226    },
227
228    // ---- Array theory ----
229    /// Array select: array\[index\].
230    Select {
231        array: Box<VerifyExpr>,
232        index: Box<VerifyExpr>,
233    },
234
235    /// Array store: array\[index\] := value.
236    Store {
237        array: Box<VerifyExpr>,
238        index: Box<VerifyExpr>,
239        value: Box<VerifyExpr>,
240    },
241
242    // ---- Biconditional (equivalence checking) ----
243    /// Biconditional: left ↔ right. Used for Z3 equivalence queries.
244    Iff(Box<VerifyExpr>, Box<VerifyExpr>),
245}
246
247impl VerifyExpr {
248    /// Create a variable reference.
249    ///
250    /// # Examples
251    ///
252    /// ```
253    /// use logicaffeine_verify::VerifyExpr;
254    ///
255    /// let x = VerifyExpr::var("x");
256    /// let counter = VerifyExpr::var("counter");
257    /// ```
258    pub fn var(name: impl Into<String>) -> Self {
259        VerifyExpr::Var(name.into())
260    }
261
262    /// Create an integer literal.
263    ///
264    /// # Examples
265    ///
266    /// ```
267    /// use logicaffeine_verify::VerifyExpr;
268    ///
269    /// let five = VerifyExpr::int(5);
270    /// let negative = VerifyExpr::int(-42);
271    /// ```
272    pub fn int(n: i64) -> Self {
273        VerifyExpr::Int(n)
274    }
275
276    /// Create a boolean literal.
277    ///
278    /// # Examples
279    ///
280    /// ```
281    /// use logicaffeine_verify::VerifyExpr;
282    ///
283    /// let truth = VerifyExpr::bool(true);
284    /// let falsity = VerifyExpr::bool(false);
285    /// ```
286    pub fn bool(b: bool) -> Self {
287        VerifyExpr::Bool(b)
288    }
289
290    /// Create a binary operation.
291    ///
292    /// For common operations, prefer the convenience methods like [`eq`](Self::eq),
293    /// [`gt`](Self::gt), [`and`](Self::and), etc.
294    ///
295    /// # Examples
296    ///
297    /// ```
298    /// use logicaffeine_verify::{VerifyExpr, VerifyOp};
299    ///
300    /// // x + y
301    /// let sum = VerifyExpr::binary(
302    ///     VerifyOp::Add,
303    ///     VerifyExpr::var("x"),
304    ///     VerifyExpr::var("y"),
305    /// );
306    /// ```
307    pub fn binary(op: VerifyOp, left: VerifyExpr, right: VerifyExpr) -> Self {
308        VerifyExpr::Binary {
309            op,
310            left: Box::new(left),
311            right: Box::new(right),
312        }
313    }
314
315    /// Create a negation.
316    ///
317    /// # Examples
318    ///
319    /// ```
320    /// use logicaffeine_verify::VerifyExpr;
321    ///
322    /// // ¬p
323    /// let not_p = VerifyExpr::not(VerifyExpr::var("p"));
324    ///
325    /// // ¬(x > 5)
326    /// let not_gt = VerifyExpr::not(
327    ///     VerifyExpr::gt(VerifyExpr::var("x"), VerifyExpr::int(5))
328    /// );
329    /// ```
330    pub fn not(expr: VerifyExpr) -> Self {
331        VerifyExpr::Not(Box::new(expr))
332    }
333
334    /// Create an uninterpreted function application.
335    ///
336    /// Use this for predicates, modals, temporals, and other constructs
337    /// that cannot be directly encoded semantically. Z3 treats these as
338    /// opaque functions and reasons about them structurally.
339    ///
340    /// # Examples
341    ///
342    /// ```
343    /// use logicaffeine_verify::VerifyExpr;
344    ///
345    /// // Mortal(socrates)
346    /// let mortal = VerifyExpr::apply("Mortal", vec![VerifyExpr::var("socrates")]);
347    ///
348    /// // Possible(P) for modal logic
349    /// let possible_p = VerifyExpr::apply("Possible", vec![VerifyExpr::var("P")]);
350    ///
351    /// // Before(e1, e2) for temporal relations
352    /// let before = VerifyExpr::apply("Before", vec![
353    ///     VerifyExpr::var("e1"),
354    ///     VerifyExpr::var("e2"),
355    /// ]);
356    /// ```
357    pub fn apply(name: impl Into<String>, args: Vec<VerifyExpr>) -> Self {
358        VerifyExpr::Apply {
359            name: name.into(),
360            args,
361        }
362    }
363
364    /// Create an uninterpreted INT-valued function application (`Int^n → Int`)
365    /// for function symbols in term position, e.g. the lattice join
366    /// `sum(a, b)`.
367    pub fn apply_int(name: impl Into<String>, args: Vec<VerifyExpr>) -> Self {
368        VerifyExpr::ApplyInt {
369            name: name.into(),
370            args,
371        }
372    }
373
374    /// Create a universal quantifier.
375    ///
376    /// # Examples
377    ///
378    /// ```
379    /// use logicaffeine_verify::{VerifyExpr, VerifyType};
380    ///
381    /// // ∀x: Object. Mortal(x) → Human(x)
382    /// let all_mortals_are_human = VerifyExpr::forall(
383    ///     vec![("x".to_string(), VerifyType::Object)],
384    ///     VerifyExpr::implies(
385    ///         VerifyExpr::apply("Mortal", vec![VerifyExpr::var("x")]),
386    ///         VerifyExpr::apply("Human", vec![VerifyExpr::var("x")]),
387    ///     ),
388    /// );
389    /// ```
390    pub fn forall(vars: Vec<(String, VerifyType)>, body: VerifyExpr) -> Self {
391        VerifyExpr::ForAll {
392            vars,
393            body: Box::new(body),
394        }
395    }
396
397    /// Create an existential quantifier.
398    ///
399    /// # Examples
400    ///
401    /// ```
402    /// use logicaffeine_verify::{VerifyExpr, VerifyType};
403    ///
404    /// // ∃x: Object. Mortal(x)
405    /// let something_is_mortal = VerifyExpr::exists(
406    ///     vec![("x".to_string(), VerifyType::Object)],
407    ///     VerifyExpr::apply("Mortal", vec![VerifyExpr::var("x")]),
408    /// );
409    /// ```
410    pub fn exists(vars: Vec<(String, VerifyType)>, body: VerifyExpr) -> Self {
411        VerifyExpr::Exists {
412            vars,
413            body: Box::new(body),
414        }
415    }
416
417    // ---- Convenience methods for common operations ----
418
419    /// Equality: `left == right`.
420    ///
421    /// # Examples
422    ///
423    /// ```
424    /// use logicaffeine_verify::VerifyExpr;
425    ///
426    /// let x_equals_10 = VerifyExpr::eq(VerifyExpr::var("x"), VerifyExpr::int(10));
427    /// ```
428    pub fn eq(left: VerifyExpr, right: VerifyExpr) -> Self {
429        Self::binary(VerifyOp::Eq, left, right)
430    }
431
432    /// Greater than: `left > right`.
433    ///
434    /// # Examples
435    ///
436    /// ```
437    /// use logicaffeine_verify::VerifyExpr;
438    ///
439    /// let x_gt_5 = VerifyExpr::gt(VerifyExpr::var("x"), VerifyExpr::int(5));
440    /// ```
441    pub fn gt(left: VerifyExpr, right: VerifyExpr) -> Self {
442        Self::binary(VerifyOp::Gt, left, right)
443    }
444
445    /// Less than: `left < right`.
446    ///
447    /// # Examples
448    ///
449    /// ```
450    /// use logicaffeine_verify::VerifyExpr;
451    ///
452    /// let x_lt_100 = VerifyExpr::lt(VerifyExpr::var("x"), VerifyExpr::int(100));
453    /// ```
454    pub fn lt(left: VerifyExpr, right: VerifyExpr) -> Self {
455        Self::binary(VerifyOp::Lt, left, right)
456    }
457
458    /// Greater than or equal: `left >= right`.
459    ///
460    /// # Examples
461    ///
462    /// ```
463    /// use logicaffeine_verify::VerifyExpr;
464    ///
465    /// let x_gte_0 = VerifyExpr::gte(VerifyExpr::var("x"), VerifyExpr::int(0));
466    /// ```
467    pub fn gte(left: VerifyExpr, right: VerifyExpr) -> Self {
468        Self::binary(VerifyOp::Gte, left, right)
469    }
470
471    /// Less than or equal: `left <= right`.
472    ///
473    /// # Examples
474    ///
475    /// ```
476    /// use logicaffeine_verify::VerifyExpr;
477    ///
478    /// let x_lte_max = VerifyExpr::lte(VerifyExpr::var("x"), VerifyExpr::var("max"));
479    /// ```
480    pub fn lte(left: VerifyExpr, right: VerifyExpr) -> Self {
481        Self::binary(VerifyOp::Lte, left, right)
482    }
483
484    /// Inequality: `left != right`.
485    ///
486    /// # Examples
487    ///
488    /// ```
489    /// use logicaffeine_verify::VerifyExpr;
490    ///
491    /// let x_neq_0 = VerifyExpr::neq(VerifyExpr::var("x"), VerifyExpr::int(0));
492    /// ```
493    pub fn neq(left: VerifyExpr, right: VerifyExpr) -> Self {
494        Self::binary(VerifyOp::Neq, left, right)
495    }
496
497    /// Conjunction: `left && right`.
498    ///
499    /// # Examples
500    ///
501    /// ```
502    /// use logicaffeine_verify::VerifyExpr;
503    ///
504    /// // x > 0 && x < 100
505    /// let in_range = VerifyExpr::and(
506    ///     VerifyExpr::gt(VerifyExpr::var("x"), VerifyExpr::int(0)),
507    ///     VerifyExpr::lt(VerifyExpr::var("x"), VerifyExpr::int(100)),
508    /// );
509    /// ```
510    pub fn and(left: VerifyExpr, right: VerifyExpr) -> Self {
511        Self::binary(VerifyOp::And, left, right)
512    }
513
514    /// Disjunction: `left || right`.
515    ///
516    /// # Examples
517    ///
518    /// ```
519    /// use logicaffeine_verify::VerifyExpr;
520    ///
521    /// // x < 0 || x > 100
522    /// let out_of_range = VerifyExpr::or(
523    ///     VerifyExpr::lt(VerifyExpr::var("x"), VerifyExpr::int(0)),
524    ///     VerifyExpr::gt(VerifyExpr::var("x"), VerifyExpr::int(100)),
525    /// );
526    /// ```
527    pub fn or(left: VerifyExpr, right: VerifyExpr) -> Self {
528        Self::binary(VerifyOp::Or, left, right)
529    }
530
531    /// Material implication: `left → right`.
532    ///
533    /// # Examples
534    ///
535    /// ```
536    /// use logicaffeine_verify::VerifyExpr;
537    ///
538    /// // Mortal(x) → Human(x)
539    /// let mortals_are_human = VerifyExpr::implies(
540    ///     VerifyExpr::apply("Mortal", vec![VerifyExpr::var("x")]),
541    ///     VerifyExpr::apply("Human", vec![VerifyExpr::var("x")]),
542    /// );
543    /// ```
544    pub fn implies(left: VerifyExpr, right: VerifyExpr) -> Self {
545        Self::binary(VerifyOp::Implies, left, right)
546    }
547
548    // ---- Bitvector convenience constructors ----
549
550    /// Create a bitvector constant.
551    pub fn bv_const(width: u32, value: u64) -> Self {
552        VerifyExpr::BitVecConst { width, value }
553    }
554
555    /// Create a bitvector binary operation.
556    pub fn bv_binary(op: BitVecOp, left: VerifyExpr, right: VerifyExpr) -> Self {
557        VerifyExpr::BitVecBinary {
558            op,
559            left: Box::new(left),
560            right: Box::new(right),
561        }
562    }
563
564    /// Biconditional: `left ↔ right`.
565    pub fn iff(left: VerifyExpr, right: VerifyExpr) -> Self {
566        VerifyExpr::Iff(Box::new(left), Box::new(right))
567    }
568}
569
570#[cfg(test)]
571#[path = "../../logicaffeine_tests/unit/logicaffeine_verify/ir/tests.rs"]
572mod tests;