Skip to main content

clock_dbm/ops/
constraints.rs

1//! Constructing zones and applying clock constraints.
2//!
3//! [`Dbm::try_from_constraints`](crate::Dbm::try_from_constraints) starts
4//! from all nonnegative valuations. Use
5//! [`Dbm::try_constrain`](crate::Dbm::try_constrain) to add one guard to an
6//! existing zone, or [`Dbm::try_constrain_all`](crate::Dbm::try_constrain_all)
7//! to add several. Contradictory guards produce an empty zone rather than
8//! an error; the method pages describe argument and arithmetic errors.
9
10// Incremental closure is specified in docs/algorithms.md; the lemmas that
11// justify each step of `close_edge` are in `constraints/proof.rs`.
12
13#![allow(clippy::question_mark)]
14
15use crate::bounds::{Bound, BoundModel, Constraint};
16#[cfg(creusot)]
17use crate::bounds::{order_refines, relax_needed, sat, view_representable};
18#[cfg(creusot)]
19use crate::dbm::proof::{
20    edge, edge_canonical, edge_ok, edge_zone, mcanonical, meq, meq_transfer, valuation,
21};
22use crate::dbm::{Dbm, Matrix, Workspace, tighter};
23use crate::error::Error;
24use creusot_std::prelude::{Clone, *};
25#[cfg(creusot)]
26use proof::{all_valid, conj, csat, edge_unrepresentable, single_range_failure, valid};
27
28// ----- range-failure provenance of a batch (specification only) -----
29
30/// The incremental strategy failed at constraint `t`: `z` denotes the input
31/// conjoined with the constraints before `t`, and the exact closure of `z`
32/// with constraint `t` has an unrepresentable entry.
33#[logic(open(crate))]
34pub(crate) fn incremental_failure_at(d0: Dbm, cs: Seq<Constraint>, t: Int, z: Dbm) -> bool {
35    pearlite! {
36        0 <= t && t < cs.len() && !z.is_empty_logic()
37            && mcanonical(z.mmat(), z.variables_logic() + 1)
38            && z.variables_logic() == d0.variables_logic()
39            && (forall<u: crate::dbm::proof::Val> z.zone(u) == (d0.zone(u) && conj(cs, t, u)))
40            && single_range_failure(z.mmat(), z.variables_logic() + 1,
41                cs[t]@.0, cs[t]@.1, cs[t]@.2)
42    }
43}
44
45/// The full-closure strategy failed: `m` is the input with every constraint
46/// tightened in, and its closure left the representable range.
47#[logic(open(crate))]
48pub(crate) fn closure_failure_at(d0: Dbm, cs: Seq<Constraint>, m: Matrix) -> bool {
49    pearlite! {
50        m.dim_logic() == d0.variables_logic() + 1
51            && (forall<u: crate::dbm::proof::Val> m.zone(u) == (d0.zone(u) && conj(cs, cs.len(), u)))
52            && m.range_failure_logic()
53    }
54}
55
56/// Why a batch returned `Err(Range)`: exact arithmetic of
57/// one of the two strategies left the representable range.
58#[logic(open(crate))]
59pub(crate) fn batch_range_failure(d0: Dbm, cs: Seq<Constraint>) -> bool {
60    pearlite! {
61        (exists<t: Int, z: Dbm> incremental_failure_at(d0, cs, t, z))
62            || exists<m: Matrix> closure_failure_at(d0, cs, m)
63    }
64}
65
66/// Some constraint of `cs` contradicts `d0` by itself (`b + D[j][i] ≺ Le 0`):
67/// the pre-pass of `constrain_all_with` returns `∅_d`.
68#[logic(open(crate))]
69pub(crate) fn some_contradiction(d0: Dbm, cs: Seq<Constraint>) -> bool {
70    pearlite! {
71        exists<t: Int> 0 <= t && t < cs.len()
72            && !edge_ok(d0.mmat(), cs[t]@.0, cs[t]@.1, cs[t]@.2)
73    }
74}
75
76/// Every constraint of `cs` is implied by `d0` (`D[i][j] ≼ b`): incremental
77/// insertion leaves `d0` unchanged.
78#[logic(open(crate))]
79pub(crate) fn all_implied(d0: Dbm, cs: Seq<Constraint>) -> bool {
80    pearlite! {
81        forall<t: Int> 0 <= t && t < cs.len() ==> d0.mmat()[cs[t]@.0][cs[t]@.1].le(cs[t]@.2)
82    }
83}
84
85/// The error of the first invalid constraint (`check_constraint`).
86#[logic(open(crate))]
87pub(crate) fn clock_error(c: Constraint, n: Int, e: Error) -> bool {
88    pearlite! {
89        match e {
90            Error::ClockOutOfRange { clock, variables } => variables@ == n
91                && if c@.0 > n { clock@ == c@.0 } else { c@.1 > n && clock@ == c@.1 },
92            _ => false,
93        }
94    }
95}
96
97/// `e` is the error of the first invalid constraint of `cs`.
98#[logic(open(crate))]
99pub(crate) fn first_clock_error(cs: Seq<Constraint>, n: Int, e: Error) -> bool {
100    pearlite! {
101        exists<t: Int> 0 <= t && t < cs.len() && !valid(cs[t], n)
102            && (forall<s: Int> 0 <= s && s < t ==> valid(cs[s], n))
103            && clock_error(cs[t], n, e)
104    }
105}
106
107/// `cs` and `ds` contain the same constraints, in any order and with any
108/// multiplicity.
109#[logic(open(crate))]
110pub(crate) fn same_constraints(cs: Seq<Constraint>, ds: Seq<Constraint>) -> bool {
111    pearlite! {
112        (forall<t: Int> 0 <= t && t < cs.len() ==> exists<s: Int> 0 <= s && s < ds.len() && ds[s] == cs[t])
113            && forall<s: Int> 0 <= s && s < ds.len() ==> exists<t: Int> 0 <= t && t < cs.len() && cs[t] == ds[s]
114    }
115}
116
117/// Order independence of batches: two successful
118/// results of `try_constrain_all` on the same input, whose constraint lists
119/// contain the same constraints (a permutation, or with repetitions), are
120/// equal values, not only equal zones (by Theorem 3.1, `Dbm::eq_semantic`).
121#[logic]
122#[requires(inv(r1) && inv(r2) && r1.variables_logic() == r2.variables_logic())]
123#[requires(same_constraints(cs, ds))]
124#[requires(forall<u: crate::dbm::proof::Val> r1.zone(u) == (d0.zone(u) && conj(cs, cs.len(), u)))]
125#[requires(forall<u: crate::dbm::proof::Val> r2.zone(u) == (d0.zone(u) && conj(ds, ds.len(), u)))]
126#[ensures(r1.deep_model() == r2.deep_model())]
127#[allow(dead_code, reason = "a theorem: checked by Creusot, never called")]
128pub(crate) fn batch_order_independent(
129    d0: Dbm,
130    cs: Seq<Constraint>,
131    ds: Seq<Constraint>,
132    r1: Dbm,
133    r2: Dbm,
134) {
135    pearlite! {
136        proof_assert!(forall<u: crate::dbm::proof::Val> conj(cs, cs.len(), u) == conj(ds, ds.len(), u));
137        r1.eq_semantic(r2)
138    }
139}
140
141// ----- the full-closure path -----
142
143impl Dbm {
144    /// `close(self ∧ cs)` by tightening every entry and running the full
145    /// closure of `dbm.rs`. The indices must already be validated.
146    #[check(terminates)]
147    #[requires(all_valid(cs@, self.variables_logic()))]
148    #[ensures(match result {
149        Ok(z) => z.variables_logic() == self.variables_logic()
150            && forall<u: crate::dbm::proof::Val> z.zone(u) == (self.zone(u) && conj(cs@, cs@.len(), u)),
151        Err(e) => e == Error::Range && exists<m: Matrix> closure_failure_at(self, cs@, m),
152    })]
153    fn constrain_all_by_closure(self, cs: &[Constraint]) -> Result<Dbm, Error> {
154        let orig = snapshot!(self);
155        let n = snapshot!(self.variables_logic());
156        snapshot!(self.model());
157        let empty = self.empty_like();
158        let mut m = match self.into_matrix() {
159            Some(m) => m,
160            None => return Ok(empty),
161        };
162        snapshot!(m.model());
163        let mut t: usize = 0;
164        #[invariant(t@ <= cs@.len())]
165        #[invariant(m.dim_logic() == *n + 1)]
166        #[invariant(forall<u: crate::dbm::proof::Val> m.zone(u) == (orig.zone(u) && conj(cs@, t@, u)))]
167        #[variant(cs@.len() - t@)]
168        while t < cs.len() {
169            let c = cs[t];
170            let (i, j, b) = (c.i().index(), c.j().index(), c.bound());
171            let before = snapshot!(m);
172            snapshot!(before.model());
173            m.tighten(i, j, b);
174            snapshot!(m.model());
175            snapshot!(order_refines(b, before.at(i@, j@)));
176            snapshot!(crate::bounds::le_total(b@, before.at(i@, j@)@));
177            snapshot!(crate::dbm::proof::bmin_spec(before.at(i@, j@)@, b@));
178            proof_assert!(m.at(i@, j@)@ == crate::dbm::proof::bmin(before.at(i@, j@)@, b@));
179            proof_assert!(forall<k: Int, l: Int> 0 <= k && k <= *n && 0 <= l && l <= *n ==>
180            m.mmat()[k][l] == if k == i@ && l == j@ {
181                crate::dbm::proof::bmin(before.mmat()[i@][j@], b@)
182            } else {
183                before.mmat()[k][l]
184            });
185            snapshot!(proof::tighten_zone(before.mmat(), m.mmat(), *n + 1, i@, j@, b@));
186            t += 1;
187        }
188        let last = snapshot!(m);
189        match m.close() {
190            Ok(z) => Ok(z),
191            Err(e) => {
192                proof_assert!(closure_failure_at(*orig, cs@, *last));
193                Err(e)
194            }
195        }
196    }
197}
198
199// ----- the incremental algorithm -----
200
201/// The constant sum of two finite bounds, exactly (`as`: a lossless
202/// widening that, unlike `i64::from`, has a Creusot specification).
203#[check(terminates)]
204#[ensures(match (a@, b@) {
205    (BoundModel::Lt(x) | BoundModel::Le(x), BoundModel::Lt(y) | BoundModel::Le(y)) =>
206        result@ == x + y,
207    _ => true,
208})]
209#[allow(clippy::cast_lossless)]
210fn constant_sum(a: Bound, b: Bound) -> i64 {
211    snapshot!(view_representable(a));
212    snapshot!(view_representable(b));
213    a.constant().unwrap_or(0) as i64 + b.constant().unwrap_or(0) as i64
214}
215
216/// Whether `a + b ≺ Le 0`, decided exactly. An unrepresentable finite sum
217/// is not an error here, because it is only compared, never stored.
218#[check(terminates)]
219#[ensures(result == !BoundModel::Le(0).le(a@.add(b@)))]
220pub(crate) fn below_le_zero(a: Bound, b: Bound) -> bool {
221    if a.is_infinite() || b.is_infinite() {
222        return false;
223    }
224    match a.checked_add(b) {
225        Ok(s) => {
226            snapshot!(order_refines(s, Bound::LE_ZERO));
227            tighter(s, Bound::LE_ZERO)
228        }
229        // |sum| > MAX_CONSTANT ≥ 1, so its sign decides.
230        Err(_) => constant_sum(a, b) < 0,
231    }
232}
233
234/// `Some(a + b)` if that finite sum is strictly tighter than `cur`, `None`
235/// if it is not. `Err(Range)` only if it is tighter but unrepresentable,
236/// i.e. the result entry itself would be unrepresentable. Used once per row
237/// for the row-skip test; whole rows use `Matrix::relax_row`.
238#[check(terminates)]
239#[requires(a@ != BoundModel::Inf && b@ != BoundModel::Inf)]
240#[ensures(match result {
241    Ok(Some(s)) => s@ == a@.add(b@) && !cur@.le(a@.add(b@)),
242    Ok(None) => cur@.le(a@.add(b@)),
243    Err(e) => e == Error::Range && !cur@.le(a@.add(b@)) && !a@.add(b@).representable(),
244})]
245fn relax(cur: Bound, a: Bound, b: Bound) -> Result<Option<Bound>, Error> {
246    snapshot!(view_representable(cur));
247    match a.checked_add(b) {
248        Ok(s) => {
249            snapshot!(order_refines(s, cur));
250            snapshot!(crate::bounds::le_total(s@, cur@));
251            Ok(if tighter(s, cur) { Some(s) } else { None })
252        }
253        // Below MIN_CONSTANT: tighter than every bound. Above MAX_CONSTANT:
254        // tighter than ∞ only.
255        Err(e) => {
256            if constant_sum(a, b) < 0 || cur.is_infinite() {
257                Err(e)
258            } else {
259                Ok(None)
260            }
261        }
262    }
263}
264
265/// Closes the canonical matrix `m` after tightening entry `(i, j)` to `b`,
266/// using two row-update phases. The new bound must be strictly tighter and
267/// consistent with the original zone (`b + D[j][i] ≽ Le 0`), with `i ≠ j`.
268/// On `Err(Range)`, the partially updated matrix must be discarded.
269#[check(terminates)]
270#[requires(m.canonical_logic())]
271#[requires(i@ < m.dim_logic() && j@ < m.dim_logic())]
272#[requires(!m.mmat()[i@][j@].le(b@) && edge_ok(m.mmat(), i@, j@, b@))]
273#[ensures((^m).dim_logic() == m.dim_logic())]
274#[ensures(match result {
275    Ok(()) => forall<k: Int, l: Int> 0 <= k && k < m.dim_logic() && 0 <= l && l < m.dim_logic() ==>
276        (^m).at(k, l)@ == edge(m.mmat(), i@, j@, b@)[k][l],
277    Err(e) => e == Error::Range && edge_unrepresentable(m.mmat(), m.dim_logic(), i@, j@, b@),
278})]
279fn close_edge(m: &mut Matrix, i: usize, j: usize, b: Bound) -> Result<(), Error> {
280    let d = m.dimension();
281    let m0 = snapshot!(*m);
282    let f = snapshot!(m.mmat());
283    let e = snapshot!(edge(*f, i@, j@, b@));
284    snapshot!(m0.model());
285    snapshot!(proof::tighten_distinct(*f, d@, i@, j@, b@));
286    debug_assert!(i < d && j < d && i != j);
287    // D'[i][l] = min(D[i][l], b ⊕ D[j][l]).
288    snapshot!(proof::phase1(*f, d@, i@, j@, b@));
289    if m.relax_row(i, j, b) {
290        return Err(Error::Range);
291    }
292    proof_assert!(forall<l: Int> 0 <= l && l < d@ ==> {
293        proof::relax_min(f[i@][l], b@, f[j@][l], m.at(i@, l)@); m.at(i@, l)@ == e[i@][l]
294    });
295    // Row `i` is final; every other row is still the input's until its turn.
296    let mut k: usize = 0;
297    #[invariant(k@ <= d@ && m.dim_logic() == d@)]
298    #[invariant(forall<k2: Int, l: Int> 0 <= k2 && k2 < d@ && 0 <= l && l < d@ ==>
299        if k2 == i@ || k2 < k@ { m.at(k2, l)@ == e[k2][l] } else { m.at(k2, l) == m0.at(k2, l) })]
300    #[variant(d@ - k@)]
301    while k < d {
302        proof_assert!(f[k@][i@] == BoundModel::Inf ==> {
303            proof::infinite_row(*f, i@, j@, b@, k@); true
304        });
305        proof_assert!(f[k@][j@].le(f[k@][i@].add(b@)) ==> {
306            proof::skip(*f, d@, i@, j@, b@, k@); true
307        });
308        proof_assert!(!f[k@][j@].le(f[k@][i@].add(b@)) && !f[k@][i@].add(b@).representable() ==> {
309            proof::skip_test_unrepresentable(*f, d@, i@, j@, b@, k@); true
310        });
311        snapshot!(proof::phase2(*f, d@, i@, j@, b@, k@));
312        proof_assert!(forall<l: Int> 0 <= l && l < d@
313        && relax_needed(f[k@][l], f[k@][i@], e[i@][l]) && !f[k@][i@].add_in_range(e[i@][l]) ==> {
314            proof::add_repr(f[k@][i@], e[i@][l]);
315            proof::edge_unrep_intro(*f, d@, i@, j@, b@, k@, l);
316            true
317        });
318        let before = snapshot!(*m);
319        let ki = m.get(k, i);
320        if k != i && !ki.is_infinite() {
321            // Update unless D[k][i] ⊕ b ≽ D[k][j].
322            let tightens = match relax(m.get(k, j), ki, b) {
323                Ok(s) => s.is_some(),
324                Err(e) => return Err(e),
325            };
326            if tightens {
327                // D'[k][l] = min(D[k][l], D[k][i] ⊕ D'[i][l]).
328                if m.relax_row(k, i, ki) {
329                    return Err(Error::Range);
330                }
331                proof_assert!(forall<l: Int> 0 <= l && l < d@ ==> {
332                    proof::relax_min(f[k@][l], f[k@][i@], e[i@][l], m.at(k@, l)@);
333                    m.at(k@, l)@ == e[k@][l]
334                });
335            }
336        }
337        proof_assert!(forall<k2: Int, l: Int> 0 <= k2 && k2 < d@ && k2 != k@ && 0 <= l && l < d@ ==>
338            m.at(k2, l) == before.at(k2, l));
339        k += 1;
340    }
341    Ok(())
342}
343
344/// `close(z ∧ xᵢ − xⱼ ⋈ b)` for validated indices.
345#[check(terminates)]
346#[requires(i@ <= z.variables_logic() && j@ <= z.variables_logic())]
347#[ensures(match result {
348    Ok(r) => r.variables_logic() == z.variables_logic()
349        && (forall<u: crate::dbm::proof::Val> r.zone(u) == (z.zone(u) && sat(b@, u[i@] - u[j@])))
350        && (!r.is_empty_logic() ==> meq(r.mmat(), edge(z.mmat(), i@, j@, b@), z.variables_logic() + 1)),
351    Err(e) => e == Error::Range && !z.is_empty_logic()
352        && single_range_failure(z.mmat(), z.variables_logic() + 1, i@, j@, b@),
353})]
354// An implied constraint returns the input itself.
355#[ensures(!z.is_empty_logic() && z.mmat()[i@][j@].le(b@) ==> result == Ok(z))]
356fn constrain_one(z: Dbm, i: usize, j: usize, b: Bound) -> Result<Dbm, Error> {
357    let dd = snapshot!(z.variables_logic() + 1);
358    let f = snapshot!(z.mmat());
359    snapshot!(z.model());
360    if z.is_empty() {
361        return Ok(z);
362    }
363    // Implied: D[i][j] ≼ b.
364    if !tighter(b, z.entry(i, j)) {
365        snapshot!(order_refines(b, z.at(i@, j@)));
366        snapshot!(crate::bounds::le_total(b@, f[i@][j@]));
367        snapshot!(proof::implied(*f, *dd, i@, j@, b@));
368        return Ok(z);
369    }
370    snapshot!(order_refines(b, z.at(i@, j@)));
371    snapshot!(crate::bounds::le_total(b@, f[i@][j@]));
372    // Contradiction: the cycle i → j → i is negative.
373    if below_le_zero(b, z.entry(j, i)) {
374        snapshot!(proof::contradiction(*f, *dd, i@, j@, b@));
375        return Ok(z.empty_like());
376    }
377    snapshot!(edge_canonical(*f, *dd, i@, j@, b@));
378    snapshot!(edge_zone(*f, *dd, i@, j@, b@));
379    let n = z.variables();
380    let mut m = match z.into_matrix() {
381        Some(m) => m,
382        // Unreachable: `z` is nonempty.
383        None => return Dbm::empty(n),
384    };
385    // One actual clock (d = 2): after the two tests above, the closure
386    // changes only (i, j). The other off-diagonal entry gains
387    // `b + D[j][i] ≽ Le 0` and each diagonal entry `D[j][i] + b ≽ Le 0`, so
388    // neither tightens (the remaining entries are unchanged at `dim ≤ 2`).
389    if m.dimension() == 2 {
390        snapshot!(m.model());
391        snapshot!(proof::one_clock(*f, *dd, i@, j@, b@));
392        m.set(i, j, b);
393        snapshot!(m.model());
394        proof_assert!(meq(m.mmat(), edge(*f, i@, j@, b@), *dd));
395        snapshot!(meq_transfer(m.mmat(), edge(*f, i@, j@, b@), *dd));
396        return Ok(m.publish_canonical());
397    }
398    match close_edge(&mut m, i, j, b) {
399        Ok(()) => {
400            snapshot!(m.model());
401            proof_assert!(meq(m.mmat(), edge(*f, i@, j@, b@), *dd));
402            snapshot!(meq_transfer(m.mmat(), edge(*f, i@, j@, b@), *dd));
403            Ok(m.publish_canonical())
404        }
405        Err(e) => Err(e),
406    }
407}
408
409/// How `try_constrain_all` closes a batch.
410#[derive(Clone, Copy, Debug)]
411pub(crate) enum Strategy {
412    /// One incremental closure per constraint.
413    Incremental,
414    /// Tighten every entry, then one full closure.
415    FullClosure,
416}
417
418impl Strategy {
419    /// `k` incremental closures cost at most `k·d²` (vectorized row
420    /// updates, usually far fewer rows), one full closure `d³` (scalar).
421    /// Measured on consistent random batches, incremental insertion stays
422    /// 3–5× faster than full closure up to `k = 4d` for `n ≥ 16` (on one
423    /// Apple Silicon host); in the worst case (every guard rewriting every
424    /// row) it can do up to about 4× the entry updates of one full closure.
425    #[check(terminates)]
426    #[requires(dimension@ <= 46_340)]
427    #[ensures(result == if constraints@ <= 4 * dimension@ {
428        Strategy::Incremental
429    } else {
430        Strategy::FullClosure
431    })]
432    pub(crate) fn choose(dimension: usize, constraints: usize) -> Strategy {
433        if constraints <= 4 * dimension {
434            Strategy::Incremental
435        } else {
436            Strategy::FullClosure
437        }
438    }
439}
440
441impl Dbm {
442    /// The indices of `c`, or `Err(ClockOutOfRange)` (checked also on `∅_d`).
443    #[check(terminates)]
444    #[ensures(match result {
445        Ok((i, j)) => valid(c, self.variables_logic()) && i@ == c@.0 && j@ == c@.1,
446        Err(e) => !valid(c, self.variables_logic()) && clock_error(c, self.variables_logic(), e),
447    })]
448    pub(crate) fn check_constraint(&self, c: Constraint) -> Result<(usize, usize), Error> {
449        let i = match self.check_clock(c.i()) {
450            Ok(i) => i,
451            Err(e) => return Err(e),
452        };
453        match self.check_clock(c.j()) {
454            Ok(j) => Ok((i, j)),
455            Err(e) => Err(e),
456        }
457    }
458
459    /// Restricts this zone by a difference constraint `c`.
460    ///
461    /// The result contains **exactly those valuations of this zone that
462    /// satisfy `c`**. It is canonical or empty on success. Inconsistent
463    /// constraints produce a successful empty zone, not an error.
464    ///
465    /// # Errors
466    ///
467    /// - [`Error::ClockOutOfRange`] if either clock in `c` is outside
468    ///   this zone's clock range, including when the zone is empty;
469    /// - [`Error::Range`] if an exact finite bound needed for the result
470    ///   lies outside the representable integer range. Such a bound is
471    ///   never saturated, and no partially updated zone is returned.
472    ///
473    /// # Complexity
474    ///
475    /// For `d = self.dimension()`, an implied or directly contradictory
476    /// constraint is handled in `O(1)` time. Otherwise the worst-case cost
477    /// is `O(d²)`.
478    #[check(terminates)]
479    #[ensures(match result {
480        Ok(r) => valid(c, self.variables_logic())
481            && r.variables_logic() == self.variables_logic()
482            && (forall<u: crate::dbm::proof::Val> r.zone(u) == (self.zone(u) && csat(c, u)))
483            && (!r.is_empty_logic() ==> meq(r.mmat(), edge(self.mmat(), c@.0, c@.1, c@.2),
484                self.variables_logic() + 1)),
485        Err(e) => if valid(c, self.variables_logic()) {
486            e == Error::Range && !self.is_empty_logic()
487                && single_range_failure(self.mmat(), self.variables_logic() + 1, c@.0, c@.1, c@.2)
488        } else {
489            clock_error(c, self.variables_logic(), e)
490        },
491    })]
492    pub fn try_constrain(self, c: Constraint) -> Result<Dbm, Error> {
493        match self.check_constraint(c) {
494            Ok((i, j)) => constrain_one(self, i, j, c.bound()),
495            Err(e) => Err(e),
496        }
497    }
498
499    /// Restricts this zone by the conjunction of all constraints in `cs`.
500    ///
501    /// The result contains **exactly those valuations of this zone that
502    /// satisfy every constraint in `cs`**. An inconsistent conjunction
503    /// produces a successful empty zone, not an error. When successful,
504    /// the resulting zone is independent of the order and repetition of
505    /// the constraints.
506    ///
507    /// All clock indices are checked before modification. Intermediate
508    /// [`Error::Range`] results can depend on the computation order even
509    /// when the final mathematical zone would be the same. No partial
510    /// result is returned. `ws` does not affect the result.
511    ///
512    /// # Errors
513    ///
514    /// - [`Error::ClockOutOfRange`] if any constraint names a clock
515    ///   outside this zone, even if the zone is empty;
516    /// - [`Error::Range`] if an exact intermediate finite bound
517    ///   cannot be represented.
518    ///
519    /// # Complexity
520    ///
521    /// For `k = cs.len()` and `d = self.dimension()`, checking arguments
522    /// and immediate contradictions costs `O(k)`. The selected strategy then
523    /// takes at most `O(k d²)` for `k <= 4d`, or `O(k + d³)` for
524    /// larger batches. `ws` is currently unused.
525    #[check(terminates)]
526    #[ensures(match result {
527        Ok(r) => all_valid(cs@, self.variables_logic())
528            && r.variables_logic() == self.variables_logic()
529            && forall<u: crate::dbm::proof::Val> r.zone(u) == (self.zone(u) && conj(cs@, cs@.len(), u)),
530        Err(e) => if all_valid(cs@, self.variables_logic()) {
531            e == Error::Range && !self.is_empty_logic() && batch_range_failure(self, cs@)
532        } else {
533            first_clock_error(cs@, self.variables_logic(), e)
534        },
535    })]
536    // Exactness of the early returns: a contradiction found by the
537    // pre-pass, or a batch of implied constraints inserted incrementally,
538    // never yields `Err`.
539    #[ensures(all_valid(cs@, self.variables_logic()) && !self.is_empty_logic()
540        && (some_contradiction(self, cs@)
541            || (cs@.len() <= 4 * (self.variables_logic() + 1) && all_implied(self, cs@)))
542        ==> match result { Ok(_) => true, Err(_) => false })]
543    pub fn try_constrain_all(self, cs: &[Constraint], ws: &mut Workspace) -> Result<Dbm, Error> {
544        let _ = ws;
545        snapshot!(self.model());
546        let strategy = Strategy::choose(self.dimension(), cs.len());
547        self.constrain_all_with(cs, strategy)
548    }
549
550    /// `try_constrain_all` with an explicit strategy (also used by tests).
551    #[check(terminates)]
552    #[ensures(match result {
553        Ok(r) => all_valid(cs@, self.variables_logic())
554            && r.variables_logic() == self.variables_logic()
555            && forall<u: crate::dbm::proof::Val> r.zone(u) == (self.zone(u) && conj(cs@, cs@.len(), u)),
556        Err(e) => if all_valid(cs@, self.variables_logic()) {
557            e == Error::Range && !self.is_empty_logic() && batch_range_failure(self, cs@)
558        } else {
559            first_clock_error(cs@, self.variables_logic(), e)
560        },
561    })]
562    // Exactness of the early returns: a contradiction found by the
563    // pre-pass, or a batch of implied constraints inserted incrementally,
564    // never yields `Err`.
565    #[ensures(all_valid(cs@, self.variables_logic()) && !self.is_empty_logic()
566        && (some_contradiction(self, cs@)
567            || (strategy == Strategy::Incremental && all_implied(self, cs@)))
568        ==> match result { Ok(_) => true, Err(_) => false })]
569    pub(crate) fn constrain_all_with(
570        self,
571        cs: &[Constraint],
572        strategy: Strategy,
573    ) -> Result<Dbm, Error> {
574        let orig = snapshot!(self);
575        let n = snapshot!(self.variables_logic());
576        snapshot!(self.model());
577        let mut t: usize = 0;
578        #[invariant(t@ <= cs@.len())]
579        #[invariant(forall<s: Int> 0 <= s && s < t@ ==> valid(cs@[s], *n))]
580        #[variant(cs@.len() - t@)]
581        while t < cs.len() {
582            if let Err(e) = self.check_constraint(cs[t]) {
583                return Err(e);
584            }
585            t += 1;
586        }
587        if self.is_empty() {
588            return Ok(self);
589        }
590        // O(k) pre-pass: a constraint that contradicts the input on its own
591        // (`b + D[j][i] ≺ Le 0`) empties the whole conjunction.
592        let mut t: usize = 0;
593        #[invariant(t@ <= cs@.len())]
594        #[invariant(forall<s: Int> 0 <= s && s < t@ ==>
595            edge_ok(orig.mmat(), cs@[s]@.0, cs@[s]@.1, cs@[s]@.2))]
596        #[variant(cs@.len() - t@)]
597        while t < cs.len() {
598            let c = cs[t];
599            if below_le_zero(c.bound(), self.entry(c.j().index(), c.i().index())) {
600                snapshot!(proof::contradiction(orig.mmat(), *n + 1, c@.0, c@.1, c@.2));
601                proof_assert!(forall<u: crate::dbm::proof::Val> !(orig.zone(u) && csat(c, u)));
602                return Ok(self.empty_like());
603            }
604            t += 1;
605        }
606        match strategy {
607            Strategy::FullClosure => self.constrain_all_by_closure(cs),
608            Strategy::Incremental => {
609                let mut z = self;
610                let mut t: usize = 0;
611                #[invariant(t@ <= cs@.len())]
612                #[invariant(z.variables_logic() == *n)]
613                #[invariant(forall<u: crate::dbm::proof::Val> z.zone(u) == (orig.zone(u) && conj(cs@, t@, u)))]
614                #[invariant(all_implied(*orig, cs@) ==> z == *orig)]
615                #[variant(cs@.len() - t@)]
616                while t < cs.len() && !z.is_empty() {
617                    let c = cs[t];
618                    let before = snapshot!(z);
619                    snapshot!(before.model());
620                    z = match constrain_one(z, c.i().index(), c.j().index(), c.bound()) {
621                        Ok(z) => z,
622                        Err(e) => {
623                            proof_assert!(incremental_failure_at(*orig, cs@, t@, *before));
624                            return Err(e);
625                        }
626                    };
627                    t += 1;
628                }
629                snapshot!(z.model());
630                Ok(z)
631            }
632        }
633    }
634
635    /// Constructs the zone of all nonnegative-real clock valuations
636    /// satisfying **every constraint in `cs`**.
637    ///
638    /// The new zone has `variables` actual clocks plus the fixed
639    /// reference clock at zero. With no constraints, it is the universe
640    /// of all nonnegative valuations. An inconsistent set of constraints
641    /// gives a successful empty zone. The result is canonical or empty.
642    /// `ws` is used as temporary workspace; it has no semantic effect.
643    ///
644    /// # Errors
645    ///
646    /// - [`Error::TooManyVariables`] if `variables` exceeds
647    ///   [`MAX_VARIABLES`];
648    /// - [`Error::ClockOutOfRange`] if a constraint refers to a clock
649    ///   outside the new zone;
650    /// - [`Error::Range`] if exact closure requires an unrepresentable
651    ///   finite intermediate bound.
652    ///
653    /// [`MAX_VARIABLES`]: crate::MAX_VARIABLES
654    ///
655    /// # Complexity
656    ///
657    /// For `d = variables + 1` and `k = cs.len()`, allocating the
658    /// initial universe takes `O(d²)`. Applying the constraints costs at
659    /// most `O(k d²)` for `k <= 4d`, or `O(k + d³)` for larger batches.
660    #[check(terminates)]
661    #[ensures(match result {
662        Ok(r) => variables@ <= crate::MAX_VARIABLES@ && all_valid(cs@, variables@)
663            && r.variables_logic() == variables@
664            && forall<u: crate::dbm::proof::Val> r.zone(u) ==
665                (valuation(variables@ + 1, u) && conj(cs@, cs@.len(), u)),
666        Err(e) => if variables@ > crate::MAX_VARIABLES@ {
667            e == Error::TooManyVariables { requested: variables }
668        } else if all_valid(cs@, variables@) {
669            e == Error::Range && exists<z: Dbm> !z.is_empty_logic()
670                && z.variables_logic() == variables@
671                && (forall<u: crate::dbm::proof::Val> z.zone(u) == valuation(variables@ + 1, u))
672                && batch_range_failure(z, cs@)
673        } else {
674            first_clock_error(cs@, variables@, e)
675        },
676    })]
677    pub fn try_from_constraints(
678        variables: usize,
679        cs: &[Constraint],
680        ws: &mut Workspace,
681    ) -> Result<Dbm, Error> {
682        match Dbm::universe(variables) {
683            Ok(z) => {
684                snapshot!(z.model());
685                z.try_constrain_all(cs, ws)
686            }
687            Err(e) => Err(e),
688        }
689    }
690}
691
692#[cfg(creusot)]
693pub(crate) mod proof;
694
695#[cfg(test)]
696mod tests;