semi_persistent_containers_verus/id_macros.rs
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! `define_id7!` / `define_id15!` / `define_id31!` / `define_id63!`:
4//! consumer-facing id-type generators with full proof obligations.
5//!
6//! Each invocation stamps out a `#[repr(transparent)]` newtype over its
7//! backing integer with the MSB reserved as the stolen tag bit, implementing:
8//!
9//! - the verified `Tagged` (MSB niche, real `bit_vector` extensionality),
10//! - the verified `IndexLike` (identity `as_nat`, type-invariant bound),
11//! - the verified `DenseId` (`Index` = backing int, `is_bit_stealing`),
12//!
13//! — the exact proof structure of the hand-written `DenseId31`
14//! (`dense_id.rs`), parameterized by width. The crate verifies one WITNESS
15//! instantiation per width (`id_witnesses` module below) in the regular
16//! sweep; consumer invocations expand to textually identical code modulo
17//! name/prefix (trust ledger group E: macro-expansion-in-unverified-crate,
18//! exercised by the canary and runtime proptests).
19//!
20//! Production-surface items generated OUTSIDE `verus!{}` (plain Rust,
21//! contract-free convenience: Debug/Display with prefix, MSB-masking
22//! PartialEq/Eq/Ord/Hash, From/TryFrom, `raw()`/`new()`): these mirror
23//! production's `define_id_impl!` verbatim. The MSB-masking comparisons are
24//! observably identity on clean ids (the type invariant keeps the MSB clear;
25//! masking a clear bit is a no-op), so the verified ordering facts
26//! (`lemma_order_is_as_nat`) speak for these too.
27//!
28//! The plain crate retains its historical `Stored` companion symbol, but no
29//! portable storage type is generated under that name: here the identifier
30//! names the hidden implementation module. Both crates use the backing integer
31//! itself as `Tagged::Repr` (as `DenseId31` does). Code intended to compile
32//! against either crate uses `<Foo as Tagged>::Repr`, never `StoredFoo`.
33
34/// One past the largest clean 7-bit id.
35pub const DENSE7_BOUND: u8 = 0x80;
36/// One past the largest clean 15-bit id.
37pub const DENSE15_BOUND: u16 = 0x8000;
38
39/// 7-bit id: `u8` backing, bit 7 stolen for the capture tag.
40#[macro_export]
41macro_rules! define_id7 {
42 ($(#[$meta:meta])* $vis:vis struct $Name:ident / $Stored:ident, $prefix:expr;) => {
43 $crate::define_id_impl!(@impl $(#[$meta])* $vis, $Name, $Stored, $prefix,
44 u8, 0x7Fu8, 0x80u8, 0x80usize);
45 };
46}
47
48/// 15-bit id: `u16` backing, bit 15 stolen for the capture tag.
49#[macro_export]
50macro_rules! define_id15 {
51 ($(#[$meta:meta])* $vis:vis struct $Name:ident / $Stored:ident, $prefix:expr;) => {
52 $crate::define_id_impl!(@impl $(#[$meta])* $vis, $Name, $Stored, $prefix,
53 u16, 0x7FFFu16, 0x8000u16, 0x8000usize);
54 };
55}
56
57/// 31-bit id: `u32` backing, bit 31 stolen for the capture tag.
58#[macro_export]
59macro_rules! define_id31 {
60 ($(#[$meta:meta])* $vis:vis struct $Name:ident / $Stored:ident, $prefix:expr;) => {
61 $crate::define_id_impl!(@impl $(#[$meta])* $vis, $Name, $Stored, $prefix,
62 u32, 0x7FFF_FFFFu32, 0x8000_0000u32, 0x8000_0000usize);
63 };
64}
65
66/// 63-bit id: `u64` backing, bit 63 stolen for the capture tag.
67#[macro_export]
68macro_rules! define_id63 {
69 ($(#[$meta:meta])* $vis:vis struct $Name:ident / $Stored:ident, $prefix:expr;) => {
70 $crate::define_id_impl!(@impl $(#[$meta])* $vis, $Name, $Stored, $prefix,
71 u64, 0x7FFF_FFFF_FFFF_FFFFu64, 0x8000_0000_0000_0000u64, 0x8000_0000_0000_0000usize);
72 };
73}
74
75/// The shared expansion. `$Int` backing, `$MASK` = value mask (low bits),
76/// `$CAP` = the stolen tag bit (MSB), `$BOUNDUSIZE` = one past the largest
77/// clean id as a `usize` literal.
78#[doc(hidden)]
79#[macro_export]
80macro_rules! define_id_impl {
81 (@impl $(#[$meta:meta])* $vis:vis, $Name:ident, $Stored:ident, $prefix:expr,
82 $Int:ty, $MASK:expr, $CAP:expr, $BOUNDUSIZE:expr) => {
83
84 // Hidden impl module: gives the verus!{} expansion the vstd prelude
85 // it needs without polluting the invoker's namespace. Named by the
86 // `$Stored` identifier (the legacy companion-symbol slot; the portable
87 // Tagged Repr in both crates is the backing integer itself).
88 #[allow(non_snake_case)]
89 // `*r = *r | CAP` (not `|=`): the exact form the verus set_tag/clear_tag
90 // proofs are stated over (bit_vector asserts mention the full assign).
91 #[allow(clippy::assign_op_pattern)]
92 #[doc(hidden)]
93 $vis mod $Stored {
94 use ::vstd::prelude::*;
95
96 verus! {
97
98 $(#[$meta])*
99 /// A clean dense id (generated by `define_id*!`): backing integer with
100 /// the MSB always clear (type invariant), naming a value in
101 /// `[0, id_bound)`. The stolen MSB is available to `Tagged` consumers.
102 #[derive(Copy, Clone)]
103 #[repr(transparent)]
104 pub struct $Name {
105 raw: $Int,
106 }
107
108 impl View for $Name {
109 type V = nat;
110
111 closed spec fn view(&self) -> nat {
112 self.raw as nat
113 }
114 }
115
116 impl $Name {
117 /// Type invariant: a clean id never has the stolen bit set.
118 #[verifier::type_invariant]
119 spec fn inv(self) -> bool {
120 self.raw < $CAP
121 }
122
123 /// Construct from a raw integer known to fit below the tag bit.
124 /// Production parity: asserts at runtime (a verified caller has
125 /// proven the range; an unverified one is trapped before an id
126 /// with the tag bit set — violating the type invariant — could
127 /// exist).
128 #[inline(always)]
129 pub fn new(n: $Int) -> (r: $Name)
130 ensures n < $CAP ==> r@ == n as nat,
131 {
132 // Total-with-documented-panic: the range check is the branch.
133 if !(n <= $MASK) {
134 $crate::guard::refuse(concat!(stringify!($Name), " exceeds range"));
135 }
136 $Name { raw: n }
137 }
138
139 /// The raw clean value (production parity).
140 #[inline(always)]
141 pub fn raw(self) -> (r: $Int)
142 ensures r as nat == self@,
143 {
144 proof { use_type_invariant(&self); }
145 self.raw
146 }
147
148 /// The dense index as a `usize` (for indexing arena vectors).
149 #[inline(always)]
150 pub fn index(self) -> (r: usize)
151 ensures r as nat == self@,
152 {
153 proof { use_type_invariant(&self); }
154 self.raw as usize
155 }
156
157 /// Production `DenseId::to_usize` parity (the heavily-used
158 /// consumer spelling; same contract as `index`).
159 #[inline(always)]
160 pub fn to_usize(self) -> (r: usize)
161 ensures r as nat == self@,
162 {
163 proof { use_type_invariant(&self); }
164 self.raw as usize
165 }
166 }
167
168 /// `Default` is id 0 (MSB clear ⟹ type invariant holds). Required by
169 /// semi-persistent containers indexing with this id: `restore` fills
170 /// reclaimed slots with `Idx::default()` before overwriting them.
171 impl ::core::default::Default for $Name {
172 fn default() -> (r: $Name)
173 ensures r@ == 0,
174 {
175 $Name { raw: 0 }
176 }
177 }
178
179 impl $crate::index_like::IndexLike for $Name {
180 open spec fn as_nat(self) -> nat { self@ }
181 open spec fn max_nat() -> nat { $CAP as nat }
182 closed spec fn min_spec() -> Self { $Name { raw: 0 } }
183 closed spec fn max_spec() -> Self { $Name { raw: $MASK } }
184
185 proof fn lemma_as_nat_bounded(tracked self) {
186 use_type_invariant(self);
187 }
188
189 proof fn lemma_as_nat_injective(a: Self, b: Self) {}
190 proof fn lemma_min_as_nat() {}
191 proof fn lemma_max_as_nat() {}
192 proof fn lemma_max_nat_positive() {}
193 proof fn lemma_order_is_as_nat(a: Self, b: Self) {}
194
195 // `$CAP` is a `$Int` value and `$Int` is never wider than a pointer here
196 // (the macro is instantiated at u8/u32/u64), so the cap is below
197 // `usize::MAX + 1` once `usize` is known to be 64 bits wide.
198 proof fn lemma_max_nat_fits_usize() {
199 $crate::index_like::lemma_u64_usize_64bit();
200 }
201
202 fn min() -> Self { $Name { raw: 0 } }
203 fn max() -> Self { $Name { raw: $MASK } }
204
205 #[inline(always)]
206 fn as_usize(self) -> (r: usize) {
207 proof { use_type_invariant(&self); }
208 self.raw as usize
209 }
210
211 fn try_from_usize(n: usize) -> (r: Option<Self>) {
212 if n < $BOUNDUSIZE {
213 Some($Name { raw: n as $Int })
214 } else {
215 None
216 }
217 }
218
219 #[inline(always)]
220 fn lt(self, other: Self) -> bool { self.raw < other.raw }
221 #[inline(always)]
222 fn le(self, other: Self) -> bool { self.raw <= other.raw }
223 }
224
225 impl $crate::opt::DenseId for $Name {
226 type Index = $Int;
227
228 open spec fn id_nat(self) -> nat { self@ }
229 open spec fn id_bound() -> nat { $CAP as nat }
230
231 #[inline(always)]
232 fn to_index(self) -> (w: $Int) {
233 proof { use_type_invariant(&self); }
234 self.raw
235 }
236
237 // `as_usize` is inherited from the `IndexLike` supertrait (prod-parity).
238
239 #[inline(always)]
240 fn from_usize(n: usize) -> (r: Self) {
241 // Match the plain crate: reject before narrowing so an
242 // out-of-range position cannot alias an existing ID.
243 if n < $BOUNDUSIZE {
244 $Name { raw: n as $Int }
245 } else {
246 $crate::guard::refuse(concat!(stringify!($Name), " exceeds range"));
247 }
248 }
249
250 #[inline(always)]
251 fn try_new(n: usize) -> (r: Option<Self>) {
252 if n < $BOUNDUSIZE {
253 Some($Name { raw: n as $Int })
254 } else {
255 None
256 }
257 }
258
259 proof fn lemma_id_injective(a: Self, b: Self) {}
260
261 proof fn lemma_as_nat_is_id_nat(self) {} // both are `self@`
262
263 proof fn lemma_id_nat_bounded(tracked self) {
264 use_type_invariant(&self);
265 }
266
267 proof fn lemma_id_bound_fits_usize() {
268 // $CAP is 2^(w-1) for a word width w <= 64, and
269 // usize::MAX + 1 == 2^64 on the pinned 64-bit target.
270 $crate::index_like::lemma_u64_usize_64bit();
271 }
272
273 open spec fn is_bit_stealing() -> bool { true }
274
275 fn bit_stealing() -> (b: bool) { true }
276
277 proof fn lemma_id_bound_word_relation() {}
278 }
279
280 impl $crate::tagged::Tagged for $Name {
281 type Repr = $Int;
282
283 closed spec fn value_of(r: $Int) -> $Name {
284 $Name { raw: (r & $MASK) }
285 }
286
287 open spec fn tag_of(r: $Int) -> bool {
288 (r & $CAP) != 0
289 }
290
291 open spec fn repr_wf(_r: $Int) -> bool {
292 true
293 }
294
295 proof fn lemma_repr_extensional(r1: $Int, r2: $Int) {
296 // Equal views give equal masked-low-bits; equal tags give
297 // equal MSBs; together all bits agree.
298 $Name::lemma_value_of_raw(r1);
299 $Name::lemma_value_of_raw(r2);
300 assert((r1 & $MASK) == (r2 & $MASK));
301 assert(((r1 & $CAP) != 0) == ((r2 & $CAP) != 0));
302 assert(
303 (r1 & $MASK) == (r2 & $MASK)
304 && (((r1 & $CAP) != 0) == ((r2 & $CAP) != 0))
305 ==> r1 == r2
306 ) by (bit_vector);
307 }
308
309 fn into_repr(self) -> (r: $Int) {
310 proof { use_type_invariant(&self); }
311 let x = self.raw;
312 assert(x < $CAP ==> (x & $MASK) == x && (x & $CAP) == 0)
313 by (bit_vector);
314 proof { $Name::lemma_value_of_raw(self.raw); }
315 self.raw
316 }
317
318 fn from_repr(r: &$Int) -> (v: $Name) {
319 assert(((*r) & $MASK) < $CAP) by (bit_vector);
320 proof { $Name::lemma_value_of_raw(*r); }
321 $Name { raw: *r & $MASK }
322 }
323
324 fn tag(r: &$Int) -> (b: bool) {
325 (*r & $CAP) != 0
326 }
327
328 fn set_tag(r: &mut $Int) {
329 assert(forall|x: $Int|
330 #![auto]
331 ((x | $CAP) & $MASK) == (x & $MASK)
332 && ((x | $CAP) & $CAP) != 0) by (bit_vector);
333 *r = *r | $CAP;
334 }
335
336 fn clear_tag(r: &mut $Int) {
337 assert(forall|x: $Int|
338 #![auto]
339 ((x & $MASK) & $MASK) == (x & $MASK)
340 && ((x & $MASK) & $CAP) == 0) by (bit_vector);
341 *r = *r & $MASK;
342 }
343 }
344
345 impl $Name {
346 /// The view of `value_of(r)` is the masked raw (a `bit_vector`
347 /// bridge used by the Tagged proofs; the DenseId31 template's
348 /// `lemma_value_of_view`, per-type since `value_of` is closed).
349 proof fn lemma_value_of_raw(r: $Int)
350 ensures
351 <$Name as $crate::tagged::Tagged>::value_of(r)@
352 == (r & $MASK) as nat,
353 (r & $MASK) < $CAP,
354 {
355 assert((r & $MASK) < $CAP) by (bit_vector);
356 }
357 }
358
359 } // verus!
360
361 // ------------------------------------------------------------------
362 // Production-surface convenience impls (plain Rust, outside verus!):
363 // MSB-masking comparisons (identity on clean ids — the type invariant
364 // keeps the MSB clear), prefix Debug/Display, integer conversions.
365 // ------------------------------------------------------------------
366
367 impl $Name {
368 /// Largest storable raw payload (production surface).
369 pub const MAX_RAW: $Int = $MASK;
370
371 /// Test-only constructor bypassing the range check (production
372 /// surface; `cfg(test)` on both sides).
373 #[cfg(test)]
374 #[allow(dead_code)]
375 pub fn from_raw_unchecked(raw: $Int) -> Self {
376 $Name { raw }
377 }
378 }
379
380 impl PartialEq for $Name {
381 #[inline(always)]
382 fn eq(&self, other: &Self) -> bool {
383 (self.raw() & $MASK) == (other.raw() & $MASK)
384 }
385 }
386 impl Eq for $Name {}
387
388 impl PartialOrd for $Name {
389 #[inline(always)]
390 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
391 Some(self.cmp(other))
392 }
393 }
394 impl Ord for $Name {
395 #[inline(always)]
396 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
397 (self.raw() & $MASK).cmp(&(other.raw() & $MASK))
398 }
399 }
400
401 impl core::hash::Hash for $Name {
402 #[inline(always)]
403 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
404 (self.raw() & $MASK).hash(state);
405 }
406 }
407
408 impl From<$Name> for $Int {
409 #[inline(always)]
410 fn from(id: $Name) -> $Int {
411 id.raw()
412 }
413 }
414
415 impl TryFrom<$Int> for $Name {
416 type Error = $crate::id_factory::IdRangeError;
417 #[inline]
418 fn try_from(raw: $Int) -> Result<Self, Self::Error> {
419 if raw <= $MASK {
420 Ok(Self::new(raw))
421 } else {
422 Err($crate::id_factory::IdRangeError { type_name: stringify!($Name) })
423 }
424 }
425 }
426
427 impl ::core::fmt::Debug for $Name {
428 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
429 write!(f, "{}{}", $prefix, self.raw())
430 }
431 }
432
433 impl ::core::fmt::Display for $Name {
434 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
435 write!(f, "{}{}", $prefix, self.raw())
436 }
437 }
438
439 } // mod $Stored
440
441 $vis use $Stored::$Name;
442 };
443}
444
445/// Witness instantiations: one per width, verified in the regular sweep.
446/// A consumer's `define_id31!(FooId, ...)` expands to code
447/// textually identical to `WitnessId31`'s modulo name/prefix, so these are
448/// the proof that every macro-generated id discharges its obligations.
449pub mod id_witnesses {
450 define_id7! { pub struct WitnessId7 / StoredWitnessId7, "w7_"; }
451 define_id15! { pub struct WitnessId15 / StoredWitnessId15, "w15_"; }
452 define_id31! { pub struct WitnessId31 / StoredWitnessId31, "w31_"; }
453 define_id63! { pub struct WitnessId63 / StoredWitnessId63, "w63_"; }
454}
455
456/// Concrete ids production exported from `containers::id` (consumed by the
457/// egraph's classes/use-lists).
458pub mod ids {
459 define_id31! { pub struct SparseSetId / StoredSparseSetId, "s"; }
460 define_id31! { pub struct UseListId / StoredUseListId, "ul"; }
461 define_id31! { pub struct UseNodeId / StoredUseNodeId, "un"; }
462}