Skip to main content

semi_persistent_egraph/au/
egraph_api.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Read-only snapshot of a frozen e-graph for anti-unification (§4.1).
4//!
5//! Owns: dense class numbering, per-class members grouped by operator, best-term
6//! sizes (§A.2), SCC-based reachability bitsets (§2.4).
7//! Borrows: the e-graph reference for node-level reads (op, children, flags).
8
9use super::{AuError, Span};
10use crate::canon::{MSetCanon, VarCanon};
11use crate::config::{AuIds, EGraphConfig};
12use crate::containers::{DenseId, IndexLike};
13use crate::egraph::EGraph;
14use crate::literal::LitVal;
15use crate::multiplicity::MultiplicityLike;
16use crate::node_types::FLAG_SUBSUMED;
17
18/// Class id projected from a config's AU family.
19pub type ClassOf<Cfg> = <<Cfg as EGraphConfig>::Au as AuIds>::Class;
20/// SCC id projected from a config's AU family.
21pub type SccOf<Cfg> = <<Cfg as EGraphConfig>::Au as AuIds>::Scc;
22
23// `ClassMembers` and `MemberNode` used to sit here, describing per-class membership
24// as `Vec<(O, u32)>` plus a `u32` child count. Both were dead — nothing in the crate
25// ever constructed or read either one — and both had the wrong widths: the `u32` was
26// documented as a *global e-node id*, which is `Cfg::G` and does not fit 32 bits in a
27// 63-bit session, and the child count is a node arity (a span in the child pool, so
28// `Cfg::Index`-wide). The live path was already correct and stays: `members()` returns
29// `&[(Cfg::O, Cfg::G)]` out of `member_pool`, spans into it are `member_spans`, and
30// arities are read from the node itself. Removed rather than widened so that nobody
31// reaches for the plausible-looking struct instead.
32
33/// Immutable snapshot built once from a frozen e-graph. The search operates on this.
34pub struct AuSnapshot<'eg, Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>
35where
36    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
37{
38    pub(crate) eg: &'eg EGraph<Cfg, L, T, P>,
39    /// Dense representative -> `ClassOf<Cfg>` map (representative global ids only).
40    repr_to_au: hashbrown::HashMap<Cfg::G, ClassOf<Cfg>>,
41    /// `ClassOf<Cfg>` -> representative global id.
42    pub(crate) au_to_repr: Vec<Cfg::G>,
43    /// Per-class member list: `members[class]` is a range into `member_pool`.
44    member_spans: Vec<Span<<Cfg::Au as AuIds>::SnapshotMember>>,
45    /// All admissible members across all classes: (op, global_id).
46    member_pool: Vec<(Cfg::O, Cfg::G)>,
47    /// Best (minimum) size of any finite member in each class.
48    best_size: Vec<u32>,
49    /// Global id of the best (cheapest) member per class.
50    best_node: Vec<Option<Cfg::G>>,
51    /// Reachability data: which class is reachable from which.
52    reach: Reachability<Cfg::Au>,
53}
54
55/// SCC-condensed reachability (§2.4): Tarjan SCCs, one bitset per SCC.
56#[derive(Debug, Clone)]
57pub struct Reachability<A: AuIds> {
58    /// class -> SCC index.
59    class_to_scc: Vec<A::Scc>,
60    /// Per-SCC: typed span into `bit_blocks`.
61    scc_spans: Vec<Span<A::ReachBlock>>,
62    /// Packed bit blocks (one dense bitset per SCC, each `ceil(num_classes/64)` u64s).
63    bit_blocks: Vec<u64>,
64    /// Per-SCC population count of the block above. Computed once with the
65    /// bitsets, which already cost one pass over every block, so the size of a
66    /// reachable set is an array read rather than a scan.
67    scc_reach_count: Vec<u32>,
68    /// Number of classes (determines bitset width).
69    num_classes: u64,
70}
71
72impl<A: AuIds> Reachability<A> {
73    /// Does class `target` belong to `reach(source)`?
74    #[inline]
75    pub fn is_reachable(&self, source: A::Class, target: A::Class) -> bool {
76        let scc = self.class_to_scc[source.to_usize()];
77        let start = self.scc_spans[scc.to_usize()].start_usize();
78        let t = target.to_usize();
79        let word = start + t / 64;
80        let bit = t % 64;
81        (self.bit_blocks[word] >> bit) & 1 != 0
82    }
83
84    /// How many classes are in `reach(source)`. Note the asymmetry the bitsets
85    /// already have: a class belongs to its own reachable set only when it sits
86    /// on a cycle, so an acyclic class counts its strict descendants.
87    #[inline]
88    pub fn reach_count(&self, source: A::Class) -> u64 {
89        let scc = self.class_to_scc[source.to_usize()];
90        u64::from(self.scc_reach_count[scc.to_usize()])
91    }
92
93    /// Number of classes in this reachability table.
94    pub fn num_classes(&self) -> u64 {
95        self.num_classes
96    }
97}
98
99impl<'eg, Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool> AuSnapshot<'eg, Cfg, L, T, P>
100where
101    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
102{
103    /// Build a snapshot from the frozen e-graph. The e-graph must not be mutated
104    /// while this snapshot is alive (enforced by the shared reference lifetime).
105    pub fn new(eg: &'eg EGraph<Cfg, L, T, P>) -> Result<Self, AuError> {
106        // --- Step 1: collect live class representatives ---
107        let n = eg.len();
108        let mut repr_to_au: hashbrown::HashMap<Cfg::G, ClassOf<Cfg>> =
109            hashbrown::HashMap::with_capacity(n / 2);
110        let mut au_to_repr: Vec<Cfg::G> = Vec::new();
111
112        // Discover representatives by scanning all nodes. Some nodes may have
113        // the same representative; HashMap deduplicates.
114        for id in eg.node_ids() {
115            let repr = eg.find_const(id);
116            repr_to_au.entry(repr).or_insert_with(|| {
117                // Checked: this is the one place snapshot class ids are minted, and nothing
118                // ties `ClassOf<Cfg>`'s id space to `Cfg::G`'s. One class per distinct
119                // representative bounds the count by the node count, but only the shipped
120                // configs happen to pair equal-width families (31/31, 63/63) — a config that
121                // narrowed the AU family would mask here, and two representatives would
122                // answer to one class id for the whole search.
123                let au = crate::id::id_at::<ClassOf<Cfg>>(au_to_repr.len());
124                au_to_repr.push(repr);
125                au
126            });
127        }
128
129        let num_classes = au_to_repr.len();
130
131        // --- Step 2: per-class members grouped by op (excluding FLAG_SUBSUMED) ---
132        // First pass: collect per-class member lists.
133        let mut class_members: Vec<Vec<(Cfg::O, Cfg::G)>> = vec![Vec::new(); num_classes];
134
135        for id in eg.node_ids() {
136            let flags = eg.node_flags(id);
137            if flags & FLAG_SUBSUMED != 0 {
138                continue;
139            }
140            let repr = eg.find_const(id);
141            let au_class = repr_to_au[&repr];
142            let op = eg.node_op(id);
143            class_members[au_class.to_usize()].push((op, id));
144        }
145
146        // Sort each class's members by op for grouped access.
147        for members in &mut class_members {
148            members.sort_by_key(|&(op, _)| op.to_usize());
149        }
150
151        // Flatten into member_pool + spans.
152        let total_members: usize = class_members.iter().map(|m| m.len()).sum();
153        let mut member_pool: Vec<(Cfg::O, Cfg::G)> = Vec::with_capacity(total_members);
154        let mut member_spans: Vec<Span<<Cfg::Au as AuIds>::SnapshotMember>> =
155            Vec::with_capacity(num_classes);
156
157        for members in &class_members {
158            let start = member_pool.len();
159            member_pool.extend_from_slice(members);
160            member_spans.push(Span::new(start, members.len()));
161        }
162
163        // --- Step 3: best-term fixpoint (§A.2) ---
164        let (best_size, best_node) = Self::compute_best_terms(eg, &repr_to_au, num_classes)?;
165
166        // --- Step 4: reachability (§2.4) ---
167        let reach = Self::compute_reachability(eg, &repr_to_au, &au_to_repr, num_classes);
168
169        Ok(AuSnapshot {
170            eg,
171            repr_to_au,
172            au_to_repr,
173            member_spans,
174            member_pool,
175            best_size,
176            best_node,
177            reach,
178        })
179    }
180
181    // --- Public API ---
182
183    /// Number of live classes in this snapshot.
184    pub fn num_classes(&self) -> usize {
185        self.au_to_repr.len()
186    }
187
188    /// SpMap a representative global id to its dense class id.
189    /// Returns `None` if the id is not a representative in this snapshot.
190    #[inline]
191    pub fn class_id(&self, repr: Cfg::G) -> Option<ClassOf<Cfg>> {
192        self.repr_to_au.get(&repr).copied()
193    }
194
195    /// SpMap a global id (not necessarily a representative) to its dense class id.
196    #[inline]
197    pub fn class_of(&self, id: Cfg::G) -> Option<ClassOf<Cfg>> {
198        let repr = self.eg.find_const(id);
199        self.repr_to_au.get(&repr).copied()
200    }
201
202    /// The representative global id for a dense class id.
203    #[inline]
204    pub fn repr(&self, au: ClassOf<Cfg>) -> Cfg::G {
205        self.au_to_repr[au.to_usize()]
206    }
207
208    /// The best (smallest) member size for class `au`.
209    #[inline]
210    pub fn best_size(&self, au: ClassOf<Cfg>) -> u32 {
211        self.best_size[au.to_usize()]
212    }
213
214    /// The global id of the best member for class `au`.
215    ///
216    /// # Panics
217    /// Panics if `au` has no admissible finite member. Callers operating on
218    /// auxiliary classes must check [`Self::has_finite_member`] first.
219    #[inline]
220    pub fn best_node(&self, au: ClassOf<Cfg>) -> Cfg::G {
221        self.best_node[au.to_usize()]
222            .expect("best_node requested for a class without an admissible finite member")
223    }
224
225    /// Iterator over `(op, global_id)` pairs for all admissible members of `au`.
226    #[inline]
227    pub fn members(&self, au: ClassOf<Cfg>) -> &[(Cfg::O, Cfg::G)] {
228        let span = self.member_spans[au.to_usize()];
229        &self.member_pool[span.start_usize()..span.end_usize()]
230    }
231
232    /// The reachability table.
233    #[inline]
234    pub fn reachability(&self) -> &Reachability<Cfg::Au> {
235        &self.reach
236    }
237
238    /// The e-graph reference (for node-level queries like op, children, etc.).
239    #[inline]
240    pub fn egraph(&self) -> &'eg EGraph<Cfg, L, T, P> {
241        self.eg
242    }
243
244    /// Operator of a global e-node id.
245    #[inline]
246    pub fn node_op(&self, id: Cfg::G) -> Cfg::O {
247        self.eg.node_op(id)
248    }
249
250    /// Whether this class has an admissible finite member (§A.2 fixpoint resolved it).
251    /// A class is infinite when every admissible member references the class itself
252    /// (e.g. its only finite leaf was subsumed).
253    #[inline]
254    pub fn has_finite_member(&self, au: ClassOf<Cfg>) -> bool {
255        self.best_size[au.to_usize()] != u32::MAX
256    }
257
258    /// Validate that `root` and every class reachable from it has a finite member
259    /// (§4.1: `AuError::NoFiniteRepresentative` if any class needed by a root has no
260    /// admissible finite member). Called once per root before a search starts.
261    pub fn validate_finite_from(&self, root: ClassOf<Cfg>) -> Result<(), AuError> {
262        if !self.has_finite_member(root) {
263            return Err(AuError::NoFiniteRepresentative(root.to_usize() as u64));
264        }
265        // `au_to_repr` was filled through a checked mint, so its length is inside the
266        // class id space and these positions all name a class.
267        for c in crate::id::ids_upto::<ClassOf<Cfg>>(self.num_classes()) {
268            if self.reach.is_reachable(root, c) && !self.has_finite_member(c) {
269                return Err(AuError::NoFiniteRepresentative(c.to_usize() as u64));
270            }
271        }
272        Ok(())
273    }
274
275    /// Whether the canonical node kind of `op` is commutative (SPair, MSet, Set):
276    /// result-term children for such operators are sorted into canonical order,
277    /// while ordered operators preserve positional order.
278    /// The identity (unit) element's `ClassOf<Cfg>` for an operator, if the operator
279    /// has a declared identity (e.g. `true` for `and`, `false` for `or`, `0` for `+`).
280    /// Returns `None` if no identity is declared, the identity node is not in a live
281    /// class, or that class has no admissible finite representative. The last check is
282    /// required because identity padding materializes the representative in projections;
283    /// a subsumed-only identity class must not be injected as an auxiliary child.
284    pub fn op_identity_class(&self, op: Cfg::O) -> Option<ClassOf<Cfg>> {
285        let unit_node = self.eg.unit_node(op)?;
286        let class = self.class_of(unit_node)?;
287        self.has_finite_member(class).then_some(class)
288    }
289
290    pub fn op_is_commutative(&self, op: Cfg::O) -> bool {
291        matches!(
292            self.eg.ops().info(op).canon_class(),
293            crate::id::ENodeKind::SPair | crate::id::ENodeKind::MSet | crate::id::ENodeKind::Set
294        )
295    }
296
297    // --- Private implementation ---
298
299    /// Best-term fixpoint: cost = 1 + sum(mult * cost(class(child))) per node,
300    /// minimized per class (§A.2). Returns (best_size, best_node) vectors indexed
301    /// by ClassOf<Cfg>.
302    ///
303    /// `u32::MAX` is the *sentinel* for "this class has no finite representative
304    /// yet" ([`has_finite_member`](Self::has_finite_member) tests exactly that), so
305    /// no finite cost may ever equal it. The summation therefore runs in `u64` with
306    /// checked steps and a node is dropped as a candidate unless its total lands
307    /// strictly below the sentinel. Saturating into `u32::MAX` instead would make a
308    /// large-but-finite term indistinguishable from an absent one: the class would
309    /// report no finite member, and — because `total < best_size` is false when both
310    /// are the sentinel — would never even record a `best_node`.
311    fn compute_best_terms(
312        eg: &EGraph<Cfg, L, T, P>,
313        repr_to_au: &hashbrown::HashMap<Cfg::G, ClassOf<Cfg>>,
314        num_classes: usize,
315    ) -> Result<(Vec<u32>, Vec<Option<Cfg::G>>), AuError> {
316        let mut best_size: Vec<u32> = vec![u32::MAX; num_classes];
317        let mut best_node: Vec<Option<Cfg::G>> = vec![None; num_classes];
318
319        loop {
320            let mut changed = false;
321            for id in eg.node_ids() {
322                let flags = eg.node_flags(id);
323                if flags & FLAG_SUBSUMED != 0 {
324                    continue;
325                }
326                let repr = eg.find_const(id);
327                let au_class = match repr_to_au.get(&repr) {
328                    Some(&c) => c,
329                    None => continue,
330                };
331
332                // Widened so the sentinel cannot be reached by arithmetic; an
333                // overflow drops the node from consideration, which costs nothing
334                // real — a term of more than 2^32 - 2 nodes cannot be materialized.
335                let mut total: u64 = 1;
336                let mut ok = true;
337                eg.for_each_child(id, |child, mult| {
338                    if !ok {
339                        return;
340                    }
341                    let child_repr = eg.find_const(child);
342                    match repr_to_au.get(&child_repr) {
343                        Some(&child_au) => {
344                            let child_cost = best_size[child_au.to_usize()];
345                            if child_cost == u32::MAX {
346                                ok = false;
347                            } else {
348                                match u64::from(child_cost)
349                                    .checked_mul(mult.to_u64())
350                                    .and_then(|c| total.checked_add(c))
351                                {
352                                    Some(t) => total = t,
353                                    None => ok = false,
354                                }
355                            }
356                        }
357                        None => {
358                            ok = false;
359                        }
360                    }
361                });
362                // Strictly below the sentinel, so a recorded size always means
363                // "finite representative of exactly this many nodes".
364                if !ok || total >= u64::from(u32::MAX) {
365                    continue;
366                }
367                let total = total as u32;
368
369                if total < best_size[au_class.to_usize()] {
370                    best_size[au_class.to_usize()] = total;
371                    best_node[au_class.to_usize()] = Some(id);
372                    changed = true;
373                }
374            }
375            if !changed {
376                break;
377            }
378        }
379
380        Ok((best_size, best_node))
381    }
382
383    /// Compute SCC-based reachability (§2.4):
384    /// 1. Tarjan SCC over the class graph (edge = class -> class of each child)
385    /// 2. Bitset union in reverse topological order
386    fn compute_reachability(
387        eg: &EGraph<Cfg, L, T, P>,
388        repr_to_au: &hashbrown::HashMap<Cfg::G, ClassOf<Cfg>>,
389        au_to_repr: &[Cfg::G],
390        num_classes: usize,
391    ) -> Reachability<Cfg::Au> {
392        let words_per_scc = num_classes.div_ceil(64);
393
394        // Build adjacency: class -> set of successor classes.
395        let mut adj: Vec<Vec<ClassOf<Cfg>>> = vec![Vec::new(); num_classes];
396        for id in eg.node_ids() {
397            let flags = eg.node_flags(id);
398            if flags & FLAG_SUBSUMED != 0 {
399                continue;
400            }
401            let repr = eg.find_const(id);
402            let src = match repr_to_au.get(&repr) {
403                Some(&c) => c,
404                None => continue,
405            };
406            eg.for_each_child(id, |child, _mult| {
407                let child_repr = eg.find_const(child);
408                if let Some(&dst) = repr_to_au.get(&child_repr) {
409                    adj[src.to_usize()].push(dst);
410                }
411            });
412        }
413
414        // Deduplicate adjacency (important for performance and correctness of SCC sizes).
415        for neighbors in &mut adj {
416            neighbors.sort_unstable();
417            neighbors.dedup();
418        }
419
420        // --- Tarjan's SCC algorithm ---
421        //
422        // Every counter below is a position in the class population, so all of them are
423        // `Cfg::Index` — the word that population is pinned to — rather than a literal
424        // `u32`. At a 63-bit config the class count passes four billion, and each of
425        // these was a silent wrap there, not a clean failure: the discovery counter would
426        // restart at zero and hand two classes the same discovery index, which makes
427        // Tarjan report SCCs that are not SCCs. The reachability bitsets built from them
428        // are what admissibility and `validate_finite_from` consult, so the damage would
429        // surface as confident, wrong anti-unification results rather than an error.
430        //
431        // `undefined` is the "not yet visited" marker for `node_index`, kept as a
432        // sentinel rather than an `Option` so the column stays one word per class. Its
433        // distinctness is checked once, below, instead of being argued from the id family:
434        // it holds for any bit-stealing id (whose `id_bound()` is half the word) but a
435        // full-range index type would have no value to spare, and that deserves to fail
436        // loudly at the top rather than alias a real discovery index at the very end.
437        let undefined = <Cfg::Index as IndexLike>::max();
438        assert!(
439            num_classes < undefined.as_usize(),
440            "AU snapshot has {num_classes} classes, leaving EGraphConfig::Index no value \
441             to spare for Tarjan's `undefined` marker; configure a wider index word"
442        );
443        let zero = <Cfg::Index as IndexLike>::min();
444        let mut index_counter = zero;
445        let mut stack: Vec<ClassOf<Cfg>> = Vec::new();
446        let mut on_stack: Vec<bool> = vec![false; num_classes];
447        let mut node_index: Vec<Cfg::Index> = vec![undefined; num_classes];
448        let mut node_lowlink: Vec<Cfg::Index> = vec![zero; num_classes];
449        // Filler until Tarjan assigns each class its real SCC. Id 0 exists in every id
450        // family, so this mint cannot be out of range.
451        let mut class_to_scc: Vec<SccOf<Cfg>> = vec![<SccOf<Cfg>>::from_usize(0); num_classes];
452        let mut scc_members: Vec<Vec<ClassOf<Cfg>>> = Vec::new();
453
454        // One discovery index per class, so the assert above bounds this; the `expect` is
455        // unreachable and says which invariant would have to break first.
456        let bump = |c: Cfg::Index| {
457            crate::containers::index_like::checked_incr(c).expect(
458                "Tarjan discovery counter passed EGraphConfig::Index; \
459                         it is bounded by the class count, checked above",
460            )
461        };
462
463        // Iterative Tarjan to avoid stack overflow on deep graphs.
464        #[derive(Clone, Copy)]
465        struct TarjanFrame<C, I> {
466            node: C,
467            /// Cursor into the node's deduplicated adjacency, which is bounded by the
468            /// class count — hence the config's index word, not a fixed one.
469            neighbor_idx: I,
470        }
471
472        // Checked once for the whole walk, not per class: the classes were minted checked
473        // in `new`, so this only re-states that here rather than trusting it.
474        for start_id in crate::id::ids_upto::<ClassOf<Cfg>>(num_classes) {
475            let start = start_id.to_usize();
476            if node_index[start] != undefined {
477                continue;
478            }
479
480            let mut call_stack: Vec<TarjanFrame<ClassOf<Cfg>, Cfg::Index>> = Vec::new();
481            // Initialize the start node.
482            node_index[start] = index_counter;
483            node_lowlink[start] = index_counter;
484            index_counter = bump(index_counter);
485            on_stack[start] = true;
486            stack.push(start_id);
487            call_stack.push(TarjanFrame {
488                node: start_id,
489                neighbor_idx: zero,
490            });
491
492            while let Some(frame) = call_stack.last_mut() {
493                let v = frame.node;
494                let vi = v.to_usize();
495                let neighbors = &adj[vi];
496
497                if frame.neighbor_idx.as_usize() < neighbors.len() {
498                    let w = neighbors[frame.neighbor_idx.as_usize()];
499                    frame.neighbor_idx = bump(frame.neighbor_idx);
500                    let wi = w.to_usize();
501
502                    if node_index[wi] == undefined {
503                        // Not yet visited: push a new frame.
504                        node_index[wi] = index_counter;
505                        node_lowlink[wi] = index_counter;
506                        index_counter = bump(index_counter);
507                        on_stack[wi] = true;
508                        stack.push(w);
509                        call_stack.push(TarjanFrame {
510                            node: w,
511                            neighbor_idx: zero,
512                        });
513                    } else if on_stack[wi] {
514                        node_lowlink[vi] = node_lowlink[vi].min(node_index[wi]);
515                    }
516                } else {
517                    // All neighbors processed: check if this is a root.
518                    if node_lowlink[vi] == node_index[vi] {
519                        // Checked: one SCC per class at worst, but `SccOf<Cfg>` is its own
520                        // id family and nothing bounds it by the class count. Masking here
521                        // would merge two SCCs under one id, and `class_to_scc` feeds the
522                        // reachability bitsets — the damage reads as confident wrong AU
523                        // results, not an error.
524                        let scc_id = crate::id::id_at::<SccOf<Cfg>>(scc_members.len());
525                        let mut members = Vec::new();
526                        loop {
527                            let w = stack.pop().unwrap();
528                            on_stack[w.to_usize()] = false;
529                            class_to_scc[w.to_usize()] = scc_id;
530                            members.push(w);
531                            if w == v {
532                                break;
533                            }
534                        }
535                        scc_members.push(members);
536                    }
537                    // Pop and propagate lowlink to parent.
538                    let popped = call_stack.pop().unwrap();
539                    if let Some(parent) = call_stack.last() {
540                        let pi = parent.node.to_usize();
541                        node_lowlink[pi] =
542                            node_lowlink[pi].min(node_lowlink[popped.node.to_usize()]);
543                    }
544                }
545            }
546        }
547
548        let num_sccs = scc_members.len();
549
550        // --- Build SCC DAG adjacency (for reverse topological order) ---
551        let mut scc_adj: Vec<Vec<SccOf<Cfg>>> = vec![Vec::new(); num_sccs];
552        for (src_class, neighbors) in adj.iter().enumerate() {
553            let src_scc = class_to_scc[src_class];
554            for &dst_class in neighbors {
555                let dst_scc = class_to_scc[dst_class.to_usize()];
556                if src_scc != dst_scc {
557                    scc_adj[src_scc.to_usize()].push(dst_scc);
558                }
559            }
560        }
561        for neighbors in &mut scc_adj {
562            neighbors.sort_unstable();
563            neighbors.dedup();
564        }
565
566        // --- Reverse topological order via Kahn's algorithm ---
567        // In-degree in the condensed DAG: bounded by the SCC count, itself bounded by the
568        // class count, so this follows `Cfg::Index` for the same reason the Tarjan
569        // counters do. The increment is checked; a wrap here would drop an SCC from the
570        // topological order and leave its reachability bitset unfilled.
571        let mut in_degree: Vec<Cfg::Index> = vec![zero; num_sccs];
572        for neighbors in &scc_adj {
573            for &dst in neighbors {
574                in_degree[dst.to_usize()] = bump(in_degree[dst.to_usize()]);
575            }
576        }
577        let mut topo_order: Vec<SccOf<Cfg>> = Vec::with_capacity(num_sccs);
578        let mut queue: std::collections::VecDeque<SccOf<Cfg>> = std::collections::VecDeque::new();
579        // Each SCC id came from the checked mint above, so `num_sccs` is inside the id
580        // space and every position below it names one.
581        for (i, scc) in crate::id::ids_upto::<SccOf<Cfg>>(num_sccs).enumerate() {
582            if in_degree[i] == zero {
583                queue.push_back(scc);
584            }
585        }
586        while let Some(scc) = queue.pop_front() {
587            topo_order.push(scc);
588            for &dst in &scc_adj[scc.to_usize()] {
589                // Checked: Kahn's only decrements an in-degree it just accounted for by
590                // removing an edge, so it is positive here. An underflow would wrap to
591                // the top of the word and hang the drain instead of ever reaching zero.
592                in_degree[dst.to_usize()] =
593                    crate::containers::index_like::checked_decr(in_degree[dst.to_usize()])
594                        .expect("Kahn's decremented an in-degree already at zero");
595                if in_degree[dst.to_usize()] == zero {
596                    queue.push_back(dst);
597                }
598            }
599        }
600        // Reverse: leaves first (process in reverse topological = leaves before roots).
601        topo_order.reverse();
602
603        // --- Bitset union in reverse topological order ---
604        let mut bit_blocks: Vec<u64> = vec![0u64; num_sccs * words_per_scc];
605        let mut scc_spans: Vec<Span<<Cfg::Au as AuIds>::ReachBlock>> = Vec::with_capacity(num_sccs);
606        for i in 0..num_sccs {
607            scc_spans.push(Span::new(i * words_per_scc, words_per_scc));
608        }
609
610        // Process in reverse topological order (leaves first).
611        for &scc in &topo_order {
612            let si = scc.to_usize();
613
614            // If the SCC is cyclic (size > 1), add own members to reach set.
615            let is_cyclic = scc_members[si].len() > 1
616                || (scc_members[si].len() == 1 && {
617                    let c = scc_members[si][0];
618                    adj[c.to_usize()].contains(&c)
619                });
620
621            if is_cyclic {
622                for &member in &scc_members[si] {
623                    let bit = member.to_usize();
624                    let word = scc_spans[si].start_usize() + bit / 64;
625                    bit_blocks[word] |= 1u64 << (bit % 64);
626                }
627            }
628
629            // Add successor SCCs' classes to this SCC's bitset.
630            // First, add successor SCC members (the classes themselves).
631            for &dst_scc in &scc_adj[si] {
632                for &member in &scc_members[dst_scc.to_usize()] {
633                    let bit = member.to_usize();
634                    let word = scc_spans[si].start_usize() + bit / 64;
635                    bit_blocks[word] |= 1u64 << (bit % 64);
636                }
637            }
638
639            // Union successor SCCs' reach sets.
640            for &dst_scc in &scc_adj[si] {
641                let dst_start = scc_spans[dst_scc.to_usize()].start_usize();
642                let src_start = scc_spans[si].start_usize();
643                for w in 0..words_per_scc {
644                    bit_blocks[src_start + w] |= bit_blocks[dst_start + w];
645                }
646            }
647        }
648
649        // Unused variable suppression.
650        let _ = au_to_repr;
651
652        let scc_reach_count: Vec<u32> = scc_spans
653            .iter()
654            .map(|span| {
655                let start = span.start_usize();
656                bit_blocks[start..start + words_per_scc]
657                    .iter()
658                    .map(|w| w.count_ones())
659                    .sum()
660            })
661            .collect();
662
663        Reachability {
664            class_to_scc,
665            scc_spans,
666            bit_blocks,
667            scc_reach_count,
668            num_classes: num_classes as u64,
669        }
670    }
671}
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676    use crate::egraph::EGraph31;
677    use crate::literal::NiraLitVal;
678
679    /// Build a small e-graph with a cycle: f(x) where x = f(x) (via merge).
680    /// This creates a self-loop class, letting us test reachability on cycles.
681    #[test]
682    fn reachability_self_loop() {
683        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
684        let int = eg.intern_sort("Int");
685        let x_op = eg.register_op0("x", int);
686        let f_op = eg.register_op1("f", int, int);
687
688        let x = eg.add(x_op, &[]);
689        let fx = eg.add(f_op, &[x]);
690        // merge x and f(x): now class(x) = class(f(x)), creating a self-loop.
691        eg.merge(x, fx);
692        eg.rebuild();
693
694        let snap = AuSnapshot::new(&eg).unwrap();
695        let x_class = snap.class_of(x).unwrap();
696
697        // x's class reaches itself (self-loop via f).
698        assert!(snap.reachability().is_reachable(x_class, x_class));
699    }
700
701    /// Linear chain: a -> f(a) -> g(f(a)). No cycles. Reachability is transitive.
702    #[test]
703    fn reachability_linear_chain() {
704        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
705        let int = eg.intern_sort("Int");
706        let a_op = eg.register_op0("a", int);
707        let f_op = eg.register_op1("f", int, int);
708        let g_op = eg.register_op1("g", int, int);
709
710        let a = eg.add(a_op, &[]);
711        let fa = eg.add(f_op, &[a]);
712        let gfa = eg.add(g_op, &[fa]);
713        eg.rebuild();
714
715        let snap = AuSnapshot::new(&eg).unwrap();
716        let a_class = snap.class_of(a).unwrap();
717        let fa_class = snap.class_of(fa).unwrap();
718        let gfa_class = snap.class_of(gfa).unwrap();
719
720        // All 3 are different classes.
721        assert_ne!(a_class, fa_class);
722        assert_ne!(fa_class, gfa_class);
723
724        // gfa reaches fa and a.
725        assert!(snap.reachability().is_reachable(gfa_class, fa_class));
726        assert!(snap.reachability().is_reachable(gfa_class, a_class));
727
728        // fa reaches a.
729        assert!(snap.reachability().is_reachable(fa_class, a_class));
730
731        // a reaches nothing.
732        assert!(!snap.reachability().is_reachable(a_class, fa_class));
733        assert!(!snap.reachability().is_reachable(a_class, gfa_class));
734    }
735
736    /// Two-node cycle: x = f(y), y = g(x). Both reach each other.
737    #[test]
738    fn reachability_mutual_cycle() {
739        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
740        let int = eg.intern_sort("Int");
741        let x_op = eg.register_op0("x", int);
742        let y_op = eg.register_op0("y", int);
743        let f_op = eg.register_op1("f", int, int);
744        let g_op = eg.register_op1("g", int, int);
745
746        let x = eg.add(x_op, &[]);
747        let y = eg.add(y_op, &[]);
748        let fx = eg.add(f_op, &[y]); // f(y)
749        let gy = eg.add(g_op, &[x]); // g(x)
750
751        // merge: x = f(y), y = g(x)
752        eg.merge(x, fx);
753        eg.merge(y, gy);
754        eg.rebuild();
755
756        let snap = AuSnapshot::new(&eg).unwrap();
757        let x_class = snap.class_of(x).unwrap();
758        let y_class = snap.class_of(y).unwrap();
759
760        // x reaches y and y reaches x (mutual cycle).
761        assert!(snap.reachability().is_reachable(x_class, y_class));
762        assert!(snap.reachability().is_reachable(y_class, x_class));
763        // Both reach themselves.
764        assert!(snap.reachability().is_reachable(x_class, x_class));
765        assert!(snap.reachability().is_reachable(y_class, y_class));
766    }
767
768    /// Best-size computation: leaf costs 1, f(leaf) costs 2.
769    #[test]
770    fn best_size_basic() {
771        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
772        let int = eg.intern_sort("Int");
773        let a_op = eg.register_op0("a", int);
774        let f_op = eg.register_op1("f", int, int);
775
776        let a = eg.add(a_op, &[]);
777        let fa = eg.add(f_op, &[a]);
778        eg.rebuild();
779
780        let snap = AuSnapshot::new(&eg).unwrap();
781        let a_class = snap.class_of(a).unwrap();
782        let fa_class = snap.class_of(fa).unwrap();
783
784        assert_eq!(snap.best_size(a_class), 1);
785        assert_eq!(snap.best_size(fa_class), 2);
786    }
787
788    /// Best-size with AC multiplicities: plus(a, a) costs 1 + 2*1 = 3.
789    #[test]
790    fn best_size_ac_multiplicity() {
791        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
792        let int = eg.intern_sort("Int");
793        let a_op = eg.register_op0("a", int);
794        let plus_op = eg.register_mset("plus", int, int);
795
796        let a = eg.add(a_op, &[]);
797        let plus_aa = eg.add(plus_op, &[a, a]);
798        eg.rebuild();
799
800        let snap = AuSnapshot::new(&eg).unwrap();
801        let a_class = snap.class_of(a).unwrap();
802        let plus_class = snap.class_of(plus_aa).unwrap();
803
804        assert_eq!(snap.best_size(a_class), 1);
805        // plus(a^2): 1 + 2*1 = 3
806        assert_eq!(snap.best_size(plus_class), 3);
807    }
808
809    /// Members exclude FLAG_SUBSUMED nodes.
810    #[test]
811    fn members_exclude_subsumed() {
812        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
813        let int = eg.intern_sort("Int");
814        let a_op = eg.register_op0("a", int);
815        let b_op = eg.register_op0("b", int);
816
817        let a = eg.add(a_op, &[]);
818        let b = eg.add(b_op, &[]);
819        // merge a and b so they share a class, then subsume b.
820        eg.merge(a, b);
821        eg.rebuild();
822        eg.subsume(b);
823
824        let snap = AuSnapshot::new(&eg).unwrap();
825        let class = snap.class_of(a).unwrap();
826        let members = snap.members(class);
827
828        // One member should be excluded (the subsumed one).
829        assert_eq!(members.len(), 1);
830    }
831
832    /// Snapshot provides correct class count.
833    #[test]
834    fn num_classes_correct() {
835        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
836        let int = eg.intern_sort("Int");
837        let a_op = eg.register_op0("a", int);
838        let b_op = eg.register_op0("b", int);
839        let c_op = eg.register_op0("c", int);
840
841        let a = eg.add(a_op, &[]);
842        let b = eg.add(b_op, &[]);
843        let _c = eg.add(c_op, &[]);
844        eg.rebuild();
845        // 3 distinct classes.
846        let snap = AuSnapshot::new(&eg).unwrap();
847        assert_eq!(snap.num_classes(), 3);
848
849        // merge a and b -> 2 classes.
850        drop(snap);
851        eg.merge(a, b);
852        eg.rebuild();
853        let snap2 = AuSnapshot::new(&eg).unwrap();
854        assert_eq!(snap2.num_classes(), 2);
855    }
856}