use super::state::{LaneScanState, LaneSuccessorAction, LaneView};
use crate::core::{AbsoluteRow, PhysicalRowCount};
use crate::execution::matching::{PatternMatcher, state_set::check_state_equivalence};
use crate::nfa::CompiledAutomaton;
use datafusion::common::{DataFusionError, Result};
#[inline]
pub(in crate::execution::matching) fn commit_scratch_transition(
matcher: &PatternMatcher,
compiled: &CompiledAutomaton,
lane: &mut LaneScanState,
row: AbsoluteRow,
retains: bool,
can_accept: bool,
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<bool> {
let program = &lane.program;
let scratch = lane.scratch();
let acceptance = if can_accept {
match program.closure_accepting[scratch.state.state_id.index()] {
Some(accepting) => Some((
accepting,
row.checked_add(PhysicalRowCount::new(1))
.ok_or_else(overflow)?,
)),
None => None,
}
} else {
None
};
let dominated_by_self_accept = acceptance.is_some()
&& (program.requires_partition_end()
|| compiled.accepting_preference_rank(
scratch.state.state_id,
program.accept_environment(),
) == Some(0));
let action = if !retains || dominated_by_self_accept {
LaneSuccessorAction::Discard
} else {
let mut found_equivalent = false;
for index in 0..lane.successor_len() {
completed(1)?;
let previous = lane
.successor_state(index)
.expect("successor index is sealed");
if previous.state_id == scratch.state.state_id
&& equivalent(
matcher,
compiled,
lane.candidate_start().expect("live lane candidate"),
scratch,
lane.successor(index).expect("successor index is sealed"),
completed,
)?
{
found_equivalent = true;
break;
}
}
if found_equivalent {
LaneSuccessorAction::Discard
} else {
LaneSuccessorAction::Append
}
};
let publication = lane.plan_publication(action, acceptance, row)?;
completed(publication.work)?;
lane.publish_scratch(publication);
Ok(publication.row_complete)
}
fn overflow() -> DataFusionError {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE lane acceptance position overflow".into(),
)
}
fn equivalent(
matcher: &PatternMatcher,
compiled: &CompiledAutomaton,
match_start: AbsoluteRow,
left: LaneView<'_>,
right: LaneView<'_>,
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<bool> {
check_state_equivalence(
match_start,
match_start,
left.state.state_id,
compiled.nfa().state(left.state.state_id).is_accepting(),
compiled,
matcher.program.aggregate_symbols_bitmap(),
!matcher.program.has_path_dependent_aggregates(),
completed,
|completed| {
completed(1)?;
if left.registers != right.registers {
completed(1)?;
return Ok(false);
}
let equivalent = left.navigation == right.navigation;
completed(left.navigation.len().max(1))?;
Ok(equivalent)
},
)
}