use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use crate::hw;
use crate::table::{Action, EOF_CP, Language, LexTable, NO_SYM, SYM_ERROR, SYM_ERROR_REPEAT};
pub(crate) const MIXED_ACCEPT: u16 = 0xFFFE;
pub(crate) const NO_LOOP: u16 = 0xFFFF;
pub(crate) const NO_ROW: u32 = u32::MAX;
#[derive(Default)]
struct FxHasher(u64);
impl Hasher for FxHasher {
#[inline]
fn finish(&self) -> u64 {
self.0
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
let mut h = self.0;
let (chunks, rem) = bytes.as_chunks::<8>();
for c in chunks {
let v = u64::from_ne_bytes(*c);
h = (h.rotate_left(5) ^ v).wrapping_mul(0x517cc1b727220a95);
}
for &b in rem {
h = (h.rotate_left(5) ^ b as u64).wrapping_mul(0x517cc1b727220a95);
}
self.0 = h;
}
#[inline]
fn write_u64(&mut self, i: u64) {
self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x517cc1b727220a95);
}
}
type FxMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>;
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub(crate) struct LexStateMeta {
pub(crate) row_off: u32,
pub(crate) accept: u16,
pub(crate) loop_id: u16,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SelfLoop {
pub(crate) lut16: [u8; 16],
pub(crate) mask_lo: u64,
pub(crate) mask_hi: u64,
pub(crate) kind: u8,
pub(crate) has_nl: bool,
}
impl SelfLoop {
#[inline(always)]
pub(crate) fn contains(&self, b: u8) -> bool {
debug_assert!(b < 128);
if b < 64 {
(self.mask_lo >> b) & 1 != 0
} else {
(self.mask_hi >> (b - 64)) & 1 != 0
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct LexAccel {
pub(crate) states: Vec<LexStateMeta>,
pub(crate) loops: Vec<SelfLoop>,
pub(crate) direct: bool,
pub(crate) ascii_class: [u8; 128],
pub(crate) trans: Vec<u16>,
}
impl Default for LexAccel {
fn default() -> Self {
Self {
states: Vec::new(),
loops: Vec::new(),
direct: true,
ascii_class: [0; 128],
trans: Vec::new(),
}
}
}
impl PartialEq for LexAccel {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for LexAccel {}
#[inline]
fn hash_row_u16_128(row: &[u16; 128]) -> u64 {
let mut h = 0xcbf29ce484222325u64;
let ptr = row.as_ptr() as *const u64;
for k in 0..32 {
let v = unsafe { core::ptr::read_unaligned(ptr.add(k)) };
h = (h.rotate_left(5) ^ v).wrapping_mul(0x517cc1b727220a95);
}
h
}
#[inline(always)]
fn range_mask_u128(pos: usize, end: usize) -> u128 {
debug_assert!(pos < end && end <= 128);
let hi = if end == 128 {
u128::MAX
} else {
(1u128 << end) - 1
};
let lo = (1u128 << pos) - 1;
hi ^ lo
}
struct RowDeduper {
rows: Vec<[u16; 128]>,
hashes: Vec<u64>,
buckets: Vec<u32>,
const_map: FxMap<u16, u32>,
}
impl RowDeduper {
fn new(est: usize) -> Self {
let cap = (est * 2).next_power_of_two().max(64);
Self {
rows: Vec::with_capacity(est.min(512)),
hashes: Vec::with_capacity(est.min(512)),
buckets: vec![0u32; cap],
const_map: FxMap::default(),
}
}
#[inline]
fn intern_const(&mut self, val: u16) -> u32 {
if let Some(&id) = self.const_map.get(&val) {
return id;
}
let row = [val; 128];
let id = self.intern(&row);
self.const_map.insert(val, id);
id
}
fn grow(&mut self) {
let new_cap = self.buckets.len() * 2;
let mut nb = vec![0u32; new_cap];
let mask = new_cap - 1;
for (i, &h) in self.hashes.iter().enumerate() {
let mut pos = (h as usize) & mask;
while nb[pos] != 0 {
pos = (pos + 1) & mask;
}
nb[pos] = (i + 1) as u32;
}
self.buckets = nb;
}
#[inline]
fn intern(&mut self, row: &[u16; 128]) -> u32 {
let h = hash_row_u16_128(row);
if (self.rows.len() + 1) * 2 >= self.buckets.len() {
self.grow();
}
let mask = self.buckets.len() - 1;
let mut pos = (h as usize) & mask;
loop {
let slot = self.buckets[pos];
if slot == 0 {
let id = self.rows.len() as u32;
self.rows.push(*row);
self.hashes.push(h);
self.buckets[pos] = id + 1;
return id;
}
let idx = (slot - 1) as usize;
if self.hashes[idx] == h && &self.rows[idx] == row {
return idx as u32;
}
pos = (pos + 1) & mask;
}
}
}
pub(crate) fn build_lex_accel(t: &LexTable) -> LexAccel {
let sc = t.state_count();
if sc == 0 {
return LexAccel::default();
}
let mut sink_accept = vec![NO_SYM; sc];
for (q, slot) in sink_accept.iter_mut().enumerate() {
let a = t.starts[q] as usize;
let b = t.starts[q + 1] as usize;
if a < b {
let first = t.segs[a];
let sym = first.accept;
if sym != NO_SYM
&& sym < 0x3FFF
&& t.segs[a..b]
.iter()
.all(|seg| seg.kind() == 0 && seg.accept == sym)
{
*slot = sym;
}
}
}
let mut states = Vec::with_capacity(sc);
let mut loops: Vec<SelfLoop> = Vec::new();
let mut loop_map: FxMap<(u64, u64, u8), u16> = FxMap::default();
let mut deduper = RowDeduper::new(sc.min(1024));
let mut state_row_idx: Vec<u32> = Vec::with_capacity(sc);
for s in 0..sc {
let a = t.starts[s] as usize;
let b = t.starts[s + 1] as usize;
if b == a + 1 || a >= b {
let seg = if a < b {
t.segs[a]
} else {
crate::table::Seg::new(0, NO_SYM, 0, 0)
};
let kind = seg.kind();
let tgt = seg.target();
if kind != 0 && tgt as usize >= sc {
state_row_idx.push(NO_ROW);
states.push(LexStateMeta {
row_off: NO_ROW,
accept: MIXED_ACCEPT,
loop_id: NO_LOOP,
});
continue;
}
let packed = if kind == 1 && sink_accept[tgt as usize] != NO_SYM {
(3u16 << 14) | sink_accept[tgt as usize]
} else {
seg.packed
};
let mut loop_id = NO_LOOP;
if kind != 0 && tgt == s as u16 {
let key = (u64::MAX, u64::MAX, kind);
if let Some(&id) = loop_map.get(&key) {
loop_id = id;
} else if loops.len() < NO_LOOP as usize {
let id = loops.len() as u16;
loops.push(SelfLoop {
lut16: hw::build_ascii_lut16(u64::MAX, u64::MAX),
mask_lo: u64::MAX,
mask_hi: u64::MAX,
kind,
has_nl: true,
});
loop_map.insert(key, id);
loop_id = id;
}
}
let ridx = deduper.intern_const(packed);
state_row_idx.push(ridx);
states.push(LexStateMeta {
row_off: 0,
accept: seg.accept,
loop_id,
});
continue;
}
let mut row = [0u16; 128];
let mut uniform_accept = NO_SYM;
let mut first_seg = true;
let mut valid_row = true;
let mut pos = 0usize;
let s_u16 = s as u16;
let (mut m1, mut m2) = (0u128, 0u128);
for k in 0..(b - a) {
let seg = t.segs[a + k];
let next_lo = if k + 1 < b - a {
t.segs[a + k + 1].lo
} else {
128
};
let end = (next_lo as usize).min(128);
if end > pos {
if first_seg {
uniform_accept = seg.accept;
first_seg = false;
} else if seg.accept != uniform_accept {
uniform_accept = MIXED_ACCEPT;
}
let kind = seg.kind();
let tgt = seg.target();
let packed = if kind != 0 {
if tgt as usize >= sc {
valid_row = false;
seg.packed
} else if kind == 1 && sink_accept[tgt as usize] != NO_SYM {
(3u16 << 14) | sink_accept[tgt as usize]
} else {
if tgt == s_u16 {
let rm = range_mask_u128(pos, end);
if kind == 1 {
m1 |= rm;
} else {
m2 |= rm;
}
}
seg.packed
}
} else {
seg.packed
};
row[pos..end].fill(packed);
pos = end;
}
if pos >= 128 {
break;
}
}
let mut loop_id = NO_LOOP;
if valid_row && uniform_accept != MIXED_ACCEPT && (m1 | m2) != 0 {
let c1 = m1.count_ones();
let c2 = m2.count_ones();
let (mask, cnt, kind) = if c1 >= c2 {
(m1, c1, 1u8)
} else {
(m2, c2, 2u8)
};
let mlo = mask as u64;
let mhi = (mask >> 64) as u64;
if cnt >= 2 || (mlo & (1u64 << b' ')) != 0 {
let key = (mlo, mhi, kind);
if let Some(&id) = loop_map.get(&key) {
loop_id = id;
} else if loops.len() < NO_LOOP as usize {
let id = loops.len() as u16;
loops.push(SelfLoop {
lut16: hw::build_ascii_lut16(mlo, mhi),
mask_lo: mlo,
mask_hi: mhi,
kind,
has_nl: (mlo & (1u64 << b'\n')) != 0,
});
loop_map.insert(key, id);
loop_id = id;
}
}
}
if valid_row && uniform_accept != MIXED_ACCEPT {
let ridx = deduper.intern(&row);
state_row_idx.push(ridx);
states.push(LexStateMeta {
row_off: 0,
accept: uniform_accept,
loop_id,
});
} else {
state_row_idx.push(NO_ROW);
states.push(LexStateMeta {
row_off: NO_ROW,
accept: MIXED_ACCEPT,
loop_id: NO_LOOP,
});
}
}
let unique_rows = deduper.rows;
let u = unique_rows.len();
if u * 128 <= 65_536 {
let mut trans = Vec::with_capacity(u * 128);
for row in &unique_rows {
trans.extend_from_slice(row);
}
for s in 0..sc {
let ridx = state_row_idx[s];
if ridx != NO_ROW {
states[s].row_off = ridx * 128;
}
}
return LexAccel {
states,
loops,
direct: true,
ascii_class: [0; 128],
trans,
};
}
let mut col_hashes = [0xcbf29ce484222325u64; 128];
for row in &unique_rows {
for (h, &v) in col_hashes.iter_mut().zip(row.iter()) {
*h = (h.rotate_left(5) ^ v as u64).wrapping_mul(0x517cc1b727220a95);
}
}
let mut ascii_class = [0u8; 128];
let mut rep_bytes: Vec<u8> = Vec::with_capacity(128);
let mut col_hash_buckets: FxMap<u64, Vec<u8>> = FxMap::default();
for b in 0..128usize {
let h = col_hashes[b];
let mut found = None;
if let Some(cands) = col_hash_buckets.get(&h) {
for &cls in cands {
let rb = rep_bytes[cls as usize] as usize;
if unique_rows.iter().all(|r| r[b] == r[rb]) {
found = Some(cls);
break;
}
}
}
let cls = match found {
Some(c) => c,
None => {
let c = rep_bytes.len() as u8;
rep_bytes.push(b as u8);
col_hash_buckets.entry(h).or_default().push(c);
c
}
};
ascii_class[b] = cls;
}
let k = rep_bytes.len().max(1);
let max_rows = (262_144 / k).max(1).min(u);
let mut trans = Vec::with_capacity(max_rows * k);
for row in &unique_rows[..max_rows] {
for &rb in &rep_bytes {
trans.push(row[rb as usize]);
}
}
for s in 0..sc {
let ridx = state_row_idx[s];
if ridx != NO_ROW && (ridx as usize) < max_rows {
states[s].row_off = ridx * k as u32;
} else {
states[s].row_off = NO_ROW;
states[s].accept = MIXED_ACCEPT;
states[s].loop_id = NO_LOOP;
}
}
LexAccel {
states,
loops,
direct: false,
ascii_class,
trans,
}
}
pub(crate) enum KwLookup {
None,
Match(u16),
Fallback,
}
#[derive(Clone, Copy, Debug, Default)]
struct KwSlot {
hash: u32,
off_len: u32,
sym: u16,
out_idx: u16,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct KeywordTable {
enabled: bool,
min_len: u8,
max_len: u8,
first_lo: u64,
first_hi: u64,
skip0_lo: u64,
skip0_hi: u64,
skip0_non_ascii: bool,
mask: usize,
slots: Vec<KwSlot>,
pool: Vec<u8>,
out_masks: Vec<[u64; 2]>,
}
impl PartialEq for KeywordTable {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for KeywordTable {}
#[inline(always)]
fn kw_hash(w: &[u8]) -> u32 {
let mut h = 0x811c9dc5u32 ^ (w.len() as u32);
for &b in w {
h ^= b as u32;
h = h.wrapping_mul(0x0100_0193);
}
h ^ (h >> 16)
}
impl KeywordTable {
#[inline(always)]
pub(crate) fn is_enabled(&self) -> bool {
self.enabled
}
pub(crate) fn build(t: &LexTable) -> Self {
let sc = t.state_count();
if sc == 0 {
return Self::default();
}
struct Entry {
word: Vec<u8>,
sym: u16,
out_lo: u64,
out_hi: u64,
}
let mut entries: Vec<Entry> = Vec::new();
let mut visiting = vec![false; sc];
let mut path: Vec<u8> = Vec::with_capacity(32);
let mut visits = 0usize;
let mut skip0_mask = 0u128;
let mut skip0_non_ascii = false;
#[allow(clippy::too_many_arguments)]
fn dfs(
t: &LexTable,
sc: usize,
s: usize,
visiting: &mut [bool],
path: &mut Vec<u8>,
entries: &mut Vec<Entry>,
visits: &mut usize,
skip0_mask: &mut u128,
skip0_non_ascii: &mut bool,
) -> bool {
*visits += 1;
if *visits > 16_384 || visiting[s] || path.len() > 32 {
return false;
}
let a = t.starts[s] as usize;
let b = t.starts[s + 1] as usize;
if a >= b {
return true;
}
visiting[s] = true;
let segs = &t.segs[a..b];
let first_acc = segs[0].accept;
let mut out_lo = 0u64;
let mut out_hi = 0u64;
let mut edges: Vec<(u8, usize)> = Vec::new();
for k in 0..segs.len() {
let seg = segs[k];
if seg.accept != first_acc {
visiting[s] = false;
return false;
}
let kind = seg.kind();
let next_lo = if k + 1 < segs.len() {
segs[k + 1].lo
} else {
EOF_CP + 1
};
if kind == 2 {
if s == 0 && path.is_empty() {
let start_c = if k == 0 { 0 } else { seg.lo };
let ascii_end = next_lo.min(128);
if ascii_end > start_c {
*skip0_mask |= range_mask_u128(start_c as usize, ascii_end as usize);
}
if next_lo > 128 {
*skip0_non_ascii = true;
}
continue;
}
visiting[s] = false;
return false;
}
if kind == 1 {
if next_lo > 128 {
visiting[s] = false;
return false;
}
let tgt = seg.target() as usize;
if tgt >= sc {
visiting[s] = false;
return false;
}
let start_c = if k == 0 { 0 } else { seg.lo };
for ch in start_c..next_lo {
let c = ch as u8;
if c < 64 {
out_lo |= 1u64 << c;
} else {
out_hi |= 1u64 << (c - 64);
}
edges.push((c, tgt));
}
}
}
if first_acc != NO_SYM {
if path.is_empty() || entries.len() >= 1024 {
visiting[s] = false;
return false;
}
entries.push(Entry {
word: path.clone(),
sym: first_acc,
out_lo,
out_hi,
});
}
for (ch, tgt) in edges {
path.push(ch);
if !dfs(
t,
sc,
tgt,
visiting,
path,
entries,
visits,
skip0_mask,
skip0_non_ascii,
) {
visiting[s] = false;
return false;
}
path.pop();
}
visiting[s] = false;
true
}
if !dfs(
t,
sc,
0,
&mut visiting,
&mut path,
&mut entries,
&mut visits,
&mut skip0_mask,
&mut skip0_non_ascii,
) || entries.is_empty()
{
return Self::default();
}
let cap = (entries.len() * 2).next_power_of_two().max(16);
let mask = cap - 1;
let mut slots = vec![KwSlot::default(); cap];
let mut pool = Vec::new();
let mut out_masks: Vec<[u64; 2]> = Vec::new();
let mut min_len = u8::MAX;
let mut max_len = 0u8;
let (mut first_lo, mut first_hi) = (0u64, 0u64);
for e in entries {
let l = e.word.len() as u8;
min_len = min_len.min(l);
max_len = max_len.max(l);
let b0 = e.word[0];
if b0 < 64 {
first_lo |= 1u64 << b0;
} else {
first_hi |= 1u64 << (b0 - 64);
}
let off = pool.len();
if off >= (1 << 24) {
return Self::default();
}
pool.extend_from_slice(&e.word);
let out_idx = if e.out_lo == 0 && e.out_hi == 0 {
u16::MAX
} else {
let id = out_masks.len() as u16;
out_masks.push([e.out_lo, e.out_hi]);
id
};
let h = kw_hash(&e.word);
let mut idx = (h as usize) & mask;
while slots[idx].off_len != 0 {
idx = (idx + 1) & mask;
}
slots[idx] = KwSlot {
hash: h,
off_len: ((l as u32) << 24) | (off as u32),
sym: e.sym,
out_idx,
};
}
KeywordTable {
enabled: true,
min_len,
max_len,
first_lo,
first_hi,
skip0_lo: skip0_mask as u64,
skip0_hi: (skip0_mask >> 64) as u64,
skip0_non_ascii,
mask,
slots,
pool,
out_masks,
}
}
#[inline(always)]
pub(crate) fn lookup(&self, word: &[u8], next_byte: Option<u8>) -> KwLookup {
if !self.enabled {
return KwLookup::Fallback;
}
let len = word.len();
if len == 0 {
return KwLookup::None;
}
let b0 = unsafe { *word.get_unchecked(0) };
if b0 >= 128 {
return if self.skip0_non_ascii {
KwLookup::Fallback
} else {
KwLookup::None
};
}
let fhit = if b0 < 64 {
if ((self.skip0_lo >> b0) & 1) != 0 {
return KwLookup::Fallback;
}
(self.first_lo >> b0) & 1
} else {
if ((self.skip0_hi >> (b0 - 64)) & 1) != 0 {
return KwLookup::Fallback;
}
(self.first_hi >> (b0 - 64)) & 1
};
if fhit == 0 || len < self.min_len as usize || len > self.max_len as usize {
return KwLookup::None;
}
let h = kw_hash(word);
let mut idx = (h as usize) & self.mask;
loop {
let slot = unsafe { *self.slots.get_unchecked(idx) };
let ol = slot.off_len;
if ol == 0 {
return KwLookup::None;
}
if slot.hash == h && (ol >> 24) as usize == len {
let off = (ol & 0x00FF_FFFF) as usize;
let cand = unsafe { self.pool.get_unchecked(off..off + len) };
if cand == word {
if slot.out_idx == u16::MAX {
return KwLookup::Match(slot.sym);
}
match next_byte {
None => return KwLookup::Match(slot.sym),
Some(nb) if nb < 128 => {
let m = unsafe { *self.out_masks.get_unchecked(slot.out_idx as usize) };
let cont = if nb < 64 {
(m[0] >> nb) & 1
} else {
(m[1] >> (nb - 64)) & 1
};
return if cont == 0 {
KwLookup::Match(slot.sym)
} else {
KwLookup::Fallback
};
}
Some(_) => return KwLookup::Match(slot.sym),
}
}
}
idx = (idx + 1) & self.mask;
}
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct DenseTable {
pub(crate) states: usize,
pub(crate) stride: usize,
pub(crate) stripped: bool,
pub(crate) data: Vec<u16>,
}
impl PartialEq for DenseTable {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for DenseTable {}
#[derive(Clone, Debug, Default)]
pub(crate) struct SparseEntries {
pub(crate) syms: Vec<u16>,
pub(crate) vals: Vec<u16>,
pub(crate) starts: Vec<u32>,
}
impl PartialEq for SparseEntries {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for SparseEntries {}
pub(crate) const FA_EMPTY: u64 = 0;
pub(crate) const FA_SHIFT: u64 = 1;
pub(crate) const FA_REDUCE: u64 = 2;
pub(crate) const FA_ACCEPT: u64 = 3;
pub(crate) const FA_RECOVER: u64 = 4;
pub(crate) const FA_MULTI: u64 = 5;
#[inline(always)]
pub(crate) fn fa_tag(v: u64) -> u64 {
v & 7
}
#[inline(always)]
pub(crate) fn fa_shift_state(v: u64) -> u16 {
(v >> 16) as u16
}
#[inline(always)]
pub(crate) fn fa_shift_extra(v: u64) -> bool {
(v & 8) != 0
}
#[inline(always)]
pub(crate) fn fa_shift_rep(v: u64) -> bool {
(v & 16) != 0
}
#[inline(always)]
pub(crate) fn fa_reduce_count(v: u64) -> u16 {
((v >> 3) & 0x0FFF) as u16
}
#[inline(always)]
pub(crate) fn fa_reduce_symbol(v: u64) -> u16 {
(v >> 16) as u16
}
#[inline(always)]
pub(crate) fn fa_reduce_dprec(v: u64) -> i16 {
(v >> 32) as i16
}
#[inline(always)]
pub(crate) fn fa_reduce_prod(v: u64) -> u16 {
(v >> 48) as u16
}
#[inline(always)]
pub(crate) fn fa_multi_start(v: u64) -> usize {
(v >> 32) as usize
}
#[inline(always)]
pub(crate) fn fa_multi_len(v: u64) -> usize {
((v >> 16) & 0xFFFF) as usize
}
#[derive(Clone, Debug, Default)]
pub(crate) struct FastParseMeta {
pub(crate) fast_actions: Vec<u64>,
pub(crate) node_flags: Vec<u8>,
pub(crate) leaf_flags: Vec<u8>,
}
impl PartialEq for FastParseMeta {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for FastParseMeta {}
pub(crate) fn build_fast_parse_meta(lang: &Language) -> FastParseMeta {
let mut fast_actions = vec![FA_EMPTY; lang.actions.len().max(1)];
let mut i = 0usize;
while i < lang.actions.len() {
if let Action::Header(n) = lang.actions[i] {
let n_us = n as usize;
let end = i + 1 + n_us;
if end <= lang.actions.len() {
if n_us == 1 {
fast_actions[i] = match lang.actions[i + 1] {
Action::Shift {
state,
extra,
repetition,
} => {
FA_SHIFT
| ((extra as u64) << 3)
| ((repetition as u64) << 4)
| ((state as u64) << 16)
}
Action::Reduce {
symbol,
count,
dprec,
prod,
} if count < 4096 => {
FA_REDUCE
| ((count as u64) << 3)
| ((symbol as u64) << 16)
| ((dprec as u16 as u64) << 32)
| ((prod as u64) << 48)
}
Action::Reduce { .. } => FA_MULTI | (1u64 << 16) | (((i + 1) as u64) << 32),
Action::Accept => FA_ACCEPT,
Action::Recover => FA_RECOVER,
Action::Header(_) => FA_EMPTY,
};
} else if n_us > 1 {
fast_actions[i] = FA_MULTI | ((n as u64) << 16) | (((i + 1) as u64) << 32);
}
i = end;
continue;
}
}
i += 1;
}
let mut node_flags: Vec<u8> = lang.symbol_metadata.iter().map(|&m| m & 3).collect();
let mut leaf_flags = node_flags.clone();
if !leaf_flags.is_empty() {
leaf_flags[0] |= crate::tree::F_EXTRA;
}
let _ = (SYM_ERROR, SYM_ERROR_REPEAT, &mut node_flags);
FastParseMeta {
fast_actions,
node_flags,
leaf_flags,
}
}
pub(crate) fn build_sparse_entries(
state_count: usize,
dense_states: usize,
state_start: &[u32],
entries: &[u32],
) -> SparseEntries {
if dense_states >= state_count || state_start.len() <= state_count {
return SparseEntries::default();
}
let rem_states = state_count - dense_states;
let first_off = state_start[dense_states] as usize;
let last_off = state_start[state_count] as usize;
let total = last_off.saturating_sub(first_off);
let mut syms = Vec::with_capacity(total + 16);
let mut vals = Vec::with_capacity(total);
let mut starts = Vec::with_capacity(rem_states + 1);
for &off in &state_start[dense_states..=state_count] {
starts.push(off.saturating_sub(first_off as u32));
}
for &x in &entries[first_off..last_off.min(entries.len())] {
syms.push((x >> 16) as u16);
vals.push((x & 0xFFFF) as u16);
}
syms.extend_from_slice(&[0xFFFF; 16]);
SparseEntries { syms, vals, starts }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::langs::Lang;
use crate::lexer::Lexer;
const ALL_TAGS: [&str; 41] = [
"c",
"cpp",
"csharp",
"go",
"java",
"javascript",
"typescript",
"tsx",
"php",
"python",
"rust",
"lua",
"bash",
"ruby",
"kotlin",
"css",
"html",
"objc",
"dart",
"julia",
"nix",
"dockerfile",
"ocaml",
"elixir",
"r",
"svelte",
"solidity",
"groovy",
"make",
"scheme",
"commonlisp",
"pascal",
"gleam",
"powershell",
"cmake",
"erlang",
"hcl",
"vue",
"d",
"elm",
"verilog",
];
#[test]
fn all_41_lex_accel_matches_raw_lex_find() {
for tag in ALL_TAGS {
let lang = Lang::from_tag(tag).unwrap().table().unwrap();
let t = &lang.lex;
let accel = &t.accel;
assert_eq!(accel.states.len(), t.state_count(), "{tag} state len");
for s in 0..t.state_count() {
let meta = accel.states[s];
if meta.row_off == NO_ROW {
continue;
}
for b in 0u8..128 {
let raw = t.find(s as u16, b as u32);
assert_eq!(meta.accept, raw.accept, "{tag} s={s} b={b} accept");
let col = if accel.direct {
b as usize
} else {
accel.ascii_class[b as usize] as usize
};
let packed = accel.trans[meta.row_off as usize + col];
let kind = packed >> 14;
let target = packed & 0x3FFF;
if kind == 3 {
assert_eq!(
raw.kind(),
1,
"{tag} s={s} b={b} fused must come from kind 1"
);
let sink_s = raw.target();
let sink_a = t.starts[sink_s as usize] as usize;
let sink_b = t.starts[sink_s as usize + 1] as usize;
assert_eq!(sink_b - sink_a, 1, "{tag} fused sink must be 1 seg");
assert_eq!(t.segs[sink_a].kind(), 0);
assert_eq!(t.segs[sink_a].accept, target);
} else {
assert_eq!(kind as u8, raw.kind(), "{tag} s={s} b={b} kind");
if kind != 0 {
assert_eq!(target, raw.target(), "{tag} s={s} b={b} target");
}
}
if meta.loop_id != NO_LOOP {
let sl = &accel.loops[meta.loop_id as usize];
let is_self = raw.kind() == sl.kind && raw.target() == s as u16;
assert_eq!(sl.contains(b), is_self, "{tag} s={s} b={b} self_loop");
}
}
}
}
}
#[test]
fn all_41_keyword_tables_match_keyword_lex() {
let mut enabled_langs = 0usize;
for tag in ALL_TAGS {
let lang = Lang::from_tag(tag).unwrap().table().unwrap();
if lang.keyword_capture_token == 0 || lang.keyword_lex.state_count() == 0 {
continue;
}
if !lang.kw_table.is_enabled() {
continue;
}
enabled_langs += 1;
let mut words: Vec<Vec<u8>> = Vec::new();
for slot in &lang.kw_table.slots {
if slot.off_len == 0 {
continue;
}
let len = (slot.off_len >> 24) as usize;
let off = (slot.off_len & 0x00FF_FFFF) as usize;
words.push(lang.kw_table.pool[off..off + len].to_vec());
}
assert!(!words.is_empty(), "{tag} enabled kw_table has 0 words");
let mut probes: Vec<Vec<u8>> = words.clone();
for w in words.iter().take(32) {
if w.len() > 1 {
probes.push(w[..w.len() - 1].to_vec());
}
let mut ext = w.clone();
ext.push(b'x');
probes.push(ext);
let mut sp = vec![b' '];
sp.extend_from_slice(w);
probes.push(sp);
let mut bs = vec![b'\\'];
bs.extend_from_slice(w);
probes.push(bs);
}
probes.push(b"".to_vec());
probes.push(b"__not_a_keyword_123".to_vec());
probes.push("中文标识符".as_bytes().to_vec());
for word in &probes {
for next_b in [
None,
Some(b' '),
Some(b'_'),
Some(b'a'),
Some(b'0'),
Some(0x80),
] {
let mut input = word.clone();
if let Some(nb) = next_b {
input.push(nb);
}
let mut lx = Lexer::new(&input);
lx.start();
let ok = lx.run(&lang.keyword_lex, 0);
lx.finish();
let kend = lx.token_end.unwrap_or(lx.pos).bytes as usize;
let expected = if ok && kend == word.len() {
Some(lx.result)
} else {
None
};
match lang.kw_table.lookup(word, next_b) {
KwLookup::None => {
assert_eq!(
expected,
None,
"{tag} word={:?} next={next_b:?} missed keyword",
String::from_utf8_lossy(word)
);
}
KwLookup::Match(sym) => {
assert_eq!(
expected,
Some(sym),
"{tag} word={:?} next={next_b:?} wrong match",
String::from_utf8_lossy(word)
);
}
KwLookup::Fallback => {}
}
}
}
}
assert!(
enabled_langs >= 25,
"expected >= 25 languages with KeywordTable enabled, got {enabled_langs}"
);
}
}