Compare commits

...
Author SHA1 Message Date
l0ng-ai ed4998c236 test: make four tests pass on Windows
Windows CI on main failed four tests the earlier clippy error had hidden:
- pipenv naming hashed a Unix path, which Windows joins with a backslash;
  the Windows expectation now uses a Windows path.
- the VIRTUAL_ENV assertion joined "member/.override" as one component.
- the diagnostics coalescing tests slept 30 ms for a 16 ms flush, too short
  for Windows timers; they wait for the flush with a deadline.
- the patch preview test read automatic mappings while new folders could
  still be re-indexing (automatic mappings pause then); it waits for indexing.
2026-11-24 15:25:24 +08:00
LU XIANGRUIandLU XIANGRUI 97e9657fd3 feat(editor): highlight JPQL, SQL and SpEL in Spring annotation strings (#5565)
- Java parses the string values of Spring Data JPA @Query (JPQL, or SQL with
  nativeQuery = true), @Value / @ConditionalOnExpression (SpEL #{...} and
  property placeholders ${...}), and the SpEL attributes of @PreAuthorize,
  @PostAuthorize, @PreFilter, @PostFilter, @Cacheable, @CachePut, @CacheEvict
- annotations are matched by their imported or qualified class, so other
  annotations named Query stay plain strings
- escape sequences stay outside the embedded text and keep the string colours

Co-authored-by: LU XIANGRUI <[email protected]>
2026-11-24 14:57:35 +08:00
LU XIANGRUIandLU XIANGRUI 1205ffecd2 fix(editor): leave Java statement labels uncoloured, as IntelliJ does (#5564)
Co-authored-by: LU XIANGRUI <[email protected]>
2026-11-24 14:54:09 +08:00
8 changed files with 467 additions and 5 deletions

No files matched your search

+8
View File
@@ -432,6 +432,14 @@ async fn patches_read_and_write_the_requested_repository() {
})
.collect::<String>();
let root = Some(roots[0].clone());
// Automatic mappings wait for indexing; the new folders and exclude rule may start a rescan.
tokio::time::sleep(Duration::from_millis(200)).await;
for _ in 0..500 {
if !project.index.status().indexing {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let preview = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.clone(), None, None).await.unwrap();
assert!(preview.files.iter().all(|file| file.applies && !file.missing_base));
assert_eq!(preview.automatic_mappings.len(), 1);
+3
View File
@@ -1605,7 +1605,10 @@ mod pipenv_tests {
#[test]
fn environments_are_named_as_pipenv_names_them() {
// `sanitize(folder)[:42] + "-" + urlsafe_b64encode(sha256(Pipfile path).digest()[:6])`, from pipenv.
#[cfg(unix)]
assert_eq!(pipenv_env_name(Path::new("/home/me/My Shop (2)")), "My_Shop__2_-6rNTtAUD");
#[cfg(windows)]
assert_eq!(pipenv_env_name(Path::new(r"C:\Users\me\My Shop (2)")), "My_Shop__2_-ED1rXUDC");
}
#[test]
+1 -1
View File
@@ -597,7 +597,7 @@ fn saved_python_configs_keep_their_explicit_interpreter() {
config.cwd = Some(Path::new("member").into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert_eq!(config.command, command);
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member/.override").to_string_lossy());
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member").join(".override").to_string_lossy());
let saved = without_derived(&config, root, &settings);
assert_eq!(saved.command, command);
}
+10 -4
View File
@@ -228,6 +228,14 @@ mod tests {
(coalescing_sink(Arc::new(move |event| saved.lock().push(event)), tokio::runtime::Handle::current()), events)
}
/// Waits for the coalescing window to flush `n` events (a fixed sleep is too short on slow CI timers).
async fn wait_for_events(events: &Mutex<Vec<IdeEvent>>, n: usize) {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while events.lock().len() < n && std::time::Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(5)).await;
}
}
fn diagnostics(path: &str, source: &str, message: &str) -> IdeEvent {
IdeEvent::Diagnostics {
path: IpcPath::from(path),
@@ -316,9 +324,7 @@ mod tests {
sink.emit(diagnostics("/p/b.rs", "rust-analyzer", "other"));
assert!(events.lock().is_empty());
tokio::task::yield_now().await;
tokio::time::sleep(Duration::from_millis(30)).await;
tokio::task::yield_now().await;
wait_for_events(&events, 3).await;
{
let saved_events = events.lock();
@@ -381,7 +387,7 @@ mod tests {
}
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS);
tokio::time::sleep(Duration::from_millis(30)).await;
wait_for_events(&events, MAX_PENDING_DIAGNOSTICS + 1).await;
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS + 1);
}
+154
View File
@@ -0,0 +1,154 @@
import { beforeAll, describe, expect, it } from "vitest";
import type { LanguageSupport } from "@codemirror/language";
import { highlightTree, tags as t, type Tag } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "./languages";
import { openideaHighlightStyle } from "./highlight";
let java: LanguageSupport;
beforeAll(async () => {
java = (await loadSupport(findLanguageDescription("Java", "")!))!;
});
function tokens(doc: string): { text: string; cls: string }[] {
const out: { text: string; cls: string }[] = [];
highlightTree(java.language.parser.parse(doc), openideaHighlightStyle, (from, to, cls) => {
out.push({ text: doc.slice(from, to), cls });
});
return out;
}
const cls = (tag: Tag) => openideaHighlightStyle.style([tag])!;
function expectTokens(doc: string, expected: readonly (readonly [string, Tag])[]) {
const got = tokens(doc);
for (const [text, tag] of expected) expect(got, text).toContainEqual({ text, cls: cls(tag) });
}
/** The literal holding `text` is one string token: nothing is embedded. */
function expectPlainString(doc: string, text: string) {
expect(
tokens(doc).some((tok) => tok.cls === cls(t.string) && tok.text.includes(text)),
text,
).toBe(true);
}
const JPA = "import org.springframework.data.jpa.repository.Query;\n";
const VALUE = "import org.springframework.beans.factory.annotation.Value;\n";
describe("Java annotation string languages", () => {
it("highlights JPQL in Spring Data JPA @Query, also concatenated and as countQuery", () => {
const doc = `${JPA}interface Repo {
@Query(value = "select u from User u " + "where u.email = :email", countQuery = "select count(u) from User u")
User find(String email);
}`;
expectTokens(doc, [
["select", t.keyword],
["from", t.keyword],
["where", t.keyword],
["count", t.keyword],
// The quotes stay the Java string's.
['"', t.string],
]);
expect(tokens(doc).filter((tok) => tok.cls === cls(t.string) && tok.text.includes("select"))).toEqual([]);
// JPQL names entities: `User` is not SQL's `USER` keyword.
expect(tokens(doc).filter((tok) => tok.text === "User" && tok.cls === cls(t.keyword))).toEqual([]);
});
it("highlights native SQL in a text block", () => {
const doc = `${JPA}interface Repo {
@Query(nativeQuery = true, value = """
SELECT * FROM User WHERE id = 1
""")
User find();
}`;
expectTokens(doc, [
["SELECT", t.keyword],
["WHERE", t.keyword],
["1", t.number],
// Native SQL keeps SQL's keywords.
["User", t.keyword],
]);
});
it("resolves the annotation through a package import or its qualified name", () => {
expectTokens('import org.springframework.data.jpa.repository.*;\ninterface R { @Query("select 1") void f(); }', [
["select", t.keyword],
]);
expectTokens('interface R { @org.springframework.data.jpa.repository.Query("select 1") void f(); }', [
["select", t.keyword],
]);
});
it("leaves other annotations named Query as plain strings", () => {
expectPlainString('import com.example.Query;\ninterface R { @Query("select u from User u") void f(); }', "select");
expectPlainString('interface R { @Query("select u from User u") void f(); }', "select");
expectPlainString(
'import org.springframework.data.mongodb.repository.Query;\ninterface R { @Query("{ name: ?0 }") void f(); }',
"name",
);
expectPlainString(
'import org.springframework.data.mongodb.repository.*;\ninterface R { @Query("{ name: ?0 }") void f(); }',
"name",
);
});
it("keeps escape sequences out of the embedded text", () => {
const doc = `${JPA}interface R { @Query("select u from User u where u.name = \\"x\\"") void f(); }`;
const got = tokens(doc);
// The escapes keep the Java string's colour; the escape colouring of the semantic layer marks them.
expect(got).toContainEqual({ text: '\\"', cls: cls(t.string) });
expect(got).toContainEqual({ text: "where", cls: cls(t.keyword) });
// The escaped quotes don't open an SQL quoted identifier: `x` is plain text.
expect(got.filter((tok) => tok.text.includes("x"))).toEqual([]);
});
it("highlights placeholders and SpEL in @Value", () => {
const doc = `${VALUE}class C {
@Value("\${app.timeout:30}") int timeout;
@Value("#{systemProperties['user.region'] ?: 'eu'}") String region;
@Value("prefix-#{@config.name()}") String name;
}`;
expectTokens(doc, [
["${", t.meta],
["app.timeout", t.propertyName],
["30", t.string],
["#{", t.meta],
["}", t.meta],
["systemProperties", t.variableName],
["'user.region'", t.string],
["?:", t.operator],
["prefix-", t.string],
["#{@config", t.meta],
["name", t.function(t.propertyName)],
]);
});
it("highlights the whole value as SpEL in security and cache annotations", () => {
const doc = `import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.cache.annotation.Cacheable;
class C {
@PreAuthorize("hasRole('ADMIN') and #id == authentication.principal.id")
@Cacheable(cacheNames = "users", key = "#id", unless = "#result == null")
User find(long id) { return null; }
}`;
expectTokens(doc, [
["hasRole", t.function(t.variableName)],
["'ADMIN'", t.string],
["and", t.keyword],
["#id", t.standard(t.variableName)],
["principal", t.propertyName],
["#result", t.standard(t.variableName)],
["null", t.null],
]);
// Not a SpEL attribute.
expectPlainString(doc, "users");
});
it("closes #{…} after an inline list", () => {
expectTokens(`${VALUE}class C { @Value("#{ {1, 2}.size() } items") int n; }`, [
["size", t.function(t.propertyName)],
[" items", t.string],
]);
});
});
+261
View File
@@ -0,0 +1,261 @@
/**
* Embedded languages in Java annotation strings, as IntelliJ IDEA Ultimate's Spring support
* injects them: JPQL (SQL with `nativeQuery = true`) in Spring Data JPA's `@Query`, SpEL in `@PreAuthorize`, `@Cacheable(key = …)`
* and the like, and SpEL `#{…}` with property placeholders `${…}` in `@Value` and
* `@ConditionalOnExpression`.
*
* An annotation counts only by its resolved name: written fully qualified, or by a simple name the file
* imports (the class itself or its package with `.*`), so a project's own `@Query` keeps a plain string.
* Escape sequences stay outside the embedded text and keep the Java string's colours.
*/
import { LanguageSupport, LRLanguage, StreamLanguage, type StringStream } from "@codemirror/language";
import { java } from "@codemirror/lang-java";
import {
parseMixed,
type Input,
type NestedParse,
type Parser,
type SyntaxNode,
type SyntaxNodeRef,
} from "@lezer/common";
import { SQLDialect, StandardSQL } from "@codemirror/lang-sql";
type Embedded = "SQL" | "SpEL" | "SpEL template";
const PREPOST = "org.springframework.security.access.prepost.";
const CACHE = "org.springframework.cache.annotation.";
const CACHE_ATTRIBUTES = {
key: "SpEL",
condition: "SpEL",
unless: "SpEL",
} as const;
/** Annotation class → attribute → embedded language. */
const INJECTIONS: Record<string, Record<string, Embedded>> = {
"org.springframework.data.jpa.repository.Query": {
value: "SQL",
countQuery: "SQL",
},
"org.springframework.beans.factory.annotation.Value": {
value: "SpEL template",
},
"org.springframework.boot.autoconfigure.condition.ConditionalOnExpression": {
value: "SpEL template",
},
[`${PREPOST}PreAuthorize`]: { value: "SpEL" },
[`${PREPOST}PostAuthorize`]: { value: "SpEL" },
[`${PREPOST}PreFilter`]: { value: "SpEL" },
[`${PREPOST}PostFilter`]: { value: "SpEL" },
[`${CACHE}Cacheable`]: CACHE_ATTRIBUTES,
[`${CACHE}CachePut`]: CACHE_ATTRIBUTES,
[`${CACHE}CacheEvict`]: CACHE_ATTRIBUTES,
};
const SIMPLE_NAMES = new Set(Object.keys(INJECTIONS).map((name) => name.slice(name.lastIndexOf(".") + 1)));
const text = (node: SyntaxNode, input: Input) => input.read(node.from, node.to).replace(/\s+/g, "");
/** The annotation's class: `name` as written when qualified, else the import that brings it in. */
function annotationClass(annotation: SyntaxNode, input: Input): string | null {
const nameNode = annotation.getChild("Identifier") ?? annotation.getChild("ScopedIdentifier");
if (!nameNode) return null;
const name = text(nameNode, input);
if (name.includes(".")) return name;
if (!SIMPLE_NAMES.has(name)) return null;
let program = annotation;
while (program.parent) program = program.parent;
for (const decl of program.getChildren("ImportDeclaration")) {
if (decl.getChild("static")) continue;
const path = decl.getChild("ScopedIdentifier");
if (!path) continue;
const imported = text(path, input);
if (!decl.getChild("Asterisk")) {
if (imported.endsWith(`.${name}`)) return imported;
} else if (INJECTIONS[`${imported}.${name}`]) return `${imported}.${name}`;
}
return null;
}
/** The string literals of an attribute value: one literal, or several joined with `+`. */
function literals(value: SyntaxNode, out: SyntaxNode[] = []): SyntaxNode[] {
if (value.name === "StringLiteral" || value.name === "TextBlock") out.push(value);
else if (value.name === "BinaryExpression" || value.name === "ParenthesizedExpression")
for (let child = value.firstChild; child; child = child.nextSibling) literals(child, out);
return out;
}
const ESCAPE = /\\(?:u+[0-9a-fA-F]{4}|[0-7]{1,3}|[\s\S])/g;
/** The literal's text between its quotes, without escape sequences. */
function contentRanges(literal: SyntaxNode, input: Input, out: { from: number; to: number }[]) {
const quote = literal.name === "TextBlock" ? 3 : 1;
const from = literal.from + quote;
const raw = input.read(literal.from, literal.to);
const closed = raw.length >= 2 * quote && raw.endsWith(quote === 3 ? '"""' : '"');
const to = closed ? literal.to - quote : literal.to;
let start = from;
// ponytail: an escape splits the embedded text, so `FROM\nUser` reads as `FROMUser`; rare in queries.
for (const m of input.read(from, to).matchAll(ESCAPE)) {
const at = from + m.index;
if (at > start) out.push({ from: start, to: at });
start = at + m[0].length;
}
if (to > start) out.push({ from: start, to });
}
const SPEL_KEYWORDS = /^(?:and|or|not|eq|ne|lt|gt|le|ge|div|mod|instanceof|matches|between|new|T)\b(?![\w$])/;
interface Frame {
kind: "#" | "$";
/** Inside a placeholder, past the `:` before its default value. */
fallback: boolean;
/** Open `{` of inline lists and maps inside a `#{…}`. */
braces: number;
}
interface SpelState {
/** Open `#{` / `${`. Outside them a template string is text and an expression-only string is SpEL. */
stack: Frame[];
/** The last token was `.` or `?.`: a property or method name follows. */
member: boolean;
}
function spelToken(stream: StringStream, state: SpelState, template: boolean): string | null {
if (stream.match(/^[#$]\{/)) {
state.stack.push({
kind: stream.current()[0] as "#" | "$",
fallback: false,
braces: 0,
});
return "meta";
}
const frame = state.stack[state.stack.length - 1];
if (frame && (frame.kind === "$" || !frame.braces) && stream.eat("}")) {
state.stack.pop();
return "meta";
}
if (template && !frame) {
if (!stream.match(/^[^#$]+/)) stream.next();
return "string";
}
if (frame?.kind === "$") {
if (frame.fallback) {
if (!stream.match(/^[^#$}]+/)) stream.next();
return "string";
}
if (stream.eat(":")) {
frame.fallback = true;
return "operator";
}
if (!stream.match(/^[^:#$}]+/)) stream.next();
return "propertyName";
}
if (stream.eatSpace()) return null;
const member = state.member;
state.member = false;
if (stream.eat("'")) {
while (!stream.eol()) if (stream.next() === "'" && !stream.eat("'")) break;
return "string";
}
if (stream.match(/^\d+(?:\.\d+)?(?:[eE][-+]?\d+)?[lLfFdD]?/)) return "number";
if (stream.match(/^#\w+/)) return "variableName.standard";
if (stream.match(/^[@&][\w$]+/)) return "meta";
if (!member && stream.match(/^(?:true|false)\b/)) return "bool";
if (!member && stream.match(/^null\b/)) return "null";
if (!member && stream.match(SPEL_KEYWORDS)) return "keyword";
if (stream.match(/^[A-Za-z_$][\w$]*/)) {
const call = stream.match(/^\s*\(/, false);
if (member) return call ? "propertyName.function" : "propertyName";
return call ? "variableName.function" : "variableName";
}
if (stream.match(/^\??\./)) {
state.member = true;
return "derefOperator";
}
if (stream.match(/^(?:\?:|\.\?|\.\^|\.\$|[!=<>]=?|&&|\|\||[-+*/%^?:])/)) return "operator";
if (frame && stream.match(/^[{}]/)) frame.braces += stream.current() === "{" ? 1 : -1;
else if (!stream.match(/^[()[\]{}]/)) {
if (stream.eat(",")) return "separator";
stream.next();
return null;
}
return "bracket";
}
function spel(template: boolean): Parser {
return StreamLanguage.define<SpelState>({
name: template ? "spel-template" : "spel",
startState: () => ({ stack: [], member: false }),
copyState: (s) => ({
stack: s.stack.map((f) => ({ ...f })),
member: s.member,
}),
token: (stream, state) => spelToken(stream, state, template),
}).parser;
}
/** JPQL / HQL: entity names such as `User` or `Order` are not keywords, unlike in SQL. */
const JPQL_KEYWORDS =
"select from where and or not as join left right inner outer full cross fetch on with distinct order by group " +
"having asc desc nulls first last in like escape between is null empty member of exists all any some case when " +
"then else end new update set delete insert into union intersect except true false count sum avg min max upper " +
"lower trim leading trailing both length locate abs sqrt mod size index key value entry treat type coalesce " +
"nullif concat substring cast extract function current_date current_time current_timestamp object limit offset";
let parsers: Record<Embedded | "JPQL", Parser> | null = null;
/** Whether `@Query(…)` has `nativeQuery = true`. */
function nativeQuery(args: SyntaxNode, input: Input): boolean {
return args
.getChildren("ElementValuePair")
.some((pair) => /^nativeQuery\s*=\s*true$/.test(input.read(pair.from, pair.to)));
}
/** The nested parse for an annotation attribute value (`ElementValuePair`) or a lone value. */
export function javaInjection() {
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 !== "ElementValuePair" && ref.name !== "AnnotationArgumentList") return null;
const node = ref.node;
let attribute: string;
let value: SyntaxNode | null;
let annotation: SyntaxNode | null;
if (node.name === "ElementValuePair") {
const name = node.getChild("Identifier");
attribute = name ? input.read(name.from, name.to) : "";
value = node.lastChild;
annotation = node.parent?.parent ?? null;
} else {
// `@Ann("…")`: the value attribute's shorthand.
attribute = "value";
value = node.firstChild?.nextSibling ?? null;
if (value?.name === "ElementValuePair") return null;
annotation = node.parent;
}
if (!value || annotation?.name !== "Annotation") return null;
const cls = annotationClass(annotation, input);
const language = cls ? INJECTIONS[cls]?.[attribute] : undefined;
if (!language) return null;
const overlay: { from: number; to: number }[] = [];
for (const literal of literals(value)) contentRanges(literal, input, overlay);
if (!overlay.length) return null;
parsers ??= {
SQL: StandardSQL.language.parser,
JPQL: SQLDialect.define({ keywords: JPQL_KEYWORDS, types: "", builtin: "" }).language.parser,
SpEL: spel(false),
"SpEL template": spel(true),
};
// ponytail: the mount is per attribute, so toggling `nativeQuery` restyles the query once it is edited.
const jpql = language === "SQL" && !nativeQuery(annotation.getChild("AnnotationArgumentList")!, input);
return { parser: parsers[jpql ? "JPQL" : language], overlay };
};
}
/** `java()` that also parses the embedded languages of Spring annotation strings. */
export function javaWithInjections(): LanguageSupport {
const base = java();
const language = (base.language as LRLanguage).configure({
wrap: parseMixed(javaInjection()),
});
return new LanguageSupport(language, base.support);
}
+23
View File
@@ -411,6 +411,29 @@ describe("language modes", () => {
}
});
it("leaves Java statement labels uncoloured, unlike JavaScript's", async () => {
const highlighter = tagHighlighter([
{ tag: t.labelName, class: "label" },
{ tag: t.variableName, class: "variable" },
]);
const labels = async (mode: string, path: string, doc: string) => {
const support = await loadSupport(findLanguageDescription(mode, path)!);
const found: string[] = [];
highlightTree(support!.language.parser.parse(doc), highlighter, (from, to, style) =>
found.push(`${doc.slice(from, to)}:${style}`),
);
return found.filter((s) => s.startsWith("outer"));
};
expect(await labels("Java", "/p/A.java", "class A { void f() { outer: for (;;) { break outer; } } }")).toEqual([
"outer:variable",
"outer:variable",
]);
expect(await labels("JavaScript", "/p/a.js", "outer: for (;;) { break outer; }")).toEqual([
"outer:label",
"outer:label",
]);
});
it("recognizes go.mod and go.work files by mode and filename", async () => {
for (const [mode, path] of [
["GoMod", "/project/go.mod"],
+7
View File
@@ -224,6 +224,11 @@ const OWN_MODES = [
load: () => import("./templateLanguages").then((m) => m.javascriptWithTemplates(config, templateLanguage)),
}),
),
// JPQL / SQL in `@Query`, SpEL and property placeholders in Spring annotation strings.
LanguageDescription.of({
name: "Java",
load: () => import("./javaInjections").then((m) => m.javaWithInjections()),
}),
// Only for template literals: `.graphql` files keep the backend's tree-sitter highlighting.
LanguageDescription.of({
name: "GraphQL",
@@ -495,6 +500,8 @@ const CSS_TAGS: Parameters<typeof styleTags>[0] = {
export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
"MarkerAnnotation/Identifier Annotation/Identifier MarkerAnnotation Annotation": t.annotation,
this: t.keyword,
// IntelliJ has no Java label colour: `outer:` stays plain text, like `break outer`.
Label: t.variableName,
};
// @lezer/go leaves `default` uncoloured, unlike `case` and `switch`.