use crate::UsedSet;
use std::collections::{BTreeMap, HashSet};
use relate_core::Value;
use relate_ir::{
label_expr_vars, pattern_prop_key, Expr, MatchMode, NodePattern, PathMode, PathPattern,
PathSelector, PatternElement, QuantifiedPathPattern, RelPattern,
};
use relate_names::NamedToken;
use crate::eval::{bound_is_row_invariant, bytecode::NodeBytecode, expr_vars};
use crate::row::{row_bound, Row};
use crate::shortest::followable;
use super::super::selector::resolve_gpm_count;
use super::super::{ElementFilter, GpmFilters};
use crate::pattern_walk::RelFilter;
use crate::shortest::CommonEndNodes;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Spelling {
KeywordSelector,
Function,
Expression,
}
impl Spelling {
pub(super) fn of(path: &PathPattern) -> Self {
if path.is_shortest_path_function {
Spelling::Function
} else {
Spelling::KeywordSelector
}
}
pub(super) fn common_end_nodes(self) -> CommonEndNodes {
match self {
Spelling::KeywordSelector => CommonEndNodes::Allowed,
Spelling::Function | Spelling::Expression => CommonEndNodes::Forbidden,
}
}
pub(super) fn first_layer_only(self) -> bool {
self == Spelling::Expression
}
pub(super) fn filters_search_by_clause_where(self) -> bool {
self != Spelling::KeywordSelector
}
fn unbounded_ceiling(self) -> Option<u32> {
(self == Spelling::Expression).then_some(crate::pattern_walk::DEFAULT_MAX_HOPS)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Keep {
Paths(usize),
Groups(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Selection {
Single,
AllShortest,
Count(Keep),
}
impl Selection {
pub(super) fn all(self) -> bool {
self == Selection::AllShortest
}
pub(super) fn counted(self) -> Option<Keep> {
match self {
Selection::Count(keep) => Some(keep),
Selection::Single | Selection::AllShortest => None,
}
}
}
#[derive(Clone, Debug)]
pub(super) enum InnerPlan {
LabelsOnly,
Bytecode(NodeBytecode),
Fallback,
}
#[cfg(test)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InnerPlanKind {
LabelsOnly,
Bytecode,
Fallback,
}
#[cfg(test)]
impl InnerPlan {
pub(crate) fn kind(&self) -> InnerPlanKind {
match self {
Self::LabelsOnly => InnerPlanKind::LabelsOnly,
Self::Bytecode(_) => InnerPlanKind::Bytecode,
Self::Fallback => InnerPlanKind::Fallback,
}
}
}
#[derive(Clone)]
pub(super) struct InnerNode<'p> {
pub(super) pattern: &'p NodePattern,
pub(super) plan: InnerPlan,
}
impl<'p> InnerNode<'p> {
fn new(pattern: &'p NodePattern) -> Self {
Self {
plan: compile_inner_node_plan(pattern),
pattern,
}
}
}
#[derive(Clone)]
pub(super) struct QppInner<'p> {
pub(super) head: InnerNode<'p>,
pub(super) tail: InnerNode<'p>,
}
pub(super) struct Shape<'p> {
pub start: &'p NodePattern,
pub rel: &'p RelPattern,
pub filter: &'p RelFilter,
pub end: &'p NodePattern,
pub qpp_inner: Option<QppInner<'p>>,
pub min: u32,
pub max: Option<u32>,
pub selection: Selection,
pub spelling: Spelling,
pub match_mode: MatchMode,
}
pub(super) fn route_shape<'p>(
path: &'p PathPattern,
filters: &'p GpmFilters,
match_mode: MatchMode,
used: &UsedSet,
row: &Row,
params: &BTreeMap<String, Value>,
spelling: Spelling,
) -> Option<Shape<'p>> {
let explicit_walk = match path.mode {
Some(PathMode::Walk) => true,
None | Some(PathMode::Trail) => false,
Some(_) => return None,
};
if match_mode != MatchMode::DifferentRelationships || !used.is_empty() {
return None;
}
let selection = match path.selector.as_ref()? {
PathSelector::AnyShortest => Selection::Single,
PathSelector::AllShortest => Selection::AllShortest,
PathSelector::Shortest {
count: Some(count),
group,
} => {
let n = resolve_gpm_count(Some(count), 1, params).ok()?;
counted(n, *group)?
}
PathSelector::Any(Some(count)) => {
let n = resolve_gpm_count(Some(count), 1, params).ok()?;
counted(n, false)?
}
PathSelector::Shortest { .. } | PathSelector::Any(_) | PathSelector::All => return None,
};
if explicit_walk && selection.counted().is_some() {
return None;
}
let hop = routed_hop(path, filters, selection, spelling, match_mode, row)?;
if hop.min > 1
|| hop.rel.where_clause.is_some()
|| !followable(hop.start, hop.rel, hop.end)
|| hop
.rel
.variable
.as_ref()
.is_some_and(|v| v.with_str(row_bound(row)))
{
return None;
}
let late: Vec<String> = hop
.rel
.variable
.as_ref()
.map(|v| v.to_string())
.into_iter()
.chain(path.path_names().map(|name| name.to_string()))
.collect();
let endpoint_ok = |np: &NodePattern| {
let mut vars = HashSet::new();
if let Some(props) = &np.properties {
expr_vars(props, &mut vars);
}
np.variable
.as_ref()
.is_none_or(|v| matches!(row.get_name(v), None | Some(Value::Node(_))))
&& !late.iter().any(|v| vars.contains(v.as_str()))
};
let end_where_ok = hop.end.where_clause.as_ref().is_none_or(|predicate| {
let mut vars = HashSet::new();
expr_vars(predicate, &mut vars);
path.path_names()
.all(|name| name.with_str(|text| !vars.contains(text)))
});
(endpoint_ok(hop.start)
&& hop.start.where_clause.is_none()
&& endpoint_ok(hop.end)
&& end_where_ok)
.then_some(hop)
}
fn routed_hop<'p>(
path: &'p PathPattern,
filters: &'p GpmFilters,
selection: Selection,
spelling: Spelling,
match_mode: MatchMode,
row: &Row,
) -> Option<Shape<'p>> {
let [PatternElement::Node(start), rel_element, PatternElement::Node(end)] =
path.elements.as_slice()
else {
return None;
};
let (rel, filter, qpp_inner, min, max) = match (rel_element, &filters.filters[1]) {
(PatternElement::Quantified(qpp), ElementFilter::Group(inner)) => {
let ElementFilter::Rel(filter) = &inner[1] else {
return None;
};
if let Some(rel) = qpp.implicit_var_length_rel() {
(rel, filter, None, qpp.min, qpp.max)
} else {
let (rel, inner) = qpp_hop(path, start, end, qpp, filter, selection, row)?;
(rel, filter, Some(inner), qpp.min, qpp.max)
}
}
(PatternElement::Relationship(rel), ElementFilter::Rel(filter)) if rel.var_length => {
(rel, filter, None, rel.min_hops, rel.max_hops)
}
_ => return None,
};
Some(Shape {
start,
rel,
filter,
end,
qpp_inner,
min,
max: max.or(spelling.unbounded_ceiling()),
selection,
spelling,
match_mode,
})
}
fn qpp_hop<'p>(
path: &'p PathPattern,
start: &'p NodePattern,
end: &'p NodePattern,
qpp: &'p QuantifiedPathPattern,
_filter: &'p RelFilter,
selection: Selection,
row: &Row,
) -> Option<(&'p RelPattern, QppInner<'p>)> {
if !matches!(selection, Selection::Single | Selection::AllShortest)
|| qpp.subpath_variable.is_some()
|| qpp.where_clause.is_some()
{
return None;
}
let [PatternElement::Node(head), PatternElement::Relationship(rel), PatternElement::Node(tail)] =
qpp.elements.as_slice()
else {
return None;
};
if rel.var_length
|| rel.where_clause.is_some()
|| rel.properties.is_some()
|| !qpp_inner_compatible(path, start, rel, end, head, tail, row)
{
return None;
}
let head = InnerNode::new(head);
let tail = InnerNode::new(tail);
Some((rel, QppInner { head, tail }))
}
fn compile_inner_node_plan(np: &NodePattern) -> InnerPlan {
if !np.has_static_labels() {
return InnerPlan::Fallback;
}
let has_predicates = np.where_clause.is_some()
|| match &np.properties {
Some(Expr::Map(m)) => !m.is_empty(),
Some(_) => true,
None => false,
};
if !has_predicates {
return InnerPlan::LabelsOnly;
}
let map_entries: Vec<(NamedToken, &Expr)> = match &np.properties {
None => Vec::new(),
Some(Expr::Map(entries)) => {
let mut out = Vec::with_capacity(entries.len());
for (key, value) in entries {
if !bound_is_row_invariant(value) {
return InnerPlan::Fallback;
}
out.push((pattern_prop_key(&np.prop_keys, key), value));
}
out
}
Some(_) => return InnerPlan::Fallback,
};
match NodeBytecode::compile_entries_and_exprs(
np.variable.as_ref(),
map_entries,
np.where_clause.as_ref(),
) {
Some(code) => InnerPlan::Bytecode(code),
None => InnerPlan::Fallback,
}
}
fn reads_only_own_or_bound(np: &NodePattern, row: &Row) -> bool {
let mut vars = HashSet::new();
if let Some(props) = &np.properties {
expr_vars(props, &mut vars);
}
if let Some(w) = &np.where_clause {
expr_vars(w, &mut vars);
}
if let Some(le) = &np.label_expr {
label_expr_vars(le, &mut vars);
}
let bound = row_bound(row);
vars.iter().all(|name| {
np.variable.as_ref().is_some_and(|v| v == name.as_str()) || bound(name.as_str())
})
}
fn qpp_inner_compatible(
path: &PathPattern,
start: &NodePattern,
rel: &RelPattern,
end: &NodePattern,
head: &NodePattern,
tail: &NodePattern,
row: &Row,
) -> bool {
if head.variable.is_some() && head.variable == tail.variable {
return false;
}
let collides = |v: &relate_names::SmallName| {
start.variable.as_ref() == Some(v)
|| rel.variable.as_ref() == Some(v)
|| end.variable.as_ref() == Some(v)
|| path.path_names().any(|p| p == v)
|| v.with_str(row_bound(row))
};
for np in [head, tail] {
if np.variable.as_ref().is_some_and(collides) || !reads_only_own_or_bound(np, row) {
return false;
}
}
true
}
fn counted(n: usize, group: bool) -> Option<Selection> {
match (n, group) {
(0, _) => None,
(1, false) => Some(Selection::Single),
(1, true) => Some(Selection::AllShortest),
(n, true) => Some(Selection::Count(Keep::Groups(n))),
(n, false) => Some(Selection::Count(Keep::Paths(n))),
}
}