use crate::table::{Language, SYM_ERROR, SYM_ERROR_REPEAT};
pub const ERROR_COST_PER_RECOVERY: u32 = 500;
pub const ERROR_COST_PER_MISSING_TREE: u32 = 110;
pub const ERROR_COST_PER_SKIPPED_TREE: u32 = 100;
pub const ERROR_COST_PER_SKIPPED_LINE: u32 = 30;
pub const ERROR_COST_PER_SKIPPED_CHAR: u32 = 1;
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Len {
pub bytes: u32,
pub rows: u32,
}
impl Len {
#[inline(always)]
#[allow(clippy::should_implement_trait)]
pub fn add(self, o: Len) -> Len {
Len {
bytes: self.bytes.wrapping_add(o.bytes),
rows: self.rows.wrapping_add(o.rows),
}
}
#[inline(always)]
#[allow(clippy::should_implement_trait)]
pub fn sub(self, o: Len) -> Len {
Len {
bytes: self.bytes.wrapping_sub(o.bytes),
rows: self.rows.wrapping_sub(o.rows),
}
}
}
pub const NONE: u32 = u32::MAX;
pub const F_VISIBLE: u8 = 1;
pub const F_NAMED: u8 = 2;
pub const F_EXTRA: u8 = 4;
pub const F_MISSING: u8 = 8;
pub const F_KEYWORD: u8 = 16;
const F_COLD_BIT: u32 = 1 << 5;
const FLAGS_MASK: u32 = 0x1F;
const MAX_INLINE_VIS: u32 = (1 << 26) - 1;
const CHILD_COUNT_MASK: u32 = 0x00FF_FFFF;
pub(crate) const EXT_COLD_U8: u8 = 254;
pub(crate) const EXT_NONE_U8: u8 = 255;
const EXT_NONE_HI: u32 = (EXT_NONE_U8 as u32) << 24;
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Node {
pub padding: Len,
pub size: Len,
pub first_child: u32,
pub child_count_ext: u32,
pub sym: u16,
pub prod: u16,
pub packed: u32,
}
const _: () = assert!(core::mem::size_of::<Node>() == 32);
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct ColdNode {
pub error_cost: u32,
pub dprec: i32,
pub visible_descendants: u32,
pub ext: u32,
}
impl Node {
#[inline(always)]
pub fn child_count(&self) -> u32 {
self.child_count_ext & CHILD_COUNT_MASK
}
#[inline(always)]
pub(crate) fn ext_inline(&self) -> u8 {
(self.child_count_ext >> 24) as u8
}
#[inline(always)]
pub fn flags(&self) -> u8 {
(self.packed & FLAGS_MASK) as u8
}
#[inline(always)]
pub(crate) fn has_cold(&self) -> bool {
(self.packed & F_COLD_BIT) != 0
}
#[inline(always)]
pub(crate) fn cold_idx(&self) -> usize {
(self.packed >> 6) as usize
}
#[inline(always)]
pub(crate) fn inline_vis(&self) -> u32 {
self.packed >> 6
}
#[inline(always)]
pub fn set_flag(&mut self, f: u8) {
self.packed |= f as u32;
}
#[inline(always)]
pub fn clear_flag(&mut self, f: u8) {
self.packed &= !(f as u32);
}
#[inline(always)]
pub fn lchar(&self) -> u32 {
if self.child_count() == 0 {
self.first_child
} else {
0
}
}
#[inline(always)]
pub fn set_lchar(&mut self, ch: u32) {
if self.child_count() == 0 {
self.first_child = ch;
}
}
#[inline(always)]
pub fn extra(&self) -> bool {
(self.packed & F_EXTRA as u32) != 0
}
#[inline(always)]
pub fn visible(&self) -> bool {
(self.packed & F_VISIBLE as u32) != 0
}
#[inline(always)]
pub fn named(&self) -> bool {
(self.packed & F_NAMED as u32) != 0
}
#[inline(always)]
pub fn missing(&self) -> bool {
(self.packed & F_MISSING as u32) != 0
}
#[inline(always)]
pub fn is_keyword(&self) -> bool {
(self.packed & F_KEYWORD as u32) != 0
}
#[inline(always)]
pub fn is_error(&self) -> bool {
self.sym == SYM_ERROR
}
#[inline(always)]
pub fn total(&self) -> Len {
self.padding.add(self.size)
}
}
#[derive(Default)]
pub struct Arena {
pub nodes: Vec<Node>,
pub kids: Vec<u32>,
pub(crate) cold: Vec<ColdNode>,
pub ext: Vec<Vec<u8>>,
pub(crate) ext_hashes: Vec<u64>,
pub(crate) ext_table: Vec<u32>,
pub ext_total: usize,
pub(crate) vc_cache: Vec<u32>,
}
#[inline(always)]
fn extent_cost(size: Len) -> u32 {
ERROR_COST_PER_RECOVERY
.wrapping_add(ERROR_COST_PER_SKIPPED_CHAR.wrapping_mul(size.bytes))
.wrapping_add(ERROR_COST_PER_SKIPPED_LINE.wrapping_mul(size.rows))
}
#[inline(always)]
fn hash_bytes(bytes: &[u8]) -> u64 {
let mut h = 0xcbf29ce484222325u64 ^ (bytes.len() as u64);
for &b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x100000001b3);
}
h ^ (h >> 33)
}
impl Arena {
#[inline(always)]
pub fn n(&self, i: u32) -> &Node {
&self.nodes[i as usize]
}
#[inline(always)]
pub fn n_mut(&mut self, i: u32) -> &mut Node {
&mut self.nodes[i as usize]
}
#[inline(always)]
pub(crate) unsafe fn n_unchecked(&self, i: u32) -> &Node {
debug_assert!((i as usize) < self.nodes.len());
unsafe { self.nodes.get_unchecked(i as usize) }
}
#[inline(always)]
pub(crate) unsafe fn n_mut_unchecked(&mut self, i: u32) -> &mut Node {
debug_assert!((i as usize) < self.nodes.len());
unsafe { self.nodes.get_unchecked_mut(i as usize) }
}
#[inline(always)]
pub(crate) unsafe fn cost_unchecked(&self, id: u32) -> u32 {
let n = unsafe { self.n_unchecked(id) };
if !n.has_cold() {
0
} else {
unsafe { self.cold.get_unchecked(n.cold_idx()).error_cost }
}
}
#[inline(always)]
pub(crate) unsafe fn dprec_unchecked(&self, id: u32) -> i32 {
let n = unsafe { self.n_unchecked(id) };
if !n.has_cold() {
0
} else {
unsafe { self.cold.get_unchecked(n.cold_idx()).dprec }
}
}
#[inline(always)]
pub(crate) unsafe fn ext_id_unchecked(&self, id: u32) -> u32 {
let n = unsafe { self.n_unchecked(id) };
let e = n.ext_inline();
if e == EXT_NONE_U8 {
NONE
} else if e < EXT_COLD_U8 {
e as u32
} else {
unsafe { self.cold.get_unchecked(n.cold_idx()).ext }
}
}
#[inline(always)]
pub(crate) unsafe fn vis_desc_unchecked(&self, id: u32) -> u32 {
let n = unsafe { self.n_unchecked(id) };
if !n.has_cold() {
n.inline_vis()
} else {
unsafe { self.cold.get_unchecked(n.cold_idx()).visible_descendants }
}
}
#[inline(always)]
pub fn cost(&self, id: u32) -> u32 {
let n = self.n(id);
if !n.has_cold() {
0
} else {
self.cold[n.cold_idx()].error_cost
}
}
#[inline(always)]
pub fn dprec(&self, id: u32) -> i32 {
let n = self.n(id);
if !n.has_cold() {
0
} else {
self.cold[n.cold_idx()].dprec
}
}
#[inline(always)]
pub fn ext_id(&self, id: u32) -> u32 {
let n = self.n(id);
let e = n.ext_inline();
if e == EXT_NONE_U8 {
NONE
} else if e < EXT_COLD_U8 {
e as u32
} else {
self.cold[n.cold_idx()].ext
}
}
#[inline(always)]
pub fn vis_desc(&self, id: u32) -> u32 {
let n = self.n(id);
if !n.has_cold() {
n.inline_vis()
} else {
self.cold[n.cold_idx()].visible_descendants
}
}
#[inline]
fn ensure_cold_mut(&mut self, id: u32) -> &mut ColdNode {
let n = self.nodes[id as usize];
if n.has_cold() {
let idx = n.cold_idx();
&mut self.cold[idx]
} else {
let e = n.ext_inline();
let ext = if e == EXT_NONE_U8 { NONE } else { e as u32 };
let idx = self.cold.len() as u32;
self.cold.push(ColdNode {
error_cost: 0,
dprec: 0,
visible_descendants: n.inline_vis(),
ext,
});
self.nodes[id as usize].packed = (n.packed & FLAGS_MASK) | F_COLD_BIT | (idx << 6);
&mut self.cold[idx as usize]
}
}
#[inline]
pub fn set_error_cost(&mut self, id: u32, cost: u32) {
if cost != 0 || self.n(id).has_cold() {
self.ensure_cold_mut(id).error_cost = cost;
}
}
#[inline]
pub fn add_dprec(&mut self, id: u32, delta: i32) {
if delta != 0 {
self.ensure_cold_mut(id).dprec += delta;
}
}
#[inline(always)]
pub fn set_ext(&mut self, id: u32, ext: u32) {
if ext == NONE {
return;
}
if ext < EXT_COLD_U8 as u32 {
let n = self.n_mut(id);
n.child_count_ext = (n.child_count_ext & CHILD_COUNT_MASK) | (ext << 24);
if n.has_cold() {
let idx = n.cold_idx();
self.cold[idx].ext = ext;
}
} else {
let n = self.n_mut(id);
n.child_count_ext =
(n.child_count_ext & CHILD_COUNT_MASK) | ((EXT_COLD_U8 as u32) << 24);
self.ensure_cold_mut(id).ext = ext;
}
}
#[inline]
fn alloc_cold(&mut self, c: ColdNode) -> u32 {
let idx = self.cold.len() as u32;
self.cold.push(c);
idx
}
pub fn intern_ext(&mut self, bytes: &[u8]) -> u32 {
if bytes.is_empty() {
return 0;
}
let h = hash_bytes(bytes);
if self.ext_table.is_empty() {
self.ext_table.resize(32, 0);
} else if (self.ext.len() + 1) * 2 >= self.ext_table.len() {
let new_cap = self.ext_table.len() * 2;
let mut nt = vec![0u32; new_cap];
let mask = new_cap - 1;
for (idx0, &eh) in self.ext_hashes.iter().enumerate() {
let mut pos = (eh as usize) & mask;
while nt[pos] != 0 {
pos = (pos + 1) & mask;
}
nt[pos] = (idx0 + 1) as u32;
}
self.ext_table = nt;
}
let mask = self.ext_table.len() - 1;
let mut pos = (h as usize) & mask;
loop {
let slot = self.ext_table[pos];
if slot == 0 {
self.ext.push(bytes.to_vec());
self.ext_hashes.push(h);
let id = self.ext.len() as u32;
self.ext_table[pos] = id;
self.ext_total += bytes.len();
return id;
}
let idx = (slot - 1) as usize;
if self.ext_hashes[idx] == h && self.ext[idx].as_slice() == bytes {
return slot;
}
pos = (pos + 1) & mask;
}
}
#[inline(always)]
pub fn ext_bytes(&self, i: u32) -> &[u8] {
if i == 0 || i == NONE {
&[]
} else {
self.ext.get(i as usize - 1).map_or(&[], |v| v.as_slice())
}
}
#[inline(always)]
pub fn children(&self, i: u32) -> &[u32] {
let n = self.n(i);
let cc = n.child_count();
if cc == 0 {
&[]
} else {
let a = n.first_child as usize;
let b = a + cc as usize;
&self.kids[a..b]
}
}
#[inline(always)]
pub fn new_leaf(&mut self, lang: &Language, sym: u16, padding: Len, size: Len) -> u32 {
let flags = lang.leaf_flags_fast(sym) as u32;
self.push(Node {
padding,
size,
first_child: 0,
child_count_ext: EXT_NONE_HI,
sym,
prod: 0,
packed: flags,
})
}
#[inline]
pub fn new_missing_leaf(&mut self, lang: &Language, sym: u16) -> u32 {
let flags = (lang.leaf_flags_fast(sym) | F_MISSING) as u32;
let cidx = self.alloc_cold(ColdNode {
error_cost: ERROR_COST_PER_MISSING_TREE + ERROR_COST_PER_RECOVERY,
dprec: 0,
visible_descendants: 0,
ext: NONE,
});
self.push(Node {
padding: Len::default(),
size: Len::default(),
first_child: 0,
child_count_ext: EXT_NONE_HI,
sym,
prod: 0,
packed: flags | F_COLD_BIT | (cidx << 6),
})
}
#[inline(always)]
fn push(&mut self, n: Node) -> u32 {
let id = self.nodes.len() as u32;
self.nodes.push(n);
id
}
#[cold]
fn count_visible_children(&mut self, lang: &Language, root_id: u32) -> u32 {
let r = root_id as usize;
if r < self.vc_cache.len() && self.vc_cache[r] != NONE {
return self.vc_cache[r];
}
if self.vc_cache.len() <= r {
self.vc_cache.resize(self.nodes.len(), NONE);
}
let mut stack: Vec<(u32, bool)> = vec![(root_id, false)];
while let Some((id, expanded)) = stack.pop() {
let idx = id as usize;
if idx < self.vc_cache.len() && self.vc_cache[idx] != NONE {
continue;
}
let n = self.nodes[idx];
let cc = n.child_count() as usize;
let start = n.first_child as usize;
let end = start + cc;
let alias = lang.alias_sequence(n.prod);
if !expanded {
stack.push((id, true));
let mut structural = 0usize;
for k in start..end {
let c = self.kids[k];
let ch = self.nodes[c as usize];
let aliased = !ch.extra()
&& ch.sym != 0
&& alias.is_some_and(|a| a.get(structural).copied().unwrap_or(0) != 0);
if !aliased && !ch.visible() && ch.child_count() > 0 {
let cu = c as usize;
if cu >= self.vc_cache.len() || self.vc_cache[cu] == NONE {
stack.push((c, false));
}
}
if !ch.extra() {
structural += 1;
}
}
} else {
let mut count = 0u32;
let mut structural = 0usize;
for k in start..end {
let c = self.kids[k];
let ch = self.nodes[c as usize];
let aliased = !ch.extra()
&& ch.sym != 0
&& alias.is_some_and(|a| a.get(structural).copied().unwrap_or(0) != 0);
if aliased || ch.visible() {
count += 1;
} else if ch.child_count() > 0 {
count += self.vc_cache[c as usize];
}
if !ch.extra() {
structural += 1;
}
}
if idx >= self.vc_cache.len() {
self.vc_cache.resize(self.nodes.len(), NONE);
}
self.vc_cache[idx] = count;
}
}
self.vc_cache[r]
}
#[inline]
pub fn new_node(&mut self, lang: &Language, sym: u16, children: &[u32], prod: u16) -> u32 {
let n_kids = children.len();
let is_err_parent = sym == SYM_ERROR || sym == SYM_ERROR_REPEAT;
if n_kids == 1 && prod == 0 && !is_err_parent {
let c = children[0];
let ch = *self.n(c);
if !ch.has_cold() {
let vis = ch.inline_vis() + ch.visible() as u32;
if vis <= MAX_INLINE_VIS {
let first_child = self.kids.len() as u32;
self.kids.push(c);
let flags = lang.node_flags_fast(sym) as u32;
return self.push(Node {
padding: ch.padding,
size: ch.size,
first_child,
child_count_ext: (ch.child_count_ext & 0xFF00_0000) | 1,
sym,
prod: 0,
packed: flags | (vis << 6),
});
}
}
}
if n_kids > 1 && n_kids <= CHILD_COUNT_MASK as usize && prod == 0 && !is_err_parent {
let c0 = children[0];
let ch0 = *self.n(c0);
let padding = ch0.padding;
let mut size = ch0.size;
let mut or_packed = ch0.packed;
let mut vis = ch0.inline_vis().saturating_add(ch0.visible() as u32);
let mut ext_hi = ch0.child_count_ext & 0xFF00_0000;
for &c in &children[1..] {
let ch = *self.n(c);
size = size.add(ch.total());
or_packed |= ch.packed;
vis = vis.saturating_add(ch.inline_vis() + ch.visible() as u32);
let ce = ch.child_count_ext & 0xFF00_0000;
if ce != EXT_NONE_HI {
ext_hi = ce;
}
}
if (or_packed & F_COLD_BIT) == 0 && vis <= MAX_INLINE_VIS {
let first_child = self.kids.len() as u32;
self.kids.extend_from_slice(children);
let flags = lang.node_flags_fast(sym) as u32;
return self.push(Node {
padding,
size,
first_child,
child_count_ext: ext_hi | (n_kids as u32),
sym,
prod: 0,
packed: flags | (vis << 6),
});
}
}
self.new_node_general(lang, sym, children, prod, is_err_parent)
}
#[inline]
pub(crate) unsafe fn new_node_unchecked(
&mut self,
lang: &Language,
sym: u16,
children: &[u32],
prod: u16,
) -> u32 {
let n_kids = children.len();
let is_err_parent = sym == SYM_ERROR || sym == SYM_ERROR_REPEAT;
if n_kids == 1 && prod == 0 && !is_err_parent {
let c = unsafe { *children.get_unchecked(0) };
let ch = *unsafe { self.n_unchecked(c) };
if !ch.has_cold() {
let vis = ch.inline_vis() + ch.visible() as u32;
if vis <= MAX_INLINE_VIS {
let first_child = self.kids.len() as u32;
self.kids.push(c);
let flags = lang.node_flags_fast(sym) as u32;
return self.push(Node {
padding: ch.padding,
size: ch.size,
first_child,
child_count_ext: (ch.child_count_ext & 0xFF00_0000) | 1,
sym,
prod: 0,
packed: flags | (vis << 6),
});
}
}
}
if n_kids > 1 && n_kids <= CHILD_COUNT_MASK as usize && prod == 0 && !is_err_parent {
let c0 = unsafe { *children.get_unchecked(0) };
let ch0 = *unsafe { self.n_unchecked(c0) };
let padding = ch0.padding;
let mut size = ch0.size;
let mut or_packed = ch0.packed;
let mut vis = ch0.inline_vis().saturating_add(ch0.visible() as u32);
let mut ext_hi = ch0.child_count_ext & 0xFF00_0000;
for &c in unsafe { children.get_unchecked(1..) } {
let ch = *unsafe { self.n_unchecked(c) };
size = size.add(ch.total());
or_packed |= ch.packed;
vis = vis.saturating_add(ch.inline_vis() + ch.visible() as u32);
let ce = ch.child_count_ext & 0xFF00_0000;
if ce != EXT_NONE_HI {
ext_hi = ce;
}
}
if (or_packed & F_COLD_BIT) == 0 && vis <= MAX_INLINE_VIS {
let first_child = self.kids.len() as u32;
self.kids.extend_from_slice(children);
let flags = lang.node_flags_fast(sym) as u32;
return self.push(Node {
padding,
size,
first_child,
child_count_ext: ext_hi | (n_kids as u32),
sym,
prod: 0,
packed: flags | (vis << 6),
});
}
}
self.new_node_general(lang, sym, children, prod, is_err_parent)
}
fn new_node_general(
&mut self,
lang: &Language,
sym: u16,
children: &[u32],
prod: u16,
is_err_parent: bool,
) -> u32 {
let first_child = self.kids.len() as u32;
self.kids.extend_from_slice(children);
let flags = lang.node_flags_fast(sym) as u32;
let mut padding = Len::default();
let mut size = Len::default();
let mut error_cost = 0u32;
let mut dprec = 0i32;
let mut vis_desc = 0u32;
let mut ext = NONE;
let alias = lang.alias_sequence(prod);
let mut structural = 0usize;
for (i, &c) in children.iter().enumerate() {
let ch = *self.n(c);
if i == 0 {
padding = ch.padding;
size = ch.size;
} else {
size = size.add(ch.total());
}
let (ch_cost, ch_dprec, ch_vis, ch_ext) = if ch.has_cold() {
let cn = self.cold[ch.cold_idx()];
let ce = {
let e = ch.ext_inline();
if e == EXT_NONE_U8 {
NONE
} else if e < EXT_COLD_U8 {
e as u32
} else {
cn.ext
}
};
(cn.error_cost, cn.dprec, cn.visible_descendants, ce)
} else {
let e = ch.ext_inline();
let ce = if e == EXT_NONE_U8 { NONE } else { e as u32 };
(0, 0, ch.inline_vis(), ce)
};
if ch.sym == SYM_ERROR_REPEAT {
error_cost = error_cost.wrapping_add(ch_cost.wrapping_sub(extent_cost(ch.size)));
} else {
error_cost = error_cost.wrapping_add(ch_cost);
let gc = ch.child_count();
if is_err_parent && !ch.extra() && !(ch.is_error() && gc == 0) {
if ch.visible() {
error_cost = error_cost.wrapping_add(ERROR_COST_PER_SKIPPED_TREE);
} else if gc > 0 {
let vc = self.count_visible_children(lang, c);
error_cost =
error_cost.wrapping_add(ERROR_COST_PER_SKIPPED_TREE.wrapping_mul(vc));
}
}
}
dprec += ch_dprec;
if ch_ext != NONE {
ext = ch_ext;
}
vis_desc += ch_vis;
let aliased = !ch.extra()
&& ch.sym != 0
&& alias.is_some_and(|a| a.get(structural).copied().unwrap_or(0) != 0);
if aliased || ch.visible() {
vis_desc += 1;
}
if !ch.extra() {
structural += 1;
}
}
if is_err_parent {
error_cost = error_cost.wrapping_add(extent_cost(size));
}
let (ext_hi, ext_needs_cold) = if ext == NONE {
(EXT_NONE_HI, false)
} else if ext < EXT_COLD_U8 as u32 {
(ext << 24, false)
} else {
((EXT_COLD_U8 as u32) << 24, true)
};
let packed =
if error_cost == 0 && dprec == 0 && !ext_needs_cold && vis_desc <= MAX_INLINE_VIS {
flags | (vis_desc << 6)
} else {
let cidx = self.alloc_cold(ColdNode {
error_cost,
dprec,
visible_descendants: vis_desc,
ext,
});
flags | F_COLD_BIT | (cidx << 6)
};
let cc = (children.len() as u32).min(CHILD_COUNT_MASK);
self.push(Node {
padding,
size,
first_child,
child_count_ext: ext_hi | cc,
sym,
prod,
packed,
})
}
pub fn new_error_node(&mut self, lang: &Language, children: &[u32], extra: bool) -> u32 {
let i = self.new_node(lang, SYM_ERROR, children, 0);
if extra {
self.n_mut(i).set_flag(F_EXTRA);
}
i
}
pub fn compare(&self, a: u32, b: u32) -> i32 {
let mut work = vec![(a, b)];
while let Some((l, r)) = work.pop() {
let (ln, rn) = (self.n(l), self.n(r));
let res = if ln.sym < rn.sym {
-1
} else if rn.sym < ln.sym {
1
} else if ln.child_count() < rn.child_count() {
-1
} else if rn.child_count() < ln.child_count() {
1
} else {
0
};
if res != 0 {
return res;
}
let (lc, rc) = (self.children(l), self.children(r));
for i in (0..lc.len()).rev() {
work.push((lc[i], rc[i]));
}
}
0
}
}