| 1 | use std::ops::Range; |
| 2 | |
| 3 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 4 | pub enum Token { |
| 5 | Keyword, |
| 6 | String, |
| 7 | Number, |
| 8 | Comment, |
| 9 | Tag, |
| 10 | Attribute, |
| 11 | Heading, |
| 12 | Strong, |
| 13 | Emphasis, |
| 14 | Link, |
| 15 | /// Built-in types, functions and values: `bool`, `print`, `self`. |
| 16 | Type, |
| 17 | /// The name a definition gives: `f` in `def f`, `A` in `class A`. |
| 18 | Title, |
| 19 | } |
| 20 | |
| 21 | /// A lexer for code: comments, strings, numbers and keywords. |
| 22 | struct Grammar { |
| 23 | line_comments: &'static [&'static str], |
| 24 | block_comment: Option<(&'static str, &'static str)>, |
| 25 | keywords: &'static [&'static str], |
| 26 | /// `'x'` is a character; other single quotes (Rust lifetimes) are left alone. |
| 27 | char_quotes: bool, |
| 28 | case_insensitive: bool, |
| 29 | /// Words after this prefix are keywords too, as `\section` in LaTeX. |
| 30 | command_prefix: Option<char>, |
| 31 | types: &'static [&'static str], |
| 32 | /// A word or string right before `:` is a key, as in JSON, YAML and CSS. |
| 33 | keys: bool, |
| 34 | /// `-` joins words, as in `font-size` and `Get-ChildItem`; such a word is a built-in. |
| 35 | dashed_words: bool, |
| 36 | } |
| 37 | |
| 38 | const CODE: Grammar = Grammar { |
| 39 | line_comments: &[], |
| 40 | block_comment: None, |
| 41 | keywords: &[], |
| 42 | char_quotes: false, |
| 43 | case_insensitive: false, |
| 44 | command_prefix: None, |
| 45 | types: &[], |
| 46 | keys: false, |
| 47 | dashed_words: false, |
| 48 | }; |
| 49 | |
| 50 | const fn c_style(keywords: &'static [&'static str]) -> Grammar { |
| 51 | Grammar { |
| 52 | line_comments: &["//"], |
| 53 | block_comment: Some(("/*", "*/")), |
| 54 | keywords, |
| 55 | ..CODE |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | const fn hash_style(keywords: &'static [&'static str]) -> Grammar { |
| 60 | Grammar { |
| 61 | line_comments: &["#"], |
| 62 | keywords, |
| 63 | ..CODE |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | const C_KEYWORDS: &[&str] = &[ |
| 68 | "auto", |
| 69 | "break", |
| 70 | "case", |
| 71 | "char", |
| 72 | "const", |
| 73 | "continue", |
| 74 | "default", |
| 75 | "do", |
| 76 | "double", |
| 77 | "else", |
| 78 | "enum", |
| 79 | "extern", |
| 80 | "float", |
| 81 | "for", |
| 82 | "goto", |
| 83 | "if", |
| 84 | "inline", |
| 85 | "int", |
| 86 | "long", |
| 87 | "register", |
| 88 | "restrict", |
| 89 | "return", |
| 90 | "short", |
| 91 | "signed", |
| 92 | "sizeof", |
| 93 | "static", |
| 94 | "struct", |
| 95 | "switch", |
| 96 | "typedef", |
| 97 | "union", |
| 98 | "unsigned", |
| 99 | "void", |
| 100 | "volatile", |
| 101 | "while", |
| 102 | "NULL", |
| 103 | "true", |
| 104 | "false", |
| 105 | "bool", |
| 106 | "#include", |
| 107 | "#define", |
| 108 | "@interface", |
| 109 | "@implementation", |
| 110 | "@end", |
| 111 | "@property", |
| 112 | "self", |
| 113 | "nil", |
| 114 | ]; |
| 115 | const CPP_KEYWORDS: &[&str] = &[ |
| 116 | "auto", |
| 117 | "bool", |
| 118 | "break", |
| 119 | "case", |
| 120 | "catch", |
| 121 | "char", |
| 122 | "class", |
| 123 | "const", |
| 124 | "constexpr", |
| 125 | "continue", |
| 126 | "default", |
| 127 | "delete", |
| 128 | "do", |
| 129 | "double", |
| 130 | "else", |
| 131 | "enum", |
| 132 | "explicit", |
| 133 | "extern", |
| 134 | "false", |
| 135 | "float", |
| 136 | "for", |
| 137 | "friend", |
| 138 | "goto", |
| 139 | "if", |
| 140 | "inline", |
| 141 | "int", |
| 142 | "long", |
| 143 | "namespace", |
| 144 | "new", |
| 145 | "noexcept", |
| 146 | "nullptr", |
| 147 | "operator", |
| 148 | "override", |
| 149 | "private", |
| 150 | "protected", |
| 151 | "public", |
| 152 | "return", |
| 153 | "short", |
| 154 | "signed", |
| 155 | "sizeof", |
| 156 | "static", |
| 157 | "struct", |
| 158 | "switch", |
| 159 | "template", |
| 160 | "this", |
| 161 | "throw", |
| 162 | "true", |
| 163 | "try", |
| 164 | "typedef", |
| 165 | "typename", |
| 166 | "union", |
| 167 | "unsigned", |
| 168 | "using", |
| 169 | "virtual", |
| 170 | "void", |
| 171 | "volatile", |
| 172 | "while", |
| 173 | ]; |
| 174 | const CSHARP_KEYWORDS: &[&str] = &[ |
| 175 | "abstract", |
| 176 | "as", |
| 177 | "async", |
| 178 | "await", |
| 179 | "base", |
| 180 | "bool", |
| 181 | "break", |
| 182 | "case", |
| 183 | "catch", |
| 184 | "class", |
| 185 | "const", |
| 186 | "continue", |
| 187 | "default", |
| 188 | "delegate", |
| 189 | "do", |
| 190 | "else", |
| 191 | "enum", |
| 192 | "event", |
| 193 | "false", |
| 194 | "finally", |
| 195 | "for", |
| 196 | "foreach", |
| 197 | "get", |
| 198 | "if", |
| 199 | "in", |
| 200 | "int", |
| 201 | "interface", |
| 202 | "internal", |
| 203 | "is", |
| 204 | "new", |
| 205 | "null", |
| 206 | "object", |
| 207 | "out", |
| 208 | "override", |
| 209 | "private", |
| 210 | "protected", |
| 211 | "public", |
| 212 | "readonly", |
| 213 | "ref", |
| 214 | "return", |
| 215 | "sealed", |
| 216 | "set", |
| 217 | "static", |
| 218 | "string", |
| 219 | "struct", |
| 220 | "switch", |
| 221 | "this", |
| 222 | "throw", |
| 223 | "true", |
| 224 | "try", |
| 225 | "using", |
| 226 | "var", |
| 227 | "virtual", |
| 228 | "void", |
| 229 | "while", |
| 230 | ]; |
| 231 | const JAVA_KEYWORDS: &[&str] = &[ |
| 232 | "abstract", |
| 233 | "boolean", |
| 234 | "break", |
| 235 | "case", |
| 236 | "catch", |
| 237 | "char", |
| 238 | "class", |
| 239 | "const", |
| 240 | "continue", |
| 241 | "default", |
| 242 | "do", |
| 243 | "double", |
| 244 | "else", |
| 245 | "enum", |
| 246 | "extends", |
| 247 | "false", |
| 248 | "final", |
| 249 | "finally", |
| 250 | "float", |
| 251 | "for", |
| 252 | "if", |
| 253 | "implements", |
| 254 | "import", |
| 255 | "instanceof", |
| 256 | "int", |
| 257 | "interface", |
| 258 | "long", |
| 259 | "new", |
| 260 | "null", |
| 261 | "package", |
| 262 | "private", |
| 263 | "protected", |
| 264 | "public", |
| 265 | "return", |
| 266 | "static", |
| 267 | "super", |
| 268 | "switch", |
| 269 | "this", |
| 270 | "throw", |
| 271 | "throws", |
| 272 | "true", |
| 273 | "try", |
| 274 | "var", |
| 275 | "void", |
| 276 | "while", |
| 277 | ]; |
| 278 | const JS_KEYWORDS: &[&str] = &[ |
| 279 | "as", |
| 280 | "async", |
| 281 | "await", |
| 282 | "break", |
| 283 | "case", |
| 284 | "catch", |
| 285 | "class", |
| 286 | "const", |
| 287 | "continue", |
| 288 | "default", |
| 289 | "delete", |
| 290 | "do", |
| 291 | "else", |
| 292 | "enum", |
| 293 | "export", |
| 294 | "extends", |
| 295 | "false", |
| 296 | "finally", |
| 297 | "for", |
| 298 | "from", |
| 299 | "function", |
| 300 | "if", |
| 301 | "implements", |
| 302 | "import", |
| 303 | "in", |
| 304 | "instanceof", |
| 305 | "interface", |
| 306 | "let", |
| 307 | "new", |
| 308 | "null", |
| 309 | "of", |
| 310 | "private", |
| 311 | "protected", |
| 312 | "public", |
| 313 | "readonly", |
| 314 | "return", |
| 315 | "static", |
| 316 | "super", |
| 317 | "switch", |
| 318 | "this", |
| 319 | "throw", |
| 320 | "true", |
| 321 | "try", |
| 322 | "type", |
| 323 | "typeof", |
| 324 | "undefined", |
| 325 | "var", |
| 326 | "void", |
| 327 | "while", |
| 328 | "yield", |
| 329 | ]; |
| 330 | const DART_KEYWORDS: &[&str] = &[ |
| 331 | "abstract", |
| 332 | "async", |
| 333 | "await", |
| 334 | "break", |
| 335 | "case", |
| 336 | "catch", |
| 337 | "class", |
| 338 | "const", |
| 339 | "continue", |
| 340 | "default", |
| 341 | "do", |
| 342 | "else", |
| 343 | "enum", |
| 344 | "extends", |
| 345 | "false", |
| 346 | "final", |
| 347 | "finally", |
| 348 | "for", |
| 349 | "if", |
| 350 | "implements", |
| 351 | "import", |
| 352 | "in", |
| 353 | "is", |
| 354 | "late", |
| 355 | "new", |
| 356 | "null", |
| 357 | "required", |
| 358 | "return", |
| 359 | "static", |
| 360 | "super", |
| 361 | "switch", |
| 362 | "this", |
| 363 | "throw", |
| 364 | "true", |
| 365 | "try", |
| 366 | "var", |
| 367 | "void", |
| 368 | "while", |
| 369 | "with", |
| 370 | "yield", |
| 371 | ]; |
| 372 | const GO_KEYWORDS: &[&str] = &[ |
| 373 | "break", |
| 374 | "case", |
| 375 | "chan", |
| 376 | "const", |
| 377 | "continue", |
| 378 | "default", |
| 379 | "defer", |
| 380 | "else", |
| 381 | "fallthrough", |
| 382 | "for", |
| 383 | "func", |
| 384 | "go", |
| 385 | "goto", |
| 386 | "if", |
| 387 | "import", |
| 388 | "interface", |
| 389 | "map", |
| 390 | "package", |
| 391 | "range", |
| 392 | "return", |
| 393 | "select", |
| 394 | "struct", |
| 395 | "switch", |
| 396 | "type", |
| 397 | "var", |
| 398 | "true", |
| 399 | "false", |
| 400 | "nil", |
| 401 | "iota", |
| 402 | ]; |
| 403 | const KOTLIN_KEYWORDS: &[&str] = &[ |
| 404 | "as", |
| 405 | "break", |
| 406 | "class", |
| 407 | "continue", |
| 408 | "data", |
| 409 | "do", |
| 410 | "else", |
| 411 | "false", |
| 412 | "for", |
| 413 | "fun", |
| 414 | "if", |
| 415 | "import", |
| 416 | "in", |
| 417 | "interface", |
| 418 | "is", |
| 419 | "null", |
| 420 | "object", |
| 421 | "override", |
| 422 | "package", |
| 423 | "private", |
| 424 | "return", |
| 425 | "super", |
| 426 | "this", |
| 427 | "throw", |
| 428 | "true", |
| 429 | "try", |
| 430 | "val", |
| 431 | "var", |
| 432 | "when", |
| 433 | "while", |
| 434 | ]; |
| 435 | const RUST_KEYWORDS: &[&str] = &[ |
| 436 | "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", |
| 437 | "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", |
| 438 | "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", |
| 439 | "unsafe", "use", "where", "while", |
| 440 | ]; |
| 441 | const SCALA_KEYWORDS: &[&str] = &[ |
| 442 | "abstract", |
| 443 | "case", |
| 444 | "catch", |
| 445 | "class", |
| 446 | "def", |
| 447 | "do", |
| 448 | "else", |
| 449 | "extends", |
| 450 | "false", |
| 451 | "final", |
| 452 | "finally", |
| 453 | "for", |
| 454 | "if", |
| 455 | "implicit", |
| 456 | "import", |
| 457 | "lazy", |
| 458 | "match", |
| 459 | "new", |
| 460 | "null", |
| 461 | "object", |
| 462 | "override", |
| 463 | "package", |
| 464 | "private", |
| 465 | "protected", |
| 466 | "return", |
| 467 | "sealed", |
| 468 | "super", |
| 469 | "this", |
| 470 | "throw", |
| 471 | "trait", |
| 472 | "true", |
| 473 | "try", |
| 474 | "type", |
| 475 | "val", |
| 476 | "var", |
| 477 | "while", |
| 478 | "with", |
| 479 | "yield", |
| 480 | ]; |
| 481 | const SWIFT_KEYWORDS: &[&str] = &[ |
| 482 | "as", |
| 483 | "break", |
| 484 | "case", |
| 485 | "catch", |
| 486 | "class", |
| 487 | "continue", |
| 488 | "default", |
| 489 | "defer", |
| 490 | "do", |
| 491 | "else", |
| 492 | "enum", |
| 493 | "extension", |
| 494 | "false", |
| 495 | "for", |
| 496 | "func", |
| 497 | "guard", |
| 498 | "if", |
| 499 | "import", |
| 500 | "in", |
| 501 | "init", |
| 502 | "let", |
| 503 | "nil", |
| 504 | "private", |
| 505 | "protocol", |
| 506 | "public", |
| 507 | "return", |
| 508 | "self", |
| 509 | "static", |
| 510 | "struct", |
| 511 | "switch", |
| 512 | "throw", |
| 513 | "throws", |
| 514 | "true", |
| 515 | "try", |
| 516 | "var", |
| 517 | "where", |
| 518 | "while", |
| 519 | ]; |
| 520 | const PHP_KEYWORDS: &[&str] = &[ |
| 521 | "abstract", |
| 522 | "array", |
| 523 | "as", |
| 524 | "break", |
| 525 | "case", |
| 526 | "catch", |
| 527 | "class", |
| 528 | "const", |
| 529 | "continue", |
| 530 | "default", |
| 531 | "do", |
| 532 | "echo", |
| 533 | "else", |
| 534 | "elseif", |
| 535 | "extends", |
| 536 | "false", |
| 537 | "final", |
| 538 | "finally", |
| 539 | "for", |
| 540 | "foreach", |
| 541 | "function", |
| 542 | "if", |
| 543 | "implements", |
| 544 | "include", |
| 545 | "interface", |
| 546 | "namespace", |
| 547 | "new", |
| 548 | "null", |
| 549 | "private", |
| 550 | "protected", |
| 551 | "public", |
| 552 | "require", |
| 553 | "return", |
| 554 | "static", |
| 555 | "switch", |
| 556 | "throw", |
| 557 | "true", |
| 558 | "try", |
| 559 | "use", |
| 560 | "while", |
| 561 | ]; |
| 562 | const PYTHON_KEYWORDS: &[&str] = &[ |
| 563 | "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", |
| 564 | "else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is", |
| 565 | "lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while", |
| 566 | "with", "yield", |
| 567 | ]; |
| 568 | const RUBY_KEYWORDS: &[&str] = &[ |
| 569 | "and", "begin", "break", "case", "class", "def", "do", "else", "elsif", "end", "ensure", |
| 570 | "false", "for", "if", "in", "module", "next", "nil", "not", "or", "require", "rescue", |
| 571 | "return", "self", "super", "then", "true", "unless", "until", "when", "while", "yield", |
| 572 | ]; |
| 573 | const PERL_KEYWORDS: &[&str] = &[ |
| 574 | "else", "elsif", "for", "foreach", "if", "last", "local", "my", "next", "our", "package", |
| 575 | "print", "require", "return", "sub", "unless", "until", "use", "while", |
| 576 | ]; |
| 577 | const R_KEYWORDS: &[&str] = &[ |
| 578 | "break", "else", "FALSE", "for", "function", "if", "in", "NA", "next", "NULL", "repeat", |
| 579 | "return", "TRUE", "while", "library", |
| 580 | ]; |
| 581 | const SHELL_KEYWORDS: &[&str] = &[ |
| 582 | "case", "do", "done", "echo", "elif", "else", "esac", "exit", "export", "fi", "for", |
| 583 | "function", "if", "in", "local", "return", "set", "then", "until", "while", |
| 584 | ]; |
| 585 | const POWERSHELL_KEYWORDS: &[&str] = &[ |
| 586 | "begin", "break", "catch", "class", "continue", "do", "else", "elseif", "end", "exit", |
| 587 | "filter", "finally", "for", "foreach", "function", "if", "in", "param", "process", "return", |
| 588 | "switch", "throw", "trap", "try", "until", "while", "$true", "$false", "$null", |
| 589 | ]; |
| 590 | const DOS_KEYWORDS: &[&str] = &[ |
| 591 | "call", "cd", "copy", "defined", "del", "do", "echo", "else", "endlocal", "equ", "exist", |
| 592 | "exit", "for", "goto", "if", "in", "mkdir", "neq", "not", "pause", "set", "setlocal", "shift", |
| 593 | "start", |
| 594 | ]; |
| 595 | const DOCKER_KEYWORDS: &[&str] = &[ |
| 596 | "add", |
| 597 | "arg", |
| 598 | "as", |
| 599 | "cmd", |
| 600 | "copy", |
| 601 | "entrypoint", |
| 602 | "env", |
| 603 | "expose", |
| 604 | "from", |
| 605 | "healthcheck", |
| 606 | "label", |
| 607 | "onbuild", |
| 608 | "run", |
| 609 | "shell", |
| 610 | "stopsignal", |
| 611 | "user", |
| 612 | "volume", |
| 613 | "workdir", |
| 614 | ]; |
| 615 | const SQL_KEYWORDS: &[&str] = &[ |
| 616 | "alter", "and", "as", "asc", "between", "by", "case", "create", "delete", "desc", "distinct", |
| 617 | "drop", "else", "end", "exists", "from", "group", "having", "in", "inner", "insert", "into", |
| 618 | "is", "join", "left", "like", "limit", "not", "null", "on", "or", "order", "outer", "right", |
| 619 | "select", "set", "table", "then", "union", "update", "values", "when", "where", "with", |
| 620 | ]; |
| 621 | const KQL_KEYWORDS: &[&str] = &[ |
| 622 | "and", |
| 623 | "asc", |
| 624 | "by", |
| 625 | "count", |
| 626 | "desc", |
| 627 | "distinct", |
| 628 | "extend", |
| 629 | "join", |
| 630 | "let", |
| 631 | "limit", |
| 632 | "or", |
| 633 | "order", |
| 634 | "project", |
| 635 | "render", |
| 636 | "sort", |
| 637 | "summarize", |
| 638 | "take", |
| 639 | "top", |
| 640 | "union", |
| 641 | "where", |
| 642 | ]; |
| 643 | const GRAPHQL_KEYWORDS: &[&str] = &[ |
| 644 | "enum", |
| 645 | "extend", |
| 646 | "false", |
| 647 | "fragment", |
| 648 | "implements", |
| 649 | "input", |
| 650 | "interface", |
| 651 | "mutation", |
| 652 | "null", |
| 653 | "on", |
| 654 | "query", |
| 655 | "scalar", |
| 656 | "schema", |
| 657 | "subscription", |
| 658 | "true", |
| 659 | "type", |
| 660 | "union", |
| 661 | ]; |
| 662 | const HTTP_KEYWORDS: &[&str] = &[ |
| 663 | "CONNECT", "DELETE", "GET", "HEAD", "HTTP", "OPTIONS", "PATCH", "POST", "PUT", "TRACE", |
| 664 | ]; |
| 665 | const VB_KEYWORDS: &[&str] = &[ |
| 666 | "and", "as", "boolean", "byval", "byref", "call", "case", "class", "const", "dim", "do", |
| 667 | "each", "else", "elseif", "end", "exit", "false", "for", "function", "if", "imports", "in", |
| 668 | "integer", "is", "loop", "module", "new", "next", "not", "nothing", "or", "private", "public", |
| 669 | "return", "select", "set", "string", "sub", "then", "to", "true", "while", "with", |
| 670 | ]; |
| 671 | const VERILOG_KEYWORDS: &[&str] = &[ |
| 672 | "always", |
| 673 | "assign", |
| 674 | "begin", |
| 675 | "case", |
| 676 | "else", |
| 677 | "end", |
| 678 | "endcase", |
| 679 | "endmodule", |
| 680 | "for", |
| 681 | "if", |
| 682 | "initial", |
| 683 | "input", |
| 684 | "integer", |
| 685 | "module", |
| 686 | "negedge", |
| 687 | "output", |
| 688 | "parameter", |
| 689 | "posedge", |
| 690 | "reg", |
| 691 | "wire", |
| 692 | ]; |
| 693 | const VHDL_KEYWORDS: &[&str] = &[ |
| 694 | "architecture", |
| 695 | "begin", |
| 696 | "case", |
| 697 | "downto", |
| 698 | "else", |
| 699 | "elsif", |
| 700 | "end", |
| 701 | "entity", |
| 702 | "for", |
| 703 | "generic", |
| 704 | "if", |
| 705 | "in", |
| 706 | "is", |
| 707 | "library", |
| 708 | "loop", |
| 709 | "map", |
| 710 | "of", |
| 711 | "others", |
| 712 | "out", |
| 713 | "port", |
| 714 | "process", |
| 715 | "signal", |
| 716 | "then", |
| 717 | "to", |
| 718 | "use", |
| 719 | "variable", |
| 720 | "when", |
| 721 | "while", |
| 722 | ]; |
| 723 | const OCTAVE_KEYWORDS: &[&str] = &[ |
| 724 | "break", |
| 725 | "case", |
| 726 | "catch", |
| 727 | "continue", |
| 728 | "else", |
| 729 | "elseif", |
| 730 | "end", |
| 731 | "for", |
| 732 | "function", |
| 733 | "if", |
| 734 | "otherwise", |
| 735 | "return", |
| 736 | "switch", |
| 737 | "try", |
| 738 | "while", |
| 739 | ]; |
| 740 | const LISP_KEYWORDS: &[&str] = &[ |
| 741 | "cond", |
| 742 | "defmacro", |
| 743 | "defparameter", |
| 744 | "defun", |
| 745 | "defvar", |
| 746 | "if", |
| 747 | "lambda", |
| 748 | "let", |
| 749 | "nil", |
| 750 | "progn", |
| 751 | "quote", |
| 752 | "setf", |
| 753 | "setq", |
| 754 | "t", |
| 755 | "unless", |
| 756 | "when", |
| 757 | ]; |
| 758 | const LITERALS: &[&str] = &["true", "false", "null", "yes", "no", "on", "off", "~"]; |
| 759 | |
| 760 | const C: Grammar = Grammar { |
| 761 | types: &[ |
| 762 | "size_t", "int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t", |
| 763 | "uint64_t", "FILE", "printf", "scanf", "malloc", "free", "memcpy", "strlen", "BOOL", "YES", |
| 764 | "NO", "id", "NSString", "NSLog", |
| 765 | ], |
| 766 | char_quotes: true, |
| 767 | ..c_style(C_KEYWORDS) |
| 768 | }; |
| 769 | const CPP: Grammar = Grammar { |
| 770 | types: &[ |
| 771 | "std", |
| 772 | "string", |
| 773 | "vector", |
| 774 | "map", |
| 775 | "set", |
| 776 | "size_t", |
| 777 | "cout", |
| 778 | "cin", |
| 779 | "endl", |
| 780 | "unique_ptr", |
| 781 | "shared_ptr", |
| 782 | "make_unique", |
| 783 | "make_shared", |
| 784 | "printf", |
| 785 | ], |
| 786 | char_quotes: true, |
| 787 | ..c_style(CPP_KEYWORDS) |
| 788 | }; |
| 789 | const CSHARP: Grammar = Grammar { |
| 790 | types: &[ |
| 791 | "byte", |
| 792 | "char", |
| 793 | "decimal", |
| 794 | "double", |
| 795 | "float", |
| 796 | "long", |
| 797 | "Console", |
| 798 | "List", |
| 799 | "Dictionary", |
| 800 | "Task", |
| 801 | "DateTime", |
| 802 | "Exception", |
| 803 | "nameof", |
| 804 | ], |
| 805 | char_quotes: true, |
| 806 | ..c_style(CSHARP_KEYWORDS) |
| 807 | }; |
| 808 | const JAVA: Grammar = Grammar { |
| 809 | types: &[ |
| 810 | "byte", |
| 811 | "short", |
| 812 | "String", |
| 813 | "Integer", |
| 814 | "Long", |
| 815 | "Double", |
| 816 | "Boolean", |
| 817 | "Object", |
| 818 | "List", |
| 819 | "Map", |
| 820 | "ArrayList", |
| 821 | "HashMap", |
| 822 | "System", |
| 823 | "Exception", |
| 824 | "Override", |
| 825 | ], |
| 826 | char_quotes: true, |
| 827 | ..c_style(JAVA_KEYWORDS) |
| 828 | }; |
| 829 | const RUST: Grammar = Grammar { |
| 830 | types: &[ |
| 831 | "i8", |
| 832 | "i16", |
| 833 | "i32", |
| 834 | "i64", |
| 835 | "i128", |
| 836 | "isize", |
| 837 | "u8", |
| 838 | "u16", |
| 839 | "u32", |
| 840 | "u64", |
| 841 | "u128", |
| 842 | "usize", |
| 843 | "f32", |
| 844 | "f64", |
| 845 | "bool", |
| 846 | "char", |
| 847 | "str", |
| 848 | "String", |
| 849 | "Vec", |
| 850 | "Option", |
| 851 | "Some", |
| 852 | "None", |
| 853 | "Result", |
| 854 | "Ok", |
| 855 | "Err", |
| 856 | "Box", |
| 857 | "Rc", |
| 858 | "Arc", |
| 859 | "println", |
| 860 | "print", |
| 861 | "format", |
| 862 | "vec", |
| 863 | "panic", |
| 864 | "assert", |
| 865 | "assert_eq", |
| 866 | ], |
| 867 | char_quotes: true, |
| 868 | ..c_style(RUST_KEYWORDS) |
| 869 | }; |
| 870 | const KOTLIN: Grammar = Grammar { |
| 871 | types: &[ |
| 872 | "Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "println", |
| 873 | "listOf", "mapOf", "setOf", |
| 874 | ], |
| 875 | char_quotes: true, |
| 876 | ..c_style(KOTLIN_KEYWORDS) |
| 877 | }; |
| 878 | const SCALA: Grammar = Grammar { |
| 879 | types: &[ |
| 880 | "Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "Option", |
| 881 | "Some", "None", "println", |
| 882 | ], |
| 883 | char_quotes: true, |
| 884 | ..c_style(SCALA_KEYWORDS) |
| 885 | }; |
| 886 | const JS: Grammar = Grammar { |
| 887 | types: &[ |
| 888 | "console", "document", "window", "Promise", "Array", "Object", "JSON", "Math", "Date", |
| 889 | "Error", "Map", "Set", "string", "number", "boolean", "any", "unknown", "never", "require", |
| 890 | "module", |
| 891 | ], |
| 892 | ..c_style(JS_KEYWORDS) |
| 893 | }; |
| 894 | const DART: Grammar = Grammar { |
| 895 | types: &[ |
| 896 | "int", "double", "num", "String", "bool", "List", "Map", "Set", "dynamic", "Future", |
| 897 | "Stream", "print", |
| 898 | ], |
| 899 | ..c_style(DART_KEYWORDS) |
| 900 | }; |
| 901 | const GO: Grammar = Grammar { |
| 902 | types: &[ |
| 903 | "bool", |
| 904 | "byte", |
| 905 | "complex64", |
| 906 | "complex128", |
| 907 | "error", |
| 908 | "float32", |
| 909 | "float64", |
| 910 | "int", |
| 911 | "int8", |
| 912 | "int16", |
| 913 | "int32", |
| 914 | "int64", |
| 915 | "rune", |
| 916 | "string", |
| 917 | "uint", |
| 918 | "uint8", |
| 919 | "uint16", |
| 920 | "uint32", |
| 921 | "uint64", |
| 922 | "uintptr", |
| 923 | "any", |
| 924 | "append", |
| 925 | "cap", |
| 926 | "close", |
| 927 | "copy", |
| 928 | "delete", |
| 929 | "len", |
| 930 | "make", |
| 931 | "new", |
| 932 | "panic", |
| 933 | "print", |
| 934 | "println", |
| 935 | "recover", |
| 936 | ], |
| 937 | ..c_style(GO_KEYWORDS) |
| 938 | }; |
| 939 | const SWIFT: Grammar = Grammar { |
| 940 | types: &[ |
| 941 | "Int", |
| 942 | "Double", |
| 943 | "Float", |
| 944 | "Bool", |
| 945 | "String", |
| 946 | "Character", |
| 947 | "Array", |
| 948 | "Dictionary", |
| 949 | "Set", |
| 950 | "Optional", |
| 951 | "Any", |
| 952 | "print", |
| 953 | ], |
| 954 | ..c_style(SWIFT_KEYWORDS) |
| 955 | }; |
| 956 | const CSS: Grammar = Grammar { |
| 957 | keys: true, |
| 958 | dashed_words: true, |
| 959 | ..c_style(&[]) |
| 960 | }; |
| 961 | const JSON: Grammar = Grammar { |
| 962 | keys: true, |
| 963 | ..c_style(LITERALS) |
| 964 | }; |
| 965 | const VERILOG: Grammar = Grammar { |
| 966 | types: &["$display", "$finish", "$time", "logic", "bit"], |
| 967 | ..c_style(VERILOG_KEYWORDS) |
| 968 | }; |
| 969 | const PHP: Grammar = Grammar { |
| 970 | types: &[ |
| 971 | "$this", |
| 972 | "array", |
| 973 | "count", |
| 974 | "isset", |
| 975 | "empty", |
| 976 | "strlen", |
| 977 | "json_encode", |
| 978 | "json_decode", |
| 979 | "var_dump", |
| 980 | "print_r", |
| 981 | ], |
| 982 | line_comments: &["//", "#"], |
| 983 | ..c_style(PHP_KEYWORDS) |
| 984 | }; |
| 985 | const KQL: Grammar = Grammar { |
| 986 | types: &[ |
| 987 | "ago", "now", "datetime", "bin", "dcount", "tostring", "toint", "strcat", "count", "sum", |
| 988 | "avg", |
| 989 | ], |
| 990 | block_comment: None, |
| 991 | case_insensitive: true, |
| 992 | ..c_style(KQL_KEYWORDS) |
| 993 | }; |
| 994 | const PYTHON: Grammar = Grammar { |
| 995 | types: &[ |
| 996 | "self", |
| 997 | "cls", |
| 998 | "print", |
| 999 | "len", |
| 1000 | "range", |
| 1001 | "int", |
| 1002 | "str", |
| 1003 | "float", |
| 1004 | "bool", |
| 1005 | "bytes", |
| 1006 | "list", |
| 1007 | "dict", |
| 1008 | "set", |
| 1009 | "tuple", |
| 1010 | "object", |
| 1011 | "open", |
| 1012 | "super", |
| 1013 | "isinstance", |
| 1014 | "enumerate", |
| 1015 | "zip", |
| 1016 | "map", |
| 1017 | "filter", |
| 1018 | "sorted", |
| 1019 | "sum", |
| 1020 | "min", |
| 1021 | "max", |
| 1022 | "abs", |
| 1023 | "type", |
| 1024 | "Exception", |
| 1025 | ], |
| 1026 | ..hash_style(PYTHON_KEYWORDS) |
| 1027 | }; |
| 1028 | const RUBY: Grammar = Grammar { |
| 1029 | types: &[ |
| 1030 | "puts", |
| 1031 | "print", |
| 1032 | "p", |
| 1033 | "attr_accessor", |
| 1034 | "attr_reader", |
| 1035 | "attr_writer", |
| 1036 | "lambda", |
| 1037 | "proc", |
| 1038 | "raise", |
| 1039 | ], |
| 1040 | ..hash_style(RUBY_KEYWORDS) |
| 1041 | }; |
| 1042 | const PERL: Grammar = Grammar { |
| 1043 | types: &[ |
| 1044 | "chomp", "die", "join", "keys", "push", "shift", "split", "values", "open", "close", |
| 1045 | ], |
| 1046 | ..hash_style(PERL_KEYWORDS) |
| 1047 | }; |
| 1048 | const R: Grammar = Grammar { |
| 1049 | types: &[ |
| 1050 | "c", "list", "print", "paste", "length", "vector", "matrix", "sum", "mean", "cat", |
| 1051 | ], |
| 1052 | ..hash_style(R_KEYWORDS) |
| 1053 | }; |
| 1054 | const SHELL: Grammar = Grammar { |
| 1055 | types: &[ |
| 1056 | "cd", "ls", "pwd", "grep", "sed", "awk", "cat", "cp", "mv", "rm", "mkdir", "touch", |
| 1057 | "chmod", "sudo", "git", "docker", "kubectl", "curl", "wget", "read", "printf", "source", |
| 1058 | "test", "true", "false", |
| 1059 | ], |
| 1060 | ..hash_style(SHELL_KEYWORDS) |
| 1061 | }; |
| 1062 | const YAML: Grammar = Grammar { |
| 1063 | keys: true, |
| 1064 | ..hash_style(LITERALS) |
| 1065 | }; |
| 1066 | const GRAPHQL: Grammar = Grammar { |
| 1067 | types: &["String", "Int", "Float", "Boolean", "ID"], |
| 1068 | ..hash_style(GRAPHQL_KEYWORDS) |
| 1069 | }; |
| 1070 | const DOCKER: Grammar = Grammar { |
| 1071 | case_insensitive: true, |
| 1072 | ..hash_style(DOCKER_KEYWORDS) |
| 1073 | }; |
| 1074 | const POWERSHELL: Grammar = Grammar { |
| 1075 | dashed_words: true, |
| 1076 | block_comment: Some(("<#", "#>")), |
| 1077 | case_insensitive: true, |
| 1078 | ..hash_style(POWERSHELL_KEYWORDS) |
| 1079 | }; |
| 1080 | const DOS: Grammar = Grammar { |
| 1081 | line_comments: &["::", "rem ", "REM ", "@rem "], |
| 1082 | case_insensitive: true, |
| 1083 | keywords: DOS_KEYWORDS, |
| 1084 | ..CODE |
| 1085 | }; |
| 1086 | const SQL: Grammar = Grammar { |
| 1087 | types: &[ |
| 1088 | "int", |
| 1089 | "integer", |
| 1090 | "bigint", |
| 1091 | "varchar", |
| 1092 | "char", |
| 1093 | "text", |
| 1094 | "date", |
| 1095 | "timestamp", |
| 1096 | "boolean", |
| 1097 | "decimal", |
| 1098 | "count", |
| 1099 | "sum", |
| 1100 | "avg", |
| 1101 | "min", |
| 1102 | "max", |
| 1103 | "coalesce", |
| 1104 | "now", |
| 1105 | ], |
| 1106 | line_comments: &["--"], |
| 1107 | block_comment: Some(("/*", "*/")), |
| 1108 | keywords: SQL_KEYWORDS, |
| 1109 | case_insensitive: true, |
| 1110 | ..CODE |
| 1111 | }; |
| 1112 | const VHDL: Grammar = Grammar { |
| 1113 | types: &[ |
| 1114 | "std_logic", |
| 1115 | "std_logic_vector", |
| 1116 | "integer", |
| 1117 | "boolean", |
| 1118 | "unsigned", |
| 1119 | "signed", |
| 1120 | "rising_edge", |
| 1121 | ], |
| 1122 | line_comments: &["--"], |
| 1123 | keywords: VHDL_KEYWORDS, |
| 1124 | case_insensitive: true, |
| 1125 | ..CODE |
| 1126 | }; |
| 1127 | const VB: Grammar = Grammar { |
| 1128 | line_comments: &["'", "rem ", "REM "], |
| 1129 | keywords: VB_KEYWORDS, |
| 1130 | case_insensitive: true, |
| 1131 | ..CODE |
| 1132 | }; |
| 1133 | const OCTAVE: Grammar = Grammar { |
| 1134 | types: &[ |
| 1135 | "disp", "zeros", "ones", "size", "numel", "length", "plot", "printf", "fprintf", "true", |
| 1136 | "false", |
| 1137 | ], |
| 1138 | line_comments: &["%", "#"], |
| 1139 | block_comment: Some(("%{", "%}")), |
| 1140 | keywords: OCTAVE_KEYWORDS, |
| 1141 | ..CODE |
| 1142 | }; |
| 1143 | const LISP: Grammar = Grammar { |
| 1144 | types: &[ |
| 1145 | "car", "cdr", "cons", "list", "format", "print", "append", "mapcar", "funcall", "apply", |
| 1146 | ], |
| 1147 | line_comments: &[";"], |
| 1148 | block_comment: Some(("#|", "|#")), |
| 1149 | keywords: LISP_KEYWORDS, |
| 1150 | ..CODE |
| 1151 | }; |
| 1152 | const HTTP: Grammar = Grammar { |
| 1153 | keys: true, |
| 1154 | dashed_words: true, |
| 1155 | keywords: HTTP_KEYWORDS, |
| 1156 | ..CODE |
| 1157 | }; |
| 1158 | const LATEX: Grammar = Grammar { |
| 1159 | line_comments: &["%"], |
| 1160 | command_prefix: Some('\\'), |
| 1161 | ..CODE |
| 1162 | }; |
| 1163 | |
| 1164 | enum Rules { |
| 1165 | Code(&'static Grammar), |
| 1166 | Markup, |
| 1167 | Markdown, |
| 1168 | } |
| 1169 | |
| 1170 | /// The rules for a code block language: one arm per Teams language id (see |
| 1171 | /// `teams_core::CODE_LANGUAGES`); a language without an arm stays plain. |
| 1172 | fn rules_for(language: &str) -> Option<Rules> { |
| 1173 | let id = teams_core::code_language(language).map_or_else( |
| 1174 | || language.to_ascii_lowercase(), |
| 1175 | |known| known.id.to_ascii_lowercase(), |
| 1176 | ); |
| 1177 | let grammar = match id.as_str() { |
| 1178 | "html" | "xml" | "jsp" => return Some(Rules::Markup), |
| 1179 | "markdown" => return Some(Rules::Markdown), |
| 1180 | "bash" => &SHELL, |
| 1181 | "c" | "objectivec" => &C, |
| 1182 | "cpp" => &CPP, |
| 1183 | "csharp" => &CSHARP, |
| 1184 | "css" | "scss" | "less" => &CSS, |
| 1185 | "dart" => &DART, |
| 1186 | "dockerfile" => &DOCKER, |
| 1187 | "dos" => &DOS, |
| 1188 | "go" => &GO, |
| 1189 | "graphql" => &GRAPHQL, |
| 1190 | "http" => &HTTP, |
| 1191 | "java" => &JAVA, |
| 1192 | "javascript" | "jsx" | "typescript" => &JS, |
| 1193 | "json" => &JSON, |
| 1194 | "kotlin" => &KOTLIN, |
| 1195 | "kql" => &KQL, |
| 1196 | "latex" => &LATEX, |
| 1197 | "lisp" => &LISP, |
| 1198 | "octave" => &OCTAVE, |
| 1199 | "perl" => &PERL, |
| 1200 | "php" => &PHP, |
| 1201 | "powershell" => &POWERSHELL, |
| 1202 | "python" => &PYTHON, |
| 1203 | "r" => &R, |
| 1204 | "ruby" => &RUBY, |
| 1205 | "rust" => &RUST, |
| 1206 | "scala" => &SCALA, |
| 1207 | "sql" | "tsql" | "plsql" => &SQL, |
| 1208 | "swift" => &SWIFT, |
| 1209 | "vbnet" | "vbscript" => &VB, |
| 1210 | "verilog" => &VERILOG, |
| 1211 | "vhdl" => &VHDL, |
| 1212 | "yaml" | "toml" => &YAML, |
| 1213 | _ => return None, |
| 1214 | }; |
| 1215 | Some(Rules::Code(grammar)) |
| 1216 | } |
| 1217 | |
| 1218 | pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> { |
| 1219 | Some(match rules_for(language)? { |
| 1220 | Rules::Code(grammar) => highlight_code(code, grammar), |
| 1221 | Rules::Markup => highlight_markup(code), |
| 1222 | Rules::Markdown => highlight_markdown(code), |
| 1223 | }) |
| 1224 | } |
| 1225 | |
| 1226 | /// Keywords whose next word is the name being defined. |
| 1227 | const DEFINITIONS: &[&str] = &[ |
| 1228 | "class", |
| 1229 | "def", |
| 1230 | "enum", |
| 1231 | "fn", |
| 1232 | "fun", |
| 1233 | "func", |
| 1234 | "function", |
| 1235 | "interface", |
| 1236 | "module", |
| 1237 | "object", |
| 1238 | "protocol", |
| 1239 | "struct", |
| 1240 | "sub", |
| 1241 | "trait", |
| 1242 | "type", |
| 1243 | ]; |
| 1244 | |
| 1245 | /// Only spaces, or a YAML list dash, before `at` on its line. |
| 1246 | fn starts_line(code: &str, at: usize) -> bool { |
| 1247 | let line = &code[code[..at].rfind('\n').map_or(0, |end| end + 1)..at]; |
| 1248 | matches!(line.trim(), "" | "-") |
| 1249 | } |
| 1250 | |
| 1251 | /// Followed by `:` (not `::`) after optional spaces. |
| 1252 | fn before_colon(code: &str, end: usize) -> bool { |
| 1253 | let rest = code[end..].trim_start_matches([' ', '\t']); |
| 1254 | rest.starts_with(':') && !rest.starts_with("::") |
| 1255 | } |
| 1256 | |
| 1257 | fn highlight_code(code: &str, grammar: &Grammar) -> Vec<(Range<usize>, Token)> { |
| 1258 | let mut tokens = Vec::new(); |
| 1259 | let mut index = 0; |
| 1260 | let mut defines = false; |
| 1261 | while index < code.len() { |
| 1262 | let rest = &code[index..]; |
| 1263 | if let Some((open, close)) = grammar.block_comment |
| 1264 | && rest.starts_with(open) |
| 1265 | { |
| 1266 | let end = rest[open.len()..].find(close).map_or(code.len(), |offset| { |
| 1267 | index + open.len() + offset + close.len() |
| 1268 | }); |
| 1269 | tokens.push((index..end, Token::Comment)); |
| 1270 | index = end; |
| 1271 | continue; |
| 1272 | } |
| 1273 | let line_start = index == 0 || code.as_bytes()[index - 1] == b'\n'; |
| 1274 | if grammar.line_comments.iter().any(|marker| { |
| 1275 | rest.starts_with(marker) |
| 1276 | // A word comment such as `rem ` only counts at the start of a line. |
| 1277 | && (!marker.ends_with(' ') || line_start || code[..index].ends_with(' ')) |
| 1278 | }) { |
| 1279 | let end = rest.find('\n').map_or(code.len(), |offset| index + offset); |
| 1280 | tokens.push((index..end, Token::Comment)); |
| 1281 | index = end; |
| 1282 | continue; |
| 1283 | } |
| 1284 | let character = rest.chars().next().unwrap_or_default(); |
| 1285 | if character == '\'' && grammar.char_quotes && !is_char_literal(rest) { |
| 1286 | index += 1; |
| 1287 | continue; |
| 1288 | } |
| 1289 | if matches!(character, '"' | '\'' | '`') { |
| 1290 | let end = string_end(code, index, character); |
| 1291 | let key = grammar.keys && before_colon(code, end); |
| 1292 | tokens.push(( |
| 1293 | index..end, |
| 1294 | if key { Token::Attribute } else { Token::String }, |
| 1295 | )); |
| 1296 | index = end; |
| 1297 | continue; |
| 1298 | } |
| 1299 | if character.is_ascii_digit() { |
| 1300 | let length = rest |
| 1301 | .find(|next: char| !(next.is_ascii_alphanumeric() || next == '.' || next == '_')) |
| 1302 | .unwrap_or(rest.len()); |
| 1303 | tokens.push((index..index + length, Token::Number)); |
| 1304 | index += length; |
| 1305 | continue; |
| 1306 | } |
| 1307 | let command = grammar.command_prefix == Some(character); |
| 1308 | if character.is_alphabetic() || matches!(character, '_' | '$' | '@' | '#') || command { |
| 1309 | let dashed = grammar.dashed_words; |
| 1310 | let length = character.len_utf8() |
| 1311 | + rest[character.len_utf8()..] |
| 1312 | .find(|next: char| { |
| 1313 | !(next.is_alphanumeric() || next == '_' || dashed && next == '-') |
| 1314 | }) |
| 1315 | .unwrap_or(rest.len() - character.len_utf8()); |
| 1316 | let length = rest[..length].trim_end_matches('-').len(); |
| 1317 | let word = &rest[..length]; |
| 1318 | let same = |known: &&str| { |
| 1319 | if grammar.case_insensitive { |
| 1320 | known.eq_ignore_ascii_case(word) |
| 1321 | } else { |
| 1322 | *known == word |
| 1323 | } |
| 1324 | }; |
| 1325 | let end = index + length; |
| 1326 | let token = if command && length > 1 || grammar.keywords.iter().any(same) { |
| 1327 | Some(Token::Keyword) |
| 1328 | } else if grammar.keys && starts_line(code, index) && before_colon(code, end) { |
| 1329 | Some(Token::Attribute) |
| 1330 | } else if defines { |
| 1331 | Some(Token::Title) |
| 1332 | } else if grammar.types.iter().any(same) || dashed && word.contains('-') { |
| 1333 | Some(Token::Type) |
| 1334 | } else { |
| 1335 | None |
| 1336 | }; |
| 1337 | defines = token == Some(Token::Keyword) && DEFINITIONS.iter().any(same); |
| 1338 | tokens.extend(token.map(|token| (index..end, token))); |
| 1339 | index = end; |
| 1340 | continue; |
| 1341 | } |
| 1342 | if !character.is_whitespace() { |
| 1343 | defines = false; |
| 1344 | } |
| 1345 | index += character.len_utf8(); |
| 1346 | } |
| 1347 | tokens |
| 1348 | } |
| 1349 | |
| 1350 | /// HTML and XML: tag names, attribute names, quoted values and comments. |
| 1351 | fn highlight_markup(code: &str) -> Vec<(Range<usize>, Token)> { |
| 1352 | let mut tokens = Vec::new(); |
| 1353 | let mut index = 0; |
| 1354 | while let Some(offset) = code[index..].find('<') { |
| 1355 | let start = index + offset; |
| 1356 | let rest = &code[start..]; |
| 1357 | if rest.starts_with("<!--") { |
| 1358 | let end = rest.find("-->").map_or(code.len(), |at| start + at + 3); |
| 1359 | tokens.push((start..end, Token::Comment)); |
| 1360 | index = end; |
| 1361 | continue; |
| 1362 | } |
| 1363 | let name_start = start + 1 + usize::from(rest[1..].starts_with(['/', '!', '?'])); |
| 1364 | let name_end = name_start |
| 1365 | + code[name_start..] |
| 1366 | .find(|next: char| { |
| 1367 | !(next.is_alphanumeric() || matches!(next, '-' | ':' | '_' | '.')) |
| 1368 | }) |
| 1369 | .unwrap_or(code.len() - name_start); |
| 1370 | if name_end == name_start { |
| 1371 | index = start + 1; |
| 1372 | continue; |
| 1373 | } |
| 1374 | tokens.push((name_start..name_end, Token::Tag)); |
| 1375 | let close = code[name_end..] |
| 1376 | .find('>') |
| 1377 | .map_or(code.len(), |at| name_end + at); |
| 1378 | let mut at = name_end; |
| 1379 | while at < close { |
| 1380 | let character = code[at..].chars().next().unwrap_or_default(); |
| 1381 | if matches!(character, '"' | '\'') { |
| 1382 | let end = code[at + 1..close] |
| 1383 | .find(character) |
| 1384 | .map_or(close, |end| at + 1 + end + 1); |
| 1385 | tokens.push((at..end, Token::String)); |
| 1386 | at = end; |
| 1387 | } else if character.is_alphabetic() { |
| 1388 | let end = at |
| 1389 | + code[at..close] |
| 1390 | .find(|next: char| { |
| 1391 | !(next.is_alphanumeric() || matches!(next, '-' | ':' | '_')) |
| 1392 | }) |
| 1393 | .unwrap_or(close - at); |
| 1394 | tokens.push((at..end, Token::Attribute)); |
| 1395 | at = end; |
| 1396 | } else { |
| 1397 | at += character.len_utf8(); |
| 1398 | } |
| 1399 | } |
| 1400 | index = (close + 1).min(code.len()); |
| 1401 | } |
| 1402 | tokens |
| 1403 | } |
| 1404 | |
| 1405 | /// Markdown by line: headings, quotes, list markers, fenced code, then inline code, bold, |
| 1406 | /// italic and links. |
| 1407 | fn highlight_markdown(code: &str) -> Vec<(Range<usize>, Token)> { |
| 1408 | let mut tokens = Vec::new(); |
| 1409 | let mut fenced = false; |
| 1410 | let mut start = 0; |
| 1411 | for line in code.split('\n') { |
| 1412 | let range = start..start + line.len(); |
| 1413 | start = range.end + 1; |
| 1414 | let trimmed = line.trim_start(); |
| 1415 | let indent = range.start + line.len() - trimmed.len(); |
| 1416 | if trimmed.starts_with("```") || trimmed.starts_with("~~~") { |
| 1417 | fenced = !fenced; |
| 1418 | tokens.push((range, Token::String)); |
| 1419 | continue; |
| 1420 | } |
| 1421 | if fenced { |
| 1422 | tokens.push((range, Token::String)); |
| 1423 | continue; |
| 1424 | } |
| 1425 | let hashes = trimmed.bytes().take_while(|byte| *byte == b'#').count(); |
| 1426 | if (1..=6).contains(&hashes) && trimmed[hashes..].starts_with(' ') { |
| 1427 | tokens.push((range, Token::Heading)); |
| 1428 | continue; |
| 1429 | } |
| 1430 | if trimmed.starts_with('>') { |
| 1431 | tokens.push((range, Token::Comment)); |
| 1432 | continue; |
| 1433 | } |
| 1434 | let marker = list_marker(trimmed); |
| 1435 | if marker > 0 { |
| 1436 | tokens.push((indent..indent + marker, Token::Keyword)); |
| 1437 | } |
| 1438 | inline_markdown(code, indent + marker..range.end, &mut tokens); |
| 1439 | } |
| 1440 | tokens |
| 1441 | } |
| 1442 | |
| 1443 | /// Byte length of a `- `, `* `, `+ ` or `1. ` list marker. |
| 1444 | fn list_marker(line: &str) -> usize { |
| 1445 | if line.starts_with(['-', '*', '+']) && line[1..].starts_with(' ') { |
| 1446 | return 1; |
| 1447 | } |
| 1448 | let digits = line.bytes().take_while(u8::is_ascii_digit).count(); |
| 1449 | if digits > 0 && line[digits..].starts_with(". ") { |
| 1450 | digits + 1 |
| 1451 | } else { |
| 1452 | 0 |
| 1453 | } |
| 1454 | } |
| 1455 | |
| 1456 | fn inline_markdown(code: &str, range: Range<usize>, tokens: &mut Vec<(Range<usize>, Token)>) { |
| 1457 | let mut index = range.start; |
| 1458 | while index < range.end { |
| 1459 | let rest = &code[index..range.end]; |
| 1460 | let span = |open: &str, close: &str| { |
| 1461 | rest.strip_prefix(open)? |
| 1462 | .find(close) |
| 1463 | .filter(|length| *length > 0) |
| 1464 | .map(|length| index + open.len() + length + close.len()) |
| 1465 | }; |
| 1466 | let found = if rest.starts_with('`') { |
| 1467 | span("`", "`").map(|end| (end, Token::String)) |
| 1468 | } else if rest.starts_with("**") || rest.starts_with("__") { |
| 1469 | span(&rest[..2], &rest[..2]).map(|end| (end, Token::Strong)) |
| 1470 | } else if rest.starts_with(['*', '_']) { |
| 1471 | span(&rest[..1], &rest[..1]).map(|end| (end, Token::Emphasis)) |
| 1472 | } else if rest.starts_with('[') { |
| 1473 | rest.find("](") |
| 1474 | .and_then(|label| { |
| 1475 | rest[label..] |
| 1476 | .find(')') |
| 1477 | .map(|close| index + label + close + 1) |
| 1478 | }) |
| 1479 | .map(|end| (end, Token::Link)) |
| 1480 | } else { |
| 1481 | None |
| 1482 | }; |
| 1483 | match found { |
| 1484 | Some((end, token)) => { |
| 1485 | tokens.push((index..end, token)); |
| 1486 | index = end; |
| 1487 | } |
| 1488 | None => index += rest.chars().next().map_or(1, char::len_utf8), |
| 1489 | } |
| 1490 | } |
| 1491 | } |
| 1492 | |
| 1493 | fn is_char_literal(rest: &str) -> bool { |
| 1494 | let mut characters = rest.chars().skip(1); |
| 1495 | match characters.next() { |
| 1496 | Some('\\') => characters.take(9).any(|character| character == '\''), |
| 1497 | Some('\n') | None => false, |
| 1498 | Some(_) => characters.next() == Some('\''), |
| 1499 | } |
| 1500 | } |
| 1501 | |
| 1502 | fn string_end(code: &str, start: usize, quote: char) -> usize { |
| 1503 | let mut escaped = false; |
| 1504 | for (offset, character) in code[start + quote.len_utf8()..].char_indices() { |
| 1505 | if character == '\n' && quote != '`' { |
| 1506 | return start + quote.len_utf8() + offset; |
| 1507 | } |
| 1508 | if escaped { |
| 1509 | escaped = false; |
| 1510 | } else if character == '\\' { |
| 1511 | escaped = true; |
| 1512 | } else if character == quote { |
| 1513 | return start + quote.len_utf8() + offset + character.len_utf8(); |
| 1514 | } |
| 1515 | } |
| 1516 | code.len() |
| 1517 | } |
| 1518 | |
| 1519 | #[cfg(test)] |
| 1520 | mod tests { |
| 1521 | use super::*; |
| 1522 | |
| 1523 | fn kinds<'a>(code: &'a str, language: &str) -> Vec<(&'a str, Token)> { |
| 1524 | highlight(code, language) |
| 1525 | .unwrap() |
| 1526 | .into_iter() |
| 1527 | .map(|(range, token)| (&code[range], token)) |
| 1528 | .collect() |
| 1529 | } |
| 1530 | |
| 1531 | #[test] |
| 1532 | fn rust_keywords_strings_and_comments() { |
| 1533 | assert_eq!( |
| 1534 | kinds("// x\nfn a() { \"b\" }", "rust"), |
| 1535 | vec![ |
| 1536 | ("// x", Token::Comment), |
| 1537 | ("fn", Token::Keyword), |
| 1538 | ("a", Token::Title), |
| 1539 | ("\"b\"", Token::String), |
| 1540 | ] |
| 1541 | ); |
| 1542 | } |
| 1543 | |
| 1544 | #[test] |
| 1545 | fn escaped_quote_stays_in_string() { |
| 1546 | assert_eq!(kinds(r#""a\"b" 1"#, "js")[0].0, r#""a\"b""#); |
| 1547 | } |
| 1548 | |
| 1549 | #[test] |
| 1550 | fn unterminated_string_stops_at_line_end() { |
| 1551 | assert_eq!( |
| 1552 | kinds("x = 'abc\nreturn", "python"), |
| 1553 | vec![("'abc", Token::String), ("return", Token::Keyword)] |
| 1554 | ); |
| 1555 | } |
| 1556 | |
| 1557 | #[test] |
| 1558 | fn rust_lifetime_is_not_a_string() { |
| 1559 | assert_eq!( |
| 1560 | kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"), |
| 1561 | vec![ |
| 1562 | ("fn", Token::Keyword), |
| 1563 | ("a", Token::Title), |
| 1564 | ("str", Token::Type), |
| 1565 | ("char", Token::Type), |
| 1566 | ("'c'", Token::String), |
| 1567 | ] |
| 1568 | ); |
| 1569 | assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]); |
| 1570 | } |
| 1571 | |
| 1572 | #[test] |
| 1573 | fn sql_keywords_ignore_case() { |
| 1574 | assert_eq!(kinds("SELECT 1", "sql")[0], ("SELECT", Token::Keyword)); |
| 1575 | } |
| 1576 | |
| 1577 | #[test] |
| 1578 | fn unknown_language_has_no_highlight() { |
| 1579 | assert!(highlight("x", "brainfuck").is_none()); |
| 1580 | assert!(highlight("x", "plaintext").is_none()); |
| 1581 | } |
| 1582 | |
| 1583 | #[test] |
| 1584 | fn identifier_with_digits_is_not_a_number() { |
| 1585 | assert!(kinds("let x1 = 2;", "rust").contains(&("2", Token::Number))); |
| 1586 | assert!( |
| 1587 | !kinds("let x1 = 2;", "rust") |
| 1588 | .iter() |
| 1589 | .any(|(text, _)| *text == "1") |
| 1590 | ); |
| 1591 | } |
| 1592 | |
| 1593 | #[test] |
| 1594 | fn every_teams_language_but_plain_text_has_rules() { |
| 1595 | let missing: Vec<_> = teams_core::CODE_LANGUAGES |
| 1596 | .iter() |
| 1597 | .filter(|language| language.id != teams_core::PLAIN_LANGUAGE) |
| 1598 | .filter(|language| rules_for(language.id).is_none()) |
| 1599 | .map(|language| language.id) |
| 1600 | .collect(); |
| 1601 | assert!(missing.is_empty(), "no highlighting for {missing:?}"); |
| 1602 | } |
| 1603 | |
| 1604 | #[test] |
| 1605 | fn markup_colours_tags_attributes_and_values() { |
| 1606 | assert_eq!( |
| 1607 | kinds("<a href=\"x\">t</a><!-- c -->", "html"), |
| 1608 | vec![ |
| 1609 | ("a", Token::Tag), |
| 1610 | ("href", Token::Attribute), |
| 1611 | ("\"x\"", Token::String), |
| 1612 | ("a", Token::Tag), |
| 1613 | ("<!-- c -->", Token::Comment), |
| 1614 | ] |
| 1615 | ); |
| 1616 | } |
| 1617 | |
| 1618 | #[test] |
| 1619 | fn markdown_colours_its_blocks_and_inline_marks() { |
| 1620 | assert_eq!( |
| 1621 | kinds( |
| 1622 | "# Title\n- **b** and *i* `c` [l](u)\n> q\n```\nx\n```", |
| 1623 | "md" |
| 1624 | ), |
| 1625 | vec", Token::Link), |
| 1632 | ("> q", Token::Comment), |
| 1633 | ("```", Token::String), |
| 1634 | ("x", Token::String), |
| 1635 | ("```", Token::String), |
| 1636 | ] |
| 1637 | ); |
| 1638 | } |
| 1639 | |
| 1640 | #[test] |
| 1641 | fn definitions_types_and_keys() { |
| 1642 | assert_eq!( |
| 1643 | kinds("def f(self): print(1)", "python"), |
| 1644 | vec![ |
| 1645 | ("def", Token::Keyword), |
| 1646 | ("f", Token::Title), |
| 1647 | ("self", Token::Type), |
| 1648 | ("print", Token::Type), |
| 1649 | ("1", Token::Number), |
| 1650 | ] |
| 1651 | ); |
| 1652 | assert_eq!( |
| 1653 | kinds("func ok() bool", "go"), |
| 1654 | vec![ |
| 1655 | ("func", Token::Keyword), |
| 1656 | ("ok", Token::Title), |
| 1657 | ("bool", Token::Type) |
| 1658 | ] |
| 1659 | ); |
| 1660 | assert_eq!( |
| 1661 | kinds("{\"a\": \"b\"}", "json"), |
| 1662 | vec![("\"a\"", Token::Attribute), ("\"b\"", Token::String)] |
| 1663 | ); |
| 1664 | assert_eq!( |
| 1665 | kinds("name: x\nurl: http://y", "yaml"), |
| 1666 | vec![("name", Token::Attribute), ("url", Token::Attribute)] |
| 1667 | ); |
| 1668 | assert_eq!( |
| 1669 | kinds(" font-size: 2px;", "css")[0], |
| 1670 | ("font-size", Token::Attribute) |
| 1671 | ); |
| 1672 | assert_eq!( |
| 1673 | kinds("Get-ChildItem -Path .", "powershell")[0], |
| 1674 | ("Get-ChildItem", Token::Type) |
| 1675 | ); |
| 1676 | } |
| 1677 | |
| 1678 | #[test] |
| 1679 | fn word_comments_and_latex_commands() { |
| 1680 | assert_eq!( |
| 1681 | kinds("rem x\necho", "dos"), |
| 1682 | vec![("rem x", Token::Comment), ("echo", Token::Keyword)] |
| 1683 | ); |
| 1684 | assert_eq!( |
| 1685 | kinds("\\section{a} % c", "latex"), |
| 1686 | vec![("\\section", Token::Keyword), ("% c", Token::Comment)] |
| 1687 | ); |
| 1688 | assert_eq!(kinds("FROM x", "dockerFile")[0], ("FROM", Token::Keyword)); |
| 1689 | } |
| 1690 | } |