Skip to main content

vstd/
invariant.rs

1#[allow(unused_imports)]
2use super::pervasive::*;
3#[allow(unused_imports)]
4use super::prelude::*;
5
6// TODO:
7//  * utility for conveniently creating unique namespaces
8
9// An invariant storing objects of type V needs to be able to have some kind of configurable
10// predicate `V -> bool`. However, doing this naively with a fully configurable
11// predicate function would result in V being reject_recursive_types,
12// which is too limiting and prevents important use cases with recursive types.
13
14//
15// Instead, we allow the user to specify a predicate which is fixed *at the type level*
16// which we do through this trait, InvariantPredicate. However, the predicate still
17// needs to be "dynamically configurable" upon the call to the invariant constructor.
18// To support this, we add another type parameter K, a constant is fixed for a given
19// Invariant object.
20//
21// So each Invariant object has 3 type parameters:
22//  * K - A "constant" which is specified at constructor time
23//  * V - Type of the stored 'tracked' object
24//  * Pred: InvariantPredicate - provides the predicate (K, V) -> bool
25//
26// With this setup, we can now declare both K and V without reject_recursive_types.
27// To be sure, note that the following, based on our trait formalism,
28// is well-formed CIC (Coq), without any type polarity issues:
29//
30// ```
31//    Inductive InvariantPredicate K V :=
32//        | inv_pred : (K -> V -> bool) -> InvariantPredicate K V.
33//
34//    Inductive Inv (K V: Type) (x: InvariantPredicate K V) :=
35//      | inv : K -> Inv K V x.
36//
37//    Definition some_predicate (V: Type) : InvariantPredicate nat V :=
38//      inv_pred nat V (fun k v => false). (* an arbitrary predicate *)
39//
40//    (* example recursive type *)
41//    Inductive T :=
42//      | A : (Inv nat T (some_predicate T)) -> T.
43// ```
44//
45// Note that the user can always just set K to be `V -> bool` in order to make the
46// Invariant's predicate maximally configurable without having to restrict it at the
47// type level. By doing so, the user opts in to the negative usage of V in exchange
48// for the flexibility.
49
50verus! {
51
52/// Trait used to specify an _invariant predicate_ for
53/// [`LocalInvariant`] and [`AtomicInvariant`].
54pub trait InvariantPredicate<K, V> {
55    #[verifier::prophetic]
56    spec fn inv(k: K, v: V) -> bool;
57}
58
59} // verus!
60// LocalInvariant is NEVER `Sync`.
61//
62// Furthermore, for either type:
63//
64//  * If an Invariant<T> is Sync, then T must be Send
65//      * We could put the T in an Invariant, sync the invariant to another thread,
66//        and then extract the T, having effectively send it to the other thread.
67//  * If Invariant<T> is Send, then T must be Send
68//      * We could put the T in an Invariant, send the invariant to another thread,
69//        and then take the T out.
70//
71// So the Sync/Send-ness of the Invariant depends on the Send-ness of T;
72// however, the Sync-ness of T is unimportant (the invariant doesn't give you an extra
73// ability to share a reference to a T across threads).
74//
75// In conclusion, we should have:
76//
77//    T                   AtomicInvariant<T>  LocalInvariant<T>
78//
79//    {}          ==>     {}                  {}
80//    Send        ==>     Send+Sync           Send
81//    Sync        ==>     {}                  {}
82//    Sync+Send   ==>     Send+Sync           Send
83/// An `AtomicInvariant` is a ghost object that provides "interior mutability"
84/// for ghost objects, specifically, for `tracked` ghost objects.
85/// A reference `&AtomicInvariant` may be shared between clients.
86/// A client holding such a reference may _open_ the invariant
87/// to obtain ghost ownership of `v1: V`, and then _close_ the invariant by returning
88/// ghost ownership of a (potentially) different object `v2: V`.
89///
90/// An `AtomicInvariant` implements [`Sync`](https://doc.rust-lang.org/std/sync/)
91/// and may be shared between threads.
92/// However, this means that an `AtomicInvariant` can be only opened for
93/// the duration of a single _sequentially consistent atomic_ operation.
94/// Such operations are provided by our [`PAtomic`](crate::atomic) library.
95/// For an invariant object without this atomicity restriction,
96/// see [`LocalInvariant`], which gives up thread safety in exchange.
97///
98/// An `AtomicInvariant` consists of:
99///
100///  * A _predicate_ specified via the `InvariantPredicate` type bound, that determines
101///    what values `V` may be saved inside the invariant.
102///  * A _constant_ `K`, specified at construction type. The predicate function takes
103///    this constant as a parameter, so the constant allows users to dynamically configure
104///    the predicate function in a way that can't be done at the type level.
105///  * A _namespace_. This is a bit of a technicality, and you can often just declare
106///    it as an arbitrary integer with no issues. See the [`open_local_invariant!`]
107///    documentation for more details.
108///
109/// The constant and namespace are specified at construction time ([`AtomicInvariant::new`]).
110/// These values are fixed for the lifetime of the `AtomicInvariant` object.
111/// To open the invariant and access the stored object `V`,
112/// use the macro [`open_atomic_invariant!`].
113///
114/// The `AtomicInvariant` API is an instance of the ["invariant" method in Verus's general philosophy on interior mutability](https://verus-lang.github.io/verus/guide/interior_mutability.html).
115///
116/// **Note:** Rather than using `AtomicInvariant` directly, we generally recommend
117/// using the [`atomic_ghost` APIs](crate::atomic_ghost).
118#[cfg_attr(verus_keep_ghost, verifier::proof)]
119#[cfg_attr(verus_keep_ghost, verifier::external_body)] /* vattr */
120#[cfg_attr(verus_keep_ghost, verifier::accept_recursive_types(K))]
121#[cfg_attr(verus_keep_ghost, verifier::accept_recursive_types(V))]
122#[cfg_attr(verus_keep_ghost, verifier::accept_recursive_types(Pred))]
123pub struct AtomicInvariant<K, V, Pred> {
124    dummy: super::prelude::SyncSendIfSend<V>,
125    dummy1: super::prelude::AlwaysSyncSend<(K, Pred, *mut V)>,
126}
127
128/// A `LocalInvariant` is a ghost object that provides "interior mutability"
129/// for ghost objects, specifically, for `tracked` ghost objects.
130/// A reference `&LocalInvariant` may be shared between clients.
131/// A client holding such a reference may _open_ the invariant
132/// to obtain ghost ownership of `v1: V`, and then _close_ the invariant by returning
133/// ghost ownership of a (potentially) different object `v2: V`.
134///
135/// A `LocalInvariant` cannot be shared between threads
136/// (that is, it does not implement [`Sync`](https://doc.rust-lang.org/std/sync/)).
137/// However, this means that a `LocalInvariant` can be opened for an indefinite length
138/// of time, since there is no risk of a race with another thread.
139/// For an invariant object with the opposite properties, see [`AtomicInvariant`].
140///
141/// A `LocalInvariant` consists of:
142///
143///  * A _predicate_ specified via the `InvariantPredicate` type bound, that determines
144///    what values `V` may be saved inside the invariant.
145///  * A _constant_ `K`, specified at construction type. The predicate function takes
146///    this constant as a parameter, so the constant allows users to dynamically configure
147///    the predicate function in a way that can't be done at the type level.
148///  * A _namespace_. This is a bit of a technicality, and you can often just declare
149///    it as an arbitrary integer with no issues. See the [`open_local_invariant!`]
150///    documentation for more details.
151///
152/// The constant and namespace are specified at construction time ([`LocalInvariant::new`]).
153/// These values are fixed for the lifetime of the `LocalInvariant` object.
154/// To open the invariant and access the stored object `V`,
155/// use the macro [`open_local_invariant!`].
156///
157/// The `LocalInvariant` API is an instance of the ["invariant" method in Verus's general philosophy on interior mutability](https://verus-lang.github.io/verus/guide/interior_mutability.html).
158
159#[cfg_attr(verus_keep_ghost, verifier::proof)]
160#[cfg_attr(verus_keep_ghost, verifier::external_body)] /* vattr */
161#[cfg_attr(verus_keep_ghost, verifier::accept_recursive_types(K))]
162#[cfg_attr(verus_keep_ghost, verifier::accept_recursive_types(V))]
163#[cfg_attr(verus_keep_ghost, verifier::accept_recursive_types(Pred))]
164pub struct LocalInvariant<K, V, Pred> {
165    dummy: super::prelude::SendIfSend<V>,
166    dummy1: super::prelude::AlwaysSyncSend<(K, Pred, *mut V)>,
167}
168
169// redundant, just makes the error msg a bit nicer
170#[cfg(verus_keep_ghost)]
171impl<K, V, Pred> !Sync for LocalInvariant<K, V, Pred> {}
172
173macro_rules! declare_invariant_impl {
174    ($invariant:ident => $selfid:ident => $($into_inner_clause:tt)*) => {
175        // note the path names of `inv` and `namespace` are harcoded into the VIR crate.
176
177        verus!{
178
179        impl<K, V, Pred> $invariant<K, V, Pred> {
180            /// The constant specified upon the initialization of this `
181            #[doc = stringify!($invariant)]
182            ///`.
183            pub uninterp spec fn constant(&self) -> K;
184
185            /// Namespace the invariant was declared in.
186            #[rustc_diagnostic_item = concat!("verus::vstd::invariant::", stringify!($invariant), "::namespace")]
187            pub uninterp spec fn namespace(&self) -> int;
188        }
189
190        impl<K, V, Pred: InvariantPredicate<K, V>> $invariant<K, V, Pred> {
191            /// Returns `true` if it is possible to store the value `v` into the `
192            #[doc = stringify!($invariant)]
193            ///`.
194            ///
195            /// This is equivalent to `Pred::inv(self.constant(), v)`.
196
197            #[rustc_diagnostic_item = concat!("verus::vstd::invariant::", stringify!($invariant), "::inv")]
198            #[verifier::prophetic]
199            pub open spec fn inv(&self, v: V) -> bool {
200                Pred::inv(self.constant(), v)
201            }
202
203            /// Initialize a new `
204            #[doc = stringify!($invariant)]
205            ///` with constant `k`. initial stored (tracked) value `v`,
206            /// and in the namespace `ns`.
207
208            pub axiom fn new(k: K, tracked v: V, ns: int) -> (tracked i: $invariant<K, V, Pred>)
209                requires
210                    Pred::inv(k, v),
211                ensures
212                    i.constant() == k,
213                    i.namespace() == ns;
214
215            // Q. Why does AtomicInvariant::into_inner have an opens_invariant clause
216            // while LocalInvariant::into_inner doesn't?
217            //
218            // A. It has to do with the way we prevent double-opening via into_inner,
219            // i.e., how we prevent the user from calling into_inner on an already-open
220            // invariant:
221            //
222            // open_{atomic|local}_invariant!(&inv => i => {
223            //     inv.into_inner(); // this should error
224            // }
225            //
226            // There are two broad approaches:
227            // 1. Use the mask-checking, treating into_inner the same as an invariant-open
228            // 2. Use lifetimes, ensuring the borrow used to open the block extends through
229            //    the entire block.
230            //
231            // Approach (1) is easier to use, but (1) is not sound for LocalInvariants.
232            // Thus, we use approach (1) for AtomicInvariants and (2) for LocalInvariants.
233            //
234            // Q. Why is approach (1) easier for AtomicInvariants?
235            //
236            // A. This makes it easier to perform an atomic operation that relinquishes
237            //    the permission to access the same atomic.
238            //
239            // Q. Why is approach (1) unsound for LocalInvariants?
240            //
241            // A. Because into_inner is not the only problem. We want to implement
242            // the bound `impl<T: Send> => LocalInvariant<T>: Send`.
243            // Furthermore, moving a local invariant to another thread basically means moving
244            // the invariant from one thread's invariant pool to another, which basically
245            // needs the same restrictions as `into_inner`.
246            //
247            // open_{atomic|local}_invariant!(&inv => i => {
248            //     send_to_another_thread(inv); // this must be disallowed, too
249            // }
250            //
251            // However, we cannot (easily) put a mask bound on the send operation.
252            //
253            // Q. How are the lifetime restrictions implemented for LocalInvariant?
254            // The short answer is that we use the lifetime argument of the InvariantBlockGuard
255            // and force it to remain alive for the duration of the open_local_invariant! block.
256            // However, this requires special support from Verus in the lifetime-erasure system.
257            // See rustc_mir_build_additional_files/verus_builder.rs for more information.
258
259            /// Destroys the `
260            #[doc = stringify!($invariant)]
261            ///`, returning the tracked value contained within.
262
263            pub axiom fn into_inner(tracked $selfid) -> (tracked v: V)
264                ensures $selfid.inv(v),
265                $($into_inner_clause)* ;
266        }
267
268        }
269    };
270}
271
272declare_invariant_impl!(AtomicInvariant => self => opens_invariants [ self.namespace() ] );
273declare_invariant_impl!(LocalInvariant => self => );
274
275#[doc(hidden)]
276#[cfg_attr(verus_keep_ghost, verifier::proof)]
277pub struct InvariantBlockGuard<'a>(core::marker::PhantomData<&'a ()>);
278
279// In the "Logical Paradoxes" section of the Iris 4.1 Reference
280// (`https://plv.mpi-sws.org/iris/appendix-4.1.pdf`), they show that
281// opening invariants carries the risk of unsoundness.
282//
283// The paradox is similar to "Landin's knot", a short program that implements
284// an infinite loop by combining two features: higher-order closures
285// and mutable state:
286//
287//    let r := new_ref();
288//    r := () -> {
289//        let f = !r;
290//        f();
291//    };
292//    let f = !r;
293//    f();
294//
295// Invariants effectively serve as "mutable state"
296// Therefore, in order to implement certain higher-order features
297// like "proof closures" or "dyn", we need to make sure we have an
298// answer to this paradox.
299//
300// One solution to
301// this, described in the paper "Later Credits: Resourceful Reasoning
302// for the Later Modality" by Spies et al. (available at
303// `https://plv.mpi-sws.org/later-credits/paper-later-credits.pdf`) is
304// to use "later credits". That is, require the expenditure of a later
305// credit, only obtainable in exec mode, when opening an invariant. So
306// we require the relinquishment of a tracked
307// `OpenInvariantCredit` to open an invariant, and we provide an
308// exec-mode function `create_open_invariant_credit` to obtain one.
309
310verus! {
311
312#[cfg_attr(verus_keep_ghost, verifier::proof)]
313#[verifier::external_body]
314#[non_exhaustive]
315pub struct OpenInvariantCredit;
316
317/// Create a new `OpenInvariantCredit`.
318///
319/// Verus enforces certain restrictions to ensure that the number of credits is always
320/// bounded in terms of the number of _executable_ steps that have passed.
321/// This means a credit can be created in the middle of an executable function:
322///
323/// ```
324/// fn example() {
325///     let tracked credit1 = create_open_invariant_credit();
326///     let tracked credit2 = create_open_invariant_credit();
327///     let tracked credit3 = create_open_invariant_credit();
328/// }
329/// ```
330///
331/// But not in a `proof` function:
332///
333/// ```
334/// proof fn example() {
335///     let tracked credit = create_open_invariant_credit();
336///                       // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
337///                       // error: creating an invariant credit in potentially-unbounded ghost code
338/// }
339/// ```
340#[cfg(verus_keep_ghost)]
341#[rustc_diagnostic_item = "verus::vstd::invariant::create_open_invariant_credit"]
342#[verifier::create_open_invariant_credit]
343pub axiom fn create_open_invariant_credit() -> (tracked c: OpenInvariantCredit);
344
345} // verus!
346// NOTE: These 3 methods are removed in the conversion to VIR; they are only used
347// for encoding and borrow-checking.
348// In the VIR these are all replaced by the OpenInvariant block.
349// This means that the bodies, preconditions, and even their modes are not important.
350//
351// An example usage of the macro is like
352//
353//   i: AtomicInvariant<X>
354//
355//   open_invariant!(&i => inner => {
356//      { modify `inner` here }
357//   });
358//
359//  where `inner` will have type `X`.
360//
361// Why does this use the 'static type param for the InvariantBlockGuard? This is because
362// AtomicInvariant doesn't need the lifetime-checking like LocalInvariant does. See the explanation
363// over `into_inner`.
364#[cfg(verus_keep_ghost)]
365#[rustc_diagnostic_item = "verus::vstd::invariant::open_atomic_invariant_begin"]
366#[doc(hidden)]
367#[verifier::external] /* vattr */
368pub fn open_atomic_invariant_begin<'a, K, V, Pred: InvariantPredicate<K, V>>(
369    _credit: OpenInvariantCredit,
370    _inv: &'a AtomicInvariant<K, V, Pred>,
371) -> (InvariantBlockGuard<'static>, V) {
372    unimplemented!();
373}
374
375#[cfg(verus_keep_ghost)]
376#[rustc_diagnostic_item = "verus::vstd::invariant::open_local_invariant_begin"]
377#[doc(hidden)]
378#[verifier::external] /* vattr */
379pub fn open_local_invariant_begin<'a, K, V, Pred: InvariantPredicate<K, V>>(
380    _credit: OpenInvariantCredit,
381    _inv: &'a LocalInvariant<K, V, Pred>,
382) -> (InvariantBlockGuard<'a>, V) {
383    unimplemented!();
384}
385
386#[cfg(verus_keep_ghost)]
387#[rustc_diagnostic_item = "verus::vstd::invariant::open_invariant_end"]
388#[doc(hidden)]
389#[verifier::external] /* vattr */
390pub fn open_invariant_end<V>(_guard: InvariantBlockGuard, _v: V) {
391    unimplemented!();
392}
393
394/// Macro used to temporarily "open" an [`AtomicInvariant`] object, obtaining the stored
395/// value within.
396///
397/// ### Usage
398///
399/// The form of the macro looks like,
400///
401/// ```rust
402/// open_atomic_invariant($inv => $id => {
403///     // Inner scope
404/// });
405/// ```
406///
407/// This operation is very similar to [`open_local_invariant!`], so we refer to its
408/// documentation for the basics. There is only one difference, besides
409/// the fact that `$inv` should be an [`&AtomicInvariant`](AtomicInvariant)
410/// rather than a [`&LocalInvariant`](LocalInvariant).
411/// The difference is that `open_atomic_invariant!` has an additional _atomicity constraint_:
412///
413///  * **Atomicity constraint**: The code body of an `open_atomic_invariant!` block
414///    cannot contain any `exec`-mode code with the exception of a _single_ atomic operation.
415///
416/// (Of course, the code block can still contain an arbitrary amount of ghost code.)
417///
418/// The atomicity constraint is needed because an `AtomicInvariant` must be thread-safe;
419/// that is, it can be shared across threads. In order for the ghost state to be shared
420/// safely, it must be restored after each atomic operation.
421///
422/// The atomic operations may be found in the [`PAtomic`](crate::atomic) library.
423/// The user can also mark their own functions as "atomic operations" using
424/// `#[verifier::atomic)]`; however, this is not useful for very much other than defining
425/// wrappers around the existing atomic operations from [`PAtomic`](crate::atomic).
426/// Note that reading and writing through a [`PCell`](crate::cell::PCell)
427/// or a [`PPtr`](crate::simple_pptr::PPtr) are _not_ atomic operations.
428///
429/// **Note:** Rather than using `open_atomic_invariant!` directly, we generally recommend
430/// using the [`atomic_ghost` APIs](crate::atomic_ghost).
431///
432/// It's not legal to use `open_atomic_invariant!` in proof mode. In proof mode, you need
433/// to use `open_atomic_invariant_in_proof!` instead. This takes one extra parameter,
434/// an open-invariant credit, which you can get by calling
435/// `create_open_invariant_credit()` before you enter proof mode.
436
437/// ### Example
438///
439/// TODO fill this in
440
441// TODO the `$eexpr` argument here should be macro'ed in ghost context, not exec
442
443#[macro_export]
444macro_rules! open_atomic_invariant {
445    [$($tail:tt)*] => {
446        #[allow(unexpected_cfgs)] // make sure client crates don't see "unexpected `cfg` condition name: `verus_...`"
447        {
448            $crate::vstd::prelude::verus_exec_inv_macro_exprs!(
449                $crate::vstd::invariant::open_atomic_invariant_internal!($crate::vstd::invariant::create_open_invariant_credit() => $($tail)*)
450            )
451        }
452    };
453}
454
455#[macro_export]
456macro_rules! open_atomic_invariant_in_proof {
457    [$($tail:tt)*] => {
458        $crate::vstd::prelude::verus_ghost_inv_macro_exprs!($crate::vstd::invariant::open_atomic_invariant_in_proof_internal!($($tail)*))
459    };
460}
461
462#[macro_export]
463macro_rules! open_atomic_invariant_internal {
464    ($credit_expr:expr => $eexpr:expr => $iident:ident => $bblock:block) => {
465        #[cfg_attr(verus_keep_ghost, verifier::invariant_block)] /* vattr */ {
466            #[cfg(verus_keep_ghost_body)]
467            #[allow(unused_mut)] let (guard, mut $iident) =
468                $crate::vstd::invariant::open_atomic_invariant_begin($credit_expr, $eexpr);
469            $bblock
470            #[cfg(verus_keep_ghost_body)]
471            $crate::vstd::invariant::open_invariant_end(guard, $iident);
472        }
473    }
474}
475
476#[macro_export]
477macro_rules! open_atomic_invariant_in_proof_internal {
478    ($credit_expr:expr => $eexpr:expr => $iident:ident => $bblock:block) => {
479        #[cfg_attr(verus_keep_ghost, verifier::invariant_block)] /* vattr */ {
480            #[cfg(verus_keep_ghost_body)]
481            #[allow(unused_mut)] let (guard, mut $iident) =
482                $crate::vstd::invariant::open_atomic_invariant_begin($credit_expr, $eexpr);
483            $bblock
484            #[cfg(verus_keep_ghost_body)]
485            $crate::vstd::invariant::open_invariant_end(guard, $iident);
486        }
487    }
488}
489
490pub use open_atomic_invariant;
491pub use open_atomic_invariant_in_proof;
492#[doc(hidden)]
493pub use open_atomic_invariant_in_proof_internal;
494#[doc(hidden)]
495pub use open_atomic_invariant_internal;
496
497/// Macro used to temporarily "open" a [`LocalInvariant`] object, obtaining the stored
498/// value within.
499///
500/// ### Usage
501///
502/// The form of the macro looks like,
503///
504/// ```rust
505/// open_local_invariant($inv => $id => {
506///     // Inner scope
507/// });
508/// ```
509///
510/// The operation of opening an invariant is a ghost one; however, the inner code block
511/// may contain arbitrary `exec`-mode code. The invariant remains "open" for the duration
512/// of the inner code block, and it is closed again of the end of the block.
513///
514/// The `$inv` parameter should be an expression of type `&LocalInvariant<K, V, Pred>`,
515/// the invariant object to be opened. The `$id` is an identifier which is bound within
516/// the code block as a `mut` variable of type `V`. This gives the user ownership over
517/// the `V` value, which they may manipulate freely within the code block. At the end
518/// of the code block, the variable `$id` is consumed.
519///
520/// The obtained object `v: V`, will satisfy the `LocalInvariant`'s invariant predicate
521/// [`$inv.inv(v)`](LocalInvariant::inv). Furthermore, the user must prove that this
522/// invariant still holds at the end. In other words, the macro usage is
523/// roughly equivalent to the following:
524///
525/// ```rust
526/// {
527///     let $id: V = /* an arbitrary value */;
528///     assume($inv.inv($id));
529///     /* user code block here */
530///     assert($inv.inv($id));
531///     consume($id);
532/// }
533/// ```
534///
535/// ### Avoiding Reentrancy
536///
537/// Verus adds additional checks to ensure that an invariant is never opened
538/// more than once at the same time. For example, suppose that you attempt to nest
539/// the use of `open_invariant`, supplying the same argument `inv` to each:
540///
541/// ```rust
542/// open_local_invariant(inv => id1 => {
543///     open_local_invariant(inv => id2 => {
544///     });
545/// });
546/// ```
547///
548/// In this situation, Verus would produce an error:
549///
550/// ```
551/// error: possible invariant collision
552///   |
553///   |   open_local_invariant!(&inv => id1 => {
554///   |                           ^ this invariant
555///   |       open_local_invariant!(&inv => id2 => {
556///   |                               ^ might be the same as this invariant
557///   ...
558///   |       }
559///   |   }
560/// ```
561///
562/// When generating these conditions, Verus compares invariants via their
563/// [`namespace()`](LocalInvariant::namespace) values.
564/// An invariant's namespace (represented simply as an integer)
565/// is specified upon the call to [`LocalInvariant::new`].
566/// If you have the need to open multiple invariants at once, make sure to given
567/// them different namespaces.
568///
569/// So that Verus can ensure that there are no nested invariant accesses across function
570/// boundaries, every `proof` and `exec` function has, as part of its specification,
571/// the set of invariant namespaces that it might open.
572///
573/// The invariant set of a function can be specified via the [`opens_invariants` clause](https://verus-lang.github.io/verus/guide/reference-opens-invariants.html).
574/// The default for an `exec`-mode function is to open any, while the default
575/// for a `proof`-mode function is to open none.
576///
577/// It's not legal to use `open_local_invariant!` in proof mode. In proof mode, you need
578/// to use `open_local_invariant_in_proof!` instead. This takes one extra parameter,
579/// an open-invariant credit, which you can get by calling
580/// `create_open_invariant_credit()` before you enter proof mode.
581///
582/// ### Example
583///
584/// TODO fill this in
585///
586/// ### More Examples
587///
588/// TODO fill this in
589
590#[macro_export]
591macro_rules! open_local_invariant {
592    [$($tail:tt)*] => {
593        #[allow(unexpected_cfgs)] // make sure client crates don't see "unexpected `cfg` condition name: `verus_...`"
594        {
595            $crate::vstd::prelude::verus_exec_inv_macro_exprs!(
596                $crate::vstd::invariant::open_local_invariant_internal!($crate::vstd::invariant::create_open_invariant_credit() => $($tail)*))
597        }
598    };
599}
600
601#[macro_export]
602macro_rules! open_local_invariant_in_proof {
603    [$($tail:tt)*] => {
604        $crate::vstd::prelude::verus_ghost_inv_macro_exprs!($crate::vstd::invariant::open_local_invariant_in_proof_internal!($($tail)*))
605    };
606}
607
608#[macro_export]
609macro_rules! open_local_invariant_internal {
610    ($credit_expr:expr => $eexpr:expr => $iident:ident => $bblock:block) => {
611        #[cfg_attr(verus_keep_ghost, verifier::invariant_block)] /* vattr */ {
612            #[cfg(verus_keep_ghost_body)]
613            #[allow(unused_mut)] let (guard, mut $iident) = $crate::vstd::invariant::open_local_invariant_begin($credit_expr, $eexpr);
614            $bblock
615            #[cfg(verus_keep_ghost_body)]
616            $crate::vstd::invariant::open_invariant_end(guard, $iident);
617        }
618    }
619}
620
621#[macro_export]
622macro_rules! open_local_invariant_in_proof_internal {
623    ($credit_expr:expr => $eexpr:expr => $iident:ident => $bblock:block) => {
624        #[cfg_attr(verus_keep_ghost, verifier::invariant_block)] /* vattr */ {
625            #[cfg(verus_keep_ghost_body)]
626            #[allow(unused_mut)] let (guard, mut $iident) = $crate::vstd::invariant::open_local_invariant_begin($credit_expr, $eexpr);
627            $bblock
628            #[cfg(verus_keep_ghost_body)]
629            $crate::vstd::invariant::open_invariant_end(guard, $iident);
630        }
631    }
632}
633
634pub use open_local_invariant;
635pub use open_local_invariant_in_proof;
636#[doc(hidden)]
637pub use open_local_invariant_in_proof_internal;
638#[doc(hidden)]
639pub use open_local_invariant_internal;