Skip to main content

semi_persistent_egraph/
multiplicity.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Multiplicities for AC multiset nodes.
4//!
5//! The multiplicity width is selected by [`crate::config::EGraphConfig::M`] and is an axis
6//! *independent* of the id width: a 63-bit e-graph does not oblige a 64-bit
7//! multiplicity, and a 31-bit e-graph may still want one. Three widths are
8//! provided — [`Multiplicity16`], [`Multiplicity`], [`Multiplicity64`] — all
9//! implementing [`MultiplicityLike`].
10//!
11//! ## Why the width is a parameter rather than a fixed `u32`
12//!
13//! A multiplicity counts occurrences of one child within one AC node, so its
14//! domain is that node's child count. `EGraph::for_each_child`'s own safety cap
15//! (`1 + 64 * node_count()`) puts that at 64·N — already 2^37 for a 31-bit
16//! e-graph, i.e. wider than `u32`. The previous contract additionally required
17//! `From<u32> + Into<u32>`, which made any width above 32 bits *unimplementable*
18//! because every generic read went through a lossy `u32`.
19//!
20//! ## Conversions are checked in both directions
21//!
22//! Surface multiplicity literals are parsed as `u64` and stay `u64` through
23//! resolution ([`crate::resolve::ResolvedMultExpr::Lit`]); they are narrowed to
24//! the configured width only at `Cfg`-generic use sites, via
25//! [`MultiplicityLike::try_from_u64`]. Narrowing with an unchecked `as` is what
26//! made `x:4294967297` match multiplicity 1 and `(mult x 4294967296)` emit zero
27//! copies. Summation goes through [`MultiplicityLike::checked_add`] so a wrap
28//! cannot silently produce a multiplicity of 0, which would violate the
29//! positivity invariant the multiset module asserts.
30
31use core::hash::Hash;
32
33/// A multiplicity width: a count of occurrences within one AC multiset node.
34///
35/// Implementors are newtypes over an unsigned primitive. Every supported width
36/// fits in `u64`, so [`Self::to_u64`] is total and lossless; the reverse
37/// direction is fallible.
38pub trait MultiplicityLike:
39    Copy + Clone + Eq + Ord + Hash + core::fmt::Debug + core::fmt::Display + Default
40{
41    /// Multiplicity zero. Not a legal stored multiplicity — the multiset
42    /// representation is duplicate-free with every entry `>= ONE` — but needed
43    /// as the identity for summation and as an "unbound" marker.
44    const ZERO: Self;
45    /// Multiplicity one: a child occurring exactly once.
46    const ONE: Self;
47    /// Largest representable multiplicity in this width.
48    const MAX: Self;
49
50    /// Widen to the surface width. Total and lossless.
51    fn to_u64(self) -> u64;
52
53    /// Narrow from the surface width, or `None` if `n` exceeds [`Self::MAX`].
54    fn try_from_u64(n: u64) -> Option<Self>;
55
56    /// Sum, or `None` on overflow of this width.
57    fn checked_add(self, other: Self) -> Option<Self>;
58
59    /// Difference, clamped at [`Self::ZERO`].
60    fn saturating_sub(self, other: Self) -> Self;
61
62    /// Reduce modulo a small algebraic order: the nilpotent count clamp
63    /// (`x∘x∘…∘x = e` after `order` copies) and self-inverse cancellation
64    /// (`order = 2`).
65    ///
66    /// Total at every width: the result is below `order`, hence below 256, which
67    /// even the narrowest supported width represents. Panics on `order == 0`,
68    /// like the `%` it stands for — no algebraic order is zero.
69    fn rem_order(self, order: u8) -> Self {
70        Self::try_from_u64(self.to_u64() % u64::from(order))
71            .expect("a remainder mod a u8 is below 256 and fits every supported width")
72    }
73
74    /// Widen to `usize` for cost/size arithmetic. Saturates rather than
75    /// truncating, which matters only for a 64-bit multiplicity on a 32-bit
76    /// target — a configuration this crate does not otherwise support.
77    fn to_usize(self) -> usize {
78        usize::try_from(self.to_u64()).unwrap_or(usize::MAX)
79    }
80}
81
82macro_rules! define_multiplicity {
83    ($name:ident, $w:ty, $bits:literal) => {
84        #[doc = concat!("AC multiplicity backed by `", stringify!($w), "` (", $bits, " bits).")]
85        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
86        #[repr(transparent)]
87        pub struct $name(pub $w);
88
89        impl From<$w> for $name {
90            fn from(v: $w) -> Self {
91                Self(v)
92            }
93        }
94        impl From<$name> for $w {
95            fn from(m: $name) -> Self {
96                m.0
97            }
98        }
99        impl core::fmt::Display for $name {
100            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
101                write!(f, "{}", self.0)
102            }
103        }
104        impl MultiplicityLike for $name {
105            const ZERO: Self = Self(0);
106            const ONE: Self = Self(1);
107            const MAX: Self = Self(<$w>::MAX);
108
109            #[inline]
110            fn to_u64(self) -> u64 {
111                u64::from(self.0)
112            }
113            #[inline]
114            fn try_from_u64(n: u64) -> Option<Self> {
115                <$w>::try_from(n).ok().map(Self)
116            }
117            #[inline]
118            fn checked_add(self, other: Self) -> Option<Self> {
119                self.0.checked_add(other.0).map(Self)
120            }
121            #[inline]
122            fn saturating_sub(self, other: Self) -> Self {
123                Self(self.0.saturating_sub(other.0))
124            }
125        }
126    };
127}
128
129define_multiplicity!(Multiplicity16, u16, "16");
130define_multiplicity!(Multiplicity, u32, "32");
131define_multiplicity!(Multiplicity64, u64, "64");
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    /// Narrowing from the surface width rejects what it cannot represent
138    /// instead of truncating. These are the exact values that used to alias:
139    /// `2^32 + 1` truncated to 1, and `2^32` truncated to 0.
140    #[test]
141    fn try_from_u64_rejects_out_of_range() {
142        assert_eq!(Multiplicity::try_from_u64(4_294_967_297), None);
143        assert_eq!(Multiplicity::try_from_u64(4_294_967_296), None);
144        assert_eq!(
145            Multiplicity::try_from_u64(4_294_967_295),
146            Some(Multiplicity(u32::MAX))
147        );
148        assert_eq!(Multiplicity16::try_from_u64(65_536), None);
149        assert_eq!(
150            Multiplicity16::try_from_u64(65_535),
151            Some(Multiplicity16(u16::MAX))
152        );
153        // The widest configuration accepts the whole surface range.
154        assert_eq!(
155            Multiplicity64::try_from_u64(u64::MAX),
156            Some(Multiplicity64(u64::MAX))
157        );
158    }
159
160    /// `to_u64` round-trips every value the width can hold, so comparing a
161    /// stored multiplicity against a surface literal is exact.
162    #[test]
163    fn to_u64_round_trips() {
164        for m in [Multiplicity::ZERO, Multiplicity::ONE, Multiplicity::MAX] {
165            assert_eq!(Multiplicity::try_from_u64(m.to_u64()), Some(m));
166        }
167        assert_eq!(Multiplicity16::MAX.to_u64(), 65_535);
168        assert_eq!(Multiplicity64::MAX.to_u64(), u64::MAX);
169    }
170
171    /// Summation reports overflow rather than wrapping to a small (or zero)
172    /// multiplicity, which would violate the multiset positivity invariant.
173    #[test]
174    fn checked_add_detects_overflow_at_each_width() {
175        assert_eq!(
176            Multiplicity16::MAX.checked_add(Multiplicity16::ONE),
177            None,
178            "u16 multiplicity must report overflow, not wrap to 0"
179        );
180        assert_eq!(Multiplicity::MAX.checked_add(Multiplicity::ONE), None);
181        assert_eq!(Multiplicity64::MAX.checked_add(Multiplicity64::ONE), None);
182        assert_eq!(
183            Multiplicity::ONE.checked_add(Multiplicity::ONE),
184            Some(Multiplicity(2))
185        );
186        // The narrower width overflows where the wider one does not.
187        let n = u64::from(u16::MAX);
188        assert_eq!(
189            Multiplicity16::try_from_u64(n)
190                .unwrap()
191                .checked_add(Multiplicity16::ONE),
192            None
193        );
194        assert_eq!(
195            Multiplicity::try_from_u64(n)
196                .unwrap()
197                .checked_add(Multiplicity::ONE),
198            Some(Multiplicity(65_536))
199        );
200    }
201
202    /// Subtraction clamps, matching `multiset_subtract_into`'s behaviour.
203    #[test]
204    fn saturating_sub_clamps_at_zero() {
205        assert_eq!(
206            Multiplicity::ONE.saturating_sub(Multiplicity(5)),
207            Multiplicity::ZERO
208        );
209        assert_eq!(
210            Multiplicity(5).saturating_sub(Multiplicity(2)),
211            Multiplicity(3)
212        );
213    }
214
215    /// The stored representation is exactly the backing primitive, so making
216    /// the width a parameter costs nothing per AC child.
217    #[test]
218    fn representation_is_the_backing_primitive() {
219        assert_eq!(size_of::<Multiplicity16>(), size_of::<u16>());
220        assert_eq!(size_of::<Multiplicity>(), size_of::<u32>());
221        assert_eq!(size_of::<Multiplicity64>(), size_of::<u64>());
222    }
223}