use std::collections::HashMap;
use std::sync::Arc;
use crate::core::vm::{NavigationLayout, VmTier};
use crate::core::{
AggregationPositions, LabeledAggregationPositions, NormalizedPattern, Pattern,
PositionOffset, RepetitionQuantifier, Symbol, SymbolId,
};
use crate::execution::matching::graph::fallible_vec::{filled, reserved};
use crate::execution::matching::path::{PathRepresentation, compact_path_shape_for_skip};
use crate::execution::matching::program::validated_vm::BoundRegisterWriter;
use crate::execution::matching::row_loop::lane_scan::LaneBoundaryAnchors;
use crate::execution::matching::row_loop::lane_scan::{
LaneRejection, LaneScanProgram, LaneSessionFacts,
};
use crate::execution::matching::row_loop::ordered_transitions::OrderedTransitionTable;
use crate::execution::matching::row_loop::types::{
LabeledPositionTrackingSet, PositionTrackingSet,
};
use crate::execution::matching::{
ExecutableIncrementalEvaluator, ExecutableSymbolEvaluator, ExecutableSymbolProgram,
MatcherConfiguration, PatternMatcher, PreparedMatcherProgram, ResolvedBoolColumn,
SymbolColumn, SymbolTable,
};
use crate::nfa::CompiledAutomaton;
use crate::planning::{ManagedAggregateBackendSet, SymbolRelationships};
use datafusion_common::{DataFusionError, Result};
use datafusion_execution::memory_pool::MemoryReservation;
#[cfg(test)]
pub(crate) use crate::execution::matching::graph::start_guard::StartCondition;
pub(crate) use crate::execution::matching::graph::start_guard::StaticStartWindow;
impl StaticStartWindow {
fn try_new(
compiled: &CompiledAutomaton,
symbol_columns: &[SymbolColumn],
programs: &[ExecutableSymbolProgram],
prepared: &PreparedMatcherProgram,
) -> Result<Self> {
use crate::execution::matching::ExecutableSymbolEvaluator;
let registers_only = !prepared
.vm_program
.aggregate_backend_set()
.requires_accumulator_state()
&& !prepared.has_volatile_managed_accumulators
&& !prepared.deferred_history.has_volatile_operations;
let mut can_cross = filled(programs.len(), false, "start-window symbols")?;
if registers_only {
for column in symbol_columns {
let id = column.id;
let Some(program) = programs[id.index()].user() else {
continue;
};
if !matches!(program.evaluator(), ExecutableSymbolEvaluator::Static)
|| !program.navigation_program().ops().is_empty()
{
continue;
}
can_cross[id.index()] = !program
.accumulation_program()
.ops()
.iter()
.any(BoundRegisterWriter::may_overflow_decimal_precision);
}
}
Self::try_new_with_conditions(
compiled,
symbol_columns,
|symbol_id| {
programs
.get(symbol_id.index())
.and_then(ExecutableSymbolProgram::user)
.map(|program| program.static_predicate_and_columns())
.unwrap_or_default()
},
|id| can_cross[id.index()],
)
}
}
#[derive(Debug)]
pub(crate) struct SymbolExecutionPlan {
static_evaluator: bool,
direct_evaluator: bool,
physical_evaluator: bool,
physical_symbols: Vec<PhysicalSymbol>,
eager_incremental_ids: Vec<SymbolId>,
pub(crate) eager_bitmap: u64,
static_precheck_ids: Vec<SymbolId>,
static_precheck_columns: Vec<ResolvedBoolColumn>,
static_precheck_slots: Arc<[Option<usize>]>,
}
#[derive(Clone, Debug)]
pub(crate) enum LaneOutcome {
Enabled(Arc<LaneScanProgram>),
Generic { rejection: Option<LaneRejection> },
}
impl LaneOutcome {
#[inline]
pub(crate) fn program(&self) -> Option<&Arc<LaneScanProgram>> {
match self {
Self::Enabled(program) => Some(program),
Self::Generic { .. } => None,
}
}
#[inline]
pub(crate) const fn rejection(&self) -> Option<LaneRejection> {
match self {
Self::Enabled(_) => None,
Self::Generic { rejection } => *rejection,
}
}
}
#[derive(Debug)]
pub(crate) struct PhysicalSymbol {
pub(crate) id: SymbolId,
pub(crate) publishes_match: bool,
}
#[derive(Clone, Debug)]
pub(crate) enum AggregateHistory {
None,
OffsetOnly,
Tracked {
positions: PositionTrackingSet,
labeled: Option<LabeledPositionTrackingSet>,
},
}
impl AggregateHistory {
#[inline]
pub(crate) fn empty_position_tracking(&self) -> Option<&PositionTrackingSet> {
match self {
Self::Tracked { positions, .. } => Some(positions),
Self::None | Self::OffsetOnly => None,
}
}
#[inline]
pub(crate) fn empty_labeled_tracking(&self) -> Option<&LabeledPositionTrackingSet> {
match self {
Self::Tracked { labeled, .. } => labeled.as_ref(),
Self::None | Self::OffsetOnly => None,
}
}
#[inline]
pub(crate) const fn requires_position_offset(&self) -> bool {
matches!(self, Self::OffsetOnly | Self::Tracked { .. })
}
}
pub(crate) fn executable_programs_are_dense(
programs: &[ExecutableSymbolProgram],
symbol_slots: usize,
) -> bool {
programs.len() == symbol_slots
&& matches!(programs.first(), Some(ExecutableSymbolProgram::Empty))
&& programs[1..].iter().enumerate().all(|(offset, program)| {
program
.user()
.is_some_and(|program| program.id().index() == 1 + offset)
})
}
fn publishers_cover_source(
compiled: &CompiledAutomaton,
published_mask: u64,
boundary_anchors: LaneBoundaryAnchors,
) -> bool {
if compiled.num_symbols() > 64 {
return false;
}
let start_state = compiled.nfa().start_state();
!(0..compiled.nfa().state_count()).any(|index| {
let state_id = compiled.nfa().state_id(index).expect("sealed NFA state id");
let env = boundary_anchors.dispatch_environment(state_id, start_state);
compiled.closure_transition_bitmap(env, state_id) & !published_mask != 0
})
}
fn checked_sum(left: usize, right: usize, label: &str) -> Result<usize> {
left.checked_add(right).ok_or_else(|| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE {label} exceeds usize"
))
})
}
impl SymbolExecutionPlan {
#[cfg(test)]
pub(crate) fn try_new(
compiled: &CompiledAutomaton,
symbol_columns: &[SymbolColumn],
programs: &[ExecutableSymbolProgram],
) -> Result<Self> {
Self::try_new_with_lane_facts(
compiled,
symbol_columns,
Arc::from(programs),
LaneSessionFacts::static_test(),
None,
)
.map(|(plan, _)| plan)
}
#[cfg(test)]
pub(crate) fn try_new_with_lane_facts(
compiled: &CompiledAutomaton,
symbol_columns: &[SymbolColumn],
programs: Arc<[ExecutableSymbolProgram]>,
lane_facts: LaneSessionFacts,
navigation_layout: Option<&NavigationLayout>,
) -> Result<(Self, LaneOutcome)> {
Self::try_new_with_relationships(
compiled,
symbol_columns,
&programs,
lane_facts,
navigation_layout,
&SymbolRelationships::default(),
)
}
fn try_new_with_relationships(
compiled: &CompiledAutomaton,
symbol_columns: &[SymbolColumn],
programs: &[ExecutableSymbolProgram],
lane_facts: LaneSessionFacts,
navigation_layout: Option<&NavigationLayout>,
relationships: &SymbolRelationships,
) -> Result<(Self, LaneOutcome)> {
let symbol_slots = compiled.num_symbols();
if !executable_programs_are_dense(programs, symbol_slots) {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE row symbol plan does not have dense identity across {symbol_slots} slots"
)));
}
let mut has_column = filled(symbol_slots, false, "physical symbol presence")?;
for column in symbol_columns {
let dense_index = column.id.index();
if dense_index == 0 || dense_index >= symbol_slots {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE row symbol column {} is outside the compiled user-symbol table",
column.id
)));
}
if std::mem::replace(&mut has_column[dense_index], true) {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE row symbol column {} is bound more than once",
column.id
)));
}
}
let mut static_evaluator = false;
let mut direct_evaluator = false;
let mut physical_evaluator = false;
let mut precheck_occurrences = 0usize;
let mut precheck_slot_count = 0usize;
for (program_index, program) in programs.iter().enumerate() {
let Some(program) = program.user() else {
continue;
};
let reachable = if symbol_slots <= u64::BITS as usize {
compiled.has_reachable_symbols(
compiled.nfa().start_state(),
1 << program_index,
)
} else {
compiled
.nfa()
.states()
.any(|state| !state.transitions(program.id()).is_empty())
};
if reachable {
use crate::execution::matching::{
ExecutableIncrementalEvaluator, ExecutableSymbolEvaluator,
};
match program.evaluator() {
ExecutableSymbolEvaluator::Static => static_evaluator = true,
ExecutableSymbolEvaluator::Incremental(
ExecutableIncrementalEvaluator::Direct { .. },
) => {
direct_evaluator = true;
}
ExecutableSymbolEvaluator::Incremental(
ExecutableIncrementalEvaluator::Physical { .. },
)
| ExecutableSymbolEvaluator::History(Some(_)) => {
physical_evaluator = true
}
ExecutableSymbolEvaluator::History(None) => {}
}
}
for &column in program
.static_predicate_and_columns()
.iter()
.chain(program.static_predicate_or_columns())
{
precheck_occurrences = checked_sum(
precheck_occurrences,
1,
"static-predicate column count",
)?;
let column_slots =
checked_sum(column.index(), 1, "static-predicate slot count")?;
precheck_slot_count = precheck_slot_count.max(column_slots);
}
}
let mut static_precheck_columns =
reserved(precheck_occurrences, "static-predicate columns")?;
let mut static_precheck_slots =
filled(precheck_slot_count, None, "static-predicate slots")?;
let mut physical_symbols =
reserved(symbol_columns.len(), "physical symbol entries")?;
let mut eager_incremental_ids = reserved(programs.len(), "program entries")?;
let mut eager_bitmap = 0;
let mut static_precheck_ids = reserved(programs.len(), "program entries")?;
let mut physical_publishers = 0;
for program in programs.iter().filter_map(ExecutableSymbolProgram::user) {
let id = program.id();
let evaluator = program.evaluator();
let publishes_match = !evaluator.may_read_history();
if has_column[id.index()] {
if publishes_match && symbol_slots <= u64::BITS as usize {
physical_publishers |= 1u64 << id.index();
}
physical_symbols.push(PhysicalSymbol {
id,
publishes_match,
});
}
if evaluator.has_bound_source() && publishes_match {
eager_incremental_ids.push(id);
if symbol_slots <= u64::BITS as usize {
eager_bitmap |= 1u64 << id.index();
}
}
if !program.static_predicate_and_columns().is_empty()
|| !program.static_predicate_or_columns().is_empty()
{
static_precheck_ids.push(id);
}
for &column in program
.static_predicate_and_columns()
.iter()
.chain(program.static_predicate_or_columns())
{
if static_precheck_slots[column.index()].is_none() {
static_precheck_slots[column.index()] =
Some(static_precheck_columns.len());
static_precheck_columns.push(column);
}
}
}
let published_mask = physical_publishers | eager_bitmap;
let (lane_anchors, mut lane_rejection) =
match super::lane_scan::control_rejection_with_navigation(
compiled,
programs,
lane_facts,
navigation_layout,
relationships,
) {
Ok(anchors)
if publishers_cover_source(compiled, published_mask, anchors) =>
{
(Some(anchors), None)
}
Ok(_) => (None, Some(LaneRejection::Evaluator)),
Err(reason) => (None, Some(reason)),
};
let lane_scan_program = if let Some(boundary_anchors) = lane_anchors {
let ordered_transitions =
Arc::new(OrderedTransitionTable::try_new_with_anchors(
compiled,
published_mask,
boundary_anchors,
)?);
match super::lane_scan::build_admitted_lane(
compiled,
programs,
ordered_transitions,
lane_facts,
navigation_layout,
boundary_anchors,
)? {
Ok(program) => Some(program),
Err(reason) => {
lane_rejection = Some(reason);
None
}
}
} else {
None
};
let lane_outcome = match lane_scan_program {
Some(program) => LaneOutcome::Enabled(program),
None => LaneOutcome::Generic {
rejection: lane_rejection,
},
};
Ok((
Self {
static_evaluator,
direct_evaluator,
physical_evaluator,
physical_symbols,
eager_incremental_ids,
eager_bitmap,
static_precheck_ids,
static_precheck_columns,
static_precheck_slots: static_precheck_slots.into(),
},
lane_outcome,
))
}
pub(crate) fn record_evaluator_routes(
&self,
metrics: &crate::execution::metrics::PatternMetrics,
accumulators: bool,
scans: usize,
) {
if self.static_evaluator {
metrics.route_evaluator_static.add(scans);
}
if self.direct_evaluator {
metrics.route_evaluator_direct_expr.add(scans);
}
if self.physical_evaluator {
metrics.route_evaluator_fallback.add(scans);
}
if accumulators {
metrics.route_evaluator_accumulator.add(scans);
}
}
#[inline]
pub(crate) fn physical_symbols(&self) -> &[PhysicalSymbol] {
&self.physical_symbols
}
#[inline]
pub(crate) fn eager_incremental_ids(&self) -> &[SymbolId] {
&self.eager_incremental_ids
}
#[inline]
pub(crate) fn static_precheck_ids(&self) -> &[SymbolId] {
&self.static_precheck_ids
}
#[inline]
pub(crate) fn static_precheck_columns(&self) -> &[ResolvedBoolColumn] {
&self.static_precheck_columns
}
#[inline]
pub(crate) fn static_precheck_slots(&self) -> &Arc<[Option<usize>]> {
&self.static_precheck_slots
}
}
fn compact_register_state_is_complete(prepared: &PreparedMatcherProgram) -> bool {
prepared
.vm_program
.aggregate_backend_set()
.is_registers_only()
&& prepared.vm_program.runtime_layout().tier() == VmTier::Compact
&& prepared.match_aware_symbols.is_empty()
&& !prepared
.vm_program
.symbol_programs()
.iter()
.filter_map(ExecutableSymbolProgram::user)
.any(|program| program.evaluator().may_read_history())
}
pub(in crate::execution::matching) fn compact_register_aggregate_history(
max_match_rows: Option<usize>,
) -> AggregateHistory {
let bounded_position_domain = max_match_rows
.and_then(|rows| u64::try_from(rows).ok())
.and_then(PositionOffset::try_new)
.is_some();
if bounded_position_domain {
AggregateHistory::None
} else {
AggregateHistory::OffsetOnly
}
}
fn build_tracked_history(
managed_aggregate_count: usize,
track_labels: bool,
) -> AggregateHistory {
let positions = PositionTrackingSet::new(
(0..managed_aggregate_count)
.map(|_| AggregationPositions::new())
.collect::<Vec<_>>()
.into_boxed_slice(),
);
let labeled = track_labels.then(|| {
LabeledPositionTrackingSet::new(
(0..managed_aggregate_count)
.map(|_| LabeledAggregationPositions::new())
.collect::<Vec<_>>()
.into_boxed_slice(),
)
});
AggregateHistory::Tracked { positions, labeled }
}
pub(in crate::execution::matching) fn build_exact_aggregate_history(
prepared: &PreparedMatcherProgram,
automaton: &CompiledAutomaton,
) -> AggregateHistory {
let compact_path_shape_is_available = compact_path_shape_for_skip(
automaton,
&prepared.after_match_skip,
prepared.match_aware_symbols.is_empty(),
)
.is_some();
let history_needed = automaton.has_alternations()
&& !prepared.aggregate_hot_tables.factories.is_empty()
&& !compact_path_shape_is_available
&& prepared.has_path_dependent_aggregates();
if !history_needed {
return AggregateHistory::None;
}
if prepared.has_volatile_managed_accumulators
|| prepared.deferred_history.has_volatile_operations
{
return AggregateHistory::OffsetOnly;
}
if compact_register_state_is_complete(prepared) {
return compact_register_aggregate_history(automaton.max_match_rows());
}
build_tracked_history(
prepared.aggregate_hot_tables.factories.len(),
prepared.has_unqualified_aggregates || prepared.has_classifier_aggregates,
)
}
fn lane_facts(
prepared: &PreparedMatcherProgram,
has_position_tracking: bool,
has_labeled_position_tracking: bool,
) -> LaneSessionFacts {
LaneSessionFacts::new(
prepared.vm_program.runtime_layout(),
prepared.vm_program.aggregate_backend_set(),
has_position_tracking,
has_labeled_position_tracking,
prepared.has_lookahead_defines(),
)
}
fn validate_exact_symbol_identity(
prepared: &PreparedMatcherProgram,
automaton: &CompiledAutomaton,
active_symbol_columns: &[SymbolColumn],
) -> Result<()> {
let base = prepared.automaton.as_ref();
let programs = prepared.vm_program.symbol_programs();
if base.num_symbols() != programs.len() {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE base compiled symbol table has {} slots, but its executable table has {} dense slots",
base.num_symbols(),
programs.len()
)));
}
let slots = automaton.num_symbols();
if automaton.id_to_symbol().first() != Some(&None) {
return Err(DataFusionError::Internal(
"MATCH_RECOGNIZE runtime symbol table must reserve Empty slot zero".into(),
));
}
if slots != programs.len() {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE runtime symbol table has {slots} slots, expected exactly the {} stable base slots",
programs.len()
)));
}
if let Some(column) = active_symbol_columns
.iter()
.find(|column| column.id.index() >= slots)
{
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE runtime symbol column {} is outside the exact executable automaton's {slots}-slot table",
column.id
)));
}
let mut base_identities = HashMap::with_capacity(slots);
for dense_index in 1..slots {
let base_name = base
.id_to_symbol()
.get(dense_index)
.and_then(Option::as_deref)
.ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE base executable slot {dense_index} has no pattern-variable identity"
))
})?;
let runtime_name = automaton
.id_to_symbol()
.get(dense_index)
.and_then(Option::as_deref)
.ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE runtime executable slot {dense_index} has no pattern-variable identity"
))
})?;
if let Some(previous) =
base_identities.insert(base_name.to_ascii_lowercase(), dense_index)
{
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE base executable symbols '{}' and '{}' are ambiguous by case-insensitive identity",
base.id_to_symbol()[previous]
.as_deref()
.unwrap_or("<missing>"),
base_name
)));
}
if !runtime_name.eq_ignore_ascii_case(base_name) {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE runtime symbol slot {dense_index} is '{runtime_name}', expected stable base symbol '{base_name}'; runtime pruning cannot reorder base symbol IDs"
)));
}
}
Ok(())
}
fn seal_path_representation(
prepared: &PreparedMatcherProgram,
disabled: bool,
automaton: &CompiledAutomaton,
) -> PathRepresentation {
crate::execution::matching::path::select_path_representation(
automaton,
&prepared.after_match_skip,
prepared.vm_program.aggregate_backend_set() == ManagedAggregateBackendSet::Empty
&& prepared.match_aware_symbols.is_empty(),
disabled,
)
}
pub(crate) struct ExecutablePatternVariant {
has_possessive_controls: bool,
is_never: bool,
automaton: Arc<CompiledAutomaton>,
active_symbol_columns: Arc<SymbolTable>,
symbol_programs: Arc<[ExecutableSymbolProgram]>,
start_symbol_plan: Arc<StaticStartWindow>,
final_symbols: Option<Arc<[SymbolId]>>,
pub(crate) end_anchored_alphabet_mask: Option<u64>,
symbol_execution_plan: Arc<SymbolExecutionPlan>,
path_representation: PathRepresentation,
aggregate_history: AggregateHistory,
lane_outcome: LaneOutcome,
pub(in crate::execution::matching) can_retire_ordered_siblings: bool,
runtime_memory: Option<Arc<MemoryReservation>>,
}
impl std::fmt::Debug for ExecutablePatternVariant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExecutablePatternVariant")
.field("automaton", &self.automaton)
.field("active_symbol_columns", &self.active_symbol_columns)
.field("symbol_slots", &self.symbol_programs.len())
.field("start_symbol_plan", &self.start_symbol_plan)
.field("symbol_execution_plan", &self.symbol_execution_plan)
.field("path_representation", &self.path_representation)
.field("aggregate_history", &self.aggregate_history)
.field("lane_outcome", &self.lane_outcome)
.finish()
}
}
impl ExecutablePatternVariant {
pub(crate) fn try_new(
prepared: &PreparedMatcherProgram,
normalized_pattern: &NormalizedPattern,
automaton: Arc<CompiledAutomaton>,
active_symbol_columns: Arc<SymbolTable>,
compact_paths_disabled: bool,
) -> Result<Arc<Self>> {
validate_exact_symbol_identity(
prepared,
&automaton,
active_symbol_columns.columns(),
)?;
let symbol_programs = prepared.vm_program.symbol_programs_arc();
let can_retire_ordered_siblings =
can_retire_siblings(normalized_pattern, prepared, &symbol_programs);
let aggregate_history = build_exact_aggregate_history(prepared, &automaton);
let lane_needs_history = aggregate_history.empty_position_tracking().is_some()
&& !(prepared
.vm_program
.aggregate_backend_set()
.is_registers_only()
&& !prepared.has_deferred_history_operations
&& symbol_programs.iter().any(|symbol| {
symbol.user().is_some_and(|program| {
!program.navigation_program().ops().is_empty()
})
}));
let mut facts = lane_facts(
prepared,
lane_needs_history,
lane_needs_history && aggregate_history.empty_labeled_tracking().is_some(),
);
facts.can_retire_ordered_siblings = can_retire_ordered_siblings;
facts.allow_direct_linear = !compact_paths_disabled;
let (symbol_execution_plan, lane_outcome) =
SymbolExecutionPlan::try_new_with_relationships(
&automaton,
active_symbol_columns.columns(),
&symbol_programs,
facts,
prepared.vm_program.navigation_layout(),
&prepared.relationships,
)?;
let start_symbol_plan = Arc::new(StaticStartWindow::try_new(
&automaton,
active_symbol_columns.columns(),
&symbol_programs,
prepared,
)?);
let all_static = symbol_programs
.iter()
.filter_map(ExecutableSymbolProgram::user)
.all(|p| p.evaluator().mode() == crate::core::SymbolEvalMode::Static);
let final_symbols = if all_static {
crate::execution::matching::graph::end_guard::last_symbols(&automaton)?
} else {
None
};
let end_anchored_alphabet_mask = if all_static {
crate::execution::matching::graph::end_guard::trailing_alphabet(&automaton)?
} else {
None
};
let path_representation =
seal_path_representation(prepared, compact_paths_disabled, &automaton);
let has_possessive_controls = automaton
.nfa()
.states()
.any(|state| !state.possessive_transition_controls().is_empty());
Ok(Arc::new(Self {
has_possessive_controls,
is_never: matches!(normalized_pattern, NormalizedPattern::Never),
automaton,
active_symbol_columns,
symbol_programs,
start_symbol_plan,
final_symbols,
end_anchored_alphabet_mask,
symbol_execution_plan: Arc::new(symbol_execution_plan),
path_representation,
aggregate_history,
lane_outcome,
can_retire_ordered_siblings,
runtime_memory: None,
}))
}
pub(crate) fn with_runtime_memory(
mut self: Arc<Self>,
reservation: MemoryReservation,
) -> Result<Arc<Self>> {
let variant = Arc::get_mut(&mut self).ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"runtime variant was shared before retained memory admission"
)
})?;
let mut bytes = size_of::<Self>();
let mut add = |extra: usize| -> Result<()> {
bytes = bytes.checked_add(extra).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE retained executable variant exceeds usize".into(),
)
})?;
Ok(())
};
add(variant.automaton.retained_size_bytes()?)?;
add(variant.start_symbol_plan.retained_size_bytes()?)?;
if let Some(symbols) = &variant.final_symbols {
add(size_of_val(symbols.as_ref()))?;
}
add(variant.active_symbol_columns.columns.capacity() * size_of::<SymbolColumn>())?;
let symbols = &variant.symbol_execution_plan;
add(symbols.physical_symbols.capacity() * size_of::<PhysicalSymbol>())?;
add(symbols.eager_incremental_ids.capacity() * size_of::<SymbolId>())?;
add(symbols.static_precheck_ids.capacity() * size_of::<SymbolId>())?;
add(symbols.static_precheck_columns.capacity() * size_of::<ResolvedBoolColumn>())?;
add(size_of_val(symbols.static_precheck_slots.as_ref()))?;
let lane = variant.lane_outcome.program();
if let Some(lane) = lane {
add(lane.capacity.encoded_program_bytes)?;
}
if let PathRepresentation::CompactPrefixSuffix(shape) =
&variant.path_representation
{
add(shape.retained_heap_bytes()?)?;
}
if let AggregateHistory::Tracked { positions, labeled } =
&variant.aggregate_history
{
add(positions.empty_template_retained_heap_bytes()?)?;
if let Some(labeled) = labeled {
add(labeled.empty_template_retained_heap_bytes()?)?;
}
}
reservation.try_resize(bytes)?;
variant.runtime_memory = Some(Arc::new(reservation));
Ok(self)
}
pub(crate) fn runtime_memory(&self) -> Option<Arc<MemoryReservation>> {
self.runtime_memory.clone()
}
pub(crate) fn configured(
self: &Arc<Self>,
config: &MatcherConfiguration,
) -> Arc<Self> {
if !config.compact_paths_disabled
|| !self.path_representation.uses_compact_paths()
{
return Arc::clone(self);
}
Arc::new(Self {
has_possessive_controls: self.has_possessive_controls,
is_never: self.is_never,
automaton: Arc::clone(&self.automaton),
active_symbol_columns: Arc::clone(&self.active_symbol_columns),
symbol_programs: Arc::clone(&self.symbol_programs),
start_symbol_plan: Arc::clone(&self.start_symbol_plan),
final_symbols: self.final_symbols.clone(),
end_anchored_alphabet_mask: self.end_anchored_alphabet_mask,
symbol_execution_plan: Arc::clone(&self.symbol_execution_plan),
path_representation: PathRepresentation::ArenaForced,
aggregate_history: self.aggregate_history.clone(),
lane_outcome: self.lane_outcome.clone(),
can_retire_ordered_siblings: self.can_retire_ordered_siblings,
runtime_memory: self.runtime_memory.clone(),
})
}
#[inline]
pub(crate) fn is_never(&self) -> bool {
self.is_never
}
pub(crate) fn has_possessive_controls(&self) -> bool {
self.has_possessive_controls
}
#[inline]
pub(crate) fn automaton(&self) -> &Arc<CompiledAutomaton> {
&self.automaton
}
#[inline]
pub(crate) fn automaton_arc(&self) -> Arc<CompiledAutomaton> {
Arc::clone(&self.automaton)
}
#[inline]
pub(crate) fn active_symbol_columns(&self) -> &Arc<SymbolTable> {
&self.active_symbol_columns
}
#[inline]
pub(crate) fn symbol_programs(&self) -> &[ExecutableSymbolProgram] {
&self.symbol_programs
}
#[inline]
pub(crate) fn final_symbols(&self) -> Option<&[SymbolId]> {
self.final_symbols.as_deref()
}
pub(crate) fn start_symbol_plan(&self) -> &StaticStartWindow {
&self.start_symbol_plan
}
#[inline]
pub(crate) fn symbol_execution_plan(&self) -> &SymbolExecutionPlan {
&self.symbol_execution_plan
}
#[inline]
pub(crate) fn path_representation(&self) -> &PathRepresentation {
&self.path_representation
}
#[inline]
pub(crate) fn empty_position_tracking(&self) -> Option<&PositionTrackingSet> {
self.aggregate_history.empty_position_tracking()
}
#[inline]
pub(crate) fn empty_labeled_tracking(&self) -> Option<&LabeledPositionTrackingSet> {
self.aggregate_history.empty_labeled_tracking()
}
#[inline]
pub(crate) fn requires_position_offset(&self) -> bool {
self.aggregate_history.requires_position_offset()
}
#[inline]
pub(crate) fn lane_outcome(&self) -> &LaneOutcome {
&self.lane_outcome
}
#[inline]
pub(crate) fn lane_scan_program(&self) -> Option<&Arc<LaneScanProgram>> {
self.lane_outcome.program()
}
#[inline]
pub(crate) fn enabled_lane_scan_program(
&self,
matcher: &PatternMatcher,
) -> Option<&Arc<LaneScanProgram>> {
#[cfg(test)]
if matcher.generic_scan_forced_by_control() {
return None;
}
#[cfg(not(test))]
let _ = matcher;
self.lane_scan_program()
}
}
fn strip_groups(mut pattern: &Pattern) -> &Pattern {
while let Pattern::Group(inner) = pattern {
pattern = inner;
}
pattern
}
fn can_retire_siblings(
normalized: &NormalizedPattern,
prepared: &PreparedMatcherProgram,
programs: &[ExecutableSymbolProgram],
) -> bool {
use super::vm_scratch::BoundStateSource;
let NormalizedPattern::Ast(pattern) = normalized else {
return false;
};
let Pattern::Repetition(
body,
RepetitionQuantifier::OneOrMore
| RepetitionQuantifier::OneOrMorePossessive
| RepetitionQuantifier::AtLeast(1..)
| RepetitionQuantifier::AtLeastPossessive(1..),
) = strip_groups(pattern)
else {
return false;
};
let Pattern::Alternation(branches) = strip_groups(body) else {
return false;
};
if branches.len() < 2
|| prepared
.vm_program
.aggregate_backend_set()
.requires_accumulator_state()
{
return false;
}
for branch in branches {
if !matches!(
strip_groups(branch),
Pattern::Symbol(Symbol::Named(_)) | Pattern::Exclude(Symbol::Named(_))
) {
return false;
}
}
for cell in prepared.vm_program.bound_state_cells() {
if !matches!(
cell.source(),
BoundStateSource::Register { .. } | BoundStateSource::RegisterD128 { .. }
) {
return false;
}
}
for program in programs.iter().filter_map(ExecutableSymbolProgram::user) {
if !program.navigation_program().ops().is_empty() {
return false;
}
match program.evaluator() {
ExecutableSymbolEvaluator::Static => {}
ExecutableSymbolEvaluator::Incremental(
ExecutableIncrementalEvaluator::Direct { predicate, .. },
) if predicate.has_total_register_predicate() => {}
_ => return false,
}
for writer in program.accumulation_program().ops() {
if writer.may_overflow_decimal_precision() {
return false;
}
}
}
true
}