1use libxml::{
12 readonly::RoNode,
13 tree::{Document, Node, NodeType},
14};
15
16use crate::common::xml::XML_NS;
17
18const LTX_NS: &str = "http://dlmf.nist.gov/LaTeXML";
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23enum Axis {
24 Document,
25 Descendant,
26 DescendantOrSelf,
27}
28
29#[derive(Debug, Clone)]
31enum NameTest {
32 Any,
33 Ltx(String),
34}
35
36#[derive(Debug)]
38enum AttrName {
39 Plain(String),
40 Xml(String),
41}
42
43#[derive(Debug)]
45enum StrPart {
46 Literal(String),
47 Attr(AttrName),
48}
49
50#[derive(Debug)]
52enum Atom {
53 Attr(AttrName),
54 NoAttr(AttrName),
55 NoAncestor(NameTest),
57 NoChild(String),
59 Ancestor(NameTest),
61 Parent(NameTest),
63 Contains(Vec<StrPart>, String),
65}
66
67#[derive(Debug)]
69struct Arm {
70 name: NameTest,
71 preds: Vec<Vec<Atom>>,
72}
73
74#[derive(Debug)]
76pub struct WalkQuery {
77 axis: Axis,
78 arms: Vec<Arm>,
79}
80
81impl WalkQuery {
82 pub fn parse(xpath: &str) -> Option<WalkQuery> {
86 let mut axis = None;
87 let mut arms = Vec::new();
88 for raw in split_top(xpath, "|") {
89 let raw = raw.trim();
90 let (arm_axis, path) = if let Some(rest) = raw.strip_prefix("//") {
91 (Axis::Document, rest)
92 } else if let Some(rest) = raw.strip_prefix(".//") {
93 (Axis::Descendant, rest)
94 } else if let Some(rest) = raw.strip_prefix("descendant::") {
95 (Axis::Descendant, rest)
96 } else {
97 (
98 Axis::DescendantOrSelf,
99 raw.strip_prefix("descendant-or-self::")?,
100 )
101 };
102 if axis.is_some_and(|a| a != arm_axis) {
103 return None;
104 }
105 axis = Some(arm_axis);
106 let steps = split_top(path, "/");
108 let (lead, step) = match steps.as_slice() {
109 [step] => (None, *step),
110 [lead, step] if arm_axis == Axis::Document => (Some((*lead, false)), *step),
111 [lead, "", step] if arm_axis == Axis::Document => (Some((*lead, true)), *step),
112 _ => return None,
113 };
114 let (name, pred) = match step.split_once('[') {
115 Some((name, pred)) => (name, Some(pred.strip_suffix(']')?)),
116 None => (step, None),
117 };
118 let mut preds = match pred {
119 Some(pred) => parse_predicate(pred)?,
120 None => Vec::new(),
121 };
122 if let Some((lead, descendant)) = lead {
123 let lead = parse_name_test(lead)?;
124 let atom = || {
125 if descendant {
126 Atom::Ancestor(lead.clone())
127 } else {
128 Atom::Parent(lead.clone())
129 }
130 };
131 if preds.is_empty() {
132 preds.push(vec![atom()]);
133 } else {
134 for group in &mut preds {
135 group.insert(0, atom());
136 }
137 }
138 }
139 arms.push(Arm {
140 name: parse_name_test(name)?,
141 preds,
142 });
143 }
144 Some(WalkQuery { axis: axis?, arms })
145 }
146
147 pub fn find(&self, doc: &Document, context: Option<&Node>) -> Option<Vec<Node>> {
152 self.find_up_to(doc, context, usize::MAX)
153 }
154
155 pub fn find_first(&self, doc: &Document, context: Option<&Node>) -> Option<Option<Node>> {
157 Some(self.find_up_to(doc, context, 1)?.pop())
158 }
159
160 fn find_up_to(&self, doc: &Document, context: Option<&Node>, limit: usize) -> Option<Vec<Node>> {
161 let root = doc.get_root_readonly()?;
162 let doc_node = root.get_parent()?;
163 let mut top = doc_node.get_first_child();
164 while let Some(child) = top {
165 if child.get_type() == Some(NodeType::DTDNode) {
166 return None;
167 }
168 top = child.get_next_sibling();
169 }
170 let context = match context {
171 Some(node) => {
172 let ro = node.as_readonly();
173 if ro.is_null() {
174 return None;
175 }
176 let mut top = ro;
177 while let Some(parent) = top.get_parent() {
178 top = parent;
179 }
180 if top != doc_node {
181 return None;
182 }
183 ro
184 },
185 None => root,
186 };
187 let mut found = Vec::new();
188 match self.axis {
189 Axis::Document => self.collect(root, true, limit, &mut found),
190 Axis::Descendant => self.collect(context, false, limit, &mut found),
191 Axis::DescendantOrSelf => self.collect(context, true, limit, &mut found),
192 }
193 Some(
194 found
195 .into_iter()
196 .map(|node| doc.node_from_readonly(node))
197 .collect(),
198 )
199 }
200
201 fn collect(&self, start: RoNode, include_self: bool, limit: usize, out: &mut Vec<RoNode>) {
204 if include_self && self.matches(start) {
205 out.push(start);
206 }
207 if out.len() >= limit
208 || !matches!(
209 start.get_type(),
210 Some(NodeType::ElementNode | NodeType::DocumentNode)
211 )
212 {
213 return;
214 }
215 let mut cur = start.get_first_child();
216 while let Some(node) = cur {
217 let is_element = node.get_type() == Some(NodeType::ElementNode);
218 if is_element && self.matches(node) {
219 out.push(node);
220 if out.len() >= limit {
221 return;
222 }
223 }
224 if is_element && let Some(child) = node.get_first_child() {
225 cur = Some(child);
226 continue;
227 }
228 let mut last = node;
230 cur = loop {
231 if let Some(next) = last.get_next_sibling() {
232 break Some(next);
233 }
234 match last.get_parent() {
235 Some(parent) if parent != start => last = parent,
236 _ => break None,
237 }
238 };
239 }
240 }
241
242 fn matches(&self, node: RoNode) -> bool {
243 if node.get_type() != Some(NodeType::ElementNode) {
244 return false;
245 }
246 node.with_name(|name| {
247 let mut in_ltx = None;
248 self.arms.iter().any(|arm| {
249 if let NameTest::Ltx(want) = &arm.name
250 && (name != want || !*in_ltx.get_or_insert_with(|| is_ltx(node)))
251 {
252 return false;
253 }
254 arm.preds.is_empty()
255 || arm
256 .preds
257 .iter()
258 .any(|group| group.iter().all(|atom| atom.holds(node)))
259 })
260 })
261 }
262}
263
264impl Atom {
265 fn holds(&self, node: RoNode) -> bool {
266 match self {
267 Atom::Attr(attr) => attr.present(node),
268 Atom::NoAttr(attr) => !attr.present(node),
269 Atom::NoAncestor(test) => !ancestors(node).any(|a| test.accepts(a)),
270 Atom::NoChild(name) => {
271 let mut child = node.get_first_child();
272 while let Some(c) = child {
273 if c.get_type() == Some(NodeType::ElementNode) && c.with_name(|n| n == name) && is_ltx(c)
274 {
275 return false;
276 }
277 child = c.get_next_sibling();
278 }
279 true
280 },
281 Atom::Ancestor(test) => ancestors(node).any(|a| test.accepts(a)),
282 Atom::Parent(test) => ancestors(node).next().is_some_and(|p| test.accepts(p)),
283 Atom::Contains(parts, needle) => {
284 let mut haystack = String::new();
285 for part in parts {
286 match part {
287 StrPart::Literal(s) => haystack.push_str(s),
288 StrPart::Attr(attr) => haystack.push_str(&attr.value(node).unwrap_or_default()),
289 }
290 }
291 haystack.contains(needle.as_str())
292 },
293 }
294 }
295}
296
297impl AttrName {
298 fn present(&self, node: RoNode) -> bool {
299 match self {
300 AttrName::Plain(name) => node.has_attribute_no_ns(name),
301 AttrName::Xml(name) => node.has_attribute_ns(name, XML_NS),
302 }
303 }
304
305 fn value(&self, node: RoNode) -> Option<String> {
306 match self {
307 AttrName::Plain(name) => node.get_attribute_no_ns(name),
308 AttrName::Xml(name) => node.get_attribute_ns(name, XML_NS),
309 }
310 }
311}
312
313impl NameTest {
314 fn accepts(&self, node: RoNode) -> bool {
316 match self {
317 NameTest::Any => true,
318 NameTest::Ltx(name) => node.with_name(|n| n == name) && is_ltx(node),
319 }
320 }
321}
322
323fn ancestors(node: RoNode) -> impl Iterator<Item = RoNode> {
325 std::iter::successors(node.get_parent(), |p| p.get_parent())
326 .take_while(|p| p.get_type() == Some(NodeType::ElementNode))
327}
328
329fn is_ltx(node: RoNode) -> bool { node.with_namespace_href(|href| href == Some(LTX_NS)) }
330
331fn split_top<'a>(s: &'a str, sep: &str) -> Vec<&'a str> {
333 let bytes = s.as_bytes();
334 let mut parts = Vec::new();
335 let (mut depth, mut quote, mut start, mut i) = (0usize, None, 0, 0);
336 while i < bytes.len() {
337 let b = bytes[i];
338 match quote {
339 Some(q) if b == q => quote = None,
340 Some(_) => {},
341 None => match b {
342 b'\'' | b'"' => quote = Some(b),
343 b'(' | b'[' => depth += 1,
344 b')' | b']' => depth = depth.saturating_sub(1),
345 _ if depth == 0 && s[i..].starts_with(sep) => {
346 parts.push(&s[start..i]);
347 i += sep.len();
348 start = i;
349 continue;
350 },
351 _ => {},
352 },
353 }
354 i += 1;
355 }
356 parts.push(&s[start..]);
357 parts
358}
359
360fn is_ncname(name: &str) -> bool {
361 name
362 .chars()
363 .next()
364 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
365 && name
366 .chars()
367 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
368}
369
370fn parse_name_test(test: &str) -> Option<NameTest> {
371 match test {
372 "*" => Some(NameTest::Any),
373 _ => {
374 let name = test.strip_prefix("ltx:")?;
375 is_ncname(name).then(|| NameTest::Ltx(name.to_string()))
376 },
377 }
378}
379
380fn parse_attr(attr: &str) -> Option<AttrName> {
381 match attr.strip_prefix("xml:") {
382 Some(name) => is_ncname(name).then(|| AttrName::Xml(name.to_string())),
383 None => is_ncname(attr).then(|| AttrName::Plain(attr.to_string())),
384 }
385}
386
387fn parse_literal(lit: &str) -> Option<String> {
389 let quote = lit.chars().next().filter(|q| *q == '\'' || *q == '"')?;
390 let inner = lit[1..].strip_suffix(quote)?;
391 (!inner.contains(quote)).then(|| inner.to_string())
392}
393
394fn parse_predicate(pred: &str) -> Option<Vec<Vec<Atom>>> {
396 split_top(pred, " or ")
397 .into_iter()
398 .map(|disjunct| {
399 split_top(disjunct, " and ")
400 .into_iter()
401 .map(|atom| parse_atom(atom.trim()))
402 .collect()
403 })
404 .collect()
405}
406
407fn parse_atom(atom: &str) -> Option<Atom> {
408 if let Some(attr) = atom.strip_prefix('@') {
409 return parse_attr(attr).map(Atom::Attr);
410 }
411 if let Some(inner) = atom.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) {
412 let inner = inner.trim();
413 return if let Some(attr) = inner.strip_prefix('@') {
414 parse_attr(attr).map(Atom::NoAttr)
415 } else if let Some(name) = inner.strip_prefix("ancestor::ltx:") {
416 is_ncname(name).then(|| Atom::NoAncestor(NameTest::Ltx(name.to_string())))
417 } else if let Some(name) = inner.strip_prefix("ltx:") {
418 is_ncname(name).then(|| Atom::NoChild(name.to_string()))
419 } else {
420 None
421 };
422 }
423 let args = atom.strip_prefix("contains(")?.strip_suffix(')')?;
424 let [haystack, needle] = split_top(args, ",")[..] else {
425 return None;
426 };
427 let haystack = haystack.trim();
428 let parts = match haystack
429 .strip_prefix("concat(")
430 .and_then(|h| h.strip_suffix(')'))
431 {
432 Some(list) => match split_top(list, ",") {
434 parts if parts.len() >= 2 => parts
435 .into_iter()
436 .map(|part| parse_str_part(part.trim()))
437 .collect::<Option<Vec<_>>>()?,
438 _ => return None,
439 },
440 None => vec![parse_str_part(haystack)?],
441 };
442 Some(Atom::Contains(parts, parse_literal(needle.trim())?))
443}
444
445fn parse_str_part(part: &str) -> Option<StrPart> {
446 match part.strip_prefix('@') {
447 Some(attr) => parse_attr(attr).map(StrPart::Attr),
448 None => parse_literal(part).map(StrPart::Literal),
449 }
450}
451
452#[cfg(test)]
453mod tests {
454 use libxml::{parser::Parser, xpath::Context};
455
456 use super::*;
457
458 fn parse(xml: &str) -> Document { Parser::default().parse_string(xml).expect("well-formed") }
459
460 fn label(node: &Node) -> String {
461 format!(
462 "{}#{}",
463 node.get_name(),
464 node
465 .get_attribute_ns("id", XML_NS)
466 .or_else(|| node.get_attribute("id"))
467 .unwrap_or_default()
468 )
469 }
470
471 fn xpath_answer(doc: &Document, xpath: &str, context: Option<&Node>) -> Vec<String> {
473 let ctx = Context::new(doc).expect("ctx");
474 ctx.register_namespace("ltx", LTX_NS).expect("ns");
475 let root = doc.get_root_element().unwrap();
476 ctx
477 .node_evaluate(xpath, context.unwrap_or(&root))
478 .expect("xpath evaluates on a small doc")
479 .get_nodes_as_vec()
480 .iter()
481 .map(label)
482 .collect()
483 }
484
485 const DOC: &str = "<document xmlns='http://dlmf.nist.gov/LaTeXML' xmlns:o='urn:other'>\
486 <ref href='u1'/>\
487 <ref href='u2' idref='i1'/>\
488 <ref labelref='L1'/>\
489 <ref id='r1' href='u3'><text fragid='f1'><text id='t1' fragid='f2'/></text></ref>\
490 <ref id='r2'><ref id='r3' fragid='f3'/></ref>\
491 <graphics/>\
492 <graphics imagesrc='a.png'/>\
493 <Math id='m1'><XMath><Math id='inner'/></XMath></Math>\
494 <index/>\
495 <index><indexlist/></index>\
496 <glossary/>\
497 <p idref='i2' o:idref='ns'/>\
498 <o:p id='foreign' idref='i3'/>\
499 <XMDual _cvis='1'/>\
500 <XMDual _pvis='1'/>\
501 <XMDual _cvis='1' _pvis='1'/>\
502 <XMDual/>\
503 <text class='ltx_cref_conjunction' id='c1'/>\
504 <text class='a ltx_cref_conjunction b' id='c2'/>\
505 <text class='ltx_cref_conjunctions' id='c3'/>\
506 <text class='x or y' id='c4'/>\
507 <text id='c5'/>\
508 <XMTok role='SUPERSCRIPT' xml:id='s1'/>\
509 <XMTok role='SUPERSCRIPT' id='s2'/>\
510 <XMTok role='ADDOP' xml:id='s3'/>\
511 <section id='s1'><para><p><ref idref='deep'/><text>tail</text></p>\
512 <ref xmlns='' id='plain' idref='nons'/><p id='onlyns' o:idref='ns2'/></para>\
513 <Math id='m2'><XMath><XMDual _cvis='1' id='outer'><XMDual _pvis='1' id='nested'/></XMDual>\
514 <XMText><Math id='m3'><XMath><XMTok id='tok' _pvis='1'/></XMath></Math></XMText></XMath></Math>\
515 </section>\
516 <p id='after'>no match follows</p>\
517 </document>";
518
519 #[test]
524 fn walk_agrees_with_xpath_on_every_supported_shape() {
525 let doc = parse(DOC);
526 let root = doc.get_root_element().unwrap();
527 let section = root.get_last_child().unwrap().get_prev_sibling().unwrap();
528 let math = section.get_last_child().unwrap();
529 let doc_node = doc.as_node();
530 let para = section.get_first_child().unwrap();
531 let text_node = para
532 .get_first_child()
533 .and_then(|p| p.get_last_child())
534 .and_then(|t| t.get_first_child())
535 .unwrap();
536 assert!(text_node.is_text_node());
537 let attr_node = section.get_attribute_node("id").unwrap();
538 for xpath in [
539 "//*",
540 "//ltx:document | //ltx:ref",
541 "//ltx:ref | //ltx:document",
542 "//*[@idref]",
543 "//*[@labelref]",
544 "//*[@idref] | //ltx:ref",
545 "//ltx:ref[@href and not(@idref) and not(@labelref)]",
546 "//ltx:graphics[not(@imagesrc)]",
547 "//ltx:Math[not(ancestor::ltx:Math)]",
548 "//ltx:index[not(ltx:indexlist)] | //ltx:glossary[not(ltx:glossarylist)]",
549 "//*[@_cvis or @_pvis]",
550 "//ltx:ref[@href or @idref]",
551 "//*[@idref or @labelref]",
552 "//ltx:ref//*[@fragid]",
553 "//ltx:ref//ltx:ref",
554 "//ltx:XMath/*",
555 "//*/ltx:ref",
556 "//ltx:ref/*[@fragid or @id]",
557 "//ltx:text[contains(concat(' ', @class, ' '), ' ltx_cref_conjunction ')]",
558 "//ltx:text[contains(concat(' ',@class,' '),' or ')]",
559 "//*[@xml:id]",
560 "//*[@xml:id and contains(@role,'SCRIPT')]",
561 "descendant::*[@decl_id or @meaning]",
562 "descendant::ltx:Math",
563 ".//ltx:Math",
564 "descendant-or-self::*[@_pvis or @_cvis]",
565 "descendant-or-self::ltx:document",
566 "descendant::ltx:document",
567 ] {
568 let query = WalkQuery::parse(xpath)
569 .unwrap_or_else(|| panic!("`{xpath}` must be inside the walk grammar"));
570 for context in [
571 None,
572 Some(§ion),
573 Some(&math),
574 Some(&doc_node),
575 Some(&text_node),
576 Some(&attr_node),
577 ] {
578 let walked: Vec<String> = query
579 .find(&doc, context)
580 .expect("no DTD, an attached context")
581 .iter()
582 .map(label)
583 .collect();
584 let expected = xpath_answer(&doc, xpath, context);
585 assert_eq!(
586 walked,
587 expected,
588 "walk disagrees with XPath for `{xpath}` at {:?}",
589 context.map(label)
590 );
591 let first = query.find_first(&doc, context).unwrap();
592 assert_eq!(first.as_ref().map(label), expected.first().cloned());
593 }
594 }
595 }
596
597 #[test]
599 fn unsupported_shapes_are_not_claimed_by_the_walk() {
600 for xpath in [
601 "//ltx:section/ltx:title/ltx:text", "//ltx:section[@id]//ltx:ref", "descendant::ltx:p/ltx:ref", "//ltx:ref[position()=1]", "//ltx:ref[@a][@b]", "//ltx:ref[@a='x']", "ltx:XMath", "//svg:svg", "//*[@svg:href]", "//ltx:Math[not(ancestor::svg:svg)]",
611 "//ltx:ref[(@a or @b) and @c]", "//ltx:text[contains(@class, x)]",
613 "//ltx:text[contains(concat(' ', @class), ' a ', 'b')]",
614 "//ltx:text[contains(concat(@class), 'x')]", "//ltx:ref | descendant::ltx:ref", "//processing-instruction('latexml')",
617 ] {
618 assert!(
619 WalkQuery::parse(xpath).is_none(),
620 "`{xpath}` must fall through to XPath, not be walked"
621 );
622 }
623 let doc = parse(DOC);
625 let ctx = Context::new(&doc).expect("ctx");
626 ctx.register_namespace("ltx", LTX_NS).expect("ns");
627 assert!(
628 ctx
629 .evaluate("//ltx:text[contains(concat(@class), 'x')]")
630 .is_err()
631 );
632 }
633
634 #[test]
637 fn walk_declines_where_xpath_must_answer() {
638 let with_dtd = parse(
639 "<?xml version='1.0'?>\
640 <!DOCTYPE document [<!ENTITY ent '<ref xmlns=\"http://dlmf.nist.gov/LaTeXML\" idref=\"in-ent\"/>'>]>\
641 <document xmlns='http://dlmf.nist.gov/LaTeXML'><p><ref idref='before'/></p><p>&ent;</p></document>",
642 );
643 let query = WalkQuery::parse("//*[@idref]").unwrap();
644 assert!(query.find(&with_dtd, None).is_none());
645 let doc = parse(DOC);
646 let other = parse("<document xmlns='http://dlmf.nist.gov/LaTeXML'><ref idref='x'/></document>");
647 let foreign = other.get_root_element().unwrap();
648 assert!(query.find(&doc, Some(&foreign)).is_none());
649 let relative = WalkQuery::parse("descendant::*[@idref]").unwrap();
650 assert!(relative.find(&doc, Some(&foreign)).is_none());
651 let mut detached = doc.get_root_element().unwrap().get_first_child().unwrap();
652 detached.unlink_node();
653 assert!(relative.find(&doc, Some(&detached)).is_none());
654 assert!(relative.find(&doc, Some(&Node::null())).is_none());
655 }
656
657 #[test]
659 fn walk_answers_from_the_live_tree_after_mutation() {
660 let doc = parse(
661 "<document xmlns='http://dlmf.nist.gov/LaTeXML'><p><ref idref='a'/></p><p/></document>",
662 );
663 let query = WalkQuery::parse("//*[@idref]").unwrap();
664 let idrefs = |doc: &Document| -> Vec<String> {
665 query
666 .find(doc, None)
667 .unwrap()
668 .iter()
669 .filter_map(|n| n.get_attribute("idref"))
670 .collect()
671 };
672 assert_eq!(idrefs(&doc), ["a"]);
673 let root = doc.get_root_element().unwrap();
674 let mut p2 = root.get_last_child().unwrap();
675 let mut added = Node::new("ref", p2.get_namespace(), &doc).unwrap();
676 added.set_attribute("idref", "b").unwrap();
677 p2.add_child(&mut added).unwrap();
678 assert_eq!(idrefs(&doc), ["a", "b"]);
679 let mut first = root.get_first_child().unwrap().get_first_child().unwrap();
680 first.unlink_node();
681 assert_eq!(idrefs(&doc), ["b"]);
682 }
683}