use crate::UsedSet;
use std::cell::{Cell, OnceCell};
use std::collections::{BTreeMap, HashSet};
use relate_core::{NodeId, Path, RelId, Result, Value};
use relate_ir::{Expr, MatchMode, NodePattern, PathPattern, PatternElement, RelPattern};
use crate::ctx::ExecCtx;
use crate::eval::{eval, predicate_holds, AllReduceFold, AllReduceStep};
use crate::exec::WalkTallies;
use crate::overlay::ExecGraph;
use super::candidates::{expect_enumerated_candidate, node_ok};
use super::pushdown::Residual;
use crate::pattern_walk::{
bind_node_stub, bind_path_names, bind_rel_stub, bind_rel_stub_list, memoized_path_rung,
node_candidates, rel_edge_ok, RelFilter, RelHop,
};
use crate::row::{Row, RowRung};
mod early;
mod emit;
mod qpp;
mod selector;
mod shortest_route;
mod sink;
mod walk;
use crate::exec::rider::Rider;
use crate::shortest::reject_static_common_end_nodes;
use early::{early_predicates, EarlyPredicates};
use emit::GpmEmit;
use qpp::gpm_expand_quantified;
use shortest_route::match_shortest_route;
pub(crate) use shortest_route::{fold_shortest_route, RouteCaches};
use sink::MatchedSink;
use walk::gpm_walk_elements;
use super::pattern_policies::{
gpm_group_vocabulary, gpm_path_mode_allows, inlined_all_reduces,
path_mode_requires_unique_rels, InlinedAllReduce, MatchTail, Matched,
};
#[derive(Clone)]
pub(crate) struct GpmState {
pub row: Row,
pub used: UsedSet,
pub current: NodeId,
pub nodes: Vec<NodeId>,
pub rels: Vec<RelId>,
}
pub(crate) struct HopFrame {
rid: RelId,
consumed: bool,
visible: bool,
current: NodeId,
}
impl GpmState {
pub(crate) fn push_hop(
&mut self,
graph: &ExecGraph<'_>,
rid: RelId,
next_id: NodeId,
) -> HopFrame {
self.rels.push(rid);
let current = self.current;
self.current = next_id;
HopFrame {
rid,
consumed: self.used.insert(rid),
visible: push_visible_node(graph, next_id, &mut self.nodes),
current,
}
}
}
impl HopFrame {
pub(crate) fn pop(self, state: &mut GpmState) {
state.current = self.current;
if self.visible {
state.nodes.pop();
}
let popped = state
.rels
.pop()
.expect("hop frame: the frame's own rel push");
debug_assert_eq!(popped, self.rid, "hop frames pop LIFO");
if self.consumed {
state.used.remove(&self.rid);
}
}
}
#[derive(Clone, Copy)]
struct GpmCtx<'a> {
graph: &'a ExecGraph<'a>,
params: &'a BTreeMap<String, Value>,
walk: &'a WalkState<'a>,
halt: &'a Cell<bool>,
}
pub(crate) struct GpmFilters {
pub(crate) filters: Vec<ElementFilter>,
}
pub(crate) enum ElementFilter {
Node,
Rel(RelFilter),
Group(Vec<ElementFilter>),
}
impl GpmFilters {
pub(crate) fn resolve(graph: &ExecGraph<'_>, path: &PathPattern) -> Self {
GpmFilters {
filters: Self::resolve_elements(graph, &path.elements),
}
}
fn resolve_elements(graph: &ExecGraph<'_>, elements: &[PatternElement]) -> Vec<ElementFilter> {
elements
.iter()
.map(|element| match element {
PatternElement::Node(_) => ElementFilter::Node,
PatternElement::Relationship(rp) => {
ElementFilter::Rel(RelFilter::resolve(graph, rp))
}
PatternElement::Quantified(qpp) => {
let inner = Self::resolve_elements(graph, &qpp.elements);
assert!(
inner.iter().all(|e| !matches!(e, ElementFilter::Group(_))),
"quantified path patterns cannot be nested (parser Rule 4)"
);
ElementFilter::Group(inner)
}
})
.collect()
}
}
impl GpmCtx<'_> {
fn halted(&self) -> bool {
self.halt.get()
}
fn unbounded_dfs_cap(&self) -> u32 {
*self
.walk
.unbounded_cap
.get_or_init(|| unbounded_dfs_cap(self.graph, self.walk.match_mode))
}
}
struct WalkState<'c> {
match_mode: MatchMode,
enforce_unique: bool,
inlined: Vec<InlinedAllReduce<'c>>,
early: EarlyPredicates<'c>,
cap_halt: Cell<bool>,
unbounded_cap: OnceCell<u32>,
path_rung: Cell<Option<RowRung>>,
tallies: WalkTallies,
}
impl<'c> WalkState<'c> {
fn new(
path: &PathPattern,
row: &Row,
match_mode: MatchMode,
where_clause: &Residual<'c>,
) -> Self {
Self {
match_mode,
enforce_unique: match_mode == MatchMode::DifferentRelationships
|| path.mode.is_some_and(path_mode_requires_unique_rels),
inlined: inlined_all_reduces(path, row, where_clause.conjuncts),
early: early_predicates(path, row, where_clause),
cap_halt: Cell::new(false),
unbounded_cap: OnceCell::new(),
path_rung: Cell::new(None),
tallies: WalkTallies::default(),
}
}
fn gctx<'s>(&'s self, ctx: ExecCtx<'s>, halt: &'s Cell<bool>) -> GpmCtx<'s>
where
'c: 's,
{
GpmCtx {
graph: ctx.graph,
params: ctx.params,
walk: self,
halt,
}
}
}
enum Prebound<'a> {
Fresh,
Pinned(&'a Value),
}
fn prebound<'a>(existing: Option<&'a Value>) -> Prebound<'a> {
match existing {
None | Some(Value::Null) => Prebound::Fresh,
Some(value) => Prebound::Pinned(value),
}
}
fn gpm_bind_node(graph: &ExecGraph<'_>, node: &NodePattern, id: NodeId, row: &mut Row) -> bool {
let Some(name) = &node.variable else {
return true;
};
match prebound(row.get_name(name)) {
Prebound::Fresh => {
row.insert(name.to_string(), bind_node_stub(graph, id));
true
}
Prebound::Pinned(Value::Node(existing)) => existing.id == id,
Prebound::Pinned(_) => false,
}
}
fn gpm_bind_rel(graph: &ExecGraph<'_>, row: &mut Row, rel: &RelPattern, segment: &[RelId]) -> bool {
let Some(name) = &rel.variable else {
return true;
};
let value = if rel.var_length {
bind_rel_stub_list(graph, segment)
} else {
bind_rel_stub(
graph,
*segment
.last()
.expect("a non-var-length walk always parks one relationship"),
)
};
match prebound(row.get_name(name)) {
Prebound::Fresh => {
row.insert(name.to_string(), value);
true
}
Prebound::Pinned(pinned) => pinned.eq_non_null(&value),
}
}
fn unbounded_dfs_cap(graph: &ExecGraph<'_>, match_mode: MatchMode) -> u32 {
let rels = u32::try_from(graph.all_rel_ids().len()).unwrap_or(u32::MAX);
if match_mode == MatchMode::DifferentRelationships {
rels.max(1)
} else {
rels.saturating_add(1)
.min(crate::pattern_walk::DEFAULT_MAX_HOPS)
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn match_gpm_path(
ctx: ExecCtx<'_>,
path: &PathPattern,
rel_filters: &GpmFilters,
caches: &RouteCaches,
row: Row,
used: UsedSet,
match_mode: MatchMode,
tail: MatchTail<'_>,
where_clause: &Residual<'_>,
mut rider: Option<&mut Rider<'_, '_>>,
) -> Result<Matched> {
let graph = ctx.graph;
let params = ctx.params;
reject_static_common_end_nodes(path)?;
let route_halt = Cell::new(false);
let mut routed = Matched::new();
let sink = MatchedSink::new(
rider.as_deref_mut(),
&route_halt,
where_clause,
tail,
&mut routed,
);
if match_shortest_route(
sink,
ctx,
path,
rel_filters,
caches,
&row,
&used,
match_mode,
)? {
return Ok(routed);
}
if path.elements.is_empty() {
return Ok(Vec::new());
}
let elements = &path.elements;
let walk_state = WalkState::new(path, &row, match_mode, where_clause);
let anonymous = NodePattern::anonymous();
let (start, first) = match elements.first() {
Some(PatternElement::Node(node)) => (1, node),
_ => (0, &anonymous),
};
let mut states = gpm_start_nodes(graph, first, row, used, params, where_clause)?;
let mut emitted: Matched = Vec::new();
let (mut emit, halt) = emit::mount_rider(
ctx,
rider.as_deref_mut(),
path,
where_clause,
&walk_state.cap_halt,
tail,
&mut emitted,
);
let gctx = walk_state.gctx(ctx, halt);
states = crate::ctx::phase_walk(|| {
gpm_walk_elements(
&gctx,
elements,
&rel_filters.filters,
start,
states,
&mut emit,
)
})?;
if emit.is_some() {
return Ok(emitted);
}
let candidates = selector::complete_and_select_candidates(&gctx, path, states)?;
let selector_halt = Cell::new(false);
let mut out = Matched::new();
let mut sink = MatchedSink::new(rider, &selector_halt, where_clause, tail, &mut out);
for state in candidates {
if sink.halted() {
break;
}
sink.offer(ctx, state.row, || state.used)?;
}
Ok(out)
}
fn complete_state(gctx: &GpmCtx<'_>, path: &PathPattern, state: &mut GpmState) -> Result<bool> {
let GpmCtx { graph, params, .. } = *gctx;
if !gpm_path_mode_allows(
path.mode,
state.nodes.iter().copied(),
state.rels.iter().copied(),
) {
return Ok(false);
}
let rung = memoized_path_rung(&gctx.walk.path_rung, &state.row, path);
bind_path_value(
graph,
&mut state.row,
path,
&state.nodes,
&state.rels,
&rung,
);
if let Some(predicate) = path.where_clause.as_deref() {
if !inline_predicate_holds(graph, &state.row, predicate, params)? {
return Ok(false);
}
}
Ok(true)
}
fn materialize_path(graph: &ExecGraph<'_>, nodes: &[NodeId], rels: &[RelId]) -> Path {
Path {
nodes: nodes
.iter()
.map(|&id| expect_enumerated_candidate(graph.node(id), id))
.collect(),
rels: rels
.iter()
.map(|&id| expect_enumerated_candidate(graph.rel(id), id))
.collect(),
}
}
fn bind_path_value(
graph: &ExecGraph<'_>,
row: &mut Row,
path: &PathPattern,
nodes: &[NodeId],
rels: &[RelId],
rung: &RowRung,
) {
bind_path_names(row, path, rung, || {
Value::from_path(materialize_path(graph, nodes, rels))
});
}
pub(crate) fn push_visible_node(
graph: &ExecGraph<'_>,
id: NodeId,
nodes: &mut Vec<NodeId>,
) -> bool {
let visible = graph.node_exists(id);
if visible {
nodes.push(id);
}
visible
}
fn gpm_start_nodes(
graph: &ExecGraph<'_>,
node: &NodePattern,
row: Row,
used: UsedSet,
params: &BTreeMap<String, Value>,
residual: &Residual<'_>,
) -> Result<Vec<GpmState>> {
let mut out = Vec::new();
let ready = super::pushdown::ready_conjuncts(residual, &row, node.variable.as_ref(), &[]);
let candidates = node_candidates(graph, node, &row, params, residual.conjuncts)?;
for id in candidates {
graph.cancel_tick()?;
if !node_ok(graph, id, node, &row, params)? {
continue;
}
let mut bound = row.clone();
if !gpm_bind_node(graph, node, id, &mut bound) {
continue;
}
if let Some(predicate) = &node.where_clause {
if !inline_predicate_holds(graph, &bound, predicate, params)? {
continue;
}
}
if !super::pushdown::conjuncts_hold(graph, &bound, &ready, params)? {
continue;
}
let mut nodes = Vec::new();
if push_visible_node(graph, id, &mut nodes) {
out.push(GpmState {
row: bound,
used: used.clone(),
current: id,
nodes,
rels: Vec::new(),
});
}
}
Ok(out)
}
fn inline_predicate_holds(
graph: &ExecGraph<'_>,
row: &Row,
predicate: &Expr,
params: &BTreeMap<String, Value>,
) -> Result<bool> {
Ok(!super::pushdown::expr_ready(predicate, row)
|| predicate_holds(graph, row, predicate, params)?)
}
#[cfg(test)]
pub(super) fn qpp_hops(graph: &crate::graph::Graph, query: &str) -> u64 {
super::take_hop_expands();
crate::exec::test_support::exec_cypher(graph, query);
super::take_hop_expands()
}
#[cfg(test)]
mod allreduce_inline_tests;
#[cfg(test)]
mod early_tests;
#[cfg(test)]
mod emit_tests;
#[cfg(test)]
mod gpm_tests;
#[cfg(test)]
mod unify_tests;