Skip to main content

latexml_core/common/
xml.rs

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
14/// Parse a standalone markup string into its own document — the port of Perl
15/// `LaTeXML::Common::XML::Parser::parseChunk` (`Common/XML/Parser.pm:36-39`:
16/// `parse_string($string)` then `->documentElement`, "expects only a single
17/// node"). Parsing lives here, beside the rest of the `Common::XML` helpers, and
18/// NOT in `Document` — mirroring Perl, where `Document::appendTree` only ever
19/// consumes already-parsed nodes.
20///
21/// Diverges from Perl in its RETURN, deliberately: Perl hands back the
22/// `documentElement` and lets the GC keep its owner alive, which in Rust would
23/// dangle — the nodes borrow the document that owns them. So we return the owning
24/// [`Document`] and let the caller take `get_root_element()`, keeping the owner
25/// alive for exactly as long as the nodes are used.
26///
27/// The markup must be a single well-formed XML root (`parseChunk`'s contract): a
28/// bare fragment of several top-level nodes, or an undeclared HTML entity such as
29/// ` `, is a parse error. The error is returned as a rendered string for the
30/// caller to report; this layer applies no logging policy of its own. See
31/// `ill_formed_markup_hint` for why that string names the likely causes instead
32/// of quoting libxml's own diagnosis.
33///
34/// **Recovery is deliberately OFF.** libxml's default is to salvage malformed
35/// input, which here silently DESTROYS author content rather than reporting it —
36/// measured: `<b>a</b> <i>b</i>` parsed to just `<b>a</b>` (the second element
37/// dropped), `<p>a&nbsp;b</p>` to `ab` (the entity deleted), and `<p>a & b</p>`
38/// to `a  b`. Swallowing a author's markup is the silent-failure mode this
39/// project forbids, so a malformed chunk must fail loudly and insert nothing.
40/// This also matches Perl, whose `XML::LibXML->parse_string` defaults to
41/// `recover => 0`. Network access is refused too: a chunk is untrusted input and
42/// must never make the parser fetch an external DTD.
43pub 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
68/// The first prefix used but not declared under `element` (an element's or an attribute's), with the name that uses
69/// it. libxml2 reports an undeclared prefix only as a namespace error, so a `recover: false` parse still succeeds,
70/// with the node named `ltx:emph` in no namespace; Perl's parser dies (`Namespace prefix ltx on emph is not
71/// defined`, #1034).
72fn 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
97/// What we can honestly say when libxml refuses a chunk.
98///
99/// libxml2 diagnoses a parse failure precisely (`Premature end of data in tag p,
100/// line 1`), but rust-libxml's safe API discards that: `parse_string_with_options`
101/// collapses every failure to `XmlParseError::GotNullPointer`, which renders as
102/// "Got a Null pointer" — a message that tells a binding author nothing about
103/// their markup. Recovering the real text needs `xmlGetLastError`, i.e. raw
104/// libxml2 FFI, and this workspace deliberately keeps ALL such FFI in the
105/// rust-libxml fork (oxide is a pure consumer) — so surfacing it is a fork
106/// change, not something to smuggle in here.
107///
108/// Until then, name the causes rather than the symptom. Hand-written snippets
109/// fail for essentially three reasons, all covered below, so this is strictly
110/// more actionable than the pointer message even though it is not per-chunk.
111fn ill_formed_markup_hint() -> String {
112  String::from(
113    "not well-formed XML — check for an unclosed or mismatched tag, a bare `&` \
114     (write `&amp;`), or an HTML entity such as `&nbsp;` that XML does not define \
115     (write the numeric form, `&#160;`)",
116  )
117}
118
119/// The element we parse a fragment inside of. Never enters the document — only
120/// its children are handed back — so the name just has to not collide.
121const FRAGMENT_WRAPPER: &str = "_lxfragment";
122
123/// Parse a markup chunk that may be a document FRAGMENT — several sibling nodes,
124/// or bare text — and return its owning document together with the top-level
125/// nodes to insert. Returning the two together is deliberate: libxml `Node`s are
126/// handles into the document that owns them, so the caller must keep the
127/// [`Document`] alive for exactly as long as it uses the nodes.
128///
129/// **Intentional divergence from Perl** (OXIDIZED_DESIGN #66). Perl's
130/// `Common::XML::Parser::parseChunk` is explicitly single-node — its own comment
131/// reads *"This expects only a single node, not a document fragment"* — and
132/// LaTeXML ships no fragment parser at all, so a Perl binding has to wrap its own
133/// markup. Yet `Document::appendTree` already has an `XML_DOCUMENT_FRAG_NODE`
134/// branch (ported at `document.rs`): the INSERTION half understands fragments
135/// perfectly well, Perl simply never feeds it one. Accepting them here inserts
136/// more of the author's content correctly and can never emit fewer errors than
137/// Perl, so it is a safe extension rather than a parity break.
138///
139/// Strategy: parse as-is FIRST, so every single-root chunk — including one led by
140/// an XML declaration, which may not be preceded by anything — behaves exactly as
141/// [`parse_chunk`] always did; only if that fails do we retry inside a throwaway
142/// wrapper. Recovery stays OFF in both attempts, so genuinely malformed markup
143/// (`<p>unclosed`, a bare `&`, an undeclared `&nbsp;`) is still rejected rather
144/// than silently salvaged.
145///
146/// Namespaces are the caller's business, as in Perl: nodes that declare none land
147/// in no namespace. Markup destined for `<ltx:rawhtml>` must therefore carry its
148/// own `xmlns` (or an `xhtml:` prefix), exactly as it must in a Perl binding.
149pub fn parse_fragment(markup: &str) -> std::result::Result<ParsedFragment, String> {
150  // 1. Single well-formed root — the plain `parseChunk` case, unchanged.
151  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  // 2. Otherwise treat it as a fragment: parse inside a wrapper and hand back the
157  //    wrapper's children. The wrapper itself is never inserted.
158  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
168/// Is `node` an artifact of HOW a chunk was parsed, rather than part of the
169/// chunk? True for exactly the two things that can sit ABOVE a chunk's top-level
170/// nodes: the throwaway [`parse_fragment`] wrapper, and the parsed document node.
171///
172/// Callers that let someone walk a parsed tree upwards need this. Handing back
173/// the wrapper would leak an internal name into a script-facing API — and worse,
174/// let a script insert `<_lxfragment>` into the page — while the document node
175/// would serialize the whole chunk from a `parent()` call. It also removes an
176/// arbitrary inconsistency: a single-root chunk's top node sits directly under
177/// the document node, a multi-root chunk's under the wrapper, and neither is
178/// something the caller wrote.
179pub 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/// A parsed markup chunk, bundled with the throwaway document that owns it.
188///
189/// The pairing is the safety property, not a convenience: a libxml `Node` is a
190/// raw pointer into its owning document, so a node that outlives its owner is a
191/// dangling FFI pointer — a failure mode this project has already taken SIGSEGVs
192/// from, and one that bypasses `catch_unwind`. `Document` is refcounted and
193/// `Clone`, so holding this handle keeps [`ParsedFragment::nodes`] valid for
194/// exactly as long as the handle lives. That is what makes it safe to hand a
195/// parsed chunk to an untrusted `.rhai` script, which controls its own lifetimes.
196#[derive(Clone)]
197pub struct ParsedFragment {
198  /// Kept solely to own the nodes below; refcounted, so cloning is cheap.
199  doc:   Document,
200  nodes: Vec<Node>,
201}
202
203/// Hand-written because libxml's `Document`/`Node` are opaque FFI handles whose
204/// derived form would print pointers, not markup. Report what a caller actually
205/// wants to see: how many top-level nodes, and their names.
206impl 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  /// The top-level parsed nodes, ready to hand to `Document::append_tree`.
220  pub fn nodes(&self) -> Vec<Node> { self.nodes.clone() }
221  /// How many top-level nodes the chunk parsed to (>1 means it was a fragment).
222  pub fn len(&self) -> usize { self.nodes.len() }
223  pub fn is_empty(&self) -> bool { self.nodes.is_empty() }
224  /// The owning document, for callers that need to keep it alive explicitly.
225  pub fn document(&self) -> &Document { &self.doc }
226}
227
228pub struct XPath {
229  context:  Context,
230  /// Each expression compiled once: a document asks some 60 distinct expressions 15k–32k times, and libxml2's string
231  /// evaluators compile on every call (docs/performance/PERFORMANCE.md P10).
232  compiled: HashMap<Box<str>, Expression>,
233  /// Each expression parsed once as a read-only walk (`None`: outside the walk's grammar), under the same limit.
234  walks:    HashMap<Box<str>, Option<WalkQuery>>,
235}
236
237/// How many compiled expressions an [`XPath`] keeps: an expression built from data (an id, a label) past it is
238/// evaluated from its string, as before.
239const COMPILED_XPATH_LIMIT: usize = 1024;
240
241/// `xpath` compiled, from `compiled` or compiled now; `None` when it does not compile (its string evaluation then
242/// reports it as before — compiling it a second time, so libxml2's stderr line prints twice: PERFORMANCE.md P10) or
243/// `compiled` is full.
244pub 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
257// pub type XPathClosure = Rc<Fn(&mut Gullet, Tokens) -> bool>;
258impl 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  /// `xpath` at `node` answered by a read-only walk ([`WalkQuery`]): `None` when it is outside the walk's grammar
269  /// or `doc` cannot let the walk vouch for XPath's answer, and the caller evaluates it as XPath.
270  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  /// The first node of [`walk`](Self::walk)'s answer (`Some(None)`: none), the walk stopping there.
281  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        // A relative query whose context node has been detached from the tree
323        // reaches here with a NULL node pointer — e.g. a stale `ltx:_Capture_`
324        // cell wrapper left by eqnarray/MathFork row surgery (base_xmath.rs
325        // `equationgroup_join_rows` counting `ltx:Math` per cell). The null is
326        // the known detached-wrapper hazard (a handle captured live, then freed
327        // while still held; see `Node::node_ptr_mut`). Such a node has no
328        // descendants, so the empty result is correct and NOT an error: Perl
329        // never logs it (its wrappers stay live). Recover silently. Keep the
330        // diagnostic for a genuine failure (malformed expression, growth limit)
331        // on a live context node.
332        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        // libxml2 XPath failures (invalid context node, growth limit
345        // hit, malformed expression) used to panic and abort the run.
346        // Treat as "no matches" instead — the conversion can usually
347        // recover and produce most of the document. Drivers:
348        // 2105.04174, 2304.07380, 1904.02716 all aborted here.
349        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        // A null (detached) context node has no descendants: empty, not an
366        // error (see `findnodes`).
367        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
393//======================================================================
394// XML Utilities
395/// gets the following `Element` sibling of `node` (skipping over non-element nodes)
396pub 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}
407/// gets the previous `Element` sibling of `node` (skipping over non-element nodes)
408pub 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}
419/// Walk `node`'s ancestor chain to the top. If the chain ends at a
420/// `Document` (or document-fragment) node the subtree is LIVE — part of a
421/// document tree — and `None` is returned; otherwise the topmost node is a
422/// DETACHED root and is returned. Callers use this to decide whether a
423/// source tree they are done with is theirs to free
424/// (`Document::discard_subtree`) or still reachable from a live document.
425pub 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
443/// obtains all `Element` children of `node`, ignoring all other node types
444pub 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
452/// The elements of `root`'s subtree, `root` included, that `keep` accepts, in document order: the walk behind a
453/// whole-document `descendant-or-self::*[pred]`, which libxml2 2.15 answers through a node set over every element and
454/// refuses past 10,000,000 of them ("XPath evaluation failure", #802).
455pub 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    // Climb to the next element in document order, never past `root`.
467    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
483/// XPath's `ltx:<local>` name test: a LaTeXML-namespace element named `local`. Unlike `get_node_qname`, it rejects a
484/// namespace-less element of that name, as the XPath it replaces does.
485pub 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
491/// `node.get_name() == name`, read without an owned `String` (MEM1 L12).
492pub fn name_is(node: &Node, name: &str) -> bool { node.as_readonly().with_name(|n| n == name) }
493
494/// obtains all content children of `node` (`Element` and `Text`), ignoring all other node types
495pub 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  // Walk UP. The cursor must advance: re-reading `node.get_parent()` every
513  // iteration spun forever on any non-element whose parent is also a
514  // non-element — a text node directly under the document being the reachable
515  // case (`xmlGetParent` of a top-level node is the DocumentNode, and only
516  // the document's own parent is NULL, which is what terminates this loop).
517  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
527/// Is `child` the same as `parent`, or a descendent of `parent`?
528pub 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.is_same_node(parent) {
533    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  /// `closest_element` must TERMINATE when no element ancestor exists.
562  /// The walk used to re-read `node.get_parent()` without advancing a cursor,
563  /// so a non-element whose parent is also a non-element spun forever; a text
564  /// node parented by the DocumentNode is the reachable shape. If this
565  /// regresses the test hangs rather than fails — that is the symptom.
566  #[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    // Mix of element + text siblings:
590    //   root: <a/> "text1" <b/> "text2" <c/>
591    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  /// A relative XPath query whose context node is a detached (null-pointer)
683  /// wrapper — as eqnarray/MathFork row surgery leaves stale `ltx:_Capture_`
684  /// cells (base_xmath.rs `equationgroup_join_rows`; the A&A `aa.cls` cluster,
685  /// witness 2605.02723) — must recover as an empty result WITHOUT logging an
686  /// `Error`: a null node has no descendants, so the empty result is correct
687  /// and Perl never reports it. Without the null-context arm this errors and
688  /// bumps `REPORT.error`.
689  #[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  //! Pins `parse_chunk`'s contract — the limits a binding author inherits from
715  //! Perl `parseChunk`, and the degrade-don't-crash promise `Document::insert_xml`
716  //! relies on.
717  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    // Faithful to Perl `parseChunk` ("expects only a single node"): a bare
731    // fragment of several top-level nodes is NOT well-formed XML. A binding that
732    // wants to insert one must wrap it in a single container element itself.
733    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    // XML predefines only lt/gt/amp/quot/apos. `&nbsp;` &c. are HTML entities and
741    // are undefined without a DTD, so an (X)HTML snippet carrying one fails to
742    // parse. It must surface as a clean Err for the caller to report — never a
743    // panic — which is what lets `insert_xml` degrade the one binding.
744    assert!(parse_chunk("<p>a&nbsp;b</p>").is_err());
745    // The numeric form is fine, and is the portable way to write it.
746    assert!(parse_chunk("<p>a&#160;b</p>").is_ok());
747  }
748}
749
750#[cfg(test)]
751mod parse_fragment_tests {
752  //! `parse_fragment` accepts what `parse_chunk` cannot (OXIDIZED_DESIGN #66)
753  //! WITHOUT loosening the reject-don't-salvage rule that protects author markup.
754  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    // The case Perl's parseChunk rejects, and the one libxml's recovery mode
766    // silently truncated to `<b>a</b>` before recovery was turned off.
767    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    // Fragment support must not become a back door to the recovery behaviour:
783    // each of these silently mangled the author's content under `recover: true`.
784    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&nbsp;b</p>").is_err(),
788      "undeclared entity"
789    );
790  }
791
792  #[test]
793  fn empty_markup_parses_to_no_nodes_rather_than_failing() {
794    // Empty input is not malformed — it simply contains nothing, so parsing
795    // SUCCEEDS with an empty node list. Whether "nothing" is acceptable is the
796    // caller's policy, not the parser's: `Document::insert_xml` treats it as a
797    // clean `Error:` rather than silently inserting nothing.
798    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    // The message a `.rhai` binding author sees is the whole point of failing
806    // loudly. rust-libxml collapses every parse failure to `GotNullPointer`
807    // ("Got a Null pointer"), which names nothing they can act on; each of the
808    // three realistic causes must instead be findable in what we report.
809    for markup in ["<p>unclosed", "<p>a & b</p>", "<p>a&nbsp;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("&amp;") && err.contains("&#160;"),
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}