use crate::core::SymbolId;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct AutomatonStateId(usize);
impl AutomatonStateId {
pub(crate) const fn try_new(index: usize, state_count: usize) -> Option<Self> {
if index < state_count {
Some(Self(index))
} else {
None
}
}
#[inline]
pub(crate) const fn from_validated(index: usize, state_count: usize) -> Self {
debug_assert!(index < state_count);
Self(index)
}
#[inline]
pub const fn index(self) -> usize {
self.0
}
}
impl fmt::Display for AutomatonStateId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EpsilonTransition {
target: AutomatonStateId,
predicate: Option<AnchorPredicate>,
}
impl EpsilonTransition {
pub(crate) const fn new(
target: AutomatonStateId,
predicate: Option<AnchorPredicate>,
) -> Self {
Self { target, predicate }
}
#[inline]
pub const fn target(self) -> AutomatonStateId {
self.target
}
#[inline]
pub const fn predicate(self) -> Option<AnchorPredicate> {
self.predicate
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PossessiveTransitionControl {
continue_state: AutomatonStateId,
exit_state: AutomatonStateId,
}
impl PossessiveTransitionControl {
pub(crate) const fn new(
continue_state: AutomatonStateId,
exit_state: AutomatonStateId,
) -> Self {
Self {
continue_state,
exit_state,
}
}
#[inline]
pub const fn continue_state(self) -> AutomatonStateId {
self.continue_state
}
#[inline]
pub const fn exit_state(self) -> AutomatonStateId {
self.exit_state
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct StateDescriptor {
is_accepting: bool,
is_excluded: bool,
transition_bitmap: u64,
}
impl StateDescriptor {
pub(crate) const fn new(
is_accepting: bool,
is_excluded: bool,
transition_bitmap: u64,
) -> Self {
Self {
is_accepting,
is_excluded,
transition_bitmap,
}
}
}
#[derive(Debug)]
pub(crate) struct PackedRows<T> {
offsets: Box<[usize]>,
values: Box<[T]>,
}
impl<T> PackedRows<T> {
pub(crate) fn new(offsets: Vec<usize>, values: Vec<T>) -> Self {
debug_assert!(!offsets.is_empty());
debug_assert_eq!(offsets.last().copied(), Some(values.len()));
Self {
offsets: offsets.into_boxed_slice(),
values: values.into_boxed_slice(),
}
}
#[inline]
fn row(&self, index: usize) -> &[T] {
&self.values[self.offsets[index]..self.offsets[index + 1]]
}
}
#[derive(Clone, Copy)]
pub struct CompiledStateRef<'a> {
nfa: &'a NFA,
id: AutomatonStateId,
descriptor: &'a StateDescriptor,
}
impl fmt::Debug for CompiledStateRef<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CompiledStateRef")
.field("id", &self.id)
.field("descriptor", self.descriptor)
.finish_non_exhaustive()
}
}
impl<'a> CompiledStateRef<'a> {
#[inline]
pub const fn is_accepting(self) -> bool {
self.descriptor.is_accepting
}
#[inline]
pub const fn is_excluded(self) -> bool {
self.descriptor.is_excluded
}
#[inline]
pub const fn transition_bitmap(self) -> u64 {
self.descriptor.transition_bitmap
}
#[inline]
pub fn transitions(self, symbol: SymbolId) -> &'a [AutomatonStateId] {
self.nfa.transition_row(self.id, symbol.index())
}
#[inline]
pub fn transition_rows(
self,
) -> impl ExactSizeIterator<Item = (SymbolId, &'a [AutomatonStateId])> + Clone + 'a
{
let slot_count = self.nfa.symbol_slot_count;
(1..slot_count).map(move |index| {
let symbol = SymbolId::try_new(index, slot_count)
.expect("non-zero sealed transition slots are user symbols");
(symbol, self.nfa.transition_row(self.id, index))
})
}
#[inline]
pub(crate) fn transition_slots(
self,
) -> impl ExactSizeIterator<Item = &'a [AutomatonStateId]> + Clone + 'a {
(0..self.nfa.symbol_slot_count)
.map(move |index| self.nfa.transition_row(self.id, index))
}
#[inline]
pub fn epsilon_transitions(self) -> &'a [EpsilonTransition] {
self.nfa.epsilon_transitions.row(self.id.index())
}
#[inline]
pub fn unconditional_dispatch(self) -> &'a [AutomatonStateId] {
self.nfa.unconditional_dispatch.row(self.id.index())
}
#[inline]
pub fn possessive_transition_controls(self) -> &'a [PossessiveTransitionControl] {
self.nfa.possessive_transition_controls.row(self.id.index())
}
}
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug)]
pub struct NFA {
states: Box<[StateDescriptor]>,
symbol_slot_count: usize,
transitions: PackedRows<AutomatonStateId>,
epsilon_transitions: PackedRows<EpsilonTransition>,
unconditional_dispatch: PackedRows<AutomatonStateId>,
possessive_transition_controls: PackedRows<PossessiveTransitionControl>,
start_state: AutomatonStateId,
source_payload_floor_bytes: usize,
}
impl NFA {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
states: Vec<StateDescriptor>,
symbol_slot_count: usize,
transitions: PackedRows<AutomatonStateId>,
epsilon_transitions: PackedRows<EpsilonTransition>,
unconditional_dispatch: PackedRows<AutomatonStateId>,
possessive_transition_controls: PackedRows<PossessiveTransitionControl>,
start_state: AutomatonStateId,
source_payload_floor_bytes: usize,
) -> Self {
Self {
states: states.into_boxed_slice(),
symbol_slot_count,
transitions,
epsilon_transitions,
unconditional_dispatch,
possessive_transition_controls,
start_state,
source_payload_floor_bytes,
}
}
#[inline]
fn transition_row(
&self,
id: AutomatonStateId,
symbol_index: usize,
) -> &[AutomatonStateId] {
let row = id.index() * self.symbol_slot_count + symbol_index;
self.transitions.row(row)
}
#[inline]
pub const fn start_state(&self) -> AutomatonStateId {
self.start_state
}
#[inline]
pub fn state_id(&self, index: usize) -> Option<AutomatonStateId> {
AutomatonStateId::try_new(index, self.states.len())
}
#[inline]
pub fn states(
&self,
) -> impl ExactSizeIterator<Item = CompiledStateRef<'_>> + Clone + '_ {
self.states.iter().enumerate().map(|(index, descriptor)| {
let id = AutomatonStateId::from_validated(index, self.states.len());
CompiledStateRef {
nfa: self,
id,
descriptor,
}
})
}
#[inline]
pub fn state(&self, id: AutomatonStateId) -> CompiledStateRef<'_> {
CompiledStateRef {
nfa: self,
id,
descriptor: &self.states[id.index()],
}
}
#[inline]
pub fn get_state(&self, id: AutomatonStateId) -> Option<CompiledStateRef<'_>> {
self.states
.get(id.index())
.map(|descriptor| CompiledStateRef {
nfa: self,
id,
descriptor,
})
}
#[inline]
pub fn state_count(&self) -> usize {
self.states.len()
}
pub(crate) fn retained_heap_bytes(&self) -> Option<usize> {
fn packed_bytes<T>(rows: &PackedRows<T>) -> Option<usize> {
size_of_val(rows.offsets.as_ref())
.checked_add(size_of_val(rows.values.as_ref()))
}
size_of_val(self.states.as_ref())
.checked_add(packed_bytes(&self.transitions)?)?
.checked_add(packed_bytes(&self.epsilon_transitions)?)?
.checked_add(packed_bytes(&self.unconditional_dispatch)?)?
.checked_add(packed_bytes(&self.possessive_transition_controls)?)
}
#[inline]
pub const fn source_payload_floor_bytes(&self) -> usize {
self.source_payload_floor_bytes
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum AnchorPredicate {
StartOfInput,
EndOfInput,
}