clock_dbm/shared.rs
1//! Shared zones with copy-on-write updates.
2//!
3//! Cloning a [`SharedDbm`] is cheap: handles share a zone until an update
4//! needs to change it. Existing snapshots remain unchanged, and an update
5//! can reuse uniquely owned storage. Sharing uses single-threaded `Rc`,
6//! not `Arc`; to move a zone to another thread, convert it to an owned
7//! [`Dbm`] with [`SharedDbm::into_dbm`].
8//!
9//! Shared and owned zones have the same mathematical operations. The
10//! [`SharedDbm`] API explains when copying can affect performance.
11
12// Source-level implementation and proof notes (not part of public API Rustdoc).
13// Shared canonical zones with copy-on-write updates.
14//
15// A shared zone contains valuations of nonnegative-real clocks.
16// The notation `∅_d` below means an empty zone with matrix dimension
17// `d`, including the fixed reference clock.
18//
19// [`SharedDbm`] is a reference-counted handle to an immutable [`Dbm`]
20// snapshot. Cloning it copies a pointer, not the `(n+1)²` matrix, so a
21// model checker can keep many states that share zones. Every operation has
22// exactly the result of the [`Dbm`] operation of the same name, including
23// every error; only the cost differs.
24//
25// # Copy-on-write
26//
27// An update takes `self` by value. If this handle is the only one, the
28// matrix is updated in place by the [`Dbm`] kernel, with no copy and no new
29// allocation. Otherwise the kernel updates a copy of the matrix, which gets
30// a new handle only on `Ok`, so the other handles keep their snapshot. On
31// `Err` the handle and any copy are dropped: no other handle changes and no
32// partial matrix is published. Published zones stay canonical or empty, as
33// for `Dbm`.
34//
35// Updates whose result is already known from the operands return without
36// copying, also for a shared handle. They are exactly the cases in which
37// the `Dbm` kernel itself returns before any bound arithmetic, so no
38// `Err(Range)` can be skipped:
39//
40// - an empty input (`∅_d` stays `∅_d`; argument errors are still reported);
41// - [`try_constrain`](SharedDbm::try_constrain) with an implied constraint
42// (the same handle) or a constraint that contradicts the zone (a new
43// `∅_d`, without copying the matrix);
44// - [`try_constrain_all`](SharedDbm::try_constrain_all) with a constraint
45// that contradicts the zone by itself, or with a batch of implied
46// constraints that the kernel inserts incrementally;
47// - [`try_intersect`](SharedDbm::try_intersect) with an empty operand, or,
48// for a shared handle, when `self ⊆ other` (an `O(d²)` comparison instead
49// of an `O(d²)` copy).
50//
51// # `Rc`, not `Arc`
52//
53// Zone-graph exploration, the intended use, commonly runs on one
54// thread, and every clone and drop of a handle touches the reference count.
55// `Rc` keeps those non-atomic. A `SharedDbm` is therefore not `Send`; use
56// [`SharedDbm::into_dbm`] to move a zone to another thread.
57//
58// # Workspace
59//
60// The operations that take a [`Workspace`] borrow it for one call only, as
61// for `Dbm`: one workspace per thread or exploration loop serves
62// owned and shared zones of any dimension. Sharing needs no extra scratch
63// memory.
64//
65// # Verification status
66//
67// Creusot checks this module (details and the trusted
68// base in `verification/PROOF_STATUS.md`):
69//
70// - every operation satisfies the contract of the [`Dbm`] operation of the
71// same name on the zone of the handle, including every error, for
72// unique and shared handles alike (both branches of `Rc::get_mut`);
73// - where a shortcut returns without the kernel, the kernel's contract is
74// proved to allow only that outcome: it excludes `Err` there, and equal
75// zones mean equal storage (canonical uniqueness);
76// - every handle holds a canonical-or-empty `Dbm`; `Clone`, `From<Dbm>`,
77// `into_dbm` and `as_dbm` preserve the zone, and `==` is `Dbm`'s,
78// whatever the pointers.
79//
80// Trusted: creusot-std's model of `Rc<T>` as a value of type `T`, and the
81// specifications of `Rc::get_mut`, `Rc::strong_count` and
82// `Rc::unwrap_or_clone` in `src/shared/rc_spec.rs`, which restate the
83// standard library's documentation. Snapshot isolation follows from that
84// model, because updates write through `Rc::get_mut` only. `Hash` is
85// outside Creusot's subset (as for `Dbm`) and covered by tests.
86//
87// ```
88// use clock_dbm::{Clock, Constraint, SharedDbm, Variable};
89//
90// let x = Variable::new(1).unwrap();
91// let z = SharedDbm::zero(1)?.future();
92// let snapshot = z.clone(); // no matrix copy
93// let z = z.try_constrain(Constraint::le(x.into(), Clock::ZERO, 5)?)?; // detaches
94// assert!(snapshot.is_subset_of(&z).is_ok_and(|b| !b));
95// assert!(z.is_subset_of(&snapshot)?);
96// # Ok::<(), clock_dbm::Error>(())
97// ```
98
99use std::convert::Infallible;
100use std::rc::Rc;
101
102use crate::bounds::{Bound, Clock, Constraint, Variable};
103#[cfg(creusot)]
104use crate::bounds::{le_total, order_refines};
105#[cfg(creusot)]
106use crate::dbm::proof::{Val, edge_ok};
107use crate::dbm::{Dbm, Workspace, tighter};
108use crate::error::Error;
109#[cfg(creusot)]
110use crate::ops::constraints::proof::{all_valid, conj, contradiction, csat, implied, valid};
111use crate::ops::constraints::{Strategy, below_le_zero};
112#[cfg(creusot)]
113use crate::ops::constraints::{all_implied, some_contradiction};
114use crate::ops::extra_m::MaxBounds;
115#[cfg(creusot)]
116use crate::ops::relations::proof::subset_pointwise;
117use creusot_std::prelude::*;
118
119#[cfg(creusot)]
120mod proof;
121#[cfg(creusot)]
122mod rc_spec;
123
124/// An immutable zone snapshot with cheap cloning and copy-on-write updates.
125///
126/// Cloning a `SharedDbm` takes `O(1)` time: it shares the underlying
127/// [`Dbm`] rather than copying the matrix. A consuming update reuses unique
128/// storage or copies a shared matrix (up to `O(d²)` entries for matrix
129/// dimension `d`). No update mutates an existing snapshot. Equality and
130/// hashing are semantic and independent of pointer identity.
131///
132/// `SharedDbm` uses `Rc` and is **not** `Send`. To transfer a zone between
133/// threads, first convert it into an owned [`Dbm`] with
134/// [`SharedDbm::into_dbm`].
135///
136/// # Example
137///
138/// ```
139/// use clock_dbm::{Clock, Constraint, SharedDbm};
140/// # fn main() -> Result<(), clock_dbm::Error> {
141/// let x = Clock::new(1).unwrap();
142/// let original = SharedDbm::universe(1)?;
143/// let branch = original.clone().try_constrain(Constraint::lt(x, Clock::ZERO, 5)?)?;
144/// assert!(branch.is_subset_of(&original)?);
145/// assert!(!original.entails(&Constraint::lt(x, Clock::ZERO, 5)?)?);
146/// # Ok(())
147/// # }
148/// ```
149#[derive(Debug)]
150// `Hash` is not translated by Creusot (see `Dbm`). `Rc` hashes the `Dbm` it
151// points to, so this is `Dbm`'s hash, consistent with the `PartialEq` below.
152#[cfg_attr(not(creusot), derive(Hash))]
153#[cfg_attr(not(creusot), allow(clippy::derived_hash_with_manual_eq))]
154pub struct SharedDbm(Rc<Dbm>);
155
156impl View for SharedDbm {
157 type ViewTy = Dbm;
158
159 /// The zone this handle denotes.
160 #[logic(open(self))]
161 fn view(self) -> Dbm {
162 pearlite! { *self.0@ }
163 }
164}
165
166/// Every handle denotes a valid `Dbm`: canonical or empty.
167impl Invariant for SharedDbm {
168 #[logic(open(self))]
169 fn invariant(self) -> bool {
170 pearlite! { self@.invariant() }
171 }
172}
173
174impl DeepModel for SharedDbm {
175 type DeepModelTy = (Int, Seq<Int>);
176
177 /// That of the zone: independent of the pointer.
178 #[logic(open(self))]
179 fn deep_model(self) -> (Int, Seq<Int>) {
180 pearlite! { self@.deep_model() }
181 }
182}
183
184/// The view of the result of a shared update.
185#[logic(open(self))]
186fn lift<E>(r: Result<SharedDbm, E>) -> Result<Dbm, E> {
187 pearlite! {
188 match r {
189 Ok(s) => Ok(s@),
190 Err(e) => Err(e),
191 }
192 }
193}
194
195/// `r` and `s` are the same outcome: equal zones (`Dbm`'s `Eq`) or the same
196/// error.
197#[logic(open(self))]
198fn same_outcome(r: Result<Dbm, Error>, s: Result<Dbm, Error>) -> bool {
199 pearlite! {
200 match (r, s) {
201 (Ok(a), Ok(b)) => a.deep_model() == b.deep_model(),
202 (Err(e), Err(f)) => e == f,
203 _ => false,
204 }
205 }
206}
207
208/// Canonical uniqueness (`Dbm::eq_semantic`) for every pair of valid DBMs:
209/// equal zones mean equal storage, so outcomes of the kernel's contract
210/// that agree on the zone are one outcome.
211#[logic(prophetic)]
212#[ensures(forall<a: Dbm, b: Dbm> inv(a) && inv(b) && a.variables_logic() == b.variables_logic()
213 && (forall<u: Val> a.zone(u) == b.zone(u)) ==> a.deep_model() == b.deep_model())]
214fn unique_zones() {
215 pearlite! {
216 proof_assert!(forall<a: Dbm, b: Dbm> inv(a) && inv(b)
217 && a.variables_logic() == b.variables_logic() ==> {
218 a.eq_semantic(b);
219 true
220 });
221 }
222}
223
224impl Clone for SharedDbm {
225 /// Copies the pointer, not the matrix.
226 #[check(terminates)]
227 #[ensures(result@ == self@)]
228 fn clone(&self) -> SharedDbm {
229 SharedDbm(Rc::clone(&self.0))
230 }
231}
232
233// Written out instead of derived, with the same code as std's `Rc` equality
234// for `T: Eq`: handles that share storage are equal without a comparison.
235impl PartialEq for SharedDbm {
236 #[ensures(result == (self.deep_model() == other.deep_model()))]
237 fn eq(&self, other: &SharedDbm) -> bool {
238 Rc::ptr_eq(&self.0, &other.0) || *self.0 == *other.0
239 }
240}
241
242impl Eq for SharedDbm {}
243
244impl From<Dbm> for SharedDbm {
245 /// Wraps `z` without copying its matrix.
246 #[check(terminates)]
247 #[ensures(result@ == z)]
248 fn from(z: Dbm) -> SharedDbm {
249 SharedDbm(Rc::new(z))
250 }
251}
252
253impl AsRef<Dbm> for SharedDbm {
254 #[check(terminates)]
255 #[ensures(*result == self@)]
256 fn as_ref(&self) -> &Dbm {
257 &self.0
258 }
259}
260
261// Each operation is specified by the contract of the `Dbm` operation of the
262// same name, applied to the zone of the handle: `Dbm::op.postcondition(args,
263// result)` is that operation's `ensures`, including every error case.
264impl SharedDbm {
265 /// Creates a shared zone in which all actual clocks equal zero.
266 ///
267 /// # Errors
268 ///
269 /// [`Error::TooManyVariables`] if the requested clock count is too large.
270 ///
271 /// # Complexity
272 ///
273 /// `O(d²)` time and space for `d = variables + 1`.
274 #[check(terminates)]
275 #[ensures(Dbm::zero.postcondition((variables,), lift(result)))]
276 pub fn zero(variables: usize) -> Result<SharedDbm, Error> {
277 match Dbm::zero(variables) {
278 Ok(z) => Ok(SharedDbm::from(z)),
279 Err(e) => Err(e),
280 }
281 }
282
283 /// Creates a shared zone containing all nonnegative-real clock valuations.
284 ///
285 /// # Errors
286 ///
287 /// [`Error::TooManyVariables`] if the requested clock count is too large.
288 ///
289 /// # Complexity
290 ///
291 /// `O(d²)` time and space for `d = variables + 1`.
292 #[check(terminates)]
293 #[ensures(Dbm::universe.postcondition((variables,), lift(result)))]
294 pub fn universe(variables: usize) -> Result<SharedDbm, Error> {
295 match Dbm::universe(variables) {
296 Ok(z) => Ok(SharedDbm::from(z)),
297 Err(e) => Err(e),
298 }
299 }
300
301 /// Creates a shared empty zone with the requested number of actual clocks.
302 /// The empty zone contains no valuations but retains its clock count.
303 ///
304 /// # Errors
305 ///
306 /// [`Error::TooManyVariables`] if the clock count is too large.
307 ///
308 /// # Complexity
309 ///
310 /// `O(1)` time, without allocating a matrix.
311 #[check(terminates)]
312 #[ensures(Dbm::empty.postcondition((variables,), lift(result)))]
313 pub fn empty(variables: usize) -> Result<SharedDbm, Error> {
314 match Dbm::empty(variables) {
315 Ok(z) => Ok(SharedDbm::from(z)),
316 Err(e) => Err(e),
317 }
318 }
319
320 /// Creates a shared zone containing exactly the nonnegative-real
321 /// valuations satisfying all constraints in `cs`. An inconsistent set returns
322 /// an empty zone. `ws` does not affect the mathematical result.
323 ///
324 /// # Errors
325 ///
326 /// [`Error::TooManyVariables`], [`Error::ClockOutOfRange`], or
327 /// [`Error::Range`] for an invalid clock count, invalid constraint index,
328 /// or unrepresentable finite intermediate bound, respectively.
329 ///
330 /// # Complexity
331 ///
332 /// For `d = variables + 1` and `k = cs.len()`, constructing the
333 /// universe takes `O(d²)`. Applying the constraints takes at most
334 /// `O(k d²)` for `k <= 4d`, or `O(k + d³)` for larger batches.
335 #[check(terminates)]
336 #[ensures(Dbm::try_from_constraints.postcondition((variables, cs, ws), lift(result)))]
337 pub fn try_from_constraints(
338 variables: usize,
339 cs: &[Constraint],
340 ws: &mut Workspace,
341 ) -> Result<SharedDbm, Error> {
342 match Dbm::try_from_constraints(variables, cs, ws) {
343 Ok(z) => Ok(SharedDbm::from(z)),
344 Err(e) => Err(e),
345 }
346 }
347
348 /// Converts this zone into an owned [`Dbm`], copying the matrix only
349 /// if another shared handle still references it.
350 ///
351 /// # Complexity
352 ///
353 /// `O(1)` for a unique handle; `O(d²)` if another handle shares
354 /// its matrix, where `d = self.dimension()`.
355 #[ensures(result == self@)]
356 pub fn into_dbm(self) -> Dbm {
357 Rc::unwrap_or_clone(self.0)
358 }
359
360 /// Borrows the underlying canonical or empty [`Dbm`] without copying.
361 ///
362 /// # Complexity
363 ///
364 /// `O(1)` time.
365 #[check(terminates)]
366 #[ensures(*result == self@)]
367 pub fn as_dbm(&self) -> &Dbm {
368 &self.0
369 }
370
371 /// Returns the number of actual clocks, excluding the reference clock.
372 ///
373 /// # Complexity
374 ///
375 /// `O(1)` time.
376 #[check(terminates)]
377 #[ensures(Dbm::variables.postcondition((&self@,), result))]
378 pub fn variables(&self) -> usize {
379 self.0.variables()
380 }
381
382 /// Returns the number of actual clocks plus the reference clock.
383 ///
384 /// # Complexity
385 ///
386 /// `O(1)` time.
387 #[check(terminates)]
388 #[ensures(Dbm::dimension.postcondition((&self@,), result))]
389 pub fn dimension(&self) -> usize {
390 self.0.dimension()
391 }
392
393 /// Returns whether this zone contains no clock valuations.
394 ///
395 /// # Complexity
396 ///
397 /// `O(1)` time.
398 #[check(terminates)]
399 #[ensures(Dbm::is_empty.postcondition((&self@,), result))]
400 pub fn is_empty(&self) -> bool {
401 self.0.is_empty()
402 }
403
404 /// Tests whether every valuation in this zone also belongs to `other`.
405 /// An empty zone is a subset of every zone of the same dimension.
406 ///
407 /// # Errors
408 ///
409 /// [`Error::DimensionMismatch`] for differing clock counts, including empty zones.
410 ///
411 /// # Complexity
412 ///
413 /// `O(d²)` in the worst case for matrix dimension
414 /// `d = self.dimension()`; empty-zone cases take `O(1)`.
415 #[check(terminates)]
416 #[ensures(Dbm::is_subset_of.postcondition((&self@, &other@), result))]
417 pub fn is_subset_of(&self, other: &SharedDbm) -> Result<bool, Error> {
418 self.0.is_subset_of(&other.0)
419 }
420
421 /// Tests whether **every** valuation in this zone satisfies `c`.
422 /// This returns `true` for an empty zone (vacuously), unlike
423 /// [`SharedDbm::intersects_constraint`].
424 ///
425 /// # Errors
426 ///
427 /// [`Error::ClockOutOfRange`] if `c` references a clock outside this zone.
428 ///
429 /// # Complexity
430 ///
431 /// `O(1)` time.
432 #[check(terminates)]
433 #[ensures(Dbm::entails.postcondition((&self@, c), result))]
434 pub fn entails(&self, c: &Constraint) -> Result<bool, Error> {
435 self.0.entails(c)
436 }
437
438 /// Tests whether **some** valuation in this zone satisfies `c`.
439 /// This returns `false` for an empty zone, unlike [`SharedDbm::entails`].
440 ///
441 /// # Errors
442 ///
443 /// [`Error::ClockOutOfRange`] if `c` references a clock outside this zone.
444 ///
445 /// # Complexity
446 ///
447 /// `O(1)` time.
448 #[check(terminates)]
449 #[ensures(Dbm::intersects_constraint.postcondition((&self@, c), result))]
450 pub fn intersects_constraint(&self, c: &Constraint) -> Result<bool, Error> {
451 self.0.intersects_constraint(c)
452 }
453
454 /// Returns the tightest bound on the difference `clock i - clock j`
455 /// satisfied by all valuations in this zone. Returns `None` for an
456 /// empty zone or [`Bound::INFINITY`] for an unbounded difference.
457 ///
458 /// # Errors
459 ///
460 /// [`Error::ClockOutOfRange`] if either clock index is outside this zone.
461 ///
462 /// # Complexity
463 ///
464 /// `O(1)` time.
465 #[check(terminates)]
466 #[ensures(Dbm::difference_bound.postcondition((&self@, i, j), result))]
467 pub fn difference_bound(&self, i: Clock, j: Clock) -> Result<Option<Bound>, Error> {
468 self.0.difference_bound(i, j)
469 }
470
471 /// Returns the zone of valuations that satisfy this zone and `c`.
472 /// An inconsistent constraint returns an empty zone. Other snapshots
473 /// remain unchanged.
474 ///
475 /// # Errors
476 ///
477 /// [`Error::ClockOutOfRange`] for an invalid clock index, or
478 /// [`Error::Range`] if exact closure needs an unrepresentable finite bound.
479 ///
480 /// # Complexity
481 ///
482 /// `O(1)` for an implied or directly contradictory constraint;
483 /// otherwise `O(d²)` in the worst case, including any copy of
484 /// a shared matrix, where `d = self.dimension()`.
485 #[ensures(Dbm::try_constrain.postcondition((self@, c), lift(result)))]
486 // The shortcuts: every outcome the kernel's contract allows is this one.
487 #[ensures(valid(c, self@.variables_logic())
488 && (self@.is_empty_logic() || self@.mmat()[c@.0][c@.1].le(c@.2)
489 || !edge_ok(self@.mmat(), c@.0, c@.1, c@.2))
490 ==> forall<r: Result<Dbm, Error>> Dbm::try_constrain.postcondition((self@, c), r)
491 ==> same_outcome(r, lift(result)))]
492 pub fn try_constrain(self, c: Constraint) -> Result<SharedDbm, Error> {
493 let z = &*self.0;
494 proof_assert!({
495 unique_zones();
496 true
497 });
498 let (i, j) = z.check_constraint(c)?;
499 let b = c.bound();
500 let f = snapshot!(z.mmat());
501 let dd = snapshot!(z.variables_logic() + 1);
502 snapshot!(z.model());
503 // The two O(1) tests of `constrain_one`, in the same order.
504 if z.is_empty() || !tighter(b, z.entry(i, j)) {
505 proof_assert!(z.is_empty_logic() || {
506 order_refines(b, z.at(i@, j@));
507 le_total(b@, f[i@][j@]);
508 implied(*f, *dd, i@, j@, b@);
509 true
510 });
511 return Ok(self);
512 }
513 snapshot!(order_refines(b, z.at(i@, j@)));
514 if below_le_zero(b, z.entry(j, i)) {
515 snapshot!(contradiction(*f, *dd, i@, j@, b@));
516 let e = z.empty_like();
517 snapshot!(e.model());
518 return Ok(SharedDbm::from(e));
519 }
520 self.update(|z| z.try_constrain(c))
521 }
522
523 /// Restricts the zone to valuations satisfying every constraint
524 /// in `cs`. An inconsistent conjunction returns an empty zone.
525 /// Other snapshots remain unchanged; `ws` cannot affect the result.
526 ///
527 /// # Errors
528 ///
529 /// [`Error::ClockOutOfRange`] for an invalid clock index, or
530 /// [`Error::Range`] for an unrepresentable finite intermediate bound.
531 ///
532 /// # Complexity
533 ///
534 /// Let `d = self.dimension()` and `k = cs.len()`. After `O(k)`
535 /// argument and contradiction checks, the selected strategy takes
536 /// at most `O(k d²)` for `k <= 4d` or `O(k + d³)` for larger batches.
537 /// Updating a shared matrix may also require an `O(d²)` copy.
538 #[ensures(Dbm::try_constrain_all.postcondition((self@, cs, ws), lift(result)))]
539 // The shortcuts: every outcome the kernel's contract allows is this one.
540 #[ensures(all_valid(cs@, self@.variables_logic())
541 && (self@.is_empty_logic() || some_contradiction(self@, cs@)
542 || (cs@.len() <= 4 * (self@.variables_logic() + 1) && all_implied(self@, cs@)))
543 ==> forall<r: Result<Dbm, Error>> Dbm::try_constrain_all.postcondition((self@, cs, ws), r)
544 ==> same_outcome(r, lift(result)))]
545 pub fn try_constrain_all(
546 self,
547 cs: &[Constraint],
548 ws: &mut Workspace,
549 ) -> Result<SharedDbm, Error> {
550 let z = &*self.0;
551 proof_assert!({
552 unique_zones();
553 true
554 });
555 let n = snapshot!(z.variables_logic());
556 let f = snapshot!(z.mmat());
557 snapshot!(z.model());
558 // The checks of `Dbm::constrain_all_with` before any update, in the
559 // same order: indices, emptiness, single-constraint contradiction.
560 let mut t: usize = 0;
561 #[invariant(t@ <= cs@.len())]
562 #[invariant(forall<s: Int> 0 <= s && s < t@ ==> valid(cs@[s], *n))]
563 #[variant(cs@.len() - t@)]
564 while t < cs.len() {
565 z.check_constraint(cs[t])?;
566 t += 1;
567 }
568 if z.is_empty() {
569 return Ok(self);
570 }
571 let mut t: usize = 0;
572 #[invariant(t@ <= cs@.len())]
573 #[invariant(forall<s: Int> 0 <= s && s < t@ ==>
574 edge_ok(*f, cs@[s]@.0, cs@[s]@.1, cs@[s]@.2))]
575 #[variant(cs@.len() - t@)]
576 while t < cs.len() {
577 let c = cs[t];
578 if below_le_zero(c.bound(), z.entry(c.j().index(), c.i().index())) {
579 snapshot!(contradiction(*f, *n + 1, c@.0, c@.1, c@.2));
580 proof_assert!(forall<u: Val> !(z.zone(u) && csat(c, u)));
581 let e = z.empty_like();
582 snapshot!(e.model());
583 return Ok(SharedDbm::from(e));
584 }
585 t += 1;
586 }
587 // Incremental insertion leaves the matrix untouched when every
588 // constraint is implied; a full closure might still report `Range`.
589 if matches!(
590 Strategy::choose(z.dimension(), cs.len()),
591 Strategy::Incremental
592 ) {
593 let mut t: usize = 0;
594 #[invariant(t@ <= cs@.len())]
595 #[invariant(forall<u: Val> z.zone(u) ==> conj(cs@, t@, u))]
596 #[variant(cs@.len() - t@)]
597 while t < cs.len() {
598 let c = cs[t];
599 let b = c.bound();
600 if tighter(b, z.entry(c.i().index(), c.j().index())) {
601 break;
602 }
603 snapshot!(order_refines(b, z.at(c@.0, c@.1)));
604 snapshot!(le_total(c@.2, f[c@.0][c@.1]));
605 snapshot!(implied(*f, *n + 1, c@.0, c@.1, c@.2));
606 t += 1;
607 }
608 if t == cs.len() {
609 return Ok(self);
610 }
611 }
612 self.update(|z| z.try_constrain_all(cs, ws))
613 }
614
615 /// Returns the zone of valuations present in both input zones.
616 /// An empty intersection is a successful empty result. Other snapshots
617 /// remain unchanged.
618 ///
619 /// # Errors
620 ///
621 /// [`Error::DimensionMismatch`] for differing clock counts, or
622 /// [`Error::Range`] if exact closure needs an unrepresentable finite
623 /// bound. `ws` only reuses temporary storage.
624 ///
625 /// # Complexity
626 ///
627 /// `O(d³)` in the worst case for matrix dimension
628 /// `d = self.dimension()`. Updating a shared matrix may add an
629 /// `O(d²)` copy; certain no-change cases avoid copying.
630 #[ensures(Dbm::try_intersect.postcondition((self@, &other@, ws), lift(result)))]
631 // The shortcuts: every outcome the kernel's contract allows is this one.
632 #[ensures(other@.variables_logic() == self@.variables_logic()
633 && (self@.is_empty_logic() || other@.is_empty_logic()
634 || forall<i: Int, j: Int>
635 0 <= i && i <= self@.variables_logic() && 0 <= j && j <= self@.variables_logic()
636 ==> self@.at(i, j).deep_model() <= other@.at(i, j).deep_model())
637 ==> forall<r: Result<Dbm, Error>> Dbm::try_intersect.postcondition((self@, &other@, ws), r)
638 ==> same_outcome(r, lift(result)))]
639 pub fn try_intersect(self, other: &SharedDbm, ws: &mut Workspace) -> Result<SharedDbm, Error> {
640 let z = &*self.0;
641 let o = &*other.0;
642 proof_assert!({
643 unique_zones();
644 true
645 });
646 z.check_variables(o.variables())?;
647 snapshot!(z.model());
648 snapshot!(o.model());
649 if z.is_empty() {
650 return Ok(self);
651 }
652 if o.is_empty() {
653 return Ok(SharedDbm::from(z.empty_like()));
654 }
655 // With `self ⊆ other` the kernel's meet tightens nothing, so it
656 // closes over no pivot and returns `self` unchanged. Only worth
657 // checking when the alternative is a copy.
658 if Rc::strong_count(&self.0) > 1 && (Rc::ptr_eq(&self.0, &other.0) || z.entries_le(o)) {
659 let d = snapshot!(z.variables_logic() + 1);
660 proof_assert!(forall<i: Int, j: Int> 0 <= i && i < *d && 0 <= j && j < *d ==> {
661 order_refines(z.at(i, j), o.at(i, j));
662 (z.at(i, j).deep_model() <= o.at(i, j).deep_model())
663 == z.mmat()[i][j].le(o.mmat()[i][j])
664 });
665 snapshot!(subset_pointwise(z.mmat(), o.mmat(), *d));
666 return Ok(self);
667 }
668 self.update(|z| z.try_intersect(o, ws))
669 }
670
671 /// Computes all valuations obtained by advancing every actual clock
672 /// by the **same nonnegative real delay**. The reference clock remains
673 /// zero and an empty zone remains empty. This operation cannot fail.
674 ///
675 /// # Complexity
676 ///
677 /// `O(d)` when uniquely owned; `O(d²)` when a shared matrix
678 /// must first be copied, where `d = self.dimension()`.
679 #[ensures(Dbm::future.postcondition((self@,), result@))]
680 pub fn future(self) -> SharedDbm {
681 let Ok(z) = self.update(|z| Ok::<_, Infallible>(z.future()));
682 z
683 }
684
685 /// Computes all valuations from which this zone can be reached by
686 /// advancing every actual clock by the **same nonnegative real delay**:
687 /// `{ v ≥ 0 | v + t lies in this zone for some real t ≥ 0 }`. Upper
688 /// bounds and differences between actual clocks are kept; lower bounds
689 /// are relaxed only as far as nonnegativity and the differences allow.
690 /// The reference clock remains zero, the clock count is unchanged, an
691 /// empty zone remains empty, and other handles to the same zone are not
692 /// affected. This operation cannot fail.
693 ///
694 /// # Complexity
695 ///
696 /// `O(d²)` whether uniquely owned or shared (a shared matrix is first
697 /// copied in `O(d²)`), where `d = self.dimension()`.
698 ///
699 /// # Examples
700 ///
701 /// ```
702 /// use clock_dbm::{Clock, Constraint, SharedDbm};
703 ///
704 /// let x = Clock::new(1).unwrap();
705 /// let z = SharedDbm::universe(1)?.try_constrain(Constraint::le(Clock::ZERO, x, -3)?)?;
706 /// let snapshot = z.clone();
707 /// let p = z.past(); // x ≥ 3 becomes x ≥ 0
708 /// assert_eq!(p, SharedDbm::universe(1)?);
709 /// assert!(snapshot.is_subset_of(&p)?);
710 /// assert_ne!(snapshot, p);
711 /// # Ok::<(), clock_dbm::Error>(())
712 /// ```
713 #[ensures(Dbm::past.postcondition((self@,), result@))]
714 pub fn past(self) -> SharedDbm {
715 let Ok(z) = self.update(|z| Ok::<_, Infallible>(z.past()));
716 z
717 }
718
719 /// Sets clock `x` to zero in every valuation, preserving all
720 /// other clock values. An empty zone remains empty.
721 ///
722 /// # Errors
723 ///
724 /// [`Error::ClockOutOfRange`] if `x` is not an actual clock of this zone.
725 ///
726 /// # Complexity
727 ///
728 /// `O(d)` when uniquely owned, or `O(d²)` if the matrix
729 /// must be copied because it is shared, where `d = self.dimension()`.
730 #[ensures(Dbm::try_reset_zero.postcondition((self@, x), lift(result)))]
731 pub fn try_reset_zero(self, x: Variable) -> Result<SharedDbm, Error> {
732 self.update(|z| z.try_reset_zero(x))
733 }
734
735 /// Sets clock `x` to `value` in every valuation, keeping all
736 /// other clock values unchanged. An empty zone remains empty.
737 ///
738 /// # Errors
739 ///
740 /// In order: [`Error::ClockOutOfRange`] if `x` is invalid,
741 /// [`Error::NegativeConstant`] if `value` is negative, and
742 /// [`Error::Range`] if the zone is nonempty and `value` exceeds
743 /// [`crate::MAX_CONSTANT`].
744 ///
745 /// # Complexity
746 ///
747 /// `O(d)` when uniquely owned, or `O(d²)` if the matrix
748 /// must be copied because it is shared, where `d = self.dimension()`.
749 #[ensures(Dbm::try_reset.postcondition((self@, x, value), lift(result)))]
750 pub fn try_reset(self, x: Variable, value: i32) -> Result<SharedDbm, Error> {
751 self.update(|z| z.try_reset(x, value))
752 }
753
754 /// Allows clock `x` to take **any nonnegative real value** while
755 /// keeping the values of all other clocks unchanged. The clock remains
756 /// part of the zone; an empty zone remains empty.
757 ///
758 /// # Errors
759 ///
760 /// [`Error::ClockOutOfRange`] if `x` is not an actual clock of this zone.
761 ///
762 /// # Complexity
763 ///
764 /// `O(d)` when uniquely owned, or `O(d²)` if the matrix
765 /// must be copied because it is shared, where `d = self.dimension()`.
766 #[ensures(Dbm::try_free.postcondition((self@, x), lift(result)))]
767 pub fn try_free(self, x: Variable) -> Result<SharedDbm, Error> {
768 self.update(|z| z.try_free(x))
769 }
770
771 /// Returns a canonical maximal-constant overapproximation
772 /// using the ceilings in `bounds`. Every original valuation remains
773 /// possible, but additional valuations may appear. Reachability preservation
774 /// requires the usual automaton-level restrictions on guards, invariants,
775 /// resets and ceilings. An empty zone remains empty.
776 ///
777 /// # Errors
778 ///
779 /// [`Error::DimensionMismatch`] if the ceilings cover a different clock
780 /// count, or [`Error::Range`] if closure needs an unrepresentable finite
781 /// bound. `ws` only reuses temporary storage.
782 ///
783 /// # Complexity
784 ///
785 /// For `d = self.dimension()`, normalization takes `O(d²)`;
786 /// closure can take `O(d³)` if an entry changes. A shared matrix
787 /// may also require an `O(d²)` copy before updating.
788 #[ensures(Dbm::try_extrapolate_max.postcondition((self@, bounds, ws), lift(result)))]
789 pub fn try_extrapolate_max(
790 self,
791 bounds: &MaxBounds,
792 ws: &mut Workspace,
793 ) -> Result<SharedDbm, Error> {
794 self.update(|z| z.try_extrapolate_max(bounds, ws))
795 }
796
797 /// Applies a consuming `Dbm` operation to the zone of this handle. If
798 /// the handle is unique (`Rc::get_mut`), the zone is moved out (leaving
799 /// an unallocated `∅_d` placeholder), updated in place by the kernel and
800 /// moved back, so the handle keeps its `Rc` allocation. Otherwise the
801 /// kernel updates a copy, which gets a new `Rc` only on `Ok`. On `Err`
802 /// the handle, with its placeholder or its share, is dropped.
803 ///
804 /// `Rc::make_mut` would do the same, but its `CloneToUninit` bound
805 /// leaves no sound way to tie its copy to `Dbm::clone`'s contract
806 /// in the pinned verification environment; `get_mut` needs no such bound.
807 // The `Dbm` behind a handle is valid (`inv`); `Rc`'s abstract invariant
808 // only exposes that through `Deref` and `get_mut`.
809 #[requires(forall<z: Dbm> z == self@ && inv(z) ==> f.precondition((z,)))]
810 #[ensures(f.postcondition_once((self@,), lift(result)))]
811 fn update<E, F: FnOnce(Dbm) -> Result<Dbm, E>>(mut self, f: F) -> Result<SharedDbm, E> {
812 match Rc::get_mut(&mut self.0) {
813 Some(slot) => {
814 let placeholder = slot.empty_like();
815 match f(std::mem::replace(slot, placeholder)) {
816 Ok(z) => {
817 *slot = z;
818 Ok(self)
819 }
820 Err(e) => Err(e),
821 }
822 }
823 None => match f(Dbm::clone(&self.0)) {
824 Ok(z) => Ok(SharedDbm::from(z)),
825 Err(e) => Err(e),
826 },
827 }
828 }
829
830 /// Whether two handles share storage (tests only; not equality).
831 #[cfg(test)]
832 pub(crate) fn ptr_eq(&self, other: &SharedDbm) -> bool {
833 Rc::ptr_eq(&self.0, &other.0)
834 }
835}
836
837#[cfg(test)]
838mod tests;