From cdfc38231fdae51841d8e2829da18175ef36d21a Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Wed, 25 Nov 2026 00:35:44 +0900 Subject: [PATCH] feat(python): add the 'Method may be static' inspection (#5347) PyCharm reports instance methods that never use self (PyMethodMayBeStatic); neither basedpyright nor Ruff's default rules do. The Python parser now reports a method's unused receiver (undecorated, not a dunder, a body that does more than pass, ..., a docstring or one raise, never naming the receiver, super or __class__), and a weak-warning inspection in the Python inheritance checks reports it, except for overrides, methods a subclass overrides, classes with an incompletely indexed hierarchy, and test code. Alt+Enter offers Make method static. It searches the method's usages with the language server's references and applies only when every call goes through an instance (self.m(...), super().m(...)); otherwise it changes nothing, says how many usages may call it through a class and lists them in Find Usages. Suppressible with # noinspection PyMethodMayBeStatic. Closes #5333 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- .../ide-language/src/syntax/python_facts.rs | 72 +++++++++- src/bindings.ts | 7 + .../analysis/inheritanceInspections.test.ts | 53 ++++++- .../analysis/inheritanceInspections.ts | 97 ++++++++++++- src/features/analysis/makeStatic.test.ts | 136 ++++++++++++++++++ src/features/analysis/makeStatic.ts | 96 +++++++++++++ .../analysis/pythonSuppression.test.ts | 1 + .../settings/__tests__/inspections.test.ts | 1 + src/platform/inspections.ts | 12 ++ src/platform/locales/text/en.json | 7 + src/platform/locales/text/zh.json | 7 + 11 files changed, 481 insertions(+), 8 deletions(-) create mode 100644 src/features/analysis/makeStatic.test.ts create mode 100644 src/features/analysis/makeStatic.ts diff --git a/crates/ide-language/src/syntax/python_facts.rs b/crates/ide-language/src/syntax/python_facts.rs index 8ba56fb109..c83c5038aa 100644 --- a/crates/ide-language/src/syntax/python_facts.rs +++ b/crates/ide-language/src/syntax/python_facts.rs @@ -60,6 +60,11 @@ pub struct PythonMethodFacts { /// Decorated with `override` from `typing` / `typing_extensions`. pub override_decorated: bool, pub body: MethodBody, + /// For 'Method may be static': the receiver parameter up to the next parameter (what + /// Make method static deletes), when the method is undecorated and not a dunder, and its + /// body does more than `pass`, `...`, a docstring or one `raise` without ever naming the + /// receiver, `super` or `__class__`. + pub unused_receiver: Option, } /// What a method body does, for the shapes a check can decide without guessing. @@ -209,18 +214,65 @@ fn methods_of(class: Node, text: &str, idx: &LineIndex, imports: &ImportBindings } let decorators = decorators_of(method, text); out.push(PythonMethodFacts { - name, selection: idx.range(name_node.start_byte(), name_node.end_byte()), definition_line: member.start_position().row as u32, params: parameters_of(method, text), abstract_method: decorators.iter().any(|d| last_segment(d) == "abstractmethod"), override_decorated: decorators.iter().any(|d| imports.is_typing_override(d)), body: body_of(method, text), + unused_receiver: if decorators.is_empty() && !is_dunder(&name) { + unused_receiver(method, text).map(|(start, end)| idx.range(start, end)) + } else { + None + }, + name, }); } out } +fn is_dunder(name: &str) -> bool { + name.len() > 4 && name.starts_with("__") && name.ends_with("__") +} + +/// The bytes Make method static deletes: the receiver up to the next parameter (or up to the +/// closing parenthesis), when the body does real work without naming the receiver. +fn unused_receiver(function: Node, text: &str) -> Option<(usize, usize)> { + let body = function.child_by_field_name("body")?; + let statements: Vec = statements_of(body).into_iter().filter(|s| !is_string(*s)).collect(); + // Stubs and placeholders (`pass`, `...`, `raise NotImplementedError`) are meant to be overridden. + if statements.iter().all(|s| is_noop(*s)) + || matches!(statements.as_slice(), [only] if only.kind() == "raise_statement") + { + return None; + } + let params = function.child_by_field_name("parameters")?; + let mut cursor = params.walk(); + let mut named = params.named_children(&mut cursor); + let receiver = named.next()?; + let name = match receiver.kind() { + "identifier" => receiver, + "typed_parameter" => receiver.named_child(0).filter(|n| n.kind() == "identifier")?, + _ => return None, + }; + let name = &text[name.byte_range()]; + let next = named.next(); + if next.is_some_and(|n| matches!(n.kind(), "positional_separator" | "keyword_separator")) { + return None; + } + let mut used = false; + let mut cursor = body.walk(); + visit(&mut cursor, &mut |node| { + used |= node.kind() == "identifier" + && matches!(&text[node.byte_range()], n if n == name || n == "super" || n == "__class__"); + }); + if used { + return None; + } + let end = next.map_or(params.end_byte() - 1, |n| n.start_byte()); + Some((receiver.start_byte(), end)) +} + /// The parameter names of a `function_definition`, or `None` when the signature contains a /// form whose forwarding cannot be compared without guessing. fn parameters_of(function: Node, text: &str) -> Option> { @@ -578,4 +630,22 @@ mod tests { let f = facts("@dataclass\nclass C:\n x: int\n"); assert_eq!(f.classes[0].definition_line, 0); } + + #[test] + fn unused_receiver_is_the_parameter_make_static_deletes() { + let src = "class C:\n def helper(self, x):\n return x * 2\n\n def only(self):\n print(1)\n\n def typed(self: 'C',) -> int:\n return 1\n\n def uses(self):\n return self.x\n\n def nested(self):\n return lambda: self\n\n def sup(self):\n return super().sup()\n\n def stub(self):\n raise NotImplementedError\n\n def empty(self):\n \"\"\"Doc.\"\"\"\n\n @property\n def prop(self):\n return 1\n\n def __repr__(self):\n return 'C'\n\n def positional(self, /, x):\n return x\n"; + let f = facts(src); + let deleted = |name: &str| { + method(&f, "C", name).unused_receiver.map(|r| { + let line = src.lines().nth(r.start.line as usize).unwrap(); + line[r.start.col as usize..r.end.col as usize].to_string() + }) + }; + assert_eq!(deleted("helper").as_deref(), Some("self, ")); + assert_eq!(deleted("only").as_deref(), Some("self")); + assert_eq!(deleted("typed").as_deref(), Some("self: 'C',")); + for name in ["uses", "nested", "sup", "stub", "empty", "prop", "__repr__", "positional"] { + assert_eq!(deleted(name), None, "{name}"); + } + } } diff --git a/src/bindings.ts b/src/bindings.ts index cd8c46c90e..cc20a586cb 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -11504,6 +11504,13 @@ export type PythonMethodFacts = { /** Decorated with `override` from `typing` / `typing_extensions`. */ overrideDecorated: boolean, body: MethodBody, + /** + * For 'Method may be static': the receiver parameter up to the next parameter (what + * Make method static deletes), when the method is undecorated and not a dunder, and its + * body does more than `pass`, `...`, a docstring or one `raise` without ever naming the + * receiver, `super` or `__class__`. + */ + unusedReceiver: Range | null, }; export type PythonPackage = { diff --git a/src/features/analysis/inheritanceInspections.test.ts b/src/features/analysis/inheritanceInspections.test.ts index 74f6d40f05..49e8d03f2d 100644 --- a/src/features/analysis/inheritanceInspections.test.ts +++ b/src/features/analysis/inheritanceInspections.test.ts @@ -9,7 +9,7 @@ import type { PythonMethodFacts, Range, } from "@/platform/ipc"; -import { inheritanceIndex } from "@/editor/navigation/inheritanceGraph"; +import { inheritanceIndex, subclassMap } from "@/editor/navigation/inheritanceGraph"; import { inheritanceDiagnostics, pythonInheritanceExtension } from "./inheritanceInspections"; interface MethodSpec { @@ -20,6 +20,8 @@ interface MethodSpec { abstract?: boolean; override?: boolean; body?: MethodBody; + /** The parser found the receiver unused (`unusedReceiver`). */ + receiverUnused?: boolean; } interface ClassSpec { @@ -56,6 +58,7 @@ const methodFacts = (spec: MethodSpec): PythonMethodFacts => ({ abstractMethod: spec.abstract ?? false, overrideDecorated: spec.override ?? false, body: spec.body ?? EMPTY, + unusedReceiver: spec.receiverUnused ? range(spec.line, 13) : null, }); const classItem = (spec: ClassSpec, col: number, methods: PythonMethodFacts[]): OutlineItem => ({ @@ -124,11 +127,13 @@ class Fixture { async run(enabled?: ReadonlySet): Promise { const facts = this.facts.get(this.current); if (!facts) throw new Error(`no fixture for ${this.current}`); + const index = inheritanceIndex(this.graph, { readFiles: async () => new Map() }); return inheritanceDiagnostics({ path: this.current, outline: this.outlines.get(this.current) ?? [], facts, - index: inheritanceIndex(this.graph, { readFiles: async () => new Map() }), + index, + subclasses: () => subclassMap(index), factsOf: async (path) => this.facts.get(path) ?? null, outlineOf: async (path) => this.outlines.get(path) ?? [], enabled, @@ -406,3 +411,47 @@ it("installs the inspections for Python documents only", () => { expect(pythonInheritanceExtension(ctx("typescript"))).toEqual([]); expect(pythonInheritanceExtension(ctx("python"))).not.toEqual([]); }); + +const STATIC = "builtin:python-method-may-be-static"; +const helper: MethodSpec = { name: "helper", line: 1, body: OTHER, receiverUnused: true }; + +it("reports a method that may be static", async () => { + const project = new Fixture("/p/a.py").add("/p/a.py", [{ name: "C", line: 0, bases: ["ABC"], methods: [helper] }]); + expect(codes(await project.run())).toEqual([[STATIC, "info", 1]]); + expect(await project.run(new Set())).toEqual([]); +}); + +it("leaves alone a static candidate that overrides or may override", async () => { + const overrides = withBase({ name: "C", line: 0, bases: ["Base"], methods: [helper] }, [ + { name: "Base", line: 0, bases: [], methods: [{ name: "helper", line: 1, body: OTHER }] }, + ]); + expect(await overrides.run()).toEqual([]); + // `Widget` is a library class: it may declare `helper`. + const foreign = new Fixture("/p/a.py").add("/p/a.py", [{ name: "C", line: 0, bases: ["Widget"], methods: [helper] }]); + expect(await foreign.run()).toEqual([]); +}); + +it("leaves alone a static candidate a subclass overrides", async () => { + const project = new Fixture("/p/a.py") + .add("/p/a.py", [{ name: "Base", line: 0, bases: [], methods: [helper] }]) + .add("/p/mid.py", [{ name: "Mid", line: 0, bases: ["Base"] }]) + .add("/p/child.py", [ + { name: "Child", line: 0, bases: ["Mid"], methods: [{ name: "helper", line: 1, body: OTHER }] }, + ]); + expect(await project.run()).toEqual([]); +}); + +it("leaves test code alone", async () => { + const testClass = new Fixture("/p/a.py").add("/p/a.py", [ + { name: "TestParser", line: 0, bases: [], methods: [helper] }, + ]); + expect(await testClass.run()).toEqual([]); + const testMethod = new Fixture("/p/a.py").add("/p/a.py", [ + { name: "Checks", line: 0, bases: [], methods: [{ ...helper, name: "test_parse" }] }, + ]); + expect(await testMethod.run()).toEqual([]); + for (const path of ["/p/tests/test_a.py", "/p/a_test.py", "/p/conftest.py"]) { + const testFile = new Fixture(path).add(path, [{ name: "Helpers", line: 0, bases: [], methods: [helper] }]); + expect(await testFile.run()).toEqual([]); + } +}); diff --git a/src/features/analysis/inheritanceInspections.ts b/src/features/analysis/inheritanceInspections.ts index 7d0c203fd7..7d5a75c8c7 100644 --- a/src/features/analysis/inheritanceInspections.ts +++ b/src/features/analysis/inheritanceInspections.ts @@ -1,6 +1,7 @@ /** * Python inheritance inspections: circular inheritance, `@override` consistency, abstract - * methods a class leaves unimplemented, and overrides that only forward to the base. + * methods a class leaves unimplemented, overrides that only forward to the base, and methods + * that may be static. * * The rules read the IDE's inheritance graph (`inheritanceGraph.ts`) plus the facts the * Python parser reports for a document (`docPythonFacts`). Nothing here parses source text, @@ -10,9 +11,15 @@ */ import type { Extension } from "@codemirror/state"; import { ViewPlugin, type EditorView } from "@codemirror/view"; -import { inspectionControlProviders, type EditorDocContext } from "@/editor/api"; +import { + inspectionControlProviders, + intentionProviders, + quickFixProviders, + type ContributedIntention, + type EditorDocContext, +} from "@/editor/api"; import { onServerSettled } from "@/editor/lsp/availability"; -import { setFileDiagnostics } from "@/editor/lsp/diagnostics"; +import { inspectionsAt, setFileDiagnostics } from "@/editor/lsp/diagnostics"; import { withDocument } from "@/editor/lsp/files"; import { lspRequest } from "@/editor/lsp/lsp"; import { @@ -29,6 +36,8 @@ import { PYTHON_ABSTRACT_METHOD_PRODUCER, PYTHON_CIRCULAR_BASES_INSPECTION, PYTHON_CIRCULAR_BASES_PRODUCER, + PYTHON_METHOD_MAY_BE_STATIC_INSPECTION, + PYTHON_METHOD_MAY_BE_STATIC_PRODUCER, PYTHON_OVERRIDE_INSPECTION, PYTHON_OVERRIDE_PRODUCER, PYTHON_REDUNDANT_OVERRIDE_INSPECTION, @@ -53,6 +62,7 @@ import { type Range, } from "@/platform/ipc"; import { isSuppressed, suppressControls, type FactsOf } from "./pythonSuppression"; +import { makeMethodStatic, makeStaticChanges } from "./makeStatic"; /** The inspection producers, one per rule. */ const PRODUCERS = [ @@ -60,6 +70,7 @@ const PRODUCERS = [ PYTHON_OVERRIDE_PRODUCER, PYTHON_ABSTRACT_METHOD_PRODUCER, PYTHON_REDUNDANT_OVERRIDE_PRODUCER, + PYTHON_METHOD_MAY_BE_STATIC_PRODUCER, ]; /** What the rules read for one document: its own facts and a way to read another file's. */ @@ -70,6 +81,8 @@ export interface InheritanceInspectionDeps { index: InheritanceIndex; factsOf: (path: string) => Promise; outlineOf: (path: string) => Promise; + /** Direct subclasses by [`declarationKey`] of their base (`PythonIndex.subclasses`). */ + subclasses: () => Promise>; /** Producers whose inspection is on; missing means every rule runs. */ enabled?: ReadonlySet; } @@ -154,6 +167,24 @@ class ProjectView { return facts?.classes.find((c) => sameDeclaration(c, decl))?.methods ?? []; } + /** Whether a class below `cls` (transitively) declares `name`. */ + async overriddenBelow(cls: ClassView, name: string): Promise { + const subclasses = await this.deps.subclasses(); + const seen = new Set(); + const queue = [cls.decl]; + while (queue.length) { + for (const sub of subclasses.get(declarationKey(queue.shift()!)) ?? []) { + const key = declarationKey(sub); + if (seen.has(key)) continue; + seen.add(key); + if ((await this.membersOf(sub)).has(name) || (await this.methodsOf(sub)).some((m) => m.name === name)) + return true; + queue.push(sub); + } + } + return false; + } + async membersOf(decl: ClassInheritance): Promise> { if (decl.path === this.deps.path) { const live = this.liveOf.get(declarationKey(decl)); @@ -223,7 +254,7 @@ function sameDeclaration(cls: PythonClassFacts, decl: ClassInheritance): boolean return cls.selection.start.line === decl.line && cls.selection.start.col === decl.col; } -/** Everything the four rules produce for one document. */ +/** Everything the rules produce for one document. */ export async function inheritanceDiagnostics(deps: InheritanceInspectionDeps): Promise { const view = new ProjectView(deps); const runs = (producer: string) => deps.enabled?.has(producer) ?? true; @@ -237,6 +268,9 @@ export async function inheritanceDiagnostics(deps: InheritanceInspectionDeps): P if (runs(PYTHON_OVERRIDE_PRODUCER) && view.complete(cls)) out.push(...(await unusedOverride(view, cls))); if (runs(PYTHON_REDUNDANT_OVERRIDE_PRODUCER)) out.push(...(await redundantOverride(view, cls))); if (runs(PYTHON_ABSTRACT_METHOD_PRODUCER)) out.push(...(await missingAbstractMethods(view, cls))); + // A method may override one a foreign base declares: only a fully known chain can say it does not. + if (runs(PYTHON_METHOD_MAY_BE_STATIC_PRODUCER) && view.complete(cls)) + out.push(...(await mayBeStatic(view, cls, deps.path))); } return out; } @@ -273,6 +307,32 @@ async function unusedOverride(view: ProjectView, cls: ClassView): Promise /(^|\/)(test_[^/]*|[^/]*_test|conftest)\.py$/.test(path); + +/** + * Methods whose body never names the receiver (the parser decides, `unusedReceiver`), unless + * they override a base's or a subclass overrides them (the instance method is then part of a + * polymorphic call), or they are test code. + */ +async function mayBeStatic(view: ProjectView, cls: ClassView, path: string): Promise { + if (isTestFile(path) || cls.facts.name.startsWith("Test")) return []; + const out: Diagnostic[] = []; + for (const method of cls.facts.methods) { + if (!method.unusedReceiver || method.name.startsWith("test")) continue; + if ((await declaredInAncestry(view, cls, method.name)) || (await view.overriddenBelow(cls, method.name))) continue; + out.push( + problem( + method.selection, + PYTHON_METHOD_MAY_BE_STATIC_INSPECTION, + "info", + tx`Method '${method.name}' may be static`, + ), + ); + } + return out; +} + /** Abstract methods of the ancestry that no class on the way down implements. */ async function missingAbstractMethods(view: ProjectView, cls: ClassView): Promise { // A class that is itself abstract (it declares abstract methods, or names `ABC` or @@ -450,6 +510,32 @@ export function pythonInheritanceExtension(ctx: EditorDocContext): Extension { if (ctx.language !== "python" || ctx.virtual || ctx.doc < 0) return []; watchChanges(); const suppress = inspectionControlProviders.of((view, id) => suppressControls(view, id, latestFacts.get(view))); + // Make method static, on a method this run reported. + const makeStatic = (view: EditorView, from: number): ContributedIntention[] => { + // After an edit, the facts and the problems' ranges are stale until the next run. + const latest = latestFacts.get(view); + if (!latest || latest.doc !== view.state.doc) return []; + const reported = inspectionsAt(ctx.path, latest.doc, from).some( + (i) => i.id === PYTHON_METHOD_MAY_BE_STATIC_INSPECTION, + ); + const fix = reported ? makeStaticChanges(latest.doc, latest.facts, from) : null; + return fix + ? [ + { + id: "python.make-static", + label: "Make method static", + quickFix: true, + run: () => { + if (view.state.doc === latest.doc) void makeMethodStatic(view, ctx.path, ctx.doc, fix); + }, + }, + ] + : []; + }; + const fixes = [ + quickFixProviders.of(makeStatic), + intentionProviders.of((view) => makeStatic(view, view.state.selection.main.head)), + ]; const plugin = ViewPlugin.define((view: EditorView) => { if (!isTauri()) return {}; viewers.set(ctx.path, (viewers.get(ctx.path) ?? 0) + 1); @@ -486,6 +572,7 @@ export function pythonInheritanceExtension(ctx: EditorDocContext): Extension { factsOf: (path) => withDocument(path, (doc) => lspRequest(() => commands.docPythonFacts(doc))).catch(() => null), outlineOf: (path) => withDocument(path, (doc) => lspRequest(() => commands.docOutline(doc))).catch(() => []), + subclasses: project.subclasses, }); if (disposed || mine !== sequence || view.state.doc !== text) return; latestFacts.set(view, { facts, doc: text }); @@ -523,5 +610,5 @@ export function pythonInheritanceExtension(ctx: EditorDocContext): Extension { }, }; }); - return [plugin, suppress]; + return [plugin, suppress, fixes]; } diff --git a/src/features/analysis/makeStatic.test.ts b/src/features/analysis/makeStatic.test.ts new file mode 100644 index 0000000000..6b7f810e1c --- /dev/null +++ b/src/features/analysis/makeStatic.test.ts @@ -0,0 +1,136 @@ +import { EditorState } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { beforeEach, expect, it, vi } from "vitest"; +import type { Location, PythonFacts, References } from "@/platform/ipc"; + +const lspReferences = vi.fn<(...args: unknown[]) => Promise>(); +const readManyFileLines = vi.fn(async (_paths: readonly string[]) => new Map()); +const showHint = vi.fn(); +const executeAction = vi.fn(async (..._args: unknown[]) => {}); +vi.mock("@/platform/ipc", async (orig) => { + const actual = await orig(); + return { ...actual, commands: { ...actual.commands, lspReferences } }; +}); +vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} })); +vi.mock("@/editor/lsp/lsp", () => ({ lspRequest: (run: () => Promise) => run() })); +vi.mock("@/editor/lsp/files", () => ({ readManyFileLines: (paths: readonly string[]) => readManyFileLines(paths) })); +vi.mock("@/editor/lsp/hint", () => ({ showHint: (...args: unknown[]) => showHint(...args) })); +vi.mock("@/platform/actions", () => ({ executeAction: (...args: unknown[]) => executeAction(...args) })); + +const { breakingUsages, makeMethodStatic, makeStaticChanges } = await import("./makeStatic"); + +const SRC = "class C:\n # note\n def helper(self, x):\n return x * 2\n"; +const pos = (line: number, col: number) => ({ line, col }); +const FACTS: PythonFacts = { + suppressions: [], + classes: [ + { + name: "C", + selection: { start: pos(0, 6), end: pos(0, 7) }, + definitionLine: 0, + bases: [], + methods: [ + { + name: "helper", + selection: { start: pos(2, 8), end: pos(2, 14) }, + definitionLine: 2, + params: ["self", "x"], + abstractMethod: false, + overrideDecorated: false, + body: { kind: "other" }, + unusedReceiver: { start: pos(2, 15), end: pos(2, 21) }, + }, + ], + }, + ], +}; +const STATIC = "class C:\n # note\n @staticmethod\n def helper(x):\n return x * 2\n"; + +/** The usage of `helper` on `line` of `text` (its first occurrence there). */ +const usageIn = (path: string, text: string, line: number): Location => { + const col = text.split("\n")[line]!.indexOf("helper"); + return { path, range: { start: pos(line, col), end: pos(line, col + 6) } }; +}; + +it("adds @staticmethod and removes the receiver", () => { + const state = EditorState.create({ doc: SRC }); + const fix = makeStaticChanges(state.doc, FACTS, state.doc.line(3).from + 10); + expect(fix).toMatchObject({ name: "helper", at: pos(2, 8) }); + expect(state.update({ changes: fix!.changes }).state.doc.toString()).toBe(STATIC); + expect(makeStaticChanges(state.doc, FACTS, 3)).toBeNull(); +}); + +it("keeps only the calls through an instance", () => { + const lines = [ + "self.helper(1)", + "super().helper(1)", + "super(Sub, self).helper(1)", + "C.helper(C(), 1)", + "Alias.helper(Alias(), 1)", + "Sub.helper(Sub(), 1)", + "type(obj).helper(obj, 1)", + "cls.helper(obj, 1)", + "self.other.helper(obj, 1)", + "obj.helper(1)", + "fn = C.helper", + ]; + const text = lines.join("\n"); + const usages = lines.map((_, i) => usageIn("a.py", text, i)); + const breaking = breakingUsages(usages, () => text.split("\n")); + expect(breaking.map((u) => lines[u.range.start.line])).toEqual(lines.slice(3)); + // A file that could not be read is not known to keep working. + expect(breakingUsages(usages.slice(0, 1), () => null)).toHaveLength(1); +}); + +const viewOf = (text: string) => { + const view = { + state: EditorState.create({ doc: text }), + dispatch: vi.fn((spec: { changes: never }) => { + view.state = view.state.update(spec).state; + }), + }; + return view; +}; +const refs = (locations: Location[]): References => ({ locations, incomplete: null }); + +beforeEach(() => { + vi.clearAllMocks(); +}); + +it("makes the method static when every usage calls it through an instance", async () => { + const own = SRC + " def run(self):\n return self.helper(1)\n"; + const other = "from a import C\nC().helper(2)\nclass D(C):\n def go(self):\n return super().helper(3)\n"; + const view = viewOf(own); + lspReferences.mockResolvedValue(refs([usageIn("/p/a.py", own, 5), usageIn("/p/b.py", other, 4)])); + readManyFileLines.mockResolvedValue(new Map([["/p/b.py", other.split("\n")]])); + const fix = makeStaticChanges(view.state.doc, FACTS, view.state.doc.line(3).from + 10)!; + await makeMethodStatic(view as unknown as EditorView, "/p/a.py", 1, fix); + expect(readManyFileLines).toHaveBeenCalledWith(["/p/b.py"]); + expect(view.state.doc.toString()).toBe(STATIC + " def run(self):\n return self.helper(1)\n"); + expect(showHint).not.toHaveBeenCalled(); +}); + +it("refuses when a usage elsewhere calls it through an alias or a subclass", async () => { + const other = + "from a import C\nclass Sub(C): pass\nAlias = C\nprint(Alias.helper(Alias(), 1))\nprint(Sub.helper(Sub(), 2))\n"; + const view = viewOf(SRC); + const breaking = [usageIn("/p/b.py", other, 3), usageIn("/p/b.py", other, 4)]; + lspReferences.mockResolvedValue(refs(breaking)); + readManyFileLines.mockResolvedValue(new Map([["/p/b.py", other.split("\n")]])); + const fix = makeStaticChanges(view.state.doc, FACTS, view.state.doc.line(3).from + 10)!; + await makeMethodStatic(view as unknown as EditorView, "/p/a.py", 1, fix); + expect(view.dispatch).not.toHaveBeenCalled(); + expect(showHint.mock.lastCall![1]).toBe("Cannot make 'helper' static: 2 usages may call it through a class"); + expect(executeAction).toHaveBeenCalledWith("find.showUsageResults", { symbol: "helper", locations: breaking }); +}); + +it("refuses when the usages cannot be searched completely", async () => { + const view = viewOf(SRC); + const fix = makeStaticChanges(view.state.doc, FACTS, view.state.doc.line(3).from + 10)!; + lspReferences.mockRejectedValueOnce(new Error("no server")); + await makeMethodStatic(view as unknown as EditorView, "/p/a.py", 1, fix); + lspReferences.mockResolvedValueOnce({ locations: [], incomplete: "indexing" } as unknown as References); + await makeMethodStatic(view as unknown as EditorView, "/p/a.py", 1, fix); + expect(view.dispatch).not.toHaveBeenCalled(); + expect(showHint).toHaveBeenCalledTimes(2); +}); diff --git a/src/features/analysis/makeStatic.ts b/src/features/analysis/makeStatic.ts new file mode 100644 index 0000000000..49fb3afd81 --- /dev/null +++ b/src/features/analysis/makeStatic.ts @@ -0,0 +1,96 @@ +import { Channel } from "@tauri-apps/api/core"; +import type { ChangeSpec, Text } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { readManyFileLines } from "@/editor/lsp/files"; +import { showHint } from "@/editor/lsp/hint"; +import { lspRequest } from "@/editor/lsp/lsp"; +import { posToOffset } from "@/editor/lsp/positions"; +import { executeAction } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import { commands, nextRequestId, type Location, type Pos, type PythonFacts } from "@/platform/ipc"; + +/** Make method static for one method: its name (and where it is) and the edit of its definition. */ +export interface MakeStaticFix { + name: string; + at: Pos; + changes: ChangeSpec[]; +} + +/** + * Make method static for the method whose name is at `pos`: `@staticmethod` above its + * definition (decorators included) and its receiver parameter removed. Whether its + * call sites keep working is for {@link makeMethodStatic} to find out. + */ +export function makeStaticChanges(doc: Text, facts: PythonFacts, pos: number): MakeStaticFix | null { + for (const cls of facts.classes) { + for (const method of cls.methods) { + const { selection, unusedReceiver } = method; + if (!unusedReceiver || pos < posToOffset(doc, selection.start) || pos > posToOffset(doc, selection.end)) continue; + const first = doc.line(Math.min(method.definitionLine + 1, doc.lines)); + const indent = /^\s*/.exec(first.text)![0]; + return { + name: method.name, + at: selection.start, + changes: [ + { from: first.from, insert: `${indent}@staticmethod\n` }, + { from: posToOffset(doc, unusedReceiver.start), to: posToOffset(doc, unusedReceiver.end) }, + ], + }; + } + } + return null; +} + +// `self.m` or `super().m` / `super(C, self).m`, the name being the usage. +const THROUGH_INSTANCE = /(?:^|[^\w.])(?:self|super\([^()]*\))\s*\.\s*$/; + +/** + * The usages a static method would break. Through an instance (`self.m(...)`, + * `super().m(...)`) a call keeps working; through anything else the receiver may be a + * class — `C.m(obj, ...)`, an alias of it, a subclass, `type(obj)` — that passes the + * instance itself, so those count as breaking. + * ponytail: receivers are read as text, not typed; `obj.m(...)` blocks the fix too. + */ +export function breakingUsages( + usages: readonly Location[], + linesOf: (path: string) => readonly string[] | null | undefined, +): Location[] { + return usages.filter(({ path, range }) => { + const line = linesOf(path)?.[range.start.line]; + return line === undefined || !THROUGH_INSTANCE.test(line.slice(0, range.start.col)); + }); +} + +/** + * Applies `fix` once Find Usages (the language server's references, the whole project) + * shows every call site keeps working; otherwise says why not and lists the ones that would break. + */ +export async function makeMethodStatic(view: EditorView, path: string, doc: number, fix: MakeStaticFix) { + const before = view.state.doc; + let usages: Location[]; + try { + const refs = await lspRequest(() => + commands.lspReferences(nextRequestId(), doc, fix.at, false, true, false, new Channel()), + ); + if (refs.incomplete) throw new Error("incomplete"); + usages = refs.locations; + } catch { + showHint(view, tx`Cannot make '${fix.name}' static: its usages could not be searched`, { tone: "warning" }); + return; + } + const files = await readManyFileLines(usages.map((u) => u.path).filter((p) => p !== path)); + if (view.state.doc !== before) return; + const own = before.toString().split("\n"); + const breaking = breakingUsages(usages, (p) => (p === path ? own : files.get(p))); + if (!breaking.length) { + view.dispatch({ changes: fix.changes, userEvent: "input" }); + return; + } + const count = breaking.length; + const message = + count === 1 + ? tx`Cannot make '${fix.name}' static: 1 usage may call it through a class` + : tx`Cannot make '${fix.name}' static: ${count} usages may call it through a class`; + showHint(view, message, { tone: "warning" }); + void executeAction("find.showUsageResults", { symbol: fix.name, locations: breaking }); +} diff --git a/src/features/analysis/pythonSuppression.test.ts b/src/features/analysis/pythonSuppression.test.ts index 92b18cd6bb..8921c5b77a 100644 --- a/src/features/analysis/pythonSuppression.test.ts +++ b/src/features/analysis/pythonSuppression.test.ts @@ -43,6 +43,7 @@ const FACTS: PythonFacts = { abstractMethod: false, overrideDecorated: true, body: { kind: "empty" }, + unusedReceiver: null, }, ], }, diff --git a/src/features/settings/__tests__/inspections.test.ts b/src/features/settings/__tests__/inspections.test.ts index 45f6f3b639..f8d816fefa 100644 --- a/src/features/settings/__tests__/inspections.test.ts +++ b/src/features/settings/__tests__/inspections.test.ts @@ -126,6 +126,7 @@ describe("inspections tree", () => { "builtin:python-override", "builtin:python-abstract-method", "builtin:python-redundant-override", + "builtin:python-method-may-be-static", ]); expect(python.children[1]!.children.map((n) => n.id)).toEqual(["lsp:ruff:E501", "lsp:ruff:F401"]); expect(find(tree, "Python/lsp:ruff:F401")!.description).toContain("imported but unused"); diff --git a/src/platform/inspections.ts b/src/platform/inspections.ts index e531237282..a12c843f45 100644 --- a/src/platform/inspections.ts +++ b/src/platform/inspections.ts @@ -257,6 +257,8 @@ export const PYTHON_ABSTRACT_METHOD_PRODUCER = "python-abstract-method"; export const PYTHON_ABSTRACT_METHOD_INSPECTION = "builtin:python-abstract-method"; export const PYTHON_REDUNDANT_OVERRIDE_PRODUCER = "python-redundant-override"; export const PYTHON_REDUNDANT_OVERRIDE_INSPECTION = "builtin:python-redundant-override"; +export const PYTHON_METHOD_MAY_BE_STATIC_PRODUCER = "python-method-may-be-static"; +export const PYTHON_METHOD_MAY_BE_STATIC_INSPECTION = "builtin:python-method-may-be-static"; /** IDEA's Typo options: which parts of source files are checked (plain text always is). */ export const SPELLING_OPTIONS = { @@ -386,6 +388,16 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [ "Reports a method whose body only repeats the inherited one — 'pass' over a method that does nothing, or calling 'super()' with the same arguments — so the override can be removed.", defaultLevel: "weakWarning", }, + { + id: PYTHON_METHOD_MAY_BE_STATIC_INSPECTION, + suppressId: "PyMethodMayBeStatic", + producer: PYTHON_METHOD_MAY_BE_STATIC_PRODUCER, + name: "Method may be static", + group: "Python", + description: + "Reports a method that never uses 'self': it can be a @staticmethod. Methods with decorators, dunder methods, stubs (pass, '...', a docstring or one raise) and methods that use super() are left alone, as are methods that override a base class's and classes whose hierarchy the IDE's index does not know completely. Alt+Enter makes the method static.", + defaultLevel: "weakWarning", + }, { id: "builtin:sql", producer: "sql-inspections", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 2aa26b58b2..c07b85b8c4 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2662,6 +2662,13 @@ "Method '{name}' is marked @override but no base class declares it": "Method '{name}' is marked @override but no base class declares it", "Class '{name}' does not implement abstract method '{method}'": "Class '{name}' does not implement abstract method '{method}'", "Redundant override of '{name}'": "Redundant override of '{name}'", + "Method may be static": "Method may be static", + "Reports a method that never uses 'self': it can be a @staticmethod. Methods with decorators, dunder methods, stubs (pass, '...', a docstring or one raise) and methods that use super() are left alone, as are methods that override a base class's and classes whose hierarchy the IDE's index does not know completely. Alt+Enter makes the method static.": "Reports a method that never uses 'self': it can be a @staticmethod. Methods with decorators, dunder methods, stubs (pass, '...', a docstring or one raise) and methods that use super() are left alone, as are methods that override a base class's and classes whose hierarchy the IDE's index does not know completely. Alt+Enter makes the method static.", + "Method '{name}' may be static": "Method '{name}' may be static", + "Make method static": "Make method static", + "Cannot make '{name}' static: its usages could not be searched": "Cannot make '{name}' static: its usages could not be searched", + "Cannot make '{name}' static: 1 usage may call it through a class": "Cannot make '{name}' static: 1 usage may call it through a class", + "Cannot make '{name}' static: {count} usages may call it through a class": "Cannot make '{name}' static: {count} usages may call it through a class", "All Configurations": "All Configurations", "'{name}' keeps running without the debugger: {message}": "'{name}' keeps running without the debugger: {message}", "Show Changes": "Show Changes", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 29e34c04e0..1e40792cac 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9030,6 +9030,13 @@ "Method '{name}' is marked @override but no base class declares it": "方法 '{name}' 标记了 @override,但没有任何基类声明该方法", "Class '{name}' does not implement abstract method '{method}'": "类 '{name}' 未实现抽象方法 '{method}'", "Redundant override of '{name}'": "冗余的重写:'{name}'", + "Method may be static": "方法可以是静态的", + "Reports a method that never uses 'self': it can be a @staticmethod. Methods with decorators, dunder methods, stubs (pass, '...', a docstring or one raise) and methods that use super() are left alone, as are methods that override a base class's and classes whose hierarchy the IDE's index does not know completely. Alt+Enter makes the method static.": "报告从不使用 'self' 的方法:它可以是 @staticmethod。带装饰器的方法、dunder 方法、桩方法(pass、'...'、只有文档字符串或一条 raise)以及使用 super() 的方法不报告;重写基类方法的方法,以及 IDE 索引无法完整了解其继承层次的类,也不报告。按 Alt+Enter 可将方法改为静态。", + "Method '{name}' may be static": "方法 '{name}' 可以是静态的", + "Make method static": "将方法设为静态", + "Cannot make '{name}' static: its usages could not be searched": "无法将 '{name}' 设为静态:无法搜索其用法", + "Cannot make '{name}' static: 1 usage may call it through a class": "无法将 '{name}' 设为静态:有 1 处用法可能通过类调用它", + "Cannot make '{name}' static: {count} usages may call it through a class": "无法将 '{name}' 设为静态:有 {count} 处用法可能通过类调用它", "Import Module from Existing Sources…": "导入已有模块…", "{name} (copy)": "{name}(副本)", "{name} (copy {n})": "{name}(副本 {n})",