Skip to main content

latexml_core/common/
locator.rs

1use std::{fmt, fmt::Write as _};
2
3use crate::{
4  common::{
5    arena::{self, SymStr},
6    object::Object,
7  },
8  util::pathname,
9};
10
11// TODO: This will require a large refactor, but
12// switching the source from an owned String to a &str reference
13// could provide a noticeable performance (and memory allocation) boost
14// (and especially if we also start adding locators to tokens)
15// my current thoughts are that we can have the core/gullet own the sources of all mouths
16// so that we can borrow them with the lifetime of the main convert_document loop...
17// that's harder than it sounds, I've already tried unsuccessfully with the Token contents,
18// but the mouth sources should be easier to manage.
19// definitely something that can be tried after test milestone is achieved.
20
21#[derive(Copy, Clone, PartialEq, Eq)]
22pub struct Locator {
23  pub source:      SymStr,
24  pub from_line:   u32,
25  pub to_line:     u32,
26  pub from_column: u32,
27  pub to_column:   u32,
28}
29
30impl Default for Locator {
31  fn default() -> Self {
32    Locator {
33      source:      arena::pin(file!()),
34      from_line:   line!(),
35      to_line:     line!(),
36      from_column: column!(),
37      to_column:   column!(),
38    }
39  }
40}
41
42// elide Locator debugging until we get to implementing them faithfully
43impl fmt::Debug for Locator {
44  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[...]") }
45}
46
47impl fmt::Display for Locator {
48  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49    write!(f, "{}", self.get_short_source(""))?;
50    if self.from_line > 0 {
51      write!(f, "; line {}", self.from_line)?;
52      if self.from_column > 0 {
53        write!(f, " col {}", self.from_column)?;
54      }
55    }
56    if self.to_line > 0 {
57      write!(f, " - line {}", self.to_line)?;
58      if self.to_column > 0 {
59        write!(f, " col {}", self.to_column)?;
60      }
61    }
62    Ok(())
63  }
64}
65
66impl Locator {
67  pub fn new<S: AsRef<str>>(
68    source: S,
69    from_line: u32,
70    from_column: u32,
71    to_line: u32,
72    to_column: u32,
73  ) -> Self {
74    Locator {
75      source: arena::pin(source.as_ref()),
76      from_line,
77      to_line,
78      from_column,
79      to_column,
80    }
81  }
82
83  /// [`Locator::new`] with an already-interned source. `Locator::new` re-pins
84  /// the source string (an interner hash probe over the whole path) on every
85  /// call, which is real cost on paths that build locators per token / per
86  /// conditional — a `Mouth` pins its source ONCE at construction and builds
87  /// locators from the cached symbol. Same parameter order as `new`.
88  pub fn from_sym(
89    source: SymStr,
90    from_line: u32,
91    from_column: u32,
92    to_line: u32,
93    to_column: u32,
94  ) -> Self {
95    Locator {
96      source,
97      from_line,
98      to_line,
99      from_column,
100      to_column,
101    }
102  }
103
104  /// creates a new locator range from a given start and end
105  pub fn new_range(from: Locator, to: Locator) -> Option<Locator> {
106    // make sure that either parameters are defined
107    // bail if we have different sources
108    if from.source != to.source {
109      return None;
110    }
111    // the end coordinates depend on
112    let (to_line, to_column) = if to.is_range() {
113      (to.to_line, to.to_column)
114    } else {
115      (to.from_line, to.from_column)
116    };
117    Some(Locator {
118      source: from.source,
119      from_line: from.from_line,
120      from_column: from.from_column,
121      to_line,
122      to_column,
123    })
124  }
125
126  pub fn is_range(&self) -> bool { self.to_line > 0 || self.to_column > 0 }
127
128  pub fn get_short_source(&self, string_source: &str) -> String {
129    arena::with(self.source, |source| {
130      if source.is_empty() {
131        if string_source.is_empty() {
132          "String".to_string()
133        } else {
134          string_source.to_string()
135        }
136      } else {
137        // Perl Locator.pm:55-60: a protocol is more than one character (`index($source, ':') > 1`), so a Windows drive
138        // (`C:/…`) is a path, as is the verbatim prefix std's canonicalize gives (`\\?\C:\…`, `//?/C:/…`); either way
139        // the file is named with its extension, "$base.$ext" (#794; `README.` for an extension-less one, as Perl).
140        let path = pathname::strip_windows_verbatim_prefix(source);
141        if path.find(':').is_some_and(|at| at > 1) {
142          let (base, ext) = pathname::url_split(path);
143          s!("{base}.{ext}")
144        } else {
145          let (_path, base, ext) = pathname::split(path);
146          s!("{base}.{ext}")
147        }
148      }
149    })
150  }
151  pub fn get_source(&self) -> SymStr { self.source }
152
153  pub fn get_from_locator(&self) -> Locator {
154    Locator {
155      source: self.source,
156      from_line: self.from_line,
157      from_column: self.from_column,
158      ..Locator::default()
159    }
160  }
161
162  pub fn get_to_locator(&self) -> Locator {
163    Locator {
164      source: self.source,
165      from_line: self.to_line,
166      from_column: self.to_column,
167      ..Locator::default()
168    }
169  }
170}
171impl Object for Locator {
172  fn stringify(&self) -> String {
173    let mut loc = arena::to_string(self.source);
174    if loc.is_empty() {
175      loc = "Anonymous String".to_string()
176    };
177    let range_from = if self.is_range() { " from" } else { "" };
178    if self.from_line > 0 {
179      write!(loc, ";{} line {}", range_from, self.from_line).ok();
180      if self.from_column > 0 {
181        write!(loc, " col {}", self.from_column).ok();
182      }
183    }
184    if self.to_line > 0 {
185      write!(loc, " to line {}", self.to_line).ok();
186      if self.to_column > 0 {
187        write!(loc, " col {}", self.to_column).ok();
188      }
189    }
190    loc
191  }
192
193  /// getting the locator of a locator should return itself
194  fn get_locator(&self) -> Option<Locator> { Some(*self) }
195}
196
197impl Locator {
198  pub fn to_attribute(&self) -> String {
199    let mut loc = self.get_short_source("anonymous_string") + "#text";
200    if self.is_range() {
201      loc.push_str("range(from='");
202      // if self.from_line > 0 {
203      loc.push_str(&self.from_line.to_string());
204      // }
205      // if self.from_column > 0 {
206      loc.push(';');
207      loc.push_str(&self.from_column.to_string());
208      // }
209      loc.push_str(",to='");
210      // if self.to_line > 0 {
211      loc.push_str(&self.to_line.to_string());
212      // }
213      // if self.to_column > 0 {
214      loc.push(';');
215      loc.push_str(&self.to_column.to_string());
216    } else {
217      loc.push_str("point('");
218      // if self.from_line > 0 {
219      loc.push_str(&self.from_line.to_string());
220      // }
221      // if self.from_column > 0 {
222      loc.push(';');
223      loc.push_str(&self.from_column.to_string());
224    }
225    // }
226    loc.push_str(")'");
227    loc
228  }
229
230  /// Serialise as a compact, web-facing `data-sourcepos` value:
231  /// `tag:line:col-tag:line:col` for a range, `tag:line:col` for a point.
232  ///
233  /// This is the source-map feature's serialiser (issues #47/#92) — the
234  /// brief, sibling-aligned form documented in `docs/performance/SOURCE_PROVENANCE.md`
235  /// §0/§0.1, deliberately *not* the XPointer `to_attribute()` above
236  /// (which has zero web-platform support and is latent in the port).
237  ///
238  /// `tag` is the source's index in the document-level `sources` table
239  /// (Source-Map-v3 style) — never an inlined path, so the markup stays
240  /// tiny and is anonymisable. The file is first-class in *each* endpoint;
241  /// a `Locator` currently carries a single `source` (so both endpoints
242  /// share `tag`), but the endpoint-complete form future-proofs a
243  /// per-endpoint-source `Locator`.
244  pub fn to_sourcepos(&self, tag: u32) -> String {
245    if self.is_range() {
246      format!(
247        "{tag}:{}:{}-{tag}:{}:{}",
248        self.from_line, self.from_column, self.to_line, self.to_column
249      )
250    } else {
251      format!("{tag}:{}:{}", self.from_line, self.from_column)
252    }
253  }
254}
255
256#[cfg(test)]
257mod tests {
258  use super::*;
259
260  #[test]
261  fn new_builds_from_parts() {
262    let l = Locator::new("source.tex", 1, 2, 3, 4);
263    assert_eq!(l.from_line, 1);
264    assert_eq!(l.from_column, 2);
265    assert_eq!(l.to_line, 3);
266    assert_eq!(l.to_column, 4);
267  }
268
269  #[test]
270  fn is_range_false_for_point() {
271    // Point locator: to_line=0 AND to_column=0.
272    let l = Locator::new("source", 1, 1, 0, 0);
273    assert!(!l.is_range());
274  }
275
276  #[test]
277  fn is_range_true_when_any_to_set() {
278    let with_to_line = Locator::new("source", 1, 1, 5, 0);
279    let with_to_col = Locator::new("source", 1, 1, 0, 5);
280    assert!(with_to_line.is_range());
281    assert!(with_to_col.is_range());
282  }
283
284  #[test]
285  fn new_range_requires_same_source() {
286    let a = Locator::new("a.tex", 1, 1, 0, 0);
287    let b = Locator::new("b.tex", 5, 5, 0, 0);
288    assert!(
289      Locator::new_range(a, b).is_none(),
290      "different sources must return None"
291    );
292  }
293
294  #[test]
295  fn new_range_takes_from_and_to() {
296    let a = Locator::new("same.tex", 1, 2, 0, 0);
297    let b = Locator::new("same.tex", 5, 6, 0, 0);
298    let r = Locator::new_range(a, b).unwrap();
299    assert_eq!(r.from_line, 1);
300    assert_eq!(r.from_column, 2);
301    // When `to` is a point (not a range), its from_line/col are used
302    // as the to_line/col.
303    assert_eq!(r.to_line, 5);
304    assert_eq!(r.to_column, 6);
305  }
306
307  #[test]
308  fn new_range_propagates_to_range() {
309    // When `to` is itself a range, use its to_line/col (not its from_*)
310    let a = Locator::new("same.tex", 1, 1, 0, 0);
311    let b = Locator::new("same.tex", 5, 5, 10, 20);
312    let r = Locator::new_range(a, b).unwrap();
313    assert_eq!(r.from_line, 1);
314    assert_eq!(r.to_line, 10);
315    assert_eq!(r.to_column, 20);
316  }
317
318  #[test]
319  fn display_includes_source_and_line() {
320    let l = Locator::new("paper.tex", 42, 10, 0, 0);
321    let s = format!("{l}");
322    assert!(s.contains("paper"), "got {s:?}");
323    assert!(s.contains("line 42"), "got {s:?}");
324  }
325
326  /// #794: the log locator names the file with its extension, as Perl's getShortSource
327  /// (Locator.pm L51-60) does, so a problem matcher can resolve it.
328  #[test]
329  fn display_names_the_file_with_its_extension() {
330    let l = Locator::new("/work/dir/t.tex", 10, 21, 10, 21);
331    assert_eq!(format!("{l}"), "t.tex; line 10 col 21 - line 10 col 21");
332    assert_eq!(
333      format!("{}", Locator::new("dir/refs.bib", 9, 0, 0, 0)),
334      "refs.bib; line 9"
335    );
336    assert_eq!(
337      format!("{}", Locator::new("dir/README", 1, 2, 0, 0)),
338      "README.; line 1 col 2"
339    );
340  }
341
342  #[test]
343  fn stringify_empty_source_is_anonymous_string() {
344    let l = Locator::new("", 1, 1, 0, 0);
345    let s = l.stringify();
346    assert!(s.contains("Anonymous String"), "got {s:?}");
347  }
348
349  /// Perl Locator.pm:55-60: a drive letter is no protocol, so a Windows path shortens to its file name with its extension
350  /// like any path (#794), with or without the verbatim prefix.
351  #[test]
352  fn a_windows_path_is_no_url() {
353    for (source, name) in [
354      ("C:/Users/x/t.tex", "t.tex"),
355      ("//?/C:/Users/x/t.tex", "t.tex"),
356      (
357        "c:/texlive/2026/texmf-dist/tex/latex/base/latex.ltx",
358        "latex.ltx",
359      ),
360    ] {
361      let short = Locator::new(source, 1, 1, 0, 0).get_short_source("");
362      assert_eq!(short, name, "{source}");
363    }
364  }
365
366  #[test]
367  fn get_short_source_fallback_when_empty() {
368    let l = Locator::new("", 0, 0, 0, 0);
369    assert_eq!(l.get_short_source(""), "String");
370    assert_eq!(l.get_short_source("inline"), "inline");
371  }
372
373  #[test]
374  fn get_from_and_to_locators_preserve_source() {
375    let l = Locator::new("paper.tex", 1, 2, 3, 4);
376    let from = l.get_from_locator();
377    let to = l.get_to_locator();
378    assert_eq!(from.source, l.source);
379    assert_eq!(to.source, l.source);
380    // from_locator captures from_*, to_locator captures to_*.
381    assert_eq!(from.from_line, 1);
382    assert_eq!(from.from_column, 2);
383    assert_eq!(to.from_line, 3);
384    assert_eq!(to.from_column, 4);
385  }
386
387  #[test]
388  fn object_get_locator_returns_self() {
389    let l = Locator::new("paper.tex", 1, 2, 3, 4);
390    let got = l.get_locator();
391    assert_eq!(got, Some(l));
392  }
393
394  #[test]
395  fn to_sourcepos_point() {
396    // Point locator (to_line==0 && to_column==0): no `-` separator.
397    let l = Locator::new("paper.tex", 12, 1, 0, 0);
398    assert_eq!(l.to_sourcepos(0), "0:12:1");
399  }
400
401  #[test]
402  fn to_sourcepos_range() {
403    let l = Locator::new("paper.tex", 12, 1, 12, 240);
404    assert_eq!(l.to_sourcepos(0), "0:12:1-0:12:240");
405  }
406
407  #[test]
408  fn to_sourcepos_tag_is_per_endpoint() {
409    // The integer file tag is first-class in *each* endpoint.
410    let l = Locator::new("paper.tex", 3, 5, 7, 9);
411    assert_eq!(l.to_sourcepos(2), "2:3:5-2:7:9");
412  }
413}