1use std::borrow::Cow;
2
3use libxml::{
4 tree::{Document, Node, NodeType},
5 xpath::{Context, Expression},
6};
7use rustc_hash::FxHashMap as HashMap;
8
9use crate::common::{error::Result, xml_walk::WalkQuery};
10
11pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
12pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
13
14pub fn parse_chunk(markup: &str) -> std::result::Result<Document, String> {
44 let options = libxml::parser::ParserOptions {
45 recover: false,
46 no_net: true,
47 no_def_dtd: true,
48 ..libxml::parser::ParserOptions::default()
49 };
50 let doc = libxml::parser::Parser::default()
51 .parse_string_with_options(markup, options)
52 .map_err(|e| match e {
53 libxml::parser::XmlParseError::DocumentTooLarge => String::from("markup too large to parse"),
54 _ => ill_formed_markup_hint(),
55 })?;
56 match doc
57 .get_root_element()
58 .and_then(|root| undeclared_prefix(root.as_readonly()))
59 {
60 Some((prefix, name)) => Err(format!(
61 "namespace prefix `{prefix}` is not declared (on `{name}`); declare it with \
62 xmlns:{prefix}=\"…\""
63 )),
64 None => Ok(doc),
65 }
66}
67
68fn undeclared_prefix(element: libxml::readonly::RoNode) -> Option<(String, String)> {
73 let unbound = |name: &str| {
74 name
75 .split_once(':')
76 .map(|(p, _)| (p.to_owned(), name.to_owned()))
77 };
78 if element.get_namespace().is_none()
79 && let Some(found) = element.with_name(unbound)
80 {
81 return Some(found);
82 }
83 let mut found = None;
84 element.for_each_property_ns(|name, ns, _| {
85 if found.is_none() && ns.is_none() {
86 found = unbound(name);
87 }
88 });
89 found.or_else(|| {
90 element
91 .get_child_elements()
92 .into_iter()
93 .find_map(undeclared_prefix)
94 })
95}
96
97fn ill_formed_markup_hint() -> String {
112 String::from(
113 "not well-formed XML — check for an unclosed or mismatched tag, a bare `&` \
114 (write `&`), or an HTML entity such as ` ` that XML does not define \
115 (write the numeric form, ` `)",
116 )
117}
118
119const FRAGMENT_WRAPPER: &str = "_lxfragment";
122
123pub fn parse_fragment(markup: &str) -> std::result::Result<ParsedFragment, String> {
150 if let Ok(doc) = parse_chunk(markup)
152 && let Some(root) = doc.get_root_element()
153 {
154 return Ok(ParsedFragment { doc, nodes: vec![root] });
155 }
156 let doc = parse_chunk(&format!(
159 "<{FRAGMENT_WRAPPER}>{markup}</{FRAGMENT_WRAPPER}>"
160 ))?;
161 let root = doc
162 .get_root_element()
163 .ok_or_else(|| String::from("markup parsed to an empty document"))?;
164 let nodes = root.get_child_nodes();
165 Ok(ParsedFragment { doc, nodes })
166}
167
168pub fn is_parse_artifact(node: &Node) -> bool {
180 match node.get_type() {
181 Some(NodeType::DocumentNode) => true,
182 Some(NodeType::ElementNode) => name_is(node, FRAGMENT_WRAPPER),
183 _ => false,
184 }
185}
186
187#[derive(Clone)]
197pub struct ParsedFragment {
198 doc: Document,
200 nodes: Vec<Node>,
201}
202
203impl std::fmt::Debug for ParsedFragment {
207 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208 f.debug_struct("ParsedFragment")
209 .field("nodes", &self.nodes.len())
210 .field(
211 "names",
212 &self.nodes.iter().map(Node::get_name).collect::<Vec<_>>(),
213 )
214 .finish()
215 }
216}
217
218impl ParsedFragment {
219 pub fn nodes(&self) -> Vec<Node> { self.nodes.clone() }
221 pub fn len(&self) -> usize { self.nodes.len() }
223 pub fn is_empty(&self) -> bool { self.nodes.is_empty() }
224 pub fn document(&self) -> &Document { &self.doc }
226}
227
228pub struct XPath {
229 context: Context,
230 compiled: HashMap<Box<str>, Expression>,
233 walks: HashMap<Box<str>, Option<WalkQuery>>,
235}
236
237const COMPILED_XPATH_LIMIT: usize = 1024;
240
241pub fn compiled_xpath<'a>(
245 compiled: &'a mut HashMap<Box<str>, Expression>,
246 xpath: &str,
247) -> Option<&'a Expression> {
248 if !compiled.contains_key(xpath) {
249 if compiled.len() >= COMPILED_XPATH_LIMIT {
250 return None;
251 }
252 compiled.insert(xpath.into(), Expression::compile(xpath).ok()?);
253 }
254 compiled.get(xpath)
255}
256
257impl XPath {
259 pub fn new(doc: &Document, _mappings: HashMap<String, String>) -> Self {
260 let context = Context::new(doc).unwrap();
261 XPath {
262 context,
263 compiled: HashMap::default(),
264 walks: HashMap::default(),
265 }
266 }
267
268 pub fn walk(&mut self, doc: &Document, xpath: &str, node: Option<&Node>) -> Option<Vec<Node>> {
271 if !self.walks.contains_key(xpath) {
272 if self.walks.len() >= COMPILED_XPATH_LIMIT {
273 return WalkQuery::parse(xpath)?.find(doc, node);
274 }
275 self.walks.insert(xpath.into(), WalkQuery::parse(xpath));
276 }
277 self.walks.get(xpath)?.as_ref()?.find(doc, node)
278 }
279
280 pub fn walk_first(
282 &mut self,
283 doc: &Document,
284 xpath: &str,
285 node: Option<&Node>,
286 ) -> Option<Option<Node>> {
287 if !self.walks.contains_key(xpath) {
288 if self.walks.len() >= COMPILED_XPATH_LIMIT {
289 return WalkQuery::parse(xpath)?.find_first(doc, node);
290 }
291 self.walks.insert(xpath.into(), WalkQuery::parse(xpath));
292 }
293 self.walks.get(xpath)?.as_ref()?.find_first(doc, node)
294 }
295
296 pub fn register_namespace(&mut self, codeprefix: &str, namespace: &str) -> Result<()> {
297 match self.context.register_namespace(codeprefix, namespace) {
298 Ok(()) => {},
299 Err(_) => {
300 let message = s!(
301 "Failed to register an XPath namespace: prefix {:?} and href {:?}",
302 codeprefix,
303 namespace
304 );
305 Error!("expected", "XPath", message);
306 },
307 };
308 Ok(())
309 }
310
311 pub fn findnodes(&mut self, xpath: &str, node: Option<&Node>) -> Vec<Node> {
312 let found = match compiled_xpath(&mut self.compiled, xpath) {
313 Some(expression) => self
314 .context
315 .findnodes_compiled(expression, node)
316 .map_err(|_| ()),
317 None => self.context.findnodes(xpath, node),
318 };
319 match found {
320 Ok(nodes) => nodes,
321 Err(e) => {
322 if node.is_some_and(|n| n.is_null()) {
333 return Vec::new();
334 }
335 let message = s!(
336 "XPath {xpath:?} failed (context node: {}): {e:?}",
337 node.is_some()
338 );
339 let err = || {
340 Error!("xpath", "findnodes", message);
341 Ok(())
342 };
343 err().ok();
344 Vec::new()
350 },
351 }
352 }
353
354 pub fn findvalues(&mut self, xpath: &str, node: Option<&Node>) -> Vec<String> {
355 let found = match compiled_xpath(&mut self.compiled, xpath) {
356 Some(expression) => self
357 .context
358 .findvalues_compiled(expression, node)
359 .map_err(|_| ()),
360 None => self.context.findvalues(xpath, node),
361 };
362 match found {
363 Ok(vals) => vals,
364 Err(e) => {
365 if node.is_some_and(|n| n.is_null()) {
368 return Vec::new();
369 }
370 let message = s!(
371 "XPath {xpath:?} failed (context node: {}): {e:?}",
372 node.is_some()
373 );
374 let err = || {
375 Error!("xpath", "findvalues", message);
376 Ok(())
377 };
378 err().ok();
379 Vec::new()
380 },
381 }
382 }
383
384 pub fn findvalue(&mut self, xpath: &str, node: Option<&Node>) -> String {
385 match compiled_xpath(&mut self.compiled, xpath) {
386 Some(expression) => self.context.findvalue_compiled(expression, node).ok(),
387 None => self.context.findvalue(xpath, node).ok(),
388 }
389 .unwrap_or_default()
390 }
391}
392
393pub fn get_next_element(node_in: &Node) -> Option<Node> {
397 let mut node = Cow::Borrowed(node_in);
398 while let Some(next) = node.get_next_sibling() {
399 if next.get_type() == Some(NodeType::ElementNode) {
400 return Some(next);
401 } else {
402 node = Cow::Owned(next);
403 }
404 }
405 None
406}
407pub fn get_prev_element(node_in: &Node) -> Option<Node> {
409 let mut node = Cow::Borrowed(node_in);
410 while let Some(next) = node.get_prev_sibling() {
411 if next.get_type() == Some(NodeType::ElementNode) {
412 return Some(next);
413 } else {
414 node = Cow::Owned(next);
415 }
416 }
417 None
418}
419pub fn detached_root(node: &Node) -> Option<Node> {
426 let mut cur = node.clone();
427 loop {
428 match cur.get_parent() {
429 None => return Some(cur),
430 Some(p)
431 if matches!(
432 p.get_type(),
433 Some(NodeType::DocumentNode) | Some(NodeType::DocumentFragNode)
434 ) =>
435 {
436 return None;
437 },
438 Some(p) => cur = p,
439 }
440 }
441}
442
443pub fn element_nodes(node: &Node) -> Vec<Node> {
445 node
446 .get_child_nodes()
447 .into_iter()
448 .filter(|n| matches!(n.get_type(), Some(NodeType::ElementNode)))
449 .collect()
450}
451
452pub fn descendant_or_self_elements(root: &Node, mut keep: impl FnMut(&Node) -> bool) -> Vec<Node> {
456 let mut found = Vec::new();
457 let mut node = root.clone();
458 loop {
459 if keep(&node) {
460 found.push(node.clone());
461 }
462 if let Some(child) = node.get_first_element_child() {
463 node = child;
464 continue;
465 }
466 loop {
468 if node == *root {
469 return found;
470 }
471 if let Some(next) = node.get_next_element_sibling() {
472 node = next;
473 break;
474 }
475 match node.get_parent() {
476 Some(parent) => node = parent,
477 None => return found,
478 }
479 }
480 }
481}
482
483pub fn is_ltx_element(node: &Node, local: &str) -> bool {
486 let node = node.as_readonly();
487 node.with_name(|name| name == local)
488 && node.with_namespace_href(|href| href == Some(crate::common::model::LTX_NAMESPACE))
489}
490
491pub fn name_is(node: &Node, name: &str) -> bool { node.as_readonly().with_name(|n| n == name) }
493
494pub fn content_nodes(node: &Node) -> Vec<Node> {
496 node
497 .get_child_nodes()
498 .into_iter()
499 .filter(|n| {
500 matches!(
501 n.get_type(),
502 Some(NodeType::ElementNode) | Some(NodeType::TextNode)
503 )
504 })
505 .collect()
506}
507
508pub fn closest_element(node: &Node) -> Option<Node> {
509 if node.get_type() == Some(NodeType::ElementNode) {
510 return Some(node.clone());
511 }
512 let mut current = node.clone();
518 while let Some(parent) = current.get_parent() {
519 if parent.get_type() == Some(NodeType::ElementNode) {
520 return Some(parent);
521 }
522 current = parent;
523 }
524 None
525}
526
527pub fn is_descendant_or_self(child: &Node, parent: &Node) -> bool {
529 let mut p = Some(child);
530 let mut parent_opt;
531 while let Some(p_node) = p {
532 if p_node == parent {
534 return true;
535 }
536 match p_node.get_parent() {
537 Some(parent_node) => {
538 parent_opt = Some(parent_node);
539 p = parent_opt.as_ref();
540 },
541 _ => {
542 break;
543 },
544 }
545 }
546 false
547}
548
549#[cfg(test)]
550mod tests {
551 use libxml::tree::Document;
552
553 use super::*;
554
555 #[test]
556 fn namespace_constants() {
557 assert_eq!(XML_NS, "http://www.w3.org/XML/1998/namespace");
558 assert_eq!(XMLNS_NS, "http://www.w3.org/2000/xmlns/");
559 }
560
561 #[test]
567 fn closest_element_terminates_without_an_element_ancestor() {
568 let doc = Document::new().unwrap();
569 let mut doc_node = doc.as_node();
570 let mut stray = Node::new_text("stray", &doc).unwrap();
571 doc_node.add_child(&mut stray).unwrap();
572
573 assert_eq!(stray.get_type(), Some(NodeType::TextNode));
574 assert_ne!(
575 doc_node.get_type(),
576 Some(NodeType::ElementNode),
577 "the parent must be a non-element for this to exercise the walk"
578 );
579 assert!(
580 closest_element(&stray).is_none(),
581 "no element ancestor exists, so the walk must end at the document"
582 );
583 }
584
585 fn build_tree() -> (Document, Node) {
586 let mut doc = Document::new().unwrap();
587 let mut root = Node::new("root", None, &doc).unwrap();
588 doc.set_root_element(&root);
589 let mut a = Node::new("a", None, &doc).unwrap();
592 let mut t1 = Node::new_text("text1", &doc).unwrap();
593 let mut b = Node::new("b", None, &doc).unwrap();
594 let mut t2 = Node::new_text("text2", &doc).unwrap();
595 let mut c = Node::new("c", None, &doc).unwrap();
596 root.add_child(&mut a).unwrap();
597 root.add_child(&mut t1).unwrap();
598 root.add_child(&mut b).unwrap();
599 root.add_child(&mut t2).unwrap();
600 root.add_child(&mut c).unwrap();
601 (doc, root)
602 }
603
604 #[test]
605 fn element_nodes_skips_text() {
606 let (_doc, root) = build_tree();
607 let children = element_nodes(&root);
608 assert_eq!(children.len(), 3);
609 assert_eq!(children[0].get_name(), "a");
610 assert_eq!(children[1].get_name(), "b");
611 assert_eq!(children[2].get_name(), "c");
612 }
613
614 #[test]
615 fn content_nodes_includes_text() {
616 let (_doc, root) = build_tree();
617 let children = content_nodes(&root);
618 assert_eq!(children.len(), 5, "3 elements + 2 text nodes");
619 }
620
621 #[test]
622 fn get_next_element_skips_text() {
623 let (_doc, root) = build_tree();
624 let a = element_nodes(&root)[0].clone();
625 let next = get_next_element(&a).expect("a has a next element");
626 assert_eq!(
627 next.get_name(),
628 "b",
629 "<a> next element must be <b>, skipping the text node"
630 );
631 }
632
633 #[test]
634 fn get_next_element_none_at_end() {
635 let (_doc, root) = build_tree();
636 let c = element_nodes(&root)[2].clone();
637 assert!(get_next_element(&c).is_none(), "last element has no next");
638 }
639
640 #[test]
641 fn get_prev_element_skips_text() {
642 let (_doc, root) = build_tree();
643 let b = element_nodes(&root)[1].clone();
644 let prev = get_prev_element(&b).expect("b has a prev element");
645 assert_eq!(
646 prev.get_name(),
647 "a",
648 "<b> prev element must be <a>, skipping text"
649 );
650 }
651
652 #[test]
653 fn get_prev_element_none_at_start() {
654 let (_doc, root) = build_tree();
655 let a = element_nodes(&root)[0].clone();
656 assert!(get_prev_element(&a).is_none(), "first element has no prev");
657 }
658
659 #[test]
660 fn is_descendant_or_self_true_for_self() {
661 let (_doc, root) = build_tree();
662 assert!(is_descendant_or_self(&root, &root));
663 }
664
665 #[test]
666 fn is_descendant_or_self_true_for_child() {
667 let (_doc, root) = build_tree();
668 let a = element_nodes(&root)[0].clone();
669 assert!(is_descendant_or_self(&a, &root));
670 }
671
672 #[test]
673 fn is_descendant_or_self_false_for_sibling() {
674 let (_doc, root) = build_tree();
675 let kids = element_nodes(&root);
676 assert!(
677 !is_descendant_or_self(&kids[0], &kids[1]),
678 "a is not a descendant of b"
679 );
680 }
681
682 #[test]
690 fn findnodes_on_a_null_context_node_recovers_without_an_error() {
691 use crate::common::error::snapshot_report_counts;
692 let doc = Document::new().unwrap();
693 let mut xpath = XPath::new(&doc, HashMap::default());
694 let null_node = Node::null();
695 assert!(
696 null_node.is_null(),
697 "precondition: the context node is null"
698 );
699
700 let before = snapshot_report_counts().error;
701 let found = xpath.findnodes("ltx:Math", Some(&null_node));
702 let after = snapshot_report_counts().error;
703
704 assert!(found.is_empty(), "a null-context query yields no nodes");
705 assert_eq!(
706 after, before,
707 "the null context node must be recovered silently, not logged as an Error"
708 );
709 }
710}
711
712#[cfg(test)]
713mod parse_chunk_tests {
714 use super::*;
718
719 #[test]
720 fn a_single_well_formed_root_parses() {
721 let doc = parse_chunk(r#"<p xmlns="http://www.w3.org/1999/xhtml">hi <b>bold</b></p>"#)
722 .expect("single-root xhtml should parse");
723 let root = doc.get_root_element().expect("parsed chunk has a root");
724 assert_eq!(root.get_name(), "p");
725 assert_eq!(root.get_attribute("class"), None);
726 }
727
728 #[test]
729 fn a_multi_root_fragment_is_rejected() {
730 assert!(parse_chunk("<b>a</b> <i>b</i>").is_err());
734 assert!(parse_chunk("bare text").is_err());
735 assert!(parse_chunk("").is_err());
736 }
737
738 #[test]
739 fn an_undefined_html_entity_is_rejected_not_crashed() {
740 assert!(parse_chunk("<p>a b</p>").is_err());
745 assert!(parse_chunk("<p>a b</p>").is_ok());
747 }
748}
749
750#[cfg(test)]
751mod parse_fragment_tests {
752 use super::*;
755
756 #[test]
757 fn a_single_root_still_yields_exactly_one_node() {
758 let f = parse_fragment(r#"<p xmlns="http://www.w3.org/1999/xhtml">hi</p>"#).unwrap();
759 assert_eq!(f.len(), 1);
760 assert_eq!(f.nodes()[0].get_name(), "p");
761 }
762
763 #[test]
764 fn sibling_roots_are_kept_whole() {
765 let f = parse_fragment("<b>a</b><i>b</i>").unwrap();
768 assert_eq!(f.len(), 2, "both siblings must survive");
769 assert_eq!(f.nodes()[0].get_name(), "b");
770 assert_eq!(f.nodes()[1].get_name(), "i");
771 }
772
773 #[test]
774 fn bare_text_is_a_legitimate_fragment() {
775 let f = parse_fragment("just text").unwrap();
776 assert_eq!(f.len(), 1);
777 assert_eq!(f.nodes()[0].get_content(), "just text");
778 }
779
780 #[test]
781 fn malformed_markup_is_still_rejected_not_salvaged() {
782 assert!(parse_fragment("<p>unclosed").is_err(), "unclosed element");
785 assert!(parse_fragment("<p>a & b</p>").is_err(), "bare ampersand");
786 assert!(
787 parse_fragment("<p>a b</p>").is_err(),
788 "undeclared entity"
789 );
790 }
791
792 #[test]
793 fn empty_markup_parses_to_no_nodes_rather_than_failing() {
794 let f = parse_fragment("").expect("empty markup is not a parse failure");
799 assert!(f.is_empty());
800 assert_eq!(f.len(), 0);
801 }
802
803 #[test]
804 fn a_rejection_says_what_to_look_for_not_got_a_null_pointer() {
805 for markup in ["<p>unclosed", "<p>a & b</p>", "<p>a b</p>"] {
810 let err = parse_fragment(markup).expect_err("markup should be rejected");
811 assert!(
812 !err.to_lowercase().contains("null pointer"),
813 "leaked the useless libxml error for {markup:?}: {err}"
814 );
815 assert!(
816 err.contains("unclosed") && err.contains("&") && err.contains(" "),
817 "rejection must point at the likely causes for {markup:?}: {err}"
818 );
819 }
820 }
821
822 #[test]
823 fn the_wrapper_never_enters_the_result() {
824 let f = parse_fragment("<b>a</b><i>b</i>").unwrap();
825 assert!(
826 !f.nodes().iter().any(|n| name_is(n, FRAGMENT_WRAPPER)),
827 "the throwaway wrapper must not be handed back"
828 );
829 }
830}