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

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

opened this

Merged 38h 17m ago, live in production

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

  • Merged. mason/17107-load-highlighter-grammars-lazily-behind was merged into main as 49c2c02.

Review

Sign in to review this change.
6 files changed +81 −48
src/web/highlight/generic.ts +1 −25
@@ -1,6 +1,6 @@
11 /** The table-driven scanner most languages use. */
22 import { isAlphaCh, isDigitCh, isIdentCh, isSpaceCh, isUpperCh, set } from "./chars.ts";
3 import { consumeStringBody, pushString, scanNumber, spaceRun } from "./lexing.ts";
3 import { consumeStringBody, pushString, readVariable, scanNumber, spaceRun } from "./lexing.ts";
44 import { scanTagAttributes } from "./tagattrs.ts";
55 import { type LangSpec } from "./specs.ts";
66 import { type Heredoc, type ScanState, type Scanned } from "./state.ts";
@@ -403,30 +403,6 @@ export function scanGeneric(
403403 return { tokens: out.done(), state: next };
404404 }
405405
406 /** `$name`, `${expr}`, `$(cmd)`, `@ivar`, `@@cvar`, `$1`. */
407 export function readVariable(line: string, at: number): number {
408 const n = line.length;
409 let i = at + 1;
410 if (line.charCodeAt(at) === 64 && line.charCodeAt(i) === 64) i++; // @@cvar
411 const c = line.charCodeAt(i);
412 if (c === 123 /* { */ || c === 40 /* ( */) {
413 const close = c === 123 ? 125 : 41;
414 let depth = 1;
415 i++;
416 while (i < n && depth > 0) {
417 const d = line.charCodeAt(i);
418 if (d === c) depth++;
419 else if (d === close) depth--;
420 i++;
421 }
422 return i;
423 }
424 if (isDigitCh(c) || c === 42 || c === 64 || c === 63 || c === 35)
425 return i + 1;
426 while (i < n && isIdentCh(line.charCodeAt(i))) i++;
427 return i;
428 }
429
430406 /**
431407 * A JSX element's opening or closing tag. Returns where it ends, or `at` if
432408 * this `<` was not markup after all. Inside the tag, names and attributes get
src/web/highlight/lexing.ts +25 −2
@@ -1,6 +1,5 @@
11 /** Scanning helpers shared by every scanner: strings, numbers, indentation. */
2 import { isAlphaCh, isDigitCh, isSpaceCh } from "./chars.ts";
3 import { readVariable } from "./generic.ts";
2 import { isAlphaCh, isDigitCh, isIdentCh, isSpaceCh } from "./chars.ts";
43 import { Out, type TokenClass, type TokenKind } from "./tokens.ts";
54
65 /** Consume a string body from `start`, honouring escapes. */
@@ -152,3 +151,27 @@ export function indentOf(line: string): number {
152151 }
153152
154153 // ---- the generic scanner ----

Nit: this header names the generic scanner, but what follows is readVariable, a shared lexing helper. Drop or rename the header.

154
155 /** `$name`, `${expr}`, `$(cmd)`, `@ivar`, `@@cvar`, `$1`. */
156 export function readVariable(line: string, at: number): number {
157 const n = line.length;
158 let i = at + 1;
159 if (line.charCodeAt(at) === 64 && line.charCodeAt(i) === 64) i++; // @@cvar
160 const c = line.charCodeAt(i);
161 if (c === 123 /* { */ || c === 40 /* ( */) {
162 const close = c === 123 ? 125 : 41;
163 let depth = 1;
164 i++;
165 while (i < n && depth > 0) {
166 const d = line.charCodeAt(i);
167 if (d === c) depth++;
168 else if (d === close) depth--;
169 i++;
170 }
171 return i;
172 }
173 if (isDigitCh(c) || c === 42 || c === 64 || c === 63 || c === 35)
174 return i + 1;
175 while (i < n && isIdentCh(line.charCodeAt(i))) i++;
176 return i;
177 }
src/web/highlight/makefile.ts +1 −1
@@ -1,6 +1,6 @@
11 /** Makefile scanner. */
22 import { scanOneLine } from "./scanners.ts";
3 import { readVariable } from "./generic.ts";
3 import { readVariable } from "./lexing.ts";
44 import { INITIAL_SCAN, type ScanState, type Scanned } from "./state.ts";
55 import { Out } from "./tokens.ts";
66
src/web/highlight/scanners.ts +21 −18
@@ -2,47 +2,50 @@
22 * The entry points that run a scanner: one line, or a whole file. Each
33 * language maps to its grammar's scanner, and a scan is synchronous.
44 */
5 import { scanCss } from "./css.ts";
6 import { scanDiff } from "./diff.ts";
7 import { scanDockerfile } from "./dockerfile.ts";
8 import { scanGeneric } from "./generic.ts";
9 import { scanHtml } from "./html.ts";
10 import { scanMakefile } from "./makefile.ts";
11 import { scanMarkdown } from "./markdown.ts";
12 import { SPECS } from "./specs.ts";
135 import { INITIAL_SCAN, type ScanState, type Scanned } from "./state.ts";
outdated

Every grammar is still imported statically here, so the dynamic imports in loader.ts are no-ops and the pull's goal is not met. Drop these imports and the duplicate scannerFor switch; loadScanner should be the single mapping.

14 import { scanToml } from "./toml.ts";
156 import { tok, type Language, type Token } from "./tokens.ts";
16 import { scanYaml } from "./yaml.ts";
177
188 type Scanner = (line: string, state: ScanState) => Scanned;
199
10 /**
11 * The one switch from a language to its scanner, and where grammars load.
12 *
13 * Each family is `require`d on first use, so a process that never opens a
14 * Dockerfile never parses the Dockerfile scanner: Bun evaluates a required
15 * module when the call runs, not at import, and `Bun.build` bundles the same
16 * literal paths for the browser. A scan stays synchronous, so no caller
17 * changes colour or timing; the module system holds what has loaded. Nothing
18 * else in this directory may import a grammar statically from here
19 * (`test/highlight-entry.test.ts` fails if one does).
20 */
2021 function scannerFor(lang: Language): Scanner | null {
2122 switch (lang) {
2223 case "markdown":
23 return scanMarkdown;
24 return (require("./markdown.ts") as typeof import("./markdown.ts")).scanMarkdown;
2425 case "yaml":
25 return scanYaml;
26 return (require("./yaml.ts") as typeof import("./yaml.ts")).scanYaml;
2627 case "toml":
2728 case "ini": {
29 const { scanToml } = require("./toml.ts") as typeof import("./toml.ts");
2830 const toml = lang === "toml";
2931 return (line, state) => scanToml(line, state, toml);
3032 }
3133 case "html":
32 return scanHtml;
34 return (require("./html.ts") as typeof import("./html.ts")).scanHtml;
3335 case "css":
34 return scanCss;
36 return (require("./css.ts") as typeof import("./css.ts")).scanCss;
3537 case "diff":
36 return scanDiff;
38 return (require("./diff.ts") as typeof import("./diff.ts")).scanDiff;
3739 case "makefile":
38 return scanMakefile;
40 return (require("./makefile.ts") as typeof import("./makefile.ts")).scanMakefile;
3941 case "dockerfile":
40 return scanDockerfile;
42 return (require("./dockerfile.ts") as typeof import("./dockerfile.ts")).scanDockerfile;
4143 case "plain":
4244 return null;
4345 default: {
44 const spec = SPECS[lang];
46 const spec = (require("./specs.ts") as typeof import("./specs.ts")).SPECS[lang];
4547 if (!spec) return null;
48 const { scanGeneric } = require("./generic.ts") as typeof import("./generic.ts");
4649 return (line, state) => scanGeneric(line, spec, state);
4750 }
4851 }
test/highlight-entry.test.ts +29 −1
@@ -1,4 +1,4 @@
1 import { expect, test } from "bun:test";
1 import { describe, expect, test } from "bun:test";
22 import * as highlight from "../src/web/highlight.ts";
33
44 test("the highlight door keeps its public names", () => {
@@ -27,3 +27,31 @@ test("every language scans losslessly through its scanner", () => {
2727 expect(one.tokens.map((t) => t.text).join("")).toBe("x = 1");
2828 }
2929 });
30
31 describe("grammars load on first use (#17107)", () => {
32 const run = (body: string) => {
33 const door = JSON.stringify(new URL("../src/web/highlight.ts", import.meta.url).pathname);
34 const script = `
35 const { highlightLines } = await import(${door});
36 const loaded = () => Object.keys(require.cache).map((k) => k.split("/").pop()).filter((n) => /^(dockerfile|yaml|css|markdown|html|specs|generic|toml|diff|makefile)\\.ts$/.test(n)).sort();
37 const before = loaded();
38 ${body}
39 console.log(JSON.stringify({ before, after: loaded() }));`;
40 const out = Bun.spawnSync(["bun", "-e", script]).stdout.toString();
41 return JSON.parse(out) as { before: string[]; after: string[] };
42 };
43
44 test("importing the door parses no grammar", () => {
45 expect(run("").before).toEqual([]);
46 });
47
48 test("scanning one language parses only its own family", () => {
49 expect(run('highlightLines("FROM x", "dockerfile");').after).toEqual([
50 "dockerfile.ts",
51 "generic.ts",
52 "specs.ts",
53 ]);
54 expect(run('highlightLines("a: 1", "yaml");').after).toEqual(["yaml.ts"]);
55 expect(run('highlightLines("x", "plain");').after).toEqual([]);
56 });
57 });
test/launch-no-tla.test.ts +4 −1
@@ -11,8 +11,11 @@ import { join } from "node:path";
1111 * The generated duty list is the one literal relative require(): a duty reaches the runner, which
1212 * imports the roster, so a static import would be a cycle, and `bun build` bundles only a literal
1313 * path. It loaded the same files by require() before (src/maintain/registry.ts).
14 * The highlighter's scanner switch is the other: scannerFor is synchronous and its callers are too,
15 * so it requires each grammar family on first use. Those modules are leaves of plain data and
16 * regexes, with no top-level await anywhere in their graph.
1417 */
15 const LITERAL_REQUIRE = new Set(["generated/duties.ts"]);
18 const LITERAL_REQUIRE = new Set(["generated/duties.ts", "web/highlight/scanners.ts"]);
1619
1720 const walk = (d: string): string[] =>
1821 readdirSync(d).flatMap((n) => {

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

Keyboard shortcuts

Docs