The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
fix(test): complete syntax parsing across language helpers (#2042)
Arnaud Ritti780e57d0c592
diff --git a/src/editor/core/cm/angular/angular.test.ts b/src/editor/core/cm/angular/angular.test.tsindex f24390120..99081b1e1 100644--- a/src/editor/core/cm/angular/angular.test.ts+++ b/src/editor/core/cm/angular/angular.test.ts@@ -2,10 +2,11 @@ import { describe, expect, it } from "vitest";import { readFileSync } from "node:fs";import { resolve } from "node:path";import { EditorState } from "@codemirror/state";-import { ensureSyntaxTree, foldable, matchBrackets } from "@codemirror/language";+import { foldable, matchBrackets } from "@codemirror/language";import { IterMode, NodeProp, type Tree } from "@lezer/common";import { buildParserFile } from "@lezer/generator";import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";+import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax";import { findLanguageDescription, loadSupport } from "../languages";import { angular, angularLanguage } from "./index";@@ -38,9 +39,7 @@ function tokens(doc: string, tree: Tree = angularLanguage.parser.parse(doc)): st/** The tree of `state`, parsed to the end. */function stateTree(state: EditorState): Tree {- const tree = ensureSyntaxTree(state, state.doc.length, 5000);- if (!tree) throw new Error("parse did not finish");- return tree;+ return completedSyntaxTree(state, 5000);}/** A ~6 KB template starting with an element, with blocks and `@let` at the top level. */@@ -192,8 +191,7 @@ describe("Angular templates", () => {it("matches a block's braces around its elements", () => {const doc = `@if (a) {\n <p>{{ a }}</p>\n}`;- const state = EditorState.create({ doc, extensions: angular() });- ensureSyntaxTree(state, doc.length, 5000);+ const state = completedSyntaxState(EditorState.create({ doc, extensions: angular() }));expect(matchBrackets(state, doc.indexOf("{"), 1)).toMatchObject({matched: true,end: { from: doc.lastIndexOf("}") },@@ -220,8 +218,7 @@ describe("Angular templates", () => {" }","}",].join("\n");- const state = EditorState.create({ doc, extensions: angular() });- stateTree(state);+ const state = completedSyntaxState(EditorState.create({ doc, extensions: angular() }));const folds = [];for (let n = 1; n <= state.doc.lines; n++) {const line = state.doc.line(n);diff --git a/src/editor/core/cm/cmake.test.ts b/src/editor/core/cm/cmake.test.tsindex 8a42fbf49..4adcbe76b 100644--- a/src/editor/core/cm/cmake.test.ts+++ b/src/editor/core/cm/cmake.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import { EditorState } from "@codemirror/state";-import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";+import { completedSyntaxTree } from "@/test/syntax";import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";import { findLanguageDescription, loadSupport } from "./languages";@@ -24,9 +24,8 @@ async function state(source: string) {}function tokens(state: EditorState) {- ensureSyntaxTree(state, state.doc.length, 1000);const out: { text: string; style: string }[] = [];- highlightTree(syntaxTree(state), highlighter, (from, to, style) =>+ highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) =>out.push({ text: state.doc.sliceString(from, to), style }),);return out;diff --git a/src/editor/core/cm/erb.test.ts b/src/editor/core/cm/erb.test.tsindex 2d70528e5..6ea714e68 100644--- a/src/editor/core/cm/erb.test.ts+++ b/src/editor/core/cm/erb.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import { EditorState } from "@codemirror/state";-import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";+import { completedSyntaxTree } from "@/test/syntax";import { classHighlighter, highlightTree } from "@lezer/highlight";import { findLanguageDescription, loadSupport } from "./languages";@@ -8,9 +8,8 @@ async function tokens(source: string) {const desc = findLanguageDescription("ERB", "show.html.erb")!;const support = await loadSupport(desc);const state = EditorState.create({ doc: source, extensions: [support!] });- ensureSyntaxTree(state, source.length, 1000);const result: { text: string; style: string }[] = [];- highlightTree(syntaxTree(state), classHighlighter, (from, to, style) =>+ highlightTree(completedSyntaxTree(state), classHighlighter, (from, to, style) =>result.push({ text: source.slice(from, to), style }),);return result;diff --git a/src/editor/core/cm/interpolation.test.ts b/src/editor/core/cm/interpolation.test.tsindex 817719d8b..a3dbeb2d7 100644--- a/src/editor/core/cm/interpolation.test.ts+++ b/src/editor/core/cm/interpolation.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import { EditorState } from "@codemirror/state";-import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";+import { completedSyntaxTree } from "@/test/syntax";import { classHighlighter, highlightTree } from "@lezer/highlight";import { findLanguageDescription, loadSupport, loadedSupport } from "./languages";@@ -9,9 +9,8 @@ async function tokens(mode: string, source: string) {const support = await loadSupport(desc);expect(loadedSupport(desc)).toBe(support);const state = EditorState.create({ doc: source, extensions: [support!] });- ensureSyntaxTree(state, source.length, 1000);const result: { text: string; style: string; from: number; to: number }[] = [];- highlightTree(syntaxTree(state), classHighlighter, (from, to, style) =>+ highlightTree(completedSyntaxTree(state), classHighlighter, (from, to, style) =>result.push({ text: source.slice(from, to), style, from, to }),);return result;diff --git a/src/editor/core/cm/interpolationIncremental.test.ts b/src/editor/core/cm/interpolationIncremental.test.tsindex 0d2dc0cde..c878e1f5a 100644--- a/src/editor/core/cm/interpolationIncremental.test.ts+++ b/src/editor/core/cm/interpolationIncremental.test.ts@@ -1,13 +1,12 @@import { expect, it } from "vitest";import { EditorState } from "@codemirror/state";-import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";+import { completedSyntaxTree } from "@/test/syntax";import { classHighlighter, highlightTree } from "@lezer/highlight";import { findLanguageDescription, loadSupport } from "./languages";function highlighted(state: EditorState) {- ensureSyntaxTree(state, state.doc.length, 1000);const result: { text: string; style: string }[] = [];- highlightTree(syntaxTree(state), classHighlighter, (from, to, style) => {+ highlightTree(completedSyntaxTree(state), classHighlighter, (from, to, style) => {result.push({ text: state.doc.sliceString(from, to), style });});return result;diff --git a/src/editor/core/cm/jsp/jsp.test.ts b/src/editor/core/cm/jsp/jsp.test.tsindex d18ff2b5d..16ad8e2aa 100644--- a/src/editor/core/cm/jsp/jsp.test.ts+++ b/src/editor/core/cm/jsp/jsp.test.ts@@ -2,10 +2,11 @@ import { describe, expect, it } from "vitest";import { readFileSync } from "node:fs";import { resolve } from "node:path";import { EditorState } from "@codemirror/state";-import { ensureSyntaxTree, foldable, matchBrackets } from "@codemirror/language";+import { foldable, matchBrackets } from "@codemirror/language";import type { Tree } from "@lezer/common";import { buildParserFile } from "@lezer/generator";import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";+import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax";import { findLanguageDescription, loadSupport } from "../languages";import { jsp, jspLanguage } from "./index";@@ -48,9 +49,7 @@ function errors(doc: string): string[] {/** The tree of `state`, parsed to the end. */function stateTree(state: EditorState): Tree {- const tree = ensureSyntaxTree(state, state.doc.length, 5000);- if (!tree) throw new Error("parse did not finish");- return tree;+ return completedSyntaxTree(state, 5000);}/** A ~8 KB page with directives, scriptlets around markup, expressions and EL. */@@ -95,8 +94,7 @@ describe("JSP pages", () => {"<%:pi","%>:pi",]);- const state = EditorState.create({ doc, extensions: jsp() });- stateTree(state);+ const state = completedSyntaxState(EditorState.create({ doc, extensions: jsp() }));const open = doc.indexOf("{");expect(matchBrackets(state, open, 1)?.end?.from).toBe(doc.lastIndexOf("}"));});@@ -191,8 +189,7 @@ describe("JSP pages", () => {it("comments with JSP comments in the markup and Java ones in scriptlets", () => {const doc = `<p>x</p><% int a; %>`;- const state = EditorState.create({ doc, extensions: jsp() });- stateTree(state);+ const state = completedSyntaxState(EditorState.create({ doc, extensions: jsp() }));const at = (pos: number) =>state.languageDataAt<{ line?: string; block?: { open: string } }>("commentTokens", pos)[0];expect(at(4)?.block?.open).toBe("<%--");@@ -201,8 +198,7 @@ describe("JSP pages", () => {it("folds JSP comments and scriptlets", () => {const doc = `<%--\n a\n--%>\n<%\n int a;\n%>`;- const state = EditorState.create({ doc, extensions: jsp() });- stateTree(state);+ const state = completedSyntaxState(EditorState.create({ doc, extensions: jsp() }));expect(foldable(state, 0, 4)).toEqual({ from: 4, to: doc.indexOf("--%>") });const line = state.doc.line(4);expect(foldable(state, line.from, line.to)).toEqual({ from: line.to, to: doc.lastIndexOf("%>") });diff --git a/src/editor/core/cm/rainbowBrackets.test.ts b/src/editor/core/cm/rainbowBrackets.test.tsindex 9b325d155..c8df0cfcd 100644--- a/src/editor/core/cm/rainbowBrackets.test.ts+++ b/src/editor/core/cm/rainbowBrackets.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { EditorState, type Extension } from "@codemirror/state";import { EditorView } from "@codemirror/view";-import { ensureSyntaxTree } from "@codemirror/language";+import { completedSyntaxState } from "@/test/syntax";import { languages } from "@codemirror/language-data";import { BracketScanner, bracketClass } from "./rainbowBrackets";import { heavyExtension } from "./setup";@@ -13,8 +13,7 @@ const cStyle = EditorState.languageData.of(() => [/** `char@depth` of every coloured bracket (`!` for unmatched). */function marks(doc: string, ext: Extension = [], from = 0, to = doc.length, scanner = new BracketScanner()) {- const state = EditorState.create({ doc, extensions: ext });- ensureSyntaxTree(state, doc.length, 5000);+ const state = completedSyntaxState(EditorState.create({ doc, extensions: ext }));return scanner.marks(state, from, to).map((m) => `${doc[m.from]}${m.depth < 0 ? "!" : m.depth}`);}diff --git a/src/editor/lsp/semantic/python/highlight.test.ts b/src/editor/lsp/semantic/python/highlight.test.tsindex 49f9d645a..f81a61921 100644--- a/src/editor/lsp/semantic/python/highlight.test.ts+++ b/src/editor/lsp/semantic/python/highlight.test.ts@@ -1,6 +1,6 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import { EditorState } from "@codemirror/state";-import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";+import { completedSyntaxTree } from "@/test/syntax";import { findLanguageDescription, loadSupport } from "../../../core/cm/languages";import { pythonSyntaxRanges, pythonFallbackRanges, pythonSymbolKinds } from "./highlight";import { semanticRanges } from "../index";@@ -8,11 +8,28 @@ import { semanticRanges } from "../index";async function parse(source: string) {const support = await loadSupport(findLanguageDescription("Python", "demo.py")!);const state = EditorState.create({ doc: source, extensions: [support!] });- ensureSyntaxTree(state, state.doc.length, 1000);- return state;+ return { doc: state.doc, tree: completedSyntaxTree(state) };}describe("Python PyCharm categories", () => {+ it("uses the completed tree when initial parsing exceeds its time budget", async () => {+ await parse("");+ // Exceed the initial 20 ms parse budget, but stay within ensureSyntaxTree's budget.+ let now = 0;+ const clock = vi.spyOn(Date, "now").mockImplementation(() => (now += 25));+ try {+ const state = await parse("def f(self):\n value = b'bytes'\n self.run(whatever=1)\n");+ expect(state.tree.length).toBe(state.doc.length);+ const styles = pythonSyntaxRanges(state.tree, state.doc).map((r) => [+ state.doc.sliceString(r.from, r.to),+ r.className,+ ]);+ expect(styles).toContainEqual(["whatever", "cm-sem-python-keyword-arg"]);+ } finally {+ clock.mockRestore();+ }+ });+it("distinguishes definitions, nested definitions, docstrings, self, bytes and keyword arguments", async () => {const state = await parse(`"""module doc"""def outer(x):@@ -27,7 +44,7 @@ class Foo:self.run(whatever=1)print(self.__doc__)`);- const ranges = pythonSyntaxRanges(syntaxTree(state), state.doc);+ const ranges = pythonSyntaxRanges(state.tree, state.doc);const styles = ranges.map((r) => [state.doc.sliceString(r.from, r.to), r.className]);expect(styles).toContainEqual(["outer", "cm-sem-python-definition"]);expect(styles).toContainEqual(["nested", "cm-sem-python-nested"]);@@ -42,7 +59,7 @@ class Foo:it("does not treat a locally shadowed builtin as a library symbol", async () => {const state = await parse("def f(print):\n print(1)\nlen([1])");- const ranges = pythonFallbackRanges(syntaxTree(state), state.doc);+ const ranges = pythonFallbackRanges(state.tree, state.doc);const print = ranges.filter((r) => state.doc.sliceString(r.from, r.to) === "print");expect(print.map((r) => r.className)).toEqual(["cm-sem-parameter", "cm-sem-parameter"]);expect(ranges.find((r) => state.doc.sliceString(r.from, r.to) === "len")?.className).toContain(@@ -60,7 +77,7 @@ def unused(param):def skipped(self, _hidden):return 1`);- const tree = syntaxTree(state);+ const tree = state.tree;const kinds = pythonSymbolKinds(tree, state.doc);const kindOf = (name: string) =>[...kinds]@@ -94,7 +111,7 @@ class Child(Plain):def method(self, override_a):return 2`);- const stubKinds = pythonSymbolKinds(syntaxTree(stubs), stubs.doc);+ const stubKinds = pythonSymbolKinds(stubs.tree, stubs.doc);const stubKindOf = (name: string) =>[...stubKinds].filter(([range]) => {@@ -122,7 +139,7 @@ class Child(Plain):{ tokenTypes: ["variable"], tokenModifiers: [], data: [0, 0, 5, 0, 0] },false,"python",- syntaxTree(state),+ state.tree,);expect(ranges.some((r) => r.className.includes("python-builtin"))).toBe(false);});@@ -138,7 +155,7 @@ class Child(Plain):},false,"python",- syntaxTree(state),+ state.tree,);expect(result.filter((r) => state.doc.sliceString(r.from, r.to) === "outer").map((r) => r.className)).toEqual(["cm-sem-python-definition",@@ -150,9 +167,9 @@ class Child(Plain):const state = await parse('x = "ordinary"\n"later"\ndef f():\n b"bytes"\n "later"\ndef g():\n f"format {x}"',);- expect(- pythonSyntaxRanges(syntaxTree(state), state.doc).some((r) => r.className === "cm-sem-python-docstring"),- ).toBe(false);+ expect(pythonSyntaxRanges(state.tree, state.doc).some((r) => r.className === "cm-sem-python-docstring")).toBe(+ false,+ );});it("honours Pyrefly selfParameter modifiers without applying rainbow colours", async () => {@@ -195,7 +212,7 @@ class Box[T]:def read(self) -> T:return Box.count + Box.ICON`);- const tree = syntaxTree(state);+ const tree = state.tree;const kinds = pythonSymbolKinds(tree, state.doc);const kindOf = (name: string) =>[...kinds]@@ -232,7 +249,7 @@ class Box[T]:},true,"python",- syntaxTree(state),+ state.tree,);const classOf = (name: string) =>result.filter((range) => state.doc.sliceString(range.from, range.to) === name).map((range) => range.className);diff --git a/src/features/templates/__tests__/editor.test.ts b/src/features/templates/__tests__/editor.test.tsindex 39d38ad63..fb22e6603 100644--- a/src/features/templates/__tests__/editor.test.ts+++ b/src/features/templates/__tests__/editor.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it } from "vitest";import { EditorSelection, EditorState, type Extension } from "@codemirror/state";import { EditorView, runScopeHandlers } from "@codemirror/view";-import { ensureSyntaxTree } from "@codemirror/language";+import { completedSyntaxState } from "@/test/syntax";import { languages } from "@codemirror/language-data";import { CompletionContext, autocompletion, completionStatus, hasNextSnippetField } from "@codemirror/autocomplete";import {@@ -42,8 +42,7 @@ async function editor(language: string, doc: string, cursor = doc.length, extra:...extra,],});- ensureSyntaxTree(state, doc.length, 5000);- view = new EditorView({ state, parent: document.body });+ view = new EditorView({ state: completedSyntaxState(state), parent: document.body });return view;}diff --git a/src/features/templates/__tests__/live.test.ts b/src/features/templates/__tests__/live.test.tsindex 2993f5b7b..8ef97851d 100644--- a/src/features/templates/__tests__/live.test.ts+++ b/src/features/templates/__tests__/live.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import { EditorState } from "@codemirror/state";import { snippet } from "@codemirror/autocomplete";import { languages } from "@codemirror/language-data";-import { ensureSyntaxTree } from "@codemirror/language";+import { completedSyntaxState } from "@/test/syntax";import {applicableTemplates,bodyVariables,@@ -26,8 +26,7 @@ function apply(doc: string, tpl: string, from: number, to = from) {async function stateFor(lang: string, doc: string) {const desc = languages.find((l) => l.name === lang)!;const support = await desc.load();- const state = EditorState.create({ doc, extensions: [support] });- ensureSyntaxTree(state, state.doc.length, 5000);+ const state = completedSyntaxState(EditorState.create({ doc, extensions: [support] }));return state;}diff --git a/src/features/templates/__tests__/postfix.test.ts b/src/features/templates/__tests__/postfix.test.tsindex 5ebff43d9..7aa542ece 100644--- a/src/features/templates/__tests__/postfix.test.ts+++ b/src/features/templates/__tests__/postfix.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import { EditorState } from "@codemirror/state";-import { ensureSyntaxTree } from "@codemirror/language";+import { completedSyntaxState } from "@/test/syntax";import { languages } from "@codemirror/language-data";import {candidatesFor,@@ -22,8 +22,7 @@ const MODES: Record<string, string> = {async function target(language: string, doc: string) {const desc = languages.find((l) => l.name === MODES[language])!;- const state = EditorState.create({ doc, extensions: [await desc.load()] });- ensureSyntaxTree(state, state.doc.length, 5000);+ const state = completedSyntaxState(EditorState.create({ doc, extensions: [await desc.load()] }));return findPostfixTarget(state, doc.length, language);}diff --git a/src/features/todo/todo.test.ts b/src/features/todo/todo.test.tsindex af15ef4aa..cfcc1e973 100644--- a/src/features/todo/todo.test.ts+++ b/src/features/todo/todo.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { EditorState } from "@codemirror/state";import { EditorView } from "@codemirror/view";-import { ensureSyntaxTree } from "@codemirror/language";+import { completedSyntaxState } from "@/test/syntax";import { languages } from "@codemirror/language-data";import type { FileMatches } from "@/platform/ipc";import {@@ -159,8 +159,7 @@ describe("editor highlighting", () => {it("decorates TODO comments only", async () => {const desc = languages.find((l) => l.name === "JavaScript")!;const doc = 'const TODO = "TODO";\n// TODO: refactor\n/* FIXME now */';- const state = EditorState.create({ doc, extensions: [await desc.load()] });- ensureSyntaxTree(state, doc.length, 5000);+ const state = completedSyntaxState(EditorState.create({ doc, extensions: [await desc.load()] }));const view = new EditorView({ state, parent: document.body });const ranges: Array<[number, number, string]> = [];todoDecorations(view, S).between(0, doc.length, (from, to, d) => {diff --git a/src/test/syntax.test.ts b/src/test/syntax.test.tsnew file mode 100644index 000000000..0a09860f7--- /dev/null+++ b/src/test/syntax.test.ts@@ -0,0 +1,80 @@+import { expect, it, vi } from "vitest";+import { EditorSelection, EditorState } from "@codemirror/state";+import { syntaxTree } from "@codemirror/language";+import { classHighlighter, highlightTree } from "@lezer/highlight";+import { findLanguageDescription, loadSupport } from "@/editor/core/cm/languages";+import { completedSyntaxState, completedSyntaxTree } from "./syntax";++const cases = [+ ["Python", "def f(self):\n value = b'bytes'\n self.run(whatever=1)\n"],+ ["ERB", "<div><%= user.name if user %></div>\n<% 42 %>"],+ ["CMake", "set(CMAKE_CXX_STANDARD 17)\nmessage(STATUS hello)"],+ ["Kotlin", 'val text = "${n + 1} tail"\nval after = 3'],+ ["Scala", 'val text = s"${n + 1} tail"\nval after = 3'],+ ["Dart", 'var text = "${n + 1} tail";\nvar after = 3;'],+ ["Groovy", 'def text = "${n + 1} tail"\ndef after = 3'],+ ["C#", 'var text = $"{n + 1} tail";\nvar after = 3;'],+ ["Shell", 'echo "$name $(echo $((n + 1)))"\necho 3'],+ ["JavaScript", 'function f() { return "("; } // TODO'],+ ["TypeScript", "function f(value: number) { return value + 1; }"],+ ["Java", "class Demo { int f() { return 1; } }"],+ ["Rust", "fn f() -> i32 { 1 }"],+ ["Go", "package main\nfunc f() int { return 1 }"],+ ["JSP", "<% if (ready) { %><p><%= value %></p><% } %>"],+ ["Angular Template", "@if (ready) {\n <p>{{ value }}</p>\n}"],+];++function highlights(state: EditorState) {+ const out: Array<[number, number, string]> = [];+ highlightTree(completedSyntaxTree(state), classHighlighter, (from, to, style) => out.push([from, to, style]));+ return out;+}++it.each(cases)(+ "%s completes an interrupted initial parse and publishes it for state consumers",+ async (mode, source) => {+ const doc = `${source}\n`.repeat(30);+ const support = await loadSupport(findLanguageDescription(mode!, "")!);+ expect(support).toBeTruthy();+ const create = () => EditorState.create({ doc, selection: EditorSelection.cursor(2), extensions: [support!] });+ const expected = highlights(create());+ expect(expected.length).toBeGreaterThan(0);+ let now = 0;+ // Force initial parsing to yield, then let completion run without clock pressure.+ const clock = vi.spyOn(Date, "now");+ const interrupted = () => {+ clock.mockImplementation(() => (now += 25));+ const state = create();+ clock.mockReturnValue(now);+ return state;+ };+ try {+ const initial = interrupted();+ expect(syntaxTree(initial).length).toBeLessThan(initial.doc.length);+ const tree = completedSyntaxTree(initial);+ expect(tree.length).toBe(initial.doc.length);+ expect(syntaxTree(initial).length).toBeLessThan(initial.doc.length);+ expect(highlights(initial)).toEqual(expected);++ const state = completedSyntaxState(interrupted());+ expect(syntaxTree(state).length).toBe(state.doc.length);+ expect(state.selection.main.head).toBe(2);+ expect(state.doc.toString()).toBe(doc);+ expect(highlights(state)).toEqual(expected);+ const edited = state.update({ changes: { from: 0, insert: "\n" } }).state;+ const fresh = EditorState.create({ doc: edited.doc, extensions: [support!] });+ expect(highlights(edited)).toEqual(highlights(fresh));+ } finally {+ clock.mockRestore();+ }+ },+);++it("preserves states without a language for lexical fallback tests", () => {+ const state = EditorState.create({ doc: "f(a[b])" });+ expect(completedSyntaxState(state)).toBe(state);+});++it("fails explicitly when a tree cannot be completed", () => {+ expect(() => completedSyntaxTree(EditorState.create())).toThrow("Test syntax parsing did not finish");+});diff --git a/src/test/syntax.ts b/src/test/syntax.tsnew file mode 100644index 000000000..0bfafe239--- /dev/null+++ b/src/test/syntax.ts@@ -0,0 +1,17 @@+import { ensureSyntaxTree, language, syntaxTree } from "@codemirror/language";+import type { EditorState } from "@codemirror/state";++export function completedSyntaxTree(state: EditorState, timeout = 1000) {+ const tree = ensureSyntaxTree(state, state.doc.length, timeout);+ if (!tree) throw new Error("Test syntax parsing did not finish");+ return tree;+}++export function completedSyntaxState(state: EditorState, timeout = 5000) {+ if (!state.facet(language)) return state;+ const tree = completedSyntaxTree(state, timeout);+ // A transaction snapshots the completed parse context into the immutable state.+ const parsed = state.update({}).state;+ if (syntaxTree(parsed) !== tree) throw new Error("Test state did not publish the completed syntax tree");+ return parsed;+}