Skip to main content

vstd/std_specs/
iter.rs

1use super::super::prelude::*;
2use super::super::seq::{
3    group_seq_lemmas, lemma_seq_empty, lemma_seq_subrange_index, lemma_seq_subrange_len,
4};
5use super::control_flow::{TrySpec, try_laws};
6use core::iter::{Enumerate, Filter, FromIterator, Iterator, Rev, Skip, Take, Zip};
7use core::num::NonZero;
8use core::ops::{ControlFlow, Try};
9
10// Reduce the boilerplate in the definitions below.  We have to use a macro,
11// since inside of ExIterator, we don't yet know that `self` is an Iterator.
12// We use two macros so that we can convert arguments to Rust-friendly terms
13// (e.g., by translating `final(.)` in to `verus_builtin::final_(.)` in `iter_state_preserved`
14// before doing the real work in `iter_state_preserved_internal`
15#[doc(hidden)]
16#[macro_export]
17macro_rules! iter_state_preserved_internal {
18    ($before:expr, $after:expr $(,)?) => {
19        // Dereference explicitly so method resolution uses the underlying
20        // iterator, and `final` is consumed through a dereference.
21        $crate::vstd::prelude::verus_proof_expr! {{
22            &&& (*($after)).obeys_prophetic_iter_laws() == (*($before)).obeys_prophetic_iter_laws()
23            &&& (*($before)).obeys_prophetic_iter_laws() ==>
24                (*($before)).produces().len() == (*($before)).remaining().len()
25            &&& (*($before)).obeys_prophetic_iter_laws() ==>
26                ((*($after)).decrease() is Some <==> (*($before)).decrease() is Some)
27        }}
28    };
29}
30
31#[macro_export]
32macro_rules! iter_state_preserved {
33    ($($args:tt)*) => {
34        $crate::vstd::prelude::verus_proof_macro_exprs!($crate::vstd::std_specs::iter::iter_state_preserved_internal!($($args)*))
35    };
36}
37
38#[doc(hidden)]
39pub use iter_state_preserved;
40#[doc(hidden)]
41pub use iter_state_preserved_internal;
42
43use verus as verus_skip_verusfmt;
44verus_skip_verusfmt! {
45
46/********************************************************************************
47 * The main Iterator specification
48 ********************************************************************************/
49
50#[verifier::external_trait_specification]
51#[verifier::external_trait_extension(IteratorSpec via IteratorSpecImpl)]
52pub trait ExIterator {
53    type ExternalTraitSpecificationFor: Iterator;
54
55    type Item;
56
57    /// This iterator obeys the specifications below, including those on
58    /// overridden provided methods, expressed in terms of prophetic spec functions.
59    /// Only finite iterators (i.e., those that eventually return None
60    /// and then continue to return None) or infinite iterators that
61    /// never return None should use this interface.
62    spec fn obeys_prophetic_iter_laws(&self) -> bool;
63
64    /// Sequence of all potentially returned items
65    #[verifier::prophetic]
66    spec fn remaining(&self) -> Seq<Self::Item>;
67
68    /// For each potential item in `remaining()`, does the item actually
69    /// get returned, or does the iterator get "stuck" trying to produce it,
70    /// e.g., because a client supplied a closure that diverges?
71    #[verifier::prophetic]
72    spec fn produces(&self) -> Seq<bool>;
73
74    /// Advances the iterator and returns the next value.
75    fn next(&mut self) -> (ret: Option<Self::Item>)
76        ensures
77            iter_state_preserved!(old(self), final(self)),
78            // `next` pops the head of the prophesized remaining(), or returns None
79            final(self).obeys_prophetic_iter_laws() ==>
80            ({
81                if old(self).remaining().len() > 0 {
82                    &&& final(self).remaining() == old(self).remaining().drop_first()
83                    &&& final(self).produces() == old(self).produces().drop_first()
84                    &&& ret == Some(old(self).remaining()[0])
85                    &&& old(self).produces()[0]
86                } else {
87                    &&& final(self).remaining() == old(self).remaining()
88                    &&& final(self).produces() == old(self).produces()
89                    &&& ret == None
90                }
91            }),
92            // If the iterator isn't done yet, then it successfully decreases its metric (if any)
93            final(self).obeys_prophetic_iter_laws() && old(self).remaining().len() > 0 && final(self).decrease() is Some ==>
94                decreases_to!(old(self).decrease()->0 => final(self).decrease()->0),
95    ;
96
97    /******* Mechanisms that support ergonomic `for` loops *********/
98
99    /// Value used by default for the decreases clause when no explicit decreases clause is provided
100    /// (the user can override this with an explicit decreases clause).
101    /// If there's no appropriate metric to decrease, this can return None,
102    /// and the user will have to provide an explicit decreases clause.
103    spec fn decrease(&self) -> Option<nat>;
104
105    // If we can make a useful guess as to what the i-th value will be, return it.
106    // Otherwise, return None.
107    spec fn peek(&self, index: int) -> Option<Self::Item>;
108
109    /******* Provided methods (in alphabetical order) *********/
110    // For provided method that returns a new iterator (e.g., filter, map, or zip),
111    // ideally we would write their postconditions here.  However, this requires
112    // a trait bound of `Self: IteratorSpec`, which introduces a cyclic dependency.
113    // Hence, we introduce a layer of indirection via an uninterp spec function that
114    // describes the postconditions.
115
116    fn advance_by(&mut self, n: usize) -> (ret: Result<(), NonZero<usize>>)
117        ensures
118            iter_state_preserved!(old(self), final(self)),
119            ret matches Err(e) ==> 1 <= e@ <= n,
120            ret is Ok ==> ret == Ok(()),
121            // Discarded items need not have been produced by an optimized implementation.
122            old(self).obeys_prophetic_iter_laws() ==> final(self).produces() ==
123                old(self).produces().skip(old(self).remaining().len() - final(self).remaining().len()),
124            old(self).obeys_prophetic_iter_laws() ==> match ret {
125                Ok(()) => n <= old(self).remaining().len()
126                    && final(self).remaining() == old(self).remaining()[n..],
127                Err(e) => old(self).remaining().len() < n
128                    && e@ == n - old(self).remaining().len()
129                    && final(self).remaining() == Seq::empty(),
130            },
131    ;
132
133    fn all<F>(&mut self, f: F) -> (r: bool)
134        where Self: Sized,
135            F: FnMut(Self::Item) -> bool
136        requires
137            self.obeys_prophetic_iter_laws() ==> forall |k| 0 <= k < self.remaining().len() && self.produces()[k] ==> f.requires((#[trigger] self.remaining()[k], )),
138            // without the laws, `remaining()` says nothing about the items `f` is called on
139            !self.obeys_prophetic_iter_laws() ==> forall |x: Self::Item| #[trigger] f.requires((x, )),
140        ensures
141            iter_state_preserved!(old(self), final(self)),
142            final(self).obeys_prophetic_iter_laws() ==> {
143                let num_consumed = old(self).remaining().len() - final(self).remaining().len();
144                &&& final(self).remaining().is_suffix_of(old(self).remaining())
145                &&& final(self).produces() == old(self).produces().skip(num_consumed)
146                &&& old(self).produces().take(num_consumed).all(|p: bool| p)
147            },
148            // If all returns true, then the iterator has no remaining elements,
149            // and the predicate was true for all of the original iterator's elements.
150            final(self).obeys_prophetic_iter_laws() && r ==> {
151                &&& final(self).remaining().len() == 0
152                &&& forall |i| 0 <= i < old(self).remaining().len() ==>
153                    f.ensures((#[trigger] old(self).remaining()[i],), true)
154            },
155            // If all returns false, then there is some element for which the
156            // predicate was false, and all previous elements satisfied the predicate.
157            final(self).obeys_prophetic_iter_laws() && !r ==> {
158                let idx = old(self).remaining().len() - final(self).remaining().len() - 1;
159                {
160                    // The failing element was consumed, so the remaining sequence strictly shrank
161                    &&& final(self).remaining().len() < old(self).remaining().len()
162                    &&& f.ensures((old(self).remaining()[idx],), false)
163                    &&& forall |i| 0 <= i < idx ==>
164                        f.ensures((#[trigger] old(self).remaining()[i],), true)
165                }
166            };
167
168    fn any<F>(&mut self, f: F) -> (r: bool)
169        where Self: Sized,
170            F: FnMut(Self::Item) -> bool
171        requires
172            self.obeys_prophetic_iter_laws() ==> forall |k| 0 <= k < self.remaining().len() && self.produces()[k] ==> f.requires((#[trigger] self.remaining()[k], )),
173            // without the laws, `remaining()` says nothing about the items `f` is called on
174            !self.obeys_prophetic_iter_laws() ==> forall |x: Self::Item| #[trigger] f.requires((x, )),
175        ensures
176            iter_state_preserved!(old(self), final(self)),
177            final(self).obeys_prophetic_iter_laws() ==> {
178                let num_consumed = old(self).remaining().len() - final(self).remaining().len();
179                &&& final(self).remaining().is_suffix_of(old(self).remaining())
180                &&& final(self).produces() == old(self).produces().skip(num_consumed)
181                &&& old(self).produces().take(num_consumed).all(|p: bool| p)
182            },
183            // If any returns false, then the iterator has no remaining elements,
184            // and the predicate was false for all of the original iterator's elements.
185            final(self).obeys_prophetic_iter_laws() && !r ==> {
186                &&& final(self).remaining().len() == 0
187                &&& forall |i| 0 <= i < old(self).remaining().len() ==>
188                    f.ensures((#[trigger] old(self).remaining()[i],), false)
189            },
190            // If any returns true, then there is some element that satisfied the predicate,
191            // and all previous elements did not satisfy the predicate.
192            final(self).obeys_prophetic_iter_laws() && r ==> {
193                let idx = old(self).remaining().len() - final(self).remaining().len() - 1;
194                {
195                    // The satisfying element was consumed, so the remaining sequence strictly shrank
196                    &&& final(self).remaining().len() < old(self).remaining().len()
197                    &&& f.ensures((old(self).remaining()[idx],), true)
198                    &&& forall |i| 0 <= i < idx ==>
199                        f.ensures((#[trigger] old(self).remaining()[i],), false)
200                }
201            };
202
203    fn collect<B>(self) -> (collection: B)
204        where
205            B: FromIterator<Self::Item>,
206            Self: Sized,
207        ensures
208            self.obeys_prophetic_iter_laws() ==>
209                FromIteratorSpec::from_iter_ensures(self.remaining(), self.produces(), collection),
210    ;
211
212    fn enumerate(self) -> (r: Enumerate<Self>)
213        where Self: Sized,
214        requires
215            // std's `Enumerate` keeps its count in a `usize`, so yielding more than `usize::MAX`
216            // items overflows it (panicking or wrapping around); without the laws, `remaining()`
217            // doesn't bound how many items will be yielded
218            self.obeys_prophetic_iter_laws(),
219            self.remaining().len() <= usize::MAX as int,
220        ensures
221            enumerate_post(self, r),
222    ;
223
224    fn filter<P>(self, predicate: P) -> (r: core::iter::Filter<Self, P>)
225        where
226            Self: Sized,
227            P: FnMut(&Self::Item) -> bool,
228        requires
229            // `filter`'s implementation loops over the inner iterator until the predicate accepts an element,
230            // so it needs a decreases metric to prove termination.
231            self.decrease() is Some,
232            self.obeys_prophetic_iter_laws() ==> forall |k| 0 <= k < self.remaining().len() && self.produces()[k] ==> predicate.requires((#[trigger] &self.remaining()[k], )),
233            // without the laws, `remaining()` says nothing about the items `predicate` is called on
234            !self.obeys_prophetic_iter_laws() ==> forall |x: &Self::Item| #[trigger] predicate.requires((x, )),
235        ensures
236            self.obeys_prophetic_iter_laws() ==> filter_post(self, predicate, r),
237    ;
238
239    fn find<P>(&mut self, predicate: P) -> (r: Option<Self::Item>)
240        where Self: Sized,
241            P: FnMut(&Self::Item) -> bool
242        requires
243            self.obeys_prophetic_iter_laws() ==> forall |k| 0 <= k < self.remaining().len() && self.produces()[k] ==> predicate.requires((#[trigger] &self.remaining()[k], )),
244            // without the laws, `remaining()` says nothing about the items `predicate` is called on
245            !self.obeys_prophetic_iter_laws() ==> forall |x: &Self::Item| #[trigger] predicate.requires((x, )),
246        ensures
247            iter_state_preserved!(old(self), final(self)),
248            final(self).obeys_prophetic_iter_laws() ==> final(self).produces() ==
249                old(self).produces().skip(old(self).remaining().len() - final(self).remaining().len()),
250            final(self).obeys_prophetic_iter_laws() ==> {
251                &&& final(self).remaining().is_suffix_of(old(self).remaining())
252                &&& old(self).produces().take(old(self).remaining().len() - final(self).remaining().len()).all(|p: bool| p)
253            },
254            // If find returns None, then the iterator has no remaining
255            // elements, and the predicate was false for all of the original
256            // iterator's elements.
257            final(self).obeys_prophetic_iter_laws() && r.is_none() ==> {
258                &&& final(self).remaining().len() == 0
259                &&& forall |i| 0 <= i < old(self).remaining().len() ==>
260                    predicate.ensures((#[trigger]&old(self).remaining()[i],), false)
261            },
262            // If find returns Some, then the returned value satisfies the
263            // predicate, and all previous elements did not satisfy the
264            // predicate.
265            final(self).obeys_prophetic_iter_laws() && r.is_some() ==> {
266                let idx = old(self).remaining().len() - final(self).remaining().len() - 1;
267                {
268                    &&& 0 <= final(self).remaining().len() < old(self).remaining().len()
269                    &&& predicate.ensures((&r.unwrap(),), true)
270                    &&& old(self).remaining()[idx] == r.unwrap()
271                    &&& forall |i| 0 <= i < idx ==>
272                        predicate.ensures((#[trigger] &old(self).remaining()[i],), false)
273                }
274            };
275
276    fn find_map<B, F>(&mut self, f: F) -> (r: Option<B>)
277        where Self: Sized,
278            F: FnMut(Self::Item) -> Option<B>
279        requires
280            self.obeys_prophetic_iter_laws() ==> forall |k| 0 <= k < self.remaining().len() && self.produces()[k] ==> f.requires((#[trigger] self.remaining()[k], )),
281            // without the laws, `remaining()` says nothing about the items `f` is called on
282            !self.obeys_prophetic_iter_laws() ==> forall |x: Self::Item| #[trigger] f.requires((x, )),
283        ensures
284            iter_state_preserved!(old(self), final(self)),
285
286            final(self).obeys_prophetic_iter_laws() ==> {
287                let num_consumed = old(self).remaining().len() - final(self).remaining().len();
288                &&& final(self).remaining().is_suffix_of(old(self).remaining())
289                &&& final(self).produces() == old(self).produces().skip(num_consumed)
290                &&& old(self).produces().take(num_consumed).all(|p: bool| p)
291            },
292            // If find_map returns None, then the iterator has no remaining
293            // elements, and f was None for all of the original
294            // iterator's elements.
295            final(self).obeys_prophetic_iter_laws() && r.is_none() ==> {
296                &&& final(self).remaining().len() == 0
297                &&& forall |i| 0 <= i < old(self).remaining().len() ==>
298                    f.ensures((#[trigger]old(self).remaining()[i],), None)
299            },
300            // If find_map returns Some, then the returned value satisfies f,
301            // and all previous elements did not satisfy f
302            final(self).obeys_prophetic_iter_laws() && r.is_some() ==> {
303                let idx = old(self).remaining().len() - final(self).remaining().len() - 1;
304                {
305                    &&& 0 <= final(self).remaining().len() < old(self).remaining().len()
306                    &&& f.ensures((old(self).remaining()[idx],), r)
307                    &&& forall |i| 0 <= i < idx ==>
308                        f.ensures((#[trigger] old(self).remaining()[i],), None)
309                }
310            };
311
312    fn fold<B, F>(self, init: B, f: F) -> (ret: B)
313        where Self: Sized, F: FnMut(B, Self::Item) -> B,
314        requires
315            self.obeys_prophetic_iter_laws() ==> fold_requires(self.remaining(), self.produces(), init, f),
316            // without the laws, `remaining()` says nothing about the items `f` is called on
317            !self.obeys_prophetic_iter_laws() ==> (forall |b: B, x: Self::Item| #[trigger] f.requires((b, x))),
318        ensures
319            self.obeys_prophetic_iter_laws() ==> fold_post(self.remaining(), self.produces(), init, f, ret),
320    ;
321
322    fn for_each<F>(self, f: F)
323        where Self: Sized, F: FnMut(Self::Item),
324        requires
325            self.obeys_prophetic_iter_laws() ==> forall |j: int| 0 <= j < self.remaining().len() && self.produces()[j] ==> f.requires((#[trigger] self.remaining()[j],)),
326            // without the laws, `remaining()` says nothing about the items `f` is called on
327            !self.obeys_prophetic_iter_laws() ==> (forall |x: Self::Item| #[trigger] f.requires((x, ))),
328        ensures
329            self.obeys_prophetic_iter_laws() ==> {
330                &&& self.produces().len() == self.remaining().len()
331                &&& self.produces().all(|p: bool| p)
332                &&& forall |j: int| 0 <= j < self.remaining().len() ==> f.ensures((#[trigger] self.remaining()[j],), ())
333            },
334    ;
335
336    fn map<B, F>(self, f: F) -> (r: core::iter::Map<Self, F>)
337        where
338            Self: Sized,
339            F: FnMut(Self::Item) -> B,
340        requires
341            self.obeys_prophetic_iter_laws() ==> forall |k| 0 <= k < self.remaining().len() && self.produces()[k] ==> f.requires((#[trigger] self.remaining()[k], )),
342            // without the laws, `remaining()` says nothing about the items `f` is called on
343            !self.obeys_prophetic_iter_laws() ==> forall |x: Self::Item| #[trigger] f.requires((x, )),
344        ensures
345            self.obeys_prophetic_iter_laws() ==> map_post(self, f, r),
346    ;
347
348    fn nth(&mut self, n: usize) -> (ret: Option<Self::Item>)
349        ensures
350            iter_state_preserved!(old(self), final(self)),
351            old(self).obeys_prophetic_iter_laws() ==> final(self).produces() ==
352                old(self).produces().skip(old(self).remaining().len() - final(self).remaining().len()),
353            old(self).obeys_prophetic_iter_laws() ==> (
354                if n < old(self).remaining().len() {
355                    ret == Some(old(self).remaining()[n as int])
356                        && old(self).produces()[n as int]
357                        && final(self).remaining() == old(self).remaining()[n + 1..]
358                } else {
359                    ret == None && final(self).remaining() == Seq::empty()
360                }),
361    ;
362
363    fn position<P>(&mut self, predicate: P) -> (r: Option<usize>)
364        where
365            Self: Sized,
366            P: FnMut(Self::Item) -> bool,
367        requires
368            // without the laws, `remaining()` bounds neither the count std's `position` keeps
369            // (which may overflow) nor the items `predicate` is called on
370            self.obeys_prophetic_iter_laws(),
371            self.remaining().len() <= usize::MAX as int,
372            forall |k| 0 <= k < self.remaining().len() && self.produces()[k] ==> predicate.requires((#[trigger] self.remaining()[k], )),
373        ensures
374            iter_state_preserved!(old(self), final(self)),
375            final(self).obeys_prophetic_iter_laws() ==> {
376                let num_consumed = old(self).remaining().len() - final(self).remaining().len();
377                &&& final(self).remaining().is_suffix_of(old(self).remaining())
378                &&& final(self).produces() == old(self).produces().skip(num_consumed)
379                &&& old(self).produces().take(num_consumed).all(|p: bool| p)
380            },
381            // If position returns None, then the iterator has no remaining
382            // elements, and the predicate was false for all of the original
383            // iterator's elements.
384            final(self).obeys_prophetic_iter_laws() && r.is_none() ==> {
385                &&& final(self).remaining().len() == 0
386                &&& forall |i| 0 <= i < old(self).remaining().len() ==>
387                    predicate.ensures((#[trigger] old(self).remaining()[i],), false)
388            },
389            // If position returns Some, then the returned index whose value satisfies the
390            // predicate, and all previous elements did not satisfy the predicate.
391            final(self).obeys_prophetic_iter_laws() && r.is_some() ==> {
392                let index = r.unwrap();
393                {
394                    &&& index as int == (old(self).remaining().len() - final(self).remaining().len() - 1)
395                    &&& 0 <= final(self).remaining().len() < old(self).remaining().len()
396                    &&& predicate.ensures((#[trigger] old(self).remaining()[index as int],), true)
397                    &&& forall |i| 0 <= i < index as int ==>
398                        predicate.ensures((#[trigger] old(self).remaining()[i],), false)
399                }
400            };
401
402    fn rev(self) -> (r: Rev<Self>)
403        where Self: Sized,
404        ensures
405            self.obeys_prophetic_iter_laws() ==> rev_post(self, r),
406    ;
407
408    fn size_hint(&self) -> ((lower, upper): (usize, Option<usize>))
409        ensures
410            self.obeys_prophetic_iter_laws() ==>
411                lower <= self.remaining().len() && (upper matches Some(b) ==> self.remaining().len() <= b),
412        default_ensures
413            (lower, upper) == (0usize, None),
414    ;
415
416    fn skip(self, n: usize) -> (s: Skip<Self>)
417        where Self: Sized,
418        ensures
419            self.obeys_prophetic_iter_laws() ==> skip_post(self, n, s),
420    ;
421
422    fn take(self, n: usize) -> (t: Take<Self>)
423        where Self: Sized,
424        ensures
425            self.obeys_prophetic_iter_laws() ==> take_post(self, n, t),
426    ;
427
428    fn try_fold<B, F, R>(&mut self, init: B, f: F) -> (ret: R)
429        where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>,
430        requires
431            self.obeys_prophetic_iter_laws() && try_laws::<R>() ==>
432                try_fold_requires(self.remaining(), self.produces(), init, f),
433            // without the laws, `remaining()` says nothing about the items `f` is called on
434            !(self.obeys_prophetic_iter_laws() && try_laws::<R>()) ==>
435                forall |b: B, x: Self::Item| #[trigger] f.requires((b, x)),
436        ensures
437            iter_state_preserved!(old(self), final(self)),
438            old(self).obeys_prophetic_iter_laws() ==> {
439                let num_consumed = old(self).remaining().len() - final(self).remaining().len();
440                &&& final(self).remaining().is_suffix_of(old(self).remaining())
441                &&& try_fold_post(old(self).remaining(), old(self).produces(), init, f, ret,
442                    num_consumed, final(self).produces())
443            },
444    ;
445
446    #[verifier::impls_cannot_extend_spec]
447    fn zip<U>(self, other: U) -> (r: Zip<Self, <U as IntoIterator>::IntoIter>)
448        where
449            Self: Sized,
450            U: IntoIterator,
451        ensures
452            self.obeys_prophetic_iter_laws() ==> zip_post(self, other, r),
453    ;
454}
455
456#[verifier::external_trait_specification]
457#[verifier::external_trait_extension(DoubleEndedIteratorSpec via DoubleEndedIteratorSpecImpl)]
458pub trait ExDoubleEndedIterator : Iterator {
459    type ExternalTraitSpecificationFor: DoubleEndedIterator;
460
461    // In the specs below, we write out the type parameters explicitly, rather than using the more concise form,
462    // e.g., `final(self).obeys_prophetic_iter_laws()`.  If we use the latter, then Rust elaborates it to
463    // `(&final(self)).obeys_prophetic_iter_laws()`, which means the type of the argument is `& &mut Self`,
464    // which means the type argument inferred for `obeys_prophetic_iter_laws` is `&mut Self`.
465    // This happens because of the existing Rust [trait impl](https://doc.rust-lang.org/std/iter/trait.Iterator.html#impl-Iterator-for-%26mut+I):
466    // ```
467    // impl<I> Iterator for &mut I
468    // where
469    //     I: Iterator + ?Sized,[4:21 AM]
470    // ```
471    fn next_back(&mut self) -> (ret: Option<<Self as core::iter::Iterator>::Item>)
472        ensures
473            iter_state_preserved!(old(self), final(self)),
474            // `next_back` pops the tail of the prophesized remaining(), or returns None
475            <Self as IteratorSpec>::obeys_prophetic_iter_laws(final(self)) ==>
476            ({
477                if <Self as IteratorSpec>::remaining(old(self)).len() > 0 {
478                    &&& <Self as IteratorSpec>::remaining(final(self)) == <Self as IteratorSpec>::remaining(old(self)).drop_last()
479                    &&& <Self as IteratorSpec>::produces(final(self)) == <Self as IteratorSpec>::produces(old(self)).drop_last()
480                    &&& ret == Some(<Self as IteratorSpec>::remaining(old(self)).last())
481                    &&& <Self as IteratorSpec>::produces(old(self)).last()
482                } else {
483                    &&& <Self as IteratorSpec>::remaining(final(self)) == <Self as IteratorSpec>::remaining(old(self))
484                    &&& <Self as IteratorSpec>::produces(final(self)) == <Self as IteratorSpec>::produces(old(self))
485                    &&& ret == None
486                }
487            }),
488            // If the iterator isn't done yet, then it successfully decreases its metric (if any)
489            <Self as IteratorSpec>::obeys_prophetic_iter_laws(final(self)) && <Self as IteratorSpec>::remaining(old(self)).len() > 0 && <Self as IteratorSpec>::decrease(final(self)) is Some ==>
490                <Self as IteratorSpec>::decrease(old(self))->0 > <Self as IteratorSpec>::decrease(final(self))->0,
491    ;
492
493    /******* Mechanisms that support ergonomic `for` loops *********/
494
495    // If we can make a useful guess as to what the i-th value from the back will be, return it.
496    // Otherwise, return None.
497    spec fn peek_back(&self, index: int) -> Option<Self::Item>;
498
499    /******* Provided methods (in alphabetical order) *********/
500    fn advance_back_by(&mut self, n: usize) -> (ret: Result<(), NonZero<usize>>)
501        ensures
502            iter_state_preserved!(old(self), final(self)),
503            ret matches Err(e) ==> 1 <= e@ <= n,
504            ret is Ok ==> ret == Ok(()),
505            // Discarded items need not have been produced by an optimized implementation.
506            <Self as IteratorSpec>::obeys_prophetic_iter_laws(old(self)) ==>
507                <Self as IteratorSpec>::produces(final(self)) ==
508                    <Self as IteratorSpec>::produces(old(self)).take(<Self as IteratorSpec>::remaining(final(self)).len() as int),
509            <Self as IteratorSpec>::obeys_prophetic_iter_laws(old(self)) ==> match ret {
510                Ok(()) => n <= <Self as IteratorSpec>::remaining(old(self)).len()
511                    && <Self as IteratorSpec>::remaining(final(self)) ==
512                        <Self as IteratorSpec>::remaining(old(self))[.. <Self as IteratorSpec>::remaining(old(self)).len() - n],
513                Err(e) => <Self as IteratorSpec>::remaining(old(self)).len() < n
514                    && e@ == n - <Self as IteratorSpec>::remaining(old(self)).len()
515                    && <Self as IteratorSpec>::remaining(final(self)) == Seq::empty(),
516            },
517    ;
518
519    fn nth_back(&mut self, n: usize) -> (ret: Option<Self::Item>)
520        ensures
521            iter_state_preserved!(old(self), final(self)),
522            <Self as IteratorSpec>::obeys_prophetic_iter_laws(old(self)) ==>
523                <Self as IteratorSpec>::produces(final(self)) ==
524                    <Self as IteratorSpec>::produces(old(self)).take(<Self as IteratorSpec>::remaining(final(self)).len() as int),
525            <Self as IteratorSpec>::obeys_prophetic_iter_laws(old(self)) ==> (
526                if n < <Self as IteratorSpec>::remaining(old(self)).len() {
527                    let idx = <Self as IteratorSpec>::remaining(old(self)).len() - n - 1;
528                    ret == Some(<Self as IteratorSpec>::remaining(old(self))[idx])
529                    && <Self as IteratorSpec>::produces(old(self))[idx]
530                    && <Self as IteratorSpec>::remaining(final(self)) ==
531                        <Self as IteratorSpec>::remaining(old(self))[..idx]
532                } else {
533                    ret == None && <Self as IteratorSpec>::remaining(final(self)) == Seq::empty()
534                }),
535    ;
536
537    fn rfind<P>(&mut self, predicate: P) -> (ret: Option<Self::Item>)
538        where Self: Sized, P: FnMut(&Self::Item) -> bool,
539        requires
540            <Self as IteratorSpec>::obeys_prophetic_iter_laws(self) ==>
541                forall |j: int| 0 <= j < <Self as IteratorSpec>::remaining(self).len()
542                    && <Self as IteratorSpec>::produces(self)[j] ==>
543                    predicate.requires((#[trigger] &<Self as IteratorSpec>::remaining(self)[j],)),
544            // without the laws, `remaining()` says nothing about the items `predicate` is called on
545            !<Self as IteratorSpec>::obeys_prophetic_iter_laws(self) ==>
546                forall |x: &Self::Item| #[trigger] predicate.requires((x,)),
547        ensures
548            iter_state_preserved!(old(self), final(self)),
549            <Self as IteratorSpec>::obeys_prophetic_iter_laws(old(self)) ==> {
550                let num_remaining = <Self as IteratorSpec>::remaining(final(self)).len() as int;
551                &&& <Self as IteratorSpec>::remaining(final(self)).is_prefix_of(<Self as IteratorSpec>::remaining(old(self)))
552                &&& <Self as IteratorSpec>::produces(final(self)) ==
553                    <Self as IteratorSpec>::produces(old(self)).take(num_remaining)
554                &&& <Self as IteratorSpec>::produces(old(self)).skip(num_remaining).all(|p: bool| p)
555            },
556            <Self as IteratorSpec>::obeys_prophetic_iter_laws(old(self)) ==> (
557                if ret is None {
558                    <Self as IteratorSpec>::remaining(final(self)) == Seq::empty()
559                    && forall |j: int| 0 <= j < <Self as IteratorSpec>::remaining(old(self)).len() ==>
560                        predicate.ensures((#[trigger] &<Self as IteratorSpec>::remaining(old(self))[j],), false)
561                } else {
562                    let k = <Self as IteratorSpec>::remaining(final(self)).len() as int;
563                    &&& k < <Self as IteratorSpec>::remaining(old(self)).len()
564                    &&& ret == Some(<Self as IteratorSpec>::remaining(old(self))[k])
565                    &&& predicate.ensures((&ret.unwrap(),), true)
566                    &&& <Self as IteratorSpec>::remaining(final(self)) == <Self as IteratorSpec>::remaining(old(self))[..k]
567                    &&& forall |j: int| k < j < <Self as IteratorSpec>::remaining(old(self)).len() ==>
568                        predicate.ensures((#[trigger] &<Self as IteratorSpec>::remaining(old(self))[j],), false)
569                }),
570    ;
571
572    fn rfold<B, F>(self, init: B, f: F) -> (ret: B)
573        where Self: Sized, F: FnMut(B, Self::Item) -> B,
574        requires
575            <Self as IteratorSpec>::obeys_prophetic_iter_laws(&self) ==>
576                fold_requires(<Self as IteratorSpec>::remaining(&self).reverse(), <Self as IteratorSpec>::produces(&self).reverse(), init, f),
577            // without the laws, `remaining()` says nothing about the items `f` is called on
578            !<Self as IteratorSpec>::obeys_prophetic_iter_laws(&self) ==>
579                forall |b: B, x: Self::Item| #[trigger] f.requires((b, x)),
580        ensures
581            <Self as IteratorSpec>::obeys_prophetic_iter_laws(&self) ==>
582                fold_post(<Self as IteratorSpec>::remaining(&self).reverse(), <Self as IteratorSpec>::produces(&self).reverse(), init, f, ret),
583    ;
584
585    fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> (ret: R)
586        where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>,
587        requires
588            <Self as IteratorSpec>::obeys_prophetic_iter_laws(self) && try_laws::<R>() ==>
589                try_fold_requires(<Self as IteratorSpec>::remaining(self).reverse(), <Self as IteratorSpec>::produces(self).reverse(), init, f),
590            // without the laws, `remaining()` says nothing about the items `f` is called on
591            !(<Self as IteratorSpec>::obeys_prophetic_iter_laws(self) && try_laws::<R>()) ==>
592                forall |b: B, x: Self::Item| #[trigger] f.requires((b, x)),
593        ensures
594            iter_state_preserved!(old(self), final(self)),
595            <Self as IteratorSpec>::obeys_prophetic_iter_laws(old(self)) ==> {
596                let num_consumed = <Self as IteratorSpec>::remaining(old(self)).len() - <Self as IteratorSpec>::remaining(final(self)).len();
597                &&& <Self as IteratorSpec>::remaining(final(self)).is_prefix_of(<Self as IteratorSpec>::remaining(old(self)))
598                &&& try_fold_post(<Self as IteratorSpec>::remaining(old(self)).reverse(), <Self as IteratorSpec>::produces(old(self)).reverse(), init, f, ret,
599                    num_consumed, <Self as IteratorSpec>::produces(final(self)).reverse())
600            },
601    ;
602
603}
604
605#[verifier::external_trait_specification]
606#[verifier::external_trait_extension(ExactSizeIteratorSpec via ExactSizeIteratorSpecImpl)]
607pub trait ExExactSizeIterator: Iterator {
608    type ExternalTraitSpecificationFor: ExactSizeIterator;
609
610    // An `ExactSizeIterator` can specify its length non-prophetically,
611    // i.e., without using `self.remaining().len()`.  This is a hint used by `peek_back`.
612    spec fn exact_len(&self) -> usize;
613
614    fn len(&self) -> (len: usize)
615        ensures
616            self.obeys_prophetic_iter_laws() ==> len == self.remaining().len() == self.produces().len(),
617    ;
618}
619
620/********************************************************************************
621 * Definitions for `IntoIterator` and `FromIterator``
622 ********************************************************************************/
623#[verifier::external_trait_specification]
624pub trait ExIntoIterator {
625    type ExternalTraitSpecificationFor: core::iter::IntoIterator;
626
627    type Item;
628    type IntoIter: Iterator<Item = Self::Item>;
629
630    fn into_iter(self) -> Self::IntoIter;
631}
632
633pub open spec fn iter_into_iter_spec<I: Iterator>(i: I) -> I {
634    i
635}
636
637#[verifier::when_used_as_spec(iter_into_iter_spec)]
638pub assume_specification<I: Iterator>[ <I as IntoIterator>::into_iter ](i: I) -> (r: I)
639    ensures
640        r == i,
641;
642
643#[verifier::external_trait_specification]
644#[verifier::external_trait_extension(FromIteratorSpec via FromIteratorSpecImpl)]
645pub trait ExFromIterator<A>: Sized {
646    type ExternalTraitSpecificationFor: FromIterator<A>;
647
648    // `produces` indicates whether the items at indices in `remaining` are actually computed
649    spec fn from_iter_ensures(remaining: Seq<A>, produces: Seq<bool>, s: Self) -> bool;
650
651    // from_iter may be nondeterministic, which we represent with an existential
652    #[verifier::impls_cannot_extend_spec]
653    fn from_iter<T>(iter: T) -> (s: Self)
654       where T: IntoIterator<Item = A>
655        ensures
656            exists |initial: T::IntoIter|
657                #[trigger] (T::into_iter).ensures((iter,), initial)
658                && (initial.obeys_prophetic_iter_laws() ==>
659                    Self::from_iter_ensures(initial.remaining(), initial.produces(), s)),
660    ;
661}
662
663/********************************************************************************
664 * Definitions for `&mut I`
665 ********************************************************************************/
666// Forwarding spec impl for the Rust-supplied blanket `impl<I> Iterator for &mut I`.
667// Without this, bare method-call syntax on a `i: &mut I` receiver (e.g. `i.remaining()`)
668// resolves to these (otherwise uninterpreted) functions on `&mut I` rather than on `I`,
669// silently disconnecting clients from `I`'s actual specs.
670impl <I> IteratorSpecImpl for &mut I
671    where I: Iterator {
672    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
673        <I as IteratorSpec>::obeys_prophetic_iter_laws(*self)
674    }
675
676    #[verifier::prophetic]
677    open spec fn remaining(&self) -> Seq<Self::Item> {
678        <I as IteratorSpec>::remaining(*self)
679    }
680
681    #[verifier::prophetic]
682    open spec fn produces(&self) -> Seq<bool> {
683        <I as IteratorSpec>::produces(*self)
684    }
685
686    open spec fn decrease(&self) -> Option<nat> {
687        <I as IteratorSpec>::decrease(*self)
688    }
689
690    open spec fn peek(&self, index: int) -> Option<Self::Item> {
691        <I as IteratorSpec>::peek(*self, index)
692    }
693}
694
695/********************************************************************************
696 * Definitions for `enumerate()`
697 ********************************************************************************/
698#[verifier::external_body]
699#[verifier::external_type_specification]
700#[verifier::reject_recursive_types(I)]
701pub struct ExEnumerate<I>(Enumerate<I>);
702
703// Ghost accessor for the inner iterator
704pub uninterp spec fn enumerate_iter<I>(e: Enumerate<I>) -> I;
705
706// Define Iter::enumerate's postcondition
707pub uninterp spec fn enumerate_post<I>(i: I, e: Enumerate<I>) -> bool;
708
709// The count starts at 0, and `enumerate`'s precondition bounds the number of items
710// by `usize::MAX`, so the count never overflows and `k as usize` is exact.
711pub broadcast axiom fn enumerate_postcondition<I: IteratorSpec>(i: I, r: Enumerate<I>)
712    requires
713        i.obeys_prophetic_iter_laws(),
714        #[trigger] enumerate_post(i, r),
715    ensures
716        IteratorSpec::remaining(&r).len() == i.remaining().len(),
717        forall|k: int|
718            #![trigger IteratorSpec::remaining(&r)[k]]
719            #![trigger i.remaining()[k]]
720            0 <= k < i.remaining().len() ==> IteratorSpec::remaining(&r)[k] == (k as usize, i.remaining()[k]),
721        IteratorSpec::produces(&r) == i.produces(),
722        enumerate_iter(r) == i,
723        IteratorSpec::decrease(&r) is Some == i.decrease() is Some,
724;
725
726impl <I> IteratorSpecImpl for Enumerate<I>
727    where I: Iterator {
728    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
729        enumerate_iter(*self).obeys_prophetic_iter_laws()
730    }
731
732    #[verifier::prophetic]
733    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
734
735    #[verifier::prophetic]
736    uninterp spec fn produces(&self) -> Seq<bool>;
737
738    uninterp spec fn decrease(&self) -> Option<nat>;
739
740    open spec fn peek(&self, index: int) -> Option<Self::Item> {
741        match enumerate_iter(*self).peek(index) {
742            Some(x) => Some((index as usize, x)),
743            None => None,
744        }
745    }
746}
747
748/********************************************************************************
749 * Definitions for `filter()`
750 ********************************************************************************/
751#[verifier::external_body]
752#[verifier::external_type_specification]
753#[verifier::reject_recursive_types(I)]
754#[verifier::reject_recursive_types(F)]
755pub struct ExFilter<I, F>(Filter<I, F>);
756
757// Ghost accessor for the inner iterator
758pub uninterp spec fn filter_iter<I, F>(r: Filter<I, F>) -> I;
759
760// Ghost accessor for the inner predicate
761pub uninterp spec fn filter_fun<I, F>(r: Filter<I, F>) -> F;
762
763// Ghost accessor for the decisions at every inner position.
764#[verifier::prophetic]
765pub uninterp spec fn filter_keep<I, F>(r: Filter<I, F>) -> Seq<bool>;
766
767// Define Iter::filter's postcondition
768pub uninterp spec fn filter_post<I, F>(i: I, f: F, r: Filter<I, F>) -> bool;
769
770// See examples/iterators/map_and_filter.rs for a verified version of this interface.
771// Any changes here should first be verified over there.
772pub broadcast axiom fn filter_postcondition<I, F>(i: I, f: F, r: core::iter::Filter<I, F>)
773    where
774        I: IteratorSpec,
775        F: FnMut(&I::Item) -> bool,
776    requires
777        #[trigger] filter_post(i, f, r),
778    ensures
779        {
780            let keep = filter_keep(r);
781            {
782            // Discarding a position requires producing its value and a false predicate result.
783            // A position that gets stuck is retained, with a false production flag.
784            &&& keep.len() == i.remaining().len()
785            &&& forall |j| 0 <= j < keep.len() && !(#[trigger] keep[j]) ==>
786                i.produces()[j] && f.ensures((&i.remaining()[j],), false)
787            &&& forall |j| 0 <= j < keep.len() && #[trigger] keep[j] ==> {
788                let k = i.remaining()[..j].filter_index(|idx: int| keep[idx]).len() as int;
789                IteratorSpec::produces(&r)[k] ==>
790                    i.produces()[j] && f.ensures((&i.remaining()[j],), true)
791            }
792            // Completeness: Every inner element the predicate keeps is retained and in order.
793            &&& IteratorSpec::remaining(&r) == i.remaining().filter_index(|j: int| keep[j])
794            // Expose the size bound and source positions directly for convenience.
795            &&& IteratorSpec::produces(&r).len() == IteratorSpec::remaining(&r).len()
796            &&& IteratorSpec::remaining(&r).len() <= i.remaining().len()
797            &&& forall |k| #![trigger IteratorSpec::remaining(&r)[k]] 0 <= k < IteratorSpec::remaining(&r).len() ==>
798                    exists |j| 0 <= j < i.remaining().len()
799                        && IteratorSpec::remaining(&r)[k] == #[trigger] i.remaining()[j]
800                        && keep[j]
801                        && k == i.remaining()[..j].filter_index(|idx: int| keep[idx]).len()
802                        && (IteratorSpec::produces(&r)[k] ==>
803                            i.produces()[j] && f.ensures((&i.remaining()[j],), true))
804            &&& IteratorSpec::decrease(&r) is Some == i.decrease() is Some
805            &&& filter_iter(r) == i
806            &&& filter_fun(r) == f
807            }
808        },
809;
810
811impl <I, P> IteratorSpecImpl for core::iter::Filter<I, P>
812    where
813        I: Iterator + IteratorSpec,
814        P: FnMut(&I::Item) -> bool,
815{
816    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
817        filter_iter(*self).obeys_prophetic_iter_laws()
818    }
819
820    #[verifier::prophetic]
821    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
822
823    #[verifier::prophetic]
824    uninterp spec fn produces(&self) -> Seq<bool>;
825
826    uninterp spec fn decrease(&self) -> Option<nat>;
827
828    // `filter` cannot make a useful static guess about which element will be returned at a given index,
829    // since that depends on prophetic evaluations of the predicate.
830    open spec fn peek(&self, index: int) -> Option<Self::Item> {
831        None
832    }
833}
834
835/********************************************************************************
836 * Definitions for fold and try_fold
837 ********************************************************************************/
838
839pub open spec fn fold_prefix<A, B, F: FnMut(B, A) -> B>(
840    items: Seq<A>, produces: Seq<bool>, init: B, f: F, bs: Seq<B>,
841) -> bool {
842    &&& 1 <= bs.len() <= items.len() + 1
843    &&& bs[0] == init
844    &&& produces.take(bs.len() - 1).all(|p: bool| p)
845    &&& forall |j: int| 0 <= j < bs.len() - 1 ==>
846        f.requires((bs[j], #[trigger] items[j]))
847        && f.ensures((bs[j], items[j]), bs[j + 1])
848}
849
850pub open spec fn fold_requires<A, B, F: FnMut(B, A) -> B>(
851    items: Seq<A>, produces: Seq<bool>, init: B, f: F,
852) -> bool {
853    forall |bs: Seq<B>| (
854        // If all of the intermediate computations succeed,
855        #[trigger] fold_prefix(items, produces, init, f, bs)
856            // and we produce the next item
857            && bs.len() - 1 < items.len()
858            && produces[bs.len() - 1]) ==>
859            // then we can call f on the last set of inputs
860            f.requires((bs.last(), items[bs.len() - 1]))
861}
862
863pub open spec fn fold_post<A, B, F: FnMut(B, A) -> B>(
864    items: Seq<A>, produces: Seq<bool>, init: B, f: F, result: B,
865) -> bool {
866    &&& produces.len() == items.len()
867    &&& produces.all(|p: bool| p)
868    &&& exists |bs: Seq<B>| #![trigger bs.len()] #![trigger bs.last()] fold_prefix(items, produces, init, f, bs)
869        && bs.len() == items.len() + 1 && result == bs.last()
870}
871
872pub open spec fn try_fold_prefix<A, B, R: Try<Output = B>, F: FnMut(B, A) -> R>(
873    items: Seq<A>, produces: Seq<bool>, init: B, f: F, bs: Seq<B>, results: Seq<R>,
874) -> bool {
875    &&& bs.len() == results.len() + 1
876    &&& results.len() <= items.len()
877    &&& bs[0] == init
878    &&& produces.take(results.len() as int).all(|p: bool| p)
879    &&& forall |j: int| #![trigger results[j]] #![trigger items[j]] 0 <= j < results.len() ==>
880        f.requires((bs[j], items[j]))
881        && f.ensures((bs[j], items[j]), results[j])
882        && results[j].branch_model() == ControlFlow::Continue(bs[j + 1])
883}
884
885pub open spec fn try_fold_requires<A, B, R: Try<Output = B>, F: FnMut(B, A) -> R>(
886    items: Seq<A>, produces: Seq<bool>, init: B, f: F,
887) -> bool {
888    forall |bs: Seq<B>, results: Seq<R>| (
889        // If all of the intermediate computations succeed,
890        #[trigger] try_fold_prefix(items, produces, init, f, bs, results)
891            // and we produce the next item
892            && results.len() < items.len()
893            && produces[results.len() as int]) ==>
894            // then we can call f on the last set of inputs
895            f.requires((bs.last(), items[results.len() as int]))
896}
897
898/// `consumed` counts items up to and including the failing item
899pub open spec fn try_fold_post<A, B, R: Try<Output = B>, F: FnMut(B, A) -> R>(
900    items: Seq<A>, produces: Seq<bool>, init: B, f: F, result: R, consumed: int,
901    remaining_produces: Seq<bool>,
902) -> bool {
903    &&& remaining_produces == produces.skip(consumed)
904    &&& produces.take(consumed).all(|p: bool| p)
905    &&& try_laws::<R>() ==> match result.branch_model() {
906        ControlFlow::Continue(output) =>
907            consumed == items.len()
908            && exists |bs: Seq<B>, results: Seq<R>|
909                #[trigger] try_fold_prefix(items, produces, init, f, bs, results)
910                && results.len() == items.len() && output == bs.last(),
911        ControlFlow::Break(residual) =>
912            1 <= consumed <= items.len()
913            && exists |bs: Seq<B>, results: Seq<R>, failed: R|
914                try_fold_prefix(items, produces, init, f, bs, results)
915                && results.len() == consumed - 1
916                && results.len() < items.len()
917                && {
918                    produces[results.len() as int]
919                    && f.requires((bs.last(), items[results.len() as int]))
920                    && #[trigger] f.ensures((bs.last(), items[results.len() as int]), failed)
921                    && failed.branch_model() == ControlFlow::Break(residual)
922                },
923    }
924}
925
926/********************************************************************************
927 * Definitions for `map()`
928 ********************************************************************************/
929#[verifier::external_body]
930#[verifier::external_type_specification]
931#[verifier::reject_recursive_types(I)]
932#[verifier::reject_recursive_types(F)]
933pub struct ExMap<I, F>(core::iter::Map<I, F>);
934
935// Ghost accessor for the inner iterator
936pub uninterp spec fn map_iter<I, F>(r: core::iter::Map<I, F>) -> I;
937
938// Ghost accessor for the inner function
939pub uninterp spec fn map_fun<I, F>(r: core::iter::Map<I, F>) -> F;
940
941// Define Iter::map's postcondition
942pub uninterp spec fn map_post<I, F>(i: I, f: F, r: core::iter::Map<I, F>) -> bool;
943
944// See examples/iterators/map_and_filter.rs for a verified version of this interface.
945// Any changes here should first be verified over there.
946pub broadcast axiom fn map_postcondition<I, F>(i: I, f: F, r: core::iter::Map<I, F>)
947    where
948        I: IteratorSpec,
949        F: FnMut<(I::Item,)>,
950    requires
951        #[trigger] map_post(i, f, r),
952    ensures
953        IteratorSpec::remaining(&r).len() == i.remaining().len(),
954        IteratorSpec::produces(&r).len() == IteratorSpec::remaining(&r).len(),
955        forall |k| #![trigger IteratorSpec::remaining(&r)[k]] #![trigger IteratorSpec::produces(&r)[k]]
956            0 <= k < IteratorSpec::remaining(&r).len() && IteratorSpec::produces(&r)[k] ==>
957            i.produces()[k] && f.ensures((i.remaining()[k],), IteratorSpec::remaining(&r)[k]),
958        IteratorSpec::decrease(&r) is Some == i.decrease() is Some,
959        map_iter(r) == i,
960        map_fun(r) == f,
961;
962
963impl <B, I, F> IteratorSpecImpl for core::iter::Map<I, F>
964    where
965        I: Iterator + IteratorSpec,
966        F: FnMut(I::Item) -> B,
967{
968
969    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
970        map_iter(*self).obeys_prophetic_iter_laws()
971    }
972
973    #[verifier::prophetic]
974    uninterp spec fn remaining(&self) -> Seq<B>;
975
976    #[verifier::prophetic]
977    uninterp spec fn produces(&self) -> Seq<bool>;
978
979    uninterp spec fn decrease(&self) -> Option<nat>;
980
981    open spec fn peek(&self, index: int) -> Option<B> {
982        match map_iter(*self).peek(index) {
983            Some(v) => {
984                let x = choose |x| map_fun(*self).ensures((v,), x);
985                Some(x)
986            }
987            None => None,
988        }
989    }
990}
991
992impl <B, I, F> DoubleEndedIteratorSpecImpl for core::iter::Map<I, F>
993    where I: DoubleEndedIterator + IteratorSpec,
994          F: FnMut(I::Item) -> B,
995{
996    open spec fn peek_back(&self, index: int) -> Option<B> {
997        match map_iter(*self).peek_back(index) {
998            Some(v) => {
999                let x = choose |x| map_fun(*self).ensures((v,), x);
1000                Some(x)
1001            }
1002            None => None,
1003        }
1004    }
1005}
1006
1007/********************************************************************************
1008 * Definitions for `rev()`
1009 ********************************************************************************/
1010#[verifier::external_body]
1011#[verifier::external_type_specification]
1012#[verifier::reject_recursive_types(I)]
1013pub struct ExRev<I>(Rev<I>);
1014
1015// Ghost accessor for the inner iterator
1016pub uninterp spec fn rev_iter<I>(r: Rev<I>) -> I;
1017
1018// Define Iter::rev's postcondition
1019pub uninterp spec fn rev_post<I>(i: I, r: Rev<I>) -> bool;
1020
1021pub broadcast axiom fn rev_postcondition<I: DoubleEndedIteratorSpec>(i: I, r: Rev<I>)
1022    requires
1023        #[trigger] rev_post(i, r),
1024    ensures
1025        IteratorSpec::remaining(&r) == IteratorSpec::remaining(&i).reverse(),
1026        IteratorSpec::produces(&r) == i.produces().reverse(),
1027        IteratorSpec::decrease(&r) is Some == i.decrease() is Some,
1028;
1029
1030impl <I> IteratorSpecImpl for Rev<I>
1031    where I: DoubleEndedIterator + DoubleEndedIteratorSpec {
1032    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
1033        rev_iter(*self).obeys_prophetic_iter_laws()
1034    }
1035
1036    #[verifier::prophetic]
1037    closed spec fn remaining(&self) -> Seq<Self::Item> {
1038        rev_iter(*self).remaining().reverse()
1039    }
1040
1041    #[verifier::prophetic]
1042    closed spec fn produces(&self) -> Seq<bool> {
1043        rev_iter(*self).produces().reverse()
1044    }
1045
1046    closed spec fn decrease(&self) -> Option<nat> {
1047        rev_iter(*self).decrease()
1048    }
1049
1050    open spec fn peek(&self, index: int) -> Option<Self::Item> {
1051        rev_iter(*self).peek_back(index)
1052    }
1053}
1054
1055impl <I> DoubleEndedIteratorSpecImpl for Rev<I>
1056    where I: DoubleEndedIterator + IteratorSpec {
1057
1058    open spec fn peek_back(&self, index: int) -> Option<Self::Item> {
1059        rev_iter(*self).peek(index)
1060    }
1061}
1062
1063/********************************************************************************
1064 * Definitions for `skip()`
1065 ********************************************************************************/
1066#[verifier::external_body]
1067#[verifier::external_type_specification]
1068#[verifier::reject_recursive_types(I)]
1069pub struct ExSkip<I>(Skip<I>);
1070
1071// Ghost accessor for the inner iterator
1072pub uninterp spec fn skip_iter<I>(s: Skip<I>) -> I;
1073
1074// Ghost accessor for the initial count of items to skip
1075pub uninterp spec fn skip_init_n<I>(s: Skip<I>) -> usize;
1076
1077// Define Iter::skip's postcondition
1078pub uninterp spec fn skip_post<I>(i: I, n: usize, s: Skip<I>) -> bool;
1079
1080pub broadcast axiom fn skip_postcondition<I: IteratorSpec>(i: I, n: usize, r: Skip<I>)
1081    requires
1082        i.obeys_prophetic_iter_laws(),
1083        #[trigger] skip_post(i, n, r),
1084    ensures
1085        IteratorSpec::remaining(&r) == if i.remaining().len() < n { Seq::empty() } else { i.remaining()[n..] },
1086        IteratorSpec::produces(&r) == if i.remaining().len() < n { Seq::empty() } else { i.produces()[n..] },
1087        skip_iter(r) == i,
1088        skip_init_n(r) == n,
1089        IteratorSpec::decrease(&r) is Some == i.decrease() is Some,
1090;
1091
1092impl <I> IteratorSpecImpl for Skip<I>
1093    where I: Iterator {
1094    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
1095        skip_iter(*self).obeys_prophetic_iter_laws()
1096    }
1097
1098    #[verifier::prophetic]
1099    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
1100
1101    #[verifier::prophetic]
1102    uninterp spec fn produces(&self) -> Seq<bool>;
1103
1104    uninterp spec fn decrease(&self) -> Option<nat>;
1105
1106    open spec fn peek(&self, index: int) -> Option<Self::Item> {
1107        skip_iter(*self).peek(skip_init_n(*self) + index)
1108    }
1109}
1110
1111impl <I> DoubleEndedIteratorSpecImpl for Skip<I>
1112    where I: DoubleEndedIteratorSpec + ExactSizeIteratorSpec
1113{
1114    open spec fn peek_back(&self, index: int) -> Option<Self::Item> {
1115        // Skip only drops elements from the front, so the back of the skipped
1116        // sequence coincides with the back of the inner iterator, as long as
1117        // `index` stays within the (un-skipped) remaining elements.
1118        let len = skip_iter(*self).exact_len();
1119        if len < skip_init_n(*self) || index >= len - skip_init_n(*self) {
1120            None
1121        } else {
1122            skip_iter(*self).peek_back(index)
1123        }
1124    }
1125}
1126
1127/********************************************************************************
1128 * Definitions for `take()`
1129 ********************************************************************************/
1130#[verifier::external_body]
1131#[verifier::external_type_specification]
1132#[verifier::reject_recursive_types(I)]
1133pub struct ExTake<I>(Take<I>);
1134
1135// Ghost accessor for the inner iterator
1136pub uninterp spec fn take_iter<I>(r: Take<I>) -> I;
1137
1138// Ghost accessor for the count
1139pub uninterp spec fn take_count<I>(r: Take<I>) -> usize;
1140
1141// Define Iter::take's postcondition
1142pub uninterp spec fn take_post<I>(i: I, n: usize, t: Take<I>) -> bool;
1143
1144// See examples/iterators/take.rs for a verified version of this interface.
1145// Any changes here should first be verified over there.
1146pub broadcast axiom fn take_postcondition<I: IteratorSpec>(i: I, n: usize, r: Take<I>)
1147    requires
1148        i.obeys_prophetic_iter_laws(),
1149        #[trigger] take_post(i, n, r),
1150    ensures
1151        IteratorSpec::remaining(&r) == if i.remaining().len() < n { i.remaining() } else { i.remaining()[..n] },
1152        IteratorSpec::produces(&r) == if i.remaining().len() < n { i.produces() } else { i.produces()[..n] },
1153        take_iter(r) == i,
1154        take_count(r) == n,
1155        IteratorSpec::decrease(&r) is Some,
1156;
1157
1158impl <I> IteratorSpecImpl for Take<I>
1159    where I: Iterator {
1160    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
1161        take_iter(*self).obeys_prophetic_iter_laws()
1162    }
1163
1164    #[verifier::prophetic]
1165    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
1166
1167    #[verifier::prophetic]
1168    uninterp spec fn produces(&self) -> Seq<bool>;
1169
1170    uninterp spec fn decrease(&self) -> Option<nat>;
1171
1172    open spec fn peek(&self, index: int) -> Option<Self::Item> {
1173        take_iter(*self).peek(index)
1174    }
1175}
1176
1177impl <I> DoubleEndedIteratorSpecImpl for Take<I>
1178    where I: DoubleEndedIteratorSpec + ExactSizeIteratorSpec
1179{
1180    open spec fn peek_back(&self, index: int) -> Option<Self::Item> {
1181        let len = take_iter(*self).exact_len();
1182        if len < take_count(*self) {
1183            None
1184        } else {
1185            take_iter(*self).peek_back(len - take_count(*self) - index - 1)
1186        }
1187    }
1188}
1189
1190/********************************************************************************
1191 * Definitions for `zip()`
1192 ********************************************************************************/
1193#[verifier::external_body]
1194#[verifier::external_type_specification]
1195#[verifier::reject_recursive_types(A)]
1196#[verifier::reject_recursive_types(B)]
1197pub struct ExZip<A, B>(Zip<A, B>);
1198
1199// Ghost accessor for the first inner iterator
1200pub uninterp spec fn zip_iter_fst<A, B>(z: Zip<A, B>) -> A;
1201
1202// Ghost accessor for the second inner iterator
1203pub uninterp spec fn zip_iter_snd<A, B>(z: Zip<A, B>) -> B;
1204
1205impl<A, B> IteratorSpecImpl for Zip<A, B>
1206    where A: Iterator + IteratorSpec, B: Iterator + IteratorSpec
1207{
1208    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
1209        &&& zip_iter_fst(*self).obeys_prophetic_iter_laws()
1210        &&& zip_iter_snd(*self).obeys_prophetic_iter_laws()
1211    }
1212
1213    #[verifier::prophetic]
1214    closed spec fn remaining(&self) -> Seq<Self::Item> {
1215        zip_iter_fst(*self).remaining().zip_truncate(zip_iter_snd(*self).remaining())
1216    }
1217
1218    #[verifier::prophetic]
1219    closed spec fn produces(&self) -> Seq<bool> {
1220        zip_iter_fst(*self).produces().zip_truncate(zip_iter_snd(*self).produces()).map_values(|p: (bool, bool)| p.0 && p.1)
1221    }
1222
1223    closed spec fn decrease(&self) -> Option<nat> {
1224        match (zip_iter_fst(*self).decrease(), zip_iter_snd(*self).decrease()) {
1225            (Some(a), Some(b)) => if a <= b { Some(a) } else { Some(b) },
1226            (Some(a), None) => Some(a),
1227            (None, Some(b)) => Some(b),
1228            (None, None) => None,
1229        }
1230    }
1231
1232    open spec fn peek(&self, index: int) -> Option<Self::Item> {
1233        match (zip_iter_fst(*self).peek(index), zip_iter_snd(*self).peek(index)) {
1234            (Some(a), Some(b)) => Some((a, b)),
1235            _ => None,
1236        }
1237    }
1238}
1239
1240// Define Iter::zip's postcondition
1241pub uninterp spec fn zip_post<I, U, Z>(i: I, other: U, r: Z) -> bool;
1242
1243pub broadcast axiom fn zip_postcondition<I, U>(i: I, other: U, r: Zip<I, <U as IntoIterator>::IntoIter>)
1244    where
1245            I: Sized + IteratorSpec,
1246            U: IntoIterator, //Spec,
1247    requires
1248        i.obeys_prophetic_iter_laws(),
1249        #[trigger] zip_post(i, other, r),
1250    ensures
1251        (U::into_iter).ensures((other,), zip_iter_snd(r)),
1252        zip_iter_fst(r) == i,
1253        IteratorSpec::remaining(&r) == i.remaining().zip_truncate(zip_iter_snd(r).remaining()),
1254        IteratorSpec::produces(&r) == i.produces().zip_truncate(zip_iter_snd(r).produces()).map_values(|p: (bool, bool)| p.0 && p.1),
1255        IteratorSpec::decrease(&r) is Some == (i.decrease() is Some || zip_iter_snd(r).decrease() is Some),
1256;
1257
1258/********************************************************************************
1259 * Defines a convenient wrapper type that bundles state and invariants needed
1260 * for ergonomic for-loop support.
1261 ********************************************************************************/
1262
1263pub struct VerusForLoopWrapper<I: Iterator> {
1264    pub index: Ghost<int>,
1265    pub snapshot: Ghost<I>,
1266    pub iter: I,
1267    pub history: Ghost<Seq<I::Item>>,
1268}
1269
1270impl <I: Iterator> VerusForLoopWrapper<I> {
1271    #[verifier::prophetic]
1272    pub open spec fn seq(self) -> Seq<I::Item> {
1273        self.snapshot@.remaining()
1274    }
1275
1276    // Keep the interface for history and seq the same
1277    pub open spec fn history(self) -> Seq<I::Item> {
1278        self.history@
1279    }
1280
1281    pub open spec fn index(self) -> int {
1282        self.index@
1283    }
1284
1285    /// These properties help maintain the properties in wf,
1286    /// but they don't need to be exposed to the client
1287    #[verifier::prophetic]
1288    pub closed spec fn wf_inner(self) -> bool {
1289        &&& self.iter.remaining().len() == self.seq().len() - self.index()
1290        &&& forall |i| 0 <= i < self.iter.remaining().len() ==> #[trigger] self.iter.remaining()[i] == self.seq()[self.index() + i]
1291        &&& self.index() <= self.snapshot@.produces().len()
1292        &&& self.iter.produces() == self.snapshot@.produces().skip(self.index())
1293    }
1294
1295    /// These properties are needed for the client code to verify
1296    #[verifier::prophetic]
1297    pub open spec fn wf(self) -> bool {
1298        &&& 0 <= self.index() <= self.seq().len()
1299        &&& self.wf_inner()
1300        &&& self.iter.obeys_prophetic_iter_laws() ==> {
1301                &&& self.history@.len() == self.index()
1302                &&& forall |i| 0 <= i < self.index() ==> #[trigger] self.history@[i] == self.seq()[i]
1303                &&& self.snapshot@.produces().take(self.index()).all(|p: bool| p)
1304            }
1305    }
1306
1307    /// Bundle the real iterator with its ghost state and loop invariants
1308    pub fn new(iter: I) -> (s: Self)
1309        ensures
1310            s.index == 0,
1311            s.snapshot == iter,
1312            s.iter == iter,
1313            s.history@ == Seq::<I::Item>::empty(),
1314            s.wf(),
1315    {
1316        broadcast use group_seq_lemmas;
1317        proof {
1318            assert(iter.produces().skip(0) =~= iter.produces());
1319        }
1320        VerusForLoopWrapper {
1321            index: Ghost(0),
1322            snapshot: Ghost(iter),
1323            iter,
1324            history: Ghost(Seq::empty()),
1325        }
1326    }
1327
1328    /// Advance the underlying (real) iterator and prove
1329    /// that the loop invariants are preserved.
1330    pub fn next(&mut self) -> (ret: Option<I::Item>)
1331        requires
1332            old(self).wf(),
1333        ensures
1334            final(self).seq() == old(self).seq(),
1335            final(self).index() == old(self).index() + if ret is Some { 1int } else { 0 },
1336            final(self).snapshot == old(self).snapshot,
1337            final(self).iter.obeys_prophetic_iter_laws() ==> final(self).wf(),
1338            final(self).iter.obeys_prophetic_iter_laws() && ret is None ==>
1339                final(self).index() == final(self).seq().len()
1340                    && final(self).snapshot@.produces().all(|p: bool| p),
1341            final(self).iter.obeys_prophetic_iter_laws() ==> (ret matches Some(r) ==>
1342                r == old(self).seq()[old(self).index()] && old(self).snapshot@.produces()[old(self).index()]),
1343            // History updates always hold
1344            ret matches Some(i) ==> final(self).history@ == old(self).history@.push(i),
1345            ret is None ==> final(self).history@ == old(self).history@,
1346            // All of the standard Iterator::next guarantees still hold
1347            exists |m: &mut I| #![auto] (I::next).ensures((m,), ret) && *m == old(self).iter && *final(m) == final(self).iter,
1348    {
1349        let ghost old_history = self.history@;
1350        let ret = self.iter.next();
1351        if ret.is_some() {
1352            self.history = Ghost(old_history.push(ret->0));
1353        }
1354        proof {
1355            broadcast use group_seq_lemmas;
1356            if ret.is_some() {
1357                self.index@ = self.index@ + 1;
1358            }
1359            if self.iter.obeys_prophetic_iter_laws() {
1360                assert(self.snapshot@.produces().len() == self.seq().len());
1361                assert(self.iter.produces() =~= self.snapshot@.produces().skip(self.index()));
1362                if ret.is_none() {
1363                    assert(self.snapshot@.produces().take(self.index()) =~= self.snapshot@.produces());
1364                }
1365            }
1366        }
1367        ret
1368    }
1369}
1370
1371// Artificial function used when we desguar a for loop.
1372// It helps bring the definition of `peek` into scope,
1373// resulting in better automation for some proofs.
1374pub open spec fn trigger_peek_implications<T>(x: T) -> bool { true }
1375
1376/********************************************************************************
1377 * Definitions for the Step trait
1378 ********************************************************************************/
1379#[verifier::external_trait_specification]
1380#[verifier::external_trait_extension(StepSpec via StepSpecImpl)]
1381pub trait ExIterStep: Clone + PartialOrd + Sized {
1382    type ExternalTraitSpecificationFor: core::iter::Step;
1383
1384    // REVIEW: it would be nice to be able to use SpecOrd::spec_lt (not yet supported)
1385    // TODO: We should now be able to use cmp_spec or partial_cmp_spec here.
1386    spec fn spec_is_lt(self, other: Self) -> bool;
1387
1388    spec fn spec_steps_between(self, end: Self) -> Option<usize>;
1389
1390    spec fn spec_steps_between_int(self, end: Self) -> int;
1391
1392    spec fn spec_forward_checked(self, count: usize) -> Option<Self>;
1393
1394    spec fn spec_forward_checked_int(self, count: int) -> Option<Self>;
1395
1396    spec fn spec_backward_checked(self, count: usize) -> Option<Self>;
1397
1398    spec fn spec_backward_checked_int(self, count: int) -> Option<Self>;
1399}
1400
1401
1402/********************************************************************************
1403 * Collect our broadcast definitions
1404 ********************************************************************************/
1405
1406pub broadcast group group_iter_axioms {
1407    enumerate_postcondition,
1408    rev_postcondition,
1409    zip_postcondition,
1410    filter_postcondition,
1411    take_postcondition,
1412    skip_postcondition,
1413    map_postcondition,
1414}
1415
1416} // verus!