creusot_std/logic/seq.rs
1#[cfg(creusot)]
2use crate::resolve::structural_resolve;
3use crate::{
4 ghost::Plain,
5 logic::{Mapping, ops::IndexLogic},
6 prelude::*,
7 std::ops::RangeInclusiveExt as _,
8};
9use core::{
10 marker::PhantomData,
11 ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive},
12};
13
14/// A type of sequence usable in pearlite and `ghost!` blocks.
15///
16/// # Logic
17///
18/// This type is (in particular) the logical representation of a [`Vec`]. This can be
19/// accessed via its [view][crate::model::View] (The `@` operator).
20///
21/// ```rust,creusot
22/// # use creusot_std::prelude::*;
23/// #[logic]
24/// fn get_model<T>(v: Vec<T>) -> Seq<T> {
25/// pearlite!(v@)
26/// }
27/// ```
28///
29/// # Ghost
30///
31/// Since [`Vec`] have finite capacity, this could cause some issues in ghost code:
32/// ```rust,creusot,compile_fail
33/// ghost! {
34/// let mut v = Vec::new();
35/// for _ in 0..=usize::MAX as u128 + 1 {
36/// v.push(0); // cannot fail, since we are in a ghost block
37/// }
38/// proof_assert!(v@.len() <= usize::MAX@); // by definition
39/// proof_assert!(v@.len() > usize::MAX@); // uh-oh
40/// }
41/// ```
42///
43/// This type is designed for this use-case, with no restriction on the capacity.
44#[builtin("seq.Seq.seq")]
45pub struct Seq<T>(PhantomData<T>);
46
47/// Logical definitions
48impl<T> Seq<T> {
49 /// Returns the empty sequence.
50 #[logic]
51 #[builtin("seq.Seq.empty", ascription)]
52 pub fn empty() -> Self {
53 dead
54 }
55
56 /// Create a new sequence in pearlite.
57 ///
58 /// The new sequence will be of length `n`, and will contain `mapping[i]` at index `i`.
59 ///
60 /// # Example
61 ///
62 /// ```
63 /// # use creusot_std::prelude::*;
64 /// let s = snapshot!(Seq::create(5, |i| i + 1));
65 /// proof_assert!(s.len() == 5);
66 /// proof_assert!(forall<i> 0 <= i && i < 5 ==> s[i] == i + 1);
67 /// ```
68 #[logic]
69 #[builtin("seq.Seq.create")]
70 pub fn create(n: Int, mapping: Mapping<Int, T>) -> Self {
71 let _ = n;
72 let _ = mapping;
73 dead
74 }
75
76 /// Returns the value at index `ix`.
77 ///
78 /// If `ix` is out of bounds, return `None`.
79 #[logic(open)]
80 pub fn get(self, ix: Int) -> Option<T> {
81 if 0 <= ix && ix < self.len() { Some(self.index_logic(ix)) } else { None }
82 }
83
84 /// Returns the value at index `ix`.
85 ///
86 /// If `ix` is out of bounds, the returned value is meaningless.
87 ///
88 /// You should prefer using the indexing operator `s[ix]`.
89 ///
90 /// # Example
91 ///
92 /// ```
93 /// # use creusot_std::prelude::*;
94 /// let s = snapshot!(Seq::singleton(2));
95 /// proof_assert!(s.index_logic_unsized(0) == 2);
96 /// proof_assert!(s[0] == 2); // prefer this
97 /// ```
98 #[logic]
99 #[builtin("seq.Seq.get")]
100 pub fn index_logic_unsized<'a>(self, ix: Int) -> &'a T {
101 let _ = ix;
102 dead
103 }
104
105 /// Returns the subsequence between indices `start` and `end`.
106 ///
107 /// If either `start` or `end` are out of bounds, the result is meaningless.
108 ///
109 /// # Example
110 ///
111 /// ```
112 /// # use creusot_std::prelude::*;
113 /// let subs = snapshot! {
114 /// let s: Seq<Int> = Seq::create(10, |i| i);
115 /// s.subsequence(2, 5)
116 /// };
117 /// proof_assert!(subs.len() == 3);
118 /// proof_assert!(subs[0] == 2 && subs[1] == 3 && subs[2] == 4);
119 /// ```
120 #[logic]
121 #[builtin("seq.Seq.([..])")]
122 pub fn subsequence(self, start: Int, end: Int) -> Self {
123 let _ = start;
124 let _ = end;
125 dead
126 }
127
128 /// Create a sequence containing one element.
129 ///
130 /// # Example
131 ///
132 /// ```
133 /// # use creusot_std::prelude::*;
134 /// let s = snapshot!(Seq::singleton(42));
135 /// proof_assert!(s.len() == 1);
136 /// proof_assert!(s[0] == 42);
137 /// ```
138 #[logic]
139 #[builtin("seq.Seq.singleton")]
140 pub fn singleton(value: T) -> Self {
141 let _ = value;
142 dead
143 }
144
145 /// Returns the sequence without its first element.
146 ///
147 /// If the sequence is empty, the result is meaningless.
148 ///
149 /// # Example
150 ///
151 /// ```
152 /// # use creusot_std::prelude::*;
153 /// let s = snapshot!(seq![5, 10, 15]);
154 /// proof_assert!(s.tail() == seq![10, 15]);
155 /// proof_assert!(s.tail().tail() == Seq::singleton(15));
156 /// proof_assert!(s.tail().tail().tail() == Seq::empty());
157 /// ```
158 #[logic(open)]
159 pub fn tail(self) -> Self {
160 self.subsequence(1, self.len())
161 }
162
163 /// Alias for [`Self::tail`].
164 #[logic(open)]
165 pub fn pop_front(self) -> Self {
166 self.tail()
167 }
168
169 /// Returns the sequence without its last element.
170 ///
171 /// If the sequence is empty, the result is meaningless.
172 ///
173 /// # Example
174 ///
175 /// ```
176 /// # use creusot_std::prelude::*;
177 /// let s = snapshot!(seq![5, 10, 15]);
178 /// proof_assert!(s.pop_back() == seq![5, 10]);
179 /// proof_assert!(s.pop_back().pop_back() == Seq::singleton(5));
180 /// proof_assert!(s.pop_back().pop_back().pop_back() == Seq::empty());
181 /// ```
182 #[logic(open)]
183 pub fn pop_back(self) -> Self {
184 self.subsequence(0, self.len() - 1)
185 }
186
187 /// Returns the number of elements in the sequence, also referred to as its 'length'.
188 ///
189 /// # Example
190 ///
191 /// ```
192 /// # use creusot_std::prelude::*;
193 /// #[requires(v@.len() > 0)]
194 /// fn f<T>(v: Vec<T>) { /* ... */ }
195 /// ```
196 #[logic]
197 #[builtin("seq.Seq.length")]
198 pub fn len(self) -> Int {
199 dead
200 }
201
202 /// Returns a new sequence, where the element at index `ix` has been replaced by `x`.
203 ///
204 /// If `ix` is out of bounds, the result is meaningless.
205 ///
206 /// # Example
207 ///
208 /// ```
209 /// # use creusot_std::prelude::*;
210 /// let s = snapshot!(Seq::create(2, |_| 0));
211 /// let s2 = snapshot!(s.set(1, 3));
212 /// proof_assert!(s2[0] == 0);
213 /// proof_assert!(s2[1] == 3);
214 /// ```
215 #[logic]
216 #[builtin("seq.Seq.set")]
217 pub fn set(self, ix: Int, x: T) -> Self {
218 let _ = ix;
219 let _ = x;
220 dead
221 }
222
223 /// Extensional equality
224 ///
225 /// Returns `true` if `self` and `other` have the same length, and contain the same
226 /// elements at the same indices.
227 ///
228 /// This is in fact equivalent with normal equality.
229 #[logic]
230 #[builtin("seq.Seq.(==)")]
231 pub fn ext_eq(self, other: Self) -> bool {
232 let _ = other;
233 dead
234 }
235
236 // internal wrapper to match the order of arguments of Seq.cons
237 #[doc(hidden)]
238 #[logic]
239 #[builtin("seq.Seq.cons")]
240 pub fn cons(_: T, _: Self) -> Self {
241 dead
242 }
243
244 /// Returns a new sequence, where `x` has been prepended to `self`.
245 ///
246 /// # Example
247 ///
248 /// ```
249 /// let s = snapshot!(Seq::singleton(1));
250 /// let s2 = snapshot!(s.push_front(2));
251 /// proof_assert!(s2[0] == 2);
252 /// proof_assert!(s2[1] == 1);
253 /// ```
254 #[logic(open, inline)]
255 pub fn push_front(self, x: T) -> Self {
256 Self::cons(x, self)
257 }
258
259 /// Returns a new sequence, where `x` has been appended to `self`.
260 ///
261 /// # Example
262 ///
263 /// ```
264 /// let s = snapshot!(Seq::singleton(1));
265 /// let s2 = snapshot!(s.push_back(2));
266 /// proof_assert!(s2[0] == 1);
267 /// proof_assert!(s2[1] == 2);
268 /// ```
269 #[logic]
270 #[builtin("seq.Seq.snoc")]
271 pub fn push_back(self, x: T) -> Self {
272 let _ = x;
273 dead
274 }
275
276 /// Returns a new sequence, made of the concatenation of `self` and `other`.
277 ///
278 /// See also the program function [`Seq::extend`].
279 ///
280 /// # Example
281 ///
282 /// ```
283 /// # use creusot_std::prelude::*;
284 /// let s1 = snapshot!(Seq::singleton(1));
285 /// let s2 = snapshot!(Seq::create(2, |i| i));
286 /// let s = snapshot!(s1.concat(s2));
287 /// proof_assert!(s[0] == 1);
288 /// proof_assert!(s[1] == 0);
289 /// proof_assert!(s[2] == 1);
290 /// ```
291 #[logic]
292 #[builtin("seq.Seq.(++)")]
293 pub fn concat(self, other: Self) -> Self {
294 let _ = other;
295 dead
296 }
297
298 #[logic]
299 #[ensures(result.len() == self.len())]
300 #[ensures(forall<i> 0 <= i && i < self.len() ==> result[i] == m[self[i]])]
301 #[variant(self.len())]
302 pub fn map<U>(self, m: Mapping<T, U>) -> Seq<U> {
303 if self.len() == 0 {
304 Seq::empty()
305 } else {
306 self.tail().map(m).push_front(m.get(*self.index_logic_unsized(0)))
307 }
308 }
309
310 #[logic(open)]
311 #[variant(self.len())]
312 pub fn flat_map<U>(self, other: Mapping<T, Seq<U>>) -> Seq<U> {
313 if self.len() == 0 {
314 Seq::empty()
315 } else {
316 other.get(*self.index_logic_unsized(0)).concat(self.tail().flat_map(other))
317 }
318 }
319
320 /// Returns a new sequence, which is `self` in reverse order.
321 ///
322 /// # Example
323 ///
324 /// ```
325 /// # use creusot_std::prelude::*;
326 /// let s = snapshot!(Seq::create(3, |i| i));
327 /// let s2 = snapshot!(s.reverse());
328 /// proof_assert!(s2[0] == 2);
329 /// proof_assert!(s2[1] == 1);
330 /// proof_assert!(s2[2] == 0);
331 /// ```
332 #[logic]
333 #[builtin("seq.Reverse.reverse")]
334 pub fn reverse(self) -> Self {
335 dead
336 }
337
338 /// Returns a new sequence, which is `self` with the element at the given `index` removed.
339 ///
340 /// See also the program function [`Seq::remove`].
341 ///
342 /// # Example
343 ///
344 /// ```rust,creusot
345 /// # use creusot_std::prelude::*;
346 /// let s = snapshot!(seq![7, 8, 9]);
347 /// proof_assert!(removed(*s, 1) == seq![7, 9]);
348 /// ```
349 #[logic(open)]
350 pub fn removed(self, index: Int) -> Self {
351 pearlite! { self[..index].concat(self[index+1..]) }
352 }
353
354 /// Returns `true` if `other` is a permutation of `self`.
355 #[logic(open)]
356 pub fn permutation_of(self, other: Self) -> bool {
357 self.permut(other, 0, self.len())
358 }
359
360 /// Returns `true` if:
361 /// - `self` and `other` have the same length
362 /// - `start` and `end` are in bounds (between `0` and `self.len()` included)
363 /// - Every element occurs as many times in `self[start..end]` as in `other[start..end]`.
364 #[logic]
365 #[builtin("seq.Permut.permut")]
366 pub fn permut(self, other: Self, start: Int, end: Int) -> bool {
367 let _ = other;
368 let _ = start;
369 let _ = end;
370 dead
371 }
372
373 /// Returns `true` if:
374 /// - `self` and `other` have the same length
375 /// - `i` and `j` are in bounds (between `0` and `self.len()` excluded)
376 /// - `other` is equal to `self` where the elements at `i` and `j` are swapped
377 #[logic]
378 #[builtin("seq.Permut.exchange")]
379 pub fn exchange(self, other: Self, i: Int, j: Int) -> bool {
380 let _ = other;
381 let _ = i;
382 let _ = j;
383 dead
384 }
385
386 /// Returns `true` if there is an index `i` such that `self[i] == x`.
387 #[logic(open)]
388 pub fn contains(self, x: T) -> bool {
389 pearlite! { exists<i> 0 <= i && i < self.len() && self[i] == x }
390 }
391
392 /// Returns `true` if `self` is sorted between `start` and `end`.
393 #[logic(open)]
394 pub fn sorted_range(self, start: Int, end: Int) -> bool
395 where
396 T: OrdLogic,
397 {
398 pearlite! {
399 forall<i, j> start <= i && i <= j && j < end ==> self[i] <= self[j]
400 }
401 }
402
403 /// Returns `true` if `self` is sorted.
404 #[logic(open)]
405 pub fn sorted(self) -> bool
406 where
407 T: OrdLogic,
408 {
409 self.sorted_range(0, self.len())
410 }
411
412 #[logic(open)]
413 #[ensures(forall<a: Seq<T>, b: Seq<T>, x>
414 a.concat(b).contains(x) == a.contains(x) || b.contains(x))]
415 pub fn concat_contains() {}
416}
417
418impl<T> Seq<Seq<T>> {
419 #[logic(open)]
420 #[variant(self.len())]
421 pub fn flatten(self) -> Seq<T> {
422 if self.len() == 0 {
423 Seq::empty()
424 } else {
425 self.index_logic_unsized(0).concat(self.tail().flatten())
426 }
427 }
428}
429
430impl<T> Seq<&T> {
431 /// Convert `Seq<&T>` to `Seq<T>`.
432 ///
433 /// This is simply a utility method, because `&T` is equivalent to `T` in pearlite.
434 #[logic]
435 #[builtin("identity")]
436 pub fn to_owned_seq(self) -> Seq<T> {
437 dead
438 }
439}
440
441impl<T> IndexLogic<Int> for Seq<T> {
442 type Item = T;
443
444 #[logic]
445 #[builtin("seq.Seq.get")]
446 fn index_logic(self, _: Int) -> Self::Item {
447 dead
448 }
449}
450
451impl<T> IndexLogic<Range<Int>> for Seq<T> {
452 type Item = Seq<T>;
453
454 #[logic(open, inline)]
455 fn index_logic(self, range: Range<Int>) -> Self::Item {
456 self.subsequence(range.start, range.end)
457 }
458}
459
460impl<T> IndexLogic<RangeInclusive<Int>> for Seq<T> {
461 type Item = Seq<T>;
462
463 #[logic(open, inline)]
464 fn index_logic(self, range: RangeInclusive<Int>) -> Self::Item {
465 self.subsequence(range.start_log(), range.end_log() + 1)
466 }
467}
468
469impl<T> IndexLogic<RangeFull> for Seq<T> {
470 type Item = Seq<T>;
471
472 #[logic(open, inline)]
473 fn index_logic(self, _: RangeFull) -> Self::Item {
474 self
475 }
476}
477
478impl<T> IndexLogic<RangeFrom<Int>> for Seq<T> {
479 type Item = Seq<T>;
480
481 #[logic(open, inline)]
482 fn index_logic(self, range: RangeFrom<Int>) -> Self::Item {
483 self.subsequence(range.start, self.len())
484 }
485}
486
487impl<T> IndexLogic<RangeTo<Int>> for Seq<T> {
488 type Item = Seq<T>;
489
490 #[logic(open, inline)]
491 fn index_logic(self, range: RangeTo<Int>) -> Self::Item {
492 self.subsequence(0, range.end)
493 }
494}
495
496impl<T> IndexLogic<RangeToInclusive<Int>> for Seq<T> {
497 type Item = Seq<T>;
498
499 #[logic(open, inline)]
500 fn index_logic(self, range: RangeToInclusive<Int>) -> Self::Item {
501 self.subsequence(0, range.end + 1)
502 }
503}
504
505/// Ghost definitions
506impl<T> Seq<T> {
507 /// Constructs a new, empty `Seq<T>`.
508 ///
509 /// This can only be manipulated in the ghost world, and as such is wrapped in [`Ghost`].
510 ///
511 /// # Example
512 ///
513 /// ```rust,creusot
514 /// use creusot_std::prelude::*;
515 /// let ghost_seq = Seq::<i32>::new();
516 /// proof_assert!(seq == Seq::create());
517 /// ```
518 #[trusted]
519 #[check(ghost)]
520 #[ensures(*result == Self::empty())]
521 #[allow(unreachable_code)]
522 pub fn new() -> Ghost<Self> {
523 Ghost::conjure()
524 }
525
526 /// Returns the number of elements in the sequence, also referred to as its 'length'.
527 ///
528 /// If you need to get the length in pearlite, consider using [`len`](Self::len).
529 ///
530 /// # Example
531 /// ```rust,creusot
532 /// use creusot_std::prelude::*;
533 ///
534 /// let mut s = Seq::new();
535 /// ghost! {
536 /// s.push_back_ghost(1);
537 /// s.push_back_ghost(2);
538 /// s.push_back_ghost(3);
539 /// let len = s.len_ghost();
540 /// proof_assert!(len == 3);
541 /// };
542 /// ```
543 #[trusted]
544 #[check(ghost)]
545 #[ensures(result == self.len())]
546 pub fn len_ghost(&self) -> Int {
547 panic!()
548 }
549
550 /// Returns `true` if the sequence is empty.
551 ///
552 /// # Example
553 ///
554 /// ```rust,creusot
555 /// use creusot_std::prelude::*;
556 /// #[check(ghost)]
557 /// #[requires(s.len() == 0)]
558 /// pub fn foo(mut s: Seq<i32>) {
559 /// assert!(s.is_empty_ghost());
560 /// s.push_back_ghost(1i32);
561 /// assert!(!s.is_empty_ghost());
562 /// }
563 /// ghost! {
564 /// foo(Seq::new().into_inner())
565 /// };
566 /// ```
567 #[trusted]
568 #[check(ghost)]
569 #[ensures(result == (self.len() == 0))]
570 pub fn is_empty_ghost(&self) -> bool {
571 panic!()
572 }
573
574 /// Appends an element to the front of a collection.
575 ///
576 /// # Example
577 /// ```rust,creusot
578 /// use creusot_std::prelude::*;
579 ///
580 /// let mut s = Seq::new();
581 /// ghost! {
582 /// s.push_front_ghost(1);
583 /// s.push_front_ghost(2);
584 /// s.push_front_ghost(3);
585 /// proof_assert!(s[0] == 3i32 && s[1] == 2i32 && s[2] == 1i32);
586 /// };
587 /// ```
588 #[trusted]
589 #[check(ghost)]
590 #[ensures(^self == self.push_front(x))]
591 pub fn push_front_ghost(&mut self, x: T) {
592 let _ = x;
593 panic!()
594 }
595
596 /// Appends an element to the back of a collection.
597 ///
598 /// # Example
599 /// ```rust,creusot
600 /// use creusot_std::prelude::*;
601 ///
602 /// let mut s = Seq::new();
603 /// ghost! {
604 /// s.push_back_ghost(1);
605 /// s.push_back_ghost(2);
606 /// s.push_back_ghost(3);
607 /// proof_assert!(s[0] == 1i32 && s[1] == 2i32 && s[2] == 3i32);
608 /// };
609 /// ```
610 #[trusted]
611 #[check(ghost)]
612 #[ensures(^self == self.push_back(x))]
613 pub fn push_back_ghost(&mut self, x: T) {
614 let _ = x;
615 panic!()
616 }
617
618 /// Returns a reference to an element at `index` or `None` if `index` is out of bounds.
619 ///
620 /// # Example
621 /// ```rust,creusot
622 /// use creusot_std::prelude::*;
623 ///
624 /// let mut s = Seq::new();
625 /// ghost! {
626 /// s.push_back_ghost(10);
627 /// s.push_back_ghost(40);
628 /// s.push_back_ghost(30);
629 /// let get1 = s.get_ghost(1int);
630 /// let get2 = s.get_ghost(3int);
631 /// proof_assert!(get1 == Some(&40i32));
632 /// proof_assert!(get2 == None);
633 /// };
634 /// ```
635 #[check(ghost)]
636 #[ensures(match self.get(index) {
637 None => result == None,
638 Some(v) => result == Some(&v),
639 })]
640 pub fn get_ghost(&self, index: Int) -> Option<&T> {
641 // FIXME: we can't write 0 outside of a `ghost!` block
642 if index - index <= index && index < self.len_ghost() {
643 Some(self.as_refs().extract(index))
644 } else {
645 None
646 }
647 }
648
649 /// Returns a mutable reference to an element at `index` or `None` if `index` is out of bounds.
650 ///
651 /// # Example
652 /// ```rust,creusot
653 /// use creusot_std::prelude::*;
654 ///
655 /// let mut s = Seq::new();
656 ///
657 /// ghost! {
658 /// s.push_back_ghost(0);
659 /// s.push_back_ghost(1);
660 /// s.push_back_ghost(2);
661 /// if let Some(elem) = s.get_mut_ghost(1int) {
662 /// *elem = 42;
663 /// }
664 /// proof_assert!(s[0] == 0i32 && s[1] == 42i32 && s[2] == 2i32);
665 /// };
666 /// ```
667 #[check(ghost)]
668 #[ensures(match result {
669 None => self.get(index) == None && *self == ^self,
670 Some(r) => self.get(index) == Some(*r) && ^r == (^self)[index],
671 })]
672 #[ensures(forall<i> i != index ==> (*self).get(i) == (^self).get(i))]
673 #[ensures((*self).len() == (^self).len())]
674 pub fn get_mut_ghost(&mut self, index: Int) -> Option<&mut T> {
675 // FIXME: we can't write 0 outside of a `ghost!` block
676 if index - index <= index && index < self.len_ghost() {
677 Some(self.as_muts().extract(index))
678 } else {
679 None
680 }
681 }
682
683 /// Remove an element and discard the rest of the sequence.
684 ///
685 /// This is sometimes preferable to `remove` because this avoids reasoning about subsequences.
686 #[check(ghost)]
687 #[requires(0 <= index && index < self.len())]
688 #[ensures(result == self[index])]
689 #[ensures(forall<i> 0 <= i && i < self.len() && i != index ==> resolve(self[i]))]
690 pub fn extract(mut self, index: Int) -> T {
691 proof_assert! { forall<i> index < i && i < self.len() ==> self[i] == self[index + 1..][i - index - 1] }
692 self.split_off_ghost(index).pop_front_ghost().unwrap()
693 }
694
695 /// Remove an element from a sequence.
696 ///
697 /// See also the logic function [`Seq::removed`].
698 #[check(ghost)]
699 #[requires(0 <= index && index < self.len())]
700 #[ensures(result == self[index])]
701 #[ensures(^self == (*self).removed(index))]
702 pub fn remove(&mut self, index: Int) -> T {
703 let mut right = self.split_off_ghost(index);
704 let result = right.pop_front_ghost().unwrap();
705 self.extend(right);
706 result
707 }
708
709 /// Append a sequence to another.
710 ///
711 /// See also the logic function [`Seq::concat`].
712 ///
713 /// ## Remark
714 ///
715 /// The second argument is currently restricted to sequences.
716 /// Generalizing it to arbitrary `IntoIterator` requires some missing features
717 /// to specify that the iterator terminates and that its methods are
718 /// callable in ghost code.
719 #[check(ghost)]
720 #[ensures(^self == (*self).concat(rhs))]
721 pub fn extend(&mut self, mut rhs: Self) {
722 let _final = snapshot! { self.concat(rhs) };
723 #[variant(rhs.len())]
724 #[invariant(self.concat(rhs) == *_final)]
725 while let Some(x) = rhs.pop_front_ghost() {
726 self.push_back_ghost(x)
727 }
728 }
729
730 /// Removes the last element from a vector and returns it, or `None` if it is empty.
731 ///
732 /// # Example
733 /// ```rust,creusot
734 /// use creusot_std::prelude::*;
735 ///
736 /// let mut s = Seq::new();
737 /// ghost! {
738 /// s.push_back_ghost(1);
739 /// s.push_back_ghost(2);
740 /// s.push_back_ghost(3);
741 /// let popped = s.pop_back_ghost();
742 /// proof_assert!(popped == Some(3i32));
743 /// proof_assert!(s[0] == 1i32 && s[1] == 2i32);
744 /// };
745 /// ```
746 #[trusted]
747 #[check(ghost)]
748 #[ensures(match result {
749 None => *self == Seq::empty() && *self == ^self,
750 Some(r) => *self == (^self).push_back(r)
751 })]
752 pub fn pop_back_ghost(&mut self) -> Option<T> {
753 panic!()
754 }
755
756 /// Removes the first element from a vector and returns it, or `None` if it is empty.
757 ///
758 /// # Example
759 /// ```rust,creusot
760 /// use creusot_std::prelude::*;
761 ///
762 /// let mut s = Seq::new();
763 /// ghost! {
764 /// s.push_back_ghost(1);
765 /// s.push_back_ghost(2);
766 /// s.push_back_ghost(3);
767 /// let popped = s.pop_front_ghost();
768 /// proof_assert!(popped == Some(1i32));
769 /// proof_assert!(s[0] == 2i32 && s[1] == 3i32);
770 /// };
771 /// ```
772 #[trusted]
773 #[check(ghost)]
774 #[ensures(match result {
775 None => *self == Seq::empty() && *self == ^self,
776 Some(r) => (*self).len() > 0 && r == (*self)[0] && ^self == (*self).tail()
777 })]
778 pub fn pop_front_ghost(&mut self) -> Option<T> {
779 panic!()
780 }
781
782 /// Clears the sequence, removing all values.
783 ///
784 /// # Example
785 /// ```rust,creusot
786 /// use creusot_std::prelude::*;
787 ///
788 /// let mut s = Seq::new();
789 /// ghost! {
790 /// s.push_back_ghost(1);
791 /// s.push_back_ghost(2);
792 /// s.push_back_ghost(3);
793 /// s.clear_ghost();
794 /// proof_assert!(s == Seq::empty());
795 /// };
796 /// ```
797 #[trusted]
798 #[check(ghost)]
799 #[ensures(^self == Self::empty())]
800 pub fn clear_ghost(&mut self) {}
801
802 /// Split a sequence in two at the given index.
803 #[trusted]
804 #[check(ghost)]
805 #[requires(0 <= mid && mid <= self.len())]
806 #[ensures(^self == self[..mid])]
807 #[ensures(result == self[mid..])]
808 pub fn split_off_ghost(&mut self, mid: Int) -> Self {
809 let _ = mid;
810 panic!("ghost code")
811 }
812
813 /// Borrow every element of a borrowed sequence.
814 #[trusted]
815 #[check(ghost)]
816 #[ensures(*self == result.to_owned_seq())]
817 pub fn as_refs(&self) -> Seq<&T> {
818 panic!("ghost code")
819 }
820
821 /// Mutably borrow every element of a borrowed sequence.
822 #[trusted]
823 #[check(ghost)]
824 #[ensures(result.len() == self.len())]
825 #[ensures((^self).len() == self.len())]
826 #[ensures(forall<i> 0 <= i && i < self.len() ==> *result[i] == (*self)[i])]
827 #[ensures(forall<i> 0 <= i && i < self.len() ==> ^result[i] == (^self)[i])]
828 pub fn as_muts(&mut self) -> Seq<&mut T> {
829 panic!("ghost code")
830 }
831}
832
833impl<T> core::ops::Index<Int> for Seq<T> {
834 type Output = T;
835
836 #[check(ghost)]
837 #[requires(0 <= index && index < self.len())]
838 #[ensures(*result == self[index])]
839 fn index(&self, index: Int) -> &Self::Output {
840 self.get_ghost(index).unwrap()
841 }
842}
843impl<T> core::ops::IndexMut<Int> for Seq<T> {
844 #[check(ghost)]
845 #[requires(0 <= index && index < self.len())]
846 #[ensures((*self).len() == (^self).len())]
847 #[ensures(*result == (*self)[index] && ^result == (^self)[index])]
848 #[ensures(forall<i> i != index ==> (*self).get(i) == (^self).get(i))]
849 fn index_mut(&mut self, index: Int) -> &mut Self::Output {
850 self.get_mut_ghost(index).unwrap()
851 }
852}
853
854impl<T> core::ops::Index<(Int, Int)> for Seq<T> {
855 type Output = (T, T);
856
857 #[trusted]
858 #[check(ghost)]
859 #[requires(0 <= index.0 && index.0 < self.len() && 0 <= index.1 && index.1 < self.len())]
860 #[ensures(result.0 == self[index.0] && result.1 == self[index.1])]
861 #[allow(unused_variables)]
862 fn index(&self, index: (Int, Int)) -> &Self::Output {
863 panic!()
864 }
865}
866
867impl<T> core::ops::IndexMut<(Int, Int)> for Seq<T> {
868 #[trusted]
869 #[check(ghost)]
870 #[requires(0 <= index.0 && index.0 < self.len() && 0 <= index.1 && index.1 < self.len())]
871 #[requires(index.0 != index.1)]
872 #[ensures((*result).0 == (*self)[index.0] && (*result).1 == (*self)[index.1]
873 && (^result).0 == (^self)[index.0] && (^result).1 == (^self)[index.1])]
874 #[ensures(forall<i> i != index.0 && i != index.1 ==> (*self).get(i) == (^self).get(i))]
875 #[ensures((*self).len() == (^self).len())]
876 #[allow(unused_variables)]
877 fn index_mut(&mut self, index: (Int, Int)) -> &mut Self::Output {
878 panic!()
879 }
880}
881
882// Having `Copy` guarantees that the operation is pure, even if we decide to change the definition of `Clone`.
883impl<T: Clone + Copy> Clone for Seq<T> {
884 #[trusted]
885 #[check(ghost)]
886 #[ensures(result == *self)]
887 fn clone(&self) -> Self {
888 *self
889 }
890}
891
892impl<T: Copy> Copy for Seq<T> {}
893impl<T: Plain> Plain for Seq<T> {
894 #[ensures(*result == *snap)]
895 #[check(ghost)]
896 #[allow(unused_variables)]
897 fn into_ghost(snap: Snapshot<Self>) -> Ghost<Self> {
898 ghost! {
899 let mut res = Seq::new().into_inner();
900 let len: Snapshot<Int> = snapshot!(snap.len());
901 let len = len.into_ghost().into_inner();
902 let mut i = 0int;
903 #[variant(len - i)]
904 #[invariant(i <= len)]
905 #[invariant(res.len() == i)]
906 #[invariant(forall<j> 0 <= j && j < i ==> res[j] == snap[j])]
907 while i < len {
908 let elem: Snapshot<T> = snapshot!(snap[i]);
909 res.push_back_ghost(elem.into_ghost().into_inner());
910 i = i + 1int;
911 }
912 res
913 }
914 }
915}
916
917impl<T> Invariant for Seq<T> {
918 #[logic(open, prophetic, inline)]
919 #[creusot::trusted_trivial_if_param_trivial]
920 fn invariant(self) -> bool {
921 pearlite! { forall<i> 0 <= i && i < self.len() ==> inv(self.index_logic_unsized(i)) }
922 }
923}
924
925// =========
926// Iterators
927// =========
928
929/// Iterator for sequences.
930///
931/// This provides all three variants of `IntoIter` for `Seq`:
932/// `Iter<T>`, `Iter<&T>`, `Iter<&mut T>`.
933///
934/// This is a different type from `Seq` to enable `IntoIterator for &mut Seq<T>`
935/// (if `Seq` were an iterator, that would conflict with `IntoIterator for I where I: Iterator`).
936///
937/// # Ghost code and variants
938///
939/// This iterator is only obtainable in ghost code.
940///
941/// To use it in a `for` loop, a variant must be declared:
942/// ```rust,creusot
943/// # use creusot_std::prelude::*;
944/// # #[requires(true)]
945/// fn iter_on_seq<T>(s: Seq<T>) {
946/// let len = snapshot!(s.len());
947/// #[variant(len - produced.len())]
948/// for i in s {
949/// // ...
950/// }
951/// }
952/// ```
953pub struct Iter<T>(Seq<T>);
954
955impl<T> View for Iter<T> {
956 type ViewTy = Seq<T>;
957 #[logic]
958 fn view(self) -> Self::ViewTy {
959 self.0
960 }
961}
962
963impl<T> Iterator for Iter<T> {
964 type Item = T;
965
966 #[check(ghost)]
967 #[ensures(match result {
968 None => self.completed(),
969 Some(v) => (*self).produces(Seq::singleton(v), ^self)
970 })]
971 fn next(&mut self) -> Option<T> {
972 self.0.pop_front_ghost()
973 }
974}
975
976impl<T> IteratorSpec for Iter<T> {
977 #[logic(prophetic, open)]
978 fn produces(self, visited: Seq<T>, o: Self) -> bool {
979 pearlite! { self@ == visited.concat(o@) }
980 }
981
982 #[logic(prophetic, open)]
983 fn completed(&mut self) -> bool {
984 pearlite! { self@ == Seq::empty() }
985 }
986
987 #[logic(law)]
988 #[ensures(self.produces(Seq::empty(), self))]
989 fn produces_refl(self) {}
990
991 #[logic(law)]
992 #[requires(a.produces(ab, b))]
993 #[requires(b.produces(bc, c))]
994 #[ensures(a.produces(ab.concat(bc), c))]
995 fn produces_trans(a: Self, ab: Seq<Self::Item>, b: Self, bc: Seq<Self::Item>, c: Self) {}
996}
997
998impl<T> IntoIterator for Seq<T> {
999 type Item = T;
1000 type IntoIter = Iter<T>;
1001
1002 #[check(ghost)]
1003 #[ensures(self == result@)]
1004 fn into_iter(self) -> Self::IntoIter {
1005 Iter(self)
1006 }
1007}
1008
1009impl<'a, T> IntoIterator for &'a Seq<T> {
1010 type Item = &'a T;
1011 type IntoIter = Iter<&'a T>;
1012
1013 #[check(ghost)]
1014 #[ensures(*self == result@.to_owned_seq())]
1015 fn into_iter(self) -> Self::IntoIter {
1016 Iter(self.as_refs())
1017 }
1018}
1019
1020impl<'a, T> IntoIterator for &'a mut Seq<T> {
1021 type Item = &'a mut T;
1022 type IntoIter = Iter<&'a mut T>;
1023
1024 #[check(ghost)]
1025 #[ensures(result@.len() == self.len())]
1026 #[ensures((^self).len() == self.len())]
1027 #[ensures(forall<i> 0 <= i && i < self.len() ==> *result@[i] == (*self)[i])]
1028 #[ensures(forall<i> 0 <= i && i < self.len() ==> ^result@[i] == (^self)[i])]
1029 fn into_iter(self) -> Self::IntoIter {
1030 Iter(self.as_muts())
1031 }
1032}
1033
1034impl<T> Resolve for Seq<T> {
1035 #[logic(open, prophetic)]
1036 #[creusot::trusted_trivial_if_param_trivial]
1037 fn resolve(self) -> bool {
1038 pearlite! { forall<i : Int> resolve(self.get(i)) }
1039 }
1040
1041 #[trusted]
1042 #[logic(prophetic)]
1043 #[requires(structural_resolve(self))]
1044 #[ensures(self.resolve())]
1045 fn resolve_coherence(self) {}
1046}
1047
1048impl<T> Resolve for Iter<T> {
1049 #[logic(open, prophetic, inline)]
1050 #[creusot::trusted_trivial_if_param_trivial]
1051 fn resolve(self) -> bool {
1052 pearlite! { resolve(self@) }
1053 }
1054
1055 #[logic(prophetic)]
1056 #[requires(structural_resolve(self))]
1057 #[ensures(self.resolve())]
1058 fn resolve_coherence(self) {}
1059}
1060
1061/// Properties
1062impl<T> Seq<T> {
1063 #[logic(open)]
1064 #[ensures(Seq::singleton(x).flat_map(f) == f.get(x))]
1065 pub fn flat_map_singleton<U>(x: T, f: Mapping<T, Seq<U>>) {}
1066
1067 #[logic(open)]
1068 #[ensures(self.push_back(x).flat_map(f) == self.flat_map(f).concat(f.get(x)))]
1069 #[variant(self.len())]
1070 pub fn flat_map_push_back<U>(self, x: T, f: Mapping<T, Seq<U>>) {
1071 if self.len() > 0 {
1072 Self::flat_map_push_back::<U>(self.tail(), x, f);
1073 proof_assert! { self.tail().push_back(x) == self.push_back(x).tail() }
1074 }
1075 }
1076}