Skip to main content

latexml_core/sxml/
fragment_index.rs

1//! Document-global facts that must survive a spill.
2//!
3//! When a subtree is spilled its DOM nodes are freed, so every registry that
4//! held a handle into it (`Document::idstore`'s `Node`s, `node_boxes`' raw
5//! pointers) must be purged — the historical finalize-SIGSEGV class. What the
6//! later phases still need from spilled content is retained HERE, as plain
7//! strings:
8//!
9//! * which segment holds a spilled `xml:id` — for `id:`-scoped rewrites, math
10//!   `XMRef` existence checks, and global id-collision dedup;
11//! * `label → id` — for `label:`-scoped rewrites (built eagerly by
12//!   `Document::load_labels_for_rewrite` today);
13//! * RDFa prefix declarations seen in spilled content — `set_rdfa_prefixes`
14//!   scans the whole DOM in eager mode, so spilled fragments must contribute
15//!   at spill time.
16//!
17//! The index is append-only during pass 1 and read-only afterwards. It can be
18//! saved beside the segments for diagnostics ([`FragmentIndex::save`] /
19//! [`FragmentIndex::load`]) in a dependency-free line format.
20
21use std::{fmt::Write as _, fs, path::Path};
22
23use rustc_hash::FxHashMap;
24
25use super::SegmentId;
26use crate::common::error::{Error, ErrorCategory, ErrorTarget, Result};
27
28/// The string-only registry of what spilled content still owes the rest of the
29/// conversion.
30#[derive(Debug, Default)]
31pub struct FragmentIndex {
32  ids:           FxHashMap<String, SegmentId>,
33  labels:        FxHashMap<String, String>,
34  rdfa_prefixes: FxHashMap<String, String>,
35}
36
37impl FragmentIndex {
38  /// A spilled node's `xml:id`, and the segment now holding it.
39  pub fn record_id(&mut self, id: &str, segment: SegmentId) {
40    self.ids.insert(id.to_string(), segment);
41  }
42
43  /// A `label → xml:id` association from spilled content.
44  pub fn record_label(&mut self, label: &str, id: &str) {
45    self.labels.insert(label.to_string(), id.to_string());
46  }
47
48  /// An RDFa prefix declaration (`prefix → uri`) seen in spilled content.
49  pub fn record_rdfa_prefix(&mut self, prefix: &str, uri: &str) {
50    self
51      .rdfa_prefixes
52      .insert(prefix.to_string(), uri.to_string());
53  }
54
55  /// Which segment holds `id`, if it was spilled.
56  pub fn id_segment(&self, id: &str) -> Option<SegmentId> { self.ids.get(id).copied() }
57
58  /// Is `id` claimed by any spilled fragment? (The global half of id-collision
59  /// dedup; the live spine's half stays in `Document::idstore`.)
60  pub fn contains_id(&self, id: &str) -> bool { self.ids.contains_key(id) }
61
62  /// The `xml:id` a spilled `label` resolves to, if any.
63  pub fn label_id(&self, label: &str) -> Option<&str> { self.labels.get(label).map(String::as_str) }
64
65  /// All spilled `label → id` associations (with the spine's, the shared map
66  /// every fragment and the spine consult on a local miss —
67  /// `Document::rewrite_labels_shared` — so a `label:`-scoped rule resolves no
68  /// matter which fragment holds the label).
69  pub fn labels(&self) -> impl Iterator<Item = (&str, &str)> {
70    self.labels.iter().map(|(l, i)| (l.as_str(), i.as_str()))
71  }
72
73  /// Registry sizes `(ids, labels, rdfa)` — pass-1 telemetry.
74  pub fn sizes(&self) -> (usize, usize, usize) {
75    (self.ids.len(), self.labels.len(), self.rdfa_prefixes.len())
76  }
77
78  /// All RDFa prefix declarations contributed by spilled content.
79  pub fn rdfa_prefixes(&self) -> impl Iterator<Item = (&str, &str)> {
80    self
81      .rdfa_prefixes
82      .iter()
83      .map(|(p, u)| (p.as_str(), u.as_str()))
84  }
85
86  /// Number of spilled ids recorded.
87  pub fn id_count(&self) -> usize { self.ids.len() }
88
89  /// Persist beside the segments (diagnostics / crash inspection). Line
90  /// format, one record per line: `kind\tkey\tvalue`, keys percent-escaped
91  /// for the three bytes that would break the framing (`%`, tab, newline).
92  /// The records of each kind are in key order, so the file is a function of the index's content and not of its hash
93  /// tables' layout (det354 C5).
94  pub fn save(&self, path: &Path) -> Result<()> {
95    fn sorted<V>(map: &FxHashMap<String, V>) -> Vec<(&String, &V)> {
96      let mut rows: Vec<(&String, &V)> = map.iter().collect();
97      rows.sort_unstable_by(|a, b| a.0.cmp(b.0));
98      rows
99    }
100    let mut out = String::new();
101    for (id, seg) in sorted(&self.ids) {
102      let _ = writeln!(out, "id\t{}\t{}", escape(id), seg.0);
103    }
104    for (label, id) in sorted(&self.labels) {
105      let _ = writeln!(out, "label\t{}\t{}", escape(label), escape(id));
106    }
107    for (prefix, uri) in sorted(&self.rdfa_prefixes) {
108      let _ = writeln!(out, "rdfa\t{}\t{}", escape(prefix), escape(uri));
109    }
110    fs::write(path, out).map_err(|e| index_error(format!("write {}: {e}", path.display())))
111  }
112
113  /// Load a saved index. Unknown record kinds are an error, not a skip — a
114  /// partially understood index would silently drop facts (fail toward
115  /// flagging).
116  pub fn load(path: &Path) -> Result<Self> {
117    let text =
118      fs::read_to_string(path).map_err(|e| index_error(format!("read {}: {e}", path.display())))?;
119    let mut index = FragmentIndex::default();
120    for (n, line) in text.lines().enumerate() {
121      if line.is_empty() {
122        continue;
123      }
124      let mut parts = line.splitn(3, '\t');
125      let (kind, key, value) = match (parts.next(), parts.next(), parts.next()) {
126        (Some(k), Some(key), Some(v)) => (k, unescape(key), unescape(v)),
127        _ => {
128          return Err(index_error(format!(
129            "malformed line {} in {}",
130            n + 1,
131            path.display()
132          )));
133        },
134      };
135      match kind {
136        "id" => {
137          let seg: u32 = value
138            .parse()
139            .map_err(|_| index_error(format!("bad segment number {value:?} at line {}", n + 1)))?;
140          index.ids.insert(key, SegmentId(seg));
141        },
142        "label" => {
143          index.labels.insert(key, value);
144        },
145        "rdfa" => {
146          index.rdfa_prefixes.insert(key, value);
147        },
148        other => {
149          return Err(index_error(format!(
150            "unknown record kind {other:?} at line {} in {}",
151            n + 1,
152            path.display()
153          )));
154        },
155      }
156    }
157    Ok(index)
158  }
159}
160
161fn escape(s: &str) -> String {
162  // Only the three bytes that would break the line framing.
163  s.replace('%', "%25")
164    .replace('\t', "%09")
165    .replace('\n', "%0A")
166}
167
168fn unescape(s: &str) -> String {
169  s.replace("%0A", "\n")
170    .replace("%09", "\t")
171    .replace("%25", "%")
172}
173
174fn index_error(details: String) -> Error {
175  Error::from(crate::common::error::ErrorData {
176    target:   ErrorTarget::Internal,
177    category: ErrorCategory::Unexpected,
178    message:  format!("fragment-index: {details}"),
179  })
180}
181
182#[cfg(test)]
183mod tests {
184  use super::*;
185
186  #[test]
187  fn records_and_queries() {
188    let mut index = FragmentIndex::default();
189    index.record_id("S1.p3", SegmentId(0));
190    index.record_id("S2.p1", SegmentId(4));
191    index.record_label("LABEL:intro", "S1.p3");
192    index.record_rdfa_prefix("dct", "http://purl.org/dc/terms/");
193
194    assert_eq!(index.id_segment("S1.p3"), Some(SegmentId(0)));
195    assert_eq!(index.id_segment("S2.p1"), Some(SegmentId(4)));
196    assert_eq!(index.id_segment("missing"), None);
197    assert!(index.contains_id("S1.p3"));
198    assert!(!index.contains_id("LABEL:intro"));
199    assert_eq!(index.label_id("LABEL:intro"), Some("S1.p3"));
200    assert_eq!(index.id_count(), 2);
201    let prefixes: Vec<_> = index.rdfa_prefixes().collect();
202    assert_eq!(prefixes, vec![("dct", "http://purl.org/dc/terms/")]);
203  }
204
205  #[test]
206  fn save_load_round_trip_with_awkward_keys() {
207    let mut index = FragmentIndex::default();
208    // Keys exercising the escaping: tab, newline, percent, non-ASCII.
209    index.record_id("id\twith\ttabs", SegmentId(1));
210    index.record_id("id\nnewline", SegmentId(2));
211    index.record_label("LABEL:100%\u{6570}", "S1.E5");
212    index.record_rdfa_prefix("foaf", "http://xmlns.com/foaf/0.1/");
213
214    let tmp = std::env::temp_dir().join(format!("lxsxml-index-{}.tsv", std::process::id()));
215    index.save(&tmp).expect("save");
216    let loaded = FragmentIndex::load(&tmp).expect("load");
217    let _ = fs::remove_file(&tmp);
218
219    assert_eq!(loaded.id_segment("id\twith\ttabs"), Some(SegmentId(1)));
220    assert_eq!(loaded.id_segment("id\nnewline"), Some(SegmentId(2)));
221    assert_eq!(loaded.label_id("LABEL:100%\u{6570}"), Some("S1.E5"));
222    assert_eq!(loaded.rdfa_prefixes().collect::<Vec<_>>(), vec![(
223      "foaf",
224      "http://xmlns.com/foaf/0.1/"
225    )]);
226  }
227
228  /// The saved records of each kind are in key order, whatever order they were recorded in (det354 C5).
229  #[test]
230  fn save_lists_each_kind_in_key_order() {
231    let save = |ids: &[&str], tag: &str| {
232      let mut index = FragmentIndex::default();
233      for (n, id) in ids.iter().enumerate() {
234        index.record_id(id, SegmentId(n as u32));
235        index.record_label(&format!("LABEL:{id}"), id);
236        index.record_rdfa_prefix(id, "u");
237      }
238      let tmp =
239        std::env::temp_dir().join(format!("lxsxml-sorted-{tag}-{}.tsv", std::process::id()));
240      index.save(&tmp).expect("save");
241      let text = fs::read_to_string(&tmp).expect("read");
242      let _ = fs::remove_file(&tmp);
243      text
244        .lines()
245        .map(|line| line.splitn(3, '\t').take(2).collect::<Vec<_>>().join(" "))
246        .collect::<Vec<_>>()
247    };
248    let expected = [
249      "id S1.p3",
250      "id S2.p1",
251      "id S9",
252      "label LABEL:S1.p3",
253      "label LABEL:S2.p1",
254      "label LABEL:S9",
255      "rdfa S1.p3",
256      "rdfa S2.p1",
257      "rdfa S9",
258    ];
259    assert_eq!(save(&["S9", "S1.p3", "S2.p1"], "a"), expected);
260    assert_eq!(save(&["S2.p1", "S9", "S1.p3"], "b"), expected);
261  }
262
263  #[test]
264  fn load_rejects_unknown_kinds_instead_of_skipping() {
265    let tmp = std::env::temp_dir().join(format!("lxsxml-badidx-{}.tsv", std::process::id()));
266    fs::write(&tmp, "mystery\tkey\tvalue\n").unwrap();
267    let result = FragmentIndex::load(&tmp);
268    let _ = fs::remove_file(&tmp);
269    assert!(result.is_err(), "unknown record kinds must fail loudly");
270  }
271
272  /// `xml:id` must be readable at spill-indexing time however the node was
273  /// produced. MECHANISM CORRECTION (2026-08-04, probed against libxml
274  /// 0.3.21): BOTH construction paths store the attribute NAMESPACED —
275  /// `set_attribute("xml:id", …)` resolves the predefined `xml` prefix via
276  /// `xmlSetProp`, exactly like parsing does — so this test's two branches
277  /// both exercise `node_xml_id_any_form`'s `get_attribute_ns` arm, and its
278  /// bare-read fallback is defensive dead code. (The comment that previously
279  /// claimed constructed nodes carry a plain-named attribute does not
280  /// reproduce; see `node_xml_id_any_form`'s doc.)
281  #[test]
282  fn xml_id_readable_in_both_attribute_forms() {
283    use libxml::{parser::Parser, tree::Node};
284
285    // Parsed: xml:id arrives namespaced.
286    let parsed = Parser::default()
287      .parse_string(r#"<r xmlns="urn:x"><s xml:id="parsed.id"/></r>"#)
288      .expect("parse");
289    let s_node = parsed
290      .get_root_element()
291      .and_then(|r| r.get_first_element_child())
292      .expect("child");
293    assert_eq!(
294      crate::document::Document::node_xml_id_any_form(&s_node).as_deref(),
295      Some("parsed.id"),
296      "namespaced form must read"
297    );
298
299    // Constructed: set_attribute ALSO stores the namespaced form.
300    let built = Parser::default().parse_string("<r/>").expect("parse shell");
301    let mut root = built.get_root_element().expect("root");
302    let mut child = Node::new("s", None, &built).expect("node");
303    child.set_attribute("xml:id", "built.id").expect("attr");
304    root.add_child(&mut child).expect("attach");
305    assert_eq!(
306      child.get_attribute_ns("id", "http://www.w3.org/XML/1998/namespace"),
307      Some("built.id".to_string()),
308      "set_attribute must namespace xml:id (probed libxml 0.3.21 behavior)"
309    );
310    assert_eq!(
311      crate::document::Document::node_xml_id_any_form(&child).as_deref(),
312      Some("built.id"),
313      "constructed form must read through the helper too"
314    );
315  }
316}