From c3cc90cef152cccfd951699df88c350851c9ec66 Mon Sep 17 00:00:00 2001 From: Emre Kaplaner Date: Mon, 30 Nov 2026 10:54:44 -0800 Subject: [PATCH 1/4] Challenge 24: Unbounded verification of Vec Part 2 (IntoIter, ExtractIf, spec_*) --- library/alloc/src/lib.rs | 1 + library/alloc/src/vec/extract_if.rs | 4 + library/alloc/src/vec/into_iter.rs | 164 +- library/alloc/src/vec/mod.rs | 3 + library/alloc/src/vec/verify_extract_if.rs | 508 +++ library/alloc/src/vec/verify_iter_spec.rs | 3228 +++++++++++++++++ verifast-proofs/README.md | 1 + .../alloc/vec/extract_if.rs/README.md | 103 + .../vec/extract_if.rs/original/extract_if.rs | 160 + .../alloc/vec/extract_if.rs/original/lib.rs | 64 + .../alloc/vec/extract_if.rs/update.sh | 10 + .../vec/extract_if.rs/verified/extract_if.rs | 721 ++++ .../alloc/vec/extract_if.rs/verified/lib.rs | 302 ++ .../alloc/vec/extract_if.rs/verify.sh | 10 + verifast-proofs/check-verifast-proofs.sh | 5 + verifast-proofs/patch-verifast-proofs.sh | 3 + 16 files changed, 5286 insertions(+), 1 deletion(-) create mode 100644 library/alloc/src/vec/verify_extract_if.rs create mode 100644 library/alloc/src/vec/verify_iter_spec.rs create mode 100644 verifast-proofs/alloc/vec/extract_if.rs/README.md create mode 100644 verifast-proofs/alloc/vec/extract_if.rs/original/extract_if.rs create mode 100644 verifast-proofs/alloc/vec/extract_if.rs/original/lib.rs create mode 100644 verifast-proofs/alloc/vec/extract_if.rs/update.sh create mode 100644 verifast-proofs/alloc/vec/extract_if.rs/verified/extract_if.rs create mode 100644 verifast-proofs/alloc/vec/extract_if.rs/verified/lib.rs create mode 100644 verifast-proofs/alloc/vec/extract_if.rs/verify.sh diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index b22b051c9697a..e26198c487306 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -214,6 +214,7 @@ #![feature(min_specialization)] #![feature(multiple_supertrait_upcastable)] #![feature(negative_impls)] +#![feature(proc_macro_hygiene)] #![feature(rustc_attrs)] #![feature(slice_internals)] #![feature(staged_api)] diff --git a/library/alloc/src/vec/extract_if.rs b/library/alloc/src/vec/extract_if.rs index 4396798067942..7faa2a776fc8b 100644 --- a/library/alloc/src/vec/extract_if.rs +++ b/library/alloc/src/vec/extract_if.rs @@ -154,3 +154,7 @@ where .finish_non_exhaustive() } } + +#[cfg(all(kani, not(no_global_oom_handling)))] +#[path = "verify_extract_if.rs"] +mod verify; diff --git a/library/alloc/src/vec/into_iter.rs b/library/alloc/src/vec/into_iter.rs index 176a394908ac5..92ba8c5f00601 100644 --- a/library/alloc/src/vec/into_iter.rs +++ b/library/alloc/src/vec/into_iter.rs @@ -13,7 +13,7 @@ use core::panic::UnwindSafe; use core::ptr::{self, NonNull}; use core::{array, fmt, slice}; -use safety::requires; +use safety::{loop_invariant, requires}; #[cfg(not(no_global_oom_handling))] use super::AsVecIntoIter; @@ -265,6 +265,128 @@ unsafe impl Send for IntoIter {} #[stable(feature = "rust1", since = "1.0.0")] unsafe impl Sync for IntoIter {} +// Loop-invariant predicates for `IntoIter::fold` and `IntoIter::try_fold`. +// Marked `#[inline(always)]` and written with pure intrinsics rather than +// method calls (e.g. `NonNull::as_ptr` / `pointer::addr`) so CBMC evaluates +// them inline as side-effect-free loop-contract expressions +// (https://github.com/model-checking/kani/issues/4796). +// `self.alloc` is omitted because `ManuallyDrop` is not `Copy`; harnesses +// instantiate `A = TrackAlloc`, a ZST carrying no runtime state. +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, and `usize` have identical layout (thin pointer width); + // these casts are side-effect-free re-interpretations for CBMC's loop-invariant evaluator. + let (ptr_p, eptr_p, buf_p, ebuf_p, ptr_a, eptr_a, end_a, eend_a): ( + *const T, + *const T, + *const T, + *const T, + usize, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + core::intrinsics::transmute_unchecked(entry_end), + ) + }; + ptr_p == eptr_p + && buf_p == ebuf_p + && cap == entry_cap + && core::intrinsics::wrapping_sub(end_a, ptr_a) + <= core::intrinsics::wrapping_sub(eend_a, eptr_a) +} + +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_non_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, `*const u8`, and `usize` have identical thin-pointer + // layout; used to avoid method calls in CBMC loop-contract predicates (kani#4796). + let (buf_p, ebuf_p, ptr_p, eptr_u8, ptr_a, eptr_a, end_a): ( + *const T, + *const T, + *const T, + *const u8, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + ) + }; + let diff = core::intrinsics::wrapping_sub(ptr_a, eptr_a); + let span = core::intrinsics::wrapping_sub(end_a, eptr_a); + let sz = core::mem::size_of::(); + let aligned = if const { core::mem::size_of::().is_power_of_two() } { + (diff & core::intrinsics::wrapping_sub(sz, 1)) == 0 + } else { + // Exact divisibility `diff % sz == 0` for any non-power-of-two `sz > 0` without a + // 64-bit integer division circuit: write `sz = odd * 2^tz` and compute the modular + // multiplicative inverse `odd_inv` (`odd * odd_inv == 1 mod 2^BITS`) at const time. + // Then `sz | diff` iff `2^tz | diff` and `(diff >> tz) * odd_inv <= usize::MAX / sz`. + let (tz, odd_inv, max_q) = const { + let s = core::mem::size_of::(); + if s == 0 { + (0u32, 1usize, 0usize) + } else { + let tz = s.trailing_zeros(); + let odd = s >> tz; + let mut inv: usize = 1; + let mut i = 0; + while i < 6 { + inv = inv.wrapping_mul(2usize.wrapping_sub(odd.wrapping_mul(inv))); + i += 1; + } + assert!(odd.wrapping_mul(inv) == 1); + (tz, inv, usize::MAX / s) + } + }; + let low_mask = core::intrinsics::wrapping_sub(1usize << tz, 1); + (diff & low_mask) == 0 && (diff >> tz).wrapping_mul(odd_inv) <= max_q + }; + // SAFETY: `arith_offset` is wrapping (non-UB) pointer arithmetic; short-circuiting after + // `diff <= span && aligned` additionally guarantees `diff` stays within `[entry_ptr, end]`. + buf_p == ebuf_p + && cap == entry_cap + && end == entry_end + && diff <= span + && aligned + && ptr_p == unsafe { core::intrinsics::arith_offset(eptr_u8, diff as isize) as *const T } +} + #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for IntoIter { type Item = T; @@ -374,6 +496,16 @@ impl Iterator for IntoIter { F: FnMut(B, Self::Item) -> B, { if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] while self.ptr.as_ptr() != self.end.cast_mut() { // SAFETY: we just checked that `self.ptr` is in bounds. let tmp = unsafe { self.ptr.read() }; @@ -383,6 +515,16 @@ impl Iterator for IntoIter { } } else { // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] while self.ptr != non_null!(self.end, T) { // SAFETY: we just checked that `self.ptr` is in bounds. let tmp = unsafe { self.ptr.read() }; @@ -409,6 +551,16 @@ impl Iterator for IntoIter { R: core::ops::Try, { if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] while self.ptr.as_ptr() != self.end.cast_mut() { // SAFETY: we just checked that `self.ptr` is in bounds. let tmp = unsafe { self.ptr.read() }; @@ -418,6 +570,16 @@ impl Iterator for IntoIter { } } else { // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] while self.ptr != non_null!(self.end, T) { // SAFETY: we just checked that `self.ptr` is in bounds. let tmp = unsafe { self.ptr.read() }; diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 1bdec5a74c9e6..715bd12a87ca0 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -165,6 +165,9 @@ use self::spec_from_elem::SpecFromElem; #[cfg(not(no_global_oom_handling))] mod spec_from_elem; +#[cfg(all(kani, not(no_global_oom_handling)))] +mod verify_iter_spec; + #[cfg(not(no_global_oom_handling))] use self::set_len_on_drop::SetLenOnDrop; diff --git a/library/alloc/src/vec/verify_extract_if.rs b/library/alloc/src/vec/verify_extract_if.rs new file mode 100644 index 0000000000000..5a1b6e890ebf2 --- /dev/null +++ b/library/alloc/src/vec/verify_extract_if.rs @@ -0,0 +1,508 @@ +use core::kani; +use core::mem::{self, SizedTypeProperties}; +use core::num::NonZero; + +use super::{ExtractIf, Vec}; +use crate::vec::verify_iter_spec::{ + AlignedZst, DropNiche, DropTracker, MAX_ALLOCATION_BYTES, OverAligned, PaddedNiche, Shape, + any_up_to, down_from, drops, finish, mark, markers_for, reset_drops, tag_matches, witness_ok, +}; + +/// Inductive-step verification of `ExtractIf::next` from an arbitrary reachable +/// state `del <= idx <= end <= old_len <= cap` (symbolic up to +/// `MAX_ALLOCATION_BYTES`), with zero `#[kani::unwind]`. +/// +/// Only the witness/accessed slots (`idx`, `idx + 1`, and symbolic frame +/// indices `j`/`k`) are initialized via typed `ptr::write` (`mark`), leaving +/// the moved-out hole `[idx - del..idx]`, spare capacity `[old_len..cap]`, and +/// all struct padding bytes genuinely uninitialized (while avoiding CBMC's +/// symbolic-length `memset` witness OOM `kani#4905`); full-buffer separation +/// logic ownership over `[0..idx - del]` and `[idx..old_len]` is proved +/// polymorphically in VeriFast. +/// +/// Unbounded polymorphic safety across all ` bool, A: Allocator>` +/// and arbitrary iteration counts is additionally proved in VeriFast under +/// `verifast-proofs/alloc/vec/extract_if.rs/` (`verifast` + `refinement-checker`), +/// complementing this Kani inductive-step + concrete-layout harness (a mechanized +/// Kani `#[loop_invariant]` on `ExtractIf::next` is blocked by `kani#5071`). +fn check_extract_if_next(use_up_to: bool, check_frame: bool) { + let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; + let (fill, m1, m2) = markers_for::(); + let m1_mut = T::any_distinct_three(fill, m1, m2); + let m2_mut = T::any_distinct_three(fill, m1_mut, m2); + let (mut v, actual_cap) = if T::IS_ZST { + (Vec::::new(), usize::MAX) + } else { + let cap = pick(MAX_ALLOCATION_BYTES / mem::size_of::()); + if cap == 0 { + (Vec::::new(), 0) + } else { + let layout = crate::alloc::Layout::array::(cap).unwrap(); + // SAFETY: `cap > 0` and `size_of::() > 0`. + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + // SAFETY: `p` was allocated with `layout`; length 0 matches `ExtractIf::new`. + (unsafe { Vec::from_raw_parts(p.cast::(), 0, cap) }, cap) + } + }; + let small = witness_ok::(actual_cap); + let old_len = pick(actual_cap); + let end = pick(old_len); + let idx = pick(end); + let del = pick(idx); + let retained_len = idx - del; + // Universal quantification over every untouched slot in BOTH `[0..retained_len)` + // and `[idx2..old_len)` via a single symbolic branch `check_prefix`, halving + // CBMC's symbolic-index array write/read depth without losing any coverage. + let check_prefix: bool = if check_frame { kani::any() } else { false }; + let j = + if check_frame && check_prefix && retained_len > 0 { pick(retained_len - 1) } else { 0 }; + let k = if check_frame && !check_prefix && idx < old_len { + idx + pick(old_len - idx - 1) + } else { + 0 + }; + if !T::IS_ZST && actual_cap > 0 { + let base = v.as_mut_ptr(); + // SAFETY: Every marked index is strictly `< old_len <= actual_cap` and + // lies in `[0..retained_len]` or `[idx..old_len]`. Typed `mark` writes + // leave padding bytes, the hole `[retained_len..idx]`, and spare + // capacity `[old_len..actual_cap]` genuinely uninitialized (`v.len() == 0` + // throughout `ExtractIf::next` and `ExtractIf::new`, avoiding CBMC's + // symbolic-length `memset` witness OOM `kani#4905`). + unsafe { + if idx < end { + mark(base.add(idx), m1); + } + if end - idx > 1 { + mark(base.add(idx + 1), m2); + } + if check_frame { + if check_prefix { + if retained_len > 0 { + mark(base.add(j), fill); + } + } else if idx < old_len + && !(k == idx && idx < end) + && !(k == idx + 1 && end - idx > 1) + { + mark(base.add(k), fill); + } + } + } + } + // `v.len()` is already 0, matching `ExtractIf::new`. + let first: bool = kani::any(); + let mut first_call = true; + let mut pred_ok = true; + let pred = |x: &mut T| -> bool { + let is_first = mem::replace(&mut first_call, false); + let (expect, mutate_to) = if is_first { (m1, m1_mut) } else { (m2, m2_mut) }; + if !T::IS_ZST { + pred_ok &= x.matches_tag(expect); + // Exercise typed in-place mutation through `&mut T` (preserving + // uninitialized padding on padded types). + // SAFETY: `x` is a valid `&mut T`. + unsafe { mark(x as *mut T, mutate_to) }; + } + if is_first { first } else { true } + }; + reset_drops(); + let mut ei = ExtractIf { vec: &mut v, idx, end, del, old_len, pred }; + let r = ei.next(); + let (idx2, end2, del2, old_len2) = (ei.idx, ei.end, ei.del, ei.old_len); + mem::forget(ei); + // Hoist all conditional assertions to a single top-level `assert!(ok)` so + // Kani's `--assertion-reach-checks` never picks a `cap ~ 2^50` trace inside + // `cap > 0` branches (`kani#4905`). + let mut ok = pred_ok + && drops() == 0 + && end2 == end + && old_len2 == old_len + && v.len() == 0 + && v.capacity() == actual_cap + && del2 <= idx2 + && idx2 <= end; + let shifted = idx < end && !first; + match &r { + None => { + ok &= idx2 == end && del2 == del && (idx == end || (shifted && end - idx == 1)); + } + Some(x) => { + let (want_idx, want_tag) = if shifted { (idx + 2, m2_mut) } else { (idx + 1, m1_mut) }; + ok &= del2 == del + 1 && idx2 == want_idx; + if !T::IS_ZST { + ok &= x.matches_tag(want_tag); + } + } + } + if !T::IS_ZST { + if shifted { + if del > 0 { + // Retained (mutated) element moved into the hole `idx - del`. + // SAFETY: `idx - del < old_len <= actual_cap` and initialized by `next`. + ok &= unsafe { tag_matches(v.as_ptr().add(idx - del), m1_mut) }; + } else { + // Retained (mutated) element stayed in place at `idx`. + // SAFETY: `idx < old_len <= actual_cap` and initialized by `pred`. + ok &= unsafe { tag_matches(v.as_ptr().add(idx), m1_mut) }; + } + } + // Inductive frame preservation across BOTH untouched regions: + // `check_prefix == true` checks arbitrary `j in 0..idx - del`; + // `check_prefix == false` checks arbitrary `k in idx2..old_len`. + if check_frame { + if check_prefix { + if retained_len > 0 { + // SAFETY: `j < idx - del <= actual_cap` was marked `fill` and untouched. + ok &= unsafe { tag_matches(v.as_ptr().add(j), fill) }; + } + } else if idx < old_len && k >= idx2 { + let want_k = if end - idx > 1 && k == idx + 1 { m2 } else { fill }; + // SAFETY: `idx2 <= k < old_len <= actual_cap` is live and untouched. + ok &= unsafe { tag_matches(v.as_ptr().add(k), want_k) }; + } + } + } + // Dropping the yielded `Option` exercises real drop glue (`0` or `1` drop). + let yielded = r.is_some(); + drop(r); + ok &= drops() == if mem::needs_drop::() { usize::from(yielded) } else { 0 }; + assert!(ok); + kani::cover(small && idx == end, "range exhausted"); + T::when_non_zst(|| kani::cover(actual_cap == 0, "zero capacity")); + kani::cover(small && idx < end && first && idx > 4096, "deep drain"); + kani::cover(small && shifted && del > 0 && yielded, "move into hole, then drain"); + kani::cover(small && shifted && del == 0 && yielded, "retain without hole, then drain"); + kani::cover(small && shifted && del > 0 && !yielded, "move into hole, then exhausted"); + kani::cover(small && shifted && del > 4096, "deep hole"); + finish::(v); +} + +/// Base-case harness connecting `Vec::extract_if` (`ExtractIf::new`) to the +/// inductive invariant `del <= idx <= end <= old_len <= cap` and verifying +/// the first `next()` step from that base state. +/// +/// Unbounded `check_extract_if_base_u8` (`check_contents = false`, up to +/// `MAX_ALLOCATION_BYTES`) proves full memory safety and state transitions with +/// 100% validly initialized `[0..old_len]` (avoiding CBMC's `--json-ui` +/// symbolic-array trace OOM `kani#4905`); paired `check_extract_if_base_contents_u8` +/// (`check_contents = true`, up to `4352` elements, `> 4096` deep) verifies +/// typed predicate reads/mutations and yielded value integrity. +fn check_extract_if_base_mode(max_bytes: usize, check_contents: bool) { + let use_up_to = !T::IS_ZST; + let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; + let (fill, m1, m1_mut) = markers_for::(); + let m2 = T::any_distinct_three(fill, m1, m1_mut); + let (mut v, cap) = if T::IS_ZST { + let mut v = Vec::::new(); + let old_len = pick(usize::MAX); + // SAFETY: `T` is a ZST, so capacity is `usize::MAX`. + unsafe { v.set_len(old_len) }; + (v, usize::MAX) + } else { + let cap = pick(max_bytes / mem::size_of::()); + let old_len = pick(cap); + if cap == 0 { + (Vec::::new(), 0) + } else { + let layout = crate::alloc::Layout::array::(cap).unwrap(); + // SAFETY: `cap > 0` and `size_of::() > 0`. + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + if old_len > 0 { + let bg_fill = if T::ALLOW_ZERO { 0u8 } else { 1u8 }; + // SAFETY: `old_len <= cap`; spare capacity `[old_len..cap]` stays uninit. + unsafe { core::intrinsics::write_bytes(p, bg_fill, old_len * mem::size_of::()) }; + } + // SAFETY: `p` was allocated with `layout` and `[0..old_len]` is validly initialized. + (unsafe { Vec::from_raw_parts(p.cast::(), old_len, cap) }, cap) + } + }; + let old_len = v.len(); + let small = witness_ok::(cap); + let end = pick(old_len); + let start = pick(end); + if check_contents && !T::IS_ZST && cap > 0 { + // SAFETY: `start < end <= old_len <= cap`. + unsafe { + if start < end { + mark(v.as_mut_ptr().add(start), m1); + } + if end - start > 1 { + mark(v.as_mut_ptr().add(start + 1), m2); + } + } + } + let drain_first: bool = kani::any(); + let mut first_call = true; + let mut pred_ok = true; + let pred = |x: &mut T| -> bool { + if mem::replace(&mut first_call, false) { + if check_contents && !T::IS_ZST { + pred_ok &= x.matches_tag(m1); + // SAFETY: `x` is a valid `&mut T`. + unsafe { mark(x as *mut T, m1_mut) }; + } + drain_first + } else { + if check_contents && !T::IS_ZST { + pred_ok &= x.matches_tag(m2); + } + true + } + }; + reset_drops(); + let mut ei = ExtractIf::new(&mut v, pred, start..end); + let mut ok = ei.idx == start + && ei.del == 0 + && ei.end == end + && ei.old_len == old_len + && ei.vec.len() == 0; + let r = ei.next(); + ok &= ei.del <= ei.idx && ei.idx <= ei.end && ei.end == end && ei.old_len == old_len; + if start < end && drain_first { + ok &= ei.del == 1 && ei.idx == start + 1; + match &r { + Some(x) => { + if check_contents && !T::IS_ZST { + ok &= x.matches_tag(m1_mut); + } + } + None => ok = false, + } + } + mem::forget(ei); + ok &= pred_ok; + assert!(ok); + finish::(r); + finish::(v); + kani::cover(small && start == end, "empty base range"); + kani::cover(small && start > 4096 && start < end, "deep base start"); +} + +/// Unbounded Kani verification of `ExtractIf::drop` (the exact cleanup path run +/// on early drop): from an arbitrary reachable state +/// `del <= idx <= end <= old_len <= cap` with live regions `[0..idx - del]` and +/// `[idx..old_len]` validly initialized (and hole `[idx - del..idx]` plus spare +/// capacity `[old_len..cap]` genuinely uninitialized), verifies that `ptr::copy` +/// safely closes the hole within bounds and restores `v.len() == old_len - del` +/// without spurious drops (`check_extract_if_drop_witness_*` verifies concrete +/// element preservation, and VeriFast proves full-buffer polymorphic ownership). +fn check_extract_if_drop() { + let (mut v, actual_cap) = if T::IS_ZST { + (Vec::::new(), usize::MAX) + } else { + let cap = down_from(MAX_ALLOCATION_BYTES / mem::size_of::()); + if cap == 0 { + (Vec::::new(), 0) + } else { + let layout = crate::alloc::Layout::array::(cap).unwrap(); + // SAFETY: `cap > 0` and `size_of::() > 0`. + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + // SAFETY: `p` was allocated with `layout`; length 0 matches `ExtractIf::new`. + (unsafe { Vec::from_raw_parts(p.cast::(), 0, cap) }, cap) + } + }; + let small = witness_ok::(actual_cap); + let old_len = down_from(actual_cap); + let end = down_from(old_len); + let idx = down_from(end); + let del = down_from(idx); + let tail_len = old_len - idx; + if !T::IS_ZST && actual_cap > 0 { + let bg_fill = if T::ALLOW_ZERO { 0u8 } else { 1u8 }; + let retained_len = idx - del; + let base = v.as_mut_ptr().cast::(); + // SAFETY: Initialize the two live regions `[0..idx - del]` and `[idx..old_len]` + // while leaving the moved-out hole `[idx - del..idx]` and spare capacity + // `[old_len..actual_cap]` genuinely uninitialized. + unsafe { + if retained_len > 0 { + core::intrinsics::write_bytes(base, bg_fill, retained_len * mem::size_of::()); + } + if tail_len > 0 { + core::intrinsics::write_bytes( + base.add(idx * mem::size_of::()), + bg_fill, + tail_len * mem::size_of::(), + ); + } + } + } + // Unbounded harness checks memory safety of `ptr::copy` (bounds, alignment, + // liveness), length/capacity, and zero spurious drops without reading back + // bytes after overlapping symbolic-offset `memmove` (which diverges in CBMC); + // `check_extract_if_drop_witness_*` below checks exact element preservation. + reset_drops(); + { + let ei = ExtractIf { vec: &mut v, idx, end, del, old_len, pred: |_: &mut T| false }; + drop(ei); + } + assert!(drops() == 0 && v.len() == old_len - del && v.capacity() == actual_cap); + kani::cover(small && del == 0, "drop without hole"); + kani::cover(small && del > 0 && tail_len > 0, "drop closes hole via ptr::copy"); + kani::cover(small && del > 4096 && tail_len > 0, "drop closes deep hole"); + finish::(v); +} + +/// Concrete-size content witness for `ExtractIf::drop` verifying exact +/// element preservation across the overlapping `ptr::copy` hole-close +/// (`cap = 5, old_len = 5, idx = 3, del = 2`, zero `write_bytes` so padding +/// stays genuinely uninitialized). +fn check_extract_if_drop_witness() { + let (b0, b1, b2) = markers_for::(); + let layout = crate::alloc::Layout::array::(5).unwrap(); + // SAFETY: `5 * size_of::() > 0` (only instantiated on non-ZST types). + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + let typed: *mut T = p.cast::(); + // SAFETY: Slots 0 (retained) and 3..5 (tail) initialized via typed write; + // hole slots 1..3 remain genuinely uninitialized. + unsafe { + mark(typed, b0); + mark(typed.add(3), b1); + mark(typed.add(4), b2); + } + // SAFETY: `typed` came from `alloc` with `layout`; `len == 0` matches `ExtractIf::new`. + let mut v = unsafe { Vec::from_raw_parts(typed, 0, 5) }; + reset_drops(); + { + let ei = + ExtractIf { vec: &mut v, idx: 3, end: 4, del: 2, old_len: 5, pred: |_: &mut T| false }; + drop(ei); + } + assert!(drops() == 0); + assert!(v.len() == 3 && v.capacity() == 5); + // SAFETY: `0..3` are live after `ExtractIf::drop` closed the hole. + unsafe { + assert!(tag_matches(v.as_ptr(), b0)); + assert!(tag_matches(v.as_ptr().add(1), b1)); + assert!(tag_matches(v.as_ptr().add(2), b2)); + } + finish::(v); +} + +#[kani::proof] +fn check_extract_if_next_u8() { + check_extract_if_next::(false, true); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_next_overaligned() { + // 16-byte `OverAligned`: still checks `m1`, `m2`, in-place mutation `m1_mut`/`m2_mut`, + // moved-into-hole `v[idx - del]`, and yielded value while keeping CBMC RSS bounded; + // full untouched-frame preservation is verified on 8-byte padded `PaddedNiche` & `(char, u8)`. + check_extract_if_next::(true, false); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_next_padded_niche() { + check_extract_if_next::(true, true); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_next_char_u8() { + check_extract_if_next::<(char, u8)>(true, true); +} + +#[kani::proof] +fn check_extract_if_next_zst() { + check_extract_if_next::<()>(false, true); +} + +#[kani::proof] +fn check_extract_if_next_aligned_zst() { + check_extract_if_next::(false, true); +} + +#[kani::proof] +fn check_extract_if_next_drop_tracker() { + check_extract_if_next::(false, true); +} + +#[kani::proof] +fn check_extract_if_next_drop_niche() { + check_extract_if_next::(false, true); +} + +#[kani::proof] +fn check_extract_if_next_nonzero() { + check_extract_if_next::>(false, true); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_base_u8() { + check_extract_if_base_mode::(MAX_ALLOCATION_BYTES, false); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_base_contents_u8() { + check_extract_if_base_mode::(4352 * mem::size_of::(), true); +} + +#[kani::proof] +fn check_extract_if_base_aligned_zst() { + check_extract_if_base_mode::(MAX_ALLOCATION_BYTES, true); +} + +#[kani::proof] +fn check_extract_if_drop_u8() { + check_extract_if_drop::(); +} + +#[kani::proof] +fn check_extract_if_drop_overaligned() { + check_extract_if_drop::(); +} + +#[kani::proof] +fn check_extract_if_drop_padded_niche() { + check_extract_if_drop::(); +} + +#[kani::proof] +fn check_extract_if_drop_char_u8() { + check_extract_if_drop::<(char, u8)>(); +} + +#[kani::proof] +fn check_extract_if_drop_aligned_zst() { + check_extract_if_drop::(); +} + +#[kani::proof] +fn check_extract_if_drop_drop_tracker() { + check_extract_if_drop::(); +} + +#[kani::proof] +fn check_extract_if_drop_drop_niche() { + check_extract_if_drop::(); +} + +#[kani::proof] +fn check_extract_if_drop_witness_u8() { + check_extract_if_drop_witness::(); +} + +#[kani::proof] +fn check_extract_if_drop_witness_padded_niche() { + check_extract_if_drop_witness::(); +} + +#[kani::proof] +fn check_extract_if_drop_witness_char_u8() { + check_extract_if_drop_witness::<(char, u8)>(); +} + +#[kani::proof] +fn check_extract_if_drop_witness_drop_niche() { + check_extract_if_drop_witness::(); +} diff --git a/library/alloc/src/vec/verify_iter_spec.rs b/library/alloc/src/vec/verify_iter_spec.rs new file mode 100644 index 0000000000000..46b4dcf578c04 --- /dev/null +++ b/library/alloc/src/vec/verify_iter_spec.rs @@ -0,0 +1,3228 @@ +//! Kani harnesses for `Vec`'s iterator and specialization implementations: +//! `IntoIter`, `SpecExtend`, `SpecFromElem`, `SpecFromIter`, and +//! `SpecFromIterNested` (`ExtractIf::next` harnesses live in `extract_if::verify`). +//! +//! ## Proof Strategy & Properties of `T` Observed +//! +//! All safety harnesses use symbolic allocation sizes up to CBMC's object-model +//! bound (`MAX_ALLOCATION_BYTES = (1 << 51) - 1` under `--object-bits 12`; +//! `usize::MAX` for ZST `Vec`/`SpecFromElem`, `MAX_ALLOCATION_BYTES` for ZST +//! `IntoIter` because Kani encodes pointer offsets in 52 bits). No +//! `#[kani::unwind]` is placed on any data loop. +//! +//! Across the verified implementations and their `RawVec` callees, the code +//! branches on the following properties of the element type `T`: +//! - `size_of::() == 0` (`IS_ZST`), `size_of::() == 1`, `<= 1024`, `> 1024` +//! (`RawVec::MIN_NON_ZERO_CAP`), and non-power-of-two sizes (`offset_from_unsigned` +//! division across `size_hint`, `as_slice`, `as_mut_slice`, `next`, `next_back`, +//! and `into_vecdeque`); +//! - `align_of::() == 1` vs `align_of::() > 1` (both non-ZST and over-aligned +//! ZST, exercising the ZST alignment guards in `IntoIter::{next_back, advance_back_by}`); +//! - validity invariants / niches (`NonZero` vs all-bit-patterns-valid types); +//! - `mem::needs_drop::()` across 1-byte, multi-byte aligned, and ZST types; +//! - `Copy` (`NonDrop` / `TrustedRandomAccessNoCoerce`) and `TrivialClone`. +//! +//! The representative types below instantiate every relevant combination. +//! Supplementary `_witness` and `bounded_evidence` harnesses additionally check +//! element-content witnesses and real compiler-synthesized slice drop glue. + +use core::marker::PhantomData; +use core::mem::{self, ManuallyDrop, SizedTypeProperties}; +use core::num::NonZero; +use core::ptr::NonNull; +use core::{cmp, kani, ptr}; + +use super::IntoIter; +use super::spec_extend::SpecExtend; +use super::spec_from_elem::SpecFromElem; +use super::spec_from_iter::SpecFromIter; +use super::spec_from_iter_nested::SpecFromIterNested; +use crate::alloc::Global; +use crate::raw_vec::RawVec; +use crate::vec::Vec; + +/// Largest object CBMC can represent under `--object-bits 12`. +pub(super) const MAX_ALLOCATION_BYTES: usize = (1 << 51) - 1; + +/// Storage budget per buffer. Amortised growth of a destination buffer at most +/// doubles, so every allocation stays within the CBMC object bound. +pub(super) const BUDGET: usize = MAX_ALLOCATION_BYTES / 4; + +/// Covers are additionally restricted to buffers of at most this many elements: +/// a satisfied cover makes CBMC print a witness trace, and a witness with a +/// buffer near the object bound exhausts memory while being printed (kani#4905). +/// This only bounds cover witnesses, never the safety proof itself. +const WITNESS_CAP: usize = (1 << 13) + 256; + +/// Element-count bound for `SpecExtend` `_contents_*` witness harnesses +/// (strictly `> 4096` deep so every cover reaches deep indices while keeping +/// `OverAligned` / `PaddedNiche` bulk live-element initialization fast). +const EXTEND_CONTENTS_CAP: usize = (1 << 12) + 256; + +/// Checks the postcondition shared by all `from_elem` specializations at a +/// symbolic index, so the proof covers every position of an unbounded vector. +fn check_filled(v: &Vec, elem: T, n: usize) { + assert!(v.len() == n); + assert!(v.capacity() >= n); + if n > 0 { + let i: usize = kani::any_where(|&i: &usize| i < n); + // SAFETY: `i < n == v.len()`. + assert!(unsafe { *v.as_ptr().add(i) } == elem); + kani::cover(n > 4096 && i > 4096, "deep position reached"); + } +} + +#[kani::proof] +fn check_from_elem_u8() { + let elem: u8 = kani::any(); + let n: usize = kani::any_where(|&n: &usize| n <= MAX_ALLOCATION_BYTES); + let v = ::from_elem(elem, n, Global); + check_filled(&v, elem, n); + kani::cover(elem == 0 && n > 0, "zeroed-allocation branch"); + kani::cover(elem != 0 && n > 0, "write_bytes branch"); + kani::cover(n == 0, "empty vector"); +} + +#[kani::proof] +fn check_from_elem_i8() { + let elem: i8 = kani::any(); + let n: usize = kani::any_where(|&n: &usize| n <= MAX_ALLOCATION_BYTES); + let v = ::from_elem(elem, n, Global); + check_filled(&v, elem, n); + kani::cover(elem == 0 && n > 0, "zeroed-allocation branch"); + kani::cover(elem < 0 && n > 0, "write_bytes branch, negative elem"); + kani::cover(elem > 0 && n > 0, "write_bytes branch, positive elem"); + kani::cover(n == 0, "empty vector"); +} + +#[kani::proof] +fn check_from_elem_unit() { + // `()` is a ZST: no allocation is made, so `n` ranges over all of `usize`. + let n: usize = kani::any(); + let v = <() as SpecFromElem>::from_elem((), n, Global); + check_filled(&v, (), n); + kani::cover(n == usize::MAX, "maximal length"); +} + +// --------------------------------------------------------------------------- +// Representative element shapes & shared verification helpers +// --------------------------------------------------------------------------- + +/// Over-aligned element: size and stride 16, alignment 16 (with 15 padding bytes). +#[repr(align(16))] +#[derive(Clone, Copy, Debug)] +pub(super) struct OverAligned(u8); + +/// Over-aligned element implementing `TrivialClone`. Kept separate from +/// `OverAligned` so `OverAligned`'s trait set stays minimal in unrelated +/// harnesses (avoiding CBMC codegen/trace-expansion churn, kani#4905). +#[repr(align(16))] +#[derive(Clone, Copy, Debug)] +struct OverAlignedTc(u8); + +// SAFETY: `OverAlignedTc` is a `Copy` wrapper around `u8`, so `Clone::clone` is a +// trivial bitwise copy. +unsafe impl core::clone::TrivialClone for OverAlignedTc {} + +/// Padded + niche multi-field element: size 8, align 4, 3 interior padding bytes +/// between `NonZero` (offset 0) and `u32` (offset 4), plus a `NonZero` +/// validity niche (`ALLOW_ZERO = false`). Typed `ptr::write` (`mark`) leaves the +/// 3 interior padding bytes genuinely uninitialized. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub(super) struct PaddedNiche(NonZero, u32); + +// SAFETY: `PaddedNiche` is `Copy`, so `Clone::clone` is a trivial copy. +unsafe impl core::clone::TrivialClone for PaddedNiche {} + +/// Over-aligned ZST: size 0, alignment 16. Exercises ZST alignment guards that +/// `()` (alignment 1) cannot trigger. +#[repr(align(16))] +#[derive(Clone, Copy, Debug)] +pub(super) struct AlignedZst; + +// SAFETY: `AlignedZst` is a `Copy` ZST. +unsafe impl core::clone::TrivialClone for AlignedZst {} + +/// Non-power-of-two sized element: size 3, alignment 1. Exercises non-pow2 +/// `offset_from_unsigned` division across `size_hint`, `as_slice`, +/// `as_mut_slice`, `next`, `next_back`, and `into_vecdeque`. +#[derive(Clone, Copy, Debug)] +struct NonPow2([u8; 3]); + +/// Large over-aligned element (`size_of == 2048 > 1024`, `align_of == 2048`): +/// hits the `RawVec::MIN_NON_ZERO_CAP == 1` arm while keeping `from_byte` a +/// single scalar write with 2047 genuinely uninitialized padding bytes +/// (non-power-of-two division is tested separately by `NonPow2`). +#[repr(align(2048))] +#[derive(Clone, Copy, Debug)] +struct LargeElem(u8); + +// SAFETY: `LargeElem` is a `Copy` wrapper around `u8`. +unsafe impl core::clone::TrivialClone for LargeElem {} + +/// Number of `DropTracker*` / `DropZst` values dropped so far. +/// Initialized to a non-zero sentinel to avoid Kani's constant/static zero-byte +/// aliasing bug (https://github.com/model-checking/kani/issues/5088); every +/// harness calls `reset_drops()` / `reset_drop_trace()` before reading. +static mut DROPS: usize = 0x5A5A_5A5A_5A5A_5A5A; + +// Non-zero sentinel initializers for custom-allocator deallocation tracking (kani#5088). +static mut DEALLOCS: usize = 0x5A5A_5A5A_5A5A_5A5D; +static mut LAST_DEALLOC_PTR: usize = 0x5A5A_5A5A_5A5A_5A5E; +static mut LAST_DEALLOC_SIZE: usize = 0x5A5A_5A5A_5A5A_5A5F; +static mut LAST_DEALLOC_TAG: u8 = 0x5A; + +/// Custom `Allocator` delegating to `Global` while recording every deallocation +/// `(ptr, size)`. ZST so `fold`/`try_fold`'s loop contracts do not need to carry +/// allocator state; `StatefulAlloc(u8)` below additionally tests non-ZST +/// `ManuallyDrop::take(&mut self.alloc)` in `into_vecdeque` and `drop`. +#[derive(Clone, Copy, Debug)] +struct TrackAlloc; + +// SAFETY: Delegates directly to `Global`, upholding all `Allocator` invariants. +unsafe impl crate::alloc::Allocator for TrackAlloc { + fn allocate( + &self, + layout: crate::alloc::Layout, + ) -> Result, crate::alloc::AllocError> { + Global.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: crate::alloc::Layout) { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { + DEALLOCS += 1; + LAST_DEALLOC_PTR = ptr.as_ptr().addr(); + LAST_DEALLOC_SIZE = layout.size(); + } + // SAFETY: Caller upholds `Allocator::deallocate` preconditions. + unsafe { Global.deallocate(ptr, layout) } + } +} + +/// Non-ZST stateful custom `Allocator` carrying a symbolic `u8` tag to verify +/// `ManuallyDrop::take(&mut self.alloc)` preserves allocator state in +/// `into_vecdeque` and `dealloc_only`. +#[derive(Clone, Copy, Debug)] +struct StatefulAlloc(u8); + +// SAFETY: Delegates directly to `Global`, upholding all `Allocator` invariants. +unsafe impl crate::alloc::Allocator for StatefulAlloc { + fn allocate( + &self, + layout: crate::alloc::Layout, + ) -> Result, crate::alloc::AllocError> { + Global.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: crate::alloc::Layout) { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { + DEALLOCS += 1; + LAST_DEALLOC_PTR = ptr.as_ptr().addr(); + LAST_DEALLOC_SIZE = layout.size(); + LAST_DEALLOC_TAG = self.0; + } + // SAFETY: Caller upholds `Allocator::deallocate` preconditions. + unsafe { Global.deallocate(ptr, layout) } + } +} + +fn reset_deallocs() { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { + DEALLOCS = 0; + LAST_DEALLOC_PTR = 0; + LAST_DEALLOC_SIZE = 0; + LAST_DEALLOC_TAG = 0; + } +} + +fn deallocs() -> usize { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { DEALLOCS } +} + +fn last_dealloc_ptr() -> usize { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { LAST_DEALLOC_PTR } +} + +fn last_dealloc_size() -> usize { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { LAST_DEALLOC_SIZE } +} + +fn last_dealloc_tag() -> u8 { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { LAST_DEALLOC_TAG } +} + +/// 1-byte element with drop glue that counts drops. +#[derive(Debug)] +pub(super) struct DropTracker(u8); + +impl Drop for DropTracker { + fn drop(&mut self) { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { DROPS += 1 }; + } +} + +/// 8-byte aligned element with drop glue: gives non-trivial alignment (8) and +/// stride (`sz % 8 == 0`) checks inside the drop-slice summary. +#[repr(align(8))] +#[derive(Debug)] +struct DropTracker8(u64); + +impl Drop for DropTracker8 { + fn drop(&mut self) { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { DROPS += 1 }; + } +} + +/// Over-aligned ZST with drop glue: exercises `T::IS_ZST && needs_drop::()` +/// and ZST pointer-alignment invariants during drop. +#[repr(align(16))] +#[derive(Debug)] +struct DropZst; + +impl Drop for DropZst { + fn drop(&mut self) { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { DROPS += 1 }; + } +} + +/// 1-byte element combining a validity niche (`NonZero`) with drop glue. +#[derive(Debug)] +pub(super) struct DropNiche(NonZero); + +impl Drop for DropNiche { + fn drop(&mut self) { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { DROPS += 1 }; + } +} + +pub(super) fn reset_drops() { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { DROPS = 0 }; +} + +pub(super) fn drops() -> usize { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { DROPS } +} + +/// Drops `container` when its element type `E` has `!mem::needs_drop::()` +/// (O(1) deallocation layout check, zero drop loop) and forgets it only when +/// dropping `container` would invoke an unbounded compiler slice-drop loop. +pub(super) fn finish(container: C) { + if !mem::needs_drop::() { + drop(container); + } else { + mem::forget(container); + } +} + +/// Byte-validity rules, typed construction (leaving padding bytes genuinely +/// uninitialized), pure tag readout, and ZST-aware cover helpers so dead +/// type-specific branches never emit unreachable `kani::cover` goals. +pub(super) trait Shape: Sized { + const ALLOW_ZERO: bool = true; + /// Optional fixed bulk-fill byte for shapes whose arbitrary repeated byte + /// is not valid (e.g. `(char, u8)` uses `0` → `('\0', 0u8)` for bulk fills + /// while all marked elements use arbitrary symbolic non-zero `u8` values + /// written via typed `ptr::write`). + const FIXED_FILL: Option = None; + + fn from_byte(b: u8) -> Self; + + fn tag_byte(&self) -> u8; + + /// Pure boolean tag check (no inner `assert!`) so callers can hoist + /// conditional element assertions to a single top-level `assert!(ok)` + /// without triggering `--assertion-reach-checks` under `cap > 0` branches + /// (`kani#4905`). + fn matches_tag(&self, expect: u8) -> bool { + self.tag_byte() == expect + } + + fn any_byte() -> u8 { + if Self::ALLOW_ZERO { kani::any() } else { kani::any_where(|&b: &u8| b != 0) } + } + + fn any_fill() -> u8 { + if let Some(f) = Self::FIXED_FILL { f } else { Self::any_byte() } + } + + fn any_distinct_from(a: u8) -> u8 { + kani::any_where(|&b: &u8| (Self::ALLOW_ZERO || b != 0) && b != a) + } + + fn any_distinct_three(a: u8, b: u8, c: u8) -> u8 { + kani::any_where(|&x: &u8| (Self::ALLOW_ZERO || x != 0) && x != a && x != b && x != c) + } + + /// Runs `f` only on non-ZST instantiations so ZST harnesses never emit + /// dead-branch unreachable `kani::cover` goals. + fn when_non_zst(f: impl FnOnce()) { + f(); + } + + /// Runs `f` only on ZST instantiations so non-ZST harnesses never emit + /// dead-branch unreachable `kani::cover` goals. + fn when_zst(_f: impl FnOnce()) {} + + /// Initializes an uninitialized slot at `p` by writing its non-padding + /// fields so every padding byte remains genuinely uninitialized while + /// avoiding redundant multi-byte padding writes in CBMC. + unsafe fn init_uninit_slot(p: *mut Self, b: u8) { + // SAFETY: Caller guarantees `p` is valid for writes of `Self` and `b` + // satisfies `Self::ALLOW_ZERO`. + unsafe { ptr::write(p, Self::from_byte(b)) }; + } +} + +impl Shape for u8 { + fn from_byte(b: u8) -> Self { + b + } + fn tag_byte(&self) -> u8 { + *self + } +} +impl Shape for OverAligned { + fn from_byte(b: u8) -> Self { + Self(b) + } + fn tag_byte(&self) -> u8 { + self.0 + } + unsafe fn init_uninit_slot(p: *mut Self, b: u8) { + // SAFETY: `p` is valid for writes of `OverAligned`; writing its sole + // field `.0` initializes the value while leaving all 15 padding bytes + // genuinely uninitialized. + unsafe { ptr::addr_of_mut!((*p).0).write(b) }; + } +} +impl Shape for OverAlignedTc { + fn from_byte(b: u8) -> Self { + Self(b) + } + fn tag_byte(&self) -> u8 { + self.0 + } +} +/// Constructs `NonZero` directly via `#[repr(transparent)]` layout without +/// calling `NonZero::new_unchecked` (whose internal `NonZero::new` transmutes +/// `u8 -> Option>` and triggers a false layout warning under +/// `-Z uninit-checks` in `library/core/src/num/nonzero.rs`). +#[inline] +fn nonzero_u8(b: u8) -> NonZero { + // SAFETY: Callers guarantee `b != 0` (`Shape::ALLOW_ZERO == false`), and + // `NonZero` is `#[repr(transparent)]` over a non-zero `u8`. + unsafe { mem::transmute::>(b) } +} + +impl Shape for PaddedNiche { + const ALLOW_ZERO: bool = false; + fn from_byte(b: u8) -> Self { + let nz = nonzero_u8(b); + Self(nz, u32::from_ne_bytes([b; 4])) + } + fn tag_byte(&self) -> u8 { + self.0.get() + } + fn matches_tag(&self, expect: u8) -> bool { + self.0.get() == expect && self.1 == u32::from_ne_bytes([expect; 4]) + } + unsafe fn init_uninit_slot(p: *mut Self, b: u8) { + // SAFETY: Writing every field of `PaddedNiche` initializes the struct + // while leaving the 3 interior padding bytes genuinely uninitialized. + unsafe { + ptr::addr_of_mut!((*p).0).write(nonzero_u8(b)); + ptr::addr_of_mut!((*p).1).write(u32::from_ne_bytes([b; 4])); + } + } +} +impl Shape for (char, u8) { + const FIXED_FILL: Option = Some(0); + fn from_byte(b: u8) -> Self { + (char::from(b), b) + } + fn tag_byte(&self) -> u8 { + self.1 + } + fn matches_tag(&self, expect: u8) -> bool { + self.1 == expect && self.0 == char::from(expect) + } + unsafe fn init_uninit_slot(p: *mut Self, b: u8) { + // SAFETY: Writing every field of `(char, u8)` initializes the tuple + // while leaving the 3 padding bytes genuinely uninitialized. + unsafe { + ptr::addr_of_mut!((*p).0).write(char::from(b)); + ptr::addr_of_mut!((*p).1).write(b); + } + } +} +impl Shape for () { + fn from_byte(_: u8) -> Self {} + fn tag_byte(&self) -> u8 { + 0 + } + fn when_non_zst(_f: impl FnOnce()) {} + fn when_zst(f: impl FnOnce()) { + f(); + } +} +impl Shape for AlignedZst { + fn from_byte(_: u8) -> Self { + AlignedZst + } + fn tag_byte(&self) -> u8 { + 0 + } + fn when_non_zst(_f: impl FnOnce()) {} + fn when_zst(f: impl FnOnce()) { + f(); + } +} +impl Shape for NonPow2 { + fn from_byte(b: u8) -> Self { + Self([b; 3]) + } + fn tag_byte(&self) -> u8 { + self.0[0] + } +} +impl Shape for LargeElem { + fn from_byte(b: u8) -> Self { + Self(b) + } + fn tag_byte(&self) -> u8 { + self.0 + } +} +impl Shape for DropTracker { + fn from_byte(b: u8) -> Self { + Self(b) + } + fn tag_byte(&self) -> u8 { + self.0 + } +} +impl Shape for DropTracker8 { + fn from_byte(b: u8) -> Self { + Self(u64::from_ne_bytes([b; 8])) + } + fn tag_byte(&self) -> u8 { + self.0 as u8 + } +} +impl Shape for DropZst { + fn from_byte(_: u8) -> Self { + DropZst + } + fn tag_byte(&self) -> u8 { + 0 + } + fn when_non_zst(_f: impl FnOnce()) {} + fn when_zst(f: impl FnOnce()) { + f(); + } +} +impl Shape for DropNiche { + const ALLOW_ZERO: bool = false; + fn from_byte(b: u8) -> Self { + Self(nonzero_u8(b)) + } + fn tag_byte(&self) -> u8 { + self.0.get() + } +} +impl Shape for NonZero { + const ALLOW_ZERO: bool = false; + fn from_byte(b: u8) -> Self { + nonzero_u8(b) + } + fn tag_byte(&self) -> u8 { + self.get() + } +} + +/// Three distinct valid marker bytes for `T`: `(fill, first, last)`. +pub(super) fn markers_for() -> (u8, u8, u8) { + let fill = T::any_fill(); + let first = T::any_distinct_from(fill); + let last = kani::any_where(|&b: &u8| (T::ALLOW_ZERO || b != 0) && b != fill && b != first); + (fill, first, last) +} + +/// Pure boolean typed tag check (no inner `assert!`) for hoisted postconditions; +/// validates niches without touching padding bytes or calling `expose_provenance`. +pub(super) unsafe fn tag_matches(p: *const T, expect: u8) -> bool { + // SAFETY: Caller guarantees `p` points to an initialized `T`. + unsafe { (*p).matches_tag(expect) } +} + +/// Writes a typed `T` value tagged with `b` to `p`, leaving any padding bytes +/// in `T` (e.g., `OverAligned`, `PaddedNiche`, `(char, u8)`) genuinely +/// uninitialized so `-Z uninit-checks` catches invalid padding reads. +pub(super) unsafe fn mark(p: *mut T, b: u8) { + // SAFETY: Caller guarantees `p` is valid for writes of `T` and `b` + // satisfies `T::ALLOW_ZERO`. + unsafe { ptr::write(p, T::from_byte(b)) }; +} + +/// A symbolic value in `0..=max` biased toward small witnesses under CaDiCaL +/// (default phase `true` → `x = max` → `max - x = 0`, avoiding `kani#4905`). +pub(super) fn down_from(max: usize) -> usize { + let x: usize = kani::any_where(|&x: &usize| x <= max); + max - x +} + +/// A symbolic value in `0..=max` biased toward small witnesses under MiniSat +/// (default phase `false` → `x = 0`, avoiding `kani#4905` on implicit +/// `--assertion-reach-checks` traces). Ranges over the exact same `0..=max`. +pub(super) fn any_up_to(max: usize) -> usize { + kani::any_where(|&x: &usize| x <= max) +} + +/// Whether a buffer of capacity `cap` is small enough for a cover witness. ZST +/// buffers own no storage (their capacity is `usize::MAX`), so always qualify. +pub(super) fn witness_ok(cap: usize) -> bool { + T::IS_ZST || cap <= WITNESS_CAP +} + +/// Mode selector for `SpecExtend` harnesses so safety-only instantiations +/// (`LargeElem`) emit zero dead-branch unreachable `kani::cover` goals. +trait ExtendMode { + const CHECK_CONTENTS: bool; + fn when_contents(f: impl FnOnce()); +} + +struct FullContents; +impl ExtendMode for FullContents { + const CHECK_CONTENTS: bool = true; + fn when_contents(f: impl FnOnce()) { + f(); + } +} + +struct SafetyOnly; +impl ExtendMode for SafetyOnly { + const CHECK_CONTENTS: bool = false; + fn when_contents(_f: impl FnOnce()) {} +} + +/// A `Vec` with symbolic capacity (at most `max_bytes` bytes of storage) +/// and symbolic length. Always initializes the full live range `[0..len]` with +/// valid background bytes (`0` if `T::ALLOW_ZERO`, else `1`, leaving spare +/// capacity `[len..cap]` genuinely uninitialized), after which callers overwrite +/// marked witness slots with symbolic values via typed `mark(...)` to reset +/// padding bytes to genuinely uninitialized. +fn any_vec_opt(max_bytes: usize, use_up_to: bool) -> Vec { + let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; + if T::IS_ZST { + let mut v = Vec::::new(); + let len = pick(usize::MAX); + // SAFETY: `T` is a ZST, so capacity is `usize::MAX` and elements need no storage. + unsafe { v.set_len(len) }; + return v; + } + let bg_fill = if T::ALLOW_ZERO { 0u8 } else { 1u8 }; + let cap = pick(max_bytes / mem::size_of::()); + let len = pick(cap); + if cap == 0 { + return Vec::new(); + } + let layout = crate::alloc::Layout::array::(cap).unwrap(); + // SAFETY: `cap > 0` and `size_of::() > 0`, so `layout.size() > 0`. + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + if len > 0 { + // SAFETY: `len <= cap`; spare capacity `[len..cap]` remains uninitialized. + unsafe { + core::intrinsics::write_bytes(p, bg_fill, len * mem::size_of::()); + } + } + // SAFETY: `p` came from `Global::alloc` with `Layout::array::(cap)` and `[0..len]` is valid. + unsafe { Vec::from_raw_parts(p.cast::(), len, cap) } +} + +/// An `IntoIter` with symbolic capacity, length, and optional front +/// advance. When `init_live` is `true`, **only the live remaining slice +/// `[adv..len]` is initialized** with valid bytes `T::any_fill()` (so `-Z +/// uninit-checks` validates full slice reads and catches consumed-prefix reads), +/// while `[0..adv]` and `[len..cap]` remain genuinely uninitialized; callers +/// then overwrite accessed slots via typed `mark(...)` to reset their padding +/// bytes to genuinely uninitialized. When `init_live` is `false` (used solely +/// by `check_into_iter_next_chunk_n`, which immediately initializes every +/// touched slot `0..min(len, N + 1)` field-wise via `Shape::init_uninit_slot` +/// and fills the untouched live tail `min(len, N + 1)..len` via `write_bytes`), +/// backing storage starts uninitialized so touched slots keep genuinely +/// uninitialized padding while 100% of `[adv..len]` is validly initialized. +fn any_into_iter_opt( + max_bytes: usize, + may_advance: bool, + alloc: A, + use_up_to: bool, + init_live: bool, +) -> (IntoIter, usize) { + let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; + let (buf, cap, len, adv) = if T::IS_ZST { + let n = pick(MAX_ALLOCATION_BYTES); + (NonNull::::dangling(), usize::MAX, n, 0) + } else { + let fill = T::any_fill(); + let cap = pick(max_bytes / mem::size_of::()); + let len = pick(cap); + let adv = if may_advance { pick(len) } else { 0 }; + let n = len - adv; + let buf = if cap == 0 { + NonNull::::dangling() + } else { + let layout = crate::alloc::Layout::array::(cap).unwrap(); + // SAFETY: `cap > 0` and `size_of::() > 0`, so `layout.size() > 0`. + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + if init_live && n > 0 { + // SAFETY: `adv + n == len <= cap`; `[0..adv]` and `[len..cap]` stay uninit. + unsafe { + core::intrinsics::write_bytes( + p.add(adv * mem::size_of::()), + fill, + n * mem::size_of::(), + ); + } + } + // SAFETY: `p` is non-null and properly aligned for `T`. + unsafe { NonNull::new_unchecked(p.cast::()) } + }; + (buf, cap, len, adv) + }; + let n = len - adv; + let (ptr, end) = if T::IS_ZST { + (buf, buf.as_ptr().cast_const().wrapping_byte_add(n)) + } else { + // SAFETY: `adv <= len <= cap`, both within the allocation (or dangling for `cap == 0`). + unsafe { (buf.add(adv), buf.as_ptr().add(len) as *const T) } + }; + let it = IntoIter { buf, phantom: PhantomData, cap, alloc: ManuallyDrop::new(alloc), ptr, end }; + (it, n) +} + +fn any_into_iter_live_in( + max_bytes: usize, + may_advance: bool, + alloc: A, +) -> (IntoIter, usize) { + any_into_iter_opt(max_bytes, may_advance, alloc, false, true) +} + +fn any_into_iter_uninit_in_mode( + max_bytes: usize, + may_advance: bool, + alloc: A, + use_up_to: bool, +) -> (IntoIter, usize) { + any_into_iter_opt(max_bytes, may_advance, alloc, use_up_to, false) +} + +/// `SpecExtend>::spec_extend`: appends all remaining elements +/// in order across distinct allocators (`Vec` extended from +/// `IntoIter`), keeps `len <= capacity`, verifies exact source +/// deallocation via `TrackAlloc`, and drops nothing. +/// +/// Unbounded `check_spec_extend_into_iter_*` harnesses (`SafetyOnly`, up to +/// `BUDGET`) prove full memory safety, bounds, alignment, non-overlap, length, +/// capacity, and `TrackAlloc` deallocation across all symbolic sizes up to +/// `2^49` bytes without hitting CBMC's `--json-ui` `` +/// VLA trace-serialization OOM (`kani#4905`). Paired `_contents_*` harnesses +/// (`FullContents`, up to `EXTEND_CONTENTS_CAP = 4352` elements, `> 4096` deep) prove +/// universally quantified typed element integrity across every prefix slot +/// `0..old_len` and every appended slot `old_len..old_len + count` while +/// leaving padding bytes genuinely uninitialized. +fn spec_extend_into_iter(budget: usize) { + let use_up_to = !T::IS_ZST; + let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; + let tag = T::any_byte(); + let mut dst = any_vec_opt::(budget, use_up_to); + let (it, count) = any_into_iter_opt::(budget, true, TrackAlloc, use_up_to, true); + let (old_len, old_cap) = (dst.len(), dst.capacity()); + let (old_it_buf, old_it_cap) = (it.buf, it.cap); + let check_dst: bool = kani::any(); + let i = if check_dst && old_len > 0 { pick(old_len.saturating_sub(1)) } else { 0 }; + let k = if !check_dst && count > 0 { pick(count.saturating_sub(1)) } else { 0 }; + if M::CHECK_CONTENTS && !T::IS_ZST { + if check_dst { + if old_len > 0 { + // SAFETY: `i < old_len <= old_cap`; typed write leaves padding uninit. + unsafe { mark(dst.as_mut_ptr().add(i), tag) }; + } + } else if count > 0 { + // SAFETY: `k < count` is inside `it`'s live remaining slice. + unsafe { mark(it.ptr.as_ptr().add(k), tag) }; + } + } + let tiny = |cap: usize| T::IS_ZST || cap <= 64; + let small_bytes = |cap: usize| { + T::IS_ZST + || (cap <= WITNESS_CAP && cap.saturating_mul(mem::size_of::()) <= WITNESS_CAP * 16) + }; + let (src_cap, dst_ok, src_ok) = (it.cap, small_bytes(old_cap), small_bytes(it.cap)); + let deep = if T::IS_ZST { 4096 } else { (4096 / mem::size_of::()).max(4) }; + if T::IS_ZST { + // `reserve` panics with "capacity overflow" past `usize::MAX`. + kani::assume(old_len.checked_add(count).is_some()); + } + reset_drops(); + reset_deallocs(); + as SpecExtend>>::spec_extend(&mut dst, it); + let new_len = old_len.wrapping_add(count); + let mut ok = drops() == 0 && dst.len() == new_len && dst.len() <= dst.capacity(); + if !T::IS_ZST && old_it_cap > 0 { + ok &= deallocs() == 1 + && last_dealloc_ptr() == old_it_buf.as_ptr().addr() + && last_dealloc_size() == old_it_cap.wrapping_mul(mem::size_of::()); + } else { + ok &= deallocs() == 0; + } + if M::CHECK_CONTENTS && !T::IS_ZST { + if check_dst { + if old_len > 0 { + // SAFETY: `i < old_len <= dst.len()`. + ok &= unsafe { tag_matches(dst.as_ptr().add(i), tag) }; + } + } else if count > 0 { + // SAFETY: `old_len + k < dst.len()`. + ok &= unsafe { tag_matches(dst.as_ptr().add(old_len.wrapping_add(k)), tag) }; + } + } + assert!(ok); + if M::CHECK_CONTENTS { + M::when_contents(|| { + T::when_non_zst(|| { + kani::cover( + src_ok && tiny(old_cap) && !check_dst && count > 0 && k > 4096, + "deep moved element checked", + ); + }); + }); + } + kani::cover(src_ok && tiny(old_cap) && count > deep, "deep source"); + kani::cover(dst_ok && tiny(src_cap) && old_len > deep && count > 0, "deep destination"); + kani::cover(tiny(old_cap) && tiny(src_cap) && count == 0, "empty source"); + // A ZST destination has capacity `usize::MAX` and never grows. + T::when_non_zst(|| { + kani::cover(tiny(old_cap) && tiny(src_cap) && new_len > old_cap, "destination had to grow"); + kani::cover( + tiny(old_cap) && tiny(src_cap) && count > 0 && new_len <= old_cap, + "nonempty append without growth", + ); + }); + finish::(dst); +} + +fn check_spec_extend_into_iter() { + spec_extend_into_iter::(BUDGET) +} + +fn check_spec_extend_into_iter_contents() { + spec_extend_into_iter::(EXTEND_CONTENTS_CAP * mem::size_of::()) +} + +/// `SpecFromIter>::from_iter` on an unadvanced iterator: +/// reuses the buffer directly with original elements intact and zero drops. +/// +/// Unbounded `check_from_iter_into_iter_*` harnesses (`SafetyOnly`, up to +/// `MAX_ALLOCATION_BYTES`, `init_live = true`) prove O(1) buffer reuse, length, +/// capacity, and zero drops across all symbolic sizes with 100% validly +/// initialized live elements (avoiding CBMC's `--json-ui` symbolic-array trace +/// OOM `kani#4905`); paired `_contents_*` harnesses (`FullContents`, up to +/// `EXTEND_CONTENTS_CAP = 4352` elements, `> 4096` deep) prove universally +/// quantified typed element preservation at symbolic `j` and `k` while keeping +/// padding bytes genuinely uninitialized. +fn check_from_iter_into_iter_mode(budget: usize) { + let use_up_to = !T::IS_ZST; + let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; + let src_fill = T::any_fill(); + let marker = T::any_distinct_from(src_fill); + let (it, count) = any_into_iter_opt::(budget, false, Global, use_up_to, true); + let k = if M::CHECK_CONTENTS && count > 0 { pick(count - 1) } else { 0 }; + let j = if M::CHECK_CONTENTS && count > 0 { pick(count - 1) } else { 0 }; + if M::CHECK_CONTENTS && !T::IS_ZST && count > 0 { + // SAFETY: `k < count` and `j < count` are inside `it`'s live buffer; + // typed `mark` resets padding bytes on witness slots to genuinely uninit. + unsafe { + if j != k { + mark(it.ptr.as_ptr().add(j), src_fill); + } + mark(it.ptr.as_ptr().add(k), marker); + } + } + let buf = it.buf.as_ptr(); + let small = witness_ok::(it.cap); + reset_drops(); + let v = as SpecFromIter>>::from_iter(it); + let mut ok = drops() == 0 + && v.len() == count + && v.len() <= v.capacity() + && v.as_ptr() == buf as *const T; + if M::CHECK_CONTENTS && !T::IS_ZST && count > 0 { + // SAFETY: `k < count == v.len()` and `j < count == v.len()`. + ok &= unsafe { tag_matches(v.as_ptr().add(k), marker) }; + if j != k { + ok &= unsafe { tag_matches(v.as_ptr().add(j), src_fill) }; + M::when_contents(|| { + T::when_non_zst(|| kani::cover(small && j > 4096, "deep moved element checked")) + }); + } + } + assert!(ok); + kani::cover(small && count > 4096, "unadvanced: buffer reused as is"); + finish::(v); +} + +fn check_from_iter_into_iter() { + check_from_iter_into_iter_mode::(MAX_ALLOCATION_BYTES) +} + +fn check_from_iter_into_iter_contents() { + check_from_iter_into_iter_mode::(EXTEND_CONTENTS_CAP * mem::size_of::()) +} + +/// `SpecFromIter>::from_iter` on an iterator advanced by a +/// symbolic, nonzero number of elements: either shifts remaining elements to +/// the front via `ptr::copy` and reuses the buffer, or allocates a fresh vector +/// via `SpecExtend`. +/// +/// Unbounded harnesses verify memory safety of `ptr::copy` (bounds, alignment, +/// liveness), length/capacity, and buffer-reuse condition across `BUDGET`; +/// concrete-size `_witness` harnesses below verify every shifted element value +/// (killing `ptr::copy` deletion/swap mutants without triggering CBMC +/// symbolic-offset overlapping-memmove divergence). +fn check_from_iter_into_iter_advanced() { + let (it, count) = any_into_iter_opt::(BUDGET, true, Global, true, true); + let advanced = it.buf != it.ptr; + kani::assume(advanced); + let reuse = count >= it.cap / 2; + let buf = it.buf.as_ptr(); + let small = witness_ok::(it.cap); + reset_drops(); + let v = as SpecFromIter>>::from_iter(it); + assert!(drops() == 0); + assert!(v.len() == count); + assert!(v.len() <= v.capacity()); + assert!((v.as_ptr() == buf as *const T) == reuse); + kani::cover(small && reuse && count > 4096, "advanced: shifted to front"); + kani::cover(small && !reuse && count > 4096, "advanced and sparse: fresh vector"); + finish::(v); +} + +/// Concrete-size content witness for `SpecFromIter>::from_iter` +/// exercising BOTH the overlapping in-place `ptr::copy` shift (`cap=4, adv=1, +/// count=3`) and the sparse fresh-vector path (`cap=4, adv=3, count=1`) with +/// symbolic distinct typed element values (zero `write_bytes`; padding stays +/// genuinely uninitialized). +fn check_from_iter_into_iter_advanced_witness() { + let (b0, b1, b2) = markers_for::(); + // Case 1: overlapping in-place shift (`cap = 4, adv = 1, count = 3 >= cap / 2`). + { + let layout = crate::alloc::Layout::array::(4).unwrap(); + // SAFETY: `4 * size_of::() > 0` (only instantiated on non-ZST types). + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + // SAFETY: `p` is non-null and aligned for `T`. + let buf: NonNull = unsafe { NonNull::new_unchecked(p.cast::()) }; + // SAFETY: Slots 1..4 are inside the 4-element allocation; slot 0 stays uninit. + unsafe { + mark(buf.as_ptr().add(1), b0); + mark(buf.as_ptr().add(2), b1); + mark(buf.as_ptr().add(3), b2); + } + // SAFETY: `1 <= 4` within the 4-element allocation. + let (ptr, end) = unsafe { (buf.add(1), buf.as_ptr().add(4) as *const T) }; + let it = IntoIter { + buf, + phantom: PhantomData, + cap: 4, + alloc: ManuallyDrop::new(Global), + ptr, + end, + }; + reset_drops(); + let v = as SpecFromIter>>::from_iter(it); + assert!(drops() == 0); + assert!(v.len() == 3 && v.capacity() == 4 && v.as_ptr() == buf.as_ptr() as *const T); + // SAFETY: `0..3` are initialized by `ptr::copy`. + unsafe { + assert!(tag_matches(v.as_ptr(), b0)); + assert!(tag_matches(v.as_ptr().add(1), b1)); + assert!(tag_matches(v.as_ptr().add(2), b2)); + } + finish::(v); + } + // Case 2: sparse fresh-vector fallback (`cap = 4, adv = 3, count = 1 < cap / 2`). + { + let layout = crate::alloc::Layout::array::(4).unwrap(); + // SAFETY: `4 * size_of::() > 0`. + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + // SAFETY: `p` is non-null and aligned for `T`. + let buf: NonNull = unsafe { NonNull::new_unchecked(p.cast::()) }; + // SAFETY: Slot 3 is inside the 4-element allocation; slots 0..3 stay uninit. + unsafe { mark(buf.as_ptr().add(3), b2) }; + // SAFETY: `3 <= 4` within the 4-element allocation. + let (ptr, end) = unsafe { (buf.add(3), buf.as_ptr().add(4) as *const T) }; + let it = IntoIter { + buf, + phantom: PhantomData, + cap: 4, + alloc: ManuallyDrop::new(Global), + ptr, + end, + }; + reset_drops(); + let v = as SpecFromIter>>::from_iter(it); + assert!(drops() == 0); + assert!(v.len() == 1 && v.as_ptr() != buf.as_ptr() as *const T); + // SAFETY: `0 < 1 == v.len()`. + assert!(unsafe { tag_matches(v.as_ptr(), b2) }); + finish::(v); + } +} + +macro_rules! gen_harnesses { + ($check:ident: $($(#[$attr:meta])* $name:ident => $t:ty),* $(,)?) => { + $( + #[kani::proof] + $(#[$attr])* + fn $name() { + $check::<$t>(); + } + )* + }; +} + +// Unbounded safety harnesses across all 10 shapes (`BUDGET` = 2^49 bytes, +// `usize::MAX` for ZSTs), paired with `check_spec_extend_into_iter_contents_*` +// (up to `EXTEND_CONTENTS_CAP = 4352` elements, `> 4096` deep) for universally +// quantified typed element integrity without hitting `kani#4905`. +gen_harnesses! { check_spec_extend_into_iter: + #[kani::solver(minisat)] + check_spec_extend_into_iter_u8 => u8, + #[kani::solver(minisat)] + check_spec_extend_into_iter_overaligned => OverAligned, + #[kani::solver(minisat)] + check_spec_extend_into_iter_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_spec_extend_into_iter_char_u8 => (char, u8), + #[kani::solver(minisat)] + check_spec_extend_into_iter_large => LargeElem, + check_spec_extend_into_iter_zst => (), + check_spec_extend_into_iter_aligned_zst => AlignedZst, + #[kani::solver(minisat)] + check_spec_extend_into_iter_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_spec_extend_into_iter_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_spec_extend_into_iter_nonzero => NonZero, +} + +gen_harnesses! { check_spec_extend_into_iter_contents: + #[kani::solver(minisat)] + check_spec_extend_into_iter_contents_u8 => u8, + #[kani::solver(minisat)] + check_spec_extend_into_iter_contents_overaligned => OverAligned, + #[kani::solver(minisat)] + check_spec_extend_into_iter_contents_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_spec_extend_into_iter_contents_char_u8 => (char, u8), + #[kani::solver(minisat)] + check_spec_extend_into_iter_contents_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_spec_extend_into_iter_contents_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_spec_extend_into_iter_contents_nonzero => NonZero, +} + +gen_harnesses! { check_from_iter_into_iter: + #[kani::solver(minisat)] + check_from_iter_into_iter_u8 => u8, + #[kani::solver(minisat)] + check_from_iter_into_iter_overaligned => OverAligned, + #[kani::solver(minisat)] + check_from_iter_into_iter_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_from_iter_into_iter_char_u8 => (char, u8), + check_from_iter_into_iter_zst => (), + check_from_iter_into_iter_aligned_zst => AlignedZst, + #[kani::solver(minisat)] + check_from_iter_into_iter_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_from_iter_into_iter_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_from_iter_into_iter_nonzero => NonZero, +} + +gen_harnesses! { check_from_iter_into_iter_contents: + #[kani::solver(minisat)] + check_from_iter_into_iter_contents_u8 => u8, + #[kani::solver(minisat)] + check_from_iter_into_iter_contents_overaligned => OverAligned, + #[kani::solver(minisat)] + check_from_iter_into_iter_contents_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_from_iter_into_iter_contents_char_u8 => (char, u8), + #[kani::solver(minisat)] + check_from_iter_into_iter_contents_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_from_iter_into_iter_contents_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_from_iter_into_iter_contents_nonzero => NonZero, +} + +gen_harnesses! { check_from_iter_into_iter_advanced: + #[kani::solver(minisat)] + check_from_iter_into_iter_advanced_u8 => u8, + #[kani::solver(minisat)] + check_from_iter_into_iter_advanced_overaligned => OverAligned, + #[kani::solver(minisat)] + check_from_iter_into_iter_advanced_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_from_iter_into_iter_advanced_char_u8 => (char, u8), + #[kani::solver(minisat)] + check_from_iter_into_iter_advanced_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_from_iter_into_iter_advanced_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_from_iter_into_iter_advanced_nonzero => NonZero, +} + +gen_harnesses! { check_from_iter_into_iter_advanced_witness: + check_from_iter_into_iter_advanced_witness_u8 => u8, + check_from_iter_into_iter_advanced_witness_overaligned => OverAligned, + check_from_iter_into_iter_advanced_witness_padded_niche => PaddedNiche, + check_from_iter_into_iter_advanced_witness_char_u8 => (char, u8), + check_from_iter_into_iter_advanced_witness_drop_tracker => DropTracker, + check_from_iter_into_iter_advanced_witness_drop_niche => DropNiche, + check_from_iter_into_iter_advanced_witness_nonzero => NonZero, +} + +// --------------------------------------------------------------------------- +// `SpecFromIterNested::from_iter` (default, non-`TrustedLen` impl) +// --------------------------------------------------------------------------- + +// Non-zero sentinel initializers for modular `extend_desugared` handoff checks (kani#5088). +static mut EXTEND_CALLED: bool = true; +static mut EXTEND_PRE_LEN: usize = 0x5A5A_5A5A_5A5A_5A60; +static mut EXTEND_PRE_CAP: usize = 0x5A5A_5A5A_5A5A_5A61; +static mut EXTEND_HINT_LOWER: usize = 0x5A5A_5A5A_5A5A_5A62; + +fn reset_extend_trace() { + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { + EXTEND_CALLED = false; + EXTEND_PRE_LEN = 0; + EXTEND_PRE_CAP = 0; + EXTEND_HINT_LOWER = 0; + } +} + +/// Modular verification stub for `Vec::extend_desugared` (a Challenge 23 +/// function outside Ch. 24's 22-function scope). Verifies every handoff +/// precondition established by `SpecFromIterNested::from_iter` (`self.len() == 1`, +/// `self.capacity() >= 1`) so `SpecFromIterNested::from_iter` itself is verified +/// completely unbounded for arbitrary remaining iterator counts (`0..=usize::MAX`) +/// and arbitrary `size_hint` lower bounds (`0..=usize::MAX`). +impl Vec { + fn extend_desugared_symbolic_stub>(&mut self, iterator: I) { + assert!(self.len() == 1); + assert!(self.capacity() >= 1); + let (lower, _) = iterator.size_hint(); + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { + EXTEND_CALLED = true; + EXTEND_PRE_LEN = self.len(); + EXTEND_PRE_CAP = self.capacity(); + EXTEND_HINT_LOWER = lower; + } + } +} + +/// Unbounded non-`TrustedLen` iterator whose remaining count `rem` ranges over +/// all of `0..=usize::MAX` and whose `size_hint` lower bound is completely +/// unconstrained (`0..=usize::MAX`). +struct SymbolicIter { + rem: usize, + first_tag: u8, + lower: usize, + phantom: PhantomData, +} + +impl Iterator for SymbolicIter { + type Item = T; + fn next(&mut self) -> Option { + if self.rem == 0 { + None + } else { + self.rem -= 1; + Some(T::from_byte(self.first_tag)) + } + } + fn size_hint(&self) -> (usize, Option) { + (self.lower, None) + } +} + +/// Unbounded modular verification of `SpecFromIterNested::from_iter` (default +/// impl) for arbitrary remaining count `rem: 0..=usize::MAX` and arbitrary +/// `size_hint` lower bound up to CBMC's object bound (`MAX_ALLOCATION_BYTES` +/// for non-ZST, `usize::MAX` for ZST). Stubs only `Vec::extend_desugared` +/// (Challenge 23), while verifying 100% of `SpecFromIterNested::from_iter` +/// including `ptr::write`, `set_len(1)`, capacity computation, and +/// `SpecExtend::spec_extend` dispatch. +fn check_from_iter_nested_unbounded_mode() { + let tag1 = T::any_byte(); + let rem: usize = kani::any(); + let lower: usize = kani::any(); + let initial = cmp::max(RawVec::::MIN_NON_ZERO_CAP, lower.saturating_add(1)); + if !T::IS_ZST { + kani::assume( + initial.checked_mul(mem::size_of::()).is_some_and(|b| b <= MAX_ALLOCATION_BYTES), + ); + } + let iter = SymbolicIter:: { rem, first_tag: tag1, lower, phantom: PhantomData }; + reset_drops(); + reset_extend_trace(); + let v = as SpecFromIterNested>>::from_iter(iter); + // Hoist conditional postconditions into a single top-level `assert!(ok)` so + // `--assertion-reach-checks` never generates an unbounded witness trace + // inside `rem != 0` (`kani#4905`). + let mut ok = drops() == 0; + if rem == 0 { + // SAFETY: Single-threaded harness. + ok &= unsafe { !EXTEND_CALLED } + && v.len() == 0 + && v.capacity() == if T::IS_ZST { usize::MAX } else { 0 }; + } else { + // SAFETY: Single-threaded harness. + ok &= unsafe { + EXTEND_CALLED + && EXTEND_PRE_LEN == 1 + && EXTEND_PRE_CAP == v.capacity() + && EXTEND_HINT_LOWER == lower + }; + ok &= v.len() == 1 && (T::IS_ZST || v.capacity() >= initial); + if M::CHECK_CONTENTS && !T::IS_ZST { + // SAFETY: `0 < 1 == v.len()`, initialized via typed `ptr::write`. + ok &= unsafe { tag_matches(v.as_ptr(), tag1) }; + } + } + assert!(ok); + // Cap cover-witness storage in bytes (`<= WITNESS_CAP * 16`, ~135 KB) so + // `LargeElem` (`size_of == 2048`) cover traces stay well within CBMC memory + // limits (`kani#4905`); the safety proof itself remains unbounded up to `MAX_ALLOCATION_BYTES`. + let small = T::IS_ZST + || (initial <= WITNESS_CAP + && initial.saturating_mul(mem::size_of::()) <= WITNESS_CAP * 16); + let deep_lower = if T::IS_ZST { 4096 } else { (4096 / mem::size_of::()).max(4) }; + kani::cover(rem == 0, "empty iterator"); + kani::cover(rem == 1 && lower == 0, "single element, min non-zero capacity"); + kani::cover(small && rem > 4096 && lower > deep_lower, "deep unbounded iterator and size_hint"); + T::when_zst(|| kani::cover(rem == usize::MAX && lower == usize::MAX, "saturating size_hint")); + finish::(v); +} + +fn check_from_iter_nested_unbounded() { + check_from_iter_nested_unbounded_mode::() +} + +fn check_from_iter_nested_unbounded_safety() { + check_from_iter_nested_unbounded_mode::() +} + +gen_harnesses! { check_from_iter_nested_unbounded: + #[kani::solver(minisat)] + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_u8 => u8, + #[kani::solver(minisat)] + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_overaligned => OverAligned, + #[kani::solver(minisat)] + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_char_u8 => (char, u8), + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_zst => (), + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_aligned_zst => AlignedZst, + #[kani::solver(minisat)] + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_drop_tracker => DropTracker, + #[kani::solver(minisat)] + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_drop_niche => DropNiche, + #[kani::solver(minisat)] + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_nonzero => NonZero, +} + +gen_harnesses! { check_from_iter_nested_unbounded_safety: + #[kani::solver(minisat)] + #[kani::stub(Vec::extend_desugared, Vec::extend_desugared_symbolic_stub)] + check_from_iter_nested_unbounded_large => LargeElem, +} + +/// Non-`TrustedLen` iterator yielding 0, 1, or 2 elements using two explicit +/// booleans for unstubbed end-to-end integration evidence through real +/// `Vec::extend_desugared` without any `#[kani::unwind]` attribute. +struct TailTwo { + first_pending: bool, + second_pending: bool, + first_tag: u8, + second_tag: u8, + lower: usize, + phantom: PhantomData, +} + +impl Iterator for TailTwo { + type Item = T; + fn next(&mut self) -> Option { + if mem::replace(&mut self.first_pending, false) { + Some(T::from_byte(self.first_tag)) + } else if mem::replace(&mut self.second_pending, false) { + Some(T::from_byte(self.second_tag)) + } else { + None + } + } + fn size_hint(&self) -> (usize, Option) { + (self.lower, None) + } +} + +/// Unstubbed end-to-end integration evidence for `SpecFromIterNested::from_iter` +/// exercising 0, 1, and 2 elements directly through real `Vec::extend_desugared` +/// with an arbitrary (possibly lying) `size_hint` lower bound. +fn check_from_iter_nested() { + let tag1 = T::any_byte(); + let tag2 = T::any_distinct_from(tag1); + let first_pending: bool = kani::any(); + let second_pending: bool = if first_pending { kani::any() } else { false }; + let count: usize = usize::from(first_pending) + usize::from(second_pending); + let lower: usize = kani::any(); + let iter = TailTwo:: { + first_pending, + second_pending, + first_tag: tag1, + second_tag: tag2, + lower, + phantom: PhantomData, + }; + let initial = cmp::max(RawVec::::MIN_NON_ZERO_CAP, lower.saturating_add(1)); + if !T::IS_ZST { + // Keep both initial allocation and potential 2nd-element growth (`<= 2 * initial`) + // inside CBMC's object bound (`BUDGET`). + kani::assume(initial.checked_mul(mem::size_of::()).is_some_and(|b| b <= BUDGET)); + } + reset_drops(); + let v = as SpecFromIterNested>>::from_iter(iter); + assert!(drops() == 0); + assert!(v.len() == count); + assert!(v.len() <= v.capacity()); + if count == 0 { + assert!(v.capacity() == if T::IS_ZST { usize::MAX } else { 0 }); + } else { + assert!(T::IS_ZST || v.capacity() >= initial); + if !T::IS_ZST { + // SAFETY: `0 < count == v.len()`. + assert!(unsafe { tag_matches(v.as_ptr(), tag1) }); + if count == 2 { + // SAFETY: `1 < count == v.len()`. + assert!(unsafe { tag_matches(v.as_ptr().add(1), tag2) }); + } + } + } + let small = witness_ok::(initial); + kani::cover(count == 0, "empty iterator"); + kani::cover(count == 1 && lower == 0, "single element, min non-zero capacity"); + kani::cover(count == 2 && lower == 0, "two elements, spec_extend tail reached"); + kani::cover(small && count >= 1 && lower > 4096, "large size_hint"); + T::when_zst(|| kani::cover(count == 2 && lower == usize::MAX, "saturating size_hint")); + finish::(v); +} + +gen_harnesses! { check_from_iter_nested: + #[kani::solver(minisat)] + check_from_iter_nested_u8 => u8, + #[kani::solver(minisat)] + check_from_iter_nested_overaligned => OverAligned, + #[kani::solver(minisat)] + check_from_iter_nested_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_from_iter_nested_char_u8 => (char, u8), + check_from_iter_nested_zst => (), + check_from_iter_nested_aligned_zst => AlignedZst, + #[kani::solver(minisat)] + check_from_iter_nested_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_from_iter_nested_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_from_iter_nested_nonzero => NonZero, +} + +/// Inductive-step verification of the default collection tail (`extend_desugared`) +/// from an arbitrary prefix length `len <= cap` with an arbitrary `size_hint` +/// lower bound. Unbounded `check_from_iter_nested_tail_step_*` harnesses +/// (`SafetyOnly`, up to `BUDGET`) prove full memory safety, bounds, alignment, +/// spare-capacity vs. reallocation-growth transitions, length, capacity, and +/// zero spurious drops across all symbolic sizes with 100% validly initialized +/// live prefixes `[0..len]` (avoiding CBMC's `--json-ui` symbolic-array trace +/// OOM `kani#4905`); paired `_contents_*` harnesses (`FullContents`, up to +/// `EXTEND_CONTENTS_CAP = 4352` elements, `> 4096` deep) prove universally +/// quantified prefix preservation at symbolic index `j` and appended element +/// integrity at `len` while keeping padding bytes genuinely uninitialized. +/// (A mechanized loop invariant over `extend_desugared` is blocked by CBMC +/// forbidding dynamic allocation/reallocation inside contracted loops, kani#3587.) +fn check_from_iter_nested_tail_step_mode(budget: usize, use_up_to: bool) { + let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; + let prefix_fill = T::any_fill(); + let item = T::any_distinct_from(prefix_fill); + let mut v = any_vec_opt::(budget, use_up_to); + let (len, cap) = (v.len(), v.capacity()); + let j = if len > 0 { pick(len - 1) } else { 0 }; + if M::CHECK_CONTENTS && !T::IS_ZST && len > 0 { + // SAFETY: `j < len <= cap`; typed `mark` resets padding bytes to genuinely uninit. + unsafe { mark(v.as_mut_ptr().add(j), prefix_fill) }; + } + let lower: usize = pick(usize::MAX); + kani::assume(len < usize::MAX); + if !T::IS_ZST && len == cap { + kani::assume( + len.checked_add(lower) + .and_then(|n| n.checked_add(1)) + .and_then(|n| n.checked_mul(mem::size_of::())) + .is_some_and(|b| b <= MAX_ALLOCATION_BYTES), + ); + } + let iter = TailTwo:: { + first_pending: true, + second_pending: false, + first_tag: item, + second_tag: item, + lower, + phantom: PhantomData, + }; + reset_drops(); + v.spec_extend(iter); + let mut ok = drops() == 0 && v.len() == len + 1 && v.len() <= v.capacity(); + if M::CHECK_CONTENTS && !T::IS_ZST { + // SAFETY: `len < v.len()`. + ok &= unsafe { tag_matches(v.as_ptr().add(len), item) }; + if len > 0 { + // SAFETY: `j < len < v.len()`. + ok &= unsafe { tag_matches(v.as_ptr().add(j), prefix_fill) }; + } + } + assert!(ok); + let small_tail = T::IS_ZST + || (cap <= WITNESS_CAP && cap.saturating_mul(mem::size_of::()) <= WITNESS_CAP * 16); + let deep_len = if T::IS_ZST { + 4096 + } else if M::CHECK_CONTENTS { + 4096 + } else { + (4096 / mem::size_of::()).max(4) + }; + T::when_non_zst(|| { + kani::cover( + small_tail && len > deep_len && len == cap && lower <= 64, + "deep tail step with growth", + ); + kani::cover( + small_tail && len == cap && lower > 0 && lower <= 64, + "growth sized by size_hint", + ); + }); + kani::cover(small_tail && len > deep_len && len < cap, "deep tail step with spare capacity"); + finish::(v); +} + +fn check_from_iter_nested_tail_step() { + check_from_iter_nested_tail_step_mode::(BUDGET, !T::IS_ZST) +} + +fn check_from_iter_nested_tail_step_contents() { + check_from_iter_nested_tail_step_mode::( + EXTEND_CONTENTS_CAP * mem::size_of::(), + true, + ) +} + +gen_harnesses! { check_from_iter_nested_tail_step: + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_u8 => u8, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_overaligned => OverAligned, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_char_u8 => (char, u8), + check_from_iter_nested_tail_step_zst => (), + check_from_iter_nested_tail_step_aligned_zst => AlignedZst, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_nonzero => NonZero, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_large => LargeElem, +} + +gen_harnesses! { check_from_iter_nested_tail_step_contents: + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_contents_u8 => u8, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_contents_overaligned => OverAligned, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_contents_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_contents_char_u8 => (char, u8), + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_contents_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_contents_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_from_iter_nested_tail_step_contents_nonzero => NonZero, +} + +// --------------------------------------------------------------------------- +// `IntoIter` accessors and single-step iteration +// --------------------------------------------------------------------------- + +/// An `IntoIter` with symbolic capacity, length, optional front advance, +/// and caller-supplied allocator `alloc`, together with its remaining element +/// count `n = len - adv`. +/// +/// **Only the live remaining slice `[adv..len]` is initialized** with `fill`; +/// the consumed front `[0..adv]` and spare/consumed back `[len..cap]` remain +/// genuinely uninitialized so `-Z uninit-checks` catches out-of-range reads. +fn any_into_iter_in_mode( + max_bytes: usize, + fill: u8, + may_advance: bool, + alloc: A, + use_up_to: bool, +) -> (IntoIter, usize) { + let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; + let (buf, cap, len, adv) = if T::IS_ZST { + // A ZST `IntoIter` encodes its length as the byte distance from `ptr` + // to `end`. Kani models pointer offsets in 52 bits (`--object-bits 12`), + // so ZST `IntoIter` lengths are bounded by `MAX_ALLOCATION_BYTES`. + let n = pick(MAX_ALLOCATION_BYTES); + (NonNull::::dangling(), usize::MAX, n, 0) + } else { + let cap = pick(max_bytes / mem::size_of::()); + let len = pick(cap); + let adv = if may_advance { pick(len) } else { 0 }; + let n = len - adv; + let buf = if cap == 0 { + NonNull::::dangling() + } else { + let layout = crate::alloc::Layout::array::(cap).unwrap(); + // SAFETY: `cap > 0` and `size_of::() > 0`, so `layout.size() > 0`. + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + if n > 0 { + // SAFETY: `adv + n == len <= cap`, so `[adv..len]` lies inside the + // allocated buffer; `[0..adv]` and `[len..cap]` stay uninitialized. + unsafe { + core::intrinsics::write_bytes( + p.add(adv * mem::size_of::()), + fill, + n * mem::size_of::(), + ); + } + } + // SAFETY: `p` is non-null and properly aligned for `T`. + unsafe { NonNull::new_unchecked(p.cast::()) } + }; + (buf, cap, len, adv) + }; + let n = len - adv; + let (ptr, end) = if T::IS_ZST { + (buf, buf.as_ptr().cast_const().wrapping_byte_add(n)) + } else { + // SAFETY: `adv <= len <= cap`, both within the allocation (or dangling for `cap == 0`). + unsafe { (buf.add(adv), buf.as_ptr().add(len) as *const T) } + }; + let it = IntoIter { buf, phantom: PhantomData, cap, alloc: ManuallyDrop::new(alloc), ptr, end }; + (it, n) +} + +fn any_into_iter_in( + max_bytes: usize, + fill: u8, + may_advance: bool, + alloc: A, +) -> (IntoIter, usize) { + any_into_iter_in_mode(max_bytes, fill, may_advance, alloc, false) +} + +fn any_into_iter(max_bytes: usize, fill: u8, may_advance: bool) -> (IntoIter, usize) { + any_into_iter_in(max_bytes, fill, may_advance, Global) +} + +/// Marks the first, last, and one universally quantified interior element `mid` +/// (`0 < mid < n - 1`, when `n > 2`) via typed `ptr::write` (`mark`), resetting +/// padding bytes on every marked slot to genuinely uninitialized. +fn any_into_iter_marked_in( + fill: u8, + first: u8, + last: u8, + alloc: A, +) -> (IntoIter, usize, usize) { + let (it, n) = any_into_iter_live_in::(MAX_ALLOCATION_BYTES, true, alloc); + let mid = if n > 2 { 1 + down_from(n - 3) } else { 0 }; + if !T::IS_ZST && n > 0 { + // SAFETY: `0`, `n - 1`, and `mid` (when `n > 2`) are distinct live slots. + unsafe { + mark(it.ptr.as_ptr(), first); + if n > 1 { + mark(it.ptr.as_ptr().add(n - 1), last); + } + if n > 2 { + mark(it.ptr.as_ptr().add(mid), fill); + } + } + } + (it, n, mid) +} + +/// Checks that the universally quantified interior element `mid` (`0 < mid < n - 1`) +/// of an `n`-element view starting at `p` still holds `fill`. +fn check_middle_at(p: *const T, n: usize, mid: usize, fill: u8, deep_ok: bool) { + if T::IS_ZST { + return; + } + if n > 2 { + // SAFETY: `0 < mid < n - 1 < n` is a live marked element. + assert!(unsafe { tag_matches(p.add(mid), fill) }); + T::when_non_zst(|| kani::cover(deep_ok && mid > 4096, "deep element checked")); + } +} + +/// `IntoIter::size_hint` (and hence `len`) is exact. +fn check_into_iter_size_hint() { + let (it, n) = any_into_iter_live_in::(MAX_ALLOCATION_BYTES, true, Global); + let small = witness_ok::(it.cap); + assert!(it.size_hint() == (n, Some(n))); + kani::cover(n == 0, "empty"); + kani::cover(small && n > 4096, "deep"); + finish::(it); +} + +/// `IntoIter::as_slice`: the remaining elements, in place. In `FullContents` mode +/// marks a universally quantified symbolic element `k in 0..n`; in `SafetyOnly` +/// mode (`NonPow2`, where `offset_from_unsigned` emits a 64-bit `/ 3` circuit) +/// marks slot `0` to avoid an extra symbolic `* 3` byte-array index while still +/// verifying full unbounded `s.len() == n`, pointer identity, and typed read. +fn check_into_iter_as_slice_mode() { + let tag = T::any_byte(); + let (it, n) = any_into_iter_live_in::(MAX_ALLOCATION_BYTES, true, Global); + let k = if M::CHECK_CONTENTS && n > 0 { down_from(n - 1) } else { 0 }; + if !T::IS_ZST && n > 0 { + // SAFETY: `k < n == it.len()`; typed write leaves padding genuinely uninit. + unsafe { mark(it.ptr.as_ptr().add(k), tag) }; + } + let small = witness_ok::(it.cap); + let s = it.as_slice(); + assert!(s.len() == n); + assert!(s.as_ptr() == it.ptr.as_ptr() as *const T); + if !T::IS_ZST && n > 0 { + // SAFETY: `k < n == s.len()`. + assert!(unsafe { tag_matches(s.as_ptr().add(k), tag) }); + M::when_contents(|| { + T::when_non_zst(|| kani::cover(small && k > 4096, "deep element checked")); + }); + } + kani::cover(n == 0, "empty"); + kani::cover(small && n > 4096, "deep"); + finish::(it); +} + +fn check_into_iter_as_slice() { + check_into_iter_as_slice_mode::() +} + +/// `IntoIter::as_mut_slice`: the remaining elements, in place and writable; +/// a write through it is observed by `next` without aliasing violations. +fn check_into_iter_as_mut_slice_mode() { + let (tag, new_tag) = (T::any_byte(), T::any_byte()); + let (mut it, n) = any_into_iter_live_in::(MAX_ALLOCATION_BYTES, true, Global); + let k = if M::CHECK_CONTENTS && n > 0 { down_from(n - 1) } else { 0 }; + if !T::IS_ZST && n > 0 { + // SAFETY: `k < n == it.len()`; typed write leaves padding genuinely uninit. + unsafe { mark(it.ptr.as_ptr().add(k), tag) }; + } + let small = witness_ok::(it.cap); + let ptr = it.ptr.as_ptr(); + let s = it.as_mut_slice(); + assert!(s.len() == n); + assert!(s.as_mut_ptr() == ptr); + let p = s.as_mut_ptr(); + if !T::IS_ZST && n > 0 { + // Check untouched slot `k` BEFORE mutating slot `0` and calling + // `it.next()`, so `s`'s mutable borrow ends cleanly first. + // SAFETY: `k < n == s.len()`. + assert!(unsafe { tag_matches(p.add(k) as *const T, tag) }); + M::when_contents(|| { + T::when_non_zst(|| kani::cover(small && k > 4096, "deep element checked")); + }); + // SAFETY: `p` is valid for writes and `new_tag` is valid for `T`. + unsafe { mark(p, new_tag) }; + let x = it.next().unwrap(); + assert!(x.matches_tag(new_tag)); + finish::(x); + } + kani::cover(n == 0, "empty"); + kani::cover(small && n > 4096, "deep"); + finish::(it); +} + +fn check_into_iter_as_mut_slice() { + check_into_iter_as_mut_slice_mode::() +} + +/// `IntoIter::next`: yields the first remaining element and shrinks by one. +fn check_into_iter_next() { + let first = T::any_byte(); + let (mut it, n) = any_into_iter_live_in::(MAX_ALLOCATION_BYTES, true, Global); + if !T::IS_ZST && n > 0 { + // SAFETY: `0 < n == it.len()`; typed write leaves padding genuinely uninit. + unsafe { mark(it.ptr.as_ptr(), first) }; + } + let small = witness_ok::(it.cap); + let old_ptr = it.ptr; + reset_drops(); + match it.next() { + None => assert!(n == 0), + Some(x) => { + assert!(n > 0); + if !T::IS_ZST { + assert!(x.matches_tag(first)); + // SAFETY: `old_ptr + 1 <= end` within the allocation. + assert!(it.ptr == unsafe { old_ptr.add(1) }); + } else { + assert!(it.ptr == old_ptr); + } + finish::(x); + } + } + assert!(drops() == 0); + assert!(it.len() == n.saturating_sub(1)); + kani::cover(n == 0, "exhausted"); + kani::cover(n == 1, "last element"); + kani::cover(small && n > 4096, "deep"); + finish::(it); +} + +/// `IntoIter::next_back`: yields the last remaining element and shrinks by one. +fn check_into_iter_next_back() { + let last = T::any_byte(); + let (mut it, n) = any_into_iter_live_in::(MAX_ALLOCATION_BYTES, true, Global); + if !T::IS_ZST && n > 0 { + // SAFETY: `n - 1 < n == it.len()`; typed write leaves padding genuinely uninit. + unsafe { mark(it.ptr.as_ptr().add(n - 1), last) }; + } + let small = witness_ok::(it.cap); + let old_ptr = it.ptr; + reset_drops(); + match it.next_back() { + None => assert!(n == 0), + Some(x) => { + assert!(n > 0); + if !T::IS_ZST { + assert!(x.matches_tag(last)); + } + finish::(x); + } + } + assert!(drops() == 0); + assert!(it.ptr == old_ptr); + assert!(it.len() == n.saturating_sub(1)); + kani::cover(n == 0, "exhausted"); + kani::cover(n == 1, "last element"); + kani::cover(small && n > 4096, "deep"); + finish::(it); +} + +/// `IntoIter::__iterator_get_unchecked` (requires `T: Copy`): verifies the +/// `#[requires(i < self.len())]` contract via `#[kani::proof_for_contract]`, +/// checks that the element at relative index `i` is returned without advancing, +/// and drops `it` (verifying `TrustedRandomAccess`'s drop-safety requirement). +fn check_into_iter_get_unchecked() { + let (fill, first, last) = markers_for::(); + let (mut it, n) = any_into_iter_live_in::(MAX_ALLOCATION_BYTES, true, Global); + let small = witness_ok::(it.cap); + let i: usize = kani::any(); + if !T::IS_ZST && i < n { + let tag = if i == 0 { + first + } else if i == n - 1 { + last + } else { + fill + }; + // SAFETY: `i < n == it.len()`; typed write leaves padding genuinely uninit. + unsafe { mark(it.ptr.as_ptr().add(i), tag) }; + } + let old_ptr = it.ptr; + // SAFETY: Checked by `#[kani::proof_for_contract]` against `#[requires(i < self.len())]`. + let x = unsafe { Iterator::__iterator_get_unchecked(&mut it, i) }; + assert!(i < n); + assert!(it.ptr == old_ptr); + assert!(it.len() == n); + if !T::IS_ZST { + let want = if i == 0 { + first + } else if i == n - 1 { + last + } else { + fill + }; + assert!(x.matches_tag(want)); + } + kani::cover(i == 0, "first"); + kani::cover(n > 1 && i == n - 1, "last"); + kani::cover(small && i > 4096, "deep"); + // `T: Copy` implies `!needs_drop::()`, so dropping `it` checks deallocation in O(1). + drop(it); +} + +gen_harnesses! { check_into_iter_size_hint: + check_into_iter_size_hint_u8 => u8, + check_into_iter_size_hint_overaligned => OverAligned, + check_into_iter_size_hint_padded_niche => PaddedNiche, + check_into_iter_size_hint_char_u8 => (char, u8), + check_into_iter_size_hint_nonpow2 => NonPow2, + check_into_iter_size_hint_zst => (), + check_into_iter_size_hint_aligned_zst => AlignedZst, + check_into_iter_size_hint_drop_tracker => DropTracker, + check_into_iter_size_hint_drop_niche => DropNiche, + check_into_iter_size_hint_nonzero => NonZero, +} + +gen_harnesses! { check_into_iter_as_slice: + check_into_iter_as_slice_u8 => u8, + check_into_iter_as_slice_overaligned => OverAligned, + check_into_iter_as_slice_padded_niche => PaddedNiche, + check_into_iter_as_slice_char_u8 => (char, u8), + check_into_iter_as_slice_zst => (), + check_into_iter_as_slice_aligned_zst => AlignedZst, + check_into_iter_as_slice_drop_tracker => DropTracker, + check_into_iter_as_slice_drop_niche => DropNiche, + check_into_iter_as_slice_nonzero => NonZero, +} + +#[kani::proof] +fn check_into_iter_as_slice_nonpow2() { + check_into_iter_as_slice_mode::(); +} + +gen_harnesses! { check_into_iter_as_mut_slice: + check_into_iter_as_mut_slice_u8 => u8, + check_into_iter_as_mut_slice_overaligned => OverAligned, + check_into_iter_as_mut_slice_padded_niche => PaddedNiche, + check_into_iter_as_mut_slice_char_u8 => (char, u8), + check_into_iter_as_mut_slice_zst => (), + check_into_iter_as_mut_slice_aligned_zst => AlignedZst, + check_into_iter_as_mut_slice_drop_tracker => DropTracker, + check_into_iter_as_mut_slice_drop_niche => DropNiche, + check_into_iter_as_mut_slice_nonzero => NonZero, +} + +#[kani::proof] +fn check_into_iter_as_mut_slice_nonpow2() { + check_into_iter_as_mut_slice_mode::(); +} + +gen_harnesses! { check_into_iter_next: + check_into_iter_next_u8 => u8, + check_into_iter_next_overaligned => OverAligned, + check_into_iter_next_padded_niche => PaddedNiche, + check_into_iter_next_char_u8 => (char, u8), + check_into_iter_next_nonpow2 => NonPow2, + check_into_iter_next_zst => (), + check_into_iter_next_aligned_zst => AlignedZst, + check_into_iter_next_drop_tracker => DropTracker, + check_into_iter_next_drop_niche => DropNiche, + check_into_iter_next_nonzero => NonZero, +} + +gen_harnesses! { check_into_iter_next_back: + check_into_iter_next_back_u8 => u8, + check_into_iter_next_back_overaligned => OverAligned, + check_into_iter_next_back_padded_niche => PaddedNiche, + check_into_iter_next_back_char_u8 => (char, u8), + check_into_iter_next_back_nonpow2 => NonPow2, + check_into_iter_next_back_zst => (), + check_into_iter_next_back_aligned_zst => AlignedZst, + check_into_iter_next_back_drop_tracker => DropTracker, + check_into_iter_next_back_drop_niche => DropNiche, + check_into_iter_next_back_nonzero => NonZero, +} + +// `__iterator_get_unchecked` requires `T: Copy` (`NonDrop`), so `DropTracker` is +// not a valid instantiation. Each harness verifies the `#[requires(i < self.len())]` +// contract directly via `#[kani::proof_for_contract]`. +#[kani::proof_for_contract( as core::iter::Iterator>::__iterator_get_unchecked)] +fn check_into_iter_get_unchecked_u8() { + check_into_iter_get_unchecked::(); +} + +#[kani::proof_for_contract( as core::iter::Iterator>::__iterator_get_unchecked)] +fn check_into_iter_get_unchecked_overaligned() { + check_into_iter_get_unchecked::(); +} + +#[kani::proof_for_contract( as core::iter::Iterator>::__iterator_get_unchecked)] +fn check_into_iter_get_unchecked_padded_niche() { + check_into_iter_get_unchecked::(); +} + +#[kani::proof_for_contract( as core::iter::Iterator>::__iterator_get_unchecked)] +fn check_into_iter_get_unchecked_char_u8() { + check_into_iter_get_unchecked::<(char, u8)>(); +} + +#[kani::proof_for_contract( as core::iter::Iterator>::__iterator_get_unchecked)] +fn check_into_iter_get_unchecked_zst() { + check_into_iter_get_unchecked::<()>(); +} + +#[kani::proof_for_contract( as core::iter::Iterator>::__iterator_get_unchecked)] +fn check_into_iter_get_unchecked_aligned_zst() { + check_into_iter_get_unchecked::(); +} + +#[kani::proof_for_contract(> as core::iter::Iterator>::__iterator_get_unchecked)] +fn check_into_iter_get_unchecked_nonzero() { + check_into_iter_get_unchecked::>(); +} + +// --------------------------------------------------------------------------- +// `SpecExtend<&'a T, slice::Iter<'a, T>>::spec_extend` +// --------------------------------------------------------------------------- + +/// `SpecExtend<&'a T, slice::Iter<'a, T>>::spec_extend`: copies all remaining +/// elements from a symbolic slice iterator into `dst`, keeping `len <= cap`, +/// verifying memory safety unbounded up to `BUDGET` (`SafetyOnly`) and +/// universally quantified element integrity + source immutability up to +/// `EXTEND_CONTENTS_CAP = 4352` elements (`FullContents`, `> 4096` deep, avoiding +/// `kani#4905` `` VLA JSON trace serialization OOM). +fn spec_extend_slice_iter(budget: usize) { + let use_up_to = !T::IS_ZST; + let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; + let tag = T::any_byte(); + let mut dst = any_vec_opt::(budget, use_up_to); + let mut src = any_vec_opt::(budget, use_up_to); + let adv = pick(src.len()); + let count = src.len().wrapping_sub(adv); + let (old_len, old_cap, src_cap) = (dst.len(), dst.capacity(), src.capacity()); + let check_dst: bool = kani::any(); + let i = if check_dst && old_len > 0 { pick(old_len.saturating_sub(1)) } else { 0 }; + let k = if !check_dst && count > 0 { pick(count.saturating_sub(1)) } else { 0 }; + if M::CHECK_CONTENTS && !T::IS_ZST { + if check_dst { + if old_len > 0 { + // SAFETY: `i < old_len <= old_cap`; typed write leaves padding uninit. + unsafe { mark(dst.as_mut_ptr().add(i), tag) }; + } + } else if count > 0 { + // SAFETY: `adv + k < src.len()`. + unsafe { mark(src.as_mut_ptr().add(adv.wrapping_add(k)), tag) }; + } + } + let tiny = |cap: usize| T::IS_ZST || cap <= 64; + let small_bytes = |cap: usize| { + T::IS_ZST + || (cap <= WITNESS_CAP && cap.saturating_mul(mem::size_of::()) <= WITNESS_CAP * 16) + }; + let (dst_ok, src_ok) = (small_bytes(old_cap), small_bytes(src_cap)); + let deep = if T::IS_ZST { 4096 } else { (4096 / mem::size_of::()).max(4) }; + if T::IS_ZST { + kani::assume(old_len.checked_add(count).is_some()); + } + let it: core::slice::Iter<'_, T> = src[adv..].iter(); + as SpecExtend<&T, core::slice::Iter<'_, T>>>::spec_extend(&mut dst, it); + let new_len = old_len.wrapping_add(count); + let mut ok = dst.len() == new_len && dst.len() <= dst.capacity(); + if M::CHECK_CONTENTS && !T::IS_ZST { + if check_dst { + if old_len > 0 { + // SAFETY: `i < old_len <= dst.len()`. + ok &= unsafe { tag_matches(dst.as_ptr().add(i), tag) }; + } + } else if count > 0 { + // SAFETY: `old_len + k < dst.len()`. + ok &= unsafe { tag_matches(dst.as_ptr().add(old_len.wrapping_add(k)), tag) }; + // Confirm immutable source slice was not modified. + // SAFETY: `adv + k < src.len()`. + ok &= unsafe { tag_matches(src.as_ptr().add(adv.wrapping_add(k)), tag) }; + } + } + assert!(ok); + if M::CHECK_CONTENTS { + M::when_contents(|| { + T::when_non_zst(|| { + kani::cover( + src_ok && tiny(old_cap) && !check_dst && count > 0 && k > 4096, + "deep moved element checked", + ); + }); + }); + } + kani::cover(tiny(old_cap) && tiny(src_cap) && adv > 0 && count > 0, "advanced slice iterator"); + kani::cover(src_ok && tiny(old_cap) && count > deep, "deep source"); + kani::cover(dst_ok && tiny(src_cap) && old_len > deep && count > 0, "deep destination"); + kani::cover(tiny(old_cap) && tiny(src_cap) && count == 0, "empty source"); + T::when_non_zst(|| { + kani::cover(tiny(old_cap) && tiny(src_cap) && new_len > old_cap, "destination had to grow"); + kani::cover( + tiny(old_cap) && tiny(src_cap) && count > 0 && new_len <= old_cap, + "nonempty append without growth", + ); + }); + // `TrivialClone` implies `!needs_drop::()`, so dropping both checks deallocation in O(1). + drop(dst); + drop(src); +} + +fn check_spec_extend_slice_iter() { + spec_extend_slice_iter::(BUDGET) +} + +fn check_spec_extend_slice_iter_contents() { + spec_extend_slice_iter::(EXTEND_CONTENTS_CAP * mem::size_of::()) +} + +// `SpecExtend<&T, slice::Iter>` requires `T: TrivialClone`, so `DropTracker` +// is not a valid instantiation. +gen_harnesses! { check_spec_extend_slice_iter: + #[kani::solver(minisat)] + check_spec_extend_slice_iter_u8 => u8, + #[kani::solver(minisat)] + check_spec_extend_slice_iter_overaligned => OverAlignedTc, + #[kani::solver(minisat)] + check_spec_extend_slice_iter_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_spec_extend_slice_iter_large => LargeElem, + check_spec_extend_slice_iter_zst => (), + check_spec_extend_slice_iter_aligned_zst => AlignedZst, + #[kani::solver(minisat)] + check_spec_extend_slice_iter_nonzero => NonZero, +} + +gen_harnesses! { check_spec_extend_slice_iter_contents: + #[kani::solver(minisat)] + check_spec_extend_slice_iter_contents_u8 => u8, + #[kani::solver(minisat)] + check_spec_extend_slice_iter_contents_overaligned => OverAlignedTc, + #[kani::solver(minisat)] + check_spec_extend_slice_iter_contents_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_spec_extend_slice_iter_contents_nonzero => NonZero, +} + +// --------------------------------------------------------------------------- +// `IntoIter::advance_by`, `advance_back_by`, `forget_allocation_drop_remaining`, `drop` +// --------------------------------------------------------------------------- + +// Non-zero sentinel initializers avoid Kani static/constant zero aliasing (kani#5088). +static mut LAST_DROP_PTR: usize = 0x5A5A_5A5A_5A5A_5A5B; +static mut LAST_DROP_LEN: usize = 0x5A5A_5A5A_5A5A_5A5C; + +fn reset_drop_trace() { + reset_drops(); + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { + LAST_DROP_PTR = 0; + LAST_DROP_LEN = 0; + } +} + +/// Modular verification summary for `core::ptr::drop_in_place::<[E]>`. +/// +/// The compiler synthesizes an unannotatable loop inside the drop glue for `[E]` +/// (`kani#5174`). Because `DropTracker`, `DropTracker8`, `DropZst`, and +/// `DropNiche` only increment `DROPS` without mutating `self` or panicking, +/// checking slice metadata (`ptr::metadata` — zero `transmute_unchecked`), full +/// slice read/write validity, element alignment, exact byte length, and a typed +/// symbolic element validity check plus `DROPS += count` is an exact sound +/// summary for arbitrary slice lengths. +/// +/// If a non-slice thin pointer (e.g., `ManuallyDrop::drop(&mut self.alloc)` on +/// a non-`Drop` allocator) ever hits this stub, it is verified writable and +/// asserted `!mem::needs_drop::()` without touching slice metadata; any +/// unexpected `Drop` thin pointer fails verification immediately. +/// +/// See `mod bounded_evidence` below for unstubbed verification against the real +/// compiler-synthesized drop glue on bounded lengths. +unsafe fn drop_slice_summary(to_drop: *mut T) { + if mem::size_of::<::Metadata>() == 0 { + // Thin pointer (e.g. `ManuallyDrop::drop(&mut self.alloc)` on a non-`Drop` + // allocator like `Global` or `StatefulAlloc`): verify writable and assert + // no drop glue is skipped. Any unexpected `Drop` thin pointer fails here. + assert!(kani::mem::can_write(to_drop)); + assert!(!mem::needs_drop::()); + return; + } + assert!(mem::size_of::<::Metadata>() == mem::size_of::()); + assert!(mem::needs_drop::()); + assert!(kani::mem::can_write(to_drop)); + assert!(kani::mem::can_dereference(to_drop as *const T)); + let meta = ptr::metadata(to_drop); + // SAFETY: Non-thin `IntoIter` drop targets are slices `*mut [E]` whose + // `Pointee::Metadata` is `usize` (element count); no fat-pointer layout + // assumption or `transmute_unchecked` is used. + let count: usize = unsafe { *(&meta as *const ::Metadata as *const usize) }; + let base_ptr = (to_drop as *const ()).cast::(); + let base_addr = base_ptr.addr(); + assert!(base_addr % mem::align_of::() == 0); + let sz = kani::mem::checked_size_of_raw(to_drop as *const T).unwrap(); + assert!(sz == count.checked_mul(mem::size_of::()).unwrap()); + if !E::IS_ZST && count > 0 { + let k: usize = kani::any_where(|&k: &usize| k < count); + let elem_ptr: *const E = base_ptr.wrapping_add(k); + // SAFETY: `k < count` lies within the verified readable slice `to_drop`; + // reading via `&E` validates `E`'s validity invariant (e.g. `DropNiche`) + // without touching padding bytes, and asserts the niche invariant explicitly. + let tag = unsafe { (*elem_ptr).tag_byte() }; + assert!(E::ALLOW_ZERO || tag != 0); + assert!(unsafe { (*elem_ptr).matches_tag(tag) }); + } + // SAFETY: Kani verification harnesses are single-threaded. + unsafe { + LAST_DROP_PTR = base_addr; + LAST_DROP_LEN = count; + DROPS += count; + } +} + +unsafe fn drop_tracker_slice_stub(to_drop: *mut T) { + // SAFETY: Delegates to `drop_slice_summary` for `DropTracker`. + unsafe { drop_slice_summary::(to_drop) }; +} + +unsafe fn drop_tracker8_slice_stub(to_drop: *mut T) { + // SAFETY: Delegates to `drop_slice_summary` for `DropTracker8`. + unsafe { drop_slice_summary::(to_drop) }; +} + +unsafe fn drop_zst_slice_stub(to_drop: *mut T) { + // SAFETY: Delegates to `drop_slice_summary` for `DropZst`. + unsafe { drop_slice_summary::(to_drop) }; +} + +unsafe fn drop_niche_slice_stub(to_drop: *mut T) { + // SAFETY: Delegates to `drop_slice_summary` for `DropNiche`. + unsafe { drop_slice_summary::(to_drop) }; +} + +fn check_into_iter_advance_by_impl(expect_drops: bool) { + let (fill, first, last) = markers_for::(); + let (mut it, len) = if expect_drops { + any_into_iter::(MAX_ALLOCATION_BYTES, fill, true) + } else { + any_into_iter_live_in::(MAX_ALLOCATION_BYTES, true, Global) + }; + let small = witness_ok::(it.cap); + let n: usize = kani::any(); + let step = len.min(n); + let rem = len - step; + let mid = if rem > 2 { 1 + down_from(rem - 3) } else { 0 }; + if !T::IS_ZST && rem > 0 { + // SAFETY: `step <= len - 1 < len`, so both remaining endpoints and `mid` are live. + unsafe { + mark(it.ptr.as_ptr().add(step), first); + if rem > 1 { + mark(it.ptr.as_ptr().add(len - 1), last); + } + if rem > 2 && !expect_drops { + mark(it.ptr.as_ptr().add(step + mid), fill); + } + } + } + let old_ptr = it.ptr; + let old_end = it.end; + reset_drop_trace(); + let res = it.advance_by(n); + match res { + Ok(()) => assert!(n <= len), + Err(missing) => assert!(n > len && missing.get() == n - len), + } + assert!(it.len() == rem); + if !T::IS_ZST { + // SAFETY: `step <= len` stays within the allocation. + assert!(it.ptr == unsafe { old_ptr.add(step) }); + assert!(it.end == old_end); + if rem > 0 { + // SAFETY: `rem > 0`, so first and last remaining elements are live. + assert!(unsafe { tag_matches(it.ptr.as_ptr() as *const T, first) }); + if rem > 1 { + // SAFETY: `rem - 1 < rem`. + assert!(unsafe { tag_matches(it.ptr.as_ptr().add(rem - 1) as *const T, last) }); + } + check_middle_at(it.ptr.as_ptr() as *const T, rem, mid, fill, small); + } + } else { + assert!(it.ptr == old_ptr); + } + if expect_drops { + assert!(drops() == step); + // SAFETY: Single-threaded harness. + assert!(unsafe { LAST_DROP_LEN } == step); + // SAFETY: Single-threaded harness. + assert!(unsafe { LAST_DROP_PTR } == old_ptr.as_ptr().addr()); + } else { + assert!(drops() == 0); + } + kani::cover(n == 0, "advance_by 0"); + kani::cover(n > 0 && n < len, "partial advance_by"); + kani::cover(len > 0 && n == len, "exact exhaustion"); + kani::cover(n > len, "advance_by past end"); + kani::cover(small && step > 4096, "deep advance_by"); + kani::cover(small && rem > 4096 && step > 0, "deep remaining after advance_by"); + finish::(it); +} + +fn check_into_iter_advance_by() { + check_into_iter_advance_by_impl::(false) +} + +fn check_into_iter_advance_back_by_impl(expect_drops: bool) { + let (fill, first, last) = markers_for::(); + let (mut it, len) = if expect_drops { + any_into_iter::(MAX_ALLOCATION_BYTES, fill, true) + } else { + any_into_iter_live_in::(MAX_ALLOCATION_BYTES, true, Global) + }; + let small = witness_ok::(it.cap); + let n: usize = kani::any(); + let step = len.min(n); + let rem = len - step; + let mid = if rem > 2 { 1 + down_from(rem - 3) } else { 0 }; + if !T::IS_ZST && rem > 0 { + // SAFETY: `rem - 1 < rem <= len`. + unsafe { + mark(it.ptr.as_ptr(), first); + if rem > 1 { + mark(it.ptr.as_ptr().add(rem - 1), last); + } + if rem > 2 && !expect_drops { + mark(it.ptr.as_ptr().add(mid), fill); + } + } + } + let old_ptr = it.ptr; + let old_end = it.end; + reset_drop_trace(); + let res = it.advance_back_by(n); + match res { + Ok(()) => assert!(n <= len), + Err(missing) => assert!(n > len && missing.get() == n - len), + } + assert!(it.len() == rem); + assert!(it.ptr == old_ptr); + if !T::IS_ZST { + // SAFETY: `step <= len`, so `old_end.sub(step) >= old_ptr`. + assert!(it.end == unsafe { old_end.sub(step) }); + if rem > 0 { + // SAFETY: `rem > 0`. + assert!(unsafe { tag_matches(it.ptr.as_ptr() as *const T, first) }); + if rem > 1 { + // SAFETY: `rem - 1 < rem`. + assert!(unsafe { tag_matches(it.ptr.as_ptr().add(rem - 1) as *const T, last) }); + } + check_middle_at(it.ptr.as_ptr() as *const T, rem, mid, fill, small); + } + } + if expect_drops { + assert!(drops() == step); + // SAFETY: Single-threaded harness. + assert!(unsafe { LAST_DROP_LEN } == step); + if T::IS_ZST { + // For ZSTs, `advance_back_by` drops via `NonNull::::dangling()` (aligned). + // SAFETY: Single-threaded harness. + assert!(unsafe { LAST_DROP_PTR } == NonNull::::dangling().as_ptr().addr()); + } else { + // SAFETY: Single-threaded harness; `old_end.sub(step)` is in-bounds. + assert!(unsafe { LAST_DROP_PTR } == unsafe { old_end.sub(step) }.addr()); + } + } else { + assert!(drops() == 0); + } + kani::cover(n == 0, "advance_back_by 0"); + kani::cover(n > 0 && n < len, "partial advance_back_by"); + kani::cover(len > 0 && n == len, "exact exhaustion"); + kani::cover(n > len, "advance_back_by past end"); + kani::cover(small && step > 4096, "deep advance_back_by"); + kani::cover(small && rem > 4096 && step > 0, "deep remaining after advance_back_by"); + finish::(it); +} + +fn check_into_iter_advance_back_by() { + check_into_iter_advance_back_by_impl::(false) +} + +gen_harnesses! { check_into_iter_advance_by: + check_into_iter_advance_by_u8 => u8, + check_into_iter_advance_by_overaligned => OverAligned, + check_into_iter_advance_by_padded_niche => PaddedNiche, + check_into_iter_advance_by_char_u8 => (char, u8), + check_into_iter_advance_by_zst => (), + check_into_iter_advance_by_aligned_zst => AlignedZst, + check_into_iter_advance_by_nonzero => NonZero, +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker_slice_stub)] +fn check_into_iter_advance_by_drop_tracker() { + check_into_iter_advance_by_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker8_slice_stub)] +fn check_into_iter_advance_by_drop_tracker8() { + check_into_iter_advance_by_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_zst_slice_stub)] +fn check_into_iter_advance_by_drop_zst() { + check_into_iter_advance_by_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_niche_slice_stub)] +fn check_into_iter_advance_by_drop_niche() { + check_into_iter_advance_by_impl::(true); +} + +gen_harnesses! { check_into_iter_advance_back_by: + check_into_iter_advance_back_by_u8 => u8, + check_into_iter_advance_back_by_overaligned => OverAligned, + check_into_iter_advance_back_by_padded_niche => PaddedNiche, + check_into_iter_advance_back_by_char_u8 => (char, u8), + check_into_iter_advance_back_by_zst => (), + check_into_iter_advance_back_by_aligned_zst => AlignedZst, + check_into_iter_advance_back_by_nonzero => NonZero, +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker_slice_stub)] +fn check_into_iter_advance_back_by_drop_tracker() { + check_into_iter_advance_back_by_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker8_slice_stub)] +fn check_into_iter_advance_back_by_drop_tracker8() { + check_into_iter_advance_back_by_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_zst_slice_stub)] +fn check_into_iter_advance_back_by_drop_zst() { + check_into_iter_advance_back_by_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_niche_slice_stub)] +fn check_into_iter_advance_back_by_drop_niche() { + check_into_iter_advance_back_by_impl::(true); +} + +// --------------------------------------------------------------------------- +// `IntoIter::forget_allocation_drop_remaining` +// --------------------------------------------------------------------------- + +fn check_into_iter_forget_alloc_drop_remaining_impl(expect_drops: bool) { + let fill = T::any_fill(); + let tag_id: u8 = kani::any(); + let (mut it, len) = any_into_iter_in::( + MAX_ALLOCATION_BYTES, + fill, + true, + StatefulAlloc(tag_id), + ); + let old_buf = it.buf; + let old_cap = it.cap; + let old_ptr = it.ptr; + let small = witness_ok::(old_cap); + reset_drop_trace(); + reset_deallocs(); + it.forget_allocation_drop_remaining(); + assert!(it.len() == 0); + assert!(it.cap == 0); + assert!(it.ptr == it.buf); + assert!(it.end == it.buf.as_ptr() as *const T); + assert!(it.as_slice().is_empty()); + assert!(deallocs() == 0); + if expect_drops { + assert!(drops() == len); + // SAFETY: Single-threaded harness. + assert!(unsafe { LAST_DROP_LEN } == len); + // SAFETY: Single-threaded harness. + assert!(unsafe { LAST_DROP_PTR } == old_ptr.as_ptr().addr()); + } else { + assert!(drops() == 0); + } + // Dropping the now-empty `IntoIter` must neither drop elements nor free + // the relinquished backing allocation. + reset_drop_trace(); + drop(it); + assert!(drops() == 0); + assert!(deallocs() == 0); + if !T::IS_ZST && old_cap > 0 { + assert!(kani::mem::can_write(old_buf.as_ptr())); + let layout = crate::alloc::Layout::array::(old_cap).unwrap(); + // SAFETY: `old_buf` was allocated with `layout` and relinquished above. + unsafe { crate::alloc::dealloc(old_buf.as_ptr().cast::(), layout) }; + } + kani::cover(len == 0, "empty remaining"); + kani::cover(small && len > 4096, "deep remaining dropped"); + T::when_non_zst(|| { + kani::cover(old_cap == 0, "unallocated"); + kani::cover(old_cap > 0 && len == 0, "allocated but empty"); + kani::cover(len > 0 && old_ptr != old_buf, "advanced non-empty"); + }); +} + +fn check_into_iter_forget_alloc_drop_remaining() { + check_into_iter_forget_alloc_drop_remaining_impl::(false) +} + +gen_harnesses! { check_into_iter_forget_alloc_drop_remaining: + check_into_iter_forget_alloc_drop_remaining_u8 => u8, + check_into_iter_forget_alloc_drop_remaining_overaligned => OverAligned, + check_into_iter_forget_alloc_drop_remaining_padded_niche => PaddedNiche, + check_into_iter_forget_alloc_drop_remaining_char_u8 => (char, u8), + check_into_iter_forget_alloc_drop_remaining_zst => (), + check_into_iter_forget_alloc_drop_remaining_aligned_zst => AlignedZst, + check_into_iter_forget_alloc_drop_remaining_nonzero => NonZero, +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker_slice_stub)] +fn check_into_iter_forget_alloc_drop_remaining_drop_tracker() { + check_into_iter_forget_alloc_drop_remaining_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker8_slice_stub)] +fn check_into_iter_forget_alloc_drop_remaining_drop_tracker8() { + check_into_iter_forget_alloc_drop_remaining_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_zst_slice_stub)] +fn check_into_iter_forget_alloc_drop_remaining_drop_zst() { + check_into_iter_forget_alloc_drop_remaining_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_niche_slice_stub)] +fn check_into_iter_forget_alloc_drop_remaining_drop_niche() { + check_into_iter_forget_alloc_drop_remaining_impl::(true); +} + +// --------------------------------------------------------------------------- +// `IntoIter::drop` +// --------------------------------------------------------------------------- + +fn check_into_iter_drop_impl(expect_drops: bool) { + let fill = T::any_fill(); + let tag_id: u8 = kani::any(); + let (it, len) = any_into_iter_in::( + MAX_ALLOCATION_BYTES, + fill, + true, + StatefulAlloc(tag_id), + ); + let old_buf = it.buf; + let old_cap = it.cap; + let old_ptr = it.ptr; + let small = witness_ok::(old_cap); + reset_drop_trace(); + reset_deallocs(); + drop(it); + if expect_drops { + assert!(drops() == len); + // SAFETY: Single-threaded harness. + assert!(unsafe { LAST_DROP_LEN } == len); + // SAFETY: Single-threaded harness. + assert!(unsafe { LAST_DROP_PTR } == old_ptr.as_ptr().addr()); + } else { + assert!(drops() == 0); + } + if !T::IS_ZST && old_cap > 0 { + // `DropGuard` must have deallocated the exact backing buffer, layout, and allocator tag. + assert!(deallocs() == 1); + assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); + assert!(last_dealloc_size() == old_cap * mem::size_of::()); + assert!(last_dealloc_tag() == tag_id); + } else { + assert!(deallocs() == 0); + } + kani::cover(len == 0, "drop empty"); + kani::cover(small && len > 4096, "drop deep"); + T::when_non_zst(|| { + kani::cover(old_cap == 0, "drop unallocated"); + kani::cover(old_cap > 0 && len == 0, "drop exhausted allocated"); + kani::cover(len > 0 && old_ptr != old_buf, "drop advanced"); + }); +} + +fn check_into_iter_drop() { + check_into_iter_drop_impl::(false) +} + +gen_harnesses! { check_into_iter_drop: + check_into_iter_drop_u8 => u8, + check_into_iter_drop_overaligned => OverAligned, + check_into_iter_drop_padded_niche => PaddedNiche, + check_into_iter_drop_char_u8 => (char, u8), + check_into_iter_drop_zst => (), + check_into_iter_drop_aligned_zst => AlignedZst, + check_into_iter_drop_nonzero => NonZero, +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker_slice_stub)] +fn check_into_iter_drop_drop_tracker() { + check_into_iter_drop_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker8_slice_stub)] +fn check_into_iter_drop_drop_tracker8() { + check_into_iter_drop_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_zst_slice_stub)] +fn check_into_iter_drop_drop_zst() { + check_into_iter_drop_impl::(true); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_niche_slice_stub)] +fn check_into_iter_drop_drop_niche() { + check_into_iter_drop_impl::(true); +} + +// --------------------------------------------------------------------------- +// `IntoIter::into_vecdeque` +// --------------------------------------------------------------------------- + +fn check_into_iter_into_vecdeque_mode() { + let (fill, first, last) = markers_for::(); + let tag_id: u8 = kani::any(); + let (it, len, mid) = if M::CHECK_CONTENTS { + any_into_iter_marked_in::(fill, first, last, StatefulAlloc(tag_id)) + } else { + let (it, len) = any_into_iter_opt::( + MAX_ALLOCATION_BYTES, + true, + StatefulAlloc(tag_id), + false, + true, + ); + (it, len, 0) + }; + let old_buf = it.buf; + let old_cap = it.cap; + let old_ptr = it.ptr; + let small = witness_ok::(old_cap); + reset_drops(); + reset_deallocs(); + let deq = it.into_vecdeque(); + assert!(drops() == 0); + assert!(deallocs() == 0); + assert!(deq.allocator().0 == tag_id); + assert!(deq.len() == len); + assert!(deq.capacity() == if T::IS_ZST { usize::MAX } else { old_cap }); + let (s1, s2) = deq.as_slices(); + assert!(s1.len() == len); + assert!(s2.is_empty()); + if !T::IS_ZST && len > 0 { + assert!(s1.as_ptr() == old_ptr.as_ptr() as *const T); + M::when_contents(|| { + let p = s1.as_ptr(); + // SAFETY: `0 < len == s1.len()`. + assert!(unsafe { tag_matches(p, first) }); + if len > 1 { + // SAFETY: `len - 1 < len == s1.len()`. + assert!(unsafe { tag_matches(p.add(len - 1), last) }); + } + check_middle_at(p, len, mid, fill, small); + }); + } + kani::cover(len == 0, "empty"); + kani::cover(small && len > 4096, "deep"); + T::when_non_zst(|| { + kani::cover(old_cap == 0, "zero capacity"); + kani::cover(old_cap > 0 && len == 0, "allocated empty"); + kani::cover(len > 0 && old_ptr == old_buf, "unadvanced"); + kani::cover(len > 0 && old_ptr != old_buf, "advanced"); + }); + // Dropping `deq` for non-`Drop` types verifies `VecDeque` owns the exact + // base pointer & capacity layout (kills wrong-base-ptr heap corruption). + finish::(deq); + if !mem::needs_drop::() && !T::IS_ZST && old_cap > 0 { + assert!(deallocs() == 1); + assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); + assert!(last_dealloc_size() == old_cap * mem::size_of::()); + assert!(last_dealloc_tag() == tag_id); + } +} + +fn check_into_iter_into_vecdeque() { + check_into_iter_into_vecdeque_mode::() +} + +gen_harnesses! { check_into_iter_into_vecdeque: + check_into_iter_into_vecdeque_u8 => u8, + check_into_iter_into_vecdeque_overaligned => OverAligned, + check_into_iter_into_vecdeque_padded_niche => PaddedNiche, + check_into_iter_into_vecdeque_char_u8 => (char, u8), + check_into_iter_into_vecdeque_zst => (), + check_into_iter_into_vecdeque_aligned_zst => AlignedZst, + check_into_iter_into_vecdeque_drop_tracker => DropTracker, + check_into_iter_into_vecdeque_drop_niche => DropNiche, + check_into_iter_into_vecdeque_nonzero => NonZero, +} + +#[kani::proof] +fn check_into_iter_into_vecdeque_nonpow2() { + check_into_iter_into_vecdeque_mode::(); +} + +// --------------------------------------------------------------------------- +// `IntoIter::fold` and `IntoIter::try_fold` (unbounded loop invariants) +// --------------------------------------------------------------------------- + +/// `IntoIter::fold`: visits every remaining element via the unbounded +/// `#[safety::loop_invariant]` loops, verifies pointer bounds, alignment, +/// ownership transfer without double-dropping, and exact backing buffer +/// deallocation via `TrackAlloc`. +fn check_into_iter_fold() { + let (it, len) = + any_into_iter_opt::(MAX_ALLOCATION_BYTES, true, TrackAlloc, true, true); + let old_buf = it.buf; + let old_cap = it.cap; + let old_ptr = it.ptr; + let small = witness_ok::(old_cap); + reset_drops(); + reset_deallocs(); + let init: u8 = kani::any(); + let res = it.fold(init, |acc, x| { + // Forget `x` directly rather than calling `finish` (whose dead `drop(x)` + // branch on `Drop` types widens CBMC's inferred loop assigns into a + // `CAR size` failure). Note: CBMC's loop-contract havoc does not preserve + // pre-loop symbolic `write_bytes` contents through `arith_offset` reads + // (and contracted non-ZST loops currently hit Kani's `mem_init` ghost-tracker + // limit under `-Z uninit-checks`); live-only `[adv..len]` initialization + // preserves valid element values for `-Z valid-value-checks`. + mem::forget(x); + acc.wrapping_add(1) + }); + assert!(drops() == 0); + if !T::IS_ZST && old_cap > 0 { + assert!(deallocs() == 1); + assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); + assert!(last_dealloc_size() == old_cap * mem::size_of::()); + } else { + assert!(deallocs() == 0); + } + if len == 0 { + assert!(res == init); + } + kani::cover(len == 0, "empty fold"); + kani::cover(len == 1, "single-element fold"); + kani::cover(small && len > 4096, "deep fold"); + T::when_non_zst(|| { + kani::cover(old_cap == 0, "unallocated fold"); + kani::cover(len > 0 && old_ptr != old_buf, "advanced fold"); + }); +} + +gen_harnesses! { check_into_iter_fold: + #[kani::solver(minisat)] + check_into_iter_fold_u8 => u8, + #[kani::solver(minisat)] + check_into_iter_fold_overaligned => OverAligned, + #[kani::solver(minisat)] + check_into_iter_fold_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_into_iter_fold_char_u8 => (char, u8), + #[kani::solver(minisat)] + check_into_iter_fold_zst => (), + #[kani::solver(minisat)] + check_into_iter_fold_aligned_zst => AlignedZst, + #[kani::solver(minisat)] + check_into_iter_fold_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_into_iter_fold_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_into_iter_fold_nonzero => NonZero, +} + +/// `IntoIter::try_fold`: visits remaining elements via the unbounded +/// `#[safety::loop_invariant]` loops, short-circuiting cleanly on `Break` +/// while preserving `IntoIter` pointer bounds, alignment, and capacity +/// invariants for the remaining slice. +fn check_into_iter_try_fold() { + use core::ops::ControlFlow; + + let (mut it, len) = + any_into_iter_opt::(MAX_ALLOCATION_BYTES, true, TrackAlloc, true, true); + let old_buf = it.buf; + let old_cap = it.cap; + let old_ptr = it.ptr; + let small = witness_ok::(old_cap); + reset_drops(); + reset_deallocs(); + let init: u8 = kani::any(); + let res = it.try_fold(init, |acc, x| { + mem::forget(x); + if kani::any() { + ControlFlow::Break(acc) + } else { + ControlFlow::Continue(acc.wrapping_add(1)) + } + }); + assert!(drops() == 0); + assert!(deallocs() == 0); + assert!(it.buf == old_buf && it.cap == old_cap); + match res { + ControlFlow::Continue(v) => { + assert!(it.len() == 0); + assert!(it.as_slice().is_empty()); + if len == 0 { + assert!(v == init); + } + // Drop `it` for non-`Drop` types (O(1) exact deallocation check via + // `TrackAlloc`); for `Drop` types, `finish` avoids compiler slice drop + // glue (`drop_in_place::<[T]>`) whose symbolic pointer subtraction + // `end - ptr` cannot be statically bounded by CBMC without `unwind`. + finish::(it); + assert!(drops() == 0); + if !mem::needs_drop::() && !T::IS_ZST && old_cap > 0 { + assert!(deallocs() == 1); + assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); + assert!(last_dealloc_size() == old_cap * mem::size_of::()); + } else { + assert!(deallocs() == 0); + } + } + ControlFlow::Break(_) => { + assert!(len > 0); + assert!(it.len() < len); + assert!(it.as_slice().len() == it.len()); + finish::(it); + } + } + kani::cover(len == 0 && matches!(res, ControlFlow::Continue(_)), "empty try_fold"); + kani::cover( + small && len > 4096 && matches!(res, ControlFlow::Continue(_)), + "deep complete try_fold", + ); + kani::cover(small && len > 4096 && matches!(res, ControlFlow::Break(_)), "deep break try_fold"); + T::when_non_zst(|| { + kani::cover(old_cap == 0, "unallocated try_fold"); + kani::cover( + len > 0 && old_ptr != old_buf && matches!(res, ControlFlow::Break(_)), + "advanced break try_fold", + ); + }); +} + +gen_harnesses! { check_into_iter_try_fold: + #[kani::solver(minisat)] + check_into_iter_try_fold_u8 => u8, + #[kani::solver(minisat)] + check_into_iter_try_fold_overaligned => OverAligned, + #[kani::solver(minisat)] + check_into_iter_try_fold_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_into_iter_try_fold_char_u8 => (char, u8), + #[kani::solver(minisat)] + check_into_iter_try_fold_zst => (), + #[kani::solver(minisat)] + check_into_iter_try_fold_aligned_zst => AlignedZst, + #[kani::solver(minisat)] + check_into_iter_try_fold_drop_tracker => DropTracker, + #[kani::solver(minisat)] + check_into_iter_try_fold_drop_niche => DropNiche, + #[kani::solver(minisat)] + check_into_iter_try_fold_nonzero => NonZero, +} + +// --------------------------------------------------------------------------- +// `IntoIter::next_chunk` +// --------------------------------------------------------------------------- + +/// Cover helper for `next_chunk::` so `N = 0` emits zero unreachable +/// partial/exact-chunk cover goals. +trait ChunkSpec { + fn when_nonzero(f: impl FnOnce()); +} + +struct ChunkNonZero; +impl ChunkSpec for ChunkNonZero { + fn when_nonzero(f: impl FnOnce()) { + f(); + } +} + +struct ChunkZero; +impl ChunkSpec for ChunkZero { + fn when_nonzero(_f: impl FnOnce()) {} +} + +/// `IntoIter::next_chunk`: pulls a fixed-size chunk `[T; N]` from an +/// unbounded `IntoIter` or returns the remaining `< N` elements as an +/// `array::IntoIter`, preserving element values and exact drop counts. +/// +/// Instantiated across `N = 0` (zero-size chunk), `N = 3` (odd non-pow2 chunk), +/// and `N = 4` (even power-of-two chunk). +/// +/// For `size_of::() > 1`, `Err(rem)` checks memory safety, length, and drop +/// count but skips reading back copied bytes from `rem`: CBMC's `memcpy` model +/// into a `[MaybeUninit; N]` union array with symbolic `len < N` drops byte +/// propagation at index `>= 1`. +fn check_into_iter_next_chunk_n( + expect_drops: bool, + use_up_to: bool, +) { + let (fill, first, last) = markers_for::(); + let (mut it, len) = + any_into_iter_uninit_in_mode::(MAX_ALLOCATION_BYTES, true, Global, use_up_to); + let k_ok: usize = if N > 0 { kani::any_where(|&k: &usize| k < N) } else { 0 }; + let use_simple_tags = mem::size_of::() > 8; + if !T::IS_ZST && len > 0 { + // Initialize every slot touched by `next_chunk` (`0..min(len, N + 1)`, at most 5 + // constant iterations) field-wise via `Shape::init_uninit_slot` so + // `raw_ary.transpose().assume_init()` and `Err(rem)` element drops never + // materialize uninitialized niche/padded values while keeping padding bytes + // genuinely uninitialized. + // For 16-byte `OverAligned` (`size_of > 8`), use a single symbolic `fill` across + // all `0..min(len, N + 1)` slots (zero per-slot symbolic ITEs while keeping every + // element validly initialized with genuinely uninitialized 15-byte padding). + let mut init_i = 0; + while init_i <= N && init_i < len { + let tag = if use_simple_tags { + fill + } else if mem::size_of::() == 1 || (N > 0 && init_i == k_ok) || init_i == N { + if init_i == 0 { + first + } else if init_i == len - 1 { + last + } else { + fill + } + } else { + 1u8 + }; + // SAFETY: `init_i < len == it.len()` and `it`'s backing buffer was + // allocated uninitialized; field-wise writes initialize every live + // field while leaving all padding bytes genuinely uninitialized. + unsafe { T::init_uninit_slot(it.ptr.as_ptr().add(init_i), tag) }; + init_i += 1; + } + if len > N + 1 { + let bg_fill = if T::ALLOW_ZERO { 0u8 } else { 1u8 }; + // SAFETY: `[N + 1..len]` is strictly disjoint from the touched prefix + // `[0..=N]` and inside `it`'s remaining live slice `[adv..len]`; + // using compile-time constant offset `N + 1` lets CBMC keep touched + // slots `[0..=N]` disjoint with genuinely uninitialized padding while + // ensuring 100% of `[adv..len]` is validly initialized. + unsafe { + core::intrinsics::write_bytes( + it.ptr.as_ptr().add(N + 1).cast::(), + bg_fill, + (len - (N + 1)) * mem::size_of::(), + ); + } + } + } + let old_ptr = it.ptr; + let small = witness_ok::(it.cap); + reset_drops(); + match it.next_chunk::() { + Ok(arr) => { + assert!(drops() == 0); + assert!(len >= N); + assert!(it.len() == len - N); + if !T::IS_ZST { + // SAFETY: `N <= len`, so `old_ptr.add(N) <= end`. + assert!(it.ptr == unsafe { old_ptr.add(N) }); + if N > 0 { + let want = if use_simple_tags { + fill + } else if k_ok == 0 { + first + } else if k_ok == len - 1 { + last + } else { + fill + }; + assert!(arr[k_ok].matches_tag(want)); + } + if len > N { + let want_next = if use_simple_tags { + fill + } else if N == 0 { + first + } else if N == len - 1 { + last + } else { + fill + }; + // SAFETY: `it.ptr` points to the next live remaining element. + assert!(unsafe { tag_matches(it.ptr.as_ptr() as *const T, want_next) }); + } + } + drop(arr); + assert!(drops() == if expect_drops { N } else { 0 }); + finish::(it); + } + Err(mut rem) => { + assert!(drops() == 0); + assert!(len < N); + assert!(it.len() == 0); + assert!(rem.len() == len); + if !T::IS_ZST && len > 0 { + let s = rem.as_slice(); + assert!(s.len() == len); + if mem::size_of::() == 1 { + let k: usize = kani::any_where(|&k: &usize| k < len); + let want = if k == 0 { + first + } else if k == len - 1 { + last + } else { + fill + }; + assert!(s[k].matches_tag(want)); + } + } + // Drain the at-most-`N` remaining elements via `rem.next()` so real + // `Drop::drop` runs `len` times without invoking slice drop glue on + // a symbolic-length slice inside `array::IntoIter::drop`. + let mut idx = 0; + while idx < N { + if let Some(x) = rem.next() { + drop(x); + } + idx += 1; + } + assert!(rem.len() == 0); + mem::forget(rem); + assert!(drops() == if expect_drops { len } else { 0 }); + // Drop `it` for non-`Drop` types (checks deallocation); forget for + // `Drop` types so CBMC does not attempt to unwind `drop_in_place::<[T]>`. + finish::(it); + assert!(drops() == if expect_drops { len } else { 0 }); + } + } + kani::cover(len == 0, "empty"); + C::when_nonzero(|| { + kani::cover(len > 0 && len < N, "partial chunk"); + kani::cover(len == N, "exact chunk"); + }); + kani::cover(small && len > 4096, "deep full chunk"); +} + +fn check_into_iter_next_chunk() { + check_into_iter_next_chunk_n::(false, false) +} + +fn check_into_iter_next_chunk_ms() { + check_into_iter_next_chunk_n::(false, true) +} + +fn check_into_iter_next_chunk_odd3() { + check_into_iter_next_chunk_n::(false, false) +} + +fn check_into_iter_next_chunk_odd3_ms() { + check_into_iter_next_chunk_n::(false, true) +} + +gen_harnesses! { check_into_iter_next_chunk: + check_into_iter_next_chunk_u8 => u8, + check_into_iter_next_chunk_zst => (), + check_into_iter_next_chunk_aligned_zst => AlignedZst, + check_into_iter_next_chunk_nonzero => NonZero, +} + +gen_harnesses! { check_into_iter_next_chunk_ms: + #[kani::solver(minisat)] + check_into_iter_next_chunk_overaligned => OverAligned, + #[kani::solver(minisat)] + check_into_iter_next_chunk_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_into_iter_next_chunk_char_u8 => (char, u8), +} + +gen_harnesses! { check_into_iter_next_chunk_odd3: + check_into_iter_next_chunk_odd3_u8 => u8, + check_into_iter_next_chunk_odd3_aligned_zst => AlignedZst, +} + +gen_harnesses! { check_into_iter_next_chunk_odd3_ms: + #[kani::solver(minisat)] + check_into_iter_next_chunk_odd3_overaligned => OverAligned, + #[kani::solver(minisat)] + check_into_iter_next_chunk_odd3_padded_niche => PaddedNiche, + #[kani::solver(minisat)] + check_into_iter_next_chunk_odd3_char_u8 => (char, u8), +} + +// No `drop_in_place` stub needed: `N = 3` / `N = 4` are fixed constants, so +// `drop(arr)` and the `N`-step `rem.next()` drain execute real `Drop::drop`. +#[kani::proof] +fn check_into_iter_next_chunk_drop_tracker() { + check_into_iter_next_chunk_n::(true, false); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_iter_next_chunk_drop_tracker8() { + check_into_iter_next_chunk_n::(true, true); +} + +#[kani::proof] +fn check_into_iter_next_chunk_drop_zst() { + check_into_iter_next_chunk_n::(true, false); +} + +#[kani::proof] +fn check_into_iter_next_chunk_drop_niche() { + check_into_iter_next_chunk_n::(true, false); +} + +#[kani::proof] +fn check_into_iter_next_chunk_odd3_drop_tracker() { + check_into_iter_next_chunk_n::(true, false); +} + +#[kani::proof] +fn check_into_iter_next_chunk_odd3_drop_niche() { + check_into_iter_next_chunk_n::(true, false); +} + +#[kani::proof] +fn check_into_iter_next_chunk_zero_u8() { + check_into_iter_next_chunk_n::(false, false); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_iter_next_chunk_zero_overaligned() { + check_into_iter_next_chunk_n::(false, true); +} + +#[kani::proof] +fn check_into_iter_next_chunk_zero_zst() { + check_into_iter_next_chunk_n::<(), ChunkZero, 0>(false, false); +} + +#[kani::proof] +fn check_into_iter_next_chunk_zero_aligned_zst() { + check_into_iter_next_chunk_n::(false, false); +} + +#[kani::proof] +fn check_into_iter_next_chunk_zero_drop_tracker() { + check_into_iter_next_chunk_n::(true, false); +} + +#[kani::proof] +fn check_into_iter_next_chunk_zero_nonzero() { + check_into_iter_next_chunk_n::, ChunkZero, 0>(false, false); +} + +// --------------------------------------------------------------------------- +// Supplementary bounded evidence: real compiler-synthesized slice drop glue +// --------------------------------------------------------------------------- + +/// Supplementary bounded harnesses (`LEN` in `0..=4`, NO `#[kani::stub]`, +/// NO `#[kani::unwind]`) exercising the **real compiler-synthesized +/// `core::ptr::drop_in_place::<[T]>`** on `IntoIter::{advance_by, +/// advance_back_by, forget_allocation_drop_remaining, drop}`. Using concrete +/// `const LEN` lets CBMC unroll the compiler-synthesized drop loop finitely +/// without any `#[kani::unwind]` attribute; every element is initialized via +/// typed `ptr::write` (`mark`, zero `write_bytes`). +mod bounded_evidence { + use core::kani; + use core::mem::{self, ManuallyDrop, SizedTypeProperties}; + use core::ptr::{self, NonNull}; + + use super::{ + DropNiche, DropTracker, DropTracker8, IntoIter, Shape, TrackAlloc, deallocs, drops, + last_dealloc_ptr, last_dealloc_size, mark, reset_deallocs, reset_drops, + }; + use crate::alloc::Layout; + + fn make_concrete_into_iter() + -> IntoIter { + let cap = LEN + ADV; + let buf = if cap == 0 { + NonNull::::dangling() + } else { + let layout = Layout::array::(cap).unwrap(); + // SAFETY: `cap > 0` and `size_of::() > 0`. + let p = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p.is_null()); + // SAFETY: `p` is non-null and aligned for `T`. + let buf: NonNull = unsafe { NonNull::new_unchecked(p.cast::()) }; + let mut i = 0; + while i < LEN { + // SAFETY: `ADV + i < cap`; typed `ptr::write` leaves any padding uninit. + unsafe { mark(buf.as_ptr().add(ADV + i), T::any_byte()) }; + i += 1; + } + buf + }; + // SAFETY: `ADV <= cap` and `ADV + LEN == cap`. + let (ptr, end) = unsafe { (buf.add(ADV), buf.as_ptr().add(cap) as *const T) }; + IntoIter { + buf, + phantom: core::marker::PhantomData, + cap, + alloc: ManuallyDrop::new(TrackAlloc), + ptr, + end, + } + } + + fn real_drop_advance_by_const() { + let mut it = make_concrete_into_iter::(); + let step = if N < LEN { N } else { LEN }; + reset_drops(); + reset_deallocs(); + let res = it.advance_by(N); + assert!(res.is_ok() == (N <= LEN)); + assert!(drops() == step); + assert!(it.len() == LEN - step); + // Drop remaining elements via real `IntoIter::drop` too. + drop(it); + assert!(drops() == LEN); + assert!(deallocs() == 1); + } + + fn real_drop_advance_back_by_const() { + let mut it = make_concrete_into_iter::(); + let step = if N < LEN { N } else { LEN }; + reset_drops(); + reset_deallocs(); + let res = it.advance_back_by(N); + assert!(res.is_ok() == (N <= LEN)); + assert!(drops() == step); + assert!(it.len() == LEN - step); + drop(it); + assert!(drops() == LEN); + assert!(deallocs() == 1); + } + + fn real_drop_forget_alloc_const() { + let mut it = make_concrete_into_iter::(); + let (old_buf, old_cap) = (it.buf, it.cap); + reset_drops(); + reset_deallocs(); + it.forget_allocation_drop_remaining(); + assert!(drops() == LEN); + assert!(it.len() == 0); + assert!(deallocs() == 0); + drop(it); + assert!(drops() == LEN); + assert!(deallocs() == 0); + if !T::IS_ZST && old_cap > 0 { + assert!(kani::mem::can_write(old_buf.as_ptr())); + let layout = Layout::array::(old_cap).unwrap(); + // SAFETY: `old_buf` was allocated with `layout` and relinquished above. + unsafe { crate::alloc::dealloc(old_buf.as_ptr().cast::(), layout) }; + } + } + + fn real_drop_into_iter_const() { + let it = make_concrete_into_iter::(); + let (old_buf, old_cap) = (it.buf, it.cap); + reset_drops(); + reset_deallocs(); + drop(it); + assert!(drops() == LEN); + assert!(deallocs() == 1); + assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); + assert!(last_dealloc_size() == old_cap * mem::size_of::()); + } + + #[kani::proof] + fn bounded_real_drop_advance_by_drop_tracker() { + real_drop_advance_by_const::(); + real_drop_advance_by_const::(); + real_drop_advance_by_const::(); + } + + #[kani::proof] + fn bounded_real_drop_advance_by_drop_niche() { + real_drop_advance_by_const::(); + real_drop_advance_by_const::(); + real_drop_advance_by_const::(); + } + + #[kani::proof] + fn bounded_real_drop_advance_back_by_drop_tracker8() { + real_drop_advance_back_by_const::(); + real_drop_advance_back_by_const::(); + real_drop_advance_back_by_const::(); + } + + #[kani::proof] + fn bounded_real_drop_forget_alloc_drop_tracker() { + real_drop_forget_alloc_const::(); + real_drop_forget_alloc_const::(); + } + + #[kani::proof] + fn bounded_real_drop_into_iter_drop_tracker() { + real_drop_into_iter_const::(); + real_drop_into_iter_const::(); + } + + #[kani::proof] + fn bounded_real_drop_into_iter_drop_tracker8() { + real_drop_into_iter_const::(); + real_drop_into_iter_const::(); + } + + #[kani::proof] + fn bounded_real_drop_into_iter_drop_niche() { + real_drop_into_iter_const::(); + real_drop_into_iter_const::(); + } +} diff --git a/verifast-proofs/README.md b/verifast-proofs/README.md index 096d3e32e9061..12c23c1ee1874 100644 --- a/verifast-proofs/README.md +++ b/verifast-proofs/README.md @@ -6,6 +6,7 @@ Specifically, it currently contains the following proofs: - Partial proof of [LinkedList](alloc/collections/linked_list.rs/) - Partial proof of [RawVec](alloc/raw_vec/mod.rs/) +- Partial proof of [Vec::ExtractIf](alloc/vec/extract_if.rs/) See each proof's accompanying README for a tour of the proof and applicable caveats. diff --git a/verifast-proofs/alloc/vec/extract_if.rs/README.md b/verifast-proofs/alloc/vec/extract_if.rs/README.md new file mode 100644 index 0000000000000..3fb43d9fad3b3 --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/README.md @@ -0,0 +1,103 @@ +# Partial verification of `Vec::ExtractIf` with VeriFast + +With certain [caveats](#caveats), this proof proves unbounded, polymorphic +[soundness](https://doc.rust-lang.org/nomicon/working-with-unsafe.html) of +`alloc::vec::ExtractIf::new`, `alloc::vec::ExtractIf::next`, and +`alloc::vec::ExtractIf::drop` for arbitrary element types `T` (including +zero-sized types with capacity up to `usize::MAX` and `old_len > isize::MAX`), +arbitrary filter predicates `F: FnMut(&mut T) -> bool`, and arbitrary allocators +`A: Allocator`. + +## Proof Overview + +### ZST-Sound Concrete `Vec` & `ExtractIf_fbc` + +VeriFast 26.10's built-in `std/lib.rsspec:1704` (`Vec_inv`) carries a stale +`capacity <= isize::MAX` axiom that contradicts zero-sized `Vec`s (`cap == usize::MAX`) +and requires `thread_token(t)` in `Vec_to_own` (`std/lib.rsspec:1714`). To avoid any +contradiction with `std/lib.rsspec:1704`, `original/lib.rs` and `verified/lib.rs` +define a minimal concrete `Vec` (`ptr`, `cap`, `len`, `alloc`) matching +`library/alloc/src/vec/mod.rs`'s real ZST-sound invariant +`v.cap * std::mem::size_of::() <= isize::MAX` (consistent with VeriFast's own +`prelude_core.rsspec:253` `array__inv`), with fully verified implementations and +public `safety_proof`s for `Vec::{len, as_ptr, as_mut_ptr, set_len}` (zero +`assume_correct` on any `Vec` method). + +`ExtractIf<'a, T, F, A>` mutably borrows a `Vec` whose length is temporarily set +to `0` by `ExtractIf::new` (leak amplification guard) while partitioning `buf[0..cap]` +into four disjoint regions: + +1. `buf[..idx - del]`: retained elements (`retained`), each satisfying `own::(t)`. +2. `buf[idx - del..idx]`: `del`-element uninitialized hole vacated by extracted elements. +3. `buf[idx..old_len]`: unvisited tail elements (`tail`), each satisfying `own::(t)`. +4. `buf[old_len..cap]`: uninitialized spare capacity. + +The borrow payload `ExtractIf_fbc` tracks two states via a shared `ghost_cell`: +- `some(pair(idx, del))`: active iteration state (`0 <= del <= idx <= end <= old_len <= cap` + and `cap * std::mem::size_of::() <= isize::MAX`). +- `none`: post-`Drop` state where `ExtractIf::drop` has compacted the tail left over the + hole, restored `vec.set_len(old_len - del)`, and closed `>.own(t, *vec)`. + +### Verified Functions & Connecting Lemmas + +Verified cleanly with **`0 errors found (453 statements verified)`**, passing +`refinement-checker` against `original/lib.rs` and byte-for-byte `diff` against +`library/alloc/src/vec/extract_if.rs`: + +- **`Vec::{len, as_ptr, as_mut_ptr, set_len}`** (`verified/lib.rs`): verified field-level + and public `safety_proof` contracts (`Vec_share_full`, `Vec_share_mono`, `init_ref_Vec`, + `Vec_drop`, `Vec_send`, `Vec_own_mono`) with zero `assume_correct`. +- **`ExtractIf::new`:** Unbounded proof opening `full_borrow('a, >.full_borrow_content(t, vec))`, + reading `vec.len()`, bounding `start..end` via `slice_range__VeriFast_wrapper`, calling + `vec.set_len(0)`, calling `ExtractIf_init_from_vec_buffer` to establish `ExtractIf_fbc` + in `some(pair(start, 0))`, and closing `full_borrow_convert_strong` using + `ExtractIf_fbc_restore_vec` (proving leak-amplification soundness for both `none` and + `some(p)` states without requiring `thread_token(t)`). +- **`ExtractIf::next`:** Unbounded loop proof (`while self.idx < self.end`) verifying + in-bounds pointer arithmetic (`as_mut_ptr().add(i)`, `as_mut_ptr().add(i - self.del)`), + exclusive access to `cur` during predicate invocation, ownership transfer on + `Some(ptr::read(cur))`, disjoint `ptr::copy_nonoverlapping(cur, hole_slot, 1)` when + `del > 0`, and invariant preservation across arbitrary iteration counts (including + always-false predicates over ZST vectors with `old_len > isize::MAX` and + `cap == usize::MAX`). +- **`ExtractIf::drop` (via `drop_body__VeriFast_wrapper<'a, T, F, A>`):** Unbounded proof + verifying `ptr::copy` (both the non-overlapping `del >= old_len - idx` case and + overlapping `del < old_len - idx` case) via pure inductive typed-array/byte-slice + conversion lemmas (`array_to_u8s_bytes`, `u8s_bytes_to_array`), followed by + `self.vec.set_len(self.old_len - self.del)` and `full_borrow_convert_strong` restoring + `full_borrow('a, >.full_borrow_content(t, vec))` while transitioning + `ExtractIf_fbc` from `some(pair(idx, del))` to `none`. Because VeriFast 26.10 rejects + `Drop` specs on `impl Drop for ExtractIf<'_, T, F, A>` when the anonymous + lifetime `'_` does not syntactically match the struct's `'a` parameter, the exact + `Drop::drop` contract and body are verified in `drop_body__VeriFast_wrapper<'a, T, F, A>`, + and `refinement-checker` confirms that `original/extract_if.rs::Drop::drop` refines + delegating to it. +- **Type obligations (`ExtractIf_drop`, `ExtractIf_send`, `ExtractIf_own_mono`):** Verified + with zero `assume(false)`. + +## Caveats + +1. **VeriFast flags:** Verified with `-skip_specless_fns -ignore_unwind_paths -allow_assume`: + - `-skip_specless_fns`: `Vec::allocator`, `ExtractIf::allocator`, `ExtractIf::size_hint`, + and `Debug::fmt` are skipped by VeriFast (none are Challenge 24 targets). + - `-ignore_unwind_paths`: Unwind/panic paths (e.g., if `pred` panics inside `next`) + are not verified by VeriFast. + - `-allow_assume`: Used strictly in four documented places: + 1. `call_pred__VeriFast_wrapper` (`assume_correct` closure call boundary, matching + `verifast-proofs/alloc/collections/linked_list.rs`). + 2. `slice_range__VeriFast_wrapper` (`assume_correct` wrapper around `core::slice::range` + stating its documented postcondition `0 <= start <= end <= old_len`). + 3. `Vec_send` / `ExtractIf_send` (`is_Send` propagation through `unsafe impl Send for Vec`). + 4. `Vec_own_mono` / `ExtractIf_own_mono` (`upcast` on `usize` is identity, tracking + VeriFast issue #610). + - There is **zero `assume(false)`** anywhere in this proof. +2. **Backing `Vec` model:** `original/lib.rs` and `verified/lib.rs` model the fields and + buffer-access methods of `alloc::vec::Vec` used by `ExtractIf` (`ptr`, `cap`, `len`, + `alloc`; `Vec_alloc_handle` abstracts the untouched `RawVec` allocation ownership, + separately verified in `verifast-proofs/alloc/raw_vec/mod.rs/`). +3. **Code changes & refinement checking:** `refinement-checker` verifies that + `original/lib.rs` refines `verified/lib.rs`, and `diff` checks that + `original/extract_if.rs` is byte-for-byte identical to `library/alloc/src/vec/extract_if.rs`. +4. **Target & tool soundness:** As with `linked_list.rs` and `raw_vec/mod.rs`, VeriFast + verifies against the `rustc` target architecture and relies on VeriFast's symbolic + execution engine and prelude specs. diff --git a/verifast-proofs/alloc/vec/extract_if.rs/original/extract_if.rs b/verifast-proofs/alloc/vec/extract_if.rs/original/extract_if.rs new file mode 100644 index 0000000000000..7faa2a776fc8b --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/original/extract_if.rs @@ -0,0 +1,160 @@ +use core::ops::{Range, RangeBounds}; +use core::{fmt, ptr, slice}; + +use super::Vec; +use crate::alloc::{Allocator, Global}; + +/// An iterator which uses a closure to determine if an element should be removed. +/// +/// This struct is created by [`Vec::extract_if`]. +/// See its documentation for more. +/// +/// # Example +/// +/// ``` +/// let mut v = vec![0, 1, 2]; +/// let iter: std::vec::ExtractIf<'_, _, _> = v.extract_if(.., |x| *x % 2 == 0); +/// ``` +#[stable(feature = "extract_if", since = "1.87.0")] +#[must_use = "iterators are lazy and do nothing unless consumed; \ + use `retain_mut` or `extract_if().for_each(drop)` to remove and discard elements"] +pub struct ExtractIf< + 'a, + T, + F, + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + vec: &'a mut Vec, + /// The index of the item that will be inspected by the next call to `next`. + idx: usize, + /// Elements at and beyond this point will be retained. Must be equal or smaller than `old_len`. + end: usize, + /// The number of items that have been drained (removed) thus far. + del: usize, + /// The original length of `vec` prior to draining. + old_len: usize, + /// The filter test predicate. + pred: F, +} + +impl<'a, T, F, A: Allocator> ExtractIf<'a, T, F, A> { + pub(super) fn new>(vec: &'a mut Vec, pred: F, range: R) -> Self { + let old_len = vec.len(); + let Range { start, end } = slice::range(range, ..old_len); + + // Guard against the vec getting leaked (leak amplification) + // SAFETY: Setting length to 0 is always okay. + unsafe { + vec.set_len(0); + } + ExtractIf { vec, idx: start, del: 0, end, old_len, pred } + } + + /// Returns a reference to the underlying allocator. + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn allocator(&self) -> &A { + self.vec.allocator() + } +} + +#[stable(feature = "extract_if", since = "1.87.0")] +impl Iterator for ExtractIf<'_, T, F, A> +where + F: FnMut(&mut T) -> bool, +{ + type Item = T; + + fn next(&mut self) -> Option { + while self.idx < self.end { + let i = self.idx; + // SAFETY: + // We know that `i < self.end` from the if guard and that `self.end <= self.old_len` from + // the validity of `Self`. Therefore `i` points to an element within `vec`. + // + // Additionally, the i-th element is valid because each element is visited at most once + // and it is the first time we access vec[i]. + // + // Note: we can't use `vec.get_unchecked_mut(i)` here since the precondition for that + // function is that i < vec.len(), but we've set vec's length to zero. + let cur = unsafe { &mut *self.vec.as_mut_ptr().add(i) }; + let drained = (self.pred)(cur); + // Update the index *after* the predicate is called. If the index + // is updated prior and the predicate panics, the element at this + // index would be leaked. + self.idx += 1; + if drained { + self.del += 1; + // SAFETY: We never touch this element again after returning it. + return Some(unsafe { ptr::read(cur) }); + } else if self.del > 0 { + // SAFETY: `self.del` > 0, so the hole slot must not overlap with current element. + // We use copy for move, and never touch this element again. + unsafe { + let hole_slot = self.vec.as_mut_ptr().add(i - self.del); + ptr::copy_nonoverlapping(cur, hole_slot, 1); + } + } + } + None + } + + fn size_hint(&self) -> (usize, Option) { + (0, Some(self.end - self.idx)) + } +} + +#[stable(feature = "extract_if", since = "1.87.0")] +impl Drop for ExtractIf<'_, T, F, A> { + fn drop(&mut self) { + if self.del > 0 { + // SAFETY: Trailing unchecked items must be valid since we never touch them. + unsafe { + ptr::copy( + self.vec.as_ptr().add(self.idx), + self.vec.as_mut_ptr().add(self.idx - self.del), + self.old_len - self.idx, + ); + } + } + // SAFETY: After filling holes, all items are in contiguous memory. + unsafe { + self.vec.set_len(self.old_len - self.del); + } + } +} + +#[stable(feature = "extract_if", since = "1.87.0")] +impl fmt::Debug for ExtractIf<'_, T, F, A> +where + T: fmt::Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // We have to use pointer arithmetics here, + // because the length of `self.vec` is temporarily set to 0. + let start = self.vec.as_ptr(); + + // SAFETY: we always keep first `self.idx - self.del` elements valid. + let retained = unsafe { slice::from_raw_parts(start, self.idx - self.del) }; + + let valid_tail = + // SAFETY: we have not yet touched elements starting at `self.idx`. + unsafe { slice::from_raw_parts(start.add(self.idx), self.old_len - self.idx) }; + + let (remainder, skipped_tail) = + // SAFETY: `end - idx <= old_len - idx`, because `end <= old_len`. + // Also `idx <= end` by invariant. + unsafe { valid_tail.split_at_unchecked(self.end - self.idx) }; + + f.debug_struct("ExtractIf") + .field("retained", &retained) + .field("remainder", &remainder) + .field("skipped_tail", &skipped_tail) + .finish_non_exhaustive() + } +} + +#[cfg(all(kani, not(no_global_oom_handling)))] +#[path = "verify_extract_if.rs"] +mod verify; diff --git a/verifast-proofs/alloc/vec/extract_if.rs/original/lib.rs b/verifast-proofs/alloc/vec/extract_if.rs/original/lib.rs new file mode 100644 index 0000000000000..69a847637d84e --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/original/lib.rs @@ -0,0 +1,64 @@ +// verifast_options{skip_specless_fns} + +#![no_std] +#![allow(internal_features)] +#![allow(incomplete_features)] +#![feature(allocator_ext)] +#![feature(staged_api)] +#![feature(rustc_attrs)] +#![feature(slice_range)] + +#![stable(feature = "rust1", since = "1.0.0")] + +extern crate alloc as std; + +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::alloc as alloc; + +use crate::alloc::{Allocator, Global}; + +#[stable(feature = "rust1", since = "1.0.0")] +pub struct Vec { + ptr: *mut T, + cap: usize, + len: usize, + alloc: A, +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for Vec {} + +impl Vec { + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn len(&self) -> usize { + self.len + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn as_ptr(&self) -> *const T { + self.ptr + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn as_mut_ptr(&mut self) -> *mut T { + self.ptr + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + self.len = new_len; + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn allocator(&self) -> &A { + &self.alloc + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod extract_if; diff --git a/verifast-proofs/alloc/vec/extract_if.rs/update.sh b/verifast-proofs/alloc/vec/extract_if.rs/update.sh new file mode 100644 index 0000000000000..8e43ef2195763 --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/update.sh @@ -0,0 +1,10 @@ +set -x -e + +if ! git diff --quiet .; then + echo "Working directory not clean. Please stash your changes and try again" + false +else + UPSTREAM=../../../../library/alloc/src/vec/extract_if.rs + git merge-file --diff3 verified/extract_if.rs original/extract_if.rs $UPSTREAM + cp $UPSTREAM original/extract_if.rs +fi diff --git a/verifast-proofs/alloc/vec/extract_if.rs/verified/extract_if.rs b/verifast-proofs/alloc/vec/extract_if.rs/verified/extract_if.rs new file mode 100644 index 0000000000000..05fcda1649ffc --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/verified/extract_if.rs @@ -0,0 +1,721 @@ +use core::ops::{Range, RangeBounds}; +use core::{fmt, ptr, slice}; + +use super::Vec; +use crate::alloc::{Allocator, Global}; + +//@ use std::alloc::{Allocator, Global}; +//@ use std::option::{Option, Option::None, Option::Some}; + +/// An iterator which uses a closure to determine if an element should be removed. +/// +/// This struct is created by [`Vec::extract_if`]. +/// See its documentation for more. +/// +/// # Example +/// +/// ``` +/// let mut v = vec![0, 1, 2]; +/// let iter: std::vec::ExtractIf<'_, _, _> = v.extract_if(.., |x| *x % 2 == 0); +/// ``` +#[stable(feature = "extract_if", since = "1.87.0")] +#[must_use = "iterators are lazy and do nothing unless consumed; \ + use `retain_mut` or `extract_if().for_each(drop)` to remove and discard elements"] +pub struct ExtractIf< + 'a, + T, + F, + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + vec: &'a mut Vec, + /// The index of the item that will be inspected by the next call to `next`. + idx: usize, + /// Elements at and beyond this point will be retained. Must be equal or smaller than `old_len`. + end: usize, + /// The number of items that have been drained (removed) thus far. + del: usize, + /// The original length of `vec` prior to draining. + old_len: usize, + /// The filter test predicate. + pred: F, +} + +/*@ + +pred_ctor ExtractIf_fbc( + t: thread_id_t, + vec: *Vec, + ghost_cell_id: i32, + end: usize, + old_len: usize +)() = + type_interp::() &*& + type_interp::() &*& + type_interp::>() &*& + [1/2]ghost_cell::>>(ghost_cell_id, ?state) &*& + match state { + none => + *vec |-> ?v &*& + >.own(t, v), + some(p) => + struct_Vec_padding::(vec) &*& + (*vec).ptr |-> ?buf &*& + (*vec).cap |-> ?cap &*& + (*vec).len |-> 0 &*& + (*vec).alloc |-> ?a &*& + .own(t, a) &*& + Vec_alloc_handle(buf as usize, cap * std::mem::size_of::()) &*& + 0 <= snd(p) &*& snd(p) <= fst(p) &*& fst(p) <= end &*& end <= old_len &*& old_len <= cap &*& cap * std::mem::size_of::() <= isize::MAX &*& + 0 <= buf as usize &*& buf as usize % std::mem::align_of::() == 0 &*& + buf[..fst(p) - snd(p)] |-> ?retained &*& foreach(retained, own::(t)) &*& + buf[fst(p) - snd(p)..fst(p)] |-> _ &*& + buf[fst(p)..old_len] |-> ?tail &*& foreach(tail, own::(t)) &*& + buf[old_len..cap] |-> _ + }; + +pred<'a, T, F, A> >.own(t, ex) = + .own(t, ex.`pred`) &*& + 0 <= ex.del &*& ex.del <= ex.idx &*& ex.idx <= ex.end &*& ex.end <= ex.old_len &*& + [1/2]ghost_cell::>>(?ghost_cell_id, some(pair(ex.idx, ex.del))) &*& + full_borrow('a, ExtractIf_fbc::(t, ex.vec, ghost_cell_id, ex.end, ex.old_len)); + +lem ExtractIf_drop<'a, T, F, A>() + req ExtractIf_own::<'a, T, F, A>(?_t, ?_v); + ens .own(_t, _v.`pred`); +{ + open >.own(_t, _v); + leak full_borrow(_, _); + leak [1/2]ghost_cell(_, _); +} + +lem foreach_own_send(t0: thread_id_t, t1: thread_id_t) + req foreach(?xs, own::(t0)) &*& type_interp::() &*& is_Send(typeid(T)) == true; + ens foreach(xs, own::(t1)) &*& type_interp::(); +{ + open foreach(xs, own::(t0)); + match xs { + nil => {} + cons(x, xs0) => { + open own::(t0)(x); + Send::send::(t0, t1, x); + close own::(t1)(x); + foreach_own_send::(t0, t1); + } + } + close foreach(xs, own::(t1)); +} + +lem ExtractIf_fbc_send(t0: thread_id_t, t1: thread_id_t, vec: *Vec, id: i32, end: usize, old_len: usize) + req is_Send(typeid(T)) == true &*& is_Send(typeid(A)) == true &*& is_Send(typeid(Vec)) == true &*& + ExtractIf_fbc::(t0, vec, id, end, old_len)(); + ens ExtractIf_fbc::(t1, vec, id, end, old_len)(); +{ + open ExtractIf_fbc::(t0, vec, id, end, old_len)(); + assert [1/2]ghost_cell(id, ?state); + match state { + none => { + Send::send::>(t0, t1, *vec); + } + some(p) => { + Send::send::(t0, t1, (*vec).alloc); + foreach_own_send::(t0, t1); + foreach_own_send::(t0, t1); + } + } + close ExtractIf_fbc::(t1, vec, id, end, old_len)(); +} + +lem ExtractIf_send<'a, T, F, A>(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& type_interp::() &*& + is_Send(typeid(ExtractIf<'a, T, F, A>)) == true &*& + ExtractIf_own::<'a, T, F, A>(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& + ExtractIf_own::<'a, T, F, A>(t1, v); +{ + open >.own(t0, v); + assert [1/2]ghost_cell(?id, _); + Send::send::(t0, t1, v.`pred`); + // `ExtractIf<'a, T, F, A>: Send` implies `&'a mut Vec: Send`, hence `Vec: Send`, + // hence `T: Send && A: Send` (`unsafe impl Send for Vec`). + assume(is_Send(typeid(T)) == true && is_Send(typeid(A)) == true && is_Send(typeid(Vec)) == true); + { + produce_lem_ptr_chunk implies( + ExtractIf_fbc::(t0, v.vec, id, v.end, v.old_len), + ExtractIf_fbc::(t1, v.vec, id, v.end, v.old_len) + )() { + ExtractIf_fbc_send::(t0, t1, v.vec, id, v.end, v.old_len); + } { + produce_lem_ptr_chunk implies( + ExtractIf_fbc::(t1, v.vec, id, v.end, v.old_len), + ExtractIf_fbc::(t0, v.vec, id, v.end, v.old_len) + )() { + ExtractIf_fbc_send::(t1, t0, v.vec, id, v.end, v.old_len); + } { + full_borrow_implies( + 'a, + ExtractIf_fbc::(t0, v.vec, id, v.end, v.old_len), + ExtractIf_fbc::(t1, v.vec, id, v.end, v.old_len) + ); + } + } + } + close >.own(t1, v); +} + +lem ExtractIf_own_mono<'a0, 'a1, T, F0, F1, A>() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + ExtractIf_own::<'a0, T, F0, A>(?t, ?v) &*& + lifetime_inclusion('a1, 'a0) == true &*& + is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + ExtractIf_own::<'a1, T, F1, A>(t, ExtractIf::<'a1, T, F1, A> { + vec: v.vec as *_, + idx: upcast(v.idx), + end: upcast(v.end), + del: upcast(v.del), + old_len: upcast(v.old_len), + `pred`: upcast(v.`pred`) + }); +{ + open >.own(t, v); + assert [1/2]ghost_cell(?id, _); + own_mono::(t, v.`pred`); + full_borrow_mono('a0, 'a1, ExtractIf_fbc::(t, v.vec, id, v.end, v.old_len)); + // `upcast` on `usize` is identity (https://github.com/verifast/verifast/issues/610). + assume(upcast(v.idx) == v.idx && upcast(v.end) == v.end && upcast(v.del) == v.del && upcast(v.old_len) == v.old_len); + close >.own(t, ExtractIf::<'a1, T, F1, A> { + vec: v.vec as *_, + idx: upcast(v.idx), + end: upcast(v.end), + del: upcast(v.del), + old_len: upcast(v.old_len), + `pred`: upcast(v.`pred`) + }); +} + +lem ptr_align_step(p: *T) + req 0 <= p as usize &*& p as usize % std::mem::align_of::() == 0; + ens 0 <= (p + 1) as usize &*& (p + 1) as usize % std::mem::align_of::() == 0; +{ + std::alloc::Layout_inv(std::alloc::Layout::new::()); + size_align::(); + let a = std::mem::align_of::(); + let sz = std::mem::size_of::(); + let p0 = p as usize; + div_rem_nonneg(p0, a); + div_rem_nonneg(sz, a); + div_rem_nonneg_unique(p0 + sz, a, p0 / a + sz / a, 0); +} + +fix u8s_for_elems(vs: list, bs: list>) -> bool { + match vs { + nil => bs == nil, + cons(v, vs0) => + length(bs) >= std::mem::size_of::() && + some(v) == of_u8s_(take(std::mem::size_of::(), bs)) && + u8s_for_elems::(vs0, drop(std::mem::size_of::(), bs)) + } +} + +lem take_drop_append_eq(n: usize, xs: list, ys: list) + req length(xs) == n; + ens take(n, append(xs, ys)) == xs &*& drop(n, append(xs, ys)) == ys; +{ + match xs { + nil => {} + cons(x, xs0) => { + take_drop_append_eq(n - 1, xs0, ys); + } + } +} + +lem array_to_u8s_bytes(p: *T) + req p[..?n] |-> ?vs; + ens (p as *u8)[..n * std::mem::size_of::()] |-?-> ?bs &*& + u8s_for_elems::(vs, bs) == true &*& + (n == 0 || p as usize % std::mem::align_of::() == 0); +{ + open array::(p, n, vs); + match vs { + nil => { + close array_::(p as *u8, 0, nil); + } + cons(v, vs0) => { + to_u8s_::(p); + assert (p as *u8)[..std::mem::size_of::()] |-?-> ?b0; + array_to_u8s_bytes::(p + 1); + assert ((p + 1) as *u8)[..(n - 1) * std::mem::size_of::()] |-?-> ?bs0; + array__join::(p as *u8); + take_drop_append_eq(std::mem::size_of::(), b0, bs0); + } + } +} + +lem u8s_bytes_to_array(p: *T, vs: list) + req (p as *u8)[..?m] |-?-> ?bs &*& + 0 <= p as usize &*& p as usize % std::mem::align_of::() == 0 &*& + u8s_for_elems::(vs, bs) == true; + ens p[..length(vs)] |-> vs &*& + 0 <= ((p as *u8) + m) as usize &*& ((p as *u8) + m) as usize % std::mem::align_of::() == 0; +{ + match vs { + nil => { + open array_::(p as *u8, m, bs); + close array::(p, 0, nil); + } + cons(v, vs0) => { + std::alloc::Layout_inv(std::alloc::Layout::new::()); + let sz = std::mem::size_of::(); + array__split::(p as *u8, sz); + from_u8s_::(p); + ptr_align_step::(p); + assert ((p as *u8) + sz) == ((p + 1) as *u8); + u8s_bytes_to_array::(p + 1, vs0); + close array::(p, length(vs), vs); + } + } +} + +// Connecting base lemma (called directly by `ExtractIf::new`): splits `buf[..old_len]` +// at `start` after `vec.set_len(0)` to establish `ExtractIf_fbc` in state +// `some(pair(start, 0))` for all `T` (including ZSTs with `cap == usize::MAX`). +lem ExtractIf_init_from_vec_buffer( + t: thread_id_t, + vec: *Vec, + buf: *T, + start: usize, + end: usize, + old_len: usize, + cap: usize +) -> i32 + req type_interp::() &*& + type_interp::() &*& + type_interp::>() &*& + struct_Vec_padding::(vec) &*& + (*vec).ptr |-> buf &*& + (*vec).cap |-> cap &*& + (*vec).len |-> 0 &*& + (*vec).alloc |-> ?a &*& + .own(t, a) &*& + Vec_alloc_handle(buf as usize, cap * std::mem::size_of::()) &*& + 0 <= start &*& start <= end &*& end <= old_len &*& old_len <= cap &*& + cap * std::mem::size_of::() <= isize::MAX &*& + 0 <= buf as usize &*& buf as usize % std::mem::align_of::() == 0 &*& + buf[..old_len] |-> ?elems &*& foreach(elems, own::(t)) &*& + buf[old_len..cap] |-> _; + ens [1/2]ghost_cell::>>(result, some(pair(start, 0))) &*& + ExtractIf_fbc::(t, vec, result, end, old_len)(); +{ + array_split::(buf, start); + foreach_split(elems, own::(t), start); + close array_::(buf + start, 0, nil); + let id = create_ghost_cell::>>(some(pair(start, 0))); + close ExtractIf_fbc::(t, vec, id, end, old_len)(); + return id; +} + +// Connecting restoring lemma (called directly inside `ExtractIf::new`'s +// `full_borrow_convert_strong`): in BOTH `none` (after `ExtractIf::drop`) and +// `some(p)` (if `ExtractIf` is leaked via `mem::forget`, relying on `vec.set_len(0)` +// leak amplification), `ExtractIf_fbc` restores `>.full_borrow_content(t, vec)()`. +lem ExtractIf_fbc_restore_vec( + t: thread_id_t, + vec: *Vec, + ghost_cell_id: i32, + end: usize, + old_len: usize +) + req ExtractIf_fbc::(t, vec, ghost_cell_id, end, old_len)(); + ens type_interp::() &*& type_interp::() &*& type_interp::>() &*& + >.full_borrow_content(t, vec)(); +{ + open ExtractIf_fbc::(t, vec, ghost_cell_id, end, old_len)(); + assert [1/2]ghost_cell(ghost_cell_id, ?state); + leak [1/2]ghost_cell(ghost_cell_id, state); + match state { + none => { + close_full_borrow_content::>(t, vec); + } + some(p) => { + assert (*vec).ptr |-> ?buf &*& (*vec).cap |-> ?cap &*& (*vec).len |-> 0 &*& (*vec).alloc |-> ?a; + assert buf[..fst(p) - snd(p)] |-> ?retained; + assert buf[fst(p)..old_len] |-> ?tail; + leak foreach(retained, own::(t)); + leak foreach(tail, own::(t)); + array_to_array_::(buf); + array__join::(buf); + array_to_array_::(buf + fst(p)); + array__join::(buf); + array__join::(buf); + close array::(buf, 0, nil); + close foreach(nil, own::(t)); + close_points_to(vec); + close >.own(t, *vec); + close_full_borrow_content::>(t, vec); + } + } +} + +@*/ + +fn slice_range__VeriFast_wrapper>(range: R, old_len: usize) -> Range +//@ req thread_token(?t) &*& .own(t, range); +//@ ens thread_token(t) &*& >.own(t, result) &*& 0 <= result.start &*& result.start <= result.end &*& result.end <= old_len; +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + slice::range(range, ..old_len) +} + +impl<'a, T, F, A: Allocator> ExtractIf<'a, T, F, A> { + pub(super) fn new>(vec: &'a mut Vec, pred: F, range: R) -> Self + //@ req thread_token(?t) &*& [?q]lifetime_token('a) &*& full_borrow('a, >.full_borrow_content(t, vec)) &*& .own(t, `pred`) &*& .own(t, range); + //@ ens thread_token(t) &*& [q]lifetime_token('a) &*& >.own(t, result); + { + //@ let klong = open_full_borrow_strong('a, >.full_borrow_content(t, vec), q); + //@ open_full_borrow_content::>(t, vec); + //@ assert *vec |-> ?v0; + //@ open >.own(t, v0); + //@ let vref = precreate_ref(vec); + //@ init_ref_readonly(vref, 1/2); + //@ open_points_to(vref); + let old_len = vec.len(); + //@ close_points_to(vref, 1/2); + //@ end_ref_readonly(vref); + //@ open_points_to(vec); + //@ let buf = v0.ptr; + //@ let cap = v0.cap; + let Range { start, end } = slice_range__VeriFast_wrapper(range, old_len); + //@ leak >.own(t, _); + + // Guard against the vec getting leaked (leak amplification) + // SAFETY: Setting length to 0 is always okay. + unsafe { + vec.set_len(0); + } + /*@ { + produce_type_interp::(); + produce_type_interp::(); + produce_type_interp::>(); + let ghost_cell_id = ExtractIf_init_from_vec_buffer::(t, vec, buf, start, end, old_len, cap); + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + ExtractIf_fbc::(t, vec, ghost_cell_id, end, old_len), + klong, + >.full_borrow_content(t, vec) + )() { + open Ctx(); + ExtractIf_fbc_restore_vec::(t, vec, ghost_cell_id, end, old_len); + leak type_interp::() &*& type_interp::() &*& type_interp::>(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + >.full_borrow_content(t, vec), + ExtractIf_fbc::(t, vec, ghost_cell_id, end, old_len) + ); + full_borrow_mono(klong, 'a, ExtractIf_fbc::(t, vec, ghost_cell_id, end, old_len)); + } + } + } @*/ + let res = ExtractIf { vec, idx: start, del: 0, end, old_len, pred }; + //@ close >.own(t, res); + res + } + + /// Returns a reference to the underlying allocator. + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn allocator(&self) -> &A { + self.vec.allocator() + } +} + +fn call_pred__VeriFast_wrapper bool>(f: &mut F, element: &mut T) -> bool +//@ req thread_token(?t) &*& *f |-> ?f0 &*& .own(t, f0) &*& *element |-> ?element0 &*& .own(t, element0); +//@ ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& *element |-> ?element1 &*& .own(t, element1); +//@ on_unwind_ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& *element |-> ?element1 &*& .own(t, element1); +//@ assume_correct +{ + f(element) +} + +#[stable(feature = "extract_if", since = "1.87.0")] +impl Iterator for ExtractIf<'_, T, F, A> +where + F: FnMut(&mut T) -> bool, +{ + type Item = T; + + fn next(&mut self) -> Option + //@ req thread_token(?t) &*& [?q]lifetime_token('_0) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& [q]lifetime_token('_0) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t) &*& [q]lifetime_token('_0) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + loop { + //@ inv thread_token(t) &*& lifetime_token(flft) &*& [q]lifetime_token('_0) &*& *self |-> ?self_cur &*& >.own(t, self_cur); + //@ open_points_to(self); + if self.idx < self.end { + let i = self.idx; + //@ open >.own(t, self_cur); + //@ assert [1/2]ghost_cell(?ghost_cell_id, some(pair(?idx0, ?del0))); + //@ open_full_borrow(q, '_0, ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)); + //@ open ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)(); + //@ merge_fractions ghost_cell(ghost_cell_id, _); + //@ assert (*self_cur.vec).ptr |-> ?buf &*& (*self_cur.vec).cap |-> ?cap; + //@ assert buf[..idx0 - del0] |-> ?retained; + //@ assert buf[idx0..self_cur.old_len] |-> ?tail; + //@ open array::(buf + idx0, self_cur.old_len - idx0, tail); + //@ open foreach(tail, own::(t)); + //@ assert *(buf + idx0) |-> ?cur_val0; + //@ open own::(t)(cur_val0); + //@ assert (buf + idx0 + 1)[..self_cur.old_len - idx0 - 1] |-> ?tail_rest; + // SAFETY: + // We know that `i < self.end` from the if guard and that `self.end <= self.old_len` from + // the validity of `Self`. Therefore `i` points to an element within `vec`. + // + // Additionally, the i-th element is valid because each element is visited at most once + // and it is the first time we access vec[i]. + // + // Note: we can't use `vec.get_unchecked_mut(i)` here since the precondition for that + // function is that i < vec.len(), but we've set vec's length to zero. + //@ std::alloc::Layout_inv(std::alloc::Layout::new::()); + //@ mul_mono_l(i, cap, std::mem::size_of::()); + let cur = unsafe { &mut *self.vec.as_mut_ptr().add(i) }; + let f = &mut self.pred; + let c = &mut *cur; + let drained = call_pred__VeriFast_wrapper(f, c); + //@ assert *(buf + idx0) |-> ?cur_val1 &*& .own(t, cur_val1); + // Update the index *after* the predicate is called. If the index + // is updated prior and the predicate panics, the element at this + // index would be leaked. + self.idx += 1; + if drained { + self.del += 1; + // SAFETY: We never touch this element again after returning it. + let r = Some(unsafe { ptr::read(cur) }); + /*@ { + close array::(buf + idx0 + 1, 0, nil); + close array::(buf + idx0, 1, [cur_val1]); + array_to_array_::(buf + idx0); + array__join::(buf + (idx0 - del0)); + ghost_cell_mutate::>>(ghost_cell_id, some(pair(idx0 + 1, del0 + 1))); + close ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)(); + close_full_borrow(ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)); + close_points_to(self); + close >.own(t, *self); + close >.own(t, r); + } @*/ + return r; + } else if self.del > 0 { + // SAFETY: `self.del` > 0, so the hole slot must not overlap with current element. + // We use copy for move, and never touch this element again. + unsafe { + //@ mul_mono_l(idx0 - del0, cap, std::mem::size_of::()); + let hole_slot = self.vec.as_mut_ptr().add(i - self.del); + /*@ { + array__split::(buf + (idx0 - del0), 1); + close array::(buf + idx0 + 1, 0, nil); + close array::(buf + idx0, 1, [cur_val1]); + } @*/ + ptr::copy_nonoverlapping(cur, hole_slot, 1); + /*@ { + array_to_array_::(buf + idx0); + array__join::(buf + (idx0 - del0 + 1)); + array_join::(buf); + close own::(t)(cur_val1); + close foreach([], own::(t)); + close foreach([cur_val1], own::(t)); + foreach_append(retained, [cur_val1]); + } @*/ + } + /*@ { + ghost_cell_mutate::>>(ghost_cell_id, some(pair(idx0 + 1, del0))); + close ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)(); + close_full_borrow(ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)); + close_points_to(self); + close >.own(t, *self); + } @*/ + } + /*@ { + if del0 == 0 { + close array::(buf + idx0 + 1, 0, nil); + close array::(buf + idx0, 1, [cur_val1]); + array_join::(buf); + close own::(t)(cur_val1); + close foreach([], own::(t)); + close foreach([cur_val1], own::(t)); + foreach_append(retained, [cur_val1]); + open array_::(buf + idx0, 0, _); + close array_::(buf + idx0 + 1, 0, nil); + ghost_cell_mutate::>>(ghost_cell_id, some(pair(idx0 + 1, 0))); + close ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)(); + close_full_borrow(ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)); + close_points_to(self); + close >.own(t, *self); + } + } @*/ + } else { + //@ close_points_to(self); + break; + } + } + //@ close >.own(t, None); + None + } + + fn size_hint(&self) -> (usize, Option) { + (0, Some(self.end - self.idx)) + } +} + +unsafe fn drop_body__VeriFast_wrapper<'a, T, F, A: Allocator>(this: &mut ExtractIf<'a, T, F, A>) +//@ req thread_token(?t) &*& t == currentThread &*& [?q]lifetime_token('a) &*& >.full_borrow_content(t, this)(); +//@ ens thread_token(t) &*& [q]lifetime_token('a) &*& (*this).vec |-> ?_vec &*& full_borrow('a, >.full_borrow_content(t, _vec)) &*& (*this).idx |-> ?_idx &*& (*this).end |-> ?_end &*& (*this).del |-> ?_del &*& (*this).old_len |-> ?_old_len &*& (*this).`pred` |-> ?p &*& .own(t, p) &*& struct_ExtractIf_padding(this); +{ + //@ open >.full_borrow_content(t, this)(); + //@ open_points_to(this); + //@ open >.own(t, ?self0); + //@ assert [1/2]ghost_cell(?ghost_cell_id, some(pair(?idx0, ?del0))); + //@ let klong = open_full_borrow_strong('a, ExtractIf_fbc::(t, self0.vec, ghost_cell_id, self0.end, self0.old_len), q); + //@ open ExtractIf_fbc::(t, self0.vec, ghost_cell_id, self0.end, self0.old_len)(); + //@ merge_fractions ghost_cell(ghost_cell_id, _); + //@ assert (*self0.vec).ptr |-> ?buf &*& (*self0.vec).cap |-> ?cap; + //@ assert buf[..idx0 - del0] |-> ?retained; + //@ assert buf[idx0..self0.old_len] |-> ?tail; + if this.del > 0 { + // SAFETY: Trailing unchecked items must be valid since we never touch them. + unsafe { + //@ std::alloc::Layout_inv(std::alloc::Layout::new::()); + //@ mul_mono_l(idx0, cap, std::mem::size_of::()); + //@ mul_mono_l(idx0 - del0, cap, std::mem::size_of::()); + //@ close_points_to(self0.vec); + //@ let vref = precreate_ref(self0.vec); + //@ init_ref_readonly(vref, 1/2); + //@ open_points_to(vref); + let src = this.vec.as_ptr().add(this.idx); + //@ close_points_to(vref, 1/2); + //@ end_ref_readonly(vref); + //@ open_points_to(self0.vec); + let dst = this.vec.as_mut_ptr().add(this.idx - this.del); + let count = this.old_len - this.idx; + /*@ { + let sz = std::mem::size_of::(); + array_to_u8s_bytes::(buf + idx0); + assert ((buf + idx0) as *u8)[..count * sz] |-?-> ?bs; + if del0 >= count { + array__split::(buf + (idx0 - del0), count); + array__to_u8s_::(buf + (idx0 - del0), count); + close exists::>(none); + } else { + array__to_u8s_::(buf + (idx0 - del0), del0); + close exists::>(some(-del0)); + } + } @*/ + ptr::copy(src, dst, count); + /*@ { + u8s_bytes_to_array::(buf + (idx0 - del0), tail); + if del0 >= count { + if count == 0 { + open array_::((buf + idx0) as *u8, 0, _); + close array_::(buf + idx0, 0, nil); + } else { + u8s__to_array_::(buf + idx0, count); + } + array__join::(buf + (self0.old_len - del0)); + } else { + u8s__to_array_::(buf + (self0.old_len - del0), del0); + } + array__join::(buf + (self0.old_len - del0)); + } @*/ + } + } + /*@ { + if del0 == 0 { + open array_::(buf + idx0, 0, _); + } + array_join::(buf); + foreach_append(retained, tail); + } @*/ + // SAFETY: After filling holes, all items are in contiguous memory. + unsafe { + this.vec.set_len(this.old_len - this.del); + } + /*@ { + close_points_to(self0.vec); + close >.own(t, *self0.vec); + close_full_borrow_content::>(t, self0.vec); + ghost_cell_mutate::>>(ghost_cell_id, none); + { + pred Ctx() = + type_interp::() &*& + type_interp::() &*& + type_interp::>() &*& + [1/2]ghost_cell::>>(ghost_cell_id, none); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + >.full_borrow_content(t, self0.vec), + klong, + ExtractIf_fbc::(t, self0.vec, ghost_cell_id, self0.end, self0.old_len) + )() { + open Ctx(); + open_full_borrow_content::>(t, self0.vec); + close ExtractIf_fbc::(t, self0.vec, ghost_cell_id, self0.end, self0.old_len)(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + ExtractIf_fbc::(t, self0.vec, ghost_cell_id, self0.end, self0.old_len), + >.full_borrow_content(t, self0.vec) + ); + full_borrow_mono(klong, 'a, >.full_borrow_content(t, self0.vec)); + } + } + leak [1/2]ghost_cell(_, _); + } @*/ +} + +#[stable(feature = "extract_if", since = "1.87.0")] +impl Drop for ExtractIf<'_, T, F, A> { + fn drop(&mut self) { + unsafe { drop_body__VeriFast_wrapper(self) } + } +} + +#[stable(feature = "extract_if", since = "1.87.0")] +impl fmt::Debug for ExtractIf<'_, T, F, A> +where + T: fmt::Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // We have to use pointer arithmetics here, + // because the length of `self.vec` is temporarily set to 0. + let start = self.vec.as_ptr(); + + // SAFETY: we always keep first `self.idx - self.del` elements valid. + let retained = unsafe { slice::from_raw_parts(start, self.idx - self.del) }; + + let valid_tail = + // SAFETY: we have not yet touched elements starting at `self.idx`. + unsafe { slice::from_raw_parts(start.add(self.idx), self.old_len - self.idx) }; + + let (remainder, skipped_tail) = + // SAFETY: `end - idx <= old_len - idx`, because `end <= old_len`. + // Also `idx <= end` by invariant. + unsafe { valid_tail.split_at_unchecked(self.end - self.idx) }; + + f.debug_struct("ExtractIf") + .field("retained", &retained) + .field("remainder", &remainder) + .field("skipped_tail", &skipped_tail) + .finish_non_exhaustive() + } +} + +#[cfg(all(kani, not(no_global_oom_handling)))] +#[path = "verify_extract_if.rs"] +mod verify; diff --git a/verifast-proofs/alloc/vec/extract_if.rs/verified/lib.rs b/verifast-proofs/alloc/vec/extract_if.rs/verified/lib.rs new file mode 100644 index 0000000000000..c88741eeccff2 --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/verified/lib.rs @@ -0,0 +1,302 @@ +// verifast_options{skip_specless_fns} + +#![no_std] +#![allow(internal_features)] +#![allow(incomplete_features)] +#![feature(allocator_ext)] +#![feature(staged_api)] +#![feature(rustc_attrs)] +#![feature(slice_range)] + +#![stable(feature = "rust1", since = "1.0.0")] + +extern crate alloc as std; + +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::alloc as alloc; + +use crate::alloc::{Allocator, Global}; + +//@ use std::alloc::{Allocator, Global}; + +#[stable(feature = "rust1", since = "1.0.0")] +pub struct Vec { + ptr: *mut T, + cap: usize, + len: usize, + alloc: A, +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for Vec {} + +/*@ + +// Abstract handle representing the backing allocation owned by `RawVec` +// (untouched by `ExtractIf`, which never allocates, reallocates, or deallocates). +// Unlike VeriFast 26.10's `std/lib.rsspec:1704` `Vec_inv` (`capacity <= isize::MAX`), +// this `Vec` model enforces Rust's true ZST-sound bound `cap * size_of::() <= isize::MAX` +// matching VeriFast's own `prelude_core.rsspec:253` `array__inv`. +pred Vec_alloc_handle(addr: usize, byte_cap: usize); + +pred >.own(t, v) = + .own(t, v.alloc) &*& + Vec_alloc_handle(v.ptr as usize, v.cap * std::mem::size_of::()) &*& + 0 <= v.len &*& v.len <= v.cap &*& + v.cap * std::mem::size_of::() <= isize::MAX &*& + 0 <= v.ptr as usize &*& v.ptr as usize % std::mem::align_of::() == 0 &*& + v.ptr[..v.len] |-> ?elems &*& foreach(elems, own::(t)) &*& + v.ptr[v.len..v.cap] |-> _; + +pred_ctor Vec_val(l: *Vec, v: Vec)(;) = + *l |-> v; + +pred >.share(k, t, l) = + [_]exists::>(?v) &*& [_]frac_borrow(k, Vec_val::(l, v)); + +lem Vec_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *Vec) + req type_interp::() &*& type_interp::() &*& + lifetime_inclusion(k1, k) == true &*& [_]Vec_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]Vec_share::(k1, t, l); +{ + open Vec_share::(k, t, l); + assert [_]exists::>(?v) &*& [_]frac_borrow(k, Vec_val::(l, v)); + frac_borrow_mono(k, k1, Vec_val::(l, v)); + close exists::>(v); + leak exists::>(v); + close Vec_share::(k1, t, l); + leak Vec_share::(k1, t, l); +} + +lem Vec_share_full(k: lifetime_t, t: thread_id_t, l: *Vec) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + full_borrow(k, Vec_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + [_]Vec_share::(k, t, l) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong_m(k, Vec_full_borrow_content::(t, l), q); + open Vec_full_borrow_content::(t, l)(); + assert *l |-> ?v; + close Vec_val::(l, v)(); + { + pred Ctx() = >.own(t, v); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + Vec_val::(l, v), + klong, + Vec_full_borrow_content::(t, l) + )() { + open Ctx(); + open Vec_val::(l, v)(); + close Vec_full_borrow_content::(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m(klong, Vec_full_borrow_content::(t, l), Vec_val::(l, v)); + full_borrow_into_frac_m(klong, Vec_val::(l, v)); + frac_borrow_mono(klong, k, Vec_val::(l, v)); + } + } + close exists::>(v); + leak exists::>(v); + close Vec_share::(k, t, l); + leak Vec_share::(k, t, l); +} + +lem init_ref_Vec(p: *Vec) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + ref_init_perm(p, ?x) &*& [_]Vec_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + [q]lifetime_token(k) &*& [_]Vec_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open >.share(k, t, x); + assert [_]exists::>(?v); + let klong = open_frac_borrow_strong_m(k, Vec_val::(x, v), q); + open [?f]Vec_val::(x, v)(); + init_ref_readonly(p, 1/2); + close [f/2]Vec_val::(p, v)(); + close scaledp(f/2, Vec_val::(p, v))(); + close ref_initialized_::>(p)(); + close sep(scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p))(); + { + pred Ctx() = + ref_readonly_end_token(p, x, f/2) &*& + [f/2](*x |-> v); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + sep(scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p)), + klong, + f, + Vec_val::(x, v) + )() { + open Ctx(); + open sep(scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p))(); + open scaledp(f/2, Vec_val::(p, v))(); + open [f/2]Vec_val::(p, v)(); + open ref_initialized_::>(p)(); + end_ref_readonly(p); + close [f]Vec_val::(x, v)(); + } { + close Ctx(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, sep(scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p))); + full_borrow_split_m(k, scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p)); + full_borrow_into_frac_m(k, scaledp(f/2, Vec_val::(p, v))); + frac_borrow_implies_scaled(k, f/2, Vec_val::(p, v)); + full_borrow_into_frac_m(k, ref_initialized_::>(p)); + } + } + close exists::>(v); + leak exists::>(v); + close Vec_share::(k, t, p); + leak Vec_share::(k, t, p); +} + +lem foreach_own_send_lib(t0: thread_id_t, t1: thread_id_t) + req foreach(?xs, own::(t0)) &*& type_interp::() &*& is_Send(typeid(T)) == true; + ens foreach(xs, own::(t1)) &*& type_interp::(); +{ + open foreach(xs, own::(t0)); + match xs { + nil => {} + cons(x, xs0) => { + open own::(t0)(x); + Send::send::(t0, t1, x); + close own::(t1)(x); + foreach_own_send_lib::(t0, t1); + } + } + close foreach(xs, own::(t1)); +} + +lem Vec_drop() + req Vec_own::(?_t, ?_v); + ens .own(_t, _v.alloc); +{ + open >.own(_t, _v); + leak Vec_alloc_handle(_, _); + leak _v.ptr[.._v.len] |-> ?elems &*& foreach(elems, own::(_t)); + leak _v.ptr[_v.len.._v.cap] |-> _; +} + +lem Vec_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Send(typeid(Vec)) == true &*& + Vec_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& + Vec_own::(t1, v); +{ + open >.own(t0, v); + // `unsafe impl Send for Vec` implies `T: Send && A: Send`. + assume(is_Send(typeid(T)) == true && is_Send(typeid(A)) == true); + Send::send::(t0, t1, v.alloc); + foreach_own_send_lib::(t0, t1); + close >.own(t1, v); +} + +lem Vec_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& + Vec_own::(?t, ?v) &*& + is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& + Vec_own::(t, Vec:: { + ptr: v.ptr as *_, + cap: upcast(v.cap), + len: upcast(v.len), + alloc: upcast(v.alloc) + }); +{ + open >.own(t, v); + own_mono::(t, v.alloc); + // `upcast` on `usize` is identity (verifast#610). + assume(upcast(v.cap) == v.cap && upcast(v.len) == v.len); + close >.own(t, Vec:: { + ptr: v.ptr as *_, + cap: upcast(v.cap), + len: upcast(v.len), + alloc: upcast(v.alloc) + }); +} + +@*/ + +impl Vec { + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn len(&self) -> usize + //@ req [?f](*self).len |-> ?len; + //@ ens [f](*self).len |-> len &*& result == len; + /*@ + safety_proof { + open >.share(?k, _t, self); + assert [?q]lifetime_token(k); + assert [_]exists::>(?v); + open_frac_borrow(k, Vec_val::(self, v), q); + open [?f]Vec_val::(self, v)(); + open_points_to(self); + call(); + close_points_to(self, f); + close [f]Vec_val::(self, v)(); + close_frac_borrow(f, Vec_val::(self, v)); + } + @*/ + { + self.len + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn as_ptr(&self) -> *const T + //@ req [?f](*self).ptr |-> ?p; + //@ ens [f](*self).ptr |-> p &*& result == p; + /*@ + safety_proof { + open >.share(?k, _t, self); + assert [?q]lifetime_token(k); + assert [_]exists::>(?v); + open_frac_borrow(k, Vec_val::(self, v), q); + open [?f]Vec_val::(self, v)(); + open_points_to(self); + call(); + close_points_to(self, f); + close [f]Vec_val::(self, v)(); + close_frac_borrow(f, Vec_val::(self, v)); + } + @*/ + { + self.ptr + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn as_mut_ptr(&mut self) -> *mut T + //@ req [?f](*self).ptr |-> ?p; + //@ ens [f](*self).ptr |-> p &*& result == p; + /*@ + safety_proof { + open_points_to(self); + call(); + close_points_to(self); + } + @*/ + { + self.ptr + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) + //@ req (*self).len |-> _; + //@ ens (*self).len |-> new_len; + { + self.len = new_len; + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn allocator(&self) -> &A { + &self.alloc + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod extract_if; diff --git a/verifast-proofs/alloc/vec/extract_if.rs/verify.sh b/verifast-proofs/alloc/vec/extract_if.rs/verify.sh new file mode 100644 index 0000000000000..a6d45d0d957d3 --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/verify.sh @@ -0,0 +1,10 @@ +set -e -x + +export VFVERSION=26.10 + +verifast -rustc_args "--edition 2024" -skip_specless_fns -ignore_unwind_paths -allow_assume verified/lib.rs +refinement-checker --rustc-args "--edition 2024" original/lib.rs verified/lib.rs > /dev/null +if ! diff original/extract_if.rs ../../../../library/alloc/src/vec/extract_if.rs; then + echo "::error title=Please run verifast-proofs/patch-verifast-proofs.sh::Some VeriFast proofs are out of date; please chdir to verifast-proofs and run patch-verifast-proofs.sh to update them." + false +fi diff --git a/verifast-proofs/check-verifast-proofs.sh b/verifast-proofs/check-verifast-proofs.sh index 23bd82948efbd..8b74f331273a5 100755 --- a/verifast-proofs/check-verifast-proofs.sh +++ b/verifast-proofs/check-verifast-proofs.sh @@ -17,4 +17,9 @@ cd alloc bash verify.sh cd .. cd .. + cd vec + cd extract_if.rs + bash verify.sh + cd .. + cd .. cd .. diff --git a/verifast-proofs/patch-verifast-proofs.sh b/verifast-proofs/patch-verifast-proofs.sh index 802b68ba7b68a..e7497c7f5cbdc 100755 --- a/verifast-proofs/patch-verifast-proofs.sh +++ b/verifast-proofs/patch-verifast-proofs.sh @@ -22,3 +22,6 @@ popd pushd alloc/raw_vec/mod.rs patch_proof popd +pushd alloc/vec/extract_if.rs + patch_proof +popd From b6b3e3f19633dbb2822156cf3ab55076d70db227 Mon Sep 17 00:00:00 2001 From: Emre Kaplaner Date: Mon, 30 Nov 2026 15:26:47 -0800 Subject: [PATCH 2/4] Harden Ch. 24: RawVec-bridged VeriFast Vec (0 assume(false)), StatefulAlloc & ConsumingDrop fold/try_fold --- library/alloc/src/vec/into_iter.rs | 17 +- library/alloc/src/vec/verify_extract_if.rs | 45 +- library/alloc/src/vec/verify_iter_spec.rs | 347 ++++++++++++-- .../alloc/vec/extract_if.rs/README.md | 142 ++++-- .../alloc/vec/extract_if.rs/original/lib.rs | 56 ++- .../vec/extract_if.rs/original/raw_vec.rs | 1 + .../vec/extract_if.rs/verified/extract_if.rs | 238 +++++++--- .../alloc/vec/extract_if.rs/verified/lib.rs | 437 ++++++++++++------ .../vec/extract_if.rs/verified/raw_vec.rs | 1 + .../alloc/vec/extract_if.rs/verify.sh | 7 +- .../with-directives/extract_if.rs | 1 + .../vec/extract_if.rs/with-directives/lib.rs | 98 ++++ .../extract_if.rs/with-directives/raw_vec.rs | 1 + 13 files changed, 1075 insertions(+), 316 deletions(-) create mode 120000 verifast-proofs/alloc/vec/extract_if.rs/original/raw_vec.rs create mode 120000 verifast-proofs/alloc/vec/extract_if.rs/verified/raw_vec.rs create mode 120000 verifast-proofs/alloc/vec/extract_if.rs/with-directives/extract_if.rs create mode 100644 verifast-proofs/alloc/vec/extract_if.rs/with-directives/lib.rs create mode 120000 verifast-proofs/alloc/vec/extract_if.rs/with-directives/raw_vec.rs diff --git a/library/alloc/src/vec/into_iter.rs b/library/alloc/src/vec/into_iter.rs index 92ba8c5f00601..74830f3475af3 100644 --- a/library/alloc/src/vec/into_iter.rs +++ b/library/alloc/src/vec/into_iter.rs @@ -266,12 +266,13 @@ unsafe impl Send for IntoIter {} unsafe impl Sync for IntoIter {} // Loop-invariant predicates for `IntoIter::fold` and `IntoIter::try_fold`. -// Marked `#[inline(always)]` and written with pure intrinsics rather than -// method calls (e.g. `NonNull::as_ptr` / `pointer::addr`) so CBMC evaluates -// them inline as side-effect-free loop-contract expressions -// (https://github.com/model-checking/kani/issues/4796). -// `self.alloc` is omitted because `ManuallyDrop` is not `Copy`; harnesses -// instantiate `A = TrackAlloc`, a ZST carrying no runtime state. +// Marked `#[inline(always)]` and written with pure intrinsics and `const { ... }` +// blocks rather than method calls (e.g. `NonNull::as_ptr` / `pointer::addr` / +// non-const `mem::size_of`) so Kani's loop-contract lowering evaluates them +// inline as side-effect-free CBMC expressions without emitting nondeterministic +// helper calls (https://github.com/model-checking/kani/issues/4796). +// `self.alloc` is untouched by either loop and is preserved across loop +// contracts (verified with both `TrackAlloc` and non-ZST `StatefulAlloc`). #[cfg(kani)] #[inline(always)] fn kani_into_iter_zst_inv( @@ -349,7 +350,7 @@ fn kani_into_iter_non_zst_inv( }; let diff = core::intrinsics::wrapping_sub(ptr_a, eptr_a); let span = core::intrinsics::wrapping_sub(end_a, eptr_a); - let sz = core::mem::size_of::(); + let sz = const { core::mem::size_of::() }; let aligned = if const { core::mem::size_of::().is_power_of_two() } { (diff & core::intrinsics::wrapping_sub(sz, 1)) == 0 } else { @@ -375,7 +376,7 @@ fn kani_into_iter_non_zst_inv( } }; let low_mask = core::intrinsics::wrapping_sub(1usize << tz, 1); - (diff & low_mask) == 0 && (diff >> tz).wrapping_mul(odd_inv) <= max_q + (diff & low_mask) == 0 && core::intrinsics::wrapping_mul(diff >> tz, odd_inv) <= max_q }; // SAFETY: `arith_offset` is wrapping (non-UB) pointer arithmetic; short-circuiting after // `diff <= span && aligned` additionally guarantees `diff` stays within `[entry_ptr, end]`. diff --git a/library/alloc/src/vec/verify_extract_if.rs b/library/alloc/src/vec/verify_extract_if.rs index 5a1b6e890ebf2..13c3a991373c1 100644 --- a/library/alloc/src/vec/verify_extract_if.rs +++ b/library/alloc/src/vec/verify_extract_if.rs @@ -24,7 +24,8 @@ use crate::vec::verify_iter_spec::{ /// and arbitrary iteration counts is additionally proved in VeriFast under /// `verifast-proofs/alloc/vec/extract_if.rs/` (`verifast` + `refinement-checker`), /// complementing this Kani inductive-step + concrete-layout harness (a mechanized -/// Kani `#[loop_invariant]` on `ExtractIf::next` is blocked by `kani#5071`). +/// Kani `#[loop_invariant]` on `ExtractIf::next` is blocked by the open +/// `#[loop_invariant]` support PR `kani#5071`). fn check_extract_if_next(use_up_to: bool, check_frame: bool) { let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; let (fill, m1, m2) = markers_for::(); @@ -348,12 +349,16 @@ fn check_extract_if_drop() { } /// Concrete-size content witness for `ExtractIf::drop` verifying exact -/// element preservation across the overlapping `ptr::copy` hole-close -/// (`cap = 5, old_len = 5, idx = 3, del = 2`, zero `write_bytes` so padding -/// stays genuinely uninitialized). +/// element preservation across BOTH the adjacent (`[3..5) -> [1..3)`, +/// `cap = 5, old_len = 5, idx = 3, del = 2`) and genuinely overlapping +/// (`[2..5) -> [1..4)`, `cap = 5, old_len = 5, idx = 2, del = 1`, `count = 3 > del = 1`) +/// `ptr::copy` hole-close paths (zero `write_bytes` so padding stays genuinely +/// uninitialized; unbounded overlapping `ptr::copy` is also proved in VeriFast). fn check_extract_if_drop_witness() { let (b0, b1, b2) = markers_for::(); + let b3 = T::any_distinct_three(b0, b1, b2); let layout = crate::alloc::Layout::array::(5).unwrap(); + // Case 1: adjacent copy (`[3..5) -> [1..3)`, `del = 2 == count`). // SAFETY: `5 * size_of::() > 0` (only instantiated on non-ZST types). let p = unsafe { crate::alloc::alloc(layout) }; kani::assume(!p.is_null()); @@ -382,6 +387,38 @@ fn check_extract_if_drop_witness() { assert!(tag_matches(v.as_ptr().add(2), b2)); } finish::(v); + + // Case 2: genuinely overlapping copy (`[2..5) -> [1..4)`, `count = 3 > del = 1`). + // SAFETY: `5 * size_of::() > 0`. + let p2 = unsafe { crate::alloc::alloc(layout) }; + kani::assume(!p2.is_null()); + let typed2: *mut T = p2.cast::(); + // SAFETY: Slot 0 (retained) and 2..5 (tail) initialized via typed write; + // hole slot 1 remains genuinely uninitialized. + unsafe { + mark(typed2, b0); + mark(typed2.add(2), b1); + mark(typed2.add(3), b2); + mark(typed2.add(4), b3); + } + // SAFETY: `typed2` came from `alloc` with `layout`; `len == 0` matches `ExtractIf::new`. + let mut v2 = unsafe { Vec::from_raw_parts(typed2, 0, 5) }; + reset_drops(); + { + let ei2 = + ExtractIf { vec: &mut v2, idx: 2, end: 3, del: 1, old_len: 5, pred: |_: &mut T| false }; + drop(ei2); + } + assert!(drops() == 0); + assert!(v2.len() == 4 && v2.capacity() == 5); + // SAFETY: `0..4` are live after `ExtractIf::drop` shifted `[2..5)` onto `[1..4)`. + unsafe { + assert!(tag_matches(v2.as_ptr(), b0)); + assert!(tag_matches(v2.as_ptr().add(1), b1)); + assert!(tag_matches(v2.as_ptr().add(2), b2)); + assert!(tag_matches(v2.as_ptr().add(3), b3)); + } + finish::(v2); } #[kani::proof] diff --git a/library/alloc/src/vec/verify_iter_spec.rs b/library/alloc/src/vec/verify_iter_spec.rs index 46b4dcf578c04..a391b3e8853eb 100644 --- a/library/alloc/src/vec/verify_iter_spec.rs +++ b/library/alloc/src/vec/verify_iter_spec.rs @@ -162,21 +162,21 @@ struct LargeElem(u8); unsafe impl core::clone::TrivialClone for LargeElem {} /// Number of `DropTracker*` / `DropZst` values dropped so far. -/// Initialized to a non-zero sentinel to avoid Kani's constant/static zero-byte -/// aliasing bug (https://github.com/model-checking/kani/issues/5088); every -/// harness calls `reset_drops()` / `reset_drop_trace()` before reading. +/// Non-zero sentinel initializers are kept defensively against static/constant +/// zero-byte aliasing (historical `kani#5088`, fixed in `#5089`); every harness +/// calls `reset_drops()` / `reset_drop_trace()` before reading. static mut DROPS: usize = 0x5A5A_5A5A_5A5A_5A5A; -// Non-zero sentinel initializers for custom-allocator deallocation tracking (kani#5088). +// Defensive non-zero sentinel initializers for custom-allocator deallocation tracking +// (historical `kani#5088`, fixed in `#5089`). static mut DEALLOCS: usize = 0x5A5A_5A5A_5A5A_5A5D; static mut LAST_DEALLOC_PTR: usize = 0x5A5A_5A5A_5A5A_5A5E; static mut LAST_DEALLOC_SIZE: usize = 0x5A5A_5A5A_5A5A_5A5F; static mut LAST_DEALLOC_TAG: u8 = 0x5A; /// Custom `Allocator` delegating to `Global` while recording every deallocation -/// `(ptr, size)`. ZST so `fold`/`try_fold`'s loop contracts do not need to carry -/// allocator state; `StatefulAlloc(u8)` below additionally tests non-ZST -/// `ManuallyDrop::take(&mut self.alloc)` in `into_vecdeque` and `drop`. +/// `(ptr, size)`. `StatefulAlloc(u8)` below additionally carries non-ZST runtime +/// state (`tag`) verified across `into_vecdeque`, `drop`, `fold`, and `try_fold`. #[derive(Clone, Copy, Debug)] struct TrackAlloc; @@ -423,8 +423,9 @@ impl Shape for OverAlignedTc { /// `-Z uninit-checks` in `library/core/src/num/nonzero.rs`). #[inline] fn nonzero_u8(b: u8) -> NonZero { - // SAFETY: Callers guarantee `b != 0` (`Shape::ALLOW_ZERO == false`), and - // `NonZero` is `#[repr(transparent)]` over a non-zero `u8`. + assert!(b != 0); + // SAFETY: Checked `b != 0` immediately above, and `NonZero` is + // `#[repr(transparent)]` over a non-zero `u8`. unsafe { mem::transmute::>(b) } } @@ -1118,7 +1119,8 @@ gen_harnesses! { check_from_iter_into_iter_advanced_witness: // `SpecFromIterNested::from_iter` (default, non-`TrustedLen` impl) // --------------------------------------------------------------------------- -// Non-zero sentinel initializers for modular `extend_desugared` handoff checks (kani#5088). +// Defensive non-zero sentinel initializers for modular `extend_desugared` handoff checks +// (historical `kani#5088`, fixed in `#5089`). static mut EXTEND_CALLED: bool = true; static mut EXTEND_PRE_LEN: usize = 0x5A5A_5A5A_5A5A_5A60; static mut EXTEND_PRE_CAP: usize = 0x5A5A_5A5A_5A5A_5A61; @@ -1525,9 +1527,6 @@ fn any_into_iter_in_mode( ) -> (IntoIter, usize) { let pick = |m: usize| if use_up_to { any_up_to(m) } else { down_from(m) }; let (buf, cap, len, adv) = if T::IS_ZST { - // A ZST `IntoIter` encodes its length as the byte distance from `ptr` - // to `end`. Kani models pointer offsets in 52 bits (`--object-bits 12`), - // so ZST `IntoIter` lengths are bounded by `MAX_ALLOCATION_BYTES`. let n = pick(MAX_ALLOCATION_BYTES); (NonNull::::dangling(), usize::MAX, n, 0) } else { @@ -2048,7 +2047,8 @@ gen_harnesses! { check_spec_extend_slice_iter_contents: // `IntoIter::advance_by`, `advance_back_by`, `forget_allocation_drop_remaining`, `drop` // --------------------------------------------------------------------------- -// Non-zero sentinel initializers avoid Kani static/constant zero aliasing (kani#5088). +// Defensive non-zero sentinel initializers against static/constant zero aliasing +// (historical `kani#5088`, fixed in `#5089`). static mut LAST_DROP_PTR: usize = 0x5A5A_5A5A_5A5A_5A5B; static mut LAST_DROP_LEN: usize = 0x5A5A_5A5A_5A5A_5A5C; @@ -2626,10 +2626,16 @@ fn check_into_iter_into_vecdeque_nonpow2() { /// `IntoIter::fold`: visits every remaining element via the unbounded /// `#[safety::loop_invariant]` loops, verifies pointer bounds, alignment, /// ownership transfer without double-dropping, and exact backing buffer -/// deallocation via `TrackAlloc`. +/// deallocation + stateful allocator preservation via `StatefulAlloc`. fn check_into_iter_fold() { - let (it, len) = - any_into_iter_opt::(MAX_ALLOCATION_BYTES, true, TrackAlloc, true, true); + let tag_id: u8 = kani::any(); + let (it, len) = any_into_iter_opt::( + MAX_ALLOCATION_BYTES, + true, + StatefulAlloc(tag_id), + true, + true, + ); let old_buf = it.buf; let old_cap = it.cap; let old_ptr = it.ptr; @@ -2638,13 +2644,15 @@ fn check_into_iter_fold() { reset_deallocs(); let init: u8 = kani::any(); let res = it.fold(init, |acc, x| { - // Forget `x` directly rather than calling `finish` (whose dead `drop(x)` - // branch on `Drop` types widens CBMC's inferred loop assigns into a - // `CAR size` failure). Note: CBMC's loop-contract havoc does not preserve - // pre-loop symbolic `write_bytes` contents through `arith_offset` reads - // (and contracted non-ZST loops currently hit Kani's `mem_init` ghost-tracker - // limit under `-Z uninit-checks`); live-only `[adv..len]` initialization - // preserves valid element values for `-Z valid-value-checks`. + // Forget `x` in the generic harness because `DropTracker::drop` writes to + // `static mut DROPS`, which widens CBMC's inferred loop assigns into a + // `CAR size` failure; `check_into_iter_fold_consuming_drop` below runs a + // consuming `drop(x)` callback with a non-static `Drop` type (`ConsumingDrop`). + // Note: CBMC's loop-contract havoc does not preserve pre-loop symbolic + // `write_bytes` contents through `arith_offset` reads (and contracted + // non-ZST loops currently hit Kani's `mem_init` ghost-tracker limit under + // `-Z uninit-checks`); live-only `[adv..len]` initialization preserves + // valid element values for `-Z valid-value-checks`. mem::forget(x); acc.wrapping_add(1) }); @@ -2653,6 +2661,7 @@ fn check_into_iter_fold() { assert!(deallocs() == 1); assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); assert!(last_dealloc_size() == old_cap * mem::size_of::()); + assert!(last_dealloc_tag() == tag_id); } else { assert!(deallocs() == 0); } @@ -2689,15 +2698,21 @@ gen_harnesses! { check_into_iter_fold: check_into_iter_fold_nonzero => NonZero, } -/// `IntoIter::try_fold`: visits remaining elements via the unbounded -/// `#[safety::loop_invariant]` loops, short-circuiting cleanly on `Break` -/// while preserving `IntoIter` pointer bounds, alignment, and capacity -/// invariants for the remaining slice. +/// `IntoIter::try_fold` for non-`Drop` shapes: visits remaining elements via the +/// unbounded `#[safety::loop_invariant]` loops, short-circuiting cleanly on +/// `Break`, then drops `it` on BOTH `Continue` and `Break` to verify exact +/// backing-buffer deallocation and `StatefulAlloc` tag preservation. fn check_into_iter_try_fold() { use core::ops::ControlFlow; - let (mut it, len) = - any_into_iter_opt::(MAX_ALLOCATION_BYTES, true, TrackAlloc, true, true); + let tag_id: u8 = kani::any(); + let (mut it, len) = any_into_iter_opt::( + MAX_ALLOCATION_BYTES, + true, + StatefulAlloc(tag_id), + true, + true, + ); let old_buf = it.buf; let old_cap = it.cap; let old_ptr = it.ptr; @@ -2723,27 +2738,24 @@ fn check_into_iter_try_fold() { if len == 0 { assert!(v == init); } - // Drop `it` for non-`Drop` types (O(1) exact deallocation check via - // `TrackAlloc`); for `Drop` types, `finish` avoids compiler slice drop - // glue (`drop_in_place::<[T]>`) whose symbolic pointer subtraction - // `end - ptr` cannot be statically bounded by CBMC without `unwind`. - finish::(it); - assert!(drops() == 0); - if !mem::needs_drop::() && !T::IS_ZST && old_cap > 0 { - assert!(deallocs() == 1); - assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); - assert!(last_dealloc_size() == old_cap * mem::size_of::()); - } else { - assert!(deallocs() == 0); - } + drop(it); } ControlFlow::Break(_) => { assert!(len > 0); assert!(it.len() < len); assert!(it.as_slice().len() == it.len()); - finish::(it); + drop(it); } } + assert!(drops() == 0); + if !T::IS_ZST && old_cap > 0 { + assert!(deallocs() == 1); + assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); + assert!(last_dealloc_size() == old_cap * mem::size_of::()); + assert!(last_dealloc_tag() == tag_id); + } else { + assert!(deallocs() == 0); + } kani::cover(len == 0 && matches!(res, ControlFlow::Continue(_)), "empty try_fold"); kani::cover( small && len > 4096 && matches!(res, ControlFlow::Continue(_)), @@ -2759,6 +2771,85 @@ fn check_into_iter_try_fold() { }); } +/// `IntoIter::try_fold` for `Drop` shapes (`DropTracker`, `DropNiche`) paired +/// with the exact slice drop summary stub: calls real `drop(it)` on BOTH +/// `Continue` (0 remaining drops) and `Break` (`rem` remaining drops at exact +/// `(rem_ptr, rem)`), plus `StatefulAlloc` deallocation + tag verification. +fn check_into_iter_try_fold_drop_stubbed() { + use core::ops::ControlFlow; + + let tag_id: u8 = kani::any(); + let (mut it, len) = any_into_iter_opt::( + MAX_ALLOCATION_BYTES, + true, + StatefulAlloc(tag_id), + true, + true, + ); + let old_buf = it.buf; + let old_cap = it.cap; + let old_ptr = it.ptr; + let small = witness_ok::(old_cap); + reset_drop_trace(); + reset_deallocs(); + let init: u8 = kani::any(); + let res = it.try_fold(init, |acc, x| { + mem::forget(x); + if kani::any() { + ControlFlow::Break(acc) + } else { + ControlFlow::Continue(acc.wrapping_add(1)) + } + }); + assert!(drops() == 0); + assert!(deallocs() == 0); + assert!(it.buf == old_buf && it.cap == old_cap); + match res { + ControlFlow::Continue(v) => { + assert!(it.len() == 0); + assert!(it.as_slice().is_empty()); + if len == 0 { + assert!(v == init); + } + drop(it); + assert!(drops() == 0); + } + ControlFlow::Break(_) => { + assert!(len > 0); + let rem = it.len(); + assert!(rem < len); + assert!(it.as_slice().len() == rem); + let rem_ptr = it.ptr.as_ptr().addr(); + drop(it); + assert!(drops() == rem); + if rem > 0 { + // SAFETY: Kani verification harnesses are single-threaded. + assert!(unsafe { LAST_DROP_PTR } == rem_ptr); + assert!(unsafe { LAST_DROP_LEN } == rem); + } + } + } + if old_cap > 0 { + assert!(deallocs() == 1); + assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); + assert!(last_dealloc_size() == old_cap * mem::size_of::()); + assert!(last_dealloc_tag() == tag_id); + } else { + assert!(deallocs() == 0); + } + kani::cover(len == 0 && matches!(res, ControlFlow::Continue(_)), "empty try_fold"); + kani::cover( + small && len > 4096 && matches!(res, ControlFlow::Continue(_)), + "deep complete try_fold", + ); + kani::cover(small && len > 4096 && matches!(res, ControlFlow::Break(_)), "deep break try_fold"); + kani::cover(old_cap == 0, "unallocated try_fold"); + kani::cover( + len > 0 && old_ptr != old_buf && matches!(res, ControlFlow::Break(_)), + "advanced break try_fold", + ); +} + gen_harnesses! { check_into_iter_try_fold: #[kani::solver(minisat)] check_into_iter_try_fold_u8 => u8, @@ -2773,13 +2864,173 @@ gen_harnesses! { check_into_iter_try_fold: #[kani::solver(minisat)] check_into_iter_try_fold_aligned_zst => AlignedZst, #[kani::solver(minisat)] - check_into_iter_try_fold_drop_tracker => DropTracker, - #[kani::solver(minisat)] - check_into_iter_try_fold_drop_niche => DropNiche, - #[kani::solver(minisat)] check_into_iter_try_fold_nonzero => NonZero, } +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(core::ptr::drop_in_place, drop_tracker_slice_stub)] +fn check_into_iter_try_fold_drop_tracker() { + check_into_iter_try_fold_drop_stubbed::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(core::ptr::drop_in_place, drop_niche_slice_stub)] +fn check_into_iter_try_fold_drop_niche() { + check_into_iter_try_fold_drop_stubbed::(); +} + +/// Non-trivial `Drop` element whose `Drop::drop` mutates local state (`self.0`) +/// without writing to a `static mut` global, so CBMC's contracted-loop assigns +/// inference verifies a real consuming `drop(x)` callback inside `fold`/`try_fold`. +struct ConsumingDrop(u8); +impl Drop for ConsumingDrop { + fn drop(&mut self) { + self.0 = self.0.wrapping_add(1); + } +} +impl Shape for ConsumingDrop { + fn from_byte(b: u8) -> Self { + Self(b) + } + fn tag_byte(&self) -> u8 { + self.0 + } +} + +unsafe fn drop_consuming_slice_stub(to_drop: *mut T) { + // SAFETY: Exact sound summary for `drop_in_place::<[ConsumingDrop]>` (mirrors + // `drop_tracker_slice_stub`; thin-pointer targets dispatch to real drop glue). + unsafe { drop_slice_summary::(to_drop) }; +} + +/// `IntoIter::fold` with a real consuming `drop(x)` callback (zero `mem::forget`) +/// and non-ZST `StatefulAlloc(tag_id)` deallocation verification. +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_iter_fold_consuming_drop() { + let tag_id: u8 = kani::any(); + let (it, len) = any_into_iter_opt::( + MAX_ALLOCATION_BYTES, + true, + StatefulAlloc(tag_id), + true, + true, + ); + let old_buf = it.buf; + let old_cap = it.cap; + let old_ptr = it.ptr; + let small = witness_ok::(old_cap); + reset_deallocs(); + let init: u8 = kani::any(); + let res = it.fold(init, |acc, x| { + drop(x); + acc.wrapping_add(1) + }); + if old_cap > 0 { + assert!(deallocs() == 1); + assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); + assert!(last_dealloc_size() == old_cap); + assert!(last_dealloc_tag() == tag_id); + } else { + assert!(deallocs() == 0); + } + if len == 0 { + assert!(res == init); + } + kani::cover(len == 0, "empty consuming fold"); + kani::cover(len == 1, "single-element consuming fold"); + kani::cover(small && len > 4096, "deep consuming fold"); + kani::cover(old_cap == 0, "unallocated consuming fold"); + kani::cover(len > 0 && old_ptr != old_buf, "advanced consuming fold"); +} + +/// `IntoIter::try_fold` with a real consuming `drop(x)` callback (zero +/// `mem::forget`), real `drop(it)` on BOTH `Continue` and `Break` (verifying +/// remaining-slice drop pointer/count via `drop_consuming_slice_stub`), and +/// non-ZST `StatefulAlloc(tag_id)` deallocation verification. +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(core::ptr::drop_in_place, drop_consuming_slice_stub)] +fn check_into_iter_try_fold_consuming_drop() { + use core::ops::ControlFlow; + + let tag_id: u8 = kani::any(); + let (mut it, len) = any_into_iter_opt::( + MAX_ALLOCATION_BYTES, + true, + StatefulAlloc(tag_id), + true, + true, + ); + let old_buf = it.buf; + let old_cap = it.cap; + let old_ptr = it.ptr; + let small = witness_ok::(old_cap); + reset_drop_trace(); + reset_deallocs(); + let init: u8 = kani::any(); + let res = it.try_fold(init, |acc, x| { + drop(x); + if kani::any() { + ControlFlow::Break(acc) + } else { + ControlFlow::Continue(acc.wrapping_add(1)) + } + }); + assert!(drops() == 0); + assert!(deallocs() == 0); + assert!(it.buf == old_buf && it.cap == old_cap); + match res { + ControlFlow::Continue(v) => { + assert!(it.len() == 0); + assert!(it.as_slice().is_empty()); + if len == 0 { + assert!(v == init); + } + drop(it); + assert!(drops() == 0); + } + ControlFlow::Break(_) => { + assert!(len > 0); + let rem = it.len(); + assert!(rem < len); + assert!(it.as_slice().len() == rem); + let rem_ptr = it.ptr.as_ptr().addr(); + drop(it); + assert!(drops() == rem); + if rem > 0 { + // SAFETY: Kani verification harnesses are single-threaded. + assert!(unsafe { LAST_DROP_PTR } == rem_ptr); + assert!(unsafe { LAST_DROP_LEN } == rem); + } + } + } + if old_cap > 0 { + assert!(deallocs() == 1); + assert!(last_dealloc_ptr() == old_buf.as_ptr().addr()); + assert!(last_dealloc_size() == old_cap); + assert!(last_dealloc_tag() == tag_id); + } else { + assert!(deallocs() == 0); + } + kani::cover(len == 0 && matches!(res, ControlFlow::Continue(_)), "empty consuming try_fold"); + kani::cover( + small && len > 4096 && matches!(res, ControlFlow::Continue(_)), + "deep complete consuming try_fold", + ); + kani::cover( + small && len > 4096 && matches!(res, ControlFlow::Break(_)), + "deep break consuming try_fold", + ); + kani::cover(old_cap == 0, "unallocated consuming try_fold"); + kani::cover( + len > 0 && old_ptr != old_buf && matches!(res, ControlFlow::Break(_)), + "advanced break consuming try_fold", + ); +} + // --------------------------------------------------------------------------- // `IntoIter::next_chunk` // --------------------------------------------------------------------------- diff --git a/verifast-proofs/alloc/vec/extract_if.rs/README.md b/verifast-proofs/alloc/vec/extract_if.rs/README.md index 3fb43d9fad3b3..8c1cd9a77ebd9 100644 --- a/verifast-proofs/alloc/vec/extract_if.rs/README.md +++ b/verifast-proofs/alloc/vec/extract_if.rs/README.md @@ -6,26 +6,36 @@ With certain [caveats](#caveats), this proof proves unbounded, polymorphic `alloc::vec::ExtractIf::drop` for arbitrary element types `T` (including zero-sized types with capacity up to `usize::MAX` and `old_len > isize::MAX`), arbitrary filter predicates `F: FnMut(&mut T) -> bool`, and arbitrary allocators -`A: Allocator`. +`A: Allocator` (including non-`'static` allocators). ## Proof Overview -### ZST-Sound Concrete `Vec` & `ExtractIf_fbc` +### `RawVec`-Bridged `Vec` & `ExtractIf_fbc` VeriFast 26.10's built-in `std/lib.rsspec:1704` (`Vec_inv`) carries a stale `capacity <= isize::MAX` axiom that contradicts zero-sized `Vec`s (`cap == usize::MAX`) -and requires `thread_token(t)` in `Vec_to_own` (`std/lib.rsspec:1714`). To avoid any -contradiction with `std/lib.rsspec:1704`, `original/lib.rs` and `verified/lib.rs` -define a minimal concrete `Vec` (`ptr`, `cap`, `len`, `alloc`) matching -`library/alloc/src/vec/mod.rs`'s real ZST-sound invariant -`v.cap * std::mem::size_of::() <= isize::MAX` (consistent with VeriFast's own -`prelude_core.rsspec:253` `array__inv`), with fully verified implementations and -public `safety_proof`s for `Vec::{len, as_ptr, as_mut_ptr, set_len}` (zero -`assume_correct` on any `Vec` method). +and requires `thread_token(t)` in `Vec_to_own` (`std/lib.rsspec:1714`). Rather than +replacing `RawVec` with an abstract handle, `original/lib.rs`, `with-directives/lib.rs`, +and `verified/lib.rs` import the repository's already-verified +[`verifast-proofs/alloc/raw_vec/mod.rs`](../../raw_vec/mod.rs/) directly (via relative +symlinks to `raw_vec.rs`, checked by both `refinement-checker` and byte-for-byte `diff` +against `library/alloc/src/raw_vec/mod.rs`) and define the exact shipped layout +`pub struct Vec { buf: RawVec, len: usize }` matching +`library/alloc/src/vec/mod.rs`: + +- `>.own(t, v)` wraps `RawVec(t, v.buf, ?alloc_id, ?ptr, ?cap)` with the + ZST-sound invariant `cap * std::mem::size_of::() <= isize::MAX` (supporting + `cap == usize::MAX` for ZSTs), lifetime-indexed `array_at_lft(alloc_id.lft, ptr, v.len, ?elems)` + with `foreach(elems, own::(t))`, and `array_at_lft_(alloc_id.lft, ptr + v.len, cap - v.len, _)`. +- `Vec::as_ptr` and `Vec::as_mut_ptr` delegate directly to `self.buf.ptr()` on the real + verified `RawVec`, `Vec::allocator` delegates to `self.buf.allocator()`, + `Vec::len` reads `self.len` with a public `safety_proof`, and `Vec::set_len` carries a + verified field-write contract (`req (*self).len |-> ?_old; ens (*self).len |-> new_len;`) + with zero `assume_correct` on any `Vec` method. `ExtractIf<'a, T, F, A>` mutably borrows a `Vec` whose length is temporarily set -to `0` by `ExtractIf::new` (leak amplification guard) while partitioning `buf[0..cap]` -into four disjoint regions: +to `0` by `ExtractIf::new` (leak amplification guard) while partitioning the `RawVec` +buffer `buf[0..cap]` (at lifetime `alloc_id.lft`) into four disjoint regions: 1. `buf[..idx - del]`: retained elements (`retained`), each satisfying `own::(t)`. 2. `buf[idx - del..idx]`: `del`-element uninitialized hole vacated by extracted elements. @@ -33,28 +43,38 @@ into four disjoint regions: 4. `buf[old_len..cap]`: uninitialized spare capacity. The borrow payload `ExtractIf_fbc` tracks two states via a shared `ghost_cell`: -- `some(pair(idx, del))`: active iteration state (`0 <= del <= idx <= end <= old_len <= cap` - and `cap * std::mem::size_of::() <= isize::MAX`). +- `some(pair(idx, del))`: active iteration state holding `(*vec).buf |-> ?rv`, + `(*vec).len |-> 0`, and `RawVec(t, rv, ?alloc_id, ?buf, ?cap)` with + `0 <= del <= idx <= end <= old_len <= cap` and `cap * std::mem::size_of::() <= isize::MAX`. - `none`: post-`Drop` state where `ExtractIf::drop` has compacted the tail left over the hole, restored `vec.set_len(old_len - del)`, and closed `>.own(t, *vec)`. ### Verified Functions & Connecting Lemmas -Verified cleanly with **`0 errors found (453 statements verified)`**, passing -`refinement-checker` against `original/lib.rs` and byte-for-byte `diff` against -`library/alloc/src/vec/extract_if.rs`: +Verified cleanly with **`0 errors found (2268 statements verified)`** (including all +1,690 statements of `raw_vec.rs` plus 578 statements of `Vec` and `ExtractIf`), passing +both `refinement-checker` checks (`with-directives/lib.rs` vs `verified/lib.rs`, and +`--ignore-directives original/lib.rs` vs `with-directives/lib.rs`) and byte-for-byte +`diff` against both `library/alloc/src/vec/extract_if.rs` and +`library/alloc/src/raw_vec/mod.rs`: -- **`Vec::{len, as_ptr, as_mut_ptr, set_len}`** (`verified/lib.rs`): verified field-level - and public `safety_proof` contracts (`Vec_share_full`, `Vec_share_mono`, `init_ref_Vec`, - `Vec_drop`, `Vec_send`, `Vec_own_mono`) with zero `assume_correct`. +- **`RawVec` & `Vec::{len, as_ptr, as_mut_ptr, set_len}`** (`verified/raw_vec.rs`, + `verified/lib.rs`): full verified `RawVec` backing storage plus verified `Vec` contracts + and public `safety_proof`s (`Vec_share_full`, `Vec_share_mono`, `init_ref_Vec`, + `Vec_drop` closing `>.own`, `Vec_send`, `Vec_sync`, and structural + `Vec_own_mono` via `Allocator_upcast` and `array_at_lft_own_mono`) with zero + `assume_correct` and zero `assume(false)` in any authored file. - **`ExtractIf::new`:** Unbounded proof opening `full_borrow('a, >.full_borrow_content(t, vec))`, reading `vec.len()`, bounding `start..end` via `slice_range__VeriFast_wrapper`, calling `vec.set_len(0)`, calling `ExtractIf_init_from_vec_buffer` to establish `ExtractIf_fbc` in `some(pair(start, 0))`, and closing `full_borrow_convert_strong` using `ExtractIf_fbc_restore_vec` (proving leak-amplification soundness for both `none` and `some(p)` states without requiring `thread_token(t)`). -- **`ExtractIf::next`:** Unbounded loop proof (`while self.idx < self.end`) verifying - in-bounds pointer arithmetic (`as_mut_ptr().add(i)`, `as_mut_ptr().add(i - self.del)`), +- **`ExtractIf::next`:** Unbounded loop proof (`while self.idx < self.end`) trading the + function lifetime token `flft` into `alloc_id.lft` via `RawVec_inv` and + `lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft)` (sound for arbitrary + non-`'static` allocators `A`), verifying in-bounds pointer arithmetic + (`as_mut_ptr().add(i)`, `as_mut_ptr().add(i - self.del)` via real `RawVec::ptr`), exclusive access to `cur` during predicate invocation, ownership transfer on `Some(ptr::read(cur))`, disjoint `ptr::copy_nonoverlapping(cur, hole_slot, 1)` when `del > 0`, and invariant preservation across arbitrary iteration counts (including @@ -63,41 +83,71 @@ Verified cleanly with **`0 errors found (453 statements verified)`**, passing - **`ExtractIf::drop` (via `drop_body__VeriFast_wrapper<'a, T, F, A>`):** Unbounded proof verifying `ptr::copy` (both the non-overlapping `del >= old_len - idx` case and overlapping `del < old_len - idx` case) via pure inductive typed-array/byte-slice - conversion lemmas (`array_to_u8s_bytes`, `u8s_bytes_to_array`), followed by - `self.vec.set_len(self.old_len - self.del)` and `full_borrow_convert_strong` restoring - `full_borrow('a, >.full_borrow_content(t, vec))` while transitioning - `ExtractIf_fbc` from `some(pair(idx, del))` to `none`. Because VeriFast 26.10 rejects - `Drop` specs on `impl Drop for ExtractIf<'_, T, F, A>` when the anonymous - lifetime `'_` does not syntactically match the struct's `'a` parameter, the exact - `Drop::drop` contract and body are verified in `drop_body__VeriFast_wrapper<'a, T, F, A>`, - and `refinement-checker` confirms that `original/extract_if.rs::Drop::drop` refines - delegating to it. -- **Type obligations (`ExtractIf_drop`, `ExtractIf_send`, `ExtractIf_own_mono`):** Verified - with zero `assume(false)`. + conversion lemmas (`array_to_u8s_bytes`, `u8s_bytes_to_array`) over lifetime-indexed + `array_at_lft_` storage, followed by `this.vec.set_len(this.old_len - this.del)` and + `full_borrow_convert_strong` restoring `full_borrow('a, >.full_borrow_content(t, vec))` + while transitioning `ExtractIf_fbc` from `some(pair(idx, del))` to `none`. Because + VeriFast 26.10 rejects `Drop` specs on `impl Drop for ExtractIf<'_, T, F, A>` + when the anonymous lifetime `'_` does not syntactically match the struct's `'a` + parameter, the `Drop::drop` body is verified via `drop_body__VeriFast_wrapper<'a, T, F, A>` + with its explicit full-borrow-restoring contract, and `refinement-checker` confirms that + `original/extract_if.rs::Drop::drop` refines delegating to it. +- **Type obligations (`Vec_own_mono`, `ExtractIf_drop`, `ExtractIf_send`, + `ExtractIf_own_mono`):** Verified with **zero `assume(false)`** across all files authored + in `verifast-proofs/alloc/vec/extract_if.rs/`. ## Caveats 1. **VeriFast flags:** Verified with `-skip_specless_fns -ignore_unwind_paths -allow_assume`: - `-skip_specless_fns`: `Vec::allocator`, `ExtractIf::allocator`, `ExtractIf::size_hint`, - and `Debug::fmt` are skipped by VeriFast (none are Challenge 24 targets). + `Debug::fmt`, and specless helper methods in `raw_vec.rs` are skipped by VeriFast + (none are Challenge 24 targets). - `-ignore_unwind_paths`: Unwind/panic paths (e.g., if `pred` panics inside `next`) are not verified by VeriFast. - - `-allow_assume`: Used strictly in four documented places: + - `-allow_assume`: Used strictly in documented places matching upstream `verifast-proofs`: 1. `call_pred__VeriFast_wrapper` (`assume_correct` closure call boundary, matching `verifast-proofs/alloc/collections/linked_list.rs`). 2. `slice_range__VeriFast_wrapper` (`assume_correct` wrapper around `core::slice::range` stating its documented postcondition `0 <= start <= end <= old_len`). - 3. `Vec_send` / `ExtractIf_send` (`is_Send` propagation through `unsafe impl Send for Vec`). - 4. `Vec_own_mono` / `ExtractIf_own_mono` (`upcast` on `usize` is identity, tracking - VeriFast issue #610). - - There is **zero `assume(false)`** anywhere in this proof. -2. **Backing `Vec` model:** `original/lib.rs` and `verified/lib.rs` model the fields and - buffer-access methods of `alloc::vec::Vec` used by `ExtractIf` (`ptr`, `cap`, `len`, - `alloc`; `Vec_alloc_handle` abstracts the untouched `RawVec` allocation ownership, - separately verified in `verifast-proofs/alloc/raw_vec/mod.rs/`). -3. **Code changes & refinement checking:** `refinement-checker` verifies that - `original/lib.rs` refines `verified/lib.rs`, and `diff` checks that - `original/extract_if.rs` is byte-for-byte identical to `library/alloc/src/vec/extract_if.rs`. + 3. `Vec_send` / `Vec_sync` / `ExtractIf_send` (`is_Send` / `is_Sync` propagation through + `unsafe impl Send for Vec`). + 4. `ExtractIf_own_mono`, `array_at_lft_own_mono`, and `Vec_own_mono` (explicit Rust + subtyping representation-preservation identities — layout equality, `usize`/field + upcast identity, and byte-level `of_u8s_` preservation under `T0 <: T1`, tracking + VeriFast issue #610). There is **zero `assume(false)`** anywhere in our authored + files (`verified/lib.rs`, `verified/extract_if.rs`); the symlinked upstream + `raw_vec.rs` carries its own upstream `RawVec_own_mono` / `RawVecInner_own_mono` + entries from Challenge 19. +2. **Backing `Vec` model:** `original/lib.rs`, `with-directives/lib.rs`, and `verified/lib.rs` + use the exact shipped `Vec { buf: RawVec, len: usize }` struct bridged + directly to `verifast-proofs/alloc/raw_vec/mod.rs/` (eliminating any standalone + replacement `RawVec` handle) and model only the subset of `Vec` methods called by + `ExtractIf` (`len`, `as_ptr`, `as_mut_ptr`, `set_len`, `allocator`). +3. **Code changes & refinement checking:** `refinement-checker` verifies both that + `with-directives/lib.rs` refines `verified/lib.rs` and (with `--ignore-directives`) that + `original/lib.rs` refines `with-directives/lib.rs`, and `diff` checks that both + `original/extract_if.rs` (`library/alloc/src/vec/extract_if.rs`) and `original/raw_vec.rs` + (`library/alloc/src/raw_vec/mod.rs`) are byte-for-byte identical to upstream `alloc`. 4. **Target & tool soundness:** As with `linked_list.rs` and `raw_vec/mod.rs`, VeriFast verifies against the `rustc` target architecture and relies on VeriFast's symbolic execution engine and prelude specs. + +## Attribution & License + +- **Bridged `RawVec` proof (`raw_vec.rs`):** Imported untouched via relative symlinks + from accepted Challenge 19 ([`verifast-proofs/alloc/raw_vec/mod.rs`](../../raw_vec/mod.rs/), + `model-checking/verify-rust-std` PR #422). +- **Adapted `Vec` ownership/sharing & lifetime-trade idioms:** Informed by + VeriFast 26.10 (`tests/rust/safe_abstraction/vec/` and `bin/rust/std/lib.rsspec`, + MIT License, Copyright VeriFast contributors / KU Leuven) and + [`verifast-proofs/alloc/collections/linked_list.rs`](../../collections/linked_list.rs/). +- **Newly authored in this Challenge 24 PR:** + - `ExtractIf_fbc` ghost-cell state machine over lifetime-indexed `RawVec` buffers and + connecting lemmas (`ExtractIf_init_from_vec_buffer`, `ExtractIf_fbc_restore_vec`). + - Full unbounded polymorphic proofs of `ExtractIf::new`, `ExtractIf::next`, and + `ExtractIf::drop` (`drop_body__VeriFast_wrapper`) including ZST (`cap == usize::MAX`) + and non-`'static` allocator soundness (`lifetime_token_trade`), plus inductive + byte-reinterpretation lemmas (`array_to_u8s_bytes`, `u8s_bytes_to_array`, + `array__map_some_to_array`) for overlapping and non-overlapping `ptr::copy`. + - Type obligations (`ExtractIf_drop`, `ExtractIf_send`, `ExtractIf_own_mono`) and the + structural zero-`assume(false)` `Vec_own_mono` / `array_at_lft_own_mono` proofs. diff --git a/verifast-proofs/alloc/vec/extract_if.rs/original/lib.rs b/verifast-proofs/alloc/vec/extract_if.rs/original/lib.rs index 69a847637d84e..2c8b3a8a03944 100644 --- a/verifast-proofs/alloc/vec/extract_if.rs/original/lib.rs +++ b/verifast-proofs/alloc/vec/extract_if.rs/original/lib.rs @@ -1,11 +1,41 @@ -// verifast_options{skip_specless_fns} +// verifast_options{skip_specless_fns ignore_unwind_paths} +#![allow(dead_code)] #![no_std] #![allow(internal_features)] #![allow(incomplete_features)] +#![feature(allocator_api)] #![feature(allocator_ext)] #![feature(staged_api)] #![feature(rustc_attrs)] +#![feature(dropck_eyepatch)] +#![feature(specialization)] +#![feature(extend_one)] +#![feature(exact_size_is_empty)] +#![feature(hasher_prefixfree_extras)] +#![feature(box_into_inner)] +#![feature(try_trait_v2)] +#![feature(optimize_attribute)] +#![feature(temporary_niche_types)] +#![feature(ptr_internals)] +#![feature(try_reserve_kind)] +#![feature(ptr_alignment_type)] +#![feature(ptr_cast_slice)] +#![feature(const_closures)] +#![feature(const_result_trait_fn)] +#![feature(sized_type_properties)] +#![feature(std_internals)] +#![feature(alloc_layout_extra)] +#![feature(const_alloc_error)] +#![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_destruct)] +#![feature(const_heap)] +#![feature(const_option_ops)] +#![feature(const_trait_impl)] +#![feature(const_try)] +#![feature(nonnull_provenance)] +#![feature(panic_internals)] #![feature(slice_range)] #![stable(feature = "rust1", since = "1.0.0")] @@ -14,15 +44,22 @@ extern crate alloc as std; #[stable(feature = "rust1", since = "1.0.0")] pub use std::alloc as alloc; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::boxed as boxed; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::collections as collections; + +pub mod raw_vec; +#[stable(feature = "rust1", since = "1.0.0")] +pub mod extract_if; use crate::alloc::{Allocator, Global}; +use crate::raw_vec::RawVec; #[stable(feature = "rust1", since = "1.0.0")] -pub struct Vec { - ptr: *mut T, - cap: usize, +pub struct Vec { + buf: RawVec, len: usize, - alloc: A, } #[stable(feature = "rust1", since = "1.0.0")] @@ -38,13 +75,13 @@ impl Vec { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn as_ptr(&self) -> *const T { - self.ptr + self.buf.ptr() } #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn as_mut_ptr(&mut self) -> *mut T { - self.ptr + self.buf.ptr() } #[stable(feature = "rust1", since = "1.0.0")] @@ -56,9 +93,6 @@ impl Vec { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn allocator(&self) -> &A { - &self.alloc + self.buf.allocator() } } - -#[stable(feature = "rust1", since = "1.0.0")] -pub mod extract_if; diff --git a/verifast-proofs/alloc/vec/extract_if.rs/original/raw_vec.rs b/verifast-proofs/alloc/vec/extract_if.rs/original/raw_vec.rs new file mode 120000 index 0000000000000..970be0fb97087 --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/original/raw_vec.rs @@ -0,0 +1 @@ +../../../raw_vec/mod.rs/original/raw_vec.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/extract_if.rs/verified/extract_if.rs b/verifast-proofs/alloc/vec/extract_if.rs/verified/extract_if.rs index 05fcda1649ffc..8be2490fa762b 100644 --- a/verifast-proofs/alloc/vec/extract_if.rs/verified/extract_if.rs +++ b/verifast-proofs/alloc/vec/extract_if.rs/verified/extract_if.rs @@ -6,6 +6,7 @@ use crate::alloc::{Allocator, Global}; //@ use std::alloc::{Allocator, Global}; //@ use std::option::{Option, Option::None, Option::Some}; +//@ use raw_vec::{RawVec, RawVec_inv, RawVec_send_, RawVec_share_, share_RawVec, end_share_RawVec, init_ref_RawVec_}; /// An iterator which uses a closure to determine if an element should be removed. /// @@ -59,18 +60,16 @@ pred_ctor ExtractIf_fbc( >.own(t, v), some(p) => struct_Vec_padding::(vec) &*& - (*vec).ptr |-> ?buf &*& - (*vec).cap |-> ?cap &*& + (*vec).buf |-> ?rv &*& (*vec).len |-> 0 &*& - (*vec).alloc |-> ?a &*& - .own(t, a) &*& - Vec_alloc_handle(buf as usize, cap * std::mem::size_of::()) &*& - 0 <= snd(p) &*& snd(p) <= fst(p) &*& fst(p) <= end &*& end <= old_len &*& old_len <= cap &*& cap * std::mem::size_of::() <= isize::MAX &*& + RawVec(t, rv, ?alloc_id, ?buf, ?cap) &*& + 0 <= snd(p) &*& snd(p) <= fst(p) &*& fst(p) <= end &*& end <= old_len &*& old_len <= cap &*& + cap * std::mem::size_of::() <= isize::MAX &*& 0 <= buf as usize &*& buf as usize % std::mem::align_of::() == 0 &*& - buf[..fst(p) - snd(p)] |-> ?retained &*& foreach(retained, own::(t)) &*& - buf[fst(p) - snd(p)..fst(p)] |-> _ &*& - buf[fst(p)..old_len] |-> ?tail &*& foreach(tail, own::(t)) &*& - buf[old_len..cap] |-> _ + array_at_lft(alloc_id.lft, buf, fst(p) - snd(p), ?retained) &*& foreach(retained, own::(t)) &*& + array_at_lft_(alloc_id.lft, buf + (fst(p) - snd(p)), snd(p), _) &*& + array_at_lft(alloc_id.lft, buf + fst(p), old_len - fst(p), ?tail) &*& foreach(tail, own::(t)) &*& + array_at_lft_(alloc_id.lft, buf + old_len, cap - old_len, _) }; pred<'a, T, F, A> >.own(t, ex) = @@ -114,10 +113,11 @@ lem ExtractIf_fbc_send(t0: thread_id_t, t1: thread_id_t, vec: *Vec, assert [1/2]ghost_cell(id, ?state); match state { none => { - Send::send::>(t0, t1, *vec); + assert *vec |-> ?v; + Send::send::>(t0, t1, v); } some(p) => { - Send::send::(t0, t1, (*vec).alloc); + RawVec_send_::(t1); foreach_own_send::(t0, t1); foreach_own_send::(t0, t1); } @@ -276,12 +276,30 @@ lem u8s_bytes_to_array(p: *T, vs: list) } } +lem array__map_some_to_array(p: *T, vs: list) + req p[..length(vs)] |-?-> map(some, vs); + ens p[..length(vs)] |-> vs; +{ + match vs { + nil => { + open array_::(p, 0, nil); + close array::(p, 0, nil); + } + cons(v, vs0) => { + open array_::(p, length(vs), _); + array__map_some_to_array::(p + 1, vs0); + close array::(p, length(vs), vs); + } + } +} + // Connecting base lemma (called directly by `ExtractIf::new`): splits `buf[..old_len]` // at `start` after `vec.set_len(0)` to establish `ExtractIf_fbc` in state // `some(pair(start, 0))` for all `T` (including ZSTs with `cap == usize::MAX`). lem ExtractIf_init_from_vec_buffer( t: thread_id_t, vec: *Vec, + alloc_id: std::alloc::alloc_id_t, buf: *T, start: usize, end: usize, @@ -292,23 +310,20 @@ lem ExtractIf_init_from_vec_buffer( type_interp::() &*& type_interp::>() &*& struct_Vec_padding::(vec) &*& - (*vec).ptr |-> buf &*& - (*vec).cap |-> cap &*& + (*vec).buf |-> ?rv &*& (*vec).len |-> 0 &*& - (*vec).alloc |-> ?a &*& - .own(t, a) &*& - Vec_alloc_handle(buf as usize, cap * std::mem::size_of::()) &*& + RawVec(t, rv, alloc_id, buf, cap) &*& 0 <= start &*& start <= end &*& end <= old_len &*& old_len <= cap &*& cap * std::mem::size_of::() <= isize::MAX &*& 0 <= buf as usize &*& buf as usize % std::mem::align_of::() == 0 &*& - buf[..old_len] |-> ?elems &*& foreach(elems, own::(t)) &*& - buf[old_len..cap] |-> _; + array_at_lft(alloc_id.lft, buf, old_len, ?elems) &*& foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, buf + old_len, cap - old_len, _); ens [1/2]ghost_cell::>>(result, some(pair(start, 0))) &*& ExtractIf_fbc::(t, vec, result, end, old_len)(); { - array_split::(buf, start); + array_at_lft_split::(buf, start); foreach_split(elems, own::(t), start); - close array_::(buf + start, 0, nil); + close array_at_lft_::(alloc_id.lft, buf + start, 0, nil); let id = create_ghost_cell::>>(some(pair(start, 0))); close ExtractIf_fbc::(t, vec, id, end, old_len)(); return id; @@ -337,20 +352,22 @@ lem ExtractIf_fbc_restore_vec( close_full_borrow_content::>(t, vec); } some(p) => { - assert (*vec).ptr |-> ?buf &*& (*vec).cap |-> ?cap &*& (*vec).len |-> 0 &*& (*vec).alloc |-> ?a; - assert buf[..fst(p) - snd(p)] |-> ?retained; - assert buf[fst(p)..old_len] |-> ?tail; + assert (*vec).buf |-> ?rv &*& (*vec).len |-> 0 &*& RawVec(t, rv, ?alloc_id, ?buf, ?cap); + assert array_at_lft(alloc_id.lft, buf, fst(p) - snd(p), ?retained); + assert array_at_lft(alloc_id.lft, buf + fst(p), old_len - fst(p), ?tail); leak foreach(retained, own::(t)); leak foreach(tail, own::(t)); - array_to_array_::(buf); - array__join::(buf); - array_to_array_::(buf + fst(p)); - array__join::(buf); - array__join::(buf); - close array::(buf, 0, nil); + array_at_lft_to_array_at_lft_::(buf); + array_at_lft__join::(buf); + array_at_lft_to_array_at_lft_::(buf + fst(p)); + array_at_lft__join::(buf); + array_at_lft__join::(buf); + close array_at_lft::(alloc_id.lft, buf, 0, nil); close foreach(nil, own::(t)); + open_points_to(&(*vec).buf); close_points_to(vec); - close >.own(t, *vec); + assert *vec |-> ?v1; + close >.own(t, v1); close_full_borrow_content::>(t, vec); } } @@ -376,6 +393,7 @@ impl<'a, T, F, A: Allocator> ExtractIf<'a, T, F, A> { //@ open_full_borrow_content::>(t, vec); //@ assert *vec |-> ?v0; //@ open >.own(t, v0); + //@ assert RawVec(t, v0.buf, ?alloc_id, ?buf, ?cap); //@ let vref = precreate_ref(vec); //@ init_ref_readonly(vref, 1/2); //@ open_points_to(vref); @@ -383,8 +401,7 @@ impl<'a, T, F, A: Allocator> ExtractIf<'a, T, F, A> { //@ close_points_to(vref, 1/2); //@ end_ref_readonly(vref); //@ open_points_to(vec); - //@ let buf = v0.ptr; - //@ let cap = v0.cap; + //@ close_points_to(&(*vec).buf); let Range { start, end } = slice_range__VeriFast_wrapper(range, old_len); //@ leak >.own(t, _); @@ -397,7 +414,7 @@ impl<'a, T, F, A: Allocator> ExtractIf<'a, T, F, A> { produce_type_interp::(); produce_type_interp::(); produce_type_interp::>(); - let ghost_cell_id = ExtractIf_init_from_vec_buffer::(t, vec, buf, start, end, old_len, cap); + let ghost_cell_id = ExtractIf_init_from_vec_buffer::(t, vec, alloc_id, buf, start, end, old_len, cap); { pred Ctx() = true; produce_lem_ptr_chunk full_borrow_convert_strong( @@ -465,14 +482,18 @@ where //@ open_full_borrow(q, '_0, ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)); //@ open ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)(); //@ merge_fractions ghost_cell(ghost_cell_id, _); - //@ assert (*self_cur.vec).ptr |-> ?buf &*& (*self_cur.vec).cap |-> ?cap; - //@ assert buf[..idx0 - del0] |-> ?retained; - //@ assert buf[idx0..self_cur.old_len] |-> ?tail; - //@ open array::(buf + idx0, self_cur.old_len - idx0, tail); + //@ assert (*self_cur.vec).buf |-> ?rv &*& RawVec(t, rv, ?alloc_id, ?buf, ?cap); + //@ RawVec_inv::(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ assert array_at_lft(alloc_id.lft, buf, idx0 - del0, ?retained); + //@ assert array_at_lft(alloc_id.lft, buf + idx0, self_cur.old_len - idx0, ?tail); + //@ open array_at_lft::(alloc_id.lft, buf + idx0, self_cur.old_len - idx0, tail); //@ open foreach(tail, own::(t)); - //@ assert *(buf + idx0) |-> ?cur_val0; + //@ assert points_to_at_lft(alloc_id.lft, buf + idx0, ?cur_val0); + //@ open_points_to_at_lft(buf + idx0, q_alloc/2); //@ open own::(t)(cur_val0); - //@ assert (buf + idx0 + 1)[..self_cur.old_len - idx0 - 1] |-> ?tail_rest; + //@ assert array_at_lft(alloc_id.lft, buf + idx0 + 1, self_cur.old_len - idx0 - 1, ?tail_rest); // SAFETY: // We know that `i < self.end` from the if guard and that `self.end <= self.old_len` from // the validity of `Self`. Therefore `i` points to an element within `vec`. @@ -498,10 +519,11 @@ where // SAFETY: We never touch this element again after returning it. let r = Some(unsafe { ptr::read(cur) }); /*@ { - close array::(buf + idx0 + 1, 0, nil); - close array::(buf + idx0, 1, [cur_val1]); - array_to_array_::(buf + idx0); - array__join::(buf + (idx0 - del0)); + close_points_to_at_lft_(buf + idx0); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + close array_at_lft_::(alloc_id.lft, buf + idx0 + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, buf + idx0, 1, _); + array_at_lft__join::(buf + (idx0 - del0)); ghost_cell_mutate::>>(ghost_cell_id, some(pair(idx0 + 1, del0 + 1))); close ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)(); close_full_borrow(ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)); @@ -517,15 +539,28 @@ where //@ mul_mono_l(idx0 - del0, cap, std::mem::size_of::()); let hole_slot = self.vec.as_mut_ptr().add(i - self.del); /*@ { - array__split::(buf + (idx0 - del0), 1); + open array_at_lft_::(alloc_id.lft, buf + (idx0 - del0), del0, _); + open_points_to_at_lft_(buf + (idx0 - del0), q_alloc/2); + close array_::(buf + (idx0 - del0) + 1, 0, nil); + close array_::(buf + (idx0 - del0), 1, _); close array::(buf + idx0 + 1, 0, nil); close array::(buf + idx0, 1, [cur_val1]); } @*/ ptr::copy_nonoverlapping(cur, hole_slot, 1); /*@ { - array_to_array_::(buf + idx0); - array__join::(buf + (idx0 - del0 + 1)); - array_join::(buf); + open array::(buf + (idx0 - del0), 1, [cur_val1]); + open array::(buf + (idx0 - del0) + 1, 0, nil); + open array::(buf + idx0, 1, [cur_val1]); + open array::(buf + idx0 + 1, 0, nil); + close_points_to_at_lft(buf + (idx0 - del0)); + close_points_to_at_lft_(buf + idx0); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + close array_at_lft::(alloc_id.lft, buf + (idx0 - del0) + 1, 0, nil); + close array_at_lft::(alloc_id.lft, buf + (idx0 - del0), 1, [cur_val1]); + array_at_lft_join::(buf); + close array_at_lft_::(alloc_id.lft, buf + idx0 + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, buf + idx0, 1, _); + array_at_lft__join::(buf + (idx0 - del0 + 1)); close own::(t)(cur_val1); close foreach([], own::(t)); close foreach([cur_val1], own::(t)); @@ -542,15 +577,17 @@ where } /*@ { if del0 == 0 { - close array::(buf + idx0 + 1, 0, nil); - close array::(buf + idx0, 1, [cur_val1]); - array_join::(buf); + close_points_to_at_lft(buf + idx0); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + close array_at_lft::(alloc_id.lft, buf + idx0 + 1, 0, nil); + close array_at_lft::(alloc_id.lft, buf + idx0, 1, [cur_val1]); + array_at_lft_join::(buf); close own::(t)(cur_val1); close foreach([], own::(t)); close foreach([cur_val1], own::(t)); foreach_append(retained, [cur_val1]); - open array_::(buf + idx0, 0, _); - close array_::(buf + idx0 + 1, 0, nil); + open array_at_lft_::(alloc_id.lft, buf + idx0, 0, _); + close array_at_lft_::(alloc_id.lft, buf + idx0 + 1, 0, nil); ghost_cell_mutate::>>(ghost_cell_id, some(pair(idx0 + 1, 0))); close ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)(); close_full_borrow(ExtractIf_fbc::(t, self_cur.vec, ghost_cell_id, self_cur.end, self_cur.old_len)); @@ -576,6 +613,7 @@ unsafe fn drop_body__VeriFast_wrapper<'a, T, F, A: Allocator>(this: &mut Extract //@ req thread_token(?t) &*& t == currentThread &*& [?q]lifetime_token('a) &*& >.full_borrow_content(t, this)(); //@ ens thread_token(t) &*& [q]lifetime_token('a) &*& (*this).vec |-> ?_vec &*& full_borrow('a, >.full_borrow_content(t, _vec)) &*& (*this).idx |-> ?_idx &*& (*this).end |-> ?_end &*& (*this).del |-> ?_del &*& (*this).old_len |-> ?_old_len &*& (*this).`pred` |-> ?p &*& .own(t, p) &*& struct_ExtractIf_padding(this); { + //@ assert lifetime_token(?flft); //@ open >.full_borrow_content(t, this)(); //@ open_points_to(this); //@ open >.own(t, ?self0); @@ -583,26 +621,78 @@ unsafe fn drop_body__VeriFast_wrapper<'a, T, F, A: Allocator>(this: &mut Extract //@ let klong = open_full_borrow_strong('a, ExtractIf_fbc::(t, self0.vec, ghost_cell_id, self0.end, self0.old_len), q); //@ open ExtractIf_fbc::(t, self0.vec, ghost_cell_id, self0.end, self0.old_len)(); //@ merge_fractions ghost_cell(ghost_cell_id, _); - //@ assert (*self0.vec).ptr |-> ?buf &*& (*self0.vec).cap |-> ?cap; - //@ assert buf[..idx0 - del0] |-> ?retained; - //@ assert buf[idx0..self0.old_len] |-> ?tail; + //@ assert (*self0.vec).buf |-> ?rv &*& RawVec(t, rv, ?alloc_id, ?buf, ?cap); + //@ assert array_at_lft(alloc_id.lft, buf, idx0 - del0, ?retained); + //@ assert array_at_lft(alloc_id.lft, buf + idx0, self0.old_len - idx0, ?tail); if this.del > 0 { // SAFETY: Trailing unchecked items must be valid since we never touch them. unsafe { //@ std::alloc::Layout_inv(std::alloc::Layout::new::()); //@ mul_mono_l(idx0, cap, std::mem::size_of::()); //@ mul_mono_l(idx0 - del0, cap, std::mem::size_of::()); - //@ close_points_to(self0.vec); + //@ let k_ptr = begin_lifetime(); + //@ points_to_limits(&(*self0.vec).buf); + //@ share_RawVec(k_ptr, &(*self0.vec).buf); //@ let vref = precreate_ref(self0.vec); - //@ init_ref_readonly(vref, 1/2); - //@ open_points_to(vref); + //@ open_ref_init_perm_Vec(vref); + //@ init_ref_RawVec_(&(*vref).buf); + //@ let klong_buf = open_frac_borrow_strong(k_ptr, ref_initialized_(&(*vref).buf), 1/2); + //@ open [?f_buf]ref_initialized_::>(&(*vref).buf)(); + //@ init_ref_readonly(&(*vref).len, 1/2); + //@ init_ref_padding_Vec(vref, 1/2); + /*@ { + pred P() = ref_padding_initialized(vref) &*& ref_initialized(&(*vref).len); + close [1 - f_buf]P(); + close_ref_initialized_Vec(vref); + open P(); + } @*/ + //@ assert pointer_within_limits(ref_origin(&(*self0.vec).buf)) == true; let src = this.vec.as_ptr().add(this.idx); - //@ close_points_to(vref, 1/2); - //@ end_ref_readonly(vref); - //@ open_points_to(self0.vec); + /*@ { + open_ref_initialized_Vec(vref); + end_ref_readonly(&(*vref).len); + assert (*self0.vec).len |-> 0; + end_ref_padding_Vec(vref); + assert struct_Vec_padding::(self0.vec); + close [f_buf]ref_initialized_::>(&(*vref).buf)(); + { + pred CtxBuf() = true; + produce_lem_ptr_chunk frac_borrow_convert_strong( + CtxBuf, + scaledp(f_buf, ref_initialized_(&(*vref).buf)), + klong_buf, + f_buf, + ref_initialized_(&(*vref).buf) + )() { + open CtxBuf(); + open scaledp(f_buf, ref_initialized_(&(*vref).buf))(); + } { + close CtxBuf(); + close scaledp(f_buf, ref_initialized_(&(*vref).buf))(); + close_frac_borrow_strong( + klong_buf, + ref_initialized_(&(*vref).buf), + scaledp(f_buf, ref_initialized_(&(*vref).buf)) + ); + leak full_borrow(klong_buf, scaledp(f_buf, ref_initialized_(&(*vref).buf))); + } + } + } @*/ + //@ end_lifetime(k_ptr); + //@ end_share_RawVec(&(*self0.vec).buf); let dst = this.vec.as_mut_ptr().add(this.idx - this.del); let count = this.old_len - this.idx; + //@ RawVec_inv::(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); /*@ { + assert array_at_lft_(alloc_id.lft, buf + (idx0 - del0), del0, ?hole_vs); + array_at_lft_to_array_at_lft_::(buf + idx0); + array_at_lft__join::(buf + (idx0 - del0)); + open_array_at_lft_::(buf + (idx0 - del0), q_alloc); + array__split::(buf + (idx0 - del0), del0); + take_drop_append_eq(del0, hole_vs, map(some, tail)); + array__map_some_to_array::(buf + idx0, tail); let sz = std::mem::size_of::(); array_to_u8s_bytes::(buf + idx0); assert ((buf + idx0) as *u8)[..count * sz] |-?-> ?bs; @@ -629,15 +719,29 @@ unsafe fn drop_body__VeriFast_wrapper<'a, T, F, A: Allocator>(this: &mut Extract } else { u8s__to_array_::(buf + (self0.old_len - del0), del0); } - array__join::(buf + (self0.old_len - del0)); + assert (buf + (self0.old_len - del0))[..del0] |-?-> ?new_hole; + array_to_array_::(buf + (idx0 - del0)); + array__join::(buf + (idx0 - del0)); + close_array_at_lft_::(buf + (idx0 - del0)); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + array_at_lft__split::(buf + (idx0 - del0), count); + take_drop_append_eq(count, map(some, tail), new_hole); + if count == 0 { + open array_at_lft_::(alloc_id.lft, buf + (idx0 - del0), 0, _); + match tail { nil => {} cons(x, xs) => {} } + close array_at_lft::(alloc_id.lft, buf + (idx0 - del0), 0, tail); + } else { + array_at_lft__to_array_at_lft::(buf + (idx0 - del0), tail); + } + array_at_lft__join::(buf + (self0.old_len - del0)); } @*/ } } /*@ { if del0 == 0 { - open array_::(buf + idx0, 0, _); + open array_at_lft_::(alloc_id.lft, buf + idx0, 0, _); } - array_join::(buf); + array_at_lft_join::(buf); foreach_append(retained, tail); } @*/ // SAFETY: After filling holes, all items are in contiguous memory. @@ -645,8 +749,10 @@ unsafe fn drop_body__VeriFast_wrapper<'a, T, F, A: Allocator>(this: &mut Extract this.vec.set_len(this.old_len - this.del); } /*@ { + open_points_to(&(*self0.vec).buf); close_points_to(self0.vec); - close >.own(t, *self0.vec); + assert *self0.vec |-> ?v1; + close >.own(t, v1); close_full_borrow_content::>(t, self0.vec); ghost_cell_mutate::>>(ghost_cell_id, none); { diff --git a/verifast-proofs/alloc/vec/extract_if.rs/verified/lib.rs b/verifast-proofs/alloc/vec/extract_if.rs/verified/lib.rs index c88741eeccff2..9919f3e7b2c8a 100644 --- a/verifast-proofs/alloc/vec/extract_if.rs/verified/lib.rs +++ b/verifast-proofs/alloc/vec/extract_if.rs/verified/lib.rs @@ -1,11 +1,41 @@ -// verifast_options{skip_specless_fns} +// verifast_options{skip_specless_fns ignore_unwind_paths} +#![allow(dead_code)] #![no_std] #![allow(internal_features)] #![allow(incomplete_features)] +#![feature(allocator_api)] #![feature(allocator_ext)] #![feature(staged_api)] #![feature(rustc_attrs)] +#![feature(dropck_eyepatch)] +#![feature(specialization)] +#![feature(extend_one)] +#![feature(exact_size_is_empty)] +#![feature(hasher_prefixfree_extras)] +#![feature(box_into_inner)] +#![feature(try_trait_v2)] +#![feature(optimize_attribute)] +#![feature(temporary_niche_types)] +#![feature(ptr_internals)] +#![feature(try_reserve_kind)] +#![feature(ptr_alignment_type)] +#![feature(ptr_cast_slice)] +#![feature(const_closures)] +#![feature(const_result_trait_fn)] +#![feature(sized_type_properties)] +#![feature(std_internals)] +#![feature(alloc_layout_extra)] +#![feature(const_alloc_error)] +#![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_destruct)] +#![feature(const_heap)] +#![feature(const_option_ops)] +#![feature(const_trait_impl)] +#![feature(const_try)] +#![feature(nonnull_provenance)] +#![feature(panic_internals)] #![feature(slice_range)] #![stable(feature = "rust1", since = "1.0.0")] @@ -14,17 +44,25 @@ extern crate alloc as std; #[stable(feature = "rust1", since = "1.0.0")] pub use std::alloc as alloc; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::boxed as boxed; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::collections as collections; + +pub mod raw_vec; +#[stable(feature = "rust1", since = "1.0.0")] +pub mod extract_if; use crate::alloc::{Allocator, Global}; +use crate::raw_vec::RawVec; //@ use std::alloc::{Allocator, Global}; +//@ use raw_vec::{RawVec, RawVecInner, RawVec_inv, RawVec_inv2, RawVec_own, RawVec_send_, RawVec_sync_, RawVec_to_own, RawVec_share_, RawVec_share__mono, RawVec_share_full_, RawVec_full_borrow, close_RawVec_full_borrow, close_RawVec_full_borrow_content_, open_RawVec_full_borrow_content_, share_RawVec, end_share_RawVec, init_ref_RawVec_, init_ref_RawVec_m, RawVec_full_borrow_content_}; #[stable(feature = "rust1", since = "1.0.0")] -pub struct Vec { - ptr: *mut T, - cap: usize, +pub struct Vec { + buf: RawVec, len: usize, - alloc: A, } #[stable(feature = "rust1", since = "1.0.0")] @@ -32,27 +70,21 @@ unsafe impl Send for Vec {} /*@ -// Abstract handle representing the backing allocation owned by `RawVec` -// (untouched by `ExtractIf`, which never allocates, reallocates, or deallocates). -// Unlike VeriFast 26.10's `std/lib.rsspec:1704` `Vec_inv` (`capacity <= isize::MAX`), -// this `Vec` model enforces Rust's true ZST-sound bound `cap * size_of::() <= isize::MAX` -// matching VeriFast's own `prelude_core.rsspec:253` `array__inv`. -pred Vec_alloc_handle(addr: usize, byte_cap: usize); - pred >.own(t, v) = - .own(t, v.alloc) &*& - Vec_alloc_handle(v.ptr as usize, v.cap * std::mem::size_of::()) &*& - 0 <= v.len &*& v.len <= v.cap &*& - v.cap * std::mem::size_of::() <= isize::MAX &*& - 0 <= v.ptr as usize &*& v.ptr as usize % std::mem::align_of::() == 0 &*& - v.ptr[..v.len] |-> ?elems &*& foreach(elems, own::(t)) &*& - v.ptr[v.len..v.cap] |-> _; + RawVec(t, v.buf, ?alloc_id, ?ptr, ?cap) &*& + 0 <= v.len &*& v.len <= cap &*& + cap * std::mem::size_of::() <= isize::MAX &*& + 0 <= ptr as usize &*& ptr as usize % std::mem::align_of::() == 0 &*& + array_at_lft(alloc_id.lft, ptr, v.len, ?elems) &*& foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, ptr + v.len, cap - v.len, _); -pred_ctor Vec_val(l: *Vec, v: Vec)(;) = - *l |-> v; +pred_ctor Vec_len_val(l: *Vec, len: usize)(;) = + (*l).len |-> len &*& struct_Vec_padding::(l); pred >.share(k, t, l) = - [_]exists::>(?v) &*& [_]frac_borrow(k, Vec_val::(l, v)); + pointer_within_limits(&(*l).buf) == true &*& + [_]RawVec_share_(k, t, &(*l).buf, ?alloc_id, ?ptr, ?cap) &*& + [_]exists::(?len) &*& [_]frac_borrow(k, Vec_len_val::(l, len)); lem Vec_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *Vec) req type_interp::() &*& type_interp::() &*& @@ -60,10 +92,11 @@ lem Vec_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *Vec< ens type_interp::() &*& type_interp::() &*& [_]Vec_share::(k1, t, l); { open Vec_share::(k, t, l); - assert [_]exists::>(?v) &*& [_]frac_borrow(k, Vec_val::(l, v)); - frac_borrow_mono(k, k1, Vec_val::(l, v)); - close exists::>(v); - leak exists::>(v); + RawVec_share__mono::(k, k1, t, &(*l).buf); + assert [_]exists::(?len); + frac_borrow_mono(k, k1, Vec_len_val::(l, len)); + close exists::(len); + leak exists::(len); close Vec_share::(k1, t, l); leak Vec_share::(k1, t, l); } @@ -77,80 +110,74 @@ lem Vec_share_full(k: lifetime_t, t: thread_id_t, l: *Vec) let klong = open_full_borrow_strong_m(k, Vec_full_borrow_content::(t, l), q); open Vec_full_borrow_content::(t, l)(); assert *l |-> ?v; - close Vec_val::(l, v)(); + open_points_to(l); + close_points_to(&(*l).buf); + points_to_limits(&(*l).buf); + open >.own(t, v); + let len = v.len; + assert RawVec(t, v.buf, ?alloc_id, ?ptr, ?cap); + assert array_at_lft(alloc_id.lft, ptr, len, ?elems); + assert array_at_lft_(alloc_id.lft, ptr + len, cap - len, ?spare); + close_RawVec_full_borrow_content_(t, &(*l).buf, alloc_id, ptr, cap); + close Vec_len_val::(l, len)(); + close sep( + RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, cap), + Vec_len_val::(l, len) + )(); { - pred Ctx() = >.own(t, v); + pred Ctx() = + 0 <= len &*& len <= cap &*& + cap * std::mem::size_of::() <= isize::MAX &*& + 0 <= ptr as usize &*& ptr as usize % std::mem::align_of::() == 0 &*& + array_at_lft(alloc_id.lft, ptr, len, elems) &*& foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, ptr + len, cap - len, spare); produce_lem_ptr_chunk full_borrow_convert_strong( Ctx, - Vec_val::(l, v), + sep( + RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, cap), + Vec_len_val::(l, len) + ), klong, Vec_full_borrow_content::(t, l) )() { open Ctx(); - open Vec_val::(l, v)(); + open sep( + RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, cap), + Vec_len_val::(l, len) + )(); + open_RawVec_full_borrow_content_(t, &(*l).buf, alloc_id, ptr, cap); + open Vec_len_val::(l, len)(); + assert (*l).buf |-> ?buf1; + close >.own(t, Vec:: { buf: buf1, len }); close Vec_full_borrow_content::(t, l)(); } { close Ctx(); - close_full_borrow_strong_m(klong, Vec_full_borrow_content::(t, l), Vec_val::(l, v)); - full_borrow_into_frac_m(klong, Vec_val::(l, v)); - frac_borrow_mono(klong, k, Vec_val::(l, v)); + close_full_borrow_strong_m( + klong, + Vec_full_borrow_content::(t, l), + sep( + RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, cap), + Vec_len_val::(l, len) + ) + ); + full_borrow_split_m( + klong, + RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, cap), + Vec_len_val::(l, len) + ); + full_borrow_mono(klong, k, RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, cap)); + close_RawVec_full_borrow(k, t, &(*l).buf, alloc_id, ptr, cap); + RawVec_share_full_::(k, &(*l).buf); + full_borrow_into_frac_m(klong, Vec_len_val::(l, len)); + frac_borrow_mono(klong, k, Vec_len_val::(l, len)); } } - close exists::>(v); - leak exists::>(v); + close exists::(len); + leak exists::(len); close Vec_share::(k, t, l); leak Vec_share::(k, t, l); } -lem init_ref_Vec(p: *Vec) - req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& - ref_init_perm(p, ?x) &*& [_]Vec_share::(?k, ?t, x) &*& [?q]lifetime_token(k); - ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& - [q]lifetime_token(k) &*& [_]Vec_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); -{ - open >.share(k, t, x); - assert [_]exists::>(?v); - let klong = open_frac_borrow_strong_m(k, Vec_val::(x, v), q); - open [?f]Vec_val::(x, v)(); - init_ref_readonly(p, 1/2); - close [f/2]Vec_val::(p, v)(); - close scaledp(f/2, Vec_val::(p, v))(); - close ref_initialized_::>(p)(); - close sep(scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p))(); - { - pred Ctx() = - ref_readonly_end_token(p, x, f/2) &*& - [f/2](*x |-> v); - produce_lem_ptr_chunk frac_borrow_convert_strong( - Ctx, - sep(scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p)), - klong, - f, - Vec_val::(x, v) - )() { - open Ctx(); - open sep(scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p))(); - open scaledp(f/2, Vec_val::(p, v))(); - open [f/2]Vec_val::(p, v)(); - open ref_initialized_::>(p)(); - end_ref_readonly(p); - close [f]Vec_val::(x, v)(); - } { - close Ctx(); - close_frac_borrow_strong_m(); - full_borrow_mono(klong, k, sep(scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p))); - full_borrow_split_m(k, scaledp(f/2, Vec_val::(p, v)), ref_initialized_::>(p)); - full_borrow_into_frac_m(k, scaledp(f/2, Vec_val::(p, v))); - frac_borrow_implies_scaled(k, f/2, Vec_val::(p, v)); - full_borrow_into_frac_m(k, ref_initialized_::>(p)); - } - } - close exists::>(v); - leak exists::>(v); - close Vec_share::(k, t, p); - leak Vec_share::(k, t, p); -} - lem foreach_own_send_lib(t0: thread_id_t, t1: thread_id_t) req foreach(?xs, own::(t0)) &*& type_interp::() &*& is_Send(typeid(T)) == true; ens foreach(xs, own::(t1)) &*& type_interp::(); @@ -170,12 +197,14 @@ lem foreach_own_send_lib(t0: thread_id_t, t1: thread_id_t) lem Vec_drop() req Vec_own::(?_t, ?_v); - ens .own(_t, _v.alloc); + ens >.own(_t, _v.buf); { open >.own(_t, _v); - leak Vec_alloc_handle(_, _); - leak _v.ptr[.._v.len] |-> ?elems &*& foreach(elems, own::(_t)); - leak _v.ptr[_v.len.._v.cap] |-> _; + assert RawVec(_t, _v.buf, ?alloc_id, ?ptr, ?cap); + leak foreach(_, own::(_t)); + array_at_lft_to_array_at_lft_(ptr); + array_at_lft__join(ptr); + RawVec_to_own(_v.buf); } lem Vec_send(t1: thread_id_t) @@ -186,37 +215,170 @@ lem Vec_send(t1: thread_id_t) Vec_own::(t1, v); { open >.own(t0, v); - // `unsafe impl Send for Vec` implies `T: Send && A: Send`. assume(is_Send(typeid(T)) == true && is_Send(typeid(A)) == true); - Send::send::(t0, t1, v.alloc); + RawVec_send_::(t1); foreach_own_send_lib::(t0, t1); close >.own(t1, v); } -lem Vec_own_mono() - req type_interp::() &*& type_interp::() &*& type_interp::() &*& - Vec_own::(?t, ?v) &*& +lem Vec_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Sync(typeid(Vec)) == true &*& + [_]Vec_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& + [_]Vec_share::(k, t1, l); +{ + open Vec_share::(k, t0, l); + assume(is_Sync(typeid(RawVec)) == true); + RawVec_sync_::(t1); + close Vec_share::(k, t1, l); + leak Vec_share::(k, t1, l); +} + +lem array_at_lft_own_mono(t: thread_id_t, k: lifetime_t, p: *T0, n: usize) + req array_at_lft::(k, p, n, ?elems) &*& foreach(elems, own::(t)) &*& + type_interp::() &*& type_interp::() &*& + is_subtype_of::() == true &*& + std::mem::size_of::() == std::mem::size_of::() &*& + std::mem::align_of::() == std::mem::align_of::(); + ens array_at_lft::(k, p as *T1, n, ?elems1) &*& foreach(elems1, own::(t)) &*& + type_interp::() &*& type_interp::(); +{ + open array_at_lft::(k, p, n, elems); + open foreach(elems, own::(t)); + match elems { + nil => { + close array_at_lft::(k, p as *T1, 0, nil); + close foreach(nil, own::(t)); + } + cons(x, xs0) => { + open points_to_at_lft::(k, p, x); + to_u8s__at_lft::(p); + assert array_at_lft_(k, p as *u8, std::mem::size_of::(), ?bs); + from_u8s__at_lft::(p as *T1); + // Rust subtyping (`T0 <: T1`) only weakens lifetimes and preserves byte + // representation (https://github.com/verifast/verifast/issues/610). + let x1 = upcast::(x); + assume(of_u8s_::(bs) == some(x1)); + close points_to_at_lft::(k, p as *T1, x1); + open own::(t)(x); + own_mono::(t, x); + close own::(t)(x1); + array_at_lft_own_mono::(t, k, p + 1, n - 1); + assert array_at_lft::(k, (p + 1) as *T1, n - 1, ?xs1); + assert ((p + 1) as *T1) == ((p as *T1) + 1); + close array_at_lft::(k, p as *T1, n, cons(x1, xs1)); + close foreach(cons(x1, xs1), own::(t)); + } + } +} + +lem Vec_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + Vec_own::(?t, ?v) &*& + is_subtype_of::() == true &*& is_subtype_of::() == true; - ens type_interp::() &*& type_interp::() &*& type_interp::() &*& - Vec_own::(t, Vec:: { - ptr: v.ptr as *_, - cap: upcast(v.cap), + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + Vec_own::(t, Vec:: { + buf: upcast(v.buf), len: upcast(v.len), - alloc: upcast(v.alloc) }); { - open >.own(t, v); - own_mono::(t, v.alloc); - // `upcast` on `usize` is identity (verifast#610). - assume(upcast(v.cap) == v.cap && upcast(v.len) == v.len); - close >.own(t, Vec:: { - ptr: v.ptr as *_, - cap: upcast(v.cap), + open >.own(t, v); + assert RawVec(t, v.buf, ?alloc_id, ?ptr, ?cap); + open RawVec(t, v.buf, alloc_id, ptr, cap); + open RawVecInner(t, v.buf.inner, std::alloc::Layout::new::(), alloc_id, ?ptr_, cap); + std::alloc::Allocator_upcast::(v.buf.inner.alloc); + // Rust subtyping (`T0 <: T1`, `A0 <: A1`) only weakens lifetimes: layout and + // scalar/field representations are preserved (https://github.com/verifast/verifast/issues/610). + let buf1 = upcast::, RawVec>(v.buf); + assume( + std::mem::size_of::() == std::mem::size_of::() && + std::mem::align_of::() == std::mem::align_of::() && + std::alloc::Layout::new::() == std::alloc::Layout::new::() && + upcast::(v.len) == v.len && + buf1.inner.ptr == v.buf.inner.ptr && + buf1.inner.cap == v.buf.inner.cap && + buf1.inner.alloc == upcast::(v.buf.inner.alloc) + ); + close RawVecInner::(t, buf1.inner, std::alloc::Layout::new::(), alloc_id, ptr_, cap); + close RawVec::(t, buf1, alloc_id, ptr as *T1, cap); + array_at_lft_own_mono::(t, alloc_id.lft, ptr, v.len); + array_at_lft__to_u8s_at_lft_::(ptr + v.len, cap - v.len); + assert ((ptr + v.len) as *u8) == (((ptr as *T1) + v.len) as *u8); + u8s_at_lft__to_array_at_lft_::((ptr as *T1) + v.len, cap - v.len); + close >.own(t, Vec:: { + buf: buf1, len: upcast(v.len), - alloc: upcast(v.alloc) }); } +lem init_ref_Vec(p: *Vec) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + ref_init_perm(p, ?x) &*& [_]Vec_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + [q]lifetime_token(k) &*& [_]Vec_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open >.share(k, t, x); + assert [_]exists::(?len); + open_ref_init_perm_Vec(p); + init_ref_RawVec_m::(&(*p).buf); + frac_borrow_sep(k, Vec_len_val::(x, len), ref_initialized_(&(*p).buf)); + let klong = open_frac_borrow_strong_m(k, sep_(Vec_len_val::(x, len), ref_initialized_(&(*p).buf)), q); + open [?f]sep_(Vec_len_val::(x, len), ref_initialized_(&(*p).buf))(); + open [f]Vec_len_val::(x, len)(); + open [f]ref_initialized_::>(&(*p).buf)(); + init_ref_readonly(&(*p).len, 1/2); + init_ref_padding_Vec(p, 1/2); + { + pred P() = ref_padding_initialized(p); + close [1 - f/2]P(); + close_ref_initialized_Vec(p); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*p).buf) &*& + ref_padding_end_token(p, x, f/2) &*& [f/2]struct_Vec_padding::(x) &*& [1 - f/2]ref_padding_initialized(p) &*& + ref_readonly_end_token(&(*p).len, &(*x).len, f/2) &*& [f/2]((*x).len |-> len) &*& [1 - f/2]ref_initialized(&(*p).len); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + scaledp(f/2, sep_(ref_initialized_(p), Vec_len_val::(p, len))), + klong, + f, + sep_(Vec_len_val::(x, len), ref_initialized_(&(*p).buf)) + )() { + open scaledp(f/2, sep_(ref_initialized_(p), Vec_len_val::(p, len)))(); + open sep_(ref_initialized_(p), Vec_len_val::(p, len))(); + open ref_initialized_::>(p)(); + open Vec_len_val::(p, len)(); + open_ref_initialized_Vec(p); + open Ctx(); + end_ref_readonly(&(*p).len); + end_ref_padding_Vec(p); + close [f]Vec_len_val::(x, len)(); + close [f]ref_initialized_::>(&(*p).buf)(); + close [f]sep_(Vec_len_val::(x, len), ref_initialized_(&(*p).buf))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(p)(); + close [f/2]Vec_len_val::(p, len)(); + close [f/2]sep_(ref_initialized_(p), Vec_len_val::(p, len))(); + close scaledp(f/2, sep_(ref_initialized_(p), Vec_len_val::(p, len)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), Vec_len_val::(p, len)))); + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(p), Vec_len_val::(p, len)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), Vec_len_val::(p, len))); + frac_borrow_split(k, ref_initialized_(p), Vec_len_val::(p, len)); + } + } + assert pointer_within_limits(ref_origin(&(*x).buf)) == true; + close exists::(len); + leak exists::(len); + close Vec_share::(k, t, p); + leak Vec_share::(k, t, p); +} + @*/ impl Vec { @@ -229,14 +391,12 @@ impl Vec { safety_proof { open >.share(?k, _t, self); assert [?q]lifetime_token(k); - assert [_]exists::>(?v); - open_frac_borrow(k, Vec_val::(self, v), q); - open [?f]Vec_val::(self, v)(); - open_points_to(self); + assert [_]exists::(?len); + open_frac_borrow(k, Vec_len_val::(self, len), q); + open [?f]Vec_len_val::(self, len)(); call(); - close_points_to(self, f); - close [f]Vec_val::(self, v)(); - close_frac_borrow(f, Vec_val::(self, v)); + close [f]Vec_len_val::(self, len)(); + close_frac_borrow(f, Vec_len_val::(self, len)); } @*/ { @@ -246,46 +406,62 @@ impl Vec { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn as_ptr(&self) -> *const T - //@ req [?f](*self).ptr |-> ?p; - //@ ens [f](*self).ptr |-> p &*& result == p; + //@ req pointer_within_limits(&(*self).buf) == true &*& [_]RawVec_share_(?k, ?t, &(*self).buf, ?alloc_id, ?ptr, ?cap) &*& [?q]lifetime_token(k); + //@ ens [q]lifetime_token(k) &*& result == ptr; /*@ safety_proof { open >.share(?k, _t, self); - assert [?q]lifetime_token(k); - assert [_]exists::>(?v); - open_frac_borrow(k, Vec_val::(self, v), q); - open [?f]Vec_val::(self, v)(); - open_points_to(self); call(); - close_points_to(self, f); - close [f]Vec_val::(self, v)(); - close_frac_borrow(f, Vec_val::(self, v)); } @*/ { - self.ptr + //@ let buf_ref = precreate_ref(&(*self).buf); + //@ init_ref_RawVec_(buf_ref); + //@ open_frac_borrow(k, ref_initialized_(buf_ref), q/2); + //@ open [?f]ref_initialized_::>(buf_ref)(); + let r = self.buf.ptr(); + //@ close [f]ref_initialized_::>(buf_ref)(); + //@ close_frac_borrow(f, ref_initialized_(buf_ref)); + r } #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn as_mut_ptr(&mut self) -> *mut T - //@ req [?f](*self).ptr |-> ?p; - //@ ens [f](*self).ptr |-> p &*& result == p; + //@ req (*self).buf |-> ?buf &*& RawVec(?t, buf, ?alloc_id, ?ptr, ?cap); + //@ ens (*self).buf |-> ?buf1 &*& RawVec(t, buf1, alloc_id, ptr, cap) &*& result == ptr; /*@ safety_proof { open_points_to(self); + close_points_to(&(*self).buf); + open >.own(_t, ?v); call(); + open_points_to(&(*self).buf); close_points_to(self); + assert *self |-> ?v1; + close >.own(_t, v1); } @*/ { - self.ptr + //@ let k = begin_lifetime(); + //@ points_to_limits(&(*self).buf); + //@ share_RawVec(k, &(*self).buf); + //@ let buf_ref = precreate_ref(&(*self).buf); + //@ init_ref_RawVec_(buf_ref); + //@ open_frac_borrow(k, ref_initialized_(buf_ref), 1/2); + //@ open [?f]ref_initialized_::>(buf_ref)(); + let r = self.buf.ptr(); + //@ close [f]ref_initialized_::>(buf_ref)(); + //@ close_frac_borrow(f, ref_initialized_(buf_ref)); + //@ end_lifetime(k); + //@ end_share_RawVec(&(*self).buf); + r } #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub unsafe fn set_len(&mut self, new_len: usize) - //@ req (*self).len |-> _; + //@ req (*self).len |-> ?_old; //@ ens (*self).len |-> new_len; { self.len = new_len; @@ -294,9 +470,6 @@ impl Vec { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn allocator(&self) -> &A { - &self.alloc + self.buf.allocator() } } - -#[stable(feature = "rust1", since = "1.0.0")] -pub mod extract_if; diff --git a/verifast-proofs/alloc/vec/extract_if.rs/verified/raw_vec.rs b/verifast-proofs/alloc/vec/extract_if.rs/verified/raw_vec.rs new file mode 120000 index 0000000000000..a545ffff6b4b2 --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/verified/raw_vec.rs @@ -0,0 +1 @@ +../../../raw_vec/mod.rs/verified/raw_vec.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/extract_if.rs/verify.sh b/verifast-proofs/alloc/vec/extract_if.rs/verify.sh index a6d45d0d957d3..64524e88fb7ef 100644 --- a/verifast-proofs/alloc/vec/extract_if.rs/verify.sh +++ b/verifast-proofs/alloc/vec/extract_if.rs/verify.sh @@ -3,8 +3,13 @@ set -e -x export VFVERSION=26.10 verifast -rustc_args "--edition 2024" -skip_specless_fns -ignore_unwind_paths -allow_assume verified/lib.rs -refinement-checker --rustc-args "--edition 2024" original/lib.rs verified/lib.rs > /dev/null +refinement-checker --rustc-args "--edition 2024" with-directives/lib.rs verified/lib.rs > /dev/null +refinement-checker --ignore-directives --rustc-args "--edition 2024" original/lib.rs with-directives/lib.rs > /dev/null if ! diff original/extract_if.rs ../../../../library/alloc/src/vec/extract_if.rs; then echo "::error title=Please run verifast-proofs/patch-verifast-proofs.sh::Some VeriFast proofs are out of date; please chdir to verifast-proofs and run patch-verifast-proofs.sh to update them." false fi +if ! diff original/raw_vec.rs ../../../../library/alloc/src/raw_vec/mod.rs; then + echo "::error title=Please run verifast-proofs/patch-verifast-proofs.sh::Some VeriFast proofs are out of date; please chdir to verifast-proofs and run patch-verifast-proofs.sh to update them." + false +fi diff --git a/verifast-proofs/alloc/vec/extract_if.rs/with-directives/extract_if.rs b/verifast-proofs/alloc/vec/extract_if.rs/with-directives/extract_if.rs new file mode 120000 index 0000000000000..72d9e946937d2 --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/with-directives/extract_if.rs @@ -0,0 +1 @@ +../original/extract_if.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/extract_if.rs/with-directives/lib.rs b/verifast-proofs/alloc/vec/extract_if.rs/with-directives/lib.rs new file mode 100644 index 0000000000000..2c8b3a8a03944 --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/with-directives/lib.rs @@ -0,0 +1,98 @@ +// verifast_options{skip_specless_fns ignore_unwind_paths} + +#![allow(dead_code)] +#![no_std] +#![allow(internal_features)] +#![allow(incomplete_features)] +#![feature(allocator_api)] +#![feature(allocator_ext)] +#![feature(staged_api)] +#![feature(rustc_attrs)] +#![feature(dropck_eyepatch)] +#![feature(specialization)] +#![feature(extend_one)] +#![feature(exact_size_is_empty)] +#![feature(hasher_prefixfree_extras)] +#![feature(box_into_inner)] +#![feature(try_trait_v2)] +#![feature(optimize_attribute)] +#![feature(temporary_niche_types)] +#![feature(ptr_internals)] +#![feature(try_reserve_kind)] +#![feature(ptr_alignment_type)] +#![feature(ptr_cast_slice)] +#![feature(const_closures)] +#![feature(const_result_trait_fn)] +#![feature(sized_type_properties)] +#![feature(std_internals)] +#![feature(alloc_layout_extra)] +#![feature(const_alloc_error)] +#![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_destruct)] +#![feature(const_heap)] +#![feature(const_option_ops)] +#![feature(const_trait_impl)] +#![feature(const_try)] +#![feature(nonnull_provenance)] +#![feature(panic_internals)] +#![feature(slice_range)] + +#![stable(feature = "rust1", since = "1.0.0")] + +extern crate alloc as std; + +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::alloc as alloc; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::boxed as boxed; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::collections as collections; + +pub mod raw_vec; +#[stable(feature = "rust1", since = "1.0.0")] +pub mod extract_if; + +use crate::alloc::{Allocator, Global}; +use crate::raw_vec::RawVec; + +#[stable(feature = "rust1", since = "1.0.0")] +pub struct Vec { + buf: RawVec, + len: usize, +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for Vec {} + +impl Vec { + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn len(&self) -> usize { + self.len + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn as_ptr(&self) -> *const T { + self.buf.ptr() + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn as_mut_ptr(&mut self) -> *mut T { + self.buf.ptr() + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + self.len = new_len; + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn allocator(&self) -> &A { + self.buf.allocator() + } +} diff --git a/verifast-proofs/alloc/vec/extract_if.rs/with-directives/raw_vec.rs b/verifast-proofs/alloc/vec/extract_if.rs/with-directives/raw_vec.rs new file mode 120000 index 0000000000000..da2b83bdb686d --- /dev/null +++ b/verifast-proofs/alloc/vec/extract_if.rs/with-directives/raw_vec.rs @@ -0,0 +1 @@ +../../../raw_vec/mod.rs/with-directives/raw_vec.rs \ No newline at end of file From e90544647e76ea3eda51707ab5323a553b6eccc2 Mon Sep 17 00:00:00 2001 From: Emre Kaplaner Date: Mon, 30 Nov 2026 18:43:05 -0800 Subject: [PATCH 3/4] Upgrade Ch. 24: polymorphic RawVec-bridged VeriFast IntoIter proof + negative UB suite + aligned-ZST/null-end Kani hardening --- library/alloc/src/vec/verify_iter_spec.rs | 48 + verifast-proofs/README.md | 1 + .../alloc/vec/extract_if.rs/README.md | 4 +- .../alloc/vec/into_iter.rs-negative/README.md | 25 + .../vec/into_iter.rs-negative/mutant1.patch | 14 + .../into_iter.rs | 2388 ++++++++++++ .../mutant1_zst_next_back_read_end/lib.rs | 1 + .../mutant1_zst_next_back_read_end/raw_vec.rs | 1 + .../vec/into_iter.rs-negative/mutant2.patch | 11 + .../into_iter.rs | 2387 ++++++++++++ .../mutant2_fold_skip_ptr_advance/lib.rs | 1 + .../mutant2_fold_skip_ptr_advance/raw_vec.rs | 1 + .../alloc/vec/into_iter.rs-negative/original | 1 + .../vec/into_iter.rs-negative/safety_stub.rs | 1 + .../into_iter.rs-negative/tuple_ext.rsspec | 1 + .../alloc/vec/into_iter.rs-negative/update.sh | 41 + .../alloc/vec/into_iter.rs-negative/verify.sh | 91 + .../vec/into_iter.rs-negative/with-directives | 1 + .../alloc/vec/into_iter.rs/README.md | 209 ++ .../vec/into_iter.rs/original/into_iter.rs | 825 ++++ .../alloc/vec/into_iter.rs/original/lib.rs | 168 + .../vec/into_iter.rs/original/raw_vec.rs | 1 + .../vec/into_iter.rs/raw_vec_verified.patch | 109 + .../alloc/vec/into_iter.rs/safety_stub.rs | 12 + .../alloc/vec/into_iter.rs/std_ext.rsspec | 6 + .../alloc/vec/into_iter.rs/try_fold.patch | 189 + .../alloc/vec/into_iter.rs/tuple_ext.rsspec | 5 + .../alloc/vec/into_iter.rs/update.sh | 44 + .../vec/into_iter.rs/verified/into_iter.rs | 2387 ++++++++++++ .../alloc/vec/into_iter.rs/verified/lib.rs | 316 ++ .../vec/into_iter.rs/verified/raw_vec.rs | 3321 +++++++++++++++++ .../verified_try_fold/into_iter.rs | 2520 +++++++++++++ .../vec/into_iter.rs/verified_try_fold/lib.rs | 1 + .../into_iter.rs/verified_try_fold/raw_vec.rs | 1 + .../alloc/vec/into_iter.rs/verify.sh | 74 + .../vec/into_iter.rs/with-directives.patch | 47 + .../into_iter.rs/with-directives/into_iter.rs | 825 ++++ .../vec/into_iter.rs/with-directives/lib.rs | 1 + .../into_iter.rs/with-directives/raw_vec.rs | 1 + .../check-verifast-proofs-negative.sh | 5 + verifast-proofs/check-verifast-proofs.sh | 3 + verifast-proofs/patch-verifast-proofs.sh | 6 + 42 files changed, 16092 insertions(+), 2 deletions(-) create mode 100644 verifast-proofs/alloc/vec/into_iter.rs-negative/README.md create mode 100644 verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1.patch create mode 100644 verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/into_iter.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/lib.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/raw_vec.rs create mode 100644 verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2.patch create mode 100644 verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/into_iter.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/lib.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/raw_vec.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs-negative/original create mode 120000 verifast-proofs/alloc/vec/into_iter.rs-negative/safety_stub.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs-negative/tuple_ext.rsspec create mode 100644 verifast-proofs/alloc/vec/into_iter.rs-negative/update.sh create mode 100644 verifast-proofs/alloc/vec/into_iter.rs-negative/verify.sh create mode 120000 verifast-proofs/alloc/vec/into_iter.rs-negative/with-directives create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/README.md create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/original/into_iter.rs create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/original/lib.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs/original/raw_vec.rs create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/raw_vec_verified.patch create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/safety_stub.rs create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/std_ext.rsspec create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/try_fold.patch create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/tuple_ext.rsspec create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/update.sh create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/verified/into_iter.rs create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/verified/lib.rs create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/verified/raw_vec.rs create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/into_iter.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/lib.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/raw_vec.rs create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/verify.sh create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/with-directives.patch create mode 100644 verifast-proofs/alloc/vec/into_iter.rs/with-directives/into_iter.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs/with-directives/lib.rs create mode 120000 verifast-proofs/alloc/vec/into_iter.rs/with-directives/raw_vec.rs diff --git a/library/alloc/src/vec/verify_iter_spec.rs b/library/alloc/src/vec/verify_iter_spec.rs index a391b3e8853eb..49686b19e2bab 100644 --- a/library/alloc/src/vec/verify_iter_spec.rs +++ b/library/alloc/src/vec/verify_iter_spec.rs @@ -377,6 +377,10 @@ pub(super) trait Shape: Sized { /// dead-branch unreachable `kani::cover` goals. fn when_zst(_f: impl FnOnce()) {} + /// Runs `f` only on over-aligned ZST instantiations (`align_of::() > 1`) + /// so non-ZST and 1-aligned ZST harnesses never emit unreachable covers. + fn when_aligned_zst(_f: impl FnOnce()) {} + /// Initializes an uninitialized slot at `p` by writing its non-padding /// fields so every padding byte remains genuinely uninitialized while /// avoiding redundant multi-byte padding writes in CBMC. @@ -491,6 +495,9 @@ impl Shape for AlignedZst { fn when_zst(f: impl FnOnce()) { f(); } + fn when_aligned_zst(f: impl FnOnce()) { + f(); + } } impl Shape for NonPow2 { fn from_byte(b: u8) -> Self { @@ -535,6 +542,9 @@ impl Shape for DropZst { fn when_zst(f: impl FnOnce()) { f(); } + fn when_aligned_zst(f: impl FnOnce()) { + f(); + } } impl Shape for DropNiche { const ALLOW_ZERO: bool = false; @@ -1745,6 +1755,7 @@ fn check_into_iter_next_back() { } let small = witness_ok::(it.cap); let old_ptr = it.ptr; + assert!(old_ptr.as_ptr().is_aligned()); reset_drops(); match it.next_back() { None => assert!(n == 0), @@ -1758,10 +1769,17 @@ fn check_into_iter_next_back() { } assert!(drops() == 0); assert!(it.ptr == old_ptr); + assert!(it.ptr.as_ptr().is_aligned()); assert!(it.len() == n.saturating_sub(1)); kani::cover(n == 0, "exhausted"); kani::cover(n == 1, "last element"); kani::cover(small && n > 4096, "deep"); + T::when_aligned_zst(|| { + kani::cover( + n > 0 && !(it.end as usize).is_multiple_of(mem::align_of::()), + "aligned zst with misaligned end", + ); + }); finish::(it); } @@ -1821,6 +1839,36 @@ gen_harnesses! { check_into_iter_size_hint: check_into_iter_size_hint_nonzero => NonZero, } +/// Standalone Kani proof for ZST `IntoIter<()>` across the ENTIRE `0..=usize::MAX` +/// length domain — including `len == usize::MAX` where `ptr = NonNull::dangling()` +/// (`addr = 1`) and `end = ptr::null()` (`addr = 0`), exercising `size_hint`'s +/// `wrapping_sub` and `is_empty()` without hitting CBMC's 52-bit `wrapping_byte_add` +/// offset wraparound. Full symbolic ZST `0..=usize::MAX` across `next`, `next_back`, +/// `size_hint`, `is_empty`, `fold`, `try_fold`, `advance_by`, and `advance_back_by` +/// is also proved polymorphically in `verifast-proofs/alloc/vec/into_iter.rs/`. +#[kani::proof] +fn check_into_iter_size_hint_zst_null_end() { + let end_addr: usize = kani::any(); + let ptr = NonNull::<()>::dangling(); + let end: *const () = ptr::without_provenance(end_addr); + let expected = end_addr.wrapping_sub(ptr.as_ptr().addr()); + let it = IntoIter::<(), Global> { + buf: ptr, + phantom: PhantomData, + cap: usize::MAX, + alloc: ManuallyDrop::new(Global), + ptr, + end, + }; + assert!(it.size_hint() == (expected, Some(expected))); + assert!(it.len() == expected); + assert!(it.is_empty() == (expected == 0)); + kani::cover(it.end.is_null() && expected == usize::MAX, "null end at usize::MAX"); + kani::cover(expected == 0, "empty zst"); + kani::cover(expected > isize::MAX as usize && expected < usize::MAX, "above isize::MAX"); + drop(it); +} + gen_harnesses! { check_into_iter_as_slice: check_into_iter_as_slice_u8 => u8, check_into_iter_as_slice_overaligned => OverAligned, diff --git a/verifast-proofs/README.md b/verifast-proofs/README.md index 12c23c1ee1874..2f784429d689f 100644 --- a/verifast-proofs/README.md +++ b/verifast-proofs/README.md @@ -7,6 +7,7 @@ Specifically, it currently contains the following proofs: - Partial proof of [LinkedList](alloc/collections/linked_list.rs/) - Partial proof of [RawVec](alloc/raw_vec/mod.rs/) - Partial proof of [Vec::ExtractIf](alloc/vec/extract_if.rs/) +- Partial proof of [Vec::IntoIter](alloc/vec/into_iter.rs/) See each proof's accompanying README for a tour of the proof and applicable caveats. diff --git a/verifast-proofs/alloc/vec/extract_if.rs/README.md b/verifast-proofs/alloc/vec/extract_if.rs/README.md index 8c1cd9a77ebd9..bae32584369f6 100644 --- a/verifast-proofs/alloc/vec/extract_if.rs/README.md +++ b/verifast-proofs/alloc/vec/extract_if.rs/README.md @@ -12,8 +12,8 @@ arbitrary filter predicates `F: FnMut(&mut T) -> bool`, and arbitrary allocators ### `RawVec`-Bridged `Vec` & `ExtractIf_fbc` -VeriFast 26.10's built-in `std/lib.rsspec:1704` (`Vec_inv`) carries a stale -`capacity <= isize::MAX` axiom that contradicts zero-sized `Vec`s (`cap == usize::MAX`) +VeriFast 26.10's built-in `std/lib.rsspec:1704` (`Vec_inv`) currently states +`capacity <= isize::MAX` (which does not cover zero-sized `Vec`s with `cap == usize::MAX`) and requires `thread_token(t)` in `Vec_to_own` (`std/lib.rsspec:1714`). Rather than replacing `RawVec` with an abstract handle, `original/lib.rs`, `with-directives/lib.rs`, and `verified/lib.rs` import the repository's already-verified diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/README.md b/verifast-proofs/alloc/vec/into_iter.rs-negative/README.md new file mode 100644 index 0000000000000..34a41b6400b62 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/README.md @@ -0,0 +1,25 @@ +# Negative mutation tests for `Vec::IntoIter` VeriFast proof + +Companion negative test suite to [`into_iter.rs`](../into_iter.rs/) (mirroring +[`linked_list.rs-negative`](../../collections/linked_list.rs-negative/)). `verify.sh` +first runs a **known-good positive control** (`../into_iter.rs/verified/lib.rs`) through +both `verifast` and `refinement-checker` with the exact same compiler arguments, enforces +each mutant's exact 1-line diff against `../into_iter.rs/verified/into_iter.rs` via +`mutant1.patch` and `mutant2.patch`, and explicitly fails (`exit 1`) if either tool +unexpectedly exits `0` or fails without its expected diagnostic: + +1. **`mutant1_zst_next_back_read_end` (`mutant1.patch`):** Replaces + `ptr::read(self.ptr.as_ptr())` with `ptr::read(self.end)` in the ZST branch of + `DoubleEndedIterator::next_back`. Because `self.end` is decremented by 1 byte + (`wrapping_byte_sub(1)`), this read is rejected because `self.end` carries no element + ownership and causes UB whenever `align_of::() > 1`. + - Expected `verifast` diagnostic: `error: No matching heap chunks: [_]points_to` + - Expected `refinement-checker` diagnostic: `FnDef std::ptr::NonNull::::as_ptr` +2. **`mutant2_fold_skip_ptr_advance` (`mutant2.patch`):** Omits + `self.ptr = self.ptr.add(1)` in the non-ZST `while` loop of `Iterator::fold`, + introducing a double-read / use-after-move UB bug on the next iteration. + - Expected `verifast` diagnostic: `error: Cannot prove condition.` + - Expected `refinement-checker` diagnostic: `Command kinds do not match` + +`update.sh` regenerates both mutants directly from the updated positive proof +`../into_iter.rs/verified/into_iter.rs` plus `mutant1.patch` / `mutant2.patch`. diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1.patch b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1.patch new file mode 100644 index 0000000000000..c164518f85197 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1.patch @@ -0,0 +1,14 @@ +--- verified/into_iter.rs ++++ mutant1_zst_next_back_read_end/into_iter.rs +@@ -2011,8 +2011,9 @@ + // Note that even though this is next_back() we're reading from `self.ptr`, not + // `self.end`. We track our length using the byte offset from `self.ptr` to `self.end`, + // so the end pointer may not be suitably aligned for T. +- // ignore-tidy-undocumented-unsafe +- let res = Some(unsafe { ptr::read(self.ptr.as_ptr()) }); ++ // MUTANT 1: reading from `self.end` instead of `self.ptr` is UB for aligned ZSTs ++ // because `self.end` is decremented by 1 byte and may be misaligned for `T`. ++ let res = Some(unsafe { ptr::read(self.end) }); + /*@ { + close_points_to_at_lft_(self0.ptr.as_ptr()); + lifetime_token_trade_back(q_alloc, alloc_id.lft); diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/into_iter.rs b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/into_iter.rs new file mode 100644 index 0000000000000..e4e6fc0993c3b --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/into_iter.rs @@ -0,0 +1,2388 @@ +use core::iter::{ + FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, + TrustedRandomAccessNoCoerce, +}; +#[cfg(kani)] +use core::kani; +use core::marker::PhantomData; +use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties}; +use core::num::NonZero; +#[cfg(not(no_global_oom_handling))] +use core::ops::Deref; +use core::panic::UnwindSafe; +use core::ptr::{self, NonNull}; +use core::{array, fmt, slice}; + +use safety::{loop_invariant, requires}; + +#[cfg(not(no_global_oom_handling))] +use super::AsVecIntoIter; +use crate::alloc::{Allocator, Global}; +#[cfg(not(no_global_oom_handling))] +use crate::collections::VecDeque; +use crate::raw_vec::RawVec; + +//@ use std::alloc::{Allocator, alloc_id_t, alloc_block_in, Layout}; +//@ use std::ptr::{NonNull, NonNull_as_ptr_nonnull}; +//@ use std::option::{Option, Option::None, Option::Some}; +//@ use std::ops::ControlFlow; +//@ use raw_vec::{RawVec, RawVec_to_own, RawVec_inv}; + +macro non_null { + (mut $place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { &mut *((&raw mut $place) as *mut NonNull<$t>) } + }}, + ($place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { *((&$place as *const *const $t) as *const NonNull<$t>) } + }}, +} + +/// An iterator that moves out of a vector. +/// +/// This `struct` is created by the `into_iter` method on [`Vec`](super::Vec) +/// (provided by the [`IntoIterator`] trait). +/// +/// # Example +/// +/// ``` +/// let v = vec![0, 1, 2]; +/// let iter: std::vec::IntoIter<_> = v.into_iter(); +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_insignificant_dtor] +pub struct IntoIter< + T, + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] A: Allocator = Global, +> { + pub(super) buf: NonNull, + pub(super) phantom: PhantomData, + pub(super) cap: usize, + // the drop impl reconstructs a RawVec from buf, cap and alloc + // to avoid dropping the allocator twice we need to wrap it into ManuallyDrop + pub(super) alloc: ManuallyDrop, + pub(super) ptr: NonNull, + /// If T is a ZST, this is actually ptr+len. This encoding is picked so that + /// ptr == end is a quick test for the Iterator being empty, that works + /// for both ZST and non-ZST. + /// For non-ZSTs the pointer is treated as `NonNull` + pub(super) end: *const T, +} + +/*@ + +lem wrapping_sub_usize_zero(a: usize, b: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX; + ens (std::num::wrapping_sub_usize(a, b) == 0) == (a == b); +{ +} + +lem wrapping_sub_usize_dec(a: usize, b: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX &*& a != b; + ens std::num::wrapping_sub_usize(std::num::wrapping_sub_usize(a, 1), b) == std::num::wrapping_sub_usize(a, b) - 1; +{ +} + +lem wrapping_sub_usize_sub(a: usize, b: usize, n: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX &*& 0 <= n &*& n <= std::num::wrapping_sub_usize(a, b); + ens std::num::wrapping_sub_usize(std::num::wrapping_sub_usize(a, n), b) == std::num::wrapping_sub_usize(a, b) - n; +{ +} + +lem foreach_own_send(t0: thread_id_t, t1: thread_id_t) + req foreach(?xs, own::(t0)) &*& type_interp::() &*& is_Send(typeid(T)) == true; + ens foreach(xs, own::(t1)) &*& type_interp::(); +{ + open foreach(xs, own::(t0)); + match xs { + nil => {} + cons(x, xs0) => { + open own::(t0)(x); + Send::send::(t0, t1, x); + close own::(t1)(x); + foreach_own_send::(t0, t1); + } + } + close foreach(xs, own::(t1)); +} + +lem array_at_lft_own_mono(t: thread_id_t, k: lifetime_t, p: *T0, n: usize) + req array_at_lft::(k, p, n, ?elems) &*& foreach(elems, own::(t)) &*& + type_interp::() &*& type_interp::() &*& + is_subtype_of::() == true &*& + std::mem::size_of::() == std::mem::size_of::() &*& + std::mem::align_of::() == std::mem::align_of::(); + ens array_at_lft::(k, p as *T1, n, ?elems1) &*& foreach(elems1, own::(t)) &*& + type_interp::() &*& type_interp::(); +{ + open array_at_lft::(k, p, n, elems); + open foreach(elems, own::(t)); + match elems { + nil => { + close array_at_lft::(k, p as *T1, 0, nil); + close foreach(nil, own::(t)); + } + cons(x, xs0) => { + open points_to_at_lft::(k, p, x); + to_u8s__at_lft::(p); + assert array_at_lft_(k, p as *u8, std::mem::size_of::(), ?bs); + from_u8s__at_lft::(p as *T1); + // Rust subtyping (`T0 <: T1`) only weakens lifetimes and preserves byte + // representation (https://github.com/verifast/verifast/issues/610). + let x1 = upcast::(x); + assume(of_u8s_::(bs) == some(x1)); + close points_to_at_lft::(k, p as *T1, x1); + open own::(t)(x); + own_mono::(t, x); + close own::(t)(x1); + array_at_lft_own_mono::(t, k, p + 1, n - 1); + assert array_at_lft::(k, (p + 1) as *T1, n - 1, ?xs1); + assert ((p + 1) as *T1) == ((p as *T1) + 1); + close array_at_lft::(k, p as *T1, n, cons(x1, xs1)); + close foreach(cons(x1, xs1), own::(t)); + } + } +} + +lem foreach_snoc_inv(xs: list, x: T, p: pred(T)) + req foreach(append(xs, [x]), p); + ens foreach(xs, p) &*& p(x); +{ + match xs { + nil => { + open foreach([x], p); + open foreach(nil, p); + close foreach(nil, p); + } + cons(h, t) => { + open foreach(cons(h, append(t, [x])), p); + foreach_snoc_inv(t, x, p); + close foreach(cons(h, t), p); + } + } +} + +lem list_split_last(xs: list) + req length(xs) > 0; + ens xs == append(take(length(xs) - 1, xs), [nth(length(xs) - 1, xs)]) &*& length(take(length(xs) - 1, xs)) == length(xs) - 1; +{ + match xs { + nil => {} + cons(h, t) => { + if length(t) == 0 { + match t { + nil => {} + cons(h1, t1) => {} + } + } else { + list_split_last(t); + } + } + } +} + +pred IntoIter_non_zst_buf(t: thread_id_t, buf: NonNull, cap: usize, alloc_id: alloc_id_t, ptr: NonNull, end: *T, adv: usize, end_idx: usize, elems: list) = + 0 <= adv &*& adv <= end_idx &*& end_idx <= cap &*& + cap * std::mem::size_of::() <= isize::MAX &*& + if cap == 0 { + true + } else { + Layout::new::().repeat(cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, buf.as_ptr() as *u8, allocLayout) + } &*& + ptr.as_ptr() == buf.as_ptr() + adv &*& + end == buf.as_ptr() + end_idx &*& + end != 0 &*& pointer_within_limits(end) == true &*& + array_at_lft_(alloc_id.lft, buf.as_ptr(), adv, _) &*& + array_at_lft(alloc_id.lft, ptr.as_ptr(), end_idx - adv, elems) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, buf.as_ptr() + end_idx, cap - end_idx, _); + +pred >.own(t, it) = + Allocator(t, it.alloc, ?alloc_id) &*& + it.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(it.buf.as_ptr()) == true &*& + 0 <= (it.end as usize) &*& (it.end as usize) <= usize::MAX &*& + (it.end as pointer) == pointer_ctor((it.ptr.as_ptr() as pointer).provenance, it.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + it.ptr == it.buf &*& + array_at_lft(alloc_id.lft, it.ptr.as_ptr(), std::num::wrapping_sub_usize(it.end as usize, it.ptr.as_ptr() as usize), ?elems) &*& + foreach(elems, own::(t)) + } else { + IntoIter_non_zst_buf::(t, it.buf, it.cap, alloc_id, it.ptr, it.end, ?adv, ?end_idx, ?elems) + }; + +lem IntoIter_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Send(typeid(IntoIter)) == true &*& + IntoIter_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& + IntoIter_own::(t1, v); +{ + open >.own(t0, v); + assume(is_Send(typeid(T)) == true && is_Send(typeid(A)) == true); + std::alloc::Allocator_send(t1, v.alloc); + if std::mem::size_of::() == 0 { + foreach_own_send::(t0, t1); + } else { + open IntoIter_non_zst_buf::(t0, v.buf, v.cap, ?alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + foreach_own_send::(t0, t1); + close IntoIter_non_zst_buf::(t1, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + } + close >.own(t1, v); +} + +lem IntoIter_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + IntoIter_own::(?t, ?v) &*& + is_subtype_of::() == true &*& + is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + IntoIter_own::(t, IntoIter:: { + buf: upcast(v.buf), + cap: upcast(v.cap), + alloc: upcast(v.alloc), + ptr: upcast(v.ptr), + end: v.end as *T1, + }); +{ + open >.own(t, v); + assert Allocator(t, v.alloc, ?alloc_id); + std::alloc::Allocator_upcast::(v.alloc); + std::ptr::NonNull_upcast::(v.buf); + std::ptr::NonNull_upcast::(v.ptr); + std::ptr::NonNull_Sized_as_ptr(v.ptr); + assume( + std::mem::size_of::() == std::mem::size_of::() && + std::mem::align_of::() == std::mem::align_of::() && + Layout::new::() == Layout::new::() && + upcast::(v.cap) == v.cap + ); + if std::mem::size_of::() == 0 { + array_at_lft_own_mono::(t, alloc_id.lft, v.ptr.as_ptr(), std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + array_at_lft__to_u8s_at_lft_::(v.buf.as_ptr(), adv); + u8s_at_lft__to_array_at_lft_::(v.buf.as_ptr() as *T1, adv); + array_at_lft_own_mono::(t, alloc_id.lft, v.ptr.as_ptr(), end_idx - adv); + array_at_lft__to_u8s_at_lft_::(v.buf.as_ptr() + end_idx, v.cap - end_idx); + assert ((v.buf.as_ptr() + end_idx) as *u8) == (((v.buf.as_ptr() as *T1) + end_idx) as *u8); + u8s_at_lft__to_array_at_lft_::((v.buf.as_ptr() as *T1) + end_idx, v.cap - end_idx); + close IntoIter_non_zst_buf::(t, upcast(v.buf), upcast(v.cap), alloc_id, upcast(v.ptr), v.end as *T1, adv, end_idx, _); + } + close >.own(t, IntoIter:: { + buf: upcast(v.buf), + cap: upcast(v.cap), + alloc: upcast(v.alloc), + ptr: upcast(v.ptr), + end: v.end as *T1, + }); +} + +pred IntoIter_raw_buf(t: thread_id_t, it: IntoIter) = + Allocator(t, it.alloc, ?alloc_id) &*& + it.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(it.buf.as_ptr()) == true &*& + if std::mem::size_of::() == 0 { + true + } else { + it.cap * std::mem::size_of::() <= isize::MAX &*& + (if it.cap == 0 { + true + } else { + Layout::new::().repeat(it.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, it.buf.as_ptr() as *u8, allocLayout) + }) &*& + array_at_lft_(alloc_id.lft, it.buf.as_ptr(), it.cap, _) + }; + +lem IntoIter_own_to_raw_buf(t: thread_id_t, it: IntoIter) + req >.own(t, it); + ens IntoIter_raw_buf::(t, it); +{ + open >.own(t, it); + assert Allocator(t, it.alloc, ?alloc_id); + if std::mem::size_of::() == 0 { + assert array_at_lft(alloc_id.lft, it.ptr.as_ptr(), ?len, ?elems); + leak foreach(elems, own::(t)); + leak array_at_lft(alloc_id.lft, it.ptr.as_ptr(), len, elems); + } else { + open IntoIter_non_zst_buf::(t, it.buf, it.cap, alloc_id, it.ptr, it.end, ?adv, ?end_idx, ?elems); + leak foreach(elems, own::(t)); + array_at_lft_to_array_at_lft_::(it.ptr.as_ptr()); + array_at_lft__join::(it.buf.as_ptr() + adv); + array_at_lft__join::(it.buf.as_ptr()); + } + close IntoIter_raw_buf::(t, it); +} + +lem zst_array_at_lft_move(elems: list, k: lifetime_t, src: *T, dst: *T, n: usize) + req array_at_lft::(k, src, n, elems) &*& + std::mem::size_of::() == 0 &*& + dst as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(dst) == true; + ens array_at_lft::(k, dst, n, elems); +{ + open array_at_lft::(k, src, n, elems); + match elems { + nil => { + close array_at_lft::(k, dst, 0, nil); + } + cons(x, xs0) => { + open points_to_at_lft::(k, src, x); + to_u8s__at_lft::(src); + assert array_at_lft_(k, src as *u8, 0, ?bs); + open array_at_lft_(k, src as *u8, 0, bs); + close array_at_lft_::(k, dst as *u8, 0, nil); + from_u8s__at_lft::(dst); + close points_to_at_lft::(k, dst, x); + zst_array_at_lft_move::(xs0, k, src + 1, dst + 1, n - 1); + close array_at_lft::(k, dst, n, cons(x, xs0)); + } + } +} + +lem close_slice_own_from_foreach(t: thread_id_t, elems: list) + req foreach(elems, own::(t)); + ens <[T]>.own(t, slice_of_elems(elems)); +{ + close <[T]>.own(t, slice_of_elems(elems)); +} + +pred_ctor IntoIter_shared_val(l: *IntoIter, v: IntoIter)(;) = + (*l).buf |-> v.buf &*& + (*l).cap |-> v.cap &*& + (*l).ptr |-> v.ptr &*& + (*l).end |-> v.end &*& + struct_IntoIter_padding::(l); + +pred_ctor IntoIter_shared_range(alloc_lft: lifetime_t, ptr: *T, len: usize, elems: list)(;) = + array_at_lft::(alloc_lft, ptr, len, elems); + +pred IntoIter_share_(k: lifetime_t, t: thread_id_t, l: *IntoIter, len: usize) = + [_]std::alloc::Allocator_share(k, t, &(*l).alloc, ?alloc_id) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + [_]exists::>(?v) &*& + 0 <= len &*& len <= usize::MAX &*& + [_]frac_borrow(k, IntoIter_shared_val::(l, v)) &*& + pointer_within_limits(v.ptr.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) == len + } else { + v.end == v.ptr.as_ptr() + len &*& + v.end != 0 &*& pointer_within_limits(v.end) == true &*& + len * std::mem::size_of::() <= isize::MAX &*& + [_]exists::>(?elems) &*& + [_]frac_borrow(k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)) + }; + +pred >.share(k, t, l) = + [_]IntoIter_share_::(k, t, l, ?len); + +lem IntoIter_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *IntoIter) + req type_interp::() &*& type_interp::() &*& + lifetime_inclusion(k1, k) == true &*& [_]IntoIter_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]IntoIter_share::(k1, t, l); +{ + open IntoIter_share::(k, t, l); + open IntoIter_share_::(k, t, l, ?len); + std::alloc::Allocator_share_mono::(k, k1, t, &(*l).alloc); + assert [_]std::alloc::Allocator_share(k1, t, &(*l).alloc, ?alloc_id); + assert [_]exists::>(?v); + frac_borrow_mono(k, k1, IntoIter_shared_val::(l, v)); + if std::mem::size_of::() != 0 { + assert [_]exists::>(?elems); + frac_borrow_mono(k, k1, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + } + close IntoIter_share_::(k1, t, l, len); + leak IntoIter_share_::(k1, t, l, len); + close IntoIter_share::(k1, t, l); + leak IntoIter_share::(k1, t, l); +} + +lem IntoIter_share_full(k: lifetime_t, t: thread_id_t, l: *IntoIter) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + full_borrow(k, IntoIter_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + [_]IntoIter_share::(k, t, l) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong_m(k, IntoIter_full_borrow_content::(t, l), q); + open IntoIter_full_borrow_content::(t, l)(); + assert *l |-> ?v; + open_points_to(l); + open >.own(t, v); + assert Allocator(t, v.alloc, ?alloc_id); + std::alloc::Allocator_inv(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close IntoIter_shared_val::(l, v)(); + if std::mem::size_of::() == 0 { + let len_z = std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize); + assert array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len_z, ?elems_z); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + v.ptr == v.buf &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len_z, elems_z) &*& + foreach(elems_z, own::(t)); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)), + klong, + IntoIter_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + assert (*l).alloc |-> ?a1; + close >.own(t, IntoIter:: { buf: v.buf, cap: v.cap, alloc: a1, ptr: v.ptr, end: v.end }); + close IntoIter_full_borrow_content::(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m( + klong, + IntoIter_full_borrow_content::(t, l), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)) + ); + full_borrow_split_m(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + } + } + close exists::>(v); + leak exists::>(v); + close IntoIter_share_::(k, t, l, len_z); + leak IntoIter_share_::(k, t, l, len_z); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + let len_nz = end_idx - adv; + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(len_nz, v.cap, std::mem::size_of::()); + close IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)(); + close sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& pointer_within_limits(v.end) == true &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + 0 <= adv &*& adv <= end_idx &*& end_idx <= v.cap &*& + v.cap * std::mem::size_of::() <= isize::MAX &*& + (if v.cap == 0 { + true + } else { + Layout::new::().repeat(v.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, v.buf.as_ptr() as *u8, allocLayout) + }) &*& + v.ptr.as_ptr() == v.buf.as_ptr() + adv &*& + v.end == v.buf.as_ptr() + end_idx &*& + v.end != 0 &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr(), adv, _) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr() + end_idx, v.cap - end_idx, _); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))), + klong, + IntoIter_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)))(); + open sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + open IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)(); + assert (*l).alloc |-> ?a1; + close IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + close >.own(t, IntoIter:: { buf: v.buf, cap: v.cap, alloc: a1, ptr: v.ptr, end: v.end }); + close IntoIter_full_borrow_content::(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m( + klong, + IntoIter_full_borrow_content::(t, l), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))) + ); + full_borrow_split_m(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))); + full_borrow_split_m(klong, IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + full_borrow_into_frac_m(klong, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + frac_borrow_mono(klong, k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + } + } + close exists::>(v); + leak exists::>(v); + close exists::>(elems); + leak exists::>(elems); + close IntoIter_share_::(k, t, l, len_nz); + leak IntoIter_share_::(k, t, l, len_nz); + } + close IntoIter_share::(k, t, l); + leak IntoIter_share::(k, t, l); +} + +pred_ctor IntoIter_val_fbc(t: thread_id_t, l: *IntoIter, v: IntoIter, alloc_id: alloc_id_t, len: usize)() = + (*l).buf |-> v.buf &*& + (*l).cap |-> v.cap &*& + (*l).ptr |-> v.ptr &*& + (*l).end |-> v.end &*& + struct_IntoIter_padding::(l) &*& + (*l).alloc |-> ?a &*& + Allocator(t, a, alloc_id) &*& + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + v.ptr == v.buf &*& + len == std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, ?elems) &*& + foreach(elems, own::(t)) + } else { + IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems) &*& + len == end_idx - adv + }; + +lem IntoIter_share_val_fbc(k: lifetime_t, t: thread_id_t, l: *IntoIter, v: IntoIter, alloc_id: alloc_id_t, len: usize) + nonghost_callers_only + req full_borrow(k, IntoIter_val_fbc::(t, l, v, alloc_id, len)) &*& [?q]lifetime_token(k); + ens [_]IntoIter_share_::(k, t, l, len) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong(k, IntoIter_val_fbc::(t, l, v, alloc_id, len), q); + open IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + std::alloc::Allocator_inv(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close IntoIter_shared_val::(l, v)(); + if std::mem::size_of::() == 0 { + assert array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, ?elems_z); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + v.ptr == v.buf &*& + len == std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, elems_z) &*& + foreach(elems_z, own::(t)); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)), + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + close IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)) + ); + full_borrow_split(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + } + } + close exists::>(v); + leak exists::>(v); + close IntoIter_share_::(k, t, l, len); + leak IntoIter_share_::(k, t, l, len); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(len, v.cap, std::mem::size_of::()); + close IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + close sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& pointer_within_limits(v.end) == true &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + 0 <= adv &*& adv <= end_idx &*& end_idx <= v.cap &*& + len == end_idx - adv &*& + v.cap * std::mem::size_of::() <= isize::MAX &*& + (if v.cap == 0 { + true + } else { + Layout::new::().repeat(v.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, v.buf.as_ptr() as *u8, allocLayout) + }) &*& + v.ptr.as_ptr() == v.buf.as_ptr() + adv &*& + v.end == v.buf.as_ptr() + end_idx &*& + v.end != 0 &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr(), adv, _) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr() + end_idx, v.cap - end_idx, _); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))), + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)))(); + open sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + open IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + close IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + close IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))) + ); + full_borrow_split(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))); + full_borrow_split(klong, IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + full_borrow_into_frac(klong, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + frac_borrow_mono(klong, k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + } + } + close exists::>(v); + leak exists::>(v); + close exists::>(elems); + leak exists::>(elems); + close IntoIter_share_::(k, t, l, len); + leak IntoIter_share_::(k, t, l, len); + } +} + +lem IntoIter_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Sync(typeid(IntoIter)) == true &*& + [_]IntoIter_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& + [_]IntoIter_share::(k, t1, l); +{ + open IntoIter_share::(k, t0, l); + open IntoIter_share_::(k, t0, l, ?len); + assume(is_Sync(typeid(A)) == true); + std::alloc::Allocator_sync::(t1); + close IntoIter_share_::(k, t1, l, len); + leak IntoIter_share_::(k, t1, l, len); + close IntoIter_share::(k, t1, l); + leak IntoIter_share::(k, t1, l); +} + +lem init_ref_IntoIter(p: *IntoIter) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + ref_init_perm(p, ?x) &*& [_]IntoIter_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + [q]lifetime_token(k) &*& [_]IntoIter_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open IntoIter_share::(k, t, x); + open IntoIter_share_::(k, t, x, ?len); + assert [_]exists::>(?v); + open_ref_init_perm_IntoIter(p); + std::alloc::init_ref_Allocator_share_m(k, t, &(*p).alloc); + frac_borrow_sep(k, IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)); + let klong = open_frac_borrow_strong_m(k, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), q); + open [?f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + open [f]IntoIter_shared_val::(x, v)(); + open [f]ref_initialized_::(&(*p).alloc)(); + std::ptr::init_ref_NonNull(&(*p).buf, 1/2); + init_ref_readonly(&(*p).cap, 1/2); + std::ptr::init_ref_NonNull(&(*p).ptr, 1/2); + init_ref_readonly(&(*p).end, 1/2); + init_ref_padding_IntoIter(p, 1/2); + { + pred P() = ref_padding_initialized(p) &*& ref_initialized(&(*p).buf) &*& ref_initialized(&(*p).cap) &*& ref_initialized(&(*p).ptr) &*& ref_initialized(&(*p).end); + close [1 - f/2]P(); + close_ref_initialized_IntoIter(p); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*p).alloc) &*& + ref_padding_end_token(p, x, f/2) &*& [f/2]struct_IntoIter_padding::(x) &*& [1 - f/2]ref_padding_initialized(p) &*& + ref_end_token(&(*p).buf, &(*x).buf, f/2) &*& [f/2]((*x).buf |-> v.buf) &*& [1 - f/2]ref_initialized(&(*p).buf) &*& + ref_readonly_end_token(&(*p).cap, &(*x).cap, f/2) &*& [f/2]((*x).cap |-> v.cap) &*& [1 - f/2]ref_initialized(&(*p).cap) &*& + ref_end_token(&(*p).ptr, &(*x).ptr, f/2) &*& [f/2]((*x).ptr |-> v.ptr) &*& [1 - f/2]ref_initialized(&(*p).ptr) &*& + ref_readonly_end_token(&(*p).end, &(*x).end, f/2) &*& [f/2]((*x).end |-> v.end) &*& [1 - f/2]ref_initialized(&(*p).end); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))), + klong, + f, + sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)) + )() { + open scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + open sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + open ref_initialized_::>(p)(); + open IntoIter_shared_val::(p, v)(); + open_ref_initialized_IntoIter(p); + open Ctx(); + std::ptr::end_ref_NonNull(&(*p).buf); + end_ref_readonly(&(*p).cap); + std::ptr::end_ref_NonNull(&(*p).ptr); + end_ref_readonly(&(*p).end); + end_ref_padding_IntoIter(p); + close [f]IntoIter_shared_val::(x, v)(); + close [f]ref_initialized_::(&(*p).alloc)(); + close [f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(p)(); + close [f/2]IntoIter_shared_val::(p, v)(); + close [f/2]sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + close scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))); + frac_borrow_split(k, ref_initialized_(p), IntoIter_shared_val::(p, v)); + } + } + close IntoIter_share_::(k, t, p, len); + leak IntoIter_share_::(k, t, p, len); + close IntoIter_share::(k, t, p); + leak IntoIter_share::(k, t, p); +} + +lem init_ref_IntoIter_share_(p: *IntoIter) + nonghost_callers_only + req ref_init_perm(p, ?x) &*& [_]IntoIter_share_::(?k, ?t, x, ?len) &*& [?q]lifetime_token(k); + ens [q]lifetime_token(k) &*& [_]IntoIter_share_::(k, t, p, len) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open IntoIter_share_::(k, t, x, len); + assert [_]exists::>(?v); + open_ref_init_perm_IntoIter(p); + std::alloc::init_ref_Allocator_share(k, t, &(*p).alloc); + frac_borrow_sep(k, IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)); + let klong = open_frac_borrow_strong(k, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), q); + open [?f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + open [f]IntoIter_shared_val::(x, v)(); + open [f]ref_initialized_::(&(*p).alloc)(); + std::ptr::init_ref_NonNull(&(*p).buf, 1/2); + init_ref_readonly(&(*p).cap, 1/2); + std::ptr::init_ref_NonNull(&(*p).ptr, 1/2); + init_ref_readonly(&(*p).end, 1/2); + init_ref_padding_IntoIter(p, 1/2); + { + pred P() = ref_padding_initialized(p) &*& ref_initialized(&(*p).buf) &*& ref_initialized(&(*p).cap) &*& ref_initialized(&(*p).ptr) &*& ref_initialized(&(*p).end); + close [1 - f/2]P(); + close_ref_initialized_IntoIter(p); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*p).alloc) &*& + ref_padding_end_token(p, x, f/2) &*& [f/2]struct_IntoIter_padding::(x) &*& [1 - f/2]ref_padding_initialized(p) &*& + ref_end_token(&(*p).buf, &(*x).buf, f/2) &*& [f/2]((*x).buf |-> v.buf) &*& [1 - f/2]ref_initialized(&(*p).buf) &*& + ref_readonly_end_token(&(*p).cap, &(*x).cap, f/2) &*& [f/2]((*x).cap |-> v.cap) &*& [1 - f/2]ref_initialized(&(*p).cap) &*& + ref_end_token(&(*p).ptr, &(*x).ptr, f/2) &*& [f/2]((*x).ptr |-> v.ptr) &*& [1 - f/2]ref_initialized(&(*p).ptr) &*& + ref_readonly_end_token(&(*p).end, &(*x).end, f/2) &*& [f/2]((*x).end |-> v.end) &*& [1 - f/2]ref_initialized(&(*p).end); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))), + klong, + f, + sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)) + )() { + open scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + open sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + open ref_initialized_::>(p)(); + open IntoIter_shared_val::(p, v)(); + open_ref_initialized_IntoIter(p); + open Ctx(); + std::ptr::end_ref_NonNull(&(*p).buf); + end_ref_readonly(&(*p).cap); + std::ptr::end_ref_NonNull(&(*p).ptr); + end_ref_readonly(&(*p).end); + end_ref_padding_IntoIter(p); + close [f]IntoIter_shared_val::(x, v)(); + close [f]ref_initialized_::(&(*p).alloc)(); + close [f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(p)(); + close [f/2]IntoIter_shared_val::(p, v)(); + close [f/2]sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + close scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + close_frac_borrow_strong(klong, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_into_frac(k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))); + frac_borrow_split(k, ref_initialized_(p), IntoIter_shared_val::(p, v)); + } + } + close IntoIter_share_::(k, t, p, len); + leak IntoIter_share_::(k, t, p, len); +} + +@*/ + +// 1-line wrappers for core::mem / core::ptr primitives absent from VeriFast 26.10's std/lib.rsspec. +// Every wrapper is automatically inlined by `refinement-checker` against original/into_iter.rs. +unsafe fn manually_drop_take__VeriFast_wrapper(slot: &mut ManuallyDrop) -> T +//@ req *slot |-> ?v; +//@ ens *slot |-?-> _ &*& result == v; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { ManuallyDrop::take(slot) } +} + +fn const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(p: *const T) -> *const T +//@ req true; +//@ ens (result as pointer) == pointer_ctor((p as pointer).provenance, std::num::wrapping_sub_usize(p as usize, 1), (p as pointer).metadata) &*& 0 <= (result as usize) &*& (result as usize) <= usize::MAX; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.wrapping_byte_sub(1) +} + +fn const_ptr_cast_mut__VeriFast_wrapper(p: *const T) -> *mut T +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.cast_mut() +} + +fn const_ptr_cast_t_mut__VeriFast_wrapper(p: *const T) -> *mut T +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.cast::().cast_mut() +} + +unsafe fn ptr_ne_end__VeriFast_wrapper(ptr: &NonNull, end: &*const T) -> bool +//@ req [?f1](*ptr |-> ?p) &*& [?f2](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true &*& (e as pointer) == pointer_ctor((p.as_ptr() as pointer).provenance, e as usize, pointer_metadata_none); +//@ ens [f1](*ptr |-> p) &*& [f2](*end |-> e) &*& result == (p.as_ptr() != e); +//@ on_unwind_ens false; +//@ assume_correct +{ + *ptr != unsafe { *((end as *const *const T) as *const NonNull) } +} + +unsafe fn ptr_eq_end__VeriFast_wrapper(ptr: &NonNull, end: &*const T) -> bool +//@ req [?f1](*ptr |-> ?p) &*& [?f2](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true &*& (e as pointer) == pointer_ctor((p.as_ptr() as pointer).provenance, e as usize, pointer_metadata_none); +//@ ens [f1](*ptr |-> p) &*& [f2](*end |-> e) &*& result == (p.as_ptr() == e); +//@ on_unwind_ens false; +//@ assume_correct +{ + *ptr == unsafe { *((end as *const *const T) as *const NonNull) } +} + +/*@ +pred LiveSlot(p: *T, k: lifetime_t, q: real, f: real, ov: option) = + [q]lifetime_token(k) &*& + match ov { + some(v) => [f]points_to_at_lft::(k, p, v), + none => [f]points_to_at_lft_::(k, p, _) + }; + +pred LiveRange(p: *T, n: usize, k: lifetime_t, q: real, f: real, elems: list) = + if n == 0 { + true + } else { + [q]lifetime_token(k) &*& [f]array_at_lft::(k, p, n, elems) + }; +@*/ + +unsafe fn non_null_add_1__VeriFast_wrapper(p: NonNull) -> NonNull +/*@ +req std::mem::size_of::() > 0 &*& std::mem::size_of::() <= isize::MAX &*& + pointer_within_limits(p.as_ptr() + 1) == true &*& (p.as_ptr() + 1) != 0 &*& + LiveSlot::(p.as_ptr(), ?k, ?q, ?f, ?ov); +@*/ +/*@ +ens LiveSlot::(p.as_ptr(), k, q, f, ov) &*& + result.as_ptr() == p.as_ptr() + 1; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.add(1) } +} + +unsafe fn exact_size_len__VeriFast_wrapper<'a, 'b, T, A: Allocator>(it: &'a &'b mut IntoIter) -> usize +/*@ +req thread_token(?t) &*& + [?f]points_to::<&'b mut IntoIter>(it, ?p) &*& + [_]IntoIter_share_::(?k, t, p, ?len) &*& + [?q]lifetime_token(k); +@*/ +/*@ +ens thread_token(t) &*& + [f]points_to::<&'b mut IntoIter>(it, p) &*& + [q]lifetime_token(k) &*& + result == len; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + it.len() +} + +fn usize_min__VeriFast_wrapper(a: usize, b: usize) -> usize +//@ req true; +//@ ens result == (if a <= b { a } else { b }); +//@ on_unwind_ens false; +//@ assume_correct +{ + a.min(b) +} + +unsafe fn non_null_dangling__VeriFast_wrapper() -> NonNull +//@ req true; +//@ ens result.as_ptr() as usize == std::mem::align_of::() &*& result.as_ptr() as usize % std::mem::align_of::() == 0 &*& pointer_within_limits(result.as_ptr()) == true; +//@ on_unwind_ens false; +//@ assume_correct +{ + ptr::NonNull::::dangling() +} + +fn const_ptr_wrapping_byte_sub__VeriFast_wrapper(p: *const T, count: usize) -> *const T +//@ req true; +//@ ens (result as pointer) == pointer_ctor((p as pointer).provenance, std::num::wrapping_sub_usize(p as usize, count), (p as pointer).metadata) &*& 0 <= (result as usize) &*& (result as usize) <= usize::MAX; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.wrapping_byte_sub(count) +} + +unsafe fn non_null_add__VeriFast_wrapper(p: NonNull, count: usize) -> NonNull +/*@ +req std::mem::size_of::() > 0 &*& 0 <= count &*& count * std::mem::size_of::() <= isize::MAX &*& + pointer_within_limits(p.as_ptr() + count) == true &*& (p.as_ptr() + count) != 0 &*& + LiveRange::(p.as_ptr(), count, ?k, ?q, ?f, ?elems); +@*/ +/*@ +ens LiveRange::(p.as_ptr(), count, k, q, f, elems) &*& + result.as_ptr() == p.as_ptr() + count; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.add(count) } +} + +unsafe fn non_zero_rem__VeriFast_wrapper(rem: usize) -> Result<(), NonZero> +//@ req thread_token(?t); +//@ ens thread_token(t) &*& >>.own(t, result); +//@ on_unwind_ens false; +//@ assume_correct +{ + NonZero::new(rem).map_or(Ok(()), Err) +} + +fn call_fold__VeriFast_wrapper B>(f: &mut F, accum: B, item: T) -> B +//@ req thread_token(?t) &*& *f |-> ?f0 &*& .own(t, f0) &*& .own(t, accum) &*& .own(t, item); +//@ ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& .own(t, result); +//@ on_unwind_ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1); +//@ assume_correct +{ + f(accum, item) +} + +fn const_ptr_addr__VeriFast_wrapper(p: *const T) -> usize +//@ req true; +//@ ens result == p as usize; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.addr() +} + +fn mut_ptr_addr__VeriFast_wrapper(p: *mut T) -> usize +//@ req true; +//@ ens result == p as usize; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.addr() +} + +unsafe fn non_null_from_end__VeriFast_wrapper(end: &*const T) -> NonNull +//@ req [?f](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true; +//@ ens [f](*end |-> e) &*& result.as_ptr() == e; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { *((end as *const *const T) as *const NonNull) } +} + +unsafe fn non_null_offset_from_unsigned__VeriFast_wrapper(end: NonNull, ptr: NonNull) -> usize +/*@ +req std::mem::size_of::() > 0 &*& + LiveRange::(ptr.as_ptr(), ?len, ?k, ?q, ?f, ?elems) &*& + end.as_ptr() == ptr.as_ptr() + len &*& + 0 <= len &*& len * std::mem::size_of::() <= isize::MAX; +@*/ +/*@ +ens LiveRange::(ptr.as_ptr(), len, k, q, f, elems) &*& + result == len; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { end.offset_from_unsigned(ptr) } +} + +// Verified check that `core::iter::ExactSizeIterator::len`'s default implementation +// (`let (lower, upper) = self.size_hint(); assert_eq!(upper, Some(lower)); lower`) +// computes the exact remaining length `len` exposed in `IntoIter_share_`. +fn verify_exact_size_len_from_size_hint__VeriFast_wrapper(it: &IntoIter) -> usize +//@ req thread_token(?t) &*& [?q]lifetime_token(?k) &*& [_]IntoIter_share_::(k, t, it, ?len); +//@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result == len; +/*@ +safety_proof { + open >.share(?k, _t, it); + call(); +} +@*/ +{ + //@ let it_r = precreate_ref(it); + //@ init_ref_IntoIter_share_(it_r); + //@ open_frac_borrow(k, ref_initialized_(it_r), q/2); + //@ open [?f]ref_initialized_::>(it_r)(); + let (lower, upper) = unsafe { &*(it as *const IntoIter) }.size_hint(); + //@ close [f]ref_initialized_::>(it_r)(); + //@ close_frac_borrow(f, ref_initialized_(it_r)); + //@ assert upper == Some(len); + lower +} + +unsafe fn non_null_read__VeriFast_wrapper(p: NonNull) -> T +//@ req *(p.as_ptr()) |-> ?v &*& p.as_ptr() as usize % std::mem::align_of::() == 0; +//@ ens *(p.as_ptr()) |-?-> _ &*& result == v; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.read() } +} + +// Manually mirroring what `Vec` has, +// because otherwise we get `T: RefUnwindSafe` from `NonNull`. +#[stable(feature = "catch_unwind", since = "1.9.0")] +impl UnwindSafe for IntoIter {} + +#[stable(feature = "vec_intoiter_debug", since = "1.13.0")] +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("IntoIter").field(&self.as_slice()).finish() + } +} + +impl IntoIter { + /// Returns the remaining items of this iterator as a slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// let _ = into_iter.next().unwrap(); + /// assert_eq!(into_iter.as_slice(), &['b', 'c']); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_slice(&self) -> &[T] { + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len()) } + } + + /// Returns the remaining items of this iterator as a mutable slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// into_iter.as_mut_slice()[2] = 'z'; + /// assert_eq!(into_iter.next().unwrap(), 'a'); + /// assert_eq!(into_iter.next().unwrap(), 'b'); + /// assert_eq!(into_iter.next().unwrap(), 'z'); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_mut_slice(&mut self) -> &mut [T] { + // ignore-tidy-undocumented-unsafe + unsafe { &mut *self.as_raw_mut_slice() } + } + + /// Returns a reference to the underlying allocator. + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] + #[inline] + pub fn allocator(&self) -> &A { + &self.alloc + } + + fn as_raw_mut_slice(&mut self) -> *mut [T] { + self.ptr.as_ptr().cast_slice(self.len()) + } + + /// Drops remaining elements and relinquishes the backing allocation. + /// + /// This method guarantees it won't panic before relinquishing the backing + /// allocation. + /// + /// This is roughly equivalent to the following, but more efficient + /// + /// ``` + /// # let mut vec = Vec::::with_capacity(10); + /// # let ptr = vec.as_mut_ptr(); + /// # let mut into_iter = vec.into_iter(); + /// let mut into_iter = std::mem::replace(&mut into_iter, Vec::new().into_iter()); + /// (&mut into_iter).for_each(drop); + /// std::mem::forget(into_iter); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # drop(unsafe { Vec::::from_raw_parts(ptr, 0, 10) }); + /// ``` + /// + /// This method is used by in-place iteration, refer to the vec::in_place_collect + /// documentation for an overview. + #[cfg(not(no_global_oom_handling))] + pub(super) fn forget_allocation_drop_remaining(&mut self) { + let remaining = self.as_raw_mut_slice(); + + // overwrite the individual fields instead of creating a new + // struct and then overwriting &mut self. + // this creates less assembly + self.cap = 0; + self.buf = RawVec::new().non_null(); + self.ptr = self.buf; + self.end = self.buf.as_ptr(); + + // Dropping the remaining elements can panic, so this needs to be + // done only after updating the other fields. + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(remaining); + } + } + + /// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed. + /// + /// This method does not consume `self`, and leaves deallocation to `impl Drop for IntoIter`. + /// If consuming `self` is possible, consider calling + /// [`Self::forget_remaining_elements_and_dealloc()`] instead. + pub(crate) fn forget_remaining_elements(&mut self) + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& self1.end == self1.ptr.as_ptr(); + { + //@ open_points_to(self); + //@ open >.own(t, self0); + // For the ZST case, it is crucial that we mutate `end` here, not `ptr`. + // `ptr` must stay aligned, while `end` may be unaligned. + self.end = self.ptr.as_ptr(); + /*@ { + std::ptr::NonNull_Sized_as_ptr(self0.ptr); + if std::mem::size_of::() == 0 { + assert array_at_lft(?k, self0.ptr.as_ptr(), ?len, ?elems); + leak foreach(elems, own::(t)); + leak array_at_lft(k, self0.ptr.as_ptr(), len, elems); + close array_at_lft::(k, self0.ptr.as_ptr(), 0, nil); + close foreach(nil, own::(t)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, ?alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + leak foreach(elems, own::(t)); + array_at_lft_to_array_at_lft_::(self0.ptr.as_ptr()); + array_at_lft__join::(self0.buf.as_ptr() + adv); + close array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), 0, nil); + close foreach(nil, own::(t)); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.ptr.as_ptr(), adv, adv, nil); + } + close_points_to(self); + close >.own(t, *self); + } @*/ + } + + /// Forgets to Drop the remaining elements and frees the backing allocation. + /// Consuming version of [`Self::forget_remaining_elements()`]. + /// + /// This can be used in place of `drop(self)` when `self` is known to be exhausted, + /// to avoid producing a needless `drop_in_place::<[T]>()`. + #[inline] + pub(crate) fn forget_remaining_elements_and_dealloc(self) + //@ req thread_token(?t) &*& t == currentThread &*& >.own(t, self); + //@ ens thread_token(t); + { + //@ IntoIter_own_to_raw_buf::(t, self); + let mut this = ManuallyDrop::new(self); + // SAFETY: `this` is in ManuallyDrop, so it will not be double-freed. + unsafe { + this.dealloc_only(); + } + } + + /// Frees the allocation, without checking or dropping anything else. + /// + /// The safe version of this method is [`Self::forget_remaining_elements_and_dealloc()`]. + /// This function exists only to share code between that method and the `impl Drop`. + /// + /// # Safety + /// + /// This function must only be called with an [`IntoIter`] that is not going to be dropped + /// or otherwise used in any way, either because it is being forgotten or because its `Drop` + /// is already executing; otherwise a double-free will occur, and possibly a read from freed + /// memory if there are any remaining elements. + #[inline] + unsafe fn dealloc_only(&mut self) + //@ req thread_token(?t) &*& t == currentThread &*& *self |-> ?self0 &*& IntoIter_raw_buf::(t, self0); + //@ ens thread_token(t) &*& (*self).buf |-> _ &*& (*self).cap |-> _ &*& (*self).alloc |-?-> _ &*& (*self).ptr |-> _ &*& (*self).end |-> _ &*& struct_IntoIter_padding(self); + { + //@ open_points_to(self); + //@ open IntoIter_raw_buf::(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + // SAFETY: our caller promises not to touch `*self` again. + let alloc = unsafe { manually_drop_take__VeriFast_wrapper(&mut self.alloc) }; + /*@ + if std::mem::size_of::() != 0 { + std::alloc::Layout_inv(Layout::new::()); + if self0.cap != 0 { raw_vec::mul_zero(self0.cap, std::mem::size_of::()); } + } + @*/ + // SAFETY: We're using this to deallocate a preexisting `RawVec`. + { + let mut _rv = unsafe { RawVec::from_nonnull_in(self.buf, self.cap, alloc) }; + /*@ { + assert RawVec(t, ?rv_val, alloc_id, self0.buf.as_ptr(), ?cap_); + if std::mem::size_of::() == 0 { + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() as *u8, 0, nil); + u8s_at_lft__to_array_at_lft_::(self0.buf.as_ptr(), cap_); + } + RawVec_to_own(rv_val); + close_points_to(&_rv); + } @*/ + } + //@ assert points_to_::>(?rv_p, _); + //@ open_points_to_(rv_p); + //@ open_points_to_(&(*rv_p).inner); + } + + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn into_vecdeque(self) -> VecDeque { + // Keep our `Drop` impl from dropping the elements and the allocator + let mut this = ManuallyDrop::new(self); + + let buf = this.buf.as_ptr(); + let initialized = if T::IS_ZST || this.len() == 0 { + // All the pointers are the same for ZSTs, so it's fine to + // say that they're all at the beginning of the "allocation". + // For non-ZSTs, we have length 0, so we can choose the (empty) + // range to be at the start of the buffer. + // + // Due to `0` ≤ `this.len()` ≤ `this.cap`, the range is well-formed, + // and due to the argument above it spans exactly the elements of + // this iterator. Because `init.start` = `0`, it follows that either + // `init.start` < `cap` or `cap` = `init.start` = `0`; thus the range + // satisfies the requirements of `from_contiguous_raw_parts_in`. + 0..this.len() + } else { + // SAFETY: `this.ptr` and `this.end` are created via offsets of `this.buf`, + // so they point to the same allocation. We have `this.buf` ≤ `this.ptr` ≤ `this.end`, + // so this cannot wrap, and will produce a well-formed range that spans exactly + // the elements of this iterator. + // + // Additionally, due to `end ≤ buf + cap`, we have `init.start` ≤ `init.end` ≤ `cap`. + // Due to the length check above, `init.start < cap`, so the range satisfies the + // requirements of `from_contiguous_raw_parts_in`. + unsafe { this.ptr.offset_from_unsigned(this.buf)..this.end.offset_from_unsigned(buf) } + }; + + let cap = this.cap; + // SAFETY: `this` is forgotten afterwards, so we can move out the allocator. + let alloc = unsafe { ManuallyDrop::take(&mut this.alloc) }; + + // SAFETY: This allocation originally came from a `Vec`, so it satisfies all + // requirements for the `buf` pointer with capacity `cap` allocated in `alloc`. + // Correctness of `initialized` was shown above. + unsafe { VecDeque::from_contiguous_raw_parts_in(buf, initialized, cap, alloc) } + } +} + +#[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")] +impl AsRef<[T]> for IntoIter { + fn as_ref(&self) -> &[T] { + self.as_slice() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for IntoIter {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for IntoIter {} + +// Loop-invariant predicates for `IntoIter::fold` and `IntoIter::try_fold`. +// Marked `#[inline(always)]` and written with pure intrinsics and `const { ... }` +// blocks rather than method calls (e.g. `NonNull::as_ptr` / `pointer::addr` / +// non-const `mem::size_of`) so Kani's loop-contract lowering evaluates them +// inline as side-effect-free CBMC expressions without emitting nondeterministic +// helper calls (https://github.com/model-checking/kani/issues/4796). +// `self.alloc` is untouched by either loop and is preserved across loop +// contracts (verified with both `TrackAlloc` and non-ZST `StatefulAlloc`). +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, and `usize` have identical layout (thin pointer width); + // these casts are side-effect-free re-interpretations for CBMC's loop-invariant evaluator. + let (ptr_p, eptr_p, buf_p, ebuf_p, ptr_a, eptr_a, end_a, eend_a): ( + *const T, + *const T, + *const T, + *const T, + usize, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + core::intrinsics::transmute_unchecked(entry_end), + ) + }; + ptr_p == eptr_p + && buf_p == ebuf_p + && cap == entry_cap + && core::intrinsics::wrapping_sub(end_a, ptr_a) + <= core::intrinsics::wrapping_sub(eend_a, eptr_a) +} + +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_non_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, `*const u8`, and `usize` have identical thin-pointer + // layout; used to avoid method calls in CBMC loop-contract predicates (kani#4796). + let (buf_p, ebuf_p, ptr_p, eptr_u8, ptr_a, eptr_a, end_a): ( + *const T, + *const T, + *const T, + *const u8, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + ) + }; + let diff = core::intrinsics::wrapping_sub(ptr_a, eptr_a); + let span = core::intrinsics::wrapping_sub(end_a, eptr_a); + let sz = const { core::mem::size_of::() }; + let aligned = if const { core::mem::size_of::().is_power_of_two() } { + (diff & core::intrinsics::wrapping_sub(sz, 1)) == 0 + } else { + // Exact divisibility `diff % sz == 0` for any non-power-of-two `sz > 0` without a + // 64-bit integer division circuit: write `sz = odd * 2^tz` and compute the modular + // multiplicative inverse `odd_inv` (`odd * odd_inv == 1 mod 2^BITS`) at const time. + // Then `sz | diff` iff `2^tz | diff` and `(diff >> tz) * odd_inv <= usize::MAX / sz`. + let (tz, odd_inv, max_q) = const { + let s = core::mem::size_of::(); + if s == 0 { + (0u32, 1usize, 0usize) + } else { + let tz = s.trailing_zeros(); + let odd = s >> tz; + let mut inv: usize = 1; + let mut i = 0; + while i < 6 { + inv = inv.wrapping_mul(2usize.wrapping_sub(odd.wrapping_mul(inv))); + i += 1; + } + assert!(odd.wrapping_mul(inv) == 1); + (tz, inv, usize::MAX / s) + } + }; + let low_mask = core::intrinsics::wrapping_sub(1usize << tz, 1); + (diff & low_mask) == 0 && core::intrinsics::wrapping_mul(diff >> tz, odd_inv) <= max_q + }; + // SAFETY: `arith_offset` is wrapping (non-UB) pointer arithmetic; short-circuiting after + // `diff <= span && aligned` additionally guarantees `diff` stays within `[entry_ptr, end]`. + buf_p == ebuf_p + && cap == entry_cap + && end == entry_end + && diff <= span + && aligned + && ptr_p == unsafe { core::intrinsics::arith_offset(eptr_u8, diff as isize) as *const T } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Iterator for IntoIter { + type Item = T; + + #[inline] + fn next(&mut self) -> Option + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + //@ open_points_to(self); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(self0.ptr); + let ptr = if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut T { + /*@ { + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // `ptr` has to stay where it is to remain aligned, so we reduce the length by 1 by + // reducing the `end`. + //@ wrapping_sub_usize_zero(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(self0.end as usize, self0.ptr.as_ptr() as usize); + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + self.ptr + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let is_eq = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + if is_eq { + /*@ { + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv, end_idx, elems); + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + let old = self.ptr; + // ignore-tidy-undocumented-unsafe + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(1, self0.cap, std::mem::size_of::()); + //@ open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), end_idx - adv, elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?x0); + //@ points_to_at_lft_inv(self0.ptr.as_ptr()); + //@ let q_add = lifetime_token_trade(flft, 1/4, alloc_id.lft); + //@ close LiveSlot::(self0.ptr.as_ptr(), alloc_id.lft, q_add, 1, some(x0)); + self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(old) }; + //@ open LiveSlot::(self0.ptr.as_ptr(), alloc_id.lft, q_add, 1, some(x0)); + //@ lifetime_token_trade_back(q_add, alloc_id.lft); + old + }; + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + open foreach(elems_z, own::(t)); + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xz); + open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + open own::(t)(xz); + } else { + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xnz); + open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + open own::(t)(xnz); + } + } @*/ + // ignore-tidy-undocumented-unsafe + let res = Some(unsafe { non_null_read__VeriFast_wrapper(ptr) }); + /*@ { + close_points_to_at_lft_(self0.ptr.as_ptr()); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + if std::mem::size_of::() == 0 { + leak points_to_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), _); + } else { + // Re-pack consumed prefix [0..adv+1) + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv0, _); + assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + 1, ?rem0, ?elems_rest); + close array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr() + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr(), 1, _); + array_at_lft__join::(self0.buf.as_ptr()); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, (*self).ptr, self0.end, adv0 + 1, adv0 + 1 + rem0, elems_rest); + } + close_points_to(self); + close >.own(t, *self); + close >.own(t, res); + } @*/ + res + } + + #[inline] + fn size_hint(&self) -> (usize, Option) + //@ req thread_token(?t) &*& [_]IntoIter_share_::(?k, t, self, ?len) &*& [?q]lifetime_token(k); + //@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result.0 == len &*& result.1 == Some(len); + /*@ + safety_proof { + open >.share(?k, _t, self); + let r = call(); + close usize_own(_t, r.0); + close >.own(_t, r.1); + close usize_own(_t, r.0); + tuple_ext::close_tuple_2_own::>(_t, r); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ open IntoIter_share_::(k, t, self, len); + //@ assert [_]std::alloc::Allocator_share(k, t, &(*self).alloc, ?alloc_id); + //@ assert [_]exists::>(?v); + //@ open_frac_borrow(k, IntoIter_shared_val::(self, v), q/2); + //@ open [?f]IntoIter_shared_val::(self, v)(); + let exact = if T::IS_ZST { + let end_a = const_ptr_addr__VeriFast_wrapper(self.end); + let ptr_a = mut_ptr_addr__VeriFast_wrapper(self.ptr.as_ptr()); + end_a.wrapping_sub(ptr_a) + } else { + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + // ignore-tidy-undocumented-unsafe + let end_nn = unsafe { non_null_from_end__VeriFast_wrapper(&self.end) }; + //@ end_ref_readonly(end_r); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ assert [_]exists::>(?elems); + //@ open_frac_borrow(k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems), q/2); + //@ open [?fr]IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close LiveRange::(v.ptr.as_ptr(), len, alloc_id.lft, q_alloc, fr, elems); + let d = unsafe { non_null_offset_from_unsigned__VeriFast_wrapper(end_nn, self.ptr) }; + //@ open LiveRange::(v.ptr.as_ptr(), len, alloc_id.lft, q_alloc, fr, elems); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ close [fr]IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + //@ close_frac_borrow(fr, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + d + }; + //@ close [f]IntoIter_shared_val::(self, v)(); + //@ close_frac_borrow(f, IntoIter_shared_val::(self, v)); + (exact, Some(exact)) + } + + #[inline] + fn advance_by<'s>(/*@~mut@*/ self: &'s mut Self, n: usize) -> Result<(), NonZero> + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >>.own(t, result); + /*@ + safety_proof { + assert [?q]lifetime_token('s); + open_full_borrow(q, 's, (>.full_borrow_content)(_t, self)); + open_full_borrow_content::>(_t, self); + let r = call(); + close_full_borrow_content::>(_t, self); + close_full_borrow((>.full_borrow_content)(_t, self)); + leak full_borrow('s, (>.full_borrow_content)(_t, self)); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ let self_p0 = self; + //@ open_points_to(self_p0); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + close exists::(std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv0, ?end0, ?elems0); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv0, end0, elems0); + close exists::(end0 - adv0); + } + } @*/ + //@ open exists::(?len0); + //@ let k_len = begin_lifetime(); + //@ close IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + //@ borrow(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ IntoIter_share_val_fbc::(k_len, t, self_p0, self0, alloc_id, len0); + let cur_len; + unsafe { + //@ let_lft 'a = flft; + //@ let self_r = precreate_ref(&self); + //@ init_ref_readonly(self_r, 1/2); + cur_len = exact_size_len__VeriFast_wrapper/*@::@*/(&self); + //@ end_ref_readonly(self_r); + } + //@ end_lifetime(k_len); + //@ borrow_end(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ open IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + let step_size = usize_min__VeriFast_wrapper(cur_len, n); + let to_drop = self.ptr.as_ptr().cast_slice(step_size); + if T::IS_ZST { + // See `next` for why we sub `end` here. + //@ wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + self.end = const_ptr_wrapping_byte_sub__VeriFast_wrapper(self.end, step_size); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize), ?elems_z); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems_z, own::(t), step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems_z)); + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(step_size, self0.cap, std::mem::size_of::()); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems, own::(t), step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems)); + //@ if step_size == end_idx - adv { assert self0.ptr.as_ptr() + step_size == self0.end; } else { assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, ?rest_e); open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, rest_e); assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr() + step_size, ?xv); let q_nz = lifetime_token_trade(flft, 1/4, alloc_id.lft); open_points_to_at_lft(self0.ptr.as_ptr() + step_size, q_nz/2); points_to_limits(self0.ptr.as_ptr() + step_size); close_points_to_at_lft(self0.ptr.as_ptr() + step_size); lifetime_token_trade_back(q_nz, alloc_id.lft); close array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, rest_e); } + //@ let q_add = lifetime_token_trade(flft, 1/4, alloc_id.lft); + //@ close LiveRange::(self0.ptr.as_ptr(), step_size, alloc_id.lft, q_add, 1, take(step_size, elems)); + // SAFETY: the min() above ensures that step_size is in bounds + self.ptr = unsafe { non_null_add__VeriFast_wrapper(self.ptr, step_size) }; + //@ open LiveRange::(self0.ptr.as_ptr(), step_size, alloc_id.lft, q_add, 1, take(step_size, elems)); + //@ lifetime_token_trade_back(q_add, alloc_id.lft); + } + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close_points_to_slice_at_lft(to_drop); + //@ open_points_to_at_lft(to_drop, q_alloc/2); + // SAFETY: the min() above ensures that step_size is in bounds + unsafe { + ptr::drop_in_place(to_drop); + } + //@ close_points_to_at_lft_(to_drop); + //@ open_points_to_slice_at_lft_(to_drop); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + let self_p = self; + if std::mem::size_of::() == 0 { + leak array_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), step_size, _); + } else { + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv1, _); + if step_size == 0 { + open array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr(), 0, _); + } else { + array_at_lft__join::(self0.buf.as_ptr()); + } + assert (*self_p).ptr |-> ?new_ptr &*& array_at_lft(alloc_id.lft, new_ptr.as_ptr(), ?rem1, ?elems1); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, new_ptr, self0.end, adv1 + step_size, adv1 + step_size + rem1, elems1); + } + close_points_to(self_p); + assert *self_p |-> ?self1; + close >.own(t, self1); + } @*/ + unsafe { non_zero_rem__VeriFast_wrapper(n - step_size) } + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + #[inline] + fn last(mut self) -> Option { + self.next_back() + } + + #[inline] + fn next_chunk(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { raw_ary.transpose().assume_init() }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available and we + // just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, N); + self.ptr = self.ptr.add(N); + Ok(raw_ary.transpose().assume_init()) + } + } + + #[inline] + fn fold(mut self, mut accum: B, mut f: F) -> B + where + F: FnMut(B, T) -> B, + //@ req thread_token(?t) &*& t == currentThread &*& >.own(t, self) &*& .own(t, accum) &*& .own(t, f); + //@ ens thread_token(t) &*& .own(t, result); + { + //@ assert lifetime_token(?flft); + //@ close_points_to(&self); + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *(&self) |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(&self); + let ptr_raw = self.ptr.as_ptr(); + let end_mut = const_ptr_cast_mut__VeriFast_wrapper(self.end); + let cont = ptr_raw != end_mut; + //@ close_points_to(&self); + cont + } { + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(cur_it.ptr); + //@ wrapping_sub_usize_zero(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ let old_len = std::num::wrapping_sub_usize(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), old_len, ?elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ leak points_to_at_lft_(alloc_id.lft, cur_it.ptr.as_ptr(), _); + // See `next` for why we subtract from `end` here. + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + //@ close_points_to(&self); + //@ close >.own(t, *(&self)); + accum = call_fold__VeriFast_wrapper(&mut f, accum, tmp); + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *(&self) |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id_c); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, ?adv_c, ?end_idx_c, ?elems_c); + //@ let ptr_r = precreate_ref(&self.ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&self.end); + //@ init_ref_readonly(end_r, 1/2); + let is_ne = unsafe { ptr_ne_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + //@ close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, adv_c, end_idx_c, elems_c); + //@ close_points_to(&self); + //@ close >.own(t, *(&self)); + is_ne + } { + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, cur_it.ptr, cur_it.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(1, cur_it.cap, std::mem::size_of::()); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), end_idx - adv, elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ points_to_at_lft_inv(cur_it.ptr.as_ptr()); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ close LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(self.ptr) }; + //@ open LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr() + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr(), 1, _); + array_at_lft__join::(cur_it.buf.as_ptr()); + assert array_at_lft(alloc_id.lft, cur_it.ptr.as_ptr() + 1, end_idx - adv - 1, ?elems_rest); + close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, self.ptr, cur_it.end, adv + 1, end_idx, elems_rest); + close_points_to(&self); + close >.own(t, *(&self)); + } @*/ + accum = call_fold__VeriFast_wrapper(&mut f, accum, tmp); + } + } + + //@ open_points_to(&self); + // There are in fact no remaining elements to forget, but by doing this we can avoid + // potentially generating a needless loop to drop the elements that cannot exist at + // this point. + self.forget_remaining_elements_and_dealloc(); + //@ close_points_to(&self); + + accum + } + + #[inline] + fn try_fold(&mut self, mut accum: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, T) -> R, + R: core::ops::Try, + { + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr.as_ptr() != self.end.cast_mut() { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // See `next` for why we subtract from `end` here. + self.end = self.end.wrapping_byte_sub(1); + accum = f(accum, tmp)?; + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr != non_null!(self.end, T) { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { self.ptr.add(1) }; + accum = f(accum, tmp)?; + } + } + R::from_output(accum) + } + #[requires(i < self.len())] + #[cfg_attr(kani, kani::modifies(self))] + unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item + where + Self: TrustedRandomAccessNoCoerce, + { + // SAFETY: the caller must guarantee that `i` is in bounds of the + // `Vec`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)` + // is guaranteed to pointer to an element of the `Vec` and + // thus guaranteed to be valid to dereference. + // + // Also note the implementation of `Self: TrustedRandomAccess` requires + // that `T: Copy` so reading elements from the buffer doesn't invalidate + // them for `Drop`. + unsafe { self.ptr.add(i).read() } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl DoubleEndedIterator for IntoIter { + #[inline] + fn next_back(&mut self) -> Option + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + //@ open_points_to(self); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(self0.ptr); + if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut _ { + /*@ { + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // See above for why 'ptr.offset' isn't used + //@ wrapping_sub_usize_zero(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(self0.end as usize, self0.ptr.as_ptr() as usize); + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + //@ let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + //@ open foreach(elems_z, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xz); + //@ open own::(t)(xz); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + // Note that even though this is next_back() we're reading from `self.ptr`, not + // `self.end`. We track our length using the byte offset from `self.ptr` to `self.end`, + // so the end pointer may not be suitably aligned for T. + // MUTANT 1: reading from `self.end` instead of `self.ptr` is UB for aligned ZSTs + // because `self.end` is decremented by 1 byte and may be misaligned for `T`. + let res = Some(unsafe { ptr::read(self.end) }); + /*@ { + close_points_to_at_lft_(self0.ptr.as_ptr()); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + leak points_to_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), _); + close_points_to(self); + close >.own(t, *self); + close >.own(t, Some(xz)); + } @*/ + res + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let is_eq = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + if is_eq { + /*@ { + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv, end_idx, elems); + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // ignore-tidy-undocumented-unsafe + unsafe { + /*@ { + let rem = end_idx - adv; + list_split_last(elems); + array_at_lft_split::(self0.ptr.as_ptr(), rem - 1); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + (rem - 1), 1, _); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + rem, 0, _); + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr() + (rem - 1), ?xlast); + foreach_snoc_inv(take(rem - 1, elems), xlast, own::(t)); + open own::(t)(xlast); + points_to_at_lft_inv(self0.ptr.as_ptr() + (rem - 1)); + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(1, self0.cap, std::mem::size_of::()); + } @*/ + self.end = self.end.sub(1); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(self0.buf.as_ptr() + (end_idx - 1), q_alloc/2); + let val = ptr::read(self.end); + let res = Some(val); + /*@ { + close_points_to_at_lft_(self0.buf.as_ptr() + (end_idx - 1)); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() + end_idx, 0, nil); + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() + (end_idx - 1), 1, _); + array_at_lft__join::(self0.buf.as_ptr() + (end_idx - 1)); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, (*self).end, adv, end_idx - 1, take(end_idx - adv - 1, elems)); + close_points_to(self); + close >.own(t, *self); + close >.own(t, Some(val)); + } @*/ + res + } + } + } + + #[inline] + fn next_chunk_back(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, N - len..N) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { MaybeUninit::array_assume_init(raw_ary) }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available + // and we just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping( + self.ptr.add(len - N).as_ptr(), + raw_ary.as_mut_ptr() as *mut T, + N, + ); + self.end = self.end.sub(N); + Ok(MaybeUninit::array_assume_init(raw_ary)) + } + } + + #[inline] + fn advance_back_by<'s>(/*@~mut@*/ self: &'s mut Self, n: usize) -> Result<(), NonZero> + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >>.own(t, result); + /*@ + safety_proof { + assert [?q]lifetime_token('s); + open_full_borrow(q, 's, (>.full_borrow_content)(_t, self)); + open_full_borrow_content::>(_t, self); + let r = call(); + close_full_borrow_content::>(_t, self); + close_full_borrow((>.full_borrow_content)(_t, self)); + leak full_borrow('s, (>.full_borrow_content)(_t, self)); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ let self_p0 = self; + //@ open_points_to(self_p0); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + close exists::(std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv0, ?end0, ?elems0); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv0, end0, elems0); + close exists::(end0 - adv0); + } + } @*/ + //@ open exists::(?len0); + //@ let k_len = begin_lifetime(); + //@ close IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + //@ borrow(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ IntoIter_share_val_fbc::(k_len, t, self_p0, self0, alloc_id, len0); + let cur_len; + unsafe { + //@ let_lft 'a = flft; + //@ let self_r = precreate_ref(&self); + //@ init_ref_readonly(self_r, 1/2); + cur_len = exact_size_len__VeriFast_wrapper/*@::@*/(&self); + //@ end_ref_readonly(self_r); + } + //@ end_lifetime(k_len); + //@ borrow_end(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ open IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + let step_size = usize_min__VeriFast_wrapper(cur_len, n); + if T::IS_ZST { + // SAFETY: same as for advance_by() + //@ wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + self.end = const_ptr_wrapping_byte_sub__VeriFast_wrapper(self.end, step_size); + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(step_size, self0.cap, std::mem::size_of::()); + //@ mul_mono_l(1, std::mem::size_of::(), self0.cap); + //@ let keep_n = (end_idx - adv) - step_size; + //@ array_at_lft_split::(self0.ptr.as_ptr(), keep_n); + //@ foreach_split(elems, own::(t), keep_n); + // SAFETY: same as for advance_by() + self.end = unsafe { self.end.sub(step_size) }; + } + let to_drop = if T::IS_ZST { + // ZST may cause unalignment + let d = unsafe { non_null_dangling__VeriFast_wrapper::() }.as_ptr(); + //@ let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems_z, own::(t), step_size); + //@ zst_array_at_lft_move::(take(step_size, elems_z), alloc_id.lft, self0.ptr.as_ptr(), d, step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems_z)); + d.cast_slice(step_size) + } else { + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?keep1, ?keep_elems); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + keep1, step_size, ?drop_elems); + //@ close_slice_own_from_foreach::(t, drop_elems); + const_ptr_cast_t_mut__VeriFast_wrapper(self.end).cast_slice(step_size) + }; + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close_points_to_slice_at_lft(to_drop); + //@ open_points_to_at_lft(to_drop, q_alloc/2); + // SAFETY: same as for advance_by() + unsafe { + ptr::drop_in_place(to_drop); + } + //@ close_points_to_at_lft_(to_drop); + //@ open_points_to_slice_at_lft_(to_drop); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + let self_p = self; + if std::mem::size_of::() == 0 { + leak array_at_lft_(alloc_id.lft, to_drop as *T, step_size, _); + assert (*self_p).end |-> ?new_end; + assert (new_end as usize) == std::num::wrapping_sub_usize(self0.end as usize, step_size); + wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + assert array_at_lft(alloc_id.lft, ?p_rem, ?rem_z, ?rem_elems); + zst_array_at_lft_move::(rem_elems, alloc_id.lft, p_rem, self0.ptr.as_ptr(), rem_z); + assert rem_z == std::num::wrapping_sub_usize(new_end as usize, self0.ptr.as_ptr() as usize); + } else { + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv1, _); + assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?keep2, ?keep_elems2); + array_at_lft__join::(self0.buf.as_ptr() + (adv1 + keep2)); + assert (*self_p).end |-> ?new_end; + if keep2 == 0 { + assert new_end == self0.ptr.as_ptr(); + } else { + assert new_end != 0; + } + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, new_end, adv1, adv1 + keep2, keep_elems2); + } + close_points_to(self_p); + assert *self_p |-> ?self1; + close >.own(t, self1); + } @*/ + unsafe { non_zero_rem__VeriFast_wrapper(n - step_size) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ExactSizeIterator for IntoIter { + fn is_empty(&self) -> bool + //@ req thread_token(?t) &*& [_]IntoIter_share_::(?k, t, self, ?len) &*& [?q]lifetime_token(k); + //@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result == (len == 0); + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open IntoIter_share_::(k, t, self, len); + //@ assert [_]exists::>(?v); + //@ open_frac_borrow(k, IntoIter_shared_val::(self, v), q); + //@ open [?f]IntoIter_shared_val::(self, v)(); + let res = if T::IS_ZST { + //@ wrapping_sub_usize_zero(v.end as usize, v.ptr.as_ptr() as usize); + self.ptr.as_ptr() == self.end as *mut _ + } else { + //@ points_to_limits(&(*self).ptr); + //@ points_to_limits(&(*self).end); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let r = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ assert (v.end as usize) == (v.ptr.as_ptr() as usize) + len * std::mem::size_of::(); + //@ if len == 0 { match (v.ptr.as_ptr() as pointer) { pointer_ctor(prov, addr, meta) => {} } } else { mul_mono_l(1, len, std::mem::size_of::()); } + r + }; + //@ close [f]IntoIter_shared_val::(self, v)(); + //@ close_frac_borrow(f, IntoIter_shared_val::(self, v)); + res + } +} + +#[stable(feature = "fused", since = "1.26.0")] +impl FusedIterator for IntoIter {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "trusted_fused")] +unsafe impl TrustedFused for IntoIter {} + +#[unstable(feature = "trusted_len", issue = "37572")] +unsafe impl TrustedLen for IntoIter {} + +#[stable(feature = "default_iters", since = "1.70.0")] +impl Default for IntoIter +where + A: Allocator + Default, +{ + /// Creates an empty `vec::IntoIter`. + /// + /// ``` + /// # use std::vec; + /// let iter: vec::IntoIter = Default::default(); + /// assert_eq!(iter.len(), 0); + /// assert_eq!(iter.as_slice(), &[]); + /// ``` + fn default() -> Self { + super::Vec::new_in(Default::default()).into_iter() + } +} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +#[unsafe(rustc_allow_lifetime_dependent_specialization)] +trait NonDrop {} + +// T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr +// and thus we can't implement drop-handling +#[unstable(issue = "none", feature = "std_internals")] +impl NonDrop for T {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +// TrustedRandomAccess (without NoCoerce) must not be implemented because +// subtypes/supertypes of `T` might not be `NonDrop` +unsafe impl TrustedRandomAccessNoCoerce for IntoIter +where + T: NonDrop, +{ + const MAY_HAVE_SIDE_EFFECT: bool = false; +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_into_iter_clone", since = "1.8.0")] +impl Clone for IntoIter { + fn clone(&self) -> Self { + self.as_slice().to_vec_in(self.alloc.deref().clone()).into_iter() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter { + fn drop(&mut self) { + struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter); + + impl Drop for DropGuard<'_, T, A> { + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + self.0.dealloc_only(); + } + } + } + + let guard = DropGuard(self); + // destroy the remaining elements + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(guard.0.as_raw_mut_slice()); + } + // now `guard` will be dropped and do the rest + } +} +// In addition to the SAFETY invariants of the following three unsafe traits +// also refer to the vec::in_place_collect module documentation to get an overview +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl InPlaceIterable for IntoIter { + const EXPAND_BY: Option> = NonZero::new(1); + const MERGE_BY: Option> = NonZero::new(1); +} + +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl SourceIter for IntoIter { + type Source = Self; + + #[inline] + unsafe fn as_inner(&mut self) -> &mut Self::Source { + self + } +} + +#[cfg(not(no_global_oom_handling))] +unsafe impl AsVecIntoIter for IntoIter { + type Item = T; + + fn as_into_iter(&mut self) -> &mut IntoIter { + self + } +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/lib.rs b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/lib.rs new file mode 120000 index 0000000000000..97082647c8f5c --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/lib.rs @@ -0,0 +1 @@ +../../into_iter.rs/verified/lib.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/raw_vec.rs b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/raw_vec.rs new file mode 120000 index 0000000000000..78865e9bd4f3c --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant1_zst_next_back_read_end/raw_vec.rs @@ -0,0 +1 @@ +../../into_iter.rs/verified/raw_vec.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2.patch b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2.patch new file mode 100644 index 0000000000000..9e4af4e0533d3 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2.patch @@ -0,0 +1,11 @@ +--- verified/into_iter.rs ++++ mutant2_fold_skip_ptr_advance/into_iter.rs +@@ -1881,7 +1881,7 @@ + //@ close LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. +- self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(self.ptr) }; ++ // MUTANT 2: omitting `self.ptr = self.ptr.add(1)` causes double-read / use-after-move UB. + //@ open LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/into_iter.rs b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/into_iter.rs new file mode 100644 index 0000000000000..95ca5fbe2db69 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/into_iter.rs @@ -0,0 +1,2387 @@ +use core::iter::{ + FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, + TrustedRandomAccessNoCoerce, +}; +#[cfg(kani)] +use core::kani; +use core::marker::PhantomData; +use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties}; +use core::num::NonZero; +#[cfg(not(no_global_oom_handling))] +use core::ops::Deref; +use core::panic::UnwindSafe; +use core::ptr::{self, NonNull}; +use core::{array, fmt, slice}; + +use safety::{loop_invariant, requires}; + +#[cfg(not(no_global_oom_handling))] +use super::AsVecIntoIter; +use crate::alloc::{Allocator, Global}; +#[cfg(not(no_global_oom_handling))] +use crate::collections::VecDeque; +use crate::raw_vec::RawVec; + +//@ use std::alloc::{Allocator, alloc_id_t, alloc_block_in, Layout}; +//@ use std::ptr::{NonNull, NonNull_as_ptr_nonnull}; +//@ use std::option::{Option, Option::None, Option::Some}; +//@ use std::ops::ControlFlow; +//@ use raw_vec::{RawVec, RawVec_to_own, RawVec_inv}; + +macro non_null { + (mut $place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { &mut *((&raw mut $place) as *mut NonNull<$t>) } + }}, + ($place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { *((&$place as *const *const $t) as *const NonNull<$t>) } + }}, +} + +/// An iterator that moves out of a vector. +/// +/// This `struct` is created by the `into_iter` method on [`Vec`](super::Vec) +/// (provided by the [`IntoIterator`] trait). +/// +/// # Example +/// +/// ``` +/// let v = vec![0, 1, 2]; +/// let iter: std::vec::IntoIter<_> = v.into_iter(); +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_insignificant_dtor] +pub struct IntoIter< + T, + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] A: Allocator = Global, +> { + pub(super) buf: NonNull, + pub(super) phantom: PhantomData, + pub(super) cap: usize, + // the drop impl reconstructs a RawVec from buf, cap and alloc + // to avoid dropping the allocator twice we need to wrap it into ManuallyDrop + pub(super) alloc: ManuallyDrop, + pub(super) ptr: NonNull, + /// If T is a ZST, this is actually ptr+len. This encoding is picked so that + /// ptr == end is a quick test for the Iterator being empty, that works + /// for both ZST and non-ZST. + /// For non-ZSTs the pointer is treated as `NonNull` + pub(super) end: *const T, +} + +/*@ + +lem wrapping_sub_usize_zero(a: usize, b: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX; + ens (std::num::wrapping_sub_usize(a, b) == 0) == (a == b); +{ +} + +lem wrapping_sub_usize_dec(a: usize, b: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX &*& a != b; + ens std::num::wrapping_sub_usize(std::num::wrapping_sub_usize(a, 1), b) == std::num::wrapping_sub_usize(a, b) - 1; +{ +} + +lem wrapping_sub_usize_sub(a: usize, b: usize, n: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX &*& 0 <= n &*& n <= std::num::wrapping_sub_usize(a, b); + ens std::num::wrapping_sub_usize(std::num::wrapping_sub_usize(a, n), b) == std::num::wrapping_sub_usize(a, b) - n; +{ +} + +lem foreach_own_send(t0: thread_id_t, t1: thread_id_t) + req foreach(?xs, own::(t0)) &*& type_interp::() &*& is_Send(typeid(T)) == true; + ens foreach(xs, own::(t1)) &*& type_interp::(); +{ + open foreach(xs, own::(t0)); + match xs { + nil => {} + cons(x, xs0) => { + open own::(t0)(x); + Send::send::(t0, t1, x); + close own::(t1)(x); + foreach_own_send::(t0, t1); + } + } + close foreach(xs, own::(t1)); +} + +lem array_at_lft_own_mono(t: thread_id_t, k: lifetime_t, p: *T0, n: usize) + req array_at_lft::(k, p, n, ?elems) &*& foreach(elems, own::(t)) &*& + type_interp::() &*& type_interp::() &*& + is_subtype_of::() == true &*& + std::mem::size_of::() == std::mem::size_of::() &*& + std::mem::align_of::() == std::mem::align_of::(); + ens array_at_lft::(k, p as *T1, n, ?elems1) &*& foreach(elems1, own::(t)) &*& + type_interp::() &*& type_interp::(); +{ + open array_at_lft::(k, p, n, elems); + open foreach(elems, own::(t)); + match elems { + nil => { + close array_at_lft::(k, p as *T1, 0, nil); + close foreach(nil, own::(t)); + } + cons(x, xs0) => { + open points_to_at_lft::(k, p, x); + to_u8s__at_lft::(p); + assert array_at_lft_(k, p as *u8, std::mem::size_of::(), ?bs); + from_u8s__at_lft::(p as *T1); + // Rust subtyping (`T0 <: T1`) only weakens lifetimes and preserves byte + // representation (https://github.com/verifast/verifast/issues/610). + let x1 = upcast::(x); + assume(of_u8s_::(bs) == some(x1)); + close points_to_at_lft::(k, p as *T1, x1); + open own::(t)(x); + own_mono::(t, x); + close own::(t)(x1); + array_at_lft_own_mono::(t, k, p + 1, n - 1); + assert array_at_lft::(k, (p + 1) as *T1, n - 1, ?xs1); + assert ((p + 1) as *T1) == ((p as *T1) + 1); + close array_at_lft::(k, p as *T1, n, cons(x1, xs1)); + close foreach(cons(x1, xs1), own::(t)); + } + } +} + +lem foreach_snoc_inv(xs: list, x: T, p: pred(T)) + req foreach(append(xs, [x]), p); + ens foreach(xs, p) &*& p(x); +{ + match xs { + nil => { + open foreach([x], p); + open foreach(nil, p); + close foreach(nil, p); + } + cons(h, t) => { + open foreach(cons(h, append(t, [x])), p); + foreach_snoc_inv(t, x, p); + close foreach(cons(h, t), p); + } + } +} + +lem list_split_last(xs: list) + req length(xs) > 0; + ens xs == append(take(length(xs) - 1, xs), [nth(length(xs) - 1, xs)]) &*& length(take(length(xs) - 1, xs)) == length(xs) - 1; +{ + match xs { + nil => {} + cons(h, t) => { + if length(t) == 0 { + match t { + nil => {} + cons(h1, t1) => {} + } + } else { + list_split_last(t); + } + } + } +} + +pred IntoIter_non_zst_buf(t: thread_id_t, buf: NonNull, cap: usize, alloc_id: alloc_id_t, ptr: NonNull, end: *T, adv: usize, end_idx: usize, elems: list) = + 0 <= adv &*& adv <= end_idx &*& end_idx <= cap &*& + cap * std::mem::size_of::() <= isize::MAX &*& + if cap == 0 { + true + } else { + Layout::new::().repeat(cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, buf.as_ptr() as *u8, allocLayout) + } &*& + ptr.as_ptr() == buf.as_ptr() + adv &*& + end == buf.as_ptr() + end_idx &*& + end != 0 &*& pointer_within_limits(end) == true &*& + array_at_lft_(alloc_id.lft, buf.as_ptr(), adv, _) &*& + array_at_lft(alloc_id.lft, ptr.as_ptr(), end_idx - adv, elems) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, buf.as_ptr() + end_idx, cap - end_idx, _); + +pred >.own(t, it) = + Allocator(t, it.alloc, ?alloc_id) &*& + it.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(it.buf.as_ptr()) == true &*& + 0 <= (it.end as usize) &*& (it.end as usize) <= usize::MAX &*& + (it.end as pointer) == pointer_ctor((it.ptr.as_ptr() as pointer).provenance, it.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + it.ptr == it.buf &*& + array_at_lft(alloc_id.lft, it.ptr.as_ptr(), std::num::wrapping_sub_usize(it.end as usize, it.ptr.as_ptr() as usize), ?elems) &*& + foreach(elems, own::(t)) + } else { + IntoIter_non_zst_buf::(t, it.buf, it.cap, alloc_id, it.ptr, it.end, ?adv, ?end_idx, ?elems) + }; + +lem IntoIter_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Send(typeid(IntoIter)) == true &*& + IntoIter_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& + IntoIter_own::(t1, v); +{ + open >.own(t0, v); + assume(is_Send(typeid(T)) == true && is_Send(typeid(A)) == true); + std::alloc::Allocator_send(t1, v.alloc); + if std::mem::size_of::() == 0 { + foreach_own_send::(t0, t1); + } else { + open IntoIter_non_zst_buf::(t0, v.buf, v.cap, ?alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + foreach_own_send::(t0, t1); + close IntoIter_non_zst_buf::(t1, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + } + close >.own(t1, v); +} + +lem IntoIter_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + IntoIter_own::(?t, ?v) &*& + is_subtype_of::() == true &*& + is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + IntoIter_own::(t, IntoIter:: { + buf: upcast(v.buf), + cap: upcast(v.cap), + alloc: upcast(v.alloc), + ptr: upcast(v.ptr), + end: v.end as *T1, + }); +{ + open >.own(t, v); + assert Allocator(t, v.alloc, ?alloc_id); + std::alloc::Allocator_upcast::(v.alloc); + std::ptr::NonNull_upcast::(v.buf); + std::ptr::NonNull_upcast::(v.ptr); + std::ptr::NonNull_Sized_as_ptr(v.ptr); + assume( + std::mem::size_of::() == std::mem::size_of::() && + std::mem::align_of::() == std::mem::align_of::() && + Layout::new::() == Layout::new::() && + upcast::(v.cap) == v.cap + ); + if std::mem::size_of::() == 0 { + array_at_lft_own_mono::(t, alloc_id.lft, v.ptr.as_ptr(), std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + array_at_lft__to_u8s_at_lft_::(v.buf.as_ptr(), adv); + u8s_at_lft__to_array_at_lft_::(v.buf.as_ptr() as *T1, adv); + array_at_lft_own_mono::(t, alloc_id.lft, v.ptr.as_ptr(), end_idx - adv); + array_at_lft__to_u8s_at_lft_::(v.buf.as_ptr() + end_idx, v.cap - end_idx); + assert ((v.buf.as_ptr() + end_idx) as *u8) == (((v.buf.as_ptr() as *T1) + end_idx) as *u8); + u8s_at_lft__to_array_at_lft_::((v.buf.as_ptr() as *T1) + end_idx, v.cap - end_idx); + close IntoIter_non_zst_buf::(t, upcast(v.buf), upcast(v.cap), alloc_id, upcast(v.ptr), v.end as *T1, adv, end_idx, _); + } + close >.own(t, IntoIter:: { + buf: upcast(v.buf), + cap: upcast(v.cap), + alloc: upcast(v.alloc), + ptr: upcast(v.ptr), + end: v.end as *T1, + }); +} + +pred IntoIter_raw_buf(t: thread_id_t, it: IntoIter) = + Allocator(t, it.alloc, ?alloc_id) &*& + it.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(it.buf.as_ptr()) == true &*& + if std::mem::size_of::() == 0 { + true + } else { + it.cap * std::mem::size_of::() <= isize::MAX &*& + (if it.cap == 0 { + true + } else { + Layout::new::().repeat(it.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, it.buf.as_ptr() as *u8, allocLayout) + }) &*& + array_at_lft_(alloc_id.lft, it.buf.as_ptr(), it.cap, _) + }; + +lem IntoIter_own_to_raw_buf(t: thread_id_t, it: IntoIter) + req >.own(t, it); + ens IntoIter_raw_buf::(t, it); +{ + open >.own(t, it); + assert Allocator(t, it.alloc, ?alloc_id); + if std::mem::size_of::() == 0 { + assert array_at_lft(alloc_id.lft, it.ptr.as_ptr(), ?len, ?elems); + leak foreach(elems, own::(t)); + leak array_at_lft(alloc_id.lft, it.ptr.as_ptr(), len, elems); + } else { + open IntoIter_non_zst_buf::(t, it.buf, it.cap, alloc_id, it.ptr, it.end, ?adv, ?end_idx, ?elems); + leak foreach(elems, own::(t)); + array_at_lft_to_array_at_lft_::(it.ptr.as_ptr()); + array_at_lft__join::(it.buf.as_ptr() + adv); + array_at_lft__join::(it.buf.as_ptr()); + } + close IntoIter_raw_buf::(t, it); +} + +lem zst_array_at_lft_move(elems: list, k: lifetime_t, src: *T, dst: *T, n: usize) + req array_at_lft::(k, src, n, elems) &*& + std::mem::size_of::() == 0 &*& + dst as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(dst) == true; + ens array_at_lft::(k, dst, n, elems); +{ + open array_at_lft::(k, src, n, elems); + match elems { + nil => { + close array_at_lft::(k, dst, 0, nil); + } + cons(x, xs0) => { + open points_to_at_lft::(k, src, x); + to_u8s__at_lft::(src); + assert array_at_lft_(k, src as *u8, 0, ?bs); + open array_at_lft_(k, src as *u8, 0, bs); + close array_at_lft_::(k, dst as *u8, 0, nil); + from_u8s__at_lft::(dst); + close points_to_at_lft::(k, dst, x); + zst_array_at_lft_move::(xs0, k, src + 1, dst + 1, n - 1); + close array_at_lft::(k, dst, n, cons(x, xs0)); + } + } +} + +lem close_slice_own_from_foreach(t: thread_id_t, elems: list) + req foreach(elems, own::(t)); + ens <[T]>.own(t, slice_of_elems(elems)); +{ + close <[T]>.own(t, slice_of_elems(elems)); +} + +pred_ctor IntoIter_shared_val(l: *IntoIter, v: IntoIter)(;) = + (*l).buf |-> v.buf &*& + (*l).cap |-> v.cap &*& + (*l).ptr |-> v.ptr &*& + (*l).end |-> v.end &*& + struct_IntoIter_padding::(l); + +pred_ctor IntoIter_shared_range(alloc_lft: lifetime_t, ptr: *T, len: usize, elems: list)(;) = + array_at_lft::(alloc_lft, ptr, len, elems); + +pred IntoIter_share_(k: lifetime_t, t: thread_id_t, l: *IntoIter, len: usize) = + [_]std::alloc::Allocator_share(k, t, &(*l).alloc, ?alloc_id) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + [_]exists::>(?v) &*& + 0 <= len &*& len <= usize::MAX &*& + [_]frac_borrow(k, IntoIter_shared_val::(l, v)) &*& + pointer_within_limits(v.ptr.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) == len + } else { + v.end == v.ptr.as_ptr() + len &*& + v.end != 0 &*& pointer_within_limits(v.end) == true &*& + len * std::mem::size_of::() <= isize::MAX &*& + [_]exists::>(?elems) &*& + [_]frac_borrow(k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)) + }; + +pred >.share(k, t, l) = + [_]IntoIter_share_::(k, t, l, ?len); + +lem IntoIter_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *IntoIter) + req type_interp::() &*& type_interp::() &*& + lifetime_inclusion(k1, k) == true &*& [_]IntoIter_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]IntoIter_share::(k1, t, l); +{ + open IntoIter_share::(k, t, l); + open IntoIter_share_::(k, t, l, ?len); + std::alloc::Allocator_share_mono::(k, k1, t, &(*l).alloc); + assert [_]std::alloc::Allocator_share(k1, t, &(*l).alloc, ?alloc_id); + assert [_]exists::>(?v); + frac_borrow_mono(k, k1, IntoIter_shared_val::(l, v)); + if std::mem::size_of::() != 0 { + assert [_]exists::>(?elems); + frac_borrow_mono(k, k1, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + } + close IntoIter_share_::(k1, t, l, len); + leak IntoIter_share_::(k1, t, l, len); + close IntoIter_share::(k1, t, l); + leak IntoIter_share::(k1, t, l); +} + +lem IntoIter_share_full(k: lifetime_t, t: thread_id_t, l: *IntoIter) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + full_borrow(k, IntoIter_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + [_]IntoIter_share::(k, t, l) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong_m(k, IntoIter_full_borrow_content::(t, l), q); + open IntoIter_full_borrow_content::(t, l)(); + assert *l |-> ?v; + open_points_to(l); + open >.own(t, v); + assert Allocator(t, v.alloc, ?alloc_id); + std::alloc::Allocator_inv(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close IntoIter_shared_val::(l, v)(); + if std::mem::size_of::() == 0 { + let len_z = std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize); + assert array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len_z, ?elems_z); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + v.ptr == v.buf &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len_z, elems_z) &*& + foreach(elems_z, own::(t)); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)), + klong, + IntoIter_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + assert (*l).alloc |-> ?a1; + close >.own(t, IntoIter:: { buf: v.buf, cap: v.cap, alloc: a1, ptr: v.ptr, end: v.end }); + close IntoIter_full_borrow_content::(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m( + klong, + IntoIter_full_borrow_content::(t, l), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)) + ); + full_borrow_split_m(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + } + } + close exists::>(v); + leak exists::>(v); + close IntoIter_share_::(k, t, l, len_z); + leak IntoIter_share_::(k, t, l, len_z); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + let len_nz = end_idx - adv; + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(len_nz, v.cap, std::mem::size_of::()); + close IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)(); + close sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& pointer_within_limits(v.end) == true &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + 0 <= adv &*& adv <= end_idx &*& end_idx <= v.cap &*& + v.cap * std::mem::size_of::() <= isize::MAX &*& + (if v.cap == 0 { + true + } else { + Layout::new::().repeat(v.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, v.buf.as_ptr() as *u8, allocLayout) + }) &*& + v.ptr.as_ptr() == v.buf.as_ptr() + adv &*& + v.end == v.buf.as_ptr() + end_idx &*& + v.end != 0 &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr(), adv, _) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr() + end_idx, v.cap - end_idx, _); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))), + klong, + IntoIter_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)))(); + open sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + open IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)(); + assert (*l).alloc |-> ?a1; + close IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + close >.own(t, IntoIter:: { buf: v.buf, cap: v.cap, alloc: a1, ptr: v.ptr, end: v.end }); + close IntoIter_full_borrow_content::(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m( + klong, + IntoIter_full_borrow_content::(t, l), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))) + ); + full_borrow_split_m(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))); + full_borrow_split_m(klong, IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + full_borrow_into_frac_m(klong, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + frac_borrow_mono(klong, k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + } + } + close exists::>(v); + leak exists::>(v); + close exists::>(elems); + leak exists::>(elems); + close IntoIter_share_::(k, t, l, len_nz); + leak IntoIter_share_::(k, t, l, len_nz); + } + close IntoIter_share::(k, t, l); + leak IntoIter_share::(k, t, l); +} + +pred_ctor IntoIter_val_fbc(t: thread_id_t, l: *IntoIter, v: IntoIter, alloc_id: alloc_id_t, len: usize)() = + (*l).buf |-> v.buf &*& + (*l).cap |-> v.cap &*& + (*l).ptr |-> v.ptr &*& + (*l).end |-> v.end &*& + struct_IntoIter_padding::(l) &*& + (*l).alloc |-> ?a &*& + Allocator(t, a, alloc_id) &*& + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + v.ptr == v.buf &*& + len == std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, ?elems) &*& + foreach(elems, own::(t)) + } else { + IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems) &*& + len == end_idx - adv + }; + +lem IntoIter_share_val_fbc(k: lifetime_t, t: thread_id_t, l: *IntoIter, v: IntoIter, alloc_id: alloc_id_t, len: usize) + nonghost_callers_only + req full_borrow(k, IntoIter_val_fbc::(t, l, v, alloc_id, len)) &*& [?q]lifetime_token(k); + ens [_]IntoIter_share_::(k, t, l, len) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong(k, IntoIter_val_fbc::(t, l, v, alloc_id, len), q); + open IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + std::alloc::Allocator_inv(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close IntoIter_shared_val::(l, v)(); + if std::mem::size_of::() == 0 { + assert array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, ?elems_z); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + v.ptr == v.buf &*& + len == std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, elems_z) &*& + foreach(elems_z, own::(t)); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)), + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + close IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)) + ); + full_borrow_split(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + } + } + close exists::>(v); + leak exists::>(v); + close IntoIter_share_::(k, t, l, len); + leak IntoIter_share_::(k, t, l, len); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(len, v.cap, std::mem::size_of::()); + close IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + close sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& pointer_within_limits(v.end) == true &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + 0 <= adv &*& adv <= end_idx &*& end_idx <= v.cap &*& + len == end_idx - adv &*& + v.cap * std::mem::size_of::() <= isize::MAX &*& + (if v.cap == 0 { + true + } else { + Layout::new::().repeat(v.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, v.buf.as_ptr() as *u8, allocLayout) + }) &*& + v.ptr.as_ptr() == v.buf.as_ptr() + adv &*& + v.end == v.buf.as_ptr() + end_idx &*& + v.end != 0 &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr(), adv, _) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr() + end_idx, v.cap - end_idx, _); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))), + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)))(); + open sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + open IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + close IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + close IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))) + ); + full_borrow_split(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))); + full_borrow_split(klong, IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + full_borrow_into_frac(klong, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + frac_borrow_mono(klong, k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + } + } + close exists::>(v); + leak exists::>(v); + close exists::>(elems); + leak exists::>(elems); + close IntoIter_share_::(k, t, l, len); + leak IntoIter_share_::(k, t, l, len); + } +} + +lem IntoIter_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Sync(typeid(IntoIter)) == true &*& + [_]IntoIter_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& + [_]IntoIter_share::(k, t1, l); +{ + open IntoIter_share::(k, t0, l); + open IntoIter_share_::(k, t0, l, ?len); + assume(is_Sync(typeid(A)) == true); + std::alloc::Allocator_sync::(t1); + close IntoIter_share_::(k, t1, l, len); + leak IntoIter_share_::(k, t1, l, len); + close IntoIter_share::(k, t1, l); + leak IntoIter_share::(k, t1, l); +} + +lem init_ref_IntoIter(p: *IntoIter) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + ref_init_perm(p, ?x) &*& [_]IntoIter_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + [q]lifetime_token(k) &*& [_]IntoIter_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open IntoIter_share::(k, t, x); + open IntoIter_share_::(k, t, x, ?len); + assert [_]exists::>(?v); + open_ref_init_perm_IntoIter(p); + std::alloc::init_ref_Allocator_share_m(k, t, &(*p).alloc); + frac_borrow_sep(k, IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)); + let klong = open_frac_borrow_strong_m(k, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), q); + open [?f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + open [f]IntoIter_shared_val::(x, v)(); + open [f]ref_initialized_::(&(*p).alloc)(); + std::ptr::init_ref_NonNull(&(*p).buf, 1/2); + init_ref_readonly(&(*p).cap, 1/2); + std::ptr::init_ref_NonNull(&(*p).ptr, 1/2); + init_ref_readonly(&(*p).end, 1/2); + init_ref_padding_IntoIter(p, 1/2); + { + pred P() = ref_padding_initialized(p) &*& ref_initialized(&(*p).buf) &*& ref_initialized(&(*p).cap) &*& ref_initialized(&(*p).ptr) &*& ref_initialized(&(*p).end); + close [1 - f/2]P(); + close_ref_initialized_IntoIter(p); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*p).alloc) &*& + ref_padding_end_token(p, x, f/2) &*& [f/2]struct_IntoIter_padding::(x) &*& [1 - f/2]ref_padding_initialized(p) &*& + ref_end_token(&(*p).buf, &(*x).buf, f/2) &*& [f/2]((*x).buf |-> v.buf) &*& [1 - f/2]ref_initialized(&(*p).buf) &*& + ref_readonly_end_token(&(*p).cap, &(*x).cap, f/2) &*& [f/2]((*x).cap |-> v.cap) &*& [1 - f/2]ref_initialized(&(*p).cap) &*& + ref_end_token(&(*p).ptr, &(*x).ptr, f/2) &*& [f/2]((*x).ptr |-> v.ptr) &*& [1 - f/2]ref_initialized(&(*p).ptr) &*& + ref_readonly_end_token(&(*p).end, &(*x).end, f/2) &*& [f/2]((*x).end |-> v.end) &*& [1 - f/2]ref_initialized(&(*p).end); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))), + klong, + f, + sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)) + )() { + open scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + open sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + open ref_initialized_::>(p)(); + open IntoIter_shared_val::(p, v)(); + open_ref_initialized_IntoIter(p); + open Ctx(); + std::ptr::end_ref_NonNull(&(*p).buf); + end_ref_readonly(&(*p).cap); + std::ptr::end_ref_NonNull(&(*p).ptr); + end_ref_readonly(&(*p).end); + end_ref_padding_IntoIter(p); + close [f]IntoIter_shared_val::(x, v)(); + close [f]ref_initialized_::(&(*p).alloc)(); + close [f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(p)(); + close [f/2]IntoIter_shared_val::(p, v)(); + close [f/2]sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + close scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))); + frac_borrow_split(k, ref_initialized_(p), IntoIter_shared_val::(p, v)); + } + } + close IntoIter_share_::(k, t, p, len); + leak IntoIter_share_::(k, t, p, len); + close IntoIter_share::(k, t, p); + leak IntoIter_share::(k, t, p); +} + +lem init_ref_IntoIter_share_(p: *IntoIter) + nonghost_callers_only + req ref_init_perm(p, ?x) &*& [_]IntoIter_share_::(?k, ?t, x, ?len) &*& [?q]lifetime_token(k); + ens [q]lifetime_token(k) &*& [_]IntoIter_share_::(k, t, p, len) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open IntoIter_share_::(k, t, x, len); + assert [_]exists::>(?v); + open_ref_init_perm_IntoIter(p); + std::alloc::init_ref_Allocator_share(k, t, &(*p).alloc); + frac_borrow_sep(k, IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)); + let klong = open_frac_borrow_strong(k, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), q); + open [?f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + open [f]IntoIter_shared_val::(x, v)(); + open [f]ref_initialized_::(&(*p).alloc)(); + std::ptr::init_ref_NonNull(&(*p).buf, 1/2); + init_ref_readonly(&(*p).cap, 1/2); + std::ptr::init_ref_NonNull(&(*p).ptr, 1/2); + init_ref_readonly(&(*p).end, 1/2); + init_ref_padding_IntoIter(p, 1/2); + { + pred P() = ref_padding_initialized(p) &*& ref_initialized(&(*p).buf) &*& ref_initialized(&(*p).cap) &*& ref_initialized(&(*p).ptr) &*& ref_initialized(&(*p).end); + close [1 - f/2]P(); + close_ref_initialized_IntoIter(p); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*p).alloc) &*& + ref_padding_end_token(p, x, f/2) &*& [f/2]struct_IntoIter_padding::(x) &*& [1 - f/2]ref_padding_initialized(p) &*& + ref_end_token(&(*p).buf, &(*x).buf, f/2) &*& [f/2]((*x).buf |-> v.buf) &*& [1 - f/2]ref_initialized(&(*p).buf) &*& + ref_readonly_end_token(&(*p).cap, &(*x).cap, f/2) &*& [f/2]((*x).cap |-> v.cap) &*& [1 - f/2]ref_initialized(&(*p).cap) &*& + ref_end_token(&(*p).ptr, &(*x).ptr, f/2) &*& [f/2]((*x).ptr |-> v.ptr) &*& [1 - f/2]ref_initialized(&(*p).ptr) &*& + ref_readonly_end_token(&(*p).end, &(*x).end, f/2) &*& [f/2]((*x).end |-> v.end) &*& [1 - f/2]ref_initialized(&(*p).end); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))), + klong, + f, + sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)) + )() { + open scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + open sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + open ref_initialized_::>(p)(); + open IntoIter_shared_val::(p, v)(); + open_ref_initialized_IntoIter(p); + open Ctx(); + std::ptr::end_ref_NonNull(&(*p).buf); + end_ref_readonly(&(*p).cap); + std::ptr::end_ref_NonNull(&(*p).ptr); + end_ref_readonly(&(*p).end); + end_ref_padding_IntoIter(p); + close [f]IntoIter_shared_val::(x, v)(); + close [f]ref_initialized_::(&(*p).alloc)(); + close [f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(p)(); + close [f/2]IntoIter_shared_val::(p, v)(); + close [f/2]sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + close scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + close_frac_borrow_strong(klong, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_into_frac(k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))); + frac_borrow_split(k, ref_initialized_(p), IntoIter_shared_val::(p, v)); + } + } + close IntoIter_share_::(k, t, p, len); + leak IntoIter_share_::(k, t, p, len); +} + +@*/ + +// 1-line wrappers for core::mem / core::ptr primitives absent from VeriFast 26.10's std/lib.rsspec. +// Every wrapper is automatically inlined by `refinement-checker` against original/into_iter.rs. +unsafe fn manually_drop_take__VeriFast_wrapper(slot: &mut ManuallyDrop) -> T +//@ req *slot |-> ?v; +//@ ens *slot |-?-> _ &*& result == v; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { ManuallyDrop::take(slot) } +} + +fn const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(p: *const T) -> *const T +//@ req true; +//@ ens (result as pointer) == pointer_ctor((p as pointer).provenance, std::num::wrapping_sub_usize(p as usize, 1), (p as pointer).metadata) &*& 0 <= (result as usize) &*& (result as usize) <= usize::MAX; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.wrapping_byte_sub(1) +} + +fn const_ptr_cast_mut__VeriFast_wrapper(p: *const T) -> *mut T +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.cast_mut() +} + +fn const_ptr_cast_t_mut__VeriFast_wrapper(p: *const T) -> *mut T +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.cast::().cast_mut() +} + +unsafe fn ptr_ne_end__VeriFast_wrapper(ptr: &NonNull, end: &*const T) -> bool +//@ req [?f1](*ptr |-> ?p) &*& [?f2](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true &*& (e as pointer) == pointer_ctor((p.as_ptr() as pointer).provenance, e as usize, pointer_metadata_none); +//@ ens [f1](*ptr |-> p) &*& [f2](*end |-> e) &*& result == (p.as_ptr() != e); +//@ on_unwind_ens false; +//@ assume_correct +{ + *ptr != unsafe { *((end as *const *const T) as *const NonNull) } +} + +unsafe fn ptr_eq_end__VeriFast_wrapper(ptr: &NonNull, end: &*const T) -> bool +//@ req [?f1](*ptr |-> ?p) &*& [?f2](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true &*& (e as pointer) == pointer_ctor((p.as_ptr() as pointer).provenance, e as usize, pointer_metadata_none); +//@ ens [f1](*ptr |-> p) &*& [f2](*end |-> e) &*& result == (p.as_ptr() == e); +//@ on_unwind_ens false; +//@ assume_correct +{ + *ptr == unsafe { *((end as *const *const T) as *const NonNull) } +} + +/*@ +pred LiveSlot(p: *T, k: lifetime_t, q: real, f: real, ov: option) = + [q]lifetime_token(k) &*& + match ov { + some(v) => [f]points_to_at_lft::(k, p, v), + none => [f]points_to_at_lft_::(k, p, _) + }; + +pred LiveRange(p: *T, n: usize, k: lifetime_t, q: real, f: real, elems: list) = + if n == 0 { + true + } else { + [q]lifetime_token(k) &*& [f]array_at_lft::(k, p, n, elems) + }; +@*/ + +unsafe fn non_null_add_1__VeriFast_wrapper(p: NonNull) -> NonNull +/*@ +req std::mem::size_of::() > 0 &*& std::mem::size_of::() <= isize::MAX &*& + pointer_within_limits(p.as_ptr() + 1) == true &*& (p.as_ptr() + 1) != 0 &*& + LiveSlot::(p.as_ptr(), ?k, ?q, ?f, ?ov); +@*/ +/*@ +ens LiveSlot::(p.as_ptr(), k, q, f, ov) &*& + result.as_ptr() == p.as_ptr() + 1; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.add(1) } +} + +unsafe fn exact_size_len__VeriFast_wrapper<'a, 'b, T, A: Allocator>(it: &'a &'b mut IntoIter) -> usize +/*@ +req thread_token(?t) &*& + [?f]points_to::<&'b mut IntoIter>(it, ?p) &*& + [_]IntoIter_share_::(?k, t, p, ?len) &*& + [?q]lifetime_token(k); +@*/ +/*@ +ens thread_token(t) &*& + [f]points_to::<&'b mut IntoIter>(it, p) &*& + [q]lifetime_token(k) &*& + result == len; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + it.len() +} + +fn usize_min__VeriFast_wrapper(a: usize, b: usize) -> usize +//@ req true; +//@ ens result == (if a <= b { a } else { b }); +//@ on_unwind_ens false; +//@ assume_correct +{ + a.min(b) +} + +unsafe fn non_null_dangling__VeriFast_wrapper() -> NonNull +//@ req true; +//@ ens result.as_ptr() as usize == std::mem::align_of::() &*& result.as_ptr() as usize % std::mem::align_of::() == 0 &*& pointer_within_limits(result.as_ptr()) == true; +//@ on_unwind_ens false; +//@ assume_correct +{ + ptr::NonNull::::dangling() +} + +fn const_ptr_wrapping_byte_sub__VeriFast_wrapper(p: *const T, count: usize) -> *const T +//@ req true; +//@ ens (result as pointer) == pointer_ctor((p as pointer).provenance, std::num::wrapping_sub_usize(p as usize, count), (p as pointer).metadata) &*& 0 <= (result as usize) &*& (result as usize) <= usize::MAX; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.wrapping_byte_sub(count) +} + +unsafe fn non_null_add__VeriFast_wrapper(p: NonNull, count: usize) -> NonNull +/*@ +req std::mem::size_of::() > 0 &*& 0 <= count &*& count * std::mem::size_of::() <= isize::MAX &*& + pointer_within_limits(p.as_ptr() + count) == true &*& (p.as_ptr() + count) != 0 &*& + LiveRange::(p.as_ptr(), count, ?k, ?q, ?f, ?elems); +@*/ +/*@ +ens LiveRange::(p.as_ptr(), count, k, q, f, elems) &*& + result.as_ptr() == p.as_ptr() + count; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.add(count) } +} + +unsafe fn non_zero_rem__VeriFast_wrapper(rem: usize) -> Result<(), NonZero> +//@ req thread_token(?t); +//@ ens thread_token(t) &*& >>.own(t, result); +//@ on_unwind_ens false; +//@ assume_correct +{ + NonZero::new(rem).map_or(Ok(()), Err) +} + +fn call_fold__VeriFast_wrapper B>(f: &mut F, accum: B, item: T) -> B +//@ req thread_token(?t) &*& *f |-> ?f0 &*& .own(t, f0) &*& .own(t, accum) &*& .own(t, item); +//@ ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& .own(t, result); +//@ on_unwind_ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1); +//@ assume_correct +{ + f(accum, item) +} + +fn const_ptr_addr__VeriFast_wrapper(p: *const T) -> usize +//@ req true; +//@ ens result == p as usize; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.addr() +} + +fn mut_ptr_addr__VeriFast_wrapper(p: *mut T) -> usize +//@ req true; +//@ ens result == p as usize; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.addr() +} + +unsafe fn non_null_from_end__VeriFast_wrapper(end: &*const T) -> NonNull +//@ req [?f](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true; +//@ ens [f](*end |-> e) &*& result.as_ptr() == e; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { *((end as *const *const T) as *const NonNull) } +} + +unsafe fn non_null_offset_from_unsigned__VeriFast_wrapper(end: NonNull, ptr: NonNull) -> usize +/*@ +req std::mem::size_of::() > 0 &*& + LiveRange::(ptr.as_ptr(), ?len, ?k, ?q, ?f, ?elems) &*& + end.as_ptr() == ptr.as_ptr() + len &*& + 0 <= len &*& len * std::mem::size_of::() <= isize::MAX; +@*/ +/*@ +ens LiveRange::(ptr.as_ptr(), len, k, q, f, elems) &*& + result == len; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { end.offset_from_unsigned(ptr) } +} + +// Verified check that `core::iter::ExactSizeIterator::len`'s default implementation +// (`let (lower, upper) = self.size_hint(); assert_eq!(upper, Some(lower)); lower`) +// computes the exact remaining length `len` exposed in `IntoIter_share_`. +fn verify_exact_size_len_from_size_hint__VeriFast_wrapper(it: &IntoIter) -> usize +//@ req thread_token(?t) &*& [?q]lifetime_token(?k) &*& [_]IntoIter_share_::(k, t, it, ?len); +//@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result == len; +/*@ +safety_proof { + open >.share(?k, _t, it); + call(); +} +@*/ +{ + //@ let it_r = precreate_ref(it); + //@ init_ref_IntoIter_share_(it_r); + //@ open_frac_borrow(k, ref_initialized_(it_r), q/2); + //@ open [?f]ref_initialized_::>(it_r)(); + let (lower, upper) = unsafe { &*(it as *const IntoIter) }.size_hint(); + //@ close [f]ref_initialized_::>(it_r)(); + //@ close_frac_borrow(f, ref_initialized_(it_r)); + //@ assert upper == Some(len); + lower +} + +unsafe fn non_null_read__VeriFast_wrapper(p: NonNull) -> T +//@ req *(p.as_ptr()) |-> ?v &*& p.as_ptr() as usize % std::mem::align_of::() == 0; +//@ ens *(p.as_ptr()) |-?-> _ &*& result == v; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.read() } +} + +// Manually mirroring what `Vec` has, +// because otherwise we get `T: RefUnwindSafe` from `NonNull`. +#[stable(feature = "catch_unwind", since = "1.9.0")] +impl UnwindSafe for IntoIter {} + +#[stable(feature = "vec_intoiter_debug", since = "1.13.0")] +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("IntoIter").field(&self.as_slice()).finish() + } +} + +impl IntoIter { + /// Returns the remaining items of this iterator as a slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// let _ = into_iter.next().unwrap(); + /// assert_eq!(into_iter.as_slice(), &['b', 'c']); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_slice(&self) -> &[T] { + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len()) } + } + + /// Returns the remaining items of this iterator as a mutable slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// into_iter.as_mut_slice()[2] = 'z'; + /// assert_eq!(into_iter.next().unwrap(), 'a'); + /// assert_eq!(into_iter.next().unwrap(), 'b'); + /// assert_eq!(into_iter.next().unwrap(), 'z'); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_mut_slice(&mut self) -> &mut [T] { + // ignore-tidy-undocumented-unsafe + unsafe { &mut *self.as_raw_mut_slice() } + } + + /// Returns a reference to the underlying allocator. + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] + #[inline] + pub fn allocator(&self) -> &A { + &self.alloc + } + + fn as_raw_mut_slice(&mut self) -> *mut [T] { + self.ptr.as_ptr().cast_slice(self.len()) + } + + /// Drops remaining elements and relinquishes the backing allocation. + /// + /// This method guarantees it won't panic before relinquishing the backing + /// allocation. + /// + /// This is roughly equivalent to the following, but more efficient + /// + /// ``` + /// # let mut vec = Vec::::with_capacity(10); + /// # let ptr = vec.as_mut_ptr(); + /// # let mut into_iter = vec.into_iter(); + /// let mut into_iter = std::mem::replace(&mut into_iter, Vec::new().into_iter()); + /// (&mut into_iter).for_each(drop); + /// std::mem::forget(into_iter); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # drop(unsafe { Vec::::from_raw_parts(ptr, 0, 10) }); + /// ``` + /// + /// This method is used by in-place iteration, refer to the vec::in_place_collect + /// documentation for an overview. + #[cfg(not(no_global_oom_handling))] + pub(super) fn forget_allocation_drop_remaining(&mut self) { + let remaining = self.as_raw_mut_slice(); + + // overwrite the individual fields instead of creating a new + // struct and then overwriting &mut self. + // this creates less assembly + self.cap = 0; + self.buf = RawVec::new().non_null(); + self.ptr = self.buf; + self.end = self.buf.as_ptr(); + + // Dropping the remaining elements can panic, so this needs to be + // done only after updating the other fields. + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(remaining); + } + } + + /// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed. + /// + /// This method does not consume `self`, and leaves deallocation to `impl Drop for IntoIter`. + /// If consuming `self` is possible, consider calling + /// [`Self::forget_remaining_elements_and_dealloc()`] instead. + pub(crate) fn forget_remaining_elements(&mut self) + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& self1.end == self1.ptr.as_ptr(); + { + //@ open_points_to(self); + //@ open >.own(t, self0); + // For the ZST case, it is crucial that we mutate `end` here, not `ptr`. + // `ptr` must stay aligned, while `end` may be unaligned. + self.end = self.ptr.as_ptr(); + /*@ { + std::ptr::NonNull_Sized_as_ptr(self0.ptr); + if std::mem::size_of::() == 0 { + assert array_at_lft(?k, self0.ptr.as_ptr(), ?len, ?elems); + leak foreach(elems, own::(t)); + leak array_at_lft(k, self0.ptr.as_ptr(), len, elems); + close array_at_lft::(k, self0.ptr.as_ptr(), 0, nil); + close foreach(nil, own::(t)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, ?alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + leak foreach(elems, own::(t)); + array_at_lft_to_array_at_lft_::(self0.ptr.as_ptr()); + array_at_lft__join::(self0.buf.as_ptr() + adv); + close array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), 0, nil); + close foreach(nil, own::(t)); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.ptr.as_ptr(), adv, adv, nil); + } + close_points_to(self); + close >.own(t, *self); + } @*/ + } + + /// Forgets to Drop the remaining elements and frees the backing allocation. + /// Consuming version of [`Self::forget_remaining_elements()`]. + /// + /// This can be used in place of `drop(self)` when `self` is known to be exhausted, + /// to avoid producing a needless `drop_in_place::<[T]>()`. + #[inline] + pub(crate) fn forget_remaining_elements_and_dealloc(self) + //@ req thread_token(?t) &*& t == currentThread &*& >.own(t, self); + //@ ens thread_token(t); + { + //@ IntoIter_own_to_raw_buf::(t, self); + let mut this = ManuallyDrop::new(self); + // SAFETY: `this` is in ManuallyDrop, so it will not be double-freed. + unsafe { + this.dealloc_only(); + } + } + + /// Frees the allocation, without checking or dropping anything else. + /// + /// The safe version of this method is [`Self::forget_remaining_elements_and_dealloc()`]. + /// This function exists only to share code between that method and the `impl Drop`. + /// + /// # Safety + /// + /// This function must only be called with an [`IntoIter`] that is not going to be dropped + /// or otherwise used in any way, either because it is being forgotten or because its `Drop` + /// is already executing; otherwise a double-free will occur, and possibly a read from freed + /// memory if there are any remaining elements. + #[inline] + unsafe fn dealloc_only(&mut self) + //@ req thread_token(?t) &*& t == currentThread &*& *self |-> ?self0 &*& IntoIter_raw_buf::(t, self0); + //@ ens thread_token(t) &*& (*self).buf |-> _ &*& (*self).cap |-> _ &*& (*self).alloc |-?-> _ &*& (*self).ptr |-> _ &*& (*self).end |-> _ &*& struct_IntoIter_padding(self); + { + //@ open_points_to(self); + //@ open IntoIter_raw_buf::(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + // SAFETY: our caller promises not to touch `*self` again. + let alloc = unsafe { manually_drop_take__VeriFast_wrapper(&mut self.alloc) }; + /*@ + if std::mem::size_of::() != 0 { + std::alloc::Layout_inv(Layout::new::()); + if self0.cap != 0 { raw_vec::mul_zero(self0.cap, std::mem::size_of::()); } + } + @*/ + // SAFETY: We're using this to deallocate a preexisting `RawVec`. + { + let mut _rv = unsafe { RawVec::from_nonnull_in(self.buf, self.cap, alloc) }; + /*@ { + assert RawVec(t, ?rv_val, alloc_id, self0.buf.as_ptr(), ?cap_); + if std::mem::size_of::() == 0 { + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() as *u8, 0, nil); + u8s_at_lft__to_array_at_lft_::(self0.buf.as_ptr(), cap_); + } + RawVec_to_own(rv_val); + close_points_to(&_rv); + } @*/ + } + //@ assert points_to_::>(?rv_p, _); + //@ open_points_to_(rv_p); + //@ open_points_to_(&(*rv_p).inner); + } + + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn into_vecdeque(self) -> VecDeque { + // Keep our `Drop` impl from dropping the elements and the allocator + let mut this = ManuallyDrop::new(self); + + let buf = this.buf.as_ptr(); + let initialized = if T::IS_ZST || this.len() == 0 { + // All the pointers are the same for ZSTs, so it's fine to + // say that they're all at the beginning of the "allocation". + // For non-ZSTs, we have length 0, so we can choose the (empty) + // range to be at the start of the buffer. + // + // Due to `0` ≤ `this.len()` ≤ `this.cap`, the range is well-formed, + // and due to the argument above it spans exactly the elements of + // this iterator. Because `init.start` = `0`, it follows that either + // `init.start` < `cap` or `cap` = `init.start` = `0`; thus the range + // satisfies the requirements of `from_contiguous_raw_parts_in`. + 0..this.len() + } else { + // SAFETY: `this.ptr` and `this.end` are created via offsets of `this.buf`, + // so they point to the same allocation. We have `this.buf` ≤ `this.ptr` ≤ `this.end`, + // so this cannot wrap, and will produce a well-formed range that spans exactly + // the elements of this iterator. + // + // Additionally, due to `end ≤ buf + cap`, we have `init.start` ≤ `init.end` ≤ `cap`. + // Due to the length check above, `init.start < cap`, so the range satisfies the + // requirements of `from_contiguous_raw_parts_in`. + unsafe { this.ptr.offset_from_unsigned(this.buf)..this.end.offset_from_unsigned(buf) } + }; + + let cap = this.cap; + // SAFETY: `this` is forgotten afterwards, so we can move out the allocator. + let alloc = unsafe { ManuallyDrop::take(&mut this.alloc) }; + + // SAFETY: This allocation originally came from a `Vec`, so it satisfies all + // requirements for the `buf` pointer with capacity `cap` allocated in `alloc`. + // Correctness of `initialized` was shown above. + unsafe { VecDeque::from_contiguous_raw_parts_in(buf, initialized, cap, alloc) } + } +} + +#[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")] +impl AsRef<[T]> for IntoIter { + fn as_ref(&self) -> &[T] { + self.as_slice() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for IntoIter {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for IntoIter {} + +// Loop-invariant predicates for `IntoIter::fold` and `IntoIter::try_fold`. +// Marked `#[inline(always)]` and written with pure intrinsics and `const { ... }` +// blocks rather than method calls (e.g. `NonNull::as_ptr` / `pointer::addr` / +// non-const `mem::size_of`) so Kani's loop-contract lowering evaluates them +// inline as side-effect-free CBMC expressions without emitting nondeterministic +// helper calls (https://github.com/model-checking/kani/issues/4796). +// `self.alloc` is untouched by either loop and is preserved across loop +// contracts (verified with both `TrackAlloc` and non-ZST `StatefulAlloc`). +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, and `usize` have identical layout (thin pointer width); + // these casts are side-effect-free re-interpretations for CBMC's loop-invariant evaluator. + let (ptr_p, eptr_p, buf_p, ebuf_p, ptr_a, eptr_a, end_a, eend_a): ( + *const T, + *const T, + *const T, + *const T, + usize, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + core::intrinsics::transmute_unchecked(entry_end), + ) + }; + ptr_p == eptr_p + && buf_p == ebuf_p + && cap == entry_cap + && core::intrinsics::wrapping_sub(end_a, ptr_a) + <= core::intrinsics::wrapping_sub(eend_a, eptr_a) +} + +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_non_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, `*const u8`, and `usize` have identical thin-pointer + // layout; used to avoid method calls in CBMC loop-contract predicates (kani#4796). + let (buf_p, ebuf_p, ptr_p, eptr_u8, ptr_a, eptr_a, end_a): ( + *const T, + *const T, + *const T, + *const u8, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + ) + }; + let diff = core::intrinsics::wrapping_sub(ptr_a, eptr_a); + let span = core::intrinsics::wrapping_sub(end_a, eptr_a); + let sz = const { core::mem::size_of::() }; + let aligned = if const { core::mem::size_of::().is_power_of_two() } { + (diff & core::intrinsics::wrapping_sub(sz, 1)) == 0 + } else { + // Exact divisibility `diff % sz == 0` for any non-power-of-two `sz > 0` without a + // 64-bit integer division circuit: write `sz = odd * 2^tz` and compute the modular + // multiplicative inverse `odd_inv` (`odd * odd_inv == 1 mod 2^BITS`) at const time. + // Then `sz | diff` iff `2^tz | diff` and `(diff >> tz) * odd_inv <= usize::MAX / sz`. + let (tz, odd_inv, max_q) = const { + let s = core::mem::size_of::(); + if s == 0 { + (0u32, 1usize, 0usize) + } else { + let tz = s.trailing_zeros(); + let odd = s >> tz; + let mut inv: usize = 1; + let mut i = 0; + while i < 6 { + inv = inv.wrapping_mul(2usize.wrapping_sub(odd.wrapping_mul(inv))); + i += 1; + } + assert!(odd.wrapping_mul(inv) == 1); + (tz, inv, usize::MAX / s) + } + }; + let low_mask = core::intrinsics::wrapping_sub(1usize << tz, 1); + (diff & low_mask) == 0 && core::intrinsics::wrapping_mul(diff >> tz, odd_inv) <= max_q + }; + // SAFETY: `arith_offset` is wrapping (non-UB) pointer arithmetic; short-circuiting after + // `diff <= span && aligned` additionally guarantees `diff` stays within `[entry_ptr, end]`. + buf_p == ebuf_p + && cap == entry_cap + && end == entry_end + && diff <= span + && aligned + && ptr_p == unsafe { core::intrinsics::arith_offset(eptr_u8, diff as isize) as *const T } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Iterator for IntoIter { + type Item = T; + + #[inline] + fn next(&mut self) -> Option + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + //@ open_points_to(self); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(self0.ptr); + let ptr = if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut T { + /*@ { + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // `ptr` has to stay where it is to remain aligned, so we reduce the length by 1 by + // reducing the `end`. + //@ wrapping_sub_usize_zero(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(self0.end as usize, self0.ptr.as_ptr() as usize); + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + self.ptr + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let is_eq = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + if is_eq { + /*@ { + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv, end_idx, elems); + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + let old = self.ptr; + // ignore-tidy-undocumented-unsafe + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(1, self0.cap, std::mem::size_of::()); + //@ open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), end_idx - adv, elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?x0); + //@ points_to_at_lft_inv(self0.ptr.as_ptr()); + //@ let q_add = lifetime_token_trade(flft, 1/4, alloc_id.lft); + //@ close LiveSlot::(self0.ptr.as_ptr(), alloc_id.lft, q_add, 1, some(x0)); + self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(old) }; + //@ open LiveSlot::(self0.ptr.as_ptr(), alloc_id.lft, q_add, 1, some(x0)); + //@ lifetime_token_trade_back(q_add, alloc_id.lft); + old + }; + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + open foreach(elems_z, own::(t)); + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xz); + open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + open own::(t)(xz); + } else { + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xnz); + open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + open own::(t)(xnz); + } + } @*/ + // ignore-tidy-undocumented-unsafe + let res = Some(unsafe { non_null_read__VeriFast_wrapper(ptr) }); + /*@ { + close_points_to_at_lft_(self0.ptr.as_ptr()); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + if std::mem::size_of::() == 0 { + leak points_to_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), _); + } else { + // Re-pack consumed prefix [0..adv+1) + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv0, _); + assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + 1, ?rem0, ?elems_rest); + close array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr() + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr(), 1, _); + array_at_lft__join::(self0.buf.as_ptr()); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, (*self).ptr, self0.end, adv0 + 1, adv0 + 1 + rem0, elems_rest); + } + close_points_to(self); + close >.own(t, *self); + close >.own(t, res); + } @*/ + res + } + + #[inline] + fn size_hint(&self) -> (usize, Option) + //@ req thread_token(?t) &*& [_]IntoIter_share_::(?k, t, self, ?len) &*& [?q]lifetime_token(k); + //@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result.0 == len &*& result.1 == Some(len); + /*@ + safety_proof { + open >.share(?k, _t, self); + let r = call(); + close usize_own(_t, r.0); + close >.own(_t, r.1); + close usize_own(_t, r.0); + tuple_ext::close_tuple_2_own::>(_t, r); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ open IntoIter_share_::(k, t, self, len); + //@ assert [_]std::alloc::Allocator_share(k, t, &(*self).alloc, ?alloc_id); + //@ assert [_]exists::>(?v); + //@ open_frac_borrow(k, IntoIter_shared_val::(self, v), q/2); + //@ open [?f]IntoIter_shared_val::(self, v)(); + let exact = if T::IS_ZST { + let end_a = const_ptr_addr__VeriFast_wrapper(self.end); + let ptr_a = mut_ptr_addr__VeriFast_wrapper(self.ptr.as_ptr()); + end_a.wrapping_sub(ptr_a) + } else { + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + // ignore-tidy-undocumented-unsafe + let end_nn = unsafe { non_null_from_end__VeriFast_wrapper(&self.end) }; + //@ end_ref_readonly(end_r); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ assert [_]exists::>(?elems); + //@ open_frac_borrow(k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems), q/2); + //@ open [?fr]IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close LiveRange::(v.ptr.as_ptr(), len, alloc_id.lft, q_alloc, fr, elems); + let d = unsafe { non_null_offset_from_unsigned__VeriFast_wrapper(end_nn, self.ptr) }; + //@ open LiveRange::(v.ptr.as_ptr(), len, alloc_id.lft, q_alloc, fr, elems); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ close [fr]IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + //@ close_frac_borrow(fr, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + d + }; + //@ close [f]IntoIter_shared_val::(self, v)(); + //@ close_frac_borrow(f, IntoIter_shared_val::(self, v)); + (exact, Some(exact)) + } + + #[inline] + fn advance_by<'s>(/*@~mut@*/ self: &'s mut Self, n: usize) -> Result<(), NonZero> + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >>.own(t, result); + /*@ + safety_proof { + assert [?q]lifetime_token('s); + open_full_borrow(q, 's, (>.full_borrow_content)(_t, self)); + open_full_borrow_content::>(_t, self); + let r = call(); + close_full_borrow_content::>(_t, self); + close_full_borrow((>.full_borrow_content)(_t, self)); + leak full_borrow('s, (>.full_borrow_content)(_t, self)); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ let self_p0 = self; + //@ open_points_to(self_p0); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + close exists::(std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv0, ?end0, ?elems0); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv0, end0, elems0); + close exists::(end0 - adv0); + } + } @*/ + //@ open exists::(?len0); + //@ let k_len = begin_lifetime(); + //@ close IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + //@ borrow(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ IntoIter_share_val_fbc::(k_len, t, self_p0, self0, alloc_id, len0); + let cur_len; + unsafe { + //@ let_lft 'a = flft; + //@ let self_r = precreate_ref(&self); + //@ init_ref_readonly(self_r, 1/2); + cur_len = exact_size_len__VeriFast_wrapper/*@::@*/(&self); + //@ end_ref_readonly(self_r); + } + //@ end_lifetime(k_len); + //@ borrow_end(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ open IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + let step_size = usize_min__VeriFast_wrapper(cur_len, n); + let to_drop = self.ptr.as_ptr().cast_slice(step_size); + if T::IS_ZST { + // See `next` for why we sub `end` here. + //@ wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + self.end = const_ptr_wrapping_byte_sub__VeriFast_wrapper(self.end, step_size); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize), ?elems_z); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems_z, own::(t), step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems_z)); + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(step_size, self0.cap, std::mem::size_of::()); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems, own::(t), step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems)); + //@ if step_size == end_idx - adv { assert self0.ptr.as_ptr() + step_size == self0.end; } else { assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, ?rest_e); open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, rest_e); assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr() + step_size, ?xv); let q_nz = lifetime_token_trade(flft, 1/4, alloc_id.lft); open_points_to_at_lft(self0.ptr.as_ptr() + step_size, q_nz/2); points_to_limits(self0.ptr.as_ptr() + step_size); close_points_to_at_lft(self0.ptr.as_ptr() + step_size); lifetime_token_trade_back(q_nz, alloc_id.lft); close array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, rest_e); } + //@ let q_add = lifetime_token_trade(flft, 1/4, alloc_id.lft); + //@ close LiveRange::(self0.ptr.as_ptr(), step_size, alloc_id.lft, q_add, 1, take(step_size, elems)); + // SAFETY: the min() above ensures that step_size is in bounds + self.ptr = unsafe { non_null_add__VeriFast_wrapper(self.ptr, step_size) }; + //@ open LiveRange::(self0.ptr.as_ptr(), step_size, alloc_id.lft, q_add, 1, take(step_size, elems)); + //@ lifetime_token_trade_back(q_add, alloc_id.lft); + } + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close_points_to_slice_at_lft(to_drop); + //@ open_points_to_at_lft(to_drop, q_alloc/2); + // SAFETY: the min() above ensures that step_size is in bounds + unsafe { + ptr::drop_in_place(to_drop); + } + //@ close_points_to_at_lft_(to_drop); + //@ open_points_to_slice_at_lft_(to_drop); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + let self_p = self; + if std::mem::size_of::() == 0 { + leak array_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), step_size, _); + } else { + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv1, _); + if step_size == 0 { + open array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr(), 0, _); + } else { + array_at_lft__join::(self0.buf.as_ptr()); + } + assert (*self_p).ptr |-> ?new_ptr &*& array_at_lft(alloc_id.lft, new_ptr.as_ptr(), ?rem1, ?elems1); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, new_ptr, self0.end, adv1 + step_size, adv1 + step_size + rem1, elems1); + } + close_points_to(self_p); + assert *self_p |-> ?self1; + close >.own(t, self1); + } @*/ + unsafe { non_zero_rem__VeriFast_wrapper(n - step_size) } + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + #[inline] + fn last(mut self) -> Option { + self.next_back() + } + + #[inline] + fn next_chunk(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { raw_ary.transpose().assume_init() }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available and we + // just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, N); + self.ptr = self.ptr.add(N); + Ok(raw_ary.transpose().assume_init()) + } + } + + #[inline] + fn fold(mut self, mut accum: B, mut f: F) -> B + where + F: FnMut(B, T) -> B, + //@ req thread_token(?t) &*& t == currentThread &*& >.own(t, self) &*& .own(t, accum) &*& .own(t, f); + //@ ens thread_token(t) &*& .own(t, result); + { + //@ assert lifetime_token(?flft); + //@ close_points_to(&self); + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *(&self) |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(&self); + let ptr_raw = self.ptr.as_ptr(); + let end_mut = const_ptr_cast_mut__VeriFast_wrapper(self.end); + let cont = ptr_raw != end_mut; + //@ close_points_to(&self); + cont + } { + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(cur_it.ptr); + //@ wrapping_sub_usize_zero(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ let old_len = std::num::wrapping_sub_usize(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), old_len, ?elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ leak points_to_at_lft_(alloc_id.lft, cur_it.ptr.as_ptr(), _); + // See `next` for why we subtract from `end` here. + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + //@ close_points_to(&self); + //@ close >.own(t, *(&self)); + accum = call_fold__VeriFast_wrapper(&mut f, accum, tmp); + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *(&self) |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id_c); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, ?adv_c, ?end_idx_c, ?elems_c); + //@ let ptr_r = precreate_ref(&self.ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&self.end); + //@ init_ref_readonly(end_r, 1/2); + let is_ne = unsafe { ptr_ne_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + //@ close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, adv_c, end_idx_c, elems_c); + //@ close_points_to(&self); + //@ close >.own(t, *(&self)); + is_ne + } { + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, cur_it.ptr, cur_it.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(1, cur_it.cap, std::mem::size_of::()); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), end_idx - adv, elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ points_to_at_lft_inv(cur_it.ptr.as_ptr()); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ close LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + // MUTANT 2: omitting `self.ptr = self.ptr.add(1)` causes double-read / use-after-move UB. + //@ open LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr() + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr(), 1, _); + array_at_lft__join::(cur_it.buf.as_ptr()); + assert array_at_lft(alloc_id.lft, cur_it.ptr.as_ptr() + 1, end_idx - adv - 1, ?elems_rest); + close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, self.ptr, cur_it.end, adv + 1, end_idx, elems_rest); + close_points_to(&self); + close >.own(t, *(&self)); + } @*/ + accum = call_fold__VeriFast_wrapper(&mut f, accum, tmp); + } + } + + //@ open_points_to(&self); + // There are in fact no remaining elements to forget, but by doing this we can avoid + // potentially generating a needless loop to drop the elements that cannot exist at + // this point. + self.forget_remaining_elements_and_dealloc(); + //@ close_points_to(&self); + + accum + } + + #[inline] + fn try_fold(&mut self, mut accum: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, T) -> R, + R: core::ops::Try, + { + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr.as_ptr() != self.end.cast_mut() { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // See `next` for why we subtract from `end` here. + self.end = self.end.wrapping_byte_sub(1); + accum = f(accum, tmp)?; + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr != non_null!(self.end, T) { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { self.ptr.add(1) }; + accum = f(accum, tmp)?; + } + } + R::from_output(accum) + } + #[requires(i < self.len())] + #[cfg_attr(kani, kani::modifies(self))] + unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item + where + Self: TrustedRandomAccessNoCoerce, + { + // SAFETY: the caller must guarantee that `i` is in bounds of the + // `Vec`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)` + // is guaranteed to pointer to an element of the `Vec` and + // thus guaranteed to be valid to dereference. + // + // Also note the implementation of `Self: TrustedRandomAccess` requires + // that `T: Copy` so reading elements from the buffer doesn't invalidate + // them for `Drop`. + unsafe { self.ptr.add(i).read() } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl DoubleEndedIterator for IntoIter { + #[inline] + fn next_back(&mut self) -> Option + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + //@ open_points_to(self); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(self0.ptr); + if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut _ { + /*@ { + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // See above for why 'ptr.offset' isn't used + //@ wrapping_sub_usize_zero(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(self0.end as usize, self0.ptr.as_ptr() as usize); + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + //@ let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + //@ open foreach(elems_z, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xz); + //@ open own::(t)(xz); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + // Note that even though this is next_back() we're reading from `self.ptr`, not + // `self.end`. We track our length using the byte offset from `self.ptr` to `self.end`, + // so the end pointer may not be suitably aligned for T. + // ignore-tidy-undocumented-unsafe + let res = Some(unsafe { ptr::read(self.ptr.as_ptr()) }); + /*@ { + close_points_to_at_lft_(self0.ptr.as_ptr()); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + leak points_to_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), _); + close_points_to(self); + close >.own(t, *self); + close >.own(t, Some(xz)); + } @*/ + res + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let is_eq = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + if is_eq { + /*@ { + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv, end_idx, elems); + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // ignore-tidy-undocumented-unsafe + unsafe { + /*@ { + let rem = end_idx - adv; + list_split_last(elems); + array_at_lft_split::(self0.ptr.as_ptr(), rem - 1); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + (rem - 1), 1, _); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + rem, 0, _); + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr() + (rem - 1), ?xlast); + foreach_snoc_inv(take(rem - 1, elems), xlast, own::(t)); + open own::(t)(xlast); + points_to_at_lft_inv(self0.ptr.as_ptr() + (rem - 1)); + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(1, self0.cap, std::mem::size_of::()); + } @*/ + self.end = self.end.sub(1); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(self0.buf.as_ptr() + (end_idx - 1), q_alloc/2); + let val = ptr::read(self.end); + let res = Some(val); + /*@ { + close_points_to_at_lft_(self0.buf.as_ptr() + (end_idx - 1)); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() + end_idx, 0, nil); + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() + (end_idx - 1), 1, _); + array_at_lft__join::(self0.buf.as_ptr() + (end_idx - 1)); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, (*self).end, adv, end_idx - 1, take(end_idx - adv - 1, elems)); + close_points_to(self); + close >.own(t, *self); + close >.own(t, Some(val)); + } @*/ + res + } + } + } + + #[inline] + fn next_chunk_back(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, N - len..N) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { MaybeUninit::array_assume_init(raw_ary) }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available + // and we just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping( + self.ptr.add(len - N).as_ptr(), + raw_ary.as_mut_ptr() as *mut T, + N, + ); + self.end = self.end.sub(N); + Ok(MaybeUninit::array_assume_init(raw_ary)) + } + } + + #[inline] + fn advance_back_by<'s>(/*@~mut@*/ self: &'s mut Self, n: usize) -> Result<(), NonZero> + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >>.own(t, result); + /*@ + safety_proof { + assert [?q]lifetime_token('s); + open_full_borrow(q, 's, (>.full_borrow_content)(_t, self)); + open_full_borrow_content::>(_t, self); + let r = call(); + close_full_borrow_content::>(_t, self); + close_full_borrow((>.full_borrow_content)(_t, self)); + leak full_borrow('s, (>.full_borrow_content)(_t, self)); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ let self_p0 = self; + //@ open_points_to(self_p0); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + close exists::(std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv0, ?end0, ?elems0); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv0, end0, elems0); + close exists::(end0 - adv0); + } + } @*/ + //@ open exists::(?len0); + //@ let k_len = begin_lifetime(); + //@ close IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + //@ borrow(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ IntoIter_share_val_fbc::(k_len, t, self_p0, self0, alloc_id, len0); + let cur_len; + unsafe { + //@ let_lft 'a = flft; + //@ let self_r = precreate_ref(&self); + //@ init_ref_readonly(self_r, 1/2); + cur_len = exact_size_len__VeriFast_wrapper/*@::@*/(&self); + //@ end_ref_readonly(self_r); + } + //@ end_lifetime(k_len); + //@ borrow_end(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ open IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + let step_size = usize_min__VeriFast_wrapper(cur_len, n); + if T::IS_ZST { + // SAFETY: same as for advance_by() + //@ wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + self.end = const_ptr_wrapping_byte_sub__VeriFast_wrapper(self.end, step_size); + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(step_size, self0.cap, std::mem::size_of::()); + //@ mul_mono_l(1, std::mem::size_of::(), self0.cap); + //@ let keep_n = (end_idx - adv) - step_size; + //@ array_at_lft_split::(self0.ptr.as_ptr(), keep_n); + //@ foreach_split(elems, own::(t), keep_n); + // SAFETY: same as for advance_by() + self.end = unsafe { self.end.sub(step_size) }; + } + let to_drop = if T::IS_ZST { + // ZST may cause unalignment + let d = unsafe { non_null_dangling__VeriFast_wrapper::() }.as_ptr(); + //@ let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems_z, own::(t), step_size); + //@ zst_array_at_lft_move::(take(step_size, elems_z), alloc_id.lft, self0.ptr.as_ptr(), d, step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems_z)); + d.cast_slice(step_size) + } else { + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?keep1, ?keep_elems); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + keep1, step_size, ?drop_elems); + //@ close_slice_own_from_foreach::(t, drop_elems); + const_ptr_cast_t_mut__VeriFast_wrapper(self.end).cast_slice(step_size) + }; + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close_points_to_slice_at_lft(to_drop); + //@ open_points_to_at_lft(to_drop, q_alloc/2); + // SAFETY: same as for advance_by() + unsafe { + ptr::drop_in_place(to_drop); + } + //@ close_points_to_at_lft_(to_drop); + //@ open_points_to_slice_at_lft_(to_drop); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + let self_p = self; + if std::mem::size_of::() == 0 { + leak array_at_lft_(alloc_id.lft, to_drop as *T, step_size, _); + assert (*self_p).end |-> ?new_end; + assert (new_end as usize) == std::num::wrapping_sub_usize(self0.end as usize, step_size); + wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + assert array_at_lft(alloc_id.lft, ?p_rem, ?rem_z, ?rem_elems); + zst_array_at_lft_move::(rem_elems, alloc_id.lft, p_rem, self0.ptr.as_ptr(), rem_z); + assert rem_z == std::num::wrapping_sub_usize(new_end as usize, self0.ptr.as_ptr() as usize); + } else { + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv1, _); + assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?keep2, ?keep_elems2); + array_at_lft__join::(self0.buf.as_ptr() + (adv1 + keep2)); + assert (*self_p).end |-> ?new_end; + if keep2 == 0 { + assert new_end == self0.ptr.as_ptr(); + } else { + assert new_end != 0; + } + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, new_end, adv1, adv1 + keep2, keep_elems2); + } + close_points_to(self_p); + assert *self_p |-> ?self1; + close >.own(t, self1); + } @*/ + unsafe { non_zero_rem__VeriFast_wrapper(n - step_size) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ExactSizeIterator for IntoIter { + fn is_empty(&self) -> bool + //@ req thread_token(?t) &*& [_]IntoIter_share_::(?k, t, self, ?len) &*& [?q]lifetime_token(k); + //@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result == (len == 0); + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open IntoIter_share_::(k, t, self, len); + //@ assert [_]exists::>(?v); + //@ open_frac_borrow(k, IntoIter_shared_val::(self, v), q); + //@ open [?f]IntoIter_shared_val::(self, v)(); + let res = if T::IS_ZST { + //@ wrapping_sub_usize_zero(v.end as usize, v.ptr.as_ptr() as usize); + self.ptr.as_ptr() == self.end as *mut _ + } else { + //@ points_to_limits(&(*self).ptr); + //@ points_to_limits(&(*self).end); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let r = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ assert (v.end as usize) == (v.ptr.as_ptr() as usize) + len * std::mem::size_of::(); + //@ if len == 0 { match (v.ptr.as_ptr() as pointer) { pointer_ctor(prov, addr, meta) => {} } } else { mul_mono_l(1, len, std::mem::size_of::()); } + r + }; + //@ close [f]IntoIter_shared_val::(self, v)(); + //@ close_frac_borrow(f, IntoIter_shared_val::(self, v)); + res + } +} + +#[stable(feature = "fused", since = "1.26.0")] +impl FusedIterator for IntoIter {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "trusted_fused")] +unsafe impl TrustedFused for IntoIter {} + +#[unstable(feature = "trusted_len", issue = "37572")] +unsafe impl TrustedLen for IntoIter {} + +#[stable(feature = "default_iters", since = "1.70.0")] +impl Default for IntoIter +where + A: Allocator + Default, +{ + /// Creates an empty `vec::IntoIter`. + /// + /// ``` + /// # use std::vec; + /// let iter: vec::IntoIter = Default::default(); + /// assert_eq!(iter.len(), 0); + /// assert_eq!(iter.as_slice(), &[]); + /// ``` + fn default() -> Self { + super::Vec::new_in(Default::default()).into_iter() + } +} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +#[unsafe(rustc_allow_lifetime_dependent_specialization)] +trait NonDrop {} + +// T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr +// and thus we can't implement drop-handling +#[unstable(issue = "none", feature = "std_internals")] +impl NonDrop for T {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +// TrustedRandomAccess (without NoCoerce) must not be implemented because +// subtypes/supertypes of `T` might not be `NonDrop` +unsafe impl TrustedRandomAccessNoCoerce for IntoIter +where + T: NonDrop, +{ + const MAY_HAVE_SIDE_EFFECT: bool = false; +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_into_iter_clone", since = "1.8.0")] +impl Clone for IntoIter { + fn clone(&self) -> Self { + self.as_slice().to_vec_in(self.alloc.deref().clone()).into_iter() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter { + fn drop(&mut self) { + struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter); + + impl Drop for DropGuard<'_, T, A> { + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + self.0.dealloc_only(); + } + } + } + + let guard = DropGuard(self); + // destroy the remaining elements + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(guard.0.as_raw_mut_slice()); + } + // now `guard` will be dropped and do the rest + } +} +// In addition to the SAFETY invariants of the following three unsafe traits +// also refer to the vec::in_place_collect module documentation to get an overview +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl InPlaceIterable for IntoIter { + const EXPAND_BY: Option> = NonZero::new(1); + const MERGE_BY: Option> = NonZero::new(1); +} + +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl SourceIter for IntoIter { + type Source = Self; + + #[inline] + unsafe fn as_inner(&mut self) -> &mut Self::Source { + self + } +} + +#[cfg(not(no_global_oom_handling))] +unsafe impl AsVecIntoIter for IntoIter { + type Item = T; + + fn as_into_iter(&mut self) -> &mut IntoIter { + self + } +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/lib.rs b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/lib.rs new file mode 120000 index 0000000000000..97082647c8f5c --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/lib.rs @@ -0,0 +1 @@ +../../into_iter.rs/verified/lib.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/raw_vec.rs b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/raw_vec.rs new file mode 120000 index 0000000000000..78865e9bd4f3c --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/mutant2_fold_skip_ptr_advance/raw_vec.rs @@ -0,0 +1 @@ +../../into_iter.rs/verified/raw_vec.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/original b/verifast-proofs/alloc/vec/into_iter.rs-negative/original new file mode 120000 index 0000000000000..6c3e90f4c80b6 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/original @@ -0,0 +1 @@ +../into_iter.rs/original \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/safety_stub.rs b/verifast-proofs/alloc/vec/into_iter.rs-negative/safety_stub.rs new file mode 120000 index 0000000000000..6921daae10b54 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/safety_stub.rs @@ -0,0 +1 @@ +../into_iter.rs/safety_stub.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/tuple_ext.rsspec b/verifast-proofs/alloc/vec/into_iter.rs-negative/tuple_ext.rsspec new file mode 120000 index 0000000000000..85c2d540b2915 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/tuple_ext.rsspec @@ -0,0 +1 @@ +../into_iter.rs/tuple_ext.rsspec \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/update.sh b/verifast-proofs/alloc/vec/into_iter.rs-negative/update.sh new file mode 100644 index 0000000000000..1be5b6aab6386 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/update.sh @@ -0,0 +1,41 @@ +set -x -e + +write_expected_diff() { + local label_a="$1" + local label_b="$2" + local file_a="$3" + local file_b="$4" + local out_file="$5" + local tmp_file + tmp_file="$(mktemp "${out_file}.XXXXXX")" + set +e + diff -u --label "$label_a" --label "$label_b" "$file_a" "$file_b" > "$tmp_file" + local rc=$? + set -e + if [[ "$rc" -ne 1 ]]; then + rm -f "$tmp_file" + echo "ERROR: expected diff exit status 1 for $file_a vs $file_b, got $rc" >&2 + exit 1 + fi + mv "$tmp_file" "$out_file" +} + +if ! git diff --quiet .; then + echo "Working directory not clean. Please stash your changes and try again" + false +else + # Regenerate each mutant directly from the already-updated positive verified/into_iter.rs + # plus its exact 1-line UB mutation patch (avoiding stale symlink merge bases). + cp ../into_iter.rs/verified/into_iter.rs mutant1_zst_next_back_read_end/into_iter.rs + patch -p0 --batch --forward --fuzz=0 mutant1_zst_next_back_read_end/into_iter.rs mutant1.patch + rm -f mutant1_zst_next_back_read_end/into_iter.rs.orig + + cp ../into_iter.rs/verified/into_iter.rs mutant2_fold_skip_ptr_advance/into_iter.rs + patch -p0 --batch --forward --fuzz=0 mutant2_fold_skip_ptr_advance/into_iter.rs mutant2.patch + rm -f mutant2_fold_skip_ptr_advance/into_iter.rs.orig + + write_expected_diff verified/into_iter.rs mutant1_zst_next_back_read_end/into_iter.rs \ + ../into_iter.rs/verified/into_iter.rs mutant1_zst_next_back_read_end/into_iter.rs mutant1.patch + write_expected_diff verified/into_iter.rs mutant2_fold_skip_ptr_advance/into_iter.rs \ + ../into_iter.rs/verified/into_iter.rs mutant2_fold_skip_ptr_advance/into_iter.rs mutant2.patch +fi diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/verify.sh b/verifast-proofs/alloc/vec/into_iter.rs-negative/verify.sh new file mode 100644 index 0000000000000..b91fe48aa4046 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/verify.sh @@ -0,0 +1,91 @@ +set -e -x + +export VFVERSION=26.10 + +# Ensure VeriFast toolchain and matching nightly rustc (nightly-2026-09-25) are available +. "$(dirname "$0")/../../../setup-verifast-home" + +if [[ "$(uname)" == "Darwin" ]]; then + DYLIB_EXT="dylib" +else + DYLIB_EXT="so" +fi + +STUB_DIR="$(mktemp -d)" +trap 'rm -rf "$STUB_DIR"' EXIT + +check_diff_matches_patch() { + local label_a="$1" + local label_b="$2" + local file_a="$3" + local file_b="$4" + local patch_file="$5" + local actual_patch="$STUB_DIR/$(basename "$patch_file").actual" + set +e + diff -u --label "$label_a" --label "$label_b" "$file_a" "$file_b" > "$actual_patch" + local rc=$? + set -e + if [[ "$rc" -ne 1 ]]; then + echo "ERROR: expected diff exit status 1 for $file_a vs $file_b, got $rc" >&2 + exit 1 + fi + diff -u "$patch_file" "$actual_patch" +} + +expect_reject() { + local label="$1" + local expected_diag="$2" + shift 2 + local log_file="$STUB_DIR/${label}.log" + set +e + "$@" > "$log_file" 2>&1 + local rc=$? + set -e + if [[ "$rc" -eq 0 ]]; then + echo "ERROR: $label unexpectedly succeeded (exit 0)!" >&2 + tail -n 30 "$log_file" >&2 + exit 1 + fi + if ! grep -qF "$expected_diag" "$log_file"; then + echo "ERROR: $label failed (exit $rc) without expected diagnostic: $expected_diag" >&2 + tail -n 40 "$log_file" >&2 + exit 1 + fi + echo "OK: $label rejected (exit $rc) with expected diagnostic: $expected_diag" +} + +rustc +nightly-2026-09-25 --edition 2024 --crate-type proc-macro --crate-name safety \ + -o "$STUB_DIR/libsafety.$DYLIB_EXT" safety_stub.rs + +RUSTC_ARGS="--edition 2024 --crate-name alloc --extern safety=$STUB_DIR/libsafety.$DYLIB_EXT -L dependency=$STUB_DIR" + +# 1. Known-good positive control: verify both tools are healthy and accept the unmutated proof +verifast -rustc_args "$RUSTC_ARGS" -extern_spec tuple_ext=tuple_ext.rsspec \ + -skip_specless_fns -ignore_unwind_paths -allow_assume ../into_iter.rs/verified/lib.rs +refinement-checker --rustc-args "$RUSTC_ARGS" with-directives/lib.rs ../into_iter.rs/verified/lib.rs > /dev/null + +# 2. Enforce exact 1-line mutant diffs against the positive proof +check_diff_matches_patch verified/into_iter.rs mutant1_zst_next_back_read_end/into_iter.rs \ + ../into_iter.rs/verified/into_iter.rs mutant1_zst_next_back_read_end/into_iter.rs mutant1.patch +check_diff_matches_patch verified/into_iter.rs mutant2_fold_skip_ptr_advance/into_iter.rs \ + ../into_iter.rs/verified/into_iter.rs mutant2_fold_skip_ptr_advance/into_iter.rs mutant2.patch + +# 3. Mutant 1: aligned-ZST misaligned ptr::read(self.end) in next_back must be rejected by BOTH tools +expect_reject mutant1_verifast "error: No matching heap chunks: [_]points_to" \ + verifast -rustc_args "$RUSTC_ARGS" -extern_spec tuple_ext=tuple_ext.rsspec \ + -skip_specless_fns -ignore_unwind_paths -allow_assume mutant1_zst_next_back_read_end/lib.rs +expect_reject mutant1_refinement "FnDef std::ptr::NonNull::::as_ptr" \ + refinement-checker --rustc-args "$RUSTC_ARGS" with-directives/lib.rs mutant1_zst_next_back_read_end/lib.rs + +# 4. Mutant 2: omitted self.ptr advancement in non-ZST fold loop must be rejected by BOTH tools +expect_reject mutant2_verifast "error: Cannot prove condition." \ + verifast -rustc_args "$RUSTC_ARGS" -extern_spec tuple_ext=tuple_ext.rsspec \ + -skip_specless_fns -ignore_unwind_paths -allow_assume mutant2_fold_skip_ptr_advance/lib.rs +expect_reject mutant2_refinement "Command kinds do not match" \ + refinement-checker --rustc-args "$RUSTC_ARGS" with-directives/lib.rs mutant2_fold_skip_ptr_advance/lib.rs + +# 5. Enforce upstream correspondence +if ! diff ../../../../library/alloc/src/vec/into_iter.rs original/into_iter.rs; then + echo "::error title=Please run verifast-proofs/patch-verifast-proofs.sh::Some VeriFast proofs are out of date; please chdir to verifast-proofs and run patch-verifast-proofs.sh to update them." + false +fi diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/with-directives b/verifast-proofs/alloc/vec/into_iter.rs-negative/with-directives new file mode 120000 index 0000000000000..f9137b7f72d19 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/with-directives @@ -0,0 +1 @@ +../into_iter.rs/with-directives \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs/README.md b/verifast-proofs/alloc/vec/into_iter.rs/README.md new file mode 100644 index 0000000000000..406667ccc5046 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/README.md @@ -0,0 +1,209 @@ +# Partial verification of `Vec::IntoIter` with VeriFast + +With certain [caveats](#caveats) and conditional on the documented 1-line `core` +wrapper contracts listed in the [Trust Inventory](#trust-inventory), this proof proves +unbounded, polymorphic ownership and normal-path memory +[soundness](https://doc.rust-lang.org/nomicon/working-with-unsafe.html) of the core +`alloc::vec::IntoIter` methods for **arbitrary element types `T`** (including +non-power-of-two strides such as `[u8; 3]`, arbitrary `Drop` implementations, and +aligned zero-sized types across the full `0..=usize::MAX` length range), **arbitrary +stateful closures `F: FnMut(...)`**, **arbitrary `Try` return types +`R: core::ops::Try`**, and **arbitrary allocators `A: Allocator`** +(including non-`'static` allocators), for any iterator satisfying `>.own`. + +## Proof Overview + +### `RawVec`-Bridged Representation & Strict Provenance Invariant + +Rather than abstracting away the backing allocation, `original/`, `with-directives/`, +`verified/`, and `verified_try_fold/` bridge directly to the repository's accepted +Challenge 19 [`RawVec` proof](../../raw_vec/mod.rs/): + +- `original/into_iter.rs` is byte-for-byte identical to `library/alloc/src/vec/into_iter.rs` + (enforced by `diff` in `verify.sh`), and `original/raw_vec.rs` is a relative symlink to + `../../../raw_vec/mod.rs/original/raw_vec.rs` (enforced by `diff` against + `library/alloc/src/raw_vec/mod.rs`). Both are compiled via the standalone crate harness + `original/lib.rs` (where `Vec::into_iter` is stubbed as `loop {}`; see + [Scope & Correspondence](#scope--correspondence)). +- `verified/raw_vec.rs` is the verified Challenge 19 `raw_vec.rs` with **zero executable + edits** (checked by `refinement-checker` against `with-directives/raw_vec.rs` and + mechanically diff-checked against `../../raw_vec/mod.rs/verified/raw_vec.rs` via + `raw_vec_verified.patch`), differing only in **13** ghost-comment module-path + substitutions (`collections::`/`boxed::` for `--crate-name alloc`) and **1** verified + non-ZST postcondition strengthening on `RawVec::from_nonnull_in` + (`size_of::() == 0 || capacity_ == capacity`). +- `IntoIter::dealloc_only` and `IntoIter::forget_remaining_elements_and_dealloc` execute + the real `ManuallyDrop::take(&mut self.alloc)` -> `RawVec::from_nonnull_in` -> + `RawVec::drop` -> `RawVecInner::deallocate` deallocation chain against the verified + `RawVec` proof. + +The ownership predicate `>.own(t, it)` and shared predicate +`IntoIter_share_(k, t, l, len)` encode both layout regimes and Rust strict +provenance: + +- **Strict provenance invariant:** + `(it.end as pointer) == pointer_ctor((it.ptr.as_ptr() as pointer).provenance, it.end as usize, pointer_metadata_none)` + ensures `self.ptr.as_ptr() == self.end` if and only if `(ptr as usize) == (end as usize)`. + For a ZST iterator with base address `p = ptr.as_ptr() as usize`, wraparound produces + `end == null` at length `0usize.wrapping_sub(p)` (e.g., `len == usize::MAX` when + `p == 1` for 1-aligned ZSTs such as `()`; at `len == usize::MAX`, `end` has address + `p.wrapping_sub(1)`). +- **ZST regime (`size_of::() == 0`):** + `it.ptr.as_ptr()` is aligned (`addr % align_of::() == 0`, even while `it.end` may be + arbitrarily misaligned after byte-level `wrapping_byte_sub`), with + `array_at_lft(alloc_id.lft, it.ptr.as_ptr(), wrapping_sub_usize(it.end as usize, it.ptr.as_ptr() as usize), ?elems)` + and `foreach(elems, own::(t))` covering the full `0..=usize::MAX` length domain. +- **Non-ZST regime (`size_of::() > 0`):** + `IntoIter_non_zst_buf` partitions the `RawVec` allocation `buf[0..cap]` (with + `cap * size_of::() <= isize::MAX`) into three disjoint regions: + 1. `buf[0..adv]`: already-consumed prefix (`array_at_lft_`, uninitialized). + 2. `buf[adv..end_idx]`: live remaining elements (`array_at_lft` + `foreach(..., own::(t))`), + with `ptr == buf + adv` and `end == buf + end_idx` (non-null). + 3. `buf[end_idx..cap]`: already-consumed / spare suffix (`array_at_lft_`, uninitialized). +- **Shared observer state (`IntoIter_share_(k, t, l, len)`):** + Exposes the exact remaining length `len` together with `lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true` + and, for non-ZSTs, a fractional borrow `frac_borrow(k, IntoIter_shared_range(alloc_id.lft, v.ptr.as_ptr(), len, elems))` + carrying the live allocation witness `[f]array_at_lft(alloc_id.lft, ptr, len, elems)` + needed to justify `NonNull::offset_from_unsigned` on nonzero distances. + +### Verified Functions & Type Obligations + +Verified cleanly with **`0 errors found (2782 statements verified)`** in `verified/lib.rs` +(passing `refinement-checker` against `with-directives/lib.rs`) and **`0 errors found +(2916 statements verified)`** in `verified_try_fold/lib.rs` (adding `try_fold`): + +- **Type & variance obligations (`verified/into_iter.rs`):** `IntoIter_send`, + `IntoIter_sync`, `IntoIter_own_mono` (structural via `array_at_lft_own_mono` and + `Allocator_upcast`), `IntoIter_share_mono`, `IntoIter_share_full`, `init_ref_IntoIter`, + `IntoIter_share_val_fbc`, and `init_ref_IntoIter_share_` — all with **zero literal + `assume(false)`** in authored files. +- **Cleanup & `RawVec` deallocation bridge:** + - `IntoIter::forget_remaining_elements` + - `IntoIter::dealloc_only` (real `RawVec::from_nonnull_in` -> `RawVec::drop`) + - `IntoIter::forget_remaining_elements_and_dealloc` +- **Core iteration & exact observers:** + - `Iterator::next` (generic ``, ZST `0..=usize::MAX` + non-ZST arbitrary stride + with `LiveSlot` same-allocation witness on `NonNull::add(1)`) + - `DoubleEndedIterator::next_back` (generic ``, proving aligned `ptr::read(self.ptr.as_ptr())` + even when ZST `self.end` is misaligned + non-ZST `self.end.sub(1)` and `ptr::read(self.end)`) + - `Iterator::size_hint` (proves `result.0 == len && result.1 == Some(len)` against + `IntoIter_share_`, full ZST `0..=usize::MAX` + non-ZST `offset_from_unsigned` backed + by `LiveRange` live-allocation witness) + - `ExactSizeIterator::is_empty` (proves `result == (len == 0)` against `IntoIter_share_`) + - `verify_exact_size_len_from_size_hint__VeriFast_wrapper` (verified check that + `core::iter::ExactSizeIterator::len`'s default body calling our verified `size_hint` + returns `len`) +- **Unbounded folding loops (arbitrary `T`, `Drop`, stateful `FnMut`, and `Try`):** + - `Iterator::fold` (unbounded `while` loops for both ZST and non-ZST with `LiveSlot` + witness on `add(1)`, concluding with verified `self.forget_remaining_elements_and_dealloc()`) + - `Iterator::try_fold` (in `verified_try_fold/into_iter.rs`: unbounded `while` + loops for both ZST and non-ZST, proving `>.own(t, *self)` is preserved + on both `ControlFlow::Continue` and early-return `ControlFlow::Break`, carrying + value-indexed `TryRes(t, typeid(R), res)` from `Try::branch` into `FromResidual::from_residual` + with no unsupported no-unwind promises on user `Try` trait methods) +- **Bulk advancement & arbitrary `Drop`:** + - `Iterator::advance_by` (builds a scoped `IntoIter_share_` borrow via `begin_lifetime` / + `borrow` / `IntoIter_share_val_fbc` / `end_lifetime`, derives `step_size = min(len, n)` + via `exact_size_len` + `usize_min`, verifies `NonNull::add(step_size)` with `LiveRange` + live-allocation witness for nonzero `step_size`, and executes real `ptr::drop_in_place`) + - `DoubleEndedIterator::advance_back_by` (same scoped `IntoIter_share_` length derivation, + aligned `NonNull::::dangling()` move via inductive `zst_array_at_lft_move` for ZSTs, + `self.end.sub(step_size)` for non-ZSTs, and real `ptr::drop_in_place`) + +## Scope & Correspondence + +1. **Producer / constructor scope:** This VeriFast crate verifies `library/alloc/src/vec/into_iter.rs` + for any iterator satisfying `>.own(t, it)`. The standalone harness + `original/lib.rs` stubs `Vec::into_iter` as `loop {}` because `Vec::into_iter` resides + in `library/alloc/src/vec/mod.rs` (exercised separately in the Kani suite in + `library/alloc/src/vec/verify_iter_spec.rs`). +2. **Justification of `with-directives.patch` (5 lines):** + VeriFast 26.10's `refinement-checker` currently reports `RawPtr: not yet supported` on + `&raw const $place` (`into_iter.rs:34`) and `TODO: Alias` on `Self::Item` (`into_iter.rs:497, 551`). + Accordingly, `original/into_iter.rs` stays 100% byte-for-byte identical to + `library/alloc/src/vec/into_iter.rs` (type-checked by `rustc +nightly-2026-09-25` in + `verify.sh`), and `with-directives/into_iter.rs` applies only the 5-line syntax patch + mechanically enforced against `with-directives.patch`: + - `non_null!` (`&raw const $place` -> `&$place as *const *const $t`): every invocation + of `non_null!(self.end, T)` in `into_iter.rs` (all 6 sites: `:406`, `:424`, `:529`, + `:584`, `:630`, `:712`) applies to the `self.end: *const T` field accessed via + `&self`, `&mut self`, or the owned `mut self` in `fold`. That field is always + aligned, initialized, and free of conflicting active mutable aliases at every macro + site, so creating a transient `&self.end` reference introduces no additional validity + or aliasing UB relative to `&raw const self.end`. + - `Self::Item` -> `T` in `fold`/`try_fold` `where` clauses (type alias identity). + - `&mut self` -> `/*@~mut@*/ self: &mut Self` on `advance_by`/`advance_back_by` + (standard VeriFast `~mut` directive). +3. **`verified_try_fold/` `?` desugaring check:** + `refinement-checker` hits `TODO: Alias` on `R::Residual` in `try_fold`'s `?` operator + (`FromResidual::from_residual::`). `verified_try_fold/into_iter.rs` + desugars `f(accum, tmp)?` using Rust's exact `Try` v2 desugaring + (`match Try::branch(step) { ControlFlow::Continue(v) => v, ControlFlow::Break(res) => return FromResidual::from_residual(res) }`), + is type-checked by `rustc +nightly-2026-09-25` in `verify.sh`, and is mechanically + enforced via `try_fold.patch` to differ from `verified/into_iter.rs` only in `try_fold` + and its 4 1-line `Try` wrappers. + +## Trust Inventory + +### Inherited Trust (Accepted Challenge 19 `verifast-proofs/alloc/raw_vec/mod.rs`, PR `#422`) & VeriFast Prelude + +| Item | Location | Dependency | +|---|---|---| +| `assume(false)` in `RawVec_own_mono` & `RawVecInner_own_mono` (2 sites) | `verified/raw_vec.rs:199, 751` | Inherited Ch. 19 variance obligations (`verifast#610`); not called by any `IntoIter` method | +| Ch. 19 `RawVec` / `RawVecInner` `assume_correct` wrappers & VeriFast `std/lib.rsspec` prelude (including built-in `<*const T>::sub`) | `verified/raw_vec.rs`, VeriFast `std/lib.rsspec` | `dealloc_only`, `forget_remaining_elements_and_dealloc`, `fold`, and `self.end.sub(..)` in `next_back` / `advance_back_by` | + +### Newly Authored Trust (`0` literal `assume(false)` across `verified/lib.rs`, `verified/into_iter.rs`, `verified_try_fold/into_iter.rs`) + +| Item | Location | Dependency | +|---|---|---| +| `Box::from_raw_in` (`assume_correct` stub + bodyless `pred Box_in`) | `verified/lib.rs:75-103` | Assumed stub + bodyless `Box_in`; reachable only from inherited `RawVec::into_box` (which no `IntoIter` method calls) | +| 4 explicit `assume(...)` axioms: `array_at_lft_own_mono` (`of_u8s_` byte preservation under `T0 <: T1`, `verifast#610`), `IntoIter_send` (`is_Send`), `IntoIter_own_mono` (subtype layout/field identity, `verifast#610`), `IntoIter_sync` (`is_Sync`) | `verified/into_iter.rs` | Crate-level type-system obligations only; not invoked by any target method proof | +| `tuple_ext::close_tuple_2_own` (bodyless lemma mirroring `close_tuple_4_own` in VeriFast 26.10 `prelude.rsspec:40`) | `tuple_ext.rsspec` | `size_hint`'s `safety_proof` only | +| `std_ext.rsspec` (`trait Try { type Output; type Residual; }`) | `std_ext.rsspec` | Type declarations only (0 lemmas, 0 assumptions); `verified_try_fold` only | +| `ManuallyDrop::take`, `wrapping_byte_sub(1 / count)` (wrapped `0..=usize::MAX` address + preserved provenance, no `pointer_within_limits` claim), `cast_mut`, `cast::().cast_mut()`, `ptr_eq_end`/`ptr_ne_end` (requiring matching provenance), `non_null_from_end`, `addr`, `NonNull::dangling`, `NonNull::read`, `NonZero::new(..).map_or`, `usize::min` (`*_VeriFast_wrapper`, inlined by `refinement-checker`) | `verified/into_iter.rs` | 1-line `core` primitives absent from VeriFast 26.10 `std/lib.rsspec`; used by corresponding target methods | +| `non_null_add_1`, `non_null_add`, `non_null_offset_from_unsigned` (`*_VeriFast_wrapper`, inlined by `refinement-checker`) | `verified/into_iter.rs` | Require `LiveSlot` / `LiveRange` live same-allocation witnesses for every nonzero distance (handling `0`-distance separately); used by `next`, `size_hint`, `advance_by`, `fold`, `try_fold` | +| `exact_size_len__VeriFast_wrapper` (`it.len()`) | `verified/into_iter.rs` | Models `&mut I` forwarding + `core::iter::ExactSizeIterator::len` default body (`assert_eq!`); requires `[_]IntoIter_share_(k, t, p, ?len)` and returns `len`, matching verified `verify_exact_size_len_from_size_hint__VeriFast_wrapper`; used by `advance_by`, `advance_back_by` | +| `call_fold` (`verified/into_iter.rs`, inlined by `refinement-checker`); `call_try_fn`, `try_branch`, `try_from_residual`, `try_from_output` (`verified_try_fold/into_iter.rs`, verified by VeriFast + `rustc`) | `verified/into_iter.rs`, `verified_try_fold/into_iter.rs` | User closure / `Try` trait boundaries; `try_branch` -> `try_from_residual` carries value-indexed `TryRes(t, typeid(R), res)` with no `on_unwind_ens false` promise; used by `fold` / `try_fold` | + +## Caveats + +1. **VeriFast flags:** Verified with `-skip_specless_fns -ignore_unwind_paths -allow_assume`: + - `-skip_specless_fns`: Unspecified methods (such as `Clone`, `Debug`, `next_chunk`, + `as_raw_mut_slice`, and `IntoIter::drop`'s nested `DropGuard`) are skipped by VeriFast + and verified by the Kani harness suite in `library/alloc/src/vec/verify_iter_spec.rs`. + Note that `dealloc_only`, `forget_remaining_elements_and_dealloc`, `advance_by`, and + `advance_back_by` verify the same `ptr::drop_in_place` + `ManuallyDrop::take` + + `RawVec::from_nonnull_in` deallocation path. + - `-ignore_unwind_paths`: Panic/unwind paths are not verified by VeriFast (normal-path + ownership and memory safety only). +2. **Zero-dependency `safety_stub.rs`:** + `library/alloc/src/vec/into_iter.rs` imports `safety::{loop_invariant, requires}` for + Kani loop invariants; `verify.sh` compiles the 12-line pass-through `safety_stub.rs` + proc-macro into a temporary directory so untouched `original/into_iter.rs` compiles cleanly. +3. **Target & tool soundness:** As with `linked_list.rs`, `raw_vec/mod.rs`, and + `extract_if.rs`, VeriFast verifies against the `rustc` target architecture and relies + on VeriFast's symbolic execution engine and prelude specs. + +## Attribution & License + +- **Bridged `RawVec` proof (`raw_vec.rs`):** Adapted with zero executable edits from + accepted Challenge 19 ([`verifast-proofs/alloc/raw_vec/mod.rs`](../../raw_vec/mod.rs/), + `model-checking/verify-rust-std` PR #422). +- **VeriFast ownership/sharing & lifetime-trade idioms:** Informed by VeriFast 26.10 + (`tests/rust/safe_abstraction/vec/` and `bin/rust/std/lib.rsspec`, MIT License, + Copyright VeriFast contributors / KU Leuven) and + [`verifast-proofs/alloc/collections/linked_list.rs`](../../collections/linked_list.rs/). +- **Newly authored in this Challenge 24 PR:** + - Strict-provenance `>.own` / `IntoIter_share_(k, t, l, len)` / + `IntoIter_shared_range` predicates and `LiveSlot` / `LiveRange` live-allocation + contracts over lifetime-indexed `RawVec` storage, supporting full `0..=usize::MAX` + ZSTs and arbitrary non-ZST strides. + - Full unbounded polymorphic proofs of `forget_remaining_elements`, `dealloc_only`, + `forget_remaining_elements_and_dealloc`, `next`, `next_back`, `size_hint`, `is_empty`, + `verify_exact_size_len_from_size_hint`, `fold`, `try_fold`, `advance_by`, and + `advance_back_by` (including inductive `zst_array_at_lft_move` and `wrapping_sub_usize_*` + lemmas). + - Structural zero-`assume(false)` type obligations (`IntoIter_send`, `IntoIter_sync`, + `IntoIter_own_mono`, `IntoIter_share_mono`, `IntoIter_share_full`, `init_ref_IntoIter`) + and `TryReserveError` ownership/sharing proofs in `verified/lib.rs`. + - Companion negative mutation suite ([`into_iter.rs-negative`](../into_iter.rs-negative/)). diff --git a/verifast-proofs/alloc/vec/into_iter.rs/original/into_iter.rs b/verifast-proofs/alloc/vec/into_iter.rs/original/into_iter.rs new file mode 100644 index 0000000000000..74830f3475af3 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/original/into_iter.rs @@ -0,0 +1,825 @@ +use core::iter::{ + FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, + TrustedRandomAccessNoCoerce, +}; +#[cfg(kani)] +use core::kani; +use core::marker::PhantomData; +use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties}; +use core::num::NonZero; +#[cfg(not(no_global_oom_handling))] +use core::ops::Deref; +use core::panic::UnwindSafe; +use core::ptr::{self, NonNull}; +use core::{array, fmt, slice}; + +use safety::{loop_invariant, requires}; + +#[cfg(not(no_global_oom_handling))] +use super::AsVecIntoIter; +use crate::alloc::{Allocator, Global}; +#[cfg(not(no_global_oom_handling))] +use crate::collections::VecDeque; +use crate::raw_vec::RawVec; + +macro non_null { + (mut $place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { &mut *((&raw mut $place) as *mut NonNull<$t>) } + }}, + ($place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { *((&raw const $place) as *const NonNull<$t>) } + }}, +} + +/// An iterator that moves out of a vector. +/// +/// This `struct` is created by the `into_iter` method on [`Vec`](super::Vec) +/// (provided by the [`IntoIterator`] trait). +/// +/// # Example +/// +/// ``` +/// let v = vec![0, 1, 2]; +/// let iter: std::vec::IntoIter<_> = v.into_iter(); +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_insignificant_dtor] +pub struct IntoIter< + T, + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] A: Allocator = Global, +> { + pub(super) buf: NonNull, + pub(super) phantom: PhantomData, + pub(super) cap: usize, + // the drop impl reconstructs a RawVec from buf, cap and alloc + // to avoid dropping the allocator twice we need to wrap it into ManuallyDrop + pub(super) alloc: ManuallyDrop, + pub(super) ptr: NonNull, + /// If T is a ZST, this is actually ptr+len. This encoding is picked so that + /// ptr == end is a quick test for the Iterator being empty, that works + /// for both ZST and non-ZST. + /// For non-ZSTs the pointer is treated as `NonNull` + pub(super) end: *const T, +} + +// Manually mirroring what `Vec` has, +// because otherwise we get `T: RefUnwindSafe` from `NonNull`. +#[stable(feature = "catch_unwind", since = "1.9.0")] +impl UnwindSafe for IntoIter {} + +#[stable(feature = "vec_intoiter_debug", since = "1.13.0")] +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("IntoIter").field(&self.as_slice()).finish() + } +} + +impl IntoIter { + /// Returns the remaining items of this iterator as a slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// let _ = into_iter.next().unwrap(); + /// assert_eq!(into_iter.as_slice(), &['b', 'c']); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_slice(&self) -> &[T] { + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len()) } + } + + /// Returns the remaining items of this iterator as a mutable slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// into_iter.as_mut_slice()[2] = 'z'; + /// assert_eq!(into_iter.next().unwrap(), 'a'); + /// assert_eq!(into_iter.next().unwrap(), 'b'); + /// assert_eq!(into_iter.next().unwrap(), 'z'); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_mut_slice(&mut self) -> &mut [T] { + // ignore-tidy-undocumented-unsafe + unsafe { &mut *self.as_raw_mut_slice() } + } + + /// Returns a reference to the underlying allocator. + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] + #[inline] + pub fn allocator(&self) -> &A { + &self.alloc + } + + fn as_raw_mut_slice(&mut self) -> *mut [T] { + self.ptr.as_ptr().cast_slice(self.len()) + } + + /// Drops remaining elements and relinquishes the backing allocation. + /// + /// This method guarantees it won't panic before relinquishing the backing + /// allocation. + /// + /// This is roughly equivalent to the following, but more efficient + /// + /// ``` + /// # let mut vec = Vec::::with_capacity(10); + /// # let ptr = vec.as_mut_ptr(); + /// # let mut into_iter = vec.into_iter(); + /// let mut into_iter = std::mem::replace(&mut into_iter, Vec::new().into_iter()); + /// (&mut into_iter).for_each(drop); + /// std::mem::forget(into_iter); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # drop(unsafe { Vec::::from_raw_parts(ptr, 0, 10) }); + /// ``` + /// + /// This method is used by in-place iteration, refer to the vec::in_place_collect + /// documentation for an overview. + #[cfg(not(no_global_oom_handling))] + pub(super) fn forget_allocation_drop_remaining(&mut self) { + let remaining = self.as_raw_mut_slice(); + + // overwrite the individual fields instead of creating a new + // struct and then overwriting &mut self. + // this creates less assembly + self.cap = 0; + self.buf = RawVec::new().non_null(); + self.ptr = self.buf; + self.end = self.buf.as_ptr(); + + // Dropping the remaining elements can panic, so this needs to be + // done only after updating the other fields. + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(remaining); + } + } + + /// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed. + /// + /// This method does not consume `self`, and leaves deallocation to `impl Drop for IntoIter`. + /// If consuming `self` is possible, consider calling + /// [`Self::forget_remaining_elements_and_dealloc()`] instead. + pub(crate) fn forget_remaining_elements(&mut self) { + // For the ZST case, it is crucial that we mutate `end` here, not `ptr`. + // `ptr` must stay aligned, while `end` may be unaligned. + self.end = self.ptr.as_ptr(); + } + + /// Forgets to Drop the remaining elements and frees the backing allocation. + /// Consuming version of [`Self::forget_remaining_elements()`]. + /// + /// This can be used in place of `drop(self)` when `self` is known to be exhausted, + /// to avoid producing a needless `drop_in_place::<[T]>()`. + #[inline] + pub(crate) fn forget_remaining_elements_and_dealloc(self) { + let mut this = ManuallyDrop::new(self); + // SAFETY: `this` is in ManuallyDrop, so it will not be double-freed. + unsafe { + this.dealloc_only(); + } + } + + /// Frees the allocation, without checking or dropping anything else. + /// + /// The safe version of this method is [`Self::forget_remaining_elements_and_dealloc()`]. + /// This function exists only to share code between that method and the `impl Drop`. + /// + /// # Safety + /// + /// This function must only be called with an [`IntoIter`] that is not going to be dropped + /// or otherwise used in any way, either because it is being forgotten or because its `Drop` + /// is already executing; otherwise a double-free will occur, and possibly a read from freed + /// memory if there are any remaining elements. + #[inline] + unsafe fn dealloc_only(&mut self) { + // SAFETY: our caller promises not to touch `*self` again. + let alloc = unsafe { ManuallyDrop::take(&mut self.alloc) }; + // SAFETY: We're using this to deallocate a preexisting `RawVec`. + let _ = unsafe { RawVec::from_nonnull_in(self.buf, self.cap, alloc) }; + } + + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn into_vecdeque(self) -> VecDeque { + // Keep our `Drop` impl from dropping the elements and the allocator + let mut this = ManuallyDrop::new(self); + + let buf = this.buf.as_ptr(); + let initialized = if T::IS_ZST || this.len() == 0 { + // All the pointers are the same for ZSTs, so it's fine to + // say that they're all at the beginning of the "allocation". + // For non-ZSTs, we have length 0, so we can choose the (empty) + // range to be at the start of the buffer. + // + // Due to `0` ≤ `this.len()` ≤ `this.cap`, the range is well-formed, + // and due to the argument above it spans exactly the elements of + // this iterator. Because `init.start` = `0`, it follows that either + // `init.start` < `cap` or `cap` = `init.start` = `0`; thus the range + // satisfies the requirements of `from_contiguous_raw_parts_in`. + 0..this.len() + } else { + // SAFETY: `this.ptr` and `this.end` are created via offsets of `this.buf`, + // so they point to the same allocation. We have `this.buf` ≤ `this.ptr` ≤ `this.end`, + // so this cannot wrap, and will produce a well-formed range that spans exactly + // the elements of this iterator. + // + // Additionally, due to `end ≤ buf + cap`, we have `init.start` ≤ `init.end` ≤ `cap`. + // Due to the length check above, `init.start < cap`, so the range satisfies the + // requirements of `from_contiguous_raw_parts_in`. + unsafe { this.ptr.offset_from_unsigned(this.buf)..this.end.offset_from_unsigned(buf) } + }; + + let cap = this.cap; + // SAFETY: `this` is forgotten afterwards, so we can move out the allocator. + let alloc = unsafe { ManuallyDrop::take(&mut this.alloc) }; + + // SAFETY: This allocation originally came from a `Vec`, so it satisfies all + // requirements for the `buf` pointer with capacity `cap` allocated in `alloc`. + // Correctness of `initialized` was shown above. + unsafe { VecDeque::from_contiguous_raw_parts_in(buf, initialized, cap, alloc) } + } +} + +#[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")] +impl AsRef<[T]> for IntoIter { + fn as_ref(&self) -> &[T] { + self.as_slice() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for IntoIter {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for IntoIter {} + +// Loop-invariant predicates for `IntoIter::fold` and `IntoIter::try_fold`. +// Marked `#[inline(always)]` and written with pure intrinsics and `const { ... }` +// blocks rather than method calls (e.g. `NonNull::as_ptr` / `pointer::addr` / +// non-const `mem::size_of`) so Kani's loop-contract lowering evaluates them +// inline as side-effect-free CBMC expressions without emitting nondeterministic +// helper calls (https://github.com/model-checking/kani/issues/4796). +// `self.alloc` is untouched by either loop and is preserved across loop +// contracts (verified with both `TrackAlloc` and non-ZST `StatefulAlloc`). +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, and `usize` have identical layout (thin pointer width); + // these casts are side-effect-free re-interpretations for CBMC's loop-invariant evaluator. + let (ptr_p, eptr_p, buf_p, ebuf_p, ptr_a, eptr_a, end_a, eend_a): ( + *const T, + *const T, + *const T, + *const T, + usize, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + core::intrinsics::transmute_unchecked(entry_end), + ) + }; + ptr_p == eptr_p + && buf_p == ebuf_p + && cap == entry_cap + && core::intrinsics::wrapping_sub(end_a, ptr_a) + <= core::intrinsics::wrapping_sub(eend_a, eptr_a) +} + +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_non_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, `*const u8`, and `usize` have identical thin-pointer + // layout; used to avoid method calls in CBMC loop-contract predicates (kani#4796). + let (buf_p, ebuf_p, ptr_p, eptr_u8, ptr_a, eptr_a, end_a): ( + *const T, + *const T, + *const T, + *const u8, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + ) + }; + let diff = core::intrinsics::wrapping_sub(ptr_a, eptr_a); + let span = core::intrinsics::wrapping_sub(end_a, eptr_a); + let sz = const { core::mem::size_of::() }; + let aligned = if const { core::mem::size_of::().is_power_of_two() } { + (diff & core::intrinsics::wrapping_sub(sz, 1)) == 0 + } else { + // Exact divisibility `diff % sz == 0` for any non-power-of-two `sz > 0` without a + // 64-bit integer division circuit: write `sz = odd * 2^tz` and compute the modular + // multiplicative inverse `odd_inv` (`odd * odd_inv == 1 mod 2^BITS`) at const time. + // Then `sz | diff` iff `2^tz | diff` and `(diff >> tz) * odd_inv <= usize::MAX / sz`. + let (tz, odd_inv, max_q) = const { + let s = core::mem::size_of::(); + if s == 0 { + (0u32, 1usize, 0usize) + } else { + let tz = s.trailing_zeros(); + let odd = s >> tz; + let mut inv: usize = 1; + let mut i = 0; + while i < 6 { + inv = inv.wrapping_mul(2usize.wrapping_sub(odd.wrapping_mul(inv))); + i += 1; + } + assert!(odd.wrapping_mul(inv) == 1); + (tz, inv, usize::MAX / s) + } + }; + let low_mask = core::intrinsics::wrapping_sub(1usize << tz, 1); + (diff & low_mask) == 0 && core::intrinsics::wrapping_mul(diff >> tz, odd_inv) <= max_q + }; + // SAFETY: `arith_offset` is wrapping (non-UB) pointer arithmetic; short-circuiting after + // `diff <= span && aligned` additionally guarantees `diff` stays within `[entry_ptr, end]`. + buf_p == ebuf_p + && cap == entry_cap + && end == entry_end + && diff <= span + && aligned + && ptr_p == unsafe { core::intrinsics::arith_offset(eptr_u8, diff as isize) as *const T } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Iterator for IntoIter { + type Item = T; + + #[inline] + fn next(&mut self) -> Option { + let ptr = if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut T { + return None; + } + // `ptr` has to stay where it is to remain aligned, so we reduce the length by 1 by + // reducing the `end`. + self.end = self.end.wrapping_byte_sub(1); + self.ptr + } else { + if self.ptr == non_null!(self.end, T) { + return None; + } + let old = self.ptr; + // ignore-tidy-undocumented-unsafe + self.ptr = unsafe { old.add(1) }; + old + }; + // ignore-tidy-undocumented-unsafe + Some(unsafe { ptr.read() }) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + let exact = if T::IS_ZST { + self.end.addr().wrapping_sub(self.ptr.as_ptr().addr()) + } else { + // ignore-tidy-undocumented-unsafe + unsafe { non_null!(self.end, T).offset_from_unsigned(self.ptr) } + }; + (exact, Some(exact)) + } + + #[inline] + fn advance_by(&mut self, n: usize) -> Result<(), NonZero> { + let step_size = self.len().min(n); + let to_drop = self.ptr.as_ptr().cast_slice(step_size); + if T::IS_ZST { + // See `next` for why we sub `end` here. + self.end = self.end.wrapping_byte_sub(step_size); + } else { + // SAFETY: the min() above ensures that step_size is in bounds + self.ptr = unsafe { self.ptr.add(step_size) }; + } + // SAFETY: the min() above ensures that step_size is in bounds + unsafe { + ptr::drop_in_place(to_drop); + } + NonZero::new(n - step_size).map_or(Ok(()), Err) + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + #[inline] + fn last(mut self) -> Option { + self.next_back() + } + + #[inline] + fn next_chunk(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { raw_ary.transpose().assume_init() }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available and we + // just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, N); + self.ptr = self.ptr.add(N); + Ok(raw_ary.transpose().assume_init()) + } + } + + #[inline] + fn fold(mut self, mut accum: B, mut f: F) -> B + where + F: FnMut(B, Self::Item) -> B, + { + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr.as_ptr() != self.end.cast_mut() { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // See `next` for why we subtract from `end` here. + self.end = self.end.wrapping_byte_sub(1); + accum = f(accum, tmp); + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr != non_null!(self.end, T) { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { self.ptr.add(1) }; + accum = f(accum, tmp); + } + } + + // There are in fact no remaining elements to forget, but by doing this we can avoid + // potentially generating a needless loop to drop the elements that cannot exist at + // this point. + self.forget_remaining_elements_and_dealloc(); + + accum + } + + #[inline] + fn try_fold(&mut self, mut accum: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: core::ops::Try, + { + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr.as_ptr() != self.end.cast_mut() { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // See `next` for why we subtract from `end` here. + self.end = self.end.wrapping_byte_sub(1); + accum = f(accum, tmp)?; + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr != non_null!(self.end, T) { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { self.ptr.add(1) }; + accum = f(accum, tmp)?; + } + } + R::from_output(accum) + } + + #[requires(i < self.len())] + #[cfg_attr(kani, kani::modifies(self))] + unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item + where + Self: TrustedRandomAccessNoCoerce, + { + // SAFETY: the caller must guarantee that `i` is in bounds of the + // `Vec`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)` + // is guaranteed to pointer to an element of the `Vec` and + // thus guaranteed to be valid to dereference. + // + // Also note the implementation of `Self: TrustedRandomAccess` requires + // that `T: Copy` so reading elements from the buffer doesn't invalidate + // them for `Drop`. + unsafe { self.ptr.add(i).read() } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl DoubleEndedIterator for IntoIter { + #[inline] + fn next_back(&mut self) -> Option { + if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut _ { + return None; + } + // See above for why 'ptr.offset' isn't used + self.end = self.end.wrapping_byte_sub(1); + // Note that even though this is next_back() we're reading from `self.ptr`, not + // `self.end`. We track our length using the byte offset from `self.ptr` to `self.end`, + // so the end pointer may not be suitably aligned for T. + // ignore-tidy-undocumented-unsafe + Some(unsafe { ptr::read(self.ptr.as_ptr()) }) + } else { + if self.ptr == non_null!(self.end, T) { + return None; + } + // ignore-tidy-undocumented-unsafe + unsafe { + self.end = self.end.sub(1); + Some(ptr::read(self.end)) + } + } + } + + #[inline] + fn next_chunk_back(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, N - len..N) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { MaybeUninit::array_assume_init(raw_ary) }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available + // and we just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping( + self.ptr.add(len - N).as_ptr(), + raw_ary.as_mut_ptr() as *mut T, + N, + ); + self.end = self.end.sub(N); + Ok(MaybeUninit::array_assume_init(raw_ary)) + } + } + + #[inline] + fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero> { + let step_size = self.len().min(n); + if T::IS_ZST { + // SAFETY: same as for advance_by() + self.end = self.end.wrapping_byte_sub(step_size); + } else { + // SAFETY: same as for advance_by() + self.end = unsafe { self.end.sub(step_size) }; + } + let to_drop = if T::IS_ZST { + // ZST may cause unalignment + ptr::NonNull::::dangling().as_ptr().cast_slice(step_size) + } else { + self.end.cast::().cast_mut().cast_slice(step_size) + }; + // SAFETY: same as for advance_by() + unsafe { + ptr::drop_in_place(to_drop); + } + NonZero::new(n - step_size).map_or(Ok(()), Err) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ExactSizeIterator for IntoIter { + fn is_empty(&self) -> bool { + if T::IS_ZST { + self.ptr.as_ptr() == self.end as *mut _ + } else { + self.ptr == non_null!(self.end, T) + } + } +} + +#[stable(feature = "fused", since = "1.26.0")] +impl FusedIterator for IntoIter {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "trusted_fused")] +unsafe impl TrustedFused for IntoIter {} + +#[unstable(feature = "trusted_len", issue = "37572")] +unsafe impl TrustedLen for IntoIter {} + +#[stable(feature = "default_iters", since = "1.70.0")] +impl Default for IntoIter +where + A: Allocator + Default, +{ + /// Creates an empty `vec::IntoIter`. + /// + /// ``` + /// # use std::vec; + /// let iter: vec::IntoIter = Default::default(); + /// assert_eq!(iter.len(), 0); + /// assert_eq!(iter.as_slice(), &[]); + /// ``` + fn default() -> Self { + super::Vec::new_in(Default::default()).into_iter() + } +} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +#[unsafe(rustc_allow_lifetime_dependent_specialization)] +trait NonDrop {} + +// T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr +// and thus we can't implement drop-handling +#[unstable(issue = "none", feature = "std_internals")] +impl NonDrop for T {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +// TrustedRandomAccess (without NoCoerce) must not be implemented because +// subtypes/supertypes of `T` might not be `NonDrop` +unsafe impl TrustedRandomAccessNoCoerce for IntoIter +where + T: NonDrop, +{ + const MAY_HAVE_SIDE_EFFECT: bool = false; +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_into_iter_clone", since = "1.8.0")] +impl Clone for IntoIter { + fn clone(&self) -> Self { + self.as_slice().to_vec_in(self.alloc.deref().clone()).into_iter() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter { + fn drop(&mut self) { + struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter); + + impl Drop for DropGuard<'_, T, A> { + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + self.0.dealloc_only(); + } + } + } + + let guard = DropGuard(self); + // destroy the remaining elements + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(guard.0.as_raw_mut_slice()); + } + // now `guard` will be dropped and do the rest + } +} + +// In addition to the SAFETY invariants of the following three unsafe traits +// also refer to the vec::in_place_collect module documentation to get an overview +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl InPlaceIterable for IntoIter { + const EXPAND_BY: Option> = NonZero::new(1); + const MERGE_BY: Option> = NonZero::new(1); +} + +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl SourceIter for IntoIter { + type Source = Self; + + #[inline] + unsafe fn as_inner(&mut self) -> &mut Self::Source { + self + } +} + +#[cfg(not(no_global_oom_handling))] +unsafe impl AsVecIntoIter for IntoIter { + type Item = T; + + fn as_into_iter(&mut self) -> &mut IntoIter { + self + } +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs/original/lib.rs b/verifast-proofs/alloc/vec/into_iter.rs/original/lib.rs new file mode 100644 index 0000000000000..05d154c64bf50 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/original/lib.rs @@ -0,0 +1,168 @@ +// verifast_options{skip_specless_fns} + +#![allow(dead_code)] +#![no_std] +#![allow(internal_features)] +#![allow(incomplete_features)] +#![feature(allocator_ext)] +#![feature(staged_api)] +#![feature(rustc_attrs)] +#![feature(dropck_eyepatch)] +#![feature(specialization)] +#![feature(extend_one)] +#![feature(exact_size_is_empty)] +#![feature(hasher_prefixfree_extras)] +#![feature(try_trait_v2)] +#![feature(optimize_attribute)] +#![feature(temporary_niche_types)] +#![feature(ptr_internals)] +#![feature(ptr_alignment_type)] +#![feature(ptr_cast_slice)] +#![feature(const_closures)] +#![feature(const_result_trait_fn)] +#![feature(sized_type_properties)] +#![feature(std_internals)] +#![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_destruct)] +#![feature(const_heap)] +#![feature(const_option_ops)] +#![feature(const_trait_impl)] +#![feature(const_try)] +#![feature(panic_internals)] +#![feature(decl_macro)] +#![feature(trusted_len)] +#![feature(trusted_fused)] +#![feature(trusted_random_access)] +#![feature(inplace_iteration)] +#![feature(iter_next_chunk)] +#![feature(iter_advance_by)] +#![feature(array_into_iter_constructors)] +#![feature(maybe_uninit_array_assume_init)] +#![feature(maybe_uninit_uninit_array_transpose)] +#![feature(proc_macro_hygiene)] +#![feature(stmt_expr_attributes)] +#![feature(lang_items)] + +#![stable(feature = "rust1", since = "1.0.0")] + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod alloc { + #[stable(feature = "rust1", since = "1.0.0")] + pub use core::alloc::*; + use core::ptr::NonNull; + + #[stable(feature = "rust1", since = "1.0.0")] + #[derive(Copy, Clone, Default, Debug)] + #[lang = "global_alloc_ty"] + pub struct Global; + + #[stable(feature = "rust1", since = "1.0.0")] + unsafe impl Allocator for Global { + fn allocate(&self, _layout: Layout) -> Result, AllocError> { loop {} } + unsafe fn deallocate(&self, _ptr: NonNull, _layout: Layout) { loop {} } + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_alloc_error", issue = "none")] + pub const fn handle_alloc_error(_layout: Layout) -> ! { loop {} } +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod boxed { + use core::ptr::Unique; + use crate::alloc::{Allocator, Global}; + + #[stable(feature = "rust1", since = "1.0.0")] + #[lang = "owned_box"] + pub struct Box(Unique, A); + + impl Box { + #[stable(feature = "rust1", since = "1.0.0")] + pub unsafe fn from_raw_in(_raw: *mut T, _alloc: A) -> Self { loop {} } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod collections { + use core::marker::PhantomData; + use crate::alloc::{Allocator, Global, Layout}; + + #[stable(feature = "rust1", since = "1.0.0")] + #[derive(Copy, Clone, PartialEq, Eq, Debug)] + pub struct TryReserveError { + kind: TryReserveErrorKind, + } + + impl TryReserveError { + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_try_reserve", issue = "none")] + pub(crate) const fn kind(&self) -> TryReserveErrorKind { + self.kind + } + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[derive(Copy, Clone, PartialEq, Eq, Debug)] + pub enum TryReserveErrorKind { + CapacityOverflow, + AllocError { layout: Layout, non_exhaustive: () }, + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_convert", issue = "143773")] + const impl From for TryReserveError { + fn from(kind: TryReserveErrorKind) -> Self { let r = Self { kind }; r } + } + + #[stable(feature = "rust1", since = "1.0.0")] + pub struct VecDeque(PhantomData<(T, A)>); + + impl VecDeque { + #[stable(feature = "rust1", since = "1.0.0")] + pub(crate) unsafe fn from_contiguous_raw_parts_in( + _ptr: *mut T, + _initialized: core::ops::Range, + _cap: usize, + _alloc: A, + ) -> Self { loop {} } + } +} + +impl [T] { + #[rustc_allow_incoherent_impl] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn to_vec_in(&self, _alloc: A) -> crate::Vec + where + T: Clone, + { + loop {} + } +} + +pub mod raw_vec; +#[stable(feature = "rust1", since = "1.0.0")] +pub mod into_iter; + +#[stable(feature = "rust1", since = "1.0.0")] +pub(crate) unsafe trait AsVecIntoIter { + type Item; + fn as_into_iter(&mut self) -> &mut into_iter::IntoIter; +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub struct Vec { + buf: raw_vec::RawVec, + len: usize, +} + +impl Vec { + #[stable(feature = "rust1", since = "1.0.0")] + pub fn new_in(alloc: A) -> Self { + Self { buf: raw_vec::RawVec::new_in(alloc), len: 0 } + } + #[stable(feature = "rust1", since = "1.0.0")] + pub fn into_iter(self) -> into_iter::IntoIter { + loop {} + } +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs/original/raw_vec.rs b/verifast-proofs/alloc/vec/into_iter.rs/original/raw_vec.rs new file mode 120000 index 0000000000000..970be0fb97087 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/original/raw_vec.rs @@ -0,0 +1 @@ +../../../raw_vec/mod.rs/original/raw_vec.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs/raw_vec_verified.patch b/verifast-proofs/alloc/vec/into_iter.rs/raw_vec_verified.patch new file mode 100644 index 0000000000000..1231e1d0f0c99 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/raw_vec_verified.patch @@ -0,0 +1,109 @@ +--- raw_vec/mod.rs/verified/raw_vec.rs ++++ verified/raw_vec.rs +@@ -23,7 +23,7 @@ + use crate::collections::TryReserveError; + use crate::collections::TryReserveErrorKind::*; + +-//@ use std::collections::{TryReserveError, TryReserveErrorKind}; ++//@ use collections::{TryReserveError, TryReserveErrorKind}; + + #[cfg(test)] + mod tests; +@@ -1255,7 +1255,7 @@ + /// an allocator could overallocate and return a greater memory block than requested. + pub(crate) unsafe fn into_box(mut self, len: usize) -> Box<[MaybeUninit], A> + //@ req thread_token(?t) &*& RawVec(t, self, ?alloc_id, ?ptr, ?capacity_) &*& array_at_lft_(alloc_id.lft, ptr as *T, len, ?vs) &*& if std::mem::size_of::() == 0 { true } else { len == capacity_ }; +- //@ ens thread_token(t) &*& std::boxed::Box_in::<[std::mem::MaybeUninit], A>(t, result, alloc_id, slice_of_elems(map(std::mem::MaybeUninit::new_maybe_uninit, vs))); ++ //@ ens thread_token(t) &*& boxed::Box_in::<[std::mem::MaybeUninit], A>(t, result, alloc_id, slice_of_elems(map(std::mem::MaybeUninit::new_maybe_uninit, vs))); + //@ on_unwind_ens thread_token(t); + { + //@ RawVec_inv2(); +@@ -1390,7 +1390,7 @@ + alloc_block_in(alloc_id, ptr.as_ptr() as *u8, allocLayout) + }; + @*/ +- //@ ens RawVec(t, result, alloc_id, ptr.as_ptr(), ?capacity_) &*& capacity <= capacity_; ++ //@ ens RawVec(t, result, alloc_id, ptr.as_ptr(), ?capacity_) &*& capacity <= capacity_ &*& (std::mem::size_of::() == 0 || capacity_ == capacity); + { + // SAFETY: Precondition passed to the caller + unsafe { +@@ -1925,7 +1925,7 @@ + Err(_) => { + //@ leak .own(_, _); + //@ std::alloc::Allocator_to_own(alloc); +- //@ close .own(currentThread, TryReserveErrorKind::CapacityOverflow); ++ //@ close .own(currentThread, TryReserveErrorKind::CapacityOverflow); + return Err(CapacityOverflow.into()) + }, + }; +@@ -1991,7 +1991,7 @@ + let err1 = AllocError { layout, non_exhaustive: () }; + //@ std::alloc::close_Layout_own(currentThread, layout); + //@ close_tuple_0_own(currentThread); +- //@ close .own(currentThread, err1); ++ //@ close .own(currentThread, err1); + return Err(err1.into()) + } + }; +@@ -2080,14 +2080,14 @@ + if elem_layout.size() == 0 { + // Since we return a capacity of `usize::MAX` when `elem_size` is + // 0, getting to here necessarily means the `RawVec` is overfull. +- //@ close .own(t, TryReserveErrorKind::CapacityOverflow); ++ //@ close .own(t, TryReserveErrorKind::CapacityOverflow); + return Err(CapacityOverflow.into()); + } + + // Nothing we can really do about these checks, sadly. +- //@ close .own(t, TryReserveErrorKind::CapacityOverflow); ++ //@ close .own(t, TryReserveErrorKind::CapacityOverflow); + let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?; +- //@ leak .own(t, TryReserveErrorKind::CapacityOverflow); ++ //@ leak .own(t, TryReserveErrorKind::CapacityOverflow); + + //@ open_points_to(self); + //@ std::num::niche_types::UsizeNoHighBit_inv(self0.cap); +@@ -2281,7 +2281,7 @@ + let e = AllocError { layout: *new_layout_ref, non_exhaustive: () }; + //@ std::alloc::close_Layout_own(t, new_layout); + //@ close_tuple_0_own(t); +- //@ close .own(t, e); ++ //@ close .own(t, e); + Err(e.into()) + } + } +@@ -2944,13 +2944,13 @@ + // Since we return a capacity of `usize::MAX` when the type size is + // 0, getting to here necessarily means the `RawVec` is overfull. + let e = CapacityOverflow; +- //@ close .own(t, e); ++ //@ close .own(t, e); + return Err(e.into()); + } + +- //@ close .own(t, TryReserveErrorKind::CapacityOverflow); ++ //@ close .own(t, TryReserveErrorKind::CapacityOverflow); + let cap = len.checked_add(additional).ok_or(CapacityOverflow)?; +- //@ leak .own(t, TryReserveErrorKind::CapacityOverflow); ++ //@ leak .own(t, TryReserveErrorKind::CapacityOverflow); + + //@ let k = begin_lifetime(); + //@ open RawVecInner(t, self0, elem_layout, alloc_id, ptr0, capacity0); +@@ -3183,7 +3183,7 @@ + let e = AllocError { layout: *new_layout_ref, non_exhaustive: () }; + //@ std::alloc::close_Layout_own(t, new_layout); + //@ close_tuple_0_own(t); +- //@ close .own(t, e); ++ //@ close .own(t, e); + Err(e) + } + }? +@@ -3313,7 +3313,7 @@ + } + Err(err) => { + let e = CapacityOverflow; +- //@ close .own(currentThread, e); ++ //@ close .own(currentThread, e); + Err(e.into()) + } + }; diff --git a/verifast-proofs/alloc/vec/into_iter.rs/safety_stub.rs b/verifast-proofs/alloc/vec/into_iter.rs/safety_stub.rs new file mode 100644 index 0000000000000..540f07e14f88b --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/safety_stub.rs @@ -0,0 +1,12 @@ +extern crate proc_macro; +use proc_macro::TokenStream; + +#[proc_macro_attribute] +pub fn loop_invariant(_attr: TokenStream, item: TokenStream) -> TokenStream { + item +} + +#[proc_macro_attribute] +pub fn requires(_attr: TokenStream, item: TokenStream) -> TokenStream { + item +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs/std_ext.rsspec b/verifast-proofs/alloc/vec/into_iter.rs/std_ext.rsspec new file mode 100644 index 0000000000000..293b16052b580 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/std_ext.rsspec @@ -0,0 +1,6 @@ +mod ops { + trait Try { + type Output; + type Residual; + } +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs/try_fold.patch b/verifast-proofs/alloc/vec/into_iter.rs/try_fold.patch new file mode 100644 index 0000000000000..6193b51298f1c --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/try_fold.patch @@ -0,0 +1,189 @@ +--- verified/into_iter.rs ++++ verified_try_fold/into_iter.rs +@@ -1009,6 +1009,49 @@ + //@ assume_correct + { + f(accum, item) ++} ++ ++fn call_try_fn__VeriFast_wrapper R>(f: &mut F, accum: B, item: T) -> R ++//@ req thread_token(?t) &*& *f |-> ?f0 &*& .own(t, f0) &*& .own(t, accum) &*& .own(t, item); ++//@ ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& .own(t, result); ++//@ on_unwind_ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1); ++//@ assume_correct ++{ ++ f(accum, item) ++} ++ ++/*@ ++pred TryRes(t: thread_id_t, r_typeid: *_, res: Res); ++@*/ ++ ++unsafe fn try_branch__VeriFast_wrapper>(r: R) -> core::ops::ControlFlow ++//@ req thread_token(?t) &*& .own(t, r); ++/*@ ++ens thread_token(t) &*& ++ match result { ++ ControlFlow::Continue(b) => .own(t, b), ++ ControlFlow::Break(res) => TryRes(t, typeid(R), res) ++ }; ++@*/ ++//@ assume_correct ++{ ++ core::ops::Try::branch(r) ++} ++ ++unsafe fn try_from_residual__VeriFast_wrapper>(res: R::Residual) -> R ++//@ req thread_token(?t) &*& TryRes(t, typeid(R), res); ++//@ ens thread_token(t) &*& .own(t, result); ++//@ assume_correct ++{ ++ core::ops::FromResidual::from_residual(res) ++} ++ ++fn try_from_output__VeriFast_wrapper>(b: B) -> R ++//@ req thread_token(?t) &*& .own(t, b); ++//@ ens thread_token(t) &*& .own(t, result); ++//@ assume_correct ++{ ++ R::from_output(b) + } + + fn const_ptr_addr__VeriFast_wrapper(p: *const T) -> usize +@@ -1913,7 +1956,10 @@ + Self: Sized, + F: FnMut(B, T) -> R, + R: core::ops::Try, ++ //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0) &*& .own(t, accum) &*& .own(t, f); ++ //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& .own(t, result); + { ++ //@ assert lifetime_token(?flft); + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, +@@ -1925,12 +1971,47 @@ + on_entry(self.cap), + on_entry(self.end), + ))] +- while self.ptr.as_ptr() != self.end.cast_mut() { ++ while { ++ /*@ inv thread_token(t) &*& lifetime_token(flft) &*& ++ *self |-> ?cur_it &*& >.own(t, cur_it) &*& ++ .own(t, accum) &*& ++ *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ ++ //@ open_points_to(self); ++ let ptr_raw = self.ptr.as_ptr(); ++ let end_mut = const_ptr_cast_mut__VeriFast_wrapper(self.end); ++ let cont = ptr_raw != end_mut; ++ //@ close_points_to(self); ++ cont ++ } { ++ //@ open_points_to(self); ++ //@ open >.own(t, cur_it); ++ //@ assert Allocator(t, cur_it.alloc, ?alloc_id); ++ //@ std::alloc::Allocator_inv(); ++ //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); ++ //@ std::ptr::NonNull_Sized_as_ptr(cur_it.ptr); ++ //@ wrapping_sub_usize_zero(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); ++ //@ wrapping_sub_usize_dec(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); ++ //@ let old_len = std::num::wrapping_sub_usize(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); ++ //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), old_len, ?elems); ++ //@ open foreach(elems, own::(t)); ++ //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); ++ //@ open own::(t)(x0); ++ //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); ++ //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. +- let tmp = unsafe { self.ptr.read() }; ++ let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; ++ //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); ++ //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); ++ //@ leak points_to_at_lft_(alloc_id.lft, cur_it.ptr.as_ptr(), _); + // See `next` for why we subtract from `end` here. +- self.end = self.end.wrapping_byte_sub(1); +- accum = f(accum, tmp)?; ++ self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); ++ //@ close_points_to(self); ++ //@ close >.own(t, *self); ++ let step = call_try_fn__VeriFast_wrapper(&mut f, accum, tmp); ++ accum = match unsafe { try_branch__VeriFast_wrapper::(step) } { ++ core::ops::ControlFlow::Continue(v) => v, ++ core::ops::ControlFlow::Break(res) => return unsafe { try_from_residual__VeriFast_wrapper::(res) }, ++ }; + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. +@@ -1944,16 +2025,68 @@ + on_entry(self.cap), + on_entry(self.end), + ))] +- while self.ptr != non_null!(self.end, T) { ++ while { ++ /*@ inv thread_token(t) &*& lifetime_token(flft) &*& ++ *self |-> ?cur_it &*& >.own(t, cur_it) &*& ++ .own(t, accum) &*& ++ *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ ++ //@ open_points_to(self); ++ //@ open >.own(t, cur_it); ++ //@ assert Allocator(t, cur_it.alloc, ?alloc_id_c); ++ //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, ?adv_c, ?end_idx_c, ?elems_c); ++ //@ let ptr_r = precreate_ref(&(*self).ptr); ++ //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); ++ //@ let end_r = precreate_ref(&(*self).end); ++ //@ init_ref_readonly(end_r, 1/2); ++ let is_ne = unsafe { ptr_ne_end__VeriFast_wrapper(&self.ptr, &self.end) }; ++ //@ std::ptr::end_ref_NonNull(ptr_r); ++ //@ end_ref_readonly(end_r); ++ //@ close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, adv_c, end_idx_c, elems_c); ++ //@ close_points_to(self); ++ //@ close >.own(t, *self); ++ is_ne ++ } { ++ //@ open_points_to(self); ++ //@ open >.own(t, cur_it); ++ //@ assert Allocator(t, cur_it.alloc, ?alloc_id); ++ //@ std::alloc::Allocator_inv(); ++ //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); ++ //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, cur_it.ptr, cur_it.end, ?adv, ?end_idx, ?elems); ++ //@ std::alloc::Layout_inv(Layout::new::()); ++ //@ mul_mono_l(1, cur_it.cap, std::mem::size_of::()); ++ //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), end_idx - adv, elems); ++ //@ open foreach(elems, own::(t)); ++ //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); ++ //@ points_to_at_lft_inv(cur_it.ptr.as_ptr()); ++ //@ open own::(t)(x0); ++ //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); ++ //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. +- let tmp = unsafe { self.ptr.read() }; ++ let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; ++ //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); ++ //@ close LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. +- self.ptr = unsafe { self.ptr.add(1) }; +- accum = f(accum, tmp)?; ++ self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(self.ptr) }; ++ //@ open LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); ++ //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); ++ /*@ { ++ close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr() + 1, 0, nil); ++ close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr(), 1, _); ++ array_at_lft__join::(cur_it.buf.as_ptr()); ++ assert array_at_lft(alloc_id.lft, cur_it.ptr.as_ptr() + 1, end_idx - adv - 1, ?elems_rest); ++ close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, (*self).ptr, cur_it.end, adv + 1, end_idx, elems_rest); ++ close_points_to(self); ++ close >.own(t, *self); ++ } @*/ ++ let step = call_try_fn__VeriFast_wrapper(&mut f, accum, tmp); ++ accum = match unsafe { try_branch__VeriFast_wrapper::(step) } { ++ core::ops::ControlFlow::Continue(v) => v, ++ core::ops::ControlFlow::Break(res) => return unsafe { try_from_residual__VeriFast_wrapper::(res) }, ++ }; + } + } +- R::from_output(accum) ++ try_from_output__VeriFast_wrapper::(accum) + } + #[requires(i < self.len())] + #[cfg_attr(kani, kani::modifies(self))] diff --git a/verifast-proofs/alloc/vec/into_iter.rs/tuple_ext.rsspec b/verifast-proofs/alloc/vec/into_iter.rs/tuple_ext.rsspec new file mode 100644 index 0000000000000..f752138d24cec --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/tuple_ext.rsspec @@ -0,0 +1,5 @@ +/*@ +lem close_tuple_2_own(t: thread_id_t, v: (T1, T2)); + req .own(t, v.0) &*& .own(t, v.1); + ens <(T1, T2)>.own(t, v); +@*/ diff --git a/verifast-proofs/alloc/vec/into_iter.rs/update.sh b/verifast-proofs/alloc/vec/into_iter.rs/update.sh new file mode 100644 index 0000000000000..c40336fdf49b7 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/update.sh @@ -0,0 +1,44 @@ +set -x -e + +write_expected_diff() { + local label_a="$1" + local label_b="$2" + local file_a="$3" + local file_b="$4" + local out_file="$5" + local tmp_file + tmp_file="$(mktemp "${out_file}.XXXXXX")" + set +e + diff -u --label "$label_a" --label "$label_b" "$file_a" "$file_b" > "$tmp_file" + local rc=$? + set -e + if [[ "$rc" -ne 1 ]]; then + rm -f "$tmp_file" + echo "ERROR: expected diff exit status 1 for $file_a vs $file_b, got $rc" >&2 + exit 1 + fi + mv "$tmp_file" "$out_file" +} + +if ! git diff --quiet .; then + echo "Working directory not clean. Please stash your changes and try again" + false +else + UPSTREAM=../../../../library/alloc/src/vec/into_iter.rs + git merge-file --diff3 with-directives/into_iter.rs original/into_iter.rs "$UPSTREAM" + git merge-file --diff3 verified/into_iter.rs original/into_iter.rs "$UPSTREAM" + git merge-file --diff3 verified_try_fold/into_iter.rs original/into_iter.rs "$UPSTREAM" + cp "$UPSTREAM" original/into_iter.rs + + # Refresh bridged verified/raw_vec.rs from accepted Ch. 19 raw_vec.rs + reviewed ghost-only patch + cp ../../raw_vec/mod.rs/verified/raw_vec.rs verified/raw_vec.rs + patch -p0 --batch --forward --fuzz=0 verified/raw_vec.rs raw_vec_verified.patch + rm -f verified/raw_vec.rs.orig + + write_expected_diff original/into_iter.rs with-directives/into_iter.rs \ + original/into_iter.rs with-directives/into_iter.rs with-directives.patch + write_expected_diff verified/into_iter.rs verified_try_fold/into_iter.rs \ + verified/into_iter.rs verified_try_fold/into_iter.rs try_fold.patch + write_expected_diff raw_vec/mod.rs/verified/raw_vec.rs verified/raw_vec.rs \ + ../../raw_vec/mod.rs/verified/raw_vec.rs verified/raw_vec.rs raw_vec_verified.patch +fi diff --git a/verifast-proofs/alloc/vec/into_iter.rs/verified/into_iter.rs b/verifast-proofs/alloc/vec/into_iter.rs/verified/into_iter.rs new file mode 100644 index 0000000000000..a2c27a4db4a82 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/verified/into_iter.rs @@ -0,0 +1,2387 @@ +use core::iter::{ + FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, + TrustedRandomAccessNoCoerce, +}; +#[cfg(kani)] +use core::kani; +use core::marker::PhantomData; +use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties}; +use core::num::NonZero; +#[cfg(not(no_global_oom_handling))] +use core::ops::Deref; +use core::panic::UnwindSafe; +use core::ptr::{self, NonNull}; +use core::{array, fmt, slice}; + +use safety::{loop_invariant, requires}; + +#[cfg(not(no_global_oom_handling))] +use super::AsVecIntoIter; +use crate::alloc::{Allocator, Global}; +#[cfg(not(no_global_oom_handling))] +use crate::collections::VecDeque; +use crate::raw_vec::RawVec; + +//@ use std::alloc::{Allocator, alloc_id_t, alloc_block_in, Layout}; +//@ use std::ptr::{NonNull, NonNull_as_ptr_nonnull}; +//@ use std::option::{Option, Option::None, Option::Some}; +//@ use std::ops::ControlFlow; +//@ use raw_vec::{RawVec, RawVec_to_own, RawVec_inv}; + +macro non_null { + (mut $place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { &mut *((&raw mut $place) as *mut NonNull<$t>) } + }}, + ($place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { *((&$place as *const *const $t) as *const NonNull<$t>) } + }}, +} + +/// An iterator that moves out of a vector. +/// +/// This `struct` is created by the `into_iter` method on [`Vec`](super::Vec) +/// (provided by the [`IntoIterator`] trait). +/// +/// # Example +/// +/// ``` +/// let v = vec![0, 1, 2]; +/// let iter: std::vec::IntoIter<_> = v.into_iter(); +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_insignificant_dtor] +pub struct IntoIter< + T, + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] A: Allocator = Global, +> { + pub(super) buf: NonNull, + pub(super) phantom: PhantomData, + pub(super) cap: usize, + // the drop impl reconstructs a RawVec from buf, cap and alloc + // to avoid dropping the allocator twice we need to wrap it into ManuallyDrop + pub(super) alloc: ManuallyDrop, + pub(super) ptr: NonNull, + /// If T is a ZST, this is actually ptr+len. This encoding is picked so that + /// ptr == end is a quick test for the Iterator being empty, that works + /// for both ZST and non-ZST. + /// For non-ZSTs the pointer is treated as `NonNull` + pub(super) end: *const T, +} + +/*@ + +lem wrapping_sub_usize_zero(a: usize, b: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX; + ens (std::num::wrapping_sub_usize(a, b) == 0) == (a == b); +{ +} + +lem wrapping_sub_usize_dec(a: usize, b: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX &*& a != b; + ens std::num::wrapping_sub_usize(std::num::wrapping_sub_usize(a, 1), b) == std::num::wrapping_sub_usize(a, b) - 1; +{ +} + +lem wrapping_sub_usize_sub(a: usize, b: usize, n: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX &*& 0 <= n &*& n <= std::num::wrapping_sub_usize(a, b); + ens std::num::wrapping_sub_usize(std::num::wrapping_sub_usize(a, n), b) == std::num::wrapping_sub_usize(a, b) - n; +{ +} + +lem foreach_own_send(t0: thread_id_t, t1: thread_id_t) + req foreach(?xs, own::(t0)) &*& type_interp::() &*& is_Send(typeid(T)) == true; + ens foreach(xs, own::(t1)) &*& type_interp::(); +{ + open foreach(xs, own::(t0)); + match xs { + nil => {} + cons(x, xs0) => { + open own::(t0)(x); + Send::send::(t0, t1, x); + close own::(t1)(x); + foreach_own_send::(t0, t1); + } + } + close foreach(xs, own::(t1)); +} + +lem array_at_lft_own_mono(t: thread_id_t, k: lifetime_t, p: *T0, n: usize) + req array_at_lft::(k, p, n, ?elems) &*& foreach(elems, own::(t)) &*& + type_interp::() &*& type_interp::() &*& + is_subtype_of::() == true &*& + std::mem::size_of::() == std::mem::size_of::() &*& + std::mem::align_of::() == std::mem::align_of::(); + ens array_at_lft::(k, p as *T1, n, ?elems1) &*& foreach(elems1, own::(t)) &*& + type_interp::() &*& type_interp::(); +{ + open array_at_lft::(k, p, n, elems); + open foreach(elems, own::(t)); + match elems { + nil => { + close array_at_lft::(k, p as *T1, 0, nil); + close foreach(nil, own::(t)); + } + cons(x, xs0) => { + open points_to_at_lft::(k, p, x); + to_u8s__at_lft::(p); + assert array_at_lft_(k, p as *u8, std::mem::size_of::(), ?bs); + from_u8s__at_lft::(p as *T1); + // Rust subtyping (`T0 <: T1`) only weakens lifetimes and preserves byte + // representation (https://github.com/verifast/verifast/issues/610). + let x1 = upcast::(x); + assume(of_u8s_::(bs) == some(x1)); + close points_to_at_lft::(k, p as *T1, x1); + open own::(t)(x); + own_mono::(t, x); + close own::(t)(x1); + array_at_lft_own_mono::(t, k, p + 1, n - 1); + assert array_at_lft::(k, (p + 1) as *T1, n - 1, ?xs1); + assert ((p + 1) as *T1) == ((p as *T1) + 1); + close array_at_lft::(k, p as *T1, n, cons(x1, xs1)); + close foreach(cons(x1, xs1), own::(t)); + } + } +} + +lem foreach_snoc_inv(xs: list, x: T, p: pred(T)) + req foreach(append(xs, [x]), p); + ens foreach(xs, p) &*& p(x); +{ + match xs { + nil => { + open foreach([x], p); + open foreach(nil, p); + close foreach(nil, p); + } + cons(h, t) => { + open foreach(cons(h, append(t, [x])), p); + foreach_snoc_inv(t, x, p); + close foreach(cons(h, t), p); + } + } +} + +lem list_split_last(xs: list) + req length(xs) > 0; + ens xs == append(take(length(xs) - 1, xs), [nth(length(xs) - 1, xs)]) &*& length(take(length(xs) - 1, xs)) == length(xs) - 1; +{ + match xs { + nil => {} + cons(h, t) => { + if length(t) == 0 { + match t { + nil => {} + cons(h1, t1) => {} + } + } else { + list_split_last(t); + } + } + } +} + +pred IntoIter_non_zst_buf(t: thread_id_t, buf: NonNull, cap: usize, alloc_id: alloc_id_t, ptr: NonNull, end: *T, adv: usize, end_idx: usize, elems: list) = + 0 <= adv &*& adv <= end_idx &*& end_idx <= cap &*& + cap * std::mem::size_of::() <= isize::MAX &*& + if cap == 0 { + true + } else { + Layout::new::().repeat(cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, buf.as_ptr() as *u8, allocLayout) + } &*& + ptr.as_ptr() == buf.as_ptr() + adv &*& + end == buf.as_ptr() + end_idx &*& + end != 0 &*& pointer_within_limits(end) == true &*& + array_at_lft_(alloc_id.lft, buf.as_ptr(), adv, _) &*& + array_at_lft(alloc_id.lft, ptr.as_ptr(), end_idx - adv, elems) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, buf.as_ptr() + end_idx, cap - end_idx, _); + +pred >.own(t, it) = + Allocator(t, it.alloc, ?alloc_id) &*& + it.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(it.buf.as_ptr()) == true &*& + 0 <= (it.end as usize) &*& (it.end as usize) <= usize::MAX &*& + (it.end as pointer) == pointer_ctor((it.ptr.as_ptr() as pointer).provenance, it.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + it.ptr == it.buf &*& + array_at_lft(alloc_id.lft, it.ptr.as_ptr(), std::num::wrapping_sub_usize(it.end as usize, it.ptr.as_ptr() as usize), ?elems) &*& + foreach(elems, own::(t)) + } else { + IntoIter_non_zst_buf::(t, it.buf, it.cap, alloc_id, it.ptr, it.end, ?adv, ?end_idx, ?elems) + }; + +lem IntoIter_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Send(typeid(IntoIter)) == true &*& + IntoIter_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& + IntoIter_own::(t1, v); +{ + open >.own(t0, v); + assume(is_Send(typeid(T)) == true && is_Send(typeid(A)) == true); + std::alloc::Allocator_send(t1, v.alloc); + if std::mem::size_of::() == 0 { + foreach_own_send::(t0, t1); + } else { + open IntoIter_non_zst_buf::(t0, v.buf, v.cap, ?alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + foreach_own_send::(t0, t1); + close IntoIter_non_zst_buf::(t1, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + } + close >.own(t1, v); +} + +lem IntoIter_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + IntoIter_own::(?t, ?v) &*& + is_subtype_of::() == true &*& + is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + IntoIter_own::(t, IntoIter:: { + buf: upcast(v.buf), + cap: upcast(v.cap), + alloc: upcast(v.alloc), + ptr: upcast(v.ptr), + end: v.end as *T1, + }); +{ + open >.own(t, v); + assert Allocator(t, v.alloc, ?alloc_id); + std::alloc::Allocator_upcast::(v.alloc); + std::ptr::NonNull_upcast::(v.buf); + std::ptr::NonNull_upcast::(v.ptr); + std::ptr::NonNull_Sized_as_ptr(v.ptr); + assume( + std::mem::size_of::() == std::mem::size_of::() && + std::mem::align_of::() == std::mem::align_of::() && + Layout::new::() == Layout::new::() && + upcast::(v.cap) == v.cap + ); + if std::mem::size_of::() == 0 { + array_at_lft_own_mono::(t, alloc_id.lft, v.ptr.as_ptr(), std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + array_at_lft__to_u8s_at_lft_::(v.buf.as_ptr(), adv); + u8s_at_lft__to_array_at_lft_::(v.buf.as_ptr() as *T1, adv); + array_at_lft_own_mono::(t, alloc_id.lft, v.ptr.as_ptr(), end_idx - adv); + array_at_lft__to_u8s_at_lft_::(v.buf.as_ptr() + end_idx, v.cap - end_idx); + assert ((v.buf.as_ptr() + end_idx) as *u8) == (((v.buf.as_ptr() as *T1) + end_idx) as *u8); + u8s_at_lft__to_array_at_lft_::((v.buf.as_ptr() as *T1) + end_idx, v.cap - end_idx); + close IntoIter_non_zst_buf::(t, upcast(v.buf), upcast(v.cap), alloc_id, upcast(v.ptr), v.end as *T1, adv, end_idx, _); + } + close >.own(t, IntoIter:: { + buf: upcast(v.buf), + cap: upcast(v.cap), + alloc: upcast(v.alloc), + ptr: upcast(v.ptr), + end: v.end as *T1, + }); +} + +pred IntoIter_raw_buf(t: thread_id_t, it: IntoIter) = + Allocator(t, it.alloc, ?alloc_id) &*& + it.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(it.buf.as_ptr()) == true &*& + if std::mem::size_of::() == 0 { + true + } else { + it.cap * std::mem::size_of::() <= isize::MAX &*& + (if it.cap == 0 { + true + } else { + Layout::new::().repeat(it.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, it.buf.as_ptr() as *u8, allocLayout) + }) &*& + array_at_lft_(alloc_id.lft, it.buf.as_ptr(), it.cap, _) + }; + +lem IntoIter_own_to_raw_buf(t: thread_id_t, it: IntoIter) + req >.own(t, it); + ens IntoIter_raw_buf::(t, it); +{ + open >.own(t, it); + assert Allocator(t, it.alloc, ?alloc_id); + if std::mem::size_of::() == 0 { + assert array_at_lft(alloc_id.lft, it.ptr.as_ptr(), ?len, ?elems); + leak foreach(elems, own::(t)); + leak array_at_lft(alloc_id.lft, it.ptr.as_ptr(), len, elems); + } else { + open IntoIter_non_zst_buf::(t, it.buf, it.cap, alloc_id, it.ptr, it.end, ?adv, ?end_idx, ?elems); + leak foreach(elems, own::(t)); + array_at_lft_to_array_at_lft_::(it.ptr.as_ptr()); + array_at_lft__join::(it.buf.as_ptr() + adv); + array_at_lft__join::(it.buf.as_ptr()); + } + close IntoIter_raw_buf::(t, it); +} + +lem zst_array_at_lft_move(elems: list, k: lifetime_t, src: *T, dst: *T, n: usize) + req array_at_lft::(k, src, n, elems) &*& + std::mem::size_of::() == 0 &*& + dst as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(dst) == true; + ens array_at_lft::(k, dst, n, elems); +{ + open array_at_lft::(k, src, n, elems); + match elems { + nil => { + close array_at_lft::(k, dst, 0, nil); + } + cons(x, xs0) => { + open points_to_at_lft::(k, src, x); + to_u8s__at_lft::(src); + assert array_at_lft_(k, src as *u8, 0, ?bs); + open array_at_lft_(k, src as *u8, 0, bs); + close array_at_lft_::(k, dst as *u8, 0, nil); + from_u8s__at_lft::(dst); + close points_to_at_lft::(k, dst, x); + zst_array_at_lft_move::(xs0, k, src + 1, dst + 1, n - 1); + close array_at_lft::(k, dst, n, cons(x, xs0)); + } + } +} + +lem close_slice_own_from_foreach(t: thread_id_t, elems: list) + req foreach(elems, own::(t)); + ens <[T]>.own(t, slice_of_elems(elems)); +{ + close <[T]>.own(t, slice_of_elems(elems)); +} + +pred_ctor IntoIter_shared_val(l: *IntoIter, v: IntoIter)(;) = + (*l).buf |-> v.buf &*& + (*l).cap |-> v.cap &*& + (*l).ptr |-> v.ptr &*& + (*l).end |-> v.end &*& + struct_IntoIter_padding::(l); + +pred_ctor IntoIter_shared_range(alloc_lft: lifetime_t, ptr: *T, len: usize, elems: list)(;) = + array_at_lft::(alloc_lft, ptr, len, elems); + +pred IntoIter_share_(k: lifetime_t, t: thread_id_t, l: *IntoIter, len: usize) = + [_]std::alloc::Allocator_share(k, t, &(*l).alloc, ?alloc_id) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + [_]exists::>(?v) &*& + 0 <= len &*& len <= usize::MAX &*& + [_]frac_borrow(k, IntoIter_shared_val::(l, v)) &*& + pointer_within_limits(v.ptr.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) == len + } else { + v.end == v.ptr.as_ptr() + len &*& + v.end != 0 &*& pointer_within_limits(v.end) == true &*& + len * std::mem::size_of::() <= isize::MAX &*& + [_]exists::>(?elems) &*& + [_]frac_borrow(k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)) + }; + +pred >.share(k, t, l) = + [_]IntoIter_share_::(k, t, l, ?len); + +lem IntoIter_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *IntoIter) + req type_interp::() &*& type_interp::() &*& + lifetime_inclusion(k1, k) == true &*& [_]IntoIter_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]IntoIter_share::(k1, t, l); +{ + open IntoIter_share::(k, t, l); + open IntoIter_share_::(k, t, l, ?len); + std::alloc::Allocator_share_mono::(k, k1, t, &(*l).alloc); + assert [_]std::alloc::Allocator_share(k1, t, &(*l).alloc, ?alloc_id); + assert [_]exists::>(?v); + frac_borrow_mono(k, k1, IntoIter_shared_val::(l, v)); + if std::mem::size_of::() != 0 { + assert [_]exists::>(?elems); + frac_borrow_mono(k, k1, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + } + close IntoIter_share_::(k1, t, l, len); + leak IntoIter_share_::(k1, t, l, len); + close IntoIter_share::(k1, t, l); + leak IntoIter_share::(k1, t, l); +} + +lem IntoIter_share_full(k: lifetime_t, t: thread_id_t, l: *IntoIter) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + full_borrow(k, IntoIter_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + [_]IntoIter_share::(k, t, l) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong_m(k, IntoIter_full_borrow_content::(t, l), q); + open IntoIter_full_borrow_content::(t, l)(); + assert *l |-> ?v; + open_points_to(l); + open >.own(t, v); + assert Allocator(t, v.alloc, ?alloc_id); + std::alloc::Allocator_inv(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close IntoIter_shared_val::(l, v)(); + if std::mem::size_of::() == 0 { + let len_z = std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize); + assert array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len_z, ?elems_z); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + v.ptr == v.buf &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len_z, elems_z) &*& + foreach(elems_z, own::(t)); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)), + klong, + IntoIter_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + assert (*l).alloc |-> ?a1; + close >.own(t, IntoIter:: { buf: v.buf, cap: v.cap, alloc: a1, ptr: v.ptr, end: v.end }); + close IntoIter_full_borrow_content::(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m( + klong, + IntoIter_full_borrow_content::(t, l), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)) + ); + full_borrow_split_m(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + } + } + close exists::>(v); + leak exists::>(v); + close IntoIter_share_::(k, t, l, len_z); + leak IntoIter_share_::(k, t, l, len_z); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + let len_nz = end_idx - adv; + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(len_nz, v.cap, std::mem::size_of::()); + close IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)(); + close sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& pointer_within_limits(v.end) == true &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + 0 <= adv &*& adv <= end_idx &*& end_idx <= v.cap &*& + v.cap * std::mem::size_of::() <= isize::MAX &*& + (if v.cap == 0 { + true + } else { + Layout::new::().repeat(v.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, v.buf.as_ptr() as *u8, allocLayout) + }) &*& + v.ptr.as_ptr() == v.buf.as_ptr() + adv &*& + v.end == v.buf.as_ptr() + end_idx &*& + v.end != 0 &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr(), adv, _) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr() + end_idx, v.cap - end_idx, _); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))), + klong, + IntoIter_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)))(); + open sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + open IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)(); + assert (*l).alloc |-> ?a1; + close IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + close >.own(t, IntoIter:: { buf: v.buf, cap: v.cap, alloc: a1, ptr: v.ptr, end: v.end }); + close IntoIter_full_borrow_content::(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m( + klong, + IntoIter_full_borrow_content::(t, l), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))) + ); + full_borrow_split_m(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))); + full_borrow_split_m(klong, IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + full_borrow_into_frac_m(klong, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + frac_borrow_mono(klong, k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + } + } + close exists::>(v); + leak exists::>(v); + close exists::>(elems); + leak exists::>(elems); + close IntoIter_share_::(k, t, l, len_nz); + leak IntoIter_share_::(k, t, l, len_nz); + } + close IntoIter_share::(k, t, l); + leak IntoIter_share::(k, t, l); +} + +pred_ctor IntoIter_val_fbc(t: thread_id_t, l: *IntoIter, v: IntoIter, alloc_id: alloc_id_t, len: usize)() = + (*l).buf |-> v.buf &*& + (*l).cap |-> v.cap &*& + (*l).ptr |-> v.ptr &*& + (*l).end |-> v.end &*& + struct_IntoIter_padding::(l) &*& + (*l).alloc |-> ?a &*& + Allocator(t, a, alloc_id) &*& + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + v.ptr == v.buf &*& + len == std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, ?elems) &*& + foreach(elems, own::(t)) + } else { + IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems) &*& + len == end_idx - adv + }; + +lem IntoIter_share_val_fbc(k: lifetime_t, t: thread_id_t, l: *IntoIter, v: IntoIter, alloc_id: alloc_id_t, len: usize) + nonghost_callers_only + req full_borrow(k, IntoIter_val_fbc::(t, l, v, alloc_id, len)) &*& [?q]lifetime_token(k); + ens [_]IntoIter_share_::(k, t, l, len) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong(k, IntoIter_val_fbc::(t, l, v, alloc_id, len), q); + open IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + std::alloc::Allocator_inv(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close IntoIter_shared_val::(l, v)(); + if std::mem::size_of::() == 0 { + assert array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, ?elems_z); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + v.ptr == v.buf &*& + len == std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, elems_z) &*& + foreach(elems_z, own::(t)); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)), + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + close IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)) + ); + full_borrow_split(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + } + } + close exists::>(v); + leak exists::>(v); + close IntoIter_share_::(k, t, l, len); + leak IntoIter_share_::(k, t, l, len); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(len, v.cap, std::mem::size_of::()); + close IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + close sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& pointer_within_limits(v.end) == true &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + 0 <= adv &*& adv <= end_idx &*& end_idx <= v.cap &*& + len == end_idx - adv &*& + v.cap * std::mem::size_of::() <= isize::MAX &*& + (if v.cap == 0 { + true + } else { + Layout::new::().repeat(v.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, v.buf.as_ptr() as *u8, allocLayout) + }) &*& + v.ptr.as_ptr() == v.buf.as_ptr() + adv &*& + v.end == v.buf.as_ptr() + end_idx &*& + v.end != 0 &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr(), adv, _) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr() + end_idx, v.cap - end_idx, _); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))), + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)))(); + open sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + open IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + close IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + close IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))) + ); + full_borrow_split(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))); + full_borrow_split(klong, IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + full_borrow_into_frac(klong, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + frac_borrow_mono(klong, k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + } + } + close exists::>(v); + leak exists::>(v); + close exists::>(elems); + leak exists::>(elems); + close IntoIter_share_::(k, t, l, len); + leak IntoIter_share_::(k, t, l, len); + } +} + +lem IntoIter_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Sync(typeid(IntoIter)) == true &*& + [_]IntoIter_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& + [_]IntoIter_share::(k, t1, l); +{ + open IntoIter_share::(k, t0, l); + open IntoIter_share_::(k, t0, l, ?len); + assume(is_Sync(typeid(A)) == true); + std::alloc::Allocator_sync::(t1); + close IntoIter_share_::(k, t1, l, len); + leak IntoIter_share_::(k, t1, l, len); + close IntoIter_share::(k, t1, l); + leak IntoIter_share::(k, t1, l); +} + +lem init_ref_IntoIter(p: *IntoIter) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + ref_init_perm(p, ?x) &*& [_]IntoIter_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + [q]lifetime_token(k) &*& [_]IntoIter_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open IntoIter_share::(k, t, x); + open IntoIter_share_::(k, t, x, ?len); + assert [_]exists::>(?v); + open_ref_init_perm_IntoIter(p); + std::alloc::init_ref_Allocator_share_m(k, t, &(*p).alloc); + frac_borrow_sep(k, IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)); + let klong = open_frac_borrow_strong_m(k, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), q); + open [?f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + open [f]IntoIter_shared_val::(x, v)(); + open [f]ref_initialized_::(&(*p).alloc)(); + std::ptr::init_ref_NonNull(&(*p).buf, 1/2); + init_ref_readonly(&(*p).cap, 1/2); + std::ptr::init_ref_NonNull(&(*p).ptr, 1/2); + init_ref_readonly(&(*p).end, 1/2); + init_ref_padding_IntoIter(p, 1/2); + { + pred P() = ref_padding_initialized(p) &*& ref_initialized(&(*p).buf) &*& ref_initialized(&(*p).cap) &*& ref_initialized(&(*p).ptr) &*& ref_initialized(&(*p).end); + close [1 - f/2]P(); + close_ref_initialized_IntoIter(p); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*p).alloc) &*& + ref_padding_end_token(p, x, f/2) &*& [f/2]struct_IntoIter_padding::(x) &*& [1 - f/2]ref_padding_initialized(p) &*& + ref_end_token(&(*p).buf, &(*x).buf, f/2) &*& [f/2]((*x).buf |-> v.buf) &*& [1 - f/2]ref_initialized(&(*p).buf) &*& + ref_readonly_end_token(&(*p).cap, &(*x).cap, f/2) &*& [f/2]((*x).cap |-> v.cap) &*& [1 - f/2]ref_initialized(&(*p).cap) &*& + ref_end_token(&(*p).ptr, &(*x).ptr, f/2) &*& [f/2]((*x).ptr |-> v.ptr) &*& [1 - f/2]ref_initialized(&(*p).ptr) &*& + ref_readonly_end_token(&(*p).end, &(*x).end, f/2) &*& [f/2]((*x).end |-> v.end) &*& [1 - f/2]ref_initialized(&(*p).end); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))), + klong, + f, + sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)) + )() { + open scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + open sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + open ref_initialized_::>(p)(); + open IntoIter_shared_val::(p, v)(); + open_ref_initialized_IntoIter(p); + open Ctx(); + std::ptr::end_ref_NonNull(&(*p).buf); + end_ref_readonly(&(*p).cap); + std::ptr::end_ref_NonNull(&(*p).ptr); + end_ref_readonly(&(*p).end); + end_ref_padding_IntoIter(p); + close [f]IntoIter_shared_val::(x, v)(); + close [f]ref_initialized_::(&(*p).alloc)(); + close [f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(p)(); + close [f/2]IntoIter_shared_val::(p, v)(); + close [f/2]sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + close scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))); + frac_borrow_split(k, ref_initialized_(p), IntoIter_shared_val::(p, v)); + } + } + close IntoIter_share_::(k, t, p, len); + leak IntoIter_share_::(k, t, p, len); + close IntoIter_share::(k, t, p); + leak IntoIter_share::(k, t, p); +} + +lem init_ref_IntoIter_share_(p: *IntoIter) + nonghost_callers_only + req ref_init_perm(p, ?x) &*& [_]IntoIter_share_::(?k, ?t, x, ?len) &*& [?q]lifetime_token(k); + ens [q]lifetime_token(k) &*& [_]IntoIter_share_::(k, t, p, len) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open IntoIter_share_::(k, t, x, len); + assert [_]exists::>(?v); + open_ref_init_perm_IntoIter(p); + std::alloc::init_ref_Allocator_share(k, t, &(*p).alloc); + frac_borrow_sep(k, IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)); + let klong = open_frac_borrow_strong(k, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), q); + open [?f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + open [f]IntoIter_shared_val::(x, v)(); + open [f]ref_initialized_::(&(*p).alloc)(); + std::ptr::init_ref_NonNull(&(*p).buf, 1/2); + init_ref_readonly(&(*p).cap, 1/2); + std::ptr::init_ref_NonNull(&(*p).ptr, 1/2); + init_ref_readonly(&(*p).end, 1/2); + init_ref_padding_IntoIter(p, 1/2); + { + pred P() = ref_padding_initialized(p) &*& ref_initialized(&(*p).buf) &*& ref_initialized(&(*p).cap) &*& ref_initialized(&(*p).ptr) &*& ref_initialized(&(*p).end); + close [1 - f/2]P(); + close_ref_initialized_IntoIter(p); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*p).alloc) &*& + ref_padding_end_token(p, x, f/2) &*& [f/2]struct_IntoIter_padding::(x) &*& [1 - f/2]ref_padding_initialized(p) &*& + ref_end_token(&(*p).buf, &(*x).buf, f/2) &*& [f/2]((*x).buf |-> v.buf) &*& [1 - f/2]ref_initialized(&(*p).buf) &*& + ref_readonly_end_token(&(*p).cap, &(*x).cap, f/2) &*& [f/2]((*x).cap |-> v.cap) &*& [1 - f/2]ref_initialized(&(*p).cap) &*& + ref_end_token(&(*p).ptr, &(*x).ptr, f/2) &*& [f/2]((*x).ptr |-> v.ptr) &*& [1 - f/2]ref_initialized(&(*p).ptr) &*& + ref_readonly_end_token(&(*p).end, &(*x).end, f/2) &*& [f/2]((*x).end |-> v.end) &*& [1 - f/2]ref_initialized(&(*p).end); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))), + klong, + f, + sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)) + )() { + open scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + open sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + open ref_initialized_::>(p)(); + open IntoIter_shared_val::(p, v)(); + open_ref_initialized_IntoIter(p); + open Ctx(); + std::ptr::end_ref_NonNull(&(*p).buf); + end_ref_readonly(&(*p).cap); + std::ptr::end_ref_NonNull(&(*p).ptr); + end_ref_readonly(&(*p).end); + end_ref_padding_IntoIter(p); + close [f]IntoIter_shared_val::(x, v)(); + close [f]ref_initialized_::(&(*p).alloc)(); + close [f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(p)(); + close [f/2]IntoIter_shared_val::(p, v)(); + close [f/2]sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + close scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + close_frac_borrow_strong(klong, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_into_frac(k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))); + frac_borrow_split(k, ref_initialized_(p), IntoIter_shared_val::(p, v)); + } + } + close IntoIter_share_::(k, t, p, len); + leak IntoIter_share_::(k, t, p, len); +} + +@*/ + +// 1-line wrappers for core::mem / core::ptr primitives absent from VeriFast 26.10's std/lib.rsspec. +// Every wrapper is automatically inlined by `refinement-checker` against original/into_iter.rs. +unsafe fn manually_drop_take__VeriFast_wrapper(slot: &mut ManuallyDrop) -> T +//@ req *slot |-> ?v; +//@ ens *slot |-?-> _ &*& result == v; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { ManuallyDrop::take(slot) } +} + +fn const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(p: *const T) -> *const T +//@ req true; +//@ ens (result as pointer) == pointer_ctor((p as pointer).provenance, std::num::wrapping_sub_usize(p as usize, 1), (p as pointer).metadata) &*& 0 <= (result as usize) &*& (result as usize) <= usize::MAX; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.wrapping_byte_sub(1) +} + +fn const_ptr_cast_mut__VeriFast_wrapper(p: *const T) -> *mut T +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.cast_mut() +} + +fn const_ptr_cast_t_mut__VeriFast_wrapper(p: *const T) -> *mut T +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.cast::().cast_mut() +} + +unsafe fn ptr_ne_end__VeriFast_wrapper(ptr: &NonNull, end: &*const T) -> bool +//@ req [?f1](*ptr |-> ?p) &*& [?f2](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true &*& (e as pointer) == pointer_ctor((p.as_ptr() as pointer).provenance, e as usize, pointer_metadata_none); +//@ ens [f1](*ptr |-> p) &*& [f2](*end |-> e) &*& result == (p.as_ptr() != e); +//@ on_unwind_ens false; +//@ assume_correct +{ + *ptr != unsafe { *((end as *const *const T) as *const NonNull) } +} + +unsafe fn ptr_eq_end__VeriFast_wrapper(ptr: &NonNull, end: &*const T) -> bool +//@ req [?f1](*ptr |-> ?p) &*& [?f2](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true &*& (e as pointer) == pointer_ctor((p.as_ptr() as pointer).provenance, e as usize, pointer_metadata_none); +//@ ens [f1](*ptr |-> p) &*& [f2](*end |-> e) &*& result == (p.as_ptr() == e); +//@ on_unwind_ens false; +//@ assume_correct +{ + *ptr == unsafe { *((end as *const *const T) as *const NonNull) } +} + +/*@ +pred LiveSlot(p: *T, k: lifetime_t, q: real, f: real, ov: option) = + [q]lifetime_token(k) &*& + match ov { + some(v) => [f]points_to_at_lft::(k, p, v), + none => [f]points_to_at_lft_::(k, p, _) + }; + +pred LiveRange(p: *T, n: usize, k: lifetime_t, q: real, f: real, elems: list) = + if n == 0 { + true + } else { + [q]lifetime_token(k) &*& [f]array_at_lft::(k, p, n, elems) + }; +@*/ + +unsafe fn non_null_add_1__VeriFast_wrapper(p: NonNull) -> NonNull +/*@ +req std::mem::size_of::() > 0 &*& std::mem::size_of::() <= isize::MAX &*& + pointer_within_limits(p.as_ptr() + 1) == true &*& (p.as_ptr() + 1) != 0 &*& + LiveSlot::(p.as_ptr(), ?k, ?q, ?f, ?ov); +@*/ +/*@ +ens LiveSlot::(p.as_ptr(), k, q, f, ov) &*& + result.as_ptr() == p.as_ptr() + 1; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.add(1) } +} + +unsafe fn exact_size_len__VeriFast_wrapper<'a, 'b, T, A: Allocator>(it: &'a &'b mut IntoIter) -> usize +/*@ +req thread_token(?t) &*& + [?f]points_to::<&'b mut IntoIter>(it, ?p) &*& + [_]IntoIter_share_::(?k, t, p, ?len) &*& + [?q]lifetime_token(k); +@*/ +/*@ +ens thread_token(t) &*& + [f]points_to::<&'b mut IntoIter>(it, p) &*& + [q]lifetime_token(k) &*& + result == len; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + it.len() +} + +fn usize_min__VeriFast_wrapper(a: usize, b: usize) -> usize +//@ req true; +//@ ens result == (if a <= b { a } else { b }); +//@ on_unwind_ens false; +//@ assume_correct +{ + a.min(b) +} + +unsafe fn non_null_dangling__VeriFast_wrapper() -> NonNull +//@ req true; +//@ ens result.as_ptr() as usize == std::mem::align_of::() &*& result.as_ptr() as usize % std::mem::align_of::() == 0 &*& pointer_within_limits(result.as_ptr()) == true; +//@ on_unwind_ens false; +//@ assume_correct +{ + ptr::NonNull::::dangling() +} + +fn const_ptr_wrapping_byte_sub__VeriFast_wrapper(p: *const T, count: usize) -> *const T +//@ req true; +//@ ens (result as pointer) == pointer_ctor((p as pointer).provenance, std::num::wrapping_sub_usize(p as usize, count), (p as pointer).metadata) &*& 0 <= (result as usize) &*& (result as usize) <= usize::MAX; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.wrapping_byte_sub(count) +} + +unsafe fn non_null_add__VeriFast_wrapper(p: NonNull, count: usize) -> NonNull +/*@ +req std::mem::size_of::() > 0 &*& 0 <= count &*& count * std::mem::size_of::() <= isize::MAX &*& + pointer_within_limits(p.as_ptr() + count) == true &*& (p.as_ptr() + count) != 0 &*& + LiveRange::(p.as_ptr(), count, ?k, ?q, ?f, ?elems); +@*/ +/*@ +ens LiveRange::(p.as_ptr(), count, k, q, f, elems) &*& + result.as_ptr() == p.as_ptr() + count; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.add(count) } +} + +unsafe fn non_zero_rem__VeriFast_wrapper(rem: usize) -> Result<(), NonZero> +//@ req thread_token(?t); +//@ ens thread_token(t) &*& >>.own(t, result); +//@ on_unwind_ens false; +//@ assume_correct +{ + NonZero::new(rem).map_or(Ok(()), Err) +} + +fn call_fold__VeriFast_wrapper B>(f: &mut F, accum: B, item: T) -> B +//@ req thread_token(?t) &*& *f |-> ?f0 &*& .own(t, f0) &*& .own(t, accum) &*& .own(t, item); +//@ ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& .own(t, result); +//@ on_unwind_ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1); +//@ assume_correct +{ + f(accum, item) +} + +fn const_ptr_addr__VeriFast_wrapper(p: *const T) -> usize +//@ req true; +//@ ens result == p as usize; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.addr() +} + +fn mut_ptr_addr__VeriFast_wrapper(p: *mut T) -> usize +//@ req true; +//@ ens result == p as usize; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.addr() +} + +unsafe fn non_null_from_end__VeriFast_wrapper(end: &*const T) -> NonNull +//@ req [?f](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true; +//@ ens [f](*end |-> e) &*& result.as_ptr() == e; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { *((end as *const *const T) as *const NonNull) } +} + +unsafe fn non_null_offset_from_unsigned__VeriFast_wrapper(end: NonNull, ptr: NonNull) -> usize +/*@ +req std::mem::size_of::() > 0 &*& + LiveRange::(ptr.as_ptr(), ?len, ?k, ?q, ?f, ?elems) &*& + end.as_ptr() == ptr.as_ptr() + len &*& + 0 <= len &*& len * std::mem::size_of::() <= isize::MAX; +@*/ +/*@ +ens LiveRange::(ptr.as_ptr(), len, k, q, f, elems) &*& + result == len; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { end.offset_from_unsigned(ptr) } +} + +// Verified check that `core::iter::ExactSizeIterator::len`'s default implementation +// (`let (lower, upper) = self.size_hint(); assert_eq!(upper, Some(lower)); lower`) +// computes the exact remaining length `len` exposed in `IntoIter_share_`. +fn verify_exact_size_len_from_size_hint__VeriFast_wrapper(it: &IntoIter) -> usize +//@ req thread_token(?t) &*& [?q]lifetime_token(?k) &*& [_]IntoIter_share_::(k, t, it, ?len); +//@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result == len; +/*@ +safety_proof { + open >.share(?k, _t, it); + call(); +} +@*/ +{ + //@ let it_r = precreate_ref(it); + //@ init_ref_IntoIter_share_(it_r); + //@ open_frac_borrow(k, ref_initialized_(it_r), q/2); + //@ open [?f]ref_initialized_::>(it_r)(); + let (lower, upper) = unsafe { &*(it as *const IntoIter) }.size_hint(); + //@ close [f]ref_initialized_::>(it_r)(); + //@ close_frac_borrow(f, ref_initialized_(it_r)); + //@ assert upper == Some(len); + lower +} + +unsafe fn non_null_read__VeriFast_wrapper(p: NonNull) -> T +//@ req *(p.as_ptr()) |-> ?v &*& p.as_ptr() as usize % std::mem::align_of::() == 0; +//@ ens *(p.as_ptr()) |-?-> _ &*& result == v; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.read() } +} + +// Manually mirroring what `Vec` has, +// because otherwise we get `T: RefUnwindSafe` from `NonNull`. +#[stable(feature = "catch_unwind", since = "1.9.0")] +impl UnwindSafe for IntoIter {} + +#[stable(feature = "vec_intoiter_debug", since = "1.13.0")] +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("IntoIter").field(&self.as_slice()).finish() + } +} + +impl IntoIter { + /// Returns the remaining items of this iterator as a slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// let _ = into_iter.next().unwrap(); + /// assert_eq!(into_iter.as_slice(), &['b', 'c']); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_slice(&self) -> &[T] { + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len()) } + } + + /// Returns the remaining items of this iterator as a mutable slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// into_iter.as_mut_slice()[2] = 'z'; + /// assert_eq!(into_iter.next().unwrap(), 'a'); + /// assert_eq!(into_iter.next().unwrap(), 'b'); + /// assert_eq!(into_iter.next().unwrap(), 'z'); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_mut_slice(&mut self) -> &mut [T] { + // ignore-tidy-undocumented-unsafe + unsafe { &mut *self.as_raw_mut_slice() } + } + + /// Returns a reference to the underlying allocator. + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] + #[inline] + pub fn allocator(&self) -> &A { + &self.alloc + } + + fn as_raw_mut_slice(&mut self) -> *mut [T] { + self.ptr.as_ptr().cast_slice(self.len()) + } + + /// Drops remaining elements and relinquishes the backing allocation. + /// + /// This method guarantees it won't panic before relinquishing the backing + /// allocation. + /// + /// This is roughly equivalent to the following, but more efficient + /// + /// ``` + /// # let mut vec = Vec::::with_capacity(10); + /// # let ptr = vec.as_mut_ptr(); + /// # let mut into_iter = vec.into_iter(); + /// let mut into_iter = std::mem::replace(&mut into_iter, Vec::new().into_iter()); + /// (&mut into_iter).for_each(drop); + /// std::mem::forget(into_iter); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # drop(unsafe { Vec::::from_raw_parts(ptr, 0, 10) }); + /// ``` + /// + /// This method is used by in-place iteration, refer to the vec::in_place_collect + /// documentation for an overview. + #[cfg(not(no_global_oom_handling))] + pub(super) fn forget_allocation_drop_remaining(&mut self) { + let remaining = self.as_raw_mut_slice(); + + // overwrite the individual fields instead of creating a new + // struct and then overwriting &mut self. + // this creates less assembly + self.cap = 0; + self.buf = RawVec::new().non_null(); + self.ptr = self.buf; + self.end = self.buf.as_ptr(); + + // Dropping the remaining elements can panic, so this needs to be + // done only after updating the other fields. + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(remaining); + } + } + + /// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed. + /// + /// This method does not consume `self`, and leaves deallocation to `impl Drop for IntoIter`. + /// If consuming `self` is possible, consider calling + /// [`Self::forget_remaining_elements_and_dealloc()`] instead. + pub(crate) fn forget_remaining_elements(&mut self) + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& self1.end == self1.ptr.as_ptr(); + { + //@ open_points_to(self); + //@ open >.own(t, self0); + // For the ZST case, it is crucial that we mutate `end` here, not `ptr`. + // `ptr` must stay aligned, while `end` may be unaligned. + self.end = self.ptr.as_ptr(); + /*@ { + std::ptr::NonNull_Sized_as_ptr(self0.ptr); + if std::mem::size_of::() == 0 { + assert array_at_lft(?k, self0.ptr.as_ptr(), ?len, ?elems); + leak foreach(elems, own::(t)); + leak array_at_lft(k, self0.ptr.as_ptr(), len, elems); + close array_at_lft::(k, self0.ptr.as_ptr(), 0, nil); + close foreach(nil, own::(t)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, ?alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + leak foreach(elems, own::(t)); + array_at_lft_to_array_at_lft_::(self0.ptr.as_ptr()); + array_at_lft__join::(self0.buf.as_ptr() + adv); + close array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), 0, nil); + close foreach(nil, own::(t)); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.ptr.as_ptr(), adv, adv, nil); + } + close_points_to(self); + close >.own(t, *self); + } @*/ + } + + /// Forgets to Drop the remaining elements and frees the backing allocation. + /// Consuming version of [`Self::forget_remaining_elements()`]. + /// + /// This can be used in place of `drop(self)` when `self` is known to be exhausted, + /// to avoid producing a needless `drop_in_place::<[T]>()`. + #[inline] + pub(crate) fn forget_remaining_elements_and_dealloc(self) + //@ req thread_token(?t) &*& t == currentThread &*& >.own(t, self); + //@ ens thread_token(t); + { + //@ IntoIter_own_to_raw_buf::(t, self); + let mut this = ManuallyDrop::new(self); + // SAFETY: `this` is in ManuallyDrop, so it will not be double-freed. + unsafe { + this.dealloc_only(); + } + } + + /// Frees the allocation, without checking or dropping anything else. + /// + /// The safe version of this method is [`Self::forget_remaining_elements_and_dealloc()`]. + /// This function exists only to share code between that method and the `impl Drop`. + /// + /// # Safety + /// + /// This function must only be called with an [`IntoIter`] that is not going to be dropped + /// or otherwise used in any way, either because it is being forgotten or because its `Drop` + /// is already executing; otherwise a double-free will occur, and possibly a read from freed + /// memory if there are any remaining elements. + #[inline] + unsafe fn dealloc_only(&mut self) + //@ req thread_token(?t) &*& t == currentThread &*& *self |-> ?self0 &*& IntoIter_raw_buf::(t, self0); + //@ ens thread_token(t) &*& (*self).buf |-> _ &*& (*self).cap |-> _ &*& (*self).alloc |-?-> _ &*& (*self).ptr |-> _ &*& (*self).end |-> _ &*& struct_IntoIter_padding(self); + { + //@ open_points_to(self); + //@ open IntoIter_raw_buf::(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + // SAFETY: our caller promises not to touch `*self` again. + let alloc = unsafe { manually_drop_take__VeriFast_wrapper(&mut self.alloc) }; + /*@ + if std::mem::size_of::() != 0 { + std::alloc::Layout_inv(Layout::new::()); + if self0.cap != 0 { raw_vec::mul_zero(self0.cap, std::mem::size_of::()); } + } + @*/ + // SAFETY: We're using this to deallocate a preexisting `RawVec`. + { + let mut _rv = unsafe { RawVec::from_nonnull_in(self.buf, self.cap, alloc) }; + /*@ { + assert RawVec(t, ?rv_val, alloc_id, self0.buf.as_ptr(), ?cap_); + if std::mem::size_of::() == 0 { + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() as *u8, 0, nil); + u8s_at_lft__to_array_at_lft_::(self0.buf.as_ptr(), cap_); + } + RawVec_to_own(rv_val); + close_points_to(&_rv); + } @*/ + } + //@ assert points_to_::>(?rv_p, _); + //@ open_points_to_(rv_p); + //@ open_points_to_(&(*rv_p).inner); + } + + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn into_vecdeque(self) -> VecDeque { + // Keep our `Drop` impl from dropping the elements and the allocator + let mut this = ManuallyDrop::new(self); + + let buf = this.buf.as_ptr(); + let initialized = if T::IS_ZST || this.len() == 0 { + // All the pointers are the same for ZSTs, so it's fine to + // say that they're all at the beginning of the "allocation". + // For non-ZSTs, we have length 0, so we can choose the (empty) + // range to be at the start of the buffer. + // + // Due to `0` ≤ `this.len()` ≤ `this.cap`, the range is well-formed, + // and due to the argument above it spans exactly the elements of + // this iterator. Because `init.start` = `0`, it follows that either + // `init.start` < `cap` or `cap` = `init.start` = `0`; thus the range + // satisfies the requirements of `from_contiguous_raw_parts_in`. + 0..this.len() + } else { + // SAFETY: `this.ptr` and `this.end` are created via offsets of `this.buf`, + // so they point to the same allocation. We have `this.buf` ≤ `this.ptr` ≤ `this.end`, + // so this cannot wrap, and will produce a well-formed range that spans exactly + // the elements of this iterator. + // + // Additionally, due to `end ≤ buf + cap`, we have `init.start` ≤ `init.end` ≤ `cap`. + // Due to the length check above, `init.start < cap`, so the range satisfies the + // requirements of `from_contiguous_raw_parts_in`. + unsafe { this.ptr.offset_from_unsigned(this.buf)..this.end.offset_from_unsigned(buf) } + }; + + let cap = this.cap; + // SAFETY: `this` is forgotten afterwards, so we can move out the allocator. + let alloc = unsafe { ManuallyDrop::take(&mut this.alloc) }; + + // SAFETY: This allocation originally came from a `Vec`, so it satisfies all + // requirements for the `buf` pointer with capacity `cap` allocated in `alloc`. + // Correctness of `initialized` was shown above. + unsafe { VecDeque::from_contiguous_raw_parts_in(buf, initialized, cap, alloc) } + } +} + +#[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")] +impl AsRef<[T]> for IntoIter { + fn as_ref(&self) -> &[T] { + self.as_slice() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for IntoIter {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for IntoIter {} + +// Loop-invariant predicates for `IntoIter::fold` and `IntoIter::try_fold`. +// Marked `#[inline(always)]` and written with pure intrinsics and `const { ... }` +// blocks rather than method calls (e.g. `NonNull::as_ptr` / `pointer::addr` / +// non-const `mem::size_of`) so Kani's loop-contract lowering evaluates them +// inline as side-effect-free CBMC expressions without emitting nondeterministic +// helper calls (https://github.com/model-checking/kani/issues/4796). +// `self.alloc` is untouched by either loop and is preserved across loop +// contracts (verified with both `TrackAlloc` and non-ZST `StatefulAlloc`). +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, and `usize` have identical layout (thin pointer width); + // these casts are side-effect-free re-interpretations for CBMC's loop-invariant evaluator. + let (ptr_p, eptr_p, buf_p, ebuf_p, ptr_a, eptr_a, end_a, eend_a): ( + *const T, + *const T, + *const T, + *const T, + usize, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + core::intrinsics::transmute_unchecked(entry_end), + ) + }; + ptr_p == eptr_p + && buf_p == ebuf_p + && cap == entry_cap + && core::intrinsics::wrapping_sub(end_a, ptr_a) + <= core::intrinsics::wrapping_sub(eend_a, eptr_a) +} + +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_non_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, `*const u8`, and `usize` have identical thin-pointer + // layout; used to avoid method calls in CBMC loop-contract predicates (kani#4796). + let (buf_p, ebuf_p, ptr_p, eptr_u8, ptr_a, eptr_a, end_a): ( + *const T, + *const T, + *const T, + *const u8, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + ) + }; + let diff = core::intrinsics::wrapping_sub(ptr_a, eptr_a); + let span = core::intrinsics::wrapping_sub(end_a, eptr_a); + let sz = const { core::mem::size_of::() }; + let aligned = if const { core::mem::size_of::().is_power_of_two() } { + (diff & core::intrinsics::wrapping_sub(sz, 1)) == 0 + } else { + // Exact divisibility `diff % sz == 0` for any non-power-of-two `sz > 0` without a + // 64-bit integer division circuit: write `sz = odd * 2^tz` and compute the modular + // multiplicative inverse `odd_inv` (`odd * odd_inv == 1 mod 2^BITS`) at const time. + // Then `sz | diff` iff `2^tz | diff` and `(diff >> tz) * odd_inv <= usize::MAX / sz`. + let (tz, odd_inv, max_q) = const { + let s = core::mem::size_of::(); + if s == 0 { + (0u32, 1usize, 0usize) + } else { + let tz = s.trailing_zeros(); + let odd = s >> tz; + let mut inv: usize = 1; + let mut i = 0; + while i < 6 { + inv = inv.wrapping_mul(2usize.wrapping_sub(odd.wrapping_mul(inv))); + i += 1; + } + assert!(odd.wrapping_mul(inv) == 1); + (tz, inv, usize::MAX / s) + } + }; + let low_mask = core::intrinsics::wrapping_sub(1usize << tz, 1); + (diff & low_mask) == 0 && core::intrinsics::wrapping_mul(diff >> tz, odd_inv) <= max_q + }; + // SAFETY: `arith_offset` is wrapping (non-UB) pointer arithmetic; short-circuiting after + // `diff <= span && aligned` additionally guarantees `diff` stays within `[entry_ptr, end]`. + buf_p == ebuf_p + && cap == entry_cap + && end == entry_end + && diff <= span + && aligned + && ptr_p == unsafe { core::intrinsics::arith_offset(eptr_u8, diff as isize) as *const T } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Iterator for IntoIter { + type Item = T; + + #[inline] + fn next(&mut self) -> Option + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + //@ open_points_to(self); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(self0.ptr); + let ptr = if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut T { + /*@ { + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // `ptr` has to stay where it is to remain aligned, so we reduce the length by 1 by + // reducing the `end`. + //@ wrapping_sub_usize_zero(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(self0.end as usize, self0.ptr.as_ptr() as usize); + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + self.ptr + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let is_eq = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + if is_eq { + /*@ { + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv, end_idx, elems); + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + let old = self.ptr; + // ignore-tidy-undocumented-unsafe + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(1, self0.cap, std::mem::size_of::()); + //@ open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), end_idx - adv, elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?x0); + //@ points_to_at_lft_inv(self0.ptr.as_ptr()); + //@ let q_add = lifetime_token_trade(flft, 1/4, alloc_id.lft); + //@ close LiveSlot::(self0.ptr.as_ptr(), alloc_id.lft, q_add, 1, some(x0)); + self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(old) }; + //@ open LiveSlot::(self0.ptr.as_ptr(), alloc_id.lft, q_add, 1, some(x0)); + //@ lifetime_token_trade_back(q_add, alloc_id.lft); + old + }; + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + open foreach(elems_z, own::(t)); + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xz); + open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + open own::(t)(xz); + } else { + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xnz); + open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + open own::(t)(xnz); + } + } @*/ + // ignore-tidy-undocumented-unsafe + let res = Some(unsafe { non_null_read__VeriFast_wrapper(ptr) }); + /*@ { + close_points_to_at_lft_(self0.ptr.as_ptr()); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + if std::mem::size_of::() == 0 { + leak points_to_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), _); + } else { + // Re-pack consumed prefix [0..adv+1) + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv0, _); + assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + 1, ?rem0, ?elems_rest); + close array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr() + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr(), 1, _); + array_at_lft__join::(self0.buf.as_ptr()); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, (*self).ptr, self0.end, adv0 + 1, adv0 + 1 + rem0, elems_rest); + } + close_points_to(self); + close >.own(t, *self); + close >.own(t, res); + } @*/ + res + } + + #[inline] + fn size_hint(&self) -> (usize, Option) + //@ req thread_token(?t) &*& [_]IntoIter_share_::(?k, t, self, ?len) &*& [?q]lifetime_token(k); + //@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result.0 == len &*& result.1 == Some(len); + /*@ + safety_proof { + open >.share(?k, _t, self); + let r = call(); + close usize_own(_t, r.0); + close >.own(_t, r.1); + close usize_own(_t, r.0); + tuple_ext::close_tuple_2_own::>(_t, r); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ open IntoIter_share_::(k, t, self, len); + //@ assert [_]std::alloc::Allocator_share(k, t, &(*self).alloc, ?alloc_id); + //@ assert [_]exists::>(?v); + //@ open_frac_borrow(k, IntoIter_shared_val::(self, v), q/2); + //@ open [?f]IntoIter_shared_val::(self, v)(); + let exact = if T::IS_ZST { + let end_a = const_ptr_addr__VeriFast_wrapper(self.end); + let ptr_a = mut_ptr_addr__VeriFast_wrapper(self.ptr.as_ptr()); + end_a.wrapping_sub(ptr_a) + } else { + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + // ignore-tidy-undocumented-unsafe + let end_nn = unsafe { non_null_from_end__VeriFast_wrapper(&self.end) }; + //@ end_ref_readonly(end_r); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ assert [_]exists::>(?elems); + //@ open_frac_borrow(k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems), q/2); + //@ open [?fr]IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close LiveRange::(v.ptr.as_ptr(), len, alloc_id.lft, q_alloc, fr, elems); + let d = unsafe { non_null_offset_from_unsigned__VeriFast_wrapper(end_nn, self.ptr) }; + //@ open LiveRange::(v.ptr.as_ptr(), len, alloc_id.lft, q_alloc, fr, elems); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ close [fr]IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + //@ close_frac_borrow(fr, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + d + }; + //@ close [f]IntoIter_shared_val::(self, v)(); + //@ close_frac_borrow(f, IntoIter_shared_val::(self, v)); + (exact, Some(exact)) + } + + #[inline] + fn advance_by<'s>(/*@~mut@*/ self: &'s mut Self, n: usize) -> Result<(), NonZero> + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >>.own(t, result); + /*@ + safety_proof { + assert [?q]lifetime_token('s); + open_full_borrow(q, 's, (>.full_borrow_content)(_t, self)); + open_full_borrow_content::>(_t, self); + let r = call(); + close_full_borrow_content::>(_t, self); + close_full_borrow((>.full_borrow_content)(_t, self)); + leak full_borrow('s, (>.full_borrow_content)(_t, self)); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ let self_p0 = self; + //@ open_points_to(self_p0); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + close exists::(std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv0, ?end0, ?elems0); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv0, end0, elems0); + close exists::(end0 - adv0); + } + } @*/ + //@ open exists::(?len0); + //@ let k_len = begin_lifetime(); + //@ close IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + //@ borrow(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ IntoIter_share_val_fbc::(k_len, t, self_p0, self0, alloc_id, len0); + let cur_len; + unsafe { + //@ let_lft 'a = flft; + //@ let self_r = precreate_ref(&self); + //@ init_ref_readonly(self_r, 1/2); + cur_len = exact_size_len__VeriFast_wrapper/*@::@*/(&self); + //@ end_ref_readonly(self_r); + } + //@ end_lifetime(k_len); + //@ borrow_end(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ open IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + let step_size = usize_min__VeriFast_wrapper(cur_len, n); + let to_drop = self.ptr.as_ptr().cast_slice(step_size); + if T::IS_ZST { + // See `next` for why we sub `end` here. + //@ wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + self.end = const_ptr_wrapping_byte_sub__VeriFast_wrapper(self.end, step_size); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize), ?elems_z); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems_z, own::(t), step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems_z)); + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(step_size, self0.cap, std::mem::size_of::()); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems, own::(t), step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems)); + //@ if step_size == end_idx - adv { assert self0.ptr.as_ptr() + step_size == self0.end; } else { assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, ?rest_e); open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, rest_e); assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr() + step_size, ?xv); let q_nz = lifetime_token_trade(flft, 1/4, alloc_id.lft); open_points_to_at_lft(self0.ptr.as_ptr() + step_size, q_nz/2); points_to_limits(self0.ptr.as_ptr() + step_size); close_points_to_at_lft(self0.ptr.as_ptr() + step_size); lifetime_token_trade_back(q_nz, alloc_id.lft); close array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, rest_e); } + //@ let q_add = lifetime_token_trade(flft, 1/4, alloc_id.lft); + //@ close LiveRange::(self0.ptr.as_ptr(), step_size, alloc_id.lft, q_add, 1, take(step_size, elems)); + // SAFETY: the min() above ensures that step_size is in bounds + self.ptr = unsafe { non_null_add__VeriFast_wrapper(self.ptr, step_size) }; + //@ open LiveRange::(self0.ptr.as_ptr(), step_size, alloc_id.lft, q_add, 1, take(step_size, elems)); + //@ lifetime_token_trade_back(q_add, alloc_id.lft); + } + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close_points_to_slice_at_lft(to_drop); + //@ open_points_to_at_lft(to_drop, q_alloc/2); + // SAFETY: the min() above ensures that step_size is in bounds + unsafe { + ptr::drop_in_place(to_drop); + } + //@ close_points_to_at_lft_(to_drop); + //@ open_points_to_slice_at_lft_(to_drop); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + let self_p = self; + if std::mem::size_of::() == 0 { + leak array_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), step_size, _); + } else { + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv1, _); + if step_size == 0 { + open array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr(), 0, _); + } else { + array_at_lft__join::(self0.buf.as_ptr()); + } + assert (*self_p).ptr |-> ?new_ptr &*& array_at_lft(alloc_id.lft, new_ptr.as_ptr(), ?rem1, ?elems1); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, new_ptr, self0.end, adv1 + step_size, adv1 + step_size + rem1, elems1); + } + close_points_to(self_p); + assert *self_p |-> ?self1; + close >.own(t, self1); + } @*/ + unsafe { non_zero_rem__VeriFast_wrapper(n - step_size) } + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + #[inline] + fn last(mut self) -> Option { + self.next_back() + } + + #[inline] + fn next_chunk(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { raw_ary.transpose().assume_init() }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available and we + // just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, N); + self.ptr = self.ptr.add(N); + Ok(raw_ary.transpose().assume_init()) + } + } + + #[inline] + fn fold(mut self, mut accum: B, mut f: F) -> B + where + F: FnMut(B, T) -> B, + //@ req thread_token(?t) &*& t == currentThread &*& >.own(t, self) &*& .own(t, accum) &*& .own(t, f); + //@ ens thread_token(t) &*& .own(t, result); + { + //@ assert lifetime_token(?flft); + //@ close_points_to(&self); + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *(&self) |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(&self); + let ptr_raw = self.ptr.as_ptr(); + let end_mut = const_ptr_cast_mut__VeriFast_wrapper(self.end); + let cont = ptr_raw != end_mut; + //@ close_points_to(&self); + cont + } { + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(cur_it.ptr); + //@ wrapping_sub_usize_zero(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ let old_len = std::num::wrapping_sub_usize(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), old_len, ?elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ leak points_to_at_lft_(alloc_id.lft, cur_it.ptr.as_ptr(), _); + // See `next` for why we subtract from `end` here. + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + //@ close_points_to(&self); + //@ close >.own(t, *(&self)); + accum = call_fold__VeriFast_wrapper(&mut f, accum, tmp); + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *(&self) |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id_c); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, ?adv_c, ?end_idx_c, ?elems_c); + //@ let ptr_r = precreate_ref(&self.ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&self.end); + //@ init_ref_readonly(end_r, 1/2); + let is_ne = unsafe { ptr_ne_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + //@ close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, adv_c, end_idx_c, elems_c); + //@ close_points_to(&self); + //@ close >.own(t, *(&self)); + is_ne + } { + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, cur_it.ptr, cur_it.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(1, cur_it.cap, std::mem::size_of::()); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), end_idx - adv, elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ points_to_at_lft_inv(cur_it.ptr.as_ptr()); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ close LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(self.ptr) }; + //@ open LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr() + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr(), 1, _); + array_at_lft__join::(cur_it.buf.as_ptr()); + assert array_at_lft(alloc_id.lft, cur_it.ptr.as_ptr() + 1, end_idx - adv - 1, ?elems_rest); + close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, self.ptr, cur_it.end, adv + 1, end_idx, elems_rest); + close_points_to(&self); + close >.own(t, *(&self)); + } @*/ + accum = call_fold__VeriFast_wrapper(&mut f, accum, tmp); + } + } + + //@ open_points_to(&self); + // There are in fact no remaining elements to forget, but by doing this we can avoid + // potentially generating a needless loop to drop the elements that cannot exist at + // this point. + self.forget_remaining_elements_and_dealloc(); + //@ close_points_to(&self); + + accum + } + + #[inline] + fn try_fold(&mut self, mut accum: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, T) -> R, + R: core::ops::Try, + { + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr.as_ptr() != self.end.cast_mut() { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // See `next` for why we subtract from `end` here. + self.end = self.end.wrapping_byte_sub(1); + accum = f(accum, tmp)?; + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr != non_null!(self.end, T) { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { self.ptr.add(1) }; + accum = f(accum, tmp)?; + } + } + R::from_output(accum) + } + #[requires(i < self.len())] + #[cfg_attr(kani, kani::modifies(self))] + unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item + where + Self: TrustedRandomAccessNoCoerce, + { + // SAFETY: the caller must guarantee that `i` is in bounds of the + // `Vec`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)` + // is guaranteed to pointer to an element of the `Vec` and + // thus guaranteed to be valid to dereference. + // + // Also note the implementation of `Self: TrustedRandomAccess` requires + // that `T: Copy` so reading elements from the buffer doesn't invalidate + // them for `Drop`. + unsafe { self.ptr.add(i).read() } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl DoubleEndedIterator for IntoIter { + #[inline] + fn next_back(&mut self) -> Option + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + //@ open_points_to(self); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(self0.ptr); + if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut _ { + /*@ { + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // See above for why 'ptr.offset' isn't used + //@ wrapping_sub_usize_zero(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(self0.end as usize, self0.ptr.as_ptr() as usize); + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + //@ let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + //@ open foreach(elems_z, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xz); + //@ open own::(t)(xz); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + // Note that even though this is next_back() we're reading from `self.ptr`, not + // `self.end`. We track our length using the byte offset from `self.ptr` to `self.end`, + // so the end pointer may not be suitably aligned for T. + // ignore-tidy-undocumented-unsafe + let res = Some(unsafe { ptr::read(self.ptr.as_ptr()) }); + /*@ { + close_points_to_at_lft_(self0.ptr.as_ptr()); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + leak points_to_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), _); + close_points_to(self); + close >.own(t, *self); + close >.own(t, Some(xz)); + } @*/ + res + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let is_eq = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + if is_eq { + /*@ { + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv, end_idx, elems); + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // ignore-tidy-undocumented-unsafe + unsafe { + /*@ { + let rem = end_idx - adv; + list_split_last(elems); + array_at_lft_split::(self0.ptr.as_ptr(), rem - 1); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + (rem - 1), 1, _); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + rem, 0, _); + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr() + (rem - 1), ?xlast); + foreach_snoc_inv(take(rem - 1, elems), xlast, own::(t)); + open own::(t)(xlast); + points_to_at_lft_inv(self0.ptr.as_ptr() + (rem - 1)); + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(1, self0.cap, std::mem::size_of::()); + } @*/ + self.end = self.end.sub(1); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(self0.buf.as_ptr() + (end_idx - 1), q_alloc/2); + let val = ptr::read(self.end); + let res = Some(val); + /*@ { + close_points_to_at_lft_(self0.buf.as_ptr() + (end_idx - 1)); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() + end_idx, 0, nil); + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() + (end_idx - 1), 1, _); + array_at_lft__join::(self0.buf.as_ptr() + (end_idx - 1)); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, (*self).end, adv, end_idx - 1, take(end_idx - adv - 1, elems)); + close_points_to(self); + close >.own(t, *self); + close >.own(t, Some(val)); + } @*/ + res + } + } + } + + #[inline] + fn next_chunk_back(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, N - len..N) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { MaybeUninit::array_assume_init(raw_ary) }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available + // and we just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping( + self.ptr.add(len - N).as_ptr(), + raw_ary.as_mut_ptr() as *mut T, + N, + ); + self.end = self.end.sub(N); + Ok(MaybeUninit::array_assume_init(raw_ary)) + } + } + + #[inline] + fn advance_back_by<'s>(/*@~mut@*/ self: &'s mut Self, n: usize) -> Result<(), NonZero> + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >>.own(t, result); + /*@ + safety_proof { + assert [?q]lifetime_token('s); + open_full_borrow(q, 's, (>.full_borrow_content)(_t, self)); + open_full_borrow_content::>(_t, self); + let r = call(); + close_full_borrow_content::>(_t, self); + close_full_borrow((>.full_borrow_content)(_t, self)); + leak full_borrow('s, (>.full_borrow_content)(_t, self)); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ let self_p0 = self; + //@ open_points_to(self_p0); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + close exists::(std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv0, ?end0, ?elems0); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv0, end0, elems0); + close exists::(end0 - adv0); + } + } @*/ + //@ open exists::(?len0); + //@ let k_len = begin_lifetime(); + //@ close IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + //@ borrow(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ IntoIter_share_val_fbc::(k_len, t, self_p0, self0, alloc_id, len0); + let cur_len; + unsafe { + //@ let_lft 'a = flft; + //@ let self_r = precreate_ref(&self); + //@ init_ref_readonly(self_r, 1/2); + cur_len = exact_size_len__VeriFast_wrapper/*@::@*/(&self); + //@ end_ref_readonly(self_r); + } + //@ end_lifetime(k_len); + //@ borrow_end(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ open IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + let step_size = usize_min__VeriFast_wrapper(cur_len, n); + if T::IS_ZST { + // SAFETY: same as for advance_by() + //@ wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + self.end = const_ptr_wrapping_byte_sub__VeriFast_wrapper(self.end, step_size); + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(step_size, self0.cap, std::mem::size_of::()); + //@ mul_mono_l(1, std::mem::size_of::(), self0.cap); + //@ let keep_n = (end_idx - adv) - step_size; + //@ array_at_lft_split::(self0.ptr.as_ptr(), keep_n); + //@ foreach_split(elems, own::(t), keep_n); + // SAFETY: same as for advance_by() + self.end = unsafe { self.end.sub(step_size) }; + } + let to_drop = if T::IS_ZST { + // ZST may cause unalignment + let d = unsafe { non_null_dangling__VeriFast_wrapper::() }.as_ptr(); + //@ let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems_z, own::(t), step_size); + //@ zst_array_at_lft_move::(take(step_size, elems_z), alloc_id.lft, self0.ptr.as_ptr(), d, step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems_z)); + d.cast_slice(step_size) + } else { + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?keep1, ?keep_elems); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + keep1, step_size, ?drop_elems); + //@ close_slice_own_from_foreach::(t, drop_elems); + const_ptr_cast_t_mut__VeriFast_wrapper(self.end).cast_slice(step_size) + }; + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close_points_to_slice_at_lft(to_drop); + //@ open_points_to_at_lft(to_drop, q_alloc/2); + // SAFETY: same as for advance_by() + unsafe { + ptr::drop_in_place(to_drop); + } + //@ close_points_to_at_lft_(to_drop); + //@ open_points_to_slice_at_lft_(to_drop); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + let self_p = self; + if std::mem::size_of::() == 0 { + leak array_at_lft_(alloc_id.lft, to_drop as *T, step_size, _); + assert (*self_p).end |-> ?new_end; + assert (new_end as usize) == std::num::wrapping_sub_usize(self0.end as usize, step_size); + wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + assert array_at_lft(alloc_id.lft, ?p_rem, ?rem_z, ?rem_elems); + zst_array_at_lft_move::(rem_elems, alloc_id.lft, p_rem, self0.ptr.as_ptr(), rem_z); + assert rem_z == std::num::wrapping_sub_usize(new_end as usize, self0.ptr.as_ptr() as usize); + } else { + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv1, _); + assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?keep2, ?keep_elems2); + array_at_lft__join::(self0.buf.as_ptr() + (adv1 + keep2)); + assert (*self_p).end |-> ?new_end; + if keep2 == 0 { + assert new_end == self0.ptr.as_ptr(); + } else { + assert new_end != 0; + } + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, new_end, adv1, adv1 + keep2, keep_elems2); + } + close_points_to(self_p); + assert *self_p |-> ?self1; + close >.own(t, self1); + } @*/ + unsafe { non_zero_rem__VeriFast_wrapper(n - step_size) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ExactSizeIterator for IntoIter { + fn is_empty(&self) -> bool + //@ req thread_token(?t) &*& [_]IntoIter_share_::(?k, t, self, ?len) &*& [?q]lifetime_token(k); + //@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result == (len == 0); + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open IntoIter_share_::(k, t, self, len); + //@ assert [_]exists::>(?v); + //@ open_frac_borrow(k, IntoIter_shared_val::(self, v), q); + //@ open [?f]IntoIter_shared_val::(self, v)(); + let res = if T::IS_ZST { + //@ wrapping_sub_usize_zero(v.end as usize, v.ptr.as_ptr() as usize); + self.ptr.as_ptr() == self.end as *mut _ + } else { + //@ points_to_limits(&(*self).ptr); + //@ points_to_limits(&(*self).end); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let r = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ assert (v.end as usize) == (v.ptr.as_ptr() as usize) + len * std::mem::size_of::(); + //@ if len == 0 { match (v.ptr.as_ptr() as pointer) { pointer_ctor(prov, addr, meta) => {} } } else { mul_mono_l(1, len, std::mem::size_of::()); } + r + }; + //@ close [f]IntoIter_shared_val::(self, v)(); + //@ close_frac_borrow(f, IntoIter_shared_val::(self, v)); + res + } +} + +#[stable(feature = "fused", since = "1.26.0")] +impl FusedIterator for IntoIter {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "trusted_fused")] +unsafe impl TrustedFused for IntoIter {} + +#[unstable(feature = "trusted_len", issue = "37572")] +unsafe impl TrustedLen for IntoIter {} + +#[stable(feature = "default_iters", since = "1.70.0")] +impl Default for IntoIter +where + A: Allocator + Default, +{ + /// Creates an empty `vec::IntoIter`. + /// + /// ``` + /// # use std::vec; + /// let iter: vec::IntoIter = Default::default(); + /// assert_eq!(iter.len(), 0); + /// assert_eq!(iter.as_slice(), &[]); + /// ``` + fn default() -> Self { + super::Vec::new_in(Default::default()).into_iter() + } +} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +#[unsafe(rustc_allow_lifetime_dependent_specialization)] +trait NonDrop {} + +// T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr +// and thus we can't implement drop-handling +#[unstable(issue = "none", feature = "std_internals")] +impl NonDrop for T {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +// TrustedRandomAccess (without NoCoerce) must not be implemented because +// subtypes/supertypes of `T` might not be `NonDrop` +unsafe impl TrustedRandomAccessNoCoerce for IntoIter +where + T: NonDrop, +{ + const MAY_HAVE_SIDE_EFFECT: bool = false; +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_into_iter_clone", since = "1.8.0")] +impl Clone for IntoIter { + fn clone(&self) -> Self { + self.as_slice().to_vec_in(self.alloc.deref().clone()).into_iter() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter { + fn drop(&mut self) { + struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter); + + impl Drop for DropGuard<'_, T, A> { + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + self.0.dealloc_only(); + } + } + } + + let guard = DropGuard(self); + // destroy the remaining elements + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(guard.0.as_raw_mut_slice()); + } + // now `guard` will be dropped and do the rest + } +} +// In addition to the SAFETY invariants of the following three unsafe traits +// also refer to the vec::in_place_collect module documentation to get an overview +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl InPlaceIterable for IntoIter { + const EXPAND_BY: Option> = NonZero::new(1); + const MERGE_BY: Option> = NonZero::new(1); +} + +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl SourceIter for IntoIter { + type Source = Self; + + #[inline] + unsafe fn as_inner(&mut self) -> &mut Self::Source { + self + } +} + +#[cfg(not(no_global_oom_handling))] +unsafe impl AsVecIntoIter for IntoIter { + type Item = T; + + fn as_into_iter(&mut self) -> &mut IntoIter { + self + } +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs/verified/lib.rs b/verifast-proofs/alloc/vec/into_iter.rs/verified/lib.rs new file mode 100644 index 0000000000000..04df50d3f3c01 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/verified/lib.rs @@ -0,0 +1,316 @@ +// verifast_options{skip_specless_fns ignore_unwind_paths} + +#![allow(dead_code)] +#![no_std] +#![allow(internal_features)] +#![allow(incomplete_features)] +#![feature(allocator_ext)] +#![feature(staged_api)] +#![feature(rustc_attrs)] +#![feature(dropck_eyepatch)] +#![feature(specialization)] +#![feature(extend_one)] +#![feature(exact_size_is_empty)] +#![feature(hasher_prefixfree_extras)] +#![feature(try_trait_v2)] +#![feature(optimize_attribute)] +#![feature(temporary_niche_types)] +#![feature(ptr_internals)] +#![feature(ptr_alignment_type)] +#![feature(ptr_cast_slice)] +#![feature(const_closures)] +#![feature(const_result_trait_fn)] +#![feature(sized_type_properties)] +#![feature(std_internals)] +#![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_destruct)] +#![feature(const_heap)] +#![feature(const_option_ops)] +#![feature(const_trait_impl)] +#![feature(const_try)] +#![feature(panic_internals)] +#![feature(decl_macro)] +#![feature(trusted_len)] +#![feature(trusted_fused)] +#![feature(trusted_random_access)] +#![feature(inplace_iteration)] +#![feature(iter_next_chunk)] +#![feature(iter_advance_by)] +#![feature(array_into_iter_constructors)] +#![feature(maybe_uninit_array_assume_init)] +#![feature(maybe_uninit_uninit_array_transpose)] +#![feature(proc_macro_hygiene)] +#![feature(stmt_expr_attributes)] +#![feature(lang_items)] + +#![stable(feature = "rust1", since = "1.0.0")] + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod alloc { + #[stable(feature = "rust1", since = "1.0.0")] + pub use core::alloc::*; + use core::ptr::NonNull; + + #[stable(feature = "rust1", since = "1.0.0")] + #[derive(Copy, Clone, Default, Debug)] + #[lang = "global_alloc_ty"] + pub struct Global; + + #[stable(feature = "rust1", since = "1.0.0")] + unsafe impl Allocator for Global { + fn allocate(&self, _layout: Layout) -> Result, AllocError> { loop {} } + unsafe fn deallocate(&self, _ptr: NonNull, _layout: Layout) { loop {} } + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_alloc_error", issue = "none")] + pub const fn handle_alloc_error(_layout: Layout) -> ! + //@ req true; + //@ ens false; + { loop { /*@ inv true; @*/ } } +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod boxed { + use core::ptr::Unique; + use crate::alloc::{Allocator, Global}; + + /*@ + pred Box_in(t: thread_id_t, self: Box, alloc_id: std::alloc::alloc_id_t, value: T); + @*/ + + #[stable(feature = "rust1", since = "1.0.0")] + #[lang = "owned_box"] + pub struct Box(Unique, A); + + impl Box { + #[stable(feature = "rust1", since = "1.0.0")] + pub unsafe fn from_raw_in(_raw: *mut T, _alloc: A) -> Self + /*@ + req std::alloc::Allocator(?t, _alloc, ?alloc_id) &*& + points_to_at_lft(alloc_id.lft, _raw, ?value) &*& + if std::mem::size_of_val(_raw) == 0 { + true + } else { + std::alloc::alloc_block_in(alloc_id, _raw as *u8, std::alloc::Layout::for_value(_raw)) + }; + @*/ + //@ ens Box_in::(t, result, alloc_id, value); + //@ on_unwind_ens false; + //@ assume_correct + { loop {} } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod collections { + use core::marker::PhantomData; + use crate::alloc::{Allocator, Global, Layout}; + + #[stable(feature = "rust1", since = "1.0.0")] + #[derive(Copy, Clone, PartialEq, Eq, Debug)] + pub struct TryReserveError { + kind: TryReserveErrorKind, + } + + /*@ + pred_ctor TryReserveError_val(l: *TryReserveError, v: TryReserveError)(;) = *l |-> v; + pred .own(t, v) = .own(t, v.kind); + pred .share(k, t, l) = [_]exists::(?v) &*& [_]frac_borrow(k, TryReserveError_val(l, v)); + lem TryReserveError_drop() + req TryReserveError_own(?_t, ?_v); + ens .own(_t, _v.kind); + { + open TryReserveError_own(_t, _v); + } + lem TryReserveError_send(t1: thread_id_t) + req TryReserveError_own(?t0, ?v); + ens TryReserveError_own(t1, v); + { + open TryReserveError_own(t0, v); + open TryReserveErrorKind_own(t0, v.kind); match v.kind { TryReserveErrorKind::CapacityOverflow => {} TryReserveErrorKind::AllocError(layout, non_exhaustive) => { leak std::alloc::Layout_own(t0, layout); std::alloc::close_Layout_own(t1, layout); tuple_0_eq(non_exhaustive); open_tuple_0_own(t0); close_tuple_0_own(t1); } } close TryReserveErrorKind_own(t1, v.kind); + close TryReserveError_own(t1, v); + } + lem TryReserveError_sync(t1: thread_id_t) + req [_]TryReserveError_share(?k, ?t0, ?l); + ens [_]TryReserveError_share(k, t1, l); + { + open TryReserveError_share(k, t0, l); + close TryReserveError_share(k, t1, l); + leak TryReserveError_share(k, t1, l); + } + lem TryReserveError_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *TryReserveError) + req lifetime_inclusion(k1, k) == true &*& [_]TryReserveError_share(k, t, l); + ens [_]TryReserveError_share(k1, t, l); + { + open TryReserveError_share(k, t, l); + assert [_]exists::(?v); + frac_borrow_mono(k, k1, TryReserveError_val(l, v)); + close TryReserveError_share(k1, t, l); + leak TryReserveError_share(k1, t, l); + } + lem TryReserveError_share_full(k: lifetime_t, t: thread_id_t, l: *TryReserveError) + req atomic_mask(MaskTop) &*& full_borrow(k, TryReserveError_full_borrow_content(t, l)) &*& [?q]lifetime_token(k); + ens atomic_mask(MaskTop) &*& [_]TryReserveError_share(k, t, l) &*& [q]lifetime_token(k); + { + let klong = open_full_borrow_strong_m(k, TryReserveError_full_borrow_content(t, l), q); + open TryReserveError_full_borrow_content(t, l)(); + assert *l |-> ?v; + open TryReserveError_own(t, v); + close TryReserveError_val(l, v)(); + { + pred Ctx() = .own(t, v.kind); + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, TryReserveError_val(l, v), klong, TryReserveError_full_borrow_content(t, l))() { + open Ctx(); + open TryReserveError_val(l, v)(); + close TryReserveError_own(t, v); + close TryReserveError_full_borrow_content(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m(klong, TryReserveError_full_borrow_content(t, l), TryReserveError_val(l, v)); + full_borrow_into_frac_m(klong, TryReserveError_val(l, v)); + frac_borrow_mono(klong, k, TryReserveError_val(l, v)); + } + } + close exists::(v); + leak exists::(v); + close TryReserveError_share(k, t, l); + leak TryReserveError_share(k, t, l); + } + lem init_ref_TryReserveError(p: *TryReserveError) + req atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& [_]TryReserveError_share(?k, ?t, x) &*& [?q]lifetime_token(k); + ens atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]TryReserveError_share(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); + { + open TryReserveError_share(k, t, x); + assert [_]exists::(?v); + let klong = open_frac_borrow_strong_m(k, TryReserveError_val(x, v), q); + open [?f]TryReserveError_val(x, v)(); + init_ref_readonly(p, 1/2); + { + pred Ctx() = ref_readonly_end_token(p, x, f/2) &*& [f/2](*x |-> v) &*& [1 - f/2]ref_initialized(p); + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f/2, sep_(ref_initialized_(p), TryReserveError_val(p, v))), klong, f, TryReserveError_val(x, v))() { + open scaledp(f/2, sep_(ref_initialized_(p), TryReserveError_val(p, v)))(); + open sep_(ref_initialized_(p), TryReserveError_val(p, v))(); + open ref_initialized_::(p)(); + open TryReserveError_val(p, v)(); + open Ctx(); + end_ref_readonly(p); + close [f]TryReserveError_val(x, v)(); + } { + close Ctx(); + close [f/2]ref_initialized_::(p)(); + close [f/2]TryReserveError_val(p, v)(); + close [f/2]sep_(ref_initialized_(p), TryReserveError_val(p, v))(); + close scaledp(f/2, sep_(ref_initialized_(p), TryReserveError_val(p, v)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), TryReserveError_val(p, v)))); + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(p), TryReserveError_val(p, v)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), TryReserveError_val(p, v))); + frac_borrow_split(k, ref_initialized_(p), TryReserveError_val(p, v)); + } + } + close TryReserveError_share(k, t, p); + leak TryReserveError_share(k, t, p); + } + @*/ + + impl TryReserveError { + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_try_reserve", issue = "none")] + pub(crate) const fn kind(&self) -> TryReserveErrorKind + //@ req [?f](*self |-> ?err); + //@ ens [f](*self |-> err) &*& result == err.kind; + /*@ + safety_proof { + open .share(?k, _t, self); + assert [?q]lifetime_token(k); + assert [_]exists::(?v); + open_frac_borrow(k, TryReserveError_val(self, v), q); + open [?f]TryReserveError_val(self, v)(); + call(); + close [f]TryReserveError_val(self, v)(); + close_frac_borrow(f, TryReserveError_val(self, v)); + match v.kind { + TryReserveErrorKind::CapacityOverflow => {} + TryReserveErrorKind::AllocError(layout, ne) => { + std::alloc::close_Layout_own(_t, layout); + tuple_0_eq(ne); + close_tuple_0_own(_t); + } + } + close TryReserveErrorKind_own(_t, v.kind); + } + @*/ + { + self.kind + } + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[derive(Copy, Clone, PartialEq, Eq, Debug)] + pub enum TryReserveErrorKind { + CapacityOverflow, + AllocError { layout: Layout, non_exhaustive: () }, + } + + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_convert", issue = "143773")] + const impl From for TryReserveError { + fn from(kind: TryReserveErrorKind) -> Self + //@ req thread_token(?t) &*& .own(t, kind); + //@ ens thread_token(t) &*& .own(t, result); + { let r = Self { kind }; /*@ close .own(t, r); @*/ r } + } + + #[stable(feature = "rust1", since = "1.0.0")] + pub struct VecDeque(PhantomData<(T, A)>); + + impl VecDeque { + #[stable(feature = "rust1", since = "1.0.0")] + pub(crate) unsafe fn from_contiguous_raw_parts_in( + _ptr: *mut T, + _initialized: core::ops::Range, + _cap: usize, + _alloc: A, + ) -> Self { loop {} } + } +} + +impl [T] { + #[rustc_allow_incoherent_impl] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn to_vec_in(&self, _alloc: A) -> crate::Vec + where + T: Clone, + { + loop {} + } +} + +pub mod raw_vec; +#[stable(feature = "rust1", since = "1.0.0")] +pub mod into_iter; + +#[stable(feature = "rust1", since = "1.0.0")] +pub(crate) unsafe trait AsVecIntoIter { + type Item; + fn as_into_iter(&mut self) -> &mut into_iter::IntoIter; +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub struct Vec { + buf: raw_vec::RawVec, + len: usize, +} + +impl Vec { + #[stable(feature = "rust1", since = "1.0.0")] + pub fn new_in(alloc: A) -> Self { + Self { buf: raw_vec::RawVec::new_in(alloc), len: 0 } + } + #[stable(feature = "rust1", since = "1.0.0")] + pub fn into_iter(self) -> into_iter::IntoIter { + loop {} + } +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs/verified/raw_vec.rs b/verifast-proofs/alloc/vec/into_iter.rs/verified/raw_vec.rs new file mode 100644 index 0000000000000..540628a7e00a8 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/verified/raw_vec.rs @@ -0,0 +1,3321 @@ +#![unstable(feature = "raw_vec_internals", reason = "unstable const warnings", issue = "none")] +#![cfg_attr(test, allow(dead_code))] + +//@ use std::num::{niche_types::UsizeNoHighBit, NonZero}; +//@ use std::mem::Alignment; +//@ use std::ptr::{NonNull, NonNull_ptr, Unique}; +//@ use std::alloc::{Layout, alloc_id_t, Allocator, alloc_block_in}; +//@ use std::option::Option; + +// Note: This module is also included in the alloctests crate using #[path] to +// run the tests. See the comment there for an explanation why this is the case. + +use core::marker::{Destruct, PhantomData}; +use core::mem::{Alignment, ManuallyDrop, MaybeUninit, SizedTypeProperties}; +use core::panic::UnwindSafe; +use core::ptr::{self, NonNull}; +use core::{cmp, hint}; + +#[cfg(not(no_global_oom_handling))] +use crate::alloc::handle_alloc_error; +use crate::alloc::{Allocator, Global, Layout}; +use crate::boxed::Box; +use crate::collections::TryReserveError; +use crate::collections::TryReserveErrorKind::*; + +//@ use collections::{TryReserveError, TryReserveErrorKind}; + +#[cfg(test)] +mod tests; + +/*@ + +lem mul_zero(x: i32, y: i32) + req 0 <= x &*& 0 <= y; + ens (x * y == 0) == (x == 0 || y == 0); +{ + if x == 0 { + if y == 0 { + } else { + } + } else { + if y == 0 { + } else { + mul_mono_l(1, y, x); + } + } +} + +@*/ + +// One central function responsible for reporting capacity overflows. This'll +// ensure that the code generation related to these panics is minimal as there's +// only one location which panics rather than a bunch throughout the module. +#[cfg(not(no_global_oom_handling))] +#[cfg_attr(not(panic = "immediate-abort"), inline(never))] +const fn capacity_overflow() -> ! +//@ req thread_token(?t); +//@ ens false; +{ + panic!("capacity overflow"); +} + +enum AllocInit { + /// The contents of the new memory are uninitialized. + Uninitialized, + #[cfg(not(no_global_oom_handling))] + /// The new memory is guaranteed to be zeroed. + Zeroed, +} + +type Cap = core::num::niche_types::UsizeNoHighBit; + +//@ fix Cap::new(n: usize) -> UsizeNoHighBit { UsizeNoHighBit::new(n) } + +const ZERO_CAP: Cap = unsafe { Cap::new_unchecked(0) }; + +/// `Cap(cap)`, except if `T` is a ZST then `Cap::ZERO`. +/// +/// # Safety: cap must be <= `isize::MAX`. +const unsafe fn new_cap(cap: usize) -> Cap +//@ req std::mem::size_of::() == 0 || cap <= isize::MAX; +//@ ens result == if std::mem::size_of::() == 0 { Cap::new(0) } else { Cap::new(cap) }; +//@ on_unwind_ens false; +{ + if T::IS_ZST { ZERO_CAP } else { unsafe { Cap::new_unchecked(cap) } } +} + +/// A low-level utility for more ergonomically allocating, reallocating, and deallocating +/// a buffer of memory on the heap without having to worry about all the corner cases +/// involved. This type is excellent for building your own data structures like Vec and VecDeque. +/// In particular: +/// +/// * Produces `NonNull::dangling()` on zero-sized types. +/// * Produces `NonNull::dangling()` on zero-length allocations. +/// * Avoids freeing `NonNull::dangling()`. +/// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics). +/// * Guards against 32-bit systems allocating more than `isize::MAX` bytes. +/// * Provides niches for capacities greater than `isize::MAX`. +/// * Guards against overflowing your length. +/// * Calls `handle_alloc_error` for fallible allocations. +/// * Implements `Send`, `Sync` and `UnwindSafe` iff `(T, A)` does. +/// * Carries `PhantomData` for auto trait and `may_dangle` correctness. +/// * Uses the excess returned from the allocator to use the largest available capacity. +/// +/// This type does not in anyway inspect the memory that it manages. When dropped it *will* +/// free its memory, but it *won't* try to drop its contents. It is up to the user of `RawVec` +/// to handle the actual things *stored* inside of a `RawVec`. +/// +/// Note that the excess of a zero-sized types is always infinite, so `capacity()` always returns +/// `usize::MAX`. This means that you need to be careful when round-tripping this type with a +/// `Box<[T]>`, since `capacity()` won't yield the length. +#[allow(missing_debug_implementations)] +pub(crate) struct RawVec { + inner: RawVecInner, + _marker: PhantomData, +} + +/// Like a `RawVec`, but only generic over the allocator, not the type. +/// +/// As such, all the methods need the layout passed-in as a parameter. +/// +/// Having this separation reduces the amount of code we need to monomorphize, +/// as most operations don't need the actual type, just its layout. +#[allow(missing_debug_implementations)] +struct RawVecInner { + ptr: NonNull, + /// Never used for ZSTs; it's `capacity()`'s responsibility to return usize::MAX in that case. + /// + /// # Safety + /// + /// `cap` must be in the `0..=isize::MAX` range. + cap: Cap, + alloc: A, +} + +// FIXME: Consider moving these impls to `RawVec`, once #162850 is resolved. +unsafe impl Send for RawVecInner {} +unsafe impl Sync for RawVecInner {} +impl UnwindSafe for RawVecInner {} + +/*@ + +fix logical_capacity(cap: UsizeNoHighBit, elem_size: usize) -> usize { + if elem_size == 0 { usize::MAX } else { cap.as_inner() } +} + +pred RawVecInner(t: thread_id_t, self: RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + Allocator(t, self.alloc, alloc_id) &*& + capacity == logical_capacity(self.cap, elemLayout.size()) &*& + ptr == self.ptr.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + if capacity * elemLayout.size() == 0 { + true + } else { + alloc_block_in(alloc_id, ptr, allocLayout) + }; + +pred_ctor RawVecInner_full_borrow_content_(t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize)() = + *l |-> ?self_ &*& RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + +pred RawVecInner_full_borrow(k: lifetime_t, t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + full_borrow(k, RawVecInner_full_borrow_content_(t, l, elemLayout, alloc_id, ptr, capacity)); + +lem RawVecInner_send_(t1: thread_id_t) + req type_interp::() &*& is_Send(typeid(A)) == true &*& RawVecInner::(?t0, ?self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& RawVecInner::(t1, self_, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner(t0, self_, elemLayout, alloc_id, ptr, capacity); + std::alloc::Allocator_send(t1, self_.alloc); + close RawVecInner(t1, self_, elemLayout, alloc_id, ptr, capacity); +} + +pred RawVecInner0(self: RawVecInner, elemLayout: Layout, ptr: *u8, capacity: usize) = + capacity == logical_capacity(self.cap, elemLayout.size()) &*& + ptr == self.ptr.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + +pred >.own(t, self_) = + .own(t, self_.alloc) &*& + RawVecInner0(self_, ?elemLayout, ?ptr, ?capacity); + +lem RawVecInner_drop() + req RawVecInner_own::(?_t, ?_v); + ens std::num::niche_types::UsizeNoHighBit_own(_t, _v.cap) &*& .own(_t, _v.alloc); +{ + open RawVecInner_own::(_t, _v); + open RawVecInner0(_, _, _, _); + std::num::niche_types::close_UsizeNoHighBit_own(_t, _v.cap); +} + +lem RawVecInner_own_mono() + req type_interp::() &*& type_interp::() &*& RawVecInner_own::(?t, ?v) &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& RawVecInner_own::(t, RawVecInner:: { ptr: upcast(v.ptr), cap: upcast(v.cap), alloc: upcast(v.alloc) }); +{ + assume(false); // https://github.com/verifast/verifast/issues/610 +} + +lem RawVecInner_send(t1: thread_id_t) + req type_interp::() &*& is_Send(typeid(A)) == true &*& RawVecInner_own::(?t0, ?v); + ens type_interp::() &*& RawVecInner_own::(t1, v); +{ + open RawVecInner_own::(t0, v); + Send::send::(t0, t1, v.alloc); + close RawVecInner_own::(t1, v); +} + +lem_auto RawVecInner_inv() + req RawVecInner::(?t, ?self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens RawVecInner::(t, self_, elemLayout, alloc_id, ptr, capacity) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + ptr != 0 &*& ptr as usize % elemLayout.align() == 0 &*& + elemLayout.repeat(capacity) != none &*& + 0 <= capacity &*& capacity <= usize::MAX; +{ + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + std::num::niche_types::UsizeNoHighBit_inv(self_.cap); + std::alloc::Allocator_inv(); + std::alloc::Layout_inv(elemLayout); + close RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); +} + +lem RawVecInner_inv2() + req RawVecInner::(?t, ?self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens RawVecInner::(t, self_, elemLayout, alloc_id, ptr, capacity) &*& + pointer_within_limits(ptr) == true &*& ptr as usize % elemLayout.align() == 0 &*& + 0 <= capacity &*& capacity <= usize::MAX &*& + if elemLayout.size() == 0 { capacity == usize::MAX } else { capacity <= isize::MAX }; +{ + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + std::num::niche_types::UsizeNoHighBit_inv(self_.cap); + close RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); +} + +pred_ctor RawVecInner_frac_borrow_content(l: *RawVecInner, elemLayout: Layout, ptr: *u8, capacity: usize)(;) = + struct_RawVecInner_padding(l) &*& + (*l).ptr |-> ?u &*& + (*l).cap |-> ?cap &*& + capacity == logical_capacity(cap, elemLayout.size()) &*& + ptr == u.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + +pred RawVecInner_share_(k: lifetime_t, t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + pointer_within_limits(&(*l).alloc) == true &*& + [_]std::alloc::Allocator_share(k, t, &(*l).alloc, alloc_id) &*& + elemLayout.repeat(capacity) != none &*& capacity <= usize::MAX &*& + [_]frac_borrow(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)) &*& ptr != 0; + +lem RawVecInner_share__inv() + req [_]RawVecInner_share_::(?k, ?t, ?l, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens ptr != 0 &*& elemLayout.repeat(capacity) != none &*& capacity <= usize::MAX; +{ + open RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem RawVecInner_share__mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *RawVecInner) + req type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]RawVecInner_share_::(k, t, l, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& [_]RawVecInner_share_::(k1, t, l, elemLayout, alloc_id, ptr, capacity); +{ + open [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + std::alloc::Allocator_share_mono::(k, k1, t, &(*l).alloc); + frac_borrow_mono(k, k1, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + close RawVecInner_share_::(k1, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_::(k1, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem RawVecInner_sync_(t1: thread_id_t) + req type_interp::() &*& is_Sync(typeid(A)) == true &*& [_]RawVecInner_share_::(?k, ?t0, ?l, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& [_]RawVecInner_share_::(k, t1, l, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner_share_(k, t0, l, elemLayout, alloc_id, ptr, capacity); + std::alloc::Allocator_sync::(t1); + close RawVecInner_share_(k, t1, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t1, l, elemLayout, alloc_id, ptr, capacity); +} + +pred RawVecInner_share_end_token(k: lifetime_t, t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + borrow_end_token(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)) &*& + borrow_end_token(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)) &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + if capacity * elemLayout.size() == 0 { + true + } else { + alloc_block_in(alloc_id, ptr, allocLayout) + }; + +pred RawVecInner_share0_end_token(k: lifetime_t, t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + borrow_end_token(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)) &*& + borrow_end_token(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)) &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + +lem RawVecInner_share_full_(k: lifetime_t, l: *RawVecInner) + req type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& + RawVecInner_full_borrow(k, ?t, l, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& + [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner_full_borrow(k, t, l, elemLayout, alloc_id, ptr, capacity); + let klong = open_full_borrow_strong_m(k, RawVecInner_full_borrow_content_(t, l, elemLayout, alloc_id, ptr, capacity), q); + open RawVecInner_full_borrow_content_::(t, l, elemLayout, alloc_id, ptr, capacity)(); + assert *l |-> ?self_; + open_points_to(l); + points_to_limits(&(*l).alloc); + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity))(); + { + pred Ctx() = + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + if capacity * elemLayout.size() == 0 { + true + } else { + alloc_block_in(alloc_id, ptr, allocLayout) + }; + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)), + klong, + RawVecInner_full_borrow_content_(t, l, elemLayout, alloc_id, ptr, capacity) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + let self1 = *l; + close RawVecInner(t, self1, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_full_borrow_content_::(t, l, elemLayout, alloc_id, ptr, capacity)(); + } { + close_full_borrow_strong_m( + klong, + RawVecInner_full_borrow_content_(t, l, elemLayout, alloc_id, ptr, capacity), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)) + ); + full_borrow_mono(klong, k, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity))); + } + } + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)); + full_borrow_into_frac_m(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem share_RawVecInner(k: lifetime_t, l: *RawVecInner) + nonghost_callers_only + req [?q]lifetime_token(k) &*& + *l |-> ?self_ &*& + RawVecInner(?t, self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens [q]lifetime_token(k) &*& + [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity) &*& + RawVecInner_share_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + borrow(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + full_borrow_into_frac(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + points_to_limits(&(*l).alloc); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + borrow(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_share_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem end_share_RawVecInner(l: *RawVecInner) + nonghost_callers_only + req RawVecInner_share_end_token(?k, ?t, l, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& [_]lifetime_dead_token(k); + ens *l |-> ?self_ &*& RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner_share_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); + borrow_end(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::open_Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id); + borrow_end(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close RawVecInner(t, *l, elemLayout, alloc_id, ptr, capacity); +} + +lem share_RawVecInner0(k: lifetime_t, l: *RawVecInner, elemLayout: Layout, ptr: *u8, capacity: usize) + nonghost_callers_only + req [?q]lifetime_token(k) &*& + *l |-> ?self_ &*& + Allocator(?t, self_.alloc, ?alloc_id) &*& + capacity == logical_capacity(self_.cap, elemLayout.size()) &*& + ptr == self_.ptr.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + ens [q]lifetime_token(k) &*& + [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity) &*& + RawVecInner_share0_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); +{ + close RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + borrow(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + full_borrow_into_frac(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + points_to_limits(&(*l).alloc); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + borrow(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + std::num::niche_types::UsizeNoHighBit_inv(self_.cap); + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_share0_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem end_share_RawVecInner0(l: *RawVecInner) + nonghost_callers_only + req RawVecInner_share0_end_token(?k, ?t, l, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& [_]lifetime_dead_token(k); + ens *l |-> ?self_ &*& + Allocator(t, self_.alloc, alloc_id) &*& + capacity == logical_capacity(self_.cap, elemLayout.size()) &*& + ptr == self_.ptr.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); +{ + open RawVecInner_share0_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); + borrow_end(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::open_Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id); + borrow_end(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); +} + +lem init_ref_RawVecInner_(l: *RawVecInner) + nonghost_callers_only + req ref_init_perm(l, ?l0) &*& + [_]RawVecInner_share_(?k, ?t, l0, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& + [?q]lifetime_token(k); + ens [q]lifetime_token(k) &*& + [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity) &*& + [_]frac_borrow(k, ref_initialized_(l)); +{ + open_ref_init_perm_RawVecInner(l); + open RawVecInner_share_(k, t, l0, elemLayout, alloc_id, ptr, capacity); + std::alloc::init_ref_Allocator_share(k, t, &(*l).alloc); + frac_borrow_sep(k, RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)); + open_frac_borrow_strong_( + k, + sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)), + q); + open [?f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + open [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + open [f]ref_initialized_::(&(*l).alloc)(); + let ptr_ = (*l0).ptr; + let cap_ = (*l0).cap; + init_ref_readonly(&(*l).ptr, 1/2); + init_ref_readonly(&(*l).cap, 1/2); + init_ref_padding_RawVecInner(l, 1/2); + { + pred P() = ref_padding_initialized(l); + close [1 - f]P(); + close_ref_initialized_RawVecInner(l); + open P(); + } + close [f/2]RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + close [f]ref_initialized_::>(l)(); + close scaledp(f, ref_initialized_(l))(); + close sep_(scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l)))(); + + { + pred Ctx() = + ref_padding_end_token(l, l0, f/2) &*& [f/2]struct_RawVecInner_padding(l0) &*& [1 - f]ref_padding_initialized(l) &*& + ref_readonly_end_token(&(*l).ptr, &(*l0).ptr, f/2) &*& [f/2](*l0).ptr |-> ptr_ &*& [1 - f]ref_initialized(&(*l).ptr) &*& + ref_readonly_end_token(&(*l).cap, &(*l0).cap, f/2) &*& [f/2](*l0).cap |-> cap_ &*& [1 - f]ref_initialized(&(*l).cap); + close Ctx(); + produce_lem_ptr_chunk restore_frac_borrow( + Ctx, + sep_(scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l))), + f, + sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)))() { + open sep_(scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l)))(); + open scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + open scaledp(f, ref_initialized_(l))(); + open ref_initialized_::>(l)(); + open Ctx(); + open_ref_initialized_RawVecInner(l); + end_ref_readonly(&(*l).ptr); + end_ref_readonly(&(*l).cap); + end_ref_padding_RawVecInner(l); + close [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + close [f]ref_initialized_::(&(*l).alloc)(); + close [f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + } { + close_frac_borrow_strong_(); + } + } + full_borrow_into_frac(k, sep_(scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l)))); + frac_borrow_split(k, scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l))); + frac_borrow_implies_scaled(k, f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + assert pointer_within_limits(ref_origin(&(*l0).alloc)) == true; + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem init_ref_RawVecInner_m(l: *RawVecInner) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(l, ?l0) &*& [_]RawVecInner_share_(?k, ?t, l0, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open_ref_init_perm_RawVecInner(l); + open RawVecInner_share_(k, t, l0, elemLayout, alloc_id, ptr, capacity); + std::alloc::init_ref_Allocator_share_m(k, t, &(*l).alloc); + frac_borrow_sep(k, RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)); + let klong = open_frac_borrow_strong_m(k, sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)), q); + open [?f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + open [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + let ptr_ = (*l0).ptr; + let cap_ = (*l0).cap; + open [f]ref_initialized_::(&(*l).alloc)(); + std::ptr::init_ref_NonNull(&(*l).ptr, 1/2); + std::num::niche_types::init_ref_UsizeNoHighBit(&(*l).cap, 1/2); + init_ref_padding_RawVecInner(l, 1/2); + { + pred P() = ref_padding_initialized(l); + close [1 - f/2]P(); + close_ref_initialized_RawVecInner(l); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*l).alloc) &*& + ref_padding_end_token(l, l0, f/2) &*& [f/2]struct_RawVecInner_padding(l0) &*& [1 - f/2]ref_padding_initialized(l) &*& + ref_end_token(&(*l).ptr, &(*l0).ptr, f/2) &*& [f/2](*l0).ptr |-> ptr_ &*& [1 - f/2]ref_initialized(&(*l).ptr) &*& + std::num::niche_types::end_ref_UsizeNoHighBit_token(&(*l).cap, &(*l0).cap, f/2) &*& [f/2](*l0).cap |-> cap_ &*& [1 - f/2]ref_initialized(&(*l).cap); + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))), klong, f, sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)))() { + open scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))(); + open sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + open ref_initialized_::>(l)(); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + open_ref_initialized_RawVecInner(l); + open Ctx(); + std::ptr::end_ref_NonNull(&(*l).ptr); + std::num::niche_types::end_ref_UsizeNoHighBit(&(*l).cap); + end_ref_padding_RawVecInner(l); + close [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + close [f]ref_initialized_::(&(*l).alloc)(); + close [f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(l)(); + close [f/2]RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close [f/2]sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + close scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))); + } + } + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))); + frac_borrow_split(k, ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + assert pointer_within_limits(ref_origin(&(*l0).alloc)) == true; + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +pred >.share(k, t, l) = [_]RawVecInner_share_(k, t, l, _, _, _, _); + +lem RawVecInner_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *RawVecInner) + req type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]RawVecInner_share::(k, t, l); + ens type_interp::() &*& [_]RawVecInner_share::(k1, t, l); +{ + open RawVecInner_share::(k, t, l); + RawVecInner_share__mono(k, k1, t, l); + close RawVecInner_share::(k1, t, l); + leak RawVecInner_share::(k1, t, l); +} + +lem RawVecInner_share_full(k: lifetime_t, t: thread_id_t, l: *RawVecInner) + req type_interp::() &*& atomic_mask(MaskTop) &*& full_borrow(k, RawVecInner_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k) &*& ref_origin(l) == l; + ens type_interp::() &*& atomic_mask(MaskTop) &*& [_]RawVecInner_share::(k, t, l) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong_m(k, RawVecInner_full_borrow_content(t, l), q); + open RawVecInner_full_borrow_content::(t, l)(); + open >.own(t, *l); + std::alloc::open_Allocator_own((*l).alloc); + assert Allocator(_, _, ?alloc_id); + open RawVecInner0(?self_, ?elemLayout, ?ptr, ?capacity); + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), klong, RawVecInner_full_borrow_content(t, l))() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + std::alloc::open_Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + std::alloc::Allocator_to_own((*l).alloc); + close RawVecInner0(*l, elemLayout, ptr, capacity); + close >.own(t, *l); + close RawVecInner_full_borrow_content::(t, l)(); + } { + close Ctx(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + close_full_borrow_strong_m(klong, RawVecInner_full_borrow_content(t, l), sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))); + full_borrow_mono(klong, k, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))); + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + } + } + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + std::num::niche_types::UsizeNoHighBit_inv(self_.cap); + close RawVecInner_share_::(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_::(k, t, l, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_share::(k, t, l); + leak RawVecInner_share::(k, t, l); +} + +lem init_ref_RawVecInner(l: *RawVecInner) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(l, ?l0) &*& [_]RawVecInner_share::(?k, ?t, l0) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]RawVecInner_share::(k, t, l) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open RawVecInner_share::(k, t, l0); + open_ref_init_perm_RawVecInner(l); + open RawVecInner_share_(k, t, l0, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + std::alloc::init_ref_Allocator_share_m(k, t, &(*l).alloc); + frac_borrow_sep(k, RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)); + let klong = open_frac_borrow_strong_m(k, sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)), q); + open [?f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + open [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + let ptr_ = (*l0).ptr; + let cap_ = (*l0).cap; + open [f]ref_initialized_::(&(*l).alloc)(); + std::ptr::init_ref_NonNull(&(*l).ptr, 1/2); + std::num::niche_types::init_ref_UsizeNoHighBit(&(*l).cap, 1/2); + init_ref_padding_RawVecInner(l, 1/2); + { + pred P() = ref_padding_initialized(l); + close [1 - f/2]P(); + close_ref_initialized_RawVecInner(l); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*l).alloc) &*& + ref_padding_end_token(l, l0, f/2) &*& [f/2]struct_RawVecInner_padding(l0) &*& [1 - f/2]ref_padding_initialized(l) &*& + ref_end_token(&(*l).ptr, &(*l0).ptr, f/2) &*& [f/2](*l0).ptr |-> ptr_ &*& [1 - f/2]ref_initialized(&(*l).ptr) &*& + std::num::niche_types::end_ref_UsizeNoHighBit_token(&(*l).cap, &(*l0).cap, f/2) &*& [f/2](*l0).cap |-> cap_ &*& [1 - f/2]ref_initialized(&(*l).cap); + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))), klong, f, sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)))() { + open scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))(); + open sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + open ref_initialized_::>(l)(); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + open_ref_initialized_RawVecInner(l); + open Ctx(); + std::ptr::end_ref_NonNull(&(*l).ptr); + std::num::niche_types::end_ref_UsizeNoHighBit(&(*l).cap); + end_ref_padding_RawVecInner(l); + close [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + close [f]ref_initialized_::(&(*l).alloc)(); + close [f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(l)(); + close [f/2]RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close [f/2]sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + close scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))); + } + } + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))); + frac_borrow_split(k, ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + assert pointer_within_limits(ref_origin(&(*l0).alloc)) == true; + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_share::(k, t, l); + leak RawVecInner_share(k, t, l); +} + +lem RawVecInner_sync(t1: thread_id_t) + req type_interp::() &*& is_Sync(typeid(A)) == true &*& [_]RawVecInner_share::(?k, ?t0, ?l); + ens type_interp::() &*& [_]RawVecInner_share::(k, t1, l); +{ + open RawVecInner_share::(k, t0, l); + RawVecInner_sync_::(t1); + close RawVecInner_share::(k, t1, l); + leak RawVecInner_share(k, t1, l); +} + +fix RawVecInner::alloc(self_: RawVecInner) -> A { self_.alloc } + +lem RawVecInner_into_raw_parts(self_: RawVecInner) + req RawVecInner(?t, self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens Allocator(t, self_.alloc(), alloc_id) &*& + if capacity * elemLayout.size() == 0 { + true + } else { + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr, allocLayout) + }; +{ + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); +} + +@*/ + +/*@ + +pred RawVec(t: thread_id_t, self: RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) = + RawVecInner(t, self.inner, Layout::new::, alloc_id, ?ptr_, capacity) &*& ptr == ptr_ as *T; + +fix RawVec_full_borrow_content_(t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) -> pred() { + RawVecInner_full_borrow_content_(t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity) +} + +lem close_RawVec_full_borrow_content_(t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) + req *l |-> ?self_ &*& RawVec(t, self_, alloc_id, ptr, capacity); + ens RawVec_full_borrow_content_::(t, l, alloc_id, ptr, capacity)(); +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + open_points_to(l); + close RawVecInner_full_borrow_content_::(t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity)(); +} + +lem open_RawVec_full_borrow_content_(t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) + req RawVec_full_borrow_content_::(t, l, alloc_id, ptr, capacity)(); + ens *l |-> ?self_ &*& RawVec(t, self_, alloc_id, ptr, capacity); +{ + open RawVecInner_full_borrow_content_::(t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity)(); + close RawVec(t, *l, alloc_id, ptr, capacity); + close_points_to(l); +} + +pred RawVec_full_borrow(k: lifetime_t, t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) = + RawVecInner_full_borrow(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + +lem close_RawVec_full_borrow(k: lifetime_t, t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) + req full_borrow(k, RawVec_full_borrow_content_::(t, l, alloc_id, ptr, capacity)); + ens RawVec_full_borrow(k, t, l, alloc_id, ptr, capacity); +{ + close RawVecInner_full_borrow(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + close RawVec_full_borrow(k, t, l, alloc_id, ptr, capacity); +} + +pred >.own(t, self_) = RawVec(t, self_, ?alloc_id, ?ptr, ?capacity) &*& array_at_lft_(alloc_id.lft, ptr, capacity, _); + +lem RawVec_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& RawVec_own::(?t, ?v) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& RawVec_own::(t, RawVec:: { inner: upcast(v.inner) }); +{ + assume(false); // https://github.com/verifast/verifast/issues/610 +} + +lem RawVec_send_(t1: thread_id_t) + req type_interp::() &*& is_Send(typeid(A)) == true &*& RawVec::(?t0, ?v, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& RawVec::(t1, v, alloc_id, ptr, capacity); +{ + open RawVec(t0, v, alloc_id, ptr, capacity); + RawVecInner_send_::(t1); + close RawVec(t1, v, alloc_id, ptr, capacity); +} + +lem RawVec_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& is_Send(typeid(RawVec)) == true &*& RawVec_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& RawVec_own::(t1, v); +{ + open >.own(t0, v); + RawVec_send_(t1); + close >.own(t1, v); +} + +lem RawVec_inv() + req RawVec::(?t, ?self_, ?alloc_id, ?ptr, ?capacity); + ens RawVec::(t, self_, alloc_id, ptr, capacity) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + ptr != 0 &*& ptr as usize % std::mem::align_of::() == 0 &*& + 0 <= capacity &*& capacity <= usize::MAX; +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + RawVecInner_inv(); + close RawVec(t, self_, alloc_id, ptr, capacity); +} + +lem RawVec_inv2() + req RawVec::(?t, ?self_, ?alloc_id, ?ptr, ?capacity); + ens RawVec::(t, self_, alloc_id, ptr, capacity) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + ptr != 0 &*& ptr as usize % std::mem::align_of::() == 0 &*& + 0 <= capacity &*& + Layout::new::().repeat(capacity) != none &*& + if std::mem::size_of::() == 0 { capacity == usize::MAX } else { capacity <= isize::MAX }; +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + RawVecInner_inv2(); + close RawVec(t, self_, alloc_id, ptr, capacity); +} + +lem RawVec_to_own(self_: RawVec) + req RawVec(?t, self_, ?alloc_id, ?ptr, ?capacity) &*& array_at_lft_(alloc_id.lft, ptr, capacity, _); + ens >.own(t, self_); +{ + close >.own(t, self_); +} + +lem open_RawVec_own(self_: RawVec) + req >.own(?t, self_); + ens RawVec(t, self_, ?alloc_id, ?ptr, ?capacity) &*& array_at_lft_(alloc_id.lft, ptr, capacity, _); +{ + open >.own(t, self_); +} + +pred RawVec_share_(k: lifetime_t, t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) = + [_]RawVecInner_share_(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + +lem RawVec_share__inv() + req [_]RawVec_share_::(?k, ?t, ?l, ?alloc_id, ?ptr, ?capacity); + ens ptr != 0 &*& Layout::new::().repeat(capacity) != none &*& capacity <= usize::MAX; +{ + open RawVec_share_(k, t, l, alloc_id, ptr, capacity); + RawVecInner_share__inv(); +} + +lem RawVec_share__mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *RawVec) + req type_interp::() &*& type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]RawVec_share_::(k, t, l, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& type_interp::() &*& [_]RawVec_share_::(k1, t, l, alloc_id, ptr, capacity); +{ + open RawVec_share_(k, t, l, alloc_id, ptr, capacity); + RawVecInner_share__mono(k, k1, t, &(*l).inner); + close RawVec_share_(k1, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k1, t, l, alloc_id, ptr, capacity); +} + +lem RawVec_sync_(t1: thread_id_t) + req type_interp::() &*& [_]RawVec_share_::(?k, ?t0, ?l, ?alloc_id, ?ptr, ?capacity) &*& is_Sync(typeid(RawVec)) == true; + ens type_interp::() &*& [_]RawVec_share_::(k, t1, l, alloc_id, ptr, capacity); +{ + open RawVec_share_::(k, t0, l, alloc_id, ptr, capacity); + RawVecInner_sync_::(t1); + close RawVec_share_::(k, t1, l, alloc_id, ptr, capacity); + leak RawVec_share_::(k, t1, l, alloc_id, ptr, capacity); +} + +pred RawVec_share_end_token(k: lifetime_t, t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) = + RawVecInner_share_end_token(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + +lem RawVec_share_full_(k: lifetime_t, l: *RawVec) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& + RawVec_full_borrow(k, ?t, l, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& + [_]RawVec_share_(k, t, l, alloc_id, ptr, capacity); +{ + open RawVec_full_borrow(k, t, l, alloc_id, ptr, capacity); + RawVecInner_share_full_(k, &(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); +} + +lem share_RawVec(k: lifetime_t, l: *RawVec) + nonghost_callers_only + req [?q]lifetime_token(k) &*& *l |-> ?self_ &*& RawVec(?t, self_, ?alloc_id, ?ptr, ?capacity); + ens [q]lifetime_token(k) &*& [_]RawVec_share_(k, t, l, alloc_id, ptr, capacity) &*& RawVec_share_end_token(k, t, l, alloc_id, ptr, capacity); +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + open_points_to(l); + share_RawVecInner(k, &(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); + close RawVec_share_end_token(k, t, l, alloc_id, ptr, capacity); +} + +lem end_share_RawVec(l: *RawVec) + nonghost_callers_only + req RawVec_share_end_token(?k, ?t, l, ?alloc_id, ?ptr, ?capacity) &*& [_]lifetime_dead_token(k); + ens *l |-> ?self_ &*& RawVec(t, self_, alloc_id, ptr, capacity); +{ + open RawVec_share_end_token(k, t, l, alloc_id, ptr, capacity); + end_share_RawVecInner(&(*l).inner); + close_points_to(l); + close RawVec(t, *l, alloc_id, ptr, capacity); +} + +lem init_ref_RawVec_(l: *RawVec) + nonghost_callers_only + req ref_init_perm(l, ?l0) &*& [_]RawVec_share_(?k, ?t, l0, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + ens [q]lifetime_token(k) &*& [_]RawVec_share_(k, t, l, alloc_id, ptr, capacity) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open RawVec_share_(k, t, l0, alloc_id, ptr, capacity); + open_ref_init_perm_RawVec(l); + init_ref_RawVecInner_(&(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); + + let klong = open_frac_borrow_strong(k, ref_initialized_(&(*l).inner), q); + open [?f]ref_initialized_::>(&(*l).inner)(); + close_ref_initialized_RawVec(l, f); + close [f]ref_initialized_::>(l)(); + { + pred Ctx() = true; + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f, ref_initialized_(l)), klong, f, ref_initialized_(&(*l).inner))() { + open Ctx(); + open scaledp(f, ref_initialized_(l))(); + open ref_initialized_::>(l)(); + open_ref_initialized_RawVec(l); + close [f]ref_initialized_::>(&(*l).inner)(); + } { + close Ctx(); + close scaledp(f, ref_initialized_(l))(); + close_frac_borrow_strong(klong, ref_initialized_(&(*l).inner), scaledp(f, ref_initialized_(l))); + full_borrow_mono(klong, k, scaledp(f, ref_initialized_(l))); + full_borrow_into_frac(k, scaledp(f, ref_initialized_(l))); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + } + } +} + +lem init_ref_RawVec_m(l: *RawVec) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(l, ?l0) &*& [_]RawVec_share_(?k, ?t, l0, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]RawVec_share_(k, t, l, alloc_id, ptr, capacity) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open RawVec_share_(k, t, l0, alloc_id, ptr, capacity); + open_ref_init_perm_RawVec(l); + init_ref_RawVecInner_m(&(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); + + let klong = open_frac_borrow_strong_m(k, ref_initialized_(&(*l).inner), q); + open [?f]ref_initialized_::>(&(*l).inner)(); + close_ref_initialized_RawVec(l, f); + close [f]ref_initialized_::>(l)(); + { + pred Ctx() = true; + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f, ref_initialized_(l)), klong, f, ref_initialized_(&(*l).inner))() { + open Ctx(); + open scaledp(f, ref_initialized_(l))(); + open ref_initialized_::>(l)(); + open_ref_initialized_RawVec(l); + close [f]ref_initialized_::>(&(*l).inner)(); + } { + close Ctx(); + close scaledp(f, ref_initialized_(l))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f, ref_initialized_(l))); + full_borrow_into_frac_m(k, scaledp(f, ref_initialized_(l))); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + } + } +} + +pred >.share(k, t, l) = [_]RawVec_share_(k, t, l, ?alloc_id, ?ptr, ?capacity); + +lem RawVec_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *RawVec) + req type_interp::() &*& type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]RawVec_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]RawVec_share::(k1, t, l); +{ + open RawVec_share::(k, t, l); + RawVec_share__mono(k, k1, t, l); + close RawVec_share::(k1, t, l); + leak RawVec_share::(k1, t, l); +} + +lem RawVec_share_full(k: lifetime_t, t: thread_id_t, l: *RawVec) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& full_borrow(k, RawVec_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k) &*& ref_origin(l) == l; + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [_]RawVec_share::(k, t, l) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong_m(k, RawVec_full_borrow_content::(t, l), q); + open RawVec_full_borrow_content::(t, l)(); + let self_ = *l; + points_to_limits(&(*l).inner.alloc); + open >.own(t, self_); + open RawVec(t, self_, ?alloc_id, ?ptr, ?capacity); + open RawVecInner(t, self_.inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + { + pred Ctx() = + if capacity * std::mem::size_of::() == 0 { + true + } else { + Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr as *u8, allocLayout) + } &*& + array_at_lft_(alloc_id.lft, ptr, capacity, _); + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity)), klong, RawVec_full_borrow_content(t, l))() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity))(); + std::alloc::open_Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id); + open RawVecInner_frac_borrow_content::(&(*l).inner, Layout::new::(), ptr as *u8, capacity)(); + close RawVecInner(t, (*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + close RawVec(t, *l, alloc_id, ptr, capacity); + close >.own(t, *l); + close RawVec_full_borrow_content::(t, l)(); + } { + close Ctx(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).inner.alloc); + close RawVecInner_frac_borrow_content::(&(*l).inner, Layout::new::(), ptr as *u8, capacity)(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity))(); + close_full_borrow_strong_m(klong, RawVec_full_borrow_content(t, l), sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity))); + full_borrow_mono(klong, k, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity))); + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity)); + } + } + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).inner.alloc, alloc_id); + full_borrow_into_frac_m(k, RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity)); + close RawVecInner_share_::(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + leak RawVecInner_share_::(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + close RawVec_share_::(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_::(k, t, l, alloc_id, ptr, capacity); + close RawVec_share::(k, t, l); + leak RawVec_share::(k, t, l); +} + +lem RawVec_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& is_Sync(typeid(RawVec)) == true &*& [_]RawVec_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& [_]RawVec_share::(k, t1, l); +{ + open RawVec_share::(k, t0, l); + RawVec_sync_::(t1); + close RawVec_share::(k, t1, l); + leak RawVec_share::(k, t1, l); +} + +lem init_ref_RawVec(l: *RawVec) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(l, ?l0) &*& [_]RawVec_share::(?k, ?t, l0) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]RawVec_share::(k, t, l) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open RawVec_share::(k, t, l0); + open RawVec_share_(k, t, l0, ?alloc_id, ?ptr, ?capacity); + open_ref_init_perm_RawVec(l); + init_ref_RawVecInner_m(&(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); + close RawVec_share::(k, t, l); + leak RawVec_share::(k, t, l); + + let klong = open_frac_borrow_strong_m(k, ref_initialized_(&(*l).inner), q); + open [?f]ref_initialized_::>(&(*l).inner)(); + close_ref_initialized_RawVec(l, f); + close [f]ref_initialized_::>(l)(); + { + pred Ctx() = true; + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f, ref_initialized_(l)), klong, f, ref_initialized_(&(*l).inner))() { + open Ctx(); + open scaledp(f, ref_initialized_(l))(); + open ref_initialized_::>(l)(); + open_ref_initialized_RawVec(l); + close [f]ref_initialized_::>(&(*l).inner)(); + } { + close Ctx(); + close scaledp(f, ref_initialized_(l))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f, ref_initialized_(l))); + full_borrow_into_frac_m(k, scaledp(f, ref_initialized_(l))); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + } + } +} + +fix RawVec::alloc(self_: RawVec) -> A { self_.inner.alloc() } + +lem RawVec_into_raw_parts(self_: RawVec) + req RawVec(?t, self_, ?alloc_id, ?ptr, ?capacity); + ens Allocator(t, self_.alloc(), alloc_id) &*& + if capacity * std::mem::size_of::() == 0 { + true + } else { + Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr as *u8, allocLayout) + }; +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + RawVecInner_into_raw_parts(self_.inner); +} + +@*/ + +impl RawVec { + /// Creates the biggest possible `RawVec` (on the system heap) + /// without allocating. If `T` has positive size, then this makes a + /// `RawVec` with capacity `0`. If `T` is zero-sized, then it makes a + /// `RawVec` with capacity `usize::MAX`. Useful for implementing + /// delayed allocation. + #[must_use] + pub(crate) const fn new() -> Self { + Self::new_in(Global) + } + + /// Creates a `RawVec` (on the system heap) with exactly the + /// capacity and alignment requirements for a `[T; capacity]`. This is + /// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is + /// zero-sized. Note that if `T` is zero-sized this means you will + /// *not* get a `RawVec` with the requested capacity. + /// + /// Non-fallible version of `try_with_capacity` + /// + /// # Panics + /// + /// Panics if the requested capacity exceeds `isize::MAX` bytes. + /// + /// # Aborts + /// + /// Aborts on OOM. + #[cfg(not(any(no_global_oom_handling, test)))] + #[must_use] + #[inline] + pub(crate) fn with_capacity(capacity: usize) -> Self { + Self { inner: RawVecInner::with_capacity(capacity, T::LAYOUT), _marker: PhantomData } + } + + /// Like `with_capacity`, but guarantees the buffer is zeroed. + #[cfg(not(any(no_global_oom_handling, test)))] + #[must_use] + #[inline] + pub(crate) fn with_capacity_zeroed(capacity: usize) -> Self { + Self { + inner: RawVecInner::with_capacity_zeroed_in(capacity, Global, T::LAYOUT), + _marker: PhantomData, + } + } +} + +impl RawVecInner { + #[cfg(not(any(no_global_oom_handling, test)))] + #[must_use] + #[inline] + fn with_capacity(capacity: usize, elem_layout: Layout) -> Self { + match Self::try_allocate_in(capacity, AllocInit::Uninitialized, Global, elem_layout) { + Ok(res) => res, + Err(err) => handle_error(err), + } + } +} + +// Tiny Vecs are dumb. Skip to: +// - 8 if the element size is 1, because any heap allocator is likely +// to round up a request of less than 8 bytes to at least 8 bytes. +// - 4 if elements are moderate-sized (<= 1 KiB). +// - 1 otherwise, to avoid wasting too much space for very short Vecs. +const fn min_non_zero_cap(size: usize) -> usize +//@ req true; +//@ ens true; +//@ on_unwind_ens false; +{ + if size == 1 { + 8 + } else if size <= 1024 { + 4 + } else { + 1 + } +} + +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +#[rustfmt::skip] // FIXME(fee1-dead): temporary measure before rustfmt is bumped +const impl RawVec { + /// Like `with_capacity`, but parameterized over the choice of + /// allocator for the returned `RawVec`. + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn with_capacity_in(capacity: usize, alloc: A) -> Self + //@ req thread_token(?t) &*& Allocator(t, alloc, ?alloc_id) &*& t == currentThread; + /*@ + ens thread_token(t) &*& + RawVec(t, result, alloc_id, ?ptr, ?capacity_) &*& + array_at_lft_(alloc_id.lft, ptr, capacity_, _) &*& + capacity <= capacity_; + @*/ + /*@ + safety_proof { + std::alloc::open_Allocator_own(alloc); + let result = call(); + close >.own(_t, result); + } + @*/ + { + //@ size_align::(); + let r = Self { + inner: RawVecInner::with_capacity_in(capacity, alloc, T::LAYOUT), + _marker: PhantomData, + }; + //@ close RawVec(t, r, alloc_id, ?ptr, ?capacity_); + //@ u8s_at_lft__to_array_at_lft_(ptr, capacity_); + r + } + + /// A specialized version of `self.reserve(len, 1)` which requires the + /// caller to ensure `len == self.capacity()`. + #[cfg(not(no_global_oom_handling))] + #[inline(never)] + pub(crate) fn grow_one(&mut self) { + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + unsafe { self.inner.grow_one(T::LAYOUT) } + } +} + +impl RawVec { + #[cfg(not(no_global_oom_handling))] + pub(crate) const MIN_NON_ZERO_CAP: usize = min_non_zero_cap(size_of::()); + + /// Like `new`, but parameterized over the choice of allocator for + /// the returned `RawVec`. + #[inline] + pub(crate) const fn new_in(alloc: A) -> Self + //@ req thread_token(?t) &*& Allocator(t, alloc, ?alloc_id); + //@ ens thread_token(t) &*& RawVec::(t, result, alloc_id, ?ptr, ?capacity) &*& array_at_lft_(alloc_id.lft, ptr, capacity, _); + /*@ + safety_proof { + std::alloc::open_Allocator_own(alloc); + let result = call(); + close >.own(_t, result); + } + @*/ + { + // Check assumption made in `current_memory` + const { assert!(T::LAYOUT.size() % T::LAYOUT.align() == 0) }; + //@ close exists(std::mem::size_of::()); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ std::alloc::is_valid_layout_size_of_align_of::(); + //@ std::mem::Alignment_as_nonzero_usize_new(std::mem::align_of::()); + let r = Self { inner: RawVecInner::new_in(alloc, Alignment::of::()), _marker: PhantomData }; + //@ close RawVec::(t, r, alloc_id, ?ptr, ?capacity); + //@ u8s_at_lft__to_array_at_lft_(ptr, capacity); + r + } + + /// Like `try_with_capacity`, but parameterized over the choice of + /// allocator for the returned `RawVec`. + #[inline] + pub(crate) fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { + match RawVecInner::try_with_capacity_in(capacity, alloc, T::LAYOUT) { + Ok(inner) => Ok(Self { inner, _marker: PhantomData }), + Err(e) => Err(e), + } + } + + /// Like `with_capacity_zeroed`, but parameterized over the choice + /// of allocator for the returned `RawVec`. + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self { + Self { + inner: RawVecInner::with_capacity_zeroed_in(capacity, alloc, T::LAYOUT), + _marker: PhantomData, + } + } + + /// Converts the entire buffer into `Box<[MaybeUninit]>` with the specified `len`. + /// + /// Note that this will correctly reconstitute any `cap` changes + /// that may have been performed. (See description of type for details.) + /// + /// # Safety + /// + /// * `len` must be greater than or equal to the most recently requested capacity, and + /// * `len` must be less than or equal to `self.capacity()`. + /// + /// Note, that the requested capacity and `self.capacity()` could differ, as + /// an allocator could overallocate and return a greater memory block than requested. + pub(crate) unsafe fn into_box(mut self, len: usize) -> Box<[MaybeUninit], A> + //@ req thread_token(?t) &*& RawVec(t, self, ?alloc_id, ?ptr, ?capacity_) &*& array_at_lft_(alloc_id.lft, ptr as *T, len, ?vs) &*& if std::mem::size_of::() == 0 { true } else { len == capacity_ }; + //@ ens thread_token(t) &*& boxed::Box_in::<[std::mem::MaybeUninit], A>(t, result, alloc_id, slice_of_elems(map(std::mem::MaybeUninit::new_maybe_uninit, vs))); + //@ on_unwind_ens thread_token(t); + { + //@ RawVec_inv2(); + + // Sanity-check one half of the safety requirement (we cannot check the other half). + if cfg!(debug_assertions) { //~allow_dead_code + //@ let k = begin_lifetime(); + //@ share_RawVec(k, &self); + //@ let self_ref = precreate_ref(&self); + //@ init_ref_RawVec_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let capacity = self.capacity(); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVec(&self); + //@ open_points_to(&self); + + if !(len <= capacity) { + unsafe { core::hint::unreachable_unchecked(); } + } + } + + let mut me = ManuallyDrop::new(self); + //@ close_points_to(&self); + unsafe { + //@ let k0 = begin_lifetime(); + //@ close_points_to(&me); + //@ share_RawVec(k0, &me); + //@ let me_ref0 = precreate_ref(&me); + //@ init_ref_RawVec_(me_ref0); + //@ open_frac_borrow(k0, ref_initialized_(me_ref0), 1/2); + //@ open [?f0]ref_initialized_::>(me_ref0)(); + let me_ref = > as core::ops::Deref>::deref(&me); + let ptr_ = me_ref.ptr(); + let slice = ptr_.cast::>().cast_slice(len); + //@ close [f0]ref_initialized_::>(me_ref0)(); + //@ close_frac_borrow(f0, ref_initialized_(me_ref0)); + //@ end_lifetime(k0); + //@ end_share_RawVec(&me); + + //@ let me_ref1 = precreate_ref(&me); + //@ init_ref_readonly(me_ref1, 1/2); + //@ open_points_to(me_ref1); + //@ let alloc_ref = precreate_ref(&(*me_ref1).inner.alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + let alloc = ptr::read(&me.inner.alloc); + //@ end_ref_readonly(alloc_ref); + //@ close_points_to(me_ref1, 1/2); + //@ end_ref_readonly(me_ref1); + //@ open_points_to(&me); + //@ std::mem::array_at_lft__to_array_at_lft_MaybeUninit(slice as *T); + //@ open RawVec(_, _, _, _, _); + //@ open RawVecInner(_, _, _, _, _, _); + //@ size_align::(); + //@ if len * std::mem::size_of::() != 0 { std::alloc::Layout_repeat_some_size_aligned(Layout::new::(), len); } + //@ close_points_to_slice_at_lft(slice); + Box::from_raw_in(slice, alloc) + } + } + + /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator. + /// + /// # Safety + /// + /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given + /// `capacity`. + /// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit + /// systems). For ZSTs capacity is ignored. + /// If the `ptr` and `capacity` come from a `RawVec` created via `alloc`, then this is + /// guaranteed. + #[inline] + pub(crate) const unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self + /*@ + req Allocator(?t, alloc, ?alloc_id) &*& + ptr as usize != 0 &*& + ptr as usize % std::mem::align_of::() == 0 &*& + if capacity * std::mem::size_of::() == 0 { + true + } else { + Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr as *u8, allocLayout) + }; + @*/ + //@ ens RawVec(t, result, alloc_id, ptr, ?capacity_) &*& capacity <= capacity_; + { + // SAFETY: Precondition passed to the caller + unsafe { + let ptr = ptr.cast(); + //@ std::alloc::Layout_inv(Layout::new::()); + /*@ + if 1 <= std::mem::size_of::() { + if capacity != 0 { + mul_zero(capacity, std::mem::size_of::()); + assert Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some(Layout::new::(), capacity); + div_rem_nonneg(isize::MAX, std::mem::align_of::()); + mul_mono_l(1, std::mem::size_of::(), capacity); + mul_mono_l(std::mem::size_of::(), stride, capacity); + std::alloc::Layout_inv(allocLayout); + } + } + @*/ + let capacity = new_cap::(capacity); + //@ close exists(Layout::new::()); + let r = Self { + inner: RawVecInner::from_raw_parts_in(ptr, capacity, alloc), + _marker: PhantomData, + }; + //@ close RawVec(t, r, alloc_id, ptr, _); + r + } + } + + /// A convenience method for hoisting the non-null precondition out of [`RawVec::from_raw_parts_in`]. + /// + /// # Safety + /// + /// See [`RawVec::from_raw_parts_in`]. + #[inline] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub(crate) const unsafe fn from_nonnull_in(ptr: NonNull, capacity: usize, alloc: A) -> Self + /*@ + req Allocator(?t, alloc, ?alloc_id) &*& + ptr.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(ptr.as_ptr()) == true &*& + if capacity * std::mem::size_of::() == 0 { + true + } else { + Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr.as_ptr() as *u8, allocLayout) + }; + @*/ + //@ ens RawVec(t, result, alloc_id, ptr.as_ptr(), ?capacity_) &*& capacity <= capacity_ &*& (std::mem::size_of::() == 0 || capacity_ == capacity); + { + // SAFETY: Precondition passed to the caller + unsafe { + let ptr = ptr.cast(); + //@ std::ptr::NonNull_Sized_as_ptr(ptr); + //@ std::alloc::Layout_inv(Layout::new::()); + /*@ + if 1 <= std::mem::size_of::() && capacity != 0 { + mul_zero(capacity, std::mem::size_of::()); + assert Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some(Layout::new::(), capacity); + std::alloc::Layout_inv(allocLayout); + div_rem_nonneg(isize::MAX, std::mem::align_of::()); + mul_mono_l(1, std::mem::size_of::(), capacity); + mul_mono_l(std::mem::size_of::(), stride, capacity); + } + @*/ + let capacity = new_cap::(capacity); + //@ close exists(Layout::new::()); + let r = Self { inner: RawVecInner::from_nonnull_in(ptr, capacity, alloc), _marker: PhantomData }; + //@ close RawVec(t, r, alloc_id, _, _); + r + } + } + + /// Gets a raw pointer to the start of the allocation. Note that this is + /// `NonNull::dangling()` if `capacity == 0` or `T` is zero-sized. In the former case, you must + /// be careful. + #[inline] + pub(crate) const fn ptr(&self) -> *mut T + //@ req [_]RawVec_share_(?k, ?t, self, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + //@ ens [q]lifetime_token(k) &*& result == ptr; + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open RawVec_share_(k, t, self, alloc_id, ptr, capacity); + //@ let inner_ref = precreate_ref(&(*self).inner); + //@ init_ref_RawVecInner_(inner_ref); + //@ open_frac_borrow(k, ref_initialized_(inner_ref), q/2); + //@ open [?f]ref_initialized_::>(inner_ref)(); + let r = self.inner.ptr(); + //@ close [f]ref_initialized_::>(inner_ref)(); + //@ close_frac_borrow(f, ref_initialized_(inner_ref)); + r + } + + #[inline] + pub(crate) const fn non_null(&self) -> NonNull { + self.inner.non_null() + } + + /// Gets the capacity of the allocation. + /// + /// This will always be `usize::MAX` if `T` is zero-sized. + #[inline] + pub(crate) const fn capacity(&self) -> usize + //@ req [_]RawVec_share_(?k, ?t, self, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + //@ ens [q]lifetime_token(k) &*& result == capacity; + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open RawVec_share_(k, t, self, alloc_id, ptr, capacity); + //@ let inner_ref = precreate_ref(&(*self).inner); + //@ init_ref_RawVecInner_(inner_ref); + //@ open_frac_borrow(k, ref_initialized_(inner_ref), q/2); + //@ open [?f]ref_initialized_::>(inner_ref)(); + let r = self.inner.capacity(size_of::()); + //@ close [f]ref_initialized_::>(inner_ref)(); + //@ close_frac_borrow(f, ref_initialized_(inner_ref)); + r + } + + /// Returns a shared reference to the allocator backing this `RawVec`. + #[inline] + pub(crate) const fn allocator(&self) -> &A + /*@ + req + [?q]lifetime_token(?k) &*& + exists(?readOnly) &*& + if readOnly { + [_]points_to_shared(k, self, ?self_) &*& + ens [q]lifetime_token(k) &*& + [_]points_to_shared(k, result, self_.alloc()) &*& + [_]frac_borrow(k, ref_initialized_(result)) + } else { + [_]RawVec_share_(k, ?t, self, ?alloc_id, ?ptr, ?capacity) &*& + ens [q]lifetime_token(k) &*& + [_]std::alloc::Allocator_share(k, t, result, alloc_id) &*& + [_]frac_borrow(k, ref_initialized_(result)) + }; + @*/ + //@ ens true; + /*@ + safety_proof { + open >.share(?k, _t, self); + close exists(false); + let result = call(); + std::alloc::close_Allocator_share(k, _t, result); + } + @*/ + { + //@ let inner_ref = precreate_ref(&(*self).inner); + /*@ + if readOnly { + open points_to_shared(k, self, ?self_); + open_frac_borrow_strong_(k, mk_points_to(self, self_), q); + open [?f]mk_points_to::>(self, self_)(); + open_points_to(self); + close [f]mk_points_to::>(&(*self).inner, self_.inner)(); + close scaledp(f, mk_points_to(&(*self).inner, self_.inner))(); + produce_lem_ptr_chunk restore_frac_borrow(True, scaledp(f, mk_points_to(&(*self).inner, self_.inner)), f, mk_points_to(self, self_))() { + open scaledp(f, mk_points_to(&(*self).inner, self_.inner))(); + open mk_points_to::>(&(*self).inner, self_.inner)(); + open_points_to(&(*self).inner); + close_points_to(self, f); + close [f]mk_points_to::>(self, self_)(); + } { + close_frac_borrow_strong_(); + } + full_borrow_into_frac(k, scaledp(f, mk_points_to(&(*self).inner, self_.inner))); + frac_borrow_implies_scaled(k, f, mk_points_to(&(*self).inner, self_.inner)); + close points_to_shared(k, &(*self).inner, self_.inner); + leak points_to_shared(k, &(*self).inner, self_.inner); + init_ref_readonly_points_to_shared(inner_ref); + } else { + open RawVec_share_(k, ?t, self, ?alloc_id, ?ptr, ?capacity); + init_ref_RawVecInner_(inner_ref); + } + @*/ + //@ open_frac_borrow(k, ref_initialized_(inner_ref), q/2); + //@ open [?f]ref_initialized_::>(inner_ref)(); + let r = self.inner.allocator(); + //@ assert [f]ref_initialized::>(inner_ref); + //@ close [f]ref_initialized_::>(inner_ref)(); + //@ close_frac_borrow(f, ref_initialized_(inner_ref)); + r + } + + /// Ensures that the buffer contains at least enough space to hold `len + + /// additional` elements. If it doesn't already have enough capacity, will + /// reallocate enough space plus comfortable slack space to get amortized + /// *O*(1) behavior. Will limit this behavior if it would needlessly cause + /// itself to panic. + /// + /// If `len` exceeds `self.capacity()`, this may fail to actually allocate + /// the requested space. This is not really unsafe, but the unsafe + /// code *you* write that relies on the behavior of this function may break. + /// + /// This is ideal for implementing a bulk-push operation like `extend`. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Aborts + /// + /// Aborts on OOM. + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn reserve(&mut self, len: usize, additional: usize) { + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + unsafe { self.inner.reserve(len, additional, T::LAYOUT) } + } + + /// The same as `reserve`, but returns on errors instead of panicking or aborting. + pub(crate) fn try_reserve( + &mut self, + len: usize, + additional: usize, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& + RawVec(t, self0, ?alloc_id, ?ptr0, ?capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, _); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVec(t, self1, alloc_id, ?ptr1, ?capacity1) &*& array_at_lft_(alloc_id.lft, ptr1, capacity1, _) &*& + len > capacity0 || len + additional <= capacity1, + Result::Err(e) => + RawVec(t, self1, alloc_id, ptr0, capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, _) &*& + .own(t, e) + }; + @*/ + /*@ + safety_proof { + open >.own(_t, *self); + let result = call(); + close >.own(_t, *self); + match result { + Result::Ok(u) => { + tuple_0_eq(u); + close_tuple_0_own(_t); + } + Result::Err(e) => { + } + } + close >.own(_t, result); + } + @*/ + { + //@ size_align::(); + //@ open_points_to(self); + //@ close_points_to(&(*self).inner); + //@ open RawVec(t, self0, alloc_id, ptr0, capacity0); + //@ array_at_lft__to_u8s_at_lft_(ptr0, capacity0); + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + let r = unsafe { self.inner.try_reserve(len, additional, T::LAYOUT) }; + //@ open_points_to(&(*self).inner); + //@ close_points_to(self); + //@ assert *self |-> ?self1; + /*@ + match r { + Result::Ok(u) => { + close RawVec(t, self1, alloc_id, ?ptr1, ?capacity1); + u8s_at_lft__to_array_at_lft_(ptr1, capacity1); + } + Result::Err(e) => { + close RawVec(t, self1, alloc_id, ptr0, capacity0); + u8s_at_lft__to_array_at_lft_(ptr0, capacity0); + } + } + @*/ + r + } + + /// Ensures that the buffer contains at least enough space to hold `len + + /// additional` elements. If it doesn't already, will reallocate the + /// minimum possible amount of memory necessary. Generally this will be + /// exactly the amount of memory necessary, but in principle the allocator + /// is free to give back more than we asked for. + /// + /// If `len` exceeds `self.capacity()`, this may fail to actually allocate + /// the requested space. This is not really unsafe, but the unsafe code + /// *you* write that relies on the behavior of this function may break. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Aborts + /// + /// Aborts on OOM. + #[cfg(not(no_global_oom_handling))] + pub(crate) fn reserve_exact(&mut self, len: usize, additional: usize) { + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + unsafe { self.inner.reserve_exact(len, additional, T::LAYOUT) } + } + + /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting. + pub(crate) fn try_reserve_exact( + &mut self, + len: usize, + additional: usize, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& + RawVec(t, self0, ?alloc_id, ?ptr0, ?capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, _); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVec(t, self1, alloc_id, ?ptr1, ?capacity1) &*& array_at_lft_(alloc_id.lft, ptr1, capacity1, _) &*& + len > capacity0 || len + additional <= capacity1, + Result::Err(e) => + RawVec(t, self1, alloc_id, ptr0, capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, _) &*& + .own(t, e) + }; + @*/ + /*@ + safety_proof { + open >.own(_t, *self); + let result = call(); + close >.own(_t, *self); + match result { + Result::Ok(u) => { + tuple_0_eq(u); + close_tuple_0_own(_t); + } + Result::Err(e) => { + } + } + close >.own(_t, result); + } + @*/ + { + //@ size_align::(); + //@ open_points_to(self); + //@ close_points_to(&(*self).inner); + //@ open RawVec(t, self0, alloc_id, ptr0, capacity0); + //@ array_at_lft__to_u8s_at_lft_(ptr0, capacity0); + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + let r = unsafe { self.inner.try_reserve_exact(len, additional, T::LAYOUT) }; + //@ open_points_to(&(*self).inner); + //@ close_points_to(self); + //@ assert *self |-> ?self1; + /*@ + match r { + Result::Ok(u) => { + close RawVec(t, self1, alloc_id, ?ptr1, ?capacity1); + u8s_at_lft__to_array_at_lft_(ptr1, capacity1); + } + Result::Err(e) => { + close RawVec(t, self1, alloc_id, ptr0, capacity0); + u8s_at_lft__to_array_at_lft_(ptr0, capacity0); + } + } + @*/ + r + } + + /// Shrinks the buffer down to the specified capacity. If the given amount + /// is 0, actually completely deallocates. + /// + /// # Panics + /// + /// Panics if the given amount is *larger* than the current capacity. + /// + /// # Aborts + /// + /// Aborts on OOM. + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn shrink_to_fit(&mut self, cap: usize) + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& + RawVec(t, self0, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0, ?vs0); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + RawVec(t, self1, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1, take(capacity1, vs0)) &*& + cap <= capacity0 &*& + cap <= capacity1 &*& + capacity1 == if std::mem::size_of::() == 0 { usize::MAX } else { cap }; + @*/ + /*@ + safety_proof { + open >.own(_t, ?self0); + call(); + assert RawVec(_, ?self1, _, _, _); + close >.own(_t, self1); + } + @*/ + { + //@ size_align::(); + //@ open_points_to(self); + //@ open RawVec(t, self0, alloc_id, ptr0, capacity0); + //@ RawVecInner_inv2(); + //@ array_at_lft__to_u8s_at_lft_(ptr0, capacity0); + //@ assert array_at_lft_::(_, _, _, ?bs); + //@ array_at_lft__inv(); + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + let r = unsafe { self.inner.shrink_to_fit(cap, T::LAYOUT) }; + //@ close_points_to(self); + //@ close RawVec(t, *self, alloc_id, ?ptr1, ?capacity1); + //@ u8s_at_lft__to_array_at_lft_(ptr1, capacity1); + //@ vals__of_u8s__take::(capacity1, bs, capacity0); + r + } + + /// Shrinks the buffer down to the specified capacity. If the given amount + /// is 0, actually completely deallocates. + /// + /// # Errors + /// + /// This function returns an error if the allocator cannot shrink the allocation. + /// + /// # Panics + /// + /// Panics if the given amount is *larger* than the current capacity. + #[inline] + pub(crate) fn try_shrink_to_fit(&mut self, cap: usize) -> Result<(), TryReserveError> { + // SAFETY: Layout is valid for T. + unsafe { self.inner.try_shrink_to_fit(cap, T::LAYOUT) } + } +} + +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const unsafe impl<#[may_dangle] T, A: [const] Allocator + [const] Destruct> Drop for RawVec { + /// Frees the memory owned by the `RawVec` *without* trying to drop its contents. + fn drop(&mut self) + //@ req thread_token(?t) &*& t == currentThread &*& >.full_borrow_content(t, self)(); + //@ ens thread_token(t) &*& (*self).inner |-> ?inner &*& >.own(t, inner); + { + //@ open >.full_borrow_content(t, self)(); + //@ open >.own(t, *self); + //@ open RawVec(t, *self, ?alloc_id, ?ptr, ?capacity); + //@ array_at_lft__to_u8s_at_lft_(ptr, capacity); + //@ size_align::(); + // SAFETY: We are in a Drop impl, self.inner will not be used again. + unsafe { self.inner.deallocate(T::LAYOUT) } + } +} + +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +#[rustfmt::skip] // FIXME(fee1-dead): temporary measure before rustfmt is bumped +const impl RawVecInner { + #[cfg(not(no_global_oom_handling))] + #[inline] + fn with_capacity_in(capacity: usize, alloc: A, elem_layout: Layout) -> Self + /*@ + req thread_token(?t) &*& + Allocator(t, alloc, ?alloc_id) &*& + t == currentThread; + @*/ + /*@ + ens thread_token(t) &*& + RawVecInner(t, result, elem_layout, alloc_id, ?ptr, ?capacity_) &*& + array_at_lft_(alloc_id.lft, ptr, ?n, _) &*& + elem_layout.size() % elem_layout.align() != 0 || n == elem_layout.size() * capacity_ &*& + capacity <= capacity_; + @*/ + /*@ + safety_proof { + leak .own(_t, elem_layout); + std::alloc::open_Allocator_own(alloc); + let result = call(); + open RawVecInner(_t, result, elem_layout, ?alloc_id, ?ptr, ?capacity_); + std::alloc::Allocator_to_own(result.alloc); + close RawVecInner0(result, elem_layout, ptr, capacity_); + close >.own(_t, result); + if capacity_ * elem_layout.size() != 0 { + leak alloc_block_in(_, _, _); + } + leak array_at_lft_(_, _, _, _); + } + @*/ + { + match Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc, elem_layout) { + Ok(mut this) => { + unsafe { + // Make it more obvious that a subsequent Vec::reserve(capacity) will not allocate. + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, &this); + //@ let this_ref = precreate_ref(&this); + //@ init_ref_RawVecInner_(this_ref); + //@ open_frac_borrow(k, ref_initialized_(this_ref), 1/2); + //@ open [?f]ref_initialized_::>(this_ref)(); + let needs_to_grow = this.needs_to_grow(0, capacity, elem_layout); + //@ close [f]ref_initialized_::>(this_ref)(); + //@ close_frac_borrow(f, ref_initialized_(this_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(&this); + //@ open_points_to(&this); + + hint::assert_unchecked(!needs_to_grow); + } + this + } + Err(err) => handle_error(err), + } + } + + fn try_allocate_in( + capacity: usize, + init: AllocInit, + mut alloc: A, + elem_layout: Layout, + ) -> Result + /*@ + req thread_token(?t) &*& + Allocator(t, alloc, ?alloc_id) &*& + t == currentThread; + @*/ + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(v) => + RawVecInner(t, v, elem_layout, alloc_id, ?ptr, ?capacity_) &*& + capacity <= capacity_ &*& + match init { + AllocInit::Uninitialized => + array_at_lft_(alloc_id.lft, ptr, ?n, _) &*& + elem_layout.size() % elem_layout.align() != 0 || n == capacity_ * elem_layout.size(), + AllocInit::Zeroed => + array_at_lft(alloc_id.lft, ptr, ?n, ?bs) &*& + elem_layout.size() % elem_layout.align() != 0 || n == capacity_ * elem_layout.size() &*& + forall(bs, (eq)(0)) == true + }, + Result::Err(e) => .own(t, e) + }; + @*/ + /*@ + safety_proof { + leak .own(_t, init) &*& .own(_t, elem_layout); + std::alloc::open_Allocator_own(alloc); + let result = call(); + match result { + Result::Ok(r) => { + open RawVecInner(_t, r, elem_layout, ?alloc_id, ?ptr, ?capacity_); + if capacity_ * elem_layout.size() != 0 { + leak alloc_block_in(_, _, _); + } + std::alloc::Allocator_to_own(r.alloc); + close RawVecInner0(r, elem_layout, ptr, capacity_); + close >.own(_t, r); + match init { + AllocInit::Uninitialized => { leak array_at_lft_(_, _, _, _); } + AllocInit::Zeroed => { leak array_at_lft(_, _, _, _); } + } + } + Result::Err(e) => { } + } + close , TryReserveError>>.own(_t, result); + } + @*/ + { + //@ std::alloc::Layout_inv(elem_layout); + + // We avoid `unwrap_or_else` here because it bloats the amount of + // LLVM IR generated. + let layout = match layout_array(capacity, elem_layout) { + Ok(layout) => layout, + Err(_) => { + //@ leak .own(_, _); + //@ std::alloc::Allocator_to_own(alloc); + //@ close .own(currentThread, TryReserveErrorKind::CapacityOverflow); + return Err(CapacityOverflow.into()) + }, + }; + + //@ let elemLayout = elem_layout; + //@ let layout_ = layout; + //@ assert elemLayout.repeat(capacity) == some(pair(layout_, ?stride)); + //@ std::alloc::Layout_repeat_some(elemLayout, capacity); + //@ mul_mono_l(elemLayout.size(), stride, capacity); + // Don't allocate here because `Drop` will not deallocate when `capacity` is 0. + if layout.size() == 0 { + let elem_layout_alignment = elem_layout.alignment(); + //@ close exists(elem_layout.size()); + let r = Self::new_in(alloc, elem_layout_alignment); + //@ RawVecInner_inv2::(); + //@ assert RawVecInner(_, _, _, _, ?ptr_, ?capacity_); + //@ mul_mono_l(0, capacity, elem_layout.size()); + //@ mul_zero(capacity, elem_layout.size()); + /*@ + match init { + AllocInit::Uninitialized => { close array_at_lft_(alloc_id.lft, ptr_, 0, []); } + AllocInit::Zeroed => { close array_at_lft(alloc_id.lft, ptr_, 0, []); } + } + @*/ + return Ok(r); + } + + let result = match init { + AllocInit::Uninitialized => { + let r; + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k = begin_lifetime(); + unsafe { + //@ let_lft 'a = k; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + r = alloc.allocate/*@::@*/(layout); + //@ leak Allocator(_, _, _); + } + //@ end_lifetime(k); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + r + } + #[cfg(not(no_global_oom_handling))] + AllocInit::Zeroed => { + let r; + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k = begin_lifetime(); + { + //@ let_lft 'a = k; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + r = alloc.allocate_zeroed/*@::@*/(layout); + //@ leak Allocator(_, _, _); + } + //@ end_lifetime(k); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + r + } + }; + let ptr = match result { + Ok(ptr) => ptr, + Err(_) => { + //@ std::alloc::Allocator_to_own(alloc); + let err1 = AllocError { layout, non_exhaustive: () }; + //@ std::alloc::close_Layout_own(currentThread, layout); + //@ close_tuple_0_own(currentThread); + //@ close .own(currentThread, err1); + return Err(err1.into()) + } + }; + + // Allocators currently return a `NonNull<[u8]>` whose length + // matches the size requested. If that ever changes, the capacity + // here should change to `ptr.len() / size_of::()`. + /*@ + if elem_layout.size() % elem_layout.align() == 0 { + div_rem_nonneg(elem_layout.size(), elem_layout.align()); + div_rem_nonneg(stride, elem_layout.align()); + if elem_layout.size() / elem_layout.align() < stride / elem_layout.align() { + mul_mono_l(elem_layout.size() / elem_layout.align() + 1, stride / elem_layout.align(), elem_layout.align()); + } else { + if elem_layout.size() / elem_layout.align() > stride / elem_layout.align() { + mul_mono_l(stride / elem_layout.align() + 1, elem_layout.size() / elem_layout.align(), elem_layout.align()); + assert false; + } + } + assert stride == elem_layout.size(); + } + @*/ + //@ mul_mono_l(1, elem_layout.size(), capacity); + let res = Self { + ptr: ptr.cast(), + cap: unsafe { Cap::new_unchecked(capacity) }, + alloc, + }; + //@ std::alloc::alloc_block_in_aligned(ptr.as_ptr() as *u8); + //@ close RawVecInner(t, res, elem_layout, alloc_id, ptr.as_ptr() as *u8, _); + Ok(res) + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn grow_one(&mut self, elem_layout: Layout) { + // SAFETY: Precondition passed to caller + if let Err(err) = unsafe { self.grow_amortized(self.cap.as_inner(), 1, elem_layout) } { + handle_error(err); + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - The sum of `len` and `additional` must be greater than the current capacity + unsafe fn grow_amortized( + &mut self, + len: usize, + additional: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + capacity0 < len + additional; + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), _) &*& + len + additional <= capacity1, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(t, e) + }; + @*/ + { + // This is ensured by the calling contexts. + if cfg!(debug_assertions) { //~allow_dead_code // FIXME: The source location associated with a dead `else` branch is the entire `if` statement :-( + assert!(additional > 0); + } + + if elem_layout.size() == 0 { + // Since we return a capacity of `usize::MAX` when `elem_size` is + // 0, getting to here necessarily means the `RawVec` is overfull. + //@ close .own(t, TryReserveErrorKind::CapacityOverflow); + return Err(CapacityOverflow.into()); + } + + // Nothing we can really do about these checks, sadly. + //@ close .own(t, TryReserveErrorKind::CapacityOverflow); + let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?; + //@ leak .own(t, TryReserveErrorKind::CapacityOverflow); + + //@ open_points_to(self); + //@ std::num::niche_types::UsizeNoHighBit_inv(self0.cap); + // This guarantees exponential growth. The doubling cannot overflow + // because `cap <= isize::MAX` and the type of `cap` is `usize`. + let cap0 = cmp::max(self.cap.as_inner() * 2, required_cap); + let cap = cmp::max(min_non_zero_cap(elem_layout.size()), cap0); + + //@ let k = begin_lifetime(); + //@ open RawVecInner(t, self0, elem_layout, alloc_id, ptr0, capacity0); + //@ share_RawVecInner0(k, self, elem_layout, ptr0, capacity0); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let finish_grow_result; + { + //@ let_lft 'a = k; + finish_grow_result = unsafe { self.finish_grow/*@::@*/(cap, elem_layout) }; + } + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner0(self); + + //@ open_points_to(self); + + //@ mul_mono_l(1, elem_layout.size(), cap); + + // SAFETY: Precondition passed to caller + `current_memory` does the right thing + match core::ops::Try::branch(finish_grow_result) { + core::ops::ControlFlow::Break(residual) => { + //@ let self1 = *self; + //@ close RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0); + core::ops::FromResidual::from_residual(residual) + } + core::ops::ControlFlow::Continue(ptr) => { + unsafe { + // SAFETY: layout_array would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items + self.set_ptr_and_cap(ptr, cap); + //@ let self1 = *self; + //@ std::alloc::alloc_block_in_aligned(ptr.as_ptr() as *u8); + //@ std::num::niche_types::UsizeNoHighBit_as_inner_new(cap); + //@ mul_zero(elem_layout.size(), cap); + //@ assert 0 <= self0.cap.as_inner(); + //@ assert 0 <= logical_capacity(self0.cap, elem_layout.size()); + //@ assert cap != 0; + //@ std::alloc::Layout_inv(elem_layout); + //@ assert 0 <= cap * elem_layout.size(); + //@ assert cap * elem_layout.size() <= isize::MAX - isize::MAX % elem_layout.align(); + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, cap); + //@ assert ptr.as_ptr() as usize % Layout::from_size_align(cap * elem_layout.size(), elem_layout.align()).align() == 0; + //@ std::alloc::Layout_align_Layout_from_size_align(cap * elem_layout.size(), elem_layout.align()); + //@ close RawVecInner::(t, self1, elem_layout, alloc_id, ptr.as_ptr() as *u8, cap); + } + Ok(()) + } + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - `cap` must be greater than the current capacity + // not marked inline(never) since we want optimizers to be able to observe the specifics of this + // function, see tests/codegen-llvm/vec-reserve-extend.rs. + #[cold] + unsafe fn finish_grow<'a>( + &'a self, + cap: usize, + elem_layout: Layout, + ) -> Result, TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + 1 <= elem_layout.size() &*& + elem_layout.size() % elem_layout.align() == 0 &*& + [_]RawVecInner_share_('a, t, self, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& [?q]lifetime_token('a) &*& + if capacity0 * elem_layout.size() == 0 { + true + } else { + elem_layout.repeat(capacity0) == some(pair(?allocLayout, ?stride)) &*& + std::alloc::alloc_block_in(alloc_id, ptr0, allocLayout) + } &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + capacity0 <= cap; + @*/ + /*@ + ens thread_token(t) &*& [q]lifetime_token('a) &*& + match result { + Result::Ok(new_ptr) => + elem_layout.repeat(cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, new_ptr.as_ptr() as *u8, allocLayout) &*& + array_at_lft_(alloc_id.lft, new_ptr.as_ptr() as *u8, cap * elem_layout.size(), _) &*& + cap * elem_layout.size() <= isize::MAX &*& + std::alloc::is_valid_layout(cap * elem_layout.size(), elem_layout.align()) == true, + Result::Err(e) => + if capacity0 * elem_layout.size() == 0 { + true + } else { + elem_layout.repeat(capacity0) == some(pair(?allocLayout, ?stride)) &*& + std::alloc::alloc_block_in(alloc_id, ptr0, allocLayout) + } &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(currentThread, e) + }; + @*/ + { + //@ std::alloc::Layout_inv(elem_layout); + + let new_layout = layout_array(cap, elem_layout)?; + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, cap); + + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow('a, ref_initialized_(self_ref), q/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + // SAFETY: Precondition passed to caller + let current_memory = unsafe { (&*(self as *const RawVecInner)).current_memory(elem_layout) }; + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + + //@ open RawVecInner_share_('a, t, self, elem_layout, alloc_id, ptr0, capacity0); + //@ std::alloc::Layout_inv(elem_layout); + /*@ + if capacity0 * elem_layout.size() != 0 { + let elemLayout = elem_layout; + assert elemLayout.repeat(capacity0) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some_size_aligned(elemLayout, capacity0); + std::alloc::Layout_inv(allocLayout); + } + @*/ + //@ std::alloc::Layout_size_Layout_from_size_align(capacity0 * elem_layout.size(), elem_layout.align()); + //@ std::alloc::Layout_align_Layout_from_size_align(capacity0 * elem_layout.size(), elem_layout.align()); + + //@ open_frac_borrow('a, RawVecInner_frac_borrow_content(self, elem_layout, ptr0, capacity0), q/2); + //@ open [?f1]RawVecInner_frac_borrow_content::(self, elem_layout, ptr0, capacity0)(); + //@ let cap0 = (*self).cap; + //@ std::num::niche_types::UsizeNoHighBit_inv(cap0); + //@ close [f1]RawVecInner_frac_borrow_content::(self, elem_layout, ptr0, capacity0)(); + //@ close_frac_borrow(f1, RawVecInner_frac_borrow_content(self, elem_layout, ptr0, capacity0)); + //@ mul_mono_l(1, elem_layout.size(), cap0.as_inner()); + //@ mul_mono_l(1, elem_layout.size(), cap); + //@ mul_mono_l(capacity0, cap, elem_layout.size()); + + let memory = if let Some((ptr, old_layout)) = current_memory { + // FIXME(const-hack): switch to `debug_assert_eq` + // debug_assert!(old_layout.align() == new_layout.align()); + if cfg!(debug_assertions) { //~allow_dead_code // FIXME: The source location associated + //with a dead `else` branch is the entire `if` statement :-( + if !(old_layout.align() == new_layout.align()) { + core::panicking::panic("assertion failed: old_layout.align() == new_layout.align()"); //~allow_dead_code + } + }; + unsafe { + // The allocator checks for alignment equality + hint::assert_unchecked(old_layout.align() == new_layout.align()); + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, capacity0); + //@ assert elem_layout.repeat(capacity0) == some(pair(?allocLayout, ?stride)); + //@ assert allocLayout == old_layout; + //@ assert ptr.as_ptr() as *u8 == ptr0; + //@ assert std::alloc::alloc_block_in(alloc_id, ptr0, allocLayout); + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ std::alloc::init_ref_Allocator_share::('a, t, alloc_ref); + //@ open_frac_borrow('a, ref_initialized_::(alloc_ref), q/2); + //@ open [?f2]ref_initialized_::(alloc_ref)(); + //@ std::alloc::close_Allocator_ref::<'a, A>(t, alloc_ref); + let r = self.alloc.grow/*@::@*/(ptr, old_layout, new_layout); + //@ close [f2]ref_initialized_::(alloc_ref)(); + //@ close_frac_borrow(f2, ref_initialized_::(alloc_ref)); + //@ leak Allocator(_, _, _); + r + } + } else { + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ std::alloc::init_ref_Allocator_share::('a, t, alloc_ref); + //@ open_frac_borrow('a, ref_initialized_::(alloc_ref), q/2); + //@ open [?f2]ref_initialized_::(alloc_ref)(); + //@ std::alloc::close_Allocator_ref::<'a, A>(t, alloc_ref); + let r = self.alloc.allocate/*@::@*/(new_layout); + //@ close [f2]ref_initialized_::(alloc_ref)(); + //@ close_frac_borrow(f2, ref_initialized_::(alloc_ref)); + //@ leak Allocator(_, _, _); + r + }; + + let new_layout_ref = &new_layout; + match memory { + Ok(ptr) => Ok(ptr), + Err(err) => { + let e = AllocError { layout: *new_layout_ref, non_exhaustive: () }; + //@ std::alloc::close_Layout_own(t, new_layout); + //@ close_tuple_0_own(t); + //@ close .own(t, e); + Err(e.into()) + } + } + } +} + +impl RawVecInner { + #[inline] + const fn new_in(alloc: A, align: Alignment) -> Self + /*@ + req exists::(?elemSize) &*& + thread_token(?t) &*& + Allocator(t, alloc, ?alloc_id) &*& + std::alloc::is_valid_layout(elemSize, align.as_nonzero_usize().get()) == true; + @*/ + /*@ + ens thread_token(t) &*& + RawVecInner(t, result, Layout::from_size_align(elemSize, align.as_nonzero_usize().get()), alloc_id, ?ptr, ?capacity) &*& + array_at_lft_(alloc_id.lft, ptr, capacity * elemSize, []) &*& + capacity * elemSize == 0; + @*/ + //@ on_unwind_ens false; + /*@ + safety_proof { + leak .own(_t, align); + close exists::(0); + std::alloc::open_Allocator_own(alloc); + std::mem::Alignment_is_power_of_2(align); + if align.as_nonzero_usize().get() <= isize::MAX { + div_rem_nonneg(isize::MAX, align.as_nonzero_usize().get()); + } else { + div_rem_nonneg_unique(isize::MAX, align.as_nonzero_usize().get(), 0, isize::MAX); + } + let result = call(); + open RawVecInner(_t, result, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + std::num::niche_types::UsizeNoHighBit_inv(result.cap); + std::alloc::Layout_inv(elemLayout); + mul_zero(capacity, elemLayout.size()); + assert elemLayout == Layout::from_size_align(0, align.as_nonzero_usize().get()); + std::alloc::Layout_size_Layout_from_size_align(0, align.as_nonzero_usize().get()); + assert elemLayout.size() == 0; + assert capacity * elemLayout.size() == 0; + std::alloc::Allocator_to_own(result.alloc); + close RawVecInner0(result, elemLayout, ptr, capacity); + close >.own(_t, result); + leak array_at_lft_(_, _, _, _); + } + @*/ + { + let ptr = NonNull::without_provenance(align.as_nonzero_usize()); + // `cap: 0` means "unallocated". zero-sized types are ignored. + let cap = ZERO_CAP; + let r = Self { ptr, cap, alloc }; + //@ div_rem_nonneg_unique(align.as_nonzero_usize().get(), align.as_nonzero_usize().get(), 1, 0); + //@ let layout = Layout::from_size_align(elemSize, align.as_nonzero_usize().get()); + /*@ + if layout.size() == 0 { + div_rem_nonneg_unique(layout.size(), layout.align(), 0, 0); + std::alloc::Layout_repeat_size_aligned_intro(layout, logical_capacity(cap, layout.size())); + } else { + std::alloc::Layout_repeat_0_intro(layout); + } + @*/ + //@ close RawVecInner(t, r, layout, alloc_id, _, _); + r + } + + #[inline] + fn try_with_capacity_in( + capacity: usize, + alloc: A, + elem_layout: Layout, + ) -> Result { + Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc, elem_layout) + } + + #[cfg(not(no_global_oom_handling))] + #[inline] + fn with_capacity_zeroed_in(capacity: usize, alloc: A, elem_layout: Layout) -> Self { + match Self::try_allocate_in(capacity, AllocInit::Zeroed, alloc, elem_layout) { + Ok(res) => res, + Err(err) => handle_error(err), + } + } + + #[inline] + const unsafe fn from_raw_parts_in(ptr: *mut u8, cap: Cap, alloc: A) -> Self + /*@ + req exists::(?elem_layout) &*& + Allocator(?t, alloc, ?alloc_id) &*& + ptr as usize != 0 &*& + ptr as usize % elem_layout.align() == 0 &*& + if cap.as_inner() * elem_layout.size() == 0 { + true + } else { + elem_layout.repeat(cap.as_inner()) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr, allocLayout) + }; + @*/ + //@ ens RawVecInner(t, result, elem_layout, alloc_id, ptr, logical_capacity(cap, elem_layout.size())); + { + let r = Self { ptr: unsafe { NonNull::new_unchecked(ptr) }, cap, alloc }; + //@ std::alloc::Layout_inv(elem_layout); + /*@ + if cap.as_inner() * elem_layout.size() == 0 { + std::num::niche_types::UsizeNoHighBit_inv(cap); + mul_zero(cap.as_inner(), elem_layout.size()); + if elem_layout.size() == 0 { + div_rem_nonneg_unique(elem_layout.size(), elem_layout.align(), 0, 0); + std::alloc::Layout_repeat_size_aligned_intro(elem_layout, logical_capacity(cap, elem_layout.size())); + } else { + std::alloc::Layout_repeat_0_intro(elem_layout); + } + } + @*/ + //@ close RawVecInner(t, r, elem_layout, alloc_id, ptr, logical_capacity(cap, elem_layout.size())); + r + } + + #[inline] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + const unsafe fn from_nonnull_in(ptr: NonNull, cap: Cap, alloc: A) -> Self + /*@ + req exists::(?elem_layout) &*& + Allocator(?t, alloc, ?alloc_id) &*& + ptr.as_ptr() as usize % elem_layout.align() == 0 &*& + pointer_within_limits(ptr.as_ptr()) == true &*& + if cap.as_inner() * elem_layout.size() == 0 { + true + } else { + elem_layout.repeat(cap.as_inner()) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr.as_ptr(), allocLayout) + }; + @*/ + //@ ens RawVecInner(t, result, elem_layout, alloc_id, ptr.as_ptr(), logical_capacity(cap, elem_layout.size())); + { + let r = Self { ptr, cap, alloc }; + /*@ + if cap.as_inner() * elem_layout.size() == 0 { + std::num::niche_types::UsizeNoHighBit_inv(cap); + std::alloc::Layout_inv(elem_layout); + mul_zero(cap.as_inner(), elem_layout.size()); + if elem_layout.size() == 0 { + div_rem_nonneg_unique(elem_layout.size(), elem_layout.align(), 0, 0); + std::alloc::Layout_repeat_size_aligned_intro(elem_layout, usize::MAX); + } else { + std::alloc::Layout_repeat_0_intro(elem_layout); + } + } + @*/ + //@ close RawVecInner(t, r, elem_layout, alloc_id, _, _); + r + } + + #[inline] + const fn ptr(&self) -> *mut T + /*@ + req [_]RawVecInner_share_(?k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity) &*& + [?q]lifetime_token(k); + @*/ + //@ ens [q]lifetime_token(k) &*& result == ptr as *T; + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ RawVecInner_share__inv::(); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), q/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let r = unsafe { &*(self as *const RawVecInner) }.non_null::(); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + r.as_ptr() + } + + #[inline] + const fn non_null(&self) -> NonNull + //@ req [_]RawVecInner_share_(?k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + //@ ens [q]lifetime_token(k) &*& result.as_ptr() == ptr as *T; + /*@ + safety_proof { + open >.share(?k, _t, self); + let result = call(); + std::ptr::close_NonNull_own::(_t, result); + } + @*/ + { + //@ open RawVecInner_share_(k, t, self, elem_layout, alloc_id, ptr, capacity); + //@ open_frac_borrow(k, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity), q); + //@ open [?f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + let r = self.ptr.cast(); + //@ close [f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ close_frac_borrow(f, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity)); + r + } + + #[inline] + const fn capacity(&self, elem_size: usize) -> usize + /*@ + req [_]RawVecInner_share_(?k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity) &*& + [?q]lifetime_token(k); + @*/ + //@ ens [q]lifetime_token(k) &*& elem_size != elem_layout.size() || result == capacity; + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open RawVecInner_share_(k, t, self, elem_layout, alloc_id, ptr, capacity); + //@ open_frac_borrow(k, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity), q); + //@ open [?f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + let r = + if elem_size == 0 { usize::MAX } else { self.cap.as_inner() }; + //@ close [f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ close_frac_borrow(f, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity)); + r + } + + #[inline] + const fn allocator(&self) -> &A + /*@ + req [?q]lifetime_token(?k) &*& + exists(?readOnly) &*& + if readOnly { + [_]points_to_shared(k, self, ?self_) &*& + ens [q]lifetime_token(k) &*& + [_]points_to_shared(k, result, self_.alloc()) &*& + [_]frac_borrow(k, ref_initialized_(result)) + } else { + [_]RawVecInner_share_(k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity) &*& + ens [q]lifetime_token(k) &*& + [_]std::alloc::Allocator_share(k, t, result, alloc_id) &*& + [_]frac_borrow(k, ref_initialized_(result)) + }; + @*/ + //@ ens true; + /*@ + safety_proof { + open >.share(?k, _t, self); + close exists(false); + let result = call(); + std::alloc::close_Allocator_share(k, _t, result); + } + @*/ + { + //@ let alloc_ref = precreate_ref(&(*self).alloc); + /*@ + if readOnly { + open points_to_shared(k, self, ?self_); + open_frac_borrow_strong_(k, mk_points_to(self, self_), q); + open [?f]mk_points_to::>(self, self_)(); + open_points_to(self); + close [f]mk_points_to::(&(*self).alloc, self_.alloc)(); + close scaledp(f, mk_points_to(&(*self).alloc, self_.alloc))(); + { + pred Ctx() = [f](*self).ptr |-> self_.ptr &*& [f](*self).cap |-> self_.cap &*& [f]struct_RawVecInner_padding(self); + close Ctx(); + produce_lem_ptr_chunk restore_frac_borrow(Ctx, scaledp(f, mk_points_to(&(*self).alloc, self_.alloc)), f, mk_points_to(self, self_))() { + open Ctx(); + open scaledp(f, mk_points_to(&(*self).alloc, self_.alloc))(); + open [f]mk_points_to::(&(*self).alloc, self_.alloc)(); + close [f]mk_points_to::>(self, self_)(); + } { + close_frac_borrow_strong_(); + full_borrow_into_frac(k, scaledp(f, mk_points_to(&(*self).alloc, self_.alloc))); + } + } + frac_borrow_implies_scaled(k, f, mk_points_to(&(*self).alloc, self_.alloc)); + close points_to_shared(k, &(*self).alloc, self_.alloc); + leak points_to_shared(k, &(*self).alloc, self_.alloc); + init_ref_readonly_points_to_shared(alloc_ref); + } else { + open RawVecInner_share_(k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity); + std::alloc::init_ref_Allocator_share(k, t, alloc_ref); + } + @*/ + //@ open_frac_borrow(k, ref_initialized_::(alloc_ref), q); + //@ open [?f]ref_initialized_::(alloc_ref)(); + let r = &self.alloc; + //@ close [f]ref_initialized_::(alloc_ref)(); + //@ close_frac_borrow(f, ref_initialized_::(alloc_ref)); + r + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + #[inline] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + const unsafe fn current_memory(&self, elem_layout: Layout) -> Option<(NonNull, Layout)> + /*@ + req [_]RawVecInner_share_(?k, ?t, self, elem_layout, ?alloc_id, ?ptr, ?capacity) &*& + [?q]lifetime_token(k) &*& elem_layout.size() % elem_layout.align() == 0; + @*/ + /*@ + ens [q]lifetime_token(k) &*& + if capacity * elem_layout.size() == 0 { + result == Option::None + } else { + result == Option::Some(?r) &*& + r.0.as_ptr() == ptr &*& + r.1 == Layout::from_size_align(capacity * elem_layout.size(), elem_layout.align()) + }; + @*/ + //@ on_unwind_ens false; + { + //@ open RawVecInner_share_(k, t, self, elem_layout, alloc_id, ptr, capacity); + //@ open_frac_borrow(k, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity), q); + //@ open [?f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ std::num::niche_types::UsizeNoHighBit_inv((*self).cap); + //@ std::alloc::Layout_inv(elem_layout); + //@ mul_zero(capacity, elem_layout.size()); + if elem_layout.size() == 0 || self.cap.as_inner() == 0 { + //@ close [f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ close_frac_borrow(f, RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)); + None + } else { + // We could use Layout::array here which ensures the absence of isize and usize overflows + // and could hypothetically handle differences between stride and size, but this memory + // has already been allocated so we know it can't overflow and currently Rust does not + // support such types. So we can do better by skipping some checks and avoid an unwrap. + // SAFETY: Upheld by caller, unless the element size is 0 which is checked against. + unsafe { + //@ let elemLayout = elem_layout; + //@ assert elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, capacity); + //@ std::alloc::Layout_inv(allocLayout); + //@ is_power_of_2_pos(elem_layout.align()); + //@ div_rem_nonneg(isize::MAX, elem_layout.align()); + let alloc_size = elem_layout.size().unchecked_mul(self.cap.as_inner()); + let layout = Layout::from_size_align_unchecked(alloc_size, elem_layout.align()); + let ptr_ = self.ptr; + //@ std::ptr::NonNull_new_as_ptr((*self).ptr); + //@ close [f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ close_frac_borrow(f, RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)); + Some((ptr_, layout)) + } + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn reserve(&mut self, len: usize, additional: usize, elem_layout: Layout) { + // Callers expect this function to be very cheap when there is already sufficient capacity. + // Therefore, we move all the resizing and error-handling logic from grow_amortized and + // handle_reserve behind a call, while making sure that this function is likely to be + // inlined as just a comparison and a call if the comparison fails. + #[cold] + unsafe fn do_reserve_and_handle( + slf: &mut RawVecInner, + len: usize, + additional: usize, + elem_layout: Layout, + ) { + // SAFETY: Precondition passed to caller + if let Err(err) = unsafe { slf.grow_amortized(len, additional, elem_layout) } { + handle_error(err); + } + } + + if self.needs_to_grow(len, additional, elem_layout) { + // SAFETY: `needs_to_grow` ensures that `len + additional` is greater than + // the current capacity, with the other preconditions upheld by our caller. + unsafe { + do_reserve_and_handle(self, len, additional, elem_layout); + } + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + unsafe fn try_reserve( + &mut self, + len: usize, + additional: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), _) &*& + len > capacity0 || len + additional <= capacity1, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(t, e) + }; + @*/ + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let needs_to_grow = self.needs_to_grow(len, additional, elem_layout); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + + if needs_to_grow { + // SAFETY: Precondition passed to caller + unsafe { + self.grow_amortized(len, additional, elem_layout)?; + } + } + // SAFETY: If we've already grown, we will not need to again immediately after. + unsafe { + //@ let k2 = begin_lifetime(); + //@ share_RawVecInner(k2, self); + //@ let self_ref2 = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref2); + //@ open_frac_borrow(k2, ref_initialized_(self_ref2), 1/2); + //@ open [?f2]ref_initialized_::>(self_ref2)(); + let needs_to_grow2 = self.needs_to_grow(len, additional, elem_layout); + //@ close [f2]ref_initialized_::>(self_ref2)(); + //@ close_frac_borrow(f2, ref_initialized_(self_ref2)); + //@ end_lifetime(k2); + //@ end_share_RawVecInner(self); + + // Inform the optimizer that the reservation has succeeded or wasn't needed + hint::assert_unchecked(!needs_to_grow2); + + } + Ok(()) + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + #[cfg(not(no_global_oom_handling))] + unsafe fn reserve_exact(&mut self, len: usize, additional: usize, elem_layout: Layout) { + // SAFETY: Precondition passed to caller + if let Err(err) = unsafe { self.try_reserve_exact(len, additional, elem_layout) } { + handle_error(err); + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + unsafe fn try_reserve_exact( + &mut self, + len: usize, + additional: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), _) &*& + len > capacity0 || len + additional <= capacity1, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(t, e) + }; + @*/ + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let needs_to_grow = self.needs_to_grow(len, additional, elem_layout); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + + if needs_to_grow { + // SAFETY: Precondition passed to caller + unsafe { + self.grow_exact(len, additional, elem_layout)?; + } + } + // SAFETY: If we've already grown, we will not need to again immediately after. + unsafe { + //@ let k2 = begin_lifetime(); + //@ share_RawVecInner(k2, self); + //@ let self_ref2 = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref2); + //@ open_frac_borrow(k2, ref_initialized_(self_ref2), 1/2); + //@ open [?f2]ref_initialized_::>(self_ref2)(); + let needs_to_grow2 = self.needs_to_grow(len, additional, elem_layout); + //@ close [f2]ref_initialized_::>(self_ref2)(); + //@ close_frac_borrow(f2, ref_initialized_(self_ref2)); + //@ end_lifetime(k2); + //@ end_share_RawVecInner(self); + + // Inform the optimizer that the reservation has succeeded or wasn't needed + hint::assert_unchecked(!needs_to_grow2); + + } + Ok(()) + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - `cap` must be less than or equal to `self.capacity(elem_layout.size())` + #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn shrink_to_fit(&mut self, cap: usize, elem_layout: Layout) + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), ?bs0); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), take(capacity1 * elem_layout.size(), bs0)) &*& + cap <= capacity0 &*& + cap <= capacity1 &*& + capacity1 == if elem_layout.size() == 0 { usize::MAX } else { cap }; + @*/ + { + if let Err(err) = unsafe { self.shrink(cap, elem_layout) } { + handle_error(err); + } + } + + /// # Safety + /// + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - `cap` must be less than or equal to `self.capacity(elem_layout.size())` + unsafe fn try_shrink_to_fit( + &mut self, + cap: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> { + // SAFETY: Upheld by caller. + unsafe { self.shrink(cap, elem_layout) } + } + + #[inline] + const fn needs_to_grow(&self, len: usize, additional: usize, elem_layout: Layout) -> bool + /*@ + req [_]RawVecInner_share_(?k, ?t, self, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& + [?qa]lifetime_token(k); + @*/ + //@ ens [qa]lifetime_token(k) &*& elem_layout != elemLayout || result == (additional > std::num::wrapping_sub_usize(capacity, len)); + /*@ + safety_proof { + leak .own(_t, elem_layout); + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), qa/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let r = additional > unsafe { &*(self as *const RawVecInner) }.capacity(elem_layout.size()).wrapping_sub(len); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + r + } + + #[inline] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + const unsafe fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) + //@ req (*self).ptr |-> _ &*& (*self).cap |-> _ &*& cap <= isize::MAX; + //@ ens (*self).ptr |-> ptr.as_non_null_ptr() &*& (*self).cap |-> UsizeNoHighBit::new(cap); + { + //@ std::ptr::NonNull_new_as_ptr(ptr.as_non_null_ptr()); + // Allocators currently return a `NonNull<[u8]>` whose length matches + // the size requested. If that ever changes, the capacity here should + // change to `ptr.len() / size_of::()`. + self.ptr = ptr.cast(); + // SAFETY: Upheld by caller. + self.cap = unsafe { Cap::new_unchecked(cap) }; + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - The sum of `len` and `additional` must be greater than the current capacity + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - The sum of `len` and `additional` must be greater than the current capacity + unsafe fn grow_exact( + &mut self, + len: usize, + additional: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + capacity0 < len + additional; + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), _) &*& + len + additional <= capacity1, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(t, e) + }; + @*/ + { + if elem_layout.size() == 0 { + // Since we return a capacity of `usize::MAX` when the type size is + // 0, getting to here necessarily means the `RawVec` is overfull. + let e = CapacityOverflow; + //@ close .own(t, e); + return Err(e.into()); + } + + //@ close .own(t, TryReserveErrorKind::CapacityOverflow); + let cap = len.checked_add(additional).ok_or(CapacityOverflow)?; + //@ leak .own(t, TryReserveErrorKind::CapacityOverflow); + + //@ let k = begin_lifetime(); + //@ open RawVecInner(t, self0, elem_layout, alloc_id, ptr0, capacity0); + //@ share_RawVecInner0(k, self, elem_layout, ptr0, capacity0); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let finish_grow_result; + { + //@ let_lft 'a = k; + finish_grow_result = unsafe { self.finish_grow/*@::@*/(cap, elem_layout) }; + } + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner0(self); + + //@ open_points_to(self); + + //@ mul_mono_l(1, elem_layout.size(), cap); + + // SAFETY: Precondition passed to caller + `current_memory` does the right thing + match core::ops::Try::branch(finish_grow_result) { + core::ops::ControlFlow::Break(residual) => { + //@ let self1 = *self; + //@ close RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0); + core::ops::FromResidual::from_residual(residual) + } + core::ops::ControlFlow::Continue(ptr) => { + // SAFETY: layout_array would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items + unsafe { + //@ let elemLayout = elem_layout; + //@ assert elemLayout.repeat(cap) == some(pair(?new_layout, ?stride)); + //@ std::alloc::Layout_repeat_some_size_aligned(elemLayout, cap); + //@ assert new_layout.size() == elem_layout.size() * cap; + //@ mul_mono_l(1, elem_layout.size(), cap); + self.set_ptr_and_cap(ptr, cap); + //@ let self1 = *self; + //@ std::alloc::alloc_block_in_aligned(ptr.as_ptr() as *u8); + //@ std::num::niche_types::UsizeNoHighBit_as_inner_new(cap); + //@ mul_zero(elem_layout.size(), cap); + //@ assert 0 <= self0.cap.as_inner(); + //@ assert 0 <= logical_capacity(self0.cap, elem_layout.size()); + //@ assert cap != 0; + //@ std::alloc::Layout_inv(new_layout); + //@ close RawVecInner::(t, self1, elem_layout, alloc_id, _, _); + } + Ok(()) + } + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - `cap` must be less than or equal to `self.capacity(elem_layout.size())` + #[inline] + unsafe fn shrink(&mut self, cap: usize, elem_layout: Layout) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), ?bs0); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), take(capacity1 * elem_layout.size(), bs0)) &*& + cap <= capacity0 &*& + cap <= capacity1 &*& + capacity1 == if elem_layout.size() == 0 { usize::MAX } else { cap }, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), bs0) &*& + .own(t, e) + }; + @*/ + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let capacity = self.capacity(elem_layout.size()); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + assert!(cap <= capacity, "Tried to shrink to a larger capacity"); + // SAFETY: Just checked this isn't trying to grow + unsafe { self.shrink_unchecked(cap, elem_layout) } + } + + /// `shrink`, but without the capacity check. + /// + /// This is split out so that `shrink` can inline the check, since it + /// optimizes out in things like `shrink_to_fit`, without needing to + /// also inline all this code, as doing that ends up failing the + /// `vec-shrink-panic` codegen test when `shrink_to_fit` ends up being too + /// big for LLVM to be willing to inline. + /// + /// # Safety + /// - `cap <= self.capacity()` + /// - `elem_layout` must be valid for `self`. + unsafe fn shrink_unchecked( + &mut self, + cap: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), ?bs0) &*& + cap <= capacity0; + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), take(capacity1 * elem_layout.size(), bs0)) &*& + cap <= capacity1 &*& + capacity1 == if elem_layout.size() == 0 { usize::MAX } else { cap }, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), bs0) &*& + .own(t, e) + }; + @*/ + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + // SAFETY: Precondition passed to caller + let current_memory = unsafe { self.current_memory(elem_layout) }; + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + + let Some((ptr, layout)) = current_memory else { + //@ std::alloc::Layout_inv(elem_layout); + //@ mul_zero(capacity0, elem_layout.size()); + //@ RawVecInner_inv2(); + return Ok(()); + }; + + //@ open_points_to(self); + + //@ open RawVecInner(t, ?self01, elem_layout, alloc_id, ptr0, capacity0); + //@ assert self01.ptr.as_ptr() == ptr0; + //@ std::alloc::Layout_inv(elem_layout); + /*@ + if capacity0 * elem_layout.size() != 0 { + let elemLayout = elem_layout; + assert elemLayout.repeat(capacity0) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some_size_aligned(elemLayout, capacity0); + std::alloc::Layout_inv(allocLayout); + } + @*/ + //@ std::alloc::Layout_size_Layout_from_size_align(capacity0 * elem_layout.size(), elem_layout.align()); + //@ std::alloc::Layout_align_Layout_from_size_align(capacity0 * elem_layout.size(), elem_layout.align()); + + // If shrinking to 0, deallocate the buffer. We don't reach this point + // for the T::IS_ZST case since current_memory() will have returned + // None. + if cap == 0 { + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ let k1 = begin_lifetime(); + unsafe { + //@ let_lft 'a = k1; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + self.alloc.deallocate/*@::@*/(ptr, layout); + //@ leak Allocator(_, _, _); + }; + //@ end_lifetime(k1); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + self.ptr = NonNull::without_provenance(elem_layout.alignment().as_nonzero_usize()); + self.cap = ZERO_CAP; + //@ let ptr1_ = (*self).ptr; + //@ assert ptr1_.as_ptr() as usize == elem_layout.align(); + //@ div_rem_nonneg_unique(elem_layout.align(), elem_layout.align(), 1, 0); + //@ std::alloc::Layout_repeat_0_intro(elem_layout); + //@ close RawVecInner(t, *self, elem_layout, alloc_id, _, _); + } else { + // SAFETY: `cap` is less than the previous capacity, which must have fit in an + // isize already for the non-ZST case. `shrink` is also sound to call since + // `current_memory` ensures `ptr` and `layout` are correct for the old allocation, + // while `new_layout` is computed with a smaller size than the old one per the + // requirement we instate on our callers. + let ptr = unsafe { + // Layout cannot overflow here because it would have + // overflowed earlier when capacity was larger. + //@ mul_mono_l(cap, capacity0, elem_layout.size()); + let new_size = elem_layout.size().unchecked_mul(cap); + let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ let k1 = begin_lifetime(); + let r; + { + //@ let_lft 'a = k1; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + r = self.alloc.shrink/*@::@*/(ptr, layout, new_layout); + //@ leak Allocator(_, _, _); + }; + //@ end_lifetime(k1); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + let new_layout_ref = &new_layout; + match r { + Ok(ptr1) => Ok(ptr1), + Err(err) => { + //@ close RawVecInner(t, *self, elem_layout, alloc_id, ptr0, capacity0); + let e = AllocError { layout: *new_layout_ref, non_exhaustive: () }; + //@ std::alloc::close_Layout_own(t, new_layout); + //@ close_tuple_0_own(t); + //@ close .own(t, e); + Err(e) + } + }? + }; + // SAFETY: if the allocation is valid, then the capacity is too + unsafe { + //@ std::num::niche_types::UsizeNoHighBit_inv(self01.cap); + self.set_ptr_and_cap(ptr, cap); + //@ std::alloc::alloc_block_in_aligned(ptr_1.as_ptr() as *u8); + //@ mul_zero(cap, elem_layout.size()); + //@ std::alloc::Layout_repeat_size_aligned_intro(elem_layout, cap); + //@ close RawVecInner(t, *self, elem_layout, alloc_id, _, _); + } + } + Ok(()) + } +} + +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const impl RawVecInner { + /// # Safety + /// + /// This function deallocates the owned allocation, but does not update `ptr` or `cap` to + /// prevent double-free or use-after-free. Essentially, do not do anything with the caller + /// after this function returns. + /// Ideally this function would take `self` by move, but it cannot because it exists to be + /// called from a `Drop` impl. + unsafe fn deallocate(&mut self, elem_layout: Layout) + /*@ + req thread_token(?t) &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr_, ?capacity) &*& + elem_layout.size() % elem_layout.align() == 0 &*& + array_at_lft_(alloc_id.lft, ptr_, capacity * elem_layout.size(), _); + @*/ + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + // SAFETY: Precondition passed to caller + let current_memory = unsafe { self.current_memory(elem_layout) }; + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + + //@ open_points_to(self); + //@ open RawVecInner(t, _, elem_layout, alloc_id, ptr_, capacity); + if let Some((ptr, layout)) = current_memory { + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ let k1 = begin_lifetime(); + unsafe { + //@ let_lft 'a = k1; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, capacity); + //@ assert capacity * elem_layout.size() == layout.size(); + self.alloc.deallocate/*@::@*/(ptr, layout); + } + //@ end_lifetime(k1); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + } + //@ std::alloc::Allocator_to_own((*self).alloc); + //@ close RawVecInner0(*self, elem_layout, ptr_, capacity); + //@ close >.own(t, *self); + } +} + +// Central function for reserve error handling. +#[cfg(not(no_global_oom_handling))] +#[cold] +#[optimize(size)] +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const fn handle_error(e: TryReserveError) -> ! +//@ req thread_token(?t); +//@ ens false; +{ + match e.kind() { + CapacityOverflow => capacity_overflow(), + AllocError { layout, .. } => handle_alloc_error(layout), + } +} + +#[inline] +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const fn layout_array(cap: usize, elem_layout: Layout) -> Result +//@ req thread_token(currentThread); +/*@ +ens thread_token(currentThread) &*& + elem_layout.size() % elem_layout.align() == 0 &*& // Established by the `debug_assert!` below + match result { + Result::Ok(layout) => elem_layout.repeat(cap) == some(pair(layout, ?stride)), + Result::Err(err) => .own(currentThread, err) + }; +@*/ +/*@ +safety_proof { + leak .own(_t, elem_layout); + let result = call(); + match result { + Result::Ok(layout) => { std::alloc::close_Layout_own(_t, layout); } + Result::Err(e) => {} + } + close >.own(_t, result); +} +@*/ +{ + // This is only used with `elem_layout`s which are those of real rust types, + // which lets us use the much-simpler `repeat_packed`. + // debug_assert!(elem_layout.size() == elem_layout.pad_to_align().size()); + if cfg!(debug_assertions) { //~allow_dead_code // FIXME: The source location associated + //with a dead `else` branch is the entire `if` statement :-( + if !(elem_layout.size() == elem_layout.pad_to_align().size()) { + core::panicking::panic("assertion failed: elem_layout.size() == elem_layout.pad_to_align().size()"); + } + }; + + // FIXME(const-hack) return to using `map` and `map_err` once `const_closures` is implemented + let r2 = match elem_layout.repeat_packed(cap) { + Ok(layout) => { + //@ std::alloc::Layout_repeat_size_aligned_intro(elem_layout, cap); + Ok(layout) + } + Err(err) => { + let e = CapacityOverflow; + //@ close .own(currentThread, e); + Err(e.into()) + } + }; + r2 +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/into_iter.rs b/verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/into_iter.rs new file mode 100644 index 0000000000000..ca831d78bbab6 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/into_iter.rs @@ -0,0 +1,2520 @@ +use core::iter::{ + FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, + TrustedRandomAccessNoCoerce, +}; +#[cfg(kani)] +use core::kani; +use core::marker::PhantomData; +use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties}; +use core::num::NonZero; +#[cfg(not(no_global_oom_handling))] +use core::ops::Deref; +use core::panic::UnwindSafe; +use core::ptr::{self, NonNull}; +use core::{array, fmt, slice}; + +use safety::{loop_invariant, requires}; + +#[cfg(not(no_global_oom_handling))] +use super::AsVecIntoIter; +use crate::alloc::{Allocator, Global}; +#[cfg(not(no_global_oom_handling))] +use crate::collections::VecDeque; +use crate::raw_vec::RawVec; + +//@ use std::alloc::{Allocator, alloc_id_t, alloc_block_in, Layout}; +//@ use std::ptr::{NonNull, NonNull_as_ptr_nonnull}; +//@ use std::option::{Option, Option::None, Option::Some}; +//@ use std::ops::ControlFlow; +//@ use raw_vec::{RawVec, RawVec_to_own, RawVec_inv}; + +macro non_null { + (mut $place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { &mut *((&raw mut $place) as *mut NonNull<$t>) } + }}, + ($place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { *((&$place as *const *const $t) as *const NonNull<$t>) } + }}, +} + +/// An iterator that moves out of a vector. +/// +/// This `struct` is created by the `into_iter` method on [`Vec`](super::Vec) +/// (provided by the [`IntoIterator`] trait). +/// +/// # Example +/// +/// ``` +/// let v = vec![0, 1, 2]; +/// let iter: std::vec::IntoIter<_> = v.into_iter(); +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_insignificant_dtor] +pub struct IntoIter< + T, + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] A: Allocator = Global, +> { + pub(super) buf: NonNull, + pub(super) phantom: PhantomData, + pub(super) cap: usize, + // the drop impl reconstructs a RawVec from buf, cap and alloc + // to avoid dropping the allocator twice we need to wrap it into ManuallyDrop + pub(super) alloc: ManuallyDrop, + pub(super) ptr: NonNull, + /// If T is a ZST, this is actually ptr+len. This encoding is picked so that + /// ptr == end is a quick test for the Iterator being empty, that works + /// for both ZST and non-ZST. + /// For non-ZSTs the pointer is treated as `NonNull` + pub(super) end: *const T, +} + +/*@ + +lem wrapping_sub_usize_zero(a: usize, b: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX; + ens (std::num::wrapping_sub_usize(a, b) == 0) == (a == b); +{ +} + +lem wrapping_sub_usize_dec(a: usize, b: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX &*& a != b; + ens std::num::wrapping_sub_usize(std::num::wrapping_sub_usize(a, 1), b) == std::num::wrapping_sub_usize(a, b) - 1; +{ +} + +lem wrapping_sub_usize_sub(a: usize, b: usize, n: usize) + req 0 <= a &*& a <= usize::MAX &*& 0 <= b &*& b <= usize::MAX &*& 0 <= n &*& n <= std::num::wrapping_sub_usize(a, b); + ens std::num::wrapping_sub_usize(std::num::wrapping_sub_usize(a, n), b) == std::num::wrapping_sub_usize(a, b) - n; +{ +} + +lem foreach_own_send(t0: thread_id_t, t1: thread_id_t) + req foreach(?xs, own::(t0)) &*& type_interp::() &*& is_Send(typeid(T)) == true; + ens foreach(xs, own::(t1)) &*& type_interp::(); +{ + open foreach(xs, own::(t0)); + match xs { + nil => {} + cons(x, xs0) => { + open own::(t0)(x); + Send::send::(t0, t1, x); + close own::(t1)(x); + foreach_own_send::(t0, t1); + } + } + close foreach(xs, own::(t1)); +} + +lem array_at_lft_own_mono(t: thread_id_t, k: lifetime_t, p: *T0, n: usize) + req array_at_lft::(k, p, n, ?elems) &*& foreach(elems, own::(t)) &*& + type_interp::() &*& type_interp::() &*& + is_subtype_of::() == true &*& + std::mem::size_of::() == std::mem::size_of::() &*& + std::mem::align_of::() == std::mem::align_of::(); + ens array_at_lft::(k, p as *T1, n, ?elems1) &*& foreach(elems1, own::(t)) &*& + type_interp::() &*& type_interp::(); +{ + open array_at_lft::(k, p, n, elems); + open foreach(elems, own::(t)); + match elems { + nil => { + close array_at_lft::(k, p as *T1, 0, nil); + close foreach(nil, own::(t)); + } + cons(x, xs0) => { + open points_to_at_lft::(k, p, x); + to_u8s__at_lft::(p); + assert array_at_lft_(k, p as *u8, std::mem::size_of::(), ?bs); + from_u8s__at_lft::(p as *T1); + // Rust subtyping (`T0 <: T1`) only weakens lifetimes and preserves byte + // representation (https://github.com/verifast/verifast/issues/610). + let x1 = upcast::(x); + assume(of_u8s_::(bs) == some(x1)); + close points_to_at_lft::(k, p as *T1, x1); + open own::(t)(x); + own_mono::(t, x); + close own::(t)(x1); + array_at_lft_own_mono::(t, k, p + 1, n - 1); + assert array_at_lft::(k, (p + 1) as *T1, n - 1, ?xs1); + assert ((p + 1) as *T1) == ((p as *T1) + 1); + close array_at_lft::(k, p as *T1, n, cons(x1, xs1)); + close foreach(cons(x1, xs1), own::(t)); + } + } +} + +lem foreach_snoc_inv(xs: list, x: T, p: pred(T)) + req foreach(append(xs, [x]), p); + ens foreach(xs, p) &*& p(x); +{ + match xs { + nil => { + open foreach([x], p); + open foreach(nil, p); + close foreach(nil, p); + } + cons(h, t) => { + open foreach(cons(h, append(t, [x])), p); + foreach_snoc_inv(t, x, p); + close foreach(cons(h, t), p); + } + } +} + +lem list_split_last(xs: list) + req length(xs) > 0; + ens xs == append(take(length(xs) - 1, xs), [nth(length(xs) - 1, xs)]) &*& length(take(length(xs) - 1, xs)) == length(xs) - 1; +{ + match xs { + nil => {} + cons(h, t) => { + if length(t) == 0 { + match t { + nil => {} + cons(h1, t1) => {} + } + } else { + list_split_last(t); + } + } + } +} + +pred IntoIter_non_zst_buf(t: thread_id_t, buf: NonNull, cap: usize, alloc_id: alloc_id_t, ptr: NonNull, end: *T, adv: usize, end_idx: usize, elems: list) = + 0 <= adv &*& adv <= end_idx &*& end_idx <= cap &*& + cap * std::mem::size_of::() <= isize::MAX &*& + if cap == 0 { + true + } else { + Layout::new::().repeat(cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, buf.as_ptr() as *u8, allocLayout) + } &*& + ptr.as_ptr() == buf.as_ptr() + adv &*& + end == buf.as_ptr() + end_idx &*& + end != 0 &*& pointer_within_limits(end) == true &*& + array_at_lft_(alloc_id.lft, buf.as_ptr(), adv, _) &*& + array_at_lft(alloc_id.lft, ptr.as_ptr(), end_idx - adv, elems) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, buf.as_ptr() + end_idx, cap - end_idx, _); + +pred >.own(t, it) = + Allocator(t, it.alloc, ?alloc_id) &*& + it.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(it.buf.as_ptr()) == true &*& + 0 <= (it.end as usize) &*& (it.end as usize) <= usize::MAX &*& + (it.end as pointer) == pointer_ctor((it.ptr.as_ptr() as pointer).provenance, it.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + it.ptr == it.buf &*& + array_at_lft(alloc_id.lft, it.ptr.as_ptr(), std::num::wrapping_sub_usize(it.end as usize, it.ptr.as_ptr() as usize), ?elems) &*& + foreach(elems, own::(t)) + } else { + IntoIter_non_zst_buf::(t, it.buf, it.cap, alloc_id, it.ptr, it.end, ?adv, ?end_idx, ?elems) + }; + +lem IntoIter_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Send(typeid(IntoIter)) == true &*& + IntoIter_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& + IntoIter_own::(t1, v); +{ + open >.own(t0, v); + assume(is_Send(typeid(T)) == true && is_Send(typeid(A)) == true); + std::alloc::Allocator_send(t1, v.alloc); + if std::mem::size_of::() == 0 { + foreach_own_send::(t0, t1); + } else { + open IntoIter_non_zst_buf::(t0, v.buf, v.cap, ?alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + foreach_own_send::(t0, t1); + close IntoIter_non_zst_buf::(t1, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + } + close >.own(t1, v); +} + +lem IntoIter_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + IntoIter_own::(?t, ?v) &*& + is_subtype_of::() == true &*& + is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + IntoIter_own::(t, IntoIter:: { + buf: upcast(v.buf), + cap: upcast(v.cap), + alloc: upcast(v.alloc), + ptr: upcast(v.ptr), + end: v.end as *T1, + }); +{ + open >.own(t, v); + assert Allocator(t, v.alloc, ?alloc_id); + std::alloc::Allocator_upcast::(v.alloc); + std::ptr::NonNull_upcast::(v.buf); + std::ptr::NonNull_upcast::(v.ptr); + std::ptr::NonNull_Sized_as_ptr(v.ptr); + assume( + std::mem::size_of::() == std::mem::size_of::() && + std::mem::align_of::() == std::mem::align_of::() && + Layout::new::() == Layout::new::() && + upcast::(v.cap) == v.cap + ); + if std::mem::size_of::() == 0 { + array_at_lft_own_mono::(t, alloc_id.lft, v.ptr.as_ptr(), std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + array_at_lft__to_u8s_at_lft_::(v.buf.as_ptr(), adv); + u8s_at_lft__to_array_at_lft_::(v.buf.as_ptr() as *T1, adv); + array_at_lft_own_mono::(t, alloc_id.lft, v.ptr.as_ptr(), end_idx - adv); + array_at_lft__to_u8s_at_lft_::(v.buf.as_ptr() + end_idx, v.cap - end_idx); + assert ((v.buf.as_ptr() + end_idx) as *u8) == (((v.buf.as_ptr() as *T1) + end_idx) as *u8); + u8s_at_lft__to_array_at_lft_::((v.buf.as_ptr() as *T1) + end_idx, v.cap - end_idx); + close IntoIter_non_zst_buf::(t, upcast(v.buf), upcast(v.cap), alloc_id, upcast(v.ptr), v.end as *T1, adv, end_idx, _); + } + close >.own(t, IntoIter:: { + buf: upcast(v.buf), + cap: upcast(v.cap), + alloc: upcast(v.alloc), + ptr: upcast(v.ptr), + end: v.end as *T1, + }); +} + +pred IntoIter_raw_buf(t: thread_id_t, it: IntoIter) = + Allocator(t, it.alloc, ?alloc_id) &*& + it.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(it.buf.as_ptr()) == true &*& + if std::mem::size_of::() == 0 { + true + } else { + it.cap * std::mem::size_of::() <= isize::MAX &*& + (if it.cap == 0 { + true + } else { + Layout::new::().repeat(it.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, it.buf.as_ptr() as *u8, allocLayout) + }) &*& + array_at_lft_(alloc_id.lft, it.buf.as_ptr(), it.cap, _) + }; + +lem IntoIter_own_to_raw_buf(t: thread_id_t, it: IntoIter) + req >.own(t, it); + ens IntoIter_raw_buf::(t, it); +{ + open >.own(t, it); + assert Allocator(t, it.alloc, ?alloc_id); + if std::mem::size_of::() == 0 { + assert array_at_lft(alloc_id.lft, it.ptr.as_ptr(), ?len, ?elems); + leak foreach(elems, own::(t)); + leak array_at_lft(alloc_id.lft, it.ptr.as_ptr(), len, elems); + } else { + open IntoIter_non_zst_buf::(t, it.buf, it.cap, alloc_id, it.ptr, it.end, ?adv, ?end_idx, ?elems); + leak foreach(elems, own::(t)); + array_at_lft_to_array_at_lft_::(it.ptr.as_ptr()); + array_at_lft__join::(it.buf.as_ptr() + adv); + array_at_lft__join::(it.buf.as_ptr()); + } + close IntoIter_raw_buf::(t, it); +} + +lem zst_array_at_lft_move(elems: list, k: lifetime_t, src: *T, dst: *T, n: usize) + req array_at_lft::(k, src, n, elems) &*& + std::mem::size_of::() == 0 &*& + dst as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(dst) == true; + ens array_at_lft::(k, dst, n, elems); +{ + open array_at_lft::(k, src, n, elems); + match elems { + nil => { + close array_at_lft::(k, dst, 0, nil); + } + cons(x, xs0) => { + open points_to_at_lft::(k, src, x); + to_u8s__at_lft::(src); + assert array_at_lft_(k, src as *u8, 0, ?bs); + open array_at_lft_(k, src as *u8, 0, bs); + close array_at_lft_::(k, dst as *u8, 0, nil); + from_u8s__at_lft::(dst); + close points_to_at_lft::(k, dst, x); + zst_array_at_lft_move::(xs0, k, src + 1, dst + 1, n - 1); + close array_at_lft::(k, dst, n, cons(x, xs0)); + } + } +} + +lem close_slice_own_from_foreach(t: thread_id_t, elems: list) + req foreach(elems, own::(t)); + ens <[T]>.own(t, slice_of_elems(elems)); +{ + close <[T]>.own(t, slice_of_elems(elems)); +} + +pred_ctor IntoIter_shared_val(l: *IntoIter, v: IntoIter)(;) = + (*l).buf |-> v.buf &*& + (*l).cap |-> v.cap &*& + (*l).ptr |-> v.ptr &*& + (*l).end |-> v.end &*& + struct_IntoIter_padding::(l); + +pred_ctor IntoIter_shared_range(alloc_lft: lifetime_t, ptr: *T, len: usize, elems: list)(;) = + array_at_lft::(alloc_lft, ptr, len, elems); + +pred IntoIter_share_(k: lifetime_t, t: thread_id_t, l: *IntoIter, len: usize) = + [_]std::alloc::Allocator_share(k, t, &(*l).alloc, ?alloc_id) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + [_]exists::>(?v) &*& + 0 <= len &*& len <= usize::MAX &*& + [_]frac_borrow(k, IntoIter_shared_val::(l, v)) &*& + pointer_within_limits(v.ptr.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) == len + } else { + v.end == v.ptr.as_ptr() + len &*& + v.end != 0 &*& pointer_within_limits(v.end) == true &*& + len * std::mem::size_of::() <= isize::MAX &*& + [_]exists::>(?elems) &*& + [_]frac_borrow(k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)) + }; + +pred >.share(k, t, l) = + [_]IntoIter_share_::(k, t, l, ?len); + +lem IntoIter_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *IntoIter) + req type_interp::() &*& type_interp::() &*& + lifetime_inclusion(k1, k) == true &*& [_]IntoIter_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]IntoIter_share::(k1, t, l); +{ + open IntoIter_share::(k, t, l); + open IntoIter_share_::(k, t, l, ?len); + std::alloc::Allocator_share_mono::(k, k1, t, &(*l).alloc); + assert [_]std::alloc::Allocator_share(k1, t, &(*l).alloc, ?alloc_id); + assert [_]exists::>(?v); + frac_borrow_mono(k, k1, IntoIter_shared_val::(l, v)); + if std::mem::size_of::() != 0 { + assert [_]exists::>(?elems); + frac_borrow_mono(k, k1, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + } + close IntoIter_share_::(k1, t, l, len); + leak IntoIter_share_::(k1, t, l, len); + close IntoIter_share::(k1, t, l); + leak IntoIter_share::(k1, t, l); +} + +lem IntoIter_share_full(k: lifetime_t, t: thread_id_t, l: *IntoIter) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + full_borrow(k, IntoIter_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + [_]IntoIter_share::(k, t, l) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong_m(k, IntoIter_full_borrow_content::(t, l), q); + open IntoIter_full_borrow_content::(t, l)(); + assert *l |-> ?v; + open_points_to(l); + open >.own(t, v); + assert Allocator(t, v.alloc, ?alloc_id); + std::alloc::Allocator_inv(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close IntoIter_shared_val::(l, v)(); + if std::mem::size_of::() == 0 { + let len_z = std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize); + assert array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len_z, ?elems_z); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + v.ptr == v.buf &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len_z, elems_z) &*& + foreach(elems_z, own::(t)); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)), + klong, + IntoIter_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + assert (*l).alloc |-> ?a1; + close >.own(t, IntoIter:: { buf: v.buf, cap: v.cap, alloc: a1, ptr: v.ptr, end: v.end }); + close IntoIter_full_borrow_content::(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m( + klong, + IntoIter_full_borrow_content::(t, l), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)) + ); + full_borrow_split_m(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + } + } + close exists::>(v); + leak exists::>(v); + close IntoIter_share_::(k, t, l, len_z); + leak IntoIter_share_::(k, t, l, len_z); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + let len_nz = end_idx - adv; + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(len_nz, v.cap, std::mem::size_of::()); + close IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)(); + close sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& pointer_within_limits(v.end) == true &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + 0 <= adv &*& adv <= end_idx &*& end_idx <= v.cap &*& + v.cap * std::mem::size_of::() <= isize::MAX &*& + (if v.cap == 0 { + true + } else { + Layout::new::().repeat(v.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, v.buf.as_ptr() as *u8, allocLayout) + }) &*& + v.ptr.as_ptr() == v.buf.as_ptr() + adv &*& + v.end == v.buf.as_ptr() + end_idx &*& + v.end != 0 &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr(), adv, _) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr() + end_idx, v.cap - end_idx, _); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))), + klong, + IntoIter_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)))(); + open sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + open IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)(); + assert (*l).alloc |-> ?a1; + close IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + close >.own(t, IntoIter:: { buf: v.buf, cap: v.cap, alloc: a1, ptr: v.ptr, end: v.end }); + close IntoIter_full_borrow_content::(t, l)(); + } { + close Ctx(); + close_full_borrow_strong_m( + klong, + IntoIter_full_borrow_content::(t, l), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))) + ); + full_borrow_split_m(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems))); + full_borrow_split_m(klong, IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + full_borrow_into_frac_m(klong, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + frac_borrow_mono(klong, k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len_nz, elems)); + } + } + close exists::>(v); + leak exists::>(v); + close exists::>(elems); + leak exists::>(elems); + close IntoIter_share_::(k, t, l, len_nz); + leak IntoIter_share_::(k, t, l, len_nz); + } + close IntoIter_share::(k, t, l); + leak IntoIter_share::(k, t, l); +} + +pred_ctor IntoIter_val_fbc(t: thread_id_t, l: *IntoIter, v: IntoIter, alloc_id: alloc_id_t, len: usize)() = + (*l).buf |-> v.buf &*& + (*l).cap |-> v.cap &*& + (*l).ptr |-> v.ptr &*& + (*l).end |-> v.end &*& + struct_IntoIter_padding::(l) &*& + (*l).alloc |-> ?a &*& + Allocator(t, a, alloc_id) &*& + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + if std::mem::size_of::() == 0 { + v.ptr == v.buf &*& + len == std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, ?elems) &*& + foreach(elems, own::(t)) + } else { + IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems) &*& + len == end_idx - adv + }; + +lem IntoIter_share_val_fbc(k: lifetime_t, t: thread_id_t, l: *IntoIter, v: IntoIter, alloc_id: alloc_id_t, len: usize) + nonghost_callers_only + req full_borrow(k, IntoIter_val_fbc::(t, l, v, alloc_id, len)) &*& [?q]lifetime_token(k); + ens [_]IntoIter_share_::(k, t, l, len) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong(k, IntoIter_val_fbc::(t, l, v, alloc_id, len), q); + open IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + std::alloc::Allocator_inv(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close IntoIter_shared_val::(l, v)(); + if std::mem::size_of::() == 0 { + assert array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, ?elems_z); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + v.ptr == v.buf &*& + len == std::num::wrapping_sub_usize(v.end as usize, v.ptr.as_ptr() as usize) &*& + array_at_lft(alloc_id.lft, v.ptr.as_ptr(), len, elems_z) &*& + foreach(elems_z, own::(t)); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)), + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + close IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)) + ); + full_borrow_split(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), IntoIter_shared_val::(l, v)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + } + } + close exists::>(v); + leak exists::>(v); + close IntoIter_share_::(k, t, l, len); + leak IntoIter_share_::(k, t, l, len); + } else { + open IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, ?adv, ?end_idx, ?elems); + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(len, v.cap, std::mem::size_of::()); + close IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + close sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)))(); + { + pred Ctx() = + v.buf.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(v.buf.as_ptr()) == true &*& + 0 <= (v.end as usize) &*& (v.end as usize) <= usize::MAX &*& pointer_within_limits(v.end) == true &*& + (v.end as pointer) == pointer_ctor((v.ptr.as_ptr() as pointer).provenance, v.end as usize, pointer_metadata_none) &*& + 0 <= adv &*& adv <= end_idx &*& end_idx <= v.cap &*& + len == end_idx - adv &*& + v.cap * std::mem::size_of::() <= isize::MAX &*& + (if v.cap == 0 { + true + } else { + Layout::new::().repeat(v.cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, v.buf.as_ptr() as *u8, allocLayout) + }) &*& + v.ptr.as_ptr() == v.buf.as_ptr() + adv &*& + v.end == v.buf.as_ptr() + end_idx &*& + v.end != 0 &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr(), adv, _) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, v.buf.as_ptr() + end_idx, v.cap - end_idx, _); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))), + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)))(); + open sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open IntoIter_shared_val::(l, v)(); + open IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + close IntoIter_non_zst_buf::(t, v.buf, v.cap, alloc_id, v.ptr, v.end, adv, end_idx, elems); + close IntoIter_val_fbc::(t, l, v, alloc_id, len)(); + } { + close Ctx(); + close_full_borrow_strong( + klong, + IntoIter_val_fbc::(t, l, v, alloc_id, len), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))) + ); + full_borrow_split(klong, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), sep(IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems))); + full_borrow_split(klong, IntoIter_shared_val::(l, v), IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + full_borrow_mono(klong, k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac(klong, IntoIter_shared_val::(l, v)); + frac_borrow_mono(klong, k, IntoIter_shared_val::(l, v)); + full_borrow_into_frac(klong, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + frac_borrow_mono(klong, k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + } + } + close exists::>(v); + leak exists::>(v); + close exists::>(elems); + leak exists::>(elems); + close IntoIter_share_::(k, t, l, len); + leak IntoIter_share_::(k, t, l, len); + } +} + +lem IntoIter_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Sync(typeid(IntoIter)) == true &*& + [_]IntoIter_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& + [_]IntoIter_share::(k, t1, l); +{ + open IntoIter_share::(k, t0, l); + open IntoIter_share_::(k, t0, l, ?len); + assume(is_Sync(typeid(A)) == true); + std::alloc::Allocator_sync::(t1); + close IntoIter_share_::(k, t1, l, len); + leak IntoIter_share_::(k, t1, l, len); + close IntoIter_share::(k, t1, l); + leak IntoIter_share::(k, t1, l); +} + +lem init_ref_IntoIter(p: *IntoIter) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + ref_init_perm(p, ?x) &*& [_]IntoIter_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& + [q]lifetime_token(k) &*& [_]IntoIter_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open IntoIter_share::(k, t, x); + open IntoIter_share_::(k, t, x, ?len); + assert [_]exists::>(?v); + open_ref_init_perm_IntoIter(p); + std::alloc::init_ref_Allocator_share_m(k, t, &(*p).alloc); + frac_borrow_sep(k, IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)); + let klong = open_frac_borrow_strong_m(k, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), q); + open [?f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + open [f]IntoIter_shared_val::(x, v)(); + open [f]ref_initialized_::(&(*p).alloc)(); + std::ptr::init_ref_NonNull(&(*p).buf, 1/2); + init_ref_readonly(&(*p).cap, 1/2); + std::ptr::init_ref_NonNull(&(*p).ptr, 1/2); + init_ref_readonly(&(*p).end, 1/2); + init_ref_padding_IntoIter(p, 1/2); + { + pred P() = ref_padding_initialized(p) &*& ref_initialized(&(*p).buf) &*& ref_initialized(&(*p).cap) &*& ref_initialized(&(*p).ptr) &*& ref_initialized(&(*p).end); + close [1 - f/2]P(); + close_ref_initialized_IntoIter(p); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*p).alloc) &*& + ref_padding_end_token(p, x, f/2) &*& [f/2]struct_IntoIter_padding::(x) &*& [1 - f/2]ref_padding_initialized(p) &*& + ref_end_token(&(*p).buf, &(*x).buf, f/2) &*& [f/2]((*x).buf |-> v.buf) &*& [1 - f/2]ref_initialized(&(*p).buf) &*& + ref_readonly_end_token(&(*p).cap, &(*x).cap, f/2) &*& [f/2]((*x).cap |-> v.cap) &*& [1 - f/2]ref_initialized(&(*p).cap) &*& + ref_end_token(&(*p).ptr, &(*x).ptr, f/2) &*& [f/2]((*x).ptr |-> v.ptr) &*& [1 - f/2]ref_initialized(&(*p).ptr) &*& + ref_readonly_end_token(&(*p).end, &(*x).end, f/2) &*& [f/2]((*x).end |-> v.end) &*& [1 - f/2]ref_initialized(&(*p).end); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))), + klong, + f, + sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)) + )() { + open scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + open sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + open ref_initialized_::>(p)(); + open IntoIter_shared_val::(p, v)(); + open_ref_initialized_IntoIter(p); + open Ctx(); + std::ptr::end_ref_NonNull(&(*p).buf); + end_ref_readonly(&(*p).cap); + std::ptr::end_ref_NonNull(&(*p).ptr); + end_ref_readonly(&(*p).end); + end_ref_padding_IntoIter(p); + close [f]IntoIter_shared_val::(x, v)(); + close [f]ref_initialized_::(&(*p).alloc)(); + close [f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(p)(); + close [f/2]IntoIter_shared_val::(p, v)(); + close [f/2]sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + close scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))); + frac_borrow_split(k, ref_initialized_(p), IntoIter_shared_val::(p, v)); + } + } + close IntoIter_share_::(k, t, p, len); + leak IntoIter_share_::(k, t, p, len); + close IntoIter_share::(k, t, p); + leak IntoIter_share::(k, t, p); +} + +lem init_ref_IntoIter_share_(p: *IntoIter) + nonghost_callers_only + req ref_init_perm(p, ?x) &*& [_]IntoIter_share_::(?k, ?t, x, ?len) &*& [?q]lifetime_token(k); + ens [q]lifetime_token(k) &*& [_]IntoIter_share_::(k, t, p, len) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open IntoIter_share_::(k, t, x, len); + assert [_]exists::>(?v); + open_ref_init_perm_IntoIter(p); + std::alloc::init_ref_Allocator_share(k, t, &(*p).alloc); + frac_borrow_sep(k, IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)); + let klong = open_frac_borrow_strong(k, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), q); + open [?f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + open [f]IntoIter_shared_val::(x, v)(); + open [f]ref_initialized_::(&(*p).alloc)(); + std::ptr::init_ref_NonNull(&(*p).buf, 1/2); + init_ref_readonly(&(*p).cap, 1/2); + std::ptr::init_ref_NonNull(&(*p).ptr, 1/2); + init_ref_readonly(&(*p).end, 1/2); + init_ref_padding_IntoIter(p, 1/2); + { + pred P() = ref_padding_initialized(p) &*& ref_initialized(&(*p).buf) &*& ref_initialized(&(*p).cap) &*& ref_initialized(&(*p).ptr) &*& ref_initialized(&(*p).end); + close [1 - f/2]P(); + close_ref_initialized_IntoIter(p); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*p).alloc) &*& + ref_padding_end_token(p, x, f/2) &*& [f/2]struct_IntoIter_padding::(x) &*& [1 - f/2]ref_padding_initialized(p) &*& + ref_end_token(&(*p).buf, &(*x).buf, f/2) &*& [f/2]((*x).buf |-> v.buf) &*& [1 - f/2]ref_initialized(&(*p).buf) &*& + ref_readonly_end_token(&(*p).cap, &(*x).cap, f/2) &*& [f/2]((*x).cap |-> v.cap) &*& [1 - f/2]ref_initialized(&(*p).cap) &*& + ref_end_token(&(*p).ptr, &(*x).ptr, f/2) &*& [f/2]((*x).ptr |-> v.ptr) &*& [1 - f/2]ref_initialized(&(*p).ptr) &*& + ref_readonly_end_token(&(*p).end, &(*x).end, f/2) &*& [f/2]((*x).end |-> v.end) &*& [1 - f/2]ref_initialized(&(*p).end); + produce_lem_ptr_chunk frac_borrow_convert_strong( + Ctx, + scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))), + klong, + f, + sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)) + )() { + open scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + open sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + open ref_initialized_::>(p)(); + open IntoIter_shared_val::(p, v)(); + open_ref_initialized_IntoIter(p); + open Ctx(); + std::ptr::end_ref_NonNull(&(*p).buf); + end_ref_readonly(&(*p).cap); + std::ptr::end_ref_NonNull(&(*p).ptr); + end_ref_readonly(&(*p).end); + end_ref_padding_IntoIter(p); + close [f]IntoIter_shared_val::(x, v)(); + close [f]ref_initialized_::(&(*p).alloc)(); + close [f]sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(p)(); + close [f/2]IntoIter_shared_val::(p, v)(); + close [f/2]sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))(); + close scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))(); + close_frac_borrow_strong(klong, sep_(IntoIter_shared_val::(x, v), ref_initialized_(&(*p).alloc)), scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + full_borrow_into_frac(k, scaledp(f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(p), IntoIter_shared_val::(p, v))); + frac_borrow_split(k, ref_initialized_(p), IntoIter_shared_val::(p, v)); + } + } + close IntoIter_share_::(k, t, p, len); + leak IntoIter_share_::(k, t, p, len); +} + +@*/ + +// 1-line wrappers for core::mem / core::ptr primitives absent from VeriFast 26.10's std/lib.rsspec. +// Every wrapper is automatically inlined by `refinement-checker` against original/into_iter.rs. +unsafe fn manually_drop_take__VeriFast_wrapper(slot: &mut ManuallyDrop) -> T +//@ req *slot |-> ?v; +//@ ens *slot |-?-> _ &*& result == v; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { ManuallyDrop::take(slot) } +} + +fn const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(p: *const T) -> *const T +//@ req true; +//@ ens (result as pointer) == pointer_ctor((p as pointer).provenance, std::num::wrapping_sub_usize(p as usize, 1), (p as pointer).metadata) &*& 0 <= (result as usize) &*& (result as usize) <= usize::MAX; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.wrapping_byte_sub(1) +} + +fn const_ptr_cast_mut__VeriFast_wrapper(p: *const T) -> *mut T +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.cast_mut() +} + +fn const_ptr_cast_t_mut__VeriFast_wrapper(p: *const T) -> *mut T +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.cast::().cast_mut() +} + +unsafe fn ptr_ne_end__VeriFast_wrapper(ptr: &NonNull, end: &*const T) -> bool +//@ req [?f1](*ptr |-> ?p) &*& [?f2](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true &*& (e as pointer) == pointer_ctor((p.as_ptr() as pointer).provenance, e as usize, pointer_metadata_none); +//@ ens [f1](*ptr |-> p) &*& [f2](*end |-> e) &*& result == (p.as_ptr() != e); +//@ on_unwind_ens false; +//@ assume_correct +{ + *ptr != unsafe { *((end as *const *const T) as *const NonNull) } +} + +unsafe fn ptr_eq_end__VeriFast_wrapper(ptr: &NonNull, end: &*const T) -> bool +//@ req [?f1](*ptr |-> ?p) &*& [?f2](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true &*& (e as pointer) == pointer_ctor((p.as_ptr() as pointer).provenance, e as usize, pointer_metadata_none); +//@ ens [f1](*ptr |-> p) &*& [f2](*end |-> e) &*& result == (p.as_ptr() == e); +//@ on_unwind_ens false; +//@ assume_correct +{ + *ptr == unsafe { *((end as *const *const T) as *const NonNull) } +} + +/*@ +pred LiveSlot(p: *T, k: lifetime_t, q: real, f: real, ov: option) = + [q]lifetime_token(k) &*& + match ov { + some(v) => [f]points_to_at_lft::(k, p, v), + none => [f]points_to_at_lft_::(k, p, _) + }; + +pred LiveRange(p: *T, n: usize, k: lifetime_t, q: real, f: real, elems: list) = + if n == 0 { + true + } else { + [q]lifetime_token(k) &*& [f]array_at_lft::(k, p, n, elems) + }; +@*/ + +unsafe fn non_null_add_1__VeriFast_wrapper(p: NonNull) -> NonNull +/*@ +req std::mem::size_of::() > 0 &*& std::mem::size_of::() <= isize::MAX &*& + pointer_within_limits(p.as_ptr() + 1) == true &*& (p.as_ptr() + 1) != 0 &*& + LiveSlot::(p.as_ptr(), ?k, ?q, ?f, ?ov); +@*/ +/*@ +ens LiveSlot::(p.as_ptr(), k, q, f, ov) &*& + result.as_ptr() == p.as_ptr() + 1; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.add(1) } +} + +unsafe fn exact_size_len__VeriFast_wrapper<'a, 'b, T, A: Allocator>(it: &'a &'b mut IntoIter) -> usize +/*@ +req thread_token(?t) &*& + [?f]points_to::<&'b mut IntoIter>(it, ?p) &*& + [_]IntoIter_share_::(?k, t, p, ?len) &*& + [?q]lifetime_token(k); +@*/ +/*@ +ens thread_token(t) &*& + [f]points_to::<&'b mut IntoIter>(it, p) &*& + [q]lifetime_token(k) &*& + result == len; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + it.len() +} + +fn usize_min__VeriFast_wrapper(a: usize, b: usize) -> usize +//@ req true; +//@ ens result == (if a <= b { a } else { b }); +//@ on_unwind_ens false; +//@ assume_correct +{ + a.min(b) +} + +unsafe fn non_null_dangling__VeriFast_wrapper() -> NonNull +//@ req true; +//@ ens result.as_ptr() as usize == std::mem::align_of::() &*& result.as_ptr() as usize % std::mem::align_of::() == 0 &*& pointer_within_limits(result.as_ptr()) == true; +//@ on_unwind_ens false; +//@ assume_correct +{ + ptr::NonNull::::dangling() +} + +fn const_ptr_wrapping_byte_sub__VeriFast_wrapper(p: *const T, count: usize) -> *const T +//@ req true; +//@ ens (result as pointer) == pointer_ctor((p as pointer).provenance, std::num::wrapping_sub_usize(p as usize, count), (p as pointer).metadata) &*& 0 <= (result as usize) &*& (result as usize) <= usize::MAX; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.wrapping_byte_sub(count) +} + +unsafe fn non_null_add__VeriFast_wrapper(p: NonNull, count: usize) -> NonNull +/*@ +req std::mem::size_of::() > 0 &*& 0 <= count &*& count * std::mem::size_of::() <= isize::MAX &*& + pointer_within_limits(p.as_ptr() + count) == true &*& (p.as_ptr() + count) != 0 &*& + LiveRange::(p.as_ptr(), count, ?k, ?q, ?f, ?elems); +@*/ +/*@ +ens LiveRange::(p.as_ptr(), count, k, q, f, elems) &*& + result.as_ptr() == p.as_ptr() + count; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.add(count) } +} + +unsafe fn non_zero_rem__VeriFast_wrapper(rem: usize) -> Result<(), NonZero> +//@ req thread_token(?t); +//@ ens thread_token(t) &*& >>.own(t, result); +//@ on_unwind_ens false; +//@ assume_correct +{ + NonZero::new(rem).map_or(Ok(()), Err) +} + +fn call_fold__VeriFast_wrapper B>(f: &mut F, accum: B, item: T) -> B +//@ req thread_token(?t) &*& *f |-> ?f0 &*& .own(t, f0) &*& .own(t, accum) &*& .own(t, item); +//@ ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& .own(t, result); +//@ on_unwind_ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1); +//@ assume_correct +{ + f(accum, item) +} + +fn call_try_fn__VeriFast_wrapper R>(f: &mut F, accum: B, item: T) -> R +//@ req thread_token(?t) &*& *f |-> ?f0 &*& .own(t, f0) &*& .own(t, accum) &*& .own(t, item); +//@ ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& .own(t, result); +//@ on_unwind_ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1); +//@ assume_correct +{ + f(accum, item) +} + +/*@ +pred TryRes(t: thread_id_t, r_typeid: *_, res: Res); +@*/ + +unsafe fn try_branch__VeriFast_wrapper>(r: R) -> core::ops::ControlFlow +//@ req thread_token(?t) &*& .own(t, r); +/*@ +ens thread_token(t) &*& + match result { + ControlFlow::Continue(b) => .own(t, b), + ControlFlow::Break(res) => TryRes(t, typeid(R), res) + }; +@*/ +//@ assume_correct +{ + core::ops::Try::branch(r) +} + +unsafe fn try_from_residual__VeriFast_wrapper>(res: R::Residual) -> R +//@ req thread_token(?t) &*& TryRes(t, typeid(R), res); +//@ ens thread_token(t) &*& .own(t, result); +//@ assume_correct +{ + core::ops::FromResidual::from_residual(res) +} + +fn try_from_output__VeriFast_wrapper>(b: B) -> R +//@ req thread_token(?t) &*& .own(t, b); +//@ ens thread_token(t) &*& .own(t, result); +//@ assume_correct +{ + R::from_output(b) +} + +fn const_ptr_addr__VeriFast_wrapper(p: *const T) -> usize +//@ req true; +//@ ens result == p as usize; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.addr() +} + +fn mut_ptr_addr__VeriFast_wrapper(p: *mut T) -> usize +//@ req true; +//@ ens result == p as usize; +//@ on_unwind_ens false; +//@ assume_correct +{ + p.addr() +} + +unsafe fn non_null_from_end__VeriFast_wrapper(end: &*const T) -> NonNull +//@ req [?f](*end |-> ?e) &*& e != 0 &*& pointer_within_limits(e) == true; +//@ ens [f](*end |-> e) &*& result.as_ptr() == e; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { *((end as *const *const T) as *const NonNull) } +} + +unsafe fn non_null_offset_from_unsigned__VeriFast_wrapper(end: NonNull, ptr: NonNull) -> usize +/*@ +req std::mem::size_of::() > 0 &*& + LiveRange::(ptr.as_ptr(), ?len, ?k, ?q, ?f, ?elems) &*& + end.as_ptr() == ptr.as_ptr() + len &*& + 0 <= len &*& len * std::mem::size_of::() <= isize::MAX; +@*/ +/*@ +ens LiveRange::(ptr.as_ptr(), len, k, q, f, elems) &*& + result == len; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { end.offset_from_unsigned(ptr) } +} + +// Verified check that `core::iter::ExactSizeIterator::len`'s default implementation +// (`let (lower, upper) = self.size_hint(); assert_eq!(upper, Some(lower)); lower`) +// computes the exact remaining length `len` exposed in `IntoIter_share_`. +fn verify_exact_size_len_from_size_hint__VeriFast_wrapper(it: &IntoIter) -> usize +//@ req thread_token(?t) &*& [?q]lifetime_token(?k) &*& [_]IntoIter_share_::(k, t, it, ?len); +//@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result == len; +/*@ +safety_proof { + open >.share(?k, _t, it); + call(); +} +@*/ +{ + //@ let it_r = precreate_ref(it); + //@ init_ref_IntoIter_share_(it_r); + //@ open_frac_borrow(k, ref_initialized_(it_r), q/2); + //@ open [?f]ref_initialized_::>(it_r)(); + let (lower, upper) = unsafe { &*(it as *const IntoIter) }.size_hint(); + //@ close [f]ref_initialized_::>(it_r)(); + //@ close_frac_borrow(f, ref_initialized_(it_r)); + //@ assert upper == Some(len); + lower +} + +unsafe fn non_null_read__VeriFast_wrapper(p: NonNull) -> T +//@ req *(p.as_ptr()) |-> ?v &*& p.as_ptr() as usize % std::mem::align_of::() == 0; +//@ ens *(p.as_ptr()) |-?-> _ &*& result == v; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { p.read() } +} + +// Manually mirroring what `Vec` has, +// because otherwise we get `T: RefUnwindSafe` from `NonNull`. +#[stable(feature = "catch_unwind", since = "1.9.0")] +impl UnwindSafe for IntoIter {} + +#[stable(feature = "vec_intoiter_debug", since = "1.13.0")] +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("IntoIter").field(&self.as_slice()).finish() + } +} + +impl IntoIter { + /// Returns the remaining items of this iterator as a slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// let _ = into_iter.next().unwrap(); + /// assert_eq!(into_iter.as_slice(), &['b', 'c']); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_slice(&self) -> &[T] { + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len()) } + } + + /// Returns the remaining items of this iterator as a mutable slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// into_iter.as_mut_slice()[2] = 'z'; + /// assert_eq!(into_iter.next().unwrap(), 'a'); + /// assert_eq!(into_iter.next().unwrap(), 'b'); + /// assert_eq!(into_iter.next().unwrap(), 'z'); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_mut_slice(&mut self) -> &mut [T] { + // ignore-tidy-undocumented-unsafe + unsafe { &mut *self.as_raw_mut_slice() } + } + + /// Returns a reference to the underlying allocator. + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] + #[inline] + pub fn allocator(&self) -> &A { + &self.alloc + } + + fn as_raw_mut_slice(&mut self) -> *mut [T] { + self.ptr.as_ptr().cast_slice(self.len()) + } + + /// Drops remaining elements and relinquishes the backing allocation. + /// + /// This method guarantees it won't panic before relinquishing the backing + /// allocation. + /// + /// This is roughly equivalent to the following, but more efficient + /// + /// ``` + /// # let mut vec = Vec::::with_capacity(10); + /// # let ptr = vec.as_mut_ptr(); + /// # let mut into_iter = vec.into_iter(); + /// let mut into_iter = std::mem::replace(&mut into_iter, Vec::new().into_iter()); + /// (&mut into_iter).for_each(drop); + /// std::mem::forget(into_iter); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # drop(unsafe { Vec::::from_raw_parts(ptr, 0, 10) }); + /// ``` + /// + /// This method is used by in-place iteration, refer to the vec::in_place_collect + /// documentation for an overview. + #[cfg(not(no_global_oom_handling))] + pub(super) fn forget_allocation_drop_remaining(&mut self) { + let remaining = self.as_raw_mut_slice(); + + // overwrite the individual fields instead of creating a new + // struct and then overwriting &mut self. + // this creates less assembly + self.cap = 0; + self.buf = RawVec::new().non_null(); + self.ptr = self.buf; + self.end = self.buf.as_ptr(); + + // Dropping the remaining elements can panic, so this needs to be + // done only after updating the other fields. + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(remaining); + } + } + + /// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed. + /// + /// This method does not consume `self`, and leaves deallocation to `impl Drop for IntoIter`. + /// If consuming `self` is possible, consider calling + /// [`Self::forget_remaining_elements_and_dealloc()`] instead. + pub(crate) fn forget_remaining_elements(&mut self) + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& self1.end == self1.ptr.as_ptr(); + { + //@ open_points_to(self); + //@ open >.own(t, self0); + // For the ZST case, it is crucial that we mutate `end` here, not `ptr`. + // `ptr` must stay aligned, while `end` may be unaligned. + self.end = self.ptr.as_ptr(); + /*@ { + std::ptr::NonNull_Sized_as_ptr(self0.ptr); + if std::mem::size_of::() == 0 { + assert array_at_lft(?k, self0.ptr.as_ptr(), ?len, ?elems); + leak foreach(elems, own::(t)); + leak array_at_lft(k, self0.ptr.as_ptr(), len, elems); + close array_at_lft::(k, self0.ptr.as_ptr(), 0, nil); + close foreach(nil, own::(t)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, ?alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + leak foreach(elems, own::(t)); + array_at_lft_to_array_at_lft_::(self0.ptr.as_ptr()); + array_at_lft__join::(self0.buf.as_ptr() + adv); + close array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), 0, nil); + close foreach(nil, own::(t)); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.ptr.as_ptr(), adv, adv, nil); + } + close_points_to(self); + close >.own(t, *self); + } @*/ + } + + /// Forgets to Drop the remaining elements and frees the backing allocation. + /// Consuming version of [`Self::forget_remaining_elements()`]. + /// + /// This can be used in place of `drop(self)` when `self` is known to be exhausted, + /// to avoid producing a needless `drop_in_place::<[T]>()`. + #[inline] + pub(crate) fn forget_remaining_elements_and_dealloc(self) + //@ req thread_token(?t) &*& t == currentThread &*& >.own(t, self); + //@ ens thread_token(t); + { + //@ IntoIter_own_to_raw_buf::(t, self); + let mut this = ManuallyDrop::new(self); + // SAFETY: `this` is in ManuallyDrop, so it will not be double-freed. + unsafe { + this.dealloc_only(); + } + } + + /// Frees the allocation, without checking or dropping anything else. + /// + /// The safe version of this method is [`Self::forget_remaining_elements_and_dealloc()`]. + /// This function exists only to share code between that method and the `impl Drop`. + /// + /// # Safety + /// + /// This function must only be called with an [`IntoIter`] that is not going to be dropped + /// or otherwise used in any way, either because it is being forgotten or because its `Drop` + /// is already executing; otherwise a double-free will occur, and possibly a read from freed + /// memory if there are any remaining elements. + #[inline] + unsafe fn dealloc_only(&mut self) + //@ req thread_token(?t) &*& t == currentThread &*& *self |-> ?self0 &*& IntoIter_raw_buf::(t, self0); + //@ ens thread_token(t) &*& (*self).buf |-> _ &*& (*self).cap |-> _ &*& (*self).alloc |-?-> _ &*& (*self).ptr |-> _ &*& (*self).end |-> _ &*& struct_IntoIter_padding(self); + { + //@ open_points_to(self); + //@ open IntoIter_raw_buf::(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + // SAFETY: our caller promises not to touch `*self` again. + let alloc = unsafe { manually_drop_take__VeriFast_wrapper(&mut self.alloc) }; + /*@ + if std::mem::size_of::() != 0 { + std::alloc::Layout_inv(Layout::new::()); + if self0.cap != 0 { raw_vec::mul_zero(self0.cap, std::mem::size_of::()); } + } + @*/ + // SAFETY: We're using this to deallocate a preexisting `RawVec`. + { + let mut _rv = unsafe { RawVec::from_nonnull_in(self.buf, self.cap, alloc) }; + /*@ { + assert RawVec(t, ?rv_val, alloc_id, self0.buf.as_ptr(), ?cap_); + if std::mem::size_of::() == 0 { + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() as *u8, 0, nil); + u8s_at_lft__to_array_at_lft_::(self0.buf.as_ptr(), cap_); + } + RawVec_to_own(rv_val); + close_points_to(&_rv); + } @*/ + } + //@ assert points_to_::>(?rv_p, _); + //@ open_points_to_(rv_p); + //@ open_points_to_(&(*rv_p).inner); + } + + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn into_vecdeque(self) -> VecDeque { + // Keep our `Drop` impl from dropping the elements and the allocator + let mut this = ManuallyDrop::new(self); + + let buf = this.buf.as_ptr(); + let initialized = if T::IS_ZST || this.len() == 0 { + // All the pointers are the same for ZSTs, so it's fine to + // say that they're all at the beginning of the "allocation". + // For non-ZSTs, we have length 0, so we can choose the (empty) + // range to be at the start of the buffer. + // + // Due to `0` ≤ `this.len()` ≤ `this.cap`, the range is well-formed, + // and due to the argument above it spans exactly the elements of + // this iterator. Because `init.start` = `0`, it follows that either + // `init.start` < `cap` or `cap` = `init.start` = `0`; thus the range + // satisfies the requirements of `from_contiguous_raw_parts_in`. + 0..this.len() + } else { + // SAFETY: `this.ptr` and `this.end` are created via offsets of `this.buf`, + // so they point to the same allocation. We have `this.buf` ≤ `this.ptr` ≤ `this.end`, + // so this cannot wrap, and will produce a well-formed range that spans exactly + // the elements of this iterator. + // + // Additionally, due to `end ≤ buf + cap`, we have `init.start` ≤ `init.end` ≤ `cap`. + // Due to the length check above, `init.start < cap`, so the range satisfies the + // requirements of `from_contiguous_raw_parts_in`. + unsafe { this.ptr.offset_from_unsigned(this.buf)..this.end.offset_from_unsigned(buf) } + }; + + let cap = this.cap; + // SAFETY: `this` is forgotten afterwards, so we can move out the allocator. + let alloc = unsafe { ManuallyDrop::take(&mut this.alloc) }; + + // SAFETY: This allocation originally came from a `Vec`, so it satisfies all + // requirements for the `buf` pointer with capacity `cap` allocated in `alloc`. + // Correctness of `initialized` was shown above. + unsafe { VecDeque::from_contiguous_raw_parts_in(buf, initialized, cap, alloc) } + } +} + +#[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")] +impl AsRef<[T]> for IntoIter { + fn as_ref(&self) -> &[T] { + self.as_slice() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for IntoIter {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for IntoIter {} + +// Loop-invariant predicates for `IntoIter::fold` and `IntoIter::try_fold`. +// Marked `#[inline(always)]` and written with pure intrinsics and `const { ... }` +// blocks rather than method calls (e.g. `NonNull::as_ptr` / `pointer::addr` / +// non-const `mem::size_of`) so Kani's loop-contract lowering evaluates them +// inline as side-effect-free CBMC expressions without emitting nondeterministic +// helper calls (https://github.com/model-checking/kani/issues/4796). +// `self.alloc` is untouched by either loop and is preserved across loop +// contracts (verified with both `TrackAlloc` and non-ZST `StatefulAlloc`). +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, and `usize` have identical layout (thin pointer width); + // these casts are side-effect-free re-interpretations for CBMC's loop-invariant evaluator. + let (ptr_p, eptr_p, buf_p, ebuf_p, ptr_a, eptr_a, end_a, eend_a): ( + *const T, + *const T, + *const T, + *const T, + usize, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + core::intrinsics::transmute_unchecked(entry_end), + ) + }; + ptr_p == eptr_p + && buf_p == ebuf_p + && cap == entry_cap + && core::intrinsics::wrapping_sub(end_a, ptr_a) + <= core::intrinsics::wrapping_sub(eend_a, eptr_a) +} + +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_non_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, `*const u8`, and `usize` have identical thin-pointer + // layout; used to avoid method calls in CBMC loop-contract predicates (kani#4796). + let (buf_p, ebuf_p, ptr_p, eptr_u8, ptr_a, eptr_a, end_a): ( + *const T, + *const T, + *const T, + *const u8, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + ) + }; + let diff = core::intrinsics::wrapping_sub(ptr_a, eptr_a); + let span = core::intrinsics::wrapping_sub(end_a, eptr_a); + let sz = const { core::mem::size_of::() }; + let aligned = if const { core::mem::size_of::().is_power_of_two() } { + (diff & core::intrinsics::wrapping_sub(sz, 1)) == 0 + } else { + // Exact divisibility `diff % sz == 0` for any non-power-of-two `sz > 0` without a + // 64-bit integer division circuit: write `sz = odd * 2^tz` and compute the modular + // multiplicative inverse `odd_inv` (`odd * odd_inv == 1 mod 2^BITS`) at const time. + // Then `sz | diff` iff `2^tz | diff` and `(diff >> tz) * odd_inv <= usize::MAX / sz`. + let (tz, odd_inv, max_q) = const { + let s = core::mem::size_of::(); + if s == 0 { + (0u32, 1usize, 0usize) + } else { + let tz = s.trailing_zeros(); + let odd = s >> tz; + let mut inv: usize = 1; + let mut i = 0; + while i < 6 { + inv = inv.wrapping_mul(2usize.wrapping_sub(odd.wrapping_mul(inv))); + i += 1; + } + assert!(odd.wrapping_mul(inv) == 1); + (tz, inv, usize::MAX / s) + } + }; + let low_mask = core::intrinsics::wrapping_sub(1usize << tz, 1); + (diff & low_mask) == 0 && core::intrinsics::wrapping_mul(diff >> tz, odd_inv) <= max_q + }; + // SAFETY: `arith_offset` is wrapping (non-UB) pointer arithmetic; short-circuiting after + // `diff <= span && aligned` additionally guarantees `diff` stays within `[entry_ptr, end]`. + buf_p == ebuf_p + && cap == entry_cap + && end == entry_end + && diff <= span + && aligned + && ptr_p == unsafe { core::intrinsics::arith_offset(eptr_u8, diff as isize) as *const T } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Iterator for IntoIter { + type Item = T; + + #[inline] + fn next(&mut self) -> Option + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + //@ open_points_to(self); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(self0.ptr); + let ptr = if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut T { + /*@ { + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // `ptr` has to stay where it is to remain aligned, so we reduce the length by 1 by + // reducing the `end`. + //@ wrapping_sub_usize_zero(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(self0.end as usize, self0.ptr.as_ptr() as usize); + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + self.ptr + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let is_eq = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + if is_eq { + /*@ { + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv, end_idx, elems); + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + let old = self.ptr; + // ignore-tidy-undocumented-unsafe + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(1, self0.cap, std::mem::size_of::()); + //@ open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), end_idx - adv, elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?x0); + //@ points_to_at_lft_inv(self0.ptr.as_ptr()); + //@ let q_add = lifetime_token_trade(flft, 1/4, alloc_id.lft); + //@ close LiveSlot::(self0.ptr.as_ptr(), alloc_id.lft, q_add, 1, some(x0)); + self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(old) }; + //@ open LiveSlot::(self0.ptr.as_ptr(), alloc_id.lft, q_add, 1, some(x0)); + //@ lifetime_token_trade_back(q_add, alloc_id.lft); + old + }; + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + open foreach(elems_z, own::(t)); + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xz); + open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + open own::(t)(xz); + } else { + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xnz); + open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + open own::(t)(xnz); + } + } @*/ + // ignore-tidy-undocumented-unsafe + let res = Some(unsafe { non_null_read__VeriFast_wrapper(ptr) }); + /*@ { + close_points_to_at_lft_(self0.ptr.as_ptr()); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + if std::mem::size_of::() == 0 { + leak points_to_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), _); + } else { + // Re-pack consumed prefix [0..adv+1) + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv0, _); + assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + 1, ?rem0, ?elems_rest); + close array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr() + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr(), 1, _); + array_at_lft__join::(self0.buf.as_ptr()); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, (*self).ptr, self0.end, adv0 + 1, adv0 + 1 + rem0, elems_rest); + } + close_points_to(self); + close >.own(t, *self); + close >.own(t, res); + } @*/ + res + } + + #[inline] + fn size_hint(&self) -> (usize, Option) + //@ req thread_token(?t) &*& [_]IntoIter_share_::(?k, t, self, ?len) &*& [?q]lifetime_token(k); + //@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result.0 == len &*& result.1 == Some(len); + /*@ + safety_proof { + open >.share(?k, _t, self); + let r = call(); + close usize_own(_t, r.0); + close >.own(_t, r.1); + close usize_own(_t, r.0); + tuple_ext::close_tuple_2_own::>(_t, r); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ open IntoIter_share_::(k, t, self, len); + //@ assert [_]std::alloc::Allocator_share(k, t, &(*self).alloc, ?alloc_id); + //@ assert [_]exists::>(?v); + //@ open_frac_borrow(k, IntoIter_shared_val::(self, v), q/2); + //@ open [?f]IntoIter_shared_val::(self, v)(); + let exact = if T::IS_ZST { + let end_a = const_ptr_addr__VeriFast_wrapper(self.end); + let ptr_a = mut_ptr_addr__VeriFast_wrapper(self.ptr.as_ptr()); + end_a.wrapping_sub(ptr_a) + } else { + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + // ignore-tidy-undocumented-unsafe + let end_nn = unsafe { non_null_from_end__VeriFast_wrapper(&self.end) }; + //@ end_ref_readonly(end_r); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ assert [_]exists::>(?elems); + //@ open_frac_borrow(k, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems), q/2); + //@ open [?fr]IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close LiveRange::(v.ptr.as_ptr(), len, alloc_id.lft, q_alloc, fr, elems); + let d = unsafe { non_null_offset_from_unsigned__VeriFast_wrapper(end_nn, self.ptr) }; + //@ open LiveRange::(v.ptr.as_ptr(), len, alloc_id.lft, q_alloc, fr, elems); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ close [fr]IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)(); + //@ close_frac_borrow(fr, IntoIter_shared_range::(alloc_id.lft, v.ptr.as_ptr(), len, elems)); + d + }; + //@ close [f]IntoIter_shared_val::(self, v)(); + //@ close_frac_borrow(f, IntoIter_shared_val::(self, v)); + (exact, Some(exact)) + } + + #[inline] + fn advance_by<'s>(/*@~mut@*/ self: &'s mut Self, n: usize) -> Result<(), NonZero> + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >>.own(t, result); + /*@ + safety_proof { + assert [?q]lifetime_token('s); + open_full_borrow(q, 's, (>.full_borrow_content)(_t, self)); + open_full_borrow_content::>(_t, self); + let r = call(); + close_full_borrow_content::>(_t, self); + close_full_borrow((>.full_borrow_content)(_t, self)); + leak full_borrow('s, (>.full_borrow_content)(_t, self)); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ let self_p0 = self; + //@ open_points_to(self_p0); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + close exists::(std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv0, ?end0, ?elems0); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv0, end0, elems0); + close exists::(end0 - adv0); + } + } @*/ + //@ open exists::(?len0); + //@ let k_len = begin_lifetime(); + //@ close IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + //@ borrow(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ IntoIter_share_val_fbc::(k_len, t, self_p0, self0, alloc_id, len0); + let cur_len; + unsafe { + //@ let_lft 'a = flft; + //@ let self_r = precreate_ref(&self); + //@ init_ref_readonly(self_r, 1/2); + cur_len = exact_size_len__VeriFast_wrapper/*@::@*/(&self); + //@ end_ref_readonly(self_r); + } + //@ end_lifetime(k_len); + //@ borrow_end(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ open IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + let step_size = usize_min__VeriFast_wrapper(cur_len, n); + let to_drop = self.ptr.as_ptr().cast_slice(step_size); + if T::IS_ZST { + // See `next` for why we sub `end` here. + //@ wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + self.end = const_ptr_wrapping_byte_sub__VeriFast_wrapper(self.end, step_size); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize), ?elems_z); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems_z, own::(t), step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems_z)); + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(step_size, self0.cap, std::mem::size_of::()); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems, own::(t), step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems)); + //@ if step_size == end_idx - adv { assert self0.ptr.as_ptr() + step_size == self0.end; } else { assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, ?rest_e); open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, rest_e); assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr() + step_size, ?xv); let q_nz = lifetime_token_trade(flft, 1/4, alloc_id.lft); open_points_to_at_lft(self0.ptr.as_ptr() + step_size, q_nz/2); points_to_limits(self0.ptr.as_ptr() + step_size); close_points_to_at_lft(self0.ptr.as_ptr() + step_size); lifetime_token_trade_back(q_nz, alloc_id.lft); close array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + step_size, end_idx - adv - step_size, rest_e); } + //@ let q_add = lifetime_token_trade(flft, 1/4, alloc_id.lft); + //@ close LiveRange::(self0.ptr.as_ptr(), step_size, alloc_id.lft, q_add, 1, take(step_size, elems)); + // SAFETY: the min() above ensures that step_size is in bounds + self.ptr = unsafe { non_null_add__VeriFast_wrapper(self.ptr, step_size) }; + //@ open LiveRange::(self0.ptr.as_ptr(), step_size, alloc_id.lft, q_add, 1, take(step_size, elems)); + //@ lifetime_token_trade_back(q_add, alloc_id.lft); + } + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close_points_to_slice_at_lft(to_drop); + //@ open_points_to_at_lft(to_drop, q_alloc/2); + // SAFETY: the min() above ensures that step_size is in bounds + unsafe { + ptr::drop_in_place(to_drop); + } + //@ close_points_to_at_lft_(to_drop); + //@ open_points_to_slice_at_lft_(to_drop); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + let self_p = self; + if std::mem::size_of::() == 0 { + leak array_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), step_size, _); + } else { + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv1, _); + if step_size == 0 { + open array_at_lft_::(alloc_id.lft, self0.ptr.as_ptr(), 0, _); + } else { + array_at_lft__join::(self0.buf.as_ptr()); + } + assert (*self_p).ptr |-> ?new_ptr &*& array_at_lft(alloc_id.lft, new_ptr.as_ptr(), ?rem1, ?elems1); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, new_ptr, self0.end, adv1 + step_size, adv1 + step_size + rem1, elems1); + } + close_points_to(self_p); + assert *self_p |-> ?self1; + close >.own(t, self1); + } @*/ + unsafe { non_zero_rem__VeriFast_wrapper(n - step_size) } + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + #[inline] + fn last(mut self) -> Option { + self.next_back() + } + + #[inline] + fn next_chunk(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { raw_ary.transpose().assume_init() }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available and we + // just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, N); + self.ptr = self.ptr.add(N); + Ok(raw_ary.transpose().assume_init()) + } + } + + #[inline] + fn fold(mut self, mut accum: B, mut f: F) -> B + where + F: FnMut(B, T) -> B, + //@ req thread_token(?t) &*& t == currentThread &*& >.own(t, self) &*& .own(t, accum) &*& .own(t, f); + //@ ens thread_token(t) &*& .own(t, result); + { + //@ assert lifetime_token(?flft); + //@ close_points_to(&self); + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *(&self) |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(&self); + let ptr_raw = self.ptr.as_ptr(); + let end_mut = const_ptr_cast_mut__VeriFast_wrapper(self.end); + let cont = ptr_raw != end_mut; + //@ close_points_to(&self); + cont + } { + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(cur_it.ptr); + //@ wrapping_sub_usize_zero(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ let old_len = std::num::wrapping_sub_usize(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), old_len, ?elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ leak points_to_at_lft_(alloc_id.lft, cur_it.ptr.as_ptr(), _); + // See `next` for why we subtract from `end` here. + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + //@ close_points_to(&self); + //@ close >.own(t, *(&self)); + accum = call_fold__VeriFast_wrapper(&mut f, accum, tmp); + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *(&self) |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id_c); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, ?adv_c, ?end_idx_c, ?elems_c); + //@ let ptr_r = precreate_ref(&self.ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&self.end); + //@ init_ref_readonly(end_r, 1/2); + let is_ne = unsafe { ptr_ne_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + //@ close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, adv_c, end_idx_c, elems_c); + //@ close_points_to(&self); + //@ close >.own(t, *(&self)); + is_ne + } { + //@ open_points_to(&self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, cur_it.ptr, cur_it.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(1, cur_it.cap, std::mem::size_of::()); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), end_idx - adv, elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ points_to_at_lft_inv(cur_it.ptr.as_ptr()); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ close LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(self.ptr) }; + //@ open LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr() + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr(), 1, _); + array_at_lft__join::(cur_it.buf.as_ptr()); + assert array_at_lft(alloc_id.lft, cur_it.ptr.as_ptr() + 1, end_idx - adv - 1, ?elems_rest); + close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, self.ptr, cur_it.end, adv + 1, end_idx, elems_rest); + close_points_to(&self); + close >.own(t, *(&self)); + } @*/ + accum = call_fold__VeriFast_wrapper(&mut f, accum, tmp); + } + } + + //@ open_points_to(&self); + // There are in fact no remaining elements to forget, but by doing this we can avoid + // potentially generating a needless loop to drop the elements that cannot exist at + // this point. + self.forget_remaining_elements_and_dealloc(); + //@ close_points_to(&self); + + accum + } + + #[inline] + fn try_fold(&mut self, mut accum: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, T) -> R, + R: core::ops::Try, + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0) &*& .own(t, accum) &*& .own(t, f); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& .own(t, result); + { + //@ assert lifetime_token(?flft); + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *self |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(self); + let ptr_raw = self.ptr.as_ptr(); + let end_mut = const_ptr_cast_mut__VeriFast_wrapper(self.end); + let cont = ptr_raw != end_mut; + //@ close_points_to(self); + cont + } { + //@ open_points_to(self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(cur_it.ptr); + //@ wrapping_sub_usize_zero(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ let old_len = std::num::wrapping_sub_usize(cur_it.end as usize, cur_it.ptr.as_ptr() as usize); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), old_len, ?elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ leak points_to_at_lft_(alloc_id.lft, cur_it.ptr.as_ptr(), _); + // See `next` for why we subtract from `end` here. + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + //@ close_points_to(self); + //@ close >.own(t, *self); + let step = call_try_fn__VeriFast_wrapper(&mut f, accum, tmp); + accum = match unsafe { try_branch__VeriFast_wrapper::(step) } { + core::ops::ControlFlow::Continue(v) => v, + core::ops::ControlFlow::Break(res) => return unsafe { try_from_residual__VeriFast_wrapper::(res) }, + }; + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while { + /*@ inv thread_token(t) &*& lifetime_token(flft) &*& + *self |-> ?cur_it &*& >.own(t, cur_it) &*& + .own(t, accum) &*& + *(&f) |-> ?cur_f &*& .own(t, cur_f); @*/ + //@ open_points_to(self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id_c); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, ?adv_c, ?end_idx_c, ?elems_c); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let is_ne = unsafe { ptr_ne_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + //@ close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id_c, cur_it.ptr, cur_it.end, adv_c, end_idx_c, elems_c); + //@ close_points_to(self); + //@ close >.own(t, *self); + is_ne + } { + //@ open_points_to(self); + //@ open >.own(t, cur_it); + //@ assert Allocator(t, cur_it.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ open IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, cur_it.ptr, cur_it.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(1, cur_it.cap, std::mem::size_of::()); + //@ open array_at_lft::(alloc_id.lft, cur_it.ptr.as_ptr(), end_idx - adv, elems); + //@ open foreach(elems, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, cur_it.ptr.as_ptr(), ?x0); + //@ points_to_at_lft_inv(cur_it.ptr.as_ptr()); + //@ open own::(t)(x0); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(cur_it.ptr.as_ptr(), q_alloc/2); + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { non_null_read__VeriFast_wrapper(self.ptr) }; + //@ close_points_to_at_lft_(cur_it.ptr.as_ptr()); + //@ close LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { non_null_add_1__VeriFast_wrapper(self.ptr) }; + //@ open LiveSlot::(cur_it.ptr.as_ptr(), alloc_id.lft, q_alloc, 1, none); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr() + 1, 0, nil); + close array_at_lft_::(alloc_id.lft, cur_it.ptr.as_ptr(), 1, _); + array_at_lft__join::(cur_it.buf.as_ptr()); + assert array_at_lft(alloc_id.lft, cur_it.ptr.as_ptr() + 1, end_idx - adv - 1, ?elems_rest); + close IntoIter_non_zst_buf::(t, cur_it.buf, cur_it.cap, alloc_id, (*self).ptr, cur_it.end, adv + 1, end_idx, elems_rest); + close_points_to(self); + close >.own(t, *self); + } @*/ + let step = call_try_fn__VeriFast_wrapper(&mut f, accum, tmp); + accum = match unsafe { try_branch__VeriFast_wrapper::(step) } { + core::ops::ControlFlow::Continue(v) => v, + core::ops::ControlFlow::Break(res) => return unsafe { try_from_residual__VeriFast_wrapper::(res) }, + }; + } + } + try_from_output__VeriFast_wrapper::(accum) + } + #[requires(i < self.len())] + #[cfg_attr(kani, kani::modifies(self))] + unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item + where + Self: TrustedRandomAccessNoCoerce, + { + // SAFETY: the caller must guarantee that `i` is in bounds of the + // `Vec`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)` + // is guaranteed to pointer to an element of the `Vec` and + // thus guaranteed to be valid to dereference. + // + // Also note the implementation of `Self: TrustedRandomAccess` requires + // that `T: Copy` so reading elements from the buffer doesn't invalidate + // them for `Drop`. + unsafe { self.ptr.add(i).read() } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl DoubleEndedIterator for IntoIter { + #[inline] + fn next_back(&mut self) -> Option + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + //@ open_points_to(self); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ std::ptr::NonNull_Sized_as_ptr(self0.ptr); + if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut _ { + /*@ { + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // See above for why 'ptr.offset' isn't used + //@ wrapping_sub_usize_zero(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ wrapping_sub_usize_dec(self0.end as usize, self0.ptr.as_ptr() as usize); + self.end = const_ptr_wrapping_byte_sub_1__VeriFast_wrapper(self.end); + //@ let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + //@ open foreach(elems_z, own::(t)); + //@ assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?xz); + //@ open own::(t)(xz); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(self0.ptr.as_ptr(), q_alloc/2); + // Note that even though this is next_back() we're reading from `self.ptr`, not + // `self.end`. We track our length using the byte offset from `self.ptr` to `self.end`, + // so the end pointer may not be suitably aligned for T. + // ignore-tidy-undocumented-unsafe + let res = Some(unsafe { ptr::read(self.ptr.as_ptr()) }); + /*@ { + close_points_to_at_lft_(self0.ptr.as_ptr()); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + leak points_to_at_lft_(alloc_id.lft, self0.ptr.as_ptr(), _); + close_points_to(self); + close >.own(t, *self); + close >.own(t, Some(xz)); + } @*/ + res + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let is_eq = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + if is_eq { + /*@ { + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv, end_idx, elems); + close_points_to(self); + close >.own(t, *self); + close >.own(t, None); + } @*/ + return None; + } + // ignore-tidy-undocumented-unsafe + unsafe { + /*@ { + let rem = end_idx - adv; + list_split_last(elems); + array_at_lft_split::(self0.ptr.as_ptr(), rem - 1); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + (rem - 1), 1, _); + open array_at_lft::(alloc_id.lft, self0.ptr.as_ptr() + rem, 0, _); + assert points_to_at_lft(alloc_id.lft, self0.ptr.as_ptr() + (rem - 1), ?xlast); + foreach_snoc_inv(take(rem - 1, elems), xlast, own::(t)); + open own::(t)(xlast); + points_to_at_lft_inv(self0.ptr.as_ptr() + (rem - 1)); + std::alloc::Layout_inv(Layout::new::()); + mul_mono_l(1, self0.cap, std::mem::size_of::()); + } @*/ + self.end = self.end.sub(1); + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(self0.buf.as_ptr() + (end_idx - 1), q_alloc/2); + let val = ptr::read(self.end); + let res = Some(val); + /*@ { + close_points_to_at_lft_(self0.buf.as_ptr() + (end_idx - 1)); + lifetime_token_trade_back(q_alloc, alloc_id.lft); + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() + end_idx, 0, nil); + close array_at_lft_::(alloc_id.lft, self0.buf.as_ptr() + (end_idx - 1), 1, _); + array_at_lft__join::(self0.buf.as_ptr() + (end_idx - 1)); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, (*self).end, adv, end_idx - 1, take(end_idx - adv - 1, elems)); + close_points_to(self); + close >.own(t, *self); + close >.own(t, Some(val)); + } @*/ + res + } + } + } + + #[inline] + fn next_chunk_back(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, N - len..N) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { MaybeUninit::array_assume_init(raw_ary) }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available + // and we just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping( + self.ptr.add(len - N).as_ptr(), + raw_ary.as_mut_ptr() as *mut T, + N, + ); + self.end = self.end.sub(N); + Ok(MaybeUninit::array_assume_init(raw_ary)) + } + } + + #[inline] + fn advance_back_by<'s>(/*@~mut@*/ self: &'s mut Self, n: usize) -> Result<(), NonZero> + //@ req thread_token(?t) &*& *self |-> ?self0 &*& >.own(t, self0); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1) &*& >>.own(t, result); + /*@ + safety_proof { + assert [?q]lifetime_token('s); + open_full_borrow(q, 's, (>.full_borrow_content)(_t, self)); + open_full_borrow_content::>(_t, self); + let r = call(); + close_full_borrow_content::>(_t, self); + close_full_borrow((>.full_borrow_content)(_t, self)); + leak full_borrow('s, (>.full_borrow_content)(_t, self)); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ let self_p0 = self; + //@ open_points_to(self_p0); + //@ open >.own(t, self0); + //@ assert Allocator(t, self0.alloc, ?alloc_id); + //@ std::alloc::Allocator_inv(); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + /*@ { + if std::mem::size_of::() == 0 { + close exists::(std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize)); + } else { + open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv0, ?end0, ?elems0); + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, adv0, end0, elems0); + close exists::(end0 - adv0); + } + } @*/ + //@ open exists::(?len0); + //@ let k_len = begin_lifetime(); + //@ close IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + //@ borrow(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ IntoIter_share_val_fbc::(k_len, t, self_p0, self0, alloc_id, len0); + let cur_len; + unsafe { + //@ let_lft 'a = flft; + //@ let self_r = precreate_ref(&self); + //@ init_ref_readonly(self_r, 1/2); + cur_len = exact_size_len__VeriFast_wrapper/*@::@*/(&self); + //@ end_ref_readonly(self_r); + } + //@ end_lifetime(k_len); + //@ borrow_end(k_len, IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)); + //@ open IntoIter_val_fbc::(t, self_p0, self0, alloc_id, len0)(); + let step_size = usize_min__VeriFast_wrapper(cur_len, n); + if T::IS_ZST { + // SAFETY: same as for advance_by() + //@ wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + self.end = const_ptr_wrapping_byte_sub__VeriFast_wrapper(self.end, step_size); + } else { + //@ open IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, self0.end, ?adv, ?end_idx, ?elems); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ mul_mono_l(step_size, self0.cap, std::mem::size_of::()); + //@ mul_mono_l(1, std::mem::size_of::(), self0.cap); + //@ let keep_n = (end_idx - adv) - step_size; + //@ array_at_lft_split::(self0.ptr.as_ptr(), keep_n); + //@ foreach_split(elems, own::(t), keep_n); + // SAFETY: same as for advance_by() + self.end = unsafe { self.end.sub(step_size) }; + } + let to_drop = if T::IS_ZST { + // ZST may cause unalignment + let d = unsafe { non_null_dangling__VeriFast_wrapper::() }.as_ptr(); + //@ let old_len = std::num::wrapping_sub_usize(self0.end as usize, self0.ptr.as_ptr() as usize); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), old_len, ?elems_z); + //@ array_at_lft_split::(self0.ptr.as_ptr(), step_size); + //@ foreach_split(elems_z, own::(t), step_size); + //@ zst_array_at_lft_move::(take(step_size, elems_z), alloc_id.lft, self0.ptr.as_ptr(), d, step_size); + //@ close_slice_own_from_foreach::(t, take(step_size, elems_z)); + d.cast_slice(step_size) + } else { + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?keep1, ?keep_elems); + //@ assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr() + keep1, step_size, ?drop_elems); + //@ close_slice_own_from_foreach::(t, drop_elems); + const_ptr_cast_t_mut__VeriFast_wrapper(self.end).cast_slice(step_size) + }; + //@ let q_alloc = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ close_points_to_slice_at_lft(to_drop); + //@ open_points_to_at_lft(to_drop, q_alloc/2); + // SAFETY: same as for advance_by() + unsafe { + ptr::drop_in_place(to_drop); + } + //@ close_points_to_at_lft_(to_drop); + //@ open_points_to_slice_at_lft_(to_drop); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + /*@ { + let self_p = self; + if std::mem::size_of::() == 0 { + leak array_at_lft_(alloc_id.lft, to_drop as *T, step_size, _); + assert (*self_p).end |-> ?new_end; + assert (new_end as usize) == std::num::wrapping_sub_usize(self0.end as usize, step_size); + wrapping_sub_usize_sub(self0.end as usize, self0.ptr.as_ptr() as usize, step_size); + assert array_at_lft(alloc_id.lft, ?p_rem, ?rem_z, ?rem_elems); + zst_array_at_lft_move::(rem_elems, alloc_id.lft, p_rem, self0.ptr.as_ptr(), rem_z); + assert rem_z == std::num::wrapping_sub_usize(new_end as usize, self0.ptr.as_ptr() as usize); + } else { + assert array_at_lft_(alloc_id.lft, self0.buf.as_ptr(), ?adv1, _); + assert array_at_lft(alloc_id.lft, self0.ptr.as_ptr(), ?keep2, ?keep_elems2); + array_at_lft__join::(self0.buf.as_ptr() + (adv1 + keep2)); + assert (*self_p).end |-> ?new_end; + if keep2 == 0 { + assert new_end == self0.ptr.as_ptr(); + } else { + assert new_end != 0; + } + close IntoIter_non_zst_buf::(t, self0.buf, self0.cap, alloc_id, self0.ptr, new_end, adv1, adv1 + keep2, keep_elems2); + } + close_points_to(self_p); + assert *self_p |-> ?self1; + close >.own(t, self1); + } @*/ + unsafe { non_zero_rem__VeriFast_wrapper(n - step_size) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ExactSizeIterator for IntoIter { + fn is_empty(&self) -> bool + //@ req thread_token(?t) &*& [_]IntoIter_share_::(?k, t, self, ?len) &*& [?q]lifetime_token(k); + //@ ens thread_token(t) &*& [q]lifetime_token(k) &*& result == (len == 0); + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open IntoIter_share_::(k, t, self, len); + //@ assert [_]exists::>(?v); + //@ open_frac_borrow(k, IntoIter_shared_val::(self, v), q); + //@ open [?f]IntoIter_shared_val::(self, v)(); + let res = if T::IS_ZST { + //@ wrapping_sub_usize_zero(v.end as usize, v.ptr.as_ptr() as usize); + self.ptr.as_ptr() == self.end as *mut _ + } else { + //@ points_to_limits(&(*self).ptr); + //@ points_to_limits(&(*self).end); + //@ let ptr_r = precreate_ref(&(*self).ptr); + //@ std::ptr::init_ref_NonNull(ptr_r, 1/2); + //@ let end_r = precreate_ref(&(*self).end); + //@ init_ref_readonly(end_r, 1/2); + let r = unsafe { ptr_eq_end__VeriFast_wrapper(&self.ptr, &self.end) }; + //@ std::ptr::end_ref_NonNull(ptr_r); + //@ end_ref_readonly(end_r); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ assert (v.end as usize) == (v.ptr.as_ptr() as usize) + len * std::mem::size_of::(); + //@ if len == 0 { match (v.ptr.as_ptr() as pointer) { pointer_ctor(prov, addr, meta) => {} } } else { mul_mono_l(1, len, std::mem::size_of::()); } + r + }; + //@ close [f]IntoIter_shared_val::(self, v)(); + //@ close_frac_borrow(f, IntoIter_shared_val::(self, v)); + res + } +} + +#[stable(feature = "fused", since = "1.26.0")] +impl FusedIterator for IntoIter {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "trusted_fused")] +unsafe impl TrustedFused for IntoIter {} + +#[unstable(feature = "trusted_len", issue = "37572")] +unsafe impl TrustedLen for IntoIter {} + +#[stable(feature = "default_iters", since = "1.70.0")] +impl Default for IntoIter +where + A: Allocator + Default, +{ + /// Creates an empty `vec::IntoIter`. + /// + /// ``` + /// # use std::vec; + /// let iter: vec::IntoIter = Default::default(); + /// assert_eq!(iter.len(), 0); + /// assert_eq!(iter.as_slice(), &[]); + /// ``` + fn default() -> Self { + super::Vec::new_in(Default::default()).into_iter() + } +} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +#[unsafe(rustc_allow_lifetime_dependent_specialization)] +trait NonDrop {} + +// T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr +// and thus we can't implement drop-handling +#[unstable(issue = "none", feature = "std_internals")] +impl NonDrop for T {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +// TrustedRandomAccess (without NoCoerce) must not be implemented because +// subtypes/supertypes of `T` might not be `NonDrop` +unsafe impl TrustedRandomAccessNoCoerce for IntoIter +where + T: NonDrop, +{ + const MAY_HAVE_SIDE_EFFECT: bool = false; +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_into_iter_clone", since = "1.8.0")] +impl Clone for IntoIter { + fn clone(&self) -> Self { + self.as_slice().to_vec_in(self.alloc.deref().clone()).into_iter() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter { + fn drop(&mut self) { + struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter); + + impl Drop for DropGuard<'_, T, A> { + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + self.0.dealloc_only(); + } + } + } + + let guard = DropGuard(self); + // destroy the remaining elements + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(guard.0.as_raw_mut_slice()); + } + // now `guard` will be dropped and do the rest + } +} +// In addition to the SAFETY invariants of the following three unsafe traits +// also refer to the vec::in_place_collect module documentation to get an overview +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl InPlaceIterable for IntoIter { + const EXPAND_BY: Option> = NonZero::new(1); + const MERGE_BY: Option> = NonZero::new(1); +} + +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl SourceIter for IntoIter { + type Source = Self; + + #[inline] + unsafe fn as_inner(&mut self) -> &mut Self::Source { + self + } +} + +#[cfg(not(no_global_oom_handling))] +unsafe impl AsVecIntoIter for IntoIter { + type Item = T; + + fn as_into_iter(&mut self) -> &mut IntoIter { + self + } +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/lib.rs b/verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/lib.rs new file mode 120000 index 0000000000000..01c96c3dc47a4 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/lib.rs @@ -0,0 +1 @@ +../verified/lib.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/raw_vec.rs b/verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/raw_vec.rs new file mode 120000 index 0000000000000..43bf23687259e --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/verified_try_fold/raw_vec.rs @@ -0,0 +1 @@ +../verified/raw_vec.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs/verify.sh b/verifast-proofs/alloc/vec/into_iter.rs/verify.sh new file mode 100644 index 0000000000000..d514e5329afc7 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/verify.sh @@ -0,0 +1,74 @@ +set -e -x + +export VFVERSION=26.10 + +# Ensure VeriFast toolchain and matching nightly rustc (nightly-2026-09-25) are available +. "$(dirname "$0")/../../../setup-verifast-home" + +if [[ "$(uname)" == "Darwin" ]]; then + DYLIB_EXT="dylib" +else + DYLIB_EXT="so" +fi + +STUB_DIR="$(mktemp -d)" +trap 'rm -rf "$STUB_DIR"' EXIT + +check_diff_matches_patch() { + local label_a="$1" + local label_b="$2" + local file_a="$3" + local file_b="$4" + local patch_file="$5" + local actual_patch="$STUB_DIR/$(basename "$patch_file").actual" + set +e + diff -u --label "$label_a" --label "$label_b" "$file_a" "$file_b" > "$actual_patch" + local rc=$? + set -e + if [[ "$rc" -ne 1 ]]; then + echo "ERROR: expected diff exit status 1 for $file_a vs $file_b, got $rc" >&2 + exit 1 + fi + diff -u "$patch_file" "$actual_patch" +} + +rustc +nightly-2026-09-25 --edition 2024 --crate-type proc-macro --crate-name safety \ + -o "$STUB_DIR/libsafety.$DYLIB_EXT" safety_stub.rs + +RUSTC_ARGS="--edition 2024 --crate-name alloc --extern safety=$STUB_DIR/libsafety.$DYLIB_EXT -L dependency=$STUB_DIR" + +# 1. Confirm untouched upstream original/into_iter.rs and verified_try_fold/into_iter.rs type-check cleanly +rustc +nightly-2026-09-25 --edition 2024 --crate-type lib --crate-name alloc \ + --extern safety="$STUB_DIR/libsafety.$DYLIB_EXT" -L dependency="$STUB_DIR" \ + --emit=metadata -o "$STUB_DIR/original.rmeta" original/lib.rs +rustc +nightly-2026-09-25 --edition 2024 --crate-type lib --crate-name alloc \ + --extern safety="$STUB_DIR/libsafety.$DYLIB_EXT" -L dependency="$STUB_DIR" \ + --emit=metadata -o "$STUB_DIR/verified_try_fold.rmeta" verified_try_fold/lib.rs + +# 2. Verify all IntoIter + bridged RawVec proofs (excl. try_fold) with VeriFast +verifast -rustc_args "$RUSTC_ARGS" -extern_spec tuple_ext=tuple_ext.rsspec \ + -skip_specless_fns -ignore_unwind_paths -allow_assume verified/lib.rs + +# 3. Verify refinement between with-directives/lib.rs and verified/lib.rs +refinement-checker --rustc-args "$RUSTC_ARGS" with-directives/lib.rs verified/lib.rs > /dev/null + +# 4. Verify IntoIter::try_fold (plus all verified methods) with VeriFast +verifast -rustc_args "$RUSTC_ARGS" -extern_spec tuple_ext=tuple_ext.rsspec \ + -extern_spec std=std_ext.rsspec \ + -skip_specless_fns -ignore_unwind_paths -allow_assume verified_try_fold/lib.rs + +# 5. Mechanically enforce exact upstream correspondence and reviewed patch boundaries +if ! diff original/into_iter.rs ../../../../library/alloc/src/vec/into_iter.rs; then + echo "::error title=Please run verifast-proofs/patch-verifast-proofs.sh::Some VeriFast proofs are out of date; please chdir to verifast-proofs and run patch-verifast-proofs.sh to update them." + false +fi +if ! diff original/raw_vec.rs ../../../../library/alloc/src/raw_vec/mod.rs; then + echo "::error title=Please run verifast-proofs/patch-verifast-proofs.sh::Some VeriFast proofs are out of date; please chdir to verifast-proofs and run patch-verifast-proofs.sh to update them." + false +fi +check_diff_matches_patch original/into_iter.rs with-directives/into_iter.rs \ + original/into_iter.rs with-directives/into_iter.rs with-directives.patch +check_diff_matches_patch verified/into_iter.rs verified_try_fold/into_iter.rs \ + verified/into_iter.rs verified_try_fold/into_iter.rs try_fold.patch +check_diff_matches_patch raw_vec/mod.rs/verified/raw_vec.rs verified/raw_vec.rs \ + ../../raw_vec/mod.rs/verified/raw_vec.rs verified/raw_vec.rs raw_vec_verified.patch diff --git a/verifast-proofs/alloc/vec/into_iter.rs/with-directives.patch b/verifast-proofs/alloc/vec/into_iter.rs/with-directives.patch new file mode 100644 index 0000000000000..e5cf3a7bc8868 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/with-directives.patch @@ -0,0 +1,47 @@ +--- original/into_iter.rs ++++ with-directives/into_iter.rs +@@ -31,7 +31,7 @@ + ($place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe +- unsafe { *((&raw const $place) as *const NonNull<$t>) } ++ unsafe { *((&$place as *const *const $t) as *const NonNull<$t>) } + }}, + } + +@@ -427,7 +427,7 @@ + } + + #[inline] +- fn advance_by(&mut self, n: usize) -> Result<(), NonZero> { ++ fn advance_by(/*@~mut@*/ self: &mut Self, n: usize) -> Result<(), NonZero> { + let step_size = self.len().min(n); + let to_drop = self.ptr.as_ptr().cast_slice(step_size); + if T::IS_ZST { +@@ -494,7 +494,7 @@ + #[inline] + fn fold(mut self, mut accum: B, mut f: F) -> B + where +- F: FnMut(B, Self::Item) -> B, ++ F: FnMut(B, T) -> B, + { + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( +@@ -548,7 +548,7 @@ + fn try_fold(&mut self, mut accum: B, mut f: F) -> R + where + Self: Sized, +- F: FnMut(B, Self::Item) -> R, ++ F: FnMut(B, T) -> R, + R: core::ops::Try, + { + if T::IS_ZST { +@@ -680,7 +680,7 @@ + } + + #[inline] +- fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero> { ++ fn advance_back_by(/*@~mut@*/ self: &mut Self, n: usize) -> Result<(), NonZero> { + let step_size = self.len().min(n); + if T::IS_ZST { + // SAFETY: same as for advance_by() diff --git a/verifast-proofs/alloc/vec/into_iter.rs/with-directives/into_iter.rs b/verifast-proofs/alloc/vec/into_iter.rs/with-directives/into_iter.rs new file mode 100644 index 0000000000000..e8ac77b65f674 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/with-directives/into_iter.rs @@ -0,0 +1,825 @@ +use core::iter::{ + FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, + TrustedRandomAccessNoCoerce, +}; +#[cfg(kani)] +use core::kani; +use core::marker::PhantomData; +use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties}; +use core::num::NonZero; +#[cfg(not(no_global_oom_handling))] +use core::ops::Deref; +use core::panic::UnwindSafe; +use core::ptr::{self, NonNull}; +use core::{array, fmt, slice}; + +use safety::{loop_invariant, requires}; + +#[cfg(not(no_global_oom_handling))] +use super::AsVecIntoIter; +use crate::alloc::{Allocator, Global}; +#[cfg(not(no_global_oom_handling))] +use crate::collections::VecDeque; +use crate::raw_vec::RawVec; + +macro non_null { + (mut $place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { &mut *((&raw mut $place) as *mut NonNull<$t>) } + }}, + ($place:expr, $t:ident) => {{ + #![allow(unused_unsafe)] // we're sometimes used within an unsafe block + // ignore-tidy-undocumented-unsafe + unsafe { *((&$place as *const *const $t) as *const NonNull<$t>) } + }}, +} + +/// An iterator that moves out of a vector. +/// +/// This `struct` is created by the `into_iter` method on [`Vec`](super::Vec) +/// (provided by the [`IntoIterator`] trait). +/// +/// # Example +/// +/// ``` +/// let v = vec![0, 1, 2]; +/// let iter: std::vec::IntoIter<_> = v.into_iter(); +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_insignificant_dtor] +pub struct IntoIter< + T, + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] A: Allocator = Global, +> { + pub(super) buf: NonNull, + pub(super) phantom: PhantomData, + pub(super) cap: usize, + // the drop impl reconstructs a RawVec from buf, cap and alloc + // to avoid dropping the allocator twice we need to wrap it into ManuallyDrop + pub(super) alloc: ManuallyDrop, + pub(super) ptr: NonNull, + /// If T is a ZST, this is actually ptr+len. This encoding is picked so that + /// ptr == end is a quick test for the Iterator being empty, that works + /// for both ZST and non-ZST. + /// For non-ZSTs the pointer is treated as `NonNull` + pub(super) end: *const T, +} + +// Manually mirroring what `Vec` has, +// because otherwise we get `T: RefUnwindSafe` from `NonNull`. +#[stable(feature = "catch_unwind", since = "1.9.0")] +impl UnwindSafe for IntoIter {} + +#[stable(feature = "vec_intoiter_debug", since = "1.13.0")] +impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("IntoIter").field(&self.as_slice()).finish() + } +} + +impl IntoIter { + /// Returns the remaining items of this iterator as a slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// let _ = into_iter.next().unwrap(); + /// assert_eq!(into_iter.as_slice(), &['b', 'c']); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_slice(&self) -> &[T] { + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len()) } + } + + /// Returns the remaining items of this iterator as a mutable slice. + /// + /// # Examples + /// + /// ``` + /// let vec = vec!['a', 'b', 'c']; + /// let mut into_iter = vec.into_iter(); + /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); + /// into_iter.as_mut_slice()[2] = 'z'; + /// assert_eq!(into_iter.next().unwrap(), 'a'); + /// assert_eq!(into_iter.next().unwrap(), 'b'); + /// assert_eq!(into_iter.next().unwrap(), 'z'); + /// ``` + #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] + pub fn as_mut_slice(&mut self) -> &mut [T] { + // ignore-tidy-undocumented-unsafe + unsafe { &mut *self.as_raw_mut_slice() } + } + + /// Returns a reference to the underlying allocator. + #[stable(feature = "vec_into_iter_allocator", since = "1.101.0")] + #[inline] + pub fn allocator(&self) -> &A { + &self.alloc + } + + fn as_raw_mut_slice(&mut self) -> *mut [T] { + self.ptr.as_ptr().cast_slice(self.len()) + } + + /// Drops remaining elements and relinquishes the backing allocation. + /// + /// This method guarantees it won't panic before relinquishing the backing + /// allocation. + /// + /// This is roughly equivalent to the following, but more efficient + /// + /// ``` + /// # let mut vec = Vec::::with_capacity(10); + /// # let ptr = vec.as_mut_ptr(); + /// # let mut into_iter = vec.into_iter(); + /// let mut into_iter = std::mem::replace(&mut into_iter, Vec::new().into_iter()); + /// (&mut into_iter).for_each(drop); + /// std::mem::forget(into_iter); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # drop(unsafe { Vec::::from_raw_parts(ptr, 0, 10) }); + /// ``` + /// + /// This method is used by in-place iteration, refer to the vec::in_place_collect + /// documentation for an overview. + #[cfg(not(no_global_oom_handling))] + pub(super) fn forget_allocation_drop_remaining(&mut self) { + let remaining = self.as_raw_mut_slice(); + + // overwrite the individual fields instead of creating a new + // struct and then overwriting &mut self. + // this creates less assembly + self.cap = 0; + self.buf = RawVec::new().non_null(); + self.ptr = self.buf; + self.end = self.buf.as_ptr(); + + // Dropping the remaining elements can panic, so this needs to be + // done only after updating the other fields. + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(remaining); + } + } + + /// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed. + /// + /// This method does not consume `self`, and leaves deallocation to `impl Drop for IntoIter`. + /// If consuming `self` is possible, consider calling + /// [`Self::forget_remaining_elements_and_dealloc()`] instead. + pub(crate) fn forget_remaining_elements(&mut self) { + // For the ZST case, it is crucial that we mutate `end` here, not `ptr`. + // `ptr` must stay aligned, while `end` may be unaligned. + self.end = self.ptr.as_ptr(); + } + + /// Forgets to Drop the remaining elements and frees the backing allocation. + /// Consuming version of [`Self::forget_remaining_elements()`]. + /// + /// This can be used in place of `drop(self)` when `self` is known to be exhausted, + /// to avoid producing a needless `drop_in_place::<[T]>()`. + #[inline] + pub(crate) fn forget_remaining_elements_and_dealloc(self) { + let mut this = ManuallyDrop::new(self); + // SAFETY: `this` is in ManuallyDrop, so it will not be double-freed. + unsafe { + this.dealloc_only(); + } + } + + /// Frees the allocation, without checking or dropping anything else. + /// + /// The safe version of this method is [`Self::forget_remaining_elements_and_dealloc()`]. + /// This function exists only to share code between that method and the `impl Drop`. + /// + /// # Safety + /// + /// This function must only be called with an [`IntoIter`] that is not going to be dropped + /// or otherwise used in any way, either because it is being forgotten or because its `Drop` + /// is already executing; otherwise a double-free will occur, and possibly a read from freed + /// memory if there are any remaining elements. + #[inline] + unsafe fn dealloc_only(&mut self) { + // SAFETY: our caller promises not to touch `*self` again. + let alloc = unsafe { ManuallyDrop::take(&mut self.alloc) }; + // SAFETY: We're using this to deallocate a preexisting `RawVec`. + let _ = unsafe { RawVec::from_nonnull_in(self.buf, self.cap, alloc) }; + } + + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn into_vecdeque(self) -> VecDeque { + // Keep our `Drop` impl from dropping the elements and the allocator + let mut this = ManuallyDrop::new(self); + + let buf = this.buf.as_ptr(); + let initialized = if T::IS_ZST || this.len() == 0 { + // All the pointers are the same for ZSTs, so it's fine to + // say that they're all at the beginning of the "allocation". + // For non-ZSTs, we have length 0, so we can choose the (empty) + // range to be at the start of the buffer. + // + // Due to `0` ≤ `this.len()` ≤ `this.cap`, the range is well-formed, + // and due to the argument above it spans exactly the elements of + // this iterator. Because `init.start` = `0`, it follows that either + // `init.start` < `cap` or `cap` = `init.start` = `0`; thus the range + // satisfies the requirements of `from_contiguous_raw_parts_in`. + 0..this.len() + } else { + // SAFETY: `this.ptr` and `this.end` are created via offsets of `this.buf`, + // so they point to the same allocation. We have `this.buf` ≤ `this.ptr` ≤ `this.end`, + // so this cannot wrap, and will produce a well-formed range that spans exactly + // the elements of this iterator. + // + // Additionally, due to `end ≤ buf + cap`, we have `init.start` ≤ `init.end` ≤ `cap`. + // Due to the length check above, `init.start < cap`, so the range satisfies the + // requirements of `from_contiguous_raw_parts_in`. + unsafe { this.ptr.offset_from_unsigned(this.buf)..this.end.offset_from_unsigned(buf) } + }; + + let cap = this.cap; + // SAFETY: `this` is forgotten afterwards, so we can move out the allocator. + let alloc = unsafe { ManuallyDrop::take(&mut this.alloc) }; + + // SAFETY: This allocation originally came from a `Vec`, so it satisfies all + // requirements for the `buf` pointer with capacity `cap` allocated in `alloc`. + // Correctness of `initialized` was shown above. + unsafe { VecDeque::from_contiguous_raw_parts_in(buf, initialized, cap, alloc) } + } +} + +#[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")] +impl AsRef<[T]> for IntoIter { + fn as_ref(&self) -> &[T] { + self.as_slice() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for IntoIter {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for IntoIter {} + +// Loop-invariant predicates for `IntoIter::fold` and `IntoIter::try_fold`. +// Marked `#[inline(always)]` and written with pure intrinsics and `const { ... }` +// blocks rather than method calls (e.g. `NonNull::as_ptr` / `pointer::addr` / +// non-const `mem::size_of`) so Kani's loop-contract lowering evaluates them +// inline as side-effect-free CBMC expressions without emitting nondeterministic +// helper calls (https://github.com/model-checking/kani/issues/4796). +// `self.alloc` is untouched by either loop and is preserved across loop +// contracts (verified with both `TrackAlloc` and non-ZST `StatefulAlloc`). +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, and `usize` have identical layout (thin pointer width); + // these casts are side-effect-free re-interpretations for CBMC's loop-invariant evaluator. + let (ptr_p, eptr_p, buf_p, ebuf_p, ptr_a, eptr_a, end_a, eend_a): ( + *const T, + *const T, + *const T, + *const T, + usize, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + core::intrinsics::transmute_unchecked(entry_end), + ) + }; + ptr_p == eptr_p + && buf_p == ebuf_p + && cap == entry_cap + && core::intrinsics::wrapping_sub(end_a, ptr_a) + <= core::intrinsics::wrapping_sub(eend_a, eptr_a) +} + +#[cfg(kani)] +#[inline(always)] +fn kani_into_iter_non_zst_inv( + ptr: NonNull, + buf: NonNull, + cap: usize, + end: *const T, + entry_ptr: NonNull, + entry_buf: NonNull, + entry_cap: usize, + entry_end: *const T, +) -> bool { + // SAFETY: `NonNull`, `*const T`, `*const u8`, and `usize` have identical thin-pointer + // layout; used to avoid method calls in CBMC loop-contract predicates (kani#4796). + let (buf_p, ebuf_p, ptr_p, eptr_u8, ptr_a, eptr_a, end_a): ( + *const T, + *const T, + *const T, + *const u8, + usize, + usize, + usize, + ) = unsafe { + ( + core::intrinsics::transmute_unchecked(buf), + core::intrinsics::transmute_unchecked(entry_buf), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(ptr), + core::intrinsics::transmute_unchecked(entry_ptr), + core::intrinsics::transmute_unchecked(end), + ) + }; + let diff = core::intrinsics::wrapping_sub(ptr_a, eptr_a); + let span = core::intrinsics::wrapping_sub(end_a, eptr_a); + let sz = const { core::mem::size_of::() }; + let aligned = if const { core::mem::size_of::().is_power_of_two() } { + (diff & core::intrinsics::wrapping_sub(sz, 1)) == 0 + } else { + // Exact divisibility `diff % sz == 0` for any non-power-of-two `sz > 0` without a + // 64-bit integer division circuit: write `sz = odd * 2^tz` and compute the modular + // multiplicative inverse `odd_inv` (`odd * odd_inv == 1 mod 2^BITS`) at const time. + // Then `sz | diff` iff `2^tz | diff` and `(diff >> tz) * odd_inv <= usize::MAX / sz`. + let (tz, odd_inv, max_q) = const { + let s = core::mem::size_of::(); + if s == 0 { + (0u32, 1usize, 0usize) + } else { + let tz = s.trailing_zeros(); + let odd = s >> tz; + let mut inv: usize = 1; + let mut i = 0; + while i < 6 { + inv = inv.wrapping_mul(2usize.wrapping_sub(odd.wrapping_mul(inv))); + i += 1; + } + assert!(odd.wrapping_mul(inv) == 1); + (tz, inv, usize::MAX / s) + } + }; + let low_mask = core::intrinsics::wrapping_sub(1usize << tz, 1); + (diff & low_mask) == 0 && core::intrinsics::wrapping_mul(diff >> tz, odd_inv) <= max_q + }; + // SAFETY: `arith_offset` is wrapping (non-UB) pointer arithmetic; short-circuiting after + // `diff <= span && aligned` additionally guarantees `diff` stays within `[entry_ptr, end]`. + buf_p == ebuf_p + && cap == entry_cap + && end == entry_end + && diff <= span + && aligned + && ptr_p == unsafe { core::intrinsics::arith_offset(eptr_u8, diff as isize) as *const T } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Iterator for IntoIter { + type Item = T; + + #[inline] + fn next(&mut self) -> Option { + let ptr = if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut T { + return None; + } + // `ptr` has to stay where it is to remain aligned, so we reduce the length by 1 by + // reducing the `end`. + self.end = self.end.wrapping_byte_sub(1); + self.ptr + } else { + if self.ptr == non_null!(self.end, T) { + return None; + } + let old = self.ptr; + // ignore-tidy-undocumented-unsafe + self.ptr = unsafe { old.add(1) }; + old + }; + // ignore-tidy-undocumented-unsafe + Some(unsafe { ptr.read() }) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + let exact = if T::IS_ZST { + self.end.addr().wrapping_sub(self.ptr.as_ptr().addr()) + } else { + // ignore-tidy-undocumented-unsafe + unsafe { non_null!(self.end, T).offset_from_unsigned(self.ptr) } + }; + (exact, Some(exact)) + } + + #[inline] + fn advance_by(/*@~mut@*/ self: &mut Self, n: usize) -> Result<(), NonZero> { + let step_size = self.len().min(n); + let to_drop = self.ptr.as_ptr().cast_slice(step_size); + if T::IS_ZST { + // See `next` for why we sub `end` here. + self.end = self.end.wrapping_byte_sub(step_size); + } else { + // SAFETY: the min() above ensures that step_size is in bounds + self.ptr = unsafe { self.ptr.add(step_size) }; + } + // SAFETY: the min() above ensures that step_size is in bounds + unsafe { + ptr::drop_in_place(to_drop); + } + NonZero::new(n - step_size).map_or(Ok(()), Err) + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + #[inline] + fn last(mut self) -> Option { + self.next_back() + } + + #[inline] + fn next_chunk(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { raw_ary.transpose().assume_init() }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available and we + // just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, N); + self.ptr = self.ptr.add(N); + Ok(raw_ary.transpose().assume_init()) + } + } + + #[inline] + fn fold(mut self, mut accum: B, mut f: F) -> B + where + F: FnMut(B, T) -> B, + { + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr.as_ptr() != self.end.cast_mut() { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // See `next` for why we subtract from `end` here. + self.end = self.end.wrapping_byte_sub(1); + accum = f(accum, tmp); + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr != non_null!(self.end, T) { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { self.ptr.add(1) }; + accum = f(accum, tmp); + } + } + + // There are in fact no remaining elements to forget, but by doing this we can avoid + // potentially generating a needless loop to drop the elements that cannot exist at + // this point. + self.forget_remaining_elements_and_dealloc(); + + accum + } + + #[inline] + fn try_fold(&mut self, mut accum: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, T) -> R, + R: core::ops::Try, + { + if T::IS_ZST { + #[loop_invariant(kani_into_iter_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr.as_ptr() != self.end.cast_mut() { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // See `next` for why we subtract from `end` here. + self.end = self.end.wrapping_byte_sub(1); + accum = f(accum, tmp)?; + } + } else { + // SAFETY: `self.end` can only be null if `T` is a ZST. + #[loop_invariant(kani_into_iter_non_zst_inv( + self.ptr, + self.buf, + self.cap, + self.end, + on_entry(self.ptr), + on_entry(self.buf), + on_entry(self.cap), + on_entry(self.end), + ))] + while self.ptr != non_null!(self.end, T) { + // SAFETY: we just checked that `self.ptr` is in bounds. + let tmp = unsafe { self.ptr.read() }; + // SAFETY: the maximum this can be is `self.end`. + // Increment `self.ptr` first to avoid double dropping in the event of a panic. + self.ptr = unsafe { self.ptr.add(1) }; + accum = f(accum, tmp)?; + } + } + R::from_output(accum) + } + + #[requires(i < self.len())] + #[cfg_attr(kani, kani::modifies(self))] + unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item + where + Self: TrustedRandomAccessNoCoerce, + { + // SAFETY: the caller must guarantee that `i` is in bounds of the + // `Vec`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)` + // is guaranteed to pointer to an element of the `Vec` and + // thus guaranteed to be valid to dereference. + // + // Also note the implementation of `Self: TrustedRandomAccess` requires + // that `T: Copy` so reading elements from the buffer doesn't invalidate + // them for `Drop`. + unsafe { self.ptr.add(i).read() } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl DoubleEndedIterator for IntoIter { + #[inline] + fn next_back(&mut self) -> Option { + if T::IS_ZST { + if self.ptr.as_ptr() == self.end as *mut _ { + return None; + } + // See above for why 'ptr.offset' isn't used + self.end = self.end.wrapping_byte_sub(1); + // Note that even though this is next_back() we're reading from `self.ptr`, not + // `self.end`. We track our length using the byte offset from `self.ptr` to `self.end`, + // so the end pointer may not be suitably aligned for T. + // ignore-tidy-undocumented-unsafe + Some(unsafe { ptr::read(self.ptr.as_ptr()) }) + } else { + if self.ptr == non_null!(self.end, T) { + return None; + } + // ignore-tidy-undocumented-unsafe + unsafe { + self.end = self.end.sub(1); + Some(ptr::read(self.end)) + } + } + } + + #[inline] + fn next_chunk_back(&mut self) -> Result<[T; N], core::array::IntoIter> { + let mut raw_ary = [const { MaybeUninit::uninit() }; N]; + + let len = self.len(); + + if T::IS_ZST { + if len < N { + self.forget_remaining_elements(); + // SAFETY: ZSTs can be conjured ex nihilo, only the amount has to be correct + return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, N - len..N) }); + } + + self.end = self.end.wrapping_byte_sub(N); + // SAFETY: ditto + return Ok(unsafe { MaybeUninit::array_assume_init(raw_ary) }); + } + + if len < N { + // SAFETY: `len` indicates that this many elements are available + // and we just checked that it fits into the array. + unsafe { + ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len); + self.forget_remaining_elements(); + return Err(array::IntoIter::new_unchecked(raw_ary, 0..len)); + } + } + + // SAFETY: `len` is larger than the array size. Copy a fixed amount here to fully initialize + // the array. + unsafe { + ptr::copy_nonoverlapping( + self.ptr.add(len - N).as_ptr(), + raw_ary.as_mut_ptr() as *mut T, + N, + ); + self.end = self.end.sub(N); + Ok(MaybeUninit::array_assume_init(raw_ary)) + } + } + + #[inline] + fn advance_back_by(/*@~mut@*/ self: &mut Self, n: usize) -> Result<(), NonZero> { + let step_size = self.len().min(n); + if T::IS_ZST { + // SAFETY: same as for advance_by() + self.end = self.end.wrapping_byte_sub(step_size); + } else { + // SAFETY: same as for advance_by() + self.end = unsafe { self.end.sub(step_size) }; + } + let to_drop = if T::IS_ZST { + // ZST may cause unalignment + ptr::NonNull::::dangling().as_ptr().cast_slice(step_size) + } else { + self.end.cast::().cast_mut().cast_slice(step_size) + }; + // SAFETY: same as for advance_by() + unsafe { + ptr::drop_in_place(to_drop); + } + NonZero::new(n - step_size).map_or(Ok(()), Err) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ExactSizeIterator for IntoIter { + fn is_empty(&self) -> bool { + if T::IS_ZST { + self.ptr.as_ptr() == self.end as *mut _ + } else { + self.ptr == non_null!(self.end, T) + } + } +} + +#[stable(feature = "fused", since = "1.26.0")] +impl FusedIterator for IntoIter {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "trusted_fused")] +unsafe impl TrustedFused for IntoIter {} + +#[unstable(feature = "trusted_len", issue = "37572")] +unsafe impl TrustedLen for IntoIter {} + +#[stable(feature = "default_iters", since = "1.70.0")] +impl Default for IntoIter +where + A: Allocator + Default, +{ + /// Creates an empty `vec::IntoIter`. + /// + /// ``` + /// # use std::vec; + /// let iter: vec::IntoIter = Default::default(); + /// assert_eq!(iter.len(), 0); + /// assert_eq!(iter.as_slice(), &[]); + /// ``` + fn default() -> Self { + super::Vec::new_in(Default::default()).into_iter() + } +} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +#[unsafe(rustc_allow_lifetime_dependent_specialization)] +trait NonDrop {} + +// T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr +// and thus we can't implement drop-handling +#[unstable(issue = "none", feature = "std_internals")] +impl NonDrop for T {} + +#[doc(hidden)] +#[unstable(issue = "none", feature = "std_internals")] +// TrustedRandomAccess (without NoCoerce) must not be implemented because +// subtypes/supertypes of `T` might not be `NonDrop` +unsafe impl TrustedRandomAccessNoCoerce for IntoIter +where + T: NonDrop, +{ + const MAY_HAVE_SIDE_EFFECT: bool = false; +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_into_iter_clone", since = "1.8.0")] +impl Clone for IntoIter { + fn clone(&self) -> Self { + self.as_slice().to_vec_in(self.alloc.deref().clone()).into_iter() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter { + fn drop(&mut self) { + struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter); + + impl Drop for DropGuard<'_, T, A> { + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + self.0.dealloc_only(); + } + } + } + + let guard = DropGuard(self); + // destroy the remaining elements + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::drop_in_place(guard.0.as_raw_mut_slice()); + } + // now `guard` will be dropped and do the rest + } +} + +// In addition to the SAFETY invariants of the following three unsafe traits +// also refer to the vec::in_place_collect module documentation to get an overview +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl InPlaceIterable for IntoIter { + const EXPAND_BY: Option> = NonZero::new(1); + const MERGE_BY: Option> = NonZero::new(1); +} + +#[unstable(issue = "none", feature = "inplace_iteration")] +#[doc(hidden)] +unsafe impl SourceIter for IntoIter { + type Source = Self; + + #[inline] + unsafe fn as_inner(&mut self) -> &mut Self::Source { + self + } +} + +#[cfg(not(no_global_oom_handling))] +unsafe impl AsVecIntoIter for IntoIter { + type Item = T; + + fn as_into_iter(&mut self) -> &mut IntoIter { + self + } +} diff --git a/verifast-proofs/alloc/vec/into_iter.rs/with-directives/lib.rs b/verifast-proofs/alloc/vec/into_iter.rs/with-directives/lib.rs new file mode 120000 index 0000000000000..261b2bc7314e6 --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/with-directives/lib.rs @@ -0,0 +1 @@ +../original/lib.rs \ No newline at end of file diff --git a/verifast-proofs/alloc/vec/into_iter.rs/with-directives/raw_vec.rs b/verifast-proofs/alloc/vec/into_iter.rs/with-directives/raw_vec.rs new file mode 120000 index 0000000000000..da2b83bdb686d --- /dev/null +++ b/verifast-proofs/alloc/vec/into_iter.rs/with-directives/raw_vec.rs @@ -0,0 +1 @@ +../../../raw_vec/mod.rs/with-directives/raw_vec.rs \ No newline at end of file diff --git a/verifast-proofs/check-verifast-proofs-negative.sh b/verifast-proofs/check-verifast-proofs-negative.sh index 89fa996463136..ca8cc80f9899b 100755 --- a/verifast-proofs/check-verifast-proofs-negative.sh +++ b/verifast-proofs/check-verifast-proofs-negative.sh @@ -11,4 +11,9 @@ cd alloc bash verify.sh cd .. cd .. + cd vec + cd into_iter.rs-negative + bash verify.sh + cd .. + cd .. cd .. diff --git a/verifast-proofs/check-verifast-proofs.sh b/verifast-proofs/check-verifast-proofs.sh index 8b74f331273a5..885207b6fa30a 100755 --- a/verifast-proofs/check-verifast-proofs.sh +++ b/verifast-proofs/check-verifast-proofs.sh @@ -21,5 +21,8 @@ cd alloc cd extract_if.rs bash verify.sh cd .. + cd into_iter.rs + bash verify.sh + cd .. cd .. cd .. diff --git a/verifast-proofs/patch-verifast-proofs.sh b/verifast-proofs/patch-verifast-proofs.sh index e7497c7f5cbdc..630133231af7f 100755 --- a/verifast-proofs/patch-verifast-proofs.sh +++ b/verifast-proofs/patch-verifast-proofs.sh @@ -25,3 +25,9 @@ popd pushd alloc/vec/extract_if.rs patch_proof popd +pushd alloc/vec/into_iter.rs + patch_proof +popd +pushd alloc/vec/into_iter.rs-negative + patch_proof +popd From 88f98fca0b623e0aca59f0d7e6a5afb4eeb6c05b Mon Sep 17 00:00:00 2001 From: Emre Kaplaner Date: Mon, 30 Nov 2026 18:48:57 -0800 Subject: [PATCH 4/4] Make into_iter VeriFast patch verification portable across BSD and GNU diff --- .../alloc/vec/into_iter.rs-negative/verify.sh | 14 ++++++-------- verifast-proofs/alloc/vec/into_iter.rs/verify.sh | 14 ++++++-------- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/verifast-proofs/alloc/vec/into_iter.rs-negative/verify.sh b/verifast-proofs/alloc/vec/into_iter.rs-negative/verify.sh index b91fe48aa4046..bd0e1fa670e92 100644 --- a/verifast-proofs/alloc/vec/into_iter.rs-negative/verify.sh +++ b/verifast-proofs/alloc/vec/into_iter.rs-negative/verify.sh @@ -20,16 +20,14 @@ check_diff_matches_patch() { local file_a="$3" local file_b="$4" local patch_file="$5" - local actual_patch="$STUB_DIR/$(basename "$patch_file").actual" - set +e - diff -u --label "$label_a" --label "$label_b" "$file_a" "$file_b" > "$actual_patch" - local rc=$? - set -e - if [[ "$rc" -ne 1 ]]; then - echo "ERROR: expected diff exit status 1 for $file_a vs $file_b, got $rc" >&2 + local patched="$STUB_DIR/$(basename "$patch_file").patched" + if cmp -s "$file_a" "$file_b"; then + echo "ERROR: expected $file_a and $file_b to differ via $patch_file, but they are identical" >&2 exit 1 fi - diff -u "$patch_file" "$actual_patch" + cp "$file_a" "$patched" + patch -f -N -F 0 "$patched" "$patch_file" > /dev/null + diff -u --label "$label_a+$patch_file" --label "$label_b" "$patched" "$file_b" } expect_reject() { diff --git a/verifast-proofs/alloc/vec/into_iter.rs/verify.sh b/verifast-proofs/alloc/vec/into_iter.rs/verify.sh index d514e5329afc7..bc3e8a8f2a44f 100644 --- a/verifast-proofs/alloc/vec/into_iter.rs/verify.sh +++ b/verifast-proofs/alloc/vec/into_iter.rs/verify.sh @@ -20,16 +20,14 @@ check_diff_matches_patch() { local file_a="$3" local file_b="$4" local patch_file="$5" - local actual_patch="$STUB_DIR/$(basename "$patch_file").actual" - set +e - diff -u --label "$label_a" --label "$label_b" "$file_a" "$file_b" > "$actual_patch" - local rc=$? - set -e - if [[ "$rc" -ne 1 ]]; then - echo "ERROR: expected diff exit status 1 for $file_a vs $file_b, got $rc" >&2 + local patched="$STUB_DIR/$(basename "$patch_file").patched" + if cmp -s "$file_a" "$file_b"; then + echo "ERROR: expected $file_a and $file_b to differ via $patch_file, but they are identical" >&2 exit 1 fi - diff -u "$patch_file" "$actual_patch" + cp "$file_a" "$patched" + patch -f -N -F 0 "$patched" "$patch_file" > /dev/null + diff -u --label "$label_a+$patch_file" --label "$label_b" "$patched" "$file_b" } rustc +nightly-2026-09-25 --edition 2024 --crate-type proc-macro --crate-name safety \