diff --git a/library/alloc/src/collections/btree/node.rs b/library/alloc/src/collections/btree/node.rs index 2144efc5d7d4d..23888b91110a0 100644 --- a/library/alloc/src/collections/btree/node.rs +++ b/library/alloc/src/collections/btree/node.rs @@ -31,12 +31,16 @@ // since leaf edges are empty and need no data representation. In an internal node, // an edge both identifies a position and contains a pointer to a child node. +#[cfg(kani)] +use core::kani; use core::marker::PhantomData; use core::mem::{self, MaybeUninit}; use core::num::NonZero; use core::ptr::{self, NonNull}; use core::slice::SliceIndex; +use safety::{ensures, requires}; + use crate::alloc::{Allocator, AllocatorClone, Layout}; use crate::boxed::Box; @@ -72,6 +76,10 @@ impl LeafNode { /// # Safety /// /// The caller must ensure that `this` points to a (possibly uninitialized) `LeafNode` + #[requires(core::ub_checks::can_write(this))] + #[ensures(|_| unsafe { (*this).parent.is_none() })] + #[ensures(|_| unsafe { (*this).len == 0 })] + #[cfg_attr(kani, kani::modifies(this))] unsafe fn init(this: *mut Self) { // As a general policy, we leave fields uninitialized if they can be, as this should // be both slightly faster and easier to track in Valgrind. @@ -326,6 +334,20 @@ impl NodeRef /// /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should /// both, upon success, do nothing. + #[requires(verify::can_ascend(&self))] + #[ensures(|result| { + let original_node = old(self.node); + let original_height = old(self.height); + match (old(verify::ascend_link(&self)), result) { + (Some((parent, idx)), Ok(edge)) => { + edge.node.node == parent.cast() + && edge.node.height == original_height + 1 + && edge.idx == idx + } + (None, Err(root)) => root.node == original_node && root.height == original_height, + _ => false, + } + })] pub(super) fn ascend( self, ) -> Result, marker::Edge>, Self> { @@ -1055,6 +1077,14 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, mark impl<'a, K, V> Handle, K, V, marker::Internal>, marker::Edge> { /// Fixes the parent pointer and index in the child node that this edge /// links to. This is useful when the ordering of edges has been changed, + #[requires(verify::can_relink(&self.node, self.idx))] + #[ensures(|_| verify::has_parent_link( + old(verify::relink_child(&self.node, self.idx)), old(self.node.node.cast()), old(self.idx), + ))] + #[cfg_attr(kani, kani::modifies( + unsafe { &raw mut (*verify::relink_child(&self.node, self.idx)).parent }, + unsafe { &raw mut (*verify::relink_child(&self.node, self.idx)).parent_idx }, + ))] fn correct_parent_link(self) { // Create backpointer without invalidating other references to the node. // ignore-tidy-undocumented-unsafe @@ -1304,6 +1334,17 @@ impl Handle, marker::KV> impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { /// Helps implementations of `split` for a particular `NodeType`, /// by taking care of leaf data. + #[requires(verify::can_split_leaf_data(&self.node, self.idx, new_node))] + #[ensures(|_| { + self.node.len() == old(self.idx) + && usize::from(new_node.len) == old(self.node.len() - self.idx - 1) + })] + #[cfg_attr(kani, kani::modifies( + unsafe { &raw mut (*NodeRef::as_leaf_ptr(&self.node)).len }, + &raw mut new_node.len, + &raw mut new_node.keys, + &raw mut new_node.vals, + ))] fn split_leaf_data(&mut self, new_node: &mut LeafNode) -> (K, V) { debug_assert!(self.idx < self.node.len()); let old_len = self.node.len(); @@ -1924,6 +1965,11 @@ pub(super) mod marker { /// /// # Safety /// The slice has more than `idx` elements. +#[requires(idx < slice.len())] +#[cfg_attr(kani, kani::modifies(ptr::slice_from_raw_parts_mut( + unsafe { slice.as_mut_ptr().add(idx) }, + slice.len() - idx, +)))] unsafe fn slice_insert(slice: &mut [MaybeUninit], idx: usize, val: T) { let len = slice.len(); debug_assert!(len > idx); @@ -1981,6 +2027,8 @@ unsafe fn slice_shr(slice: &mut [MaybeUninit], distance: usize) { /// Moves all values from a slice of initialized elements to a slice /// of uninitialized elements, leaving behind `src` as all uninitialized. /// Works like `dst.copy_from_slice(src)` but does not require `T` to be `Copy`. +#[requires(src.len() == dst.len())] +#[cfg_attr(kani, kani::modifies(dst))] fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) { assert!(src.len() == dst.len()); // ignore-tidy-undocumented-unsafe @@ -1991,3 +2039,1167 @@ fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) { #[cfg(test)] mod tests; + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use core::cell::Cell; + + use super::*; + use crate::alloc::{AllocError, Global}; + + type OwnedLeaf = NodeRef; + type OwnedInternal = NodeRef; + + const fn empty_leaf() -> LeafNode { + LeafNode { + parent: None, + parent_idx: MaybeUninit::uninit(), + len: 0, + keys: [const { MaybeUninit::uninit() }; CAPACITY], + vals: [const { MaybeUninit::uninit() }; CAPACITY], + } + } + + const fn empty_internal() -> InternalNode { + InternalNode { data: empty_leaf(), edges: [const { MaybeUninit::uninit() }; CAPACITY + 1] } + } + + fn borrow_leaf( + leaf: &mut LeafNode, + ) -> NodeRef, K, V, marker::Leaf> { + NodeRef { height: 0, node: NonNull::from_mut(leaf), _marker: PhantomData } + } + + #[derive(Default)] + struct TrackingAllocator { + freed: Cell, Layout)>>, + } + + // SAFETY: Global handles allocation and deallocation. Bookkeeping does not affect live allocations. + unsafe impl Allocator for TrackingAllocator { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + Global.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // SAFETY: The caller provides a live allocation and its layout. + unsafe { Global.deallocate(ptr, layout) }; + self.freed.set(Some((ptr, layout))); + } + } + + fn leaf_with_len(len: usize) -> OwnedLeaf { + OwnedLeaf::from_new_leaf(Box::new(leaf_for_insertion(len))) + } + + // Initialize exactly the live prefix in bulk, including when len is symbolic. + fn leaf_for_insertion(len: usize) -> LeafNode { + assert!(len <= CAPACITY); + let mut leaf = empty_leaf(); + let keys = kani::any::<[u8; CAPACITY]>(); + let vals = kani::any::<[u8; CAPACITY]>(); + // SAFETY: The arrays have the same capacity. The source bytes are initialized and the + // destination prefixes are separate storage. + unsafe { + ptr::copy_nonoverlapping(keys.as_ptr(), leaf.keys.as_mut_ptr().cast(), len); + ptr::copy_nonoverlapping(vals.as_ptr(), leaf.vals.as_mut_ptr().cast(), len); + } + leaf.len = len as u16; + leaf + } + + /// Constructs a leaf with a Kani-selected length in the complete legal range + /// `0..=CAPACITY`. The owned node has a live allocation, a detached header, + /// and exactly len initialized key/value slots. + /// Key/value contents are symbolic; this helper is used for structural and memory-safety + /// properties rather than position-sensitive content checks. + fn verifier_leaf() -> (OwnedLeaf, usize) { + let len = kani::any_where(|len: &usize| *len <= CAPACITY); + (leaf_with_len(len), len) + } + + /// Constructs a non-empty leaf with a Kani-selected length in `1..=CAPACITY`. + /// A non-empty fixture is required by APIs such as `first_kv` and `last_kv`, + /// whose precondition is that at least one key/value is initialized. + fn verifier_nonempty_leaf() -> (OwnedLeaf, usize) { + let len = kani::any_where(|len: &usize| *len > 0 && *len <= CAPACITY); + (leaf_with_len(len), len) + } + + fn internal_root_with_child( + child: Root, + alloc: A, + ) -> NodeRef { + let height = child.height + 1; + // SAFETY: The fixture initializes the first edge before using the internal node. + let mut parent = unsafe { InternalNode::new(alloc) }; + parent.edges[0].write(child.node); + let (parent, _alloc) = Box::into_non_null_with_allocator(parent); + let mut parent = NodeRef::from_internal(parent, height); + parent.borrow_mut().first_edge().correct_parent_link(); + parent + } + + // Use disjoint leaf subobjects for proofs that only relink the existing children. They live + // through the whole call. Operations that deallocate a child must first give that edge a + // separately allocated node. + fn internal_with_borrowed_children<'a, K: kani::Arbitrary + Copy, V: kani::Arbitrary + Copy>( + parent: &'a mut InternalNode, + children: &'a mut [LeafNode; CAPACITY + 1], + len: usize, + ) -> NodeRef, K, V, marker::Internal> { + assert!(len <= CAPACITY); + const { assert!(CAPACITY == 11) }; + let keys = kani::any::<[K; CAPACITY]>(); + let vals = kani::any::<[V; CAPACITY]>(); + let parent = NonNull::from_mut(parent); + let parent_ptr = parent.as_ptr(); + let child_ptr = children.as_mut_ptr(); + let link_child = move |i: usize| { + // SAFETY: Each call initializes a distinct live child and a distinct edge in the + // separately borrowed parent. + unsafe { + let child = &mut *child_ptr.add(i); + child.parent = Some(parent); + child.parent_idx.write(i as u16); + (*parent_ptr).edges[i].write(NonNull::from_mut(child)); + } + }; + link_child(0); + macro_rules! initialize_entries { + ($($i:literal),*) => { + $(if $i < len { + // SAFETY: The parent is live and exclusively borrowed by the fixture. + let data = unsafe { &mut (*parent_ptr).data }; + data.keys[$i].write(keys[$i]); + data.vals[$i].write(vals[$i]); + link_child($i + 1); + })* + }; + } + initialize_entries!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + // SAFETY: All live key, value, and edge slots of the owned parent storage are initialized. + unsafe { (*parent_ptr).data.len = len as u16 }; + NodeRef::from_internal(parent, 1) + } + + pub(super) fn ascend_link( + node: &NodeRef, + ) -> Option<(NonNull>, usize)> { + let child = NodeRef::as_leaf_ptr(node); + // SAFETY: The precondition checks the child and, if attached, the backlink index. + unsafe { (*child).parent.map(|parent| (parent, (*child).parent_idx.assume_init().into())) } + } + + pub(super) fn can_ascend( + node: &NodeRef, + ) -> bool { + let child = NodeRef::as_leaf_ptr(node); + // SAFETY: The raw field addresses are formed within the live child prefix. The index + // is only read when a parent is present and its value can be read as a u16. + unsafe { + core::ub_checks::can_dereference(child) + && ((*child).parent.is_none() + || (node.height < usize::MAX + && core::ub_checks::can_dereference((*child).parent_idx.as_ptr()))) + } + } + + pub(super) fn can_split_leaf_data( + node: &NodeRef, K, V, Type>, + pivot: usize, + destination: &LeafNode, + ) -> bool { + let source = NodeRef::as_leaf_ptr(node); + // Both split callers allocate a fresh node for the destination. + // SAFETY: Once the leaf prefix is accessible and the pivot is in range, its key and + // value slot addresses can be checked as pointers to initialized K and V. + unsafe { + core::ub_checks::can_write(source) + && core::ub_checks::can_dereference(source) + && !core::ub_checks::same_allocation(source, ptr::from_ref(destination)) + && pivot < node.len() + && node.len() <= CAPACITY + && core::ub_checks::can_dereference((*source).keys[pivot].as_ptr()) + && core::ub_checks::can_dereference((*source).vals[pivot].as_ptr()) + } + } + + // Relinking uses only the initialized edge and the child's LeafNode prefix. The child can + // be a leaf or an internal node, and its old backlink is allowed to be stale. + pub(super) fn can_relink( + node: &NodeRef, K, V, marker::Internal>, + idx: usize, + ) -> bool { + let ptr = NodeRef::as_internal_ptr(node); + node.height() > 0 + && core::ub_checks::can_dereference(ptr) + && idx <= node.len() + && node.len() <= CAPACITY + // SAFETY: The parent is accessible and idx is within its edge array. + && core::ub_checks::can_dereference(unsafe { (*ptr).edges[idx].as_ptr() }) + && core::ub_checks::can_write(relink_child(node, idx)) + } + + pub(super) fn relink_child( + node: &NodeRef, K, V, marker::Internal>, + idx: usize, + ) -> *mut LeafNode { + let ptr = NodeRef::as_internal_ptr(node); + // SAFETY: The contract checks that the internal node and the selected edge are valid. + unsafe { (*ptr).edges[idx].assume_init_read().as_ptr() } + } + + pub(super) fn has_parent_link( + child: *const LeafNode, + parent: NonNull>, + idx: usize, + ) -> bool { + core::ub_checks::can_dereference(child) + // SAFETY: The child is live, and a present backlink includes an initialized index. + && unsafe { + (*child).parent == Some(parent) + && usize::from((*child).parent_idx.assume_init()) == idx + } + } + + #[kani::proof_for_contract( + Handle::, u8, u8, marker::Internal>, marker::Edge>::correct_parent_link + )] + fn harness_correct_parent_link() { + check_parent_link_contract::(); + } + + #[kani::proof_for_contract( + Handle::, (), (), marker::Internal>, marker::Edge>::correct_parent_link + )] + fn harness_correct_parent_link_unit() { + check_parent_link_contract::<(), ()>(); + } + + fn check_parent_link_contract() { + let len = kani::any_where(|len: &usize| *len <= CAPACITY); + let idx = kani::any_where(|idx: &usize| *idx <= len); + let height = kani::any_where(|h: &usize| *h > 0); + let child = NodeRef::::new_leaf(Global); + // SAFETY: Only the selected edge is required by the single-edge repair contract. + let mut parent = unsafe { InternalNode::new(Global) }; + parent.data.len = len as u16; + parent.edges[idx].write(child.node); + let parent_ptr = NonNull::from_mut(&mut *parent); + let parent = NodeRef::from_internal(parent_ptr, height); + // SAFETY: The chosen index is in the initialized edge prefix. + unsafe { Handle::new_edge(parent, idx) }.correct_parent_link(); + assert!(has_parent_link(child.node.as_ptr(), parent_ptr, idx)); + kani::cover(idx == CAPACITY && height > 1, "relink the last edge above the leaf level"); + } + + // Checks the usize instance of the conversions used by the VeriFast root proof. + #[kani::proof] + fn harness_new_internal_height_conversion() { + let height: usize = kani::any(); + match NonZero::new(height) { + None => { + assert_eq!(height, 0); + kani::cover(true, "zero has no NonZero representation"); + } + Some(nonzero) => { + assert_ne!(height, 0); + let converted: usize = nonzero.into(); + assert_eq!(converted, height); + // SAFETY: This branch establishes that height is nonzero. + let unchecked = unsafe { NonZero::new_unchecked(height) }; + assert_eq!(usize::from(unchecked), height); + kani::cover(height == usize::MAX, "round-trip the largest representable height"); + } + } + } + + // The shared loop proof also uses the production inclusive iterator. Its specification + // covers ranges whose end is below usize::MAX, including the empty state after returning + // the last item. + #[kani::proof] + fn harness_relink_inclusive_range_next() { + let start = kani::any::(); + let end = kani::any_where(|end: &usize| *end < usize::MAX); + let range = start..=end; + let mut iter = IntoIterator::into_iter(range.clone()); + assert_eq!(iter, range); + if start <= end { + assert_eq!(iter.next(), Some(start)); + assert_eq!(iter, start + 1..=end); + } else { + assert_eq!(iter.next(), None); + assert_eq!(iter, range); + } + kani::cover(start == end && end == CAPACITY, "yield the last valid child edge"); + kani::cover(start > end, "an empty range leaves the iterator unchanged"); + } + + fn assert_edge_child( + parent: NodeRef, u8, u8, marker::Internal>, + idx: usize, + expected: BoxedNode, + ) { + assert!(idx <= parent.len()); + // SAFETY: The assertions in the caller establish the initialized edge prefix. + let child = unsafe { Handle::new_edge(parent, idx) }.descend(); + assert_eq!(child.node, expected); + assert_eq!(child.height(), parent.height() - 1); + let backlink = child.ascend().ok().unwrap(); + assert_eq!(backlink.idx(), idx); + assert_eq!(backlink.into_node().node, parent.node); + } + + // Harness for `LeafNode::init`. + #[kani::proof_for_contract(LeafNode::init)] + fn harness_leaf_node_init() { + let mut leaf = Box::, _>::new_uninit_in(Global); + unsafe { + LeafNode::init(leaf.as_mut_ptr()); + kani::cover(true, "LeafNode::init was called"); + } + } + + // Harness for `LeafNode::new`. + #[kani::proof] + fn harness_leaf_node_new() { + let leaf = LeafNode::::new(Global); + assert!(leaf.parent.is_none()); + assert_eq!(leaf.len, 0); + kani::cover(true, "LeafNode::new returned an initialized empty leaf"); + } + + // Harness for `InternalNode::new`. + // + // `InternalNode::new` initializes only the embedded `LeafNode` portion. The + // edge array intentionally remains `MaybeUninit`; this harness therefore + // checks the initialized metadata and does not read any edge slot. + #[kani::proof] + fn harness_internal_node_new() { + let node = unsafe { InternalNode::::new(Global) }; + + assert!(node.data.parent.is_none()); + assert_eq!(node.data.len, 0); + kani::cover(true, "InternalNode::new returned initialized metadata"); + } + + // Harness for `NodeRef::as_internal_mut`. + #[kani::proof] + fn harness_node_ref_as_internal_mut() { + let len = kani::any_where(|n: &usize| *n <= CAPACITY); + let mut parent = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let mut internal_view = internal_with_borrowed_children(&mut parent, &mut children, len); + let node = internal_view.as_internal_mut(); + assert_eq!(node.data.len, len as u16); + kani::cover(len == 0, "as_internal_mut checked an empty internal node"); + kani::cover(len == CAPACITY, "as_internal_mut checked a full internal node"); + } + + // Harness for `NodeRef::len`. + #[kani::proof] + fn harness_node_ref_len() { + let (root, len) = verifier_leaf(); + assert_eq!(root.len(), len); + kani::cover(len == 0, "len checked an empty leaf"); + kani::cover(len == CAPACITY, "len checked a full leaf"); + + let mut parent = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let root = internal_with_borrowed_children(&mut parent, &mut children, len); + assert_eq!(root.len(), len); + kani::cover(len == 0, "len checked the prefix of an empty internal node"); + kani::cover(len == CAPACITY, "len checked the prefix of a full internal node"); + } + + // Harness for `NodeRef::first_edge`. + #[kani::proof] + fn harness_node_ref_first_edge() { + let (root, len) = verifier_leaf(); + let edge = root.first_edge(); + assert_eq!(edge.idx(), 0); + kani::cover(len == 0, "first_edge checked an empty leaf"); + kani::cover(len == CAPACITY, "first_edge checked a full leaf"); + } + + // Harness for `NodeRef::last_edge`. + #[kani::proof] + fn harness_node_ref_last_edge() { + let (root, len) = verifier_leaf(); + let edge = root.last_edge(); + assert_eq!(edge.idx(), len); + kani::cover(len == 0, "last_edge checked an empty leaf"); + kani::cover(len == CAPACITY, "last_edge checked a full leaf"); + } + + // Harness for `NodeRef::first_kv`. + #[kani::proof] + fn harness_node_ref_first_kv() { + let (root, len) = verifier_nonempty_leaf(); + let kv = root.first_kv(); + assert_eq!(kv.idx(), 0); + kani::cover(len == 1, "first_kv checked a one-element leaf"); + kani::cover(len == CAPACITY, "first_kv checked a full leaf"); + } + + // Harness for `NodeRef::last_kv`. + #[kani::proof] + fn harness_node_ref_last_kv() { + let (root, len) = verifier_nonempty_leaf(); + let kv = root.last_kv(); + assert_eq!(kv.idx(), len - 1); + kani::cover(len == 1, "last_kv checked a one-element leaf"); + kani::cover(len == CAPACITY, "last_kv checked a full leaf"); + } + + // The empty modifies set checks that following either kind of backlink leaves the tree alone. + #[kani::proof_for_contract(NodeRef::, u8, u8, marker::LeafOrInternal>::ascend)] + fn harness_node_ref_ascend_contract() { + let attached = kani::any::(); + let height = kani::any_where(|h: &usize| !attached || *h < usize::MAX); + let len = kani::any_where(|n: &u16| usize::from(*n) <= CAPACITY); + let idx = kani::any_where(|i: &u16| *i <= len); + let mut leaf = empty_leaf(); + let mut internal = empty_internal(); + let data = if height == 0 { &mut leaf } else { &mut internal.data }; + let mut parent = empty_internal(); + let parent_ptr = NonNull::from_mut(&mut parent); + if attached { + parent.data.len = len; + parent.edges[usize::from(idx)].write(NonNull::from_mut(data)); + data.parent = Some(parent_ptr); + data.parent_idx.write(idx); + } + let mut child = borrow_leaf::(data).forget_type(); + child.height = height; + let result = child.ascend(); + kani::cover(!attached && result.is_err(), "ascend from a detached root"); + kani::cover( + attached && height > 0 && usize::from(idx) == CAPACITY && result.is_ok(), + "ascend from the last internal child of a full node", + ); + } + + // Harness for `NodeRef::into_leaf`. + #[kani::proof] + fn harness_node_ref_into_leaf() { + let (root, len) = verifier_leaf(); + let leaf = root.reborrow().into_leaf(); + assert_eq!(leaf.len as usize, len); + kani::cover(len == 0, "into_leaf checked an empty leaf"); + kani::cover(len == CAPACITY, "into_leaf checked a full leaf"); + } + + // Harness for `NodeRef::keys`. + #[kani::proof] + fn harness_node_ref_keys() { + let (root, len) = verifier_leaf(); + let view = root.reborrow(); + let keys = view.keys(); + assert_eq!(keys.len(), len); + if len > 0 { + let idx = kani::any_where(|i: &usize| *i < len); + assert!(ptr::eq(&keys[idx], view.into_leaf().keys[idx].as_ptr())); + } + kani::cover(len == 0, "keys checked an empty leaf"); + kani::cover(len == CAPACITY, "keys checked a full leaf"); + } + + // Harness for `NodeRef::as_leaf_mut`. + #[kani::proof] + fn harness_node_ref_as_leaf_mut() { + let (mut root, len) = verifier_leaf(); + let mut view = root.borrow_mut(); + let leaf = view.as_leaf_mut(); + assert_eq!(leaf.len as usize, len); + kani::cover(len == 0, "as_leaf_mut checked an empty leaf"); + kani::cover(len == CAPACITY, "as_leaf_mut checked a full leaf"); + } + + // Harness for `NodeRef::into_leaf_mut`. + #[kani::proof] + fn harness_node_ref_into_leaf_mut() { + let (mut root, len) = verifier_leaf(); + let view = root.borrow_mut(); + let leaf = view.into_leaf_mut(); + assert_eq!(leaf.len as usize, len); + kani::cover(len == 0, "into_leaf_mut checked an empty leaf"); + kani::cover(len == CAPACITY, "into_leaf_mut checked a full leaf"); + } + + // Harness for `NodeRef::as_leaf_dying`. + #[kani::proof] + fn harness_node_ref_as_leaf_dying() { + let (mut root, len) = verifier_leaf(); + let mut dying = root.into_dying(); + let leaf = dying.as_leaf_dying(); + assert_eq!(leaf.len as usize, len); + kani::cover(len == 0, "as_leaf_dying checked an empty leaf"); + kani::cover(len == CAPACITY, "as_leaf_dying checked a full leaf"); + } + + // Harness for `NodeRef::pop_internal_level`. + #[kani::proof] + fn harness_node_ref_pop_internal_level() { + let height = kani::any_where(|height: &usize| *height > 0); + let (leaf, _) = verifier_leaf(); + let leaf = leaf.forget_type(); + let mut child = + if height == 1 { leaf } else { internal_root_with_child(leaf, Global).forget_type() }; + // Pop reads the first edge and clears the retained child's backlink. + child.height = height - 1; + let child_ptr = child.node; + let child_len = child.len(); + let mut root = internal_root_with_child(child, Global).forget_type(); + root.pop_internal_level(Global); + assert_eq!(root.node, child_ptr); + assert_eq!(root.height(), height - 1); + assert_eq!(root.len(), child_len); + assert!(root.reborrow().ascend().is_err()); + kani::cover(height == 1, "pop an internal root above a leaf"); + kani::cover(height == usize::MAX, "pop an internal root above an internal child"); + } + + // Harness for `NodeRef::push`. + #[kani::proof] + fn harness_node_ref_push() { + let (mut root, _) = verifier_leaf(); + let before = root.len(); + if before < CAPACITY { + let (key, val) = kani::any::<(u8, u8)>(); + let inserted = root.borrow_mut().push(key, val); + assert_eq!(root.len(), before + 1); + let (stored_key, stored_val) = root.reborrow().last_kv().into_kv(); + assert!(ptr::eq(inserted, stored_val)); + assert_eq!((*stored_key, *stored_val), (key, val)); + kani::cover(before == 0, "push checked insertion into an empty leaf"); + kani::cover(before == CAPACITY - 1, "push checked insertion into a nearly full leaf"); + } + } + + #[kani::proof] + fn harness_node_ref_push_internal() { + let len = kani::any_where(|n: &usize| *n < CAPACITY); + let height = kani::any_where(|h: &usize| *h > 0); + let leaf = OwnedLeaf::new_leaf(Global).forget_type(); + let mut incoming = + if height == 1 { leaf } else { internal_root_with_child(leaf, Global).forget_type() }; + // Push reads only the incoming root and writes its backlink. + incoming.height = height - 1; + let child = incoming.node; + let mut storage = empty_internal(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let mut parent = internal_with_borrowed_children(&mut storage, &mut children, len); + parent.height = height; + let (key, val) = kani::any(); + parent.push(key, val, incoming); + + let parent = parent.reborrow(); + assert_eq!(parent.len(), len + 1); + assert_eq!(parent.last_kv().into_kv(), (&key, &val)); + assert_edge_child(parent, len + 1, child); + kani::cover(len + 1 == CAPACITY, "push into the last available internal slot"); + kani::cover(height > 1, "push a subtree into an internal node"); + } + + // Harness for `Handle::left_edge`. + #[kani::proof] + fn harness_handle_left_edge() { + let (root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: idx identifies an initialized KV. + let edge = unsafe { Handle::new_kv(root.reborrow(), idx) }.left_edge(); + assert_eq!(edge.idx(), idx); + assert_eq!(edge.into_node().node, root.node); + kani::cover(idx + 1 == CAPACITY, "left_edge from the last KV of a full node"); + } + + // Harness for `Handle::right_edge`. + #[kani::proof] + fn harness_handle_right_edge() { + let (root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: idx identifies an initialized KV. + let edge = unsafe { Handle::new_kv(root.reborrow(), idx) }.right_edge(); + assert_eq!(edge.idx(), idx + 1); + assert_eq!(edge.into_node().node, root.node); + kani::cover(idx + 1 == CAPACITY, "right_edge from the last KV of a full node"); + } + + // Harness for `Handle::left_kv`. + #[kani::proof] + fn harness_handle_left_kv() { + let (root, len) = verifier_leaf(); + let idx = kani::any_where(|i: &usize| *i <= len); + // SAFETY: Leaves have an edge at every position from 0 through len. + match unsafe { Handle::new_edge(root.reborrow(), idx) }.left_kv() { + Ok(kv) => { + assert!(idx > 0); + assert_eq!(kv.idx(), idx - 1); + assert_eq!(kv.into_node().node, root.node); + kani::cover(idx == len, "left_kv succeeds at the last edge"); + } + Err(edge) => { + assert_eq!(idx, 0); + assert_eq!(edge.idx(), idx); + assert_eq!(edge.into_node().node, root.node); + kani::cover(len == 0, "left_kv returns the edge of an empty node"); + } + } + } + + // Harness for `Handle::right_kv`. + #[kani::proof] + fn harness_handle_right_kv() { + let (root, len) = verifier_leaf(); + let idx = kani::any_where(|i: &usize| *i <= len); + // SAFETY: Leaves have an edge at every position from 0 through len. + match unsafe { Handle::new_edge(root.reborrow(), idx) }.right_kv() { + Ok(kv) => { + assert!(idx < len); + assert_eq!(kv.idx(), idx); + assert_eq!(kv.into_node().node, root.node); + kani::cover(idx == 0, "right_kv succeeds at the first edge"); + } + Err(edge) => { + assert_eq!(idx, len); + assert_eq!(edge.idx(), idx); + assert_eq!(edge.into_node().node, root.node); + kani::cover(len == CAPACITY, "right_kv returns the last edge of a full node"); + } + } + } + + // Harness for `Handle::descend`. + #[kani::proof] + fn harness_handle_descend() { + let len = kani::any_where(|n: &usize| *n <= CAPACITY); + let mut parent = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let internal = internal_with_borrowed_children(&mut parent, &mut children, len); + let idx = kani::any_where(|i: &usize| *i <= len); + let child_ptr = relink_child(&internal, idx); + // SAFETY: The fixture initializes each edge up to and including len. + let edge = unsafe { Handle::new_edge(internal.reborrow(), idx) }.forget_node_type(); + let ForceResult::Internal(edge) = edge.force() else { + panic!("the edge belongs to an internal node"); + }; + assert_eq!(edge.idx(), idx); + let descended = edge.descend(); + assert_eq!(descended.height(), 0); + assert_eq!(descended.node.as_ptr(), child_ptr); + kani::cover(idx == CAPACITY, "descend through the last edge of a full node"); + } + + #[kani::proof] + fn harness_consider_for_balancing() { + let len = kani::any_where(|n: &usize| 0 < *n && *n <= CAPACITY); + let idx = kani::any_where(|i: &usize| *i < len); + let mut storage = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let parent = internal_with_borrowed_children(&mut storage, &mut children, len); + let parent_ptr = parent.node; + let left = relink_child(&parent, idx); + let right = relink_child(&parent, idx + 1); + + // SAFETY: The separator and both adjacent edges belong to the active prefix. + let context = unsafe { Handle::new_kv(parent, idx) }.consider_for_balancing(); + assert_eq!((context.parent.node.node, context.parent.idx()), (parent_ptr, idx)); + assert_eq!(context.left_child.node.as_ptr(), left); + assert_eq!(context.right_child.node.as_ptr(), right); + kani::cover(idx == 0, "balance around the first separator"); + kani::cover(idx + 1 == CAPACITY, "balance around the last separator of a full node"); + } + + #[kani::proof] + fn harness_choose_parent_kv() { + let len = kani::any_where(|n: &usize| 0 < *n && *n <= CAPACITY); + let idx = kani::any_where(|i: &usize| *i <= len); + let attached = kani::any::(); + let mut detached = empty_leaf::(); + let mut parent = empty_internal(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let parent = internal_with_borrowed_children(&mut parent, &mut children, len); + let parent_ptr = parent.node; + let separator = idx.saturating_sub(1); + // SAFETY: The separator and both adjacent edges belong to the active prefix. + let (left, right) = unsafe { + let kv = Handle::new_kv(parent.reborrow(), separator); + (kv.left_edge().descend().node, kv.right_edge().descend().node) + }; + let child = if attached { + // SAFETY: idx selects an initialized edge, and no shared view remains live. + unsafe { Handle::new_edge(parent, idx) }.descend() + } else { + borrow_leaf(&mut detached).forget_type() + }; + let original = child.node; + + let context = match child.choose_parent_kv() { + Ok(LeftOrRight::Left(context)) => { + assert!(attached && idx > 0); + context + } + Ok(LeftOrRight::Right(context)) => { + assert!(attached && idx == 0); + context + } + Err(root) => { + assert!(!attached && root.node == original); + kani::cover(!attached, "a detached root has no parent separator"); + return; + } + }; + assert_eq!((context.parent.node.node, context.parent.idx()), (parent_ptr, separator)); + assert_eq!((context.left_child.node, context.right_child.node), (left, right)); + kani::cover(idx == 0, "choose the separator to the right of the first child"); + kani::cover(idx == CAPACITY, "choose the separator to the left of the last child"); + } + + // Harness for `Handle::into_kv`. + #[kani::proof] + fn harness_handle_into_kv() { + let (root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + let leaf = root.reborrow().into_leaf(); + // SAFETY: idx is in the initialized prefix of both arrays. + let (key, value) = unsafe { Handle::new_kv(root.reborrow(), idx) }.into_kv(); + assert!(ptr::eq(key, leaf.keys[idx].as_ptr())); + assert!(ptr::eq(value, leaf.vals[idx].as_ptr())); + kani::cover(idx + 1 == CAPACITY, "into_kv reads the last pair of a full node"); + } + + // Harness for `Handle::key_mut`. + #[kani::proof] + fn harness_handle_key_mut() { + let (mut root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + let key = kani::any(); + // SAFETY: idx is in the initialized prefix. + *unsafe { Handle::new_kv(root.borrow_mut(), idx) }.key_mut() = key; + assert_eq!(root.reborrow().keys()[idx], key); + kani::cover(idx + 1 == CAPACITY, "key_mut writes the last key of a full node"); + } + + // Harness for `Handle::into_val_mut`. + #[kani::proof] + fn harness_handle_into_val_mut() { + let (mut root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + let val = kani::any(); + // SAFETY: idx is in the initialized prefix. + *unsafe { Handle::new_kv(root.borrow_mut(), idx) }.into_val_mut() = val; + // SAFETY: The same slot remains initialized after writing a value through it. + assert_eq!(unsafe { root.reborrow().into_leaf().vals[idx].assume_init() }, val); + kani::cover(idx + 1 == CAPACITY, "into_val_mut writes the last value of a full node"); + } + + // Harness for `Handle::into_kv_mut`. + #[kani::proof] + fn harness_handle_into_kv_mut() { + let (mut root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: Both slots at idx are initialized and uniquely borrowed. + let (key, value) = unsafe { Handle::new_kv(root.borrow_mut(), idx) }.into_kv_mut(); + *key = 1; + *value = 2; + assert_eq!((*key, *value), (1, 2)); + kani::cover(idx + 1 == CAPACITY, "into_kv_mut writes both fields of the last pair"); + } + + // Harness for `Handle::into_kv_valmut`. + #[kani::proof] + fn harness_handle_into_kv_valmut() { + let len = kani::any_where(|n: &usize| (2..=CAPACITY).contains(n)); + let mut root = leaf_with_len(len); + let first = kani::any_where(|i: &usize| *i < len); + let second = kani::any_where(|i: &usize| *i < len && *i != first); + let first_key = root.reborrow().keys()[first]; + let second_key = root.reborrow().keys()[second]; + let view = root.borrow_valmut(); + // SAFETY: As in IterMut, duplicate the view only to visit two distinct initialized slots. + let (key1, val1) = unsafe { Handle::new_kv(ptr::read(&view), first) }.into_kv_valmut(); + // SAFETY: second is initialized and distinct from the outstanding value reference. + let (key2, val2) = unsafe { Handle::new_kv(view, second) }.into_kv_valmut(); + *val1 = 1; + *val2 = 2; + assert_eq!((*key1, *key2), (first_key, second_key)); + assert_eq!((*val1, *val2), (1, 2)); + kani::cover(first + 1 == CAPACITY && second == 0, "two value references coexist"); + } + + // Harness for `Handle::kv_mut`. + #[kani::proof] + fn harness_handle_kv_mut() { + let (mut root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: idx is in the initialized prefix. + let mut handle = unsafe { Handle::new_kv(root.borrow_mut(), idx) }; + let (key, value) = handle.kv_mut(); + *key = 1; + *value = 2; + assert_eq!((*key, *value), (1, 2)); + let (key, value) = handle.reborrow().into_kv(); + assert_eq!((*key, *value), (1, 2)); + kani::cover(idx + 1 == CAPACITY, "kv_mut writes both fields of the last pair"); + } + + #[kani::proof] + fn harness_handle_into_key_val() { + let (leaf, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: idx selects an initialized pair in both views. The shared view ends before + // moving the pair, and the dying node is never accessed again. + let (key, value) = unsafe { Handle::new_kv(leaf.reborrow(), idx) }.into_kv(); + let expected = (*key, *value); + let dying = leaf.into_dying(); + let actual = unsafe { Handle::new_kv(dying, idx).into_key_val() }; + assert_eq!(actual, expected); + kani::cover(len == CAPACITY && idx == len - 1, "extract the final pair of a full node"); + } + + #[kani::proof] + fn harness_handle_remove_leaf() { + let (mut leaf, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: Both handles selected below refer to initialized pairs. + let (expected, next) = unsafe { + let view = leaf.reborrow(); + let (key, val) = Handle::new_kv(view, idx).forget_node_type().into_kv(); + let next = (idx + 1 < len).then(|| { + let (key, val) = Handle::new_kv(view, idx + 1).into_kv(); + (*key, *val) + }); + ((*key, *val), next) + }; + + let leaf_ptr = leaf.node; + // SAFETY: The removed KV was initialized by the fixture. + let (removed, edge) = unsafe { Handle::new_kv(leaf.borrow_mut(), idx) }.remove(); + let edge = edge.forget_node_type(); + // SAFETY: The edge returned by leaf removal still points into the leaf. + let edge = unsafe { edge.cast_to_leaf_unchecked() }; + assert_eq!(removed, expected); + assert_eq!(edge.idx(), idx); + assert_eq!(edge.node.node, leaf_ptr); + assert_eq!(edge.reborrow().into_node().len(), len - 1); + if let Some(next) = next { + let (key, val) = edge.reborrow().right_kv().ok().unwrap().into_kv(); + assert_eq!((*key, *val), next); + } + kani::cover(idx == 0 && len == CAPACITY, "remove shifts the longest leaf suffix"); + kani::cover(idx + 1 == len, "remove returns the last edge"); + } + + #[kani::proof] + fn harness_deallocate_leaf_root() { + let alloc = TrackingAllocator::default(); + let root = OwnedLeaf::new_leaf(&alloc).forget_type().into_dying(); + let ptr = root.node; + // SAFETY: The empty node was allocated by alloc and has no live handles. + let parent = unsafe { root.deallocate_and_ascend(&alloc) }; + assert!(parent.is_none()); + assert_eq!(alloc.freed.get(), Some((ptr.cast(), Layout::new::>()))); + kani::cover(parent.is_none(), "deallocate a leaf root without a parent"); + } + + #[kani::proof] + fn harness_deallocate_attached_child() { + let internal = kani::any::(); + let alloc = TrackingAllocator::default(); + let leaf = OwnedLeaf::new_leaf(&alloc).forget_type(); + let child = + if internal { internal_root_with_child(leaf, &alloc).forget_type() } else { leaf }; + let child_ptr = child.node; + let parent = internal_root_with_child(child, &alloc).into_dying(); + let parent_ptr = parent.node; + let child = parent.first_edge().descend(); + // SAFETY: The child came from alloc, and the proof uses only the parent after freeing it. + let edge = unsafe { child.deallocate_and_ascend(&alloc) }.unwrap(); + assert_eq!((edge.node.node, edge.idx()), (parent_ptr, 0)); + let layout = if internal { + Layout::new::>() + } else { + Layout::new::>() + }; + assert_eq!(alloc.freed.get(), Some((child_ptr.cast(), layout))); + kani::cover(internal, "deallocate an internal node and recover the parent edge"); + kani::cover(!internal, "deallocate a leaf and recover the parent edge"); + } + + #[kani::proof] + fn harness_move_suffix_projections() { + let len = kani::any_where(|n: &usize| *n <= CAPACITY); + let cut = kani::any_where(|i: &usize| *i <= len); + let height = kani::any_where(|h: &usize| *h > 0); + let mut storage = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let mut source = internal_with_borrowed_children(&mut storage, &mut children, len); + source.height = height; + let base = NodeRef::as_internal_ptr(&source); + // SAFETY: The internal allocation is live and all these addresses lie in its storage. + let (key_base, val_base, edge_base, length) = unsafe { + ( + (&raw const (*base).data.keys).cast::>(), + (&raw const (*base).data.vals).cast::>(), + (&raw const (*base).edges).cast::>>(), + &raw const (*base).data.len, + ) + }; + let moved = len - cut; + + // SAFETY: The handle selects an initialized edge and the borrowed node is used exclusively. + let mut edge = unsafe { Handle::new_edge(source.forget_type(), cut) }; + // SAFETY: There is no other active borrow of this handle. + let mut node = unsafe { edge.reborrow_mut() }.into_node(); + assert_eq!(node.height(), height); + assert_eq!(node.len(), len); + assert!(ptr::addr_eq(node.len_mut(), length)); + + // SAFETY: All the ranges are within the respective node arrays, including when empty. + let keys = unsafe { node.key_area_mut(cut..len) }; + assert_eq!(keys.len(), moved); + assert!(ptr::addr_eq(keys.as_ptr(), key_base.wrapping_add(cut))); + // SAFETY: The moved prefix is at most CAPACITY elements long. + let vals = unsafe { node.val_area_mut(..moved) }; + assert_eq!(vals.len(), moved); + assert!(ptr::addr_eq(vals.as_ptr(), val_base)); + let ForceResult::Internal(mut node) = node.force() else { + panic!("positive height selects the internal layout"); + }; + // SAFETY: Both endpoints are in 0..=CAPACITY + 1 and cut <= len. + let edges = unsafe { node.edge_area_mut(cut + 1..len + 1) }; + assert_eq!(edges.len(), moved); + assert!(ptr::addr_eq(edges.as_ptr(), edge_base.wrapping_add(cut + 1))); + kani::cover( + cut == 0 && len == CAPACITY && height > 1, + "project the full suffix at an internal level", + ); + kani::cover(cut == CAPACITY && len == CAPACITY, "project the empty suffix at the end"); + } + + #[kani::proof] + fn harness_insert_leaf_step_fit() { + let len = kani::any_where(|n: &usize| *n < CAPACITY); + let idx = kani::any_where(|i: &usize| *i <= len); + let mut leaf = leaf_for_insertion(len); + let (key, val) = kani::any::<(u8, u8)>(); + // SAFETY: idx is a valid insertion edge in this leaf. + let edge = unsafe { Handle::new_edge(borrow_leaf(&mut leaf), idx) }; + let (split, dormant) = edge.insert(key, val, Global); + assert!(split.is_none()); + // SAFETY: Insertion is complete and the leaf is exclusively borrowed by the handle. + let handle = unsafe { dormant.awaken() }; + assert_eq!(handle.idx(), idx); + let (stored_key, stored_val) = handle.reborrow().into_kv(); + assert_eq!((*stored_key, *stored_val), (key, val)); + assert_eq!(usize::from(leaf.len), len + 1); + kani::cover(len == 0, "insert into an empty leaf"); + kani::cover(len + 1 == CAPACITY && idx < len, "insert by shifting an occupied leaf suffix"); + } + + #[kani::proof] + fn harness_splitpoint_bounds() { + let edge = kani::any_where(|i: &usize| *i <= CAPACITY); + let (middle, insertion) = splitpoint(edge); + assert!((KV_IDX_CENTER - 1..=KV_IDX_CENTER + 1).contains(&middle)); + assert!(middle < CAPACITY); + let left_len = middle; + let right_len = CAPACITY - middle - 1; + assert!(left_len < CAPACITY && right_len < CAPACITY); + assert!(right_len + 1 <= 7); + match insertion { + LeftOrRight::Left(idx) => { + assert!(idx <= left_len); + assert_eq!(idx, edge); + assert!(left_len + 1 - idx <= 7); + } + LeftOrRight::Right(idx) => { + assert!(idx <= right_len); + assert_eq!(middle + 1 + idx, edge); + assert!(right_len + 1 - idx <= 7); + } + } + kani::cover(edge == 0, "a full node can split at the first insertion edge"); + kani::cover(edge == CAPACITY, "a full node can split at the last insertion edge"); + } + + #[kani::proof_for_contract(slice_insert::)] + fn harness_slice_insert_frame() { + // A node has at most CAPACITY KV slots and CAPACITY + 1 edge slots. + let len = usize::from(kani::any_where(|n: &u8| *n > 0 && usize::from(*n) <= CAPACITY + 1)); + let idx = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let observed = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let mut slots = MaybeUninit::new(kani::any::<[u8; CAPACITY + 1]>()).transpose(); + let value = kani::any(); + // SAFETY: The observed prefix element is initialized. Elements after idx move right. + let expected = if observed == idx { + value + } else { + unsafe { slots[observed - usize::from(observed > idx)].assume_init() } + }; + slots[len - 1] = MaybeUninit::uninit(); + // SAFETY: The prefix to be shifted is initialized, and idx is in bounds. + unsafe { slice_insert(&mut slots[..len], idx, value) }; + // SAFETY: Insertion initializes the entire active prefix. + assert_eq!(unsafe { slots[observed].assume_init() }, expected); + kani::cover(idx == 0 && len == CAPACITY + 1, "shift a full edge array's live prefix"); + } + + #[kani::proof_for_contract(slice_insert::>>)] + fn harness_slice_insert_edge_frame() { + let len = usize::from(kani::any_where(|n: &u8| *n > 0 && usize::from(*n) <= CAPACITY + 1)); + let idx = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let mut child = empty_leaf::(); + let mut incoming = empty_leaf(); + let mut slots = [MaybeUninit::new(NonNull::from_mut(&mut child)); CAPACITY + 1]; + slots[len - 1] = MaybeUninit::uninit(); + // SAFETY: The active range has an initialized prefix with an open last slot, and idx + // selects a position in the range. + unsafe { slice_insert(&mut slots[..len], idx, NonNull::from_mut(&mut incoming)) }; + kani::cover(idx == 0 && len == CAPACITY + 1, "shift the largest pointer suffix"); + } + + #[kani::proof_for_contract(move_to_slice::>>)] + fn harness_move_edge_slice_frame() { + let len = usize::from(kani::any_where(|n: &u8| usize::from(*n) <= CAPACITY + 1)); + let from = usize::from(kani::any_where(|i: &u8| usize::from(*i) <= CAPACITY + 1 - len)); + let to = usize::from(kani::any_where(|i: &u8| usize::from(*i) <= CAPACITY + 1 - len)); + let mut child = empty_leaf::(); + let mut src = [MaybeUninit::new(NonNull::from_mut(&mut child)); CAPACITY + 1]; + let mut dst = [MaybeUninit::uninit(); CAPACITY + 1]; + move_to_slice(&mut src[from..from + len], &mut dst[to..to + len]); + kani::cover(from == 1 && to == 0 && len == CAPACITY, "copy an internal edge suffix"); + } + + // Check the payload movement separately from child-edge relinking. The write set preserves + // both backlinks and any payload in a descendant. + #[kani::proof_for_contract( + Handle::, u8, u8, marker::Internal>, marker::KV>::split_leaf_data + )] + #[kani::solver(minisat)] + fn harness_split_leaf_data_frame() { + let len = usize::from(kani::any_where(|n: &u8| *n > 0 && usize::from(*n) <= CAPACITY)); + let pivot = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let observed = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let height = kani::any_where(|h: &usize| *h > 0); + let mut source = InternalNode { data: leaf_for_insertion(len), ..empty_internal() }; + let mut right = empty_internal(); + // SAFETY: observed lies in the initialized prefix of source. + let expected = unsafe { + (source.data.keys[observed].assume_init(), source.data.vals[observed].assume_init()) + }; + let node = NodeRef::from_internal(NonNull::from_mut(&mut source), height); + // SAFETY: pivot identifies an initialized KV slot. + let mut pivot_handle = unsafe { Handle::new_kv(node, pivot) }; + let promoted = pivot_handle.split_leaf_data(&mut right.data); + + let stored = if observed == pivot { + promoted + } else { + let (data, slot) = if observed < pivot { + (&source.data, observed) + } else { + (&right.data, observed - pivot - 1) + }; + assert!(slot < usize::from(data.len)); + // SAFETY: The retained slot is in the live prefix of the corresponding half. + unsafe { (data.keys[slot].assume_init(), data.vals[slot].assume_init()) } + }; + assert_eq!(stored, expected); + kani::cover( + len == CAPACITY && pivot == 0 && observed == CAPACITY - 1, + "move the last pair of the maximum length KV suffix", + ); + } + + #[kani::proof] + fn harness_insert_leaf_step_split() { + let idx = usize::from(kani::any_where(|i: &u8| usize::from(*i) <= CAPACITY)); + let ancestor_idx = kani::any_where(|i: &u16| usize::from(*i) <= CAPACITY); + let attached = kani::any::(); + let mut leaf = leaf_for_insertion(CAPACITY); + let mut ancestor = empty_internal(); + let ancestor_ptr = NonNull::from_mut(&mut ancestor); + if attached { + leaf.parent = Some(ancestor_ptr); + leaf.parent_idx.write(ancestor_idx); + ancestor.data.len = ancestor_idx; + ancestor.edges[usize::from(ancestor_idx)].write(NonNull::from_mut(&mut leaf)); + } + let (pivot, insertion) = splitpoint(idx); + // SAFETY: The full leaf initializes every pair, including the selected pivot. + let promoted = unsafe { (leaf.keys[pivot].assume_init(), leaf.vals[pivot].assume_init()) }; + let leaf = borrow_leaf(&mut leaf); + let original = leaf.node; + let (key, val) = kani::any::<(u8, u8)>(); + // SAFETY: Every edge of the full leaf is available for insertion. + let edge = unsafe { Handle::new_edge(leaf, idx) }; + let (split, dormant) = edge.insert(key, val, Global); + let split = split.expect("a full leaf splits"); + assert_eq!(split.left.node, original); + assert_ne!(split.right.node, original); + assert_eq!(split.left.height(), 0); + assert_eq!(split.right.height(), 0); + assert_eq!(split.left.len() + split.right.len(), CAPACITY); + assert_eq!(split.kv, promoted); + match split.left.reborrow().ascend() { + Ok(edge) => { + assert!(attached); + assert_eq!(edge.node.node, ancestor_ptr.cast()); + assert_eq!(edge.idx(), usize::from(ancestor_idx)); + assert_eq!(edge.descend().node, original); + } + Err(root) => { + assert!(!attached); + assert_eq!(root.node, original); + } + } + assert!(split.right.reborrow().ascend().is_err()); + let (destination, slot) = match insertion { + LeftOrRight::Left(slot) => (split.left.node, slot), + LeftOrRight::Right(slot) => (split.right.node, slot), + }; + assert_eq!((dormant.node.node, dormant.idx()), (destination, slot)); + drop(split); + // SAFETY: No split handle or reference into either result node is used again. + let inserted = unsafe { dormant.awaken() }; + let (stored_key, stored_val) = inserted.reborrow().into_kv(); + assert_eq!((*stored_key, *stored_val), (key, val)); + kani::cover( + attached && idx == EDGE_IDX_LEFT_OF_CENTER, + "split an attached leaf to the left", + ); + kani::cover( + !attached && idx == EDGE_IDX_RIGHT_OF_CENTER, + "split the leaf root to the right", + ); + } + + // The parent shifts in do_merge depend only on its occupancy and separator index. + // Exercise every such pair on the actual slice_remove helper, independently of the + // child-occupancy proofs and the relink-range proof. + #[kani::proof] + fn harness_merge_parent_shift_ranges() { + let len = kani::any_where(|n: &usize| *n > 0 && *n <= CAPACITY); + let idx = kani::any_where(|i: &usize| *i < len); + let original_keys = kani::any::<[u8; CAPACITY]>(); + let mut keys = MaybeUninit::new(original_keys).transpose(); + // Use pointer-sized words to check the edge ranges. VeriFast checks the pointer moves + // and repairs in the production merge. + let original_edges = kani::any::<[usize; CAPACITY + 1]>(); + let mut edges = MaybeUninit::new(original_edges).transpose(); + + // SAFETY: The source slices contain only initialized slots, and len and idx + // specify an existing separator and its right edge. + let (key, removed) = unsafe { + (slice_remove(&mut keys[..len], idx), slice_remove(&mut edges[..=len], idx + 1)) + }; + assert!(key == original_keys[idx], "remove the parent separator"); + assert!(removed == original_edges[idx + 1], "remove the edge right of the separator"); + kani::cover(len == CAPACITY && idx == 0, "shift the longest parent suffix"); + kani::cover(idx + 1 == len, "remove the final separator with no trailing shift"); + } +} diff --git a/verifast-proofs/README.md b/verifast-proofs/README.md index 096d3e32e9061..1b538ca9d4831 100644 --- a/verifast-proofs/README.md +++ b/verifast-proofs/README.md @@ -6,12 +6,15 @@ 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/) +- [B-tree node insertion, balancing, and destruction](alloc/collections/btree/node.rs/) See each proof's accompanying README for a tour of the proof and applicable caveats. ## Maintaining the proofs - If the VeriFast CI action fails because of a failing diff, please run `cd verifast-proofs; ./patch-verifast-proofs.sh` to fix the problem. +For LinkedList and RawVec, use `cd verifast-proofs && ./patch-verifast-proofs.sh` to refresh +the snapshots after a diff failure. For B-tree nodes, review the source and +comparison diffs together using the [B-tree instructions](alloc/collections/btree/node.rs/README.md#maintaining-the-comparison). ## `-skip_specless_fns` @@ -23,7 +26,7 @@ To verify a function in a file library/crate/src/mod/file 1. Copy that file to verifast-proofs/crate/mod/file.rs/original/file.rs as well as to verifast-proofs/crate/mod/file.rs/verified/file.rs. 2. Create a file verifast-proofs/crate/mod/file.rs/original/lib.rs to serve as crate root for verification, and include mod file;. (See the existing proofs for examples.) Copy it to verifast-proofs/crate/mod/file.rs/verified/lib.rs. 2. Add a VeriFast specification to the function(s) you want to verify, and any other VeriFast annotations to make the proof go through, in verifast-proofs/crate/mod/file.rs/verified/file.rs. While doing so, you will need to change the code slightly so as to be able to insert ghost commands in the correct places. -3. Add commands for checking your proof to `verifast-proofs/check-verifast-proofs.mysh`. This includes the following: +3. Add the following checks to [the VeriFast runner](check-verifast-proofs.sh). 1. A `verifast` invocation for checking the VeriFast proof. 2. A `refinement-checker` invocation for checking that the code changes you made in the verified version do not change the meaning of the program. Specifically, this tool checks that the original code *refines* the verified code, i.e. that each behavior of a function in the original version is also a behavior of the corresponding function in the verified version. As a result, if the verified version has been verified to have no bad behaviors, the original version also has no bad behaviors. 3. A `diff` invocation for checking that the version in `original` is identical to the original version in `library`. @@ -56,4 +59,4 @@ We then: Separating steps 2) and 3) lets us distinguish between CI failures caused by incorrect modifications to the verified files (failure in step 2) versus a proof that was once correct, but is just out of date (failure in step 3). Without the copy of the original file, when the `library/` files change, there would be no easy way to tell whether the VeriFast proofs are wrong or just stale. -The [VeriFast](../.github/workflows/verifast.yml) GitHub action will run `verifast-proofs/check-verifast-proofs.mysh`. Check that file to see which version of VeriFast is used. +The [VeriFast](../.github/workflows/verifast.yml) GitHub action runs [check-verifast-proofs.sh](check-verifast-proofs.sh). Each proof's runner selects its VeriFast version. diff --git a/verifast-proofs/alloc/collections/btree/node.rs/README.md b/verifast-proofs/alloc/collections/btree/node.rs/README.md new file mode 100644 index 0000000000000..90da268a0acbd --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/README.md @@ -0,0 +1,182 @@ +# B-tree node proofs for Challenge 4 + +The proofs use the node's `CAPACITY` for its storage and let the tree height +and ancestor chain vary. A balancing operation owns the parent, the two +adjacent child nodes, and the headers it updates. The rest of each subtree +stays with the caller. + +| Production function | Inductive proof entry | +| --- | --- | +| `NodeRef::new_internal` | `new_internal` owns the fresh root, initializes edge zero, and links the supplied subtree root at a symbolic height. The proof uses the production height conversion and calls the inclusive relink proof. | +| `Handle::insert_recursing` | `insert_recursing_for_root` invokes the production leaf dispatcher, the unbounded propagation loop and the root installation used by the three in-tree callers. The loop tracks the pending split, unvisited ancestors, completed levels, and dormant leaf slot. | +| `BalancingContext::do_merge` | The proof verifies the full production method with symbolic child heights and occupancies. It transfers the separator, repairs both edge ranges, releases the right node, and checks the normal and unwind exits. | +| `BalancingContext::merge_tracking_child_edge` | The proof checks the production index assertion, calls the proved merge with its child-returning callback, and preserves the tracked edge and its backlink on either side. | +| `BalancingContext::bulk_steal_left` | `bulk_steal_left_production` shifts the receiving key, value, and edge prefixes, transfers the donated entries to the recipient and parent, and repairs the right child's links. | +| `BalancingContext::bulk_steal_right` | `bulk_steal_right_production` transfers the right child's prefix, shifts its remaining entries left, and repairs both required edge ranges. | +| `BalancingContext::steal_left` | `steal_left_production` calls the verified bulk method with count one and verifies the offset in the returned right-child edge handle. | +| `BalancingContext::steal_right` | `steal_right_production` calls the verified bulk method with count one and constructs the handle at the original left-child edge index. | +| `NodeRef::correct_childrens_parent_links` and `correct_all_childrens_parent_links` | The half-open and inclusive range invariants track the repaired prefix and the remaining child headers. | +| `Handle::move_suffix` | `move_suffix_production` preserves the receiving node's first edge and repairs the transferred interval. | +| `NodeRef::drop_kvs` | `drop_remaining` and `resume_drop_remaining` track the initialized suffix in the main loop and the node guard. Both guard scopes are assembled from the proof and compared with production. | + +## Node access and local operations + +The contracts use the production node capacity and a symbolic initialized +length. They express access to the allocation with points-to predicates and +track the ownership of initialized keys and values separately from the +`MaybeUninit` storage. + +| Production methods | Memory-safety argument | +| --- | --- | +| `LeafNode::new`, `InternalNode::new` | Initializes the required node fields in newly allocated typed storage. Inactive slots and a detached node's parent index remain inside `MaybeUninit`. | +| `len`, `new_edge`, `new_kv`, `first_edge`, `last_edge`, `first_kv`, `last_kv`, `left_edge`, `right_edge`, `left_kv`, `right_kv` | The length read uses a live node field. Each returned handle carries the index required by its edge or key-value role. The first and last key-value operations require a nonempty node as documented. | +| `ascend` | Needs a read fraction of the backlink fields and reads `parent_idx` only when the backlink is present. The generic proof covers the traversal-permitted marker types, including `ValMut` and `Dying`, without borrowing the key and value storage. | +| `descend` | Reads the selected initialized edge with a shared loan and verifies the height decrement. The node's key and value permissions stay with the caller. | +| `into_leaf`, `keys`, `into_kv` | Constructs shared loans from the node and the typed owners of the occupied slots. The key slice includes exactly the initialized prefix. The pair accessors borrow only the selected initialized elements after projecting their arrays. | +| `as_internal_mut`, `as_leaf_mut`, `into_leaf_mut`, `as_leaf_dying`, `key_mut`, `into_val_mut`, `into_kv_mut`, `kv_mut` | Exclusive projections transfer ownership from the source place. The end tokens identify the original places and the frame preserves untouched slots. The conversion from `MaybeUninit` requires an initialized element. | +| `into_key_val_mut_at`, `into_kv_valmut` | Raw array-to-slice coercions preserve the base pointer and attach the capacity. Indexing computes the specified slot address. Only the chosen key and value slots are borrowed, so other value loans are outside the proof's footprint. | +| `pop_internal_level`, `push_with_handle`, and both `push` implementations | Root removal reads the initialized first edge, clears the new root's backlink, and consumes the old allocation with its internal-node layout. For a leaf root, the assertion unwinds before touching the node storage. Append requires space for the new slots and initializes them while updating the length. | +| `into_key_val`, leaf `remove` | Moving an entry requires ownership of its initialized key and value. Leaf removal shifts the occupied prefixes and checks the returned edge against the shortened length. | +| `deallocate_and_ascend` | Reads the parent index only for a linked node, chooses the layout from the node's height, and consumes the matching allocation. The frame retains the ancestor storage used by the returned edge. | +| `consider_for_balancing`, `choose_parent_kv` | Copies the handle metadata and follows initialized edges next to the separator. The selection proof covers ascent from a root, either adjacent sibling, and the panic for an empty parent. The child nodes stay in the caller's frame. | +| `cast_to_leaf_unchecked`, `cast_to_internal_unchecked`, `forget_node_type`, `reborrow_mut`, and `awaken` | Validates the marker changes and the metadata carried by the resulting handle. The conversions preserve the address of the node and the slot index when present. | + +## Correspondence with the library + +[verify.sh](verify.sh) follows the repository's `original/` and `verified/` +layout. It diffs the snapshots of `node.rs`, `borrow.rs`, and `mem.rs` +against the checkout. It reads all three `insert_recursing` callbacks, +checks for additional call sites, and fingerprints additional library sources. The +fingerprints keep those dependencies pinned without duplicating entire +`core` and `alloc` modules. + +The refinement checker compares four pairs of Rust programs. The +`// SOURCE` entries in the comparison templates copy complete functions +from the production snapshot or the annotated proof. [The refinement diff](refinement.patch) +records changes to signatures, specialized ranges, and wrapper calls. +The runner builds the views in a temporary directory. + +| Comparison | Coverage | +| --- | --- | +| [Backlinks](verified/insertion.rs#L354) | Uses the shared backlink proof from `verified/insertion.rs` and copies the production `as_leaf_ptr` and `set_parent_link` for comparison. | +| [Operations](original/operations.rs.in) | Extracts the production constructors, leaf and internal insertion and split bodies, merge and steal methods, and suffix move. It also compares the arguments to the two root-install operations using the actual callback bodies and capture types from `map.rs` and `map/entry.rs`, and checks the native internal `push` and dormant-root reborrow. The [verified view](verified/operations.rs.in) draws the checked routines from [the annotated proof](verified/insertion.rs). | +| [Loops](original/loop_regions.rs.in) | Compiles the production node module with compared regions for root installation, range relinking, and tracked handles. The [verified regions](verified/loop_regions.rs.in) draw the root exit, relinking, and index calculations from the annotated proof. | +| Whole functions | Compiles the production definitions and assembles the checked insertion loop, both drop guards, and the accessor, navigation, and local-operation bodies in their production scopes. The comparison retains the owned allocator and `FnOnce` argument and follows ordinary returns and unwind cleanup edges. | + +The whole-function comparison unfolds the proof helpers inside the owning +scope of `insert_recursing`. The checked entry supplies the pending split +and dormant handle. The checked loop supplies the propagation and wakeup +paths. The runner folds the checked `ascend` and its backlink and parent +construction helpers into the native `Option` operations, then diffs the +result against production. The proof reads an initialized index only when +there is a parent and establishes that its height increment is in range. +The loop's root arm calls the production `FnOnce` before awakening the +handle. All three callback projections are compiled from their production +bodies, and the projection requires the two root-install calls in their +production order. The [refinement diff](refinement.patch) folds the checked +read, internal allocation, write, and node projection into the body of +`push_internal_level`. The runner compares that body with production. It +also assembles `mem::replace` from the [verified replacement core and aborting +destructor](verified/root_replace.rs) and compares the full guard scope, +including the `take_mut` adapter, with the production MIR. The whole-function +checker follows the compiler's unwind edges without expanding calls, so it +retains the allocator and closure drop scopes as well as the cleanup for +partially moved split values. + +The whole-function check also compares `do_merge`. The runner checks the +verified callback wrapper's body before emitting its `FnOnce` call in the +production scope. The checker follows a cleanup branch when the value of its +local drop flag is known. + +For `choose_parent_kv`, the proof uses VeriFast's literal panic primitive. +The runner checks the pinned `unreachable_display` body and restores the +native macro with the fixed message before checking the production MIR. +The standard panic handler is a library boundary, and the branch preserves +the parent's verified resources on unwind. + +For [destruction](verified/insertion.rs), the verifier checks the Dying +handle, slot projections, iterator step, and remaining suffix. The +[refinement diff](refinement.patch) folds the proved loop into the +production ranges starting at zero and at `idx + 1`. It folds the verified +key and value steps into `drop_key_val` and its value guard. The compiler +compares both guard scopes in the whole-function MIR check. This covers the +value drop after a key panic, the remaining pairs, and termination if a +destructor unwinds while the thread is already unwinding. + +## Library specifications + +The runner applies the B-tree library specification patch to a temporary +copy of the pinned VeriFast tool. The patch records the trusted extensions +used by the proof. [library-specs.patch](library-specs.patch) + +| Primitive | Model and evidence | +| --- | --- | +| `ptr::copy` | Aligned endpoints in an owned byte span. The destination receives the source snapshot, including initialization state. Other bytes stay unchanged. Checked lemmas convert between bytes and slots, and the node contracts transfer the live `K` and `V` ownership separately. | +| `AllocatorClone::clone` | Equivalent allocation identity and a non-unwinding clone, as required by the library's unsafe trait. | +| Box and option projections | The comparison covers the production pointer conversions and the mutable `Option::Some` field projection. | +| `MaybeUninit::as_mut_ptr` | VeriFast checks the pointer cast extracted from the library body without accessing the pointee. | +| `slice::get_unchecked(usize)` and `MaybeUninit::assume_init_read` | The slice keeps the array pointer and its length. Indexing requires a live shared borrow of the in-bounds slot. The read requires an initialized value and preserves the original bits without creating another ownership of the value. The pinned core implementations provide the checked projection and read. | +| Shared prefix and `MaybeUninit::assume_init_ref` | The range preserves the base address and supplies the prefix length. Conversion to a typed reference requires the existing storage, valid alignment and extent, and initialization of the selected elements. Read permissions stay fractional. | +| `MaybeUninit::assume_init_mut` and raw slice indexing | The mutable conversion transfers the initialized slot's ownership to the resulting borrow. Raw slice indexing checks extent, alignment, and bounds. It returns the computed pointer and preserves its existing fraction of the live slot. Creating an exclusive reference requires full ownership of the slot. | +| `array::as_mut_slice` and `slice::get_unchecked_mut` | The slice keeps the array borrow's lifetime, tag, and length. An in-bounds index transfers ownership of the selected slots to the new borrow. Ending it restores the slots to the original array. The proof uses the pinned core implementations for `usize`, `Range`, and `RangeTo`. | +| `IndexMut>` for arrays | The pinned array and slice implementations define the coercion, delegation, and checked range calculation. The spec transfers the prefix exclusively and restores it through a slice borrow end token, including for an empty prefix. | +| `NonZero` conversions | `harness_new_internal_height_conversion` checks the checked constructor for every `usize` and the unchecked constructor at every positive value. Both preserve the input through conversion back to `usize`. | +| `From for usize` | The dependency fingerprints include the source macro implementing the widening conversion in `NodeRef::len`. | +| `MaybeUninit` storage conversion for `parent_idx` | The existing layout conversion lemmas take and return the same permission fraction. The proof reads the `u16` only when the stored option contains an initialized value. | +| `Allocator::deallocate` and allocator drop | Each deallocation consumes the right allocation with its matching layout. Typed proof entries use the fingerprinted `Allocator` safety guarantee where they need non-unwinding destruction. Generic drop retains its unwind branch, and converting an allocator ownership predicate to ordinary ownership supplies no such guarantee. | +| `ptr::drop_in_place` | The pinned VeriFast contract consumes the initialized value and its ownership. The slot stays available as storage on either exit. The patched frontend follows the compiler's unwind action for a MIR `Drop`. | +| `ptr::read` of a Dying handle | `duplicate_dying` proves the read from initialized handle storage. It copies the handle metadata and frames the node's slot ownership through the read. | +| Tuple ownership | The callback proofs use componentwise ownership for one- and two-element tuples, following the pinned prelude's tuple rules. | +| `RangeInclusive` | For a fresh iterator with `end < usize::MAX`, `harness_relink_inclusive_range_next` checks the initialization and step of the production iterator. | + +## Maintaining the comparison + +When production changes, review the checkout against the `original/` +snapshots and update the affected comparison templates and diffs together. +Rerun the pinned checker and the mutation tests after retargeting a +comparison. The [refinement.patch](refinement.patch) adapts the compiler inputs for the +runtime-inert safety attributes and the pinned compiler's abort spelling. + +## Running the checks + +The repository's VeriFast runner calls `verify.sh --ci` on Linux x86_64. +This mode builds the pinned tool in a temporary directory and runs the +proofs, MIR comparisons, and negative suite. Positive VeriFast runs reject +a prover diagnostic about inconsistent axiom instantiations. The runner uses +Bash, Git, and the pinned Rust and VeriFast tools. [The negative diff](negative/mutations.patch) +groups 32 independent cases applied to temporary copies. +[Repository runner](../../../../check-verifast-proofs.sh) · [VeriFast patches and regressions](verifast-patches/README.md) + +The negative suite changes the fit-at-capacity decision, root edge write +and replacement guard, split suffix and relink, merge layout and tracked +edge, steal ranges and separator, and the first destination edge in a +suffix transfer. It also checks rejection of an incorrect drop slot, a +suppressed value guard, and an incorrect cleanup start. The script tests +both the verifier and the MIR comparison where the mutation changes a +verified memory operation. Changing the merge deallocation layout also +fails the whole-function unwind comparison. +It also rejects a non-allocator's false no-unwind contract, a changed +production callback even without the source fingerprint check, an early +release of the root replacement guard, and a change in destructor order +visible only on unwind. The production dispatch and ascend mutations check +that a changed fullness test or parent index fails the source correspondence. +The whole-function comparison also rejects an early return that skips a +parent split. The drop proof's source fold rejects using the same slot again +on each iteration. +The UB cases read one slot past the initialized prefix within the array's +capacity, write through a shared view, borrow an already borrowed key +exclusively, and construct a `NonNull` from a null pointer. Each exercises +the corresponding initialization, permission, or validity obligation. + +Kani uses the pinned tool and default checks for the loop-free constructors, +accessors, and local operations. The harnesses cover every function in the +challenge's 26-function list with symbolic node occupancy and concrete +allocations. Their contracts have matching `proof_for_contract` harnesses. +Covers exercise branches such as empty and full nodes, either balancing +side, and successful allocation release. The B-tree harness group uses +zero explicit `assume`, stubs, and `#[kani::unwind]` annotations. + +```sh +./scripts/run-kani.sh --path . --kani-args --harness-timeout 1800 --jobs 1 \ + --harness collections::btree::node::verify:: +``` diff --git a/verifast-proofs/alloc/collections/btree/node.rs/library-specs.patch b/verifast-proofs/alloc/collections/btree/node.rs/library-specs.patch new file mode 100644 index 0000000000000..9fe6fe85f8b0c --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/library-specs.patch @@ -0,0 +1,315 @@ +diff --git a/bin/rust/prelude.rsspec b/bin/rust/prelude.rsspec +index e7e07fe..4b701ae 100644 +--- a/bin/rust/prelude.rsspec ++++ b/bin/rust/prelude.rsspec +@@ -33,6 +33,18 @@ lem close_tuple_0_own(t: thread_id_t); + + pred <(T1, T2)>.share(k, t, l) = .share(k, t, &(*l).0) &*& .share(k, t, &(*l).1); + ++lem close_tuple_1_own(t: thread_id_t, v: (T,)); ++ req .own(t, v.0); ++ ens <(T,)>.own(t, v); ++ ++lem close_tuple_2_own(t: thread_id_t, v: (T, R)); ++ req .own(t, v.0) &*& .own(t, v.1); ++ ens <(T, R)>.own(t, v); ++ ++lem open_tuple_2_own(t: thread_id_t, v: (T, R)); ++ req <(T, R)>.own(t, v); ++ ens .own(t, v.0) &*& .own(t, v.1); ++ + lem open_tuple_4_own(t: thread_id_t, v: (T1, T2, T3, T4)); + req <(T1, T2, T3, T4)>.own(t, v); + ens .own(t, v.0) &*& .own(t, v.1) &*& .own(t, v.2) &*& .own(t, v.3); +--- a/bin/rust/std/lib.rsspec ++++ b/bin/rust/std/lib.rsspec +@@ -28,6 +28,20 @@ + + } + ++mod clone { ++ //@ pred allocator_clone_bound(); ++ ++ trait Clone { ++ fn clone<'a>(self: &'a Self) -> Self; ++ /*@ ++ req thread_token(?t) &*& [_]allocator_clone_bound::() &*& ++ [_]std::alloc::Allocator_share::(?k,t,self,?alloc_id) &*& [?q]lifetime_token(k); ++ @*/ ++ //@ ens thread_token(t) &*& std::alloc::Allocator::(t,result,alloc_id) &*& [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ } ++} ++ + mod ops { + + trait FnOnce { +@@ -93,6 +107,40 @@ + + } + ++ struct RangeInclusive { ++ start: Idx, ++ end: Idx, ++ exhausted: bool, ++ } ++ ++ impl RangeInclusive { ++ fn new(start: Idx, end: Idx) -> RangeInclusive; ++ //@ req true; ++ //@ ens result == RangeInclusive:: { start, end, exhausted: false }; ++ //@ on_unwind_ens false; ++ } ++ ++ impl std::iter::IntoIterator for std::ops::RangeInclusive { ++ fn into_iter(self: RangeInclusive) -> RangeInclusive; ++ //@ req self.exhausted == false; ++ //@ ens result == self; ++ //@ on_unwind_ens false; ++ } ++ ++ impl std::iter::Iterator for std::ops::RangeInclusive { ++ fn next<'a>(self: &'a mut RangeInclusive) -> std::option::Option; ++ //@ req *self |-> ?state &*& state.exhausted == false &*& state.end < usize::MAX; ++ /*@ ++ ens if state.start <= state.end { ++ *self |-> RangeInclusive:: { start: state.start + 1, end: state.end, exhausted: false } &*& ++ result == std::option::Option::Some(state.start) ++ } else { ++ *self |-> state &*& result == std::option::Option::None ++ }; ++ @*/ ++ //@ on_unwind_ens false; ++ } ++ + enum ControlFlow { + Continue(C), + Break(B) +@@ -272,6 +320,32 @@ + //@ fix NonZero::get(nz: NonZero) -> T; + + /*@ ++ fix NonZero::is_zero(n: T) -> bool; ++ ++ lem_auto(NonZero::is_zero::(n)) NonZero_is_zero_usize(n: usize); ++ req true; ++ ens NonZero::is_zero(n) == (n == 0); ++ @*/ ++ ++ impl NonZero { ++ unsafe fn new_unchecked(n: T) -> NonZero; ++ //@ req NonZero::is_zero(n) == false; ++ //@ ens result.get() == n; ++ //@ on_unwind_ens false; ++ ++ fn new(n: T) -> std::option::Option>; ++ //@ req true; ++ /*@ ++ ens match result { ++ Option::None => NonZero::is_zero(n) == true, ++ Option::Some(v) => NonZero::get(v) == n &*& NonZero::is_zero(n) == false ++ }; ++ @*/ ++ //@ on_unwind_ens false; ++ } ++ ++ ++ /*@ + + lem NonZero_usize_limits(nz: NonZero); + req true; +@@ -445,16 +519,16 @@ + ens MaybeUninit::new_maybe_uninit(v).inner() == v; + + lem open_MaybeUninit(self: *MaybeUninit); +- req *self |-> ?value; +- ens *(self as *T) |-?-> value.inner(); ++ req [?f](*self |-> ?value); ++ ens [f](*(self as *T) |-?-> value.inner()); + + lem close_MaybeUninit_(self: *MaybeUninit); + req *(self as *T) |-?-> ?value; + ens *self |-> MaybeUninit::new_maybe_uninit(value); + + lem close_MaybeUninit(self: *MaybeUninit); +- req *(self as *T) |-> ?value; +- ens *self |-> MaybeUninit::new(value); ++ req [?f](*(self as *T) |-> ?value); ++ ens [f](*self |-> MaybeUninit::new(value)); + + lem open_MaybeUninit_(self: *MaybeUninit); + req *self |-?-> ?value; +@@ -492,6 +566,16 @@ + + impl MaybeUninit { + ++ fn as_mut_ptr<'a>(self: &'a mut MaybeUninit) -> *mut T; ++ //@ req true; ++ //@ ens result == self as *mut T; ++ //@ on_unwind_ens false; ++ ++ unsafe fn assume_init_read<'a>(self: &'a MaybeUninit) -> T; ++ //@ req [?f](*self |-> ?bits) &*& bits.inner() == some(?value); ++ //@ ens [f](*self |-> bits) &*& result == value; ++ //@ on_unwind_ens false; ++ + unsafe fn assume_init_ref<'a>(self: &'a MaybeUninit) -> &'a T; + /*@ + req [?f](*self |-> ?bits) &*& bits.inner() == some(?value) &*& +@@ -590,31 +674,19 @@ + + unsafe fn copy(src: *mut T, dst: *mut T, count: usize); + /*@ +- req exists::>(?offset_opt) &*& +- match offset_opt { +- none => // No overlap +- [?f](src as *u8)[..count * std::mem::size_of::()] |-?-> ?bs &*& (dst as *u8)[..count * std::mem::size_of::()] |-> _ &*& +- ens [f](src as *u8)[..count * std::mem::size_of::()] |-?-> bs &*& (dst as *u8)[..count * std::mem::size_of::()] |-?-> bs, +- some(offset) => +- dst == src + offset &*& +- if offset == 0 { +- // The docs require write access even in this case +- (dst as *u8)[..count * std::mem::size_of::()] |-?-> ?bs &*& +- ens (dst as *u8)[..count * std::mem::size_of::()] |-?-> bs +- } else if offset > 0 { +- // TODO: Require only read access for the part of `src` that does not overlap with `dst` +- (src as *u8)[..count * std::mem::size_of::()] |-?-> ?bs &*& ((src + count) as *u8)[..offset * std::mem::size_of::()] |-> _ &*& +- ens (src as *u8)[..offset * std::mem::size_of::()] |-?-> take(offset * std::mem::size_of::(), bs) &*& +- (dst as *u8)[..count * std::mem::size_of::()] |-?-> bs ++ req exists::(?right) &*& exists::(?distance) &*& 0 <= distance &*& ++ (if right { dst == src + distance } else { src == dst + distance }) == true &*& ++ src as usize % std::mem::align_of::() == 0 &*& dst as usize % std::mem::align_of::() == 0 &*& ++ ((if right { src } else { dst }) as *u8)[..(count + distance) * std::mem::size_of::()] |-?-> ?bytes; ++ @*/ ++ /*@ ++ ens ((if right { src } else { dst }) as *u8)[..(count + distance) * std::mem::size_of::()] |-?-> ++ (if right { ++ append(take(distance * std::mem::size_of::(), bytes), take(count * std::mem::size_of::(), bytes)) + } else { +- // TODO: Require only read access for the part of `src` that does not overlap with `dst` +- (src as *u8)[..count * std::mem::size_of::()] |-?-> ?bs &*& (dst as *u8)[..-offset * std::mem::size_of::()] |-> _ &*& +- ens ((dst + count) as *u8)[..-offset * std::mem::size_of::()] |-?-> drop((count + offset) * std::mem::size_of::(), bs) &*& +- (dst as *u8)[..count * std::mem::size_of::()] |-?-> bs +- } +- }; ++ append(drop(distance * std::mem::size_of::(), bytes), drop(count * std::mem::size_of::(), bytes)) ++ }); + @*/ +- //@ ens true; + //@ on_unwind_ens false; + //@ terminates; + +@@ -652,10 +724,12 @@ + //@ ens result == (strip_pointer_metadata(self as pointer) as *T) + index &*& [f](*result |-?-> slot); + //@ on_unwind_ens false; + ++ //@ fix drop_may_unwind() -> bool; ++ + unsafe fn drop_in_place(to_drop: *mut T); + //@ req thread_token(?t) &*& *to_drop |-> ?v &*& .own(t, v); + //@ ens thread_token(t) &*& *to_drop |-> _; +- //@ on_unwind_ens thread_token(t) &*& *to_drop |-> _; ++ //@ on_unwind_ens drop_may_unwind::() == true &*& thread_token(t) &*& *to_drop |-> _; + + struct NonNull; + +@@ -750,6 +824,7 @@ + fn cast(self: NonNull) -> NonNull; + //@ req true; + //@ ens result == NonNull::new(self.as_ptr() as *U); ++ //@ on_unwind_ens false; + + } + +@@ -1409,7 +1484,7 @@ + unsafe fn deallocate<'a>(self: &'a Self, ptr: std::ptr::NonNull, layout: Layout); + //@ req thread_token(?t) &*& Allocator::<&'a Self>(t, self, ?alloc_id) &*& alloc_block_in(alloc_id, ptr.as_ptr(), layout) &*& array_at_lft_(alloc_id.lft, ptr.as_ptr(), layout.size(), _); + //@ ens thread_token(t) &*& Allocator::<&'a Self>(t, self, alloc_id); +- //@ on_unwind_ens thread_token(t) &*& Allocator::<&'a Self>(t, self, alloc_id); ++ //@ on_unwind_ens false; + + unsafe fn grow<'a>(self: &'a Self, ptr: std::ptr::NonNull, old_layout: Layout, new_layout: Layout) -> std::result::Result, AllocError>; + /*@ +@@ -1598,6 +1673,7 @@ + fn assume_init(b: Box, A>) -> Box; + //@ req Box_in(?t, b, ?alloc_id, ?value) &*& std::mem::MaybeUninit::inner(value) == some(?value_); + //@ ens Box_in(t, result, alloc_id, value_); ++ //@ on_unwind_ens false; + + } + +@@ -1665,6 +1741,17 @@ + + impl Option { + ++ fn as_mut<'a>(self: &'a mut Option) -> Option<&'a mut T>; ++ //@ req *self |-> ?value; ++ /*@ ++ ens match value { ++ Option::None => *self |-> Option::None &*& result == Option::None, ++ Option::Some(v) => Option_Some(self) &*& *Option_Some_0_ptr(self) |-> v &*& ++ result == Option::Some(Option_Some_0_ptr(self)) ++ }; ++ @*/ ++ //@ on_unwind_ens false; ++ + fn is_some<'a>(self: &'a Option) -> bool; + //@ req [?f](*self |-> ?v); + //@ ens [f](*self |-> v) &*& result == (v != Option::None); +@@ -2190,12 +2277,52 @@ + + type Infallible = !; + +- trait Into { ++ /*@ ++ fix known_from(value: S) -> option; + +- fn into(self: Self) -> T; +- //@ req thread_token(currentThread) &*& .own(currentThread, self); +- //@ ens thread_token(currentThread) &*& .own(currentThread, result); ++ lem_auto(known_from::(value)) known_u16_to_usize(value: u16); ++ req true; ++ ens known_from::(value) == some(value as usize); ++ @*/ ++ ++ trait From { ++ fn from(value: S) -> Self; ++ /*@ ++ req if known_from::(value) == none { ++ thread_token(currentThread) &*& .own(currentThread, value) ++ } else { true }; ++ @*/ ++ /*@ ++ ens match known_from::(value) { ++ none => thread_token(currentThread) &*& .own(currentThread, result), ++ some(converted) => result == converted ++ }; ++ @*/ ++ //@ on_unwind_ens known_from::(value) == none &*& thread_token(currentThread); ++ } ++ ++ /*@ ++ fix known_into(value: S) -> option; + ++ lem_auto(known_into::, usize>(value)) known_nonzero_usize_into(value: std::num::NonZero); ++ req true; ++ ens known_into::, usize>(value) == some(value.get()); ++ @*/ ++ ++ trait Into { ++ fn into(self: Self) -> T; ++ /*@ ++ req if known_into::(self) == none { ++ thread_token(currentThread) &*& .own(currentThread, self) ++ } else { true }; ++ @*/ ++ /*@ ++ ens match known_into::(self) { ++ none => thread_token(currentThread) &*& .own(currentThread, result), ++ some(v) => result == v ++ }; ++ @*/ ++ //@ on_unwind_ens known_into::(self) == none &*& thread_token(currentThread); + } + + } diff --git a/verifast-proofs/alloc/collections/btree/node.rs/negative/mutations.patch b/verifast-proofs/alloc/collections/btree/node.rs/negative/mutations.patch new file mode 100644 index 0000000000000..0675ec882a2ea --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/negative/mutations.patch @@ -0,0 +1,370 @@ +# Case bad-internal-capacity +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -10014,5 +10014,5 @@ + //@ let len_view = precreate_ref(&self.node); + //@ init_ref_readonly(len_view, 1/2); +- let fits = self.node.merge_len() < CAPACITY; ++ let fits = self.node.merge_len() <= CAPACITY; + //@ end_ref_readonly(len_view); + //@ merge_fractions points_to(&self.node, _); +# Case bad-key-range +--- a/verified/operations.rs ++++ b/verified/operations.rs +@@ -1155,5 +1155,5 @@ + //@ drop_twice(last - first, first, slots); + +- let lent = unsafe { view.get_unchecked_mut(index) }; ++ let lent = unsafe { view.get_unchecked_mut(0..index.end) }; + //@ close move_slice(lent as *MaybeUninit, last - first, _); + //@ close leaf_without_keys(storage, parent, idx, len, vals); +# Case bad-leaf-capacity +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -10295,5 +10295,5 @@ + //@ let len_view = precreate_ref(&self.node); + //@ init_ref_readonly(len_view,1/2); +- let fits = unsafe { self.node.merge_len() < CAPACITY }; ++ let fits = unsafe { self.node.merge_len() <= CAPACITY }; + //@ end_ref_readonly(len_view); + //@ merge_fractions points_to(&self.node,_); +# Case bad-relink-read +--- a/verified/relink.rs ++++ b/verified/relink.rs +@@ -484,5 +484,5 @@ + //@ let slot = precreate_ref(base + self.idx); + //@ init_ref_readonly(slot, 1/2); +- let edge = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() }; ++ let edge = unsafe { (*parent_ptr).edges.get_unchecked(CAPACITY + 1).assume_init_read() }; + //@ end_ref_readonly(slot); + //@ merge_fractions points_to(base + self.idx, _); +# Case bad-root-edge +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -10536,5 +10536,5 @@ + //@ assert array(first_edge+1,CAPACITY,?tail); + //@ open array(first_edge,1,_); +- new_node.edges[0].write(child.node); ++ new_node.edges[1].write(child.node); + //@ close array(first_edge,1,[MaybeUninit::new(child.node)]); + //@ array_join(first_edge); +# Case bad-separator +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -4227,5 +4227,5 @@ + //@ drop_append(old_parent_len, active_after, drop(old_parent_len, p)); + +- left_node.key_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(old_left_len).write(entry); ++ left_node.key_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(0).write(entry); + //@ assert keys_slot_loan(left, ?slot, old_left_len, l_parent, l_idx, l_len, l_vals, _, _); + //@ end_keys_slot(left, slot); +# Case bad-split-boundaries +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -9331,5 +9331,5 @@ + //@ move_slice_offset(vals_base, CAPACITY, new_len); + //@ array_split(vals_base, new_len); +- let vals_target = &mut vals_array[..new_len]; ++ let vals_target = &mut vals_array[..new_len + 1]; + //@ close move_slice(vals_target as *MaybeUninit, new_len, _); + vals_target +# Case bad-suffix-range +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -8695,5 +8695,5 @@ + move_to_slice( + left.edge_area_range_mut/*@::<'a,K,V,'short>@*/(new_left_len + 1..old_left_len + 1), +- right_child.edge_area_range_mut/*@::<'a,K,V,'short>@*/(1..new_right_len + 1), ++ right_child.edge_area_range_mut/*@::<'a,K,V,'short>@*/(0..new_right_len), + ); + //@ assert edges_range_loan(left_edges.as_ptr(), ?source, new_left_len + 1, old_left_len + 1, left_data, _, _); +# Case drop-next-pair +--- a/original/whole/node.rs ++++ b/original/whole/node.rs +@@ -462,5 +462,5 @@ + // If `kv.drop_key_val()` panics, the guard would drop + // the rest and skip the panicked kv. +- let guard = DropGuard { node: self, idx: idx + 1 }; ++ let guard = DropGuard { node: self, idx: idx + 2 }; + // SAFETY: idx < len and the kv has been initialized and + // it won't touch the idx-th more than once +# Case drop-value-guard +--- a/original/whole/node.rs ++++ b/original/whole/node.rs +@@ -1304,4 +1304,5 @@ + let val = leaf.vals.get_unchecked_mut(self.idx); + let _guard = Dropper(val); ++ std::mem::forget(_guard); + key.assume_init_drop(); + // dropping the guard will drop the value +# Case drop-loop-index +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -9142,5 +9142,5 @@ + match next { + None => break, +- Some(i) => unsafe { drop_at(node, i) }, ++ Some(_i) => unsafe { drop_at(node, start) }, + } + } +# Case whole-insert-loop +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -5926,5 +5926,5 @@ + //@ open exists(fresh); + //@ close completed_levels::(t,alloc_id,k, cons(Placement(receiving,fresh,current_key,current_value),completed)); +- unsafe { pending.forget_node_type() } ++ return unsafe { inserted.awaken() }; + } + } +# Case missing-insert-relink +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -9904,5 +9904,5 @@ + //@ close exists(parent); + //@ close exists(pair(initialized_edges(before), inactive)); +- self.node.relink_range/*@::<'a,K,V,'short>@*/(self.idx + 1..new_len + 1); //~track_ref_creation ++ self.node.relink_range/*@::<'a,K,V,'short>@*/(self.idx + 2..new_len + 1); //~track_ref_creation + //@ assert ref_mut_end_token(?relink_receiver, &(*self).node); + //@ end_ref_mut(relink_receiver); +# Case missing-internal-relink +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -9533,5 +9533,4 @@ + //@ close exists(node); + //@ close exists(tail); +- unsafe { this.borrow_mut().correct_all_childrens_parent_links() }; + //@ close node_arrays(root, Array_elems(contents.data.keys), Array_elems(contents.data.vals), Array_elems(contents.edges)); + //@ initialized_edge_count(children); +# Case production-steal-range +--- a/original/node.rs ++++ b/original/node.rs +@@ -1784,5 +1784,5 @@ + slice_shl(right.edge_area_mut(..old_right_len + 1), count); + +- left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); ++ left.correct_childrens_parent_links(old_left_len + 2..new_left_len + 1); + right.correct_childrens_parent_links(0..new_right_len + 1); + } +# Case root-guard +--- a/original/whole/mem.rs ++++ b/original/whole/mem.rs +@@ -23,6 +23,7 @@ + } + } + let guard = PanicGuard; ++ mem::forget(guard); + // SAFETY: v is valid for reads and we write a new value before returning. + let value = unsafe { ptr::read(v) }; + let (new_value, ret) = change(value); +@@ -30,6 +31,5 @@ + unsafe { + ptr::write(v, new_value); + } +- mem::forget(guard); + ret + } +# Case short-edges +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -9662,5 +9662,5 @@ + //@ move_slice_offset(right_base, CAPACITY + 1, moved_count); + //@ array_split(right_base, moved_count); +- let right_edges = &mut right_array[..new_len + 1]; ++ let right_edges = &mut right_array[..new_len]; + //@ close move_slice(right_edges as *MaybeUninit>, moved_count, _); + right_edges +# Case skipped-merge +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -7389,5 +7389,5 @@ + let merging = self; + //@ close_points_to(&self); +- let child = unsafe { merging.merge_tracking_child/*@::<'a,K,V,A>@*/(alloc) }; ++ let child = merging.left_child; + //@ let new_len = l + 1 + r; + //@ let surviving = append(take(index + 1, pc), drop(index + 2, pc)); +# Case skipped-stolen-edge +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -7990,5 +7990,5 @@ + //@ close exists(pair(nil::>>,tail)); + //@ length_append(moved,right_children); +- right_internal.relink_range/*@::<'a,K,V,'short>@*/(0..new_right_len + 1); ++ right_internal.relink_range/*@::<'a,K,V,'short>@*/(1..new_right_len + 1); + //@ close_points_to(&(*right_edges.as_ptr()).data); + //@ close internal_without_edges(right_edges.as_ptr(),right_data); +# Case wrong-drop-slot +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -8887,5 +8887,5 @@ + slice + }, +- self.idx, ++ self.idx + 1, + ); + //@ close drop_slot_loan(&(*leaf).keys,key_array,key_slot,index,take(index,keys),drop(index+1,keys)); +# Case wrong-layout +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -6748,5 +6748,5 @@ + //@ std::ptr::NonNull_Sized_as_ptr(right_internal_node.node); + //@ std::ptr::NonNull_as_ptr_new(right_internal_node.node.as_ptr() as *u8); +- alloc.deallocate/*@::@*/(right_internal_node.node.cast(), std::alloc::Layout::new::>()); ++ alloc.deallocate/*@::@*/(right_internal_node.node.cast(), std::alloc::Layout::new::>()); + //@ close_points_to(&right_internal_node); + //@ leak Allocator::<&'call A>(t, view, id); +# Case wrong-left-steal-offset +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -5479,5 +5479,5 @@ + { + unsafe { +- Handle::, K, V, marker::LeafOrInternal>, marker::Edge>::new_edge(child, 1 + tracked_idx) ++ Handle::, K, V, marker::LeafOrInternal>, marker::Edge>::new_edge(child, 1 - tracked_idx) + } + } +# Case wrong-merge-offset +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -4799,5 +4799,5 @@ + let new_idx = match track_edge_idx { + LeftOrRight::Left(idx) => idx, +- LeftOrRight::Right(idx) => old_left_len + 1 + idx, ++ LeftOrRight::Right(idx) => old_left_len + idx, + }; + unsafe { +# Case allocator-drop-bound +--- /dev/null ++++ b/verified/allocator-drop.rs +@@ -0,0 +1,23 @@ ++#![allow(dead_code)] ++ ++unsafe fn claimed_no_unwind(value: T) ++//@ req thread_token(?t) &*& type_interp::() &*& .own(t, value); ++//@ ens thread_token(t) &*& type_interp::(); ++//@ on_unwind_ens false; ++{ ++ //@ std::alloc::open_Allocator_own::(value); ++ //@ std::alloc::Allocator_to_own::(value); ++ let mut primary = value; ++ //@ close_points_to(&mut primary); ++} ++ ++struct Panicking; ++impl Drop for Panicking { ++ fn drop(&mut self) { ++ panic!("destructor unwinds"); ++ } ++} ++ ++fn main() { ++ assert!(std::panic::catch_unwind(|| unsafe { claimed_no_unwind(Panicking) }).is_err()); ++} +# Case production-root-callback +--- a/callers/entry.rs ++++ b/callers/entry.rs +@@ -463,7 +463,7 @@ + // SAFETY: Pushing a new root node doesn't invalidate + // handles to existing nodes. + let map = unsafe { self.dormant_map.reborrow() }; +- let root = map.root.as_mut().unwrap(); // same as ins.left ++ let root = map.root.as_mut().filter(|_| false).unwrap(); + root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right) + }), + }; +# Case unwind-order +--- /dev/null ++++ b/original/unwind_order.rs +@@ -0,0 +1,7 @@ ++fn cleanup_order(first: T, second: U, action: impl FnOnce()) { ++ action(); ++ drop(second); ++ drop(first); ++} ++ ++fn main() {} +--- /dev/null ++++ b/verified/unwind_order.rs +@@ -0,0 +1,8 @@ ++fn cleanup_order(first: T, second: U, action: impl FnOnce()) { ++ let first = first; ++ action(); ++ drop(second); ++ drop(first); ++} ++ ++fn main() {} +# Case production-leaf-dispatch +--- a/original/node.rs ++++ b/original/node.rs +@@ -1048,7 +1048,7 @@ + Option>, + Handle, marker::KV>, + ) { +- if self.node.len() < CAPACITY { ++ if self.node.len() <= CAPACITY { + // SAFETY: There is enough space in the node for insertion. + let handle = unsafe { self.insert_fit(key, val) }; + (None, handle.dormant()) +# Case production-ascend +--- a/portable/node.rs ++++ b/portable/node.rs +@@ -347,7 +347,7 @@ + .map(|parent| Handle { + node: NodeRef::from_internal(*parent, self.height + 1), + // ignore-tidy-undocumented-unsafe +- idx: unsafe { usize::from((*leaf_ptr).parent_idx.assume_init()) }, ++ idx: unsafe { usize::from((*leaf_ptr).parent_idx.assume_init()) }.saturating_add(1), + _marker: PhantomData, + }) + .ok_or(self) + +# Case duplicate-key-loan +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -10801,5 +10801,7 @@ + ) + }; ++ let raw_key = key_slot.as_mut_ptr(); + let key = key_slot.assume_init_mut(); ++ let _duplicate = &mut *raw_key; //~track_ref_creation + //@ close exists::<*MaybeUninit>(key_slot); + //@ close initialized_array_slot(key_base,index,key,take(index,keys),drop(index+1,keys)); + +# Case invalid-parent-nonnull +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -6010,5 +6010,5 @@ + //@ std::ptr::NonNull_new_as_ptr(parent); + let parent_ptr = self.node.node.as_ptr() as *mut InternalNode; +- let parent_link = unsafe { NonNull::new_unchecked(parent_ptr) }; ++ let parent_link = unsafe { NonNull::new_unchecked(std::ptr::null_mut::>()) }; + //@ std::ptr::NonNull_new_as_ptr(parent_link); + // BEGIN_RAW_EDGE_READ + +# Case write-shared-node-length +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -10757,4 +10757,6 @@ + //@ close [store/2]leaf_slots(root,len,key_slots,vals); + //@ open_points_to(leaf); ++ let len_ptr = (&raw const leaf.len) as *mut u16; ++ unsafe { *len_ptr = 0 }; + //@ let keys_addr = &(*leaf).keys; + //@ close_points_to(keys_addr,store/2); + +# Case uninitialized-key-prefix +--- a/verified/insertion.rs ++++ b/verified/insertion.rs +@@ -10782,6 +10782,8 @@ + //@ assert (base as *u8 + len * std::mem::size_of::()) as pointer == (base + len) as pointer; + //@ slots_are_initialized(t,take(len,key_slots)); +- let prefix = unsafe { <[MaybeUninit]>::get_unchecked(key_slice, ..usize::from(leaf.len)) }; +- //@ array_split(base,len); ++ let live_len = usize::from(leaf.len); ++ let end = if live_len < CAPACITY { live_len + 1 } else { live_len }; ++ let prefix = unsafe { <[MaybeUninit]>::get_unchecked(key_slice, ..end) }; ++ //@ array_split(base,end); + let result = unsafe { <[MaybeUninit]>::assume_init_ref/*@::@*/(prefix) }; + //@ array_join(base); diff --git a/verifast-proofs/alloc/collections/btree/node.rs/original/borrow.rs b/verifast-proofs/alloc/collections/btree/node.rs/original/borrow.rs new file mode 100644 index 0000000000000..e848ac3f2d192 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/original/borrow.rs @@ -0,0 +1,69 @@ +use core::marker::PhantomData; +use core::ptr::NonNull; + +/// Models a reborrow of some unique reference, when you know that the reborrow +/// and all its descendants (i.e., all pointers and references derived from it) +/// will not be used any more at some point, after which you want to use the +/// original unique reference again. +/// +/// The borrow checker usually handles this stacking of borrows for you, but +/// some control flows that accomplish this stacking are too complicated for +/// the compiler to follow. A `DormantMutRef` allows you to check borrowing +/// yourself, while still expressing its stacked nature, and encapsulating +/// the raw pointer code needed to do this without undefined behavior. +pub(super) struct DormantMutRef<'a, T> { + ptr: NonNull, + _marker: PhantomData<&'a mut T>, +} + +unsafe impl<'a, T> Sync for DormantMutRef<'a, T> where &'a mut T: Sync {} +unsafe impl<'a, T> Send for DormantMutRef<'a, T> where &'a mut T: Send {} + +impl<'a, T> DormantMutRef<'a, T> { + /// Capture a unique borrow, and immediately reborrow it. For the compiler, + /// the lifetime of the new reference is the same as the lifetime of the + /// original reference, but you promise to use it for a shorter period. + pub(super) fn new(t: &'a mut T) -> (&'a mut T, Self) { + let ptr = NonNull::from(t); + // SAFETY: we hold the borrow throughout 'a via `_marker`, and we expose + // only this reference, so it is unique. + let new_ref = unsafe { &mut *ptr.as_ptr() }; + (new_ref, Self { ptr, _marker: PhantomData }) + } + + /// Revert to the unique borrow initially captured. + /// + /// # Safety + /// + /// The reborrow must have ended, i.e., the reference returned by `new` and + /// all pointers and references derived from it, must not be used anymore. + pub(super) unsafe fn awaken(self) -> &'a mut T { + // SAFETY: our own safety conditions imply this reference is again unique. + unsafe { &mut *self.ptr.as_ptr() } + } + + /// Borrows a new mutable reference from the unique borrow initially captured. + /// + /// # Safety + /// + /// The reborrow must have ended, i.e., the reference returned by `new` and + /// all pointers and references derived from it, must not be used anymore. + pub(super) unsafe fn reborrow(&mut self) -> &'a mut T { + // SAFETY: our own safety conditions imply this reference is again unique. + unsafe { &mut *self.ptr.as_ptr() } + } + + /// Borrows a new shared reference from the unique borrow initially captured. + /// + /// # Safety + /// + /// The reborrow must have ended, i.e., the reference returned by `new` and + /// all pointers and references derived from it, must not be used anymore. + pub(super) unsafe fn reborrow_shared(&self) -> &'a T { + // SAFETY: our own safety conditions imply this reference is again unique. + unsafe { &*self.ptr.as_ptr() } + } +} + +#[cfg(test)] +mod tests; diff --git a/verifast-proofs/alloc/collections/btree/node.rs/original/dependencies.sha256 b/verifast-proofs/alloc/collections/btree/node.rs/original/dependencies.sha256 new file mode 100644 index 0000000000000..a3ea66df2bbff --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/original/dependencies.sha256 @@ -0,0 +1,22 @@ +28dbdbf513203785ff66200c836c3b19ae8921e0be20dd9470c477ebf0518441 alloc/src/boxed.rs +4cd2e63953a64f97646578ca4cd43ae4f4dce1d1cbef053d1152661d844f8054 alloc/src/collections/btree/map.rs +91cdab820bad495bc3d7920cab077c0101b9627865aac467d32412f5dfeca6aa alloc/src/collections/btree/map/entry.rs +dfc19f213f0798becab9bba05d5a7ab3df5e3a6f0238c40a3aaf5034af65c3f2 contracts/safety/src/lib.rs +b6582bb8ac2cc0e886f8b1f45294ce4904615108a9b8740ac2802ed108ea7e02 contracts/safety/src/runtime.rs +cdb6b3ffcafffe909e453010f033328e7f8f97854e593389883d5b34786663bd core/src/alloc/mod.rs +62eff35f915bcf6e13befba95dea9d8246b01420ad39af654951c071c8abc4ac core/src/array/mod.rs +62e1f0712870651fc52da8ea9fb48bf2bc901718b39f1d40eb3a6db501142fca core/src/convert/num.rs +7af25ded20e6b9163d8feb302973a09f7aa696894d7192330415ba640829ce05 core/src/fmt/mod.rs +50c7d567881acfe4bbe9a2d1a9119776d7040b69df22d8890f8f4dc81ea691d9 core/src/mem/maybe_uninit.rs +4b7aea1426c7ac7297d8f1b7210d599bbd89535a7f4bfaec7969609c6d665798 core/src/mem/mod.rs +8c6ed433c6d0307605f1de1cee974d3a42842c6459275545034790dc570c2fb2 core/src/num/nonzero.rs +5d791bd2ee8997e93ac72c35db831815d9acbb7aed05cd1539799b7677a13d20 core/src/ops/range.rs +1d0f3f6245b7093e493e0c0ae99c24f4215b6124db9d5c93bf63b2ba2e0e92b2 core/src/option.rs +af3a2db8556694b0b223af81ea434f4735a6b675b52a5b39ee0e442258bdf957 core/src/panic.rs +1e65b73f080e427e4d95e25a02babf9c6f73c2a77d05d53f3e9de56e9fa962e4 core/src/panicking.rs +ce1a147361ddd5fd9623620129fa43107010211aeaa59eab108c1466c6ad0eef core/src/ptr/const_ptr.rs +7bc0669653c04bfca702da3214ce9284e1258068d598b0ea90846cc14612ce4a core/src/ptr/mut_ptr.rs +1dc0737f0658cddc210c8fa8eea0f2717e017c62824dadcc7bce9714fb5a2397 core/src/ptr/non_null.rs +418f952ac225871d6b4cb3bbf1f11aa83d6bb0a09fca827e611021d124ae5e0b core/src/result.rs +080ad30d5226cc0089ba585248b88118921d19440f9c57c48371bca0d67e219d core/src/slice/index.rs +236947f8e58246c8d347aa442bf57898f4fb85f5d00993b4e35b30042bcaa053 core/src/slice/mod.rs diff --git a/verifast-proofs/alloc/collections/btree/node.rs/original/loop_crate.rs b/verifast-proofs/alloc/collections/btree/node.rs/original/loop_crate.rs new file mode 100644 index 0000000000000..667330c10929a --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/original/loop_crate.rs @@ -0,0 +1,8 @@ +#![feature(allocator_ext, maybe_uninit_slice, slice_ptr_get, box_as_ptr)] +#![allow(dead_code, unused_imports, unexpected_cfgs)] +mod alloc { pub use std::alloc::*; } +mod boxed { pub use std::boxed::Box; } +mod node; +mod mem; +mod borrow; +fn main() {} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/original/loop_regions.rs.in b/verifast-proofs/alloc/collections/btree/node.rs/original/loop_regions.rs.in new file mode 100644 index 0000000000000..236d8deee11ba --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/original/loop_regions.rs.in @@ -0,0 +1,53 @@ + +const _: () = { + type LeafRef = NodeRef, String, String, marker::Leaf>; + type InternalRef = NodeRef, String, String, marker::Internal>; + assert!(!std::mem::needs_drop::>()); + assert!(!std::mem::needs_drop::>()); + assert!(!std::mem::needs_drop::>()); + assert!(!std::mem::needs_drop::, String, String, marker::LeafOrInternal>>()); + assert!(!std::mem::needs_drop::>()); +}; + +use super::borrow::DormantMutRef; + +unsafe fn finish_root_split<'tree, 'slot, K, V, A: AllocatorClone>( + split: SplitResult<'tree, K, V, marker::LeafOrInternal>, + inserted: Handle, marker::KV>, + root_slot: &'slot mut DormantMutRef<'tree, Option>>, + allocator: &'slot mut A, +) -> Handle, K, V, marker::Leaf>, marker::KV> +{ + let root = unsafe { root_slot.reborrow().as_mut().unwrap() }; + root.push_internal_level(allocator.clone()).push(split.kv.0, split.kv.1, split.right); + unsafe { inserted.awaken() } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn correct_childrens_parent_links>(&mut self, range: R) { +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn correct_childrens_parent_links>(&mut self, range: R) { +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE fn correct_all_childrens_parent_links(&mut self) { +} + +fn moved_node_metadata( + node: NodeRef, +) -> (usize, NonNull>) { + let moved = node; + (moved.height, moved.node) +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +// SOURCE pub(super) fn merge_tracking_child_edge( +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +// SOURCE pub(super) fn steal_left( + +// SOURCE pub(super) fn steal_right( +} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/original/mem.rs b/verifast-proofs/alloc/collections/btree/node.rs/original/mem.rs new file mode 100644 index 0000000000000..c9a1ec8ca63c6 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/original/mem.rs @@ -0,0 +1,35 @@ +use core::{intrinsics, mem, ptr}; + +/// This replaces the value behind the `v` unique reference by calling the +/// relevant function. +/// +/// If a panic occurs in the `change` closure, the entire process will be aborted. +#[allow(dead_code)] // keep as illustration and for future use +#[inline] +pub(super) fn take_mut(v: &mut T, change: impl FnOnce(T) -> T) { + replace(v, |value| (change(value), ())) +} + +/// This replaces the value behind the `v` unique reference by calling the +/// relevant function, and returns a result obtained along the way. +/// +/// If a panic occurs in the `change` closure, the entire process will be aborted. +#[inline] +pub(super) fn replace(v: &mut T, change: impl FnOnce(T) -> (T, R)) -> R { + struct PanicGuard; + impl Drop for PanicGuard { + fn drop(&mut self) { + intrinsics::abort_immediate() + } + } + let guard = PanicGuard; + // SAFETY: v is valid for reads and we write a new value before returning. + let value = unsafe { ptr::read(v) }; + let (new_value, ret) = change(value); + // SAFETY: new_value is T and v is valid for writes. + unsafe { + ptr::write(v, new_value); + } + mem::forget(guard); + ret +} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/original/node.rs b/verifast-proofs/alloc/collections/btree/node.rs/original/node.rs new file mode 100644 index 0000000000000..23888b91110a0 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/original/node.rs @@ -0,0 +1,3205 @@ +// This is an attempt at an implementation following the ideal +// +// ``` +// struct BTreeMap { +// height: usize, +// root: Option>> +// } +// +// struct Node { +// keys: [K; 2 * B - 1], +// vals: [V; 2 * B - 1], +// edges: [if height > 0 { Box> } else { () }; 2 * B], +// parent: Option<(NonNull>, u16)>, +// len: u16, +// } +// ``` +// +// Since Rust doesn't actually have dependent types and polymorphic recursion, +// we make do with lots of unsafety. + +// A major goal of this module is to avoid complexity by treating the tree as a generic (if +// weirdly shaped) container and avoiding dealing with most of the B-Tree invariants. As such, +// this module doesn't care whether the entries are sorted, which nodes can be underfull, or +// even what underfull means. However, we do rely on a few invariants: +// +// - Trees must have uniform depth/height. This means that every path down to a leaf from a +// given node has exactly the same length. +// - A node of length `n` has `n` keys, `n` values, and `n + 1` edges. +// This implies that even an empty node has at least one edge. +// For a leaf node, "having an edge" only means we can identify a position in the node, +// since leaf edges are empty and need no data representation. In an internal node, +// an edge both identifies a position and contains a pointer to a child node. + +#[cfg(kani)] +use core::kani; +use core::marker::PhantomData; +use core::mem::{self, MaybeUninit}; +use core::num::NonZero; +use core::ptr::{self, NonNull}; +use core::slice::SliceIndex; + +use safety::{ensures, requires}; + +use crate::alloc::{Allocator, AllocatorClone, Layout}; +use crate::boxed::Box; + +const B: usize = 6; +pub(super) const CAPACITY: usize = 2 * B - 1; +pub(super) const MIN_LEN_AFTER_SPLIT: usize = B - 1; +const KV_IDX_CENTER: usize = B - 1; +const EDGE_IDX_LEFT_OF_CENTER: usize = B - 1; +const EDGE_IDX_RIGHT_OF_CENTER: usize = B; + +/// The underlying representation of leaf nodes and part of the representation of internal nodes. +struct LeafNode { + /// We want to be covariant in `K` and `V`. + parent: Option>>, + + /// This node's index into the parent node's `edges` array. + /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`. + /// This is only guaranteed to be initialized when `parent` is non-null. + parent_idx: MaybeUninit, + + /// The number of keys and values this node stores. + len: u16, + + /// The arrays storing the actual data of the node. Only the first `len` elements of each + /// array are initialized and valid. + keys: [MaybeUninit; CAPACITY], + vals: [MaybeUninit; CAPACITY], +} + +impl LeafNode { + /// Initializes a new `LeafNode` in-place. + /// + /// # Safety + /// + /// The caller must ensure that `this` points to a (possibly uninitialized) `LeafNode` + #[requires(core::ub_checks::can_write(this))] + #[ensures(|_| unsafe { (*this).parent.is_none() })] + #[ensures(|_| unsafe { (*this).len == 0 })] + #[cfg_attr(kani, kani::modifies(this))] + unsafe fn init(this: *mut Self) { + // As a general policy, we leave fields uninitialized if they can be, as this should + // be both slightly faster and easier to track in Valgrind. + // ignore-tidy-undocumented-unsafe + unsafe { + // parent_idx, keys, and vals are all MaybeUninit + (&raw mut (*this).parent).write(None); + (&raw mut (*this).len).write(0); + } + } + + /// Creates a new boxed `LeafNode`. + fn new(alloc: A) -> Box { + let mut leaf = Box::new_uninit_in(alloc); + + // SAFETY: `leaf` points to a `LeafNode`. + unsafe { LeafNode::init(leaf.as_mut_ptr()) }; + // SAFETY: `leaf` was just initialized. + unsafe { leaf.assume_init() } + } +} + +/// The underlying representation of internal nodes. As with `LeafNode`s, these should be hidden +/// behind `BoxedNode`s to prevent dropping uninitialized keys and values. Any pointer to an +/// `InternalNode` can be directly cast to a pointer to the underlying `LeafNode` portion of the +/// node, allowing code to act on leaf and internal nodes generically without having to even check +/// which of the two a pointer is pointing at. This property is enabled by the use of `repr(C)`. +#[repr(C)] +// gdb_providers.py uses this type name for introspection. +struct InternalNode { + data: LeafNode, + + /// The pointers to the children of this node. `len + 1` of these are considered + /// initialized and valid, except that near the end, while the tree is held + /// through borrow type `Dying`, some of these pointers are dangling. + edges: [MaybeUninit>; 2 * B], +} + +impl InternalNode { + /// Creates a new boxed `InternalNode`. + /// + /// # Safety + /// An invariant of internal nodes is that they have at least one + /// initialized and valid edge. This function does not set up + /// such an edge. + unsafe fn new(alloc: A) -> Box { + let mut node = Box::::new_uninit_in(alloc); + + // SAFETY: argument points to the `node.data` `LeafNode`. + unsafe { LeafNode::init(&raw mut (*node.as_mut_ptr()).data) }; + // SAFETY: `node.data` was just initialized and `node.edges` is MaybeUninit. + unsafe { node.assume_init() } + } +} + +/// A managed, non-null pointer to a node. This is either an owned pointer to +/// `LeafNode` or an owned pointer to `InternalNode`. +/// +/// However, `BoxedNode` contains no information as to which of the two types +/// of nodes it actually contains, and, partially due to this lack of information, +/// is not a separate type and has no destructor. +type BoxedNode = NonNull>; + +// N.B. `NodeRef` is always covariant in `K` and `V`, even when the `BorrowType` +// is `Mut`. This is technically wrong, but cannot result in any unsafety due to +// internal use of `NodeRef` because we stay completely generic over `K` and `V`. +// However, whenever a public type wraps `NodeRef`, make sure that it has the +// correct variance. +/// +/// A reference to a node. +/// +/// This type has a number of parameters that control how it acts: +/// - `BorrowType`: A dummy type that describes the kind of borrow and carries a lifetime. +/// - When this is `Immut<'a>`, the `NodeRef` acts roughly like `&'a Node`. +/// - When this is `ValMut<'a>`, the `NodeRef` acts roughly like `&'a Node` +/// with respect to keys and tree structure, but also allows many +/// mutable references to values throughout the tree to coexist. +/// - When this is `Mut<'a>`, the `NodeRef` acts roughly like `&'a mut Node`, +/// although insert methods allow a mutable pointer to a value to coexist. +/// - When this is `Owned`, the `NodeRef` acts roughly like `Box`, +/// but does not have a destructor, and must be cleaned up manually. +/// - When this is `Dying`, the `NodeRef` still acts roughly like `Box`, +/// but has methods to destroy the tree bit by bit, and ordinary methods, +/// while not marked as unsafe to call, can invoke UB if called incorrectly. +/// Since any `NodeRef` allows navigating through the tree, `BorrowType` +/// effectively applies to the entire tree, not just to the node itself. +/// - `K` and `V`: These are the types of keys and values stored in the nodes. +/// - `Type`: This can be `Leaf`, `Internal`, or `LeafOrInternal`. When this is +/// `Leaf`, the `NodeRef` points to a leaf node, when this is `Internal` the +/// `NodeRef` points to an internal node, and when this is `LeafOrInternal` the +/// `NodeRef` could be pointing to either type of node. +/// `Type` is named `NodeType` when used outside `NodeRef`. +/// +/// Both `BorrowType` and `NodeType` restrict what methods we implement, to +/// exploit static type safety. There are limitations in the way we can apply +/// such restrictions: +/// - For each type parameter, we can only define a method either generically +/// or for one particular type. For example, we cannot define a method like +/// `into_kv` generically for all `BorrowType`, or once for all types that +/// carry a lifetime, because we want it to return `&'a` references. +/// Therefore, we define it only for the least powerful type `Immut<'a>`. +/// - We cannot get implicit coercion from say `Mut<'a>` to `Immut<'a>`. +/// Therefore, we have to explicitly call `reborrow` on a more powerful +/// `NodeRef` in order to reach a method like `into_kv`. +/// +/// All methods on `NodeRef` that return some kind of reference, either: +/// - Take `self` by value, and return the lifetime carried by `BorrowType`. +/// Sometimes, to invoke such a method, we need to call `reborrow_mut`. +/// - Take `self` by reference, and (implicitly) return that reference's +/// lifetime, instead of the lifetime carried by `BorrowType`. That way, +/// the borrow checker guarantees that the `NodeRef` remains borrowed as long +/// as the returned reference is used. +/// The methods supporting insert bend this rule by returning a raw pointer, +/// i.e., a reference without any lifetime. +pub(super) struct NodeRef { + /// The number of levels that the node and the level of leaves are apart, a + /// constant of the node that cannot be entirely described by `Type`, and that + /// the node itself does not store. We only need to store the height of the root + /// node, and derive every other node's height from it. + /// Must be zero if `Type` is `Leaf` and non-zero if `Type` is `Internal`. + height: usize, + /// The pointer to the leaf or internal node. The definition of `InternalNode` + /// ensures that the pointer is valid either way. + node: NonNull>, + _marker: PhantomData<(BorrowType, Type)>, +} + +/// The root node of an owned tree. +/// +/// Note that this does not have a destructor, and must be cleaned up manually. +pub(super) type Root = NodeRef; + +impl<'a, K: 'a, V: 'a, Type> Copy for NodeRef, K, V, Type> {} +impl<'a, K: 'a, V: 'a, Type> Clone for NodeRef, K, V, Type> { + fn clone(&self) -> Self { + *self + } +} + +unsafe impl Sync for NodeRef {} + +unsafe impl Send for NodeRef, K, V, Type> {} +unsafe impl Send for NodeRef, K, V, Type> {} +unsafe impl Send for NodeRef, K, V, Type> {} +unsafe impl Send for NodeRef {} +unsafe impl Send for NodeRef {} + +impl NodeRef { + pub(super) fn new_leaf(alloc: A) -> Self { + Self::from_new_leaf(LeafNode::new(alloc)) + } + + fn from_new_leaf(leaf: Box, A>) -> Self { + // The allocator must be dropped, not leaked. See also `BTreeMap::alloc`. + let (node, _alloc) = Box::into_non_null_with_allocator(leaf); + NodeRef { height: 0, node, _marker: PhantomData } + } +} + +impl NodeRef { + /// Creates a new internal (height > 0) `NodeRef` + fn new_internal(child: Root, alloc: A) -> Self { + // ignore-tidy-undocumented-unsafe + let mut new_node = unsafe { InternalNode::new(alloc) }; + new_node.edges[0].write(child.node); + NodeRef::from_new_internal(new_node, NonZero::new(child.height + 1).unwrap()) + } + + /// Creates a new internal (height > 0) `NodeRef` from an existing internal node + fn from_new_internal( + internal: Box, A>, + height: NonZero, + ) -> Self { + // The allocator must be dropped, not leaked. See also `BTreeMap::alloc`. + let (node, _alloc) = Box::into_non_null_with_allocator(internal); + let mut this = NodeRef { height: height.into(), node: node.cast(), _marker: PhantomData }; + this.borrow_mut().correct_all_childrens_parent_links(); + this + } +} + +impl NodeRef { + /// Unpack a node reference that was packed as `NodeRef::parent`. + fn from_internal(node: NonNull>, height: usize) -> Self { + debug_assert!(height > 0); + NodeRef { height, node: node.cast(), _marker: PhantomData } + } +} + +impl NodeRef { + /// Exposes the data of an internal node. + /// + /// Returns a raw ptr to avoid invalidating other references to this node. + fn as_internal_ptr(this: &Self) -> *mut InternalNode { + // SAFETY: the static node type is `Internal`. + this.node.as_ptr() as *mut InternalNode + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + /// Borrows exclusive access to the data of an internal node. + fn as_internal_mut(&mut self) -> &mut InternalNode { + let ptr = Self::as_internal_ptr(self); + // ignore-tidy-undocumented-unsafe + unsafe { &mut *ptr } + } +} + +impl NodeRef { + /// Finds the length of the node. This is the number of keys or values. + /// The number of edges is `len() + 1`. + /// Note that, despite being safe, calling this function can have the side effect + /// of invalidating mutable references that unsafe code has created. + pub(super) fn len(&self) -> usize { + // SAFETY: We only access the `len` field here. If BorrowType is marker::ValMut, + // there might be outstanding mutable references to values that we must not invalidate. + unsafe { usize::from((*Self::as_leaf_ptr(self)).len) } + } + + /// Returns the number of levels that the node and leaves are apart. Zero + /// height means the node is a leaf itself. If you picture trees with the + /// root on top, the number says at which elevation the node appears. + /// If you picture trees with leaves on top, the number says how high + /// the tree extends above the node. + pub(super) fn height(&self) -> usize { + self.height + } + + /// Temporarily takes out another, immutable reference to the same node. + pub(super) fn reborrow(&self) -> NodeRef, K, V, Type> { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } + + /// Exposes the leaf portion of any leaf or internal node. + /// + /// Returns a raw ptr to avoid invalidating other references to this node. + fn as_leaf_ptr(this: &Self) -> *mut LeafNode { + // The node must be valid for at least the LeafNode portion. + // This is not a reference in the NodeRef type because we don't know if + // it should be unique or shared. + this.node.as_ptr() + } +} + +impl NodeRef { + /// Finds the parent of the current node. Returns `Ok(handle)` if the current + /// node actually has a parent, where `handle` points to the edge of the parent + /// that points to the current node. Returns `Err(self)` if the current node has + /// no parent, giving back the original `NodeRef`. + /// + /// The method name assumes you picture trees with the root node on top. + /// + /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should + /// both, upon success, do nothing. + #[requires(verify::can_ascend(&self))] + #[ensures(|result| { + let original_node = old(self.node); + let original_height = old(self.height); + match (old(verify::ascend_link(&self)), result) { + (Some((parent, idx)), Ok(edge)) => { + edge.node.node == parent.cast() + && edge.node.height == original_height + 1 + && edge.idx == idx + } + (None, Err(root)) => root.node == original_node && root.height == original_height, + _ => false, + } + })] + pub(super) fn ascend( + self, + ) -> Result, marker::Edge>, Self> { + const { + assert!(BorrowType::TRAVERSAL_PERMIT); + } + + // We need to use raw pointers to nodes because, if BorrowType is marker::ValMut, + // there might be outstanding mutable references to values that we must not invalidate. + let leaf_ptr: *const _ = Self::as_leaf_ptr(&self); + // ignore-tidy-undocumented-unsafe + unsafe { (*leaf_ptr).parent } + .as_ref() + .map(|parent| Handle { + node: NodeRef::from_internal(*parent, self.height + 1), + // ignore-tidy-undocumented-unsafe + idx: unsafe { usize::from((*leaf_ptr).parent_idx.assume_init()) }, + _marker: PhantomData, + }) + .ok_or(self) + } + + pub(super) fn first_edge(self) -> Handle { + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(self, 0) } + } + + pub(super) fn last_edge(self) -> Handle { + let len = self.len(); + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(self, len) } + } + + /// Note that `self` must be nonempty. + pub(super) fn first_kv(self) -> Handle { + let len = self.len(); + assert!(len > 0); + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_kv(self, 0) } + } + + /// Note that `self` must be nonempty. + pub(super) fn last_kv(self) -> Handle { + let len = self.len(); + assert!(len > 0); + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_kv(self, len - 1) } + } +} + +impl NodeRef { + /// Could be a public implementation of PartialEq, but only used in this module. + fn eq(&self, other: &Self) -> bool { + let Self { node, height, _marker } = self; + if node.eq(&other.node) { + debug_assert_eq!(*height, other.height); + true + } else { + false + } + } +} + +impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { + /// Exposes the leaf portion of any leaf or internal node in an immutable tree. + fn into_leaf(self) -> &'a LeafNode { + let ptr = Self::as_leaf_ptr(&self); + // SAFETY: there can be no mutable references into this tree borrowed as `Immut`. + unsafe { &*ptr } + } + + /// Borrows a view into the keys stored in the node. + pub(super) fn keys(&self) -> &[K] { + let leaf = self.into_leaf(); + // ignore-tidy-undocumented-unsafe + unsafe { leaf.keys.get_unchecked(..usize::from(leaf.len)).assume_init_ref() } + } +} + +impl NodeRef { + /// Similar to `ascend`, gets a reference to a node's parent node, but also + /// deallocates the current node in the process. This is unsafe because the + /// current node will still be accessible despite being deallocated. + pub(super) unsafe fn deallocate_and_ascend( + self, + alloc: A, + ) -> Option, marker::Edge>> { + let height = self.height; + let node = self.node; + let ret = self.ascend().ok(); + // ignore-tidy-undocumented-unsafe + unsafe { + alloc.deallocate( + node.cast(), + if height > 0 { + Layout::new::>() + } else { + Layout::new::>() + }, + ); + } + ret + } + /// Drops all kvs in this node without deallocating the node itself + /// + /// # Safety + /// + /// - kvs in the node must be initialized and must not be accessed after this call. + /// - No kvs in the node can be accessed through any other path while this function is running. + pub(super) unsafe fn drop_kvs(&mut self) { + struct DropGuard<'a, K, V> { + node: &'a NodeRef, + idx: usize, + } + impl<'a, K, V> Drop for DropGuard<'a, K, V> { + fn drop(&mut self) { + let len = self.node.len(); + for i in self.idx..len { + // SAFETY: i < len and the kv has been initialized and + // it won't use the i-th kv more than once. + unsafe { + let kv = Handle::new_kv(ptr::read(self.node), i); + kv.drop_key_val(); + } + } + } + } + let len = self.len(); + for idx in 0..len { + // If `kv.drop_key_val()` panics, the guard would drop + // the rest and skip the panicked kv. + let guard = DropGuard { node: self, idx: idx + 1 }; + // SAFETY: idx < len and the kv has been initialized and + // it won't touch the idx-th more than once + unsafe { + let kv = Handle::new_kv(ptr::read(self), idx); + kv.drop_key_val(); + } + + core::mem::forget(guard); + } + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + /// Temporarily takes out another mutable reference to the same node. Beware, as + /// this method is very dangerous, doubly so since it might not immediately appear + /// dangerous. + /// + /// Because mutable pointers can roam anywhere around the tree, the returned + /// pointer can easily be used to make the original pointer dangling, out of + /// bounds, or invalid under stacked borrow rules. + // FIXME(@gereeter) consider adding yet another type parameter to `NodeRef` + // that restricts the use of navigation methods on reborrowed pointers, + // preventing this unsafety. + unsafe fn reborrow_mut(&mut self) -> NodeRef, K, V, Type> { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } + + /// Borrows exclusive access to the leaf portion of a leaf or internal node. + fn as_leaf_mut(&mut self) -> &mut LeafNode { + let ptr = Self::as_leaf_ptr(self); + // SAFETY: we have exclusive access to the entire node. + unsafe { &mut *ptr } + } + + /// Offers exclusive access to the leaf portion of a leaf or internal node. + fn into_leaf_mut(mut self) -> &'a mut LeafNode { + let ptr = Self::as_leaf_ptr(&mut self); + // SAFETY: we have exclusive access to the entire node. + unsafe { &mut *ptr } + } + + /// Returns a dormant copy of this node with its lifetime erased which can + /// be reawakened later. + pub(super) fn dormant(&self) -> NodeRef { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +impl NodeRef { + /// Revert to the unique borrow initially captured. + /// + /// # Safety + /// + /// The reborrow must have ended, i.e., the reference returned by `new` and + /// all pointers and references derived from it, must not be used anymore. + pub(super) unsafe fn awaken<'a>(self) -> NodeRef, K, V, Type> { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +impl NodeRef { + /// Borrows exclusive access to the leaf portion of a dying leaf or internal node. + fn as_leaf_dying(&mut self) -> &mut LeafNode { + let ptr = Self::as_leaf_ptr(self); + // SAFETY: we have exclusive access to the entire node. + unsafe { &mut *ptr } + } +} + +impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { + /// Borrows exclusive access to an element of the key storage area. + /// + /// # Safety + /// `index` is in bounds of 0..CAPACITY + unsafe fn key_area_mut(&mut self, index: I) -> &mut Output + where + I: SliceIndex<[MaybeUninit], Output = Output>, + { + // SAFETY: the caller will not be able to call further methods on self + // until the key slice reference is dropped, as we have unique access + // for the lifetime of the borrow. + unsafe { self.as_leaf_mut().keys.as_mut_slice().get_unchecked_mut(index) } + } + + /// Borrows exclusive access to an element or slice of the node's value storage area. + /// + /// # Safety + /// `index` is in bounds of 0..CAPACITY + unsafe fn val_area_mut(&mut self, index: I) -> &mut Output + where + I: SliceIndex<[MaybeUninit], Output = Output>, + { + // SAFETY: the caller will not be able to call further methods on self + // until the value slice reference is dropped, as we have unique access + // for the lifetime of the borrow. + unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { + /// Borrows exclusive access to an element or slice of the node's storage area for edge contents. + /// + /// # Safety + /// `index` is in bounds of 0..CAPACITY + 1 + unsafe fn edge_area_mut(&mut self, index: I) -> &mut Output + where + I: SliceIndex<[MaybeUninit>], Output = Output>, + { + // SAFETY: the caller will not be able to call further methods on self + // until the edge slice reference is dropped, as we have unique access + // for the lifetime of the borrow. + unsafe { self.as_internal_mut().edges.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + /// # Safety + /// - The node has more than `idx` initialized elements. + unsafe fn into_key_val_mut_at(mut self, idx: usize) -> (&'a K, &'a mut V) { + // We only create a reference to the one element we are interested in, + // to avoid aliasing with outstanding references to other elements, + // in particular, those returned to the caller in earlier iterations. + let leaf = Self::as_leaf_ptr(&mut self); + // ignore-tidy-undocumented-unsafe + let keys = unsafe { &raw const (*leaf).keys }; + // ignore-tidy-undocumented-unsafe + let vals = unsafe { &raw mut (*leaf).vals }; + // We must coerce to unsized array pointers because of Rust issue #74679. + let keys: *const [_] = keys; + let vals: *mut [_] = vals; + // ignore-tidy-undocumented-unsafe + let key = unsafe { (&*keys.get_unchecked(idx)).assume_init_ref() }; + // ignore-tidy-undocumented-unsafe + let val = unsafe { (&mut *vals.get_unchecked_mut(idx)).assume_init_mut() }; + (key, val) + } +} + +impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { + /// Borrows exclusive access to the length of the node. + pub(super) fn len_mut(&mut self) -> &mut u16 { + &mut self.as_leaf_mut().len + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + /// # Safety + /// Every item returned by `range` is a valid edge index for the node. + unsafe fn correct_childrens_parent_links>(&mut self, range: R) { + for i in range { + debug_assert!(i <= self.len()); + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(self.reborrow_mut(), i) }.correct_parent_link(); + } + } + + fn correct_all_childrens_parent_links(&mut self) { + let len = self.len(); + // ignore-tidy-undocumented-unsafe + unsafe { self.correct_childrens_parent_links(0..=len) }; + } +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { + /// Sets the node's link to its parent edge, + /// without invalidating other references to the node. + fn set_parent_link(&mut self, parent: NonNull>, parent_idx: usize) { + let leaf = Self::as_leaf_ptr(self); + // ignore-tidy-undocumented-unsafe + unsafe { (*leaf).parent = Some(parent) }; + // ignore-tidy-undocumented-unsafe + unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; + } +} + +impl NodeRef { + /// Clears the root's link to its parent edge. + fn clear_parent_link(&mut self) { + let mut root_node = self.borrow_mut(); + let leaf = root_node.as_leaf_mut(); + leaf.parent = None; + } +} + +impl NodeRef { + /// Returns a new owned tree, with its own root node that is initially empty. + pub(super) fn new(alloc: A) -> Self { + NodeRef::new_leaf(alloc).forget_type() + } + + /// Adds a new internal node with a single edge pointing to the previous root node, + /// make that new node the root node, and return it. This increases the height by 1 + /// and is the opposite of `pop_internal_level`. + pub(super) fn push_internal_level( + &mut self, + alloc: A, + ) -> NodeRef, K, V, marker::Internal> { + super::mem::take_mut(self, |old_root| NodeRef::new_internal(old_root, alloc).forget_type()); + + // `self.borrow_mut()`, except that we just forgot we're internal now: + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } + + /// Removes the internal root node, using its first child as the new root node. + /// As it is intended only to be called when the root node has only one child, + /// no cleanup is done on any of the keys, values and other children. + /// This decreases the height by 1 and is the opposite of `push_internal_level`. + /// + /// Does not invalidate any handles or references pointing into the subtree + /// rooted at the first child of `self`. + /// + /// Panics if there is no internal level, i.e., if the root node is a leaf. + pub(super) fn pop_internal_level(&mut self, alloc: A) { + assert!(self.height > 0); + + let top = self.node; + + // SAFETY: we asserted to be internal. + let mut internal_self = unsafe { self.borrow_mut().cast_to_internal_unchecked() }; + let internal_node = internal_self.as_internal_mut(); + // SAFETY: the first edge is always initialized. + self.node = unsafe { internal_node.edges[0].assume_init_read() }; + self.height -= 1; + self.clear_parent_link(); + + // ignore-tidy-undocumented-unsafe + unsafe { + alloc.deallocate(top.cast(), Layout::new::>()); + } + } +} + +impl NodeRef { + /// Mutably borrows the owned root node. Unlike `reborrow_mut`, this is safe + /// because the return value cannot be used to destroy the root, and there + /// cannot be other references to the tree. + pub(super) fn borrow_mut(&mut self) -> NodeRef, K, V, Type> { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } + + /// Slightly mutably borrows the owned root node. + pub(super) fn borrow_valmut(&mut self) -> NodeRef, K, V, Type> { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } + + /// Irreversibly transitions to a reference that permits traversal and offers + /// destructive methods and little else. + pub(super) fn into_dying(self) -> NodeRef { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Leaf> { + /// Adds a key-value pair to the end of the node, and returns + /// a handle to the inserted value. + /// + /// # Safety + /// + /// The returned handle has an unbound lifetime. + pub(super) unsafe fn push_with_handle<'b>( + &mut self, + key: K, + val: V, + ) -> Handle, K, V, marker::Leaf>, marker::KV> { + let len = self.len_mut(); + let idx = usize::from(*len); + assert!(idx < CAPACITY); + *len += 1; + // ignore-tidy-undocumented-unsafe + unsafe { + self.key_area_mut(idx).write(key); + self.val_area_mut(idx).write(val); + Handle::new_kv( + NodeRef { height: self.height, node: self.node, _marker: PhantomData }, + idx, + ) + } + } + + /// Adds a key-value pair to the end of the node, and returns + /// the mutable reference of the inserted value. + pub(super) fn push(&mut self, key: K, val: V) -> *mut V { + // SAFETY: The unbound handle is no longer accessible. + unsafe { self.push_with_handle(key, val).into_val_mut() } + } +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { + /// Adds a key-value pair, and an edge to go to the right of that pair, + /// to the end of the node. + pub(super) fn push(&mut self, key: K, val: V, edge: Root) { + assert!(edge.height == self.height - 1); + + let len = self.len_mut(); + let idx = usize::from(*len); + assert!(idx < CAPACITY); + *len += 1; + // ignore-tidy-undocumented-unsafe + unsafe { + self.key_area_mut(idx).write(key); + self.val_area_mut(idx).write(val); + self.edge_area_mut(idx + 1).write(edge.node); + Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link(); + } + } +} + +impl NodeRef { + /// Removes any static information asserting that this node is a `Leaf` node. + pub(super) fn forget_type(self) -> NodeRef { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +impl NodeRef { + /// Removes any static information asserting that this node is an `Internal` node. + pub(super) fn forget_type(self) -> NodeRef { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +impl NodeRef { + /// Checks whether a node is an `Internal` node or a `Leaf` node. + pub(super) fn force( + self, + ) -> ForceResult< + NodeRef, + NodeRef, + > { + if self.height == 0 { + ForceResult::Leaf(NodeRef { + height: self.height, + node: self.node, + _marker: PhantomData, + }) + } else { + ForceResult::Internal(NodeRef { + height: self.height, + node: self.node, + _marker: PhantomData, + }) + } + } +} + +impl<'a, K, V> NodeRef, K, V, marker::LeafOrInternal> { + /// Unsafely asserts to the compiler the static information that this node is a `Leaf`. + pub(super) unsafe fn cast_to_leaf_unchecked( + self, + ) -> NodeRef, K, V, marker::Leaf> { + debug_assert!(self.height == 0); + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } + + /// Unsafely asserts to the compiler the static information that this node is an `Internal`. + unsafe fn cast_to_internal_unchecked(self) -> NodeRef, K, V, marker::Internal> { + debug_assert!(self.height > 0); + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +/// A reference to a specific key-value pair or edge within a node. The `Node` parameter +/// must be a `NodeRef`, while the `Type` can either be `KV` (signifying a handle on a key-value +/// pair) or `Edge` (signifying a handle on an edge). +/// +/// Note that even `Leaf` nodes can have `Edge` handles. Instead of representing a pointer to +/// a child node, these represent the spaces where child pointers would go between the key-value +/// pairs. For example, in a node with length 2, there would be 3 possible edge locations - one +/// to the left of the node, one between the two pairs, and one at the right of the node. +pub(super) struct Handle { + node: Node, + idx: usize, + _marker: PhantomData, +} + +impl Copy for Handle {} +// We don't need the full generality of `#[derive(Clone)]`, as the only time `Node` will be +// `Clone`able is when it is an immutable reference and therefore `Copy`. +impl Clone for Handle { + fn clone(&self) -> Self { + *self + } +} + +impl Handle { + /// Retrieves the node that contains the edge or key-value pair this handle points to. + pub(super) fn into_node(self) -> Node { + self.node + } + + /// Returns the position of this handle in the node. + pub(super) fn idx(&self) -> usize { + self.idx + } +} + +impl Handle, marker::KV> { + /// Creates a new handle to a key-value pair in `node`. + /// Unsafe because the caller must ensure that `idx < node.len()`. + pub(super) unsafe fn new_kv(node: NodeRef, idx: usize) -> Self { + debug_assert!(idx < node.len()); + + Handle { node, idx, _marker: PhantomData } + } + + pub(super) fn left_edge(self) -> Handle, marker::Edge> { + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(self.node, self.idx) } + } + + pub(super) fn right_edge(self) -> Handle, marker::Edge> { + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(self.node, self.idx + 1) } + } +} + +impl PartialEq + for Handle, HandleType> +{ + fn eq(&self, other: &Self) -> bool { + let Self { node, idx, _marker } = self; + node.eq(&other.node) && *idx == other.idx + } +} + +impl + Handle, HandleType> +{ + /// Temporarily takes out another immutable handle on the same location. + pub(super) fn reborrow( + &self, + ) -> Handle, K, V, NodeType>, HandleType> { + // We can't use Handle::new_kv or Handle::new_edge because we don't know our type + Handle { node: self.node.reborrow(), idx: self.idx, _marker: PhantomData } + } +} + +impl<'a, K, V, NodeType, HandleType> Handle, K, V, NodeType>, HandleType> { + /// Temporarily takes out another mutable handle on the same location. Beware, as + /// this method is very dangerous, doubly so since it might not immediately appear + /// dangerous. + /// + /// For details, see `NodeRef::reborrow_mut`. + pub(super) unsafe fn reborrow_mut( + &mut self, + ) -> Handle, K, V, NodeType>, HandleType> { + // We can't use Handle::new_kv or Handle::new_edge because we don't know our type + // ignore-tidy-undocumented-unsafe + Handle { node: unsafe { self.node.reborrow_mut() }, idx: self.idx, _marker: PhantomData } + } + + /// Returns a dormant copy of this handle which can be reawakened later. + /// + /// See `DormantMutRef` for more details. + pub(super) fn dormant( + &self, + ) -> Handle, HandleType> { + Handle { node: self.node.dormant(), idx: self.idx, _marker: PhantomData } + } +} + +impl Handle, HandleType> { + /// Revert to the unique borrow initially captured. + /// + /// # Safety + /// + /// The reborrow must have ended, i.e., the reference returned by `new` and + /// all pointers and references derived from it, must not be used anymore. + pub(super) unsafe fn awaken<'a>( + self, + ) -> Handle, K, V, NodeType>, HandleType> { + // ignore-tidy-undocumented-unsafe + Handle { node: unsafe { self.node.awaken() }, idx: self.idx, _marker: PhantomData } + } +} + +impl Handle, marker::Edge> { + /// Creates a new handle to an edge in `node`. + /// Unsafe because the caller must ensure that `idx <= node.len()`. + pub(super) unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { + debug_assert!(idx <= node.len()); + + Handle { node, idx, _marker: PhantomData } + } + + pub(super) fn left_kv( + self, + ) -> Result, marker::KV>, Self> { + if self.idx > 0 { + // ignore-tidy-undocumented-unsafe + Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) }) + } else { + Err(self) + } + } + + pub(super) fn right_kv( + self, + ) -> Result, marker::KV>, Self> { + if self.idx < self.node.len() { + // ignore-tidy-undocumented-unsafe + Ok(unsafe { Handle::new_kv(self.node, self.idx) }) + } else { + Err(self) + } + } +} + +pub(super) enum LeftOrRight { + Left(T), + Right(T), +} + +/// Given an edge index where we want to insert into a node filled to capacity, +/// computes a sensible KV index of a split point and where to perform the insertion. +/// The goal of the split point is for its key and value to end up in a parent node; +/// the keys, values and edges to the left of the split point become the left child; +/// the keys, values and edges to the right of the split point become the right child. +fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight) { + debug_assert!(edge_idx <= CAPACITY); + // Rust issue #74834 tries to explain these symmetric rules. + match edge_idx { + 0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, LeftOrRight::Left(edge_idx)), + EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Left(edge_idx)), + EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Right(0)), + _ => (KV_IDX_CENTER + 1, LeftOrRight::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))), + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { + /// Inserts a new key-value pair between the key-value pairs to the right and left of + /// this edge. This method assumes that there is enough space in the node for the new + /// pair to fit. + unsafe fn insert_fit( + mut self, + key: K, + val: V, + ) -> Handle, K, V, marker::Leaf>, marker::KV> { + debug_assert!(self.node.len() < CAPACITY); + let new_len = self.node.len() + 1; + + // ignore-tidy-undocumented-unsafe + unsafe { + slice_insert(self.node.key_area_mut(..new_len), self.idx, key); + slice_insert(self.node.val_area_mut(..new_len), self.idx, val); + *self.node.len_mut() = new_len as u16; + + Handle::new_kv(self.node, self.idx) + } + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { + /// Inserts a new key-value pair between the key-value pairs to the right and left of + /// this edge. This method splits the node if there isn't enough room. + /// + /// Returns a dormant handle to the inserted node which can be reawakened + /// once splitting is complete. + fn insert( + self, + key: K, + val: V, + alloc: A, + ) -> ( + Option>, + Handle, marker::KV>, + ) { + if self.node.len() < CAPACITY { + // SAFETY: There is enough space in the node for insertion. + let handle = unsafe { self.insert_fit(key, val) }; + (None, handle.dormant()) + } else { + let (middle_kv_idx, insertion) = splitpoint(self.idx); + // ignore-tidy-undocumented-unsafe + let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; + let mut result = middle.split(alloc); + let insertion_edge = match insertion { + // ignore-tidy-undocumented-unsafe + LeftOrRight::Left(insert_idx) => unsafe { + Handle::new_edge(result.left.reborrow_mut(), insert_idx) + }, + // ignore-tidy-undocumented-unsafe + LeftOrRight::Right(insert_idx) => unsafe { + Handle::new_edge(result.right.borrow_mut(), insert_idx) + }, + }; + // SAFETY: We just split the node, so there is enough space for + // insertion. + let handle = unsafe { insertion_edge.insert_fit(key, val).dormant() }; + (Some(result), handle) + } + } +} + +impl<'a, K, V> Handle, K, V, marker::Internal>, marker::Edge> { + /// Fixes the parent pointer and index in the child node that this edge + /// links to. This is useful when the ordering of edges has been changed, + #[requires(verify::can_relink(&self.node, self.idx))] + #[ensures(|_| verify::has_parent_link( + old(verify::relink_child(&self.node, self.idx)), old(self.node.node.cast()), old(self.idx), + ))] + #[cfg_attr(kani, kani::modifies( + unsafe { &raw mut (*verify::relink_child(&self.node, self.idx)).parent }, + unsafe { &raw mut (*verify::relink_child(&self.node, self.idx)).parent_idx }, + ))] + fn correct_parent_link(self) { + // Create backpointer without invalidating other references to the node. + // ignore-tidy-undocumented-unsafe + let ptr = unsafe { NonNull::new_unchecked(NodeRef::as_internal_ptr(&self.node)) }; + let idx = self.idx; + let mut child = self.descend(); + child.set_parent_link(ptr, idx); + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { + /// Inserts a new key-value pair and an edge that will go to the right of that new pair + /// between this edge and the key-value pair to the right of this edge. This method assumes + /// that there is enough space in the node for the new pair to fit. + fn insert_fit(&mut self, key: K, val: V, edge: Root) { + debug_assert!(self.node.len() < CAPACITY); + debug_assert!(edge.height == self.node.height - 1); + let new_len = self.node.len() + 1; + + // ignore-tidy-undocumented-unsafe + unsafe { + slice_insert(self.node.key_area_mut(..new_len), self.idx, key); + slice_insert(self.node.val_area_mut(..new_len), self.idx, val); + slice_insert(self.node.edge_area_mut(..new_len + 1), self.idx + 1, edge.node); + *self.node.len_mut() = new_len as u16; + + self.node.correct_childrens_parent_links(self.idx + 1..new_len + 1); + } + } + + /// Inserts a new key-value pair and an edge that will go to the right of that new pair + /// between this edge and the key-value pair to the right of this edge. This method splits + /// the node if there isn't enough room. + fn insert( + mut self, + key: K, + val: V, + edge: Root, + alloc: A, + ) -> Option> { + assert!(edge.height == self.node.height - 1); + + if self.node.len() < CAPACITY { + self.insert_fit(key, val, edge); + None + } else { + let (middle_kv_idx, insertion) = splitpoint(self.idx); + // ignore-tidy-undocumented-unsafe + let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; + let mut result = middle.split(alloc); + let mut insertion_edge = match insertion { + // ignore-tidy-undocumented-unsafe + LeftOrRight::Left(insert_idx) => unsafe { + Handle::new_edge(result.left.reborrow_mut(), insert_idx) + }, + // ignore-tidy-undocumented-unsafe + LeftOrRight::Right(insert_idx) => unsafe { + Handle::new_edge(result.right.borrow_mut(), insert_idx) + }, + }; + insertion_edge.insert_fit(key, val, edge); + Some(result) + } + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { + /// Inserts a new key-value pair between the key-value pairs to the right and left of + /// this edge. This method splits the node if there isn't enough room, and tries to + /// insert the split off portion into the parent node recursively, until the root is reached. + /// + /// If the returned result is some `SplitResult`, the `left` field will be the root node. + /// The returned pointer points to the inserted value, which in the case of `SplitResult` + /// is in the `left` or `right` tree. + pub(super) fn insert_recursing( + self, + key: K, + value: V, + alloc: A, + split_root: impl FnOnce(SplitResult<'a, K, V, marker::LeafOrInternal>), + ) -> Handle, K, V, marker::Leaf>, marker::KV> { + let (mut split, handle) = match self.insert(key, value, alloc.clone()) { + // SAFETY: we have finished splitting and can now re-awaken the + // handle to the inserted element. + (None, handle) => return unsafe { handle.awaken() }, + (Some(split), handle) => (split.forget_node_type(), handle), + }; + + loop { + split = match split.left.ascend() { + Ok(parent) => { + match parent.insert(split.kv.0, split.kv.1, split.right, alloc.clone()) { + // SAFETY: we have finished splitting and can now re-awaken the + // handle to the inserted element. + None => return unsafe { handle.awaken() }, + Some(split) => split.forget_node_type(), + } + } + Err(root) => { + split_root(SplitResult { left: root, ..split }); + // SAFETY: we have finished splitting and can now re-awaken the + // handle to the inserted element. + return unsafe { handle.awaken() }; + } + }; + } + } +} + +impl + Handle, marker::Edge> +{ + /// Finds the node pointed to by this edge. + /// + /// The method name assumes you picture trees with the root node on top. + /// + /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should + /// both, upon success, do nothing. + pub(super) fn descend(self) -> NodeRef { + const { + assert!(BorrowType::TRAVERSAL_PERMIT); + } + + // We need to use raw pointers to nodes because, if BorrowType is + // marker::ValMut, there might be outstanding mutable references to + // values that we must not invalidate. There's no worry accessing the + // height field because that value is copied. Beware that, once the + // node pointer is dereferenced, we access the edges array with a + // reference (Rust issue #73987) and invalidate any other references + // to or inside the array, should any be around. + let parent_ptr = NodeRef::as_internal_ptr(&self.node); + // ignore-tidy-undocumented-unsafe + let node = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() }; + NodeRef { node, height: self.node.height - 1, _marker: PhantomData } + } +} + +impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { + pub(super) fn into_kv(self) -> (&'a K, &'a V) { + debug_assert!(self.idx < self.node.len()); + let leaf = self.node.into_leaf(); + // ignore-tidy-undocumented-unsafe + let k = unsafe { leaf.keys.get_unchecked(self.idx).assume_init_ref() }; + // ignore-tidy-undocumented-unsafe + let v = unsafe { leaf.vals.get_unchecked(self.idx).assume_init_ref() }; + (k, v) + } +} + +impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { + pub(super) fn key_mut(&mut self) -> &mut K { + // ignore-tidy-undocumented-unsafe + unsafe { self.node.key_area_mut(self.idx).assume_init_mut() } + } + + pub(super) fn into_val_mut(self) -> &'a mut V { + debug_assert!(self.idx < self.node.len()); + let leaf = self.node.into_leaf_mut(); + // ignore-tidy-undocumented-unsafe + unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() } + } + + pub(super) fn into_kv_mut(self) -> (&'a mut K, &'a mut V) { + debug_assert!(self.idx < self.node.len()); + let leaf = self.node.into_leaf_mut(); + // ignore-tidy-undocumented-unsafe + let k = unsafe { leaf.keys.get_unchecked_mut(self.idx).assume_init_mut() }; + // ignore-tidy-undocumented-unsafe + let v = unsafe { leaf.vals.get_unchecked_mut(self.idx).assume_init_mut() }; + (k, v) + } +} + +impl<'a, K, V, NodeType> Handle, K, V, NodeType>, marker::KV> { + pub(super) fn into_kv_valmut(self) -> (&'a K, &'a mut V) { + // ignore-tidy-undocumented-unsafe + unsafe { self.node.into_key_val_mut_at(self.idx) } + } +} + +impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { + pub(super) fn kv_mut(&mut self) -> (&mut K, &mut V) { + debug_assert!(self.idx < self.node.len()); + // We cannot call separate key and value methods, because calling the second one + // invalidates the reference returned by the first. + // ignore-tidy-undocumented-unsafe + unsafe { + let leaf = self.node.as_leaf_mut(); + let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_mut(); + let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_mut(); + (key, val) + } + } + + /// Replaces the key and value that the KV handle refers to. + pub(super) fn replace_kv(&mut self, k: K, v: V) -> (K, V) { + let (key, val) = self.kv_mut(); + (mem::replace(key, k), mem::replace(val, v)) + } +} + +impl Handle, marker::KV> { + /// Extracts the key and value that the KV handle refers to. + /// # Safety + /// The node that the handle refers to must not yet have been deallocated. + pub(super) unsafe fn into_key_val(mut self) -> (K, V) { + debug_assert!(self.idx < self.node.len()); + let leaf = self.node.as_leaf_dying(); + // ignore-tidy-undocumented-unsafe + unsafe { + let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_read(); + let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_read(); + (key, val) + } + } + + /// Drops the key and value that the KV handle refers to. + /// # Safety + /// The node that the handle refers to must not yet have been deallocated. + #[inline] + pub(super) unsafe fn drop_key_val(mut self) { + // Run the destructor of the value even if the destructor of the key panics. + struct Dropper<'a, T>(&'a mut MaybeUninit); + impl Drop for Dropper<'_, T> { + #[inline] + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + self.0.assume_init_drop(); + } + } + } + + debug_assert!(self.idx < self.node.len()); + let leaf = self.node.as_leaf_dying(); + // ignore-tidy-undocumented-unsafe + unsafe { + let key = leaf.keys.get_unchecked_mut(self.idx); + let val = leaf.vals.get_unchecked_mut(self.idx); + let _guard = Dropper(val); + key.assume_init_drop(); + // dropping the guard will drop the value + } + } +} + +impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { + /// Helps implementations of `split` for a particular `NodeType`, + /// by taking care of leaf data. + #[requires(verify::can_split_leaf_data(&self.node, self.idx, new_node))] + #[ensures(|_| { + self.node.len() == old(self.idx) + && usize::from(new_node.len) == old(self.node.len() - self.idx - 1) + })] + #[cfg_attr(kani, kani::modifies( + unsafe { &raw mut (*NodeRef::as_leaf_ptr(&self.node)).len }, + &raw mut new_node.len, + &raw mut new_node.keys, + &raw mut new_node.vals, + ))] + fn split_leaf_data(&mut self, new_node: &mut LeafNode) -> (K, V) { + debug_assert!(self.idx < self.node.len()); + let old_len = self.node.len(); + let new_len = old_len - self.idx - 1; + new_node.len = new_len as u16; + // ignore-tidy-undocumented-unsafe + unsafe { + let k = self.node.key_area_mut(self.idx).assume_init_read(); + let v = self.node.val_area_mut(self.idx).assume_init_read(); + + move_to_slice( + self.node.key_area_mut(self.idx + 1..old_len), + &mut new_node.keys[..new_len], + ); + move_to_slice( + self.node.val_area_mut(self.idx + 1..old_len), + &mut new_node.vals[..new_len], + ); + + *self.node.len_mut() = self.idx as u16; + (k, v) + } + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { + /// Splits the underlying node into three parts: + /// + /// - The node is truncated to only contain the key-value pairs to the left of + /// this handle. + /// - The key and value pointed to by this handle are extracted. + /// - All the key-value pairs to the right of this handle are put into a newly + /// allocated node. + pub(super) fn split( + mut self, + alloc: A, + ) -> SplitResult<'a, K, V, marker::Leaf> { + let mut new_node = LeafNode::new(alloc); + + let kv = self.split_leaf_data(&mut new_node); + + let right = NodeRef::from_new_leaf(new_node); + SplitResult { left: self.node, kv, right } + } + + /// Removes the key-value pair pointed to by this handle and returns it, along with the edge + /// that the key-value pair collapsed into. + pub(super) fn remove( + mut self, + ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { + let old_len = self.node.len(); + // ignore-tidy-undocumented-unsafe + unsafe { + let k = slice_remove(self.node.key_area_mut(..old_len), self.idx); + let v = slice_remove(self.node.val_area_mut(..old_len), self.idx); + *self.node.len_mut() = (old_len - 1) as u16; + ((k, v), self.left_edge()) + } + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { + /// Splits the underlying node into three parts: + /// + /// - The node is truncated to only contain the edges and key-value pairs to the + /// left of this handle. + /// - The key and value pointed to by this handle are extracted. + /// - All the edges and key-value pairs to the right of this handle are put into + /// a newly allocated node. + pub(super) fn split( + mut self, + alloc: A, + ) -> SplitResult<'a, K, V, marker::Internal> { + let old_len = self.node.len(); + // ignore-tidy-undocumented-unsafe + unsafe { + let mut new_node = InternalNode::new(alloc); + let kv = self.split_leaf_data(&mut new_node.data); + let new_len = usize::from(new_node.data.len); + move_to_slice( + self.node.edge_area_mut(self.idx + 1..old_len + 1), + &mut new_node.edges[..new_len + 1], + ); + + // SAFETY: self is `marker::Internal`, so `self.node.height` is positive + let height = NonZero::new_unchecked(self.node.height); + let right = NodeRef::from_new_internal(new_node, height); + + SplitResult { left: self.node, kv, right } + } + } +} + +/// Represents a session for evaluating and performing a balancing operation +/// around an internal key-value pair. +pub(super) struct BalancingContext<'a, K, V> { + parent: Handle, K, V, marker::Internal>, marker::KV>, + left_child: NodeRef, K, V, marker::LeafOrInternal>, + right_child: NodeRef, K, V, marker::LeafOrInternal>, +} + +impl<'a, K, V> Handle, K, V, marker::Internal>, marker::KV> { + pub(super) fn consider_for_balancing(self) -> BalancingContext<'a, K, V> { + // ignore-tidy-undocumented-unsafe + let self1 = unsafe { ptr::read(&self) }; + // ignore-tidy-undocumented-unsafe + let self2 = unsafe { ptr::read(&self) }; + BalancingContext { + parent: self, + left_child: self1.left_edge().descend(), + right_child: self2.right_edge().descend(), + } + } +} + +impl<'a, K, V> NodeRef, K, V, marker::LeafOrInternal> { + /// Chooses a balancing context involving the node as a child, thus between + /// the KV immediately to the left or to the right in the parent node. + /// Returns an `Err` if there is no parent. + /// Panics if the parent is empty. + /// + /// Prefers the left side, to be optimal if the given node is somehow + /// underfull, meaning here only that it has fewer elements than its left + /// sibling and than its right sibling, if they exist. In that case, + /// merging with the left sibling is faster, since we only need to move + /// the node's N elements, instead of shifting them to the right and moving + /// more than N elements in front. Stealing from the left sibling is also + /// typically faster, since we only need to shift the node's N elements to + /// the right, instead of shifting at least N of the sibling's elements to + /// the left. + pub(super) fn choose_parent_kv(self) -> Result>, Self> { + // ignore-tidy-undocumented-unsafe + match unsafe { ptr::read(&self) }.ascend() { + Ok(parent_edge) => match parent_edge.left_kv() { + Ok(left_parent_kv) => Ok(LeftOrRight::Left(BalancingContext { + // ignore-tidy-undocumented-unsafe + parent: unsafe { ptr::read(&left_parent_kv) }, + left_child: left_parent_kv.left_edge().descend(), + right_child: self, + })), + Err(parent_edge) => match parent_edge.right_kv() { + Ok(right_parent_kv) => Ok(LeftOrRight::Right(BalancingContext { + // ignore-tidy-undocumented-unsafe + parent: unsafe { ptr::read(&right_parent_kv) }, + left_child: self, + right_child: right_parent_kv.right_edge().descend(), + })), + Err(_) => unreachable!("empty internal node"), + }, + }, + Err(root) => Err(root), + } + } +} + +impl<'a, K, V> BalancingContext<'a, K, V> { + pub(super) fn left_child_len(&self) -> usize { + self.left_child.len() + } + + pub(super) fn right_child_len(&self) -> usize { + self.right_child.len() + } + + pub(super) fn into_left_child(self) -> NodeRef, K, V, marker::LeafOrInternal> { + self.left_child + } + + pub(super) fn into_right_child(self) -> NodeRef, K, V, marker::LeafOrInternal> { + self.right_child + } + + /// Returns whether merging is possible, i.e., whether there is enough room + /// in a node to combine the central KV with both adjacent child nodes. + pub(super) fn can_merge(&self) -> bool { + self.left_child.len() + 1 + self.right_child.len() <= CAPACITY + } +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { + /// Performs a merge and lets a closure decide what to return. + fn do_merge< + F: FnOnce( + NodeRef, K, V, marker::Internal>, + NodeRef, K, V, marker::LeafOrInternal>, + ) -> R, + R, + A: Allocator, + >( + self, + result: F, + alloc: A, + ) -> R { + let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent; + let old_parent_len = parent_node.len(); + let mut left_node = self.left_child; + let old_left_len = left_node.len(); + let mut right_node = self.right_child; + let right_len = right_node.len(); + let new_left_len = old_left_len + 1 + right_len; + + assert!(new_left_len <= CAPACITY); + + // ignore-tidy-undocumented-unsafe + unsafe { + *left_node.len_mut() = new_left_len as u16; + + let parent_key = slice_remove(parent_node.key_area_mut(..old_parent_len), parent_idx); + left_node.key_area_mut(old_left_len).write(parent_key); + move_to_slice( + right_node.key_area_mut(..right_len), + left_node.key_area_mut(old_left_len + 1..new_left_len), + ); + + let parent_val = slice_remove(parent_node.val_area_mut(..old_parent_len), parent_idx); + left_node.val_area_mut(old_left_len).write(parent_val); + move_to_slice( + right_node.val_area_mut(..right_len), + left_node.val_area_mut(old_left_len + 1..new_left_len), + ); + + slice_remove(parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1); + parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len); + *parent_node.len_mut() -= 1; + + if parent_node.height > 1 { + // SAFETY: the height of the nodes being merged is one below the height + // of the node of this edge, thus above zero, so they are internal. + let mut left_node = left_node.reborrow_mut().cast_to_internal_unchecked(); + let mut right_node = right_node.cast_to_internal_unchecked(); + move_to_slice( + right_node.edge_area_mut(..right_len + 1), + left_node.edge_area_mut(old_left_len + 1..new_left_len + 1), + ); + + left_node.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); + + alloc.deallocate(right_node.node.cast(), Layout::new::>()); + } else { + alloc.deallocate(right_node.node.cast(), Layout::new::>()); + } + } + result(parent_node, left_node) + } + + /// Merges the parent's key-value pair and both adjacent child nodes into + /// the left child node and returns the shrunk parent node. + /// + /// Panics unless we `.can_merge()`. + pub(super) fn merge_tracking_parent( + self, + alloc: A, + ) -> NodeRef, K, V, marker::Internal> { + self.do_merge(|parent, _child| parent, alloc) + } + + /// Merges the parent's key-value pair and both adjacent child nodes into + /// the left child node and returns that child node. + /// + /// Panics unless we `.can_merge()`. + pub(super) fn merge_tracking_child( + self, + alloc: A, + ) -> NodeRef, K, V, marker::LeafOrInternal> { + self.do_merge(|_parent, child| child, alloc) + } + + /// Merges the parent's key-value pair and both adjacent child nodes into + /// the left child node and returns the edge handle in that child node + /// where the tracked child edge ended up, + /// + /// Panics unless we `.can_merge()`. + pub(super) fn merge_tracking_child_edge( + self, + track_edge_idx: LeftOrRight, + alloc: A, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { + let old_left_len = self.left_child.len(); + let right_len = self.right_child.len(); + assert!(match track_edge_idx { + LeftOrRight::Left(idx) => idx <= old_left_len, + LeftOrRight::Right(idx) => idx <= right_len, + }); + let child = self.merge_tracking_child(alloc); + let new_idx = match track_edge_idx { + LeftOrRight::Left(idx) => idx, + LeftOrRight::Right(idx) => old_left_len + 1 + idx, + }; + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(child, new_idx) } + } + + /// Removes a key-value pair from the left child and places it in the key-value storage + /// of the parent, while pushing the old parent key-value pair into the right child. + /// Returns a handle to the edge in the right child corresponding to where the original + /// edge specified by `track_right_edge_idx` ended up. + pub(super) fn steal_left( + mut self, + track_right_edge_idx: usize, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { + self.bulk_steal_left(1); + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(self.right_child, 1 + track_right_edge_idx) } + } + + /// Removes a key-value pair from the right child and places it in the key-value storage + /// of the parent, while pushing the old parent key-value pair onto the left child. + /// Returns a handle to the edge in the left child specified by `track_left_edge_idx`, + /// which didn't move. + pub(super) fn steal_right( + mut self, + track_left_edge_idx: usize, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { + self.bulk_steal_right(1); + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(self.left_child, track_left_edge_idx) } + } + + /// This does stealing similar to `steal_left` but steals multiple elements at once. + pub(super) fn bulk_steal_left(&mut self, count: usize) { + assert!(count > 0); + // ignore-tidy-undocumented-unsafe + unsafe { + let left_node = &mut self.left_child; + let old_left_len = left_node.len(); + let right_node = &mut self.right_child; + let old_right_len = right_node.len(); + + // Make sure that we may steal safely. + assert!(old_right_len + count <= CAPACITY); + assert!(old_left_len >= count); + + let new_left_len = old_left_len - count; + let new_right_len = old_right_len + count; + *left_node.len_mut() = new_left_len as u16; + *right_node.len_mut() = new_right_len as u16; + + // Move leaf data. + { + // Make room for stolen elements in the right child. + slice_shr(right_node.key_area_mut(..new_right_len), count); + slice_shr(right_node.val_area_mut(..new_right_len), count); + + // Move elements from the left child to the right one. + move_to_slice( + left_node.key_area_mut(new_left_len + 1..old_left_len), + right_node.key_area_mut(..count - 1), + ); + move_to_slice( + left_node.val_area_mut(new_left_len + 1..old_left_len), + right_node.val_area_mut(..count - 1), + ); + + // Move the leftmost stolen pair to the parent. + let k = left_node.key_area_mut(new_left_len).assume_init_read(); + let v = left_node.val_area_mut(new_left_len).assume_init_read(); + let (k, v) = self.parent.replace_kv(k, v); + + // Move parent's key-value pair to the right child. + right_node.key_area_mut(count - 1).write(k); + right_node.val_area_mut(count - 1).write(v); + } + + match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { + (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { + // Make room for stolen edges. + slice_shr(right.edge_area_mut(..new_right_len + 1), count); + + // Steal edges. + move_to_slice( + left.edge_area_mut(new_left_len + 1..old_left_len + 1), + right.edge_area_mut(..count), + ); + + right.correct_childrens_parent_links(0..new_right_len + 1); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} + _ => unreachable!(), + } + } + } + + /// The symmetric clone of `bulk_steal_left`. + pub(super) fn bulk_steal_right(&mut self, count: usize) { + assert!(count > 0); + // ignore-tidy-undocumented-unsafe + unsafe { + let left_node = &mut self.left_child; + let old_left_len = left_node.len(); + let right_node = &mut self.right_child; + let old_right_len = right_node.len(); + + // Make sure that we may steal safely. + assert!(old_left_len + count <= CAPACITY); + assert!(old_right_len >= count); + + let new_left_len = old_left_len + count; + let new_right_len = old_right_len - count; + *left_node.len_mut() = new_left_len as u16; + *right_node.len_mut() = new_right_len as u16; + + // Move leaf data. + { + // Move the rightmost stolen pair to the parent. + let k = right_node.key_area_mut(count - 1).assume_init_read(); + let v = right_node.val_area_mut(count - 1).assume_init_read(); + let (k, v) = self.parent.replace_kv(k, v); + + // Move parent's key-value pair to the left child. + left_node.key_area_mut(old_left_len).write(k); + left_node.val_area_mut(old_left_len).write(v); + + // Move elements from the right child to the left one. + move_to_slice( + right_node.key_area_mut(..count - 1), + left_node.key_area_mut(old_left_len + 1..new_left_len), + ); + move_to_slice( + right_node.val_area_mut(..count - 1), + left_node.val_area_mut(old_left_len + 1..new_left_len), + ); + + // Fill gap where stolen elements used to be. + slice_shl(right_node.key_area_mut(..old_right_len), count); + slice_shl(right_node.val_area_mut(..old_right_len), count); + } + + match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { + (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { + // Steal edges. + move_to_slice( + right.edge_area_mut(..count), + left.edge_area_mut(old_left_len + 1..new_left_len + 1), + ); + + // Fill gap where stolen edges used to be. + slice_shl(right.edge_area_mut(..old_right_len + 1), count); + + left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); + right.correct_childrens_parent_links(0..new_right_len + 1); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} + _ => unreachable!(), + } + } + } +} + +impl Handle, marker::Edge> { + pub(super) fn forget_node_type( + self, + ) -> Handle, marker::Edge> { + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(self.node.forget_type(), self.idx) } + } +} + +impl Handle, marker::Edge> { + pub(super) fn forget_node_type( + self, + ) -> Handle, marker::Edge> { + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_edge(self.node.forget_type(), self.idx) } + } +} + +impl Handle, marker::KV> { + pub(super) fn forget_node_type( + self, + ) -> Handle, marker::KV> { + // ignore-tidy-undocumented-unsafe + unsafe { Handle::new_kv(self.node.forget_type(), self.idx) } + } +} + +impl Handle, Type> { + /// Checks whether the underlying node is an `Internal` node or a `Leaf` node. + pub(super) fn force( + self, + ) -> ForceResult< + Handle, Type>, + Handle, Type>, + > { + match self.node.force() { + ForceResult::Leaf(node) => { + ForceResult::Leaf(Handle { node, idx: self.idx, _marker: PhantomData }) + } + ForceResult::Internal(node) => { + ForceResult::Internal(Handle { node, idx: self.idx, _marker: PhantomData }) + } + } + } +} + +impl<'a, K, V, Type> Handle, K, V, marker::LeafOrInternal>, Type> { + /// Unsafely asserts to the compiler the static information that the handle's node is a `Leaf`. + pub(super) unsafe fn cast_to_leaf_unchecked( + self, + ) -> Handle, K, V, marker::Leaf>, Type> { + // ignore-tidy-undocumented-unsafe + let node = unsafe { self.node.cast_to_leaf_unchecked() }; + Handle { node, idx: self.idx, _marker: PhantomData } + } +} + +impl<'a, K, V> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { + /// Move the suffix after `self` from one node to another one. `right` must be empty. + /// The first edge of `right` remains unchanged. + pub(super) fn move_suffix( + &mut self, + right: &mut NodeRef, K, V, marker::LeafOrInternal>, + ) { + // ignore-tidy-undocumented-unsafe + unsafe { + let new_left_len = self.idx; + let mut left_node = self.reborrow_mut().into_node(); + let old_left_len = left_node.len(); + + let new_right_len = old_left_len - new_left_len; + let mut right_node = right.reborrow_mut(); + + assert!(right_node.len() == 0); + assert!(left_node.height == right_node.height); + + if new_right_len > 0 { + *left_node.len_mut() = new_left_len as u16; + *right_node.len_mut() = new_right_len as u16; + + move_to_slice( + left_node.key_area_mut(new_left_len..old_left_len), + right_node.key_area_mut(..new_right_len), + ); + move_to_slice( + left_node.val_area_mut(new_left_len..old_left_len), + right_node.val_area_mut(..new_right_len), + ); + match (left_node.force(), right_node.force()) { + (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { + move_to_slice( + left.edge_area_mut(new_left_len + 1..old_left_len + 1), + right.edge_area_mut(1..new_right_len + 1), + ); + right.correct_childrens_parent_links(1..new_right_len + 1); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} + _ => unreachable!(), + } + } + } + } +} + +pub(super) enum ForceResult { + Leaf(Leaf), + Internal(Internal), +} + +/// Result of insertion, when a node needed to expand beyond its capacity. +pub(super) struct SplitResult<'a, K, V, NodeType> { + // Altered node in existing tree with elements and edges that belong to the left of `kv`. + pub left: NodeRef, K, V, NodeType>, + // Some key and value that existed before and were split off, to be inserted elsewhere. + pub kv: (K, V), + // Owned, unattached, new node with elements and edges that belong to the right of `kv`. + pub right: NodeRef, +} + +impl<'a, K, V> SplitResult<'a, K, V, marker::Leaf> { + pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> { + SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() } + } +} + +impl<'a, K, V> SplitResult<'a, K, V, marker::Internal> { + pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> { + SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() } + } +} + +pub(super) mod marker { + use core::marker::PhantomData; + + pub(crate) enum Leaf {} + pub(crate) enum Internal {} + pub(crate) enum LeafOrInternal {} + + pub(crate) enum Owned {} + pub(crate) enum Dying {} + pub(crate) enum DormantMut {} + pub(crate) struct Immut<'a>(PhantomData<&'a ()>); + pub(crate) struct Mut<'a>(PhantomData<&'a mut ()>); + pub(crate) struct ValMut<'a>(PhantomData<&'a mut ()>); + + pub(crate) trait BorrowType { + /// If node references of this borrow type allow traversing to other + /// nodes in the tree, this constant is set to `true`. It can be used + /// for a compile-time assertion. + const TRAVERSAL_PERMIT: bool = true; + } + impl BorrowType for Owned { + /// Reject traversal, because it isn't needed. Instead traversal + /// happens using the result of `borrow_mut`. + /// By disabling traversal, and only creating new references to roots, + /// we know that every reference of the `Owned` type is to a root node. + const TRAVERSAL_PERMIT: bool = false; + } + impl BorrowType for Dying {} + impl<'a> BorrowType for Immut<'a> {} + impl<'a> BorrowType for Mut<'a> {} + impl<'a> BorrowType for ValMut<'a> {} + impl BorrowType for DormantMut {} + + pub(crate) enum KV {} + pub(crate) enum Edge {} +} + +/// Inserts a value into a slice of initialized elements followed by one uninitialized element. +/// +/// # Safety +/// The slice has more than `idx` elements. +#[requires(idx < slice.len())] +#[cfg_attr(kani, kani::modifies(ptr::slice_from_raw_parts_mut( + unsafe { slice.as_mut_ptr().add(idx) }, + slice.len() - idx, +)))] +unsafe fn slice_insert(slice: &mut [MaybeUninit], idx: usize, val: T) { + let len = slice.len(); + debug_assert!(len > idx); + let slice_ptr = slice.as_mut_ptr(); + // ignore-tidy-undocumented-unsafe + unsafe { + if len > idx + 1 { + ptr::copy(slice_ptr.add(idx), slice_ptr.add(idx + 1), len - idx - 1); + } + (*slice_ptr.add(idx)).write(val); + } +} + +/// Removes and returns a value from a slice of all initialized elements, leaving behind one +/// trailing uninitialized element. +/// +/// # Safety +/// The slice has more than `idx` elements. +unsafe fn slice_remove(slice: &mut [MaybeUninit], idx: usize) -> T { + let len = slice.len(); + debug_assert!(idx < len); + let slice_ptr = slice.as_mut_ptr(); + // ignore-tidy-undocumented-unsafe + unsafe { + let ret = (*slice_ptr.add(idx)).assume_init_read(); + ptr::copy(slice_ptr.add(idx + 1), slice_ptr.add(idx), len - idx - 1); + ret + } +} + +/// Shifts the elements in a slice `distance` positions to the left. +/// +/// # Safety +/// The slice has at least `distance` elements. +unsafe fn slice_shl(slice: &mut [MaybeUninit], distance: usize) { + let slice_ptr = slice.as_mut_ptr(); + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::copy(slice_ptr.add(distance), slice_ptr, slice.len() - distance); + } +} + +/// Shifts the elements in a slice `distance` positions to the right. +/// +/// # Safety +/// The slice has at least `distance` elements. +unsafe fn slice_shr(slice: &mut [MaybeUninit], distance: usize) { + let slice_ptr = slice.as_mut_ptr(); + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::copy(slice_ptr, slice_ptr.add(distance), slice.len() - distance); + } +} + +/// Moves all values from a slice of initialized elements to a slice +/// of uninitialized elements, leaving behind `src` as all uninitialized. +/// Works like `dst.copy_from_slice(src)` but does not require `T` to be `Copy`. +#[requires(src.len() == dst.len())] +#[cfg_attr(kani, kani::modifies(dst))] +fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) { + assert!(src.len() == dst.len()); + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len()); + } +} + +#[cfg(test)] +mod tests; + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use core::cell::Cell; + + use super::*; + use crate::alloc::{AllocError, Global}; + + type OwnedLeaf = NodeRef; + type OwnedInternal = NodeRef; + + const fn empty_leaf() -> LeafNode { + LeafNode { + parent: None, + parent_idx: MaybeUninit::uninit(), + len: 0, + keys: [const { MaybeUninit::uninit() }; CAPACITY], + vals: [const { MaybeUninit::uninit() }; CAPACITY], + } + } + + const fn empty_internal() -> InternalNode { + InternalNode { data: empty_leaf(), edges: [const { MaybeUninit::uninit() }; CAPACITY + 1] } + } + + fn borrow_leaf( + leaf: &mut LeafNode, + ) -> NodeRef, K, V, marker::Leaf> { + NodeRef { height: 0, node: NonNull::from_mut(leaf), _marker: PhantomData } + } + + #[derive(Default)] + struct TrackingAllocator { + freed: Cell, Layout)>>, + } + + // SAFETY: Global handles allocation and deallocation. Bookkeeping does not affect live allocations. + unsafe impl Allocator for TrackingAllocator { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + Global.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // SAFETY: The caller provides a live allocation and its layout. + unsafe { Global.deallocate(ptr, layout) }; + self.freed.set(Some((ptr, layout))); + } + } + + fn leaf_with_len(len: usize) -> OwnedLeaf { + OwnedLeaf::from_new_leaf(Box::new(leaf_for_insertion(len))) + } + + // Initialize exactly the live prefix in bulk, including when len is symbolic. + fn leaf_for_insertion(len: usize) -> LeafNode { + assert!(len <= CAPACITY); + let mut leaf = empty_leaf(); + let keys = kani::any::<[u8; CAPACITY]>(); + let vals = kani::any::<[u8; CAPACITY]>(); + // SAFETY: The arrays have the same capacity. The source bytes are initialized and the + // destination prefixes are separate storage. + unsafe { + ptr::copy_nonoverlapping(keys.as_ptr(), leaf.keys.as_mut_ptr().cast(), len); + ptr::copy_nonoverlapping(vals.as_ptr(), leaf.vals.as_mut_ptr().cast(), len); + } + leaf.len = len as u16; + leaf + } + + /// Constructs a leaf with a Kani-selected length in the complete legal range + /// `0..=CAPACITY`. The owned node has a live allocation, a detached header, + /// and exactly len initialized key/value slots. + /// Key/value contents are symbolic; this helper is used for structural and memory-safety + /// properties rather than position-sensitive content checks. + fn verifier_leaf() -> (OwnedLeaf, usize) { + let len = kani::any_where(|len: &usize| *len <= CAPACITY); + (leaf_with_len(len), len) + } + + /// Constructs a non-empty leaf with a Kani-selected length in `1..=CAPACITY`. + /// A non-empty fixture is required by APIs such as `first_kv` and `last_kv`, + /// whose precondition is that at least one key/value is initialized. + fn verifier_nonempty_leaf() -> (OwnedLeaf, usize) { + let len = kani::any_where(|len: &usize| *len > 0 && *len <= CAPACITY); + (leaf_with_len(len), len) + } + + fn internal_root_with_child( + child: Root, + alloc: A, + ) -> NodeRef { + let height = child.height + 1; + // SAFETY: The fixture initializes the first edge before using the internal node. + let mut parent = unsafe { InternalNode::new(alloc) }; + parent.edges[0].write(child.node); + let (parent, _alloc) = Box::into_non_null_with_allocator(parent); + let mut parent = NodeRef::from_internal(parent, height); + parent.borrow_mut().first_edge().correct_parent_link(); + parent + } + + // Use disjoint leaf subobjects for proofs that only relink the existing children. They live + // through the whole call. Operations that deallocate a child must first give that edge a + // separately allocated node. + fn internal_with_borrowed_children<'a, K: kani::Arbitrary + Copy, V: kani::Arbitrary + Copy>( + parent: &'a mut InternalNode, + children: &'a mut [LeafNode; CAPACITY + 1], + len: usize, + ) -> NodeRef, K, V, marker::Internal> { + assert!(len <= CAPACITY); + const { assert!(CAPACITY == 11) }; + let keys = kani::any::<[K; CAPACITY]>(); + let vals = kani::any::<[V; CAPACITY]>(); + let parent = NonNull::from_mut(parent); + let parent_ptr = parent.as_ptr(); + let child_ptr = children.as_mut_ptr(); + let link_child = move |i: usize| { + // SAFETY: Each call initializes a distinct live child and a distinct edge in the + // separately borrowed parent. + unsafe { + let child = &mut *child_ptr.add(i); + child.parent = Some(parent); + child.parent_idx.write(i as u16); + (*parent_ptr).edges[i].write(NonNull::from_mut(child)); + } + }; + link_child(0); + macro_rules! initialize_entries { + ($($i:literal),*) => { + $(if $i < len { + // SAFETY: The parent is live and exclusively borrowed by the fixture. + let data = unsafe { &mut (*parent_ptr).data }; + data.keys[$i].write(keys[$i]); + data.vals[$i].write(vals[$i]); + link_child($i + 1); + })* + }; + } + initialize_entries!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + // SAFETY: All live key, value, and edge slots of the owned parent storage are initialized. + unsafe { (*parent_ptr).data.len = len as u16 }; + NodeRef::from_internal(parent, 1) + } + + pub(super) fn ascend_link( + node: &NodeRef, + ) -> Option<(NonNull>, usize)> { + let child = NodeRef::as_leaf_ptr(node); + // SAFETY: The precondition checks the child and, if attached, the backlink index. + unsafe { (*child).parent.map(|parent| (parent, (*child).parent_idx.assume_init().into())) } + } + + pub(super) fn can_ascend( + node: &NodeRef, + ) -> bool { + let child = NodeRef::as_leaf_ptr(node); + // SAFETY: The raw field addresses are formed within the live child prefix. The index + // is only read when a parent is present and its value can be read as a u16. + unsafe { + core::ub_checks::can_dereference(child) + && ((*child).parent.is_none() + || (node.height < usize::MAX + && core::ub_checks::can_dereference((*child).parent_idx.as_ptr()))) + } + } + + pub(super) fn can_split_leaf_data( + node: &NodeRef, K, V, Type>, + pivot: usize, + destination: &LeafNode, + ) -> bool { + let source = NodeRef::as_leaf_ptr(node); + // Both split callers allocate a fresh node for the destination. + // SAFETY: Once the leaf prefix is accessible and the pivot is in range, its key and + // value slot addresses can be checked as pointers to initialized K and V. + unsafe { + core::ub_checks::can_write(source) + && core::ub_checks::can_dereference(source) + && !core::ub_checks::same_allocation(source, ptr::from_ref(destination)) + && pivot < node.len() + && node.len() <= CAPACITY + && core::ub_checks::can_dereference((*source).keys[pivot].as_ptr()) + && core::ub_checks::can_dereference((*source).vals[pivot].as_ptr()) + } + } + + // Relinking uses only the initialized edge and the child's LeafNode prefix. The child can + // be a leaf or an internal node, and its old backlink is allowed to be stale. + pub(super) fn can_relink( + node: &NodeRef, K, V, marker::Internal>, + idx: usize, + ) -> bool { + let ptr = NodeRef::as_internal_ptr(node); + node.height() > 0 + && core::ub_checks::can_dereference(ptr) + && idx <= node.len() + && node.len() <= CAPACITY + // SAFETY: The parent is accessible and idx is within its edge array. + && core::ub_checks::can_dereference(unsafe { (*ptr).edges[idx].as_ptr() }) + && core::ub_checks::can_write(relink_child(node, idx)) + } + + pub(super) fn relink_child( + node: &NodeRef, K, V, marker::Internal>, + idx: usize, + ) -> *mut LeafNode { + let ptr = NodeRef::as_internal_ptr(node); + // SAFETY: The contract checks that the internal node and the selected edge are valid. + unsafe { (*ptr).edges[idx].assume_init_read().as_ptr() } + } + + pub(super) fn has_parent_link( + child: *const LeafNode, + parent: NonNull>, + idx: usize, + ) -> bool { + core::ub_checks::can_dereference(child) + // SAFETY: The child is live, and a present backlink includes an initialized index. + && unsafe { + (*child).parent == Some(parent) + && usize::from((*child).parent_idx.assume_init()) == idx + } + } + + #[kani::proof_for_contract( + Handle::, u8, u8, marker::Internal>, marker::Edge>::correct_parent_link + )] + fn harness_correct_parent_link() { + check_parent_link_contract::(); + } + + #[kani::proof_for_contract( + Handle::, (), (), marker::Internal>, marker::Edge>::correct_parent_link + )] + fn harness_correct_parent_link_unit() { + check_parent_link_contract::<(), ()>(); + } + + fn check_parent_link_contract() { + let len = kani::any_where(|len: &usize| *len <= CAPACITY); + let idx = kani::any_where(|idx: &usize| *idx <= len); + let height = kani::any_where(|h: &usize| *h > 0); + let child = NodeRef::::new_leaf(Global); + // SAFETY: Only the selected edge is required by the single-edge repair contract. + let mut parent = unsafe { InternalNode::new(Global) }; + parent.data.len = len as u16; + parent.edges[idx].write(child.node); + let parent_ptr = NonNull::from_mut(&mut *parent); + let parent = NodeRef::from_internal(parent_ptr, height); + // SAFETY: The chosen index is in the initialized edge prefix. + unsafe { Handle::new_edge(parent, idx) }.correct_parent_link(); + assert!(has_parent_link(child.node.as_ptr(), parent_ptr, idx)); + kani::cover(idx == CAPACITY && height > 1, "relink the last edge above the leaf level"); + } + + // Checks the usize instance of the conversions used by the VeriFast root proof. + #[kani::proof] + fn harness_new_internal_height_conversion() { + let height: usize = kani::any(); + match NonZero::new(height) { + None => { + assert_eq!(height, 0); + kani::cover(true, "zero has no NonZero representation"); + } + Some(nonzero) => { + assert_ne!(height, 0); + let converted: usize = nonzero.into(); + assert_eq!(converted, height); + // SAFETY: This branch establishes that height is nonzero. + let unchecked = unsafe { NonZero::new_unchecked(height) }; + assert_eq!(usize::from(unchecked), height); + kani::cover(height == usize::MAX, "round-trip the largest representable height"); + } + } + } + + // The shared loop proof also uses the production inclusive iterator. Its specification + // covers ranges whose end is below usize::MAX, including the empty state after returning + // the last item. + #[kani::proof] + fn harness_relink_inclusive_range_next() { + let start = kani::any::(); + let end = kani::any_where(|end: &usize| *end < usize::MAX); + let range = start..=end; + let mut iter = IntoIterator::into_iter(range.clone()); + assert_eq!(iter, range); + if start <= end { + assert_eq!(iter.next(), Some(start)); + assert_eq!(iter, start + 1..=end); + } else { + assert_eq!(iter.next(), None); + assert_eq!(iter, range); + } + kani::cover(start == end && end == CAPACITY, "yield the last valid child edge"); + kani::cover(start > end, "an empty range leaves the iterator unchanged"); + } + + fn assert_edge_child( + parent: NodeRef, u8, u8, marker::Internal>, + idx: usize, + expected: BoxedNode, + ) { + assert!(idx <= parent.len()); + // SAFETY: The assertions in the caller establish the initialized edge prefix. + let child = unsafe { Handle::new_edge(parent, idx) }.descend(); + assert_eq!(child.node, expected); + assert_eq!(child.height(), parent.height() - 1); + let backlink = child.ascend().ok().unwrap(); + assert_eq!(backlink.idx(), idx); + assert_eq!(backlink.into_node().node, parent.node); + } + + // Harness for `LeafNode::init`. + #[kani::proof_for_contract(LeafNode::init)] + fn harness_leaf_node_init() { + let mut leaf = Box::, _>::new_uninit_in(Global); + unsafe { + LeafNode::init(leaf.as_mut_ptr()); + kani::cover(true, "LeafNode::init was called"); + } + } + + // Harness for `LeafNode::new`. + #[kani::proof] + fn harness_leaf_node_new() { + let leaf = LeafNode::::new(Global); + assert!(leaf.parent.is_none()); + assert_eq!(leaf.len, 0); + kani::cover(true, "LeafNode::new returned an initialized empty leaf"); + } + + // Harness for `InternalNode::new`. + // + // `InternalNode::new` initializes only the embedded `LeafNode` portion. The + // edge array intentionally remains `MaybeUninit`; this harness therefore + // checks the initialized metadata and does not read any edge slot. + #[kani::proof] + fn harness_internal_node_new() { + let node = unsafe { InternalNode::::new(Global) }; + + assert!(node.data.parent.is_none()); + assert_eq!(node.data.len, 0); + kani::cover(true, "InternalNode::new returned initialized metadata"); + } + + // Harness for `NodeRef::as_internal_mut`. + #[kani::proof] + fn harness_node_ref_as_internal_mut() { + let len = kani::any_where(|n: &usize| *n <= CAPACITY); + let mut parent = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let mut internal_view = internal_with_borrowed_children(&mut parent, &mut children, len); + let node = internal_view.as_internal_mut(); + assert_eq!(node.data.len, len as u16); + kani::cover(len == 0, "as_internal_mut checked an empty internal node"); + kani::cover(len == CAPACITY, "as_internal_mut checked a full internal node"); + } + + // Harness for `NodeRef::len`. + #[kani::proof] + fn harness_node_ref_len() { + let (root, len) = verifier_leaf(); + assert_eq!(root.len(), len); + kani::cover(len == 0, "len checked an empty leaf"); + kani::cover(len == CAPACITY, "len checked a full leaf"); + + let mut parent = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let root = internal_with_borrowed_children(&mut parent, &mut children, len); + assert_eq!(root.len(), len); + kani::cover(len == 0, "len checked the prefix of an empty internal node"); + kani::cover(len == CAPACITY, "len checked the prefix of a full internal node"); + } + + // Harness for `NodeRef::first_edge`. + #[kani::proof] + fn harness_node_ref_first_edge() { + let (root, len) = verifier_leaf(); + let edge = root.first_edge(); + assert_eq!(edge.idx(), 0); + kani::cover(len == 0, "first_edge checked an empty leaf"); + kani::cover(len == CAPACITY, "first_edge checked a full leaf"); + } + + // Harness for `NodeRef::last_edge`. + #[kani::proof] + fn harness_node_ref_last_edge() { + let (root, len) = verifier_leaf(); + let edge = root.last_edge(); + assert_eq!(edge.idx(), len); + kani::cover(len == 0, "last_edge checked an empty leaf"); + kani::cover(len == CAPACITY, "last_edge checked a full leaf"); + } + + // Harness for `NodeRef::first_kv`. + #[kani::proof] + fn harness_node_ref_first_kv() { + let (root, len) = verifier_nonempty_leaf(); + let kv = root.first_kv(); + assert_eq!(kv.idx(), 0); + kani::cover(len == 1, "first_kv checked a one-element leaf"); + kani::cover(len == CAPACITY, "first_kv checked a full leaf"); + } + + // Harness for `NodeRef::last_kv`. + #[kani::proof] + fn harness_node_ref_last_kv() { + let (root, len) = verifier_nonempty_leaf(); + let kv = root.last_kv(); + assert_eq!(kv.idx(), len - 1); + kani::cover(len == 1, "last_kv checked a one-element leaf"); + kani::cover(len == CAPACITY, "last_kv checked a full leaf"); + } + + // The empty modifies set checks that following either kind of backlink leaves the tree alone. + #[kani::proof_for_contract(NodeRef::, u8, u8, marker::LeafOrInternal>::ascend)] + fn harness_node_ref_ascend_contract() { + let attached = kani::any::(); + let height = kani::any_where(|h: &usize| !attached || *h < usize::MAX); + let len = kani::any_where(|n: &u16| usize::from(*n) <= CAPACITY); + let idx = kani::any_where(|i: &u16| *i <= len); + let mut leaf = empty_leaf(); + let mut internal = empty_internal(); + let data = if height == 0 { &mut leaf } else { &mut internal.data }; + let mut parent = empty_internal(); + let parent_ptr = NonNull::from_mut(&mut parent); + if attached { + parent.data.len = len; + parent.edges[usize::from(idx)].write(NonNull::from_mut(data)); + data.parent = Some(parent_ptr); + data.parent_idx.write(idx); + } + let mut child = borrow_leaf::(data).forget_type(); + child.height = height; + let result = child.ascend(); + kani::cover(!attached && result.is_err(), "ascend from a detached root"); + kani::cover( + attached && height > 0 && usize::from(idx) == CAPACITY && result.is_ok(), + "ascend from the last internal child of a full node", + ); + } + + // Harness for `NodeRef::into_leaf`. + #[kani::proof] + fn harness_node_ref_into_leaf() { + let (root, len) = verifier_leaf(); + let leaf = root.reborrow().into_leaf(); + assert_eq!(leaf.len as usize, len); + kani::cover(len == 0, "into_leaf checked an empty leaf"); + kani::cover(len == CAPACITY, "into_leaf checked a full leaf"); + } + + // Harness for `NodeRef::keys`. + #[kani::proof] + fn harness_node_ref_keys() { + let (root, len) = verifier_leaf(); + let view = root.reborrow(); + let keys = view.keys(); + assert_eq!(keys.len(), len); + if len > 0 { + let idx = kani::any_where(|i: &usize| *i < len); + assert!(ptr::eq(&keys[idx], view.into_leaf().keys[idx].as_ptr())); + } + kani::cover(len == 0, "keys checked an empty leaf"); + kani::cover(len == CAPACITY, "keys checked a full leaf"); + } + + // Harness for `NodeRef::as_leaf_mut`. + #[kani::proof] + fn harness_node_ref_as_leaf_mut() { + let (mut root, len) = verifier_leaf(); + let mut view = root.borrow_mut(); + let leaf = view.as_leaf_mut(); + assert_eq!(leaf.len as usize, len); + kani::cover(len == 0, "as_leaf_mut checked an empty leaf"); + kani::cover(len == CAPACITY, "as_leaf_mut checked a full leaf"); + } + + // Harness for `NodeRef::into_leaf_mut`. + #[kani::proof] + fn harness_node_ref_into_leaf_mut() { + let (mut root, len) = verifier_leaf(); + let view = root.borrow_mut(); + let leaf = view.into_leaf_mut(); + assert_eq!(leaf.len as usize, len); + kani::cover(len == 0, "into_leaf_mut checked an empty leaf"); + kani::cover(len == CAPACITY, "into_leaf_mut checked a full leaf"); + } + + // Harness for `NodeRef::as_leaf_dying`. + #[kani::proof] + fn harness_node_ref_as_leaf_dying() { + let (mut root, len) = verifier_leaf(); + let mut dying = root.into_dying(); + let leaf = dying.as_leaf_dying(); + assert_eq!(leaf.len as usize, len); + kani::cover(len == 0, "as_leaf_dying checked an empty leaf"); + kani::cover(len == CAPACITY, "as_leaf_dying checked a full leaf"); + } + + // Harness for `NodeRef::pop_internal_level`. + #[kani::proof] + fn harness_node_ref_pop_internal_level() { + let height = kani::any_where(|height: &usize| *height > 0); + let (leaf, _) = verifier_leaf(); + let leaf = leaf.forget_type(); + let mut child = + if height == 1 { leaf } else { internal_root_with_child(leaf, Global).forget_type() }; + // Pop reads the first edge and clears the retained child's backlink. + child.height = height - 1; + let child_ptr = child.node; + let child_len = child.len(); + let mut root = internal_root_with_child(child, Global).forget_type(); + root.pop_internal_level(Global); + assert_eq!(root.node, child_ptr); + assert_eq!(root.height(), height - 1); + assert_eq!(root.len(), child_len); + assert!(root.reborrow().ascend().is_err()); + kani::cover(height == 1, "pop an internal root above a leaf"); + kani::cover(height == usize::MAX, "pop an internal root above an internal child"); + } + + // Harness for `NodeRef::push`. + #[kani::proof] + fn harness_node_ref_push() { + let (mut root, _) = verifier_leaf(); + let before = root.len(); + if before < CAPACITY { + let (key, val) = kani::any::<(u8, u8)>(); + let inserted = root.borrow_mut().push(key, val); + assert_eq!(root.len(), before + 1); + let (stored_key, stored_val) = root.reborrow().last_kv().into_kv(); + assert!(ptr::eq(inserted, stored_val)); + assert_eq!((*stored_key, *stored_val), (key, val)); + kani::cover(before == 0, "push checked insertion into an empty leaf"); + kani::cover(before == CAPACITY - 1, "push checked insertion into a nearly full leaf"); + } + } + + #[kani::proof] + fn harness_node_ref_push_internal() { + let len = kani::any_where(|n: &usize| *n < CAPACITY); + let height = kani::any_where(|h: &usize| *h > 0); + let leaf = OwnedLeaf::new_leaf(Global).forget_type(); + let mut incoming = + if height == 1 { leaf } else { internal_root_with_child(leaf, Global).forget_type() }; + // Push reads only the incoming root and writes its backlink. + incoming.height = height - 1; + let child = incoming.node; + let mut storage = empty_internal(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let mut parent = internal_with_borrowed_children(&mut storage, &mut children, len); + parent.height = height; + let (key, val) = kani::any(); + parent.push(key, val, incoming); + + let parent = parent.reborrow(); + assert_eq!(parent.len(), len + 1); + assert_eq!(parent.last_kv().into_kv(), (&key, &val)); + assert_edge_child(parent, len + 1, child); + kani::cover(len + 1 == CAPACITY, "push into the last available internal slot"); + kani::cover(height > 1, "push a subtree into an internal node"); + } + + // Harness for `Handle::left_edge`. + #[kani::proof] + fn harness_handle_left_edge() { + let (root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: idx identifies an initialized KV. + let edge = unsafe { Handle::new_kv(root.reborrow(), idx) }.left_edge(); + assert_eq!(edge.idx(), idx); + assert_eq!(edge.into_node().node, root.node); + kani::cover(idx + 1 == CAPACITY, "left_edge from the last KV of a full node"); + } + + // Harness for `Handle::right_edge`. + #[kani::proof] + fn harness_handle_right_edge() { + let (root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: idx identifies an initialized KV. + let edge = unsafe { Handle::new_kv(root.reborrow(), idx) }.right_edge(); + assert_eq!(edge.idx(), idx + 1); + assert_eq!(edge.into_node().node, root.node); + kani::cover(idx + 1 == CAPACITY, "right_edge from the last KV of a full node"); + } + + // Harness for `Handle::left_kv`. + #[kani::proof] + fn harness_handle_left_kv() { + let (root, len) = verifier_leaf(); + let idx = kani::any_where(|i: &usize| *i <= len); + // SAFETY: Leaves have an edge at every position from 0 through len. + match unsafe { Handle::new_edge(root.reborrow(), idx) }.left_kv() { + Ok(kv) => { + assert!(idx > 0); + assert_eq!(kv.idx(), idx - 1); + assert_eq!(kv.into_node().node, root.node); + kani::cover(idx == len, "left_kv succeeds at the last edge"); + } + Err(edge) => { + assert_eq!(idx, 0); + assert_eq!(edge.idx(), idx); + assert_eq!(edge.into_node().node, root.node); + kani::cover(len == 0, "left_kv returns the edge of an empty node"); + } + } + } + + // Harness for `Handle::right_kv`. + #[kani::proof] + fn harness_handle_right_kv() { + let (root, len) = verifier_leaf(); + let idx = kani::any_where(|i: &usize| *i <= len); + // SAFETY: Leaves have an edge at every position from 0 through len. + match unsafe { Handle::new_edge(root.reborrow(), idx) }.right_kv() { + Ok(kv) => { + assert!(idx < len); + assert_eq!(kv.idx(), idx); + assert_eq!(kv.into_node().node, root.node); + kani::cover(idx == 0, "right_kv succeeds at the first edge"); + } + Err(edge) => { + assert_eq!(idx, len); + assert_eq!(edge.idx(), idx); + assert_eq!(edge.into_node().node, root.node); + kani::cover(len == CAPACITY, "right_kv returns the last edge of a full node"); + } + } + } + + // Harness for `Handle::descend`. + #[kani::proof] + fn harness_handle_descend() { + let len = kani::any_where(|n: &usize| *n <= CAPACITY); + let mut parent = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let internal = internal_with_borrowed_children(&mut parent, &mut children, len); + let idx = kani::any_where(|i: &usize| *i <= len); + let child_ptr = relink_child(&internal, idx); + // SAFETY: The fixture initializes each edge up to and including len. + let edge = unsafe { Handle::new_edge(internal.reborrow(), idx) }.forget_node_type(); + let ForceResult::Internal(edge) = edge.force() else { + panic!("the edge belongs to an internal node"); + }; + assert_eq!(edge.idx(), idx); + let descended = edge.descend(); + assert_eq!(descended.height(), 0); + assert_eq!(descended.node.as_ptr(), child_ptr); + kani::cover(idx == CAPACITY, "descend through the last edge of a full node"); + } + + #[kani::proof] + fn harness_consider_for_balancing() { + let len = kani::any_where(|n: &usize| 0 < *n && *n <= CAPACITY); + let idx = kani::any_where(|i: &usize| *i < len); + let mut storage = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let parent = internal_with_borrowed_children(&mut storage, &mut children, len); + let parent_ptr = parent.node; + let left = relink_child(&parent, idx); + let right = relink_child(&parent, idx + 1); + + // SAFETY: The separator and both adjacent edges belong to the active prefix. + let context = unsafe { Handle::new_kv(parent, idx) }.consider_for_balancing(); + assert_eq!((context.parent.node.node, context.parent.idx()), (parent_ptr, idx)); + assert_eq!(context.left_child.node.as_ptr(), left); + assert_eq!(context.right_child.node.as_ptr(), right); + kani::cover(idx == 0, "balance around the first separator"); + kani::cover(idx + 1 == CAPACITY, "balance around the last separator of a full node"); + } + + #[kani::proof] + fn harness_choose_parent_kv() { + let len = kani::any_where(|n: &usize| 0 < *n && *n <= CAPACITY); + let idx = kani::any_where(|i: &usize| *i <= len); + let attached = kani::any::(); + let mut detached = empty_leaf::(); + let mut parent = empty_internal(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let parent = internal_with_borrowed_children(&mut parent, &mut children, len); + let parent_ptr = parent.node; + let separator = idx.saturating_sub(1); + // SAFETY: The separator and both adjacent edges belong to the active prefix. + let (left, right) = unsafe { + let kv = Handle::new_kv(parent.reborrow(), separator); + (kv.left_edge().descend().node, kv.right_edge().descend().node) + }; + let child = if attached { + // SAFETY: idx selects an initialized edge, and no shared view remains live. + unsafe { Handle::new_edge(parent, idx) }.descend() + } else { + borrow_leaf(&mut detached).forget_type() + }; + let original = child.node; + + let context = match child.choose_parent_kv() { + Ok(LeftOrRight::Left(context)) => { + assert!(attached && idx > 0); + context + } + Ok(LeftOrRight::Right(context)) => { + assert!(attached && idx == 0); + context + } + Err(root) => { + assert!(!attached && root.node == original); + kani::cover(!attached, "a detached root has no parent separator"); + return; + } + }; + assert_eq!((context.parent.node.node, context.parent.idx()), (parent_ptr, separator)); + assert_eq!((context.left_child.node, context.right_child.node), (left, right)); + kani::cover(idx == 0, "choose the separator to the right of the first child"); + kani::cover(idx == CAPACITY, "choose the separator to the left of the last child"); + } + + // Harness for `Handle::into_kv`. + #[kani::proof] + fn harness_handle_into_kv() { + let (root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + let leaf = root.reborrow().into_leaf(); + // SAFETY: idx is in the initialized prefix of both arrays. + let (key, value) = unsafe { Handle::new_kv(root.reborrow(), idx) }.into_kv(); + assert!(ptr::eq(key, leaf.keys[idx].as_ptr())); + assert!(ptr::eq(value, leaf.vals[idx].as_ptr())); + kani::cover(idx + 1 == CAPACITY, "into_kv reads the last pair of a full node"); + } + + // Harness for `Handle::key_mut`. + #[kani::proof] + fn harness_handle_key_mut() { + let (mut root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + let key = kani::any(); + // SAFETY: idx is in the initialized prefix. + *unsafe { Handle::new_kv(root.borrow_mut(), idx) }.key_mut() = key; + assert_eq!(root.reborrow().keys()[idx], key); + kani::cover(idx + 1 == CAPACITY, "key_mut writes the last key of a full node"); + } + + // Harness for `Handle::into_val_mut`. + #[kani::proof] + fn harness_handle_into_val_mut() { + let (mut root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + let val = kani::any(); + // SAFETY: idx is in the initialized prefix. + *unsafe { Handle::new_kv(root.borrow_mut(), idx) }.into_val_mut() = val; + // SAFETY: The same slot remains initialized after writing a value through it. + assert_eq!(unsafe { root.reborrow().into_leaf().vals[idx].assume_init() }, val); + kani::cover(idx + 1 == CAPACITY, "into_val_mut writes the last value of a full node"); + } + + // Harness for `Handle::into_kv_mut`. + #[kani::proof] + fn harness_handle_into_kv_mut() { + let (mut root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: Both slots at idx are initialized and uniquely borrowed. + let (key, value) = unsafe { Handle::new_kv(root.borrow_mut(), idx) }.into_kv_mut(); + *key = 1; + *value = 2; + assert_eq!((*key, *value), (1, 2)); + kani::cover(idx + 1 == CAPACITY, "into_kv_mut writes both fields of the last pair"); + } + + // Harness for `Handle::into_kv_valmut`. + #[kani::proof] + fn harness_handle_into_kv_valmut() { + let len = kani::any_where(|n: &usize| (2..=CAPACITY).contains(n)); + let mut root = leaf_with_len(len); + let first = kani::any_where(|i: &usize| *i < len); + let second = kani::any_where(|i: &usize| *i < len && *i != first); + let first_key = root.reborrow().keys()[first]; + let second_key = root.reborrow().keys()[second]; + let view = root.borrow_valmut(); + // SAFETY: As in IterMut, duplicate the view only to visit two distinct initialized slots. + let (key1, val1) = unsafe { Handle::new_kv(ptr::read(&view), first) }.into_kv_valmut(); + // SAFETY: second is initialized and distinct from the outstanding value reference. + let (key2, val2) = unsafe { Handle::new_kv(view, second) }.into_kv_valmut(); + *val1 = 1; + *val2 = 2; + assert_eq!((*key1, *key2), (first_key, second_key)); + assert_eq!((*val1, *val2), (1, 2)); + kani::cover(first + 1 == CAPACITY && second == 0, "two value references coexist"); + } + + // Harness for `Handle::kv_mut`. + #[kani::proof] + fn harness_handle_kv_mut() { + let (mut root, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: idx is in the initialized prefix. + let mut handle = unsafe { Handle::new_kv(root.borrow_mut(), idx) }; + let (key, value) = handle.kv_mut(); + *key = 1; + *value = 2; + assert_eq!((*key, *value), (1, 2)); + let (key, value) = handle.reborrow().into_kv(); + assert_eq!((*key, *value), (1, 2)); + kani::cover(idx + 1 == CAPACITY, "kv_mut writes both fields of the last pair"); + } + + #[kani::proof] + fn harness_handle_into_key_val() { + let (leaf, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: idx selects an initialized pair in both views. The shared view ends before + // moving the pair, and the dying node is never accessed again. + let (key, value) = unsafe { Handle::new_kv(leaf.reborrow(), idx) }.into_kv(); + let expected = (*key, *value); + let dying = leaf.into_dying(); + let actual = unsafe { Handle::new_kv(dying, idx).into_key_val() }; + assert_eq!(actual, expected); + kani::cover(len == CAPACITY && idx == len - 1, "extract the final pair of a full node"); + } + + #[kani::proof] + fn harness_handle_remove_leaf() { + let (mut leaf, len) = verifier_nonempty_leaf(); + let idx = kani::any_where(|i: &usize| *i < len); + // SAFETY: Both handles selected below refer to initialized pairs. + let (expected, next) = unsafe { + let view = leaf.reborrow(); + let (key, val) = Handle::new_kv(view, idx).forget_node_type().into_kv(); + let next = (idx + 1 < len).then(|| { + let (key, val) = Handle::new_kv(view, idx + 1).into_kv(); + (*key, *val) + }); + ((*key, *val), next) + }; + + let leaf_ptr = leaf.node; + // SAFETY: The removed KV was initialized by the fixture. + let (removed, edge) = unsafe { Handle::new_kv(leaf.borrow_mut(), idx) }.remove(); + let edge = edge.forget_node_type(); + // SAFETY: The edge returned by leaf removal still points into the leaf. + let edge = unsafe { edge.cast_to_leaf_unchecked() }; + assert_eq!(removed, expected); + assert_eq!(edge.idx(), idx); + assert_eq!(edge.node.node, leaf_ptr); + assert_eq!(edge.reborrow().into_node().len(), len - 1); + if let Some(next) = next { + let (key, val) = edge.reborrow().right_kv().ok().unwrap().into_kv(); + assert_eq!((*key, *val), next); + } + kani::cover(idx == 0 && len == CAPACITY, "remove shifts the longest leaf suffix"); + kani::cover(idx + 1 == len, "remove returns the last edge"); + } + + #[kani::proof] + fn harness_deallocate_leaf_root() { + let alloc = TrackingAllocator::default(); + let root = OwnedLeaf::new_leaf(&alloc).forget_type().into_dying(); + let ptr = root.node; + // SAFETY: The empty node was allocated by alloc and has no live handles. + let parent = unsafe { root.deallocate_and_ascend(&alloc) }; + assert!(parent.is_none()); + assert_eq!(alloc.freed.get(), Some((ptr.cast(), Layout::new::>()))); + kani::cover(parent.is_none(), "deallocate a leaf root without a parent"); + } + + #[kani::proof] + fn harness_deallocate_attached_child() { + let internal = kani::any::(); + let alloc = TrackingAllocator::default(); + let leaf = OwnedLeaf::new_leaf(&alloc).forget_type(); + let child = + if internal { internal_root_with_child(leaf, &alloc).forget_type() } else { leaf }; + let child_ptr = child.node; + let parent = internal_root_with_child(child, &alloc).into_dying(); + let parent_ptr = parent.node; + let child = parent.first_edge().descend(); + // SAFETY: The child came from alloc, and the proof uses only the parent after freeing it. + let edge = unsafe { child.deallocate_and_ascend(&alloc) }.unwrap(); + assert_eq!((edge.node.node, edge.idx()), (parent_ptr, 0)); + let layout = if internal { + Layout::new::>() + } else { + Layout::new::>() + }; + assert_eq!(alloc.freed.get(), Some((child_ptr.cast(), layout))); + kani::cover(internal, "deallocate an internal node and recover the parent edge"); + kani::cover(!internal, "deallocate a leaf and recover the parent edge"); + } + + #[kani::proof] + fn harness_move_suffix_projections() { + let len = kani::any_where(|n: &usize| *n <= CAPACITY); + let cut = kani::any_where(|i: &usize| *i <= len); + let height = kani::any_where(|h: &usize| *h > 0); + let mut storage = empty_internal::(); + let mut children = [const { empty_leaf() }; CAPACITY + 1]; + let mut source = internal_with_borrowed_children(&mut storage, &mut children, len); + source.height = height; + let base = NodeRef::as_internal_ptr(&source); + // SAFETY: The internal allocation is live and all these addresses lie in its storage. + let (key_base, val_base, edge_base, length) = unsafe { + ( + (&raw const (*base).data.keys).cast::>(), + (&raw const (*base).data.vals).cast::>(), + (&raw const (*base).edges).cast::>>(), + &raw const (*base).data.len, + ) + }; + let moved = len - cut; + + // SAFETY: The handle selects an initialized edge and the borrowed node is used exclusively. + let mut edge = unsafe { Handle::new_edge(source.forget_type(), cut) }; + // SAFETY: There is no other active borrow of this handle. + let mut node = unsafe { edge.reborrow_mut() }.into_node(); + assert_eq!(node.height(), height); + assert_eq!(node.len(), len); + assert!(ptr::addr_eq(node.len_mut(), length)); + + // SAFETY: All the ranges are within the respective node arrays, including when empty. + let keys = unsafe { node.key_area_mut(cut..len) }; + assert_eq!(keys.len(), moved); + assert!(ptr::addr_eq(keys.as_ptr(), key_base.wrapping_add(cut))); + // SAFETY: The moved prefix is at most CAPACITY elements long. + let vals = unsafe { node.val_area_mut(..moved) }; + assert_eq!(vals.len(), moved); + assert!(ptr::addr_eq(vals.as_ptr(), val_base)); + let ForceResult::Internal(mut node) = node.force() else { + panic!("positive height selects the internal layout"); + }; + // SAFETY: Both endpoints are in 0..=CAPACITY + 1 and cut <= len. + let edges = unsafe { node.edge_area_mut(cut + 1..len + 1) }; + assert_eq!(edges.len(), moved); + assert!(ptr::addr_eq(edges.as_ptr(), edge_base.wrapping_add(cut + 1))); + kani::cover( + cut == 0 && len == CAPACITY && height > 1, + "project the full suffix at an internal level", + ); + kani::cover(cut == CAPACITY && len == CAPACITY, "project the empty suffix at the end"); + } + + #[kani::proof] + fn harness_insert_leaf_step_fit() { + let len = kani::any_where(|n: &usize| *n < CAPACITY); + let idx = kani::any_where(|i: &usize| *i <= len); + let mut leaf = leaf_for_insertion(len); + let (key, val) = kani::any::<(u8, u8)>(); + // SAFETY: idx is a valid insertion edge in this leaf. + let edge = unsafe { Handle::new_edge(borrow_leaf(&mut leaf), idx) }; + let (split, dormant) = edge.insert(key, val, Global); + assert!(split.is_none()); + // SAFETY: Insertion is complete and the leaf is exclusively borrowed by the handle. + let handle = unsafe { dormant.awaken() }; + assert_eq!(handle.idx(), idx); + let (stored_key, stored_val) = handle.reborrow().into_kv(); + assert_eq!((*stored_key, *stored_val), (key, val)); + assert_eq!(usize::from(leaf.len), len + 1); + kani::cover(len == 0, "insert into an empty leaf"); + kani::cover(len + 1 == CAPACITY && idx < len, "insert by shifting an occupied leaf suffix"); + } + + #[kani::proof] + fn harness_splitpoint_bounds() { + let edge = kani::any_where(|i: &usize| *i <= CAPACITY); + let (middle, insertion) = splitpoint(edge); + assert!((KV_IDX_CENTER - 1..=KV_IDX_CENTER + 1).contains(&middle)); + assert!(middle < CAPACITY); + let left_len = middle; + let right_len = CAPACITY - middle - 1; + assert!(left_len < CAPACITY && right_len < CAPACITY); + assert!(right_len + 1 <= 7); + match insertion { + LeftOrRight::Left(idx) => { + assert!(idx <= left_len); + assert_eq!(idx, edge); + assert!(left_len + 1 - idx <= 7); + } + LeftOrRight::Right(idx) => { + assert!(idx <= right_len); + assert_eq!(middle + 1 + idx, edge); + assert!(right_len + 1 - idx <= 7); + } + } + kani::cover(edge == 0, "a full node can split at the first insertion edge"); + kani::cover(edge == CAPACITY, "a full node can split at the last insertion edge"); + } + + #[kani::proof_for_contract(slice_insert::)] + fn harness_slice_insert_frame() { + // A node has at most CAPACITY KV slots and CAPACITY + 1 edge slots. + let len = usize::from(kani::any_where(|n: &u8| *n > 0 && usize::from(*n) <= CAPACITY + 1)); + let idx = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let observed = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let mut slots = MaybeUninit::new(kani::any::<[u8; CAPACITY + 1]>()).transpose(); + let value = kani::any(); + // SAFETY: The observed prefix element is initialized. Elements after idx move right. + let expected = if observed == idx { + value + } else { + unsafe { slots[observed - usize::from(observed > idx)].assume_init() } + }; + slots[len - 1] = MaybeUninit::uninit(); + // SAFETY: The prefix to be shifted is initialized, and idx is in bounds. + unsafe { slice_insert(&mut slots[..len], idx, value) }; + // SAFETY: Insertion initializes the entire active prefix. + assert_eq!(unsafe { slots[observed].assume_init() }, expected); + kani::cover(idx == 0 && len == CAPACITY + 1, "shift a full edge array's live prefix"); + } + + #[kani::proof_for_contract(slice_insert::>>)] + fn harness_slice_insert_edge_frame() { + let len = usize::from(kani::any_where(|n: &u8| *n > 0 && usize::from(*n) <= CAPACITY + 1)); + let idx = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let mut child = empty_leaf::(); + let mut incoming = empty_leaf(); + let mut slots = [MaybeUninit::new(NonNull::from_mut(&mut child)); CAPACITY + 1]; + slots[len - 1] = MaybeUninit::uninit(); + // SAFETY: The active range has an initialized prefix with an open last slot, and idx + // selects a position in the range. + unsafe { slice_insert(&mut slots[..len], idx, NonNull::from_mut(&mut incoming)) }; + kani::cover(idx == 0 && len == CAPACITY + 1, "shift the largest pointer suffix"); + } + + #[kani::proof_for_contract(move_to_slice::>>)] + fn harness_move_edge_slice_frame() { + let len = usize::from(kani::any_where(|n: &u8| usize::from(*n) <= CAPACITY + 1)); + let from = usize::from(kani::any_where(|i: &u8| usize::from(*i) <= CAPACITY + 1 - len)); + let to = usize::from(kani::any_where(|i: &u8| usize::from(*i) <= CAPACITY + 1 - len)); + let mut child = empty_leaf::(); + let mut src = [MaybeUninit::new(NonNull::from_mut(&mut child)); CAPACITY + 1]; + let mut dst = [MaybeUninit::uninit(); CAPACITY + 1]; + move_to_slice(&mut src[from..from + len], &mut dst[to..to + len]); + kani::cover(from == 1 && to == 0 && len == CAPACITY, "copy an internal edge suffix"); + } + + // Check the payload movement separately from child-edge relinking. The write set preserves + // both backlinks and any payload in a descendant. + #[kani::proof_for_contract( + Handle::, u8, u8, marker::Internal>, marker::KV>::split_leaf_data + )] + #[kani::solver(minisat)] + fn harness_split_leaf_data_frame() { + let len = usize::from(kani::any_where(|n: &u8| *n > 0 && usize::from(*n) <= CAPACITY)); + let pivot = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let observed = usize::from(kani::any_where(|i: &u8| usize::from(*i) < len)); + let height = kani::any_where(|h: &usize| *h > 0); + let mut source = InternalNode { data: leaf_for_insertion(len), ..empty_internal() }; + let mut right = empty_internal(); + // SAFETY: observed lies in the initialized prefix of source. + let expected = unsafe { + (source.data.keys[observed].assume_init(), source.data.vals[observed].assume_init()) + }; + let node = NodeRef::from_internal(NonNull::from_mut(&mut source), height); + // SAFETY: pivot identifies an initialized KV slot. + let mut pivot_handle = unsafe { Handle::new_kv(node, pivot) }; + let promoted = pivot_handle.split_leaf_data(&mut right.data); + + let stored = if observed == pivot { + promoted + } else { + let (data, slot) = if observed < pivot { + (&source.data, observed) + } else { + (&right.data, observed - pivot - 1) + }; + assert!(slot < usize::from(data.len)); + // SAFETY: The retained slot is in the live prefix of the corresponding half. + unsafe { (data.keys[slot].assume_init(), data.vals[slot].assume_init()) } + }; + assert_eq!(stored, expected); + kani::cover( + len == CAPACITY && pivot == 0 && observed == CAPACITY - 1, + "move the last pair of the maximum length KV suffix", + ); + } + + #[kani::proof] + fn harness_insert_leaf_step_split() { + let idx = usize::from(kani::any_where(|i: &u8| usize::from(*i) <= CAPACITY)); + let ancestor_idx = kani::any_where(|i: &u16| usize::from(*i) <= CAPACITY); + let attached = kani::any::(); + let mut leaf = leaf_for_insertion(CAPACITY); + let mut ancestor = empty_internal(); + let ancestor_ptr = NonNull::from_mut(&mut ancestor); + if attached { + leaf.parent = Some(ancestor_ptr); + leaf.parent_idx.write(ancestor_idx); + ancestor.data.len = ancestor_idx; + ancestor.edges[usize::from(ancestor_idx)].write(NonNull::from_mut(&mut leaf)); + } + let (pivot, insertion) = splitpoint(idx); + // SAFETY: The full leaf initializes every pair, including the selected pivot. + let promoted = unsafe { (leaf.keys[pivot].assume_init(), leaf.vals[pivot].assume_init()) }; + let leaf = borrow_leaf(&mut leaf); + let original = leaf.node; + let (key, val) = kani::any::<(u8, u8)>(); + // SAFETY: Every edge of the full leaf is available for insertion. + let edge = unsafe { Handle::new_edge(leaf, idx) }; + let (split, dormant) = edge.insert(key, val, Global); + let split = split.expect("a full leaf splits"); + assert_eq!(split.left.node, original); + assert_ne!(split.right.node, original); + assert_eq!(split.left.height(), 0); + assert_eq!(split.right.height(), 0); + assert_eq!(split.left.len() + split.right.len(), CAPACITY); + assert_eq!(split.kv, promoted); + match split.left.reborrow().ascend() { + Ok(edge) => { + assert!(attached); + assert_eq!(edge.node.node, ancestor_ptr.cast()); + assert_eq!(edge.idx(), usize::from(ancestor_idx)); + assert_eq!(edge.descend().node, original); + } + Err(root) => { + assert!(!attached); + assert_eq!(root.node, original); + } + } + assert!(split.right.reborrow().ascend().is_err()); + let (destination, slot) = match insertion { + LeftOrRight::Left(slot) => (split.left.node, slot), + LeftOrRight::Right(slot) => (split.right.node, slot), + }; + assert_eq!((dormant.node.node, dormant.idx()), (destination, slot)); + drop(split); + // SAFETY: No split handle or reference into either result node is used again. + let inserted = unsafe { dormant.awaken() }; + let (stored_key, stored_val) = inserted.reborrow().into_kv(); + assert_eq!((*stored_key, *stored_val), (key, val)); + kani::cover( + attached && idx == EDGE_IDX_LEFT_OF_CENTER, + "split an attached leaf to the left", + ); + kani::cover( + !attached && idx == EDGE_IDX_RIGHT_OF_CENTER, + "split the leaf root to the right", + ); + } + + // The parent shifts in do_merge depend only on its occupancy and separator index. + // Exercise every such pair on the actual slice_remove helper, independently of the + // child-occupancy proofs and the relink-range proof. + #[kani::proof] + fn harness_merge_parent_shift_ranges() { + let len = kani::any_where(|n: &usize| *n > 0 && *n <= CAPACITY); + let idx = kani::any_where(|i: &usize| *i < len); + let original_keys = kani::any::<[u8; CAPACITY]>(); + let mut keys = MaybeUninit::new(original_keys).transpose(); + // Use pointer-sized words to check the edge ranges. VeriFast checks the pointer moves + // and repairs in the production merge. + let original_edges = kani::any::<[usize; CAPACITY + 1]>(); + let mut edges = MaybeUninit::new(original_edges).transpose(); + + // SAFETY: The source slices contain only initialized slots, and len and idx + // specify an existing separator and its right edge. + let (key, removed) = unsafe { + (slice_remove(&mut keys[..len], idx), slice_remove(&mut edges[..=len], idx + 1)) + }; + assert!(key == original_keys[idx], "remove the parent separator"); + assert!(removed == original_edges[idx + 1], "remove the edge right of the separator"); + kani::cover(len == CAPACITY && idx == 0, "shift the longest parent suffix"); + kani::cover(idx + 1 == len, "remove the final separator with no trailing shift"); + } +} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/original/operations.rs.in b/verifast-proofs/alloc/collections/btree/node.rs/original/operations.rs.in new file mode 100644 index 0000000000000..e0eb0e16bc6a1 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/original/operations.rs.in @@ -0,0 +1,1429 @@ +#![feature(allocator_ext)] +//! Ancestor ownership and the key, value, and child moves used during splitting. +//! Refinement checks the production `as_leaf_ptr` and `set_parent_link`. + +#![allow(dead_code)] + +use std::marker::PhantomData; +use std::mem::MaybeUninit; +use std::ptr::NonNull; + +//@ use std::mem::{MaybeUninit, open_MaybeUninit, close_MaybeUninit}; +//@ use std::option::Option; +//@ use std::ptr::NonNull; + +const B: usize = 6; + +const CAPACITY: usize = 2 * B - 1; + +//@ fix B() -> usize { 6 } + +//@ fix CAPACITY() -> usize { 2 * B - 1 } + +struct LeafNode { + /// We want to be covariant in `K` and `V`. + parent: Option>>, + + /// This node's index into the parent node's `edges` array. + /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`. + /// This is only guaranteed to be initialized when `parent` is non-null. + parent_idx: MaybeUninit, + + /// The number of keys and values this node stores. + len: u16, + + /// The arrays storing the actual data of the node. Only the first `len` elements of each + /// array are initialized and valid. + keys: [MaybeUninit; CAPACITY], + vals: [MaybeUninit; CAPACITY], +} + +#[repr(C)] +struct InternalNode { + data: LeafNode, + + /// The pointers to the children of this node. `len + 1` of these are considered + /// initialized and valid, except that near the end, while the tree is held + /// through borrow type `Dying`, some of these pointers are dangling. + edges: [MaybeUninit>; 2 * B], +} + +type BoxedNode = NonNull>; + +struct NodeRef { + /// The number of levels that the node and the level of leaves are apart, a + /// constant of the node that cannot be entirely described by `Type`, and that + /// the node itself does not store. We only need to store the height of the root + /// node, and derive every other node's height from it. + /// Must be zero if `Type` is `Leaf` and non-zero if `Type` is `Internal`. + height: usize, + /// The pointer to the leaf or internal node. The definition of `InternalNode` + /// ensures that the pointer is valid either way. + node: NonNull>, + _marker: PhantomData<(BorrowType, Type)>, +} + +mod marker { + use super::PhantomData; + pub(crate) struct Mut<'a>(PhantomData<&'a mut ()>); + pub(crate) enum LeafOrInternal {} + pub(crate) enum DormantMut {} + pub(crate) enum Owned {} + pub(crate) enum Dying {} + pub(crate) enum Leaf {} + pub(crate) enum Internal {} + pub(crate) enum KV {} + pub(crate) enum Edge {} +} + +use std::alloc::AllocatorClone; +use std::ptr; + +const KV_IDX_CENTER: usize = B - 1; +//@ fix KV_IDX_CENTER() -> usize { B - 1 } +const EDGE_IDX_LEFT_OF_CENTER: usize = B - 1; +//@ fix EDGE_IDX_LEFT_OF_CENTER() -> usize { B - 1 } +const EDGE_IDX_RIGHT_OF_CENTER: usize = B; +//@ fix EDGE_IDX_RIGHT_OF_CENTER() -> usize { B } + +enum LeftOrRight { + Left(T), + Right(T), +} + +struct SplitResult<'a, K, V, NodeType> { + // Altered node in existing tree with elements and edges that belong to the left of `kv`. + pub left: NodeRef, K, V, NodeType>, + // Some key and value that existed before and were split off, to be inserted elsewhere. + pub kv: (K, V), + // Owned, unattached, new node with elements and edges that belong to the right of `kv`. + pub right: NodeRef, +} + +type Root = NodeRef; + +struct Handle { + node: Node, + idx: usize, + _marker: PhantomData, +} + +// SOURCE unsafe fn slice_insert(slice: &mut [MaybeUninit], idx: usize, val: T) { + +impl NodeRef { +// SOURCE pub(super) unsafe fn awaken<'a>(self) -> NodeRef, K, V, Type> { +} + +impl Handle, HandleType> { +// SOURCE pub(super) unsafe fn awaken<'a>( +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE pub(super) fn dormant(&self) -> NodeRef { +} + +impl<'a, K, V, NodeType, HandleType> Handle, K, V, NodeType>, HandleType> { +// SOURCE pub(super) fn dormant( +} + +// SOURCE pub(super) struct DormantMutRef<'a, T> { + +impl<'a, T> DormantMutRef<'a, T> { +// SOURCE pub(super) unsafe fn reborrow(&mut self) -> &'a mut T { +} + +fn clone_allocator(alloc: &mut A) -> A { + alloc.clone() +} + +unsafe fn read_promoted(slot: *const MaybeUninit) -> T +//@ req thread_token(?t) &*& type_interp::() &*& *slot |-> ?bits &*& bits.inner() == some(?value) &*& .own(t,value); +//@ ens thread_token(t) &*& type_interp::() &*& *slot |-> MaybeUninit::new(value) &*& result == value &*& .own(t,value); +//@ on_unwind_ens false; +{ + //@ open_MaybeUninit(slot); + //@ points_to_limits(slot as *T); + let promoted = unsafe { std::ptr::read(slot as *const T) }; + //@ close_MaybeUninit(slot); + promoted +} + +// SOURCE unsafe fn slice_shl(slice: &mut [MaybeUninit], distance: usize) { + +// SOURCE unsafe fn slice_shr(slice: &mut [MaybeUninit], distance: usize) { + +// SOURCE fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) { + +// SOURCE unsafe fn slice_remove(slice: &mut [MaybeUninit], idx: usize) -> T { + +unsafe fn move_slice_mut<'a, T>(base: *mut MaybeUninit, len: usize) -> &'a mut [MaybeUninit] +//@ req move_slice(base, len, ?slots); +//@ ens move_slice(base, len, slots) &*& result as *MaybeUninit == base &*& result.len() == len; +//@ on_unwind_ens false; +{ + //@ open move_slice(base, len, slots); + let slice = unsafe { std::slice::from_raw_parts_mut(base, len) }; + //@ close move_slice(base, len, slots); + slice +} + +unsafe fn merge_payload( + parent: *mut MaybeUninit, + left: *mut MaybeUninit, + right: *mut MaybeUninit, + parent_idx: usize, + old_parent_len: usize, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +){ + unsafe { +let entry = slice_remove(move_slice_mut(parent, old_parent_len), parent_idx); +(*left.add(old_left_len)).write(entry); +move_to_slice( +move_slice_mut(right, right_len), +move_slice_mut(left.add(old_left_len + 1), new_left_len - (old_left_len + 1)), +); + } +} + +unsafe fn merge_field( + parent: *mut MaybeUninit, + left: *mut MaybeUninit, + right: *mut MaybeUninit, + parent_idx: usize, + old_parent_len: usize, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +) + +{ + unsafe { merge_payload(parent, left, right, parent_idx, old_parent_len, old_left_len, right_len, new_left_len) }; +} + +unsafe fn release_balancing_node<'alloc, T, A: std::alloc::Allocator>( + node: NonNull, + alloc: &'alloc A, +) + +{ + let ptr = node.as_ptr(); + let bytes = unsafe { NonNull::new_unchecked(ptr as *mut u8) }; + unsafe { alloc.deallocate(bytes, std::alloc::Layout::new::()) } +} + +unsafe fn merge_keys<'a, 'short, K, V>( + parent_node: &'short mut NodeRef, K, V, marker::Internal>, + left_node: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + right_node: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + parent_idx: usize, + old_parent_len: usize, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +) { + unsafe { +let parent_key = slice_remove(parent_node.key_area_prefix_mut(..old_parent_len), parent_idx); +left_node.key_area_slot_mut(old_left_len).write(parent_key); +move_to_slice( +right_node.key_area_prefix_mut(..right_len), +left_node.key_area_range_mut(old_left_len + 1..new_left_len), +); + } +} + +unsafe fn merge_vals<'a, 'short, K, V>( + parent_node: &'short mut NodeRef, K, V, marker::Internal>, + left_node: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + right_node: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + parent_idx: usize, + old_parent_len: usize, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +) { + unsafe { +let parent_val = slice_remove(parent_node.val_area_prefix_mut(..old_parent_len), parent_idx); +left_node.val_area_slot_mut(old_left_len).write(parent_val); +move_to_slice( +right_node.val_area_prefix_mut(..right_len), +left_node.val_area_range_mut(old_left_len + 1..new_left_len), +); + } +} + +unsafe fn remove_merged_edge<'a, 'short, K, V>( + parent_node: &'short mut NodeRef, K, V, marker::Internal>, + parent_idx: usize, + old_parent_len: usize, +) { + unsafe { +slice_remove(parent_node.edge_area_prefix_mut(..old_parent_len + 1), parent_idx + 1); +parent_node.relink_range(parent_idx + 1..old_parent_len); +*parent_node.len_mut() -= 1; + } +} + +unsafe fn append_merged_edges<'a, 'short, K, V>( + left_node: &'short mut NodeRef, K, V, marker::Internal>, + right_node: &'short mut NodeRef, K, V, marker::Internal>, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +) { + unsafe { +move_to_slice( +right_node.edge_area_prefix_mut(..right_len + 1), +left_node.edge_area_range_mut(old_left_len + 1..new_left_len + 1), +); +left_node.relink_range(old_left_len + 1..new_left_len + 1); + } +} + +impl NodeRef { +// SOURCE_IN_IMPL pub(super) fn forget_type(self) -> NodeRef { +} + +impl NodeRef { +// SOURCE_IN_IMPL pub(super) fn forget_type(self) -> NodeRef { +} + +impl<'a, K, V> SplitResult<'a, K, V, marker::Leaf> { +// SOURCE_IN_IMPL pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> { +} + +impl<'a, K, V> SplitResult<'a, K, V, marker::Internal> { +// SOURCE_IN_IMPL pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> { +} + +impl LeafNode { +// SOURCE unsafe fn init(this: *mut Self) { + +// SOURCE fn new(alloc: A) -> Box { +} + +impl InternalNode { +// SOURCE unsafe fn new(alloc: A) -> Box { +} + +impl NodeRef { +// SOURCE fn as_leaf_ptr(this: &Self) -> *mut LeafNode { +} + +impl NodeRef { +// SOURCE fn as_internal_ptr(this: &Self) -> *mut InternalNode { +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE fn as_leaf_mut(&mut self) -> &mut LeafNode { +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn key_area_range_mut<'short>( + &'short mut self, index: std::ops::Range, + ) -> &'short mut [MaybeUninit] { + unsafe { self.as_leaf_mut().keys.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn key_area_prefix_mut<'short>( + &'short mut self, index: std::ops::RangeTo, + ) -> &'short mut [MaybeUninit] { + unsafe { self.as_leaf_mut().keys.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn key_area_slot_mut<'short>( + &'short mut self, index: usize, + ) -> &'short mut MaybeUninit { + unsafe { self.as_leaf_mut().keys.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn val_area_range_mut<'short>( + &'short mut self, index: std::ops::Range, + ) -> &'short mut [MaybeUninit] { + unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn val_area_prefix_mut<'short>( + &'short mut self, index: std::ops::RangeTo, + ) -> &'short mut [MaybeUninit] { + unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn val_area_slot_mut<'short>( + &'short mut self, index: usize, + ) -> &'short mut MaybeUninit { + unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE fn as_internal_mut(&mut self) -> &mut InternalNode { +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn edge_area_range_mut<'short>( + &'short mut self, index: std::ops::Range, + ) -> &'short mut [MaybeUninit>] { + unsafe { self.as_internal_mut().edges.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn edge_area_prefix_mut<'short>( + &'short mut self, index: std::ops::RangeTo, + ) -> &'short mut [MaybeUninit>] { + unsafe { self.as_internal_mut().edges.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn edge_area_slot_mut<'short>( + &'short mut self, index: usize, + ) -> &'short mut MaybeUninit> { + unsafe { self.as_internal_mut().edges.as_mut_slice().get_unchecked_mut(index) } + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + fn len_mut(&mut self) -> &mut u16 { + &mut self.as_leaf_mut().len + } +} + +impl<'a, K, V> NodeRef, K, V, marker::LeafOrInternal> { +// SOURCE unsafe fn cast_to_internal_unchecked(self) -> NodeRef, K, V, marker::Internal> { +} + +fn main() {} + + +struct BalancingContext<'a, K, V> { + parent: Handle, K, V, marker::Internal>, marker::KV>, + left_child: NodeRef, K, V, marker::LeafOrInternal>, + right_child: NodeRef, K, V, marker::LeafOrInternal>, +} + +impl NodeRef { + unsafe fn reborrow_mut<'b>(&'b mut self) -> NodeRef, K, V, Type> + //@ req *self |-> ?node; + //@ ens *self |-> node &*& result.node == node.node &*& result.height == node.height; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let borrowed = NodeRef { height: self.height, node: self.node, _marker: PhantomData }; + //@ close_points_to(self); + borrowed + } +} + +impl NodeRef { +// SOURCE pub(super) fn len(&self) -> usize { +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +// SOURCE fn do_merge< +} + +impl Handle, marker::Edge> { + unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { + debug_assert!(idx <= node.merge_len()); + + Handle { node, idx, _marker: PhantomData } + } +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { + fn merge_tracking_child( + self, + alloc: A, + ) -> NodeRef, K, V, marker::LeafOrInternal> { + self.merge_child_production(alloc) + } + +// SOURCE fn do_merge< + + fn merge_tracking_child_edge( + self, + track_edge_idx: LeftOrRight, + alloc: A, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { + let old_left_len = self.left_child.merge_len(); + let right_len = self.right_child.merge_len(); + assert!(match track_edge_idx { + LeftOrRight::Left(idx) => idx <= old_left_len, + LeftOrRight::Right(idx) => idx <= right_len, + }); + let child = self.merge_tracking_child(alloc); + let new_idx = match track_edge_idx { + LeftOrRight::Left(idx) => idx, + LeftOrRight::Right(idx) => old_left_len + 1 + idx, + }; + // ignore-tidy-undocumented-unsafe + unsafe { Handle::, marker::Edge>::new_edge(child, new_idx) } + } +} + +fn select_merged_child<'a,K,V>( + _parent: NodeRef, K, V, marker::Internal>, + child: NodeRef, K, V, marker::LeafOrInternal>, +) -> NodeRef, K, V, marker::LeafOrInternal> +{ + child +} + +unsafe fn borrow_initialized_slot<'short,T>(slot: &'short mut MaybeUninit) -> &'short mut T +{ + unsafe { &mut *slot.as_mut_ptr() } +} + +/*@ +fix replace_slot(index: usize, entry: T, slots: list) -> list { + append(take(index,slots),cons(entry,drop(index+1,slots))) +} +@*/ + +impl<'a, K:'a, V:'a, NodeType> Handle,K,V,NodeType>,marker::KV> { + unsafe fn replace_kv_production<'short>(&'short mut self, k:K, v:V) -> (K,V) + { + debug_assert!(self.idx < self.node.merge_len()); + let leaf = self.node.as_leaf_mut(); + let key = unsafe { borrow_initialized_slot(leaf.keys.get_unchecked_mut(self.idx)) }; + let val = unsafe { borrow_initialized_slot(leaf.vals.get_unchecked_mut(self.idx)) }; + (std::mem::replace(key, k), std::mem::replace(val, v)) + } +} + +enum ForceResult { + Leaf(Leaf), + Internal(Internal), +} + +impl NodeRef { + unsafe fn force( + self, + ) -> ForceResult< + NodeRef, + NodeRef, + > + //@ req 0 <= self.height; + /*@ + ens match result { + ForceResult::Leaf(leaf) => self.height == 0 &*& leaf.height == self.height &*& leaf.node == self.node, + ForceResult::Internal(internal) => self.height > 0 &*& internal.height == self.height &*& internal.node == self.node + }; + @*/ + //@ on_unwind_ens false; + { + if self.height == 0 { + ForceResult::Leaf(NodeRef { + height: self.height, + node: self.node, + _marker: PhantomData, + }) + } else { + ForceResult::Internal(NodeRef { + height: self.height, + node: self.node, + _marker: PhantomData, + }) + } + } +} + + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +// SOURCE pub(super) fn bulk_steal_left(&mut self, count: usize) { + +// SOURCE pub(super) fn bulk_steal_right(&mut self, count: usize) { + +// SOURCE pub(super) fn steal_left( + +// SOURCE pub(super) fn steal_right( +} + + +impl<'a, K, V, Type, Kind> Handle, K, V, Type>, Kind> { + unsafe fn reborrow_handle_mut<'short>(&'short mut self) -> Handle, K, V, Type>, Kind> { + // We can't use Handle::new_kv or Handle::new_edge because we don't know our type + // ignore-tidy-undocumented-unsafe + Handle { node: unsafe { self.node.reborrow_mut() }, idx: self.idx, _marker: PhantomData } + } +} + +impl Handle { + unsafe fn into_node(self) -> Node { + self.node + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { +// SOURCE pub(super) fn move_suffix( +} + + + +// BEGIN_DROP_VALUE +unsafe fn drop_slot_production<'slot, T>(slot: &'slot mut MaybeUninit) { + unsafe { std::ptr::drop_in_place(slot.as_mut_ptr()) } +} + +struct Dropper<'a, T>(&'a mut MaybeUninit); + +impl<'a, T> Dropper<'a, T> { + unsafe fn drop_value_guard(&mut self) { + unsafe { + drop_slot_production(self.0); + } + } +} +// END_DROP_VALUE + +// The storage remains reusable after either exit from the destructor. +unsafe fn drop_initialized_slot(slot: *mut MaybeUninit) +/*@ +req thread_token(?t) &*& type_interp::() &*& *slot |-> ?bits &*& + bits.inner() == some(?value) &*& .own(t, value); +@*/ +//@ ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +{ + unsafe { drop_slot_production(&mut *slot) } +} + +unsafe fn drop_guarded_value(slot: *mut MaybeUninit) +/*@ +req thread_token(?t) &*& type_interp::() &*& *slot |-> ?bits &*& + bits.inner() == some(?value) &*& .own(t, value); +@*/ +//@ ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +{ + let mut guard = Dropper(unsafe { &mut *slot }); + //@ close_points_to(&mut guard); + unsafe { guard.drop_value_guard() }; + //@ open_points_to(&mut guard); +} + +unsafe fn drop_pair(key: *mut MaybeUninit, value: *mut MaybeUninit) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *key |-> ?key_bits &*& key_bits.inner() == some(?k) &*& .own(t, k) &*& + *value |-> ?value_bits &*& value_bits.inner() == some(?v) &*& .own(t, v); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *(key as *K) |-> _ &*& *(value as *V) |-> _; +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *(key as *K) |-> _ &*& exists::(?value_pending) &*& + if value_pending { *value |-> value_bits &*& .own(t, v) } + else { *(value as *V) |-> _ }; +@*/ +{ + //@ close exists::(true); + unsafe { drop_initialized_slot(key) }; + //@ open exists::(true); + //@ close exists::(false); + unsafe { drop_guarded_value(value) }; + //@ open exists::(false); +} + + +impl NodeRef { + unsafe fn len(&self) -> usize + //@ req [?f](*self |-> ?node) &*& [?ql]((*node.node.as_ptr()).len |-> ?len); + //@ ens [f](*self |-> node) &*& [ql]((*node.node.as_ptr()).len |-> len) &*& result == len; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let ptr = self.node.as_ptr(); + //@ close_points_to(self, f); + unsafe { (*ptr).len as usize } + } +} + +// The production cleanup edges are checked separately. A key unwind +// leaves its value pending. Its value guard completes that slot before +// the node guard resumes at the next pair. + +impl NodeRef { + unsafe fn as_leaf_dying<'short>(&'short mut self) -> &'short mut LeafNode { + let ptr = Self::as_leaf_ptr(self); + unsafe { &mut *ptr } + } +} + +unsafe fn duplicate_dying( + node: *const NodeRef, +) -> NodeRef { + unsafe { std::ptr::read(node) } +} + +/*@ +pred drop_slot_loan( + field: *[MaybeUninit; N], array: *[MaybeUninit; N], slot: *MaybeUninit, index: usize, + prior: list>, later: list> +) = + ref_mut_end_token(array, field) &*& + ref_mut_end_token(slot, array as *MaybeUninit + index) &*& + (array as *MaybeUninit)[..index] |-> prior &*& + (array as *MaybeUninit)[index+1..int_of_const(typeid(N))] |-> later; + +lem close_drop_array(p: *[T; N]) + req (p as *T)[..int_of_const(typeid(N))] |-> ?values; + ens *p |-> ?value &*& Array_elems(value) == values; +{ + let base = p as *T; + close_points_to(p, 1/2); + assert [1/2](*p |-> ?value); + Array_to_array(p); + merge_fractions array(base, int_of_const(typeid(N)), _); + assert Array_elems(value) == values; + close_points_to(p); +} + +lem end_drop_slot(field: *[MaybeUninit; N], slot: *MaybeUninit, index: usize) + req drop_slot_loan(field,?array,slot,index,?before,?after) &*& *slot |-> ?entry; + ens *field |-> ?entries &*& Array_elems(entries) == append(before,cons(entry,after)); +{ + open drop_slot_loan(field,array,slot,index,before,after); + let base = array as *MaybeUninit; + end_ref_mut(slot); + close array(base+index+1,0,[]); + close array(base+index,1,[entry]); + array_join(base+index); + array_join(base); + close_drop_array(array); + end_ref_mut(array); +} +@*/ + +impl Handle, marker::KV> { + unsafe fn project_drop_slots<'short>( + &'short mut self, + ) -> (&'short mut MaybeUninit, &'short mut MaybeUninit) { + debug_assert!(self.idx < self.node.merge_len()); + let leaf = self.node.as_leaf_dying(); + unsafe { + let key = leaf.keys.get_unchecked_mut(self.idx); + let val = leaf.vals.get_unchecked_mut(self.idx); + (key, val) + } + } +} + +/*@ +pred drop_kv_frame( + node: *LeafNode, leaf: *LeafNode, key: *MaybeUninit, value: *MaybeUninit, + index: usize, len: usize, keys: list>, vals: list>, + parent: Option>>, parent_idx: MaybeUninit +) = + ref_mut_end_token(leaf,node) &*& + leaf_header(leaf,parent,parent_idx) &*& (*leaf).len |-> len as u16 &*& + drop_slot_loan(&(*leaf).keys,?keys_ref,key,index,take(index,keys),drop(index+1,keys)) &*& + drop_slot_loan(&(*leaf).vals,?vals_ref,value,index,take(index,vals),drop(index+1,vals)); + +lem take_after_replacing_cell(entries: list, len: usize, index: usize, cell: T) + req 0 <= index &*& index < len &*& len <= length(entries); + ens drop(index+1,take(len,replace_slot(index,cell,entries))) == drop(index+1,take(len,entries)); +{ + let before = take(index,entries); + let head = append(before,[cell]); + let tail = drop(index+1,entries); + length_take(index,entries); + length_append(before,[cell]); + append_assoc(before,[cell],tail); + take_append(len,head,tail); + drop_append(index+1,head,take(len-index-1,tail)); + drop_0(take(len-index-1,tail)); + take_after_drop(entries,index+1,len-index-1); +} + +lem restore_dropped_kv( + node: *LeafNode, leaf: *LeafNode, key: *MaybeUninit, value: *MaybeUninit, + index: usize, len: usize, keys: list>, vals: list>, + parent: Option>>, parent_idx: MaybeUninit +) + req drop_kv_frame(node,leaf,key,value,index,len,keys,vals,parent,parent_idx) &*& + *(key as *K) |-> _ &*& *(value as *V) |-> _ &*& + 0 <= index &*& index < len &*& len <= CAPACITY &*& length(keys) == CAPACITY &*& length(vals) == CAPACITY; + ens leaf_header(node,parent,parent_idx) &*& leaf_slots(node,len,?next_keys,?next_vals) &*& + drop(index+1,take(len,next_keys)) == drop(index+1,take(len,keys)) &*& + drop(index+1,take(len,next_vals)) == drop(index+1,take(len,vals)); +{ + open drop_kv_frame(node,leaf,key,value,index,len,keys,vals,parent,parent_idx); + std::mem::close_MaybeUninit_(key); + std::mem::close_MaybeUninit_(value); + assert *key |-> ?dead_key; + assert *value |-> ?dead_val; + end_drop_slot(&(*leaf).keys,key,index); + end_drop_slot(&(*leaf).vals,value,index); + assert *(&(*leaf).keys) |-> ?repacked_keys; + assert *(&(*leaf).vals) |-> ?repacked_vals; + assert Array_elems(repacked_keys) == replace_slot(index,dead_key,keys); + assert Array_elems(repacked_vals) == replace_slot(index,dead_val,vals); + Array_to_array(&(*leaf).keys); + Array_to_array(&(*leaf).vals); + assert (*leaf).keys[..CAPACITY] |-> replace_slot(index,dead_key,keys); + assert (*leaf).vals[..CAPACITY] |-> replace_slot(index,dead_val,vals); + open leaf_header(leaf,parent,parent_idx); + close_points_to(leaf); + end_ref_mut(leaf); + open_points_to(node); + assert (*node).keys[..CAPACITY] |-> replace_slot(index,dead_key,keys); + assert (*node).vals[..CAPACITY] |-> replace_slot(index,dead_val,vals); + close leaf_header(node,parent,parent_idx); + close leaf_slots(node,len,_,_); + take_after_replacing_cell(keys,len,index,dead_key); + take_after_replacing_cell(vals,len,index,dead_val); +} +@*/ + +impl Handle,marker::KV> { + unsafe fn drop_key_val_step(mut self) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= self.idx &*& self.idx < len &*& + slot_owners(t,drop(self.idx,take(len,keys))) &*& slot_owners(t,drop(self.idx,take(len,vals))); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.node.node.as_ptr(),parent,parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),len,?final_keys,?final_vals) &*& + slot_owners(t,drop(self.idx+1,take(len,final_keys))) &*& slot_owners(t,drop(self.idx+1,take(len,final_vals))); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + drop_kv_frame(self.node.node.as_ptr(),?leaf,?key,?value,self.idx,len,keys,vals,parent,parent_idx) &*& + length(keys) == CAPACITY &*& length(vals) == CAPACITY &*& len <= CAPACITY &*& + *(key as *K) |-> _ &*& exists::(?pending) &*& + (if pending { + *value |-> ?contents &*& contents.inner() == some(?v) &*& .own(t,v) + } else { + *(value as *V) |-> _ + }) &*& slot_owners(t,drop(self.idx+1,take(len,keys))) &*& slot_owners(t,drop(self.idx+1,take(len,vals))); + @*/ + { + //@ assert *(&mut self) |-> ?incoming; + //@ let node = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open leaf_slots(node,len,keys,vals); + //@ assert length(keys) == CAPACITY && length(vals) == CAPACITY; + //@ close leaf_slots(node,len,keys,vals); + let (key_slot,value_slot) = self.project_drop_slots/*@::@*/(); + //@ assert ref_mut_end_token(?leaf,node); + //@ close drop_kv_frame(node,leaf,key_slot,value_slot,index,len,keys,vals,parent,parent_idx); + //@ length_take(len,keys); + //@ length_take(len,vals); + //@ drop_n_plus_one(index,take(len,keys)); + //@ drop_n_plus_one(index,take(len,vals)); + //@ open slot_owners(t,drop(index,take(len,keys))); + //@ open slot_owners(t,drop(index,take(len,vals))); + //@ nth_take_range(keys,len,index); + //@ nth_take_range(vals,len,index); + //@ drop_twice(1,index,take(len,keys)); + //@ drop_twice(1,index,take(len,vals)); + unsafe { drop_pair(key_slot,value_slot) }; + //@ restore_dropped_kv(node,leaf,key_slot,value_slot,index,len,keys,vals,parent,parent_idx); + } +} + +impl Handle,marker::KV> { + unsafe fn new_dying_kv(node: NodeRef, idx: usize) -> Self { + debug_assert!(idx < node.len()); + Handle { node, idx, _marker: PhantomData } + } +} + +unsafe fn drop_at( + node: *const NodeRef, + index: usize, +) { + unsafe { + let kv = Handle::new_dying_kv(duplicate_dying(node), index); + kv.drop_key_val_step(); + } +} + +unsafe fn drop_remaining( + node: *const NodeRef, + start: usize, +) { + let len = unsafe { (*node).len() }; + for i in start..len { + unsafe { drop_at(node, i) }; + } +} + +/*@ pred resume_phase(inside_value: bool) = true; @*/ + +unsafe fn finish_drop_value(value: *mut MaybeUninit, pending: bool) +/*@ +req thread_token(?t) &*& type_interp::() &*& + (if pending { + *value |-> ?contents &*& contents.inner() == some(?v) &*& .own(t,v) + } else { + *(value as *V) |-> _ + }); +@*/ +//@ ens thread_token(t) &*& type_interp::() &*& *(value as *V) |-> _; +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& *(value as *V) |-> _; +{ + if pending { + unsafe { drop_guarded_value(value) }; + } +} + +unsafe fn resume_drop_remaining( + node: *const NodeRef, + leaf: *mut LeafNode, + key: *mut MaybeUninit, + value: *mut MaybeUninit, + index: usize, + len: usize, + pending: bool, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& [?q](*node |-> ?incoming) &*& + drop_kv_frame(incoming.node.as_ptr(),leaf,key,value,index,len,?keys,?vals,?parent,?parent_idx) &*& + length(keys) == CAPACITY &*& length(vals) == CAPACITY &*& 0 <= index &*& index < len &*& len <= CAPACITY &*& + *(key as *K) |-> _ &*& + (if pending { + *value |-> ?contents &*& contents.inner() == some(?v) &*& .own(t,v) + } else { + *(value as *V) |-> _ + }) &*& slot_owners(t,drop(index+1,take(len,keys))) &*& slot_owners(t,drop(index+1,take(len,vals))); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& [q](*node |-> incoming) &*& + leaf_header(incoming.node.as_ptr(),parent,parent_idx) &*& leaf_slots(incoming.node.as_ptr(),len,_,_); +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& [q](*node |-> incoming) &*& + resume_phase(?inside_value) &*& + if inside_value { + drop_kv_frame(incoming.node.as_ptr(),leaf,key,value,index,len,keys,vals,parent,parent_idx) &*& + *(key as *K) |-> _ &*& *(value as *V) |-> _ &*& + slot_owners(t,drop(index+1,take(len,keys))) &*& slot_owners(t,drop(index+1,take(len,vals))) + } else { + drop_kv_frame(incoming.node.as_ptr(),?rest_leaf,?rest_key,?rest_value,?remaining,len,?ks,?vs,parent,parent_idx) &*& + length(ks) == CAPACITY &*& length(vs) == CAPACITY &*& index < remaining &*& remaining < len &*& + *(rest_key as *K) |-> _ &*& exists::(?rest_pending) &*& + (if rest_pending { + *rest_value |-> ?bits &*& bits.inner() == some(?entry) &*& .own(t,entry) + } else { + *(rest_value as *V) |-> _ + }) &*& slot_owners(t,drop(remaining+1,take(len,ks))) &*& slot_owners(t,drop(remaining+1,take(len,vs))) + }; +@*/ +{ + //@ close resume_phase(true); + unsafe { finish_drop_value(value, pending) }; + //@ open resume_phase(true); + //@ restore_dropped_kv(incoming.node.as_ptr(),leaf,key,value,index,len,keys,vals,parent,parent_idx); + //@ close resume_phase(false); + unsafe { drop_remaining(node, index + 1) }; + //@ open resume_phase(false); +} + + +use std::num::NonZero; + +impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { +// SOURCE fn split_leaf_data(&mut self, new_node: &mut LeafNode) -> (K, V) { +} + +impl NodeRef { +// SOURCE fn from_new_leaf(leaf: Box, A>) -> Self { +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { +// SOURCE_IN_IMPL pub(super) fn split( +} + +impl NodeRef { +// SOURCE fn from_new_internal( +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { +// SOURCE_IN_IMPL pub(super) fn split( +} + +impl NodeRef { +// SOURCE pub(super) fn borrow_mut(&mut self) -> NodeRef, K, V, Type> { +} + +// SOURCE fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight) { + +impl Handle, marker::Edge> { +// SOURCE pub(super) unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { +} + +impl Handle, marker::KV> { +// SOURCE pub(super) unsafe fn new_kv(node: NodeRef, idx: usize) -> Self { +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { +// SOURCE fn insert_fit(&mut self, key: K, val: V, edge: Root) { +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { +// SOURCE_IN_IMPL fn insert( +} + +impl<'tree, K: 'tree, V: 'tree> Handle, K, V, marker::Internal>, marker::Edge> { + unsafe fn insert(self, key: K, val: V, edge: Root, alloc: A) + -> Option> + { + unsafe { self.insert_production(key, val, edge, alloc) } + } +} + +impl Handle, marker::Edge> { +// SOURCE pub(super) unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { +} + +impl Handle, marker::KV> { +// SOURCE pub(super) unsafe fn new_kv(node: NodeRef, idx: usize) -> Self { +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { +// SOURCE unsafe fn insert_fit( +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { +// SOURCE_IN_IMPL fn insert( +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { + unsafe fn insert( + self, key: K, val: V, alloc: A, + ) -> ( + Option>, + Handle, marker::KV>, + ) + { + unsafe { self.insert_leaf_production(key, val, alloc) } + } +} + +impl NodeRef { +// SOURCE fn new_internal(child: Root, alloc: A) -> Self { +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { +// SOURCE pub(super) fn push(&mut self, key: K, val: V, edge: Root) { +} + +unsafe fn install_root_split<'tree, 'slot, K, V, A: AllocatorClone>( + root_slot: &'slot mut DormantMutRef<'tree, Option>>, + allocator: &mut A, + left: NonNull>, + key: K, + value: V, + right: Root, +) +{ + let borrowed_root = unsafe { root_slot.reborrow() }; + let root_payload = borrowed_root.as_mut().unwrap(); + let root_allocator = unsafe { clone_allocator(allocator) }; + let old = unsafe { ptr::read(root_payload) }; + let new = NodeRef::new_internal_production(old, root_allocator).forget_type(); + unsafe { ptr::write(root_payload, new); } + let mut view = NodeRef::, K, V, marker::Internal> { height: root_payload.height, node: root_payload.node, _marker: PhantomData }; + view.push_production(key, value, right); +} + +unsafe fn write_child_backlink( + leaf: *mut LeafNode, + parent: NonNull>, + parent_idx: usize, +) +//@ req thread_token(?t) &*& (*leaf).parent |-> _ &*& (*leaf).parent_idx |-> _ &*& parent_idx <= CAPACITY; +//@ ens thread_token(t) &*& (*leaf).parent |-> Option::Some(parent) &*& (*leaf).parent_idx |-> MaybeUninit::new(parent_idx as u16); +//@ on_unwind_ens false; +{ + unsafe { (*leaf).parent = Some(parent) }; + //@ open LeafNode_parent_idx_(leaf, _); + //@ points_to__limits(&(*leaf).parent_idx); + unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; +} + +// The production iterator is specialized to the two range types used by its +// callers. The invariant preserves the edge slots and separates the repaired +// prefix from the pending suffix. + +// BEGIN_NODE_LEN +impl NodeRef { + unsafe fn relink_len(&self) -> usize + //@ req [?f](*self |-> ?node) &*& [?ql]((*node.node.as_ptr()).len |-> ?len); + //@ ens [f](*self |-> node) &*& [ql]((*node.node.as_ptr()).len |-> len) &*& result == len; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let ptr = self.node.as_ptr(); + //@ close_points_to(self, f); + unsafe { (*ptr).len as usize } + } +} +// END_NODE_LEN + +// BEGIN_NODE_REBORROW +impl NodeRef { + unsafe fn relink_reborrow<'b>(&'b mut self) -> NodeRef, K, V, Type> + //@ req *self |-> ?node; + //@ ens *self |-> node &*& result.node == node.node &*& result.height == node.height; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let borrowed = NodeRef { height: self.height, node: self.node, _marker: PhantomData }; + //@ close_points_to(self); + borrowed + } +} +// END_NODE_REBORROW + +// BEGIN_NEW_EDGE +impl Handle, marker::Edge> { + unsafe fn new_relink_edge(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx <= len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx <= node.relink_len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} +// END_NEW_EDGE + +// The generator binds the read and the two stores to descend and set_parent_link. +impl<'a, K, V> Handle, K, V, marker::Internal>, marker::Edge> { + unsafe fn correct_parent_link(self) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + 0 < self.node.height &*& self.node.height <= usize::MAX &*& 0 <= self.idx &*& self.idx <= CAPACITY &*& + exists::>>(?parent) &*& self.node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + exists::>(?child) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + nth(self.idx, edges) == MaybeUninit::new(child) &*& + (*child.as_ptr()).parent |-> _ &*& (*child.as_ptr()).parent_idx |-> _; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new(self.idx as u16); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(child); + //@ std::ptr::NonNull_new_as_ptr(parent); + let parent_ptr = self.node.node.as_ptr() as *mut InternalNode; + let parent_link = unsafe { NonNull::new_unchecked(parent_ptr) }; + //@ std::ptr::NonNull_new_as_ptr(parent_link); + // BEGIN_RAW_EDGE_READ + //@ let array = &(*parent_ptr).edges; + //@ close_points_to(array); + //@ let view = precreate_ref(array); + //@ init_ref_readonly(view, 1/2); + //@ open_points_to(view); + //@ let base = view as *MaybeUninit>; + //@ array_inv::>>(); + //@ array_split(base, self.idx); + //@ array_split(base + self.idx, 1); + //@ nth_drop(0, self.idx, edges); + //@ open [1/2]array(base + self.idx, 1, _); + //@ open [1/2]array(base + self.idx + 1, 0, _); + //@ let slot = precreate_ref(base + self.idx); + //@ init_ref_readonly(slot, 1/2); + let edge = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() }; + //@ end_ref_readonly(slot); + //@ merge_fractions points_to(base + self.idx, _); + //@ close [1/2]array(base + self.idx, 1, [MaybeUninit::new(child)]); + //@ array_join(base + self.idx); + //@ array_join(base); + //@ close_points_to(view, 1/2); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(array, _); + //@ open_points_to(array); + // END_RAW_EDGE_READ + let _child_height = self.node.height - 1; + unsafe { write_child_backlink(edge.as_ptr(), parent_link, self.idx) }; + } +} + +// BEGIN_RELINK_STEP +unsafe fn repair_one<'a, 'b, K, V>( + node: &'b mut NodeRef, K, V, marker::Internal>, + i: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *node |-> ?original &*& 0 < original.height &*& original.height <= usize::MAX &*& + (*original.node.as_ptr()).len |-> ?len &*& 0 <= i &*& i <= len &*& len <= CAPACITY &*& + exists::>>(?parent) &*& original.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& exists::>(?child) &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& nth(i, edges) == MaybeUninit::new(child) &*& + (*child.as_ptr()).parent |-> _ &*& (*child.as_ptr()).parent_idx |-> _; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *node |-> original &*& (*original.node.as_ptr()).len |-> len &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new(i as u16); +@*/ +//@ on_unwind_ens false; +{ + //@ open exists(parent); + //@ open exists(child); + //@ close exists(parent); + //@ close exists(child); + unsafe { Handle::new_relink_edge/*@::,K,V,marker::Internal>@*/( + node.relink_reborrow/*@::,K,V,marker::Internal,'b>@*/(), i + ).correct_parent_link/*@::<'b,K,V>@*/() }; +} + +// END_RELINK_STEP + + + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn relink_range<'b>(&'b mut self, range: std::ops::Range) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + (*node.node.as_ptr()).len |-> ?len &*& len <= CAPACITY &*& + 0 <= range.start &*& range.start <= range.end &*& range.end <= len + 1 &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + child_headers(?children) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + exists::>>, list>>>>(pair(?before, ?after)) &*& + length(before) == range.start &*& + edges == append(before, append(initialized_edges(children), after)) &*& + length(children) == range.end - range.start; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + linked_headers(children, parent, range.start); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(pair(before, after)); + let mut iter = range.into_iter(); + //@ let first = range.start; + //@ let end = range.end; + //@ close linked_headers([], parent, first); + loop { + /*@ + inv iter |-> ?state &*& state.end == end &*& + thread_token(t) &*& lifetime_token(func_lft) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + first <= state.start &*& state.start <= end &*& + linked_headers(?prefix, parent, first) &*& child_headers(?rest) &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + children == append(prefix, rest) &*& length(prefix) == state.start - first &*& length(rest) == end - state.start; + @*/ + let iter_ref = &mut iter; + let next = iter_ref.next(); + match next { + None => break, + Some(i) => { + //@ unpack_nonempty(rest); + //@ assert rest == cons(?child, ?remaining); + //@ initialized_edge_count(prefix); + //@ initialized_edge_count(rest); + //@ initialized_edges_append(prefix, rest); + //@ length_append(initialized_edges(prefix), initialized_edges(rest)); + //@ length_append(initialized_edges(children), after); + //@ nth_append_r(before, append(initialized_edges(children), after), i - first); + //@ nth_append(initialized_edges(children), after, i - first); + //@ nth_append_r(initialized_edges(prefix), initialized_edges(rest), 0); + //@ open child_headers(rest); + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + unsafe { debug_assert!(i <= self.relink_len()) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self,_); + //@ close exists(parent); + //@ close exists(child); + unsafe { repair_one/*@::@*/(self, i) }; + //@ append_linked_header(prefix, child, parent, first); + //@ append_assoc(prefix, [child], remaining); + } + } + } + //@ assert child_headers(?unrepaired); + //@ assert linked_headers(?repaired, parent, first); + //@ empty_list_if_zero(unrepaired); + //@ append_nil(repaired); + //@ open child_headers(unrepaired); + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn relink_inclusive<'b>(&'b mut self, range: std::ops::RangeInclusive) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + (*node.node.as_ptr()).len |-> ?len &*& len <= CAPACITY &*& + range.exhausted == false &*& 0 <= range.start &*& range.start <= (range.end + 1) &*& (range.end + 1) <= len + 1 &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + child_headers(?children) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + exists::>>, list>>>>(pair(?before, ?after)) &*& + length(before) == range.start &*& + edges == append(before, append(initialized_edges(children), after)) &*& + length(children) == (range.end + 1) - range.start; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + linked_headers(children, parent, range.start); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(pair(before, after)); + let mut iter = range.into_iter(); + //@ let first = range.start; + //@ let end = (range.end + 1); + //@ close linked_headers([], parent, first); + loop { + /*@ + inv iter |-> ?state &*& state.end + 1 == end &*& state.exhausted == false &*& + thread_token(t) &*& lifetime_token(func_lft) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + first <= state.start &*& state.start <= end &*& + linked_headers(?prefix, parent, first) &*& child_headers(?rest) &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + children == append(prefix, rest) &*& length(prefix) == state.start - first &*& length(rest) == end - state.start; + @*/ + let iter_ref = &mut iter; + let next = iter_ref.next(); + match next { + None => break, + Some(i) => { + //@ unpack_nonempty(rest); + //@ assert rest == cons(?child, ?remaining); + //@ initialized_edge_count(prefix); + //@ initialized_edge_count(rest); + //@ initialized_edges_append(prefix, rest); + //@ length_append(initialized_edges(prefix), initialized_edges(rest)); + //@ length_append(initialized_edges(children), after); + //@ nth_append_r(before, append(initialized_edges(children), after), i - first); + //@ nth_append(initialized_edges(children), after, i - first); + //@ nth_append_r(initialized_edges(prefix), initialized_edges(rest), 0); + //@ open child_headers(rest); + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + unsafe { debug_assert!(i <= self.relink_len()) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self,_); + //@ close exists(parent); + //@ close exists(child); + unsafe { repair_one/*@::@*/(self, i) }; + //@ append_linked_header(prefix, child, parent, first); + //@ append_assoc(prefix, [child], remaining); + } + } + } + //@ assert child_headers(?unrepaired); + //@ assert linked_headers(?repaired, parent, first); + //@ empty_list_if_zero(unrepaired); + //@ append_nil(repaired); + //@ open child_headers(unrepaired); + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn correct_all_childrens_parent_links<'b>(&'b mut self) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + (*node.node.as_ptr()).len |-> ?occupancy &*& occupancy <= CAPACITY &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + child_headers(?children) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + exists::>>>(?tail) &*& + edges == append(initialized_edges(children), tail) &*& length(children) == occupancy + 1; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> occupancy &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& linked_headers(children, parent, 0); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(tail); + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + let len = unsafe { self.relink_len() }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self, _); + //@ close exists(parent); + //@ let prefix = nil::>>; + //@ close exists(pair(prefix, tail)); + unsafe { self.relink_inclusive/*@::<'a,K,V,'b>@*/(0..=len) }; + } +} +use std::{alloc::Global, boxed::Box, mem::ManuallyDrop}; + +// SOURCE pub struct BTreeMap< + +// SOURCE pub struct CursorMutKey< + +// SOURCE pub struct VacantEntry< + +type RootInputs<'a, K, V, A> = (&'a mut Root, A, K, V, Root); + +impl<'a, K, V, A: AllocatorClone> CursorMutKey<'a, K, V, A> { + fn project_root_inputs_0( + &mut self, split: Option>, + ) -> Option> { + split.map(|ins| { +// ROOT_CALLBACK 1 + }) + } +} + +impl<'a, K, V, A: AllocatorClone> CursorMutKey<'a, K, V, A> { + fn project_root_inputs_1( + &mut self, split: Option>, + ) -> Option> { + split.map(|ins| { +// ROOT_CALLBACK 2 + }) + } +} + +impl<'a, K, V, A: AllocatorClone> VacantEntry<'a, K, V, A> { + fn project_root_inputs_0( + &mut self, split: Option>, + ) -> Option> { + split.map(|ins| { +// ROOT_CALLBACK 3 + }) + } +} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/refinement.patch b/verifast-proofs/alloc/collections/btree/node.rs/refinement.patch new file mode 100644 index 0000000000000..b4ed77331b97b --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/refinement.patch @@ -0,0 +1,1175 @@ +--- a/original/operations.rs ++++ b/original/operations.rs +@@ -123,5 +123,5 @@ + + impl NodeRef { +- pub(super) unsafe fn awaken<'a>(self) -> NodeRef, K, V, Type> { ++ unsafe fn awaken<'a>(self) -> NodeRef, K, V, Type> { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +@@ -129,5 +129,5 @@ + + impl Handle, HandleType> { +- pub(super) unsafe fn awaken<'a>( ++ unsafe fn awaken<'a>( + self, + ) -> Handle, K, V, NodeType>, HandleType> { +@@ -138,5 +138,5 @@ + + impl<'a, K, V, Type> NodeRef, K, V, Type> { +- pub(super) fn dormant(&self) -> NodeRef { ++ fn dormant(&self) -> NodeRef { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +@@ -144,5 +144,5 @@ + + impl<'a, K, V, NodeType, HandleType> Handle, K, V, NodeType>, HandleType> { +- pub(super) fn dormant( ++ fn dormant( + &self, + ) -> Handle, HandleType> { +@@ -151,5 +151,5 @@ + } + +-pub(super) struct DormantMutRef<'a, T> { ++struct DormantMutRef<'a, T> { + ptr: NonNull, + _marker: PhantomData<&'a mut T>, +@@ -157,5 +157,5 @@ + + impl<'a, T> DormantMutRef<'a, T> { +- pub(super) unsafe fn reborrow(&mut self) -> &'a mut T { ++ unsafe fn reborrow(&mut self) -> &'a mut T { + // SAFETY: our own safety conditions imply this reference is again unique. + unsafe { &mut *self.ptr.as_ptr() } +@@ -341,5 +341,5 @@ + + impl NodeRef { +- pub(super) fn forget_type(self) -> NodeRef { ++ fn forget_type(self) -> NodeRef { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +@@ -347,5 +347,5 @@ + + impl NodeRef { +- pub(super) fn forget_type(self) -> NodeRef { ++ fn forget_type(self) -> NodeRef { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +@@ -353,5 +353,5 @@ + + impl<'a, K, V> SplitResult<'a, K, V, marker::Leaf> { +- pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> { ++ fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> { + SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() } + } +@@ -359,5 +359,5 @@ + + impl<'a, K, V> SplitResult<'a, K, V, marker::Internal> { +- pub(super) fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> { ++ fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> { + SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() } + } +@@ -537,5 +537,5 @@ + + impl NodeRef { +- pub(super) fn len(&self) -> usize { ++ fn merge_len(&self) -> usize { + // SAFETY: We only access the `len` field here. If BorrowType is marker::ValMut, + // there might be outstanding mutable references to values that we must not invalidate. +@@ -545,5 +545,5 @@ + + impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +- fn do_merge< ++ fn do_merge_production< + F: FnOnce( + NodeRef, K, V, marker::Internal>, +@@ -551,16 +551,16 @@ + ) -> R, + R, +- A: Allocator, ++ A: std::alloc::Allocator, + >( + self, + result: F, +- alloc: A, ++ /*@~mut@*/ alloc: A, + ) -> R { + let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent; +- let old_parent_len = parent_node.len(); ++ let old_parent_len = parent_node.merge_len(); + let mut left_node = self.left_child; +- let old_left_len = left_node.len(); ++ let old_left_len = left_node.merge_len(); + let mut right_node = self.right_child; +- let right_len = right_node.len(); ++ let right_len = right_node.merge_len(); + let new_left_len = old_left_len + 1 + right_len; + +@@ -571,20 +571,20 @@ + *left_node.len_mut() = new_left_len as u16; + +- let parent_key = slice_remove(parent_node.key_area_mut(..old_parent_len), parent_idx); +- left_node.key_area_mut(old_left_len).write(parent_key); ++ let parent_key = slice_remove(parent_node.key_area_prefix_mut(..old_parent_len), parent_idx); ++ left_node.key_area_slot_mut(old_left_len).write(parent_key); + move_to_slice( +- right_node.key_area_mut(..right_len), +- left_node.key_area_mut(old_left_len + 1..new_left_len), ++ right_node.key_area_prefix_mut(..right_len), ++ left_node.key_area_range_mut(old_left_len + 1..new_left_len), + ); + +- let parent_val = slice_remove(parent_node.val_area_mut(..old_parent_len), parent_idx); +- left_node.val_area_mut(old_left_len).write(parent_val); ++ let parent_val = slice_remove(parent_node.val_area_prefix_mut(..old_parent_len), parent_idx); ++ left_node.val_area_slot_mut(old_left_len).write(parent_val); + move_to_slice( +- right_node.val_area_mut(..right_len), +- left_node.val_area_mut(old_left_len + 1..new_left_len), ++ right_node.val_area_prefix_mut(..right_len), ++ left_node.val_area_range_mut(old_left_len + 1..new_left_len), + ); + +- slice_remove(parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1); +- parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len); ++ slice_remove(parent_node.edge_area_prefix_mut(..old_parent_len + 1), parent_idx + 1); ++ parent_node.relink_range(parent_idx + 1..old_parent_len); + *parent_node.len_mut() -= 1; + +@@ -595,13 +595,13 @@ + let mut right_node = right_node.cast_to_internal_unchecked(); + move_to_slice( +- right_node.edge_area_mut(..right_len + 1), +- left_node.edge_area_mut(old_left_len + 1..new_left_len + 1), ++ right_node.edge_area_prefix_mut(..right_len + 1), ++ left_node.edge_area_range_mut(old_left_len + 1..new_left_len + 1), + ); + +- left_node.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); ++ left_node.relink_range(old_left_len + 1..new_left_len + 1); + +- alloc.deallocate(right_node.node.cast(), Layout::new::>()); ++ alloc.deallocate(right_node.node.cast(), std::alloc::Layout::new::>()); + } else { +- alloc.deallocate(right_node.node.cast(), Layout::new::>()); ++ alloc.deallocate(right_node.node.cast(), std::alloc::Layout::new::>()); + } + } +@@ -626,22 +626,14 @@ + } + +- fn do_merge< +- F: FnOnce( +- NodeRef, K, V, marker::Internal>, +- NodeRef, K, V, marker::LeafOrInternal>, +- ) -> R, +- R, +- A: Allocator, +- >( ++ fn merge_child_production( + self, +- result: F, +- alloc: A, +- ) -> R { ++ /*@~mut@*/ alloc: A, ++ ) -> NodeRef, K, V, marker::LeafOrInternal> { + let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent; +- let old_parent_len = parent_node.len(); ++ let old_parent_len = parent_node.merge_len(); + let mut left_node = self.left_child; +- let old_left_len = left_node.len(); ++ let old_left_len = left_node.merge_len(); + let mut right_node = self.right_child; +- let right_len = right_node.len(); ++ let right_len = right_node.merge_len(); + let new_left_len = old_left_len + 1 + right_len; + +@@ -652,20 +644,20 @@ + *left_node.len_mut() = new_left_len as u16; + +- let parent_key = slice_remove(parent_node.key_area_mut(..old_parent_len), parent_idx); +- left_node.key_area_mut(old_left_len).write(parent_key); ++ let parent_key = slice_remove(parent_node.key_area_prefix_mut(..old_parent_len), parent_idx); ++ left_node.key_area_slot_mut(old_left_len).write(parent_key); + move_to_slice( +- right_node.key_area_mut(..right_len), +- left_node.key_area_mut(old_left_len + 1..new_left_len), ++ right_node.key_area_prefix_mut(..right_len), ++ left_node.key_area_range_mut(old_left_len + 1..new_left_len), + ); + +- let parent_val = slice_remove(parent_node.val_area_mut(..old_parent_len), parent_idx); +- left_node.val_area_mut(old_left_len).write(parent_val); ++ let parent_val = slice_remove(parent_node.val_area_prefix_mut(..old_parent_len), parent_idx); ++ left_node.val_area_slot_mut(old_left_len).write(parent_val); + move_to_slice( +- right_node.val_area_mut(..right_len), +- left_node.val_area_mut(old_left_len + 1..new_left_len), ++ right_node.val_area_prefix_mut(..right_len), ++ left_node.val_area_range_mut(old_left_len + 1..new_left_len), + ); + +- slice_remove(parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1); +- parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len); ++ slice_remove(parent_node.edge_area_prefix_mut(..old_parent_len + 1), parent_idx + 1); ++ parent_node.relink_range(parent_idx + 1..old_parent_len); + *parent_node.len_mut() -= 1; + +@@ -676,16 +668,16 @@ + let mut right_node = right_node.cast_to_internal_unchecked(); + move_to_slice( +- right_node.edge_area_mut(..right_len + 1), +- left_node.edge_area_mut(old_left_len + 1..new_left_len + 1), ++ right_node.edge_area_prefix_mut(..right_len + 1), ++ left_node.edge_area_range_mut(old_left_len + 1..new_left_len + 1), + ); + +- left_node.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); ++ left_node.relink_range(old_left_len + 1..new_left_len + 1); + +- alloc.deallocate(right_node.node.cast(), Layout::new::>()); ++ alloc.deallocate(right_node.node.cast(), std::alloc::Layout::new::>()); + } else { +- alloc.deallocate(right_node.node.cast(), Layout::new::>()); ++ alloc.deallocate(right_node.node.cast(), std::alloc::Layout::new::>()); + } + } +- result(parent_node, left_node) ++ select_merged_child(parent_node, left_node) + } + +@@ -780,12 +772,12 @@ + + impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +- pub(super) fn bulk_steal_left(&mut self, count: usize) { ++ unsafe fn bulk_steal_left_production<'short>(&'short mut self, count: usize) { + assert!(count > 0); + // ignore-tidy-undocumented-unsafe + unsafe { + let left_node = &mut self.left_child; +- let old_left_len = left_node.len(); ++ let old_left_len = left_node.merge_len(); + let right_node = &mut self.right_child; +- let old_right_len = right_node.len(); ++ let old_right_len = right_node.merge_len(); + + // Make sure that we may steal safely. +@@ -801,25 +793,25 @@ + { + // Make room for stolen elements in the right child. +- slice_shr(right_node.key_area_mut(..new_right_len), count); +- slice_shr(right_node.val_area_mut(..new_right_len), count); ++ slice_shr(right_node.key_area_prefix_mut(..new_right_len), count); ++ slice_shr(right_node.val_area_prefix_mut(..new_right_len), count); + + // Move elements from the left child to the right one. + move_to_slice( +- left_node.key_area_mut(new_left_len + 1..old_left_len), +- right_node.key_area_mut(..count - 1), ++ left_node.key_area_range_mut(new_left_len + 1..old_left_len), ++ right_node.key_area_prefix_mut(..count - 1), + ); + move_to_slice( +- left_node.val_area_mut(new_left_len + 1..old_left_len), +- right_node.val_area_mut(..count - 1), ++ left_node.val_area_range_mut(new_left_len + 1..old_left_len), ++ right_node.val_area_prefix_mut(..count - 1), + ); + + // Move the leftmost stolen pair to the parent. +- let k = left_node.key_area_mut(new_left_len).assume_init_read(); +- let v = left_node.val_area_mut(new_left_len).assume_init_read(); +- let (k, v) = self.parent.replace_kv(k, v); ++ let k = left_node.key_area_slot_mut(new_left_len).assume_init_read(); ++ let v = left_node.val_area_slot_mut(new_left_len).assume_init_read(); ++ let (k, v) = self.parent.replace_kv_production(k, v); + + // Move parent's key-value pair to the right child. +- right_node.key_area_mut(count - 1).write(k); +- right_node.val_area_mut(count - 1).write(v); ++ right_node.key_area_slot_mut(count - 1).write(k); ++ right_node.val_area_slot_mut(count - 1).write(v); + } + +@@ -827,13 +819,13 @@ + (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { + // Make room for stolen edges. +- slice_shr(right.edge_area_mut(..new_right_len + 1), count); ++ slice_shr(right.edge_area_prefix_mut(..new_right_len + 1), count); + + // Steal edges. + move_to_slice( +- left.edge_area_mut(new_left_len + 1..old_left_len + 1), +- right.edge_area_mut(..count), ++ left.edge_area_range_mut(new_left_len + 1..old_left_len + 1), ++ right.edge_area_prefix_mut(..count), + ); + +- right.correct_childrens_parent_links(0..new_right_len + 1); ++ right.relink_range(0..new_right_len + 1); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} +@@ -843,12 +835,12 @@ + } + +- pub(super) fn bulk_steal_right(&mut self, count: usize) { ++ unsafe fn bulk_steal_right_production<'short>(&'short mut self, count: usize) { + assert!(count > 0); + // ignore-tidy-undocumented-unsafe + unsafe { + let left_node = &mut self.left_child; +- let old_left_len = left_node.len(); ++ let old_left_len = left_node.merge_len(); + let right_node = &mut self.right_child; +- let old_right_len = right_node.len(); ++ let old_right_len = right_node.merge_len(); + + // Make sure that we may steal safely. +@@ -864,25 +856,25 @@ + { + // Move the rightmost stolen pair to the parent. +- let k = right_node.key_area_mut(count - 1).assume_init_read(); +- let v = right_node.val_area_mut(count - 1).assume_init_read(); +- let (k, v) = self.parent.replace_kv(k, v); ++ let k = right_node.key_area_slot_mut(count - 1).assume_init_read(); ++ let v = right_node.val_area_slot_mut(count - 1).assume_init_read(); ++ let (k, v) = self.parent.replace_kv_production(k, v); + + // Move parent's key-value pair to the left child. +- left_node.key_area_mut(old_left_len).write(k); +- left_node.val_area_mut(old_left_len).write(v); ++ left_node.key_area_slot_mut(old_left_len).write(k); ++ left_node.val_area_slot_mut(old_left_len).write(v); + + // Move elements from the right child to the left one. + move_to_slice( +- right_node.key_area_mut(..count - 1), +- left_node.key_area_mut(old_left_len + 1..new_left_len), ++ right_node.key_area_prefix_mut(..count - 1), ++ left_node.key_area_range_mut(old_left_len + 1..new_left_len), + ); + move_to_slice( +- right_node.val_area_mut(..count - 1), +- left_node.val_area_mut(old_left_len + 1..new_left_len), ++ right_node.val_area_prefix_mut(..count - 1), ++ left_node.val_area_range_mut(old_left_len + 1..new_left_len), + ); + + // Fill gap where stolen elements used to be. +- slice_shl(right_node.key_area_mut(..old_right_len), count); +- slice_shl(right_node.val_area_mut(..old_right_len), count); ++ slice_shl(right_node.key_area_prefix_mut(..old_right_len), count); ++ slice_shl(right_node.val_area_prefix_mut(..old_right_len), count); + } + +@@ -891,13 +883,13 @@ + // Steal edges. + move_to_slice( +- right.edge_area_mut(..count), +- left.edge_area_mut(old_left_len + 1..new_left_len + 1), ++ right.edge_area_prefix_mut(..count), ++ left.edge_area_range_mut(old_left_len + 1..new_left_len + 1), + ); + + // Fill gap where stolen edges used to be. +- slice_shl(right.edge_area_mut(..old_right_len + 1), count); ++ slice_shl(right.edge_area_prefix_mut(..old_right_len + 1), count); + +- left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); +- right.correct_childrens_parent_links(0..new_right_len + 1); ++ left.relink_range(old_left_len + 1..new_left_len + 1); ++ right.relink_range(0..new_right_len + 1); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} +@@ -907,20 +899,20 @@ + } + +- pub(super) fn steal_left( ++ unsafe fn steal_left_production( + mut self, + track_right_edge_idx: usize, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { +- self.bulk_steal_left(1); ++ self.bulk_steal_left_production(1); + // ignore-tidy-undocumented-unsafe +- unsafe { Handle::new_edge(self.right_child, 1 + track_right_edge_idx) } ++ unsafe { Handle::, marker::Edge>::new_edge(self.right_child, 1 + track_right_edge_idx) } + } + +- pub(super) fn steal_right( ++ unsafe fn steal_right_production( + mut self, + track_left_edge_idx: usize, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { +- self.bulk_steal_right(1); ++ self.bulk_steal_right_production(1); + // ignore-tidy-undocumented-unsafe +- unsafe { Handle::new_edge(self.left_child, track_left_edge_idx) } ++ unsafe { Handle::, marker::Edge>::new_edge(self.left_child, track_left_edge_idx) } + } + } +@@ -942,18 +934,18 @@ + + impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { +- pub(super) fn move_suffix( +- &mut self, +- right: &mut NodeRef, K, V, marker::LeafOrInternal>, ++ unsafe fn move_suffix_production<'short>( ++ &'short mut self, ++ right: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + ) { + // ignore-tidy-undocumented-unsafe + unsafe { + let new_left_len = self.idx; +- let mut left_node = self.reborrow_mut().into_node(); +- let old_left_len = left_node.len(); ++ let mut left_node = self.reborrow_handle_mut().into_node(); ++ let old_left_len = left_node.merge_len(); + + let new_right_len = old_left_len - new_left_len; + let mut right_node = right.reborrow_mut(); + +- assert!(right_node.len() == 0); ++ assert!(right_node.merge_len() == 0); + assert!(left_node.height == right_node.height); + +@@ -963,18 +955,18 @@ + + move_to_slice( +- left_node.key_area_mut(new_left_len..old_left_len), +- right_node.key_area_mut(..new_right_len), ++ left_node.key_area_range_mut(new_left_len..old_left_len), ++ right_node.key_area_prefix_mut(..new_right_len), + ); + move_to_slice( +- left_node.val_area_mut(new_left_len..old_left_len), +- right_node.val_area_mut(..new_right_len), ++ left_node.val_area_range_mut(new_left_len..old_left_len), ++ right_node.val_area_prefix_mut(..new_right_len), + ); + match (left_node.force(), right_node.force()) { + (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { + move_to_slice( +- left.edge_area_mut(new_left_len + 1..old_left_len + 1), +- right.edge_area_mut(1..new_right_len + 1), ++ left.edge_area_range_mut(new_left_len + 1..old_left_len + 1), ++ right.edge_area_range_mut(1..new_right_len + 1), + ); +- right.correct_childrens_parent_links(1..new_right_len + 1); ++ right.relink_range(1..new_right_len + 1); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} +@@ -1359,19 +1351,19 @@ + impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { + fn split_leaf_data(&mut self, new_node: &mut LeafNode) -> (K, V) { +- debug_assert!(self.idx < self.node.len()); +- let old_len = self.node.len(); ++ debug_assert!(self.idx < self.node.merge_len()); ++ let old_len = self.node.merge_len(); + let new_len = old_len - self.idx - 1; + new_node.len = new_len as u16; + // ignore-tidy-undocumented-unsafe + unsafe { +- let k = self.node.key_area_mut(self.idx).assume_init_read(); +- let v = self.node.val_area_mut(self.idx).assume_init_read(); ++ let k = self.node.key_area_slot_mut(self.idx).assume_init_read(); ++ let v = self.node.val_area_slot_mut(self.idx).assume_init_read(); + + move_to_slice( +- self.node.key_area_mut(self.idx + 1..old_len), ++ self.node.key_area_range_mut(self.idx + 1..old_len), + &mut new_node.keys[..new_len], + ); + move_to_slice( +- self.node.val_area_mut(self.idx + 1..old_len), ++ self.node.val_area_range_mut(self.idx + 1..old_len), + &mut new_node.vals[..new_len], + ); +@@ -1392,5 +1384,5 @@ + + impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { +- pub(super) fn split( ++ fn split_production_leaf( + mut self, + alloc: A, +@@ -1413,5 +1405,5 @@ + let (node, _alloc) = Box::into_non_null_with_allocator(internal); + let mut this = NodeRef { height: height.into(), node: node.cast(), _marker: PhantomData }; +- this.borrow_mut().correct_all_childrens_parent_links(); ++ unsafe { this.borrow_mut().correct_all_childrens_parent_links() }; + this + } +@@ -1419,9 +1411,9 @@ + + impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { +- pub(super) fn split( ++ fn split_production_internal( + mut self, + alloc: A, + ) -> SplitResult<'a, K, V, marker::Internal> { +- let old_len = self.node.len(); ++ let old_len = unsafe { self.node.merge_len() }; + // ignore-tidy-undocumented-unsafe + unsafe { +@@ -1430,5 +1422,5 @@ + let new_len = usize::from(new_node.data.len); + move_to_slice( +- self.node.edge_area_mut(self.idx + 1..old_len + 1), ++ self.node.edge_area_range_mut(self.idx + 1..old_len + 1), + &mut new_node.edges[..new_len + 1], + ); +@@ -1444,5 +1436,5 @@ + + impl NodeRef { +- pub(super) fn borrow_mut(&mut self) -> NodeRef, K, V, Type> { ++fn borrow_mut(&mut self) -> NodeRef, K, V, Type> { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +@@ -1461,6 +1453,6 @@ + + impl Handle, marker::Edge> { +- pub(super) unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { +- debug_assert!(idx <= node.len()); ++ unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { ++ debug_assert!(idx <= node.merge_len()); + + Handle { node, idx, _marker: PhantomData } +@@ -1469,6 +1461,6 @@ + + impl Handle, marker::KV> { +- pub(super) unsafe fn new_kv(node: NodeRef, idx: usize) -> Self { +- debug_assert!(idx < node.len()); ++ unsafe fn new_kv(node: NodeRef, idx: usize) -> Self { ++ debug_assert!(idx < node.merge_len()); + + Handle { node, idx, _marker: PhantomData } +@@ -1477,17 +1469,17 @@ + + impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { +- fn insert_fit(&mut self, key: K, val: V, edge: Root) { +- debug_assert!(self.node.len() < CAPACITY); ++ fn insert_fit_production(&mut self, key: K, val: V, edge: Root) { ++ debug_assert!(self.node.merge_len() < CAPACITY); + debug_assert!(edge.height == self.node.height - 1); +- let new_len = self.node.len() + 1; ++ let new_len = self.node.merge_len() + 1; + + // ignore-tidy-undocumented-unsafe + unsafe { +- slice_insert(self.node.key_area_mut(..new_len), self.idx, key); +- slice_insert(self.node.val_area_mut(..new_len), self.idx, val); +- slice_insert(self.node.edge_area_mut(..new_len + 1), self.idx + 1, edge.node); ++ slice_insert(self.node.key_area_prefix_mut(..new_len), self.idx, key); ++ slice_insert(self.node.val_area_prefix_mut(..new_len), self.idx, val); ++ slice_insert(self.node.edge_area_prefix_mut(..new_len + 1), self.idx + 1, edge.node); + *self.node.len_mut() = new_len as u16; + +- self.node.correct_childrens_parent_links(self.idx + 1..new_len + 1); ++ self.node.relink_range(self.idx + 1..new_len + 1); + } + } +@@ -1495,5 +1487,5 @@ + + impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { +- fn insert( ++ fn insert_production( + mut self, + key: K, +@@ -1504,23 +1496,23 @@ + assert!(edge.height == self.node.height - 1); + +- if self.node.len() < CAPACITY { +- self.insert_fit(key, val, edge); ++ if self.node.merge_len() < CAPACITY { ++ self.insert_fit_production(key, val, edge); + None + } else { + let (middle_kv_idx, insertion) = splitpoint(self.idx); + // ignore-tidy-undocumented-unsafe +- let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; +- let mut result = middle.split(alloc); ++ let middle = unsafe { Handle::, marker::KV>::new_kv(self.node, middle_kv_idx) }; ++ let mut result = middle.split_production_internal(alloc); + let mut insertion_edge = match insertion { + // ignore-tidy-undocumented-unsafe + LeftOrRight::Left(insert_idx) => unsafe { +- Handle::new_edge(result.left.reborrow_mut(), insert_idx) ++ Handle::, marker::Edge>::new_edge(result.left.reborrow_mut(), insert_idx) + }, + // ignore-tidy-undocumented-unsafe + LeftOrRight::Right(insert_idx) => unsafe { +- Handle::new_edge(result.right.borrow_mut(), insert_idx) ++ Handle::, marker::Edge>::new_edge(result.right.borrow_mut(), insert_idx) + }, + }; +- insertion_edge.insert_fit(key, val, edge); ++ insertion_edge.insert_fit_production(key, val, edge); + Some(result) + } +@@ -1537,6 +1529,6 @@ + + impl Handle, marker::Edge> { +- pub(super) unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { +- debug_assert!(idx <= node.len()); ++ unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { ++ debug_assert!(idx <= node.merge_len()); + + Handle { node, idx, _marker: PhantomData } +@@ -1545,6 +1537,6 @@ + + impl Handle, marker::KV> { +- pub(super) unsafe fn new_kv(node: NodeRef, idx: usize) -> Self { +- debug_assert!(idx < node.len()); ++ unsafe fn new_kv(node: NodeRef, idx: usize) -> Self { ++ debug_assert!(idx < node.merge_len()); + + Handle { node, idx, _marker: PhantomData } +@@ -1553,19 +1545,19 @@ + + impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { +- unsafe fn insert_fit( ++ unsafe fn insert_fit_leaf_production( + mut self, + key: K, + val: V, + ) -> Handle, K, V, marker::Leaf>, marker::KV> { +- debug_assert!(self.node.len() < CAPACITY); +- let new_len = self.node.len() + 1; ++ debug_assert!(self.node.merge_len() < CAPACITY); ++ let new_len = self.node.merge_len() + 1; + + // ignore-tidy-undocumented-unsafe + unsafe { +- slice_insert(self.node.key_area_mut(..new_len), self.idx, key); +- slice_insert(self.node.val_area_mut(..new_len), self.idx, val); ++ slice_insert(self.node.key_area_prefix_mut(..new_len), self.idx, key); ++ slice_insert(self.node.val_area_prefix_mut(..new_len), self.idx, val); + *self.node.len_mut() = new_len as u16; + +- Handle::new_kv(self.node, self.idx) ++ Handle::, marker::KV>::new_kv(self.node, self.idx) + } + } +@@ -1573,5 +1565,5 @@ + + impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { +- fn insert( ++ fn insert_leaf_production( + self, + key: K, +@@ -1582,26 +1574,26 @@ + Handle, marker::KV>, + ) { +- if self.node.len() < CAPACITY { ++ if self.node.merge_len() < CAPACITY { + // SAFETY: There is enough space in the node for insertion. +- let handle = unsafe { self.insert_fit(key, val) }; ++ let handle = unsafe { self.insert_fit_leaf_production(key, val) }; + (None, handle.dormant()) + } else { + let (middle_kv_idx, insertion) = splitpoint(self.idx); + // ignore-tidy-undocumented-unsafe +- let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; +- let mut result = middle.split(alloc); ++ let middle = unsafe { Handle::, marker::KV>::new_kv(self.node, middle_kv_idx) }; ++ let mut result = middle.split_production_leaf(alloc); + let insertion_edge = match insertion { + // ignore-tidy-undocumented-unsafe + LeftOrRight::Left(insert_idx) => unsafe { +- Handle::new_edge(result.left.reborrow_mut(), insert_idx) ++ Handle::, marker::Edge>::new_edge(result.left.reborrow_mut(), insert_idx) + }, + // ignore-tidy-undocumented-unsafe + LeftOrRight::Right(insert_idx) => unsafe { +- Handle::new_edge(result.right.borrow_mut(), insert_idx) ++ Handle::, marker::Edge>::new_edge(result.right.borrow_mut(), insert_idx) + }, + }; + // SAFETY: We just split the node, so there is enough space for + // insertion. +- let handle = unsafe { insertion_edge.insert_fit(key, val).dormant() }; ++ let handle = unsafe { insertion_edge.insert_fit_leaf_production(key, val).dormant() }; + (Some(result), handle) + } +@@ -1622,5 +1614,5 @@ + + impl NodeRef { +- fn new_internal(child: Root, alloc: A) -> Self { ++ fn new_internal_production(child: Root, alloc: A) -> Self { + // ignore-tidy-undocumented-unsafe + let mut new_node = unsafe { InternalNode::new(alloc) }; +@@ -1631,5 +1623,5 @@ + + impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { +- pub(super) fn push(&mut self, key: K, val: V, edge: Root) { ++ fn push_production(&mut self, key: K, val: V, edge: Root) { + assert!(edge.height == self.height - 1); + +@@ -1640,8 +1632,8 @@ + // ignore-tidy-undocumented-unsafe + unsafe { +- self.key_area_mut(idx).write(key); +- self.val_area_mut(idx).write(val); +- self.edge_area_mut(idx + 1).write(edge.node); +- Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link(); ++ self.key_area_slot_mut(idx).write(key); ++ self.val_area_slot_mut(idx).write(val); ++ self.edge_area_slot_mut(idx + 1).write(edge.node); ++ Handle::, marker::Edge>::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link(); + } + } +--- a/original/loop_regions.rs ++++ b/original/loop_regions.rs +@@ -25,5 +25,6 @@ + + impl<'a, K, V> NodeRef, K, V, marker::Internal> { +- unsafe fn correct_childrens_parent_links>(&mut self, range: R) { ++ unsafe fn relink_range<'b>(&'b mut self, range: std::ops::Range) ++ { + for i in range { + debug_assert!(i <= self.len()); +@@ -35,5 +36,6 @@ + + impl<'a, K, V> NodeRef, K, V, marker::Internal> { +- unsafe fn correct_childrens_parent_links>(&mut self, range: R) { ++ unsafe fn relink_inclusive<'b>(&'b mut self, range: std::ops::RangeInclusive) ++ { + for i in range { + debug_assert!(i <= self.len()); +@@ -45,8 +47,9 @@ + + impl<'a, K, V> NodeRef, K, V, marker::Internal> { +- fn correct_all_childrens_parent_links(&mut self) { ++ unsafe fn relink_all<'b>(&'b mut self) ++ { + let len = self.len(); + // ignore-tidy-undocumented-unsafe +- unsafe { self.correct_childrens_parent_links(0..=len) }; ++ unsafe { self.relink_inclusive(0..=len) }; + } + } +@@ -60,5 +63,5 @@ + + impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +- pub(super) fn merge_tracking_child_edge( ++ pub(super) fn compare_merge_tracking_child_edge( + self, + track_edge_idx: LeftOrRight, +@@ -82,5 +85,5 @@ + + impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +- pub(super) fn steal_left( ++ pub(super) fn compare_steal_left( + mut self, + track_right_edge_idx: usize, +@@ -91,5 +94,5 @@ + } + +- pub(super) fn steal_right( ++ pub(super) fn compare_steal_right( + mut self, + track_left_edge_idx: usize, +--- a/verified/operations.rs ++++ b/verified/operations.rs +@@ -5318,5 +5318,5 @@ + //@ on_unwind_ens false; + { +- unsafe { debug_assert!(idx <= node.len()) }; ++ unsafe { debug_assert!(idx <= node.merge_len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); +@@ -5331,5 +5331,5 @@ + //@ on_unwind_ens false; + { +- unsafe { debug_assert!(idx < node.len()) }; ++ unsafe { debug_assert!(idx < node.merge_len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); +@@ -6462,5 +6462,5 @@ + //@ close exists(parent); + //@ close exists(child); +- unsafe { repair_one__VeriFast_wrapper/*@::@*/(self, i) }; ++ unsafe { repair_one/*@::@*/(self, i) }; + //@ append_linked_header(prefix, child, parent, first); + //@ append_assoc(prefix, [child], remaining); +@@ -6538,5 +6538,5 @@ + //@ close exists(parent); + //@ close exists(child); +- unsafe { repair_one__VeriFast_wrapper/*@::@*/(self, i) }; ++ unsafe { repair_one/*@::@*/(self, i) }; + //@ append_linked_header(prefix, child, parent, first); + //@ append_assoc(prefix, [child], remaining); +--- a/verified/loop_regions.rs ++++ b/verified/loop_regions.rs +@@ -77,5 +77,5 @@ + //@ close_points_to(&split, 1/2); + unsafe { +- install_root_split/*@::@*/(root_slot, allocator, original_root, key, value, sibling); ++ install_root_split__VeriFast_wrapper/*@::@*/(root_slot, allocator, original_root, key, value, sibling); + inserted.awaken/*@::@*/() + } +@@ -108,7 +108,7 @@ + //@ close exists(parent); + //@ close exists(child); +- unsafe { Handle::new_relink_edge/*@::,K,V,marker::Internal>@*/( +- node.relink_reborrow/*@::,K,V,marker::Internal,'b>@*/(), i +- ).correct_parent_link/*@::<'b,K,V>@*/() }; ++ unsafe { Handle::new_edge( ++ node.reborrow_mut(), i ++ ).correct_parent_link() }; + } + +@@ -170,5 +170,5 @@ + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); +- unsafe { debug_assert!(i <= self.relink_len()) }; ++ unsafe { debug_assert!(i <= self.len()) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self,_); +@@ -246,5 +246,5 @@ + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); +- unsafe { debug_assert!(i <= self.relink_len()) }; ++ unsafe { debug_assert!(i <= self.len()) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self,_); +@@ -266,5 +266,5 @@ + + impl<'a, K, V> NodeRef, K, V, marker::Internal> { +- unsafe fn correct_all_childrens_parent_links<'b>(&'b mut self) ++ unsafe fn relink_all<'b>(&'b mut self) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& +@@ -288,5 +288,5 @@ + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); +- let len = unsafe { self.relink_len() }; ++ let len = unsafe { self.len() }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self, _); +--- a/portable/node.rs ++++ b/portable/node.rs +@@ -40,5 +40,4 @@ + use core::slice::SliceIndex; + +-use safety::{ensures, requires}; + + use crate::alloc::{Allocator, AllocatorClone, Layout}; +@@ -77,7 +76,4 @@ + /// + /// The caller must ensure that `this` points to a (possibly uninitialized) `LeafNode` +- #[requires(core::ub_checks::can_write(this))] +- #[ensures(|_| unsafe { (*this).parent.is_none() })] +- #[ensures(|_| unsafe { (*this).len == 0 })] + #[cfg_attr(kani, kani::modifies(this))] + unsafe fn init(this: *mut Self) { +@@ -335,18 +331,4 @@ + /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should + /// both, upon success, do nothing. +- #[requires(verify::can_ascend(&self))] +- #[ensures(|result| { +- let original_node = old(self.node); +- let original_height = old(self.height); +- match (old(verify::ascend_link(&self)), result) { +- (Some((parent, idx)), Ok(edge)) => { +- edge.node.node == parent.cast() +- && edge.node.height == original_height + 1 +- && edge.idx == idx +- } +- (None, Err(root)) => root.node == original_node && root.height == original_height, +- _ => false, +- } +- })] + pub(super) fn ascend( + self, +@@ -1078,8 +1060,4 @@ + /// Fixes the parent pointer and index in the child node that this edge + /// links to. This is useful when the ordering of edges has been changed, +- #[requires(verify::can_relink(&self.node, self.idx))] +- #[ensures(|_| verify::has_parent_link( +- old(verify::relink_child(&self.node, self.idx)), old(self.node.node.cast()), old(self.idx), +- ))] + #[cfg_attr(kani, kani::modifies( + unsafe { &raw mut (*verify::relink_child(&self.node, self.idx)).parent }, +@@ -1335,9 +1313,4 @@ + /// Helps implementations of `split` for a particular `NodeType`, + /// by taking care of leaf data. +- #[requires(verify::can_split_leaf_data(&self.node, self.idx, new_node))] +- #[ensures(|_| { +- self.node.len() == old(self.idx) +- && usize::from(new_node.len) == old(self.node.len() - self.idx - 1) +- })] + #[cfg_attr(kani, kani::modifies( + unsafe { &raw mut (*NodeRef::as_leaf_ptr(&self.node)).len }, +@@ -1966,5 +1939,4 @@ + /// # Safety + /// The slice has more than `idx` elements. +-#[requires(idx < slice.len())] + #[cfg_attr(kani, kani::modifies(ptr::slice_from_raw_parts_mut( + unsafe { slice.as_mut_ptr().add(idx) }, +@@ -2028,5 +2000,4 @@ + /// of uninitialized elements, leaving behind `src` as all uninitialized. + /// Works like `dst.copy_from_slice(src)` but does not require `T` to be `Copy`. +-#[requires(src.len() == dst.len())] + #[cfg_attr(kani, kani::modifies(dst))] + fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) { +--- a/portable/mem.rs ++++ b/portable/mem.rs +@@ -1,3 +1,3 @@ +-use core::{intrinsics, mem, ptr}; ++use core::{mem, ptr}; + + /// This replaces the value behind the `v` unique reference by calling the +@@ -20,5 +20,5 @@ + impl Drop for PanicGuard { + fn drop(&mut self) { +- intrinsics::abort_immediate() ++ std::process::abort() + } + } +--- a/verified/backlinks.rs ++++ b/verified/backlinks.rs +@@ -1,3 +1,2 @@ +-#![feature(allocator_ext)] + //! Ancestor ownership and the key, value, and child moves used during splitting. + //! Refinement checks the production `as_leaf_ptr` and `set_parent_link`. +@@ -70,5 +69,4 @@ + pub(crate) enum DormantMut {} + pub(crate) enum Owned {} +- pub(crate) enum Dying {} + pub(crate) enum Leaf {} + pub(crate) enum Internal {} +--- a/original/backlinks.rs.in ++++ b/original/backlinks.rs.in +@@ -1,3 +1,2 @@ +-#![feature(allocator_ext)] + //! Ancestor ownership and the key, value, and child moves used during splitting. + //! Refinement checks the production `as_leaf_ptr` and `set_parent_link`. +@@ -70,5 +69,4 @@ + pub(crate) enum DormantMut {} + pub(crate) enum Owned {} +- pub(crate) enum Dying {} + pub(crate) enum Leaf {} + pub(crate) enum Internal {} +@@ -352,38 +350,10 @@ + } + +-// BEGIN_BACKLINK_METHODS + impl NodeRef { +- unsafe fn as_leaf_ptr(this: &Self) -> *mut LeafNode +-/*@ +- req [?f](*this |-> ?node_ref); +- @*/ +- /*@ +- ens [f](*this |-> node_ref) &*& result == node_ref.node.as_ptr(); +- @*/ +- //@ on_unwind_ens false; +- { +- //@ open_points_to(this); +- let ptr = this.node.as_ptr(); +- //@ close_points_to(this, f); +- ptr +- } ++// SOURCE fn as_leaf_ptr(this: &Self) -> *mut LeafNode { + } + + impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { +- unsafe fn set_parent_link(&mut self, parent: NonNull>, parent_idx: usize) +- //@ req *self |-> ?node_ref &*& (*node_ref.node.as_ptr()).parent |-> _ &*& (*node_ref.node.as_ptr()).parent_idx |-> _ &*& parent_idx <= CAPACITY; +- //@ ens *self |-> node_ref &*& (*node_ref.node.as_ptr()).parent |-> Option::Some(parent) &*& (*node_ref.node.as_ptr()).parent_idx |-> MaybeUninit::new(parent_idx as u16); +- //@ on_unwind_ens false; +- { +- //@ let view = precreate_ref(self); +- //@ init_ref_readonly(view, 1/2); +- let leaf = unsafe { Self::as_leaf_ptr(self) }; +- //@ end_ref_readonly(view); +- //@ merge_fractions points_to(self, _); +- unsafe { (*leaf).parent = Some(parent) }; +- //@ open LeafNode_parent_idx_(leaf, _); +- //@ points_to__limits(&(*leaf).parent_idx); +- unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; +- } ++// SOURCE fn set_parent_link(&mut self, parent: NonNull>, parent_idx: usize) { + } + +--- a/verified/root-level-body.rs ++++ b/verified/root-level-body.rs +@@ -1,14 +1,4 @@ + // BEGIN_ROOT_INSTALL +- let borrowed_root = unsafe { root_slot.reborrow() }; +- let root_payload = borrowed_root.as_mut().unwrap(); +- let root_allocator = unsafe { clone_allocator(allocator) }; +- let old = unsafe { ptr::read(root_payload) }; +- let new = unsafe { +- NodeRef::::new_internal_production(old,root_allocator).forget_type() +- }; +- unsafe { ptr::write(root_payload,new) }; +- let mut view = NodeRef::,K,V,marker::Internal> { +- height: root_payload.height, node: root_payload.node, _marker: PhantomData +- }; +- unsafe { view.push_production(key,value,right) }; //~track_ref_creation ++ super::mem::take_mut(self, |old_root| NodeRef::new_internal(old_root, alloc).forget_type()); ++ NodeRef { height: self.height, node: self.node, _marker: PhantomData } + // END_ROOT_INSTALL +--- a/verified/ascend-body.rs ++++ b/verified/ascend-body.rs +@@ -1,35 +1,18 @@ + // BEGIN_ASCEND +- let leaf_ptr: *const _ = unsafe { Self::as_leaf_ptr(&self) }; +- let height = self.height; +- let node = self.node; +- let successor = unsafe { open_next_parent(leaf_ptr) }; +- let result = match successor { +- None => None, +- Some((parent, observed_index)) => { +- let parent_height = height + 1; +- Some(Handle { +- node: unsafe { NodeRef::from_internal(parent, parent_height) }, +- idx: observed_index as usize, +- _marker: PhantomData, +- }) +- } +- }; +- result.ok_or(NodeRef { height, node, _marker: PhantomData }) ++ const { ++ assert!(BorrowType::TRAVERSAL_PERMIT); ++ } ++ let leaf_ptr: *const _ = Self::as_leaf_ptr(&self); ++ unsafe { (*leaf_ptr).parent } ++ .as_ref() ++ .map(|parent| Handle { ++ node: NodeRef::from_internal(*parent, self.height + 1), ++ idx: unsafe { usize::from((*leaf_ptr).parent_idx.assume_init()) }, ++ _marker: PhantomData, ++ }) ++ .ok_or(self) + // END_ASCEND + // BEGIN_FROM_INTERNAL + debug_assert!(height > 0); +- let leaf = unsafe { NonNull::new_unchecked(node.as_ptr() as *mut LeafNode) }; +- NodeRef { height, node: leaf, _marker: PhantomData } ++ NodeRef { height, node: node.cast(), _marker: PhantomData } + // END_FROM_INTERNAL +-// BEGIN_OPEN_NEXT_PARENT +- let backlink = unsafe { (*child).parent }; +- match backlink { +- None => { +- None +- } +- Some(parent) => { +- let observed_index = unsafe { *((&raw const (*child).parent_idx) as *const u16) }; +- Some((parent, observed_index)) +- } +- } +-// END_OPEN_NEXT_PARENT +--- a/verified/drop-bodies.rs ++++ b/verified/drop-bodies.rs +@@ -1,69 +1,43 @@ + // body drop_kvs +-// unsafe fn drop_remaining< +- let count = unsafe { (*node).len() }; +- let mut iter = (start..count).into_iter(); +- loop { +- let iter_ref = &mut iter; +- let next = iter_ref.next(); +- match next { +- None => break, +- Some(i) => unsafe { drop_at(node, i) }, ++ struct DropGuard<'a, K, V> { ++ node: &'a NodeRef, ++ idx: usize, ++ } ++ impl<'a, K, V> Drop for DropGuard<'a, K, V> { ++ fn drop(&mut self) { ++ let len = self.node.len(); ++ for i in self.idx..len { ++ unsafe { ++ let kv = Handle::new_kv(ptr::read(self.node), i); ++ kv.drop_key_val(); ++ } ++ } ++ } ++ } ++ let len = self.len(); ++ for idx in 0..len { ++ let guard = DropGuard { node: self, idx: idx + 1 }; ++ unsafe { ++ let kv = Handle::new_kv(ptr::read(self), idx); ++ kv.drop_key_val(); + } ++ core::mem::forget(guard); + } +-// unsafe fn drop_at< +- let kv = unsafe { Handle::new_dying_kv(duplicate_dying(node), index) }; +- unsafe { kv.drop_key_val_step() }; +-// unsafe fn duplicate_dying< +- let duplicated = unsafe { std::ptr::read(node) }; +- duplicated +-// unsafe fn new_dying_kv( +- unsafe { debug_assert!(idx < node.len()) }; +- let result = Handle { node, idx, _marker: PhantomData }; +- result +-// unsafe fn resume_drop_remaining< +- unsafe { finish_drop_value(value, pending) }; +- unsafe { drop_remaining(node, index + 1) }; + // body drop_key_val +-// unsafe fn finish_drop_value< +- if pending { +- unsafe { drop_guarded_value(value) }; ++ struct Dropper<'a, T>(&'a mut MaybeUninit); ++ impl Drop for Dropper<'_, T> { ++ #[inline] ++ fn drop(&mut self) { ++ unsafe { ++ self.0.assume_init_drop(); ++ } ++ } ++ } ++ debug_assert!(self.idx < self.node.len()); ++ let leaf = self.node.as_leaf_dying(); ++ unsafe { ++ let key = leaf.keys.get_unchecked_mut(self.idx); ++ let val = leaf.vals.get_unchecked_mut(self.idx); ++ let _guard = Dropper(val); ++ key.assume_init_drop(); + } +-// unsafe fn drop_key_val_step( +- let (key_slot,value_slot) = self.project_drop_slots(); +- unsafe { drop_pair(key_slot,value_slot) }; +-// unsafe fn project_drop_slots< +- debug_assert!(self.idx < self.node.merge_len()); +- let leaf = unsafe { self.node.as_leaf_dying() }; //~track_ref_creation +- let key_slot = +- <[MaybeUninit]>::get_unchecked_mut( +- { +- let key_array = &mut leaf.keys; //~track_ref_creation +- let slice: &mut [MaybeUninit] = key_array; +- slice +- }, +- self.idx, +- ); +- let val_slot = +- <[MaybeUninit]>::get_unchecked_mut( +- { +- let val_array = &mut leaf.vals; //~track_ref_creation +- let slice: &mut [MaybeUninit] = val_array; +- slice +- }, +- self.idx, +- ); +- (key_slot, val_slot) +-// unsafe fn drop_pair< +- unsafe { drop_initialized_slot(key) }; +- unsafe { drop_guarded_value(value) }; +-// unsafe fn drop_initialized_slot< +- unsafe { drop_slot_production(&mut *slot) } +-// unsafe fn drop_guarded_value< +- let mut guard = Dropper(unsafe { &mut *slot }); +- unsafe { guard.drop_value_guard() }; +-// unsafe fn drop_value_guard( +- let slot = &mut *self.0; +- unsafe { drop_slot_production(slot) }; +-// unsafe fn drop_slot_production< +- let ptr = slot.as_mut_ptr(); +- unsafe { std::ptr::drop_in_place(ptr) } diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0001-refinement-raw-ptr.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0001-refinement-raw-ptr.patch new file mode 100644 index 0000000000000..a9b1c74f94c07 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0001-refinement-raw-ptr.patch @@ -0,0 +1,189 @@ +diff --git a/src/refinement_checker/refinement_checker.ml b/src/refinement_checker/refinement_checker.ml +index 77c3c28..cf2a08f 100644 +--- a/src/refinement_checker/refinement_checker.ml ++++ b/src/refinement_checker/refinement_checker.ml +@@ -1910,10 +1910,13 @@ let rec process_commands bodies (env: env) opnds (i_bb: basic_block_info) i_s (s + | Aggregate (Closure _, n) -> + let vs, opnds = popn n opnds in + cont env (Closure vs::opnds) +- | RawPtr raw_ptr_data -> +- begin match raw_ptr_data.place.projection with ++ | RawPtr {kind; place} ++ when kind = FakeForPtrMetadata || (kind = RawMut && place.kind = MutableRef) -> ++ (* Keep the existing reference-to-pointer coercion used in reservation ++ lowering. Match other raw borrows with their kind and place intact. *) ++ begin match place.projection with + [Deref] -> +- let placeLocalPath = {lv_caller=i_bb#id.bb_caller; lv_name=raw_ptr_data.place.local.name} in ++ let placeLocalPath = {lv_caller=i_bb#id.bb_caller; lv_name=place.local.name} in + begin match List.assoc placeLocalPath env with + Value placeValue -> + cont env (placeValue::opnds) +@@ -2655,7 +2658,18 @@ let check_body_refines_body bodies0 bodies1 def_path body0 body1 = + let v = fresh_symbol () in + cont env0 (v::opnds0) env1 (v::opnds1) + end +- | RawPtr raw_ptr_data_cpn0, RawPtr raw_ptr_data_cpn1 -> error "RawPtr: not yet supported" ++ | RawPtr raw0, RawPtr raw1 -> ++ if raw0.kind = Unknown || raw1.kind = Unknown then ++ error "RawPtr: The exporter did not provide the raw pointer kind"; ++ if raw0.kind <> raw1.kind || raw0.mutability <> raw1.mutability then ++ error "RawPtr: The pointer kinds do not match"; ++ begin match check_place_refines_place env0 caller0 raw0.place env1 caller1 raw1.place with ++ (Local x0, Local x1) | (LocalProjection x0, LocalProjection x1) -> ++ local_address_taken x0 x1 ++ | Nonlocal, Nonlocal -> ++ let address = fresh_symbol () in ++ cont env0 (address::opnds0) env1 (address::opnds1) ++ end + | Cast ty0, Cast ty1 -> + let v, opnds0, opnds1 = consume_operand opnds0 opnds1 in + if decode_ty i_bb0#genv ty0 <> decode_ty i_bb1#genv ty1 then +diff --git a/src/rust_frontend/vf_mir/vf_mir.capnp b/src/rust_frontend/vf_mir/vf_mir.capnp +index 9e81d09..e31f8fb 100644 +--- a/src/rust_frontend/vf_mir/vf_mir.capnp ++++ b/src/rust_frontend/vf_mir/vf_mir.capnp +@@ -618,9 +618,17 @@ struct Rvalue { + count @1: TyConst; + } + ++ enum RawPtrKind { ++ unknown @0; ++ rawConst @1; ++ rawMut @2; ++ fakeForPtrMetadata @3; ++ } ++ + struct RawPtrData { + mutability @0: Mutability; + place @1: Place; ++ kind @2: RawPtrKind; + } + + struct BinaryOpData { +diff --git a/src/rust_frontend/vf_mir_exporter/src/lib.rs b/src/rust_frontend/vf_mir_exporter/src/lib.rs +index 9621ba9..8306e22 100644 +--- a/src/rust_frontend/vf_mir_exporter/src/lib.rs ++++ b/src/rust_frontend/vf_mir_exporter/src/lib.rs +@@ -2261,6 +2261,11 @@ use rustc_span::RemapPathScopeComponents; + mir::Rvalue::ThreadLocalRef(def_id) => rvalue_cpn.set_thread_local_ref(()), + mir::Rvalue::RawPtr(raw_ptr_kind, place) => { + let mut raw_ptr_data_cpn = rvalue_cpn.init_raw_ptr(); ++ raw_ptr_data_cpn.set_kind(match raw_ptr_kind { ++ mir::RawPtrKind::Const => rvalue_cpn::RawPtrKind::RawConst, ++ mir::RawPtrKind::Mut => rvalue_cpn::RawPtrKind::RawMut, ++ mir::RawPtrKind::FakeForPtrMetadata => rvalue_cpn::RawPtrKind::FakeForPtrMetadata, ++ }); + let mutability_cpn = raw_ptr_data_cpn.reborrow().init_mutability(); + Self::encode_mutability(match raw_ptr_kind { + mir::RawPtrKind::Mut => mir::Mutability::Mut, +diff --git a/tests/rust/refinement_checker/raw-pointer_orig.rs b/tests/rust/refinement_checker/raw-pointer_orig.rs +new file mode 100644 +index 0000000..aee9572 +--- /dev/null ++++ b/tests/rust/refinement_checker/raw-pointer_orig.rs +@@ -0,0 +1,17 @@ ++#[repr(C)] ++struct Pair { ++ left: i32, ++ right: i32, ++} ++ ++unsafe fn field_addr(pair: *mut Pair) -> usize { ++ let field = unsafe { &raw mut (*pair).left }; ++ field as usize ++} ++ ++fn local_addr() -> i32 { ++ let mut value = 1; ++ let ptr = &raw mut value; ++ unsafe { *ptr = 2 }; ++ value ++} +diff --git a/tests/rust/refinement_checker/raw-pointer_verified.rs b/tests/rust/refinement_checker/raw-pointer_verified.rs +new file mode 100644 +index 0000000..cd5a6d6 +--- /dev/null ++++ b/tests/rust/refinement_checker/raw-pointer_verified.rs +@@ -0,0 +1,19 @@ ++#[repr(C)] ++struct Pair { ++ left: i32, ++ right: i32, ++} ++ ++unsafe fn field_addr(pair: *mut Pair) -> usize { ++ //@ assert true; ++ let field = unsafe { &raw mut (*pair).left }; ++ field as usize ++} ++ ++fn local_addr() -> i32 { ++ let mut value = 1; ++ //@ assert true; ++ let ptr = &raw mut value; ++ unsafe { *ptr = 2 }; ++ value ++} +diff --git a/tests/rust/refinement_checker/raw-pointer_verified_bad_field.rs b/tests/rust/refinement_checker/raw-pointer_verified_bad_field.rs +new file mode 100644 +index 0000000..040a603 +--- /dev/null ++++ b/tests/rust/refinement_checker/raw-pointer_verified_bad_field.rs +@@ -0,0 +1,19 @@ ++#[repr(C)] ++struct Pair { ++ left: i32, ++ right: i32, ++} ++ ++unsafe fn field_addr(pair: *mut Pair) -> usize { ++ //@ assert true; ++ let field = unsafe { &raw mut (*pair).right }; ++ field as usize ++} ++ ++fn local_addr() -> i32 { ++ let mut value = 1; ++ //@ assert true; ++ let ptr = &raw mut value; ++ unsafe { *ptr = 2 }; ++ value ++} +diff --git a/tests/rust/refinement_checker/raw-pointer_verified_bad_kind.rs b/tests/rust/refinement_checker/raw-pointer_verified_bad_kind.rs +new file mode 100644 +index 0000000..7363a33 +--- /dev/null ++++ b/tests/rust/refinement_checker/raw-pointer_verified_bad_kind.rs +@@ -0,0 +1,19 @@ ++#[repr(C)] ++struct Pair { ++ left: i32, ++ right: i32, ++} ++ ++unsafe fn field_addr(pair: *mut Pair) -> usize { ++ //@ assert true; ++ let field = unsafe { &raw const (*pair).left }; ++ field as usize ++} ++ ++fn local_addr() -> i32 { ++ let mut value = 1; ++ //@ assert true; ++ let ptr = &raw mut value; ++ unsafe { *ptr = 2 }; ++ value ++} +diff --git a/tests/rust/refinement_checker/testsuite.mysh b/tests/rust/refinement_checker/testsuite.mysh +index ec62e86..56a5b63 100644 +--- a/tests/rust/refinement_checker/testsuite.mysh ++++ b/tests/rust/refinement_checker/testsuite.mysh +@@ -42,4 +42,7 @@ begin_parallel + refinement-checker result-map_orig.rs result-map_verified.rs + refinement-checker result-map_err_orig.rs result-map_err_verified.rs + refinement-checker override-local-mut_orig.rs override-local-mut_verified.rs ++ refinement-checker raw-pointer_orig.rs raw-pointer_verified.rs ++ !refinement-checker raw-pointer_orig.rs raw-pointer_verified_bad_field.rs ++ !refinement-checker raw-pointer_orig.rs raw-pointer_verified_bad_kind.rs + end_parallel diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0002-rust-box-deref-unwind.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0002-rust-box-deref-unwind.patch new file mode 100644 index 0000000000000..356df7f93cd35 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0002-rust-box-deref-unwind.patch @@ -0,0 +1,62 @@ +diff --git a/bin/rust/std/lib.rsspec b/bin/rust/std/lib.rsspec +index a5d925d..2696613 100644 +--- a/bin/rust/std/lib.rsspec ++++ b/bin/rust/std/lib.rsspec +@@ -1453,6 +1453,7 @@ mod boxed { + fn as_mut_ptr<'a>(self: &'a mut Box) -> *mut T; + //@ req Box_minus_contents_in(?f, ?t, ?fs, self, ?alloc_id, ?contents_ptr); + //@ ens Box_minus_contents_in(f, t, fs, self, alloc_id, contents_ptr) &*& result == contents_ptr; ++ //@ on_unwind_ens false; + + } + +diff --git a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +index 4e237a6..7e36cfc 100644 +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -3372,7 +3372,7 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + [ LitPat (AddressOf (loc, Var (loc, id))) ], + Static )) + in +- Ok (`TrRvalueExpr e) ++ Ok (`TrRvalueExpr (result_of_outcome loc e)) + | _ -> + let* ty_info = translate_decoded_ty cast_data.ty loc in + let ty = ty_info.vf_ty in +diff --git a/tests/rust/purely_unsafe/box_projection.rs b/tests/rust/purely_unsafe/box_projection.rs +new file mode 100644 +index 0000000..498688e +--- /dev/null ++++ b/tests/rust/purely_unsafe/box_projection.rs +@@ -0,0 +1,19 @@ ++unsafe fn replace_box_contents(mut owner: Box, value: i32) -> Box ++/*@ ++req thread_token(?t) &*& std::boxed::Box_in(t, owner, ?id, _) &*& ++ exists::(?k) &*& [?q]lifetime_token(k) &*& lifetime_inclusion(k,id.lft) == true; ++@*/ ++//@ ens thread_token(t) &*& std::boxed::Box_in(t, result, id, value) &*& [q]lifetime_token(k); ++//@ on_unwind_ens false; ++{ ++ //@ open exists(k); ++ //@ let contents = std::boxed::Box_separate_contents(&mut owner); ++ //@ let traded = lifetime_token_trade(k, q, id.lft); ++ //@ open_points_to_at_lft(contents, traded); ++ //@ points_to_limits(contents); ++ *owner = value; ++ //@ close_points_to_at_lft(contents); ++ //@ lifetime_token_trade_back(traded, id.lft); ++ //@ std::boxed::Box_unseparate_contents(&mut owner); ++ owner ++} +diff --git a/tests/rust/testsuite.mysh b/tests/rust/testsuite.mysh +index 3c5ed1d..0de6dbd 100644 +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -36,6 +36,7 @@ cd purely_unsafe + verifast enum_discr.rs + verifast -ignore_unwind_paths leftpad.rs + verifast arrays.rs ++ verifast -skip_specless_fns box_projection.rs + verifast -allow_assume std_thread.rs + verifast -allow_should_fail -allow_dead_code nonmut_let_immut.rs + verifast struct_exprs.rs diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0003-rust-fixed-array-index.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0003-rust-fixed-array-index.patch new file mode 100644 index 0000000000000..43c1bfb6b4719 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0003-rust-fixed-array-index.patch @@ -0,0 +1,326 @@ +diff --git a/src/refinement_checker/refinement_checker.ml b/src/refinement_checker/refinement_checker.ml +index cf2a08f..6c582f2 100644 +--- a/src/refinement_checker/refinement_checker.ml ++++ b/src/refinement_checker/refinement_checker.ml +@@ -362,7 +362,11 @@ let string_of_local_var_state = function + + let eval_mir_const genv mir_const_cpn = + match mir_const_cpn with +- Ty mir_ty_const_cpn -> failwith "Using typesystem constant expressions as MIR constant operands is not yet supported" ++ Ty {const; _} -> ++ begin match decode_const_expr genv const with ++ LiteralConstExpr literal -> ScalarInt literal ++ | ParamConstExpr _ -> failwith "Symbolic typesystem constant as a MIR operand is not yet supported" ++ end + | Val mir_val_const_cpn -> + let ty = decode_ty genv mir_val_const_cpn.ty in + let mir_const_value_cpn = mir_val_const_cpn.const_value in +@@ -1599,6 +1603,7 @@ type command = + | LoadLocal of local_decl_id (* Push the value of the specified local variable onto the operand stack *) + | Deref (* Pop a value from the top of the operand stack, which is an address, and push the value at that address *) + | Field of int (* Pop a value from the top of the operand stack, which is an aggregate value, and push the specified field of the aggregate value *) ++| ReadArrayElement of Vf_mir_decoder.ty + | BoxAsPtr (* Pop a value from the top of the operand stack, which is a Box, and push a pointer to the contents of the Box *) + | Downcast of int (* Pop a value from the top of the operand stack, which is an enum value, and push the specified variant of the enum value *) + | Constant of const_operand (* Push a constant operand onto the operand stack *) +@@ -1621,6 +1626,7 @@ let string_of_command c = + | LoadLocal {name} -> Printf.sprintf "LoadLocal %s" name + | Deref -> "Deref" + | Field i -> Printf.sprintf "Field %d" i ++ | ReadArrayElement _ -> "ReadArrayElement" + | BoxAsPtr -> "BoxAsPtr" + | Downcast i -> Printf.sprintf "Downcast %d" i + | Constant {const} -> Printf.sprintf "Constant %s" (string_of_mir_const const) +@@ -1637,10 +1643,12 @@ let string_of_command c = + + let commands_for_loading_place {local; projection}: command list = + let proj_cmds = +- projection |> List.map @@ function +- (Deref: place_elem) -> (Deref: command) +- | Field {index} -> Field (Stdint.Uint32.to_int index) +- | Downcast index -> Downcast (Stdint.Uint32.to_int index) ++ projection |> List.concat_map @@ function ++ (Deref: place_elem) -> [(Deref: command)] ++ | Field {index} -> [Field (Stdint.Uint32.to_int index)] ++ | Downcast index -> [Downcast (Stdint.Uint32.to_int index)] ++ | ArrayIndex {index_local; elem_ty} -> [LoadLocal index_local; ReadArrayElement elem_ty] ++ | _ -> failwith "Unsupported projection when loading a place" + in + LoadLocal local::proj_cmds + +@@ -1965,6 +1973,8 @@ let check_place_element_refines_place_element (elem0: place_elem) (elem1: place_ + if fieldIndex0 <> fieldIndex1 then failwith "Field indices do not match" + | BoxAsNonNull _, BoxAsNonNull _ -> () + | Index, Index -> failwith "PlaceElement::Index not supported" ++ | ArrayIndex index0, ArrayIndex index1 -> ++ if index0.elem_ty <> index1.elem_ty then failwith "Array element types do not match" + | ConstantIndex, ConstantIndex -> failwith "PlaceElement::ConstantIndex not supported" + | Subslice, Subslice -> failwith "PlaceElement::Subslice not supported" + | Downcast variant_idx0, Downcast variant_idx1 -> +@@ -1993,7 +2003,17 @@ let check_place_refines_place (env0: env) caller0 place0 (env1: env) caller1 pla + let placeProjection1 = place1.projection in + if List.length placeProjection0 <> List.length placeProjection1 then + failwith "The two place expressions have a different number of projection elements"; +- List.iter2 check_place_element_refines_place_element placeProjection0 placeProjection1; ++ List.iter2 (fun elem0 elem1 -> ++ check_place_element_refines_place_element elem0 elem1; ++ match elem0, elem1 with ++ ArrayIndex index0, ArrayIndex index1 -> ++ let path0 = {lv_caller=caller0; lv_name=index0.index_local.name} in ++ let path1 = {lv_caller=caller1; lv_name=index1.index_local.name} in ++ begin match List.assoc_opt path0 env0, List.assoc_opt path1 env1 with ++ Some (Value v0), Some (Value v1) when values_equal env0 env1 v0 v1 -> () ++ | _ -> failwith "Array indices do not match" ++ end ++ | _ -> ()) placeProjection0 placeProjection1; + match placeLocalState0, placeLocalState1 with + Some (Address a1), Some (Address a2) -> + if not (values_equal env0 env1 a1 a2) then failwith "The addresses of the two places are not equal"; +@@ -2636,6 +2656,12 @@ let check_body_refines_body bodies0 bodies1 def_path body0 body1 = + let v, opnds0, opnds1 = consume_operand opnds0 opnds1 in + let v = fresh_symbol () in + cont env0 (v::opnds0) env1 (v::opnds1) ++ | ReadArrayElement ty0, ReadArrayElement ty1 -> ++ if decode_ty i_bb0#genv ty0 <> decode_ty i_bb1#genv ty1 then ++ error "ReadArrayElement: The element types do not match"; ++ let _, opnds0, opnds1 = consume_operands 2 opnds0 opnds1 in ++ let v = fresh_symbol () in ++ cont env0 (v::opnds0) env1 (v::opnds1) + | BoxAsPtr, BoxAsPtr -> + let v, opnds0, opnds1 = consume_operand opnds0 opnds1 in + let v = fresh_symbol () in +diff --git a/src/refinement_checker/stringifier.ml b/src/refinement_checker/stringifier.ml +index 17b4917..fa103d7 100644 +--- a/src/refinement_checker/stringifier.ml ++++ b/src/refinement_checker/stringifier.ml +@@ -26,6 +26,8 @@ let string_of_place {local; projection; local_is_mutable} = + iter (Printf.sprintf "box_as_NonNull(%s)" inner) rest + | Index::rest -> + iter (Printf.sprintf "%s[?]" inner) rest ++ | ArrayIndex {index_local}::rest -> ++ iter (Printf.sprintf "%s[%s]" inner index_local.name) rest + | ConstantIndex::rest -> + iter (Printf.sprintf "%s[constant ?]" inner) rest + | Subslice::rest -> +diff --git a/src/rust_frontend/vf_mir/vf_mir.capnp b/src/rust_frontend/vf_mir/vf_mir.capnp +index e31f8fb..6283a6e 100644 +--- a/src/rust_frontend/vf_mir/vf_mir.capnp ++++ b/src/rust_frontend/vf_mir/vf_mir.capnp +@@ -451,6 +451,10 @@ struct PlaceElem { + name @1: Option(Symbol); + ty @2: Ty; + } ++ struct ArrayIndexData { ++ indexLocal @0: LocalDeclId; ++ elemTy @1: Ty; ++ } + union { + deref @0: Void; + field @1: FieldData; +@@ -460,6 +464,7 @@ struct PlaceElem { + subslice @5: Void; + downcast @2: UInt32; + opaqueCast @6: Void; ++ arrayIndex @8: ArrayIndexData; + } + } + +diff --git a/src/rust_frontend/vf_mir_exporter/src/lib.rs b/src/rust_frontend/vf_mir_exporter/src/lib.rs +index 8306e22..ef0ba83 100644 +--- a/src/rust_frontend/vf_mir_exporter/src/lib.rs ++++ b/src/rust_frontend/vf_mir_exporter/src/lib.rs +@@ -2982,8 +2982,14 @@ use rustc_span::RemapPathScopeComponents; + */ + PlaceKind::Other + } +- mir::ProjectionElem::Index(_) => { +- place_elm_cpn.set_index(()); ++ mir::ProjectionElem::Index(index) => { ++ if let ty::TyKind::Array(elem_ty, _) = ty.kind() { ++ let mut data = place_elm_cpn.init_array_index(); ++ Self::encode_local_decl_id(*index, data.reborrow().init_index_local()); ++ Self::encode_ty(enc_ctx.tcx, enc_ctx, *elem_ty, data.init_elem_ty()); ++ } else { ++ place_elm_cpn.set_index(()); ++ } + PlaceKind::Other + } + mir::ProjectionElem::ConstantIndex{ .. } => { +diff --git a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +index 7e36cfc..666b69e 100644 +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -2039,10 +2039,11 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + type place_element = + | Deref + | Field of string option * int ++ | ArrayIndex of string * Ast.type_expr + | Downcast of int + | BoxAsNonNull + +- let decode_place_element (place_elm : PlaceElementRd.t) : place_element = ++ let decode_place_element loc (place_elm : PlaceElementRd.t) : place_element = + let open PlaceElementRd in + match get place_elm with + | Deref -> +@@ -2062,7 +2063,17 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + Some (SymbolRd.name_get (VfMirRd.of_pointer name_cpn)) + in + Field (name, Stdint.Uint32.to_int index) ++ | ArrayIndex data -> ++ if Option.is_some TranslatorArgs.rocq_writer.buf then ++ Ast.static_error loc "Array index projections are not yet supported in Rocq output" None; ++ let open ArrayIndexData in ++ let index = translate_local_decl_id (index_local_get data) in ++ begin match translate_ty (elem_ty_get data) loc with ++ | Ok elem_ty -> ArrayIndex (index, elem_ty.vf_ty) ++ | Error _ -> Ast.static_error loc "Unsupported array element type" None ++ end + | Downcast variant_index -> Downcast (Stdint.Uint32.to_int variant_index) ++ | _ -> Ast.static_error loc "Unsupported MIR place projection" None + + let translate_projection (loc : Ast.loc) (elems : place_element list) + (e : Ast.expr) (e_is_mutable : bool) : +@@ -2091,6 +2102,12 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let name = match name with Some name -> name | None -> string_of_int field_idx in + let e1, e1_is_mutable = iter elems in + (Ast.Select (loc, e1, name), e1_is_mutable) ++ | ArrayIndex (index, elem_ty) :: elems -> ++ let array, is_mutable = iter elems in ++ let base = ++ Ast.CastExpr (loc, Ast.PtrTypeExpr (loc, elem_ty), Ast.AddressOf (loc, array)) ++ in ++ (Ast.ReadArray (loc, base, Ast.Var (loc, index)), is_mutable) + | Downcast _ :: _ -> failwith "Not yet supported: Downcast _::_" + | BoxAsNonNull :: _ -> Ast.EmpAsn loc, false (* Dummy result; never used *) + in +@@ -2112,7 +2129,7 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + Rocq_writer.rocq_print_small_list TranslatorArgs.rocq_writer @@ fun () -> + projection_cpn |> List.map @@ fun pe_cpn -> + Rocq_writer.rocq_print_small_list_element TranslatorArgs.rocq_writer @@ fun () -> +- decode_place_element pe_cpn ++ decode_place_element loc pe_cpn + in + Ok + (translate_projection loc (List.rev place_elems) +diff --git a/tests/rust/purely_unsafe/fixed_array_index.rs b/tests/rust/purely_unsafe/fixed_array_index.rs +new file mode 100644 +index 0000000..c9ac59a +--- /dev/null ++++ b/tests/rust/purely_unsafe/fixed_array_index.rs +@@ -0,0 +1,21 @@ ++struct Node { ++ edges: [i32; 12], ++} ++ ++unsafe fn set_edge(node: *mut Node, index: usize, child: i32) ++//@ req index < 12 &*& pointer_within_limits(&(*node).edges) == true &*& *(&(*node).edges as *i32 + index) |-> _; ++//@ ens *(&(*node).edges as *i32 + index) |-> child; ++//@ on_unwind_ens false; ++{ ++ //@ assert index < 12; ++ unsafe { (*node).edges[index] = child }; ++} ++ ++unsafe fn first_edge(node: *const Node) -> i32 ++//@ req pointer_within_limits(&(*node).edges) == true &*& *(&(*node).edges as *i32) |-> ?edge; ++//@ ens *(&(*node).edges as *i32) |-> edge &*& result == edge; ++//@ on_unwind_ens false; ++{ ++ //@ assert 0 < 12; ++ unsafe { (*node).edges[0] } ++} +diff --git a/tests/rust/purely_unsafe/fixed_array_index_bad.rs b/tests/rust/purely_unsafe/fixed_array_index_bad.rs +new file mode 100644 +index 0000000..565a300 +--- /dev/null ++++ b/tests/rust/purely_unsafe/fixed_array_index_bad.rs +@@ -0,0 +1,20 @@ ++struct Node { ++ edges: [i32; 12], ++} ++ ++unsafe fn set_edge(node: *mut Node, index: usize, child: i32) ++//@ req pointer_within_limits(&(*node).edges) == true &*& *(&(*node).edges as *i32 + index) |-> _; ++//@ ens *(&(*node).edges as *i32 + index) |-> child; ++//@ on_unwind_ens false; ++{ ++ unsafe { (*node).edges[index] = child }; ++} ++ ++unsafe fn first_edge(node: *const Node) -> i32 ++//@ req pointer_within_limits(&(*node).edges) == true &*& *(&(*node).edges as *i32) |-> ?edge; ++//@ ens *(&(*node).edges as *i32) |-> edge &*& result == edge; ++//@ on_unwind_ens false; ++{ ++ //@ assert 0 < 12; ++ unsafe { (*node).edges[0] } ++} +diff --git a/tests/rust/refinement_checker/array_index_orig.rs b/tests/rust/refinement_checker/array_index_orig.rs +new file mode 100644 +index 0000000..a29ec13 +--- /dev/null ++++ b/tests/rust/refinement_checker/array_index_orig.rs +@@ -0,0 +1,11 @@ ++struct Node { ++ edges: [i32; 12], ++} ++ ++unsafe fn set_edge(node: *mut Node, index: usize, child: i32) { ++ unsafe { (*node).edges[index] = child }; ++} ++ ++unsafe fn first_edge(node: *const Node) -> i32 { ++ unsafe { (*node).edges[0] } ++} +diff --git a/tests/rust/refinement_checker/array_index_verified_bad.rs b/tests/rust/refinement_checker/array_index_verified_bad.rs +new file mode 100644 +index 0000000..9e282c0 +--- /dev/null ++++ b/tests/rust/refinement_checker/array_index_verified_bad.rs +@@ -0,0 +1,21 @@ ++struct Node { ++ edges: [i32; 12], ++} ++ ++unsafe fn set_edge(node: *mut Node, index: usize, child: i32) ++//@ req index < 12 &*& pointer_within_limits(&(*node).edges) == true &*& *(&(*node).edges as *i32 + index) |-> _; ++//@ ens *(&(*node).edges as *i32 + index) |-> child; ++//@ on_unwind_ens false; ++{ ++ //@ assert index < 12; ++ unsafe { (*node).edges[index] = child }; ++} ++ ++unsafe fn first_edge(node: *const Node) -> i32 ++//@ req pointer_within_limits(&(*node).edges) == true &*& *(&(*node).edges as *i32) |-> ?edge; ++//@ ens *(&(*node).edges as *i32) |-> edge &*& result == edge; ++//@ on_unwind_ens false; ++{ ++ //@ assert 0 < 12; ++ unsafe { (*node).edges[1] } ++} +diff --git a/tests/rust/refinement_checker/testsuite.mysh b/tests/rust/refinement_checker/testsuite.mysh +index 56a5b63..d874e77 100644 +--- a/tests/rust/refinement_checker/testsuite.mysh ++++ b/tests/rust/refinement_checker/testsuite.mysh +@@ -45,4 +45,6 @@ begin_parallel + refinement-checker raw-pointer_orig.rs raw-pointer_verified.rs + !refinement-checker raw-pointer_orig.rs raw-pointer_verified_bad_field.rs + !refinement-checker raw-pointer_orig.rs raw-pointer_verified_bad_kind.rs ++ refinement-checker array_index_orig.rs ../purely_unsafe/fixed_array_index.rs ++ !refinement-checker array_index_orig.rs array_index_verified_bad.rs + end_parallel +diff --git a/tests/rust/testsuite.mysh b/tests/rust/testsuite.mysh +index 0de6dbd..9697d51 100644 +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -36,6 +36,8 @@ cd purely_unsafe + verifast enum_discr.rs + verifast -ignore_unwind_paths leftpad.rs + verifast arrays.rs ++ verifast -skip_specless_fns fixed_array_index.rs ++ !verifast -skip_specless_fns fixed_array_index_bad.rs + verifast -skip_specless_fns box_projection.rs + verifast -allow_assume std_thread.rs + verifast -allow_should_fail -allow_dead_code nonmut_let_immut.rs diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0004-rust-preserve-array-value.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0004-rust-preserve-array-value.patch new file mode 100644 index 0000000000000..635512bf01678 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0004-rust-preserve-array-value.patch @@ -0,0 +1,34 @@ +diff --git a/src/verify_expr.ml b/src/verify_expr.ml +index b26182a..ee42f9e 100644 +--- a/src/verify_expr.ml ++++ b/src/verify_expr.ml +@@ -1792,6 +1792,9 @@ module VerifyExpr(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + in + iter h env (Z.to_int elemCount) es $. fun h env elems -> + produce_array_chunk h env false elemTp addr elems elemCountTerm ++ | _, Term elems when is_rust -> ++ (* Rust array values use the same list as the array chunk. *) ++ produce_array_chunk h env false elemTp addr elems elemCountTerm + | _, MaybeUninitTerm term -> + produce_array_chunk h env true elemTp addr term elemCountTerm + | _ -> +diff --git a/tests/rust/purely_unsafe/arrays.rs b/tests/rust/purely_unsafe/arrays.rs +index da1bc3d..72afcf1 100644 +--- a/tests/rust/purely_unsafe/arrays.rs ++++ b/tests/rust/purely_unsafe/arrays.rs +@@ -59,6 +59,15 @@ unsafe fn test3(xs: *mut [i32; 3]) + //@ array_to_Array(xs); + } + ++unsafe fn keep_array(xs: *mut [i32; 3]) ++//@ req (xs as *i32)[..3] |-> [10, 20, 30]; ++//@ ens (xs as *i32)[..3] |-> [10, 20, 30]; ++//@ on_unwind_ens false; ++{ ++ //@ close_points_to(xs); ++ //@ open_points_to(xs); ++} ++ + fn main() { + test1(); + test2(); diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0005-shared-array-slice.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0005-shared-array-slice.patch new file mode 100644 index 0000000000000..c3f9068dc9b90 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0005-shared-array-slice.patch @@ -0,0 +1,119 @@ +diff --git a/bin/rust/aliasing.rsspec b/bin/rust/aliasing.rsspec +index e9864ee..3664ccc 100644 +--- a/bin/rust/aliasing.rsspec ++++ b/bin/rust/aliasing.rsspec +@@ -99,6 +99,12 @@ fn create_ref_UnsafeCell(x: *_) -> *_; + //@ ens ref_origin(result) == ref_origin(x); + //@ on_unwind_ens false; + ++// Unsizing preserves the lifetime and reference tag of the array borrow. ++fn unsize_shared_array_ref(array: &'a [T; N]) -> &'a [T]; ++//@ req [?f]ref_initialized(array); ++//@ ens [f]ref_initialized(array) &*& result as *T == array as *T &*& result.len() == int_of_const(typeid(N)); ++//@ on_unwind_ens false; ++ + fn create_slice_ref(x: &'static [T]) -> &'static [T]; + //@ req true; // TODO + //@ ens result == x; +diff --git a/bin/rust/std/lib.rsspec b/bin/rust/std/lib.rsspec +index 2696613..f959297 100644 +--- a/bin/rust/std/lib.rsspec ++++ b/bin/rust/std/lib.rsspec +@@ -777,6 +777,13 @@ mod ptr { + + mod slice { + ++ // The usize implementation requires an in-bounds offset and creates a ++ // shared reference to the same element via &*index.get_unchecked(self). ++ unsafe fn get_unchecked_usize(self: &'a [T], index: usize) -> &'a T; ++ //@ req index < self.len() &*& ref_precreated_token((self as *T) + index, ?element) &*& [?f]ref_initialized(element); ++ //@ ens [f]ref_initialized(element) &*& result == element; ++ //@ on_unwind_ens false; ++ + struct Iter<'a, T>; + + struct IterMut<'a, T>; +diff --git a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +index 666b69e..24a1aea 100644 +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -2630,6 +2630,12 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + Ok + ( tmp_rvalue_binders, + FnCallResult (CastExpr (fn_loc, PtrTypeExpr (fn_loc, ManifestTypeExpr (fn_loc, Int (Unsigned, FixedWidthRank 0))), arg)) ) ++ | "std::slice::::get_unchecked" -> ++ begin match substs_cpn, substs with ++ | [_; { kind = Type { kind = UInt USize } }; _], [element; _; lifetime] -> ++ translate_regular_fn_call [element; lifetime] "std::slice::get_unchecked_usize" ++ | _ -> translate_regular_fn_call substs fn_name ++ end + | "std::slice::::as_ptr" -> + let [ Mir.GenArgType gen_arg_ty_info; _ ] = substs in + let [ arg ] = args in +@@ -3390,6 +3396,16 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + Static )) + in + Ok (`TrRvalueExpr (result_of_outcome loc e)) ++ | { kind = PointerCoercion; ty = { kind = Ref { mutability = Not; ty = { kind = Slice _ } } } } -> ++ (* A pointer coercion to a shared slice reference is array unsizing. ++ Keep the array reference's tag and attach its static length. *) ++ let expr = ++ match operand with ++ | `TrOperandCopy expr | `TrOperandMove (expr, _) -> expr ++ | _ -> Ast.static_error loc "Expected an array reference operand for slice unsizing" None ++ in ++ let call = Ast.CallExpr (loc, "unsize_shared_array_ref", [], [], [LitPat expr], Static) in ++ Ok (`TrRvalueExpr (result_of_outcome loc call)) + | _ -> + let* ty_info = translate_decoded_ty cast_data.ty loc in + let ty = ty_info.vf_ty in +diff --git a/tests/rust/purely_unsafe/shared_array_slice.rs b/tests/rust/purely_unsafe/shared_array_slice.rs +new file mode 100644 +index 0000000..8512efd +--- /dev/null ++++ b/tests/rust/purely_unsafe/shared_array_slice.rs +@@ -0,0 +1,33 @@ ++unsafe fn read_array(array: *const [u32; 3], index: usize) -> u32 ++//@ req (array as *u32)[..3] |-> ?items &*& index < 3; ++//@ ens (array as *u32)[..3] |-> items &*& result == nth(index, items); ++//@ on_unwind_ens false; ++{ ++ //@ close_points_to(array); ++ //@ let view = precreate_ref(array); ++ //@ init_ref_readonly(view, 1/2); ++ //@ open_points_to(view); ++ //@ let base = view as *u32; ++ //@ array_inv::(); ++ //@ array_split(base, index); ++ //@ array_split(base + index, 1); ++ //@ nth_drop(0, index, items); ++ //@ open [1/2]array(base + index, 1, _); ++ //@ open [1/2]array(base + index + 1, 0, _); ++ //@ let slot = precreate_ref(base + index); ++ //@ init_ref_readonly(slot, 1/2); ++ //@ points_to_limits(slot); ++ let value = unsafe { *(*array).get_unchecked(index) }; ++ //@ end_ref_readonly(slot); ++ //@ merge_fractions points_to(base + index, _); ++ //@ close [1/2]array(base + index, 1, [nth(index, items)]); ++ //@ array_join(base + index); ++ //@ array_join(base); ++ //@ close_points_to(view, 1/2); ++ //@ end_ref_readonly(view); ++ //@ merge_fractions points_to(array, _); ++ //@ open_points_to(array); ++ value ++} ++ ++fn main() {} +diff --git a/tests/rust/testsuite.mysh b/tests/rust/testsuite.mysh +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -58,6 +58,7 @@ cd purely_unsafe + verifast -ignore_unwind_paths account.rs + verifast -ignore_unwind_paths account_value.rs + verifast -ignore_unwind_paths point_value.rs ++ verifast -skip_specless_fns shared_array_slice.rs + verifast -ignore_unwind_paths account_with_box.rs + verifast -ignore_unwind_paths deque_i32.rs + verifast -ignore_unwind_paths deque.rs diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0006-mutable-array-slice.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0006-mutable-array-slice.patch new file mode 100644 index 0000000000000..89fd96c5bbf60 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0006-mutable-array-slice.patch @@ -0,0 +1,230 @@ +diff --git a/bin/rust/aliasing.rsspec b/bin/rust/aliasing.rsspec +index 57b00d6..7a4936f 100644 +--- a/bin/rust/aliasing.rsspec ++++ b/bin/rust/aliasing.rsspec +@@ -105,6 +105,19 @@ fn unsize_shared_array_ref(array: &'a [T; N]) -> &'a [T]; + //@ ens [f]ref_initialized(array) &*& result as *T == array as *T &*& result.len() == int_of_const(typeid(N)); + //@ on_unwind_ens false; + ++fn unsize_mut_array_ref(array: &'a mut [T; N]) -> &'a mut [T]; ++//@ req *array |-> ?items; ++//@ ens *array |-> items &*& result as *T == array as *T &*& result.len() == int_of_const(typeid(N)); ++//@ on_unwind_ens false; ++ ++/*@ ++pred slice_ref_mut_end_token(slice: *[T]; source: *T, count: usize); ++ ++lem end_slice_ref_mut(slice: *[T]); ++ req slice_ref_mut_end_token(slice, ?source, ?count) &*& (slice as *T)[..count] |-> ?elements; ++ ens source[..count] |-> elements; ++@*/ ++ + fn create_slice_ref(x: &'static [T]) -> &'static [T]; + //@ req true; // TODO + //@ ens result == x; +diff --git a/bin/rust/std/lib.rsspec b/bin/rust/std/lib.rsspec +index df09e22..8b1cd59 100644 +--- a/bin/rust/std/lib.rsspec ++++ b/bin/rust/std/lib.rsspec +@@ -63,6 +63,11 @@ mod ops { + start: Idx, + end: Idx, + } ++ ++ struct RangeTo { ++ end: Idx, ++ } ++ + + impl std::iter::IntoIterator for std::ops::Range { + +@@ -784,6 +789,34 @@ mod slice { + //@ ens [f]ref_initialized(element) &*& result == element; + //@ on_unwind_ens false; + ++ unsafe fn get_unchecked_mut_range(self: &'a mut [T], index: std::ops::Range) -> &'a mut [T]; ++ /*@ ++ req 0 <= index.start &*& index.start <= index.end &*& index.end <= self.len() &*& ++ (self as *T)[index.start..index.end] |-> ?elements; ++ @*/ ++ /*@ ++ ens (result as *T)[..result.len()] |-> elements &*& result.len() == index.end - index.start &*& ++ slice_ref_mut_end_token(result, (self as *T) + index.start, result.len()) &*& ++ ref_origin(result as *T) == ref_origin((self as *T) + index.start); ++ @*/ ++ //@ on_unwind_ens false; ++ ++ unsafe fn get_unchecked_mut_range_to(self: &'a mut [T], index: std::ops::RangeTo) -> &'a mut [T]; ++ //@ req 0 <= index.end &*& index.end <= self.len() &*& (self as *T)[..index.end] |-> ?elements; ++ /*@ ++ ens (result as *T)[..index.end] |-> elements &*& result.len() == index.end &*& ++ slice_ref_mut_end_token(result, self as *T, index.end) &*& ref_origin(result as *T) == ref_origin(self as *T); ++ @*/ ++ //@ on_unwind_ens false; ++ ++ unsafe fn get_unchecked_mut_usize(self: &'a mut [T], index: usize) -> &'a mut T; ++ //@ req 0 <= index &*& index < self.len() &*& *((self as *T) + index) |-> ?element; ++ /*@ ++ ens *result |-> element &*& ref_mut_end_token(result, (self as *T) + index) &*& ++ ref_origin(result) == ref_origin((self as *T) + index); ++ @*/ ++ //@ on_unwind_ens false; ++ + struct Iter<'a, T>; + + struct IterMut<'a, T>; +diff --git a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +index 24a1aea..19a92cd 100644 +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -2636,7 +2636,23 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + translate_regular_fn_call [element; lifetime] "std::slice::get_unchecked_usize" + | _ -> translate_regular_fn_call substs fn_name + end +- | "std::slice::::as_ptr" -> ++ | "std::slice::::get_unchecked_mut" -> ++ begin match substs_cpn, substs with ++ | [_; { kind = Type { kind = UInt USize } }; _], [element; _; lifetime] -> ++ translate_regular_fn_call [element; lifetime] "std::slice::get_unchecked_mut_usize" ++ | [_; { kind = Type { kind = Adt { id = { name }; ++ substs = [{ kind = Type { kind = UInt USize } }] } } }; _], ++ [element; _; lifetime] when name = "std::ops::Range" || name = "std::ops::RangeTo" -> ++ let spec = ++ if name = "std::ops::Range" then "std::slice::get_unchecked_mut_range" ++ else "std::slice::get_unchecked_mut_range_to" ++ in ++ translate_regular_fn_call [element; lifetime] spec ++ | _ -> translate_regular_fn_call substs fn_name ++ end ++ | "std::array::::as_mut_slice" -> ++ translate_regular_fn_call substs "unsize_mut_array_ref" ++ | "std::slice::::as_ptr" | "std::slice::::as_mut_ptr" -> + let [ Mir.GenArgType gen_arg_ty_info; _ ] = substs in + let [ arg ] = args in + Ok +@@ -3260,12 +3276,13 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let place_does_not_need_drop = place_does_not_need_drop_get ref_data_cpn in + let* place_expr, place_is_mutable = translate_place place_cpn loc in + let (path, line, _), _ = Ast.lexed_loc loc in ++ let place_ty = decode_ty (D.decode_ty (place_ty_get ref_data_cpn)) in + let ignore_ref_creation = +- bor_kind = Mut +- || +- not place_is_mutable && place_does_not_need_drop ++ (match bor_kind, place_ty with ++ | Mut, `Array -> false ++ | Mut, _ -> true (* Other mutable borrow forms are not tracked yet. *) ++ | Shared, _ -> not place_is_mutable && place_does_not_need_drop) + || +- (* ignore &mut E for now *) + if TranslatorArgs.ignore_ref_creation then true + else + let directives = +@@ -3293,9 +3310,6 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + if ignore_ref_creation then + Ok (`TrRvalueExpr (Ast.AddressOf (loc, place_expr))) + else +- let place_ty = +- decode_ty (D.decode_ty (place_ty_get ref_data_cpn)) +- in + let is_implicit = is_implicit_get ref_data_cpn in + let place_kind = + VfMirRd.PlaceKind.get (VfMirRd.Place.kind_get place_cpn) +@@ -3396,15 +3410,18 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + Static )) + in + Ok (`TrRvalueExpr (result_of_outcome loc e)) +- | { kind = PointerCoercion; ty = { kind = Ref { mutability = Not; ty = { kind = Slice _ } } } } -> +- (* A pointer coercion to a shared slice reference is array unsizing. +- Keep the array reference's tag and attach its static length. *) ++ | { kind = PointerCoercion; ty = { kind = Ref { mutability; ty = { kind = Slice _ } } } } -> ++ (* Array-to-slice coercion keeps the reference tag and adds the array length. *) + let expr = + match operand with + | `TrOperandCopy expr | `TrOperandMove (expr, _) -> expr + | _ -> Ast.static_error loc "Expected an array reference operand for slice unsizing" None + in +- let call = Ast.CallExpr (loc, "unsize_shared_array_ref", [], [], [LitPat expr], Static) in ++ let unsize = match mutability with ++ | Not -> "unsize_shared_array_ref" ++ | Mut -> "unsize_mut_array_ref" ++ in ++ let call = Ast.CallExpr (loc, unsize, [], [], [LitPat expr], Static) in + Ok (`TrRvalueExpr (result_of_outcome loc call)) + | _ -> + let* ty_info = translate_decoded_ty cast_data.ty loc in +diff --git a/tests/rust/purely_unsafe/mutable_array_slice.rs b/tests/rust/purely_unsafe/mutable_array_slice.rs +new file mode 100644 +index 0000000..dc08696 +--- /dev/null ++++ b/tests/rust/purely_unsafe/mutable_array_slice.rs +@@ -0,0 +1,58 @@ ++unsafe fn update_array(array: *mut [u32; 3], first: usize, last: usize) ++//@ req (array as *u32)[..3] |-> ?slots &*& first < 3 &*& first <= last &*& last <= 3; ++//@ ens (array as *u32)[..3] |-> append(take(first, slots), cons(42, drop(first + 1, slots))); ++//@ on_unwind_ens false; ++{ ++ //@ close_points_to(array); ++ unsafe { ++ let borrowed = &mut *array; ++ let values = borrowed.as_mut_slice(); ++ let base = values.as_mut_ptr(); ++ //@ open_points_to(borrowed); ++ ++ //@ array_split(base, first); ++ //@ array_split(base + first, last - first); ++ let range = values.get_unchecked_mut(first..last); ++ //@ assert range.len() == last - first; ++ //@ end_slice_ref_mut(range); ++ //@ array_join(base + first); ++ //@ array_join(base); ++ ++ //@ array_split(base, last); ++ let prefix = values.get_unchecked_mut(..last); ++ //@ assert prefix.len() == last; ++ //@ end_slice_ref_mut(prefix); ++ //@ array_join(base); ++ ++ //@ array_split(base, first); ++ //@ array_split(base + first, 1); ++ //@ open array(base + first, 1, _); ++ let slot = values.get_unchecked_mut(first); ++ //@ points_to_limits(slot); ++ *slot = 42; ++ //@ end_ref_mut(slot); ++ //@ close array(base + first, 1, [42]); ++ //@ array_join(base + first); ++ //@ array_join(base); ++ //@ length_drop(first, slots); ++ //@ drop_n_plus_one(first, slots); ++ //@ close_points_to(borrowed); ++ //@ end_ref_mut(borrowed); ++ } ++ //@ open_points_to(array); ++} ++ ++unsafe fn reject_write_through_parent(x: &mut [u32]) -> u32 ++//@ req 0 < x.len() &*& *(x as *u32) |-> ?value; ++//@ ens *(x as *u32) |-> value &*& result == value; ++//@ on_unwind_ens false; ++{ ++ let old = x.as_mut_ptr(); ++ let borrow = unsafe { x.get_unchecked_mut(0) }; ++ unsafe { *old = 42 }; //~should_fail ++ let observed = *borrow; ++ //@ end_ref_mut(borrow); ++ observed ++} ++ ++fn main() {} +diff --git a/tests/rust/testsuite.mysh b/tests/rust/testsuite.mysh +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -65,6 +65,7 @@ cd purely_unsafe + verifast -ignore_unwind_paths tree.rs + verifast -ignore_unwind_paths -allow_assume tree2.rs + verifast traits0.rs ++ verifast -skip_specless_fns -allow_dead_code -allow_should_fail mutable_array_slice.rs + verifast -allow_should_fail -allow_dead_code traits0_error.rs + verifast -allow_should_fail -allow_dead_code traits0_error2.rs + verifast pred_fam.rs diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0007-scoped-struct-borrow.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0007-scoped-struct-borrow.patch new file mode 100644 index 0000000000000..0c7b3785d7d9a --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0007-scoped-struct-borrow.patch @@ -0,0 +1,142 @@ +diff --git a/bin/rust/aliasing.rsspec b/bin/rust/aliasing.rsspec +index 7a4936f..b37594a 100644 +--- a/bin/rust/aliasing.rsspec ++++ b/bin/rust/aliasing.rsspec +@@ -54,7 +54,7 @@ lem end_ref_readonly(p: *T); + + fn create_ref_mut(x: *T) -> *T; + //@ req *x |-> ?v; +-//@ ens *result |-> v &*& ref_mut_end_token(result, x); ++//@ ens *result |-> v &*& ref_mut_end_token(result, x) &*& ref_origin(result) == ref_origin(x); + //@ on_unwind_ens false; + + fn reborrow_ref_mut_implicit(x: *T) -> *T; +diff --git a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +index 19a92cd..c52f73e 100644 +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -3277,43 +3277,44 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let* place_expr, place_is_mutable = translate_place place_cpn loc in + let (path, line, _), _ = Ast.lexed_loc loc in + let place_ty = decode_ty (D.decode_ty (place_ty_get ref_data_cpn)) in ++ let place_kind = VfMirRd.PlaceKind.get (VfMirRd.Place.kind_get place_cpn) in ++ let directive_on_line name = ++ List.find_opt ++ (fun { Mir.span; raw } -> ++ let (source_path, source_line, _), _ = Ast.lexed_loc span in ++ raw = name && source_path = path && source_line = line) ++ Args.body_tr_defs_ctx.directives ++ in ++ (* Opt in for fresh mutable borrows from raw places. Reborrows ++ retain their existing treatment. *) ++ let track_fresh_mut_ref = ++ bor_kind = Mut && place_kind = Other ++ && Option.is_some (directive_on_line "track_ref_creation") ++ in + let ignore_ref_creation = +- (match bor_kind, place_ty with +- | Mut, `Array -> false +- | Mut, _ -> true (* Other mutable borrow forms are not tracked yet. *) +- | Shared, _ -> not place_is_mutable && place_does_not_need_drop) +- || +- if TranslatorArgs.ignore_ref_creation then true ++ if track_fresh_mut_ref then false + else +- let directives = +- Util.flatmap +- (fun { Mir.span; raw } -> +- if +- raw = "ignore_ref_creation" +- && +- let (path', line', _), _ = Ast.lexed_loc span in +- path' = path && line' = line +- then [ span ] +- else []) +- Args.body_tr_defs_ctx.directives +- in +- match directives with +- | directive_span :: _ -> +- if not TranslatorArgs.allow_ignore_ref_creation then +- Ast.static_error directive_span +- "Ignoring reference creation is not allowed; specify \ +- -allow_ignore_ref_creation on the command line to allow" +- None; +- true +- | [] -> false ++ (match bor_kind, place_ty with ++ | Mut, `Array -> false ++ | Mut, _ -> true (* Other mutable borrow forms are not tracked yet. *) ++ | Shared, _ -> not place_is_mutable && place_does_not_need_drop) ++ || ++ if TranslatorArgs.ignore_ref_creation then true ++ else ++ match directive_on_line "ignore_ref_creation" with ++ | Some directive -> ++ if not TranslatorArgs.allow_ignore_ref_creation then ++ Ast.static_error directive.Mir.span ++ "Ignoring reference creation is not allowed; specify \ ++ -allow_ignore_ref_creation on the command line to allow" ++ None; ++ true ++ | None -> false + in + if ignore_ref_creation then + Ok (`TrRvalueExpr (Ast.AddressOf (loc, place_expr))) + else + let is_implicit = is_implicit_get ref_data_cpn in +- let place_kind = +- VfMirRd.PlaceKind.get (VfMirRd.Place.kind_get place_cpn) +- in + (* + Printf.printf "ref creation at %s: place_ty=%s, bor_kind=%s, place_kind=%s, is_implicit=%b\n" + (Ast.string_of_loc loc) +@@ -8032,7 +8033,7 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let* directives = ListAux.try_map translate_annotation directives_cpn in + let vf_mir_translator_directives, vf_directives = + directives +- |> List.partition (fun { Mir.raw } -> raw = "ignore_ref_creation") ++ |> List.partition (fun { Mir.raw } -> raw = "ignore_ref_creation" || raw = "track_ref_creation") + in + vf_directives + |> List.iter (fun ({ span; raw } : Mir.annot) -> +diff --git a/tests/rust/testsuite.mysh b/tests/rust/testsuite.mysh +index 9697d51..5e4d3fd 100644 +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -36,6 +36,7 @@ cd purely_unsafe + verifast enum_discr.rs + verifast -ignore_unwind_paths leftpad.rs + verifast arrays.rs ++ verifast -allow_dead_code -skip_specless_fns mutable_struct_borrow.rs + verifast -skip_specless_fns fixed_array_index.rs + !verifast -skip_specless_fns fixed_array_index_bad.rs + verifast -skip_specless_fns box_projection.rs +diff --git a/tests/rust/purely_unsafe/mutable_struct_borrow.rs b/tests/rust/purely_unsafe/mutable_struct_borrow.rs +new file mode 100644 +index 0000000..168799c +--- /dev/null ++++ b/tests/rust/purely_unsafe/mutable_struct_borrow.rs +@@ -0,0 +1,23 @@ ++struct Record { size: u16, entries: [u16; 2] } ++ ++unsafe fn borrow_record<'a>(ptr: *mut Record) -> &'a mut Record ++//@ req *ptr |-> ?value; ++//@ ens *result |-> value &*& ref_mut_end_token(result, ptr) &*& ref_origin(result) == ref_origin(ptr); ++//@ on_unwind_ens false; ++{ ++ unsafe { &mut *ptr } //~track_ref_creation ++} ++ ++unsafe fn update(ptr: *mut Record) ++//@ req *ptr |-> ?value; ++//@ ens *ptr |-> Record { size: 1, entries: value.entries }; ++//@ on_unwind_ens false; ++{ ++ let reference = unsafe { borrow_record(ptr) }; ++ //@ open_points_to(reference); ++ reference.size = 1; ++ //@ close_points_to(reference); ++ //@ end_ref_mut(reference); ++} ++ ++fn main() {} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0008-array-prefix-index.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0008-array-prefix-index.patch new file mode 100644 index 0000000000000..bdbf3112702dc --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0008-array-prefix-index.patch @@ -0,0 +1,86 @@ +diff --git a/bin/rust/std/lib.rsspec b/bin/rust/std/lib.rsspec +index 8b1cd59..3d87eb2 100644 +--- a/bin/rust/std/lib.rsspec ++++ b/bin/rust/std/lib.rsspec +@@ -801,6 +801,19 @@ mod slice { + @*/ + //@ on_unwind_ens false; + ++ // RangeTo array indexing unsizes the array and checks 0..index.end. ++ fn array_index_mut_range_to(array: &'a mut [T; N], index: std::ops::RangeTo) -> &'a mut [T]; ++ /*@ ++ req 0 <= index.end &*& index.end <= int_of_const(typeid(N)) &*& ++ (array as *T)[..index.end] |-> ?elements; ++ @*/ ++ /*@ ++ ens result.len() == index.end &*& (result as *T)[..index.end] |-> elements &*& ++ slice_ref_mut_end_token(result, array as *T, index.end) &*& ++ ref_origin(result as *T) == ref_origin(array as *T); ++ @*/ ++ //@ on_unwind_ens false; ++ + unsafe fn get_unchecked_mut_range_to(self: &'a mut [T], index: std::ops::RangeTo) -> &'a mut [T]; + //@ req 0 <= index.end &*& index.end <= self.len() &*& (self as *T)[..index.end] |-> ?elements; + /*@ +diff --git a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +index c52f73e..ff7a380 100644 +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -2650,6 +2650,17 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + translate_regular_fn_call [element; lifetime] spec + | _ -> translate_regular_fn_call substs fn_name + end ++ | "std::ops::IndexMut::index_mut" -> ++ begin match substs_cpn, substs with ++ | [{ kind = Type { kind = Array { elem_ty; size } } }; ++ { kind = Type { kind = Adt { id = { name = "std::ops::RangeTo" }; ++ substs = [{ kind = Type { kind = UInt USize } }] } } }; _], ++ [_; _; lifetime] -> ++ let* element = translate_generic_arg { kind = Type elem_ty } call_loc in ++ let* length = translate_generic_arg { kind = Const size } call_loc in ++ translate_regular_fn_call [element; length; lifetime] "std::slice::array_index_mut_range_to" ++ | _ -> translate_regular_fn_call substs fn_name ++ end + | "std::array::::as_mut_slice" -> + translate_regular_fn_call substs "unsize_mut_array_ref" + | "std::slice::::as_ptr" | "std::slice::::as_mut_ptr" -> +diff --git a/tests/rust/purely_unsafe/array_prefix_borrow.rs b/tests/rust/purely_unsafe/array_prefix_borrow.rs +new file mode 100644 +index 0000000..b57d6bf +--- /dev/null ++++ b/tests/rust/purely_unsafe/array_prefix_borrow.rs +@@ -0,0 +1,22 @@ ++unsafe fn prefix_probe<'a, T>(x: &'a mut [T; 11], end: usize) ++ //@ req 0 <= end &*& end <= 11 &*& (x as *T)[..11] |-> ?values; ++ //@ ens (x as *T)[..11] |-> values; ++ //@ on_unwind_ens false; ++{ ++ //@ array_split(x as *T, end); ++ let prefix = &mut x[..end]; ++ //@ assert prefix.len() == end; ++ //@ assert ref_origin(prefix as *T) == ref_origin(x as *T); ++ //@ end_slice_ref_mut(prefix); ++ //@ array_join(x as *T); ++} ++ ++unsafe fn out_of_bounds(x: &mut [u8; 11], end: usize) ++ //@ req end == 12 &*& (x as *u8)[..12] |-> ?values; ++ //@ ens true; ++ //@ on_unwind_ens false; ++{ ++ let _ = &mut x[..end]; //~should_fail ++} ++ ++fn main() {} +diff --git a/tests/rust/testsuite.mysh b/tests/rust/testsuite.mysh +index 5e4d3fd..e92cdb3 100644 +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -36,6 +36,7 @@ cd purely_unsafe + verifast enum_discr.rs + verifast -ignore_unwind_paths leftpad.rs + verifast arrays.rs ++ verifast -skip_specless_fns -allow_dead_code -allow_should_fail array_prefix_borrow.rs + verifast -allow_dead_code -skip_specless_fns mutable_struct_borrow.rs + verifast -skip_specless_fns fixed_array_index.rs + !verifast -skip_specless_fns fixed_array_index_bad.rs diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0009-borrowed-box-projection.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0009-borrowed-box-projection.patch new file mode 100644 index 0000000000000..53c0876b7f763 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0009-borrowed-box-projection.patch @@ -0,0 +1,242 @@ +diff --git a/src/refinement_checker/refinement_checker.ml b/src/refinement_checker/refinement_checker.ml +index 6c582f2..8b6407a 100644 +--- a/src/refinement_checker/refinement_checker.ml ++++ b/src/refinement_checker/refinement_checker.ml +@@ -1664,6 +1664,7 @@ let commands_of_rvalue = function + | ThreadLocalRef -> failwith "TODO: ThreadLocalRef" + | RawPtr rvalue_raw_ptr_data -> [RawPtr rvalue_raw_ptr_data] + | Cast {operand=Copy {local; projection=[BoxAsNonNull _]}} -> [LoadLocal local; BoxAsPtr] ++| Cast {operand=Copy {local; projection=[Deref; BoxAsNonNull _]}} -> [LoadLocal local; Deref; BoxAsPtr] + | Cast {operand; ty} -> commands_of_operand operand @ [Cast ty] + | BinaryOp {operator; operandl; operandr} -> commands_of_operand operandl @ commands_of_operand operandr @ [BinaryOp operator] + | UnaryOp {operator; operand} -> commands_of_operand operand @ [UnaryOp operator] +diff --git a/src/rust_frontend/vf_mir_exporter/src/lib.rs b/src/rust_frontend/vf_mir_exporter/src/lib.rs +index ef0ba83..902bd17 100644 +--- a/src/rust_frontend/vf_mir_exporter/src/lib.rs ++++ b/src/rust_frontend/vf_mir_exporter/src/lib.rs +@@ -628,6 +628,17 @@ use rustc_span::RemapPathScopeComponents; + Adt, + Other, + } ++ ++ struct LocalUses(Vec); ++ ++ impl<'tcx> mir::visit::Visitor<'tcx> for LocalUses { ++ fn visit_local(&mut self, local: mir::Local, context: mir::visit::PlaceContext, _: mir::Location) { ++ if context.is_use() || matches!(context, mir::visit::PlaceContext::NonUse(mir::visit::NonUseContext::VarDebugInfo)) { ++ self.0[local.as_usize()] += 1; ++ } ++ } ++ } ++ + struct EncCtx<'tcx, 'a> { + req_adts: Vec>, + tcx: TyCtxt<'tcx>, +@@ -1426,6 +1437,7 @@ use rustc_span::RemapPathScopeComponents; + }, + ); + ++ let mut local_uses = None; + body_cpn.fill_basic_blocks( + body.basic_blocks.iter_enumerated(), + |basic_block_cpn, (basic_block_idx, basic_block)| { +@@ -1434,6 +1446,7 @@ use rustc_span::RemapPathScopeComponents; + enc_ctx, + basic_block_idx, + basic_block, ++ &mut local_uses, + basic_block_cpn, + ); + }, +@@ -2080,17 +2093,59 @@ use rustc_span::RemapPathScopeComponents; + enc_ctx: &mut EncCtx<'tcx, 'a>, + basic_block_idx: mir::BasicBlock, + basic_block_data: &mir::BasicBlockData<'tcx>, ++ local_uses: &mut Option, + mut basic_block_cpn: basic_block_cpn::Builder<'_>, + ) { + let basic_block_id_cpn = basic_block_cpn.reborrow().init_id(); + Self::encode_basic_block_id(basic_block_idx, basic_block_id_cpn); + +- basic_block_cpn.fill_statements( +- &basic_block_data.statements, +- |statement_cpn, statement| { +- Self::encode_statement(tcx, enc_ctx, statement, statement_cpn); +- }, +- ); ++ let mut rewritten_statements = None; ++ for (i, pair) in basic_block_data.statements.windows(2).enumerate() { ++ // Derefer copies a Box through a reference without a retag before ++ // ElaborateBoxDerefs extracts its pointer. When that extraction ++ // is the temporary's only read, project from the original place. ++ let [copy, cast] = pair else { unreachable!() }; ++ let mir::StatementKind::Assign((tmp, mir::Rvalue::Use( ++ mir::Operand::Copy(source), mir::WithRetag::No, ++ ))) = ©.kind else { continue }; ++ let mir::StatementKind::Assign((target, mir::Rvalue::Cast( ++ mir::CastKind::BoxDerefTransmute, mir::Operand::Copy(field), ty, ++ ))) = &cast.kind else { continue }; ++ let body = enc_ctx.body(); ++ let tmp_decl = &body.local_decls[tmp.local]; ++ if !tmp.projection.is_empty() ++ || tmp.local.as_usize() <= body.arg_count ++ || source.projection.as_slice() != [mir::PlaceElem::Deref] ++ || tmp.local != field.local ++ || !matches!(field.projection.as_slice(), [mir::PlaceElem::Field(index, _)] if index.as_usize() == 0) ++ || !matches!(body.local_decls[source.local].ty.kind(), ++ ty::Ref(_, boxed, mir::Mutability::Mut) if boxed.is_box() && *boxed == tmp_decl.ty) ++ { ++ continue; ++ } ++ let uses = local_uses.get_or_insert_with(|| { ++ let mut counts = LocalUses(vec![0; body.local_decls.len()]); ++ mir::visit::Visitor::visit_body(&mut counts, body); ++ counts ++ }); ++ if uses.0[tmp.local.as_usize()] != 2 { ++ continue; ++ } ++ let place = mir::Place { ++ local: source.local, ++ projection: tcx.mk_place_elems(&[mir::PlaceElem::Deref, field.projection[0]]), ++ }; ++ let statements = rewritten_statements.get_or_insert_with(|| basic_block_data.statements.clone()); ++ statements[i].kind = mir::StatementKind::Nop; ++ statements[i + 1].kind = mir::StatementKind::Assign(( ++ *target, ++ mir::Rvalue::Cast(mir::CastKind::BoxDerefTransmute, mir::Operand::Copy(place), *ty), ++ ).into()); ++ } ++ let statements = rewritten_statements.as_deref().unwrap_or(&basic_block_data.statements); ++ basic_block_cpn.fill_statements(statements, |statement_cpn, statement| { ++ Self::encode_statement(tcx, enc_ctx, statement, statement_cpn); ++ }); + + let terminator_cpn = basic_block_cpn.reborrow().init_terminator(); + Self::encode_terminator(tcx, enc_ctx, basic_block_data.terminator(), terminator_cpn); +@@ -2911,20 +2966,27 @@ use rustc_span::RemapPathScopeComponents; + let local = &enc_ctx.body().local_decls()[place.local]; + let mut pty = mir::PlaceTy::from_ty(local.ty); + let mut kind = PlaceKind::Other; +- let is_box_field0_projection = local.ty.is_box() +- && !place.projection.is_empty() ++ let (box_ty, prefix_len) = match (local.ty.kind(), place.projection.first()) { ++ (ty::Ref(_, target, mir::Mutability::Mut), Some(mir::PlaceElem::Deref)) => (*target, 1), ++ _ => (local.ty, 0), ++ }; ++ let fields = &place.projection.as_slice()[prefix_len..]; ++ let is_box_field0_projection = box_ty.is_box() ++ && !fields.is_empty() + && place.projection.len() <= 2 +- && place.projection.iter().all(|elem| { ++ && fields.iter().all(|elem| { + matches!(elem, mir::ProjectionElem::Field(field_idx, _) if field_idx.as_usize() == 0) + }); + if is_box_field0_projection { +- // The only projections that can be applied to a Box are +- // `X.0: std::ptr::Unique` (emitted by ElaborateBoxDerefs) and +- // `(X.0: std::ptr::Unique).0: std::ptr::NonNull` (emitted by drop glue). +- let place_projection_cpn = place_cpn.reborrow().init_projection(1); +- let place_elem_cpn = place_projection_cpn.get(0); +- let ty_cpn = place_elem_cpn.init_box_as_non_null(); +- Self::encode_ty(enc_ctx.tcx, enc_ctx, local.ty.boxed_ty().unwrap(), ty_cpn); ++ // Box's first field is its pointer. Drop glue also projects ++ // Unique's first field to obtain NonNull. ++ let mut projection = place_cpn.reborrow().init_projection(prefix_len + 1); ++ if prefix_len == 1 { ++ projection.reborrow().get(0).set_deref(()); ++ kind = PlaceKind::MutableRef; ++ } ++ let ty_cpn = projection.get(prefix_len).init_box_as_non_null(); ++ Self::encode_ty(enc_ctx.tcx, enc_ctx, box_ty.boxed_ty().unwrap(), ty_cpn); + } else { + place_cpn.reborrow().fill_projection(place.projection, |place_elm_cpn, place_elm| { + kind = Self::encode_place_element(enc_ctx, pty.ty, &place_elm, place_elm_cpn, kind); +diff --git a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +index ff7a380..21feb7e 100644 +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -3410,15 +3410,16 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + cast_data.ty + end; + match cast_data with +- {operand=Copy {local; projection=[BoxAsNonNull _]}} -> +- let id = translate_local_decl_id_ local.name in ++ {operand=Copy {local; projection=([BoxAsNonNull _] | [Deref; BoxAsNonNull _]) as projection}} -> ++ let var = Ast.Var (loc, translate_local_decl_id_ local.name) in ++ let box_ref = if List.length projection = 1 then Ast.AddressOf (loc, var) else var in + let e = + ( Ast.CallExpr + ( loc, + "std::boxed::Box::::as_mut_ptr", + [], + [], +- [ LitPat (AddressOf (loc, Var (loc, id))) ], ++ [ LitPat box_ref ], + Static )) + in + Ok (`TrRvalueExpr (result_of_outcome loc e)) +diff --git a/tests/rust/purely_unsafe/borrowed_box_projection.rs b/tests/rust/purely_unsafe/borrowed_box_projection.rs +new file mode 100644 +index 0000000..b4083fb +--- /dev/null ++++ b/tests/rust/purely_unsafe/borrowed_box_projection.rs +@@ -0,0 +1,46 @@ ++#![allow(dead_code)] ++ ++unsafe fn replace_borrowed_box_contents(mut owner: Box, value: i32) -> Box ++/*@ ++req thread_token(?t) &*& std::boxed::Box_in(t, owner, ?id, _) &*& ++ exists::(?k) &*& [?q]lifetime_token(k) &*& lifetime_inclusion(k, id.lft) == true; ++@*/ ++//@ ens thread_token(t) &*& std::boxed::Box_in(t, result, id, value) &*& [q]lifetime_token(k); ++//@ on_unwind_ens false; ++{ ++ //@ open exists(k); ++ let view = &mut owner; //~track_ref_creation ++ //@ let contents = std::boxed::Box_separate_contents(view); ++ //@ let traded = lifetime_token_trade(k, q, id.lft); ++ //@ open_points_to_at_lft(contents, traded); ++ //@ points_to_limits(contents); ++ let destination: &mut i32 = view; //~track_ref_creation ++ *destination = value; ++ //@ end_ref_mut(destination); ++ //@ close_points_to_at_lft(contents); ++ //@ lifetime_token_trade_back(traded, id.lft); ++ //@ std::boxed::Box_unseparate_contents(view); ++ //@ end_ref_mut(view); ++ owner ++} ++ ++unsafe fn borrow_another_box(mut owner: Box, mut other: Box) ++/*@ ++req thread_token(?t) &*& std::boxed::Box_in(t, owner, ?id, _) &*& std::boxed::Box_in(t, other, _, _) &*& ++ exists::(?k) &*& [?q]lifetime_token(k) &*& lifetime_inclusion(k, id.lft) == true; ++@*/ ++//@ ens thread_token(t) &*& [q]lifetime_token(k); ++//@ on_unwind_ens false; ++{ ++ //@ open exists(k); ++ let _view = &mut owner; //~track_ref_creation ++ //@ let contents = std::boxed::Box_separate_contents(_view); ++ //@ let traded = lifetime_token_trade(k, q, id.lft); ++ //@ open_points_to_at_lft(contents, traded); ++ //@ points_to_limits(contents); ++ ++ let other_view = &mut other; //~track_ref_creation ++ let _destination: &mut i32 = other_view; //~should_fail ++} ++ ++fn main() {} +diff --git a/tests/rust/testsuite.mysh b/tests/rust/testsuite.mysh +index e92cdb3..138a69e 100644 +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -41,6 +41,7 @@ cd purely_unsafe + verifast -skip_specless_fns fixed_array_index.rs + !verifast -skip_specless_fns fixed_array_index_bad.rs + verifast -skip_specless_fns box_projection.rs ++ verifast -skip_specless_fns -allow_dead_code -allow_should_fail borrowed_box_projection.rs + verifast -allow_assume std_thread.rs + verifast -allow_should_fail -allow_dead_code nonmut_let_immut.rs + verifast struct_exprs.rs diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0010-merge-fractions-address-traversal.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0010-merge-fractions-address-traversal.patch new file mode 100644 index 0000000000000..872304125b5bb --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0010-merge-fractions-address-traversal.patch @@ -0,0 +1,44 @@ +diff --git a/src/verify_expr.ml b/src/verify_expr.ml +index ee42f9e..a4a0bf6 100644 +--- a/src/verify_expr.ml ++++ b/src/verify_expr.ml +@@ -1553,7 +1553,7 @@ module VerifyExpr(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + List.iter (fun p -> pat_expr_mark_addr_taken p locals) pats; + (match eopt with None -> () | Some(e) -> expr_mark_addr_taken e locals); + cont locals +- | MergeFractionsStmt(_, a) -> ass_mark_addr_taken a locals; ++ | MergeFractionsStmt(_, a) -> ass_mark_addr_taken a locals; cont locals + | CreateHandleStmt(_, _, _, _, e) -> expr_mark_addr_taken e locals; cont locals + | DisposeBoxStmt(_, _, pats, clauses) -> + List.iter (fun p -> pat_expr_mark_addr_taken p locals) pats; +diff --git a/tests/rust/purely_unsafe/merge_fractions_before_borrow.rs b/tests/rust/purely_unsafe/merge_fractions_before_borrow.rs +new file mode 100644 +index 0000000..c0fd4b9 +--- /dev/null ++++ b/tests/rust/purely_unsafe/merge_fractions_before_borrow.rs +@@ -0,0 +1,13 @@ ++unsafe fn write_after_merge(ptr: *mut u8) -> u8 ++//@ req [1/2](*ptr |-> ?value) &*& [1/2](*ptr |-> value); ++//@ ens *ptr |-> value &*& result == 2; ++//@ on_unwind_ens false; ++{ ++ //@ merge_fractions points_to(ptr, _); ++ let mut local = 1; ++ let address = &raw mut local; ++ unsafe { *address = 2 }; ++ local ++} ++ ++fn main() {} +diff --git a/tests/rust/testsuite.mysh b/tests/rust/testsuite.mysh +index 138a69e..94c290b 100644 +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -42,6 +42,7 @@ cd purely_unsafe + !verifast -skip_specless_fns fixed_array_index_bad.rs + verifast -skip_specless_fns box_projection.rs + verifast -skip_specless_fns -allow_dead_code -allow_should_fail borrowed_box_projection.rs ++ verifast -skip_specless_fns merge_fractions_before_borrow.rs + verifast -allow_assume std_thread.rs + verifast -allow_should_fail -allow_dead_code nonmut_let_immut.rs + verifast struct_exprs.rs diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0011-rust-field-provenance-injectivity.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0011-rust-field-provenance-injectivity.patch new file mode 100644 index 0000000000000..a787a35f0c6db --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0011-rust-field-provenance-injectivity.patch @@ -0,0 +1,50 @@ +diff --git a/bin/rust/prelude_core.rsspec b/bin/rust/prelude_core.rsspec +index 34d3057..2a4e145 100644 +--- a/bin/rust/prelude_core.rsspec ++++ b/bin/rust/prelude_core.rsspec +@@ -111,11 +111,8 @@ fix ptr_add_strip_metadata(p: pointer, offset: i32) -> pointer { + } + + fix field_ptr_provenance(p: pointer, structTypeid: *_, fieldOffset: i32) -> pointer_provenance; +-fix field_ptr_provenance_parent(pr: pointer_provenance, fieldOffset: i32) -> pointer; +- +-lem_auto(field_ptr_provenance(p, structTypeid, fieldOffset)) field_ptr_provenance_injective(p: pointer, structTypeid: *_, fieldOffset: i32); +- req true; +- ens field_ptr_provenance_parent(field_ptr_provenance(p, structTypeid, fieldOffset), fieldOffset) == p; ++// Rust field projections retain the base provenance. The provenance ++// and field offset therefore cannot recover the base address. + + fix field_ptr(p: pointer, structTypeid: *_, fieldOffset: i32) -> pointer { + pointer_ctor(field_ptr_provenance(p, structTypeid, fieldOffset), p.address + fieldOffset, pointer_metadata_none) +diff --git a/tests/rust/purely_unsafe/field_projection_addresses.rs b/tests/rust/purely_unsafe/field_projection_addresses.rs +new file mode 100644 +index 0000000..11991b9 +--- /dev/null ++++ b/tests/rust/purely_unsafe/field_projection_addresses.rs +@@ -0,0 +1,14 @@ ++/*@ ++lem distinct_fields(p: pointer) ++ req true; ++ ens true; ++{ ++ let q = ptr_add(p, 1); ++ let a = last_field_ptr(p, typeid(i32), 0); ++ let b = last_field_ptr(q, typeid(i32), 0); ++ assert a != b; ++ assert a == b; //~should_fail ++} ++@*/ ++ ++fn main() {} +diff --git a/tests/rust/testsuite.mysh b/tests/rust/testsuite.mysh +index 94c290b..db88fe4 100644 +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -43,6 +43,7 @@ cd purely_unsafe + verifast -skip_specless_fns box_projection.rs + verifast -skip_specless_fns -allow_dead_code -allow_should_fail borrowed_box_projection.rs + verifast -skip_specless_fns merge_fractions_before_borrow.rs ++ verifast -skip_specless_fns -allow_should_fail field_projection_addresses.rs + verifast -allow_assume std_thread.rs + verifast -allow_should_fail -allow_dead_code nonmut_let_immut.rs + verifast struct_exprs.rs diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0012-rust-drop-unwind.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0012-rust-drop-unwind.patch new file mode 100644 index 0000000000000..6b3a335a7be7a --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0012-rust-drop-unwind.patch @@ -0,0 +1,241 @@ +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -3032,21 +3032,45 @@ + Static )); + ] ) + in ++ let drop_expr = ++ Ast.CallExpr ++ ( loc, ++ "std::ptr::drop_in_place", ++ [], ++ [], ++ [ LitPat (AddressOf (loc, place)) ], ++ Static ) ++ in ++ let drop_stmts, unwind_targets = ++ if TranslatorArgs.ignore_unwind_paths then ++ ([ Ast.ExprStmt drop_expr ] @ freeze_stmts, []) ++ else ++ let unwind_stmts, unwind_targets = ++ translate_unwind_action (unwind_action_get drop_data_cpn) loc ++ in ++ ( [ ++ Ast.SwitchStmt ++ ( loc, ++ drop_expr, ++ [ ++ Ast.SwitchStmtClause ++ ( loc, ++ CallExpr ++ ( loc, "returning", [], [], ++ [ LitPat (Var (loc, "__drop_result")) ], Static ), ++ freeze_stmts ); ++ Ast.SwitchStmtClause ++ ( loc, ++ CallExpr (loc, "unwinding", [], [], [], Static), ++ freeze_stmts @ unwind_stmts ); ++ ] ); ++ ], ++ unwind_targets ) ++ in + Ok +- ( unfreeze_stmts +- @ [ +- Ast.ExprStmt +- (CallExpr +- ( loc, +- "std::ptr::drop_in_place", +- [], +- [], +- [ LitPat (AddressOf (loc, place)) ], +- Static )); +- ] +- @ freeze_stmts, ++ ( unfreeze_stmts @ drop_stmts, + Mir.GotoTerminator (loc, target), +- [ target ] ) ++ target :: unwind_targets ) + | Assert assert_data_cpn -> + (* `Assert { cond, expected, target, unwind }`: continue at `target` if `cond == expected`, + otherwise panic (i.e. unwind). With -ignore_unwind_paths the panicking branch is +diff --git a/tests/rust/purely_unsafe/drop_cleanup.rs b/tests/rust/purely_unsafe/drop_cleanup.rs +new file mode 100644 +--- /dev/null ++++ b/tests/rust/purely_unsafe/drop_cleanup.rs +@@ -0,0 +1,21 @@ ++unsafe fn drop_with_cleanup(value: T, pending: U) ++//@ req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& .own(t, value) &*& .own(t, pending); ++//@ ens thread_token(t) &*& type_interp::() &*& type_interp::(); ++//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::(); ++{ ++ let mut cleanup = pending; ++ //@ close_points_to(&mut cleanup); ++ let mut primary = value; ++ //@ close_points_to(&mut primary); ++} ++ ++unsafe fn cannot_rule_out_unwind(value: T) ++//@ req thread_token(?t) &*& type_interp::() &*& .own(t, value); ++//@ ens thread_token(t) &*& type_interp::(); ++//@ on_unwind_ens false; //~should_fail ++{ ++ let mut primary = value; ++ //@ close_points_to(&mut primary); ++} ++ ++fn main() {} +--- a/tests/rust/testsuite.mysh ++++ b/tests/rust/testsuite.mysh +@@ -44,6 +44,7 @@ + verifast -skip_specless_fns -allow_dead_code -allow_should_fail borrowed_box_projection.rs + verifast -skip_specless_fns merge_fractions_before_borrow.rs + verifast -skip_specless_fns -allow_should_fail field_projection_addresses.rs ++ verifast -skip_specless_fns -allow_dead_code -allow_should_fail drop_cleanup.rs + verifast -allow_assume std_thread.rs + verifast -allow_should_fail -allow_dead_code nonmut_let_immut.rs + verifast struct_exprs.rs +diff --git a/src/refinement_checker/main.ml b/src/refinement_checker/main.ml +--- a/src/refinement_checker/main.ml ++++ b/src/refinement_checker/main.ml +@@ -25,6 +25,9 @@ + | "--ignore-directives" :: args -> + ignore_directives := true; + process_args args ++ | "--check-unwind" :: args -> ++ check_unwind := true; ++ process_args args + | "--verbose" :: value :: args -> + verbosity := + begin match int_of_string_opt value with +@@ -39,12 +42,13 @@ + | [ original_path; verified_path ] -> (original_path, verified_path) + | _ -> + print_endline +- "Usage: refinement_checker [--ignore-directives] [--verbose N] [--rustc-args ARGS] [--] \ ++ "Usage: refinement_checker [--ignore-directives] [--check-unwind] [--verbose N] [--rustc-args ARGS] [--] \ + \n\n\ + Checks that each behavior of each function in the original path is \ + also exhibited by the corresponding function in the verified path\n\n + Options:\n\ +- --ignore-directives Ignore /*@~mut@*/ directives"; ++ --ignore-directives Ignore /*@~mut@*/ directives\n\ ++ --check-unwind Compare cleanup paths without call inlining"; + exit 1 + in + process_args (List.tl (Array.to_list Sys.argv)) +diff --git a/src/refinement_checker/refinement_checker.ml b/src/refinement_checker/refinement_checker.ml +--- a/src/refinement_checker/refinement_checker.ml ++++ b/src/refinement_checker/refinement_checker.ml +@@ -8,6 +8,7 @@ + let verbosity_call = 1 + let verbosity_basic_block = 2 + let verbosity_stmt = 3 ++let check_unwind = ref false + + exception RefinementCheckFailure of string + +@@ -1768,6 +1769,7 @@ + eval_operand operand fallback (fun v -> eval_operands operands fallback (fun vs -> cont (v::vs))) + in + let inline_call0 funcName generic_params substs call (body: body) = ++ if !check_unwind then error "Unwind comparison does not support inlining calls"; + let {args; destination; target; unwind_action} = call in + let args = args |> List.map @@ fun arg -> + eval_operand arg (fun msg -> failwith (msg ^ " are not yet supported as arguments of inlined calls")) (fun v -> v) +@@ -1859,6 +1861,24 @@ + end + | Address _ -> failwith "The scenario where the result variable's address is taken is not yet supported for inlined calls" + end ++ | SwitchInt {discr=Copy {local; projection=[]}; values; targets} when !check_unwind && opnds = [] -> ++ (* A cleanup block may test a drop flag already assigned on this path. *) ++ let path = {lv_caller=i_bb#id.bb_caller; lv_name=local.name} in ++ begin match List.assoc_opt path env with ++ Some (Value (ScalarInt (BoolValue value))) -> ++ let cases, [], [otherwise] = Stringifier.zip_with_remainder values targets in ++ let flag = Stdint.Uint128.of_int (if value then 1 else 0) in ++ let target = match List.find_opt (fun (v, _) -> decode_uint128 v = flag) cases with ++ | Some (_, target) -> target ++ | None -> otherwise ++ in ++ let index = Stdint.Uint32.to_int target.index in ++ if index = i_bb#id.bb_index || List.mem index i_bb#predecessors then done_ () ++ else ++ let target = i_bb#sibling index in ++ process_commands bodies env [] target 0 target#commands ++ | _ -> done_ () ++ end + | Goto {index} when not (List.mem (Stdint.Uint32.to_int index) i_bb#predecessors) -> (* Non-looping jump *) + assert (opnds = []); + let i_bb = i_bb#sibling (Stdint.Uint32.to_int index) in +@@ -2505,6 +2525,18 @@ + if opnds1 <> [] then failwith "opnds1 <> [] at terminator"; + let terminatorKind0 = terminator0.kind in + let terminatorKind1 = terminator1.kind in ++ let check_unwind_actions env0 env1 action0 action1 = ++ if !check_unwind then ++ match action0, action1 with ++ | Cleanup bb0, Cleanup bb1 -> ++ check_basic_block_refines_basic_block ++ env0 (i_bb0#sibling (Stdint.Uint32.to_int bb0.index)) ++ env1 (i_bb1#sibling (Stdint.Uint32.to_int bb1.index)) ++ | Continue, Continue | Terminate, Terminate | Unreachable, Unreachable -> () ++ | _ -> ++ error ("Unwind actions do not match: " ^ Stringifier.string_of_unwind_action action0 ++ ^ " vs " ^ Stringifier.string_of_unwind_action action1) ++ in + match (terminatorKind0, terminatorKind1) with + (Goto bb_id0, Goto bb_id1) -> + let bb_idx0 = Stdint.Uint32.to_int @@ bb_id0.index in +@@ -2537,7 +2569,8 @@ + let retVal1 = List.assoc {lv_caller=None; lv_name=locals1.(0).id.name} env1 in + if retVal0 <> retVal1 then + error (Printf.sprintf "In function %s, at basic block %s in the original crate and basic block %s in the verified crate, the return values %s and %s are not equal" def_path i_bb0#to_string i_bb1#to_string (string_of_local_var_state retVal0) (string_of_local_var_state retVal1)) +- | _, Unreachable -> () ++ | Unreachable, Unreachable -> () ++ | _, Unreachable when not !check_unwind -> () + | (Call call0, Call call1) -> + let func0 = call0.func in + let func1 = call1.func in +@@ -2547,6 +2580,7 @@ + List.combine args0 args1 |> List.iteri (fun i (arg0, arg1) -> + check_operand_refines_operand (i + 1) i_bb0#genv env0 span0 caller0 arg0 i_bb1#genv env1 span1 caller1 arg1 + ); ++ check_unwind_actions env0 env1 call0.unwind_action call1.unwind_action; + let dest0 = call0.destination in + let dest1 = call1.destination in + begin match call0.target, call1.target with +@@ -2569,18 +2603,22 @@ + check_basic_block_refines_basic_block env0 (i_bb0#sibling dest0bbidx) env1 (i_bb1#sibling dest1bbidx) + end + end +- (* TODO: Check that unwindAction0 refines unwindAction1 *) + | Drop drop_data0, Drop drop_data1 -> + let env0, env1 = + match check_place_refines_place env0 caller0 drop_data0.place env1 caller1 drop_data1.place with + Local x0, Local x1 -> + if List.assoc x0 env0 <> List.assoc x1 env1 then error "The two drop terminators drop different values"; + List.remove_assoc x0 env0, List.remove_assoc x1 env1 ++ | LocalProjection x0, LocalProjection x1 -> ++ begin match List.assoc_opt x0 env0, List.assoc_opt x1 env1 with ++ Some (Value v0), Some (Value v1) when values_equal env0 env1 v0 v1 -> env0, env1 ++ | _ -> error "The two drop terminators drop projections of different values" ++ end + | Nonlocal, Nonlocal -> env0, env1 + in + let i_bb_target0 = i_bb0#sibling (Stdint.Uint32.to_int drop_data0.target.index) in + let i_bb_target1 = i_bb1#sibling (Stdint.Uint32.to_int drop_data1.target.index) in +- (* Todo: follow unwind path *) ++ check_unwind_actions env0 env1 drop_data0.unwind_action drop_data1.unwind_action; + check_basic_block_refines_basic_block env0 i_bb_target0 env1 i_bb_target1 + | TailCall, TailCall -> error "TailCall not supported" + | Assert assert0, Assert assert1 -> +@@ -2588,7 +2626,7 @@ + if assert0.expected <> assert1.expected then error "The two assert terminators expect different values"; + let i_bb_target0 = i_bb0#sibling (Stdint.Uint32.to_int assert0.target.index) in + let i_bb_target1 = i_bb1#sibling (Stdint.Uint32.to_int assert1.target.index) in +- (* Todo: follow unwind path *) ++ check_unwind_actions env0 env1 assert0.unwind_action assert1.unwind_action; + check_basic_block_refines_basic_block env0 i_bb_target0 env1 i_bb_target1 + | Yield, Yield -> error "Yield not supported" + | CoroutineDrop, CoroutineDrop -> error "CoroutineDrop not supported" diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0013-shared-initialized-slice.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0013-shared-initialized-slice.patch new file mode 100644 index 0000000000000..2e3ada74054fa --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0013-shared-initialized-slice.patch @@ -0,0 +1,93 @@ +--- a/bin/rust/aliasing.rsspec ++++ b/bin/rust/aliasing.rsspec +@@ -102,7 +102,7 @@ + // Unsizing preserves the lifetime and reference tag of the array borrow. + fn unsize_shared_array_ref(array: &'a [T; N]) -> &'a [T]; + //@ req [?f]ref_initialized(array); +-//@ ens [f]ref_initialized(array) &*& result as *T == array as *T &*& result.len() == int_of_const(typeid(N)); ++//@ ens [f]ref_initialized(array) &*& [_]ref_initialized(result) &*& strip_pointer_metadata(result as pointer) == array as pointer &*& result as *T == array as *T &*& result.len() == int_of_const(typeid(N)); + //@ on_unwind_ens false; + + fn unsize_mut_array_ref(array: &'a mut [T; N]) -> &'a mut [T]; +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -2634,8 +2634,14 @@ + begin match substs_cpn, substs with + | [_; { kind = Type { kind = UInt USize } }; _], [element; _; lifetime] -> + translate_regular_fn_call [element; lifetime] "std::slice::get_unchecked_usize" ++ | [_; { kind = Type { kind = Adt { id = { name = "std::ops::RangeTo" }; ++ substs = [{ kind = Type { kind = UInt USize } }] } } }; _], ++ [element; _; lifetime] -> ++ translate_regular_fn_call [element; lifetime] "std::slice::get_unchecked_range_to" + | _ -> translate_regular_fn_call substs fn_name + end ++ | "<[std::mem::MaybeUninit]>::assume_init_ref" -> ++ translate_regular_fn_call substs "std::mem::assume_init_slice_ref" + | "std::slice::::get_unchecked_mut" -> + begin match substs_cpn, substs with + | [_; { kind = Type { kind = UInt USize } }; _], [element; _; lifetime] -> +--- a/bin/rust/std/lib.rsspec ++++ b/bin/rust/std/lib.rsspec +@@ -492,6 +492,11 @@ + + impl MaybeUninit { + ++ unsafe fn assume_init_mut<'a>(self: &'a mut MaybeUninit) -> &'a mut T; ++ //@ req *self |-> ?bits &*& bits.inner() == some(?value); ++ //@ ens *result |-> value &*& ref_mut_end_token(result, self as *T) &*& ref_origin(result) == ref_origin(self as *T); ++ //@ on_unwind_ens false; ++ + fn write<'a>(self: &'a mut MaybeUninit, value: T) -> &'a mut T; + //@ req *self |-> _; + //@ ens *self |-> MaybeUninit::new(value); +@@ -499,6 +504,30 @@ + + } + ++ /*@ ++ fix initialized_slots(slots: list>) -> bool { ++ match slots { ++ nil => true, ++ cons(slot, tail) => slot.inner() != none && initialized_slots(tail) ++ } ++ } ++ @*/ ++ ++ unsafe fn assume_init_slice_ref(self: &'a [MaybeUninit]) -> &'a [T]; ++ /*@ ++ req [?f]ref_initialized(self) &*& [?q]lifetime_token('a) &*& ++ [?g](strip_pointer_metadata(self as pointer) as *MaybeUninit)[..self.len()] |-> ?slots &*& ++ initialized_slots(slots) == true &*& ++ object_pointer_within_limits(strip_pointer_metadata(self as pointer) as *u8, self.len() * std::mem::size_of::()) == true &*& ++ (strip_pointer_metadata(self as pointer).address % std::mem::align_of::()) == 0 &*& ++ self.len() * std::mem::size_of::() <= isize::MAX; ++ @*/ ++ /*@ ++ ens [f]ref_initialized(self) &*& [q]lifetime_token('a) &*& [_]ref_initialized(result) &*& ++ [g](strip_pointer_metadata(self as pointer) as *MaybeUninit)[..self.len()] |-> slots &*& ++ result as pointer == self as pointer; ++ @*/ ++ //@ on_unwind_ens false; + struct Alignment; + + //@ fix Alignment::as_nonzero_usize(align: Alignment) -> std::num::NonZero; +@@ -789,6 +818,19 @@ + //@ ens [f]ref_initialized(element) &*& result == element; + //@ on_unwind_ens false; + ++ // RangeTo starts at zero, so the shared pointer keeps its origin and base. ++ unsafe fn get_unchecked_range_to(self: &'a [T], index: std::ops::RangeTo) -> &'a [T]; ++ /*@ ++ req [?f]ref_initialized(self) &*& 0 <= index.end &*& index.end <= self.len() &*& ++ [?g](strip_pointer_metadata(self as pointer) as *T)[..self.len()] |-> ?items; ++ @*/ ++ /*@ ++ ens [f]ref_initialized(self) &*& [_]ref_initialized(result) &*& ++ [g](strip_pointer_metadata(self as pointer) as *T)[..self.len()] |-> items &*& ++ strip_pointer_metadata(result as pointer) == strip_pointer_metadata(self as pointer) &*& result.len() == index.end; ++ @*/ ++ //@ on_unwind_ens false; ++ + unsafe fn get_unchecked_mut_range(self: &'a mut [T], index: std::ops::Range) -> &'a mut [T]; + /*@ + req 0 <= index.start &*& index.start <= index.end &*& index.end <= self.len() &*& diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0014-raw-slice-access.patch b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0014-raw-slice-access.patch new file mode 100644 index 0000000000000..f3253cdc12e93 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/0014-raw-slice-access.patch @@ -0,0 +1,85 @@ +--- a/bin/rust/aliasing.rsspec ++++ b/bin/rust/aliasing.rsspec +@@ -137,3 +137,9 @@ + //@ req true; // TODO + //@ ens result == x; + //@ on_unwind_ens false; ++ ++// Array-to-slice raw unsizing attaches metadata without borrowing the array. ++fn unsize_raw_array_ptr(array: *[T; N]) -> *[T]; ++//@ req true; ++//@ ens strip_pointer_metadata(result as pointer) == array as pointer &*& result.len() == int_of_const(typeid(N)); ++//@ on_unwind_ens false; +--- a/bin/rust/std/lib.rsspec ++++ b/bin/rust/std/lib.rsspec +@@ -492,6 +492,17 @@ + + impl MaybeUninit { + ++ unsafe fn assume_init_ref<'a>(self: &'a MaybeUninit) -> &'a T; ++ /*@ ++ req [?f](*self |-> ?bits) &*& bits.inner() == some(?value) &*& ++ [?g]ref_initialized(self) &*& [?q]lifetime_token('a); ++ @*/ ++ /*@ ++ ens [f](*self |-> bits) &*& [g]ref_initialized(self) &*& [q]lifetime_token('a) &*& ++ [_]frac_borrow('a, ref_initialized_(result)) &*& result as pointer == self as pointer; ++ @*/ ++ //@ on_unwind_ens false; ++ + unsafe fn assume_init_mut<'a>(self: &'a mut MaybeUninit) -> &'a mut T; + //@ req *self |-> ?bits &*& bits.inner() == some(?value); + //@ ens *result |-> value &*& ref_mut_end_token(result, self as *T) &*& ref_origin(result) == ref_origin(self as *T); +@@ -628,6 +639,19 @@ + //@ ens result as *T == data &*& result.len() == len; + //@ on_unwind_ens false; + ++ // Access the original allocation by offset. No references or memory ++ // permissions are created by raw indexing. ++ unsafe fn slice_get_unchecked_usize(self: *[T], index: usize) -> *T; ++ /*@ ++ req 0 <= index &*& index < self.len() &*& strip_pointer_metadata(self as pointer).address != 0 &*& ++ object_pointer_within_limits(strip_pointer_metadata(self as pointer) as *u8, self.len() * std::mem::size_of::()) == true &*& ++ strip_pointer_metadata(self as pointer).address % std::mem::align_of::() == 0 &*& ++ self.len() * std::mem::size_of::() <= isize::MAX &*& ++ [?f](*((strip_pointer_metadata(self as pointer) as *T) + index) |-?-> ?slot); ++ @*/ ++ //@ ens result == (strip_pointer_metadata(self as pointer) as *T) + index &*& [f](*result |-?-> slot); ++ //@ on_unwind_ens false; ++ + unsafe fn drop_in_place(to_drop: *mut T); + //@ req thread_token(?t) &*& *to_drop |-> ?v &*& .own(t, v); + //@ ens thread_token(t) &*& *to_drop |-> _; +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -2630,6 +2630,13 @@ + Ok + ( tmp_rvalue_binders, + FnCallResult (CastExpr (fn_loc, PtrTypeExpr (fn_loc, ManifestTypeExpr (fn_loc, Int (Unsigned, FixedWidthRank 0))), arg)) ) ++ | "std::ptr::const_ptr::::get_unchecked" ++ | "std::ptr::mut_ptr::::get_unchecked_mut" -> ++ begin match substs_cpn, substs with ++ | [_; { kind = Type { kind = UInt USize } }], [element; _] -> ++ translate_regular_fn_call [element] "std::ptr::slice_get_unchecked_usize" ++ | _ -> translate_regular_fn_call substs fn_name ++ end + | "std::slice::::get_unchecked" -> + begin match substs_cpn, substs with + | [_; { kind = Type { kind = UInt USize } }; _], [element; _; lifetime] -> +@@ -3453,6 +3460,16 @@ + Static )) + in + Ok (`TrRvalueExpr (result_of_outcome loc e)) ++ | { kind = PointerCoercion; ty = { kind = RawPtr { ty = { kind = Slice _ } } }; ++ operand = (Copy {projection=[]} | Move {projection=[]}) } -> ++ (* An array's raw pointer coercion changes the metadata alone. *) ++ let expr = ++ match operand with ++ | `TrOperandCopy expr | `TrOperandMove (expr, _) -> expr ++ | _ -> Ast.static_error loc "Expected an array pointer operand for slice unsizing" None ++ in ++ let call = Ast.CallExpr (loc, "unsize_raw_array_ptr", [], [], [LitPat expr], Static) in ++ Ok (`TrRvalueExpr (result_of_outcome loc call)) + | { kind = PointerCoercion; ty = { kind = Ref { mutability; ty = { kind = Slice _ } } } } -> + (* Array-to-slice coercion keeps the reference tag and adds the array length. *) + let expr = diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/README.md b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/README.md new file mode 100644 index 0000000000000..38817da960b4f --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/README.md @@ -0,0 +1,103 @@ +# VeriFast changes for the B-tree proofs + +The B-tree verification entry builds VeriFast **26.10** at +`f76012fb518703b1d98e243ac4f487f16877cfcb` with the 14 patches in this +directory. On 2026-11-24, the latest tagged release was 26.10. Upstream +`master` at `0a83dba42db7ce0b445034ece5298afe980e57dc` adds one build +commit. The changes to the Rust frontend and checker select the toolchain +through `RUSTUP_TOOLCHAIN`. The affected MIR lowering, refinement rules, +and Rust specifications match the release. [Release][release] · [Source comparison][compare] + +## Necessity and upstream status + +Each row identifies the production obligation served by the patch and the +available rollback or regression evidence. The contracts rely on the +pointer, ownership, and lifetime premises described in the row. + +| Patch | Scope and rollback result | Upstream status | +| --- | --- | --- | +| 0001 | Refinement compares the exported raw pointer kind and place, including projections, and takes account of address-taken locals. The existing normalization is limited to metadata and the simple mutable-reference reservation lowering. Removing the paired rule blocks production MIR comparison. Narrowing the normalization to metadata alone breaks the upstream reservation regression. | [#1062][raw-pr] addresses [#1040][raw-issue]. It compares place and mutability. Its checker change passed all three B-tree MIR comparisons when substituted into the otherwise patched tool. The more conservative kind export is local. [#1064][hardening] includes the same checker change as #1062. Both PRs are open. | +| 0002 | Box dereference lowering extracts the normal result of the pointer projection. The raw projection cannot unwind and preserves the owned Box storage. Reverting the lowering leaves a `fn_outcome` where the generated code needs a pointer. | [#786][box-base] provides the merged baseline Box support. I found no PR for this outcome fix. | +| 0003 | Fixed-array MIR projections retain the evaluated index and the element type. Reads and stores compare the corresponding operand and place, and the Rust MIR bounds assertion stays in the proof. Disabling the projection blocks translation of the production edge write. | [#1048][const-generic] partially overlaps typesystem constant operands. [#994][arrays] improves static-array handling. Both are open and leave this MIR projection unsupported. | +| 0004 | Opening a points-to assertion for an initialized array reuses its stored element list. The uninitialized case still uses its separate predicate. Without the fix the proof loses the known values when it reopens the array. | The initialized `Term` case in open [#994][arrays] already implements the same fix. | +| 0005 | Shared array unsizing preserves the reference's address, tag, and lifetime, and adds the static length. The `usize` unchecked read requires an in-bounds element and its shared loan. Removing the coercion blocks the production edge read used by relinking. | Merged [#1001][shared-slice] supplies shared slice types. I found no equivalent array-to-slice projection PR. | +| 0006 | Mutable array unsizing preserves the same loan. An in-bounds `usize`, `Range`, or `RangeTo` projection transfers exclusive ownership and restores it when the loan ends. The negative regression attempts a write through the original pointer while the element is borrowed. Removing mutable coercion blocks the production transfers. | Merged [#1015][mut-slice] and [#1027][slice-contracts] supply slice types and generated in-out contracts. I found no PR for these projection rules. | +| 0007 | The explicit `track_ref_creation` directive uses the existing fresh-mutable-reference rule on the selected places. The rule consumes the original points-to ownership and records the origin and end token. Without it the proof lacks the loan token for a production node projection. | I found no equivalent opt-in directive. | +| 0008 | Array `IndexMut>` requires that the end is within the static length and consumes exactly the prefix's permission. The regression supplies twelve slots to an eleven-element array type so an oversized end is rejected by the bound itself. Without the specialization, the native split's prefix projection has no dispatch rule. | Related to [#994][arrays] and the merged slice support. I found no equivalent `IndexMut` rule. | +| 0009 | The exporter folds an adjacent, retag-free Box copy and pointer projection through a mutable Box reference when that projection is the temporary's sole read. The checker keeps the source dereference and Box pointer projection. Without the fold the full split proof cannot recover the borrowed Box's points-to permission. | [#786][box-base] is the baseline. I found no PR for this MIR shape. | +| 0010 | Address-taken analysis continues after `merge_fractions`. This restores traversal of the remaining statements, with no change to the proof rules for fractions. The split proof and a standalone raw-borrow regression fail without it. | Merged [#1023][address-local] addresses locals in projection clauses. I found no fix for the `merge_fractions` traversal. | +| 0011 | Rust field provenance cannot determine the parent address. The patch removes the incompatible inverse axiom. When restored, the B-tree run reports inconsistent axiom instantiation and still exits successfully with fewer verified statements. The regression rejects equality of projections from different addresses. | Merged [#538][c-provenance] fixed a related axiom in the C prelude. The Rust axiom remains on master. | +| 0012 | MIR `Drop` follows the compiler's normal and unwind actions. Strict refinement compares cleanup edges from calls, drops, and assertions, including projected drop places. It follows a copied plain local's branch when its value is already a known boolean. The merge comparison needs this rule for a compiler drop flag after the key has moved. Symbolic and address-taken locals still use the regular comparison. The generic-drop, layout, and changed-cleanup-order regressions check these rules. | Merged [#664][unwind] provides the general unwind handling. Open [#1046][manual-drop] concerns `ManuallyDrop::new`. Open [#1036][nested] and [#1058][nested2] concern nested specifications. I found no matching fix for `Drop` terminators or strict drop-flag comparison. | +| 0013 | `NodeRef::keys` needs shared `RangeTo` indexing and a typed slice view of the initialized prefix. Indexing preserves the base address and shortens the metadata. Scalar `assume_init_mut` transfers an initialized slot and supplies its borrow end token. The B-tree regressions reject an uninitialized prefix and a second exclusive borrow. | Neither the current release nor master supplies these dispatch and initialized-view rules. [#1001][shared-slice] and [#1015][mut-slice] supply the underlying slice reference types. | +| 0014 | `ValMut` uses raw array unsizing and raw slot indexing to leave the other value loans in place. The index checks pointer geometry and preserves the existing permission for the addressed slot. The shared projection requires an initialized slot, and the exclusive projection requires full ownership. | Open [#1061][raw-slice-fields] adds type interpretations for raw slice pointer fields. Open [#1035][raw-slice-aggregate] lowers construction from data and metadata. The coercion, indexing, and initialized-slot operations in this patch are separate. | + +The B-tree proof also installs a temporary set of library contracts described +in the [proof README](../README.md#library-specifications). These are reviewed +as specifications in addition to the frontend patches. Open [#1037][tuple1] +and [#1057][tuple2] overlap its one- and two-element tuple ownership rules. + +## Upstream submissions + +Follow [#1062][raw-pr] and [#994][arrays] for the overlapping changes and +discuss exporting the raw pointer kind in #1062. The remaining changes fit +seven new PRs. + +| Proposed PR | Local patches | Review scope | +| --- | --- | --- | +| Rust Box pointer projection | 0002, 0009 | Extract the normal result of Box pointer projection and handle the borrowed-Box MIR shape. | +| Fixed-array MIR projections | 0003 | Carry the evaluated index and element type through MIR export and refinement. Coordinate constant operands with [#1048][const-generic]. | +| Array-to-slice projections | 0005, 0006, 0008, 0013, 0014 | Cover shared unsizing, exclusive element and range borrows, checked prefix indexing, and raw offset calculation. Include the initialized-view contracts and rejection tests. | +| Scoped mutable reference creation | 0007 | Track the transfer and return of a mutable place's permissions. | +| Address scanning after `merge_fractions` | 0010 | Continue scanning the remaining statements and verify the standalone raw-borrow regression. | +| Rust field provenance | 0011 | Remove the inconsistent Rust axiom and keep the distinct-address regression with the fix. | +| Rust MIR `Drop` unwind | 0012 | Follow compiler cleanup actions in the verifier and in direct refinement comparisons. Include known drop-flag handling, the generic destructor regression, and the cleanup-order regression. | + +Submit the provenance and `Drop` fixes first so each can be reviewed and +merged independently. The scoped borrow change builds on the mutable borrow +dispatch in 0006. Run the borrowed-Box regression on top of that change +because the regression uses its tracking directive. Refresh overlapping +translator and test registration hunks against each PR's base. + +## Reproducing the B-tree check + +Run the same command as the repository's VeriFast runner from a Linux +x86_64 checkout. The build compiles the verifier, refinement checker, +and exporter together with a common MIR schema. + +```sh +bash verifast-proofs/alloc/collections/btree/node.rs/verify.sh --ci +``` + +On patched 26.10, all 48 upstream Rust refinement-checker cases and 11 +patch-registered Rust verifier cases produced their expected outcomes. +Stock 26.10 loses the initialized array values in `keep_array`, reports +an axiom inconsistency in `field_projection_addresses.rs`, and accepts the +false no-unwind contract in `drop_cleanup.rs`. The corresponding patched +tests pass with their expected rejections. All 14 patches and the +B-tree library specification diff apply to the inspected `master` revision. + +The patches include regression entries in the upstream Rust and refinement +testsuites. The B-tree negative suite independently checks the production +proof and its correspondence. + +[release]: https://github.com/verifast/verifast/releases/tag/26.10 +[compare]: https://github.com/verifast/verifast/compare/26.10...0a83dba42db7ce0b445034ece5298afe980e57dc +[raw-issue]: https://github.com/verifast/verifast/issues/1040 +[raw-pr]: https://github.com/verifast/verifast/pull/1062 +[hardening]: https://github.com/verifast/verifast/pull/1064 +[box-base]: https://github.com/verifast/verifast/pull/786 +[const-generic]: https://github.com/verifast/verifast/pull/1048 +[arrays]: https://github.com/verifast/verifast/pull/994 +[shared-slice]: https://github.com/verifast/verifast/pull/1001 +[mut-slice]: https://github.com/verifast/verifast/pull/1015 +[slice-contracts]: https://github.com/verifast/verifast/pull/1027 +[address-local]: https://github.com/verifast/verifast/pull/1023 +[c-provenance]: https://github.com/verifast/verifast/pull/538 +[unwind]: https://github.com/verifast/verifast/pull/664 +[manual-drop]: https://github.com/verifast/verifast/pull/1046 +[nested]: https://github.com/verifast/verifast/pull/1036 +[nested2]: https://github.com/verifast/verifast/pull/1058 +[tuple1]: https://github.com/verifast/verifast/pull/1037 +[tuple2]: https://github.com/verifast/verifast/pull/1057 +[raw-slice-fields]: https://github.com/verifast/verifast/pull/1061 +[raw-slice-aggregate]: https://github.com/verifast/verifast/pull/1035 diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/build.sh b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/build.sh new file mode 100644 index 0000000000000..203ccbe3274c9 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/build.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +set -euo pipefail + +patch_dir=$(cd "$(dirname "$0")" && pwd) +destination=$(cd "${1:?Pass an empty tool installation directory}" && pwd) +build_dir=$(mktemp -d) +trap 'rm -rf -- "$build_dir"' EXIT + +git clone --quiet --depth 1 --branch 26.10 https://github.com/verifast/verifast.git "$build_dir/verifast" +cd "$build_dir/verifast" +test "$(git rev-parse HEAD)" = f76012fb518703b1d98e243ac4f487f16877cfcb +for patch in "$patch_dir"/*.patch; do + git apply "$patch" +done + +# Use the dependency archive pinned by VeriFast 26.10's setup-build.sh. +. ./config.sh +deps="/tmp/$VFDEPS_NAME" +if [[ ! -x "$deps/bin/dune" ]]; then + archive="$build_dir/$VFDEPS_NAME-linux.txz" + curl -fLsS --retry 3 "https://github.com/verifast/vfdeps/releases/download/25.01/$VFDEPS_NAME-linux.txz" -o "$archive" + printf '8d022c93d51a1d13ec1e782d767c60462405f6865d5ee416f82d6234e93ee580 %s\n' "$archive" | sha256sum --check + tar -xf "$archive" -C /tmp +fi + +cargo +stable install --locked --root "$build_dir/decoder" \ + --git https://github.com/btj/capnpc-ocaml-decoder --rev 2d6606d9b59cd0c88a66729f3f076c10c0c8e0b2 +export PATH="$build_dir/decoder/bin:$deps/bin:$PATH" +export CAPNP_INC_DIR="$deps/include" CAPNP_INCLUDE="$deps/include" +export LIBRARY_PATH="$deps/lib${LIBRARY_PATH:+:$LIBRARY_PATH}" +export LD_LIBRARY_PATH="$deps/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" + +( + cd src + dune build -j 2 vfconsole/vfconsole.exe refinement_checker/main.exe +) +cargo build --locked --release --jobs 2 --target-dir "$build_dir/target" \ + --manifest-path src/rust_frontend/vf_mir_exporter/Cargo.toml + +mkdir "$destination/bin" +cp -a bin/. "$destination/bin/" +install -m 755 src/_build/default/vfconsole/vfconsole.exe "$destination/bin/verifast" +install -m 755 src/_build/default/refinement_checker/main.exe "$destination/bin/refinement-checker" +install -m 755 "$build_dir/target/release/vf_mir_exporter" "$destination/bin/vf-rust-mir-exporter" +cp "$deps/lib/libz3.so" "$destination/bin/" diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verified/insertion.rs b/verifast-proofs/alloc/collections/btree/node.rs/verified/insertion.rs new file mode 100644 index 0000000000000..ecc5afe671168 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verified/insertion.rs @@ -0,0 +1,12270 @@ +#![feature(allocator_ext)] +#![feature(slice_ptr_get)] +//! Ancestor ownership and the key, value, and child moves used during splitting. +//! Refinement checks the production `as_leaf_ptr` and `set_parent_link`. + +#![allow(dead_code)] + +use std::marker::PhantomData; +use std::mem::MaybeUninit; +use std::ptr::NonNull; + +//@ use std::mem::{MaybeUninit, open_MaybeUninit, close_MaybeUninit}; +//@ use std::option::Option; +//@ use std::ptr::NonNull; + +const B: usize = 6; + +const CAPACITY: usize = 2 * B - 1; + +//@ fix B() -> usize { 6 } + +//@ fix CAPACITY() -> usize { 2 * B - 1 } + +struct LeafNode { + /// We want to be covariant in `K` and `V`. + parent: Option>>, + + /// This node's index into the parent node's `edges` array. + /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`. + /// This is only guaranteed to be initialized when `parent` is non-null. + parent_idx: MaybeUninit, + + /// The number of keys and values this node stores. + len: u16, + + /// The arrays storing the actual data of the node. Only the first `len` elements of each + /// array are initialized and valid. + keys: [MaybeUninit; CAPACITY], + vals: [MaybeUninit; CAPACITY], +} + +#[repr(C)] +struct InternalNode { + data: LeafNode, + + /// The pointers to the children of this node. `len + 1` of these are considered + /// initialized and valid, except that near the end, while the tree is held + /// through borrow type `Dying`, some of these pointers are dangling. + edges: [MaybeUninit>; 2 * B], +} + +type BoxedNode = NonNull>; + +struct NodeRef { + /// The number of levels that the node and the level of leaves are apart, a + /// constant of the node that cannot be entirely described by `Type`, and that + /// the node itself does not store. We only need to store the height of the root + /// node, and derive every other node's height from it. + /// Must be zero if `Type` is `Leaf` and non-zero if `Type` is `Internal`. + height: usize, + /// The pointer to the leaf or internal node. The definition of `InternalNode` + /// ensures that the pointer is valid either way. + node: NonNull>, + _marker: PhantomData<(BorrowType, Type)>, +} + +mod marker { + use super::PhantomData; + pub(crate) struct Immut<'a>(PhantomData<&'a ()>); + pub(crate) struct Mut<'a>(PhantomData<&'a mut ()>); + pub(crate) struct ValMut<'a>(PhantomData<&'a mut ()>); + pub(crate) enum LeafOrInternal {} + pub(crate) enum DormantMut {} + pub(crate) enum Owned {} + pub(crate) enum Dying {} + pub(crate) enum Leaf {} + pub(crate) enum Internal {} + pub(crate) enum KV {} + pub(crate) enum Edge {} + pub(crate) trait BorrowType { + const TRAVERSAL_PERMIT: bool = true; + } + impl BorrowType for Owned { + const TRAVERSAL_PERMIT: bool = false; + } + impl BorrowType for Dying {} + impl BorrowType for DormantMut {} + impl BorrowType for Immut<'_> {} + impl BorrowType for Mut<'_> {} + impl BorrowType for ValMut<'_> {} +} + +// BEGIN_ANCESTOR_PROOF +/*@ +// Keep exact ancestor storage, including inactive slots that must stay unchanged. +inductive ParentPayload = ParentPayload( + list>, list>, list>>> +); +inductive ParentStep = ParentStep(*InternalNode, u16, u16, ParentPayload); + +pred link(child: *LeafNode, parent: Option>>, index: u16;) = + (*child).parent |-> parent &*& + if parent == Option::None { + index == 0 + } else { + (*child).parent_idx |-> MaybeUninit::new(index) + }; + +pred parent_payload( + child: *LeafNode, parent: *InternalNode, index: u16, len: u16, payload: ParentPayload; +) = + parent != 0 &*& pointer_within_limits(parent) == true &*& pointer_within_limits(&(*parent).data) == true &*& + 0 <= index &*& index <= len &*& len <= CAPACITY &*& + match payload { + ParentPayload(keys, vals, edges) => + (*parent).data.len |-> len &*& + (*parent).data.keys[..CAPACITY] |-> keys &*& + (*parent).data.vals[..CAPACITY] |-> vals &*& + (*parent).edges[..CAPACITY + 1] |-> edges &*& + nth(index, edges) == MaybeUninit::new(NonNull::new(child)) + }; + +pred ancestors(child: *LeafNode, path: list>, root: *LeafNode;) = + match path { + nil => child == root &*& link(child, Option::None, 0), + cons(step, rest) => + match step { + ParentStep(parent, idx, len, payload) => + link(child, Option::Some(NonNull::new(parent)), idx) &*& + parent_payload(child, parent, idx, len, payload) &*& + ancestors(&(*parent).data, rest, root) + } + }; + +@*/ + +// The raw-pointer form uses the exact two stores extracted from the NodeRef method. +unsafe fn write_child_backlink( + leaf: *mut LeafNode, + parent: NonNull>, + parent_idx: usize, +) +//@ req thread_token(?t) &*& (*leaf).parent |-> _ &*& (*leaf).parent_idx |-> _ &*& parent_idx <= CAPACITY; +//@ ens thread_token(t) &*& (*leaf).parent |-> Option::Some(parent) &*& (*leaf).parent_idx |-> MaybeUninit::new(parent_idx as u16); +//@ on_unwind_ens false; +{ + unsafe { (*leaf).parent = Some(parent) }; + //@ open LeafNode_parent_idx_(leaf, _); + //@ points_to__limits(&(*leaf).parent_idx); + unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; +} + +/*@ +pred child_headers(children: list>>;) = + match children { + nil => true, + cons(child, rest) => + (*child.as_ptr()).parent |-> _ &*& (*child.as_ptr()).parent_idx |-> _ &*& child_headers(rest) + }; + +pred linked_headers(children: list>>, parent: NonNull>, index: usize;) = + match children { + nil => true, + cons(child, rest) => + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new(index as u16) &*& + linked_headers(rest, parent, index + 1) + }; + +lem append_linked_header(prefix: list>>, child: NonNull>, parent: NonNull>, first: usize) + req linked_headers(prefix, parent, first) &*& + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new((first + length(prefix)) as u16); + ens linked_headers(append(prefix, [child]), parent, first); +{ + open linked_headers(prefix, parent, first); + match prefix { + nil => { close linked_headers([], parent, first + 1); } + cons(old, rest) => { append_linked_header(rest, child, parent, first + 1); } + } + close linked_headers(append(prefix, [child]), parent, first); +} + +fix initialized_edges(children: list>>) -> list>>> { + match children { + nil => nil, + cons(child, rest) => cons(MaybeUninit::new(child), initialized_edges(rest)) + } +} + +lem initialized_edges_append(a: list>>, b: list>>) + req true; + ens initialized_edges(append(a, b)) == append(initialized_edges(a), initialized_edges(b)); +{ + match a { + nil => {} + cons(child, rest) => { initialized_edges_append(rest, b); } + } +} + +lem initialized_edge_count(children: list>>) + req true; + ens length(initialized_edges(children)) == length(children); +{ + match children { + nil => {} + cons(child, rest) => { initialized_edge_count(rest); } + } +} + +lem empty_list_if_zero(items: list) + req length(items) == 0; + ens items == []; +{ + match items { + nil => {} + cons(item, more) => {} + } +} + +lem unpack_nonempty(items: list) + req length(items) > 0; + ens items == cons(?item, ?more); +{ + match items { nil => {} cons(item, more) => {} } +} +@*/ + +unsafe fn repair_edges(parent: NonNull>, start: usize, end: usize) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + start <= end &*& end <= CAPACITY + 1 &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + (*parent.as_ptr()).edges[start..end] |-> ?bits &*& child_headers(?children) &*& + bits == initialized_edges(children) &*& length(children) == end - start; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + (*parent.as_ptr()).edges[start..end] |-> initialized_edges(children) &*& + linked_headers(children, parent, start); +@*/ +//@ on_unwind_ens false; +{ + let parent_ptr = parent.as_ptr(); + let base = unsafe { (&raw const (*parent_ptr).edges) as *const MaybeUninit> }; + let mut i = start; + //@ close array(base + start, 0, []); + //@ close linked_headers([], parent, start); + loop { + /*@ + inv thread_token(t) &*& lifetime_token(func_lft) &*& type_interp::() &*& type_interp::() &*& + start <= i &*& i <= end &*& end <= CAPACITY + 1 &*& + (*parent_ptr).edges[start..i] |-> ?prefix_bits &*& + (*parent_ptr).edges[i..end] |-> ?rest_bits &*& + linked_headers(?prefix, parent, start) &*& child_headers(?rest) &*& + prefix_bits == initialized_edges(prefix) &*& rest_bits == initialized_edges(rest) &*& + children == append(prefix, rest) &*& length(prefix) == i - start &*& length(rest) == end - i; + @*/ + if i == end { + break; + } + //@ unpack_nonempty(rest); + //@ assert rest == cons(?child, ?remaining); + //@ open array(base + i, end - i, initialized_edges(rest)); + //@ open_MaybeUninit(base + i); + let edge = unsafe { *(base.add(i) as *const NonNull>) }; + //@ close_MaybeUninit(base + i); + //@ close array(base + i + 1, 0, []); + //@ close array(base + i, 1, initialized_edges([child])); + //@ open child_headers(rest); + unsafe { write_child_backlink(edge.as_ptr(), parent, i) }; + //@ append_linked_header(prefix, child, parent, start); + //@ array_join(base + start); + //@ initialized_edges_append(prefix, [child]); + //@ append_assoc(prefix, [child], remaining); + i += 1; + } + //@ assert child_headers(?unrepaired); + //@ assert linked_headers(?repaired, parent, start); + //@ empty_list_if_zero(unrepaired); + //@ append_nil(repaired); + //@ open child_headers(unrepaired); + //@ array_join(base + start); +} + +unsafe fn move_split_edges( + left: NonNull>, + right: NonNull>, + pivot: usize, + old_len: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& pivot < old_len &*& old_len <= CAPACITY &*& + pointer_within_limits(&(*left.as_ptr()).edges) == true &*& + pointer_within_limits(&(*right.as_ptr()).edges) == true &*& + (*left.as_ptr()).edges[pivot + 1..old_len + 1] |-> ?edges &*& + (*right.as_ptr()).edges[..old_len - pivot] |-> _ &*& + child_headers(?children) &*& edges == initialized_edges(children) &*& length(children) == old_len - pivot; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + (*left.as_ptr()).edges[pivot + 1..old_len + 1] |-> edges &*& + (*right.as_ptr()).edges[..old_len - pivot] |-> edges &*& linked_headers(children, right, 0); +@*/ +//@ on_unwind_ens false; +{ + let src = unsafe { (&raw const (*left.as_ptr()).edges) as *const MaybeUninit> }; + let dst = unsafe { (&raw mut (*right.as_ptr()).edges) as *mut MaybeUninit> }; + unsafe { std::ptr::copy_nonoverlapping(src.add(pivot + 1), dst, old_len - pivot) }; + unsafe { repair_edges(right, 0, old_len - pivot) }; +} + +// Match the storage effects of moving the key, value, and edge suffixes. A +// separate Kani contract checks the pivot read in the native split_leaf_data. +unsafe fn split_preserves_ancestors( + left: NonNull>, + right: NonNull>, + pivot: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + ancestors(&(*left.as_ptr()).data, ?path, ?root) &*& link(&(*right.as_ptr()).data, Option::None, 0) &*& + (*left.as_ptr()).data.len |-> ?old_len &*& (*right.as_ptr()).data.len |-> 0 &*& pivot < old_len &*& old_len <= CAPACITY &*& + pointer_within_limits(&(*left.as_ptr()).edges) == true &*& + pointer_within_limits(&(*right.as_ptr()).edges) == true &*& + (*left.as_ptr()).edges[pivot + 1..old_len + 1] |-> ?edges &*& + (*right.as_ptr()).edges[..old_len - pivot] |-> _ &*& + child_headers(?children) &*& edges == initialized_edges(children) &*& length(children) == old_len - pivot &*& + pointer_within_limits(&(*left.as_ptr()).data.keys) == true &*& + pointer_within_limits(&(*left.as_ptr()).data.vals) == true &*& + pointer_within_limits(&(*right.as_ptr()).data.keys) == true &*& + pointer_within_limits(&(*right.as_ptr()).data.vals) == true &*& + (*left.as_ptr()).data.keys[pivot + 1..old_len] |-> ?keys &*& + (*left.as_ptr()).data.vals[pivot + 1..old_len] |-> ?vals &*& + (*right.as_ptr()).data.keys[..old_len - pivot - 1] |-> _ &*& + (*right.as_ptr()).data.vals[..old_len - pivot - 1] |-> _; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + ancestors(&(*left.as_ptr()).data, path, root) &*& link(&(*right.as_ptr()).data, Option::None, 0) &*& + (*left.as_ptr()).data.len |-> (pivot as u16) &*& (*right.as_ptr()).data.len |-> ((old_len - pivot - 1) as u16) &*& + (*left.as_ptr()).edges[pivot + 1..old_len + 1] |-> edges &*& + (*right.as_ptr()).edges[..old_len - pivot] |-> edges &*& linked_headers(children, right, 0) &*& + (*left.as_ptr()).data.keys[pivot + 1..old_len] |-> keys &*& + (*left.as_ptr()).data.vals[pivot + 1..old_len] |-> vals &*& + (*right.as_ptr()).data.keys[..old_len - pivot - 1] |-> keys &*& + (*right.as_ptr()).data.vals[..old_len - pivot - 1] |-> vals; +@*/ +//@ on_unwind_ens false; +{ + let src = left.as_ptr(); + let dst = right.as_ptr(); + let len = unsafe { (*src).data.len } as usize; + let new_len = len - pivot - 1; + unsafe { + (*dst).data.len = new_len as u16; + let src_keys = ((&raw const (*src).data.keys) as *const MaybeUninit); + let src_vals = ((&raw const (*src).data.vals) as *const MaybeUninit); + let dst_keys = ((&raw mut (*dst).data.keys) as *mut MaybeUninit); + let dst_vals = ((&raw mut (*dst).data.vals) as *mut MaybeUninit); + std::ptr::copy_nonoverlapping(src_keys.add(pivot + 1), dst_keys, new_len); + std::ptr::copy_nonoverlapping(src_vals.add(pivot + 1), dst_vals, new_len); + (*src).data.len = pivot as u16; + move_split_edges(left, right, pivot, len); + } +} + +// BEGIN_BACKLINK_METHODS +impl NodeRef { + unsafe fn as_leaf_ptr(this: &Self) -> *mut LeafNode +/*@ + req [?f](*this |-> ?node_ref); + @*/ + /*@ + ens [f](*this |-> node_ref) &*& result == node_ref.node.as_ptr(); + @*/ + //@ on_unwind_ens false; + { + //@ open_points_to(this); + let ptr = this.node.as_ptr(); + //@ close_points_to(this, f); + ptr + } +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { + unsafe fn set_parent_link(&mut self, parent: NonNull>, parent_idx: usize) + //@ req *self |-> ?node_ref &*& (*node_ref.node.as_ptr()).parent |-> _ &*& (*node_ref.node.as_ptr()).parent_idx |-> _ &*& parent_idx <= CAPACITY; + //@ ens *self |-> node_ref &*& (*node_ref.node.as_ptr()).parent |-> Option::Some(parent) &*& (*node_ref.node.as_ptr()).parent_idx |-> MaybeUninit::new(parent_idx as u16); + //@ on_unwind_ens false; + { + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + let leaf = unsafe { Self::as_leaf_ptr(self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self, _); + unsafe { (*leaf).parent = Some(parent) }; + //@ open LeafNode_parent_idx_(leaf, _); + //@ points_to__limits(&(*leaf).parent_idx); + unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; + } +} + +// END_BACKLINK_METHODS + +use std::num::NonZero; +use std::ptr; + +// Ownership proof of insertion using the library's node layout and +// AllocatorClone bound. It covers both leaf insertion paths, propagation +// through an arbitrary ancestor chain, and installation of a new root +// before awakening the inserted handle. +// Where a proof needs non-unwinding allocator destruction, its contract +// records the safety guarantee of the Rust A: Allocator bound. Ordinary +// ownership of A does not imply that guarantee. + +use std::alloc::AllocatorClone; + +//@ use std::alloc::{Allocator, Allocator_full_borrow_content_}; +//@ use std::boxed::Box_in; +//@ use std::clone::allocator_clone_bound; + +// The shared borrow ends before any allocation or allocator drop. +// BEGIN_ALLOCATOR_CLONE +unsafe fn clone_allocator(alloc: &mut A) -> A +/*@ +req thread_token(?t) &*& type_interp::() &*& [_]allocator_clone_bound::() &*& + *alloc |-> ?original &*& Allocator(t, original, ?id); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& + *alloc |-> ?after &*& Allocator(t, after, id) &*& Allocator(t, result, id); +@*/ +//@ on_unwind_ens false; +{ + //@ std::alloc::close_Allocator_full_borrow_content_(t, alloc); + //@ let k = begin_lifetime(); + //@ borrow(k, Allocator_full_borrow_content_(t, alloc, id)); + //@ std::alloc::share_Allocator_full_borrow_content_(k, t, alloc, id); + //@ let view = precreate_ref(alloc); + //@ std::alloc::init_ref_Allocator_share(k, t, view); + //@ let f = open_frac_borrow(k, ref_initialized_(view), 1/2); + //@ open [f]ref_initialized_::(view)(); + let clone = (*alloc).clone(); + //@ close [f]ref_initialized_::(view)(); + //@ close_frac_borrow(f, ref_initialized_(view)); + //@ merge_fractions lifetime_token(k); + //@ end_lifetime(k); + //@ borrow_end(k, Allocator_full_borrow_content_(t, alloc, id)); + //@ std::alloc::open_Allocator_full_borrow_content_(t, alloc, id); + clone +} +// END_ALLOCATOR_CLONE + +// Verify the drop using the generic drop contract, including its unwind case. +unsafe fn drop_allocator(allocator: A) +//@ req thread_token(?t) &*& Allocator::(t, allocator, _); +//@ ens thread_token(t); +//@ on_unwind_ens thread_token(t); +{ + //@ std::alloc::Allocator_to_own(allocator); + drop(allocator); +} +impl LeafNode { + unsafe fn init(this: *mut Self) + //@ req (*this).parent |-?-> _ &*& (*this).len |-?-> _; + //@ ens (*this).parent |-> Option::None &*& (*this).len |-> 0; + //@ on_unwind_ens false; + { + // As a general policy, we leave fields uninitialized if they can be, as this should + // be both slightly faster and easier to track in Valgrind. + // ignore-tidy-undocumented-unsafe + unsafe { + // parent_idx, keys, and vals are all MaybeUninit + (&raw mut (*this).parent).write(None); + (&raw mut (*this).len).write(0); + } + } + + // Expose the boxed storage contract for the array fields in VeriFast. + unsafe fn new(alloc: A) -> Box + //@ req thread_token(?t) &*& Allocator(t, alloc, ?alloc_id); + //@ ens thread_token(t) &*& Box_in(t, result, alloc_id, ?node) &*& node.parent == Option::None &*& node.len == 0; + //@ on_unwind_ens thread_token(t); + { + //@ let allocator = alloc; + //@ std::alloc::Allocator_inv::(); + //@ assert Allocator(t, allocator, alloc_id); + let mut leaf = Box::new_uninit_in(alloc); + //@ let contents = std::boxed::Box_separate_contents(&mut leaf); + // Open storage only for the allocator lifetime available in this call. + // The traded token is returned before rebuilding the Box. + //@ assert [?q]lifetime_token(?k); + //@ assert lifetime_inclusion(k, lft_of_type::()) == true; + //@ lifetime_inclusion_trans(k, lft_of_type::(), alloc_id.lft); + //@ let q_alloc = lifetime_token_trade(k, q, alloc_id.lft); + //@ open_points_to_at_lft(contents, q_alloc); + //@ points_to_limits(contents); + let storage = &mut *leaf; + //@ points_to_limits(storage); + //@ std::mem::open_MaybeUninit(storage); + //@ let data = storage as *LeafNode; + + // SAFETY: `leaf` points to a `LeafNode`. + unsafe { LeafNode::init(storage.as_mut_ptr()) }; + // SAFETY: `leaf` was just initialized. + //@ std::mem::MaybeUninit__to_MaybeUninit(&(*data).parent_idx); + //@ open LeafNode_keys_(data, _); + //@ std::mem::Array__MaybeUninit_to_Array_MaybeUninit(&(*data).keys); + //@ open LeafNode_vals_(data, _); + //@ std::mem::Array__MaybeUninit_to_Array_MaybeUninit(&(*data).vals); + //@ std::mem::close_MaybeUninit(storage); + //@ close_points_to_at_lft(contents); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ std::boxed::Box_unseparate_contents(&mut leaf); + unsafe { leaf.assume_init() } + } +} + +impl InternalNode { + unsafe fn new(alloc: A) -> Box + //@ req thread_token(?t) &*& Allocator(t, alloc, ?alloc_id); + //@ ens thread_token(t) &*& Box_in(t, result, alloc_id, ?value) &*& value.data.parent == Option::None &*& value.data.len == 0; + //@ on_unwind_ens thread_token(t); + { + //@ let allocator = alloc; + //@ std::alloc::Allocator_inv::(); + //@ assert Allocator(t, allocator, alloc_id); + let mut node = Box::::new_uninit_in(alloc); + //@ let contents = std::boxed::Box_separate_contents(&mut node); + // Open storage only for the allocator lifetime available in this call. + // The traded token is returned before rebuilding the Box. + //@ assert [?q]lifetime_token(?k); + //@ assert lifetime_inclusion(k, lft_of_type::()) == true; + //@ lifetime_inclusion_trans(k, lft_of_type::(), alloc_id.lft); + //@ let q_alloc = lifetime_token_trade(k, q, alloc_id.lft); + //@ open_points_to_at_lft(contents, q_alloc); + //@ points_to_limits(contents); + let storage = &mut *node; + //@ points_to_limits(storage); + //@ std::mem::open_MaybeUninit(storage); + //@ let data = storage as *InternalNode; + //@ open InternalNode_data_(data, _); + + // SAFETY: argument points to the `node.data` `LeafNode`. + unsafe { LeafNode::init(&raw mut (*storage.as_mut_ptr()).data) }; + // SAFETY: `node.data` was just initialized and `node.edges` is MaybeUninit. + //@ std::mem::MaybeUninit__to_MaybeUninit(&(*data).data.parent_idx); + //@ open LeafNode_keys_(&(*data).data, _); + //@ std::mem::Array__MaybeUninit_to_Array_MaybeUninit(&(*data).data.keys); + //@ open LeafNode_vals_(&(*data).data, _); + //@ std::mem::Array__MaybeUninit_to_Array_MaybeUninit(&(*data).data.vals); + //@ close LeafNode_keys(&(*data).data, _); + //@ close LeafNode_vals(&(*data).data, _); + //@ close InternalNode_data(data, _); + //@ open InternalNode_edges_(data, _); + //@ std::mem::Array__MaybeUninit_to_Array_MaybeUninit(&(*data).edges); + //@ std::mem::close_MaybeUninit(storage); + //@ close_points_to_at_lft(contents); + //@ lifetime_token_trade_back(q_alloc, alloc_id.lft); + //@ std::boxed::Box_unseparate_contents(&mut node); + unsafe { node.assume_init() } + } +} + +struct Handle { + node: Node, + idx: usize, + _marker: PhantomData, +} + +// BEGIN_ROOT_REBORROW +struct DormantMutRef<'a, T> { + ptr: NonNull, + _marker: PhantomData<&'a mut T>, +} + +impl<'a, T> DormantMutRef<'a, T> { + unsafe fn reborrow(&mut self) -> &'a mut T + //@ req *self |-> ?dormant &*& *dormant.ptr.as_ptr() |-> ?value; + //@ ens *self |-> dormant &*& *result |-> value &*& result == dormant.ptr.as_ptr(); + //@ on_unwind_ens false; + { + // SAFETY: our own safety conditions imply this reference is again unique. + //@ open_points_to(self); + let result = unsafe { &mut *self.ptr.as_ptr() }; + //@ close_points_to(self); + result + } +} +// END_ROOT_REBORROW + +// BEGIN_WAKE_HANDLES +impl NodeRef { + unsafe fn awaken<'a>(self) -> NodeRef, K, V, Type> + //@ req true; + //@ ens result.node == self.node &*& result.height == self.height; + //@ on_unwind_ens false; + { + NodeRef { + height: self.height, + node: self.node, + _marker: PhantomData, + } + } +} + +impl Handle, HandleType> { + unsafe fn awaken<'a>(self) -> Handle, K, V, NodeType>, HandleType> + //@ req true; + /*@ + ens result.node.node == self.node.node &*& result.node.height == self.node.height &*& result.idx == self.idx; + @*/ + //@ on_unwind_ens false; + { + Handle { + node: unsafe { self.node.awaken() }, + idx: self.idx, + _marker: PhantomData, + } + } +} +// END_WAKE_HANDLES + +// BEGIN_DORMANCY +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn dormant<'b>(&'b self) -> NodeRef + //@ req [?f](*self |-> ?node); + //@ ens [f](*self |-> node) &*& result.height == node.height &*& result.node == node.node; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let result = NodeRef { height: self.height, node: self.node, _marker: PhantomData }; + //@ close_points_to(self, f); + result + } +} + +impl<'a, K, V, NodeType, HandleType> Handle, K, V, NodeType>, HandleType> { + unsafe fn dormant<'b>(&'b self) -> Handle, HandleType> + //@ req [?f](*self |-> ?origin); + /*@ + ens [f](*self |-> origin) &*& result.node.node == origin.node.node &*& + result.node.height == origin.node.height &*& result.idx == origin.idx; + @*/ + //@ on_unwind_ens false; + { + //@ open_points_to(self); + //@ let node_view = precreate_ref(&(*self).node); + //@ init_ref_readonly(node_view, 1/2); + let result = Handle { + node: unsafe { self.node.dormant/*@::<'a,K,V,NodeType,'b>@*/() }, + idx: self.idx, + _marker: PhantomData, + }; + //@ end_ref_readonly(node_view); + //@ merge_fractions points_to(&(*self).node, _); + //@ close_points_to(self, f); + result + } +} +// END_DORMANCY + +// The NodeRef in this proof carries pointer and height metadata. The +// contracts for node operations separately require the relevant storage. +/*@ +pred >.own(t, node) = + node.node.as_ptr() as usize != 0; + +lem NodeRef_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + NodeRef_own::(?t,?node) &*& + is_subtype_of::() == true &*& is_subtype_of::() == true &*& + is_subtype_of::() == true &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + NodeRef_own::(t,NodeRef:: { height: upcast::(node.height), node: upcast(node.node) }); +{ + open NodeRef_own::(t,node); + std::ptr::NonNull_upcast::,LeafNode>(node.node); + let n1 = upcast::>,NonNull>>(node.node); + close NodeRef_own::(t,NodeRef:: { height: upcast::(node.height), node: n1 }); +} + +lem NodeRef_drop() + req NodeRef_own::(?t,?node); + ens .own(t,node.height) &*& >>.own(t,node.node); +{ + open NodeRef_own::(t,node); + close usize_own(t,node.height); + std::ptr::close_NonNull_own(t,node.node); +} +@*/ + +/*@ +fix btree_product(x: i32, y: i32) -> i32 { x * y } +lem btree_distribute(x: i32, y: i32, z: i32) + req true; + ens btree_product(x, y + z) == x * y + x * z; +{} +fix btree_nat_value(n: nat) -> i32 { + match n { zero => 0, succ(n0) => btree_nat_value(n0) + 1 } +} +lem btree_nat_for_usize(n: usize) -> nat + req 0 <= n; + ens btree_nat_value(result) == n; +{ + let i = 0; + let value = zero; + while i < n + inv 0 <= i &*& i <= n &*& btree_nat_value(value) == i; + decreases n - i; + { + value = succ(value); + i = i + 1; + } + return value; +} +lem btree_associate(n: nat, b: i32, c: i32) + req true; + ens (btree_nat_value(n) * b) * c == btree_nat_value(n) * (b * c); +{ + match n { + zero => {} + succ(n0) => { + btree_associate(n0, b, c); + btree_distribute(b, btree_nat_value(n0), 1); + btree_distribute(c, btree_nat_value(n0) * b, b); + btree_distribute(b * c, btree_nat_value(n0), 1); + } + } +} + +// Pointer arithmetic preserves alignment when the element stride is aligned. +lem btree_aligned_offset(base: *T, count: usize) + req 0 <= count &*& (base as usize) % std::mem::align_of::() == 0 &*& + pointer_within_limits(base) == true &*& pointer_within_limits(base + count) == true; + ens ((base + count) as usize) % std::mem::align_of::() == 0; +{ + std::alloc::is_valid_layout_size_of_align_of::(); + is_power_of_2_pos(std::mem::align_of::()); + assert ((base + count) as usize) == (base as usize) + count * std::mem::size_of::(); + size_align::(); + div_rem_nonneg(base as usize, std::mem::align_of::()); + div_rem_nonneg(std::mem::size_of::(), std::mem::align_of::()); + let n = btree_nat_for_usize(count); + btree_associate(n, std::mem::size_of::() / std::mem::align_of::(), std::mem::align_of::()); + btree_distribute(std::mem::align_of::(), (base as usize) / std::mem::align_of::(), + count * (std::mem::size_of::() / std::mem::align_of::())); + div_rem_nonneg_unique((base + count) as usize, std::mem::align_of::(), + (base as usize) / std::mem::align_of::() + count * (std::mem::size_of::() / std::mem::align_of::()), 0); +} + + +fix btree_encoded(values: list, bytes: list>) -> bool { + match values { + nil => bytes == nil, + cons(v, rest) => + length(bytes) == length(values) * std::mem::size_of::() && + of_u8s_::(take(std::mem::size_of::(), bytes)) == some(v) && + btree_encoded(rest, drop(std::mem::size_of::(), bytes)) + } +} + +lem btree_drop_append_left(n: i32, xs: list, ys: list) + req 0 <= n &*& n <= length(xs); + ens drop(n, append(xs, ys)) == append(drop(n, xs), ys); +{ + match xs { + nil => {} + cons(x, rest) => { + if n != 0 { btree_drop_append_left(n - 1, rest, ys); } + } + } +} + +lem btree_encoded_length(values: list, bytes: list>) + req btree_encoded(values, bytes) == true; + ens length(bytes) == length(values) * std::mem::size_of::(); +{ + match values { nil => {} cons(v, rest) => {} } +} + +lem btree_encoded_append(xs: list, xb: list>, ys: list, yb: list>) + req btree_encoded(xs, xb) == true &*& btree_encoded(ys, yb) == true; + ens btree_encoded(append(xs, ys), append(xb, yb)) == true; +{ + match xs { + nil => { assert xb == nil; } + cons(x, rest) => { + std::alloc::is_valid_layout_size_of_align_of::(); + btree_encoded_length(xs, xb); + btree_encoded_length(ys, yb); + btree_distribute(std::mem::size_of::(), length(xs), length(ys)); + mul_mono_l(1, length(xs), std::mem::size_of::()); + take_append_l(std::mem::size_of::(), xb, yb); + btree_drop_append_left(std::mem::size_of::(), xb, yb); + btree_encoded_append(rest, drop(std::mem::size_of::(), xb), ys, yb); + assert length(append(xb, yb)) == length(append(xs, ys)) * std::mem::size_of::(); + assert of_u8s_::(take(std::mem::size_of::(), append(xb, yb))) == some(x); + assert btree_encoded(append(rest, ys), drop(std::mem::size_of::(), append(xb, yb))) == true; + } + } +} + +lem btree_encoded_split(values: list, bytes: list>, count: i32) + req btree_encoded(values, bytes) == true &*& 0 <= count &*& count <= length(values); + ens btree_encoded(take(count, values), take(count * std::mem::size_of::(), bytes)) == true &*& + btree_encoded(drop(count, values), drop(count * std::mem::size_of::(), bytes)) == true; +{ + match values { + nil => {} + cons(v, rest) => { + std::alloc::is_valid_layout_size_of_align_of::(); + btree_encoded_length(values, bytes); + if count != 0 { + mul_mono_l(1, length(values), std::mem::size_of::()); + mul_mono_l(1, count, std::mem::size_of::()); + let first = take(std::mem::size_of::(), bytes); + let tail = drop(std::mem::size_of::(), bytes); + btree_encoded_split(rest, tail, count - 1); + append_take_drop_n(bytes, std::mem::size_of::()); + take_append(count * std::mem::size_of::(), first, tail); + drop_append(count * std::mem::size_of::(), first, tail); + btree_encoded_append(cons(v, nil), first, + take(count - 1, rest), take((count - 1) * std::mem::size_of::(), tail)); + } + } + } +} + +lem btree_values_to_bytes(p: *T, n: i32) + req p[..n] |-> ?values &*& p as usize % std::mem::align_of::() == 0; + ens (p as *u8)[..n * std::mem::size_of::()] |-?-> ?bytes &*& btree_encoded(values, bytes) == true; +{ + std::alloc::is_valid_layout_size_of_align_of::(); + open array(p, n, values); + if n == 0 { + close array_::(p as *u8, 0, nil); + } else { + to_u8s_(p); + array__inv::(); + assert (p as *u8)[..std::mem::size_of::()] |-?-> ?first; + btree_aligned_offset(p, 1); + btree_values_to_bytes(p + 1, n - 1); + assert ((p + 1) as *u8)[..(n - 1) * std::mem::size_of::()] |-?-> ?tail_bytes; + btree_encoded_append(cons(head(values), nil), first, tail(values), tail_bytes); + array__join(p as *u8); + } +} + +lem btree_bytes_to_values(p: *T, values: list) + req (p as *u8)[..length(values) * std::mem::size_of::()] |-?-> ?bytes &*& + btree_encoded(values, bytes) == true &*& p as usize % std::mem::align_of::() == 0; + ens p[..length(values)] |-> values; +{ + match values { + nil => { + open array_::(p as *u8, 0, bytes); + close array(p, 0, nil); + } + cons(v, rest) => { + std::alloc::is_valid_layout_size_of_align_of::(); + mul_mono_l(1, length(values), std::mem::size_of::()); + btree_distribute(std::mem::size_of::(), 1, length(rest)); + array__split(p as *u8, std::mem::size_of::()); + from_u8s_(p); + btree_aligned_offset(p, 1); + btree_bytes_to_values(p + 1, rest); + close array(p, length(values), values); + } + } +} + +lem btree_restore_shr(p: *T, n: i32, distance: i32, values: list, bytes: list>) + req 0 <= distance &*& distance <= n &*& length(values) == n &*& + btree_encoded(values, bytes) == true &*& + (p as *u8)[..n * std::mem::size_of::()] |-?-> append(take(distance * std::mem::size_of::(), bytes), take((n - distance) * std::mem::size_of::(), bytes)) &*& + p as usize % std::mem::align_of::() == 0; + ens p[..n] |-> append(take(distance, values), take(n - distance, values)); +{ + btree_encoded_split(values, bytes, distance); + btree_encoded_split(values, bytes, n - distance); + btree_encoded_append(take(distance, values), take(distance * std::mem::size_of::(), bytes), take(n - distance, values), take((n - distance) * std::mem::size_of::(), bytes)); + btree_bytes_to_values(p, append(take(distance, values), take(n - distance, values))); +} + +@*/ + +// The slice-to-pointer cast is the body of [T]::as_mut_ptr. The proof +// generator checks that body and the remaining operations against the library. +// BEGIN_SLICE_INSERT +unsafe fn slice_insert(slice: &mut [MaybeUninit], idx: usize, val: T) +/*@ +req thread_token(?t) &*& type_interp::() &*& .own(t,val) &*& + 0 <= idx &*& idx < slice.len() &*& slice.len() <= CAPACITY + 1 &*& + (slice as *MaybeUninit)[..slice.len()] |-> ?slots; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& .own(t,val) &*& + (slice as *MaybeUninit)[..slice.len()] |-> + append(take(idx,slots),cons(MaybeUninit::new(val),take(slice.len() - idx - 1, drop(idx,slots)))); +@*/ +//@ on_unwind_ens false; +{ + let len = slice.len(); + debug_assert!(len > idx); + let slice_ptr = slice.as_mut_ptr(); + //@ array_split(slice_ptr,idx); + //@ let base = slice_ptr + idx; + //@ let suffix = drop(idx, slots); + //@ length_drop(idx,slots); + //@ insertion_slot_limits(base); + //@ let shifted = append(take(1,suffix),take(len - idx - 1,suffix)); + unsafe { + if len > idx + 1 { + //@ btree_values_to_bytes(base, len - idx); + //@ assert (base as *u8)[..(len - idx) * std::mem::size_of::>()] |-?-> ?bytes; + //@ btree_aligned_offset(base, 1); + //@ close exists::(true); + //@ close exists::(1); + ptr::copy(slice_ptr.add(idx), slice_ptr.add(idx + 1), len - idx - 1); + //@ btree_restore_shr(base,len - idx,1,suffix,bytes); + } else { + //@ take_length(suffix); + //@ take_0(suffix); + //@ append_nil(suffix); + } + //@ length_take(1,suffix); + //@ drop_append(1,take(1,suffix),take(len - idx - 1,suffix)); + //@ array_split(base,1); + //@ open array(base,1,take(1,shifted)); + (*slice_ptr.add(idx)).write(val); + //@ close array(base,1,[MaybeUninit::new(val)]); + //@ array_join(base); + //@ array_join(slice_ptr); + } +} + +// END_SLICE_INSERT + +/*@ +lem insertion_slot_limits(p: *MaybeUninit) + req p[..?n] |-> ?values &*& n > 0; + ens p[..n] |-> values &*& p != 0 &*& p as usize != 0 &*& pointer_within_limits(p + 1) == true &*& + p as usize % std::mem::align_of::>() == 0; +{ + array_split(p, 1); + open array(p, 1, take(1, values)); + points_to_limits(p); + to_u8s_(p); + from_u8s_(p); + std::mem::MaybeUninit__to_MaybeUninit(p); + close array(p, 1, take(1, values)); + array_join(p); +} +@*/ + +const KV_IDX_CENTER: usize = B - 1; +//@ fix KV_IDX_CENTER() -> usize { B - 1 } +const EDGE_IDX_LEFT_OF_CENTER: usize = B - 1; +//@ fix EDGE_IDX_LEFT_OF_CENTER() -> usize { B - 1 } +const EDGE_IDX_RIGHT_OF_CENTER: usize = B; +//@ fix EDGE_IDX_RIGHT_OF_CENTER() -> usize { B } + +enum LeftOrRight { + Left(T), + Right(T), +} + +struct SplitResult<'a, K, V, NodeType> { + // Altered node in existing tree with elements and edges that belong to the left of `kv`. + pub left: NodeRef, K, V, NodeType>, + // Some key and value that existed before and were split off, to be inserted elsewhere. + pub kv: (K, V), + // Owned, unattached, new node with elements and edges that belong to the right of `kv`. + pub right: NodeRef, +} + +type Root = NodeRef; + +/*@ +fix insertion_pivot(index: usize) -> usize { + if index < EDGE_IDX_LEFT_OF_CENTER { KV_IDX_CENTER - 1 } else if index <= EDGE_IDX_RIGHT_OF_CENTER { KV_IDX_CENTER } else { KV_IDX_CENTER + 1 } +} +@*/ +unsafe fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight) +//@ req 0 <= edge_idx &*& edge_idx <= CAPACITY; +/*@ +ens 0 <= result.0 &*& result.0 < CAPACITY &*& result.0 == insertion_pivot(edge_idx) &*& + match result.1 { + LeftOrRight::Left(index) => 0 <= index &*& index == edge_idx &*& index <= result.0, + LeftOrRight::Right(index) => 0 <= index &*& edge_idx == result.0 + 1 + index &*& index <= CAPACITY - result.0 - 1 + }; +@*/ +//@ on_unwind_ens false; +{ + debug_assert!(edge_idx <= CAPACITY); + // Rust issue #74834 tries to explain these symmetric rules. + match edge_idx { + 0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, LeftOrRight::Left(edge_idx)), + EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Left(edge_idx)), + EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Right(0)), + _ => { + /*@ + if edge_idx < EDGE_IDX_LEFT_OF_CENTER + 1 { + assert edge_idx == EDGE_IDX_LEFT_OF_CENTER; + } else if edge_idx < EDGE_IDX_RIGHT_OF_CENTER + 1 { + assert edge_idx == EDGE_IDX_RIGHT_OF_CENTER; + } + @*/ + (KV_IDX_CENTER + 1, LeftOrRight::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))) + } + } +} + +/*@ +// Separating the active child headers is valid even if each child is itself +// internal. Its payload and descendants can stay with the caller. +lem split_linked_headers(children: list>>, parent: NonNull>, start: usize, count: usize) + req linked_headers(children, parent, start) &*& 0 <= count &*& count <= length(children); + ens linked_headers(take(count,children), parent, start) &*& linked_headers(drop(count,children), parent, start + count); +{ + if count == 0 { + close linked_headers([], parent, start); + } else { + unpack_nonempty(children); + assert children == cons(?child, ?rest); + open linked_headers(children, parent, start); + split_linked_headers(rest, parent, start + 1, count - 1); + close linked_headers(take(count,children), parent, start); + } +} + +lem join_linked_headers(a: list>>, b: list>>, parent: NonNull>, start: usize) + req linked_headers(a, parent, start) &*& linked_headers(b, parent, start + length(a)); + ens linked_headers(append(a,b), parent, start); +{ + open linked_headers(a, parent, start); + match a { + nil => {} + cons(child, rest) => { + join_linked_headers(rest, b, parent, start + 1); + close linked_headers(append(a,b), parent, start); + } + } +} + +lem forget_link_indices(children: list>>, parent: NonNull>, start: usize) + req linked_headers(children, parent, start); + ens child_headers(children); +{ + open linked_headers(children, parent, start); + match children { + nil => {} + cons(child, rest) => { forget_link_indices(rest, parent, start + 1); } + } + close child_headers(children); +} + +lem take_after_drop(xs: list, first: usize, count: usize) + req 0 <= first &*& 0 <= count &*& first + count <= length(xs); + ens take(count, drop(first,xs)) == drop(first,take(first + count,xs)); +{ + match xs { + nil => {} + cons(x, rest) => { + if first > 0 { take_after_drop(rest, first - 1, count); } + } + } +} + +lem take_twice(xs: list, short: usize, long: usize) + req 0 <= short &*& short <= long &*& long <= length(xs); + ens take(short,take(long,xs)) == take(short,xs); +{ + match xs { + nil => {} + cons(x, rest) => { if short > 0 { take_twice(rest, short - 1, long - 1); } } + } +} + +lem initialized_edge_split(children: list>>, first: usize) + req 0 <= first &*& first <= length(children); + ens take(first,initialized_edges(children)) == initialized_edges(take(first,children)) &*& + drop(first,initialized_edges(children)) == initialized_edges(drop(first,children)); +{ + match children { + nil => {} + cons(child, rest) => { + if first > 0 { initialized_edge_split(rest, first - 1); } + } + } +} + +lem join_segments(base: *T, first: usize, second: usize, prefix: list, suffix: list) + req (base + first)[..second] |-> suffix &*& base[..first] |-> prefix; + ens base[..first + second] |-> append(prefix,suffix); +{ + array_join(base); +} + +pred node_arrays(node: *InternalNode; keys: list>, vals: list>, edges: list>>>) = + pointer_within_limits(&(*node).data) == true &*& pointer_within_limits(&(*node).data.keys) == true &*& + pointer_within_limits(&(*node).data.vals) == true &*& pointer_within_limits(&(*node).edges) == true &*& + (*node).data.keys[..CAPACITY] |-> keys &*& (*node).data.vals[..CAPACITY] |-> vals &*& + (*node).edges[..CAPACITY + 1] |-> edges; + +pred internal_slots(node: NonNull>, len: usize, children: list>>; keys: list>, vals: list>) = + node_arrays(node.as_ptr(), keys, vals, ?edges) &*& (*node.as_ptr()).data.len |-> (len as u16) &*& + 0 <= len &*& len <= CAPACITY &*& length(children) == len + 1 &*& + take(len + 1, edges) == initialized_edges(children) &*& linked_headers(children, node, 0); +@*/ + +unsafe fn fit_node( + parent: NonNull>, + index: usize, + key: K, + value: V, + right: NonNull>, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,value) &*& + ancestors(&(*parent.as_ptr()).data, ?path, ?root) &*& internal_slots(parent, ?len, ?children, ?original_keys, ?original_vals) &*& + 0 <= index &*& index <= len &*& len < CAPACITY &*& (*right.as_ptr()).parent |-> Option::None &*& (*right.as_ptr()).parent_idx |-> _; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,value) &*& + ancestors(&(*parent.as_ptr()).data, path, root) &*& internal_slots(parent, len + 1, append(take(index + 1,children),cons(right,drop(index + 1,children))), ?fitted_keys, ?fitted_vals); +@*/ +//@ on_unwind_ens false; +{ + //@ open internal_slots(parent, len, children, original_keys, original_vals); + //@ assert node_arrays(parent.as_ptr(), original_keys, original_vals, ?original_edges); + //@ open node_arrays(parent.as_ptr(), original_keys, original_vals, original_edges); + let parent_ptr = parent.as_ptr(); + let new_len = unsafe { (*parent_ptr).data.len } as usize + 1; + let key_base = unsafe { (&raw mut (*parent_ptr).data.keys) as *mut MaybeUninit }; + let val_base = unsafe { (&raw mut (*parent_ptr).data.vals) as *mut MaybeUninit }; + let edge_base = unsafe { (&raw mut (*parent_ptr).edges) as *mut MaybeUninit> }; + //@ array_split(key_base,new_len); + //@ array_split(val_base,new_len); + //@ array_split(edge_base,new_len + 1); + //@ insertion_slot_limits(key_base); + //@ insertion_slot_limits(val_base); + //@ insertion_slot_limits(edge_base); + //@ split_linked_headers(children, parent, 0, index + 1); + //@ let before = take(index + 1, children); + //@ let after = drop(index + 1, children); + //@ length_take(index + 1,children); + //@ length_drop(index + 1,children); + //@ forget_link_indices(after, parent, index + 1); + //@ initialized_edge_split(children,index + 1); + //@ take_after_drop(original_edges,index + 1,len - index); + //@ take_after_drop(original_edges,index + 1,len + 1 - index); + //@ take_twice(drop(index + 1,original_edges),len - index,len + 1 - index); + //@ take_twice(original_edges,index + 1,len + 2); + //@ take_twice(original_edges,index + 1,len + 1); + + unsafe { + slice_insert(std::slice::from_raw_parts_mut(key_base, new_len), index, key); + slice_insert(std::slice::from_raw_parts_mut(val_base, new_len), index, value); + //@ std::ptr::close_NonNull_own(t,right); + //@ produce_type_interp::>>(); + slice_insert(std::slice::from_raw_parts_mut(edge_base, new_len + 1), index + 1, right); + //@ leak >>.own(t,right); + //@ std::ptr::open_NonNull_own(t,right); + //@ leak type_interp::>>(); + (*parent_ptr).data.len = new_len as u16; + + //@ let inserted = cons(right, after); + //@ assert edge_base[..len + 2] |-> ?filled; + //@ assert filled == append(initialized_edges(before), initialized_edges(inserted)); + //@ array_split(edge_base,index + 1); + //@ initialized_edge_count(before); + //@ initialized_edge_count(inserted); + //@ take_append_l(index + 1,initialized_edges(before),initialized_edges(inserted)); + //@ take_length(initialized_edges(before)); + //@ drop_append(index + 1,initialized_edges(before),initialized_edges(inserted)); + //@ close child_headers(inserted); + repair_edges(parent, index + 1, new_len + 1); + //@ join_linked_headers(before,inserted,parent,0); + //@ let inactive = drop(len + 2,original_edges); + //@ join_segments(edge_base + index + 1,len + 1 - index,CAPACITY - len - 1,initialized_edges(inserted),inactive); + //@ join_segments(edge_base,index + 1,CAPACITY - index,initialized_edges(before),append(initialized_edges(inserted),inactive)); + //@ append_assoc(initialized_edges(before),initialized_edges(inserted),inactive); + //@ array_join(key_base); + //@ array_join(val_base); + //@ assert edge_base[..CAPACITY + 1] |-> ?new_edges; + //@ assert key_base[..CAPACITY] |-> ?new_keys; + //@ assert val_base[..CAPACITY] |-> ?new_vals; + //@ let active = append(initialized_edges(before), initialized_edges(inserted)); + //@ assert new_edges == append(active,inactive); + //@ initialized_edges_append(before,inserted); + //@ take_append_l(len + 2, active, inactive); + //@ take_length(active); + //@ close node_arrays(parent_ptr, new_keys, new_vals, new_edges); + //@ close internal_slots(parent, len + 1, append(before,inserted), new_keys, new_vals); + } +} + +// BEGIN_READ_SLOT +unsafe fn read_promoted(slot: *const MaybeUninit) -> T +//@ req thread_token(?t) &*& type_interp::() &*& *slot |-> ?bits &*& bits.inner() == some(?value) &*& .own(t,value); +//@ ens thread_token(t) &*& type_interp::() &*& *slot |-> MaybeUninit::new(value) &*& result == value &*& .own(t,value); +//@ on_unwind_ens false; +{ + //@ open_MaybeUninit(slot); + //@ points_to_limits(slot as *T); + let promoted = unsafe { std::ptr::read(slot as *const T) }; + //@ close_MaybeUninit(slot); + promoted +} +// END_READ_SLOT + +unsafe fn split_full_node( + left: NonNull>, + right: NonNull>, + pivot: usize, +) -> (K, V) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + ancestors(&(*left.as_ptr()).data, ?path, ?root) &*& + ancestors(&(*right.as_ptr()).data, [], &(*right.as_ptr()).data) &*& + internal_slots(left, CAPACITY, ?children, ?keys, ?vals) &*& + node_arrays(right.as_ptr(), ?right_keys, ?right_vals, ?right_edges) &*& + (*right.as_ptr()).data.len |-> 0 &*& 0 <= pivot &*& pivot < CAPACITY &*& + nth(pivot, keys).inner() == some(?promoted_key) &*& nth(pivot, vals).inner() == some(?promoted_value) &*& + .own(t, promoted_key) &*& .own(t, promoted_value); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + ancestors(&(*left.as_ptr()).data, path, root) &*& + ancestors(&(*right.as_ptr()).data, [], &(*right.as_ptr()).data) &*& + internal_slots(left, pivot, take(pivot + 1, children), ?left_key_bits, ?left_val_bits) &*& + internal_slots(right, CAPACITY - pivot - 1, drop(pivot + 1, children), ?new_key_bits, ?new_val_bits) &*& + result.0 == promoted_key &*& result.1 == promoted_value &*& .own(t, promoted_key) &*& .own(t, promoted_value); +@*/ +//@ on_unwind_ens false; +{ + //@ open internal_slots(left, CAPACITY, children, keys, vals); + //@ assert node_arrays(left.as_ptr(), keys, vals, ?edges); + //@ open node_arrays(left.as_ptr(), keys, vals, edges); + //@ open node_arrays(right.as_ptr(), right_keys, right_vals, right_edges); + //@ let left_edge_base = &(*left.as_ptr()).edges as *MaybeUninit>>; + //@ let right_edge_base = &(*right.as_ptr()).edges as *MaybeUninit>>; + //@ let right_key_base = &(*right.as_ptr()).data.keys as *MaybeUninit; + //@ let right_val_base = &(*right.as_ptr()).data.vals as *MaybeUninit; + let key_base = unsafe { (&raw const (*left.as_ptr()).data.keys) as *const MaybeUninit }; + let val_base = unsafe { (&raw const (*left.as_ptr()).data.vals) as *const MaybeUninit }; + //@ array_split(key_base, pivot); + //@ array_split(key_base + pivot, 1); + //@ array_split(val_base, pivot); + //@ array_split(val_base + pivot, 1); + //@ drop_n_plus_one(pivot, keys); + //@ drop_n_plus_one(pivot, vals); + //@ open array(key_base + pivot, 1, take(1, drop(pivot, keys))); + //@ open array(val_base + pivot, 1, take(1, drop(pivot, vals))); + let key = unsafe { read_promoted(key_base.add(pivot)) }; + let value = unsafe { read_promoted(val_base.add(pivot)) }; + //@ close array(key_base + pivot, 1, [MaybeUninit::new(promoted_key)]); + //@ close array(val_base + pivot, 1, [MaybeUninit::new(promoted_value)]); + + //@ let left_children = take(pivot + 1, children); + //@ let right_children = drop(pivot + 1, children); + //@ array_split(left_edge_base, pivot + 1); + //@ array_split(right_edge_base, CAPACITY - pivot); + //@ array_split(right_key_base, CAPACITY - pivot - 1); + //@ array_split(right_val_base, CAPACITY - pivot - 1); + //@ take_length(edges); + //@ initialized_edge_split(children, pivot + 1); + //@ length_take(pivot + 1, children); + //@ length_drop(pivot + 1, children); + //@ split_linked_headers(children, left, 0, pivot + 1); + //@ forget_link_indices(right_children, left, pivot + 1); + //@ open ancestors(&(*right.as_ptr()).data, [], &(*right.as_ptr()).data); + //@ array_to_array_(right_edge_base); + //@ array_to_array_(right_key_base); + //@ array_to_array_(right_val_base); + unsafe { split_preserves_ancestors(left, right, pivot) }; + //@ close ancestors(&(*right.as_ptr()).data, [], &(*right.as_ptr()).data); + + //@ array_join(key_base + pivot); + //@ array_join(key_base); + //@ array_join(val_base + pivot); + //@ array_join(val_base); + //@ array_join(left_edge_base); + //@ array_join(right_key_base); + //@ array_join(right_val_base); + //@ array_join(right_edge_base); + //@ assert left_edge_base[..CAPACITY + 1] |-> ?new_left_edges; + //@ assert right_edge_base[..CAPACITY + 1] |-> ?new_right_edges; + //@ assert key_base[..CAPACITY] |-> ?new_left_keys; + //@ assert val_base[..CAPACITY] |-> ?new_left_vals; + //@ assert right_key_base[..CAPACITY] |-> ?new_right_keys; + //@ assert right_val_base[..CAPACITY] |-> ?new_right_vals; + //@ append_take_drop_n(edges, pivot + 1); + //@ assert new_left_edges == edges; + //@ initialized_edge_count(right_children); + //@ take_append_l(CAPACITY - pivot, initialized_edges(right_children), drop(CAPACITY - pivot, right_edges)); + //@ take_length(initialized_edges(right_children)); + //@ close node_arrays(left.as_ptr(), new_left_keys, new_left_vals, new_left_edges); + //@ close node_arrays(right.as_ptr(), new_right_keys, new_right_vals, new_right_edges); + //@ close internal_slots(left, pivot, left_children, new_left_keys, new_left_vals); + //@ close internal_slots(right, CAPACITY - pivot - 1, right_children, new_right_keys, new_right_vals); + (key, value) +} + +/*@ +pred dormant_pair(leaf: *LeafNode, index: usize; key: MaybeUninit, value: MaybeUninit) = + (*leaf).len |-> ?len &*& 0 <= index &*& index < len &*& len <= CAPACITY &*& + *((&(*leaf).keys as *MaybeUninit) + index) |-> key &*& + *((&(*leaf).vals as *MaybeUninit) + index) |-> value &*& + key.inner() != none &*& value.inner() != none; +@*/ + +/*@ +pred reserve_allocation(k: lifetime_t, q: real) = [q]lifetime_token(k); + +pred allocated_internal(node: *InternalNode, alloc_id: std::alloc::alloc_id_t, lifetime: lifetime_t, fraction: real) = + std::alloc::alloc_block_in(alloc_id, node as *u8, std::alloc::Layout::new::>()) &*& + close_points_to_at_lft_token(1, alloc_id.lft, node, ?alloc_fraction) &*& + close_lifetime_trade_token(alloc_fraction, alloc_id.lft, fraction, lifetime) &*& + struct_InternalNode_padding(node) &*& struct_LeafNode_padding(&(*node).data); +@*/ + +unsafe fn fresh_internal(alloc: A) -> (NonNull>, A) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + Allocator::(t, alloc, ?alloc_id) &*& exists::(?k) &*& [?q]lifetime_token(k) &*& lifetime_inclusion(k, alloc_id.lft) == true; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,result.1,alloc_id) &*& [q/2]lifetime_token(k) &*& allocated_internal(result.0.as_ptr(), alloc_id, k, q/2) &*& node_arrays(result.0.as_ptr(), _, _, _) &*& + ancestors(&(*result.0.as_ptr()).data, [], &(*result.0.as_ptr()).data) &*& + (*result.0.as_ptr()).data.len |-> 0 &*& (*result.0.as_ptr()).data.parent_idx |-> _; +@*/ +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& [q]lifetime_token(k); +{ + let internal = unsafe { InternalNode::::new(alloc) }; + let (node, retained_allocator) = Box::into_non_null_with_allocator(internal); + //@ let pointer = node.as_ptr(); + // Keep a positive share for the next iteration. The other share can + // be recovered by closing the freshly opened node storage. + //@ close reserve_allocation(k,q/2); + //@ let q_alloc = lifetime_token_trade(k, q/2, alloc_id.lft); + //@ open_points_to_at_lft(pointer, q_alloc); + //@ points_to_limits(pointer); + //@ open_points_to(pointer); + //@ close node_arrays(pointer, _, _, _); + //@ close allocated_internal(pointer, alloc_id, k, q/2); + //@ close link(&(*pointer).data, Option::None, 0); + //@ close ancestors(&(*pointer).data, [], &(*pointer).data); + //@ open reserve_allocation(k,q/2); + (node, retained_allocator) +} + +/*@ +pred pivot_owner(t: thread_id_t, len: usize, index: usize, keys: list>, vals: list>) = + if len == CAPACITY { + nth(insertion_pivot(index), keys).inner() == some(?key) &*& + nth(insertion_pivot(index), vals).inner() == some(?value) &*& + .own(t, key) &*& .own(t, value) + } else { true }; + +pred route_frames(t: thread_id_t, path: list>) = + match path { + nil => true, + cons(step, rest) => + match step { + ParentStep(parent, index, len, payload) => + match payload { + ParentPayload(keys, vals, edges) => + exists::>>>(?children) &*& + length(children) == len + 1 &*& take(len + 1, edges) == initialized_edges(children) &*& + linked_headers(take(index, children), NonNull::new(parent), 0) &*& + linked_headers(drop(index + 1, children), NonNull::new(parent), index + 1) &*& + pivot_owner(t, len, index, keys, vals) &*& struct_LeafNode_padding(&(*parent).data) &*& struct_InternalNode_padding(parent) &*& route_frames(t, rest) + } + } + }; + +lem nth_initialized_edge(children: list>>, index: i32) + req 0 <= index &*& index < length(children); + ens nth(index, initialized_edges(children)) == MaybeUninit::new(nth(index, children)); +{ + match children { + nil => {} + cons(child, rest) => { if index > 0 { nth_initialized_edge(rest, index - 1); } } + } +} + +lem nth_take_range(items: list, len: i32, index: i32) + req 0 <= index &*& index < len &*& len <= length(items); + ens nth(index, take(len, items)) == nth(index, items); +{ + match items { + nil => {} + cons(item, rest) => { if index > 0 { nth_take_range(rest, len - 1, index - 1); } } + } +} + +lem nth_at_partition(items: list, index: i32) + req 0 <= index &*& index < length(items); + ens append(take(index, items),cons(nth(index,items), drop(index + 1,items))) == items; +{ + drop_n_plus_one(index, items); + append_take_drop_n(items, index); +} + +lem expose_receiving_node( + t: thread_id_t, child: *LeafNode, parent: NonNull>, index: u16, + len: u16, keys: list>, vals: list>, edges: list>>>, + higher: list> +) + req child != 0 &*& pointer_within_limits(child) == true &*& + link(child, Option::Some(parent), index) &*& parent_payload(child, parent.as_ptr(), index, len, ParentPayload(keys,vals,edges)) &*& + route_frames(t, cons(ParentStep(parent.as_ptr(), index, len, ParentPayload(keys,vals,edges)), higher)); + ens internal_slots(parent, len, ?children, keys, vals) &*& 0 <= index &*& index <= len &*& + nth(index, children) == NonNull::new(child) &*& pivot_owner(t, len, index, keys, vals) &*& route_frames(t, higher) &*& struct_LeafNode_padding(&(*parent.as_ptr()).data) &*& struct_InternalNode_padding(parent.as_ptr()); +{ + open link(child, Option::Some(parent), index); + open parent_payload(child, parent.as_ptr(), index, len, ParentPayload(keys,vals,edges)); + open route_frames(t, cons(ParentStep(parent.as_ptr(), index, len, ParentPayload(keys,vals,edges)), higher)); + assert exists::>>>(?all_children); + open exists::>>>(all_children); + std::ptr::NonNull_new_as_ptr(parent); + assert 0 <= index; + nth_take_range(edges, len + 1, index); + nth_initialized_edge(all_children, index); + assert (nth(index, edges)).inner() == some(nth(index, all_children)); + assert (nth(index, edges)).inner() == some(NonNull::new(child)); + let focus = nth(index, all_children); + assert focus == NonNull::new(child); + points_to_limits(&(*child).parent); + assert child != 0 &*& pointer_within_limits(child) == true; + close linked_headers([], parent, index + 1); + close linked_headers([focus], parent, index); + join_linked_headers([focus], drop(index + 1,all_children), parent, index); + length_take(index, all_children); + join_linked_headers(take(index,all_children), cons(focus,drop(index + 1,all_children)), parent, 0); + nth_at_partition(all_children, index); + close node_arrays(parent.as_ptr(), keys, vals, edges); + close internal_slots(parent, len, all_children, keys, vals); +} +@*/ + +unsafe fn open_next_parent( + child: *const LeafNode, +) -> Option<(NonNull>, u16)> +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + child != 0 &*& pointer_within_limits(child) == true &*& + ancestors(child, ?path, ?root) &*& route_frames(t, path); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + match result { + Option::None => path == [] &*& ancestors(child, path, root) &*& route_frames(t, path), + Option::Some(step) => + path == cons(ParentStep(step.0.as_ptr(), step.1, ?len, ParentPayload(?keys, ?vals, ?edges)), ?higher) &*& + ancestors(&(*step.0.as_ptr()).data, higher, root) &*& route_frames(t, higher) &*& + internal_slots(step.0, len, ?children, keys, vals) &*& 0 <= step.1 &*& step.1 <= len &*& len <= CAPACITY &*& + nth(step.1,children) == NonNull::new(child) &*& + pivot_owner(t, len, step.1, keys, vals) &*& struct_LeafNode_padding(&(*step.0.as_ptr()).data) &*& struct_InternalNode_padding(step.0.as_ptr()) + }; +@*/ +//@ on_unwind_ens false; +{ + //@ open ancestors(child, path, root); + //@ open link(child, _, _); + let backlink = unsafe { (*child).parent }; + match backlink { + None => { + //@ assert path == []; + //@ close link(child, Option::None, 0); + //@ close ancestors(child, [], root); + None + } + Some(parent) => { + //@ assert path == cons(ParentStep(?parent_ptr, ?index, ?len, ParentPayload(?keys, ?vals, ?edges)), ?higher); + //@ std::ptr::NonNull_new_as_ptr(parent); + //@ open_MaybeUninit(&(*child).parent_idx); + //@ points_to_limits(&(*child).parent_idx as *u16); + let observed_index = unsafe { *((&raw const (*child).parent_idx) as *const u16) }; + //@ close_MaybeUninit(&(*child).parent_idx); + //@ open parent_payload(child, parent_ptr, index, len, ParentPayload(keys,vals,edges)); + //@ assert parent == NonNull::new(parent_ptr); + //@ std::ptr::NonNull_as_ptr_new(parent_ptr); + //@ close parent_payload(child, parent_ptr, index, len, ParentPayload(keys,vals,edges)); + //@ close link(child, Option::Some(parent), index); + //@ expose_receiving_node(t, child, parent, index, len, keys, vals, edges, higher); + Some((parent, observed_index)) + } + } +} + +impl<'tree,K,V> NodeRef, K, V, marker::LeafOrInternal> { + unsafe fn ascend(mut self) -> Result, K, V, marker::Internal>, marker::Edge>, Self> + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + ancestors(self.node.as_ptr(), ?path, ?root) &*& route_frames(t, path) &*& + 0 <= self.height &*& self.height + length(path) < usize::MAX; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + match result { + Result::Err(detached) => detached == self &*& path == [] &*& ancestors(self.node.as_ptr(), path, root) &*& route_frames(t, path), + Result::Ok(edge) => + exists::>>(?parent) &*& edge.node.node.as_ptr() == parent.as_ptr() as *LeafNode &*& + path == cons(ParentStep(parent.as_ptr(), ?idx, ?len, ParentPayload(?keys, ?vals, ?edges)), ?higher) &*& + edge.idx == idx &*& edge.node.height == self.height + 1 &*& edge.idx <= len &*& len <= CAPACITY &*& + ancestors(&(*parent.as_ptr()).data, higher, root) &*& route_frames(t, higher) &*& + ready_parent(t,parent,len,idx,?children,keys,vals) &*& nth(idx,children) == self.node &*& + struct_LeafNode_padding(&(*parent.as_ptr()).data) &*& struct_InternalNode_padding(parent.as_ptr()) + }; + @*/ + //@ on_unwind_ens false; + { + //@ assert [?q]points_to(&self, ?original); + //@ let view = precreate_ref(&self); + //@ init_ref_readonly(view, 1/2); + let leaf_ptr: *const _ = unsafe { Self::as_leaf_ptr(&self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self, _); + //@ open_points_to(&self); + let height = self.height; + let node = self.node; + //@ close_points_to(&self, q); + //@ std::ptr::NonNull_as_ptr_nonnull(original.node); + //@ std::ptr::NonNull_new_as_ptr(original.node); + let successor = unsafe { open_next_parent(leaf_ptr) }; + let result = match successor { + None => None, + Some((parent, observed_index)) => { + //@ assert path == cons(ParentStep(parent.as_ptr(), observed_index, ?len, ParentPayload(?keys, ?vals, ?edges)), ?higher); + //@ close ready_parent(t,parent,len,observed_index,_,keys,vals); + //@ close exists(parent); + let parent_height = height + 1; + Some(Handle { + node: unsafe { NodeRef::from_internal(parent, parent_height) }, + idx: observed_index as usize, + _marker: PhantomData, + }) + } + }; + result.ok_or(NodeRef { height, node, _marker: PhantomData }) + } +} + +impl NodeRef { + unsafe fn from_internal(node: NonNull>, height: usize) -> Self + //@ req height > 0; + //@ ens result.node.as_ptr() == node.as_ptr() as *LeafNode &*& result.height == height; + //@ on_unwind_ens false; + { + debug_assert!(height > 0); + //@ std::ptr::NonNull_as_ptr_as_usize_nonzero(node); + let leaf = unsafe { NonNull::new_unchecked(node.as_ptr() as *mut LeafNode) }; + NodeRef { height, node: leaf, _marker: PhantomData } + } +} + +/*@ +pred failed_full_parent( + t: thread_id_t, id: std::alloc::alloc_id_t, k: lifetime_t, + parent: NonNull>, index: usize, + children: list>>, + keys: list>, vals: list>, sibling: Option>> +) = + match sibling { + Option::None => + internal_slots(parent,CAPACITY,children,keys,vals) &*& pivot_owner(t,CAPACITY,index,keys,vals), + Option::Some(fresh) => + internal_slots(parent,insertion_pivot(index),take(insertion_pivot(index)+1,children),_,_) &*& + internal_slots(fresh,CAPACITY-insertion_pivot(index)-1,drop(insertion_pivot(index)+1,children),_,_) &*& + ancestors(&(*fresh.as_ptr()).data,[],&(*fresh.as_ptr()).data) &*& (*fresh.as_ptr()).data.parent_idx |-> _ &*& + allocated_internal(fresh.as_ptr(),id,k,_) + }; +@*/ + +/*@ +pred ready_parent( + t: thread_id_t, + parent: NonNull>, len: usize, index: usize, + children: list>>, slots_k: list>, slots_v: list> +) = internal_slots(parent,len,children,slots_k,slots_v) &*& pivot_owner(t,len,index,slots_k,slots_v); +@*/ + +// Check the dispatch and result ownership for both library insert methods. +// Allocation and array updates use the verified storage operations in insertion.rs. + +impl NodeRef { + unsafe fn reborrow_mut<'b>(&'b mut self) -> NodeRef, K, V, Type> + //@ req *self |-> ?node; + //@ ens *self |-> node &*& result.node == node.node &*& result.height == node.height; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let borrowed = NodeRef { height: self.height, node: self.node, _marker: PhantomData }; + //@ close_points_to(self); + borrowed + } +} + +impl NodeRef { + unsafe fn borrow_mut<'b>(&'b mut self) -> NodeRef, K, V, Type> + //@ req *self |-> ?node; + //@ ens *self |-> node &*& result.node == node.node &*& result.height == node.height; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let borrowed = NodeRef { height: self.height, node: self.node, _marker: PhantomData }; + //@ close_points_to(self); + borrowed + } +} + +impl NodeRef { + unsafe fn len(&self) -> usize + //@ req [?f](*self |-> ?node) &*& [?ql]((*node.node.as_ptr()).len |-> ?len); + //@ ens [f](*self |-> node) &*& [ql]((*node.node.as_ptr()).len |-> len) &*& result == len; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let ptr = self.node.as_ptr(); + //@ close_points_to(self, f); + unsafe { (*ptr).len as usize } + } +} + +impl Handle, marker::Edge> { + unsafe fn new_edge(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx <= len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx <= node.len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} + +impl Handle, marker::KV> { + unsafe fn new_kv(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx < len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx < node.len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} + +impl NodeRef { + unsafe fn len(&self) -> usize + //@ req [?f](*self |-> ?node) &*& [?ql]((*(node.node.as_ptr() as *InternalNode)).data.len |-> ?len); + //@ ens [f](*self |-> node) &*& [ql]((*(node.node.as_ptr() as *InternalNode)).data.len |-> len) &*& result == len; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let ptr = self.node.as_ptr() as *mut InternalNode; + //@ close_points_to(self, f); + unsafe { (*ptr).data.len as usize } + } +} + +impl Handle, marker::Edge> { + unsafe fn new_edge(node: NodeRef, idx: usize) -> Self + //@ req (*(node.node.as_ptr() as *InternalNode)).data.len |-> ?len &*& idx <= len; + //@ ens result.node == node &*& result.idx == idx &*& (*(node.node.as_ptr() as *InternalNode)).data.len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx <= node.len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} + +impl Handle, marker::KV> { + unsafe fn new_kv(node: NodeRef, idx: usize) -> Self + //@ req (*(node.node.as_ptr() as *InternalNode)).data.len |-> ?len &*& idx < len; + //@ ens result.node == node &*& result.idx == idx &*& (*(node.node.as_ptr() as *InternalNode)).data.len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx < node.len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} + +impl NodeRef { + unsafe fn len(&self) -> usize + //@ req [?f](*self |-> ?node) &*& [?ql]((*node.node.as_ptr()).len |-> ?len); + //@ ens [f](*self |-> node) &*& [ql]((*node.node.as_ptr()).len |-> len) &*& result == len; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let ptr = self.node.as_ptr(); + //@ close_points_to(self, f); + unsafe { (*ptr).len as usize } + } +} + +impl Handle, marker::Edge> { + unsafe fn new_edge(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx <= len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx <= node.len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} + +impl<'a,K,V> Handle,K,V,marker::Leaf>,marker::Edge> { + unsafe fn insert_fit(self, key: K, val: V) -> Handle,K,V,marker::Leaf>,marker::KV> + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + .own(t,key) &*& .own(t,val) &*& leaf_slots(self.node.node.as_ptr(),?len,_,_) &*& + 0 <= self.idx &*& self.idx <= len &*& len < CAPACITY; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,val) &*& + result.node == self.node &*& result.idx == self.idx &*& + dormant_pair(self.node.node.as_ptr(),self.idx,MaybeUninit::new(key),MaybeUninit::new(val)) &*& + leaf_rest(self.node.node.as_ptr(),self.idx); + @*/ + //@ on_unwind_ens false; + { + unsafe { fit_leaf(self.node.node, self.idx, key, val) }; + //@ open dormant_pair(self.node.node.as_ptr(),self.idx,MaybeUninit::new(key),MaybeUninit::new(val)); + let kv_handle = unsafe { + Handle::, K, V, marker::Leaf>, marker::KV>::new_kv(self.node, self.idx) + }; + //@ close dormant_pair(self.node.node.as_ptr(),self.idx,MaybeUninit::new(key),MaybeUninit::new(val)); + kv_handle + } +} + +/*@ +pred leaf_split_on_unwind( + t: thread_id_t, left: NonNull>, index: usize, + id: std::alloc::alloc_id_t, k: lifetime_t, keys: list>, vals: list>, + sibling: Option>> +) = + match sibling { + Option::None => leaf_slots(left.as_ptr(),CAPACITY,keys,vals) &*& pivot_owner(t,CAPACITY,index,keys,vals), + Option::Some(right) => allocated_leaf(right.as_ptr(),id,k,_) &*& detached_child(right.as_ptr()) &*& + leaf_slots(left.as_ptr(),insertion_pivot(index),_,_) &*& leaf_slots(right.as_ptr(),CAPACITY-insertion_pivot(index)-1,_,_) + }; +@*/ + +impl<'a,K,V> Handle,K,V,marker::Leaf>,marker::KV> { + unsafe fn split(self, alloc: A) -> SplitResult<'a,K,V,marker::Leaf> + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,alloc,?id) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& lifetime_inclusion(k,id.lft) == true &*& + exists::(?index) &*& self.idx == insertion_pivot(index) &*& self.node.height == 0 &*& 0 <= self.idx &*& self.idx < CAPACITY &*& + leaf_slots(self.node.node.as_ptr(),CAPACITY,?keys,?vals) &*& pivot_owner(t,CAPACITY,index,keys,vals); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& [available/2]lifetime_token(k) &*& + result.left == self.node &*& result.right.height == 0 &*& + exists::>>(?fresh) &*& result.right.node == fresh &*& + allocated_leaf(result.right.node.as_ptr(),id,k,_) &*& detached_child(result.right.node.as_ptr()) &*& + leaf_slots(result.left.node.as_ptr(),self.idx,_,_) &*& leaf_slots(result.right.node.as_ptr(),CAPACITY-self.idx-1,_,_) &*& + .own(t,result.kv.0) &*& .own(t,result.kv.1); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [?rest]lifetime_token(k) &*& exists::>>>(?sibling) &*& + leaf_split_on_unwind(t,self.node.node,index,id,k,keys,vals,sibling); + @*/ + { + //@ open exists(index); + //@ let left = self.node.node; + //@ close exists::>>>(Option::None); + //@ close leaf_split_on_unwind(t,left,index,id,k,keys,vals,Option::None); + let (right, allocator) = unsafe { fresh_leaf(alloc) }; + //@ open leaf_split_on_unwind(t,left,index,id,k,keys,vals,Option::None); + //@ open exists::>>>(Option::None); + //@ open pivot_owner(t,CAPACITY,index,keys,vals); + let kv = unsafe { split_full_leaf(self.node.node, right, self.idx) }; + //@ close exists(Option::Some(right)); + //@ close leaf_split_on_unwind(t,left,index,id,k,keys,vals,Option::Some(right)); + // MIR tracks the two fields separately because leaf_split_result moves them separately. + unsafe { drop_allocator(allocator) }; + //@ open leaf_split_on_unwind(t,left,index,id,k,keys,vals,Option::Some(right)); + //@ open exists(Option::Some(right)); + //@ close exists(right); + unsafe { leaf_split_result/*@::<'a,K,V>@*/(self.node.node,right,kv.0,kv.1) } + } +} + +impl<'a, K: 'a, V: 'a> Handle,K,V,marker::Leaf>,marker::Edge> { + unsafe fn insert( + self, key: K, val: V, alloc: A, + ) -> ( + Option>, + Handle, marker::KV>, + ) + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,alloc,?id) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& + lifetime_inclusion(k,id.lft) == true &*& self.node.height == 0 &*& .own(t,key) &*& .own(t,val) &*& + ancestors(self.node.node.as_ptr(),?path,?root) &*& (*root).parent_idx |-> ?root_index &*& + struct_LeafNode_padding(self.node.node.as_ptr()) &*& + leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= self.idx &*& self.idx <= len &*& pivot_owner(t,len,self.idx,keys,vals); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [?remaining]lifetime_token(k) &*& .own(t,key) &*& .own(t,val) &*& result.1.node.height == 0 &*& + ancestors(self.node.node.as_ptr(),path,root) &*& (*root).parent_idx |-> root_index &*& + struct_LeafNode_padding(self.node.node.as_ptr()) &*& + dormant_pair(result.1.node.node.as_ptr(),result.1.idx,MaybeUninit::new(key),MaybeUninit::new(val)) &*& + leaf_insert_sibling(result, self, t, len, id, k); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [?remaining]lifetime_token(k) &*& len == CAPACITY &*& + ancestor_tail(self.node.node.as_ptr(),path,root,root_index,?parent,?idx) &*& + leaf_header(self.node.node.as_ptr(),parent,idx) &*& leaf_slots(self.node.node.as_ptr(),len,keys,vals) &*& + nth(insertion_pivot(self.idx),keys).inner() == some(?promoted_key) &*& + nth(insertion_pivot(self.idx),vals).inner() == some(?promoted_val) &*& + .own(t,promoted_key) &*& .own(t,promoted_val); + @*/ + { + //@ let entry = self; + //@ let leaf = self.node.node.as_ptr(); + //@ open_ancestor_header(leaf,path,root); + let result = unsafe { self.insert_leaf_production/*@::<'a,K,V,A>@*/(key, val, alloc) }; + //@ close_ancestor_header(leaf,path,root); + //@ close leaf_insert_sibling(result,entry,t,len,id,k); + result + } +} + +impl<'a,K,V> Handle,K,V,marker::Internal>,marker::Edge> { + unsafe fn insert_fit(&mut self, key: K, val: V, edge: Root) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?incoming &*& incoming.node.height > 0 &*& edge.height == incoming.node.height - 1 &*& + exists::>>(?parent) &*& incoming.node.node.as_ptr() == parent.as_ptr() as *LeafNode &*& + internal_slots(parent,?len,?children,_,_) &*& 0 <= incoming.idx &*& incoming.idx <= len &*& len < CAPACITY &*& + ancestors(&(*parent.as_ptr()).data,?path,?root) &*& detached_child(edge.node.as_ptr()) &*& + .own(t,key) &*& .own(t,val); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& *self |-> incoming &*& + ancestors(&(*parent.as_ptr()).data,path,root) &*& .own(t,key) &*& .own(t,val) &*& + internal_slots(parent,len+1,append(take(incoming.idx+1,children),cons(edge.node,drop(incoming.idx+1,children))),_,_); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open_points_to(self); + //@ open_points_to(&(*self).node); + let ptr = self.node.node.as_ptr() as *mut InternalNode; + let index = self.idx; + //@ close_points_to(&(*self).node); + //@ close_points_to(self); + let receiver = unsafe { NonNull::new_unchecked(ptr) }; + //@ std::ptr::NonNull_new_as_ptr(receiver); + //@ std::ptr::NonNull_new_as_ptr(parent); + //@ open detached_child(edge.node.as_ptr()); + unsafe { fit_node(receiver,index,key,val,edge.node) }; + } +} + +impl<'a,K,V> Handle,K,V,marker::Internal>,marker::KV> { + unsafe fn split(self, alloc: A) -> SplitResult<'a,K,V,marker::Internal> + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,alloc,?id) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& lifetime_inclusion(k,id.lft) == true &*& + exists::(?index) &*& self.idx == insertion_pivot(index) &*& self.node.height > 0 &*& 0 <= self.idx &*& self.idx < CAPACITY &*& + exists::>>(?parent) &*& self.node.node.as_ptr() == parent.as_ptr() as *LeafNode &*& + ancestors(&(*parent.as_ptr()).data,?path,?root) &*& internal_slots(parent,CAPACITY,?children,?keys,?vals) &*& + pivot_owner(t,CAPACITY,index,keys,vals); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& [available/2]lifetime_token(k) &*& + result.left == self.node &*& result.right.height == self.node.height &*& + exists::>>(?fresh) &*& result.right.node.as_ptr() == fresh.as_ptr() as *LeafNode &*& + allocated_internal(fresh.as_ptr(),id,k,_) &*& (*fresh.as_ptr()).data.parent_idx |-> _ &*& + ancestors(&(*parent.as_ptr()).data,path,root) &*& ancestors(&(*fresh.as_ptr()).data,[],&(*fresh.as_ptr()).data) &*& + internal_slots(parent,self.idx,take(self.idx+1,children),_,_) &*& + internal_slots(fresh,CAPACITY-self.idx-1,drop(self.idx+1,children),_,_) &*& + .own(t,result.kv.0) &*& .own(t,result.kv.1) &*& + nth(self.idx,keys).inner() == some(result.kv.0) &*& nth(self.idx,vals).inner() == some(result.kv.1); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [?remaining]lifetime_token(k) &*& ancestors(&(*parent.as_ptr()).data,path,root) &*& + exists::>>>(?sibling) &*& failed_full_parent(t,id,k,parent,index,children,keys,vals,sibling); + @*/ + { + //@ open exists(parent); + //@ open exists(index); + let parent_ptr = self.node.node.as_ptr() as *mut InternalNode; + let receiver = unsafe { NonNull::new_unchecked(parent_ptr) }; + //@ std::ptr::NonNull_new_as_ptr(receiver); + //@ std::ptr::NonNull_new_as_ptr(parent); + //@ close exists::>>>(Option::None); + //@ close failed_full_parent(t,id,k,parent,index,children,keys,vals,Option::None); + let (fresh, allocator) = unsafe { fresh_internal(alloc) }; + //@ open exists::>>>(Option::None); + //@ open failed_full_parent(t,id,k,parent,index,children,keys,vals,Option::None); + //@ open pivot_owner(t,CAPACITY,index,keys,vals); + let kv = unsafe { split_full_node(receiver,fresh,self.idx) }; + //@ close exists(Option::Some(fresh)); + //@ close failed_full_parent(t,id,k,parent,index,children,keys,vals,Option::Some(fresh)); + //@ close_tuple_2_own(t,kv); + unsafe { drop_allocator(allocator) }; + //@ open_tuple_2_own(t,kv); + //@ open exists(Option::Some(fresh)); + //@ open failed_full_parent(t,id,k,parent,index,children,keys,vals,Option::Some(fresh)); + let right = unsafe { NonNull::new_unchecked(fresh.as_ptr() as *mut LeafNode) }; + //@ close exists(fresh); + let height = self.node.height; + SplitResult { + left: self.node, + kv, + right: NodeRef { height, node: right, _marker: PhantomData }, + } + } +} + +impl<'tree,K,V> Handle,K,V,marker::Internal>,marker::Edge> { + // BEGIN_INTERNAL_DISPATCH + unsafe fn insert_exact(mut self, key: K, val: V, edge: Root, alloc: A) + -> Option> + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,alloc,?id) &*& + exists::(?k) &*& [?available]lifetime_token(k) &*& lifetime_inclusion(k,id.lft) == true &*& + .own(t,key) &*& .own(t,val) &*& 0 < self.node.height &*& self.node.height <= usize::MAX &*& edge.height == self.node.height - 1 &*& + exists::>>(?parent) &*& self.node.node.as_ptr() == parent.as_ptr() as *LeafNode &*& + ready_parent(t,parent,?len,self.idx,?children,?keys,?vals) &*& + ancestors(&(*parent.as_ptr()).data,?path,?root) &*& 0 <= self.idx &*& self.idx <= len &*& len <= CAPACITY &*& + detached_child(edge.node.as_ptr()); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + ancestors(&(*parent.as_ptr()).data,path,root) &*& .own(t,key) &*& .own(t,val) &*& + [?remaining]lifetime_token(k) &*& + match result { + Option::None => len < CAPACITY &*& internal_slots(parent,len+1,append(take(self.idx+1,children),cons(edge.node,drop(self.idx+1,children))),_,_), + Option::Some(split) => len == CAPACITY &*& + split.left.node.as_ptr() == parent.as_ptr() as *LeafNode &*& + split.left.height == self.node.height &*& split.right.height == self.node.height &*& + exists::>>(?fresh) &*& split.right.node.as_ptr() == fresh.as_ptr() as *LeafNode &*& + allocated_internal(fresh.as_ptr(),id,k,_) &*& (*fresh.as_ptr()).data.parent_idx |-> _ &*& + ancestors(&(*fresh.as_ptr()).data,[],&(*fresh.as_ptr()).data) &*& + internal_slots(parent,?left_len,_,_,_) &*& internal_slots(fresh,?right_len,_,_,_) &*& left_len + right_len == CAPACITY &*& + .own(t,split.kv.0) &*& .own(t,split.kv.1) &*& + nth(insertion_pivot(self.idx),keys).inner() == some(split.kv.0) &*& nth(insertion_pivot(self.idx),vals).inner() == some(split.kv.1) + }; + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + ancestors(&(*parent.as_ptr()).data,path,root) &*& + [?remaining]lifetime_token(k) &*& + if len < CAPACITY { + .own(t,key) &*& .own(t,val) &*& internal_slots(parent,len+1,append(take(self.idx+1,children),cons(edge.node,drop(self.idx+1,children))),_,_) + } else { + detached_child(edge.node.as_ptr()) &*& + exists::>>>(?sibling) &*& failed_full_parent(t,id,k,parent,self.idx,children,keys,vals,sibling) + }; + @*/ + { + //@ open exists(k); + //@ open exists(parent); + //@ assert [?fraction]points_to(&self,?incoming); + //@ let index = incoming.idx; + //@ open_points_to(&self); + //@ open_points_to(&self.node); + assert!(edge.height == self.node.height - 1); + //@ close_points_to(&self.node,fraction); + //@ open ready_parent(t,parent,len,index,children,keys,vals); + //@ open internal_slots(parent,len,children,keys,vals); + //@ let view = precreate_ref(&self.node); + //@ init_ref_readonly(view,1/2); + let fits = unsafe { self.node.len() < CAPACITY }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self.node,_); + //@ close internal_slots(parent,len,children,keys,vals); + if fits { + //@ open pivot_owner(t,len,index,keys,vals); + //@ close exists(parent); + unsafe { self.insert_fit/*@::<'tree,K,V,'tree>@*/(key, val, edge) }; + //@ std::alloc::Allocator_to_own(alloc); + None + } else { + let (middle_kv_idx, insertion) = unsafe { splitpoint(self.idx) }; + //@ open internal_slots(parent,len,children,keys,vals); + //@ open_points_to(&self.node); + let node = NodeRef::, K, V, marker::Internal> { + height: self.node.height, + node: self.node.node, + _marker: PhantomData, + }; + //@ close_points_to(&self.node); + //@ close Handle_node_(&self, some(incoming.node)); + let middle = unsafe { + Handle::, K, V, marker::Internal>, marker::KV>::new_kv/*@::,K,V>@*/( + node, middle_kv_idx, + ) + }; + //@ close internal_slots(parent,len,children,keys,vals); + //@ close exists(k); + //@ close exists(index); + //@ close exists(parent); + let mut result = unsafe { middle.split/*@::<'tree,K,V,A>@*/(alloc) }; + //@ open exists::>>(?fresh); + let mut insertion_edge = match insertion { + LeftOrRight::Left(insert_idx) => unsafe { + //@ open internal_slots(parent,middle_kv_idx,take(middle_kv_idx+1,children),_,_); + let selected = Handle::, K, V, marker::Internal>, marker::Edge>::new_edge( + result.left.reborrow_mut(), insert_idx, + ); + //@ close internal_slots(parent,middle_kv_idx,take(middle_kv_idx+1,children),_,_); + selected + }, + LeftOrRight::Right(insert_idx) => unsafe { + //@ open internal_slots(fresh,CAPACITY-middle_kv_idx-1,drop(middle_kv_idx+1,children),_,_); + let selected = Handle::, K, V, marker::Internal>, marker::Edge>::new_edge( + result.right.borrow_mut(), insert_idx, + ); + //@ close internal_slots(fresh,CAPACITY-middle_kv_idx-1,drop(middle_kv_idx+1,children),_,_); + selected + }, + }; + /*@ match insertion { + LeftOrRight::Left(at) => { close exists(parent); } + LeftOrRight::Right(at) => { close exists(fresh); } + } @*/ + //@ close_points_to(&insertion_edge.node); + unsafe { insertion_edge.insert_fit/*@::<'tree,K,V,'tree>@*/(key, val, edge) }; + //@ open_points_to(&insertion_edge); + //@ open_points_to(&insertion_edge.node); + //@ close exists(fresh); + let output = Some(result); + output + } + } + // END_INTERNAL_DISPATCH +} + +// Project the two internal roots to their leaf prefixes for the propagation +// invariant. The dispatch itself uses the whole internal allocation. +impl<'tree, K: 'tree, V: 'tree> Handle, K, V, marker::Internal>, marker::Edge> { + unsafe fn insert(self, key: K, val: V, edge: Root, alloc: A) + -> Option> + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,alloc,?id) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& + lifetime_inclusion(k,id.lft) == true &*& self.node.height > 0 &*& edge.height == self.node.height - 1 &*& + exists::>>(?parent) &*& self.node.node.as_ptr() == &(*parent.as_ptr()).data &*& + ready_parent(t,parent,?len,self.idx,?children,?keys,?vals) &*& 0 <= self.idx &*& self.idx <= len &*& + ancestors(&(*parent.as_ptr()).data,?path,?root) &*& (*root).parent_idx |-> ?root_index &*& + struct_LeafNode_padding(&(*parent.as_ptr()).data) &*& struct_InternalNode_padding(parent.as_ptr()) &*& + detached_child(edge.node.as_ptr()) &*& .own(t,key) &*& .own(t,val); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + ancestors(&(*parent.as_ptr()).data,path,root) &*& (*root).parent_idx |-> root_index &*& + struct_LeafNode_padding(&(*parent.as_ptr()).data) &*& struct_InternalNode_padding(parent.as_ptr()) &*& + .own(t,key) &*& .own(t,val) &*& + match result { + Option::None => len < CAPACITY &*& [available]lifetime_token(k) &*& + internal_slots(parent,len+1,insert_item(children,self.idx+1,edge.node),_,_), + Option::Some(split) => len == CAPACITY &*& [available/2]lifetime_token(k) &*& + split.left == self.node &*& split.right.height == self.node.height &*& + exists::>>(?fresh) &*& split.right.node.as_ptr() == &(*fresh.as_ptr()).data &*& + allocated_internal(fresh.as_ptr(),id,k,available/2) &*& detached_child(split.right.node.as_ptr()) &*& + internal_slots(parent,?left_len,?left_children,_,_) &*& + internal_slots(fresh,?right_len,?right_children,_,_) &*& left_len + right_len == len &*& + append(left_children,right_children) == insert_item(children,self.idx+1,edge.node) &*& + .own(t,split.kv.0) &*& .own(t,split.kv.1) + }; + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [available]lifetime_token(k) &*& struct_InternalNode_padding(parent.as_ptr()) &*& + ancestor_tail(&(*parent.as_ptr()).data,path,root,root_index,?ancestor,?ancestor_idx) &*& + leaf_header(&(*parent.as_ptr()).data,ancestor,ancestor_idx) &*& + internal_slots(parent,len,children,keys,vals) &*& detached_child(edge.node.as_ptr()) &*& + if len == CAPACITY { + nth(insertion_pivot(self.idx), keys).inner() == some(?pivot_key) &*& + nth(insertion_pivot(self.idx), vals).inner() == some(?pivot_val) &*& + .own(t,pivot_key) &*& .own(t,pivot_val) + } else { true }; + @*/ + { + //@ open exists(parent); + //@ open ready_parent(t,parent,len,self.idx,children,keys,vals); + //@ let parent_data = &(*parent.as_ptr()).data; + //@ open_ancestor_header(parent_data,path,root); + //@ close exists(parent); + let result = unsafe { self.insert_production/*@::<'tree,K,V,A>@*/(key,val,edge,alloc) }; + //@ close_ancestor_header(parent_data,path,root); + /*@ match result { + Option::None => {} + Option::Some(split) => { close detached_child(split.right.node.as_ptr()); } + } @*/ + result + } +} + + +impl<'a, K: 'a, V: 'a> Handle,K,V,marker::Leaf>,marker::Edge> { + unsafe fn clone_and_insert( + self, key: K, val: V, alloc: &A, + ) -> ( + Option>, + Handle, marker::KV>, + ) + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + [_]allocator_clone_bound::() &*& + [_]std::alloc::Allocator_share::(?alloc_lifetime,t,alloc,?id) &*& + [_]frac_borrow(alloc_lifetime,ref_initialized_(alloc)) &*& [?qa]lifetime_token(alloc_lifetime) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& + lifetime_inclusion(k,id.lft) == true &*& self.node.height == 0 &*& .own(t,key) &*& .own(t,val) &*& + ancestors(self.node.node.as_ptr(),?path,?root) &*& (*root).parent_idx |-> ?root_index &*& + struct_LeafNode_padding(self.node.node.as_ptr()) &*& + leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= self.idx &*& self.idx <= len &*& pivot_owner(t,len,self.idx,keys,vals); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [qa]lifetime_token(alloc_lifetime) &*& [?remaining]lifetime_token(k) &*& .own(t,key) &*& .own(t,val) &*& result.1.node.height == 0 &*& + ancestors(self.node.node.as_ptr(),path,root) &*& (*root).parent_idx |-> root_index &*& + struct_LeafNode_padding(self.node.node.as_ptr()) &*& + dormant_pair(result.1.node.node.as_ptr(),result.1.idx,MaybeUninit::new(key),MaybeUninit::new(val)) &*& + leaf_insert_sibling(result, self, t, len, id, k); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [qa]lifetime_token(alloc_lifetime) &*& [?remaining]lifetime_token(k) &*& len == CAPACITY &*& + ancestor_tail(self.node.node.as_ptr(),path,root,root_index,?parent,?idx) &*& + leaf_header(self.node.node.as_ptr(),parent,idx) &*& leaf_slots(self.node.node.as_ptr(),len,keys,vals) &*& + nth(insertion_pivot(self.idx),keys).inner() == some(?promoted_key) &*& + nth(insertion_pivot(self.idx),vals).inner() == some(?promoted_val) &*& + .own(t,promoted_key) &*& .own(t,promoted_val); + @*/ + { + unsafe { self.insert/*@::<'a,K,V,A>@*/(key, val, alloc.clone()) } + } +} + +/*@ +inductive Placement = Placement(NonNull>, NonNull>, K, V); + +pred completed_levels(t: thread_id_t, alloc_id: std::alloc::alloc_id_t, k: lifetime_t, records: list>) = + match records { + nil => true, + cons(record, rest) => + match record { + Placement(left, right, key, value) => + internal_slots(left, _, _, _, _) &*& internal_slots(right, _, _, _, _) &*& + struct_LeafNode_padding(&(*left.as_ptr()).data) &*& struct_InternalNode_padding(left.as_ptr()) &*& + allocated_internal(right.as_ptr(),alloc_id,k,_) &*& .own(t,key) &*& .own(t,value) &*& completed_levels(t,alloc_id,k,rest) + } + }; +@*/ + +/*@ +pred detached_child(child: *LeafNode;) = + (*child).parent |-> Option::None &*& (*child).parent_idx |-> _; +@*/ + +/*@ +pred leaf_slots(node: *LeafNode, len: usize; keys: list>, vals: list>) = + (*node).len |-> (len as u16) &*& 0 <= len &*& len <= CAPACITY &*& + pointer_within_limits(&(*node).keys) == true &*& pointer_within_limits(&(*node).vals) == true &*& + (*node).keys[..CAPACITY] |-> keys &*& (*node).vals[..CAPACITY] |-> vals; + +pred leaf_rest(node: *LeafNode, index: usize;) = + (*node).keys[..index] |-> ?keys_before &*& (*node).keys[index+1..CAPACITY] |-> ?keys_after &*& + (*node).vals[..index] |-> ?vals_before &*& (*node).vals[index+1..CAPACITY] |-> ?vals_after; +@*/ + +unsafe fn fit_leaf(leaf: NonNull>, index: usize, key: K, value: V) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,value) &*& + leaf_slots(leaf.as_ptr(),?len,?keys,?vals) &*& 0 <= index &*& index <= len &*& len < CAPACITY; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,value) &*& + dormant_pair(leaf.as_ptr(), index, MaybeUninit::new(key), MaybeUninit::new(value)) &*& leaf_rest(leaf.as_ptr(),index); +@*/ +//@ on_unwind_ens false; +{ + let leaf_ptr = leaf.as_ptr(); + //@ open leaf_slots(leaf_ptr,len,keys,vals); + let new_len = unsafe { (*leaf_ptr).len } as usize + 1; + let key_base = unsafe { (&raw mut (*leaf_ptr).keys) as *mut MaybeUninit }; + let val_base = unsafe { (&raw mut (*leaf_ptr).vals) as *mut MaybeUninit }; + //@ array_split(key_base,new_len); + //@ array_split(val_base,new_len); + //@ insertion_slot_limits(key_base); + //@ insertion_slot_limits(val_base); + unsafe { + slice_insert(std::slice::from_raw_parts_mut(key_base, new_len), index, key); + slice_insert(std::slice::from_raw_parts_mut(val_base, new_len), index, value); + (*leaf_ptr).len = new_len as u16; + } + /*@ { + assert key_base[..new_len] |-> ?fitted_keys; + assert val_base[..new_len] |-> ?fitted_vals; + array_join(key_base); + array_join(val_base); + length_take(new_len,keys); + length_take(new_len,vals); + length_take(index,take(new_len,keys)); + length_take(index,take(new_len,vals)); + btree_drop_append_left(index,fitted_keys,drop(new_len,keys)); + btree_drop_append_left(index,fitted_vals,drop(new_len,vals)); + drop_append(index,take(index,take(new_len,keys)),cons(MaybeUninit::new(key),take(len-index,drop(index,take(new_len,keys))))); + drop_append(index,take(index,take(new_len,vals)),cons(MaybeUninit::new(value),take(len-index,drop(index,take(new_len,vals))))); + array_split(key_base,index); + array_split(val_base,index); + array_split(key_base+index,1); + array_split(val_base+index,1); + open array(key_base+index,1,[MaybeUninit::new(key)]); + open array(val_base+index,1,[MaybeUninit::new(value)]); + close dormant_pair(leaf_ptr,index,MaybeUninit::new(key),MaybeUninit::new(value)); + close leaf_rest(leaf_ptr,index); + } @*/ +} + +unsafe fn split_full_leaf( + left: NonNull>, + right: NonNull>, + pivot: usize, +) -> (K, V) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + leaf_slots(left.as_ptr(),CAPACITY,?keys,?vals) &*& leaf_slots(right.as_ptr(),0,?right_keys,?right_vals) &*& + 0 <= pivot &*& pivot < CAPACITY &*& + nth(pivot,keys).inner() == some(?promoted_key) &*& nth(pivot,vals).inner() == some(?promoted_value) &*& + .own(t,promoted_key) &*& .own(t,promoted_value); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + leaf_slots(left.as_ptr(),pivot,_,_) &*& leaf_slots(right.as_ptr(),CAPACITY-pivot-1,_,_) &*& + result.0 == promoted_key &*& result.1 == promoted_value &*& .own(t,promoted_key) &*& .own(t,promoted_value); +@*/ +//@ on_unwind_ens false; +{ + let src = left.as_ptr(); + let dst = right.as_ptr(); + //@ open leaf_slots(src,CAPACITY,keys,vals); + //@ open leaf_slots(dst,0,right_keys,right_vals); + let len = unsafe { (*src).len } as usize; + let new_len = len - pivot - 1; + unsafe { (*dst).len = new_len as u16 }; + let key_base = unsafe { (&raw const (*src).keys) as *const MaybeUninit }; + let val_base = unsafe { (&raw const (*src).vals) as *const MaybeUninit }; + let right_key_base = unsafe { (&raw mut (*dst).keys) as *mut MaybeUninit }; + let right_val_base = unsafe { (&raw mut (*dst).vals) as *mut MaybeUninit }; + /*@ { + array_split(key_base,pivot); + array_split(key_base+pivot,1); + array_split(val_base,pivot); + array_split(val_base+pivot,1); + drop_n_plus_one(pivot,keys); + drop_n_plus_one(pivot,vals); + open array(key_base+pivot,1,take(1,drop(pivot,keys))); + open array(val_base+pivot,1,take(1,drop(pivot,vals))); + } @*/ + let key = unsafe { read_promoted(key_base.add(pivot)) }; + let value = unsafe { read_promoted(val_base.add(pivot)) }; + /*@ { + close array(key_base+pivot,1,[MaybeUninit::new(key)]); + close array(val_base+pivot,1,[MaybeUninit::new(value)]); + array_split(right_key_base,new_len); + array_split(right_val_base,new_len); + array_to_array_(right_key_base); + array_to_array_(right_val_base); + } @*/ + unsafe { + ptr::copy_nonoverlapping(key_base.add(pivot + 1), right_key_base, new_len); + ptr::copy_nonoverlapping(val_base.add(pivot + 1), right_val_base, new_len); + (*src).len = pivot as u16; + } + /*@ { + array_join(key_base+pivot); + array_join(key_base); + array_join(val_base+pivot); + array_join(val_base); + array_join(right_key_base); + array_join(right_val_base); + close leaf_slots(src,pivot,_,_); + close leaf_slots(dst,new_len,_,_); + } @*/ + (key, value) +} + +/*@ +pred allocated_leaf(node: *LeafNode, alloc_id: std::alloc::alloc_id_t,k: lifetime_t, q: real) = + std::alloc::alloc_block_in(alloc_id,node as *u8,std::alloc::Layout::new::>()) &*& + close_points_to_at_lft_token(1,alloc_id.lft,node,?alloc_fraction) &*& + close_lifetime_trade_token(alloc_fraction,alloc_id.lft,q,k) &*& struct_LeafNode_padding(node); +@*/ + +unsafe fn fresh_leaf(alloc: A) -> (NonNull>, A) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,alloc,?alloc_id) &*& exists::(?k) &*& [?q]lifetime_token(k) &*& lifetime_inclusion(k,alloc_id.lft) == true; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& [q/2]lifetime_token(k) &*& + Allocator::(t,result.1,alloc_id) &*& allocated_leaf(result.0.as_ptr(),alloc_id,k,q/2) &*& leaf_slots(result.0.as_ptr(),0,_,_) &*& detached_child(result.0.as_ptr()); +@*/ +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& [q]lifetime_token(k); +{ + let leaf = unsafe { LeafNode::::new(alloc) }; + let (node, retained_allocator) = Box::into_non_null_with_allocator(leaf); + //@ let pointer = node.as_ptr(); + //@ close reserve_allocation(k,q/2); + //@ let q_alloc = lifetime_token_trade(k,q/2,alloc_id.lft); + //@ open_points_to_at_lft(pointer, q_alloc); + //@ points_to_limits(pointer); + //@ open_points_to(pointer); + //@ close allocated_leaf(pointer, alloc_id, k, q/2); + //@ close leaf_slots(pointer, 0, _, _); + //@ close detached_child(pointer); + //@ open reserve_allocation(k,q/2); + (node, retained_allocator) +} + +/*@ +pred insertion_leaves( + first: NonNull>, + inserted: NonNull>, + index: usize, + split: Option>>, + alloc_id: std::alloc::alloc_id_t, + k: lifetime_t +) = + leaf_rest(inserted.as_ptr(),index) &*& + match split { + Option::None => inserted == first, + Option::Some(right) => + allocated_leaf(right.as_ptr(),alloc_id,k,_) &*& + exists::>>(?other) &*& + leaf_slots(other.as_ptr(),_,_,_) &*& + ((inserted == first && other == right) || (inserted == right && other == first)) + }; +@*/ + +// VeriFast 26.10 hoists Rust MIR's temporary storage to function scope. +// Preserve the compiler's private stack slots through the loop invariant. +/*@ +pred cursor_node_buffer(p: *NodeRef;) = + struct_NodeRef_padding(p) &*& (*p).height |-> _ &*& (*p).node |-> _; + +pred cursor_pair_buffer(p: *std_tuple_2_;) = + struct_std_tuple_2__padding(p) &*& (*p).0 |-> _ &*& (*p).1 |-> _; + +pred cursor_split_buffer<'tree,K,V,T>(p: *SplitResult<'tree,K,V,T>;) = + struct_SplitResult_padding(p) &*& cursor_node_buffer(&(*p).left) &*& + cursor_pair_buffer(&(*p).kv) &*& cursor_node_buffer(&(*p).right); + +pred cursor_handle_buffer(p: *Handle,H>;) = + struct_Handle_padding(p) &*& cursor_node_buffer(&(*p).node) &*& (*p).idx |-> _; +@*/ + +/*@ +pred root_split_header(p: *LeafNode;) = + (*p).parent |-> _ &*& (*p).parent_idx |-> _; + +pred root_split_inputs( + left: *LeafNode, right: *LeafNode, inserted: *LeafNode, index: usize; + left_index: MaybeUninit, key_cell: MaybeUninit, val_cell: MaybeUninit +) = + ancestors(left, [], left) &*& (*left).parent_idx |-> left_index &*& detached_child(right) &*& + dormant_pair(inserted,index,key_cell,val_cell); +@*/ + +// The production loop takes its split and dormant handle from leaf insertion. +// Its allocator is borrowed because the loop only uses it to clone. +// The root branch establishes the storage needed for concrete installation +// and awakening. The generic call uses the standard FnOnce ownership contract. +// BEGIN_PRODUCTION_LOOP + +// END_PRODUCTION_LOOP + +// Check the ownership transfer after the leaf call, including the early +// return when the leaf absorbs the insertion. +// BEGIN_LEAF_HANDOFF + +// END_LEAF_HANDOFF + +// The concrete root callbacks use these node operations after reborrowing +// the root slot. The guarded replacement is checked separately. +unsafe fn install_root_split<'tree, 'slot, K, V, A: AllocatorClone>( + root_slot: &'slot mut DormantMutRef<'tree, Option>>, + allocator: &mut A, + left: NonNull>, + key: K, + value: V, + right: Root, +) +/*@ +req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + [_]allocator_clone_bound::() &*& + *allocator |-> ?original_allocator &*& Allocator::(t,original_allocator,?id) &*& + exists::(?k) &*& [?available]lifetime_token(k) &*& lifetime_inclusion(k,id.lft) == true &*& + *root_slot |-> ?sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(?old_root) &*& + old_root.node == left &*& old_root.height < usize::MAX &*& right.height == old_root.height &*& + ancestors(left.as_ptr(),[],left.as_ptr()) &*& (*left.as_ptr()).parent_idx |-> ?left_index &*& + detached_child(right.node.as_ptr()) &*& .own(t,key) &*& .own(t,value); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + *allocator |-> ?after &*& Allocator::(t,after,id) &*& [available/2]lifetime_token(k) &*& + *root_slot |-> sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(?installed) &*& + installed.height == old_root.height + 1 &*& + exists::>>(?root) &*& installed.node.as_ptr() == &(*root.as_ptr()).data &*& + allocated_internal(root.as_ptr(),id,k,_) &*& (*root.as_ptr()).data.parent_idx |-> _ &*& + ancestors(installed.node.as_ptr(),[],installed.node.as_ptr()) &*& + internal_slots(root,1,[left,right.node],_,_) &*& .own(t,key) &*& .own(t,value); +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + *allocator |-> ?after &*& Allocator::(t,after,id) &*& [?remaining]lifetime_token(k) &*& + *root_slot |-> sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& + detached_child(right.node.as_ptr()) &*& + exists::>>>(?partial_root) &*& interrupted_root_change(left,left_index,id,k,partial_root); +@*/ +{ + //@ open exists(k); + let borrowed_root = unsafe { root_slot.reborrow/*@::<'tree, Option>, 'slot>@*/() }; + let root_payload = borrowed_root.as_mut().unwrap(); + let root_allocator = unsafe { clone_allocator(allocator) }; + let old = unsafe { ptr::read(root_payload) }; + //@ std::option::close_points_to_Option_Some(borrowed_root); + //@ close exists(k); + let new = unsafe { + NodeRef::::new_internal_production(old,root_allocator).forget_type() + }; + //@ std::option::open_points_to_Option_Some(borrowed_root); + unsafe { ptr::write(root_payload,new) }; + + //@ open exists::>>(?root); + //@ std::ptr::NonNull_Sized_as_ptr(root); + //@ let data = &(*root.as_ptr()).data; + //@ open allocated_internal(root.as_ptr(),id,k,available/2); + //@ open_ancestor_header(data,[],data); + //@ open_points_to(root_payload); + let mut view = NodeRef::,K,V,marker::Internal> { + height: root_payload.height, node: root_payload.node, _marker: PhantomData + }; + //@ close_points_to(root_payload); + //@ std::option::close_points_to_Option_Some(borrowed_root); + //@ close exists(root); + unsafe { view.push_production/*@::<'slot,K,V,'slot>@*/(key,value,right) }; //~track_ref_creation + //@ assert ref_mut_end_token(?view_ref,&mut view); + //@ end_ref_mut(view_ref); + //@ close_ancestor_header(data,[],data); + //@ close allocated_internal(root.as_ptr(),id,k,available/2); + //@ close exists(root); +} + +// Consume the physical root split before recovering the outstanding leaf handle. +// BEGIN_FINISH_ROOT_SPLIT +unsafe fn finish_root_split<'tree, 'slot, K, V, A: AllocatorClone>( + split: SplitResult<'tree, K, V, marker::LeafOrInternal>, + inserted: Handle, marker::KV>, + root_slot: &'slot mut DormantMutRef<'tree, Option>>, + allocator: &'slot mut A, +) -> Handle, K, V, marker::Leaf>, marker::KV> +/*@ +req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + [_]allocator_clone_bound::() &*& + *allocator |-> ?original_allocator &*& Allocator::(t,original_allocator,?id) &*& + exists::(?k) &*& [?available]lifetime_token(k) &*& lifetime_inclusion(k,id.lft) == true &*& + *root_slot |-> ?sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(?old_root) &*& + old_root.node == split.left.node &*& old_root.height == split.left.height &*& + old_root.height < usize::MAX &*& split.right.height == old_root.height &*& + root_split_inputs(?left,?right,?leaf,?index,?left_index,?key_cell,?val_cell) &*& + left == split.left.node.as_ptr() &*& right == split.right.node.as_ptr() &*& + leaf == inserted.node.node.as_ptr() &*& index == inserted.idx &*& inserted.node.height == 0 &*& + .own(t,split.kv.0) &*& .own(t,split.kv.1); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + *allocator |-> ?after &*& Allocator::(t,after,id) &*& [available/2]lifetime_token(k) &*& + *root_slot |-> sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(?installed) &*& + installed.height == old_root.height + 1 &*& + exists::>>(?root) &*& installed.node.as_ptr() == &(*root.as_ptr()).data &*& + allocated_internal(root.as_ptr(),id,k,_) &*& (*root.as_ptr()).data.parent_idx |-> _ &*& + ancestors(installed.node.as_ptr(),[],installed.node.as_ptr()) &*& internal_slots(root,1,[split.left.node,split.right.node],_,_) &*& + .own(t,split.kv.0) &*& .own(t,split.kv.1) &*& + result.node.height == 0 &*& result.node.node == inserted.node.node &*& result.idx == inserted.idx &*& + dormant_pair(result.node.node.as_ptr(),result.idx,key_cell,val_cell); +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + *allocator |-> ?after &*& Allocator::(t,after,id) &*& [?remaining]lifetime_token(k) &*& + *root_slot |-> sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& detached_child(split.right.node.as_ptr()) &*& + exists::>>>(?partial_root) &*& + interrupted_root_change(split.left.node,left_index,id,k,partial_root) &*& + dormant_pair(inserted.node.node.as_ptr(),inserted.idx,key_cell,val_cell); +@*/ +{ + //@ open root_split_inputs(left,right,leaf,index,left_index,key_cell,val_cell); + //@ open_points_to(&split); + //@ open_points_to(&split.left); + let original_root = split.left.node; + //@ close_points_to(&split.left, 1/2); + //@ open_points_to(&split.kv); + let key = split.kv.0; + let value = split.kv.1; + //@ close_points_to(&split.kv, 1/2); + let sibling = split.right; + //@ close_points_to(&split, 1/2); + unsafe { + install_root_split/*@::@*/(root_slot, allocator, original_root, key, value, sibling); + inserted.awaken/*@::@*/() + } +} +// END_FINISH_ROOT_SPLIT + +/*@ +pred interrupted_root_change( + old_root: NonNull>, old_index: MaybeUninit, + alloc_id: std::alloc::alloc_id_t, k: lifetime_t, new_root: Option>> +) = + match new_root { + Option::None => + ancestors(old_root.as_ptr(),[],old_root.as_ptr()) &*& (*old_root.as_ptr()).parent_idx |-> old_index, + Option::Some(node) => + allocated_internal(node.as_ptr(),alloc_id,k,_) &*& (*node.as_ptr()).data.parent_idx |-> _ &*& + ancestors(&(*node.as_ptr()).data,[],&(*node.as_ptr()).data) &*& internal_slots(node,0,[old_root],_,_) + }; +@*/ + +// BEGIN_NEW_INTERNAL + +// END_NEW_INTERNAL + +unsafe fn leaf_split_result<'tree,K,V>(left: NonNull>, right: NonNull>, key:K, val:V) -> SplitResult<'tree,K,V,marker::Leaf> +/*@ +req true; +@*/ +/*@ +ens result == SplitResult::<'tree,K,V,marker::Leaf> { + left: NodeRef::,K,V,marker::Leaf> { height: 0, node: left }, + kv: std_tuple_2_:: { 0: key, 1: val }, + right: NodeRef:: { height: 0, node: right }, +}; +@*/ +//@ on_unwind_ens false; +{ + SplitResult { + left: NodeRef::,K,V,marker::Leaf> { height: 0, node: left, _marker: PhantomData }, + kv: (key,val), + right: NodeRef:: { height: 0, node: right, _marker: PhantomData }, + } +} + +// The owned tuple is the normal result of Handle::insert. Keep its handoff +// separate so VeriFast need not unpack an uninitialized tuple on unwind +// from the call that creates it. +// BEGIN_ROOT_HANDOFF +unsafe fn resume_after_leaf_insert_for_root<'tree, 'alloc, 'slot, K: 'tree, V: 'tree, A: AllocatorClone>( + initial: (Option>, Handle,marker::KV>), + alloc: &'alloc A, + root_slot: &'slot mut DormantMutRef<'tree, Option>>, + root_allocator: &'slot mut A, +) -> Handle,K,V,marker::Leaf>,marker::KV> +/*@ +req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + [_]allocator_clone_bound::() &*& + [_]std::alloc::Allocator_share::(?alloc_lifetime,t,alloc,?alloc_id) &*& + [_]frac_borrow(alloc_lifetime, ref_initialized_(alloc)) &*& [?qa]lifetime_token(alloc_lifetime) &*& + [?available]lifetime_token(?k) &*& lifetime_inclusion(k,alloc_id.lft) == true &*& + exists::>>(?first) &*& + ancestors(first.as_ptr(),?path,?root) &*& route_frames(t,path) &*& (*root).parent_idx |-> ?root_index &*& + *root_allocator |-> ?root_alloc &*& Allocator::(t,root_alloc,alloc_id) &*& + *root_slot |-> ?sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(?old_root) &*& + old_root.node.as_ptr() == root &*& old_root.height == length(path) &*& + length(path) < usize::MAX &*& initial.1.node.height == 0 &*& + dormant_pair(initial.1.node.node.as_ptr(),initial.1.idx,?key_cell,?val_cell) &*& + key_cell.inner() == some(?key) &*& val_cell.inner() == some(?value) &*& + .own(t,key) &*& .own(t,value) &*& + match initial.0 { + Option::None => insertion_leaves(first,initial.1.node.node,initial.1.idx,Option::None,alloc_id,k), + Option::Some(leaf_split) => leaf_split.left.node == first &*& leaf_split.left.height == 0 &*& leaf_split.right.height == 0 &*& + insertion_leaves(first,initial.1.node.node,initial.1.idx,Option::Some(leaf_split.right.node),alloc_id,k) &*& + detached_child(leaf_split.right.node.as_ptr()) &*& .own(t,leaf_split.kv.0) &*& .own(t,leaf_split.kv.1) + }; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [qa]lifetime_token(alloc_lifetime) &*& [?remaining_fraction]lifetime_token(k) &*& + *root_allocator |-> ?after &*& Allocator::(t,after,alloc_id) &*& *root_slot |-> sleeper &*& + result.node.height == 0 &*& + .own(t,key) &*& .own(t,value) &*& + dormant_pair(result.node.node.as_ptr(),result.idx,key_cell,val_cell) &*& + exists::>>>(?initial_sibling) &*& + insertion_leaves(first,result.node.node,result.idx,initial_sibling,alloc_id,k) &*& + match initial_sibling { + Option::None => + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& (*root).parent_idx |-> root_index &*& + ancestors(first.as_ptr(),path,root) &*& route_frames(t,path), + Option::Some(sibling) => completed_levels::(t,alloc_id,k,?completed) &*& + if length(completed) == length(path) { + *sleeper.ptr.as_ptr() |-> Option::Some(?installed) &*& installed.height == old_root.height + 1 &*& + exists::>>(?new_root) &*& installed.node.as_ptr() == &(*new_root.as_ptr()).data &*& + allocated_internal(new_root.as_ptr(),alloc_id,k,_) &*& (*new_root.as_ptr()).data.parent_idx |-> _ &*& + ancestors(installed.node.as_ptr(),[],installed.node.as_ptr()) &*& + internal_slots(new_root,1,cons(old_root.node,cons(?right,nil)),_,_) &*& .own(t,_) &*& .own(t,_) + } else { + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& (*root).parent_idx |-> root_index &*& + exists::>>(?receiving) &*& ancestors(&(*receiving.as_ptr()).data,?remaining,root) &*& + route_frames(t,remaining) &*& internal_slots(receiving,_,_,_,_) &*& struct_LeafNode_padding(&(*receiving.as_ptr()).data) &*& struct_InternalNode_padding(receiving.as_ptr()) &*& .own(t,_) &*& .own(t,_) &*& + length(completed) + length(remaining) + 1 == length(path) + } + }; +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [qa]lifetime_token(alloc_lifetime) &*& [?remaining_fraction]lifetime_token(k) &*& + *root_allocator |-> ?after &*& Allocator::(t,after,alloc_id) &*& *root_slot |-> sleeper &*& + .own(t,key) &*& .own(t,value) &*& + dormant_pair(initial.1.node.node.as_ptr(),initial.1.idx,key_cell,val_cell) &*& + match initial.0 { + Option::None => *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& (*root).parent_idx |-> root_index &*& + ancestors(first.as_ptr(),path,root) &*& route_frames(t,path) &*& + insertion_leaves(first,initial.1.node.node,initial.1.idx,Option::None,alloc_id,k), + Option::Some(leaf_split) => + insertion_leaves(first,initial.1.node.node,initial.1.idx,Option::Some(leaf_split.right.node),alloc_id,k) &*& + completed_levels::(t,alloc_id,k,?completed) &*& + if length(completed) == length(path) { + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& detached_child::(?pending_sibling) &*& + exists::>>>(?partial_root) &*& + interrupted_root_change(old_root.node,root_index,alloc_id,k,partial_root) + } else { + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& exists::>>(?receiving) &*& + ancestor_tail(&(*receiving.as_ptr()).data,?remaining,root,root_index,?ancestor,?ancestor_idx) &*& + leaf_header(&(*receiving.as_ptr()).data,ancestor,ancestor_idx) &*& struct_InternalNode_padding(receiving.as_ptr()) &*& + route_frames(t,remaining) &*& length(completed) + length(remaining) + 1 == length(path) &*& + internal_slots(receiving,?len,_,_,_) &*& detached_child::(?detached) &*& + if len == CAPACITY { .own(t,_) &*& .own(t,_) } else { true } + } + }; +@*/ +{ + //@ open exists(first); + //@ open_points_to(&initial); + let (pending, inserted) = match initial { + (None, inserted) => { + //@ close_points_to(&initial, 1/2); + //@ close exists::>>>(Option::None); + return unsafe { inserted.awaken/*@::@*/() }; + } + (Some(leaf_split), inserted) => { + //@ close_points_to(&initial, 1/2); + (unsafe { leaf_split.forget_node_type/*@::<'tree,K,V>@*/() }, inserted) + } + }; + //@ let right = pending.right.node; + //@ close exists(std_tuple_2_::>, NonNull>> { 0: first, 1: right }); + //@ close exists(k); + let result = unsafe { propagate_split_for_root/*@::<'tree,K,V,A,'slot,'alloc>@*/(pending, inserted, alloc, root_slot, root_allocator) }; + //@ close exists(Option::Some(right)); + result +} +// END_ROOT_HANDOFF + + +impl NodeRef { + unsafe fn as_internal_ptr(this: &Self) -> *mut InternalNode + //@ req [?f](*this |-> ?node); + //@ ens [f](*this |-> node) &*& result == node.node.as_ptr() as *mut InternalNode; + //@ on_unwind_ens false; + { + //@ open_points_to(this); + let ptr = this.node.as_ptr() as *mut InternalNode; + //@ close_points_to(this, f); + ptr + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn as_leaf_mut<'short>(&'short mut self) -> &'short mut LeafNode + //@ req *self |-> ?node &*& *node.node.as_ptr() |-> ?contents; + //@ ens *self |-> node &*& *result |-> contents &*& ref_mut_end_token(result, node.node.as_ptr()) &*& ref_origin(result) == ref_origin(node.node.as_ptr()); + //@ on_unwind_ens false; + { + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + let ptr = unsafe { Self::as_leaf_ptr(self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self, _); + unsafe { &mut *ptr } //~track_ref_creation + } +} + +/*@ +pred leaf_without_keys(leaf: *LeafNode; + parent: Option>>, index: MaybeUninit, len: u16, + vals: list>) = + leaf_header(leaf, parent, index) &*& (*leaf).len |-> len &*& + (*leaf).vals[..CAPACITY] |-> vals; + +@*/ + +/*@ +pred keys_loan( + owner: *LeafNode, base: *MaybeUninit, first: usize, last: usize, + parent: Option>>, index: MaybeUninit, len: u16, + vals: list>, before: list>, tail: list> +) = + exists::<*LeafNode>(?view) &*& ref_mut_end_token(view, owner) &*& + ref_mut_end_token(?array, &(*view).keys) &*& base == array as *MaybeUninit &*& + leaf_without_keys(view, parent, index, len, vals) &*& + 0 <= first &*& first <= last &*& last <= CAPACITY &*& + (if first == 0 { before == nil } else { base[..first] |-> before }) &*& + base[last..CAPACITY] |-> tail; + +lem restore_keys(owner: *LeafNode, base: *MaybeUninit) + req keys_loan(owner, base, ?first, ?last, ?parent, ?index, ?len, ?vals, ?before, ?tail) &*& + base[first..last] |-> ?active; + ens leaf_without_keys(owner, parent, index, len, vals) &*& + (*owner).keys[..CAPACITY] |-> append(before, append(active, tail)); +{ + open keys_loan(owner, base, first, last, parent, index, len, vals, before, tail); + open exists::<*LeafNode>(?view); + assert ref_mut_end_token(?array, &(*view).keys); + if first != 0 { + array_join(base + first); + } + array_join(base); + close_points_to(array); + end_ref_mut(array); + open_points_to(&(*view).keys); + open leaf_without_keys(view, parent, index, len, vals); + + close_points_to(view); + end_ref_mut(view); + open_points_to(owner); + + close leaf_without_keys(owner, parent, index, len, vals); +} + +pred keys_range_loan( + owner: *LeafNode, lent: *[MaybeUninit], first: usize, last: usize, + parent: Option>>, index: MaybeUninit, len: u16, + vals: list>, before: list>, tail: list> +) = + keys_loan(owner, ?base, first, last, parent, index, len, vals, before, tail) &*& + slice_ref_mut_end_token(lent, base + first, last - first); + +pred keys_slot_loan( + owner: *LeafNode, lent: *MaybeUninit, first: usize, + parent: Option>>, index: MaybeUninit, len: u16, + vals: list>, before: list>, tail: list> +) = + keys_loan(owner, ?base, first, first + 1, parent, index, len, vals, before, tail) &*& + ref_mut_end_token(lent, base + first); + +lem end_keys_range(owner: *LeafNode, lent: *[MaybeUninit]) + req keys_range_loan(owner, lent, ?first, ?last, ?parent, ?index, ?len, ?vals, ?before, ?tail) &*& + move_slice(lent as *MaybeUninit, last - first, ?active); + ens leaf_without_keys(owner, parent, index, len, vals) &*& + (*owner).keys[..CAPACITY] |-> append(before, append(active, tail)); +{ + open keys_range_loan(owner, lent, first, last, parent, index, len, vals, before, tail); + assert keys_loan(owner, ?base, first, last, parent, index, len, vals, before, tail); + open move_slice(lent as *MaybeUninit, last - first, active); + end_slice_ref_mut(lent); + restore_keys(owner, base); +} + +lem end_keys_slot(owner: *LeafNode, lent: *MaybeUninit) + req keys_slot_loan(owner, lent, ?first, ?parent, ?index, ?len, ?vals, ?before, ?tail) &*& + *lent |-> ?entry; + ens leaf_without_keys(owner, parent, index, len, vals) &*& + (*owner).keys[..CAPACITY] |-> append(before, cons(entry, tail)); +{ + open keys_slot_loan(owner, lent, first, parent, index, len, vals, before, tail); + assert keys_loan(owner, ?base, first, first + 1, parent, index, len, vals, before, tail); + open keys_loan(owner, base, first, first + 1, parent, index, len, vals, before, tail); + assert base[first + 1..CAPACITY] |-> tail; + array_inv::>(); + close keys_loan(owner, base, first, first + 1, parent, index, len, vals, before, tail); + end_ref_mut(lent); + points_to_limits(base + first); + close array(base + first + 1, 0, []); + close array(base + first, 1, [entry]); + restore_keys(owner, base); +} +@*/ + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn key_area_range_mut<'short>( + &'short mut self, index: std::ops::Range, + ) -> &'short mut [MaybeUninit] + /*@ + req *self |-> ?node &*& leaf_without_keys(node.node.as_ptr(), ?parent, ?idx, ?len, ?vals) &*& + (*node.node.as_ptr()).keys[..CAPACITY] |-> ?slots &*& 0 <= index.start &*& index.start <= index.end &*& index.end <= CAPACITY; + @*/ + /*@ + ens *self |-> node &*& + keys_range_loan(node.node.as_ptr(), result, index.start, index.end, parent, idx, len, vals, take(index.start, slots), drop(index.end, slots)) &*& + result.len() == index.end - index.start &*& + move_slice(result as *MaybeUninit, index.end - index.start, take(index.end - index.start, drop(index.start, slots))) &*& ref_origin((result as *MaybeUninit)) == ref_origin(&(*node.node.as_ptr()).keys as *MaybeUninit + index.start); + @*/ + //@ on_unwind_ens false; + { + //@ open leaf_without_keys(node.node.as_ptr(), parent, idx, len, vals); + + //@ close_points_to(node.node.as_ptr()); + let storage = unsafe { self.as_leaf_mut/*@::<'a,K,V, Type,'short>@*/() }; + //@ open_points_to(storage); + + //@ close_points_to(&(*storage).keys); + let array = &mut storage.keys; + let view = array.as_mut_slice(); + //@ open_points_to(array); + //@ let base = view as *MaybeUninit; + //@ let first = index.start; + //@ let last = index.end; + //@ insertion_slot_limits(base); + //@ move_slice_offset(base, CAPACITY, first); + //@ btree_aligned_offset(base, first); + //@ if first != 0 { array_split(base, first); } + //@ array_split(base + first, last - first); + //@ drop_twice(last - first, first, slots); + + let lent = unsafe { view.get_unchecked_mut(index) }; + //@ close move_slice(lent as *MaybeUninit, last - first, _); + //@ close leaf_without_keys(storage, parent, idx, len, vals); + //@ close exists::<*LeafNode>(storage); + //@ close keys_loan(node.node.as_ptr(), base, first, last, parent, idx, len, vals, take(first, slots), drop(last, slots)); + //@ close keys_range_loan(node.node.as_ptr(), lent, first, last, parent, idx, len, vals, take(first, slots), drop(last, slots)); + lent + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn key_area_prefix_mut<'short>( + &'short mut self, index: std::ops::RangeTo, + ) -> &'short mut [MaybeUninit] + /*@ + req *self |-> ?node &*& leaf_without_keys(node.node.as_ptr(), ?parent, ?idx, ?len, ?vals) &*& + (*node.node.as_ptr()).keys[..CAPACITY] |-> ?slots &*& 0 <= index.end &*& index.end <= CAPACITY; + @*/ + /*@ + ens *self |-> node &*& + keys_range_loan(node.node.as_ptr(), result, 0, index.end, parent, idx, len, vals, take(0, slots), drop(index.end, slots)) &*& + result.len() == index.end - 0 &*& + move_slice(result as *MaybeUninit, index.end - 0, take(index.end - 0, drop(0, slots))) &*& ref_origin((result as *MaybeUninit)) == ref_origin(&(*node.node.as_ptr()).keys as *MaybeUninit + 0); + @*/ + //@ on_unwind_ens false; + { + //@ open leaf_without_keys(node.node.as_ptr(), parent, idx, len, vals); + + //@ close_points_to(node.node.as_ptr()); + let storage = unsafe { self.as_leaf_mut/*@::<'a,K,V, Type,'short>@*/() }; + //@ open_points_to(storage); + + //@ close_points_to(&(*storage).keys); + let array = &mut storage.keys; + let view = array.as_mut_slice(); + //@ open_points_to(array); + //@ let base = view as *MaybeUninit; + //@ let first = 0; + //@ let last = index.end; + //@ insertion_slot_limits(base); + //@ move_slice_offset(base, CAPACITY, first); + //@ btree_aligned_offset(base, first); + //@ if first != 0 { array_split(base, first); } + //@ array_split(base + first, last - first); + //@ drop_twice(last - first, first, slots); + + let lent = unsafe { view.get_unchecked_mut(index) }; + //@ close move_slice(lent as *MaybeUninit, last - first, _); + //@ close leaf_without_keys(storage, parent, idx, len, vals); + //@ close exists::<*LeafNode>(storage); + //@ close keys_loan(node.node.as_ptr(), base, first, last, parent, idx, len, vals, take(first, slots), drop(last, slots)); + //@ close keys_range_loan(node.node.as_ptr(), lent, first, last, parent, idx, len, vals, take(first, slots), drop(last, slots)); + lent + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn key_area_slot_mut<'short>( + &'short mut self, index: usize, + ) -> &'short mut MaybeUninit + /*@ + req *self |-> ?node &*& leaf_without_keys(node.node.as_ptr(), ?parent, ?idx, ?len, ?vals) &*& + (*node.node.as_ptr()).keys[..CAPACITY] |-> ?slots &*& 0 <= index &*& index < CAPACITY; + @*/ + /*@ + ens *self |-> node &*& + keys_slot_loan(node.node.as_ptr(), result, index, parent, idx, len, vals, take(index, slots), drop(index + 1, slots)) &*& + *result |-> nth(index, slots) &*& ref_origin(result) == ref_origin(&(*node.node.as_ptr()).keys as *MaybeUninit + index); + @*/ + //@ on_unwind_ens false; + { + //@ open leaf_without_keys(node.node.as_ptr(), parent, idx, len, vals); + + //@ close_points_to(node.node.as_ptr()); + let storage = unsafe { self.as_leaf_mut/*@::<'a,K,V, Type,'short>@*/() }; + //@ open_points_to(storage); + + //@ close_points_to(&(*storage).keys); + let array = &mut storage.keys; + let view = array.as_mut_slice(); + //@ open_points_to(array); + //@ let base = view as *MaybeUninit; + //@ let first = index; + //@ let last = index + 1; + + //@ if first != 0 { array_split(base, first); } + //@ array_split(base + first, last - first); + //@ drop_twice(last - first, first, slots); + //@ open array(base + first, 1, _); + //@ nth_drop(0, first, slots); + let lent = unsafe { view.get_unchecked_mut(index) }; + + //@ close leaf_without_keys(storage, parent, idx, len, vals); + //@ close exists::<*LeafNode>(storage); + //@ close keys_loan(node.node.as_ptr(), base, first, last, parent, idx, len, vals, take(first, slots), drop(last, slots)); + //@ close keys_slot_loan(node.node.as_ptr(), lent, first, parent, idx, len, vals, take(first, slots), drop(last, slots)); + lent + } +} + +/*@ +pred leaf_without_vals(leaf: *LeafNode; + parent: Option>>, index: MaybeUninit, len: u16, + keys: list>) = + leaf_header(leaf, parent, index) &*& (*leaf).len |-> len &*& + (*leaf).keys[..CAPACITY] |-> keys; + +@*/ + +/*@ +pred vals_loan( + owner: *LeafNode, base: *MaybeUninit, first: usize, last: usize, + parent: Option>>, index: MaybeUninit, len: u16, + keys: list>, before: list>, tail: list> +) = + exists::<*LeafNode>(?view) &*& ref_mut_end_token(view, owner) &*& + ref_mut_end_token(?array, &(*view).vals) &*& base == array as *MaybeUninit &*& + leaf_without_vals(view, parent, index, len, keys) &*& + 0 <= first &*& first <= last &*& last <= CAPACITY &*& + (if first == 0 { before == nil } else { base[..first] |-> before }) &*& + base[last..CAPACITY] |-> tail; + +lem restore_vals(owner: *LeafNode, base: *MaybeUninit) + req vals_loan(owner, base, ?first, ?last, ?parent, ?index, ?len, ?keys, ?before, ?tail) &*& + base[first..last] |-> ?active; + ens leaf_without_vals(owner, parent, index, len, keys) &*& + (*owner).vals[..CAPACITY] |-> append(before, append(active, tail)); +{ + open vals_loan(owner, base, first, last, parent, index, len, keys, before, tail); + open exists::<*LeafNode>(?view); + assert ref_mut_end_token(?array, &(*view).vals); + if first != 0 { + array_join(base + first); + } + array_join(base); + close_points_to(array); + end_ref_mut(array); + open_points_to(&(*view).vals); + open leaf_without_vals(view, parent, index, len, keys); + + close_points_to(view); + end_ref_mut(view); + open_points_to(owner); + + close leaf_without_vals(owner, parent, index, len, keys); +} + +pred vals_range_loan( + owner: *LeafNode, lent: *[MaybeUninit], first: usize, last: usize, + parent: Option>>, index: MaybeUninit, len: u16, + keys: list>, before: list>, tail: list> +) = + vals_loan(owner, ?base, first, last, parent, index, len, keys, before, tail) &*& + slice_ref_mut_end_token(lent, base + first, last - first); + +pred vals_slot_loan( + owner: *LeafNode, lent: *MaybeUninit, first: usize, + parent: Option>>, index: MaybeUninit, len: u16, + keys: list>, before: list>, tail: list> +) = + vals_loan(owner, ?base, first, first + 1, parent, index, len, keys, before, tail) &*& + ref_mut_end_token(lent, base + first); + +lem end_vals_range(owner: *LeafNode, lent: *[MaybeUninit]) + req vals_range_loan(owner, lent, ?first, ?last, ?parent, ?index, ?len, ?keys, ?before, ?tail) &*& + move_slice(lent as *MaybeUninit, last - first, ?active); + ens leaf_without_vals(owner, parent, index, len, keys) &*& + (*owner).vals[..CAPACITY] |-> append(before, append(active, tail)); +{ + open vals_range_loan(owner, lent, first, last, parent, index, len, keys, before, tail); + assert vals_loan(owner, ?base, first, last, parent, index, len, keys, before, tail); + open move_slice(lent as *MaybeUninit, last - first, active); + end_slice_ref_mut(lent); + restore_vals(owner, base); +} + +lem end_vals_slot(owner: *LeafNode, lent: *MaybeUninit) + req vals_slot_loan(owner, lent, ?first, ?parent, ?index, ?len, ?keys, ?before, ?tail) &*& + *lent |-> ?entry; + ens leaf_without_vals(owner, parent, index, len, keys) &*& + (*owner).vals[..CAPACITY] |-> append(before, cons(entry, tail)); +{ + open vals_slot_loan(owner, lent, first, parent, index, len, keys, before, tail); + assert vals_loan(owner, ?base, first, first + 1, parent, index, len, keys, before, tail); + open vals_loan(owner, base, first, first + 1, parent, index, len, keys, before, tail); + assert base[first + 1..CAPACITY] |-> tail; + array_inv::>(); + close vals_loan(owner, base, first, first + 1, parent, index, len, keys, before, tail); + end_ref_mut(lent); + points_to_limits(base + first); + close array(base + first + 1, 0, []); + close array(base + first, 1, [entry]); + restore_vals(owner, base); +} +@*/ + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn val_area_range_mut<'short>( + &'short mut self, index: std::ops::Range, + ) -> &'short mut [MaybeUninit] + /*@ + req *self |-> ?node &*& leaf_without_vals(node.node.as_ptr(), ?parent, ?idx, ?len, ?keys) &*& + (*node.node.as_ptr()).vals[..CAPACITY] |-> ?slots &*& 0 <= index.start &*& index.start <= index.end &*& index.end <= CAPACITY; + @*/ + /*@ + ens *self |-> node &*& + vals_range_loan(node.node.as_ptr(), result, index.start, index.end, parent, idx, len, keys, take(index.start, slots), drop(index.end, slots)) &*& + result.len() == index.end - index.start &*& + move_slice(result as *MaybeUninit, index.end - index.start, take(index.end - index.start, drop(index.start, slots))) &*& ref_origin((result as *MaybeUninit)) == ref_origin(&(*node.node.as_ptr()).vals as *MaybeUninit + index.start); + @*/ + //@ on_unwind_ens false; + { + //@ open leaf_without_vals(node.node.as_ptr(), parent, idx, len, keys); + + //@ close_points_to(node.node.as_ptr()); + let storage = unsafe { self.as_leaf_mut/*@::<'a,K,V, Type,'short>@*/() }; + //@ open_points_to(storage); + + //@ close_points_to(&(*storage).vals); + let array = &mut storage.vals; + let view = array.as_mut_slice(); + //@ open_points_to(array); + //@ let base = view as *MaybeUninit; + //@ let first = index.start; + //@ let last = index.end; + //@ insertion_slot_limits(base); + //@ move_slice_offset(base, CAPACITY, first); + //@ btree_aligned_offset(base, first); + //@ if first != 0 { array_split(base, first); } + //@ array_split(base + first, last - first); + //@ drop_twice(last - first, first, slots); + + let lent = unsafe { view.get_unchecked_mut(index) }; + //@ close move_slice(lent as *MaybeUninit, last - first, _); + //@ close leaf_without_vals(storage, parent, idx, len, keys); + //@ close exists::<*LeafNode>(storage); + //@ close vals_loan(node.node.as_ptr(), base, first, last, parent, idx, len, keys, take(first, slots), drop(last, slots)); + //@ close vals_range_loan(node.node.as_ptr(), lent, first, last, parent, idx, len, keys, take(first, slots), drop(last, slots)); + lent + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn val_area_prefix_mut<'short>( + &'short mut self, index: std::ops::RangeTo, + ) -> &'short mut [MaybeUninit] + /*@ + req *self |-> ?node &*& leaf_without_vals(node.node.as_ptr(), ?parent, ?idx, ?len, ?keys) &*& + (*node.node.as_ptr()).vals[..CAPACITY] |-> ?slots &*& 0 <= index.end &*& index.end <= CAPACITY; + @*/ + /*@ + ens *self |-> node &*& + vals_range_loan(node.node.as_ptr(), result, 0, index.end, parent, idx, len, keys, take(0, slots), drop(index.end, slots)) &*& + result.len() == index.end - 0 &*& + move_slice(result as *MaybeUninit, index.end - 0, take(index.end - 0, drop(0, slots))) &*& ref_origin((result as *MaybeUninit)) == ref_origin(&(*node.node.as_ptr()).vals as *MaybeUninit + 0); + @*/ + //@ on_unwind_ens false; + { + //@ open leaf_without_vals(node.node.as_ptr(), parent, idx, len, keys); + + //@ close_points_to(node.node.as_ptr()); + let storage = unsafe { self.as_leaf_mut/*@::<'a,K,V, Type,'short>@*/() }; + //@ open_points_to(storage); + + //@ close_points_to(&(*storage).vals); + let array = &mut storage.vals; + let view = array.as_mut_slice(); + //@ open_points_to(array); + //@ let base = view as *MaybeUninit; + //@ let first = 0; + //@ let last = index.end; + //@ insertion_slot_limits(base); + //@ move_slice_offset(base, CAPACITY, first); + //@ btree_aligned_offset(base, first); + //@ if first != 0 { array_split(base, first); } + //@ array_split(base + first, last - first); + //@ drop_twice(last - first, first, slots); + + let lent = unsafe { view.get_unchecked_mut(index) }; + //@ close move_slice(lent as *MaybeUninit, last - first, _); + //@ close leaf_without_vals(storage, parent, idx, len, keys); + //@ close exists::<*LeafNode>(storage); + //@ close vals_loan(node.node.as_ptr(), base, first, last, parent, idx, len, keys, take(first, slots), drop(last, slots)); + //@ close vals_range_loan(node.node.as_ptr(), lent, first, last, parent, idx, len, keys, take(first, slots), drop(last, slots)); + lent + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn val_area_slot_mut<'short>( + &'short mut self, index: usize, + ) -> &'short mut MaybeUninit + /*@ + req *self |-> ?node &*& leaf_without_vals(node.node.as_ptr(), ?parent, ?idx, ?len, ?keys) &*& + (*node.node.as_ptr()).vals[..CAPACITY] |-> ?slots &*& 0 <= index &*& index < CAPACITY; + @*/ + /*@ + ens *self |-> node &*& + vals_slot_loan(node.node.as_ptr(), result, index, parent, idx, len, keys, take(index, slots), drop(index + 1, slots)) &*& + *result |-> nth(index, slots) &*& ref_origin(result) == ref_origin(&(*node.node.as_ptr()).vals as *MaybeUninit + index); + @*/ + //@ on_unwind_ens false; + { + //@ open leaf_without_vals(node.node.as_ptr(), parent, idx, len, keys); + + //@ close_points_to(node.node.as_ptr()); + let storage = unsafe { self.as_leaf_mut/*@::<'a,K,V, Type,'short>@*/() }; + //@ open_points_to(storage); + + //@ close_points_to(&(*storage).vals); + let array = &mut storage.vals; + let view = array.as_mut_slice(); + //@ open_points_to(array); + //@ let base = view as *MaybeUninit; + //@ let first = index; + //@ let last = index + 1; + + //@ if first != 0 { array_split(base, first); } + //@ array_split(base + first, last - first); + //@ drop_twice(last - first, first, slots); + //@ open array(base + first, 1, _); + //@ nth_drop(0, first, slots); + let lent = unsafe { view.get_unchecked_mut(index) }; + + //@ close leaf_without_vals(storage, parent, idx, len, keys); + //@ close exists::<*LeafNode>(storage); + //@ close vals_loan(node.node.as_ptr(), base, first, last, parent, idx, len, keys, take(first, slots), drop(last, slots)); + //@ close vals_slot_loan(node.node.as_ptr(), lent, first, parent, idx, len, keys, take(first, slots), drop(last, slots)); + lent + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn as_internal_mut<'short>(&'short mut self) -> &'short mut InternalNode + //@ req *self |-> ?node &*& *(node.node.as_ptr() as *mut InternalNode) |-> ?contents; + //@ ens *self |-> node &*& *result |-> contents &*& ref_mut_end_token(result, (node.node.as_ptr() as *mut InternalNode)) &*& ref_origin(result) == ref_origin((node.node.as_ptr() as *mut InternalNode)); + //@ on_unwind_ens false; + { + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + let ptr = unsafe { Self::as_internal_ptr(self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self, _); + unsafe { &mut *ptr } //~track_ref_creation + } +} + +/*@ +pred internal_without_edges(node: *InternalNode; data: LeafNode) = + struct_InternalNode_padding(node) &*& *(&(*node).data) |-> data; +@*/ + +/*@ +pred edges_loan( + owner: *InternalNode, base: *MaybeUninit>, first: usize, last: usize, + data: LeafNode, before: list>>, tail: list>> +) = + exists::<*InternalNode>(?view) &*& ref_mut_end_token(view, owner) &*& + ref_mut_end_token(?array, &(*view).edges) &*& base == array as *MaybeUninit> &*& + internal_without_edges(view, data) &*& + 0 <= first &*& first <= last &*& last <= (CAPACITY + 1) &*& + (if first == 0 { before == nil } else { base[..first] |-> before }) &*& + base[last..(CAPACITY + 1)] |-> tail; + +lem restore_edges(owner: *InternalNode, base: *MaybeUninit>) + req edges_loan(owner, base, ?first, ?last, ?data, ?before, ?tail) &*& + base[first..last] |-> ?active; + ens internal_without_edges(owner, data) &*& + (*owner).edges[..(CAPACITY + 1)] |-> append(before, append(active, tail)); +{ + open edges_loan(owner, base, first, last, data, before, tail); + open exists::<*InternalNode>(?view); + assert ref_mut_end_token(?array, &(*view).edges); + if first != 0 { + array_join(base + first); + } + array_join(base); + close_points_to(array); + end_ref_mut(array); + open_points_to(&(*view).edges); + open internal_without_edges(view, data); + open_points_to(&(*view).data); + close_points_to(view); + end_ref_mut(view); + open_points_to(owner); + close_points_to(&(*owner).data); + close internal_without_edges(owner, data); +} + +pred edges_range_loan( + owner: *InternalNode, lent: *[MaybeUninit>], first: usize, last: usize, + data: LeafNode, before: list>>, tail: list>> +) = + edges_loan(owner, ?base, first, last, data, before, tail) &*& + slice_ref_mut_end_token(lent, base + first, last - first); + +pred edges_slot_loan( + owner: *InternalNode, lent: *MaybeUninit>, first: usize, + data: LeafNode, before: list>>, tail: list>> +) = + edges_loan(owner, ?base, first, first + 1, data, before, tail) &*& + ref_mut_end_token(lent, base + first); + +lem end_edges_range(owner: *InternalNode, lent: *[MaybeUninit>]) + req edges_range_loan(owner, lent, ?first, ?last, ?data, ?before, ?tail) &*& + move_slice(lent as *MaybeUninit>, last - first, ?active); + ens internal_without_edges(owner, data) &*& + (*owner).edges[..(CAPACITY + 1)] |-> append(before, append(active, tail)); +{ + open edges_range_loan(owner, lent, first, last, data, before, tail); + assert edges_loan(owner, ?base, first, last, data, before, tail); + open move_slice(lent as *MaybeUninit>, last - first, active); + end_slice_ref_mut(lent); + restore_edges(owner, base); +} + +lem end_edges_slot(owner: *InternalNode, lent: *MaybeUninit>) + req edges_slot_loan(owner, lent, ?first, ?data, ?before, ?tail) &*& + *lent |-> ?entry; + ens internal_without_edges(owner, data) &*& + (*owner).edges[..(CAPACITY + 1)] |-> append(before, cons(entry, tail)); +{ + open edges_slot_loan(owner, lent, first, data, before, tail); + assert edges_loan(owner, ?base, first, first + 1, data, before, tail); + open edges_loan(owner, base, first, first + 1, data, before, tail); + assert base[first + 1..(CAPACITY + 1)] |-> tail; + array_inv::>>(); + close edges_loan(owner, base, first, first + 1, data, before, tail); + end_ref_mut(lent); + points_to_limits(base + first); + close array(base + first + 1, 0, []); + close array(base + first, 1, [entry]); + restore_edges(owner, base); +} +@*/ + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn edge_area_range_mut<'short>( + &'short mut self, index: std::ops::Range, + ) -> &'short mut [MaybeUninit>] + /*@ + req *self |-> ?node &*& internal_without_edges((node.node.as_ptr() as *mut InternalNode), ?data) &*& + (*(node.node.as_ptr() as *mut InternalNode)).edges[..(CAPACITY + 1)] |-> ?slots &*& 0 <= index.start &*& index.start <= index.end &*& index.end <= (CAPACITY + 1); + @*/ + /*@ + ens *self |-> node &*& + edges_range_loan((node.node.as_ptr() as *mut InternalNode), result, index.start, index.end, data, take(index.start, slots), drop(index.end, slots)) &*& + result.len() == index.end - index.start &*& + move_slice(result as *MaybeUninit>, index.end - index.start, take(index.end - index.start, drop(index.start, slots))) &*& ref_origin((result as *MaybeUninit>)) == ref_origin(&(*(node.node.as_ptr() as *mut InternalNode)).edges as *MaybeUninit> + index.start); + @*/ + //@ on_unwind_ens false; + { + //@ open internal_without_edges((node.node.as_ptr() as *mut InternalNode), data); + //@ open_points_to(&(*(node.node.as_ptr() as *mut InternalNode)).data); + //@ close_points_to((node.node.as_ptr() as *mut InternalNode)); + let storage = unsafe { self.as_internal_mut/*@::<'a,K,V,'short>@*/() }; + //@ open_points_to(storage); + //@ close_points_to(&(*storage).data); + //@ close_points_to(&(*storage).edges); + let array = &mut storage.edges; + let view = array.as_mut_slice(); + //@ open_points_to(array); + //@ let base = view as *MaybeUninit>; + //@ let first = index.start; + //@ let last = index.end; + //@ insertion_slot_limits(base); + //@ move_slice_offset(base, (CAPACITY + 1), first); + //@ btree_aligned_offset(base, first); + //@ if first != 0 { array_split(base, first); } + //@ array_split(base + first, last - first); + //@ drop_twice(last - first, first, slots); + + let lent = unsafe { view.get_unchecked_mut(index) }; + //@ close move_slice(lent as *MaybeUninit>, last - first, _); + //@ close internal_without_edges(storage, data); + //@ close exists::<*InternalNode>(storage); + //@ close edges_loan((node.node.as_ptr() as *mut InternalNode), base, first, last, data, take(first, slots), drop(last, slots)); + //@ close edges_range_loan((node.node.as_ptr() as *mut InternalNode), lent, first, last, data, take(first, slots), drop(last, slots)); + lent + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn edge_area_prefix_mut<'short>( + &'short mut self, index: std::ops::RangeTo, + ) -> &'short mut [MaybeUninit>] + /*@ + req *self |-> ?node &*& internal_without_edges((node.node.as_ptr() as *mut InternalNode), ?data) &*& + (*(node.node.as_ptr() as *mut InternalNode)).edges[..(CAPACITY + 1)] |-> ?slots &*& 0 <= index.end &*& index.end <= (CAPACITY + 1); + @*/ + /*@ + ens *self |-> node &*& + edges_range_loan((node.node.as_ptr() as *mut InternalNode), result, 0, index.end, data, take(0, slots), drop(index.end, slots)) &*& + result.len() == index.end - 0 &*& + move_slice(result as *MaybeUninit>, index.end - 0, take(index.end - 0, drop(0, slots))) &*& ref_origin((result as *MaybeUninit>)) == ref_origin(&(*(node.node.as_ptr() as *mut InternalNode)).edges as *MaybeUninit> + 0); + @*/ + //@ on_unwind_ens false; + { + //@ open internal_without_edges((node.node.as_ptr() as *mut InternalNode), data); + //@ open_points_to(&(*(node.node.as_ptr() as *mut InternalNode)).data); + //@ close_points_to((node.node.as_ptr() as *mut InternalNode)); + let storage = unsafe { self.as_internal_mut/*@::<'a,K,V,'short>@*/() }; + //@ open_points_to(storage); + //@ close_points_to(&(*storage).data); + //@ close_points_to(&(*storage).edges); + let array = &mut storage.edges; + let view = array.as_mut_slice(); + //@ open_points_to(array); + //@ let base = view as *MaybeUninit>; + //@ let first = 0; + //@ let last = index.end; + //@ insertion_slot_limits(base); + //@ move_slice_offset(base, (CAPACITY + 1), first); + //@ btree_aligned_offset(base, first); + //@ if first != 0 { array_split(base, first); } + //@ array_split(base + first, last - first); + //@ drop_twice(last - first, first, slots); + + let lent = unsafe { view.get_unchecked_mut(index) }; + //@ close move_slice(lent as *MaybeUninit>, last - first, _); + //@ close internal_without_edges(storage, data); + //@ close exists::<*InternalNode>(storage); + //@ close edges_loan((node.node.as_ptr() as *mut InternalNode), base, first, last, data, take(first, slots), drop(last, slots)); + //@ close edges_range_loan((node.node.as_ptr() as *mut InternalNode), lent, first, last, data, take(first, slots), drop(last, slots)); + lent + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn edge_area_slot_mut<'short>( + &'short mut self, index: usize, + ) -> &'short mut MaybeUninit> + /*@ + req *self |-> ?node &*& internal_without_edges((node.node.as_ptr() as *mut InternalNode), ?data) &*& + (*(node.node.as_ptr() as *mut InternalNode)).edges[..(CAPACITY + 1)] |-> ?slots &*& 0 <= index &*& index < (CAPACITY + 1); + @*/ + /*@ + ens *self |-> node &*& + edges_slot_loan((node.node.as_ptr() as *mut InternalNode), result, index, data, take(index, slots), drop(index + 1, slots)) &*& + *result |-> nth(index, slots) &*& ref_origin(result) == ref_origin(&(*(node.node.as_ptr() as *mut InternalNode)).edges as *MaybeUninit> + index); + @*/ + //@ on_unwind_ens false; + { + //@ open internal_without_edges((node.node.as_ptr() as *mut InternalNode), data); + //@ open_points_to(&(*(node.node.as_ptr() as *mut InternalNode)).data); + //@ close_points_to((node.node.as_ptr() as *mut InternalNode)); + let storage = unsafe { self.as_internal_mut/*@::<'a,K,V,'short>@*/() }; + //@ open_points_to(storage); + //@ close_points_to(&(*storage).data); + //@ close_points_to(&(*storage).edges); + let array = &mut storage.edges; + let view = array.as_mut_slice(); + //@ open_points_to(array); + //@ let base = view as *MaybeUninit>; + //@ let first = index; + //@ let last = index + 1; + + //@ if first != 0 { array_split(base, first); } + //@ array_split(base + first, last - first); + //@ drop_twice(last - first, first, slots); + //@ open array(base + first, 1, _); + //@ nth_drop(0, first, slots); + let lent = unsafe { view.get_unchecked_mut(index) }; + + //@ close internal_without_edges(storage, data); + //@ close exists::<*InternalNode>(storage); + //@ close edges_loan((node.node.as_ptr() as *mut InternalNode), base, first, last, data, take(first, slots), drop(last, slots)); + //@ close edges_slot_loan((node.node.as_ptr() as *mut InternalNode), lent, first, data, take(first, slots), drop(last, slots)); + lent + } +} + +/*@ +pred leaf_without_len(leaf: *LeafNode; + parent: Option>>, index: MaybeUninit, + keys: list>, vals: list>) = + struct_LeafNode_padding(leaf) &*& + (*leaf).parent |-> parent &*& (*leaf).parent_idx |-> index &*& + (*leaf).keys[..CAPACITY] |-> keys &*& (*leaf).vals[..CAPACITY] |-> vals; + +pred len_loan(leaf: *LeafNode, lent: *u16, + parent: Option>>, index: MaybeUninit, + keys: list>, vals: list>) = + exists::<*LeafNode>(?view) &*& ref_mut_end_token(view, leaf) &*& + ref_mut_end_token(lent, &(*view).len) &*& leaf_without_len(view, parent, index, keys, vals); + +lem end_len_loan(leaf: *LeafNode, lent: *u16) + req len_loan(leaf, lent, ?parent, ?index, ?keys, ?vals) &*& *lent |-> ?updated; + ens leaf_without_len(leaf, parent, index, keys, vals) &*& (*leaf).len |-> updated; +{ + open len_loan(leaf, lent, parent, index, keys, vals); + open exists::<*LeafNode>(?view); + end_ref_mut(lent); + open leaf_without_len(view, parent, index, keys, vals); + close_points_to(view); + end_ref_mut(view); + open_points_to(leaf); + close leaf_without_len(leaf, parent, index, keys, vals); +} +@*/ + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn len_mut<'short>(&'short mut self) -> &'short mut u16 + /*@ + req *self |-> ?node &*& + leaf_without_len(node.node.as_ptr(), ?parent, ?index, ?keys, ?vals) &*& + (*node.node.as_ptr()).len |-> ?len; + @*/ + /*@ + ens *self |-> node &*& *result |-> len &*& + len_loan(node.node.as_ptr(), result, parent, index, keys, vals) &*& + ref_origin(result) == ref_origin(&(*node.node.as_ptr()).len); + @*/ + //@ on_unwind_ens false; + { + //@ open leaf_without_len(node.node.as_ptr(), parent, index, keys, vals); + //@ close_points_to(node.node.as_ptr()); + let storage = unsafe { self.as_leaf_mut/*@::<'a,K,V,Type,'short>@*/() }; + //@ open_points_to(storage); + let lent = &mut storage.len; //~track_ref_creation + //@ close leaf_without_len(storage, parent, index, keys, vals); + //@ close exists::<*LeafNode>(storage); + //@ close len_loan(node.node.as_ptr(), lent, parent, index, keys, vals); + lent + } +} + +impl<'a, K, V> NodeRef, K, V, marker::LeafOrInternal> { + unsafe fn cast_to_internal_unchecked(self) -> NodeRef, K, V, marker::Internal> + //@ req 0 < self.height; + //@ ens result.node == self.node &*& result.height == self.height; + //@ on_unwind_ens false; + { + debug_assert!(self.height > 0); + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +/*@ +pred move_slice(base: *MaybeUninit, len: usize; slots: list>) = + base[..len] |-> slots &*& 0 <= len &*& len <= usize::MAX &*& base as usize != 0 &*& + base as usize % std::mem::align_of::>() == 0 &*& + pointer_within_limits(base) == true &*& pointer_within_limits(base + len) == true; + +lem move_slice_length(base: *MaybeUninit, len: usize) + req move_slice(base, len, ?slots); + ens move_slice(base, len, slots) &*& length(slots) == len; +{ + open move_slice(base, len, slots); + array_inv::>(); + close move_slice(base, len, slots); +} + +lem move_slice_offset(base: *T, len: usize, index: usize) + req 0 <= index &*& index <= len &*& + pointer_within_limits(base) == true &*& pointer_within_limits(base + len) == true; + ens pointer_within_limits(base + index) == true &*& + (base + index) as usize >= base as usize; +{ + std::alloc::is_valid_layout_size_of_align_of::(); + mul_mono_l(0, index, std::mem::size_of::()); + mul_mono_l(index, len, std::mem::size_of::()); +} + +lem drop_twice(outer: i32, inner: i32, slots: list) + req 0 <= inner &*& 0 <= outer &*& inner + outer <= length(slots); + ens drop(outer, drop(inner, slots)) == drop(inner + outer, slots); +{ + match slots { + nil => {} + cons(slot, rest) => { + if inner > 0 { drop_twice(outer, inner - 1, rest); } + } + } +} + +lem btree_restore_shl(p: *T, n: i32, distance: i32, values: list, bytes: list>) + req 0 <= distance &*& distance <= n &*& length(values) == n &*& + btree_encoded(values, bytes) == true &*& + (p as *u8)[..n * std::mem::size_of::()] |-?-> + append(drop(distance * std::mem::size_of::(), bytes), drop((n - distance) * std::mem::size_of::(), bytes)) &*& + p as usize % std::mem::align_of::() == 0; + ens p[..n] |-> append(drop(distance, values), drop(n - distance, values)); +{ + btree_encoded_split(values, bytes, distance); + btree_encoded_split(values, bytes, n - distance); + btree_encoded_append(drop(distance, values), drop(distance * std::mem::size_of::(), bytes), + drop(n - distance, values), drop((n - distance) * std::mem::size_of::(), bytes)); + btree_bytes_to_values(p, append(drop(distance, values), drop(n - distance, values))); +} +@*/ + +// BEGIN_SLICE_SHL +unsafe fn slice_shl(slice: &mut [MaybeUninit], distance: usize) +/*@ +req 0 <= distance &*& distance <= slice.len() &*& + move_slice(slice as *MaybeUninit, slice.len(), ?slots); +@*/ +/*@ +ens move_slice(slice as *MaybeUninit, slice.len(), + append(drop(distance, slots), drop(slice.len() - distance, slots))); +@*/ +//@ on_unwind_ens false; +{ + let slice_ptr = slice.as_mut_ptr(); + //@ open move_slice(slice_ptr, slice.len(), slots); + //@ btree_values_to_bytes(slice_ptr, slice.len()); + //@ assert (slice_ptr as *u8)[..slice.len() * std::mem::size_of::>()] |-?-> ?bytes; + //@ move_slice_offset(slice_ptr, slice.len(), distance); + //@ btree_aligned_offset(slice_ptr, distance); + //@ close exists::(false); + //@ close exists::(distance); + unsafe { + ptr::copy(slice_ptr.add(distance), slice_ptr, slice.len() - distance); + } + //@ btree_restore_shl(slice_ptr, slice.len(), distance, slots, bytes); + //@ close move_slice(slice_ptr, slice.len(), _); +} +// END_SLICE_SHL + +// BEGIN_SLICE_SHR +unsafe fn slice_shr(slice: &mut [MaybeUninit], distance: usize) +/*@ +req 0 <= distance &*& distance <= slice.len() &*& + move_slice(slice as *MaybeUninit, slice.len(), ?slots); +@*/ +/*@ +ens move_slice(slice as *MaybeUninit, slice.len(), + append(take(distance, slots), take(slice.len() - distance, slots))); +@*/ +//@ on_unwind_ens false; +{ + let slice_ptr = slice.as_mut_ptr(); + //@ open move_slice(slice_ptr, slice.len(), slots); + //@ btree_values_to_bytes(slice_ptr, slice.len()); + //@ assert (slice_ptr as *u8)[..slice.len() * std::mem::size_of::>()] |-?-> ?bytes; + //@ move_slice_offset(slice_ptr, slice.len(), distance); + //@ btree_aligned_offset(slice_ptr, distance); + //@ close exists::(true); + //@ close exists::(distance); + unsafe { + ptr::copy(slice_ptr, slice_ptr.add(distance), slice.len() - distance); + } + //@ btree_restore_shr(slice_ptr, slice.len(), distance, slots, bytes); + //@ close move_slice(slice_ptr, slice.len(), _); +} +// END_SLICE_SHR + +// The copied bytes do not duplicate ownership of T. The caller transfers the +// ownership of the initialized elements when it changes the active prefixes. +// BEGIN_MOVE_TO_SLICE +unsafe fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) +/*@ +req src.len() == dst.len() &*& + move_slice(src as *MaybeUninit, src.len(), ?source) &*& + move_slice(dst as *MaybeUninit, dst.len(), _); +@*/ +/*@ +ens move_slice(src as *MaybeUninit, src.len(), source) &*& + move_slice(dst as *MaybeUninit, dst.len(), source); +@*/ +//@ on_unwind_ens false; +{ + assert!(src.len() == dst.len()); + //@ open move_slice(src as *MaybeUninit, src.len(), source); + //@ open move_slice(dst as *MaybeUninit, dst.len(), _); + //@ array_to_array_::>(dst as *MaybeUninit); + unsafe { + ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len()); + } + //@ close move_slice(src as *MaybeUninit, src.len(), source); + //@ close move_slice(dst as *MaybeUninit, dst.len(), source); +} +// END_MOVE_TO_SLICE + +// BEGIN_SLICE_REMOVE +unsafe fn slice_remove(slice: &mut [MaybeUninit], idx: usize) -> T +/*@ +req thread_token(?t) &*& type_interp::() &*& 0 <= idx &*& idx < slice.len() &*& + move_slice(slice as *MaybeUninit, slice.len(), ?slots) &*& + nth(idx, slots).inner() == some(?value) &*& + nth(idx, slots) == MaybeUninit::new(value) &*& .own(t, value); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& result == value &*& .own(t, result) &*& + move_slice(slice as *MaybeUninit, slice.len(), + append(take(idx, slots), append(drop(idx + 1, slots), drop(slice.len() - 1, slots)))); +@*/ +//@ on_unwind_ens false; +{ + let len = slice.len(); + debug_assert!(idx < len); + let slice_ptr = slice.as_mut_ptr(); + //@ open move_slice(slice_ptr, len, slots); + //@ let base = slice_ptr + idx; + //@ let suffix = drop(idx, slots); + //@ move_slice_offset(slice_ptr, len, idx); + //@ move_slice_offset(slice_ptr, len, idx + 1); + //@ array_split(slice_ptr, idx); + //@ array_split(base, 1); + //@ drop_n_plus_one(idx, slots); + //@ open array(base, 1, take(1, suffix)); + unsafe { + //@ let view = precreate_ref(base); + //@ init_ref_readonly(view, 1/2); + let ret = (*slice_ptr.add(idx)).assume_init_read(); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(base, _); + //@ close array(base, 1, take(1, suffix)); + //@ array_join(base); + //@ btree_aligned_offset(slice_ptr, idx); + //@ btree_values_to_bytes(base, len - idx); + //@ assert (base as *u8)[..(len - idx) * std::mem::size_of::>()] |-?-> ?bytes; + //@ btree_aligned_offset(base, 1); + //@ close exists::(false); + //@ close exists::(1); + ptr::copy(slice_ptr.add(idx + 1), slice_ptr.add(idx), len - idx - 1); + //@ btree_restore_shl(base, len - idx, 1, suffix, bytes); + //@ array_join(slice_ptr); + //@ drop_twice(1, idx, slots); + //@ drop_twice(len - idx - 1, idx, slots); + //@ close move_slice(slice_ptr, len, _); + ret + } +} +// END_SLICE_REMOVE + +/*@ +pred slot_owners(thread: thread_id_t, slots: list>) = + match slots { + nil => true, + cons(slot, rest) => slot.inner() == some(?value) &*& slot == MaybeUninit::new(value) &*& + .own(thread, value) &*& slot_owners(thread, rest) + }; + +lem split_slot_owners(thread: thread_id_t, slots: list>, index: usize) + req slot_owners(thread, slots) &*& 0 <= index &*& index <= length(slots); + ens slot_owners(thread, take(index, slots)) &*& slot_owners(thread, drop(index, slots)); +{ + if index == 0 { + close slot_owners::(thread, nil); + } else { + open slot_owners(thread, slots); + match slots { + nil => {} + cons(slot, rest) => { + split_slot_owners(thread, rest, index - 1); + close slot_owners(thread, take(index, slots)); + } + } + } +} + +lem join_slot_owners(thread: thread_id_t, left: list>, right: list>) + req slot_owners(thread, left) &*& slot_owners(thread, right); + ens slot_owners(thread, append(left, right)); +{ + open slot_owners(thread, left); + match left { + nil => {} + cons(slot, rest) => { + join_slot_owners(thread, rest, right); + close slot_owners(thread, append(left, right)); + } + } +} + +lem split_move_slice(base: *MaybeUninit, len: usize, index: usize) + req move_slice(base, len, ?slots) &*& 0 <= index &*& index <= len; + ens move_slice(base, index, take(index, slots)) &*& + move_slice(base + index, len - index, drop(index, slots)) &*& + pointer_within_limits(base + index) == true; +{ + open move_slice(base, len, slots); + move_slice_offset(base, len, index); + btree_aligned_offset(base, index); + array_split(base, index); + close move_slice(base, index, take(index, slots)); + close move_slice(base + index, len - index, drop(index, slots)); +} + +lem join_move_slices(base: *MaybeUninit, first: usize, second: usize) + req move_slice(base, first, ?prefix) &*& move_slice(base + first, second, ?suffix) &*& + first + second <= usize::MAX; + ens move_slice(base, first + second, append(prefix, suffix)); +{ + open move_slice(base, first, prefix); + open move_slice(base + first, second, suffix); + array_join(base); + close move_slice(base, first + second, append(prefix, suffix)); +} +@*/ + +// Array accessors in the node code produce views of this form. The proof +// retains the permissions for the selected range across view creation. +// BEGIN_MOVE_SLICE_VIEW +unsafe fn move_slice_mut<'a, T>(base: *mut MaybeUninit, len: usize) -> &'a mut [MaybeUninit] +//@ req move_slice(base, len, ?slots); +//@ ens move_slice(base, len, slots) &*& result as *MaybeUninit == base &*& result.len() == len; +//@ on_unwind_ens false; +{ + //@ open move_slice(base, len, slots); + let slice = unsafe { std::slice::from_raw_parts_mut(base, len) }; + //@ close move_slice(base, len, slots); + slice +} +// END_MOVE_SLICE_VIEW + +// BEGIN_MERGE_PAYLOAD +unsafe fn merge_payload( + parent: *mut MaybeUninit, + left: *mut MaybeUninit, + right: *mut MaybeUninit, + parent_idx: usize, + old_parent_len: usize, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& + 0 <= parent_idx &*& parent_idx < old_parent_len &*& + 0 <= old_left_len &*& 0 <= right_len &*& new_left_len == old_left_len + 1 + right_len &*& + move_slice(parent, old_parent_len, ?p) &*& move_slice(left, new_left_len, ?l) &*& + move_slice(right, right_len, ?r) &*& slot_owners(t, p) &*& + slot_owners(t, take(old_left_len, l)) &*& slot_owners(t, r); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& + move_slice(parent, old_parent_len, ?p_after) &*& + take(old_parent_len - 1, p_after) == append(take(parent_idx, p), drop(parent_idx + 1, p)) &*& + move_slice(left, new_left_len, append(take(old_left_len, l), cons(nth(parent_idx, p), r))) &*& + move_slice(right, right_len, r) &*& slot_owners(t, take(old_parent_len - 1, p_after)) &*& + slot_owners(t, append(take(old_left_len, l), cons(nth(parent_idx, p), r))); +@*/ +//@ on_unwind_ens false; +{ + //@ move_slice_length(parent, old_parent_len); + //@ split_slot_owners(t, p, parent_idx); + //@ drop_n_plus_one(parent_idx, p); + //@ open slot_owners(t, drop(parent_idx, p)); + unsafe { + let entry = slice_remove(move_slice_mut(parent, old_parent_len), parent_idx); + //@ split_move_slice(left, new_left_len, old_left_len); + //@ split_move_slice(left + old_left_len, new_left_len - old_left_len, 1); + //@ let target = left + old_left_len; + //@ open move_slice(target, 1, _); + //@ open array(target, 1, _); + //@ open array(target + 1, 0, _); + //@ close array(target + 1, 0, nil); + (*left.add(old_left_len)).write(entry); + //@ close array(target, 1, [MaybeUninit::new(entry)]); + //@ close move_slice(target, 1, [MaybeUninit::new(entry)]); + move_to_slice( + move_slice_mut(right, right_len), + move_slice_mut(left.add(old_left_len + 1), new_left_len - (old_left_len + 1)), + ); + //@ join_move_slices(target, 1, right_len); + //@ join_move_slices(left, old_left_len, 1 + right_len); + //@ close slot_owners(t, cons(nth(parent_idx, p), r)); + //@ join_slot_owners(t, take(old_left_len, l), cons(nth(parent_idx, p), r)); + //@ let surviving = append(take(parent_idx, p), drop(parent_idx + 1, p)); + //@ join_slot_owners(t, take(parent_idx, p), drop(parent_idx + 1, p)); + //@ append_assoc(take(parent_idx, p), drop(parent_idx + 1, p), drop(old_parent_len - 1, p)); + //@ length_take(parent_idx, p); + //@ length_drop(parent_idx + 1, p); + //@ take_append_l(old_parent_len - 1, surviving, drop(old_parent_len - 1, p)); + //@ take_length(surviving); + } +} +// END_MERGE_PAYLOAD + +unsafe fn move_array_prefix( + src: *mut [MaybeUninit; CAPACITY], + start: usize, + end: usize, + dst: *mut [MaybeUninit; CAPACITY], + from: usize, + to: usize, +) +/*@ +req (src as *MaybeUninit)[..CAPACITY] |-> ?s &*& + (dst as *MaybeUninit)[..CAPACITY] |-> ?d &*& + 0 <= start &*& start <= end &*& end <= CAPACITY &*& + from == 0 &*& 0 <= from &*& from <= to &*& to <= CAPACITY &*& end - start == to - from; +@*/ +/*@ +ens (src as *MaybeUninit)[..CAPACITY] |-> s &*& + (dst as *MaybeUninit)[..CAPACITY] |-> + append(take(from, d), append(take(end - start, drop(start, s)), drop(to, d))); +@*/ +//@ on_unwind_ens false; +{ + //@ close_points_to(src); + //@ close_points_to(dst); + unsafe { + let source_array = &mut *src; + let target_array = &mut *dst; + let source = source_array.as_mut_slice(); + let target = target_array.as_mut_slice(); + //@ points_to_limits(source_array); + //@ points_to_limits(target_array); + //@ open_points_to(source_array); + //@ open_points_to(target_array); + //@ let source_base = source as *MaybeUninit; + //@ let target_base = target as *MaybeUninit; + //@ insertion_slot_limits(source_base); + //@ insertion_slot_limits(target_base); + //@ move_slice_offset(source_base, CAPACITY, start); + //@ move_slice_offset(target_base, CAPACITY, from); + //@ btree_aligned_offset(source_base, start); + //@ btree_aligned_offset(target_base, from); + //@ array_split(source_base, start); + //@ array_split(source_base + start, end - start); + + //@ array_split(target_base + from, to - from); + let source_range = source.get_unchecked_mut(start..end); + let target_range = target.get_unchecked_mut(..to); + //@ close move_slice(source_range as *MaybeUninit, end - start, _); + //@ close move_slice(target_range as *MaybeUninit, to - from, _); + move_to_slice(source_range, target_range); + //@ open move_slice(source_range as *MaybeUninit, end - start, _); + //@ open move_slice(target_range as *MaybeUninit, to - from, _); + //@ end_slice_ref_mut(source_range); + //@ end_slice_ref_mut(target_range); + //@ array_join(source_base + start); + //@ array_join(source_base); + //@ array_join(target_base + from); + + //@ close_points_to(source_array); + //@ close_points_to(target_array); + //@ end_ref_mut(source_array); + //@ end_ref_mut(target_array); + } + //@ open_points_to(src); + //@ open_points_to(dst); + //@ drop_twice(to - from, from, d); +} + +unsafe fn move_edge_range( + src: *mut [MaybeUninit; CAPACITY + 1], + start: usize, + end: usize, + dst: *mut [MaybeUninit; CAPACITY + 1], + from: usize, + to: usize, +) +/*@ +req (src as *MaybeUninit)[..CAPACITY + 1] |-> ?s &*& + (dst as *MaybeUninit)[..CAPACITY + 1] |-> ?d &*& + 0 <= start &*& start <= end &*& end <= CAPACITY + 1 &*& + 0 <= from &*& from <= to &*& to <= CAPACITY + 1 &*& end - start == to - from; +@*/ +/*@ +ens (src as *MaybeUninit)[..CAPACITY + 1] |-> s &*& + (dst as *MaybeUninit)[..CAPACITY + 1] |-> + append(take(from, d), append(take(end - start, drop(start, s)), drop(to, d))); +@*/ +//@ on_unwind_ens false; +{ + //@ close_points_to(src); + //@ close_points_to(dst); + unsafe { + let source_array = &mut *src; + let target_array = &mut *dst; + let source = source_array.as_mut_slice(); + let target = target_array.as_mut_slice(); + //@ points_to_limits(source_array); + //@ points_to_limits(target_array); + //@ open_points_to(source_array); + //@ open_points_to(target_array); + //@ let source_base = source as *MaybeUninit; + //@ let target_base = target as *MaybeUninit; + //@ insertion_slot_limits(source_base); + //@ insertion_slot_limits(target_base); + //@ move_slice_offset(source_base, CAPACITY + 1, start); + //@ move_slice_offset(target_base, CAPACITY + 1, from); + //@ btree_aligned_offset(source_base, start); + //@ btree_aligned_offset(target_base, from); + //@ array_split(source_base, start); + //@ array_split(source_base + start, end - start); + //@ array_split(target_base, from); + //@ array_split(target_base + from, to - from); + let source_range = source.get_unchecked_mut(start..end); + let target_range = target.get_unchecked_mut(from..to); + //@ close move_slice(source_range as *MaybeUninit, end - start, _); + //@ close move_slice(target_range as *MaybeUninit, to - from, _); + move_to_slice(source_range, target_range); + //@ open move_slice(source_range as *MaybeUninit, end - start, _); + //@ open move_slice(target_range as *MaybeUninit, to - from, _); + //@ end_slice_ref_mut(source_range); + //@ end_slice_ref_mut(target_range); + //@ array_join(source_base + start); + //@ array_join(source_base); + //@ array_join(target_base + from); + //@ array_join(target_base); + //@ close_points_to(source_array); + //@ close_points_to(target_array); + //@ end_ref_mut(source_array); + //@ end_ref_mut(target_array); + } + //@ open_points_to(src); + //@ open_points_to(dst); + //@ drop_twice(to - from, from, d); +} + +/*@ +lem own_move_array(base: *MaybeUninit, len: usize) + req base[..len] |-> ?slots &*& 0 < len &*& len <= usize::MAX; + ens move_slice(base, len, slots); +{ + insertion_slot_limits(base); + array_inv::>(); + close move_slice(base, len, slots); +} + +pred balancing_edges( + node: NonNull>, children: list>; + slots: list>> +) = + length(children) <= CAPACITY + 1 &*& + pointer_within_limits(&(*node.as_ptr()).edges) == true &*& + (*node.as_ptr()).edges[..CAPACITY + 1] |-> slots &*& + take(length(children), slots) == initialized_edges(children) &*& + linked_headers(children, node, 0); +@*/ + +// BEGIN_MERGE_PARENT_EDGES +unsafe fn remove_merged_edge<'a, 'short, K, V>( + parent_node: &'short mut NodeRef, K, V, marker::Internal>, + parent_idx: usize, + old_parent_len: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *parent_node |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& + node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + node.node.as_ptr() == &(*parent.as_ptr()).data &*& + struct_InternalNode_padding(parent.as_ptr()) &*& + leaf_without_len(&(*parent.as_ptr()).data, ?ancestor, ?ancestor_idx, ?keys, ?vals) &*& + balancing_edges(parent, ?children, ?slots) &*& (*parent.as_ptr()).data.len |-> (old_parent_len as u16) &*& + length(children) == old_parent_len + 1 &*& + 0 <= parent_idx &*& parent_idx < old_parent_len &*& old_parent_len <= CAPACITY &*& + nth(parent_idx + 1, children).as_ptr() as usize != 0; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *parent_node |-> node &*& struct_InternalNode_padding(parent.as_ptr()) &*& + leaf_without_len(&(*parent.as_ptr()).data, ancestor, ancestor_idx, keys, vals) &*& + (*parent.as_ptr()).data.len |-> (old_parent_len - 1) as u16 &*& + balancing_edges(parent, append(take(parent_idx + 1, children), drop(parent_idx + 2, children)), _) &*& + (*nth((parent_idx + 1) as i32, children).as_ptr()).parent |-> Option::Some(parent) &*& + (*nth((parent_idx + 1) as i32, children).as_ptr()).parent_idx |-> MaybeUninit::new((parent_idx + 1) as u16); +@*/ +//@ on_unwind_ens false; +{ + //@ open exists(parent); + //@ open balancing_edges(parent, children, slots); + //@ let parent_ptr = parent.as_ptr(); + //@ let prefix = take(parent_idx + 1, children); + //@ let rest = drop(parent_idx + 2, children); + //@ let removed = nth(parent_idx + 1, children); + //@ split_linked_headers(children, parent, 0, parent_idx + 1); + //@ drop_n_plus_one(parent_idx + 1, children); + //@ open linked_headers(cons(removed, rest), parent, parent_idx + 1); + //@ forget_link_indices(rest, parent, parent_idx + 2); + //@ let active = initialized_edges(children); + //@ nth_initialized_edge(children, parent_idx + 1); + //@ std::ptr::close_NonNull_own(t, removed); + //@ produce_type_interp::>(); + unsafe { + //@ nth_take_range(slots, old_parent_len + 1, parent_idx + 1); + //@ open leaf_without_len(&(*parent_ptr).data, ancestor, ancestor_idx, keys, vals); + //@ close_points_to(&(*parent_ptr).data); + //@ close internal_without_edges(parent_ptr, ?data); + slice_remove( + parent_node.edge_area_prefix_mut/*@::<'a,K,V,'short>@*/(..old_parent_len + 1), parent_idx + 1, + ); + //@ assert edges_range_loan(parent_ptr, ?removed_prefix, 0, old_parent_len + 1, data, _, _); + //@ end_edges_range(parent_ptr, removed_prefix); + //@ open internal_without_edges(parent_ptr, data); + //@ open_points_to(&(*parent_ptr).data); + //@ close leaf_without_len(&(*parent_ptr).data, ancestor, ancestor_idx, keys, vals); + //@ leak >.own(t, removed); + //@ std::ptr::open_NonNull_own(t, removed); + //@ leak type_interp::>(); + //@ initialized_edge_split(children, parent_idx + 1); + //@ initialized_edge_split(children, parent_idx + 2); + //@ let surviving = append(initialized_edges(prefix), initialized_edges(rest)); + //@ let residual = drop(old_parent_len, active); + //@ append_assoc(initialized_edges(prefix), initialized_edges(rest), residual); + //@ initialized_edge_count(prefix); + //@ initialized_edge_count(rest); + //@ length_take(parent_idx + 1, children); + //@ length_drop(parent_idx + 2, children); +// BEGIN_MERGE_PARENT_RELINK + //@ assert (*parent_ptr).edges[..CAPACITY + 1] |-> ?new_edges; + //@ let before = initialized_edges(prefix); + //@ let tail = drop(old_parent_len + 1, slots); + //@ append_assoc(before, append(initialized_edges(rest), residual), tail); + //@ append_assoc(initialized_edges(rest), residual, tail); + //@ close exists(parent); + //@ close exists(pair(before, append(residual, tail))); + parent_node.relink_range/*@::<'a,K,V,'short>@*/(parent_idx + 1..old_parent_len); + *parent_node.len_mut/*@::<'a,K,V,marker::Internal,'short>@*/() -= 1; + //@ assert len_loan(&(*parent_ptr).data, ?slot, ancestor, ancestor_idx, keys, vals); + //@ end_len_loan(&(*parent_ptr).data, slot); +// END_MERGE_PARENT_RELINK + //@ take_append_l(parent_idx + 1, initialized_edges(prefix), initialized_edges(rest)); + //@ take_length(initialized_edges(prefix)); + //@ take_append_l(old_parent_len, surviving, residual); + //@ take_append_l(old_parent_len, append(surviving, residual), drop(old_parent_len + 1, slots)); + //@ join_linked_headers(prefix, rest, parent, 0); + //@ initialized_edges_append(prefix, rest); + //@ close balancing_edges(parent, append(prefix, rest), new_edges); + } +} +// END_MERGE_PARENT_EDGES + +// BEGIN_MERGE_CHILD_EDGES +unsafe fn append_merged_edges<'a, 'short, K, V>( + left_node: &'short mut NodeRef, K, V, marker::Internal>, + right_node: &'short mut NodeRef, K, V, marker::Internal>, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *left_node |-> ?ln &*& *right_node |-> ?rn &*& + exists::>, NonNull>>>(pair(?left, ?right)) &*& + ln.node.as_ptr() == &(*left.as_ptr()).data &*& ln.node.as_ptr() as *InternalNode == left.as_ptr() &*& + rn.node.as_ptr() as *InternalNode == right.as_ptr() &*& + 0 < ln.height &*& ln.height <= usize::MAX &*& + internal_without_edges(left.as_ptr(), ?left_data) &*& internal_without_edges(right.as_ptr(), ?right_data) &*& + left_data.len == new_left_len as u16 &*& + balancing_edges(left, ?left_children, ?left_slots) &*& balancing_edges(right, ?right_children, ?right_slots) &*& + length(left_children) == old_left_len + 1 &*& length(right_children) == right_len + 1 &*& + 0 <= old_left_len &*& 0 <= right_len &*& new_left_len == old_left_len + 1 + right_len &*& new_left_len <= CAPACITY; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *left_node |-> ln &*& *right_node |-> rn &*& + internal_without_edges(left.as_ptr(), left_data) &*& internal_without_edges(right.as_ptr(), right_data) &*& + balancing_edges(left, append(left_children, right_children), _) &*& + (*right.as_ptr()).edges[..CAPACITY + 1] |-> right_slots; +@*/ +//@ on_unwind_ens false; +{ + //@ open exists(pair(left, right)); + //@ open balancing_edges(left, left_children, left_slots); + //@ open balancing_edges(right, right_children, right_slots); + //@ forget_link_indices(right_children, right, 0); + unsafe { + move_to_slice( + right_node.edge_area_prefix_mut/*@::<'a,K,V,'short>@*/(..right_len + 1), + left_node.edge_area_range_mut/*@::<'a,K,V,'short>@*/(old_left_len + 1..new_left_len + 1), + ); + //@ assert edges_range_loan(right.as_ptr(), ?source, 0, right_len + 1, right_data, _, _); + //@ assert edges_range_loan(left.as_ptr(), ?destination, old_left_len + 1, new_left_len + 1, left_data, _, _); + //@ end_edges_range(right.as_ptr(), source); + //@ append_take_drop_n(right_slots, right_len + 1); + //@ end_edges_range(left.as_ptr(), destination); + //@ let before = take(old_left_len + 1, left_slots); + //@ let after_copy = drop(new_left_len + 1, left_slots); + //@ length_take(old_left_len + 1, left_slots); + //@ open internal_without_edges(left.as_ptr(), left_data); + //@ open_points_to(&(*left.as_ptr()).data); + //@ close exists(left); + //@ close exists(pair(before, after_copy)); + left_node.relink_range/*@::<'a,K,V,'short>@*/(old_left_len + 1..new_left_len + 1); + //@ close_points_to(&(*left.as_ptr()).data); + //@ close internal_without_edges(left.as_ptr(), left_data); + //@ assert (*left.as_ptr()).edges[..CAPACITY + 1] |-> ?merged_slots; + //@ append_assoc(before, initialized_edges(right_children), after_copy); + //@ let active = append(initialized_edges(left_children), initialized_edges(right_children)); + //@ initialized_edge_count(left_children); + //@ initialized_edge_count(right_children); + //@ take_twice(left_slots, old_left_len + 1, new_left_len + 1); + //@ take_append_l(new_left_len + 1, active, drop(new_left_len + 1, left_slots)); + //@ take_length(active); + //@ join_linked_headers(left_children, right_children, left, 0); + //@ initialized_edges_append(left_children, right_children); + //@ close balancing_edges(left, append(left_children, right_children), merged_slots); + } +} +// END_MERGE_CHILD_EDGES + +// BEGIN_RELEASE_BALANCING_NODE +unsafe fn release_balancing_node<'alloc, T, A: std::alloc::Allocator>( + node: NonNull, + alloc: &'alloc A, +) +/*@ +req thread_token(?t) &*& Allocator::<&'alloc A>(t, alloc, ?id) &*& + [_]frac_borrow('alloc, ref_initialized_(alloc)) &*& [?shared]lifetime_token('alloc) &*& + std::alloc::alloc_block_in(id, node.as_ptr() as *u8, std::alloc::Layout::new::()) &*& + *node.as_ptr() |-> _ &*& + close_points_to_at_lft_token(1, id.lft, node.as_ptr(), ?alloc_fraction) &*& + close_lifetime_trade_token(alloc_fraction, id.lft, ?q, ?k); +@*/ +//@ ens thread_token(t) &*& Allocator::<&'alloc A>(t, alloc, id) &*& [q]lifetime_token(k) &*& [shared]lifetime_token('alloc); +//@ on_unwind_ens thread_token(t) &*& Allocator::<&'alloc A>(t, alloc, id) &*& [q]lifetime_token(k) &*& [shared]lifetime_token('alloc); +{ + let ptr = node.as_ptr(); + //@ points_to__limits(ptr); + let bytes = unsafe { NonNull::new_unchecked(ptr as *mut u8) }; + //@ to_u8s_(ptr); + //@ close_points_to_at_lft_token_to_close_u8s_at_lft_token(ptr); + //@ close_array_at_lft_(ptr as *u8); + //@ lifetime_token_trade_back(alloc_fraction, id.lft); + unsafe { alloc.deallocate/*@::@*/(bytes, std::alloc::Layout::new::()) } +} +// END_RELEASE_BALANCING_NODE + +// BEGIN_MERGE_FIELD +unsafe fn merge_keys<'a, 'short, K, V>( + parent_node: &'short mut NodeRef, K, V, marker::Internal>, + left_node: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + right_node: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + parent_idx: usize, + old_parent_len: usize, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& + *parent_node |-> ?pn &*& *left_node |-> ?ln &*& *right_node |-> ?rn &*& + leaf_without_keys(pn.node.as_ptr(), ?p_parent, ?p_idx, ?p_len, ?p_vals) &*& + leaf_without_keys(ln.node.as_ptr(), ?l_parent, ?l_idx, ?l_len, ?l_vals) &*& + leaf_without_keys(rn.node.as_ptr(), ?r_parent, ?r_idx, ?r_len, ?r_vals) &*& + (*pn.node.as_ptr()).keys[..CAPACITY] |-> ?p &*& + (*ln.node.as_ptr()).keys[..CAPACITY] |-> ?l &*& + (*rn.node.as_ptr()).keys[..CAPACITY] |-> ?r &*& + 0 <= parent_idx &*& parent_idx < old_parent_len &*& old_parent_len <= CAPACITY &*& + 0 <= old_left_len &*& 0 <= right_len &*& new_left_len == old_left_len + 1 + right_len &*& new_left_len <= CAPACITY &*& + slot_owners(t, take(old_parent_len, p)) &*& slot_owners(t, take(old_left_len, l)) &*& slot_owners(t, take(right_len, r)); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& + *parent_node |-> pn &*& *left_node |-> ln &*& *right_node |-> rn &*& + leaf_without_keys(pn.node.as_ptr(), p_parent, p_idx, p_len, p_vals) &*& + leaf_without_keys(ln.node.as_ptr(), l_parent, l_idx, l_len, l_vals) &*& + leaf_without_keys(rn.node.as_ptr(), r_parent, r_idx, r_len, r_vals) &*& + (*pn.node.as_ptr()).keys[..CAPACITY] |-> ?p_after &*& + (*ln.node.as_ptr()).keys[..CAPACITY] |-> ?l_after &*& + (*rn.node.as_ptr()).keys[..CAPACITY] |-> r &*& + take(old_parent_len - 1, p_after) == + append(take(parent_idx, take(old_parent_len, p)), drop(parent_idx + 1, take(old_parent_len, p))) &*& + take(new_left_len, l_after) == append(take(old_left_len, l), cons(nth(parent_idx, p), take(right_len, r))) &*& + drop(old_parent_len, p_after) == drop(old_parent_len, p) &*& + drop(new_left_len, l_after) == drop(new_left_len, l) &*& + slot_owners(t, take(old_parent_len - 1, p_after)) &*& slot_owners(t, take(new_left_len, l_after)); +@*/ +//@ on_unwind_ens false; +{ + //@ let parent = pn.node.as_ptr(); + //@ let left = ln.node.as_ptr(); + //@ let right = rn.node.as_ptr(); + //@ let old_parent = take(old_parent_len, p); + //@ let old_left = take(old_left_len, l); + //@ let incoming = take(right_len, r); + //@ length_take(old_parent_len, p); + //@ length_take(old_left_len, l); + //@ length_take(right_len, r); + //@ nth_take_range(p, old_parent_len, parent_idx); + //@ split_slot_owners(t, old_parent, parent_idx); + //@ drop_n_plus_one(parent_idx, old_parent); + //@ open slot_owners(t, drop(parent_idx, old_parent)); + unsafe { + let entry = slice_remove( + parent_node.key_area_prefix_mut/*@::<'a,K,V,marker::Internal,'short>@*/(..old_parent_len), parent_idx, + ); + //@ assert keys_range_loan(parent, ?active, 0, old_parent_len, p_parent, p_idx, p_len, p_vals, _, _); + //@ assert move_slice(active as *MaybeUninit, old_parent_len, ?active_after); + //@ end_keys_range(parent, active); + //@ let surviving = append(take(parent_idx, old_parent), drop(parent_idx + 1, old_parent)); + //@ join_slot_owners(t, take(parent_idx, old_parent), drop(parent_idx + 1, old_parent)); + //@ length_take(parent_idx, old_parent); + //@ length_drop(parent_idx + 1, old_parent); + //@ append_assoc(take(parent_idx, old_parent), drop(parent_idx + 1, old_parent), drop(old_parent_len - 1, old_parent)); + //@ take_append_l(old_parent_len - 1, surviving, drop(old_parent_len - 1, old_parent)); + //@ take_length(surviving); + //@ length_append(surviving, drop(old_parent_len - 1, old_parent)); + //@ length_drop(old_parent_len - 1, old_parent); + //@ take_append_l(old_parent_len - 1, active_after, drop(old_parent_len, p)); + //@ drop_append(old_parent_len, active_after, drop(old_parent_len, p)); + + left_node.key_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(old_left_len).write(entry); + //@ assert keys_slot_loan(left, ?slot, old_left_len, l_parent, l_idx, l_len, l_vals, _, _); + //@ end_keys_slot(left, slot); + //@ assert (*left).keys[..CAPACITY] |-> ?left_with_entry; + //@ let with_entry = append(old_left, [MaybeUninit::new(entry)]); + //@ append_assoc(old_left, [MaybeUninit::new(entry)], drop(old_left_len + 1, l)); + //@ take_append_l(old_left_len + 1, with_entry, drop(old_left_len + 1, l)); + //@ take_length(with_entry); + + move_to_slice( + right_node.key_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..right_len), + left_node.key_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(old_left_len + 1..new_left_len), + ); + //@ assert keys_range_loan(right, ?source, 0, right_len, r_parent, r_idx, r_len, r_vals, _, _); + //@ assert keys_range_loan(left, ?destination, old_left_len + 1, new_left_len, l_parent, l_idx, l_len, l_vals, _, _); + //@ end_keys_range(right, source); + //@ append_take_drop_n(r, right_len); + //@ end_keys_range(left, destination); + //@ close slot_owners::(t, cons(MaybeUninit::new(entry), incoming)); + //@ join_slot_owners(t, old_left, cons(MaybeUninit::new(entry), incoming)); + //@ let merged = append(old_left, cons(MaybeUninit::new(entry), incoming)); + //@ append_assoc(with_entry, incoming, drop(new_left_len, left_with_entry)); + //@ append_assoc(old_left, [MaybeUninit::new(entry)], incoming); + //@ take_append_l(new_left_len, merged, drop(new_left_len, left_with_entry)); + //@ take_length(merged); + //@ length_append(with_entry, incoming); + //@ drop_append(new_left_len, merged, drop(new_left_len, left_with_entry)); + //@ drop_append(new_left_len, with_entry, drop(old_left_len + 1, l)); + //@ drop_twice(right_len, old_left_len + 1, l); + } +} + +unsafe fn merge_vals<'a, 'short, K, V>( + parent_node: &'short mut NodeRef, K, V, marker::Internal>, + left_node: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + right_node: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + parent_idx: usize, + old_parent_len: usize, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& + *parent_node |-> ?pn &*& *left_node |-> ?ln &*& *right_node |-> ?rn &*& + leaf_without_vals(pn.node.as_ptr(), ?p_parent, ?p_idx, ?p_len, ?p_keys) &*& + leaf_without_vals(ln.node.as_ptr(), ?l_parent, ?l_idx, ?l_len, ?l_keys) &*& + leaf_without_vals(rn.node.as_ptr(), ?r_parent, ?r_idx, ?r_len, ?r_keys) &*& + (*pn.node.as_ptr()).vals[..CAPACITY] |-> ?p &*& + (*ln.node.as_ptr()).vals[..CAPACITY] |-> ?l &*& + (*rn.node.as_ptr()).vals[..CAPACITY] |-> ?r &*& + 0 <= parent_idx &*& parent_idx < old_parent_len &*& old_parent_len <= CAPACITY &*& + 0 <= old_left_len &*& 0 <= right_len &*& new_left_len == old_left_len + 1 + right_len &*& new_left_len <= CAPACITY &*& + slot_owners(t, take(old_parent_len, p)) &*& slot_owners(t, take(old_left_len, l)) &*& slot_owners(t, take(right_len, r)); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& + *parent_node |-> pn &*& *left_node |-> ln &*& *right_node |-> rn &*& + leaf_without_vals(pn.node.as_ptr(), p_parent, p_idx, p_len, p_keys) &*& + leaf_without_vals(ln.node.as_ptr(), l_parent, l_idx, l_len, l_keys) &*& + leaf_without_vals(rn.node.as_ptr(), r_parent, r_idx, r_len, r_keys) &*& + (*pn.node.as_ptr()).vals[..CAPACITY] |-> ?p_after &*& + (*ln.node.as_ptr()).vals[..CAPACITY] |-> ?l_after &*& + (*rn.node.as_ptr()).vals[..CAPACITY] |-> r &*& + take(old_parent_len - 1, p_after) == + append(take(parent_idx, take(old_parent_len, p)), drop(parent_idx + 1, take(old_parent_len, p))) &*& + take(new_left_len, l_after) == append(take(old_left_len, l), cons(nth(parent_idx, p), take(right_len, r))) &*& + drop(old_parent_len, p_after) == drop(old_parent_len, p) &*& + drop(new_left_len, l_after) == drop(new_left_len, l) &*& + slot_owners(t, take(old_parent_len - 1, p_after)) &*& slot_owners(t, take(new_left_len, l_after)); +@*/ +//@ on_unwind_ens false; +{ + //@ let parent = pn.node.as_ptr(); + //@ let left = ln.node.as_ptr(); + //@ let right = rn.node.as_ptr(); + //@ let old_parent = take(old_parent_len, p); + //@ let old_left = take(old_left_len, l); + //@ let incoming = take(right_len, r); + //@ length_take(old_parent_len, p); + //@ length_take(old_left_len, l); + //@ length_take(right_len, r); + //@ nth_take_range(p, old_parent_len, parent_idx); + //@ split_slot_owners(t, old_parent, parent_idx); + //@ drop_n_plus_one(parent_idx, old_parent); + //@ open slot_owners(t, drop(parent_idx, old_parent)); + unsafe { + let entry = slice_remove( + parent_node.val_area_prefix_mut/*@::<'a,K,V,marker::Internal,'short>@*/(..old_parent_len), parent_idx, + ); + //@ assert vals_range_loan(parent, ?active, 0, old_parent_len, p_parent, p_idx, p_len, p_keys, _, _); + //@ assert move_slice(active as *MaybeUninit, old_parent_len, ?active_after); + //@ end_vals_range(parent, active); + //@ let surviving = append(take(parent_idx, old_parent), drop(parent_idx + 1, old_parent)); + //@ join_slot_owners(t, take(parent_idx, old_parent), drop(parent_idx + 1, old_parent)); + //@ length_take(parent_idx, old_parent); + //@ length_drop(parent_idx + 1, old_parent); + //@ append_assoc(take(parent_idx, old_parent), drop(parent_idx + 1, old_parent), drop(old_parent_len - 1, old_parent)); + //@ take_append_l(old_parent_len - 1, surviving, drop(old_parent_len - 1, old_parent)); + //@ take_length(surviving); + //@ length_append(surviving, drop(old_parent_len - 1, old_parent)); + //@ length_drop(old_parent_len - 1, old_parent); + //@ take_append_l(old_parent_len - 1, active_after, drop(old_parent_len, p)); + //@ drop_append(old_parent_len, active_after, drop(old_parent_len, p)); + + left_node.val_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(old_left_len).write(entry); + //@ assert vals_slot_loan(left, ?slot, old_left_len, l_parent, l_idx, l_len, l_keys, _, _); + //@ end_vals_slot(left, slot); + //@ assert (*left).vals[..CAPACITY] |-> ?left_with_entry; + //@ let with_entry = append(old_left, [MaybeUninit::new(entry)]); + //@ append_assoc(old_left, [MaybeUninit::new(entry)], drop(old_left_len + 1, l)); + //@ take_append_l(old_left_len + 1, with_entry, drop(old_left_len + 1, l)); + //@ take_length(with_entry); + + move_to_slice( + right_node.val_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..right_len), + left_node.val_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(old_left_len + 1..new_left_len), + ); + //@ assert vals_range_loan(right, ?source, 0, right_len, r_parent, r_idx, r_len, r_keys, _, _); + //@ assert vals_range_loan(left, ?destination, old_left_len + 1, new_left_len, l_parent, l_idx, l_len, l_keys, _, _); + //@ end_vals_range(right, source); + //@ append_take_drop_n(r, right_len); + //@ end_vals_range(left, destination); + //@ close slot_owners::(t, cons(MaybeUninit::new(entry), incoming)); + //@ join_slot_owners(t, old_left, cons(MaybeUninit::new(entry), incoming)); + //@ let merged = append(old_left, cons(MaybeUninit::new(entry), incoming)); + //@ append_assoc(with_entry, incoming, drop(new_left_len, left_with_entry)); + //@ append_assoc(old_left, [MaybeUninit::new(entry)], incoming); + //@ take_append_l(new_left_len, merged, drop(new_left_len, left_with_entry)); + //@ take_length(merged); + //@ length_append(with_entry, incoming); + //@ drop_append(new_left_len, merged, drop(new_left_len, left_with_entry)); + //@ drop_append(new_left_len, with_entry, drop(old_left_len + 1, l)); + //@ drop_twice(right_len, old_left_len + 1, l); + } +} +// END_MERGE_FIELD + +/*@ +pred owned_leaf_slots( + thread: thread_id_t, node: *LeafNode, len: usize +) = + leaf_slots(node, len, ?keys, ?vals) &*& + slot_owners(thread, take(len, keys)) &*& slot_owners(thread, take(len, vals)); + +pred balancing_child_edges( + child: NonNull>, height: usize, len: usize, + descendants: list> +) = + if height == 0 { + descendants == [] + } else { + balancing_edges(NonNull::new(child.as_ptr() as *InternalNode), descendants, _) &*& + length(descendants) == len + 1 + }; + +pred balancing_child_allocation( + child: NonNull>, height: usize, id: std::alloc::alloc_id_t, k: lifetime_t, q: real +) = + if height == 0 { + allocated_leaf(child.as_ptr(), id, k, q) + } else { + allocated_internal(child.as_ptr() as *InternalNode, id, k, q) + }; + +pred leaf_header(node: *LeafNode; + ancestor: Option>>, ancestor_idx: MaybeUninit) = + struct_LeafNode_padding(node) &*& (*node).parent |-> ancestor &*& (*node).parent_idx |-> ancestor_idx; + +pred balancing_child_padding(child: NonNull>, height: usize) = + if height > 0 { struct_InternalNode_padding(child.as_ptr() as *InternalNode) } else { true }; + +pred merge_inputs( + t: thread_id_t, parent: NonNull>, left: NonNull>, right: NonNull>, + parent_height: usize, parent_idx: usize, id: std::alloc::alloc_id_t, k: lifetime_t, released: real, + parent_len: usize, left_len: usize, right_len: usize, + parent_children: list>, left_children: list>, right_children: list> +) = + 0 < parent_height &*& parent_height <= usize::MAX &*& + struct_InternalNode_padding(parent.as_ptr()) &*& leaf_header(&(*parent.as_ptr()).data, _, _) &*& + owned_leaf_slots(t, &(*parent.as_ptr()).data, parent_len) &*& + balancing_edges(parent, parent_children, _) &*& length(parent_children) == parent_len + 1 &*& + 0 <= parent_idx &*& parent_idx < parent_len &*& + nth(parent_idx, parent_children) == left &*& nth(parent_idx + 1, parent_children) == right &*& + left.as_ptr() as usize != 0 &*& right.as_ptr() as usize != 0 &*& + struct_LeafNode_padding(left.as_ptr()) &*& + balancing_child_padding(left, parent_height - 1) &*& + owned_leaf_slots(t, left.as_ptr(), left_len) &*& owned_leaf_slots(t, right.as_ptr(), right_len) &*& + balancing_child_edges(left, parent_height - 1, left_len, left_children) &*& + balancing_child_edges(right, parent_height - 1, right_len, right_children) &*& + balancing_child_allocation(right, parent_height - 1, id, k, released); + +pred merged_nodes( + t: thread_id_t, parent: NonNull>, left: NonNull>, + child_height: usize, parent_len: usize, left_len: usize, + parent_children: list>, left_children: list> +) = + struct_InternalNode_padding(parent.as_ptr()) &*& leaf_header(&(*parent.as_ptr()).data, _, _) &*& + owned_leaf_slots(t, &(*parent.as_ptr()).data, parent_len) &*& + balancing_edges(parent, parent_children, _) &*& + struct_LeafNode_padding(left.as_ptr()) &*& + balancing_child_padding(left, child_height) &*& + owned_leaf_slots(t, left.as_ptr(), left_len) &*& + balancing_child_edges(left, child_height, left_len, left_children); +@*/ + +// BEGIN_MERGE_NODES +unsafe fn merge_nodes<'alloc, K, V, A: std::alloc::Allocator>( + parent: NonNull>, + left: NonNull>, + right: NonNull>, + parent_height: usize, + parent_idx: usize, + alloc: &'alloc A, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, ?id) &*& [_]frac_borrow('alloc, ref_initialized_(alloc)) &*& + [?shared]lifetime_token('alloc) &*& exists::(?k) &*& exists::(?released) &*& + merge_inputs(t, parent, left, right, parent_height, parent_idx, id, k, released, + ?parent_len, ?left_len, ?right_len_0, ?parent_children, ?left_children, ?right_children) &*& + left_len + 1 + right_len_0 <= CAPACITY; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, id) &*& [shared]lifetime_token('alloc) &*& [released]lifetime_token(k) &*& + merged_nodes(t, parent, left, parent_height - 1, parent_len - 1, left_len + 1 + right_len_0, + append(take(parent_idx + 1, parent_children), drop(parent_idx + 2, parent_children)), + append(left_children, right_children)); +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, id) &*& [shared]lifetime_token('alloc) &*& [released]lifetime_token(k) &*& + merged_nodes(t, parent, left, parent_height - 1, parent_len - 1, left_len + 1 + right_len_0, + append(take(parent_idx + 1, parent_children), drop(parent_idx + 2, parent_children)), + append(left_children, right_children)); +@*/ +{ + //@ open exists(k); + //@ open exists(released); + //@ open merge_inputs(t, parent, left, right, parent_height, parent_idx, id, k, released, parent_len, left_len, right_len_0, parent_children, left_children, right_children); + //@ open owned_leaf_slots(t, &(*parent.as_ptr()).data, parent_len); + //@ open leaf_slots(&(*parent.as_ptr()).data, parent_len, ?p_keys, ?p_vals); + let parent_ptr = unsafe { &raw mut (*parent.as_ptr()).data }; + let old_parent_len = unsafe { (*parent_ptr).len } as usize; + //@ open owned_leaf_slots(t, left.as_ptr(), left_len); + //@ open leaf_slots(left.as_ptr(), left_len, ?l_keys, ?l_vals); + let left_ptr = left.as_ptr(); + let old_left_len = unsafe { (*left_ptr).len } as usize; + //@ open owned_leaf_slots(t, right.as_ptr(), right_len_0); + //@ open leaf_slots(right.as_ptr(), right_len_0, ?r_keys, ?r_vals); + let right_ptr = right.as_ptr(); + let right_len = unsafe { (*right_ptr).len } as usize; + let new_left_len = old_left_len + 1 + right_len; + assert!(new_left_len <= CAPACITY); + +// BEGIN_MERGE_MODEL_PAYLOAD + let mut parent_node = NodeRef::, K, V, marker::Internal> { + height: parent_height, node: parent.cast(), _marker: PhantomData, + }; + //@ std::ptr::NonNull_new_as_ptr(parent_node.node); + let mut left_node = NodeRef::, K, V, marker::LeafOrInternal> { + height: parent_height - 1, node: left, _marker: PhantomData, + }; + let mut right_node = NodeRef::, K, V, marker::LeafOrInternal> { + height: parent_height - 1, node: right, _marker: PhantomData, + }; + //@ open balancing_edges(parent, parent_children, ?parent_slots); + //@ split_linked_headers(parent_children, parent, 0, parent_idx); + //@ drop_n_plus_one(parent_idx, parent_children); + //@ open linked_headers(drop(parent_idx, parent_children), parent, parent_idx); + //@ drop_n_plus_one(parent_idx + 1, parent_children); + //@ open linked_headers(drop(parent_idx + 1, parent_children), parent, parent_idx + 1); + //@ close leaf_without_len(left_ptr, Option::Some(parent), MaybeUninit::new(parent_idx as u16), l_keys, l_vals); + unsafe { + let slot = left_node.len_mut(); + *slot = new_left_len as u16; + //@ end_len_loan(left_ptr, slot); + //@ open leaf_without_len(left_ptr, Option::Some(parent), MaybeUninit::new(parent_idx as u16), l_keys, l_vals); + //@ open balancing_child_allocation(right, parent_height - 1, id, k, released); + /*@ + if parent_height > 1 { + let internal = right_ptr as *InternalNode; + open allocated_internal(internal, id, k, released); + assert &(*internal).data == right_ptr; + } else { + open allocated_leaf(right_ptr, id, k, released); + } + @*/ + //@ close leaf_header(left_ptr, Option::Some(parent), MaybeUninit::new(parent_idx as u16)); + //@ close leaf_header(right_ptr, Option::Some(parent), MaybeUninit::new((parent_idx + 1) as u16)); + //@ close leaf_without_keys(parent_ptr, _, _, old_parent_len as u16, _); + //@ close leaf_without_keys(left_ptr, _, _, new_left_len as u16, _); + //@ close leaf_without_keys(right_ptr, _, _, right_len as u16, _); + merge_keys( + &mut parent_node, &mut left_node, &mut right_node, + parent_idx, old_parent_len, old_left_len, right_len, new_left_len, + ); + //@ open leaf_without_keys(parent_ptr, _, _, old_parent_len as u16, _); + //@ open leaf_without_keys(left_ptr, _, _, new_left_len as u16, _); + //@ open leaf_without_keys(right_ptr, _, _, right_len as u16, _); + //@ close leaf_without_vals(parent_ptr, _, _, old_parent_len as u16, _); + //@ close leaf_without_vals(left_ptr, _, _, new_left_len as u16, _); + //@ close leaf_without_vals(right_ptr, _, _, right_len as u16, _); + merge_vals( + &mut parent_node, &mut left_node, &mut right_node, + parent_idx, old_parent_len, old_left_len, right_len, new_left_len, + ); + //@ open leaf_without_vals(parent_ptr, _, _, old_parent_len as u16, _); + //@ open leaf_without_vals(left_ptr, _, _, new_left_len as u16, _); + //@ open leaf_without_vals(right_ptr, _, _, right_len as u16, _); + //@ open leaf_header(right_ptr, _, _); + //@ open leaf_header(left_ptr, _, _); + /*@ + if parent_height > 1 { + close allocated_internal(right_ptr as *InternalNode, id, k, released); + } else { + close allocated_leaf(right_ptr, id, k, released); + } + @*/ + //@ close balancing_child_allocation(right, parent_height - 1, id, k, released); + //@ close linked_headers(drop(parent_idx + 1, parent_children), parent, parent_idx + 1); + //@ close linked_headers(drop(parent_idx, parent_children), parent, parent_idx); + //@ length_take(parent_idx, parent_children); + //@ join_linked_headers(take(parent_idx, parent_children), drop(parent_idx, parent_children), parent, 0); + //@ append_take_drop_n(parent_children, parent_idx); + //@ close balancing_edges(parent, parent_children, parent_slots); +// END_MERGE_MODEL_PAYLOAD +// BEGIN_MERGE_MODEL_PARENT_CALL + //@ open leaf_header(parent_ptr, ?ancestor, ?ancestor_idx); + //@ close leaf_without_len(parent_ptr, ancestor, ancestor_idx, _, _); + //@ close exists(parent); + remove_merged_edge(&mut parent_node, parent_idx, old_parent_len); + //@ open leaf_without_len(parent_ptr, ancestor, ancestor_idx, _, _); + //@ close leaf_header(parent_ptr, ancestor, ancestor_idx); +// END_MERGE_MODEL_PARENT_CALL + //@ close leaf_slots(parent_ptr, old_parent_len - 1, _, _); + //@ close owned_leaf_slots(t, parent_ptr, old_parent_len - 1); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ open balancing_child_edges(left, parent_height - 1, left_len, left_children); + //@ open balancing_child_edges(right, parent_height - 1, right_len, right_children); + //@ open balancing_child_allocation(right, parent_height - 1, id, k, released); + //@ let surviving = append(take(parent_idx + 1, parent_children), drop(parent_idx + 2, parent_children)); + if parent_height > 1 { +// BEGIN_MERGE_MODEL_INTERNAL + let mut left_node = left_node.reborrow_mut().cast_to_internal_unchecked(); + let mut right_node = right_node.cast_to_internal_unchecked(); + let left_internal: NonNull> = left_node.node.cast(); + let right_internal: NonNull> = right_node.node.cast(); +// END_MERGE_MODEL_CASTS + //@ std::ptr::NonNull_new_as_ptr(left_internal); + //@ std::ptr::NonNull_new_as_ptr(right_internal); + //@ assert &(*left_internal.as_ptr()).data == left_ptr; + //@ assert &(*right_internal.as_ptr()).data == right_ptr; + //@ open owned_leaf_slots(t, left_ptr, new_left_len); + //@ open leaf_slots(left_ptr, new_left_len, _, _); + //@ open balancing_child_padding(left, parent_height - 1); + //@ open allocated_internal(right_internal.as_ptr(), id, k, released); + //@ open balancing_edges(parent, surviving, ?parent_edges); + //@ let before_left = take(parent_idx + 1, parent_children); + //@ let after_right = drop(parent_idx + 2, parent_children); + //@ length_take(parent_idx + 1, parent_children); + //@ length_drop(parent_idx + 2, parent_children); + //@ length_append(before_left, after_right); + //@ take_append_l(parent_idx + 1, before_left, after_right); + //@ take_length(before_left); + //@ nth_take_range(surviving, parent_idx + 1, parent_idx); + //@ nth_take_range(parent_children, parent_idx + 1, parent_idx); + //@ split_linked_headers(surviving, parent, 0, parent_idx); + //@ drop_n_plus_one(parent_idx, surviving); + //@ open linked_headers(drop(parent_idx, surviving), parent, parent_idx); + //@ close_points_to(left_ptr); + //@ close_points_to(right_ptr); + //@ close internal_without_edges(left_internal.as_ptr(), ?left_data); + //@ close internal_without_edges(right_internal.as_ptr(), ?right_data); + //@ close exists(pair(left_internal, right_internal)); + append_merged_edges(&mut left_node, &mut right_node, old_left_len, right_len, new_left_len); + //@ open internal_without_edges(left_internal.as_ptr(), left_data); + //@ open_points_to(left_ptr); + //@ close linked_headers(drop(parent_idx, surviving), parent, parent_idx); + //@ length_take(parent_idx, surviving); + //@ join_linked_headers(take(parent_idx, surviving), drop(parent_idx, surviving), parent, 0); + //@ append_take_drop_n(surviving, parent_idx); + //@ close balancing_edges(parent, surviving, parent_edges); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ close balancing_child_edges(left, parent_height - 1, new_left_len, append(left_children, right_children)); + //@ close balancing_child_padding(left, parent_height - 1); + //@ close merged_nodes(t, parent, left, parent_height - 1, old_parent_len - 1, new_left_len, surviving, append(left_children, right_children)); + //@ open internal_without_edges(right_internal.as_ptr(), right_data); + //@ open_points_to(right_ptr); + //@ close_points_to(right_internal.as_ptr(), 1); + release_balancing_node/*@::,A,'alloc>@*/(right_internal, alloc); +// END_MERGE_MODEL_INTERNAL + } else { + //@ close balancing_child_edges(left, parent_height - 1, new_left_len, append(left_children, right_children)); + //@ close merged_nodes(t, parent, left, parent_height - 1, old_parent_len - 1, new_left_len, surviving, append(left_children, right_children)); + //@ open allocated_leaf(right_ptr, id, k, released); + //@ close_points_to(right_ptr, 1); + release_balancing_node/*@::,A,'alloc>@*/(right, alloc); + } + } +} +// END_MERGE_NODES + +struct BalancingContext<'a, K, V> { + parent: Handle, K, V, marker::Internal>, marker::KV>, + left_child: NodeRef, K, V, marker::LeafOrInternal>, + right_child: NodeRef, K, V, marker::LeafOrInternal>, +} + +/*@ +inductive MergeLengths = MergeLengths( + usize, usize, usize, list>, list>, list> +); + +pred context_merge_inputs<'tree,K,V>( + t: thread_id_t, context: BalancingContext<'tree,K,V>, id: std::alloc::alloc_id_t, + k: lifetime_t, released: real, shape: MergeLengths +) = + context.parent.node.node.as_ptr() as usize != 0 &*& context.left_child.node.as_ptr() as usize != 0 &*& + context.left_child.height == context.parent.node.height - 1 &*& + context.right_child.height == context.parent.node.height - 1 &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + merge_inputs(t, NonNull::new(context.parent.node.node.as_ptr() as *InternalNode), + context.left_child.node, context.right_child.node, context.parent.node.height, context.parent.idx, + id, k, released, p, l, r, pc, lc, rc) + }; + +pred context_can_merge<'tree,K,V>( + t: thread_id_t, context: BalancingContext<'tree,K,V>, id: std::alloc::alloc_id_t, + k: lifetime_t, released: real, shape: MergeLengths +) = + context_merge_inputs(t, context, id, k, released, shape) &*& + match shape { MergeLengths(p, l, r, pc, lc, rc) => l + 1 + r <= CAPACITY }; + +@*/ + +// BEGIN_MERGE_LEFT_CHILD +unsafe fn merge_left_child<'tree, 'alloc, K, V, A: std::alloc::Allocator>( + context: BalancingContext<'tree, K, V>, + alloc: &'alloc A, +) -> NodeRef, K, V, marker::LeafOrInternal> +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, ?id) &*& [_]frac_borrow('alloc, ref_initialized_(alloc)) &*& + [?shared]lifetime_token('alloc) &*& exists::(?k) &*& exists::(?released) &*& + context_can_merge(t, context, id, k, released, ?shape); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, id) &*& [shared]lifetime_token('alloc) &*& [released]lifetime_token(k) &*& + result == context.left_child &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + merged_nodes(t, NonNull::new(context.parent.node.node.as_ptr() as *InternalNode), + context.left_child.node, context.parent.node.height - 1, p - 1, l + 1 + r, + append(take(context.parent.idx + 1, pc), drop(context.parent.idx + 2, pc)), append(lc, rc)) + }; +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, id) &*& [shared]lifetime_token('alloc) &*& [released]lifetime_token(k) &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + merged_nodes(t, NonNull::new(context.parent.node.node.as_ptr() as *InternalNode), + context.left_child.node, context.parent.node.height - 1, p - 1, l + 1 + r, + append(take(context.parent.idx + 1, pc), drop(context.parent.idx + 2, pc)), append(lc, rc)) + }; +@*/ +{ + //@ open context_can_merge(t, context, id, k, released, shape); + //@ open context_merge_inputs(t, context, id, k, released, shape); + let Handle { node: parent_node, idx: parent_idx, .. } = context.parent; + let left_node = context.left_child; + let right_node = context.right_child; + let parent = unsafe { NonNull::new_unchecked(parent_node.node.as_ptr() as *mut InternalNode) }; + //@ std::ptr::NonNull_new_as_ptr(parent); + unsafe { + merge_nodes/*@::@*/(parent, left_node.node, right_node.node, parent_node.height, parent_idx, alloc); + } + left_node +} +// END_MERGE_LEFT_CHILD + +// BEGIN_MERGE_CALLBACK +unsafe fn call_merge__VeriFast_wrapper R, R>(finish: F, parent: P, child: C) -> R +//@ req thread_token(?t) &*& .own(t, finish) &*&

.own(t, parent) &*& .own(t, child); +//@ ens thread_token(t) &*& .own(t, result); +//@ on_unwind_ens thread_token(t); +{ + //@ close_tuple_2_own(t, std_tuple_2_:: { 0: parent, 1: child }); + finish(parent, child) +} +// END_MERGE_CALLBACK + +// BEGIN_DO_MERGE +unsafe fn do_merge<'tree, 'alloc, K, V, F, R, A>( + context: BalancingContext<'tree, K, V>, + finish: F, + alloc: &'alloc A, +) -> R +where + F: FnOnce( + NodeRef, K, V, marker::Internal>, + NodeRef, K, V, marker::LeafOrInternal>, + ) -> R, + A: std::alloc::Allocator, +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& .own(t, finish) &*& + Allocator::<&'alloc A>(t, alloc, ?id) &*& [_]frac_borrow('alloc, ref_initialized_(alloc)) &*& + [?shared]lifetime_token('alloc) &*& exists::(?k) &*& exists::(?released) &*& + context_can_merge(t, context, id, k, released, ?shape); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& .own(t, result) &*& + Allocator::<&'alloc A>(t, alloc, id) &*& [shared]lifetime_token('alloc) &*& [released]lifetime_token(k) &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + merged_nodes(t, NonNull::new(context.parent.node.node.as_ptr() as *InternalNode), + context.left_child.node, context.parent.node.height - 1, p - 1, l + 1 + r, + append(take(context.parent.idx + 1, pc), drop(context.parent.idx + 2, pc)), append(lc, rc)) + }; +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, id) &*& [shared]lifetime_token('alloc) &*& [released]lifetime_token(k) &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + merged_nodes(t, NonNull::new(context.parent.node.node.as_ptr() as *InternalNode), + context.left_child.node, context.parent.node.height - 1, p - 1, l + 1 + r, + append(take(context.parent.idx + 1, pc), drop(context.parent.idx + 2, pc)), append(lc, rc)) + }; +@*/ +{ + //@ open context_can_merge(t, context, id, k, released, shape); + //@ open context_merge_inputs(t, context, id, k, released, shape); + let Handle { node: parent_node, idx: parent_idx, .. } = context.parent; + let left_node = context.left_child; + let right_node = context.right_child; + let parent = unsafe { NonNull::new_unchecked(parent_node.node.as_ptr() as *mut InternalNode) }; + //@ std::ptr::NonNull_new_as_ptr(parent); + unsafe { + merge_nodes/*@::@*/(parent, left_node.node, right_node.node, parent_node.height, parent_idx, alloc); + } + //@ close NodeRef_own::,K,V,marker::Internal>(t,parent_node); + //@ close NodeRef_own::,K,V,marker::LeafOrInternal>(t,left_node); + unsafe { call_merge__VeriFast_wrapper(finish, parent_node, left_node) } +} +// END_DO_MERGE + +// BEGIN_FINISH_MERGE_TRACKING +unsafe fn finish_merge_tracking__VeriFast_wrapper<'tree, K, V>( + child: NodeRef, K, V, marker::LeafOrInternal>, + old_left_len: usize, + track_edge_idx: LeftOrRight, +) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> +/*@ +req (*child.node.as_ptr()).len |-> ?len &*& 0 <= old_left_len &*& old_left_len < len &*& + match track_edge_idx { + LeftOrRight::Left(idx) => 0 <= idx &*& idx <= old_left_len, + LeftOrRight::Right(idx) => 0 <= idx &*& idx <= len - old_left_len - 1 + }; +@*/ +/*@ +ens (*child.node.as_ptr()).len |-> len &*& result.node == child &*& + match track_edge_idx { + LeftOrRight::Left(idx) => result.idx == idx, + LeftOrRight::Right(idx) => result.idx == old_left_len + 1 + idx + }; +@*/ +//@ on_unwind_ens false; +{ + let new_idx = match track_edge_idx { + LeftOrRight::Left(idx) => idx, + LeftOrRight::Right(idx) => old_left_len + 1 + idx, + }; + unsafe { + Handle::, K, V, marker::LeafOrInternal>, marker::Edge>::new_edge(child, new_idx) + } +} +// END_FINISH_MERGE_TRACKING + +// BEGIN_MERGE_TRACKED_EDGE +unsafe fn merge_tracking_child_edge<'tree, 'alloc, K, V, A: std::alloc::Allocator>( + parent: NonNull>, + left: NodeRef, K, V, marker::LeafOrInternal>, + right: NonNull>, + parent_height: usize, + parent_idx: usize, + track_edge_idx: LeftOrRight, + alloc: &'alloc A, +) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, ?id) &*& [_]frac_borrow('alloc, ref_initialized_(alloc)) &*& + [?shared]lifetime_token('alloc) &*& exists::(?k) &*& exists::(?released) &*& + merge_inputs(t, parent, left.node, right, parent_height, parent_idx, id, k, released, + ?parent_len, ?left_len, ?right_len_0, ?parent_children, ?left_children, ?right_children) &*& + left_len + 1 + right_len_0 <= CAPACITY &*& + left.height == parent_height - 1 &*& + match track_edge_idx { + LeftOrRight::Left(idx) => 0 <= idx &*& idx <= left_len, + LeftOrRight::Right(idx) => 0 <= idx &*& idx <= right_len_0 + }; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, id) &*& [shared]lifetime_token('alloc) &*& [released]lifetime_token(k) &*& + merged_nodes(t, parent, left.node, parent_height - 1, parent_len - 1, left_len + 1 + right_len_0, + append(take(parent_idx + 1, parent_children), drop(parent_idx + 2, parent_children)), + append(left_children, right_children)) &*& result.node == left &*& + match track_edge_idx { + LeftOrRight::Left(idx) => result.idx == idx, + LeftOrRight::Right(idx) => result.idx == left_len + 1 + idx + }; +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + Allocator::<&'alloc A>(t, alloc, id) &*& [shared]lifetime_token('alloc) &*& [released]lifetime_token(k) &*& + merged_nodes(t, parent, left.node, parent_height - 1, parent_len - 1, left_len + 1 + right_len_0, + append(take(parent_idx + 1, parent_children), drop(parent_idx + 2, parent_children)), + append(left_children, right_children)); +@*/ +{ + //@ open merge_inputs(t, parent, left.node, right, parent_height, parent_idx, id, k, released, parent_len, left_len, right_len_0, parent_children, left_children, right_children); + //@ open owned_leaf_slots(t, left.node.as_ptr(), left_len); + //@ open leaf_slots(left.node.as_ptr(), left_len, ?lk, ?lv); + let old_left_len = unsafe { (*left.node.as_ptr()).len } as usize; + //@ close leaf_slots(left.node.as_ptr(), left_len, lk, lv); + //@ close owned_leaf_slots(t, left.node.as_ptr(), left_len); + //@ open owned_leaf_slots(t, right.as_ptr(), right_len_0); + //@ open leaf_slots(right.as_ptr(), right_len_0, ?rk, ?rv); + let right_len = unsafe { (*right.as_ptr()).len } as usize; + //@ close leaf_slots(right.as_ptr(), right_len_0, rk, rv); + //@ close owned_leaf_slots(t, right.as_ptr(), right_len_0); + //@ close merge_inputs(t, parent, left.node, right, parent_height, parent_idx, id, k, released, parent_len, left_len, right_len_0, parent_children, left_children, right_children); + assert!(match track_edge_idx { + LeftOrRight::Left(idx) => idx <= old_left_len, + LeftOrRight::Right(idx) => idx <= right_len, + }); + unsafe { merge_nodes/*@::@*/(parent, left.node, right, parent_height, parent_idx, alloc) }; + //@ let pc = append(take(parent_idx + 1, parent_children), drop(parent_idx + 2, parent_children)); + //@ let lc = append(left_children, right_children); + //@ let new_len = left_len + 1 + right_len_0; + //@ open merged_nodes(t, parent, left.node, parent_height - 1, parent_len - 1, new_len, pc, lc); + //@ open owned_leaf_slots(t, left.node.as_ptr(), new_len); + //@ open leaf_slots(left.node.as_ptr(), new_len, ?keys, ?vals); + let edge = unsafe { + finish_merge_tracking__VeriFast_wrapper/*@::@*/(left, old_left_len, track_edge_idx) + }; + //@ close leaf_slots(left.node.as_ptr(), new_len, keys, vals); + //@ close owned_leaf_slots(t, left.node.as_ptr(), new_len); + //@ close merged_nodes(t, parent, left.node, parent_height - 1, parent_len - 1, new_len, pc, lc); + edge +} +// END_MERGE_TRACKED_EDGE + +// Verify the read, separator exchange, and write used by both steal directions. +unsafe fn move_steal_separator( + parent: *mut MaybeUninit, + source: *mut MaybeUninit, + destination: *mut MaybeUninit, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& + move_slice(parent, 1, ?p) &*& head(p).inner() == some(?old) &*& p == [MaybeUninit::new(old)] &*& + move_slice(source, 1, ?s) &*& head(s).inner() == some(?donated) &*& s == [MaybeUninit::new(donated)] &*& + move_slice(destination, 1, _) &*& .own(t, old) &*& .own(t, donated); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& + move_slice(parent, 1, [MaybeUninit::new(donated)]) &*& + move_slice(source, 1, [MaybeUninit::new(donated)]) &*& + move_slice(destination, 1, [MaybeUninit::new(old)]) &*& .own(t, old) &*& .own(t, donated); +@*/ +//@ on_unwind_ens false; +{ + //@ open move_slice(source, 1, [MaybeUninit::new(donated)]); + //@ open array(source, 1, [MaybeUninit::new(donated)]); + let entry = unsafe { read_promoted(source) }; + //@ close array(source, 1, [MaybeUninit::new(donated)]); + //@ close move_slice(source, 1, [MaybeUninit::new(donated)]); + //@ open move_slice(parent, 1, [MaybeUninit::new(old)]); + //@ open array(parent, 1, [MaybeUninit::new(old)]); + //@ open_MaybeUninit(parent); + let saved = unsafe { std::mem::replace(&mut *(parent as *mut T), entry) }; + //@ close_MaybeUninit(parent); + //@ close array(parent, 1, [MaybeUninit::new(donated)]); + //@ close move_slice(parent, 1, [MaybeUninit::new(donated)]); + //@ open move_slice(destination, 1, _); + //@ open array(destination, 1, _); + //@ open array(destination + 1, 0, _); + //@ close array(destination + 1, 0, nil); + unsafe { (*destination).write(saved) }; + //@ close array(destination, 1, [MaybeUninit::new(old)]); + //@ close move_slice(destination, 1, [MaybeUninit::new(old)]); +} + +unsafe fn steal_left_field( + parent: *mut MaybeUninit, + left: *mut MaybeUninit, + right: *mut MaybeUninit, + old_left_len: usize, + old_right_len: usize, + count: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& + 0 < count &*& count <= old_left_len &*& old_left_len <= CAPACITY &*& + 0 <= old_right_len &*& old_right_len + count <= CAPACITY &*& + move_slice(parent, 1, ?p) &*& move_slice(left, old_left_len, ?l) &*& + move_slice(right, old_right_len + count, ?r) &*& + slot_owners(t, p) &*& slot_owners(t, l) &*& slot_owners(t, take(old_right_len, r)); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& + move_slice(parent, 1, ?new_p) &*& move_slice(left, old_left_len, l) &*& + move_slice(right, old_right_len + count, ?new_r) &*& + slot_owners(t, new_p) &*& slot_owners(t, take(old_left_len - count, l)) &*& slot_owners(t, new_r); +@*/ +//@ on_unwind_ens false; +{ + let new_left_len = old_left_len - count; + let new_right_len = old_right_len + count; + //@ move_slice_length(left, old_left_len); + //@ move_slice_length(parent, 1); + //@ move_slice_length(right, new_right_len); + //@ split_slot_owners(t, l, new_left_len); + //@ let donated = nth(new_left_len, l); + //@ let remaining = drop(new_left_len + 1, l); + //@ drop_n_plus_one(new_left_len, l); + //@ open slot_owners(t, drop(new_left_len, l)); + //@ split_move_slice(left, old_left_len, new_left_len); + //@ split_move_slice(left + new_left_len, count, 1); + //@ drop_twice(1, new_left_len, l); + //@ drop_n_plus_one(0, p); + //@ length_drop(1, p); + //@ empty_list_if_zero(drop(1, p)); + //@ open slot_owners(t, p); + unsafe { + slice_shr(move_slice_mut(right, new_right_len), count); + //@ split_move_slice(right, new_right_len, count); + //@ length_take(count, r); + //@ take_append_l(count, take(count, r), take(old_right_len, r)); + //@ take_length(take(count, r)); + //@ drop_append(count, take(count, r), take(old_right_len, r)); + //@ split_move_slice(right, count, count - 1); + move_to_slice( + move_slice_mut(left.add(new_left_len + 1), old_left_len - (new_left_len + 1)), + move_slice_mut(right, count - 1), + ); + move_steal_separator(parent, left.add(new_left_len), right.add(count - 1)); + //@ join_move_slices(left + new_left_len, 1, count - 1); + //@ join_move_slices(left, new_left_len, count); + //@ join_move_slices(right, count - 1, 1); + //@ join_move_slices(right, count, old_right_len); + //@ close slot_owners(t, [donated]); + //@ close slot_owners::(t, nil); + //@ close slot_owners(t, p); + //@ join_slot_owners(t, remaining, p); + //@ join_slot_owners(t, append(remaining, p), take(old_right_len, r)); + } +} + +unsafe fn steal_right_field( + parent: *mut MaybeUninit, + left: *mut MaybeUninit, + right: *mut MaybeUninit, + old_left_len: usize, + old_right_len: usize, + count: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& + 0 < count &*& count <= old_right_len &*& old_right_len <= CAPACITY &*& + 0 <= old_left_len &*& old_left_len + count <= CAPACITY &*& + move_slice(parent, 1, ?p) &*& move_slice(left, old_left_len + count, ?l) &*& + move_slice(right, old_right_len, ?r) &*& + slot_owners(t, p) &*& slot_owners(t, take(old_left_len, l)) &*& slot_owners(t, r); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& + move_slice(parent, 1, ?new_p) &*& move_slice(left, old_left_len + count, ?new_l) &*& + move_slice(right, old_right_len, ?new_r) &*& + slot_owners(t, new_p) &*& slot_owners(t, new_l) &*& slot_owners(t, take(old_right_len - count, new_r)); +@*/ +//@ on_unwind_ens false; +{ + let new_left_len = old_left_len + count; + //@ move_slice_length(right, old_right_len); + //@ move_slice_length(parent, 1); + //@ move_slice_length(left, new_left_len); + //@ split_slot_owners(t, r, count - 1); + //@ let donated = nth(count - 1, r); + //@ drop_n_plus_one(count - 1, r); + //@ open slot_owners(t, drop(count - 1, r)); + //@ split_move_slice(right, old_right_len, count - 1); + //@ split_move_slice(right + count - 1, old_right_len - count + 1, 1); + //@ split_move_slice(left, new_left_len, old_left_len); + //@ split_move_slice(left + old_left_len, count, 1); + //@ drop_n_plus_one(0, p); + //@ length_drop(1, p); + //@ empty_list_if_zero(drop(1, p)); + //@ open slot_owners(t, p); + unsafe { + move_steal_separator(parent, right.add(count - 1), left.add(old_left_len)); + move_to_slice( + move_slice_mut(right, count - 1), + move_slice_mut(left.add(old_left_len + 1), new_left_len - (old_left_len + 1)), + ); + //@ join_move_slices(left + old_left_len, 1, count - 1); + //@ join_move_slices(left, old_left_len, count); + //@ join_move_slices(right + count - 1, 1, old_right_len - count); + //@ join_move_slices(right, count - 1, old_right_len - count + 1); + //@ append_take_drop_n(drop(count - 1, r), 1); + //@ append_take_drop_n(r, count - 1); + slice_shl(move_slice_mut(right, old_right_len), count); + //@ length_drop(count, r); + //@ take_append_l(old_right_len - count, drop(count, r), drop(old_right_len - count, r)); + //@ take_length(drop(count, r)); + //@ close slot_owners(t, [donated]); + //@ close slot_owners::(t, nil); + //@ close slot_owners(t, p); + //@ join_slot_owners(t, p, take(count - 1, r)); + //@ join_slot_owners(t, take(old_left_len, l), append(p, take(count - 1, r))); + } +} + +/*@ +lem join_child_headers(left: list>, right: list>) + req child_headers(left) &*& child_headers(right); + ens child_headers(append(left, right)); +{ + open child_headers(left); + match left { + nil => {} + cons(child, rest) => { + join_child_headers(rest, right); + close child_headers(append(left, right)); + } + } +} +@*/ + +unsafe fn steal_left_edges( + left: NonNull>, + right: NonNull>, + old_left_len: usize, + old_right_len: usize, + count: usize, + height: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + balancing_edges(left, ?left_children, ?left_slots) &*& balancing_edges(right, ?right_children, ?right_slots) &*& + length(left_children) == old_left_len + 1 &*& length(right_children) == old_right_len + 1 &*& + (*right.as_ptr()).data.len |-> ((old_right_len + count) as u16) &*& 0 < height &*& + 0 < count &*& count <= old_left_len &*& 0 <= old_right_len &*& old_right_len + count <= CAPACITY; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + (*right.as_ptr()).data.len |-> ((old_right_len + count) as u16) &*& + balancing_edges(left, take(old_left_len - count + 1, left_children), left_slots) &*& + balancing_edges(right, append(drop(old_left_len - count + 1, left_children), right_children), _); +@*/ +//@ on_unwind_ens false; +{ + let new_left_len = old_left_len - count; + let new_right_len = old_right_len + count; + //@ open balancing_edges(left, left_children, left_slots); + //@ open balancing_edges(right, right_children, right_slots); + let left_base = unsafe { (&raw mut (*left.as_ptr()).edges) as *mut MaybeUninit> }; + let right_base = unsafe { (&raw mut (*right.as_ptr()).edges) as *mut MaybeUninit> }; + //@ own_move_array(left_base, CAPACITY + 1); + //@ own_move_array(right_base, CAPACITY + 1); + //@ split_move_slice(left_base, CAPACITY + 1, old_left_len + 1); + //@ split_move_slice(left_base, old_left_len + 1, new_left_len + 1); + //@ split_move_slice(right_base, CAPACITY + 1, new_right_len + 1); + //@ let kept = take(new_left_len + 1, left_children); + //@ let moved = drop(new_left_len + 1, left_children); + //@ initialized_edge_split(left_children, new_left_len + 1); + //@ initialized_edge_count(kept); + //@ initialized_edge_count(moved); + //@ initialized_edge_count(right_children); + //@ length_take(new_left_len + 1, left_children); + //@ length_drop(new_left_len + 1, left_children); + //@ split_linked_headers(left_children, left, 0, new_left_len + 1); + //@ forget_link_indices(moved, left, new_left_len + 1); + //@ forget_link_indices(right_children, right, 0); + //@ join_child_headers(moved, right_children); + //@ let after = append(moved, right_children); + //@ initialized_edges_append(moved, right_children); + //@ let right_before = take(new_right_len + 1, right_slots); + unsafe { + slice_shr(move_slice_mut(right_base, new_right_len + 1), count); + //@ take_twice(right_slots, old_right_len + 1, new_right_len + 1); + //@ split_move_slice(right_base, new_right_len + 1, count); + //@ length_take(count, right_before); + //@ take_append_l(count, take(count, right_before), initialized_edges(right_children)); + //@ take_length(take(count, right_before)); + //@ drop_append(count, take(count, right_before), initialized_edges(right_children)); + move_to_slice( + move_slice_mut(left_base.add(new_left_len + 1), old_left_len + 1 - (new_left_len + 1)), + move_slice_mut(right_base, count), + ); + //@ join_move_slices(right_base, count, old_right_len + 1); + //@ join_move_slices(right_base, new_right_len + 1, CAPACITY - new_right_len); + //@ open move_slice(right_base, CAPACITY + 1, ?full); + let mut right_node = NodeRef::, K, V, marker::Internal> { + height, node: right.cast(), _marker: PhantomData, + }; + //@ std::ptr::NonNull_new_as_ptr(right_node.node); + //@ close exists(right); + //@ close exists(pair(nil::>>, drop(new_right_len + 1, right_slots))); + //@ initialized_edge_count(after); + right_node.relink_range(0..new_right_len + 1); + } + //@ let old_left = take(old_left_len + 1, left_slots); + //@ append_take_drop_n(old_left, new_left_len + 1); + //@ append_take_drop_n(left_slots, old_left_len + 1); + //@ join_move_slices(left_base, new_left_len + 1, count); + //@ join_move_slices(left_base, old_left_len + 1, CAPACITY - old_left_len); + //@ open move_slice(left_base, CAPACITY + 1, left_slots); + //@ take_twice(left_slots, new_left_len + 1, old_left_len + 1); + //@ close balancing_edges(left, kept, left_slots); + //@ assert (*right.as_ptr()).edges[..CAPACITY + 1] |-> ?packed; + //@ initialized_edge_count(after); + //@ take_append_l(new_right_len + 1, initialized_edges(after), drop(new_right_len + 1, right_slots)); + //@ take_length(initialized_edges(after)); + //@ close balancing_edges(right, after, packed); +} + +unsafe fn steal_right_edges( + left: NonNull>, + right: NonNull>, + old_left_len: usize, + old_right_len: usize, + count: usize, + height: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + balancing_edges(left, ?left_children, ?left_slots) &*& balancing_edges(right, ?right_children, ?right_slots) &*& + length(left_children) == old_left_len + 1 &*& length(right_children) == old_right_len + 1 &*& + (*left.as_ptr()).data.len |-> ((old_left_len + count) as u16) &*& + (*right.as_ptr()).data.len |-> ((old_right_len - count) as u16) &*& 0 < height &*& + 0 < count &*& count <= old_right_len &*& 0 <= old_left_len &*& old_left_len + count <= CAPACITY; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + (*left.as_ptr()).data.len |-> ((old_left_len + count) as u16) &*& + (*right.as_ptr()).data.len |-> ((old_right_len - count) as u16) &*& + balancing_edges(left, append(left_children, take(count, right_children)), _) &*& + balancing_edges(right, drop(count, right_children), _); +@*/ +//@ on_unwind_ens false; +{ + let new_left_len = old_left_len + count; + let new_right_len = old_right_len - count; + //@ open balancing_edges(left, left_children, left_slots); + //@ open balancing_edges(right, right_children, right_slots); + let left_base = unsafe { (&raw mut (*left.as_ptr()).edges) as *mut MaybeUninit> }; + let right_base = unsafe { (&raw mut (*right.as_ptr()).edges) as *mut MaybeUninit> }; + //@ own_move_array(left_base, CAPACITY + 1); + //@ own_move_array(right_base, CAPACITY + 1); + //@ split_move_slice(left_base, CAPACITY + 1, new_left_len + 1); + //@ split_move_slice(left_base, new_left_len + 1, old_left_len + 1); + //@ split_move_slice(right_base, CAPACITY + 1, old_right_len + 1); + //@ split_move_slice(right_base, old_right_len + 1, count); + //@ let moved = take(count, right_children); + //@ let kept = drop(count, right_children); + //@ let right_before = initialized_edges(right_children); + //@ let inactive = drop(new_right_len + 1, right_before); + //@ initialized_edge_split(right_children, count); + //@ initialized_edge_count(left_children); + //@ initialized_edge_count(moved); + //@ initialized_edge_count(kept); + //@ length_take(count, right_children); + //@ length_drop(count, right_children); + //@ split_linked_headers(right_children, right, 0, count); + //@ forget_link_indices(kept, right, count); + //@ forget_link_indices(moved, right, 0); + unsafe { + move_to_slice( + move_slice_mut(right_base, count), + move_slice_mut(left_base.add(old_left_len + 1), new_left_len + 1 - (old_left_len + 1)), + ); + //@ join_move_slices(right_base, count, new_right_len + 1); + //@ append_take_drop_n(right_before, count); + slice_shl(move_slice_mut(right_base, old_right_len + 1), count); + //@ split_move_slice(right_base, old_right_len + 1, new_right_len + 1); + //@ take_append_l(new_right_len + 1, initialized_edges(kept), inactive); + //@ take_length(initialized_edges(kept)); + //@ join_move_slices(left_base, old_left_len + 1, count); + //@ join_move_slices(left_base, new_left_len + 1, CAPACITY - new_left_len); + //@ open move_slice(left_base, CAPACITY + 1, _); + //@ join_move_slices(right_base, new_right_len + 1, count); + //@ join_move_slices(right_base, old_right_len + 1, CAPACITY - old_right_len); + //@ open move_slice(right_base, CAPACITY + 1, _); + let mut left_node = NodeRef::, K, V, marker::Internal> { + height, node: left.cast(), _marker: PhantomData, + }; + let mut right_node = NodeRef::, K, V, marker::Internal> { + height, node: right.cast(), _marker: PhantomData, + }; + //@ std::ptr::NonNull_new_as_ptr(left_node.node); + //@ std::ptr::NonNull_new_as_ptr(right_node.node); + //@ take_twice(left_slots, old_left_len + 1, new_left_len + 1); + //@ append_assoc(initialized_edges(left_children), initialized_edges(moved), drop(new_left_len + 1, left_slots)); + //@ close exists(left); + //@ close exists(pair(initialized_edges(left_children), drop(new_left_len + 1, left_slots))); + left_node.relink_range(old_left_len + 1..new_left_len + 1); + //@ close exists(right); + //@ close exists(pair(nil::>>, append(inactive, drop(old_right_len + 1, right_slots)))); + //@ append_assoc(initialized_edges(kept), inactive, drop(old_right_len + 1, right_slots)); + right_node.relink_range(0..new_right_len + 1); + } + //@ let after_left = append(left_children, moved); + //@ initialized_edges_append(left_children, moved); + //@ initialized_edge_count(after_left); + //@ take_twice(left_slots, old_left_len + 1, new_left_len + 1); + //@ join_linked_headers(left_children, moved, left, 0); + //@ assert (*left.as_ptr()).edges[..CAPACITY + 1] |-> ?packed_left; + //@ take_append_l(new_left_len + 1, initialized_edges(after_left), drop(new_left_len + 1, left_slots)); + //@ take_length(initialized_edges(after_left)); + //@ close balancing_edges(left, after_left, packed_left); + //@ assert (*right.as_ptr()).edges[..CAPACITY + 1] |-> ?packed_right; + //@ take_append_l(new_right_len + 1, initialized_edges(kept), inactive); + //@ take_append_l(new_right_len + 1, append(initialized_edges(kept), inactive), drop(old_right_len + 1, right_slots)); + //@ close balancing_edges(right, kept, packed_right); +} + +/*@ +fix steal_len(receives: bool, old_len: usize, count: usize) -> usize { + if receives { old_len + count } else { old_len - count } +} +@*/ + +unsafe fn steal_field( + parent: *mut MaybeUninit, + left: *mut MaybeUninit, + right: *mut MaybeUninit, + parent_idx: usize, + old_left_len: usize, + old_right_len: usize, + count: usize, + from_left: bool, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& exists::(?parent_len) &*& + 0 <= parent_idx &*& parent_idx < parent_len &*& parent_len <= CAPACITY &*& + 0 <= old_left_len &*& old_left_len <= CAPACITY &*& 0 <= old_right_len &*& old_right_len <= CAPACITY &*& + 0 < count &*& + (if from_left { count <= old_left_len && old_right_len + count <= CAPACITY } + else { count <= old_right_len && old_left_len + count <= CAPACITY }) == true &*& + parent[..CAPACITY] |-> ?p &*& left[..CAPACITY] |-> ?l &*& right[..CAPACITY] |-> ?r &*& + slot_owners(t, take(parent_len, p)) &*& slot_owners(t, take(old_left_len, l)) &*& slot_owners(t, take(old_right_len, r)); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& + parent[..CAPACITY] |-> ?new_p &*& left[..CAPACITY] |-> ?new_l &*& right[..CAPACITY] |-> ?new_r &*& + slot_owners(t, take(parent_len, new_p)) &*& + slot_owners(t, take(steal_len(!from_left, old_left_len, count), new_l)) &*& + slot_owners(t, take(steal_len(from_left, old_right_len, count), new_r)); +@*/ +//@ on_unwind_ens false; +{ + //@ open exists(parent_len); + //@ let left_view = if from_left { old_left_len } else { old_left_len + count }; + //@ let right_view = if from_left { old_right_len + count } else { old_right_len }; + //@ own_move_array(parent, CAPACITY); + //@ own_move_array(left, CAPACITY); + //@ own_move_array(right, CAPACITY); + //@ split_move_slice(parent, CAPACITY, parent_idx); + //@ split_move_slice(parent + parent_idx, CAPACITY - parent_idx, 1); + //@ split_move_slice(left, CAPACITY, left_view); + //@ split_move_slice(right, CAPACITY, right_view); + //@ take_twice(l, old_left_len, left_view); + //@ take_twice(r, old_right_len, right_view); + //@ let active = take(parent_len, p); + //@ length_take(parent_len, p); + //@ split_slot_owners(t, active, parent_idx); + //@ length_drop(parent_idx, active); + //@ split_slot_owners(t, drop(parent_idx, active), 1); + //@ take_twice(p, parent_idx, parent_len); + //@ take_after_drop(p, parent_idx, parent_len - parent_idx); + //@ take_twice(drop(parent_idx, p), 1, parent_len - parent_idx); + let separator = unsafe { parent.add(parent_idx) }; + if from_left { + unsafe { steal_left_field(separator, left, right, old_left_len, old_right_len, count) }; + } else { + unsafe { steal_right_field(separator, left, right, old_left_len, old_right_len, count) }; + } + //@ assert move_slice(separator, 1, ?new_separator); + //@ assert move_slice(left, left_view, ?moved_left); + //@ assert move_slice(right, right_view, ?moved_right); + //@ move_slice_length(separator, 1); + //@ move_slice_length(left, left_view); + //@ move_slice_length(right, right_view); + //@ join_move_slices(parent, parent_idx, 1); + //@ join_move_slices(parent, parent_idx + 1, CAPACITY - parent_idx - 1); + //@ join_move_slices(left, left_view, CAPACITY - left_view); + //@ join_move_slices(right, right_view, CAPACITY - right_view); + //@ take_append_l(steal_len(!from_left, old_left_len, count), moved_left, drop(left_view, l)); + //@ take_append_l(steal_len(from_left, old_right_len, count), moved_right, drop(right_view, r)); + //@ drop_twice(1, parent_idx, p); + //@ drop_twice(1, parent_idx, active); + //@ take_after_drop(p, parent_idx + 1, parent_len - parent_idx - 1); + //@ length_take(parent_idx, p); + //@ take_append(parent_len, append(take(parent_idx, p), new_separator), drop(parent_idx + 1, p)); + //@ join_slot_owners(t, take(parent_idx, p), new_separator); + //@ join_slot_owners(t, append(take(parent_idx, p), new_separator), drop(parent_idx + 1, active)); + //@ open move_slice(parent, CAPACITY, _); + //@ open move_slice(left, CAPACITY, _); + //@ open move_slice(right, CAPACITY, _); +} + +unsafe fn bulk_steal_nodes( + parent: NonNull>, + left: NonNull>, + right: NonNull>, + child_height: usize, + parent_idx: usize, + count: usize, + from_left: bool, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + owned_leaf_slots(t, parent.as_ptr(), ?parent_len) &*& 0 <= parent_idx &*& parent_idx < parent_len &*& + owned_leaf_slots(t, left.as_ptr(), ?left_len) &*& owned_leaf_slots(t, right.as_ptr(), ?right_len) &*& + left.as_ptr() as usize != 0 &*& right.as_ptr() as usize != 0 &*& 0 <= child_height &*& child_height <= usize::MAX &*& + balancing_child_edges(left, child_height, left_len, ?lc) &*& balancing_child_edges(right, child_height, right_len, ?rc) &*& + 0 < count &*& + (if from_left { count <= left_len && right_len + count <= CAPACITY } + else { count <= right_len && left_len + count <= CAPACITY }) == true; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + owned_leaf_slots(t, parent.as_ptr(), parent_len) &*& + owned_leaf_slots(t, left.as_ptr(), steal_len(!from_left, left_len, count)) &*& + owned_leaf_slots(t, right.as_ptr(), steal_len(from_left, right_len, count)) &*& + balancing_child_edges(left, child_height, steal_len(!from_left, left_len, count), + if from_left { take(left_len - count + 1, lc) } else { append(lc, take(count, rc)) }) &*& + balancing_child_edges(right, child_height, steal_len(from_left, right_len, count), + if from_left { append(drop(left_len - count + 1, lc), rc) } else { drop(count, rc) }); +@*/ +//@ on_unwind_ens false; +{ + assert!(count > 0); + //@ open owned_leaf_slots(t, left.as_ptr(), left_len); + //@ open leaf_slots(left.as_ptr(), left_len, ?lk, ?lv); + let left_ptr = left.as_ptr(); + let old_left_len = unsafe { (*left_ptr).len } as usize; + //@ open owned_leaf_slots(t, right.as_ptr(), right_len); + //@ open leaf_slots(right.as_ptr(), right_len, ?rk, ?rv); + let right_ptr = right.as_ptr(); + let old_right_len = unsafe { (*right_ptr).len } as usize; + let new_left_len; + let new_right_len; + if from_left { + assert!(old_right_len + count <= CAPACITY); + assert!(old_left_len >= count); + new_left_len = old_left_len - count; + new_right_len = old_right_len + count; + } else { + assert!(old_left_len + count <= CAPACITY); + assert!(old_right_len >= count); + new_left_len = old_left_len + count; + new_right_len = old_right_len - count; + } + //@ open owned_leaf_slots(t, parent.as_ptr(), parent_len); + //@ open leaf_slots(parent.as_ptr(), parent_len, ?pk, ?pv); + let parent_ptr = parent.as_ptr(); + unsafe { + (*left_ptr).len = new_left_len as u16; + (*right_ptr).len = new_right_len as u16; + //@ close exists(parent_len); + steal_field( + (&raw mut (*parent_ptr).keys) as *mut MaybeUninit, + (&raw mut (*left_ptr).keys) as *mut MaybeUninit, + (&raw mut (*right_ptr).keys) as *mut MaybeUninit, + parent_idx, old_left_len, old_right_len, count, from_left, + ); + //@ close exists(parent_len); + steal_field( + (&raw mut (*parent_ptr).vals) as *mut MaybeUninit, + (&raw mut (*left_ptr).vals) as *mut MaybeUninit, + (&raw mut (*right_ptr).vals) as *mut MaybeUninit, + parent_idx, old_left_len, old_right_len, count, from_left, + ); + //@ close leaf_slots(parent_ptr, parent_len, _, _); + //@ close owned_leaf_slots(t, parent_ptr, parent_len); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ close leaf_slots(right_ptr, new_right_len, _, _); + //@ close owned_leaf_slots(t, right_ptr, new_right_len); + //@ open balancing_child_edges(left, child_height, left_len, lc); + //@ open balancing_child_edges(right, child_height, right_len, rc); + let left_node = NodeRef::, K, V, marker::LeafOrInternal> { + height: child_height, node: left, _marker: PhantomData, + }; + let right_node = NodeRef::, K, V, marker::LeafOrInternal> { + height: child_height, node: right, _marker: PhantomData, + }; + match (left_node.force(), right_node.force()) { + (ForceResult::Internal(left), ForceResult::Internal(right)) => { + let left_internal = left.node.cast::>(); + let right_internal = right.node.cast::>(); + //@ std::ptr::NonNull_new_as_ptr(left_internal); + //@ std::ptr::NonNull_new_as_ptr(right_internal); + //@ assert &(*right_internal.as_ptr()).data == right_ptr; + //@ open owned_leaf_slots(t, right_ptr, new_right_len); + //@ open leaf_slots(right_ptr, new_right_len, _, _); + if from_left { + steal_left_edges(left_internal, right_internal, old_left_len, old_right_len, count, child_height); + //@ length_take(new_left_len + 1, lc); + //@ length_drop(new_left_len + 1, lc); + } else { + //@ assert &(*left_internal.as_ptr()).data == left_ptr; + //@ open owned_leaf_slots(t, left_ptr, new_left_len); + //@ open leaf_slots(left_ptr, new_left_len, _, _); + steal_right_edges(left_internal, right_internal, old_left_len, old_right_len, count, child_height); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ length_take(count, rc); + //@ length_drop(count, rc); + } + //@ close leaf_slots(right_ptr, new_right_len, _, _); + //@ close owned_leaf_slots(t, right_ptr, new_right_len); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} + _ => unreachable!(), + } + //@ close balancing_child_edges(left, child_height, new_left_len, if from_left { take(new_left_len + 1, lc) } else { append(lc, take(count, rc)) }); + //@ close balancing_child_edges(right, child_height, new_right_len, if from_left { append(drop(new_left_len + 1, lc), rc) } else { drop(count, rc) }); + } +} + +// BEGIN_FINISH_STEAL +unsafe fn finish_steal_left__VeriFast_wrapper<'tree, K, V>( + child: NodeRef, K, V, marker::LeafOrInternal>, + tracked_idx: usize, +) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> +/*@ +req (*child.node.as_ptr()).len |-> ?len &*& 0 <= tracked_idx &*& + 1 + tracked_idx <= len; +@*/ +/*@ +ens (*child.node.as_ptr()).len |-> len &*& result.node == child &*& + result.idx == 1 + tracked_idx; +@*/ +//@ on_unwind_ens false; +{ + unsafe { + Handle::, K, V, marker::LeafOrInternal>, marker::Edge>::new_edge(child, 1 + tracked_idx) + } +} + +unsafe fn finish_steal_right__VeriFast_wrapper<'tree, K, V>( + child: NodeRef, K, V, marker::LeafOrInternal>, + tracked_idx: usize, +) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> +/*@ +req (*child.node.as_ptr()).len |-> ?len &*& 0 <= tracked_idx &*& + tracked_idx <= len; +@*/ +/*@ +ens (*child.node.as_ptr()).len |-> len &*& result.node == child &*& + result.idx == tracked_idx; +@*/ +//@ on_unwind_ens false; +{ + unsafe { + Handle::, K, V, marker::LeafOrInternal>, marker::Edge>::new_edge(child, tracked_idx) + } +} +// END_FINISH_STEAL + +unsafe fn steal_one<'tree, K, V>( + parent: NonNull>, + left: NodeRef, K, V, marker::LeafOrInternal>, + right: NodeRef, K, V, marker::LeafOrInternal>, + parent_idx: usize, + tracked_idx: usize, + from_left: bool, +) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + owned_leaf_slots(t, parent.as_ptr(), ?parent_len) &*& 0 <= parent_idx &*& parent_idx < parent_len &*& + owned_leaf_slots(t, left.node.as_ptr(), ?left_len) &*& owned_leaf_slots(t, right.node.as_ptr(), ?right_len) &*& + left.node.as_ptr() as usize != 0 &*& right.node.as_ptr() as usize != 0 &*& + left.height == right.height &*& 0 <= left.height &*& left.height <= usize::MAX &*& + balancing_child_edges(left.node, left.height, left_len, ?lc) &*& balancing_child_edges(right.node, right.height, right_len, ?rc) &*& + 0 <= tracked_idx &*& + (if from_left { 1 <= left_len && right_len < CAPACITY && tracked_idx <= right_len } + else { 1 <= right_len && left_len < CAPACITY && tracked_idx <= left_len }) == true; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + owned_leaf_slots(t, parent.as_ptr(), parent_len) &*& + owned_leaf_slots(t, left.node.as_ptr(), steal_len(!from_left, left_len, 1)) &*& + owned_leaf_slots(t, right.node.as_ptr(), steal_len(from_left, right_len, 1)) &*& + balancing_child_edges(left.node, left.height, steal_len(!from_left, left_len, 1), + if from_left { take(left_len, lc) } else { append(lc, take(1, rc)) }) &*& + balancing_child_edges(right.node, right.height, steal_len(from_left, right_len, 1), + if from_left { append(drop(left_len, lc), rc) } else { drop(1, rc) }) &*& + result.node == (if from_left { right } else { left }) &*& + result.idx == tracked_idx + (if from_left { 1 } else { 0 }); +@*/ +//@ on_unwind_ens false; +{ + unsafe { bulk_steal_nodes(parent, left.node, right.node, left.height, parent_idx, 1, from_left) }; + let child = if from_left { right } else { left }; + //@ let child_len = if from_left { right_len + 1 } else { left_len + 1 }; + //@ open owned_leaf_slots(t, child.node.as_ptr(), child_len); + //@ open leaf_slots(child.node.as_ptr(), child_len, ?keys, ?vals); + let edge = if from_left { + unsafe { finish_steal_left__VeriFast_wrapper/*@::@*/(child, tracked_idx) } + } else { + unsafe { finish_steal_right__VeriFast_wrapper/*@::@*/(child, tracked_idx) } + }; + //@ close leaf_slots(child.node.as_ptr(), child_len, keys, vals); + //@ close owned_leaf_slots(t, child.node.as_ptr(), child_len); + edge +} + + +enum ForceResult { + Leaf(Leaf), + Internal(Internal), +} + +impl NodeRef { + unsafe fn force( + self, + ) -> ForceResult< + NodeRef, + NodeRef, + > + //@ req 0 <= self.height; + /*@ + ens match result { + ForceResult::Leaf(leaf) => self.height == 0 &*& leaf.height == self.height &*& leaf.node == self.node, + ForceResult::Internal(internal) => self.height > 0 &*& internal.height == self.height &*& internal.node == self.node + }; + @*/ + //@ on_unwind_ens false; + { + if self.height == 0 { + ForceResult::Leaf(NodeRef { + height: self.height, + node: self.node, + _marker: PhantomData, + }) + } else { + ForceResult::Internal(NodeRef { + height: self.height, + node: self.node, + _marker: PhantomData, + }) + } + } +} + + +// BEGIN_DROP_VALUE +unsafe fn drop_slot_production<'slot, T>(slot: &'slot mut MaybeUninit) +/*@ +req thread_token(?t) &*& type_interp::() &*& *slot |-> ?bits &*& + bits.inner() == some(?value) &*& .own(t, value); +@*/ +//@ ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +{ + let ptr = slot.as_mut_ptr(); + //@ open_MaybeUninit(slot); + unsafe { std::ptr::drop_in_place(ptr) } +} + +struct Dropper<'a, T>(&'a mut MaybeUninit); + +impl<'a, T> Dropper<'a, T> { + unsafe fn drop_value_guard(&mut self) + /*@ + req thread_token(?t) &*& type_interp::() &*& *self |-> ?guard &*& + *guard.0 |-> ?bits &*& bits.inner() == some(?value) &*& .own(t, value); + @*/ + //@ ens thread_token(t) &*& type_interp::() &*& *self |-> guard &*& *(guard.0 as *T) |-> _; + //@ on_unwind_ens thread_token(t) &*& type_interp::() &*& *self |-> guard &*& *(guard.0 as *T) |-> _; + { + //@ open_points_to(self); + let slot = &mut *self.0; + //@ close_points_to(self); + unsafe { drop_slot_production(slot) }; + } +} +// END_DROP_VALUE + +// The storage remains reusable after either exit from the destructor. +unsafe fn drop_initialized_slot(slot: *mut MaybeUninit) +/*@ +req thread_token(?t) &*& type_interp::() &*& *slot |-> ?bits &*& + bits.inner() == some(?value) &*& .own(t, value); +@*/ +//@ ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +{ + unsafe { drop_slot_production(&mut *slot) } +} + +unsafe fn drop_guarded_value(slot: *mut MaybeUninit) +/*@ +req thread_token(?t) &*& type_interp::() &*& *slot |-> ?bits &*& + bits.inner() == some(?value) &*& .own(t, value); +@*/ +//@ ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& *(slot as *T) |-> _; +{ + let mut guard = Dropper(unsafe { &mut *slot }); + //@ close_points_to(&mut guard); + unsafe { guard.drop_value_guard() }; + //@ open_points_to(&mut guard); +} + +unsafe fn drop_pair(key: *mut MaybeUninit, value: *mut MaybeUninit) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *key |-> ?key_bits &*& key_bits.inner() == some(?k) &*& .own(t, k) &*& + *value |-> ?value_bits &*& value_bits.inner() == some(?v) &*& .own(t, v); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *(key as *K) |-> _ &*& *(value as *V) |-> _; +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *(key as *K) |-> _ &*& exists::(?value_pending) &*& + if value_pending { *value |-> value_bits &*& .own(t, v) } + else { *(value as *V) |-> _ }; +@*/ +{ + //@ close exists::(true); + unsafe { drop_initialized_slot(key) }; + //@ open exists::(true); + //@ close exists::(false); + unsafe { drop_guarded_value(value) }; + //@ open exists::(false); +} + + +unsafe fn maybe_uninit_storage_ptr(storage: &mut MaybeUninit) -> *mut T +//@ req true; +//@ ens result == storage as *mut T; +//@ on_unwind_ens false; +{ + storage as *mut _ as *mut T +} + +impl NodeRef { + unsafe fn forget_type(self) -> NodeRef + //@ req true; + /*@ + ens result.node == self.node &*& result.height == self.height; + @*/ + //@ on_unwind_ens false; + { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +impl NodeRef { + unsafe fn forget_type(self) -> NodeRef + //@ req true; + /*@ + ens result.node == self.node &*& result.height == self.height; + @*/ + //@ on_unwind_ens false; + { + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +impl<'a, K, V> SplitResult<'a, K, V, marker::Leaf> { + unsafe fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> + //@ req true; + /*@ + ens result.left.node == self.left.node &*& result.left.height == self.left.height &*& + result.right.node == self.right.node &*& result.right.height == self.right.height &*& + result.kv == self.kv; + @*/ + //@ on_unwind_ens false; + { + //@ open_points_to(&self); + let rebuilt = unsafe { SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() } }; + //@ close_points_to(&self, 1/2); + rebuilt + } +} + +impl<'a, K, V> SplitResult<'a, K, V, marker::Internal> { + unsafe fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> + //@ req true; + /*@ + ens result.left.node == self.left.node &*& result.left.height == self.left.height &*& + result.right.node == self.right.node &*& result.right.height == self.right.height &*& + result.kv == self.kv; + @*/ + //@ on_unwind_ens false; + { + //@ open_points_to(&self); + let rebuilt = unsafe { SplitResult { left: self.left.forget_type(), kv: self.kv, right: self.right.forget_type() } }; + //@ close_points_to(&self, 1/2); + rebuilt + } +} + +unsafe fn propagate_split_for_root<'tree, 'slot, K: 'tree, V: 'tree, A: AllocatorClone>( + initial_split: SplitResult<'tree,K,V,marker::LeafOrInternal>, + inserted: Handle,marker::KV>, + alloc: &A, + root_slot: &'slot mut DormantMutRef<'tree, Option>>, + root_allocator: &'slot mut A, +) -> Handle,K,V,marker::Leaf>,marker::KV> +/*@ +req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + [_]allocator_clone_bound::() &*& + [_]std::alloc::Allocator_share::(?alloc_lifetime,t,alloc,?alloc_id) &*& + [_]frac_borrow(alloc_lifetime, ref_initialized_(alloc)) &*& [?qa]lifetime_token(alloc_lifetime) &*& + exists::(?k) &*& [?available]lifetime_token(k) &*& lifetime_inclusion(k,alloc_id.lft) == true &*& + exists::<(NonNull>, NonNull>)>(?leaf_nodes) &*& + ancestors(initial_split.left.node.as_ptr(),?path,?root) &*& route_frames(t,path) &*& + (*root).parent_idx |-> ?root_index &*& detached_child(initial_split.right.node.as_ptr()) &*& + *root_allocator |-> ?root_alloc &*& Allocator::(t,root_alloc,alloc_id) &*& + *root_slot |-> ?sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(?old_root) &*& old_root.node.as_ptr() == root &*& old_root.height == length(path) &*& + initial_split.left.node == leaf_nodes.0 &*& initial_split.right.node == leaf_nodes.1 &*& + initial_split.left.height == 0 &*& initial_split.right.height == 0 &*& length(path) < usize::MAX &*& + .own(t,initial_split.kv.0) &*& .own(t,initial_split.kv.1) &*& + inserted.node.height == 0 &*& insertion_leaves(leaf_nodes.0,inserted.node.node,inserted.idx,Option::Some(leaf_nodes.1),alloc_id,k) &*& + dormant_pair(inserted.node.node.as_ptr(),inserted.idx,?key_cell,?value_cell) &*& + key_cell.inner() == some(?leaf_key) &*& value_cell.inner() == some(?leaf_value) &*& + .own(t,leaf_key) &*& .own(t,leaf_value); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [qa]lifetime_token(alloc_lifetime) &*& [?remaining_fraction]lifetime_token(k) &*& + *root_allocator |-> ?after &*& Allocator::(t,after,alloc_id) &*& *root_slot |-> sleeper &*& + result.node.node == inserted.node.node &*& result.idx == inserted.idx &*& result.node.height == 0 &*& + .own(t,leaf_key) &*& .own(t,leaf_value) &*& + dormant_pair(inserted.node.node.as_ptr(),inserted.idx,key_cell,value_cell) &*& + insertion_leaves(leaf_nodes.0,inserted.node.node,inserted.idx,Option::Some(leaf_nodes.1),alloc_id,k) &*& + completed_levels::(t,alloc_id,k,?completed) &*& + if length(completed) == length(path) { + *sleeper.ptr.as_ptr() |-> Option::Some(?installed) &*& installed.height == old_root.height + 1 &*& + exists::>>(?new_root) &*& installed.node.as_ptr() == &(*new_root.as_ptr()).data &*& + allocated_internal(new_root.as_ptr(),alloc_id,k,_) &*& (*new_root.as_ptr()).data.parent_idx |-> _ &*& + ancestors(installed.node.as_ptr(),[],installed.node.as_ptr()) &*& + internal_slots(new_root,1,cons(old_root.node,cons(?sibling,nil)),_,_) &*& .own(t,_) &*& .own(t,_) + } else { + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& (*root).parent_idx |-> root_index &*& + exists::>>(?receiving) &*& ancestors(&(*receiving.as_ptr()).data,?remaining,root) &*& + route_frames(t,remaining) &*& internal_slots(receiving,_,_,_,_) &*& struct_LeafNode_padding(&(*receiving.as_ptr()).data) &*& struct_InternalNode_padding(receiving.as_ptr()) &*& .own(t,_) &*& .own(t,_) &*& + length(completed) + length(remaining) + 1 == length(path) + }; +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [qa]lifetime_token(alloc_lifetime) &*& [?remaining_fraction]lifetime_token(k) &*& + *root_allocator |-> ?after &*& Allocator::(t,after,alloc_id) &*& *root_slot |-> sleeper &*& + .own(t,leaf_key) &*& .own(t,leaf_value) &*& + dormant_pair(inserted.node.node.as_ptr(),inserted.idx,key_cell,value_cell) &*& + insertion_leaves(leaf_nodes.0,inserted.node.node,inserted.idx,Option::Some(leaf_nodes.1),alloc_id,k) &*& + completed_levels::(t,alloc_id,k,?completed) &*& + if length(completed) == length(path) { + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& detached_child::(?sibling) &*& + exists::>>>(?partial_root) &*& + interrupted_root_change(old_root.node,root_index,alloc_id,k,partial_root) + } else { + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& + exists::>>(?receiving) &*& + ancestor_tail(&(*receiving.as_ptr()).data,?remaining,root,root_index,?ancestor,?ancestor_idx) &*& + leaf_header(&(*receiving.as_ptr()).data,ancestor,ancestor_idx) &*& struct_InternalNode_padding(receiving.as_ptr()) &*& + route_frames(t,remaining) &*& length(completed) + length(remaining) + 1 == length(path) &*& + internal_slots(receiving,?len,_,_,_) &*& detached_child::(?detached) &*& + if len == CAPACITY { .own(t,_) &*& .own(t,_) } else { true } + }; +@*/ +{ + //@ open exists(k); + //@ open exists(leaf_nodes); + //@ let inserted_value = inserted; + //@ let inserted_node = inserted_value.node.node; + //@ let inserted_index = inserted_value.idx; + //@ open_points_to(&initial_split); + let mut split = initial_split; + //@ close_points_to(&initial_split, 1/2); + //@ close_points_to(&split.left); + //@ close_points_to(&split.kv); + //@ close_points_to(&split.right); + //@ close_points_to(&split); + /*@ + assert struct_SplitResult_padding::<'tree,K,V,marker::LeafOrInternal>(?loop_result) &*& + struct_SplitResult_padding::<'tree,K,V,marker::LeafOrInternal>(?payload_arg) &*& + [1/2]struct_SplitResult_padding::<'tree,K,V,marker::LeafOrInternal>(&payload) &*& + struct_SplitResult_padding::<'tree,K,V,marker::Internal>(?forget_arg) &*& + [1/2]struct_SplitResult_padding::<'tree,K,V,marker::Internal>(&pending); + @*/ + //@ close cursor_split_buffer(loop_result); + //@ close cursor_split_buffer(payload_arg); + //@ close [1/2]cursor_split_buffer(&payload); + //@ close cursor_split_buffer(forget_arg); + //@ close [1/2]cursor_split_buffer(&pending); + /*@ + assert struct_Handle_padding::, K, V, marker::Internal>,marker::Edge>(?parent_arg) &*& + [1/2]struct_Handle_padding::, K, V, marker::Internal>,marker::Edge>(&parent) &*& + struct_Handle_padding::, K, V, marker::Leaf>,marker::KV>(?return_addr) &*& + struct_Handle_padding::,marker::KV>(?wake_root_arg) &*& + struct_Handle_padding::,marker::KV>(?wake_fit_arg); + @*/ + //@ close cursor_handle_buffer(parent_arg); + //@ close [1/2]cursor_handle_buffer(&parent); + //@ close cursor_handle_buffer(return_addr); + //@ close cursor_handle_buffer(wake_root_arg); + //@ close cursor_handle_buffer(wake_fit_arg); + /*@ + assert struct_NodeRef_padding::,K,V,marker::LeafOrInternal>(?ascend_arg) &*& + [1/2]struct_NodeRef_padding::,K,V,marker::LeafOrInternal>(&detached) &*& + struct_NodeRef_padding::(?insert_right_arg); + @*/ + //@ close cursor_node_buffer(ascend_arg); + //@ close [1/2]cursor_node_buffer(&detached); + //@ close cursor_node_buffer(insert_right_arg); + //@ assert points_to_::(?key_argument,_) &*& points_to_::(?value_argument,_); + //@ close completed_levels::(t,alloc_id,k,[]); + loop { + /*@ + inv *&split |-> ?loop_split &*& + cursor_split_buffer(loop_result) &*& + cursor_split_buffer(payload_arg) &*& + [1/2]cursor_split_buffer(&payload) &*& + cursor_split_buffer(forget_arg) &*& + [1/2]cursor_split_buffer(&pending) &*& + cursor_node_buffer(ascend_arg) &*& + [1/2]cursor_node_buffer(&detached) &*& + cursor_node_buffer(insert_right_arg) &*& + cursor_handle_buffer(parent_arg) &*& + [1/2]cursor_handle_buffer(&parent) &*& + cursor_handle_buffer(return_addr) &*& + cursor_handle_buffer(wake_root_arg) &*& cursor_handle_buffer(wake_fit_arg) &*& + *key_argument |-> _ &*& *value_argument |-> _ &*& + *root_allocator |-> root_alloc &*& Allocator::(t,root_alloc,alloc_id) &*& + *root_slot |-> sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& + lifetime_token(func_lft) &*& thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [_]allocator_clone_bound::() &*& + [_]std::alloc::Allocator_share::(alloc_lifetime,t,alloc,alloc_id) &*& + [_]frac_borrow(alloc_lifetime, ref_initialized_(alloc)) &*& [qa]lifetime_token(alloc_lifetime) &*& + [?remaining_fraction]lifetime_token(k) &*& + (*root).parent_idx |-> root_index &*& + dormant_pair(inserted_node.as_ptr(), inserted_index, key_cell,value_cell) &*& + insertion_leaves(leaf_nodes.0,inserted_node,inserted_index,Option::Some(leaf_nodes.1),alloc_id,k) &*& + .own(t,leaf_key) &*& .own(t,leaf_value) &*& + detached_child(loop_split.right.node.as_ptr()) &*& + .own(t,loop_split.kv.0) &*& .own(t,loop_split.kv.1) &*& + ancestors(loop_split.left.node.as_ptr(), ?remaining, root) &*& route_frames(t, remaining) &*& completed_levels::(t,alloc_id,k,?completed) &*& + length(completed) + length(remaining) == length(path) &*& loop_split.left.height == length(completed) &*& + loop_split.right.height == loop_split.left.height &*& loop_split.left.height + length(remaining) < usize::MAX; + @*/ + //@ let current_key = loop_split.kv.0; + //@ let current_value = loop_split.kv.1; + //@ open_points_to(&split); + //@ open_points_to(&split.left); + //@ open_points_to(&split.kv); + //@ open_points_to(&split.right); + split = match unsafe { split.left.ascend() } { + Err(detached) => { + let root_node = detached.node; + //@ open ancestors(root_node.as_ptr(), [], root); + //@ close ancestors(root_node.as_ptr(), [], root); + let payload = SplitResult { left: detached, ..split }; + //@ close root_split_inputs(root,payload.right.node.as_ptr(),inserted_node.as_ptr(),inserted_index,root_index,key_cell,value_cell); + //@ open route_frames(t,[]); + //@ close exists(k); + //@ std::ptr::NonNull_new_as_ptr(old_root.node); + //@ std::ptr::NonNull_new_as_ptr(root_node); + return unsafe { finish_root_split/*@::@*/(payload, inserted, root_slot, root_allocator) }; + } + Ok(parent) => { + //@ assert exists::>>(?receiving); + //@ std::ptr::NonNull_Sized_as_ptr(receiving); + //@ assert &(*receiving.as_ptr()).data == (receiving.as_ptr() as *LeafNode); + //@ close exists(receiving); + //@ close exists(k); + match unsafe { parent.insert(split.kv.0, split.kv.1, split.right, alloc.clone()) } { + None => { + return unsafe { inserted.awaken/*@::@*/() }; + } + Some(pending) => { + //@ open exists(receiving); + //@ assert exists::>>(?fresh); + //@ open exists(fresh); + //@ close completed_levels::(t,alloc_id,k, cons(Placement(receiving,fresh,current_key,current_value),completed)); + unsafe { pending.forget_node_type() } + } + } + } + }; + //@ close_points_to(&split.left); + //@ close_points_to(&split.kv); + //@ close_points_to(&split.right); + } +} +// The production iterator is specialized to the two range types used by its +// callers. The invariant preserves the edge slots and separates the repaired +// prefix from the pending suffix. + +// BEGIN_NODE_LEN +impl NodeRef { + unsafe fn relink_len(&self) -> usize + //@ req [?f](*self |-> ?node) &*& [?ql]((*node.node.as_ptr()).len |-> ?len); + //@ ens [f](*self |-> node) &*& [ql]((*node.node.as_ptr()).len |-> len) &*& result == len; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let ptr = self.node.as_ptr(); + //@ close_points_to(self, f); + unsafe { (*ptr).len as usize } + } +} +// END_NODE_LEN + +// BEGIN_NODE_REBORROW +impl NodeRef { + unsafe fn relink_reborrow<'b>(&'b mut self) -> NodeRef, K, V, Type> + //@ req *self |-> ?node; + //@ ens *self |-> node &*& result.node == node.node &*& result.height == node.height; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let borrowed = NodeRef { height: self.height, node: self.node, _marker: PhantomData }; + //@ close_points_to(self); + borrowed + } +} +// END_NODE_REBORROW + +// BEGIN_NEW_EDGE +impl Handle, marker::Edge> { + unsafe fn new_relink_edge(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx <= len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx <= node.relink_len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} +// END_NEW_EDGE + +// The generator binds the read and the two stores to descend and set_parent_link. +impl<'a, K, V> Handle, K, V, marker::Internal>, marker::Edge> { + unsafe fn correct_parent_link(self) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + 0 < self.node.height &*& self.node.height <= usize::MAX &*& 0 <= self.idx &*& self.idx <= CAPACITY &*& + exists::>>(?parent) &*& self.node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + exists::>(?child) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + nth(self.idx, edges) == MaybeUninit::new(child) &*& + (*child.as_ptr()).parent |-> _ &*& (*child.as_ptr()).parent_idx |-> _; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new(self.idx as u16); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(child); + //@ std::ptr::NonNull_new_as_ptr(parent); + let parent_ptr = self.node.node.as_ptr() as *mut InternalNode; + let parent_link = unsafe { NonNull::new_unchecked(parent_ptr) }; + //@ std::ptr::NonNull_new_as_ptr(parent_link); + // BEGIN_RAW_EDGE_READ + //@ let array = &(*parent_ptr).edges; + //@ close_points_to(array); + //@ let view = precreate_ref(array); + //@ init_ref_readonly(view, 1/2); + //@ open_points_to(view); + //@ let base = view as *MaybeUninit>; + //@ array_inv::>>(); + //@ array_split(base, self.idx); + //@ array_split(base + self.idx, 1); + //@ nth_drop(0, self.idx, edges); + //@ open [1/2]array(base + self.idx, 1, _); + //@ open [1/2]array(base + self.idx + 1, 0, _); + //@ let slot = precreate_ref(base + self.idx); + //@ init_ref_readonly(slot, 1/2); + let edge = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() }; + //@ end_ref_readonly(slot); + //@ merge_fractions points_to(base + self.idx, _); + //@ close [1/2]array(base + self.idx, 1, [MaybeUninit::new(child)]); + //@ array_join(base + self.idx); + //@ array_join(base); + //@ close_points_to(view, 1/2); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(array, _); + //@ open_points_to(array); + // END_RAW_EDGE_READ + let _child_height = self.node.height - 1; + unsafe { write_child_backlink(edge.as_ptr(), parent_link, self.idx) }; + } +} + +// BEGIN_RELINK_STEP +unsafe fn repair_one__VeriFast_wrapper<'a, 'b, K, V>( + node: &'b mut NodeRef, K, V, marker::Internal>, + i: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *node |-> ?original &*& 0 < original.height &*& original.height <= usize::MAX &*& + (*original.node.as_ptr()).len |-> ?len &*& 0 <= i &*& i <= len &*& len <= CAPACITY &*& + exists::>>(?parent) &*& original.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& exists::>(?child) &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& nth(i, edges) == MaybeUninit::new(child) &*& + (*child.as_ptr()).parent |-> _ &*& (*child.as_ptr()).parent_idx |-> _; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *node |-> original &*& (*original.node.as_ptr()).len |-> len &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new(i as u16); +@*/ +//@ on_unwind_ens false; +{ + //@ open exists(parent); + //@ open exists(child); + //@ close exists(parent); + //@ close exists(child); + unsafe { Handle::new_relink_edge/*@::,K,V,marker::Internal>@*/( + node.relink_reborrow/*@::,K,V,marker::Internal,'b>@*/(), i + ).correct_parent_link/*@::<'b,K,V>@*/() }; +} + +// END_RELINK_STEP + + + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn relink_range<'b>(&'b mut self, range: std::ops::Range) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + (*node.node.as_ptr()).len |-> ?len &*& len <= CAPACITY &*& + 0 <= range.start &*& range.start <= range.end &*& range.end <= len + 1 &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + child_headers(?children) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + exists::>>, list>>>>(pair(?before, ?after)) &*& + length(before) == range.start &*& + edges == append(before, append(initialized_edges(children), after)) &*& + length(children) == range.end - range.start; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + linked_headers(children, parent, range.start); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(pair(before, after)); + let mut iter = range.into_iter(); + //@ let first = range.start; + //@ let end = range.end; + //@ close linked_headers([], parent, first); + loop { + /*@ + inv iter |-> ?state &*& state.end == end &*& + thread_token(t) &*& lifetime_token(func_lft) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + first <= state.start &*& state.start <= end &*& + linked_headers(?prefix, parent, first) &*& child_headers(?rest) &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + children == append(prefix, rest) &*& length(prefix) == state.start - first &*& length(rest) == end - state.start; + @*/ + let iter_ref = &mut iter; + let next = iter_ref.next(); + match next { + None => break, + Some(i) => { + //@ unpack_nonempty(rest); + //@ assert rest == cons(?child, ?remaining); + //@ initialized_edge_count(prefix); + //@ initialized_edge_count(rest); + //@ initialized_edges_append(prefix, rest); + //@ length_append(initialized_edges(prefix), initialized_edges(rest)); + //@ length_append(initialized_edges(children), after); + //@ nth_append_r(before, append(initialized_edges(children), after), i - first); + //@ nth_append(initialized_edges(children), after, i - first); + //@ nth_append_r(initialized_edges(prefix), initialized_edges(rest), 0); + //@ open child_headers(rest); + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + unsafe { debug_assert!(i <= self.relink_len()) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self,_); + //@ close exists(parent); + //@ close exists(child); + unsafe { repair_one__VeriFast_wrapper/*@::@*/(self, i) }; + //@ append_linked_header(prefix, child, parent, first); + //@ append_assoc(prefix, [child], remaining); + } + } + } + //@ assert child_headers(?unrepaired); + //@ assert linked_headers(?repaired, parent, first); + //@ empty_list_if_zero(unrepaired); + //@ append_nil(repaired); + //@ open child_headers(unrepaired); + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn relink_inclusive<'b>(&'b mut self, range: std::ops::RangeInclusive) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + (*node.node.as_ptr()).len |-> ?len &*& len <= CAPACITY &*& + range.exhausted == false &*& 0 <= range.start &*& range.start <= (range.end + 1) &*& (range.end + 1) <= len + 1 &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + child_headers(?children) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + exists::>>, list>>>>(pair(?before, ?after)) &*& + length(before) == range.start &*& + edges == append(before, append(initialized_edges(children), after)) &*& + length(children) == (range.end + 1) - range.start; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + linked_headers(children, parent, range.start); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(pair(before, after)); + let mut iter = range.into_iter(); + //@ let first = range.start; + //@ let end = (range.end + 1); + //@ close linked_headers([], parent, first); + loop { + /*@ + inv iter |-> ?state &*& state.end + 1 == end &*& state.exhausted == false &*& + thread_token(t) &*& lifetime_token(func_lft) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + first <= state.start &*& state.start <= end &*& + linked_headers(?prefix, parent, first) &*& child_headers(?rest) &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + children == append(prefix, rest) &*& length(prefix) == state.start - first &*& length(rest) == end - state.start; + @*/ + let iter_ref = &mut iter; + let next = iter_ref.next(); + match next { + None => break, + Some(i) => { + //@ unpack_nonempty(rest); + //@ assert rest == cons(?child, ?remaining); + //@ initialized_edge_count(prefix); + //@ initialized_edge_count(rest); + //@ initialized_edges_append(prefix, rest); + //@ length_append(initialized_edges(prefix), initialized_edges(rest)); + //@ length_append(initialized_edges(children), after); + //@ nth_append_r(before, append(initialized_edges(children), after), i - first); + //@ nth_append(initialized_edges(children), after, i - first); + //@ nth_append_r(initialized_edges(prefix), initialized_edges(rest), 0); + //@ open child_headers(rest); + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + unsafe { debug_assert!(i <= self.relink_len()) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self,_); + //@ close exists(parent); + //@ close exists(child); + unsafe { repair_one__VeriFast_wrapper/*@::@*/(self, i) }; + //@ append_linked_header(prefix, child, parent, first); + //@ append_assoc(prefix, [child], remaining); + } + } + } + //@ assert child_headers(?unrepaired); + //@ assert linked_headers(?repaired, parent, first); + //@ empty_list_if_zero(unrepaired); + //@ append_nil(repaired); + //@ open child_headers(unrepaired); + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn correct_all_childrens_parent_links<'b>(&'b mut self) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + (*node.node.as_ptr()).len |-> ?occupancy &*& occupancy <= CAPACITY &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + child_headers(?children) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + exists::>>>(?tail) &*& + edges == append(initialized_edges(children), tail) &*& length(children) == occupancy + 1; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> occupancy &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& linked_headers(children, parent, 0); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(tail); + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + let len = unsafe { self.relink_len() }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self, _); + //@ close exists(parent); + //@ let prefix = nil::>>; + //@ close exists(pair(prefix, tail)); + unsafe { self.relink_inclusive/*@::<'a,K,V,'b>@*/(0..=len) }; + } +} + +impl NodeRef { + unsafe fn merge_len(&self) -> usize + //@ req [?f](*self |-> ?node) &*& [?ql]((*node.node.as_ptr()).len |-> ?len) &*& ref_initialized(self); + //@ ens [f](*self |-> node) &*& [ql]((*node.node.as_ptr()).len |-> len) &*& result == len &*& ref_initialized(self); + //@ on_unwind_ens false; + { + //@ let local = begin_lifetime(); + //@ close ref_initialized_::>(self)(); + //@ borrow(local, ref_initialized_::>(self)); + //@ full_borrow_into_frac(local, ref_initialized_::>(self)); + let length = unsafe { usize::from((*Self::as_leaf_ptr(self)).len) }; + //@ end_lifetime(local); + //@ borrow_end(local, ref_initialized_::>(self)); + //@ open ref_initialized_::>(self)(); + length + } +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { + unsafe fn do_merge_production< + F: FnOnce( + NodeRef, K, V, marker::Internal>, + NodeRef, K, V, marker::LeafOrInternal>, + ) -> R, + R, + A: std::alloc::Allocator, + >( + self, + finish: F, + /*@~mut@*/ alloc: A, + ) -> R + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& .own(t, finish) &*& + Allocator::(t, alloc, ?id) &*& exists::(?k) &*& exists::(?released) &*& + context_merge_inputs(t, self, id, k, released, ?shape); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& .own(t, result) &*& + [released]lifetime_token(k) &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + merged_nodes(t, NonNull::new(self.parent.node.node.as_ptr() as *InternalNode), + self.left_child.node, self.parent.node.height - 1, p - 1, l + 1 + r, + append(take(self.parent.idx + 1, pc), drop(self.parent.idx + 2, pc)), append(lc, rc)) + }; + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + if l + 1 + r <= CAPACITY { + [released]lifetime_token(k) &*& + merged_nodes(t, NonNull::new(self.parent.node.node.as_ptr() as *InternalNode), + self.left_child.node, self.parent.node.height - 1, p - 1, l + 1 + r, + append(take(self.parent.idx + 1, pc), drop(self.parent.idx + 2, pc)), append(lc, rc)) + } else { + context_merge_inputs(t, self, id, k, released, shape) + } + }; + @*/ + { + //@ open exists(k); + //@ open exists(released); + //@ let context = self; + //@ open context_merge_inputs(t, context, id, k, released, shape); + //@ let parent = NonNull::new(self.parent.node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(self.parent.node.node); + //@ std::ptr::NonNull_as_ptr_new(self.parent.node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(parent); + //@ let left = self.left_child.node; + //@ let right = self.right_child.node; + //@ std::ptr::NonNull_Sized_as_ptr(left); + //@ std::ptr::NonNull_Sized_as_ptr(right); + //@ let parent_height = self.parent.node.height; + //@ let index = self.parent.idx; + //@ assert merge_inputs(t, parent, left, right, parent_height, index, id, k, released, ?parent_len, ?left_len, ?right_len_0, ?parent_children, ?left_children, ?right_children); + //@ open merge_inputs(t, parent, left, right, parent_height, index, id, k, released, parent_len, left_len, right_len_0, parent_children, left_children, right_children); + let Handle { node: mut parent_node, idx: parent_idx, .. } = self.parent; + //@ let parent_ptr = &(*parent.as_ptr()).data; + //@ assert parent_ptr == parent_node.node.as_ptr(); + //@ open owned_leaf_slots(t, parent_ptr, parent_len); + //@ open leaf_slots(parent_ptr, parent_len, ?p_keys, ?p_vals); + //@ let parent_view = precreate_ref(&parent_node); + //@ init_ref_readonly(parent_view, 1/2); + let old_parent_len = unsafe { parent_node.merge_len() }; + //@ end_ref_readonly(parent_view); + //@ merge_fractions points_to(&parent_node, _); + let mut left_node = self.left_child; + //@ let left_ptr = left.as_ptr(); + //@ assert left_ptr == left_node.node.as_ptr(); + //@ open owned_leaf_slots(t, left_ptr, left_len); + //@ open leaf_slots(left_ptr, left_len, ?l_keys, ?l_vals); + //@ let left_view = precreate_ref(&left_node); + //@ init_ref_readonly(left_view, 1/2); + let old_left_len = unsafe { left_node.merge_len() }; + //@ end_ref_readonly(left_view); + //@ merge_fractions points_to(&left_node, _); + let mut right_node = self.right_child; + //@ let right_ptr = right.as_ptr(); + //@ assert right_ptr == right_node.node.as_ptr(); + //@ open owned_leaf_slots(t, right_ptr, right_len_0); + //@ open leaf_slots(right_ptr, right_len_0, ?r_keys, ?r_vals); + //@ let right_view = precreate_ref(&right_node); + //@ init_ref_readonly(right_view, 1/2); + let right_len = unsafe { right_node.merge_len() }; + //@ end_ref_readonly(right_view); + //@ merge_fractions points_to(&right_node, _); + let new_left_len = old_left_len + 1 + right_len; + /*@ + if new_left_len > CAPACITY { + close leaf_slots(parent_ptr, parent_len, p_keys, p_vals); + close owned_leaf_slots(t, parent_ptr, parent_len); + close leaf_slots(left_ptr, left_len, l_keys, l_vals); + close owned_leaf_slots(t, left_ptr, left_len); + close leaf_slots(right_ptr, right_len, r_keys, r_vals); + close owned_leaf_slots(t, right_ptr, right_len); + close merge_inputs(t, parent, left, right, parent_height, index, id, k, released, + parent_len, left_len, right_len, parent_children, left_children, right_children); + close context_merge_inputs(t, context, id, k, released, shape); + std::alloc::Allocator_to_own(alloc); + } + @*/ + assert!(new_left_len <= CAPACITY); + //@ open balancing_edges(parent, parent_children, ?parent_slots); + //@ split_linked_headers(parent_children, parent, 0, parent_idx); + //@ drop_n_plus_one(parent_idx, parent_children); + //@ open linked_headers(drop(parent_idx, parent_children), parent, parent_idx); + //@ drop_n_plus_one(parent_idx + 1, parent_children); + //@ open linked_headers(drop(parent_idx + 1, parent_children), parent, parent_idx + 1); + //@ close leaf_without_len(left_ptr, Option::Some(parent), MaybeUninit::new(parent_idx as u16), l_keys, l_vals); + unsafe { + *left_node.len_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/() = new_left_len as u16; + //@ assert len_loan(left_ptr, ?slot, Option::Some(parent), MaybeUninit::new(parent_idx as u16), l_keys, l_vals); + //@ end_len_loan(left_ptr, slot); + //@ open leaf_without_len(left_ptr, Option::Some(parent), MaybeUninit::new(parent_idx as u16), l_keys, l_vals); + //@ open balancing_child_allocation(right, parent_height - 1, id, k, released); + /*@ + if parent_height > 1 { + let internal = right_ptr as *InternalNode; + open allocated_internal(internal, id, k, released); + assert &(*internal).data == right_ptr; + } else { + open allocated_leaf(right_ptr, id, k, released); + } + @*/ + //@ close leaf_header(left_ptr, Option::Some(parent), MaybeUninit::new(parent_idx as u16)); + //@ close leaf_header(right_ptr, Option::Some(parent), MaybeUninit::new((parent_idx + 1) as u16)); + //@ close leaf_without_keys(parent_ptr, _, _, old_parent_len as u16, _); + //@ close leaf_without_keys(left_ptr, _, _, new_left_len as u16, _); + //@ close leaf_without_keys(right_ptr, _, _, right_len as u16, _); + { + //@ assert leaf_without_keys(parent_ptr, ?keys_p_parent, ?keys_p_idx, ?keys_p_len, ?keys_p_vals); + //@ assert leaf_without_keys(left_ptr, ?keys_l_parent, ?keys_l_idx, ?keys_l_len, ?keys_l_vals); + //@ assert leaf_without_keys(right_ptr, ?keys_r_parent, ?keys_r_idx, ?keys_r_len, ?keys_r_vals); + //@ let keys_old_parent = take(old_parent_len, p_keys); + //@ let keys_old_left = take(old_left_len, l_keys); + //@ let keys_incoming = take(right_len, r_keys); + //@ length_take(old_parent_len, p_keys); + //@ length_take(old_left_len, l_keys); + //@ length_take(right_len, r_keys); + //@ nth_take_range(p_keys, old_parent_len, parent_idx); + //@ split_slot_owners(t, keys_old_parent, parent_idx); + //@ drop_n_plus_one(parent_idx, keys_old_parent); + //@ open slot_owners(t, drop(parent_idx, keys_old_parent)); + unsafe { + let parent_key = slice_remove( + parent_node.key_area_prefix_mut/*@::<'a,K,V,marker::Internal,'a>@*/(..old_parent_len), parent_idx, + ); + //@ assert keys_range_loan(parent_ptr, ?keys_active, 0, old_parent_len, keys_p_parent, keys_p_idx, keys_p_len, keys_p_vals, _, _); + //@ assert move_slice(keys_active as *MaybeUninit, old_parent_len, ?keys_active_after); + //@ end_keys_range(parent_ptr, keys_active); + //@ let keys_surviving = append(take(parent_idx, keys_old_parent), drop(parent_idx + 1, keys_old_parent)); + //@ join_slot_owners(t, take(parent_idx, keys_old_parent), drop(parent_idx + 1, keys_old_parent)); + //@ length_take(parent_idx, keys_old_parent); + //@ length_drop(parent_idx + 1, keys_old_parent); + //@ append_assoc(take(parent_idx, keys_old_parent), drop(parent_idx + 1, keys_old_parent), drop(old_parent_len - 1, keys_old_parent)); + //@ take_append_l(old_parent_len - 1, keys_surviving, drop(old_parent_len - 1, keys_old_parent)); + //@ take_length(keys_surviving); + //@ length_append(keys_surviving, drop(old_parent_len - 1, keys_old_parent)); + //@ length_drop(old_parent_len - 1, keys_old_parent); + //@ take_append_l(old_parent_len - 1, keys_active_after, drop(old_parent_len, p_keys)); + //@ drop_append(old_parent_len, keys_active_after, drop(old_parent_len, p_keys)); + + left_node.key_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(old_left_len).write(parent_key); + //@ assert keys_slot_loan(left_ptr, ?keys_slot, old_left_len, keys_l_parent, keys_l_idx, keys_l_len, keys_l_vals, _, _); + //@ end_keys_slot(left_ptr, keys_slot); + //@ assert (*left_ptr).keys[..CAPACITY] |-> ?keys_left_with_entry; + //@ let keys_with_entry = append(keys_old_left, [MaybeUninit::new(parent_key)]); + //@ append_assoc(keys_old_left, [MaybeUninit::new(parent_key)], drop(old_left_len + 1, l_keys)); + //@ take_append_l(old_left_len + 1, keys_with_entry, drop(old_left_len + 1, l_keys)); + //@ take_length(keys_with_entry); + + move_to_slice( + right_node.key_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(..right_len), + left_node.key_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(old_left_len + 1..new_left_len), + ); + //@ assert keys_range_loan(right_ptr, ?keys_source, 0, right_len, keys_r_parent, keys_r_idx, keys_r_len, keys_r_vals, _, _); + //@ assert keys_range_loan(left_ptr, ?keys_destination, old_left_len + 1, new_left_len, keys_l_parent, keys_l_idx, keys_l_len, keys_l_vals, _, _); + //@ end_keys_range(right_ptr, keys_source); + //@ append_take_drop_n(r_keys, right_len); + //@ end_keys_range(left_ptr, keys_destination); + //@ close slot_owners::(t, cons(MaybeUninit::new(parent_key), keys_incoming)); + //@ join_slot_owners(t, keys_old_left, cons(MaybeUninit::new(parent_key), keys_incoming)); + //@ let keys_merged = append(keys_old_left, cons(MaybeUninit::new(parent_key), keys_incoming)); + //@ append_assoc(keys_with_entry, keys_incoming, drop(new_left_len, keys_left_with_entry)); + //@ append_assoc(keys_old_left, [MaybeUninit::new(parent_key)], keys_incoming); + //@ take_append_l(new_left_len, keys_merged, drop(new_left_len, keys_left_with_entry)); + //@ take_length(keys_merged); + //@ length_append(keys_with_entry, keys_incoming); + //@ drop_append(new_left_len, keys_merged, drop(new_left_len, keys_left_with_entry)); + //@ drop_append(new_left_len, keys_with_entry, drop(old_left_len + 1, l_keys)); + //@ drop_twice(right_len, old_left_len + 1, l_keys); + } + } + //@ open leaf_without_keys(parent_ptr, _, _, old_parent_len as u16, _); + //@ open leaf_without_keys(left_ptr, _, _, new_left_len as u16, _); + //@ open leaf_without_keys(right_ptr, _, _, right_len as u16, _); + //@ close leaf_without_vals(parent_ptr, _, _, old_parent_len as u16, _); + //@ close leaf_without_vals(left_ptr, _, _, new_left_len as u16, _); + //@ close leaf_without_vals(right_ptr, _, _, right_len as u16, _); + { + //@ assert leaf_without_vals(parent_ptr, ?vals_p_parent, ?vals_p_idx, ?vals_p_len, ?vals_p_keys); + //@ assert leaf_without_vals(left_ptr, ?vals_l_parent, ?vals_l_idx, ?vals_l_len, ?vals_l_keys); + //@ assert leaf_without_vals(right_ptr, ?vals_r_parent, ?vals_r_idx, ?vals_r_len, ?vals_r_keys); + //@ let vals_old_parent = take(old_parent_len, p_vals); + //@ let vals_old_left = take(old_left_len, l_vals); + //@ let vals_incoming = take(right_len, r_vals); + //@ length_take(old_parent_len, p_vals); + //@ length_take(old_left_len, l_vals); + //@ length_take(right_len, r_vals); + //@ nth_take_range(p_vals, old_parent_len, parent_idx); + //@ split_slot_owners(t, vals_old_parent, parent_idx); + //@ drop_n_plus_one(parent_idx, vals_old_parent); + //@ open slot_owners(t, drop(parent_idx, vals_old_parent)); + unsafe { + let parent_val = slice_remove( + parent_node.val_area_prefix_mut/*@::<'a,K,V,marker::Internal,'a>@*/(..old_parent_len), parent_idx, + ); + //@ assert vals_range_loan(parent_ptr, ?vals_active, 0, old_parent_len, vals_p_parent, vals_p_idx, vals_p_len, vals_p_keys, _, _); + //@ assert move_slice(vals_active as *MaybeUninit, old_parent_len, ?vals_active_after); + //@ end_vals_range(parent_ptr, vals_active); + //@ let vals_surviving = append(take(parent_idx, vals_old_parent), drop(parent_idx + 1, vals_old_parent)); + //@ join_slot_owners(t, take(parent_idx, vals_old_parent), drop(parent_idx + 1, vals_old_parent)); + //@ length_take(parent_idx, vals_old_parent); + //@ length_drop(parent_idx + 1, vals_old_parent); + //@ append_assoc(take(parent_idx, vals_old_parent), drop(parent_idx + 1, vals_old_parent), drop(old_parent_len - 1, vals_old_parent)); + //@ take_append_l(old_parent_len - 1, vals_surviving, drop(old_parent_len - 1, vals_old_parent)); + //@ take_length(vals_surviving); + //@ length_append(vals_surviving, drop(old_parent_len - 1, vals_old_parent)); + //@ length_drop(old_parent_len - 1, vals_old_parent); + //@ take_append_l(old_parent_len - 1, vals_active_after, drop(old_parent_len, p_vals)); + //@ drop_append(old_parent_len, vals_active_after, drop(old_parent_len, p_vals)); + + left_node.val_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(old_left_len).write(parent_val); + //@ assert vals_slot_loan(left_ptr, ?vals_slot, old_left_len, vals_l_parent, vals_l_idx, vals_l_len, vals_l_keys, _, _); + //@ end_vals_slot(left_ptr, vals_slot); + //@ assert (*left_ptr).vals[..CAPACITY] |-> ?vals_left_with_entry; + //@ let vals_with_entry = append(vals_old_left, [MaybeUninit::new(parent_val)]); + //@ append_assoc(vals_old_left, [MaybeUninit::new(parent_val)], drop(old_left_len + 1, l_vals)); + //@ take_append_l(old_left_len + 1, vals_with_entry, drop(old_left_len + 1, l_vals)); + //@ take_length(vals_with_entry); + + move_to_slice( + right_node.val_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(..right_len), + left_node.val_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(old_left_len + 1..new_left_len), + ); + //@ assert vals_range_loan(right_ptr, ?vals_source, 0, right_len, vals_r_parent, vals_r_idx, vals_r_len, vals_r_keys, _, _); + //@ assert vals_range_loan(left_ptr, ?vals_destination, old_left_len + 1, new_left_len, vals_l_parent, vals_l_idx, vals_l_len, vals_l_keys, _, _); + //@ end_vals_range(right_ptr, vals_source); + //@ append_take_drop_n(r_vals, right_len); + //@ end_vals_range(left_ptr, vals_destination); + //@ close slot_owners::(t, cons(MaybeUninit::new(parent_val), vals_incoming)); + //@ join_slot_owners(t, vals_old_left, cons(MaybeUninit::new(parent_val), vals_incoming)); + //@ let vals_merged = append(vals_old_left, cons(MaybeUninit::new(parent_val), vals_incoming)); + //@ append_assoc(vals_with_entry, vals_incoming, drop(new_left_len, vals_left_with_entry)); + //@ append_assoc(vals_old_left, [MaybeUninit::new(parent_val)], vals_incoming); + //@ take_append_l(new_left_len, vals_merged, drop(new_left_len, vals_left_with_entry)); + //@ take_length(vals_merged); + //@ length_append(vals_with_entry, vals_incoming); + //@ drop_append(new_left_len, vals_merged, drop(new_left_len, vals_left_with_entry)); + //@ drop_append(new_left_len, vals_with_entry, drop(old_left_len + 1, l_vals)); + //@ drop_twice(right_len, old_left_len + 1, l_vals); + } + } + //@ open leaf_without_vals(parent_ptr, _, _, old_parent_len as u16, _); + //@ open leaf_without_vals(left_ptr, _, _, new_left_len as u16, _); + //@ open leaf_without_vals(right_ptr, _, _, right_len as u16, _); + //@ open leaf_header(right_ptr, _, _); + //@ open leaf_header(left_ptr, _, _); + /*@ + if parent_height > 1 { + close allocated_internal(right_ptr as *InternalNode, id, k, released); + } else { + close allocated_leaf(right_ptr, id, k, released); + } + @*/ + //@ close balancing_child_allocation(right, parent_height - 1, id, k, released); + //@ close linked_headers(drop(parent_idx + 1, parent_children), parent, parent_idx + 1); + //@ close linked_headers(drop(parent_idx, parent_children), parent, parent_idx); + //@ length_take(parent_idx, parent_children); + //@ join_linked_headers(take(parent_idx, parent_children), drop(parent_idx, parent_children), parent, 0); + //@ append_take_drop_n(parent_children, parent_idx); + //@ close balancing_edges(parent, parent_children, parent_slots); + //@ open leaf_header(parent_ptr, ?ancestor, ?ancestor_idx); + //@ close leaf_without_len(parent_ptr, ancestor, ancestor_idx, _, _); + { + //@ assert balancing_edges(parent, parent_children, ?slots_before_removal); + //@ assert leaf_without_len(parent_ptr, ancestor, ancestor_idx, ?parent_keys_for_relink, ?parent_vals_for_relink); + //@ open exists(parent); + //@ open balancing_edges(parent, parent_children, slots_before_removal); + //@ let parent_storage = parent.as_ptr(); + //@ let prefix = take(parent_idx + 1, parent_children); + //@ let rest = drop(parent_idx + 2, parent_children); + //@ let removed = nth(parent_idx + 1, parent_children); + //@ split_linked_headers(parent_children, parent, 0, parent_idx + 1); + //@ drop_n_plus_one(parent_idx + 1, parent_children); + //@ open linked_headers(cons(removed, rest), parent, parent_idx + 1); + //@ forget_link_indices(rest, parent, parent_idx + 2); + //@ let parent_active_edges = initialized_edges(parent_children); + //@ nth_initialized_edge(parent_children, parent_idx + 1); + //@ std::ptr::close_NonNull_own(t, removed); + //@ produce_type_interp::>(); + unsafe { + //@ nth_take_range(slots_before_removal, old_parent_len + 1, parent_idx + 1); + //@ open leaf_without_len(&(*parent_storage).data, ancestor, ancestor_idx, parent_keys_for_relink, parent_vals_for_relink); + //@ close_points_to(&(*parent_storage).data); + //@ close internal_without_edges(parent_storage, ?data); + slice_remove( + parent_node.edge_area_prefix_mut/*@::<'a,K,V,'a>@*/(..old_parent_len + 1), parent_idx + 1, + ); + //@ assert edges_range_loan(parent_storage, ?removed_prefix, 0, old_parent_len + 1, data, _, _); + //@ end_edges_range(parent_storage, removed_prefix); + //@ open internal_without_edges(parent_storage, data); + //@ open_points_to(&(*parent_storage).data); + //@ close leaf_without_len(&(*parent_storage).data, ancestor, ancestor_idx, parent_keys_for_relink, parent_vals_for_relink); + //@ leak >.own(t, removed); + //@ std::ptr::open_NonNull_own(t, removed); + //@ leak type_interp::>(); + //@ initialized_edge_split(parent_children, parent_idx + 1); + //@ initialized_edge_split(parent_children, parent_idx + 2); + //@ let parent_children_after = append(initialized_edges(prefix), initialized_edges(rest)); + //@ let residual = drop(old_parent_len, parent_active_edges); + //@ append_assoc(initialized_edges(prefix), initialized_edges(rest), residual); + //@ initialized_edge_count(prefix); + //@ initialized_edge_count(rest); + //@ length_take(parent_idx + 1, parent_children); + //@ length_drop(parent_idx + 2, parent_children); + // BEGIN_MERGE_PARENT_RELINK + //@ assert (*parent_storage).edges[..CAPACITY + 1] |-> ?new_edges; + //@ let parent_relink_before = initialized_edges(prefix); + //@ let tail = drop(old_parent_len + 1, slots_before_removal); + //@ append_assoc(parent_relink_before, append(initialized_edges(rest), residual), tail); + //@ append_assoc(initialized_edges(rest), residual, tail); + //@ close exists(parent); + //@ close exists(pair(parent_relink_before, append(residual, tail))); + parent_node.relink_range/*@::<'a,K,V,'a>@*/(parent_idx + 1..old_parent_len); + *parent_node.len_mut/*@::<'a,K,V,marker::Internal,'a>@*/() -= 1; + //@ assert len_loan(&(*parent_storage).data, ?parent_length_slot, ancestor, ancestor_idx, parent_keys_for_relink, parent_vals_for_relink); + //@ end_len_loan(&(*parent_storage).data, parent_length_slot); + // END_MERGE_PARENT_RELINK + //@ take_append_l(parent_idx + 1, initialized_edges(prefix), initialized_edges(rest)); + //@ take_length(initialized_edges(prefix)); + //@ take_append_l(old_parent_len, parent_children_after, residual); + //@ take_append_l(old_parent_len, append(parent_children_after, residual), drop(old_parent_len + 1, slots_before_removal)); + //@ join_linked_headers(prefix, rest, parent, 0); + //@ initialized_edges_append(prefix, rest); + //@ close balancing_edges(parent, append(prefix, rest), new_edges); + } + } + //@ open leaf_without_len(parent_ptr, ancestor, ancestor_idx, _, _); + //@ close leaf_header(parent_ptr, ancestor, ancestor_idx); + //@ close leaf_slots(parent_ptr, old_parent_len - 1, _, _); + //@ close owned_leaf_slots(t, parent_ptr, old_parent_len - 1); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ open balancing_child_edges(left, parent_height - 1, left_len, left_children); + //@ open balancing_child_edges(right, parent_height - 1, right_len, right_children); + //@ open balancing_child_allocation(right, parent_height - 1, id, k, released); + //@ let surviving = append(take(parent_idx + 1, parent_children), drop(parent_idx + 2, parent_children)); + if parent_node.height > 1 { + let mut left_internal_node = left_node.reborrow_mut/*@::,K,V,marker::LeafOrInternal,'a>@*/().cast_to_internal_unchecked/*@::<'a,K,V>@*/(); + let mut right_internal_node = right_node.cast_to_internal_unchecked/*@::<'a,K,V>@*/(); + //@ let left_internal = NonNull::new(left_internal_node.node.as_ptr() as *InternalNode); + //@ let right_internal = NonNull::new(right_internal_node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_as_ptr_new(left_internal_node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(left_internal); + //@ std::ptr::NonNull_as_ptr_new(right_internal_node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(right_internal); + //@ assert &(*left_internal.as_ptr()).data == left_ptr; + //@ assert &(*right_internal.as_ptr()).data == right_ptr; + //@ open owned_leaf_slots(t, left_ptr, new_left_len); + //@ open leaf_slots(left_ptr, new_left_len, _, _); + //@ open balancing_child_padding(left, parent_height - 1); + //@ open allocated_internal(right_internal.as_ptr(), id, k, released); + //@ open balancing_edges(parent, surviving, ?parent_edges); + //@ let before_left = take(parent_idx + 1, parent_children); + //@ let after_right = drop(parent_idx + 2, parent_children); + //@ length_take(parent_idx + 1, parent_children); + //@ length_drop(parent_idx + 2, parent_children); + //@ length_append(before_left, after_right); + //@ take_append_l(parent_idx + 1, before_left, after_right); + //@ take_length(before_left); + //@ nth_take_range(surviving, parent_idx + 1, parent_idx); + //@ nth_take_range(parent_children, parent_idx + 1, parent_idx); + //@ split_linked_headers(surviving, parent, 0, parent_idx); + //@ drop_n_plus_one(parent_idx, surviving); + //@ open linked_headers(drop(parent_idx, surviving), parent, parent_idx); + //@ close_points_to(left_ptr); + //@ close_points_to(right_ptr); + //@ close internal_without_edges(left_internal.as_ptr(), ?left_data); + //@ close internal_without_edges(right_internal.as_ptr(), ?right_data); + { + //@ assert balancing_edges(left_internal, left_children, ?left_slots); + //@ assert balancing_edges(right_internal, right_children, ?right_slots); + //@ open exists(pair(left_internal, right_internal)); + //@ open balancing_edges(left_internal, left_children, left_slots); + //@ open balancing_edges(right_internal, right_children, right_slots); + //@ forget_link_indices(right_children, right_internal, 0); + unsafe { + move_to_slice( + right_internal_node.edge_area_prefix_mut/*@::<'a,K,V,'a>@*/(..right_len + 1), + left_internal_node.edge_area_range_mut/*@::<'a,K,V,'a>@*/(old_left_len + 1..new_left_len + 1), + ); + //@ assert edges_range_loan(right_internal.as_ptr(), ?edge_source, 0, right_len + 1, right_data, _, _); + //@ assert edges_range_loan(left_internal.as_ptr(), ?edge_destination, old_left_len + 1, new_left_len + 1, left_data, _, _); + //@ end_edges_range(right_internal.as_ptr(), edge_source); + //@ append_take_drop_n(right_slots, right_len + 1); + //@ end_edges_range(left_internal.as_ptr(), edge_destination); + //@ let before = take(old_left_len + 1, left_slots); + //@ let after_copy = drop(new_left_len + 1, left_slots); + //@ length_take(old_left_len + 1, left_slots); + //@ open internal_without_edges(left_internal.as_ptr(), left_data); + //@ open_points_to(&(*left_internal.as_ptr()).data); + //@ close exists(left_internal); + //@ close exists(pair(before, after_copy)); + left_internal_node.relink_range/*@::<'a,K,V,'a>@*/(old_left_len + 1..new_left_len + 1); + //@ close_points_to(&(*left_internal.as_ptr()).data); + //@ close internal_without_edges(left_internal.as_ptr(), left_data); + //@ assert (*left_internal.as_ptr()).edges[..CAPACITY + 1] |-> ?merged_slots; + //@ append_assoc(before, initialized_edges(right_children), after_copy); + //@ let active = append(initialized_edges(left_children), initialized_edges(right_children)); + //@ initialized_edge_count(left_children); + //@ initialized_edge_count(right_children); + //@ take_twice(left_slots, old_left_len + 1, new_left_len + 1); + //@ take_append_l(new_left_len + 1, active, drop(new_left_len + 1, left_slots)); + //@ take_length(active); + //@ join_linked_headers(left_children, right_children, left_internal, 0); + //@ initialized_edges_append(left_children, right_children); + //@ close balancing_edges(left_internal, append(left_children, right_children), merged_slots); + } + } + //@ open internal_without_edges(left_internal.as_ptr(), left_data); + //@ open_points_to(left_ptr); + //@ close linked_headers(drop(parent_idx, surviving), parent, parent_idx); + //@ length_take(parent_idx, surviving); + //@ join_linked_headers(take(parent_idx, surviving), drop(parent_idx, surviving), parent, 0); + //@ append_take_drop_n(surviving, parent_idx); + //@ close balancing_edges(parent, surviving, parent_edges); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ close balancing_child_edges(left, parent_height - 1, new_left_len, append(left_children, right_children)); + //@ close balancing_child_padding(left, parent_height - 1); + //@ close merged_nodes(t, parent, left, parent_height - 1, old_parent_len - 1, new_left_len, surviving, append(left_children, right_children)); + //@ open internal_without_edges(right_internal.as_ptr(), right_data); + //@ open_points_to(right_ptr); + //@ close_points_to(right_internal.as_ptr(), 1); + //@ let target = right_internal.as_ptr(); + //@ points_to__limits(target); + //@ assert close_points_to_at_lft_token(1, id.lft, target, ?allocation_fraction); + //@ to_u8s_(target); + //@ close_points_to_at_lft_token_to_close_u8s_at_lft_token(target); + //@ close_array_at_lft_(target as *u8); + //@ lifetime_token_trade_back(allocation_fraction, id.lft); + //@ let view = precreate_ref(&alloc); + //@ let call_lifetime = begin_lifetime(); + { + //@ let_lft 'call = call_lifetime; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'call, A>(view); + //@ open_points_to(&right_internal_node); + //@ std::ptr::NonNull_Sized_as_ptr(right_internal_node.node); + //@ std::ptr::NonNull_as_ptr_new(right_internal_node.node.as_ptr() as *u8); + alloc.deallocate/*@::@*/(right_internal_node.node.cast(), std::alloc::Layout::new::>()); + //@ close_points_to(&right_internal_node); + //@ leak Allocator::<&'call A>(t, view, id); + } + //@ end_lifetime(call_lifetime); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + } else { + //@ close balancing_child_edges(left, parent_height - 1, new_left_len, append(left_children, right_children)); + //@ close merged_nodes(t, parent, left, parent_height - 1, old_parent_len - 1, new_left_len, surviving, append(left_children, right_children)); + //@ open allocated_leaf(right_ptr, id, k, released); + //@ close_points_to(right_ptr, 1); + //@ let target = right.as_ptr(); + //@ points_to__limits(target); + //@ assert close_points_to_at_lft_token(1, id.lft, target, ?allocation_fraction); + //@ to_u8s_(target); + //@ close_points_to_at_lft_token_to_close_u8s_at_lft_token(target); + //@ close_array_at_lft_(target as *u8); + //@ lifetime_token_trade_back(allocation_fraction, id.lft); + //@ let view = precreate_ref(&alloc); + //@ let call_lifetime = begin_lifetime(); + { + //@ let_lft 'call = call_lifetime; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'call, A>(view); + //@ open_points_to(&right_node); + //@ std::ptr::NonNull_Sized_as_ptr(right_node.node); + //@ std::ptr::NonNull_as_ptr_new(right_node.node.as_ptr() as *u8); + alloc.deallocate/*@::@*/(right_node.node.cast(), std::alloc::Layout::new::>()); + //@ close_points_to(&right_node); + //@ leak Allocator::<&'call A>(t, view, id); + } + //@ end_lifetime(call_lifetime); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + } + } + //@ std::alloc::Allocator_to_own::(alloc); + //@ close NodeRef_own::,K,V,marker::Internal>(t, parent_node); + //@ close NodeRef_own::,K,V,marker::LeafOrInternal>(t, left_node); + unsafe { call_merge__VeriFast_wrapper(finish, parent_node, left_node) } + } +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { + unsafe fn merge_tracking_child( + self, + alloc: A, + ) -> NodeRef, K, V, marker::LeafOrInternal> + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t, alloc, ?id) &*& exists::(?k) &*& exists::(?released) &*& + context_merge_inputs(t, self, id, k, released, ?shape); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& result == self.left_child &*& + [released]lifetime_token(k) &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + merged_nodes(t, NonNull::new(self.parent.node.node.as_ptr() as *InternalNode), + self.left_child.node, self.parent.node.height - 1, p - 1, l + 1 + r, + append(take(self.parent.idx + 1, pc), drop(self.parent.idx + 2, pc)), append(lc, rc)) + }; + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + context_merge_inputs(t, self, id, k, released, shape); + @*/ + { + unsafe { self.merge_child_production/*@::<'a,K,V,A>@*/(alloc) } + } + + unsafe fn merge_child_production( + self, + /*@~mut@*/ alloc: A, + ) -> NodeRef, K, V, marker::LeafOrInternal> + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t, alloc, ?id) &*& exists::(?k) &*& exists::(?released) &*& + context_merge_inputs(t, self, id, k, released, ?shape); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& result == self.left_child &*& + [released]lifetime_token(k) &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + merged_nodes(t, NonNull::new(self.parent.node.node.as_ptr() as *InternalNode), + self.left_child.node, self.parent.node.height - 1, p - 1, l + 1 + r, + append(take(self.parent.idx + 1, pc), drop(self.parent.idx + 2, pc)), append(lc, rc)) + }; + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + context_merge_inputs(t, self, id, k, released, shape); + @*/ + { + //@ open exists(k); + //@ open exists(released); + //@ let context = self; + //@ open context_merge_inputs(t, context, id, k, released, shape); + //@ let parent = NonNull::new(self.parent.node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(self.parent.node.node); + //@ std::ptr::NonNull_as_ptr_new(self.parent.node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(parent); + //@ let left = self.left_child.node; + //@ let right = self.right_child.node; + //@ std::ptr::NonNull_Sized_as_ptr(left); + //@ std::ptr::NonNull_Sized_as_ptr(right); + //@ let parent_height = self.parent.node.height; + //@ let index = self.parent.idx; + //@ assert merge_inputs(t, parent, left, right, parent_height, index, id, k, released, ?parent_len, ?left_len, ?right_len_0, ?parent_children, ?left_children, ?right_children); + //@ open merge_inputs(t, parent, left, right, parent_height, index, id, k, released, parent_len, left_len, right_len_0, parent_children, left_children, right_children); + let Handle { node: mut parent_node, idx: parent_idx, .. } = self.parent; + //@ let parent_ptr = &(*parent.as_ptr()).data; + //@ assert parent_ptr == parent_node.node.as_ptr(); + //@ open owned_leaf_slots(t, parent_ptr, parent_len); + //@ open leaf_slots(parent_ptr, parent_len, ?p_keys, ?p_vals); + //@ let parent_view = precreate_ref(&parent_node); + //@ init_ref_readonly(parent_view, 1/2); + let old_parent_len = unsafe { parent_node.merge_len() }; + //@ end_ref_readonly(parent_view); + //@ merge_fractions points_to(&parent_node, _); + let mut left_node = self.left_child; + //@ let left_ptr = left.as_ptr(); + //@ assert left_ptr == left_node.node.as_ptr(); + //@ open owned_leaf_slots(t, left_ptr, left_len); + //@ open leaf_slots(left_ptr, left_len, ?l_keys, ?l_vals); + //@ let left_view = precreate_ref(&left_node); + //@ init_ref_readonly(left_view, 1/2); + let old_left_len = unsafe { left_node.merge_len() }; + //@ end_ref_readonly(left_view); + //@ merge_fractions points_to(&left_node, _); + let mut right_node = self.right_child; + //@ let right_ptr = right.as_ptr(); + //@ assert right_ptr == right_node.node.as_ptr(); + //@ open owned_leaf_slots(t, right_ptr, right_len_0); + //@ open leaf_slots(right_ptr, right_len_0, ?r_keys, ?r_vals); + //@ let right_view = precreate_ref(&right_node); + //@ init_ref_readonly(right_view, 1/2); + let right_len = unsafe { right_node.merge_len() }; + //@ end_ref_readonly(right_view); + //@ merge_fractions points_to(&right_node, _); + let new_left_len = old_left_len + 1 + right_len; + /*@ + if new_left_len > CAPACITY { + close leaf_slots(parent_ptr, parent_len, p_keys, p_vals); + close owned_leaf_slots(t, parent_ptr, parent_len); + close leaf_slots(left_ptr, left_len, l_keys, l_vals); + close owned_leaf_slots(t, left_ptr, left_len); + close leaf_slots(right_ptr, right_len, r_keys, r_vals); + close owned_leaf_slots(t, right_ptr, right_len); + close merge_inputs(t, parent, left, right, parent_height, index, id, k, released, + parent_len, left_len, right_len, parent_children, left_children, right_children); + close context_merge_inputs(t, context, id, k, released, shape); + std::alloc::Allocator_to_own(alloc); + } + @*/ + assert!(new_left_len <= CAPACITY); + //@ open balancing_edges(parent, parent_children, ?parent_slots); + //@ split_linked_headers(parent_children, parent, 0, parent_idx); + //@ drop_n_plus_one(parent_idx, parent_children); + //@ open linked_headers(drop(parent_idx, parent_children), parent, parent_idx); + //@ drop_n_plus_one(parent_idx + 1, parent_children); + //@ open linked_headers(drop(parent_idx + 1, parent_children), parent, parent_idx + 1); + //@ close leaf_without_len(left_ptr, Option::Some(parent), MaybeUninit::new(parent_idx as u16), l_keys, l_vals); + unsafe { + *left_node.len_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/() = new_left_len as u16; + //@ assert len_loan(left_ptr, ?slot, Option::Some(parent), MaybeUninit::new(parent_idx as u16), l_keys, l_vals); + //@ end_len_loan(left_ptr, slot); + //@ open leaf_without_len(left_ptr, Option::Some(parent), MaybeUninit::new(parent_idx as u16), l_keys, l_vals); + //@ open balancing_child_allocation(right, parent_height - 1, id, k, released); + /*@ + if parent_height > 1 { + let internal = right_ptr as *InternalNode; + open allocated_internal(internal, id, k, released); + assert &(*internal).data == right_ptr; + } else { + open allocated_leaf(right_ptr, id, k, released); + } + @*/ + //@ close leaf_header(left_ptr, Option::Some(parent), MaybeUninit::new(parent_idx as u16)); + //@ close leaf_header(right_ptr, Option::Some(parent), MaybeUninit::new((parent_idx + 1) as u16)); + //@ close leaf_without_keys(parent_ptr, _, _, old_parent_len as u16, _); + //@ close leaf_without_keys(left_ptr, _, _, new_left_len as u16, _); + //@ close leaf_without_keys(right_ptr, _, _, right_len as u16, _); + { + //@ assert leaf_without_keys(parent_ptr, ?keys_p_parent, ?keys_p_idx, ?keys_p_len, ?keys_p_vals); + //@ assert leaf_without_keys(left_ptr, ?keys_l_parent, ?keys_l_idx, ?keys_l_len, ?keys_l_vals); + //@ assert leaf_without_keys(right_ptr, ?keys_r_parent, ?keys_r_idx, ?keys_r_len, ?keys_r_vals); + //@ let keys_old_parent = take(old_parent_len, p_keys); + //@ let keys_old_left = take(old_left_len, l_keys); + //@ let keys_incoming = take(right_len, r_keys); + //@ length_take(old_parent_len, p_keys); + //@ length_take(old_left_len, l_keys); + //@ length_take(right_len, r_keys); + //@ nth_take_range(p_keys, old_parent_len, parent_idx); + //@ split_slot_owners(t, keys_old_parent, parent_idx); + //@ drop_n_plus_one(parent_idx, keys_old_parent); + //@ open slot_owners(t, drop(parent_idx, keys_old_parent)); + unsafe { + let parent_key = slice_remove( + parent_node.key_area_prefix_mut/*@::<'a,K,V,marker::Internal,'a>@*/(..old_parent_len), parent_idx, + ); + //@ assert keys_range_loan(parent_ptr, ?keys_active, 0, old_parent_len, keys_p_parent, keys_p_idx, keys_p_len, keys_p_vals, _, _); + //@ assert move_slice(keys_active as *MaybeUninit, old_parent_len, ?keys_active_after); + //@ end_keys_range(parent_ptr, keys_active); + //@ let keys_surviving = append(take(parent_idx, keys_old_parent), drop(parent_idx + 1, keys_old_parent)); + //@ join_slot_owners(t, take(parent_idx, keys_old_parent), drop(parent_idx + 1, keys_old_parent)); + //@ length_take(parent_idx, keys_old_parent); + //@ length_drop(parent_idx + 1, keys_old_parent); + //@ append_assoc(take(parent_idx, keys_old_parent), drop(parent_idx + 1, keys_old_parent), drop(old_parent_len - 1, keys_old_parent)); + //@ take_append_l(old_parent_len - 1, keys_surviving, drop(old_parent_len - 1, keys_old_parent)); + //@ take_length(keys_surviving); + //@ length_append(keys_surviving, drop(old_parent_len - 1, keys_old_parent)); + //@ length_drop(old_parent_len - 1, keys_old_parent); + //@ take_append_l(old_parent_len - 1, keys_active_after, drop(old_parent_len, p_keys)); + //@ drop_append(old_parent_len, keys_active_after, drop(old_parent_len, p_keys)); + + left_node.key_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(old_left_len).write(parent_key); + //@ assert keys_slot_loan(left_ptr, ?keys_slot, old_left_len, keys_l_parent, keys_l_idx, keys_l_len, keys_l_vals, _, _); + //@ end_keys_slot(left_ptr, keys_slot); + //@ assert (*left_ptr).keys[..CAPACITY] |-> ?keys_left_with_entry; + //@ let keys_with_entry = append(keys_old_left, [MaybeUninit::new(parent_key)]); + //@ append_assoc(keys_old_left, [MaybeUninit::new(parent_key)], drop(old_left_len + 1, l_keys)); + //@ take_append_l(old_left_len + 1, keys_with_entry, drop(old_left_len + 1, l_keys)); + //@ take_length(keys_with_entry); + + move_to_slice( + right_node.key_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(..right_len), + left_node.key_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(old_left_len + 1..new_left_len), + ); + //@ assert keys_range_loan(right_ptr, ?keys_source, 0, right_len, keys_r_parent, keys_r_idx, keys_r_len, keys_r_vals, _, _); + //@ assert keys_range_loan(left_ptr, ?keys_destination, old_left_len + 1, new_left_len, keys_l_parent, keys_l_idx, keys_l_len, keys_l_vals, _, _); + //@ end_keys_range(right_ptr, keys_source); + //@ append_take_drop_n(r_keys, right_len); + //@ end_keys_range(left_ptr, keys_destination); + //@ close slot_owners::(t, cons(MaybeUninit::new(parent_key), keys_incoming)); + //@ join_slot_owners(t, keys_old_left, cons(MaybeUninit::new(parent_key), keys_incoming)); + //@ let keys_merged = append(keys_old_left, cons(MaybeUninit::new(parent_key), keys_incoming)); + //@ append_assoc(keys_with_entry, keys_incoming, drop(new_left_len, keys_left_with_entry)); + //@ append_assoc(keys_old_left, [MaybeUninit::new(parent_key)], keys_incoming); + //@ take_append_l(new_left_len, keys_merged, drop(new_left_len, keys_left_with_entry)); + //@ take_length(keys_merged); + //@ length_append(keys_with_entry, keys_incoming); + //@ drop_append(new_left_len, keys_merged, drop(new_left_len, keys_left_with_entry)); + //@ drop_append(new_left_len, keys_with_entry, drop(old_left_len + 1, l_keys)); + //@ drop_twice(right_len, old_left_len + 1, l_keys); + } + } + //@ open leaf_without_keys(parent_ptr, _, _, old_parent_len as u16, _); + //@ open leaf_without_keys(left_ptr, _, _, new_left_len as u16, _); + //@ open leaf_without_keys(right_ptr, _, _, right_len as u16, _); + //@ close leaf_without_vals(parent_ptr, _, _, old_parent_len as u16, _); + //@ close leaf_without_vals(left_ptr, _, _, new_left_len as u16, _); + //@ close leaf_without_vals(right_ptr, _, _, right_len as u16, _); + { + //@ assert leaf_without_vals(parent_ptr, ?vals_p_parent, ?vals_p_idx, ?vals_p_len, ?vals_p_keys); + //@ assert leaf_without_vals(left_ptr, ?vals_l_parent, ?vals_l_idx, ?vals_l_len, ?vals_l_keys); + //@ assert leaf_without_vals(right_ptr, ?vals_r_parent, ?vals_r_idx, ?vals_r_len, ?vals_r_keys); + //@ let vals_old_parent = take(old_parent_len, p_vals); + //@ let vals_old_left = take(old_left_len, l_vals); + //@ let vals_incoming = take(right_len, r_vals); + //@ length_take(old_parent_len, p_vals); + //@ length_take(old_left_len, l_vals); + //@ length_take(right_len, r_vals); + //@ nth_take_range(p_vals, old_parent_len, parent_idx); + //@ split_slot_owners(t, vals_old_parent, parent_idx); + //@ drop_n_plus_one(parent_idx, vals_old_parent); + //@ open slot_owners(t, drop(parent_idx, vals_old_parent)); + unsafe { + let parent_val = slice_remove( + parent_node.val_area_prefix_mut/*@::<'a,K,V,marker::Internal,'a>@*/(..old_parent_len), parent_idx, + ); + //@ assert vals_range_loan(parent_ptr, ?vals_active, 0, old_parent_len, vals_p_parent, vals_p_idx, vals_p_len, vals_p_keys, _, _); + //@ assert move_slice(vals_active as *MaybeUninit, old_parent_len, ?vals_active_after); + //@ end_vals_range(parent_ptr, vals_active); + //@ let vals_surviving = append(take(parent_idx, vals_old_parent), drop(parent_idx + 1, vals_old_parent)); + //@ join_slot_owners(t, take(parent_idx, vals_old_parent), drop(parent_idx + 1, vals_old_parent)); + //@ length_take(parent_idx, vals_old_parent); + //@ length_drop(parent_idx + 1, vals_old_parent); + //@ append_assoc(take(parent_idx, vals_old_parent), drop(parent_idx + 1, vals_old_parent), drop(old_parent_len - 1, vals_old_parent)); + //@ take_append_l(old_parent_len - 1, vals_surviving, drop(old_parent_len - 1, vals_old_parent)); + //@ take_length(vals_surviving); + //@ length_append(vals_surviving, drop(old_parent_len - 1, vals_old_parent)); + //@ length_drop(old_parent_len - 1, vals_old_parent); + //@ take_append_l(old_parent_len - 1, vals_active_after, drop(old_parent_len, p_vals)); + //@ drop_append(old_parent_len, vals_active_after, drop(old_parent_len, p_vals)); + + left_node.val_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(old_left_len).write(parent_val); + //@ assert vals_slot_loan(left_ptr, ?vals_slot, old_left_len, vals_l_parent, vals_l_idx, vals_l_len, vals_l_keys, _, _); + //@ end_vals_slot(left_ptr, vals_slot); + //@ assert (*left_ptr).vals[..CAPACITY] |-> ?vals_left_with_entry; + //@ let vals_with_entry = append(vals_old_left, [MaybeUninit::new(parent_val)]); + //@ append_assoc(vals_old_left, [MaybeUninit::new(parent_val)], drop(old_left_len + 1, l_vals)); + //@ take_append_l(old_left_len + 1, vals_with_entry, drop(old_left_len + 1, l_vals)); + //@ take_length(vals_with_entry); + + move_to_slice( + right_node.val_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(..right_len), + left_node.val_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'a>@*/(old_left_len + 1..new_left_len), + ); + //@ assert vals_range_loan(right_ptr, ?vals_source, 0, right_len, vals_r_parent, vals_r_idx, vals_r_len, vals_r_keys, _, _); + //@ assert vals_range_loan(left_ptr, ?vals_destination, old_left_len + 1, new_left_len, vals_l_parent, vals_l_idx, vals_l_len, vals_l_keys, _, _); + //@ end_vals_range(right_ptr, vals_source); + //@ append_take_drop_n(r_vals, right_len); + //@ end_vals_range(left_ptr, vals_destination); + //@ close slot_owners::(t, cons(MaybeUninit::new(parent_val), vals_incoming)); + //@ join_slot_owners(t, vals_old_left, cons(MaybeUninit::new(parent_val), vals_incoming)); + //@ let vals_merged = append(vals_old_left, cons(MaybeUninit::new(parent_val), vals_incoming)); + //@ append_assoc(vals_with_entry, vals_incoming, drop(new_left_len, vals_left_with_entry)); + //@ append_assoc(vals_old_left, [MaybeUninit::new(parent_val)], vals_incoming); + //@ take_append_l(new_left_len, vals_merged, drop(new_left_len, vals_left_with_entry)); + //@ take_length(vals_merged); + //@ length_append(vals_with_entry, vals_incoming); + //@ drop_append(new_left_len, vals_merged, drop(new_left_len, vals_left_with_entry)); + //@ drop_append(new_left_len, vals_with_entry, drop(old_left_len + 1, l_vals)); + //@ drop_twice(right_len, old_left_len + 1, l_vals); + } + } + //@ open leaf_without_vals(parent_ptr, _, _, old_parent_len as u16, _); + //@ open leaf_without_vals(left_ptr, _, _, new_left_len as u16, _); + //@ open leaf_without_vals(right_ptr, _, _, right_len as u16, _); + //@ open leaf_header(right_ptr, _, _); + //@ open leaf_header(left_ptr, _, _); + /*@ + if parent_height > 1 { + close allocated_internal(right_ptr as *InternalNode, id, k, released); + } else { + close allocated_leaf(right_ptr, id, k, released); + } + @*/ + //@ close balancing_child_allocation(right, parent_height - 1, id, k, released); + //@ close linked_headers(drop(parent_idx + 1, parent_children), parent, parent_idx + 1); + //@ close linked_headers(drop(parent_idx, parent_children), parent, parent_idx); + //@ length_take(parent_idx, parent_children); + //@ join_linked_headers(take(parent_idx, parent_children), drop(parent_idx, parent_children), parent, 0); + //@ append_take_drop_n(parent_children, parent_idx); + //@ close balancing_edges(parent, parent_children, parent_slots); + //@ open leaf_header(parent_ptr, ?ancestor, ?ancestor_idx); + //@ close leaf_without_len(parent_ptr, ancestor, ancestor_idx, _, _); + { + //@ assert balancing_edges(parent, parent_children, ?slots_before_removal); + //@ assert leaf_without_len(parent_ptr, ancestor, ancestor_idx, ?parent_keys_for_relink, ?parent_vals_for_relink); + //@ open exists(parent); + //@ open balancing_edges(parent, parent_children, slots_before_removal); + //@ let parent_storage = parent.as_ptr(); + //@ let prefix = take(parent_idx + 1, parent_children); + //@ let rest = drop(parent_idx + 2, parent_children); + //@ let removed = nth(parent_idx + 1, parent_children); + //@ split_linked_headers(parent_children, parent, 0, parent_idx + 1); + //@ drop_n_plus_one(parent_idx + 1, parent_children); + //@ open linked_headers(cons(removed, rest), parent, parent_idx + 1); + //@ forget_link_indices(rest, parent, parent_idx + 2); + //@ let parent_active_edges = initialized_edges(parent_children); + //@ nth_initialized_edge(parent_children, parent_idx + 1); + //@ std::ptr::close_NonNull_own(t, removed); + //@ produce_type_interp::>(); + unsafe { + //@ nth_take_range(slots_before_removal, old_parent_len + 1, parent_idx + 1); + //@ open leaf_without_len(&(*parent_storage).data, ancestor, ancestor_idx, parent_keys_for_relink, parent_vals_for_relink); + //@ close_points_to(&(*parent_storage).data); + //@ close internal_without_edges(parent_storage, ?data); + slice_remove( + parent_node.edge_area_prefix_mut/*@::<'a,K,V,'a>@*/(..old_parent_len + 1), parent_idx + 1, + ); + //@ assert edges_range_loan(parent_storage, ?removed_prefix, 0, old_parent_len + 1, data, _, _); + //@ end_edges_range(parent_storage, removed_prefix); + //@ open internal_without_edges(parent_storage, data); + //@ open_points_to(&(*parent_storage).data); + //@ close leaf_without_len(&(*parent_storage).data, ancestor, ancestor_idx, parent_keys_for_relink, parent_vals_for_relink); + //@ leak >.own(t, removed); + //@ std::ptr::open_NonNull_own(t, removed); + //@ leak type_interp::>(); + //@ initialized_edge_split(parent_children, parent_idx + 1); + //@ initialized_edge_split(parent_children, parent_idx + 2); + //@ let parent_children_after = append(initialized_edges(prefix), initialized_edges(rest)); + //@ let residual = drop(old_parent_len, parent_active_edges); + //@ append_assoc(initialized_edges(prefix), initialized_edges(rest), residual); + //@ initialized_edge_count(prefix); + //@ initialized_edge_count(rest); + //@ length_take(parent_idx + 1, parent_children); + //@ length_drop(parent_idx + 2, parent_children); + // BEGIN_MERGE_PARENT_RELINK + //@ assert (*parent_storage).edges[..CAPACITY + 1] |-> ?new_edges; + //@ let parent_relink_before = initialized_edges(prefix); + //@ let tail = drop(old_parent_len + 1, slots_before_removal); + //@ append_assoc(parent_relink_before, append(initialized_edges(rest), residual), tail); + //@ append_assoc(initialized_edges(rest), residual, tail); + //@ close exists(parent); + //@ close exists(pair(parent_relink_before, append(residual, tail))); + parent_node.relink_range/*@::<'a,K,V,'a>@*/(parent_idx + 1..old_parent_len); + *parent_node.len_mut/*@::<'a,K,V,marker::Internal,'a>@*/() -= 1; + //@ assert len_loan(&(*parent_storage).data, ?parent_length_slot, ancestor, ancestor_idx, parent_keys_for_relink, parent_vals_for_relink); + //@ end_len_loan(&(*parent_storage).data, parent_length_slot); + // END_MERGE_PARENT_RELINK + //@ take_append_l(parent_idx + 1, initialized_edges(prefix), initialized_edges(rest)); + //@ take_length(initialized_edges(prefix)); + //@ take_append_l(old_parent_len, parent_children_after, residual); + //@ take_append_l(old_parent_len, append(parent_children_after, residual), drop(old_parent_len + 1, slots_before_removal)); + //@ join_linked_headers(prefix, rest, parent, 0); + //@ initialized_edges_append(prefix, rest); + //@ close balancing_edges(parent, append(prefix, rest), new_edges); + } + } + //@ open leaf_without_len(parent_ptr, ancestor, ancestor_idx, _, _); + //@ close leaf_header(parent_ptr, ancestor, ancestor_idx); + //@ close leaf_slots(parent_ptr, old_parent_len - 1, _, _); + //@ close owned_leaf_slots(t, parent_ptr, old_parent_len - 1); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ open balancing_child_edges(left, parent_height - 1, left_len, left_children); + //@ open balancing_child_edges(right, parent_height - 1, right_len, right_children); + //@ open balancing_child_allocation(right, parent_height - 1, id, k, released); + //@ let surviving = append(take(parent_idx + 1, parent_children), drop(parent_idx + 2, parent_children)); + if parent_node.height > 1 { + let mut left_internal_node = left_node.reborrow_mut/*@::,K,V,marker::LeafOrInternal,'a>@*/().cast_to_internal_unchecked/*@::<'a,K,V>@*/(); + let mut right_internal_node = right_node.cast_to_internal_unchecked/*@::<'a,K,V>@*/(); + //@ let left_internal = NonNull::new(left_internal_node.node.as_ptr() as *InternalNode); + //@ let right_internal = NonNull::new(right_internal_node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_as_ptr_new(left_internal_node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(left_internal); + //@ std::ptr::NonNull_as_ptr_new(right_internal_node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(right_internal); + //@ assert &(*left_internal.as_ptr()).data == left_ptr; + //@ assert &(*right_internal.as_ptr()).data == right_ptr; + //@ open owned_leaf_slots(t, left_ptr, new_left_len); + //@ open leaf_slots(left_ptr, new_left_len, _, _); + //@ open balancing_child_padding(left, parent_height - 1); + //@ open allocated_internal(right_internal.as_ptr(), id, k, released); + //@ open balancing_edges(parent, surviving, ?parent_edges); + //@ let before_left = take(parent_idx + 1, parent_children); + //@ let after_right = drop(parent_idx + 2, parent_children); + //@ length_take(parent_idx + 1, parent_children); + //@ length_drop(parent_idx + 2, parent_children); + //@ length_append(before_left, after_right); + //@ take_append_l(parent_idx + 1, before_left, after_right); + //@ take_length(before_left); + //@ nth_take_range(surviving, parent_idx + 1, parent_idx); + //@ nth_take_range(parent_children, parent_idx + 1, parent_idx); + //@ split_linked_headers(surviving, parent, 0, parent_idx); + //@ drop_n_plus_one(parent_idx, surviving); + //@ open linked_headers(drop(parent_idx, surviving), parent, parent_idx); + //@ close_points_to(left_ptr); + //@ close_points_to(right_ptr); + //@ close internal_without_edges(left_internal.as_ptr(), ?left_data); + //@ close internal_without_edges(right_internal.as_ptr(), ?right_data); + { + //@ assert balancing_edges(left_internal, left_children, ?left_slots); + //@ assert balancing_edges(right_internal, right_children, ?right_slots); + //@ open exists(pair(left_internal, right_internal)); + //@ open balancing_edges(left_internal, left_children, left_slots); + //@ open balancing_edges(right_internal, right_children, right_slots); + //@ forget_link_indices(right_children, right_internal, 0); + unsafe { + move_to_slice( + right_internal_node.edge_area_prefix_mut/*@::<'a,K,V,'a>@*/(..right_len + 1), + left_internal_node.edge_area_range_mut/*@::<'a,K,V,'a>@*/(old_left_len + 1..new_left_len + 1), + ); + //@ assert edges_range_loan(right_internal.as_ptr(), ?edge_source, 0, right_len + 1, right_data, _, _); + //@ assert edges_range_loan(left_internal.as_ptr(), ?edge_destination, old_left_len + 1, new_left_len + 1, left_data, _, _); + //@ end_edges_range(right_internal.as_ptr(), edge_source); + //@ append_take_drop_n(right_slots, right_len + 1); + //@ end_edges_range(left_internal.as_ptr(), edge_destination); + //@ let before = take(old_left_len + 1, left_slots); + //@ let after_copy = drop(new_left_len + 1, left_slots); + //@ length_take(old_left_len + 1, left_slots); + //@ open internal_without_edges(left_internal.as_ptr(), left_data); + //@ open_points_to(&(*left_internal.as_ptr()).data); + //@ close exists(left_internal); + //@ close exists(pair(before, after_copy)); + left_internal_node.relink_range/*@::<'a,K,V,'a>@*/(old_left_len + 1..new_left_len + 1); + //@ close_points_to(&(*left_internal.as_ptr()).data); + //@ close internal_without_edges(left_internal.as_ptr(), left_data); + //@ assert (*left_internal.as_ptr()).edges[..CAPACITY + 1] |-> ?merged_slots; + //@ append_assoc(before, initialized_edges(right_children), after_copy); + //@ let active = append(initialized_edges(left_children), initialized_edges(right_children)); + //@ initialized_edge_count(left_children); + //@ initialized_edge_count(right_children); + //@ take_twice(left_slots, old_left_len + 1, new_left_len + 1); + //@ take_append_l(new_left_len + 1, active, drop(new_left_len + 1, left_slots)); + //@ take_length(active); + //@ join_linked_headers(left_children, right_children, left_internal, 0); + //@ initialized_edges_append(left_children, right_children); + //@ close balancing_edges(left_internal, append(left_children, right_children), merged_slots); + } + } + //@ open internal_without_edges(left_internal.as_ptr(), left_data); + //@ open_points_to(left_ptr); + //@ close linked_headers(drop(parent_idx, surviving), parent, parent_idx); + //@ length_take(parent_idx, surviving); + //@ join_linked_headers(take(parent_idx, surviving), drop(parent_idx, surviving), parent, 0); + //@ append_take_drop_n(surviving, parent_idx); + //@ close balancing_edges(parent, surviving, parent_edges); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ close balancing_child_edges(left, parent_height - 1, new_left_len, append(left_children, right_children)); + //@ close balancing_child_padding(left, parent_height - 1); + //@ close merged_nodes(t, parent, left, parent_height - 1, old_parent_len - 1, new_left_len, surviving, append(left_children, right_children)); + //@ open internal_without_edges(right_internal.as_ptr(), right_data); + //@ open_points_to(right_ptr); + //@ close_points_to(right_internal.as_ptr(), 1); + //@ let target = right_internal.as_ptr(); + //@ points_to__limits(target); + //@ assert close_points_to_at_lft_token(1, id.lft, target, ?allocation_fraction); + //@ to_u8s_(target); + //@ close_points_to_at_lft_token_to_close_u8s_at_lft_token(target); + //@ close_array_at_lft_(target as *u8); + //@ lifetime_token_trade_back(allocation_fraction, id.lft); + //@ let view = precreate_ref(&alloc); + //@ let call_lifetime = begin_lifetime(); + { + //@ let_lft 'call = call_lifetime; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'call, A>(view); + //@ open_points_to(&right_internal_node); + //@ std::ptr::NonNull_Sized_as_ptr(right_internal_node.node); + //@ std::ptr::NonNull_as_ptr_new(right_internal_node.node.as_ptr() as *u8); + alloc.deallocate/*@::@*/(right_internal_node.node.cast(), std::alloc::Layout::new::>()); + //@ close_points_to(&right_internal_node); + //@ leak Allocator::<&'call A>(t, view, id); + } + //@ end_lifetime(call_lifetime); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + } else { + //@ close balancing_child_edges(left, parent_height - 1, new_left_len, append(left_children, right_children)); + //@ close merged_nodes(t, parent, left, parent_height - 1, old_parent_len - 1, new_left_len, surviving, append(left_children, right_children)); + //@ open allocated_leaf(right_ptr, id, k, released); + //@ close_points_to(right_ptr, 1); + //@ let target = right.as_ptr(); + //@ points_to__limits(target); + //@ assert close_points_to_at_lft_token(1, id.lft, target, ?allocation_fraction); + //@ to_u8s_(target); + //@ close_points_to_at_lft_token_to_close_u8s_at_lft_token(target); + //@ close_array_at_lft_(target as *u8); + //@ lifetime_token_trade_back(allocation_fraction, id.lft); + //@ let view = precreate_ref(&alloc); + //@ let call_lifetime = begin_lifetime(); + { + //@ let_lft 'call = call_lifetime; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'call, A>(view); + //@ open_points_to(&right_node); + //@ std::ptr::NonNull_Sized_as_ptr(right_node.node); + //@ std::ptr::NonNull_as_ptr_new(right_node.node.as_ptr() as *u8); + alloc.deallocate/*@::@*/(right_node.node.cast(), std::alloc::Layout::new::>()); + //@ close_points_to(&right_node); + //@ leak Allocator::<&'call A>(t, view, id); + } + //@ end_lifetime(call_lifetime); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + } + } + //@ std::alloc::Allocator_to_own::(alloc); + unsafe { select_merged_child(parent_node, left_node) } + } + + unsafe fn merge_tracking_child_edge( + /*@~mut@*/ self, + track_edge_idx: LeftOrRight, + alloc: A, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t, alloc, ?id) &*& exists::(?k) &*& exists::(?released) &*& + context_merge_inputs(t, self, id, k, released, ?shape) &*& + match track_edge_idx { + LeftOrRight::Left(idx) => 0 <= idx, + LeftOrRight::Right(idx) => 0 <= idx + }; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& [released]lifetime_token(k) &*& + result.node == self.left_child &*& + match shape { + MergeLengths(p, l, r, pc, lc, rc) => + merged_nodes(t, NonNull::new(self.parent.node.node.as_ptr() as *InternalNode), + self.left_child.node, self.parent.node.height - 1, p - 1, l + 1 + r, + append(take(self.parent.idx + 1, pc), drop(self.parent.idx + 2, pc)), append(lc, rc)) &*& + match track_edge_idx { + LeftOrRight::Left(idx) => result.idx == idx &*& idx <= l, + LeftOrRight::Right(idx) => result.idx == l + 1 + idx &*& idx <= r + } + }; + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + context_merge_inputs(t, self, id, k, released, shape); + @*/ + { + //@ open exists(k); + //@ open exists(released); + //@ assert context_merge_inputs(t, ?context, id, k, released, shape); + //@ open context_merge_inputs(t, context, id, k, released, shape); + //@ let parent = NonNull::new(context.parent.node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(context.parent.node.node); + //@ std::ptr::NonNull_as_ptr_new(context.parent.node.node.as_ptr() as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(parent); + //@ let left = context.left_child.node; + //@ let right = context.right_child.node; + //@ std::ptr::NonNull_Sized_as_ptr(left); + //@ std::ptr::NonNull_Sized_as_ptr(right); + //@ let height = context.parent.node.height; + //@ let index = context.parent.idx; + //@ assert merge_inputs(t, parent, left, right, height, index, id, k, released, ?p, ?l, ?r, ?pc, ?lc, ?rc); + //@ open merge_inputs(t, parent, left, right, height, index, id, k, released, p, l, r, pc, lc, rc); + //@ let left_ptr = left.as_ptr(); + //@ let right_ptr = right.as_ptr(); + //@ open owned_leaf_slots(t, left_ptr, l); + //@ open leaf_slots(left_ptr, l, ?lk, ?lv); + //@ open_points_to(&self); + //@ let left_view = precreate_ref(&self.left_child); + //@ init_ref_readonly(left_view, 1/2); + let old_left_len = unsafe { self.left_child.merge_len() }; + //@ end_ref_readonly(left_view); + //@ merge_fractions points_to(&self.left_child, _); + //@ close leaf_slots(left_ptr, l, lk, lv); + //@ close owned_leaf_slots(t, left_ptr, l); + //@ open owned_leaf_slots(t, right_ptr, r); + //@ open leaf_slots(right_ptr, r, ?rk, ?rv); + //@ let right_view = precreate_ref(&self.right_child); + //@ init_ref_readonly(right_view, 1/2); + let right_len = unsafe { self.right_child.merge_len() }; + //@ end_ref_readonly(right_view); + //@ merge_fractions points_to(&self.right_child, _); + //@ close_points_to(&self); + //@ close leaf_slots(right_ptr, r, rk, rv); + //@ close owned_leaf_slots(t, right_ptr, r); + //@ close merge_inputs(t, parent, left, right, height, index, id, k, released, p, l, r, pc, lc, rc); + //@ close context_merge_inputs(t, context, id, k, released, shape); + /*@ + if !(match track_edge_idx { + LeftOrRight::Left(at) => at <= old_left_len, + LeftOrRight::Right(at) => at <= right_len + }) { + std::alloc::Allocator_to_own(alloc); + } + @*/ + assert!(match track_edge_idx { + LeftOrRight::Left(idx) => idx <= old_left_len, + LeftOrRight::Right(idx) => idx <= right_len, + }); + //@ close exists(k); + //@ close exists(released); + //@ open_points_to(&self); + let merging = self; + //@ close_points_to(&self); + let child = unsafe { merging.merge_tracking_child/*@::<'a,K,V,A>@*/(alloc) }; + //@ let new_len = l + 1 + r; + //@ let surviving = append(take(index + 1, pc), drop(index + 2, pc)); + //@ open merged_nodes(t, parent, left, height - 1, p - 1, new_len, surviving, append(lc, rc)); + //@ open owned_leaf_slots(t, left_ptr, new_len); + //@ open leaf_slots(left_ptr, new_len, ?keys, ?vals); + let edge = unsafe { finish_merge_tracking__VeriFast_wrapper/*@::@*/(child, old_left_len, track_edge_idx) }; + //@ close leaf_slots(left_ptr, new_len, keys, vals); + //@ close owned_leaf_slots(t, left_ptr, new_len); + //@ close merged_nodes(t, parent, left, height - 1, p - 1, new_len, surviving, append(lc, rc)); + edge + } +} + +unsafe fn select_merged_child<'a,K,V>( + _parent: NodeRef, K, V, marker::Internal>, + child: NodeRef, K, V, marker::LeafOrInternal>, +) -> NodeRef, K, V, marker::LeafOrInternal> +//@ req true; +//@ ens result == child; +//@ on_unwind_ens false; +{ + child +} + +// The separator replacement shared by the production steal methods. + +// BEGIN_BORROW_INITIALIZED_SLOT +unsafe fn borrow_initialized_slot<'short,T>(slot: &'short mut MaybeUninit) -> &'short mut T +//@ req *slot |-> ?bits &*& bits.inner() == some(?entry); +//@ ens *result |-> entry &*& ref_mut_end_token(result, slot as *T) &*& ref_origin(result) == ref_origin(slot as *T); +//@ on_unwind_ens false; +{ + let ptr = slot.as_mut_ptr(); + //@ open_MaybeUninit(slot); + let lent = unsafe { &mut *ptr }; //~track_ref_creation + lent +} +// END_BORROW_INITIALIZED_SLOT + +/*@ +pred initialized_array_slot( + base: *MaybeUninit, index: usize, lent: *T, + before: list>, after: list> +) = + array(base,index,before) &*& + array(base+index+1,CAPACITY-index-1,after) &*& + exists::<*MaybeUninit>(?slot) &*& ref_mut_end_token(slot,base+index) &*& ref_mut_end_token(lent,slot as *T); + +lem end_initialized_array_slot(base: *MaybeUninit, index: usize, lent: *T) + req 0 <= index &*& index < CAPACITY &*& initialized_array_slot(base,index,lent,?before,?after) &*& *lent |-> ?entry; + ens base[..CAPACITY] |-> append(before,cons(MaybeUninit::new(entry),after)); +{ + open initialized_array_slot(base,index,lent,before,after); + open exists::<*MaybeUninit>(?slot); + end_ref_mut(lent); + std::mem::close_MaybeUninit(slot); + end_ref_mut(slot); + close array(base+index,1,[MaybeUninit::new(entry)]); + array_join(base+index); + array_join(base); +} +@*/ + +/*@ +fix replace_slot(index: usize, entry: T, slots: list) -> list { + append(take(index,slots),cons(entry,drop(index+1,slots))) +} +@*/ + +impl<'a, K:'a, V:'a, NodeType> Handle,K,V,NodeType>,marker::KV> { + unsafe fn replace_kv_production<'short>(&'short mut self, k:K, v:V) -> (K,V) + /*@ + req *self |-> ?incoming &*& leaf_header(incoming.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(incoming.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= incoming.idx &*& incoming.idx < len &*& + nth(incoming.idx,keys).inner() == some(?old_key) &*& nth(incoming.idx,vals).inner() == some(?old_val); + @*/ + /*@ + ens *self |-> incoming &*& leaf_header(incoming.node.node.as_ptr(),parent,parent_idx) &*& + leaf_slots(incoming.node.node.as_ptr(),len,replace_slot(incoming.idx,MaybeUninit::new(k),keys),replace_slot(incoming.idx,MaybeUninit::new(v),vals)) &*& + result.0 == old_key &*& result.1 == old_val; + @*/ + //@ on_unwind_ens false; + { + //@ let node = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open leaf_slots(node,len,keys,vals); + //@ open_points_to(self); + //@ let view = precreate_ref(&(*self).node); + //@ init_ref_readonly(view,1/2); + debug_assert!(self.idx < self.node.merge_len()); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&(*self).node, _); + //@ open leaf_header(node,parent,parent_idx); + //@ close_points_to(node); + let leaf = unsafe { self.node.as_leaf_mut/*@::<'a,K,V,NodeType,'short>@*/() }; //~track_ref_creation + //@ open_points_to(leaf); + //@ close_points_to(&(*leaf).keys); + let key_slot = unsafe { + <[MaybeUninit]>::get_unchecked_mut( + { + let key_array = &mut leaf.keys; //~track_ref_creation + let slice: &mut [MaybeUninit] = key_array; + //@ open_points_to(key_array); + //@ let key_base = key_array as *MaybeUninit; + //@ array_split(key_base,index); + //@ array_split(key_base+index,1); + //@ open array(key_base+index,1,_); + //@ open array(key_base+index+1,0,_); + //@ nth_drop(0,index,keys); + //@ drop_twice(1,index,keys); + slice + }, + self.idx, + ) + }; + let key = unsafe { borrow_initialized_slot(key_slot) }; + //@ close exists::<*MaybeUninit>(key_slot); + //@ close initialized_array_slot(key_base,index,key,take(index,keys),drop(index+1,keys)); + //@ close_points_to(&(*leaf).vals); + let val_slot = unsafe { + <[MaybeUninit]>::get_unchecked_mut( + { + let val_array = &mut leaf.vals; //~track_ref_creation + let slice: &mut [MaybeUninit] = val_array; + //@ open_points_to(val_array); + //@ let val_base = val_array as *MaybeUninit; + //@ array_split(val_base,index); + //@ array_split(val_base+index,1); + //@ open array(val_base+index,1,_); + //@ open array(val_base+index+1,0,_); + //@ nth_drop(0,index,vals); + //@ drop_twice(1,index,vals); + slice + }, + self.idx, + ) + }; + let val = unsafe { borrow_initialized_slot(val_slot) }; + //@ close exists::<*MaybeUninit>(val_slot); + //@ close initialized_array_slot(val_base,index,val,take(index,vals),drop(index+1,vals)); + let result = (std::mem::replace(key,k), std::mem::replace(val,v)); + //@ end_initialized_array_slot(key_base,index,key); + //@ close_points_to(key_array); + //@ end_ref_mut(key_array); + //@ open_points_to(&(*leaf).keys); + //@ end_initialized_array_slot(val_base,index,val); + //@ close_points_to(val_array); + //@ end_ref_mut(val_array); + //@ open_points_to(&(*leaf).vals); + //@ close_points_to(leaf); + //@ end_ref_mut(leaf); + //@ assert ref_mut_end_token(?receiver,&(*self).node); + //@ end_ref_mut(receiver); + //@ open_points_to(node); + //@ close leaf_header(node,parent,parent_idx); + //@ close leaf_slots(node,len,replace_slot(index,MaybeUninit::new(k),keys),replace_slot(index,MaybeUninit::new(v),vals)); + //@ close_points_to(self); + result + } +} + +/*@ +lem open_slot_owner(t: thread_id_t, slots: list>, len: usize, idx: usize) + req 0 <= idx &*& idx < len &*& len <= length(slots) &*& slot_owners(t,take(len,slots)); + ens slot_owners(t,take(idx,slots)) &*& slot_owners(t,drop(idx+1,take(len,slots))) &*& + nth(idx,slots).inner() == some(?value) &*& nth(idx,slots) == MaybeUninit::new(value) &*& .own(t,value); +{ + let live = take(len,slots); + length_take(len,slots); + split_slot_owners(t,live,idx); + take_twice(slots,idx,len); + drop_n_plus_one(idx,live); + drop_twice(1,idx,live); + open slot_owners(t,drop(idx,live)); + nth_take_range(slots,len,idx); +} + +lem restore_slot_owner(t: thread_id_t, slots: list>, len: usize, idx: usize, value: T) + req 0 <= idx &*& idx < len &*& len <= length(slots) &*& + slot_owners(t,take(idx,slots)) &*& slot_owners(t,drop(idx+1,take(len,slots))) &*& .own(t,value); + ens slot_owners(t,take(len,replace_slot(idx,MaybeUninit::new(value),slots))); +{ + let head = take(idx,slots); + let middle = [MaybeUninit::new(value)]; + let tail = drop(idx+1,take(len,slots)); + take_after_drop(slots,idx+1,len-idx-1); + length_take(idx,slots); + length_append(head,middle); + append_assoc(head,middle,drop(idx+1,slots)); + take_append(len,append(head,middle),drop(idx+1,slots)); + close slot_owners::(t,nil); + close slot_owners(t,middle); + join_slot_owners(t,head,middle); + join_slot_owners(t,append(head,middle),tail); +} + +lem join_stolen_prefix( + t: thread_id_t, l: list>, r: list>, + shifted: list>, copied: list>, written: list>, + left_len: usize, right_len: usize, count: usize, saved: T +) + req 0 < count &*& count <= left_len &*& left_len <= length(l) &*& + 0 <= right_len &*& right_len+count <= length(r) &*& + shifted == append(take(count,take(right_len+count,r)),append(take(right_len,r),drop(right_len+count,r))) &*& + copied == append(take(count-1,drop(left_len-count+1,l)),drop(count-1,shifted)) &*& + written == replace_slot(count-1,MaybeUninit::new(saved),copied) &*& + slot_owners(t,drop(left_len-count+1,take(left_len,l))) &*& + slot_owners(t,take(right_len,r)) &*& .own(t,saved); + ens slot_owners(t,take(right_len+count,written)); +{ + let stolen = take(count-1,drop(left_len-count+1,l)); + let kept = take(right_len,r); + let prefix = take(count,take(right_len+count,r)); + let tail = drop(right_len+count,r); + let separator = [MaybeUninit::new(saved)]; + length_take(right_len+count,r); + length_take(count,take(right_len+count,r)); + take_after_drop(l,left_len-count+1,count-1); + length_drop(left_len-count+1,l); + length_take(count-1,drop(left_len-count+1,l)); + take_append_l(count-1,stolen,drop(count-1,shifted)); + take_length(stolen); + drop_append(count,stolen,drop(count-1,shifted)); + drop_twice(1,count-1,shifted); + drop_append(count,prefix,append(kept,tail)); + drop_0(append(kept,tail)); + append_assoc(stolen,separator,append(kept,tail)); + append_assoc(append(stolen,separator),kept,tail); + length_take(right_len,r); + length_append(stolen,separator); + length_append(append(stolen,separator),kept); + take_append_l(right_len+count,append(append(stolen,separator),kept),tail); + take_length(append(append(stolen,separator),kept)); + close slot_owners::(t,nil); + close slot_owners(t,separator); + join_slot_owners(t,stolen,separator); + join_slot_owners(t,append(stolen,separator),kept); +} + +lem join_right_steal( + t: thread_id_t, l: list>, r: list>, + written: list>, copied: list>, shifted: list>, + left_len: usize, right_len: usize, count: usize, saved: T +) + req 0 < count &*& count <= right_len &*& right_len <= length(r) &*& + 0 <= left_len &*& left_len+count <= length(l) &*& + written == replace_slot(left_len,MaybeUninit::new(saved),l) &*& + copied == append(take(left_len+1,written),append(take(count-1,r),drop(left_len+count,written))) &*& + shifted == append(append(drop(count,take(right_len,r)),drop(right_len-count,take(right_len,r))),drop(right_len,r)) &*& + slot_owners(t,take(count-1,take(right_len,r))) &*& slot_owners(t,drop(count,take(right_len,r))) &*& + slot_owners(t,take(left_len,l)) &*& .own(t,saved); + ens slot_owners(t,take(left_len+count,copied)) &*& slot_owners(t,take(right_len-count,shifted)); +{ + let kept_left = take(left_len,l); + let separator = [MaybeUninit::new(saved)]; + let left_head = append(kept_left,separator); + let stolen = take(count-1,r); + let kept_right = drop(count,take(right_len,r)); + length_take(left_len,l); + length_append(kept_left,separator); + append_assoc(kept_left,separator,drop(left_len+1,l)); + assert written == append(left_head,drop(left_len+1,l)); + take_append_l(left_len+1,left_head,drop(left_len+1,l)); + take_length(left_head); + assert take(left_len+1,written) == left_head; + take_twice(r,count-1,right_len); + length_take(count-1,r); + append_assoc(left_head,stolen,drop(left_len+count,written)); + length_append(left_head,stolen); + take_append_l(left_len+count,append(left_head,stolen),drop(left_len+count,written)); + take_length(append(left_head,stolen)); + close slot_owners::(t,nil); + close slot_owners(t,separator); + join_slot_owners(t,kept_left,separator); + join_slot_owners(t,left_head,stolen); + length_take(right_len,r); + length_drop(count,take(right_len,r)); + append_assoc(kept_right,drop(right_len-count,take(right_len,r)),drop(right_len,r)); + take_append_l(right_len-count,kept_right,append(drop(right_len-count,take(right_len,r)),drop(right_len,r))); + take_length(kept_right); +} +@*/ + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { + unsafe fn bulk_steal_left_production<'short>(&'short mut self, count: usize) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& *self |-> ?incoming &*& + leaf_header(incoming.parent.node.node.as_ptr(),?parent_parent,?parent_index) &*& + owned_leaf_slots(t,incoming.parent.node.node.as_ptr(),?parent_len) &*& + 0 <= incoming.parent.idx &*& incoming.parent.idx < parent_len &*& + leaf_header(incoming.left_child.node.as_ptr(),?left_parent,?left_index) &*& + leaf_header(incoming.right_child.node.as_ptr(),?right_parent,?right_index) &*& + owned_leaf_slots(t,incoming.left_child.node.as_ptr(),?left_len) &*& + owned_leaf_slots(t,incoming.right_child.node.as_ptr(),?right_len) &*& + 0 < count &*& count <= left_len &*& right_len + count <= CAPACITY + &*& incoming.left_child.height == incoming.right_child.height + &*& 0 <= incoming.left_child.height &*& incoming.left_child.height <= usize::MAX + &*& balancing_child_padding(incoming.left_child.node,incoming.left_child.height) + &*& balancing_child_padding(incoming.right_child.node,incoming.right_child.height) + &*& balancing_child_edges(incoming.left_child.node,incoming.left_child.height,left_len,?left_children) + &*& balancing_child_edges(incoming.right_child.node,incoming.right_child.height,right_len,?right_children); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& *self |-> incoming &*& + leaf_header(incoming.parent.node.node.as_ptr(),parent_parent,parent_index) &*& + owned_leaf_slots(t,incoming.parent.node.node.as_ptr(),parent_len) &*& + leaf_header(incoming.left_child.node.as_ptr(),left_parent,left_index) &*& + leaf_header(incoming.right_child.node.as_ptr(),right_parent,right_index) &*& + owned_leaf_slots(t,incoming.left_child.node.as_ptr(),left_len - count) &*& + owned_leaf_slots(t,incoming.right_child.node.as_ptr(),right_len + count) + &*& balancing_child_padding(incoming.left_child.node,incoming.left_child.height) + &*& balancing_child_padding(incoming.right_child.node,incoming.right_child.height) + &*& balancing_child_edges(incoming.left_child.node,incoming.left_child.height,left_len - count,take(left_len-count+1,left_children)) + &*& balancing_child_edges(incoming.right_child.node,incoming.right_child.height,right_len + count,append(drop(left_len-count+1,left_children),right_children)); + @*/ + //@ on_unwind_ens false; + { + assert!(count > 0); + //@ let left = incoming.left_child.node.as_ptr(); + //@ let right = incoming.right_child.node.as_ptr(); + //@ open_points_to(self); + //@ close_points_to(&(*self).left_child); + let left_node = &mut self.left_child; //~track_ref_creation + //@ open owned_leaf_slots(t,left,left_len); + //@ open leaf_slots(left,left_len,?left_keys,?left_vals); + //@ let left_view = precreate_ref(left_node); + //@ init_ref_readonly(left_view,1/2); + let old_left_len = unsafe { left_node.merge_len() }; + //@ end_ref_readonly(left_view); + //@ merge_fractions points_to(left_node, _); + + //@ close_points_to(&(*self).right_child); + let right_node = &mut self.right_child; //~track_ref_creation + //@ open owned_leaf_slots(t,right,right_len); + //@ open leaf_slots(right,right_len,?right_keys,?right_vals); + //@ let right_view = precreate_ref(right_node); + //@ init_ref_readonly(right_view,1/2); + let old_right_len = unsafe { right_node.merge_len() }; + //@ end_ref_readonly(right_view); + //@ merge_fractions points_to(right_node, _); + assert!(old_right_len + count <= CAPACITY); + assert!(old_left_len >= count); + + let new_left_len = old_left_len - count; + let new_right_len = old_right_len + count; + //@ open leaf_header(left,left_parent,left_index); + //@ close leaf_without_len(left,left_parent,left_index,left_keys,left_vals); + *left_node.len_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/() = new_left_len as u16; + //@ assert len_loan(left,?left_mut,left_parent,left_index,left_keys,left_vals); + //@ end_len_loan(left,left_mut); + //@ open leaf_without_len(left,left_parent,left_index,left_keys,left_vals); + //@ close leaf_header(left,left_parent,left_index); + //@ close leaf_slots(left,new_left_len,left_keys,left_vals); + //@ open leaf_header(right,right_parent,right_index); + //@ close leaf_without_len(right,right_parent,right_index,right_keys,right_vals); + *right_node.len_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/() = new_right_len as u16; + //@ assert len_loan(right,?right_mut,right_parent,right_index,right_keys,right_vals); + //@ end_len_loan(right,right_mut); + //@ open leaf_without_len(right,right_parent,right_index,right_keys,right_vals); + //@ close leaf_header(right,right_parent,right_index); + //@ close leaf_slots(right,new_right_len,right_keys,right_vals); + //@ open leaf_slots(left,new_left_len,left_keys,left_vals); + //@ open leaf_slots(right,new_right_len,right_keys,right_vals); + //@ assert length(left_keys) == CAPACITY; + //@ assert length(left_vals) == CAPACITY; + //@ assert length(right_keys) == CAPACITY; + //@ assert length(right_vals) == CAPACITY; + { + //@ close leaf_without_keys(right,right_parent,right_index,new_right_len as u16,right_vals); + slice_shr(right_node.key_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..new_right_len), count); + //@ assert keys_range_loan(right,?keys_shift,0,new_right_len,right_parent,right_index,new_right_len as u16,right_vals,_,_); + //@ end_keys_range(right,keys_shift); + //@ open leaf_without_keys(right,right_parent,right_index,new_right_len as u16,right_vals); + //@ take_0(right_keys); + //@ drop_0(right_keys); + //@ take_twice(right_keys,old_right_len,new_right_len); + //@ length_take(new_right_len,right_keys); + //@ length_take(count,take(new_right_len,right_keys)); + //@ append_assoc(take(count,take(new_right_len,right_keys)),take(old_right_len,right_keys),drop(new_right_len,right_keys)); + //@ drop_append(count,take(count,take(new_right_len,right_keys)),append(take(old_right_len,right_keys),drop(new_right_len,right_keys))); + //@ drop_0(append(take(old_right_len,right_keys),drop(new_right_len,right_keys))); + //@ assert (*right).keys[..CAPACITY] |-> ?shifted_keys; + //@ close leaf_without_vals(right,right_parent,right_index,new_right_len as u16,shifted_keys); + slice_shr(right_node.val_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..new_right_len), count); + //@ assert vals_range_loan(right,?vals_shift,0,new_right_len,right_parent,right_index,new_right_len as u16,shifted_keys,_,_); + //@ end_vals_range(right,vals_shift); + //@ open leaf_without_vals(right,right_parent,right_index,new_right_len as u16,shifted_keys); + //@ take_0(right_vals); + //@ drop_0(right_vals); + //@ take_twice(right_vals,old_right_len,new_right_len); + //@ length_take(new_right_len,right_vals); + //@ length_take(count,take(new_right_len,right_vals)); + //@ append_assoc(take(count,take(new_right_len,right_vals)),take(old_right_len,right_vals),drop(new_right_len,right_vals)); + //@ drop_append(count,take(count,take(new_right_len,right_vals)),append(take(old_right_len,right_vals),drop(new_right_len,right_vals))); + //@ drop_0(append(take(old_right_len,right_vals),drop(new_right_len,right_vals))); + //@ assert (*right).vals[..CAPACITY] |-> ?shifted_vals; + //@ close leaf_without_keys(left,left_parent,left_index,new_left_len as u16,left_vals); + //@ close leaf_without_keys(right,right_parent,right_index,new_right_len as u16,shifted_vals); + move_to_slice( + left_node.key_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(new_left_len + 1..old_left_len), + right_node.key_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..count - 1), + ); + //@ assert keys_range_loan(left,?keys_source,new_left_len+1,old_left_len,left_parent,left_index,new_left_len as u16,left_vals,_,_); + //@ end_keys_range(left,keys_source); + //@ open leaf_without_keys(left,left_parent,left_index,new_left_len as u16,left_vals); + //@ assert keys_range_loan(right,?keys_dest,0,count-1,right_parent,right_index,new_right_len as u16,shifted_vals,_,_); + //@ end_keys_range(right,keys_dest); + //@ open leaf_without_keys(right,right_parent,right_index,new_right_len as u16,shifted_vals); + //@ take_0(left_keys); + //@ drop_0(left_keys); + //@ take_after_drop(left_keys,new_left_len+1,count-1); + //@ take_twice(left_keys,new_left_len+1,old_left_len); + //@ append_take_drop_n(take(old_left_len,left_keys),new_left_len+1); + //@ append_assoc(take(new_left_len+1,left_keys),take(count-1,drop(new_left_len+1,left_keys)),drop(old_left_len,left_keys)); + //@ append_take_drop_n(left_keys,old_left_len); + //@ assert (*left).keys[..CAPACITY] |-> left_keys; + //@ take_0(shifted_keys); + //@ drop_0(left_keys); + //@ assert (*right).keys[..CAPACITY] |-> ?copied_keys; + //@ close leaf_without_vals(left,left_parent,left_index,new_left_len as u16,left_keys); + //@ close leaf_without_vals(right,right_parent,right_index,new_right_len as u16,copied_keys); + move_to_slice( + left_node.val_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(new_left_len + 1..old_left_len), + right_node.val_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..count - 1), + ); + //@ assert vals_range_loan(left,?vals_source,new_left_len+1,old_left_len,left_parent,left_index,new_left_len as u16,left_keys,_,_); + //@ end_vals_range(left,vals_source); + //@ open leaf_without_vals(left,left_parent,left_index,new_left_len as u16,left_keys); + //@ assert vals_range_loan(right,?vals_dest,0,count-1,right_parent,right_index,new_right_len as u16,copied_keys,_,_); + //@ end_vals_range(right,vals_dest); + //@ open leaf_without_vals(right,right_parent,right_index,new_right_len as u16,copied_keys); + //@ take_0(left_vals); + //@ drop_0(left_vals); + //@ take_after_drop(left_vals,new_left_len+1,count-1); + //@ take_twice(left_vals,new_left_len+1,old_left_len); + //@ append_take_drop_n(take(old_left_len,left_vals),new_left_len+1); + //@ append_assoc(take(new_left_len+1,left_vals),take(count-1,drop(new_left_len+1,left_vals)),drop(old_left_len,left_vals)); + //@ append_take_drop_n(left_vals,old_left_len); + //@ assert (*left).vals[..CAPACITY] |-> left_vals; + //@ take_0(shifted_vals); + //@ drop_0(left_vals); + //@ assert (*right).vals[..CAPACITY] |-> ?copied_vals; + //@ let original_keys = take(old_left_len,left_keys); + //@ length_take(old_left_len,left_keys); + //@ split_slot_owners(t,original_keys,new_left_len); + //@ drop_n_plus_one(new_left_len,original_keys); + //@ open slot_owners(t,drop(new_left_len,original_keys)); + //@ nth_take_range(left_keys,old_left_len,new_left_len); + //@ close leaf_without_keys(left,left_parent,left_index,new_left_len as u16,left_vals); + let donated_keys_slot = left_node.key_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(new_left_len); + //@ assert keys_slot_loan(left,donated_keys_slot,new_left_len,left_parent,left_index,new_left_len as u16,left_vals,_,_); + //@ let keys_view = precreate_ref(donated_keys_slot); + //@ init_ref_readonly(keys_view,1/2); + let k = donated_keys_slot.assume_init_read(); + //@ end_ref_readonly(keys_view); + //@ merge_fractions points_to(donated_keys_slot, _); + //@ end_keys_slot(left,donated_keys_slot); + //@ open leaf_without_keys(left,left_parent,left_index,new_left_len as u16,left_vals); + //@ nth_at_partition(left_keys,new_left_len); + //@ assert (*left).keys[..CAPACITY] |-> left_keys; + //@ let donation_keys = k; + //@ let original_vals = take(old_left_len,left_vals); + //@ length_take(old_left_len,left_vals); + //@ split_slot_owners(t,original_vals,new_left_len); + //@ drop_n_plus_one(new_left_len,original_vals); + //@ open slot_owners(t,drop(new_left_len,original_vals)); + //@ nth_take_range(left_vals,old_left_len,new_left_len); + //@ close leaf_without_vals(left,left_parent,left_index,new_left_len as u16,left_keys); + let donated_vals_slot = left_node.val_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(new_left_len); + //@ assert vals_slot_loan(left,donated_vals_slot,new_left_len,left_parent,left_index,new_left_len as u16,left_keys,_,_); + //@ let vals_view = precreate_ref(donated_vals_slot); + //@ init_ref_readonly(vals_view,1/2); + let v = donated_vals_slot.assume_init_read(); + //@ end_ref_readonly(vals_view); + //@ merge_fractions points_to(donated_vals_slot, _); + //@ end_vals_slot(left,donated_vals_slot); + //@ open leaf_without_vals(left,left_parent,left_index,new_left_len as u16,left_keys); + //@ nth_at_partition(left_vals,new_left_len); + //@ assert (*left).vals[..CAPACITY] |-> left_vals; + //@ let donation_vals = v; + //@ let parent = incoming.parent.node.node.as_ptr(); + //@ let separator = incoming.parent.idx; + //@ open owned_leaf_slots(t,parent,parent_len); + //@ assert leaf_slots(parent,parent_len,?parent_keys,?parent_vals); + //@ open leaf_slots(parent,parent_len,parent_keys,parent_vals); + //@ open_slot_owner(t,parent_keys,parent_len,separator); + //@ open_slot_owner(t,parent_vals,parent_len,separator); + //@ close leaf_slots(parent,parent_len,parent_keys,parent_vals); + //@ close_points_to(&(*self).parent); + let (separator_key, separator_value) = self.parent.replace_kv_production/*@::<'a,K,V,marker::Internal,'short>@*/(k, v); //~track_ref_creation + //@ assert ref_mut_end_token(?parent_view,&(*self).parent); + //@ end_ref_mut(parent_view); + //@ open_points_to(&(*self).parent); + //@ assert leaf_slots(parent,parent_len,?replaced_keys,?replaced_vals); + //@ restore_slot_owner(t,parent_keys,parent_len,separator,donation_keys); + //@ restore_slot_owner(t,parent_vals,parent_len,separator,donation_vals); + //@ close owned_leaf_slots(t,parent,parent_len); + //@ close leaf_without_keys(right,right_parent,right_index,new_right_len as u16,copied_vals); + right_node.key_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(count - 1).write(separator_key); + //@ assert keys_slot_loan(right,?recipient_keys_slot,count - 1,right_parent,right_index,new_right_len as u16,copied_vals,_,_); + //@ end_keys_slot(right,recipient_keys_slot); + //@ open leaf_without_keys(right,right_parent,right_index,new_right_len as u16,copied_vals); + //@ assert (*right).keys[..CAPACITY] |-> ?written_keys; + //@ close leaf_without_vals(right,right_parent,right_index,new_right_len as u16,written_keys); + right_node.val_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(count - 1).write(separator_value); + //@ assert vals_slot_loan(right,?recipient_vals_slot,count - 1,right_parent,right_index,new_right_len as u16,written_keys,_,_); + //@ end_vals_slot(right,recipient_vals_slot); + //@ open leaf_without_vals(right,right_parent,right_index,new_right_len as u16,written_keys); + //@ assert (*right).vals[..CAPACITY] |-> ?written_vals; + //@ take_twice(left_keys,new_left_len,old_left_len); + //@ take_after_drop(left_keys,new_left_len+1,count-1); + //@ drop_twice(1,new_left_len,original_keys); + //@ join_stolen_prefix(t,left_keys,right_keys,shifted_keys,copied_keys,written_keys,old_left_len,old_right_len,count,separator_key); + //@ take_twice(left_vals,new_left_len,old_left_len); + //@ take_after_drop(left_vals,new_left_len+1,count-1); + //@ drop_twice(1,new_left_len,original_vals); + //@ join_stolen_prefix(t,left_vals,right_vals,shifted_vals,copied_vals,written_vals,old_left_len,old_right_len,count,separator_value); + } + //@ close leaf_slots(left,new_left_len,left_keys,left_vals); + //@ close leaf_slots(right,new_right_len,written_keys,written_vals); + //@ close owned_leaf_slots(t,left,new_left_len); + //@ close owned_leaf_slots(t,right,new_right_len); + //@ let height = incoming.left_child.height; + //@ open balancing_child_edges(incoming.left_child.node,height,left_len,left_children); + //@ open balancing_child_edges(incoming.right_child.node,height,right_len,right_children); + match ( + left_node.reborrow_mut/*@::,K,V,marker::LeafOrInternal,'short>@*/().force/*@::,K,V>@*/(), + right_node.reborrow_mut/*@::,K,V,marker::LeafOrInternal,'short>@*/().force/*@::,K,V>@*/(), + ) { + (ForceResult::Internal(mut left_internal), ForceResult::Internal(mut right_internal)) => { + //@ let left_edges = NonNull::new(left as *InternalNode); + //@ let right_edges = NonNull::new(right as *InternalNode); + //@ std::ptr::NonNull_as_ptr_new(left as *InternalNode); + //@ std::ptr::NonNull_as_ptr_new(right as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(left_edges); + //@ std::ptr::NonNull_Sized_as_ptr(right_edges); + //@ assert &(*left_edges.as_ptr()).data == left; + //@ assert &(*right_edges.as_ptr()).data == right; + //@ open owned_leaf_slots(t,left,new_left_len); + //@ open owned_leaf_slots(t,right,new_right_len); + //@ open leaf_slots(left,new_left_len,_,_); + //@ open leaf_slots(right,new_right_len,_,_); + //@ open leaf_header(left,left_parent,left_index); + //@ open leaf_header(right,right_parent,right_index); + //@ open balancing_child_padding(incoming.left_child.node,height); + //@ open balancing_child_padding(incoming.right_child.node,height); + //@ close_points_to(left); + //@ close_points_to(right); + //@ close internal_without_edges(left_edges.as_ptr(),?left_data); + //@ close internal_without_edges(right_edges.as_ptr(),?right_data); + //@ close_points_to(&mut left_internal); + //@ close_points_to(&mut right_internal); + //@ open balancing_edges(left_edges,left_children,?left_slots); + //@ open balancing_edges(right_edges,right_children,?right_slots); + //@ let kept = take(new_left_len+1,left_children); + //@ let moved = drop(new_left_len+1,left_children); + //@ let shifted_children = append(moved,right_children); + //@ let tail = drop(new_right_len+1,right_slots); + //@ let saved = take(count,take(new_right_len+1,right_slots)); + //@ initialized_edge_split(left_children,new_left_len+1); + //@ initialized_edge_count(kept); + //@ initialized_edge_count(moved); + //@ initialized_edge_count(right_children); + //@ length_take(new_left_len+1,left_children); + //@ length_drop(new_left_len+1,left_children); + //@ split_linked_headers(left_children,left_edges,0,new_left_len+1); + //@ forget_link_indices(moved,left_edges,new_left_len+1); + //@ forget_link_indices(right_children,right_edges,0); + //@ join_child_headers(moved,right_children); + //@ initialized_edges_append(moved,right_children); + unsafe { + slice_shr(right_internal.edge_area_prefix_mut/*@::<'a,K,V,'short>@*/(..new_right_len + 1), count); + //@ assert edges_range_loan(right_edges.as_ptr(),?shifted,0,new_right_len+1,right_data,_,_); + //@ end_edges_range(right_edges.as_ptr(),shifted); + //@ take_twice(right_slots,old_right_len+1,new_right_len+1); + //@ append_assoc(saved,initialized_edges(right_children),tail); + //@ length_take(new_right_len+1,right_slots); + //@ length_take(count,take(new_right_len+1,right_slots)); + //@ drop_append(count,saved,append(initialized_edges(right_children),tail)); + //@ drop_0(append(initialized_edges(right_children),tail)); + move_to_slice( + left_internal.edge_area_range_mut/*@::<'a,K,V,'short>@*/(new_left_len + 1..old_left_len + 1), + right_internal.edge_area_prefix_mut/*@::<'a,K,V,'short>@*/(..count), + ); + //@ assert edges_range_loan(left_edges.as_ptr(),?source,new_left_len+1,old_left_len+1,left_data,_,_); + //@ assert edges_range_loan(right_edges.as_ptr(),?destination,0,count,right_data,_,_); + //@ end_edges_range(left_edges.as_ptr(),source); + //@ end_edges_range(right_edges.as_ptr(),destination); + //@ take_after_drop(left_slots,new_left_len+1,count); + //@ append_take_drop_n(take(old_left_len+1,left_slots),new_left_len+1); + //@ append_take_drop_n(left_slots,old_left_len+1); + //@ take_twice(left_slots,new_left_len+1,old_left_len+1); + //@ append_assoc(take(new_left_len+1,left_slots),take(count,drop(new_left_len+1,left_slots)),drop(old_left_len+1,left_slots)); + //@ append_assoc(initialized_edges(moved),initialized_edges(right_children),tail); + + //@ open internal_without_edges(right_edges.as_ptr(),right_data); + //@ open_points_to(&(*right_edges.as_ptr()).data); + //@ close exists(right_edges); + //@ close exists(pair(nil::>>,tail)); + //@ length_append(moved,right_children); + right_internal.relink_range/*@::<'a,K,V,'short>@*/(0..new_right_len + 1); + //@ close_points_to(&(*right_edges.as_ptr()).data); + //@ close internal_without_edges(right_edges.as_ptr(),right_data); + //@ initialized_edge_count(shifted_children); + //@ take_append_l(new_right_len+1,initialized_edges(shifted_children),tail); + //@ take_length(initialized_edges(shifted_children)); + //@ take_twice(left_slots,new_left_len+1,old_left_len+1); + //@ close balancing_edges(left_edges,kept,left_slots); + //@ close balancing_edges(right_edges,shifted_children,_); + } + //@ open internal_without_edges(left_edges.as_ptr(),left_data); + //@ open_points_to(left); + //@ close leaf_header(left,left_parent,left_index); + //@ close leaf_slots(left,new_left_len,_,_); + //@ close owned_leaf_slots(t,left,new_left_len); + //@ close balancing_child_padding(incoming.left_child.node,height); + //@ open internal_without_edges(right_edges.as_ptr(),right_data); + //@ open_points_to(right); + //@ close leaf_header(right,right_parent,right_index); + //@ close leaf_slots(right,new_right_len,_,_); + //@ close owned_leaf_slots(t,right,new_right_len); + //@ close balancing_child_padding(incoming.right_child.node,height); + //@ open_points_to(&mut left_internal); + //@ open_points_to(&mut right_internal); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} + _ => unreachable!(), + } + //@ close balancing_child_edges(incoming.left_child.node,height,new_left_len,take(left_len-count+1,left_children)); + //@ close balancing_child_edges(incoming.right_child.node,height,new_right_len,append(drop(left_len-count+1,left_children),right_children)); + //@ end_ref_mut(right_node); + //@ end_ref_mut(left_node); + //@ close_points_to(self); + } + + unsafe fn bulk_steal_right_production<'short>(&'short mut self, count: usize) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& *self |-> ?incoming &*& + leaf_header(incoming.parent.node.node.as_ptr(),?parent_parent,?parent_index) &*& + owned_leaf_slots(t,incoming.parent.node.node.as_ptr(),?parent_len) &*& + 0 <= incoming.parent.idx &*& incoming.parent.idx < parent_len &*& + leaf_header(incoming.left_child.node.as_ptr(),?left_parent,?left_index) &*& + leaf_header(incoming.right_child.node.as_ptr(),?right_parent,?right_index) &*& + owned_leaf_slots(t,incoming.left_child.node.as_ptr(),?left_len) &*& + owned_leaf_slots(t,incoming.right_child.node.as_ptr(),?right_len) &*& + 0 < count &*& count <= right_len &*& left_len + count <= CAPACITY + &*& incoming.left_child.height == incoming.right_child.height + &*& 0 <= incoming.left_child.height &*& incoming.left_child.height <= usize::MAX + &*& balancing_child_padding(incoming.left_child.node,incoming.left_child.height) + &*& balancing_child_padding(incoming.right_child.node,incoming.right_child.height) + &*& balancing_child_edges(incoming.left_child.node,incoming.left_child.height,left_len,?left_children) + &*& balancing_child_edges(incoming.right_child.node,incoming.right_child.height,right_len,?right_children); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& *self |-> incoming &*& + leaf_header(incoming.parent.node.node.as_ptr(),parent_parent,parent_index) &*& + owned_leaf_slots(t,incoming.parent.node.node.as_ptr(),parent_len) &*& + leaf_header(incoming.left_child.node.as_ptr(),left_parent,left_index) &*& + leaf_header(incoming.right_child.node.as_ptr(),right_parent,right_index) &*& + owned_leaf_slots(t,incoming.left_child.node.as_ptr(),left_len + count) &*& + owned_leaf_slots(t,incoming.right_child.node.as_ptr(),right_len - count) + &*& balancing_child_padding(incoming.left_child.node,incoming.left_child.height) + &*& balancing_child_padding(incoming.right_child.node,incoming.right_child.height) + &*& balancing_child_edges(incoming.left_child.node,incoming.left_child.height,left_len + count,append(left_children,take(count,right_children))) + &*& balancing_child_edges(incoming.right_child.node,incoming.right_child.height,right_len - count,drop(count,right_children)); + @*/ + //@ on_unwind_ens false; + { + assert!(count > 0); + //@ let left = incoming.left_child.node.as_ptr(); + //@ let right = incoming.right_child.node.as_ptr(); + //@ open_points_to(self); + //@ close_points_to(&(*self).left_child); + let left_node = &mut self.left_child; //~track_ref_creation + //@ open owned_leaf_slots(t,left,left_len); + //@ open leaf_slots(left,left_len,?left_keys,?left_vals); + //@ let left_view = precreate_ref(left_node); + //@ init_ref_readonly(left_view,1/2); + let old_left_len = unsafe { left_node.merge_len() }; + //@ end_ref_readonly(left_view); + //@ merge_fractions points_to(left_node, _); + + //@ close_points_to(&(*self).right_child); + let right_node = &mut self.right_child; //~track_ref_creation + //@ open owned_leaf_slots(t,right,right_len); + //@ open leaf_slots(right,right_len,?right_keys,?right_vals); + //@ let right_view = precreate_ref(right_node); + //@ init_ref_readonly(right_view,1/2); + let old_right_len = unsafe { right_node.merge_len() }; + //@ end_ref_readonly(right_view); + //@ merge_fractions points_to(right_node, _); + assert!(old_left_len + count <= CAPACITY); + assert!(old_right_len >= count); + + let new_left_len = old_left_len + count; + let new_right_len = old_right_len - count; + //@ open leaf_header(left,left_parent,left_index); + //@ close leaf_without_len(left,left_parent,left_index,left_keys,left_vals); + *left_node.len_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/() = new_left_len as u16; + //@ assert len_loan(left,?left_mut,left_parent,left_index,left_keys,left_vals); + //@ end_len_loan(left,left_mut); + //@ open leaf_without_len(left,left_parent,left_index,left_keys,left_vals); + //@ close leaf_header(left,left_parent,left_index); + //@ close leaf_slots(left,new_left_len,left_keys,left_vals); + //@ open leaf_header(right,right_parent,right_index); + //@ close leaf_without_len(right,right_parent,right_index,right_keys,right_vals); + *right_node.len_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/() = new_right_len as u16; + //@ assert len_loan(right,?right_mut,right_parent,right_index,right_keys,right_vals); + //@ end_len_loan(right,right_mut); + //@ open leaf_without_len(right,right_parent,right_index,right_keys,right_vals); + //@ close leaf_header(right,right_parent,right_index); + //@ close leaf_slots(right,new_right_len,right_keys,right_vals); + //@ open leaf_slots(left,new_left_len,left_keys,left_vals); + //@ open leaf_slots(right,new_right_len,right_keys,right_vals); + //@ assert length(left_keys) == CAPACITY; + //@ assert length(left_vals) == CAPACITY; + //@ assert length(right_keys) == CAPACITY; + //@ assert length(right_vals) == CAPACITY; + { + //@ let original_keys = take(old_right_len,right_keys); + //@ length_take(old_right_len,right_keys); + //@ split_slot_owners(t,original_keys,count - 1); + //@ drop_n_plus_one(count - 1,original_keys); + //@ open slot_owners(t,drop(count - 1,original_keys)); + //@ nth_take_range(right_keys,old_right_len,count - 1); + //@ close leaf_without_keys(right,right_parent,right_index,new_right_len as u16,right_vals); + let donated_keys_slot = right_node.key_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(count - 1); + //@ assert keys_slot_loan(right,donated_keys_slot,count - 1,right_parent,right_index,new_right_len as u16,right_vals,_,_); + //@ let keys_view = precreate_ref(donated_keys_slot); + //@ init_ref_readonly(keys_view,1/2); + let k = donated_keys_slot.assume_init_read(); + //@ end_ref_readonly(keys_view); + //@ merge_fractions points_to(donated_keys_slot, _); + //@ end_keys_slot(right,donated_keys_slot); + //@ open leaf_without_keys(right,right_parent,right_index,new_right_len as u16,right_vals); + //@ nth_at_partition(right_keys,count - 1); + //@ assert (*right).keys[..CAPACITY] |-> right_keys; + //@ let donation_keys = k; + //@ let original_vals = take(old_right_len,right_vals); + //@ length_take(old_right_len,right_vals); + //@ split_slot_owners(t,original_vals,count - 1); + //@ drop_n_plus_one(count - 1,original_vals); + //@ open slot_owners(t,drop(count - 1,original_vals)); + //@ nth_take_range(right_vals,old_right_len,count - 1); + //@ close leaf_without_vals(right,right_parent,right_index,new_right_len as u16,right_keys); + let donated_vals_slot = right_node.val_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(count - 1); + //@ assert vals_slot_loan(right,donated_vals_slot,count - 1,right_parent,right_index,new_right_len as u16,right_keys,_,_); + //@ let vals_view = precreate_ref(donated_vals_slot); + //@ init_ref_readonly(vals_view,1/2); + let v = donated_vals_slot.assume_init_read(); + //@ end_ref_readonly(vals_view); + //@ merge_fractions points_to(donated_vals_slot, _); + //@ end_vals_slot(right,donated_vals_slot); + //@ open leaf_without_vals(right,right_parent,right_index,new_right_len as u16,right_keys); + //@ nth_at_partition(right_vals,count - 1); + //@ assert (*right).vals[..CAPACITY] |-> right_vals; + //@ let donation_vals = v; + //@ let parent = incoming.parent.node.node.as_ptr(); + //@ let separator = incoming.parent.idx; + //@ open owned_leaf_slots(t,parent,parent_len); + //@ assert leaf_slots(parent,parent_len,?parent_keys,?parent_vals); + //@ open leaf_slots(parent,parent_len,parent_keys,parent_vals); + //@ open_slot_owner(t,parent_keys,parent_len,separator); + //@ open_slot_owner(t,parent_vals,parent_len,separator); + //@ close leaf_slots(parent,parent_len,parent_keys,parent_vals); + //@ close_points_to(&(*self).parent); + let (separator_key, separator_value) = self.parent.replace_kv_production/*@::<'a,K,V,marker::Internal,'short>@*/(k, v); //~track_ref_creation + //@ assert ref_mut_end_token(?parent_view,&(*self).parent); + //@ end_ref_mut(parent_view); + //@ open_points_to(&(*self).parent); + //@ assert leaf_slots(parent,parent_len,?replaced_keys,?replaced_vals); + //@ restore_slot_owner(t,parent_keys,parent_len,separator,donation_keys); + //@ restore_slot_owner(t,parent_vals,parent_len,separator,donation_vals); + //@ close owned_leaf_slots(t,parent,parent_len); + //@ close leaf_without_keys(left,left_parent,left_index,new_left_len as u16,left_vals); + left_node.key_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(old_left_len).write(separator_key); + //@ assert keys_slot_loan(left,?recipient_keys_slot,old_left_len,left_parent,left_index,new_left_len as u16,left_vals,_,_); + //@ end_keys_slot(left,recipient_keys_slot); + //@ open leaf_without_keys(left,left_parent,left_index,new_left_len as u16,left_vals); + //@ assert (*left).keys[..CAPACITY] |-> ?written_keys; + //@ close leaf_without_vals(left,left_parent,left_index,new_left_len as u16,written_keys); + left_node.val_area_slot_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(old_left_len).write(separator_value); + //@ assert vals_slot_loan(left,?recipient_vals_slot,old_left_len,left_parent,left_index,new_left_len as u16,written_keys,_,_); + //@ end_vals_slot(left,recipient_vals_slot); + //@ open leaf_without_vals(left,left_parent,left_index,new_left_len as u16,written_keys); + //@ assert (*left).vals[..CAPACITY] |-> ?written_vals; + //@ close leaf_without_keys(right,right_parent,right_index,new_right_len as u16,right_vals); + //@ close leaf_without_keys(left,left_parent,left_index,new_left_len as u16,written_vals); + move_to_slice( + right_node.key_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..count - 1), + left_node.key_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(old_left_len + 1..new_left_len), + ); + //@ assert keys_range_loan(right,?keys_source,0,count-1,right_parent,right_index,new_right_len as u16,right_vals,_,_); + //@ end_keys_range(right,keys_source); + //@ open leaf_without_keys(right,right_parent,right_index,new_right_len as u16,right_vals); + //@ assert keys_range_loan(left,?keys_dest,old_left_len+1,new_left_len,left_parent,left_index,new_left_len as u16,written_vals,_,_); + //@ end_keys_range(left,keys_dest); + //@ open leaf_without_keys(left,left_parent,left_index,new_left_len as u16,written_vals); + //@ take_0(right_keys); + //@ drop_0(right_keys); + //@ append_take_drop_n(right_keys,count-1); + //@ assert (*right).keys[..CAPACITY] |-> right_keys; + //@ take_0(written_keys); + //@ drop_0(right_keys); + //@ assert (*left).keys[..CAPACITY] |-> ?copied_keys; + //@ close leaf_without_vals(right,right_parent,right_index,new_right_len as u16,right_keys); + //@ close leaf_without_vals(left,left_parent,left_index,new_left_len as u16,copied_keys); + move_to_slice( + right_node.val_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..count - 1), + left_node.val_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(old_left_len + 1..new_left_len), + ); + //@ assert vals_range_loan(right,?vals_source,0,count-1,right_parent,right_index,new_right_len as u16,right_keys,_,_); + //@ end_vals_range(right,vals_source); + //@ open leaf_without_vals(right,right_parent,right_index,new_right_len as u16,right_keys); + //@ assert vals_range_loan(left,?vals_dest,old_left_len+1,new_left_len,left_parent,left_index,new_left_len as u16,copied_keys,_,_); + //@ end_vals_range(left,vals_dest); + //@ open leaf_without_vals(left,left_parent,left_index,new_left_len as u16,copied_keys); + //@ take_0(right_vals); + //@ drop_0(right_vals); + //@ append_take_drop_n(right_vals,count-1); + //@ assert (*right).vals[..CAPACITY] |-> right_vals; + //@ take_0(written_vals); + //@ drop_0(right_vals); + //@ assert (*left).vals[..CAPACITY] |-> ?copied_vals; + //@ close leaf_without_keys(right,right_parent,right_index,new_right_len as u16,right_vals); + slice_shl(right_node.key_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..old_right_len), count); + //@ assert keys_range_loan(right,?keys_shift,0,old_right_len,right_parent,right_index,new_right_len as u16,right_vals,_,_); + //@ end_keys_range(right,keys_shift); + //@ open leaf_without_keys(right,right_parent,right_index,new_right_len as u16,right_vals); + //@ take_0(right_keys); + //@ drop_0(right_keys); + //@ assert (*right).keys[..CAPACITY] |-> ?shifted_keys; + //@ close leaf_without_vals(right,right_parent,right_index,new_right_len as u16,shifted_keys); + slice_shl(right_node.val_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..old_right_len), count); + //@ assert vals_range_loan(right,?vals_shift,0,old_right_len,right_parent,right_index,new_right_len as u16,shifted_keys,_,_); + //@ end_vals_range(right,vals_shift); + //@ open leaf_without_vals(right,right_parent,right_index,new_right_len as u16,shifted_keys); + //@ take_0(right_vals); + //@ drop_0(right_vals); + //@ assert (*right).vals[..CAPACITY] |-> ?shifted_vals; + //@ join_right_steal(t,left_keys,right_keys,written_keys,copied_keys,shifted_keys,old_left_len,old_right_len,count,separator_key); + //@ join_right_steal(t,left_vals,right_vals,written_vals,copied_vals,shifted_vals,old_left_len,old_right_len,count,separator_value); + } + //@ close leaf_slots(left,new_left_len,copied_keys,copied_vals); + //@ close leaf_slots(right,new_right_len,shifted_keys,shifted_vals); + //@ close owned_leaf_slots(t,left,new_left_len); + //@ close owned_leaf_slots(t,right,new_right_len); + //@ let height = incoming.left_child.height; + //@ open balancing_child_edges(incoming.left_child.node,height,left_len,left_children); + //@ open balancing_child_edges(incoming.right_child.node,height,right_len,right_children); + match ( + left_node.reborrow_mut/*@::,K,V,marker::LeafOrInternal,'short>@*/().force/*@::,K,V>@*/(), + right_node.reborrow_mut/*@::,K,V,marker::LeafOrInternal,'short>@*/().force/*@::,K,V>@*/(), + ) { + (ForceResult::Internal(mut left_internal), ForceResult::Internal(mut right_internal)) => { + //@ let left_edges = NonNull::new(left as *InternalNode); + //@ let right_edges = NonNull::new(right as *InternalNode); + //@ std::ptr::NonNull_as_ptr_new(left as *InternalNode); + //@ std::ptr::NonNull_as_ptr_new(right as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(left_edges); + //@ std::ptr::NonNull_Sized_as_ptr(right_edges); + //@ assert &(*left_edges.as_ptr()).data == left; + //@ assert &(*right_edges.as_ptr()).data == right; + //@ open owned_leaf_slots(t,left,new_left_len); + //@ open owned_leaf_slots(t,right,new_right_len); + //@ open leaf_slots(left,new_left_len,_,_); + //@ open leaf_slots(right,new_right_len,_,_); + //@ open leaf_header(left,left_parent,left_index); + //@ open leaf_header(right,right_parent,right_index); + //@ open balancing_child_padding(incoming.left_child.node,height); + //@ open balancing_child_padding(incoming.right_child.node,height); + //@ close_points_to(left); + //@ close_points_to(right); + //@ close internal_without_edges(left_edges.as_ptr(),?left_data); + //@ close internal_without_edges(right_edges.as_ptr(),?right_data); + //@ close_points_to(&mut left_internal); + //@ close_points_to(&mut right_internal); + //@ open balancing_edges(left_edges,left_children,?left_slots); + //@ open balancing_edges(right_edges,right_children,?right_slots); + //@ let moved = take(count,right_children); + //@ let kept = drop(count,right_children); + //@ let before = take(old_left_len+1,left_slots); + //@ let left_tail = drop(new_left_len+1,left_slots); + //@ let inactive = drop(new_right_len+1,take(old_right_len+1,right_slots)); + //@ let right_tail = append(inactive,drop(old_right_len+1,right_slots)); + //@ let joined = append(left_children,moved); + //@ initialized_edge_split(right_children,count); + //@ initialized_edge_count(left_children); + //@ initialized_edge_count(moved); + //@ initialized_edge_count(kept); + //@ length_take(count,right_children); + //@ length_drop(count,right_children); + //@ split_linked_headers(right_children,right_edges,0,count); + //@ forget_link_indices(moved,right_edges,0); + //@ initialized_edges_append(left_children,moved); + unsafe { + move_to_slice( + right_internal.edge_area_prefix_mut/*@::<'a,K,V,'short>@*/(..count), + left_internal.edge_area_range_mut/*@::<'a,K,V,'short>@*/(old_left_len + 1..new_left_len + 1), + ); + //@ assert edges_range_loan(right_edges.as_ptr(),?source,0,count,right_data,_,_); + //@ assert edges_range_loan(left_edges.as_ptr(),?destination,old_left_len+1,new_left_len+1,left_data,_,_); + //@ end_edges_range(right_edges.as_ptr(),source); + //@ end_edges_range(left_edges.as_ptr(),destination); + //@ take_0(right_slots); + //@ drop_0(right_slots); + //@ append_take_drop_n(right_slots,count); + //@ take_twice(right_slots,count,old_right_len+1); + //@ append_assoc(before,initialized_edges(moved),left_tail); + slice_shl(right_internal.edge_area_prefix_mut/*@::<'a,K,V,'short>@*/(..old_right_len + 1), count); + //@ assert edges_range_loan(right_edges.as_ptr(),?shifted,0,old_right_len+1,right_data,_,_); + //@ end_edges_range(right_edges.as_ptr(),shifted); + //@ open internal_without_edges(left_edges.as_ptr(),left_data); + //@ open_points_to(&(*left_edges.as_ptr()).data); + //@ close exists(left_edges); + //@ close exists(pair(before,left_tail)); + //@ length_take(old_left_len+1,left_slots); + left_internal.relink_range/*@::<'a,K,V,'short>@*/(old_left_len + 1..new_left_len + 1); + //@ close_points_to(&(*left_edges.as_ptr()).data); + //@ close internal_without_edges(left_edges.as_ptr(),left_data); + + //@ forget_link_indices(kept,right_edges,count); + //@ open internal_without_edges(right_edges.as_ptr(),right_data); + //@ open_points_to(&(*right_edges.as_ptr()).data); + //@ close exists(right_edges); + //@ close exists(pair(nil::>>,right_tail)); + //@ take_0(right_slots); + //@ drop_0(right_slots); + //@ append_assoc(initialized_edges(kept),inactive,drop(old_right_len+1,right_slots)); + right_internal.relink_range/*@::<'a,K,V,'short>@*/(0..new_right_len + 1); + //@ close_points_to(&(*right_edges.as_ptr()).data); + //@ close internal_without_edges(right_edges.as_ptr(),right_data); + //@ join_linked_headers(left_children,moved,left_edges,0); + //@ length_append(left_children,moved); + //@ initialized_edge_count(joined); + //@ take_append_l(new_left_len+1,initialized_edges(joined),left_tail); + //@ take_length(initialized_edges(joined)); + //@ take_append_l(new_right_len+1,initialized_edges(kept),right_tail); + //@ take_length(initialized_edges(kept)); + //@ close balancing_edges(left_edges,joined,_); + //@ close balancing_edges(right_edges,kept,_); + } + //@ open internal_without_edges(left_edges.as_ptr(),left_data); + //@ open_points_to(left); + //@ close leaf_header(left,left_parent,left_index); + //@ close leaf_slots(left,new_left_len,_,_); + //@ close owned_leaf_slots(t,left,new_left_len); + //@ close balancing_child_padding(incoming.left_child.node,height); + //@ open internal_without_edges(right_edges.as_ptr(),right_data); + //@ open_points_to(right); + //@ close leaf_header(right,right_parent,right_index); + //@ close leaf_slots(right,new_right_len,_,_); + //@ close owned_leaf_slots(t,right,new_right_len); + //@ close balancing_child_padding(incoming.right_child.node,height); + //@ open_points_to(&mut left_internal); + //@ open_points_to(&mut right_internal); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} + _ => unreachable!(), + } + //@ close balancing_child_edges(incoming.left_child.node,height,new_left_len,append(left_children,take(count,right_children))); + //@ close balancing_child_edges(incoming.right_child.node,height,new_right_len,drop(count,right_children)); + //@ end_ref_mut(right_node); + //@ end_ref_mut(left_node); + //@ close_points_to(self); + } + + unsafe fn steal_left_production( + mut self, track_right_edge_idx: usize, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.parent.node.node.as_ptr(),?parent_parent,?parent_index) &*& + owned_leaf_slots(t,self.parent.node.node.as_ptr(),?parent_len) &*& + 0 <= self.parent.idx &*& self.parent.idx < parent_len &*& + leaf_header(self.left_child.node.as_ptr(),?left_parent,?left_index) &*& + leaf_header(self.right_child.node.as_ptr(),?right_parent,?right_index) &*& + owned_leaf_slots(t,self.left_child.node.as_ptr(),?left_len) &*& + owned_leaf_slots(t,self.right_child.node.as_ptr(),?right_len) &*& + 0 <= track_right_edge_idx &*& track_right_edge_idx <= right_len &*& 1 <= left_len &*& right_len + 1 <= CAPACITY + &*& self.left_child.height == self.right_child.height + &*& 0 <= self.left_child.height &*& self.left_child.height <= usize::MAX + &*& balancing_child_padding(self.left_child.node,self.left_child.height) + &*& balancing_child_padding(self.right_child.node,self.right_child.height) + &*& balancing_child_edges(self.left_child.node,self.left_child.height,left_len,?left_children) + &*& balancing_child_edges(self.right_child.node,self.right_child.height,right_len,?right_children); + @*/ + /*@ + ens result.node == self.right_child &*& result.idx == 1 + track_right_edge_idx &*& + thread_token(t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.parent.node.node.as_ptr(),parent_parent,parent_index) &*& + owned_leaf_slots(t,self.parent.node.node.as_ptr(),parent_len) &*& + leaf_header(self.left_child.node.as_ptr(),left_parent,left_index) &*& + leaf_header(self.right_child.node.as_ptr(),right_parent,right_index) &*& + owned_leaf_slots(t,self.left_child.node.as_ptr(),left_len - 1) &*& + owned_leaf_slots(t,self.right_child.node.as_ptr(),right_len + 1) + &*& balancing_child_padding(self.left_child.node,self.left_child.height) + &*& balancing_child_padding(self.right_child.node,self.right_child.height) + &*& balancing_child_edges(self.left_child.node,self.left_child.height,left_len - 1,take(left_len-1+1,left_children)) + &*& balancing_child_edges(self.right_child.node,self.right_child.height,right_len + 1,append(drop(left_len-1+1,left_children),right_children)); + @*/ + //@ on_unwind_ens false; + { + //@ assert *(&mut self) |-> ?original; + self.bulk_steal_left_production/*@::<'a,K,V,'a>@*/(1); //~track_ref_creation + //@ assert ref_mut_end_token(?context, &mut self); + //@ end_ref_mut(context); + //@ open_points_to(&mut self); + //@ let recipient = self.right_child.node.as_ptr(); + //@ close_points_to(&self.right_child); + //@ open owned_leaf_slots(t,recipient,right_len + 1); + //@ open leaf_slots(recipient,right_len + 1,_,_); + let edge = unsafe { + Handle::, K, V, marker::LeafOrInternal>, marker::Edge>::new_edge/*@::,K,V>@*/(self.right_child, 1 + track_right_edge_idx) + }; + //@ close leaf_slots(recipient,right_len + 1,_,_); + //@ close owned_leaf_slots(t,recipient,right_len + 1); + //@ close_points_to(&self.parent.node); + //@ close Handle_node_(&self.parent, some(original.parent.node)); + //@ close BalancingContext_parent_(&self, _); + //@ close NodeRef_node_(&self.left_child, some(original.left_child.node)); + //@ close BalancingContext_left_child_(&self, _); + //@ close NodeRef_node_(&self.right_child, _); + //@ close BalancingContext_right_child_(&self, _); + edge + } + + unsafe fn steal_right_production( + mut self, track_left_edge_idx: usize, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.parent.node.node.as_ptr(),?parent_parent,?parent_index) &*& + owned_leaf_slots(t,self.parent.node.node.as_ptr(),?parent_len) &*& + 0 <= self.parent.idx &*& self.parent.idx < parent_len &*& + leaf_header(self.left_child.node.as_ptr(),?left_parent,?left_index) &*& + leaf_header(self.right_child.node.as_ptr(),?right_parent,?right_index) &*& + owned_leaf_slots(t,self.left_child.node.as_ptr(),?left_len) &*& + owned_leaf_slots(t,self.right_child.node.as_ptr(),?right_len) &*& + 0 <= track_left_edge_idx &*& track_left_edge_idx <= left_len &*& 1 <= right_len &*& left_len + 1 <= CAPACITY + &*& self.left_child.height == self.right_child.height + &*& 0 <= self.left_child.height &*& self.left_child.height <= usize::MAX + &*& balancing_child_padding(self.left_child.node,self.left_child.height) + &*& balancing_child_padding(self.right_child.node,self.right_child.height) + &*& balancing_child_edges(self.left_child.node,self.left_child.height,left_len,?left_children) + &*& balancing_child_edges(self.right_child.node,self.right_child.height,right_len,?right_children); + @*/ + /*@ + ens result.node == self.left_child &*& result.idx == track_left_edge_idx &*& + thread_token(t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.parent.node.node.as_ptr(),parent_parent,parent_index) &*& + owned_leaf_slots(t,self.parent.node.node.as_ptr(),parent_len) &*& + leaf_header(self.left_child.node.as_ptr(),left_parent,left_index) &*& + leaf_header(self.right_child.node.as_ptr(),right_parent,right_index) &*& + owned_leaf_slots(t,self.left_child.node.as_ptr(),left_len + 1) &*& + owned_leaf_slots(t,self.right_child.node.as_ptr(),right_len - 1) + &*& balancing_child_padding(self.left_child.node,self.left_child.height) + &*& balancing_child_padding(self.right_child.node,self.right_child.height) + &*& balancing_child_edges(self.left_child.node,self.left_child.height,left_len + 1,append(left_children,take(1,right_children))) + &*& balancing_child_edges(self.right_child.node,self.right_child.height,right_len - 1,drop(1,right_children)); + @*/ + //@ on_unwind_ens false; + { + //@ assert *(&mut self) |-> ?original; + self.bulk_steal_right_production/*@::<'a,K,V,'a>@*/(1); //~track_ref_creation + //@ assert ref_mut_end_token(?context, &mut self); + //@ end_ref_mut(context); + //@ open_points_to(&mut self); + //@ let recipient = self.left_child.node.as_ptr(); + //@ close_points_to(&self.left_child); + //@ open owned_leaf_slots(t,recipient,left_len + 1); + //@ open leaf_slots(recipient,left_len + 1,_,_); + let edge = unsafe { + Handle::, K, V, marker::LeafOrInternal>, marker::Edge>::new_edge/*@::,K,V>@*/(self.left_child, track_left_edge_idx) + }; + //@ close leaf_slots(recipient,left_len + 1,_,_); + //@ close owned_leaf_slots(t,recipient,left_len + 1); + //@ close_points_to(&self.parent.node); + //@ close Handle_node_(&self.parent, some(original.parent.node)); + //@ close BalancingContext_parent_(&self, _); + //@ close NodeRef_node_(&self.right_child, some(original.right_child.node)); + //@ close BalancingContext_right_child_(&self, _); + //@ close NodeRef_node_(&self.left_child, _); + //@ close BalancingContext_left_child_(&self, _); + edge + } +} + + +impl<'a, K, V, Type, Kind> Handle, K, V, Type>, Kind> { + unsafe fn reborrow_handle_mut<'short>(&'short mut self) -> Handle, K, V, Type>, Kind> + //@ req *self |-> ?incoming; + //@ ens *self |-> incoming &*& result.idx == incoming.idx &*& result.node.node == incoming.node.node &*& result.node.height == incoming.node.height; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + //@ close_points_to(&(*self).node); + let reborrowed = Handle { + node: unsafe { self.node.reborrow_mut/*@::,K,V,Type,'short>@*/() }, //~track_ref_creation + idx: self.idx, + _marker: PhantomData, + }; + //@ assert ref_mut_end_token(?loan, &(*self).node); + //@ end_ref_mut(loan); + //@ open_points_to(&(*self).node); + //@ close_points_to(self); + reborrowed + } +} + +impl Handle { + unsafe fn into_node(self) -> Node + //@ req true; + //@ ens result == self.node; + //@ on_unwind_ens false; + { + self.node + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { + unsafe fn move_suffix_production<'short>( + &'short mut self, + right: &'short mut NodeRef, K, V, marker::LeafOrInternal>, + ) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?edge &*& *right |-> ?target &*& + leaf_header(edge.node.node.as_ptr(), ?left_parent, ?left_index) &*& + leaf_header(target.node.as_ptr(), ?right_parent, ?right_index) &*& + owned_leaf_slots(t, edge.node.node.as_ptr(), ?old_len) &*& + owned_leaf_slots(t, target.node.as_ptr(), 0) &*& + 0 <= edge.idx &*& edge.idx <= old_len &*& + 0 <= edge.node.height &*& edge.node.height <= usize::MAX &*& edge.node.height == target.height &*& + balancing_child_padding(edge.node.node, edge.node.height) &*& + balancing_child_padding(target.node, target.height) &*& + balancing_child_edges(edge.node.node, edge.node.height, old_len, ?lc) &*& + balancing_child_edges(target.node, target.height, 0, ?rc); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> edge &*& *right |-> target &*& + leaf_header(edge.node.node.as_ptr(), left_parent, left_index) &*& + leaf_header(target.node.as_ptr(), right_parent, right_index) &*& + owned_leaf_slots(t, edge.node.node.as_ptr(), edge.idx) &*& + owned_leaf_slots(t, target.node.as_ptr(), old_len - edge.idx) &*& + balancing_child_padding(edge.node.node, edge.node.height) &*& + balancing_child_padding(target.node, target.height) &*& + balancing_child_edges(edge.node.node, edge.node.height, edge.idx, take(edge.idx + 1, lc)) &*& + balancing_child_edges(target.node, target.height, old_len - edge.idx, append(rc, drop(edge.idx + 1, lc))); + @*/ + //@ on_unwind_ens false; + { + unsafe { + //@ let left_ptr = edge.node.node.as_ptr(); + //@ let right_ptr = target.node.as_ptr(); + //@ let height = edge.node.height; + //@ open_points_to(self); + let new_left_len = self.idx; + //@ close_points_to(self); + let mut left_node = self.reborrow_handle_mut/*@::<'a,K,V,marker::LeafOrInternal,marker::Edge,'short>@*/().into_node/*@::,K,V,marker::LeafOrInternal>,marker::Edge>@*/(); + //@ close_points_to(&mut left_node); + //@ let left_view = precreate_ref(&mut left_node); + //@ init_ref_readonly(left_view, 1/2); + //@ open owned_leaf_slots(t, left_ptr, old_len); + //@ open leaf_slots(left_ptr, old_len, ?left_keys, ?left_vals); + let old_left_len = left_node.merge_len/*@::,K,V,marker::LeafOrInternal,'short>@*/(); + //@ end_ref_readonly(left_view); + //@ merge_fractions points_to(&mut left_node, _); + + let new_right_len = old_left_len - new_left_len; + let mut right_node = right.reborrow_mut/*@::,K,V,marker::LeafOrInternal,'short>@*/(); + //@ close_points_to(&mut right_node); + //@ let right_view = precreate_ref(&mut right_node); + //@ init_ref_readonly(right_view, 1/2); + //@ open owned_leaf_slots(t, right_ptr, 0); + //@ open leaf_slots(right_ptr, 0, ?right_keys, ?right_vals); + assert!(right_node.merge_len/*@::,K,V,marker::LeafOrInternal,'short>@*/() == 0); + //@ end_ref_readonly(right_view); + //@ merge_fractions points_to(&mut right_node, _); + //@ open_points_to(&mut left_node); + //@ open_points_to(&mut right_node); + assert!(left_node.height == right_node.height); + //@ open balancing_child_edges(edge.node.node, height, old_len, lc); + //@ open balancing_child_edges(target.node, height, 0, rc); + + if new_right_len > 0 { + //@ close_points_to(&mut left_node); + //@ close_points_to(&mut right_node); + //@ open leaf_header(left_ptr, left_parent, left_index); + //@ close leaf_without_len(left_ptr, left_parent, left_index, left_keys, left_vals); + *left_node.len_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/() = new_left_len as u16; + //@ assert len_loan(left_ptr, ?left_len_ref, left_parent, left_index, left_keys, left_vals); + //@ end_len_loan(left_ptr, left_len_ref); + //@ open leaf_without_len(left_ptr, left_parent, left_index, left_keys, left_vals); + //@ open leaf_header(right_ptr, right_parent, right_index); + //@ close leaf_without_len(right_ptr, right_parent, right_index, right_keys, right_vals); + *right_node.len_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/() = new_right_len as u16; + //@ assert len_loan(right_ptr, ?right_len_ref, right_parent, right_index, right_keys, right_vals); + //@ end_len_loan(right_ptr, right_len_ref); + //@ open leaf_without_len(right_ptr, right_parent, right_index, right_keys, right_vals); + //@ close leaf_without_keys(left_ptr, left_parent, left_index, new_left_len as u16, left_vals); + //@ close leaf_without_keys(right_ptr, right_parent, right_index, new_right_len as u16, right_vals); + move_to_slice( + left_node.key_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(new_left_len..old_left_len), + right_node.key_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..new_right_len), + ); + //@ assert keys_range_loan(left_ptr, ?keys_source, new_left_len, old_left_len, left_parent, left_index, new_left_len as u16, left_vals, _, _); + //@ assert keys_range_loan(right_ptr, ?keys_dest, 0, new_right_len, right_parent, right_index, new_right_len as u16, right_vals, _, _); + //@ end_keys_range(left_ptr, keys_source); + //@ end_keys_range(right_ptr, keys_dest); + //@ open leaf_without_keys(left_ptr, left_parent, left_index, new_left_len as u16, left_vals); + //@ open leaf_without_keys(right_ptr, right_parent, right_index, new_right_len as u16, right_vals); + //@ take_0(right_keys); + //@ length_take(old_left_len, left_keys); + //@ let active_keys = take(old_left_len, left_keys); + //@ split_slot_owners(t, active_keys, new_left_len); + //@ take_after_drop(left_keys, new_left_len, new_right_len); + //@ take_twice(left_keys, new_left_len, old_left_len); + //@ append_take_drop_n(active_keys, new_left_len); + //@ append_assoc(take(new_left_len,left_keys), drop(new_left_len,active_keys), drop(old_left_len,left_keys)); + //@ append_take_drop_n(left_keys, old_left_len); + //@ assert (*left_ptr).keys[..CAPACITY] |-> left_keys; + //@ assert (*right_ptr).keys[..CAPACITY] |-> ?packed_keys; + //@ length_drop(new_left_len, active_keys); + //@ take_append_l(new_right_len, drop(new_left_len,active_keys), drop(new_right_len,right_keys)); + //@ take_length(drop(new_left_len,active_keys)); + //@ open slot_owners::(t, nil); + //@ close leaf_without_vals(left_ptr, left_parent, left_index, new_left_len as u16, left_keys); + //@ close leaf_without_vals(right_ptr, right_parent, right_index, new_right_len as u16, packed_keys); + move_to_slice( + left_node.val_area_range_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(new_left_len..old_left_len), + right_node.val_area_prefix_mut/*@::<'a,K,V,marker::LeafOrInternal,'short>@*/(..new_right_len), + ); + //@ assert vals_range_loan(left_ptr, ?vals_source, new_left_len, old_left_len, left_parent, left_index, new_left_len as u16, left_keys, _, _); + //@ assert vals_range_loan(right_ptr, ?vals_dest, 0, new_right_len, right_parent, right_index, new_right_len as u16, packed_keys, _, _); + //@ end_vals_range(left_ptr, vals_source); + //@ end_vals_range(right_ptr, vals_dest); + //@ open leaf_without_vals(left_ptr, left_parent, left_index, new_left_len as u16, left_keys); + //@ open leaf_without_vals(right_ptr, right_parent, right_index, new_right_len as u16, packed_keys); + //@ take_0(right_vals); + //@ length_take(old_left_len, left_vals); + //@ let active_vals = take(old_left_len, left_vals); + //@ split_slot_owners(t, active_vals, new_left_len); + //@ take_after_drop(left_vals, new_left_len, new_right_len); + //@ take_twice(left_vals, new_left_len, old_left_len); + //@ append_take_drop_n(active_vals, new_left_len); + //@ append_assoc(take(new_left_len,left_vals), drop(new_left_len,active_vals), drop(old_left_len,left_vals)); + //@ append_take_drop_n(left_vals, old_left_len); + //@ assert (*left_ptr).vals[..CAPACITY] |-> left_vals; + //@ assert (*right_ptr).vals[..CAPACITY] |-> ?packed_vals; + //@ length_drop(new_left_len, active_vals); + //@ take_append_l(new_right_len, drop(new_left_len,active_vals), drop(new_right_len,right_vals)); + //@ take_length(drop(new_left_len,active_vals)); + //@ open slot_owners::(t, nil); + //@ close leaf_header(left_ptr, left_parent, left_index); + //@ close leaf_header(right_ptr, right_parent, right_index); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close leaf_slots(right_ptr, new_right_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ close owned_leaf_slots(t, right_ptr, new_right_len); + match ( + left_node.force/*@::,K,V>@*/(), + right_node.force/*@::,K,V>@*/(), + ) { + (ForceResult::Internal(mut left), ForceResult::Internal(mut right_child)) => { + //@ let left_edges = NonNull::new(left_ptr as *InternalNode); + //@ let right_edges = NonNull::new(right_ptr as *InternalNode); + //@ std::ptr::NonNull_as_ptr_new(left_ptr as *InternalNode); + //@ std::ptr::NonNull_as_ptr_new(right_ptr as *InternalNode); + //@ std::ptr::NonNull_Sized_as_ptr(left_edges); + //@ std::ptr::NonNull_Sized_as_ptr(right_edges); + //@ open balancing_edges(left_edges, lc, ?left_slots); + //@ open balancing_edges(right_edges, rc, ?right_slots); + //@ let kept = take(new_left_len + 1, lc); + //@ let moved = drop(new_left_len + 1, lc); + //@ let joined = append(rc, moved); + //@ let first = take(1, right_slots); + //@ let tail = drop(new_right_len + 1, right_slots); + //@ initialized_edge_split(lc, new_left_len + 1); + //@ initialized_edge_count(kept); + //@ initialized_edge_count(moved); + //@ initialized_edge_count(rc); + //@ length_take(new_left_len + 1, lc); + //@ length_drop(new_left_len + 1, lc); + //@ split_linked_headers(lc, left_edges, 0, new_left_len + 1); + //@ forget_link_indices(moved, left_edges, new_left_len + 1); + //@ assert &(*left_edges.as_ptr()).data == left_ptr; + //@ open owned_leaf_slots(t, left_ptr, new_left_len); + //@ open leaf_slots(left_ptr, new_left_len, _, _); + //@ open leaf_header(left_ptr, left_parent, left_index); + //@ open balancing_child_padding(edge.node.node, height); + //@ close_points_to(left_ptr); + //@ close internal_without_edges(left_edges.as_ptr(), ?left_data); + //@ close_points_to(&mut left); + //@ assert &(*right_edges.as_ptr()).data == right_ptr; + //@ open owned_leaf_slots(t, right_ptr, new_right_len); + //@ open leaf_slots(right_ptr, new_right_len, _, _); + //@ open leaf_header(right_ptr, right_parent, right_index); + //@ open balancing_child_padding(target.node, height); + //@ close_points_to(right_ptr); + //@ close internal_without_edges(right_edges.as_ptr(), ?right_data); + //@ close_points_to(&mut right_child); + move_to_slice( + left.edge_area_range_mut/*@::<'a,K,V,'short>@*/(new_left_len + 1..old_left_len + 1), + right_child.edge_area_range_mut/*@::<'a,K,V,'short>@*/(1..new_right_len + 1), + ); + //@ assert edges_range_loan(left_edges.as_ptr(), ?source, new_left_len + 1, old_left_len + 1, left_data, _, _); + //@ assert edges_range_loan(right_edges.as_ptr(), ?destination, 1, new_right_len + 1, right_data, _, _); + //@ end_edges_range(left_edges.as_ptr(), source); + //@ end_edges_range(right_edges.as_ptr(), destination); + //@ take_after_drop(left_slots, new_left_len + 1, new_right_len); + //@ take_twice(left_slots, new_left_len + 1, old_left_len + 1); + //@ append_take_drop_n(take(old_left_len + 1,left_slots), new_left_len + 1); + //@ append_take_drop_n(left_slots, old_left_len + 1); + //@ append_assoc(take(new_left_len + 1,left_slots), initialized_edges(moved), drop(old_left_len + 1,left_slots)); + //@ length_take(1, right_slots); + //@ open internal_without_edges(right_edges.as_ptr(), right_data); + //@ open_points_to(&(*right_edges.as_ptr()).data); + //@ close exists(right_edges); + //@ close exists(pair(first, tail)); + right_child.relink_range/*@::<'a,K,V,'short>@*/(1..new_right_len + 1); + //@ close_points_to(&(*right_edges.as_ptr()).data); + //@ close internal_without_edges(right_edges.as_ptr(), right_data); + //@ initialized_edges_append(rc, moved); + //@ append_assoc(first, initialized_edges(moved), tail); + //@ join_linked_headers(rc, moved, right_edges, 0); + //@ length_append(rc, moved); + //@ initialized_edge_count(joined); + //@ take_append_l(new_right_len + 1, initialized_edges(joined), tail); + //@ take_length(initialized_edges(joined)); + //@ close balancing_edges(left_edges, kept, left_slots); + //@ close balancing_edges(right_edges, joined, _); + //@ open internal_without_edges(left_edges.as_ptr(), left_data); + //@ open_points_to(left_ptr); + //@ close leaf_header(left_ptr, left_parent, left_index); + //@ close leaf_slots(left_ptr, new_left_len, _, _); + //@ close owned_leaf_slots(t, left_ptr, new_left_len); + //@ close balancing_child_padding(edge.node.node, height); + //@ open_points_to(&mut left); + //@ open internal_without_edges(right_edges.as_ptr(), right_data); + //@ open_points_to(right_ptr); + //@ close leaf_header(right_ptr, right_parent, right_index); + //@ close leaf_slots(right_ptr, new_right_len, _, _); + //@ close owned_leaf_slots(t, right_ptr, new_right_len); + //@ close balancing_child_padding(target.node, height); + //@ open_points_to(&mut right_child); + } + (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} + _ => unreachable!(), + } + //@ close NodeRef_node_(&mut left_node, _); + //@ close NodeRef_node_(&mut right_node, _); + } else { + /*@ + if height > 0 { + take_length(lc); + length_drop(new_left_len + 1, lc); + empty_list_if_zero(drop(new_left_len + 1, lc)); + } + @*/ + //@ append_nil(rc); + //@ close leaf_slots(left_ptr, old_len, left_keys, left_vals); + //@ close leaf_slots(right_ptr, 0, right_keys, right_vals); + //@ close owned_leaf_slots(t, left_ptr, old_len); + //@ close owned_leaf_slots(t, right_ptr, 0); + //@ close NodeRef_node_(&mut left_node, _); + //@ close NodeRef_node_(&mut right_node, _); + } + //@ close balancing_child_edges(edge.node.node, height, new_left_len, take(new_left_len + 1, lc)); + //@ close balancing_child_edges(target.node, height, new_right_len, append(rc, drop(new_left_len + 1, lc))); + } + } +} + + + +// The production cleanup edges are checked separately. A key unwind +// leaves its value pending. Its value guard completes that slot before +// the node guard resumes at the next pair. + +impl NodeRef { + unsafe fn as_leaf_dying<'short>(&'short mut self) -> &'short mut LeafNode + //@ req *self |-> ?node &*& *node.node.as_ptr() |-> ?contents; + //@ ens *self |-> node &*& *result |-> contents &*& ref_mut_end_token(result, node.node.as_ptr()) &*& ref_origin(result) == ref_origin(node.node.as_ptr()); + //@ on_unwind_ens false; + { + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + let ptr = unsafe { Self::as_leaf_ptr(self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self, _); + unsafe { &mut *ptr } //~track_ref_creation + } +} + +unsafe fn duplicate_dying( + node: *const NodeRef, +) -> NodeRef +/*@ +req thread_token(?t) &*& [?q](*node |-> ?value); +@*/ +//@ ens thread_token(t) &*& [q](*node |-> value) &*& result == value; +//@ on_unwind_ens false; +{ + //@ close NodeRef_own::(t, value); + let duplicated = unsafe { std::ptr::read(node) }; + //@ open NodeRef_own::(t, duplicated); + duplicated +} + +/*@ +pred drop_slot_loan( + field: *[MaybeUninit; N], array: *[MaybeUninit; N], slot: *MaybeUninit, index: usize, + prior: list>, later: list> +) = + ref_mut_end_token(array, field) &*& + ref_mut_end_token(slot, array as *MaybeUninit + index) &*& + (array as *MaybeUninit)[..index] |-> prior &*& + (array as *MaybeUninit)[index+1..int_of_const(typeid(N))] |-> later; + +lem close_drop_array(p: *[T; N]) + req (p as *T)[..int_of_const(typeid(N))] |-> ?values; + ens *p |-> ?value &*& Array_elems(value) == values; +{ + let base = p as *T; + close_points_to(p, 1/2); + assert [1/2](*p |-> ?value); + Array_to_array(p); + merge_fractions array(base, int_of_const(typeid(N)), _); + assert Array_elems(value) == values; + close_points_to(p); +} + +lem end_drop_slot(field: *[MaybeUninit; N], slot: *MaybeUninit, index: usize) + req drop_slot_loan(field,?array,slot,index,?before,?after) &*& *slot |-> ?entry; + ens *field |-> ?entries &*& Array_elems(entries) == append(before,cons(entry,after)); +{ + open drop_slot_loan(field,array,slot,index,before,after); + let base = array as *MaybeUninit; + end_ref_mut(slot); + close array(base+index+1,0,[]); + close array(base+index,1,[entry]); + array_join(base+index); + array_join(base); + close_drop_array(array); + end_ref_mut(array); +} +@*/ + +impl Handle, marker::KV> { + unsafe fn project_drop_slots<'short>( + &'short mut self, + ) -> (&'short mut MaybeUninit, &'short mut MaybeUninit) + /*@ + req *self |-> ?incoming &*& leaf_header(incoming.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(incoming.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= incoming.idx &*& incoming.idx < len; + @*/ + /*@ + ens *self |-> incoming &*& + ref_mut_end_token(?leaf,incoming.node.node.as_ptr()) &*& + leaf_header(leaf,parent,parent_idx) &*& (*leaf).len |-> len as u16 &*& + drop_slot_loan(&(*leaf).keys,?key_array,result.0,incoming.idx,take(incoming.idx,keys),drop(incoming.idx+1,keys)) &*& + drop_slot_loan(&(*leaf).vals,?val_array,result.1,incoming.idx,take(incoming.idx,vals),drop(incoming.idx+1,vals)) &*& + *result.0 |-> nth(incoming.idx,keys) &*& *result.1 |-> nth(incoming.idx,vals); + @*/ + //@ on_unwind_ens false; + { + //@ let node = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open leaf_slots(node,len,keys,vals); + //@ open_points_to(self); + //@ let view = precreate_ref(&(*self).node); + //@ init_ref_readonly(view,1/2); + debug_assert!(self.idx < self.node.merge_len()); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&(*self).node, _); + //@ open leaf_header(node,parent,parent_idx); + //@ close_points_to(node); + let leaf = unsafe { self.node.as_leaf_dying/*@::@*/() }; //~track_ref_creation + //@ open_points_to(leaf); + //@ close_points_to(&(*leaf).keys); + let key_slot = + <[MaybeUninit]>::get_unchecked_mut( + { + let key_array = &mut leaf.keys; //~track_ref_creation + let slice: &mut [MaybeUninit] = key_array; + //@ open_points_to(key_array); + //@ let key_base = key_array as *MaybeUninit; + //@ array_split(key_base,index); + //@ array_split(key_base+index,1); + //@ open array(key_base+index,1,_); + //@ open array(key_base+index+1,0,_); + //@ nth_drop(0,index,keys); + //@ drop_twice(1,index,keys); + slice + }, + self.idx, + ); + //@ close drop_slot_loan(&(*leaf).keys,key_array,key_slot,index,take(index,keys),drop(index+1,keys)); + //@ close_points_to(&(*leaf).vals); + let val_slot = + <[MaybeUninit]>::get_unchecked_mut( + { + let val_array = &mut leaf.vals; //~track_ref_creation + let slice: &mut [MaybeUninit] = val_array; + //@ open_points_to(val_array); + //@ let val_base = val_array as *MaybeUninit; + //@ array_split(val_base,index); + //@ array_split(val_base+index,1); + //@ open array(val_base+index,1,_); + //@ open array(val_base+index+1,0,_); + //@ nth_drop(0,index,vals); + //@ drop_twice(1,index,vals); + slice + }, + self.idx, + ); + //@ close drop_slot_loan(&(*leaf).vals,val_array,val_slot,index,take(index,vals),drop(index+1,vals)); + //@ close leaf_header(leaf,parent,parent_idx); + //@ assert ref_mut_end_token(?receiver,&(*self).node); + //@ end_ref_mut(receiver); + //@ open_points_to(&(*self).node); + //@ close_points_to(self); + (key_slot, val_slot) + } +} + +/*@ +pred drop_kv_frame( + node: *LeafNode, leaf: *LeafNode, key: *MaybeUninit, value: *MaybeUninit, + index: usize, len: usize, keys: list>, vals: list>, + parent: Option>>, parent_idx: MaybeUninit +) = + ref_mut_end_token(leaf,node) &*& + leaf_header(leaf,parent,parent_idx) &*& (*leaf).len |-> len as u16 &*& + drop_slot_loan(&(*leaf).keys,?keys_ref,key,index,take(index,keys),drop(index+1,keys)) &*& + drop_slot_loan(&(*leaf).vals,?vals_ref,value,index,take(index,vals),drop(index+1,vals)); + +lem take_after_replacing_cell(entries: list, len: usize, index: usize, cell: T) + req 0 <= index &*& index < len &*& len <= length(entries); + ens drop(index+1,take(len,replace_slot(index,cell,entries))) == drop(index+1,take(len,entries)); +{ + let before = take(index,entries); + let head = append(before,[cell]); + let tail = drop(index+1,entries); + length_take(index,entries); + length_append(before,[cell]); + append_assoc(before,[cell],tail); + take_append(len,head,tail); + drop_append(index+1,head,take(len-index-1,tail)); + drop_0(take(len-index-1,tail)); + take_after_drop(entries,index+1,len-index-1); +} + +lem restore_dropped_kv( + node: *LeafNode, leaf: *LeafNode, key: *MaybeUninit, value: *MaybeUninit, + index: usize, len: usize, keys: list>, vals: list>, + parent: Option>>, parent_idx: MaybeUninit +) + req drop_kv_frame(node,leaf,key,value,index,len,keys,vals,parent,parent_idx) &*& + *(key as *K) |-> _ &*& *(value as *V) |-> _ &*& + 0 <= index &*& index < len &*& len <= CAPACITY &*& length(keys) == CAPACITY &*& length(vals) == CAPACITY; + ens leaf_header(node,parent,parent_idx) &*& leaf_slots(node,len,?next_keys,?next_vals) &*& + drop(index+1,take(len,next_keys)) == drop(index+1,take(len,keys)) &*& + drop(index+1,take(len,next_vals)) == drop(index+1,take(len,vals)); +{ + open drop_kv_frame(node,leaf,key,value,index,len,keys,vals,parent,parent_idx); + std::mem::close_MaybeUninit_(key); + std::mem::close_MaybeUninit_(value); + assert *key |-> ?dead_key; + assert *value |-> ?dead_val; + end_drop_slot(&(*leaf).keys,key,index); + end_drop_slot(&(*leaf).vals,value,index); + assert *(&(*leaf).keys) |-> ?repacked_keys; + assert *(&(*leaf).vals) |-> ?repacked_vals; + assert Array_elems(repacked_keys) == replace_slot(index,dead_key,keys); + assert Array_elems(repacked_vals) == replace_slot(index,dead_val,vals); + Array_to_array(&(*leaf).keys); + Array_to_array(&(*leaf).vals); + assert (*leaf).keys[..CAPACITY] |-> replace_slot(index,dead_key,keys); + assert (*leaf).vals[..CAPACITY] |-> replace_slot(index,dead_val,vals); + open leaf_header(leaf,parent,parent_idx); + close_points_to(leaf); + end_ref_mut(leaf); + open_points_to(node); + assert (*node).keys[..CAPACITY] |-> replace_slot(index,dead_key,keys); + assert (*node).vals[..CAPACITY] |-> replace_slot(index,dead_val,vals); + close leaf_header(node,parent,parent_idx); + close leaf_slots(node,len,_,_); + take_after_replacing_cell(keys,len,index,dead_key); + take_after_replacing_cell(vals,len,index,dead_val); +} +@*/ + +impl Handle,marker::KV> { + unsafe fn drop_key_val_step(mut self) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= self.idx &*& self.idx < len &*& + slot_owners(t,drop(self.idx,take(len,keys))) &*& slot_owners(t,drop(self.idx,take(len,vals))); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.node.node.as_ptr(),parent,parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),len,?final_keys,?final_vals) &*& + slot_owners(t,drop(self.idx+1,take(len,final_keys))) &*& slot_owners(t,drop(self.idx+1,take(len,final_vals))); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + drop_kv_frame(self.node.node.as_ptr(),?leaf,?key,?value,self.idx,len,keys,vals,parent,parent_idx) &*& + length(keys) == CAPACITY &*& length(vals) == CAPACITY &*& len <= CAPACITY &*& + *(key as *K) |-> _ &*& exists::(?pending) &*& + (if pending { + *value |-> ?contents &*& contents.inner() == some(?v) &*& .own(t,v) + } else { + *(value as *V) |-> _ + }) &*& slot_owners(t,drop(self.idx+1,take(len,keys))) &*& slot_owners(t,drop(self.idx+1,take(len,vals))); + @*/ + { + //@ assert *(&mut self) |-> ?incoming; + //@ let node = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open leaf_slots(node,len,keys,vals); + //@ assert length(keys) == CAPACITY && length(vals) == CAPACITY; + //@ close leaf_slots(node,len,keys,vals); + let (key_slot,value_slot) = self.project_drop_slots/*@::@*/(); + //@ assert ref_mut_end_token(?leaf,node); + //@ close drop_kv_frame(node,leaf,key_slot,value_slot,index,len,keys,vals,parent,parent_idx); + //@ length_take(len,keys); + //@ length_take(len,vals); + //@ drop_n_plus_one(index,take(len,keys)); + //@ drop_n_plus_one(index,take(len,vals)); + //@ open slot_owners(t,drop(index,take(len,keys))); + //@ open slot_owners(t,drop(index,take(len,vals))); + //@ nth_take_range(keys,len,index); + //@ nth_take_range(vals,len,index); + //@ drop_twice(1,index,take(len,keys)); + //@ drop_twice(1,index,take(len,vals)); + unsafe { drop_pair(key_slot,value_slot) }; + //@ restore_dropped_kv(node,leaf,key_slot,value_slot,index,len,keys,vals,parent,parent_idx); + } +} + +impl Handle,marker::KV> { + unsafe fn new_dying_kv(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& 0 <= idx &*& idx < len; + //@ ens (*node.node.as_ptr()).len |-> len &*& result.node == node &*& result.idx == idx; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx < node.len()) }; + let result = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node,1/2); + result + } +} + +unsafe fn drop_at( + node: *const NodeRef, + index: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + [?q](*node |-> ?incoming) &*& + leaf_header(incoming.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(incoming.node.as_ptr(),?len,?keys,?vals) &*& 0 <= index &*& index < len &*& + slot_owners(t,drop(index,take(len,keys))) &*& slot_owners(t,drop(index,take(len,vals))); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + [q](*node |-> incoming) &*& + leaf_header(incoming.node.as_ptr(),parent,parent_idx) &*& leaf_slots(incoming.node.as_ptr(),len,?next_keys,?next_vals) &*& + slot_owners(t,drop(index+1,take(len,next_keys))) &*& slot_owners(t,drop(index+1,take(len,next_vals))); +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + [q](*node |-> incoming) &*& + drop_kv_frame(incoming.node.as_ptr(),?leaf,?key,?value,index,len,keys,vals,parent,parent_idx) &*& + length(keys) == CAPACITY &*& length(vals) == CAPACITY &*& len <= CAPACITY &*& 0 <= index &*& index < len &*& + *(key as *K) |-> _ &*& exists::(?pending) &*& + (if pending { + *value |-> ?contents &*& contents.inner() == some(?v) &*& .own(t,v) + } else { + *(value as *V) |-> _ + }) &*& slot_owners(t,drop(index+1,take(len,keys))) &*& slot_owners(t,drop(index+1,take(len,vals))); +@*/ +{ + //@ let leaf = incoming.node.as_ptr(); + //@ open leaf_slots(leaf,len,keys,vals); + let kv = unsafe { Handle::new_dying_kv(duplicate_dying(node), index) }; + //@ close leaf_slots(leaf,len,keys,vals); + unsafe { kv.drop_key_val_step() }; +} + +unsafe fn drop_remaining( + node: *const NodeRef, + start: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + [?q](*node |-> ?incoming) &*& + leaf_header(incoming.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(incoming.node.as_ptr(),?len,?keys,?vals) &*& 0 <= start &*& start <= len &*& + slot_owners(t,drop(start,take(len,keys))) &*& slot_owners(t,drop(start,take(len,vals))); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + [q](*node |-> incoming) &*& + leaf_header(incoming.node.as_ptr(),parent,parent_idx) &*& leaf_slots(incoming.node.as_ptr(),len,_,_); +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + [q](*node |-> incoming) &*& + drop_kv_frame(incoming.node.as_ptr(),?leaf,?key,?value,?index,len,?ks,?vs,parent,parent_idx) &*& + length(ks) == CAPACITY &*& length(vs) == CAPACITY &*& len <= CAPACITY &*& start <= index &*& index < len &*& + *(key as *K) |-> _ &*& exists::(?pending) &*& + (if pending { + *value |-> ?contents &*& contents.inner() == some(?v) &*& .own(t,v) + } else { + *(value as *V) |-> _ + }) &*& slot_owners(t,drop(index+1,take(len,ks))) &*& slot_owners(t,drop(index+1,take(len,vs))); +@*/ +{ + //@ let leaf = incoming.node.as_ptr(); + //@ open leaf_slots(leaf,len,keys,vals); + //@ let view = precreate_ref(node); + //@ init_ref_readonly(view,1/2); + let count = unsafe { (*node).len() }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(node, _); + //@ close leaf_slots(leaf,len,keys,vals); + let mut iter = (start..count).into_iter(); + loop { + /*@ + inv iter |-> ?state &*& state.end == len &*& start <= state.start &*& state.start <= len &*& + thread_token(t) &*& lifetime_token(func_lft) &*& type_interp::() &*& type_interp::() &*& + [q](*node |-> incoming) &*& + leaf_header(leaf,parent,parent_idx) &*& leaf_slots(leaf,len,?active_keys,?active_vals) &*& + slot_owners(t,drop(state.start,take(len,active_keys))) &*& slot_owners(t,drop(state.start,take(len,active_vals))); + @*/ + let iter_ref = &mut iter; + let next = iter_ref.next(); + match next { + None => break, + Some(i) => unsafe { drop_at(node, i) }, + } + } + //@ assert leaf_slots(leaf,len,?last_keys,?last_vals); + //@ open leaf_slots(leaf,len,last_keys,last_vals); + //@ length_take(len,last_keys); + //@ length_take(len,last_vals); + //@ drop_length(take(len,last_keys)); + //@ drop_length(take(len,last_vals)); + //@ open slot_owners::(t,nil); + //@ open slot_owners::(t,nil); + //@ close leaf_slots(leaf,len,last_keys,last_vals); +} + +/*@ pred resume_phase(inside_value: bool) = true; @*/ + +unsafe fn finish_drop_value(value: *mut MaybeUninit, pending: bool) +/*@ +req thread_token(?t) &*& type_interp::() &*& + (if pending { + *value |-> ?contents &*& contents.inner() == some(?v) &*& .own(t,v) + } else { + *(value as *V) |-> _ + }); +@*/ +//@ ens thread_token(t) &*& type_interp::() &*& *(value as *V) |-> _; +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& *(value as *V) |-> _; +{ + if pending { + unsafe { drop_guarded_value(value) }; + } +} + +unsafe fn resume_drop_remaining( + node: *const NodeRef, + leaf: *mut LeafNode, + key: *mut MaybeUninit, + value: *mut MaybeUninit, + index: usize, + len: usize, + pending: bool, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& [?q](*node |-> ?incoming) &*& + drop_kv_frame(incoming.node.as_ptr(),leaf,key,value,index,len,?keys,?vals,?parent,?parent_idx) &*& + length(keys) == CAPACITY &*& length(vals) == CAPACITY &*& 0 <= index &*& index < len &*& len <= CAPACITY &*& + *(key as *K) |-> _ &*& + (if pending { + *value |-> ?contents &*& contents.inner() == some(?v) &*& .own(t,v) + } else { + *(value as *V) |-> _ + }) &*& slot_owners(t,drop(index+1,take(len,keys))) &*& slot_owners(t,drop(index+1,take(len,vals))); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& [q](*node |-> incoming) &*& + leaf_header(incoming.node.as_ptr(),parent,parent_idx) &*& leaf_slots(incoming.node.as_ptr(),len,_,_); +@*/ +/*@ +on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& [q](*node |-> incoming) &*& + resume_phase(?inside_value) &*& + if inside_value { + drop_kv_frame(incoming.node.as_ptr(),leaf,key,value,index,len,keys,vals,parent,parent_idx) &*& + *(key as *K) |-> _ &*& *(value as *V) |-> _ &*& + slot_owners(t,drop(index+1,take(len,keys))) &*& slot_owners(t,drop(index+1,take(len,vals))) + } else { + drop_kv_frame(incoming.node.as_ptr(),?rest_leaf,?rest_key,?rest_value,?remaining,len,?ks,?vs,parent,parent_idx) &*& + length(ks) == CAPACITY &*& length(vs) == CAPACITY &*& index < remaining &*& remaining < len &*& + *(rest_key as *K) |-> _ &*& exists::(?rest_pending) &*& + (if rest_pending { + *rest_value |-> ?bits &*& bits.inner() == some(?entry) &*& .own(t,entry) + } else { + *(rest_value as *V) |-> _ + }) &*& slot_owners(t,drop(remaining+1,take(len,ks))) &*& slot_owners(t,drop(remaining+1,take(len,vs))) + }; +@*/ +{ + //@ close resume_phase(true); + unsafe { finish_drop_value(value, pending) }; + //@ open resume_phase(true); + //@ restore_dropped_kv(incoming.node.as_ptr(),leaf,key,value,index,len,keys,vals,parent,parent_idx); + //@ close resume_phase(false); + unsafe { drop_remaining(node, index + 1) }; + //@ open resume_phase(false); +} + + +impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { + unsafe fn split_leaf_data<'short, 'dst>(&'short mut self, new_node: &'dst mut LeafNode) -> (K, V) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?incoming &*& leaf_header(incoming.node.node.as_ptr(), ?parent, ?parent_idx) &*& + leaf_slots(incoming.node.node.as_ptr(), ?len, ?keys, ?vals) &*& 0 <= incoming.idx &*& incoming.idx < len &*& + nth(incoming.idx, keys).inner() == some(?key) &*& nth(incoming.idx, vals).inner() == some(?val) &*& + .own(t, key) &*& .own(t, val) &*& + leaf_header(new_node, ?right_parent, ?right_index) &*& leaf_slots(new_node, _, ?right_keys, ?right_vals); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> incoming &*& leaf_header(incoming.node.node.as_ptr(), parent, parent_idx) &*& + leaf_slots(incoming.node.node.as_ptr(), incoming.idx, keys, vals) &*& + leaf_header(new_node, right_parent, right_index) &*& + leaf_slots(new_node, len - incoming.idx - 1, + append(take(len - incoming.idx - 1, drop(incoming.idx + 1, keys)), drop(len - incoming.idx - 1, right_keys)), + append(take(len - incoming.idx - 1, drop(incoming.idx + 1, vals)), drop(len - incoming.idx - 1, right_vals))) &*& + result.0 == key &*& result.1 == val &*& .own(t, key) &*& .own(t, val); + @*/ + //@ on_unwind_ens false; + { + //@ let left = incoming.node.node.as_ptr(); + //@ std::ptr::NonNull_Sized_as_ptr(incoming.node.node); + //@ open leaf_slots(left, len, keys, vals); + //@ open leaf_slots(new_node, _, right_keys, right_vals); + //@ open_points_to(self); + //@ let check_view = precreate_ref(&(*self).node); + //@ init_ref_readonly(check_view, 1/2); + unsafe { debug_assert!(self.idx < self.node.merge_len()); } + //@ end_ref_readonly(check_view); + //@ merge_fractions points_to(&(*self).node, _); + //@ let len_view = precreate_ref(&(*self).node); + //@ init_ref_readonly(len_view, 1/2); + let old_len = unsafe { self.node.merge_len() }; + //@ end_ref_readonly(len_view); + //@ merge_fractions points_to(&(*self).node, _); + let new_len = old_len - self.idx - 1; + new_node.len = new_len as u16; + unsafe { + //@ close leaf_without_keys(left, parent, parent_idx, old_len as u16, vals); + let keys_slot = self.node.key_area_slot_mut/*@::<'a,K,V,NodeType,'short>@*/(self.idx); + //@ assert keys_slot_loan(left, keys_slot, incoming.idx, parent, parent_idx, old_len as u16, vals, _, _); + //@ let keys_ref = precreate_ref(keys_slot); + //@ init_ref_readonly(keys_ref, 1/2); + let promoted_keys = keys_slot.assume_init_read(); + //@ end_ref_readonly(keys_ref); + //@ merge_fractions points_to(keys_slot, _); + //@ end_keys_slot(left, keys_slot); + //@ append_take_drop_n(keys, incoming.idx); + //@ drop_n_plus_one(incoming.idx, keys); + //@ assert drop(incoming.idx, keys) == cons(nth(incoming.idx, keys), drop(incoming.idx + 1, keys)); + //@ open leaf_without_keys(left, parent, parent_idx, old_len as u16, vals); + //@ close leaf_without_vals(left, parent, parent_idx, old_len as u16, keys); + let vals_slot = self.node.val_area_slot_mut/*@::<'a,K,V,NodeType,'short>@*/(self.idx); + //@ assert vals_slot_loan(left, vals_slot, incoming.idx, parent, parent_idx, old_len as u16, keys, _, _); + //@ let vals_ref = precreate_ref(vals_slot); + //@ init_ref_readonly(vals_ref, 1/2); + let promoted_vals = vals_slot.assume_init_read(); + //@ end_ref_readonly(vals_ref); + //@ merge_fractions points_to(vals_slot, _); + //@ end_vals_slot(left, vals_slot); + //@ append_take_drop_n(vals, incoming.idx); + //@ drop_n_plus_one(incoming.idx, vals); + //@ assert drop(incoming.idx, vals) == cons(nth(incoming.idx, vals), drop(incoming.idx + 1, vals)); + //@ open leaf_without_vals(left, parent, parent_idx, old_len as u16, keys); + //@ close leaf_without_keys(left, parent, parent_idx, old_len as u16, vals); + move_to_slice( + self.node.key_area_range_mut/*@::<'a,K,V,NodeType,'short>@*/(self.idx + 1..old_len), + { + //@ close_points_to(&(*new_node).keys); + let keys_array = &mut new_node.keys; //~track_ref_creation + //@ open_points_to(keys_array); + //@ let keys_base = keys_array as *MaybeUninit; + //@ insertion_slot_limits(keys_base); + //@ move_slice_offset(keys_base, CAPACITY, new_len); + //@ array_split(keys_base, new_len); + let keys_target = &mut keys_array[..new_len]; + //@ close move_slice(keys_target as *MaybeUninit, new_len, _); + keys_target + }, + ); + //@ assert keys_range_loan(left, ?keys_source, incoming.idx + 1, old_len, parent, parent_idx, old_len as u16, vals, _, _); + //@ assert ref_mut_end_token(?keys_lent_array, &(*new_node).keys); + //@ let keys_lent_base = keys_lent_array as *MaybeUninit; + //@ assert slice_ref_mut_end_token(?keys_lent_slice, keys_lent_base, new_len); + //@ end_keys_range(left, keys_source); + //@ let keys_copied = take(new_len, drop(incoming.idx + 1, keys)); + //@ open move_slice(keys_lent_slice as *MaybeUninit, new_len, keys_copied); + //@ end_slice_ref_mut(keys_lent_slice); + //@ array_join(keys_lent_base); + //@ close_points_to(keys_lent_array); + //@ end_ref_mut(keys_lent_array); + //@ open_points_to(&(*new_node).keys); + //@ drop_twice(new_len, incoming.idx + 1, keys); + //@ append_take_drop_n(drop(incoming.idx + 1, keys), new_len); + //@ append_assoc(take(incoming.idx + 1, keys), keys_copied, drop(old_len, keys)); + //@ append_take_drop_n(keys, incoming.idx + 1); + //@ open leaf_without_keys(left, parent, parent_idx, old_len as u16, vals); + //@ close leaf_without_vals(left, parent, parent_idx, old_len as u16, keys); + move_to_slice( + self.node.val_area_range_mut/*@::<'a,K,V,NodeType,'short>@*/(self.idx + 1..old_len), + { + //@ close_points_to(&(*new_node).vals); + let vals_array = &mut new_node.vals; //~track_ref_creation + //@ open_points_to(vals_array); + //@ let vals_base = vals_array as *MaybeUninit; + //@ insertion_slot_limits(vals_base); + //@ move_slice_offset(vals_base, CAPACITY, new_len); + //@ array_split(vals_base, new_len); + let vals_target = &mut vals_array[..new_len]; + //@ close move_slice(vals_target as *MaybeUninit, new_len, _); + vals_target + }, + ); + //@ assert vals_range_loan(left, ?vals_source, incoming.idx + 1, old_len, parent, parent_idx, old_len as u16, keys, _, _); + //@ assert ref_mut_end_token(?vals_lent_array, &(*new_node).vals); + //@ let vals_lent_base = vals_lent_array as *MaybeUninit; + //@ assert slice_ref_mut_end_token(?vals_lent_slice, vals_lent_base, new_len); + //@ end_vals_range(left, vals_source); + //@ let vals_copied = take(new_len, drop(incoming.idx + 1, vals)); + //@ open move_slice(vals_lent_slice as *MaybeUninit, new_len, vals_copied); + //@ end_slice_ref_mut(vals_lent_slice); + //@ array_join(vals_lent_base); + //@ close_points_to(vals_lent_array); + //@ end_ref_mut(vals_lent_array); + //@ open_points_to(&(*new_node).vals); + //@ drop_twice(new_len, incoming.idx + 1, vals); + //@ append_take_drop_n(drop(incoming.idx + 1, vals), new_len); + //@ append_assoc(take(incoming.idx + 1, vals), vals_copied, drop(old_len, vals)); + //@ append_take_drop_n(vals, incoming.idx + 1); + //@ open leaf_without_vals(left, parent, parent_idx, old_len as u16, keys); + //@ close leaf_without_len(left, parent, parent_idx, keys, vals); + *self.node.len_mut/*@::<'a,K,V,NodeType,'short>@*/() = self.idx as u16; + //@ assert len_loan(left, ?length, parent, parent_idx, keys, vals); + //@ end_len_loan(left, length); + //@ open leaf_without_len(left, parent, parent_idx, keys, vals); + //@ close leaf_header(left, parent, parent_idx); + //@ close leaf_slots(left, incoming.idx, keys, vals); + //@ close leaf_slots(new_node, new_len, _, _); + //@ close_points_to(self); + (promoted_keys, promoted_vals) + } + } +} + +impl NodeRef { + unsafe fn from_new_leaf(leaf: Box, A>) -> Self + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& Box_in(t, leaf, ?id, ?contents); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& result.height == 0 &*& + points_to_at_lft(id.lft, result.node.as_ptr(), contents) &*& + std::alloc::alloc_block_in(id, result.node.as_ptr() as *u8, std::alloc::Layout::new::>()) &*& + result.node.as_ptr() as usize != 0; + @*/ + //@ on_unwind_ens false; + { + let (node, _alloc) = Box::into_non_null_with_allocator(leaf); + //@ std::alloc::Allocator_to_own(_alloc); + NodeRef { height: 0, node, _marker: PhantomData } + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { + unsafe fn split_production_leaf( + mut self, alloc: A, + ) -> SplitResult<'a, K, V, marker::Leaf> + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t, alloc, ?id) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& + lifetime_inclusion(k, id.lft) == true &*& + self.node.height == 0 &*& leaf_header(self.node.node.as_ptr(), ?parent, ?parent_idx) &*& + leaf_slots(self.node.node.as_ptr(), ?len, ?keys, ?vals) &*& 0 <= self.idx &*& self.idx < len &*& + nth(self.idx, keys).inner() == some(?key) &*& nth(self.idx, vals).inner() == some(?val) &*& + .own(t, key) &*& .own(t, val); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [available/2]lifetime_token(k) &*& result.left == self.node &*& result.right.height == 0 &*& + leaf_header(self.node.node.as_ptr(), parent, parent_idx) &*& + leaf_slots(self.node.node.as_ptr(), self.idx, keys, vals) &*& + allocated_leaf(result.right.node.as_ptr(), id, k, available/2) &*& + (*result.right.node.as_ptr()).parent |-> Option::None &*& + (*result.right.node.as_ptr()).parent_idx |-> ?right_parent_idx &*& + result.right.node.as_ptr() != self.node.node.as_ptr() &*& + leaf_slots(result.right.node.as_ptr(), len - self.idx - 1, ?new_keys, ?new_vals) &*& + take(len - self.idx - 1, new_keys) == take(len - self.idx - 1, drop(self.idx + 1, keys)) &*& + take(len - self.idx - 1, new_vals) == take(len - self.idx - 1, drop(self.idx + 1, vals)) &*& + result.kv.0 == key &*& result.kv.1 == val &*& .own(t, key) &*& .own(t, val); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [available]lifetime_token(k) &*& leaf_header(self.node.node.as_ptr(), parent, parent_idx) &*& + leaf_slots(self.node.node.as_ptr(), len, keys, vals) &*& .own(t, key) &*& .own(t, val); + @*/ + { + //@ open exists(k); + //@ assert *&self |-> ?incoming; + //@ let suffix_len = len - incoming.idx - 1; + //@ let left = incoming.node.node.as_ptr(); + //@ open leaf_slots(left, len, keys, vals); + //@ assert length(keys) == CAPACITY && length(vals) == CAPACITY; + //@ close leaf_slots(left, len, keys, vals); + let mut new_node = unsafe { LeafNode::::new(alloc) }; + let kv = unsafe { + self.split_leaf_data/*@::<'a,K,V,marker::Leaf,'a,'a>@*/({ //~track_ref_creation + let box_view = &mut new_node; //~track_ref_creation + //@ let contents = std::boxed::Box_separate_contents(box_view); + //@ let q_box = lifetime_token_trade(k, available, id.lft); + //@ open_points_to_at_lft(contents, q_box); + //@ points_to_limits(contents); + //@ assert *contents |-> ?fresh; + let destination: &mut LeafNode = box_view; //~track_ref_creation + //@ open_points_to(destination); + //@ close leaf_header(destination, fresh.parent, fresh.parent_idx); + //@ close leaf_slots(destination, 0, _, _); + //@ assert leaf_slots(destination, 0, ?initial_keys, ?initial_vals); + destination + }) + }; + //@ assert ref_mut_end_token(?source_view, &mut self); + //@ assert ref_mut_end_token(?box_ref, &mut new_node); + //@ assert std::boxed::Box_minus_contents_in(_, t, _, box_ref, id, contents); + //@ assert ref_mut_end_token(?right_view, contents); + //@ assert leaf_slots(right_view, suffix_len, ?split_keys, ?split_vals); + //@ length_drop(incoming.idx + 1, keys); + //@ length_drop(incoming.idx + 1, vals); + //@ length_take(suffix_len, drop(incoming.idx + 1, keys)); + //@ length_take(suffix_len, drop(incoming.idx + 1, vals)); + //@ take_append_l(suffix_len, take(suffix_len, drop(incoming.idx + 1, keys)), drop(suffix_len, initial_keys)); + //@ take_append_l(suffix_len, take(suffix_len, drop(incoming.idx + 1, vals)), drop(suffix_len, initial_vals)); + //@ close_points_to(right_view); + //@ end_ref_mut(right_view); + //@ assert close_points_to_at_lft_token(1, id.lft, contents, q_box); + //@ close_points_to_at_lft(contents); + //@ lifetime_token_trade_back(q_box, id.lft); + //@ std::boxed::Box_unseparate_contents(box_ref); + //@ end_ref_mut(box_ref); + //@ end_ref_mut(source_view); + let right = unsafe { NodeRef::::from_new_leaf(new_node) }; + //@ let ptr = right.node.as_ptr(); + //@ std::ptr::NonNull_Sized_as_ptr(right.node); + //@ close reserve_allocation(k, available/2); + //@ let q_alloc = lifetime_token_trade(k, available/2, id.lft); + //@ open_points_to_at_lft(ptr, q_alloc); + //@ points_to_limits(ptr); + //@ open_points_to(ptr); + //@ close allocated_leaf(ptr, id, k, available/2); + //@ open reserve_allocation(k, available/2); + //@ open_points_to(&self); + //@ close leaf_slots(ptr, len - self.idx - 1, split_keys, split_vals); + /*@ if ptr == left { + open leaf_slots(left, incoming.idx, keys, vals); + open leaf_slots(ptr, suffix_len, split_keys, split_vals); + merge_fractions LeafNode_len_(left, _); + } @*/ + let result = SplitResult { left: self.node, kv, right }; + //@ close_points_to(&self); + result + } +} + +impl NodeRef { + unsafe fn from_new_internal( + internal: Box, A>, + height: NonZero, + ) -> Self + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Box_in(t, internal, ?id, ?contents) &*& contents.data.parent == Option::None &*& + exists::(?k) &*& [?available]lifetime_token(k) &*& lifetime_inclusion(k, id.lft) == true &*& + child_headers(?children) &*& contents.data.len <= CAPACITY &*& length(children) == contents.data.len + 1 &*& + exists::>>>(?tail) &*& + Array_elems(contents.edges) == append(initialized_edges(children), tail); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [available/2]lifetime_token(k) &*& result.height == height.get() &*& 0 < result.height &*& + exists::>>(?node) &*& result.node.as_ptr() == &(*node.as_ptr()).data &*& + allocated_internal(node.as_ptr(), id, k, available/2) &*& + (*result.node.as_ptr()).parent |-> Option::None &*& + (*result.node.as_ptr()).parent_idx |-> contents.data.parent_idx &*& + internal_slots(node, contents.data.len, children, Array_elems(contents.data.keys), Array_elems(contents.data.vals)); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(k); + //@ open exists(tail); + let (node, _alloc) = Box::into_non_null_with_allocator(internal); + //@ std::alloc::Allocator_to_own(_alloc); + //@ let root = node.as_ptr(); + //@ std::ptr::NonNull_Sized_as_ptr(node); + //@ close reserve_allocation(k, available/2); + //@ let q_alloc = lifetime_token_trade(k, available/2, id.lft); + //@ open_points_to_at_lft(root, q_alloc); + //@ points_to_limits(root); + //@ open_points_to(root); + //@ close_points_to(&(*root).edges); + //@ Array_to_array(&(*root).edges); + //@ close_points_to(&(*root).data.keys); + //@ Array_to_array(&(*root).data.keys); + //@ close_points_to(&(*root).data.vals); + //@ Array_to_array(&(*root).data.vals); + //@ close allocated_internal(root, id, k, available/2); + //@ open reserve_allocation(k, available/2); + //@ std::num::NonZero_usize_limits(height); + let mut this = NodeRef { height: height.into(), node: node.cast(), _marker: PhantomData }; + //@ std::ptr::NonNull_new_as_ptr(this.node); + //@ close exists(node); + //@ close exists(tail); + unsafe { this.borrow_mut().correct_all_childrens_parent_links() }; + //@ close node_arrays(root, Array_elems(contents.data.keys), Array_elems(contents.data.vals), Array_elems(contents.edges)); + //@ initialized_edge_count(children); + //@ take_append_l(length(children), initialized_edges(children), tail); + //@ close internal_slots(node, contents.data.len, children, Array_elems(contents.data.keys), Array_elems(contents.data.vals)); + //@ close exists(node); + this + } +} + +// The two half permissions describe the same cells. Their agreement +// carries the element list through the enclosing Box value. +/*@ +lem close_known_array(p: *[T; N]) + req (p as *T)[..int_of_const(typeid(N))] |-> ?values; + ens *p |-> ?value &*& Array_elems(value) == values; +{ + let base = p as *T; + close_points_to(p, 1/2); + assert [1/2](*p |-> ?value); + Array_to_array(p); + merge_fractions array(base, int_of_const(typeid(N)), _); + assert Array_elems(value) == values; + close_points_to(p); +} +@*/ + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { + unsafe fn split_production_internal( + mut self, alloc: A, + ) -> SplitResult<'a, K, V, marker::Internal> + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t, alloc, ?id) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& + lifetime_inclusion(k, id.lft) == true &*& self.node.height > 0 &*& + exists::>>(?left) &*& self.node.node.as_ptr() == &(*left.as_ptr()).data &*& + leaf_header(self.node.node.as_ptr(), ?parent, ?parent_idx) &*& struct_InternalNode_padding(left.as_ptr()) &*& + internal_slots(left, ?len, ?children, ?keys, ?vals) &*& 0 <= self.idx &*& self.idx < len &*& + nth(self.idx, keys).inner() == some(?key) &*& nth(self.idx, vals).inner() == some(?val) &*& + .own(t, key) &*& .own(t, val); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [available/2]lifetime_token(k) &*& result.left == self.node &*& result.right.height == self.node.height &*& + result.right.node.as_ptr() != self.node.node.as_ptr() &*& + leaf_header(self.node.node.as_ptr(), parent, parent_idx) &*& struct_InternalNode_padding(left.as_ptr()) &*& + internal_slots(left, self.idx, take(self.idx + 1, children), keys, vals) &*& + exists::>>(?right) &*& result.right.node.as_ptr() == &(*right.as_ptr()).data &*& + allocated_internal(right.as_ptr(), id, k, available/2) &*& + (*result.right.node.as_ptr()).parent |-> Option::None &*& + (*result.right.node.as_ptr()).parent_idx |-> ?right_parent_idx &*& + internal_slots(right, len - self.idx - 1, drop(self.idx + 1, children), ?new_keys, ?new_vals) &*& + take(len - self.idx - 1, new_keys) == take(len - self.idx - 1, drop(self.idx + 1, keys)) &*& + take(len - self.idx - 1, new_vals) == take(len - self.idx - 1, drop(self.idx + 1, vals)) &*& + result.kv.0 == key &*& result.kv.1 == val &*& .own(t, key) &*& .own(t, val); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [available]lifetime_token(k) &*& leaf_header(self.node.node.as_ptr(), parent, parent_idx) &*& + struct_InternalNode_padding(left.as_ptr()) &*& internal_slots(left, len, children, keys, vals) &*& + .own(t, key) &*& .own(t, val); + @*/ + { + //@ open exists(k); + //@ open exists(left); + //@ assert *&self |-> ?incoming; + //@ let source = incoming.node.node.as_ptr(); + //@ let left_ptr = left.as_ptr(); + //@ let first = incoming.idx + 1; + //@ let suffix_len = len - first; + //@ let moved_count = suffix_len + 1; + //@ let kept = take(first, children); + //@ let moved = drop(first, children); + //@ std::ptr::NonNull_Sized_as_ptr(left); + //@ std::ptr::NonNull_Sized_as_ptr(incoming.node.node); + //@ open internal_slots(left, len, children, keys, vals); + //@ open_points_to(&self); + //@ let len_view = precreate_ref(&self.node); + //@ init_ref_readonly(len_view, 1/2); + let old_len = unsafe { self.node.merge_len() }; + //@ end_ref_readonly(len_view); + //@ merge_fractions points_to(&self.node, _); + //@ close_points_to(&self); + //@ close internal_slots(left, len, children, keys, vals); + let mut new_node = unsafe { InternalNode::::new(alloc) }; + //@ open internal_slots(left, len, children, keys, vals); + //@ open node_arrays(left_ptr, keys, vals, ?edges); + //@ assert length(keys) == CAPACITY && length(vals) == CAPACITY; + //@ close leaf_slots(source, len, keys, vals); + //@ let contents = std::boxed::Box_separate_contents(&mut new_node); + //@ let q_box = lifetime_token_trade(k, available, id.lft); + //@ open_points_to_at_lft(contents, q_box); + //@ points_to_limits(contents); + //@ assert *contents |-> ?initial; + //@ open_points_to(contents); + //@ close_points_to(&(*contents).data); + let kv = self.split_leaf_data/*@::<'a,K,V,marker::Internal,'a,'a>@*/({ //~track_ref_creation + let destination = &mut new_node.data; //~track_ref_creation + //@ open_points_to(destination); + //@ close leaf_header(destination, Option::None, initial.data.parent_idx); + //@ close leaf_slots(destination, 0, _, _); + //@ assert leaf_slots(destination, 0, ?initial_keys, ?initial_vals); + destination + }); + //@ assert ref_mut_end_token(?source_view, &mut self); + //@ assert ref_mut_end_token(?right_view, &(*contents).data); + //@ assert leaf_slots(right_view, suffix_len, ?split_keys, ?split_vals); + //@ close_points_to(right_view); + //@ end_ref_mut(right_view); + //@ end_ref_mut(source_view); + //@ open_points_to(&(*contents).data); + let new_len = usize::from(new_node.data.len); + + //@ open leaf_slots(source, incoming.idx, keys, vals); + //@ open leaf_header(source, parent, parent_idx); + //@ close_points_to(source); + //@ close internal_without_edges(left_ptr, _); + //@ assert (*contents).edges[..CAPACITY + 1] |-> ?fresh_edges; + //@ open_points_to(&self); + move_to_slice( + self.node.edge_area_range_mut/*@::<'a,K,V,'a>@*/(self.idx + 1..old_len + 1), //~track_ref_creation + { + //@ close_points_to(&(*contents).edges); + let right_array = &mut new_node.edges; //~track_ref_creation + //@ open_points_to(right_array); + //@ let right_base = right_array as *MaybeUninit>; + //@ insertion_slot_limits(right_base); + //@ move_slice_offset(right_base, CAPACITY + 1, moved_count); + //@ array_split(right_base, moved_count); + let right_edges = &mut right_array[..new_len + 1]; + //@ close move_slice(right_edges as *MaybeUninit>, moved_count, _); + right_edges + }, + ); + //@ assert ref_mut_end_token(?node_view, &(*&self).node); + //@ assert edges_range_loan(left_ptr, ?left_edges, first, len + 1, ?left_data, _, _); + //@ end_edges_range(left_ptr, left_edges); + //@ end_ref_mut(node_view); + //@ close_points_to(&self); + + //@ let copied = take(moved_count, drop(first, edges)); + //@ assert ref_mut_end_token(?right_lent, &(*contents).edges); + //@ let right_lent_base = right_lent as *MaybeUninit>; + //@ assert slice_ref_mut_end_token(?right_lent_slice, right_lent_base, moved_count); + //@ open move_slice(right_lent_slice as *MaybeUninit>, moved_count, copied); + //@ end_slice_ref_mut(right_lent_slice); + //@ array_join(right_lent_base); + //@ close_points_to(right_lent); + //@ end_ref_mut(right_lent); + //@ open_points_to(&(*contents).edges); + + //@ take_after_drop(edges, first, moved_count); + //@ append_take_drop_n(children, first); + //@ initialized_edges_append(kept, moved); + //@ initialized_edge_count(kept); + //@ initialized_edge_count(moved); + //@ drop_append(first, initialized_edges(kept), initialized_edges(moved)); + //@ drop_0(initialized_edges(moved)); + //@ assert copied == initialized_edges(moved); + //@ let tail = drop(moved_count, fresh_edges); + //@ close_known_array(&(*contents).edges); + //@ open_points_to(&(*contents).edges); + //@ close_known_array(&(*contents).data.keys); + //@ open_points_to(&(*contents).data.keys); + //@ close_known_array(&(*contents).data.vals); + //@ open_points_to(&(*contents).data.vals); + //@ close_points_to(contents); + //@ close_points_to_at_lft(contents); + //@ lifetime_token_trade_back(q_box, id.lft); + //@ std::boxed::Box_unseparate_contents(&mut new_node); + //@ split_linked_headers(children, left, 0, first); + //@ forget_link_indices(moved, left, first); + //@ close exists(k); + //@ close exists(tail); + //@ open_points_to(&self); + //@ open_points_to(&self.node); + let height = NonZero::new_unchecked(self.node.height); + //@ close_points_to(&self.node); + let right = NodeRef::::from_new_internal(new_node, height); + + //@ open internal_without_edges(left_ptr, left_data); + //@ open_points_to(source); + //@ close leaf_header(source, parent, parent_idx); + //@ drop_twice(moved_count, first, edges); + //@ append_take_drop_n(drop(first, edges), moved_count); + //@ append_take_drop_n(edges, first); + //@ close node_arrays(left_ptr, keys, vals, edges); + //@ take_twice(edges, first, len + 1); + //@ take_append_l(first, initialized_edges(kept), initialized_edges(moved)); + //@ close internal_slots(left, incoming.idx, kept, keys, vals); + //@ length_drop(first, keys); + //@ length_drop(first, vals); + //@ length_take(suffix_len, drop(first, keys)); + //@ length_take(suffix_len, drop(first, vals)); + //@ take_append_l(suffix_len, take(suffix_len, drop(first, keys)), drop(suffix_len, initial_keys)); + //@ take_append_l(suffix_len, take(suffix_len, drop(first, vals)), drop(suffix_len, initial_vals)); + //@ assert exists::>>(?new_right); + //@ open exists(new_right); + // Both nodes own their length fields exclusively. + /*@ if right.node.as_ptr() == source { + open internal_slots(left, incoming.idx, kept, keys, vals); + open internal_slots(new_right, suffix_len, moved, _, _); + merge_fractions LeafNode_len_(source, _); + } @*/ + //@ close exists(new_right); + let result = SplitResult { left: self.node, kv, right }; + //@ close_points_to(&self); + result + } +} + +// Production insertion into an internal B-tree node. + +/*@ +fix inserted_prefix(slots: list>, n: usize, index: usize, value: T) -> list> { + append( + append(take(index, take(n, slots)), cons(MaybeUninit::new(value), take(n - index - 1, drop(index, take(n, slots))))), + drop(n, slots)) +} + +lem nth_inserted_prefix(slots: list>, n: usize, index: usize, value: T) + req 0 <= index &*& index < n &*& n <= length(slots); + ens nth(index, inserted_prefix(slots, n, index, value)) == MaybeUninit::new(value); +{ + let before = take(index, take(n, slots)); + let rest = cons(MaybeUninit::new(value), take(n - index - 1, drop(index, take(n, slots)))); + length_take(n, slots); + length_take(index, take(n, slots)); + length_append(before, rest); + nth_append_r(before, rest, 0); + nth_append(append(before, rest), drop(n, slots), index); +} +@*/ + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { + unsafe fn insert_fit_production<'short>(&'short mut self, key: K, val: V, edge: Root) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,val) &*& + *self |-> ?incoming &*& incoming.node.height > 0 &*& edge.height == incoming.node.height - 1 &*& + exists::>>(?parent) &*& incoming.node.node.as_ptr() == &(*parent.as_ptr()).data &*& + leaf_header(incoming.node.node.as_ptr(), ?ancestor, ?parent_idx) &*& struct_InternalNode_padding(parent.as_ptr()) &*& + internal_slots(parent, ?len, ?children, ?keys, ?vals) &*& 0 <= incoming.idx &*& incoming.idx <= len &*& len < CAPACITY &*& + detached_child(edge.node.as_ptr()); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,val) &*& *self |-> incoming &*& + leaf_header(incoming.node.node.as_ptr(), ancestor, parent_idx) &*& struct_InternalNode_padding(parent.as_ptr()) &*& + internal_slots(parent, len + 1, append(take(incoming.idx+1, children), cons(edge.node, drop(incoming.idx+1, children))), + ?fitted_keys, ?fitted_vals) &*& + fitted_keys == inserted_prefix(keys, len + 1, incoming.idx, key) &*& + fitted_vals == inserted_prefix(vals, len + 1, incoming.idx, val) &*& + nth(incoming.idx, fitted_keys).inner() == some(key) &*& nth(incoming.idx, fitted_vals).inner() == some(val); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ let node = incoming.node.node.as_ptr(); + //@ let parent_ptr = parent.as_ptr(); + //@ let right = edge.node; + //@ let index = incoming.idx; + //@ std::ptr::NonNull_Sized_as_ptr(parent); + //@ std::ptr::NonNull_Sized_as_ptr(incoming.node.node); + //@ open internal_slots(parent, len, children, keys, vals); + //@ open node_arrays(parent_ptr, keys, vals, ?edges); + //@ open_points_to(self); + //@ let cap_view = precreate_ref(&(*self).node); + //@ init_ref_readonly(cap_view, 1/2); + debug_assert!(self.node.merge_len() < CAPACITY); + //@ end_ref_readonly(cap_view); + //@ merge_fractions points_to(&(*self).node, _); + //@ open_points_to(&(*self).node); + debug_assert!(edge.height == self.node.height - 1); + //@ close_points_to(&(*self).node); + //@ let len_view = precreate_ref(&(*self).node); + //@ init_ref_readonly(len_view, 1/2); + let new_len = self.node.merge_len() + 1; + //@ end_ref_readonly(len_view); + //@ merge_fractions points_to(&(*self).node, _); + + //@ open leaf_header(node, ancestor, parent_idx); + //@ close leaf_without_keys(node, ancestor, parent_idx, len as u16, vals); + slice_insert( + { + let keys_view = self.node.key_area_prefix_mut/*@::<'a,K,V,marker::Internal,'short>@*/(..new_len); //~track_ref_creation + //@ open move_slice(keys_view as *MaybeUninit, len + 1, _); + keys_view + }, + self.idx, key, + ); + //@ assert ref_mut_end_token(?keys_receiver, &(*self).node); + //@ assert keys_range_loan(node, ?keys_lent, 0, len + 1, ancestor, parent_idx, len as u16, vals, _, _); + //@ close move_slice(keys_lent as *MaybeUninit, len + 1, _); + //@ end_keys_range(node, keys_lent); + //@ end_ref_mut(keys_receiver); + //@ open leaf_without_keys(node, ancestor, parent_idx, len as u16, vals); + //@ assert (*node).keys[..CAPACITY] |-> ?fitted_keys; + //@ take_0(keys); + //@ drop_0(keys); + //@ nth_inserted_prefix(keys, len + 1, index, key); + //@ close leaf_without_vals(node, ancestor, parent_idx, len as u16, fitted_keys); + slice_insert( + { + let vals_view = self.node.val_area_prefix_mut/*@::<'a,K,V,marker::Internal,'short>@*/(..new_len); //~track_ref_creation + //@ open move_slice(vals_view as *MaybeUninit, len + 1, _); + vals_view + }, + self.idx, val, + ); + //@ assert ref_mut_end_token(?vals_receiver, &(*self).node); + //@ assert vals_range_loan(node, ?vals_lent, 0, len + 1, ancestor, parent_idx, len as u16, fitted_keys, _, _); + //@ close move_slice(vals_lent as *MaybeUninit, len + 1, _); + //@ end_vals_range(node, vals_lent); + //@ end_ref_mut(vals_receiver); + //@ open leaf_without_vals(node, ancestor, parent_idx, len as u16, fitted_keys); + //@ assert (*node).vals[..CAPACITY] |-> ?fitted_vals; + //@ take_0(vals); + //@ drop_0(vals); + //@ nth_inserted_prefix(vals, len + 1, index, val); + + //@ close_points_to(node); + //@ close internal_without_edges(parent_ptr, _); + //@ std::ptr::close_NonNull_own(t, right); + //@ produce_type_interp::>>(); + slice_insert( + { + let edges_view = self.node.edge_area_prefix_mut/*@::<'a,K,V,'short>@*/(..new_len + 1); //~track_ref_creation + //@ open move_slice(edges_view as *MaybeUninit>, len + 2, _); + edges_view + }, + self.idx + 1, edge.node, + ); + //@ leak >>.own(t,right); + //@ std::ptr::open_NonNull_own(t,right); + //@ leak type_interp::>>(); + //@ assert ref_mut_end_token(?edges_receiver, &(*self).node); + //@ assert edges_range_loan(parent_ptr, ?edges_lent, 0, len + 2, ?data, _, _); + //@ close move_slice(edges_lent as *MaybeUninit>, len + 2, _); + //@ end_edges_range(parent_ptr, edges_lent); + //@ end_ref_mut(edges_receiver); + //@ open internal_without_edges(parent_ptr, data); + //@ open_points_to(node); + + //@ close leaf_without_len(node, ancestor, parent_idx, fitted_keys, fitted_vals); + *self.node.len_mut/*@::<'a,K,V,marker::Internal,'short>@*/() = new_len as u16; //~track_ref_creation + //@ assert ref_mut_end_token(?len_receiver, &(*self).node); + //@ assert len_loan(node, ?new_length, ancestor, parent_idx, fitted_keys, fitted_vals); + //@ end_len_loan(node, new_length); + //@ end_ref_mut(len_receiver); + //@ open leaf_without_len(node, ancestor, parent_idx, fitted_keys, fitted_vals); + + //@ let before = take(index + 1, children); + //@ let after = drop(index + 1, children); + //@ let inserted = cons(right, after); + //@ let inactive = drop(len + 2, edges); + //@ split_linked_headers(children, parent, 0, index + 1); + //@ forget_link_indices(after, parent, index + 1); + //@ open detached_child(right.as_ptr()); + //@ close child_headers(inserted); + //@ length_take(index + 1, children); + //@ length_drop(index + 1, children); + //@ initialized_edge_split(children, index + 1); + //@ initialized_edge_count(before); + //@ initialized_edge_count(inserted); + //@ take_after_drop(edges, index + 1, len - index); + //@ take_after_drop(edges, index + 1, len + 1 - index); + //@ take_twice(drop(index + 1, edges), len - index, len + 1 - index); + //@ take_twice(edges, index + 1, len + 2); + //@ take_twice(edges, index + 1, len + 1); + //@ append_assoc(initialized_edges(before), initialized_edges(inserted), inactive); + //@ close exists(parent); + //@ close exists(pair(initialized_edges(before), inactive)); + self.node.relink_range/*@::<'a,K,V,'short>@*/(self.idx + 1..new_len + 1); //~track_ref_creation + //@ assert ref_mut_end_token(?relink_receiver, &(*self).node); + //@ end_ref_mut(relink_receiver); + //@ join_linked_headers(before, inserted, parent, 0); + //@ initialized_edges_append(before, inserted); + //@ let active = initialized_edges(append(before, inserted)); + //@ take_append_l(len + 2, active, inactive); + //@ take_length(active); + //@ close node_arrays(parent_ptr, fitted_keys, fitted_vals, append(active, inactive)); + //@ close internal_slots(parent, len + 1, append(before, inserted), fitted_keys, fitted_vals); + //@ close leaf_header(node, ancestor, parent_idx); + //@ close_points_to(self); + } +} + +/*@ +fix insert_item(items: list, at: usize, item: T) -> list { + append(take(at, items), cons(item, drop(at, items))) +} + +lem insert_item_across_split(items: list, cut: usize, at: usize, item: T) + req 0 <= cut &*& cut <= length(items) &*& 0 <= at &*& at <= length(items); + ens insert_item(items, at, item) == if at <= cut { + append(insert_item(take(cut, items), at, item), drop(cut, items)) + } else { + append(take(cut, items), insert_item(drop(cut, items), at - cut, item)) + }; +{ + if at <= cut { + take_twice(items, at, cut); + take_after_drop(items, at, cut - at); + drop_twice(cut - at, at, items); + append_take_drop_n(drop(at, items), cut - at); + append_assoc(take(at, items), cons(item, drop(at, take(cut, items))), drop(cut, items)); + } else { + length_take(cut, items); + append_take_drop_n(items, cut); + take_append(at, take(cut, items), drop(cut, items)); + drop_twice(at - cut, cut, items); + append_assoc(take(cut, items), take(at - cut, drop(cut, items)), cons(item, drop(at, items))); + } +} +@*/ + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { + unsafe fn insert_production( + mut self, key: K, val: V, edge: Root, alloc: A, + ) -> Option> + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t, alloc, ?id) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& + lifetime_inclusion(k, id.lft) == true &*& self.node.height > 0 &*& edge.height == self.node.height - 1 &*& + exists::>>(?parent) &*& self.node.node.as_ptr() == &(*parent.as_ptr()).data &*& + leaf_header(self.node.node.as_ptr(), ?ancestor, ?parent_idx) &*& struct_InternalNode_padding(parent.as_ptr()) &*& + internal_slots(parent, ?len, ?children, ?keys, ?vals) &*& 0 <= self.idx &*& self.idx <= len &*& + pivot_owner(t, len, self.idx, keys, vals) &*& detached_child(edge.node.as_ptr()) &*& .own(t, key) &*& .own(t, val); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + .own(t, key) &*& .own(t, val) &*& leaf_header(self.node.node.as_ptr(), ancestor, parent_idx) &*& + struct_InternalNode_padding(parent.as_ptr()) &*& + match result { + Option::None => len < CAPACITY &*& [available]lifetime_token(k) &*& + internal_slots(parent, len + 1, insert_item(children, self.idx + 1, edge.node), ?fitted_keys, ?fitted_vals) &*& + nth(self.idx, fitted_keys).inner() == some(key) &*& nth(self.idx, fitted_vals).inner() == some(val), + Option::Some(split) => len == CAPACITY &*& [available/2]lifetime_token(k) &*& split.left == self.node &*& + split.right.height == self.node.height &*& split.right.node.as_ptr() != self.node.node.as_ptr() &*& + exists::>>(?sibling) &*& split.right.node.as_ptr() == &(*sibling.as_ptr()).data &*& + allocated_internal(sibling.as_ptr(), id, k, available/2) &*& + (*split.right.node.as_ptr()).parent |-> Option::None &*& (*split.right.node.as_ptr()).parent_idx |-> ?right_parent_idx &*& + internal_slots(parent, ?left_len, ?left_children, ?left_keys, ?left_vals) &*& + internal_slots(sibling, ?right_len, ?right_children, ?right_keys, ?right_vals) &*& left_len + right_len == len &*& + append(left_children, right_children) == insert_item(children, self.idx + 1, edge.node) &*& + nth(insertion_pivot(self.idx), keys).inner() == some(split.kv.0) &*& + nth(insertion_pivot(self.idx), vals).inner() == some(split.kv.1) &*& + .own(t, split.kv.0) &*& .own(t, split.kv.1) &*& + if self.idx < left_len { + nth(self.idx, left_keys).inner() == some(key) &*& nth(self.idx, left_vals).inner() == some(val) + } else { + nth(self.idx - left_len - 1, right_keys).inner() == some(key) &*& + nth(self.idx - left_len - 1, right_vals).inner() == some(val) + } + }; + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [available]lifetime_token(k) &*& leaf_header(self.node.node.as_ptr(), ancestor, parent_idx) &*& + struct_InternalNode_padding(parent.as_ptr()) &*& + internal_slots(parent, len, children, keys, vals) &*& detached_child(edge.node.as_ptr()) &*& + if len == CAPACITY { + nth(insertion_pivot(self.idx), keys).inner() == some(?pivot_key) &*& + nth(insertion_pivot(self.idx), vals).inner() == some(?pivot_val) &*& + .own(t, pivot_key) &*& .own(t, pivot_val) + } else { true }; + @*/ + { + //@ open exists(k); + //@ open exists(parent); + //@ assert *&self |-> ?incoming; + //@ let source = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ std::ptr::NonNull_Sized_as_ptr(parent); + //@ std::ptr::NonNull_Sized_as_ptr(incoming.node.node); + //@ open_points_to(&self); + //@ open_points_to(&self.node); + assert!(edge.height == self.node.height - 1); + //@ close_points_to(&self.node); + //@ open internal_slots(parent, len, children, keys, vals); + //@ let len_view = precreate_ref(&self.node); + //@ init_ref_readonly(len_view, 1/2); + let fits = self.node.merge_len() < CAPACITY; + //@ end_ref_readonly(len_view); + //@ merge_fractions points_to(&self.node, _); + //@ close internal_slots(parent, len, children, keys, vals); + if fits { + //@ open pivot_owner(t, len, index, keys, vals); + //@ close_points_to(&self); + //@ close exists(parent); + self.insert_fit_production/*@::<'a,K,V,'a>@*/(key, val, edge); //~track_ref_creation + //@ assert ref_mut_end_token(?this_view, &mut self); + //@ end_ref_mut(this_view); + //@ std::alloc::Allocator_to_own(alloc); + None + } else { + let (middle_kv_idx, insertion) = splitpoint(self.idx); + //@ open internal_slots(parent, len, children, keys, vals); + let middle = unsafe { Handle::,K,V,marker::Internal>,marker::KV>::new_kv/*@::,K,V>@*/(self.node, middle_kv_idx) }; + //@ close_points_to(&self); + //@ close internal_slots(parent, len, children, keys, vals); + //@ open pivot_owner(t, len, index, keys, vals); + //@ close exists(k); + //@ close exists(parent); + let mut result = middle.split_production_internal/*@::<'a,K,V,A>@*/(alloc); + //@ open exists::>>(?sibling); + //@ let right = sibling.as_ptr(); + //@ let inserted_edge_index = incoming.idx + 1; + //@ let first_right_edge = middle_kv_idx + 1; + //@ let right_count = len - first_right_edge; + let mut insertion_edge = match insertion { + LeftOrRight::Left(insert_idx) => unsafe { + //@ open internal_slots(parent, middle_kv_idx, take(first_right_edge, children), keys, vals); + let selected = Handle::,K,V,marker::Internal>,marker::Edge>::new_edge( + result.left.reborrow_mut(), insert_idx, + ); + //@ close internal_slots(parent, middle_kv_idx, take(first_right_edge, children), keys, vals); + selected + }, + LeftOrRight::Right(insert_idx) => unsafe { + //@ std::ptr::NonNull_Sized_as_ptr(sibling); + //@ open internal_slots(sibling, right_count, drop(first_right_edge, children), _, _); + let selected = Handle::,K,V,marker::Internal>,marker::Edge>::new_edge( + result.right.borrow_mut(), insert_idx, + ); + //@ close internal_slots(sibling, right_count, drop(first_right_edge, children), _, _); + selected + }, + }; + /*@ match insertion { + LeftOrRight::Left(at) => { + close exists(parent); + } + LeftOrRight::Right(at) => { + open allocated_internal(right, id, k, available/2); + close leaf_header(&(*right).data, Option::None, _); + close exists(sibling); + } + } @*/ + //@ close_points_to(&insertion_edge.node); + insertion_edge.insert_fit_production/*@::<'a,K,V,'a>@*/(key, val, edge); //~track_ref_creation + //@ assert ref_mut_end_token(?finished, &mut insertion_edge); + //@ end_ref_mut(finished); + //@ open_points_to(&insertion_edge); + //@ open_points_to(&insertion_edge.node); + //@ insert_item_across_split(children, first_right_edge, inserted_edge_index, edge.node); + /*@ match insertion { + LeftOrRight::Left(at) => {} + LeftOrRight::Right(at) => { + open leaf_header(&(*right).data, Option::None, _); + close allocated_internal(right, id, k, available/2); + } + } @*/ + //@ close exists(sibling); + Some(result) + } + } +} + +/*@ +pred ancestor_tail( + node: *LeafNode, path: list>, root: *LeafNode, root_index: MaybeUninit; + parent: Option>>, parent_idx: MaybeUninit +) = + match path { + nil => node == root &*& parent == Option::None &*& parent_idx == root_index, + cons(step, remaining) => + match step { + ParentStep(upper, idx, len, payload) => + parent == Option::Some(NonNull::new(upper)) &*& parent_idx == MaybeUninit::new(idx) &*& + parent_payload(node, upper, idx, len, payload) &*& + ancestors(&(*upper).data, remaining, root) &*& (*root).parent_idx |-> root_index + } + }; + +lem open_ancestor_header(node: *LeafNode, path: list>, root: *LeafNode) + req ancestors(node, path, root) &*& (*root).parent_idx |-> ?root_index &*& struct_LeafNode_padding(node); + ens ancestor_tail(node, path, root, root_index, ?parent, ?idx) &*& leaf_header(node, parent, idx); +{ + open ancestors(node, path, root); + match path { + nil => { + open link(node, Option::None, 0); + close leaf_header(node, Option::None, root_index); + close ancestor_tail(node, path, root, root_index, Option::None, root_index); + } + cons(step, remaining) => { + match step { + ParentStep(upper, idx, len, payload) => { + let parent = Option::Some(NonNull::new(upper)); + open link(node, parent, idx); + close leaf_header(node, parent, MaybeUninit::new(idx)); + close ancestor_tail(node, path, root, root_index, parent, MaybeUninit::new(idx)); + } + } + } + } +} + +lem close_ancestor_header(node: *LeafNode, path: list>, root: *LeafNode) + req ancestor_tail(node, path, root, ?root_index, ?parent, ?parent_idx) &*& leaf_header(node, parent, parent_idx); + ens ancestors(node, path, root) &*& (*root).parent_idx |-> root_index &*& struct_LeafNode_padding(node); +{ + open leaf_header(node, parent, parent_idx); + open ancestor_tail(node, path, root, root_index, parent, parent_idx); + match path { + nil => { close link(node, Option::None, 0); } + cons(step, remaining) => { + match step { + ParentStep(upper, idx, len, payload) => { close link(node, Option::Some(NonNull::new(upper)), idx); } + } + } + } + close ancestors(node, path, root); +} +@*/ + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { + unsafe fn insert_fit_leaf_production(mut self, key: K, val: V) + -> Handle, K, V, marker::Leaf>, marker::KV> + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,val) &*& + self.node.height == 0 &*& leaf_header(self.node.node.as_ptr(), ?ancestor, ?parent_idx) &*& + leaf_slots(self.node.node.as_ptr(), ?len, ?keys, ?vals) &*& 0 <= self.idx &*& self.idx <= len &*& len < CAPACITY; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,val) &*& + result.node == self.node &*& result.idx == self.idx &*& + leaf_header(self.node.node.as_ptr(), ancestor, parent_idx) &*& + dormant_pair(self.node.node.as_ptr(), self.idx, MaybeUninit::new(key), MaybeUninit::new(val)) &*& + leaf_rest(self.node.node.as_ptr(),self.idx); + @*/ + //@ on_unwind_ens false; + { + //@ assert *&self |-> ?incoming; + //@ let node = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ std::ptr::NonNull_Sized_as_ptr(incoming.node.node); + //@ open leaf_slots(node, len, keys, vals); + //@ open_points_to(&self); + //@ let cap_view = precreate_ref(&self.node); + //@ init_ref_readonly(cap_view, 1/2); + debug_assert!(self.node.merge_len() < CAPACITY); + //@ end_ref_readonly(cap_view); + //@ merge_fractions points_to(&self.node, _); + //@ let len_view = precreate_ref(&self.node); + //@ init_ref_readonly(len_view, 1/2); + let new_len = self.node.merge_len() + 1; + //@ end_ref_readonly(len_view); + //@ merge_fractions points_to(&self.node, _); + //@ open leaf_header(node, ancestor, parent_idx); + //@ close leaf_without_keys(node, ancestor, parent_idx, len as u16, vals); + slice_insert( + { + let keys_view = self.node.key_area_prefix_mut/*@::<'a,K,V,marker::Leaf,'a>@*/(..new_len); //~track_ref_creation + //@ open move_slice(keys_view as *MaybeUninit, len + 1, _); + keys_view + }, + self.idx, key, + ); + //@ assert ref_mut_end_token(?keys_receiver, &self.node); + //@ assert keys_range_loan(node, ?keys_lent, 0, len + 1, ancestor, parent_idx, len as u16, vals, _, _); + //@ close move_slice(keys_lent as *MaybeUninit, len + 1, _); + //@ end_keys_range(node, keys_lent); + //@ end_ref_mut(keys_receiver); + //@ open leaf_without_keys(node, ancestor, parent_idx, len as u16, vals); + //@ assert (*node).keys[..CAPACITY] |-> ?fitted_keys; + //@ take_0(keys); + //@ drop_0(keys); + //@ nth_inserted_prefix(keys, len + 1, index, key); + //@ close leaf_without_vals(node, ancestor, parent_idx, len as u16, fitted_keys); + slice_insert( + { + let vals_view = self.node.val_area_prefix_mut/*@::<'a,K,V,marker::Leaf,'a>@*/(..new_len); //~track_ref_creation + //@ open move_slice(vals_view as *MaybeUninit, len + 1, _); + vals_view + }, + self.idx, val, + ); + //@ assert ref_mut_end_token(?vals_receiver, &self.node); + //@ assert vals_range_loan(node, ?vals_lent, 0, len + 1, ancestor, parent_idx, len as u16, fitted_keys, _, _); + //@ close move_slice(vals_lent as *MaybeUninit, len + 1, _); + //@ end_vals_range(node, vals_lent); + //@ end_ref_mut(vals_receiver); + //@ open leaf_without_vals(node, ancestor, parent_idx, len as u16, fitted_keys); + //@ assert (*node).vals[..CAPACITY] |-> ?fitted_vals; + //@ take_0(vals); + //@ drop_0(vals); + //@ nth_inserted_prefix(vals, len + 1, index, val); + + //@ close leaf_without_len(node, ancestor, parent_idx, fitted_keys, fitted_vals); + *self.node.len_mut/*@::<'a,K,V,marker::Leaf,'a>@*/() = new_len as u16; //~track_ref_creation + //@ assert ref_mut_end_token(?len_receiver, &self.node); + //@ assert len_loan(node, ?new_length, ancestor, parent_idx, fitted_keys, fitted_vals); + //@ end_len_loan(node, new_length); + //@ end_ref_mut(len_receiver); + //@ open leaf_without_len(node, ancestor, parent_idx, fitted_keys, fitted_vals); + let handle = Handle::, K, V, marker::Leaf>, marker::KV>::new_kv/*@::,K,V>@*/(self.node, self.idx); + //@ close_points_to(&self); + //@ close leaf_header(node, ancestor, parent_idx); + //@ let key_base = &(*node).keys as *MaybeUninit; + //@ let val_base = &(*node).vals as *MaybeUninit; + //@ array_split(key_base,index); + //@ array_split(val_base,index); + //@ array_split(key_base+index,1); + //@ array_split(val_base+index,1); + //@ nth_drop(0,index,fitted_keys); + //@ nth_drop(0,index,fitted_vals); + //@ open array(key_base+index,1,_); + //@ open array(val_base+index,1,_); + //@ close dormant_pair(node,index,MaybeUninit::new(key),MaybeUninit::new(val)); + //@ close leaf_rest(node,index); + handle + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { + unsafe fn insert_leaf_production(mut self, key: K, val: V, alloc: A) -> ( + Option>, + Handle, marker::KV>, + ) + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,alloc,?id) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& lifetime_inclusion(k,id.lft) == true &*& + self.node.height == 0 &*& .own(t,key) &*& .own(t,val) &*& + leaf_header(self.node.node.as_ptr(),?ancestor,?parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= self.idx &*& self.idx <= len &*& pivot_owner(t,len,self.idx,keys,vals); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [?remaining]lifetime_token(k) &*& .own(t,key) &*& .own(t,val) &*& result.1.node.height == 0 &*& + leaf_header(self.node.node.as_ptr(),ancestor,parent_idx) &*& + dormant_pair(result.1.node.node.as_ptr(),result.1.idx,MaybeUninit::new(key),MaybeUninit::new(val)) &*& + match result.0 { + Option::None => len < CAPACITY &*& result.1.node.node == self.node.node &*& result.1.idx == self.idx &*& + insertion_leaves(self.node.node,self.node.node,self.idx,Option::None,id,k), + Option::Some(split) => len == CAPACITY &*& split.left == self.node &*& split.right.height == 0 &*& + split.right.node.as_ptr() != self.node.node.as_ptr() &*& + detached_child(split.right.node.as_ptr()) &*& + insertion_leaves(self.node.node,result.1.node.node,result.1.idx,Option::Some(split.right.node),id,k) &*& + nth(insertion_pivot(self.idx),keys).inner() == some(split.kv.0) &*& + nth(insertion_pivot(self.idx),vals).inner() == some(split.kv.1) &*& + .own(t,split.kv.0) &*& .own(t,split.kv.1) + }; + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [?remaining]lifetime_token(k) &*& len == CAPACITY &*& + leaf_header(self.node.node.as_ptr(),ancestor,parent_idx) &*& leaf_slots(self.node.node.as_ptr(),len,keys,vals) &*& + nth(insertion_pivot(self.idx),keys).inner() == some(?promoted_key) &*& + nth(insertion_pivot(self.idx),vals).inner() == some(?promoted_val) &*& + .own(t,promoted_key) &*& .own(t,promoted_val); + @*/ + { + //@ open exists(k); + //@ assert *&self |-> ?entry; + //@ let left = entry.node.node; + //@ let index = entry.idx; + //@ std::ptr::NonNull_Sized_as_ptr(left); + //@ open leaf_slots(left.as_ptr(),len,keys,vals); + //@ open_points_to(&self); + //@ let len_view = precreate_ref(&self.node); + //@ init_ref_readonly(len_view,1/2); + let fits = unsafe { self.node.merge_len() < CAPACITY }; + //@ end_ref_readonly(len_view); + //@ merge_fractions points_to(&self.node,_); + //@ close leaf_slots(left.as_ptr(),len,keys,vals); + if fits { + //@ open pivot_owner(t,len,index,keys,vals); + //@ open_points_to(&self.node); + let kv_handle = unsafe { self.insert_fit_leaf_production(key,val) }; + //@ close_points_to(&self.node); + //@ close_points_to(&kv_handle.node,1/2); + let dormant = unsafe { kv_handle.dormant/*@::<'a,K,V,marker::Leaf,marker::KV,'a>@*/() }; + //@ open_points_to(&kv_handle); + //@ open_points_to(&kv_handle.node); + //@ close Handle_node_(&self, some(entry.node)); + //@ std::alloc::Allocator_to_own(alloc); + //@ close insertion_leaves(left,left,index,Option::None,id,k); + (None, dormant) + } else { + let (middle_kv_idx, insertion) = unsafe { splitpoint(self.idx) }; + //@ open leaf_slots(left.as_ptr(),len,keys,vals); + //@ open_points_to(&self.node); + let middle = unsafe { + Handle::, K, V, marker::Leaf>, marker::KV>::new_kv/*@::,K,V>@*/( + self.node, middle_kv_idx + ) + }; + //@ close_points_to(&self.node); + //@ close Handle_node_(&self, some(entry.node)); + //@ close leaf_slots(left.as_ptr(),len,keys,vals); + //@ open pivot_owner(t,len,index,keys,vals); + //@ close exists(k); + let mut result = unsafe { middle.split_production_leaf/*@::<'a,K,V,A>@*/(alloc) }; + //@ let right = result.right.node; + //@ std::ptr::NonNull_Sized_as_ptr(right); + let insertion_edge = match insertion { + LeftOrRight::Left(insert_idx) => unsafe { + //@ open leaf_slots(left.as_ptr(),middle_kv_idx,_,_); + let edge = Handle::, K, V, marker::Leaf>, marker::Edge>::new_edge( + result.left.reborrow_mut(), insert_idx, + ); + //@ close leaf_slots(left.as_ptr(),middle_kv_idx,_,_); + edge + }, + LeftOrRight::Right(insert_idx) => unsafe { + //@ open leaf_slots(right.as_ptr(),CAPACITY-middle_kv_idx-1,_,_); + let edge = Handle::, K, V, marker::Leaf>, marker::Edge>::new_edge( + result.right.borrow_mut(), insert_idx, + ); + //@ close leaf_slots(right.as_ptr(),CAPACITY-middle_kv_idx-1,_,_); + edge + }, + }; + /*@ match insertion { + LeftOrRight::Left(at) => {} + LeftOrRight::Right(at) => { + open allocated_leaf(right.as_ptr(),id,k,available/2); + close leaf_header(right.as_ptr(), Option::None, _); + } + } @*/ + let fitted = unsafe { insertion_edge.insert_fit_leaf_production(key,val) }; + //@ close_points_to(&fitted.node,1/2); + let dormant = unsafe { fitted.dormant/*@::<'a,K,V,marker::Leaf,marker::KV,'a>@*/() }; + //@ open_points_to(&fitted); + //@ open_points_to(&fitted.node); + /*@ match insertion { + LeftOrRight::Left(at) => { + close exists(right); + close insertion_leaves(left,left,at,Option::Some(right),id,k); + } + LeftOrRight::Right(at) => { + open leaf_header(right.as_ptr(), Option::None, _); + close allocated_leaf(right.as_ptr(),id,k,available/2); + close exists(left); + close insertion_leaves(left,right,at,Option::Some(right),id,k); + } + } @*/ + //@ close detached_child(right.as_ptr()); + (Some(result), dormant) + } + } +} + +/*@ +pred leaf_insert_sibling<'a,K,V>( + result: (Option>, Handle,marker::KV>), + entry: Handle,K,V,marker::Leaf>,marker::Edge>, + t: thread_id_t, len: usize, id: std::alloc::alloc_id_t, k: lifetime_t +) = + match result.0 { + Option::None => len < CAPACITY &*& result.1.node.node == entry.node.node &*& result.1.idx == entry.idx &*& + insertion_leaves(entry.node.node,entry.node.node,entry.idx,Option::None,id,k), + Option::Some(split) => len == CAPACITY &*& split.left == entry.node &*& split.right.height == 0 &*& + split.right.node.as_ptr() != entry.node.node.as_ptr() &*& detached_child(split.right.node.as_ptr()) &*& + insertion_leaves(entry.node.node,result.1.node.node,result.1.idx,Option::Some(split.right.node),id,k) &*& + .own(t,split.kv.0) &*& .own(t,split.kv.1) + }; +@*/ + +impl<'tree, K: 'tree, V: 'tree> Handle, K, V, marker::Leaf>, marker::Edge> { + unsafe fn insert_recursing_for_root<'alloc, 'slot, A: AllocatorClone>( + self, key: K, val: V, alloc: &'alloc A, + root_slot: &'slot mut DormantMutRef<'tree, Option>>, + root_allocator: &'slot mut A, + ) -> Handle,K,V,marker::Leaf>,marker::KV> + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + [_]allocator_clone_bound::() &*& + [_]std::alloc::Allocator_share::(?alloc_lifetime,t,alloc,?alloc_id) &*& + [_]frac_borrow(alloc_lifetime, ref_initialized_(alloc)) &*& [?qa]lifetime_token(alloc_lifetime) &*& + exists::(?k) &*& [?available]lifetime_token(k) &*& lifetime_inclusion(k,alloc_id.lft) == true &*& + ancestors(self.node.node.as_ptr(),?path,?root) &*& route_frames(t,path) &*& (*root).parent_idx |-> ?root_index &*& + *root_allocator |-> ?root_alloc &*& Allocator::(t,root_alloc,alloc_id) &*& + *root_slot |-> ?sleeper &*& *sleeper.ptr.as_ptr() |-> Option::Some(?old_root) &*& + old_root.node.as_ptr() == root &*& old_root.height == length(path) &*& + length(path) < usize::MAX &*& self.node.height == 0 &*& + struct_LeafNode_padding(self.node.node.as_ptr()) &*& + leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= self.idx &*& self.idx <= len &*& pivot_owner(t,len,self.idx,keys,vals) &*& + .own(t,key) &*& .own(t,val); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [qa]lifetime_token(alloc_lifetime) &*& [?remaining_fraction]lifetime_token(k) &*& + *root_allocator |-> ?after &*& Allocator::(t,after,alloc_id) &*& *root_slot |-> sleeper &*& + struct_LeafNode_padding(self.node.node.as_ptr()) &*& result.node.height == 0 &*& + .own(t,key) &*& .own(t,val) &*& + dormant_pair(result.node.node.as_ptr(),result.idx,MaybeUninit::new(key),MaybeUninit::new(val)) &*& + exists::>>>(?initial_sibling) &*& + insertion_leaves(self.node.node,result.node.node,result.idx,initial_sibling,alloc_id,k) &*& + match initial_sibling { + Option::None => + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& (*root).parent_idx |-> root_index &*& + ancestors(self.node.node.as_ptr(),path,root) &*& route_frames(t,path), + Option::Some(sibling) => completed_levels::(t,alloc_id,k,?completed) &*& + if length(completed) == length(path) { + *sleeper.ptr.as_ptr() |-> Option::Some(?installed) &*& installed.height == old_root.height + 1 &*& + exists::>>(?new_root) &*& installed.node.as_ptr() == &(*new_root.as_ptr()).data &*& + allocated_internal(new_root.as_ptr(),alloc_id,k,_) &*& (*new_root.as_ptr()).data.parent_idx |-> _ &*& + ancestors(installed.node.as_ptr(),[],installed.node.as_ptr()) &*& + internal_slots(new_root,1,cons(old_root.node,cons(?right,nil)),_,_) &*& .own(t,_) &*& .own(t,_) + } else { + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& (*root).parent_idx |-> root_index &*& + exists::>>(?receiving) &*& ancestors(&(*receiving.as_ptr()).data,?remaining,root) &*& + route_frames(t,remaining) &*& internal_slots(receiving,_,_,_,_) &*& struct_LeafNode_padding(&(*receiving.as_ptr()).data) &*& struct_InternalNode_padding(receiving.as_ptr()) &*& .own(t,_) &*& .own(t,_) &*& + length(completed) + length(remaining) + 1 == length(path) + } + }; + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [qa]lifetime_token(alloc_lifetime) &*& [?remaining_fraction]lifetime_token(k) &*& + *root_allocator |-> ?after &*& Allocator::(t,after,alloc_id) &*& *root_slot |-> sleeper &*& + exists::(?after_leaf) &*& + if after_leaf { + struct_LeafNode_padding(self.node.node.as_ptr()) &*& + exists::<(Option>, Handle,marker::KV>)>(?initial) &*& + .own(t,key) &*& .own(t,val) &*& + dormant_pair(initial.1.node.node.as_ptr(),initial.1.idx,MaybeUninit::new(key),MaybeUninit::new(val)) &*& + match initial.0 { + Option::None => *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& (*root).parent_idx |-> root_index &*& + ancestors(self.node.node.as_ptr(),path,root) &*& route_frames(t,path) &*& + insertion_leaves(self.node.node,initial.1.node.node,initial.1.idx,Option::None,alloc_id,k), + Option::Some(split_leaf) => + insertion_leaves(self.node.node,initial.1.node.node,initial.1.idx,Option::Some(split_leaf.right.node),alloc_id,k) &*& + completed_levels::(t,alloc_id,k,?completed) &*& + if length(completed) == length(path) { + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& detached_child::(?pending_sibling) &*& + exists::>>>(?partial_root) &*& + interrupted_root_change(old_root.node,root_index,alloc_id,k,partial_root) + } else { + *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& exists::>>(?receiving) &*& + ancestor_tail(&(*receiving.as_ptr()).data,?remaining,root,root_index,?ancestor,?ancestor_idx) &*& + leaf_header(&(*receiving.as_ptr()).data,ancestor,ancestor_idx) &*& struct_InternalNode_padding(receiving.as_ptr()) &*& + route_frames(t,remaining) &*& length(completed) + length(remaining) + 1 == length(path) &*& + internal_slots(receiving,?receiving_len,_,_,_) &*& detached_child::(?detached) &*& + if receiving_len == CAPACITY { .own(t,_) &*& .own(t,_) } else { true } + } + } + } else { + len == CAPACITY &*& *sleeper.ptr.as_ptr() |-> Option::Some(old_root) &*& route_frames(t,path) &*& + ancestor_tail(self.node.node.as_ptr(),path,root,root_index,?parent,?idx) &*& + leaf_header(self.node.node.as_ptr(),parent,idx) &*& leaf_slots(self.node.node.as_ptr(),len,keys,vals) &*& + nth(insertion_pivot(self.idx),keys).inner() == some(?promoted_key) &*& + nth(insertion_pivot(self.idx),vals).inner() == some(?promoted_val) &*& + .own(t,promoted_key) &*& .own(t,promoted_val) + }; + @*/ + { + //@ let entry = self; + //@ let first = self.node.node; + //@ close exists(false); + let initial = unsafe { self.clone_and_insert/*@::<'tree,K,V,A,'alloc>@*/(key,val,alloc) }; + //@ open leaf_insert_sibling(initial,entry,t,len,alloc_id,k); + //@ open exists(false); + //@ close exists(initial); + //@ close exists(true); + //@ close exists(first); + let result = unsafe { resume_after_leaf_insert_for_root/*@::<'tree,K,V,A,'alloc,'slot>@*/(initial,alloc,root_slot,root_allocator) }; + //@ open exists(true); + //@ open exists(initial); + result + } +} + +impl NodeRef { + unsafe fn new_internal_production(child: Root, alloc: A) -> Self + /*@ + req thread_token(?t) &*& std::ptr::drop_may_unwind::() == false &*& + type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,alloc,?id) &*& exists::(?k) &*& [?available]lifetime_token(k) &*& + lifetime_inclusion(k,id.lft) == true &*& 0 <= child.height &*& child.height < usize::MAX &*& + ancestors(child.node.as_ptr(),[],child.node.as_ptr()) &*& (*child.node.as_ptr()).parent_idx |-> ?old_index; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [available/2]lifetime_token(k) &*& result.height == child.height + 1 &*& + exists::>>(?root) &*& result.node.as_ptr() == &(*root.as_ptr()).data &*& + allocated_internal(root.as_ptr(),id,k,available/2) &*& + ancestors(result.node.as_ptr(),[],result.node.as_ptr()) &*& (*result.node.as_ptr()).parent_idx |-> ?created_index &*& + internal_slots(root,0,[child.node],_,_); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + [available]lifetime_token(k) &*& exists::>>>(?partial) &*& + interrupted_root_change(child.node,old_index,id,k,partial); + @*/ + { + //@ open exists(k); + //@ close interrupted_root_change(child.node,old_index,id,k,Option::None); + //@ close exists::>>>(Option::None); + let mut new_node = unsafe { InternalNode::new(alloc) }; + //@ open exists::>>>(Option::None); + //@ open interrupted_root_change(child.node,old_index,id,k,Option::None); + //@ let contents = std::boxed::Box_separate_contents(&mut new_node); + //@ let q_box = lifetime_token_trade(k,available,id.lft); + //@ open_points_to_at_lft(contents,q_box); + //@ points_to_limits(contents); + //@ assert *contents |-> ?initial; + //@ open_points_to(contents); + //@ let first_edge = &(*contents).edges as *MaybeUninit>; + //@ array_split(first_edge,1); + //@ assert array(first_edge+1,CAPACITY,?tail); + //@ open array(first_edge,1,_); + new_node.edges[0].write(child.node); + //@ close array(first_edge,1,[MaybeUninit::new(child.node)]); + //@ array_join(first_edge); + //@ close_known_array(&(*contents).edges); + //@ open_points_to(&(*contents).edges); + //@ close_points_to(contents); + //@ assert *contents |-> ?new_contents; + //@ assert new_contents.data == initial.data; + //@ assert Array_elems(new_contents.edges) == append(initialized_edges([child.node]),tail); + //@ close_points_to_at_lft(contents); + //@ lifetime_token_trade_back(q_box,id.lft); + //@ std::boxed::Box_unseparate_contents(&mut new_node); + //@ open ancestors(child.node.as_ptr(),[],child.node.as_ptr()); + //@ open link(child.node.as_ptr(),Option::None,0); + //@ close child_headers::([]); + //@ close child_headers([child.node]); + //@ close exists(tail); + //@ close exists(k); + let root = unsafe { NodeRef::from_new_internal(new_node, NonZero::new(child.height + 1).unwrap()) }; + //@ open exists::>>(?ptr); + //@ close link(root.node.as_ptr(),Option::None,0); + //@ close ancestors(root.node.as_ptr(),[],root.node.as_ptr()); + //@ close exists(ptr); + root + } +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { + unsafe fn push_production<'short>(&'short mut self, key: K, val: V, edge: Root) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,val) &*& + *self |-> ?incoming &*& incoming.height > 0 &*& edge.height == incoming.height - 1 &*& + exists::>>(?parent) &*& incoming.node.as_ptr() == &(*parent.as_ptr()).data &*& + leaf_header(incoming.node.as_ptr(),?ancestor,?parent_idx) &*& struct_InternalNode_padding(parent.as_ptr()) &*& + internal_slots(parent,?count,?children,?keys,?vals) &*& count < CAPACITY &*& detached_child(edge.node.as_ptr()); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& .own(t,key) &*& .own(t,val) &*& + *self |-> incoming &*& leaf_header(incoming.node.as_ptr(),ancestor,parent_idx) &*& struct_InternalNode_padding(parent.as_ptr()) &*& + internal_slots(parent,count+1,append(children,[edge.node]),?fitted_keys,?fitted_vals) &*& + nth(count,fitted_keys).inner() == some(key) &*& nth(count,fitted_vals).inner() == some(val); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ let node = incoming.node.as_ptr(); + //@ let parent_ptr = parent.as_ptr(); + //@ let right = edge.node; + //@ std::ptr::NonNull_Sized_as_ptr(parent); + //@ std::ptr::NonNull_Sized_as_ptr(incoming.node); + //@ std::ptr::NonNull_Sized_as_ptr(right); + //@ open_points_to(self); + assert!(edge.height == self.height - 1); + //@ close_points_to(self); + //@ open internal_slots(parent,count,children,keys,vals); + //@ open node_arrays(parent_ptr,keys,vals,?edges); + //@ open leaf_header(node,ancestor,parent_idx); + //@ close leaf_without_len(node,ancestor,parent_idx,keys,vals); + let len = unsafe { self.len_mut/*@::<'a,K,V,marker::Internal,'short>@*/() }; //~track_ref_creation + let idx = usize::from(*len); + assert!(idx < CAPACITY); + *len += 1; + //@ end_len_loan(node,len); + //@ open leaf_without_len(node,ancestor,parent_idx,keys,vals); + //@ close leaf_header(node,ancestor,parent_idx); + unsafe { + //@ close leaf_without_keys(node,ancestor,parent_idx,(count+1) as u16,vals); + self.key_area_slot_mut/*@::<'a,K,V,marker::Internal,'short>@*/(idx).write(key); //~track_ref_creation + //@ assert keys_slot_loan(node,?key_slot,count,ancestor,parent_idx,(count+1) as u16,vals,_,_); + //@ end_keys_slot(node,key_slot); + //@ open leaf_without_keys(node,ancestor,parent_idx,(count+1) as u16,vals); + //@ assert (*node).keys[..CAPACITY] |-> ?fitted_keys; + + //@ close leaf_without_vals(node,ancestor,parent_idx,(count+1) as u16,fitted_keys); + self.val_area_slot_mut/*@::<'a,K,V,marker::Internal,'short>@*/(idx).write(val); //~track_ref_creation + //@ assert vals_slot_loan(node,?val_slot,count,ancestor,parent_idx,(count+1) as u16,fitted_keys,_,_); + //@ end_vals_slot(node,val_slot); + //@ open leaf_without_vals(node,ancestor,parent_idx,(count+1) as u16,fitted_keys); + //@ assert (*node).vals[..CAPACITY] |-> ?fitted_vals; + + //@ open leaf_header(node,ancestor,parent_idx); + //@ close_points_to(node); + //@ close internal_without_edges(parent_ptr,_); + self.edge_area_slot_mut/*@::<'a,K,V,'short>@*/(idx + 1).write(edge.node); //~track_ref_creation + //@ assert edges_slot_loan(parent_ptr,?edge_slot,count+1,?data,_,_); + //@ end_edges_slot(parent_ptr,edge_slot); + //@ open internal_without_edges(parent_ptr,data); + //@ open_points_to(node); + //@ assert (*parent_ptr).edges[..CAPACITY+1] |-> ?fitted_edges; + + //@ let head = take(count+1, edges); + //@ let tail = drop(count+2, edges); + //@ length_take(count+1,edges); + //@ nth_append_r(head,cons(MaybeUninit::new(right),tail),0); + //@ close exists(parent); + //@ close exists(right); + //@ open detached_child(right.as_ptr()); + Handle::,K,V,marker::Internal>,marker::Edge>::new_edge( + self.reborrow_mut/*@::,K,V,marker::Internal,'short>@*/(), idx + 1 + ).correct_parent_link/*@::<'short,K,V>@*/(); + //@ append_linked_header(children,right,parent,0); + //@ initialized_edges_append(children,[right]); + //@ initialized_edge_count(children); + //@ append_assoc(head,[MaybeUninit::new(right)],tail); + //@ take_append_l(count+2,append(head,[MaybeUninit::new(right)]),tail); + //@ take_length(append(head,[MaybeUninit::new(right)])); + + //@ length_take(count,keys); + //@ length_take(count,vals); + //@ nth_append_r(take(count,keys),cons(MaybeUninit::new(key),drop(count+1,keys)),0); + //@ nth_append_r(take(count,vals),cons(MaybeUninit::new(val),drop(count+1,vals)),0); + //@ close node_arrays(parent_ptr,fitted_keys,fitted_vals,fitted_edges); + //@ close internal_slots(parent,count+1,append(children,[right]),fitted_keys,fitted_vals); + //@ close leaf_header(node,ancestor,parent_idx); + } + } +} + +impl<'a, K: 'a, V: 'a, Type> Copy for NodeRef, K, V, Type> {} +impl<'a, K: 'a, V: 'a, Type> Clone for NodeRef, K, V, Type> { + fn clone(&self) -> Self { + *self + } +} + +/*@ +lem slots_are_initialized(t: thread_id_t, slots: list>) + req slot_owners(t, slots); + ens slot_owners(t, slots) &*& std::mem::initialized_slots(slots) == true; +{ + open slot_owners(t, slots); + match slots { + nil => {} + cons(slot, tail) => { + slots_are_initialized(t, tail); + } + } + close slot_owners(t, slots); +} + +pred shared_key_view( + root: *LeafNode, slice: *[K], store: real, + parent: Option>>, pidx: MaybeUninit, len: usize, + keys: list>, vals: list> +) = + ref_readonly_end_token(?leaf,root,store/2) &*& ref_initialized(leaf) &*& + [store/2]leaf_header(leaf,parent,pidx) &*& [store/2](*leaf).len |-> (len as u16) &*& + [store/2](*leaf).vals[..CAPACITY] |-> vals &*& + [store/4](*leaf).keys[..CAPACITY] |-> keys &*& + ref_readonly_end_token(?array,&(*leaf).keys,store/4) &*& + [store/4](array as *MaybeUninit)[..CAPACITY] |-> keys &*& + ref_initialized(array) &*& [_]ref_initialized(slice) &*& + strip_pointer_metadata(slice as pointer) == array as pointer &*& slice.len() == len; +@*/ +impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { + unsafe fn into_leaf(mut self) -> &'a LeafNode + //@ req ref_precreated_token(self.node.as_ptr(), ?leaf) &*& [?f]ref_initialized(leaf); + //@ ens [f]ref_initialized(leaf) &*& result == leaf; + //@ on_unwind_ens false; + { + //@ let view = precreate_ref(&self); + //@ init_ref_readonly(view, 1/2); + let ptr = unsafe { Self::as_leaf_ptr(&self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self, _); + unsafe { &*ptr } + } + + unsafe fn keys<'short>(&'short self) -> &'short [K] + /*@ + req [?f](*self |-> ?node) &*& ref_initialized(self) &*& [?q]lifetime_token('short) &*& + [?store]leaf_header(node.node.as_ptr(),?parent,?pidx) &*& + [store]leaf_slots(node.node.as_ptr(),?len,?key_slots,?vals) &*& + slot_owners(?t,take(len,key_slots)) &*& + ((&(*node.node.as_ptr()).keys) as pointer).address != 0 &*& + ((&(*node.node.as_ptr()).keys) as pointer).address % std::mem::align_of::() == 0; + @*/ + /*@ + ens [f](*self |-> node) &*& ref_initialized(self) &*& [q]lifetime_token('short) &*& + [store/2]leaf_header(node.node.as_ptr(),parent,pidx) &*& + [store/2]leaf_slots(node.node.as_ptr(),len,key_slots,vals) &*& + slot_owners(t,take(len,key_slots)) &*& + shared_key_view(node.node.as_ptr(),result,store,parent,pidx,len,key_slots,vals); + @*/ + //@ on_unwind_ens false; + { + //@ let root = node.node.as_ptr(); + //@ open [store]leaf_header(root,parent,pidx); + //@ open [store]leaf_slots(root,len,key_slots,vals); + //@ close_points_to(root,store); + //@ let view = precreate_ref(root); + //@ init_ref_readonly(view,1/2); + //@ open_points_to(self); + let leaf = unsafe { self.into_leaf() }; + //@ close_points_to(self, f); + //@ open_points_to(root); + //@ close [store/2]leaf_header(root,parent,pidx); + //@ close [store/2]leaf_slots(root,len,key_slots,vals); + //@ open_points_to(leaf); + //@ let keys_addr = &(*leaf).keys; + //@ close_points_to(keys_addr,store/2); + //@ let array = precreate_ref(keys_addr); + //@ init_ref_readonly(array,1/2); + let keys = &leaf.keys; + // Rust reborrows the array reference before attaching slice metadata. + //@ let local = begin_lifetime(); + //@ close ref_initialized_::<[MaybeUninit; 11]>(keys)(); + //@ borrow(local, ref_initialized_::<[MaybeUninit; 11]>(keys)); + //@ full_borrow_into_frac(local, ref_initialized_::<[MaybeUninit; 11]>(keys)); + //@ let half = open_frac_borrow(local, ref_initialized_::<[MaybeUninit; 11]>(keys), 1/2); + //@ open [half]ref_initialized_::<[MaybeUninit; 11]>(keys)(); + let key_slice: &[MaybeUninit] = keys; + //@ close [half]ref_initialized_::<[MaybeUninit; 11]>(keys)(); + //@ close_frac_borrow(half, ref_initialized_::<[MaybeUninit; 11]>(keys)); + //@ end_lifetime(local); + //@ borrow_end(local, ref_initialized_::<[MaybeUninit; 11]>(keys)); + //@ open ref_initialized_::<[MaybeUninit; 11]>(keys)(); + //@ open_points_to(keys); + //@ let base = keys as *MaybeUninit; + //@ array_inv::>(); + //@ move_slice_offset(base,CAPACITY,len); + //@ assert (base as pointer).address != 0; + //@ assert (base as *u8 + len * std::mem::size_of::()) as pointer == (base + len) as pointer; + //@ slots_are_initialized(t,take(len,key_slots)); + let prefix = unsafe { <[MaybeUninit]>::get_unchecked(key_slice, ..usize::from(leaf.len)) }; + //@ array_split(base,len); + let result = unsafe { <[MaybeUninit]>::assume_init_ref/*@::@*/(prefix) }; + //@ array_join(base); + //@ open_points_to(keys_addr); + //@ close [store/2]leaf_header(leaf,parent,pidx); + //@ close shared_key_view(root,result,store,parent,pidx,len,key_slots,vals); + result + } +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn into_leaf_mut(mut self) -> &'a mut LeafNode + //@ req *self.node.as_ptr() |-> ?contents; + //@ ens *result |-> contents &*& ref_mut_end_token(result, self.node.as_ptr()) &*& ref_origin(result) == ref_origin(self.node.as_ptr()); + //@ on_unwind_ens false; + { + //@ let view = precreate_ref(&self); + //@ init_ref_readonly(view, 1/2); + let ptr = unsafe { Self::as_leaf_ptr(&mut self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self, _); + unsafe { &mut *ptr } //~track_ref_creation + } +} + +/*@ +pred kv_loan<'a,K,V,NodeType>(owner: *Handle, K, V, NodeType>, marker::KV>, + view: *LeafNode, key: *K, val: *V, + contents: Handle, K, V, NodeType>, marker::KV>, len: u16, + parent: Option>>, parent_idx: MaybeUninit, keys: list>, vals: list>) = + (*owner).idx |-> contents.idx &*& struct_Handle_padding(owner) &*& + ref_mut_end_token(?receiver,&(*owner).node) &*& *receiver |-> contents.node &*& + ref_mut_end_token(view,contents.node.node.as_ptr()) &*& + leaf_header(view,parent,parent_idx) &*& (*view).len |-> len &*& + ref_mut_end_token(?key_array,&(*view).keys) &*& ref_mut_end_token(?val_array,&(*view).vals) &*& + initialized_array_slot(key_array as *MaybeUninit,contents.idx,key,take(contents.idx,keys),drop(contents.idx+1,keys)) &*& + initialized_array_slot(val_array as *MaybeUninit,contents.idx,val,take(contents.idx,vals),drop(contents.idx+1,vals)); +@*/ + +impl<'a, K:'a, V:'a, NodeType> Handle,K,V,NodeType>,marker::KV> { + unsafe fn kv_mut<'short>(&'short mut self) -> (&'short mut K, &'short mut V) + /*@ + req *self |-> ?incoming &*& leaf_header(incoming.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(incoming.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= incoming.idx &*& incoming.idx < len &*& + nth(incoming.idx,keys).inner() == some(?old_key) &*& nth(incoming.idx,vals).inner() == some(?old_val); + @*/ + /*@ + ens kv_loan(self, ?leaf, result.0, result.1, incoming, len, parent, parent_idx, keys, vals) &*& + *result.0 |-> old_key &*& *result.1 |-> old_val; + @*/ + //@ on_unwind_ens false; + { + //@ let node = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open leaf_slots(node,len,keys,vals); + //@ open_points_to(self); + //@ let view = precreate_ref(&(*self).node); + //@ init_ref_readonly(view,1/2); + debug_assert!(self.idx < self.node.merge_len()); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&(*self).node, _); + //@ open leaf_header(node,parent,parent_idx); + //@ close_points_to(node); + unsafe { + let leaf = self.node.as_leaf_mut/*@::<'a,K,V,NodeType,'short>@*/(); //~track_ref_creation + //@ open_points_to(leaf); + //@ close_points_to(&(*leaf).keys); + let key_slot = { + <[MaybeUninit]>::get_unchecked_mut( + { + let key_array = &mut leaf.keys; //~track_ref_creation + let slice: &mut [MaybeUninit] = key_array; + //@ open_points_to(key_array); + //@ let key_base = key_array as *MaybeUninit; + //@ array_split(key_base,index); + //@ array_split(key_base+index,1); + //@ open array(key_base+index,1,_); + //@ open array(key_base+index+1,0,_); + //@ nth_drop(0,index,keys); + //@ drop_twice(1,index,keys); + slice + }, + self.idx, + ) + }; + let key = key_slot.assume_init_mut(); + //@ close exists::<*MaybeUninit>(key_slot); + //@ close initialized_array_slot(key_base,index,key,take(index,keys),drop(index+1,keys)); + //@ close_points_to(&(*leaf).vals); + let val_slot = { + <[MaybeUninit]>::get_unchecked_mut( + { + let val_array = &mut leaf.vals; //~track_ref_creation + let slice: &mut [MaybeUninit] = val_array; + //@ open_points_to(val_array); + //@ let val_base = val_array as *MaybeUninit; + //@ array_split(val_base,index); + //@ array_split(val_base+index,1); + //@ open array(val_base+index,1,_); + //@ open array(val_base+index+1,0,_); + //@ nth_drop(0,index,vals); + //@ drop_twice(1,index,vals); + slice + }, + self.idx, + ) + }; + let val = val_slot.assume_init_mut(); + //@ close exists::<*MaybeUninit>(val_slot); + //@ close initialized_array_slot(val_base,index,val,take(index,vals),drop(index+1,vals)); + //@ close leaf_header(leaf,parent,parent_idx); + //@ close kv_loan(self,leaf,key,val,incoming,len,parent,parent_idx,keys,vals); + (key, val) + } + } +} + +impl Handle, marker::KV> { + unsafe fn new_navigation_kv(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx < len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx < node.relink_len()) }; + let kv = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + kv + } +} + +impl NodeRef { + unsafe fn first_edge(self) -> Handle + //@ req (*self.node.as_ptr()).len |-> ?len; + //@ ens (*self.node.as_ptr()).len |-> len &*& result.node == self &*& result.idx == 0; + //@ on_unwind_ens false; + { + unsafe { Handle::new_relink_edge(self, 0) } + } + + unsafe fn last_edge(self) -> Handle + //@ req (*self.node.as_ptr()).len |-> ?count; + //@ ens (*self.node.as_ptr()).len |-> count &*& result.node == self &*& result.idx == count; + //@ on_unwind_ens false; + { + let len = unsafe { self.relink_len() }; + let edge = unsafe { Handle::new_relink_edge(self, len) }; + //@ close_points_to(&self, 1/2); + edge + } + + unsafe fn first_kv(self) -> Handle + //@ req (*self.node.as_ptr()).len |-> ?count &*& count > 0; + //@ ens (*self.node.as_ptr()).len |-> count &*& result.node == self &*& result.idx == 0; + //@ on_unwind_ens false; + { + let len = unsafe { self.relink_len() }; + assert!(len > 0); + let kv = unsafe { Handle::new_navigation_kv(self, 0) }; + //@ close_points_to(&self, 1/2); + kv + } + + unsafe fn last_kv(self) -> Handle + //@ req (*self.node.as_ptr()).len |-> ?count &*& count > 0; + //@ ens (*self.node.as_ptr()).len |-> count &*& result.node == self &*& result.idx == count - 1; + //@ on_unwind_ens false; + { + let len = unsafe { self.relink_len() }; + assert!(len > 0); + let kv = unsafe { Handle::new_navigation_kv(self, len - 1) }; + //@ close_points_to(&self, 1/2); + kv + } +} + +impl Handle, marker::KV> { + unsafe fn left_edge(self) -> Handle, marker::Edge> + //@ req (*self.node.node.as_ptr()).len |-> ?len &*& self.idx <= len; + //@ ens (*self.node.node.as_ptr()).len |-> len &*& result.node == self.node &*& result.idx == self.idx; + //@ on_unwind_ens false; + { + unsafe { Handle::new_relink_edge(self.node, self.idx) } + } + + unsafe fn right_edge(self) -> Handle, marker::Edge> + //@ req (*self.node.node.as_ptr()).len |-> ?len &*& 0 <= self.idx &*& self.idx < len; + //@ ens (*self.node.node.as_ptr()).len |-> len &*& result.node == self.node &*& result.idx == self.idx + 1; + //@ on_unwind_ens false; + { + unsafe { Handle::new_relink_edge(self.node, self.idx + 1) } + } +} + +impl Handle, marker::Edge> { + unsafe fn left_kv(self) -> Result, marker::KV>, Self> + //@ req (*self.node.node.as_ptr()).len |-> ?len &*& self.idx <= len; + /*@ + ens (*self.node.node.as_ptr()).len |-> len &*& + match result { Result::Ok(kv) => self.idx > 0 && kv.node == self.node && kv.idx == self.idx - 1, + Result::Err(edge) => self.idx == 0 && edge == self }; + @*/ + //@ on_unwind_ens false; + { + if self.idx > 0 { + Ok(unsafe { Handle::new_navigation_kv(self.node, self.idx - 1) }) + } else { + Err(self) + } + } + +} +impl Handle, marker::Edge> { + unsafe fn descend(mut self) -> NodeRef + /*@ + req 0 < self.node.height &*& 0 <= self.idx &*& self.idx <= CAPACITY &*& + pointer_within_limits(&(*(self.node.node.as_ptr() as *InternalNode)).edges) == true &*& + [?f](*(self.node.node.as_ptr() as *InternalNode)).edges[..CAPACITY+1] |-> ?edges &*& + exists::>(?child) &*& nth(self.idx,edges) == MaybeUninit::new(child); + @*/ + /*@ + ens exists::>(child) &*& [f](*(self.node.node.as_ptr() as *InternalNode)).edges[..CAPACITY+1] |-> edges &*& + result.node == child &*& result.height == self.node.height - 1; + @*/ + //@ on_unwind_ens false; + { + const { assert!(BorrowType::TRAVERSAL_PERMIT); } + //@ open exists(child); + //@ open_points_to(&self); + //@ let receiver = precreate_ref(&self.node); + //@ init_ref_readonly(receiver, 1/2); + let parent_ptr = unsafe { NodeRef::as_internal_ptr(&self.node) }; + //@ end_ref_readonly(receiver); + //@ merge_fractions points_to(&self.node, _); + // BEGIN_RAW_EDGE_READ + //@ let array = &(*parent_ptr).edges; + //@ close_points_to(array, f); + //@ let view = precreate_ref(array); + //@ init_ref_readonly(view, 1/2); + //@ open_points_to(view); + //@ let base = view as *MaybeUninit>; + //@ array_inv::>>(); + //@ array_split(base, self.idx); + //@ array_split(base + self.idx, 1); + //@ nth_drop(0, self.idx, edges); + //@ open [f/2]array(base + self.idx, 1, _); + //@ open [f/2]array(base + self.idx + 1, 0, _); + //@ let slot = precreate_ref(base + self.idx); + //@ init_ref_readonly(slot, 1/2); + let edge = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() }; + //@ end_ref_readonly(slot); + //@ merge_fractions points_to(base + self.idx, _); + //@ close [f/2]array(base + self.idx, 1, [MaybeUninit::new(child)]); + //@ array_join(base + self.idx); + //@ array_join(base); + //@ close_points_to(view, f/2); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(array, _); + //@ open_points_to(array); + // END_RAW_EDGE_READ + let descended = NodeRef { node: edge, height: self.node.height - 1, _marker: PhantomData }; + //@ close_points_to(&self); + //@ close exists(child); + descended + } +} + +/*@ +pred handle_key_loan<'a,K,V,NodeType>( + owner: *Handle,K,V,NodeType>,marker::KV>, key: *K, + contents: Handle,K,V,NodeType>,marker::KV>, + parent: Option>>, parent_idx: MaybeUninit, len: u16, + keys: list>, vals: list> +) = + (*owner).idx |-> contents.idx &*& struct_Handle_padding(owner) &*& + ref_mut_end_token(?receiver,&(*owner).node) &*& *receiver |-> contents.node &*& + keys_slot_loan(contents.node.node.as_ptr(),?slot,contents.idx,parent,parent_idx,len,vals, + take(contents.idx,keys),drop(contents.idx+1,keys)) &*& + ref_mut_end_token(key,slot as *K); +@*/ + +impl<'a, K:'a, V:'a, NodeType> Handle,K,V,NodeType>,marker::KV> { + unsafe fn key_mut<'short>(&'short mut self) -> &'short mut K + /*@ + req *self |-> ?incoming &*& leaf_header(incoming.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(incoming.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= incoming.idx &*& incoming.idx < len &*& + nth(incoming.idx,keys).inner() == some(?entry); + @*/ + //@ ens handle_key_loan(self,result,incoming,parent,parent_idx,len as u16,keys,vals) &*& *result |-> entry; + //@ on_unwind_ens false; + { + //@ let raw = incoming.node.node.as_ptr(); + //@ open leaf_slots(raw,len,keys,vals); + //@ close leaf_without_keys(raw,parent,parent_idx,len as u16,vals); + //@ open_points_to(self); + unsafe { + let slot = self.node.key_area_slot_mut/*@::<'a,K,V,NodeType,'short>@*/(self.idx); //~track_ref_creation + let key = slot.assume_init_mut(); + //@ close handle_key_loan(self,key,incoming,parent,parent_idx,len as u16,keys,vals); + key + } + } +} + +/*@ +fix array_address_ok(base: *MaybeUninit) -> bool { + base != 0 && + object_pointer_within_limits(base as *u8, CAPACITY * std::mem::size_of::()) && + (base as pointer).address % std::mem::align_of::() == 0 && + CAPACITY * std::mem::size_of::() <= isize::MAX +} + +pred valmut_input(leaf: *LeafNode, index: usize, f: real; bits: MaybeUninit, value_bits: MaybeUninit) = + 0 <= index &*& index < CAPACITY &*& + array_address_ok(&(*leaf).keys as *MaybeUninit) == true &*& + array_address_ok(&(*leaf).vals as *MaybeUninit) == true &*& + [f](*((&(*leaf).keys as *MaybeUninit) + index) |-> bits) &*& + *((&(*leaf).vals as *MaybeUninit) + index) |-> value_bits; + +pred valmut_loan( + leaf: *LeafNode, index: usize, key: *K, val: *V, bits: MaybeUninit, f: real +) = + [f/2](*((&(*leaf).keys as *MaybeUninit) + index) |-> bits) &*& + ref_readonly_end_token(?key_view, ((&(*leaf).keys as *MaybeUninit) + index), f/2) &*& [f/2](*key_view |-> bits) &*& ref_initialized(key_view) &*& + key as pointer == key_view as pointer &*& + ref_mut_end_token(?val_view,((&(*leaf).vals as *MaybeUninit) + index)) &*& ref_mut_end_token(val,val_view as *V); +@*/ + +impl<'a, K, V, Type> NodeRef, K, V, Type> { + unsafe fn into_key_val_mut_at(mut self, idx: usize) -> (&'a K, &'a mut V) + //@ req valmut_input(self.node.as_ptr(), idx, ?f, ?bits, ?value_bits) &*& bits.inner() == some(?entry_key) &*& value_bits.inner() == some(?entry_val) &*& [?q]lifetime_token('a); + //@ ens valmut_loan(self.node.as_ptr(), idx, result.0, result.1, bits, f) &*& *result.1 |-> entry_val &*& [q]lifetime_token('a) &*& [_]frac_borrow('a, ref_initialized_(result.0)); + //@ on_unwind_ens false; + { + //@ assert *(&self) |-> ?original; + //@ let storage = original.node.as_ptr(); + //@ open valmut_input(storage, idx, f, bits, value_bits); + //@ let view = precreate_ref(&self); + //@ init_ref_readonly(view,1/2); + let leaf = unsafe { Self::as_leaf_ptr(&mut self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self, _); + let keys = unsafe { &raw const (*leaf).keys }; + let vals = unsafe { &raw mut (*leaf).vals }; + let keys: *const [_] = keys; + let vals: *mut [_] = vals; + //@ let key_view = precreate_ref((&(*leaf).keys as *MaybeUninit) + idx); + //@ init_ref_readonly(key_view,1/2); + let key = unsafe { (&*keys.get_unchecked(idx)).assume_init_ref/*@::@*/() }; + let val = unsafe { (&mut *vals.get_unchecked_mut(idx)).assume_init_mut() }; //~track_ref_creation + //@ close valmut_loan(storage,idx,key,val,bits,f); + (key, val) + } +} + +impl<'a, K, V, NodeType> Handle, K, V, NodeType>, marker::KV> { + unsafe fn into_kv_valmut(self) -> (&'a K, &'a mut V) + //@ req valmut_input(self.node.node.as_ptr(), self.idx, ?f, ?bits, ?value_bits) &*& bits.inner() == some(?key) &*& value_bits.inner() == some(?val) &*& [?q]lifetime_token('a); + //@ ens valmut_loan(self.node.node.as_ptr(), self.idx, result.0, result.1, bits, f) &*& *result.1 |-> val &*& [q]lifetime_token('a) &*& [_]frac_borrow('a, ref_initialized_(result.0)); + //@ on_unwind_ens false; + { + unsafe { self.node.into_key_val_mut_at/*@::<'a,K,V,NodeType>@*/(self.idx) } + } +} + +/*@ +lem split_node_slot(base: *MaybeUninit, index: usize) + req [?f]base[..CAPACITY] |-> ?slots &*& 0 <= index &*& index < CAPACITY; + ens [f]base[..index] |-> take(index,slots) &*& [f](*(base+index) |-> nth(index,slots)) &*& + [f]base[index+1..CAPACITY] |-> drop(index+1,slots); +{ + array_split(base,index); + array_split(base+index,1); + open [f]array(base+index,1,_); + open [f]array(base+index+1,0,_); + nth_drop(0,index,slots); + drop_twice(1,index,slots); +} + +pred consumed_val_loan( + root: *LeafNode, index: usize, val: *V, len: usize, + parent: Option>>, parent_idx: MaybeUninit, + keys: list>, vals: list> +) = + ref_mut_end_token(?leaf,root) &*& leaf_header(leaf,parent,parent_idx) &*& (*leaf).len |-> (len as u16) &*& + (*leaf).keys[..CAPACITY] |-> keys &*& + ref_mut_end_token(?val_array,&(*leaf).vals) &*& + initialized_array_slot(val_array as *MaybeUninit,index,val,take(index,vals),drop(index+1,vals)); + +pred consumed_kv_loan( + root: *LeafNode, index: usize, key: *K, val: *V, len: usize, + parent: Option>>, parent_idx: MaybeUninit, + keys: list>, vals: list> +) = + ref_mut_end_token(?leaf,root) &*& leaf_header(leaf,parent,parent_idx) &*& (*leaf).len |-> (len as u16) &*& + ref_mut_end_token(?key_array,&(*leaf).keys) &*& ref_mut_end_token(?val_array,&(*leaf).vals) &*& + initialized_array_slot(key_array as *MaybeUninit,index,key,take(index,keys),drop(index+1,keys)) &*& + initialized_array_slot(val_array as *MaybeUninit,index,val,take(index,vals),drop(index+1,vals)); +@*/ + +impl<'a, K:'a, V:'a, NodeType> Handle,K,V,NodeType>,marker::KV> { + unsafe fn into_val_mut(mut self) -> &'a mut V + /*@ + req leaf_header(self.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= self.idx &*& self.idx < len &*& + nth(self.idx,vals).inner() == some(?entry); + @*/ + /*@ + ens consumed_val_loan(self.node.node.as_ptr(),self.idx,result,len,parent,parent_idx,keys,vals) &*& *result |-> entry; + @*/ + //@ on_unwind_ens false; + { + //@ assert *(&self) |-> ?incoming; + //@ let node = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open leaf_slots(node,len,keys,vals); + //@ open_points_to(&self); + //@ let view = precreate_ref(&self.node); + //@ init_ref_readonly(view,1/2); + debug_assert!(self.idx < self.node.merge_len()); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self.node, _); + //@ open leaf_header(node,parent,parent_idx); + //@ close_points_to(node); + let leaf = self.node.into_leaf_mut/*@::<'a,K,V,NodeType>@*/(); + //@ open_points_to(leaf); + //@ close_points_to(&(*leaf).vals); + unsafe { + let slot = <[MaybeUninit]>::get_unchecked_mut( + { + let val_array = &mut leaf.vals; //~track_ref_creation + let slice: &mut [MaybeUninit] = val_array; + //@ open_points_to(val_array); + //@ let base = val_array as *MaybeUninit; + //@ split_node_slot(base,index); + slice + }, + self.idx, + ); + let val = slot.assume_init_mut(); + //@ close exists::<*MaybeUninit>(slot); + //@ close initialized_array_slot(base,index,val,take(index,vals),drop(index+1,vals)); + //@ close leaf_header(leaf,parent,parent_idx); + //@ close consumed_val_loan(node,index,val,len,parent,parent_idx,keys,vals); + //@ close_points_to(&self); + val + } + } + + unsafe fn into_kv_mut(mut self) -> (&'a mut K, &'a mut V) + /*@ + req leaf_header(self.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= self.idx &*& self.idx < len &*& + nth(self.idx,keys).inner() == some(?old_key) &*& nth(self.idx,vals).inner() == some(?old_val); + @*/ + /*@ + ens consumed_kv_loan(self.node.node.as_ptr(),self.idx,result.0,result.1,len,parent,parent_idx,keys,vals) &*& + *result.0 |-> old_key &*& *result.1 |-> old_val; + @*/ + //@ on_unwind_ens false; + { + //@ assert *(&self) |-> ?incoming; + //@ let node = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open leaf_slots(node,len,keys,vals); + //@ open_points_to(&self); + //@ let view = precreate_ref(&self.node); + //@ init_ref_readonly(view,1/2); + debug_assert!(self.idx < self.node.merge_len()); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self.node, _); + //@ open leaf_header(node,parent,parent_idx); + //@ close_points_to(node); + let leaf = self.node.into_leaf_mut/*@::<'a,K,V,NodeType>@*/(); + //@ open_points_to(leaf); + //@ close_points_to(&(*leaf).keys); + let key = unsafe { + let key_slot = { + <[MaybeUninit]>::get_unchecked_mut( + { + let key_array = &mut leaf.keys; //~track_ref_creation + let slice: &mut [MaybeUninit] = key_array; + //@ open_points_to(key_array); + //@ let key_base = key_array as *MaybeUninit; + //@ array_split(key_base,index); + //@ array_split(key_base+index,1); + //@ open array(key_base+index,1,_); + //@ open array(key_base+index+1,0,_); + //@ nth_drop(0,index,keys); + //@ drop_twice(1,index,keys); + slice + }, + self.idx, + ) + }; + let lent_key = key_slot.assume_init_mut(); + //@ close exists::<*MaybeUninit>(key_slot); + //@ close initialized_array_slot(key_base,index,lent_key,take(index,keys),drop(index+1,keys)); + lent_key + }; + //@ close_points_to(&(*leaf).vals); + let val = unsafe { + let val_slot = { + <[MaybeUninit]>::get_unchecked_mut( + { + let val_array = &mut leaf.vals; //~track_ref_creation + let slice: &mut [MaybeUninit] = val_array; + //@ open_points_to(val_array); + //@ let val_base = val_array as *MaybeUninit; + //@ array_split(val_base,index); + //@ array_split(val_base+index,1); + //@ open array(val_base+index,1,_); + //@ open array(val_base+index+1,0,_); + //@ nth_drop(0,index,vals); + //@ drop_twice(1,index,vals); + slice + }, + self.idx, + ) + }; + let lent_val = val_slot.assume_init_mut(); + //@ close exists::<*MaybeUninit>(val_slot); + //@ close initialized_array_slot(val_base,index,lent_val,take(index,vals),drop(index+1,vals)); + lent_val + }; + //@ close leaf_header(leaf,parent,parent_idx); + //@ close consumed_kv_loan(node,index,key,val,len,parent,parent_idx,keys,vals); + //@ close_points_to(&self); + (key, val) + } +} + + +/*@ +lem initialized_entry(slots: list>, index: usize) + req std::mem::initialized_slots(slots) == true &*& 0 <= index &*& index < length(slots); + ens nth(index,slots).inner() != none; +{ + match slots { + nil => {} + cons(slot, tail) => { + if index != 0 { + initialized_entry(tail,index-1); + } + } + } +} + +pred shared_slot_backing( + array: *[MaybeUninit; 11], view: *[MaybeUninit; 11], slot: *MaybeUninit, + share: real, index: usize, slots: list> +) = + ref_readonly_end_token(view,array,share/2) &*& + [share/2](array as *MaybeUninit)[..CAPACITY] |-> slots &*& + [share/2](view as *MaybeUninit)[..index] |-> take(index,slots) &*& + [share/2](view as *MaybeUninit)[index+1..CAPACITY] |-> drop(index+1,slots) &*& + ref_readonly_end_token(slot,(view as *MaybeUninit) + index,share/4) &*& + [share/4](*((view as *MaybeUninit) + index) |-> nth(index,slots)); + +pred shared_slot_loan( + array: *[MaybeUninit; 11], result: *T, share: real, index: usize, slots: list> +) = + shared_slot_backing(array,?view,?slot,share,index,slots) &*& ref_initialized(view) &*& + [share/4](*slot |-> nth(index,slots)) &*& ref_initialized(slot) &*& result as pointer == slot as pointer; + +lem prepare_shared_slot(array: *[MaybeUninit; 11], index: usize) + req [?f](array as *MaybeUninit)[..CAPACITY] |-> ?slots &*& 0 <= index &*& index < CAPACITY; + ens ref_precreated_token(array,?view) &*& ref_precreated_token((view as *MaybeUninit) + index,?slot) &*& + shared_slot_backing(array,view,slot,f,index,slots) &*& ref_initialized(view) &*& ref_initialized(slot) &*& + [f/4](*slot |-> nth(index,slots)); +{ + close_points_to(array,f); + let view = precreate_ref(array); + init_ref_readonly(view,1/2); + open_points_to(array); + open_points_to(view); + let base = view as *MaybeUninit; + split_node_slot(base,index); + let slot = precreate_ref(base+index); + init_ref_readonly(slot,1/2); + // Keep the array marker outside the backing predicate for native unsizing. + close shared_slot_backing(array,view,slot,f,index,slots); +} + +pred shared_kv_loan( + root: *LeafNode, key: *K, val: *V, store: real, index: usize, + parent: Option>>, parent_idx: MaybeUninit, len: usize, + keys: list>, vals: list> +) = + ref_readonly_end_token(?leaf,root,store/2) &*& ref_initialized(leaf) &*& + [store/2]leaf_header(leaf,parent,parent_idx) &*& [store/2](*leaf).len |-> (len as u16) &*& + shared_slot_loan(&(*leaf).keys,key,store/2,index,keys) &*& + shared_slot_loan(&(*leaf).vals,val,store/2,index,vals); +@*/ + +impl<'a, K:'a, V:'a, NodeType> Handle,K,V,NodeType>,marker::KV> { + unsafe fn into_kv(mut self) -> (&'a K, &'a V) + /*@ + req [?store]leaf_header(self.node.node.as_ptr(),?parent,?parent_idx) &*& + [store]leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& + 0 <= self.idx &*& self.idx < len &*& + slot_owners(?t,take(len,keys)) &*& slot_owners(t,take(len,vals)) &*& [?q]lifetime_token('a); + @*/ + /*@ + ens [store/2]leaf_header(self.node.node.as_ptr(),parent,parent_idx) &*& + [store/2]leaf_slots(self.node.node.as_ptr(),len,keys,vals) &*& + slot_owners(t,take(len,keys)) &*& slot_owners(t,take(len,vals)) &*& [q]lifetime_token('a) &*& + shared_kv_loan(self.node.node.as_ptr(),result.0,result.1,store,self.idx,parent,parent_idx,len,keys,vals) &*& + [_]frac_borrow('a,ref_initialized_(result.0)) &*& [_]frac_borrow('a,ref_initialized_(result.1)); + @*/ + //@ on_unwind_ens false; + { + //@ assert *(&self) |-> ?incoming; + //@ let root = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open [store]leaf_slots(root,len,keys,vals); + //@ open_points_to(&self); + //@ let receiver = precreate_ref(&self.node); + //@ init_ref_readonly(receiver,1/2); + debug_assert!(self.idx < self.node.merge_len()); + //@ end_ref_readonly(receiver); + //@ merge_fractions points_to(&self.node, _); + //@ open [store]leaf_header(root,parent,parent_idx); + //@ close_points_to(root,store); + //@ let view = precreate_ref(root); + //@ init_ref_readonly(view,1/2); + let leaf = unsafe { self.node.into_leaf() }; + //@ open_points_to(root); + //@ close [store/2]leaf_header(root,parent,parent_idx); + //@ close [store/2]leaf_slots(root,len,keys,vals); + //@ open_points_to(leaf); + //@ slots_are_initialized(t,take(len,keys)); + //@ initialized_entry(take(len,keys),index); + //@ nth_take(index,len,keys); + //@ prepare_shared_slot(&(*leaf).keys,index); + let key = unsafe { leaf.keys.get_unchecked(self.idx).assume_init_ref/*@::@*/() }; + //@ close shared_slot_loan(&(*leaf).keys,key,store/2,index,keys); + //@ slots_are_initialized(t,take(len,vals)); + //@ initialized_entry(take(len,vals),index); + //@ nth_take(index,len,vals); + //@ prepare_shared_slot(&(*leaf).vals,index); + let val = unsafe { leaf.vals.get_unchecked(self.idx).assume_init_ref/*@::@*/() }; + //@ close shared_slot_loan(&(*leaf).vals,val,store/2,index,vals); + //@ close [store/2]leaf_header(leaf,parent,parent_idx); + //@ close shared_kv_loan(root,key,val,store,index,parent,parent_idx,len,keys,vals); + //@ close_points_to(&self); + (key, val) + } +} + +impl<'a,K:'a,V:'a> NodeRef,K,V,marker::Leaf> { + unsafe fn push_with_handle<'b,'short>(&'short mut self, key: K, val: V) -> Handle,K,V,marker::Leaf>,marker::KV> + /*@ + req *self |-> ?node &*& leaf_header(node.node.as_ptr(),?parent,?pidx) &*& + leaf_slots(node.node.as_ptr(),?count,?keys,?vals) &*& count < CAPACITY; + @*/ + /*@ + ens *self |-> node &*& result.node.node == node.node &*& result.node.height == node.height &*& result.idx == count &*& + leaf_header(node.node.as_ptr(),parent,pidx) &*& + leaf_slots(node.node.as_ptr(),count+1,replace_slot(count,MaybeUninit::new(key),keys), + replace_slot(count,MaybeUninit::new(val),vals)); + @*/ + //@ on_unwind_ens false; + { + //@ let raw = node.node.as_ptr(); + //@ open leaf_header(raw,parent,pidx); + //@ open leaf_slots(raw,count,keys,vals); + //@ close leaf_without_len(raw,parent,pidx,keys,vals); + let len = self.len_mut/*@::<'a,K,V,marker::Leaf,'short>@*/(); //~track_ref_creation + let idx = usize::from(*len); + assert!(idx < CAPACITY); + *len += 1; + //@ end_len_loan(raw,len); + //@ open leaf_without_len(raw,parent,pidx,keys,vals); + //@ close leaf_header(raw,parent,pidx); + unsafe { + //@ close leaf_without_keys(raw,parent,pidx,(count+1) as u16,vals); + self.key_area_slot_mut/*@::<'a,K,V,marker::Leaf,'short>@*/(idx).write(key); //~track_ref_creation + //@ assert keys_slot_loan(raw,?key_slot,count,parent,pidx,(count+1) as u16,vals,_,_); + //@ end_keys_slot(raw,key_slot); + //@ open leaf_without_keys(raw,parent,pidx,(count+1) as u16,vals); + //@ let fitted_keys = replace_slot(count,MaybeUninit::new(key),keys); + //@ close leaf_without_vals(raw,parent,pidx,(count+1) as u16,fitted_keys); + self.val_area_slot_mut/*@::<'a,K,V,marker::Leaf,'short>@*/(idx).write(val); //~track_ref_creation + //@ assert vals_slot_loan(raw,?val_slot,count,parent,pidx,(count+1) as u16,fitted_keys,_,_); + //@ end_vals_slot(raw,val_slot); + //@ open leaf_without_vals(raw,parent,pidx,(count+1) as u16,fitted_keys); + //@ open_points_to(self); + let handle = Handle::,K,V,marker::Leaf>,marker::KV>::new_kv( + NodeRef { height: self.height, node: self.node, _marker: PhantomData }, + idx, + ); + //@ close_points_to(self); + //@ close leaf_slots(raw,count+1,fitted_keys,replace_slot(count,MaybeUninit::new(val),vals)); + handle + } + } + + unsafe fn push_leaf<'short>(&'short mut self, key: K, val: V) -> *mut V + /*@ + req *self |-> ?node &*& leaf_header(node.node.as_ptr(),?parent,?pidx) &*& + leaf_slots(node.node.as_ptr(),?count,?keys,?vals) &*& count < CAPACITY; + @*/ + /*@ + ens *self |-> node &*& + consumed_val_loan(node.node.as_ptr(),count,result,count+1,parent,pidx, + replace_slot(count,MaybeUninit::new(key),keys),replace_slot(count,MaybeUninit::new(val),vals)) &*& *result |-> val; + @*/ + //@ on_unwind_ens false; + { + //@ open leaf_slots(node.node.as_ptr(),count,keys,vals); + //@ array_inv::>(); + //@ close leaf_slots(node.node.as_ptr(),count,keys,vals); + //@ length_take(count,vals); + //@ nth_append_r(take(count,vals),cons(MaybeUninit::new(val),drop(count+1,vals)),0); + unsafe { + self.push_with_handle/*@::<'a,K,V,'short,'short>@*/(key,val).into_val_mut/*@::<'short,K,V,marker::Leaf>@*/() + } + } +} + +impl Handle,marker::Edge> { + unsafe fn right_kv(mut self) -> Result,marker::KV>,Self> + //@ req (*self.node.node.as_ptr()).len |-> ?len &*& self.idx <= len; + /*@ + ens (*self.node.node.as_ptr()).len |-> len &*& + match result { Result::Ok(kv) => self.idx < len && kv.node == self.node && kv.idx == self.idx, + Result::Err(edge) => self.idx == len && edge == self }; + @*/ + //@ on_unwind_ens false; + { + //@ open_points_to(&self); + //@ let receiver = precreate_ref(&self.node); + //@ init_ref_readonly(receiver,1/2); + let has_right = self.idx < unsafe { self.node.merge_len() }; + //@ end_ref_readonly(receiver); + //@ merge_fractions points_to(&self.node,_); + if has_right { + let kv = unsafe { Handle::new_navigation_kv(self.node,self.idx) }; + //@ close_points_to(&self); + Ok(kv) + } else { + //@ open_points_to(&self.node); + let out = Err(self); + //@ close_points_to(&self.node); + //@ close_points_to(&self); + out + } + } +} + +impl NodeRef { + unsafe fn clear_parent_link<'short>(&'short mut self) + /*@ + req *self |-> ?node &*& leaf_header(node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(node.node.as_ptr(),?len,?keys,?vals); + @*/ + /*@ + ens *self |-> node &*& leaf_header(node.node.as_ptr(),Option::None,parent_idx) &*& + leaf_slots(node.node.as_ptr(),len,keys,vals); + @*/ + //@ on_unwind_ens false; + { + let mut root_node = self.borrow_mut/*@::@*/(); + //@ let raw = node.node.as_ptr(); + //@ open leaf_header(raw,parent,parent_idx); + //@ open leaf_slots(raw,len,keys,vals); + //@ close_points_to(raw); + let leaf = root_node.as_leaf_mut/*@::<'short,K,V,marker::LeafOrInternal,'short>@*/(); + //@ open_points_to(leaf); + leaf.parent = None; + //@ close_points_to(leaf); + //@ end_ref_mut(leaf); + //@ open_points_to(raw); + //@ close leaf_header(raw,Option::None,parent_idx); + //@ close leaf_slots(raw,len,keys,vals); + } + + unsafe fn pop_internal_level<'short,A: AllocatorClone>(&'short mut self, /*@~mut@*/ alloc: A) + /*@ + req *self |-> ?old &*& std::ptr::drop_may_unwind::() == false &*& + thread_token(?t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + Allocator::(t,alloc,?id) &*& exists::(?k) &*& exists::(?fraction) &*& + exists::>(?child) &*& + leaf_header(child.as_ptr(),?parent,?parent_idx) &*& leaf_slots(child.as_ptr(),?len,?keys,?vals) &*& + if old.height == 0 { + child == old.node + } else { + allocated_internal(old.node.as_ptr() as *InternalNode,id,k,fraction) &*& + (*(old.node.as_ptr() as *InternalNode)).data.parent |-> Option::None &*& + (*(old.node.as_ptr() as *InternalNode)).data.parent_idx |-> _ &*& + leaf_slots(&(*(old.node.as_ptr() as *InternalNode)).data,0,_,_) &*& + (*(old.node.as_ptr() as *InternalNode)).edges[..CAPACITY+1] |-> ?edges &*& + nth(0,edges) == MaybeUninit::new(child) + }; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + *self |-> ?root &*& root.node == child &*& root.height == old.height - 1 &*& + leaf_header(child.as_ptr(),Option::None,parent_idx) &*& leaf_slots(child.as_ptr(),len,keys,vals) &*& + [fraction]lifetime_token(k); + @*/ + /*@ + on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + old.height == 0 &*& *self |-> old &*& + leaf_header(child.as_ptr(),parent,parent_idx) &*& leaf_slots(child.as_ptr(),len,keys,vals); + @*/ + { + //@ open exists(k); + //@ open exists(fraction); + //@ open exists(child); + /*@ + if old.height == 0 { + std::alloc::Allocator_to_own::(alloc); + } + @*/ + //@ open_points_to(self); + assert!(self.height > 0); + let top = self.node; + //@ close_points_to(self); + let mut internal_self = unsafe { self.borrow_mut/*@::@*/().cast_to_internal_unchecked() }; + //@ let target = old.node.as_ptr() as *InternalNode; + //@ let old_root = &(*target).data; + //@ open allocated_internal(target,id,k,fraction); + //@ std::ptr::NonNull_Sized_as_ptr(old.node); + //@ open leaf_slots(old_root,0,_,_); + //@ std::mem::MaybeUninit__to_MaybeUninit(&(*old_root).parent_idx); + //@ close_points_to(target); + let internal_node = internal_self.as_internal_mut/*@::<'short,K,V,'short>@*/(); + //@ open_points_to(internal_node); + //@ let base = &(*internal_node).edges as *MaybeUninit>; + //@ array_split(base,1); + //@ open array(base,1,_); + //@ open array(base+1,0,_); + //@ let slot = precreate_ref(base); + //@ init_ref_readonly(slot,1/2); + //@ open_points_to(self); + self.node = unsafe { internal_node.edges[0].assume_init_read() }; + //@ end_ref_readonly(slot); + //@ merge_fractions points_to(base,_); + //@ close array(base,1,[MaybeUninit::new(child)]); + //@ array_join(base); + //@ close_points_to(internal_node); + //@ end_ref_mut(internal_node); + self.height -= 1; + //@ close_points_to(self); + self.clear_parent_link/*@::@*/(); + + //@ points_to__limits(target); + //@ assert close_points_to_at_lft_token(1,id.lft,target,?allocation_fraction); + //@ to_u8s_(target); + //@ close_points_to_at_lft_token_to_close_u8s_at_lft_token(target); + //@ close_array_at_lft_(target as *u8); + //@ lifetime_token_trade_back(allocation_fraction,id.lft); + //@ let view = precreate_ref(&alloc); + //@ let call_lifetime = begin_lifetime(); + unsafe { + //@ let_lft 'call = call_lifetime; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'call,A>(view); + //@ std::ptr::NonNull_as_ptr_new(top.as_ptr() as *u8); + alloc.deallocate/*@::@*/(top.cast(),std::alloc::Layout::new::>()); + //@ leak Allocator::<&'call A>(t,view,id); + } + //@ end_lifetime(call_lifetime); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + //@ std::alloc::Allocator_to_own::(alloc); + } +} + +impl Handle,marker::KV> { + unsafe fn into_key_val(mut self) -> (K,V) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),?len,?keys,?vals) &*& 0 <= self.idx &*& self.idx < len &*& + nth(self.idx,keys).inner() == some(?former_key) &*& nth(self.idx,vals).inner() == some(?former_val) &*& + .own(t,former_key) &*& .own(t,former_val); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.node.node.as_ptr(),parent,parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),len,keys,vals) &*& + result.0 == former_key &*& result.1 == former_val &*& .own(t,result.0) &*& .own(t,result.1); + @*/ + //@ on_unwind_ens false; + { + //@ assert *(&self) |-> ?incoming; + //@ let node = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open leaf_slots(node,len,keys,vals); + //@ open_points_to(&self); + //@ let view = precreate_ref(&self.node); + //@ init_ref_readonly(view,1/2); + debug_assert!(self.idx < self.node.merge_len()); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self.node,_); + //@ open leaf_header(node,parent,parent_idx); + //@ close_points_to(node); + let leaf = self.node.as_leaf_dying/*@::@*/(); //~track_ref_creation + //@ open_points_to(leaf); + //@ close_points_to(&(*leaf).keys); + unsafe { + let key_slot = <[MaybeUninit]>::get_unchecked_mut( + { + let key_array = &mut leaf.keys; //~track_ref_creation + let slice: &mut [MaybeUninit] = key_array; + //@ open_points_to(key_array); + //@ split_node_slot(key_array as *MaybeUninit,index); + slice + }, + self.idx, + ); + //@ let key_view = precreate_ref(key_slot); + //@ init_ref_readonly(key_view,1/2); + let key = key_slot.assume_init_read(); + //@ end_ref_readonly(key_view); + //@ merge_fractions points_to(key_slot,_); + //@ close drop_slot_loan(&(*leaf).keys,key_array,key_slot,index,take(index,keys),drop(index+1,keys)); + //@ end_drop_slot(&(*leaf).keys,key_slot,index); + + //@ close_points_to(&(*leaf).vals); + let val_slot = <[MaybeUninit]>::get_unchecked_mut( + { + let val_array = &mut leaf.vals; //~track_ref_creation + let slice: &mut [MaybeUninit] = val_array; + //@ open_points_to(val_array); + //@ split_node_slot(val_array as *MaybeUninit,index); + slice + }, + self.idx, + ); + //@ let val_view = precreate_ref(val_slot); + //@ init_ref_readonly(val_view,1/2); + let val = val_slot.assume_init_read(); + //@ end_ref_readonly(val_view); + //@ merge_fractions points_to(val_slot,_); + //@ close drop_slot_loan(&(*leaf).vals,val_array,val_slot,index,take(index,vals),drop(index+1,vals)); + //@ end_drop_slot(&(*leaf).vals,val_slot,index); + //@ nth_at_partition(keys,index); + //@ nth_at_partition(vals,index); + //@ Array_to_array(&(*leaf).keys); + //@ Array_to_array(&(*leaf).vals); + //@ close_points_to(leaf); + //@ end_ref_mut(leaf); + //@ assert ref_mut_end_token(?receiver,&self.node); + //@ end_ref_mut(receiver); + //@ close_points_to(&self); + //@ open_points_to(node); + //@ close leaf_header(node,parent,parent_idx); + //@ close leaf_slots(node,len,keys,vals); + (key,val) + } + } +} + +unsafe fn read_parent_link(child: *const LeafNode) -> Option<(NonNull>,u16)> +/*@ +req [?f]link(child,?expected_parent,?idx); +@*/ +/*@ +ens [f]link(child,expected_parent,idx) &*& + match expected_parent { + Option::None => result == Option::None, + Option::Some(p) => result == Option::Some(std_tuple_2_::>,u16> { 0: p, 1: idx }) + }; +@*/ +//@ on_unwind_ens false; +{ + //@ open [f]link(child,expected_parent,idx); + let backlink = unsafe { (*child).parent }; + match backlink { + None => { + //@ close [f]link(child,Option::None,idx); + None + } + Some(parent) => { + //@ open_MaybeUninit(&(*child).parent_idx); + //@ points_to_limits(&(*child).parent_idx as *u16); + let observed_index = unsafe { *((&raw const (*child).parent_idx) as *const u16) }; + //@ close_MaybeUninit(&(*child).parent_idx); + //@ close [f]link(child,Option::Some(parent),idx); + Some((parent, observed_index)) + } + } +} + +impl NodeRef { + unsafe fn ascend_from_link(mut self) -> Result,marker::Edge>, Self> + /*@ + req [?f]link(self.node.as_ptr(),?expected_parent,?index) &*& + (if expected_parent != Option::None { self.height < usize::MAX } else { true }); + @*/ + /*@ + ens [f]link(self.node.as_ptr(),expected_parent,index) &*& + match expected_parent { + Option::None => match result { + Result::Err(original) => original == self, + Result::Ok(edge) => false + }, + Option::Some(p) => match result { + Result::Err(original) => false, + Result::Ok(edge) => edge.node.node.as_ptr() == p.as_ptr() as *LeafNode &*& + edge.node.height == self.height+1 &*& edge.idx == index + } + }; + @*/ + //@ on_unwind_ens false; + { + const { assert!(BorrowType::TRAVERSAL_PERMIT); } + //@ assert [?q]points_to(&self, ?original); + //@ let view = precreate_ref(&self); + //@ init_ref_readonly(view, 1/2); + let leaf_ptr: *const _ = unsafe { Self::as_leaf_ptr(&self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self, _); + //@ open_points_to(&self); + let height = self.height; + let node = self.node; + //@ close_points_to(&self, q); + let successor = unsafe { read_parent_link(leaf_ptr) }; + let result = match successor { + None => None, + Some((parent, observed_index)) => { + let parent_height = height + 1; + Some(Handle { + node: unsafe { NodeRef::from_internal(parent, parent_height) }, + idx: observed_index as usize, + _marker: PhantomData, + }) + } + }; + result.ok_or(NodeRef { height, node, _marker: PhantomData }) + } +} + +type DyingParent = Handle,marker::Edge>; +type DyingNode = NodeRef; + +unsafe fn dying_result_ok(value: Result,DyingNode>) -> Option> +//@ req true; +//@ ens match value { Result::Ok(v) => result == Option::Some(v), Result::Err(original) => result == Option::None }; +//@ on_unwind_ens false; +{ + match value { + Ok(x) => Some(x), + Err(_) => None, + } +} + +impl NodeRef { + unsafe fn deallocate_and_ascend( + self, /*@~mut@*/ alloc: A, + ) -> Option> + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + std::ptr::drop_may_unwind::() == false &*& Allocator::(t,alloc,?id) &*& + 0 <= self.height &*& + balancing_child_allocation(self.node,self.height,id,?k,?fraction) &*& + (*self.node.as_ptr()).parent |-> ?parent &*& (*self.node.as_ptr()).parent_idx |-> ?pidx &*& + leaf_slots(self.node.as_ptr(),_,_,_) &*& + exists::(?index) &*& + (if parent == Option::None { + index == 0 + } else { + self.height < usize::MAX &*& pidx == MaybeUninit::new(index) + }) &*& + (if self.height > 0 { + (*(self.node.as_ptr() as *InternalNode)).edges[..CAPACITY+1] |-> ?edge_storage + } else { + true + }); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& [fraction]lifetime_token(k) &*& + match parent { + Option::None => result == Option::None, + Option::Some(p) => match result { + Option::None => false, + Option::Some(edge) => edge.node.node.as_ptr() == p.as_ptr() as *LeafNode &*& + edge.node.height == self.height+1 &*& edge.idx == index + } + }; + @*/ + //@ on_unwind_ens false; + { + let height = self.height; + let node = self.node; + //@ let root = node.as_ptr(); + //@ open exists(index); + //@ close link(root,parent,index); + let ret = unsafe { dying_result_ok(self.ascend_from_link()) }; + //@ open link(root,parent,index); + //@ open balancing_child_allocation(node,height,id,k,fraction); + //@ open leaf_slots(root,_,_,_); + //@ std::ptr::NonNull_Sized_as_ptr(node); + /*@ + if height > 0 { + let internal = root as *InternalNode; + open allocated_internal(internal,id,k,fraction); + assert &(*internal).data == root; + close_points_to(internal); + points_to__limits(internal); + assert close_points_to_at_lft_token(1,id.lft,internal,?allocation_fraction); + to_u8s_(internal); + close_points_to_at_lft_token_to_close_u8s_at_lft_token(internal); + close_array_at_lft_(internal as *u8); + lifetime_token_trade_back(allocation_fraction,id.lft); + } else { + open allocated_leaf(root,id,k,fraction); + close_points_to(root); + points_to__limits(root); + assert close_points_to_at_lft_token(1,id.lft,root,?allocation_fraction); + to_u8s_(root); + close_points_to_at_lft_token_to_close_u8s_at_lft_token(root); + close_array_at_lft_(root as *u8); + lifetime_token_trade_back(allocation_fraction,id.lft); + } + @*/ + //@ let view = precreate_ref(&alloc); + //@ let call_lifetime = begin_lifetime(); + unsafe { + //@ let_lft 'call = call_lifetime; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'call,A>(view); + //@ std::ptr::NonNull_as_ptr_new(node.as_ptr() as *u8); + alloc.deallocate/*@::@*/( + node.cast(), + if height > 0 { + std::alloc::Layout::new::>() + } else { + std::alloc::Layout::new::>() + }, + ); + //@ leak Allocator::<&'call A>(t,view,id); + } + //@ end_lifetime(call_lifetime); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + //@ std::alloc::Allocator_to_own::(alloc); + ret + } +} + +/*@ +fix removed_prefix(entries: list, count: usize, index: usize) -> list { + append(take(index, take(count,entries)), append(drop(index+1,take(count,entries)), + append(drop(count-1,take(count,entries)), drop(count,entries)))) +} + +lem expand_removed_prefix(entries: list, count: usize, index: usize) + req true; + ens append(append(take(index,take(count,entries)),append(drop(index+1,take(count,entries)), + drop(count-1,take(count,entries)))),drop(count,entries)) == removed_prefix(entries,count,index); +{ + append_assoc(drop(index+1,take(count,entries)),drop(count-1,take(count,entries)),drop(count,entries)); + append_assoc(take(index,take(count,entries)),append(drop(index+1,take(count,entries)), + drop(count-1,take(count,entries))),drop(count,entries)); +} +@*/ + +impl<'a,K:'a,V:'a> Handle,K,V,marker::Leaf>,marker::KV> { + unsafe fn remove<'short>(mut self) + -> ((K,V), Handle,K,V,marker::Leaf>,marker::Edge>) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.node.node.as_ptr(),?parent,?parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),?size,?keys,?vals) &*& 0 <= self.idx &*& self.idx < size &*& + nth(self.idx,keys).inner() == some(?key) &*& nth(self.idx,keys) == MaybeUninit::new(key) &*& + nth(self.idx,vals).inner() == some(?val) &*& nth(self.idx,vals) == MaybeUninit::new(val) &*& + .own(t,key) &*& .own(t,val); + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + leaf_header(self.node.node.as_ptr(),parent,parent_idx) &*& + leaf_slots(self.node.node.as_ptr(),size-1,removed_prefix(keys,size,self.idx),removed_prefix(vals,size,self.idx)) &*& + (result.0).0 == key &*& (result.0).1 == val &*& .own(t,key) &*& .own(t,val) &*& + result.1.node == self.node &*& result.1.idx == self.idx; + @*/ + //@ on_unwind_ens false; + { + //@ assert *(&self) |-> ?incoming; + //@ let raw = incoming.node.node.as_ptr(); + //@ let index = incoming.idx; + //@ open leaf_slots(raw,size,keys,vals); + //@ open_points_to(&self); + //@ let meta = precreate_ref(&self.node); + //@ init_ref_readonly(meta,1/2); + let old_len = self.node.merge_len(); + //@ end_ref_readonly(meta); + //@ merge_fractions points_to(&self.node,_); + unsafe { + //@ close leaf_without_keys(raw,parent,parent_idx,size as u16,vals); + //@ nth_take_range(keys,size,index); + let k = slice_remove(self.node.key_area_prefix_mut/*@::<'a,K,V,marker::Leaf,'short>@*/(..old_len),self.idx); //~track_ref_creation + //@ assert keys_range_loan(raw,?key_slice,0,size,parent,parent_idx,size as u16,vals,_,_); + //@ end_keys_range(raw,key_slice); + //@ open leaf_without_keys(raw,parent,parent_idx,size as u16,vals); + //@ assert ref_mut_end_token(?after_key,&self.node); + //@ end_ref_mut(after_key); + //@ expand_removed_prefix(keys,size,index); + + //@ close leaf_without_vals(raw,parent,parent_idx,size as u16,removed_prefix(keys,size,index)); + //@ nth_take_range(vals,size,index); + let v = slice_remove(self.node.val_area_prefix_mut/*@::<'a,K,V,marker::Leaf,'short>@*/(..old_len),self.idx); //~track_ref_creation + //@ assert vals_range_loan(raw,?val_slice,0,size,parent,parent_idx,size as u16,_,_,_); + //@ end_vals_range(raw,val_slice); + //@ open leaf_without_vals(raw,parent,parent_idx,size as u16,removed_prefix(keys,size,index)); + //@ assert ref_mut_end_token(?after_val,&self.node); + //@ end_ref_mut(after_val); + //@ expand_removed_prefix(vals,size,index); + + //@ open leaf_header(raw,parent,parent_idx); + //@ close leaf_without_len(raw,parent,parent_idx,removed_prefix(keys,size,index),removed_prefix(vals,size,index)); + *self.node.len_mut/*@::<'a,K,V,marker::Leaf,'short>@*/() = (old_len-1) as u16; //~track_ref_creation + //@ assert len_loan(raw,?len,parent,parent_idx,_,_); + //@ end_len_loan(raw,len); + //@ open leaf_without_len(raw,parent,parent_idx,removed_prefix(keys,size,index),removed_prefix(vals,size,index)); + //@ assert ref_mut_end_token(?after_len,&self.node); + //@ end_ref_mut(after_len); + + let result = ((k,v),self.left_edge()); + //@ close leaf_header(raw,parent,parent_idx); + //@ close leaf_slots(raw,size-1,removed_prefix(keys,size,index),removed_prefix(vals,size,index)); + //@ close_points_to(&self); + result + } + } +} + +impl<'a,K,V> Handle,K,V,marker::Internal>,marker::KV> { + unsafe fn consider_for_balancing(mut self) -> BalancingContext<'a,K,V> + /*@ + req thread_token(?t) &*& 0 < self.node.height &*& + 0 <= self.idx &*& (*self.node.node.as_ptr()).len |-> ?len &*& self.idx < len &*& len <= CAPACITY &*& + pointer_within_limits(&(*(self.node.node.as_ptr() as *InternalNode)).edges) == true &*& + [?f](*(self.node.node.as_ptr() as *InternalNode)).edges[..CAPACITY+1] |-> ?edges &*& + exists::,BoxedNode>>(pair(?left,?right)) &*& + nth(self.idx,edges) == MaybeUninit::new(left) &*& nth(self.idx+1,edges) == MaybeUninit::new(right); + @*/ + /*@ + ens thread_token(t) &*& (*self.node.node.as_ptr()).len |-> len &*& + [f](*(self.node.node.as_ptr() as *InternalNode)).edges[..CAPACITY+1] |-> edges &*& + exists::,BoxedNode>>(pair(left,right)) &*& + result.parent == self &*& result.left_child.node == left &*& result.right_child.node == right &*& + result.left_child.height == self.node.height-1 &*& result.right_child.height == self.node.height-1; + @*/ + //@ on_unwind_ens false; + { + //@ open exists(pair(left,right)); + //@ assert *(&self) |-> ?incoming; + //@ let view = precreate_ref(&self); + //@ init_ref_readonly(view,1/2); + //@ open_points_to(view); + //@ open_points_to(&(*view).node); + let self1 = unsafe { std::ptr::read(&self) }; + //@ close_points_to(&(*view).node,1/2); + //@ close_points_to(view,1/2); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self,_); + //@ let view2 = precreate_ref(&self); + //@ init_ref_readonly(view2,1/2); + //@ open_points_to(view2); + //@ open_points_to(&(*view2).node); + let self2 = unsafe { std::ptr::read(&self) }; + //@ close_points_to(&(*view2).node,1/2); + //@ close_points_to(view2,1/2); + //@ end_ref_readonly(view2); + //@ merge_fractions points_to(&self,_); + //@ open_points_to(&self); + //@ open_points_to(&self.node); + let context = BalancingContext { + parent: self, + left_child: { + //@ close exists(left); + let child = unsafe { self1.left_edge().descend() }; + //@ open exists(left); + child + }, + right_child: { + //@ close exists(right); + let child = unsafe { self2.right_edge().descend() }; + //@ open exists(right); + child + }, + }; + //@ close_points_to(&self.node); + //@ close_points_to(&self); + //@ close exists(pair(left,right)); + context + } +} + + +impl<'a,K,V> NodeRef,K,V,marker::LeafOrInternal> { + unsafe fn cast_node_to_leaf(self) -> NodeRef,K,V,marker::Leaf> + //@ req self.height == 0; + //@ ens result.node == self.node &*& result.height == 0; + //@ on_unwind_ens false; + { + debug_assert!(self.height == 0); + NodeRef { height: self.height, node: self.node, _marker: PhantomData } + } +} + +impl<'a,K,V,Type> Handle,K,V,marker::LeafOrInternal>,Type> { + unsafe fn cast_handle_to_leaf(self) -> Handle,K,V,marker::Leaf>,Type> + //@ req self.node.height == 0; + //@ ens result.node.node == self.node.node &*& result.node.height == 0 &*& result.idx == self.idx; + //@ on_unwind_ens false; + { + let node = unsafe { self.node.cast_node_to_leaf() }; + Handle { node, idx: self.idx, _marker: PhantomData } + } +} + + +impl Handle,marker::Edge> { + unsafe fn forget_leaf_edge(self) -> Handle,marker::Edge> + //@ req (*self.node.node.as_ptr()).len |-> ?len &*& self.idx <= len; + //@ ens (*self.node.node.as_ptr()).len |-> len &*& result.node.node == self.node.node &*& result.node.height == self.node.height &*& result.idx == self.idx; + //@ on_unwind_ens false; + { + unsafe { Handle::new_relink_edge(self.node.forget_type(),self.idx) } + } +} + +impl Handle,marker::Edge> { + unsafe fn forget_internal_edge(self) -> Handle,marker::Edge> + //@ req (*self.node.node.as_ptr()).len |-> ?len &*& self.idx <= len; + //@ ens (*self.node.node.as_ptr()).len |-> len &*& result.node.node == self.node.node &*& result.node.height == self.node.height &*& result.idx == self.idx; + //@ on_unwind_ens false; + { + unsafe { Handle::new_relink_edge(self.node.forget_type(),self.idx) } + } +} + +impl Handle,marker::KV> { + unsafe fn forget_leaf_kv(self) -> Handle,marker::KV> + //@ req (*self.node.node.as_ptr()).len |-> ?len &*& self.idx < len; + //@ ens (*self.node.node.as_ptr()).len |-> len &*& result.node.node == self.node.node &*& result.node.height == self.node.height &*& result.idx == self.idx; + //@ on_unwind_ens false; + { + unsafe { Handle::new_navigation_kv(self.node.forget_type(),self.idx) } + } +} + + +/*@ +lem prepare_neighbor(children: list>, edges: list>>, index: usize) + req take(length(children),edges) == initialized_edges(children) &*& length(children) <= length(edges) &*& + 0 <= index &*& index < length(children); + ens exists::>(nth(index,children)) &*& nth(index,edges) == MaybeUninit::new(nth(index,children)); +{ + nth_take_range(edges,length(children),index); + nth_initialized_edge(children,index); + close exists(nth(index,children)); +} + +pred chosen_parent( + t: thread_id_t, path: list>, origin: *LeafNode, root: *LeafNode +) = + path == cons(ParentStep(?address,?idx,?count,ParentPayload(?keys,?vals,?edges)),?rest) &*& + exists::>>(?parent) &*& parent.as_ptr() == address &*& + ancestors(&(*address).data,rest,root) &*& route_frames(t,rest) &*& + ready_parent(t,parent,count,idx,?children,keys,vals) &*& nth(idx,children) == NonNull::new(origin) &*& + struct_LeafNode_padding(&(*address).data) &*& struct_InternalNode_padding(address); +@*/ + +impl<'a,K,V> NodeRef,K,V,marker::LeafOrInternal> { + unsafe fn choose_parent_kv(mut self) -> Result>,Self> + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + ancestors(self.node.as_ptr(),?path,?root) &*& route_frames(t,path) &*& + 0 <= self.height &*& self.height + length(path) < usize::MAX; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + match result { + Result::Err(top) => top == self &*& path == nil &*& ancestors(self.node.as_ptr(),path,root) &*& route_frames(t,path), + Result::Ok(choice) => chosen_parent(t,path,self.node.as_ptr(),root) &*& + match choice { + LeftOrRight::Left(context) => context.right_child == self, + LeftOrRight::Right(context) => context.left_child == self + } + }; + @*/ + //@ on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& chosen_parent(t,path,self.node.as_ptr(),root); + { + //@ assert *(&self) |-> ?incoming; + //@ let raw = incoming.node.as_ptr(); + //@ let view = precreate_ref(&self); + //@ init_ref_readonly(view,1/2); + //@ std::ptr::NonNull_new_as_ptr(incoming.node); + //@ close NodeRef_own::,K,V,marker::LeafOrInternal>(t,incoming); + let original = unsafe { std::ptr::read(&self) }; + //@ open NodeRef_own::,K,V,marker::LeafOrInternal>(t,original); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(&self,_); + match unsafe { original.ascend/*@::<'a,K,V>@*/() } { + Ok(parent_edge) => { + //@ open exists::>>(?parent); + //@ assert path == cons(ParentStep(parent.as_ptr(),?index,?count,ParentPayload(?keys,?vals,?original_edges)),?rest); + //@ std::ptr::NonNull_new_as_ptr(parent); + //@ std::ptr::NonNull_Sized_as_ptr(parent); + //@ open ready_parent(t,parent,count,index,?children,keys,vals); + //@ open internal_slots(parent,count,children,keys,vals); + //@ open node_arrays(parent.as_ptr(),keys,vals,?edges); + //@ assert parent_edge.node.node.as_ptr() == parent.as_ptr() as *LeafNode; + //@ assert &(*parent.as_ptr()).data == parent.as_ptr() as *LeafNode; + //@ array_inv::>>(); + match parent_edge.left_kv() { + Ok(/*@~mut@*/ left_parent_kv) => { + //@ close_points_to(&left_parent_kv); + //@ let meta = precreate_ref(&left_parent_kv); + //@ init_ref_readonly(meta,1/2); + //@ open_points_to(meta); + //@ open_points_to(&(*meta).node); + let parent_handle = unsafe { std::ptr::read(&left_parent_kv) }; + //@ close_points_to(&(*meta).node,1/2); + //@ close_points_to(meta,1/2); + //@ end_ref_readonly(meta); + //@ merge_fractions points_to(&left_parent_kv,_); + //@ prepare_neighbor(children,edges,index-1); + //@ open_points_to(&left_parent_kv); + //@ open_points_to(&left_parent_kv.node); + let left_child = unsafe { left_parent_kv.left_edge().descend() }; + //@ open exists(nth(index-1,children)); + //@ close node_arrays(parent.as_ptr(),keys,vals,edges); + //@ close internal_slots(parent,count,children,keys,vals); + //@ close ready_parent(t,parent,count,index,children,keys,vals); + //@ close exists(parent); + //@ close chosen_parent(t,path,raw,root); + //@ open_points_to(&self); + let answer = Ok(LeftOrRight::Left(BalancingContext { + parent: parent_handle, left_child, right_child: self, + })); + //@ close_points_to(&self); + answer + } + Err(parent_edge) => match parent_edge.right_kv() { + Ok(/*@~mut@*/ right_parent_kv) => { + //@ close_points_to(&right_parent_kv); + //@ let meta = precreate_ref(&right_parent_kv); + //@ init_ref_readonly(meta,1/2); + //@ open_points_to(meta); + //@ open_points_to(&(*meta).node); + let parent_handle = unsafe { std::ptr::read(&right_parent_kv) }; + //@ close_points_to(&(*meta).node,1/2); + //@ close_points_to(meta,1/2); + //@ end_ref_readonly(meta); + //@ merge_fractions points_to(&right_parent_kv,_); + //@ open_points_to(&self); + let left_child = self; + //@ prepare_neighbor(children,edges,index+1); + //@ open_points_to(&right_parent_kv); + //@ open_points_to(&right_parent_kv.node); + let right_child = unsafe { right_parent_kv.right_edge().descend() }; + //@ open exists(nth(index+1,children)); + //@ close node_arrays(parent.as_ptr(),keys,vals,edges); + //@ close internal_slots(parent,count,children,keys,vals); + //@ close ready_parent(t,parent,count,index,children,keys,vals); + //@ close exists(parent); + //@ close chosen_parent(t,path,raw,root); + let answer = Ok(LeftOrRight::Right(BalancingContext { + parent: parent_handle, left_child, right_child, + })); + //@ close_points_to(&self); + answer + } + Err(_) => { + //@ close node_arrays(parent.as_ptr(),keys,vals,edges); + //@ close internal_slots(parent,count,children,keys,vals); + //@ close ready_parent(t,parent,count,index,children,keys,vals); + //@ close exists(parent); + //@ close chosen_parent(t,path,raw,root); + panic!("internal error: entered unreachable code: empty internal node") + }, + }, + } + } + Err(top) => Err(top), + } + } +} + +fn main() {} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verified/loop_regions.rs.in b/verifast-proofs/alloc/collections/btree/node.rs/verified/loop_regions.rs.in new file mode 100644 index 0000000000000..b115bfdf04c4b --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verified/loop_regions.rs.in @@ -0,0 +1,90 @@ + +const _: () = { + type LeafRef = NodeRef, String, String, marker::Leaf>; + type InternalRef = NodeRef, String, String, marker::Internal>; + assert!(!std::mem::needs_drop::>()); + assert!(!std::mem::needs_drop::>()); + assert!(!std::mem::needs_drop::>()); + assert!(!std::mem::needs_drop::, String, String, marker::LeafOrInternal>>()); + assert!(!std::mem::needs_drop::>()); +}; + +use super::borrow::DormantMutRef; + +unsafe fn install_root_split__VeriFast_wrapper<'tree, K, V, A: AllocatorClone>( + root_slot: &mut DormantMutRef<'tree, Option>>, + allocator: &mut A, + _left: NonNull>, + key: K, + value: V, + right: Root, +) { + let root = unsafe { root_slot.reborrow().as_mut().unwrap() }; + root.push_internal_level(allocator.clone()).push(key, value, right); +} + +// SOURCE unsafe fn finish_root_split<'tree, 'slot, K, V, A: AllocatorClone>( + +// SOURCE unsafe fn repair_one__VeriFast_wrapper<'a, 'b, K, V>( + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn relink_range<'b>(&'b mut self, range: std::ops::Range) +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn relink_inclusive<'b>(&'b mut self, range: std::ops::RangeInclusive) +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn correct_all_childrens_parent_links<'b>(&'b mut self) +} + +fn moved_node_metadata( + node: NodeRef, +) -> (usize, NonNull>) { + let moved = NodeRef:: { height: node.height, node: node.node, _marker: PhantomData }; + (moved.height, moved.node) +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { + pub(super) fn compare_merge_tracking_child_edge( + self, + track_edge_idx: LeftOrRight, + alloc: A, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { + let old_left_len = self.left_child.len(); + let right_len = self.right_child.len(); + assert!(match track_edge_idx { + LeftOrRight::Left(idx) => idx <= old_left_len, + LeftOrRight::Right(idx) => idx <= right_len, + }); + let child = self.merge_tracking_child(alloc); + unsafe { finish_merge_tracking__VeriFast_wrapper(child, old_left_len, track_edge_idx) } + } +} + +// SOURCE unsafe fn finish_merge_tracking__VeriFast_wrapper<'tree, K, V>( + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { + pub(super) fn compare_steal_left( + mut self, + track_right_edge_idx: usize, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { + self.bulk_steal_left(1); + // ignore-tidy-undocumented-unsafe + unsafe { finish_steal_left__VeriFast_wrapper(self.right_child, track_right_edge_idx) } + } + + pub(super) fn compare_steal_right( + mut self, + track_left_edge_idx: usize, + ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { + self.bulk_steal_right(1); + // ignore-tidy-undocumented-unsafe + unsafe { finish_steal_right__VeriFast_wrapper(self.left_child, track_left_edge_idx) } + } +} + +// SOURCE unsafe fn finish_steal_left__VeriFast_wrapper<'tree, K, V>( + +// SOURCE unsafe fn finish_steal_right__VeriFast_wrapper<'tree, K, V>( diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verified/operations.rs.in b/verifast-proofs/alloc/collections/btree/node.rs/verified/operations.rs.in new file mode 100644 index 0000000000000..f3250b42f894c --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verified/operations.rs.in @@ -0,0 +1,1004 @@ +#![feature(allocator_ext)] +//! Ancestor ownership and the key, value, and child moves used during splitting. +//! Refinement checks the production `as_leaf_ptr` and `set_parent_link`. + +#![allow(dead_code)] + +use std::marker::PhantomData; +use std::mem::MaybeUninit; +use std::ptr::NonNull; + +//@ use std::mem::{MaybeUninit, open_MaybeUninit, close_MaybeUninit}; +//@ use std::option::Option; +//@ use std::ptr::NonNull; + +const B: usize = 6; + +const CAPACITY: usize = 2 * B - 1; + +//@ fix B() -> usize { 6 } + +//@ fix CAPACITY() -> usize { 2 * B - 1 } + +struct LeafNode { + /// We want to be covariant in `K` and `V`. + parent: Option>>, + + /// This node's index into the parent node's `edges` array. + /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`. + /// This is only guaranteed to be initialized when `parent` is non-null. + parent_idx: MaybeUninit, + + /// The number of keys and values this node stores. + len: u16, + + /// The arrays storing the actual data of the node. Only the first `len` elements of each + /// array are initialized and valid. + keys: [MaybeUninit; CAPACITY], + vals: [MaybeUninit; CAPACITY], +} + +#[repr(C)] +struct InternalNode { + data: LeafNode, + + /// The pointers to the children of this node. `len + 1` of these are considered + /// initialized and valid, except that near the end, while the tree is held + /// through borrow type `Dying`, some of these pointers are dangling. + edges: [MaybeUninit>; 2 * B], +} + +type BoxedNode = NonNull>; + +struct NodeRef { + /// The number of levels that the node and the level of leaves are apart, a + /// constant of the node that cannot be entirely described by `Type`, and that + /// the node itself does not store. We only need to store the height of the root + /// node, and derive every other node's height from it. + /// Must be zero if `Type` is `Leaf` and non-zero if `Type` is `Internal`. + height: usize, + /// The pointer to the leaf or internal node. The definition of `InternalNode` + /// ensures that the pointer is valid either way. + node: NonNull>, + _marker: PhantomData<(BorrowType, Type)>, +} + +mod marker { + use super::PhantomData; + pub(crate) struct Mut<'a>(PhantomData<&'a mut ()>); + pub(crate) enum LeafOrInternal {} + pub(crate) enum DormantMut {} + pub(crate) enum Owned {} + pub(crate) enum Dying {} + pub(crate) enum Leaf {} + pub(crate) enum Internal {} + pub(crate) enum KV {} + pub(crate) enum Edge {} +} + +use std::alloc::AllocatorClone; +use std::ptr; + +const KV_IDX_CENTER: usize = B - 1; +//@ fix KV_IDX_CENTER() -> usize { B - 1 } +const EDGE_IDX_LEFT_OF_CENTER: usize = B - 1; +//@ fix EDGE_IDX_LEFT_OF_CENTER() -> usize { B - 1 } +const EDGE_IDX_RIGHT_OF_CENTER: usize = B; +//@ fix EDGE_IDX_RIGHT_OF_CENTER() -> usize { B } + +enum LeftOrRight { + Left(T), + Right(T), +} + +struct SplitResult<'a, K, V, NodeType> { + // Altered node in existing tree with elements and edges that belong to the left of `kv`. + pub left: NodeRef, K, V, NodeType>, + // Some key and value that existed before and were split off, to be inserted elsewhere. + pub kv: (K, V), + // Owned, unattached, new node with elements and edges that belong to the right of `kv`. + pub right: NodeRef, +} + +type Root = NodeRef; + +struct Handle { + node: Node, + idx: usize, + _marker: PhantomData, +} + +// SOURCE unsafe fn slice_insert(slice: &mut [MaybeUninit], idx: usize, val: T) + +impl NodeRef { +// SOURCE unsafe fn awaken<'a>(self) -> NodeRef, K, V, Type> +} + +impl Handle, HandleType> { +// SOURCE unsafe fn awaken<'a>(self) -> Handle, K, V, NodeType>, HandleType> +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE unsafe fn dormant<'b>(&'b self) -> NodeRef +} + +impl<'a, K, V, NodeType, HandleType> Handle, K, V, NodeType>, HandleType> { +// SOURCE unsafe fn dormant<'b>(&'b self) -> Handle, HandleType> +} + +struct DormantMutRef<'a, T> { + ptr: NonNull, + _marker: PhantomData<&'a mut T>, +} + +impl<'a, T> DormantMutRef<'a, T> { +// SOURCE unsafe fn reborrow(&mut self) -> &'a mut T +} + +// SOURCE unsafe fn clone_allocator(alloc: &mut A) -> A + +// SOURCE unsafe fn read_promoted(slot: *const MaybeUninit) -> T + +// SOURCE unsafe fn slice_shl(slice: &mut [MaybeUninit], distance: usize) + +// SOURCE unsafe fn slice_shr(slice: &mut [MaybeUninit], distance: usize) + +// SOURCE unsafe fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) + +// SOURCE unsafe fn slice_remove(slice: &mut [MaybeUninit], idx: usize) -> T + +// SOURCE unsafe fn move_slice_mut<'a, T>(base: *mut MaybeUninit, len: usize) -> &'a mut [MaybeUninit] + +// SOURCE unsafe fn merge_payload( + +unsafe fn merge_field( + parent: *mut MaybeUninit, + left: *mut MaybeUninit, + right: *mut MaybeUninit, + parent_idx: usize, + old_parent_len: usize, + old_left_len: usize, + right_len: usize, + new_left_len: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& + 0 <= parent_idx &*& parent_idx < old_parent_len &*& old_parent_len <= CAPACITY &*& + 0 <= old_left_len &*& 0 <= right_len &*& new_left_len == old_left_len + 1 + right_len &*& new_left_len <= CAPACITY &*& + parent[..CAPACITY] |-> ?p &*& left[..CAPACITY] |-> ?l &*& right[..CAPACITY] |-> ?r &*& + slot_owners(t, take(old_parent_len, p)) &*& slot_owners(t, take(old_left_len, l)) &*& + slot_owners(t, take(right_len, r)); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& + parent[..CAPACITY] |-> ?p_after &*& left[..CAPACITY] |-> ?l_after &*& right[..CAPACITY] |-> r &*& + slot_owners(t, take(old_parent_len - 1, p_after)) &*& slot_owners(t, take(new_left_len, l_after)); +@*/ +//@ on_unwind_ens false; +{ + //@ own_move_array(parent, CAPACITY); + //@ own_move_array(left, CAPACITY); + //@ own_move_array(right, CAPACITY); + //@ split_move_slice(parent, CAPACITY, old_parent_len); + //@ split_move_slice(left, CAPACITY, new_left_len); + //@ split_move_slice(right, CAPACITY, right_len); + //@ take_twice(l, old_left_len, new_left_len); + unsafe { merge_payload(parent, left, right, parent_idx, old_parent_len, old_left_len, right_len, new_left_len) }; + //@ assert move_slice(parent, old_parent_len, ?new_p); + //@ assert move_slice(left, new_left_len, ?new_l); + //@ move_slice_length(parent, old_parent_len); + //@ move_slice_length(left, new_left_len); + //@ join_move_slices(parent, old_parent_len, CAPACITY - old_parent_len); + //@ join_move_slices(left, new_left_len, CAPACITY - new_left_len); + //@ join_move_slices(right, right_len, CAPACITY - right_len); + //@ take_append_l(old_parent_len - 1, new_p, drop(old_parent_len, p)); + //@ take_append_l(new_left_len, new_l, drop(new_left_len, l)); + //@ take_length(new_l); + //@ append_take_drop_n(r, right_len); + //@ open move_slice(parent, CAPACITY, _); + //@ open move_slice(left, CAPACITY, _); + //@ open move_slice(right, CAPACITY, r); +} + +// SOURCE unsafe fn release_balancing_node<'alloc, T, A: std::alloc::Allocator>( + +// SOURCE unsafe fn merge_keys<'a, 'short, K, V>( + +// SOURCE unsafe fn merge_vals<'a, 'short, K, V>( + +// SOURCE unsafe fn remove_merged_edge<'a, 'short, K, V>( + +// SOURCE unsafe fn append_merged_edges<'a, 'short, K, V>( + +impl NodeRef { +// SOURCE_IN_IMPL unsafe fn forget_type(self) -> NodeRef +} + +impl NodeRef { +// SOURCE_IN_IMPL unsafe fn forget_type(self) -> NodeRef +} + +impl<'a, K, V> SplitResult<'a, K, V, marker::Leaf> { +// SOURCE_IN_IMPL unsafe fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> +} + +impl<'a, K, V> SplitResult<'a, K, V, marker::Internal> { +// SOURCE_IN_IMPL unsafe fn forget_node_type(self) -> SplitResult<'a, K, V, marker::LeafOrInternal> +} + +impl LeafNode { +// SOURCE unsafe fn init(this: *mut Self) + +// SOURCE_IN_IMPL unsafe fn new(alloc: A) -> Box +} + +impl InternalNode { +// SOURCE_IN_IMPL unsafe fn new(alloc: A) -> Box +} + +impl NodeRef { + fn as_leaf_ptr(this: &Self) -> *mut LeafNode { + // The node must be valid for at least the LeafNode portion. + // This is not a reference in the NodeRef type because we don't know if + // it should be unique or shared. + this.node.as_ptr() + } +} + +impl NodeRef { +// SOURCE unsafe fn as_internal_ptr(this: &Self) -> *mut InternalNode +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE unsafe fn as_leaf_mut<'short>(&'short mut self) -> &'short mut LeafNode +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE unsafe fn key_area_range_mut<'short>( +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE unsafe fn key_area_prefix_mut<'short>( +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE unsafe fn key_area_slot_mut<'short>( +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE unsafe fn val_area_range_mut<'short>( +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE unsafe fn val_area_prefix_mut<'short>( +} + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE unsafe fn val_area_slot_mut<'short>( +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn as_internal_mut<'short>(&'short mut self) -> &'short mut InternalNode +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn edge_area_range_mut<'short>( +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn edge_area_prefix_mut<'short>( +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn edge_area_slot_mut<'short>( +} + +/*@ +pred leaf_without_len(leaf: *LeafNode; + parent: Option>>, index: MaybeUninit, + keys: list>, vals: list>) = + struct_LeafNode_padding(leaf) &*& + (*leaf).parent |-> parent &*& (*leaf).parent_idx |-> index &*& + (*leaf).keys[..CAPACITY] |-> keys &*& (*leaf).vals[..CAPACITY] |-> vals; + +pred len_loan(leaf: *LeafNode, lent: *u16, + parent: Option>>, index: MaybeUninit, + keys: list>, vals: list>) = + exists::<*LeafNode>(?view) &*& ref_mut_end_token(view, leaf) &*& + ref_mut_end_token(lent, &(*view).len) &*& leaf_without_len(view, parent, index, keys, vals); + +lem end_len_loan(leaf: *LeafNode, lent: *u16) + req len_loan(leaf, lent, ?parent, ?index, ?keys, ?vals) &*& *lent |-> ?updated; + ens leaf_without_len(leaf, parent, index, keys, vals) &*& (*leaf).len |-> updated; +{ + open len_loan(leaf, lent, parent, index, keys, vals); + open exists::<*LeafNode>(?view); + end_ref_mut(lent); + open leaf_without_len(view, parent, index, keys, vals); + close_points_to(view); + end_ref_mut(view); + open_points_to(leaf); + close leaf_without_len(leaf, parent, index, keys, vals); +} +@*/ + +impl<'a, K, V, Type> NodeRef, K, V, Type> { +// SOURCE unsafe fn len_mut<'short>(&'short mut self) -> &'short mut u16 +} + +impl<'a, K, V> NodeRef, K, V, marker::LeafOrInternal> { +// SOURCE unsafe fn cast_to_internal_unchecked(self) -> NodeRef, K, V, marker::Internal> +} + +fn main() {} + + +struct BalancingContext<'a, K, V> { + parent: Handle, K, V, marker::Internal>, marker::KV>, + left_child: NodeRef, K, V, marker::LeafOrInternal>, + right_child: NodeRef, K, V, marker::LeafOrInternal>, +} + +impl NodeRef { +// SOURCE unsafe fn reborrow_mut<'b>(&'b mut self) -> NodeRef, K, V, Type> +} + +impl NodeRef { +// SOURCE unsafe fn merge_len(&self) -> usize +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +// SOURCE unsafe fn do_merge_production< +} + +// SOURCE unsafe fn call_merge__VeriFast_wrapper R, R>(finish: F, parent: P, child: C) -> R + +impl Handle, marker::Edge> { + unsafe fn new_edge(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx <= len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx <= node.merge_len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +// SOURCE unsafe fn merge_tracking_child( + +// SOURCE unsafe fn merge_child_production( + +// SOURCE unsafe fn merge_tracking_child_edge( +} + +// SOURCE unsafe fn select_merged_child<'a,K,V>( + +// SOURCE unsafe fn finish_merge_tracking__VeriFast_wrapper<'tree, K, V>( + +// SOURCE unsafe fn borrow_initialized_slot<'short,T>(slot: &'short mut MaybeUninit) -> &'short mut T + +/*@ +fix replace_slot(index: usize, entry: T, slots: list) -> list { + append(take(index,slots),cons(entry,drop(index+1,slots))) +} +@*/ + +impl<'a, K:'a, V:'a, NodeType> Handle,K,V,NodeType>,marker::KV> { +// SOURCE unsafe fn replace_kv_production<'short>(&'short mut self, k:K, v:V) -> (K,V) +} + +enum ForceResult { + Leaf(Leaf), + Internal(Internal), +} + +impl NodeRef { +// SOURCE unsafe fn force( +} + + +/*@ +lem open_slot_owner(t: thread_id_t, slots: list>, len: usize, idx: usize) + req 0 <= idx &*& idx < len &*& len <= length(slots) &*& slot_owners(t,take(len,slots)); + ens slot_owners(t,take(idx,slots)) &*& slot_owners(t,drop(idx+1,take(len,slots))) &*& + nth(idx,slots).inner() == some(?value) &*& nth(idx,slots) == MaybeUninit::new(value) &*& .own(t,value); +{ + let live = take(len,slots); + length_take(len,slots); + split_slot_owners(t,live,idx); + take_twice(slots,idx,len); + drop_n_plus_one(idx,live); + drop_twice(1,idx,live); + open slot_owners(t,drop(idx,live)); + nth_take_range(slots,len,idx); +} + +lem restore_slot_owner(t: thread_id_t, slots: list>, len: usize, idx: usize, value: T) + req 0 <= idx &*& idx < len &*& len <= length(slots) &*& + slot_owners(t,take(idx,slots)) &*& slot_owners(t,drop(idx+1,take(len,slots))) &*& .own(t,value); + ens slot_owners(t,take(len,replace_slot(idx,MaybeUninit::new(value),slots))); +{ + let head = take(idx,slots); + let middle = [MaybeUninit::new(value)]; + let tail = drop(idx+1,take(len,slots)); + take_after_drop(slots,idx+1,len-idx-1); + length_take(idx,slots); + length_append(head,middle); + append_assoc(head,middle,drop(idx+1,slots)); + take_append(len,append(head,middle),drop(idx+1,slots)); + close slot_owners::(t,nil); + close slot_owners(t,middle); + join_slot_owners(t,head,middle); + join_slot_owners(t,append(head,middle),tail); +} + +lem join_stolen_prefix( + t: thread_id_t, l: list>, r: list>, + shifted: list>, copied: list>, written: list>, + left_len: usize, right_len: usize, count: usize, saved: T +) + req 0 < count &*& count <= left_len &*& left_len <= length(l) &*& + 0 <= right_len &*& right_len+count <= length(r) &*& + shifted == append(take(count,take(right_len+count,r)),append(take(right_len,r),drop(right_len+count,r))) &*& + copied == append(take(count-1,drop(left_len-count+1,l)),drop(count-1,shifted)) &*& + written == replace_slot(count-1,MaybeUninit::new(saved),copied) &*& + slot_owners(t,drop(left_len-count+1,take(left_len,l))) &*& + slot_owners(t,take(right_len,r)) &*& .own(t,saved); + ens slot_owners(t,take(right_len+count,written)); +{ + let stolen = take(count-1,drop(left_len-count+1,l)); + let kept = take(right_len,r); + let prefix = take(count,take(right_len+count,r)); + let tail = drop(right_len+count,r); + let separator = [MaybeUninit::new(saved)]; + length_take(right_len+count,r); + length_take(count,take(right_len+count,r)); + take_after_drop(l,left_len-count+1,count-1); + length_drop(left_len-count+1,l); + length_take(count-1,drop(left_len-count+1,l)); + take_append_l(count-1,stolen,drop(count-1,shifted)); + take_length(stolen); + drop_append(count,stolen,drop(count-1,shifted)); + drop_twice(1,count-1,shifted); + drop_append(count,prefix,append(kept,tail)); + drop_0(append(kept,tail)); + append_assoc(stolen,separator,append(kept,tail)); + append_assoc(append(stolen,separator),kept,tail); + length_take(right_len,r); + length_append(stolen,separator); + length_append(append(stolen,separator),kept); + take_append_l(right_len+count,append(append(stolen,separator),kept),tail); + take_length(append(append(stolen,separator),kept)); + close slot_owners::(t,nil); + close slot_owners(t,separator); + join_slot_owners(t,stolen,separator); + join_slot_owners(t,append(stolen,separator),kept); +} + +lem join_right_steal( + t: thread_id_t, l: list>, r: list>, + written: list>, copied: list>, shifted: list>, + left_len: usize, right_len: usize, count: usize, saved: T +) + req 0 < count &*& count <= right_len &*& right_len <= length(r) &*& + 0 <= left_len &*& left_len+count <= length(l) &*& + written == replace_slot(left_len,MaybeUninit::new(saved),l) &*& + copied == append(take(left_len+1,written),append(take(count-1,r),drop(left_len+count,written))) &*& + shifted == append(append(drop(count,take(right_len,r)),drop(right_len-count,take(right_len,r))),drop(right_len,r)) &*& + slot_owners(t,take(count-1,take(right_len,r))) &*& slot_owners(t,drop(count,take(right_len,r))) &*& + slot_owners(t,take(left_len,l)) &*& .own(t,saved); + ens slot_owners(t,take(left_len+count,copied)) &*& slot_owners(t,take(right_len-count,shifted)); +{ + let kept_left = take(left_len,l); + let separator = [MaybeUninit::new(saved)]; + let left_head = append(kept_left,separator); + let stolen = take(count-1,r); + let kept_right = drop(count,take(right_len,r)); + length_take(left_len,l); + length_append(kept_left,separator); + append_assoc(kept_left,separator,drop(left_len+1,l)); + assert written == append(left_head,drop(left_len+1,l)); + take_append_l(left_len+1,left_head,drop(left_len+1,l)); + take_length(left_head); + assert take(left_len+1,written) == left_head; + take_twice(r,count-1,right_len); + length_take(count-1,r); + append_assoc(left_head,stolen,drop(left_len+count,written)); + length_append(left_head,stolen); + take_append_l(left_len+count,append(left_head,stolen),drop(left_len+count,written)); + take_length(append(left_head,stolen)); + close slot_owners::(t,nil); + close slot_owners(t,separator); + join_slot_owners(t,kept_left,separator); + join_slot_owners(t,left_head,stolen); + length_take(right_len,r); + length_drop(count,take(right_len,r)); + append_assoc(kept_right,drop(right_len-count,take(right_len,r)),drop(right_len,r)); + take_append_l(right_len-count,kept_right,append(drop(right_len-count,take(right_len,r)),drop(right_len,r))); + take_length(kept_right); +} +@*/ + +impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { +// SOURCE unsafe fn bulk_steal_left_production<'short>(&'short mut self, count: usize) + +// SOURCE unsafe fn bulk_steal_right_production<'short>(&'short mut self, count: usize) + +// SOURCE unsafe fn steal_left_production( + +// SOURCE unsafe fn steal_right_production( +} + + +impl<'a, K, V, Type, Kind> Handle, K, V, Type>, Kind> { +// SOURCE unsafe fn reborrow_handle_mut<'short>(&'short mut self) -> Handle, K, V, Type>, Kind> +} + +impl Handle { +// SOURCE unsafe fn into_node(self) -> Node +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { +// SOURCE unsafe fn move_suffix_production<'short>( +} + + + +// BEGIN_DROP_VALUE +// SOURCE unsafe fn drop_slot_production<'slot, T>(slot: &'slot mut MaybeUninit) + +struct Dropper<'a, T>(&'a mut MaybeUninit); + +impl<'a, T> Dropper<'a, T> { +// SOURCE unsafe fn drop_value_guard(&mut self) +} +// END_DROP_VALUE + +// The storage remains reusable after either exit from the destructor. +// SOURCE unsafe fn drop_initialized_slot(slot: *mut MaybeUninit) + +// SOURCE unsafe fn drop_guarded_value(slot: *mut MaybeUninit) + +// SOURCE unsafe fn drop_pair(key: *mut MaybeUninit, value: *mut MaybeUninit) + + +impl NodeRef { +// SOURCE_IN_IMPL unsafe fn len(&self) -> usize +} + +// The production cleanup edges are checked separately. A key unwind +// leaves its value pending. Its value guard completes that slot before +// the node guard resumes at the next pair. + +impl NodeRef { +// SOURCE unsafe fn as_leaf_dying<'short>(&'short mut self) -> &'short mut LeafNode +} + +// SOURCE unsafe fn duplicate_dying( + +/*@ +pred drop_slot_loan( + field: *[MaybeUninit; N], array: *[MaybeUninit; N], slot: *MaybeUninit, index: usize, + prior: list>, later: list> +) = + ref_mut_end_token(array, field) &*& + ref_mut_end_token(slot, array as *MaybeUninit + index) &*& + (array as *MaybeUninit)[..index] |-> prior &*& + (array as *MaybeUninit)[index+1..int_of_const(typeid(N))] |-> later; + +lem close_drop_array(p: *[T; N]) + req (p as *T)[..int_of_const(typeid(N))] |-> ?values; + ens *p |-> ?value &*& Array_elems(value) == values; +{ + let base = p as *T; + close_points_to(p, 1/2); + assert [1/2](*p |-> ?value); + Array_to_array(p); + merge_fractions array(base, int_of_const(typeid(N)), _); + assert Array_elems(value) == values; + close_points_to(p); +} + +lem end_drop_slot(field: *[MaybeUninit; N], slot: *MaybeUninit, index: usize) + req drop_slot_loan(field,?array,slot,index,?before,?after) &*& *slot |-> ?entry; + ens *field |-> ?entries &*& Array_elems(entries) == append(before,cons(entry,after)); +{ + open drop_slot_loan(field,array,slot,index,before,after); + let base = array as *MaybeUninit; + end_ref_mut(slot); + close array(base+index+1,0,[]); + close array(base+index,1,[entry]); + array_join(base+index); + array_join(base); + close_drop_array(array); + end_ref_mut(array); +} +@*/ + +impl Handle, marker::KV> { +// SOURCE unsafe fn project_drop_slots<'short>( +} + +/*@ +pred drop_kv_frame( + node: *LeafNode, leaf: *LeafNode, key: *MaybeUninit, value: *MaybeUninit, + index: usize, len: usize, keys: list>, vals: list>, + parent: Option>>, parent_idx: MaybeUninit +) = + ref_mut_end_token(leaf,node) &*& + leaf_header(leaf,parent,parent_idx) &*& (*leaf).len |-> len as u16 &*& + drop_slot_loan(&(*leaf).keys,?keys_ref,key,index,take(index,keys),drop(index+1,keys)) &*& + drop_slot_loan(&(*leaf).vals,?vals_ref,value,index,take(index,vals),drop(index+1,vals)); + +lem take_after_replacing_cell(entries: list, len: usize, index: usize, cell: T) + req 0 <= index &*& index < len &*& len <= length(entries); + ens drop(index+1,take(len,replace_slot(index,cell,entries))) == drop(index+1,take(len,entries)); +{ + let before = take(index,entries); + let head = append(before,[cell]); + let tail = drop(index+1,entries); + length_take(index,entries); + length_append(before,[cell]); + append_assoc(before,[cell],tail); + take_append(len,head,tail); + drop_append(index+1,head,take(len-index-1,tail)); + drop_0(take(len-index-1,tail)); + take_after_drop(entries,index+1,len-index-1); +} + +lem restore_dropped_kv( + node: *LeafNode, leaf: *LeafNode, key: *MaybeUninit, value: *MaybeUninit, + index: usize, len: usize, keys: list>, vals: list>, + parent: Option>>, parent_idx: MaybeUninit +) + req drop_kv_frame(node,leaf,key,value,index,len,keys,vals,parent,parent_idx) &*& + *(key as *K) |-> _ &*& *(value as *V) |-> _ &*& + 0 <= index &*& index < len &*& len <= CAPACITY &*& length(keys) == CAPACITY &*& length(vals) == CAPACITY; + ens leaf_header(node,parent,parent_idx) &*& leaf_slots(node,len,?next_keys,?next_vals) &*& + drop(index+1,take(len,next_keys)) == drop(index+1,take(len,keys)) &*& + drop(index+1,take(len,next_vals)) == drop(index+1,take(len,vals)); +{ + open drop_kv_frame(node,leaf,key,value,index,len,keys,vals,parent,parent_idx); + std::mem::close_MaybeUninit_(key); + std::mem::close_MaybeUninit_(value); + assert *key |-> ?dead_key; + assert *value |-> ?dead_val; + end_drop_slot(&(*leaf).keys,key,index); + end_drop_slot(&(*leaf).vals,value,index); + assert *(&(*leaf).keys) |-> ?repacked_keys; + assert *(&(*leaf).vals) |-> ?repacked_vals; + assert Array_elems(repacked_keys) == replace_slot(index,dead_key,keys); + assert Array_elems(repacked_vals) == replace_slot(index,dead_val,vals); + Array_to_array(&(*leaf).keys); + Array_to_array(&(*leaf).vals); + assert (*leaf).keys[..CAPACITY] |-> replace_slot(index,dead_key,keys); + assert (*leaf).vals[..CAPACITY] |-> replace_slot(index,dead_val,vals); + open leaf_header(leaf,parent,parent_idx); + close_points_to(leaf); + end_ref_mut(leaf); + open_points_to(node); + assert (*node).keys[..CAPACITY] |-> replace_slot(index,dead_key,keys); + assert (*node).vals[..CAPACITY] |-> replace_slot(index,dead_val,vals); + close leaf_header(node,parent,parent_idx); + close leaf_slots(node,len,_,_); + take_after_replacing_cell(keys,len,index,dead_key); + take_after_replacing_cell(vals,len,index,dead_val); +} +@*/ + +impl Handle,marker::KV> { +// SOURCE unsafe fn drop_key_val_step(mut self) +} + +impl Handle,marker::KV> { +// SOURCE unsafe fn new_dying_kv(node: NodeRef, idx: usize) -> Self +} + +// SOURCE unsafe fn drop_at( + +// SOURCE unsafe fn drop_remaining( + +/*@ pred resume_phase(inside_value: bool) = true; @*/ + +// SOURCE unsafe fn finish_drop_value(value: *mut MaybeUninit, pending: bool) + +// SOURCE unsafe fn resume_drop_remaining( + + +use std::num::NonZero; + +impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { +// SOURCE unsafe fn split_leaf_data<'short, 'dst>(&'short mut self, new_node: &'dst mut LeafNode) -> (K, V) +} + +impl NodeRef { +// SOURCE unsafe fn from_new_leaf(leaf: Box, A>) -> Self +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { +// SOURCE unsafe fn split_production_leaf( +} + +impl NodeRef { +// SOURCE unsafe fn from_new_internal( +} + +// The two half permissions describe the same cells. Their agreement +// carries the element list through the enclosing Box value. +/*@ +lem close_known_array(p: *[T; N]) + req (p as *T)[..int_of_const(typeid(N))] |-> ?values; + ens *p |-> ?value &*& Array_elems(value) == values; +{ + let base = p as *T; + close_points_to(p, 1/2); + assert [1/2](*p |-> ?value); + Array_to_array(p); + merge_fractions array(base, int_of_const(typeid(N)), _); + assert Array_elems(value) == values; + close_points_to(p); +} +@*/ + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { +// SOURCE unsafe fn split_production_internal( +} + +impl NodeRef { +// SOURCE unsafe fn borrow_mut<'b>(&'b mut self) -> NodeRef, K, V, Type> +} + +// SOURCE unsafe fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight) + +impl Handle, marker::Edge> { +// SOURCE unsafe fn new_edge(node: NodeRef, idx: usize) -> Self +} + +impl Handle, marker::KV> { +// SOURCE unsafe fn new_kv(node: NodeRef, idx: usize) -> Self +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { +// SOURCE unsafe fn insert_fit_production<'short>(&'short mut self, key: K, val: V, edge: Root) +} + +/*@ +fix insert_item(items: list, at: usize, item: T) -> list { + append(take(at, items), cons(item, drop(at, items))) +} + +lem insert_item_across_split(items: list, cut: usize, at: usize, item: T) + req 0 <= cut &*& cut <= length(items) &*& 0 <= at &*& at <= length(items); + ens insert_item(items, at, item) == if at <= cut { + append(insert_item(take(cut, items), at, item), drop(cut, items)) + } else { + append(take(cut, items), insert_item(drop(cut, items), at - cut, item)) + }; +{ + if at <= cut { + take_twice(items, at, cut); + take_after_drop(items, at, cut - at); + drop_twice(cut - at, at, items); + append_take_drop_n(drop(at, items), cut - at); + append_assoc(take(at, items), cons(item, drop(at, take(cut, items))), drop(cut, items)); + } else { + length_take(cut, items); + append_take_drop_n(items, cut); + take_append(at, take(cut, items), drop(cut, items)); + drop_twice(at - cut, cut, items); + append_assoc(take(cut, items), take(at - cut, drop(cut, items)), cons(item, drop(at, items))); + } +} +@*/ + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { +// SOURCE unsafe fn insert_production( +} + +impl<'tree, K: 'tree, V: 'tree> Handle, K, V, marker::Internal>, marker::Edge> { +// SOURCE unsafe fn insert(self, key: K, val: V, edge: Root, alloc: A) +} + +impl Handle, marker::Edge> { + unsafe fn new_edge(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx <= len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx <= node.merge_len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} + +impl Handle, marker::KV> { + unsafe fn new_kv(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx < len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx < node.merge_len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { +// SOURCE unsafe fn insert_fit_leaf_production(mut self, key: K, val: V) +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { +// SOURCE unsafe fn insert_leaf_production(mut self, key: K, val: V, alloc: A) -> ( +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { +// SOURCE unsafe fn insert( +} + +impl NodeRef { +// SOURCE unsafe fn new_internal_production(child: Root, alloc: A) -> Self +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn push_production<'short>(&'short mut self, key: K, val: V, edge: Root) +} + +// SOURCE unsafe fn install_root_split<'tree, 'slot, K, V, A: AllocatorClone>( + +// SOURCE unsafe fn write_child_backlink( + +// The production iterator is specialized to the two range types used by its +// callers. The invariant preserves the edge slots and separates the repaired +// prefix from the pending suffix. + +// BEGIN_NODE_LEN +impl NodeRef { +// SOURCE unsafe fn relink_len(&self) -> usize +} +// END_NODE_LEN + +// BEGIN_NODE_REBORROW +impl NodeRef { +// SOURCE unsafe fn relink_reborrow<'b>(&'b mut self) -> NodeRef, K, V, Type> +} +// END_NODE_REBORROW + +// BEGIN_NEW_EDGE +impl Handle, marker::Edge> { +// SOURCE unsafe fn new_relink_edge(node: NodeRef, idx: usize) -> Self +} +// END_NEW_EDGE + +// The generator binds the read and the two stores to descend and set_parent_link. +impl<'a, K, V> Handle, K, V, marker::Internal>, marker::Edge> { +// SOURCE unsafe fn correct_parent_link(self) +} + +// BEGIN_RELINK_STEP +// SOURCE unsafe fn repair_one__VeriFast_wrapper<'a, 'b, K, V>( + +// END_RELINK_STEP + + + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn relink_range<'b>(&'b mut self, range: std::ops::Range) +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn relink_inclusive<'b>(&'b mut self, range: std::ops::RangeInclusive) +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { +// SOURCE unsafe fn correct_all_childrens_parent_links<'b>(&'b mut self) +} +use std::{alloc::Global, boxed::Box, mem::ManuallyDrop}; + +pub struct BTreeMap< + K, + V, + A: AllocatorClone = Global, +> { + root: Option>, + length: usize, + /// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes). + // Although some of the accessory types store a copy of the allocator, the nodes do not. + // Because allocations will remain live as long as any copy (like this one) of the allocator + // is live, it's unnecessary to store the allocator in each node. + alloc: ManuallyDrop, + // For dropck; the `Box` avoids making the `Unpin` impl more strict than before + _marker: PhantomData>, +} + +pub struct CursorMutKey< + 'a, + K: 'a, + V: 'a, + A = Global, +> { + // If current is None then it means the tree has not been allocated yet. + current: Option, K, V, marker::Leaf>, marker::Edge>>, + root: DormantMutRef<'a, Option>>, + length: &'a mut usize, + alloc: &'a mut A, +} + +pub struct VacantEntry< + 'a, + K, + V, + A: AllocatorClone = Global, +> { + key: K, + /// `None` for a (empty) map without root + handle: Option, K, V, marker::Leaf>, marker::Edge>>, + dormant_map: DormantMutRef<'a, BTreeMap>, + + /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`. + alloc: A, + + // Be invariant in `K` and `V` + _marker: PhantomData<&'a mut (K, V)>, +} + +type RootInputs<'a, K, V, A> = (&'a mut Root, A, K, V, Root); + +impl<'a, K, V, A: AllocatorClone> CursorMutKey<'a, K, V, A> { + fn project_root_inputs_0( + &mut self, split: Option>, + ) -> Option> { + let capture = &mut self.root; + let alloc = &*self.alloc; + match split { + None => None, + Some(ins) => { + drop(ins.left); + let root = unsafe { capture.reborrow().as_mut().unwrap() }; + let inputs = (root, alloc.clone(), ins.kv.0, ins.kv.1, ins.right); + Some(inputs) + } + } + } +} + +impl<'a, K, V, A: AllocatorClone> CursorMutKey<'a, K, V, A> { + fn project_root_inputs_1( + &mut self, split: Option>, + ) -> Option> { + let capture = &mut self.root; + let alloc = &*self.alloc; + match split { + None => None, + Some(ins) => { + drop(ins.left); + let root = unsafe { capture.reborrow().as_mut().unwrap() }; + let inputs = (root, alloc.clone(), ins.kv.0, ins.kv.1, ins.right); + Some(inputs) + } + } + } +} + +impl<'a, K, V, A: AllocatorClone> VacantEntry<'a, K, V, A> { + fn project_root_inputs_0( + &mut self, split: Option>, + ) -> Option> { + let capture = &mut self.dormant_map; + let alloc = &self.alloc; + match split { + None => None, + Some(ins) => { + drop(ins.left); + let map = unsafe { capture.reborrow() }; + let root = map.root.as_mut().unwrap(); + let inputs = (root, alloc.clone(), ins.kv.0, ins.kv.1, ins.right); + Some(inputs) + } + } + } +} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verified/relink.rs b/verifast-proofs/alloc/collections/btree/node.rs/verified/relink.rs new file mode 100644 index 0000000000000..cefa5edbcd9d5 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verified/relink.rs @@ -0,0 +1,723 @@ +//! Ancestor ownership and the key, value, and child moves used during splitting. +//! Refinement checks the production `as_leaf_ptr` and `set_parent_link`. + +#![allow(dead_code)] + +use std::marker::PhantomData; +use std::mem::MaybeUninit; +use std::ptr::NonNull; + +//@ use std::mem::{MaybeUninit, open_MaybeUninit, close_MaybeUninit}; +//@ use std::option::Option; +//@ use std::ptr::NonNull; + +const B: usize = 6; + +const CAPACITY: usize = 2 * B - 1; + +//@ fix B() -> usize { 6 } + +//@ fix CAPACITY() -> usize { 2 * B - 1 } + +struct LeafNode { + /// We want to be covariant in `K` and `V`. + parent: Option>>, + + /// This node's index into the parent node's `edges` array. + /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`. + /// This is only guaranteed to be initialized when `parent` is non-null. + parent_idx: MaybeUninit, + + /// The number of keys and values this node stores. + len: u16, + + /// The arrays storing the actual data of the node. Only the first `len` elements of each + /// array are initialized and valid. + keys: [MaybeUninit; CAPACITY], + vals: [MaybeUninit; CAPACITY], +} + +#[repr(C)] +struct InternalNode { + data: LeafNode, + + /// The pointers to the children of this node. `len + 1` of these are considered + /// initialized and valid, except that near the end, while the tree is held + /// through borrow type `Dying`, some of these pointers are dangling. + edges: [MaybeUninit>; 2 * B], +} + +type BoxedNode = NonNull>; + +struct NodeRef { + /// The number of levels that the node and the level of leaves are apart, a + /// constant of the node that cannot be entirely described by `Type`, and that + /// the node itself does not store. We only need to store the height of the root + /// node, and derive every other node's height from it. + /// Must be zero if `Type` is `Leaf` and non-zero if `Type` is `Internal`. + height: usize, + /// The pointer to the leaf or internal node. The definition of `InternalNode` + /// ensures that the pointer is valid either way. + node: NonNull>, + _marker: PhantomData<(BorrowType, Type)>, +} + +mod marker { + use super::PhantomData; + pub(crate) struct Mut<'a>(PhantomData<&'a mut ()>); + pub(crate) enum LeafOrInternal {} + pub(crate) enum DormantMut {} + pub(crate) enum Owned {} + pub(crate) enum Leaf {} + pub(crate) enum Internal {} + pub(crate) enum KV {} + pub(crate) enum Edge {} +} + +// BEGIN_ANCESTOR_PROOF +/*@ +// Keep exact ancestor storage, including inactive slots that must stay unchanged. +inductive ParentPayload = ParentPayload( + list>, list>, list>>> +); +inductive ParentStep = ParentStep(*InternalNode, u16, u16, ParentPayload); + +pred link(child: *LeafNode, parent: Option>>, index: u16;) = + (*child).parent |-> parent &*& + if parent == Option::None { + index == 0 + } else { + (*child).parent_idx |-> MaybeUninit::new(index) + }; + +pred parent_payload( + child: *LeafNode, parent: *InternalNode, index: u16, len: u16, payload: ParentPayload; +) = + parent != 0 &*& pointer_within_limits(parent) == true &*& pointer_within_limits(&(*parent).data) == true &*& + 0 <= index &*& index <= len &*& len <= CAPACITY &*& + match payload { + ParentPayload(keys, vals, edges) => + (*parent).data.len |-> len &*& + (*parent).data.keys[..CAPACITY] |-> keys &*& + (*parent).data.vals[..CAPACITY] |-> vals &*& + (*parent).edges[..CAPACITY + 1] |-> edges &*& + nth(index, edges) == MaybeUninit::new(NonNull::new(child)) + }; + +pred ancestors(child: *LeafNode, path: list>, root: *LeafNode;) = + match path { + nil => child == root &*& link(child, Option::None, 0), + cons(step, rest) => + match step { + ParentStep(parent, idx, len, payload) => + link(child, Option::Some(NonNull::new(parent)), idx) &*& + parent_payload(child, parent, idx, len, payload) &*& + ancestors(&(*parent).data, rest, root) + } + }; + +@*/ + +// The raw-pointer form uses the exact two stores extracted from the NodeRef method. +unsafe fn write_child_backlink( + leaf: *mut LeafNode, + parent: NonNull>, + parent_idx: usize, +) +//@ req thread_token(?t) &*& (*leaf).parent |-> _ &*& (*leaf).parent_idx |-> _ &*& parent_idx <= CAPACITY; +//@ ens thread_token(t) &*& (*leaf).parent |-> Option::Some(parent) &*& (*leaf).parent_idx |-> MaybeUninit::new(parent_idx as u16); +//@ on_unwind_ens false; +{ + unsafe { (*leaf).parent = Some(parent) }; + //@ open LeafNode_parent_idx_(leaf, _); + //@ points_to__limits(&(*leaf).parent_idx); + unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; +} + +/*@ +pred child_headers(children: list>>;) = + match children { + nil => true, + cons(child, rest) => + (*child.as_ptr()).parent |-> _ &*& (*child.as_ptr()).parent_idx |-> _ &*& child_headers(rest) + }; + +pred linked_headers(children: list>>, parent: NonNull>, index: usize;) = + match children { + nil => true, + cons(child, rest) => + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new(index as u16) &*& + linked_headers(rest, parent, index + 1) + }; + +lem append_linked_header(prefix: list>>, child: NonNull>, parent: NonNull>, first: usize) + req linked_headers(prefix, parent, first) &*& + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new((first + length(prefix)) as u16); + ens linked_headers(append(prefix, [child]), parent, first); +{ + open linked_headers(prefix, parent, first); + match prefix { + nil => { close linked_headers([], parent, first + 1); } + cons(old, rest) => { append_linked_header(rest, child, parent, first + 1); } + } + close linked_headers(append(prefix, [child]), parent, first); +} + +fix initialized_edges(children: list>>) -> list>>> { + match children { + nil => nil, + cons(child, rest) => cons(MaybeUninit::new(child), initialized_edges(rest)) + } +} + +lem initialized_edges_append(a: list>>, b: list>>) + req true; + ens initialized_edges(append(a, b)) == append(initialized_edges(a), initialized_edges(b)); +{ + match a { + nil => {} + cons(child, rest) => { initialized_edges_append(rest, b); } + } +} + +lem initialized_edge_count(children: list>>) + req true; + ens length(initialized_edges(children)) == length(children); +{ + match children { + nil => {} + cons(child, rest) => { initialized_edge_count(rest); } + } +} + +lem empty_list_if_zero(items: list) + req length(items) == 0; + ens items == []; +{ + match items { + nil => {} + cons(item, more) => {} + } +} + +lem unpack_nonempty(items: list) + req length(items) > 0; + ens items == cons(?item, ?more); +{ + match items { nil => {} cons(item, more) => {} } +} +@*/ + +unsafe fn repair_edges(parent: NonNull>, start: usize, end: usize) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + start <= end &*& end <= CAPACITY + 1 &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + (*parent.as_ptr()).edges[start..end] |-> ?bits &*& child_headers(?children) &*& + bits == initialized_edges(children) &*& length(children) == end - start; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + (*parent.as_ptr()).edges[start..end] |-> initialized_edges(children) &*& + linked_headers(children, parent, start); +@*/ +//@ on_unwind_ens false; +{ + let parent_ptr = parent.as_ptr(); + let base = unsafe { (&raw const (*parent_ptr).edges) as *const MaybeUninit> }; + let mut i = start; + //@ close array(base + start, 0, []); + //@ close linked_headers([], parent, start); + loop { + /*@ + inv thread_token(t) &*& lifetime_token(func_lft) &*& type_interp::() &*& type_interp::() &*& + start <= i &*& i <= end &*& end <= CAPACITY + 1 &*& + (*parent_ptr).edges[start..i] |-> ?prefix_bits &*& + (*parent_ptr).edges[i..end] |-> ?rest_bits &*& + linked_headers(?prefix, parent, start) &*& child_headers(?rest) &*& + prefix_bits == initialized_edges(prefix) &*& rest_bits == initialized_edges(rest) &*& + children == append(prefix, rest) &*& length(prefix) == i - start &*& length(rest) == end - i; + @*/ + if i == end { + break; + } + //@ unpack_nonempty(rest); + //@ assert rest == cons(?child, ?remaining); + //@ open array(base + i, end - i, initialized_edges(rest)); + //@ open_MaybeUninit(base + i); + let edge = unsafe { *(base.add(i) as *const NonNull>) }; + //@ close_MaybeUninit(base + i); + //@ close array(base + i + 1, 0, []); + //@ close array(base + i, 1, initialized_edges([child])); + //@ open child_headers(rest); + unsafe { write_child_backlink(edge.as_ptr(), parent, i) }; + //@ append_linked_header(prefix, child, parent, start); + //@ array_join(base + start); + //@ initialized_edges_append(prefix, [child]); + //@ append_assoc(prefix, [child], remaining); + i += 1; + } + //@ assert child_headers(?unrepaired); + //@ assert linked_headers(?repaired, parent, start); + //@ empty_list_if_zero(unrepaired); + //@ append_nil(repaired); + //@ open child_headers(unrepaired); + //@ array_join(base + start); +} + +unsafe fn move_split_edges( + left: NonNull>, + right: NonNull>, + pivot: usize, + old_len: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& pivot < old_len &*& old_len <= CAPACITY &*& + pointer_within_limits(&(*left.as_ptr()).edges) == true &*& + pointer_within_limits(&(*right.as_ptr()).edges) == true &*& + (*left.as_ptr()).edges[pivot + 1..old_len + 1] |-> ?edges &*& + (*right.as_ptr()).edges[..old_len - pivot] |-> _ &*& + child_headers(?children) &*& edges == initialized_edges(children) &*& length(children) == old_len - pivot; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + (*left.as_ptr()).edges[pivot + 1..old_len + 1] |-> edges &*& + (*right.as_ptr()).edges[..old_len - pivot] |-> edges &*& linked_headers(children, right, 0); +@*/ +//@ on_unwind_ens false; +{ + let src = unsafe { (&raw const (*left.as_ptr()).edges) as *const MaybeUninit> }; + let dst = unsafe { (&raw mut (*right.as_ptr()).edges) as *mut MaybeUninit> }; + unsafe { std::ptr::copy_nonoverlapping(src.add(pivot + 1), dst, old_len - pivot) }; + unsafe { repair_edges(right, 0, old_len - pivot) }; +} + +// Match the storage effects of moving the key, value, and edge suffixes. A +// separate Kani contract checks the pivot read in the native split_leaf_data. +unsafe fn split_preserves_ancestors( + left: NonNull>, + right: NonNull>, + pivot: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + ancestors(&(*left.as_ptr()).data, ?path, ?root) &*& link(&(*right.as_ptr()).data, Option::None, 0) &*& + (*left.as_ptr()).data.len |-> ?old_len &*& (*right.as_ptr()).data.len |-> 0 &*& pivot < old_len &*& old_len <= CAPACITY &*& + pointer_within_limits(&(*left.as_ptr()).edges) == true &*& + pointer_within_limits(&(*right.as_ptr()).edges) == true &*& + (*left.as_ptr()).edges[pivot + 1..old_len + 1] |-> ?edges &*& + (*right.as_ptr()).edges[..old_len - pivot] |-> _ &*& + child_headers(?children) &*& edges == initialized_edges(children) &*& length(children) == old_len - pivot &*& + pointer_within_limits(&(*left.as_ptr()).data.keys) == true &*& + pointer_within_limits(&(*left.as_ptr()).data.vals) == true &*& + pointer_within_limits(&(*right.as_ptr()).data.keys) == true &*& + pointer_within_limits(&(*right.as_ptr()).data.vals) == true &*& + (*left.as_ptr()).data.keys[pivot + 1..old_len] |-> ?keys &*& + (*left.as_ptr()).data.vals[pivot + 1..old_len] |-> ?vals &*& + (*right.as_ptr()).data.keys[..old_len - pivot - 1] |-> _ &*& + (*right.as_ptr()).data.vals[..old_len - pivot - 1] |-> _; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + ancestors(&(*left.as_ptr()).data, path, root) &*& link(&(*right.as_ptr()).data, Option::None, 0) &*& + (*left.as_ptr()).data.len |-> (pivot as u16) &*& (*right.as_ptr()).data.len |-> ((old_len - pivot - 1) as u16) &*& + (*left.as_ptr()).edges[pivot + 1..old_len + 1] |-> edges &*& + (*right.as_ptr()).edges[..old_len - pivot] |-> edges &*& linked_headers(children, right, 0) &*& + (*left.as_ptr()).data.keys[pivot + 1..old_len] |-> keys &*& + (*left.as_ptr()).data.vals[pivot + 1..old_len] |-> vals &*& + (*right.as_ptr()).data.keys[..old_len - pivot - 1] |-> keys &*& + (*right.as_ptr()).data.vals[..old_len - pivot - 1] |-> vals; +@*/ +//@ on_unwind_ens false; +{ + let src = left.as_ptr(); + let dst = right.as_ptr(); + let len = unsafe { (*src).data.len } as usize; + let new_len = len - pivot - 1; + unsafe { + (*dst).data.len = new_len as u16; + let src_keys = ((&raw const (*src).data.keys) as *const MaybeUninit); + let src_vals = ((&raw const (*src).data.vals) as *const MaybeUninit); + let dst_keys = ((&raw mut (*dst).data.keys) as *mut MaybeUninit); + let dst_vals = ((&raw mut (*dst).data.vals) as *mut MaybeUninit); + std::ptr::copy_nonoverlapping(src_keys.add(pivot + 1), dst_keys, new_len); + std::ptr::copy_nonoverlapping(src_vals.add(pivot + 1), dst_vals, new_len); + (*src).data.len = pivot as u16; + move_split_edges(left, right, pivot, len); + } +} + +// BEGIN_BACKLINK_METHODS +impl NodeRef { + unsafe fn as_leaf_ptr(this: &Self) -> *mut LeafNode +/*@ + req [?f](*this |-> ?node_ref); + @*/ + /*@ + ens [f](*this |-> node_ref) &*& result == node_ref.node.as_ptr(); + @*/ + //@ on_unwind_ens false; + { + //@ open_points_to(this); + let ptr = this.node.as_ptr(); + //@ close_points_to(this, f); + ptr + } +} + +impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { + unsafe fn set_parent_link(&mut self, parent: NonNull>, parent_idx: usize) + //@ req *self |-> ?node_ref &*& (*node_ref.node.as_ptr()).parent |-> _ &*& (*node_ref.node.as_ptr()).parent_idx |-> _ &*& parent_idx <= CAPACITY; + //@ ens *self |-> node_ref &*& (*node_ref.node.as_ptr()).parent |-> Option::Some(parent) &*& (*node_ref.node.as_ptr()).parent_idx |-> MaybeUninit::new(parent_idx as u16); + //@ on_unwind_ens false; + { + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + let leaf = unsafe { Self::as_leaf_ptr(self) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self, _); + unsafe { (*leaf).parent = Some(parent) }; + //@ open LeafNode_parent_idx_(leaf, _); + //@ points_to__limits(&(*leaf).parent_idx); + unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; + } +} + +// END_BACKLINK_METHODS + +struct Handle { + node: Node, + idx: usize, + _marker: PhantomData, +} + +// The production iterator is specialized to the two range types used by its +// callers. The invariant preserves the edge slots and separates the repaired +// prefix from the pending suffix. + +// BEGIN_NODE_LEN +impl NodeRef { + unsafe fn len(&self) -> usize + //@ req [?f](*self |-> ?node) &*& [?ql]((*node.node.as_ptr()).len |-> ?len); + //@ ens [f](*self |-> node) &*& [ql]((*node.node.as_ptr()).len |-> len) &*& result == len; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let ptr = self.node.as_ptr(); + //@ close_points_to(self, f); + unsafe { (*ptr).len as usize } + } +} +// END_NODE_LEN + +// BEGIN_NODE_REBORROW +impl NodeRef { + unsafe fn reborrow_mut<'b>(&'b mut self) -> NodeRef, K, V, Type> + //@ req *self |-> ?node; + //@ ens *self |-> node &*& result.node == node.node &*& result.height == node.height; + //@ on_unwind_ens false; + { + //@ open_points_to(self); + let borrowed = NodeRef { height: self.height, node: self.node, _marker: PhantomData }; + //@ close_points_to(self); + borrowed + } +} +// END_NODE_REBORROW + +// BEGIN_NEW_EDGE +impl Handle, marker::Edge> { + unsafe fn new_edge(node: NodeRef, idx: usize) -> Self + //@ req (*node.node.as_ptr()).len |-> ?len &*& idx <= len; + //@ ens result.node == node &*& result.idx == idx &*& (*node.node.as_ptr()).len |-> len; + //@ on_unwind_ens false; + { + unsafe { debug_assert!(idx <= node.len()) }; + let edge = Handle { node, idx, _marker: PhantomData }; + //@ close_points_to(&node, 1/2); + edge + } +} +// END_NEW_EDGE + +// The generator binds the read and the two stores to descend and set_parent_link. +impl<'a, K, V> Handle, K, V, marker::Internal>, marker::Edge> { + unsafe fn correct_parent_link(self) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + 0 < self.node.height &*& self.node.height <= usize::MAX &*& 0 <= self.idx &*& self.idx <= CAPACITY &*& + exists::>>(?parent) &*& self.node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + exists::>(?child) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + nth(self.idx, edges) == MaybeUninit::new(child) &*& + (*child.as_ptr()).parent |-> _ &*& (*child.as_ptr()).parent_idx |-> _; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new(self.idx as u16); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(child); + //@ std::ptr::NonNull_new_as_ptr(parent); + let parent_ptr = self.node.node.as_ptr() as *mut InternalNode; + let parent_link = unsafe { NonNull::new_unchecked(parent_ptr) }; + //@ std::ptr::NonNull_new_as_ptr(parent_link); + // BEGIN_RAW_EDGE_READ + //@ let array = &(*parent_ptr).edges; + //@ close_points_to(array); + //@ let view = precreate_ref(array); + //@ init_ref_readonly(view, 1/2); + //@ open_points_to(view); + //@ let base = view as *MaybeUninit>; + //@ array_inv::>>(); + //@ array_split(base, self.idx); + //@ array_split(base + self.idx, 1); + //@ nth_drop(0, self.idx, edges); + //@ open [1/2]array(base + self.idx, 1, _); + //@ open [1/2]array(base + self.idx + 1, 0, _); + //@ let slot = precreate_ref(base + self.idx); + //@ init_ref_readonly(slot, 1/2); + let edge = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() }; + //@ end_ref_readonly(slot); + //@ merge_fractions points_to(base + self.idx, _); + //@ close [1/2]array(base + self.idx, 1, [MaybeUninit::new(child)]); + //@ array_join(base + self.idx); + //@ array_join(base); + //@ close_points_to(view, 1/2); + //@ end_ref_readonly(view); + //@ merge_fractions points_to(array, _); + //@ open_points_to(array); + // END_RAW_EDGE_READ + let _child_height = self.node.height - 1; + unsafe { write_child_backlink(edge.as_ptr(), parent_link, self.idx) }; + } +} + +// BEGIN_RELINK_STEP +unsafe fn repair_one__VeriFast_wrapper<'a, 'b, K, V>( + node: &'b mut NodeRef, K, V, marker::Internal>, + i: usize, +) +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *node |-> ?original &*& 0 < original.height &*& original.height <= usize::MAX &*& + (*original.node.as_ptr()).len |-> ?len &*& 0 <= i &*& i <= len &*& len <= CAPACITY &*& + exists::>>(?parent) &*& original.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& exists::>(?child) &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& nth(i, edges) == MaybeUninit::new(child) &*& + (*child.as_ptr()).parent |-> _ &*& (*child.as_ptr()).parent_idx |-> _; +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *node |-> original &*& (*original.node.as_ptr()).len |-> len &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + (*child.as_ptr()).parent |-> Option::Some(parent) &*& + (*child.as_ptr()).parent_idx |-> MaybeUninit::new(i as u16); +@*/ +//@ on_unwind_ens false; +{ + //@ open exists(parent); + //@ open exists(child); + //@ close exists(parent); + //@ close exists(child); + unsafe { Handle::new_edge/*@::,K,V,marker::Internal>@*/( + node.reborrow_mut/*@::,K,V,marker::Internal,'b>@*/(), i + ).correct_parent_link/*@::<'b,K,V>@*/() }; +} + +// END_RELINK_STEP + + + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn relink_range<'b>(&'b mut self, range: std::ops::Range) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + (*node.node.as_ptr()).len |-> ?len &*& len <= CAPACITY &*& + 0 <= range.start &*& range.start <= range.end &*& range.end <= len + 1 &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + child_headers(?children) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + exists::>>, list>>>>(pair(?before, ?after)) &*& + length(before) == range.start &*& + edges == append(before, append(initialized_edges(children), after)) &*& + length(children) == range.end - range.start; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + linked_headers(children, parent, range.start); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(pair(before, after)); + let mut iter = range.into_iter(); + //@ let first = range.start; + //@ let end = range.end; + //@ close linked_headers([], parent, first); + loop { + /*@ + inv iter |-> ?state &*& state.end == end &*& + thread_token(t) &*& lifetime_token(func_lft) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + first <= state.start &*& state.start <= end &*& + linked_headers(?prefix, parent, first) &*& child_headers(?rest) &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + children == append(prefix, rest) &*& length(prefix) == state.start - first &*& length(rest) == end - state.start; + @*/ + let iter_ref = &mut iter; + let next = iter_ref.next(); + match next { + None => break, + Some(i) => { + //@ unpack_nonempty(rest); + //@ assert rest == cons(?child, ?remaining); + //@ initialized_edge_count(prefix); + //@ initialized_edge_count(rest); + //@ initialized_edges_append(prefix, rest); + //@ length_append(initialized_edges(prefix), initialized_edges(rest)); + //@ length_append(initialized_edges(children), after); + //@ nth_append_r(before, append(initialized_edges(children), after), i - first); + //@ nth_append(initialized_edges(children), after, i - first); + //@ nth_append_r(initialized_edges(prefix), initialized_edges(rest), 0); + //@ open child_headers(rest); + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + unsafe { debug_assert!(i <= self.len()) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self,_); + //@ close exists(parent); + //@ close exists(child); + unsafe { repair_one__VeriFast_wrapper/*@::@*/(self, i) }; + //@ append_linked_header(prefix, child, parent, first); + //@ append_assoc(prefix, [child], remaining); + } + } + } + //@ assert child_headers(?unrepaired); + //@ assert linked_headers(?repaired, parent, first); + //@ empty_list_if_zero(unrepaired); + //@ append_nil(repaired); + //@ open child_headers(unrepaired); + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn relink_inclusive<'b>(&'b mut self, range: std::ops::RangeInclusive) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + (*node.node.as_ptr()).len |-> ?len &*& len <= CAPACITY &*& + range.exhausted == false &*& 0 <= range.start &*& range.start <= (range.end + 1) &*& (range.end + 1) <= len + 1 &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + child_headers(?children) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + exists::>>, list>>>>(pair(?before, ?after)) &*& + length(before) == range.start &*& + edges == append(before, append(initialized_edges(children), after)) &*& + length(children) == (range.end + 1) - range.start; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + linked_headers(children, parent, range.start); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(pair(before, after)); + let mut iter = range.into_iter(); + //@ let first = range.start; + //@ let end = (range.end + 1); + //@ close linked_headers([], parent, first); + loop { + /*@ + inv iter |-> ?state &*& state.end + 1 == end &*& state.exhausted == false &*& + thread_token(t) &*& lifetime_token(func_lft) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> len &*& + first <= state.start &*& state.start <= end &*& + linked_headers(?prefix, parent, first) &*& child_headers(?rest) &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& + children == append(prefix, rest) &*& length(prefix) == state.start - first &*& length(rest) == end - state.start; + @*/ + let iter_ref = &mut iter; + let next = iter_ref.next(); + match next { + None => break, + Some(i) => { + //@ unpack_nonempty(rest); + //@ assert rest == cons(?child, ?remaining); + //@ initialized_edge_count(prefix); + //@ initialized_edge_count(rest); + //@ initialized_edges_append(prefix, rest); + //@ length_append(initialized_edges(prefix), initialized_edges(rest)); + //@ length_append(initialized_edges(children), after); + //@ nth_append_r(before, append(initialized_edges(children), after), i - first); + //@ nth_append(initialized_edges(children), after, i - first); + //@ nth_append_r(initialized_edges(prefix), initialized_edges(rest), 0); + //@ open child_headers(rest); + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + unsafe { debug_assert!(i <= self.len()) }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self,_); + //@ close exists(parent); + //@ close exists(child); + unsafe { repair_one__VeriFast_wrapper/*@::@*/(self, i) }; + //@ append_linked_header(prefix, child, parent, first); + //@ append_assoc(prefix, [child], remaining); + } + } + } + //@ assert child_headers(?unrepaired); + //@ assert linked_headers(?repaired, parent, first); + //@ empty_list_if_zero(unrepaired); + //@ append_nil(repaired); + //@ open child_headers(unrepaired); + } +} + +impl<'a, K, V> NodeRef, K, V, marker::Internal> { + unsafe fn relink_all<'b>(&'b mut self) + /*@ + req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& + *self |-> ?node &*& 0 < node.height &*& node.height <= usize::MAX &*& + exists::>>(?parent) &*& node.node.as_ptr() as *InternalNode == parent.as_ptr() &*& + (*node.node.as_ptr()).len |-> ?occupancy &*& occupancy <= CAPACITY &*& + pointer_within_limits(&(*parent.as_ptr()).edges) == true &*& + child_headers(?children) &*& (*parent.as_ptr()).edges[..CAPACITY + 1] |-> ?edges &*& + exists::>>>(?tail) &*& + edges == append(initialized_edges(children), tail) &*& length(children) == occupancy + 1; + @*/ + /*@ + ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& + *self |-> node &*& (*node.node.as_ptr()).len |-> occupancy &*& + (*parent.as_ptr()).edges[..CAPACITY + 1] |-> edges &*& linked_headers(children, parent, 0); + @*/ + //@ on_unwind_ens false; + { + //@ open exists(parent); + //@ open exists(tail); + //@ let view = precreate_ref(self); + //@ init_ref_readonly(view, 1/2); + let len = unsafe { self.len() }; + //@ end_ref_readonly(view); + //@ merge_fractions points_to(self, _); + //@ close exists(parent); + //@ let prefix = nil::>>; + //@ close exists(pair(prefix, tail)); + unsafe { self.relink_inclusive/*@::<'a,K,V,'b>@*/(0..=len) }; + } +} + +fn main() {} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verified/root_replace.rs b/verifast-proofs/alloc/collections/btree/node.rs/verified/root_replace.rs new file mode 100644 index 0000000000000..e0680b2a40074 --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verified/root_replace.rs @@ -0,0 +1,48 @@ +//! Ownership transfer inside the guarded root replacement in `btree::mem`. + +#![allow(dead_code)] + +use std::ptr; + +struct PanicGuard; + +//@ pred .own(t, guard) = true; + +impl Drop for PanicGuard { + fn drop(&mut self) + //@ req true; + //@ ens false; + //@ on_unwind_ens false; + { + // The source intrinsic and the pinned toolchain's process abort + // both terminate without unwinding. + std::process::abort() + } +} + +// Verify the replacement transfer with the callback's ownership contract. +// The MIR comparison wraps this core with the checked aborting destructor +// and checks the guard's lifetime against btree::mem::replace. +unsafe fn replace_core (T, R)>(v: &mut T, change: F) -> R +/*@ +req thread_token(?t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + *v |-> ?old &*& .own(t,old) &*& .own(t,change); +@*/ +/*@ +ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + *v |-> ?new &*& .own(t,new) &*& .own(t,result); +@*/ +//@ on_unwind_ens thread_token(t) &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& *v |-> old; +{ + let value = unsafe { ptr::read(v) }; + //@ close_tuple_1_own(t, std_tuple_1_:: { 0: old }); + let (new_value, ret) = change(value); + //@ assert <(T,R)>.own(t,?replacement); + //@ open_tuple_2_own(t,replacement); + unsafe { + ptr::write(v, new_value); + } + ret +} + +fn main() {} diff --git a/verifast-proofs/alloc/collections/btree/node.rs/verify.sh b/verifast-proofs/alloc/collections/btree/node.rs/verify.sh new file mode 100644 index 0000000000000..a434d8a1c514d --- /dev/null +++ b/verifast-proofs/alloc/collections/btree/node.rs/verify.sh @@ -0,0 +1,749 @@ +#!/bin/bash + +set -euo pipefail + +cd "$(dirname "$0")" +proof_dir=$PWD +library=$(cd ../../../../../library && pwd) +work_dir=$(mktemp -d) +work_dir=$(cd "$work_dir" && pwd) +trap 'rm -rf -- "$work_dir"' EXIT + +if [[ ${1:-} == --ci ]]; then + tool="$work_dir/tool" + mkdir "$tool" + bash verifast-patches/build.sh "$tool" + VERIFAST_HOME="$tool" bash verify.sh + VERIFAST_HOME="$tool" bash verify.sh --negative + exit 0 +fi + +: "${VERIFAST_HOME:?Build the B-tree VeriFast tool with verifast-patches/build.sh}" +verifast_home=$(cd "$VERIFAST_HOME" && pwd) +export LD_LIBRARY_PATH="$verifast_home/bin${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" + +cp -a original verified "$work_dir/" +cd "$work_dir" +# Keep git apply independent of the user's checkout when TMPDIR is inside it. +export GIT_CEILING_DIRECTORIES=$(dirname "$work_dir") + +check_sources() { + local btree="$library/alloc/src/collections/btree" + local source uses + for source in node.rs mem.rs borrow.rs; do + if ! diff -u "$btree/$source" "original/$source"; then + echo "B-tree production snapshot changed: $source" >&2 + return 1 + fi + done + (cd "$library" && sha256sum --quiet --strict -c "$work_dir/original/dependencies.sha256") || return + # The empty-parent branch uses the verifier's literal-panic primitive. + # Its production expansion formats this same static string and panics. + local panic_body + panic_body=$(proof_body 'pub fn unreachable_display<' "$library/core/src/panicking.rs") || return + if [[ $panic_body != ' panic_fmt(format_args!("internal error: entered unreachable code: {}", *x));' ]]; then + echo 'B-tree empty-parent panic expansion changed' >&2 + return 1 + fi + uses=$( + cd "$btree" + LC_ALL=C grep -Rnw --include='*.rs' --exclude=tests.rs --exclude-dir=tests insert_recursing . + ) || return + # assemble_views reads the two cursor callbacks and the vacant-entry + # callback. The remaining occurrence is the production definition. + if [[ $(wc -l <<< "$uses") != 4 ]]; then + echo 'B-tree insert_recursing call sites changed' >&2 + return 1 + fi +} + +# Fill the named function positions with their complete source text. The +# declarations being compared may use different enclosing impls, lifetimes, +# or wrapper calls. The checked-in diffs record those adaptations. +# SOURCE_IN_IMPL disambiguates overloads using the surrounding impl line. +copy_regions() { + local template=$1 + shift + awk ' + FNR == NR { + lines[++size] = $0 + if (/^impl[< ]/) scope = $0 + if ($0 == "}") scope = "" + if (sub(/^\/\/ SOURCE /, "")) { + selections[size] = $0 + } else if (sub(/^\/\/ SOURCE_IN_IMPL /, "")) { + selections[size] = scope SUBSEP $0 + } + if (size in selections) requested[selections[size]] = $0 + next + } + !copying { + if (FNR == 1 || $0 == "}") scope = "" + if (/^impl[< ]/) scope = $0 + signature = ($0 in requested) ? $0 : scope SUBSEP $0 + if (signature in requested) { + match($0, /^ */) + closing = substr($0, 1, RLENGTH) "}" + region[signature] = "" + copying = 1 + } + } + copying { + region[signature] = region[signature] $0 "\n" + if ($0 == closing) { + seen[signature]++ + copying = 0 + } + } + END { + for (name in requested) { + if (seen[name] != 1) { + print "Expected exactly one source region: " requested[name] > "/dev/stderr" + exit 1 + } + } + for (i = 1; i <= size; i++) { + if (i in selections) printf "%s", region[selections[i]] + else print lines[i] + } + } + ' "$template" "$@" +} + +# Use each production callback as the original side of the root comparison. +# Project just the arguments to the final install, whose two operations +# (push_internal_level and push) are compared separately. +project_root_callbacks() { + awk ' + FILENAME != ARGV[3] { + if (!active) { + if (FILENAME == ARGV[1] && + /^ let handle = edge[.]insert_recursing[(]key, value, self[.]alloc[.]clone[(][)], [|]ins[|] [{]$/) { + ++cursors + active = ++count + end = " });" + } else if (FILENAME == ARGV[2] && + /^ Some[(]handle[)] => handle[.]insert_recursing[(]self[.]key, value, self[.]alloc[.]clone[(][)], [|]ins[|] [{]$/) { + ++entries + active = ++count + end = " })," + } + } else if ($0 == end) { + if (!installed) failed = 1 + active = installed = 0 + } else if ($0 ~ /^ +root[.]push_internal_level[(]self[.]alloc[.]clone[(][)][)][.]push[(]ins[.]kv[.]0, ins[.]kv[.]1, ins[.]right[)]$/) { + if (installed) failed = 1 + installed = 1 + callback[active] = callback[active] \ + " (root, self.alloc.clone(), ins.kv.0, ins.kv.1, ins.right)\n" + } else { + if (installed && $0 !~ /^ *(\/\/.*)?$/) failed = 1 + callback[active] = callback[active] $0 "\n" + } + next + } + /^\/\/ ROOT_CALLBACK [1-3]$/ { + ++used[$3] + printf "%s", callback[$3] + next + } + /^pub struct (BTreeMap|CursorMutKey|VacantEntry) "/dev/stderr" + exit 1 + } + } + ' "$1" "$2" "$3" +} + +# Read the executable body of a named function in the annotated proof. +proof_body() { + awk -v signature="$1" ''' + index($0, signature) == 1 { + ++found + match($0, /^ */) + indent = substr($0, 1, RLENGTH) + header = 1 + } + header && ($0 == indent "{" || /^ *[)] ->.* [{]$/ || + (index($0, signature) == 1 && /[{]$/)) { + header = 0 + body = 1 + next + } + body && $0 == indent "}" { body = 0; ++closed; next } + !body { next } + /^[[:space:]]*\/\*@[[:space:]]*$/ { ghost = 1 } + ghost && /^[[:space:]]*@\*\/[[:space:]]*$/ { ghost = 0; next } + ghost || /^[[:space:]]*(\/\/.*)?$/ { next } + { + gsub(/\/\*@::<[^@]*>@\*\//, "") + gsub(/\/\*@~mut@\*\/ /, "") + if (index($0, "/*@")) exit 1 + print substr($0, length(indent) + 1) + } + END { if (found != 1 || closed != 1 || ghost) exit 1 } + ' "$2" +} + + +# Inline the proved entry and handoff in the owning production scope. +# Keep the FnOnce invocation in the root arm. Its three implementations +# are checked through the root projections and the root-install refinement. +compose_insert_recursing() { + local entry clone handoff loop + entry=$(proof_body ' unsafe fn insert_recursing_for_root<' verified/insertion.rs) || return + clone=$(proof_body ' unsafe fn clone_and_insert<' verified/insertion.rs) || return + handoff=$(proof_body 'unsafe fn resume_after_leaf_insert_for_root<' verified/insertion.rs) || return + loop=$(proof_body 'unsafe fn propagate_split_for_root<' verified/insertion.rs) || return + + if [[ "$entry" != ' let initial = unsafe { self.clone_and_insert(key,val,alloc) }; + let result = unsafe { resume_after_leaf_insert_for_root(initial,alloc,root_slot,root_allocator) }; + result' || "$clone" != ' unsafe { self.insert(key, val, alloc.clone()) }' ]]; then + echo 'B-tree proved insertion entry changed' >&2 + return 1 + fi + + printf '%s\n' ' let initial = self.insert(key, value, alloc.clone());' + awk ' + NR == 1 && $0 == " let (pending, inserted) = match initial {" { + print " let (mut split, inserted) = match initial {" + ++binding + next + } + $0 == " let result = unsafe { propagate_split_for_root(pending, inserted, alloc, root_slot, root_allocator) };" { + ++handoff + if ((getline) != 1 || $0 != " result") exit 1 + if ((getline) != 0) exit 1 + next + } + { print } + END { if (binding != 1 || handoff != 1) exit 1 } + ' <<< "$handoff" || return + + awk ' + NR == 1 && $0 == " let mut split = initial_split;" { ++binding; next } + $0 == " return unsafe { finish_root_split(payload, inserted, root_slot, root_allocator) };" { + ++root + print " split_root(payload);" + print " return unsafe { inserted.awaken() };" + next + } + { print } + END { if (binding != 1 || root != 1) exit 1 } + ' <<< "$loop" +} + +# Fold the checked drop steps into the two native guard scopes. The diff +# connects the first and cleanup ranges to drop_remaining, and the value +# destructor to both exits from drop_pair. +collect_drop_bodies() { + local signature + while IFS= read -r signature; do + if [[ $signature == '// body '* ]]; then + printf '%s\n' "$signature" + else + printf '// %s\n' "$signature" + proof_body "$signature" verified/insertion.rs || return + fi + done <<'EOF' +// body drop_kvs +unsafe fn drop_remaining< +unsafe fn drop_at< +unsafe fn duplicate_dying< + unsafe fn new_dying_kv( +unsafe fn resume_drop_remaining< +// body drop_key_val +unsafe fn finish_drop_value< + unsafe fn drop_key_val_step( + unsafe fn project_drop_slots< +unsafe fn drop_pair< +unsafe fn drop_initialized_slot< +unsafe fn drop_guarded_value< + unsafe fn drop_value_guard( +unsafe fn drop_slot_production< +EOF +} + +assemble_verified_operations() { + copy_regions verified/operations.rs.in verified/insertion.rs | + sed 's/^unsafe fn repair_one__VeriFast_wrapper verified/operations.rs || return + git apply --whitespace=nowarn --include=verified/operations.rs "$proof_dir/refinement.patch" +} + +assemble_views() { + local btree="$library/alloc/src/collections/btree" + # Reuse the backlink proof from the insertion program. + sed -e '/^#!\[feature(slice_ptr_get)\]$/d' -e '/^ impl BorrowType for Dying {}$/d' \ + -e '/^\/\/ END_BACKLINK_METHODS$/q' \ + verified/insertion.rs > verified/backlinks.rs + printf '\nfn main() {}\n' >> verified/backlinks.rs + cp verified/backlinks.rs original/backlinks.rs.in + copy_regions original/operations.rs.in original/node.rs original/borrow.rs \ + "$btree/map.rs" "$btree/map/entry.rs" > original/operations.rs + copy_regions original/loop_regions.rs.in original/node.rs > original/loop_regions.rs + copy_regions verified/loop_regions.rs.in verified/insertion.rs > verified/loop_regions.rs + collect_drop_bodies > verified/drop-bodies.rs || return + { + echo '// BEGIN_ROOT_INSTALL' + proof_body 'unsafe fn install_root_split<' verified/insertion.rs || return + echo '// END_ROOT_INSTALL' + } > verified/root-level-body.rs + { + echo '// BEGIN_ASCEND' + proof_body ' unsafe fn ascend(' verified/insertion.rs || return + echo '// END_ASCEND' + echo '// BEGIN_FROM_INTERNAL' + proof_body ' unsafe fn from_internal(' verified/insertion.rs || return + echo '// END_FROM_INTERNAL' + echo '// BEGIN_OPEN_NEXT_PARENT' + proof_body 'unsafe fn open_next_parent<' verified/insertion.rs || return + echo '// END_OPEN_NEXT_PARENT' + } > verified/ascend-body.rs + + mkdir portable + cp original/{node,borrow,mem}.rs portable/ + cp original/loop_crate.rs portable/main.rs + git apply --whitespace=nowarn --exclude=verified/operations.rs "$proof_dir/refinement.patch" || return + assemble_verified_operations || return + mv original/operations.rs original/operations-template.rs + project_root_callbacks \ + "$btree/map.rs" "$btree/map/entry.rs" \ + original/operations-template.rs > original/operations.rs + copy_regions original/backlinks.rs.in original/node.rs > original/backlinks.rs + # Standalone compilation only needs the production runtime prefix. + sed -i '/^#\[cfg(test)\]$/,$d' portable/{node,borrow}.rs +} + +check_ascend_body() { + # The comparison diff folds the checked backlink step into the native + # Option combinators and restores the generic traversal assertion. + { + echo '// BEGIN_ASCEND' + proof_body ' pub(super) fn ascend(' portable/node.rs || return + echo '// END_ASCEND' + echo '// BEGIN_FROM_INTERNAL' + proof_body ' fn from_internal(' portable/node.rs || return + echo '// END_FROM_INTERNAL' + } > original/ascend-body.rs + if ! diff -u original/ascend-body.rs verified/ascend-body.rs; then + echo 'B-tree production ascend differs from the checked parent step' >&2 + return 1 + fi + check_link_ascend +} + +check_link_ascend() { + local common link expected actual + while IFS='|' read -r common link; do + expected=$(proof_body "$common" verified/insertion.rs) || return + actual=$(proof_body "$link" verified/insertion.rs | + sed -e 's/read_parent_link(/open_next_parent(/' \ + -e '/^ const { assert!(BorrowType::TRAVERSAL_PERMIT); }$/d') || return + diff -u <(printf '%s\n' "$expected") <(printf '%s\n' "$actual") || return + done <<'EOF' +unsafe fn open_next_parent<|unsafe fn read_parent_link< + unsafe fn ascend(| unsafe fn ascend_from_link( +EOF + expected=$(proof_body ' pub const fn ok(self)' "$library/core/src/result.rs") || return + actual=$(proof_body 'unsafe fn dying_result_ok<' verified/insertion.rs | + sed 's/^ match value {/ match self {/') || return + diff -u <(printf '%s\n' "$expected") <(printf '%s\n' "$actual") +} + +assemble_loops() { + local side + for side in original verified; do + mkdir -p "$side/loops" + cp portable/*.rs "$side/loops/" + cat "$side/loop_regions.rs" >> "$side/loops/node.rs" + done +} + +# Put the verified replacement core and aborting destructor in the native +# guard scope. The strict MIR check also compares take_mut's closure adapter. +assemble_root_replacement() { + cat <<'EOF' +use core::{mem, ptr}; + +#[allow(dead_code)] +#[inline] +pub(super) fn take_mut(v: &mut T, change: impl FnOnce(T) -> T) { + replace(v, |value| (change(value), ())) +} + +#[inline] +pub(super) fn replace(v: &mut T, change: impl FnOnce(T) -> (T, R)) -> R { + struct PanicGuard; + impl Drop for PanicGuard { + fn drop(&mut self) { +EOF + proof_body ' fn drop(&mut self)' verified/root_replace.rs | sed 's/^/ /' || return + cat <<'EOF' + } + } + let guard = PanicGuard; +EOF + proof_body 'unsafe fn replace_core<' verified/root_replace.rs | awk ' + /^ ret$/ { print " mem::forget(guard);"; ++returned } + { print } + END { if (returned != 1 || $0 != " ret") exit 1 } + ' || return + echo '}' +} + +collect_access_bodies() { + local method signature callback + # The prover checks the generic wrapper. In the owning scope, emit its + # native call so the checker can compare cleanup without inlining. + callback=$(proof_body 'unsafe fn call_merge__VeriFast_wrapper<' verified/insertion.rs) || return + if [[ $callback != ' finish(parent, child)' ]]; then + echo 'B-tree merge callback body changed' >&2 + return 1 + fi + while read -r method signature; do + printf '// body %s\n' "$method" + proof_body " unsafe fn $signature" verified/insertion.rs | + sed -e 's/\.\(merge_len\|relink_len\)(/.len(/g' \ + -e 's/Handle::new_relink_edge(/Handle::new_edge(/g' \ + -e 's/Handle::new_navigation_kv(/Handle::new_kv(/g' \ + -e 's/\.\(key\|val\|edge\)_area_\(slot\|prefix\|range\)_mut(/.\1_area_mut(/g' \ + -e 's/\.relink_range(/.correct_childrens_parent_links(/g' \ + -e 's/unsafe { call_merge__VeriFast_wrapper(finish, parent_node, left_node) }/result(parent_node, left_node)/' \ + -e 's/\.cast_node_to_leaf(/.cast_to_leaf_unchecked(/g' \ + -e 's/^\( *\)panic!("internal error: entered unreachable code: empty internal node")$/\1unreachable!("empty internal node")/' \ + -e 's/unsafe { dying_result_ok(self\.ascend_from_link()) }/self.ascend().ok()/' || return + done <<'EOF' +len merge_len( +new_edge new_relink_edge( +new_kv new_navigation_kv( +first_edge first_edge( +last_edge last_edge( +first_kv first_kv( +last_kv last_kv( +left_edge left_edge( +right_edge right_edge( +left_kv left_kv( +right_kv right_kv( +descend descend( +as_internal_ptr as_internal_ptr( +into_leaf into_leaf( +keys keys< +into_kv into_kv( +as_leaf_mut as_leaf_mut< +into_leaf_mut into_leaf_mut( +as_leaf_dying as_leaf_dying< +as_internal_mut as_internal_mut< +key_mut key_mut< +kv_mut kv_mut< +into_val_mut into_val_mut( +into_kv_mut into_kv_mut( +into_key_val_mut_at into_key_val_mut_at( +into_kv_valmut into_kv_valmut( +into_key_val into_key_val( +push_with_handle push_with_handle< +push_leaf push_leaf< +borrow_mut borrow_mut< +cast_to_internal_unchecked cast_to_internal_unchecked( +clear_parent_link clear_parent_link< +pop_internal_level pop_internal_level< +deallocate_and_ascend deallocate_and_ascend< +remove remove< +consider_for_balancing consider_for_balancing( +do_merge do_merge_production< +choose_parent_kv choose_parent_kv( +cast_node_to_leaf cast_node_to_leaf( +cast_handle_to_leaf cast_handle_to_leaf( +reborrow_node_mut reborrow_mut< +reborrow_handle_mut reborrow_handle_mut< +awaken_node awaken<'a>(self) -> NodeRef +awaken_handle awaken<'a>(self) -> Handle +forget_leaf_edge forget_leaf_edge( +forget_internal_edge forget_internal_edge( +forget_leaf_kv forget_leaf_kv( +EOF +} + +assemble_whole_functions() { + local side + # Compare the folded root installation with the production method. + # Identical closure text also preserves its Rust capture and call scope. + { + echo '// BEGIN_ROOT_INSTALL' + proof_body ' pub(super) fn push_internal_level<' portable/node.rs || return + echo '// END_ROOT_INSTALL' + } > original/root-level-body.rs + diff -u original/root-level-body.rs verified/root-level-body.rs || return + + for side in original verified; do + mkdir -p "$side/whole" + cp portable/*.rs "$side/whole/" + done + { + echo '// body insert_recursing' + compose_insert_recursing || return + collect_access_bodies || return + cat verified/drop-bodies.rs + } > whole-bodies.rs + awk ' + FNR == NR { + if (/^\/\/ body /) { + name = $3 + if (name in body) exit 1 + body[name] = "" + next + } + body[name] = body[name] " " $0 "\n" + next + } + /^impl[< ]/ { + impl_header = $0 + handle_impl = / Handle \*mut V/) name = "push_leaf" + if (name == "reborrow_mut") name = handle_impl ? "reborrow_handle_mut" : "reborrow_node_mut" + if (name == "cast_to_leaf_unchecked") name = handle_impl ? "cast_handle_to_leaf" : "cast_node_to_leaf" + if (name == "awaken") name = handle_impl ? "awaken_handle" : "awaken_node" + if (name == "forget_node_type" && handle_impl) { + if (impl_header ~ /marker::Internal>, marker::Edge>/) name = "forget_internal_edge" + if (impl_header ~ /marker::Leaf>, marker::Edge>/) name = "forget_leaf_edge" + if (impl_header ~ /marker::Leaf>, marker::KV>/) name = "forget_leaf_kv" + } + if (name in body) { + header = 1 + ++found[name] + } + } + header && /[{]$/ { + print + printf "%s", body[name] + header = 0 + skipping = 1 + next + } + skipping && /^ }$/ { skipping = 0; ++closed[name] } + !skipping { print } + END { + for (name in body) if (found[name] != 1 || closed[name] != 1) exit 1 + } + ' whole-bodies.rs portable/node.rs > verified/whole/node.rs || return + assemble_root_replacement > verified/whole/mem.rs +} + +verify_proof() { + "$@" 2>&1 | tee verification.log + if grep -Fq 'Detected an inconsistency after axiom instantiations' verification.log; then + echo "VeriFast reported an inconsistent proof state." >&2 + return 1 + fi +} + +refine() { + "$verifast_home/bin/refinement-checker" --rustc-args '--edition=2024' "$@" +} + +refine_whole_functions() { + refine --check-unwind original/whole/main.rs verified/whole/main.rs +} + +proof() { + "$work_dir/verifast/bin/verifast" -skip_specless_fns -allow_dead_code "$@" +} + +rejected() { + local diagnostic=$1 + shift + if "$@" > rejection.log 2>&1 || ! grep -Fq -- "$diagnostic" rejection.log; then + cat rejection.log + return 1 + fi + printf '%s\n' "$diagnostic" +} + +mutate() { + local patch + patch=$(awk -v label="# Case $1" ' + $0 == label { seen++; selected = 1; next } + /^# Case / { selected = 0; next } + selected { print } + END { if (seen != 1) exit 1 } + ' "$proof_dir/negative/mutations.patch") + shift + + git apply --whitespace=error <<< "$patch" + "$@" + git apply --whitespace=error -R <<< "$patch" +} + +reject_proof() { + local diagnostic=$1 file=$2 signature=$3 line + line=$(awk -v signature="$signature" 'index($0, signature) == 1 { print NR; exit }' "$file") + test -n "$line" + rejected "$diagnostic" proof -focus "$file:$line" "$file" +} + +reject_loop() { + copy_regions verified/loop_regions.rs.in verified/insertion.rs > verified/loop_regions.rs || return + git apply --whitespace=nowarn --include=verified/loop_regions.rs "$proof_dir/refinement.patch" || return + assemble_loops + rejected "$1" refine original/loops/main.rs verified/loops/main.rs +} + +reject_insert_loop() { + assemble_whole_functions || return + rejected 'The constants FnDef node::SplitResult::' refine_whole_functions +} + +reject_keys_prefix() { + reject_proof 'Cannot prove std::mem::initialized_slots' verified/insertion.rs ' unsafe fn keys<' + assemble_whole_functions || return + rejected '::keys, cannot prove' refine_whole_functions +} + +reject_drop_loop() { + mkdir -p drop-loop/verified + collect_drop_bodies > drop-loop/verified/drop-bodies.rs || return + rejected 'verified/drop-bodies.rs: patch does not apply' git -C drop-loop apply --check \ + --include=verified/drop-bodies.rs "$proof_dir/refinement.patch" +} + +reject_operation() { + local proof_diagnostic=$1 refinement_diagnostic=$2 signature=$3 + reject_proof "$proof_diagnostic" verified/insertion.rs "$signature" + mv verified/operations.rs verified/operations-baseline.rs + assemble_verified_operations || return + rejected "$refinement_diagnostic" refine original/operations.rs verified/operations.rs + mv verified/operations-baseline.rs verified/operations.rs +} + +reject_merge_layout() { + reject_operation 'No matching heap chunks: std::alloc::alloc_block_in' \ + 'The constants FnDef std::alloc::Layout::new' ' unsafe fn do_merge_production<' + assemble_whole_functions || return + rejected 'The constants FnDef std::alloc::Layout::new' refine_whole_functions +} + +reject_allocator_drop() { + rustc +nightly-2026-09-25 --edition=2024 -Awarnings -Cpanic=unwind \ + verified/allocator-drop.rs -o allocator-drop + ./allocator-drop > allocator-drop.log 2>&1 + reject_proof 'Cannot prove false' verified/allocator-drop.rs 'unsafe fn claimed_no_unwind<' +} + +reject_root_callback() { + project_root_callbacks "$library/alloc/src/collections/btree/map.rs" callers/entry.rs \ + original/operations-template.rs > callers/operations.rs + rejected '::filter' refine callers/operations.rs verified/operations.rs +} + +reject_unwind_order() { + refine original/unwind_order.rs verified/unwind_order.rs + rejected 'The two drop terminators drop different values' refine --check-unwind \ + original/unwind_order.rs verified/unwind_order.rs +} + +reject_production_dispatch() { + local btree="$library/alloc/src/collections/btree" + mkdir -p dispatch/original + copy_regions original/operations.rs.in original/node.rs original/borrow.rs \ + "$btree/map.rs" "$btree/map/entry.rs" > dispatch/original/operations.rs + rejected 'patch does not apply' git -C dispatch apply --check \ + --include=original/operations.rs "$proof_dir/refinement.patch" +} + +check_sources +assemble_views +check_ascend_body +assemble_loops +assemble_whole_functions +mkdir -p verifast/bin +cp -a -- "$verifast_home/bin/." verifast/bin/ +git -C verifast apply --whitespace=error "$proof_dir/library-specs.patch" + +if [[ ${1:-} == --negative ]]; then + binary_mismatch='BinaryOp: The operators do not match' + terminator_mismatch='in the original version refines the terminator of basic block' + + mkdir callers + cp "$library/alloc/src/collections/btree/map/entry.rs" callers/entry.rs + mutate allocator-drop-bound reject_allocator_drop + mutate production-root-callback reject_root_callback + mutate unwind-order reject_unwind_order + mutate production-leaf-dispatch reject_production_dispatch + mutate production-ascend rejected 'B-tree production ascend differs' check_ascend_body + + mutate whole-insert-loop reject_insert_loop + mutate uninitialized-key-prefix reject_keys_prefix + mutate write-shared-node-length reject_proof 'No matching heap chunks: points_to_' \ + verified/insertion.rs ' unsafe fn keys<' + mutate duplicate-key-loan reject_proof 'No matching heap chunks: points_to' \ + verified/insertion.rs ' unsafe fn kv_mut<' + mutate invalid-parent-nonnull reject_proof 'Cannot prove !(get_pointer_address(null_pointer) = 0)' \ + verified/insertion.rs ' unsafe fn correct_parent_link(self)' + assemble_whole_functions + mutate wrong-merge-offset reject_proof 'Cannot prove condition' verified/insertion.rs \ + 'unsafe fn finish_merge_tracking__VeriFast_wrapper<' + mutate wrong-merge-offset reject_loop 'compare_merge_tracking_child_edge, at command' + mutate wrong-left-steal-offset reject_loop "$binary_mismatch" + + mutate drop-value-guard rejected 'drop_key_val' refine_whole_functions + mutate drop-next-pair rejected 'drop_kvs' refine_whole_functions + mutate drop-loop-index reject_drop_loop + mutate wrong-drop-slot reject_operation 'Cannot prove condition' 'project_drop_slots, cannot prove' \ + ' unsafe fn project_drop_slots<' + mutate skipped-merge reject_operation 'No matching heap chunks: [_]merged_nodes' \ + 'merge_tracking_child_edge, cannot prove that the terminator' ' unsafe fn merge_tracking_child_edge<' + mutate skipped-stolen-edge reject_operation 'Cannot prove length(before) = get_std::ops::Range_start' \ + 'are not equal' ' unsafe fn bulk_steal_left_production<' + mutate bad-root-edge reject_operation 'Cannot prove condition' 'are not equal' \ + ' unsafe fn new_internal_production<' + mutate root-guard rejected 'In function mem::replace, cannot prove' refine_whole_functions + mutate bad-relink-read reject_proof 'Cannot prove condition' verified/relink.rs \ + ' unsafe fn correct_parent_link(self)' + mutate bad-suffix-range reject_operation 'No matching heap chunks: edges_range_loan' \ + 'move_suffix_production, cannot prove that statement' ' unsafe fn move_suffix_production<' + mutate bad-separator reject_proof 'No matching heap chunks: keys_slot_loan' verified/insertion.rs \ + 'unsafe fn merge_keys<' + mutate bad-split-boundaries reject_operation 'No matching heap chunks: array>' \ + 'cannot prove that the terminator of basic block' ' unsafe fn split_leaf_data<' + mutate missing-internal-relink reject_operation 'No matching heap chunks: linked_headers' \ + "$terminator_mismatch" ' unsafe fn from_new_internal<' + mutate short-edges reject_operation \ + 'No matching heap chunks: array>>>' \ + "$terminator_mismatch" ' unsafe fn split_production_internal<' + mutate bad-leaf-capacity reject_operation 'Cannot prove len < CAPACITY' "$binary_mismatch" \ + ' unsafe fn insert_leaf_production<' + mutate bad-internal-capacity reject_operation 'Cannot prove len < CAPACITY' "$binary_mismatch" \ + ' unsafe fn insert_production<' + mutate missing-insert-relink reject_operation 'Cannot prove length(before) = get_std::ops::Range_start' \ + 'are not equal' ' unsafe fn insert_fit_production<' + mutate wrong-layout reject_merge_layout + mutate bad-key-range rejected 'are not equal: Symbol' refine original/operations.rs verified/operations.rs + mutate production-steal-range rejected 'B-tree production snapshot changed: node.rs' check_sources + exit 0 +fi + +verify_proof "$verifast_home/bin/verifast" -skip_specless_fns verified/backlinks.rs +"$verifast_home/bin/refinement-checker" original/backlinks.rs verified/backlinks.rs +# Rust MIR retains assertion failures and cleanup blocks proved unreachable. +verify_proof proof verified/insertion.rs +verify_proof proof verified/relink.rs +refine original/operations.rs verified/operations.rs +refine_whole_functions +refine original/loops/main.rs verified/loops/main.rs +verify_proof proof verified/root_replace.rs diff --git a/verifast-proofs/check-verifast-proofs.sh b/verifast-proofs/check-verifast-proofs.sh index 23bd82948efbd..3814d932350c8 100755 --- a/verifast-proofs/check-verifast-proofs.sh +++ b/verifast-proofs/check-verifast-proofs.sh @@ -6,6 +6,11 @@ cd "$(dirname "$0")" export PATH=`pwd`:$PATH +# The B-tree build uses the Linux x86_64 VeriFast dependency archive. +if [[ $(uname -sm) == 'Linux x86_64' ]]; then + bash alloc/collections/btree/node.rs/verify.sh --ci +fi + cd alloc cd collections cd linked_list.rs