use crate::ast::{CmpOp, LitValVarId, MsetVarId, MultVarId, SeqVarId, SetVarId, VarId};
use crate::canon::{MSetCanon, VarCanon};
use crate::config::EGraphConfig;
use crate::containers::IndexLike;
use crate::egraph::EGraph;
use crate::index::{IndexMode, IndexStore, SortedVecCursor, VariantIndex};
use crate::leapfrog::seek_stats::Probed;
use crate::leapfrog::{CursorVec, Difference, LeapfrogJoin, SortedCursor};
use crate::literal::LitVal;
use crate::multiplicity::MultiplicityLike;
use crate::resolve::{PatVar, RMult};
use crate::schedule::{IndexLookup, QueryPlan, Step};
use smallvec::SmallVec;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::cell::Cell;
thread_local! {
static MATCH_STEPS: Cell<u64> = const { Cell::new(0) };
static COUNTING: Cell<bool> = const { Cell::new(false) };
}
pub fn set_match_step_counting(on: bool) {
COUNTING.with(|c| c.set(on));
}
pub fn match_step_counting_enabled() -> bool {
COUNTING.with(|c| c.get())
}
pub fn reset_match_steps() {
MATCH_STEPS.with(|c| c.set(0));
}
pub fn match_steps() -> u64 {
MATCH_STEPS.with(|c| c.get())
}
#[inline]
fn add_match_steps(n: u64) {
if COUNTING.with(|c| c.get()) {
MATCH_STEPS.with(|c| c.set(c.get() + n));
}
}
type PoolSpan<Cfg> = (<Cfg as EGraphConfig>::Index, <Cfg as EGraphConfig>::Index);
#[inline]
fn empty_span<Cfg: EGraphConfig>() -> PoolSpan<Cfg> {
let zero = <Cfg::Index as IndexLike>::min();
(zero, zero)
}
#[inline]
fn pool_span<Cfg: EGraphConfig>(start: usize, end: usize, pool: &'static str) -> PoolSpan<Cfg> {
debug_assert!(
start <= end,
"{pool}: span end {end} precedes start {start}"
);
if <Cfg::Index as IndexLike>::try_from_usize(end).is_none() {
panic!(
"{pool} grew to {end} entries, past the {} addressable by EGraphConfig::Index; \
configure a wider index word",
<Cfg::Index as IndexLike>::max().as_usize(),
);
}
let ix = |n: usize| {
<Cfg::Index as IndexLike>::try_from_usize(n).expect("bounded by the checked end position")
};
(ix(start), ix(end - start))
}
#[inline]
fn span_range<Cfg: EGraphConfig>(span: PoolSpan<Cfg>) -> core::ops::Range<usize> {
let start = span.0.as_usize();
start..start + span.1.as_usize()
}
#[derive(Debug)]
pub struct Match<Cfg: EGraphConfig> {
pub nodes: Vec<Option<Cfg::G>>,
pub mults: Vec<Cfg::M>,
pub lit_vals: Vec<Cfg::V>,
pub seq_pool: Vec<Cfg::G>,
pub seq_spans: Vec<PoolSpan<Cfg>>,
pub set_pool: Vec<Cfg::G>,
pub set_spans: Vec<PoolSpan<Cfg>>,
pub mset_pool: Vec<Cfg::C>,
pub mset_spans: Vec<PoolSpan<Cfg>>,
}
impl<Cfg: EGraphConfig> Clone for Match<Cfg> {
fn clone(&self) -> Self {
Self {
nodes: self.nodes.clone(),
mults: self.mults.clone(),
lit_vals: self.lit_vals.clone(),
seq_pool: self.seq_pool.clone(),
seq_spans: self.seq_spans.clone(),
set_pool: self.set_pool.clone(),
set_spans: self.set_spans.clone(),
mset_pool: self.mset_pool.clone(),
mset_spans: self.mset_spans.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.nodes.clone_from(&source.nodes);
self.mults.clone_from(&source.mults);
self.lit_vals.clone_from(&source.lit_vals);
self.seq_pool.clone_from(&source.seq_pool);
self.seq_spans.clone_from(&source.seq_spans);
self.set_pool.clone_from(&source.set_pool);
self.set_spans.clone_from(&source.set_spans);
self.mset_pool.clone_from(&source.mset_pool);
self.mset_spans.clone_from(&source.mset_spans);
}
}
impl<Cfg: EGraphConfig> Match<Cfg> {
pub fn new(shape: &crate::resolve::MatchShape) -> Self {
Self {
nodes: vec![None; shape.num_vars()],
mults: vec![Cfg::M::ZERO; shape.num_mult_vars()],
lit_vals: vec![Cfg::V::default(); shape.num_lit_val_vars()],
seq_pool: Vec::new(),
seq_spans: vec![empty_span::<Cfg>(); shape.num_seq_vars()],
set_pool: Vec::new(),
set_spans: vec![empty_span::<Cfg>(); shape.num_set_vars()],
mset_pool: Vec::new(),
mset_spans: vec![empty_span::<Cfg>(); shape.num_mset_vars()],
}
}
pub fn get(&self, v: VarId) -> Cfg::G {
self.nodes[v.idx()].unwrap()
}
pub fn set(&mut self, v: VarId, val: Cfg::G) {
self.nodes[v.idx()] = Some(val);
}
pub fn clear(&mut self, v: VarId) {
self.nodes[v.idx()] = None;
}
pub fn get_opt(&self, v: VarId) -> Option<Cfg::G> {
self.nodes[v.idx()]
}
pub fn set_opt(&mut self, v: VarId, val: Option<Cfg::G>) {
self.nodes[v.idx()] = val;
}
pub fn resolve_pv<S: Copy>(
&self,
pv: PatVar,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
) -> Cfg::G {
match pv {
PatVar::Local(vid) => self.get(vid),
PatVar::Global(gid) => globals.binding(gid),
}
}
pub fn get_mult(&self, v: MultVarId) -> Cfg::M {
self.mults[v.idx()]
}
pub fn set_mult(&mut self, v: MultVarId, val: Cfg::M) {
self.mults[v.idx()] = val;
}
pub fn get_lit_val(&self, v: LitValVarId) -> Cfg::V {
self.lit_vals[v.idx()]
}
pub fn set_lit_val(&mut self, v: LitValVarId, val: Cfg::V) {
self.lit_vals[v.idx()] = val;
}
pub fn seq_slice(&self, v: SeqVarId) -> &[Cfg::G] {
&self.seq_pool[span_range::<Cfg>(self.seq_spans[v.idx()])]
}
pub fn push_seq(&mut self, v: SeqVarId, data: &[Cfg::G]) {
let start = self.seq_pool.len();
self.seq_pool.extend_from_slice(data);
self.seq_spans[v.idx()] = pool_span::<Cfg>(start, self.seq_pool.len(), "Match::seq_pool");
}
pub fn pop_seq(&mut self, v: SeqVarId) {
let (s, _) = self.seq_spans[v.idx()];
self.seq_pool.truncate(s.as_usize());
self.seq_spans[v.idx()] = empty_span::<Cfg>();
}
pub fn set_slice(&self, v: SetVarId) -> &[Cfg::G] {
&self.set_pool[span_range::<Cfg>(self.set_spans[v.idx()])]
}
pub fn push_set(&mut self, v: SetVarId, data: &[Cfg::G]) {
let start = self.set_pool.len();
self.set_pool.extend_from_slice(data);
self.set_spans[v.idx()] = pool_span::<Cfg>(start, self.set_pool.len(), "Match::set_pool");
}
pub fn pop_set(&mut self, v: SetVarId) {
let (s, _) = self.set_spans[v.idx()];
self.set_pool.truncate(s.as_usize());
self.set_spans[v.idx()] = empty_span::<Cfg>();
}
pub fn mset_slice(&self, v: MsetVarId) -> &[Cfg::C] {
&self.mset_pool[span_range::<Cfg>(self.mset_spans[v.idx()])]
}
pub fn push_mset(&mut self, v: MsetVarId, data: &[Cfg::C]) {
let start = self.mset_pool.len();
self.mset_pool.extend_from_slice(data);
self.mset_spans[v.idx()] =
pool_span::<Cfg>(start, self.mset_pool.len(), "Match::mset_pool");
}
pub fn pop_mset(&mut self, v: MsetVarId) {
let (s, _) = self.mset_spans[v.idx()];
self.mset_pool.truncate(s.as_usize());
self.mset_spans[v.idx()] = empty_span::<Cfg>();
}
pub fn push_mset_residual(&mut self, v: MsetVarId, residual: &[(Cfg::G, Cfg::M)]) {
let start = self.mset_pool.len();
let zero = Cfg::M::ZERO;
self.mset_pool.extend(
residual
.iter()
.filter(|&&(_, m)| m > zero)
.map(|&(g, m)| Cfg::mset_child_with_mult(g, m)),
);
self.mset_spans[v.idx()] =
pool_span::<Cfg>(start, self.mset_pool.len(), "Match::mset_pool");
}
pub fn push_set_residual(
&mut self,
v: SetVarId,
residual: &[Cfg::G],
used: &crate::containers::bitset::BitSet,
) {
let start = self.set_pool.len();
self.set_pool.extend(
residual
.iter()
.enumerate()
.filter(|&(i, _)| !used.test(i))
.map(|(_, &g)| g),
);
self.set_spans[v.idx()] = pool_span::<Cfg>(start, self.set_pool.len(), "Match::set_pool");
}
}
pub struct MatchPool<Cfg: EGraphConfig> {
set: MatchSet<Cfg>,
id_bufs: Vec<Vec<Cfg::G>>,
mset_bufs: Vec<Vec<(Cfg::G, Cfg::M)>>,
steps: u64,
op_filter_policy: OpFilterPolicy,
}
impl<Cfg: EGraphConfig> Default for MatchPool<Cfg> {
fn default() -> Self {
Self::new()
}
}
impl<Cfg: EGraphConfig> MatchPool<Cfg> {
pub fn new() -> Self {
Self {
set: MatchSet::empty(),
id_bufs: Vec::new(),
mset_bufs: Vec::new(),
steps: 0,
op_filter_policy: OpFilterPolicy::Adaptive,
}
}
pub fn reshape(&mut self, shape: &crate::resolve::MatchShape) {
self.set.reshape(shape);
}
#[inline]
pub fn row(&self, j: usize) -> MatchRow<'_, Cfg> {
MatchRow { set: &self.set, j }
}
pub fn clone_match(&self, j: usize) -> Match<Cfg> {
let s = &self.set;
let mut m = Match {
nodes: (0..s.node_stride)
.map(|i| Some(s.nodes[j * s.node_stride + i]))
.collect(),
mults: s.mults[j * s.mult_stride..(j + 1) * s.mult_stride].to_vec(),
lit_vals: s.lit_vals[j * s.lit_stride..(j + 1) * s.lit_stride].to_vec(),
seq_pool: Vec::new(),
seq_spans: vec![empty_span::<Cfg>(); s.seq_stride],
set_pool: Vec::new(),
set_spans: vec![empty_span::<Cfg>(); s.set_stride],
mset_pool: Vec::new(),
mset_spans: vec![empty_span::<Cfg>(); s.mset_stride],
};
for i in 0..s.seq_stride {
let span = s.seq_spans[j * s.seq_stride + i];
let start = m.seq_pool.len();
m.seq_pool
.extend_from_slice(&s.seq_pool[span_range::<Cfg>(span)]);
m.seq_spans[i] = pool_span::<Cfg>(start, m.seq_pool.len(), "clone_match:seq");
}
for i in 0..s.set_stride {
let span = s.set_spans[j * s.set_stride + i];
let start = m.set_pool.len();
m.set_pool
.extend_from_slice(&s.set_pool[span_range::<Cfg>(span)]);
m.set_spans[i] = pool_span::<Cfg>(start, m.set_pool.len(), "clone_match:set");
}
for i in 0..s.mset_stride {
let span = s.mset_spans[j * s.mset_stride + i];
let start = m.mset_pool.len();
m.mset_pool
.extend_from_slice(&s.mset_pool[span_range::<Cfg>(span)]);
m.mset_spans[i] = pool_span::<Cfg>(start, m.mset_pool.len(), "clone_match:mset");
}
m
}
#[inline]
fn take_id_buf(&mut self) -> Vec<Cfg::G> {
self.id_bufs.pop().unwrap_or_default()
}
#[inline]
fn give_id_buf(&mut self, buf: Vec<Cfg::G>) {
self.id_bufs.push(buf);
}
#[inline]
fn take_mset_buf(&mut self) -> Vec<(Cfg::G, Cfg::M)> {
self.mset_bufs.pop().unwrap_or_default()
}
#[inline]
fn give_mset_buf(&mut self, buf: Vec<(Cfg::G, Cfg::M)>) {
self.mset_bufs.push(buf);
}
#[inline]
pub fn clear(&mut self) {
self.set.clear();
}
#[inline]
pub fn push(&mut self, env: &Match<Cfg>) {
self.set.push(env);
}
#[inline]
pub fn len(&self) -> usize {
self.set.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.set.is_empty()
}
}
pub struct MatchSet<Cfg: EGraphConfig> {
pub count: usize,
node_stride: usize,
mult_stride: usize,
lit_stride: usize,
seq_stride: usize,
set_stride: usize,
mset_stride: usize,
nodes: Vec<Cfg::G>,
mults: Vec<Cfg::M>,
lit_vals: Vec<Cfg::V>,
seq_spans: Vec<PoolSpan<Cfg>>,
set_spans: Vec<PoolSpan<Cfg>>,
mset_spans: Vec<PoolSpan<Cfg>>,
seq_pool: Vec<Cfg::G>,
set_pool: Vec<Cfg::G>,
mset_pool: Vec<Cfg::C>,
}
impl<Cfg: EGraphConfig> MatchSet<Cfg> {
pub fn new(shape: &crate::resolve::MatchShape) -> Self {
Self {
count: 0,
node_stride: shape.num_vars(),
mult_stride: shape.num_mult_vars(),
lit_stride: shape.num_lit_val_vars(),
seq_stride: shape.num_seq_vars(),
set_stride: shape.num_set_vars(),
mset_stride: shape.num_mset_vars(),
nodes: Vec::new(),
mults: Vec::new(),
lit_vals: Vec::new(),
seq_spans: Vec::new(),
set_spans: Vec::new(),
mset_spans: Vec::new(),
seq_pool: Vec::new(),
set_pool: Vec::new(),
mset_pool: Vec::new(),
}
}
pub fn empty() -> Self {
Self {
count: 0,
node_stride: 0,
mult_stride: 0,
lit_stride: 0,
seq_stride: 0,
set_stride: 0,
mset_stride: 0,
nodes: Vec::new(),
mults: Vec::new(),
lit_vals: Vec::new(),
seq_spans: Vec::new(),
set_spans: Vec::new(),
mset_spans: Vec::new(),
seq_pool: Vec::new(),
set_pool: Vec::new(),
mset_pool: Vec::new(),
}
}
pub fn reshape(&mut self, shape: &crate::resolve::MatchShape) {
self.node_stride = shape.num_vars();
self.mult_stride = shape.num_mult_vars();
self.lit_stride = shape.num_lit_val_vars();
self.seq_stride = shape.num_seq_vars();
self.set_stride = shape.num_set_vars();
self.mset_stride = shape.num_mset_vars();
self.count = 0;
self.nodes.clear();
self.mults.clear();
self.lit_vals.clear();
self.seq_spans.clear();
self.set_spans.clear();
self.mset_spans.clear();
self.seq_pool.clear();
self.set_pool.clear();
self.mset_pool.clear();
}
pub fn push(&mut self, m: &Match<Cfg>) {
self.nodes
.extend(m.nodes[..self.node_stride].iter().map(|v| v.unwrap()));
if !m.mults.is_empty() {
self.mults.extend_from_slice(&m.mults);
}
if !m.lit_vals.is_empty() {
self.lit_vals.extend_from_slice(&m.lit_vals);
}
for &span in &m.seq_spans {
let start = self.seq_pool.len();
self.seq_pool
.extend_from_slice(&m.seq_pool[span_range::<Cfg>(span)]);
self.seq_spans.push(pool_span::<Cfg>(
start,
self.seq_pool.len(),
"MatchSet::seq_pool",
));
}
for &span in &m.set_spans {
let start = self.set_pool.len();
self.set_pool
.extend_from_slice(&m.set_pool[span_range::<Cfg>(span)]);
self.set_spans.push(pool_span::<Cfg>(
start,
self.set_pool.len(),
"MatchSet::set_pool",
));
}
for &span in &m.mset_spans {
let start = self.mset_pool.len();
self.mset_pool
.extend_from_slice(&m.mset_pool[span_range::<Cfg>(span)]);
self.mset_spans.push(pool_span::<Cfg>(
start,
self.mset_pool.len(),
"MatchSet::mset_pool",
));
}
self.count += 1;
}
pub fn is_empty(&self) -> bool {
self.count == 0
}
pub fn len(&self) -> usize {
self.count
}
pub fn get_node(&self, v: VarId, j: usize) -> Cfg::G {
self.nodes[j * self.node_stride + v.idx()]
}
pub fn get_mult(&self, v: MultVarId, j: usize) -> Cfg::M {
self.mults[j * self.mult_stride + v.idx()]
}
pub fn get_lit_val(&self, v: LitValVarId, j: usize) -> Cfg::V {
self.lit_vals[j * self.lit_stride + v.idx()]
}
pub fn set_node(&mut self, v: VarId, j: usize, val: Cfg::G) {
self.nodes[j * self.node_stride + v.idx()] = val;
}
pub fn set_mult(&mut self, v: MultVarId, j: usize, val: Cfg::M) {
self.mults[j * self.mult_stride + v.idx()] = val;
}
pub fn seq_slice(&self, v: SeqVarId, j: usize) -> &[Cfg::G] {
let span = self.seq_spans[j * self.seq_stride + v.idx()];
&self.seq_pool[span_range::<Cfg>(span)]
}
pub fn set_slice(&self, v: SetVarId, j: usize) -> &[Cfg::G] {
let span = self.set_spans[j * self.set_stride + v.idx()];
&self.set_pool[span_range::<Cfg>(span)]
}
pub fn mset_slice(&self, v: MsetVarId, j: usize) -> &[Cfg::C] {
let span = self.mset_spans[j * self.mset_stride + v.idx()];
&self.mset_pool[span_range::<Cfg>(span)]
}
pub fn clear(&mut self) {
self.count = 0;
self.nodes.clear();
self.mults.clear();
self.lit_vals.clear();
self.seq_spans.clear();
self.set_spans.clear();
self.mset_spans.clear();
self.seq_pool.clear();
self.set_pool.clear();
self.mset_pool.clear();
}
}
pub trait MatchView<Cfg: EGraphConfig> {
fn get(&self, v: VarId) -> Cfg::G;
fn get_mult(&self, v: MultVarId) -> Cfg::M;
fn get_lit_val(&self, v: LitValVarId) -> Cfg::V;
fn seq_slice(&self, v: SeqVarId) -> &[Cfg::G];
fn set_slice(&self, v: SetVarId) -> &[Cfg::G];
fn mset_slice(&self, v: MsetVarId) -> &[Cfg::C];
}
impl<Cfg: EGraphConfig> MatchView<Cfg> for Match<Cfg> {
fn get(&self, v: VarId) -> Cfg::G {
Match::get(self, v)
}
fn get_mult(&self, v: MultVarId) -> Cfg::M {
Match::get_mult(self, v)
}
fn get_lit_val(&self, v: LitValVarId) -> Cfg::V {
Match::get_lit_val(self, v)
}
fn seq_slice(&self, v: SeqVarId) -> &[Cfg::G] {
Match::seq_slice(self, v)
}
fn set_slice(&self, v: SetVarId) -> &[Cfg::G] {
Match::set_slice(self, v)
}
fn mset_slice(&self, v: MsetVarId) -> &[Cfg::C] {
Match::mset_slice(self, v)
}
}
pub struct MatchRow<'a, Cfg: EGraphConfig> {
set: &'a MatchSet<Cfg>,
j: usize,
}
impl<'a, Cfg: EGraphConfig> MatchView<Cfg> for MatchRow<'a, Cfg> {
fn get(&self, v: VarId) -> Cfg::G {
self.set.get_node(v, self.j)
}
fn get_mult(&self, v: MultVarId) -> Cfg::M {
self.set.get_mult(v, self.j)
}
fn get_lit_val(&self, v: LitValVarId) -> Cfg::V {
self.set.get_lit_val(v, self.j)
}
fn seq_slice(&self, v: SeqVarId) -> &[Cfg::G] {
self.set.seq_slice(v, self.j)
}
fn set_slice(&self, v: SetVarId) -> &[Cfg::G] {
self.set.set_slice(v, self.j)
}
fn mset_slice(&self, v: MsetVarId) -> &[Cfg::C] {
self.set.mset_slice(v, self.j)
}
}
pub struct ClonedMatchIter<'a, Cfg: EGraphConfig, L: LitVal, S: Copy, const T: bool, const P: bool>
{
inner: MatchIterator<'a, Cfg, L, S, T, P>,
}
impl<'a, Cfg, L, S: Copy, const T: bool, const P: bool> Iterator
for ClonedMatchIter<'a, Cfg, L, S, T, P>
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
type Item = Match<Cfg>;
fn next(&mut self) -> Option<Match<Cfg>> {
if self.inner.next_match() {
Some(self.inner.env().clone())
} else {
None
}
}
}
pub fn run_query<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
) -> Vec<Match<Cfg>>
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let mut pool = MatchPool::new();
run_query_into(plan, eg, index, globals, &mut pool);
(0..pool.len()).map(|j| pool.clone_match(j)).collect()
}
#[inline]
fn canon<Cfg, L, const TRACK: bool, const PROOFS: bool>(
index: &VariantIndex<'_, Cfg>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
id: Cfg::G,
) -> Cfg::G
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
match index.full.round_repr(id) {
Some(r) => r,
None => eg.find_const(id),
}
}
pub fn run_query_into<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
pool: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
pool.reshape(&plan.shape);
pool.steps = 0;
pool.op_filter_policy = op_filter_policy();
let mut env = Match::new(&plan.shape);
let exec = Exec::<Cfg, L, S>::static_plan(&plan.steps);
run_step(&exec, 0, eg, index, globals, &mut env, pool);
add_match_steps(pool.steps);
}
pub fn run_query_scheduled_into<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
rq: &crate::resolve::ResolvedQuery<Cfg::O, S, L>,
plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
pool: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
if !runtime_scheduling() || !Adaptive::<Cfg, L, S>::fits(rq) {
run_query_into(plan, eg, index, globals, pool);
return;
}
pool.reshape(&rq.shape);
pool.steps = 0;
pool.op_filter_policy = op_filter_policy();
let mut env = Match::new(&rq.shape);
let adaptive = Adaptive::new(rq);
let exec = Exec::adaptive(&adaptive);
run_step(&exec, 0, eg, index, globals, &mut env, pool);
add_match_steps(pool.steps);
}
pub fn run_query_scheduled<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
rq: &crate::resolve::ResolvedQuery<Cfg::O, S, L>,
plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
) -> Vec<Match<Cfg>>
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let mut pool = MatchPool::new();
run_query_scheduled_into(rq, plan, eg, index, globals, &mut pool);
(0..pool.len()).map(|j| pool.clone_match(j)).collect()
}
thread_local! {
static RUNTIME_SCHEDULING: Cell<bool> = const { Cell::new(false) };
}
pub fn set_runtime_scheduling(on: bool) {
RUNTIME_SCHEDULING.with(|c| c.set(on));
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum SchedulingMode {
#[default]
Static,
Runtime,
Auto,
}
thread_local! {
static SCHEDULING_MODE: Cell<SchedulingMode> = const { Cell::new(SchedulingMode::Static) };
}
pub fn set_scheduling_mode(mode: SchedulingMode) {
SCHEDULING_MODE.with(|c| c.set(mode));
match mode {
SchedulingMode::Static => set_runtime_scheduling(false),
SchedulingMode::Runtime => set_runtime_scheduling(true),
SchedulingMode::Auto => {}
}
}
pub fn scheduling_mode() -> SchedulingMode {
SCHEDULING_MODE.with(|c| c.get())
}
pub fn runtime_scheduling() -> bool {
RUNTIME_SCHEDULING.with(|c| c.get())
}
pub const ADAPTIVE_MAX_WIDTH: usize = 64;
const EAGER: u32 = u32::MAX;
struct Segment<Cfg: EGraphConfig, L: LitVal> {
steps: std::rc::Rc<[Step<Cfg::O, Cfg::Index, L>]>,
bound: u64,
used: u64,
}
impl<Cfg: EGraphConfig, L: LitVal> Clone for Segment<Cfg, L> {
fn clone(&self) -> Self {
Self {
steps: self.steps.clone(),
bound: self.bound,
used: self.used,
}
}
}
struct Adaptive<'q, Cfg: EGraphConfig, L: LitVal, S: Copy> {
atoms: &'q [crate::resolve::RAtom<Cfg::O, S, L>],
costed: u64,
num_vars: usize,
memo: std::cell::RefCell<Vec<((u32, u64, u64), Segment<Cfg, L>)>>,
}
impl<'q, Cfg: EGraphConfig, L: LitVal, S: Copy> Adaptive<'q, Cfg, L, S> {
fn fits(rq: &crate::resolve::ResolvedQuery<Cfg::O, S, L>) -> bool {
rq.atoms.len() <= ADAPTIVE_MAX_WIDTH && rq.shape.num_vars() <= ADAPTIVE_MAX_WIDTH
}
fn new(rq: &'q crate::resolve::ResolvedQuery<Cfg::O, S, L>) -> Self {
let mut costed = 0u64;
for (i, atom) in rq.atoms.iter().enumerate() {
if !matches!(
atom,
crate::resolve::RAtom::Eq(..)
| crate::resolve::RAtom::EqGlobal(..)
| crate::resolve::RAtom::Pred { .. }
) {
costed |= 1 << i;
}
}
Self {
atoms: &rq.atoms,
costed,
num_vars: rq.shape.num_vars(),
memo: std::cell::RefCell::new(Vec::new()),
}
}
fn segment(&self, chosen: u32, bound: u64, used: u64) -> Segment<Cfg, L> {
let key = (chosen, bound, used);
if let Some((_, seg)) = self.memo.borrow().iter().find(|(k, _)| *k == key) {
return seg.clone();
}
let mut bound_buf = [false; ADAPTIVE_MAX_WIDTH];
let mut used_buf = [false; ADAPTIVE_MAX_WIDTH];
let bound_arr = &mut bound_buf[..self.num_vars];
let used_arr = &mut used_buf[..self.atoms.len()];
for (i, b) in bound_arr.iter_mut().enumerate() {
*b = bound & (1 << i) != 0;
}
for (i, u) in used_arr.iter_mut().enumerate() {
*u = used & (1 << i) != 0;
}
let mut steps = Vec::new();
if chosen == EAGER {
crate::schedule::lower_eager(self.atoms, used_arr, bound_arr, &mut steps);
} else {
let ai = chosen as usize;
crate::schedule::emit_atom(&self.atoms[ai], ai, bound_arr, &mut steps);
used_arr[ai] = true;
}
let seg = Segment {
steps: steps.into(),
bound: mask_of(bound_arr),
used: mask_of(used_arr),
};
self.memo.borrow_mut().push((key, seg.clone()));
seg
}
}
fn mask_of(flags: &[bool]) -> u64 {
flags
.iter()
.enumerate()
.fold(0u64, |m, (i, &b)| if b { m | (1 << i) } else { m })
}
struct Exec<'a, Cfg: EGraphConfig, L: LitVal, S: Copy> {
steps: &'a [Step<Cfg::O, Cfg::Index, L>],
adaptive: Option<&'a Adaptive<'a, Cfg, L, S>>,
bound: u64,
used: u64,
}
impl<'a, Cfg: EGraphConfig, L: LitVal, S: Copy> Exec<'a, Cfg, L, S> {
fn static_plan(steps: &'a [Step<Cfg::O, Cfg::Index, L>]) -> Self {
Self {
steps,
adaptive: None,
bound: 0,
used: 0,
}
}
fn adaptive(ad: &'a Adaptive<'a, Cfg, L, S>) -> Self {
Self {
steps: &[],
adaptive: Some(ad),
bound: 0,
used: 0,
}
}
}
fn advance<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
ad: &Adaptive<'_, Cfg, L, S>,
exec: &Exec<'_, Cfg, L, S>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let eager = ad.segment(EAGER, exec.bound, exec.used);
if !eager.steps.is_empty() {
let next = Exec {
steps: &eager.steps,
adaptive: Some(ad),
bound: eager.bound,
used: eager.used,
};
run_step(&next, 0, eg, index, globals, env, results);
return;
}
let Some(ai) = choose_atom(ad, exec, eg, index, globals, env) else {
results.steps += 1;
results.push(env);
return;
};
let seg = ad.segment(ai as u32, exec.bound, exec.used);
let next = Exec {
steps: &seg.steps,
adaptive: Some(ad),
bound: seg.bound,
used: seg.used,
};
run_step(&next, 0, eg, index, globals, env, results);
}
fn choose_atom<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
ad: &Adaptive<'_, Cfg, L, S>,
exec: &Exec<'_, Cfg, L, S>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &Match<Cfg>,
) -> Option<usize>
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let candidates = ad.costed & !exec.used;
if candidates.count_ones() == 1 {
let ai = candidates.trailing_zeros() as usize;
#[cfg(test)]
ATOM_CHOICE_LOG.with(|l| l.borrow_mut().push((exec.used, ai)));
return Some(ai);
}
let mut best: Option<(usize, usize)> = None;
for ai in 0..ad.atoms.len() {
if candidates & (1 << ai) == 0 {
continue;
}
let seg = ad.segment(ai as u32, exec.bound, exec.used);
let len = cursor_len(&seg, ai, eg, index, globals, env);
if best.is_none_or(|(b, _)| len < b) {
best = Some((len, ai));
}
}
#[cfg(test)]
if let Some((_, ai)) = best {
ATOM_CHOICE_LOG.with(|l| l.borrow_mut().push((exec.used, ai)));
}
best.map(|(_, ai)| ai)
}
#[cfg(test)]
thread_local! {
static ATOM_CHOICE_LOG: std::cell::RefCell<Vec<(u64, usize)>> =
const { std::cell::RefCell::new(Vec::new()) };
}
#[cfg(test)]
pub(crate) fn take_atom_choices() -> Vec<(u64, usize)> {
ATOM_CHOICE_LOG.with(|l| std::mem::take(&mut *l.borrow_mut()))
}
fn cursor_len<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
seg: &Segment<Cfg, L>,
atom_id: usize,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &Match<Cfg>,
) -> usize
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let Some(Step::Join { lookups, .. }) = seg.steps.first() else {
return usize::MAX;
};
let store = match index.mode(atom_id) {
IndexMode::Delta => index.delta,
IndexMode::Full | IndexMode::FullMinusDelta => index.full,
};
let mut best = usize::MAX;
for l in lookups {
let len = bucket_in(store, index, l, eg, globals, env).len();
if len < best {
best = len;
}
}
best
}
fn run_step<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
exec: &Exec<'_, Cfg, L, S>,
step_idx: usize,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
if step_idx >= exec.steps.len() {
match exec.adaptive {
None => {
results.steps += 1;
results.push(env);
}
Some(ad) => advance(ad, exec, eg, index, globals, env, results),
}
return;
}
results.steps += 1;
match &exec.steps[step_idx] {
Step::Join {
target,
lookups,
atom_id,
} => {
run_join(
exec, step_idx, *target, lookups, *atom_id, eg, index, globals, env, results,
);
}
Step::ExtractChild {
target,
parent,
pos,
} => {
let parent_id = env.get(*parent);
let child = eg.child_at(parent_id, *pos);
env.set(*target, child);
run_step(exec, step_idx + 1, eg, index, globals, env, results);
env.clear(*target);
}
Step::CheckChildEq {
parent,
pos,
expected,
} => {
let parent_id = env.get(*parent);
let child = eg.child_at(parent_id, *pos);
let exp = env.resolve_pv(*expected, globals);
if canon(index, eg, child) == canon(index, eg, exp) {
run_step(exec, step_idx + 1, eg, index, globals, env, results);
}
}
Step::CheckEq { a, b } => {
if canon(index, eg, env.get(*a)) == canon(index, eg, env.get(*b)) {
run_step(exec, step_idx + 1, eg, index, globals, env, results);
}
}
Step::CheckEqGlobal { local, global } => {
if canon(index, eg, env.get(*local)) == canon(index, eg, globals.binding(*global)) {
run_step(exec, step_idx + 1, eg, index, globals, env, results);
}
}
Step::BindGlobal { target, global } => {
let val = canon(index, eg, globals.binding(*global));
env.set(*target, val);
run_step(exec, step_idx + 1, eg, index, globals, env, results);
env.clear(*target);
}
Step::CopyBinding { target, other } => {
let val = canon(index, eg, env.get(*other));
env.set(*target, val);
run_step(exec, step_idx + 1, eg, index, globals, env, results);
env.clear(*target);
}
Step::ExpandA {
node,
children,
pre,
suf,
} => {
let node_id = env.get(*node);
let mut buf = results.take_id_buf();
eg.seq_children(node_id, &mut buf);
run_expand_a(
exec, step_idx, children, *pre, *suf, &buf, eg, index, globals, env, results,
);
results.give_id_buf(buf);
}
Step::DecomposeAC {
node,
elems,
rest,
idempotent: _,
} => {
let node_id = env.get(*node);
let mut residual = results.take_mset_buf();
eg.mset_children(node_id, &mut residual);
for entry in &mut residual {
entry.0 = canon(index, eg, entry.0);
}
run_decompose_ac(
exec,
step_idx,
elems,
*rest,
&mut residual,
eg,
index,
globals,
env,
results,
);
results.give_mset_buf(residual);
}
Step::DecomposeACI { node, elems, rest } => {
let node_id = env.get(*node);
let mut residual = results.take_id_buf();
eg.set_children(node_id, &mut residual);
for entry in &mut residual {
*entry = canon(index, eg, *entry);
}
run_decompose_aci(
exec, step_idx, elems, *rest, &residual, eg, index, globals, env, results,
);
results.give_id_buf(residual);
}
Step::ExtractLitVal { node, val } => {
let node_id = env.get(*node);
if let Some(lit_val_id) = eg.get_lit_val_id(node_id) {
env.set_lit_val(*val, lit_val_id);
run_step(exec, step_idx + 1, eg, index, globals, env, results);
}
}
Step::CheckLit { node, value } => {
let node_id = env.get(*node);
if eg.get_lit_val(node_id) == Some(value) {
run_step(exec, step_idx + 1, eg, index, globals, env, results);
}
}
Step::CheckPred { guard } => {
if eval_guard(guard, eg, env) {
run_step(exec, step_idx + 1, eg, index, globals, env, results);
}
}
}
}
const GUARD_ARGS: usize = 2;
fn eval_guard<Cfg, L, const TRACK: bool, const PROOFS: bool>(
guard: &crate::resolve::PredGuard<Cfg::O, L>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
env: &Match<Cfg>,
) -> bool
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let v = eval_pred_expr(&guard.expr, eg, env);
(guard.truthy)(&v)
}
fn eval_pred_expr<Cfg, L, const TRACK: bool, const PROOFS: bool>(
expr: &crate::resolve::RPredExpr<Cfg::O, L>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
env: &Match<Cfg>,
) -> L
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
use crate::resolve::RPredExpr;
match expr {
RPredExpr::Val(v) => eg.lits().get(env.get_lit_val(*v)).clone(),
RPredExpr::Const(l) => l.clone(),
RPredExpr::App { eval, args, .. } => {
let vals: SmallVec<[L; GUARD_ARGS]> =
args.iter().map(|a| eval_pred_expr(a, eg, env)).collect();
let refs: SmallVec<[&L; GUARD_ARGS]> = vals.iter().collect();
eval(&refs)
}
}
}
fn run_expand_a<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
exec: &Exec<'_, Cfg, L, S>,
step_idx: usize,
children: &[PatVar],
pre: Option<SeqVarId>,
suf: Option<SeqVarId>,
seq: &[Cfg::G],
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let nfixed = children.len();
match (pre, suf) {
(None, None) => {
if seq.len() != nfixed {
return;
}
bind_fixed_and_continue(
exec, step_idx, children, seq, 0, eg, index, globals, env, results,
);
}
(Some(p), None) => {
if seq.len() < nfixed {
return;
}
let split = seq.len() - nfixed;
env.push_seq(p, &seq[..split]);
bind_fixed_and_continue(
exec, step_idx, children, seq, split, eg, index, globals, env, results,
);
env.pop_seq(p);
}
(None, Some(s)) => {
if seq.len() < nfixed {
return;
}
env.push_seq(s, &seq[nfixed..]);
bind_fixed_and_continue(
exec, step_idx, children, seq, 0, eg, index, globals, env, results,
);
env.pop_seq(s);
}
(Some(p), Some(s)) => {
if seq.len() < nfixed {
return;
}
let slack = seq.len() - nfixed;
for offset in 0..=slack {
env.push_seq(p, &seq[..offset]);
env.push_seq(s, &seq[offset + nfixed..]);
bind_fixed_and_continue(
exec, step_idx, children, seq, offset, eg, index, globals, env, results,
);
env.pop_seq(s);
env.pop_seq(p);
}
}
}
}
type BoundHere = SmallVec<[VarId; 8]>;
fn unbind<Cfg: EGraphConfig>(env: &mut Match<Cfg>, bound: &BoundHere) {
for &v in bound {
env.clear(v);
}
}
fn bind_fixed_and_continue<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
exec: &Exec<'_, Cfg, L, S>,
step_idx: usize,
children: &[PatVar],
seq: &[Cfg::G],
offset: usize,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let mut bound: BoundHere = BoundHere::new();
for (i, &cv) in children.iter().enumerate() {
let val = seq[offset + i];
match cv {
PatVar::Global(gid) => {
if canon(index, eg, globals.binding(gid)) != canon(index, eg, val) {
unbind(env, &bound);
return;
}
}
PatVar::Local(vid) => {
if let Some(existing) = env.nodes[vid.idx()] {
if canon(index, eg, existing) != canon(index, eg, val) {
unbind(env, &bound);
return;
}
} else {
env.set(vid, val);
bound.push(vid);
}
}
}
}
run_step(exec, step_idx + 1, eg, index, globals, env, results);
unbind(env, &bound);
}
fn mult_matches(mult: &RMult, avail: u64, bound_mult: Option<u64>) -> bool {
match mult {
RMult::Exact(n) => avail == *n,
RMult::Var { constraint, .. } => {
if avail < 1 {
return false;
}
if let Some(prev) = bound_mult
&& prev > 0
&& avail != prev
{
return false;
}
match constraint {
None => true,
Some((op, val)) => {
let v = *val;
match op {
CmpOp::Ge => avail >= v,
CmpOp::Gt => avail > v,
CmpOp::Le => avail <= v,
CmpOp::Lt => avail < v,
CmpOp::Eq => avail == v,
CmpOp::Ne => avail != v,
}
}
}
}
}
}
fn bound_mult_val<Cfg: EGraphConfig>(mult: &RMult, env: &Match<Cfg>) -> Option<u64> {
match mult {
RMult::Exact(_) => None,
RMult::Var { var, .. } => {
let v = env.get_mult(*var).to_u64();
if v > 0 { Some(v) } else { None }
}
}
}
fn run_decompose_ac<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
exec: &Exec<'_, Cfg, L, S>,
step_idx: usize,
elems: &[(PatVar, RMult)],
rest: Option<MsetVarId>,
residual: &mut [(Cfg::G, Cfg::M)],
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
decompose_ac_elem(
exec, step_idx, elems, 0, rest, residual, eg, index, globals, env, results,
);
}
fn decompose_ac_elem<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
exec: &Exec<'_, Cfg, L, S>,
step_idx: usize,
elems: &[(PatVar, RMult)],
ei: usize,
rest: Option<MsetVarId>,
residual: &mut [(Cfg::G, Cfg::M)],
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let zero = Cfg::M::ZERO;
if ei >= elems.len() {
if let Some(rv) = rest {
env.push_mset_residual(rv, residual);
run_step(exec, step_idx + 1, eg, index, globals, env, results);
env.pop_mset(rv);
} else if residual.iter().all(|&(_, m)| m == zero) {
run_step(exec, step_idx + 1, eg, index, globals, env, results);
}
return;
}
let (var, mult) = &elems[ei];
let bound_repr = match *var {
PatVar::Global(gid) => Some(canon(index, eg, globals.binding(gid))),
PatVar::Local(vid) => env.nodes[vid.idx()].map(|v| canon(index, eg, v)),
};
if let Some(repr) = bound_repr {
if let Some(pos) = residual.iter().position(|&(r, m)| {
r == repr && mult_matches(mult, m.to_u64(), bound_mult_val(mult, env))
}) {
let actual = residual[pos].1;
let was_unbound = match mult {
RMult::Var { var: mv, .. } => env.get_mult(*mv) == Cfg::M::ZERO,
_ => false,
};
let take: Cfg::M = match mult {
RMult::Exact(_) => actual,
RMult::Var { var: mv, .. } => {
env.set_mult(*mv, actual);
actual
}
};
let prev = residual[pos].1;
residual[pos].1 = prev.saturating_sub(take);
decompose_ac_elem(
exec,
step_idx,
elems,
ei + 1,
rest,
residual,
eg,
index,
globals,
env,
results,
);
residual[pos].1 = prev;
if was_unbound && let RMult::Var { var: mv, .. } = mult {
env.set_mult(*mv, Cfg::M::ZERO);
}
}
return;
}
let n = residual.len();
for ri in 0..n {
let (repr, avail) = residual[ri];
if !mult_matches(mult, avail.to_u64(), bound_mult_val(mult, env)) {
continue;
}
let PatVar::Local(vid) = *var else {
unreachable!()
};
env.set(vid, repr);
let was_unbound = match mult {
RMult::Var { var: mv, .. } => env.get_mult(*mv) == Cfg::M::ZERO,
_ => false,
};
let take: Cfg::M = match mult {
RMult::Exact(_) => avail,
RMult::Var { var: mv, .. } => {
env.set_mult(*mv, avail);
avail
}
};
let prev = residual[ri].1;
residual[ri].1 = prev.saturating_sub(take);
decompose_ac_elem(
exec,
step_idx,
elems,
ei + 1,
rest,
residual,
eg,
index,
globals,
env,
results,
);
residual[ri].1 = prev;
env.clear(vid);
if was_unbound && let RMult::Var { var: mv, .. } = mult {
env.set_mult(*mv, Cfg::M::ZERO);
}
}
}
fn run_decompose_aci<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
exec: &Exec<'_, Cfg, L, S>,
step_idx: usize,
elems: &[PatVar],
rest: Option<SetVarId>,
residual: &[Cfg::G],
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let mut used = crate::containers::bitset::BitSet::new(residual.len());
decompose_aci_elem(
exec, step_idx, elems, 0, rest, residual, &mut used, eg, index, globals, env, results,
);
}
fn decompose_aci_elem<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
exec: &Exec<'_, Cfg, L, S>,
step_idx: usize,
elems: &[PatVar],
ei: usize,
rest: Option<SetVarId>,
residual: &[Cfg::G],
used: &mut crate::containers::bitset::BitSet,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
if ei >= elems.len() {
if let Some(rv) = rest {
env.push_set_residual(rv, residual, used);
run_step(exec, step_idx + 1, eg, index, globals, env, results);
env.pop_set(rv);
} else if (0..residual.len()).all(|i| used.test(i)) {
run_step(exec, step_idx + 1, eg, index, globals, env, results);
}
return;
}
let var = elems[ei];
let bound_repr = match var {
PatVar::Global(gid) => Some(canon(index, eg, globals.binding(gid))),
PatVar::Local(vid) => env.nodes[vid.idx()].map(|v| canon(index, eg, v)),
};
if let Some(repr) = bound_repr {
if let Some(pos) = residual
.iter()
.enumerate()
.position(|(i, &r)| !used.test(i) && r == repr)
{
used.set(pos);
decompose_aci_elem(
exec,
step_idx,
elems,
ei + 1,
rest,
residual,
used,
eg,
index,
globals,
env,
results,
);
used.clear(pos);
}
return;
}
let PatVar::Local(vid) = var else {
unreachable!()
};
for ri in 0..residual.len() {
if used.test(ri) {
continue;
}
env.set(vid, residual[ri]);
used.set(ri);
decompose_aci_elem(
exec,
step_idx,
elems,
ei + 1,
rest,
residual,
used,
eg,
index,
globals,
env,
results,
);
used.clear(ri);
env.clear(vid);
}
}
const OP_FILTER_RELATION_PER_CANDIDATE: usize = 512;
pub const OP_FILTER_MIN_RELATION: usize = 131_072;
const OP_FILTER_SEEK_COST: usize = 2;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum OpFilterPolicy {
Adaptive,
AlwaysFilter,
AlwaysLeapfrog,
}
static OP_FILTER_POLICY: AtomicUsize = AtomicUsize::new(0);
pub fn set_op_filter_policy(p: OpFilterPolicy) {
OP_FILTER_POLICY.store(
match p {
OpFilterPolicy::Adaptive => 0,
OpFilterPolicy::AlwaysFilter => 1,
OpFilterPolicy::AlwaysLeapfrog => 2,
},
Ordering::Relaxed,
);
}
pub fn op_filter_policy() -> OpFilterPolicy {
match OP_FILTER_POLICY.load(Ordering::Relaxed) {
1 => OpFilterPolicy::AlwaysFilter,
2 => OpFilterPolicy::AlwaysLeapfrog,
_ => OpFilterPolicy::Adaptive,
}
}
#[cfg(test)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum OpRestriction {
Leapfrog,
Filter,
}
#[cfg(test)]
thread_local! {
static OP_RESTRICTION_LOG: std::cell::RefCell<Vec<OpRestriction>> =
const { std::cell::RefCell::new(Vec::new()) };
}
#[cfg(test)]
pub(crate) fn take_op_restriction_log() -> Vec<OpRestriction> {
OP_RESTRICTION_LOG.with(|l| std::mem::take(&mut *l.borrow_mut()))
}
#[inline]
fn demote_by_op(m: usize, n: Option<usize>, policy: OpFilterPolicy) -> bool {
let Some(n) = n else { return false };
let demote = match policy {
OpFilterPolicy::AlwaysFilter => true,
OpFilterPolicy::AlwaysLeapfrog => false,
OpFilterPolicy::Adaptive => {
n >= OP_FILTER_MIN_RELATION.min(m.saturating_mul(OP_FILTER_RELATION_PER_CANDIDATE))
&& m <= n.saturating_mul(OP_FILTER_SEEK_COST)
}
};
#[cfg(test)]
OP_RESTRICTION_LOG.with(|l| {
l.borrow_mut().push(if demote {
OpRestriction::Filter
} else {
OpRestriction::Leapfrog
})
});
demote
}
#[inline]
fn cursor_of<G: crate::containers::DenseId>(b: &[G]) -> Probed<'_, G> {
Probed::new(b)
}
fn run_join<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
exec: &Exec<'_, Cfg, L, S>,
step_idx: usize,
target: VarId,
lookups: &[IndexLookup<Cfg::O, Cfg::Index>],
atom_id: usize,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
if lookups.is_empty() {
return;
}
debug_assert_eq!(
lookups
.iter()
.filter(|l| matches!(l, IndexLookup::ByOp { .. }))
.count(),
1,
"a join's lookups must carry exactly one ByOp"
);
let op_pos = if lookups.len() > 1 {
lookups
.iter()
.position(|l| matches!(l, IndexLookup::ByOp { .. }))
} else {
None
};
let policy = results.op_filter_policy;
macro_rules! dispatch {
($store:expr, $open:expr) => {{
let store = $store;
let mut m = usize::MAX;
let mut cursors = CursorVec::new();
for (i, l) in lookups.iter().enumerate() {
if Some(i) == op_pos {
continue;
}
let b = bucket_in(store, index, l, eg, globals, env);
let len = b.len();
if len < m {
m = len;
}
cursors.push($open(b, l));
}
let op_bucket = op_pos.map(|p| bucket_in(store, index, &lookups[p], eg, globals, env));
let op_filter = if demote_by_op(m, op_bucket.map(|b| b.len()), policy) {
match &lookups[op_pos.expect("a demoted join has a ByOp lookup")] {
IndexLookup::ByOp { op } => Some(*op),
_ => unreachable!("op_pos indexes a ByOp lookup"),
}
} else {
if let (Some(b), Some(p)) = (op_bucket, op_pos) {
cursors.push($open(b, &lookups[p]));
}
None
};
leapfrog_join(
cursors, op_filter, exec, step_idx, target, eg, index, globals, env, results,
);
}};
}
match index.mode(atom_id) {
IndexMode::Full => dispatch!(index.full, |b, _l| cursor_of(b)),
IndexMode::Delta => dispatch!(index.delta, |b, _l| cursor_of(b)),
IndexMode::FullMinusDelta => dispatch!(index.full, |b, l| Difference::new(
cursor_of(b),
cursor_in(index.delta, index, l, eg, globals, env)
)),
}
}
fn bucket_in<'a, Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
store: &'a IndexStore<Cfg>,
index: &VariantIndex<'_, Cfg>,
l: &IndexLookup<Cfg::O, Cfg::Index>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &Match<Cfg>,
) -> &'a [Cfg::G]
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
match l {
IndexLookup::ByOp { op } => store.nodes_by_op(*op),
IndexLookup::ByChildPos { child, pos } => {
let r = canon(index, eg, env.resolve_pv(*child, globals));
store.nodes_by_child_pos(r, *pos)
}
IndexLookup::ByRepr { repr } => {
let r = canon(index, eg, env.get(*repr));
store.nodes_by_repr(r)
}
IndexLookup::ByContains { child } => {
let r = canon(index, eg, env.resolve_pv(*child, globals));
store.nodes_by_contains(r)
}
}
}
fn cursor_in<'a, Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
store: &'a IndexStore<Cfg>,
index: &VariantIndex<'_, Cfg>,
l: &IndexLookup<Cfg::O, Cfg::Index>,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &Match<Cfg>,
) -> Probed<'a, Cfg::G>
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
cursor_of(bucket_in(store, index, l, eg, globals, env))
}
fn leapfrog_join<Cfg, L, S: Copy, C, const TRACK: bool, const PROOFS: bool>(
cursors: CursorVec<C>,
op_filter: Option<Cfg::O>,
exec: &Exec<'_, Cfg, L, S>,
step_idx: usize,
target: VarId,
eg: &EGraph<Cfg, L, TRACK, PROOFS>,
index: &VariantIndex<'_, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &mut Match<Cfg>,
results: &mut MatchPool<Cfg>,
) where
Cfg: EGraphConfig,
L: LitVal,
C: SortedCursor<Key = Cfg::G>,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let prev = env.get_opt(target);
let mut join = LeapfrogJoin::new(cursors);
while join.is_valid() {
let id = join.key();
if op_filter.is_none_or(|o| index.full.round_op(id).unwrap_or_else(|| eg.node_op(id)) == o)
{
env.set(target, id);
run_step(exec, step_idx + 1, eg, index, globals, env, results);
}
join.next();
}
env.set_opt(target, prev);
}
fn resolve_lookup<'a, Cfg: EGraphConfig, L: LitVal, S: Copy, const T: bool, const P: bool>(
l: &IndexLookup<Cfg::O, Cfg::Index>,
eg: &EGraph<Cfg, L, T, P>,
index: &'a VariantIndex<'a, Cfg>,
globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
env: &Match<Cfg>,
) -> &'a [Cfg::G]
where
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
match l {
IndexLookup::ByOp { op } => index.full.nodes_by_op(*op),
IndexLookup::ByChildPos { child, pos } => {
let r = canon(index, eg, env.resolve_pv(*child, globals));
index.full.nodes_by_child_pos(r, *pos)
}
IndexLookup::ByRepr { repr } => {
let r = canon(index, eg, env.get(*repr));
index.full.nodes_by_repr(r)
}
IndexLookup::ByContains { child } => {
let r = canon(index, eg, env.resolve_pv(*child, globals));
index.full.nodes_by_contains(r)
}
}
}
enum FrameKind<'a, Cfg: EGraphConfig> {
Join {
target: VarId,
join: LeapfrogJoin<SortedVecCursor<'a, Cfg::G>>,
},
SlidingWindow {
children: Vec<PatVar>,
pre: SeqVarId,
suf: SeqVarId,
seq: Vec<Cfg::G>,
offset: usize,
slack: usize,
bound: BoundHere,
},
ACDecompose {
elems: Vec<(PatVar, RMult)>,
rest: Option<MsetVarId>,
residual: Vec<(Cfg::G, Cfg::M)>,
ri_at: Vec<usize>,
bound: Vec<bool>,
ei: usize,
},
ACIDecompose {
elems: Vec<PatVar>,
rest: Option<SetVarId>,
residual: Vec<Cfg::G>,
used: crate::containers::bitset::BitSet,
ri_at: Vec<usize>,
bound: Vec<bool>,
ei: usize,
},
}
struct Frame<'a, Cfg: EGraphConfig> {
kind: FrameKind<'a, Cfg>,
step_idx: usize,
}
pub struct MatchIterator<'a, Cfg: EGraphConfig, L: LitVal, S: Copy, const T: bool, const P: bool> {
plan: &'a QueryPlan<Cfg::O, Cfg::Index, L>,
eg: &'a EGraph<Cfg, L, T, P>,
index: &'a VariantIndex<'a, Cfg>,
globals: &'a crate::resolve::GlobalCtx<S, Cfg::G>,
env: Match<Cfg>,
frames: Vec<Frame<'a, Cfg>>,
cursor: usize,
done: bool,
}
impl<'a, Cfg, L, S: Copy, const T: bool, const P: bool> MatchIterator<'a, Cfg, L, S, T, P>
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
pub fn new(
plan: &'a QueryPlan<Cfg::O, Cfg::Index, L>,
eg: &'a EGraph<Cfg, L, T, P>,
index: &'a VariantIndex<'a, Cfg>,
globals: &'a crate::resolve::GlobalCtx<S, Cfg::G>,
) -> Self {
Self {
plan,
eg,
index,
globals,
env: Match::new(&plan.shape),
frames: Vec::new(),
cursor: 0,
done: false,
}
}
pub fn env(&self) -> &Match<Cfg> {
&self.env
}
pub fn cloned_iter(self) -> ClonedMatchIter<'a, Cfg, L, S, T, P> {
ClonedMatchIter { inner: self }
}
pub fn collect_set(&mut self, shape: &crate::resolve::MatchShape) -> MatchSet<Cfg> {
let mut set = MatchSet::new(shape);
while self.next_match() {
set.push(&self.env);
}
set
}
pub fn next_match(&mut self) -> bool {
if self.done {
return false;
}
if self.cursor == usize::MAX && !self.backtrack() {
self.done = true;
return false;
}
loop {
if self.cursor >= self.plan.steps.len() {
self.cursor = usize::MAX;
return true;
}
match self.enter() {
Enter::Advanced => continue,
Enter::Failed => {
if !self.backtrack() {
self.done = true;
return false;
}
}
Enter::Pushed(true) => {
self.cursor += 1;
continue;
}
Enter::Pushed(false) => {
self.frames.pop();
if !self.backtrack() {
self.done = true;
return false;
}
}
}
}
}
fn enter(&mut self) -> Enter {
match &self.plan.steps[self.cursor] {
Step::ExtractChild {
target,
parent,
pos,
} => {
let child = self.eg.child_at(self.env.get(*parent), *pos);
self.env.set(*target, child);
self.cursor += 1;
Enter::Advanced
}
Step::CheckChildEq {
parent,
pos,
expected,
} => {
let child = self.eg.child_at(self.env.get(*parent), *pos);
if canon(self.index, self.eg, child)
== canon(
self.index,
self.eg,
self.env.resolve_pv(*expected, self.globals),
)
{
self.cursor += 1;
Enter::Advanced
} else {
Enter::Failed
}
}
Step::CheckEq { a, b } => {
if canon(self.index, self.eg, self.env.get(*a))
== canon(self.index, self.eg, self.env.get(*b))
{
self.cursor += 1;
Enter::Advanced
} else {
Enter::Failed
}
}
Step::BindGlobal { target, global } => {
let val = canon(self.index, self.eg, self.globals.binding(*global));
self.env.set(*target, val);
self.cursor += 1;
Enter::Advanced
}
Step::CheckEqGlobal { local, global } => {
if canon(self.index, self.eg, self.env.get(*local))
== canon(self.index, self.eg, self.globals.binding(*global))
{
self.cursor += 1;
Enter::Advanced
} else {
Enter::Failed
}
}
Step::CopyBinding { target, other } => {
self.env
.set(*target, canon(self.index, self.eg, self.env.get(*other)));
self.cursor += 1;
Enter::Advanced
}
Step::Join {
target, lookups, ..
} => {
let target = *target;
let lookups = lookups.clone();
self.enter_join(target, &lookups)
}
Step::ExpandA {
node,
children,
pre,
suf,
} => {
let node_id = self.env.get(*node);
let mut seq = Vec::new();
self.eg.seq_children(node_id, &mut seq);
let children = children.clone();
let pre = *pre;
let suf = *suf;
self.enter_expand_a(&children, pre, suf, seq)
}
Step::DecomposeAC {
node, elems, rest, ..
} => {
let node_id = self.env.get(*node);
let mut residual = Vec::new();
self.eg.mset_children(node_id, &mut residual);
for e in &mut residual {
e.0 = canon(self.index, self.eg, e.0);
}
let elems = elems.clone();
let rest = *rest;
self.enter_ac(&elems, rest, residual)
}
Step::DecomposeACI { node, elems, rest } => {
let node_id = self.env.get(*node);
let mut residual = Vec::new();
self.eg.set_children(node_id, &mut residual);
for e in &mut residual {
*e = canon(self.index, self.eg, *e);
}
let elems = elems.clone();
let rest = *rest;
self.enter_aci(&elems, rest, residual)
}
Step::ExtractLitVal { node, val } => {
let node_id = self.env.get(*node);
if let Some(lit_val_id) = self.eg.get_lit_val_id(node_id) {
self.env.set_lit_val(*val, lit_val_id);
self.cursor += 1;
Enter::Advanced
} else {
Enter::Failed
}
}
Step::CheckLit { node, value } => {
let node_id = self.env.get(*node);
if self.eg.get_lit_val(node_id) == Some(value) {
self.cursor += 1;
Enter::Advanced
} else {
Enter::Failed
}
}
Step::CheckPred { guard } => {
if eval_guard(guard, self.eg, &self.env) {
self.cursor += 1;
Enter::Advanced
} else {
Enter::Failed
}
}
}
}
fn enter_join(&mut self, target: VarId, lookups: &[IndexLookup<Cfg::O, Cfg::Index>]) -> Enter {
let mut iters: CursorVec<SortedVecCursor<'a, Cfg::G>> = CursorVec::new();
for l in lookups {
let b = resolve_lookup(l, self.eg, self.index, self.globals, &self.env);
if b.is_empty() {
return Enter::Failed;
}
iters.push(SortedVecCursor::new(b));
}
if iters.is_empty() {
return Enter::Failed;
}
let join = LeapfrogJoin::new(iters);
let valid = join.is_valid();
if valid {
self.env.set(target, join.key());
}
self.frames.push(Frame {
kind: FrameKind::Join { target, join },
step_idx: self.cursor,
});
Enter::Pushed(valid)
}
fn enter_expand_a(
&mut self,
children: &[PatVar],
pre: Option<SeqVarId>,
suf: Option<SeqVarId>,
seq: Vec<Cfg::G>,
) -> Enter {
let nfixed = children.len();
match (pre, suf) {
(Some(p), Some(s)) => {
if seq.len() < nfixed {
return Enter::Failed;
}
let slack = seq.len() - nfixed;
let mut bound = BoundHere::new();
let mut offset = 0;
let mut valid = false;
while offset <= slack {
self.env.push_seq(p, &seq[..offset]);
self.env.push_seq(s, &seq[offset + nfixed..]);
if self.bind_fixed(children, &seq, offset, &mut bound) {
valid = true;
break;
}
self.env.pop_seq(s);
self.env.pop_seq(p);
offset += 1;
}
if !valid {
return Enter::Failed;
}
self.frames.push(Frame {
kind: FrameKind::SlidingWindow {
children: children.to_vec(),
pre: p,
suf: s,
seq,
offset,
slack,
bound,
},
step_idx: self.cursor,
});
Enter::Pushed(true)
}
_ => {
let mut bound = BoundHere::new();
if pre.is_none() && suf.is_none() {
if seq.len() != nfixed {
return Enter::Failed;
}
if !self.bind_fixed(children, &seq, 0, &mut bound) {
return Enter::Failed;
}
self.cursor += 1;
Enter::Advanced
} else if let (Some(p), None) = (pre, suf) {
if seq.len() < nfixed {
return Enter::Failed;
}
let split = seq.len() - nfixed;
self.env.push_seq(p, &seq[..split]);
if !self.bind_fixed(children, &seq, split, &mut bound) {
self.env.pop_seq(p);
return Enter::Failed;
}
self.cursor += 1;
Enter::Advanced
} else {
let s = suf.unwrap();
if seq.len() < nfixed {
return Enter::Failed;
}
self.env.push_seq(s, &seq[nfixed..]);
if !self.bind_fixed(children, &seq, 0, &mut bound) {
self.env.pop_seq(s);
return Enter::Failed;
}
self.cursor += 1;
Enter::Advanced
}
}
}
}
fn enter_ac(
&mut self,
elems: &[(PatVar, RMult)],
rest: Option<MsetVarId>,
mut residual: Vec<(Cfg::G, Cfg::M)>,
) -> Enter {
if elems.is_empty() {
let zero = Cfg::M::ZERO;
if let Some(rv) = rest {
let rem: Vec<Cfg::C> = residual
.iter()
.filter(|&&(_, m)| m > zero)
.map(|&(g, m)| Cfg::mset_child_with_mult(g, m))
.collect();
self.env.push_mset(rv, &rem);
self.cursor += 1;
return Enter::Advanced;
} else if residual.iter().all(|&(_, m)| m == zero) {
self.cursor += 1;
return Enter::Advanced;
} else {
return Enter::Failed;
}
}
let mut ri_at = vec![0usize; elems.len()];
let mut bound = vec![false; elems.len()];
let mut valid = self.ac_find_first(elems, &mut residual, &mut ri_at, &mut bound, 0);
if valid {
if let Some(rv) = rest {
let zero = Cfg::M::ZERO;
let rem: Vec<Cfg::C> = residual
.iter()
.filter(|&&(_, m)| m > zero)
.map(|&(g, m)| Cfg::mset_child_with_mult(g, m))
.collect();
self.env.push_mset(rv, &rem);
} else {
let zero = Cfg::M::ZERO;
if !residual.iter().all(|&(_, m)| m == zero) {
for e in (0..elems.len()).rev() {
self.ac_undo(elems, &mut residual, e, ri_at[e], &mut bound);
}
valid = false;
}
}
}
if !valid {
return Enter::Failed;
}
let ei = elems.len();
self.frames.push(Frame {
kind: FrameKind::ACDecompose {
elems: elems.to_vec(),
rest,
residual,
ri_at,
bound,
ei,
},
step_idx: self.cursor,
});
Enter::Pushed(true)
}
fn enter_aci(
&mut self,
elems: &[PatVar],
rest: Option<SetVarId>,
residual: Vec<Cfg::G>,
) -> Enter {
if elems.is_empty() {
if let Some(rv) = rest {
self.env.push_set(rv, &residual);
self.cursor += 1;
return Enter::Advanced;
} else if residual.is_empty() {
self.cursor += 1;
return Enter::Advanced;
} else {
return Enter::Failed;
}
}
let mut used = crate::containers::bitset::BitSet::new(residual.len());
let mut ri_at = vec![0usize; elems.len()];
let mut bound = vec![false; elems.len()];
let mut valid = self.aci_find_first(elems, &residual, &mut used, &mut ri_at, &mut bound, 0);
if valid {
if let Some(rv) = rest {
let rem: Vec<Cfg::G> = residual
.iter()
.enumerate()
.filter(|&(i, _)| !used.test(i))
.map(|(_, &g)| g)
.collect();
self.env.push_set(rv, &rem);
} else if !(0..residual.len()).all(|i| used.test(i)) {
for e in (0..elems.len()).rev() {
self.aci_undo(elems, &mut used, e, ri_at[e], &mut bound);
}
valid = false;
}
}
if !valid {
return Enter::Failed;
}
let ei = elems.len();
self.frames.push(Frame {
kind: FrameKind::ACIDecompose {
elems: elems.to_vec(),
rest,
residual,
used,
ri_at,
bound,
ei,
},
step_idx: self.cursor,
});
Enter::Pushed(true)
}
fn bind_fixed(
&mut self,
children: &[PatVar],
seq: &[Cfg::G],
offset: usize,
bound: &mut BoundHere,
) -> bool {
bound.clear();
for (i, &cv) in children.iter().enumerate() {
let val = seq[offset + i];
match cv {
PatVar::Global(gid) => {
if canon(self.index, self.eg, self.globals.binding(gid))
!= canon(self.index, self.eg, val)
{
unbind(&mut self.env, bound);
bound.clear();
return false;
}
}
PatVar::Local(vid) => {
if let Some(existing) = self.env.nodes[vid.idx()] {
if canon(self.index, self.eg, existing) != canon(self.index, self.eg, val) {
unbind(&mut self.env, bound);
bound.clear();
return false;
}
} else {
self.env.set(vid, val);
bound.push(vid);
}
}
}
}
true
}
fn backtrack(&mut self) -> bool {
loop {
let mut frame = match self.frames.pop() {
Some(f) => f,
None => return false,
};
self.cursor = frame.step_idx;
match &mut frame.kind {
FrameKind::Join { target, join } => {
self.env.clear(*target);
join.next();
if join.is_valid() {
self.env.set(*target, join.key());
self.cursor += 1;
self.frames.push(frame);
return true;
}
}
FrameKind::SlidingWindow {
children,
pre,
suf,
seq,
offset,
slack,
bound,
} => {
unbind(&mut self.env, bound);
self.env.pop_seq(*suf);
self.env.pop_seq(*pre);
*offset += 1;
while *offset <= *slack {
let nfixed = children.len();
let o = *offset;
self.env.push_seq(*pre, &seq[..o]);
self.env.push_seq(*suf, &seq[o + nfixed..]);
if self.bind_fixed(children, seq, o, bound) {
self.cursor += 1;
self.frames.push(frame);
return true;
}
self.env.pop_seq(*suf);
self.env.pop_seq(*pre);
*offset += 1;
}
}
FrameKind::ACDecompose {
elems,
rest,
residual,
ri_at,
bound,
ei,
} => {
if *ei == elems.len()
&& let Some(rv) = *rest
{
self.env.pop_mset(rv);
}
loop {
if !self.ac_advance(elems, residual, ri_at, bound, ei) {
break;
}
if let Some(rv) = *rest {
let zero = Cfg::M::ZERO;
let rem: Vec<Cfg::C> = residual
.iter()
.filter(|&&(_, m)| m > zero)
.map(|&(g, m)| Cfg::mset_child_with_mult(g, m))
.collect();
self.env.push_mset(rv, &rem);
self.cursor += 1;
self.frames.push(frame);
return true;
} else {
let zero = Cfg::M::ZERO;
if residual.iter().all(|&(_, m)| m == zero) {
self.cursor += 1;
self.frames.push(frame);
return true;
}
}
}
}
FrameKind::ACIDecompose {
elems,
rest,
residual,
used,
ri_at,
bound,
ei,
} => {
if *ei == elems.len()
&& let Some(rv) = *rest
{
self.env.pop_set(rv);
}
loop {
if !self.aci_advance(elems, residual, used, ri_at, bound, ei) {
break;
}
if let Some(rv) = *rest {
let rem: Vec<Cfg::G> = residual
.iter()
.enumerate()
.filter(|&(i, _)| !used.test(i))
.map(|(_, &g)| g)
.collect();
self.env.push_set(rv, &rem);
self.cursor += 1;
self.frames.push(frame);
return true;
} else if (0..residual.len()).all(|i| used.test(i)) {
self.cursor += 1;
self.frames.push(frame);
return true;
}
}
}
}
}
}
fn ac_find_first(
&mut self,
elems: &[(PatVar, RMult)],
residual: &mut [(Cfg::G, Cfg::M)],
ri_at: &mut [usize],
bound: &mut [bool],
from: usize,
) -> bool {
let mut ei = from;
while ei < elems.len() {
let start = if ei == from { ri_at[ei] } else { 0 };
match self.ac_scan(elems, residual, ei, start, bound) {
Some(ri) => {
ri_at[ei] = ri;
ei += 1;
}
None => {
ri_at[ei] = 0;
if ei == 0 {
return false;
}
ei -= 1;
self.ac_undo(elems, residual, ei, ri_at[ei], bound);
ri_at[ei] += 1;
}
}
}
true
}
fn ac_scan(
&mut self,
elems: &[(PatVar, RMult)],
residual: &mut [(Cfg::G, Cfg::M)],
ei: usize,
start: usize,
bound: &mut [bool],
) -> Option<usize> {
let (var, mult) = &elems[ei];
bound[ei] = false;
let bound_repr = match *var {
PatVar::Global(gid) => Some(canon(self.index, self.eg, self.globals.binding(gid))),
PatVar::Local(vid) => self.env.nodes[vid.idx()].map(|v| canon(self.index, self.eg, v)),
};
if let Some(repr) = bound_repr {
for ri in start..residual.len() {
if residual[ri].0 == repr
&& mult_matches(
mult,
residual[ri].1.to_u64(),
bound_mult_val(mult, &self.env),
)
{
let take: Cfg::M = match mult {
RMult::Exact(_) => residual[ri].1,
RMult::Var { var: mv, .. } => {
self.env.set_mult(*mv, residual[ri].1);
residual[ri].1
}
};
residual[ri].1 = residual[ri].1.saturating_sub(take);
return Some(ri);
}
}
return None;
}
for ri in start..residual.len() {
let (repr, avail) = residual[ri];
if !mult_matches(mult, avail.to_u64(), bound_mult_val(mult, &self.env)) {
continue;
}
let PatVar::Local(vid) = *var else {
unreachable!()
};
self.env.set(vid, repr);
bound[ei] = true;
let take: Cfg::M = match mult {
RMult::Exact(_) => avail,
RMult::Var { var: mv, .. } => {
self.env.set_mult(*mv, avail);
avail
}
};
residual[ri].1 = avail.saturating_sub(take);
return Some(ri);
}
None
}
fn ac_undo(
&mut self,
elems: &[(PatVar, RMult)],
residual: &mut [(Cfg::G, Cfg::M)],
ei: usize,
ri: usize,
bound: &mut [bool],
) {
let (var, mult) = &elems[ei];
let restore: Cfg::M = match mult {
RMult::Exact(n) => Cfg::M::try_from_u64(*n)
.expect("Exact multiplicity matched a stored one, so it fits the configured width"),
RMult::Var { var: mv, .. } => self.env.get_mult(*mv),
};
residual[ri].1 = residual[ri].1.checked_add(restore).expect(
"ac_undo restores a multiplicity previously subtracted from this entry, so the sum fits",
);
if let PatVar::Local(vid) = *var
&& bound[ei]
{
self.env.clear(vid);
}
bound[ei] = false;
if let RMult::Var { var: mv, .. } = mult {
let earlier_uses = elems[..ei]
.iter()
.any(|(_, m)| matches!(m, RMult::Var { var: v, .. } if *v == *mv));
if !earlier_uses {
self.env.set_mult(*mv, Cfg::M::ZERO);
}
}
}
fn ac_advance(
&mut self,
elems: &[(PatVar, RMult)],
residual: &mut [(Cfg::G, Cfg::M)],
ri_at: &mut [usize],
bound: &mut [bool],
ei: &mut usize,
) -> bool {
if elems.is_empty() || *ei != elems.len() {
return false;
}
let mut e = elems.len() - 1;
loop {
self.ac_undo(elems, residual, e, ri_at[e], bound);
ri_at[e] += 1;
if let Some(ri) = self.ac_scan(elems, residual, e, ri_at[e], bound) {
ri_at[e] = ri;
let mut ok = true;
for e2 in (e + 1)..elems.len() {
ri_at[e2] = 0;
match self.ac_scan(elems, residual, e2, 0, bound) {
Some(ri2) => ri_at[e2] = ri2,
None => {
for undo in (e + 1..e2).rev() {
self.ac_undo(elems, residual, undo, ri_at[undo], bound);
}
ok = false;
break;
}
}
}
if ok {
*ei = elems.len();
return true;
}
self.ac_undo(elems, residual, e, ri_at[e], bound);
ri_at[e] += 1;
continue;
}
ri_at[e] = 0;
if e == 0 {
*ei = 0;
return false;
}
e -= 1;
}
}
fn aci_find_first(
&mut self,
elems: &[PatVar],
residual: &[Cfg::G],
used: &mut crate::containers::bitset::BitSet,
ri_at: &mut [usize],
bound: &mut [bool],
from: usize,
) -> bool {
let mut ei = from;
while ei < elems.len() {
let start = if ei == from { ri_at[ei] } else { 0 };
match self.aci_scan(elems, residual, used, ei, start, bound) {
Some(ri) => {
ri_at[ei] = ri;
ei += 1;
}
None => {
ri_at[ei] = 0;
if ei == 0 {
return false;
}
ei -= 1;
self.aci_undo(elems, used, ei, ri_at[ei], bound);
ri_at[ei] += 1;
}
}
}
true
}
fn aci_scan(
&mut self,
elems: &[PatVar],
residual: &[Cfg::G],
used: &mut crate::containers::bitset::BitSet,
ei: usize,
start: usize,
bound: &mut [bool],
) -> Option<usize> {
let var = elems[ei];
bound[ei] = false;
let bound_repr = match var {
PatVar::Global(gid) => Some(canon(self.index, self.eg, self.globals.binding(gid))),
PatVar::Local(vid) => self.env.nodes[vid.idx()].map(|v| canon(self.index, self.eg, v)),
};
if let Some(repr) = bound_repr {
for ri in start..residual.len() {
if !used.test(ri) && residual[ri] == repr {
used.set(ri);
return Some(ri);
}
}
return None;
}
let PatVar::Local(vid) = var else {
unreachable!()
};
for ri in start..residual.len() {
if used.test(ri) {
continue;
}
self.env.set(vid, residual[ri]);
bound[ei] = true;
used.set(ri);
return Some(ri);
}
None
}
fn aci_undo(
&mut self,
elems: &[PatVar],
used: &mut crate::containers::bitset::BitSet,
ei: usize,
ri: usize,
bound: &mut [bool],
) {
used.clear(ri);
if let PatVar::Local(vid) = elems[ei]
&& bound[ei]
{
self.env.clear(vid);
}
bound[ei] = false;
}
fn aci_advance(
&mut self,
elems: &[PatVar],
residual: &[Cfg::G],
used: &mut crate::containers::bitset::BitSet,
ri_at: &mut [usize],
bound: &mut [bool],
ei: &mut usize,
) -> bool {
if elems.is_empty() || *ei != elems.len() {
return false;
}
let mut e = elems.len() - 1;
loop {
self.aci_undo(elems, used, e, ri_at[e], bound);
ri_at[e] += 1;
if let Some(ri) = self.aci_scan(elems, residual, used, e, ri_at[e], bound) {
ri_at[e] = ri;
let mut ok = true;
for e2 in (e + 1)..elems.len() {
ri_at[e2] = 0;
match self.aci_scan(elems, residual, used, e2, 0, bound) {
Some(ri2) => ri_at[e2] = ri2,
None => {
for undo in (e + 1..e2).rev() {
self.aci_undo(elems, used, undo, ri_at[undo], bound);
}
ok = false;
break;
}
}
}
if ok {
*ei = elems.len();
return true;
}
self.aci_undo(elems, used, e, ri_at[e], bound);
ri_at[e] += 1;
continue;
}
ri_at[e] = 0;
if e == 0 {
*ei = 0;
return false;
}
e -= 1;
}
}
}
enum Enter {
Advanced,
Failed,
Pushed(bool),
}
pub fn run_query_iter<Cfg, L, const T: bool, const P: bool>(
plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
eg: &EGraph<Cfg, L, T, P>,
index: &VariantIndex<'_, Cfg>,
) -> Vec<Match<Cfg>>
where
Cfg: EGraphConfig,
L: LitVal,
MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
let empty: crate::resolve::GlobalCtx<(), Cfg::G> = crate::resolve::GlobalCtx::new();
let mut it = MatchIterator::new(plan, eg, index, &empty);
let mut out = Vec::new();
while it.next_match() {
out.push(it.env().clone());
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::id::{ENodeId, OpId, SortId};
use crate::literal::{NiraLitVal, NiraModel};
use crate::nodes::DefaultConfig;
use crate::registry::{OpRegistry, SortRegistry};
use crate::resolve::MatchShape;
use crate::resolve::resolve;
use crate::schedule::schedule;
use crate::sortcheck::flatten_surface as flatten;
use crate::test_helpers::parse_pattern;
type EG = EGraph<DefaultConfig, NiraLitVal, false, false>;
fn make_eg() -> EG {
let mut eg = EG::from_model(&NiraModel);
let e = eg.intern_sort("IExpr");
eg.register_op2("f", e, e, e);
eg.register_op1("g", e, e);
eg.register_op2("h", e, e, e);
eg.register_op0("a", e);
eg.register_op0("b", e);
eg.register_op0("c", e);
eg.register_a("concat", e, e, crate::registry::AssocDir::Right);
eg.register_mset("add", e, e);
eg.register_set("union", e, e);
eg
}
fn query<const TRACK: bool>(
eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
ops: &OpRegistry<OpId, SortId, TRACK>,
sorts: &SortRegistry<SortId, TRACK>,
srcs: &[&str],
) -> Vec<Match<DefaultConfig>> {
let model = NiraModel;
let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
let fq = flatten(&pats, ops).unwrap();
let rq = resolve(
&fq,
ops,
sorts,
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let plan = schedule(&rq);
let index = IndexStore::build(eg);
let index = VariantIndex::naive(&index);
run_query(
&plan,
eg,
&index,
&crate::resolve::GlobalCtx::<(), _>::new(),
)
}
#[test]
fn empty_egraph_no_matches() {
let eg = make_eg();
let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
assert!(matches.is_empty());
}
#[test]
fn reused_pool_matches_a_fresh_pool() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
eg.rebuild();
let shapes = [
"(f x y)",
"(add x:1 ..rest)",
"(union x ..rest)",
"(concat x y ..rest)",
];
let index = IndexStore::build(&eg);
let index = VariantIndex::naive(&index);
let ng = crate::resolve::GlobalCtx::<(), _>::new();
let plans: Vec<_> = shapes
.iter()
.map(|src| {
let pats = [parse_pattern(src)];
let fq = flatten(&pats, eg.ops()).unwrap();
let rq = resolve(
&fq,
eg.ops(),
eg.sorts(),
&NiraModel,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
schedule(&rq)
})
.collect();
let mut shared = MatchPool::new();
for _ in 0..2 {
for plan in &plans {
let mut fresh = MatchPool::new();
run_query_into(plan, &eg, &index, &ng, &mut fresh);
run_query_into(plan, &eg, &index, &ng, &mut shared);
assert_eq!(shared.len(), fresh.len(), "match count diverged");
let expect: Vec<_> = (0..fresh.len())
.map(|j| env_key(&fresh.clone_match(j), &eg))
.collect();
let got: Vec<_> = (0..shared.len())
.map(|j| env_key(&shared.clone_match(j), &eg))
.collect();
assert_eq!(got, expect, "reused pool produced different bindings");
}
}
}
#[test]
fn single_node_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
assert_eq!(matches.len(), 1);
}
#[test]
fn two_f_nodes() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _f1 = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let _f2 = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, a]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
assert_eq!(matches.len(), 2);
}
#[test]
fn nested_pattern() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, g_a]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x (g y))"]);
assert_eq!(matches.len(), 1);
}
#[test]
fn nested_no_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x (g y))"]);
assert!(matches.is_empty());
}
#[test]
fn nonlinear_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, a]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x x)"]);
assert_eq!(matches.len(), 1);
}
#[test]
fn nonlinear_no_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x x)"]);
assert!(matches.is_empty());
}
#[test]
fn multi_pattern() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let _g = eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)", "(g y)"]);
assert_eq!(matches.len(), 1);
}
#[test]
fn multi_pattern_no_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let _g = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]); let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)", "(g y)"]);
assert!(matches.is_empty());
}
#[test]
fn binding_values_correct() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
let model = NiraModel;
let pat = parse_pattern("(f x y)");
let fq = flatten(&[pat], eg.ops()).unwrap();
let rq = resolve(
&fq,
eg.ops(),
eg.sorts(),
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let plan = schedule(&rq);
let index = IndexStore::build(&eg);
let index = VariantIndex::naive(&index);
let matches = run_query(
&plan,
&eg,
&index,
&crate::resolve::GlobalCtx::<(), _>::new(),
);
assert_eq!(matches.len(), 1);
let x = rq.shape.find_var("x").unwrap();
let y = rq.shape.find_var("y").unwrap();
assert_eq!(eg.find_const(matches[0].get(x)), eg.find_const(a));
assert_eq!(eg.find_const(matches[0].get(y)), eg.find_const(b));
}
#[test]
fn deep_nesting() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
let g_g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[g_a]);
let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, g_g_a]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x (g (g y)))"]);
assert_eq!(matches.len(), 1);
}
#[test]
fn ac_exact_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:1 y:1)"]);
assert_eq!(matches.len(), 2); }
#[test]
fn ac_exact_no_match_extra() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:1 y:1)"]);
assert!(matches.is_empty());
}
#[test]
fn ac_subset_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:1 ..rest)"]);
assert_eq!(matches.len(), 3);
}
#[test]
fn ac_mult_exact() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:2 ..rest)"]);
assert_eq!(matches.len(), 0);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:3 ..rest)"]);
assert_eq!(matches.len(), 1);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:k>=2 ..rest)"]);
assert_eq!(matches.len(), 1);
}
#[test]
fn ac_mult_exact_no_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:2 ..rest)"]);
assert!(matches.is_empty());
}
#[test]
fn a_exact_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _cat = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(concat x y)"]);
assert_eq!(matches.len(), 1);
}
#[test]
fn a_exact_wrong_length() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let _cat = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(concat x y)"]);
assert!(matches.is_empty());
}
#[test]
fn a_prefix_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let _cat = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x)"]);
assert_eq!(matches.len(), 1);
}
#[test]
fn a_sliding_window() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let _cat = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
let matches = query(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x ..suf)"]);
assert_eq!(matches.len(), 3);
}
fn query_named<const TRACK: bool>(
eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
ops: &OpRegistry<OpId, SortId, TRACK>,
sorts: &SortRegistry<SortId, TRACK>,
srcs: &[&str],
) -> (Vec<Match<DefaultConfig>>, MatchShape) {
let model = NiraModel;
let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
let fq = flatten(&pats, ops).unwrap();
let rq = resolve(
&fq,
ops,
sorts,
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let plan = schedule(&rq);
let index = IndexStore::build(eg);
let index = VariantIndex::naive(&index);
(
run_query(
&plan,
eg,
&index,
&crate::resolve::GlobalCtx::<(), _>::new(),
),
rq.shape,
)
}
fn binding_map<const TRACK: bool>(
m: &Match<DefaultConfig>,
vars: &MatchShape,
eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
) -> Vec<(String, String)> {
vars.nodes
.iter()
.enumerate()
.filter(|(_, name)| !name.starts_with('#')) .filter_map(|(vi, name)| {
m.nodes[vi].map(|g| (name.clone(), eg.node_op_name(g).to_string()))
})
.collect()
}
fn has_binding<const TRACK: bool>(
matches: &[Match<DefaultConfig>],
vars: &MatchShape,
eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
expected: &[(&str, &str)],
) -> bool {
matches.iter().any(|m| {
let bm = binding_map(m, vars, eg);
expected
.iter()
.all(|&(var, op)| bm.iter().any(|(v, o)| v == var && o == op))
})
}
#[test]
fn verify_plain_f_x_y() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[b, g_a]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
assert_eq!(matches.len(), 2);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "g")]));
}
#[test]
fn verify_nested_f_x_g_y() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[b, g_a]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(f x (g y))"]);
assert_eq!(matches.len(), 1);
assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "a")]));
}
#[test]
fn verify_ac_subset() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:1 ..rest)"]);
assert_eq!(matches.len(), 3);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a")]));
assert!(has_binding(&matches, &vars, &eg, &[("x", "b")]));
assert!(has_binding(&matches, &vars, &eg, &[("x", "c")]));
}
#[test]
fn verify_ac_exact_two_of_three() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:1 y:1)"]);
assert_eq!(matches.len(), 2);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "a")]));
}
#[test]
fn verify_ac_mult() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b]);
let (matches, _vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:2 ..rest)"]);
assert_eq!(matches.len(), 0);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k>=2 ..rest)"]);
assert_eq!(matches.len(), 1);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a")]));
}
#[test]
fn verify_a_exact() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat x y z)"]);
assert_eq!(matches.len(), 1);
assert!(has_binding(
&matches,
&vars,
&eg,
&[("x", "a"), ("y", "b"), ("z", "c")]
));
}
#[test]
fn verify_a_sliding_window() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x ..suf)"]);
assert_eq!(matches.len(), 3);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a")]));
assert!(has_binding(&matches, &vars, &eg, &[("x", "b")]));
assert!(has_binding(&matches, &vars, &eg, &[("x", "c")]));
}
#[test]
fn verify_a_suffix() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat x y ..suf)"]);
assert_eq!(matches.len(), 1);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
}
#[test]
fn verify_multi_pattern_bindings() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(f x y)", "(g y)"]);
assert_eq!(matches.len(), 1);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
}
fn fmt_match<const TRACK: bool>(
m: &Match<DefaultConfig>,
vars: &MatchShape,
eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
shape: &crate::resolve::MatchShape,
) -> String {
let mut parts = Vec::new();
for (vi, name) in vars.nodes.iter().enumerate() {
if name.starts_with('#') {
continue;
}
if let Some(g) = m.nodes[vi] {
parts.push(format!("{}={}", name, eg.node_op_name(g)));
}
}
for i in 0..shape.num_seq_vars() {
let s = m.seq_slice(SeqVarId(i as u16));
let elems: Vec<&str> = s.iter().map(|&g| eg.node_op_name(g)).collect();
parts.push(format!("seq{}=[{}]", i, elems.join(", ")));
}
for i in 0..shape.num_set_vars() {
let s = m.set_slice(SetVarId(i as u16));
let elems: Vec<&str> = s.iter().map(|&g| eg.node_op_name(g)).collect();
parts.push(format!("set{}={{{}}}", i, elems.join(", ")));
}
for i in 0..shape.num_mset_vars() {
let s = m.mset_slice(MsetVarId(i as u16));
let elems: Vec<String> = s
.iter()
.map(|c| {
format!(
"{}:{}",
eg.node_op_name(DefaultConfig::mset_child_id(c)),
DefaultConfig::mset_child_mult(c)
)
})
.collect();
parts.push(format!("mset{}={{{}}}", i, elems.join(", ")));
}
for i in 0..shape.num_mult_vars() {
parts.push(format!("mult{}={}", i, m.mults[i]));
}
parts.join(", ")
}
fn check<const TRACK: bool>(
eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
ops: &OpRegistry<OpId, SortId, TRACK>,
sorts: &SortRegistry<SortId, TRACK>,
label: &str,
srcs: &[&str],
expected_count: usize,
expected: &[&[(&str, &str)]],
) {
let model = NiraModel;
let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
let fq = flatten(&pats, ops).unwrap();
let rq = resolve(
&fq,
ops,
sorts,
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let plan = schedule(&rq);
let index = IndexStore::build(eg);
let index = VariantIndex::naive(&index);
let matches = run_query(
&plan,
eg,
&index,
&crate::resolve::GlobalCtx::<(), _>::new(),
);
println!("\n--- {label} ---");
println!(" pattern: {}", srcs.join(" , "));
println!("{} got match(es):", matches.len());
for (i, m) in matches.iter().enumerate() {
println!(" [{i}] {{ {} }}", fmt_match(m, &rq.shape, eg, &rq.shape));
}
assert_eq!(matches.len(), expected_count, "{label}: wrong match count");
for (ei, exp) in expected.iter().enumerate() {
assert!(
has_binding(&matches, &rq.shape, eg, exp),
"{label}: expected binding [{ei}] {:?} not found",
exp
);
}
}
#[test]
fn ac_comprehensive() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b]);
println!("\n=== AC node: add(a,b) = a:1, b:1 ===");
check(
&eg,
eg.ops(),
eg.sorts(),
"AC exact {x:1 y:1} vs {a:1,b:1}",
&["(add x:1 y:1)"],
2,
&[&[("x", "a"), ("y", "b")], &[("x", "b"), ("y", "a")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"AC subset {x:1 ..rest} vs {a:1,b:1}",
&["(add x:1 ..rest)"],
2,
&[&[("x", "a")], &[("x", "b")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"AC exact {x:1} vs {a:1,b:1}",
&["(add x:1)"],
0,
&[],
);
}
#[test]
fn ac_with_multiplicities() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, b]);
println!("\n=== AC node: add(a,a,a,b,b) = a:3, b:2 ===");
check(
&eg,
eg.ops(),
eg.sorts(),
"AC {x:2 ..rest} vs {a:3,b:2}",
&["(add x:2 ..rest)"],
1,
&[&[("x", "b")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"AC {x:3 ..rest} vs {a:3,b:2}",
&["(add x:3 ..rest)"],
1,
&[&[("x", "a")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"AC {x:4 ..rest} vs {a:3,b:2}",
&["(add x:4 ..rest)"],
0,
&[],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"AC {x:2 y:1 ..rest} vs {a:3,b:2}",
&["(add x:2 y:1 ..rest)"],
0,
&[],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"AC exact {x:3 y:2} vs {a:3,b:2}",
&["(add x:3 y:2)"],
1,
&[&[("x", "a"), ("y", "b")]],
);
}
#[test]
fn aci_comprehensive() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c, a]);
println!("\n=== ACI node: union(a,b,c,a) = a, b, c ===");
check(
&eg,
eg.ops(),
eg.sorts(),
"ACI exact {x y z} vs {a,b,c}",
&["(union x y z)"],
6,
&[
&[("x", "a"), ("y", "b"), ("z", "c")],
&[("x", "a"), ("y", "c"), ("z", "b")],
&[("x", "b"), ("y", "a"), ("z", "c")],
&[("x", "b"), ("y", "c"), ("z", "a")],
&[("x", "c"), ("y", "a"), ("z", "b")],
&[("x", "c"), ("y", "b"), ("z", "a")],
],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"ACI {x ..rest} vs {a,b,c}",
&["(union x ..rest)"],
3,
&[&[("x", "a")], &[("x", "b")], &[("x", "c")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"ACI {x y ..rest} vs {a,b,c}",
&["(union x y ..rest)"],
6,
&[
&[("x", "a"), ("y", "b")],
&[("x", "a"), ("y", "c")],
&[("x", "b"), ("y", "a")],
&[("x", "b"), ("y", "c")],
&[("x", "c"), ("y", "a")],
&[("x", "c"), ("y", "b")],
],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"ACI {..rest} vs {a,b,c}",
&["(union ..rest)"],
1,
&[],
);
}
#[test]
fn aci_x_rest_printed() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c, d]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(union x ..rest)"]);
println!("\n=== (union x ..rest) vs ACI node a, b, c, g(a) ===");
println!(" {} matches:", matches.len());
let x_var = vars.find_var("x").unwrap();
let rest_id = SetVarId(0);
for (i, m) in matches.iter().enumerate() {
let x_name = eg.node_op_name(m.get(x_var));
let rest_slice = m.set_slice(rest_id);
let rest_names: Vec<&str> = rest_slice.iter().map(|&g| eg.node_op_name(g)).collect();
println!(" [{i}] x={x_name} rest={{{}}}", rest_names.join(", "));
assert_eq!(rest_slice.len(), 3, "rest should have 3 elements");
}
assert_eq!(matches.len(), 4);
let mut x_ops: Vec<String> = matches
.iter()
.map(|m| eg.node_op_name(m.get(x_var)).to_string())
.collect();
x_ops.sort();
assert_eq!(x_ops, ["a", "b", "c", "g"]);
}
#[test]
fn a_comprehensive() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
println!("\n=== A node: concat(a, b, c) = a, b, c ===");
check(
&eg,
eg.ops(),
eg.sorts(),
"A exact [x y z] vs [a,b,c]",
&["(concat x y z)"],
1,
&[&[("x", "a"), ("y", "b"), ("z", "c")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"A exact [x y] vs [a,b,c]",
&["(concat x y)"],
0,
&[],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"A prefix [..pre x] vs [a,b,c]",
&["(concat ..pre x)"],
1,
&[&[("x", "c")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"A suffix [x ..suf] vs [a,b,c]",
&["(concat x ..suf)"],
1,
&[&[("x", "a")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"A suffix [x y ..suf] vs [a,b,c]",
&["(concat x y ..suf)"],
1,
&[&[("x", "a"), ("y", "b")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"A sliding [..pre x ..suf] vs [a,b,c]",
&["(concat ..pre x ..suf)"],
3,
&[&[("x", "a")], &[("x", "b")], &[("x", "c")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"A sliding [..pre x y ..suf] vs [a,b,c]",
&["(concat ..pre x y ..suf)"],
2,
&[&[("x", "a"), ("y", "b")], &[("x", "b"), ("y", "c")]],
);
check(
&eg,
eg.ops(),
eg.sorts(),
"A [..pre ..suf] vs [a,b,c]",
&["(concat ..pre ..suf)"],
4,
&[],
); }
#[test]
fn aci_two_vars_plus_rest() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c, d]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(union x y ..rest)"]);
let x_var = vars.find_var("x").unwrap();
let y_var = vars.find_var("y").unwrap();
println!("\n=== (union x y ..rest) vs a, b, c, g(a) ===");
let rest_id = SetVarId(0);
for (i, m) in matches.iter().enumerate() {
let xn = eg.node_op_name(m.get(x_var));
let yn = eg.node_op_name(m.get(y_var));
let rest: Vec<&str> = m
.set_slice(rest_id)
.iter()
.map(|&g| eg.node_op_name(g))
.collect();
println!(" [{i}] x={xn}, y={yn}, rest={{{}}}", rest.join(", "));
}
assert_eq!(matches.len(), 12);
let names = ["a", "b", "c", "g"];
for &x in &names {
for &y in &names {
if x == y {
continue;
}
assert!(
has_binding(&matches, &vars, &eg, &[("x", x), ("y", y)]),
"missing x={x}, y={y}"
);
}
}
}
#[test]
fn ac_two_vars_plus_rest() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:1 y:1 ..rest)"]);
let x_var = vars.find_var("x").unwrap();
let y_var = vars.find_var("y").unwrap();
println!("\n=== (add x:1 y:1 ..rest) vs a:1, b:1, c:1 ===");
let rest_id = MsetVarId(0);
for (i, m) in matches.iter().enumerate() {
let xn = eg.node_op_name(m.get(x_var));
let yn = eg.node_op_name(m.get(y_var));
let rest: Vec<String> = m
.mset_slice(rest_id)
.iter()
.map(|c| {
let g = DefaultConfig::mset_child_id(c);
let k = DefaultConfig::mset_child_mult(c);
format!("{}:{}", eg.node_op_name(g), k)
})
.collect();
println!(" [{i}] x={xn}, y={yn}, rest={{{}}}", rest.join(", "));
}
assert_eq!(matches.len(), 6);
let names = ["a", "b", "c"];
for &x in &names {
for &y in &names {
if x == y {
continue;
}
assert!(
has_binding(&matches, &vars, &eg, &[("x", x), ("y", y)]),
"missing x={x}, y={y}"
);
}
}
}
#[test]
fn ac_two_vars_with_mult_plus_rest() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, b, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:2 y:1 ..rest)"]);
let x_var = vars.find_var("x").unwrap();
let y_var = vars.find_var("y").unwrap();
println!("\n=== (add x:2 y:1 ..rest) vs a:3, b:2, c:1 ===");
let rest_id = MsetVarId(0);
for (i, m) in matches.iter().enumerate() {
let xn = eg.node_op_name(m.get(x_var));
let yn = eg.node_op_name(m.get(y_var));
let rest: Vec<String> = m
.mset_slice(rest_id)
.iter()
.map(|c| {
let g = DefaultConfig::mset_child_id(c);
let k = DefaultConfig::mset_child_mult(c);
format!("{}:{}", eg.node_op_name(g), k)
})
.collect();
println!(" [{i}] x={xn}, y={yn}, rest={{{}}}", rest.join(", "));
}
assert_eq!(matches.len(), 1);
assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "c")]));
}
#[test]
fn a_prefix_suffix_all_splits() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c, d]);
let (matches, _vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat ..pre ..suf)"]);
println!("\n=== (concat ..pre ..suf) vs a, b, c, g(a) ===");
println!("{} matches (split points):", matches.len());
let pre_id = SeqVarId(0);
let suf_id = SeqVarId(1);
for (i, m) in matches.iter().enumerate() {
let pre: Vec<&str> = m
.seq_slice(pre_id)
.iter()
.map(|&g| eg.node_op_name(g))
.collect();
let suf: Vec<&str> = m
.seq_slice(suf_id)
.iter()
.map(|&g| eg.node_op_name(g))
.collect();
println!(" [{i}] pre=[{}], suf=[{}]", pre.join(", "), suf.join(", "));
}
assert_eq!(matches.len(), 5);
}
#[test]
fn a_prefix_xy_suffix_all_positions() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c, d]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x y ..suf)"]);
let x_var = vars.find_var("x").unwrap();
let y_var = vars.find_var("y").unwrap();
println!("\n=== (concat ..pre x y ..suf) vs a, b, c, g(a) ===");
let pre_id = SeqVarId(0);
let suf_id = SeqVarId(1);
for (i, m) in matches.iter().enumerate() {
let xn = eg.node_op_name(m.get(x_var));
let yn = eg.node_op_name(m.get(y_var));
let pre: Vec<&str> = m
.seq_slice(pre_id)
.iter()
.map(|&g| eg.node_op_name(g))
.collect();
let suf: Vec<&str> = m
.seq_slice(suf_id)
.iter()
.map(|&g| eg.node_op_name(g))
.collect();
println!(
" [{i}] pre=[{}], x={xn}, y={yn}, suf=[{}]",
pre.join(", "),
suf.join(", ")
);
}
assert_eq!(matches.len(), 3);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")])); assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "c")])); assert!(has_binding(&matches, &vars, &eg, &[("x", "c"), ("y", "g")])); }
fn query_both<const TRACK: bool>(
eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
ops: &OpRegistry<OpId, SortId, TRACK>,
sorts: &SortRegistry<SortId, TRACK>,
srcs: &[&str],
) -> (Vec<Match<DefaultConfig>>, Vec<Match<DefaultConfig>>) {
let model = NiraModel;
let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
let fq = flatten(&pats, ops).unwrap();
let rq = resolve(
&fq,
ops,
sorts,
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let plan = schedule(&rq);
let index = IndexStore::build(eg);
let index = VariantIndex::naive(&index);
let recursive = run_query(
&plan,
eg,
&index,
&crate::resolve::GlobalCtx::<(), _>::new(),
);
let iter = run_query_iter(&plan, eg, &index);
(recursive, iter)
}
fn env_key(m: &Match<DefaultConfig>, eg: &EG) -> Vec<Option<u32>> {
m.nodes
.iter()
.map(|o| o.map(|g| eg.find_const(g).raw()))
.collect()
}
fn assert_same(
label: &str,
recursive: &[Match<DefaultConfig>],
iter: &[Match<DefaultConfig>],
eg: &EG,
) {
assert_eq!(
recursive.len(),
iter.len(),
"{label}: count mismatch (recursive={}, iter={})",
recursive.len(),
iter.len()
);
let mut rkeys: Vec<_> = recursive.iter().map(|m| env_key(m, eg)).collect();
let mut ikeys: Vec<_> = iter.iter().map(|m| env_key(m, eg)).collect();
rkeys.sort();
ikeys.sort();
assert_eq!(rkeys, ikeys, "{label}: binding mismatch");
}
#[test]
fn iter_vs_recursive_plain() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[b, g_a]);
for pat in &["(f x y)", "(f x (g y))", "(f x x)"] {
let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &[pat]);
assert_same(pat, &r, &i, &eg);
}
}
#[test]
fn iter_vs_recursive_multi_pattern() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &["(f x y)", "(g y)"]);
assert_same("multi", &r, &i, &eg);
}
#[test]
fn iter_vs_recursive_ac() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, b]);
for pat in &[
"(add x:1 y:1)",
"(add x:1 ..rest)",
"(add x:2 ..rest)",
"(add x:2 y:1 ..rest)",
"(add x:3 y:2)",
] {
let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &[pat]);
assert_same(pat, &r, &i, &eg);
}
}
#[test]
fn iter_vs_recursive_aci() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c, d]);
for pat in &[
"(union x y z)",
"(union x ..rest)",
"(union x y ..rest)",
"(union ..rest)",
] {
let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &[pat]);
assert_same(pat, &r, &i, &eg);
}
}
#[test]
fn iter_vs_recursive_a() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
for pat in &[
"(concat x y z)",
"(concat ..pre x)",
"(concat x ..suf)",
"(concat ..pre x ..suf)",
"(concat ..pre x y ..suf)",
"(concat ..pre ..suf)",
] {
let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &[pat]);
assert_same(pat, &r, &i, &eg);
}
}
#[test]
fn bench_recursive_vs_iterator() {
use crate::registry::AssocDir;
let model = NiraModel;
let mut eg = EGraph::<DefaultConfig, NiraLitVal, false, false>::from_model(&model);
let e = eg.intern_sort("IExpr");
let leaf_names: Vec<String> = (0..200).map(|i| format!("n{i}")).collect();
for name in &leaf_names {
eg.register_op0(name, e);
}
eg.register_op2("f", e, e, e);
eg.register_op1("g", e, e);
eg.register_op2("h", e, e, e);
eg.register_a("concat", e, e, AssocDir::Right);
eg.register_mset("add", e, e);
eg.register_set("union", e, e);
let mut leaves = Vec::new();
for name in &leaf_names {
leaves.push(eg.add(eg.ops().id_by_name(name).unwrap(), &[]));
}
for i in 0..100 {
let a = leaves[i];
let b = leaves[i + 100];
eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("h").unwrap(), &[a, b]);
}
for i in 0..50 {
eg.add(
eg.ops().id_by_name("add").unwrap(),
&[
leaves[i],
leaves[i + 50],
leaves[i + 100],
leaves[i],
leaves[i + 50],
],
);
}
for i in 0..50 {
eg.add(
eg.ops().id_by_name("union").unwrap(),
&[leaves[i], leaves[i + 50], leaves[i + 100], leaves[i + 150]],
);
}
for i in 0..50 {
eg.add(
eg.ops().id_by_name("concat").unwrap(),
&[leaves[i], leaves[i + 50], leaves[i + 100]],
);
}
let patterns: &[&str] = &[
"(f x y)",
"(f x (g y))",
"(add x:1 ..rest)",
"(add x:1 y:1 ..rest)",
"(union x ..rest)",
"(union x y ..rest)",
"(concat ..pre x ..suf)",
"(concat ..pre x y ..suf)",
];
let model = NiraModel;
let index = IndexStore::build(&eg);
let index = VariantIndex::naive(&index);
for pat in patterns {
let p = parse_pattern(pat);
let fq = flatten(&[p], eg.ops()).unwrap();
let rq = resolve(
&fq,
eg.ops(),
eg.sorts(),
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let plan = schedule(&rq);
let iters = 100;
let t0 = std::time::Instant::now();
let mut n_rec = 0;
for _ in 0..iters {
n_rec = run_query(
&plan,
&eg,
&index,
&crate::resolve::GlobalCtx::<(), _>::new(),
)
.len();
}
let d_rec = t0.elapsed();
let t1 = std::time::Instant::now();
let mut n_iter = 0;
for _ in 0..iters {
n_iter = run_query_iter(&plan, &eg, &index).len();
}
let d_iter = t1.elapsed();
assert_eq!(n_rec, n_iter);
let us_rec = d_rec.as_micros() as f64 / iters as f64;
let us_iter = d_iter.as_micros() as f64 / iters as f64;
let ratio = us_iter / us_rec;
println!(
"{pat:40} matches={n_rec:5} rec={us_rec:8.1}µs iter={us_iter:8.1}µs ratio={ratio:.2}x"
);
}
}
fn make_match_set<const TRACK: bool>(
eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
ops: &OpRegistry<OpId, SortId, TRACK>,
sorts: &SortRegistry<SortId, TRACK>,
srcs: &[&str],
) -> (MatchSet<DefaultConfig>, crate::resolve::MatchShape) {
let model = NiraModel;
let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
let fq = flatten(&pats, ops).unwrap();
let rq = resolve(
&fq,
ops,
sorts,
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let shape = rq.shape.clone();
let plan = schedule(&rq);
let index = IndexStore::build(eg);
let index = VariantIndex::naive(&index);
let ng = crate::resolve::GlobalCtx::<(), _>::new();
let mut iter = MatchIterator::new(&plan, eg, &index, &ng);
let set = iter.collect_set(&shape);
(set, shape)
}
fn ni(shape: &crate::resolve::MatchShape, name: &str) -> VarId {
let i = shape.nodes.iter().position(|n| n == name).unwrap();
VarId::new(i as u16)
}
#[test]
fn matchset_plain_bindings() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
eg.add(eg.ops().id_by_name("f").unwrap(), &[b, a]);
let (set, shape) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
assert_eq!(set.count, 2);
let xi = ni(&shape, "x");
let yi = ni(&shape, "y");
let mut pairs: Vec<_> = (0..set.count)
.map(|j| {
(
eg.find_const(set.get_node(xi, j)).raw(),
eg.find_const(set.get_node(yi, j)).raw(),
)
})
.collect();
pairs.sort();
let a_r = eg.find_const(a).raw();
let b_r = eg.find_const(b).raw();
let mut expected = vec![(a_r, b_r), (b_r, a_r)];
expected.sort();
assert_eq!(pairs, expected);
}
#[test]
fn matchset_ac_with_mset_rest() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
let (set, shape) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(add x:1 ..rest)"]);
assert_eq!(set.count, 3);
assert_eq!(shape.msets.len(), 1);
let xi = ni(&shape, "x");
for j in 0..set.count {
let rest_slice = set.mset_slice(MsetVarId(0), j);
assert_eq!(
rest_slice.len(),
2,
"match {j}: rest should have 2 elements"
);
let mut ids: Vec<u32> = rest_slice
.iter()
.map(|c| eg.find_const(DefaultConfig::mset_child_id(c)).raw())
.collect();
ids.push(eg.find_const(set.get_node(xi, j)).raw());
ids.sort();
let mut orig = vec![
eg.find_const(a).raw(),
eg.find_const(b).raw(),
eg.find_const(c).raw(),
];
orig.sort();
assert_eq!(ids, orig, "match {j}: recomposition failed");
}
}
#[test]
fn matchset_aci_with_set_rest() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c]);
let (set, shape) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(union x ..rest)"]);
assert_eq!(set.count, 3);
assert_eq!(shape.sets.len(), 1);
let xi = ni(&shape, "x");
for j in 0..set.count {
let rest_slice = set.set_slice(SetVarId(0), j);
assert_eq!(rest_slice.len(), 2);
let mut ids: Vec<u32> = rest_slice.iter().map(|&g| eg.find_const(g).raw()).collect();
ids.push(eg.find_const(set.get_node(xi, j)).raw());
ids.sort();
let mut orig = vec![
eg.find_const(a).raw(),
eg.find_const(b).raw(),
eg.find_const(c).raw(),
];
orig.sort();
assert_eq!(ids, orig, "match {j}: recomposition failed");
}
}
#[test]
fn matchset_a_sliding_window() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
let (set, shape) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x ..suf)"]);
assert_eq!(set.count, 3);
assert_eq!(shape.seqs.len(), 2);
let xi = ni(&shape, "x");
for j in 0..set.count {
let pre_s = set.seq_slice(SeqVarId(0), j);
let suf_s = set.seq_slice(SeqVarId(1), j);
let mut recomp: Vec<u32> = pre_s.iter().map(|&g| eg.find_const(g).raw()).collect();
recomp.push(eg.find_const(set.get_node(xi, j)).raw());
recomp.extend(suf_s.iter().map(|&g| eg.find_const(g).raw()));
let orig: Vec<u32> = [a, b, c].iter().map(|&g| eg.find_const(g).raw()).collect();
assert_eq!(recomp, orig, "match {j}: recomposition failed");
}
}
#[test]
fn matchset_agrees_with_vec_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, b, c]);
let model = NiraModel;
let pat = parse_pattern("(add x:1 y:1 ..rest)");
let fq = flatten(&[pat], eg.ops()).unwrap();
let rq = resolve(
&fq,
eg.ops(),
eg.sorts(),
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let plan = schedule(&rq);
let index = IndexStore::build(&eg);
let index = VariantIndex::naive(&index);
let ng = crate::resolve::GlobalCtx::<(), _>::new();
let vec_matches = run_query(&plan, &eg, &index, &ng);
let shape = rq.shape.clone();
let mut iter = MatchIterator::new(&plan, &eg, &index, &ng);
let set = iter.collect_set(&shape);
assert_eq!(vec_matches.len(), set.count);
let xi = ni(&shape, "x");
let yi = ni(&shape, "y");
let x_vid = shape.find_var("x").unwrap();
let y_vid = shape.find_var("y").unwrap();
for j in 0..set.count {
assert_eq!(
eg.find_const(set.get_node(xi, j)),
eg.find_const(vec_matches[j].get(x_vid))
);
assert_eq!(
eg.find_const(set.get_node(yi, j)),
eg.find_const(vec_matches[j].get(y_vid))
);
assert_eq!(
set.mset_slice(MsetVarId(0), j).len(),
vec_matches[j].mset_slice(MsetVarId(0)).len()
);
}
}
#[test]
fn matchset_empty() {
let eg = make_eg();
let (set, _) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
assert_eq!(set.count, 0);
}
#[test]
fn cloned_iter_filter_take() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c]);
let model = NiraModel;
let pat = parse_pattern("(union x ..rest)");
let fq = flatten(&[pat], eg.ops()).unwrap();
let rq = resolve(
&fq,
eg.ops(),
eg.sorts(),
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let plan = schedule(&rq);
let index = IndexStore::build(&eg);
let index = VariantIndex::naive(&index);
let x = rq.shape.find_var("x").unwrap();
let ng = crate::resolve::GlobalCtx::<(), _>::new();
let iter = MatchIterator::new(&plan, &eg, &index, &ng);
let filtered: Vec<Match<DefaultConfig>> = iter
.cloned_iter()
.filter(|m| eg.find_const(m.get(x)) != eg.find_const(a))
.take(2)
.collect();
assert_eq!(filtered.len(), 2);
for m in &filtered {
assert_ne!(eg.find_const(m.get(x)), eg.find_const(a));
}
}
#[test]
fn ac_concrete_with_higher_mult() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, b]);
let (matches, shape) = query_named(&eg, eg.ops(), eg.sorts(), &["(add (a) ..rest)"]);
eprintln!("=== (add (a) ..rest) against {{a:2, b:1}} ===");
eprintln!("match count: {}", matches.len());
for (i, m) in matches.iter().enumerate() {
let bindings = binding_map(m, &shape, &eg);
eprintln!(" match {i}: {bindings:?}");
for (mi, name) in shape.msets.iter().enumerate() {
let (start, len) = m.mset_spans[mi];
let rest: Vec<_> = m.mset_pool[start as usize..(start + len) as usize]
.iter()
.map(|c| format!("{:?}", c))
.collect();
eprintln!(" {name} = [{rest}]", rest = rest.join(", "));
}
}
let (matches2, shape2) = query_named(&eg, eg.ops(), eg.sorts(), &["(add (a):k ..rest)"]);
eprintln!("\n=== (add (a):k ..rest) against {{a:2, b:1}} ===");
eprintln!("match count: {}", matches2.len());
for (i, m) in matches2.iter().enumerate() {
let bindings = binding_map(m, &shape2, &eg);
eprintln!(" match {i}: {bindings:?}");
for (mi, name) in shape2.msets.iter().enumerate() {
let (start, len) = m.mset_spans[mi];
let rest: Vec<_> = m.mset_pool[start as usize..(start + len) as usize]
.iter()
.map(|c| format!("{:?}", c))
.collect();
eprintln!(" {name} = [{rest}]", rest = rest.join(", "));
}
for (mi, name) in shape2.mults.iter().enumerate() {
eprintln!(" {name} = {}", m.mults[mi]);
}
}
}
#[test]
fn ac_constraint_ge() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, c, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k>=2 ..rest)"]);
eprintln!("\n=== (add x:k>=2 ..rest) against {{a:3, b:1, c:2}} ===");
for (i, m) in matches.iter().enumerate() {
let bindings = binding_map(m, &vars, &eg);
let k = m.mults[0];
eprintln!(" match {i}: {bindings:?}, k={k}");
}
assert_eq!(matches.len(), 2);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a")]));
assert!(has_binding(&matches, &vars, &eg, &[("x", "c")]));
}
#[test]
fn ac_constraint_le() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, c, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k<=2 ..rest)"]);
eprintln!("\n=== (add x:k<=2 ..rest) against {{a:3, b:1, c:2}} ===");
for (i, m) in matches.iter().enumerate() {
let bindings = binding_map(m, &vars, &eg);
let k = m.mults[0];
eprintln!(" match {i}: {bindings:?}, k={k}");
}
assert_eq!(matches.len(), 2);
assert!(has_binding(&matches, &vars, &eg, &[("x", "b")]));
assert!(has_binding(&matches, &vars, &eg, &[("x", "c")]));
}
#[test]
fn ac_nonlinear_mult_same_count() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, b, b, c, c, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k y:k ..rest)"]);
eprintln!("\n=== (add x:k y:k ..rest) against {{a:2, b:2, c:3}} ===");
for (i, m) in matches.iter().enumerate() {
let bindings = binding_map(m, &vars, &eg);
let k = m.mults[0];
eprintln!(" match {i}: {bindings:?}, k={k}");
}
assert_eq!(matches.len(), 2);
assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "a")]));
}
#[test]
fn ac_nonlinear_mult_no_match() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, b, c, c, c]);
let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k y:k ..rest)"]);
eprintln!("\n=== (add x:k y:k ..rest) against {{a:1, b:2, c:3}} ===");
for (i, m) in matches.iter().enumerate() {
let bindings = binding_map(m, &vars, &eg);
let k = m.mults[0];
eprintln!(" match {i}: {bindings:?}, k={k}");
}
assert_eq!(matches.len(), 0);
}
#[test]
fn ac_nonlinear_empty_interval() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a]);
let model = NiraModel;
let pats: Vec<_> = ["(add x:k>=3 y:k<=1 ..rest)"]
.iter()
.map(|s| parse_pattern(s))
.collect();
let fq = flatten(&pats, eg.ops()).unwrap();
let result = resolve(
&fq,
eg.ops(),
eg.sorts(),
&model,
&crate::resolve::GlobalCtx::<_, ()>::new(),
);
eprintln!("\n=== (add x:k>=3 y:k<=1 ..rest) — empty interval ===");
eprintln!("resolve result: {result:?}");
assert!(result.is_err(), "expected unsatisfiable interval error");
}
#[test]
fn ac_nonlinear_narrow_interval() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, b, c, c, c]);
let (matches, vars) =
query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k>=2 y:k<=3 ..rest)"]);
eprintln!("\n=== (add x:k>=2 y:k<=3 ..rest) against {{a:1, b:2, c:3}} ===");
for (i, m) in matches.iter().enumerate() {
let bindings = binding_map(m, &vars, &eg);
let k = m.mults[0];
eprintln!(" match {i}: {bindings:?}, k={k}");
}
assert_eq!(matches.len(), 0);
}
fn plan_driven_from(
eg: &EG,
srcs: &[&str],
first: &str,
ops_in_query: &[&str],
) -> (RQ, QueryPlan<OpId, u32, NiraLitVal>) {
let rq = resolve_srcs(eg, srcs);
let mut stats = crate::schedule::IndexStats::<OpId>::new();
for name in ops_in_query {
stats
.op_card
.insert(eg.ops().id_by_name(name).unwrap(), 1000);
}
stats.op_card.insert(eg.ops().id_by_name(first).unwrap(), 0);
let plan = crate::schedule::schedule_with_stats(&rq, &stats);
(rq, plan)
}
type RQ = crate::resolve::ResolvedQuery<OpId, SortId, NiraLitVal>;
fn resolve_srcs(eg: &EG, srcs: &[&str]) -> RQ {
let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
let fq = flatten(&pats, eg.ops()).unwrap();
resolve(
&fq,
eg.ops(),
eg.sorts(),
&NiraModel,
&crate::resolve::GlobalCtx::<SortId, ()>::new(),
)
.unwrap()
}
fn match_keys(
eg: &EG,
rq: &RQ,
plan: &QueryPlan<OpId, u32, NiraLitVal>,
index: &IndexStore<DefaultConfig>,
) -> Vec<Vec<Option<u32>>> {
let vindex = VariantIndex::naive(index);
let ng = crate::resolve::GlobalCtx::<SortId, _>::new();
let key = |m: &Match<DefaultConfig>| -> Vec<Option<u32>> {
m.nodes
.iter()
.map(|o| o.map(|g| index.round_repr(g).unwrap_or(g).raw()))
.collect()
};
let mut recursive: Vec<_> = run_query(plan, eg, &vindex, &ng).iter().map(key).collect();
let mut it = MatchIterator::new(plan, eg, &vindex, &ng);
let mut pull = Vec::new();
while it.next_match() {
pull.push(key(it.env()));
}
set_runtime_scheduling(true);
let mut adaptive: Vec<_> = run_query_scheduled(rq, plan, eg, &vindex, &ng)
.iter()
.map(key)
.collect();
set_runtime_scheduling(false);
recursive.sort();
pull.sort();
adaptive.sort();
assert_eq!(recursive, pull, "the two matcher engines disagree");
assert_eq!(
adaptive, pull,
"runtime atom scheduling changed the match set"
);
recursive
}
fn mid_round_merge(tall_g_class: bool) -> (EG, IndexStore<DefaultConfig>) {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let ga = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
let _fbc = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, c]);
if tall_g_class {
let haa = eg.add(eg.ops().id_by_name("h").unwrap(), &[a, a]);
eg.merge(ga, haa);
}
eg.rebuild();
let index = IndexStore::build(&eg);
eg.merge(c, ga);
(eg, index)
}
#[test]
fn match_set_is_independent_of_join_order() {
for tall_g_class in [false, true] {
let (eg, index) = mid_round_merge(tall_g_class);
let from_f = plan_driven_from(&eg, &["(f x (g y))"], "f", &["f", "g"]);
let from_g = plan_driven_from(&eg, &["(f x (g y))"], "g", &["f", "g"]);
assert_ne!(
from_f.1.steps, from_g.1.steps,
"the two pins produced the same plan (tall_g_class={tall_g_class})"
);
let mf = match_keys(&eg, &from_f.0, &from_f.1, &index);
let mg = match_keys(&eg, &from_g.0, &from_g.1, &index);
assert_eq!(
mf, mg,
"join order changed the match set (tall_g_class={tall_g_class})"
);
assert!(
mf.is_empty(),
"matched a class membership the round's index does not have \
(tall_g_class={tall_g_class}): {mf:?}"
);
}
}
#[test]
fn nonlinear_check_uses_the_rounds_classes() {
let mut eg = make_eg();
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let _fbc = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, c]);
eg.merge(b, c);
eg.rebuild();
let index = IndexStore::build(&eg);
let driven = plan_driven_from(&eg, &["(f x x)"], "f", &["f"]);
assert_eq!(
match_keys(&eg, &driven.0, &driven.1, &index).len(),
1,
"control: a merge the index build can see does make the pattern match"
);
let mut eg = make_eg();
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let _fbc = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, c]);
eg.rebuild();
let index = IndexStore::build(&eg);
eg.merge(b, c);
let driven = plan_driven_from(&eg, &["(f x x)"], "f", &["f"]);
let matches = match_keys(&eg, &driven.0, &driven.1, &index);
assert!(
matches.is_empty(),
"a merge after the index build made `(f x x)` match: {matches:?}"
);
}
#[test]
fn expand_a_checks_a_prebound_fixed_child() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[c]);
let cat = eg.ops().id_by_name("concat").unwrap();
eg.add(cat, &[a, b, c]);
eg.add(cat, &[c, a, b]);
eg.rebuild();
let index = IndexStore::build(&eg);
let driven = plan_driven_from(
&eg,
&["(g x)", "(concat ..pre x ..suf)"],
"g",
&["g", "concat"],
);
let matches = match_keys(&eg, &driven.0, &driven.1, &index);
assert_eq!(
matches.len(),
4,
"expected x=a and x=c once per concat node: {matches:?}"
);
let vindex = VariantIndex::naive(&index);
let ms = run_query(
&driven.1,
&eg,
&vindex,
&crate::resolve::GlobalCtx::<(), _>::new(),
);
assert_eq!(ms.len(), 4);
assert!(has_binding(&ms, &driven.0.shape, &eg, &[("x", "a")]));
assert!(has_binding(&ms, &driven.0.shape, &eg, &[("x", "c")]));
assert!(!has_binding(&ms, &driven.0.shape, &eg, &[("x", "b")]));
}
#[test]
fn expand_a_prebound_child_oracle_blind_spot() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
eg.rebuild();
let index = IndexStore::build(&eg);
let driven = plan_driven_from(
&eg,
&["(g x)", "(concat ..pre x ..suf)"],
"g",
&["g", "concat"],
);
let matches = match_keys(&eg, &driven.0, &driven.1, &index);
assert_eq!(
matches.len(),
1,
"only the window at `a` matches: {matches:?}"
);
}
#[test]
fn decompose_ac_checks_a_prebound_element() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[c]);
let add = eg.ops().id_by_name("add").unwrap();
eg.add(add, &[a, b, c]);
eg.add(add, &[a, b]);
eg.rebuild();
let index = IndexStore::build(&eg);
let driven = plan_driven_from(&eg, &["(g x)", "(add x:1 ..rest)"], "g", &["g", "add"]);
let matches = match_keys(&eg, &driven.0, &driven.1, &index);
assert_eq!(
matches.len(),
3,
"expected x=a in both add nodes and x=c in the first: {matches:?}"
);
let vindex = VariantIndex::naive(&index);
let ms = run_query(
&driven.1,
&eg,
&vindex,
&crate::resolve::GlobalCtx::<(), _>::new(),
);
assert_eq!(ms.len(), 3);
assert!(!has_binding(&ms, &driven.0.shape, &eg, &[("x", "b")]));
}
#[test]
fn decompose_aci_checks_a_prebound_element() {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
eg.add(eg.ops().id_by_name("g").unwrap(), &[c]);
let un = eg.ops().id_by_name("union").unwrap();
eg.add(un, &[a, b, c]);
eg.add(un, &[a, b]);
eg.rebuild();
let index = IndexStore::build(&eg);
let driven = plan_driven_from(&eg, &["(g x)", "(union x ..rest)"], "g", &["g", "union"]);
let matches = match_keys(&eg, &driven.0, &driven.1, &index);
assert_eq!(
matches.len(),
3,
"expected x=a in both union nodes and x=c in the first: {matches:?}"
);
let vindex = VariantIndex::naive(&index);
let ms = run_query(
&driven.1,
&eg,
&vindex,
&crate::resolve::GlobalCtx::<(), _>::new(),
);
assert_eq!(ms.len(), 3);
assert!(!has_binding(&ms, &driven.0.shape, &eg, &[("x", "b")]));
}
fn every_shape() -> EG {
let mut eg = make_eg();
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let ga = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
let gb = eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
let f = eg.ops().id_by_name("f").unwrap();
let fab = eg.add(f, &[a, b]);
eg.add(f, &[ga, b]);
eg.add(f, &[a, a]);
eg.add(f, &[gb, ga]);
eg.add(eg.ops().id_by_name("h").unwrap(), &[fab, gb]);
eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c]);
eg.rebuild();
eg
}
#[test]
fn runtime_scheduling_matches_the_static_plan() {
let eg = every_shape();
let index = IndexStore::build(&eg);
let shapes: &[&[&str]] = &[
&["(f x y)"],
&["(f (g x) y)"],
&["(f x x)"],
&["(h (f x y) (g y))"],
&["(concat x y ..rest)"],
&["(add x:1 ..rest)"],
&["(union x ..rest)"],
&["(f x y)", "(g z)"],
&["(f x y)", "(g x)", "(g y)"],
];
for srcs in shapes {
let rq = resolve_srcs(&eg, srcs);
let plan = schedule(&rq);
let m = match_keys(&eg, &rq, &plan, &index);
assert!(!m.is_empty(), "{srcs:?}: shape must match something");
}
}
#[test]
fn atom_order_is_chosen_per_binding() {
let mut eg = make_eg();
let (f, g, h) = (
eg.ops().id_by_name("f").unwrap(),
eg.ops().id_by_name("g").unwrap(),
eg.ops().id_by_name("h").unwrap(),
);
let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
let x0 = eg.add(g, &[a]);
let y0 = eg.add(g, &[b]);
let x1 = eg.add(g, &[c]);
let y1 = eg.add(h, &[a, b]);
eg.add(f, &[x0, y0]);
eg.add(f, &[x1, y1]);
eg.add(h, &[a, x0]);
eg.add(h, &[b, x0]);
eg.add(g, &[y1]);
eg.rebuild();
let index = IndexStore::build(&eg);
let rq = resolve_srcs(&eg, &["(f x y)", "(h w x)", "(g y)"]);
let plan = schedule(&rq);
let _ = take_atom_choices();
match_keys(&eg, &rq, &plan, &index);
let choices = take_atom_choices();
let after_f: Vec<usize> = choices
.iter()
.filter(|(used, _)| *used != 0)
.map(|(_, ai)| *ai)
.collect();
assert!(
after_f.contains(&1) && after_f.contains(&2),
"both atoms must be chosen second on some binding, got {choices:?}"
);
}
static OP_FILTER_PIN: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn op_restriction_rule_reads_both_lengths() {
let c = OP_FILTER_MIN_RELATION;
let k = OP_FILTER_RELATION_PER_CANDIDATE;
let cases = [
(1, k - 1, false),
(1, k, true),
(16, 16 * k - 1, false),
(16, 16 * k, true),
(c / k, c, true),
(c, c - 1, false),
(c, c, true),
(262_144, 26, false),
(2 * c, c, true),
(2 * c + 1, c, false),
(usize::MAX, c, false),
(usize::MAX, usize::MAX, true),
(0, 1, true),
];
for (m, n, expect) in cases {
assert_eq!(
demote_by_op(m, Some(n), OpFilterPolicy::Adaptive),
expect,
"m={m} n={n}"
);
assert!(demote_by_op(m, Some(n), OpFilterPolicy::AlwaysFilter));
assert!(!demote_by_op(m, Some(n), OpFilterPolicy::AlwaysLeapfrog));
}
for p in [
OpFilterPolicy::Adaptive,
OpFilterPolicy::AlwaysFilter,
OpFilterPolicy::AlwaysLeapfrog,
] {
assert!(!demote_by_op(3, None, p));
}
take_op_restriction_log();
}
fn op_restriction_eg() -> (EG, ENodeId, ENodeId) {
let mut eg = EG::from_model(&NiraModel);
let e = eg.intern_sort("IExpr");
eg.register_op0("z", e);
eg.register_op1("s", e, e);
eg.register_op1("hub", e, e);
eg.register_op2("f0", e, e, e);
eg.register_op2("f1", e, e, e);
let s = eg.ops().id_by_name("s").unwrap();
let hub = eg.ops().id_by_name("hub").unwrap();
let f0 = eg.ops().id_by_name("f0").unwrap();
let f1 = eg.ops().id_by_name("f1").unwrap();
let relation = 4 * OP_FILTER_RELATION_PER_CANDIDATE;
let side = (relation as f64).sqrt().ceil() as usize + 1;
let mut leaves = vec![eg.add(eg.ops().id_by_name("z").unwrap(), &[])];
for i in 1..side {
let prev = leaves[i - 1];
leaves.push(eg.add(s, &[prev]));
}
let hub_a = eg.add(hub, &[leaves[0]]);
let hub_b = eg.add(hub, &[leaves[1]]);
for k in 0..4 {
eg.add(f0, &[hub_a, leaves[k]]);
}
let mut made = 4;
'fill: for i in 0..side {
for j in 0..side {
if made >= relation {
break 'fill;
}
eg.add(f0, &[leaves[i], leaves[j]]);
made += 1;
}
}
for k in 0..40 {
eg.add(f1, &[hub_b, leaves[k]]);
}
eg.rebuild();
(eg, hub_a, hub_b)
}
fn op_restriction_run(
eg: &EG,
src: &str,
policy: OpFilterPolicy,
) -> (Vec<OpRestriction>, Vec<Vec<ENodeId>>) {
set_op_filter_policy(policy);
let pats = [parse_pattern(src)];
let fq = flatten(&pats, eg.ops()).unwrap();
let rq = resolve(
&fq,
eg.ops(),
eg.sorts(),
&NiraModel,
&crate::resolve::GlobalCtx::<_, ()>::new(),
)
.unwrap();
let plan = schedule(&rq);
let store = IndexStore::build(eg);
let index = VariantIndex::naive(&store);
take_op_restriction_log();
let ms = run_query(
&plan,
eg,
&index,
&crate::resolve::GlobalCtx::<(), _>::new(),
);
let log = take_op_restriction_log();
let mut keys: Vec<Vec<ENodeId>> = ms
.iter()
.map(|m| {
(0..plan.shape.num_vars())
.map(|v| m.get(VarId(v as u16)))
.collect()
})
.collect();
keys.sort();
(log, keys)
}
#[test]
fn op_restriction_policy_is_taken_per_binding() {
let _pin = OP_FILTER_PIN.lock().unwrap_or_else(|e| e.into_inner());
let (eg, _, _) = op_restriction_eg();
let (log, _) = op_restriction_run(&eg, "(f0 (hub z) y)", OpFilterPolicy::Adaptive);
assert_eq!(
log,
vec![OpRestriction::Filter, OpRestriction::Leapfrog],
"4 parents against a relation of {} must filter and 40 must not",
4 * OP_FILTER_RELATION_PER_CANDIDATE
);
let (log, _) = op_restriction_run(&eg, "(f1 (hub z) y)", OpFilterPolicy::Adaptive);
assert_eq!(log, vec![OpRestriction::Leapfrog; 2]);
set_op_filter_policy(OpFilterPolicy::Adaptive);
}
#[test]
fn op_restriction_mechanisms_agree_on_the_match_set() {
let _pin = OP_FILTER_PIN.lock().unwrap_or_else(|e| e.into_inner());
let (eg, _, _) = op_restriction_eg();
for src in ["(f0 (hub z) y)", "(f1 (hub z) y)", "(f0 x y)"] {
let (_, adaptive) = op_restriction_run(&eg, src, OpFilterPolicy::Adaptive);
let (fl, filter) = op_restriction_run(&eg, src, OpFilterPolicy::AlwaysFilter);
let (ll, leapfrog) = op_restriction_run(&eg, src, OpFilterPolicy::AlwaysLeapfrog);
assert_eq!(adaptive, filter, "{src}: filter changed the match set");
assert_eq!(adaptive, leapfrog, "{src}: leapfrog changed the match set");
assert!(!adaptive.is_empty(), "{src}: shape must match something");
if src == "(f0 x y)" {
assert!(fl.is_empty() && ll.is_empty());
}
}
set_op_filter_policy(OpFilterPolicy::Adaptive);
}
}