Skip to main content

latexml_core/
rewrite.rs

1use std::{collections::VecDeque, fmt, rc::Rc};
2
3use libxml::tree::Node;
4use rustc_hash::FxHashMap as HashMap;
5
6use crate::{
7  common::{arena, error::*},
8  document::{Document, get_node_qname},
9  state::Scope,
10  tokens::Tokens,
11};
12
13pub mod declare;
14
15/// Perl `getLabelID`'s error for a scope label no element carries (Rewrite.pm:49-55), reported once
16/// per conversion (OXIDIZED_DESIGN #357): the flag is conversion state, which a streaming
17/// conversion's fragments share.
18fn report_missing_rewrite_label(label: &str) -> Result<()> {
19  let flag = format!("rewrite_missing_label:{label}");
20  if crate::state::lookup_value(&flag).is_none() {
21    crate::state::assign_value(&flag, true, Some(Scope::Global));
22    Error!(
23      "misdefined",
24      "<rewrite>",
25      format!("No id for label {label} in Rewrite")
26    );
27  }
28  Ok(())
29}
30
31/// Perl's error for a scope pattern that is neither `label:` nor `id:` (Rewrite.pm:308-311), once
32/// per conversion (OXIDIZED_DESIGN #357), as `report_missing_rewrite_label`.
33fn report_unrecognized_rewrite_scope(scope: &str) -> Result<()> {
34  let flag = format!("rewrite_unrecognized_scope:{scope}");
35  if crate::state::lookup_value(&flag).is_none() {
36    crate::state::assign_value(&flag, true, Some(Scope::Global));
37    Error!(
38      "misdefined",
39      "<rewrite>",
40      format!("Unrecognized scope pattern in Rewrite clause: \"{scope}\"; Ignoring it.")
41    );
42  }
43  Ok(())
44}
45
46/// Is `node` `root` or one of its descendants.
47fn node_within(node: &Node, root: &Node) -> bool {
48  let mut current = Some(node.clone());
49  while let Some(ancestor) = current {
50    if ancestor == *root {
51      return true;
52    }
53    current = ancestor.get_parent();
54  }
55  false
56}
57
58/// Is `node` in `document`'s tree: its root is the document's root element (an id store entry
59/// can outlive a node an earlier pass unlinked).
60fn node_in_document(document: &Document, node: &Node) -> bool {
61  let Some(root) = document.get_document().get_root_element() else {
62    return false;
63  };
64  let mut current = Some(node.clone());
65  while let Some(ancestor) = current {
66    if ancestor == root {
67      return true;
68    }
69    current = ancestor.get_parent();
70  }
71  false
72}
73
74pub type RewriteReplaceClosure = Rc<dyn Fn(&mut Document, Vec<&mut Node>) -> Result<()>>;
75/// Test closure: Perl signature is ($document, $node) → $nnodes (0/undef = skip).
76pub type RewriteTestClosure = Rc<dyn Fn(&mut Document, &Node) -> Result<usize>>;
77/// Regexp closure: Perl signature is (\$string) → modified in-place via s///g.
78pub type RewriteRegexpClosure = Rc<dyn Fn(&str) -> Option<String>>;
79
80/// A single sub-pattern in a MultiSelect clause.
81/// Perl: `[$xpath, $nnodes, @wilds]`
82#[derive(Debug, Clone)]
83pub struct MultiSelectEntry {
84  pub xpath:  String,
85  pub nnodes: usize,
86  pub wilds:  Vec<WildPath>,
87}
88
89// ======================================================================
90// Defining Rewrite rules that act on the DOM
91// These are applied after the document is completely constructed
92#[derive(Clone, Default)]
93pub struct RewriteOptions {
94  pub label:          Option<String>,
95  pub scope:          Option<Scope>,
96  pub xpath:          Option<String>,
97  pub on_match:       Option<Tokens>,
98  pub attributes:     Option<String>,
99  pub attributes_map: Option<HashMap<String, String>>,
100  pub replace:        Option<RewriteReplaceClosure>,
101  pub regexp:         Option<String>,
102  pub select:         Option<String>,
103  pub select_count:   Option<usize>,
104  pub is_math:        bool,
105  pub wildcard_paths: Option<Vec<WildPath>>,
106  /// Declare-side structural filter for \lxDeclare rules — the compiled
107  /// [`declare::DeclarePattern`] whose broad XPath needs Rust-side
108  /// verification (`declare::declare_node_matches`) on every Select match.
109  /// Set by BOTH attribute and replace registrations.
110  pub declare_filter: Option<declare::DeclarePattern>,
111  /// Rust-only: run the rule up to this many times, each later pass on the nodes the previous one inserted.
112  /// For a rule whose select can match only what its replacement inserts (`base_xmath`'s thousands separator).
113  pub passes:         Option<usize>,
114  /// Rust-only opt-in for built-in rules whose `replace` closure is strictly DOM-local
115  /// (never calls `findnodes`, `\label`, or inspects/moves unrelated siblings): splices
116  /// replacements in O(inserted) instead of detaching/re-appending all following siblings.
117  pub local_replace:  bool,
118}
119impl fmt::Debug for RewriteOptions {
120  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<RewriteOptions>") }
121}
122impl PartialEq for RewriteOptions {
123  fn eq(&self, other: &RewriteOptions) -> bool { self.select == other.select }
124}
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub enum RewriteOperator {
127  // only uncompiled:
128  Label,
129  Scope,
130  Xpath,
131  Match,
132  // with available actions:
133  Regexp,
134  Attributes,
135  Action,
136  Replace,
137  Test,
138  MultiSelect,
139  Select,
140  Ignore,
141  Trace,
142}
143#[derive(Clone)]
144pub enum RewritePattern {
145  String(String),
146  Scope(Scope),
147  Tokens(Tokens),
148  Closure(RewriteReplaceClosure),
149  /// Test closure: returns number of matched nodes (0 = skip remaining clauses).
150  TestClosure(RewriteTestClosure),
151  /// Compiled regexp substitution: returns Some(modified) or None (no match).
152  RegexpClosure(RewriteRegexpClosure),
153  /// Multiple xpath+count+wilds tuples for MultiSelect.
154  MultiSelectPatterns(Vec<MultiSelectEntry>),
155  /// Pre-resolved node list (for scope resolution via DOM walking instead of XPath).
156  NodeList(Vec<Node>),
157}
158impl fmt::Debug for RewritePattern {
159  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
160    match self {
161      RewritePattern::String(x) => write!(f, "{x:?}"),
162      RewritePattern::Scope(x) => write!(f, "{x:?}"),
163      RewritePattern::Tokens(x) => write!(f, "{x:?}"),
164      RewritePattern::Closure(_) => write!(f, "<Rewrite Replacement Closure>"),
165      RewritePattern::TestClosure(_) => write!(f, "<Rewrite Test Closure>"),
166      RewritePattern::RegexpClosure(_) => write!(f, "<Rewrite Regexp Closure>"),
167      RewritePattern::MultiSelectPatterns(v) => write!(f, "<MultiSelect {} patterns>", v.len()),
168      RewritePattern::NodeList(v) => write!(f, "<NodeList {} nodes>", v.len()),
169    }
170  }
171}
172#[derive(Debug, Clone)]
173pub struct RewriteClause {
174  compiled:    bool,
175  pub op:      RewriteOperator,
176  pub pattern: RewritePattern,
177}
178impl RewriteClause {
179  pub fn new_uncompiled(op: RewriteOperator, pattern: RewritePattern) -> Self {
180    RewriteClause { compiled: false, op, pattern }
181  }
182
183  pub fn new_compiled(op: RewriteOperator, pattern: RewritePattern) -> Self {
184    RewriteClause { compiled: true, op, pattern }
185  }
186}
187
188#[derive(Debug, Clone, Default)]
189pub struct Rewrite {
190  pub options: RewriteOptions,
191  pub clauses: Vec<RewriteClause>,
192  /// The nodes the current pass of a multi-pass rule inserted (`RewriteOptions::passes`).
193  inserted:    std::cell::RefCell<Option<Vec<Node>>>,
194}
195impl PartialEq for Rewrite {
196  fn eq(&self, other: &Rewrite) -> bool { self.options == other.options }
197}
198
199impl Rewrite {
200  pub fn new(_kind: &str, mut options: RewriteOptions) -> Self {
201    use RewriteOperator::*;
202    let mut clauses = Vec::new();
203    // collect the non-compiling, early phase clauses from the options
204    if let Some(xpath) = options.select.take() {
205      clauses.push(RewriteClause {
206        compiled: true,
207        op:       Select,
208        pattern:  RewritePattern::String(xpath),
209      })
210    }
211    // collect the actionable clauses from the options
212    if let Some(label) = options.label.take() {
213      clauses.push(RewriteClause {
214        compiled: false,
215        op:       Label,
216        pattern:  RewritePattern::String(label),
217      });
218    }
219    // A named scope is a Perl scope pattern ("label:sec:restricted", "id:S1", or one Perl does
220    // not recognize); the assignment scopes (`Global`, `Local`, `InPlace`) never are, and select
221    // nothing to scope by.
222    if let Some(crate::state::Scope::Named(s)) = options.scope.take() {
223      clauses.push(RewriteClause {
224        compiled: false,
225        op:       Scope,
226        pattern:  RewritePattern::String(arena::with(s, |r| r.to_string())),
227      });
228    }
229    if let Some(xpath) = options.xpath.take() {
230      clauses.push(RewriteClause {
231        compiled: false,
232        op:       Xpath,
233        pattern:  RewritePattern::String(xpath),
234      });
235    }
236    if let Some(tokens) = options.on_match.take() {
237      clauses.push(RewriteClause {
238        compiled: false,
239        op:       Match,
240        pattern:  RewritePattern::Tokens(tokens),
241      });
242    }
243    if let Some(replace) = options.replace.take() {
244      clauses.push(RewriteClause {
245        compiled: false,
246        op:       Replace,
247        pattern:  RewritePattern::Closure(replace),
248      });
249    }
250    if let Some(r) = options.regexp.take() {
251      clauses.push(RewriteClause {
252        compiled: false,
253        op:       Regexp,
254        pattern:  RewritePattern::String(r),
255      });
256    }
257    // If attributes string is set but attributes_map is not, parse string into map.
258    // Perl format: "role='ID'" or "role='ID', meaning='foo'"
259    if options.attributes_map.is_none()
260      && let Some(ref attrs_str) = options.attributes
261    {
262      let mut map = HashMap::default();
263      for part in attrs_str.split(',') {
264        let part = part.trim();
265        if let Some((key, val)) = part.split_once('=') {
266          let val = val.trim().trim_matches('\'').trim_matches('"');
267          map.insert(key.trim().to_string(), val.to_string());
268        }
269      }
270      if !map.is_empty() {
271        options.attributes_map = Some(map);
272      }
273    }
274    if options.attributes_map.is_some() {
275      clauses.push(RewriteClause {
276        compiled: true,
277        op:       Attributes,
278        pattern:  RewritePattern::String(String::new()), // attributes stored in options
279      });
280    }
281    Rewrite {
282      options,
283      clauses,
284      inserted: Default::default(),
285    }
286  }
287
288  /// A rule from already-built clauses (`\lxDeclare`'s registration).
289  pub fn from_clauses(options: RewriteOptions, clauses: Vec<RewriteClause>) -> Self {
290    Rewrite {
291      options,
292      clauses,
293      inserted: Default::default(),
294    }
295  }
296
297  pub fn compile_clauses(&mut self, document: &mut Document) {
298    let current_clauses: Vec<RewriteClause> = std::mem::take(&mut self.clauses);
299    let mut new_clauses: Vec<RewriteClause> = Vec::new();
300    for clause in current_clauses {
301      if !clause.compiled {
302        new_clauses.push(self.compile_clause(document, clause));
303      } else {
304        new_clauses.push(clause);
305      }
306    }
307    self.clauses = new_clauses;
308  }
309
310  pub fn compile_clause(
311    &mut self,
312    document: &mut Document,
313    clause: RewriteClause,
314  ) -> RewriteClause {
315    let op = clause.op;
316    let pattern = clause.pattern;
317
318    if op == RewriteOperator::Xpath {
319      if self.options.select_count.is_none() {
320        self.options.select_count = Some(1);
321      }
322      return RewriteClause {
323        compiled: true,
324        op: RewriteOperator::Select,
325        pattern,
326      };
327    }
328    // Perl Rewrite.pm L288-297: a `label` clause COMPILES to a select on the
329    // labeled node's xml:id (via getLabelID) — it has no runtime behavior.
330    // `scope => "label:<label>"` compiles through the identical getLabelID
331    // path (L300-302), so delegate to that branch below. (The former runtime
332    // Label arm instead tried to RECORD the current node's id under the
333    // label — not Perl semantics, and dead anyway: its bare
334    // get_attribute("xml:id") read always returned None.)
335    if op == RewriteOperator::Label
336      && let RewritePattern::String(label_str) = &pattern
337    {
338      let as_scope = RewriteClause {
339        compiled: false,
340        op:       RewriteOperator::Scope,
341        pattern:  RewritePattern::String(format!("label:{label_str}")),
342      };
343      return self.compile_clause(document, as_scope);
344    }
345    // scope => 'label:...' compiles to select with xpath via label ID resolution
346    // Perl: $op = 'select'; $pattern = ["descendant-or-self::*[@xml:id='<id>']", 1];
347    if op == RewriteOperator::Scope
348      && let RewritePattern::String(scope_str) = &pattern
349    {
350      // Streaming pass 2: a scope resolving to a fragment ANCESTOR covers
351      // the whole fragment — the scope node itself lives in another
352      // fragment, so the id-xpath below would select nothing (witness
353      // tests/math/simplemath.tex, `label:sec:restricted`).
354      let whole_fragment_scope = |document: &Document| RewriteClause {
355        compiled: true,
356        op:       RewriteOperator::Select,
357        pattern:  RewritePattern::NodeList(
358          document
359            .get_document()
360            .get_root_element()
361            .into_iter()
362            .collect(),
363        ),
364      };
365      if let Some(label_part) = scope_str.strip_prefix("label:") {
366        if let Some(id) = document.lookup_rewrite_label(label_part) {
367          if self.options.select_count.is_none() {
368            self.options.select_count = Some(1);
369          }
370          if document.fragment_ancestor_ids.contains(&id) {
371            return whole_fragment_scope(document);
372          }
373          let xpath = format!("descendant-or-self::*[@xml:id='{}']", id);
374          return RewriteClause {
375            compiled: true,
376            op:       RewriteOperator::Select,
377            pattern:  RewritePattern::String(xpath),
378          };
379        }
380        // Try with LABEL: prefix (clean_label adds it)
381        let clean_key = format!("LABEL:{}", label_part);
382        if let Some(id) = document.lookup_rewrite_label(&clean_key) {
383          if self.options.select_count.is_none() {
384            self.options.select_count = Some(1);
385          }
386          if document.fragment_ancestor_ids.contains(&id) {
387            return whole_fragment_scope(document);
388          }
389          let xpath = format!("descendant-or-self::*[@xml:id='{}']", id);
390          return RewriteClause {
391            compiled: true,
392            op:       RewriteOperator::Select,
393            pattern:  RewritePattern::String(xpath),
394          };
395        }
396        // Label not found. Perl's `getLabelID` errors and returns undef, and the
397        // scope compiles to `descendant-or-self::*[@xml:id='']`, which selects
398        // nothing (Rewrite.pm:49-55, :300-302): the rule applies nowhere. The
399        // error is reported once per conversion (a streaming conversion compiles
400        // its rules once per fragment; the shared labels resolve across them).
401        // (A too-many-errors Fatal is logged and latched where `Error!` raises it.)
402        let _ = report_missing_rewrite_label(label_part);
403        return RewriteClause {
404          compiled: true,
405          op:       RewriteOperator::Select,
406          pattern:  RewritePattern::NodeList(Vec::new()),
407        };
408      } else if let Some(id_part) = scope_str.strip_prefix("id:") {
409        if self.options.select_count.is_none() {
410          self.options.select_count = Some(1);
411        }
412        let target_id = id_part.to_string();
413        if document.fragment_ancestor_ids.contains(&target_id) {
414          return whole_fragment_scope(document);
415        }
416        // The id store answers in O(1) — every unscoped `\lxDeclare` after the first
417        // unit carries an `id:` scope (57aq), so a walk of every node per rule cost
418        // 50% in a 300-section document. A missing or detached entry falls back to
419        // the walk (get_property("id") for xml:id: findnodes with @xml:id='...'
420        // fails in rust-libxml).
421        let scope_nodes: Vec<Node> = match document.idstore.get(&target_id) {
422          Some(node)
423            if node.get_attribute("id").as_deref() == Some(target_id.as_str())
424              && node_in_document(document, node) =>
425          {
426            vec![node.clone()]
427          },
428          _ => document
429            .findnodes("descendant-or-self::*", None)
430            .into_iter()
431            .filter(|n| {
432              n.get_property("id").as_deref() == Some(&target_id)
433                || n.get_attribute("xml:id").as_deref() == Some(&target_id)
434            })
435            .collect(),
436        };
437        if !scope_nodes.is_empty() {
438          // Found the scoped element — use it as the tree root for subsequent clauses
439          return RewriteClause {
440            compiled: true,
441            op:       RewriteOperator::Select,
442            pattern:  RewritePattern::NodeList(scope_nodes),
443          };
444        }
445        // No element carries the id: Perl's `descendant-or-self::*[@xml:id='…']`
446        // selects nothing (Rewrite.pm:303-304), so the rule applies nowhere — in
447        // a streaming fragment too, where "not here" means "in another fragment"
448        // (continuing unscoped once stamped section-7 declarations on section-1
449        // math; sweep witness tests/math/declare.tex).
450        return RewriteClause {
451          compiled: true,
452          op:       RewriteOperator::Select,
453          pattern:  RewritePattern::NodeList(Vec::new()),
454        };
455      }
456      // Any other scope: Perl errors and ignores the clause, so the rule applies
457      // unscoped (Rewrite.pm:308-311) — `\lxDeclare[scope=bogus]`, `scope=chapter`
458      // in a class without chapters, `scope=global`.
459      // (A too-many-errors Fatal is logged and latched where `Error!` raises it.)
460      let _ = report_unrecognized_rewrite_scope(scope_str);
461      return RewriteClause {
462        compiled: true,
463        op:       RewriteOperator::Ignore,
464        pattern:  RewritePattern::String(String::new()),
465      };
466    }
467    // Match compilation:
468    // Perl: match => $code → op='test', pattern=$code (closure returns $nnodes)
469    // Perl: match => $string → op='select', pattern=compile_match1($string) ([$xpath, $nnodes,
470    // @wilds]) Perl: match => [$array] → op='multi_select', pattern=[compile_match1($_) for
471    // @$array]
472    if op == RewriteOperator::Match {
473      match pattern {
474        RewritePattern::String(xpath) => {
475          // Pre-compiled XPath string (from .latexml loader)
476          if self.options.select_count.is_none() {
477            self.options.select_count = Some(1);
478          }
479          return RewriteClause {
480            compiled: true,
481            op:       RewriteOperator::Select,
482            pattern:  RewritePattern::String(xpath),
483          };
484        },
485        RewritePattern::TestClosure(_) => {
486          // match => $code: becomes Test operator
487          return RewriteClause {
488            compiled: true,
489            op: RewriteOperator::Test,
490            pattern,
491          };
492        },
493        RewritePattern::MultiSelectPatterns(_) => {
494          // match => [array]: becomes MultiSelect operator
495          return RewriteClause {
496            compiled: true,
497            op: RewriteOperator::MultiSelect,
498            pattern,
499          };
500        },
501        _ => {},
502      }
503    }
504    RewriteClause { compiled: true, op, pattern }
505  }
506
507  pub fn invoke(&mut self, document: &mut Document, root: &Node) -> Result<()> {
508    let clauses: VecDeque<&RewriteClause> = self.clauses.iter().collect();
509    let passes = self.options.passes.unwrap_or(1);
510    if passes > 1 {
511      *self.inserted.borrow_mut() = Some(Vec::new());
512    }
513    self.apply_clause(document, root, 0, clauses.clone())?;
514    // A later pass over the whole tree could only select what the previous pass inserted (the rule's
515    // contract), so it evaluates the select on those nodes alone, in the same (document) order.
516    if let Some(RewriteClause {
517      op: RewriteOperator::Select,
518      pattern: RewritePattern::String(xpath),
519      ..
520    }) = self.clauses.first()
521    {
522      for _pass in 1..passes {
523        let fresh = self
524          .inserted
525          .borrow_mut()
526          .replace(Vec::new())
527          .unwrap_or_default();
528        if fresh.is_empty() {
529          break;
530        }
531        let rest: VecDeque<&RewriteClause> = clauses.iter().skip(1).copied().collect();
532        for node in fresh {
533          if node_within(&node, root) {
534            let matches = document.findnodes(xpath, Some(&node));
535            self.apply_select_matches(document, xpath, matches, &rest)?;
536          }
537        }
538      }
539    }
540    *self.inserted.borrow_mut() = None;
541    Ok(())
542  }
543  // Rewrite spec as input
544  //   scope  => $scope  : a scope like "section:1.2.3" or "label:eq.one"; translated to xpath
545  //   select => $xpath  : selects subtrees based on xpath expression.
546  //   match  => $code   : called on $document and current $node: tests current node, returns
547  // $nnodes, if match   match  => $string : Treats as TeX, converts Box, then DOM tree, to xpath
548  //                      (The matching top-level nodes will be replaced, if replace is the next
549  // op.)   replace=> $code   : removes the current $nnodes, calls $code with $document and
550  // removed nodes   replace=> $string : removes $nnodes
551  //                       Treats $string as TeX, converts to Box and inserts to replace
552  //                       the removed nodes.
553  //   attributes=>$hash : adds data from hash as attributes to the current node.
554  //   regexp  => $string: apply regexp (subst) to all text nodes in/under the current node.
555
556  // Compiled rewrite spec:
557  //   select => $xpath  : operate on nodes selected by $xpath.
558  //   test   => $code   : Calls $code on $document and current $node.
559  //                       Returns number of nodes matched.
560  //   replace=> $code   : removes the current $nnodes, calls $code on them.
561  //   action => $code   : invoke $code on current $node, without removing them.
562  //   regexp  => $string: apply regexp (subst) to all text nodes in/under the current node.
563
564  /// Apply the clauses after a Select to each of its `matches`.
565  fn apply_select_matches(
566    &self,
567    document: &mut Document,
568    xpath: &str,
569    matches: Vec<Node>,
570    clauses: &VecDeque<&RewriteClause>,
571  ) -> Result<()> {
572    // Only apply wildcard filtering on content Selects, not scope Selects
573    let is_content_select = !xpath.contains("xml:id") && !xpath.contains("@id=");
574    let wilds = if is_content_select {
575      self.options.wildcard_paths.clone()
576    } else {
577      None
578    };
579    // Declare-side structural filter (content Selects only, not
580    // scope Selects): verify each broad-XPath match against the
581    // compiled pattern.
582    let pattern_filter = if is_content_select {
583      self.options.declare_filter.as_ref()
584    } else {
585      None
586    };
587    for node in matches {
588      if node.has_attribute("_matched") {
589        continue;
590      }
591      if let Some(pat) = pattern_filter
592        && !declare::declare_node_matches(document, &node, pat)
593      {
594        continue;
595      }
596      let marked = if let Some(ref wpaths) = wilds {
597        mark_wildcards(&node, wpaths)
598      } else {
599        vec![]
600      };
601      // Scope Selects always pass nmatched=1; content Selects use select_count
602      let nmatched_for_clause = if is_content_select {
603        self.options.select_count.unwrap_or(1)
604      } else {
605        1
606      };
607      self.apply_clause(document, &node, nmatched_for_clause, clauses.clone())?;
608      if !marked.is_empty() {
609        unmark_wildcards(&marked);
610      }
611    }
612    Ok(())
613  }
614
615  fn apply_clause(
616    &self,
617    document: &mut Document,
618    tree: &Node,
619    nmatched: usize,
620    mut clauses: VecDeque<&RewriteClause>,
621  ) -> Result<()> {
622    use RewriteOperator::*;
623    if let Some(RewriteClause { compiled: _, op, pattern }) = clauses.pop_front() {
624      match op {
625        Select => {
626          // NodeList variant: pre-resolved nodes from scope DOM walking
627          if let RewritePattern::NodeList(nodes) = pattern {
628            for node in nodes {
629              self.apply_clause(document, node, 1, clauses.clone())?;
630            }
631            return Ok(());
632          }
633          if let RewritePattern::String(xpath) = pattern {
634            // Try subtree context first; if 0 results on a non-root subtree, retry
635            // from document root and filter to descendants of `tree`. This works
636            // around rust-libxml XPath namespace issues on subtree contexts; when
637            // `tree` IS the document root, `findnodes(xpath, None)` evaluates the
638            // exact same query on the exact same root node, so skip the duplicate.
639            let mut matches = document.findnodes(xpath, Some(tree));
640            let is_root = document
641              .get_document()
642              .get_root_element()
643              .is_some_and(|r| std::ptr::eq(r.node_ptr(), tree.node_ptr()));
644            if matches.is_empty()
645              && !is_root
646              && !xpath.contains("xml:id")
647              && !xpath.contains("@id=")
648            {
649              let all = document.findnodes(xpath, None);
650              if !all.is_empty() {
651                let tree_ptr = tree.node_ptr();
652                matches = all
653                  .into_iter()
654                  .filter(|n| {
655                    let mut cur = n.get_parent();
656                    while let Some(p) = cur {
657                      if std::ptr::eq(p.node_ptr(), tree_ptr) {
658                        return true;
659                      }
660                      cur = p.get_parent();
661                    }
662                    false
663                  })
664                  .collect();
665              }
666            }
667            self.apply_select_matches(document, xpath, matches, &clauses)?;
668          }
669        },
670        Replace => {
671          // Perl Rewrite.pm L122 uses `$tree->parentNode` with no check —
672          // XML::LibXML returns undef silently and subsequent operations
673          // (lastChild / childNodes) on undef are no-ops in practice,
674          // effectively skipping root-level rewrites. In Rust we have to
675          // be explicit: if the matched node is detached or is the root,
676          // there's no parent tree structure to splice into, so skip the
677          // clause just as Perl's no-op degrades to.
678          let Some(mut parent) = tree.get_parent() else {
679            return Ok(());
680          };
681          if !self.options.local_replace {
682            // Perl `Rewrite.pm:123-152`: detach the matched node and every following sibling
683            // while the closure runs so closures that query or inspect the DOM see Perl's tree.
684            let mut following = VecDeque::new();
685            while let Some(mut sib) = parent.get_last_child() {
686              sib.unbind_node();
687              following.push_front(sib.clone());
688              if sib == *tree {
689                break;
690              }
691            }
692            let mut replaced = Vec::with_capacity(nmatched);
693            for _ in 0..nmatched {
694              if let Some(node) = following.pop_front() {
695                replaced.push(node);
696              }
697            }
698            for rnode in replaced.iter() {
699              document.unrecord_node_ids(rnode);
700            }
701            document.set_node(&parent);
702            let point_opt = parent.get_last_child();
703            if let RewritePattern::Closure(closure) = pattern
704              && let Err(fatal) = closure(document, replaced.iter_mut().collect())
705            {
706              // (the siblings after the match are kept where Perl's `die` leaves them detached;
707              // rhai-bindings/rewrite_fatal_keeps_the_document.tex)
708              for mut fnode in following {
709                parent.add_child(&mut fnode)?;
710              }
711              return Err(fatal);
712            }
713            let mut ins_queue = VecDeque::new();
714            let mut walk = parent.get_last_child();
715            while let Some(sib) = walk {
716              if point_opt.as_ref() == Some(&sib) {
717                break;
718              }
719              walk = sib.get_prev_sibling();
720              ins_queue.push_front(sib);
721            }
722            let inserted: Vec<Node> = ins_queue.into_iter().collect();
723            for ins in inserted.iter() {
724              document.record_node_ids(ins)?;
725            }
726            let font = document.get_node_font(tree).clone();
727            for ins in inserted.iter() {
728              document.merge_node_font_rec(ins, &font)?;
729            }
730            if let Some(sink) = self.inserted.borrow_mut().as_mut() {
731              sink.extend(inserted.iter().cloned());
732            }
733            for mut fnode in following {
734              parent.add_child(&mut fnode)?;
735            }
736            return Ok(());
737          }
738
739          // Opt-in O(inserted) splice for DOM-local built-in rules: detach only `nmatched`
740          // nodes and park an RAII `<?_lx_rw?>` PI sentinel at the end of `parent`.
741          struct SentinelGuard(Option<Node>);
742          impl Drop for SentinelGuard {
743            fn drop(&mut self) {
744              if let Some(pi) = self.0.take() {
745                pi.free_subtree();
746              }
747            }
748          }
749
750          let mut replaced = Vec::with_capacity(nmatched);
751          let mut cur_opt = Some(tree.clone());
752          for _ in 0..nmatched {
753            let Some(mut node) = cur_opt else {
754              break;
755            };
756            cur_opt = node.get_next_sibling();
757            node.unbind_node();
758            replaced.push(node);
759          }
760          let anchor_opt = cur_opt;
761          for rnode in replaced.iter() {
762            document.unrecord_node_ids(rnode);
763          }
764          let mut sentinel = SentinelGuard(if anchor_opt.is_some() {
765            let mut pi = document
766              .document
767              .create_processing_instruction("_lx_rw", "")
768              .expect("create rewrite sentinel PI");
769            parent.add_child(&mut pi)?;
770            Some(pi)
771          } else {
772            None
773          });
774          document.set_node(&parent);
775          let point_opt = sentinel.0.clone().or_else(|| parent.get_last_child());
776          if let RewritePattern::Closure(closure) = pattern {
777            closure(document, replaced.iter_mut().collect())?;
778          }
779          let mut ins_queue = VecDeque::new();
780          let mut walk = parent.get_last_child();
781          while let Some(sib) = walk {
782            if point_opt.as_ref() == Some(&sib) {
783              break;
784            }
785            walk = sib.get_prev_sibling();
786            ins_queue.push_front(sib);
787          }
788          drop(point_opt);
789          let inserted: Vec<Node> = ins_queue.into_iter().collect();
790
791          for ins in inserted.iter() {
792            document.record_node_ids(ins)?;
793          }
794          let font = document.get_node_font(tree).clone();
795          for ins in inserted.iter() {
796            document.merge_node_font_rec(ins, &font)?;
797          }
798          if let Some(mut target) = anchor_opt.filter(|a| a.get_parent().as_ref() == Some(&parent))
799          {
800            if let Some(sink) = self.inserted.borrow_mut().as_mut() {
801              for ins in &inserted {
802                if ins.get_type() != Some(libxml::tree::NodeType::TextNode) {
803                  sink.push(ins.clone());
804                }
805              }
806            }
807            // Move the non-text PI right before `target` so inserting TextNodes cannot
808            // reorder via `xmlAddPrevSibling(Text, Text)`, and coalesce both text boundaries.
809            if let Some(mut pi) = sentinel.0.take() {
810              pi.unlink_node();
811              if let Err(err) = target.add_prev_sibling(&mut pi) {
812                document.discard_subtree(pi);
813                return Err(err.into());
814              }
815              sentinel.0 = Some(pi);
816              let pi_ref = sentinel.0.as_mut().unwrap();
817              for mut ins in inserted {
818                ins.unlink_node();
819                if ins.get_type() == Some(libxml::tree::NodeType::TextNode)
820                  && let Some(mut prev) = pi_ref.get_prev_sibling()
821                  && prev.get_type() == Some(libxml::tree::NodeType::TextNode)
822                {
823                  let mut merged = prev.get_content();
824                  merged.push_str(&ins.get_content());
825                  let _ = prev.set_content(&merged);
826                  document.discard_subtree(ins);
827                } else {
828                  pi_ref.add_prev_sibling(&mut ins)?;
829                }
830              }
831              let left_neighbor = pi_ref.get_prev_sibling();
832              let right_neighbor = pi_ref.get_next_sibling();
833              if let Some(pi) = sentinel.0.take() {
834                document.discard_subtree(pi);
835              }
836              if let (Some(mut left), Some(right)) = (left_neighbor, right_neighbor)
837                && left.get_type() == Some(libxml::tree::NodeType::TextNode)
838                && right.get_type() == Some(libxml::tree::NodeType::TextNode)
839              {
840                let mut merged = left.get_content();
841                merged.push_str(&right.get_content());
842                let _ = left.set_content(&merged);
843                document.discard_subtree(right);
844              }
845            }
846          } else {
847            if let Some(pi) = sentinel.0.take() {
848              document.discard_subtree(pi);
849            }
850            if let Some(sink) = self.inserted.borrow_mut().as_mut() {
851              sink.extend(inserted.iter().cloned());
852            }
853          }
854        },
855        Attributes => {
856          if let Some(ref attrs) = self.options.attributes_map {
857            let has_wc = tree.has_attribute("_has_wildcards");
858            if has_wc {
859              // Perl: setAttributes_wild — wildcards present in matched tree
860              let mut nodes = vec![tree.clone()];
861              // Collect nmatched siblings
862              let mut cur = tree.clone();
863              for _ in 1..nmatched {
864                match cur.get_next_sibling() {
865                  Some(sib) => {
866                    cur = sib.clone();
867                    nodes.push(sib);
868                  },
869                  _ => {
870                    break;
871                  },
872                }
873              }
874              set_attributes_wild(document, attrs, nodes, nmatched)?;
875            } else if nmatched > 1 {
876              // Multi-node: collect nmatched element siblings starting from tree
877              let mut nodes = vec![tree.clone()];
878              let mut cur = tree.clone();
879              for _ in 1..nmatched {
880                while let Some(sib) = cur.get_next_sibling() {
881                  cur = sib.clone();
882                  if sib.get_type() == Some(libxml::tree::NodeType::ElementNode) {
883                    nodes.push(sib);
884                    break;
885                  }
886                }
887              }
888              // Perl: skip if ALL nodes already matched
889              if nodes.iter().any(|n| !n.has_attribute("_matched"))
890                && let Ok(Some(mut wrapper)) = document.wrap_nodes("ltx:XMWrap", nodes)
891              {
892                for (key, value) in attrs {
893                  if !key.starts_with('_') {
894                    let _ = wrapper.set_attribute(key, value);
895                  }
896                }
897                let _ = wrapper.set_attribute("_rewrite", "1");
898              }
899            } else if !tree.has_attribute("_matched") {
900              // Single node: set attributes directly
901              let mut node = tree.clone();
902              for (key, value) in attrs {
903                if !key.starts_with('_') {
904                  let _ = node.set_attribute(key, value);
905                }
906              }
907              if node.get_name() == "XMApp" && attrs.contains_key("role") {
908                let _ = node.set_attribute("_rewrite", "1");
909              }
910            }
911          }
912          mark_seen(tree, nmatched);
913          self.apply_clause(document, tree, nmatched, clauses)?;
914        },
915        Ignore => {
916          // Perl: $self->applyClause($document, $tree, $nmatched, @more_clauses);
917          self.apply_clause(document, tree, nmatched, clauses)?;
918        },
919        Regexp => {
920          // Perl: finds ALL descendant text nodes via 'descendant-or-self::text()',
921          // applies s///g substitution via compiled closure, and calls setData().
922          if let RewritePattern::RegexpClosure(closure) = pattern {
923            let text_nodes = document.findnodes("descendant-or-self::text()", Some(tree));
924            for mut text_node in text_nodes {
925              let content = text_node.get_content();
926              if let Some(modified) = closure(&content) {
927                let _ = text_node.set_content(&modified);
928              }
929            }
930          } else if let RewritePattern::String(regex_str) = pattern {
931            // Fallback for uncompiled string regex: compile and apply as substitution
932            let re =
933              regex::Regex::new(regex_str).unwrap_or_else(|_| regex::Regex::new("$^").unwrap());
934            let text_nodes = document.findnodes("descendant-or-self::text()", Some(tree));
935            for mut text_node in text_nodes {
936              let content = text_node.get_content();
937              let result = re.replace_all(&content, "");
938              if result != content {
939                let _ = text_node.set_content(&result);
940              }
941            }
942          }
943        },
944        Label => {
945          // Unreachable once compiled: compile_clause lowers Label to a
946          // Select via the scope "label:…" path (Perl Rewrite.pm L288-297 —
947          // a label clause has NO runtime behavior). Defensive pass-through.
948          self.apply_clause(document, tree, nmatched, clauses)?;
949        },
950        Trace => {
951          // Debug tracing — just continue
952          self.apply_clause(document, tree, nmatched, clauses)?;
953        },
954        Action => {
955          // Perl: $code->($document, $tree, $nmatched)
956          // Action invokes a closure on the matched node without removing it.
957          if let RewritePattern::Closure(closure) = pattern {
958            let mut node = tree.clone();
959            closure(document, vec![&mut node])?;
960          }
961          // Continue with remaining clauses
962          self.apply_clause(document, tree, nmatched, clauses)?;
963        },
964        Test => {
965          // Perl: $nnodes = &$pattern($document, $tree);
966          //       $self->applyClause($document, $tree, $nnodes, @more_clauses) if $nnodes;
967          // Test closure returns node count; if 0/falsy, skip remaining clauses.
968          if let RewritePattern::TestClosure(closure) = pattern {
969            let nnodes = closure(document, tree)?;
970            if nnodes > 0 {
971              self.apply_clause(document, tree, nnodes, clauses)?;
972            }
973          } else if let RewritePattern::Closure(closure) = pattern {
974            // Legacy fallback: RewriteReplaceClosure used as test (always passes)
975            let mut node = tree.clone();
976            closure(document, vec![&mut node])?;
977            self.apply_clause(document, tree, nmatched, clauses)?;
978          }
979        },
980        MultiSelect => {
981          // Perl: foreach my $subpattern (@$pattern) {
982          //         my ($xpath, $nnodes, @wilds) = @$subpattern;
983          //         my @matches = $document->findnodes($xpath, $tree);
984          //         foreach my $node (@matches) {
985          //           my @w = markWildcards($node, @wilds);
986          //           $self->applyClause($document, $node, $nnodes, @more_clauses);
987          //           unmarkWildcards($node, @w); } }
988          if let RewritePattern::MultiSelectPatterns(entries) = pattern {
989            for entry in entries {
990              let matches = document.findnodes(&entry.xpath, Some(tree));
991              for node in matches {
992                if node.has_attribute("_matched") {
993                  continue;
994                }
995                let marked = if !entry.wilds.is_empty() {
996                  mark_wildcards(&node, &entry.wilds)
997                } else {
998                  vec![]
999                };
1000                self.apply_clause(document, &node, entry.nnodes, clauses.clone())?;
1001                if !marked.is_empty() {
1002                  unmark_wildcards(&marked);
1003                }
1004              }
1005            }
1006          } else if let RewritePattern::String(xpath) = pattern {
1007            // Legacy fallback: single xpath with shared select_count
1008            let count = self.options.select_count.unwrap_or(1);
1009            let matches = document.findnodes(xpath, Some(tree));
1010            for node in matches {
1011              if node.has_attribute("_matched") {
1012                continue;
1013              }
1014              self.apply_clause(document, &node, count, clauses.clone())?;
1015            }
1016          }
1017        },
1018        _ => {
1019          // Remaining unimplemented operators — skip silently
1020          self.apply_clause(document, tree, nmatched, clauses)?;
1021        },
1022      }
1023    } else {
1024      // No more clauses — mark the matched nodes as seen
1025      // Perl: markSeen($tree, $nmatched) when no more clauses
1026      mark_seen(tree, nmatched);
1027    }
1028
1029    Ok(())
1030  }
1031}
1032
1033// ======================================================================
1034// WildCard support: domToXPath, wildcard marking, XMDual wrapping
1035// ======================================================================
1036
1037/// Wildcard position path: indices to navigate from matched root to wildcard node.
1038/// First index uses nth_sibling (sibling offset), rest use nth_child (child position).
1039pub type WildPath = Vec<usize>;
1040
1041/// Result of domToXPath compilation: xpath string, node count, wildcard paths.
1042pub type CompiledMatch = (String, usize, Vec<WildPath>);
1043
1044/// Convert a DOM subtree to an XPath expression + wildcard position tracking.
1045/// Perl: domToXPath() → domToXPath_rec() → domToXPath_seq()
1046pub fn dom_to_xpath(document: &Document, node: &Node) -> CompiledMatch {
1047  let (xpath, nnodes, _nwilds, wilds) =
1048    dom_to_xpath_rec(document, node, "descendant-or-self", None);
1049  (xpath, nnodes, wilds)
1050}
1051
1052/// Attributes excluded from XPath match predicates.
1053fn is_excluded_match_attr(key: &str) -> bool {
1054  matches!(
1055    key,
1056    "scriptpos" | "mathstyle" | "xml:id" | "fontsize" | "_font" | "_pvis" | "_cvis"
1057  ) || key.starts_with('_')
1058}
1059
1060/// Recursive DOM-to-XPath conversion.
1061/// Returns (xpath_fragment, node_count, wildcard_count, wildcard_paths)
1062fn dom_to_xpath_rec(
1063  document: &Document,
1064  node: &Node,
1065  axis: &str,
1066  pos: Option<usize>,
1067) -> (String, usize, usize, Vec<WildPath>) {
1068  let node_type = node.get_type();
1069  // NodeList / DocumentFragment: sequence of children
1070  if node_type == Some(libxml::tree::NodeType::DocumentFragNode) {
1071    let children = node.get_child_nodes();
1072    let (xpath, nnodes, wilds) = dom_to_xpath_seq(document, axis, pos, &children);
1073    return (xpath, nnodes, 0, wilds);
1074  }
1075  if node_type == Some(libxml::tree::NodeType::ElementNode) {
1076    let qname = arena::with(get_node_qname(node), |s| s.to_string());
1077    let children = node.get_child_nodes();
1078
1079    // _WildCard_ element → matches anything
1080    if qname == "_WildCard_" {
1081      if !children.is_empty() {
1082        // WildCard WITH children: recurse on children
1083        let child_list = node.get_child_nodes();
1084        // Create a fragment-like approach: process children as a sequence
1085        let (xpath, _nnodes, _nwilds, _wilds) =
1086          dom_to_xpath_rec(document, &child_list[0], axis, pos);
1087        let n = children.len().max(1);
1088        return (xpath, n, n, vec![]);
1089      } else {
1090        return (format!("{axis}::*"), 1, 1, vec![]);
1091      }
1092    }
1093    // XMRef pointing to a _WildCard_ is also a wildcard
1094    if qname == "ltx:XMRef"
1095      && let Some(idref) = node.get_property("idref")
1096      && let Some(target) = document.lookup_id(&idref).cloned()
1097    {
1098      let tqname = arena::with(get_node_qname(&target), |s| s.to_string());
1099      // Check if target is XMArg/XMWrap with single WildCard child
1100      let is_wild = if tqname.ends_with("XMArg") || tqname.ends_with("XMWrap") {
1101        let tc = target.get_child_nodes();
1102        tc.len() == 1 && arena::with(get_node_qname(&tc[0]), |s| s == "_WildCard_")
1103      } else {
1104        tqname == "_WildCard_"
1105      };
1106      if is_wild {
1107        return (format!("{axis}::*"), 1, 1, vec![]);
1108      }
1109    }
1110    // XMArg/XMWrap with single _WildCard_ child
1111    if (qname.ends_with("XMArg") || qname.ends_with("XMWrap"))
1112      && children.len() == 1
1113      && arena::with(get_node_qname(&children[0]), |s| s.to_string()) == "_WildCard_"
1114    {
1115      let wc_children = children[0].get_child_nodes();
1116      if !wc_children.is_empty() {
1117        let (child_xpath, _nn, _nw, _w) =
1118          dom_to_xpath_rec(document, &wc_children[0], "child", Some(1));
1119        let mut preds = vec![];
1120        if let Some(p) = pos {
1121          preds.push(format!("position()={p}"));
1122        }
1123        preds.push(child_xpath);
1124        return (
1125          format!("{axis}::{qname}[{}]", preds.join(" and ")),
1126          1,
1127          1,
1128          vec![],
1129        );
1130      } else {
1131        return (format!("{axis}::*"), 1, 1, vec![]);
1132      }
1133    }
1134
1135    // Standard element: build predicates from attributes and children
1136    let mut predicates = Vec::new();
1137    let mut wilds = Vec::new();
1138
1139    // Attribute predicates
1140    let attrs = node.get_attributes();
1141    for (key, value) in &attrs {
1142      if !is_excluded_match_attr(key) {
1143        predicates.push(format!("@{key}='{}'", value.replace('\'', "&apos;")));
1144      }
1145    }
1146    // Child predicates
1147    if !children.is_empty() {
1148      let all_text = children
1149        .iter()
1150        .all(|c| c.get_type() == Some(libxml::tree::NodeType::TextNode));
1151      let all_elem = children
1152        .iter()
1153        .all(|c| c.get_type() == Some(libxml::tree::NodeType::ElementNode));
1154      if all_text {
1155        let text = node.get_content();
1156        predicates.push(format!("text()='{}'", text.replace('\'', "&apos;")));
1157      } else if all_elem {
1158        let (xp, _nn, w) = dom_to_xpath_seq(document, "child", Some(1), &children);
1159        predicates.push(xp);
1160        wilds.extend(w);
1161      }
1162      // Mixed content: skip (rare in math patterns)
1163    }
1164
1165    // Position-based matching (when this is a child in a sequence)
1166    let tag = if let Some(p) = pos {
1167      predicates.insert(0, format!("self::{qname}"));
1168      predicates.insert(0, format!("position()={p}"));
1169      "*".to_string()
1170    } else {
1171      qname
1172    };
1173    let preds = predicates.join(" and ");
1174    let xpath = if preds.is_empty() {
1175      format!("{axis}::{tag}")
1176    } else {
1177      format!("{axis}::{tag}[{preds}]")
1178    };
1179    return (xpath, 1, 0, wilds);
1180  }
1181  if node_type == Some(libxml::tree::NodeType::TextNode) {
1182    let text = node.get_content();
1183    return (
1184      format!("*[text()='{}']", text.replace('\'', "&apos;")),
1185      1,
1186      0,
1187      vec![],
1188    );
1189  }
1190  (String::new(), 0, 0, vec![])
1191}
1192
1193/// Convert a sequence of sibling nodes to XPath with wildcard tracking.
1194/// Perl: domToXPath_seq()
1195fn dom_to_xpath_seq(
1196  document: &Document,
1197  axis: &str,
1198  pos: Option<usize>,
1199  nodes: &[Node],
1200) -> (String, usize, Vec<WildPath>) {
1201  if nodes.is_empty() {
1202    return (String::new(), 0, vec![]);
1203  }
1204  let mut i: usize = 1;
1205  let mut sib_xpaths = Vec::new();
1206  let mut wilds = Vec::new();
1207
1208  // First node
1209  let (xpath, _nn, nwilds, w0) = dom_to_xpath_rec(document, &nodes[0], axis, pos);
1210  if nwilds > 0 {
1211    for _ in 0..nwilds {
1212      wilds.push(vec![i]);
1213      i += 1;
1214    }
1215  } else {
1216    for w in &w0 {
1217      let mut path = vec![1usize];
1218      path.extend(w);
1219      wilds.push(path);
1220    }
1221    i += 1;
1222  }
1223  // Remaining siblings
1224  for sib in &nodes[1..] {
1225    let (xp, _nn, nw, w) = dom_to_xpath_rec(document, sib, "following-sibling", Some(i - 1));
1226    sib_xpaths.push(xp);
1227    if nw > 0 {
1228      for _ in 0..nw {
1229        wilds.push(vec![i]);
1230        i += 1;
1231      }
1232    } else {
1233      for ww in &w {
1234        let mut path = vec![i];
1235        path.extend(ww);
1236        wilds.push(path);
1237      }
1238      i += 1;
1239    }
1240  }
1241  let mut result = xpath;
1242  for sp in &sib_xpaths {
1243    result = format!("{result}[{sp}]");
1244  }
1245  (result, i - 1, wilds)
1246}
1247
1248/// Navigate to the nth sibling (1-based) from a starting node.
1249fn nth_sibling(node: &Node, n: usize) -> Option<Node> {
1250  let mut current = Some(node.clone());
1251  for _ in 1..n {
1252    current = current.and_then(|n| {
1253      let mut next = n.get_next_sibling();
1254      // Skip non-element nodes
1255      while let Some(ref s) = next {
1256        if s.get_type() == Some(libxml::tree::NodeType::ElementNode) {
1257          break;
1258        }
1259        next = s.get_next_sibling();
1260      }
1261      next
1262    });
1263  }
1264  current
1265}
1266
1267/// Navigate to the nth child (1-based) of a node.
1268fn nth_child(node: &Node, n: usize) -> Option<Node> {
1269  node.get_child_nodes().into_iter().nth(n - 1)
1270}
1271
1272/// Mark wildcard nodes in the matched tree.
1273/// Perl: markWildcards($node, @wilds)
1274pub fn mark_wildcards(node: &Node, wilds: &[WildPath]) -> Vec<Node> {
1275  if wilds.is_empty() {
1276    return vec![];
1277  }
1278  let mut n = node.clone();
1279  let _ = n.set_attribute("_has_wildcards", "1");
1280  let mut marked = Vec::new();
1281  for wild in wilds {
1282    let mut current = Some(node.clone());
1283    let mut first = true;
1284    for &idx in wild {
1285      if current.is_none() {
1286        break;
1287      }
1288      current = if first {
1289        first = false;
1290        nth_sibling(current.as_ref().unwrap(), idx)
1291      } else {
1292        nth_child(current.as_ref().unwrap(), idx)
1293      };
1294    }
1295    if let Some(ref c) = current
1296      && c.get_type() == Some(libxml::tree::NodeType::ElementNode)
1297    {
1298      let mut mc = c.clone();
1299      let _ = mc.set_attribute("_wildcard", "1");
1300      marked.push(mc);
1301    }
1302  }
1303  marked
1304}
1305
1306/// Unmark wildcard nodes after processing.
1307pub fn unmark_wildcards(nodes: &[Node]) {
1308  for n in nodes {
1309    if n.get_type() == Some(libxml::tree::NodeType::ElementNode) {
1310      let mut mc = n.clone();
1311      let _ = mc.remove_attribute("_has_wildcards");
1312      let _ = mc.remove_attribute("_wildcard");
1313    }
1314  }
1315}
1316
1317/// Collect xml:ids of wildcard-marked nodes, generating IDs if needed.
1318/// Collect xml:ids of wildcard-marked nodes, generating IDs if needed.
1319/// Perl: set_wildcard_ids($document, $node) — Rewrite.pm L219-231
1320/// Faithfully translated: if node has _wildcard, return its ID.
1321/// If node has _matched, skip (already processed by prior rule).
1322/// Otherwise recurse into children.
1323pub fn set_wildcard_ids(document: &mut Document, node: &Node) -> Vec<String> {
1324  if node.get_type() != Some(libxml::tree::NodeType::ElementNode) {
1325    return vec![];
1326  }
1327  if node.has_attribute("_matched") {
1328    return vec![];
1329  }
1330  if node.has_attribute("_wildcard") {
1331    // Perl: unconditionally returns the wildcard's ID.
1332    // Even if all descendants are already matched, the ID is still needed
1333    // for XMRef in the content arm. pruneXMDuals handles collapsing later.
1334    let id = if let Some(existing) = node
1335      .get_property("xml:id")
1336      .or_else(|| node.get_property("id"))
1337    {
1338      existing
1339    } else {
1340      // Generate an ID for this node
1341      let mut n = node.clone();
1342      let _ = document.generate_id(&mut n, "");
1343      node
1344        .get_property("xml:id")
1345        .or_else(|| node.get_property("id"))
1346        .unwrap_or_default()
1347    };
1348    return vec![id];
1349  }
1350  // Recurse into children
1351  let mut ids = Vec::new();
1352  for child in node.get_child_nodes() {
1353    ids.extend(set_wildcard_ids(document, &child));
1354  }
1355  ids
1356}
1357
1358/// Set attributes on a tree containing wildcards, creating XMDual wrappers.
1359/// Perl: setAttributes_wild($document, $attributes, @nodes) — Rewrite.pm L195-217
1360///
1361/// Faithfully translated from Perl. The structure created is:
1362/// ```xml
1363/// <XMDual role="...">
1364///   <XMApp>                    <!-- content arm -->
1365///     <XMTok decl_id="..." />  <!-- semantic operator -->
1366///     <XMRef idref="..." />    <!-- references to wildcards -->
1367///   </XMApp>
1368///   <XMWrap>                   <!-- presentation arm -->
1369///     [original nodes]         <!-- with _wildcard markers -->
1370///   </XMWrap>
1371/// </XMDual>
1372/// ```
1373pub fn set_attributes_wild(
1374  document: &mut Document,
1375  attrs: &HashMap<String, String>,
1376  nodes: Vec<Node>,
1377  _nmatched: usize,
1378) -> Result<()> {
1379  // Perl L197: return unless grep { !$_->getAttribute('_matched'); } @nodes;
1380  if nodes.iter().all(|n| n.has_attribute("_matched")) {
1381    return Ok(());
1382  }
1383  let nowrap = attrs.contains_key("_nowrap");
1384  // Perl L199-203: _nowrap or single XMDual → set attrs on first non-wildcard node
1385  if nowrap || (nodes.len() == 1 && nodes[0].get_name() == "XMDual") {
1386    if let Some(nonwild) = nodes.iter().find(|n| !n.has_attribute("_wildcard")) {
1387      let mut n = nonwild.clone();
1388      for (key, value) in attrs {
1389        if !key.starts_with('_') {
1390          let _ = n.set_attribute(key, value);
1391        }
1392      }
1393    }
1394    return Ok(());
1395  }
1396
1397  // Perl L205-216: wrap the presentation nodes in an XMWrap, collect the
1398  // wildcard ids, wrap that in an XMDual, then build the content arm
1399  // XMApp(op-with-attrs, XMRef per wildcard) BEFORE the XMWrap. An XMDual
1400  // has EXACTLY two children (content, presentation) — the earlier "flat"
1401  // variant (presentation nodes as direct dual children) was destroyed
1402  // downstream, silently dropping the matched span (gee-one repro:
1403  // `g(a)` collapsed to a bare `)` carrying the declaration's role).
1404  let Some(wrap_node) = document.wrap_nodes("ltx:XMWrap", nodes)? else {
1405    return Ok(());
1406  };
1407  let wild_ids = set_wildcard_ids(document, &wrap_node);
1408  let Some(mut dual_node) = document.wrap_nodes("ltx:XMDual", vec![wrap_node.clone()])? else {
1409    return Ok(());
1410  };
1411
1412  // Set role on XMDual (Perl L209)
1413  if let Some(role) = attrs.get("role") {
1414    let _ = dual_node.set_attribute("role", role);
1415  }
1416
1417  // Build content arm: XMApp > XMTok[attrs] + XMRef[wildcard_ids]
1418  let doc = document.get_document();
1419  let mut content_app = Node::new("XMApp", None, doc)?;
1420  let mut content_op = Node::new("XMTok", None, doc)?;
1421  for (key, value) in attrs {
1422    if key != "role" && !key.starts_with('_') {
1423      let _ = content_op.set_attribute(key, value);
1424    }
1425  }
1426  content_app.add_child(&mut content_op)?;
1427  for rid in &wild_ids {
1428    let mut xmref = Node::new("XMRef", None, doc)?;
1429    let _ = xmref.set_attribute("idref", rid);
1430    content_app.add_child(&mut xmref)?;
1431  }
1432
1433  // Insert content arm before the presentation XMWrap (Perl removes the
1434  // wrapper, opens the XMApp, then re-appends the wrapper — same order).
1435  let mut wrap_mut = wrap_node;
1436  wrap_mut.add_prev_sibling(&mut content_app)?;
1437  Ok(())
1438}
1439
1440/// Mark a node (and nsibs following siblings) as matched, preventing re-matching.
1441/// Perl: markSeen($node, $nsibs) + markSeen_rec($node)
1442fn mark_seen(node: &Node, nsibs: usize) {
1443  let mut current = Some(node.clone());
1444  for _i in 0..nsibs {
1445    if let Some(n) = current {
1446      mark_seen_rec(&n);
1447      current = n.get_next_sibling();
1448    } else {
1449      break;
1450    }
1451  }
1452}
1453
1454fn mark_seen_rec(node: &Node) {
1455  if node.has_attribute("_wildcard") {
1456    return;
1457  }
1458  let mut n = node.clone();
1459  let _ = n.set_attribute("_matched", "1");
1460  for child in node.get_child_nodes() {
1461    if child.get_type() == Some(libxml::tree::NodeType::ElementNode) {
1462      mark_seen_rec(&child);
1463    }
1464  }
1465}
1466
1467#[cfg(test)]
1468mod tests {
1469  use super::*;
1470  use crate::document::Document;
1471
1472  /// A `label` clause must COMPILE AWAY into a Select on the labeled node's
1473  /// `xml:id` — Perl `Rewrite.pm::compileClause` L288-297:
1474  /// `$op = 'select'; $pattern = ["descendant-or-self::*[\@xml:id='" .
1475  ///  $self->getLabelID($pattern) . "']", 1];`
1476  ///
1477  /// It has no runtime behavior in Perl. The former Rust runtime arm instead
1478  /// tried to RECORD the current node's id under the label — not Perl
1479  /// semantics, and dead anyway (its bare `get_attribute("xml:id")` read
1480  /// always returned None). `label => …` is reachable only from the Rhai
1481  /// `DefRewrite(#{label: …})` option bag, so this unit test is its only
1482  /// coverage.
1483  #[test]
1484  fn label_clause_compiles_to_a_select_on_the_labeled_id() {
1485    let mut document = Document::new();
1486    document
1487      .rewrite_labels
1488      .insert("LABEL:eq.one".to_string(), "S1.E2".to_string());
1489
1490    let mut rule = Rewrite::new("text", RewriteOptions {
1491      label: Some("eq.one".to_string()),
1492      ..RewriteOptions::default()
1493    });
1494    assert!(
1495      matches!(
1496        rule.clauses.first().map(|c| c.op),
1497        Some(RewriteOperator::Label)
1498      ),
1499      "a label option must start life as a Label clause"
1500    );
1501    rule.compile_clauses(&mut document);
1502
1503    match rule.clauses.first() {
1504      Some(RewriteClause {
1505        op: RewriteOperator::Select,
1506        pattern: RewritePattern::String(xpath),
1507        ..
1508      }) => assert_eq!(xpath, "descendant-or-self::*[@xml:id='S1.E2']"),
1509      other => panic!("label must lower to a Select on the labeled id, got {other:?}"),
1510    }
1511    // Perl sets the select count to 1 in the same breath (L297's trailing `1`).
1512    assert_eq!(rule.options.select_count, Some(1));
1513  }
1514
1515  /// An UNKNOWN label selects nothing, as Perl's empty-id xpath does (Rewrite.pm:49-55,
1516  /// :300-302): the rule applies nowhere, in the eager and the streaming path alike (57aq).
1517  #[test]
1518  fn unknown_label_selects_nothing() {
1519    let mut document = Document::new();
1520    let mut rule = Rewrite::new("text", RewriteOptions {
1521      label: Some("nope".to_string()),
1522      ..RewriteOptions::default()
1523    });
1524    rule.compile_clauses(&mut document);
1525    assert!(
1526      matches!(
1527        rule.clauses.first(),
1528        Some(RewriteClause {
1529          op: RewriteOperator::Select,
1530          pattern: RewritePattern::NodeList(nodes),
1531          ..
1532        }) if nodes.is_empty()
1533      ),
1534      "an unresolvable label must select nothing"
1535    );
1536  }
1537
1538  /// The id store answers an `id:` scope only while its entry still carries the id: an id moved to
1539  /// another node (a stale entry) falls back to the walk, which finds the node that carries it now
1540  /// (57as).
1541  #[test]
1542  fn id_scope_skips_a_stale_idstore_entry() {
1543    let mut document = Document::new();
1544    let xml = document.get_document_mut();
1545    let mut root = Node::new("root", None, xml).unwrap();
1546    xml.set_root_element(&root);
1547    let mut first = Node::new("first", None, xml).unwrap();
1548    let mut second = Node::new("second", None, xml).unwrap();
1549    root.add_child(&mut first).unwrap();
1550    root.add_child(&mut second).unwrap();
1551    first.set_attribute("xml:id", "X").unwrap();
1552    document.idstore.insert("X".to_string(), first.clone());
1553    // The id moves on; the store is not told.
1554    first
1555      .remove_attribute_ns("id", crate::common::xml::XML_NS)
1556      .unwrap();
1557    second.set_attribute("xml:id", "X").unwrap();
1558
1559    let mut rule = Rewrite::new("text", RewriteOptions {
1560      scope: Some(Scope::Named(crate::pin!("id:X"))),
1561      ..RewriteOptions::default()
1562    });
1563    rule.compile_clauses(&mut document);
1564    match rule.clauses.first() {
1565      Some(RewriteClause {
1566        op: RewriteOperator::Select,
1567        pattern: RewritePattern::NodeList(nodes),
1568        ..
1569      }) => assert_eq!(nodes, &vec![second]),
1570      other => panic!("an id scope must select the node carrying the id, got {other:?}"),
1571    }
1572  }
1573
1574  /// Guard `Replace`'s PI-sentinel O(1) splice against three libxml2 hazards:
1575  /// 1. `[Text("A"), <old/>, Text("B")]` + `[Text("X"), <Y/>, Text("Z")]` must
1576  ///    preserve order and coalesce both boundaries (`[Text("AX"), <Y/>, Text("ZB")]`)
1577  ///    rather than letting `xmlAddPrevSibling(Text("B"), Text("X"))` reorder nodes.
1578  /// 2. `[Text("A"), <old/>, Text("B")]` + `[]` must coalesce to `[Text("AB")]`.
1579  /// 3. A closure returning `Err` must unlink and free the `<?_lx_rw?>` sentinel.
1580  #[test]
1581  fn replace_preserves_order_coalesces_text_and_cleans_sentinel_on_error() {
1582    use libxml::tree::NodeType;
1583
1584    // Case 1: `[Text("A"), <old/>, Text("B")]` -> `[Text("AX"), <Y/>, Text("ZB")]`
1585    {
1586      let mut document = Document::new();
1587      let xml = document.get_document_mut();
1588      let mut root = Node::new("root", None, xml).unwrap();
1589      xml.set_root_element(&root);
1590      let mut t_a = Node::new_text("A", xml).unwrap();
1591      let mut old = Node::new("old", None, xml).unwrap();
1592      let mut t_b = Node::new_text("B", xml).unwrap();
1593      root.add_child(&mut t_a).unwrap();
1594      root.add_child(&mut old).unwrap();
1595      root.add_child(&mut t_b).unwrap();
1596
1597      let rule = Rewrite::new("text", RewriteOptions {
1598        local_replace: true,
1599        ..RewriteOptions::default()
1600      });
1601      let clause = RewriteClause::new_compiled(
1602        RewriteOperator::Replace,
1603        RewritePattern::Closure(Rc::new(|doc, _replaced| {
1604          let mut parent = doc.get_node().clone();
1605          let mut t_x = Node::new_text("X", doc.get_document()).unwrap();
1606          let mut y = Node::new("Y", None, doc.get_document()).unwrap();
1607          let mut t_z = Node::new_text("Z", doc.get_document()).unwrap();
1608          parent.add_child(&mut t_x).unwrap();
1609          parent.add_child(&mut y).unwrap();
1610          parent.add_child(&mut t_z).unwrap();
1611          Ok(())
1612        })),
1613      );
1614      rule
1615        .apply_clause(&mut document, &old, 1, VecDeque::from([&clause]))
1616        .unwrap();
1617
1618      let children = root.get_child_nodes();
1619      assert_eq!(children.len(), 3, "expected [Text(AX), <Y/>, Text(ZB)]");
1620      assert_eq!(children[0].get_type(), Some(NodeType::TextNode));
1621      assert_eq!(children[0].get_content(), "AX");
1622      assert_eq!(children[1].get_type(), Some(NodeType::ElementNode));
1623      assert_eq!(children[1].get_name(), "Y");
1624      assert_eq!(children[2].get_type(), Some(NodeType::TextNode));
1625      assert_eq!(children[2].get_content(), "ZB");
1626    }
1627
1628    // Case 2: `[Text("A"), <old/>, Text("B")]` -> `[]` coalesces to `[Text("AB")]`
1629    {
1630      let mut document = Document::new();
1631      let xml = document.get_document_mut();
1632      let mut root = Node::new("root", None, xml).unwrap();
1633      xml.set_root_element(&root);
1634      let mut t_a = Node::new_text("A", xml).unwrap();
1635      let mut old = Node::new("old", None, xml).unwrap();
1636      let mut t_b = Node::new_text("B", xml).unwrap();
1637      root.add_child(&mut t_a).unwrap();
1638      root.add_child(&mut old).unwrap();
1639      root.add_child(&mut t_b).unwrap();
1640
1641      let rule = Rewrite::new("text", RewriteOptions {
1642        local_replace: true,
1643        ..RewriteOptions::default()
1644      });
1645      let clause = RewriteClause::new_compiled(
1646        RewriteOperator::Replace,
1647        RewritePattern::Closure(Rc::new(|_doc, _replaced| Ok(()))),
1648      );
1649      rule
1650        .apply_clause(&mut document, &old, 1, VecDeque::from([&clause]))
1651        .unwrap();
1652
1653      let children = root.get_child_nodes();
1654      assert_eq!(children.len(), 1, "adjacent text nodes must coalesce");
1655      assert_eq!(children[0].get_type(), Some(NodeType::TextNode));
1656      assert_eq!(children[0].get_content(), "AB");
1657    }
1658
1659    // Case 3: closure returning `Err` must not leak `<?_lx_rw?>` into the DOM
1660    {
1661      let mut document = Document::new();
1662      let xml = document.get_document_mut();
1663      let mut root = Node::new("root", None, xml).unwrap();
1664      xml.set_root_element(&root);
1665      let mut old = Node::new("old", None, xml).unwrap();
1666      let mut tail = Node::new("tail", None, xml).unwrap();
1667      root.add_child(&mut old).unwrap();
1668      root.add_child(&mut tail).unwrap();
1669
1670      let rule = Rewrite::new("text", RewriteOptions {
1671        local_replace: true,
1672        ..RewriteOptions::default()
1673      });
1674      let clause = RewriteClause::new_compiled(
1675        RewriteOperator::Replace,
1676        RewritePattern::Closure(Rc::new(|_doc, _replaced| Err(Error::todo()))),
1677      );
1678      assert!(
1679        rule
1680          .apply_clause(&mut document, &old, 1, VecDeque::from([&clause]))
1681          .is_err()
1682      );
1683
1684      let children = root.get_child_nodes();
1685      assert!(
1686        children
1687          .iter()
1688          .all(|n| n.get_type() != Some(NodeType::PiNode)),
1689        "sentinel PI must not remain in DOM after closure error: {children:?}"
1690      );
1691      assert_eq!(children.len(), 1);
1692      assert_eq!(children[0].get_name(), "tail");
1693    }
1694
1695    // Case 4: default (`local_replace: false`) detaches following siblings during closure
1696    {
1697      let mut document = Document::new();
1698      let xml = document.get_document_mut();
1699      let mut root = Node::new("root", None, xml).unwrap();
1700      xml.set_root_element(&root);
1701      let mut head = Node::new("head", None, xml).unwrap();
1702      let mut old = Node::new("old", None, xml).unwrap();
1703      let mut tail = Node::new("tail", None, xml).unwrap();
1704      root.add_child(&mut head).unwrap();
1705      root.add_child(&mut old).unwrap();
1706      root.add_child(&mut tail).unwrap();
1707
1708      let rule = Rewrite::new("text", RewriteOptions::default());
1709      let clause = RewriteClause::new_compiled(
1710        RewriteOperator::Replace,
1711        RewritePattern::Closure(Rc::new(|doc, _replaced| {
1712          // Following sibling `<tail/>` must be detached while closure runs.
1713          assert!(doc.findnodes("//tail", None).is_empty());
1714          assert_eq!(
1715            doc.get_node().get_last_child().map(|n| n.get_name()),
1716            Some("head".to_string())
1717          );
1718          Ok(())
1719        })),
1720      );
1721      rule
1722        .apply_clause(&mut document, &old, 1, VecDeque::from([&clause]))
1723        .unwrap();
1724      let names: Vec<String> = root
1725        .get_child_nodes()
1726        .into_iter()
1727        .map(|n| n.get_name())
1728        .collect();
1729      assert_eq!(names, vec!["head", "tail"]);
1730    }
1731  }
1732}