Skip to main content

clock_dbm/
dbm.rs

1//! Canonical zones, constructors, and workspaces.
2//!
3//! Use [`Dbm::zero`] for an all-zero valuation, [`Dbm::universe`] for all
4//! nonnegative valuations, [`Dbm::empty`] for an empty zone, or
5//! [`Dbm::try_from_constraints`] to construct a constrained zone.
6//!
7//! An inconsistent guard produces a successful empty zone; invalid arguments
8//! and arithmetic range failures instead return an error. Every successful
9//! transformation returns a canonical or empty zone. [`Workspace`] is
10//! reusable temporary storage for operations that request it.
11
12// Source-level implementation and proof notes (not part of public API Rustdoc).
13// Canonical DBM storage, constructors, the private working matrix and full
14// Floyd–Warshall closure.
15//
16// A DBM over `n` nonnegative-real clocks has matrix dimension `n + 1`,
17// including the reference clock fixed at zero. `∅_d` denotes an empty
18// zone with matrix dimension `d`.
19//
20// # Storage
21//
22// A [`Dbm`] over `n` actual clocks is a flat, row-major buffer of `(n+1)²`
23// packed [`Bound`]s: entry `(i, j)` (the bound on `xᵢ − xⱼ`, index 0 being
24// the reference clock) lives at `i·(n+1) + j`. The
25// empty zone `∅_{n+1}` keeps `n` and stores **no** entries, so
26// `is_empty()` is `entries.is_empty()` and `Eq`/`Hash` compare
27// dimension plus canonical matrix.
28//
29// Every public `Dbm` is either empty or canonical and nonempty.
30// Operations work on a crate-private `Matrix` that may be temporarily
31// noncanonical. The only ways back to a `Dbm`
32// are `Matrix::close` (full closure) and `Matrix::publish_canonical`
33// (for in-place kernels that preserve canonicity). A working matrix is never
34// returned to a caller; on `Err` it is dropped.
35//
36// # Interface for `ops::*`
37//
38// Operation modules add `impl Dbm` blocks in their own files using
39// only: `Dbm::into_matrix`, `Dbm::entry`, `Dbm::check_clock`,
40// `Dbm::check_variables`, `Dbm::empty_like`, and the `Matrix` methods
41// `universe`, `dimension`, `get`, `set`, `tighten`, `relax_row`, `close`
42// and `publish_canonical`. The temporal operations also use the
43// whole-row/column updates `add_weak_to_row`, `add_weak_to_column`,
44// `copy_column`, `fill_column` and `fill_row`, proved with exact frame
45// conditions. The relations use `Dbm::entries_le`, `Matrix::meet`,
46// `Matrix::close_pivots` and `Workspace::reset_touched`, proved with
47// `Matrix::meet_ready` and the touched-pivot lemmas of `dbm/proof.rs`.
48// ExtraM uses `Matrix::close_pivots` with every pivot selected
49// (`Workspace::select_all`, `Matrix::full_pivot_ready`) and the equality
50// helper `same` for exact bound equality.
51//
52// # Verification status
53//
54// Creusot proves this module, on the shipped bodies:
55//
56// - **safety:** no panic (every index is in bounds), no arithmetic overflow
57//   (index arithmetic stays below `d²`, B5), termination, and the exact
58//   frame conditions of `get`/`set`/`tighten`;
59// - **public invariant:** every [`Dbm`] is empty or canonical (C2–C4;
60//   C1 is the
61//   `Bound` invariant; C5 follows by `proof::canonical_nonempty`). Every
62//   constructor, `Clone`, `Matrix::close` and `Matrix::publish_canonical`
63//   (under its `canonical` precondition) establish it;
64// - **closure correctness:** `Matrix::close` returns a `Dbm`
65//   with exactly the matrix's zone over nonnegative real valuations (so
66//   `∅_d` iff that zone is empty, strict-zero cycles included), or
67//   `Err(Range)` only when an exact intermediate sum is unrepresentable;
68//   `Err(Range)` is impossible when every finite input constant has
69//   magnitude `≤ B` with `B · 2^d ≤ MAX_CONSTANT`;
70// - **semantic equality:** two valid DBMs with
71//   the same number of variables have equal storage, i.e. `==`, iff they
72//   denote the same zone (`Dbm::eq_semantic`). The core is the uniqueness
73//   of canonical forms, `proof::canonical_unique`.
74//
75// The ghost layer is `dbm/proof.rs`. The linear range premise of
76// a proposed linear sufficient-range premise is **not** proved; see `verification/PROOF_STATUS.md`.
77
78// `?` and the default `PartialOrd::lt` are not terminating calls for Creusot,
79// so this module matches on `Result` and compares bounds through `tighter`.
80#![allow(clippy::question_mark)]
81
82use crate::bounds::{Bound, BoundModel, Clock, add_weak, add_weak_row, relax_row};
83#[cfg(creusot)]
84use crate::bounds::{relax_entry, relax_needed};
85#[cfg(creusot)]
86use proof::{cell, cell_all, cell_read, cell_set};
87// Lemmas (logic functions) exist only under Creusot.
88#[cfg(creusot)]
89use crate::bounds::{
90    add_comm_unit, add_sound, below_le_zero_unsat, le_total, le_trans, order_refines,
91    view_injective,
92};
93use crate::error::Error;
94use crate::ops::constraints::below_le_zero;
95#[cfg(creusot)]
96use creusot_std::logic::real::Real;
97use creusot_std::{
98    invariant::{Invariant, inv},
99    prelude::{Clone, Default, PartialEq, *},
100};
101
102/// Maximum number of actual clocks supported by a DBM. The reference
103/// clock is additional and does not count toward this limit.
104pub const MAX_VARIABLES: usize = 46_339;
105
106/// Largest matrix dimension, `MAX_VARIABLES + 1` (a literal for Creusot,
107/// checked by a unit test). Used only in specifications.
108#[cfg_attr(not(creusot), allow(dead_code))]
109const MAX_DIMENSION: usize = 46_340;
110
111/// `a ≺ b`: `a` is strictly tighter than `b` (B2: the code order). Written
112/// with the verified `Ord::cmp`.
113#[check(terminates)]
114#[ensures(result == (a.deep_model() < b.deep_model()))]
115pub(crate) fn tighter(a: Bound, b: Bound) -> bool {
116    matches!(a.cmp(&b), core::cmp::Ordering::Less)
117}
118
119/// `a = b` (the derived `Eq`), written with the verified `Ord::cmp` like
120/// [`tighter`], because the derived `PartialEq` is not a terminating call
121/// for Creusot. Used by ExtraM.
122#[check(terminates)]
123#[ensures(result == (a.deep_model() == b.deep_model()))]
124#[cfg_attr(not(creusot), allow(dead_code))]
125pub(crate) fn same(a: Bound, b: Bound) -> bool {
126    matches!(a.cmp(&b), core::cmp::Ordering::Equal)
127}
128
129// ----- index arithmetic (B5) -----
130
131/// The square of a dimension fits comfortably in `usize` (and in `u32`).
132#[logic]
133#[requires(0 <= d && d <= MAX_DIMENSION@)]
134#[ensures(0 <= d * d && d * d <= MAX_DIMENSION@ * MAX_DIMENSION@)]
135#[ensures(MAX_DIMENSION@ * MAX_DIMENSION@ < usize::MAX@)]
136fn square_fits(d: Int) {
137    pearlite! { proof_assert!(d * d <= d * MAX_DIMENSION@); }
138}
139
140/// In-bounds coordinates map into the flat storage.
141#[logic]
142#[requires(0 <= i && i < d && 0 <= j && j < d)]
143#[ensures(0 <= i * d && i * d + j < d * d)]
144fn index_in_bounds(d: Int, i: Int, j: Int) {
145    pearlite! { proof_assert!(i * d + d <= d * d); }
146}
147
148/// Row-major index arithmetic is injective on in-bounds coordinates.
149#[logic]
150#[requires(0 <= i && i < d && 0 <= j && j < d)]
151#[requires(0 <= k && k < d && 0 <= l && l < d)]
152#[ensures((i * d + j == k * d + l) == (i == k && j == l))]
153fn index_injective(d: Int, i: Int, j: Int, k: Int, l: Int) {
154    pearlite! {
155        if i < k {
156            proof_assert!(i * d + d <= k * d);
157        } else if k < i {
158            proof_assert!(k * d + d <= i * d);
159        }
160    }
161}
162
163/// Rows are contiguous and ordered: entry `(k, l)` lies before, inside or
164/// after row `r` according to `k` versus `r`.
165#[logic]
166#[requires(0 <= l && l < d && 0 <= k && 0 <= r)]
167#[ensures(k < r ==> k * d + l < r * d)]
168#[ensures(r < k ==> r * d + d <= k * d + l)]
169#[ensures(k == r ==> r * d <= k * d + l && k * d + l < r * d + d)]
170fn row_cmp(d: Int, k: Int, l: Int, r: Int) {
171    pearlite! {
172        if k < r {
173            proof_assert!(k * d + d <= r * d);
174        } else if r < k {
175            proof_assert!(r * d + d <= k * d);
176        }
177    }
178}
179
180/// Every flat index of a `d × d` matrix is `i·d + j` for in-bounds `i, j`.
181#[logic]
182#[requires(1 <= d && 0 <= x && x < d * d)]
183#[ensures(0 <= x.div_euclid(d) && x.div_euclid(d) < d)]
184#[ensures(0 <= x.rem_euclid(d) && x.rem_euclid(d) < d)]
185#[ensures(x == x.div_euclid(d) * d + x.rem_euclid(d))]
186fn index_cover(d: Int, x: Int) {
187    pearlite! {
188        if x.div_euclid(d) >= d {
189            proof_assert!(x.div_euclid(d) * d >= d * d);
190        }
191    }
192}
193
194/// Storages with equal entries have equal codes (B1 per flat index).
195#[logic]
196#[requires(1 <= d && s.len() == d * d && t.len() == d * d && 0 <= x && x < d * d)]
197#[requires(inv(s[x]) && inv(t[x]))]
198#[requires(forall<i: Int, j: Int> 0 <= i && i < d && 0 <= j && j < d ==>
199    proof::ent(s, d, i, j) == proof::ent(t, d, i, j))]
200#[ensures(s[x].deep_model() == t[x].deep_model())]
201fn flat_eq_at(s: Seq<Bound>, t: Seq<Bound>, d: Int, x: Int) {
202    pearlite! {
203        index_cover(d, x);
204        proof::ent_read(s, d, x.div_euclid(d), x.rem_euclid(d));
205        proof::ent_read(t, d, x.div_euclid(d), x.rem_euclid(d));
206        view_injective(s[x], t[x])
207    }
208}
209
210/// `e[dst + l] := min(e[dst + l], via + e[src + l])` for `l < n`
211/// (`bounds::relax_row` on two disjoint ranges of one slice); every other
212/// element is unchanged.
213#[check(terminates)]
214#[requires(dst@ + n@ <= e@.len() && src@ + n@ <= e@.len())]
215#[requires(dst@ + n@ <= src@ || src@ + n@ <= dst@)]
216#[requires(n@ <= u32::MAX@)]
217#[requires(via@ != BoundModel::Inf)]
218#[ensures((^e)@.len() == e@.len())]
219#[ensures(forall<x: Int> 0 <= x && x < e@.len() ==>
220    if dst@ <= x && x < dst@ + n@ {
221        relax_entry(e@[x]@, via@, e@[src@ + (x - dst@)]@, (^e)@[x]@)
222    } else {
223        (^e)@[x] == e@[x]
224    })]
225#[ensures(result ==> exists<l: Int> 0 <= l && l < n@
226    && relax_needed(e@[dst@ + l]@, via@, e@[src@ + l]@) && !via@.add_in_range(e@[src@ + l]@))]
227#[ensures(!result ==> forall<l: Int> 0 <= l && l < n@ ==>
228    !(relax_needed(e@[dst@ + l]@, via@, e@[src@ + l]@) && !via@.add_in_range(e@[src@ + l]@)))]
229#[inline]
230fn relax_range(e: &mut [Bound], dst: usize, src: usize, n: usize, via: Bound) -> bool {
231    let old = snapshot!(e@);
232    if dst < src {
233        let (lo, hi) = e.split_at_mut(src);
234        let row = &mut lo[dst..dst + n];
235        let from = &hi[..n];
236        let r = relax_row(row, via, from);
237        proof_assert!(forall<l: Int> 0 <= l && l < n@ ==> (^lo)@[dst@ + l] == (^row)@[l]);
238        proof_assert!(forall<x: Int> 0 <= x && x < src@ && (x < dst@ || dst@ + n@ <= x) ==>
239            (^lo)@[x] == old[x]);
240        proof_assert!(forall<x: Int> 0 <= x && x < (^hi)@.len() ==> (^hi)@[x] == old[src@ + x]);
241        r
242    } else {
243        let (lo, hi) = e.split_at_mut(dst);
244        let row = &mut hi[..n];
245        let from = &lo[src..src + n];
246        let r = relax_row(row, via, from);
247        proof_assert!(forall<l: Int> 0 <= l && l < n@ ==> (^hi)@[l] == (^row)@[l]);
248        proof_assert!(forall<x: Int> n@ <= x && x < (^hi)@.len() ==> (^hi)@[x] == old[dst@ + x]);
249        proof_assert!(forall<x: Int> 0 <= x && x < dst@ ==> (^lo)@[x] == old[x]);
250        r
251    }
252}
253
254// ----- the public zone -----
255
256/// A canonical difference-bound matrix representing a set of clock valuations.
257///
258/// Each actual clock has a nonnegative real value; clock zero is the fixed
259/// reference clock. Each matrix entry bounds the difference between two
260/// clocks. A canonical matrix records the tightest implied bounds, while
261/// an empty DBM represents no possible valuations.
262///
263/// Construct with [`Dbm::zero`], [`Dbm::universe`], [`Dbm::empty`], or
264/// [`Dbm::try_from_constraints`]. Every successful transformation returns a
265/// canonical zone or an explicit empty zone. The number of actual clocks
266/// remains fixed; the reference clock has index 0 and is not counted in
267/// [`Dbm::variables`].
268///
269/// Two DBMs compare equal when they have the same number of clocks and
270/// represent the same zone, even if constructed from different constraints.
271/// Hashing is consistent with that equality.
272///
273/// # Example
274///
275/// ```
276/// use clock_dbm::{Clock, Constraint, Dbm};
277/// # fn main() -> Result<(), clock_dbm::Error> {
278/// let x = Clock::new(1).unwrap();
279/// let z = Dbm::universe(1)?
280///     .try_constrain(Constraint::le(x, Clock::ZERO, 4)?)?;
281/// assert!(!z.is_empty());
282/// assert_eq!(z.variables(), 1);
283/// assert_eq!(z.dimension(), 2);
284/// # Ok(())
285/// # }
286/// ```
287#[derive(Debug)]
288// `Hash` is not translated by Creusot (see `bounds.rs`). It is derived from
289// the same fields that the written-out `PartialEq` compares (`variables`,
290// then every entry), so `a == b ⇒ hash(a) == hash(b)`.
291#[cfg_attr(not(creusot), derive(Hash))]
292#[cfg_attr(not(creusot), allow(clippy::derived_hash_with_manual_eq))]
293pub struct Dbm {
294    variables: u32,
295    /// Row-major `(variables+1)²` entries, or none for the empty zone.
296    entries: Box<[Bound]>,
297}
298
299// Written out instead of derived: creusot-std's `Clone` for `Box<[T]>` does
300// not state the length, which the `Dbm` invariant needs; `to_vec` does.
301impl Clone for Dbm {
302    #[ensures(result == *self)]
303    fn clone(&self) -> Dbm {
304        let entries = self.entries.to_vec().into_boxed_slice();
305        proof_assert!(entries@.ext_eq(self.entries@));
306        Dbm {
307            variables: self.variables,
308            entries,
309        }
310    }
311}
312
313impl DeepModel for Dbm {
314    type DeepModelTy = (Int, Seq<Int>);
315
316    /// The number of variables and the packed codes; `Eq` works on it.
317    #[logic(open(self))]
318    fn deep_model(self) -> (Int, Seq<Int>) {
319        pearlite! { (self.variables@, *self.entries.deep_model()) }
320    }
321}
322
323// Written out instead of derived: the derived comparison of `Box<[Bound]>`
324// is an element-by-element loop with an early exit (std's `memcmp`
325// specialization covers primitive integers only), which made `==` the
326// dominant cost of small-zone transitions (benchmark investigation). This branch-free
327// accumulation vectorizes. It compares the same fields as the derive, so it
328// stays consistent with the derived `Hash`.
329impl PartialEq for Dbm {
330    // Not `#[check(terminates)]`: like the derive it replaces, it calls
331    // `Bound`'s derived `eq`, which Creusot does not mark as terminating.
332    #[ensures(result == (self.deep_model() == other.deep_model()))]
333    // The explicit, non-short-circuiting `&` keeps the loop branch-free.
334    #[allow(clippy::assign_op_pattern)]
335    fn eq(&self, other: &Dbm) -> bool {
336        if self.variables != other.variables || self.entries.len() != other.entries.len() {
337            return false;
338        }
339        let (a, b) = (&*self.entries, &*other.entries);
340        let mut eq = true;
341        let mut l: usize = 0;
342        #[invariant(l@ <= a@.len() && a@.len() == b@.len())]
343        #[invariant(eq == forall<k: Int> 0 <= k && k < l@ ==>
344            a@[k].deep_model() == b@[k].deep_model())]
345        #[variant(a@.len() - l@)]
346        while l < a.len() {
347            eq = eq & (a[l] == b[l]);
348            l += 1;
349        }
350        proof_assert!(eq == (*self.entries.deep_model()).ext_eq(*other.entries.deep_model()));
351        eq
352    }
353}
354
355impl Eq for Dbm {}
356
357impl Invariant for Dbm {
358    #[logic(open(self))]
359    fn invariant(self) -> bool {
360        pearlite! {
361            self.variables@ <= MAX_VARIABLES@
362                && (self.entries@.len() == 0
363                    || proof::canonical(self.entries@, self.variables@ + 1))
364        }
365    }
366}
367
368/// Checks `variables ≤ MAX_VARIABLES` and returns the dimension.
369#[check(terminates)]
370#[ensures(match result {
371    Ok(d) => variables@ <= MAX_VARIABLES@ && d@ == variables@ + 1,
372    Err(e) => variables@ > MAX_VARIABLES@ && e == Error::TooManyVariables { requested: variables },
373})]
374fn checked_dimension(variables: usize) -> Result<usize, Error> {
375    if variables <= MAX_VARIABLES {
376        Ok(variables + 1)
377    } else {
378        Err(Error::TooManyVariables {
379            requested: variables,
380        })
381    }
382}
383
384/// `d²` entries all equal to `fill`.
385#[check(terminates)]
386#[requires(1 <= d@ && d@ <= MAX_DIMENSION@)]
387#[ensures(result@.len() == d@ * d@)]
388#[ensures(forall<x: Int> 0 <= x && x < result@.len() ==> result@[x] == fill)]
389fn filled(d: usize, fill: Bound) -> Box<[Bound]> {
390    snapshot!(square_fits(d@));
391    let len = d * d;
392    // A push loop rather than `vec![fill; len]`: creusot-std does not mark
393    // `vec::from_elem` as terminating.
394    let mut v = Vec::with_capacity(len);
395    #[invariant(v@.len() <= len@)]
396    #[invariant(forall<x: Int> 0 <= x && x < v@.len() ==> v@[x] == fill)]
397    #[variant(len@ - v@.len())]
398    while v.len() < len {
399        v.push(fill);
400    }
401    v.into_boxed_slice()
402}
403
404/// The entries of `universe`: `Le 0` on row 0 and the diagonal, `∞` elsewhere.
405#[check(terminates)]
406#[requires(1 <= d@ && d@ <= MAX_DIMENSION@)]
407#[ensures(result@.len() == d@ * d@)]
408#[ensures(forall<i: Int, j: Int> 0 <= i && i < d@ && 0 <= j && j < d@ ==>
409    proof::ent(result@, d@, i, j) == proof::universe_entry(i, j))]
410fn universe_entries(d: usize) -> Box<[Bound]> {
411    let mut e = filled(d, Bound::INFINITY);
412    let len = snapshot!(d@ * d@);
413    proof_assert!(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==> {
414        proof::ent_read(e@, d@, a, b); proof::ent(e@, d@, a, b) == BoundModel::Inf
415    });
416    let mut i: usize = 0;
417    #[invariant(i@ <= d@)]
418    #[invariant(e@.len() == *len)]
419    #[invariant(inv(e))]
420    #[invariant(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==>
421        proof::ent(e@, d@, a, b) == if (a == 0 && b < i@) || (a == b && a < i@) {
422            BoundModel::Le(0)
423        } else {
424            BoundModel::Inf
425        })]
426    #[variant(d@ - i@)]
427    while i < d {
428        snapshot!(index_in_bounds(d@, 0, i@));
429        snapshot!(index_in_bounds(d@, i@, i@));
430        snapshot!(proof::ent_set_ref(e@, d@, i@, Bound::LE_ZERO));
431        let prev = snapshot!(e@);
432        e[i] = Bound::LE_ZERO;
433        proof_assert!(e@.ext_eq(prev.set(i@, Bound::LE_ZERO)));
434        snapshot!(proof::ent_set(e@, d@, i@, i@, Bound::LE_ZERO));
435        let prev = snapshot!(e@);
436        e[i * d + i] = Bound::LE_ZERO;
437        proof_assert!(e@.ext_eq(prev.set(i@ * d@ + i@, Bound::LE_ZERO)));
438        i += 1;
439    }
440    e
441}
442
443/// An empty boxed slice (no allocation).
444#[check(terminates)]
445#[ensures(result@.len() == 0)]
446fn no_entries() -> Box<[Bound]> {
447    Vec::new().into_boxed_slice()
448}
449
450impl Dbm {
451    /// Logical entry `(i, j)` of a nonempty DBM.
452    #[logic(open(self))]
453    pub(crate) fn at(self, i: Int, j: Int) -> Bound {
454        pearlite! { self.entries@[i * (self.variables@ + 1) + j] }
455    }
456
457    /// Logical number of actual clocks.
458    #[logic(open(self))]
459    pub(crate) fn variables_logic(self) -> Int {
460        pearlite! { self.variables@ }
461    }
462
463    /// Logical emptiness.
464    #[logic(open(self))]
465    pub(crate) fn is_empty_logic(self) -> bool {
466        pearlite! { self.entries@.len() == 0 }
467    }
468
469    /// `u ∈ γ(self)`: never for the empty zone, otherwise
470    /// `u` is a nonnegative valuation satisfying every entry.
471    #[logic(open(self))]
472    pub(crate) fn zone(self, u: proof::Val) -> bool {
473        pearlite! { !self.is_empty_logic() && proof::zone(self.entries@, self.variables@ + 1, u) }
474    }
475
476    /// The model matrix of the storage (meaningful when nonempty).
477    #[logic(open(self))]
478    pub(crate) fn mmat(self) -> proof::MMat {
479        pearlite! { proof::mat(self.entries@, self.variables@ + 1) }
480    }
481
482    /// A valid DBM in model terms: its entries are `mmat`, its zone is
483    /// `mzone(mmat)` unless empty, a nonempty DBM is canonical, and it is
484    /// empty iff its zone is (Inv C5).
485    #[logic]
486    #[requires(inv(self))]
487    #[ensures(self.variables_logic() <= MAX_VARIABLES@)]
488    #[ensures(!self.is_empty_logic() ==> forall<i: Int, j: Int>
489        0 <= i && i <= self.variables_logic() && 0 <= j && j <= self.variables_logic() ==>
490            self.at(i, j)@ == self.mmat()[i][j] && inv(self.at(i, j)))]
491    #[ensures(forall<u: proof::Val> self.zone(u) ==
492        (!self.is_empty_logic() && proof::mzone(self.mmat(), self.variables_logic() + 1, u)))]
493    #[ensures(!self.is_empty_logic() ==> proof::mcanonical(self.mmat(), self.variables_logic() + 1))]
494    #[ensures(self.is_empty_logic() == forall<u: proof::Val> !self.zone(u))]
495    pub(crate) fn model(self) {
496        pearlite! {
497            let d = self.variables@ + 1;
498            proof::mat_bridge(self.entries@, d);
499            if !self.is_empty_logic() {
500                proof::canonical_nonempty(self.entries@, d);
501                proof_assert!(forall<i: Int, j: Int> 0 <= i && i < d && 0 <= j && j < d ==> {
502                    proof::ent_read(self.entries@, d, i, j); index_in_bounds(d, i, j); true
503                });
504            }
505        }
506    }
507
508    /// Semantic equality (Theorem 3.1, B6–B7): two valid DBMs with the same
509    /// number of variables have equal storage (the `Eq` of [`Dbm`]) iff they
510    /// denote the same zone.
511    #[logic]
512    #[requires(inv(self) && inv(other))]
513    #[requires(self.variables_logic() == other.variables_logic())]
514    #[ensures((self.deep_model() == other.deep_model()) ==
515        forall<u: proof::Val> self.zone(u) == other.zone(u))]
516    pub(crate) fn eq_semantic(self, other: Dbm) {
517        pearlite! {
518            let d = self.variables@ + 1;
519            let s = self.entries@;
520            let t = other.entries@;
521            self.model();
522            other.model();
523            if s.len() != 0 && t.len() != 0 {
524                proof_assert!(s.len() == d * d && t.len() == d * d);
525                proof_assert!(forall<x: Int> 0 <= x && x < s.len() ==> inv(s[x]) && inv(t[x]));
526                if forall<u: proof::Val> self.zone(u) == other.zone(u) {
527                    proof::canonical_unique(self.mmat(), other.mmat(), d);
528                    proof_assert!(forall<i: Int, j: Int> 0 <= i && i < d && 0 <= j && j < d ==>
529                        proof::ent(s, d, i, j) == proof::ent(t, d, i, j));
530                    proof_assert!(forall<x: Int> 0 <= x && x < s.len() ==> {
531                        flat_eq_at(s, t, d, x); s[x].deep_model() == t[x].deep_model()
532                    });
533                    proof_assert!((*self.entries.deep_model()).ext_eq(*other.entries.deep_model()));
534                }
535                if self.deep_model() == other.deep_model() {
536                    proof_assert!(forall<x: Int> 0 <= x && x < s.len() ==> {
537                        view_injective(s[x], t[x]); s[x]@ == t[x]@
538                    });
539                    proof_assert!(forall<i: Int, j: Int> 0 <= i && i < d && 0 <= j && j < d ==> {
540                        proof::ent_read(s, d, i, j); proof::ent_read(t, d, i, j);
541                        self.mmat()[i][j] == other.mmat()[i][j]
542                    });
543                    proof::meq_transfer(self.mmat(), other.mmat(), d);
544                }
545            } else if s.len() == 0 && t.len() == 0 {
546                proof_assert!((*self.entries.deep_model()).ext_eq(*other.entries.deep_model()));
547            }
548        }
549    }
550
551    /// Constructs the zone containing only the all-zero clock valuation.
552    ///
553    /// Each of the `variables` actual clocks is exactly zero.
554    ///
555    /// # Errors
556    ///
557    /// [`Error::TooManyVariables`] if `variables` exceeds [`MAX_VARIABLES`].
558    ///
559    /// # Complexity
560    ///
561    /// Constructing the matrix takes `O(d²)` time and space, where
562    /// `d = variables + 1` includes the reference clock.
563    #[check(terminates)]
564    #[ensures(match result {
565        Ok(z) => z.variables_logic() == variables@ && !z.is_empty_logic(),
566        Err(e) => variables@ > MAX_VARIABLES@ && e == Error::TooManyVariables { requested: variables },
567    })]
568    pub fn zero(variables: usize) -> Result<Dbm, Error> {
569        let d = match checked_dimension(variables) {
570            Ok(d) => d,
571            Err(e) => return Err(e),
572        };
573        let entries = filled(d, Bound::LE_ZERO);
574        snapshot!(proof::zero_canonical(entries@, d@));
575        Ok(Dbm {
576            variables: variables as u32,
577            entries,
578        })
579    }
580
581    /// Constructs the zone of **all nonnegative-real valuations** of the
582    /// specified number of actual clocks, without any other constraints.
583    ///
584    /// # Errors
585    ///
586    /// [`Error::TooManyVariables`] if `variables` exceeds [`MAX_VARIABLES`].
587    ///
588    /// # Complexity
589    ///
590    /// Constructing the matrix takes `O(d²)` time and space, where
591    /// `d = variables + 1` includes the reference clock.
592    #[check(terminates)]
593    #[ensures(match result {
594        Ok(z) => z.variables_logic() == variables@ && !z.is_empty_logic()
595            && forall<u: proof::Val> z.zone(u) == proof::valuation(variables@ + 1, u),
596        Err(e) => variables@ > MAX_VARIABLES@ && e == Error::TooManyVariables { requested: variables },
597    })]
598    pub fn universe(variables: usize) -> Result<Dbm, Error> {
599        let d = match checked_dimension(variables) {
600            Ok(d) => d,
601            Err(e) => return Err(e),
602        };
603        let entries = universe_entries(d);
604        snapshot!(proof::universe_canonical(entries@, d@));
605        snapshot!(proof::universe_zone(entries@, d@));
606        Ok(Dbm {
607            variables: variables as u32,
608            entries,
609        })
610    }
611
612    /// Constructs an empty zone with the specified number of actual clocks.
613    ///
614    /// The empty zone contains no clock valuations but remembers its
615    /// clock count. Empty zones with different clock counts are distinct.
616    ///
617    /// # Errors
618    ///
619    /// [`Error::TooManyVariables`] if `variables` exceeds [`MAX_VARIABLES`].
620    ///
621    /// # Complexity
622    ///
623    /// `O(1)` time and no matrix allocation; the empty zone retains its
624    /// clock count.
625    #[check(terminates)]
626    #[ensures(match result {
627        Ok(z) => z.variables_logic() == variables@ && z.is_empty_logic(),
628        Err(e) => variables@ > MAX_VARIABLES@ && e == Error::TooManyVariables { requested: variables },
629    })]
630    pub fn empty(variables: usize) -> Result<Dbm, Error> {
631        if variables > MAX_VARIABLES {
632            return Err(Error::TooManyVariables {
633                requested: variables,
634            });
635        }
636        Ok(Dbm {
637            variables: variables as u32,
638            entries: no_entries(),
639        })
640    }
641
642    /// Returns the number of actual clocks (excluding the reference clock).
643    ///
644    /// # Complexity
645    ///
646    /// `O(1)` time.
647    #[check(terminates)]
648    #[ensures(result@ == self.variables_logic())]
649    pub fn variables(&self) -> usize {
650        self.variables as usize
651    }
652
653    /// Returns the matrix dimension: the actual clock count plus one for
654    /// the reference clock.
655    ///
656    /// # Complexity
657    ///
658    /// `O(1)` time.
659    #[check(terminates)]
660    #[ensures(result@ == self.variables_logic() + 1)]
661    pub fn dimension(&self) -> usize {
662        self.variables as usize + 1
663    }
664
665    /// Whether the zone is empty.
666    ///
667    /// # Complexity
668    ///
669    /// `O(1)` time.
670    #[check(terminates)]
671    #[ensures(result == self.is_empty_logic())]
672    pub fn is_empty(&self) -> bool {
673        self.entries.is_empty()
674    }
675}
676
677// ----- crate-private interface for `ops::*` -----
678
679#[allow(dead_code, reason = "crate-private interface for ops::*")]
680impl Dbm {
681    /// The empty zone with the same number of variables.
682    #[check(terminates)]
683    #[ensures(result.variables_logic() == self.variables_logic() && result.is_empty_logic())]
684    pub(crate) fn empty_like(&self) -> Dbm {
685        Dbm {
686            variables: self.variables,
687            entries: no_entries(),
688        }
689    }
690
691    /// Entry `(i, j)` of a nonempty DBM, i.e. the canonical (tightest) bound
692    /// on `xᵢ − xⱼ`. The caller has validated the indices (for example with
693    /// [`Dbm::check_clock`]) and handled the empty case.
694    #[check(terminates)]
695    #[requires(!self.is_empty_logic())]
696    #[requires(i@ <= self.variables_logic() && j@ <= self.variables_logic())]
697    #[ensures(result == self.at(i@, j@))]
698    pub(crate) fn entry(&self, i: usize, j: usize) -> Bound {
699        let d = self.variables as usize + 1;
700        snapshot!(square_fits(d@));
701        snapshot!(index_in_bounds(d@, i@, j@));
702        self.entries[i * d + j]
703    }
704
705    /// The index of `c` if it names a clock of this DBM (`0..=variables`),
706    /// otherwise `Err(ClockOutOfRange)`. Checked also for empty DBMs.
707    #[check(terminates)]
708    #[ensures(match result {
709        Ok(i) => i@ == c@ && i@ <= self.variables_logic(),
710        Err(e) => c@ > self.variables_logic() && match e {
711            Error::ClockOutOfRange { clock, variables } =>
712                clock@ == c@ && variables@ == self.variables_logic(),
713            _ => false,
714        },
715    })]
716    pub(crate) fn check_clock(&self, c: Clock) -> Result<usize, Error> {
717        let i = c.index();
718        if i <= self.variables as usize {
719            Ok(i)
720        } else {
721            Err(Error::ClockOutOfRange {
722                clock: i,
723                variables: self.variables as usize,
724            })
725        }
726    }
727
728    /// `Err(DimensionMismatch)` unless `found` equals `self.variables()`.
729    #[check(terminates)]
730    #[ensures(match result {
731        Ok(()) => found@ == self.variables_logic(),
732        Err(e) => found@ != self.variables_logic() && match e {
733            Error::DimensionMismatch { expected, found: f } =>
734                expected@ == self.variables_logic() && f == found,
735            _ => false,
736        },
737    })]
738    pub(crate) fn check_variables(&self, found: usize) -> Result<(), Error> {
739        if found == self.variables as usize {
740            Ok(())
741        } else {
742            Err(Error::DimensionMismatch {
743                expected: self.variables as usize,
744                found,
745            })
746        }
747    }
748
749    /// The working matrix of a nonempty DBM (moves the storage, no copy);
750    /// `None` for the empty zone.
751    #[check(terminates)]
752    #[ensures(match result {
753        Some(m) => !self.is_empty_logic() && m.dim_logic() == self.variables_logic() + 1
754            && m.mmat() == self.mmat()
755            && forall<i: Int, j: Int> 0 <= i && i < m.dim_logic() && 0 <= j && j < m.dim_logic()
756                ==> m.at(i, j) == self.at(i, j),
757        None => self.is_empty_logic(),
758    })]
759    pub(crate) fn into_matrix(self) -> Option<Matrix> {
760        if self.entries.is_empty() {
761            None
762        } else {
763            Some(Matrix {
764                dim: self.variables as usize + 1,
765                entries: self.entries,
766            })
767        }
768    }
769}
770
771// ----- the private working matrix -----
772
773/// A crate-private, possibly noncanonical working matrix (`WInv`):
774/// `dim × dim` valid bounds, row-major, `dim ≥ 1`.
775///
776/// It is never stored in a `Dbm` or returned to a caller except through
777/// [`Matrix::close`] or [`Matrix::publish_canonical`].
778pub(crate) struct Matrix {
779    dim: usize,
780    entries: Box<[Bound]>,
781}
782
783impl Invariant for Matrix {
784    #[logic(open(self))]
785    fn invariant(self) -> bool {
786        pearlite! {
787            1 <= self.dim@ && self.dim@ <= MAX_DIMENSION@
788                && self.entries@.len() == self.dim@ * self.dim@
789        }
790    }
791}
792
793// These helpers implement the private interface used by operation modules.
794#[allow(dead_code, reason = "crate-private interface for ops::*")]
795impl Matrix {
796    /// Logical entry `(i, j)`.
797    #[logic(open(self))]
798    pub(crate) fn at(self, i: Int, j: Int) -> Bound {
799        pearlite! { self.entries@[i * self.dim@ + j] }
800    }
801
802    /// Logical dimension.
803    #[logic(open(self))]
804    pub(crate) fn dim_logic(self) -> Int {
805        pearlite! { self.dim@ }
806    }
807
808    /// `u ∈ γ(self)` over nonnegative valuations.
809    #[logic(open(self))]
810    pub(crate) fn zone(self, u: proof::Val) -> bool {
811        pearlite! { proof::zone(self.entries@, self.dim@, u) }
812    }
813
814    /// The model matrix.
815    #[logic(open(self))]
816    pub(crate) fn mmat(self) -> proof::MMat {
817        pearlite! { proof::mat(self.entries@, self.dim@) }
818    }
819
820    /// A valid working matrix in model terms: its entries are `mmat`, and
821    /// its zone and canonicity are those of `mmat`.
822    #[logic]
823    #[requires(inv(self))]
824    #[ensures(forall<i: Int, j: Int>
825        0 <= i && i < self.dim_logic() && 0 <= j && j < self.dim_logic() ==>
826            self.at(i, j)@ == self.mmat()[i][j] && inv(self.at(i, j)))]
827    #[ensures(forall<u: proof::Val> self.zone(u) == proof::mzone(self.mmat(), self.dim_logic(), u))]
828    #[ensures(self.canonical_logic() == proof::mcanonical(self.mmat(), self.dim_logic()))]
829    pub(crate) fn model(self) {
830        pearlite! {
831            let d = self.dim@;
832            proof::mat_bridge(self.entries@, d);
833            proof_assert!(forall<i: Int, j: Int> 0 <= i && i < d && 0 <= j && j < d ==> {
834                proof::ent_read(self.entries@, d, i, j); index_in_bounds(d, i, j); true
835            });
836        }
837    }
838
839    /// Whether the working matrix satisfies the canonicality conditions.
840    #[logic(open(self))]
841    pub(crate) fn canonical_logic(self) -> bool {
842        pearlite! { proof::canonical(self.entries@, self.dim@) }
843    }
844
845    /// Whether closure of this matrix needs an unrepresentable finite sum
846    /// (characterized by `proof::range_failure`).
847    #[logic(open(self))]
848    pub(crate) fn range_failure_logic(self) -> bool {
849        pearlite! { proof::range_failure(self.entries@, self.dim@) }
850    }
851
852    /// Every finite constant of the matrix lies in `[−b, b]`.
853    #[logic(open(self))]
854    pub(crate) fn bounded_logic(self, b: Int) -> bool {
855        pearlite! { proof::bounded(self.entries@, self.dim@, b) }
856    }
857
858    /// The working matrix of [`Dbm::universe`]. `Err(TooManyVariables)` if
859    /// `variables > MAX_VARIABLES`. Intended as the starting point of
860    /// `try_from_constraints`: tighten entries, then [`Matrix::close`].
861    #[check(terminates)]
862    #[ensures(match result {
863        Ok(m) => m.dim_logic() == variables@ + 1,
864        Err(e) => variables@ > MAX_VARIABLES@ && e == Error::TooManyVariables { requested: variables },
865    })]
866    pub(crate) fn universe(variables: usize) -> Result<Matrix, Error> {
867        let d = match checked_dimension(variables) {
868            Ok(d) => d,
869            Err(e) => return Err(e),
870        };
871        Ok(Matrix {
872            dim: d,
873            entries: universe_entries(d),
874        })
875    }
876
877    /// The dimension `n + 1`.
878    #[check(terminates)]
879    #[ensures(result@ == self.dim_logic())]
880    pub(crate) fn dimension(&self) -> usize {
881        self.dim
882    }
883
884    /// Row `a := min(row a, via + row c)` entrywise, skipping infinite
885    /// entries of row `c` (`bounds::relax_row`); every other row is
886    /// unchanged. Returns `true` iff some needed sum is unrepresentable (that
887    /// entry is left unchanged). One row of an incremental closure
888    /// (`ops::constraints`), `O(d)` and vectorizable.
889    #[check(terminates)]
890    #[requires(a@ < self.dim_logic() && c@ < self.dim_logic() && a@ != c@)]
891    #[requires(via@ != BoundModel::Inf)]
892    #[ensures((^self).dim_logic() == self.dim_logic())]
893    #[ensures(forall<k: Int, l: Int>
894        0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
895        if k == a@ {
896            relax_entry(self.at(a@, l)@, via@, self.at(c@, l)@, (^self).at(a@, l)@)
897        } else {
898            (^self).at(k, l) == self.at(k, l)
899        })]
900    #[ensures(result ==> exists<l: Int> 0 <= l && l < self.dim_logic()
901        && relax_needed(self.at(a@, l)@, via@, self.at(c@, l)@)
902        && !via@.add_in_range(self.at(c@, l)@))]
903    #[ensures(!result ==> forall<l: Int> 0 <= l && l < self.dim_logic() ==>
904        !(relax_needed(self.at(a@, l)@, via@, self.at(c@, l)@)
905            && !via@.add_in_range(self.at(c@, l)@)))]
906    #[inline]
907    pub(crate) fn relax_row(&mut self, a: usize, c: usize, via: Bound) -> bool {
908        let d = self.dim;
909        snapshot!(square_fits(d@));
910        snapshot!(index_in_bounds(d@, a@, 0));
911        snapshot!(index_in_bounds(d@, c@, 0));
912        proof_assert!(forall<k: Int, l: Int> 0 <= k && k < d@ && 0 <= l && l < d@ ==> {
913            index_in_bounds(d@, k, l); row_cmp(d@, k, l, a@); true
914        });
915        snapshot!(row_cmp(d@, a@, 0, c@));
916        snapshot!(row_cmp(d@, c@, 0, a@));
917        let old = snapshot!(*self);
918        let (dst, src) = (a * d, c * d);
919        let r = relax_range(&mut self.entries, dst, src, d, via);
920        proof_assert!(forall<l: Int> 0 <= l && l < d@ ==>
921            old.at(a@, l) == old.entries@[dst@ + l] && old.at(c@, l) == old.entries@[src@ + l]);
922        proof_assert!(r ==> exists<l: Int> 0 <= l && l < d@
923            && relax_needed(old.at(a@, l)@, via@, old.at(c@, l)@)
924            && !via@.add_in_range(old.at(c@, l)@));
925        proof_assert!(!r ==> forall<l: Int> 0 <= l && l < d@ ==>
926            !(relax_needed(old.at(a@, l)@, via@, old.at(c@, l)@)
927                && !via@.add_in_range(old.at(c@, l)@)));
928        r
929    }
930
931    /// Entry `(i, j)`.
932    #[check(terminates)]
933    #[requires(i@ < self.dim_logic() && j@ < self.dim_logic())]
934    #[ensures(result == self.at(i@, j@))]
935    pub(crate) fn get(&self, i: usize, j: usize) -> Bound {
936        snapshot!(index_in_bounds(self.dim@, i@, j@));
937        self.entries[i * self.dim + j]
938    }
939
940    /// Overwrites entry `(i, j)`; every other entry is unchanged.
941    ///
942    /// `WInv` asks for `W[0][j] ≼ Le 0`; [`Matrix::close`] re-imposes it, so
943    /// a loosened row 0 is harmless there, but [`Matrix::publish_canonical`]
944    /// requires the caller to keep it.
945    #[check(terminates)]
946    #[requires(i@ < self.dim_logic() && j@ < self.dim_logic())]
947    #[ensures((^self).dim_logic() == self.dim_logic())]
948    #[ensures(forall<k: Int, l: Int>
949        0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
950        (^self).at(k, l) == if k == i@ && l == j@ { b } else { self.at(k, l) })]
951    pub(crate) fn set(&mut self, i: usize, j: usize, b: Bound) {
952        let d = snapshot!(self.dim@);
953        snapshot!(index_in_bounds(*d, i@, j@));
954        proof_assert!(forall<k: Int, l: Int> 0 <= k && k < *d && 0 <= l && l < *d ==> {
955            index_injective(*d, i@, j@, k, l); index_in_bounds(*d, k, l); true
956        });
957        self.entries[i * self.dim + j] = b;
958    }
959
960    /// `W[i][j] := min(W[i][j], b)`; every other entry is unchanged. This is
961    /// the conjunction with `xᵢ − xⱼ ⋈ b` (before closure).
962    #[check(terminates)]
963    #[requires(i@ < self.dim_logic() && j@ < self.dim_logic())]
964    #[ensures((^self).dim_logic() == self.dim_logic())]
965    #[ensures(forall<k: Int, l: Int>
966        0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
967        (^self).at(k, l) == if k == i@ && l == j@ && b.deep_model() < self.at(k, l).deep_model()
968            { b } else { self.at(k, l) })]
969    pub(crate) fn tighten(&mut self, i: usize, j: usize, b: Bound) {
970        if tighter(b, self.get(i, j)) {
971            self.set(i, j, b);
972        }
973    }
974
975    /// Full closure, converting a working matrix into a canonical public zone.
976    ///
977    /// Returns `Ok(∅_d)` if the matrix denotes the empty zone, the canonical
978    /// form otherwise, or `Err(Range)` if a finite intermediate sum is
979    /// unrepresentable (never saturated to `∞`). This operation needs no
980    /// workspace and takes `O(d³)` time in place.
981    ///
982    /// Proved: the result denotes exactly the zone of `self` over
983    /// nonnegative valuations, it is canonical or `∅_d` by the `Dbm`
984    /// invariant (so `∅_d` is returned iff that zone is empty), and
985    /// `Err(Range)` only when exact arithmetic leaves the range.
986    #[check(terminates)]
987    #[ensures(match result {
988        Ok(z) => z.variables_logic() == self.dim_logic() - 1
989            && forall<u: proof::Val> z.zone(u) == self.zone(u),
990        Err(e) => e == Error::Range && self.range_failure_logic()
991            && forall<b: Int> 0 <= b && self.bounded_logic(b) ==>
992                crate::bounds::MAX_CONSTANT@ < b * proof::pow2(self.dim_logic()),
993    })]
994    pub(crate) fn close(self) -> Result<Dbm, Error> {
995        let d = self.dim;
996        let mut entries = self.entries;
997        let variables = (d - 1) as u32;
998        match close_in_place(&mut entries, d) {
999            Ok(true) => Ok(Dbm { variables, entries }),
1000            Ok(false) => Ok(Dbm {
1001                variables,
1002                entries: no_entries(),
1003            }),
1004            Err(e) => Err(e),
1005        }
1006    }
1007
1008    /// Publishes a matrix that the caller guarantees to be **canonical and
1009    /// nonempty** (the public invariant), without closure. For
1010    /// in-place kernels that preserve canonicity (future, reset, free,
1011    /// incremental closure).
1012    ///
1013    /// The precondition `canonical` (C2–C4) is a proof obligation for each
1014    /// caller; Creusot rejects a call that does not discharge it.
1015    /// Debug builds additionally check the invariant by brute force
1016    /// (`O(d³)`) and panic on a violation.
1017    #[check(terminates)]
1018    #[requires(self.canonical_logic())]
1019    #[ensures(result.variables_logic() == self.dim_logic() - 1 && !result.is_empty_logic())]
1020    #[ensures(forall<u: proof::Val> result.zone(u) == self.zone(u))]
1021    #[ensures(result.mmat() == self.mmat())]
1022    pub(crate) fn publish_canonical(self) -> Dbm {
1023        #[cfg(all(debug_assertions, not(creusot)))]
1024        if let Err(msg) = check_canonical(&self.entries, self.dim) {
1025            panic!("publish_canonical: {msg}");
1026        }
1027        Dbm {
1028            variables: (self.dim - 1) as u32,
1029            entries: self.entries,
1030        }
1031    }
1032}
1033
1034// ----- whole-row and whole-column updates (temporal operations) -----
1035//
1036// `O(d)` primitives for `ops::temporal`. The contiguous row of
1037// `add_weak_to_row` goes through a slice (vectorized); columns are strided
1038// index loops (`x += d`), with the source column addressed relative to the
1039// target (`x − (a − c)`, `c < a`) so that one bounds check per row remains.
1040// Each states its exact effect and frame: only the named row or column
1041// changes. Proved, with termination.
1042
1043/// `e[dst + l] := via + e[src + l]` for `l < n` (`bounds::add_weak_row` on
1044/// two disjoint ranges of one slice); every other element is unchanged.
1045#[check(terminates)]
1046#[requires(dst@ + n@ <= e@.len() && src@ + n@ <= e@.len())]
1047#[requires(dst@ + n@ <= src@ || src@ + n@ <= dst@)]
1048#[requires(exists<c: Int> via@ == BoundModel::Le(c))]
1049#[requires(forall<l: Int> 0 <= l && l < n@ ==> via@.add_in_range(e@[src@ + l]@))]
1050#[ensures((^e)@.len() == e@.len())]
1051#[ensures(forall<x: Int> 0 <= x && x < e@.len() ==>
1052    if dst@ <= x && x < dst@ + n@ {
1053        (^e)@[x]@ == via@.add(e@[src@ + (x - dst@)]@)
1054    } else {
1055        (^e)@[x] == e@[x]
1056    })]
1057#[inline]
1058fn add_weak_range(e: &mut [Bound], dst: usize, src: usize, n: usize, via: Bound) {
1059    let old = snapshot!(e@);
1060    if dst < src {
1061        let (lo, hi) = e.split_at_mut(src);
1062        let row = &mut lo[dst..dst + n];
1063        let from = &hi[..n];
1064        add_weak_row(row, via, from);
1065        proof_assert!(forall<l: Int> 0 <= l && l < n@ ==> (^lo)@[dst@ + l] == (^row)@[l]);
1066        proof_assert!(forall<x: Int> 0 <= x && x < src@ && (x < dst@ || dst@ + n@ <= x) ==>
1067            (^lo)@[x] == old[x]);
1068        proof_assert!(forall<x: Int> 0 <= x && x < (^hi)@.len() ==> (^hi)@[x] == old[src@ + x]);
1069        proof_assert!(forall<x: Int> src@ <= x && x < old.len() ==> (^hi)@[x - src@] == old[x]);
1070    } else {
1071        let (lo, hi) = e.split_at_mut(dst);
1072        let row = &mut hi[..n];
1073        let from = &lo[src..src + n];
1074        add_weak_row(row, via, from);
1075        proof_assert!(forall<l: Int> 0 <= l && l < n@ ==> (^hi)@[l] == (^row)@[l]);
1076        proof_assert!(forall<x: Int> n@ <= x && x < (^hi)@.len() ==> (^hi)@[x] == old[dst@ + x]);
1077        proof_assert!(forall<x: Int> 0 <= x && x < dst@ ==> (^lo)@[x] == old[x]);
1078    }
1079}
1080
1081impl Matrix {
1082    /// Row `a := via + row c` entrywise (`bounds::add_weak`, whose
1083    /// precondition must hold for every entry; `via` finite and weak,
1084    /// `a ≠ c`); every other row is unchanged.
1085    #[check(terminates)]
1086    #[requires(a@ < self.dim_logic() && c@ < self.dim_logic() && a@ != c@)]
1087    #[requires(exists<v: Int> via@ == BoundModel::Le(v))]
1088    #[requires(forall<l: Int> 0 <= l && l < self.dim_logic() ==>
1089        via@.add_in_range(self.at(c@, l)@))]
1090    #[ensures((^self).dim_logic() == self.dim_logic())]
1091    #[ensures(forall<k: Int, l: Int>
1092        0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
1093        if k == a@ {
1094            (^self).at(k, l)@ == via@.add(self.at(c@, l)@)
1095        } else {
1096            (^self).at(k, l) == self.at(k, l)
1097        })]
1098    #[inline]
1099    pub(crate) fn add_weak_to_row(&mut self, a: usize, c: usize, via: Bound) {
1100        let d = self.dim;
1101        assert!(a < d && c < d && a != c);
1102        snapshot!(square_fits(d@));
1103        snapshot!(index_in_bounds(d@, a@, 0));
1104        snapshot!(index_in_bounds(d@, c@, 0));
1105        proof_assert!(forall<k: Int, l: Int> 0 <= k && k < d@ && 0 <= l && l < d@ ==> {
1106            index_in_bounds(d@, k, l); row_cmp(d@, k, l, a@); true
1107        });
1108        snapshot!(row_cmp(d@, a@, 0, c@));
1109        snapshot!(row_cmp(d@, c@, 0, a@));
1110        let old = snapshot!(*self);
1111        proof_assert!(forall<l: Int> 0 <= l && l < d@ ==> old.at(c@, l) == old.entries@[c@ * d@ + l]);
1112        add_weak_range(&mut self.entries, a * d, c * d, d, via);
1113        proof_assert!(forall<l: Int> 0 <= l && l < d@ ==>
1114            old.at(a@, l) == old.entries@[a@ * d@ + l] && old.at(c@, l) == old.entries@[c@ * d@ + l]);
1115    }
1116
1117    /// A working matrix has at least the reference clock.
1118    #[logic]
1119    #[requires(inv(self))]
1120    #[ensures(1 <= self.dim_logic() && self.dim_logic() <= MAX_DIMENSION@)]
1121    pub(crate) fn dim_pos(self) {}
1122
1123    /// Every entry is its `cell` (bridges `at` to the loop invariants).
1124    #[logic]
1125    #[requires(inv(self))]
1126    #[ensures(forall<k: Int, l: Int> 0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
1127        self.at(k, l) == cell(self.entries@, self.dim@, k, l))]
1128    pub(crate) fn at_cell(self) {
1129        pearlite! { cell_all(self.entries@, self.dim@) }
1130    }
1131
1132    /// Entry `(i, j)` read at its precomputed flat index `x = i·d + j`.
1133    #[check(terminates)]
1134    #[requires(0 <= *i && *i < self.dim_logic() && j@ < self.dim_logic())]
1135    #[requires(x@ == *i * self.dim_logic() + j@)]
1136    #[ensures(result == cell(self.entries@, self.dim@, *i, j@))]
1137    #[inline(always)]
1138    fn load(&self, x: usize, i: Snapshot<Int>, j: usize) -> Bound {
1139        snapshot!(cell_read(self.entries@, self.dim@, *i, j@));
1140        self.entries[x]
1141    }
1142
1143    /// Overwrites entry `(i, j)` at its precomputed flat index `x = i·d + j`;
1144    /// every other entry is unchanged.
1145    #[check(terminates)]
1146    #[requires(0 <= *i && *i < self.dim_logic() && j@ < self.dim_logic())]
1147    #[requires(x@ == *i * self.dim_logic() + j@)]
1148    #[ensures((^self).dim_logic() == self.dim_logic())]
1149    #[ensures(forall<k: Int, l: Int> 0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
1150        cell((^self).entries@, self.dim@, k, l)
1151            == if k == *i && l == j@ { v } else { cell(self.entries@, self.dim@, k, l) })]
1152    #[inline(always)]
1153    fn store(&mut self, x: usize, i: Snapshot<Int>, j: usize, v: Bound) {
1154        let old = snapshot!(self.entries@);
1155        snapshot!(cell_set(*old, self.dim@, *i, j@, v));
1156        self.entries[x] = v;
1157        proof_assert!(self.entries@.ext_eq(old.set(x@, v)));
1158    }
1159
1160    /// Column `a := via + column c` entrywise, in every row (as
1161    /// [`Matrix::add_weak_to_row`], with `c < a`); every other column is
1162    /// unchanged.
1163    #[check(terminates)]
1164    #[requires(a@ < self.dim_logic() && c@ < a@)]
1165    #[requires(exists<v: Int> via@ == BoundModel::Le(v))]
1166    #[requires(forall<k: Int> 0 <= k && k < self.dim_logic() ==>
1167        via@.add_in_range(self.at(k, c@)@))]
1168    #[ensures((^self).dim_logic() == self.dim_logic())]
1169    #[ensures(forall<k: Int, l: Int>
1170        0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
1171        if l == a@ {
1172            (^self).at(k, l)@ == via@.add(self.at(k, c@)@)
1173        } else {
1174            (^self).at(k, l) == self.at(k, l)
1175        })]
1176    #[inline]
1177    pub(crate) fn add_weak_to_column(&mut self, a: usize, c: usize, via: Bound) {
1178        let d = self.dim;
1179        assert!(a < d && c < a);
1180        snapshot!(square_fits(d@));
1181        let old = snapshot!(*self);
1182        snapshot!(old.at_cell());
1183        let off = a - c;
1184        let mut x = a;
1185        let mut i = snapshot!(0);
1186        #[invariant(0 <= *i && *i <= d@ && x@ == *i * d@ + a@)]
1187        #[invariant(self.dim == d && self.entries@.len() == d@ * d@)]
1188        #[invariant(forall<k: Int, l: Int> 0 <= k && k < d@ && 0 <= l && l < d@ ==>
1189            if l == a@ && k < *i {
1190                cell(self.entries@, d@, k, l)@ == via@.add(cell(old.entries@, d@, k, c@)@)
1191            } else {
1192                cell(self.entries@, d@, k, l) == cell(old.entries@, d@, k, l)
1193            })]
1194        #[variant(d@ * d@ - x@)]
1195        while x < self.entries.len() {
1196            snapshot!(row_cmp(d@, *i, a@, d@));
1197            let v = add_weak(self.load(x - off, i, c), via);
1198            self.store(x, i, a, v);
1199            x += d;
1200            i = snapshot!(*i + 1);
1201        }
1202        snapshot!(row_cmp(d@, *i, a@, d@));
1203        snapshot!(self.at_cell());
1204    }
1205
1206    /// Column `a := column c` in every row (`c < a`); every other column is
1207    /// unchanged.
1208    #[check(terminates)]
1209    #[requires(a@ < self.dim_logic() && c@ < a@)]
1210    #[ensures((^self).dim_logic() == self.dim_logic())]
1211    #[ensures(forall<k: Int, l: Int>
1212        0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
1213        (^self).at(k, l) == if l == a@ { self.at(k, c@) } else { self.at(k, l) })]
1214    #[inline]
1215    pub(crate) fn copy_column(&mut self, a: usize, c: usize) {
1216        let d = self.dim;
1217        assert!(a < d && c < a);
1218        snapshot!(square_fits(d@));
1219        let old = snapshot!(*self);
1220        snapshot!(old.at_cell());
1221        let off = a - c;
1222        let mut x = a;
1223        let mut i = snapshot!(0);
1224        #[invariant(0 <= *i && *i <= d@ && x@ == *i * d@ + a@)]
1225        #[invariant(self.dim == d && self.entries@.len() == d@ * d@)]
1226        #[invariant(forall<k: Int, l: Int> 0 <= k && k < d@ && 0 <= l && l < d@ ==>
1227            cell(self.entries@, d@, k, l) == if l == a@ && k < *i {
1228                cell(old.entries@, d@, k, c@)
1229            } else {
1230                cell(old.entries@, d@, k, l)
1231            })]
1232        #[variant(d@ * d@ - x@)]
1233        while x < self.entries.len() {
1234            snapshot!(row_cmp(d@, *i, a@, d@));
1235            let v = self.load(x - off, i, c);
1236            self.store(x, i, a, v);
1237            x += d;
1238            i = snapshot!(*i + 1);
1239        }
1240        snapshot!(row_cmp(d@, *i, a@, d@));
1241        snapshot!(self.at_cell());
1242    }
1243
1244    /// Every entry of column `a` becomes `b`; every other column is unchanged.
1245    #[check(terminates)]
1246    #[requires(a@ < self.dim_logic())]
1247    #[ensures((^self).dim_logic() == self.dim_logic())]
1248    #[ensures(forall<k: Int, l: Int>
1249        0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
1250        (^self).at(k, l) == if l == a@ { b } else { self.at(k, l) })]
1251    #[inline]
1252    pub(crate) fn fill_column(&mut self, a: usize, b: Bound) {
1253        let d = self.dim;
1254        assert!(a < d);
1255        snapshot!(square_fits(d@));
1256        let old = snapshot!(*self);
1257        snapshot!(old.at_cell());
1258        let mut x = a;
1259        let mut i = snapshot!(0);
1260        #[invariant(0 <= *i && *i <= d@ && x@ == *i * d@ + a@)]
1261        #[invariant(self.dim == d && self.entries@.len() == d@ * d@)]
1262        #[invariant(forall<k: Int, l: Int> 0 <= k && k < d@ && 0 <= l && l < d@ ==>
1263            cell(self.entries@, d@, k, l) == if l == a@ && k < *i {
1264                b
1265            } else {
1266                cell(old.entries@, d@, k, l)
1267            })]
1268        #[variant(d@ * d@ - x@)]
1269        while x < self.entries.len() {
1270            snapshot!(row_cmp(d@, *i, a@, d@));
1271            self.store(x, i, a, b);
1272            x += d;
1273            i = snapshot!(*i + 1);
1274        }
1275        snapshot!(row_cmp(d@, *i, a@, d@));
1276        snapshot!(self.at_cell());
1277    }
1278
1279    /// Every entry of row `a` becomes `b`; every other row is unchanged.
1280    #[check(terminates)]
1281    #[requires(a@ < self.dim_logic())]
1282    #[ensures((^self).dim_logic() == self.dim_logic())]
1283    #[ensures(forall<k: Int, l: Int>
1284        0 <= k && k < self.dim_logic() && 0 <= l && l < self.dim_logic() ==>
1285        (^self).at(k, l) == if k == a@ { b } else { self.at(k, l) })]
1286    #[inline]
1287    pub(crate) fn fill_row(&mut self, a: usize, b: Bound) {
1288        let d = self.dim;
1289        assert!(a < d);
1290        snapshot!(square_fits(d@));
1291        snapshot!(index_in_bounds(d@, a@, 0));
1292        let old = snapshot!(*self);
1293        proof_assert!(forall<k: Int, l: Int> 0 <= k && k < d@ && 0 <= l && l < d@ ==> {
1294            index_in_bounds(d@, k, l); row_cmp(d@, k, l, a@); true
1295        });
1296        let mut x = a * d;
1297        let end = x + d;
1298        #[invariant(a@ * d@ <= x@ && x@ <= end@ && end@ == a@ * d@ + d@)]
1299        #[invariant(self.entries@.len() == d@ * d@ && self.dim == d)]
1300        #[invariant(forall<y: Int> 0 <= y && y < d@ * d@ ==>
1301            self.entries@[y] == if a@ * d@ <= y && y < x@ { b } else { old.entries@[y] })]
1302        #[variant(end@ - x@)]
1303        while x < end {
1304            self.entries[x] = b;
1305            x += 1;
1306        }
1307    }
1308}
1309
1310/// Full closure in place on a flat row-major `d × d` matrix, using
1311/// Floyd–Warshall with the diagonal/reference-row preprocessing described
1312/// by the full-closure algorithm.
1313///
1314/// 1. `W[i][i] := min(W[i][i], Le 0)` and `W[0][j] := min(W[0][j], Le 0)`.
1315/// Both preserve γ over nonnegative clocks. A diagonal that is still
1316/// below `Le 0` (an input such as `xᵢ − xᵢ < 0`) means γ = ∅. Afterwards
1317/// every diagonal entry is exactly `Le 0`, and step 3 keeps it so for
1318/// every row that step 2 changes.
1319/// 2. Floyd–Warshall: for every pivot `k`, row `i ≠ k` and column `j`,
1320/// `W[i][j] := min(W[i][j], W[i][k] + W[k][j])`, skipping infinite
1321/// summands. Row `k` itself is skipped: with `W[k][k] = Le 0` its update
1322/// is a no-op.
1323/// 3. After each row, a diagonal below `Le 0` means γ = ∅: return
1324/// `Ok(false)` immediately (the negative-diagonal test).
1325///
1326/// Returns `Ok(true)` if the result is nonempty (then canonical), and
1327/// `Err(Range)` on an unrepresentable finite sum, leaving the matrix
1328/// partially updated (the caller drops it).
1329///
1330/// Proved using the ghost lemmas in `dbm/proof.rs`:
1331/// - `Ok(true)`: the result is canonical (`Inv` C2–C4, hence nonempty by
1332/// `proof::canonical_nonempty`) and denotes the input's zone;
1333/// - `Ok(false)`: the input's zone is empty;
1334/// - `Err(Range)`: exact arithmetic left the range (`proof::range_failure`),
1335/// which cannot happen if every finite input constant has magnitude
1336/// `≤ B` with `B · 2^d ≤ MAX_CONSTANT` (each pivot at most doubles it).
1337///
1338/// The loop invariants justify the optimizations: row `k` is skipped and
1339/// `W[i][k]` is read once per row because, with `W[k][k] = Le 0`, pivot `k`
1340/// changes neither; skipped infinite summands give `∞`, which never
1341/// tightens; and every early exit happens in a state with the input's zone.
1342#[check(terminates)]
1343#[requires(1 <= d@ && d@ <= MAX_DIMENSION@)]
1344#[requires(m@.len() == d@ * d@)]
1345#[ensures((^m)@.len() == m@.len())]
1346#[ensures(match result {
1347    Ok(true) => proof::canonical((^m)@, d@) && proof::same_zone((^m)@, m@, d@),
1348    Ok(false) => forall<u: proof::Val> !proof::zone(m@, d@, u),
1349    Err(e) => e == Error::Range && proof::range_failure(m@, d@)
1350        && forall<b: Int> 0 <= b && proof::bounded(m@, d@, b) ==>
1351            crate::bounds::MAX_CONSTANT@ < b * proof::pow2(d@),
1352})]
1353fn close_in_place(m: &mut [Bound], d: usize) -> Result<bool, Error> {
1354    let len = snapshot!(m@.len());
1355    let w = snapshot!(m@);
1356    snapshot!(square_fits(d@));
1357    snapshot!(proof::growth_init(m@, d@));
1358
1359    // Step 1: normalize the diagonal and the reference row.
1360    let mut i: usize = 0;
1361    #[invariant(i@ <= d@)]
1362    #[invariant(m@.len() == *len)]
1363    #[invariant(inv(m))]
1364    #[invariant(proof::same_zone(m@, *w, d@))]
1365    #[invariant(proof::growth(*w, m@, d@, 0))]
1366    #[invariant(forall<a: Int> 0 <= a && a < i@ ==>
1367        proof::ent(m@, d@, a, a) == BoundModel::Le(0)
1368            && proof::ent(m@, d@, 0, a).le(BoundModel::Le(0)))]
1369    #[variant(d@ - i@)]
1370    while i < d {
1371        snapshot!(index_in_bounds(d@, i@, i@));
1372        snapshot!(index_in_bounds(d@, 0, i@));
1373        let p = i * d + i;
1374        snapshot!(proof::ent_read(m@, d@, i@, i@));
1375        snapshot!(order_refines(Bound::LE_ZERO, m@[p@]));
1376        snapshot!(order_refines(m@[p@], Bound::LE_ZERO));
1377        if tighter(Bound::LE_ZERO, m[p]) {
1378            snapshot!(proof::ent_set(m@, d@, i@, i@, Bound::LE_ZERO));
1379            snapshot!(proof::zone_diag(m@, d@, i@, Bound::LE_ZERO));
1380            snapshot!(proof::growth_le0(*w, m@, d@, 0, i@, i@, Bound::LE_ZERO));
1381            let prev = snapshot!(m@);
1382            m[p] = Bound::LE_ZERO;
1383            proof_assert!(m@.ext_eq(prev.set(p@, Bound::LE_ZERO)));
1384        } else if tighter(m[p], Bound::LE_ZERO) {
1385            snapshot!(proof::neg_diag_empty(m@, d@, i@));
1386            return Ok(false);
1387        } else {
1388            snapshot!(view_injective(m@[p@], Bound::LE_ZERO));
1389        }
1390        snapshot!(proof::ent_read(m@, d@, 0, i@));
1391        proof_assert!(0 * d@ + i@ == i@);
1392        snapshot!(order_refines(Bound::LE_ZERO, m@[i@]));
1393        if tighter(Bound::LE_ZERO, m[i]) {
1394            snapshot!(proof::zone_ref(m@, d@, i@, Bound::LE_ZERO));
1395            snapshot!(proof::growth_le0(*w, m@, d@, 0, 0, i@, Bound::LE_ZERO));
1396            let prev = snapshot!(m@);
1397            m[i] = Bound::LE_ZERO;
1398            proof_assert!(m@.ext_eq(prev.set(i@, Bound::LE_ZERO)));
1399        }
1400        proof_assert!(proof::ent(m@, d@, i@, i@) == BoundModel::Le(0));
1401        proof_assert!(proof::ent(m@, d@, 0, i@).le(BoundModel::Le(0)));
1402        i += 1;
1403    }
1404    proof_assert!(proof::diag_le0(m@, d@) && proof::ref_nonneg(m@, d@));
1405
1406    // Step 2: Floyd–Warshall with early exit on a negative diagonal.
1407    let mut k: usize = 0;
1408    #[invariant(k@ <= d@)]
1409    #[invariant(m@.len() == *len)]
1410    #[invariant(inv(m))]
1411    #[invariant(proof::same_zone(m@, *w, d@))]
1412    #[invariant(proof::diag_le0(m@, d@) && proof::ref_nonneg(m@, d@))]
1413    #[invariant(proof::tri_upto(m@, d@, k@))]
1414    #[invariant(proof::growth(*w, m@, d@, k@))]
1415    #[variant(d@ - k@)]
1416    while k < d {
1417        snapshot!(index_in_bounds(d@, k@, 0));
1418        let old = snapshot!(m@);
1419        snapshot!(proof::growth_mono(*w, m@, d@, k@, k@ + 1));
1420        let rk = k * d;
1421        let mut i: usize = 0;
1422        #[invariant(i@ <= d@)]
1423        #[invariant(m@.len() == *len)]
1424        #[invariant(inv(m))]
1425        // Rows `< i` other than `k` are relaxed through `k`; the others,
1426        // including row `k`, are unchanged so far.
1427        #[invariant(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==>
1428            if a < i@ && a != k@ {
1429                proof::relax_full(proof::ent(*old, d@, a, b),
1430                    proof::ent(*old, d@, a, k@).add(proof::ent(*old, d@, k@, b)),
1431                    proof::ent(m@, d@, a, b))
1432            } else {
1433                proof::ent(m@, d@, a, b) == proof::ent(*old, d@, a, b)
1434            })]
1435        #[invariant(proof::diag_le0(m@, d@))]
1436        #[invariant(proof::growth(*w, m@, d@, k@ + 1))]
1437        #[variant(d@ - i@)]
1438        while i < d {
1439            if i != k {
1440                snapshot!(index_in_bounds(d@, i@, k@));
1441                snapshot!(index_in_bounds(d@, i@, i@));
1442                let ri = i * d;
1443                snapshot!(proof::ent_read(m@, d@, i@, k@));
1444                let ik = m[ri + k];
1445                proof_assert!(ik@ == proof::ent(*old, d@, i@, k@));
1446                if !ik.is_infinite() {
1447                    let row = snapshot!(m@);
1448                    let mut j: usize = 0;
1449                    #[invariant(j@ <= d@)]
1450                    #[invariant(m@.len() == *len)]
1451                    #[invariant(inv(m))]
1452                    #[invariant(forall<b: Int> 0 <= b && b < j@ ==>
1453                        proof::relax_full(proof::ent(*old, d@, i@, b),
1454                            ik@.add(proof::ent(*old, d@, k@, b)),
1455                            proof::ent(m@, d@, i@, b)))]
1456                    #[invariant(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==>
1457                        a != i@ || j@ <= b ==> proof::ent(m@, d@, a, b) == proof::ent(*row, d@, a, b))]
1458                    #[invariant(proof::growth(*w, m@, d@, k@ + 1))]
1459                    #[variant(d@ - j@)]
1460                    while j < d {
1461                        snapshot!(index_in_bounds(d@, k@, j@));
1462                        snapshot!(index_in_bounds(d@, i@, j@));
1463                        snapshot!(proof::ent_read(m@, d@, k@, j@));
1464                        snapshot!(proof::ent_read(m@, d@, i@, j@));
1465                        let kj = m[rk + j];
1466                        if !kj.is_infinite() {
1467                            let s = match ik.checked_add(kj) {
1468                                Ok(s) => s,
1469                                Err(e) => {
1470                                    snapshot!(proof::range_failure_intro(*old, *w, d@, i@, k@, j@));
1471                                    snapshot!(proof::growth_err(*w, *old, d@, k@, i@, j@));
1472                                    return Err(e);
1473                                }
1474                            };
1475                            snapshot!(order_refines(s, m@[i@ * d@ + j@]));
1476                            if tighter(s, m[ri + j]) {
1477                                snapshot!(proof::ent_set(m@, d@, i@, j@, s));
1478                                proof_assert!(kj@ == proof::ent(*old, d@, k@, j@));
1479                                snapshot!(proof::growth_sum(*w, *old, m@, d@, k@, i@, j@, s));
1480                                let prev = snapshot!(m@);
1481                                m[ri + j] = s;
1482                                proof_assert!(m@.ext_eq(prev.set(i@ * d@ + j@, s)));
1483                            }
1484                        } else {
1485                            snapshot!(add_comm_unit(ik@, BoundModel::Inf));
1486                        }
1487                        proof_assert!(proof::relax_full(proof::ent(*old, d@, i@, j@),
1488                            ik@.add(proof::ent(*old, d@, k@, j@)),
1489                            proof::ent(m@, d@, i@, j@)));
1490                        j += 1;
1491                    }
1492                    proof_assert!(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==>
1493                        a != i@ ==> proof::ent(m@, d@, a, b) == proof::ent(*row, d@, a, b));
1494                    proof_assert!(forall<b: Int> 0 <= b && b < d@ ==>
1495                        proof::relax_full(proof::ent(*old, d@, i@, b),
1496                            proof::ent(*old, d@, i@, k@).add(proof::ent(*old, d@, k@, b)),
1497                            proof::ent(m@, d@, i@, b)));
1498                    proof_assert!(proof::step_sound(*old, m@, d@, k@));
1499                    snapshot!(proof::ent_read(m@, d@, i@, i@));
1500                    snapshot!(order_refines(m@[i@ * d@ + i@], Bound::LE_ZERO));
1501                    if tighter(m[ri + i], Bound::LE_ZERO) {
1502                        snapshot!(proof::zone_relax(*old, m@, d@, k@));
1503                        snapshot!(proof::neg_diag_empty(m@, d@, i@));
1504                        return Ok(false);
1505                    }
1506                    snapshot!(view_injective(m@[i@ * d@ + i@], Bound::LE_ZERO));
1507                    proof_assert!(proof::ent(m@, d@, i@, i@) == BoundModel::Le(0));
1508                } else {
1509                    proof_assert!(forall<b: Int> 0 <= b && b < d@ ==>
1510                        proof::relax_full(proof::ent(*old, d@, i@, b),
1511                            ik@.add(proof::ent(*old, d@, k@, b)),
1512                            proof::ent(m@, d@, i@, b)));
1513                }
1514            } else {
1515                proof_assert!(forall<b: Int> 0 <= b && b < d@ ==> {
1516                    add_comm_unit(proof::ent(*old, d@, k@, b), BoundModel::Le(0));
1517                    le_trans(proof::ent(*old, d@, k@, b), proof::ent(*old, d@, k@, b), proof::ent(*old, d@, k@, b));
1518                    proof::relax_full(proof::ent(*old, d@, k@, b),
1519                        proof::ent(*old, d@, k@, k@).add(proof::ent(*old, d@, k@, b)),
1520                        proof::ent(m@, d@, k@, b))
1521                });
1522            }
1523            i += 1;
1524        }
1525        proof_assert!(proof::step_full(*old, m@, d@, k@));
1526        snapshot!(proof::pivot_step(*old, m@, d@, k@));
1527        snapshot!(proof::zone_relax(*old, m@, d@, k@));
1528        proof_assert!(forall<b: Int> 0 <= b && b < d@ ==> {
1529            le_trans(proof::ent(*old, d@, 0, b), proof::ent(*old, d@, 0, b), proof::ent(*old, d@, 0, b));
1530            le_trans(proof::ent(m@, d@, 0, b), proof::ent(*old, d@, 0, b), BoundModel::Le(0));
1531            proof::ent(m@, d@, 0, b).le(BoundModel::Le(0))
1532        });
1533        k += 1;
1534    }
1535    Ok(true)
1536}
1537
1538/// Brute-force check of the canonicality conditions C2–C4 for the debug
1539/// assertion in [`Matrix::publish_canonical`] and for tests. C1 holds by the
1540/// `Bound` type invariant; C5 follows from C2 and C4.
1541// Only debug builds and tests call it (`publish_canonical`).
1542#[cfg(all(not(creusot), any(test, debug_assertions)))]
1543fn check_canonical(m: &[Bound], d: usize) -> Result<(), String> {
1544    for i in 0..d {
1545        if m[i * d + i] != Bound::LE_ZERO {
1546            return Err(format!(
1547                "diagonal ({i},{i}) is {:?}, not Le 0",
1548                m[i * d + i]
1549            ));
1550        }
1551        if m[i] > Bound::LE_ZERO {
1552            return Err(format!("reference entry (0,{i}) allows a negative clock"));
1553        }
1554        for k in 0..d {
1555            for j in 0..d {
1556                let (ik, kj, ij) = (m[i * d + k], m[k * d + j], m[i * d + j]);
1557                let violated = match ik.checked_add(kj) {
1558                    Ok(via) => via < ij,
1559                    // Both summands are finite. A sum above MAX_CONSTANT is
1560                    // looser than every valid bound; one below MIN_CONSTANT
1561                    // is tighter than every valid bound.
1562                    Err(_) => {
1563                        let c = |b: Bound| i64::from(b.constant().unwrap_or(0));
1564                        c(ik) + c(kj) < 0
1565                    }
1566                };
1567                if violated {
1568                    return Err(format!("({i},{j}) is looser than ({i},{k}) + ({k},{j})"));
1569                }
1570            }
1571        }
1572    }
1573    Ok(())
1574}
1575
1576// ----- whole-matrix comparison and meet (relations) -----
1577//
1578// Kernels of `ops::relations`, proved.
1579
1580impl Dbm {
1581    /// `self[i][j] ≼ other[i][j]` for every `i, j` (`Bound`'s code order is
1582    /// the tightness order, B2). Both DBMs are nonempty with the same number
1583    /// of variables. Each row is compared branch-free (the loop vectorizes);
1584    /// a failing row ends the scan.
1585    ///
1586    /// Proved: the result is exactly the entrywise comparison, with
1587    /// termination and in-bounds row slices.
1588    #[check(terminates)]
1589    #[requires(self.variables_logic() == other.variables_logic())]
1590    #[requires(!self.is_empty_logic() && !other.is_empty_logic())]
1591    #[ensures(result == forall<i: Int, j: Int>
1592        0 <= i && i <= self.variables_logic() && 0 <= j && j <= self.variables_logic() ==>
1593            self.at(i, j).deep_model() <= other.at(i, j).deep_model())]
1594    // The explicit, non-short-circuiting `&` keeps the loop branch-free.
1595    #[allow(clippy::assign_op_pattern)]
1596    pub(crate) fn entries_le(&self, other: &Dbm) -> bool {
1597        let d = self.variables as usize + 1;
1598        let (a, b) = (&*self.entries, &*other.entries);
1599        snapshot!(square_fits(d@));
1600        proof_assert!(a@.len() == d@ * d@ && b@.len() == d@ * d@);
1601        let mut i: usize = 0;
1602        let mut r: usize = 0;
1603        #[invariant(i@ <= d@ && r@ == i@ * d@)]
1604        #[invariant(forall<k: Int, l: Int> 0 <= k && k < i@ && 0 <= l && l < d@ ==>
1605            a@[k * d@ + l].deep_model() <= b@[k * d@ + l].deep_model())]
1606        #[variant(d@ - i@)]
1607        while i < d {
1608            snapshot!(index_in_bounds(d@, i@, d@ - 1));
1609            proof_assert!(r@ + d@ <= d@ * d@);
1610            let (ra, rb) = (&a[r..r + d], &b[r..r + d]);
1611            // `n ≤ ra.len(), rb.len()` lets the compiler drop the bounds checks.
1612            let n = if ra.len() < rb.len() {
1613                ra.len()
1614            } else {
1615                rb.len()
1616            };
1617            let mut le = true;
1618            let mut l: usize = 0;
1619            #[invariant(l@ <= n@ && n@ == d@)]
1620            #[invariant(le == forall<x: Int> 0 <= x && x < l@ ==>
1621                ra@[x].deep_model() <= rb@[x].deep_model())]
1622            #[variant(n@ - l@)]
1623            while l < n {
1624                le = le & !tighter(rb[l], ra[l]);
1625                l += 1;
1626            }
1627            proof_assert!(forall<x: Int> 0 <= x && x < d@ ==>
1628                ra@[x] == a@[i@ * d@ + x] && rb@[x] == b@[i@ * d@ + x]);
1629            if !le {
1630                return false;
1631            }
1632            proof_assert!((i@ + 1) * d@ == i@ * d@ + d@);
1633            i += 1;
1634            r += d;
1635        }
1636        true
1637    }
1638}
1639
1640impl Matrix {
1641    /// `W[i][j] := min(W[i][j], E[i][j])` for every `i, j` (the pointwise meet,
1642    /// before closure), where `W = self` and `E = other` have the same
1643    /// dimension. Sets `touched[i]` and `touched[j]` for every entry that
1644    /// `E` strictly tightens, and no other flag.
1645    ///
1646    /// Returns `false` as soon as a tightened entry `(i, j)` and the current
1647    /// opposite entry `(j, i)` close a negative 2-cycle (the exact test
1648    /// `below_le_zero`, strict-zero cycles included): the intersection is
1649    /// empty, and the partially updated matrix must be discarded.
1650    ///
1651    /// Proved: on `true`, every entry is the pointwise minimum (`E`'s
1652    /// entry exactly when it is strictly tighter, both endpoints then
1653    /// touched, otherwise unchanged) and the flags grow exactly by the
1654    /// endpoints of tightened entries; on `false`, the zones of `W` and `E`
1655    /// do not intersect. Termination and in-bounds accesses.
1656    #[check(terminates)]
1657    #[requires(other.variables_logic() + 1 == self.dim_logic() && !other.is_empty_logic())]
1658    #[requires(touched@.len() == self.dim_logic())]
1659    #[ensures((^self).dim_logic() == self.dim_logic())]
1660    #[ensures((^touched)@.len() == touched@.len())]
1661    #[ensures(forall<x: Int> 0 <= x && x < self.dim_logic() && touched@[x] ==> (^touched)@[x])]
1662    #[ensures(result ==> forall<i: Int, j: Int>
1663        0 <= i && i < self.dim_logic() && 0 <= j && j < self.dim_logic() ==>
1664        if other.at(i, j).deep_model() < self.at(i, j).deep_model() {
1665            (^self).at(i, j) == other.at(i, j) && (^touched)@[i] && (^touched)@[j]
1666        } else {
1667            (^self).at(i, j) == self.at(i, j)
1668        })]
1669    #[ensures(result ==> forall<x: Int> 0 <= x && x < self.dim_logic() && (^touched)@[x] ==>
1670        touched@[x] || exists<y: Int> 0 <= y && y < self.dim_logic() && (
1671            other.at(x, y).deep_model() < self.at(x, y).deep_model()
1672                || other.at(y, x).deep_model() < self.at(y, x).deep_model()))]
1673    #[ensures(!result ==> forall<u: proof::Val> !(self.zone(u) && other.zone(u)))]
1674    pub(crate) fn meet(&mut self, other: &Dbm, touched: &mut [bool]) -> bool {
1675        let d = self.dim;
1676        let old = snapshot!(*self);
1677        let t0 = snapshot!(touched@);
1678        snapshot!(old.model());
1679        snapshot!(other.model());
1680        snapshot!(square_fits(d@));
1681        let mut i: usize = 0;
1682        let mut r: usize = 0;
1683        #[invariant(i@ <= d@ && r@ == i@ * d@)]
1684        #[invariant(self.dim_logic() == d@ && self.entries@.len() == d@ * d@ && touched@.len() == d@)]
1685        #[invariant(forall<x: Int> 0 <= x && x < d@ && t0[x] ==> touched@[x])]
1686        #[invariant(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==>
1687            if a < i@ && other.at(a, b).deep_model() < old.at(a, b).deep_model() {
1688                self.at(a, b) == other.at(a, b) && touched@[a] && touched@[b]
1689            } else {
1690                self.at(a, b) == old.at(a, b)
1691            })]
1692        #[invariant(forall<x: Int> 0 <= x && x < d@ && touched@[x] ==>
1693            t0[x] || exists<y: Int> 0 <= y && y < d@ && (
1694                (x < i@ && other.at(x, y).deep_model() < old.at(x, y).deep_model())
1695                    || (y < i@ && other.at(y, x).deep_model() < old.at(y, x).deep_model())))]
1696        #[variant(d@ - i@)]
1697        while i < d {
1698            snapshot!(index_in_bounds(d@, i@, d@ - 1));
1699            // Row `i` of `E`, read through one slice (no per-entry index check).
1700            let er = &other.entries[r..r + d];
1701            proof_assert!(d@ == other.variables@ + 1);
1702            proof_assert!(forall<y: Int> 0 <= y && y < d@ ==>
1703                er@[y] == other.entries@[r@ + y] && other.at(i@, y) == other.entries@[r@ + y]);
1704            let mut j: usize = 0;
1705            #[invariant(j@ <= d@ && self.dim_logic() == d@ && self.entries@.len() == d@ * d@)]
1706            #[invariant(touched@.len() == d@)]
1707            #[invariant(forall<y: Int> 0 <= y && y < d@ ==> er@[y] == other.at(i@, y))]
1708            #[invariant(forall<x: Int> 0 <= x && x < d@ && t0[x] ==> touched@[x])]
1709            #[invariant(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==>
1710                if (a < i@ || (a == i@ && b < j@))
1711                    && other.at(a, b).deep_model() < old.at(a, b).deep_model() {
1712                    self.at(a, b) == other.at(a, b) && touched@[a] && touched@[b]
1713                } else {
1714                    self.at(a, b) == old.at(a, b)
1715                })]
1716            #[invariant(forall<x: Int> 0 <= x && x < d@ && touched@[x] ==>
1717                t0[x] || exists<y: Int> 0 <= y && y < d@ && (
1718                    ((x < i@ || (x == i@ && y < j@))
1719                        && other.at(x, y).deep_model() < old.at(x, y).deep_model())
1720                    || ((y < i@ || (y == i@ && x < j@))
1721                        && other.at(y, x).deep_model() < old.at(y, x).deep_model())))]
1722            #[variant(d@ - j@)]
1723            while j < d {
1724                snapshot!(index_in_bounds(d@, i@, j@));
1725                let e = er[j];
1726                proof_assert!(e == other.at(i@, j@));
1727                let x = r + j;
1728                proof_assert!(x@ == i@ * d@ + j@ && d@ == self.dim@);
1729                proof_assert!(self.entries@[x@] == self.at(i@, j@));
1730                if tighter(e, self.entries[x]) {
1731                    // Only tightened entries take the proved `set`/`get`.
1732                    self.set(i, j, e);
1733                    let back = self.get(j, i);
1734                    if below_le_zero(e, back) {
1735                        // `back` is `W[j][i]` or `E[j][i]`: both hold on the
1736                        // intersection, and so does `e`, so it is empty.
1737                        proof_assert!(back == old.at(j@, i@) || back == other.at(j@, i@));
1738                        proof_assert!(forall<u: proof::Val> old.zone(u) && other.zone(u) ==> {
1739                            add_sound(e@, back@, u[i@] - u[j@], u[j@] - u[i@]);
1740                            below_le_zero_unsat(e@.add(back@));
1741                            (u[i@] - u[j@]) + (u[j@] - u[i@]) == Real::from_int(0)
1742                        });
1743                        return false;
1744                    }
1745                    touched[i] = true;
1746                    touched[j] = true;
1747                }
1748                j += 1;
1749            }
1750            proof_assert!((i@ + 1) * d@ == i@ * d@ + d@);
1751            i += 1;
1752            r += d;
1753        }
1754        true
1755    }
1756}
1757
1758impl Matrix {
1759    /// The precondition of [`Matrix::close_pivots`]: a `Le 0`
1760    /// diagonal, a nonnegative reference row, and the triangle inequality
1761    /// through every pivot that is **not** selected.
1762    #[logic(open(self))]
1763    pub(crate) fn pivot_ready(self, pivots: Seq<bool>) -> bool {
1764        pearlite! {
1765            pivots.len() == self.dim@
1766                && proof::diag_le0(self.entries@, self.dim@)
1767                && proof::ref_nonneg(self.entries@, self.dim@)
1768                && forall<l: Int> 0 <= l && l < self.dim@ && !pivots[l] ==>
1769                    proof::tri_through(self.entries@, self.dim@, l)
1770        }
1771    }
1772
1773    /// What [`Matrix::meet`] leaves for [`Matrix::close_pivots`].
1774    /// Let `w0` be a canonical matrix, `e` a nonempty `Dbm` of the same
1775    /// dimension, and `w` their pointwise minimum with `t` covering both
1776    /// endpoints of every tightened entry. Then:
1777    ///
1778    /// - `γ(w) = γ(w0) ∩ γ(e)`;
1779    /// - `w` is ready for the touched-pivot closure. For an untouched `l`,
1780    /// row and column `l` of `w` are those of `w0`, so
1781    /// `w[i][j] ≼ w0[i][j] ≼ w0[i][l] + w0[l][j] = w[i][l] + w[l][j]`.
1782    /// This is the path-free form of "a run of unchanged edges collapses
1783    /// into one entry of `w0`".
1784    #[logic]
1785    #[requires(inv(w0) && inv(w) && inv(e) && !e.is_empty_logic())]
1786    #[requires(w.dim_logic() == w0.dim_logic() && e.variables_logic() + 1 == w0.dim_logic())]
1787    #[requires(w0.canonical_logic() && t.len() == w0.dim_logic())]
1788    #[requires(forall<i: Int, j: Int>
1789        0 <= i && i < w0.dim_logic() && 0 <= j && j < w0.dim_logic() ==>
1790        if e.at(i, j).deep_model() < w0.at(i, j).deep_model() {
1791            w.at(i, j) == e.at(i, j) && t[i] && t[j]
1792        } else {
1793            w.at(i, j) == w0.at(i, j)
1794        })]
1795    #[ensures(w.pivot_ready(t))]
1796    #[ensures(forall<u: proof::Val> w.zone(u) == (w0.zone(u) && e.zone(u)))]
1797    #[ensures(proof::meq(w.mmat(), proof::bmin_mat(w0.mmat(), e.mmat()), w0.dim_logic()))]
1798    pub(crate) fn meet_ready(w0: Matrix, e: Dbm, w: Matrix, t: Seq<bool>) {
1799        pearlite! {
1800            let d = w0.dim@;
1801            w0.model();
1802            w.model();
1803            e.model();
1804            // The code order of `meet` is the tightness order (B2).
1805            proof_assert!(forall<i: Int, j: Int> 0 <= i && i < d && 0 <= j && j < d ==> {
1806                order_refines(e.at(i, j), w0.at(i, j));
1807                order_refines(w0.at(i, j), e.at(i, j));
1808                le_total(w0.mmat()[i][j], e.mmat()[i][j]);
1809                (w.mmat()[i][j] == w0.mmat()[i][j] && w0.mmat()[i][j].le(e.mmat()[i][j]))
1810                    || (w.mmat()[i][j] == e.mmat()[i][j] && !w0.mmat()[i][j].le(e.mmat()[i][j])
1811                        && t[i] && t[j])
1812            });
1813            proof::min_closed(w0.mmat(), e.mmat(), w.mmat(), t, d);
1814        }
1815    }
1816
1817    /// With every pivot selected, [`Matrix::pivot_ready`] asks only for a
1818    /// `Le 0` diagonal and a reference row `≼ Le 0` (ExtraM,: `norm`
1819    /// keeps both, `extra_m::proof::norm_ready`).
1820    #[logic]
1821    #[requires(inv(self))]
1822    #[requires(pivots.len() == self.dim_logic())]
1823    #[requires(forall<l: Int> 0 <= l && l < pivots.len() ==> pivots[l])]
1824    #[requires(forall<i: Int> 0 <= i && i < self.dim_logic() ==>
1825        self.mmat()[i][i] == BoundModel::Le(0))]
1826    #[requires(forall<j: Int> 0 <= j && j < self.dim_logic() ==>
1827        self.mmat()[0][j].le(BoundModel::Le(0)))]
1828    #[ensures(self.pivot_ready(pivots))]
1829    pub(crate) fn full_pivot_ready(self, pivots: Seq<bool>) {
1830        pearlite! { proof::mat_bridge(self.entries@, self.dim@) }
1831    }
1832
1833    /// A range failure of this matrix, stated on its model matrix.
1834    #[logic]
1835    #[requires(inv(self) && self.range_failure_logic())]
1836    #[ensures(proof::mrange_failure(self.mmat(), self.dim_logic()))]
1837    pub(crate) fn range_failure_model(self) {
1838        pearlite! { proof::mat_bridge(self.entries@, self.dim@) }
1839    }
1840
1841    /// Floyd–Warshall restricted to the pivots `k` with `pivots[k]`, each
1842    /// row relaxed by the proved, vectorized [`Matrix::relax_row`]. Row `k`
1843    /// is skipped (with `W[k][k] = Le 0` its update is a no-op), and so is a
1844    /// row with `W[i][k] = ∞`. After each relaxed row, a diagonal entry
1845    /// below `Le 0` means the zone is empty. `O(p·d²)` for `p` pivots, no
1846    /// scratch memory.
1847    ///
1848    /// The precondition [`Matrix::pivot_ready`] says that every unselected
1849    /// pivot already satisfies the triangle inequality. For the pointwise
1850    /// minimum of two canonical matrices with the touched clocks of
1851    /// [`Matrix::meet`] selected, [`Matrix::meet_ready`] establishes it.
1852    /// Each full pivot step keeps the triangles that hold and adds its own
1853    /// (`proof::pivot_keep`), so at the end the matrix is canonical: the
1854    /// result is the full closure of `self`, computed from the selected
1855    /// pivots only.
1856    ///
1857    /// Proved:
1858    /// - `Ok(z)`: `z` denotes exactly the zone of `self`. It is `∅_d` iff
1859    /// that zone is empty (a negative cycle of any length), otherwise
1860    /// canonical (`publish_canonical`'s precondition is discharged).
1861    /// - `Err(Range)`: only when an exact needed sum is unrepresentable
1862    /// (`proof::range_failure`, as for `Matrix::close`). This is never a
1863    /// way of reporting emptiness.
1864    /// - Termination and in-bounds accesses.
1865    #[check(terminates)]
1866    #[requires(self.pivot_ready(pivots@))]
1867    #[ensures(match result {
1868        Ok(z) => z.variables_logic() == self.dim_logic() - 1
1869            && forall<u: proof::Val> z.zone(u) == self.zone(u),
1870        Err(e) => e == Error::Range && self.range_failure_logic(),
1871    })]
1872    // Without a selected pivot nothing is relaxed, so nothing can fail.
1873    #[ensures((forall<l: Int> 0 <= l && l < self.dim_logic() ==> !pivots@[l])
1874        ==> match result { Ok(_) => true, Err(_) => false })]
1875    pub(crate) fn close_pivots(mut self, pivots: &[bool]) -> Result<Dbm, Error> {
1876        let d = self.dim;
1877        let w = snapshot!(self);
1878        let len = snapshot!(d@ * d@);
1879        let mut k: usize = 0;
1880        #[invariant(k@ <= d@ && self.dim@ == d@ && self.entries@.len() == *len)]
1881        #[invariant(inv(self))]
1882        #[invariant(proof::same_zone(self.entries@, w.entries@, d@))]
1883        #[invariant(proof::diag_le0(self.entries@, d@) && proof::ref_nonneg(self.entries@, d@))]
1884        #[invariant(forall<l: Int> 0 <= l && l < d@ && (!pivots@[l] || l < k@) ==>
1885            proof::tri_through(self.entries@, d@, l))]
1886        #[variant(d@ - k@)]
1887        while k < d {
1888            if pivots[k] {
1889                let old = snapshot!(self);
1890                snapshot!(old.model());
1891                let mut i: usize = 0;
1892                #[invariant(i@ <= d@ && self.dim@ == d@ && self.entries@.len() == *len)]
1893                #[invariant(inv(self))]
1894                // Rows `< i` other than `k` are relaxed through `k`; the
1895                // others, including row `k`, are unchanged so far.
1896                #[invariant(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==>
1897                    if a < i@ && a != k@ {
1898                        proof::relax_full(proof::ent(old.entries@, d@, a, b),
1899                            proof::ent(old.entries@, d@, a, k@)
1900                                .add(proof::ent(old.entries@, d@, k@, b)),
1901                            proof::ent(self.entries@, d@, a, b))
1902                    } else {
1903                        proof::ent(self.entries@, d@, a, b) == proof::ent(old.entries@, d@, a, b)
1904                    })]
1905                #[invariant(proof::diag_le0(self.entries@, d@))]
1906                #[variant(d@ - i@)]
1907                while i < d {
1908                    snapshot!(self.model());
1909                    let ik = self.get(i, k);
1910                    if i != k && !ik.is_infinite() {
1911                        let row = snapshot!(self);
1912                        let failed = self.relax_row(i, k, ik);
1913                        snapshot!(self.model());
1914                        proof_assert!(forall<b: Int> 0 <= b && b < d@ ==>
1915                            row.at(i@, b)@ == proof::ent(old.entries@, d@, i@, b)
1916                                && row.at(k@, b)@ == proof::ent(old.entries@, d@, k@, b));
1917                        if failed {
1918                            proof_assert!(exists<b: Int> 0 <= b && b < d@ &&
1919                                proof::range_failure_at(old.entries@, w.entries@, d@, i@, k@, b));
1920                            return Err(Error::Range);
1921                        }
1922                        proof_assert!(forall<b: Int> 0 <= b && b < d@ ==> {
1923                            proof::relax_row_full(row.at(i@, b)@, ik@, row.at(k@, b)@, self.at(i@, b)@);
1924                            proof::relax_full(proof::ent(old.entries@, d@, i@, b),
1925                                proof::ent(old.entries@, d@, i@, k@)
1926                                    .add(proof::ent(old.entries@, d@, k@, b)),
1927                                proof::ent(self.entries@, d@, i@, b))
1928                        });
1929                        proof_assert!(proof::step_sound(old.entries@, self.entries@, d@, k@));
1930                        snapshot!(order_refines(self.at(i@, i@), Bound::LE_ZERO));
1931                        if tighter(self.get(i, i), Bound::LE_ZERO) {
1932                            snapshot!(proof::zone_relax(old.entries@, self.entries@, d@, k@));
1933                            snapshot!(proof::neg_diag_empty(self.entries@, d@, i@));
1934                            return Ok(Dbm {
1935                                variables: (d - 1) as u32,
1936                                entries: no_entries(),
1937                            });
1938                        }
1939                        snapshot!(view_injective(self.at(i@, i@), Bound::LE_ZERO));
1940                        proof_assert!(proof::ent(self.entries@, d@, i@, i@) == BoundModel::Le(0));
1941                    } else if i == k {
1942                        proof_assert!(forall<b: Int> 0 <= b && b < d@ ==> {
1943                            add_comm_unit(proof::ent(old.entries@, d@, k@, b), BoundModel::Le(0));
1944                            le_trans(proof::ent(old.entries@, d@, k@, b),
1945                                proof::ent(old.entries@, d@, k@, b),
1946                                proof::ent(old.entries@, d@, k@, b));
1947                            proof::relax_full(proof::ent(old.entries@, d@, k@, b),
1948                                proof::ent(old.entries@, d@, k@, k@)
1949                                    .add(proof::ent(old.entries@, d@, k@, b)),
1950                                proof::ent(self.entries@, d@, k@, b))
1951                        });
1952                    } else {
1953                        proof_assert!(forall<b: Int> 0 <= b && b < d@ ==> {
1954                            add_comm_unit(proof::ent(old.entries@, d@, k@, b), BoundModel::Inf);
1955                            le_trans(proof::ent(old.entries@, d@, i@, b),
1956                                proof::ent(old.entries@, d@, i@, b),
1957                                proof::ent(old.entries@, d@, i@, b));
1958                            proof::relax_full(proof::ent(old.entries@, d@, i@, b),
1959                                proof::ent(old.entries@, d@, i@, k@)
1960                                    .add(proof::ent(old.entries@, d@, k@, b)),
1961                                proof::ent(self.entries@, d@, i@, b))
1962                        });
1963                    }
1964                    i += 1;
1965                }
1966                proof_assert!(proof::step_full(old.entries@, self.entries@, d@, k@));
1967                snapshot!(proof::pivot_keep(old.entries@, self.entries@, d@, k@));
1968                snapshot!(proof::zone_relax(old.entries@, self.entries@, d@, k@));
1969                proof_assert!(forall<b: Int> 0 <= b && b < d@ ==> {
1970                    le_trans(proof::ent(old.entries@, d@, 0, b),
1971                        proof::ent(old.entries@, d@, 0, b),
1972                        proof::ent(old.entries@, d@, 0, b));
1973                    le_trans(proof::ent(self.entries@, d@, 0, b),
1974                        proof::ent(old.entries@, d@, 0, b), BoundModel::Le(0));
1975                    proof::ent(self.entries@, d@, 0, b).le(BoundModel::Le(0))
1976                });
1977            }
1978            k += 1;
1979        }
1980        proof_assert!(proof::tri_upto(self.entries@, d@, d@));
1981        Ok(self.publish_canonical())
1982    }
1983}
1984
1985// ----- workspace -----
1986
1987/// Reusable scratch storage for operations that require temporary buffers.
1988///
1989/// Reuse one workspace across successive [`Dbm::try_intersect`] and
1990/// [`Dbm::try_extrapolate_max`] calls, including calls on different dimensions.
1991/// It contains no references to zones and does not affect their semantics.
1992/// A workspace is intended to be borrowed mutably by one operation at a time.
1993/// It is `Send`, so a caller may use one per thread or exploration loop.
1994///
1995/// [`Workspace::with_capacity`] accepts a sizing hint, but callers must
1996/// not rely on it eliminating allocations.
1997///
1998/// # Example
1999///
2000/// ```
2001/// use clock_dbm::{Dbm, Workspace};
2002/// # fn main() -> Result<(), clock_dbm::Error> {
2003/// let mut ws = Workspace::new();
2004/// let a = Dbm::zero(1)?;
2005/// let b = Dbm::universe(1)?;
2006/// assert_eq!(a.clone().try_intersect(&b, &mut ws)?, a);
2007/// assert_eq!(b.try_intersect(&a, &mut ws)?, a);
2008/// # Ok(())
2009/// # }
2010/// ```
2011#[derive(Default, Debug)]
2012pub struct Workspace {
2013    _private: (),
2014    /// Touched-clock flags of `Dbm::try_intersect`, and
2015    /// the all-pivot flags of `Dbm::try_extrapolate_max`.
2016    pub(crate) touched: Vec<bool>,
2017}
2018
2019impl Workspace {
2020    /// A fresh workspace.
2021    ///
2022    /// # Complexity
2023    ///
2024    /// `O(1)` time; temporary storage is allocated when needed by an operation.
2025    #[check(terminates)]
2026    pub fn new() -> Workspace {
2027        Workspace {
2028            _private: (),
2029            touched: Vec::new(),
2030        }
2031    }
2032
2033    /// `d` cleared touched-clock flags (intersection).
2034    #[check(terminates)]
2035    #[ensures((^self).touched@.len() == d@)]
2036    #[ensures(forall<x: Int> 0 <= x && x < d@ ==> !(^self).touched@[x])]
2037    pub(crate) fn reset_touched(&mut self, d: usize) {
2038        self.fill_touched(d, false);
2039    }
2040
2041    /// `d` set flags: every clock is a pivot (ExtraM's full closure).
2042    #[check(terminates)]
2043    #[ensures((^self).touched@.len() == d@)]
2044    #[ensures(forall<x: Int> 0 <= x && x < d@ ==> (^self).touched@[x])]
2045    pub(crate) fn select_all(&mut self, d: usize) {
2046        self.fill_touched(d, true);
2047    }
2048
2049    /// `d` flags equal to `flag`. Once the vector has length `d` (every call
2050    /// after the first for that dimension), the flags are overwritten in
2051    /// place. Otherwise they are pushed one by one, because `Vec::resize` and
2052    /// `slice::fill` have no creusot-std specification. Allocates only while
2053    /// the vector grows.
2054    #[check(terminates)]
2055    #[ensures((^self).touched@.len() == d@)]
2056    #[ensures(forall<x: Int> 0 <= x && x < d@ ==> (^self).touched@[x] == flag)]
2057    #[inline]
2058    fn fill_touched(&mut self, d: usize, flag: bool) {
2059        if self.touched.len() == d {
2060            let mut x: usize = 0;
2061            #[invariant(x@ <= d@ && self.touched@.len() == d@)]
2062            #[invariant(forall<y: Int> 0 <= y && y < x@ ==> self.touched@[y] == flag)]
2063            #[variant(d@ - x@)]
2064            while x < d {
2065                self.touched[x] = flag;
2066                x += 1;
2067            }
2068        } else {
2069            self.touched.clear();
2070            let mut x: usize = 0;
2071            #[invariant(x@ <= d@ && self.touched@.len() == x@)]
2072            #[invariant(forall<y: Int> 0 <= y && y < x@ ==> self.touched@[y] == flag)]
2073            #[variant(d@ - x@)]
2074            while x < d {
2075                self.touched.push(flag);
2076                x += 1;
2077            }
2078        }
2079    }
2080
2081    /// Creates a workspace using `variables` as a capacity hint.
2082    ///
2083    /// The current implementation does not preallocate storage, so this
2084    /// behaves like [`Workspace::new`]. No allocation guarantee is made.
2085    ///
2086    /// # Complexity
2087    ///
2088    /// `O(1)` time. The argument is currently only a hint; no storage
2089    /// is allocated eagerly.
2090    #[check(terminates)]
2091    pub fn with_capacity(variables: usize) -> Workspace {
2092        let _ = variables;
2093        Workspace::new()
2094    }
2095}
2096
2097// Ghost-only proof layer; it has no runtime content.
2098#[cfg(creusot)]
2099pub(crate) mod proof;
2100
2101#[cfg(test)]
2102mod tests;