From 8b4e1e71fb2d37f10459759c067e718c9aad528c Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Wed, 25 Nov 2026 00:49:11 +0900 Subject: [PATCH] feat(editor): Override Methods and Generate entries for Python classes (#5353) Python classes had Implement Methods but no Override Methods or Generate. Override Methods (Ctrl+O) now opens a member chooser ("Select Methods to Override", grouped by declaring class) when the language server offers no code action, and Generate (Cmd+N / Alt+Insert) lists Override Methods and Implement Methods in Python editors. The overridable methods follow the class's C3 linearization: for each name only the first definition in MRO order is offered, so the copied signature matches what super() calls; a @final, overload-only or name-mangled first definition hides the name. Class headers spanning several lines are read up to their closing colon, and inserting into a one-line class body (class C(Base): pass) splits it first. Overrides of one-line, static and non-ASCII methods are generated correctly, and missing imports for annotations are added. Closes #5328 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/editor/lsp/MemberChooserDialog.module.css | 91 ++++ src/editor/lsp/MemberChooserDialog.test.tsx | 38 ++ src/editor/lsp/MemberChooserDialog.tsx | 100 ++++ src/editor/lsp/actions.ts | 25 +- src/editor/lsp/index.ts | 2 + src/editor/lsp/memberChooser.ts | 39 ++ src/editor/lsp/semantic/languages.ts | 12 + .../lsp/semantic/python/imports.test.ts | 88 ++++ src/editor/lsp/semantic/python/imports.ts | 134 +++++ src/editor/lsp/semantic/python/index.ts | 9 +- .../lsp/semantic/python/members.test.ts | 196 ++++++- src/editor/lsp/semantic/python/members.ts | 485 ++++++++++++++++-- src/platform/keymaps/newElement.test.ts | 3 +- src/platform/locales/text/en.json | 2 + src/platform/locales/text/zh.json | 2 + 15 files changed, 1175 insertions(+), 51 deletions(-) create mode 100644 src/editor/lsp/MemberChooserDialog.module.css create mode 100644 src/editor/lsp/MemberChooserDialog.test.tsx create mode 100644 src/editor/lsp/MemberChooserDialog.tsx create mode 100644 src/editor/lsp/memberChooser.ts create mode 100644 src/editor/lsp/semantic/python/imports.test.ts create mode 100644 src/editor/lsp/semantic/python/imports.ts diff --git a/src/editor/lsp/MemberChooserDialog.module.css b/src/editor/lsp/MemberChooserDialog.module.css new file mode 100644 index 0000000000..16549862f2 --- /dev/null +++ b/src/editor/lsp/MemberChooserDialog.module.css @@ -0,0 +1,91 @@ +.dialog { + height: 460px; +} + +.dialog > [data-dialog-body] { + display: flex; + flex-direction: column; +} + +.body { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + padding: var(--space-2) var(--space-4); + font-size: var(--fs-ui); + color: var(--fg); +} + +.table { + flex: 1; + min-height: calc(var(--h-list-row) * 3); + overflow: auto; + scrollbar-gutter: stable; + scroll-padding-top: var(--h-list-row); + border: 1px solid var(--border); + border-radius: var(--radius-small); +} + +.head, +.row, +.group { + display: grid; + grid-template-columns: minmax(0, 1fr); + align-items: center; + padding: 0 var(--space-2); + min-height: var(--h-list-row); +} + +.head { + position: sticky; + top: 0; + z-index: 1; + background: var(--bg-popup); + border-bottom: 1px solid var(--border); +} + +.head .member { + color: var(--fg-muted); +} + +.group > span { + display: flex; + align-items: center; + gap: var(--space-1); + color: var(--fg-muted); +} + +.row[data-grouped] { + padding-left: calc(var(--space-2) + var(--space-4)); +} + +.row:hover { + background: var(--bg-hover); +} + +.member { + display: flex; + min-width: 0; +} + +.memberLabel { + display: flex; + align-items: center; + gap: var(--space-1); +} + +.memberLabel > svg { + flex: none; +} + +.label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: var(--font-mono); +} + +.detail { + color: var(--fg-muted); +} diff --git a/src/editor/lsp/MemberChooserDialog.test.tsx b/src/editor/lsp/MemberChooserDialog.test.tsx new file mode 100644 index 0000000000..baeeb7a89f --- /dev/null +++ b/src/editor/lsp/MemberChooserDialog.test.tsx @@ -0,0 +1,38 @@ +import { describe, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen } from "@testing-library/react"; +import type { EditorView } from "@codemirror/view"; +import { MemberChooserDialog } from "./MemberChooserDialog"; +import { chooseMembers, useMemberChooser } from "./memberChooser"; + +const view = { focus: vi.fn() } as unknown as EditorView; +const members = [ + { id: "a", label: "area", detail: "(self)", icon: "method", group: "Shape" }, + { id: "b", label: "describe", detail: "(self)", icon: "method", group: "Shape" }, + { id: "c", label: "__repr__", detail: "(self)", icon: "method", group: "Base" }, +]; + +describe("MemberChooserDialog", () => { + it("groups the members and resolves with the checked ones in list order", async () => { + render(); + let chosen!: Promise; + act(() => void (chosen = chooseMembers(view, { title: "Select Methods to Override", members }))); + expect(screen.getByText("Shape")).toBeTruthy(); + expect(screen.getByText("Base")).toBeTruthy(); + const ok = screen.getByRole("button", { name: "OK" }); + expect((ok as HTMLButtonElement).disabled).toBe(true); + fireEvent.click(screen.getByText("__repr__")); + fireEvent.click(screen.getByText("area")); + fireEvent.click(ok); + await expect(chosen).resolves.toEqual(["a", "c"]); + expect(useMemberChooser.getState().request).toBeNull(); + }); + + it("resolves with null when cancelled", async () => { + render(); + let chosen!: Promise; + act(() => void (chosen = chooseMembers(view, { title: "Select Methods to Override", members }))); + fireEvent.click(screen.getByLabelText("Select All")); + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + await expect(chosen).resolves.toBeNull(); + }); +}); diff --git a/src/editor/lsp/MemberChooserDialog.tsx b/src/editor/lsp/MemberChooserDialog.tsx new file mode 100644 index 0000000000..087187c554 --- /dev/null +++ b/src/editor/lsp/MemberChooserDialog.tsx @@ -0,0 +1,100 @@ +import { useState } from "react"; +import { Checkbox, Dialog, Icon, T } from "@/ui"; +import { useTx } from "@/platform/i18n"; +import { useMemberChooser, type MemberChooserRequest } from "./memberChooser"; +import styles from "./MemberChooserDialog.module.css"; + +export function MemberChooserDialog() { + const request = useMemberChooser((s) => s.request); + if (!request) return null; + return ; +} + +function MemberChooserInner({ request }: { request: MemberChooserRequest }) { + const tx = useTx(); + const { members } = request; + const [checked, setChecked] = useState>(new Set()); + const allChecked = checked.size === members.length; + + const finish = (ids: string[] | null) => { + if (useMemberChooser.getState().request === request) useMemberChooser.setState({ request: null }); + request.resolve(ids); + request.view.focus(); + }; + const toggle = (id: string, on: boolean) => + setChecked((all) => { + const next = new Set(all); + if (on) next.add(id); + else next.delete(id); + return next; + }); + + return ( + finish(null)} + title={request.title} + className={styles.dialog} + width={520} + minWidth={320} + minHeight={300} + resizable="both" + buttons={[ + { + label: "OK", + role: "default", + disabled: !checked.size, + onClick: () => finish(members.map((m) => m.id).filter((id) => checked.has(id))), + }, + { label: "Cancel", role: "cancel" }, + ]} + > +
+
+
+
+ 0 && !allChecked} + onChange={(on) => setChecked(on ? new Set(members.map((m) => m.id)) : new Set())} + aria-label="Select All" + label={Member} + /> +
+
+ {members.map((m, i) => ( +
+ {m.group && m.group !== members[i - 1]?.group && ( +
+ + + {m.group} + +
+ )} +
+
+ toggle(m.id, on)} + label={ + + + + {m.label} + {m.detail && {m.detail}} + + + } + /> +
+
+
+ ))} +
+
+
+ ); +} diff --git a/src/editor/lsp/actions.ts b/src/editor/lsp/actions.ts index 7ba28cf666..dea790059e 100644 --- a/src/editor/lsp/actions.ts +++ b/src/editor/lsp/actions.ts @@ -18,6 +18,7 @@ import { gotoDiagnostic, showErrorDescription } from "./diagnostics"; import { applyKindSilently, applyQuickFix, runKindAction, showIntentions } from "./intentions"; import { docOf, reportLspError } from "./lsp"; import { languageSemantics } from "./semantic"; +import { caretAnchor, openPopup } from "./popupStore"; import { workflowSettings, type ActionsOnSaveValid } from "@/platform/workflowSettings"; import { startRename } from "./rename"; import { formatDocument, reformatDialog, type FormatResult } from "./format"; @@ -38,8 +39,8 @@ import { tx } from "@/platform/i18n"; export const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)"; /** - * Languages whose servers offer Generate (constructors, accessors, overrides…). - * Elsewhere the Generate shortcut (⌘N / Alt+Insert) yields to the New popup, as in IDEA. + * Languages whose servers (or, for Python, the editor itself) offer Generate (constructors, + * accessors, overrides…). Elsewhere the Generate shortcut (⌘N / Alt+Insert) yields to the New popup, as in IDEA. */ const GENERATE_LANGUAGES = [ "java", @@ -60,6 +61,7 @@ const GENERATE_LANGUAGES = [ "swift", "dart", "php", + "python", ]; export const GENERATE_KEY_WHEN = GENERATE_LANGUAGES.map((id) => `editorLangId == ${id}`).join(" || "); @@ -461,6 +463,18 @@ export function registerLspActions(): () => void { label: tx("Generate"), compact: true, actionIcon: generateActionIcon, + fallback: async () => { + const entries = languageSemantics(docOf(v)?.language)?.generate?.(v) ?? []; + if (!entries.length) return false; + openPopup({ + kind: "list", + anchor: caretAnchor(v, v.state.selection.main.head), + title: tx("Generate"), + compact: true, + items: entries.map((e) => ({ id: e.id, label: tx(e.label), icon: e.icon, run: () => void e.run() })), + }); + return true; + }, }), { keyWhen: GENERATE_KEY_WHEN }, ), @@ -482,7 +496,12 @@ export function registerLspActions(): () => void { }), ), editorAction("code.overrideMethods", "Override Methods…", "Code", (v) => - runKindAction(v, "", { title: OVERRIDE_TITLE, none: "Nothing to override", label: "Override Members" }), + runKindAction(v, "", { + title: OVERRIDE_TITLE, + none: "Nothing to override", + label: "Override Members", + fallback: () => languageSemantics(docOf(v)?.language)?.overrideMethods?.(v) ?? Promise.resolve(false), + }), ), editorAction("code.expressionTypeInfo", "Expression Type Info", "View", expressionTypeInfo, { keywords: ["type of expression", "show type"], diff --git a/src/editor/lsp/index.ts b/src/editor/lsp/index.ts index 4023097550..19669d92e6 100644 --- a/src/editor/lsp/index.ts +++ b/src/editor/lsp/index.ts @@ -40,6 +40,7 @@ import { unresolvedReferences } from "./fileReferences"; import { syntaxErrorsExtension } from "./syntaxErrors"; import { spellingExtension } from "./spelling"; import { DocumentationWindow, LspPopups, UsagesStatus } from "./Popups"; +import { MemberChooserDialog } from "./MemberChooserDialog"; import { DOCUMENTATION_WINDOW } from "./docs"; import { prefetchMarkdown } from "./markdown"; import { outsideProjectBanner } from "./outsideProject"; @@ -129,6 +130,7 @@ export function activate(): () => void { registerOverlay({ id: "editor-lsp.hierarchyDialog", component: HierarchyDialog }), registerOverlay({ id: "editor-lsp.changeSignatureDialog", component: ChangeSignatureDialog }), registerOverlay({ id: "editor-lsp.extractInterfaceDialog", component: ExtractInterfaceDialog }), + registerOverlay({ id: "editor-lsp.memberChooser", component: MemberChooserDialog }), registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand), registerEditorBanner(outsideProjectBanner), registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }), diff --git a/src/editor/lsp/memberChooser.ts b/src/editor/lsp/memberChooser.ts new file mode 100644 index 0000000000..8a72f78126 --- /dev/null +++ b/src/editor/lsp/memberChooser.ts @@ -0,0 +1,39 @@ +/** + * IDEA's member chooser ("Select Methods to Override", "Choose Fields to Initialize"): a dialog + * with the members grouped by the class declaring them; resolves with the chosen ids in list + * order, or null when cancelled. + */ +import type { EditorView } from "@codemirror/view"; +import { create } from "zustand"; + +export interface ChooserMember { + id: string; + label: string; + /** Muted text after the label (the signature). */ + detail?: string; + icon: string; + /** Heading of the members' group (the declaring class). */ + group?: string; +} + +export interface MemberChooserRequest { + seq: number; + title: string; + members: ChooserMember[]; + view: EditorView; + resolve: (ids: string[] | null) => void; +} + +export const useMemberChooser = create<{ request: MemberChooserRequest | null }>(() => ({ request: null })); + +let seq = 0; + +export function chooseMembers( + view: EditorView, + { title, members }: { title: string; members: ChooserMember[] }, +): Promise { + useMemberChooser.getState().request?.resolve(null); + return new Promise((resolve) => { + useMemberChooser.setState({ request: { seq: ++seq, title, members, view, resolve } }); + }); +} diff --git a/src/editor/lsp/semantic/languages.ts b/src/editor/lsp/semantic/languages.ts index e0e5e9a6ab..bd53ab135a 100644 --- a/src/editor/lsp/semantic/languages.ts +++ b/src/editor/lsp/semantic/languages.ts @@ -67,6 +67,18 @@ export interface LanguageSemantics { asyncIntentions?(view: EditorView, signal: AbortSignal): Promise; /** Fallback for the Implement Methods action when the server offers no code action. */ implementMethods?(view: EditorView): Promise; + /** Fallback for the Override Methods action when the server offers no code action. */ + overrideMethods?(view: EditorView): Promise; + /** Generate (⌘N) entries when the server offers no code action. */ + generate?(view: EditorView): GenerateEntry[]; +} + +/** A row of the Generate popup contributed by a language. */ +export interface GenerateEntry { + id: string; + label: string; + icon: string; + run: () => unknown; } const registry: Record = {}; diff --git a/src/editor/lsp/semantic/python/imports.test.ts b/src/editor/lsp/semantic/python/imports.test.ts new file mode 100644 index 0000000000..dc0a455e14 --- /dev/null +++ b/src/editor/lsp/semantic/python/imports.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vitest"; +import { importLine, importedFrom, neededImports, placeImports, topLevelBindings } from "./imports"; + +const models = `from __future__ import annotations + +import os +from datetime import date +from enum import IntEnum +from .util import ( + slug, + clean as tidy, +) + +Alias = dict[str, int] + + +class Priority(IntEnum): + LOW = 1 + + +class TaskList: + def add(self, title: str, priority: Priority = Priority.NORMAL, due: date | None = None) -> Task: + pass +`.split("\n"); + +describe("override imports", () => { + it("reads the top-level bindings of a module", () => { + const b = topLevelBindings(models); + expect(b.get("date")).toEqual({ import: "from datetime import date" }); + expect(b.get("os")).toEqual({ import: "import os" }); + expect(b.get("tidy")).toEqual({ import: "from .util import clean as tidy" }); + expect(b.get("slug")).toEqual({ import: "from .util import slug" }); + expect(b.get("Priority")).toEqual({ defined: true }); + expect(b.get("Alias")).toEqual({ defined: true }); + expect(b.has("add")).toBe(false); + }); + + it("finds where a base class is imported from", () => { + const current = [ + "from tasks.models import TaskList", + "import abc", + "from tasks import models", + "import numpy as np", + ]; + expect(importedFrom(current, "TaskList")).toBe("tasks.models"); + expect(importedFrom(current, "abc.ABC")).toBe("abc"); + expect(importedFrom(current, "models.Base")).toBe("tasks.models"); + expect(importedFrom(current, "np.ndarray")).toBe("numpy"); + expect(importedFrom(current, "Local")).toBeNull(); + }); + + it("imports the names a copied signature needs, as the base module binds them", () => { + const sig = ["str", "Priority", "NORMAL", "date", "None", "Task"]; + const current = topLevelBindings(["from tasks.models import TaskList", "from datetime import date"]); + expect(neededImports(sig, current, topLevelBindings(models), "tasks.models")).toEqual([ + "from tasks.models import Priority", + ]); + expect(neededImports(["slug", "None"], current, topLevelBindings(models), "tasks.models")).toEqual([]); + expect(neededImports(["slug", "None"], current, topLevelBindings(models), "")).toEqual(["from .util import slug"]); + expect(neededImports(sig, new Map(), topLevelBindings(models), null)).toEqual(["from datetime import date"]); + }); + + it("puts new imports after the last import, else after the module docstring", () => { + expect(importLine(models)).toBe(9); + expect(importLine(["from x import a, \\", " b", "", "y = 1"])).toBe(2); + expect(topLevelBindings(["from x import a, \\", " b"]).get("b")).toEqual({ import: "from x import b" }); + expect(importLine(['"""Doc', 'string."""', "# note", "", "class A:", " pass"])).toBe(4); + expect(importLine(['"""Doc."""', "x = 1"])).toBe(1); + expect(importLine(["class A:", " pass"])).toBe(0); + }); + + it("adds names to an existing one-line import of the module, else one new line per module", () => { + const lines = ["from tasks.models import TaskList", "from x import (a,", " b)"]; + expect( + placeImports(lines, [ + "from tasks.models import Priority", + "from datetime import date", + "from tasks.models import Task", + "from x import c", + "import os", + "from datetime import time", + ]), + ).toEqual({ + appended: new Map([[0, ", Priority, Task"]]), + added: ["import os", "from datetime import date, time", "from x import c"], + }); + }); +}); diff --git a/src/editor/lsp/semantic/python/imports.ts b/src/editor/lsp/semantic/python/imports.ts new file mode 100644 index 0000000000..dadd1966a9 --- /dev/null +++ b/src/editor/lsp/semantic/python/imports.ts @@ -0,0 +1,134 @@ +/** + * The imports an override copied from a base class needs: names its signature uses that the + * current file does not bind, imported the way the base class's file binds them. + */ + +/** How a module binds a top-level name: an import statement (`from m import x`, `import m`) or its own definition. */ +export type Binding = { import: string } | { defined: true }; + +/** Top-level names `lines` bind (imports, classes, functions, assignments). */ +export function topLevelBindings(lines: readonly string[]): Map { + const out = new Map(); + for (let i = 0; i < lines.length; i++) { + let text = lines[i]!; + if (/^\s/.test(text)) continue; + // `from m import a, \` + `b`: one statement. + while (text.trimEnd().endsWith("\\") && i + 1 < lines.length) + text = text.trimEnd().slice(0, -1) + " " + lines[++i]!; + const from = /^from\s+(\S+)\s+import\s+(.*)$/.exec(text); + if (from) { + let names = from[2]!; + // `from m import (a,\n b)`. + if (names.includes("(")) while (!names.includes(")") && i + 1 < lines.length) names += " " + lines[++i]!; + for (const part of names.replace(/[()]/g, "").replace(/#.*/, "").split(",")) { + const m = /^\s*(\w+)(?:\s+as\s+(\w+))?\s*$/.exec(part); + if (m) out.set(m[2] ?? m[1]!, { import: `from ${from[1]} import ${m[1]}${m[2] ? ` as ${m[2]}` : ""}` }); + } + continue; + } + const imp = /^import\s+(.*)$/.exec(text); + if (imp) { + for (const part of imp[1]!.replace(/#.*/, "").split(",")) { + const m = /^\s*([\w.]+)(?:\s+as\s+(\w+))?\s*$/.exec(part); + if (m) out.set(m[2] ?? m[1]!.split(".")[0]!, { import: `import ${m[1]}${m[2] ? ` as ${m[2]}` : ""}` }); + } + continue; + } + text = text.replace(/^async\s+/, ""); + const def = /^(?:class|def|type)\s+(\w+)|^(\w+)\s*(?::[^=]*)?=(?!=)|^(\w+)\s*:/.exec(text); + const name = def && (def[1] ?? def[2] ?? def[3]); + if (name && !out.has(name)) out.set(name, { defined: true }); + } + return out; +} + +/** The module `name` (a base class as written, `Base` or `mod.Base`) is imported from in `lines`; null if it is not imported. */ +export function importedFrom(lines: readonly string[], name: string): string | null { + const head = name.split(".")[0]!; + const binding = topLevelBindings(lines).get(head); + if (!binding || !("import" in binding)) return null; + const from = /^from\s+(\S+)\s+import\s+(\w+)/.exec(binding.import); + if (from) + return name.includes(".") ? `${from[1]}.${from[2]}${name.slice(head.length, name.lastIndexOf("."))}` : from[1]!; + const imp = /^import\s+([\w.]+)/.exec(binding.import)!; + return name.includes(".") ? imp[1]! + name.slice(head.length, name.lastIndexOf(".")) : null; +} + +/** + * Import statements for `names` that `current` does not bind and the base file binds + * (`base`); `module` is where the base file's own definitions are imported from ("" for the + * current file, null when unknown). + */ +export function neededImports( + names: readonly string[], + current: ReadonlyMap, + base: ReadonlyMap, + module: string | null, +): string[] { + const out = new Set(); + for (const name of names) { + if (current.has(name)) continue; + const binding = base.get(name); + if (!binding) continue; + if ("import" in binding) { + // The base file's relative imports mean something else here. + if (module === "" || !/^from\s+\./.test(binding.import)) out.add(binding.import); + } else if (module) out.add(`from ${module} import ${name}`); + } + return [...out]; +} + +/** 0-based line before which new imports go: after the file's last top-level import, else before its first statement. */ +export function importLine(lines: readonly string[]): number { + let last = -1; + for (let i = 0; i < lines.length; i++) { + const text = lines[i]!; + if (/^(class|def|async\s+def|@)/.test(text)) break; + if (/^(import|from)\s/.test(text)) { + last = i; + if (text.includes("(") && !text.includes(")")) + while (last + 1 < lines.length && !lines[last]!.includes(")")) last++; + // `from m import a, \` + `b`: up to its last line. + while (lines[last]!.trimEnd().endsWith("\\") && last + 1 < lines.length) last++; + i = last; + } + } + if (last >= 0) return last + 1; + let i = 0; + // A module docstring and leading comments stay first. + if (/^[rRuUbB]?("""|''')/.test(lines[0] ?? "")) { + const quote = /("""|''')/.exec(lines[0]!)![1]!; + i = + lines[0]!.indexOf(quote, lines[0]!.indexOf(quote) + 3) >= 0 + ? 1 + : lines.findIndex((l, n) => n > 0 && l.includes(quote)) + 1; + } + while (i < lines.length && /^\s*(#.*)?$/.test(lines[i]!)) i++; + return i; +} + +/** + * Where `statements` go in `lines`: names imported `from` a module the file already imports from + * on one line are added to that line (0-based number, text appended); the rest are new lines, + * one per module, inserted at `importLine`. + */ +export function placeImports( + lines: readonly string[], + statements: readonly string[], +): { appended: Map; added: string[] } { + const appended = new Map(); + const grouped = new Map(); + const added: string[] = []; + for (const statement of statements) { + const from = /^from\s+(\S+)\s+import\s+(.+)$/.exec(statement); + if (!from) { + added.push(statement); + continue; + } + const existing = lines.findIndex((l) => l.startsWith(`from ${from[1]} import `) && !/[(#\\]/.test(l)); + if (existing >= 0) appended.set(existing, `${appended.get(existing) ?? ""}, ${from[2]}`); + else grouped.set(from[1]!, [...(grouped.get(from[1]!) ?? []), from[2]!]); + } + for (const [module, names] of grouped) added.push(`from ${module} import ${names.join(", ")}`); + return { appended, added }; +} diff --git a/src/editor/lsp/semantic/python/index.ts b/src/editor/lsp/semantic/python/index.ts index 8eef387724..c4afaf67f6 100644 --- a/src/editor/lsp/semantic/python/index.ts +++ b/src/editor/lsp/semantic/python/index.ts @@ -12,7 +12,12 @@ import { pythonSyntaxRanges, type PythonSymbolKind, } from "./highlight"; -import { implementPythonAbstractMethods, pythonMemberIntentions } from "./members"; +import { + implementPythonAbstractMethods, + overridePythonMethods, + pythonGenerateEntries, + pythonMemberIntentions, +} from "./members"; import { pythonCreateFixes } from "./createFromUsage"; import { pythonTypeHintIntentions } from "./typeHints"; import { pythonStringIntentions } from "./stringFormat"; @@ -62,6 +67,8 @@ const pythonSemantics: LanguageSemantics = { quickFixes: pythonCreateFixes, asyncIntentions: pythonTypeHintIntentions, implementMethods: implementPythonAbstractMethods, + overrideMethods: overridePythonMethods, + generate: pythonGenerateEntries, }; registerLanguageSemantics("python", pythonSemantics); diff --git a/src/editor/lsp/semantic/python/members.test.ts b/src/editor/lsp/semantic/python/members.test.ts index 7ddf3996e1..d10cc9d6ec 100644 --- a/src/editor/lsp/semantic/python/members.test.ts +++ b/src/editor/lsp/semantic/python/members.test.ts @@ -1,5 +1,20 @@ import { describe, expect, it } from "vitest"; -import { classMembers, enclosingClass, memberStubs } from "./members"; +import { indentUnit } from "@codemirror/language"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { + type PythonBase, + classBases, + classMembers, + enclosingClass, + forwardedArgs, + insertMembers, + linearize, + memberStubs, + overrideChoices, + overrideText, + signatureNames, +} from "./members"; const src = `from abc import ABC, abstractmethod @@ -70,3 +85,182 @@ describe("python members", () => { expect(memberStubs([name!], " ", " ")).toBe(" @property\n def name(self) -> str:\n pass"); }); }); + +describe("python overrides", () => { + it("passes the parameters on, keyword-only ones by keyword", () => { + expect(forwardedArgs("def f(self, a, b: int = 2, /, c=None, *, d, **kw) -> None:")).toBe("a, b, c, d=d, **kw"); + expect(forwardedArgs("def g(cls, *args: Any, key: str = 'x') -> int:")).toBe("*args, key=key"); + expect(forwardedArgs("def h(x: dict[str, int] = {}):")).toBe("x"); + }); + + it("calls the base through super(), without return for __init__ and None", () => { + const [area, describe_] = classMembers(src, 4).slice(1); + expect(overrideText(area!, "Shape", " ", " ")).toBe( + " def area(\n self, scale: float = 1.0\n ) -> float:\n return super().area(scale)", + ); + expect(overrideText(describe_!, "Shape", " ", " ")).toBe( + " def describe(self) -> str:\n return super().describe()", + ); + const init = classMembers(src, 19)[0]!; + expect(overrideText(init, "Square", "", " ")).toBe("def __init__(self, side: float):\n super().__init__(side)"); + const [prop, stat, coro] = classMembers( + [ + "class B:", + " @property", + " def name(self) -> str: ...", + " @staticmethod", + " def make(x) -> None: ...", + " async def fetch(self, url: str) -> bytes: ...", + " @overload", + " def get(self, k: int) -> int: ...", + ], + 1, + ); + expect(overrideText(prop!, "B", "", " ")).toBe("@property\ndef name(self) -> str:\n return super().name"); + expect(stat!.name).toBe("make"); + expect(overrideText(coro!, "B", "", " ")).toBe( + "async def fetch(self, url: str) -> bytes:\n return await super().fetch(url)", + ); + expect(classMembers(["class B:", " @overload", " def get(self) -> int: ..."], 1)[0]!.hidden).toBe(true); + }); + + it("finds a class without bases when asked", () => { + expect(enclosingClass(["class A:", " x = 1"], 2)).toBeNull(); + expect(enclosingClass(["class A:", " x = 1"], 2, true)).toBe(1); + }); +}); + +describe("python override review cases", () => { + it("splits parameters outside strings and lambdas", () => { + expect(forwardedArgs('def f(self, names="a, b", x=1):')).toBe("names, x"); + expect(forwardedArgs('def f(self, close=")", later=2):')).toBe("close, later"); + expect(forwardedArgs('def f(self, open="(", y=0):')).toBe("open, y"); + expect(forwardedArgs("def f(self, key=lambda a, b: a, *, z):")).toBe("key, z=z"); + }); + + it("cuts a one-line method at the colon closing its header", () => { + const [go, repr] = classMembers( + ["class B:", " def go(self, x): return x + 1", ' def __repr__(self) -> str: return f"B({1}:{2})"'], + 1, + ); + expect(go!.lines).toEqual(["def go(self, x):"]); + expect(repr!.lines).toEqual(["def __repr__(self) -> str:"]); + expect(overrideText(go!, "C", "", " ")).toBe("def go(self, x):\n return super().go(x)"); + }); + + it("reads non-ASCII class, method and base names", () => { + const src = ["class Größe(basis.Maß, Ünter):", " def größe(self, wert: int) -> int: ..."]; + expect(enclosingClass(src, 2)).toBe(1); + expect(classMembers(src, 1)[0]!.name).toBe("größe"); + expect(forwardedArgs("def größe(self, wert: int):")).toBe("wert"); + }); + + it("calls a static method's base through the overriding class", () => { + const [stat] = classMembers(["class B:", " @staticmethod", " def make(x) -> None: ..."], 1); + expect(overrideText(stat!, "Child", "", " ")).toBe( + "@staticmethod\ndef make(x) -> None:\n super(Child, Child).make(x)", + ); + }); + + it("lists the names an override's annotations, defaults and decorators use", () => { + const [add] = classMembers( + [ + "class B:", + " @functools.cache", + " def add(self, title: str, p: Priority = Priority.LOW, *, d: 'Date' = None) -> Task: ...", + ], + 1, + ); + expect(signatureNames(add!).sort()).toEqual([ + "Date", + "LOW", + "None", + "Priority", + "Task", + "cache", + "functools", + "str", + ]); + }); +}); + +describe("python overrides follow the MRO", () => { + const base = (name: string, src: string[]): PythonBase => ({ + name, + members: classMembers([`class ${name}:`, ...src], 1), + lines: [], + module: "", + }); + + it("linearizes bases as Python does (C3)", () => { + const parents: Record = { C: ["First", "Right"], First: ["Base"], Right: ["Base"], Base: [] }; + expect(linearize("C", (k) => parents[k] ?? [])).toEqual(["First", "Right", "Base"]); + // `class D(Base, First)` puts Base before its own subclass: Python rejects it. + expect(linearize("D", (k) => ({ ...parents, D: ["Base", "First"] })[k] ?? [])).toBeNull(); + }); + + it("copies the definition first in the MRO, the one super() calls", () => { + const first = base("First", [" def label(self, text: str) -> str: ..."]); + const right = base("Right", [" def label(self, text: str, width: int) -> str: ...", " def size(self): ..."]); + const choices = overrideChoices([first, right], []); + expect(choices.map((c) => [c.base.name, c.member.lines.join(" ")])).toEqual([ + ["First", "def label(self, text: str) -> str:"], + ["Right", "def size(self):"], + ]); + }); + + it("offers nothing for a name whose first definition is final or only overloads", () => { + const first = base("First", [ + " @final", + " def label(self): ...", + " @overload", + " def get(self) -> int: ...", + ]); + const right = base("Right", [" def label(self, x): ...", " def get(self): ..."]); + expect(overrideChoices([first, right], [])).toEqual([]); + const impl = base("Impl", [" @overload", " def get(self) -> int: ...", " def get(self, *a): ..."]); + expect(overrideChoices([impl], []).map((c) => c.member.lines.join(" "))).toEqual(["def get(self, *a):"]); + }); +}); + +describe("python class headers spanning lines", () => { + const src = ["class C(", " First, # the main one", " pkg.Right,", "):", " def own(self): ...", "", ""]; + + it("finds the class and its body below the header", () => { + expect(enclosingClass(src, 5)).toBe(1); + expect(enclosingClass(src, 6)).toBe(1); + expect(enclosingClass(src, 2)).toBe(1); + expect(classMembers(src, 1).map((m) => m.name)).toEqual(["own"]); + }); + + it("locates each base on its own line", () => { + expect(classBases(src, 1)).toEqual([ + { name: "First", line: 1, col: 4 }, + { name: "pkg.Right", line: 2, col: 8 }, + ]); + }); +}); + +describe("python members inserted into a one-line class", () => { + const insert = (doc: string) => { + const view = new EditorView({ state: EditorState.create({ doc, extensions: indentUnit.of(" ") }) }); + insertMembers(view, doc.split("\n"), 1, (indent, unit) => `${indent}def go(self):\n${indent}${unit}pass`); + return view.state.doc.toString(); + }; + + it("replaces a `pass` body on the header line", () => { + expect(insert("class Inline(Base): pass")).toBe("class Inline(Base):\n def go(self):\n pass"); + }); + + it("moves a statement off the header line", () => { + expect(insert("class Inline(Base): x = 1")).toBe( + "class Inline(Base):\n x = 1\n\n def go(self):\n pass", + ); + }); + + it("inserts below a header spanning lines", () => { + expect(insert("class C(\n Base,\n):\n pass")).toBe( + "class C(\n Base,\n):\n def go(self):\n pass", + ); + }); +}); diff --git a/src/editor/lsp/semantic/python/members.ts b/src/editor/lsp/semantic/python/members.ts index 5ac0afd33d..1faa49843c 100644 --- a/src/editor/lsp/semantic/python/members.ts +++ b/src/editor/lsp/semantic/python/members.ts @@ -1,46 +1,74 @@ /** - * Python "Implement abstract methods": Python servers (pyright, basedpyright) - * offer no such code action. The bases of the class at the caret are resolved - * with Go to Declaration; their `@abstractmethod`s the class lacks get stubs - * at the end of its body. + * Python "Implement abstract methods" and "Override Methods": Python servers + * (pyright, basedpyright) offer no such code actions. The bases of the class at + * the caret are resolved with Go to Declaration; implemented abstract methods get + * `pass` stubs, overrides call `super()`, at the end of the class body. */ import { indentUnit } from "@codemirror/language"; import type { EditorView } from "@codemirror/view"; import { commands } from "@/platform/ipc"; import type { ContributedIntention } from "@/editor/api"; +import type { GenerateEntry } from "../languages"; import { docOf, lspRequest, reportLspError } from "../../lsp"; -import { offsetToPos } from "../../positions"; -import { readFileLines } from "../../files"; +import { readFileLines, withDocument } from "../../files"; import { showHint } from "../../hint"; +import { chooseMembers } from "../../memberChooser"; +import { importLine, importedFrom, neededImports, placeImports, topLevelBindings } from "./imports"; -const CLASS_HEADER = /^(\s*)class\s+\w+\s*\((.*)\)\s*:/; +/** A Python identifier (letters of any script). */ +const ID = "[\\p{L}_][\\p{L}\\p{N}_]*"; +const CLASS_HEADER = new RegExp(`^(\\s*)class\\s+${ID}\\s*\\(([\\s\\S]*)\\)\\s*:$`, "u"); const CLASS = /^\s*class\s/; -const DEF = /^\s*(?:async\s+)?def\s+(\w+)/; +const CLASS_NAME = new RegExp(`class\\s+(${ID})`, "u"); +const DEF = new RegExp(`^\\s*(?:async\\s+)?def\\s+(${ID})`, "u"); +const BASE = new RegExp(`(?:^|,)\\s*(${ID}(?:\\.${ID})*)\\s*(?=,|$|\\[)`, "gu"); +const PARAM = new RegExp(`^(\\*{0,2})(${ID})`, "u"); const indentOf = (line: string) => line.length - line.trimStart().length; const isPython = (view: EditorView) => docOf(view)?.uiMode === "Python"; -/** 1-based number of the class header line enclosing `line` (or on it); null unless it has bases. */ -export function enclosingClass(lines: readonly string[], line: number): number | null { - let limit = Infinity; - for (let n = line; n >= 1; n--) { - const text = lines[n - 1]!; - if (!text.trim()) continue; - const indent = indentOf(text); - if (n !== line && indent >= limit) continue; - if (CLASS.test(text)) return CLASS_HEADER.test(text) ? n : null; - limit = Math.min(limit, indent); - if (indent === 0 && n !== line) return null; +/** + * 1-based number of the class header line enclosing `line` (or on it); null unless it has bases + * (or, with `any`, unless there is one). + */ +export function enclosingClass(lines: readonly string[], line: number, any = false): number | null { + // A blank line belongs to the block above it. + let at = line; + while (at > 1 && !lines[at - 1]!.trim()) at--; + // The nearest class above whose header or body holds the line (a header may span lines). + for (let n = at; n >= 1; n--) { + if (!CLASS.test(lines[n - 1]!) || bodyEnd(lines, n) < at) continue; + return any || CLASS_HEADER.test(classHeader(lines, n).text) ? n : null; } return null; } +/** How many lines a class header may span. */ +const MAX_HEADER_LINES = 30; + +/** + * The header of the class starting at line `header` (1-based), up to its closing `:`: its text + * (lines joined by `\n`), last line and the index of the `:` in that line (-1 when unclosed). + */ +export function classHeader(lines: readonly string[], header: number): { text: string; end: number; colon: number } { + const parts: string[] = []; + for (let n = header; n <= Math.min(lines.length, header + MAX_HEADER_LINES); n++) { + parts.push(lines[n - 1]!); + const joined = parts.join("\n"); + const colon = headerColon(joined, false); + if (colon >= 0) + return { text: joined.slice(0, colon + 1), end: n, colon: colon - (joined.length - lines[n - 1]!.length) }; + } + return { text: lines[header - 1]!, end: header, colon: -1 }; +} + /** Last 1-based line of the body of the class headed at `header`. */ function bodyEnd(lines: readonly string[], header: number): number { const indent = indentOf(lines[header - 1]!); - let last = header; + const start = classHeader(lines, header).end; + let last = start; let quote: string | null = null; - for (let n = header + 1; n <= lines.length; n++) { + for (let n = start + 1; n <= lines.length; n++) { const text = lines[n - 1]!; // Lines inside a triple-quoted string belong to it, however indented. const inString = quote !== null; @@ -64,6 +92,8 @@ export interface PythonMember { abstract: boolean; /** Decorators (without `@abstractmethod`) and the signature, dedented. */ lines: string[]; + /** Decorated `@overload` / `@final`: not something to override. */ + hidden?: boolean; } /** Methods declared directly in the class headed at `header` (1-based). */ @@ -72,7 +102,7 @@ export function classMembers(lines: readonly string[], header: number): PythonMe const out: PythonMember[] = []; let memberIndent = -1; let decorators: string[] = []; - for (let n = header + 1; n <= end; n++) { + for (let n = classHeader(lines, header).end + 1; n <= end; n++) { const text = lines[n - 1]!; if (!text.trim()) continue; const indent = indentOf(text); @@ -85,21 +115,27 @@ export function classMembers(lines: readonly string[], header: number): PythonMe } const def = DEF.exec(text); if (def) { - // The signature may span lines: up to the `:` closing it. + // The signature may span lines: up to the `:` closing it; a body on the same line + // (`def f(self) -> int: ...`, `def go(self): return 1`) is left out. const sig: string[] = []; - let depth = 0; for (let m = n; m <= end; m++) { const part = lines[m - 1]!; sig.push(part.slice(Math.min(memberIndent, indentOf(part)))); - for (const ch of part) depth += ch === "(" || ch === "[" ? 1 : ch === ")" || ch === "]" ? -1 : 0; - if (depth <= 0 && /:\s*(#.*)?$|:\s*\.\.\.\s*$|:\s*\S/.test(part)) break; + const joined = sig.join("\n"); + const colon = headerColon(joined); + if (colon >= 0) { + sig[sig.length - 1] = sig[sig.length - 1]!.slice( + 0, + colon + 1 - (joined.length - sig[sig.length - 1]!.length), + ); + break; + } } - // `def f(self) -> int: ...` keeps only the signature. - sig[sig.length - 1] = sig[sig.length - 1]!.replace(/:\s*(\.\.\.|pass)?\s*(#.*)?$/, ":"); const abstract = decorators.some((d) => /^@(abc\.)?abstract(method|property)\b/.test(d)); out.push({ name: def[1]!, abstract, + hidden: decorators.some((d) => /^@(typing\.|typing_extensions\.)?(overload|final)\b/.test(d)), lines: [ ...decorators .filter((d) => !/^@(abc\.)?abstractmethod\b/.test(d)) @@ -113,18 +149,25 @@ export function classMembers(lines: readonly string[], header: number): PythonMe return out; } -/** Base class names of a header and where each starts in the line. */ -function bases(header: string): Array<{ name: string; col: number }> { - const m = CLASS_HEADER.exec(header); +/** Base class names of the class headed at `header` (1-based) and where each starts (0-based line, column). */ +export function classBases( + lines: readonly string[], + header: number, +): Array<{ name: string; line: number; col: number }> { + // Comments blanked to spaces, keeping columns. + const text = classHeader(lines, header).text.replace(/#[^\n]*/g, (c) => " ".repeat(c.length)); + const m = CLASS_HEADER.exec(text); if (!m) return []; - const start = header.indexOf("(") + 1; - const out: Array<{ name: string; col: number }> = []; - for (const b of m[2]!.matchAll(/(?:^|,)\s*([A-Za-z_][\w.]*)\s*(?=,|$|\[)/g)) { + const start = text.indexOf("(") + 1; + const out: Array<{ name: string; line: number; col: number }> = []; + for (const b of m[2]!.matchAll(BASE)) { const name = b[1]!; if (name === "object" || name.includes("=")) continue; // The last segment of `abc.ABC`: that's what Go to Declaration resolves. - const col = start + b.index! + b[0].indexOf(name) + name.lastIndexOf(".") + 1; - out.push({ name, col }); + const at = start + b.index! + b[0].indexOf(name) + name.lastIndexOf(".") + 1; + const before = text.slice(0, at); + const row = before.split("\n").length - 1; + out.push({ name, line: header - 1 + row, col: at - (before.lastIndexOf("\n") + 1) }); } return out; } @@ -136,11 +179,9 @@ export function memberStubs(members: readonly PythonMember[], indent: string, un async function abstractMembersOfBases(view: EditorView, header: number): Promise { const doc = docOf(view)!; - const state = view.state; - const line = state.doc.line(header); const out = new Map(); - for (const base of bases(line.text)) { - const pos = offsetToPos(state.doc, line.from + base.col); + for (const base of classBases(view.state.doc.toJSON(), header)) { + const pos = { line: base.line, col: base.col }; const [loc] = await lspRequest(() => commands.lspGoto(doc.doc, pos, "definition")); if (!loc) continue; const lines = await readFileLines(loc.path); @@ -173,31 +214,385 @@ export async function implementPythonAbstractMethods(view: EditorView): Promise< showHint(view, "No abstract methods to implement"); return true; } + insertMembers(view, lines, header, (indent, unit) => memberStubs(missing, indent, unit)); + return true; +} + +/** Inserts `text(indent, unit)` at the end of the body of the class headed at `header` (1-based). */ +export function insertMembers( + view: EditorView, + lines: readonly string[], + header: number, + text: (indent: string, unit: string) => string, + imports: readonly string[] = [], +) { + const state = view.state; const end = bodyEnd(lines, header); const unit = state.facet(indentUnit) || " "; + const head = classHeader(lines, header); const bodyLines = []; - for (let n = header + 1; n <= end; n++) if (lines[n - 1]!.trim()) bodyLines.push(n); + for (let n = head.end + 1; n <= end; n++) if (lines[n - 1]!.trim()) bodyLines.push(n); const first = bodyLines[0] ? lines[bodyLines[0] - 1]! : null; const indent = first ? first.slice(0, indentOf(first)) : lines[header - 1]!.slice(0, indentOf(lines[header - 1]!)) + unit; - const stubs = memberStubs(missing, indent, unit); + const stubs = text(indent, unit); + // A body on the header line (`class C: pass`) moves to a line of its own, unless only `pass` / `...`. + const headerEnd = state.doc.line(head.end); + const inline = head.colon < 0 ? "" : headerEnd.text.slice(head.colon + 1).trim(); + const inlineBody = inline && !inline.startsWith("#") && !/^(pass|\.\.\.)\s*(#.*)?$/.test(inline) ? inline : ""; // A body that is only `pass` / `...` is replaced. const placeholder = bodyLines.length === 1 && /^\s*(pass|\.\.\.)\s*$/.test(first!); const changes = !bodyLines.length - ? { from: state.doc.line(header).to, insert: `\n${stubs}` } + ? inline && !inline.startsWith("#") + ? { + from: headerEnd.from + head.colon + 1, + to: headerEnd.to, + insert: `\n${inlineBody ? `${indent}${inlineBody}\n\n` : ""}${stubs}`, + } + : { from: headerEnd.to, insert: `\n${stubs}` } : placeholder ? { from: state.doc.line(bodyLines[0]!).from, to: state.doc.line(end).to, insert: stubs } : { from: state.doc.line(end).to, insert: `\n\n${stubs}` }; - view.dispatch({ changes, userEvent: "input.complete", scrollIntoView: true }); + const { appended, added } = placeImports(lines, imports); + const importChanges = [...appended].map(([n, text]) => ({ from: state.doc.line(n + 1).to, insert: text })); + if (added.length) { + const before = importLine(lines); + importChanges.push( + before < state.doc.lines + ? { from: state.doc.line(before + 1).from, insert: `${added.join("\n")}\n` } + : { from: state.doc.length, insert: `\n${added.join("\n")}` }, + ); + } + view.dispatch({ changes: [...importChanges, changes], userEvent: "input.complete", scrollIntoView: true }); +} + +/** A base class of the class at the caret and the methods it declares. */ +export interface PythonBase { + name: string; + members: PythonMember[]; + /** Lines of the file declaring it. */ + lines: readonly string[]; + /** Where its file's own definitions are imported from; "" for the current file, null when unknown. */ + module: string | null; +} + +/** How many ancestor classes are looked at (typeshed hierarchies run deep). */ +const MAX_ANCESTORS = 30; + +/** + * The C3 linearization (Python's MRO) of `root` given each class's direct bases, without `root`; + * null when the bases admit none (Python rejects such a class) or loop. + */ +export function linearize(root: string, parents: (key: string) => readonly string[]): string[] | null { + const memo = new Map(); + const visiting = new Set(); + const visit = (key: string): string[] | null => { + if (memo.has(key)) return memo.get(key)!; + if (visiting.has(key)) return null; + visiting.add(key); + const direct = parents(key); + const seqs: string[][] = []; + for (const p of direct) { + const mro = visit(p); + if (!mro) return null; + seqs.push([...mro]); + } + seqs.push([...direct]); + visiting.delete(key); + const out = [key]; + for (;;) { + const live = seqs.filter((s) => s.length); + if (!live.length) break; + // The first head that is in no other sequence's tail. + const head = live.map((s) => s[0]!).find((h) => !live.some((s) => s.indexOf(h, 1) > 0)); + if (head === undefined) { + memo.set(key, null); + return null; + } + out.push(head); + for (const s of live) if (s[0] === head) s.shift(); + } + memo.set(key, out); + return out; + }; + return visit(root)?.slice(1) ?? null; +} + +/** + * Ancestors of the class headed at `header`, in its MRO (breadth-first when it has none), via Go to + * Declaration. + */ +async function ancestors(view: EditorView, header: number): Promise { + const doc = docOf(view)!; + const root = ""; + const queue: Array<{ + key: string; + path: string | null; + lines: readonly string[]; + header: number; + module: string | null; + }> = [{ key: root, path: null, lines: view.state.doc.toJSON(), header, module: "" }]; + const found = new Map(); + const parents = new Map(); + while (queue.length && found.size < MAX_ANCESTORS) { + const cls = queue.shift()!; + const direct: string[] = []; + parents.set(cls.key, direct); + for (const base of classBases(cls.lines, cls.header)) { + const pos = { line: base.line, col: base.col }; + const goto = (id: number) => lspRequest(() => commands.lspGoto(id, pos, "definition")); + const [loc] = cls.path ? await withDocument(cls.path, goto) : await goto(doc.doc); + if (!loc) continue; + const key = `${loc.path}:${loc.range.start.line}`; + if (found.has(key)) { + direct.push(key); + continue; + } + const lines = await readFileLines(loc.path); + const target = lines && enclosingClass(lines, loc.range.start.line + 1, true); + if (!lines || !target) continue; + const name = CLASS_NAME.exec(lines[target - 1]!)?.[1]; + if (!name || name === "object") continue; + // Imported in the file naming it, else declared in that file (and imported from where it is). + const from = importedFrom(cls.lines, base.name); + const module = from === null ? cls.module : cls.path && from.startsWith(".") ? null : from; + found.set(key, { name, members: classMembers(lines, target), lines, module }); + direct.push(key); + queue.push({ key, path: loc.path, lines, header: target, module }); + } + } + const mro = linearize(root, (key) => parents.get(key) ?? []); + return (mro ?? [...found.keys()]).map((key) => found.get(key)!).filter(Boolean); +} + +/** Index of the quote closing the string literal that opens at `i` of `text`, or `text.length`. */ +function skipString(text: string, i: number): number { + const quote = text[i]!; + for (let j = i + 1; j < text.length; j++) { + if (text[j] === "\\") j++; + else if (text[j] === quote) return j; + } + return text.length; +} + +/** + * Index of the `:` that closes a `def` header in `text` (outside brackets, strings and comments), or -1; + * with `bracketed` false, of a `class` header, which needs no brackets. + */ +export function headerColon(text: string, bracketed = true): number { + let depth = 0; + let opened = false; + for (let i = 0; i < text.length; i++) { + const c = text[i]!; + if (c === '"' || c === "'") i = skipString(text, i); + else if (c === "#") { + const nl = text.indexOf("\n", i); + if (nl < 0) return -1; + i = nl; + } else if ("([{".includes(c)) { + depth++; + opened = true; + } else if (")]}".includes(c)) depth--; + else if (c === ":" && depth === 0 && (opened || !bracketed)) return i; + } + return -1; +} + +/** + * The parameters of `signature` (a `def`, possibly joined from several lines), trimmed; null when + * unclosed. Commas in strings, brackets and between a `lambda` and its `:` do not split. + */ +export function signatureParams(signature: string): string[] | null { + const open = signature.indexOf("("); + if (open < 0) return null; + const params: string[] = []; + let depth = 0; + let start = open + 1; + let lambda = false; + for (let i = open; i < signature.length; i++) { + const c = signature[i]!; + if (c === '"' || c === "'") i = skipString(signature, i); + else if ("([{".includes(c)) depth++; + else if (")]}".includes(c) && --depth === 0) { + params.push(signature.slice(start, i)); + return params.map((p) => p.trim()).filter(Boolean); + } else if (depth === 1 && /^lambda\b/.test(signature.slice(i, i + 7)) && !/[\p{L}\p{N}_]/u.test(signature[i - 1]!)) + lambda = true; + else if (c === ":" && depth === 1 && lambda) lambda = false; + else if (c === "," && depth === 1 && !lambda) { + params.push(signature.slice(start, i)); + start = i + 1; + } + } + return null; +} + +/** + * The names an override copied from `member` uses besides its own and its parameters': in its + * decorators, annotations, defaults and return annotation (string annotations included). + */ +export function signatureNames(member: PythonMember): string[] { + const decorators = member.lines.filter((l) => l.startsWith("@")); + const joined = member.lines.filter((l) => !l.startsWith("@")).join(" "); + const parts = [...decorators.map((d) => d.slice(1))]; + for (const p of signatureParams(joined) ?? []) parts.push(p.replace(PARAM, "")); + const close = joined.lastIndexOf(")", headerColon(joined)); + parts.push(joined.slice(close + 1)); + return [...new Set(parts.join(" ").match(new RegExp(ID, "gu")) ?? [])]; +} + +/** + * The argument list passing the parameters of `signature` on, as the `super()` call of an + * override: keyword-only parameters by keyword, `self` / `cls` dropped. + */ +export function forwardedArgs(signature: string): string | null { + const params = signatureParams(signature); + if (!params) return null; + let keyword = false; + const args: string[] = []; + for (const [i, raw] of params.entries()) { + if (raw === "/") continue; + if (raw === "*") { + keyword = true; + continue; + } + const m = PARAM.exec(raw); + if (!m) continue; + if (i === 0 && !m[1] && (m[2] === "self" || m[2] === "cls")) continue; + if (m[1] === "*") keyword = true; + args.push(m[1] ? m[1] + m[2] : keyword ? `${m[2]}=${m[2]}` : m[2]!); + } + return args.join(", "); +} + +/** + * An override of `member` in the class named `owner`: its decorators and signature, and a body + * calling the base; null when the signature cannot be read. + */ +export function overrideText(member: PythonMember, owner: string, indent: string, unit: string): string | null { + const decorators = member.lines.filter((l) => l.startsWith("@")); + const signature = member.lines.filter((l) => !l.startsWith("@")); + const joined = signature.join(" "); + const isStatic = decorators.some((d) => /^@(builtins\.)?staticmethod\b/.test(d)); + const isProperty = decorators.some((d) => /^@((builtins|functools)\.)?(property|cached_property)\b/.test(d)); + // ponytail: a static method has no `self` for `super()`; a nested class needs `Outer.Owner` here. + const target = isStatic ? `super(${owner}, ${owner})` : "super()"; + const args = forwardedArgs(joined); + if (!isProperty && args === null) return null; + const call = isProperty ? `${target}.${member.name}` : `${target}.${member.name}(${args})`; + const awaited = /^\s*async\s/.test(joined) ? `await ${call}` : call; + const returns = member.name !== "__init__" && !/->\s*None\s*:\s*$/.test(joined); + return [...member.lines.map((l) => indent + l), `${indent}${unit}${returns ? "return " : ""}${awaited}`].join("\n"); +} + +/** + * The methods `bases` (in MRO order) offer to override in a class declaring `own`: of each name, the + * definition first in the MRO, which `super()` calls; none when that one is `@final`, only + * `@overload`s, name-mangled or unreadable. + */ +export function overrideChoices( + bases: readonly PythonBase[], + own: readonly PythonMember[], +): Array<{ base: PythonBase; member: PythonMember }> { + const taken = new Set(own.map((m) => m.name)); + const choices: Array<{ base: PythonBase; member: PythonMember }> = []; + for (const base of bases) { + const here = new Set(); + for (const member of base.members) { + if (taken.has(member.name)) continue; + here.add(member.name); + // `__x` is name-mangled: a subclass cannot override it. + if (member.hidden || /^__[\p{L}\p{N}_]*[^_]_?$/u.test(member.name)) continue; + if (overrideText(member, "C", "", "") === null) continue; + taken.add(member.name); + choices.push({ base, member }); + } + for (const name of here) taken.add(name); + } + return choices; +} + +/** ⌃O: the base classes' methods the class does not define, chosen in a dialog, as overrides calling `super()`. */ +export async function overridePythonMethods(view: EditorView): Promise { + if (!isPython(view)) return false; + const lines = view.state.doc.toJSON(); + const header = enclosingClass(lines, view.state.doc.lineAt(view.state.selection.main.head).number, true); + if (!header) return false; + let found: PythonBase[]; + try { + found = await ancestors(view, header); + } catch (e) { + reportLspError(view, e, true); + return true; + } + const choices = overrideChoices(found, classMembers(lines, header)); + if (!choices.length) { + showHint(view, "No methods to override"); + return true; + } + const ids = await chooseMembers(view, { + title: "Select Methods to Override", + members: choices.map(({ base, member }, i) => { + const sig = member.lines.filter((l) => !l.startsWith("@")).join(" "); + return { + id: String(i), + label: member.name, + detail: sig.slice(sig.indexOf("(")).replace(/:\s*$/, ""), + icon: member.abstract ? "gutter-implemented" : "gutter-overridden", + group: base.name, + }; + }), + }); + if (!ids?.length) return true; + if (view.state.doc.toJSON().join("\n") !== lines.join("\n")) return true; + const chosen = ids.map((id) => choices[Number(id)]!); + const current = topLevelBindings(lines); + const imports = new Set(); + for (const { base, member } of chosen) + for (const i of neededImports(signatureNames(member), current, topLevelBindings(base.lines), base.module)) + imports.add(i); + const owner = CLASS_NAME.exec(lines[header - 1]!)![1]!; + insertMembers( + view, + lines, + header, + (indent, unit) => chosen.map(({ member }) => overrideText(member, owner, indent, unit)!).join("\n\n"), + [...imports], + ); return true; } +/** Generate (⌘N) in a Python class: Override / Implement Methods. */ +export function pythonGenerateEntries(view: EditorView): GenerateEntry[] { + if (!isPython(view)) return []; + const lines = view.state.doc.toJSON(); + const line = view.state.doc.lineAt(view.state.selection.main.head).number; + if (!enclosingClass(lines, line, true)) return []; + const entries: GenerateEntry[] = [ + { + id: "python.overrideMethods", + label: "Override Methods…", + icon: "gutter-overridden", + run: () => overridePythonMethods(view), + }, + ]; + // Abstract methods come from bases: a class without any has nothing to implement. + if (enclosingClass(lines, line)) + entries.push({ + id: "python.implementMethods", + label: "Implement Methods…", + icon: "gutter-implemented", + run: () => implementPythonAbstractMethods(view), + }); + return entries; +} + /** The bulb on a Python class header with bases. */ export function pythonMemberIntentions(view: EditorView): ContributedIntention[] { if (!isPython(view)) return []; const line = view.state.doc.lineAt(view.state.selection.main.head); - if (!bases(line.text).length) return []; + if (!CLASS.test(line.text) || !classBases(view.state.doc.toJSON(), line.number).length) return []; return [ { id: "python.implementAbstract", diff --git a/src/platform/keymaps/newElement.test.ts b/src/platform/keymaps/newElement.test.ts index cdc37a50fb..b641f57313 100644 --- a/src/platform/keymaps/newElement.test.ts +++ b/src/platform/keymaps/newElement.test.ts @@ -21,7 +21,8 @@ describe("New keymap", () => { const generate = compileWhen(GENERATE_KEY_WHEN); expect(generate({ editorLangId: "java" })).toBe(true); expect(generate({ editorLangId: "rust" })).toBe(true); - expect(generate({ editorLangId: "python" })).toBe(false); + expect(generate({ editorLangId: "python" })).toBe(true); + expect(generate({ editorLangId: "ruby" })).toBe(false); expect(generate({ editorLangId: "markdown" })).toBe(false); expect(generate({})).toBe(false); }); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index c07b85b8c4..82a98c4810 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -10,6 +10,8 @@ "Select a configured custom dictionary": "Select a configured custom dictionary", "'{word}' is not a word a dictionary can list": "'{word}' is not a word a dictionary can list", "{path} is not a writable dictionary file": "{path} is not a writable dictionary file", + "Select Methods to Override": "Select Methods to Override", + "No methods to override": "No methods to override", "Task Actions": "Task Actions", "Search commits": "Search commits", "Amend commit failed": "Amend commit failed", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 1e40792cac..4dc9d080d5 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2,6 +2,8 @@ "Create function '{name}'": "创建函数 '{name}'", "Create class '{name}'": "创建类 '{name}'", "Create method '{name}' in '{owner}'": "在 '{owner}' 中创建方法 '{name}'", + "Select Methods to Override": "选择要重写的方法", + "No methods to override": "没有可重写的方法", "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": "仍然创建修订提交",