hydro_lang/properties/mod.rs
1//! Types for reasoning about algebraic properties for Rust closures.
2
3use std::marker::PhantomData;
4
5use stageleft::properties::Property;
6
7use crate::live_collections::boundedness::Boundedness;
8use crate::live_collections::keyed_singleton::KeyedSingletonBound;
9use crate::live_collections::singleton::SingletonBound;
10use crate::live_collections::stream::{ExactlyOnce, Ordering, Retries, TotalOrder};
11use crate::sim_hooks::{OnProcess, OrderingHook};
12
13/// A trait for proof mechanisms that can validate commutativity.
14///
15/// `T` and `B` name the element type and boundedness of the stream the commutative
16/// function consumes. The simulator does not trust commutativity proofs — it still
17/// explores the input ordering — so a proof may carry an [`OrderingHook`] for scripting
18/// that exploration, surfaced through [`Self::take_hook`]. `S` is the hook's
19/// [scope](crate::sim_hooks#hook-scopes).
20#[sealed::sealed]
21pub trait CommutativeProof<T, B: Boundedness, S = OnProcess> {
22 /// Registers the expression with the proof mechanism.
23 ///
24 /// This should not perform any blocking analysis; it is only intended to record the expression for later processing.
25 fn register_proof(&self, expr: &syn::Expr);
26
27 /// Takes the simulator ordering hook attached to this proof, if any.
28 fn take_hook(&mut self) -> Option<OrderingHook<T, B, ExactlyOnce, S>>;
29}
30
31/// A trait for proof mechanisms that can validate idempotence.
32#[sealed::sealed]
33pub trait IdempotentProof {
34 /// Registers the expression with the proof mechanism.
35 ///
36 /// This should not perform any blocking analysis; it is only intended to record the expression for later processing.
37 fn register_proof(&self, expr: &syn::Expr);
38}
39
40/// A trait for proof mechanisms that can validate monotonicity.
41#[sealed::sealed]
42pub trait MonotoneProof {
43 /// Registers the expression with the proof mechanism.
44 ///
45 /// This should not perform any blocking analysis; it is only intended to record the expression for later processing.
46 fn register_proof(&self, expr: &syn::Expr);
47}
48
49/// A trait for proof mechanisms that can validate order-preservation (monotonicity of a map function).
50#[sealed::sealed]
51pub trait OrderPreservingProof {
52 /// Registers the expression with the proof mechanism.
53 ///
54 /// This should not perform any blocking analysis; it is only intended to record the expression for later processing.
55 fn register_proof(&self, expr: &syn::Expr);
56}
57
58/// A trait for proof mechanisms that can validate consistency of a collection.
59#[sealed::sealed]
60pub trait ConsistencyProof {}
61
62/// A hand-written human proof of the correctness property.
63///
64/// To create a manual proof, use the [`manual_proof!`] macro, which takes in a doc comment
65/// explaining why the property holds.
66///
67/// Manual proofs are not trusted by the simulator, which still explores the guarded
68/// non-determinism. `H` is the simulator hook payload (like [`crate::nondet::NonDet`]) so a
69/// commutativity proof can carry an ordering hook for scripting that exploration.
70pub struct ManualProof<H = ()> {
71 hook: H,
72}
73
74impl<H> ManualProof<H> {
75 #[doc(hidden)]
76 pub fn unhooked() -> Self
77 where
78 H: Default,
79 {
80 ManualProof { hook: H::default() }
81 }
82}
83
84impl<T, B: Boundedness, S> ManualProof<Option<OrderingHook<T, B, ExactlyOnce, S>>> {
85 #[doc(hidden)]
86 pub fn hooked(hook: impl Into<Option<OrderingHook<T, B, ExactlyOnce, S>>>) -> Self {
87 ManualProof { hook: hook.into() }
88 }
89}
90
91#[sealed::sealed]
92impl<T, B: Boundedness, S> CommutativeProof<T, B, S>
93 for ManualProof<Option<OrderingHook<T, B, ExactlyOnce, S>>>
94{
95 fn register_proof(&self, _expr: &syn::Expr) {}
96
97 fn take_hook(&mut self) -> Option<OrderingHook<T, B, ExactlyOnce, S>> {
98 self.hook.take()
99 }
100}
101
102#[sealed::sealed]
103impl<T, B: Boundedness, S> CommutativeProof<T, B, S> for ManualProof {
104 fn register_proof(&self, _expr: &syn::Expr) {}
105
106 fn take_hook(&mut self) -> Option<OrderingHook<T, B, ExactlyOnce, S>> {
107 None
108 }
109}
110#[sealed::sealed]
111impl IdempotentProof for ManualProof {
112 fn register_proof(&self, _expr: &syn::Expr) {}
113}
114#[sealed::sealed]
115impl MonotoneProof for ManualProof {
116 fn register_proof(&self, _expr: &syn::Expr) {}
117}
118#[sealed::sealed]
119impl OrderPreservingProof for ManualProof {
120 fn register_proof(&self, _expr: &syn::Expr) {}
121}
122#[sealed::sealed]
123impl ConsistencyProof for ManualProof {}
124
125/// A machine-checked proof of **commutativity**, verified by [Verus](https://verus-lang.github.io/verus/guide/).
126///
127/// Created by the [`verus_proof_commutative_fold!`], [`verus_proof_commutative_map!`],
128/// [`verus_proof_commutative_filter!`], and [`verus_proof_commutative_effect!`] macros,
129/// one per closure shape, each generating the precise obligation that makes reordering
130/// unobservable for that shape (final accumulator, output multiset, retained multiset,
131/// or captured state, respectively). The obligation is generated by the macro directly
132/// from the *actual closure body* — it symbolically executes the body in both orders
133/// (`x` then `y`, and `y` then `x`) from equal initial states and requires the
134/// observable results to be equal — so users never write (and cannot weaken) the
135/// assertion. Users only declare the types involved and, optionally, provide a proof
136/// *script* to help the SMT solver, which is itself checked by Verus.
137///
138/// When the crate is verified with `cargo verus verify`, Verus checks the obligation
139/// (which also proves the closure body panic-free, e.g. no arithmetic overflow). Under
140/// normal compilation, the proof is erased and this type simply marks the property as
141/// proven. This type only implements [`CommutativeProof`], so it cannot be used to
142/// fulfill a different property (e.g. `idempotent = ...`; see [`VerusIdempotentProof`]).
143pub struct VerusCommutativeProof {
144 _private: (),
145}
146
147impl VerusCommutativeProof {
148 #[doc(hidden)]
149 pub fn new() -> Self {
150 VerusCommutativeProof { _private: () }
151 }
152}
153
154impl Default for VerusCommutativeProof {
155 fn default() -> Self {
156 Self::new()
157 }
158}
159
160#[sealed::sealed]
161impl<T, B: Boundedness, S> CommutativeProof<T, B, S> for VerusCommutativeProof {
162 fn register_proof(&self, _expr: &syn::Expr) {}
163
164 fn take_hook(&mut self) -> Option<OrderingHook<T, B, ExactlyOnce, S>> {
165 // Verus proofs are still not trusted by the simulator, which explores the
166 // input ordering on its own; no scripting hook is attached.
167 None
168 }
169}
170
171/// A machine-checked proof of **idempotence**, verified by [Verus](https://verus-lang.github.io/verus/guide/).
172///
173/// Created by the [`verus_proof_idempotent_fold!`], [`verus_proof_idempotent_reduce!`],
174/// [`verus_proof_idempotent_map!`], [`verus_proof_idempotent_filter!`], and
175/// [`verus_proof_idempotent_effect!`] macros, one per closure shape, each generating the
176/// precise obligation that makes a retried (duplicated) element unobservable for that
177/// shape (final accumulator, re-emitted output, retention decision, or captured state,
178/// respectively). The obligation is generated by the macro directly from the *actual
179/// closure body* — it symbolically executes the body on an element once, and on the same
180/// element twice in a row, from equal initial states, and requires the observable
181/// results to be equal — so users never write (and cannot weaken) the assertion. Users
182/// only declare the types involved and, optionally, provide a proof *script* to help the
183/// SMT solver, which is itself checked by Verus.
184///
185/// Combined with a commutativity proof (required on unordered streams), the obligation
186/// also covers duplicates that are not adjacent to the original element, since
187/// commutativity allows moving the duplicate next to it.
188///
189/// When the crate is verified with `cargo verus verify`, Verus checks the obligation
190/// (which also proves the closure body panic-free, e.g. no arithmetic overflow). Under
191/// normal compilation, the proof is erased and this type simply marks the property as
192/// proven. Note that the simulator does not inject retries, so (unlike commutativity)
193/// idempotence claims are not explored by simulation tests at all; a Verus proof is the
194/// only mechanical check. This type only implements [`IdempotentProof`], so it cannot be
195/// used to fulfill a different property (e.g. `commutative = ...`).
196pub struct VerusIdempotentProof {
197 _private: (),
198}
199
200impl VerusIdempotentProof {
201 #[doc(hidden)]
202 pub fn new() -> Self {
203 VerusIdempotentProof { _private: () }
204 }
205}
206
207impl Default for VerusIdempotentProof {
208 fn default() -> Self {
209 Self::new()
210 }
211}
212
213#[sealed::sealed]
214impl IdempotentProof for VerusIdempotentProof {
215 fn register_proof(&self, _expr: &syn::Expr) {}
216}
217
218/// A machine-checked proof of **monotonicity**, verified by [Verus](https://verus-lang.github.io/verus/guide/).
219///
220/// Created by the [`verus_proof_monotone_fold!`] macro, which generates the obligation
221/// directly from the *actual closure body*: applying the aggregation to any accumulator
222/// and any item must leave the accumulator **greater than or equal** to its previous
223/// value, with respect to the accumulator type's [`PartialOrd`] (the order used by
224/// APIs such as [`Singleton::threshold_greater_or_equal`]). Users never write (and
225/// cannot weaken) the assertion; they only declare the types involved and, optionally,
226/// provide a proof *script* to help the SMT solver, which is itself checked by Verus.
227///
228/// When the crate is verified with `cargo verus verify`, Verus checks the obligation
229/// (which also proves the closure body panic-free). Under normal compilation, the proof
230/// is erased and this type simply marks the property as proven. This type only
231/// implements [`MonotoneProof`], so it cannot be used to fulfill a different property.
232///
233/// [`Singleton::threshold_greater_or_equal`]: crate::live_collections::singleton::Singleton::threshold_greater_or_equal
234pub struct VerusMonotoneProof {
235 _private: (),
236}
237
238impl VerusMonotoneProof {
239 #[doc(hidden)]
240 pub fn new() -> Self {
241 VerusMonotoneProof { _private: () }
242 }
243}
244
245impl Default for VerusMonotoneProof {
246 fn default() -> Self {
247 Self::new()
248 }
249}
250
251#[sealed::sealed]
252impl MonotoneProof for VerusMonotoneProof {
253 fn register_proof(&self, _expr: &syn::Expr) {}
254}
255
256/// A machine-checked proof of **order preservation**, verified by [Verus](https://verus-lang.github.io/verus/guide/).
257///
258/// Created by the [`verus_proof_order_preserving_map!`] macro, which generates the
259/// obligation directly from the *actual closure body*: for any two inputs `x <= y`
260/// (with respect to the input type's [`PartialOrd`]), the outputs must satisfy
261/// `f(x) <= f(y)` (with respect to the output type's [`PartialOrd`]). This is exactly
262/// what is needed for a [`Singleton::map`] to keep a `Monotonic` singleton monotonic.
263/// Users never write (and cannot weaken) the assertion; they only declare the types
264/// involved and, optionally, provide a proof *script* to help the SMT solver, which is
265/// itself checked by Verus.
266///
267/// When the crate is verified with `cargo verus verify`, Verus checks the obligation
268/// (which also proves the closure body panic-free). Under normal compilation, the proof
269/// is erased and this type simply marks the property as proven. This type only
270/// implements [`OrderPreservingProof`], so it cannot be used to fulfill a different
271/// property.
272///
273/// [`Singleton::map`]: crate::live_collections::singleton::Singleton::map
274pub struct VerusOrderPreservingProof {
275 _private: (),
276}
277
278impl VerusOrderPreservingProof {
279 #[doc(hidden)]
280 pub fn new() -> Self {
281 VerusOrderPreservingProof { _private: () }
282 }
283}
284
285impl Default for VerusOrderPreservingProof {
286 fn default() -> Self {
287 Self::new()
288 }
289}
290
291#[sealed::sealed]
292impl OrderPreservingProof for VerusOrderPreservingProof {
293 fn register_proof(&self, _expr: &syn::Expr) {}
294}
295
296#[doc(inline)]
297pub use crate::__manual_proof__ as manual_proof;
298
299// Verus only sees items declared inside `verus!`, so under the Verus driver (with the
300// `verus` feature) the function backing `verus_panic!` is declared there.
301// `external_body`: Verus trusts the signature without checking the body (which calls
302// `panic!`, whose vstd specification is `requires false`). The signature has no
303// precondition and the default unwind specification (may unwind), so callers need not
304// prove anything, and since the return type is `!`, nothing after the call is reachable.
305#[cfg(all(verus_keep_ghost, feature = "verus"))]
306vstd::prelude::verus! {
307 #[doc(hidden)]
308 #[verifier::external_body]
309 pub fn __verus_panic() -> ! {
310 panic!("verus_panic! was reached")
311 }
312}
313
314#[doc(inline)]
315pub use crate::__verus_panic__ as verus_panic;
316
317#[cfg(all(verus_keep_ghost, feature = "verus"))]
318#[doc(hidden)]
319#[macro_export]
320macro_rules! __verus_panic__ {
321 // The message arguments are dropped: Verus does not support `format_args!`, and they
322 // would only be evaluated on a path that panics anyway.
323 ($($arg:tt)*) => {
324 $crate::properties::__verus_panic()
325 };
326}
327
328#[cfg(not(all(verus_keep_ghost, feature = "verus")))]
329#[macro_export]
330/// Panics, in a way that **Verus proofs of algebraic properties treat as an acceptable
331/// outcome**. Takes the same arguments as [`panic!`].
332///
333/// A Verus proof (e.g. [`verus_proof_commutative_fold!`]) normally requires the closure body
334/// to be panic-free for every input, which rejects closures such as `*acc += x` (which
335/// panics on overflow) even though they are commutative whenever they complete. Calling
336/// `verus_panic!(...)` instead tells Verus that this path ends the program: the property
337/// only has to hold for executions that do **not** reach it. That matches Hydro's
338/// requirement, since a panicking closure crashes the process rather than producing a
339/// result.
340///
341/// The typical use is to guard an operation that could otherwise panic, so that Verus
342/// knows it cannot fail on the paths that continue:
343///
344/// ```rust,ignore
345/// q!(
346/// |acc, x| {
347/// if *acc > u32::MAX - x {
348/// verus_panic!("sum overflowed");
349/// }
350/// *acc += x; // cannot overflow here, so Verus accepts it
351/// },
352/// commutative = verus_proof_commutative_fold!(acc = u32, item = u32)
353/// )
354/// ```
355///
356/// This is sound because the guard really executes: the closure panics at runtime whenever
357/// the guard condition holds, so a guard that is stricter than necessary is still correct.
358/// A guard that is too weak is caught by Verus, which reports the operation that may still
359/// panic. Unlike `assume(...)` in a proof script, nothing is taken on faith beyond the fact
360/// that `verus_panic!` never returns.
361///
362/// Under normal compilation, this forwards its arguments to [`panic!`]. When verifying
363/// with `cargo verus verify`, the `verus` feature of `hydro_lang` must be enabled; Verus
364/// then sees a call to a function that never returns (the message arguments are not
365/// evaluated by the proof).
366macro_rules! __verus_panic__ {
367 ($($arg:tt)*) => {
368 ::core::panic!($($arg)*)
369 };
370}
371
372#[macro_export]
373/// Fulfills a proof parameter by declaring a human-written justification for why
374/// the algebraic property (e.g. commutativity, idempotence) holds.
375///
376/// The argument must be a doc comment explaining why the property is satisfied.
377///
378/// # Examples
379/// ```rust
380/// # #[cfg(feature = "deploy")] {
381/// # use hydro_lang::prelude::*;
382/// # use hydro_lang::live_collections::stream::NoOrder;
383/// # use futures::StreamExt;
384/// # tokio_test::block_on(hydro_lang::test_util::stream_transform_test(|process| {
385/// # let stream = process.source_iter(q!(vec![1, 2, 3])).weaken_ordering::<NoOrder>();
386/// // stream: [1, 2, 3] (unordered)
387/// stream
388/// .fold(
389/// q!(|| 0),
390/// q!(
391/// |acc, x| *acc += x,
392/// commutative = manual_proof!(/** integer addition is commutative */)
393/// ),
394/// )
395/// .into_stream()
396/// # }, |mut stream| async move {
397/// # assert_eq!(stream.next().await.unwrap(), 6);
398/// # }));
399/// # }
400/// ```
401/// An optional trailing `hook = ...` argument attaches a **simulator ordering hook** to a
402/// commutativity proof (see `hydro_lang::sim::hooks`). The simulator does not trust manual
403/// proofs — it still explores the input ordering — so the hook lets a simulation test
404/// script that exploration:
405///
406/// ```rust,ignore
407/// commutative = manual_proof!(/** set insert is commutative */ hook = my_ordering_hook)
408/// ```
409macro_rules! __manual_proof__ {
410 (
411 $(#[doc = $doc:expr])+hook =
412 $hook:expr,__target =
413 { $($target:tt)* } $(,__captures = [$($captures:ident),*])? $(,)?
414 ) => {
415 $crate::properties::ManualProof::hooked($hook)
416 };
417 ($(#[doc = $doc:expr])+hook = $hook:expr $(,)?) => {
418 $crate::properties::ManualProof::hooked($hook)
419 };
420 (
421 $(#[doc = $doc:expr])+,__target =
422 { $($target:tt)* } $(,__captures = [$($captures:ident),*])? $(,)?
423 ) => {
424 $crate::properties::ManualProof::<()>::unhooked()
425 };
426 ($(#[doc = $doc:expr])+) => {
427 $crate::properties::ManualProof::<()>::unhooked()
428 };
429}
430
431#[doc(inline)]
432pub use crate::__verus_proof_commutative_effect__ as verus_proof_commutative_effect;
433#[doc(inline)]
434pub use crate::__verus_proof_commutative_filter__ as verus_proof_commutative_filter;
435#[doc(inline)]
436pub use crate::__verus_proof_commutative_fold__ as verus_proof_commutative_fold;
437#[doc(inline)]
438pub use crate::__verus_proof_commutative_map__ as verus_proof_commutative_map;
439#[doc(inline)]
440pub use crate::__verus_proof_monotone_fold__ as verus_proof_monotone_fold;
441#[doc(inline)]
442pub use crate::__verus_proof_order_preserving_map__ as verus_proof_order_preserving_map;
443
444#[macro_export]
445/// Fulfills a `commutative = ...` proof parameter for an **aggregation closure**
446/// (`fold` / `reduce`, shape `|acc, item|` with `acc: &mut A`) with a **Verus-checked
447/// proof of commutativity**.
448///
449/// Users never write the proof obligation (so they cannot get it wrong): this macro
450/// receives the quoted closure itself from `q!` (as a trailing `__target = { ... }`
451/// argument) and generates a Verus function that symbolically executes the *actual
452/// closure body* in both orders — `x` then `y`, and `y` then `x` — starting from equal
453/// accumulators, and asserts that the final accumulators are equal. Verifying this
454/// obligation also proves the closure body panic-free (e.g. no arithmetic overflow).
455/// Users only declare the accumulator and item types:
456///
457/// ```rust,ignore
458/// batch.reduce(q!(
459/// |curr, new| { if new > *curr { *curr = new; } },
460/// commutative = verus_proof_commutative_fold!(acc = u32, item = u32)
461/// ));
462/// ```
463///
464/// If the closure captures (read-only) variables from its environment, re-declare them
465/// (with their runtime types) in a `captures = |...|` clause; the obligation is then
466/// universally quantified over the capture values, which is sound since any particular
467/// execution uses some fixed value. `q!` also passes the closure's capture list (as a
468/// trailing `__captures = [...]` argument), and the macro checks at compile time that
469/// every capture is declared.
470///
471/// An optional `proof = |state, x, y| { ... }` clause supplies a proof *script* to help
472/// the SMT solver, with ghost bindings for the initial accumulator and the two items
473/// (e.g. `proof = |s, x, y| { assert((s | x) | y == (s | y) | x) by (bit_vector); }`).
474/// The script is checked by Verus and cannot weaken the obligation (though, as anywhere
475/// in Verus, `assume` is an explicit soundness escape hatch).
476///
477/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
478/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
479/// macro just produces a [`VerusCommutativeProof`] marker, so the types go through the
480/// ordinary `commutative = ...` mechanism with zero overhead.
481macro_rules! __verus_proof_commutative_fold__ {
482 (
483 acc = $accty:ty, item = $itemty:ty
484 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
485 $(, proof = |$pstate:ident, $px:ident, $py:ident| { $($proof_body:tt)* })?
486 , __target = { $(move)? |$tacc:ident $(: $taccty:ty)?, $titem:ident $(: $titemty:ty)?| $target_body:expr }
487 , __captures = [$($fv:ident),* $(,)?] $(,)?
488 ) => {{
489 /// Checks that every free variable captured by the closure is declared (with its
490 /// type) in the `captures = |...|` clause: within this function, the *only* names
491 /// in scope are the declared captures and the closure parameters, so an
492 /// undeclared capture fails to resolve.
493 #[allow(unused, reason = "only checks name resolution")]
494 fn __hydro_verus_captures_declared($($($cap: $capty),*)?) {
495 $(let $fv = &$fv;)*
496 }
497 #[cfg(verus_keep_ghost)]
498 const _: () = {
499 #[allow(unused_imports)]
500 use ::vstd::prelude::*;
501
502 ::vstd::prelude::verus! {
503 /// Commutativity obligation, generated by `verus_proof_commutative_fold!`:
504 /// applying the closure body with `x` then `y` must yield the same
505 /// accumulator as applying it with `y` then `x`, from any equal starting
506 /// accumulators, for all items and capture values. Verifying this also
507 /// proves the body panic-free.
508 fn __hydro_verus_commutative(
509 $($($cap: $capty,)*)?
510 __hydro_acc_xy: $accty,
511 __hydro_acc_yx: $accty,
512 __hydro_x_0: $itemty,
513 __hydro_x_1: $itemty,
514 __hydro_y_0: $itemty,
515 __hydro_y_1: $itemty,
516 )
517 requires
518 __hydro_acc_xy == __hydro_acc_yx,
519 __hydro_x_0 == __hydro_x_1,
520 __hydro_y_0 == __hydro_y_1,
521 {
522 $(
523 let ghost $pstate = __hydro_acc_xy;
524 let ghost $px = __hydro_x_0;
525 let ghost $py = __hydro_y_0;
526 )?
527 let mut __hydro_acc_xy = __hydro_acc_xy;
528 let mut __hydro_acc_yx = __hydro_acc_yx;
529 { let $tacc = &mut __hydro_acc_xy; let $titem = __hydro_x_0; let _ = { $target_body }; }
530 { let $tacc = &mut __hydro_acc_xy; let $titem = __hydro_y_0; let _ = { $target_body }; }
531 { let $tacc = &mut __hydro_acc_yx; let $titem = __hydro_y_1; let _ = { $target_body }; }
532 { let $tacc = &mut __hydro_acc_yx; let $titem = __hydro_x_1; let _ = { $target_body }; }
533 $(proof { $($proof_body)* })?
534 assert(__hydro_acc_xy == __hydro_acc_yx);
535 }
536 }
537 };
538
539 $crate::properties::VerusCommutativeProof::new()
540 }};
541 (
542 $($rest:tt)*
543 ) => {{
544 ::core::compile_error!(
545 "verus_proof_commutative_fold! must be used as a property annotation inside `q!(...)` on a `|acc, item| ...` closure, e.g. `commutative = verus_proof_commutative_fold!(acc = u32, item = u32)`"
546 );
547 $crate::properties::VerusCommutativeProof::new()
548 }};
549}
550
551#[macro_export]
552/// Fulfills a `commutative = ...` proof parameter for a **map-like closure**
553/// (shape `|item| -> out`, e.g. for `map`) that may mutate a captured singleton
554/// reference (from [`Singleton::by_mut`]), with a **Verus-checked proof of
555/// commutativity**.
556///
557/// **What commutativity means for a map closure:** processing any two items in either
558/// order, starting from the same captured state, must (1) leave the captured state in
559/// the same final value, *and* (2) produce the same **multiset of output values** (the
560/// outputs may be swapped in order, but not changed). Both conditions are required for
561/// downstream determinism: outputs that depend on the processing order (e.g. emitting a
562/// running total) are **not** commutative even if the state update is.
563///
564/// The commuting state is the mutable capture, declared (with the type behind the
565/// reference) in the required `captures_mut = |state: S|` clause; additional read-only
566/// captures can be declared in a `captures = |...|` clause. `q!` also passes the
567/// closure's capture list (as a trailing `__captures = [...]` argument), and the macro
568/// checks at compile time that every capture is declared. The `item = ...` type must be
569/// written exactly as the closure receives it.
570///
571/// Users never write the proof obligation: this macro receives the quoted closure itself
572/// from `q!` (as a trailing `__target = { ... }` argument) and generates a Verus function
573/// that symbolically executes the *actual closure body* in both orders — `x` then `y`,
574/// and `y` then `x` — from equal captured states, then asserts that the final states are
575/// equal and that the two runs' outputs are equal as a multiset (pairwise or crossed).
576/// Verifying this also proves the body panic-free.
577///
578/// An optional `proof = |state, x, y| { ... }` clause supplies a proof *script* to help
579/// the SMT solver, with ghost bindings for the initial captured state and the two items.
580/// The script is checked by Verus and cannot weaken the obligation.
581///
582/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
583/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
584/// macro just produces a [`VerusCommutativeProof`] marker.
585///
586/// # Example
587/// ```rust,ignore
588/// let count_mut = my_count.by_mut();
589/// stream.map(q!(
590/// |x| {
591/// *count_mut = count_mut.wrapping_add(x);
592/// x // outputting `*count_mut` here would NOT be commutative!
593/// },
594/// commutative = verus_proof_commutative_map!(
595/// item = i32,
596/// captures_mut = |count_mut: i32|
597/// )
598/// ));
599/// ```
600///
601/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
602macro_rules! __verus_proof_commutative_map__ {
603 (
604 item = $itemty:ty
605 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
606 , captures_mut = |$mcap:ident : $mcapty:ty $(,)?|
607 $(, proof = |$pstate:ident, $px:ident, $py:ident| { $($proof_body:tt)* })?
608 , __target = { $(move)? |$titem:ident $(: $titemty:ty)?| $target_body:expr }
609 , __captures = [$($fv:ident),* $(,)?] $(,)?
610 ) => {{
611 /// Checks that every free variable captured by the closure is declared (with its
612 /// type) in the `captures = |...|` or `captures_mut = |...|` clauses: within this
613 /// function, the *only* names in scope are the declared captures, so an
614 /// undeclared capture fails to resolve.
615 #[allow(unused, reason = "only checks name resolution")]
616 fn __hydro_verus_captures_declared($($($cap: $capty,)*)? $mcap: $mcapty) {
617 $(let $fv = &$fv;)*
618 }
619
620 #[cfg(verus_keep_ghost)]
621 const _: () = {
622 #[allow(unused_imports)]
623 use ::vstd::prelude::*;
624
625 ::vstd::prelude::verus! {
626 /// Commutativity obligation, generated by `verus_proof_commutative_map!`:
627 /// from any equal starting captured states, processing `x` then `y` must
628 /// yield the same final captured state as processing `y` then `x`, and
629 /// the two runs must produce the same multiset of outputs (pairwise or
630 /// crossed equality). Verifying this also proves the body panic-free.
631 fn __hydro_verus_commutative(
632 $($($cap: $capty,)*)?
633 __hydro_state_xy: $mcapty,
634 __hydro_state_yx: $mcapty,
635 __hydro_x_0: $itemty,
636 __hydro_x_1: $itemty,
637 __hydro_y_0: $itemty,
638 __hydro_y_1: $itemty,
639 )
640 requires
641 __hydro_state_xy == __hydro_state_yx,
642 __hydro_x_0 == __hydro_x_1,
643 __hydro_y_0 == __hydro_y_1,
644 {
645 $(
646 let ghost $pstate = __hydro_state_xy;
647 let ghost $px = __hydro_x_0;
648 let ghost $py = __hydro_y_0;
649 )?
650 let mut __hydro_state_xy = __hydro_state_xy;
651 let mut __hydro_state_yx = __hydro_state_yx;
652 let __hydro_out_xy_x = { let $mcap = &mut __hydro_state_xy; let $titem = __hydro_x_0; $target_body };
653 let __hydro_out_xy_y = { let $mcap = &mut __hydro_state_xy; let $titem = __hydro_y_0; $target_body };
654 let __hydro_out_yx_y = { let $mcap = &mut __hydro_state_yx; let $titem = __hydro_y_1; $target_body };
655 let __hydro_out_yx_x = { let $mcap = &mut __hydro_state_yx; let $titem = __hydro_x_1; $target_body };
656 $(proof { $($proof_body)* })?
657 assert(__hydro_state_xy == __hydro_state_yx);
658 assert(
659 (__hydro_out_xy_x == __hydro_out_yx_x && __hydro_out_xy_y == __hydro_out_yx_y)
660 || (__hydro_out_xy_x == __hydro_out_yx_y && __hydro_out_xy_y == __hydro_out_yx_x)
661 );
662 }
663 }
664 };
665
666 $crate::properties::VerusCommutativeProof::new()
667 }};
668 (
669 $($rest:tt)*
670 ) => {{
671 ::core::compile_error!(
672 "verus_proof_commutative_map! must be used as a property annotation inside `q!(...)` on a `|item| ...` closure with exactly one `captures_mut` entry, e.g. `commutative = verus_proof_commutative_map!(item = u32, captures_mut = |state: u32|)`"
673 );
674 $crate::properties::VerusCommutativeProof::new()
675 }};
676}
677
678#[macro_export]
679/// Fulfills a `commutative = ...` proof parameter for a **filter predicate**
680/// (shape `|item| -> bool` where `item` is received by reference) that may mutate a
681/// captured singleton reference (from [`Singleton::by_mut`]), with a **Verus-checked
682/// proof of commutativity**.
683///
684/// **What commutativity means for a filter predicate:** processing any two items in
685/// either order, starting from the same captured state, must (1) leave the captured
686/// state in the same final value, *and* (2) retain the same **multiset of elements**.
687/// The second condition is essential for soundness: a stateful predicate like a rate
688/// limiter converges to the same state either way, but *which* element passes depends on
689/// the order, which is **not** commutative (unless the elements are equal).
690///
691/// The commuting state is the mutable capture, declared (with the type behind the
692/// reference) in the required `captures_mut = |state: S|` clause; additional read-only
693/// captures can be declared in a `captures = |...|` clause. `q!` also passes the
694/// closure's capture list (as a trailing `__captures = [...]` argument), and the macro
695/// checks at compile time that every capture is declared. The `item = ...` type must be
696/// written exactly as the closure receives it (for `filter`, a reference like `&u32`).
697///
698/// Users never write the proof obligation: this macro receives the quoted closure itself
699/// from `q!` (as a trailing `__target = { ... }` argument) and generates a Verus function
700/// that symbolically executes the *actual predicate body* in both orders — `x` then `y`,
701/// and `y` then `x` — from equal captured states, then asserts that the final states are
702/// equal and that the retained multisets are equal: either the per-item decisions match
703/// across the two orders, or the two items are equal and the number of retained copies
704/// matches. Verifying this also proves the body panic-free.
705///
706/// An optional `proof = |state, x, y| { ... }` clause supplies a proof *script* to help
707/// the SMT solver, with ghost bindings for the initial captured state and the two items.
708/// The script is checked by Verus and cannot weaken the obligation.
709///
710/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
711/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
712/// macro just produces a [`VerusCommutativeProof`] marker.
713///
714/// # Example
715/// ```rust,ignore
716/// let seen_mut = seen_count.by_mut();
717/// stream.filter(q!(
718/// |x| {
719/// *seen_mut = seen_mut.wrapping_add(1);
720/// *x > 1 // the decision must not depend on the mutable state!
721/// },
722/// commutative = verus_proof_commutative_filter!(
723/// item = &u32,
724/// captures_mut = |seen_mut: u32|
725/// )
726/// ));
727/// ```
728///
729/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
730macro_rules! __verus_proof_commutative_filter__ {
731 (
732 item = $itemty:ty
733 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
734 , captures_mut = |$mcap:ident : $mcapty:ty $(,)?|
735 $(, proof = |$pstate:ident, $px:ident, $py:ident| { $($proof_body:tt)* })?
736 , __target = { $(move)? |$titem:ident $(: $titemty:ty)?| $target_body:expr }
737 , __captures = [$($fv:ident),* $(,)?] $(,)?
738 ) => {{
739 /// Checks that every free variable captured by the closure is declared (with its
740 /// type) in the `captures = |...|` or `captures_mut = |...|` clauses: within this
741 /// function, the *only* names in scope are the declared captures, so an
742 /// undeclared capture fails to resolve.
743 #[allow(unused, reason = "only checks name resolution")]
744 fn __hydro_verus_captures_declared($($($cap: $capty,)*)? $mcap: $mcapty) {
745 $(let $fv = &$fv;)*
746 }
747
748 #[cfg(verus_keep_ghost)]
749 const _: () = {
750 #[allow(unused_imports)]
751 use ::vstd::prelude::*;
752
753 ::vstd::prelude::verus! {
754 /// Commutativity obligation, generated by
755 /// `verus_proof_commutative_filter!`: from any equal starting captured
756 /// states, processing `x` then `y` must yield the same final captured
757 /// state as processing `y` then `x`, and the retained multisets must be
758 /// equal: either the per-item decisions match across the two orders, or
759 /// the two items are equal and the retained counts match. Verifying this
760 /// also proves the body panic-free.
761 fn __hydro_verus_commutative(
762 $($($cap: $capty,)*)?
763 __hydro_state_xy: $mcapty,
764 __hydro_state_yx: $mcapty,
765 __hydro_x_0: $itemty,
766 __hydro_x_1: $itemty,
767 __hydro_y_0: $itemty,
768 __hydro_y_1: $itemty,
769 )
770 requires
771 __hydro_state_xy == __hydro_state_yx,
772 __hydro_x_0 == __hydro_x_1,
773 __hydro_y_0 == __hydro_y_1,
774 {
775 $(
776 let ghost $pstate = __hydro_state_xy;
777 let ghost $px = __hydro_x_0;
778 let ghost $py = __hydro_y_0;
779 )?
780 let mut __hydro_state_xy = __hydro_state_xy;
781 let mut __hydro_state_yx = __hydro_state_yx;
782 let __hydro_keep_xy_x: bool = { let $mcap = &mut __hydro_state_xy; let $titem = __hydro_x_0; $target_body };
783 let __hydro_keep_xy_y: bool = { let $mcap = &mut __hydro_state_xy; let $titem = __hydro_y_0; $target_body };
784 let __hydro_keep_yx_y: bool = { let $mcap = &mut __hydro_state_yx; let $titem = __hydro_y_1; $target_body };
785 let __hydro_keep_yx_x: bool = { let $mcap = &mut __hydro_state_yx; let $titem = __hydro_x_1; $target_body };
786 $(proof { $($proof_body)* })?
787 assert(__hydro_state_xy == __hydro_state_yx);
788 assert(
789 (__hydro_keep_xy_x == __hydro_keep_yx_x && __hydro_keep_xy_y == __hydro_keep_yx_y)
790 || (__hydro_x_0 == __hydro_y_0
791 && (__hydro_keep_xy_x as int) + (__hydro_keep_xy_y as int)
792 == (__hydro_keep_yx_x as int) + (__hydro_keep_yx_y as int))
793 );
794 }
795 }
796 };
797
798 $crate::properties::VerusCommutativeProof::new()
799 }};
800 (
801 $($rest:tt)*
802 ) => {{
803 ::core::compile_error!(
804 "verus_proof_commutative_filter! must be used as a property annotation inside `q!(...)` on a `|item| -> bool` closure with exactly one `captures_mut` entry, e.g. `commutative = verus_proof_commutative_filter!(item = &u32, captures_mut = |state: u32|)`"
805 );
806 $crate::properties::VerusCommutativeProof::new()
807 }};
808}
809
810#[macro_export]
811/// Fulfills a `commutative = ...` proof parameter for a **unit-returning, effectful
812/// closure** (shape `|item| -> ()`, e.g. for `for_each` or `inspect`) that mutates a
813/// captured singleton reference (from [`Singleton::by_mut`]), with a **Verus-checked
814/// proof of commutativity** of the captured-state update.
815///
816/// **What commutativity means for an effectful closure:** processing any two items in
817/// either order, starting from the same captured state, must leave the captured state in
818/// the same final value. Because the closure returns `()` (enforced by this macro; use
819/// [`verus_proof_commutative_map!`] or [`verus_proof_commutative_filter!`] for closures
820/// whose return value is observable), the state is the only observable effect.
821///
822/// The commuting state is the mutable capture, declared (with the type behind the
823/// reference) in the required `captures_mut = |state: S|` clause; additional read-only
824/// captures can be declared in a `captures = |...|` clause. `q!` also passes the
825/// closure's capture list (as a trailing `__captures = [...]` argument), and the macro
826/// checks at compile time that every capture is declared. The `item = ...` type must be
827/// written exactly as the closure receives it (e.g. `&u32` for `inspect`).
828///
829/// Users never write the proof obligation: this macro receives the quoted closure itself
830/// from `q!` (as a trailing `__target = { ... }` argument) and generates a Verus function
831/// that symbolically executes the *actual closure body* in both orders — `x` then `y`,
832/// and `y` then `x` — from equal captured states, and asserts that the final states are
833/// equal. Verifying this also proves the body panic-free.
834///
835/// An optional `proof = |state, x, y| { ... }` clause supplies a proof *script* to help
836/// the SMT solver, with ghost bindings for the initial captured state and the two items.
837/// The script is checked by Verus and cannot weaken the obligation.
838///
839/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
840/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
841/// macro just produces a [`VerusCommutativeProof`] marker.
842///
843/// # Example
844/// ```rust,ignore
845/// let flags_mut = flags.by_mut();
846/// stream.for_each(q!(
847/// |x| { *flags_mut |= x; },
848/// commutative = verus_proof_commutative_effect!(
849/// item = u32,
850/// captures_mut = |flags_mut: u32|,
851/// proof = |s, x, y| { assert(((s | x) | y) == ((s | y) | x)) by (bit_vector); }
852/// )
853/// ));
854/// ```
855///
856/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
857macro_rules! __verus_proof_commutative_effect__ {
858 (
859 item = $itemty:ty
860 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
861 , captures_mut = |$mcap:ident : $mcapty:ty $(,)?|
862 $(, proof = |$pstate:ident, $px:ident, $py:ident| { $($proof_body:tt)* })?
863 , __target = { $(move)? |$titem:ident $(: $titemty:ty)?| $target_body:expr }
864 , __captures = [$($fv:ident),* $(,)?] $(,)?
865 ) => {{
866 /// Checks that every free variable captured by the closure is declared (with its
867 /// type) in the `captures = |...|` or `captures_mut = |...|` clauses: within this
868 /// function, the *only* names in scope are the declared captures, so an
869 /// undeclared capture fails to resolve.
870 #[allow(unused, reason = "only checks name resolution")]
871 fn __hydro_verus_captures_declared($($($cap: $capty,)*)? $mcap: $mcapty) {
872 $(let $fv = &$fv;)*
873 }
874
875 #[cfg(verus_keep_ghost)]
876 const _: () = {
877 #[allow(unused_imports)]
878 use ::vstd::prelude::*;
879
880 ::vstd::prelude::verus! {
881 /// Commutativity obligation, generated by
882 /// `verus_proof_commutative_effect!`: applying the closure body with `x`
883 /// then `y` must yield the same captured state as applying it with `y`
884 /// then `x`, from any equal starting states. The closure must return
885 /// `()`, so the state is the only observable effect. Verifying this also
886 /// proves the body panic-free.
887 fn __hydro_verus_commutative(
888 $($($cap: $capty,)*)?
889 __hydro_state_xy: $mcapty,
890 __hydro_state_yx: $mcapty,
891 __hydro_x_0: $itemty,
892 __hydro_x_1: $itemty,
893 __hydro_y_0: $itemty,
894 __hydro_y_1: $itemty,
895 )
896 requires
897 __hydro_state_xy == __hydro_state_yx,
898 __hydro_x_0 == __hydro_x_1,
899 __hydro_y_0 == __hydro_y_1,
900 {
901 $(
902 let ghost $pstate = __hydro_state_xy;
903 let ghost $px = __hydro_x_0;
904 let ghost $py = __hydro_y_0;
905 )?
906 let mut __hydro_state_xy = __hydro_state_xy;
907 let mut __hydro_state_yx = __hydro_state_yx;
908 { let $mcap = &mut __hydro_state_xy; let $titem = __hydro_x_0; let __hydro_out: () = { $target_body }; }
909 { let $mcap = &mut __hydro_state_xy; let $titem = __hydro_y_0; let __hydro_out: () = { $target_body }; }
910 { let $mcap = &mut __hydro_state_yx; let $titem = __hydro_y_1; let __hydro_out: () = { $target_body }; }
911 { let $mcap = &mut __hydro_state_yx; let $titem = __hydro_x_1; let __hydro_out: () = { $target_body }; }
912 $(proof { $($proof_body)* })?
913 assert(__hydro_state_xy == __hydro_state_yx);
914 }
915 }
916 };
917
918 $crate::properties::VerusCommutativeProof::new()
919 }};
920 (
921 $($rest:tt)*
922 ) => {{
923 ::core::compile_error!(
924 "verus_proof_commutative_effect! must be used as a property annotation inside `q!(...)` on a `|item| -> ()` closure with exactly one `captures_mut` entry, e.g. `commutative = verus_proof_commutative_effect!(item = u32, captures_mut = |state: u32|)`"
925 );
926 $crate::properties::VerusCommutativeProof::new()
927 }};
928}
929
930#[doc(inline)]
931pub use crate::__verus_proof_idempotent_effect__ as verus_proof_idempotent_effect;
932#[doc(inline)]
933pub use crate::__verus_proof_idempotent_filter__ as verus_proof_idempotent_filter;
934#[doc(inline)]
935pub use crate::__verus_proof_idempotent_fold__ as verus_proof_idempotent_fold;
936#[doc(inline)]
937pub use crate::__verus_proof_idempotent_map__ as verus_proof_idempotent_map;
938#[doc(inline)]
939pub use crate::__verus_proof_idempotent_reduce__ as verus_proof_idempotent_reduce;
940
941#[macro_export]
942/// Fulfills an `idempotent = ...` proof parameter for a **fold closure** (shape
943/// `|acc, item|` with `acc: &mut A`) with a **Verus-checked proof of idempotence**.
944///
945/// Use [`verus_proof_idempotent_reduce!`] for `reduce`, whose accumulator is seeded with
946/// the first element, which needs an additional obligation.
947///
948/// Users never write the proof obligation (so they cannot get it wrong): this macro
949/// receives the quoted closure itself from `q!` (as a trailing `__target = { ... }`
950/// argument) and generates a Verus function that symbolically executes the *actual
951/// closure body* on an item `x` once, and on `x` twice in a row, starting from equal
952/// accumulators, and asserts that the final accumulators are equal. Verifying this
953/// obligation also proves the closure body panic-free (e.g. no arithmetic overflow).
954/// Users only declare the accumulator and item types:
955///
956/// ```rust,ignore
957/// stream.fold(
958/// q!(|| 0u32),
959/// q!(
960/// |acc, x| { if x > *acc { *acc = x; } },
961/// idempotent = verus_proof_idempotent_fold!(acc = u32, item = u32)
962/// ),
963/// );
964/// ```
965///
966/// Read-only captures are declared in a `captures = |...|` clause, exactly as for
967/// [`verus_proof_commutative_fold!`]; the macro checks at compile time that every capture
968/// is declared.
969///
970/// An optional `proof = |state, x| { ... }` clause supplies a proof *script* to help the
971/// SMT solver, with ghost bindings for the initial accumulator and the item (e.g.
972/// `proof = |s, x| { assert(((s | x) | x) == (s | x)) by (bit_vector); }`). The script is
973/// checked by Verus and cannot weaken the obligation.
974///
975/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
976/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
977/// macro just produces a [`VerusIdempotentProof`] marker.
978macro_rules! __verus_proof_idempotent_fold__ {
979 (
980 acc = $accty:ty, item = $itemty:ty
981 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
982 $(, proof = |$pstate:ident, $px:ident| { $($proof_body:tt)* })?
983 , __target = { $(move)? |$tacc:ident $(: $taccty:ty)?, $titem:ident $(: $titemty:ty)?| $target_body:expr }
984 , __captures = [$($fv:ident),* $(,)?] $(,)?
985 ) => {{
986 /// Checks that every free variable captured by the closure is declared (with its
987 /// type) in the `captures = |...|` clause: within this function, the *only* names
988 /// in scope are the declared captures and the closure parameters, so an
989 /// undeclared capture fails to resolve.
990 #[allow(unused, reason = "only checks name resolution")]
991 fn __hydro_verus_captures_declared($($($cap: $capty),*)?) {
992 $(let $fv = &$fv;)*
993 }
994
995 #[cfg(verus_keep_ghost)]
996 const _: () = {
997 #[allow(unused_imports)]
998 use ::vstd::prelude::*;
999
1000 ::vstd::prelude::verus! {
1001 /// Idempotence obligation, generated by `verus_proof_idempotent_fold!`:
1002 /// applying the closure body with `x` twice in a row must yield the same
1003 /// accumulator as applying it once, from any equal starting accumulators,
1004 /// for all items and capture values. Verifying this also proves the body
1005 /// panic-free.
1006 fn __hydro_verus_idempotent(
1007 $($($cap: $capty,)*)?
1008 __hydro_acc_once: $accty,
1009 __hydro_acc_twice: $accty,
1010 __hydro_x_0: $itemty,
1011 __hydro_x_1: $itemty,
1012 __hydro_x_2: $itemty,
1013 )
1014 requires
1015 __hydro_acc_once == __hydro_acc_twice,
1016 __hydro_x_0 == __hydro_x_1,
1017 __hydro_x_0 == __hydro_x_2,
1018 {
1019 $(
1020 let ghost $pstate = __hydro_acc_once;
1021 let ghost $px = __hydro_x_0;
1022 )?
1023 let mut __hydro_acc_once = __hydro_acc_once;
1024 let mut __hydro_acc_twice = __hydro_acc_twice;
1025 { let $tacc = &mut __hydro_acc_once; let $titem = __hydro_x_0; let _ = { $target_body }; }
1026 { let $tacc = &mut __hydro_acc_twice; let $titem = __hydro_x_1; let _ = { $target_body }; }
1027 { let $tacc = &mut __hydro_acc_twice; let $titem = __hydro_x_2; let _ = { $target_body }; }
1028 $(proof { $($proof_body)* })?
1029 assert(__hydro_acc_once == __hydro_acc_twice);
1030 }
1031 }
1032 };
1033
1034 $crate::properties::VerusIdempotentProof::new()
1035 }};
1036 (
1037 $($rest:tt)*
1038 ) => {{
1039 ::core::compile_error!(
1040 "verus_proof_idempotent_fold! must be used as a property annotation inside `q!(...)` on a `|acc, item| ...` closure, e.g. `idempotent = verus_proof_idempotent_fold!(acc = u32, item = u32)`"
1041 );
1042 $crate::properties::VerusIdempotentProof::new()
1043 }};
1044}
1045
1046#[macro_export]
1047/// Fulfills an `idempotent = ...` proof parameter for a **reduce closure** (shape
1048/// `|acc, item|` with `acc: &mut T` and `item: T`) with a **Verus-checked proof of
1049/// idempotence**.
1050///
1051/// `reduce` seeds its accumulator with the first element, so in addition to the
1052/// [`verus_proof_idempotent_fold!`] obligation (applying `x` twice in a row equals
1053/// applying it once, from any accumulator), this macro also proves the **seed**
1054/// obligation: if the first element is duplicated, applying the closure to an
1055/// accumulator seeded with `x` and the item `x` must leave the accumulator equal to `x`.
1056/// The fold obligation alone does not imply this; for example,
1057/// `|acc, x| *acc = max(*acc, x + 1)` satisfies it, but reducing `[a, a]` yields `a + 1`
1058/// instead of `a`.
1059///
1060/// ```rust,ignore
1061/// stream.reduce(q!(
1062/// |curr, new| { if new > *curr { *curr = new; } },
1063/// idempotent = verus_proof_idempotent_reduce!(item = u32)
1064/// ));
1065/// ```
1066///
1067/// Read-only captures are declared in a `captures = |...|` clause. An optional
1068/// `proof = |state, x| { ... }` script is inserted into both obligations (for the seed
1069/// obligation, `state` is bound to the item itself).
1070///
1071/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
1072/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
1073/// macro just produces a [`VerusIdempotentProof`] marker.
1074macro_rules! __verus_proof_idempotent_reduce__ {
1075 (
1076 item = $itemty:ty
1077 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
1078 $(, proof = |$pstate:ident, $px:ident| { $($proof_body:tt)* })?
1079 , __target = { $(move)? |$tacc:ident $(: $taccty:ty)?, $titem:ident $(: $titemty:ty)?| $target_body:expr }
1080 , __captures = [$($fv:ident),* $(,)?] $(,)?
1081 ) => {{
1082 /// Checks that every free variable captured by the closure is declared (with its
1083 /// type) in the `captures = |...|` clause: within this function, the *only* names
1084 /// in scope are the declared captures and the closure parameters, so an
1085 /// undeclared capture fails to resolve.
1086 #[allow(unused, reason = "only checks name resolution")]
1087 fn __hydro_verus_captures_declared($($($cap: $capty),*)?) {
1088 $(let $fv = &$fv;)*
1089 }
1090
1091 #[cfg(verus_keep_ghost)]
1092 const _: () = {
1093 #[allow(unused_imports)]
1094 use ::vstd::prelude::*;
1095
1096 ::vstd::prelude::verus! {
1097 /// Idempotence obligation, generated by `verus_proof_idempotent_reduce!`:
1098 /// applying the closure body with `x` twice in a row must yield the same
1099 /// accumulator as applying it once, from any equal starting accumulators,
1100 /// for all items and capture values. Verifying this also proves the body
1101 /// panic-free.
1102 fn __hydro_verus_idempotent(
1103 $($($cap: $capty,)*)?
1104 __hydro_acc_once: $itemty,
1105 __hydro_acc_twice: $itemty,
1106 __hydro_x_0: $itemty,
1107 __hydro_x_1: $itemty,
1108 __hydro_x_2: $itemty,
1109 )
1110 requires
1111 __hydro_acc_once == __hydro_acc_twice,
1112 __hydro_x_0 == __hydro_x_1,
1113 __hydro_x_0 == __hydro_x_2,
1114 {
1115 $(
1116 let ghost $pstate = __hydro_acc_once;
1117 let ghost $px = __hydro_x_0;
1118 )?
1119 let mut __hydro_acc_once = __hydro_acc_once;
1120 let mut __hydro_acc_twice = __hydro_acc_twice;
1121 { let $tacc = &mut __hydro_acc_once; let $titem = __hydro_x_0; let _ = { $target_body }; }
1122 { let $tacc = &mut __hydro_acc_twice; let $titem = __hydro_x_1; let _ = { $target_body }; }
1123 { let $tacc = &mut __hydro_acc_twice; let $titem = __hydro_x_2; let _ = { $target_body }; }
1124 $(proof { $($proof_body)* })?
1125 assert(__hydro_acc_once == __hydro_acc_twice);
1126 }
1127
1128 /// Seed obligation, generated by `verus_proof_idempotent_reduce!`: when
1129 /// the first element `x` is duplicated, the accumulator is seeded with `x`
1130 /// and then combined with `x`, which must leave it equal to `x`.
1131 fn __hydro_verus_idempotent_seed(
1132 $($($cap: $capty,)*)?
1133 __hydro_x_0: $itemty,
1134 __hydro_x_1: $itemty,
1135 )
1136 requires
1137 __hydro_x_0 == __hydro_x_1,
1138 {
1139 let ghost __hydro_seed = __hydro_x_0;
1140 $(
1141 let ghost $pstate = __hydro_x_0;
1142 let ghost $px = __hydro_x_0;
1143 )?
1144 let mut __hydro_acc = __hydro_x_0;
1145 { let $tacc = &mut __hydro_acc; let $titem = __hydro_x_1; let _ = { $target_body }; }
1146 $(proof { $($proof_body)* })?
1147 assert(__hydro_acc == __hydro_seed);
1148 }
1149 }
1150 };
1151
1152 $crate::properties::VerusIdempotentProof::new()
1153 }};
1154 (
1155 $($rest:tt)*
1156 ) => {{
1157 ::core::compile_error!(
1158 "verus_proof_idempotent_reduce! must be used as a property annotation inside `q!(...)` on a `|acc, item| ...` closure, e.g. `idempotent = verus_proof_idempotent_reduce!(item = u32)`"
1159 );
1160 $crate::properties::VerusIdempotentProof::new()
1161 }};
1162}
1163
1164#[macro_export]
1165/// Fulfills an `idempotent = ...` proof parameter for a **map-like closure** (shape
1166/// `|item| -> out`, e.g. for `map`, `filter_map`, or `flat_map_*`) that may mutate a
1167/// captured singleton reference (from [`Singleton::by_mut`]), with a **Verus-checked
1168/// proof of idempotence**.
1169///
1170/// **What idempotence means for a map closure:** processing an item twice in a row,
1171/// starting from the same captured state, must (1) leave the captured state in the same
1172/// final value as processing it once, *and* (2) produce the same output both times as
1173/// processing it once. Because the output stream also has at-least-once semantics, a
1174/// retried element may re-emit its output, but must not emit a *different* one: a closure
1175/// that reports whether an element is new (e.g. `true` then `false`) is **not**
1176/// idempotent even if its state update is.
1177///
1178/// The mutated state is the mutable capture, declared (with the type behind the
1179/// reference) in the required `captures_mut = |state: S|` clause; additional read-only
1180/// captures can be declared in a `captures = |...|` clause. The macro checks at compile
1181/// time that every capture is declared. The `item = ...` type must be written exactly as
1182/// the closure receives it.
1183///
1184/// An optional `proof = |state, x| { ... }` clause supplies a proof *script* to help the
1185/// SMT solver, with ghost bindings for the initial captured state and the item.
1186///
1187/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
1188/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
1189/// macro just produces a [`VerusIdempotentProof`] marker.
1190///
1191/// # Example
1192/// ```rust,ignore
1193/// let max_mut = max_seen.by_mut();
1194/// stream.map(q!(
1195/// |x| {
1196/// if x > *max_mut { *max_mut = x; }
1197/// x // outputting `x > *max_mut` (is this new?) would NOT be idempotent!
1198/// },
1199/// idempotent = verus_proof_idempotent_map!(
1200/// item = u32,
1201/// captures_mut = |max_mut: u32|
1202/// )
1203/// ));
1204/// ```
1205///
1206/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
1207macro_rules! __verus_proof_idempotent_map__ {
1208 (
1209 item = $itemty:ty
1210 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
1211 , captures_mut = |$mcap:ident : $mcapty:ty $(,)?|
1212 $(, proof = |$pstate:ident, $px:ident| { $($proof_body:tt)* })?
1213 , __target = { $(move)? |$titem:ident $(: $titemty:ty)?| $target_body:expr }
1214 , __captures = [$($fv:ident),* $(,)?] $(,)?
1215 ) => {{
1216 /// Checks that every free variable captured by the closure is declared (with its
1217 /// type) in the `captures = |...|` or `captures_mut = |...|` clauses: within this
1218 /// function, the *only* names in scope are the declared captures, so an
1219 /// undeclared capture fails to resolve.
1220 #[allow(unused, reason = "only checks name resolution")]
1221 fn __hydro_verus_captures_declared($($($cap: $capty,)*)? $mcap: $mcapty) {
1222 $(let $fv = &$fv;)*
1223 }
1224
1225 #[cfg(verus_keep_ghost)]
1226 const _: () = {
1227 #[allow(unused_imports)]
1228 use ::vstd::prelude::*;
1229
1230 ::vstd::prelude::verus! {
1231 /// Idempotence obligation, generated by `verus_proof_idempotent_map!`:
1232 /// from any equal starting captured states, processing `x` twice in a
1233 /// row must yield the same final captured state as processing it once,
1234 /// and both outputs of the repeated run must equal the output of the
1235 /// single run. Verifying this also proves the body panic-free.
1236 fn __hydro_verus_idempotent(
1237 $($($cap: $capty,)*)?
1238 __hydro_state_once: $mcapty,
1239 __hydro_state_twice: $mcapty,
1240 __hydro_x_0: $itemty,
1241 __hydro_x_1: $itemty,
1242 __hydro_x_2: $itemty,
1243 )
1244 requires
1245 __hydro_state_once == __hydro_state_twice,
1246 __hydro_x_0 == __hydro_x_1,
1247 __hydro_x_0 == __hydro_x_2,
1248 {
1249 $(
1250 let ghost $pstate = __hydro_state_once;
1251 let ghost $px = __hydro_x_0;
1252 )?
1253 let mut __hydro_state_once = __hydro_state_once;
1254 let mut __hydro_state_twice = __hydro_state_twice;
1255 let __hydro_out_once = { let $mcap = &mut __hydro_state_once; let $titem = __hydro_x_0; $target_body };
1256 let __hydro_out_twice_1 = { let $mcap = &mut __hydro_state_twice; let $titem = __hydro_x_1; $target_body };
1257 let __hydro_out_twice_2 = { let $mcap = &mut __hydro_state_twice; let $titem = __hydro_x_2; $target_body };
1258 $(proof { $($proof_body)* })?
1259 assert(__hydro_state_once == __hydro_state_twice);
1260 assert(__hydro_out_twice_1 == __hydro_out_once && __hydro_out_twice_2 == __hydro_out_once);
1261 }
1262 }
1263 };
1264
1265 $crate::properties::VerusIdempotentProof::new()
1266 }};
1267 (
1268 $($rest:tt)*
1269 ) => {{
1270 ::core::compile_error!(
1271 "verus_proof_idempotent_map! must be used as a property annotation inside `q!(...)` on a `|item| ...` closure with exactly one `captures_mut` entry, e.g. `idempotent = verus_proof_idempotent_map!(item = u32, captures_mut = |state: u32|)`"
1272 );
1273 $crate::properties::VerusIdempotentProof::new()
1274 }};
1275}
1276
1277#[macro_export]
1278/// Fulfills an `idempotent = ...` proof parameter for a **predicate** (shape
1279/// `|item| -> bool` where `item` is received by reference, e.g. for `filter` or
1280/// `partition`) that may mutate a captured singleton reference (from
1281/// [`Singleton::by_mut`]), with a **Verus-checked proof of idempotence**.
1282///
1283/// **What idempotence means for a predicate:** processing an item twice in a row,
1284/// starting from the same captured state, must (1) leave the captured state in the same
1285/// final value as processing it once, *and* (2) make the same decision both times as
1286/// processing it once. Condition (2) is required for `partition`, where an element
1287/// rejected on retry lands in the *other* output. (For `filter` alone, dropping a retried
1288/// element that was retained the first time would be harmless; this macro
1289/// conservatively rejects it as well.)
1290///
1291/// The mutated state is the mutable capture, declared (with the type behind the
1292/// reference) in the required `captures_mut = |state: S|` clause; additional read-only
1293/// captures can be declared in a `captures = |...|` clause. The macro checks at compile
1294/// time that every capture is declared. The `item = ...` type must be written exactly as
1295/// the closure receives it (a reference like `&u32`).
1296///
1297/// An optional `proof = |state, x| { ... }` clause supplies a proof *script* to help the
1298/// SMT solver, with ghost bindings for the initial captured state and the item.
1299///
1300/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
1301/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
1302/// macro just produces a [`VerusIdempotentProof`] marker.
1303///
1304/// # Example
1305/// ```rust,ignore
1306/// let max_mut = max_seen.by_mut();
1307/// stream.filter(q!(
1308/// |x| {
1309/// if *x > *max_mut { *max_mut = *x; }
1310/// *x > 1 // the decision must not depend on whether `x` was seen before!
1311/// },
1312/// idempotent = verus_proof_idempotent_filter!(
1313/// item = &u32,
1314/// captures_mut = |max_mut: u32|
1315/// )
1316/// ));
1317/// ```
1318///
1319/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
1320macro_rules! __verus_proof_idempotent_filter__ {
1321 (
1322 item = $itemty:ty
1323 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
1324 , captures_mut = |$mcap:ident : $mcapty:ty $(,)?|
1325 $(, proof = |$pstate:ident, $px:ident| { $($proof_body:tt)* })?
1326 , __target = { $(move)? |$titem:ident $(: $titemty:ty)?| $target_body:expr }
1327 , __captures = [$($fv:ident),* $(,)?] $(,)?
1328 ) => {{
1329 /// Checks that every free variable captured by the closure is declared (with its
1330 /// type) in the `captures = |...|` or `captures_mut = |...|` clauses: within this
1331 /// function, the *only* names in scope are the declared captures, so an
1332 /// undeclared capture fails to resolve.
1333 #[allow(unused, reason = "only checks name resolution")]
1334 fn __hydro_verus_captures_declared($($($cap: $capty,)*)? $mcap: $mcapty) {
1335 $(let $fv = &$fv;)*
1336 }
1337
1338 #[cfg(verus_keep_ghost)]
1339 const _: () = {
1340 #[allow(unused_imports)]
1341 use ::vstd::prelude::*;
1342
1343 ::vstd::prelude::verus! {
1344 /// Idempotence obligation, generated by `verus_proof_idempotent_filter!`:
1345 /// from any equal starting captured states, processing `x` twice in a
1346 /// row must yield the same final captured state as processing it once,
1347 /// and both decisions of the repeated run must equal the decision of the
1348 /// single run. Verifying this also proves the body panic-free.
1349 fn __hydro_verus_idempotent(
1350 $($($cap: $capty,)*)?
1351 __hydro_state_once: $mcapty,
1352 __hydro_state_twice: $mcapty,
1353 __hydro_x_0: $itemty,
1354 __hydro_x_1: $itemty,
1355 __hydro_x_2: $itemty,
1356 )
1357 requires
1358 __hydro_state_once == __hydro_state_twice,
1359 __hydro_x_0 == __hydro_x_1,
1360 __hydro_x_0 == __hydro_x_2,
1361 {
1362 $(
1363 let ghost $pstate = __hydro_state_once;
1364 let ghost $px = __hydro_x_0;
1365 )?
1366 let mut __hydro_state_once = __hydro_state_once;
1367 let mut __hydro_state_twice = __hydro_state_twice;
1368 let __hydro_keep_once: bool = { let $mcap = &mut __hydro_state_once; let $titem = __hydro_x_0; $target_body };
1369 let __hydro_keep_twice_1: bool = { let $mcap = &mut __hydro_state_twice; let $titem = __hydro_x_1; $target_body };
1370 let __hydro_keep_twice_2: bool = { let $mcap = &mut __hydro_state_twice; let $titem = __hydro_x_2; $target_body };
1371 $(proof { $($proof_body)* })?
1372 assert(__hydro_state_once == __hydro_state_twice);
1373 assert(__hydro_keep_twice_1 == __hydro_keep_once && __hydro_keep_twice_2 == __hydro_keep_once);
1374 }
1375 }
1376 };
1377
1378 $crate::properties::VerusIdempotentProof::new()
1379 }};
1380 (
1381 $($rest:tt)*
1382 ) => {{
1383 ::core::compile_error!(
1384 "verus_proof_idempotent_filter! must be used as a property annotation inside `q!(...)` on a `|item| -> bool` closure with exactly one `captures_mut` entry, e.g. `idempotent = verus_proof_idempotent_filter!(item = &u32, captures_mut = |state: u32|)`"
1385 );
1386 $crate::properties::VerusIdempotentProof::new()
1387 }};
1388}
1389
1390#[macro_export]
1391/// Fulfills an `idempotent = ...` proof parameter for a **unit-returning, effectful
1392/// closure** (shape `|item| -> ()`, e.g. for `for_each` or `inspect`) that mutates a
1393/// captured singleton reference (from [`Singleton::by_mut`]), with a **Verus-checked
1394/// proof of idempotence** of the captured-state update.
1395///
1396/// **What idempotence means for an effectful closure:** processing an item twice in a
1397/// row, starting from the same captured state, must leave the captured state in the same
1398/// final value as processing it once. Because the closure returns `()` (enforced by this
1399/// macro; use [`verus_proof_idempotent_map!`] or [`verus_proof_idempotent_filter!`] for
1400/// closures whose return value is observable), the state is the only observable effect.
1401///
1402/// The mutated state is the mutable capture, declared (with the type behind the
1403/// reference) in the required `captures_mut = |state: S|` clause; additional read-only
1404/// captures can be declared in a `captures = |...|` clause. The macro checks at compile
1405/// time that every capture is declared. The `item = ...` type must be written exactly as
1406/// the closure receives it (e.g. `&u32` for `inspect`).
1407///
1408/// An optional `proof = |state, x| { ... }` clause supplies a proof *script* to help the
1409/// SMT solver, with ghost bindings for the initial captured state and the item.
1410///
1411/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
1412/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
1413/// macro just produces a [`VerusIdempotentProof`] marker.
1414///
1415/// # Example
1416/// ```rust,ignore
1417/// let flags_mut = flags.by_mut();
1418/// stream.for_each(q!(
1419/// |x| { *flags_mut |= x; },
1420/// idempotent = verus_proof_idempotent_effect!(
1421/// item = u32,
1422/// captures_mut = |flags_mut: u32|,
1423/// proof = |s, x| { assert(((s | x) | x) == (s | x)) by (bit_vector); }
1424/// )
1425/// ));
1426/// ```
1427///
1428/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
1429macro_rules! __verus_proof_idempotent_effect__ {
1430 (
1431 item = $itemty:ty
1432 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
1433 , captures_mut = |$mcap:ident : $mcapty:ty $(,)?|
1434 $(, proof = |$pstate:ident, $px:ident| { $($proof_body:tt)* })?
1435 , __target = { $(move)? |$titem:ident $(: $titemty:ty)?| $target_body:expr }
1436 , __captures = [$($fv:ident),* $(,)?] $(,)?
1437 ) => {{
1438 /// Checks that every free variable captured by the closure is declared (with its
1439 /// type) in the `captures = |...|` or `captures_mut = |...|` clauses: within this
1440 /// function, the *only* names in scope are the declared captures, so an
1441 /// undeclared capture fails to resolve.
1442 #[allow(unused, reason = "only checks name resolution")]
1443 fn __hydro_verus_captures_declared($($($cap: $capty,)*)? $mcap: $mcapty) {
1444 $(let $fv = &$fv;)*
1445 }
1446
1447 #[cfg(verus_keep_ghost)]
1448 const _: () = {
1449 #[allow(unused_imports)]
1450 use ::vstd::prelude::*;
1451
1452 ::vstd::prelude::verus! {
1453 /// Idempotence obligation, generated by `verus_proof_idempotent_effect!`:
1454 /// applying the closure body with `x` twice in a row must yield the same
1455 /// captured state as applying it once, from any equal starting states.
1456 /// The closure must return `()`, so the state is the only observable
1457 /// effect. Verifying this also proves the body panic-free.
1458 fn __hydro_verus_idempotent(
1459 $($($cap: $capty,)*)?
1460 __hydro_state_once: $mcapty,
1461 __hydro_state_twice: $mcapty,
1462 __hydro_x_0: $itemty,
1463 __hydro_x_1: $itemty,
1464 __hydro_x_2: $itemty,
1465 )
1466 requires
1467 __hydro_state_once == __hydro_state_twice,
1468 __hydro_x_0 == __hydro_x_1,
1469 __hydro_x_0 == __hydro_x_2,
1470 {
1471 $(
1472 let ghost $pstate = __hydro_state_once;
1473 let ghost $px = __hydro_x_0;
1474 )?
1475 let mut __hydro_state_once = __hydro_state_once;
1476 let mut __hydro_state_twice = __hydro_state_twice;
1477 { let $mcap = &mut __hydro_state_once; let $titem = __hydro_x_0; let __hydro_out: () = { $target_body }; }
1478 { let $mcap = &mut __hydro_state_twice; let $titem = __hydro_x_1; let __hydro_out: () = { $target_body }; }
1479 { let $mcap = &mut __hydro_state_twice; let $titem = __hydro_x_2; let __hydro_out: () = { $target_body }; }
1480 $(proof { $($proof_body)* })?
1481 assert(__hydro_state_once == __hydro_state_twice);
1482 }
1483 }
1484 };
1485
1486 $crate::properties::VerusIdempotentProof::new()
1487 }};
1488 (
1489 $($rest:tt)*
1490 ) => {{
1491 ::core::compile_error!(
1492 "verus_proof_idempotent_effect! must be used as a property annotation inside `q!(...)` on a `|item| -> ()` closure with exactly one `captures_mut` entry, e.g. `idempotent = verus_proof_idempotent_effect!(item = u32, captures_mut = |state: u32|)`"
1493 );
1494 $crate::properties::VerusIdempotentProof::new()
1495 }};
1496}
1497
1498#[macro_export]
1499/// Fulfills a `monotone = ...` proof parameter for an **aggregation closure**
1500/// (`fold` / `reduce`, shape `|acc, item|` with `acc: &mut A`) with a **Verus-checked
1501/// proof of monotonicity**.
1502///
1503/// **What monotonicity means for an aggregation:** applying the closure to any
1504/// accumulator value and any item must leave the accumulator **greater than or equal**
1505/// to its previous value, with respect to the accumulator type's [`PartialOrd`]. This is
1506/// the order that `Monotonic` singletons are observed through (e.g. by
1507/// [`Singleton::threshold_greater_or_equal`]), so a monotone aggregation yields a
1508/// singleton whose value only grows over time, making threshold detection deterministic.
1509///
1510/// Users never write the proof obligation (so they cannot get it wrong): this macro
1511/// receives the quoted closure itself from `q!` (as a trailing `__target = { ... }`
1512/// argument) and generates a Verus function that takes a ghost snapshot of an arbitrary
1513/// accumulator, symbolically executes the *actual closure body* on it with an arbitrary
1514/// item, and asserts that the snapshot compares less than or equal to the final
1515/// accumulator. Verifying this obligation also proves the closure body panic-free (e.g.
1516/// no arithmetic overflow). Users only declare the accumulator and item types:
1517///
1518/// ```rust,ignore
1519/// stream.fold(
1520/// q!(|| 0u32),
1521/// q!(
1522/// |max, x| { if x > *max { *max = x; } },
1523/// monotone = verus_proof_monotone_fold!(acc = u32, item = u32)
1524/// )
1525/// );
1526/// ```
1527///
1528/// The comparison is expressed through Verus's specification of [`PartialOrd`]
1529/// (`vstd::std_specs::cmp::PartialOrdSpec`): the obligation requires that the
1530/// accumulator type's `PartialOrd` implementation is known to follow its specification
1531/// (`obeys_partial_cmp_spec()`), and that the specification orders the old value at or
1532/// below the new one. This holds automatically for primitive integers and tuples of
1533/// them; your own accumulator types must implement `PartialOrdSpecImpl` inside a
1534/// `verus!` block.
1535///
1536/// If the closure captures (read-only) variables from its environment, re-declare them
1537/// (with their runtime types) in a `captures = |...|` clause; the obligation is then
1538/// universally quantified over the capture values. `q!` also passes the closure's capture
1539/// list (as a trailing `__captures = [...]` argument), and the macro checks at compile
1540/// time that every capture is declared.
1541///
1542/// An optional `proof = |state, x| { ... }` (or `proof = |state, x, result| { ... }`)
1543/// clause supplies a proof *script* to help the SMT solver, with ghost bindings for the
1544/// initial accumulator, the item, and (optionally) the final accumulator (e.g.
1545/// `proof = |s, x| { assert(s <= (s | x)) by (bit_vector); }`). The script is checked by
1546/// Verus and cannot weaken the obligation (though, as anywhere in Verus, `assume` is an
1547/// explicit soundness escape hatch).
1548///
1549/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
1550/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
1551/// macro just produces a [`VerusMonotoneProof`] marker, so the types go through the
1552/// ordinary `monotone = ...` mechanism with zero overhead.
1553///
1554/// [`Singleton::threshold_greater_or_equal`]: crate::live_collections::singleton::Singleton::threshold_greater_or_equal
1555macro_rules! __verus_proof_monotone_fold__ {
1556 (
1557 acc = $accty:ty, item = $itemty:ty
1558 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
1559 $(, proof = |$pstate:ident, $px:ident $(, $pafter:ident)?| { $($proof_body:tt)* })?
1560 , __target = { $(move)? |$tacc:ident $(: $taccty:ty)?, $titem:ident $(: $titemty:ty)?| $target_body:expr }
1561 , __captures = [$($fv:ident),* $(,)?] $(,)?
1562 ) => {{
1563 /// Checks that every free variable captured by the closure is declared (with its
1564 /// type) in the `captures = |...|` clause: within this function, the *only* names
1565 /// in scope are the declared captures and the closure parameters, so an
1566 /// undeclared capture fails to resolve.
1567 #[allow(unused, reason = "only checks name resolution")]
1568 fn __hydro_verus_captures_declared($($($cap: $capty),*)?) {
1569 $(let $fv = &$fv;)*
1570 }
1571 #[cfg(verus_keep_ghost)]
1572 const _: () = {
1573 #[allow(unused_imports)]
1574 use ::vstd::prelude::*;
1575 #[allow(unused_imports)]
1576 use ::vstd::std_specs::cmp::PartialOrdSpec;
1577
1578 ::vstd::prelude::verus! {
1579 /// Monotonicity obligation, generated by `verus_proof_monotone_fold!`:
1580 /// applying the closure body to any accumulator with any item must
1581 /// leave the accumulator greater than or equal (per its `PartialOrd`
1582 /// specification) to its previous value, for all capture values.
1583 /// Verifying this also proves the body panic-free.
1584 fn __hydro_verus_monotone(
1585 $($($cap: $capty,)*)?
1586 __hydro_acc: $accty,
1587 __hydro_x: $itemty,
1588 ) {
1589 let ghost __hydro_before = __hydro_acc;
1590 $(
1591 let ghost $pstate = __hydro_acc;
1592 let ghost $px = __hydro_x;
1593 )?
1594 let mut __hydro_acc = __hydro_acc;
1595 { let $tacc = &mut __hydro_acc; let $titem = __hydro_x; let _ = { $target_body }; }
1596 $(
1597 $(let ghost $pafter = __hydro_acc;)?
1598 proof { $($proof_body)* }
1599 )?
1600 assert(<$accty as PartialOrdSpec>::obeys_partial_cmp_spec());
1601 assert(
1602 __hydro_before.partial_cmp_spec(&__hydro_acc)
1603 matches Some(::core::cmp::Ordering::Less | ::core::cmp::Ordering::Equal)
1604 );
1605 }
1606 }
1607 };
1608
1609 $crate::properties::VerusMonotoneProof::new()
1610 }};
1611 (
1612 $($rest:tt)*
1613 ) => {{
1614 ::core::compile_error!(
1615 "verus_proof_monotone_fold! must be used as a property annotation inside `q!(...)` on a `|acc, item| ...` closure, e.g. `monotone = verus_proof_monotone_fold!(acc = u32, item = u32)`"
1616 );
1617 $crate::properties::VerusMonotoneProof::new()
1618 }};
1619}
1620
1621#[macro_export]
1622/// Fulfills an `order_preserving = ...` proof parameter for a **singleton map closure**
1623/// (shape `|value| -> out`, as taken by [`Singleton::map`]) with a **Verus-checked proof
1624/// of order preservation**.
1625///
1626/// **What order preservation means for a map closure:** for any two inputs `x <= y`
1627/// (with respect to the input type's [`PartialOrd`]), the outputs must satisfy
1628/// `f(x) <= f(y)` (with respect to the output type's [`PartialOrd`]). A `Monotonic`
1629/// singleton only ever grows, so mapping it through an order-preserving function yields
1630/// a singleton that also only grows, which lets the result stay `Monotonic` (e.g. for a
1631/// deterministic [`Singleton::threshold_greater_or_equal`]).
1632///
1633/// Users never write the proof obligation (so they cannot get it wrong): this macro
1634/// receives the quoted closure itself from `q!` (as a trailing `__target = { ... }`
1635/// argument) and generates a Verus function that, assuming two arbitrary inputs with
1636/// `x <= y`, symbolically executes the *actual closure body* on each and asserts that the
1637/// outputs compare less than or equal. Verifying this obligation also proves the closure
1638/// body panic-free (e.g. no arithmetic overflow). Users only declare the input and output
1639/// types:
1640///
1641/// ```rust,ignore
1642/// let doubled = sum.map(q!(
1643/// |v| v.saturating_mul(2),
1644/// order_preserving = verus_proof_order_preserving_map!(input = u32, output = u32)
1645/// ));
1646/// ```
1647///
1648/// The comparisons are expressed through Verus's specification of [`PartialOrd`]
1649/// (`vstd::std_specs::cmp::PartialOrdSpec`): the obligation requires that both the
1650/// input and output types' `PartialOrd` implementations are known to follow their
1651/// specification (`obeys_partial_cmp_spec()`). This holds automatically for primitive
1652/// integers and tuples of them; your own types must implement `PartialOrdSpecImpl`
1653/// inside a `verus!` block.
1654///
1655/// If the closure captures (read-only) variables from its environment, re-declare them
1656/// (with their runtime types) in a `captures = |...|` clause; the obligation is then
1657/// universally quantified over the capture values. `q!` also passes the closure's capture
1658/// list (as a trailing `__captures = [...]` argument), and the macro checks at compile
1659/// time that every capture is declared.
1660///
1661/// An optional `proof = |x, y| { ... }` (or `proof = |x, y, fx, fy| { ... }`) clause
1662/// supplies a proof *script* to help the SMT solver, with ghost bindings for the two
1663/// inputs and (optionally) the two outputs. The script is checked by Verus and cannot
1664/// weaken the obligation (though, as anywhere in Verus, `assume` is an explicit soundness
1665/// escape hatch).
1666///
1667/// The proof is gated on `cfg(verus_keep_ghost)`, so it only exists when the crate is
1668/// compiled by the Verus driver (`cargo verus verify`). Under normal compilation the
1669/// macro just produces a [`VerusOrderPreservingProof`] marker, so the types go through
1670/// the ordinary `order_preserving = ...` mechanism with zero overhead.
1671///
1672/// [`Singleton::map`]: crate::live_collections::singleton::Singleton::map
1673/// [`Singleton::threshold_greater_or_equal`]: crate::live_collections::singleton::Singleton::threshold_greater_or_equal
1674macro_rules! __verus_proof_order_preserving_map__ {
1675 (
1676 input = $inty:ty, output = $outty:ty
1677 $(, captures = |$($cap:ident : $capty:ty),* $(,)?|)?
1678 $(, proof = |$px:ident, $py:ident $(, $pfx:ident, $pfy:ident)?| { $($proof_body:tt)* })?
1679 , __target = { $(move)? |$tin:ident $(: $tinty:ty)?| $target_body:expr }
1680 , __captures = [$($fv:ident),* $(,)?] $(,)?
1681 ) => {{
1682 /// Checks that every free variable captured by the closure is declared (with its
1683 /// type) in the `captures = |...|` clause: within this function, the *only* names
1684 /// in scope are the declared captures and the closure parameter, so an
1685 /// undeclared capture fails to resolve.
1686 #[allow(unused, reason = "only checks name resolution")]
1687 fn __hydro_verus_captures_declared($($($cap: $capty),*)?) {
1688 $(let $fv = &$fv;)*
1689 }
1690 #[cfg(verus_keep_ghost)]
1691 const _: () = {
1692 #[allow(unused_imports)]
1693 use ::vstd::prelude::*;
1694 #[allow(unused_imports)]
1695 use ::vstd::std_specs::cmp::PartialOrdSpec;
1696
1697 ::vstd::prelude::verus! {
1698 /// Order-preservation obligation, generated by
1699 /// `verus_proof_order_preserving_map!`: for any two inputs ordered
1700 /// `x <= y` (per the input type's `PartialOrd` specification), applying
1701 /// the closure body to each must yield outputs ordered `f(x) <= f(y)`
1702 /// (per the output type's `PartialOrd` specification), for all capture
1703 /// values. Verifying this also proves the body panic-free.
1704 fn __hydro_verus_order_preserving(
1705 $($($cap: $capty,)*)?
1706 __hydro_x: $inty,
1707 __hydro_y: $inty,
1708 )
1709 requires
1710 __hydro_x.partial_cmp_spec(&__hydro_y)
1711 matches Some(::core::cmp::Ordering::Less | ::core::cmp::Ordering::Equal),
1712 {
1713 $(
1714 let ghost $px = __hydro_x;
1715 let ghost $py = __hydro_y;
1716 )?
1717 let __hydro_out_x: $outty = { let $tin = __hydro_x; $target_body };
1718 let __hydro_out_y: $outty = { let $tin = __hydro_y; $target_body };
1719 $(
1720 $(
1721 let ghost $pfx = __hydro_out_x;
1722 let ghost $pfy = __hydro_out_y;
1723 )?
1724 proof { $($proof_body)* }
1725 )?
1726 assert(<$inty as PartialOrdSpec>::obeys_partial_cmp_spec());
1727 assert(<$outty as PartialOrdSpec>::obeys_partial_cmp_spec());
1728 assert(
1729 __hydro_out_x.partial_cmp_spec(&__hydro_out_y)
1730 matches Some(::core::cmp::Ordering::Less | ::core::cmp::Ordering::Equal)
1731 );
1732 }
1733 }
1734 };
1735
1736 $crate::properties::VerusOrderPreservingProof::new()
1737 }};
1738 (
1739 $($rest:tt)*
1740 ) => {{
1741 ::core::compile_error!(
1742 "verus_proof_order_preserving_map! must be used as a property annotation inside `q!(...)` on a `|value| ...` closure, e.g. `order_preserving = verus_proof_order_preserving_map!(input = u32, output = u32)`"
1743 );
1744 $crate::properties::VerusOrderPreservingProof::new()
1745 }};
1746}
1747
1748/// Marks that the property is not proved.
1749pub enum NotProved {}
1750
1751/// Marks that the property is proven.
1752pub enum Proved {}
1753
1754/// Algebraic properties for an aggregation function of type (T, &mut A) -> ().
1755///
1756/// Commutativity:
1757/// ```rust,ignore
1758/// let mut state = ???;
1759/// f(a, &mut state); f(b, &mut state) // produces same final state as
1760/// f(b, &mut state); f(a, &mut state)
1761/// ```
1762///
1763/// Idempotence:
1764/// ```rust,ignore
1765/// let mut state = ???;
1766/// f(a, &mut state);
1767/// let state1 = *state;
1768/// f(a, &mut state);
1769/// // state1 must be equal to state
1770/// ```
1771///
1772/// For `reduce`, whose accumulator is seeded with the first element, idempotence
1773/// additionally requires that `f(a, &mut a)` leaves the accumulator equal to `a` (the
1774/// first element may itself be duplicated).
1775pub struct AggFuncAlgebra<
1776 T = (),
1777 B: Boundedness = crate::live_collections::boundedness::Unbounded,
1778 Commutative = NotProved,
1779 Idempotent = NotProved,
1780 Monotone = NotProved,
1781 S = OnProcess,
1782>(
1783 Option<Box<dyn CommutativeProof<T, B, S>>>,
1784 Option<Box<dyn IdempotentProof>>,
1785 Option<Box<dyn MonotoneProof>>,
1786 PhantomData<(Commutative, Idempotent, Monotone)>,
1787);
1788
1789impl<T, B: Boundedness, C, I, M, S> AggFuncAlgebra<T, B, C, I, M, S> {
1790 /// Marks the function as being commutative, with the given proof mechanism.
1791 pub fn commutative(
1792 self,
1793 proof: impl CommutativeProof<T, B, S> + 'static,
1794 ) -> AggFuncAlgebra<T, B, Proved, I, M, S> {
1795 AggFuncAlgebra(Some(Box::new(proof)), self.1, self.2, PhantomData)
1796 }
1797
1798 /// Marks the function as being idempotent, with the given proof mechanism.
1799 pub fn idempotent(
1800 self,
1801 proof: impl IdempotentProof + 'static,
1802 ) -> AggFuncAlgebra<T, B, C, Proved, M, S> {
1803 AggFuncAlgebra(self.0, Some(Box::new(proof)), self.2, PhantomData)
1804 }
1805
1806 /// Marks the function as being monotone, with the given proof mechanism.
1807 pub fn monotone(
1808 self,
1809 proof: impl MonotoneProof + 'static,
1810 ) -> AggFuncAlgebra<T, B, C, I, Proved, S> {
1811 AggFuncAlgebra(self.0, self.1, Some(Box::new(proof)), PhantomData)
1812 }
1813
1814 /// Registers the expression with the underlying proof mechanisms, and takes the
1815 /// simulator ordering hook attached to the commutativity proof, if any.
1816 pub(crate) fn register_proof(
1817 self,
1818 expr: &syn::Expr,
1819 ) -> Option<OrderingHook<T, B, ExactlyOnce, S>> {
1820 let mut hook = None;
1821 if let Some(mut comm_proof) = self.0 {
1822 comm_proof.register_proof(expr);
1823 hook = comm_proof.take_hook();
1824 }
1825
1826 if let Some(idem_proof) = self.1 {
1827 idem_proof.register_proof(expr);
1828 }
1829
1830 if let Some(monotone_proof) = self.2 {
1831 monotone_proof.register_proof(expr);
1832 }
1833
1834 hook
1835 }
1836}
1837
1838impl<T, B: Boundedness, C, I, M, S> Property for AggFuncAlgebra<T, B, C, I, M, S> {
1839 type Root = AggFuncAlgebra<T, B, NotProved, NotProved, NotProved, S>;
1840
1841 fn make_root(_target: &mut Option<Self>) -> Self::Root {
1842 AggFuncAlgebra(None, None, None, PhantomData)
1843 }
1844}
1845
1846/// Algebraic properties for a singleton map function of type T -> U.
1847///
1848/// Order-preserving means that if the input grows monotonically, the output also grows monotonically.
1849pub struct SingletonMapFuncAlgebra<
1850 T = (),
1851 B: Boundedness = crate::live_collections::boundedness::Unbounded,
1852 OrderPreserving = NotProved,
1853 Commutative = NotProved,
1854 Idempotent = NotProved,
1855 S = OnProcess,
1856>(
1857 Option<Box<dyn OrderPreservingProof>>,
1858 Option<Box<dyn CommutativeProof<T, B, S>>>,
1859 Option<Box<dyn IdempotentProof>>,
1860 PhantomData<(OrderPreserving, Commutative, Idempotent)>,
1861);
1862
1863impl<T, B: Boundedness, O, C, I, S> SingletonMapFuncAlgebra<T, B, O, C, I, S> {
1864 /// Marks the function as being order-preserving, with the given proof mechanism.
1865 pub fn order_preserving(
1866 self,
1867 proof: impl OrderPreservingProof + 'static,
1868 ) -> SingletonMapFuncAlgebra<T, B, Proved, C, I, S> {
1869 SingletonMapFuncAlgebra(Some(Box::new(proof)), self.1, self.2, PhantomData)
1870 }
1871
1872 /// Marks the function as being commutative, with the given proof mechanism.
1873 pub fn commutative(
1874 self,
1875 proof: impl CommutativeProof<T, B, S> + 'static,
1876 ) -> SingletonMapFuncAlgebra<T, B, O, Proved, I, S> {
1877 SingletonMapFuncAlgebra(self.0, Some(Box::new(proof)), self.2, PhantomData)
1878 }
1879
1880 /// Marks the function as being idempotent, with the given proof mechanism.
1881 pub fn idempotent(
1882 self,
1883 proof: impl IdempotentProof + 'static,
1884 ) -> SingletonMapFuncAlgebra<T, B, O, C, Proved, S> {
1885 SingletonMapFuncAlgebra(self.0, self.1, Some(Box::new(proof)), PhantomData)
1886 }
1887
1888 /// Registers the expression with the underlying proof mechanisms, and takes the
1889 /// simulator ordering hook attached to the commutativity proof, if any.
1890 pub(crate) fn register_proof(
1891 self,
1892 expr: &syn::Expr,
1893 ) -> Option<OrderingHook<T, B, ExactlyOnce, S>> {
1894 if let Some(proof) = self.0 {
1895 proof.register_proof(expr);
1896 }
1897 self.1.and_then(|mut proof| {
1898 proof.register_proof(expr);
1899 proof.take_hook()
1900 })
1901 }
1902}
1903
1904impl<T, B: Boundedness, O, C, I, S> Property for SingletonMapFuncAlgebra<T, B, O, C, I, S> {
1905 type Root = SingletonMapFuncAlgebra<T, B, NotProved, NotProved, NotProved, S>;
1906
1907 fn make_root(_target: &mut Option<Self>) -> Self::Root {
1908 SingletonMapFuncAlgebra(None, None, None, PhantomData)
1909 }
1910}
1911
1912/// Algebraic properties for a stream map function of type T -> U.
1913pub struct StreamMapFuncAlgebra<
1914 T = (),
1915 B: Boundedness = crate::live_collections::boundedness::Unbounded,
1916 Commutative = NotProved,
1917 Idempotent = NotProved,
1918 S = OnProcess,
1919>(
1920 Option<Box<dyn CommutativeProof<T, B, S>>>,
1921 Option<Box<dyn IdempotentProof>>,
1922 PhantomData<(Commutative, Idempotent)>,
1923);
1924
1925impl<T, B: Boundedness, C, I, S> StreamMapFuncAlgebra<T, B, C, I, S> {
1926 /// Marks the function as being commutative, with the given proof mechanism.
1927 pub fn commutative(
1928 self,
1929 proof: impl CommutativeProof<T, B, S> + 'static,
1930 ) -> StreamMapFuncAlgebra<T, B, Proved, I, S> {
1931 StreamMapFuncAlgebra(Some(Box::new(proof)), self.1, PhantomData)
1932 }
1933
1934 /// Marks the function as being idempotent, with the given proof mechanism.
1935 pub fn idempotent(
1936 self,
1937 proof: impl IdempotentProof + 'static,
1938 ) -> StreamMapFuncAlgebra<T, B, C, Proved, S> {
1939 StreamMapFuncAlgebra(self.0, Some(Box::new(proof)), PhantomData)
1940 }
1941
1942 /// Registers the expression with the underlying proof mechanisms, and takes the
1943 /// simulator ordering hook attached to the commutativity proof, if any.
1944 pub(crate) fn register_proof(
1945 self,
1946 expr: &syn::Expr,
1947 ) -> Option<OrderingHook<T, B, ExactlyOnce, S>> {
1948 let hook = self.0.and_then(|mut proof| {
1949 proof.register_proof(expr);
1950 proof.take_hook()
1951 });
1952 if let Some(proof) = self.1 {
1953 proof.register_proof(expr);
1954 }
1955 hook
1956 }
1957}
1958
1959impl<T, B: Boundedness, C, I, S> Property for StreamMapFuncAlgebra<T, B, C, I, S> {
1960 type Root = StreamMapFuncAlgebra<T, B, NotProved, NotProved, S>;
1961
1962 fn make_root(_target: &mut Option<Self>) -> Self::Root {
1963 StreamMapFuncAlgebra(None, None, PhantomData)
1964 }
1965}
1966
1967/// Marker trait identifying that the commutativity property is valid for the given stream ordering.
1968///
1969/// **Definition (aggregations, `|acc: &mut A, item: T|`):** for any accumulator value
1970/// and any two items `x`, `y`, applying the closure with `x` then `y` must produce the
1971/// same final accumulator as applying it with `y` then `x`. This makes the final
1972/// aggregate independent of the (non-deterministic) arrival order; note that
1973/// *intermediate* accumulator values may still differ and must not be observed without
1974/// a non-determinism annotation.
1975#[diagnostic::on_unimplemented(
1976 message = "because the input stream has ordering `{O}`, the closure must demonstrate commutativity",
1977 label = "required for this call",
1978 note = "prove it with a `commutative = manual_proof!(/** why the order does not matter */)` annotation on the closure",
1979 note = "to intentionally process the stream by observing a non-deterministic (shuffled) order of elements, use `.assume_ordering`; this introduces non-determinism, so avoid it unless necessary"
1980)]
1981#[sealed::sealed]
1982pub trait ValidCommutativityFor<O: Ordering> {}
1983#[sealed::sealed]
1984impl ValidCommutativityFor<TotalOrder> for NotProved {}
1985#[sealed::sealed]
1986impl<O: Ordering> ValidCommutativityFor<O> for Proved {}
1987
1988/// Marker trait identifying that the idempotence property is valid for the given stream ordering.
1989///
1990/// **Definition (aggregations, `|acc: &mut A, item: T|`):** for any accumulator value
1991/// and any item `x`, applying the closure with `x` twice in a row must produce the same
1992/// final accumulator as applying it once. For `reduce`, whose accumulator is seeded with
1993/// the first element, applying the closure to an accumulator equal to `x` with the item
1994/// `x` must also leave the accumulator equal to `x`. On unordered streams, combined with
1995/// commutativity, this makes the final aggregate independent of duplicates at any
1996/// position. **Definition (`for_each`, `|item: T|`):** processing an item twice in a row
1997/// must leave the mutably-captured state in the same final value as processing it once.
1998#[diagnostic::on_unimplemented(
1999 message = "because the input stream has retries `{R}`, the closure must demonstrate idempotence",
2000 label = "required for this call",
2001 note = "prove it with an `idempotent = manual_proof!(/** why a repeat does not matter */)` annotation on the closure",
2002 note = "to intentionally process the stream by observing non-deterministic (randomly duplicated) retries, use `.assume_retries`; this introduces non-determinism, so avoid it unless necessary"
2003)]
2004#[sealed::sealed]
2005pub trait ValidIdempotenceFor<R: Retries> {}
2006#[sealed::sealed]
2007impl ValidIdempotenceFor<ExactlyOnce> for NotProved {}
2008#[sealed::sealed]
2009impl<R: Retries> ValidIdempotenceFor<R> for Proved {}
2010
2011/// Marker trait identifying that the commutativity property is valid for the given stream ordering.
2012///
2013/// A proof is required when the stream is unordered **and** the closure mutably captures
2014/// state (`WAS_MUT`). **Definition (owned-item closures, `|item: T| -> Out`, e.g. `map`
2015/// / `for_each`):** processing any two items in either order must (1) leave the
2016/// mutably-captured state (e.g. [`Singleton::by_mut`] references) in the same final
2017/// value, *and* (2) produce the same **multiset of return values**. Condition (2) is
2018/// required whenever the return value is observable (as in `map`): a closure that
2019/// emits, say, a running total is **not** commutative even if its state update is. For
2020/// `()`-returning closures (as in `for_each`), condition (2) is trivial.
2021///
2022/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
2023#[sealed::sealed]
2024#[diagnostic::on_unimplemented(
2025 message = "because the input stream has ordering `{O}`, the closure must demonstrate commutativity",
2026 label = "required for this call",
2027 note = "prove it with a `commutative = manual_proof!(/** why the order does not matter */)` annotation on the closure",
2028 note = "to intentionally process the stream by observing a non-deterministic (shuffled) order of elements, use `.assume_ordering`; this introduces non-determinism, so avoid it unless necessary"
2029)]
2030pub trait ValidMutCommutativityFor<F: FnMut(In) -> Out, In, Out, O: Ordering, const WAS_MUT: bool> {}
2031#[sealed::sealed]
2032impl<In, Out, F: FnMut(In) -> Out> ValidMutCommutativityFor<F, In, Out, TotalOrder, true>
2033 for NotProved
2034{
2035}
2036#[sealed::sealed]
2037impl<In, Out, F: Fn(In) -> Out, O: Ordering> ValidMutCommutativityFor<F, In, Out, O, false>
2038 for NotProved
2039{
2040}
2041#[sealed::sealed]
2042impl<In, Out, F: FnMut(In) -> Out, O: Ordering> ValidMutCommutativityFor<F, In, Out, O, true>
2043 for Proved
2044{
2045}
2046#[sealed::sealed]
2047impl<In, Out, F: Fn(In) -> Out, O: Ordering> ValidMutCommutativityFor<F, In, Out, O, false>
2048 for Proved
2049{
2050}
2051
2052/// Marker trait identifying that the idempotence property is valid for the given stream ordering.
2053///
2054/// A proof is required when the stream has retries (`AtLeastOnce`) **and** the closure
2055/// mutably captures state (`WAS_MUT`). **Definition (owned-item closures,
2056/// `|item: T| -> Out`, e.g. `map` / `filter_map` / `flat_map_*`):** processing an item
2057/// twice in a row must (1) leave the mutably-captured state (e.g. [`Singleton::by_mut`]
2058/// references) in the same final value as processing it once, *and* (2) return the same
2059/// value both times as when processing it once. Condition (2) is required because the
2060/// output stream inherits the retries: a retried element may re-emit its output, but must
2061/// not emit a *different* one (e.g. a closure that reports whether an element is new is
2062/// **not** idempotent even if its state update is).
2063///
2064/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
2065#[diagnostic::on_unimplemented(
2066 message = "because the input stream has retries `{R}`, the closure must demonstrate idempotence",
2067 label = "required for this call",
2068 note = "prove it with an `idempotent = manual_proof!(/** why a repeat does not matter */)` annotation on the closure",
2069 note = "to intentionally process the stream by observing non-deterministic (randomly duplicated) retries, use `.assume_retries`; this introduces non-determinism, so avoid it unless necessary"
2070)]
2071#[sealed::sealed]
2072pub trait ValidMutIdempotenceFor<F: FnMut(In) -> Out, In, Out, R: Retries, const WAS_MUT: bool> {}
2073#[sealed::sealed]
2074impl<In, Out, F: FnMut(In) -> Out> ValidMutIdempotenceFor<F, In, Out, ExactlyOnce, true>
2075 for NotProved
2076{
2077}
2078#[sealed::sealed]
2079impl<In, Out, F: Fn(In) -> Out, R: Retries> ValidMutIdempotenceFor<F, In, Out, R, false>
2080 for NotProved
2081{
2082}
2083#[sealed::sealed]
2084impl<In, Out, F: FnMut(In) -> Out, R: Retries> ValidMutIdempotenceFor<F, In, Out, R, true>
2085 for Proved
2086{
2087}
2088#[sealed::sealed]
2089impl<In, Out, F: Fn(In) -> Out, R: Retries> ValidMutIdempotenceFor<F, In, Out, R, false>
2090 for Proved
2091{
2092}
2093
2094/// Marker trait for commutativity of closures that borrow their input (`FnMut(&In) -> Out`).
2095///
2096/// A proof is required when the stream is unordered **and** the closure mutably captures
2097/// state (`WAS_MUT`). **Definition (borrowing closures, `|item: &T| -> Out`, e.g.
2098/// `filter` / `inspect`):** processing any two items in either order must (1) leave the
2099/// mutably-captured state (e.g. [`Singleton::by_mut`] references) in the same final
2100/// value, *and* (2) keep the operator's observable output identical as a multiset. For
2101/// `filter`, the outputs are the **retained elements**, so the predicate's decisions
2102/// must not depend on the processing order: a stateful predicate like a rate limiter is
2103/// **not** commutative — its budget converges either way, but *which* element passes
2104/// depends on the order. For `inspect`, the elements pass through unchanged, so only
2105/// condition (1) applies.
2106///
2107/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
2108#[sealed::sealed]
2109#[diagnostic::on_unimplemented(
2110 message = "because the input stream has ordering `{O}`, the closure must demonstrate commutativity",
2111 label = "required for this call",
2112 note = "prove it with a `commutative = manual_proof!(/** why the order does not matter */)` annotation on the closure",
2113 note = "to intentionally process the stream by observing a non-deterministic (shuffled) order of elements, use `.assume_ordering`; this introduces non-determinism, so avoid it unless necessary"
2114)]
2115pub trait ValidMutBorrowCommutativityFor<
2116 F: FnMut(&In) -> Out,
2117 In: ?Sized,
2118 Out,
2119 O: Ordering,
2120 const WAS_MUT: bool,
2121>
2122{
2123}
2124#[sealed::sealed]
2125impl<In: ?Sized, Out, F: FnMut(&In) -> Out>
2126 ValidMutBorrowCommutativityFor<F, In, Out, TotalOrder, true> for NotProved
2127{
2128}
2129#[sealed::sealed]
2130impl<In: ?Sized, Out, F: Fn(&In) -> Out, O: Ordering>
2131 ValidMutBorrowCommutativityFor<F, In, Out, O, false> for NotProved
2132{
2133}
2134#[sealed::sealed]
2135impl<In: ?Sized, Out, F: FnMut(&In) -> Out, O: Ordering>
2136 ValidMutBorrowCommutativityFor<F, In, Out, O, true> for Proved
2137{
2138}
2139#[sealed::sealed]
2140impl<In: ?Sized, Out, F: Fn(&In) -> Out, O: Ordering>
2141 ValidMutBorrowCommutativityFor<F, In, Out, O, false> for Proved
2142{
2143}
2144
2145/// Marker trait for idempotence of closures that borrow their input (`FnMut(&In) -> Out`).
2146///
2147/// A proof is required when the stream has retries (`AtLeastOnce`) **and** the closure
2148/// mutably captures state (`WAS_MUT`). **Definition (borrowing closures,
2149/// `|item: &T| -> Out`, e.g. `filter` / `partition` / `inspect`):** processing an item
2150/// twice in a row must (1) leave the mutably-captured state (e.g. [`Singleton::by_mut`]
2151/// references) in the same final value as processing it once, *and* (2) keep the
2152/// operator's observable output unchanged. For `filter` and `partition`, the predicate
2153/// must return the same decision both times as when processing the item once (for
2154/// `partition`, an element rejected on retry would appear in the *other* output). For
2155/// `inspect`, the elements pass through unchanged, so only condition (1) applies.
2156///
2157/// [`Singleton::by_mut`]: crate::live_collections::singleton::Singleton::by_mut
2158#[diagnostic::on_unimplemented(
2159 message = "because the input stream has retries `{R}`, the closure must demonstrate idempotence",
2160 label = "required for this call",
2161 note = "prove it with an `idempotent = manual_proof!(/** why a repeat does not matter */)` annotation on the closure",
2162 note = "to intentionally process the stream by observing non-deterministic (randomly duplicated) retries, use `.assume_retries`; this introduces non-determinism, so avoid it unless necessary"
2163)]
2164#[sealed::sealed]
2165pub trait ValidMutBorrowIdempotenceFor<
2166 F: FnMut(&In) -> Out,
2167 In: ?Sized,
2168 Out,
2169 R: Retries,
2170 const WAS_MUT: bool,
2171>
2172{
2173}
2174#[sealed::sealed]
2175impl<In: ?Sized, Out, F: FnMut(&In) -> Out>
2176 ValidMutBorrowIdempotenceFor<F, In, Out, ExactlyOnce, true> for NotProved
2177{
2178}
2179#[sealed::sealed]
2180impl<In: ?Sized, Out, F: Fn(&In) -> Out, R: Retries>
2181 ValidMutBorrowIdempotenceFor<F, In, Out, R, false> for NotProved
2182{
2183}
2184#[sealed::sealed]
2185impl<In: ?Sized, Out, F: FnMut(&In) -> Out, R: Retries>
2186 ValidMutBorrowIdempotenceFor<F, In, Out, R, true> for Proved
2187{
2188}
2189#[sealed::sealed]
2190impl<In: ?Sized, Out, F: Fn(&In) -> Out, R: Retries>
2191 ValidMutBorrowIdempotenceFor<F, In, Out, R, false> for Proved
2192{
2193}
2194
2195/// Marker trait identifying the boundedness of a singleton given a monotonicity property of
2196/// an aggregation on a stream.
2197#[sealed::sealed]
2198pub trait ApplyMonotoneStream<P, B2: SingletonBound> {}
2199
2200#[sealed::sealed]
2201impl<B: Boundedness> ApplyMonotoneStream<NotProved, B> for B {}
2202
2203#[sealed::sealed]
2204impl<B: Boundedness> ApplyMonotoneStream<Proved, B::StreamToMonotone> for B {}
2205
2206/// Marker trait identifying the boundedness of a singleton given a monotonicity property of
2207/// an aggregation on a keyed stream.
2208#[sealed::sealed]
2209pub trait ApplyMonotoneKeyedStream<P, B2: KeyedSingletonBound> {}
2210
2211#[sealed::sealed]
2212impl<B: Boundedness> ApplyMonotoneKeyedStream<NotProved, B::KeyedStreamToNonMonotone> for B {}
2213
2214#[sealed::sealed]
2215impl<B: Boundedness> ApplyMonotoneKeyedStream<Proved, B::KeyedStreamToMonotone> for B {}
2216
2217/// Marker trait identifying the boundedness of a singleton after a map operation,
2218/// given an order-preserving property.
2219#[sealed::sealed]
2220pub trait ApplyOrderPreservingSingleton<P, B2: SingletonBound> {}
2221
2222#[sealed::sealed]
2223impl<B: SingletonBound> ApplyOrderPreservingSingleton<NotProved, B::UnderlyingBound> for B {}
2224
2225#[sealed::sealed]
2226impl<B: SingletonBound> ApplyOrderPreservingSingleton<Proved, B> for B {}