Public: anyone can read this; the crew can change it.

Load highlighter grammars lazily behind an async loader (#16804 follow-up) #17271

opened this

Closed 2d 7h ago

mason/forge:mason/17107-load-highlighter-grammars-lazily-behind → main 8 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +120 −34
src/web/diff-syntax.ts +12 −9
@@ -11,8 +11,9 @@ import { blobForRender } from "../git/read.ts";
1111 import {
1212 INITIAL_SCAN,
1313 detectLanguage,
14 highlightLines,
15 scanOneLine,
14 highlightWith,
15 loadScanner,
16 scanWith,
1617 type ScanState,
1718 type Token,
1819 } from "./highlight.ts";
@@ -41,18 +42,18 @@ export async function diffSyntax(
4142 if (file.oldPath) {
4243 const blob = await blobForRender(dir, oldRev, file.oldPath, CAP_BYTES);
4344 if (blob.kind === "text") {
44 entry.old = highlightLines(
45 entry.old = highlightWith(
46 await loadScanner(detectLanguage(file.oldPath)),
4547 new TextDecoder().decode(blob.body),
46 detectLanguage(file.oldPath),
4748 );
4849 }
4950 }
5051 if (file.newPath) {
5152 const blob = await blobForRender(dir, newRev, file.newPath, CAP_BYTES);
5253 if (blob.kind === "text") {
53 entry.new = highlightLines(
54 entry.new = highlightWith(
55 await loadScanner(detectLanguage(file.newPath)),
5456 new TextDecoder().decode(blob.body),
55 detectLanguage(file.newPath),
5657 );
5758 }
5859 }
@@ -72,13 +73,15 @@ export async function diffSyntax(
7273 * plain state, so its first lines may colour differently from a whole-file
7374 * pass. `diffSyntax` keeps that exactness for the pull page.
7475 */
75 export function hunkSyntax(diff: Diff): SyntaxMap {
76 export async function hunkSyntax(diff: Diff): Promise<SyntaxMap> {
7677 const map: SyntaxMap = new Map();
7778 for (const file of diff.files.slice(0, MAX_DIFF_FILES)) {
7879 if (file.binary || stubFor(file) !== null) continue;
7980 const entry: FileTokens = {};
8081 const oldLang = file.oldPath ? detectLanguage(file.oldPath) : null;
8182 const newLang = file.newPath ? detectLanguage(file.newPath) : null;
83 const oldScan = oldLang ? await loadScanner(oldLang) : null;
84 const newScan = newLang ? await loadScanner(newLang) : null;
8285 for (const hunk of file.hunks) {
8386 let oldState = INITIAL_SCAN;
8487 let newState = INITIAL_SCAN;
@@ -93,7 +96,7 @@ export function hunkSyntax(diff: Diff): SyntaxMap {
9396 isPlain(oldState) &&
9497 isPlain(newState);
9598 if (line.oldNumber !== null && oldLang) {
96 const scanned = scanOneLine(line.content, oldLang, oldState);
99 const scanned = scanWith(oldScan, line.content, oldState);
97100 oldTokens = scanned.tokens;
98101 oldState = scanned.state;
99102 if (shared) newTokens = oldTokens;
@@ -102,7 +105,7 @@ export function hunkSyntax(diff: Diff): SyntaxMap {
102105 if (newTokens) {
103106 newState = oldState;
104107 } else {
105 const scanned = scanOneLine(line.content, newLang, newState);
108 const scanned = scanWith(newScan, line.content, newState);
106109 newTokens = scanned.tokens;
107110 newState = scanned.state;
108111 }
src/web/highlight.ts +11 −4
@@ -28,9 +28,9 @@
2828 *
2929 * This file is the door; the work is in `highlight/`, one module a concept:
3030 * `tokens` (the vocabulary and the sink), `state` (what a line hands the
31 * next), `detect` (which language a file is), `scanners` (the entry points), `specs` and
32 * `generic` (the table-driven scanner), and one module for each of Markdown,
33 * YAML, TOML/INI, HTML, CSS, diff, Makefile and Dockerfile.
31 * next), `detect` (which language a file is), `scanners` (the entry points), `loader` (one grammar,
32 * loaded on demand), `specs` and `generic` (the table-driven scanner), and one module for each of
33 * Markdown, YAML, TOML/INI, HTML, CSS, diff, Makefile and Dockerfile.
3434 */
3535
3636 export type { TokenClass, TokenKind, Token, Language } from "./highlight/tokens.ts";
@@ -41,4 +41,11 @@ export {
4141 detectLanguage,
4242 languageFromFirstLine,
4343 } from "./highlight/detect.ts";
44 export { scanOneLine, highlightLines } from "./highlight/scanners.ts";
44 export {
45 scanOneLine,
46 scanWith,
47 highlightLines,
48 highlightWith,
49 } from "./highlight/scanners.ts";
50 export { loadScanner } from "./highlight/loader.ts";
51 export type { Scanner } from "./highlight/state.ts";
src/web/highlight/generic.ts +7 −1
@@ -3,7 +3,7 @@ import { isAlphaCh, isDigitCh, isIdentCh, isSpaceCh, isUpperCh, set } from "./ch
33 import { consumeStringBody, pushString, scanNumber, spaceRun } from "./lexing.ts";
44 import { scanTagAttributes } from "./tagattrs.ts";
55 import { type LangSpec } from "./specs.ts";
6 import { type Heredoc, type ScanState, type Scanned } from "./state.ts";
6 import { type Heredoc, type ScanState, type Scanned, type Scanner } from "./state.ts";
77 import { Out, type TokenClass, type TokenKind } from "./tokens.ts";
88
99 /** Shell words after which the next word is a command again. */
@@ -451,3 +451,9 @@ export function scanJsxTag(line: string, at: number, out: Out): number {
451451 }
452452
453453 // ---- Markdown ----
454
455 /** The table-driven scanner bound to one language's spec. */
456 export const genericScanner =
457 (spec: LangSpec): Scanner =>
458 (line, state) =>
459 scanGeneric(line, spec, state);
src/web/highlight/loader.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * Grammars on demand. A file of one kind needs one grammar, so each family is
3 * its own `import()`: the module system holds the loaded grammar (nothing is
4 * kept here), and a process that never opens a Dockerfile never parses the
5 * Dockerfile scanner. The scan itself stays synchronous: load once, then
6 * `scanWith` / `highlightWith` as often as needed.
7 */
8 import type { Scanner } from "./state.ts";
9 import type { Language } from "./tokens.ts";
10
11 /** The scanner for `lang`, or null where the language is plain or unknown. */
12 export async function loadScanner(lang: Language): Promise<Scanner | null> {

This switch duplicates scannerFor in scanners.ts, so there are two ways to pick a grammar. Keep only this one, and say how embedded-language scanners get preloaded.

13 switch (lang) {
14 case "markdown":
15 return (await import("./markdown.ts")).scanMarkdown;
16 case "yaml":
17 return (await import("./yaml.ts")).scanYaml;
18 case "toml":
19 case "ini":
20 return (await import("./toml.ts")).tomlScanner(lang === "toml");
21 case "html":
22 return (await import("./html.ts")).scanHtml;
23 case "css":
24 return (await import("./css.ts")).scanCss;
25 case "diff":
26 return (await import("./diff.ts")).scanDiff;
27 case "makefile":
28 return (await import("./makefile.ts")).scanMakefile;
29 case "dockerfile":
30 return (await import("./dockerfile.ts")).scanDockerfile;
31 case "plain":
32 return null;
33 default: {
34 const spec = (await import("./specs.ts")).SPECS[lang];
35 if (!spec) return null;
36 return (await import("./generic.ts")).genericScanner(spec);
37 }
38 }
39 }
src/web/highlight/scanners.ts +20 −12
@@ -5,18 +5,16 @@
55 import { scanCss } from "./css.ts";

The static imports of every grammar start here. While they stay, loadScanner defers nothing. Move the last callers and delete this switch (the issue's own goal).

66 import { scanDiff } from "./diff.ts";
77 import { scanDockerfile } from "./dockerfile.ts";
8 import { scanGeneric } from "./generic.ts";
8 import { genericScanner } from "./generic.ts";
99 import { scanHtml } from "./html.ts";
1010 import { scanMakefile } from "./makefile.ts";
1111 import { scanMarkdown } from "./markdown.ts";
1212 import { SPECS } from "./specs.ts";
13 import { INITIAL_SCAN, type ScanState, type Scanned } from "./state.ts";
14 import { scanToml } from "./toml.ts";
13 import { INITIAL_SCAN, type ScanState, type Scanned, type Scanner } from "./state.ts";
14 import { tomlScanner } from "./toml.ts";
1515 import { tok, type Language, type Token } from "./tokens.ts";
1616 import { scanYaml } from "./yaml.ts";
1717
18 type Scanner = (line: string, state: ScanState) => Scanned;
19
2018 function scannerFor(lang: Language): Scanner | null {
2119 switch (lang) {
2220 case "markdown":
@@ -24,10 +22,8 @@ function scannerFor(lang: Language): Scanner | null {
2422 case "yaml":
2523 return scanYaml;
2624 case "toml":
27 case "ini": {
28 const toml = lang === "toml";
29 return (line, state) => scanToml(line, state, toml);
30 }
25 case "ini":
26 return tomlScanner(lang === "toml");
3127 case "html":
3228 return scanHtml;
3329 case "css":
@@ -43,7 +39,7 @@ function scannerFor(lang: Language): Scanner | null {
4339 default: {
4440 const spec = SPECS[lang];
4541 if (!spec) return null;
46 return (line, state) => scanGeneric(line, spec, state);
42 return genericScanner(spec);
4743 }
4844 }
4945 }
@@ -65,14 +61,26 @@ export function scanOneLine(
6561 lang: Language,
6662 state: ScanState,
6763 ): Scanned {
68 const scan = scannerFor(lang);
64 return scanWith(scannerFor(lang), line, state);
65 }
66
67 /** `scanOneLine` for a scanner already in hand (`loadScanner`); null is plain. */
68 export function scanWith(
69 scan: Scanner | null,
70 line: string,
71 state: ScanState,
72 ): Scanned {
6973 if (!scan) return { tokens: [tok("plain", line)], state };
7074 return scan(line, state);
7175 }
7276
7377 export function highlightLines(code: string, lang: Language): Token[][] {
78 return highlightWith(scannerFor(lang), code);
79 }
80
81 /** `highlightLines` for a scanner already in hand (`loadScanner`); null is plain. */
82 export function highlightWith(scan: Scanner | null, code: string): Token[][] {
7483 const lines = code.split("\n");
75 const scan = scannerFor(lang);
7684 if (!scan) return lines.map((line) => [tok("plain", line)]);
7785
7886 const out: Token[][] = [];
src/web/highlight/state.ts +3
@@ -55,3 +55,6 @@ export interface Scanned {
5555 tokens: Token[];
5656 state: ScanState;
5757 }
58
59 /** A loaded grammar: one line and the state before it in, tokens and the state after out. */
60 export type Scanner = (line: string, state: ScanState) => Scanned;
src/web/highlight/toml.ts +7 −1
@@ -1,6 +1,6 @@
11 /** TOML and INI scanner. */
22 import { consumeStringBody } from "./lexing.ts";
3 import { type ScanState, type Scanned } from "./state.ts";
3 import { type ScanState, type Scanned, type Scanner } from "./state.ts";
44 import { Out } from "./tokens.ts";
55 import { scanConfigValue } from "./value.ts";
66
@@ -67,3 +67,9 @@ export function scanTomlRest(
6767 }
6868
6969 // ---- HTML ----
70
71 /** The TOML scanner, or the INI one: the grammars differ in one flag. */
72 export const tomlScanner =
73 (toml: boolean): Scanner =>
74 (line, state) =>
75 scanToml(line, state, toml);
src/web/pages/commits.ts +1 −1
@@ -341,7 +341,7 @@ export async function commitPage(ctx: Ctx): Promise<Response> {
341341 ? diffResult.value
342342 : { files: [], additions: 0, deletions: 0 };
343343 const highlighting = performance.now();
344 const syntax = hunkSyntax(diff);
344 const syntax = await hunkSyntax(diff);
345345 notePhase(ctx.request, "highlight", performance.now() - highlighting);
346346
347347 const checked = await checking;
test/diff-syntax-hunks.test.ts +6 −6
@@ -23,23 +23,23 @@ function patch(path: string, oldLines: string[], newLines: string[]): string {
2323 ].join("\n");
2424 }
2525
26 test("a hunk's tokens equal the whole-file tokens at its line numbers", () => {
26 test("a hunk's tokens equal the whole-file tokens at its line numbers", async () => {
2727 const diff = parseUnifiedDiff(patch("a.ts", OLD, NEW));
28 const got = hunkSyntax(diff).get("a.ts")!;
28 const got = (await hunkSyntax(diff)).get("a.ts")!;
2929 const lang = detectLanguage("a.ts");
3030 expect(got.old).toEqual(highlightLines(OLD.join("\n"), lang));
3131 expect(got.new).toEqual(highlightLines(NEW.join("\n"), lang));
3232 });
3333
34 test("only the hunk's lines are tokenised", () => {
34 test("only the hunk's lines are tokenised", async () => {
3535 const text = patch("a.ts", OLD, NEW).replace("@@ -1,4 +1,4 @@", "@@ -101,4 +101,4 @@");
36 const got = hunkSyntax(parseUnifiedDiff(text)).get("a.ts")!;
36 const got = (await hunkSyntax(parseUnifiedDiff(text))).get("a.ts")!;
3737 expect(got.new![0]).toBeUndefined();
3838 expect(got.new![100]).toBeDefined();
3939 expect(got.new![103]).toBeDefined();
4040 });
4141
42 test("20 files of 800 lines: only the 7-line hunks are tokenised", () => {
42 test("20 files of 800 lines: only the 7-line hunks are tokenised", async () => {
4343 const body = Array.from({ length: 800 }, (_, i) => `const v${i} = foo("s${i}", ${i}); // c`);
4444 const parts: string[] = [];
4545 for (let f = 0; f < 20; f++) {
@@ -62,7 +62,7 @@ test("20 files of 800 lines: only the 7-line hunks are tokenised", () => {
6262 }
6363 const diff = parseUnifiedDiff(parts.join("\n"));
6464 expect(diff.files.length).toBe(20);
65 const map = hunkSyntax(diff);
65 const map = await hunkSyntax(diff);
6666 expect(map.size).toBe(20);
6767 // Work done, not wall time: one token row per drawn line per side. Each
6868 // hunk draws 7 old and 7 new lines (6 shared context + 1 changed each),
test/highlight-entry.test.ts +14
@@ -27,3 +27,17 @@ test("every language scans losslessly through its scanner", () => {
2727 expect(one.tokens.map((t) => t.text).join("")).toBe("x = 1");
2828 }
2929 });
30
31 test("a loaded scanner tokenizes exactly as the language-named entry points", async () => {
32 const sample = "a = 1 # x\n\"s\" <b> {k: v}\n/* c\n";
33 for (const lang of highlight.LANGUAGES) {
34 const scan = await highlight.loadScanner(lang);
35 expect(highlight.highlightWith(scan, sample)).toEqual(
36 highlight.highlightLines(sample, lang),
37 );
38 expect(highlight.scanWith(scan, "x = 1", highlight.INITIAL_SCAN)).toEqual(
39 highlight.scanOneLine("x = 1", lang, highlight.INITIAL_SCAN),
40 );
41 }
42 expect(await highlight.loadScanner("plain")).toBeNull();
43 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs