Skip to main content

semi_persistent_egraph/
node_types.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Generic node types for the e-graph node stores.
4//!
5//! Three structs cover all ten node kinds:
6//! - `FixedArityNode<G, O, K>` — Plain0/1/2/3 and Commutative
7//! - `VariableArityNode<G, O>` — PlainN, A, AC, ACI
8//! - `LitNode<G, O, V>` — literal leaves
9//!
10//! `global_id` and `op` are stored as `Repr` types so the tag bits
11//! can be manipulated directly via `Tagged` without unsafe casts.
12//! `global_id` MSB = VecI capture tag, `op` MSB = has_history flag.
13//! `flags` is a per-node u8 bitfield for control bits (subsumption, etc).
14
15use std::hash::{Hash, Hasher};
16
17use crate::containers::DenseId;
18use crate::containers::Tagged;
19
20/// Per-node control flags stored in the `flags` field.
21///
22/// `FLAG_SUBSUMED` and `FLAG_AC_COLLAPSED` are deliberately distinct concepts (see
23/// `doc/design/ac-congruence-completeness.md` §6b):
24/// - `FLAG_SUBSUMED` — user-level `(subsume …)`: "do not *match* this node." The
25///   matcher's indices skip it.
26/// - `FLAG_AC_COLLAPSED` — AC completion's inter-reduction: "do not use this node as a
27///   completion *rule*" (its child multiset is reducible by a smaller AC rule, so every
28///   superposition off it is redundant). The node stays fully **matchable** — its
29///   reduced form is in the same class — and stays a legal child of other nodes; only
30///   AC completion's active rule set excludes it.
31///
32/// A node may carry either, both, or neither. Completion's active set is the AC nodes
33/// with *neither* flag; the matcher's visible set is the nodes without `FLAG_SUBSUMED`.
34pub const FLAG_SUBSUMED: u8 = 1 << 0;
35pub const FLAG_CONSTRUCTOR: u8 = 1 << 1;
36pub const FLAG_AC_COLLAPSED: u8 = 1 << 2;
37
38// ---------------------------------------------------------------------------
39// FixedArityNode<G, O, K>
40// ---------------------------------------------------------------------------
41
42#[derive(Clone, Copy, Debug)]
43pub struct FixedArityNode<G: DenseId, O: DenseId, const K: usize> {
44    pub global_id: G::Repr,
45    pub op: O::Repr,
46    pub flags: u8,
47    pub children: [G; K],
48}
49
50// Filler for `resize_default` during restore; never observed (overwritten by
51// the captured diff value). Routes id values through `new`/`into_repr` rather
52// than fabricating a raw `Repr`, so the stolen niche bit is cleared.
53impl<G: DenseId, O: DenseId, const K: usize> Default for FixedArityNode<G, O, K> {
54    fn default() -> Self {
55        Self::new(G::default(), O::default(), [G::default(); K])
56    }
57}
58
59impl<G: DenseId, O: DenseId, const K: usize> FixedArityNode<G, O, K> {
60    #[inline]
61    pub fn new(global_id: G, op: O, children: [G; K]) -> Self {
62        Self {
63            global_id: global_id.into_repr(),
64            op: op.into_repr(),
65            flags: 0,
66            children,
67        }
68    }
69
70    #[inline]
71    pub fn global_id(&self) -> G {
72        G::from_repr(&self.global_id)
73    }
74
75    #[inline]
76    pub fn op(&self) -> O {
77        O::from_repr(&self.op)
78    }
79
80    #[inline]
81    pub fn has_history(&self) -> bool {
82        O::tag(&self.op)
83    }
84
85    #[inline]
86    pub fn set_history(&mut self) {
87        O::set_tag(&mut self.op);
88    }
89
90    #[inline]
91    pub fn content_hash(&self) -> u64
92    where
93        O: Hash,
94        G: Hash,
95    {
96        let mut h = rapidhash::fast::RapidHasher::default();
97        self.op().hash(&mut h);
98        self.children.hash(&mut h);
99        h.finish()
100    }
101
102    #[inline]
103    pub fn content_eq(&self, other: &Self) -> bool
104    where
105        O: PartialEq,
106        G: PartialEq,
107    {
108        self.op() == other.op() && self.children == other.children
109    }
110}
111
112impl<G: DenseId, O: DenseId, const K: usize> Tagged for FixedArityNode<G, O, K> {
113    type Repr = Self;
114    #[inline(always)]
115    fn into_repr(self) -> Self {
116        self
117    }
118    #[inline(always)]
119    fn from_repr(stored: &Self) -> Self {
120        let mut v = *stored;
121        G::clear_tag(&mut v.global_id);
122        O::clear_tag(&mut v.op);
123        v
124    }
125    #[inline(always)]
126    fn tag(stored: &Self) -> bool {
127        G::tag(&stored.global_id)
128    }
129    #[inline(always)]
130    fn set_tag(stored: &mut Self) {
131        G::set_tag(&mut stored.global_id);
132    }
133    #[inline(always)]
134    fn clear_tag(stored: &mut Self) {
135        G::clear_tag(&mut stored.global_id);
136    }
137}
138
139// ---------------------------------------------------------------------------
140// VariableArityNode<G, O>
141// ---------------------------------------------------------------------------
142
143/// A node whose children live in a shared side pool, addressed by a `[start, end)` span.
144///
145/// `start`/`end` stay `usize` **deliberately**, and this is the one place in the store where
146/// that is the right answer rather than an unfixed hardcoding. Everywhere else a stored index
147/// drops to the id family's `Index` word, because what it addresses is one-per-id and so its
148/// population is bounded by the id capacity — [`ClassData::min_row`] is the pattern: one pool
149/// row per class, so a row number cannot outgrow `T::Index`.
150///
151/// The child pool has no such bound. Its length is the *sum of arities* over every
152/// variable-arity node, which no single population bounds: `G::Index` bounds the node count,
153/// and nothing at all bounds the per-node arity. Narrowing these two words to `G::Index`
154/// would therefore not track a width — it would install a fresh capacity cap at
155/// `G::Index::MAX` children *in total*, reachable at the 31-bit config with a few large AC
156/// terms, reintroducing the capacity cap this representation avoids. Pointer
157/// width is the honest width for an offset into a pool whose population is `Σ arity`.
158///
159/// The size is asserted below, so this choice is priced rather than assumed: two `usize`
160/// words are what put the node at 32 bytes.
161///
162/// [`ClassData::min_row`]: crate::classes::ClassData::min_row
163#[derive(Clone, Copy, Debug)]
164pub struct VariableArityNode<G: DenseId, O: DenseId> {
165    pub global_id: G::Repr,
166    pub op: O::Repr,
167    /// Inclusive start of this node's span in the child pool. `usize`, not `G::Index` — see
168    /// the type doc: the pool's population is `Σ arity`, which the id capacity does not bound.
169    pub start: usize,
170    /// Exclusive end of this node's span in the child pool. `usize` for the same reason as
171    /// [`start`](Self::start).
172    pub end: usize,
173    pub flags: u8,
174}
175
176// Filler for `resize_default` during restore; never observed. Routes ids
177// through `make`/`into_repr` so the niche bit is cleared (no raw-Repr fabric).
178impl<G: DenseId, O: DenseId> Default for VariableArityNode<G, O> {
179    fn default() -> Self {
180        Self::make(G::default(), O::default(), 0, 0)
181    }
182}
183
184impl<G: DenseId, O: DenseId> VariableArityNode<G, O> {
185    #[inline]
186    pub fn make(global_id: G, op: O, start: usize, end: usize) -> Self {
187        Self {
188            global_id: global_id.into_repr(),
189            op: op.into_repr(),
190            start,
191            end,
192            flags: 0,
193        }
194    }
195
196    #[inline]
197    pub fn global_id(&self) -> G {
198        G::from_repr(&self.global_id)
199    }
200
201    #[inline]
202    pub fn op(&self) -> O {
203        O::from_repr(&self.op)
204    }
205
206    #[inline]
207    pub fn has_history(&self) -> bool {
208        O::tag(&self.op)
209    }
210
211    #[inline]
212    pub fn set_history(&mut self) {
213        O::set_tag(&mut self.op);
214    }
215
216    #[inline]
217    pub fn span(&self) -> (usize, usize) {
218        (self.start, self.end)
219    }
220
221    #[inline]
222    pub fn with_end(self, new_end: usize) -> Self {
223        Self {
224            end: new_end,
225            ..self
226        }
227    }
228}
229
230impl<G: DenseId, O: DenseId> Tagged for VariableArityNode<G, O> {
231    type Repr = Self;
232    #[inline(always)]
233    fn into_repr(self) -> Self {
234        self
235    }
236    #[inline(always)]
237    fn from_repr(stored: &Self) -> Self {
238        let mut v = *stored;
239        G::clear_tag(&mut v.global_id);
240        O::clear_tag(&mut v.op);
241        v
242    }
243    #[inline(always)]
244    fn tag(stored: &Self) -> bool {
245        G::tag(&stored.global_id)
246    }
247    #[inline(always)]
248    fn set_tag(stored: &mut Self) {
249        G::set_tag(&mut stored.global_id);
250    }
251    #[inline(always)]
252    fn clear_tag(stored: &mut Self) {
253        G::clear_tag(&mut stored.global_id);
254    }
255}
256
257// ---------------------------------------------------------------------------
258// LitNode<G, O, V>
259// ---------------------------------------------------------------------------
260
261#[derive(Clone, Copy, Debug)]
262pub struct LitNode<G: DenseId, O: DenseId, V: DenseId> {
263    pub global_id: G::Repr,
264    pub op: O::Repr,
265    pub flags: u8,
266    pub lit: V,
267}
268
269// Filler for `resize_default` during restore; never observed. Routes ids
270// through `new`/`into_repr` so the niche bit is cleared (no raw-Repr fabric).
271impl<G: DenseId, O: DenseId, V: DenseId> Default for LitNode<G, O, V> {
272    fn default() -> Self {
273        Self::new(G::default(), O::default(), V::default())
274    }
275}
276
277impl<G: DenseId, O: DenseId, V: DenseId> LitNode<G, O, V> {
278    #[inline]
279    pub fn new(global_id: G, op: O, lit: V) -> Self {
280        Self {
281            global_id: global_id.into_repr(),
282            op: op.into_repr(),
283            flags: 0,
284            lit,
285        }
286    }
287
288    #[inline]
289    pub fn global_id(&self) -> G {
290        G::from_repr(&self.global_id)
291    }
292
293    #[inline]
294    pub fn op(&self) -> O {
295        O::from_repr(&self.op)
296    }
297
298    #[inline]
299    pub fn has_history(&self) -> bool {
300        O::tag(&self.op)
301    }
302
303    #[inline]
304    pub fn set_history(&mut self) {
305        O::set_tag(&mut self.op);
306    }
307
308    #[inline]
309    pub fn content_hash(&self) -> u64
310    where
311        O: Hash,
312        V: Hash,
313    {
314        let mut h = rapidhash::fast::RapidHasher::default();
315        self.op().hash(&mut h);
316        self.lit.hash(&mut h);
317        h.finish()
318    }
319
320    #[inline]
321    pub fn content_eq(&self, other: &Self) -> bool
322    where
323        O: PartialEq,
324        V: PartialEq,
325    {
326        self.op() == other.op() && self.lit == other.lit
327    }
328}
329
330impl<G: DenseId, O: DenseId, V: DenseId> Tagged for LitNode<G, O, V> {
331    type Repr = Self;
332    #[inline(always)]
333    fn into_repr(self) -> Self {
334        self
335    }
336    #[inline(always)]
337    fn from_repr(stored: &Self) -> Self {
338        let mut v = *stored;
339        G::clear_tag(&mut v.global_id);
340        O::clear_tag(&mut v.op);
341        v
342    }
343    #[inline(always)]
344    fn tag(stored: &Self) -> bool {
345        G::tag(&stored.global_id)
346    }
347    #[inline(always)]
348    fn set_tag(stored: &mut Self) {
349        G::set_tag(&mut stored.global_id);
350    }
351    #[inline(always)]
352    fn clear_tag(stored: &mut Self) {
353        G::clear_tag(&mut stored.global_id);
354    }
355}
356
357// ---------------------------------------------------------------------------
358// Tests
359// ---------------------------------------------------------------------------
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use crate::id::{ENodeId, OpId};
365    use crate::nodes::LitValId;
366
367    #[test]
368    fn fixed_arity_sizes() {
369        use std::mem::size_of;
370        // +4 bytes vs no-flags: u8 flags rounds up to u32 alignment
371        assert_eq!(size_of::<FixedArityNode<ENodeId, OpId, 0>>(), 12);
372        assert_eq!(size_of::<FixedArityNode<ENodeId, OpId, 1>>(), 16);
373        assert_eq!(size_of::<FixedArityNode<ENodeId, OpId, 2>>(), 20);
374        assert_eq!(size_of::<FixedArityNode<ENodeId, OpId, 3>>(), 24);
375    }
376
377    #[test]
378    fn variable_arity_size() {
379        use std::mem::size_of;
380        // +8 bytes vs no-flags: u8 flags rounds up to usize alignment
381        assert_eq!(size_of::<VariableArityNode<ENodeId, OpId>>(), 32);
382    }
383
384    #[test]
385    fn lit_node_size() {
386        use std::mem::size_of;
387        assert_eq!(size_of::<LitNode<ENodeId, OpId, LitValId>>(), 16);
388    }
389
390    #[test]
391    fn tagged_roundtrip() {
392        type N = FixedArityNode<ENodeId, OpId, 2>;
393        let node = N::new(
394            ENodeId::new(42),
395            OpId::new(5),
396            [ENodeId::new(1), ENodeId::new(2)],
397        );
398        let mut stored = node.into_repr();
399        assert!(!N::tag(&stored));
400
401        N::set_tag(&mut stored);
402        assert!(N::tag(&stored));
403
404        let clean = N::from_repr(&stored);
405        assert_eq!(clean.global_id(), ENodeId::new(42));
406        assert_eq!(clean.op(), OpId::new(5));
407        assert_eq!(clean.children, [ENodeId::new(1), ENodeId::new(2)]);
408        assert!(!clean.has_history());
409    }
410
411    #[test]
412    fn history_flag() {
413        let mut node = FixedArityNode::<ENodeId, OpId, 1>::new(
414            ENodeId::new(10),
415            OpId::new(3),
416            [ENodeId::new(7)],
417        );
418        assert!(!node.has_history());
419        node.set_history();
420        assert!(node.has_history());
421        assert_eq!(node.op(), OpId::new(3));
422    }
423
424    #[test]
425    fn content_eq_ignores_global_id() {
426        let a = FixedArityNode::<ENodeId, OpId, 0>::new(ENodeId::new(0), OpId::new(1), []);
427        let b = FixedArityNode::<ENodeId, OpId, 0>::new(ENodeId::new(99), OpId::new(1), []);
428        assert!(a.content_eq(&b));
429    }
430
431    #[test]
432    fn history_flag_independent_of_capture() {
433        type N = FixedArityNode<ENodeId, OpId, 1>;
434        let mut node = N::new(ENodeId::new(10), OpId::new(3), [ENodeId::new(7)]);
435        node.set_history();
436        let mut stored = node;
437        N::set_tag(&mut stored); // set capture tag on global_id MSB
438
439        // Both flags set in stored repr
440        assert!(stored.has_history()); // op MSB
441        assert!(N::tag(&stored)); // global_id MSB
442
443        // from_repr clears capture tag but op tag is also cleared (both use MSB)
444        // The clean node has neither flag — that's correct.
445        // In practice, has_history is only read on raw stored values from VecI::get.
446        let clean = N::from_repr(&stored);
447        assert_eq!(clean.op(), OpId::new(3));
448        assert_eq!(clean.global_id(), ENodeId::new(10));
449        assert_eq!(clean.children, [ENodeId::new(7)]);
450    }
451
452    // prod-parity: production exposed `ENodeId::from_raw_unchecked` to fabricate
453    // an id with the stolen MSB set, then asserted `Eq`/`Ord`/`Hash` masked that
454    // bit off ("MSB-oblivious"). The verified crate takes a different, stronger
455    // route: a clean id carries a `#[verifier::type_invariant]` that the MSB is
456    // ALWAYS clear, so a dirty id cannot be constructed at all — there is no
457    // `from_raw_unchecked`, and the masking the test checked is unnecessary
458    // because the case it guards against is unrepresentable. The residual
459    // property (equal clean ids compare/ hash equal) is what remains testable.
460    #[test]
461    fn dense_id_clean_ids_compare_and_hash_by_value() {
462        let a = ENodeId::new(42);
463        let b = ENodeId::new(42);
464        assert_eq!(a, b);
465        assert_eq!(a.cmp(&b), core::cmp::Ordering::Equal);
466
467        use core::hash::{Hash, Hasher};
468        let hash = |v: ENodeId| {
469            let mut h = std::collections::hash_map::DefaultHasher::new();
470            v.hash(&mut h);
471            h.finish()
472        };
473        assert_eq!(hash(a), hash(b));
474    }
475}