steid

@jamesgill /

steid/src/infrastructure/highlight.rs
Rust37.9 KBCode·Blame·History·Raw
1//! Syntax highlighting for the blob view.
2//!
3//! Classes, never colours. [`syntect`] can emit inline `style` attributes, and that
4//! would hardcode one palette into the markup — the theme would then follow neither a
5//! palette change nor the colour scheme, which is exactly what `styles.css` forbids
6//! everywhere else. So the output is `hl-`-prefixed classes and the colours live in
7//! `styles.css` beside every other token.
8//!
9//! **One HTML fragment per source line**, because the blob view is a table with a line
10//! number in one cell and the code in the other. `syntect`'s own
11//! `ClassedHTMLGenerator` produces a single blob whose `<span>`s cross line boundaries,
12//! which cannot be split across table rows — so this drives the parser a line at a time
13//! and closes every open span at the end of each line, reopening it at the start of the
14//! next. The DOM shape is unchanged: what was a text node is now the same text wrapped
15//! in spans.
16//!
17//! **Highlighting never turns a viewable file into an error.** Every failure path —
18//! no syntax for the file, a regex that gives up, a file past the cap — falls back to
19//! the plain text the page rendered before.
20
21use std::sync::{Arc, Mutex, OnceLock};
22
23use lru::LruCache;
24use sha2::{Digest, Sha256};
25
26use crate::infrastructure::metrics::metrics;
27
28use syntect::{
29 html::{ClassStyle, line_tokens_to_classed_spans},
30 parsing::{ParseState, ScopeStack, SyntaxReference, SyntaxSet},
31 util::LinesWithEndings,
32};
33
34/// The class prefix, so a scope atom cannot collide with a Tailwind utility.
35const PREFIX: &str = "hl-";
36
37const CLASS_STYLE: ClassStyle = ClassStyle::SpacedPrefixed { prefix: PREFIX };
38
39/// Past this, a file is shown as plain text.
40///
41/// Highlighting is regex matching over every line, and the fancy-regex engine is pure
42/// Rust rather than fast C — a generated or vendored file can be megabytes of one long
43/// line, and the page should still arrive. Half a megabyte is well above anything
44/// written by hand and far below `MAX_BLOB_BYTES`.
45pub const MAX_BYTES: usize = 512 * 1024;
46
47/// The other half of the cap: many short lines cost per-line work, not per-byte work.
48pub const MAX_LINES: usize = 10_000;
49
50/// A file, ready for the blob view's table: one entry per line, in the same order as
51/// `text.lines()`.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Source {
54 pub lines: Vec<SourceLine>,
55 /// Whether highlighting was skipped because the file is past the caps. The page
56 /// says so, because otherwise a large Rust file silently looks like an
57 /// unsupported language.
58 pub too_large: bool,
59}
60
61/// One line of a file.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum SourceLine {
64 /// Text, to be escaped by the view like anything else.
65 Plain(String),
66 /// Markup this module wrote, to be emitted verbatim.
67 Classed(String),
68}
69
70/// Splits a file into lines, highlighted where the language is known.
71///
72/// Every fallback lands on [`SourceLine::Plain`]: past the caps, no syntax for the
73/// name, a parser that gave up. Highlighting can make a file prettier; it can never
74/// stop it being readable.
75pub fn source_lines(file_name: &str, text: &str) -> Source {
76 let too_large = text.len() > MAX_BYTES || text.lines().count() > MAX_LINES;
77
78 let classed = (!too_large)
79 .then(|| {
80 let syntaxes = syntaxes();
81 let syntax = syntax_for(syntaxes, file_name, text)?;
82 classed_lines(syntaxes, syntax, text)
83 })
84 .flatten()
85 // A fragment per line is the contract the table relies on; anything else is a
86 // bug in this module, and plain text is the safe reading of it.
87 .filter(|lines| lines.len() == text.lines().count());
88
89 let lines = match classed {
90 Some(classed) => text
91 .lines()
92 .zip(classed)
93 .map(|(line, html)| match line.is_empty() {
94 // An empty cell has no height, so a blank line would close the gap it
95 // is there to make. The plain path has always spent a space on this.
96 true => SourceLine::Plain(" ".to_owned()),
97 false => SourceLine::Classed(html),
98 })
99 .collect(),
100 None => text
101 .lines()
102 .map(|line| match line.is_empty() {
103 true => SourceLine::Plain(" ".to_owned()),
104 false => SourceLine::Plain(line.to_owned()),
105 })
106 .collect(),
107 };
108
109 Source { lines, too_large }
110}
111
112/// The language a file would be highlighted as, by name — `"Rust"`, `"TOML"`.
113///
114/// `None` when no grammar claims the file, and also when the file is past the caps: the
115/// blob header says what the *view* is doing, and naming a language beside a body shown
116/// as plain text would contradict the line under it that says highlighting was skipped.
117///
118/// Asked separately from [`source_lines`] rather than carried back on [`Source`], because
119/// the header is rendered by a different component from the body and threading the value
120/// between them would mean the blob page computing the whole file before drawing its
121/// frame. It costs a second `syntax_for` — an extension lookup against a set that is
122/// already loaded, with no parsing behind it.
123pub fn language_of(file_name: &str, text: &str) -> Option<&'static str> {
124 if text.len() > MAX_BYTES || text.lines().count() > MAX_LINES {
125 return None;
126 }
127
128 syntax_for(syntaxes(), file_name, text).map(|syntax| syntax.name.as_str())
129}
130
131/// The syntax set, loaded once.
132///
133/// `two_face` rather than `SyntaxSet::load_defaults_newlines`: syntect's own defaults
134/// are Sublime's, which have no TOML, no Dockerfile and no TypeScript — the first two
135/// of which are in this repository. `two_face` is the same set plus the grammars `bat`
136/// curates, so the gap closes without teaching this module anything about individual
137/// languages. Its `syntect-fancy` feature pins it to the same pure-Rust regex engine,
138/// so no `onig` — and therefore no C — comes in behind it.
139///
140/// Loading is a few megabytes of deserialization, so it happens on the first blob
141/// viewed and never again. `_newlines` is the variant whose rules expect a trailing
142/// newline on each line, which is what [`LinesWithEndings`] hands it.
143fn syntaxes() -> &'static SyntaxSet {
144 static SYNTAXES: OnceLock<SyntaxSet> = OnceLock::new();
145 SYNTAXES.get_or_init(two_face::syntax::extra_newlines)
146}
147
148/// Extensions no grammar in the set claims, and the grammar to read them with anyway.
149///
150/// `two-face`'s JavaScript grammar registers `js` and `htc` and nothing else, so `.jsx`
151/// rendered as plain text while `.tsx` was highlighted, TypeScriptReact being its own
152/// grammar. JSX is JavaScript with element literals in it and the JavaScript grammar
153/// reads it well enough.
154///
155/// One entry, deliberately: every alias is a claim that two languages are close enough
156/// to read as one, and a wrong one is worse than no colour.
157const ALIASES: &[(&str, &str)] = &[("jsx", "js")];
158
159/// The language, from the file name and then the first line.
160///
161/// This is `SyntaxSet::find_syntax_for_file` without the filesystem: that method opens
162/// the path to read a shebang, and here the contents are already in memory. The whole
163/// name is tried as an extension first because that is how syntect registers names like
164/// `Makefile`; plain text is treated as no syntax at all, since wrapping every line in
165/// a span that carries no colour is pure markup for nothing.
166fn syntax_for<'a>(
167 syntaxes: &'a SyntaxSet,
168 file_name: &str,
169 text: &str,
170) -> Option<&'a SyntaxReference> {
171 let extension = file_name.rsplit_once('.').map(|(_, ext)| ext);
172
173 // After the set's own answer, never before it: an alias is what to do when no
174 // grammar claims the extension, not a way to overrule one that does.
175 let aliased = extension.and_then(|ext| {
176 ALIASES
177 .iter()
178 .find(|(from, _)| *from == ext)
179 .map(|(_, to)| *to)
180 });
181
182 let syntax = syntaxes
183 .find_syntax_by_extension(file_name)
184 .or_else(|| extension.and_then(|ext| syntaxes.find_syntax_by_extension(ext)))
185 .or_else(|| aliased.and_then(|to| syntaxes.find_syntax_by_extension(to)))
186 .or_else(|| syntaxes.find_syntax_by_first_line(text.lines().next().unwrap_or("")))?;
187
188 (syntax.name != syntaxes.find_syntax_plain_text().name).then_some(syntax)
189}
190
191/// One line of HTML per line of source, or `None` if the parser gave up.
192///
193/// The span stack is carried across lines — a block comment opens on one line and
194/// closes on another — but the *markup* is not: the scopes open at the end of a line
195/// are closed there and reopened on the next, so each fragment is balanced and can sit
196/// in its own table cell.
197fn classed_lines(
198 syntaxes: &SyntaxSet,
199 syntax: &SyntaxReference,
200 text: &str,
201) -> Option<Vec<String>> {
202 let mut state = ParseState::new(syntax);
203 let mut stack = ScopeStack::new();
204 let mut lines = Vec::new();
205
206 for line in LinesWithEndings::from(text) {
207 let ops = state.parse_line(line, syntaxes).ok()?;
208
209 let mut html = String::with_capacity(line.len());
210 for scope in &stack.scopes {
211 open(&mut html, &scope.build_string());
212 }
213
214 let (body, _) = line_tokens_to_classed_spans(line, &ops, CLASS_STYLE, &mut stack).ok()?;
215 // The line ending was handed to the parser because the `_newlines` syntaxes
216 // expect it, but it must not reach the cell: `white-space: pre` would render it
217 // as a second, empty line inside every row. It can be escaped anywhere in the
218 // fragment — inside a span, or after one closes — so it is dropped by character
219 // rather than trimmed off the end.
220 html.extend(body.chars().filter(|c| *c != '\n' && *c != '\r'));
221
222 // Whatever the line left open on the stack is open in the markup too, and is
223 // closed here so the fragment stands alone in its own table cell.
224 for _ in 0..stack.scopes.len() {
225 html.push_str("</span>");
226 }
227
228 lines.push(html);
229 }
230
231 Some(lines)
232}
233
234/// Opens one span for a scope, spelling its atoms the way syntect's own writer does.
235fn open(html: &mut String, scope: &str) {
236 html.push_str("<span class=\"");
237 for (index, atom) in scope.split('.').filter(|atom| !atom.is_empty()).enumerate() {
238 if index != 0 {
239 html.push(' ');
240 }
241 html.push_str(PREFIX);
242 html.push_str(atom);
243 }
244 html.push_str("\">");
245}
246
247/// Highlighted markup for a fenced code block, one fragment per line of `text`, or
248/// `None` when the fence should be rendered as plain text.
249///
250/// `None` is every fallback the blob view has — no grammar for the info string, a
251/// parser that gave up, a block past the caps — and it means the same thing here: the
252/// caller writes the source as text, exactly as it did before highlighting existed.
253///
254/// Unlike [`source_lines`] an empty line stays empty rather than becoming a space: a
255/// fence renders inside `<pre>`, where the newline itself makes the blank line, and a
256/// space there would be trailing whitespace a reader could select.
257pub fn fenced_lines(language: &str, text: &str) -> Option<Vec<String>> {
258 if text.len() > MAX_BYTES || text.lines().count() > MAX_LINES {
259 return None;
260 }
261
262 let syntaxes = syntaxes();
263 let syntax = syntax_for_token(syntaxes, language)?;
264
265 classed_lines(syntaxes, syntax, text)
266 // One fragment per line is the contract the caller joins on; anything else is
267 // a bug in this module, and plain text is the safe reading of it.
268 .filter(|lines| lines.len() == text.lines().count())
269}
270
271/// The grammar a fence's info string names, or `None` when nothing claims it.
272///
273/// An info string is a token rather than a file name — ` ```rust ` , not `main.rs` — so
274/// this is `find_syntax_by_token`, which tries extensions and then grammar names. The
275/// [`ALIASES`] table is consulted after it and never before, for the same reason
276/// [`syntax_for`] does: an alias says what to do when no grammar claims the token.
277fn syntax_for_token<'a>(syntaxes: &'a SyntaxSet, language: &str) -> Option<&'a SyntaxReference> {
278 let token = language.trim();
279
280 let syntax = syntaxes.find_syntax_by_token(token).or_else(|| {
281 ALIASES
282 .iter()
283 .find(|(from, _)| from.eq_ignore_ascii_case(token))
284 .and_then(|(_, to)| syntaxes.find_syntax_by_token(to))
285 })?;
286
287 (syntax.name != syntaxes.find_syntax_plain_text().name).then_some(syntax)
288}
289
290/// Highlighted markup for a standalone snippet, one fragment per line of `text`.
291///
292/// The same output [`source_lines`] builds its [`SourceLine::Classed`] entries from,
293/// without the plain-text fallback: `None` is every failure — past the caps, no grammar
294/// for the name, a parser that gave up — and it means the caller renders the snippet as
295/// text, exactly as it did before highlighting existed.
296///
297/// **Standalone is the whole point, and the whole limitation.** A diff hunk is a window
298/// into a file with no view of what came before it, so a multi-line string or block
299/// comment opened above the hunk is invisible here and the snippet is parsed as if the
300/// file started at the hunk's first line. That colours such a hunk wrong. The
301/// alternative is reading the whole blob on both sides of every changed file, which is
302/// two object reads per file to fix a case that is rare and cosmetic.
303pub fn snippet_lines(file_name: &str, text: &str) -> Option<Vec<String>> {
304 if text.len() > MAX_BYTES || text.lines().count() > MAX_LINES {
305 return None;
306 }
307
308 let syntaxes = syntaxes();
309 let syntax = syntax_for(syntaxes, file_name, text)?;
310
311 classed_lines(syntaxes, syntax, text)
312 // One fragment per line is the contract the caller aligns rows against; anything
313 // else is a bug in this module, and plain text is the safe reading of it.
314 .filter(|lines| lines.len() == text.lines().count())
315}
316
317// --- The cache --------------------------------------------------------------------
318
319/// The one highlight cache this process has.
320///
321/// Registered in app context at the composition root — `main` puts *this* `Arc` there,
322/// so `web::context::highlights` and this function hand out the same cache rather than
323/// two of them. It exists as a static as well as in app context for one caller:
324/// [`markdown`](crate::infrastructure::web::markdown) renders a README from a plain
325/// function with no `Cx` in reach, and threading a cache through `render`,
326/// `render_with_links` and every page that calls them would put a parameter on four
327/// call sites to say what one process-wide cache already says.
328pub fn cache() -> &'static Arc<HighlightCache> {
329 static CACHE: OnceLock<Arc<HighlightCache>> = OnceLock::new();
330 CACHE.get_or_init(|| Arc::new(HighlightCache::new()))
331}
332
333/// How much highlighted markup the process keeps before it starts evicting.
334///
335/// Bounded by **bytes rather than by entries**, because the entries are wildly uneven:
336/// a one-line `.gitignore` and a 113 KB source file are one entry each and three orders
337/// of magnitude apart, so an entry count would either hold almost nothing or promise an
338/// operator no bound at all. Sixty-four mebibytes is roughly a large repository's worth
339/// of the source files anyone actually opens — markup runs three to four times the size
340/// of the text it wraps — and is small enough to sit inside the footprint a personal
341/// instance already has, beside the syntax set's own few megabytes and `cat-file`'s
342/// mapped pack indexes.
343const MAX_CACHE_BYTES: usize = 64 * 1024 * 1024;
344
345/// A rough per-entry overhead, so a file of ten thousand one-character lines is charged
346/// for its `Vec` and its ten thousand `String` headers rather than for ten thousand
347/// bytes. Not exact — the point of the budget is that it is a bound, not an audit.
348const PER_LINE_OVERHEAD: usize = 32;
349
350/// What a cached highlight is keyed by.
351///
352/// `content` is whatever identifies the bytes: for a blob it is the object id, which
353/// git has already computed and which is exactly a hash of the contents; for a blame
354/// body or a fence it is [`content_digest`], because neither has an object id to hand —
355/// blame's text is reassembled from runs and a fence's is a slice of a README.
356///
357/// `syntax` is the file name or the fence's info string, because that is what chooses
358/// the grammar: the same bytes named `x.rs` and `x.txt` are two different answers.
359///
360/// `fenced` separates the two shapes stored under this key. Without it a README's fence
361/// and a blob with the same digest and token would collide, and one would be handed the
362/// other's variant.
363#[derive(Debug, Clone, PartialEq, Eq, Hash)]
364struct Key {
365 content: String,
366 syntax: String,
367 fenced: bool,
368}
369
370/// One cached answer, in whichever shape its caller asked for.
371#[derive(Debug, Clone)]
372enum Cached {
373 Source(Arc<Source>),
374 /// `None` inside the `Arc` is a fence with no grammar — worth caching, because
375 /// deciding it costs the same lookup every time and the answer never changes.
376 Fence(Arc<Option<Vec<String>>>),
377}
378
379impl Cached {
380 /// What this entry is charged against the budget.
381 fn weight(&self) -> usize {
382 match self {
383 Self::Source(source) => source
384 .lines
385 .iter()
386 .map(|line| match line {
387 SourceLine::Plain(text) | SourceLine::Classed(text) => {
388 text.len() + PER_LINE_OVERHEAD
389 }
390 })
391 .sum(),
392 Self::Fence(lines) => lines
393 .iter()
394 .flatten()
395 .map(|line| line.len() + PER_LINE_OVERHEAD)
396 .sum(),
397 }
398 }
399}
400
401/// Highlighting, remembered.
402///
403/// One per process, in app context — see `web::context::highlights`. Highlighting a
404/// 113 KB file is tens of milliseconds of regex over every line, and a reader scrolling
405/// a file, flipping to blame and back, or reloading after a push pays it again every
406/// time for bytes that have not changed. Keyed by content, so an entry is never stale:
407/// different bytes are a different key rather than an invalidation problem.
408///
409/// The `lru` crate rather than a hand-rolled list, because the recency half is the part
410/// that is fiddly to get right and the byte budget it does not do is a dozen lines on
411/// top: an unbounded [`LruCache`] plus a running total, popping the least-recent entry
412/// until the total fits.
413pub struct HighlightCache {
414 entries: Mutex<Entries>,
415}
416
417struct Entries {
418 cache: LruCache<Key, Cached>,
419 bytes: usize,
420}
421
422impl Default for HighlightCache {
423 fn default() -> Self {
424 Self::new()
425 }
426}
427
428impl HighlightCache {
429 pub fn new() -> Self {
430 Self {
431 entries: Mutex::new(Entries {
432 // Unbounded by count; [`MAX_CACHE_BYTES`] is the real bound and is
433 // enforced on insert.
434 cache: LruCache::unbounded(),
435 bytes: 0,
436 }),
437 }
438 }
439
440 /// A file's lines, highlighted once per distinct content.
441 ///
442 /// `content` identifies the bytes — a blob's object id, or [`content_digest`] when
443 /// there is no object id to hand. Handing the wrong one in would serve another
444 /// file's markup, so it must be derived from `text` and from nothing else.
445 pub fn source_lines(&self, content: &str, file_name: &str, text: &str) -> Arc<Source> {
446 let key = Key {
447 content: content.to_owned(),
448 syntax: file_name.to_owned(),
449 fenced: false,
450 };
451
452 if let Some(Cached::Source(source)) = self.get(&key) {
453 return source;
454 }
455
456 // Deliberately computed with the lock **not** held: highlighting is the slow
457 // thing here, and holding a mutex across it would serialise every blob view in
458 // the process. Two requests for the same uncached file therefore both compute
459 // it and the second insert replaces the first with an identical value, which
460 // costs one wasted parse and never a wrong answer.
461 let source = Arc::new(source_lines(file_name, text));
462 self.put(key, Cached::Source(source.clone()));
463 source
464 }
465
466 /// A fence's lines, highlighted once per distinct content and info string.
467 ///
468 /// `None` inside the `Arc` means the fence is rendered as plain text, exactly as
469 /// [`fenced_lines`] means it.
470 pub fn fenced_lines(&self, language: &str, text: &str) -> Arc<Option<Vec<String>>> {
471 let key = Key {
472 content: content_digest(text),
473 syntax: language.to_owned(),
474 fenced: true,
475 };
476
477 if let Some(Cached::Fence(lines)) = self.get(&key) {
478 return lines;
479 }
480
481 let lines = Arc::new(fenced_lines(language, text));
482 self.put(key, Cached::Fence(lines.clone()));
483 lines
484 }
485
486 fn get(&self, key: &Key) -> Option<Cached> {
487 // A poisoned lock means another thread panicked mid-insert. The cache holds
488 // nothing anyone needs, so the entry it was writing is the only casualty and
489 // reading on is better than propagating a panic into a page.
490 let mut entries = match self.entries.lock() {
491 Ok(entries) => entries,
492 Err(poisoned) => poisoned.into_inner(),
493 };
494
495 let found = entries.cache.get(key).cloned();
496
497 // Counted in the one place every lookup passes through, rather than at each
498 // caller. The hit rate is the whole question this cache exists to answer, and a
499 // second `source_lines` variant added later would otherwise be invisible in it.
500 match found.is_some() {
501 true => metrics().record_highlight_hit(),
502 false => metrics().record_highlight_miss(),
503 }
504
505 found
506 }
507
508 fn put(&self, key: Key, value: Cached) {
509 let weight = value.weight();
510
511 // A single entry larger than the whole budget would evict everything and then
512 // itself; it is simply not cached.
513 if weight > MAX_CACHE_BYTES {
514 return;
515 }
516
517 let mut entries = match self.entries.lock() {
518 Ok(entries) => entries,
519 Err(poisoned) => poisoned.into_inner(),
520 };
521
522 if let Some(replaced) = entries.cache.put(key, value) {
523 entries.bytes = entries.bytes.saturating_sub(replaced.weight());
524 }
525 entries.bytes += weight;
526
527 while entries.bytes > MAX_CACHE_BYTES {
528 match entries.cache.pop_lru() {
529 Some((_, evicted)) => {
530 entries.bytes = entries.bytes.saturating_sub(evicted.weight())
531 }
532 // Unreachable while the accounting is right, and a `break` rather than a
533 // panic if it ever is not: an over-counted cache is a cache that holds
534 // less than it could, not a page that fails.
535 None => break,
536 }
537 }
538 }
539
540 /// How many entries and how many accounted bytes the cache holds.
541 ///
542 /// Nothing on a *page* asks — `/metrics` does, for `steid_cache_bytes`, and so do
543 /// the tests below. Sampled rather than mirrored into a counter, so the number
544 /// cannot drift from the map it describes.
545 #[must_use]
546 pub fn stats(&self) -> (usize, usize) {
547 let entries = match self.entries.lock() {
548 Ok(entries) => entries,
549 Err(poisoned) => poisoned.into_inner(),
550 };
551
552 (entries.cache.len(), entries.bytes)
553 }
554}
555
556/// A cache key for text with no object id behind it.
557///
558/// SHA-256 because it is already a dependency and because the key must not collide:
559/// two different files sharing a key would serve one of them the other's markup, which
560/// is a correctness bug rather than a slow page. Hex, so the key is a plain `String`
561/// like an object id and the two read the same in a debugger.
562pub fn content_digest(text: &str) -> String {
563 let digest = Sha256::digest(text.as_bytes());
564
565 digest.iter().map(|byte| format!("{byte:02x}")).collect()
566}
567
568#[cfg(test)]
569mod tests {
570 use super::*;
571
572 fn classes(line: &SourceLine) -> String {
573 match line {
574 SourceLine::Classed(html) => html.clone(),
575 SourceLine::Plain(text) => text.clone(),
576 }
577 }
578
579 #[test]
580 fn rust_source_is_wrapped_in_prefixed_classes() {
581 let source = source_lines("main.rs", "fn main() {\n // hi\n}\n");
582
583 assert!(!source.too_large);
584 assert_eq!(source.lines.len(), 3);
585 assert!(matches!(source.lines[0], SourceLine::Classed(_)));
586
587 let first = classes(&source.lines[0]);
588 assert!(first.contains("class=\"hl-"), "{first}");
589 // `fn` is `storage.type.function.rust`, so every atom becomes its own class.
590 assert!(first.contains("hl-storage"), "{first}");
591 assert!(first.contains("hl-entity hl-name hl-function"), "{first}");
592 assert!(classes(&source.lines[1]).contains("hl-comment"));
593 }
594
595 #[test]
596 fn a_line_carries_no_line_ending_and_closes_every_span_it_opens() {
597 let source = source_lines("main.rs", "fn main() {\n let x = \"a\";\n}\n");
598
599 for line in &source.lines {
600 let html = classes(line);
601 assert!(!html.contains('\n'), "{html}");
602 assert_eq!(
603 html.matches("<span").count(),
604 html.matches("</span>").count(),
605 "{html}"
606 );
607 }
608 }
609
610 #[test]
611 fn the_source_is_escaped_rather_than_passed_through() {
612 let source = source_lines("main.rs", "// <script>alert(1)</script>\n");
613
614 let html = classes(&source.lines[0]);
615 assert!(!html.contains("<script"), "{html}");
616 assert!(html.contains("&lt;script"), "{html}");
617 }
618
619 #[test]
620 fn an_unknown_extension_stays_plain() {
621 let source = source_lines("notes.wibble", "hello\nworld\n");
622
623 assert_eq!(
624 source.lines,
625 vec![
626 SourceLine::Plain("hello".to_owned()),
627 SourceLine::Plain("world".to_owned()),
628 ]
629 );
630 }
631
632 #[test]
633 fn a_shebang_names_the_language_when_the_name_does_not() {
634 let source = source_lines("run", "#!/bin/sh\necho hi\n");
635
636 assert!(matches!(source.lines[0], SourceLine::Classed(_)));
637 }
638
639 #[test]
640 fn a_file_past_the_byte_cap_is_plain_and_says_so() {
641 let text = format!("fn main() {{}}\n{}\n", "x".repeat(MAX_BYTES));
642 let source = source_lines("main.rs", &text);
643
644 assert!(source.too_large);
645 assert!(
646 source
647 .lines
648 .iter()
649 .all(|line| matches!(line, SourceLine::Plain(_)))
650 );
651 }
652
653 #[test]
654 fn a_file_past_the_line_cap_is_plain_and_says_so() {
655 let text = "let x = 1;\n".repeat(MAX_LINES + 1);
656 let source = source_lines("main.rs", &text);
657
658 assert!(source.too_large);
659 assert_eq!(source.lines.len(), MAX_LINES + 1);
660 assert!(matches!(source.lines[0], SourceLine::Plain(_)));
661 }
662
663 #[test]
664 fn a_blank_line_keeps_its_height() {
665 let source = source_lines("main.rs", "fn a() {}\n\nfn b() {}\n");
666
667 assert_eq!(source.lines[1], SourceLine::Plain(" ".to_owned()));
668 }
669
670 #[test]
671 fn plain_text_is_not_dressed_in_spans_that_colour_nothing() {
672 let source = source_lines("notes.txt", "hello\n");
673
674 assert_eq!(source.lines, vec![SourceLine::Plain("hello".to_owned())]);
675 }
676
677 /// The gap `two_face` was added to close, asserted rather than described: TOML,
678 /// Dockerfile and TypeScript rendered plain until it landed, and the first two are
679 /// in this repository. `.jsx` is here through [`ALIASES`] rather than through a
680 /// grammar of its own.
681 #[test]
682 fn the_languages_this_repository_uses_are_all_highlighted() {
683 for name in [
684 "main.rs",
685 "install.sh",
686 "Cargo.toml",
687 "Dockerfile",
688 "app.ts",
689 "App.tsx",
690 "README.md",
691 "styles.css",
692 "config.yaml",
693 "data.json",
694 "Makefile",
695 "app.py",
696 "index.js",
697 "App.jsx",
698 "main.go",
699 "query.sql",
700 "main.c",
701 ] {
702 assert!(
703 syntax_for(syntaxes(), name, "").is_some(),
704 "{name} has no syntax"
705 );
706 }
707 }
708
709 #[test]
710 fn toml_is_highlighted_and_not_merely_recognised() {
711 let source = source_lines("Cargo.toml", "[package]\nname = \"steid\"\n");
712
713 assert!(matches!(source.lines[1], SourceLine::Classed(_)));
714 let html = classes(&source.lines[1]);
715 assert!(html.contains("hl-string"), "{html}");
716 }
717
718 #[test]
719 fn an_info_string_names_a_grammar_by_name_or_by_extension() {
720 for token in ["rust", "rs", "Rust", "toml", "sh", "json"] {
721 assert!(
722 syntax_for_token(syntaxes(), token).is_some(),
723 "{token} has no syntax"
724 );
725 }
726 }
727
728 #[test]
729 fn a_fence_is_highlighted_line_by_line() {
730 let lines = fenced_lines("rust", "fn main() {\n // hi\n}\n").expect("highlighted");
731
732 assert_eq!(lines.len(), 3);
733 assert!(lines[0].contains("hl-storage"), "{}", lines[0]);
734 assert!(lines[1].contains("hl-comment"), "{}", lines[1]);
735 for line in &lines {
736 assert!(!line.contains('\n'), "{line}");
737 }
738 }
739
740 #[test]
741 fn a_fence_naming_nothing_usable_is_not_highlighted() {
742 assert!(fenced_lines("", "fn main() {}\n").is_none());
743 assert!(fenced_lines("nosuchlang", "fn main() {}\n").is_none());
744 assert!(fenced_lines("txt", "just words\n").is_none());
745 }
746
747 #[test]
748 fn a_fence_past_the_caps_is_not_highlighted() {
749 let many = "let x = 1;\n".repeat(MAX_LINES + 1);
750
751 assert!(fenced_lines("rust", &many).is_none());
752 assert!(fenced_lines("rust", &"a".repeat(MAX_BYTES + 1)).is_none());
753 }
754
755 #[test]
756 fn an_empty_line_in_a_fence_carries_no_text() {
757 let lines = fenced_lines("rust", "fn a() {}\n\nfn b() {}\n").expect("highlighted");
758
759 assert_eq!(lines.len(), 3);
760
761 // It may still be a pair of spans — what matters is that nothing is inside
762 // them, since a space there would be selectable trailing whitespace.
763 let mut text = String::new();
764 let mut inside_tag = false;
765 for character in lines[1].chars() {
766 match character {
767 '<' => inside_tag = true,
768 '>' => inside_tag = false,
769 _ if !inside_tag => text.push(character),
770 _ => {}
771 }
772 }
773
774 assert!(text.is_empty(), "{:?}", lines[1]);
775 }
776
777 #[test]
778 fn a_recognised_file_is_named_by_its_grammar() {
779 assert_eq!(language_of("main.rs", "fn main() {}\n"), Some("Rust"));
780 assert_eq!(
781 language_of("Cargo.toml", "[package]\n"),
782 Some("TOML"),
783 "the header names what the body is coloured as"
784 );
785 }
786
787 #[test]
788 fn a_file_with_no_grammar_is_named_nothing() {
789 // Plain text is treated as no syntax at all, exactly as `source_lines` does —
790 // the header must not claim a language the body has no colour for.
791 assert_eq!(language_of("notes.txt", "hello\n"), None);
792 assert_eq!(language_of("LICENSE", "hello\n"), None);
793 }
794
795 #[test]
796 fn a_file_past_the_caps_is_named_nothing() {
797 // It is shown as plain text and says so; naming Rust beside that line would
798 // contradict it.
799 let huge = "fn main() {}\n".repeat(MAX_LINES + 1);
800
801 assert_eq!(language_of("main.rs", &huge), None);
802 }
803 // --- The cache ----------------------------------------------------------------
804
805 #[test]
806 fn a_lookup_counts_itself_as_a_hit_or_a_miss() {
807 // Process-wide counters and concurrent tests, so both assertions are about a
808 // rise rather than an absolute value.
809 let counters = crate::infrastructure::metrics::metrics();
810 let hits = counters.value_of("steid_highlight_cache_hits_total");
811 let misses = counters.value_of("steid_highlight_cache_misses_total");
812
813 let cache = HighlightCache::new();
814 let text = "fn main() {}\n";
815
816 cache.source_lines("counted", "main.rs", text);
817 assert!(
818 counters.value_of("steid_highlight_cache_misses_total") > misses,
819 "the first view of a file is a miss"
820 );
821
822 cache.source_lines("counted", "main.rs", text);
823 assert!(
824 counters.value_of("steid_highlight_cache_hits_total") > hits,
825 "the second view of the same bytes is a hit"
826 );
827 }
828
829 #[test]
830 fn a_cache_hit_renders_byte_for_byte_what_a_miss_did() {
831 let cache = HighlightCache::new();
832 let text = "fn main() {\n let x = \"a\";\n}\n";
833
834 let cold = cache.source_lines("deadbeef", "main.rs", text);
835 let warm = cache.source_lines("deadbeef", "main.rs", text);
836
837 assert_eq!(cold, warm);
838 assert_eq!(*cold, source_lines("main.rs", text));
839 assert_eq!(cache.stats().0, 1, "the second view added no entry");
840 }
841
842 #[test]
843 fn the_same_bytes_under_two_names_are_two_answers() {
844 let cache = HighlightCache::new();
845 let text = "fn main() {}\n";
846
847 let rust = cache.source_lines("same", "main.rs", text);
848 let plain = cache.source_lines("same", "notes.txt", text);
849
850 assert!(matches!(rust.lines[0], SourceLine::Classed(_)));
851 assert!(
852 matches!(plain.lines[0], SourceLine::Plain(_)),
853 "the file name chooses the grammar, so it has to be part of the key"
854 );
855 assert_eq!(cache.stats().0, 2);
856 }
857
858 #[test]
859 fn a_fence_is_cached_by_its_content_and_its_info_string() {
860 let cache = HighlightCache::new();
861 let text = "fn main() {}\n";
862
863 let cold = cache.fenced_lines("rust", text);
864 let warm = cache.fenced_lines("rust", text);
865
866 assert_eq!(cold, warm);
867 assert_eq!(*cold, fenced_lines("rust", text));
868 assert_eq!(cache.stats().0, 1);
869
870 // A fence with no grammar is an answer worth keeping too.
871 assert!(cache.fenced_lines("nosuchlang", text).is_none());
872 assert_eq!(cache.stats().0, 2);
873 }
874
875 #[test]
876 fn a_fence_and_a_blob_with_the_same_digest_do_not_collide() {
877 let cache = HighlightCache::new();
878 let text = "fn main() {}\n";
879 let digest = content_digest(text);
880
881 // The same syntax string on both sides — `rs` is an extension and a fence
882 // token — so only the `fenced` flag keeps the two entries apart.
883 let blob = cache.source_lines(&digest, "rs", text);
884 let fence = cache.fenced_lines("rs", text);
885
886 assert_eq!(cache.stats().0, 2);
887 assert!(matches!(blob.lines[0], SourceLine::Classed(_)));
888 assert!(fence.is_some());
889 }
890
891 #[test]
892 fn the_budget_evicts_the_least_recently_used_entry() {
893 let cache = HighlightCache::new();
894 let text = "fn main() {}\n";
895
896 for index in 0..4 {
897 cache.source_lines(&index.to_string(), "main.rs", text);
898 }
899
900 let (_, bytes) = cache.stats();
901 assert!(bytes > 0, "an entry has to be charged for something");
902
903 // Everything fits under 64 MiB, so nothing has been evicted yet.
904 assert_eq!(cache.stats().0, 4);
905
906 // Now force it: touch entry 0 so it is the most recent, then fill past the
907 // budget by hand and check that 0 survived and 1 did not.
908 cache.source_lines("0", "main.rs", text);
909 {
910 let mut entries = cache.entries.lock().expect("not poisoned");
911 entries.bytes = MAX_CACHE_BYTES;
912 }
913 cache.source_lines("4", "main.rs", text);
914
915 assert!(
916 cache
917 .get(&Key {
918 content: "0".to_owned(),
919 syntax: "main.rs".to_owned(),
920 fenced: false,
921 })
922 .is_some(),
923 "the most recently used entry is the last to go"
924 );
925 assert!(
926 cache
927 .get(&Key {
928 content: "1".to_owned(),
929 syntax: "main.rs".to_owned(),
930 fenced: false,
931 })
932 .is_none(),
933 "the least recently used entry is the first to go"
934 );
935 }
936
937 #[test]
938 fn a_digest_follows_the_bytes_and_nothing_else() {
939 assert_eq!(content_digest("abc"), content_digest("abc"));
940 assert_ne!(content_digest("abc"), content_digest("abd"));
941 assert_eq!(content_digest("").len(), 64, "SHA-256 in hex");
942 }
943
944 #[test]
945 fn one_cache_is_shared_by_everything_that_asks_for_it() {
946 assert!(Arc::ptr_eq(cache(), cache()));
947 }
948
949 // --- Snippets -----------------------------------------------------------------
950
951 #[test]
952 fn a_snippet_is_highlighted_line_by_line() {
953 let lines = snippet_lines("main.rs", "fn main() {\n // hi\n}\n").expect("highlighted");
954
955 assert_eq!(lines.len(), 3);
956 assert!(lines[0].contains("hl-storage"), "{}", lines[0]);
957 assert!(lines[1].contains("hl-comment"), "{}", lines[1]);
958 for line in &lines {
959 assert!(!line.contains('\n'), "{line}");
960 assert_eq!(
961 line.matches("<span").count(),
962 line.matches("</span>").count()
963 );
964 }
965 }
966
967 #[test]
968 fn a_snippet_of_a_file_with_no_grammar_is_not_highlighted() {
969 assert!(snippet_lines("notes.wibble", "hello\n").is_none());
970 assert!(snippet_lines("notes.txt", "hello\n").is_none());
971 }
972
973 #[test]
974 fn a_snippet_past_the_caps_is_not_highlighted() {
975 assert!(snippet_lines("main.rs", &"let x = 1;\n".repeat(MAX_LINES + 1)).is_none());
976 assert!(snippet_lines("main.rs", &"a".repeat(MAX_BYTES + 1)).is_none());
977 }
978
979 #[test]
980 fn a_snippet_is_read_as_if_the_file_began_at_its_first_line() {
981 // The limitation, asserted rather than described: a hunk has no view of what
982 // opened above it, so a string opened before the snippet is not a string here.
983 let inside = snippet_lines("main.rs", "still inside the string\";\n").expect("highlighted");
984
985 assert!(
986 !inside[0].starts_with("<span class=\"hl-string"),
987 "{}",
988 inside[0]
989 );
990 }
991}