Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

embeddedScripts.ts

748 lines24.1 KB

1import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
2import {
3 parse,
4 type Command,
5 type DoubleQuotedChild,
6 type HereDoc,
7 type Word,
8 type WordPart,
9} from "unbash";
10​
11/** starts[i]..ends[i] spans the original spelling of text[i], including escapes. */
12export interface EmbeddedScript {
13 readonly language: string;
14 readonly text: string;
15 readonly starts: ReadonlyArray<number>;
16 readonly ends: ReadonlyArray<number>;
18​
19export interface SyntaxToken {
20 readonly content: string;
21 readonly offset: number;
22 readonly color?: string;
23 readonly fontStyle?: number;
25​
26type TokenLines = ReadonlyArray<ReadonlyArray<SyntaxToken>>;
27​
28interface MappedText {
29 readonly text: string;
30 readonly starts: ReadonlyArray<number>;
31 readonly ends: ReadonlyArray<number>;
33​
34interface Interpreter {
35 readonly language: string;
36 readonly inline: (flag: string) => boolean;
37 readonly optionalInline?: ReadonlySet<string>;
38 readonly shortFlags?: RegExp;
39 readonly valueOptions?: ReadonlySet<string>;
40 readonly scriptFileOptions?: ReadonlySet<string>;
41 /** A script file named `-` is read from stdin. */
42 readonly stdinScriptFile?: boolean;
43 readonly stdin: "always" | "without-script-file" | "never";
44 readonly positionalScript?: number;
45 readonly repeatable?: boolean;
46 readonly subcommand?: string;
47 /** PowerShell matches parameters case-insensitively; the lists above are lowercase. */
48 readonly ignoreCase?: boolean;
50​
51const MAX_DEPTH = 4;
52​
53const flagIn =
54 (...flags: string[]) =>
55 (flag: string) =>
56 flags.includes(flag);
57​
58const SHELL: Interpreter = {
59 language: "shellscript",
60 inline: (flag) => /^-[a-zA-Z]*c[a-zA-Z]*$/u.test(flag),
61 valueOptions: new Set(["-o", "-O", "--rcfile", "--init-file"]),
62 stdin: "without-script-file",
63};
64​
65const PYTHON: Interpreter = {
66 language: "python",
67 // Bundles like -uc and -IBc; -W and -X take a value, so a c after them is that value.
68 inline: flagIn("-c"),
69 shortFlags: /^-(?!-)[bBdEiIOPqRsStuvx]*/u,
70 valueOptions: new Set(["-W", "-X", "--check-hash-based-pycs"]),
71 scriptFileOptions: new Set(["-m"]),
72 stdin: "without-script-file",
73};
74​
75const SQL_SHELL = {
76 language: "sql",
77 valueOptions: new Set([
78 "-d",
79 "-h",
80 "-u",
81 "-U",
82 "--dbname",
83 "--host",
84 "--user",
85 "--username",
86 "-separator",
87 "-newline",
88 "-nullvalue",
89 "-init",
90 ]),
91 stdin: "always",
92 repeatable: true,
93} satisfies Omit<Interpreter, "inline">;
94​
95const INTERPRETERS: Record<string, Interpreter> = {
96 sh: SHELL,
97 bash: SHELL,
98 zsh: SHELL,
99 dash: SHELL,
100 ash: SHELL,
101 ksh: SHELL,
102 fish: {
103 language: "fish",
104 inline: flagIn("-c", "--command"),
105 // Bundles like -lc and -ic; a c after a value option such as -C or -d is that option's value.
106 shortFlags: /^-(?!-)[hilnNPv]*/u,
107 valueOptions: new Set([
108 "-C",
109 "--init-command",
110 "-d",
111 "--debug",
112 "-D",
113 "--debug-stack-frames",
114 "-o",
115 "--debug-output",
116 "-p",
117 "--profile",
118 "--profile-startup",
119 "-f",
120 "--features",
121 ]),
122 stdin: "without-script-file",
123 },
124 node: {
125 language: "javascript",
126 inline: flagIn("-e", "--eval", "-pe"),
127 optionalInline: new Set(["-p", "--print"]),
128 valueOptions: new Set([
129 "-r",
130 "--require",
131 "--import",
132 "--loader",
133 "-C",
134 "--conditions",
135 "--input-type",
136 "--env-file",
137 "--env-file-if-exists",
138 "--experimental-loader",
139 "--title",
140 "--inspect-port",
141 "--disable-warning",
142 "--unhandled-rejections",
143 "--redirect-warnings",
144 ]),
145 stdin: "without-script-file",
146 },
147 bun: { language: "typescript", inline: flagIn("-e", "--eval", "-p", "--print"), stdin: "never" },
148 deno: {
149 language: "typescript",
150 inline: () => false,
151 // `--env-file` takes its optional path only as `--env-file=path`.
152 valueOptions: new Set(["-c", "--config", "--import-map", "--ext"]),
153 stdin: "never",
154 subcommand: "eval",
155 },
156 ruby: {
157 language: "ruby",
158 // Bundles like -ne and -lane; -i, -I, -r, -C and -E take a value, so an e after them is that value.
159 inline: flagIn("-e"),
160 shortFlags: /^-(?!-)(?:[acdlnpsSUvwy]|0[0-7]{0,3}|W[0-7]?|K[\x20-\x7e]?)*/u,
161 valueOptions: new Set([
162 "-r",
163 "-I",
164 "-C",
165 "-E",
166 "--encoding",
167 "--external-encoding",
168 "--internal-encoding",
169 "--enable",
170 "--disable",
171 ]),
172 stdin: "without-script-file",
173 repeatable: true,
174 },
175 perl: {
176 language: "perl",
177 // Bundles like -pe and -0777ne; in -pie or -Me the e is the value of -i or -M.
178 inline: flagIn("-e", "-E"),
179 shortFlags: /^-(?!-)(?:[acdfgnpsStTuUwWX]|0[0-7]{0,3}|l0?[0-7]{0,3})*/u,
180 // -M and -m take their module only attached (`-Mstrict`).
181 valueOptions: new Set(["-I"]),
182 stdin: "without-script-file",
183 repeatable: true,
184 },
185 osascript: {
186 language: "applescript",
187 inline: flagIn("-e"),
188 valueOptions: new Set(["-l", "-s"]),
189 stdin: "without-script-file",
190 repeatable: true,
191 },
192 pwsh: {
193 language: "powershell",
194 inline: flagIn("-c", "-command"),
195 valueOptions: new Set(["-executionpolicy", "-workingdirectory", "-windowstyle"]),
196 scriptFileOptions: new Set(["-f", "-file", "-encodedcommand"]),
197 stdin: "never",
198 ignoreCase: true,
199 },
200 psql: {
201 ...SQL_SHELL,
202 inline: flagIn("-c", "--command"),
203 // Bundles like -Atc and -Xtf; a c or f after -d, -h, -U and the like is that option's value.
204 shortFlags: /^-(?!-)[aAbeEHlnqsStwWxXz01]*/u,
205 scriptFileOptions: new Set(["-f", "--file"]),
206 stdinScriptFile: true,
207 },
208 mysql: {
209 ...SQL_SHELL,
210 inline: flagIn("-e", "--execute"),
211 // Bundles like -Ne and -sNe; an e after -D, -h, -u and the like is that option's value.
212 shortFlags: /^-(?!-)[AbBcCEfGHinNoqrstUvVwWX]*/u,
213 },
214 sqlite3: { ...SQL_SHELL, inline: flagIn("-cmd"), positionalScript: 1 },
215 duckdb: {
216 ...SQL_SHELL,
217 inline: flagIn("-c", "-cmd", "-s"),
218 scriptFileOptions: new Set(["-f"]),
219 positionalScript: 1,
220 },
221};
222INTERPRETERS.powershell = INTERPRETERS.pwsh!;
223INTERPRETERS.mariadb = INTERPRETERS.mysql!;
224​
225const JXA: Interpreter = { ...INTERPRETERS.osascript!, language: "javascript" };
226​
227/** `osascript -l JavaScript` runs JXA; the last `-l` option wins, and the name is case-sensitive. */
228function isJxa(args: ReadonlyArray<Word>): boolean {
229 let language = "AppleScript";
230 for (let index = 0; index < args.length; index += 1) {
231 const value = args[index]!.value;
232 if (value === "-l") language = args[++index]?.value ?? language;
233 else if (value.startsWith("-l")) language = value.slice(2);
234 else if (value === "-e" || value === "-s") index += 1;
235 else if (!value.startsWith("-") || value === "-" || value === "--") break;
236 }
237 return language === "JavaScript";
239​
240const PROGRAM_WRAPPERS: Record<string, ReadonlySet<string>> = {
241 env: new Set(["-u", "--unset", "-C", "--chdir"]),
242 sudo: new Set([
243 "-u",
244 "--user",
245 "-g",
246 "--group",
247 "-C",
248 "--close-from",
249 "-D",
250 "--chdir",
251 "-p",
252 "--prompt",
253 "-h",
254 "--host",
255 "-r",
256 "--role",
257 "-t",
258 "--type",
259 "-T",
260 "--command-timeout",
261 "-R",
262 "--chroot",
263 ]),
264 nice: new Set(["-n", "--adjustment"]),
265 nohup: new Set(),
266 exec: new Set(["-a"]),
267 command: new Set(),
268 builtin: new Set(),
269 timeout: new Set(["-k", "--kill-after", "-s", "--signal"]),
270};
271PROGRAM_WRAPPERS.gtimeout = PROGRAM_WRAPPERS.timeout!;
272​
273const DELIMITER_LANGUAGES: Record<string, string> = {
274 py: "python",
275 python: "python",
276 js: "javascript",
277 javascript: "javascript",
278 ts: "typescript",
279 typescript: "typescript",
280 sql: "sql",
281 json: "json",
282 yaml: "yaml",
283 yml: "yaml",
284 toml: "toml",
285 sh: "shellscript",
286 bash: "shellscript",
287 shell: "shellscript",
288 rb: "ruby",
289 ruby: "ruby",
290 html: "html",
291 css: "css",
292 md: "markdown",
293 markdown: "markdown",
294 xml: "xml",
295 diff: "diff",
296 patch: "diff",
297};
298​
299/** Returns nothing for commands that do not parse cleanly. */
300export function embeddedScripts(command: string): EmbeddedScript[] {
301 const identity = Array.from({ length: command.length }, (_, index) => index);
302 return scriptsIn(
303 { text: command, starts: identity, ends: identity.map((index) => index + 1) },
304 0,
305 );
307​
308function scriptsIn(source: MappedText, depth: number): EmbeddedScript[] {
309 const script = parse(source.text);
310 if (script.errors?.length) return [];
311 const found: EmbeddedScript[] = [];
312 forEachCommand(script.commands, (command) => {
313 for (const { language, mapped } of commandScripts(command, source.text)) {
314 if (mapped.text.trim() === "") continue;
315 const embedded: EmbeddedScript = {
316 language,
317 text: mapped.text,
318 starts: mapped.starts.map((start) => source.starts[start]!),
319 ends: mapped.ends.map((end) => source.ends[end - 1]!),
320 };
321 found.push(embedded);
322 if (language === "shellscript" && depth + 1 < MAX_DEPTH) {
323 found.push(...scriptsIn(embedded, depth + 1));
324 }
325 }
326 });
327 return found;
329​
330function isNode(value: unknown): value is { readonly type: string } {
331 return typeof value === "object" && value !== null && "type" in value;
333​
334function forEachCommand(
335 node: unknown,
336 visit: (command: Command) => void,
337 seen = new WeakSet<object>(),
338): void {
339 if (Array.isArray(node)) {
340 for (const child of node) forEachCommand(child, visit, seen);
341 return;
342 }
343 if (!isNode(node) || seen.has(node)) return;
344 seen.add(node);
345 switch (node.type) {
346 case "Command":
347 visit(node as Command);
348 break;
349 case "CommandExpansion":
350 case "ProcessSubstitution": {
351 const { script } = node as Extract<WordPart, { type: "CommandExpansion" }>;
352 if (script && !script.errors?.length && script.source === undefined) {
353 forEachCommand(script.commands, visit, seen);
354 }
355 return;
356 }
357 }
358 // Word parts are lazy getters, which Object.values skips.
359 if ("parts" in node) forEachCommand(node.parts, visit, seen);
360 for (const value of Object.values(node)) {
361 if (typeof value === "object") forEachCommand(value, visit, seen);
362 }
364​
365function programName(word: Word): string {
366 // Bash reads `C:\Python312\python.exe` unquoted as escapes; Windows meant a path.
367 const path = /\\/u.test(word.text) ? word.text.replace(/^["']|["']$/gu, "") : word.value;
368 return (path.split(/[\\/]/u).at(-1) ?? "").toLowerCase().replace(/\.exe$/u, "");
370​
371function interpreterFor(name: string): Interpreter | undefined {
372 if (/^python(?:\d+(?:\.\d+)?)?$|^pypy3?$|^py$/u.test(name)) return PYTHON;
373 return Object.hasOwn(INTERPRETERS, name) ? INTERPRETERS[name] : undefined;
375​
376function programIndex(words: ReadonlyArray<Word>): number {
377 let index = 0;
378 while (index < words.length) {
379 const name = programName(words[index]!);
380 if (!Object.hasOwn(PROGRAM_WRAPPERS, name)) return index;
381 const valueOptions = PROGRAM_WRAPPERS[name]!;
382 const isTimeout = name === "timeout" || name === "gtimeout";
383 index += 1;
384 let optionsEnded = false;
385 while (index < words.length) {
386 const value = words[index]!.value;
387 const isOption = !optionsEnded && value.startsWith("-");
388 if (isOption && value === "--") optionsEnded = true;
389 // `env -- FOO=1 cmd` still takes assignments after the options end.
390 if (isOption || /^[A-Za-z_]\w*=/u.test(value)) {
391 const takesValue =
392 isOption &&
393 (valueOptions.has(value) ||
394 (isTimeout && /^-[fpv]*[ks]$/u.test(value)) ||
395 (name === "env" && /^-[i0v]+[uC]$/u.test(value)) ||
396 (name === "sudo" && /^-[ABEHKNPSVbiklnsv]+[ugCDprtTR]$/u.test(value)));
397 index += takesValue ? 2 : 1;
398 } else {
399 break;
400 }
401 }
402 if (isTimeout) index += 1;
403 }
404 return index;
406​
407function commandScripts(
408 command: Command,
409 source: string,
410): Array<{ language: string; mapped: MappedText }> {
411 if (!command.name) return [];
412 const words = [command.name, ...command.args.filter((arg): arg is Word => arg.type === "Word")];
413 const index = programIndex(words);
414 const program = words[index];
415 if (!program) return [];
416 const name = programName(program);
417 const args = words.slice(index + 1);
418 const interpreter = name === "osascript" && isJxa(args) ? JXA : interpreterFor(name);
419 const scripts: Array<{ language: string; mapped: MappedText }> = [];
420​
421 let readsStdinScript = false;
422 if (interpreter) {
423 const found = interpreterArgs(interpreter, args, name);
424 for (const script of found.scripts) {
425 const mapped = wordText(script.word, source);
426 if (!mapped) continue;
427 scripts.push({ language: interpreter.language, mapped: sliceMapped(mapped, script.start) });
428 }
429 readsStdinScript =
430 interpreter.stdin !== "never" &&
431 (found.useStdin || (found.scripts.length === 0 && !found.scriptFromFile));
432 }
433​
434 const stdinLanguage = readsStdinScript ? interpreter?.language : undefined;
435 const writtenLanguage = writtenFileLanguage(name, command, args);
436 for (const redirect of command.redirects) {
437 const toStdin = isDescriptor(redirect.descriptor, 0);
438 if (redirect.type === "HereString" && toStdin && stdinLanguage && redirect.target) {
439 const mapped = wordText(redirect.target, source);
440 if (mapped) scripts.push({ language: stdinLanguage, mapped });
441 }
442 if (redirect.type === "HereDoc") {
443 const language =
444 (toStdin ? (stdinLanguage ?? writtenLanguage) : undefined) ?? delimiterLanguage(redirect);
445 if (language) scripts.push({ language, mapped: hereDocText(redirect, source) });
446 }
447 }
448 return scripts;
450​
451function isDescriptor(descriptor: HereDoc["descriptor"], fd: number): boolean {
452 return (
453 descriptor === undefined || (descriptor.type === "FileDescriptor" && descriptor.value === fd)
454 );
456​
457interface ScriptArgument {
458 readonly word: Word;
459 readonly start: number;
461​
462function interpreterArgs(
463 interpreter: Interpreter,
464 args: ReadonlyArray<Word>,
465 program: string,
466): { scripts: ScriptArgument[]; scriptFromFile: boolean; useStdin?: boolean } {
467 const positionals: Word[] = [];
468 const scripts: ScriptArgument[] = [];
469 const whole = (word: Word): ScriptArgument => ({ word, start: 0 });
470 let optionsEnded = false;
471 let scriptFromFile = false;
472 let shellInline = false;
473 let useStdin = false;
474 for (let index = 0; index < args.length; index += 1) {
475 const arg = args[index]!;
476 const flag = interpreter.ignoreCase ? arg.value.toLowerCase() : arg.value;
477 if (!optionsEnded && (flag === "--" || (shellInline && flag === "-"))) {
478 optionsEnded = true;
479 continue;
480 }
481 if (
482 !optionsEnded &&
483 (flag.startsWith("-") || (interpreter === SHELL && flag.startsWith("+"))) &&
484 flag !== "-"
485 ) {
486 let [name = flag, value] = flag.startsWith("--") ? flag.split(/=(.*)/su) : [flag];
487 const at = interpreter.shortFlags?.exec(flag)?.[0].length;
488 if (at && at < flag.length) [name, value] = [`-${flag[at]}`, flag.slice(at + 1) || undefined];
489 if (interpreter.scriptFileOptions?.has(name)) {
490 if (!interpreter.repeatable) return { scripts, scriptFromFile: true };
491 const file = value ?? args[index + 1]?.value;
492 if (file === undefined) return { scripts, scriptFromFile: true };
493 if (interpreter.stdinScriptFile && file === "-") useStdin = true;
494 // SQL shells run `-f` files and `-c` statements alike, in order.
495 scriptFromFile = true;
496 if (value === undefined) index += 1;
497 continue;
498 }
499 if (interpreter === SHELL) {
500 // bash, dash, and sh accept `--long` options only before `-c` or `-s`.
501 if ((shellInline || useStdin) && name.startsWith("--") && LONG_OPTIONS_FIRST.has(program)) {
502 return { scripts, scriptFromFile: true };
503 }
504 // zsh and ksh attach `-o` names (`-oshwordsplit`).
505 const opts = program === "zsh" || program === "ksh" ? flag.split("o", 1)[0]! : flag;
506 // `-c` makes the first operand the script, so more options may follow it.
507 if (interpreter.inline(opts)) shellInline = true;
508 // `-s` reads the script from stdin even with operands.
509 if (/^[+-][a-zA-Z]*s[a-zA-Z]*$/u.test(opts)) useStdin = opts[0] === "-";
510 if (value === undefined) index += shellOptionValues(program, flag);
511 continue;
512 }
513 const optionalInline = interpreter.optionalInline?.has(name);
514 if (optionalInline || interpreter.inline(name)) {
515 const next = args[index + 1];
516 if (optionalInline && value === undefined && (!next || next.value.startsWith("-"))) {
517 continue;
518 }
519 if (value !== undefined) scripts.push({ word: arg, start: flag.length - value.length });
520 else if (next) scripts.push(whole(next));
521 else return { scripts, scriptFromFile: true };
522 if (!interpreter.repeatable) return { scripts, scriptFromFile };
523 if (value === undefined) index += 1;
524 continue;
525 }
526 if (value === undefined && interpreter.valueOptions?.has(name)) index += 1;
527 continue;
528 }
529 if (shellInline) return { scripts: [whole(arg)], scriptFromFile: false };
530 positionals.push(arg);
531 if (interpreter.stdin === "without-script-file" && !interpreter.subcommand) break;
532 }
533 if (shellInline) return { scripts, scriptFromFile: true };
534​
535 if (interpreter.subcommand) {
536 if (positionals[0]?.value !== interpreter.subcommand) return { scripts, scriptFromFile: true };
537 return { scripts: positionals.slice(1, 2).map(whole), scriptFromFile: false };
538 }
539 if (interpreter.positionalScript !== undefined) {
540 scripts.push(...positionals.slice(interpreter.positionalScript).map(whole));
541 }
542 // SQL shells take databases as positional arguments, not script files.
543 if (interpreter.stdin === "always" || useStdin) return { scripts, scriptFromFile, useStdin };
544 const first = positionals[0];
545 return { scripts, scriptFromFile: first !== undefined && first.value !== "-" };
547​
548const LONG_OPTIONS_FIRST = new Set(["bash", "dash", "sh"]);
549​
550/** How many following words a shell option consumes as values. */
551function shellOptionValues(program: string, flag: string): number {
552 if (flag.startsWith("--")) {
553 // zsh reads the emulation mode from the word after `--emulate`.
554 if (program === "zsh") return flag === "--emulate" ? 1 : 0;
555 return (program === "bash" || program === "sh") && SHELL.valueOptions?.has(flag) ? 1 : 0;
556 }
557 // zsh and ksh take an `-o` value attached (`-oextendedglob`); other shells read one word per o or O in a bundle (`-oe pipefail`).
558 if (program === "zsh" || program === "ksh") {
559 return /^[-+][a-zA-Z]+$/u.test(flag) && flag.indexOf("o") === flag.length - 1 ? 1 : 0;
560 }
561 return /^[-+][a-zA-Z]+$/u.test(flag) ? (flag.match(/[oO]/gu)?.length ?? 0) : 0;
563​
564function sliceMapped(mapped: MappedText, start: number): MappedText {
565 if (start === 0) return mapped;
566 return {
567 text: mapped.text.slice(start),
568 starts: mapped.starts.slice(start),
569 ends: mapped.ends.slice(start),
570 };
572​
573function writtenFileLanguage(
574 name: string,
575 command: Command,
576 args: ReadonlyArray<Word>,
577): string | undefined {
578 let path: string | undefined;
579 if (name === "cat") {
580 for (const redirect of command.redirects) {
581 if (
582 redirect.type === "Redirect" &&
583 [">", ">>", ">|", "&>", "&>>"].includes(redirect.operator) &&
584 isDescriptor(redirect.descriptor, 1)
585 ) {
586 path = redirect.target?.value;
587 }
588 }
589 } else if (name === "tee") {
590 path = args.find((arg) => !arg.value.startsWith("-"))?.value;
591 }
592 if (!path) return undefined;
593 const language = getFiletypeFromFileName(path);
594 return language === "text" ? undefined : language;
596​
597function delimiterLanguage(hereDoc: HereDoc): string | undefined {
598 const name = hereDoc.delimiter?.value.toLowerCase();
599 return name && Object.hasOwn(DELIMITER_LANGUAGES, name) ? DELIMITER_LANGUAGES[name] : undefined;
601​
602function hereDocText(hereDoc: HereDoc, source: string): MappedText {
603 const { pos, end } = hereDoc.body;
604 const starts = Array.from({ length: end - pos }, (_, index) => pos + index);
605 return {
606 text: source.slice(pos, end),
607 starts,
608 ends: starts.map((start) => start + 1),
609 };
611​
612// Preserve literal expansions; return undefined for unmappable spellings.
613function wordText(word: Word, source: string): MappedText | undefined {
614 const builder = new MappedTextBuilder();
615 const parts: ReadonlyArray<WordPart> = word.parts ?? [
616 { type: "Literal", pos: word.pos, end: word.end, text: word.text, value: word.value },
617 ];
618 for (const part of parts) {
619 switch (part.type) {
620 case "Literal":
621 if (!builder.addEscaped(part, false)) return undefined;
622 break;
623 case "SingleQuoted":
624 builder.addRaw(part.value, part.pos + 1);
625 break;
626 case "DoubleQuoted":
627 case "LocaleString":
628 for (const child of part.parts) {
629 if (!builder.addDoubleQuotedChild(child)) return undefined;
630 }
631 break;
632 case "AnsiCQuoted":
633 // $'…' escapes such as \x41 do not map character for character.
634 if (part.value !== part.text.slice(2, -1)) return undefined;
635 builder.addRaw(part.value, part.pos + 2);
636 break;
637 default:
638 builder.addRaw(source.slice(part.pos, part.end), part.pos);
639 }
640 }
641 return builder.build();
643​
644class MappedTextBuilder {
645 private text = "";
646 private readonly starts: number[] = [];
647 private readonly ends: number[] = [];
648​
649 addRaw(text: string, pos: number) {
650 for (let index = 0; index < text.length; index += 1) this.push(text[index]!, pos + index, 1);
651 }
652​
653 addDoubleQuotedChild(child: DoubleQuotedChild): boolean {
654 if (child.type === "Literal") return this.addEscaped(child, true);
655 this.addRaw(child.text, child.pos);
656 return true;
657 }
658​
659 addEscaped(literal: { pos: number; text: string; value: string }, doubleQuoted: boolean) {
660 const before = this.text.length;
661 const { text, pos } = literal;
662 for (let index = 0; index < text.length; index += 1) {
663 const next = text[index + 1];
664 if (
665 text[index] === "\\" &&
666 next !== undefined &&
667 (!doubleQuoted || '$`"\\\n'.includes(next))
668 ) {
669 // A backslash-newline joins lines and spells nothing.
670 if (next !== "\n") this.push(next, pos + index, 2);
671 index += 1;
672 } else {
673 this.push(text[index]!, pos + index, 1);
674 }
675 }
676 return this.text.slice(before) === literal.value;
677 }
678​
679 build(): MappedText {
680 return { text: this.text, starts: this.starts, ends: this.ends };
681 }
682​
683 private push(character: string, start: number, length: number) {
684 this.text += character;
685 this.starts.push(start);
686 this.ends.push(start + length);
687 }
689​
690export function withEmbeddedScripts(
691 code: string,
692 lines: TokenLines,
693 embedded: ReadonlyArray<EmbeddedScript>,
694 tokenize: (text: string, language: string) => TokenLines,
695): TokenLines {
696 if (embedded.length === 0) return lines;
697 const styles = Array.from<SyntaxToken | undefined>({ length: code.length });
698 for (const token of lines.flat()) {
699 styles.fill(token, token.offset, token.offset + token.content.length);
700 }
701 for (const script of embedded) {
702 let scriptLines: TokenLines;
703 try {
704 scriptLines = tokenize(script.text, script.language);
705 } catch {
706 continue;
707 }
708 for (const token of scriptLines.flat()) {
709 if (token.content === "") continue;
710 const last = token.offset + token.content.length - 1;
711 styles.fill(token, script.starts[token.offset], script.ends[last]);
712 }
713 }
714 return restyledLines(code, styles);
716​
717function restyledLines(
718 code: string,
719 styles: ReadonlyArray<SyntaxToken | undefined>,
720): SyntaxToken[][] {
721 const lines: SyntaxToken[][] = [];
722 let start = 0;
723 for (const lineBreak of [...code.matchAll(/\r?\n/gu), undefined]) {
724 const end = lineBreak?.index ?? code.length;
725 const tokens: SyntaxToken[] = [];
726 for (let index = start; index < end;) {
727 const style = styles[index];
728 let next = index + 1;
729 while (
730 next < end &&
731 styles[next]?.color === style?.color &&
732 styles[next]?.fontStyle === style?.fontStyle
733 ) {
734 next += 1;
735 }
736 tokens.push({
737 content: code.slice(index, next),
738 offset: index,
739 ...(style?.color ? { color: style.color } : {}),
740 ...(style?.fontStyle ? { fontStyle: style.fontStyle } : {}),
741 });
742 index = next;
743 }
744 lines.push(tokens);
745 if (lineBreak) start = lineBreak.index + lineBreak[0].length;
746 }
747 return lines;