| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | use std::sync::{Arc, Mutex, OnceLock}; |
| 22 | |
| 23 | use lru::LruCache; |
| 24 | use sha2::{Digest, Sha256}; |
| 25 | |
| 26 | use syntect::{ |
| 27 | html::{ClassStyle, line_tokens_to_classed_spans}, |
| 28 | parsing::{ParseState, ScopeStack, SyntaxReference, SyntaxSet}, |
| 29 | util::LinesWithEndings, |
| 30 | }; |
| 31 | |
| 32 | |
| 33 | const PREFIX: &str = "hl-"; |
| 34 | |
| 35 | const CLASS_STYLE: ClassStyle = ClassStyle::SpacedPrefixed { prefix: PREFIX }; |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | pub const MAX_BYTES: usize = 512 * 1024; |
| 44 | |
| 45 | |
| 46 | pub const MAX_LINES: usize = 10_000; |
| 47 | |
| 48 | |
| 49 | |
| 50 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 51 | pub struct Source { |
| 52 | pub lines: Vec<SourceLine>, |
| 53 | |
| 54 | |
| 55 | |
| 56 | pub too_large: bool, |
| 57 | } |
| 58 | |
| 59 | |
| 60 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 61 | pub enum SourceLine { |
| 62 | |
| 63 | Plain(String), |
| 64 | |
| 65 | Classed(String), |
| 66 | } |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | pub 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 | |
| 84 | |
| 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 | |
| 93 | |
| 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 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | pub 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 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | fn syntaxes() -> &'static SyntaxSet { |
| 142 | static SYNTAXES: OnceLock<SyntaxSet> = OnceLock::new(); |
| 143 | SYNTAXES.get_or_init(two_face::syntax::extra_newlines) |
| 144 | } |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | const ALIASES: &[(&str, &str)] = &[("jsx", "js")]; |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | fn 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 | |
| 172 | |
| 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 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | fn 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 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | html.extend(body.chars().filter(|c| *c != '\n' && *c != '\r')); |
| 219 | |
| 220 | |
| 221 | |
| 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 | |
| 233 | fn 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 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | pub 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 | |
| 265 | |
| 266 | .filter(|lines| lines.len() == text.lines().count()) |
| 267 | } |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | fn 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 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | pub 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 | |
| 311 | |
| 312 | .filter(|lines| lines.len() == text.lines().count()) |
| 313 | } |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | pub 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 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | const MAX_CACHE_BYTES: usize = 64 * 1024 * 1024; |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | const PER_LINE_OVERHEAD: usize = 32; |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 362 | struct Key { |
| 363 | content: String, |
| 364 | syntax: String, |
| 365 | fenced: bool, |
| 366 | } |
| 367 | |
| 368 | |
| 369 | #[derive(Debug, Clone)] |
| 370 | enum Cached { |
| 371 | Source(Arc<Source>), |
| 372 | |
| 373 | |
| 374 | Fence(Arc<Option<Vec<String>>>), |
| 375 | } |
| 376 | |
| 377 | impl Cached { |
| 378 | |
| 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 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | |
| 411 | pub struct HighlightCache { |
| 412 | entries: Mutex<Entries>, |
| 413 | } |
| 414 | |
| 415 | struct Entries { |
| 416 | cache: LruCache<Key, Cached>, |
| 417 | bytes: usize, |
| 418 | } |
| 419 | |
| 420 | impl Default for HighlightCache { |
| 421 | fn default() -> Self { |
| 422 | Self::new() |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | impl HighlightCache { |
| 427 | pub fn new() -> Self { |
| 428 | Self { |
| 429 | entries: Mutex::new(Entries { |
| 430 | |
| 431 | |
| 432 | cache: LruCache::unbounded(), |
| 433 | bytes: 0, |
| 434 | }), |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | |
| 439 | |
| 440 | |
| 441 | |
| 442 | |
| 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 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | let source = Arc::new(source_lines(file_name, text)); |
| 460 | self.put(key, Cached::Source(source.clone())); |
| 461 | source |
| 462 | } |
| 463 | |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 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 | |
| 486 | |
| 487 | |
| 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 | |
| 500 | |
| 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 | |
| 521 | |
| 522 | |
| 523 | None => break, |
| 524 | } |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | |
| 529 | |
| 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 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | |
| 546 | |
| 547 | pub 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)] |
| 554 | mod 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 | |
| 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("<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 | |
| 663 | |
| 664 | |
| 665 | |
| 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 | |
| 747 | |
| 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 | |
| 775 | |
| 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 | |
| 783 | |
| 784 | let huge = "fn main() {}\n".repeat(MAX_LINES + 1); |
| 785 | |
| 786 | assert_eq!(language_of("main.rs", &huge), None); |
| 787 | } |
| 788 | |
| 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 | |
| 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 | |
| 843 | |
| 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 | |
| 865 | assert_eq!(cache.stats().0, 4); |
| 866 | |
| 867 | |
| 868 | |
| 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 | |
| 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 | |
| 943 | |
| 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 | } |