use super::fallible_vec::{filled, reserved};
use crate::core::SymbolId;
use crate::execution::matching::symbols::BoolColumnProvider;
use crate::nfa::{AnchorEnvironment, CompiledAutomaton};
use datafusion_common::Result;
use std::sync::Arc;
pub(crate) fn last_symbols(
compiled: &CompiledAutomaton,
) -> Result<Option<Arc<[SymbolId]>>> {
if compiled.min_match_rows() == 0 || !compiled.anchored_at_end() {
return Ok(None);
}
let mut seen = filled(compiled.num_symbols(), false, "final-symbol marks")?;
let mut symbols = reserved(compiled.num_symbols(), "final symbols")?;
for state in compiled.nfa().states() {
for (symbol, targets) in state.transition_rows() {
if !seen[symbol.index()] {
for &target in targets {
let accepts = compiled
.accepting_preference_rank(
target,
Some(AnchorEnvironment::VirtualEnd),
)
.is_some();
if accepts {
seen[symbol.index()] = true;
symbols.push(symbol);
break;
}
}
}
}
}
Ok(Some(Arc::from(symbols)))
}
pub(crate) fn can_finish(
symbols: &[SymbolId],
provider: &impl BoolColumnProvider,
provider_origin: usize,
end: usize,
completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<bool> {
let Some(row) = end
.checked_sub(1)
.and_then(|row| row.checked_sub(provider_origin))
else {
return Ok(true);
};
if row >= provider.num_rows() {
return Ok(true);
}
let Some(location) = provider.locate_with_work(row, completed)? else {
return Ok(true);
};
for &symbol in symbols {
completed(1)?;
if provider.get_bool_with_loc(symbol, location) {
return Ok(true);
}
}
Ok(false)
}
pub(crate) fn trailing_alphabet(compiled: &CompiledAutomaton) -> Result<Option<u64>> {
if compiled.min_match_rows() == 0
|| !compiled.has_end_anchor()
|| compiled.num_symbols() > 64
{
return Ok(None);
}
let nfa = compiled.nfa();
let mut seen = filled(nfa.state_count(), false, "suffix reachability")?;
let mut queue = reserved(nfa.state_count(), "suffix states")?;
let root = nfa.start_state();
seen[root.index()] = true;
queue.push(root);
let mut cursor = 0;
let mut mask = 0;
while cursor < queue.len() {
let state = queue[cursor];
cursor += 1;
if compiled
.anchor_first_accepting_state(AnchorEnvironment::PhysicalInterior, state)
.is_some()
{
return Ok(None);
}
for &dispatch in
compiled.anchor_dispatch_closure(AnchorEnvironment::PhysicalInterior, state)
{
for (symbol, targets) in nfa.state(dispatch).transition_rows() {
if targets.is_empty() {
continue;
}
let Some(bit) = symbol.packed_membership_bit() else {
return Ok(None);
};
mask |= bit;
for &target in targets {
if !seen[target.index()] {
seen[target.index()] = true;
queue.push(target);
}
}
}
}
}
Ok(Some(mask))
}