steid

@jamesgill /

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