use std::collections::HashSet;
use crate::model::control::{Control, FieldType};
use crate::model::document::Document;
use crate::model::paragraph::Paragraph;
use super::ast::{AttrPred, Axis, CmpOp, Combinator, Literal, Path, Pred, Pseudo, Selector, Step};
use super::error::SelectorError;
use super::glob::Glob;
use super::node::{
control_kind_name, paragraphs_of_control, runs_of, Node, NodeId, NodeRef, NodeStep, PathStack,
};
#[derive(Debug, Clone, Copy)]
pub struct EvalLimits {
pub max_nodes: usize,
pub max_depth: usize,
pub max_results: usize,
}
impl Default for EvalLimits {
fn default() -> Self {
EvalLimits {
max_nodes: 200_000,
max_depth: 64,
max_results: 50_000,
}
}
}
struct Flat<'d> {
id: NodeId,
node: Node<'d>,
step: NodeStep,
parent: Option<usize>,
index: usize,
sibling_count: usize,
}
pub fn select<'d>(sel: &Selector, doc: &'d Document) -> Result<Vec<NodeRef<'d>>, SelectorError> {
select_with(sel, doc, EvalLimits::default())
}
pub fn select_with<'d>(
sel: &Selector,
doc: &'d Document,
limits: EvalLimits,
) -> Result<Vec<NodeRef<'d>>, SelectorError> {
let flat = flatten(doc, &limits)?;
let hits = eval_paths(&sel.paths, &flat, &limits, 0)?;
if hits.len() > limits.max_results {
return Err(SelectorError::limit(
0,
format!(
"결과가 너무 많다 ({}건, 상한 {}건)",
hits.len(),
limits.max_results
),
)
.hinting("술어를 붙여 범위를 좁힌다"));
}
Ok(hits
.into_iter()
.map(|i| NodeRef {
id: flat[i].id.clone(),
node: flat[i].node,
index: flat[i].index,
sibling_count: flat[i].sibling_count,
})
.collect())
}
pub fn count<'d>(
sel: &Selector,
doc: &'d Document,
limits: EvalLimits,
) -> Result<usize, SelectorError> {
let flat = flatten(doc, &limits)?;
Ok(eval_paths(&sel.paths, &flat, &limits, 0)?.len())
}
struct Walker<'d> {
out: Vec<Flat<'d>>,
stack: PathStack,
limits: EvalLimits,
}
impl<'d> Walker<'d> {
fn emit(
&mut self,
step: NodeStep,
node: Node<'d>,
parent: Option<usize>,
index: usize,
sibling_count: usize,
) -> Result<usize, SelectorError> {
if self.out.len() >= self.limits.max_nodes {
return Err(SelectorError::limit(
0,
format!("문서 노드가 너무 많다 (상한 {})", self.limits.max_nodes),
));
}
self.stack.push(step);
let id = self.stack.snapshot();
self.out.push(Flat {
id,
node,
step,
parent,
index,
sibling_count,
});
Ok(self.out.len() - 1)
}
fn check_depth(&self) -> Result<(), SelectorError> {
if self.stack.depth() > self.limits.max_depth {
return Err(SelectorError::limit(
0,
format!("문서 중첩이 너무 깊다 (상한 {})", self.limits.max_depth),
));
}
Ok(())
}
fn walk_paragraphs(
&mut self,
paras: &'d [Paragraph],
parent: Option<usize>,
) -> Result<(), SelectorError> {
self.check_depth()?;
let total = paras.len();
for (i, para) in paras.iter().enumerate() {
let me = self.emit(NodeStep::Para(i as u32), Node::Para(para), parent, i, total)?;
self.walk_para_children(para, me)?;
self.stack.pop();
}
Ok(())
}
fn walk_para_children(
&mut self,
para: &'d Paragraph,
parent: usize,
) -> Result<(), SelectorError> {
self.check_depth()?;
let control_total = para.controls.len();
for (i, control) in para.controls.iter().enumerate() {
let me = self.emit(
NodeStep::Control(i as u32),
Node::Control(control),
Some(parent),
i,
control_total,
)?;
self.walk_control_children(control, me)?;
self.stack.pop();
}
let runs = runs_of(para);
let run_total = runs.len();
for (i, run) in runs.into_iter().enumerate() {
self.emit(
NodeStep::Run(i as u32),
Node::Run(run),
Some(parent),
i,
run_total,
)?;
self.stack.pop();
}
Ok(())
}
fn walk_control_children(
&mut self,
control: &'d Control,
parent: usize,
) -> Result<(), SelectorError> {
self.check_depth()?;
if let Control::Table(table) = control {
let total = table.cells.len();
for (i, cell) in table.cells.iter().enumerate() {
let me = self.emit(
NodeStep::Cell(i as u32),
Node::Cell(cell),
Some(parent),
i,
total,
)?;
self.walk_paragraphs(&cell.paragraphs, Some(me))?;
self.stack.pop();
}
return Ok(());
}
if let Some(paras) = paragraphs_of_control(control) {
self.walk_paragraphs(paras, Some(parent))?;
}
Ok(())
}
}
fn flatten<'d>(doc: &'d Document, limits: &EvalLimits) -> Result<Vec<Flat<'d>>, SelectorError> {
let mut w = Walker {
out: Vec::new(),
stack: PathStack::new(),
limits: *limits,
};
let total = doc.sections.len();
for (i, section) in doc.sections.iter().enumerate() {
let me = w.emit(
NodeStep::Section(i as u32),
Node::Section(section),
None,
i,
total,
)?;
w.walk_paragraphs(§ion.paragraphs, Some(me))?;
w.stack.pop();
}
Ok(w.out)
}
fn eval_paths(
paths: &[Path],
flat: &[Flat<'_>],
limits: &EvalLimits,
depth: usize,
) -> Result<Vec<usize>, SelectorError> {
if depth > super::parse::MAX_NESTING {
return Err(SelectorError::limit(
0,
format!(
"중첩 선택자가 너무 깊다 (상한 {})",
super::parse::MAX_NESTING
),
));
}
let mut seen = vec![false; flat.len()];
for path in paths {
for i in eval_path(path, flat, limits, depth)? {
seen[i] = true;
}
}
Ok((0..flat.len()).filter(|&i| seen[i]).collect())
}
fn eval_path(
path: &Path,
flat: &[Flat<'_>],
limits: &EvalLimits,
depth: usize,
) -> Result<Vec<usize>, SelectorError> {
let mut current: Vec<usize> = Vec::new();
for (si, step) in path.steps.iter().enumerate() {
let candidates = if si == 0 {
(0..flat.len())
.filter(|&i| flat[i].node.matches_axis(step.axis))
.collect()
} else {
reachable(step.combinator, ¤t, flat, step.axis)
};
current = apply_preds(candidates, step, flat, limits, depth)?;
if current.is_empty() {
break;
}
}
Ok(current)
}
fn reachable(comb: Combinator, current: &[usize], flat: &[Flat<'_>], axis: Axis) -> Vec<usize> {
let mut in_current = vec![false; flat.len()];
for &i in current {
in_current[i] = true;
}
let mut sib_exact: HashSet<(usize, u8, usize)> = HashSet::new();
let mut sib_min: std::collections::HashMap<(usize, u8), usize> =
std::collections::HashMap::new();
if matches!(comb, Combinator::NextSibling | Combinator::FollowingSibling) {
for &c in current {
let Some(p) = flat[c].parent else { continue };
let key = (p, flat[c].step.kind_ord());
sib_exact.insert((p, flat[c].step.kind_ord(), flat[c].index));
sib_min
.entry(key)
.and_modify(|m| *m = (*m).min(flat[c].index))
.or_insert(flat[c].index);
}
}
(0..flat.len())
.filter(|&n| flat[n].node.matches_axis(axis))
.filter(|&n| match comb {
Combinator::Root => true,
Combinator::Child => flat[n].parent.is_some_and(|p| in_current[p]),
Combinator::Descendant => {
let mut cur = flat[n].parent;
while let Some(p) = cur {
if in_current[p] {
return true;
}
cur = flat[p].parent;
}
false
}
Combinator::NextSibling => {
let Some(p) = flat[n].parent else {
return false;
};
flat[n].index > 0
&& sib_exact.contains(&(p, flat[n].step.kind_ord(), flat[n].index - 1))
}
Combinator::FollowingSibling => {
let Some(p) = flat[n].parent else {
return false;
};
sib_min
.get(&(p, flat[n].step.kind_ord()))
.is_some_and(|&m| m < flat[n].index)
}
})
.collect()
}
fn apply_preds(
candidates: Vec<usize>,
step: &Step,
flat: &[Flat<'_>],
limits: &EvalLimits,
depth: usize,
) -> Result<Vec<usize>, SelectorError> {
let mut survivors = candidates;
for pred in &step.preds {
if survivors.is_empty() {
break;
}
match pred {
Pred::Attr(attr) => {
let glob = compile_glob_for(attr)?;
survivors.retain(|&n| attr_matches(&flat[n], attr, glob.as_ref()));
}
Pred::Pseudo(Pseudo::Contains(needle)) => {
survivors.retain(|&n| {
flat[n]
.node
.text()
.is_some_and(|t| visible(&t).contains(needle.as_str()))
});
}
Pred::Pseudo(Pseudo::Matches(pattern)) => {
let g = Glob::compile(pattern, step.offset)?;
survivors.retain(|&n| {
flat[n]
.node
.text()
.is_some_and(|t| g.is_match(&visible(&t)))
});
}
Pred::Pseudo(Pseudo::Empty) => {
survivors.retain(|&n| flat[n].node.text().is_some_and(|t| visible(&t).is_empty()));
}
Pred::Pseudo(Pseudo::Not(inner)) => {
let hits = eval_paths(&inner.paths, flat, limits, depth + 1)?;
let set: HashSet<usize> = hits.into_iter().collect();
survivors.retain(|n| !set.contains(n));
}
Pred::Pseudo(Pseudo::Has(inner)) => {
let hits = eval_paths(&inner.paths, flat, limits, depth + 1)?;
let mut has_desc = vec![false; flat.len()];
for h in hits {
let mut cur = flat[h].parent;
while let Some(p) = cur {
if has_desc[p] {
break; }
has_desc[p] = true;
cur = flat[p].parent;
}
}
survivors.retain(|&n| has_desc[n]);
}
Pred::Pseudo(Pseudo::First | Pseudo::Last | Pseudo::Nth(_) | Pseudo::Range { .. }) => {}
}
}
for pred in &step.preds {
if survivors.is_empty() {
break;
}
let Pred::Pseudo(p) = pred else { continue };
let len = survivors.len();
match p {
Pseudo::First => survivors.truncate(1),
Pseudo::Last => {
let last = survivors[len - 1];
survivors.clear();
survivors.push(last);
}
Pseudo::Nth(n) => {
survivors = match resolve_index(*n, len) {
Some(i) => vec![survivors[i]],
None => Vec::new(),
};
}
Pseudo::Range { from, to } => {
let lo = clamp_index(*from, len);
let hi = clamp_index(*to, len);
survivors = if lo < hi {
survivors[lo..hi].to_vec()
} else {
Vec::new()
};
}
_ => {}
}
}
Ok(survivors)
}
fn resolve_index(n: i64, len: usize) -> Option<usize> {
if len == 0 {
return None;
}
let len_i = len as i64;
let idx = if n < 0 { len_i + n } else { n };
if idx < 0 || idx >= len_i {
return None;
}
Some(idx as usize)
}
fn clamp_index(n: i64, len: usize) -> usize {
let len_i = len as i64;
let idx = if n < 0 { len_i + n } else { n };
idx.clamp(0, len_i) as usize
}
fn compile_glob_for(attr: &AttrPred) -> Result<Option<Glob>, SelectorError> {
match &attr.compare {
Some((CmpOp::Glob, Literal::Str(pattern))) => {
Ok(Some(Glob::compile(pattern, attr.offset)?))
}
_ => Ok(None),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum AttrValue {
Str(String),
Int(i64),
Bool(bool),
}
fn visible(text: &str) -> String {
text.chars().filter(|c| !c.is_control()).collect()
}
fn attr_of(flat: &Flat<'_>, name: &str) -> Option<AttrValue> {
if name == "index" {
return Some(AttrValue::Int(flat.index as i64));
}
match flat.node {
Node::Section(s) => match name {
"paras" => Some(AttrValue::Int(s.paragraphs.len() as i64)),
_ => None,
},
Node::Para(p) => match name {
"text" => Some(AttrValue::Str(visible(&p.text))),
"len" => Some(AttrValue::Int(visible(&p.text).chars().count() as i64)),
"styleId" => Some(AttrValue::Int(i64::from(p.style_id))),
"shapeId" => Some(AttrValue::Int(i64::from(p.para_shape_id))),
"empty" => Some(AttrValue::Bool(visible(&p.text).trim().is_empty())),
"controls" => Some(AttrValue::Int(p.controls.len() as i64)),
_ => None,
},
Node::Run(r) => match name {
"text" => Some(AttrValue::Str(visible(r.text()))),
"len" => Some(AttrValue::Int(visible(r.text()).chars().count() as i64)),
"charShapeId" => Some(AttrValue::Int(i64::from(r.char_shape_id()))),
_ => None,
},
Node::Cell(c) => match name {
"row" => Some(AttrValue::Int(i64::from(c.row))),
"col" => Some(AttrValue::Int(i64::from(c.col))),
"rowSpan" => Some(AttrValue::Int(i64::from(c.row_span))),
"colSpan" => Some(AttrValue::Int(i64::from(c.col_span))),
"header" => Some(AttrValue::Bool(c.is_header)),
"name" => c.field_name.as_ref().map(|n| AttrValue::Str(n.clone())),
"text" => Some(AttrValue::Str(visible(
&c.paragraphs
.iter()
.map(|p| p.text.as_str())
.collect::<Vec<_>>()
.join("\n"),
))),
_ => None,
},
Node::Control(control) => attr_of_control(control, name),
}
}
fn attr_of_control(control: &Control, name: &str) -> Option<AttrValue> {
match name {
"kind" => return Some(AttrValue::Str(control_kind_name(control).to_string())),
"inline" => return Some(AttrValue::Bool(control.is_treat_as_char_object())),
_ => {}
}
match control {
Control::Table(t) => match name {
"rows" => Some(AttrValue::Int(i64::from(t.row_count))),
"cols" => Some(AttrValue::Int(i64::from(t.col_count))),
_ => None,
},
Control::Field(f) => match name {
"name" => {
let raw = f.ctrl_data_name.as_deref().unwrap_or(f.command.as_str());
if raw.is_empty() {
None
} else {
Some(AttrValue::Str(raw.to_string()))
}
}
"type" => Some(AttrValue::Str(field_type_name(f.field_type).to_string())),
_ => None,
},
Control::Bookmark(b) => match name {
"name" if !b.name.is_empty() => Some(AttrValue::Str(b.name.clone())),
_ => None,
},
_ => None,
}
}
fn field_type_name(ty: FieldType) -> &'static str {
match ty {
FieldType::Unknown => "unknown",
FieldType::Date => "date",
FieldType::DocDate => "docDate",
FieldType::Path => "path",
FieldType::Bookmark => "bookmark",
FieldType::MailMerge => "mailMerge",
FieldType::CrossRef => "crossRef",
FieldType::Formula => "formula",
FieldType::ClickHere => "clickHere",
FieldType::Summary => "summary",
FieldType::UserInfo => "userInfo",
FieldType::Hyperlink => "hyperlink",
FieldType::Memo => "memo",
FieldType::PrivateInfoSecurity => "privateInfoSecurity",
FieldType::TableOfContents => "tableOfContents",
}
}
fn attr_matches(flat: &Flat<'_>, pred: &AttrPred, glob: Option<&Glob>) -> bool {
let Some(value) = attr_of(flat, &pred.name) else {
return false;
};
let Some((op, literal)) = &pred.compare else {
return match value {
AttrValue::Bool(b) => b,
_ => true,
};
};
match (&value, literal) {
(AttrValue::Int(a), Literal::Int(b)) => match op {
CmpOp::Eq => a == b,
CmpOp::Ne => a != b,
CmpOp::Gt => a > b,
CmpOp::Lt => a < b,
CmpOp::Ge => a >= b,
CmpOp::Le => a <= b,
_ => false,
},
(AttrValue::Bool(a), Literal::Bool(b)) => match op {
CmpOp::Eq => a == b,
CmpOp::Ne => a != b,
_ => false,
},
(AttrValue::Str(a), Literal::Str(b)) => match op {
CmpOp::Eq => a == b,
CmpOp::Ne => a != b,
CmpOp::Prefix => a.starts_with(b.as_str()),
CmpOp::Suffix => a.ends_with(b.as_str()),
CmpOp::Substr => a.contains(b.as_str()),
CmpOp::Glob => glob.is_some_and(|g| g.is_match(a)),
_ => false,
},
_ => false,
}
}
#[cfg(test)]
#[path = "eval_tests.rs"]
mod tests;