diff --git a/e2e/templateLiterals.spec.ts b/e2e/templateLiterals.spec.ts new file mode 100644 index 000000000..6210038cd --- /dev/null +++ b/e2e/templateLiterals.spec.ts @@ -0,0 +1,29 @@ +import { expect, test } from "./fixtures"; + +test("template literals highlight and comment in their embedded language", async ({ workbench: page }) => { + await page.evaluate(async () => { + const backendPath = "/src/editor/core/backend.ts"; + const contributionsPath = "/src/workbench/contributions.ts"; + const { docBackend } = await import(backendPath); + const { editorService } = await import(contributionsPath); + docBackend().files.set( + "/dev/acme-api/styles.ts", + "const Button = styled.button`\n padding: 4px;\n`;\nconst QUERY = gql`\n query Cart { total }\n`;\nconst plain = `margin: 0`;\n", + ); + await editorService().openFile("/dev/acme-api/styles.ts"); + }); + const content = page.locator('.cm-editor[data-language="TypeScript"] .cm-content'); + await expect(content).toBeVisible(); + // Each word of an embedded language is a token of its own; a plain literal stays one string. + await expect(content.locator("span").filter({ hasText: /^padding$/ })).toBeVisible(); + await expect(content.locator("span").filter({ hasText: /^query$/ })).toBeVisible(); + await expect(content.locator("span").filter({ hasText: /^`margin: 0`$/ })).toBeVisible(); + + await content.evaluate((element) => { + const view = (element as HTMLElement & { cmTile: { view: import("@codemirror/view").EditorView } }).cmTile.view; + view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("query") } }); + view.focus(); + }); + await page.keyboard.press("Meta+/"); + await expect(content).toContainText("# query Cart { total }"); +}); diff --git a/fixtures/ts-app/src/templates.ts b/fixtures/ts-app/src/templates.ts new file mode 100644 index 000000000..f39eba106 --- /dev/null +++ b/fixtures/ts-app/src/templates.ts @@ -0,0 +1,70 @@ +// Embedded languages in template literals: CSS, GraphQL, SQL and HTML are highlighted inside them. +// The tags are local stand-ins for styled-components, graphql-tag, a SQL client and Lit. + +type Tag = (strings: TemplateStringsArray, ...values: unknown[]) => string; + +const tag: Tag = (strings, ...values) => String.raw({ raw: strings }, ...values); +const css = tag; +const keyframes = tag; +const gql = tag; +const sql = tag; +const html = tag; +const styled = Object.assign((_component: unknown) => tag, { button: tag, div: tag }); + +export const fadeIn = keyframes` + from { opacity: 0; } + to { opacity: 1; } +`; + +export const Button = styled.button` + padding: 4px 12px; + color: ${() => "white"}; + background: #3574f0; + animation: ${fadeIn} 120ms ease-out; + + &:hover { + background: #4682fa; + } +`; + +export const Card = styled(Button)` + border-radius: 8px; +`; + +export const centered = css` + display: flex; + align-items: center; +`; + +export const CART_QUERY = gql` + query Cart($id: ID!, $first: Int = 10) { + cart(id: $id) { + total + items(first: $first) { + ...CartItem + } + } + } + + fragment CartItem on Item { + name + price + } +`; + +export function cartRows(cartId: string): string { + return sql` + SELECT name, price + FROM cart_items + WHERE cart_id = ${cartId} + ORDER BY price DESC + `; +} + +export function cartView(total: string): string { + return html`

Total

${total}

`; +} + +export const ITEM_FIELDS = /* GraphQL */ ` + fragment ItemFields on Item { name price } +`; diff --git a/src/editor/core/cm/angular/inline.ts b/src/editor/core/cm/angular/inline.ts index 5e496fd6d..b8e23e313 100644 --- a/src/editor/core/cm/angular/inline.ts +++ b/src/editor/core/cm/angular/inline.ts @@ -2,6 +2,7 @@ import { LanguageSupport, LRLanguage } from "@codemirror/language"; import { javascript } from "@codemirror/lang-javascript"; import { parseMixed, type Input, type NestedParse, type SyntaxNode, type SyntaxNodeRef } from "@lezer/common"; import { angular, angularLanguage } from "./index"; +import { templateInjection, type TemplateLanguageResolver } from "../templateLanguages"; function nextCode(node: SyntaxNode): SyntaxNode | null { let next = node.nextSibling; @@ -37,10 +38,11 @@ function mixTemplate(node: SyntaxNodeRef, input: Input): NestedParse | null { const typescript = javascript({ typescript: true }); -export function angularTypescript(): LanguageSupport { +export function angularTypescript(resolve: TemplateLanguageResolver): LanguageSupport { + const literals = templateInjection(resolve); // Mount on the decorator so changing its name or metadata invalidates the template too. const language = (typescript.language as LRLanguage).configure( - { wrap: parseMixed(mixTemplate) }, + { wrap: parseMixed((node, input) => mixTemplate(node, input) ?? literals(node, input)) }, "angular-typescript", ); return new LanguageSupport(language, [typescript.support, angular().support]); diff --git a/src/editor/core/cm/graphql.ts b/src/editor/core/cm/graphql.ts new file mode 100644 index 000000000..5adeefcd8 --- /dev/null +++ b/src/editor/core/cm/graphql.ts @@ -0,0 +1,195 @@ +/** + * GraphQL for template literals (`gql`, `graphql`), coloured as `.graphql` files' tree-sitter + * highlighting colours them: operation and fragment names as functions, fields as properties, + * argument names and `$variables` as variables, named types as types, enum values as + * constants and directives as annotations. + */ +import type { StreamParser, StringStream } from "@codemirror/language"; + +/** What a bracket opened: a selection set, a type's fields, an enum's values, arguments, … */ +type Scope = "selection" | "fields" | "values" | "arguments" | "variables" | "inputs" | "object" | "list"; + +interface Frame { + scope: Scope; + /** After `:` (or `=`) in this scope: a type or a value comes next. */ + colon: boolean; + /** After `=`: a default value, not a type. */ + value?: boolean; + /** For `list`: its items are types, not values. */ + types?: boolean; +} + +export interface GraphQLState { + stack: Frame[]; + /** The top-level definition being read: `type`, `enum`, `union`, `directive`, `schema` or an operation. */ + definition: string | null; + /** What the next name is, whatever the scope. */ + next: "definition" | "type" | "spread" | "location" | null; + inBlockString: boolean; +} + +const OPERATIONS = new Set(["query", "mutation", "subscription", "fragment"]); +const TYPE_DEFINITIONS = new Set(["type", "interface", "input", "scalar", "union", "enum"]); +const KEYWORDS = new Set([...OPERATIONS, ...TYPE_DEFINITIONS, "schema", "extend", "implements", "directive", "on"]); +const VALUE_KEYWORDS = new Set(["true", "false", "null"]); +const NAME = /^[_A-Za-z][_0-9A-Za-z]*/; + +function blockString(stream: StringStream, state: GraphQLState): string { + while (!stream.eol()) { + if (stream.match('\\"""') || stream.next() !== '"') continue; + if (stream.match('""')) { + state.inBlockString = false; + break; + } + } + return "string"; +} + +function open(state: GraphQLState, bracket: string) { + const top = state.stack[state.stack.length - 1]; + const definition = state.definition; + let frame: Frame; + if (bracket === "[") frame = { scope: "list", colon: false, types: isTypePosition(state) }; + else if (bracket === "{") { + const scope: Scope = !top + ? definition === "enum" + ? "values" + : definition && definition !== "operation" + ? "fields" + : "selection" + : top.colon || top.scope === "list" || top.scope === "object" || top.scope === "arguments" + ? "object" + : "selection"; + frame = { scope, colon: false }; + } else { + const typeSystem = !!definition && definition !== "operation"; + const scope: Scope = typeSystem ? "inputs" : top ? "arguments" : "variables"; + frame = { scope, colon: false }; + } + state.stack.push(frame); + state.next = null; +} + +/** Whether a name here is a type (`$id: ID`, `name: String`, `[Episode!]`). */ +function isTypePosition(state: GraphQLState): boolean { + const top = state.stack[state.stack.length - 1]; + if (!top) return false; + if (top.scope === "list") return !!top.types; + return top.colon && !top.value && (top.scope === "fields" || top.scope === "variables" || top.scope === "inputs"); +} + +/** A name, string or number was read: what follows is no longer after `:`. */ +function consumed(top: Frame | undefined) { + if (top && top.scope !== "list") top.colon = top.value = false; +} + +function name(word: string, state: GraphQLState): string | null { + const top = state.stack[state.stack.length - 1]; + const next = state.next; + if (next === "definition") { + state.next = null; + return state.definition === "operation" ? "variableName.function" : "typeName"; + } + if (next === "spread") { + if (word === "on") { + state.next = "type"; + return "keyword"; + } + state.next = null; + return "variableName.function"; + } + if (next === "type") { + state.next = null; + return "typeName"; + } + if (next === "location") { + if (/^[A-Z_]+$/.test(word)) return "variableName.constant"; + state.next = null; + } + if (!top) { + if (!KEYWORDS.has(word)) return null; + if (OPERATIONS.has(word)) { + state.definition = "operation"; + state.next = "definition"; + } else if (TYPE_DEFINITIONS.has(word)) { + state.definition = word; + state.next = "definition"; + } else if (word === "schema" || word === "directive") state.definition = word; + else if (word === "implements") state.next = "type"; + else if (word === "on") state.next = state.definition === "directive" ? "location" : "type"; + return "keyword"; + } + if (isTypePosition(state)) { + consumed(top); + return "typeName"; + } + if (top.colon || top.scope === "list") { + consumed(top); + return VALUE_KEYWORDS.has(word) ? "keyword" : "variableName.constant"; + } + switch (top.scope) { + case "values": + return "variableName.constant"; + case "arguments": + case "inputs": + return "variableName"; + default: + return "propertyName"; + } +} + +export const graphqlParser: StreamParser = { + name: "graphql", + startState: () => ({ stack: [], definition: null, next: null, inBlockString: false }), + copyState: (s) => ({ ...s, stack: s.stack.map((f) => ({ ...f })) }), + token(stream, state) { + if (state.inBlockString) return blockString(stream, state); + if (stream.eatSpace() || stream.eat(",")) return null; + if (stream.match("#")) { + stream.skipToEnd(); + return "comment"; + } + if (stream.match('"""')) { + state.inBlockString = true; + return blockString(stream, state); + } + const top = state.stack[state.stack.length - 1]; + if (stream.match(/^"(?:[^"\\]|\\.)*"?/)) { + consumed(top); + return "string"; + } + if (stream.match(/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/)) { + consumed(top); + return "number"; + } + if (stream.match(/^\$[_A-Za-z][_0-9A-Za-z]*/)) { + if (top?.scope !== "variables") consumed(top); + return "variableName"; + } + if (stream.match(/^@[_A-Za-z][_0-9A-Za-z]*/)) return "annotation"; + if (stream.match("...")) { + state.next = "spread"; + return "punctuation"; + } + const word = stream.match(NAME); + if (word) return name((word as RegExpMatchArray)[0], state); + const ch = stream.next()!; + if ("{([".includes(ch)) { + open(state, ch); + return "bracket"; + } + if ("})]".includes(ch)) { + state.stack.pop(); + consumed(state.stack[state.stack.length - 1]); + if (!state.stack.length && ch === "}") state.definition = null; + return "bracket"; + } + // In a selection set, `alias: field` names a field after the colon too. + if (ch === ":" && top && top.scope !== "selection") top.colon = true; + else if (ch === "=" && top) top.colon = top.value = true; + else if (ch === "=" && state.definition === "union") state.next = "type"; + else if ((ch === "|" || ch === "&") && !top && state.next !== "location") state.next = "type"; + return "punctuation"; + }, + languageData: { commentTokens: { line: "#" }, closeBrackets: { brackets: ["(", "[", "{", '"'] } }, +}; diff --git a/src/editor/core/cm/languages.ts b/src/editor/core/cm/languages.ts index fde5c8910..87b6dd2c8 100644 --- a/src/editor/core/cm/languages.ts +++ b/src/editor/core/cm/languages.ts @@ -12,6 +12,7 @@ import { LanguageSupport, StreamLanguage, delimitedIndent, + type Language, indentNodeProp, indentService, language as languageFacet, @@ -169,9 +170,28 @@ const OWN_MODES = [ }, }), ), + // CSS, GraphQL, SQL and HTML in tagged template literals (`styled.div`, `gql`, `sql`, `html`). + ...( + [ + ["JavaScript", {}], + ["TypeScript", { typescript: true }], + ["JSX", { jsx: true }], + ["TSX", { jsx: true, typescript: true }], + ] as const + ).map(([name, config]) => + LanguageDescription.of({ + name, + load: () => import("./templateLanguages").then((m) => m.javascriptWithTemplates(config, templateLanguage)), + }), + ), + // Only for template literals: `.graphql` files keep the backend's tree-sitter highlighting. + LanguageDescription.of({ + name: "GraphQL", + load: async () => new LanguageSupport(StreamLanguage.define((await import("./graphql")).graphqlParser)), + }), LanguageDescription.of({ name: "Angular TypeScript", - load: () => import("./angular/inline").then((m) => m.angularTypescript()), + load: () => import("./angular/inline").then((m) => m.angularTypescript(templateLanguage)), }), LanguageDescription.of({ name: "Angular Template", load: () => import("./angular").then((m) => m.angular()) }), LanguageDescription.of({ name: "Thymeleaf", load: () => import("./thymeleaf").then((m) => m.thymeleafSupport()) }), @@ -368,7 +388,17 @@ export function fencedCodeMode(info: string): FencedCodeMode | null { const uiMode = infos?.has(name) ? infos.get(name)!.uiMode : uiModeForPath(`.${name}`); desc = uiMode ? findLanguageDescription(uiMode, "") : null; } - if (!desc) return null; + return desc ? patchedMode(desc) : null; +} + +/** The mode named `name` (`CSS`, `GraphQL`) for a template literal, with the tag patches of a file in it. */ +function templateLanguage(name: string): Language | LanguageDescription | null { + const desc = findLanguageDescription(name, ""); + return desc ? patchedMode(desc).language : null; +} + +/** `desc` with the same tag patches as a file of that language, loaded on first use. */ +function patchedMode(desc: LanguageDescription): FencedCodeMode { const ready = patched.get(desc); if (ready) return { name: desc.name, language: ready.language }; // Markdown parses the block once the proxy has loaded the patched support. diff --git a/src/editor/core/cm/templateLanguages.test.ts b/src/editor/core/cm/templateLanguages.test.ts new file mode 100644 index 000000000..8c863e3d7 --- /dev/null +++ b/src/editor/core/cm/templateLanguages.test.ts @@ -0,0 +1,196 @@ +import { beforeAll, describe, expect, it } from "vitest"; +import { ensureSyntaxTree, type LanguageSupport } from "@codemirror/language"; +import { EditorState } from "@codemirror/state"; +import { highlightTree, tags as t, type Tag } from "@lezer/highlight"; +import { toggleComment } from "@codemirror/commands"; +import { findLanguageDescription, loadSupport } from "./languages"; +import { openideaHighlightStyle } from "./highlight"; + +const supports: Record = {}; + +beforeAll(async () => { + // Embedded modes load lazily; load them up front so one parse covers the literals. + for (const name of ["CSS", "GraphQL", "SQL", "HTML", "JavaScript", "TypeScript", "TSX", "Angular TypeScript"]) + supports[name] = (await loadSupport(findLanguageDescription(name, "")!))!; +}); + +function tokens(mode: string, doc: string): { text: string; cls: string }[] { + const out: { text: string; cls: string }[] = []; + highlightTree(supports[mode]!.language.parser.parse(doc), openideaHighlightStyle, (from, to, cls) => { + out.push({ text: doc.slice(from, to), cls }); + }); + return out; +} + +function expectTokens(mode: string, doc: string, expected: readonly (readonly [string, Tag])[]) { + const got = tokens(mode, doc); + for (const [text, tag] of expected) { + const cls = openideaHighlightStyle.style([tag]); + expect(cls, String(tag)).toBeTruthy(); + expect(got, text).toContainEqual({ text, cls }); + } +} + +/** No string-coloured token contains `text`: the literal's body is not one string. */ +function expectNotString(mode: string, doc: string, text: string) { + const string = openideaHighlightStyle.style([t.string]); + expect(tokens(mode, doc).filter((tok) => tok.cls === string && tok.text.includes(text))).toEqual([]); +} + +describe("template literal languages", () => { + it("highlights CSS in styled-components and emotion templates", () => { + const doc = [ + "const Button = styled.button`", + " color: ${(p) => p.color};", + " padding: 4px 8px;", + " &:hover { background: #fff; }", + "`;", + "const Link = styled(Anchor).attrs({ role: 'link' })`margin: 0;`;", + "const Global = createGlobalStyle`body { margin: 0 }`;", + "const spin = keyframes`from { opacity: 0 } to { opacity: 1 }`;", + "const mixin = css`display: flex;`;", + ].join("\n"); + expectTokens("JavaScript", doc, [ + ["color", t.attributeName], + ["padding", t.attributeName], + ["4", t.number], + ["px", t.attributeValue], + ["background", t.attributeName], + ["#fff", t.tagName], + ["margin", t.attributeName], + ["body", t.tagName], + ["opacity", t.attributeName], + ["display", t.attributeName], + ["flex", t.attributeValue], + // The substitution stays JavaScript. + ["=>", t.punctuation], + ]); + expectNotString("JavaScript", doc, "padding"); + }); + + it("follows TypeScript type arguments on the tag", () => { + expectTokens("TypeScript", "const Box = styled.div<{ gap: number }>`gap: ${(p) => p.gap}px;`;", [ + ["gap", t.attributeName], + ["number", t.typeName], + ]); + }); + + it("highlights GraphQL in gql and graphql templates and calls", () => { + const doc = [ + "const HERO = gql`", + " query Hero($id: ID!, $first: Int = 10) @cached {", + " hero(id: $id, episode: JEDI) { name friends(first: $first) { ...Friend } }", + " }", + " fragment Friend on Character { name }", + "`;", + "const Me = graphql(`query Me { me { id } }`, [Friend]);", + ].join("\n"); + expectTokens("TypeScript", doc, [ + ["query", t.keyword], + ["Hero", t.function(t.variableName)], + ["$id", t.variableName], + ["ID", t.typeName], + ["Int", t.typeName], + ["10", t.number], + ["@cached", t.annotation], + ["hero", t.propertyName], + ["episode", t.variableName], + ["JEDI", t.constant(t.variableName)], + ["Friend", t.function(t.variableName)], + ["fragment", t.keyword], + ["Character", t.typeName], + ["Me", t.function(t.variableName)], + ["me", t.propertyName], + ]); + }); + + it("highlights GraphQL schema definitions", () => { + const doc = [ + "const typeDefs = gql`", + " type Query implements Node { hero(episode: Episode = JEDI): [Character!]! }", + " enum Episode { NEWHOPE JEDI }", + " union Result = Human | Droid", + "`;", + ].join("\n"); + expectTokens("JavaScript", doc, [ + ["type", t.keyword], + ["Query", t.typeName], + ["Node", t.typeName], + ["hero", t.propertyName], + ["episode", t.variableName], + ["Episode", t.typeName], + ["Character", t.typeName], + ["NEWHOPE", t.constant(t.variableName)], + ["Human", t.typeName], + ["Droid", t.typeName], + ]); + }); + + it("highlights SQL and HTML templates", () => { + const doc = [ + "const rows = await sql`SELECT id, name FROM users WHERE id = ${id}`;", + 'const view = html``;', + ].join("\n"); + expectTokens("JavaScript", doc, [ + ["SELECT", t.keyword], + ["FROM", t.keyword], + ["WHERE", t.keyword], + ["button", t.tagName], + ["class", t.attributeName], + ['"primary"', t.attributeValue], + ]); + expectNotString("JavaScript", doc, "SELECT"); + }); + + it("highlights a literal a /* language */ comment names", () => { + expectTokens("TSX", "const q = /* GraphQL */ `query Q { a }`;\nconst s = /* sql */ `SELECT 1`;", [ + ["query", t.keyword], + ["Q", t.function(t.variableName)], + ["SELECT", t.keyword], + ]); + }); + + it("leaves other template literals strings", () => { + const doc = "const a = `color: red;`;\nconst b = tag`query Q { a }`;\nconst c = /* note */ `SELECT 1`;"; + const string = openideaHighlightStyle.style([t.string]); + for (const text of ["`color: red;`", "`query Q { a }`", "`SELECT 1`"]) + expect(tokens("JavaScript", doc)).toContainEqual({ text, cls: string }); + }); + + it("injects into Angular TypeScript files too", () => { + expectTokens( + "Angular TypeScript", + "@Component({ template: '

{{ name }}

' })\nclass A {}\nconst q = gql`query Q { a }`;", + [ + ["p", t.tagName], + ["query", t.keyword], + ], + ); + }); + + it.each([ + ["css", "tag", "const a = css`color: red;`;", "`color: red;`"], + ["GraphQL", "note", "const a = /* GraphQL */ `query Q { a }`;", "`query Q { a }`"], + ])("re-parses the literal when its %s tag changes", (from, to, doc, literal) => { + let state = EditorState.create({ doc, extensions: [supports.JavaScript!] }); + ensureSyntaxTree(state, state.doc.length, 5000); + const at = doc.indexOf(from); + state = state.update({ changes: { from: at, to: at + from.length, insert: to } }).state; + const tree = ensureSyntaxTree(state, state.doc.length, 5000)!; + const parsed: string[] = []; + highlightTree(tree, openideaHighlightStyle, (from, to) => parsed.push(state.sliceDoc(from, to))); + expect(parsed).toContain(literal); + }); + + it("comments lines with the embedded language's comment syntax", () => { + const doc = "const q = gql`\n query Q { a }\n`;"; + let state = EditorState.create({ + doc, + selection: { anchor: doc.indexOf("query") }, + extensions: [supports.JavaScript!], + }); + ensureSyntaxTree(state, state.doc.length, 5000); + toggleComment({ state, dispatch: (tr) => (state = tr.state) }); + expect(state.doc.line(2).text).toBe(" # query Q { a }"); + }); +}); diff --git a/src/editor/core/cm/templateLanguages.ts b/src/editor/core/cm/templateLanguages.ts new file mode 100644 index 000000000..8292648f2 --- /dev/null +++ b/src/editor/core/cm/templateLanguages.ts @@ -0,0 +1,146 @@ +/** + * Embedded languages in JavaScript and TypeScript template literals, as WebStorm injects them: + * CSS in styled-components / emotion / Lit (`styled.div`, `styled(Button).attrs(…)`, `css`, + * `createGlobalStyle`, `keyframes`, `injectGlobal`), GraphQL (`gql`, `graphql`, also called as + * `graphql(`…`)`), SQL (`sql`) and HTML (`html`). A `/* GraphQL *\/`-style comment right before + * a plain template literal names its language too. + * + * The literal's text between `${…}` substitutions is parsed as one document of the embedded + * language; the substitutions stay JavaScript. + */ +import { LanguageDescription, LanguageSupport, LRLanguage, ParseContext, type Language } from "@codemirror/language"; +import { javascript } from "@codemirror/lang-javascript"; +import type { LRParser } from "@lezer/lr"; +import { + parseMixed, + type Input, + type NestedParse, + type Parser, + type SyntaxNode, + type SyntaxNodeRef, +} from "@lezer/common"; + +/** A mode by `LanguageDescription` name, with the tag patches of a file in that language. */ +export type TemplateLanguageResolver = (name: string) => Language | LanguageDescription | null; + +const CSS_TAGS = new Set(["css", "createGlobalStyle", "keyframes", "injectGlobal"]); + +/** The embedded language a tag names, by mode name. */ +function tagLanguage(tag: SyntaxNode, input: Input): string | null { + if (rootName(tag, input) === "styled") return "CSS"; + const name = lastName(tag, input); + if (!name) return null; + if (CSS_TAGS.has(name)) return "CSS"; + if (name === "gql" || name === "graphql") return "GraphQL"; + if (name === "sql" || name === "SQL") return "SQL"; + if (name === "html") return "HTML"; + return null; +} + +const COMMENT_LANGUAGES: Record = { + css: "CSS", + graphql: "GraphQL", + gql: "GraphQL", + sql: "SQL", + html: "HTML", +}; + +/** The language a `/* name *\/` comment names. */ +function commentLanguage(comment: SyntaxNode, input: Input): string | null { + const name = /^\/\*\s*([A-Za-z]+)\s*\*\/$/.exec(input.read(comment.from, comment.to))?.[1]; + return (name && COMMENT_LANGUAGES[name.toLowerCase()]) ?? null; +} + +/** The identifier a tag expression starts from: `styled` in `styled(Button).attrs({})`. */ +function rootName(node: SyntaxNode, input: Input): string | null { + for (let n: SyntaxNode | null = node; n; n = n.firstChild) { + if (n.name === "VariableName") return input.read(n.from, n.to); + if (!["MemberExpression", "CallExpression", "InstantiationExpression"].includes(n.name)) return null; + } + return null; +} + +/** The name a tag expression ends with: `sql` in `sql` and `Prisma.sql`, `css` in `css`. */ +function lastName(node: SyntaxNode, input: Input): string | null { + let n: SyntaxNode | null = node; + if (n.name === "InstantiationExpression") n = n.firstChild; + if (n?.name === "MemberExpression") n = n.lastChild; + return n && (n.name === "VariableName" || n.name === "PropertyName") ? input.read(n.from, n.to) : null; +} + +/** The literal's text between the backticks, without its `${…}` substitutions. */ +function contentRanges(template: SyntaxNode, input: Input): { from: number; to: number }[] { + const ranges: { from: number; to: number }[] = []; + let from = template.from + 1; + for (const sub of template.getChildren("Interpolation")) { + if (sub.from > from) ranges.push({ from, to: sub.from }); + from = sub.to; + } + const closed = template.to - template.from > 1 && input.read(template.to - 1, template.to) === "`"; + const to = closed ? template.to - 1 : template.to; + if (to > from) ranges.push({ from, to }); + return ranges; +} + +/** Styled-components and emotion bodies are declarations and nested rules, as in a `style` attribute. */ +const declarationParsers = new WeakMap(); + +function parserFor(name: string, resolve: TemplateLanguageResolver): Parser | null { + const mode = resolve(name); + if (!mode) return null; + let language: Language; + if (mode instanceof LanguageDescription) { + if (!mode.support) return ParseContext.getSkippingParser(mode.load()); + language = mode.support.language; + } else language = mode; + if (name !== "CSS" || !(language instanceof LRLanguage)) return language.parser; + let parser = declarationParsers.get(language.parser); + if (!parser) + declarationParsers.set(language.parser, (parser = (language.parser as LRParser).configure({ top: "Styles" }))); + return parser; +} + +/** The nested parse for `node`, mounted on the tagged template or call so editing the tag re-parses it. */ +export function templateInjection(resolve: TemplateLanguageResolver) { + return (ref: SyntaxNodeRef, input: Input): NestedParse | null => { + // Called for every node on each parse: rule out the rest before materializing the node. + if (ref.name !== "TaggedTemplateExpression" && ref.name !== "CallExpression" && ref.name !== "TemplateString") + return null; + const node = ref.node; + let template: SyntaxNode | null = null; + let language: string | null = null; + if (node.name === "TaggedTemplateExpression") { + template = node.lastChild; + const tag = node.firstChild; + language = tag && template !== tag ? tagLanguage(tag, input) : null; + } else if (node.name === "CallExpression") { + // `graphql(`…`)` (gql.tada, GraphQL Code Generator's client preset). + const callee = node.firstChild; + const first = node.getChild("ArgList")?.firstChild?.nextSibling; + if (callee && first?.name === "TemplateString" && tagLanguage(callee, input) === "GraphQL") { + template = first; + language = "GraphQL"; + } + } else if (node.name === "TemplateString" && node.parent?.name !== "TaggedTemplateExpression") { + const before = node.prevSibling; + if (before?.name === "BlockComment") { + template = node; + language = commentLanguage(before, input); + } + } + if (!template || template.name !== "TemplateString" || !language) return null; + const overlay = contentRanges(template, input); + if (!overlay.length) return null; + const parser = parserFor(language, resolve); + return parser ? { parser, overlay } : null; + }; +} + +type JavaScriptConfig = NonNullable[0]>; + +/** `javascript(config)` that also parses embedded languages in template literals. */ +export function javascriptWithTemplates(config: JavaScriptConfig, resolve: TemplateLanguageResolver): LanguageSupport { + const base = javascript(config); + const language = (base.language as LRLanguage).configure({ wrap: parseMixed(templateInjection(resolve)) }); + return new LanguageSupport(language, base.support); +}