Skip to main content

semi_persistent_containers_verus/
eclasses.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Verified equivalence-class aggregate: the e-graph's class layer with
4//! W1-W7 as its machine-checked `wf()`.
5//!
6//! The module composes five verified structures: `CircularList` ring,
7//! `SparseSet` class-key set, `UnionFind`, `ListArena` use-lists, `Vec`
8//! min-monomial pool. Their agreement is `eg_model_wf`, a predicate over the
9//! components' specification views. This table is the authoritative
10//! W-invariant numbering; every other document cites it.
11//!
12//!   - W1: the union-find's ghost root map and its measure (inside
13//!     `UnionFind::wf`);
14//!   - W2: `x` is a union-find root iff ring cell `x` carries a present
15//!     payload, and the live class keys are exactly the root payloads
16//!     (stated as an iff, with injectivity across roots);
17//!   - W3: two nodes share a ring iff they share a root, stated over model
18//!     coordinates in both directions (same ring implies same root, same
19//!     root implies same ring), which is what discharges `splice_absorb`'s
20//!     distinct-rings precondition inside `merge`;
21//!   - W4: live classes own pairwise-distinct, allocated use-lists;
22//!   - W5: every use-list entry is an allocated node id (freshness across a
23//!     merge is the consumer's dirty-set discipline, deliberately not
24//!     claimed here);
25//!   - W6: the pool is whole rows of `min_width`, live row numbers are
26//!     allocated and pairwise distinct;
27//!   - W7: the size stored in a class payload equals its ring's length,
28//!     stated at the ring member that is the class's root. The archive
29//!     invariant (`eg_archive_agrees`) asserts `eg_model_wf` per frame, so
30//!     W7 holds in every archived mark and `restore` preserves it.
31//!
32//! Terminology: a "class key" is the `SparseSet` id a root's ring payload
33//! carries; "live" is the key's state while its class exists. The prose
34//! word "frame" and the API word "snapshot" (`*_snapshots_view`) name the
35//! same thing: one archived mark level. The key stored in a ring payload is a
36//! configured bit-stealing `DenseId`, so the key and successor occupy one word
37//! each;
38//! the 16-byte class payload (`ClassData`) is pinned by the consumer's
39//! compile-time asserts. This kernel is the production e-graph class layer:
40//! `egraph::EClasses` and `egraph::UnionFind` are type aliases of it.
41
42use vstd::prelude::*;
43
44use crate::circular_list::{CircularList, CircularListNode, CircularListToken};
45use crate::index_like::IndexLike;
46use crate::inline_store::InlineStore;
47use crate::list::{ListArena, ListArenaToken, ListNode};
48use crate::opt::{DenseId, Opt};
49use crate::parallel_store::ParallelStore;
50use crate::sparse_set::{SparseSet, SparseSetToken};
51use crate::tagged::Tagged;
52use crate::union_find::{UnionFind, UnionFindToken};
53use crate::vec::{ShrinkPolicy, Vec as SpVec, VecToken};
54
55verus! {
56
57// ---------------------------------------------------------------------------
58// ClassData — per-class payload in the repr sparse set
59// ---------------------------------------------------------------------------
60
61/// Per-class data: the class's use-list id, its optional min-monomial pool
62/// row number, and the atomic flag (production's `ClassData`).
63#[derive(Copy)]
64pub struct ClassData<L: DenseId, T: DenseId> {
65    pub use_list: L,
66    pub min_row: Option<<T as DenseId>::Index>,
67    pub atomic: bool,
68    /// Member-node count of the class, in the node-id family's index type so
69    /// the width follows the configuration (the `min_row` pattern). Set to 1
70    /// at `add_singleton`, folded survivor += absorbed at `merge_with`,
71    /// carried unchanged by every other payload write. Feeds the
72    /// `--union-by size`/`sum` survivor policy.
73    pub size: <T as DenseId>::Index,
74}
75
76impl<L: DenseId, T: DenseId> Clone for ClassData<L, T> {
77    fn clone(&self) -> (r: Self)
78        ensures r == *self,
79    {
80        *self
81    }
82}
83
84impl<L: DenseId, T: DenseId> core::default::Default for ClassData<L, T> {
85    fn default() -> (r: ClassData<L, T>)
86    {
87        ClassData {
88            use_list: L::default(),
89            min_row: None,
90            atomic: false,
91            size: <T::Index as IndexLike>::min(),
92        }
93    }
94}
95
96/// Repr for `ClassData`: the use-list word carries the capture tag
97/// (production's ordering); `min_row` is stored as `(row, present)` because
98/// `T::Index` has no spare niche. A named struct because Verus's
99/// trait-conflict checker rejects `Tagged` on tuples (the `ListNodeRepr`
100/// limitation).
101#[derive(Copy)]
102pub struct ClassDataRepr<LR, I> {
103    pub a: LR,
104    pub row: I,
105    pub present: bool,
106    pub atomic: bool,
107    pub size: I,
108}
109
110impl<LR: Copy, I: Copy> Clone for ClassDataRepr<LR, I> {
111    fn clone(&self) -> (r: Self)
112        ensures r == *self,
113    {
114        *self
115    }
116}
117
118/// `Tagged` for `ClassData`, delegating the capture tag to the use-list
119/// word. `repr_wf` pins the absent-row encoding to a canonical `(min, false)`
120/// — without that, two reprs differing only in a hidden dead `row` word would
121/// decode equal, violating the extensionality law.
122impl<L: DenseId, T: DenseId> Tagged for ClassData<L, T> {
123    type Repr = ClassDataRepr<<L as Tagged>::Repr, <T as DenseId>::Index>;
124
125    open spec fn value_of(r: Self::Repr) -> Self {
126        ClassData {
127            use_list: L::value_of(r.a),
128            min_row: if r.present { Some(r.row) } else { None },
129            atomic: r.atomic,
130            size: r.size,
131        }
132    }
133    open spec fn tag_of(r: Self::Repr) -> bool {
134        L::tag_of(r.a)
135    }
136    open spec fn repr_wf(r: Self::Repr) -> bool {
137        &&& L::repr_wf(r.a)
138        &&& (!r.present ==> r.row == <T::Index as IndexLike>::min_spec())
139    }
140
141    proof fn lemma_repr_extensional(r1: Self::Repr, r2: Self::Repr) {
142        L::lemma_repr_extensional(r1.a, r2.a);
143        // equal values pin `present` (Some vs None) and, when present, `row`;
144        // when absent, repr_wf pins both rows to the canonical min.
145        if r1.present {
146            assert(Self::value_of(r1).min_row == Some(r1.row));
147        }
148    }
149
150    fn into_repr(self) -> (r: Self::Repr) {
151        let (row, present) = match self.min_row {
152            Some(r) => (r, true),
153            None => (<T::Index as IndexLike>::min(), false),
154        };
155        proof { <T::Index as IndexLike>::lemma_min_as_nat(); }
156        ClassDataRepr {
157            a: self.use_list.into_repr(),
158            row,
159            present,
160            atomic: self.atomic,
161            size: self.size,
162        }
163    }
164    fn from_repr(r: &Self::Repr) -> (v: Self) {
165        ClassData {
166            use_list: L::from_repr(&r.a),
167            min_row: if r.present { Some(r.row) } else { None },
168            atomic: r.atomic,
169            size: r.size,
170        }
171    }
172    fn tag(r: &Self::Repr) -> (b: bool) {
173        L::tag(&r.a)
174    }
175    fn set_tag(r: &mut Self::Repr) {
176        L::set_tag(&mut r.a);
177    }
178    fn clear_tag(r: &mut Self::Repr) {
179        L::clear_tag(&mut r.a);
180    }
181}
182
183// ---------------------------------------------------------------------------
184// The joint model invariant (free function, archive-restateable)
185// ---------------------------------------------------------------------------
186
187/// Sparse-set liveness over bare column views (`SparseSet::contains_spec`
188/// restated so the archive can apply it to snapshots).
189pub open(crate) spec fn ss_contains<Idx: IndexLike>(
190    sparse: Seq<Idx>, indices: Seq<Idx>, live: nat, id: nat,
191) -> bool {
192    &&& id < sparse.len()
193    &&& sparse[id as int].as_nat() < live
194    &&& indices[sparse[id as int].as_nat() as int].as_nat() == id
195}
196
197/// The value stored for the live class key `id` (dense slot through the indirection).
198pub open(crate) spec fn ss_value<V, Idx: IndexLike>(
199    dense: Seq<V>, sparse: Seq<Idx>, id: nat,
200) -> V {
201    dense[sparse[id as int].as_nat() as int]
202}
203
204/// W2-W7 over the components' views (the module header holds the invariant
205/// table). `ring_model`/`payloads` are the
206/// `CircularList`'s ghost rings and payload cells; `roots` is the
207/// `UnionFind`'s ghost root map; the three `reprs_*` sequences are the
208/// `SparseSet` columns (`live` its element count); `uses_model`/`uses_nodes`
209/// are the `ListArena`'s ghost lists and node cells; `pool_len`/`min_width`
210/// the pool geometry.
211pub open(crate) spec fn eg_model_wf<
212    T: DenseId,
213    K: DenseId<Index = T::Index>,
214    L: DenseId,
215    N: DenseId + Tagged,
216>(
217    ring_model: Seq<Seq<usize>>,
218    payloads: Seq<Opt<K>>,
219    roots: Seq<usize>,
220    reprs_dense: Seq<ClassData<L, T>>,
221    reprs_sparse: Seq<<T as DenseId>::Index>,
222    reprs_indices: Seq<<T as DenseId>::Index>,
223    uses_model: Seq<Seq<usize>>,
224    uses_nodes: Seq<ListNode<T, N>>,
225    pool: Seq<Opt<T>>,
226    min_width: nat,
227) -> bool {
228    let n = payloads.len();
229    let live = reprs_dense.len();
230    let pool_len = pool.len();
231    &&& T::id_bound() == K::id_bound()
232    &&& roots.len() == n
233    // the repr capacity never outgrows the node count (one live class key per
234    // root, keys minted at most one per node)
235    &&& reprs_sparse.len() <= n
236    // payload cells decode (Opt well-formedness)
237    &&& (forall|x: int| 0 <= x < n ==> (#[trigger] payloads[x]).wf())
238    // W2a: a root iff a present payload
239    &&& (forall|x: int| 0 <= x < n
240            ==> ((#[trigger] roots[x]) == x as usize <==> payloads[x].get_spec() is Some))
241    // W2b (one direction of the key bijection): a root's key is live, and its
242    // stored data names an allocated use-list
243    &&& (forall|x: int| 0 <= x < n && (#[trigger] roots[x]) == x as usize
244            ==> ss_contains(reprs_sparse, reprs_indices, live,
245                    payloads[x].get_spec()->Some_0.as_nat()))
246    // W2c: keys are injective across roots
247    &&& (forall|x: int, y: int|
248            0 <= x < n && 0 <= y < n && x != y
249                && (#[trigger] roots[x]) == x as usize && (#[trigger] roots[y]) == y as usize
250                ==> payloads[x].get_spec()->Some_0.as_nat()
251                    != payloads[y].get_spec()->Some_0.as_nat())
252    // W2d (the other direction): every live class key is some root's key
253    &&& (forall|id: nat| #[trigger] ss_contains(reprs_sparse, reprs_indices, live, id)
254            ==> exists|x: int| 0 <= x < n && roots[x] == x as usize
255                && (#[trigger] payloads[x]).get_spec()->Some_0.as_nat() == id)
256    // W3a: same ring implies same root
257    &&& (forall|c: int, p: int, q: int|
258            0 <= c < ring_model.len() && 0 <= p < ring_model[c].len()
259                && 0 <= q < ring_model[c].len()
260                ==> roots[(#[trigger] ring_model[c][p]) as int]
261                    == roots[(#[trigger] ring_model[c][q]) as int])
262    // W3b: same root implies same ring
263    &&& (forall|c1: int, p1: int, c2: int, p2: int|
264            0 <= c1 < ring_model.len() && 0 <= p1 < ring_model[c1].len()
265                && 0 <= c2 < ring_model.len() && 0 <= p2 < ring_model[c2].len()
266                && roots[(#[trigger] ring_model[c1][p1]) as int]
267                    == roots[(#[trigger] ring_model[c2][p2]) as int]
268                ==> c1 == c2)
269    // W7: the stored class size is the ring length. Stated at the ring member
270    // that is the class's root (every class's root node sits on its own ring),
271    // whose payload carries the live class key; the key's ClassData.size counts
272    // exactly the ring's members. This is what makes `class_size` a verified
273    // O(1) read of the member count (the `--union-by size` policy input).
274    &&& (forall|c: int, p: int|
275            0 <= c < ring_model.len() && 0 <= p < ring_model[c].len()
276                && roots[(#[trigger] ring_model[c][p]) as int] == ring_model[c][p]
277                ==> ss_value(reprs_dense, reprs_sparse,
278                        payloads[ring_model[c][p] as int].get_spec()->Some_0.as_nat())
279                    .size.as_nat() == ring_model[c].len())
280    // W4: live classes own pairwise-distinct, allocated use-lists
281    &&& (forall|id: nat| #[trigger] ss_contains(reprs_sparse, reprs_indices, live, id)
282            ==> ss_value(reprs_dense, reprs_sparse, id).use_list.id_nat()
283                < uses_model.len())
284    &&& (forall|id1: nat, id2: nat|
285            ss_contains(reprs_sparse, reprs_indices, live, id1)
286                && ss_contains(reprs_sparse, reprs_indices, live, id2) && id1 != id2
287                ==> #[trigger] ss_value(reprs_dense, reprs_sparse, id1).use_list.id_nat()
288                    != #[trigger] ss_value(reprs_dense, reprs_sparse, id2).use_list.id_nat())
289    // W5: every use-list entry names an allocated node
290    &&& (forall|l: int, p: int|
291            0 <= l < uses_model.len() && 0 <= p < (#[trigger] uses_model[l]).len()
292                ==> uses_nodes[#[trigger] uses_model[l][p] as int].payload.id_nat() < n)
293    // pool cells decode (Opt well-formedness; the cells are data, W6 is
294    // geometry, but a read must round-trip)
295    &&& (forall|i: int| 0 <= i < pool.len() ==> (#[trigger] pool[i]).wf())
296    // W6: whole rows; live row numbers allocated and pairwise distinct
297    &&& (min_width > 0 ==> pool_len % min_width == 0)
298    &&& (forall|id: nat| #[trigger] ss_contains(reprs_sparse, reprs_indices, live, id)
299            && ss_value(reprs_dense, reprs_sparse, id).min_row is Some
300            ==> min_width > 0
301                && (ss_value(reprs_dense, reprs_sparse, id).min_row->Some_0.as_nat() + 1)
302                    * min_width <= pool_len)
303    &&& (forall|id1: nat, id2: nat|
304            ss_contains(reprs_sparse, reprs_indices, live, id1)
305                && ss_contains(reprs_sparse, reprs_indices, live, id2) && id1 != id2
306                && #[trigger] ss_value(reprs_dense, reprs_sparse, id1).min_row is Some
307                && #[trigger] ss_value(reprs_dense, reprs_sparse, id2).min_row is Some
308                ==> ss_value(reprs_dense, reprs_sparse, id1).min_row->Some_0.as_nat()
309                    != ss_value(reprs_dense, reprs_sparse, id2).min_row->Some_0.as_nat())
310}
311
312
313/// The payload column of a ring snapshot.
314pub open(crate) spec fn ring_payloads<T: DenseId, K: DenseId<Index = T::Index>>(
315    cells: Seq<CircularListNode<Opt<K>, T>>,
316) -> Seq<Opt<K>> {
317    Seq::new(cells.len(), |i: int| cells[i].payload)
318}
319
320/// The aggregate archive: each frame's component snapshots jointly
321/// satisfy the invariant, the stacks move in lockstep, the archived pool
322/// lengths are monotone (the pool only grows between marks), and each
323/// archived repr triple is a valid sparse-set state. This lets the aggregate's
324/// restore discharge `SparseSet::restore`'s snapshot-wf precondition from its
325/// own `wf`.
326/// Opaque for the standard reason; only mark/restore (and `set_min_width`,
327/// which re-checks W6 vacuity over empty archived pools) reveal it.
328#[verifier::opaque]
329pub open(crate) spec fn eg_archive_agrees<
330    T: DenseId,
331    K: DenseId<Index = T::Index>,
332    L: DenseId,
333    N: DenseId + Tagged,
334>(
335    ring_models: Seq<Seq<Seq<usize>>>,
336    ring_cells: Seq<Seq<CircularListNode<Opt<K>, T>>>,
337    roots_arch: Seq<Seq<usize>>,
338    dense_snaps: Seq<Seq<ClassData<L, T>>>,
339    sparse_snaps: Seq<Seq<<T as DenseId>::Index>>,
340    indices_snaps: Seq<Seq<<T as DenseId>::Index>>,
341    uses_models: Seq<Seq<Seq<usize>>>,
342    uses_nodes_snaps: Seq<Seq<ListNode<T, N>>>,
343    pool_snaps: Seq<Seq<Opt<T>>>,
344    min_width: nat,
345) -> bool {
346    let f = ring_models.len();
347    &&& ring_cells.len() == f
348    &&& roots_arch.len() == f
349    &&& dense_snaps.len() == f
350    &&& sparse_snaps.len() == f
351    &&& indices_snaps.len() == f
352    &&& uses_models.len() == f
353    &&& uses_nodes_snaps.len() == f
354    &&& pool_snaps.len() == f
355    &&& (forall|k: int| 0 <= k < f ==> eg_model_wf::<T, K, L, N>(
356            ring_models[k], ring_payloads(#[trigger] ring_cells[k]), roots_arch[k],
357            dense_snaps[k], sparse_snaps[k], indices_snaps[k],
358            uses_models[k], uses_nodes_snaps[k], pool_snaps[k], min_width))
359    &&& (forall|k: int| 0 <= k < f ==> crate::sparse_set::sparse_set_snap_wf(
360            #[trigger] dense_snaps[k], sparse_snaps[k], indices_snaps[k]))
361    &&& (forall|k1: int, k2: int| 0 <= k1 <= k2 < f
362            ==> (#[trigger] pool_snaps[k1]).len() <= (#[trigger] pool_snaps[k2]).len())
363}
364
365// ---------------------------------------------------------------------------
366// EClasses
367// ---------------------------------------------------------------------------
368
369/// Verified equivalence classes: ring + union-find + repr set + use-lists +
370/// min-monomial pool, with the agreement clauses as `wf`.
371pub struct EClasses<T, K, L, N, J, const TRACK: bool, const PROOFS: bool>
372where
373    T: DenseId,
374    K: DenseId<Index = T::Index>,
375    L: DenseId,
376    N: DenseId + Tagged + core::default::Default,
377    J: Tagged + Copy + core::default::Default,
378{
379    /// The class ring; a root cell carries the class's configured-width key
380    /// while the class is live, absent once absorbed.
381    pub(crate) entries: CircularList<Opt<K>, T, TRACK>,
382    /// Per-class data. The sparse set uses the full index word internally so
383    /// its length can represent the complete bit-stealing ID cardinality; its
384    /// numeric keys convert losslessly to the packed `K` stored in the ring.
385    pub(crate) reprs: SparseSet<ClassData<L, T>, <T as DenseId>::Index,
386        InlineStore<ClassData<L, T>, <T as DenseId>::Index>, TRACK>,
387    /// Verified canonical-representative lookup.
388    pub(crate) uf: UnionFind<T, J, TRACK, PROOFS>,
389    /// Per-class parent lists.
390    pub(crate) uses: ListArena<T, L, N, TRACK>,
391    /// Min-monomial pool: flat rows of `min_width` columns. `ParallelStore`,
392    /// as production's `VecP`: `Opt` owns its niche bit, so it cannot sit in
393    /// a bit-stealing `InlineStore`.
394    pub(crate) min_pool: SpVec<Opt<T>, usize, ParallelStore<Opt<T>, usize>, TRACK>,
395    /// Fixed row width; 0 until `set_min_width`.
396    pub(crate) min_width: usize,
397}
398
399impl<T, K, L, N, J, const TRACK: bool, const PROOFS: bool>
400    EClasses<T, K, L, N, J, TRACK, PROOFS>
401where
402    T: DenseId,
403    K: DenseId<Index = T::Index>,
404    L: DenseId,
405    N: DenseId + Tagged + core::default::Default,
406    J: Tagged + Copy + core::default::Default,
407{
408    /// Convert the public, packed class-key type to the sparse set's full-word
409    /// internal key. The numeric identity is unchanged.
410    fn key_index(key: K) -> (raw: <T as DenseId>::Index)
411        ensures raw.as_nat() == key.as_nat(),
412    {
413        let raw = key.to_index();
414        proof { key.lemma_as_nat_is_id_nat(); }
415        raw
416    }
417
418    /// Convert an internal sparse-set key back to the configured packed key.
419    /// `wf` ties the two ID families' capacities, so every key minted while a
420    /// node ID remains available satisfies this precondition.
421    fn class_key(raw: <T as DenseId>::Index) -> (key: K)
422        requires raw.as_nat() < K::id_bound(),
423        ensures key.as_nat() == raw.as_nat(),
424    {
425        let n = raw.as_usize();
426        let key = match K::try_new(n) {
427            Some(key) => key,
428            None => {
429                proof { assert(false); }
430                crate::guard::refuse(
431                    "EClasses class-key width must match the node-id width")
432            }
433        };
434        proof { key.lemma_as_nat_is_id_nat(); }
435        key
436    }
437
438    /// Node count (spec).
439    pub open(crate) spec fn n_spec(&self) -> nat {
440        self.entries.n_spec()
441    }
442
443    /// Live class count (spec).
444    pub open(crate) spec fn num_classes_spec(&self) -> nat {
445        self.reprs.n_spec()
446    }
447
448    pub open(crate) spec fn roots_view(&self) -> Seq<usize> {
449        self.uf.roots_view()
450    }
451
452    /// Two nodes are in the same class (spec).
453    pub open(crate) spec fn same_class_spec(&self, a: int, b: int) -> bool {
454        self.uf.same_set_spec(a, b)
455    }
456
457    /// The class key stored in `x`'s ring cell (meaningful when `x` is a root).
458    pub open(crate) spec fn key_of(&self, x: int) -> nat {
459        self.entries.payload_seq()[x].get_spec()->Some_0.as_nat()
460    }
461
462    /// The class data of live class key `id` (spec).
463    pub open(crate) spec fn class_data_spec(&self, id: nat) -> ClassData<L, T> {
464        ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), id)
465    }
466
467    /// Key liveness (spec counterpart of the repr set's membership).
468    pub open(crate) spec fn contains_key_spec(&self, key: K) -> bool {
469        ss_contains(
470            self.reprs.sparse_view(),
471            self.reprs.indices_view(),
472            self.reprs.n_spec(),
473            key.as_nat(),
474        )
475    }
476
477    /// The ring component (spec ref, for iterator ensures).
478    pub open(crate) spec fn entries_ref(&self)
479        -> &CircularList<Opt<K>, T, TRACK> {
480        &self.entries
481    }
482
483    /// The use-list arena (spec ref, for iterator ensures).
484    pub open(crate) spec fn uses_ref(&self) -> &ListArena<T, L, N, TRACK> {
485        &self.uses
486    }
487
488    /// The class-ring walk of `start` (spec counterpart of `iter_class`'s output).
489    pub open(crate) spec fn class_seq(&self, start: int) -> Seq<usize> {
490        self.entries.class_seq(start)
491    }
492
493    /// The archived root maps, one per mark (spec).
494    pub open(crate) spec fn roots_archive_view(&self) -> Seq<Seq<usize>> {
495        self.uf.roots_snapshots_view()
496    }
497
498    /// Mark depth (spec): the number of live frames.
499    pub open(crate) spec fn depth_spec(&self) -> nat {
500        self.min_pool.snapshots_view().len()
501    }
502
503    pub open(crate) spec fn min_width_spec(&self) -> nat {
504        self.min_width as nat
505    }
506
507    pub open(crate) spec fn wf(&self) -> bool {
508        &&& self.entries.wf()
509        &&& self.reprs.wf()
510        &&& self.uf.wf()
511        &&& self.uses.wf()
512        &&& self.min_pool.wf()
513        &&& self.uf.n_spec() == self.n_spec()
514        &&& eg_model_wf::<T, K, L, N>(
515                self.entries.model_view(),
516                self.entries.payload_seq(),
517                self.uf.roots_view(),
518                self.reprs.dense_view(),
519                self.reprs.sparse_view(),
520                self.reprs.indices_view(),
521                self.uses.model_view(),
522                self.uses.nodes_view(),
523                self.min_pool.view(),
524                self.min_width as nat)
525        // Joint archive over the component snapshot stacks.
526        &&& eg_archive_agrees::<T, K, L, N>(
527                self.entries.model_snapshots_view(),
528                self.entries.entries_snapshots_view(),
529                self.uf.roots_snapshots_view(),
530                self.reprs.dense_snapshots_view(),
531                self.reprs.sparse_snapshots_view(),
532                self.reprs.indices_snapshots_view(),
533                self.uses.model_snapshots_view(),
534                self.uses.nodes_snapshots_view(),
535                self.min_pool.snapshots_view(),
536                self.min_width as nat)
537        // archived pool lengths never exceed the live pool (outside the
538        // opaque predicate: the live length changes on row allocation, and
539        // an opaque argument change would not transfer by congruence).
540        &&& (forall|k: int| 0 <= k < self.min_pool.snapshots_view().len()
541                ==> (#[trigger] self.min_pool.snapshots_view()[k]).len()
542                    <= self.min_pool.view().len())
543    }
544
545    pub fn new() -> (e: Self)
546        ensures e.wf(), e.n_spec() == 0, e.num_classes_spec() == 0,
547            e.min_width_spec() == 0,
548    {
549        let t_steals = T::bit_stealing();
550        let k_steals = K::bit_stealing();
551        if !(t_steals && k_steals) {
552            crate::guard::refuse(
553                "EClasses requires node IDs and class keys with matching bit-stealing widths");
554        }
555        let e = EClasses {
556            entries: CircularList::new(),
557            reprs: SparseSet::new_inline(),
558            uf: UnionFind::new(),
559            uses: ListArena::new(),
560            min_pool: SpVec::<Opt<T>, usize, ParallelStore<Opt<T>, usize>, TRACK>::new(),
561            min_width: 0,
562        };
563        proof {
564            T::lemma_id_bound_word_relation();
565            K::lemma_id_bound_word_relation();
566            assert(T::id_bound() * 2
567                == <T::Index as IndexLike>::max_nat());
568            assert(K::id_bound() * 2
569                == <T::Index as IndexLike>::max_nat());
570            assert(T::id_bound() * 2 == K::id_bound() * 2);
571            assert(T::id_bound() == K::id_bound());
572            reveal(eg_archive_agrees);
573        }
574        e
575    }
576
577    /// Node count as the id family's index word.
578    pub fn len(&self) -> (n: <T as DenseId>::Index)
579        requires self.wf(),
580        ensures n.as_nat() == self.n_spec(),
581    {
582        self.uf.len()
583    }
584
585    pub fn is_empty(&self) -> (b: bool)
586        requires self.wf(),
587        ensures b == (self.n_spec() == 0),
588    {
589        self.uf.is_empty()
590    }
591
592    /// Live class count.
593    pub fn num_classes(&self) -> (n: <T as DenseId>::Index)
594        requires self.wf(),
595        ensures n.as_nat() == self.num_classes_spec(),
596    {
597        self.reprs.len()
598    }
599
600    /// Canonical representative (compressing).
601    pub fn find(&mut self, x: T) -> (r: T)
602        requires old(self).wf(),
603        ensures
604            final(self).wf(),
605            final(self).n_spec() == old(self).n_spec(),
606            final(self).roots_view() == old(self).roots_view(),
607            x.id_nat() < old(self).n_spec() ==> {
608                &&& r.id_nat() == old(self).roots_view()[x.id_nat() as int] as nat
609                &&& r.id_nat() < old(self).n_spec()
610            },
611    {
612        let r = self.uf.find(x);
613        proof {
614            // only uf.parent changed (compression); every eg_model_wf clause
615            // reads roots, which find preserves.
616            assert(self.entries == old(self).entries);
617            assert(self.reprs == old(self).reprs);
618            assert(self.uses == old(self).uses);
619            assert(self.min_pool == old(self).min_pool);
620        }
621        r
622    }
623
624    /// Canonical representative (read-only).
625    pub fn find_const(&self, x: T) -> (r: T)
626        requires self.wf(),
627        ensures
628            x.id_nat() < self.n_spec() ==> {
629                &&& r.id_nat() == self.roots_view()[x.id_nat() as int] as nat
630                &&& r.id_nat() < self.n_spec()
631            },
632    {
633        self.uf.find_const(x)
634    }
635
636    /// The class key of node `idx`'s ring cell, `None` once its class was
637    /// absorbed (production's `repr_id`). For a CANONICAL id (a root), `Some`
638    /// is guaranteed by W2.
639    pub fn repr_id(&self, idx: T) -> (r: Option<K>)
640        requires self.wf(),
641        ensures
642            idx.id_nat() < self.n_spec() ==> {
643                &&& (r is Some <==> self.roots_view()[idx.id_nat() as int] == idx.id_nat() as usize)
644                &&& (r matches Some(k) ==> k.as_nat() == self.key_of(idx.id_nat() as int))
645            },
646    {
647        if !(idx.to_usize() < self.entries.len().as_usize()) {
648            crate::guard::refuse("EClasses::repr_id: node id out of range");
649        }
650        let p = self.entries.payload_of(idx);
651        proof {
652            crate::opt::lemma_id_nat_fits_usize(idx);
653            assert(p == self.entries.payload_seq()[idx.id_nat() as int]);
654            assert(p.wf());
655        }
656        p.to_option()
657    }
658
659    /// Allocate `id` as its own singleton class, returning its class key
660    /// (production's surface: the caller supplies the next dense id; the
661    /// sequential contract refuses with production's message, which
662    /// historically came from `UnionFind::make_set`).
663    pub fn add_singleton(&mut self, id: T) -> (key: K)
664        requires old(self).wf(),
665        ensures
666            final(self).wf(),
667            id.id_nat() == old(self).n_spec() ==> {
668                &&& final(self).n_spec() == old(self).n_spec() + 1
669                &&& final(self).num_classes_spec() == old(self).num_classes_spec() + 1
670                &&& final(self).roots_view()
671                    == old(self).roots_view().push(old(self).n_spec() as usize)
672                &&& final(self).key_of(id.id_nat() as int) == key.as_nat()
673            },
674    {
675        if !(id.to_usize() == self.uf.len().as_usize()) {
676            crate::guard::refuse("UnionFind::make_set: id must be sequential");
677        }
678        let (minted, key) = self.try_add_singleton();
679        proof {
680            if id.id_nat() == old(self).n_spec() {
681                T::lemma_id_injective(minted, id);
682            }
683        }
684        key
685    }
686
687    /// Allocate the NEXT fresh node as its own singleton class; returns the
688    /// minted node id and its class key. Total-with-documented-panic at the
689    /// capacity ceilings (production allocates through `expect` at the same
690    /// points).
691    pub fn try_add_singleton(&mut self) -> (r: (T, K))
692        requires old(self).wf(),
693        ensures
694            final(self).wf(),
695            final(self).n_spec() == old(self).n_spec() + 1,
696            final(self).num_classes_spec() == old(self).num_classes_spec() + 1,
697            r.0.id_nat() == old(self).n_spec(),
698            r.1.as_nat() == final(self).key_of(r.0.id_nat() as int),
699            final(self).roots_view()
700                == old(self).roots_view().push(old(self).n_spec() as usize),
701            final(self).key_of(r.0.id_nat() as int) == r.1.as_nat(),
702            final(self).min_width_spec() == old(self).min_width_spec(),
703    {
704        let ghost n0 = self.n_spec();
705        // 1. union-find slot
706        let id = match self.uf.try_make_set() {
707            Ok(id) => id,
708            Err(_) => crate::guard::refuse("EClasses::add_singleton: node-id range exhausted"),
709        };
710        // 2. use-list
711        let list_id = match self.uses.try_new_list() {
712            Ok(l) => l,
713            Err(_) => crate::guard::refuse("EClasses::add_singleton: use-list id range exhausted"),
714        };
715        // 3. repr slot
716        let one = match <T::Index as IndexLike>::try_from_usize(1) {
717            Some(o) => o,
718            None => crate::guard::refuse("EClasses::add_singleton: index width below 1"),
719        };
720        let raw_key = match self.reprs.try_add(ClassData {
721            use_list: list_id, min_row: None, atomic: false, size: one,
722        }) {
723            Ok(k) => k,
724            Err(_) => crate::guard::refuse("EClasses::add_singleton: repr capacity exhausted"),
725        };
726        proof {
727            crate::opt::lemma_id_nat_fits_usize(id);
728            id.lemma_id_nat_bounded();
729            assert(raw_key.as_nat() <= old(self).reprs.cap_spec());
730            assert(old(self).reprs.cap_spec() <= n0);
731            assert(T::id_bound() == K::id_bound());
732            assert(raw_key.as_nat() < K::id_bound());
733        }
734        let key = Self::class_key(raw_key);
735        // 4. ring cell: the key word is the payload, as production stores it.
736        let opt_key = Opt::some(key);
737        let ring_id = match self.entries.try_add_singleton(opt_key) {
738            Ok(rid) => rid,
739            Err(_) => crate::guard::refuse("EClasses::add_singleton: ring capacity exhausted"),
740        };
741        proof {
742            assert(ring_id.id_nat() == n0);
743            assert(id.id_nat() == n0);
744            T::lemma_id_injective(ring_id, id);
745
746            let o = *old(self);
747            let n1 = n0 + 1;
748            let rm = self.entries.model_view();
749            let pay = self.entries.payload_seq();
750            let roots = self.uf.roots_view();
751            let dense = self.reprs.dense_view();
752            let sparse = self.reprs.sparse_view();
753            let indices = self.reprs.indices_view();
754            let um = self.uses.model_view();
755            let un = self.uses.nodes_view();
756            let orm = o.entries.model_view();
757            let opay = o.entries.payload_seq();
758            let oroots = o.uf.roots_view();
759            let odense = o.reprs.dense_view();
760            let osparse = o.reprs.sparse_view();
761            let oindices = o.reprs.indices_view();
762            let oum = o.uses.model_view();
763            let olive = o.reprs.n_spec();
764            let live = self.reprs.n_spec();
765            let kn = key.as_nat();
766
767            assert(pay == opay.push(opt_key));
768            assert(opt_key.get_spec() == Some(key));
769            assert(rm == orm.push(seq![n0 as usize]));
770            assert(roots == oroots.push(n0 as usize));
771            assert(um == oum.push(Seq::<usize>::empty()));
772            assert(un == o.uses.nodes_view());
773            assert(pay.len() == n1);
774            crate::opt::lemma_id_nat_fits_usize(id);
775
776            // the new key is live, with the fresh ClassData
777            assert(self.reprs.contains_spec(raw_key));
778            assert(ss_contains(sparse, indices, live, kn));
779            assert(ss_value(dense, sparse, kn)
780                == ClassData::<L, T> { use_list: list_id, min_row: None, atomic: false, size: one });
781
782            // survivors: old liveness and values carry over, id-for-nat
783            assert forall|kk: nat| #[trigger] ss_contains(osparse, oindices, olive, kk)
784                implies ss_contains(sparse, indices, live, kk)
785                    && ss_value(dense, sparse, kk) == ss_value(odense, osparse, kk)
786                    && kk != kn by {
787                let kw = oindices[osparse[kk as int].as_nat() as int];
788                assert(kw.as_nat() == kk);
789                assert(o.reprs.contains_spec(kw));
790                assert(self.reprs.contains_spec(kw));
791                // the fresh key was not live before
792                assert(!o.reprs.id_set().contains(kn));
793                if kk == kn {
794                    assert(o.reprs.id_set().contains(kk)) by {
795                        assert(oindices[osparse[kk as int].as_nat() as int].as_nat() == kk);
796                    }
797                }
798            }
799            // dead keys stay dead (contrapositive of the id_set update)
800            assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk) && kk != kn
801                implies ss_contains(osparse, oindices, olive, kk) by {
802                let kw = indices[sparse[kk as int].as_nat() as int];
803                assert(kw.as_nat() == kk);
804                assert(self.reprs.contains_spec(kw));
805                assert(self.reprs.id_set().contains(kk)) by {
806                    assert(indices[sparse[kk as int].as_nat() as int].as_nat() == kk);
807                }
808                assert(o.reprs.id_set().contains(kk));
809                let p = choose|p: int| 0 <= p < olive
810                    && (#[trigger] oindices[p]).as_nat() == kk;
811                let ow = oindices[p];
812                assert(o.reprs.contains_spec(ow));
813            }
814
815            // --- W2a
816            assert forall|x: int| 0 <= x < n1 implies
817                ((#[trigger] roots[x]) == x as usize <==> pay[x].get_spec() is Some) by {
818                if x < n0 {
819                    assert(roots[x] == oroots[x]);
820                    assert(pay[x] == opay[x]);
821                }
822            }
823            // --- W2b
824            assert forall|x: int| 0 <= x < n1 && (#[trigger] roots[x]) == x as usize
825                implies ss_contains(sparse, indices, live,
826                    pay[x].get_spec()->Some_0.as_nat()) by {
827                if x < n0 {
828                    assert(ss_contains(osparse, oindices, olive,
829                        opay[x].get_spec()->Some_0.as_nat()));
830                    assert(pay[x] == opay[x]);
831                }
832            }
833            // --- W2c
834            assert forall|x: int, y: int|
835                0 <= x < n1 && 0 <= y < n1 && x != y
836                    && (#[trigger] roots[x]) == x as usize
837                    && (#[trigger] roots[y]) == y as usize
838                implies pay[x].get_spec()->Some_0.as_nat()
839                    != pay[y].get_spec()->Some_0.as_nat() by {
840                if x < n0 && y < n0 {
841                    assert(pay[x] == opay[x] && pay[y] == opay[y]);
842                } else if x == n0 as int && y < n0 {
843                    // the fresh key differs from every old root's key, which
844                    // is live in the OLD set.
845                    assert(pay[y] == opay[y]);
846                    assert(ss_contains(osparse, oindices, olive,
847                        opay[y].get_spec()->Some_0.as_nat()));
848                } else if y == n0 as int && x < n0 {
849                    assert(pay[x] == opay[x]);
850                    assert(ss_contains(osparse, oindices, olive,
851                        opay[x].get_spec()->Some_0.as_nat()));
852                }
853            }
854            // --- W2d
855            assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
856                implies exists|x: int| 0 <= x < n1 && roots[x] == x as usize
857                    && (#[trigger] pay[x]).get_spec()->Some_0.as_nat() == kk by {
858                if kk == kn {
859                    assert(roots[n0 as int] == n0 as usize);
860                    assert(pay[n0 as int].get_spec()->Some_0.as_nat() == kk);
861                } else {
862                    assert(ss_contains(osparse, oindices, olive, kk));
863                    let x = choose|x: int| 0 <= x < n0 && oroots[x] == x as usize
864                        && (#[trigger] opay[x]).get_spec()->Some_0.as_nat() == kk;
865                    assert(roots[x] == x as usize);
866                    assert(pay[x].get_spec()->Some_0.as_nat() == kk);
867                }
868            }
869            // --- W3a / W3b (rings gained the singleton [n0])
870            assert forall|c: int, p: int, q: int|
871                0 <= c < rm.len() && 0 <= p < rm[c].len() && 0 <= q < rm[c].len()
872                implies roots[(#[trigger] rm[c][p]) as int]
873                    == roots[(#[trigger] rm[c][q]) as int] by {
874                if c < orm.len() {
875                    assert(rm[c] == orm[c]);
876                    assert(orm[c][p] < n0 && orm[c][q] < n0);
877                    assert(roots[orm[c][p] as int] == oroots[orm[c][p] as int]);
878                    assert(roots[orm[c][q] as int] == oroots[orm[c][q] as int]);
879                }
880            }
881            assert forall|c1: int, p1: int, c2: int, p2: int|
882                0 <= c1 < rm.len() && 0 <= p1 < rm[c1].len()
883                    && 0 <= c2 < rm.len() && 0 <= p2 < rm[c2].len()
884                    && roots[(#[trigger] rm[c1][p1]) as int]
885                        == roots[(#[trigger] rm[c2][p2]) as int]
886                implies c1 == c2 by {
887                if c1 < orm.len() && c2 < orm.len() {
888                    assert(rm[c1] == orm[c1] && rm[c2] == orm[c2]);
889                    assert(orm[c1][p1] < n0 && orm[c2][p2] < n0);
890                } else if c1 < orm.len() && c2 == orm.len() as int {
891                    // old member's root is an old id (< n0); the new ring's
892                    // sole member has root n0.
893                    assert(rm[c1][p1] < n0);
894                    assert(roots[rm[c1][p1] as int] == oroots[rm[c1][p1] as int]);
895                    assert(oroots[rm[c1][p1] as int] < n0 as usize);
896                    assert(rm[c2][p2] == n0 as usize);
897                    assert(roots[n0 as int] == n0 as usize);
898                } else if c2 < orm.len() && c1 == orm.len() as int {
899                    assert(rm[c2][p2] < n0);
900                    assert(roots[rm[c2][p2] as int] == oroots[rm[c2][p2] as int]);
901                    assert(oroots[rm[c2][p2] as int] < n0 as usize);
902                    assert(rm[c1][p1] == n0 as usize);
903                    assert(roots[n0 as int] == n0 as usize);
904                }
905            }
906            // --- W4
907            assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
908                implies ss_value(dense, sparse, kk).use_list.id_nat() < um.len() by {
909                if kk != kn {
910                    assert(ss_contains(osparse, oindices, olive, kk));
911                    assert(ss_value(dense, sparse, kk) == ss_value(odense, osparse, kk));
912                }
913            }
914            assert forall|k1: nat, k2: nat|
915                ss_contains(sparse, indices, live, k1)
916                    && ss_contains(sparse, indices, live, k2) && k1 != k2
917                implies #[trigger] ss_value(dense, sparse, k1).use_list.id_nat()
918                    != #[trigger] ss_value(dense, sparse, k2).use_list.id_nat() by {
919                if k1 != kn && k2 != kn {
920                    assert(ss_contains(osparse, oindices, olive, k1));
921                    assert(ss_contains(osparse, oindices, olive, k2));
922                    assert(ss_value(dense, sparse, k1) == ss_value(odense, osparse, k1));
923                    assert(ss_value(dense, sparse, k2) == ss_value(odense, osparse, k2));
924                } else if k1 == kn {
925                    assert(ss_contains(osparse, oindices, olive, k2));
926                    assert(ss_value(dense, sparse, k2) == ss_value(odense, osparse, k2));
927                    assert(ss_value(dense, sparse, k2).use_list.id_nat() < oum.len());
928                    assert(ss_value(dense, sparse, k1).use_list.id_nat() == oum.len());
929                } else {
930                    assert(ss_contains(osparse, oindices, olive, k1));
931                    assert(ss_value(dense, sparse, k1) == ss_value(odense, osparse, k1));
932                    assert(ss_value(dense, sparse, k1).use_list.id_nat() < oum.len());
933                    assert(ss_value(dense, sparse, k2).use_list.id_nat() == oum.len());
934                }
935            }
936            // --- W5 (new list is empty; old lists and nodes untouched)
937            assert forall|l: int, p: int|
938                0 <= l < um.len() && 0 <= p < (#[trigger] um[l]).len()
939                implies un[#[trigger] um[l][p] as int].payload.id_nat() < n1 by {
940                assert(l < oum.len());
941                assert(um[l] == oum[l]);
942            }
943            // --- W6 (pool untouched; new key has no row)
944            assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
945                && ss_value(dense, sparse, kk).min_row is Some
946                implies self.min_width as nat > 0
947                    && (ss_value(dense, sparse, kk).min_row->Some_0.as_nat() + 1)
948                        * (self.min_width as nat) <= self.min_pool.view().len() by {
949                assert(kk != kn);
950                assert(ss_contains(osparse, oindices, olive, kk));
951                assert(ss_value(dense, sparse, kk) == ss_value(odense, osparse, kk));
952            }
953            assert forall|k1: nat, k2: nat|
954                ss_contains(sparse, indices, live, k1)
955                    && ss_contains(sparse, indices, live, k2) && k1 != k2
956                    && #[trigger] ss_value(dense, sparse, k1).min_row is Some
957                    && #[trigger] ss_value(dense, sparse, k2).min_row is Some
958                implies ss_value(dense, sparse, k1).min_row->Some_0.as_nat()
959                    != ss_value(dense, sparse, k2).min_row->Some_0.as_nat() by {
960                assert(k1 != kn && k2 != kn);
961                assert(ss_contains(osparse, oindices, olive, k1));
962                assert(ss_contains(osparse, oindices, olive, k2));
963                assert(ss_value(dense, sparse, k1) == ss_value(odense, osparse, k1));
964                assert(ss_value(dense, sparse, k2) == ss_value(odense, osparse, k2));
965            }
966            assert(eg_model_wf::<T, K, L, N>(rm, pay, roots, dense, sparse, indices,
967                um, un, self.min_pool.view(), self.min_width as nat));
968            // the archive transfers by congruence: every snapshot stack is
969            // framed by the component contracts.
970            assert(eg_archive_agrees::<T, K, L, N>(
971                self.entries.model_snapshots_view(),
972                self.entries.entries_snapshots_view(),
973                self.uf.roots_snapshots_view(),
974                self.reprs.dense_snapshots_view(),
975                self.reprs.sparse_snapshots_view(),
976                self.reprs.indices_snapshots_view(),
977                self.uses.model_snapshots_view(),
978                self.uses.nodes_snapshots_view(),
979                self.min_pool.snapshots_view(),
980                self.min_width as nat))
981            by {
982                assert(self.entries.model_snapshots_view()
983                    == o.entries.model_snapshots_view());
984                assert(self.entries.entries_snapshots_view()
985                    == o.entries.entries_snapshots_view());
986                assert(self.uf.roots_snapshots_view() == o.uf.roots_snapshots_view());
987                assert(self.reprs.dense_snapshots_view()
988                    == o.reprs.dense_snapshots_view());
989                assert(self.reprs.sparse_snapshots_view()
990                    == o.reprs.sparse_snapshots_view());
991                assert(self.reprs.indices_snapshots_view()
992                    == o.reprs.indices_snapshots_view());
993                assert(self.uses.model_snapshots_view()
994                    == o.uses.model_snapshots_view());
995                assert(self.uses.nodes_snapshots_view()
996                    == o.uses.nodes_snapshots_view());
997                assert(self.min_pool.snapshots_view() == o.min_pool.snapshots_view());
998            }
999        }
1000        (id, key)
1001    }
1002}
1003
1004
1005/// W5 after a use-list splice, over bare views (extracted like
1006/// `lemma_splice_disjoint`: in the method body this quantifier e-matches
1007/// against both states' full wf).
1008pub(crate) proof fn lemma_splice_uses_w5<T: DenseId, N: DenseId + Tagged>(
1009    oum: Seq<Seq<usize>>, um: Seq<Seq<usize>>,
1010    oun: Seq<ListNode<T, N>>, un: Seq<ListNode<T, N>>,
1011    di: int, si: int, n: nat,
1012)
1013    requires
1014        0 <= di < oum.len(),
1015        0 <= si < oum.len(),
1016        di != si,
1017        um == oum.update(di, oum[di] + oum[si]).update(si, Seq::<usize>::empty()),
1018        un.len() == oun.len(),
1019        forall|k: int| 0 <= k < oun.len()
1020            ==> (#[trigger] un[k]).payload == oun[k].payload,
1021        forall|l: int, p: int|
1022            0 <= l < oum.len() && 0 <= p < oum[l].len()
1023                ==> (#[trigger] oum[l][p]) < oun.len(),
1024        forall|l: int, p: int|
1025            0 <= l < oum.len() && 0 <= p < oum[l].len()
1026                ==> oun[(#[trigger] oum[l][p]) as int].payload.id_nat() < n,
1027    ensures
1028        forall|l: int, p: int|
1029            0 <= l < um.len() && 0 <= p < (#[trigger] um[l]).len()
1030                ==> un[#[trigger] um[l][p] as int].payload.id_nat() < n,
1031{
1032    assert forall|l: int, p: int|
1033        0 <= l < um.len() && 0 <= p < (#[trigger] um[l]).len()
1034        implies un[#[trigger] um[l][p] as int].payload.id_nat() < n by {
1035        if l == di {
1036            if p < oum[di].len() {
1037                assert(um[l][p] == oum[di][p]);
1038            } else {
1039                assert(um[l][p] == oum[si][p - oum[di].len()]);
1040            }
1041        } else if l != si {
1042            assert(um[l] == oum[l]);
1043        }
1044        assert(um[l][p] < oun.len());
1045        assert(un[um[l][p] as int].payload == oun[um[l][p] as int].payload);
1046    }
1047}
1048
1049// ---------------------------------------------------------------------------
1050// Merge
1051// ---------------------------------------------------------------------------
1052
1053/// Returned by `merge`: the surviving and absorbed canonical ids plus the
1054/// absorbed class's data, which the rebuild loop consumes (production's
1055/// `MergeInfo`).
1056pub struct MergeInfo<T: DenseId, L: DenseId> {
1057    pub survivor: T,
1058    pub absorbed: T,
1059    pub absorbed_uses: L,
1060    pub absorbed_min_row: Option<<T as DenseId>::Index>,
1061    pub absorbed_atomic: bool,
1062}
1063
1064impl<T, K, L, N, J, const TRACK: bool, const PROOFS: bool>
1065    EClasses<T, K, L, N, J, TRACK, PROOFS>
1066where
1067    T: DenseId,
1068    K: DenseId<Index = T::Index>,
1069    L: DenseId,
1070    N: DenseId + Tagged + core::default::Default,
1071    J: Tagged + Copy + core::default::Default,
1072{
1073
1074    /// Re-establishes `eg_model_wf` after a merge's three mutations (union,
1075    /// ring splice with payload clear, repr removal). Extracted for the same
1076    /// reason as `lemma_splice_disjoint` (list.rs): proved inline, the ring
1077    /// and root quantifiers e-match against both states' full `wf`.
1078    proof fn lemma_merge_wf(&self, o: Self, s: T, ab: T, key_ab: nat, skey: nat,
1079        ab_pay: Opt<K>, cs: int, ps: int, ca: int, pa: int)
1080        requires
1081            o.wf(),
1082            self.uf.wf(),
1083            self.entries.wf(),
1084            self.reprs.wf(),
1085            self.uses.wf(),
1086            self.min_pool.wf(),
1087            s.id_nat() < o.n_spec(),
1088            ab.id_nat() < o.n_spec(),
1089            s.id_nat() != ab.id_nat(),
1090            s.id_nat() <= usize::MAX as nat,
1091            ab.id_nat() <= usize::MAX as nat,
1092            o.roots_view()[s.id_nat() as int] == s.id_nat() as usize,
1093            o.roots_view()[ab.id_nat() as int] == ab.id_nat() as usize,
1094            key_ab == o.key_of(ab.id_nat() as int),
1095            ss_contains(o.reprs.sparse_view(), o.reprs.indices_view(),
1096                o.reprs.n_spec(), key_ab),
1097            skey == o.key_of(s.id_nat() as int),
1098            ss_contains(o.reprs.sparse_view(), o.reprs.indices_view(),
1099                o.reprs.n_spec(), skey),
1100            skey != key_ab,
1101            0 <= cs < o.entries.model_view().len(),
1102            0 <= ps < o.entries.model_view()[cs].len(),
1103            o.entries.model_view()[cs][ps] == s.id_nat() as usize,
1104            0 <= ca < o.entries.model_view().len(),
1105            0 <= pa < o.entries.model_view()[ca].len(),
1106            o.entries.model_view()[ca][pa] == ab.id_nat() as usize,
1107            cs != ca,
1108            self.entries.model_view() == o.entries.model_view()
1109                .update(cs, crate::circular_list::rotate(o.entries.model_view()[cs], ps + 1)
1110                    + crate::circular_list::rotate(o.entries.model_view()[ca], pa + 1))
1111                .update(ca, Seq::<usize>::empty()),
1112            self.entries.payload_seq()
1113                == o.entries.payload_seq().update(ab.id_nat() as int, ab_pay),
1114            self.entries.n_spec() == o.n_spec(),
1115            ab_pay.wf(),
1116            ab_pay.get_spec() is None,
1117            self.uf.roots_view() == crate::union_find::merge_roots(
1118                o.roots_view(), s.id_nat(), ab.id_nat()),
1119            self.uf.n_spec() == o.n_spec(),
1120            self.reprs.n_spec() == o.reprs.n_spec() - 1,
1121            self.reprs.cap_spec() == o.reprs.cap_spec(),
1122            self.reprs.id_set() == o.reprs.id_set().remove(key_ab),
1123            forall|k: <T as DenseId>::Index| #[trigger] o.reprs.contains_spec(k)
1124                && k.as_nat() != key_ab && k.as_nat() != skey
1125                ==> self.reprs.contains_spec(k)
1126                    && ss_value(self.reprs.dense_view(), self.reprs.sparse_view(),
1127                            k.as_nat())
1128                        == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(),
1129                            k.as_nat()),
1130            // the survivor's key stays live with only its size folded:
1131            // new size = old survivor size + absorbed size.
1132            forall|k: <T as DenseId>::Index| #[trigger] o.reprs.contains_spec(k)
1133                && k.as_nat() == skey
1134                ==> self.reprs.contains_spec(k),
1135            ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), skey).use_list
1136                == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), skey).use_list,
1137            ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), skey).min_row
1138                == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), skey).min_row,
1139            ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), skey).atomic
1140                == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), skey).atomic,
1141            ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), skey)
1142                .size.as_nat()
1143                == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), skey)
1144                    .size.as_nat()
1145                    + ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), key_ab)
1146                        .size.as_nat(),
1147            self.uses.model_view() == o.uses.model_view(),
1148            self.uses.nodes_view() == o.uses.nodes_view(),
1149            self.min_pool.view() == o.min_pool.view(),
1150            self.min_width == o.min_width,
1151        ensures
1152            eg_model_wf::<T, K, L, N>(
1153                self.entries.model_view(), self.entries.payload_seq(),
1154                self.uf.roots_view(), self.reprs.dense_view(),
1155                self.reprs.sparse_view(), self.reprs.indices_view(),
1156                self.uses.model_view(), self.uses.nodes_view(),
1157                self.min_pool.view(), self.min_width as nat),
1158            self.reprs.cap_spec() <= self.n_spec(),
1159    {
1160        let n = o.n_spec();
1161        let sn = s.id_nat();
1162        let abn = ab.id_nat();
1163        let su = sn as usize;
1164        let abu = abn as usize;
1165        let orm = o.entries.model_view();
1166        let opay = o.entries.payload_seq();
1167        let oroots = o.roots_view();
1168        let odense = o.reprs.dense_view();
1169        let osparse = o.reprs.sparse_view();
1170        let oindices = o.reprs.indices_view();
1171        let olive = o.reprs.n_spec();
1172        let rm = self.entries.model_view();
1173        let pay = self.entries.payload_seq();
1174        let roots = self.uf.roots_view();
1175        let dense = self.reprs.dense_view();
1176        let sparse = self.reprs.sparse_view();
1177        let indices = self.reprs.indices_view();
1178        let live = self.reprs.n_spec();
1179        let um = self.uses.model_view();
1180        let un = self.uses.nodes_view();
1181        let merged = crate::circular_list::rotate(orm[cs], ps + 1)
1182            + crate::circular_list::rotate(orm[ca], pa + 1);
1183
1184        // casts between int positions and usize root values are faithful:
1185        // every id is below n <= id_bound <= usize::MAX + 1.
1186        T::lemma_id_bound_fits_usize();
1187        assert(n <= usize::MAX as nat + 1);
1188
1189        crate::circular_list::lemma_rotate_props(orm[cs], ps + 1);
1190        crate::circular_list::lemma_rotate_props(orm[ca], pa + 1);
1191
1192        // every merged-ring element is an element of one of the two old rings
1193        assert forall|q: int| 0 <= q < merged.len() implies
1194            exists|c0: int, j: int| (c0 == cs || c0 == ca)
1195                && 0 <= j < orm[c0].len()
1196                && (#[trigger] orm[c0][j]) == #[trigger] merged[q] by {
1197            let lcs = orm[cs].len() as int;
1198            if q < lcs {
1199                let j = if ps + 1 + q < lcs { ps + 1 + q } else { ps + 1 + q - lcs };
1200                assert(merged[q] == orm[cs][j]);
1201            } else {
1202                let q2 = q - lcs;
1203                let lca = orm[ca].len() as int;
1204                let j = if pa + 1 + q2 < lca { pa + 1 + q2 } else { pa + 1 + q2 - lca };
1205                assert(merged[q] == orm[ca][j]);
1206            }
1207        }
1208        // old roots of the two rings' members: cs members root to s, ca to ab
1209        assert forall|j: int| 0 <= j < orm[cs].len() implies
1210            oroots[(#[trigger] orm[cs][j]) as int] == su by {
1211            assert(oroots[orm[cs][j] as int] == oroots[orm[cs][ps] as int]);
1212        }
1213        assert forall|j: int| 0 <= j < orm[ca].len() implies
1214            oroots[(#[trigger] orm[ca][j]) as int] == abu by {
1215            assert(oroots[orm[ca][j] as int] == oroots[orm[ca][pa] as int]);
1216        }
1217        // a member of any OTHER ring roots to neither s nor ab
1218        assert forall|c: int, p: int|
1219            0 <= c < orm.len() && c != cs && c != ca && 0 <= p < orm[c].len()
1220            implies oroots[(#[trigger] orm[c][p]) as int] != su
1221                && oroots[orm[c][p] as int] != abu by {
1222            if oroots[orm[c][p] as int] == su {
1223                // same root as s -> same ring as s (old W3b) -> c == cs.
1224                assert(oroots[orm[cs][ps] as int] == su);
1225            }
1226            if oroots[orm[c][p] as int] == abu {
1227                assert(oroots[orm[ca][pa] as int] == abu);
1228            }
1229        }
1230        // the remap in one line: roots[x] = s if old ab, else old.
1231        assert forall|x: int| 0 <= x < n implies
1232            #[trigger] roots[x] == (if oroots[x] == abu { su } else { oroots[x] }) by {
1233            assert(roots[x] == crate::union_find::merge_roots(oroots, sn, abn)[x]);
1234        }
1235
1236        // survivors + dead-stay-dead, in the nat form the clauses use: values
1237        // carry field-for-field, fully except the survivor key's folded size.
1238        assert forall|kk: nat| #[trigger] ss_contains(osparse, oindices, olive, kk)
1239            && kk != key_ab
1240            implies ss_contains(sparse, indices, live, kk)
1241                && ss_value(dense, sparse, kk).use_list
1242                    == ss_value(odense, osparse, kk).use_list
1243                && ss_value(dense, sparse, kk).min_row
1244                    == ss_value(odense, osparse, kk).min_row
1245                && (kk != skey ==> ss_value(dense, sparse, kk)
1246                    == ss_value(odense, osparse, kk)) by {
1247            let kw = oindices[osparse[kk as int].as_nat() as int];
1248            assert(kw.as_nat() == kk);
1249            assert(o.reprs.contains_spec(kw));
1250            assert(self.reprs.contains_spec(kw));
1251        }
1252        assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
1253            implies ss_contains(osparse, oindices, olive, kk) && kk != key_ab by {
1254            let kw = indices[sparse[kk as int].as_nat() as int];
1255            assert(kw.as_nat() == kk);
1256            assert(self.reprs.contains_spec(kw));
1257            assert(self.reprs.id_set().contains(kk)) by {
1258                assert(indices[sparse[kk as int].as_nat() as int].as_nat() == kk);
1259            }
1260            assert(o.reprs.id_set().contains(kk) && kk != key_ab);
1261            let p = choose|p: int| 0 <= p < olive
1262                && (#[trigger] oindices[p]).as_nat() == kk;
1263            let ow = oindices[p];
1264            assert(o.reprs.contains_spec(ow));
1265        }
1266
1267        // --- Opt wf on payload cells
1268        assert forall|x: int| 0 <= x < n implies (#[trigger] pay[x]).wf() by {
1269            if x != abn as int { assert(pay[x] == opay[x]); }
1270        }
1271        // --- W2a
1272        assert forall|x: int| 0 <= x < n implies
1273            ((#[trigger] roots[x]) == x as usize <==> pay[x].get_spec() is Some) by {
1274            if x == abn as int {
1275                assert(roots[x] == su);
1276                assert(pay[x] == ab_pay);
1277            } else {
1278                assert(pay[x] == opay[x]);
1279                if oroots[x] == abu {
1280                    // x was in ab's class but is not ab: not an old root
1281                    // (an old root satisfies oroots[x] == x, which with
1282                    // oroots[x] == ab forces x == ab), and its new root is
1283                    // s != x (x == s would make s's old root ab).
1284                    if oroots[x] == x as usize {
1285                        assert(x as usize == abu);
1286                        assert(x == abn as int);
1287                        assert(false);
1288                    }
1289                    assert(roots[x] == su);
1290                    if roots[x] == x as usize {
1291                        assert(x as usize == su);
1292                        assert(x == sn as int);
1293                        assert(oroots[sn as int] == su);
1294                        assert(false);
1295                    }
1296                } else {
1297                    assert(roots[x] == oroots[x]);
1298                }
1299            }
1300        }
1301        // --- W2b
1302        assert forall|x: int| 0 <= x < n && (#[trigger] roots[x]) == x as usize
1303            implies ss_contains(sparse, indices, live,
1304                pay[x].get_spec()->Some_0.as_nat()) by {
1305            assert(x != abn as int);
1306            assert(pay[x] == opay[x]);
1307            assert(oroots[x] == x as usize);
1308            assert(ss_contains(osparse, oindices, olive,
1309                opay[x].get_spec()->Some_0.as_nat()));
1310            // x's key is not ab's key: W2c injectivity in the old state.
1311            assert(opay[x].get_spec()->Some_0.as_nat() != key_ab);
1312        }
1313        // --- W2c
1314        assert forall|x: int, y: int|
1315            0 <= x < n && 0 <= y < n && x != y
1316                && (#[trigger] roots[x]) == x as usize
1317                && (#[trigger] roots[y]) == y as usize
1318            implies pay[x].get_spec()->Some_0.as_nat()
1319                != pay[y].get_spec()->Some_0.as_nat() by {
1320            assert(x != abn as int && y != abn as int);
1321            assert(pay[x] == opay[x] && pay[y] == opay[y]);
1322            assert(oroots[x] == x as usize && oroots[y] == y as usize);
1323        }
1324        // --- W2d
1325        assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
1326            implies exists|x: int| 0 <= x < n && roots[x] == x as usize
1327                && (#[trigger] pay[x]).get_spec()->Some_0.as_nat() == kk by {
1328            assert(ss_contains(osparse, oindices, olive, kk) && kk != key_ab);
1329            let x = choose|x: int| 0 <= x < n && oroots[x] == x as usize
1330                && (#[trigger] opay[x]).get_spec()->Some_0.as_nat() == kk;
1331            // x is an old root with key kk != key_ab, so x != ab, so x keeps
1332            // its payload; and x's class was not ab's (both were roots), so
1333            // its root stays x.
1334            assert(x != abn as int) by {
1335                if x == abn as int { assert(kk == key_ab); }
1336            }
1337            assert(oroots[x] != abu) by {
1338                if oroots[x] == abu {
1339                    assert(x as usize == abu);
1340                    assert(x == abn as int);
1341                    assert(false);
1342                }
1343            }
1344            assert(roots[x] == x as usize);
1345            assert(pay[x] == opay[x]);
1346        }
1347        // --- W3a
1348        assert forall|c: int, p: int, q: int|
1349            0 <= c < rm.len() && 0 <= p < rm[c].len() && 0 <= q < rm[c].len()
1350            implies roots[(#[trigger] rm[c][p]) as int]
1351                == roots[(#[trigger] rm[c][q]) as int] by {
1352            if c == cs {
1353                assert(rm[c] == merged);
1354                // both elements come from the two old rings; either way the
1355                // new root is s.
1356                let (c1, j1) = choose|c0: int, j: int| (c0 == cs || c0 == ca)
1357                    && 0 <= j < orm[c0].len() && (#[trigger] orm[c0][j]) == merged[p];
1358                let (c2, j2) = choose|c0: int, j: int| (c0 == cs || c0 == ca)
1359                    && 0 <= j < orm[c0].len() && (#[trigger] orm[c0][j]) == merged[q];
1360                assert(roots[merged[p] as int] == su);
1361                assert(roots[merged[q] as int] == su);
1362            } else if c == ca {
1363                assert(rm[c].len() == 0);
1364            } else {
1365                assert(rm[c] == orm[c]);
1366                assert(oroots[orm[c][p] as int] == oroots[orm[c][q] as int]);
1367                assert(oroots[orm[c][p] as int] != abu);
1368            }
1369        }
1370        // --- W3b
1371        assert forall|c1: int, p1: int, c2: int, p2: int|
1372            0 <= c1 < rm.len() && 0 <= p1 < rm[c1].len()
1373                && 0 <= c2 < rm.len() && 0 <= p2 < rm[c2].len()
1374                && roots[(#[trigger] rm[c1][p1]) as int]
1375                    == roots[(#[trigger] rm[c2][p2]) as int]
1376            implies c1 == c2 by {
1377            // roots of members: cs -> s; other rings -> their old root,
1378            // which is neither s nor ab.
1379            if c1 == cs && c2 != cs && c2 != ca {
1380                assert(roots[rm[c1][p1] as int] == su);
1381                assert(rm[c2] == orm[c2]);
1382                assert(oroots[orm[c2][p2] as int] != abu);
1383                assert(roots[rm[c2][p2] as int] == oroots[orm[c2][p2] as int]);
1384                assert(oroots[orm[c2][p2] as int] != su);
1385                assert(false);
1386            } else if c2 == cs && c1 != cs && c1 != ca {
1387                assert(roots[rm[c2][p2] as int] == su);
1388                assert(rm[c1] == orm[c1]);
1389                assert(oroots[orm[c1][p1] as int] != abu);
1390                assert(roots[rm[c1][p1] as int] == oroots[orm[c1][p1] as int]);
1391                assert(oroots[orm[c1][p1] as int] != su);
1392                assert(false);
1393            } else if c1 != cs && c1 != ca && c2 != cs && c2 != ca {
1394                assert(rm[c1] == orm[c1] && rm[c2] == orm[c2]);
1395                assert(oroots[orm[c1][p1] as int] != abu);
1396                assert(oroots[orm[c2][p2] as int] != abu);
1397                assert(roots[rm[c1][p1] as int] == oroots[orm[c1][p1] as int]);
1398                assert(roots[rm[c2][p2] as int] == oroots[orm[c2][p2] as int]);
1399            } else if c1 == ca {
1400                assert(rm[ca].len() == 0);
1401            } else if c2 == ca {
1402                assert(rm[ca].len() == 0);
1403            }
1404        }
1405        // --- W4
1406        assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
1407            implies ss_value(dense, sparse, kk).use_list.id_nat() < um.len() by {
1408            assert(ss_contains(osparse, oindices, olive, kk) && kk != key_ab);
1409            assert(ss_value(dense, sparse, kk).use_list
1410                == ss_value(odense, osparse, kk).use_list);
1411        }
1412        assert forall|k1: nat, k2: nat|
1413            ss_contains(sparse, indices, live, k1)
1414                && ss_contains(sparse, indices, live, k2) && k1 != k2
1415            implies #[trigger] ss_value(dense, sparse, k1).use_list.id_nat()
1416                != #[trigger] ss_value(dense, sparse, k2).use_list.id_nat() by {
1417            assert(ss_contains(osparse, oindices, olive, k1) && k1 != key_ab);
1418            assert(ss_contains(osparse, oindices, olive, k2) && k2 != key_ab);
1419            assert(ss_value(dense, sparse, k1).use_list
1420                == ss_value(odense, osparse, k1).use_list);
1421            assert(ss_value(dense, sparse, k2).use_list
1422                == ss_value(odense, osparse, k2).use_list);
1423        }
1424        // --- W5 (uses untouched)
1425        assert forall|l: int, p: int|
1426            0 <= l < um.len() && 0 <= p < (#[trigger] um[l]).len()
1427            implies un[#[trigger] um[l][p] as int].payload.id_nat() < n by {
1428            assert(um[l] == o.uses.model_view()[l]);
1429        }
1430        // --- W6
1431        assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
1432            && ss_value(dense, sparse, kk).min_row is Some
1433            implies self.min_width as nat > 0
1434                && (ss_value(dense, sparse, kk).min_row->Some_0.as_nat() + 1)
1435                    * (self.min_width as nat) <= self.min_pool.view().len() by {
1436            assert(ss_contains(osparse, oindices, olive, kk) && kk != key_ab);
1437            assert(ss_value(dense, sparse, kk).min_row
1438                == ss_value(odense, osparse, kk).min_row);
1439        }
1440        assert forall|k1: nat, k2: nat|
1441            ss_contains(sparse, indices, live, k1)
1442                && ss_contains(sparse, indices, live, k2) && k1 != k2
1443                && #[trigger] ss_value(dense, sparse, k1).min_row is Some
1444                && #[trigger] ss_value(dense, sparse, k2).min_row is Some
1445            implies ss_value(dense, sparse, k1).min_row->Some_0.as_nat()
1446                != ss_value(dense, sparse, k2).min_row->Some_0.as_nat() by {
1447            assert(ss_contains(osparse, oindices, olive, k1) && k1 != key_ab);
1448            assert(ss_contains(osparse, oindices, olive, k2) && k2 != key_ab);
1449            assert(ss_value(dense, sparse, k1).min_row
1450                == ss_value(odense, osparse, k1).min_row);
1451            assert(ss_value(dense, sparse, k2).min_row
1452                == ss_value(odense, osparse, k2).min_row);
1453        }
1454        // --- W7: the stored class size is the ring length.
1455        // s sits on the merged ring: rotate(orm[cs], ps+1)[lcs-1] == orm[cs][ps].
1456        let lcs = orm[cs].len() as int;
1457        assert(merged[lcs - 1] == orm[cs][ps]);
1458        assert forall|c: int, p: int|
1459            0 <= c < rm.len() && 0 <= p < rm[c].len()
1460                && roots[(#[trigger] rm[c][p]) as int] == rm[c][p]
1461            implies ss_value(dense, sparse,
1462                    pay[rm[c][p] as int].get_spec()->Some_0.as_nat())
1463                .size.as_nat() == rm[c].len() by {
1464            let m = rm[c][p];
1465            if c == ca {
1466                assert(rm[ca].len() == 0);
1467            } else if c == cs {
1468                // every merged member roots to s, so the root member IS s.
1469                assert(roots[m as int] == su);
1470                assert(m == su);
1471                assert(pay[m as int] == opay[m as int]);
1472                assert(pay[m as int].get_spec()->Some_0.as_nat() == skey);
1473                // o's W7 at the two old rings gives the two old sizes.
1474                assert(oroots[orm[cs][ps] as int] == orm[cs][ps]);
1475                assert(ss_value(odense, osparse, skey).size.as_nat()
1476                    == orm[cs].len());
1477                assert(oroots[orm[ca][pa] as int] == orm[ca][pa]);
1478                assert(ss_value(odense, osparse, key_ab).size.as_nat()
1479                    == orm[ca].len());
1480                assert(merged.len() == orm[cs].len() + orm[ca].len());
1481                assert(ss_value(dense, sparse, skey).size.as_nat()
1482                    == orm[cs].len() + orm[ca].len());
1483            } else {
1484                assert(rm[c] == orm[c]);
1485                // the root member kept its old root (it is neither s's nor
1486                // ab's class member: those all live on cs/ca in o).
1487                assert(oroots[m as int] != abu && oroots[m as int] != su);
1488                assert(roots[m as int] == oroots[m as int]);
1489                assert(oroots[m as int] == m);
1490                assert(m != abu && m != su);
1491                assert(pay[m as int] == opay[m as int]);
1492                let kk = opay[m as int].get_spec()->Some_0.as_nat();
1493                assert(ss_contains(osparse, oindices, olive, kk));
1494                assert(ss_value(odense, osparse, kk).size.as_nat() == orm[c].len());
1495                // kk is neither the absorbed key nor the survivor key (W2c on
1496                // o: distinct roots carry distinct keys).
1497                assert(kk != key_ab);
1498                assert(kk != skey);
1499                assert(ss_value(dense, sparse, kk) == ss_value(odense, osparse, kk));
1500            }
1501        }
1502        assert(eg_model_wf::<T, K, L, N>(rm, pay, roots, dense, sparse, indices,
1503            um, un, self.min_pool.view(), self.min_width as nat));
1504    }
1505
1506    /// Merge the classes of `a` and `b`: union-find link, ring splice with
1507    /// the absorbed payload cleared, repr removal. `None` iff already one
1508    /// class. The core of `merge` and `merge_directed`; the distinct-rings
1509    /// precondition of `splice_absorb` is discharged here from W2 + W3.
1510    pub(crate) fn merge_with(&mut self, a: T, b: T, directed: bool, prefer_a: bool)
1511        -> (r: Option<MergeInfo<T, L>>)
1512        requires old(self).wf(),
1513        ensures
1514            final(self).wf(),
1515            final(self).n_spec() == old(self).n_spec(),
1516            final(self).min_width_spec() == old(self).min_width_spec(),
1517            a.id_nat() < old(self).n_spec() && b.id_nat() < old(self).n_spec() ==> {
1518                let ra = old(self).roots_view()[a.id_nat() as int] as nat;
1519                let rb = old(self).roots_view()[b.id_nat() as int] as nat;
1520                &&& (r is None <==> ra == rb)
1521                &&& (r is None ==> final(self).roots_view() == old(self).roots_view()
1522                        && final(self).num_classes_spec() == old(self).num_classes_spec())
1523                &&& (r matches Some(mi) ==> {
1524                        &&& ((mi.survivor.id_nat() == ra && mi.absorbed.id_nat() == rb)
1525                            || (mi.survivor.id_nat() == rb && mi.absorbed.id_nat() == ra))
1526                        &&& (directed ==> mi.survivor.id_nat()
1527                                == (if prefer_a { ra } else { rb }))
1528                        &&& ra != rb
1529                        &&& final(self).roots_view() == crate::union_find::merge_roots(
1530                                old(self).roots_view(), mi.survivor.id_nat(),
1531                                mi.absorbed.id_nat())
1532                        &&& final(self).num_classes_spec()
1533                            == old(self).num_classes_spec() - 1
1534                        &&& mi.absorbed_uses == old(self).class_data_spec(
1535                                old(self).key_of(mi.absorbed.id_nat() as int)).use_list
1536                        &&& mi.absorbed_min_row == old(self).class_data_spec(
1537                                old(self).key_of(mi.absorbed.id_nat() as int)).min_row
1538                        &&& mi.absorbed_atomic == old(self).class_data_spec(
1539                                old(self).key_of(mi.absorbed.id_nat() as int)).atomic
1540                    })
1541            },
1542    {
1543        if !(a.to_usize() < self.uf.len().as_usize()
1544            && b.to_usize() < self.uf.len().as_usize())
1545        {
1546            crate::guard::refuse("EClasses::merge: node id out of range");
1547        }
1548        let ghost o = *old(self);
1549        let ghost n = o.n_spec();
1550        let res = if directed {
1551            self.uf.union_directed_core(a, b, prefer_a)
1552        } else {
1553            self.uf.union_core(a, b)
1554        };
1555        let (s, ab) = match res {
1556            None => {
1557                return None;
1558            }
1559            Some(pair) => pair,
1560        };
1561        proof {
1562            crate::opt::lemma_id_nat_fits_usize(s);
1563            crate::opt::lemma_id_nat_fits_usize(ab);
1564            // s and ab are distinct old roots.
1565            assert(o.roots_view()[s.id_nat() as int] == s.id_nat() as usize);
1566            assert(o.roots_view()[ab.id_nat() as int] == ab.id_nat() as usize);
1567            assert(s.id_nat() != ab.id_nat());
1568        }
1569        // the absorbed root's payload is present (W2a) and names a live class key
1570        // (W2b): production reads it with get_unchecked; here presence is a
1571        // theorem.
1572        let pay_ab = self.entries.payload_of(ab);
1573        proof {
1574            assert(self.entries == o.entries);
1575            assert(pay_ab == o.entries.payload_seq()[ab.id_nat() as int]);
1576            assert(pay_ab.wf());
1577            assert(pay_ab.get_spec() is Some);
1578        }
1579        let key = pay_ab.get();
1580        let raw_key = Self::key_index(key);
1581        proof {
1582            assert(key.as_nat() == o.key_of(ab.id_nat() as int));
1583            assert(ss_contains(o.reprs.sparse_view(), o.reprs.indices_view(),
1584                o.reprs.n_spec(), key.as_nat()));
1585            assert(self.reprs.contains_spec(raw_key));
1586        }
1587        let data = self.reprs.get_live(raw_key);
1588        proof {
1589            assert(data == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(),
1590                key.as_nat()));
1591        }
1592        // Survivor size fold, BEFORE the splice so the wf lemma sees the final
1593        // payload: survivor.size += absorbed.size, tied to the merged ring
1594        // length by W7. The survivor root's payload is present (W2a) and
1595        // names a live class key (W2b), the same theorem as for `ab` above.
1596        let pay_s = self.entries.payload_of(s);
1597        proof {
1598            assert(pay_s == o.entries.payload_seq()[s.id_nat() as int]);
1599            assert(pay_s.wf());
1600            assert(pay_s.get_spec() is Some);
1601        }
1602        let skey = pay_s.get();
1603        let raw_skey = Self::key_index(skey);
1604        proof {
1605            assert(skey.as_nat() == o.key_of(s.id_nat() as int));
1606            assert(ss_contains(o.reprs.sparse_view(), o.reprs.indices_view(),
1607                o.reprs.n_spec(), skey.as_nat()));
1608            assert(self.reprs.contains_spec(raw_skey));
1609            // distinct roots carry distinct keys (W2c).
1610            assert(skey.as_nat() != key.as_nat());
1611        }
1612        let mut sdata = self.reprs.get_live(raw_skey);
1613        proof {
1614            assert(sdata == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(),
1615                skey.as_nat()));
1616        }
1617        sdata.size = match crate::index_like::checked_add(sdata.size, data.size) {
1618            Some(v) => v,
1619            None => crate::guard::refuse(
1620                "EClasses::merge: class size overflows the index width"),
1621        };
1622        self.reprs.set_live(raw_skey, sdata);
1623        let ghost m1 = *self;
1624        // distinct rings, from W3a: were s and ab on one ring, they would
1625        // share a root, and they are distinct roots.
1626        let ghost cs = self.entries.locate(s.id_nat() as int).0;
1627        let ghost ps = self.entries.locate(s.id_nat() as int).1;
1628        let ghost ca = self.entries.locate(ab.id_nat() as int).0;
1629        let ghost pa = self.entries.locate(ab.id_nat() as int).1;
1630        proof {
1631            let orm = o.entries.model_view();
1632            assert(o.entries.in_some_ring(s.id_nat() as int));
1633            assert(o.entries.in_some_ring(ab.id_nat() as int));
1634            assert(0 <= cs < orm.len() && 0 <= ps < orm[cs].len()
1635                && orm[cs][ps] == s.id_nat() as usize);
1636            assert(0 <= ca < orm.len() && 0 <= pa < orm[ca].len()
1637                && orm[ca][pa] == ab.id_nat() as usize);
1638            if cs == ca {
1639                // same ring -> same root (W3a on the OLD state) -> s == ab.
1640                assert(o.roots_view()[orm[cs][ps] as int]
1641                    == o.roots_view()[orm[cs][pa] as int]);
1642                assert(false);
1643            }
1644        }
1645        let none_pay = Opt::<K>::none();
1646        self.entries.splice_absorb(s, ab, none_pay);
1647        self.reprs.remove(raw_key);
1648        proof {
1649            // assemble the pointwise splice ensures into the update form.
1650            assert(self.entries.model_view() =~= o.entries.model_view()
1651                .update(cs, crate::circular_list::rotate(o.entries.model_view()[cs], ps + 1)
1652                    + crate::circular_list::rotate(o.entries.model_view()[ca], pa + 1))
1653                .update(ca, Seq::<usize>::empty()));
1654            assert(self.reprs.id_set() =~= o.reprs.id_set().remove(key.as_nat()));
1655            // set_live changed only skey's dense slot: distinct live class keys sit
1656            // at distinct dense positions, so every other survivor's value is
1657            // o's, and skey's is `sdata` (o's value with the size folded).
1658            assert forall|k: <T as DenseId>::Index| #[trigger] o.reprs.contains_spec(k)
1659                && k.as_nat() != key.as_nat() && k.as_nat() != skey.as_nat()
1660                implies self.reprs.contains_spec(k)
1661                    && ss_value(self.reprs.dense_view(), self.reprs.sparse_view(),
1662                            k.as_nat())
1663                        == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(),
1664                            k.as_nat()) by {
1665                assert(m1.reprs.contains_spec(k));
1666                assert(o.reprs.sparse_view()[k.as_nat() as int].as_nat()
1667                    != o.reprs.sparse_view()[skey.as_nat() as int].as_nat()) by {
1668                    if o.reprs.sparse_view()[k.as_nat() as int].as_nat()
1669                        == o.reprs.sparse_view()[skey.as_nat() as int].as_nat() {
1670                        assert(o.reprs.indices_view()[o.reprs.sparse_view()
1671                            [k.as_nat() as int].as_nat() as int].as_nat() == k.as_nat());
1672                    }
1673                }
1674                assert(ss_value(m1.reprs.dense_view(), m1.reprs.sparse_view(),
1675                        k.as_nat())
1676                    == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(),
1677                        k.as_nat()));
1678            }
1679            assert(m1.reprs.contains_spec(raw_skey));
1680            assert(ss_contains(m1.reprs.sparse_view(), m1.reprs.indices_view(),
1681                m1.reprs.n_spec(), skey.as_nat()));
1682            assert(ss_value(m1.reprs.dense_view(), m1.reprs.sparse_view(),
1683                skey.as_nat()) == sdata);
1684            assert(self.reprs.contains_spec(raw_skey));
1685            assert(ss_value(self.reprs.dense_view(), self.reprs.sparse_view(),
1686                skey.as_nat()) == sdata);
1687            self.lemma_merge_wf(o, s, ab, key.as_nat(), skey.as_nat(),
1688                none_pay, cs, ps, ca, pa);
1689        }
1690        Some(MergeInfo {
1691            survivor: s,
1692            absorbed: ab,
1693            absorbed_uses: data.use_list,
1694            absorbed_min_row: data.min_row,
1695            absorbed_atomic: data.atomic,
1696        })
1697    }
1698
1699
1700    /// Record that `parent_node` uses class `child_key` as a child, marking
1701    /// the class atomic (production's `add_use`). Refuses a dead key, an
1702    /// out-of-range parent id, or node exhaustion.
1703    ///
1704    /// Prepends. W5 constrains the use-list's contents, not its order, and no
1705    /// consumer reads the order: the rebuild sweep recanonizes each parent
1706    /// independently, and critical-pair partner discovery sorts and dedups what
1707    /// it collects. Prepending touches one memory location (the list head)
1708    /// where appending touches two (the head and the old tail node).
1709    pub fn add_use(&mut self, child_key: K, parent_node: T)
1710        requires old(self).wf(),
1711        ensures
1712            final(self).wf(),
1713            final(self).n_spec() == old(self).n_spec(),
1714            final(self).roots_view() == old(self).roots_view(),
1715            final(self).num_classes_spec() == old(self).num_classes_spec(),
1716    {
1717        if !(parent_node.to_usize() < self.uf.len().as_usize()) {
1718            crate::guard::refuse("EClasses::add_use: parent node id out of range");
1719        }
1720        let raw_key = Self::key_index(child_key);
1721        if !self.reprs.contains(raw_key) {
1722            crate::guard::refuse("EClasses::add_use: class key is not live");
1723        }
1724        let ghost o = *old(self);
1725        let mut data = self.reprs.get_live(raw_key);
1726        proof {
1727            crate::opt::lemma_id_nat_fits_usize(parent_node);
1728            assert(data == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(),
1729                child_key.as_nat()));
1730            assert(ss_contains(o.reprs.sparse_view(), o.reprs.indices_view(),
1731                o.reprs.n_spec(), child_key.as_nat()));
1732            // W4a: the class's list handle is allocated.
1733            assert(data.use_list.id_nat() < o.uses.model_view().len());
1734        }
1735        match self.uses.try_prepend(data.use_list, parent_node) {
1736            Ok(()) => (),
1737            Err(_) => crate::guard::refuse("EClasses::add_use: use-list node range exhausted"),
1738        }
1739        let ghost mid_um = self.uses.model_view();
1740        let ghost mid_un = self.uses.nodes_view();
1741        if !data.atomic {
1742            data.atomic = true;
1743            self.reprs.set_live(raw_key, data);
1744        }
1745        proof {
1746            let n = o.n_spec();
1747            let li = data.use_list.id_nat() as int;
1748            let um = self.uses.model_view();
1749            let un = self.uses.nodes_view();
1750            let oum = o.uses.model_view();
1751            let oun = o.uses.nodes_view();
1752            let dense = self.reprs.dense_view();
1753            let sparse = self.reprs.sparse_view();
1754            let indices = self.reprs.indices_view();
1755            let live = self.reprs.n_spec();
1756            let odense = o.reprs.dense_view();
1757            let osparse = o.reprs.sparse_view();
1758            let oindices = o.reprs.indices_view();
1759
1760            // reprs: at most one value changed, and only its atomic flag.
1761            assert(sparse == osparse && indices == oindices && live == o.reprs.n_spec());
1762            assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
1763                implies ss_contains(osparse, oindices, o.reprs.n_spec(), kk)
1764                    && ss_value(dense, sparse, kk).use_list
1765                        == ss_value(odense, osparse, kk).use_list
1766                    && ss_value(dense, sparse, kk).min_row
1767                        == ss_value(odense, osparse, kk).min_row by {
1768                if kk != child_key.as_nat() {
1769                    // positions are injective on the live region, so a
1770                    // different live class key reads a different dense slot.
1771                    assert(osparse[kk as int].as_nat() != osparse[child_key.as_nat() as int].as_nat()) by {
1772                        if osparse[kk as int].as_nat() == osparse[child_key.as_nat() as int].as_nat() {
1773                            assert(oindices[osparse[kk as int].as_nat() as int].as_nat() == kk);
1774                        }
1775                    }
1776                }
1777            }
1778            assert forall|kk: nat| #[trigger] ss_contains(osparse, oindices, o.reprs.n_spec(), kk)
1779                implies ss_contains(sparse, indices, live, kk) by {}
1780
1781            // uses: list li gained one entry naming parent_node; others same.
1782            o.uses.lemma_nodes_len_fits();
1783            <N as DenseId>::Index::lemma_max_nat_fits_usize();
1784            assert(oun.len() <= usize::MAX as nat);
1785            assert(um == oum.update(li, seq![oun.len() as usize] + oum[li]));
1786            assert(un.len() == oun.len() + 1);
1787            assert(un[oun.len() as int].payload == parent_node);
1788
1789            assert forall|l: int, p: int|
1790                0 <= l < um.len() && 0 <= p < (#[trigger] um[l]).len()
1791                implies un[#[trigger] um[l][p] as int].payload.id_nat() < n by {
1792                if l == li && p == 0 {
1793                    // the fresh node, at the front: it names `parent_node`,
1794                    // whose id the entry guard bounded by `n`.
1795                    assert(um[l][p] == oun.len() as usize);
1796                } else if l == li {
1797                    // an old entry of this list, shifted one right by the prepend.
1798                    assert(um[l][p] == oum[l][p - 1]);
1799                    assert(oum[l][p - 1] < oun.len());
1800                    assert(un[um[l][p] as int].payload == oun[oum[l][p - 1] as int].payload);
1801                } else {
1802                    assert(um[l][p] == oum[l][p]);
1803                    assert(oum[l][p] < oun.len());
1804                    assert(un[um[l][p] as int].payload == oun[oum[l][p] as int].payload);
1805                }
1806            }
1807            assert(eg_model_wf::<T, K, L, N>(
1808                self.entries.model_view(), self.entries.payload_seq(),
1809                self.uf.roots_view(), dense, sparse, indices, um, un,
1810                self.min_pool.view(), self.min_width as nat));
1811        }
1812    }
1813
1814    /// Splice the absorbed class's use-list onto the survivor's after a
1815    /// merge (production's `splice_uses`; the rebuild loop iterates the
1816    /// absorbed list first). Refuses equal handles at runtime inside the
1817    /// arena; W4 ownership is untouched because list ids do not move.
1818    #[verifier::spinoff_prover]
1819    #[verifier::rlimit(120)]
1820    pub fn splice_uses(&mut self, survivor_list: L, absorbed_list: L)
1821        requires old(self).wf(),
1822        ensures
1823            final(self).wf(),
1824            final(self).n_spec() == old(self).n_spec(),
1825            final(self).roots_view() == old(self).roots_view(),
1826            final(self).num_classes_spec() == old(self).num_classes_spec(),
1827    {
1828        let ghost o = *old(self);
1829        self.uses.splice(survivor_list, absorbed_list);
1830        proof {
1831            let n = o.n_spec();
1832            let um = self.uses.model_view();
1833            let un = self.uses.nodes_view();
1834            let oum = o.uses.model_view();
1835            let oun = o.uses.nodes_view();
1836            o.uses.lemma_nodes_len_fits();
1837            <N as DenseId>::Index::lemma_max_nat_fits_usize();
1838            if survivor_list.id_nat() < oum.len() && absorbed_list.id_nat() < oum.len()
1839                && survivor_list.id_nat() != absorbed_list.id_nat()
1840            {
1841                let di = survivor_list.id_nat() as int;
1842                let si = absorbed_list.id_nat() as int;
1843                assert(um == oum.update(di, oum[di] + oum[si]).update(si, Seq::<usize>::empty()));
1844                lemma_splice_uses_w5::<T, N>(oum, um, oun, un, di, si, n);
1845                assert(eg_model_wf::<T, K, L, N>(
1846                    self.entries.model_view(), self.entries.payload_seq(),
1847                    self.uf.roots_view(), self.reprs.dense_view(),
1848                    self.reprs.sparse_view(), self.reprs.indices_view(),
1849                    um, un, self.min_pool.view(), self.min_width as nat));
1850            } else {
1851                // the arena refused (equal or out-of-range handles diverge
1852                // before mutation) or the ensures' conditional guards fired;
1853                // in every returning case the views are unchanged.
1854                assert(um == oum && un == oun);
1855                assert(eg_model_wf::<T, K, L, N>(
1856                    self.entries.model_view(), self.entries.payload_seq(),
1857                    self.uf.roots_view(), self.reprs.dense_view(),
1858                    self.reprs.sparse_view(), self.reprs.indices_view(),
1859                    um, un, self.min_pool.view(), self.min_width as nat));
1860            }
1861        }
1862    }
1863
1864
1865    /// Set the min-monomial pool row width (production's `set_min_width`):
1866    /// once rows exist the width is frozen, and a change request refuses.
1867    pub fn set_min_width(&mut self, width: usize)
1868        requires old(self).wf(),
1869        ensures
1870            final(self).wf(),
1871            final(self).n_spec() == old(self).n_spec(),
1872            final(self).roots_view() == old(self).roots_view(),
1873            final(self).min_width_spec() == width as nat,
1874    {
1875        if self.min_width == width {
1876            return;
1877        }
1878        if !(self.min_pool.len() == 0) {
1879            crate::guard::refuse("EClasses::set_min_width: width is fixed once rows exist");
1880        }
1881        let ghost o = *old(self);
1882        self.min_width = width;
1883        proof {
1884            // the pool is empty, so the geometry clause is 0 % w == 0 and no
1885            // live class can hold a row number (its allocation bound would
1886            // read (r+1)*w <= 0).
1887            let dense = self.reprs.dense_view();
1888            let sparse = self.reprs.sparse_view();
1889            let indices = self.reprs.indices_view();
1890            let live = self.reprs.n_spec();
1891            assert(self.min_pool.view().len() == 0);
1892            assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
1893                && ss_value(dense, sparse, kk).min_row is Some
1894                implies (width as nat) > 0
1895                    && (ss_value(dense, sparse, kk).min_row->Some_0.as_nat() + 1)
1896                        * (width as nat) <= self.min_pool.view().len() by {
1897                // refuted: under the OLD width the same clause bounded the
1898                // row by the pool length, which is 0.
1899                assert((ss_value(dense, sparse, kk).min_row->Some_0.as_nat() + 1)
1900                    * (o.min_width as nat) <= 0);
1901                assert(false) by (nonlinear_arith)
1902                    requires (ss_value(dense, sparse, kk).min_row->Some_0.as_nat() + 1)
1903                        * (o.min_width as nat) <= 0,
1904                        o.min_width as nat > 0;
1905            }
1906            assert((self.min_pool.view().len() as nat) % (width as nat) == 0
1907                || width == 0) by {
1908                if width > 0 {
1909                    assert((0 as nat) % (width as nat) == 0);
1910                }
1911            }
1912            assert(eg_model_wf::<T, K, L, N>(
1913                self.entries.model_view(), self.entries.payload_seq(),
1914                self.uf.roots_view(), dense, sparse, indices,
1915                self.uses.model_view(), self.uses.nodes_view(),
1916                self.min_pool.view(), width as nat));
1917            // the archive under the NEW width: the live pool is empty and
1918            // archived pool lengths are bounded by it, so every archived
1919            // frame's pool is empty, W6 is vacuous at any width, and no
1920            // other clause reads the width.
1921            reveal(eg_archive_agrees);
1922            assert(eg_archive_agrees::<T, K, L, N>(
1923                o.entries.model_snapshots_view(),
1924                o.entries.entries_snapshots_view(),
1925                o.uf.roots_snapshots_view(),
1926                o.reprs.dense_snapshots_view(),
1927                o.reprs.sparse_snapshots_view(),
1928                o.reprs.indices_snapshots_view(),
1929                o.uses.model_snapshots_view(),
1930                o.uses.nodes_snapshots_view(),
1931                o.min_pool.snapshots_view(),
1932                o.min_width as nat));
1933            assert forall|k: int| 0 <= k < self.entries.model_snapshots_view().len()
1934                implies eg_model_wf::<T, K, L, N>(
1935                    #[trigger] self.entries.model_snapshots_view()[k],
1936                    ring_payloads(self.entries.entries_snapshots_view()[k]),
1937                    self.uf.roots_snapshots_view()[k],
1938                    self.reprs.dense_snapshots_view()[k],
1939                    self.reprs.sparse_snapshots_view()[k],
1940                    self.reprs.indices_snapshots_view()[k],
1941                    self.uses.model_snapshots_view()[k],
1942                    self.uses.nodes_snapshots_view()[k],
1943                    self.min_pool.snapshots_view()[k],
1944                    width as nat) by {
1945                let pool_k = self.min_pool.snapshots_view()[k];
1946                assert(pool_k.len() <= self.min_pool.view().len());
1947                assert(pool_k.len() == 0);
1948                let sp_k = self.reprs.sparse_snapshots_view()[k];
1949                let ix_k = self.reprs.indices_snapshots_view()[k];
1950                let de_k = self.reprs.dense_snapshots_view()[k];
1951                // old-width frame invariant
1952                assert(eg_model_wf::<T, K, L, N>(
1953                    self.entries.model_snapshots_view()[k],
1954                    ring_payloads(self.entries.entries_snapshots_view()[k]),
1955                    self.uf.roots_snapshots_view()[k],
1956                    de_k, sp_k, ix_k,
1957                    self.uses.model_snapshots_view()[k],
1958                    self.uses.nodes_snapshots_view()[k],
1959                    pool_k, o.min_width as nat));
1960                // no archived live class key can hold a row: the old-width W6
1961                // bound reads (r+1)*old_w <= 0 with old_w > 0, or forces
1962                // old_w > 0 when a row exists.
1963                assert forall|id: nat| #[trigger] ss_contains(sp_k, ix_k, de_k.len(), id)
1964                    && ss_value(de_k, sp_k, id).min_row is Some
1965                    implies false by {
1966                    let r0 = ss_value(de_k, sp_k, id).min_row->Some_0.as_nat();
1967                    assert((o.min_width as nat) > 0
1968                        && (r0 + 1) * (o.min_width as nat) <= pool_k.len());
1969                    assert((r0 + 1) * (o.min_width as nat) > 0) by (nonlinear_arith)
1970                        requires (o.min_width as nat) > 0;
1971                }
1972                if width > 0 {
1973                    assert((pool_k.len() as nat) % (width as nat) == 0);
1974                }
1975            }
1976            assert(eg_archive_agrees::<T, K, L, N>(
1977                self.entries.model_snapshots_view(),
1978                self.entries.entries_snapshots_view(),
1979                self.uf.roots_snapshots_view(),
1980                self.reprs.dense_snapshots_view(),
1981                self.reprs.sparse_snapshots_view(),
1982                self.reprs.indices_snapshots_view(),
1983                self.uses.model_snapshots_view(),
1984                self.uses.nodes_snapshots_view(),
1985                self.min_pool.snapshots_view(),
1986                width as nat));
1987        }
1988    }
1989
1990    pub fn min_width(&self) -> (w: usize)
1991        requires self.wf(),
1992        ensures w as nat == self.min_width_spec(),
1993    {
1994        self.min_width
1995    }
1996
1997    /// Read class `key`'s min-monomial for completion column `col`
1998    /// (`None` when the class has no row or the cell is empty). Refuses a
1999    /// dead key or an out-of-range column.
2000    pub fn min_monomial(&self, key: K, col: usize) -> (r: Option<T>)
2001        requires self.wf(),
2002    {
2003        if !(col < self.min_width) {
2004            crate::guard::refuse("EClasses::min_monomial: completion column out of range");
2005        }
2006        let raw_key = Self::key_index(key);
2007        if !self.reprs.contains(raw_key) {
2008            crate::guard::refuse("EClasses::min_monomial: class key is not live");
2009        }
2010        let data = self.reprs.get_live(raw_key);
2011        match data.min_row {
2012            None => None,
2013            Some(row) => {
2014                proof {
2015                    // W6: the row is allocated, so base + col is in the pool.
2016                    assert(ss_contains(self.reprs.sparse_view(), self.reprs.indices_view(),
2017                        self.reprs.n_spec(), key.as_nat()));
2018                    assert((row.as_nat() + 1) * (self.min_width as nat)
2019                        <= self.min_pool.view().len());
2020                    assert(row.as_nat() * (self.min_width as nat) + (self.min_width as nat)
2021                        == (row.as_nat() + 1) * (self.min_width as nat)) by (nonlinear_arith);
2022                    <T::Index as IndexLike>::lemma_max_nat_fits_usize();
2023                }
2024                let base = row.as_usize() * self.min_width;
2025                let cell = self.min_pool.get_index(base + col);
2026                proof {
2027                    assert(cell == self.min_pool.view()[(base + col) as int]);
2028                    assert(cell.wf());
2029                }
2030                cell.to_option()
2031            }
2032        }
2033    }
2034
2035    /// Write class `key`'s min-monomial for column `col`, allocating the
2036    /// class's pool row on first use (production's `ensure_min_row` +
2037    /// `set_min_monomial`). Refuses a dead key, an out-of-range column, a
2038    /// zero width, or pool exhaustion.
2039    #[verifier::spinoff_prover]
2040    #[verifier::rlimit(120)]
2041    pub fn set_min_monomial(&mut self, key: K, col: usize, node: T)
2042        requires old(self).wf(),
2043        ensures
2044            final(self).wf(),
2045            final(self).n_spec() == old(self).n_spec(),
2046            final(self).roots_view() == old(self).roots_view(),
2047            final(self).num_classes_spec() == old(self).num_classes_spec(),
2048            final(self).min_width_spec() == old(self).min_width_spec(),
2049    {
2050        if !(self.min_width > 0 && col < self.min_width) {
2051            crate::guard::refuse("EClasses::set_min_monomial: completion column out of range");
2052        }
2053        let raw_key = Self::key_index(key);
2054        if !self.reprs.contains(raw_key) {
2055            crate::guard::refuse("EClasses::set_min_monomial: class key is not live");
2056        }
2057        let ghost o = *old(self);
2058        let ghost w = o.min_width as nat;
2059        let mut data = self.reprs.get_live(raw_key);
2060        proof {
2061            assert(ss_contains(o.reprs.sparse_view(), o.reprs.indices_view(),
2062                o.reprs.n_spec(), key.as_nat()));
2063            assert(data == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(),
2064                key.as_nat()));
2065        }
2066        let row = match data.min_row {
2067            Some(row) => {
2068                proof {
2069                    // W6 in the old state bounds the existing row; the pool
2070                    // is untouched on this arm.
2071                    assert((row.as_nat() + 1) * w <= self.min_pool.view().len());
2072                    assert(forall|i: int| 0 <= i < self.min_pool.view().len()
2073                        ==> (#[trigger] self.min_pool.view()[i]).wf());
2074                }
2075                row
2076            }
2077            None => {
2078                // allocate a fresh all-empty row at the pool's end.
2079                let len0 = self.min_pool.len();
2080                proof {
2081                    assert(len0 as nat % w == 0);
2082                    assert(len0 as nat == self.min_pool.view().len());
2083                }
2084                let row_num = len0 / self.min_width;
2085                proof {
2086                    vstd::arithmetic::div_mod::lemma_fundamental_div_mod(
2087                        len0 as int, o.min_width as int);
2088                    assert(len0 as int == (o.min_width as int) * (row_num as int));
2089                }
2090                let row = match <T::Index as IndexLike>::try_from_usize(row_num) {
2091                    Some(r) => r,
2092                    None => crate::guard::refuse(
2093                        "EClasses::set_min_monomial: row number exceeds the id index range"),
2094                };
2095                let mut i: usize = 0;
2096                while i < self.min_width
2097                    invariant
2098                        o.wf(),
2099                        self.min_width == o.min_width,
2100                        self.min_width > 0,
2101                        i <= self.min_width,
2102                        self.entries == o.entries,
2103                        self.reprs == o.reprs,
2104                        self.uf == o.uf,
2105                        self.uses == o.uses,
2106                        self.min_pool.wf(),
2107                        self.min_pool.view().len() == o.min_pool.view().len() + i as nat,
2108                        self.min_pool.snapshots_view() == o.min_pool.snapshots_view(),
2109                        forall|j: int| 0 <= j < self.min_pool.view().len()
2110                            ==> (#[trigger] self.min_pool.view()[j]).wf(),
2111                    decreases self.min_width - i,
2112                {
2113                    match self.min_pool.try_push(Opt::none()) {
2114                        Ok(()) => (),
2115                        Err(_) => crate::guard::refuse(
2116                            "EClasses::set_min_monomial: min-monomial pool exhausted"),
2117                    }
2118                    i = i + 1;
2119                }
2120                data.min_row = Some(row);
2121                self.reprs.set_live(raw_key, data);
2122                proof {
2123                    let len1 = self.min_pool.view().len();
2124                    let dense = self.reprs.dense_view();
2125                    let sparse = self.reprs.sparse_view();
2126                    let indices = self.reprs.indices_view();
2127                    let live = self.reprs.n_spec();
2128                    let odense = o.reprs.dense_view();
2129                    let osparse = o.reprs.sparse_view();
2130                    let oindices = o.reprs.indices_view();
2131                    assert(len1 == o.min_pool.view().len() + w);
2132                    assert(row.as_nat() == row_num as nat);
2133                    // the new row is exactly the grown tail.
2134                    assert((row.as_nat() + 1) * w == len1) by (nonlinear_arith)
2135                        requires
2136                            o.min_pool.view().len() as int
2137                                == (w as int) * (row.as_nat() as int),
2138                            len1 == o.min_pool.view().len() + w;
2139                    // geometry: len1 == w * (row + 1), a whole number of rows.
2140                    assert(len1 as int == (w as int) * ((row.as_nat() + 1) as int))
2141                        by (nonlinear_arith)
2142                        requires
2143                            o.min_pool.view().len() as int
2144                                == (w as int) * (row.as_nat() as int),
2145                            len1 == o.min_pool.view().len() + w;
2146                    vstd::arithmetic::div_mod::lemma_mod_multiples_basic(
2147                        (row.as_nat() + 1) as int, w as int);
2148                    assert(len1 % w == 0);
2149                    // reprs: only key's value changed, and only its min_row.
2150                    assert(sparse == osparse && indices == oindices
2151                        && live == o.reprs.n_spec());
2152                    assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
2153                        && kk != key.as_nat()
2154                        implies ss_value(dense, sparse, kk)
2155                            == ss_value(odense, osparse, kk) by {
2156                        assert(osparse[kk as int].as_nat()
2157                            != osparse[key.as_nat() as int].as_nat()) by {
2158                            if osparse[kk as int].as_nat()
2159                                == osparse[key.as_nat() as int].as_nat() {
2160                                assert(oindices[osparse[kk as int].as_nat() as int]
2161                                    .as_nat() == kk);
2162                            }
2163                        }
2164                    }
2165                    // every OLD row is strictly below the new one.
2166                    assert forall|kk: nat| #[trigger] ss_contains(osparse, oindices,
2167                            o.reprs.n_spec(), kk)
2168                        && ss_value(odense, osparse, kk).min_row is Some
2169                        implies ss_value(odense, osparse, kk).min_row->Some_0.as_nat()
2170                            < row.as_nat() by {
2171                        let r0 = ss_value(odense, osparse, kk).min_row->Some_0.as_nat();
2172                        assert((r0 + 1) * w <= o.min_pool.view().len());
2173                        assert(r0 < row.as_nat()) by (nonlinear_arith)
2174                            requires
2175                                (r0 + 1) * w <= o.min_pool.view().len(),
2176                                o.min_pool.view().len() as int
2177                                    == (w as int) * (row.as_nat() as int),
2178                                w > 0;
2179                    }
2180                    assert(forall|i: int| 0 <= i < self.min_pool.view().len()
2181                        ==> (#[trigger] self.min_pool.view()[i]).wf());
2182                }
2183                row
2184            }
2185        };
2186        let ghost mid = *self;
2187        proof {
2188            // both arms deliver: the class's row is allocated in the current
2189            // pool, and eg_model_wf holds for the mid state.
2190            assert((row.as_nat() + 1) * w <= self.min_pool.view().len());
2191            assert(row.as_nat() * w + w == (row.as_nat() + 1) * w) by (nonlinear_arith);
2192            <T::Index as IndexLike>::lemma_max_nat_fits_usize();
2193            self.lemma_mid_pool_wf(o, key, row);
2194        }
2195        let base = row.as_usize() * self.min_width;
2196        let cell = Opt::some(node);
2197        self.min_pool.set_index(base + col, cell);
2198        proof {
2199            assert(self.min_pool.view().len() == mid.min_pool.view().len());
2200            assert(eg_model_wf::<T, K, L, N>(
2201                self.entries.model_view(), self.entries.payload_seq(),
2202                self.uf.roots_view(), self.reprs.dense_view(),
2203                self.reprs.sparse_view(), self.reprs.indices_view(),
2204                self.uses.model_view(), self.uses.nodes_view(),
2205                self.min_pool.view(), self.min_width as nat));
2206            // the pool only grew, so the archived-length bound carries.
2207            assert(self.min_pool.snapshots_view() == o.min_pool.snapshots_view());
2208            assert(o.min_pool.view().len() <= self.min_pool.view().len());
2209            assert forall|k: int| 0 <= k < self.min_pool.snapshots_view().len()
2210                implies (#[trigger] self.min_pool.snapshots_view()[k]).len()
2211                    <= self.min_pool.view().len() by {
2212                assert(self.min_pool.snapshots_view()[k].len()
2213                    <= o.min_pool.view().len());
2214            }
2215        }
2216    }
2217
2218    /// The mid-state invariant of `set_min_monomial`, per arm: with the row
2219    /// already allocated (either from the old state or freshly grown), the
2220    /// full joint invariant holds. Extracted so the two arms discharge one
2221    /// obligation each instead of the final assert re-deriving both.
2222    proof fn lemma_mid_pool_wf(&self, o: Self, key: K,
2223        row: <T as DenseId>::Index)
2224        requires
2225            o.wf(),
2226            self.entries == o.entries,
2227            self.uf == o.uf,
2228            self.uses == o.uses,
2229            self.min_width == o.min_width,
2230            (o.min_width as nat) > 0,
2231            self.reprs.wf(),
2232            self.min_pool.wf(),
2233            self.reprs.n_spec() == o.reprs.n_spec(),
2234            self.reprs.cap_spec() == o.reprs.cap_spec(),
2235            self.reprs.sparse_view() == o.reprs.sparse_view(),
2236            self.reprs.indices_view() == o.reprs.indices_view(),
2237            ss_contains(o.reprs.sparse_view(), o.reprs.indices_view(),
2238                o.reprs.n_spec(), key.as_nat()),
2239            // the only possible dense change is key's min_row becoming
2240            // Some(row); everything else of the value survives.
2241            ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), key.as_nat())
2242                .use_list
2243                == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), key.as_nat())
2244                    .use_list,
2245            ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), key.as_nat())
2246                .size
2247                == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), key.as_nat())
2248                    .size,
2249            ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), key.as_nat())
2250                .min_row is Some,
2251            ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), key.as_nat())
2252                .min_row->Some_0 == row,
2253            forall|kk: nat| #[trigger] ss_contains(o.reprs.sparse_view(),
2254                    o.reprs.indices_view(), o.reprs.n_spec(), kk)
2255                && kk != key.as_nat()
2256                ==> ss_value(self.reprs.dense_view(), self.reprs.sparse_view(), kk)
2257                    == ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), kk),
2258            (row.as_nat() + 1) * (o.min_width as nat) <= self.min_pool.view().len(),
2259            self.min_pool.view().len() % (o.min_width as nat) == 0,
2260            forall|i: int| 0 <= i < self.min_pool.view().len()
2261                ==> (#[trigger] self.min_pool.view()[i]).wf(),
2262            // strict dominance: every other live row is below `row` OR the
2263            // pool did not grow and rows are the old ones (covered by the
2264            // dominance hypothesis at the call sites).
2265            forall|kk: nat| #[trigger] ss_contains(o.reprs.sparse_view(),
2266                    o.reprs.indices_view(), o.reprs.n_spec(), kk)
2267                && kk != key.as_nat()
2268                && ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), kk)
2269                    .min_row is Some
2270                ==> ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), kk)
2271                        .min_row->Some_0.as_nat() != row.as_nat()
2272                    && (ss_value(o.reprs.dense_view(), o.reprs.sparse_view(), kk)
2273                        .min_row->Some_0.as_nat() + 1) * (o.min_width as nat)
2274                        <= self.min_pool.view().len(),
2275        ensures
2276            eg_model_wf::<T, K, L, N>(
2277                self.entries.model_view(), self.entries.payload_seq(),
2278                self.uf.roots_view(), self.reprs.dense_view(),
2279                self.reprs.sparse_view(), self.reprs.indices_view(),
2280                self.uses.model_view(), self.uses.nodes_view(),
2281                self.min_pool.view(), self.min_width as nat),
2282    {
2283        let dense = self.reprs.dense_view();
2284        let sparse = self.reprs.sparse_view();
2285        let indices = self.reprs.indices_view();
2286        let live = self.reprs.n_spec();
2287        let odense = o.reprs.dense_view();
2288        let osparse = o.reprs.sparse_view();
2289        let oindices = o.reprs.indices_view();
2290        // W2b-d and W4 quantify over values whose use_list/liveness are
2291        // untouched; W6 is the hypothesis set.
2292        assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
2293            implies ss_value(dense, sparse, kk).use_list
2294                    == ss_value(odense, osparse, kk).use_list
2295                && ss_value(dense, sparse, kk).size
2296                    == ss_value(odense, osparse, kk).size by {
2297            if kk != key.as_nat() {
2298                assert(ss_value(dense, sparse, kk) == ss_value(odense, osparse, kk));
2299            }
2300        }
2301        assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
2302            && kk != key.as_nat()
2303            implies ss_value(dense, sparse, kk) == ss_value(odense, osparse, kk) by {}
2304        assert(eg_model_wf::<T, K, L, N>(
2305            self.entries.model_view(), self.entries.payload_seq(),
2306            self.uf.roots_view(), dense, sparse, indices,
2307            self.uses.model_view(), self.uses.nodes_view(),
2308            self.min_pool.view(), self.min_width as nat));
2309    }
2310
2311    /// Whether class `key` is atomic (referenced as a child). Refuses a
2312    /// dead key.
2313    pub fn atomic(&self, key: K) -> (b: bool)
2314        requires self.wf(),
2315    {
2316        let raw_key = Self::key_index(key);
2317        if !self.reprs.contains(raw_key) {
2318            crate::guard::refuse("EClasses::atomic: class key is not live");
2319        }
2320        self.reprs.get_live(raw_key).atomic
2321    }
2322
2323    /// The use-list id of class `key`. Refuses a dead key.
2324    pub fn use_list_id(&self, key: K) -> (l: L)
2325        requires self.wf(),
2326        ensures self.contains_key_spec(key)
2327            ==> l == self.class_data_spec(key.as_nat()).use_list,
2328    {
2329        let raw_key = Self::key_index(key);
2330        if !self.reprs.contains(raw_key) {
2331            crate::guard::refuse("EClasses::use_list_id: class key is not live");
2332        }
2333        self.reprs.get_live(raw_key).use_list
2334    }
2335
2336
2337    /// Mark class `key` atomic (production's `set_atomic`; `EGraph` calls it
2338    /// when a class gains a non-completion node). Refuses a dead key.
2339    pub fn set_atomic(&mut self, key: K)
2340        requires old(self).wf(),
2341        ensures
2342            final(self).wf(),
2343            final(self).n_spec() == old(self).n_spec(),
2344            final(self).roots_view() == old(self).roots_view(),
2345            final(self).num_classes_spec() == old(self).num_classes_spec(),
2346    {
2347        let raw_key = Self::key_index(key);
2348        if !self.reprs.contains(raw_key) {
2349            crate::guard::refuse("EClasses::set_atomic: class key is not live");
2350        }
2351        let ghost o = *old(self);
2352        let mut data = self.reprs.get_live(raw_key);
2353        if data.atomic {
2354            return;
2355        }
2356        data.atomic = true;
2357        self.reprs.set_live(raw_key, data);
2358        proof {
2359            let dense = self.reprs.dense_view();
2360            let sparse = self.reprs.sparse_view();
2361            let indices = self.reprs.indices_view();
2362            let live = self.reprs.n_spec();
2363            let odense = o.reprs.dense_view();
2364            let osparse = o.reprs.sparse_view();
2365            let oindices = o.reprs.indices_view();
2366            assert(sparse == osparse && indices == oindices && live == o.reprs.n_spec());
2367            assert forall|kk: nat| #[trigger] ss_contains(sparse, indices, live, kk)
2368                implies ss_value(dense, sparse, kk).use_list
2369                        == ss_value(odense, osparse, kk).use_list
2370                    && ss_value(dense, sparse, kk).min_row
2371                        == ss_value(odense, osparse, kk).min_row by {
2372                if kk != key.as_nat() {
2373                    assert(osparse[kk as int].as_nat()
2374                        != osparse[key.as_nat() as int].as_nat()) by {
2375                        if osparse[kk as int].as_nat()
2376                            == osparse[key.as_nat() as int].as_nat() {
2377                            assert(oindices[osparse[kk as int].as_nat() as int]
2378                                .as_nat() == kk);
2379                        }
2380                    }
2381                    assert(ss_value(dense, sparse, kk) == ss_value(odense, osparse, kk));
2382                }
2383            }
2384            assert(eg_model_wf::<T, K, L, N>(
2385                self.entries.model_view(), self.entries.payload_seq(),
2386                self.uf.roots_view(), dense, sparse, indices,
2387                self.uses.model_view(), self.uses.nodes_view(),
2388                self.min_pool.view(), self.min_width as nat));
2389        }
2390    }
2391
2392    /// Iterate `start`'s class ring (the verified `RingIter`: exactly the
2393    /// ring's nodes, each once, in successor order).
2394    pub fn iter_class(&self, start: T)
2395        -> (it: crate::circular_list::RingIter<'_, Opt<K>, T, TRACK>)
2396        requires self.wf(),
2397        ensures start.id_nat() < self.n_spec() ==> ({
2398            &&& it.list_ref() == self.entries_ref()
2399            &&& it.start_spec() == start.id_nat()
2400            &&& it.pos_spec() == 0
2401            &&& !it.done_spec()
2402            &&& it.cursor_ok()
2403            &&& it.walk_seq() == self.class_seq(start.id_nat() as int)
2404        }),
2405    {
2406        self.entries.iter_class(start)
2407    }
2408
2409    /// Iterate class `key`'s use-list (the verified `ListIter`). Refuses a
2410    /// dead key.
2411    pub fn iter_uses(&self, key: K)
2412        -> (it: crate::list::ListIter<'_, T, L, N, TRACK>)
2413        requires self.wf(),
2414        ensures self.contains_key_spec(key) ==> ({
2415            &&& it.arena_ref() == self.uses_ref()
2416            &&& it.list_spec() == self.class_data_spec(key.as_nat()).use_list.id_nat()
2417            &&& it.pos_spec() == 0
2418            &&& it.cursor_ok()
2419        }),
2420    {
2421        let raw_key = Self::key_index(key);
2422        if !self.reprs.contains(raw_key) {
2423            crate::guard::refuse("EClasses::iter_uses: class key is not live");
2424        }
2425        let l = self.reprs.get_live(raw_key).use_list;
2426        proof {
2427            assert(ss_contains(self.reprs.sparse_view(), self.reprs.indices_view(),
2428                self.reprs.n_spec(), key.as_nat()));
2429            assert(l.id_nat() < self.uses.model_view().len());
2430        }
2431        self.uses.iter(l)
2432    }
2433
2434
2435    /// O(1) length of class `key`'s use-list, widened to `usize` at the
2436    /// boundary (production's `use_list_len`). Refuses a dead key.
2437    pub fn use_list_len(&self, key: K) -> (n: usize)
2438        requires self.wf(),
2439    {
2440        let raw_key = Self::key_index(key);
2441        if !self.reprs.contains(raw_key) {
2442            crate::guard::refuse("EClasses::use_list_len: class key is not live");
2443        }
2444        let l = self.reprs.get_live(raw_key).use_list;
2445        proof {
2446            assert(ss_contains(self.reprs.sparse_view(), self.reprs.indices_view(),
2447                self.reprs.n_spec(), key.as_nat()));
2448            assert(l.id_nat() < self.uses.model_view().len());
2449        }
2450        self.uses.len(l).as_usize()
2451    }
2452
2453    /// O(1) member-node count of class `key`, widened to `usize` at the
2454    /// boundary like `use_list_len` (the stored counter is `T::Index`-wide,
2455    /// so the width follows the configuration). Refuses a dead key. Feeds the
2456    /// `--union-by size`/`sum` survivor policy.
2457    pub fn class_size(&self, key: K) -> (n: usize)
2458        requires self.wf(),
2459    {
2460        let raw_key = Self::key_index(key);
2461        if !self.reprs.contains(raw_key) {
2462            crate::guard::refuse("EClasses::class_size: class key is not live");
2463        }
2464        self.reprs.get_live(raw_key).size.as_usize()
2465    }
2466
2467    /// Read completion column `col` of a pool row number carried in
2468    /// `MergeInfo` (production's `min_monomial_at_row`): `None` when the row
2469    /// is absent or the cell is empty. Refuses an out-of-range column or an
2470    /// unallocated row number.
2471    pub fn min_monomial_at_row(&self, row: Option<<T as DenseId>::Index>, col: usize)
2472        -> (r: Option<T>)
2473        requires self.wf(),
2474    {
2475        if !(col < self.min_width) {
2476            crate::guard::refuse("EClasses::min_monomial_at_row: completion column out of range");
2477        }
2478        let row = match row {
2479            None => {
2480                return None;
2481            }
2482            Some(row) => row,
2483        };
2484        proof { <T::Index as IndexLike>::lemma_max_nat_fits_usize(); }
2485        let base = match crate::index_like::checked_mul(row.as_usize(), self.min_width) {
2486            Some(b) => b,
2487            None => crate::guard::refuse(
2488                "EClasses::min_monomial_at_row: row offset overflows"),
2489        };
2490        let len = self.min_pool.len();
2491        if !(base < len && col < len - base) {
2492            crate::guard::refuse("EClasses::min_monomial_at_row: row is not allocated");
2493        }
2494        let cell = self.min_pool.get_index(base + col);
2495        proof {
2496            assert(cell == self.min_pool.view()[(base + col) as int]);
2497            assert(cell.wf());
2498        }
2499        cell.to_option()
2500    }
2501
2502    /// Direct read access to the use-list arena (production's `uses`; the
2503    /// rebuild loop iterates an absorbed list by id).
2504    pub fn uses(&self) -> (a: &ListArena<T, L, N, TRACK>)
2505        requires self.wf(),
2506        ensures a == self.uses_ref(), a.wf(),
2507    {
2508        &self.uses
2509    }
2510
2511    /// Union-by-rank merge. Only available when `PROOFS = false`
2512    /// (production's contract, with its message); `merge_justified` is the
2513    /// proofs form.
2514    pub fn merge(&mut self, a: T, b: T) -> (r: Option<MergeInfo<T, L>>)
2515        requires old(self).wf(),
2516        ensures
2517            final(self).wf(),
2518            final(self).n_spec() == old(self).n_spec(),
2519            final(self).min_width_spec() == old(self).min_width_spec(),
2520            a.id_nat() < old(self).n_spec() && b.id_nat() < old(self).n_spec() ==> {
2521                let ra = old(self).roots_view()[a.id_nat() as int] as nat;
2522                let rb = old(self).roots_view()[b.id_nat() as int] as nat;
2523                &&& (r is None <==> ra == rb)
2524                &&& (r is None ==> final(self).roots_view() == old(self).roots_view())
2525                &&& (r matches Some(mi) ==> {
2526                        &&& ((mi.survivor.id_nat() == ra && mi.absorbed.id_nat() == rb)
2527                            || (mi.survivor.id_nat() == rb && mi.absorbed.id_nat() == ra))
2528                        &&& ra != rb
2529                        &&& final(self).roots_view() == crate::union_find::merge_roots(
2530                                old(self).roots_view(), mi.survivor.id_nat(),
2531                                mi.absorbed.id_nat())
2532                        &&& final(self).num_classes_spec()
2533                            == old(self).num_classes_spec() - 1
2534                    })
2535            },
2536    {
2537        if PROOFS {
2538            crate::guard::refuse(
2539                "union() called on a PROOFS=true UnionFind; use union_justified() instead");
2540        }
2541        self.merge_with(a, b, false, false)
2542    }
2543
2544    /// Whether `find(a)`'s class has at least as many parents as `find(b)`'s
2545    /// (production's survivor policy for directed merges).
2546    fn prefer_a_by_uses(&self, a: T, b: T) -> (r: bool)
2547        requires self.wf(),
2548    {
2549        if !(a.to_usize() < self.uf.len().as_usize()
2550            && b.to_usize() < self.uf.len().as_usize())
2551        {
2552            crate::guard::refuse("EClasses::merge_directed: node id out of range");
2553        }
2554        let ra = self.uf.find_const(a);
2555        let rb = self.uf.find_const(b);
2556        let la = match self.repr_id(ra) {
2557            Some(k) => self.use_list_len(k),
2558            None => 0,
2559        };
2560        let lb = match self.repr_id(rb) {
2561            Some(k) => self.use_list_len(k),
2562            None => 0,
2563        };
2564        la >= lb
2565    }
2566
2567    /// Like [`Self::merge`], but keeps the larger-use-list class as
2568    /// survivor (production's two-argument `merge_directed`). Only
2569    /// available when `PROOFS = false`.
2570    pub fn merge_directed(&mut self, a: T, b: T) -> (r: Option<MergeInfo<T, L>>)
2571        requires old(self).wf(),
2572        ensures
2573            final(self).wf(),
2574            final(self).n_spec() == old(self).n_spec(),
2575            a.id_nat() < old(self).n_spec() && b.id_nat() < old(self).n_spec() ==> {
2576                let ra = old(self).roots_view()[a.id_nat() as int] as nat;
2577                let rb = old(self).roots_view()[b.id_nat() as int] as nat;
2578                &&& (r is None <==> ra == rb)
2579                &&& (r matches Some(mi) ==> {
2580                        &&& ((mi.survivor.id_nat() == ra && mi.absorbed.id_nat() == rb)
2581                            || (mi.survivor.id_nat() == rb && mi.absorbed.id_nat() == ra))
2582                        &&& final(self).roots_view() == crate::union_find::merge_roots(
2583                                old(self).roots_view(), mi.survivor.id_nat(),
2584                                mi.absorbed.id_nat())
2585                    })
2586            },
2587    {
2588        if PROOFS {
2589            crate::guard::refuse(
2590                "union_directed() called on a PROOFS=true UnionFind; use union_justified_directed()");
2591        }
2592        let prefer_a = self.prefer_a_by_uses(a, b);
2593        self.merge_with(a, b, true, prefer_a)
2594    }
2595
2596    /// The directed core with an explicit survivor flag (`merge_with`'s
2597    /// public face for callers that computed their own policy; the
2598    /// conformance differential uses it).
2599    pub fn merge_directed_with(&mut self, a: T, b: T, prefer_a: bool)
2600        -> (r: Option<MergeInfo<T, L>>)
2601        requires old(self).wf(),
2602        ensures
2603            final(self).wf(),
2604            final(self).n_spec() == old(self).n_spec(),
2605            a.id_nat() < old(self).n_spec() && b.id_nat() < old(self).n_spec() ==> {
2606                let ra = old(self).roots_view()[a.id_nat() as int] as nat;
2607                let rb = old(self).roots_view()[b.id_nat() as int] as nat;
2608                &&& (r is None <==> ra == rb)
2609                &&& (r matches Some(mi) ==> {
2610                        &&& mi.survivor.id_nat() == (if prefer_a { ra } else { rb })
2611                        &&& mi.absorbed.id_nat() == (if prefer_a { rb } else { ra })
2612                        &&& final(self).roots_view() == crate::union_find::merge_roots(
2613                                old(self).roots_view(), mi.survivor.id_nat(),
2614                                mi.absorbed.id_nat())
2615                    })
2616            },
2617    {
2618        self.merge_with(a, b, true, prefer_a)
2619    }
2620}
2621
2622// ---------------------------------------------------------------------------
2623// Semi-persistence: compose from the five components
2624// ---------------------------------------------------------------------------
2625
2626/// Token bundling the five component tokens.
2627#[derive(Copy, Clone)]
2628pub struct EClassesToken {
2629    pub(crate) entries: CircularListToken,
2630    pub(crate) reprs: SparseSetToken,
2631    pub(crate) uf: UnionFindToken,
2632    pub(crate) uses: ListArenaToken,
2633    pub(crate) pool: VecToken,
2634}
2635
2636impl EClassesToken {
2637    pub open(crate) spec fn frame_idx_spec(self) -> nat {
2638        self.pool.frame_idx as nat
2639    }
2640}
2641
2642impl<T, K, L, N, J, const TRACK: bool, const PROOFS: bool>
2643    EClasses<T, K, L, N, J, TRACK, PROOFS>
2644where
2645    T: DenseId,
2646    K: DenseId<Index = T::Index>,
2647    L: DenseId,
2648    N: DenseId + Tagged + core::default::Default,
2649    J: Tagged + Copy + core::default::Default,
2650{
2651    /// Mark the aggregate: one frame on every component, atomically from the
2652    /// caller's view (a component that cannot mark refuses before the next
2653    /// one is touched, production's panic-on-depth-exhaustion semantics).
2654    pub fn mark(&mut self, shrink: ShrinkPolicy) -> (token: EClassesToken)
2655        requires old(self).wf(),
2656        ensures
2657            final(self).wf(),
2658            final(self).n_spec() == old(self).n_spec(),
2659            final(self).roots_view() == old(self).roots_view(),
2660            final(self).num_classes_spec() == old(self).num_classes_spec(),
2661            final(self).min_width_spec() == old(self).min_width_spec(),
2662            token.frame_idx_spec() == final(self).depth_spec() - 1,
2663            final(self).depth_spec() == old(self).depth_spec() + 1,
2664    {
2665        if !TRACK {
2666            crate::guard::refuse("EClasses::mark: untracked aggregate");
2667        }
2668        let ghost o = *old(self);
2669        let t_entries = match self.entries.try_mark(shrink) {
2670            Ok(t) => t,
2671            Err(_) => crate::guard::refuse("EClasses::mark: ring mark refused"),
2672        };
2673        let t_reprs = match self.reprs.try_mark(shrink) {
2674            Ok(t) => t,
2675            Err(_) => crate::guard::refuse("EClasses::mark: repr-set mark refused"),
2676        };
2677        let t_uf = match self.uf.try_mark(shrink) {
2678            Ok(t) => t,
2679            Err(_) => crate::guard::refuse("EClasses::mark: union-find mark refused"),
2680        };
2681        let t_uses = match self.uses.try_mark(shrink) {
2682            Ok(t) => t,
2683            Err(_) => crate::guard::refuse("EClasses::mark: use-list mark refused"),
2684        };
2685        let t_pool = match self.min_pool.try_mark(shrink) {
2686            Ok(t) => t,
2687            Err(_) => crate::guard::refuse("EClasses::mark: pool mark refused"),
2688        };
2689        proof {
2690            reveal(eg_archive_agrees);
2691            assert(eg_archive_agrees::<T, K, L, N>(
2692                o.entries.model_snapshots_view(),
2693                o.entries.entries_snapshots_view(),
2694                o.uf.roots_snapshots_view(),
2695                o.reprs.dense_snapshots_view(),
2696                o.reprs.sparse_snapshots_view(),
2697                o.reprs.indices_snapshots_view(),
2698                o.uses.model_snapshots_view(),
2699                o.uses.nodes_snapshots_view(),
2700                o.min_pool.snapshots_view(),
2701                o.min_width as nat));
2702            let k_new = self.entries.model_snapshots_view().len() - 1;
2703            // the pushed frame archives the live views; the live joint
2704            // invariant IS eg_model_wf over them. The payload projection of
2705            // the pushed cell snapshot is the live payload_seq.
2706            assert(ring_payloads(self.entries.entries_snapshots_view()[k_new])
2707                =~= o.entries.payload_seq());
2708            assert(eg_model_wf::<T, K, L, N>(
2709                self.entries.model_snapshots_view()[k_new],
2710                ring_payloads(self.entries.entries_snapshots_view()[k_new]),
2711                self.uf.roots_snapshots_view()[k_new],
2712                self.reprs.dense_snapshots_view()[k_new],
2713                self.reprs.sparse_snapshots_view()[k_new],
2714                self.reprs.indices_snapshots_view()[k_new],
2715                self.uses.model_snapshots_view()[k_new],
2716                self.uses.nodes_snapshots_view()[k_new],
2717                self.min_pool.snapshots_view()[k_new],
2718                self.min_width as nat));
2719            assert(crate::sparse_set::sparse_set_snap_wf(
2720                self.reprs.dense_snapshots_view()[k_new],
2721                self.reprs.sparse_snapshots_view()[k_new],
2722                self.reprs.indices_snapshots_view()[k_new]));
2723            assert forall|k: int| 0 <= k < self.entries.model_snapshots_view().len()
2724                implies eg_model_wf::<T, K, L, N>(
2725                    #[trigger] self.entries.model_snapshots_view()[k],
2726                    ring_payloads(self.entries.entries_snapshots_view()[k]),
2727                    self.uf.roots_snapshots_view()[k],
2728                    self.reprs.dense_snapshots_view()[k],
2729                    self.reprs.sparse_snapshots_view()[k],
2730                    self.reprs.indices_snapshots_view()[k],
2731                    self.uses.model_snapshots_view()[k],
2732                    self.uses.nodes_snapshots_view()[k],
2733                    self.min_pool.snapshots_view()[k],
2734                    self.min_width as nat)
2735                && crate::sparse_set::sparse_set_snap_wf(
2736                    self.reprs.dense_snapshots_view()[k],
2737                    self.reprs.sparse_snapshots_view()[k],
2738                    self.reprs.indices_snapshots_view()[k]) by {
2739                if k < k_new {
2740                    assert(self.entries.model_snapshots_view()[k]
2741                        == o.entries.model_snapshots_view()[k]);
2742                    assert(self.entries.entries_snapshots_view()[k]
2743                        == o.entries.entries_snapshots_view()[k]);
2744                    assert(self.uf.roots_snapshots_view()[k]
2745                        == o.uf.roots_snapshots_view()[k]);
2746                    assert(self.reprs.dense_snapshots_view()[k]
2747                        == o.reprs.dense_snapshots_view()[k]);
2748                    assert(self.reprs.sparse_snapshots_view()[k]
2749                        == o.reprs.sparse_snapshots_view()[k]);
2750                    assert(self.reprs.indices_snapshots_view()[k]
2751                        == o.reprs.indices_snapshots_view()[k]);
2752                    assert(self.uses.model_snapshots_view()[k]
2753                        == o.uses.model_snapshots_view()[k]);
2754                    assert(self.uses.nodes_snapshots_view()[k]
2755                        == o.uses.nodes_snapshots_view()[k]);
2756                    assert(self.min_pool.snapshots_view()[k]
2757                        == o.min_pool.snapshots_view()[k]);
2758                }
2759            }
2760            // pool monotonicity: old pairs carry; pairs ending at the new
2761            // frame are bounded by the live length it archives.
2762            assert forall|k1: int, k2: int|
2763                0 <= k1 <= k2 < self.min_pool.snapshots_view().len()
2764                implies (#[trigger] self.min_pool.snapshots_view()[k1]).len()
2765                    <= (#[trigger] self.min_pool.snapshots_view()[k2]).len() by {
2766                if k2 < k_new {
2767                    assert(self.min_pool.snapshots_view()[k1]
2768                        == o.min_pool.snapshots_view()[k1]);
2769                    assert(self.min_pool.snapshots_view()[k2]
2770                        == o.min_pool.snapshots_view()[k2]);
2771                } else if k1 < k_new {
2772                    assert(self.min_pool.snapshots_view()[k1]
2773                        == o.min_pool.snapshots_view()[k1]);
2774                    assert(self.min_pool.snapshots_view()[k1].len()
2775                        <= o.min_pool.view().len());
2776                }
2777            }
2778        }
2779        EClassesToken {
2780            entries: t_entries,
2781            reprs: t_reprs,
2782            uf: t_uf,
2783            uses: t_uses,
2784            pool: t_pool,
2785        }
2786    }
2787
2788    /// "Restorable now" for the composite token: every constituent
2789    /// restorable AND all nine leaf frames name the same mark.
2790    pub fn is_valid_token(&self, token: &EClassesToken) -> (b: bool)
2791        requires self.wf(),
2792    {
2793        self.entries.is_valid_token(&token.entries)
2794            && self.reprs.is_valid_token(&token.reprs)
2795            && self.uf.is_valid_token(&token.uf)
2796            && self.uses.is_valid_token(&token.uses)
2797            && self.min_pool.is_valid_token(&token.pool)
2798            && self.frames_agree(token)
2799    }
2800
2801    /// All nine leaf tokens name the same frame (frankentoken defense).
2802    fn frames_agree(&self, token: &EClassesToken) -> (b: bool)
2803        ensures b == ({
2804            &&& token.entries.frame_idx_spec() == token.frame_idx_spec()
2805            &&& token.reprs.dense_frame_idx_spec() == token.frame_idx_spec()
2806            &&& token.reprs.sparse_frame_idx_spec() == token.frame_idx_spec()
2807            &&& token.reprs.indices_frame_idx_spec() == token.frame_idx_spec()
2808            &&& token.uf.parent_frame_idx_spec() == token.frame_idx_spec()
2809            &&& token.uf.rank_frame_idx_spec() == token.frame_idx_spec()
2810            &&& token.uses.heads_frame_idx_spec() == token.frame_idx_spec()
2811            &&& token.uses.nodes_frame_idx_spec() == token.frame_idx_spec()
2812        }),
2813    {
2814        let f = token.pool.frame_idx;
2815        token.entries.entries.frame_idx == f
2816            && token.reprs.dense.frame_idx == f
2817            && token.reprs.sparse.frame_idx == f
2818            && token.reprs.indices.frame_idx == f
2819            && token.uf.parent.frame_idx == f
2820            && token.uf.rank.frame_idx == f
2821            && token.uses.heads.frame_idx == f
2822            && token.uses.nodes.frame_idx == f
2823    }
2824
2825    /// Restore the aggregate to the marked frame. Refuses an invalid,
2826    /// foreign, stale, consumed, or mixed-mark token before any mutation;
2827    /// `SparseSet::restore`'s snapshot-wellformedness precondition is
2828    /// discharged from the aggregate's own archive.
2829    pub fn restore(&mut self, token: EClassesToken)
2830        requires old(self).wf(),
2831        ensures
2832            final(self).wf(),
2833            final(self).min_width_spec() == old(self).min_width_spec(),
2834            old(self).is_restorable_full_spec(token) ==> {
2835                &&& final(self).roots_view() == old(self).roots_archive_view()[
2836                        token.frame_idx_spec() as int]
2837                &&& final(self).n_spec() == old(self).roots_archive_view()[
2838                        token.frame_idx_spec() as int].len()
2839            },
2840    {
2841        if !(self.entries.is_valid_token(&token.entries)
2842            && self.reprs.is_valid_token(&token.reprs)
2843            && self.uf.is_valid_token(&token.uf)
2844            && self.uses.is_valid_token(&token.uses)
2845            && self.min_pool.is_valid_token(&token.pool)
2846            && self.frames_agree(&token))
2847        {
2848            crate::guard::refuse(
2849                "EClasses::restore: invalid, foreign, stale, consumed, abandoned, or mixed-mark token");
2850        }
2851        let ghost o = *old(self);
2852        let ghost f = token.pool.frame_idx as int;
2853        proof {
2854            reveal(eg_archive_agrees);
2855            assert(eg_archive_agrees::<T, K, L, N>(
2856                o.entries.model_snapshots_view(),
2857                o.entries.entries_snapshots_view(),
2858                o.uf.roots_snapshots_view(),
2859                o.reprs.dense_snapshots_view(),
2860                o.reprs.sparse_snapshots_view(),
2861                o.reprs.indices_snapshots_view(),
2862                o.uses.model_snapshots_view(),
2863                o.uses.nodes_snapshots_view(),
2864                o.min_pool.snapshots_view(),
2865                o.min_width as nat));
2866            // the archived frame f is a jointly-valid state; in particular
2867            // the repr triple is sparse-set well-formed, which is
2868            // SparseSet::restore's precondition.
2869            assert(crate::sparse_set::sparse_set_snap_wf(
2870                o.reprs.dense_snapshots_view()[f],
2871                o.reprs.sparse_snapshots_view()[f],
2872                o.reprs.indices_snapshots_view()[f]));
2873        }
2874        self.entries.restore(token.entries);
2875        self.reprs.restore(token.reprs);
2876        self.uf.restore(token.uf);
2877        self.uses.restore(token.uses);
2878        self.min_pool.restore(token.pool);
2879        proof {
2880            reveal(eg_archive_agrees);
2881            // restored views are the archived frame-f views.
2882            assert(self.entries.model_view() == o.entries.model_snapshots_view()[f]);
2883            assert(self.entries.payload_seq()
2884                =~= ring_payloads(o.entries.entries_snapshots_view()[f]));
2885            assert(self.uf.roots_view() == o.uf.roots_snapshots_view()[f]);
2886            assert(eg_model_wf::<T, K, L, N>(
2887                self.entries.model_view(), self.entries.payload_seq(),
2888                self.uf.roots_view(), self.reprs.dense_view(),
2889                self.reprs.sparse_view(), self.reprs.indices_view(),
2890                self.uses.model_view(), self.uses.nodes_view(),
2891                self.min_pool.view(), self.min_width as nat));
2892            // truncated stacks agree per frame below f.
2893            assert forall|k: int| 0 <= k < self.entries.model_snapshots_view().len()
2894                implies eg_model_wf::<T, K, L, N>(
2895                    #[trigger] self.entries.model_snapshots_view()[k],
2896                    ring_payloads(self.entries.entries_snapshots_view()[k]),
2897                    self.uf.roots_snapshots_view()[k],
2898                    self.reprs.dense_snapshots_view()[k],
2899                    self.reprs.sparse_snapshots_view()[k],
2900                    self.reprs.indices_snapshots_view()[k],
2901                    self.uses.model_snapshots_view()[k],
2902                    self.uses.nodes_snapshots_view()[k],
2903                    self.min_pool.snapshots_view()[k],
2904                    self.min_width as nat)
2905                && crate::sparse_set::sparse_set_snap_wf(
2906                    self.reprs.dense_snapshots_view()[k],
2907                    self.reprs.sparse_snapshots_view()[k],
2908                    self.reprs.indices_snapshots_view()[k]) by {
2909                assert(self.entries.model_snapshots_view()[k]
2910                    == o.entries.model_snapshots_view()[k]);
2911                assert(self.entries.entries_snapshots_view()[k]
2912                    == o.entries.entries_snapshots_view()[k]);
2913                assert(self.uf.roots_snapshots_view()[k]
2914                    == o.uf.roots_snapshots_view()[k]);
2915                assert(self.reprs.dense_snapshots_view()[k]
2916                    == o.reprs.dense_snapshots_view()[k]);
2917                assert(self.reprs.sparse_snapshots_view()[k]
2918                    == o.reprs.sparse_snapshots_view()[k]);
2919                assert(self.reprs.indices_snapshots_view()[k]
2920                    == o.reprs.indices_snapshots_view()[k]);
2921                assert(self.uses.model_snapshots_view()[k]
2922                    == o.uses.model_snapshots_view()[k]);
2923                assert(self.uses.nodes_snapshots_view()[k]
2924                    == o.uses.nodes_snapshots_view()[k]);
2925                assert(self.min_pool.snapshots_view()[k]
2926                    == o.min_pool.snapshots_view()[k]);
2927            }
2928            assert forall|k1: int, k2: int|
2929                0 <= k1 <= k2 < self.min_pool.snapshots_view().len()
2930                implies (#[trigger] self.min_pool.snapshots_view()[k1]).len()
2931                    <= (#[trigger] self.min_pool.snapshots_view()[k2]).len() by {
2932                assert(self.min_pool.snapshots_view()[k1]
2933                    == o.min_pool.snapshots_view()[k1]);
2934                assert(self.min_pool.snapshots_view()[k2]
2935                    == o.min_pool.snapshots_view()[k2]);
2936            }
2937            // archived pools below f are bounded by the restored pool
2938            // (monotonicity at (k, f)).
2939            assert forall|k: int| 0 <= k < self.min_pool.snapshots_view().len()
2940                implies (#[trigger] self.min_pool.snapshots_view()[k]).len()
2941                    <= self.min_pool.view().len() by {
2942                assert(o.min_pool.snapshots_view()[k].len()
2943                    <= o.min_pool.snapshots_view()[f].len());
2944            }
2945        }
2946    }
2947
2948    /// The full runtime-checkable restore precondition (spec counterpart of
2949    /// `is_valid_token` plus the frame agreement).
2950    pub open(crate) spec fn is_restorable_full_spec(&self, token: EClassesToken) -> bool {
2951        &&& self.entries.is_restorable_spec(token.entries)
2952        &&& self.reprs.is_restorable_spec(token.reprs)
2953        &&& self.uf.is_restorable_spec(token.uf)
2954        &&& self.uses.is_restorable_spec(token.uses)
2955        &&& self.min_pool.is_restorable_spec(token.pool)
2956        &&& token.entries.frame_idx_spec() == token.frame_idx_spec()
2957        &&& token.reprs.dense_frame_idx_spec() == token.frame_idx_spec()
2958        &&& token.reprs.sparse_frame_idx_spec() == token.frame_idx_spec()
2959        &&& token.reprs.indices_frame_idx_spec() == token.frame_idx_spec()
2960        &&& token.uf.parent_frame_idx_spec() == token.frame_idx_spec()
2961        &&& token.uf.rank_frame_idx_spec() == token.frame_idx_spec()
2962        &&& token.uses.heads_frame_idx_spec() == token.frame_idx_spec()
2963        &&& token.uses.nodes_frame_idx_spec() == token.frame_idx_spec()
2964    }
2965
2966    /// Total restore: an unusable token is `Err(InvalidToken)`.
2967    pub fn try_restore(&mut self, token: EClassesToken)
2968        -> (r: Result<(), crate::error::ContainerError>)
2969        requires old(self).wf(),
2970        ensures
2971            final(self).wf(),
2972            r matches Err(e) ==> e == crate::error::ContainerError::InvalidToken
2973                && final(self).roots_view() == old(self).roots_view(),
2974    {
2975        if self.entries.is_valid_token(&token.entries)
2976            && self.reprs.is_valid_token(&token.reprs)
2977            && self.uf.is_valid_token(&token.uf)
2978            && self.uses.is_valid_token(&token.uses)
2979            && self.min_pool.is_valid_token(&token.pool)
2980            && self.frames_agree(&token)
2981        {
2982            self.restore(token);
2983            Ok(())
2984        } else {
2985            Err(crate::error::ContainerError::InvalidToken)
2986        }
2987    }
2988}
2989
2990} // verus!
2991
2992// ---------------------------------------------------------------------------
2993// Justified merges and explain (trusted glue; the partition work is the
2994// verified core, the proof edge and LCA walk are production's algorithms in
2995// the union-find's glue — doc/design/egraph-class-layer.md).
2996// ---------------------------------------------------------------------------
2997
2998impl<T, K, L, N, J, const TRACK: bool, const PROOFS: bool> EClasses<T, K, L, N, J, TRACK, PROOFS>
2999where
3000    T: DenseId,
3001    K: DenseId<Index = T::Index>,
3002    L: DenseId,
3003    N: DenseId + Tagged + core::default::Default,
3004    J: Tagged + Copy + core::default::Default,
3005{
3006    /// Merge with justification (records the proof edge `a—b`).
3007    pub fn merge_justified(&mut self, a: T, b: T, just: J) -> Option<MergeInfo<T, L>> {
3008        let r = self.merge_with(a, b, false, false);
3009        if r.is_some() {
3010            self.uf.record_proof_edge(a, b, just);
3011        }
3012        r
3013    }
3014
3015    /// Justified counterpart of [`Self::merge_directed`].
3016    pub fn merge_justified_directed(&mut self, a: T, b: T, just: J) -> Option<MergeInfo<T, L>> {
3017        let prefer_a = self.prefer_a_by_uses(a, b);
3018        let r = self.merge_with(a, b, true, prefer_a);
3019        if r.is_some() {
3020            self.uf.record_proof_edge(a, b, just);
3021        }
3022        r
3023    }
3024
3025    /// Justified counterpart of [`Self::merge_directed_with`]: the caller
3026    /// computed its own survivor policy (`--union-by`).
3027    pub fn merge_justified_directed_with(
3028        &mut self,
3029        a: T,
3030        b: T,
3031        prefer_a: bool,
3032        just: J,
3033    ) -> Option<MergeInfo<T, L>> {
3034        let r = self.merge_with(a, b, true, prefer_a);
3035        if r.is_some() {
3036            self.uf.record_proof_edge(a, b, just);
3037        }
3038        r
3039    }
3040
3041    /// Explain why `a ≡ b` by walking the proof tree (production's surface).
3042    pub fn explain(&self, a: T, b: T, buf: &mut crate::union_find::ProofBuf<T, J>) -> bool {
3043        self.uf.explain(a, b, buf)
3044    }
3045
3046    /// Read-only proof-parent forest for an Euler-tour batch index.
3047    pub fn proof_parent(&self) -> Option<&crate::VecI<T, T::Index, TRACK>> {
3048        self.uf.proof_parent()
3049    }
3050
3051    /// Extract a proof using an LCA obtained from [`Self::proof_parent`].
3052    pub fn explain_with_lca(
3053        &self,
3054        a: T,
3055        b: T,
3056        lca: T,
3057        buf: &mut crate::union_find::ProofBuf<T, J>,
3058    ) -> bool {
3059        self.uf.explain_with_lca(a, b, lca, buf)
3060    }
3061}
3062
3063// prod-parity: the consumer's adapter token derives `Debug` and bundles this
3064// one; manual because deriving inside `verus!{}` is unsupported.
3065impl core::fmt::Debug for EClassesToken {
3066    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3067        f.debug_struct("EClassesToken")
3068            .field("entries", &self.entries)
3069            .field("reprs", &self.reprs)
3070            .field("uf", &self.uf)
3071            .field("uses", &self.uses)
3072            .field("pool", &self.pool)
3073            .finish()
3074    }
3075}
3076
3077// Production-surface parity (the pre-swap class layer shipped Default).
3078impl<T, K, L, N, J, const TRACK: bool, const PROOFS: bool> Default
3079    for EClasses<T, K, L, N, J, TRACK, PROOFS>
3080where
3081    T: DenseId,
3082    K: DenseId<Index = T::Index>,
3083    L: DenseId,
3084    N: DenseId + Tagged + core::default::Default,
3085    J: Tagged + Copy + core::default::Default,
3086{
3087    fn default() -> Self {
3088        Self::new()
3089    }
3090}