use crate::UsedSet;
use std::cell::Cell;
use relate_core::Result;
use relate_ir::{MatchMode, PathPattern};
use crate::ctx::ExecCtx;
use crate::exec::pushdown::Residual;
use crate::row::Row;
mod guard;
mod route;
mod trail_walk;
use route::Route;
use super::sink::MatchedSink;
use super::GpmFilters;
use guard::{route_shape, Spelling};
#[cfg(test)]
mod anchor_tests;
#[cfg(test)]
mod bounded_tests;
#[cfg(test)]
mod expr_parity_tests;
#[cfg(test)]
mod fixtures;
#[cfg(test)]
mod parity_tests;
#[cfg(test)]
mod reject_tests;
#[cfg(test)]
mod route_tests;
#[cfg(test)]
thread_local! {
static FORCE_GPM: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static ROUTE_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
#[inline(always)]
fn note_route_run() {
#[cfg(test)]
ROUTE_RUNS.with(|c| c.set(c.get() + 1));
}
#[cfg(test)]
pub(crate) fn take_route_runs() -> u64 {
ROUTE_RUNS.with(|c| c.replace(0))
}
#[cfg(test)]
fn with_forced_gpm<T>(f: impl FnOnce() -> T) -> T {
struct Restore(bool);
impl Drop for Restore {
fn drop(&mut self) {
FORCE_GPM.with(|c| c.set(self.0));
}
}
let _restore = Restore(FORCE_GPM.with(|c| c.replace(true)));
f()
}
pub(super) fn match_shortest_route<'a>(
mut sink: MatchedSink<'a, '_>,
ctx: ExecCtx<'a>,
path: &'a PathPattern,
filters: &'a GpmFilters,
row: &'a Row,
used: &UsedSet,
match_mode: MatchMode,
) -> Result<bool> {
#[cfg(test)]
if FORCE_GPM.with(|c| c.get()) {
return Ok(false);
}
let Some(shape) = route_shape(path, filters, match_mode, used, row, ctx.params) else {
return Ok(false);
};
let Some(route) = Route::try_new(ctx, path, row, shape, &sink) else {
return Ok(false);
};
route.run(&mut sink)?;
note_route_run();
Ok(true)
}
pub(crate) fn fold_shortest_route(
ctx: ExecCtx<'_>,
path: &PathPattern,
row: &Row,
fold: &mut dyn FnMut(Row) -> Result<()>,
) -> Result<bool> {
#[cfg(test)]
if FORCE_GPM.with(|c| c.get()) {
return Ok(false);
}
let filters = GpmFilters::resolve(ctx.graph, path);
let used = UsedSet::default();
let Some(mut shape) = route_shape(
path,
&filters,
MatchMode::DifferentRelationships,
&used,
row,
ctx.params,
) else {
return Ok(false);
};
shape.max = shape.max.or(Some(crate::pattern_walk::DEFAULT_MAX_HOPS));
shape.spelling = Spelling::Expression;
let residual = Residual::empty();
let halt = Cell::new(false);
let mut sink = MatchedSink::fold(&residual, &halt, fold);
let Some(route) = Route::try_new(ctx, path, row, shape, &sink) else {
return Ok(false);
};
route.run(&mut sink)?;
note_route_run();
Ok(true)
}