From 1d19a6dfec5bec83a802ace4e70a230382dfbfd8 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Tue, 24 Nov 2026 21:56:17 +0900 Subject: [PATCH] fix(java): underline reassigned local variables and parameters (#5556) IntelliJ underlines reassigned locals and parameters; jdtls's token legend has no modifier for it. java/reassigned.ts finds them in the parse tree following ControlFlowUtil.isReassigned (parameters once assigned; locals assigned again, outside exclusive branches, in a loop they're declared outside of, or in switch case groups that fall through) and adds cm-sem-mutable to jdtls's variable/parameter tokens. SemanticToken gains from/doc/tree for hooks that look at the tree. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/editor/lsp/semantic/index.ts | 2 +- src/editor/lsp/semantic/java/index.ts | 4 +- .../lsp/semantic/java/reassigned.test.ts | 172 +++++++++++++ src/editor/lsp/semantic/java/reassigned.ts | 231 ++++++++++++++++++ src/editor/lsp/semantic/languages.ts | 4 + 5 files changed, 411 insertions(+), 2 deletions(-) create mode 100644 src/editor/lsp/semantic/java/reassigned.test.ts create mode 100644 src/editor/lsp/semantic/java/reassigned.ts diff --git a/src/editor/lsp/semantic/index.ts b/src/editor/lsp/semantic/index.ts index 839798ea4..57f24a999 100644 --- a/src/editor/lsp/semantic/index.ts +++ b/src/editor/lsp/semantic/index.ts @@ -160,7 +160,7 @@ export function semanticRanges( if (base && base !== "variable") classes.push(`cm-sem-${base}`); // `hasOwn`: servers send names like `constructor` (jdtls) that `Object.prototype` also has. for (const n of names) if (Object.hasOwn(MODIFIER_CLASS, n)) classes.push(`cm-sem-${MODIFIER_CLASS[n]}`); - semantics?.tokenClasses?.({ type, modifiers: names, kind, classes, marksLocals }); + semantics?.tokenClasses?.({ type, modifiers: names, kind, classes, marksLocals, from, doc, tree }); const local = rainbow && !constant && diff --git a/src/editor/lsp/semantic/java/index.ts b/src/editor/lsp/semantic/java/index.ts index 50d66e309..4351623ed 100644 --- a/src/editor/lsp/semantic/java/index.ts +++ b/src/editor/lsp/semantic/java/index.ts @@ -2,6 +2,7 @@ import type { Tree } from "@lezer/common"; import type { Text } from "@codemirror/state"; import { registerLanguageSemantics, type LanguageSemantics, type SemanticRange } from "../languages"; import { javaDeclarationRanges } from "./declarations"; +import { isReassignedAt } from "./reassigned"; const TYPE_TOKENS = new Set(["class", "interface", "enum", "record", "annotation", "type", "typeParameter"]); @@ -57,7 +58,7 @@ export function javaKeywordRanges(tree: Tree, doc: Text): SemanticRange[] { const javaSemantics: LanguageSemantics = { syntaxRanges: (tree, doc) => javaKeywordRanges(tree, doc), fallbackRanges: (tree) => javaDeclarationRanges(tree), - tokenClasses({ type, classes }) { + tokenClasses({ type, classes, from, doc, tree }) { // Relies on jdtls sending only contextual keywords (`sealed`, `permits`, `record`, `non-sealed`) as `modifier` tokens. if (type === "modifier" || type === "keyword") classes.push("cm-sem-keyword"); // Java colours JDK types and calls like any other: `defaultLibrary` (sent for JDK symbols) gets no colour of its own. @@ -68,6 +69,7 @@ const javaSemantics: LanguageSemantics = { const s = classes.indexOf("cm-sem-static"); if (s >= 0) classes.splice(s, 1); } + if (tree && isReassignedAt(tree, doc, from)) classes.push("cm-sem-mutable"); }, }; diff --git a/src/editor/lsp/semantic/java/reassigned.test.ts b/src/editor/lsp/semantic/java/reassigned.test.ts new file mode 100644 index 000000000..c43f44251 --- /dev/null +++ b/src/editor/lsp/semantic/java/reassigned.test.ts @@ -0,0 +1,172 @@ +import { describe, expect, it } from "vitest"; +import { Text } from "@codemirror/state"; +import { javaLanguage } from "@codemirror/lang-java"; +import { semanticRanges } from "../index"; +import { reassignedNames } from "./reassigned"; + +/** `name@line` (1-based) of every underlined name in a method body. */ +function underlined(body: string) { + const source = `class A {\n${body}\n}`; + const doc = Text.of(source.split("\n")); + return [...reassignedNames(javaLanguage.parser.parse(source), doc)] + .sort((a, b) => a - b) + .map((from) => `${doc.sliceString(from, source.slice(from).search(/\W/) + from)}@${doc.lineAt(from).number - 1}`); +} + +describe("Java reassigned locals and parameters", () => { + it("underlines a local at its declaration and every use once it is assigned again", () => { + expect( + underlined(`int sum(int[] xs) { + int total = 0; + for (int x : xs) total += x; + return total; +}`), + ).toEqual(["total@2", "total@3", "total@4"]); + }); + + it("leaves locals assigned once alone, including a late or branch-exclusive assignment", () => { + expect( + underlined(`void m(boolean c, int k) { + int once = 1; + int late; + late = 2; + String s; + if (c) s = "a"; else if (k > 0) s = "b"; else s = "c"; + int t = c ? (late) : once; + String u; + switch (k) { case 1: u = "x"; break; default: u = "y"; } + String v; + switch (k) { case 1 -> v = "x"; default -> { v = "y"; } } + final int f; + f = 3; + print(once, late, s, t, u, v, f); +}`), + ).toEqual([]); + }); + + it("counts compound assignments, increments and two unconditional assignments", () => { + expect( + underlined(`void m() { + int a = 0; a++; + int b = 0; --b; + int c; c = 1; c = 2; + int d; d = 1; d *= 2; +}`), + ).toEqual(["a@2", "a@2", "b@3", "b@3", "c@4", "c@4", "c@4", "d@5", "d@5", "d@5"]); + }); + + it("counts assignments in case groups that fall through, not ones separated by a jump", () => { + expect( + underlined(`void m(int k) { + String a; + switch (k) { case 1: a = "x"; case 2: a = "y"; break; } + String b; + switch (k) { case 1: b = "x"; if (k > 0) break; case 2: case 3: b = "y"; } + String c; + switch (k) { case 1: c = "x"; break; case 2: { c = "y"; return; } case 3: c = "z"; throw new Error(); default: c = "w"; } + print(a, b, c); +}`), + ).toEqual(["a@2", "a@3", "a@3", "b@4", "b@5", "b@5", "a@8", "b@8"]); + }); + + it("underlines a local assigned in a loop it is declared outside of, and loop counters", () => { + expect( + underlined(`void m(int n) { + int last; + while (n-- > 0) { last = n; } + for (int i = 0; i < 3; i++) { int inner; inner = i; } +}`), + ).toEqual(["n@1", "last@2", "n@3", "last@3", "n@3", "i@4", "i@4", "i@4", "i@4"]); + }); + + it("underlines every kind of parameter once it is assigned", () => { + expect( + underlined(`void m(int p, String... rest) { + p = 1; + for (String s : rest) s = s.trim(); + try { run(); } catch (RuntimeException e) { e = null; } + Op op = (z) -> z++; + call(y -> y = 2); + if (rest instanceof Object o) o = null; + rest = null; +}`), + ).toEqual([ + "p@1", + "rest@1", + "p@2", + "s@3", + "rest@3", + "s@3", + "s@3", + "e@4", + "e@4", + "z@5", + "z@5", + "y@6", + "y@6", + "rest@7", + "o@7", + "o@7", + "rest@8", + ]); + }); + + it("leaves final variables, resources and unassigned parameters alone", () => { + expect( + underlined(`void m(final int p, int q) { + try (var r = open()) { use(r, p, q); } + for (final String s : list) use(s); +}`), + ).toEqual([]); + }); + + it("matches uses by declaration, not by name", () => { + expect( + underlined(`int x; +void m(int k) { + this.x = 1; + x = 2; + { int k2 = 0; k2 = 1; } + { int k2 = 0; use(k2); } + Runnable r = new Runnable() { int k; public void run() { k = 1; } }; + for (int j = 0; j < 1; j++) {} + for (int j : arr) use(j); +}`), + ).toEqual(["k2@5", "k2@5", "j@8", "j@8", "j@8"]); + }); + + it("follows a local into lambdas and nested classes", () => { + expect( + underlined(`void m() { + int n = 0; + n = 1; + Runnable r = () -> use(n); + Object o = new Object() { int f = n; }; +}`), + ).toEqual(["n@2", "n@3", "n@4", "n@5"]); + }); + + it("adds the underline class to jdtls's variable and parameter tokens only", () => { + const source = "class A { void m(int p) { int t = 0; t = p; p = 1; int k = p; } }"; + const doc = Text.of([source]); + const at = (name: string, nth = 0) => { + let i = -1; + for (let n = 0; n <= nth; n++) i = source.indexOf(` ${name} `, i + 1) + 1; + return [0, i, name.length]; + }; + const tokens = { + tokenTypes: ["variable", "parameter"], + tokenModifiers: ["declaration"], + data: [...at("p"), 1, 1, ...at("t"), 0, 1, ...at("k"), 0, 1], + }; + // `m` is coloured by the declaration fallback, which jdtls's tokens here don't cover. + const classes = semanticRanges(doc, tokens, false, "java", javaLanguage.parser.parse(source)) + .map((r) => [source.slice(r.from, r.to), r.className]) + .filter(([name]) => name !== "m"); + expect(classes).toEqual([ + ["t", "cm-sem-declaration cm-sem-mutable"], + ["p", "cm-sem-parameter cm-sem-declaration cm-sem-mutable"], + ["k", "cm-sem-declaration"], + ]); + }); +}); diff --git a/src/editor/lsp/semantic/java/reassigned.ts b/src/editor/lsp/semantic/java/reassigned.ts new file mode 100644 index 000000000..e0c67930d --- /dev/null +++ b/src/editor/lsp/semantic/java/reassigned.ts @@ -0,0 +1,231 @@ +/** + * IDEA's "Reassigned local variable" / "Reassigned parameter" (underlined by default): jdtls has no + * modifier for it, so the parse tree finds them. Names resolve by scope, not by text, so a shadowing + * field or a same-named variable elsewhere stays plain. + * + * Rules (IDEA's `ControlFlowUtil.isReassigned`): a parameter (method, lambda, catch, for-each, pattern) + * counts once it is assigned at all; a local once a second assignment may follow the first, i.e. an + * initialised local that is assigned again, two assignments outside exclusive branches, or one inside + * a loop the local is declared outside of. `final` variables and try-with-resources resources never count. + * + * Limit: no real control flow, so `if (a) { x = 1; return; } x = 2;` is judged by branch structure only. + * An old-style `case` group falls into the next unless its last statement is a `break`, `continue`, + * `return` or `throw`. + */ +import type { SyntaxNode, Tree } from "@lezer/common"; +import type { Text } from "@codemirror/state"; + +interface Variable { + param: boolean; + initialized: boolean; + /** The scope node it was declared in. */ + scope: SyntaxNode; + /** Start offsets of the declaration and every use. */ + names: number[]; + writes: SyntaxNode[]; +} + +/** `null` marks a field: it shadows outer locals and is never underlined. */ +type Scope = Map; + +const SCOPES = new Set([ + "Block", + "MethodDeclaration", + "ConstructorDeclaration", + "CompactConstructorDeclaration", + "LambdaExpression", + "ForStatement", + "EnhancedForStatement", + "CatchClause", + "TryWithResourcesStatement", + "SwitchBlock", + "SwitchRule", +]); +const CLASS_BODIES = new Set(["ClassBody", "InterfaceBody", "EnumBody", "AnnotationTypeBody", "RecordBody"]); +const LOOPS = new Set(["WhileStatement", "DoStatement", "ForStatement", "EnhancedForStatement"]); + +const cache = new WeakMap>(); + +/** Whether the name starting at `from` declares or uses a reassigned local or parameter. */ +export function isReassignedAt(tree: Tree, doc: Text, from: number): boolean { + let starts = cache.get(tree); + if (!starts) cache.set(tree, (starts = reassignedNames(tree, doc))); + return starts.has(from); +} + +/** Start offsets of every declaration and use of a reassigned local or parameter. */ +export function reassignedNames(tree: Tree, doc: Text): Set { + const text = (n: SyntaxNode) => doc.sliceString(n.from, n.to); + const variables: Variable[] = []; + const scopes: Array<{ node: SyntaxNode; names: Scope }> = []; + const lookup = (name: string) => { + for (let i = scopes.length - 1; i >= 0; i--) { + const v = scopes[i]!.names.get(name); + if (v !== undefined) return v; + } + return null; + }; + + const declare = (def: SyntaxNode) => { + const scope = scopes.at(-1); + if (!scope) return; + const owner = def.parent!; + const declaration = owner.name === "VariableDeclarator" ? owner.parent : owner; + let param = true; + switch (declaration?.name) { + case "LocalVariableDeclaration": + param = false; + break; + case "FormalParameter": + case "SpreadParameter": + case "InferredParameters": + case "LambdaExpression": + case "ForSpec": + case "CatchFormalParameter": + case "TypePattern": + break; + case "Resource": + // Implicitly final; still shadows outer names. + scope.names.set(text(def), null); + return; + default: + // Fields are collected per class body; methods and types are not variables. + return; + } + let final = false; + for (let c = declaration.firstChild; c && c.from < def.from; c = c.nextSibling) + if (c.name === "Modifiers") final = c.getChild("final") != null; + const v: Variable = { + param, + initialized: def.nextSibling?.name === "AssignOp", + scope: scope.node, + names: [def.from], + writes: [], + }; + scope.names.set(text(def), final ? null : v); + if (!final) variables.push(v); + }; + + const fields = (body: SyntaxNode): Scope => { + const names: Scope = new Map(); + const add = (def: SyntaxNode | null) => def && names.set(text(def), null); + const members = (parent: SyntaxNode) => { + for (let c = parent.firstChild; c; c = c.nextSibling) + if (c.name === "FieldDeclaration" || c.name === "ConstantDeclaration") + for (const d of c.getChildren("VariableDeclarator")) add(d.getChild("Definition")); + else if (c.name === "EnumConstant") add(c.getChild("Definition")); + else if (c.name === "EnumBodyDeclarations") members(c); + }; + members(body); + for (const c of body.parent?.getChild("RecordHeader")?.getChildren("RecordComponent") ?? []) + add(c.getChild("Definition")); + return names; + }; + + // A cursor walk: syntax nodes are only built for scopes, declarations and resolved names. + tree.iterate({ + enter(ref) { + if (SCOPES.has(ref.name)) scopes.push({ node: ref.node, names: new Map() }); + else if (CLASS_BODIES.has(ref.name)) scopes.push({ node: ref.node, names: fields(ref.node) }); + else if (ref.name === "Definition") declare(ref.node); + else if (ref.name === "Identifier") { + const v = lookup(doc.sliceString(ref.from, ref.to)); + if (!v) return; + const node = ref.node; + if (isMemberName(node)) return; + v.names.push(node.from); + if (isWriteTarget(node)) v.writes.push(node); + } + }, + leave(ref) { + if (SCOPES.has(ref.name) || CLASS_BODIES.has(ref.name)) scopes.pop(); + }, + }); + + const out = new Set(); + for (const v of variables) if (isReassigned(v)) for (const n of v.names) out.add(n); + return out; +} + +/** `b` in `a.b` and method names are not variable references. */ +function isMemberName(node: SyntaxNode) { + const parent = node.parent; + return parent?.name === "MethodName" || (parent?.name === "FieldAccess" && node.prevSibling?.name === "."); +} + +function isWriteTarget(node: SyntaxNode) { + const parent = node.parent; + if (parent?.name === "UpdateExpression") return true; + return parent?.name === "AssignmentExpression" && parent.firstChild?.from === node.from; +} + +function isReassigned(v: Variable) { + if (!v.writes.length) return false; + if (v.param || v.initialized) return true; + if (v.writes.some((w) => inLoopBelow(w, v.scope))) return true; + // Pairwise, but a local has few assignments. + for (let i = 0; i < v.writes.length; i++) + for (let j = i + 1; j < v.writes.length; j++) if (!exclusive(v.writes[i]!, v.writes[j]!)) return true; + return false; +} + +function inLoopBelow(node: SyntaxNode, scope: SyntaxNode) { + for (let n = node.parent; n && !same(n, scope); n = n.parent) if (LOOPS.has(n.name)) return true; + return false; +} + +/** Whether at most one of the two writes can run: different branches of an `if`, `?:` or `switch`. */ +function exclusive(a: SyntaxNode, b: SyntaxNode) { + const pathA = ancestors(a); + const pathB = ancestors(b); + let i = 0; + while (i < pathA.length && i < pathB.length && same(pathA[i]!, pathB[i]!)) i++; + const common = pathA[i - 1]; + const childA = pathA[i]; + const childB = pathB[i]; + if (!common || !childA || !childB) return false; + switch (common.name) { + case "IfStatement": + case "TernaryExpression": { + // The condition runs before either branch. + const condition = common.name === "IfStatement" ? common.getChild("ParenthesizedExpression") : common.firstChild; + return !!condition && !same(childA, condition) && !same(childB, condition); + } + case "SwitchBlock": { + if (childA.name === "SwitchRule") return true; + const [first, second] = childA.from < childB.from ? [childA, childB] : [childB, childA]; + return !fallsInto(first, second); + } + default: + return false; + } +} + +/** Root-first ancestors of `node`, itself included. */ +function ancestors(node: SyntaxNode) { + const path: SyntaxNode[] = []; + for (let n: SyntaxNode | null = node; n; n = n.parent) path.push(n); + return path.reverse(); +} + +const same = (a: SyntaxNode, b: SyntaxNode) => a.from === b.from && a.to === b.to && a.name === b.name; + +const JUMPS = new Set(["BreakStatement", "ContinueStatement", "ReturnStatement", "ThrowStatement"]); + +/** Whether an old-style switch can run on from statement `first` to `second`: no case group between them ends in a jump. */ +function fallsInto(first: SyntaxNode, second: SyntaxNode) { + let last: SyntaxNode | null = first; + for (let n = first.nextSibling; n && !same(n, second); n = n.nextSibling) { + if (n.name === "SwitchLabel") { + if (last && jumps(last)) return false; + last = null; + } else if (n.name !== ":") last = n; + } + return true; +} + +function jumps(node: SyntaxNode): boolean { + if (node.name !== "Block") return JUMPS.has(node.name); + const statement = node.lastChild?.prevSibling; + return !!statement && jumps(statement); +} diff --git a/src/editor/lsp/semantic/languages.ts b/src/editor/lsp/semantic/languages.ts index 88deacdf4..e0e5e9a6a 100644 --- a/src/editor/lsp/semantic/languages.ts +++ b/src/editor/lsp/semantic/languages.ts @@ -26,6 +26,10 @@ export interface SemanticToken { marksLocals?: boolean; /** Classes accumulated so far; the hook appends or removes. */ classes: string[]; + /** Where the token is, for hooks that look at the parse tree around it. */ + from: number; + doc: Text; + tree: Tree | undefined; } /** Documentation of a language construct that has no source declaration. */