Skip to main content

semi_persistent_egraph/
id.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Concrete e-graph identifier types.
4
5pub use semi_persistent_containers::{SparseSetId, UseListId, UseNodeId};
6
7semi_persistent_containers::define_id31! {
8    /// A 31-bit e-node identifier.
9    pub struct ENodeId / StoredENodeId, "e";
10}
11
12semi_persistent_containers::define_id31! {
13    /// A 31-bit recycled key into the packed e-class data store.
14    pub struct EClassKey / StoredEClassKey, "ec";
15}
16
17semi_persistent_containers::define_id31! {
18    /// A 31-bit sort identifier (Bool, Int, Real, …).
19    pub struct SortId / StoredSortId, "sort";
20}
21
22semi_persistent_containers::define_id31! {
23    /// A 31-bit operator identifier (+, ×, and, or, =, ite, …).
24    pub struct OpId / StoredOpId, "op";
25}
26
27semi_persistent_containers::define_id15! {
28    /// A 15-bit rule identifier (indexes into the rule registry).
29    pub struct RuleId / StoredRuleId, "r";
30}
31
32semi_persistent_containers::define_id15! {
33    /// A 15-bit axiom identifier (user-asserted equalities).
34    pub struct AxiomId / StoredAxiomId, "ax";
35}
36
37/// Mint the dense id for an arena or log position, checked.
38///
39/// Use this wherever an id is derived from a container position. A position and its
40/// id share a word (`D::Index`) but NOT a range: a bit-stealing id reserves the top
41/// bit, so `D::Index` spans twice the id space and a position at or past
42/// `D::id_bound()` has no id at all. `DenseId::from_usize` rejects such a
43/// position; this helper centralizes the fallible check and the e-graph-specific
44/// exhaustion message before any owning structure is mutated.
45///
46/// These cases are reachable in practice: [`RuleId`] and [`AxiomId`] are 15-bit,
47/// so the 32769th registered rule has no representable ID.
48#[inline]
49pub fn id_at<D: crate::containers::DenseId>(pos: usize) -> D {
50    D::try_new(pos).unwrap_or_else(|| panic!("position {pos} has no id: the id space is exhausted"))
51}
52
53/// [`id_at`] for a position already in the container's index word.
54#[inline]
55pub fn id_at_index<D: crate::containers::DenseId>(pos: D::Index) -> D {
56    use crate::containers::IndexLike;
57    id_at(pos.as_usize())
58}
59
60/// The ids for positions `0..n`, with the bound checked once.
61///
62/// The loop form of [`id_at`]. Scanning a population by position needs one check, not
63/// one per step: positions are contiguous, so only the last can be out of range. This
64/// panics before yielding anything rather than producing a valid prefix and then
65/// failing partway through a long scan.
66///
67/// Use this when the caller cannot show `n` is within the id space. When it can — most
68/// often because the container is indexed *by* `D`, so its own capacity guard is the id
69/// bound — the bare `DenseId::from_usize` is correct and the reason belongs in a
70/// comment at the loop.
71#[inline]
72pub fn ids_upto<D: crate::containers::DenseId>(n: usize) -> impl Iterator<Item = D> {
73    if n > 0 {
74        let _ = id_at::<D>(n - 1);
75    }
76    (0..n).map(D::from_usize)
77}
78
79/// The ten node kinds. Stored in a routing table indexed by [`ENodeId`].
80#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
81#[repr(u8)]
82pub enum ENodeKind {
83    /// Nullary (constant, no children).
84    Plain0 = 0,
85    /// Unary (1 inline child).
86    Plain1 = 1,
87    /// Binary (2 inline children).
88    Plain2 = 2,
89    /// Ternary (3 inline children).
90    Plain3 = 3,
91    /// N-ary ordered (N > 3, children in pool).
92    PlainN = 4,
93    /// Commutative sorted pair (2 inline children).
94    SPair = 5,
95    /// Associative flattened list (variadic, pool).
96    Seq = 6,
97    /// Associative-commutative sorted multiset (variadic, pool). Multiset child
98    /// representation `(G, mult)`; the AC algebra in Kapur's AC-CC terms. Stores plain AC
99    /// (`Clamp::None`) AND nilpotent (`Clamp::Nilpotent`) ops — nilpotent keeps true
100    /// multiplicities here for the build/recanonize mod-n reduction (a `Set` dedup would
101    /// destroy them). The op's `Clamp` (on `OpKind`) says which.
102    MSet = 7,
103    /// Associative-commutative-idempotent sorted set (variadic, pool). Set child
104    /// representation (bare `G`, {0,1} counts). Idempotent ops only (`Clamp::Idempotent`):
105    /// dedup is the sound build/recanonize canonize rule for them. Nilpotent ops do NOT
106    /// live here (see `MSet`).
107    Set = 8,
108    /// Literal leaf (no children, has value).
109    Lit = 9,
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use crate::containers::DenseId;
116
117    /// `id_at` accepts exactly the positions that have an id. `RuleId` is 15-bit, so
118    /// the boundary is reachable in a test — see `registry::tests` for the registry
119    /// path that used to alias across it.
120    #[test]
121    fn id_at_covers_the_whole_id_space() {
122        let bound = 1usize << 15; // RuleId is define_id15!
123        assert_eq!(id_at::<RuleId>(0).to_usize(), 0);
124        assert_eq!(id_at::<RuleId>(bound - 1).to_usize(), bound - 1);
125    }
126
127    #[test]
128    #[should_panic(expected = "the id space is exhausted")]
129    fn id_at_rejects_a_position_with_no_id() {
130        // Representable as a `u16` index word, but past `RuleId`'s 15-bit bound.
131        let _ = id_at::<RuleId>(1usize << 15);
132    }
133
134    /// `id_at_index` is the same check, entered from a container's index word.
135    #[test]
136    fn id_at_index_agrees_with_id_at() {
137        let pos: <RuleId as DenseId>::Index = 7;
138        assert_eq!(id_at_index::<RuleId>(pos), id_at::<RuleId>(7));
139    }
140
141    #[test]
142    #[should_panic(expected = "the id space is exhausted")]
143    fn id_at_index_rejects_a_position_with_no_id() {
144        let pos: <RuleId as DenseId>::Index = 1u16 << 15;
145        let _ = id_at_index::<RuleId>(pos);
146    }
147
148    #[test]
149    fn ids_upto_yields_every_position_in_order() {
150        let ids: Vec<usize> = ids_upto::<RuleId>(4).map(|r| r.to_usize()).collect();
151        assert_eq!(ids, vec![0, 1, 2, 3]);
152        assert_eq!(ids_upto::<RuleId>(0).count(), 0);
153    }
154
155    /// The whole id space scans, so the check is on the last position and not one past it.
156    #[test]
157    fn ids_upto_accepts_a_full_id_space() {
158        let bound = 1usize << 15;
159        assert_eq!(ids_upto::<RuleId>(bound).count(), bound);
160    }
161
162    /// The panic lands before the first item, not partway through: an iterator that
163    /// yielded 32768 good ids and then aliased would corrupt whatever it fed.
164    #[test]
165    #[should_panic(expected = "the id space is exhausted")]
166    fn ids_upto_rejects_a_population_larger_than_the_id_space() {
167        let _ = ids_upto::<RuleId>((1usize << 15) + 1);
168    }
169}