From c72a162b5cda4a540c09f513aa985f476c49157d Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Tue, 24 Nov 2026 09:23:02 +0900 Subject: [PATCH] feat(python): create a function, class or method from an unresolved reference (#5355) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On an unresolved name in Python, Alt+Enter only offered basedpyright's "Add `# pyright: ignore[...]`" (and an import when one matches). It now also offers PyCharm's **Create function 'foo'** and **Create class 'Foo'** on an undefined name, and **Create method 'bar' in 'Greeter'** on a missing method called on `self`/`cls`. Parameters come from the call site: a keyword keeps its keyword, a plain-name argument keeps its name, others become `param1`, `param2`…, with `*args` / `**kwargs` for starred arguments; positional and starred names are renamed so they never repeat the receiver or a keyword. The function or class goes above the top-level statement that uses it; the method goes at the end of the enclosing class, a `@classmethod` when the calling method is one (none is offered from a `@staticmethod`). The caret lands on the `pass` body. The server says what is unresolved (`reportUndefinedVariable` / `reportAttributeAccessIssue`, and the equivalent codes of Ruff, ty and pyrefly); the parse tree says where and how it is used. The fixes are local quick fixes, so they also show in the problem hover's quick-fix list. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/editor/lsp/intentions.ts | 4 + src/editor/lsp/semantic/languages.ts | 2 + .../semantic/python/createFromUsage.test.ts | 123 ++++++++++ .../lsp/semantic/python/createFromUsage.ts | 219 ++++++++++++++++++ src/editor/lsp/semantic/python/index.ts | 7 +- src/platform/locales/text/en.json | 3 + src/platform/locales/text/zh.json | 3 + 7 files changed, 360 insertions(+), 1 deletion(-) create mode 100644 src/editor/lsp/semantic/python/createFromUsage.test.ts create mode 100644 src/editor/lsp/semantic/python/createFromUsage.ts diff --git a/src/editor/lsp/intentions.ts b/src/editor/lsp/intentions.ts index fc0c2552c5..f9cfd5fb57 100644 --- a/src/editor/lsp/intentions.ts +++ b/src/editor/lsp/intentions.ts @@ -15,6 +15,7 @@ import { contributedIntentionsAsync, contributedQuickFixes, intentionProviders, + quickFixProviders, intentionsChanged, whenSynced, } from "@/editor/api"; @@ -882,6 +883,9 @@ export function intentionsExtension(): Extension { bulbPlugin, floatingBulb, intentionProviders.of((view) => languageSemantics(docOf(view)?.language)?.intentions?.(view) ?? []), + quickFixProviders.of( + (view, from, to) => languageSemantics(docOf(view)?.language)?.quickFixes?.(view, from, to) ?? [], + ), asyncIntentionProviders.of( async (view, signal) => (await languageSemantics(docOf(view)?.language)?.asyncIntentions?.(view, signal)) ?? [], ), diff --git a/src/editor/lsp/semantic/languages.ts b/src/editor/lsp/semantic/languages.ts index da29c4b8a6..88deacdf4b 100644 --- a/src/editor/lsp/semantic/languages.ts +++ b/src/editor/lsp/semantic/languages.ts @@ -57,6 +57,8 @@ export interface LanguageSemantics { constructDocumentation?(name: string): string | null; /** Bulb intentions contributed on this language's documents. */ intentions?(view: EditorView): ContributedIntention[]; + /** Local fixes of the problems at `from..to` on this language's documents (also listed by ⌥↵ at the caret). */ + quickFixes?(view: EditorView, from: number, to: number): ContributedIntention[]; /** Intentions that need the language server's answer first; `signal` aborts when the caret moved on. */ asyncIntentions?(view: EditorView, signal: AbortSignal): Promise; /** Fallback for the Implement Methods action when the server offers no code action. */ diff --git a/src/editor/lsp/semantic/python/createFromUsage.test.ts b/src/editor/lsp/semantic/python/createFromUsage.test.ts new file mode 100644 index 0000000000..b44d785647 --- /dev/null +++ b/src/editor/lsp/semantic/python/createFromUsage.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from "vitest"; +import { EditorState } from "@codemirror/state"; +import { completedSyntaxTree } from "@/test/syntax"; +import { findLanguageDescription, loadSupport } from "../../../core/cm/languages"; +import { createForAttribute, createForName, type CreateFix } from "./createFromUsage"; + +async function parse(source: string) { + const support = await loadSupport(findLanguageDescription("Python", "demo.py")!); + const state = EditorState.create({ doc: source, extensions: [support!] }); + return { doc: state.doc, tree: completedSyntaxTree(state) }; +} + +function applied(source: string, fix: CreateFix): string { + const { from, text } = fix.insert; + return source.slice(0, from) + text + source.slice(from); +} + +const at = (source: string, needle: string) => source.indexOf(needle); + +describe("Python create from usage", () => { + it("creates a function above the top-level statement with parameters from the call", async () => { + const source = + "import os\n\n\ndef main():\n r = make(count, label=x, *rest, **opts)\n make2(1, a.b, count, count)\n"; + const { doc, tree } = await parse(source); + const [fn, cls] = createForName(tree, doc, at(source, "make("), " "); + expect(fn!.kind).toBe("function"); + expect(applied(source, fn!)).toBe( + "import os\n\n\ndef make(count, *args, label, **kwargs):\n pass\n\n\ndef main():\n" + + " r = make(count, label=x, *rest, **opts)\n make2(1, a.b, count, count)\n", + ); + expect(fn!.insert.text.slice(fn!.body, fn!.body + 4)).toBe("pass"); + expect(cls!.insert.text).toBe( + "class make:\n def __init__(self, count, *args, label, **kwargs):\n pass\n\n\n", + ); + expect(cls!.insert.text.slice(cls!.body, cls!.body + 4)).toBe("pass"); + + const [fn2] = createForName(tree, doc, at(source, "make2"), " "); + expect(fn2!.insert.text).toMatch(/^def make2\(param1, param2, count, count1\):/); + }); + + it("offers only a class for a name that is not called", async () => { + const source = "x = isinstance(y, Widget)\n"; + const { doc, tree } = await parse(source); + const fixes = createForName(tree, doc, at(source, "Widget"), " "); + expect(fixes.map((f) => f.kind)).toEqual(["class"]); + expect(fixes[0]!.insert.text).toBe("class Widget:\n pass\n\n\n"); + }); + + it("creates a method at the end of the class for self and cls calls", async () => { + const source = + "class Greeter:\n def greet(self, name):\n self.helper(name, 3)\n\n @classmethod\n" + + " def make(cls):\n return cls.build()\n\n\nprint(1)\n"; + const { doc, tree } = await parse(source); + const [method] = createForAttribute(tree, doc, at(source, "helper"), " "); + expect(method!.owner).toBe("Greeter"); + const result = applied(source, method!); + expect(result).toContain( + " return cls.build()\n\n def helper(self, name, param1):\n pass\n\n\nprint(1)\n", + ); + expect(method!.insert.text.slice(method!.body, method!.body + 4)).toBe("pass"); + + const [classMethod] = createForAttribute(tree, doc, at(source, "build"), " "); + expect(classMethod!.insert.text).toBe("\n\n @classmethod\n def build(cls):\n pass"); + }); + + it("offers no method for another receiver or an attribute that is not called", async () => { + const source = "class A:\n def f(self, other):\n other.g()\n self.h\n"; + const { doc, tree } = await parse(source); + expect(createForAttribute(tree, doc, at(source, "g()"), " ")).toEqual([]); + expect(createForAttribute(tree, doc, at(source, "h\n"), " ")).toEqual([]); + }); + + it("never repeats a name: the receiver and keywords win, positional and starred names are renamed", async () => { + const source = + "def run():\n f(args, *rest)\n g(kwargs, **o)\n h(x, x=1)\n k(a, # note\n label=1)\n" + + " panel = Panel(self)\n"; + const { doc, tree } = await parse(source); + const head = (needle: string, kind = 0) => + createForName(tree, doc, at(source, needle), " ")[kind]!.insert.text.split("\n")[0]; + expect(head("f(")).toBe("def f(args, *args1):"); + expect(head("g(")).toBe("def g(kwargs, **kwargs1):"); + expect(head("h(")).toBe("def h(x1, x):"); + expect(head("k(")).toBe("def k(a, label):"); + expect(createForName(tree, doc, at(source, "Panel"), " ")[1]!.insert.text).toMatch( + /^class Panel:\n {4}def __init__\(self, self1\):/, + ); + }); + + it("follows the calling method's decorators, not the receiver's name", async () => { + const source = + "class A:\n def f(self):\n self.register(self)\n\n @classmethod\n def make(klass):\n" + + " return klass.build()\n\n @staticmethod\n def s(x):\n x.g()\n"; + const { doc, tree } = await parse(source); + const text = (needle: string) => + createForAttribute(tree, doc, at(source, needle), " ").map((f) => f.insert.text); + expect(text("register")).toEqual(["\n\n def register(self, self1):\n pass"]); + expect(text("build")).toEqual(["\n\n @classmethod\n def build(klass):\n pass"]); + expect(text("g()")).toEqual([]); + }); + it("keeps receiver keywords and makes normalized parameter names unique", async () => { + const source = "def run(K):\n work(K, K, 1, param1)\n return Widget(self=1)\n"; + const { doc, tree } = await parse(source); + expect(createForName(tree, doc, at(source, "work"), " ")[0]!.insert.text).toMatch( + /^def work\(K, K1, param2, param1\):/, + ); + expect(createForName(tree, doc, at(source, "Widget"), " ")[1]!.insert.text).toMatch( + /^class Widget:\n {4}def __init__\(self1, self\):/, + ); + }); + + it("creates async functions and methods for awaited calls, including grouped calls", async () => { + const source = + "async def run():\n await (work(1))\n\nclass A:\n @builtins.classmethod\n" + + " async def run(cls):\n await (cls.load)(cls=1)\n\n" + + " @builtins.staticmethod\n def other(x):\n x.missing()\n"; + const { doc, tree } = await parse(source); + expect(createForName(tree, doc, at(source, "work"), " ")[0]!.insert.text).toMatch(/^async def work\(param1\):/); + expect(createForAttribute(tree, doc, at(source, "load"), " ")[0]!.insert.text).toContain( + " @classmethod\n async def load(cls1, cls):", + ); + expect(createForAttribute(tree, doc, at(source, "missing"), " ")).toEqual([]); + }); +}); diff --git a/src/editor/lsp/semantic/python/createFromUsage.ts b/src/editor/lsp/semantic/python/createFromUsage.ts new file mode 100644 index 0000000000..0a9e6c47ae --- /dev/null +++ b/src/editor/lsp/semantic/python/createFromUsage.ts @@ -0,0 +1,219 @@ +/** + * PyCharm's "Create function / class / method" quick fixes on an unresolved + * reference. Python servers only offer an import or a suppression comment; the + * server says what is unresolved, the parse tree says where and how it is used. + */ +import { syntaxTree, indentUnit } from "@codemirror/language"; +import type { EditorState, Text } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { forEachDiagnostic } from "@codemirror/lint"; +import type { SyntaxNode, Tree } from "@lezer/common"; +import type { ContributedIntention } from "@/editor/api"; +import { tx } from "@/platform/i18n"; +import { docOf } from "../../lsp"; +import type { EditorDiagnostic } from "../../diagnostics"; + +/** Unresolved-name and missing-attribute codes of basedpyright/pyright, Ruff, ty and pyrefly. */ +const UNDEFINED_NAME = new Set(["reportUndefinedVariable", "F821", "unresolved-reference", "unknown-name"]); +const MISSING_ATTRIBUTE = new Set(["reportAttributeAccessIssue", "unresolved-attribute", "missing-attribute"]); + +export interface CreateFix { + kind: "function" | "class" | "method"; + name: string; + /** The class a method goes into. */ + owner?: string; + insert: { from: number; text: string }; + /** Offset of the `pass` placeholder inside `text`. */ + body: number; +} + +const PASS = "pass"; +const indentOf = (doc: Text, pos: number) => /^\s*/.exec(doc.lineAt(pos).text)![0]; + +/** + * Parameter names for the arguments of `args` (an ArgList), in an order a `def` accepts. + * Keyword names are kept, since callers pass them by name. The receiver, positional + * and starred parameters are made unique using Python's identifier normalization. + */ +function paramsFor(args: SyntaxNode | null, doc: Text, receiver?: string): string[] { + if (!args) return receiver ? [receiver] : []; + const groups: SyntaxNode[][] = [[]]; + for (let c = args.firstChild; c; c = c.nextSibling) { + if (c.name === "(" || c.name === ")" || c.name === "Comment") continue; + if (c.name === ",") groups.push([]); + else groups[groups.length - 1]!.push(c); + } + const positional: string[] = []; + const keyword = new Map(); + let star = false; + let starStar = false; + for (const g of groups) { + const [first, second] = g; + if (!first) continue; + if (first.name === "*") star = true; + else if (first.name === "**") starStar = true; + else if (second?.name === "AssignOp") { + const name = doc.sliceString(first.from, first.to); + keyword.set(name.normalize("NFKC"), name); + } else if (g.length === 1 && first.name === "VariableName") positional.push(doc.sliceString(first.from, first.to)); + else positional.push(""); + } + const used = new Set(keyword.keys()); + const unique = (base: string) => { + let name = base; + for (let i = 1; used.has(name.normalize("NFKC")); i++) name = `${base}${i}`; + used.add(name.normalize("NFKC")); + return name; + }; + const leading = receiver ? [unique(receiver)] : []; + const named = positional.map((name) => name && unique(name)); + let next = 0; + const parameters = named.map((name) => { + if (name) return name; + let placeholder: string; + do placeholder = `param${++next}`; + while (used.has(placeholder)); + return unique(placeholder); + }); + const args_ = star ? [`*${unique("args")}`] : []; + const kwargs = starStar ? [`**${unique("kwargs")}`] : []; + return [...leading, ...parameters, ...args_, ...keyword.values(), ...kwargs]; +} + +function topLevel(node: SyntaxNode): SyntaxNode | null { + for (let n: SyntaxNode | null = node; n; n = n.parent) if (n.parent?.name === "Script") return n; + return null; +} + +function outsideParentheses(node: SyntaxNode): SyntaxNode { + while (node.parent?.name === "ParenthesizedExpression") node = node.parent; + return node; +} + +/** The call `node` (a name or attribute) is the callee of, if any. */ +function callOf(node: SyntaxNode): SyntaxNode | null { + const callee = outsideParentheses(node); + const call = callee.parent; + return call?.name === "CallExpression" && call.firstChild?.from === callee.from && call.firstChild.to === callee.to + ? call + : null; +} + +function functionText( + name: string, + params: string[], + indent: string, + unit: string, + { awaited = false, decorator = "" }: { awaited?: boolean; decorator?: string } = {}, +) { + const head = `${decorator}${indent}${awaited ? "async " : ""}def ${name}(${params.join(", ")}):\n${indent}${unit}`; + return { text: head + PASS, body: head.length }; +} + +/** Fixes for an unresolved name at `from..to`. */ +export function createForName(tree: Tree, doc: Text, from: number, unit: string): CreateFix[] { + const node = tree.resolveInner(from, 1); + if (node.name !== "VariableName") return []; + const statement = topLevel(node); + if (!statement) return []; + const name = doc.sliceString(node.from, node.to); + const call = callOf(node); + const args = call?.getChild("ArgList") ?? null; + const at = statement.from; + const gap = "\n\n\n"; + const fixes: CreateFix[] = []; + if (call) { + const f = functionText(name, paramsFor(args, doc), "", unit, { + awaited: outsideParentheses(call).parent?.name === "AwaitExpression", + }); + fixes.push({ kind: "function", name, insert: { from: at, text: f.text + gap }, body: f.body }); + } + const initParams = paramsFor(args, doc, "self"); + const init = initParams.length > 1 ? functionText("__init__", initParams, unit, unit) : null; + const head = `class ${name}:\n`; + const cls = init + ? { text: head + init.text, body: head.length + init.body } + : { text: head + unit + PASS, body: head.length + unit.length }; + fixes.push({ kind: "class", name, insert: { from: at, text: cls.text + gap }, body: cls.body }); + return fixes; +} + +/** A fix for a missing method called on `self`/`cls` inside its class, the attribute at `from`. */ +export function createForAttribute(tree: Tree, doc: Text, from: number, unit: string): CreateFix[] { + const property = tree.resolveInner(from, 1); + const member = property.parent; + if (property.name !== "PropertyName" || member?.name !== "MemberExpression") return []; + const call = callOf(member); + const receiver = member.firstChild; + if (!call || receiver?.name !== "VariableName") return []; + let fn: SyntaxNode | null = member; + while (fn && fn.name !== "FunctionDefinition") fn = fn.parent; + const holder = fn?.parent?.name === "DecoratedStatement" ? fn.parent : fn; + const cls = holder?.parent?.parent; + if (!fn || cls?.name !== "ClassDefinition") return []; + const first = fn.getChild("ParamList")?.getChild("VariableName"); + const self = doc.sliceString(receiver.from, receiver.to); + if (!first || doc.sliceString(first.from, first.to).normalize("NFKC") !== self.normalize("NFKC")) return []; + // The new method is of the kind of the one calling it; a static method has no receiver. + const decorators = (holder === fn ? [] : holder!.getChildren("Decorator")).map( + (d) => /^@\s*([\w.]+)/.exec(doc.sliceString(d.from, d.to))?.[1], + ); + if (decorators.includes("staticmethod") || decorators.includes("builtins.staticmethod")) return []; + const name = doc.sliceString(property.from, property.to); + const owner = doc.sliceString(cls.getChild("VariableName")!.from, cls.getChild("VariableName")!.to); + const indent = indentOf(doc, holder!.from); + const classMethod = decorators.includes("classmethod") || decorators.includes("builtins.classmethod"); + const f = functionText(name, paramsFor(call.getChild("ArgList"), doc, self), indent, unit, { + awaited: outsideParentheses(call).parent?.name === "AwaitExpression", + decorator: classMethod ? `${indent}@classmethod\n` : "", + }); + const body = cls.getChild("Body")!; + const end = doc.lineAt(body.from + doc.sliceString(body.from, body.to).trimEnd().length).to; + return [{ kind: "method", name, owner, insert: { from: end, text: `\n\n${f.text}` }, body: 2 + f.body }]; +} + +function label(fix: CreateFix): string { + const { name, owner } = fix; + if (fix.kind === "function") return tx`Create function '${name}'`; + if (fix.kind === "class") return tx`Create class '${name}'`; + return tx`Create method '${name}' in '${owner}'`; +} + +export function createFixes(state: EditorState, from: number, to: number): CreateFix[] { + const tree = syntaxTree(state); + const unit = state.facet(indentUnit); + const fixes: CreateFix[] = []; + const seen = new Set(); + forEachDiagnostic(state, (d, dFrom, dTo) => { + const code = (d as EditorDiagnostic).problem?.code; + if (code == null || dFrom > to || dTo < from || seen.has(dFrom)) return; + if (UNDEFINED_NAME.has(code)) fixes.push(...createForName(tree, state.doc, dFrom, unit)); + else if (MISSING_ATTRIBUTE.has(code)) fixes.push(...createForAttribute(tree, state.doc, dFrom, unit)); + else return; + seen.add(dFrom); + }); + return fixes; +} + +function apply(view: EditorView, fix: CreateFix): void { + const { from, text } = fix.insert; + const body = from + fix.body; + view.dispatch({ + changes: { from, insert: text }, + selection: { anchor: body, head: body + PASS.length }, + userEvent: "input.complete", + scrollIntoView: true, + }); + view.focus(); +} + +/** Quick fixes of the unresolved references at `from..to` (the caret for ⌥↵). */ +export function pythonCreateFixes(view: EditorView, from: number, to: number): ContributedIntention[] { + if (docOf(view)?.uiMode !== "Python") return []; + return createFixes(view.state, from, to).map((fix) => ({ + id: `python.create.${fix.kind}:${fix.name}`, + label: label(fix), + quickFix: true, + run: () => apply(view, fix), + })); +} diff --git a/src/editor/lsp/semantic/python/index.ts b/src/editor/lsp/semantic/python/index.ts index ac5f21bea0..8eef387724 100644 --- a/src/editor/lsp/semantic/python/index.ts +++ b/src/editor/lsp/semantic/python/index.ts @@ -13,6 +13,7 @@ import { type PythonSymbolKind, } from "./highlight"; import { implementPythonAbstractMethods, pythonMemberIntentions } from "./members"; +import { pythonCreateFixes } from "./createFromUsage"; import { pythonTypeHintIntentions } from "./typeHints"; import { pythonStringIntentions } from "./stringFormat"; @@ -54,7 +55,11 @@ const pythonSemantics: LanguageSemantics = { } }, isLocal: ({ type, kind }) => (kind ? kind === "localVariable" || kind === "parameter" : type === "parameter"), - intentions: (view) => [...pythonMemberIntentions(view), ...pythonStringIntentions(view)], + intentions: (view) => { + const { from, to } = view.state.selection.main; + return [...pythonCreateFixes(view, from, to), ...pythonMemberIntentions(view), ...pythonStringIntentions(view)]; + }, + quickFixes: pythonCreateFixes, asyncIntentions: pythonTypeHintIntentions, implementMethods: implementPythonAbstractMethods, }; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 772d6b012b..78b49afed9 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1,4 +1,7 @@ { + "Create function '{name}'": "Create function '{name}'", + "Create class '{name}'": "Create class '{name}'", + "Create method '{name}' in '{owner}'": "Create method '{name}' in '{owner}'", "Docstring stubs (Enter after \"\"\") are written in this markup format, and docstring tags and keywords are highlighted according to it (Color Scheme › Python styles their colours).": "Docstring stubs (Enter after \"\"\") are written in this markup format, and docstring tags and keywords are highlighted according to it (Color Scheme › Python styles their colours).", "Default dictionary": "Default dictionary", "The dictionary the editor's Save '…' to dictionary quick fix writes to.": "The dictionary the editor's Save '…' to dictionary quick fix writes to.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 101b667d6d..7dfe2683f7 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1,4 +1,7 @@ { + "Create function '{name}'": "创建函数 '{name}'", + "Create class '{name}'": "创建类 '{name}'", + "Create method '{name}' in '{owner}'": "在 '{owner}' 中创建方法 '{name}'", "Amend commit failed": "修订提交失败", "Amending this commit would cause a conflict. You can keep the prepared changes as a separate amend commit.": "修订此提交会产生冲突。可以将已准备好的改动保留为单独的修订提交。", "Create Amend Commit Anyway": "仍然创建修订提交",