Skip to main content

clock_dbm/
bounds.rs

1//! Bounds, clock identifiers, and difference constraints.
2//!
3//! A [`Bound`] is a strict (`< c`) or non-strict (`<= c`) bound, or
4//! [infinity](Bound::INFINITY) when no finite limit is imposed. Smaller
5//! bounds are tighter.
6//!
7//! A [`Clock`] identifies any clock, including the fixed reference clock
8//! [`Clock::ZERO`]; a [`Variable`] identifies only an actual clock and
9//! is used for reset and free operations. A [`Constraint`] bounds the
10//! difference between two clocks. The [`constraint!`](crate::constraint)
11//! macro provides concise notation for common clock guards.
12
13// Source-level implementation and proof notes (not part of public API Rustdoc).
14// Packed `i32` bounds, clock identifiers and difference constraints.
15//
16// `Le(c)` means a non-strict upper bound (`<= c`), `Lt(c)` means a
17// strict upper bound (`< c`), and `∞` imposes no restriction.
18//
19// # Encoding
20//
21// A [`Bound`] is one `i32` in an order-preserving encoding
22// (see the encoding below):
23//
24// | bound | code |
25// |---|---|
26// | `Lt(c)` | `2c` |
27// | `Le(c)` | `2c + 1` |
28// | `∞` | `0x7FFF_FFFE` (the reserved infinity value) |
29//
30// with `c ∈ [MIN_CONSTANT, MAX_CONSTANT] = [−(2²⁹−1), 2²⁹−1]`. Valid finite
31// codes therefore lie in `[−2³⁰+2, 2³⁰−1]`. Every other bit pattern except
32// the infinity code is unconstructible (a type invariant, checked by the
33// proofs). Comparing codes as integers is the tightness order.
34//
35// # Headroom
36//
37// Finite codes satisfy `|code| < 2³⁰`, so the sum of two codes lies strictly
38// inside `(−2³¹, 2³¹)` and packed addition `a + b − ((a | b) & 1)` cannot
39// overflow `i32`. [`Bound::checked_add`] computes it in `i32` and then checks
40// that the result is a valid code. An out-of-range finite sum is
41// [`Error::Range`], never `∞`.
42//
43// # Verification
44//
45// The functions below are the verified ones. Their contracts are stated
46// against the logical model [`BoundModel`] and are proved by Creusot v0.14.0
47// (`verification/scripts/prove-crate.sh`). Contracts and lemmas erase in
48// ordinary builds. See `verification/PROOF_STATUS.md`.
49
50use crate::dbm::MAX_VARIABLES;
51use crate::error::Error;
52use creusot_std::{
53    invariant::{Invariant, inv},
54    logic::real::Real,
55    prelude::{Clone, PartialEq, *},
56};
57
58/// Largest representable finite constant: `2²⁹ − 1`.
59// Literal values (not `(1 << 29) - 1` etc.): Creusot keeps computed
60// constants opaque, so the proofs need them spelled out. Unit tests below
61// check them against their defining expressions.
62pub const MAX_CONSTANT: i32 = 0x1FFF_FFFF;
63/// Smallest representable finite constant: `−MAX_CONSTANT` (symmetric, so
64/// negating a representable constant is always representable).
65pub const MIN_CONSTANT: i32 = -0x1FFF_FFFF;
66
67/// The reserved encoding for infinity.
68const INF: i32 = 0x7FFF_FFFE;
69/// Smallest valid code, `Lt(MIN_CONSTANT)`.
70const MIN_CODE: i32 = -0x3FFF_FFFE;
71/// Largest valid finite code, `Le(MAX_CONSTANT)`.
72const MAX_CODE: i32 = 0x3FFF_FFFF;
73
74/// Logical (ghost) model of a bound: `x − y < c`, `x − y ≤ c`, or no
75/// constraint. Used only in specifications.
76pub enum BoundModel {
77    /// `< c`
78    Lt(Int),
79    /// `≤ c`
80    Le(Int),
81    /// `< ∞`
82    Inf,
83}
84
85impl BoundModel {
86    /// Whether a finite constant is representable.
87    #[logic(open)]
88    pub fn in_range(c: Int) -> bool {
89        pearlite! { MIN_CONSTANT@ <= c && c <= MAX_CONSTANT@ }
90    }
91
92    /// Tightness order `≼`: `self` is at least as tight as `other`.
93    #[logic(open)]
94    pub fn le(self, other: BoundModel) -> bool {
95        match (self, other) {
96            (_, BoundModel::Inf) => true,
97            (BoundModel::Inf, _) => false,
98            (BoundModel::Lt(a), BoundModel::Lt(b)) => a <= b,
99            (BoundModel::Lt(a), BoundModel::Le(b)) => a <= b,
100            (BoundModel::Le(a), BoundModel::Lt(b)) => a < b,
101            (BoundModel::Le(a), BoundModel::Le(b)) => a <= b,
102        }
103    }
104
105    /// Bound addition: constants add, the result is
106    /// strict iff a summand is strict, and `∞` absorbs.
107    #[logic(open)]
108    pub fn add(self, other: BoundModel) -> BoundModel {
109        match (self, other) {
110            (BoundModel::Inf, _) | (_, BoundModel::Inf) => BoundModel::Inf,
111            (BoundModel::Le(a), BoundModel::Le(b)) => BoundModel::Le(a + b),
112            (BoundModel::Lt(a), BoundModel::Lt(b))
113            | (BoundModel::Lt(a), BoundModel::Le(b))
114            | (BoundModel::Le(a), BoundModel::Lt(b)) => BoundModel::Lt(a + b),
115        }
116    }
117
118    /// The sum of two bounds is representable (trivially so if infinite).
119    #[logic(open)]
120    pub fn add_in_range(self, other: BoundModel) -> bool {
121        match (self, other) {
122            (BoundModel::Inf, _) | (_, BoundModel::Inf) => true,
123            (BoundModel::Lt(a) | BoundModel::Le(a), BoundModel::Lt(b) | BoundModel::Le(b)) => {
124                BoundModel::in_range(a + b)
125            }
126        }
127    }
128
129    /// Negation of finite bounds: `Le c ↦ Lt (−c)`,
130    /// `Lt c ↦ Le (−c)`. Meaningful for finite bounds only.
131    #[logic(open)]
132    pub fn neg(self) -> BoundModel {
133        match self {
134            BoundModel::Lt(c) => BoundModel::Le(-c),
135            BoundModel::Le(c) => BoundModel::Lt(-c),
136            BoundModel::Inf => BoundModel::Inf,
137        }
138    }
139
140    /// The constant of a finite bound is representable.
141    #[logic(open)]
142    pub fn representable(self) -> bool {
143        match self {
144            BoundModel::Lt(c) | BoundModel::Le(c) => BoundModel::in_range(c),
145            BoundModel::Inf => true,
146        }
147    }
148}
149
150/// `d` satisfies `b`: the constraint `x − y ⋈ c` holds
151/// when `x − y = d`. Differences are real numbers, never integers.
152#[logic(open)]
153pub fn sat(b: BoundModel, d: Real) -> bool {
154    match b {
155        BoundModel::Lt(c) => d < Real::from_int(c),
156        BoundModel::Le(c) => d <= Real::from_int(c),
157        BoundModel::Inf => true,
158    }
159}
160
161/// Soundness of addition over the reals.
162#[logic]
163#[requires(sat(a, x) && sat(b, y))]
164#[ensures(sat(a.add(b), x + y))]
165pub fn add_sound(a: BoundModel, b: BoundModel, x: Real, y: Real) {}
166
167/// The tightness order implies inclusion of real solution sets.
168#[logic]
169#[requires(a.le(b))]
170#[requires(sat(a, d))]
171#[ensures(sat(b, d))]
172pub fn le_sound(a: BoundModel, b: BoundModel, d: Real) {}
173
174/// Inclusion of real solution sets implies the tightness order.
175#[logic]
176#[requires(forall<d: Real> sat(a, d) ==> sat(b, d))]
177#[ensures(a.le(b))]
178pub fn le_complete(a: BoundModel, b: BoundModel) {
179    pearlite! {
180        match a {
181            BoundModel::Lt(ca) => {
182                let w = Real::from_int(ca) - half();
183                proof_assert!(sat(a, w));
184                proof_assert!(sat(b, w));
185            }
186            BoundModel::Le(ca) => {
187                proof_assert!(sat(a, Real::from_int(ca)));
188                proof_assert!(sat(b, Real::from_int(ca)));
189            }
190            BoundModel::Inf => match b {
191                BoundModel::Lt(cb) | BoundModel::Le(cb) => {
192                    proof_assert!(sat(a, Real::from_int(cb + 1)));
193                    proof_assert!(sat(b, Real::from_int(cb + 1)));
194                }
195                BoundModel::Inf => {}
196            },
197        }
198    }
199}
200
201#[logic(open)]
202fn half() -> Real {
203    Real::from_int(1) / Real::from_int(2)
204}
205
206/// Real (not integer) semantics: `< c+1` and `≤ c` differ at `c + 1/2`.
207#[logic]
208#[ensures(sat(BoundModel::Lt(c + 1), Real::from_int(c) + half()))]
209#[ensures(!sat(BoundModel::Le(c), Real::from_int(c) + half()))]
210pub fn strict_is_not_integer(c: Int) {}
211
212/// Negation is the complement:
213/// `¬sat(r, b) ⟺ sat(−r, neg b)` for finite `b`.
214#[logic]
215#[requires(b != BoundModel::Inf)]
216#[ensures(forall<r: Real> !sat(b, r) == sat(b.neg(), -r))]
217pub fn neg_complement(b: BoundModel) {}
218
219/// The constant range is symmetric, so negating a representable constant
220/// (e.g. to write the lower-bound guard `x ≥ c` as `0 − x ≤ −c`) is
221/// representable, and so is negating a representable finite bound.
222#[logic]
223#[requires(BoundModel::in_range(c))]
224#[ensures(BoundModel::in_range(-c))]
225#[ensures(BoundModel::Lt(c).neg().representable() && BoundModel::Le(c).neg().representable())]
226pub fn neg_in_range(c: Int) {}
227
228/// `Lt c ≺ Le c ≺ Lt (c+1) ≺ ∞`.
229#[logic]
230#[ensures(BoundModel::Lt(c).le(BoundModel::Le(c)) && !BoundModel::Le(c).le(BoundModel::Lt(c)))]
231#[ensures(BoundModel::Le(c).le(BoundModel::Lt(c + 1)) && !BoundModel::Lt(c + 1).le(BoundModel::Le(c)))]
232#[ensures(BoundModel::Le(c).le(BoundModel::Inf) && !BoundModel::Inf.le(BoundModel::Le(c)))]
233pub fn tightness_chain(c: Int) {}
234
235// ----- algebra of `(𝔹, ≼, +, Le 0)` used by the closure proof -----
236//
237// These are the algebraic facts needed by the closure proof,
238// restated and proved for `BoundModel`.
239
240/// `≼` is reflexive and transitive.
241#[logic]
242#[ensures(a.le(a))]
243#[ensures(a.le(b) && b.le(c) ==> a.le(c))]
244pub fn le_trans(a: BoundModel, b: BoundModel, c: BoundModel) {}
245
246/// `≼` is total and antisymmetric.
247#[logic]
248#[ensures(a.le(b) || b.le(a))]
249#[ensures(a.le(b) && b.le(a) ==> a == b)]
250pub fn le_total(a: BoundModel, b: BoundModel) {}
251
252/// `+` is commutative and has unit `Le 0`; `∞` absorbs.
253#[logic]
254#[ensures(a.add(b) == b.add(a))]
255#[ensures(a.add(BoundModel::Le(0)) == a)]
256#[ensures(a.add(BoundModel::Inf) == BoundModel::Inf)]
257pub fn add_comm_unit(a: BoundModel, b: BoundModel) {}
258
259/// `+` is associative.
260#[logic]
261#[ensures(a.add(b).add(c) == a.add(b.add(c)))]
262pub fn add_assoc(a: BoundModel, b: BoundModel, c: BoundModel) {}
263
264/// `+` is monotone in `≼` (in each argument).
265#[logic]
266#[requires(a.le(b))]
267#[ensures(a.add(c).le(b.add(c)))]
268#[ensures(c.add(a).le(c.add(b)))]
269pub fn add_mono(a: BoundModel, b: BoundModel, c: BoundModel) {}
270
271/// A bound strictly tighter than `Le 0` excludes the difference 0, e.g. the
272/// strict-zero cycle `Lt 0`.
273#[logic]
274#[requires(!BoundModel::Le(0).le(b))]
275#[ensures(!sat(b, Real::from_int(0)))]
276pub fn below_le_zero_unsat(b: BoundModel) {}
277
278/// `PartialOrd`/`Ord` on the single field, i.e. on the deep model (the packed
279/// code or the clock index). Written out instead of derived because Creusot
280/// needs the contract that refines the `Ord` trait specification.
281macro_rules! ord_by_deep_model {
282    ($t:ty) => {
283        impl PartialOrd for $t {
284            #[check(terminates)]
285            #[ensures(result == (*self).deep_model().partial_cmp_log((*other).deep_model()))]
286            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
287                Some(self.cmp(other))
288            }
289        }
290
291        impl Ord for $t {
292            #[check(terminates)]
293            #[ensures(result == (*self).deep_model().cmp_log((*other).deep_model()))]
294            fn cmp(&self, other: &Self) -> core::cmp::Ordering {
295                self.0.cmp(&other.0)
296            }
297        }
298    };
299}
300
301/// A strict bound `x - y < c`, a non-strict bound `x - y <= c`,
302/// or infinity (no restriction on the difference).
303///
304/// Construct bounds with [`Bound::lt`], [`Bound::le`], or
305/// [`Bound::INFINITY`].
306/// The [`Ord`] implementation orders bounds by *tightness*: smaller bounds
307/// exclude at least as many valuations.
308///
309/// # Example
310///
311/// ```
312/// use clock_dbm::Bound;
313/// # fn main() -> Result<(), clock_dbm::Error> {
314/// assert!(Bound::lt(3)? < Bound::le(3)?);
315/// assert_eq!(Bound::lt(2)?.checked_add(Bound::le(3)?)?, Bound::lt(5)?);
316/// assert!(Bound::INFINITY.is_infinite());
317/// # Ok(())
318/// # }
319/// ```
320#[derive(Copy, PartialEq, Eq, Debug)]
321// `Hash` is not translated by Creusot (std's `Hasher` has no specs); it is
322// derived from the same field as `Eq`, so it is consistent with it.
323#[cfg_attr(not(creusot), derive(Hash))]
324pub struct Bound(i32);
325
326ord_by_deep_model!(Bound);
327
328// Written out instead of derived: the derived contract names the private
329// field, which Creusot cannot resolve when another module clones a container
330// of bounds (e.g. the `Box<[Bound]>` inside `Dbm`).
331impl Clone for Bound {
332    #[check(terminates)]
333    #[ensures(result == *self)]
334    fn clone(&self) -> Bound {
335        *self
336    }
337}
338
339impl Invariant for Bound {
340    #[logic(open(self))]
341    fn invariant(self) -> bool {
342        pearlite! { (MIN_CODE@ <= self.0@ && self.0@ <= MAX_CODE@) || self.0 == INF }
343    }
344}
345
346impl DeepModel for Bound {
347    type DeepModelTy = Int;
348
349    /// The packed code. The derived `Eq`/`Ord`/`Hash` work on this value.
350    #[logic(open(self))]
351    fn deep_model(self) -> Int {
352        pearlite! { self.0@ }
353    }
354}
355
356impl View for Bound {
357    type ViewTy = BoundModel;
358
359    #[logic(open(self))]
360    fn view(self) -> BoundModel {
361        pearlite! {
362            if self.0 == INF {
363                BoundModel::Inf
364            } else if self.0@.rem_euclid(2) == 0 {
365                BoundModel::Lt(self.0@.div_euclid(2))
366            } else {
367                BoundModel::Le(self.0@.div_euclid(2))
368            }
369        }
370    }
371}
372
373/// Every bound denotes a representable model value.
374#[logic]
375#[requires(inv(b))]
376#[ensures(b@.representable())]
377pub fn view_representable(b: Bound) {}
378
379/// B1: the encoding is injective, so equality of bounds (derived `Eq` on the
380/// code) is equality of models.
381#[logic]
382#[requires(inv(a) && inv(b))]
383#[ensures((a@ == b@) == (a.deep_model() == b.deep_model()))]
384pub fn view_injective(a: Bound, b: Bound) {}
385
386/// B2: comparing codes (the derived `Ord`) is the tightness order. With B1
387/// this also gives B4: `Ord::min`/`max` are the model's `min`/`max`.
388#[logic]
389#[requires(inv(a) && inv(b))]
390#[ensures((a.deep_model() <= b.deep_model()) == a@.le(b@))]
391#[ensures((a.deep_model() < b.deep_model()) == (a@.le(b@) && a@ != b@))]
392pub fn order_refines(a: Bound, b: Bound) {}
393
394/// `(x | y) & 1` is 1 iff at least one of `x`, `y` is odd (a weak bound).
395#[check(terminates)]
396#[bitwise_proof]
397#[ensures(result == 0i32 || result == 1i32)]
398#[ensures((result == 1i32) == (x & 1i32 == 1i32 || y & 1i32 == 1i32))]
399const fn weak_or(x: i32, y: i32) -> i32 {
400    (x | y) & 1
401}
402
403/// Bit-level decomposition, proved by bitvector reasoning:
404/// `x = (x >> 1) + (x >> 1) + (x & 1)` (in wrapping arithmetic), with the
405/// ranges of both parts. This is the only place where bits meet arithmetic.
406#[check(terminates)]
407#[bitwise_proof]
408#[ensures(x == (x >> 1i32) + (x >> 1i32) + (x & 1i32))]
409#[ensures(x & 1i32 == 0i32 || x & 1i32 == 1i32)]
410#[ensures(-0x4000_0000i32 <= (x >> 1i32) && (x >> 1i32) <= 0x3FFF_FFFFi32)]
411#[allow(unused_variables)]
412const fn bit_split(x: i32) {}
413
414/// Integer-mode consequences of [`bit_split`]: the low bit is the Euclidean
415/// remainder by 2 and the arithmetic shift is the Euclidean quotient.
416#[check(terminates)]
417#[ensures((x & 1i32)@ == x@.rem_euclid(2))]
418#[ensures((x & 1i32 == 1i32) == (x@.rem_euclid(2) == 1))]
419#[ensures(x & 1i32 == 0i32 || x & 1i32 == 1i32)]
420#[ensures((x >> 1i32)@ == x@.div_euclid(2))]
421const fn low_bit(x: i32) {
422    bit_split(x);
423}
424
425impl Bound {
426    /// A bound that places no restriction on a clock difference.
427    #[ensures(Bound::INFINITY@ == BoundModel::Inf)]
428    pub const INFINITY: Bound = Bound(INF);
429    /// The non-strict bound `<= 0`, used on a canonical DBM's diagonal.
430    #[ensures(Bound::LE_ZERO@ == BoundModel::Le(0))]
431    pub const LE_ZERO: Bound = Bound(1);
432    /// The strict bound `< 0`.
433    #[ensures(Bound::LT_ZERO@ == BoundModel::Lt(0))]
434    pub const LT_ZERO: Bound = Bound(0);
435
436    /// Constructs the non-strict upper bound `<= c`.
437    ///
438    /// Returns [`Error::Range`] if `c` is outside the supported interval
439    /// from [`MIN_CONSTANT`] to [`MAX_CONSTANT`].
440    #[check(terminates)]
441    #[ensures(match result {
442        Ok(b) => BoundModel::in_range(c@) && b@ == BoundModel::Le(c@),
443        Err(e) => !BoundModel::in_range(c@) && e == Error::Range,
444    })]
445    pub const fn le(c: i32) -> Result<Bound, Error> {
446        if MIN_CONSTANT <= c && c <= MAX_CONSTANT {
447            Ok(Bound(2 * c + 1))
448        } else {
449            Err(Error::Range)
450        }
451    }
452
453    /// Constructs the strict upper bound `< c`.
454    ///
455    /// Returns [`Error::Range`] if `c` is outside the supported interval
456    /// from [`MIN_CONSTANT`] to [`MAX_CONSTANT`].
457    #[check(terminates)]
458    #[ensures(match result {
459        Ok(b) => BoundModel::in_range(c@) && b@ == BoundModel::Lt(c@),
460        Err(e) => !BoundModel::in_range(c@) && e == Error::Range,
461    })]
462    pub const fn lt(c: i32) -> Result<Bound, Error> {
463        if MIN_CONSTANT <= c && c <= MAX_CONSTANT {
464            Ok(Bound(2 * c))
465        } else {
466            Err(Error::Range)
467        }
468    }
469
470    /// Whether this is `∞`.
471    #[check(terminates)]
472    #[ensures(result == (self@ == BoundModel::Inf))]
473    pub const fn is_infinite(self) -> bool {
474        self.0 == INF
475    }
476
477    /// Returns whether the bound uses `<` rather than `<=`.
478    ///
479    /// An unrestricted (infinite) bound is not strict.
480    #[check(terminates)]
481    #[ensures(result == match self@ { BoundModel::Lt(_) => true, _ => false })]
482    pub const fn is_strict(self) -> bool {
483        low_bit(self.0);
484        self.0 != INF && self.0 & 1 == 0
485    }
486
487    /// Returns the integer constant of a finite strict or non-strict
488    /// bound, or `None` for an unrestricted (infinite) bound.
489    #[check(terminates)]
490    #[ensures(match self@ {
491        BoundModel::Lt(c) | BoundModel::Le(c) => match result { Some(r) => r@ == c, None => false },
492        BoundModel::Inf => result == None,
493    })]
494    pub const fn constant(self) -> Option<i32> {
495        if self.0 == INF {
496            None
497        } else {
498            low_bit(self.0);
499            Some(self.0 >> 1)
500        }
501    }
502
503    /// Adds two bounds, as when chaining clock-difference inequalities.
504    ///
505    /// The finite constants are added; the result is strict (`<`) if
506    /// either operand is strict. If either bound is infinite, so is the
507    /// sum. Returns [`Error::Range`] if a finite sum cannot be represented;
508    /// it is never saturated to infinity.
509    #[check(terminates)]
510    #[ensures(match result {
511        Ok(r) => self@.add_in_range(other@) && r@ == self@.add(other@),
512        Err(e) => !self@.add_in_range(other@) && e == Error::Range,
513    })]
514    pub const fn checked_add(self, other: Bound) -> Result<Bound, Error> {
515        if self.0 == INF || other.0 == INF {
516            return Ok(Bound::INFINITY);
517        }
518        low_bit(self.0);
519        low_bit(other.0);
520        // Packed finite-bound addition. No overflow: both codes are in
521        // [MIN_CODE, MAX_CODE] ⊂ (−2³⁰, 2³⁰).
522        let r = (self.0 + other.0) - weak_or(self.0, other.0);
523        if MIN_CODE <= r && r <= MAX_CODE {
524            Ok(Bound(r))
525        } else {
526            Err(Error::Range)
527        }
528    }
529}
530
531// ----- adding a weak constant (temporal operations) -----
532
533/// `b + via` for a finite **weak** `via = Le c`: the constant of a finite
534/// `b` shifts by `c` and its strictness is kept (the code shifts by `2c`);
535/// `∞` stays `∞`.
536///
537/// **Precondition:** the sum is representable (trivially so if `b = ∞`).
538/// The reset of `ops::temporal` establishes it from the `Dbm` invariant
539/// (`ops::temporal::proof::reset_representable`). No `i32` overflow: `b`
540/// (with `∞` masked to 0) and `2c` both lie in `(−2³⁰, 2³⁰)`.
541///
542/// Branch-free, so that row loops vectorize. Proved: the result is
543/// exactly `via + b` in the model.
544#[check(terminates)]
545#[requires(exists<c: Int> via@ == BoundModel::Le(c))]
546#[requires(via@.add_in_range(b@))]
547#[ensures(result@ == via@.add(b@))]
548#[inline]
549pub(crate) fn add_weak(b: Bound, via: Bound) -> Bound {
550    snapshot!(enc_view(via));
551    let fin = b.0 != INF;
552    proof_assert!(fin ==> { enc_view(b); enc_range(via@.add(b@)); true });
553    let sum = if fin { b.0 } else { 0 } + (via.0 - 1);
554    proof_assert!(fin ==> sum@ == enc(via@.add(b@)));
555    Bound(if fin { sum } else { INF })
556}
557
558/// `dst[l] := via + src[l]` for every `l` ([`add_weak`], whose precondition
559/// must hold for every entry). Branch-free; it vectorizes.
560#[check(terminates)]
561#[requires(dst@.len() == src@.len())]
562#[requires(exists<c: Int> via@ == BoundModel::Le(c))]
563#[requires(forall<l: Int> 0 <= l && l < src@.len() ==> via@.add_in_range(src@[l]@))]
564#[ensures((^dst)@.len() == dst@.len())]
565#[ensures(forall<l: Int> 0 <= l && l < dst@.len() ==> (^dst)@[l]@ == via@.add(src@[l]@))]
566#[inline]
567pub(crate) fn add_weak_row(dst: &mut [Bound], via: Bound, src: &[Bound]) {
568    let old = snapshot!(dst@);
569    // `n ≤ src.len()` lets the compiler drop the bounds checks.
570    let n = if dst.len() < src.len() {
571        dst.len()
572    } else {
573        src.len()
574    };
575    let mut l: usize = 0;
576    #[invariant(l@ <= n@ && n@ == old.len() && dst@.len() == old.len())]
577    #[invariant(forall<k: Int> 0 <= k && k < l@ ==> dst@[k]@ == via@.add(src@[k]@))]
578    #[variant(n@ - l@)]
579    while l < n {
580        dst[l] = add_weak(src[l], via);
581        l += 1;
582    }
583}
584
585// ----- row relaxation (incremental closure) -----
586
587/// The packed code of a finite model bound, without range restriction:
588/// `Lt c ↦ 2c`, `Le c ↦ 2c + 1`.
589#[logic(open)]
590pub fn enc(m: BoundModel) -> Int {
591    match m {
592        BoundModel::Lt(c) => 2 * c,
593        BoundModel::Le(c) => 2 * c + 1,
594        BoundModel::Inf => 0,
595    }
596}
597
598/// `enc` is injective and order-preserving on finite bounds, and a valid
599/// finite `Bound` stores exactly `enc` of its model.
600#[logic]
601#[requires(x != BoundModel::Inf && y != BoundModel::Inf)]
602#[ensures(x.le(y) == (enc(x) <= enc(y)))]
603#[ensures((enc(x) == enc(y)) == (x == y))]
604pub fn enc_order(x: BoundModel, y: BoundModel) {}
605
606/// A valid finite bound stores `enc` of its model.
607#[logic]
608#[requires(inv(b) && b@ != BoundModel::Inf)]
609#[ensures(enc(b@) == b.deep_model())]
610pub fn enc_view(b: Bound) {}
611
612/// `b`'s model is representable iff its code lies in `[MIN_CODE, MAX_CODE]`.
613#[logic]
614#[requires(m != BoundModel::Inf)]
615#[ensures(m.representable() == (MIN_CODE@ <= enc(m) && enc(m) <= MAX_CODE@))]
616pub fn enc_range(m: BoundModel) {}
617
618/// `via + s` is strictly tighter than `cur`: the entry must change.
619#[logic(open)]
620pub fn relax_needed(cur: BoundModel, via: BoundModel, s: BoundModel) -> bool {
621    s != BoundModel::Inf && !cur.le(via.add(s))
622}
623
624/// One entry of [`relax_row`]: `new = via + s` if that sum is needed and
625/// representable, otherwise `new = cur`.
626#[logic(open)]
627pub fn relax_entry(cur: BoundModel, via: BoundModel, s: BoundModel, new: BoundModel) -> bool {
628    if relax_needed(cur, via, s) && via.add_in_range(s) {
629        new == via.add(s)
630    } else {
631        new == cur
632    }
633}
634
635/// `dst[l] := min(dst[l], via + src[l])` for every `l` with `src[l]`
636/// finite (one row of a Floyd–Warshall-style relaxation through a finite
637/// `via`). Returns `true` iff some needed sum is unrepresentable; that entry
638/// is then left unchanged, so `dst` stays valid, and the caller reports
639/// `Err(Range)`.
640///
641/// The loop is branch-free so that it vectorizes (as the incremental closure
642/// does). An infinite `src[l]` is replaced by 0 before adding,
643/// so no intermediate value can overflow `i32`. Unrepresentable needed sums
644/// are *counted* in a `u32` rather than OR-ed into a `bool`: the loop-carried
645/// `bool` reduction vectorized poorly and cost about 6 ns per tightening step
646/// at `d = 5` (benchmark investigation).
647#[check(terminates)]
648#[requires(dst@.len() == src@.len())]
649#[requires(dst@.len() <= u32::MAX@)]
650#[requires(via@ != BoundModel::Inf)]
651#[ensures((^dst)@.len() == dst@.len())]
652#[ensures(forall<l: Int> 0 <= l && l < dst@.len() ==>
653    relax_entry(dst@[l]@, via@, src@[l]@, (^dst)@[l]@))]
654#[ensures(result ==> exists<l: Int> 0 <= l && l < dst@.len()
655    && relax_needed(dst@[l]@, via@, src@[l]@) && !via@.add_in_range(src@[l]@))]
656#[ensures(!result ==> forall<l: Int> 0 <= l && l < dst@.len() ==>
657    !(relax_needed(dst@[l]@, via@, src@[l]@) && !via@.add_in_range(src@[l]@)))]
658#[inline]
659// Explicit, non-short-circuiting forms: they keep the loop branch-free (it
660// must vectorize) and are what the proof reasons about.
661#[allow(clippy::manual_range_contains, clippy::assign_op_pattern)]
662pub(crate) fn relax_row(dst: &mut [Bound], via: Bound, src: &[Bound]) -> bool {
663    let old = snapshot!(dst@);
664    // `n ≤ src.len()` lets the compiler drop the bounds checks.
665    let n = if dst.len() < src.len() {
666        dst.len()
667    } else {
668        src.len()
669    };
670    let v = via.0;
671    low_bit(v);
672    snapshot!(enc_view(via));
673    let mut bad: u32 = 0;
674    let mut l: usize = 0;
675    #[invariant(l@ <= n@ && n@ == old.len() && dst@.len() == old.len())]
676    #[invariant(inv(dst))]
677    #[invariant(forall<k: Int> 0 <= k && k < l@ ==>
678        relax_entry(old[k]@, via@, src@[k]@, dst@[k]@))]
679    #[invariant(forall<k: Int> l@ <= k && k < n@ ==> dst@[k] == old[k])]
680    #[invariant(bad@ <= l@)]
681    #[invariant((bad@ > 0) == exists<k: Int> 0 <= k && k < l@
682        && relax_needed(old[k]@, via@, src@[k]@) && !via@.add_in_range(src@[k]@))]
683    #[variant(n@ - l@)]
684    while l < n {
685        let s = src[l].0;
686        let fin = s != INF;
687        let s2 = if fin { s } else { 0 };
688        low_bit(s2);
689        let sum = (v + s2) - weak_or(v, s2);
690        let cur = dst[l].0;
691        let tighter = fin & (sum < cur);
692        let ok = (MIN_CODE <= sum) & (sum <= MAX_CODE);
693        proof_assert!(fin ==> {
694            enc_view(src@[l@]); enc_view(dst@[l@]);
695            enc_order(via@.add(src@[l@]@), dst@[l@]@);
696            enc_range(via@.add(src@[l@]@));
697            sum@ == enc(via@.add(src@[l@]@))
698                && (tighter == relax_needed(dst@[l@]@, via@, src@[l@]@))
699                && (ok == via@.add_in_range(src@[l@]@))
700        });
701        bad = bad + (tighter & !ok) as u32;
702        let new = Bound(if tighter & ok { sum } else { cur });
703        proof_assert!(tighter && ok ==> {
704            enc_view(new); enc_order(new@, via@.add(src@[l@]@)); new@ == via@.add(src@[l@]@)
705        });
706        dst[l] = new;
707        l += 1;
708    }
709    bad != 0
710}
711
712/// Any clock index, including the reference clock `x₀` (index 0).
713#[derive(Clone, Copy, PartialEq, Eq, Debug)]
714#[cfg_attr(not(creusot), derive(Hash))]
715pub struct Clock(u32);
716
717ord_by_deep_model!(Clock);
718
719impl Invariant for Clock {
720    #[logic(open(self))]
721    fn invariant(self) -> bool {
722        pearlite! { self.0@ <= MAX_VARIABLES@ }
723    }
724}
725
726impl DeepModel for Clock {
727    type DeepModelTy = Int;
728
729    #[logic(open(self))]
730    fn deep_model(self) -> Int {
731        pearlite! { self.0@ }
732    }
733}
734
735impl View for Clock {
736    type ViewTy = Int;
737
738    /// The clock index.
739    #[logic(open(self))]
740    fn view(self) -> Int {
741        pearlite! { self.0@ }
742    }
743}
744
745impl Clock {
746    /// The reference clock `x₀`.
747    #[ensures(Clock::ZERO@ == 0)]
748    pub const ZERO: Clock = Clock(0);
749
750    /// The clock with this index. `None` if `index > MAX_VARIABLES`.
751    #[check(terminates)]
752    #[ensures(match result {
753        Some(x) => index@ <= MAX_VARIABLES@ && x@ == index@,
754        None => index@ > MAX_VARIABLES@,
755    })]
756    pub const fn new(index: usize) -> Option<Clock> {
757        if index <= MAX_VARIABLES {
758            Some(Clock(index as u32))
759        } else {
760            None
761        }
762    }
763
764    /// The index (0 for the reference clock).
765    #[check(terminates)]
766    #[ensures(result@ == self@)]
767    pub const fn index(self) -> usize {
768        self.0 as usize
769    }
770}
771
772/// An actual clock (index 1 or greater), used for resetting or freeing a clock.
773///
774/// Unlike [`Clock`], a `Variable` cannot represent the reference clock:
775/// `Variable::new(0)` returns `None`. Convert a variable to a [`Clock`]
776/// with `.into()` to use it in a [`Constraint`].
777#[derive(Clone, Copy, PartialEq, Eq, Debug)]
778#[cfg_attr(not(creusot), derive(Hash))]
779pub struct Variable(u32);
780
781ord_by_deep_model!(Variable);
782
783impl Invariant for Variable {
784    #[logic(open(self))]
785    fn invariant(self) -> bool {
786        pearlite! { 1 <= self.0@ && self.0@ <= MAX_VARIABLES@ }
787    }
788}
789
790impl DeepModel for Variable {
791    type DeepModelTy = Int;
792
793    #[logic(open(self))]
794    fn deep_model(self) -> Int {
795        pearlite! { self.0@ }
796    }
797}
798
799impl View for Variable {
800    type ViewTy = Int;
801
802    /// The clock index.
803    #[logic(open(self))]
804    fn view(self) -> Int {
805        pearlite! { self.0@ }
806    }
807}
808
809impl Variable {
810    /// The actual clock with this index. `None` if `index == 0` or
811    /// `index > MAX_VARIABLES`.
812    #[check(terminates)]
813    #[ensures(match result {
814        Some(x) => 1 <= index@ && index@ <= MAX_VARIABLES@ && x@ == index@,
815        None => index@ == 0 || index@ > MAX_VARIABLES@,
816    })]
817    pub const fn new(index: usize) -> Option<Variable> {
818        if 1 <= index && index <= MAX_VARIABLES {
819            Some(Variable(index as u32))
820        } else {
821            None
822        }
823    }
824
825    /// The index (at least 1).
826    #[check(terminates)]
827    #[ensures(result@ == self@ && 1 <= result@)]
828    pub const fn index(self) -> usize {
829        self.0 as usize
830    }
831}
832
833impl From<Variable> for Clock {
834    /// The clock with the same index.
835    #[check(terminates)]
836    #[ensures(result@ == x@)]
837    fn from(x: Variable) -> Clock {
838        Clock(x.0)
839    }
840}
841
842/// An actual clock is never the reference clock.
843#[logic]
844#[requires(inv(x))]
845#[ensures(x@ != Clock::ZERO@)]
846pub fn variable_not_zero(x: Variable) {}
847
848/// A constraint on the difference between two clocks.
849///
850/// [`Constraint::le`] represents `x_i - x_j <= c` and [`Constraint::lt`]
851/// represents `x_i - x_j < c`. Clock 0 is the fixed reference
852/// [`Clock::ZERO`]. Constructing a constraint does not validate it against
853/// a particular DBM; that happens when the constraint is applied.
854///
855/// # Example
856///
857/// ```
858/// use clock_dbm::{Clock, Constraint};
859/// # fn main() -> Result<(), clock_dbm::Error> {
860/// let x = Clock::new(1).unwrap();
861/// let y = Clock::new(2).unwrap();
862/// let x_at_least_two = Constraint::le(Clock::ZERO, x, -2)?;
863/// let x_minus_y_below_three = Constraint::lt(x, y, 3)?;
864/// assert_eq!(x_at_least_two.i(), Clock::ZERO);
865/// assert_eq!(x_minus_y_below_three.j(), y);
866/// # Ok(())
867/// # }
868/// ```
869#[derive(Clone, Copy, PartialEq, Eq, Debug)]
870#[cfg_attr(not(creusot), derive(Hash))]
871pub struct Constraint {
872    i: Clock,
873    j: Clock,
874    bound: Bound,
875}
876
877impl DeepModel for Constraint {
878    type DeepModelTy = (Int, Int, Int);
879
880    #[logic(open(self))]
881    fn deep_model(self) -> (Int, Int, Int) {
882        pearlite! { (self.i.deep_model(), self.j.deep_model(), self.bound.deep_model()) }
883    }
884}
885
886impl View for Constraint {
887    type ViewTy = (Int, Int, BoundModel);
888
889    /// `(i, j, b)`: the indices and the model of the bound.
890    #[logic(open(self))]
891    fn view(self) -> (Int, Int, BoundModel) {
892        pearlite! { (self.i@, self.j@, self.bound@) }
893    }
894}
895
896impl Constraint {
897    /// Constructs a constraint on `clock i - clock j` using `bound`.
898    ///
899    /// The bound specifies either `< c`, `<= c`, or no restriction.
900    /// Both clocks may be the same; validity for a particular zone is
901    /// checked when the constraint is applied.
902    #[check(terminates)]
903    #[ensures(result@ == (i@, j@, bound@))]
904    pub const fn new(i: Clock, j: Clock, bound: Bound) -> Constraint {
905        Constraint { i, j, bound }
906    }
907
908    /// Constructs the constraint `clock i - clock j <= c`.
909    ///
910    /// Returns [`Error::Range`] if `c` is outside the supported bound range.
911    #[check(terminates)]
912    #[ensures(match result {
913        Ok(g) => BoundModel::in_range(c@) && g@ == (i@, j@, BoundModel::Le(c@)),
914        Err(e) => !BoundModel::in_range(c@) && e == Error::Range,
915    })]
916    pub const fn le(i: Clock, j: Clock, c: i32) -> Result<Constraint, Error> {
917        match Bound::le(c) {
918            Ok(bound) => Ok(Constraint { i, j, bound }),
919            Err(e) => Err(e),
920        }
921    }
922
923    /// Constructs the constraint `clock i - clock j < c`.
924    ///
925    /// Returns [`Error::Range`] if `c` is outside the supported bound range.
926    #[check(terminates)]
927    #[ensures(match result {
928        Ok(g) => BoundModel::in_range(c@) && g@ == (i@, j@, BoundModel::Lt(c@)),
929        Err(e) => !BoundModel::in_range(c@) && e == Error::Range,
930    })]
931    pub const fn lt(i: Clock, j: Clock, c: i32) -> Result<Constraint, Error> {
932        match Bound::lt(c) {
933            Ok(bound) => Ok(Constraint { i, j, bound }),
934            Err(e) => Err(e),
935        }
936    }
937
938    /// The minuend clock `x_i`.
939    #[check(terminates)]
940    #[ensures(result@ == self@.0)]
941    pub const fn i(self) -> Clock {
942        self.i
943    }
944
945    /// The subtrahend clock `x_j`.
946    #[check(terminates)]
947    #[ensures(result@ == self@.1)]
948    pub const fn j(self) -> Clock {
949        self.j
950    }
951
952    /// Returns the strict, non-strict, or infinite bound on the difference
953    /// between the two clocks.
954    #[check(terminates)]
955    #[ensures(result@ == self@.2)]
956    pub const fn bound(self) -> Bound {
957        self.bound
958    }
959}
960
961#[cfg(test)]
962mod tests {
963    use super::*;
964
965    fn le(c: i32) -> Bound {
966        Bound::le(c).unwrap()
967    }
968    fn lt(c: i32) -> Bound {
969        Bound::lt(c).unwrap()
970    }
971
972    #[test]
973    fn codes() {
974        assert_eq!(lt(3).0, 6);
975        assert_eq!(le(3).0, 7);
976        assert_eq!(lt(-3).0, -6);
977        assert_eq!(le(-3).0, -5);
978        assert_eq!(Bound::INFINITY.0, 0x7FFF_FFFE);
979        assert_eq!(Bound::LE_ZERO, le(0));
980        assert_eq!(Bound::LT_ZERO, lt(0));
981    }
982
983    #[test]
984    fn literal_constants() {
985        const {
986            assert!(MAX_CONSTANT == (1 << 29) - 1);
987            assert!(MIN_CONSTANT == -MAX_CONSTANT);
988            assert!(MIN_CODE == 2 * MIN_CONSTANT);
989            assert!(MAX_CODE == 2 * MAX_CONSTANT + 1);
990            assert!(MAX_VARIABLES == 46_339);
991            // Dimension safety: (n+1)² < 2³¹.
992            assert!(((MAX_VARIABLES + 1) as u64).pow(2) < 1 << 31);
993        }
994    }
995
996    #[test]
997    fn relax_row_cases() {
998        let inf = Bound::INFINITY;
999        // dst = [Le 5, ∞, Lt 3, ∞, Le 0, Le 1], via = Le 2.
1000        let mut dst = [le(5), inf, lt(3), inf, le(0), le(1)];
1001        let src = [le(1), le(4), le(1), inf, lt(-2), le(-1)];
1002        assert!(!relax_row(&mut dst, le(2), &src));
1003        // 2+1 = Le 3 < Le 5; ∞ → Le 6; Le 3 not tighter than Lt 3; ∞ source
1004        // skipped; Lt 0 < Le 0; Le 1 is not strictly tighter than Le 1.
1005        assert_eq!(dst, [le(3), le(6), lt(3), inf, lt(0), le(1)]);
1006
1007        // A needed unrepresentable sum is flagged and leaves the entry
1008        // unchanged; an unneeded one (above MAX, finite current) is not.
1009        let big = le(MAX_CONSTANT);
1010        let mut dst = [inf, le(0), lt(-MAX_CONSTANT)];
1011        let src = [big, big, lt(MIN_CONSTANT)];
1012        assert!(relax_row(&mut dst, le(1), &src));
1013        assert_eq!(dst[0], inf);
1014        assert_eq!(dst[1], le(0));
1015        let mut dst = [le(0)];
1016        assert!(!relax_row(&mut dst, le(1), &[big]));
1017        assert_eq!(dst, [le(0)]);
1018        // Below MIN_CONSTANT: tighter than everything, so needed and flagged.
1019        let mut dst = [lt(MIN_CONSTANT)];
1020        assert!(relax_row(&mut dst, le(-1), &[le(MIN_CONSTANT)]));
1021        assert_eq!(dst, [lt(MIN_CONSTANT)]);
1022    }
1023
1024    #[test]
1025    fn codes_at_limits() {
1026        assert_eq!(le(MAX_CONSTANT).0, (1 << 30) - 1);
1027        assert_eq!(lt(MAX_CONSTANT).0, (1 << 30) - 2);
1028        assert_eq!(lt(MIN_CONSTANT).0, -(1 << 30) + 2);
1029        assert_eq!(le(MIN_CONSTANT).0, -(1 << 30) + 3);
1030        assert_eq!(MIN_CODE, lt(MIN_CONSTANT).0);
1031        assert_eq!(MAX_CODE, le(MAX_CONSTANT).0);
1032        // Headroom: valid codes are below the sentinel's neighbor, and the
1033        // sum of two codes (before the strictness correction) fits in i32.
1034        const {
1035            assert!(MAX_CODE < INF - 1);
1036            assert!(2 * (MIN_CODE as i64) > i32::MIN as i64);
1037            assert!(2 * (MAX_CODE as i64) < i32::MAX as i64);
1038        }
1039    }
1040}