use crate::UsedSet;
use std::collections::{BTreeMap, HashSet};
use relate_core::Value;
use relate_ir::{
MatchMode, NodePattern, PathMode, PathPattern, PathSelector, PatternElement, RelPattern,
};
use crate::eval::expr_vars;
use crate::row::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)
}
}
pub(super) struct Shape<'p> {
pub start: &'p NodePattern,
pub rel: &'p RelPattern,
pub filter: &'p RelFilter,
pub end: &'p NodePattern,
pub min: u32,
pub max: Option<u32>,
pub all: bool,
pub spelling: Spelling,
}
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>> {
if match_mode != MatchMode::DifferentRelationships
|| !used.is_empty()
|| !matches!(path.mode, None | Some(PathMode::Walk | PathMode::Trail))
{
return None;
}
let all = match path.selector.as_ref()? {
PathSelector::AnyShortest => false,
PathSelector::AllShortest => true,
PathSelector::Shortest {
count: Some(count),
group,
} if resolve_gpm_count(Some(count), 1, params).is_ok_and(|n| n == 1) => *group,
PathSelector::Shortest { .. } | PathSelector::Any(_) | PathSelector::All => return None,
};
let hop = routed_hop(path, filters, all, spelling)?;
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(|text| row.contains_key(text)))
{
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,
all: bool,
spelling: Spelling,
) -> Option<Shape<'p>> {
let [PatternElement::Node(start), rel_element, PatternElement::Node(end)] =
path.elements.as_slice()
else {
return None;
};
let (rel, filter, min, max) = match (rel_element, &filters.filters[1]) {
(PatternElement::Quantified(qpp), ElementFilter::Group(inner)) => {
let rel = qpp.implicit_var_length_rel()?;
let ElementFilter::Rel(filter) = &inner[1] else {
return None;
};
(rel, filter, qpp.min, qpp.max)
}
(PatternElement::Relationship(rel), ElementFilter::Rel(filter)) if rel.var_length => {
(rel, filter, rel.min_hops, rel.max_hops)
}
_ => return None,
};
Some(Shape {
start,
rel,
filter,
end,
min,
max: max.or(spelling.unbounded_ceiling()),
all,
spelling,
})
}