use std::collections::HashMap;
use std::sync::OnceLock;
use crate::tree::{NodeId, NodeType, TagKey, Tree};
pub const ELEMENT: u8 = NodeType::Element as u8;
pub const TEXT: u8 = NodeType::Text as u8;
pub const CDATA: u8 = NodeType::Cdata as u8;
pub const PI: u8 = NodeType::ProcessingInstruction as u8;
pub const COMMENT: u8 = NodeType::Comment as u8;
pub const DOCUMENT: u8 = NodeType::Document as u8;
pub const DOCTYPE: u8 = NodeType::Doctype as u8;
pub struct Index {
raw: Vec<u32>,
parent: Vec<u32>,
end: Vec<u32>,
kind: Vec<u8>,
tag: Vec<u32>,
order: Vec<u32>,
names: HashMap<String, usize>,
ids: OnceLock<HashMap<String, Vec<u32>>>,
scopes: OnceLock<Scopes>,
}
pub(crate) struct Scopes {
block_at: Vec<u32>,
pub(crate) blocks: Vec<Block>,
pub(crate) decls: Vec<Decl>,
pub(crate) prefixes: usize,
}
pub(crate) struct Block {
pub(crate) first: u32,
pub(crate) len: u32,
pub(crate) parent: u32,
}
pub(crate) struct Decl {
pub(crate) node: NodeId,
pub(crate) index: u32,
pub(crate) prefix: u32,
pub(crate) undeclares: bool,
}
impl Scopes {
pub(crate) fn block_at(&self, at: u32) -> u32 {
self.block_at.get(at as usize).copied().unwrap_or(u32::MAX)
}
}
fn tag_id(names: &mut HashMap<String, usize>, key: String) -> u32 {
let next = names.len() + 1;
*names.entry(key).or_insert(next) as u32
}
impl Index {
pub fn build<T: Tree + ?Sized>(tree: &T, roots: &[NodeId]) -> Index {
let mut raw = Vec::with_capacity(tree.len());
let mut parent = Vec::with_capacity(tree.len());
let mut kind = Vec::with_capacity(tree.len());
let mut tag = Vec::with_capacity(tree.len());
let mut order = vec![u32::MAX; tree.len()];
let mut names: HashMap<String, usize> = HashMap::new();
let mut known: Vec<u32> = Vec::new();
for &root in roots {
let mut ancestors: Vec<u32> = Vec::new();
let mut at = Some(root);
while let Some(n) = at {
let pos = raw.len() as u32;
order[n as usize] = pos;
raw.push(n);
parent.push(ancestors.last().copied().unwrap_or(u32::MAX));
let k = tree.kind(n) as u8;
kind.push(k);
tag.push(if k != ELEMENT {
0
} else {
match tree.tag_key(n) {
TagKey::Known(t) => {
let t = t as usize;
match known.get(t) {
Some(&id) if id != 0 => id,
_ => {
let key = tree.local_name(n).to_ascii_lowercase();
let id = tag_id(&mut names, key);
if known.len() <= t {
known.resize(t + 1, 0);
}
known[t] = id;
id
}
}
}
TagKey::Name(name) => tag_id(&mut names, name.to_ascii_lowercase()),
}
});
at = match tree.first_child(n) {
Some(child) => {
ancestors.push(pos);
Some(child)
}
None => {
let mut up = n;
loop {
if up == root {
break None;
}
if let Some(s) = tree.next_sibling(up) {
break Some(s);
}
up = tree
.parent(up)
.expect("a node inside the root has a parent");
ancestors.pop();
}
}
};
}
}
let n = raw.len();
let mut end: Vec<u32> = (1..=n as u32).collect();
for i in (1..n).rev() {
let p = parent[i] as usize;
if p < n && end[i] > end[p] {
end[p] = end[i];
}
}
Index {
raw,
parent,
end,
kind,
tag,
order,
names,
ids: OnceLock::new(),
scopes: OnceLock::new(),
}
}
pub(crate) fn scopes(&self, tree: &dyn Tree) -> (&Scopes, bool) {
let mut built = false;
let scopes = self.scopes.get_or_init(|| {
built = true;
let mut block_at = Vec::with_capacity(self.raw.len());
let mut blocks = Vec::new();
let mut decls = Vec::new();
let mut prefixes: HashMap<&str, u32> = HashMap::new();
for (pos, &n) in self.raw.iter().enumerate() {
let up = match self.parent[pos] {
u32::MAX => u32::MAX,
p => block_at[p as usize],
};
let count = tree.namespace_declaration_count(n);
if count == 0 {
block_at.push(up);
continue;
}
let first = decls.len() as u32;
for i in (0..count).rev() {
let Some((prefix, uri)) = tree.namespace_declaration(n, i) else {
continue;
};
if prefix == "xml" {
continue;
}
let next = prefixes.len() as u32;
decls.push(Decl {
node: n,
index: i,
prefix: *prefixes.entry(prefix).or_insert(next),
undeclares: uri.is_empty(),
});
}
blocks.push(Block {
first,
len: decls.len() as u32 - first,
parent: up,
});
block_at.push(blocks.len() as u32 - 1);
}
Scopes {
block_at,
blocks,
decls,
prefixes: prefixes.len(),
}
});
(scopes, built)
}
pub fn covers(&self, tree: &dyn Tree) -> bool {
self.order.len() == tree.len()
}
pub fn len(&self) -> usize {
self.raw.len()
}
pub fn is_empty(&self) -> bool {
self.raw.is_empty()
}
pub fn order(&self, id: NodeId) -> u32 {
self.order.get(id as usize).copied().unwrap_or(u32::MAX)
}
pub fn node_at(&self, at: u32) -> NodeId {
self.raw[at as usize]
}
pub fn kind_at(&self, at: u32) -> u8 {
self.kind[at as usize]
}
pub fn tag_at(&self, at: u32) -> usize {
self.tag.get(at as usize).map_or(0, |&t| t as usize)
}
pub fn tag_id_named(&self, name: &str) -> Option<usize> {
self.names.get(&name.to_ascii_lowercase()).copied()
}
pub fn with_id<'t>(&self, id: &str, id_of: impl Fn(NodeId) -> Option<&'t str>) -> Vec<NodeId> {
let ids = self.ids.get_or_init(|| {
let mut ids: HashMap<String, Vec<u32>> = HashMap::new();
for (j, &raw) in self.raw.iter().enumerate() {
if let Some(v) = id_of(raw) {
ids.entry(v.to_string()).or_default().push(j as u32);
}
}
ids
});
ids.get(id)
.map(|at| at.iter().map(|&j| self.raw[j as usize]).collect())
.unwrap_or_default()
}
pub fn descendants(
&self,
at: u32,
include_self: bool,
keep: impl Fn(u8, usize) -> bool,
out: &mut Vec<NodeId>,
) {
let start = if include_self { at } else { at + 1 } as usize;
for j in start..self.end[at as usize] as usize {
if keep(self.kind[j], self.tag[j] as usize) {
out.push(self.raw[j]);
}
}
}
pub fn end_of(&self, at: u32) -> u32 {
self.end[at as usize]
}
pub fn parent_of(&self, at: u32) -> u32 {
self.parent[at as usize]
}
pub fn children(&self, at: u32, keep: impl Fn(u8, usize) -> bool, out: &mut Vec<NodeId>) {
let stop = self.end[at as usize] as usize;
let mut c = at as usize + 1;
while c < stop {
if keep(self.kind[c], self.tag[c] as usize) {
out.push(self.raw[c]);
}
c = self.end[c] as usize;
}
}
}