semi_persistent_containers_verus/opt.rs
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! `Opt<T>`: niche-optional over a `Tagged` repr, and `DenseId`: an
4//! id type that is a bijection with a dense `usize` range. Both are
5//! prerequisites for `ListArena` (intrusive linked lists over a node arena).
6//!
7//! `Opt<T>` packs `Option<T>` into a single `T::Repr` using `T`'s tag bit:
8//! `tag_of(repr) == true` encodes `None`, otherwise `Some(value_of(repr))`.
9//! Like production, an `Opt<T>` must live inside a struct that provides its
10//! own (different) capture bit — `Opt` owns the option bit, the enclosing
11//! struct owns the capture bit, on separate fields, so they never collide.
12
13use vstd::prelude::*;
14
15use crate::index_like::IndexLike;
16use crate::tagged::Tagged;
17
18verus! {
19
20/// A `Tagged` type that also requires `Default` (needed to mint the `None`
21/// repr: take any value, set its tag). The crate's `Copy` convention applies.
22pub trait OptElem: Tagged + core::default::Default {
23}
24
25/// Niche-optional over `T::Repr`. `None` is `tag_of` set; `Some(v)` is a clean
26/// repr with `value_of == v`.
27#[derive(Copy)]
28pub struct Opt<T: Tagged> {
29 pub(crate) repr: T::Repr,
30}
31
32// Hand-written `Clone` (a plain copy); the autoderived `Clone` on a generic
33// struct emits a "clone is not a copy" warning under Verus otherwise.
34impl<T: Tagged> Clone for Opt<T> {
35 fn clone(&self) -> (r: Self)
36 ensures r == *self,
37 {
38 *self
39 }
40}
41
42impl<T: Tagged> Opt<T> {
43 /// Ghost view: the optional value this repr encodes. Requires `repr_wf`.
44 pub open(crate) spec fn get_spec(self) -> Option<T> {
45 if T::tag_of(self.repr) {
46 None
47 } else {
48 Some(T::value_of(self.repr))
49 }
50 }
51
52 /// `Opt` is well-formed iff its repr is.
53 pub open(crate) spec fn wf(self) -> bool {
54 T::repr_wf(self.repr)
55 }
56
57 /// `Some(val)`: encode the value with tag clear.
58 pub fn some(val: T) -> (r: Opt<T>)
59 ensures r.wf(), r.get_spec() == Some(val),
60 {
61 Opt { repr: val.into_repr() }
62 }
63
64 /// `is_none` reads the tag.
65 pub fn is_none(&self) -> (b: bool)
66 requires self.wf(),
67 ensures b == (self.get_spec() is None),
68 {
69 T::tag(&self.repr)
70 }
71
72 pub fn is_some(&self) -> (b: bool)
73 requires self.wf(),
74 ensures b == (self.get_spec() is Some),
75 {
76 !T::tag(&self.repr)
77 }
78
79 /// Extract the value (panics on `None` in exec via the precondition).
80 pub fn get(&self) -> (v: T)
81 requires self.wf(),
82 ensures self.get_spec() is Some ==> Some(v) == self.get_spec(),
83 {
84 // Total-with-documented-panic: presence is the branch.
85 if !self.is_some() {
86 crate::guard::refuse("Opt::get: value is None");
87 }
88 T::from_repr(&self.repr)
89 }
90
91 /// The optional value (production `Opt::get` parity — production's `get`
92 /// returned `Option<T>`; under the verus names `get` unwraps and this is the
93 /// total, `Option`-returning form). prod-parity.
94 pub fn to_option(&self) -> (r: Option<T>)
95 requires self.wf(),
96 ensures r == self.get_spec(),
97 {
98 if T::tag(&self.repr) {
99 None
100 } else {
101 Some(T::from_repr(&self.repr))
102 }
103 }
104
105 /// The embedded value, **ignoring the option bit**. `get_spec()` is
106 /// `Some(value_spec())` when the tag is clear and `None` when it is set; this
107 /// projection sees the value in *both* cases, which is what makes the
108 /// value-preserving `set_none`/`get_unchecked` pair below meaningful.
109 pub open(crate) spec fn value_spec(self) -> T {
110 T::value_of(self.repr)
111 }
112
113 /// The embedded value even when the option bit says `None` — the verified
114 /// counterpart of the e-graph's `EClassEntry::repr_id_unchecked`. A class that has
115 /// been absorbed keeps its (now-absent) repr key in place; the merge path
116 /// reads it back to look up the absorbed class's data before the key is
117 /// removed from the sparse set. `Tagged::from_repr` already strips the tag,
118 /// so this needs only `wf` — no `is Some` precondition, unlike `get`.
119 pub fn get_unchecked(&self) -> (v: T)
120 requires self.wf(),
121 ensures v == self.value_spec(),
122 {
123 T::from_repr(&self.repr)
124 }
125
126 /// Set the option bit to `None` **in place, preserving the value** — the
127 /// verified counterpart of `EClassEntry::set_absent`. `Tagged::set_tag`'s contract
128 /// is exactly "flips the tag, keeps `value_of`", so the value stays readable
129 /// through `get_unchecked` afterwards.
130 pub fn set_none(&mut self)
131 requires old(self).wf(),
132 ensures
133 final(self).wf(),
134 final(self).get_spec() is None,
135 final(self).value_spec() == old(self).value_spec(),
136 {
137 T::set_tag(&mut self.repr);
138 }
139
140 /// The raw repr (spec counterpart; the field is `pub(crate)` — privacy closeout).
141 pub open(crate) spec fn repr_spec(self) -> T::Repr {
142 self.repr
143 }
144
145 /// Embed into the raw repr (for storing inside a struct's Repr).
146 pub fn into_raw(self) -> (r: T::Repr)
147 ensures r == self.repr_spec(),
148 {
149 self.repr
150 }
151
152 /// Reconstruct from a raw repr.
153 pub fn from_raw(r: T::Repr) -> (o: Opt<T>)
154 ensures o.repr_spec() == r,
155 {
156 Opt { repr: r }
157 }
158}
159
160impl<T: Tagged + core::default::Default> Opt<T> {
161 /// `None`: take any value's repr and set its tag bit.
162 pub fn none() -> (r: Opt<T>)
163 ensures r.wf(), r.get_spec() is None,
164 {
165 let mut repr = T::default().into_repr();
166 T::set_tag(&mut repr);
167 Opt { repr }
168 }
169}
170
171// prod-parity: `Default for Opt<T>` is `None` — production parity
172// (`containers/src/tagged.rs:67`). `Vec::restore` requires the element type to
173// be `Default` (it refills reclaimed slots before overwriting), and the
174// consumer stores `Opt<T>` in such a `Vec` (`classes.rs` min-pool). Verus's
175// `none()` needs `T: Default` (to mint a repr), so the bound is slightly
176// tighter than production's `T: Tagged`; every consumer element type is Default.
177impl<T: Tagged + core::default::Default> core::default::Default for Opt<T> {
178 fn default() -> (r: Opt<T>)
179 ensures r.wf(), r.get_spec() is None,
180 {
181 Opt::none()
182 }
183}
184
185/// An id type in bijection with a dense `usize` range `[0, max)`. Used to index
186/// arena vectors (list ids → heads, node ids → nodes). Modeled like
187/// `IndexLike` (ghost `as_nat` + injective + bounded) plus exec `as_usize` /
188/// `from_usize`.
189pub trait DenseId:
190 Sized
191 + Copy
192 + crate::index_like::IndexLike
193 + crate::tagged::Tagged
194 + core::default::Default
195 + core::cmp::PartialEq
196 + core::cmp::Eq
197 + core::cmp::PartialOrd
198 + core::cmp::Ord
199 + core::hash::Hash
200 + Into<<Self as DenseId>::Index>
201{
202 /// Natural storage word for this id (production's `DenseId::Index`: u8, u16,
203 /// u32, or u64). This is the `Word` a `NodeLayout` stores keys as, and is
204 /// what makes the B+tree generic over the 31-bit (`u32`) and 63-bit (`u64`)
205 /// id families.
206 ///
207 /// `Tagged` matches production's `DenseId` (`containers/src/dense_id.rs:21`,
208 /// `type Index: IndexLike + Tagged`): the consumer's `EClassEntry`/`ClassData`
209 /// store an id's word directly and steal its MSB as a niche
210 /// (`egraph/src/classes.rs`), which needs `Index: Tagged`. Every `Index`
211 /// (u8/u16/u32/u64/usize) already impls `Tagged` (`tagged.rs`), so the bound
212 /// is discharged by the existing impls.
213 type Index: crate::index_like::IndexLike + crate::tagged::Tagged;
214
215 /// Ghost projection to a natural number (the dense index).
216 spec fn id_nat(self) -> nat;
217
218 /// One past the largest representable dense index (`2^31` for a 31-bit id,
219 /// `usize::MAX + 1` for `DenseUsize`). `from_usize` round-trips exactly the
220 /// indices below this bound; `id_nat` is always within it.
221 spec fn id_bound() -> nat;
222
223 /// Exec: serialize the id to its storage word (production's
224 /// `Into<Self::Index>`, used as `key_to_word(k) = k.into()`). The word's
225 /// dense index equals the id's, so ordering on words agrees with ordering
226 /// on ids; this is what lets the B+tree store and compare `Index` words
227 /// while reasoning about the abstract `id_nat` model.
228 fn to_index(self) -> (w: Self::Index)
229 ensures w.as_nat() == self.id_nat();
230
231 /// The `IndexLike` projection (now a supertrait) and the `DenseId`
232 /// projection coincide — both name the dense index. Every concrete impl has
233 /// `as_nat(self) == id_nat(self) == self@`; this law exposes that to generic
234 /// code, which Verus does not unfold through a type parameter. It is what
235 /// lets `as_usize` (whose `IndexLike` ensures is stated in `as_nat`) satisfy
236 /// a `DenseId` postcondition stated in `id_nat`.
237 proof fn lemma_as_nat_is_id_nat(self)
238 ensures self.as_nat() == self.id_nat();
239
240 /// Production's `DenseId::to_usize` spelling (`containers/src/dense_id.rs:23`).
241 /// prod-parity: the consumer calls `to_usize`; verus's own code uses
242 /// `as_usize`. Provided default delegates through the supertrait `as_usize`;
243 /// the bridge law reconciles its `as_nat`-stated ensures with `id_nat`.
244 fn to_usize(self) -> (r: usize)
245 ensures r as nat == self.id_nat()
246 {
247 proof { self.lemma_as_nat_is_id_nat(); }
248 self.as_usize()
249 }
250
251 /// Exec: construct from a `usize`. Bounded IDs panic when
252 /// `n >= id_bound()` rather than narrowing or aliasing; use [`Self::try_new`]
253 /// at an untrusted capacity boundary. `DenseUsize` spans every `usize`, so
254 /// it round-trips unconditionally.
255 fn from_usize(n: usize) -> (r: Self)
256 ensures (n as nat) < Self::id_bound() ==> r.id_nat() == n as nat;
257
258 /// Exec: range-checked construction — `Some` exactly on the representable
259 /// range. The primitive `IdFactory` allocates through (production's
260 /// `try_alloc` checked the WORD range, not the id range, and would panic
261 /// half-way through the bit-stealing family's word range; checking
262 /// `id_bound` here is the corrected contract).
263 fn try_new(n: usize) -> (r: Option<Self>)
264 ensures
265 r is Some <==> (n as nat) < Self::id_bound(),
266 r is Some ==> r->Some_0.id_nat() == n as nat;
267
268 /// Injectivity: distinct ids project to distinct nats.
269 proof fn lemma_id_injective(a: Self, b: Self)
270 requires a.id_nat() == b.id_nat(),
271 ensures a == b;
272
273 /// `id_nat` is always within `id_bound` (the doc invariant on `id_bound`).
274 /// What makes `from_usize(self.as_usize())` round-trip: the cursor's `key()`
275 /// reads a stored word back into a `K`, and this is the precondition
276 /// (`as_usize() < id_bound`) the `from_usize` round-trip needs.
277 proof fn lemma_id_nat_bounded(tracked self)
278 ensures self.id_nat() < Self::id_bound();
279
280 /// The dense range fits in a `usize`. Inherent to the trait's meaning — a
281 /// `DenseId` is a bijection with a dense `usize` range, and `from_usize` /
282 /// `as_usize` would be ill-defined past `usize::MAX`. Every impl is a
283 /// bit-stealing word type (bound `2^(w-1)`) or `DenseUsize` (bound exactly
284 /// `usize::MAX + 1`), so all satisfy it.
285 ///
286 /// Why it must be a law and not a derived fact: code holding an `N` (rather
287 /// than its `usize`) needs `id_nat() <= usize::MAX` to relate the id to a
288 /// width-agnostic `Seq<usize>` model — e.g. `CircularList::next_of`, which
289 /// returns the successor as `N` and must tie it to `next_seq()`, a
290 /// `Seq<usize>`. The old `usize`-returning surface got the bound for free
291 /// from `to_usize`'s ensures; an `N`-typed surface has no such handle.
292 proof fn lemma_id_bound_fits_usize()
293 ensures Self::id_bound() <= usize::MAX as nat + 1;
294
295 /// How the value count relates to the storage word's range. A
296 /// bit-stealing id (Id31/Id63) keeps one bit for the tag, so it has exactly
297 /// HALF the word's values: `id_bound * 2 == Index::max_nat()`. A full-range id
298 /// (DenseUsize) uses the whole word: `id_bound == Index::max_nat()`. The
299 /// disjunction lets every `DenseId` honestly report which it is; the B+tree
300 /// (only ever keyed by a bit-stealing id) consumes the `* 2` arm to bound the
301 /// arena. `is_bit_stealing()` selects the arm so generic tree code can branch.
302 spec fn is_bit_stealing() -> bool;
303
304 /// Exec counterpart of `is_bit_stealing`: a static
305 /// type property, so every impl is a literal and the check const-folds;
306 /// it exists so the B+tree's total shell can refuse a non-bit-stealing
307 /// key at runtime instead of carrying a `requires`.
308 fn bit_stealing() -> (b: bool)
309 ensures b == Self::is_bit_stealing();
310
311 proof fn lemma_id_bound_word_relation()
312 ensures
313 if Self::is_bit_stealing() {
314 Self::id_bound() * 2 == <Self::Index as crate::index_like::IndexLike>::max_nat()
315 } else {
316 Self::id_bound() == <Self::Index as crate::index_like::IndexLike>::max_nat()
317 };
318}
319
320/// A concrete `DenseId` over `usize` (the dense index is the value itself).
321/// Mirrors production's `define_id*!` newtypes at the model level; concrete
322/// instantiation point for `ListArena`.
323#[derive(Copy, Clone)]
324pub struct DenseUsize {
325 pub(crate) raw: usize,
326}
327
328impl DenseUsize {
329 /// The raw value (spec counterpart; the field is `pub(crate)` — privacy
330 /// closeout). The open trait-impl spec fn delegates here.
331 pub open(crate) spec fn raw_spec(self) -> nat {
332 self.raw as nat
333 }
334}
335
336// prod-parity: the production-parity `DenseId` supertrait bundle needs `Tagged`
337// on `DenseUsize`. It is full-range (no bit to steal), so it uses the
338// `BoolTagged` fallback repr exactly like the primitive `usize` impl — the tag
339// is a separate bool, `repr_wf` is vacuous.
340impl crate::tagged::Tagged for DenseUsize {
341 type Repr = crate::tagged::BoolTagged<DenseUsize>;
342 open spec fn value_of(r: Self::Repr) -> Self { r.value }
343 open spec fn tag_of(r: Self::Repr) -> bool { r.tagged }
344 open spec fn repr_wf(_r: Self::Repr) -> bool { true }
345 proof fn lemma_repr_extensional(_r1: Self::Repr, _r2: Self::Repr) {}
346 fn into_repr(self) -> Self::Repr { crate::tagged::BoolTagged { tagged: false, value: self } }
347 fn from_repr(r: &Self::Repr) -> Self { r.value }
348 fn tag(r: &Self::Repr) -> bool { r.tagged }
349 fn set_tag(r: &mut Self::Repr) { r.tagged = true; }
350 fn clear_tag(r: &mut Self::Repr) { r.tagged = false; }
351}
352
353// prod-parity: `IndexLike` is now a supertrait of `DenseId` (matching
354// production, whose `DenseId: … + IndexLike`), so `DenseUsize` — the internal
355// ListArena id — must impl it. Mirrors the primitive `usize` impl
356// (`index_like.rs`): full-range, `as_nat` is the raw value, no bit-stealing.
357impl crate::index_like::IndexLike for DenseUsize {
358 open spec fn as_nat(self) -> nat { self.raw_spec() }
359 open spec fn max_nat() -> nat { usize::MAX as nat + 1 }
360 // `closed`: constructs `DenseUsize` (opaque outside the crate via its
361 // `pub(crate)` field), so the body must not be visible everywhere — same as
362 // `DenseId31`/`DenseId63`'s `min_spec`/`max_spec`.
363 closed spec fn min_spec() -> Self { DenseUsize { raw: 0 } }
364 closed spec fn max_spec() -> Self { DenseUsize { raw: usize::MAX } }
365
366 proof fn lemma_as_nat_bounded(tracked self) {}
367 proof fn lemma_as_nat_injective(a: Self, b: Self) {}
368 proof fn lemma_min_as_nat() {}
369 proof fn lemma_max_nat_positive() {}
370 proof fn lemma_max_as_nat() {}
371 proof fn lemma_order_is_as_nat(a: Self, b: Self) {
372 assert(a.lt_spec(b) == (a.as_nat() < b.as_nat()));
373 assert(a.le_spec(b) == (a.as_nat() <= b.as_nat()));
374 }
375 // `max_nat()` is defined as `usize::MAX + 1` — the obligation is that definition.
376 proof fn lemma_max_nat_fits_usize() {}
377
378 fn min() -> Self { DenseUsize { raw: 0 } }
379 fn max() -> Self { DenseUsize { raw: usize::MAX } }
380 fn as_usize(self) -> usize { self.raw }
381 fn try_from_usize(n: usize) -> Option<Self> { Some(DenseUsize { raw: n }) }
382 fn lt(self, other: Self) -> bool { self.raw < other.raw }
383 fn le(self, other: Self) -> bool { self.raw <= other.raw }
384}
385
386impl DenseId for DenseUsize {
387 type Index = usize;
388
389 open spec fn id_nat(self) -> nat {
390 self.raw_spec()
391 }
392
393 open spec fn id_bound() -> nat {
394 usize::MAX as nat + 1
395 }
396
397 fn to_index(self) -> (w: usize) {
398 self.raw
399 }
400
401 // `as_usize` is inherited from the `IndexLike` supertrait (prod-parity).
402
403 fn from_usize(n: usize) -> (r: Self) {
404 DenseUsize { raw: n }
405 }
406
407 fn try_new(n: usize) -> (r: Option<Self>) {
408 Some(DenseUsize { raw: n }) // full-range: every usize is representable
409 }
410
411 proof fn lemma_id_injective(a: Self, b: Self) {
412 // id_nat is `raw as nat`, injective on usize.
413 }
414
415 proof fn lemma_as_nat_is_id_nat(self) {
416 // Both are `self.raw_spec()`.
417 }
418
419 proof fn lemma_id_nat_bounded(tracked self) {
420 // id_nat == raw as nat <= usize::MAX < usize::MAX + 1 == id_bound.
421 }
422
423 proof fn lemma_id_bound_fits_usize() {
424 // Full-range: id_bound IS usize::MAX + 1 (the `<=` arm is equality).
425 }
426
427 open spec fn is_bit_stealing() -> bool { false } // full-range id
428
429 fn bit_stealing() -> (b: bool) { false }
430
431 proof fn lemma_id_bound_word_relation() {
432 // id_bound == usize::MAX + 1 == <usize as IndexLike>::max_nat() (the `== ` arm).
433 }
434}
435
436/// Corollary of `lemma_id_bound_fits_usize` + `lemma_id_nat_bounded`, in the
437/// form call sites actually want: this id's dense index is a representable
438/// `usize`, so `id_nat() as usize` does not truncate. A free function rather
439/// than a defaulted trait method — a `proof fn` with a body inside the trait
440/// makes Verus re-check the surrounding lemmas' postconditions in every impl.
441pub proof fn lemma_id_nat_fits_usize<N: DenseId>(tracked id: N)
442 ensures
443 id.id_nat() <= usize::MAX as nat,
444 (id.id_nat() as usize) as nat == id.id_nat(),
445{
446 N::lemma_id_bound_fits_usize();
447 id.lemma_id_nat_bounded();
448}
449
450} // verus!
451
452// prod-parity: the production-parity `DenseId` supertrait bundle needs these
453// plain-Rust impls on `DenseUsize`. It is full-range, so ordering/equality/hash
454// on the raw `usize` is the dense-index order (`lemma_order_is_as_nat`), and
455// `Into<usize>` is the identity on the value.
456impl core::default::Default for DenseUsize {
457 #[inline(always)]
458 fn default() -> Self {
459 DenseUsize { raw: 0 }
460 }
461}
462impl PartialEq for DenseUsize {
463 #[inline(always)]
464 fn eq(&self, other: &Self) -> bool {
465 self.raw == other.raw
466 }
467}
468impl Eq for DenseUsize {}
469impl PartialOrd for DenseUsize {
470 #[inline(always)]
471 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
472 Some(self.cmp(other))
473 }
474}
475impl Ord for DenseUsize {
476 #[inline(always)]
477 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
478 self.raw.cmp(&other.raw)
479 }
480}
481impl core::hash::Hash for DenseUsize {
482 #[inline(always)]
483 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
484 self.raw.hash(state);
485 }
486}
487impl From<DenseUsize> for usize {
488 #[inline(always)]
489 fn from(id: DenseUsize) -> usize {
490 id.raw
491 }
492}
493// prod-parity: `IndexLike: Debug` (production parity, dense_id.rs:69).
494impl core::fmt::Debug for DenseUsize {
495 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
496 write!(f, "DenseUsize({})", self.raw)
497 }
498}
499
500// Production-surface parity: production prints `Some(v)` / `None`.
501impl<T> core::fmt::Debug for Opt<T>
502where
503 T: crate::tagged::Tagged + Copy + core::fmt::Debug,
504{
505 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
506 core::fmt::Debug::fmt(&self.to_option(), f)
507 }
508}