vstd_extra/panic.rs
1//! Runtime panic helper whose type (`-> !`) lets Verus discharge
2//! post-conditions by branch elimination at the call site.
3use vstd::prelude::*;
4use vstd::vpanic;
5
6verus! {
7
8mod internal {
9 // Public for unfolding the open spec function, with no public path to the marker.
10 pub uninterp spec fn may_panic() -> bool;
11
12}
13
14/// Requires permission to panic when the condition holds.
15/// A false condition discharges this precondition without panic permission.
16pub open spec fn allowed_to_panic_if(condition: bool) -> bool {
17 condition ==> internal::may_panic()
18}
19
20/// Unconditionally panics. The caller must permit a panic.
21#[verifier::external_body]
22pub fn panic_diverge() -> !
23 requires
24 allowed_to_panic_if(true),
25{
26 vpanic!("");
27}
28
29/// Extension trait providing a panicking `unwrap` that models Rust's
30/// real `Option::unwrap` semantics.
31///
32/// Verus' `Option::unwrap` carries a `requires self is Some`; Rust's
33/// `unwrap` instead panics on `None`. `unwrap_or_panic` *diverges* on
34/// `None` (via [`panic_diverge`]) — a sound model of the real panic —
35/// and discharges `is_present()` (i.e. `self is Some` for `Option`) at
36/// the call site by branch elimination, so callers need not prove the
37/// value is populated.
38pub trait UnwrapOrPanic: Sized {
39 type Inner;
40
41 spec fn is_present(&self) -> bool;
42
43 spec fn payload(&self) -> Self::Inner;
44
45 fn unwrap_or_panic(self) -> (r: Self::Inner)
46 requires
47 allowed_to_panic_if(!self.is_present()),
48 ensures
49 self.is_present(),
50 r == self.payload(),
51 ;
52}
53
54impl<T> UnwrapOrPanic for Option<T> {
55 type Inner = T;
56
57 open spec fn is_present(&self) -> bool {
58 self is Some
59 }
60
61 open spec fn payload(&self) -> T {
62 self->0
63 }
64
65 fn unwrap_or_panic(self) -> (r: T) {
66 match self {
67 Some(v) => v,
68 None => panic_diverge(),
69 }
70 }
71}
72
73} // verus!