Skip to main content

vstd/std_specs/
btree.rs

1//! This code adds specifications for the standard-library types
2//! `alloc::collections::BTreeMap` and `alloc::collections::BTreeSet`.
3//!
4//! The specification is only meaningful when the `Key` obeys our [`Ord`] model,
5//! as specified by [`super::super::laws_cmp::obeys_cmp_spec`].
6//! Borrowed-query comparison guarantees additionally require
7//! `obeys_cmp::<&Q>()` and
8//! `<Key as BorrowSpec<Q>>::obeys_borrow_spec()`.
9//!
10//! By default, the Verus standard library brings useful axioms
11//! about the behavior of `BTreeMap` and `BTreeSet` into the ambient
12//! reasoning context by broadcasting the group
13//! `vstd::std_specs::btree::group_btree_axioms`.
14use super::super::laws_cmp::{obeys_cmp, obeys_cmp_concrete_eq, obeys_cmp_deep_eq};
15use super::super::map::{assert_maps_equal, assert_maps_equal_internal};
16use super::super::pervasive::obeys_clone_eq;
17use super::super::prelude::*;
18use super::borrow::BorrowSpec;
19use super::cmp::OrdSpec;
20pub use super::cmp::borrowed_key_ordering_matches;
21use super::iter::IteratorSpec;
22
23use alloc::alloc::AllocatorClone;
24use alloc::boxed::Box;
25use alloc::collections::btree_map;
26use alloc::collections::btree_map::{CursorMut, Keys, UnorderedKeyError, Values};
27use alloc::collections::btree_set;
28use alloc::collections::{BTreeMap, BTreeSet};
29use core::borrow::Borrow;
30use core::cmp::Ordering;
31use core::marker::PhantomData;
32use core::ops::Bound;
33use core::option::Option;
34
35verus! {
36
37/// Whether the `Key` type obeys the cmp spec, required for [`BTreeMap`]
38///
39/// This is a workaround to the fact that [`BTreeMap`] "late binds" the trait bounds when needed.
40/// For instance, [`BTreeMap::iter`] does not require `Key: Ord`, even though it yields ordered
41/// items. Rather, it relies on the fact that [`BTreeMap::insert`] does require `Key: Ord`, meaning
42/// no instance of a [`BTreeMap`] will ever have keys that cannot be comparable.
43///
44/// See also [`axiom_key_obeys_cmp_spec_meaning`].
45pub uninterp spec fn key_obeys_cmp_spec<Key: ?Sized>() -> bool;
46
47/// For types that are ordered, [`key_obeys_cmp_spec`] is equivalent to [`obeys_cmp`].
48pub broadcast axiom fn axiom_key_obeys_cmp_spec_meaning<K: Ord>()
49    ensures
50        #[trigger] key_obeys_cmp_spec::<K>() <==> obeys_cmp::<K>(),
51;
52
53/// Whether a sequence is ordered in increasing order.
54/// This only has meaning if `K: Ord` and [`obeys_cmp::<K>`].
55///
56/// See [`axiom_increasing_seq_meaning`] for an interpretation of this predicate.
57pub uninterp spec fn increasing_seq<K>(s: Seq<K>) -> bool;
58
59/// An interpretation for the [`increasing_seq`] predicate.
60pub broadcast axiom fn axiom_increasing_seq_meaning<K: Ord>(s: Seq<K>)
61    requires
62        obeys_cmp::<K>(),
63    ensures
64        #[trigger] increasing_seq(s) <==> forall|i, j|
65            0 <= i < j < s.len() ==> s[i].cmp_spec(&s[j]) is Less,
66;
67
68/// Specifications for the behavior of
69/// [`alloc::collections::btree_map::Keys`](https://doc.rust-lang.org/alloc/collections/btree_map/struct.Keys.html).
70#[verifier::external_type_specification]
71#[verifier::external_body]
72#[verifier::accept_recursive_types(Key)]
73#[verifier::accept_recursive_types(Value)]
74pub struct ExKeys<'a, Key, Value>(Keys<'a, Key, Value>);
75
76// To allow reasoning about the "contents" of the Keys iterator, without using
77// a prophecy, we need a function that gives us the underlying sequence of the original keys.
78pub uninterp spec fn into_iter_keys<'a, Key, Value>(i: Keys<'a, Key, Value>) -> Seq<Key>;
79
80impl<'a, K, V> super::iter::IteratorSpecImpl for Keys<'a, K, V> {
81    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
82        true
83    }
84
85    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
86
87    #[verifier::prophetic]
88    open spec fn produces(&self) -> Seq<bool> {
89        Seq::new(IteratorSpec::remaining(self).len(), |i: int| true)
90    }
91
92    uninterp spec fn decrease(&self) -> Option<nat>;
93
94    open spec fn peek(&self, index: int) -> Option<Self::Item> {
95        if 0 <= index < into_iter_keys(*self).len() {
96            Some(&into_iter_keys(*self)[index])
97        } else {
98            None
99        }
100    }
101}
102
103/// Specifications for the behavior of
104/// [`alloc::collections::btree_map::Values`](https://doc.rust-lang.org/alloc/collections/btree_map/struct.Values.html).
105#[verifier::external_type_specification]
106#[verifier::external_body]
107#[verifier::accept_recursive_types(Key)]
108#[verifier::accept_recursive_types(Value)]
109pub struct ExValues<'a, Key, Value>(Values<'a, Key, Value>);
110
111// To allow reasoning about the "contents" of the Values iterator, without using
112// a prophecy, we need a function that gives us the underlying sequence of the original values.
113pub uninterp spec fn into_iter_values<'a, Key, Value>(i: Values<'a, Key, Value>) -> Seq<Value>;
114
115impl<'a, K, V> super::iter::IteratorSpecImpl for Values<'a, K, V> {
116    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
117        true
118    }
119
120    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
121
122    #[verifier::prophetic]
123    open spec fn produces(&self) -> Seq<bool> {
124        Seq::new(IteratorSpec::remaining(self).len(), |i: int| true)
125    }
126
127    uninterp spec fn decrease(&self) -> Option<nat>;
128
129    open spec fn peek(&self, index: int) -> Option<Self::Item> {
130        if 0 <= index < into_iter_values(*self).len() {
131            Some(&into_iter_values(*self)[index])
132        } else {
133            None
134        }
135    }
136}
137
138// The `iter` method of a `BTreeMap` returns an iterator of type `btree_map::Iter`,
139// so we specify that type here.
140#[verifier::external_type_specification]
141#[verifier::external_body]
142#[verifier::accept_recursive_types(K)]
143#[verifier::accept_recursive_types(V)]
144pub struct ExMapIter<'a, K, V>(btree_map::Iter<'a, K, V>);
145
146// To allow reasoning about the "contents" of the Iter iterator, without using
147// a prophecy, we need a function that gives us the underlying sequence of the original map.
148pub uninterp spec fn into_iter<'a, Key, Value>(i: btree_map::Iter<'a, Key, Value>) -> Seq<
149    (Key, Value),
150>;
151
152impl<'a, K, V> super::iter::IteratorSpecImpl for btree_map::Iter<'a, K, V> {
153    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
154        true
155    }
156
157    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
158
159    #[verifier::prophetic]
160    open spec fn produces(&self) -> Seq<bool> {
161        Seq::new(IteratorSpec::remaining(self).len(), |i: int| true)
162    }
163
164    uninterp spec fn decrease(&self) -> Option<nat>;
165
166    open spec fn peek(&self, index: int) -> Option<Self::Item> {
167        if 0 <= index < into_iter(*self).len() {
168            let (k, v) = into_iter(*self)[index];
169            Some((&k, &v))
170        } else {
171            None
172        }
173    }
174}
175
176pub assume_specification<'a, Key, Value, A: AllocatorClone>[ BTreeMap::<Key, Value, A>::iter ](
177    m: &'a BTreeMap<Key, Value, A>,
178) -> (iter: btree_map::Iter<'a, Key, Value>)
179    ensures
180        key_obeys_cmp_spec::<Key>() && btree_map_wf(m) ==> {
181            // `m.len()` is mentioned so callers learn that the length fits in a `usize`
182            // (needed, e.g., by `enumerate` and `position`)
183            &&& IteratorSpec::remaining(&iter).len() == m@.dom().len()
184            &&& IteratorSpec::remaining(&iter).len() == m.len()
185            &&& forall|i: int|
186                #![trigger m@.contains_key(*IteratorSpec::remaining(&iter)[i].0)]
187                #![trigger m@[*IteratorSpec::remaining(&iter)[i].0]]
188                0 <= i < IteratorSpec::remaining(&iter).len() ==> m@.contains_key(
189                    *IteratorSpec::remaining(&iter)[i].0,
190                ) && m@[*IteratorSpec::remaining(&iter)[i].0] == *IteratorSpec::remaining(
191                    &iter,
192                )[i].1
193            &&& forall|k: Key| #[trigger]
194                m@.contains_key(k) ==> IteratorSpec::remaining(&iter).contains((&k, &m@[k]))
195            &&& IteratorSpec::remaining(&iter).unref().to_set() == m@.kv_pairs()
196            &&& iter.remaining().no_duplicates()
197            &&& into_iter(iter) == IteratorSpec::remaining(&iter).unref()
198            &&& IteratorSpec::decrease(&iter) is Some
199            &&& increasing_seq(iter.remaining().map_values(|kv: (&Key, &Value)| *kv.0))
200        },
201;
202
203/// Specifications for the behavior of [`alloc::collections::BTreeMap`](https://doc.rust-lang.org/alloc/collections/struct.BTreeMap.html).
204///
205/// We model a `BTreeMap` as having a view of type `Map<Key, Value>`, which reflects the current state of the map.
206///
207/// These specifications are only meaningful if `key_obeys_cmp_spec::<Key>()` holds.
208/// See [`key_obeys_cmp_spec`] for information on use with primitive types and other types.
209///
210/// Axioms about the behavior of BTreeMap are present in the broadcast group `vstd::std_specs::btree::group_btree_axioms`.
211#[verifier::external_type_specification]
212#[verifier::external_body]
213#[verifier::accept_recursive_types(Key)]
214#[verifier::accept_recursive_types(Value)]
215#[verifier::reject_recursive_types(A)]
216pub struct ExBTreeMap<Key, Value, A: AllocatorClone>(BTreeMap<Key, Value, A>);
217
218/// Verus declaration for Rust's mutable B-tree cursor type.
219#[verifier::external_type_specification]
220#[verifier::external_body]
221#[verifier::accept_recursive_types(Key)]
222#[verifier::accept_recursive_types(Value)]
223#[verifier::reject_recursive_types(A)]
224pub struct ExCursorMut<'a, Key: 'a, Value: 'a, A>(CursorMut<'a, Key, Value, A>);
225
226/// Verus declaration for the error returned when a cursor insertion would break key ordering.
227#[verifier::external_type_specification]
228#[verifier::external_body]
229pub struct ExUnorderedKeyError(UnorderedKeyError);
230
231/// The abstract state of a mutable B-tree cursor.
232///
233/// A cursor points at the gap immediately before `keys[position]`. Therefore, `peek_next`
234/// accesses `keys[position]`, while `peek_prev` accesses `keys[position - 1]`.
235pub ghost struct CursorMutModel<Key, Value> {
236    /// All keys in the underlying map, in strictly increasing order.
237    pub keys: Seq<Key>,
238    /// The index of the element immediately after the cursor.
239    pub position: int,
240    /// The current contents of the complete map borrowed by the cursor.
241    pub map: Map<Key, Value>,
242}
243
244impl<Key, Value> CursorMutModel<Key, Value> {
245    /// Whether this model consistently represents an ordered map and a gap in that map.
246    pub open spec fn wf(self) -> bool {
247        &&& 0 <= self.position <= self.keys.len()
248        &&& self.keys.no_duplicates()
249        &&& self.keys.to_set() == self.map.dom()
250        &&& increasing_seq(self.keys)
251    }
252}
253
254/// Abstract and prophetic state for mutable B-tree cursors.
255pub trait CursorMutSpecFns<Key, Value>: View<V = CursorMutModel<Key, Value>> + Sized {
256    /// The contents of the borrowed map when this cursor's borrow is resolved.
257    #[verifier::prophetic]
258    spec fn final_map(self) -> Map<Key, Value>;
259}
260
261impl<'a, Key, Value, A> View for CursorMut<'a, Key, Value, A> {
262    type V = CursorMutModel<Key, Value>;
263
264    uninterp spec fn view(&self) -> CursorMutModel<Key, Value>;
265}
266
267impl<'a, Key, Value, A> CursorMutSpecFns<Key, Value> for CursorMut<'a, Key, Value, A> {
268    #[verifier::prophetic]
269    uninterp spec fn final_map(self) -> Map<Key, Value>;
270}
271
272/// Whether a key occurs before the gap returned by [`BTreeMap::lower_bound_mut`].
273pub open spec fn before_lower_bound<Key: Borrow<Q>, Q: Ord + ?Sized>(
274    key: Key,
275    bound: Bound<&Q>,
276) -> bool {
277    let borrowed_key = <Key as BorrowSpec<Q>>::borrow_spec(&key);
278    match bound {
279        Bound::Included(bound_key) => borrowed_key.cmp_spec(bound_key) is Less,
280        Bound::Excluded(bound_key) => !(borrowed_key.cmp_spec(bound_key) is Greater),
281        Bound::Unbounded => false,
282    }
283}
284
285/// Whether a key occurs before the gap returned by [`BTreeMap::upper_bound_mut`].
286pub open spec fn before_upper_bound<Key: Borrow<Q>, Q: Ord + ?Sized>(
287    key: Key,
288    bound: Bound<&Q>,
289) -> bool {
290    let borrowed_key = <Key as BorrowSpec<Q>>::borrow_spec(&key);
291    match bound {
292        Bound::Included(bound_key) => !(borrowed_key.cmp_spec(bound_key) is Greater),
293        Bound::Excluded(bound_key) => borrowed_key.cmp_spec(bound_key) is Less,
294        Bound::Unbounded => true,
295    }
296}
297
298/// Whether a cursor is at the gap selected by [`BTreeMap::lower_bound_mut`].
299pub open spec fn positioned_at_lower_bound<Key: Borrow<Q>, Value, Q: Ord + ?Sized>(
300    model: CursorMutModel<Key, Value>,
301    bound: Bound<&Q>,
302) -> bool {
303    &&& forall|i: int|
304        #![trigger before_lower_bound(model.keys[i], bound)]
305        0 <= i < model.position ==> before_lower_bound(model.keys[i], bound)
306    &&& forall|i: int|
307        #![trigger before_lower_bound(model.keys[i], bound)]
308        model.position <= i < model.keys.len() ==> !before_lower_bound(model.keys[i], bound)
309}
310
311/// Whether a cursor is at the gap selected by [`BTreeMap::upper_bound_mut`].
312pub open spec fn positioned_at_upper_bound<Key: Borrow<Q>, Value, Q: Ord + ?Sized>(
313    model: CursorMutModel<Key, Value>,
314    bound: Bound<&Q>,
315) -> bool {
316    &&& forall|i: int|
317        #![trigger before_upper_bound(model.keys[i], bound)]
318        0 <= i < model.position ==> before_upper_bound(model.keys[i], bound)
319    &&& forall|i: int|
320        #![trigger before_upper_bound(model.keys[i], bound)]
321        model.position <= i < model.keys.len() ==> !before_upper_bound(model.keys[i], bound)
322}
323
324/// Whether a key can be inserted at the cursor's current gap without breaking key order.
325pub open spec fn key_fits_at_position<Key: Ord, Value>(
326    model: CursorMutModel<Key, Value>,
327    key: Key,
328) -> bool {
329    &&& (model.position == 0 || model.keys[model.position - 1].cmp_spec(&key) is Less)
330    &&& (model.position == model.keys.len() || key.cmp_spec(&model.keys[model.position]) is Less)
331}
332
333/// Once the cursor has been dropped, its prophesied map is its current map.
334pub broadcast axiom fn axiom_has_resolved_cursor<Key, Value, A>(cursor: CursorMut<Key, Value, A>)
335    ensures
336        #[trigger] has_resolved(cursor) ==> cursor.final_map() == cursor@.map,
337;
338
339pub trait BTreeMapAdditionalSpecFns<Key, Value>: View<V = Map<Key, Value>> {
340    spec fn spec_index(&self, k: Key) -> Value
341        recommends
342            self@.contains_key(k),
343    ;
344}
345
346impl<Key, Value, A: AllocatorClone> BTreeMapAdditionalSpecFns<Key, Value> for BTreeMap<
347    Key,
348    Value,
349    A,
350> {
351    #[verifier::inline]
352    open spec fn spec_index(&self, k: Key) -> Value {
353        self@.index(k)
354    }
355}
356
357impl<Key, Value, A: AllocatorClone> View for BTreeMap<Key, Value, A> {
358    type V = Map<Key, Value>;
359
360    uninterp spec fn view(&self) -> Map<Key, Value>;
361}
362
363impl<Key: DeepView, Value: DeepView, A: AllocatorClone> DeepView for BTreeMap<Key, Value, A> {
364    type V = Map<Key::V, Value::V>;
365
366    open spec fn deep_view(&self) -> Map<Key::V, Value::V> {
367        btree_map_deep_view_impl(*self)
368    }
369}
370
371/// The actual definition of `BTreeMap::deep_view`.
372///
373/// This is a separate function since it introduces a lot of quantifiers and revealing an opaque trait
374/// method is not supported. In most cases, it's easier to use one of the lemmas below instead
375/// of revealing this function directly.
376#[verifier::opaque]
377pub open spec fn btree_map_deep_view_impl<Key: DeepView, Value: DeepView, A: AllocatorClone>(
378    m: BTreeMap<Key, Value, A>,
379) -> Map<Key::V, Value::V> {
380    Map::new(
381        m@.dom().map(|k: Key| k.deep_view()),
382        |dk: Key::V|
383            {
384                let k = choose|k: Key| m@.contains_key(k) && #[trigger] k.deep_view() == dk;
385                m@[k].deep_view()
386            },
387    )
388}
389
390pub broadcast proof fn lemma_btree_map_deepview_dom<K: DeepView, V: DeepView>(m: BTreeMap<K, V>)
391    ensures
392        #[trigger] m.deep_view().dom() == m@.dom().map(|k: K| k.deep_view()),
393{
394    reveal(btree_map_deep_view_impl);
395    broadcast use group_btree_axioms;
396    broadcast use crate::vstd::group_vstd_default;
397
398    assert(m.deep_view().dom() =~= m@.dom().map(|k: K| k.deep_view()));
399}
400
401pub broadcast proof fn lemma_btree_map_deepview_properties<K: DeepView, V: DeepView>(
402    m: BTreeMap<K, V>,
403)
404    requires
405        crate::relations::injective(|k: K| k.deep_view()),
406    ensures
407        #![trigger m.deep_view()]
408        // all elements in m.view() are present in m.deep_view()
409        forall|k: K| #[trigger]
410            m@.contains_key(k) ==> m.deep_view().contains_key(k.deep_view())
411                && m.deep_view()[k.deep_view()] == m@[k].deep_view(),
412        // all elements in m.deep_view() are present in m.view()
413        forall|dk: <K as DeepView>::V| #[trigger]
414            m.deep_view().contains_key(dk) ==> exists|k: K|
415                k.deep_view() == dk && #[trigger] m@.contains_key(k),
416{
417    reveal(btree_map_deep_view_impl);
418    broadcast use group_btree_axioms;
419    broadcast use crate::vstd::group_vstd_default;
420
421    assert(m.deep_view().dom() == m@.dom().map(|k: K| k.deep_view()));
422    assert forall|k: K| #[trigger] m@.contains_key(k) implies m.deep_view().contains_key(
423        k.deep_view(),
424    ) && m.deep_view()[k.deep_view()] == m@[k].deep_view() by {
425        assert forall|k1: K, k2: K| #[trigger]
426            k1.deep_view() == #[trigger] k2.deep_view() implies k1 == k2 by {
427            let ghost k_deepview = |k: K| k.deep_view();
428            assert(crate::relations::injective(k_deepview));
429            assert(k_deepview(k1) == k_deepview(k2));
430        }
431    }
432}
433
434pub broadcast proof fn lemma_btree_map_deepview_values<K: DeepView, V: DeepView>(m: BTreeMap<K, V>)
435    requires
436        crate::relations::injective(|k: K| k.deep_view()),
437    ensures
438        #[trigger] m.deep_view().values() =~= m@.values().map(|v: V| v.deep_view()),
439{
440    reveal(btree_map_deep_view_impl);
441    broadcast use group_btree_axioms;
442    broadcast use lemma_btree_map_deepview_properties;
443    broadcast use crate::vstd::group_vstd_default;
444
445    let lhs = m.deep_view().values();
446    let rhs = m@.values().map(|v: V| v.deep_view());
447    assert forall|v: V::V| #[trigger] lhs.contains(v) implies rhs.contains(v) by {
448        let dk = choose|dk: K::V| #[trigger]
449            m.deep_view().contains_key(dk) && m.deep_view()[dk] == v;
450        let k = choose|k: K| #[trigger] m@.contains_key(k) && k.deep_view() == dk;
451        let ov = choose|ov: V| #[trigger] m@.contains_key(k) && m@[k] == ov && ov.deep_view() == v;
452        assert(v == ov.deep_view());
453        assert(m@.values().contains(ov));
454    }
455}
456
457/// Whether the map's entries are arranged as the tree requires, so that its view describes
458/// what its operations do. The specified operations build well-formed maps, and keep a map
459/// well formed. Safe code can build malformed maps, though: for example by cloning a map whose
460/// key type's `Clone` changes the key (see [`obeys_clone_eq`]; the copy holds the changed keys
461/// at the positions of the originals), or through a `Borrow` that disagrees with the key's `Ord`.
462/// So a map from unverified code is not known to be well formed.
463///
464/// This depends on the map value, not only its view: a malformed copy can have the same view
465/// as the well-formed original.
466pub uninterp spec fn btree_map_wf<Key, Value, A: AllocatorClone>(
467    m: &BTreeMap<Key, Value, A>,
468) -> bool;
469
470pub open spec fn btree_map_inv<Key: Ord, Value, A: AllocatorClone>(
471    m: &BTreeMap<Key, Value, A>,
472) -> bool {
473    &&& btree_map_wf(m)
474    &&& forall|k1: Key, k2: Key|
475        {
476            &&& #[trigger] m@.contains_key(k1)
477            &&& #[trigger] m@.contains_key(k2)
478            &&& k1 != k2
479        } ==> !(k1.cmp_spec(&k2) is Equal)
480}
481
482pub uninterp spec fn spec_btree_map_len<Key, Value, A: AllocatorClone>(
483    m: &BTreeMap<Key, Value, A>,
484) -> usize;
485
486pub broadcast axiom fn axiom_spec_btree_map_len<Key, Value, A: AllocatorClone>(
487    m: &BTreeMap<Key, Value, A>,
488)
489    ensures
490        key_obeys_cmp_spec::<Key>() ==> #[trigger] spec_btree_map_len(m) == m@.len(),
491;
492
493#[verifier::when_used_as_spec(spec_btree_map_len)]
494pub assume_specification<Key, Value, A: AllocatorClone>[ BTreeMap::<Key, Value, A>::len ](
495    m: &BTreeMap<Key, Value, A>,
496) -> (len: usize)
497    ensures
498        len == spec_btree_map_len(m),
499;
500
501pub assume_specification<Key, Value, A: AllocatorClone>[ BTreeMap::<Key, Value, A>::is_empty ](
502    m: &BTreeMap<Key, Value, A>,
503) -> (res: bool)
504    ensures
505        res == m@.is_empty(),
506;
507
508pub assume_specification<K: Clone, V: Clone, A: AllocatorClone>[ <BTreeMap::<
509    K,
510    V,
511    A,
512> as Clone>::clone ](this: &BTreeMap<K, V, A>) -> (other: BTreeMap<K, V, A>)
513    ensures
514// The keys are cloned too; only keys that clone to equal values leave them unchanged (and
515// the copy well formed). The values are cloned (equal only if `V` obeys `obeys_clone_eq`).
516
517        obeys_clone_eq::<K>() ==> {
518            &&& other@.dom() == this@.dom()
519            &&& forall|key|
520                #![trigger other@.dom().contains(key)]
521                other@.dom().contains(key) ==> cloned(this@[key], #[trigger] other@[key])
522        },
523        obeys_clone_eq::<K>() && btree_map_wf(this) ==> btree_map_wf(&other),
524;
525
526pub assume_specification<Key, Value>[ BTreeMap::<Key, Value>::new ]() -> (m: BTreeMap<Key, Value>)
527    ensures
528        m@ == Map::<Key, Value>::empty(),
529        btree_map_wf(&m),
530;
531
532pub assume_specification<K, V>[ <BTreeMap<K, V> as core::default::Default>::default ]() -> (m:
533    BTreeMap<K, V>)
534    ensures
535        m@ == Map::<K, V>::empty(),
536        btree_map_wf(&m),
537;
538
539pub open spec fn btree_map_insert_ensures<Key: Ord, Value, A: AllocatorClone>(
540    old_m: &BTreeMap<Key, Value, A>,
541    final_m: &BTreeMap<Key, Value, A>,
542    k: Key,
543    v: Value,
544    result: Option<Value>,
545) -> bool {
546    obeys_cmp::<Key>() && btree_map_inv(old_m) ==> {
547        &&& btree_map_inv(final_m)
548        &&& match result {
549            Some(old_value) => exists|stored_key: Key|
550                {
551                    &&& #[trigger] old_m@.contains_key(stored_key)
552                    &&& k.cmp_spec(&stored_key) is Equal
553                    &&& old_value == old_m@[stored_key]
554                    &&& final_m@ == old_m@.insert(stored_key, v)
555                },
556            None => {
557                &&& forall|stored_key: Key| #[trigger]
558                    old_m@.contains_key(stored_key) ==> !(k.cmp_spec(&stored_key) is Equal)
559                &&& final_m@ == old_m@.insert(k, v)
560            },
561        }
562    }
563}
564
565pub assume_specification<Key: Ord, Value, A: AllocatorClone>[ BTreeMap::<Key, Value, A>::insert ](
566    m: &mut BTreeMap<Key, Value, A>,
567    k: Key,
568    v: Value,
569) -> (result: Option<Value>)
570    ensures
571        btree_map_wf(old(m)) ==> btree_map_wf(final(m)),
572        btree_map_insert_ensures(old(m), final(m), k, v, result),
573;
574
575pub broadcast proof fn lemma_btree_map_insert_ensures_if_obeys_cmp_concrete_eq<
576    Key: Ord,
577    Value,
578    A: AllocatorClone,
579>(
580    old_m: &BTreeMap<Key, Value, A>,
581    final_m: &BTreeMap<Key, Value, A>,
582    k: Key,
583    v: Value,
584    result: Option<Value>,
585)
586    requires
587        obeys_cmp::<Key>(),
588        obeys_cmp_concrete_eq::<Key>(),
589        btree_map_inv(old_m),
590        #[trigger] btree_map_insert_ensures::<Key, Value, A>(old_m, final_m, k, v, result),
591    ensures
592        final_m@ == old_m@.insert(k, v),
593        match result {
594            Some(old_value) => old_m@.contains_key(k) && old_value == old_m[k],
595            None => !old_m@.contains_key(k),
596        },
597{
598}
599
600pub broadcast proof fn lemma_btree_map_insert_ensures_if_obeys_cmp_deep_eq<
601    Key: Ord + DeepView,
602    Value: DeepView,
603    A: AllocatorClone,
604>(
605    old_m: &BTreeMap<Key, Value, A>,
606    final_m: &BTreeMap<Key, Value, A>,
607    k: Key,
608    v: Value,
609    result: Option<Value>,
610)
611    requires
612        obeys_cmp::<Key>(),
613        obeys_cmp_deep_eq::<Key>(),
614        btree_map_inv(old_m),
615        #[trigger] btree_map_insert_ensures::<Key, Value, A>(old_m, final_m, k, v, result),
616    ensures
617        final_m.deep_view() == old_m.deep_view().insert(k.deep_view(), v.deep_view()),
618        match result {
619            Some(old_value) => {
620                &&& old_m.deep_view().contains_key(k.deep_view())
621                &&& old_value.deep_view() == old_m.deep_view()[k.deep_view()]
622            },
623            None => !old_m.deep_view().contains_key(k.deep_view()),
624        },
625{
626    broadcast use {
627        crate::map::group_map_lemmas,
628        crate::set::group_set_lemmas,
629        Set::lemma_map_contains,
630    };
631
632    reveal(btree_map_deep_view_impl);
633
634    let stored_key = match result {
635        Some(old_value) => choose|stored_key: Key|
636            {
637                &&& #[trigger] old_m@.contains_key(stored_key)
638                &&& k.cmp_spec(&stored_key) is Equal
639                &&& old_value == old_m@[stored_key]
640                &&& final_m@ == old_m@.insert(stored_key, v)
641            },
642        None => k,
643    };
644
645    assert(final_m@.contains_key(stored_key));
646    assert_maps_equal!(
647        final_m.deep_view(),
648        old_m.deep_view().insert(k.deep_view(), v.deep_view()),
649        kd => {
650            if final_m.deep_view().contains_key(kd) && kd != k.deep_view() {
651                let key = choose|key: Key|
652                    final_m@.contains_key(key) && #[trigger] key.deep_view() == kd;
653                assert(old_m@.contains_key(key));
654            }
655            if old_m.deep_view().contains_key(kd) {
656                let key = choose|key: Key|
657                    old_m@.contains_key(key) && #[trigger] key.deep_view() == kd;
658                assert(final_m@.contains_key(key));
659            }
660        }
661    );
662}
663
664pub open spec fn btree_map_contains_key_ensures<
665    Key: Borrow<Q> + Ord,
666    Value,
667    A: AllocatorClone,
668    Q: Ord + ?Sized,
669>(m: &BTreeMap<Key, Value, A>, k: &Q, result: bool) -> bool {
670    ({
671        &&& obeys_cmp::<Key>()
672        &&& obeys_cmp::<&Q>()
673        &&& <Key as BorrowSpec<Q>>::obeys_borrow_spec()
674        &&& btree_map_inv(m)
675    }) ==> {
676        &&& result == exists|key: Key|
677            {
678                &&& #[trigger] m@.contains_key(key)
679                &&& k.cmp_spec(<Key as BorrowSpec<Q>>::borrow_spec(&key)) is Equal
680            }
681    }
682}
683
684pub assume_specification<
685    Key: Borrow<Q> + Ord,
686    Value,
687    A: AllocatorClone,
688    Q: Ord + ?Sized,
689>[ BTreeMap::<Key, Value, A>::contains_key::<Q> ](m: &BTreeMap<Key, Value, A>, k: &Q) -> (result:
690    bool)
691    requires
692        borrowed_key_ordering_matches::<Key, Q>(),
693    ensures
694        btree_map_contains_key_ensures(m, k, result),
695;
696
697pub broadcast proof fn lemma_btree_map_contains_key_ensures_if_obeys_cmp_concrete_eq<
698    Key: Ord,
699    Value,
700    A: AllocatorClone,
701>(m: &BTreeMap<Key, Value, A>, k: &Key, result: bool)
702    requires
703        obeys_cmp::<Key>(),
704        obeys_cmp_concrete_eq::<Key>(),
705        btree_map_inv(m),
706        #[trigger] btree_map_contains_key_ensures(m, k, result),
707    ensures
708        result == m@.contains_key(*k),
709{
710    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
711
712    reveal(crate::laws_cmp::obeys_cmp_ord);
713}
714
715pub broadcast proof fn lemma_btree_map_contains_key_ensures_if_obeys_cmp_deep_eq<
716    Key: Ord + DeepView,
717    Value: DeepView,
718    A: AllocatorClone,
719>(m: &BTreeMap<Key, Value, A>, k: &Key, result: bool)
720    requires
721        obeys_cmp::<Key>(),
722        obeys_cmp_deep_eq::<Key>(),
723        btree_map_inv(m),
724        #[trigger] btree_map_contains_key_ensures(m, k, result),
725    ensures
726        Key::obeys_cmp_spec(),
727        result == m.deep_view().contains_key(k.deep_view()),
728{
729    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
730    broadcast use {
731        crate::map::group_map_lemmas,
732        crate::set::group_set_lemmas,
733        Set::lemma_map_contains,
734    };
735
736    reveal(crate::laws_cmp::obeys_cmp_ord);
737    reveal(btree_map_deep_view_impl);
738
739    if result {
740        let key = choose|key: Key|
741            {
742                &&& #[trigger] m@.contains_key(key)
743                &&& k.cmp_spec(&key) is Equal
744            };
745        assert(m.deep_view().contains_key(key.deep_view()));
746    }
747    if m.deep_view().contains_key(k.deep_view()) {
748        let key = choose|key: Key|
749            m@.contains_key(key) && #[trigger] key.deep_view() == k.deep_view();
750        assert(k.cmp_spec(&key) is Equal);
751    }
752}
753
754pub open spec fn btree_map_get_ensures<
755    Key: Borrow<Q> + Ord,
756    Value,
757    A: AllocatorClone,
758    Q: Ord + ?Sized,
759>(m: &BTreeMap<Key, Value, A>, k: &Q, result: Option<&Value>) -> bool {
760    ({
761        &&& obeys_cmp::<Key>()
762        &&& obeys_cmp::<&Q>()
763        &&& <Key as BorrowSpec<Q>>::obeys_borrow_spec()
764        &&& btree_map_inv(m)
765    }) ==> {
766        match result {
767            Some(v) => exists|key: Key|
768                {
769                    &&& #[trigger] m@.contains_key(key)
770                    &&& k.cmp_spec(<Key as BorrowSpec<Q>>::borrow_spec(&key)) is Equal
771                    &&& m@[key] == *v
772                },
773            None => forall|key: Key| #[trigger]
774                m@.contains_key(key) ==> !(k.cmp_spec(
775                    <Key as BorrowSpec<Q>>::borrow_spec(&key),
776                ) is Equal),
777        }
778    }
779}
780
781pub assume_specification<
782    'a,
783    Key: Borrow<Q> + Ord,
784    Value,
785    A: AllocatorClone,
786    Q: Ord + ?Sized,
787>[ BTreeMap::<Key, Value, A>::get::<Q> ](m: &'a BTreeMap<Key, Value, A>, k: &Q) -> (result: Option<
788    &'a Value,
789>)
790    requires
791        borrowed_key_ordering_matches::<Key, Q>(),
792    ensures
793        btree_map_get_ensures(m, k, result),
794;
795
796pub broadcast proof fn lemma_btree_map_get_ensures_if_obeys_cmp_concrete_eq<
797    Key: Ord,
798    Value,
799    A: AllocatorClone,
800>(m: &BTreeMap<Key, Value, A>, k: &Key, result: Option<&Value>)
801    requires
802        obeys_cmp::<Key>(),
803        obeys_cmp_concrete_eq::<Key>(),
804        btree_map_inv(m),
805        #[trigger] btree_map_get_ensures(m, k, result),
806    ensures
807        match result {
808            Some(v) => m@.contains_key(*k) && *v == m@[*k],
809            None => !m@.contains_key(*k),
810        },
811{
812    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
813
814    reveal(crate::laws_cmp::obeys_cmp_ord);
815}
816
817pub broadcast proof fn lemma_btree_map_get_ensures_if_obeys_cmp_deep_eq<
818    Key: Ord + DeepView,
819    Value: DeepView,
820    A: AllocatorClone,
821>(m: &BTreeMap<Key, Value, A>, k: &Key, result: Option<&Value>)
822    requires
823        obeys_cmp::<Key>(),
824        obeys_cmp_deep_eq::<Key>(),
825        btree_map_inv(m),
826        #[trigger] btree_map_get_ensures(m, k, result),
827    ensures
828        Key::obeys_cmp_spec(),
829        match result {
830            Some(v) => {
831                &&& m.deep_view().contains_key(k.deep_view())
832                &&& v.deep_view() == m.deep_view()[k.deep_view()]
833            },
834            None => !m.deep_view().contains_key(k.deep_view()),
835        },
836{
837    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
838    broadcast use {
839        crate::map::group_map_lemmas,
840        crate::set::group_set_lemmas,
841        Set::lemma_map_contains,
842    };
843
844    reveal(crate::laws_cmp::obeys_cmp_ord);
845    reveal(btree_map_deep_view_impl);
846
847    match result {
848        Some(v) => {
849            let stored_key = choose|key: Key|
850                {
851                    &&& #[trigger] m@.contains_key(key)
852                    &&& k.cmp_spec(&key) is Equal
853                    &&& m@[key] == *v
854                };
855            assert(m.deep_view().contains_key(k.deep_view()));
856            let key = choose|key: Key|
857                m@.contains_key(key) && #[trigger] key.deep_view() == k.deep_view();
858            assert(key == stored_key);
859        },
860        None => {
861            if m.deep_view().contains_key(k.deep_view()) {
862                let key = choose|key: Key|
863                    m@.contains_key(key) && #[trigger] key.deep_view() == k.deep_view();
864                assert(k.cmp_spec(&key) is Equal);
865            }
866        },
867    }
868}
869
870pub open spec fn btree_map_remove_ensures<
871    Key: Borrow<Q> + Ord,
872    Value,
873    A: AllocatorClone,
874    Q: Ord + ?Sized,
875>(
876    old_m: &BTreeMap<Key, Value, A>,
877    final_m: &BTreeMap<Key, Value, A>,
878    k: &Q,
879    result: Option<Value>,
880) -> bool {
881    ({
882        &&& obeys_cmp::<Key>()
883        &&& obeys_cmp::<&Q>()
884        &&& <Key as BorrowSpec<Q>>::obeys_borrow_spec()
885        &&& btree_map_inv(old_m)
886    }) ==> {
887        &&& btree_map_inv(final_m)
888        &&& match result {
889            Some(v) => exists|key: Key|
890                {
891                    &&& #[trigger] old_m@.contains_key(key)
892                    &&& k.cmp_spec(<Key as BorrowSpec<Q>>::borrow_spec(&key)) is Equal
893                    &&& old_m@[key] == v
894                    &&& final_m@ == old_m@.remove(key)
895                },
896            None => {
897                &&& forall|key: Key| #[trigger]
898                    old_m@.contains_key(key) ==> !(k.cmp_spec(
899                        <Key as BorrowSpec<Q>>::borrow_spec(&key),
900                    ) is Equal)
901                &&& final_m@ == old_m@
902            },
903        }
904    }
905}
906
907pub assume_specification<
908    Key: Borrow<Q> + Ord,
909    Value,
910    A: AllocatorClone,
911    Q: Ord + ?Sized,
912>[ BTreeMap::<Key, Value, A>::remove::<Q> ](m: &mut BTreeMap<Key, Value, A>, k: &Q) -> (result:
913    Option<Value>)
914    requires
915        borrowed_key_ordering_matches::<Key, Q>(),
916    ensures
917        btree_map_wf(old(m)) ==> btree_map_wf(final(m)),
918        btree_map_remove_ensures(old(m), final(m), k, result),
919;
920
921pub broadcast proof fn lemma_btree_map_remove_ensures_if_obeys_cmp_concrete_eq<
922    Key: Ord,
923    Value,
924    A: AllocatorClone,
925>(
926    old_m: &BTreeMap<Key, Value, A>,
927    final_m: &BTreeMap<Key, Value, A>,
928    k: &Key,
929    result: Option<Value>,
930)
931    requires
932        obeys_cmp::<Key>(),
933        obeys_cmp_concrete_eq::<Key>(),
934        btree_map_inv(old_m),
935        #[trigger] btree_map_remove_ensures(old_m, final_m, k, result),
936    ensures
937        final_m@ == old_m@.remove(*k),
938        match result {
939            Some(v) => old_m@.contains_key(*k) && v == old_m@[*k],
940            None => !old_m@.contains_key(*k),
941        },
942{
943    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
944    broadcast use {crate::map::group_map_lemmas, crate::set::group_set_lemmas};
945
946    reveal(crate::laws_cmp::obeys_cmp_ord);
947
948    if result is None {
949        assert(!old_m@.contains_key(*k));
950        assert(old_m@.remove(*k) =~= old_m@);
951    }
952}
953
954pub broadcast proof fn lemma_btree_map_remove_ensures_if_obeys_cmp_deep_eq<
955    Key: Ord + DeepView,
956    Value: DeepView,
957    A: AllocatorClone,
958>(
959    old_m: &BTreeMap<Key, Value, A>,
960    final_m: &BTreeMap<Key, Value, A>,
961    k: &Key,
962    result: Option<Value>,
963)
964    requires
965        obeys_cmp::<Key>(),
966        obeys_cmp_deep_eq::<Key>(),
967        btree_map_inv(old_m),
968        #[trigger] btree_map_remove_ensures(old_m, final_m, k, result),
969    ensures
970        Key::obeys_cmp_spec(),
971        final_m.deep_view() == old_m.deep_view().remove(k.deep_view()),
972        match result {
973            Some(v) => {
974                &&& old_m.deep_view().contains_key(k.deep_view())
975                &&& v.deep_view() == old_m.deep_view()[k.deep_view()]
976            },
977            None => !old_m.deep_view().contains_key(k.deep_view()),
978        },
979{
980    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
981    broadcast use {
982        crate::map::group_map_lemmas,
983        crate::set::group_set_lemmas,
984        Set::lemma_map_contains,
985    };
986
987    reveal(crate::laws_cmp::obeys_cmp_ord);
988    reveal(btree_map_deep_view_impl);
989
990    let stored_key = match result {
991        Some(v) => choose|key: Key|
992            {
993                &&& #[trigger] old_m@.contains_key(key)
994                &&& k.cmp_spec(&key) is Equal
995                &&& old_m@[key] == v
996                &&& final_m@ == old_m@.remove(key)
997            },
998        None => *k,
999    };
1000
1001    match result {
1002        Some(v) => {
1003            assert(old_m.deep_view().contains_key(k.deep_view()));
1004            let key = choose|key: Key|
1005                old_m@.contains_key(key) && #[trigger] key.deep_view() == k.deep_view();
1006            assert(key == stored_key);
1007        },
1008        None => {
1009            if old_m.deep_view().contains_key(k.deep_view()) {
1010                let key = choose|key: Key|
1011                    old_m@.contains_key(key) && #[trigger] key.deep_view() == k.deep_view();
1012                assert(k.cmp_spec(&key) is Equal);
1013            }
1014        },
1015    }
1016
1017    assert_maps_equal!(
1018        final_m.deep_view(),
1019        old_m.deep_view().remove(k.deep_view()),
1020        kd => {
1021            if final_m.deep_view().contains_key(kd) {
1022                let key = choose|key: Key|
1023                    final_m@.contains_key(key) && #[trigger] key.deep_view() == kd;
1024                assert(old_m@.contains_key(key));
1025                assert(key.deep_view() != k.deep_view());
1026            }
1027            if old_m.deep_view().contains_key(kd) && kd != k.deep_view() {
1028                let key = choose|key: Key|
1029                    old_m@.contains_key(key) && #[trigger] key.deep_view() == kd;
1030                assert(final_m@.contains_key(key));
1031            }
1032        }
1033    );
1034}
1035
1036pub open spec fn btree_map_get_mut_ensures<
1037    Key: Borrow<Q> + Ord,
1038    Value,
1039    A: AllocatorClone,
1040    Q: Ord + ?Sized,
1041>(
1042    old_m: &BTreeMap<Key, Value, A>,
1043    final_m: &BTreeMap<Key, Value, A>,
1044    k: &Q,
1045    result: Option<(Value, Value)>,
1046) -> bool {
1047    ({
1048        &&& obeys_cmp::<Key>()
1049        &&& obeys_cmp::<&Q>()
1050        &&& <Key as BorrowSpec<Q>>::obeys_borrow_spec()
1051        &&& btree_map_inv(old_m)
1052    }) ==> {
1053        &&& btree_map_inv(final_m)
1054        &&& match result {
1055            Some((current_value, final_value)) => exists|stored_key: Key|
1056                {
1057                    &&& #[trigger] old_m@.contains_key(stored_key)
1058                    &&& k.cmp_spec(<Key as BorrowSpec<Q>>::borrow_spec(&stored_key)) is Equal
1059                    &&& old_m@[stored_key] == current_value
1060                    &&& final_m@ == old_m@.insert(stored_key, final_value)
1061                },
1062            None => {
1063                &&& forall|stored_key: Key| #[trigger]
1064                    old_m@.contains_key(stored_key) ==> !(k.cmp_spec(
1065                        <Key as BorrowSpec<Q>>::borrow_spec(&stored_key),
1066                    ) is Equal)
1067                &&& final_m@ == old_m@
1068            },
1069        }
1070    }
1071}
1072
1073/// Specification for [`BTreeMap::get_mut`].
1074pub assume_specification<
1075    'a,
1076    Key: Borrow<Q> + Ord,
1077    Value,
1078    A: AllocatorClone,
1079    Q: Ord + ?Sized,
1080>[ BTreeMap::<Key, Value, A>::get_mut::<Q> ](
1081    m: &'a mut BTreeMap<Key, Value, A>,
1082    key: &Q,
1083) -> (result: Option<&'a mut Value>)
1084    requires
1085        borrowed_key_ordering_matches::<Key, Q>(),
1086    ensures
1087        btree_map_wf(old(m)) ==> btree_map_wf(final(m)),
1088        match result {
1089            Some(value) => btree_map_get_mut_ensures(
1090                old(m),
1091                final(m),
1092                key,
1093                Some((*value, *final(value))),
1094            ),
1095            None => btree_map_get_mut_ensures(old(m), final(m), key, None),
1096        },
1097;
1098
1099pub broadcast proof fn lemma_btree_map_get_mut_ensures_if_obeys_cmp_concrete_eq<
1100    Key: Ord,
1101    Value,
1102    A: AllocatorClone,
1103>(
1104    old_m: &BTreeMap<Key, Value, A>,
1105    final_m: &BTreeMap<Key, Value, A>,
1106    k: &Key,
1107    result: Option<(Value, Value)>,
1108)
1109    requires
1110        obeys_cmp::<Key>(),
1111        obeys_cmp_concrete_eq::<Key>(),
1112        btree_map_inv(old_m),
1113        #[trigger] btree_map_get_mut_ensures(old_m, final_m, k, result),
1114    ensures
1115        match result {
1116            Some((current_value, final_value)) => {
1117                &&& old_m@.contains_key(*k)
1118                &&& current_value == old_m@[*k]
1119                &&& final_m@ == old_m@.insert(*k, final_value)
1120            },
1121            None => {
1122                &&& !old_m@.contains_key(*k)
1123                &&& final_m@ == old_m@
1124            },
1125        },
1126{
1127    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
1128
1129    reveal(crate::laws_cmp::obeys_cmp_ord);
1130}
1131
1132pub broadcast proof fn lemma_btree_map_get_mut_ensures_if_obeys_cmp_deep_eq<
1133    Key: Ord + DeepView,
1134    Value: DeepView,
1135    A: AllocatorClone,
1136>(
1137    old_m: &BTreeMap<Key, Value, A>,
1138    final_m: &BTreeMap<Key, Value, A>,
1139    k: &Key,
1140    result: Option<(Value, Value)>,
1141)
1142    requires
1143        obeys_cmp::<Key>(),
1144        obeys_cmp_deep_eq::<Key>(),
1145        btree_map_inv(old_m),
1146        #[trigger] btree_map_get_mut_ensures(old_m, final_m, k, result),
1147    ensures
1148        Key::obeys_cmp_spec(),
1149        match result {
1150            Some((current_value, final_value)) => {
1151                &&& old_m.deep_view().contains_key(k.deep_view())
1152                &&& current_value.deep_view() == old_m.deep_view()[k.deep_view()]
1153                &&& final_m.deep_view() == old_m.deep_view().insert(
1154                    k.deep_view(),
1155                    final_value.deep_view(),
1156                )
1157            },
1158            None => {
1159                &&& !old_m.deep_view().contains_key(k.deep_view())
1160                &&& final_m.deep_view() == old_m.deep_view()
1161            },
1162        },
1163{
1164    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
1165
1166    reveal(crate::laws_cmp::obeys_cmp_ord);
1167
1168    match result {
1169        Some((current_value, final_value)) => {
1170            lemma_btree_map_insert_ensures_if_obeys_cmp_deep_eq(
1171                old_m,
1172                final_m,
1173                *k,
1174                final_value,
1175                Some(current_value),
1176            );
1177        },
1178        None => {
1179            broadcast use {
1180                crate::map::group_map_lemmas,
1181                crate::set::group_set_lemmas,
1182                Set::lemma_map_contains,
1183            };
1184
1185            reveal(btree_map_deep_view_impl);
1186
1187            if old_m.deep_view().contains_key(k.deep_view()) {
1188                let key = choose|key: Key|
1189                    old_m@.contains_key(key) && #[trigger] key.deep_view() == k.deep_view();
1190                assert(k.cmp_spec(&key) is Equal);
1191            }
1192        },
1193    }
1194}
1195
1196pub assume_specification<Key, Value, A: AllocatorClone>[ BTreeMap::<Key, Value, A>::clear ](
1197    m: &mut BTreeMap<Key, Value, A>,
1198)
1199    ensures
1200        final(m)@ == Map::<Key, Value>::empty(),
1201        btree_map_wf(final(m)),
1202;
1203
1204/// Specification for [`BTreeMap::lower_bound_mut`].
1205pub assume_specification<
1206    'a,
1207    Key: Borrow<Q> + Ord,
1208    Value,
1209    A: AllocatorClone,
1210    Q: Ord + ?Sized,
1211>[ BTreeMap::<Key, Value, A>::lower_bound_mut::<Q> ](
1212    map: &'a mut BTreeMap<Key, Value, A>,
1213    bound: Bound<&Q>,
1214) -> (cursor: CursorMut<'a, Key, Value, A>)
1215    requires
1216        borrowed_key_ordering_matches::<Key, Q>(),
1217    ensures
1218// the cursor's operations keep the entries in order, and describe the map only if it is
1219// well formed
1220
1221        btree_map_wf(old(map)) ==> btree_map_wf(final(map)),
1222        ({
1223            &&& obeys_cmp::<Key>()
1224            &&& obeys_cmp::<&Q>()
1225            &&& <Key as BorrowSpec<Q>>::obeys_borrow_spec()
1226            &&& btree_map_wf(old(map))
1227        }) ==> {
1228            &&& cursor@.wf()
1229            &&& cursor@.map == old(map)@
1230            &&& final(map)@ == cursor.final_map()
1231            &&& positioned_at_lower_bound(cursor@, bound)
1232        },
1233;
1234
1235/// Specification for [`BTreeMap::upper_bound_mut`].
1236pub assume_specification<
1237    'a,
1238    Key: Borrow<Q> + Ord,
1239    Value,
1240    A: AllocatorClone,
1241    Q: Ord + ?Sized,
1242>[ BTreeMap::<Key, Value, A>::upper_bound_mut::<Q> ](
1243    map: &'a mut BTreeMap<Key, Value, A>,
1244    bound: Bound<&Q>,
1245) -> (cursor: CursorMut<'a, Key, Value, A>)
1246    requires
1247        borrowed_key_ordering_matches::<Key, Q>(),
1248    ensures
1249// the cursor's operations keep the entries in order, and describe the map only if it is
1250// well formed
1251
1252        btree_map_wf(old(map)) ==> btree_map_wf(final(map)),
1253        ({
1254            &&& obeys_cmp::<Key>()
1255            &&& obeys_cmp::<&Q>()
1256            &&& <Key as BorrowSpec<Q>>::obeys_borrow_spec()
1257            &&& btree_map_wf(old(map))
1258        }) ==> {
1259            &&& cursor@.wf()
1260            &&& cursor@.map == old(map)@
1261            &&& final(map)@ == cursor.final_map()
1262            &&& positioned_at_upper_bound(cursor@, bound)
1263        },
1264;
1265
1266/// Specification for [`CursorMut::next`].
1267pub assume_specification<'a, 'b, Key, Value, A>[ CursorMut::<'a, Key, Value, A>::next ](
1268    cursor: &'b mut CursorMut<'a, Key, Value, A>,
1269) -> (result: Option<(&'b Key, &'b mut Value)>)
1270    requires
1271        old(cursor)@.wf(),
1272    ensures
1273        final(cursor).final_map() == old(cursor).final_map(),
1274        final(cursor)@.wf(),
1275        match result {
1276            Some((key, value)) => {
1277                let old_model = old(cursor)@;
1278                let new_model = final(cursor)@;
1279                &&& old_model.position < old_model.keys.len()
1280                &&& *key == old_model.keys[old_model.position]
1281                &&& *value == old_model.map[*key]
1282                &&& new_model.keys == old_model.keys
1283                &&& new_model.position == old_model.position + 1
1284                &&& new_model.map == old_model.map.insert(*key, *final(value))
1285            },
1286            None => {
1287                &&& old(cursor)@.position == old(cursor)@.keys.len()
1288                &&& final(cursor)@ == old(cursor)@
1289            },
1290        },
1291;
1292
1293/// Specification for [`CursorMut::prev`].
1294pub assume_specification<'a, 'b, Key, Value, A>[ CursorMut::<'a, Key, Value, A>::prev ](
1295    cursor: &'b mut CursorMut<'a, Key, Value, A>,
1296) -> (result: Option<(&'b Key, &'b mut Value)>)
1297    requires
1298        old(cursor)@.wf(),
1299    ensures
1300        final(cursor).final_map() == old(cursor).final_map(),
1301        final(cursor)@.wf(),
1302        match result {
1303            Some((key, value)) => {
1304                let old_model = old(cursor)@;
1305                let new_model = final(cursor)@;
1306                &&& old_model.position > 0
1307                &&& *key == old_model.keys[old_model.position - 1]
1308                &&& *value == old_model.map[*key]
1309                &&& new_model.keys == old_model.keys
1310                &&& new_model.position == old_model.position - 1
1311                &&& new_model.map == old_model.map.insert(*key, *final(value))
1312            },
1313            None => {
1314                &&& old(cursor)@.position == 0
1315                &&& final(cursor)@ == old(cursor)@
1316            },
1317        },
1318;
1319
1320/// Specification for [`CursorMut::peek_prev`].
1321pub assume_specification<'a, 'b, Key, Value, A>[ CursorMut::<'a, Key, Value, A>::peek_prev ](
1322    cursor: &'b mut CursorMut<'a, Key, Value, A>,
1323) -> (result: Option<(&'b Key, &'b mut Value)>)
1324    requires
1325        old(cursor)@.wf(),
1326    ensures
1327        final(cursor).final_map() == old(cursor).final_map(),
1328        final(cursor)@.wf(),
1329        match result {
1330            Some((key, value)) => {
1331                let old_model = old(cursor)@;
1332                let new_model = final(cursor)@;
1333                &&& old_model.position > 0
1334                &&& *key == old_model.keys[old_model.position - 1]
1335                &&& *value == old_model.map[*key]
1336                &&& new_model.keys == old_model.keys
1337                &&& new_model.position == old_model.position
1338                &&& new_model.map == old_model.map.insert(*key, *final(value))
1339            },
1340            None => {
1341                &&& old(cursor)@.position == 0
1342                &&& final(cursor)@ == old(cursor)@
1343            },
1344        },
1345;
1346
1347/// Specification for [`CursorMut::peek_next`].
1348pub assume_specification<'a, 'b, Key, Value, A>[ CursorMut::<'a, Key, Value, A>::peek_next ](
1349    cursor: &'b mut CursorMut<'a, Key, Value, A>,
1350) -> (result: Option<(&'b Key, &'b mut Value)>)
1351    requires
1352        old(cursor)@.wf(),
1353    ensures
1354        final(cursor).final_map() == old(cursor).final_map(),
1355        final(cursor)@.wf(),
1356        match result {
1357            Some((key, value)) => {
1358                let old_model = old(cursor)@;
1359                let new_model = final(cursor)@;
1360                &&& old_model.position < old_model.keys.len()
1361                &&& *key == old_model.keys[old_model.position]
1362                &&& *value == old_model.map[*key]
1363                &&& new_model.keys == old_model.keys
1364                &&& new_model.position == old_model.position
1365                &&& new_model.map == old_model.map.insert(*key, *final(value))
1366            },
1367            None => {
1368                &&& old(cursor)@.position == old(cursor)@.keys.len()
1369                &&& final(cursor)@ == old(cursor)@
1370            },
1371        },
1372;
1373
1374/// Specification for [`CursorMut::insert_after`].
1375pub assume_specification<'a, Key: Ord, Value, A: AllocatorClone>[ CursorMut::<
1376    'a,
1377    Key,
1378    Value,
1379    A,
1380>::insert_after ](cursor: &mut CursorMut<'a, Key, Value, A>, key: Key, value: Value) -> (result:
1381    Result<(), UnorderedKeyError>)
1382    requires
1383        old(cursor)@.wf(),
1384    ensures
1385        final(cursor).final_map() == old(cursor).final_map(),
1386        obeys_cmp::<Key>() ==> {
1387            &&& final(cursor)@.wf()
1388            &&& match result {
1389                Ok(()) => {
1390                    let old_model = old(cursor)@;
1391                    let new_model = final(cursor)@;
1392                    &&& key_fits_at_position(old_model, key)
1393                    &&& new_model.keys == old_model.keys.insert(old_model.position, key)
1394                    &&& new_model.position == old_model.position
1395                    &&& new_model.map == old_model.map.insert(key, value)
1396                },
1397                Err(_) => {
1398                    &&& !key_fits_at_position(old(cursor)@, key)
1399                    &&& final(cursor)@ == old(cursor)@
1400                },
1401            }
1402        },
1403;
1404
1405/// Specification for [`CursorMut::remove_next`].
1406pub assume_specification<'a, Key: Ord, Value, A: AllocatorClone>[ CursorMut::<
1407    'a,
1408    Key,
1409    Value,
1410    A,
1411>::remove_next ](cursor: &mut CursorMut<'a, Key, Value, A>) -> (result: Option<(Key, Value)>)
1412    requires
1413        old(cursor)@.wf(),
1414    ensures
1415        final(cursor).final_map() == old(cursor).final_map(),
1416        final(cursor)@.wf(),
1417        match result {
1418            Some((key, value)) => {
1419                let old_model = old(cursor)@;
1420                let new_model = final(cursor)@;
1421                &&& old_model.position < old_model.keys.len()
1422                &&& key == old_model.keys[old_model.position]
1423                &&& value == old_model.map[key]
1424                &&& new_model.keys == old_model.keys.remove(old_model.position)
1425                &&& new_model.position == old_model.position
1426                &&& new_model.map == old_model.map.remove(key)
1427            },
1428            None => {
1429                &&& old(cursor)@.position == old(cursor)@.keys.len()
1430                &&& final(cursor)@ == old(cursor)@
1431            },
1432        },
1433;
1434
1435pub assume_specification<'a, Key, Value, A: AllocatorClone>[ BTreeMap::<Key, Value, A>::keys ](
1436    m: &'a BTreeMap<Key, Value, A>,
1437) -> (keys: Keys<'a, Key, Value>)
1438    ensures
1439        key_obeys_cmp_spec::<Key>() && btree_map_wf(m) ==> {
1440            &&& IteratorSpec::remaining(&keys).unref().to_set() == m@.dom()
1441            &&& IteratorSpec::remaining(&keys).no_duplicates()
1442            &&& IteratorSpec::remaining(&keys).len() == m@.dom().len()
1443            &&& IteratorSpec::remaining(&keys).len() == m.len()
1444            &&& increasing_seq(IteratorSpec::remaining(&keys))
1445            &&& into_iter_keys(keys) == IteratorSpec::remaining(&keys).unref()
1446            &&& IteratorSpec::decrease(&keys) is Some
1447        },
1448;
1449
1450pub assume_specification<'a, Key, Value, A: AllocatorClone>[ BTreeMap::<Key, Value, A>::values ](
1451    m: &'a BTreeMap<Key, Value, A>,
1452) -> (values: Values<'a, Key, Value>)
1453    ensures
1454        key_obeys_cmp_spec::<Key>() && btree_map_wf(m) ==> {
1455            &&& IteratorSpec::remaining(&values).unref().to_set() == m@.values()
1456            &&& IteratorSpec::remaining(&values).len() == m@.dom().len()
1457            &&& IteratorSpec::remaining(&values).len() == m.len()
1458            &&& into_iter_values(values) == IteratorSpec::remaining(&values).unref()
1459            &&& IteratorSpec::decrease(&values) is Some
1460            &&& exists|key_seq: Seq<Key>|
1461                {
1462                    &&& increasing_seq(key_seq)
1463                    &&& key_seq.to_set() == m@.dom()
1464                    &&& key_seq.no_duplicates()
1465                    &&& IteratorSpec::remaining(&values) == key_seq.map(|i: int, k| &m@[k])
1466                }
1467        },
1468;
1469
1470pub broadcast axiom fn axiom_btree_map_decreases<Key, Value, A: AllocatorClone>(
1471    m: BTreeMap<Key, Value, A>,
1472)
1473    ensures
1474        #[trigger] (decreases_to!(m => m@)),
1475;
1476
1477// The `iter` method of a `BTreeSet` returns an iterator of type `btree_set::Iter`,
1478// so we specify that type here.
1479#[verifier::external_type_specification]
1480#[verifier::external_body]
1481#[verifier::accept_recursive_types(K)]
1482pub struct ExSetIter<'a, K: 'a>(btree_set::Iter<'a, K>);
1483
1484// To allow reasoning about the "contents" of the BtreeSet iterator, without using
1485// a prophecy, we need a function that gives us the underlying sequence of the original keys.
1486pub uninterp spec fn into_iter_btree_keys<'a, Key>(i: btree_set::Iter::<'a, Key>) -> Seq<Key>;
1487
1488impl<'a, T> super::iter::IteratorSpecImpl for btree_set::Iter::<'a, T> {
1489    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
1490        true
1491    }
1492
1493    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
1494
1495    #[verifier::prophetic]
1496    open spec fn produces(&self) -> Seq<bool> {
1497        Seq::new(IteratorSpec::remaining(self).len(), |i: int| true)
1498    }
1499
1500    uninterp spec fn decrease(&self) -> Option<nat>;
1501
1502    open spec fn peek(&self, index: int) -> Option<Self::Item> {
1503        if 0 <= index < into_iter_btree_keys(*self).len() {
1504            Some(&into_iter_btree_keys(*self)[index])
1505        } else {
1506            None
1507        }
1508    }
1509}
1510
1511/// Specifications for the behavior of [`alloc::collections::BTreeSet`](https://doc.rust-lang.org/alloc/collections/struct.BTreeSet.html).
1512///
1513/// We model a `BTreeSet` as having a view of type `Set<Key>`, which reflects the current state of the set.
1514///
1515/// These specifications are only meaningful if `obeys_cmp::<Key>()` hold.
1516/// See [`obeys_cmp`] for information on use with primitive types and custom types.
1517///
1518/// Axioms about the behavior of BTreeSet are present in the broadcast group `vstd::std_specs::btree::group_btree_axioms`.
1519#[verifier::external_type_specification]
1520#[verifier::external_body]
1521#[verifier::accept_recursive_types(Key)]
1522#[verifier::reject_recursive_types(A)]
1523pub struct ExBTreeSet<Key, A: AllocatorClone>(BTreeSet<Key, A>);
1524
1525impl<Key, A: AllocatorClone> View for BTreeSet<Key, A> {
1526    type V = Set<Key>;
1527
1528    uninterp spec fn view(&self) -> Set<Key>;
1529}
1530
1531impl<Key: DeepView, A: AllocatorClone> DeepView for BTreeSet<Key, A> {
1532    type V = Set<Key::V>;
1533
1534    open spec fn deep_view(&self) -> Set<Key::V> {
1535        self@.map(|x: Key| x.deep_view())
1536    }
1537}
1538
1539/// Whether the set's elements are arranged as the tree requires; see [`btree_map_wf`].
1540pub uninterp spec fn btree_set_wf<Key, A: AllocatorClone>(m: &BTreeSet<Key, A>) -> bool;
1541
1542pub open spec fn btree_set_inv<Key: Ord, A: AllocatorClone>(m: &BTreeSet<Key, A>) -> bool {
1543    &&& btree_set_wf(m)
1544    &&& forall|k1: Key, k2: Key|
1545        {
1546            &&& #[trigger] m@.contains(k1)
1547            &&& #[trigger] m@.contains(k2)
1548            &&& k1 != k2
1549        } ==> !(k1.cmp_spec(&k2) is Equal)
1550}
1551
1552pub uninterp spec fn spec_btree_set_len<Key, A: AllocatorClone>(m: &BTreeSet<Key, A>) -> usize;
1553
1554pub broadcast axiom fn axiom_spec_btree_set_len<Key, A: AllocatorClone>(m: &BTreeSet<Key, A>)
1555    ensures
1556        key_obeys_cmp_spec::<Key>() ==> #[trigger] spec_btree_set_len(m) == m@.len(),
1557;
1558
1559#[verifier::when_used_as_spec(spec_btree_set_len)]
1560pub assume_specification<Key, A: AllocatorClone>[ BTreeSet::<Key, A>::len ](
1561    m: &BTreeSet<Key, A>,
1562) -> (len: usize)
1563    ensures
1564        len == spec_btree_set_len(m),
1565;
1566
1567pub assume_specification<Key, A: AllocatorClone>[ BTreeSet::<Key, A>::is_empty ](
1568    m: &BTreeSet<Key, A>,
1569) -> (res: bool)
1570    ensures
1571        res == m@.is_empty(),
1572;
1573
1574pub assume_specification<K: Clone, A: AllocatorClone>[ <BTreeSet::<K, A> as Clone>::clone ](
1575    this: &BTreeSet<K, A>,
1576) -> (other: BTreeSet<K, A>)
1577    ensures
1578// The elements are cloned; only elements that clone to equal values leave them
1579// unchanged (and the copy well formed).
1580
1581        obeys_clone_eq::<K>() ==> other@ == this@,
1582        obeys_clone_eq::<K>() && btree_set_wf(this) ==> btree_set_wf(&other),
1583;
1584
1585pub assume_specification<Key>[ BTreeSet::<Key>::new ]() -> (m: BTreeSet<Key>)
1586    ensures
1587        m@ == Set::<Key>::empty(),
1588        btree_set_wf(&m),
1589;
1590
1591pub assume_specification<T>[ <BTreeSet<T> as core::default::Default>::default ]() -> (m: BTreeSet<
1592    T,
1593>)
1594    ensures
1595        m@ == Set::<T>::empty(),
1596        btree_set_wf(&m),
1597;
1598
1599pub open spec fn btree_set_insert_ensures<Key: Ord, A: AllocatorClone>(
1600    old_m: &BTreeSet<Key, A>,
1601    final_m: &BTreeSet<Key, A>,
1602    k: Key,
1603    result: bool,
1604) -> bool {
1605    obeys_cmp::<Key>() && btree_set_inv(old_m) ==> {
1606        &&& btree_set_inv(final_m)
1607        &&& if result {
1608            &&& forall|stored_key: Key| #[trigger]
1609                old_m@.contains(stored_key) ==> !(k.cmp_spec(&stored_key) is Equal)
1610            &&& final_m@ == old_m@.insert(k)
1611        } else {
1612            &&& exists|stored_key: Key| #[trigger]
1613                old_m@.contains(stored_key) && k.cmp_spec(&stored_key) is Equal
1614            &&& final_m@ == old_m@
1615        }
1616    }
1617}
1618
1619pub assume_specification<Key: Ord, A: AllocatorClone>[ BTreeSet::<Key, A>::insert ](
1620    m: &mut BTreeSet<Key, A>,
1621    k: Key,
1622) -> (result: bool)
1623    ensures
1624        btree_set_wf(old(m)) ==> btree_set_wf(final(m)),
1625        btree_set_insert_ensures(old(m), final(m), k, result),
1626;
1627
1628pub broadcast proof fn lemma_btree_set_insert_ensures_if_obeys_cmp_concrete_eq<
1629    Key: Ord,
1630    A: AllocatorClone,
1631>(old_m: &BTreeSet<Key, A>, final_m: &BTreeSet<Key, A>, k: Key, result: bool)
1632    requires
1633        obeys_cmp::<Key>(),
1634        obeys_cmp_concrete_eq::<Key>(),
1635        btree_set_inv(old_m),
1636        #[trigger] btree_set_insert_ensures::<Key, A>(old_m, final_m, k, result),
1637    ensures
1638        final_m@ == old_m@.insert(k),
1639        result == !old_m@.contains(k),
1640{
1641    broadcast use crate::set::group_set_lemmas;
1642
1643    assert(k.cmp_spec(&k) is Equal);
1644    if !result {
1645        assert(old_m@.contains(k));
1646        assert(old_m@.insert(k) =~= old_m@);
1647    }
1648}
1649
1650pub broadcast proof fn lemma_btree_set_insert_ensures_if_obeys_cmp_deep_eq<
1651    Key: Ord + DeepView,
1652    A: AllocatorClone,
1653>(old_m: &BTreeSet<Key, A>, final_m: &BTreeSet<Key, A>, k: Key, result: bool)
1654    requires
1655        obeys_cmp::<Key>(),
1656        obeys_cmp_deep_eq::<Key>(),
1657        btree_set_inv(old_m),
1658        #[trigger] btree_set_insert_ensures::<Key, A>(old_m, final_m, k, result),
1659    ensures
1660        final_m.deep_view() == old_m.deep_view().insert(k.deep_view()),
1661        result == !old_m.deep_view().contains(k.deep_view()),
1662{
1663    broadcast use {
1664        crate::set::group_set_lemmas,
1665        Set::lemma_map_contains,
1666        Set::lemma_set_map_insert_commute,
1667    };
1668
1669    if result {
1670        assert(!old_m.deep_view().contains(k.deep_view())) by {
1671            if old_m.deep_view().contains(k.deep_view()) {
1672                let stored_key = choose|stored_key: Key|
1673                    old_m@.contains(stored_key) && #[trigger] stored_key.deep_view()
1674                        == k.deep_view();
1675                assert(k.cmp_spec(&stored_key) is Equal);
1676            }
1677        }
1678    } else {
1679        let stored_key = choose|stored_key: Key| #[trigger]
1680            old_m@.contains(stored_key) && k.cmp_spec(&stored_key) is Equal;
1681        assert(stored_key.deep_view() == k.deep_view());
1682        assert(old_m.deep_view().contains(k.deep_view()));
1683    }
1684    assert(final_m.deep_view() =~= old_m.deep_view().insert(k.deep_view()));
1685}
1686
1687pub open spec fn btree_set_contains_ensures<
1688    Key: Borrow<Q> + Ord,
1689    A: AllocatorClone,
1690    Q: Ord + ?Sized,
1691>(m: &BTreeSet<Key, A>, k: &Q, result: bool) -> bool {
1692    ({
1693        &&& obeys_cmp::<Key>()
1694        &&& obeys_cmp::<&Q>()
1695        &&& <Key as BorrowSpec<Q>>::obeys_borrow_spec()
1696        &&& btree_set_inv(m)
1697    }) ==> {
1698        &&& result == exists|key: Key|
1699            {
1700                &&& #[trigger] m@.contains(key)
1701                &&& k.cmp_spec(<Key as BorrowSpec<Q>>::borrow_spec(&key)) is Equal
1702            }
1703    }
1704}
1705
1706pub assume_specification<Key: Borrow<Q> + Ord, A: AllocatorClone, Q: Ord + ?Sized>[ BTreeSet::<
1707    Key,
1708    A,
1709>::contains ](m: &BTreeSet<Key, A>, k: &Q) -> (result: bool)
1710    requires
1711        borrowed_key_ordering_matches::<Key, Q>(),
1712    ensures
1713        btree_set_contains_ensures(m, k, result),
1714;
1715
1716pub broadcast proof fn lemma_btree_set_contains_ensures_if_obeys_cmp_concrete_eq<
1717    Key: Ord,
1718    A: AllocatorClone,
1719>(m: &BTreeSet<Key, A>, k: &Key, result: bool)
1720    requires
1721        obeys_cmp::<Key>(),
1722        obeys_cmp_concrete_eq::<Key>(),
1723        btree_set_inv(m),
1724        #[trigger] btree_set_contains_ensures(m, k, result),
1725    ensures
1726        result == m@.contains(*k),
1727{
1728    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
1729
1730    reveal(crate::laws_cmp::obeys_cmp_ord);
1731}
1732
1733pub broadcast proof fn lemma_btree_set_contains_ensures_if_obeys_cmp_deep_eq<
1734    Key: Ord + DeepView,
1735    A: AllocatorClone,
1736>(m: &BTreeSet<Key, A>, k: &Key, result: bool)
1737    requires
1738        obeys_cmp::<Key>(),
1739        obeys_cmp_deep_eq::<Key>(),
1740        btree_set_inv(m),
1741        #[trigger] btree_set_contains_ensures(m, k, result),
1742    ensures
1743        Key::obeys_cmp_spec(),
1744        result == m.deep_view().contains(k.deep_view()),
1745{
1746    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
1747    broadcast use {crate::set::group_set_lemmas, Set::lemma_map_contains};
1748
1749    reveal(crate::laws_cmp::obeys_cmp_ord);
1750
1751    if result {
1752        let key = choose|key: Key|
1753            {
1754                &&& #[trigger] m@.contains(key)
1755                &&& k.cmp_spec(&key) is Equal
1756            };
1757        assert(m.deep_view().contains(key.deep_view()));
1758    }
1759    if m.deep_view().contains(k.deep_view()) {
1760        let key = choose|key: Key| m@.contains(key) && #[trigger] key.deep_view() == k.deep_view();
1761        assert(k.cmp_spec(&key) is Equal);
1762    }
1763}
1764
1765pub open spec fn btree_set_get_ensures<Key: Borrow<Q> + Ord, A: AllocatorClone, Q: Ord + ?Sized>(
1766    m: &BTreeSet<Key, A>,
1767    k: &Q,
1768    result: Option<&Key>,
1769) -> bool {
1770    ({
1771        &&& obeys_cmp::<Key>()
1772        &&& obeys_cmp::<&Q>()
1773        &&& <Key as BorrowSpec<Q>>::obeys_borrow_spec()
1774        &&& btree_set_inv(m)
1775    }) ==> {
1776        &&& match result {
1777            Some(key) => {
1778                &&& m@.contains(*key)
1779                &&& k.cmp_spec(<Key as BorrowSpec<Q>>::borrow_spec(key)) is Equal
1780            },
1781            None => forall|key: Key| #[trigger]
1782                m@.contains(key) ==> !(k.cmp_spec(
1783                    <Key as BorrowSpec<Q>>::borrow_spec(&key),
1784                ) is Equal),
1785        }
1786    }
1787}
1788
1789pub assume_specification<'a, Key: Borrow<Q> + Ord, A: AllocatorClone, Q: Ord + ?Sized>[ BTreeSet::<
1790    Key,
1791    A,
1792>::get::<Q> ](m: &'a BTreeSet<Key, A>, k: &Q) -> (result: Option<&'a Key>)
1793    requires
1794        borrowed_key_ordering_matches::<Key, Q>(),
1795    ensures
1796        btree_set_get_ensures(m, k, result),
1797;
1798
1799pub broadcast proof fn lemma_btree_set_get_ensures_if_obeys_cmp_concrete_eq<
1800    Key: Ord,
1801    A: AllocatorClone,
1802>(m: &BTreeSet<Key, A>, k: &Key, result: Option<&Key>)
1803    requires
1804        obeys_cmp::<Key>(),
1805        obeys_cmp_concrete_eq::<Key>(),
1806        btree_set_inv(m),
1807        #[trigger] btree_set_get_ensures(m, k, result),
1808    ensures
1809        match result {
1810            Some(key) => m@.contains(*key) && *key == *k,
1811            None => !m@.contains(*k),
1812        },
1813{
1814    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
1815
1816    reveal(crate::laws_cmp::obeys_cmp_ord);
1817}
1818
1819pub broadcast proof fn lemma_btree_set_get_ensures_if_obeys_cmp_deep_eq<
1820    Key: Ord + DeepView,
1821    A: AllocatorClone,
1822>(m: &BTreeSet<Key, A>, k: &Key, result: Option<&Key>)
1823    requires
1824        obeys_cmp::<Key>(),
1825        obeys_cmp_deep_eq::<Key>(),
1826        btree_set_inv(m),
1827        #[trigger] btree_set_get_ensures(m, k, result),
1828    ensures
1829        Key::obeys_cmp_spec(),
1830        match result {
1831            Some(key) => {
1832                &&& m@.contains(*key)
1833                &&& m.deep_view().contains(k.deep_view())
1834                &&& key.deep_view() == k.deep_view()
1835            },
1836            None => !m.deep_view().contains(k.deep_view()),
1837        },
1838{
1839    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
1840    broadcast use {crate::set::group_set_lemmas, Set::lemma_map_contains};
1841
1842    reveal(crate::laws_cmp::obeys_cmp_ord);
1843
1844    match result {
1845        Some(key) => {
1846            assert(m.deep_view().contains(key.deep_view()));
1847        },
1848        None => {
1849            if m.deep_view().contains(k.deep_view()) {
1850                let key = choose|key: Key|
1851                    m@.contains(key) && #[trigger] key.deep_view() == k.deep_view();
1852                assert(k.cmp_spec(&key) is Equal);
1853            }
1854        },
1855    }
1856}
1857
1858pub open spec fn btree_set_remove_ensures<Key: Borrow<Q> + Ord, A: AllocatorClone, Q: Ord + ?Sized>(
1859    old_m: &BTreeSet<Key, A>,
1860    final_m: &BTreeSet<Key, A>,
1861    k: &Q,
1862    result: bool,
1863) -> bool {
1864    ({
1865        &&& obeys_cmp::<Key>()
1866        &&& obeys_cmp::<&Q>()
1867        &&& <Key as BorrowSpec<Q>>::obeys_borrow_spec()
1868        &&& btree_set_inv(old_m)
1869    }) ==> {
1870        &&& btree_set_inv(final_m)
1871        &&& if result {
1872            exists|key: Key|
1873                {
1874                    &&& #[trigger] old_m@.contains(key)
1875                    &&& k.cmp_spec(<Key as BorrowSpec<Q>>::borrow_spec(&key)) is Equal
1876                    &&& final_m@ == old_m@.remove(key)
1877                }
1878        } else {
1879            &&& forall|key: Key| #[trigger]
1880                old_m@.contains(key) ==> !(k.cmp_spec(
1881                    <Key as BorrowSpec<Q>>::borrow_spec(&key),
1882                ) is Equal)
1883            &&& final_m@ == old_m@
1884        }
1885    }
1886}
1887
1888pub assume_specification<Key: Borrow<Q> + Ord, A: AllocatorClone, Q: Ord + ?Sized>[ BTreeSet::<
1889    Key,
1890    A,
1891>::remove::<Q> ](m: &mut BTreeSet<Key, A>, k: &Q) -> (result: bool)
1892    requires
1893        borrowed_key_ordering_matches::<Key, Q>(),
1894    ensures
1895        btree_set_wf(old(m)) ==> btree_set_wf(final(m)),
1896        btree_set_remove_ensures(old(m), final(m), k, result),
1897;
1898
1899pub broadcast proof fn lemma_btree_set_remove_ensures_if_obeys_cmp_concrete_eq<
1900    Key: Ord,
1901    A: AllocatorClone,
1902>(old_m: &BTreeSet<Key, A>, final_m: &BTreeSet<Key, A>, k: &Key, result: bool)
1903    requires
1904        obeys_cmp::<Key>(),
1905        obeys_cmp_concrete_eq::<Key>(),
1906        btree_set_inv(old_m),
1907        #[trigger] btree_set_remove_ensures(old_m, final_m, k, result),
1908    ensures
1909        final_m@ == old_m@.remove(*k),
1910        result == old_m@.contains(*k),
1911{
1912    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
1913    broadcast use crate::set::group_set_lemmas;
1914
1915    reveal(crate::laws_cmp::obeys_cmp_ord);
1916
1917    if !result {
1918        assert(!old_m@.contains(*k));
1919        assert(old_m@.remove(*k) =~= old_m@);
1920    }
1921}
1922
1923pub broadcast proof fn lemma_btree_set_remove_ensures_if_obeys_cmp_deep_eq<
1924    Key: Ord + DeepView,
1925    A: AllocatorClone,
1926>(old_m: &BTreeSet<Key, A>, final_m: &BTreeSet<Key, A>, k: &Key, result: bool)
1927    requires
1928        obeys_cmp::<Key>(),
1929        obeys_cmp_deep_eq::<Key>(),
1930        btree_set_inv(old_m),
1931        #[trigger] btree_set_remove_ensures(old_m, final_m, k, result),
1932    ensures
1933        Key::obeys_cmp_spec(),
1934        final_m.deep_view() == old_m.deep_view().remove(k.deep_view()),
1935        result == old_m.deep_view().contains(k.deep_view()),
1936{
1937    broadcast use crate::laws_cmp::lemma_ref_obeys_cmp_spec;
1938    broadcast use {crate::set::group_set_lemmas, Set::lemma_map_contains};
1939
1940    reveal(crate::laws_cmp::obeys_cmp_ord);
1941
1942    let stored_key = if result {
1943        choose|key: Key|
1944            {
1945                &&& #[trigger] old_m@.contains(key)
1946                &&& k.cmp_spec(&key) is Equal
1947                &&& final_m@ == old_m@.remove(key)
1948            }
1949    } else {
1950        *k
1951    };
1952    assert(stored_key.deep_view() == k.deep_view());
1953
1954    if result {
1955        assert(old_m.deep_view().contains(k.deep_view()));
1956    } else if old_m.deep_view().contains(k.deep_view()) {
1957        let key = choose|key: Key|
1958            old_m@.contains(key) && #[trigger] key.deep_view() == k.deep_view();
1959        assert(k.cmp_spec(&key) is Equal);
1960    }
1961    assert forall|kd: Key::V| #[trigger]
1962        final_m.deep_view().contains(kd) <==> old_m.deep_view().remove(k.deep_view()).contains(
1963            kd,
1964        ) by {
1965        if final_m.deep_view().contains(kd) {
1966            let key = choose|key: Key| final_m@.contains(key) && #[trigger] key.deep_view() == kd;
1967            assert(old_m@.contains(key));
1968            assert(key.deep_view() != k.deep_view());
1969        }
1970        if old_m.deep_view().contains(kd) && kd != k.deep_view() {
1971            let key = choose|key: Key| old_m@.contains(key) && #[trigger] key.deep_view() == kd;
1972            assert(final_m@.contains(key));
1973        }
1974    }
1975    assert(final_m.deep_view() =~= old_m.deep_view().remove(k.deep_view()));
1976}
1977
1978pub assume_specification<Key, A: AllocatorClone>[ BTreeSet::<Key, A>::clear ](
1979    m: &mut BTreeSet<Key, A>,
1980) where A: Clone
1981    ensures
1982        final(m)@ == Set::<Key>::empty(),
1983        btree_set_wf(final(m)),
1984;
1985
1986pub assume_specification<'a, Key, A: AllocatorClone>[ BTreeSet::<Key, A>::iter ](
1987    m: &'a BTreeSet<Key, A>,
1988) -> (r: btree_set::Iter<'a, Key>)
1989    ensures
1990        key_obeys_cmp_spec::<Key>() && btree_set_wf(m) ==> {
1991            &&& IteratorSpec::remaining(&r).unref().to_set() == m@
1992            &&& IteratorSpec::remaining(&r).no_duplicates()
1993            &&& IteratorSpec::remaining(&r).len() == m@.len()
1994            &&& IteratorSpec::remaining(&r).len() == m.len()
1995            &&& increasing_seq(IteratorSpec::remaining(&r))
1996            &&& into_iter_btree_keys(r) == IteratorSpec::remaining(&r).unref()
1997            &&& IteratorSpec::decrease(&r) is Some
1998        },
1999;
2000
2001pub broadcast axiom fn axiom_btree_set_decreases<Key, A: AllocatorClone>(m: BTreeSet<Key, A>)
2002    ensures
2003        #[trigger] (decreases_to!(m => m@)),
2004;
2005
2006pub broadcast group group_btree_axioms {
2007    axiom_key_obeys_cmp_spec_meaning,
2008    axiom_increasing_seq_meaning,
2009    axiom_spec_btree_map_len,
2010    lemma_btree_map_insert_ensures_if_obeys_cmp_concrete_eq,
2011    lemma_btree_map_insert_ensures_if_obeys_cmp_deep_eq,
2012    lemma_btree_map_contains_key_ensures_if_obeys_cmp_concrete_eq,
2013    lemma_btree_map_contains_key_ensures_if_obeys_cmp_deep_eq,
2014    lemma_btree_map_get_ensures_if_obeys_cmp_concrete_eq,
2015    lemma_btree_map_get_ensures_if_obeys_cmp_deep_eq,
2016    lemma_btree_map_remove_ensures_if_obeys_cmp_concrete_eq,
2017    lemma_btree_map_remove_ensures_if_obeys_cmp_deep_eq,
2018    lemma_btree_map_get_mut_ensures_if_obeys_cmp_concrete_eq,
2019    lemma_btree_map_get_mut_ensures_if_obeys_cmp_deep_eq,
2020    axiom_spec_btree_set_len,
2021    lemma_btree_set_insert_ensures_if_obeys_cmp_concrete_eq,
2022    lemma_btree_set_insert_ensures_if_obeys_cmp_deep_eq,
2023    lemma_btree_set_contains_ensures_if_obeys_cmp_concrete_eq,
2024    lemma_btree_set_contains_ensures_if_obeys_cmp_deep_eq,
2025    lemma_btree_set_get_ensures_if_obeys_cmp_concrete_eq,
2026    lemma_btree_set_get_ensures_if_obeys_cmp_deep_eq,
2027    lemma_btree_set_remove_ensures_if_obeys_cmp_concrete_eq,
2028    lemma_btree_set_remove_ensures_if_obeys_cmp_deep_eq,
2029    axiom_btree_map_decreases,
2030    axiom_btree_set_decreases,
2031    axiom_has_resolved_cursor,
2032}
2033
2034} // verus!