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