Skip to main content

vstd/resource/
pcm.rs

1use super::super::prelude::*;
2use super::Loc;
3use super::algebra::ResourceAlgebra;
4use super::relations::*;
5use super::trusted;
6
7#[cfg(verus_keep_ghost)]
8use super::super::modes::tracked_swap;
9
10verus! {
11
12broadcast use super::super::iset::group_iset_lemmas;
13
14/// Interface for PCM / Resource Algebra ghost state.
15///
16/// RA-based ghost state is a well-established theory that is especially
17/// useful for verifying concurrent code. An introduction to the concept
18/// can be found in
19/// [Iris: Monoids and Invariants as an Orthogonal Basis for Concurrent Reasoning](https://iris-project.org/pdfs/2015-popl-iris1-final.pdf)
20/// or
21/// [Iris from the ground up](https://people.mpi-sws.org/~dreyer/papers/iris-ground-up/paper.pdf).
22///
23/// To embed the concept into Verus, we:
24///  * Use a trait, [`PCM`], to embed the well-formedness laws of a resource algebra
25///  * use a "tracked ghost" object, `Resource<P>` (this page) to represent ownership of a resource.
26///
27/// Most operations are fairly standard, just "translated" from the usual CSL presentation into Verus.
28///
29///  * [`alloc`](Self::alloc) to allocate a resource.
30///  * [`join`](Self::join) to combine two resources via `P::op`, and [`split`](Self::split), its inverse.
31///  * [`validate`](Self::validate) to assert the validity of any held resource.
32///  * [`update`](Self::update) or [`update_nondeterministic`](Self::update_nondeterministic) to perform a frame-preserving update.
33///
34/// The interface also includes a nontrivial extension for working with _shared references_ to resources.
35/// Shared resources do not compose in a "separating" way via `P::op`, but rather, in a "potentially overlapping" way ([`join_shared`](Self::join_shared)). Shared resources can also be used to "help" perform frame-preserving updates, as long as they themselves do not change ([`update_with_shared`](Self::update_with_shared)).
36///
37/// ### Examples
38///
39/// See:
40///  * Any of the examples in [this directory](https://github.com/verus-lang/verus/tree/main/examples/pcm)
41///  * The source code for the [fractional resource library](super::frac::FracGhost)
42///
43/// ### See also
44///
45/// The ["storage protocol"](super::storage_protocol::StorageResource) formalism
46/// is an even more significant
47/// extension with additional capabilities for interacting with shared resources.
48///
49/// [VerusSync](https://verus-lang.github.io/verus/state_machines/intro.html) provides a higher-level
50/// "swiss army knife" for building useful ghost resources.
51#[verifier::accept_recursive_types(P)]
52pub tracked struct Resource<P: PCM> {
53    r: trusted::ra::Resource<P>,
54}
55
56#[cfg(verus_keep_ghost)]
57#[verifier::external]
58impl<P: PCM> !Copy for Resource<P> {
59
60}
61
62#[verifier::accept_recursive_types(P)]
63pub tracked struct CopyableResource<P: PCM> {
64    tracked r: trusted::ra::CopyableResource<P>,
65}
66
67impl<P: PCM> Copy for CopyableResource<P> {
68
69}
70
71impl<P: PCM> Clone for CopyableResource<P> {
72    #[verifier::external_body]
73    fn clone(&self) -> Self {
74        *self
75    }
76}
77
78/// A Partial Commutative Monoid is a special type of [`ResourceAlgebra`], where all elements have
79/// the same core (which belongs in the carrier), the unit. For this reason, they are also called
80/// unitary resource algebras[^note].
81///
82/// [^note]: This is slightly misleading. PCMs are partial in the sense that the operation is not
83/// defined for certain inputs. Because Verus does not support partial functions, we model that
84/// partiality with the validity predicate, which does make it a unitary resource algebra.
85pub trait PCM: ResourceAlgebra {
86    /// The unit of the monoid, i.e., the carrier value that composed with any other carrier value
87    /// yields the identity function
88    spec fn unit() -> Self;
89
90    /// The core of an element `a` is, by definition, some other element `x`
91    /// such that `a · x = a`
92    proof fn op_unit(self)
93        ensures
94            Self::op(self, Self::unit()) == self,
95    ;
96
97    /// The unit is always a valid element
98    proof fn unit_valid()
99        ensures
100            Self::unit().valid(),
101    ;
102}
103
104/// Every [`PCM`] is an [`RA`](trusted::ra::RA) in the sense of the trusted interface.
105impl<P: PCM> trusted::ra::RA for P {
106    open spec fn valid(self) -> bool {
107        <P as ResourceAlgebra>::valid(self)
108    }
109
110    open spec fn op(a: Self, b: Self) -> Self {
111        <P as ResourceAlgebra>::op(a, b)
112    }
113
114    open spec fn unit() -> Self {
115        <P as PCM>::unit()
116    }
117
118    proof fn associative(a: Self, b: Self, c: Self) {
119        <P as ResourceAlgebra>::associative(a, b, c);
120    }
121
122    proof fn commutative(a: Self, b: Self) {
123        <P as ResourceAlgebra>::commutative(a, b);
124    }
125
126    proof fn valid_op(a: Self, b: Self) {
127        <P as ResourceAlgebra>::valid_op(a, b);
128    }
129
130    proof fn op_unit(self) {
131        <P as PCM>::op_unit(self);
132    }
133
134    proof fn unit_valid() {
135        <P as PCM>::unit_valid();
136    }
137}
138
139impl<P: PCM> Resource<P> {
140    /// The underlying value of the resource
141    pub closed spec fn value(self) -> P {
142        self.r.value()
143    }
144
145    /// The location of the resource
146    pub closed spec fn loc(self) -> Loc {
147        self.r.loc()
148    }
149
150    proof fn mk_ref<'a>(tracked r: &'a trusted::ra::Resource<P>) -> (tracked res: &'a Self)
151        ensures
152            res.r == r,
153    {
154        shr_ref_struct_wrap(r, &Self { r: arbitrary() }, "", "r")
155    }
156
157    /// Allocate a new resource at a fresh location
158    // GHOST-ALLOC rule
159    pub proof fn alloc(value: P) -> (tracked out: Self)
160        requires
161            value.valid(),
162        ensures
163            out.value() == value,
164    {
165        Resource { r: trusted::ra::Resource::alloc(value) }
166    }
167
168    /// We can join together two resources at the same location, where we obtain the combination of
169    /// the two
170    // reverse implication in the GHOST-OP rule
171    pub proof fn join(tracked self, tracked other: Self) -> (tracked out: Self)
172        requires
173            self.loc() == other.loc(),
174        ensures
175            out.loc() == self.loc(),
176            out.value() == P::op(self.value(), other.value()),
177    {
178        Resource { r: self.r.join(other.r) }
179    }
180
181    /// If a resource holds the result of a composition, we can split it into the components
182    // implication in the GHOST-OP rule
183    pub proof fn split(tracked self, left: P, right: P) -> (tracked out: (Self, Self))
184        requires
185            self.value() == P::op(left, right),
186        ensures
187            out.0.loc() == self.loc(),
188            out.1.loc() == self.loc(),
189            out.0.value() == left,
190            out.1.value() == right,
191    {
192        let tracked (a, b) = self.r.split(left, right);
193        (Resource { r: a }, Resource { r: b })
194    }
195
196    /// Create a unit at a particular location
197    pub proof fn create_unit(loc: Loc) -> (tracked out: Self)
198        ensures
199            out.value() == P::unit(),
200            out.loc() == loc,
201    {
202        Resource { r: trusted::ra::Resource::create_unit(loc) }
203    }
204
205    /// Whenever we have a resource, that resource is valid. This intuitively (and inductively)
206    /// holds because:
207    ///     1. We only create valid resources (either via [`alloc`] or
208    ///        [`create_unit`](Self::create_unit)).
209    ///     2. We can only update the value of a resource via a [`frame_preserving_update`] (see
210    ///        [`update`](Self::update) for more details. Because of the requirement of that
211    ///        updates are frame preserving this means that `join`s remain valid.
212    // GHOST-VALID rule
213    pub proof fn validate(tracked &self)
214        ensures
215            self.value().valid(),
216    {
217        self.r.validate()
218    }
219
220    /// This is a more general version of [`update`](Self::update).
221    // GHOST-UPDATE rule
222    pub proof fn update_nondeterministic(tracked self, new_values: ISet<P>) -> (tracked out: Self)
223        requires
224            frame_preserving_update_nondeterministic(self.value(), new_values),
225        ensures
226            out.loc() == self.loc(),
227            new_values.contains(out.value()),
228    {
229        let tracked u = Self::create_unit(self.loc());
230        PCM::op_unit(self.value());
231        assert(set_op(new_values, u.value()) =~= new_values) by {
232            assert forall|x|
233                set_op(new_values, u.value()).contains(x) <==> #[trigger] new_values.contains(
234                    x,
235                ) by {
236                PCM::op_unit(x);
237                if set_op(new_values, u.value()).contains(x) {
238                    let q = choose|q| #[trigger] new_values.contains(q) && x == P::op(q, u.value());
239                    PCM::op_unit(q);
240                }
241            }
242        };
243        self.update_nondeterministic_with_shared(&u, new_values)
244    }
245
246    // VERIFIED
247    /// Update a resource to a new value. This can only be done if the update is frame preserving
248    /// (i.e., any value that could be composed with the original value can still be composed with
249    /// the new value).
250    ///
251    /// See [`frame_preserving_update`] for more information.
252    // variant of the GHOST-UPDATE rule
253    pub proof fn update(tracked self, new_value: P) -> (tracked out: Self)
254        requires
255            frame_preserving_update(self.value(), new_value),
256        ensures
257            out.loc() == self.loc(),
258            out.value() == new_value,
259    {
260        let new_values = iset![new_value];
261        assert(new_values.contains(new_value));
262        self.update_nondeterministic(new_values)
263    }
264
265    /// Extracts the resource from `r`, leaving `r` unspecified and returning
266    /// a new resource holding the previous value of `r`.
267    pub proof fn extract(tracked &mut self) -> (tracked other: Self)
268        ensures
269            other.loc() == old(self).loc(),
270            other.value() == old(self).value(),
271    {
272        self.validate();
273        let tracked mut other = Self::alloc(self.value());
274        tracked_swap(self, &mut other);
275        other
276    }
277
278    // Operations with shared references
279    /// This is useful when you have two (or more) shared resources and want to learn
280    /// that they agree, as you can combine this validate, e.g., `x.join_shared(y).validate()`.
281    pub proof fn join_shared<'a>(tracked &'a self, tracked other: &'a Self) -> (tracked out:
282        &'a Self)
283        requires
284            self.loc() == other.loc(),
285        ensures
286            out.loc() == self.loc(),
287            incl(self.value(), out.value()),
288            incl(other.value(), out.value()),
289    {
290        Self::mk_ref(self.r.join_shared(&other.r))
291    }
292
293    /// Extract a shared reference to a preceding element in the extension order from a shared reference.
294    pub proof fn weaken<'a>(tracked &'a self, target: P) -> (tracked out: &'a Self)
295        requires
296            incl(target, self.value()),
297        ensures
298            out.loc() == self.loc(),
299            out.value() == target,
300    {
301        let c = choose|c| P::op(target, c) == self.value();
302        assert(<P as trusted::ra::RA>::op(target, c) == self.value());
303        Self::mk_ref(self.r.weaken(target))
304    }
305
306    /// Validate two items at once. If we have two resources at the same location then its
307    /// composition is valid.
308    pub proof fn validate_2(tracked &mut self, tracked other: &Self)
309        requires
310            old(self).loc() == other.loc(),
311        ensures
312            *final(self) == *old(self),
313            P::op(final(self).value(), other.value()).valid(),
314    {
315        self.r.validate_2(&other.r)
316    }
317
318    /// We can do a similar update to [`update_with_shared`](Self::update_with_shared) for non-deterministic updates
319    pub proof fn update_nondeterministic_with_shared(
320        tracked self,
321        tracked other: &Self,
322        new_values: ISet<P>,
323    ) -> (tracked out: Self)
324        requires
325            self.loc() == other.loc(),
326            frame_preserving_update_nondeterministic(
327                P::op(self.value(), other.value()),
328                set_op(new_values, other.value()),
329            ),
330        ensures
331            out.loc() == self.loc(),
332            new_values.contains(out.value()),
333    {
334        let ghost bs = set_op(new_values, other.value());
335        let ghost f = |c: P| choose|b: P| #[trigger] bs.contains(b) && P::op(b, c).valid();
336        assert(trusted::ra::set_op(new_values, other.value()) =~= bs);
337        Resource { r: self.r.update_nondeterministic_with_shared(&other.r, new_values, f) }
338    }
339
340    // VERIFIED facts about shared references
341    /// We can do a similar update to [`update_with_shared`](Self::update_with_shared) for non-deterministic updates
342    pub proof fn join_shared_to_target<'a>(
343        tracked &'a self,
344        tracked other: &'a Self,
345        target: P,
346    ) -> (tracked out: &'a Self)
347        requires
348            self.loc() == other.loc(),
349            conjunct_shared(self.value(), other.value(), target),
350        ensures
351            out.loc() == self.loc(),
352            out.value() == target,
353    {
354        let tracked j = self.join_shared(other);
355        j.validate();
356        j.weaken(target)
357    }
358
359    /// If `x · y --> x · z` is a frame-perserving update, and we have a shared reference to `x`,
360    /// we can update the `y` resource to `z`.
361    pub proof fn update_with_shared(
362        tracked self,
363        tracked other: &Self,
364        new_value: P,
365    ) -> (tracked out: Self)
366        requires
367            self.loc() == other.loc(),
368            frame_preserving_update(
369                P::op(self.value(), other.value()),
370                P::op(new_value, other.value()),
371            ),
372        ensures
373            out.loc() == self.loc(),
374            out.value() == new_value,
375    {
376        let new_values = iset![new_value];
377        let so = set_op(new_values, other.value());
378        assert(so.contains(P::op(new_value, other.value())));
379        self.update_nondeterministic_with_shared(other, new_values)
380    }
381
382    /// If `x --> x · y` is a frame-perserving update, and we have a shared reference to `x`,
383    /// we can create a resource to y
384    pub proof fn duplicate_previous(tracked &self, value: P) -> (tracked out: Self)
385        requires
386            frame_preserving_update(self.value(), P::op(value, self.value())),
387        ensures
388            out.loc() == self.loc(),
389            out.value() == value,
390    {
391        let tracked mut unit = Self::create_unit(self.loc());
392        self.value().op_unit();
393        P::commutative(self.value(), unit.value());
394        unit.update_with_shared(self, value)
395    }
396
397    /// Wrap this resource in a type that implements `Copy`,
398    /// given that the resource is duplicable.
399    pub proof fn into_copyable(tracked self, p: P) -> (tracked r: CopyableResource<P>)
400        requires
401            P::op(P::op(self.value(), self.value()), p) == self.value(),
402        ensures
403            r.loc() == self.loc(),
404            r.value() == self.value(),
405    {
406        CopyableResource { r: self.r.into_copyable(p) }
407    }
408}
409
410/// A variant of [`Resource`] that implements `Copy`.
411///
412/// Use [`Self::into_resource`] to get the underlying resource.
413impl<P: PCM> CopyableResource<P> {
414    /// The underlying value of the resource
415    pub closed spec fn value(self) -> P {
416        self.r.value()
417    }
418
419    /// The location of the resource
420    pub closed spec fn loc(self) -> Loc {
421        self.r.loc()
422    }
423
424    pub proof fn into_resource(tracked self) -> (tracked r: Resource<P>)
425        ensures
426            r.loc() == self.loc(),
427            r.value() == self.value(),
428    {
429        Resource { r: self.r.into_resource() }
430    }
431}
432
433} // verus!