use crate::canon::{MSetCanon, VarCanon};
use crate::config::EGraphConfig;
use crate::containers::{DenseId, IndexLike};
use crate::egraph::EGraph;
use crate::literal::LitVal;
use semi_persistent_containers::{DenseSpanMap, SpanArena};
use std::collections::HashMap;
pub type FastMap<K, V> = HashMap<K, V, foldhash::fast::RandomState>;
pub use semi_persistent_containers::SortedVecCursor;
#[derive(Clone, Debug)]
pub struct FanOuts<O> {
pub by_repr: f64,
pub by_child_pos_skew: FastMap<(O, usize), f64>,
pub by_contains_skew: FastMap<O, f64>,
pub by_child_pos: FastMap<(O, usize), f64>,
pub by_contains: FastMap<O, f64>,
pub nodes: usize,
}
impl<O> Default for FanOuts<O> {
fn default() -> Self {
Self {
by_repr: 1.0,
by_child_pos_skew: FastMap::default(),
by_contains_skew: FastMap::default(),
by_child_pos: FastMap::default(),
by_contains: FastMap::default(),
nodes: 0,
}
}
}
pub struct IndexScratch<Cfg: EGraphConfig> {
by_op: Vec<(usize, Cfg::G)>,
by_repr: Vec<(usize, Cfg::G)>,
by_child_pos: Vec<(usize, Cfg::G)>,
by_contains: Vec<(usize, Cfg::G)>,
seen: Vec<Cfg::G>,
arenas_full: [Option<SpanArena>; 4],
arenas_delta: [Option<SpanArena>; 4],
}
pub(crate) const FAM_OP: usize = 0;
pub(crate) const FAM_REPR: usize = 1;
pub(crate) const FAM_CHILD_POS: usize = 2;
pub(crate) const FAM_CONTAINS: usize = 3;
impl<Cfg: EGraphConfig> Default for IndexScratch<Cfg> {
fn default() -> Self {
Self::new()
}
}
impl<Cfg: EGraphConfig> IndexScratch<Cfg> {
pub fn new() -> Self {
Self {
by_op: Vec::new(),
by_repr: Vec::new(),
by_child_pos: Vec::new(),
by_contains: Vec::new(),
seen: Vec::new(),
arenas_full: [None, None, None, None],
arenas_delta: [None, None, None, None],
}
}
fn clear(&mut self) {
self.by_op.clear();
self.by_repr.clear();
self.by_child_pos.clear();
self.by_contains.clear();
self.seen.clear();
}
fn take_arena(&mut self, full: bool, fam: usize) -> SpanArena {
let slot = if full {
&mut self.arenas_full[fam]
} else {
&mut self.arenas_delta[fam]
};
slot.take().unwrap_or_default()
}
fn put_arena(&mut self, full: bool, fam: usize, arena: SpanArena) {
let slot = if full {
&mut self.arenas_full[fam]
} else {
&mut self.arenas_delta[fam]
};
*slot = Some(arena);
}
pub fn arena_capacity(&self) -> usize {
self.arenas_full
.iter()
.chain(self.arenas_delta.iter())
.filter_map(|a| a.as_ref())
.map(|a| a.capacity())
.sum()
}
}
pub struct IndexStore<Cfg: EGraphConfig> {
pub by_op: DenseSpanMap<Cfg::G>,
pub by_repr: DenseSpanMap<Cfg::G>,
pub by_child_pos: DenseSpanMap<Cfg::G>,
pub by_contains: DenseSpanMap<Cfg::G>,
pub child_pos_stride: usize,
pub repr: Vec<Cfg::G>,
pub op: Vec<Cfg::O>,
pub fanouts: FanOuts<Cfg::O>,
}
fn build_family<G: DenseId>(
arena: SpanArena,
stream: &[(usize, G)],
num_keys: usize,
) -> DenseSpanMap<G> {
DenseSpanMap::try_build_in(arena, stream, num_keys).unwrap_or_else(|_| {
panic!("num_keys is the stream's own key bound, accumulated as it was written")
})
}
#[inline]
fn for_each_occupied<G: DenseId>(m: &DenseSpanMap<G>, mut f: impl FnMut(usize, &[G])) {
for &k in m.occupied_keys() {
f(k, m.get(k));
}
}
#[inline]
fn debug_assert_id_sorted<G: DenseId>(m: &DenseSpanMap<G>, family: &str) {
#[cfg(debug_assertions)]
for_each_occupied(m, |k, b| {
debug_assert!(
b.windows(2).all(|w| w[0] < w[1]),
"{family}: bucket {k} is not strictly ascending in node id \
(lemma_view_sorted's hypothesis, the ascending build stream, was violated)"
);
});
#[cfg(not(debug_assertions))]
let _ = (m, family);
}
impl<Cfg: EGraphConfig> IndexStore<Cfg>
where
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
pub fn build<L: LitVal, const TRACK: bool, const PROOFS: bool>(
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
) -> Self {
Self::build_with(eg, &mut IndexScratch::new())
}
pub fn build_with<L: LitVal, const TRACK: bool, const PROOFS: bool>(
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
scratch: &mut IndexScratch<Cfg>,
) -> Self {
Self::build_from(eg, eg.node_ids(), true, scratch)
}
pub fn build_delta<L: LitVal, const TRACK: bool, const PROOFS: bool>(
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
touched: &[Cfg::G],
) -> Self {
Self::build_delta_with(eg, touched, &mut IndexScratch::new())
}
pub fn build_delta_with<L: LitVal, const TRACK: bool, const PROOFS: bool>(
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
touched: &[Cfg::G],
scratch: &mut IndexScratch<Cfg>,
) -> Self {
let ids: Vec<Cfg::G> = {
let _t = crate::phase_timing::Timer::start(crate::phase_timing::DELTA_DEDUP);
let mut ids: Vec<Cfg::G> = touched.to_vec();
ids.sort_unstable();
ids.dedup();
ids
};
Self::build_from(eg, ids.into_iter(), false, scratch)
}
pub fn recycle_into(self, scratch: &mut IndexScratch<Cfg>, full: bool) {
scratch.put_arena(full, FAM_OP, self.by_op.recycle());
scratch.put_arena(full, FAM_REPR, self.by_repr.recycle());
scratch.put_arena(full, FAM_CHILD_POS, self.by_child_pos.recycle());
scratch.put_arena(full, FAM_CONTAINS, self.by_contains.recycle());
}
fn build_from<L: LitVal, const TRACK: bool, const PROOFS: bool>(
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
ids: impl Iterator<Item = Cfg::G>,
full: bool,
scratch: &mut IndexScratch<Cfg>,
) -> Self {
scratch.clear();
let stride = eg.node_count();
let mut indexed = 0usize;
let (mut op_keys, mut repr_keys, mut cp_keys, mut ct_keys) = (0usize, 0, 0, 0);
let mut repr_tab: Vec<Cfg::G> = Vec::new();
let mut op_tab: Vec<Cfg::O> = Vec::new();
if full {
repr_tab.reserve(eg.node_count());
op_tab.reserve(eg.node_count());
}
let (walk_slot, span_base) = if full {
(
crate::phase_timing::FULL_WALK,
crate::phase_timing::FULL_SPAN_OP,
)
} else {
(
crate::phase_timing::DELTA_WALK,
crate::phase_timing::DELTA_SPAN_OP,
)
};
let walk_timer = crate::phase_timing::Timer::start(walk_slot);
for gid in ids {
let op = eg.node_op(gid);
let repr = eg.class_repr(gid);
if full {
debug_assert_eq!(repr_tab.len(), gid.to_usize());
repr_tab.push(repr);
op_tab.push(op);
}
if eg.node_flags(gid) & crate::node_types::FLAG_SUBSUMED != 0 {
continue;
}
let ok = op.to_usize();
op_keys = op_keys.max(ok + 1);
scratch.by_op.push((ok, gid));
let rk = repr.to_usize();
repr_keys = repr_keys.max(rk + 1);
scratch.by_repr.push((rk, gid));
indexed += 1;
let arity = {
let cp = &mut scratch.by_child_pos;
let mut pos = <Cfg::Index as IndexLike>::min();
eg.for_each_child(gid, |child, _mult| {
let child_repr = eg.class_repr(child).to_usize();
let key =
DenseSpanMap::<Cfg::G>::composite_key(pos.as_usize(), child_repr, stride)
.expect("child class is below the node bound and the product fits");
cp_keys = cp_keys.max(key + 1);
cp.push((key, gid));
pos = crate::containers::index_like::checked_incr(pos).expect(
"node arity exceeds EGraphConfig::Index; configure a wider index word",
);
})
};
if arity > 3
|| matches!(
eg.node_ref(gid),
crate::typed_routing::NodeRef::Seq(_)
| crate::typed_routing::NodeRef::MSet(_)
| crate::typed_routing::NodeRef::Set(_)
| crate::typed_routing::NodeRef::PlainN(_)
)
{
let seen = &mut scratch.seen;
let ct = &mut scratch.by_contains;
seen.clear(); eg.for_each_child(gid, |child, _mult| {
let cr = eg.class_repr(child);
if !seen.contains(&cr) {
seen.push(cr);
let k = cr.to_usize();
ct_keys = ct_keys.max(k + 1);
ct.push((k, gid));
}
});
}
}
walk_timer.stop();
let (a_op, a_repr, a_cp, a_ct) = (
scratch.take_arena(full, FAM_OP),
scratch.take_arena(full, FAM_REPR),
scratch.take_arena(full, FAM_CHILD_POS),
scratch.take_arena(full, FAM_CONTAINS),
);
let by_op = {
let _t = crate::phase_timing::Timer::start(span_base);
build_family(a_op, &scratch.by_op, op_keys)
};
let by_repr = {
let _t = crate::phase_timing::Timer::start(span_base + 1);
build_family(a_repr, &scratch.by_repr, repr_keys)
};
let by_child_pos = {
let _t = crate::phase_timing::Timer::start(span_base + 2);
build_family(a_cp, &scratch.by_child_pos, cp_keys)
};
let by_contains = {
let _t = crate::phase_timing::Timer::start(span_base + 3);
build_family(a_ct, &scratch.by_contains, ct_keys)
};
Self::record_shape(full, indexed, &by_child_pos);
debug_assert_id_sorted(&by_op, "by_op");
debug_assert_id_sorted(&by_repr, "by_repr");
debug_assert_id_sorted(&by_child_pos, "by_child_pos");
debug_assert_id_sorted(&by_contains, "by_contains");
let fanouts = if full {
let _t = crate::phase_timing::Timer::start(crate::phase_timing::FULL_FANOUTS);
Self::measure_fanouts(
&op_tab,
&by_repr,
&by_child_pos,
&by_contains,
stride,
indexed,
)
} else {
FanOuts::default()
};
Self {
by_op,
by_repr,
by_child_pos,
by_contains,
child_pos_stride: stride,
repr: repr_tab,
op: op_tab,
fanouts,
}
}
#[inline]
fn record_shape(full: bool, indexed: usize, by_child_pos: &DenseSpanMap<Cfg::G>) {
use crate::phase_timing as pt;
if !pt::enabled() {
return;
}
let (nodes, keys, values, nonempty) = if full {
(
pt::C_FULL_NODES,
pt::C_FULL_CP_KEYS,
pt::C_FULL_CP_VALUES,
pt::C_FULL_CP_NONEMPTY,
)
} else {
(
pt::C_DELTA_IDS,
pt::C_DELTA_CP_KEYS,
pt::C_DELTA_CP_VALUES,
pt::C_DELTA_CP_NONEMPTY,
)
};
pt::count(nodes, indexed as u64);
pt::count(keys, by_child_pos.len() as u64);
pt::count(values, by_child_pos.total() as u64);
let mut occupied = 0u64;
for_each_occupied(by_child_pos, |_, _| occupied += 1);
pt::count(nonempty, occupied);
}
fn measure_fanouts(
op_tab: &[Cfg::O],
by_repr: &DenseSpanMap<Cfg::G>,
by_child_pos: &DenseSpanMap<Cfg::G>,
by_contains: &DenseSpanMap<Cfg::G>,
stride: usize,
indexed: usize,
) -> FanOuts<Cfg::O> {
let mut cp: FastMap<(Cfg::O, usize), (u128, u128, u128)> = FastMap::default();
let mut ct: FastMap<Cfg::O, (u128, u128, u128)> = FastMap::default();
let mut tally: Vec<u64> = Vec::new();
let mut touched: Vec<usize> = Vec::new();
let tally_bucket = |bucket: &[Cfg::G], tally: &mut Vec<u64>, touched: &mut Vec<usize>| {
touched.clear();
for &gid in bucket {
let o = op_tab[gid.to_usize()].to_usize();
if o >= tally.len() {
tally.resize(o + 1, 0);
}
if tally[o] == 0 {
touched.push(o);
}
tally[o] += 1;
}
};
for_each_occupied(by_child_pos, |k, bucket| {
let pos = k / stride;
tally_bucket(bucket, &mut tally, &mut touched);
for &o in touched.iter() {
let c = u128::from(tally[o]);
let e = cp.entry((Cfg::O::from_usize(o), pos)).or_insert((0, 0, 0));
e.0 += c;
e.1 += c * c;
e.2 += 1;
tally[o] = 0;
}
});
for_each_occupied(by_contains, |_, bucket| {
tally_bucket(bucket, &mut tally, &mut touched);
for &o in touched.iter() {
let c = u128::from(tally[o]);
let e = ct.entry(Cfg::O::from_usize(o)).or_insert((0, 0, 0));
e.0 += c;
e.1 += c * c;
e.2 += 1;
tally[o] = 0;
}
});
let biased = |(sum, sq, _): &(u128, u128, u128)| -> f64 {
if *sum == 0 {
1.0
} else {
*sq as f64 / *sum as f64
}
};
let skew = |(sum, sq, count): &(u128, u128, u128)| -> f64 {
if *sum == 0 {
1.0
} else {
(*sq as f64 * *count as f64) / (*sum as f64 * *sum as f64)
}
};
let (mut class_sum, mut class_sq) = (0u128, 0u128);
for_each_occupied(by_repr, |_, b| {
let c = b.len() as u128;
class_sum += c;
class_sq += c * c;
});
FanOuts {
by_repr: biased(&(class_sum, class_sq, 0)),
by_child_pos_skew: cp.iter().map(|(&k, v)| (k, skew(v))).collect(),
by_contains_skew: ct.iter().map(|(&k, v)| (k, skew(v))).collect(),
by_child_pos: cp.iter().map(|(&k, v)| (k, biased(v))).collect(),
by_contains: ct.iter().map(|(&k, v)| (k, biased(v))).collect(),
nodes: indexed,
}
}
#[inline]
pub fn round_repr(&self, id: Cfg::G) -> Option<Cfg::G> {
self.repr.get(id.to_usize()).copied()
}
#[inline]
pub fn round_op(&self, id: Cfg::G) -> Option<Cfg::O> {
self.op.get(id.to_usize()).copied()
}
#[inline]
pub fn nodes_by_op(&self, op: Cfg::O) -> &[Cfg::G] {
self.by_op.try_get(op.to_usize()).unwrap_or(&[])
}
#[inline]
pub fn nodes_by_repr(&self, repr: Cfg::G) -> &[Cfg::G] {
self.by_repr.try_get(repr.to_usize()).unwrap_or(&[])
}
#[inline]
pub fn nodes_by_child_pos(&self, child_repr: Cfg::G, pos: Cfg::Index) -> &[Cfg::G] {
match DenseSpanMap::<Cfg::G>::composite_key(
pos.as_usize(),
child_repr.to_usize(),
self.child_pos_stride,
) {
Some(k) => self.by_child_pos.try_get(k).unwrap_or(&[]),
None => &[],
}
}
#[inline]
pub fn nodes_by_contains(&self, child_repr: Cfg::G) -> &[Cfg::G] {
self.by_contains
.try_get(child_repr.to_usize())
.unwrap_or(&[])
}
pub fn iter_by_op(&self, op: Cfg::O) -> SortedVecCursor<'_, Cfg::G> {
SortedVecCursor::new(self.nodes_by_op(op))
}
pub fn iter_by_repr(&self, repr: Cfg::G) -> SortedVecCursor<'_, Cfg::G> {
SortedVecCursor::new(self.nodes_by_repr(repr))
}
pub fn iter_by_child_pos(
&self,
child_repr: Cfg::G,
pos: Cfg::Index,
) -> SortedVecCursor<'_, Cfg::G> {
SortedVecCursor::new(self.nodes_by_child_pos(child_repr, pos))
}
pub fn iter_by_contains(&self, child_repr: Cfg::G) -> SortedVecCursor<'_, Cfg::G> {
SortedVecCursor::new(self.nodes_by_contains(child_repr))
}
pub fn op_cardinalities(&self) -> impl Iterator<Item = (Cfg::O, usize)> + '_ {
(0..self.by_op.len()).filter_map(|k| {
let n = self.by_op.key_len(k);
(n > 0).then(|| (Cfg::O::from_usize(k), n))
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum IndexMode {
Full,
Delta,
FullMinusDelta,
}
pub struct VariantIndex<'a, Cfg: EGraphConfig> {
pub full: &'a IndexStore<Cfg>,
pub delta: &'a IndexStore<Cfg>,
pub delta_atom: Option<usize>,
}
impl<Cfg: EGraphConfig> Clone for VariantIndex<'_, Cfg> {
fn clone(&self) -> Self {
*self
}
}
impl<Cfg: EGraphConfig> Copy for VariantIndex<'_, Cfg> {}
impl<'a, Cfg: EGraphConfig> VariantIndex<'a, Cfg> {
pub fn naive(full: &'a IndexStore<Cfg>) -> Self {
Self {
full,
delta: full,
delta_atom: None,
}
}
pub fn variant(
full: &'a IndexStore<Cfg>,
delta: &'a IndexStore<Cfg>,
delta_atom: usize,
) -> Self {
Self {
full,
delta,
delta_atom: Some(delta_atom),
}
}
#[inline]
pub fn mode(&self, atom_id: usize) -> IndexMode {
match self.delta_atom {
None => IndexMode::Full,
Some(i) if atom_id == i => IndexMode::Delta,
Some(i) if atom_id < i => IndexMode::FullMinusDelta,
Some(_) => IndexMode::Full,
}
}
}
const PROBE_SCAN_CAP: usize = 256;
pub struct IndexSampler<'a, Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool> {
eg: &'a EGraph<Cfg, L, TRACK, PROOFS>,
index: VariantIndex<'a, Cfg>,
}
impl<'a, Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool>
IndexSampler<'a, Cfg, L, TRACK, PROOFS>
where
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
pub fn new(eg: &'a EGraph<Cfg, L, TRACK, PROOFS>, index: VariantIndex<'a, Cfg>) -> Self {
Self { eg, index }
}
#[inline]
fn canon(&self, id: Cfg::G) -> Cfg::G {
match self.index.full.round_repr(id) {
Some(r) => r,
None => self.eg.find_const(id),
}
}
fn op_restricted(&self, s: &[Cfg::G], op: Cfg::O) -> usize {
let n = s.len();
let op_tab = &self.index.full.op;
let hits = |g: &Cfg::G| op_tab.get(g.to_usize()).is_some_and(|&o| o == op);
if n <= PROBE_SCAN_CAP {
return s.iter().filter(|g| hits(g)).count();
}
let seen = (0..PROBE_SCAN_CAP)
.filter(|j| hits(&s[j * n / PROBE_SCAN_CAP]))
.count();
seen * n / PROBE_SCAN_CAP
}
}
impl<Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool>
crate::schedule::CrossSampler<Cfg::O> for IndexSampler<'_, Cfg, L, TRACK, PROOFS>
where
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
fn driver_sample(&self, atom_id: usize, op: Cfg::O, k: usize, out: &mut Vec<usize>) {
out.clear();
let store = match self.index.mode(atom_id) {
IndexMode::Delta => self.index.delta,
IndexMode::Full | IndexMode::FullMinusDelta => self.index.full,
};
let s = store.nodes_by_op(op);
let n = s.len();
if n == 0 || k == 0 {
return;
}
let take = k.min(n);
out.extend((0..take).map(|j| s[j * n / take].to_usize()));
}
fn key_classes(&self, node: usize, site: crate::schedule::KeySite, out: &mut Vec<usize>) {
use crate::schedule::KeySite;
let g = Cfg::G::from_usize(node);
match site {
KeySite::Node => out.push(self.canon(g).to_usize()),
KeySite::Child(pos) => {
let mut i = 0usize;
self.eg.for_each_child(g, |c, _| {
if i == pos {
out.push(self.canon(c).to_usize());
}
i += 1;
});
}
KeySite::Element => {
self.eg.for_each_child(g, |c, _| {
let cr = self.canon(c).to_usize();
if !out.contains(&cr) {
out.push(cr);
}
});
}
}
}
fn probe_len(&self, class: usize, path: crate::schedule::ProbePath, op: Cfg::O) -> usize {
use crate::schedule::ProbePath;
let c = Cfg::G::from_usize(class);
let bucket = match path {
ProbePath::ChildPos(pos) => {
let Some(p) = <Cfg::Index as IndexLike>::try_from_usize(pos) else {
return 0;
};
self.index.full.nodes_by_child_pos(c, p)
}
ProbePath::Contains => self.index.full.nodes_by_contains(c),
};
self.op_restricted(bucket, op)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::egraph::EGraph31;
use crate::leapfrog::SortedCursor;
use crate::literal::NiraLitVal;
#[test]
fn by_op_index() {
let mut eg = EGraph31::<NiraLitVal, false, false>::new();
let int = eg.intern_sort("Int");
let f = eg.register_op1("f", int, int);
let g = eg.register_op1("g", int, int);
let x_op = eg.register_op0("x", int);
let x = eg.add(x_op, &[]);
let fx = eg.add(f, &[x]);
let gx = eg.add(g, &[x]);
let ffx = eg.add(f, &[fx]);
let idx = IndexStore::build(&eg);
let f_nodes = idx.nodes_by_op(f);
assert_eq!(f_nodes.len(), 2);
assert!(f_nodes.contains(&fx));
assert!(f_nodes.contains(&ffx));
assert_eq!(idx.nodes_by_op(g).len(), 1);
assert!(idx.nodes_by_op(g).contains(&gx));
assert_eq!(idx.nodes_by_op(x_op).len(), 1);
}
#[test]
fn by_repr_after_merge() {
let mut eg = EGraph31::<NiraLitVal, false, false>::new();
let int = eg.intern_sort("Int");
let x_op = eg.register_op0("x", int);
let y_op = eg.register_op0("y", int);
let x = eg.add(x_op, &[]);
let y = eg.add(y_op, &[]);
eg.merge(x, y);
eg.rebuild();
let idx = IndexStore::build(&eg);
let repr = eg.class_repr(x);
let class_nodes = idx.nodes_by_repr(repr);
assert_eq!(class_nodes.len(), 2);
}
#[test]
fn by_child_pos_index() {
let mut eg = EGraph31::<NiraLitVal, false, false>::new();
let int = eg.intern_sort("Int");
let f = eg.register_op1("f", int, int);
let g = eg.register_op2("g", int, int, int);
let x_op = eg.register_op0("x", int);
let y_op = eg.register_op0("y", int);
let x = eg.add(x_op, &[]);
let y = eg.add(y_op, &[]);
let fx = eg.add(f, &[x]);
let gxy = eg.add(g, &[x, y]);
let idx = IndexStore::build(&eg);
let parents_x_0 = idx.nodes_by_child_pos(x, 0);
assert_eq!(parents_x_0.len(), 2);
assert!(parents_x_0.contains(&fx));
assert!(parents_x_0.contains(&gxy));
let parents_y_1 = idx.nodes_by_child_pos(y, 1);
assert_eq!(parents_y_1.len(), 1);
assert!(parents_y_1.contains(&gxy));
}
#[test]
fn seek_and_step() {
let data = vec![
crate::id::ENodeId::from_usize(2),
crate::id::ENodeId::from_usize(5),
crate::id::ENodeId::from_usize(8),
crate::id::ENodeId::from_usize(12),
];
let mut it = SortedVecCursor::new(&data);
assert!(it.is_valid());
assert_eq!(it.key().to_usize(), 2);
it.seek(crate::id::ENodeId::from_usize(5));
assert_eq!(it.key().to_usize(), 5);
it.seek(crate::id::ENodeId::from_usize(7));
assert_eq!(it.key().to_usize(), 8);
it.step();
assert_eq!(it.key().to_usize(), 12);
it.step();
assert!(!it.is_valid());
}
mod seek_props {
use super::*;
use crate::containers::DenseId;
use proptest::prelude::*;
fn sorted_unique() -> impl Strategy<Value = Vec<usize>> {
proptest::collection::vec(0usize..200, 0..64).prop_map(|mut v| {
v.sort_unstable();
v.dedup();
v
})
}
fn targets() -> impl Strategy<Value = Vec<usize>> {
proptest::collection::vec(0usize..220, 0..16)
}
fn expected_pos(data: &[usize], from: usize, target: usize) -> usize {
let mut p = from;
while p < data.len() && data[p] < target {
p += 1;
}
p
}
fn run_seek_lands_on_first_ge<G: DenseId>(vals: &[usize], ts: &[usize]) {
let data: Vec<G> = vals.iter().map(|&v| G::from_usize(v)).collect();
for &t in ts {
let mut c = SortedVecCursor::new(&data);
c.seek(G::from_usize(t));
assert_eq!(
c.pos(),
expected_pos(vals, 0, t),
"seek({t}) on {vals:?} landed at {}",
c.pos()
);
if c.is_valid() {
assert!(c.key().to_usize() >= t, "landed below target");
if c.pos() > 0 {
assert!(vals[c.pos() - 1] < t, "skipped a key ≥ target");
}
}
}
}
fn run_seek_sequence_is_monotone<G: DenseId>(vals: &[usize], ts: &[usize]) {
let data: Vec<G> = vals.iter().map(|&v| G::from_usize(v)).collect();
let mut c = SortedVecCursor::new(&data);
let mut prev = c.pos();
let mut from = 0usize;
for &t in ts {
c.seek(G::from_usize(t));
assert!(c.pos() >= prev, "pos went backwards: {prev} -> {}", c.pos());
assert!(c.pos() <= data.len(), "pos {} out of bounds", c.pos());
assert_eq!(
c.pos(),
expected_pos(vals, from, t),
"seek({t}) mid-sequence"
);
prev = c.pos();
from = c.pos();
}
}
fn run_no_keys_are_skipped<G: DenseId>(vals: &[usize], ops: &[(bool, usize)]) {
let data: Vec<G> = vals.iter().map(|&v| G::from_usize(v)).collect();
let mut c = SortedVecCursor::new(&data);
let mut model = 0usize;
for &(is_seek, arg) in ops {
if is_seek {
c.seek(G::from_usize(arg));
model = expected_pos(vals, model, arg);
} else if c.is_valid() {
c.step();
model += 1;
}
assert_eq!(c.pos(), model, "cursor diverged from the model");
}
let mut seen = Vec::new();
while c.is_valid() {
seen.push(c.key().to_usize());
c.step();
}
assert_eq!(seen, vals[model.min(vals.len())..], "tail mismatch");
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2000))]
#[test]
fn seek_lands_on_first_ge_31(vals in sorted_unique(), ts in targets()) {
run_seek_lands_on_first_ge::<crate::id::ENodeId>(&vals, &ts);
}
#[test]
fn seek_lands_on_first_ge_63(vals in sorted_unique(), ts in targets()) {
run_seek_lands_on_first_ge::<crate::nodes::ENodeId64>(&vals, &ts);
}
#[test]
fn seek_sequence_is_monotone_31(vals in sorted_unique(), ts in targets()) {
run_seek_sequence_is_monotone::<crate::id::ENodeId>(&vals, &ts);
}
#[test]
fn seek_sequence_is_monotone_63(vals in sorted_unique(), ts in targets()) {
run_seek_sequence_is_monotone::<crate::nodes::ENodeId64>(&vals, &ts);
}
#[test]
fn no_keys_are_skipped_31(
vals in sorted_unique(),
ops in proptest::collection::vec((any::<bool>(), 0usize..220), 0..24),
) {
run_no_keys_are_skipped::<crate::id::ENodeId>(&vals, &ops);
}
#[test]
fn no_keys_are_skipped_63(
vals in sorted_unique(),
ops in proptest::collection::vec((any::<bool>(), 0usize..220), 0..24),
) {
run_no_keys_are_skipped::<crate::nodes::ENodeId64>(&vals, &ops);
}
}
#[test]
fn long_gallop_does_not_overflow() {
let data: Vec<crate::id::ENodeId> = (0..4096)
.map(|i| crate::id::ENodeId::from_usize(i * 2))
.collect();
let mut c = SortedVecCursor::new(&data);
c.seek(crate::id::ENodeId::from_usize(100_000));
assert_eq!(c.pos(), data.len());
assert!(!c.is_valid());
let mut c = SortedVecCursor::new(&data);
c.seek(crate::id::ENodeId::from_usize(8190));
assert_eq!(c.key().to_usize(), 8190);
}
#[test]
fn edge_shapes() {
let empty: [crate::id::ENodeId; 0] = [];
let mut c = SortedVecCursor::new(&empty);
c.seek(crate::id::ENodeId::from_usize(7));
assert_eq!(c.pos(), 0);
assert!(!c.is_valid());
let one = [crate::id::ENodeId::from_usize(5)];
for (t, want) in [(0usize, 0usize), (5, 0), (6, 1)] {
let mut c = SortedVecCursor::new(&one);
c.seek(crate::id::ENodeId::from_usize(t));
assert_eq!(c.pos(), want, "single-element seek({t})");
}
let mut c = SortedVecCursor::new(&one);
c.step();
assert!(!c.is_valid());
c.seek(crate::id::ENodeId::from_usize(0));
assert_eq!(c.pos(), 1);
c.seek(crate::id::ENodeId::from_usize(99));
assert_eq!(c.pos(), 1);
}
#[test]
fn saturated_ids() {
fn run<G: DenseId>(max: usize) {
let data: Vec<G> = [max - 2, max - 1, max]
.iter()
.map(|&v| G::from_usize(v))
.collect();
let mut c = SortedVecCursor::new(&data);
c.seek(G::from_usize(max));
assert_eq!(c.pos(), 2);
assert_eq!(c.key().to_usize(), max);
c.step();
assert!(!c.is_valid());
let mut c = SortedVecCursor::new(&data);
c.seek(G::from_usize(max - 1));
assert_eq!(c.key().to_usize(), max - 1);
}
run::<crate::id::ENodeId>((1usize << 31) - 1);
run::<crate::nodes::ENodeId64>((1usize << 63) - 1);
}
}
#[test]
fn child_pos_key_separates_positions_and_absent_keys() {
let mut eg = EGraph31::<NiraLitVal, false, false>::new();
let int = eg.intern_sort("Int");
let wide = eg.register_opn("w", &[int; 6], int);
let g = eg.register_op2("g", int, int, int);
let leaves: Vec<_> = ["a", "b", "c", "d", "e", "f"]
.iter()
.map(|n| {
let o = eg.register_op0(n, int);
eg.add(o, &[])
})
.collect();
let w = eg.add(wide, &leaves);
let gg = eg.add(g, &[leaves[0], leaves[5]]);
let idx = IndexStore::build(&eg);
assert_eq!(idx.nodes_by_child_pos(leaves[0], 0), &[w, gg]);
assert_eq!(idx.nodes_by_child_pos(leaves[1], 1), &[w]);
assert_eq!(idx.nodes_by_child_pos(leaves[5], 1), &[gg]);
assert_eq!(idx.nodes_by_child_pos(leaves[5], 5), &[w]);
assert!(idx.nodes_by_child_pos(leaves[0], 5).is_empty());
assert!(idx.nodes_by_child_pos(leaves[0], 6).is_empty());
assert!(
idx.nodes_by_child_pos(crate::id::ENodeId::from_usize(eg.node_count()), 0)
.is_empty()
);
}
#[test]
fn by_child_pos_after_merge() {
let mut eg = EGraph31::<NiraLitVal, false, false>::new();
let int = eg.intern_sort("Int");
let f = eg.register_op1("f", int, int);
let x_op = eg.register_op0("x", int);
let y_op = eg.register_op0("y", int);
let x = eg.add(x_op, &[]);
let y = eg.add(y_op, &[]);
let fx = eg.add(f, &[x]);
let _fy = eg.add(f, &[y]);
eg.merge(x, y);
eg.rebuild();
let idx = IndexStore::build(&eg);
let repr = eg.class_repr(x);
let parents = idx.nodes_by_child_pos(repr, 0);
assert!(parents.contains(&eg.find_const(fx)));
}
#[test]
fn by_contains_variadic() {
let mut eg = EGraph31::<NiraLitVal, false, false>::new();
let int = eg.intern_sort("Int");
let plus = eg.register_mset("plus", int, int);
let x_op = eg.register_op0("x", int);
let y_op = eg.register_op0("y", int);
let z_op = eg.register_op0("z", int);
let x = eg.add(x_op, &[]);
let y = eg.add(y_op, &[]);
let z = eg.add(z_op, &[]);
let pxy = eg.add(plus, &[x, y]);
let pxz = eg.add(plus, &[x, z]);
let idx = IndexStore::build(&eg);
let contains_x = idx.nodes_by_contains(x);
assert_eq!(contains_x.len(), 2);
assert!(contains_x.contains(&pxy));
assert!(contains_x.contains(&pxz));
let contains_y = idx.nodes_by_contains(y);
assert_eq!(contains_y.len(), 1);
}
}