diff --git a/crates/ide-language/src/lib.rs b/crates/ide-language/src/lib.rs index 1d41b6a6f0..cff6bce301 100644 --- a/crates/ide-language/src/lib.rs +++ b/crates/ide-language/src/lib.rs @@ -28,7 +28,7 @@ pub use syntax::{ VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility, set_external_syntax, shift_pos, shift_range, }; -pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts}; +pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression}; /// Parsed form of `languages/.toml`. Backend-only; the UI gets [`LanguageInfo`]. #[derive(Clone, Debug, Serialize, Deserialize)] diff --git a/crates/ide-language/src/syntax/mod.rs b/crates/ide-language/src/syntax/mod.rs index 79716e20f3..b79b253bf6 100644 --- a/crates/ide-language/src/syntax/mod.rs +++ b/crates/ide-language/src/syntax/mod.rs @@ -32,7 +32,7 @@ pub use lines::{shift_pos, shift_range}; pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion}; pub use outline::{merge_kinds, merge_visibility}; pub use php_align::PhpAlignment; -pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts}; +pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression}; use std::cell::RefCell; use std::collections::HashMap; use std::sync::OnceLock; diff --git a/crates/ide-language/src/syntax/python_facts.rs b/crates/ide-language/src/syntax/python_facts.rs index 0b195c0a64..8ba56fb109 100644 --- a/crates/ide-language/src/syntax/python_facts.rs +++ b/crates/ide-language/src/syntax/python_facts.rs @@ -15,6 +15,18 @@ use tree_sitter::{Node, Tree}; #[serde(rename_all = "camelCase")] pub struct PythonFacts { pub classes: Vec, + /// `# noinspection` comments, in source order. + pub suppressions: Vec, +} + +/// A `# noinspection Id1,Id2` comment (PyCharm's) and the code it covers: the statement +/// right below it (a whole `def` / `class` with its decorators), or the whole file when it +/// sits among the file's leading comments, followed by a blank line. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PythonSuppression { + pub ids: Vec, + pub range: crate::Range, } /// A class definition and the methods it declares. @@ -24,6 +36,8 @@ pub struct PythonClassFacts { pub name: String, /// The class name identifier (selection range). pub selection: crate::Range, + /// First line of the definition, its decorators included. + pub definition_line: u32, /// Base names as written, a qualified name reduced to its last segment. pub bases: Vec, pub methods: Vec, @@ -36,6 +50,8 @@ pub struct PythonMethodFacts { pub name: String, /// The method name identifier (selection range). pub selection: crate::Range, + /// First line of the definition, its decorators included. + pub definition_line: u32, /// Parameter names in order; `None` for a form whose forwarding cannot be compared /// (`*args`, `**kwargs`, keyword-only, positional-only). pub params: Option>, @@ -84,11 +100,91 @@ fn extract(tree: &Tree, text: &str) -> PythonFacts { classes.push(PythonClassFacts { name, selection: idx.range(name_node.start_byte(), name_node.end_byte()), + definition_line: definition_line(node), bases: super::inheritance::class_base_names(node, text), methods: methods_of(node, text, &idx, &imports), }); }); - PythonFacts { classes } + PythonFacts { classes, suppressions: suppressions(tree, text, &idx) } +} + +/// The row a definition starts on: its first decorator's when it has one. +fn definition_line(definition: Node) -> u32 { + let start = definition.parent().filter(|p| p.kind() == "decorated_definition").unwrap_or(definition); + start.start_position().row as u32 +} + +/// The ids of a `# noinspection` comment, or `None` for any other comment. +fn noinspection_ids(comment: &str) -> Option> { + let rest = comment.strip_prefix('#')?.trim_start().strip_prefix("noinspection")?; + if !rest.starts_with(char::is_whitespace) { + return None; + } + let ids: Vec = rest.split(',').map(str::trim).filter(|id| !id.is_empty()).map(str::to_owned).collect(); + (!ids.is_empty()).then_some(ids) +} + +fn suppressions(tree: &Tree, text: &str, idx: &LineIndex) -> Vec { + let root = tree.root_node(); + let lines: Vec<&str> = text.split('\n').collect(); + let starts: Vec = + lines.iter().scan(0, |at, line| Some(std::mem::replace(at, *at + line.len() + 1))).collect(); + let is_comment = |row: usize| lines[row].trim_start().starts_with('#'); + let first_statement = { + let mut cursor = root.walk(); + let first = root.named_children(&mut cursor).find(|n| n.kind() != "comment"); + first.map(|n| n.start_position().row) + }; + let mut out = Vec::new(); + let mut cursor = tree.walk(); + visit(&mut cursor, &mut |node| { + if node.kind() != "comment" { + return; + } + let row = node.start_position().row; + // Only a comment on a line of its own: a trailing one belongs to its code. + if !lines[row][..node.start_position().column].trim().is_empty() { + return; + } + let Some(ids) = noinspection_ids(&text[node.byte_range()]) else { return }; + // Several comments may stack up above one statement. + let mut next = row + 1; + while next < lines.len() && is_comment(next) { + next += 1; + } + let blank_after = next >= lines.len() || lines[next].trim().is_empty(); + let range = if blank_after && first_statement.is_none_or(|first| row < first) { + idx.range(0, text.len()) + } else if blank_after { + return; + } else { + let indent = indent_len(lines[next]); + if indent != node.start_position().column { + return; + } + let Some(statement) = statement_at(root, starts[next] + indent) else { return }; + idx.range(statement.start_byte(), statement.end_byte()) + }; + out.push(PythonSuppression { ids, range }); + }); + out +} + +fn indent_len(line: &str) -> usize { + line.len() - line.trim_start().len() +} + +/// The outermost node starting at `byte` below the enclosing block: the whole statement +/// (a decorated definition included) that begins there. +fn statement_at(root: Node, byte: usize) -> Option { + let mut node = root.descendant_for_byte_range(byte, byte)?; + while let Some(parent) = node.parent() { + if parent.start_byte() != byte || matches!(parent.kind(), "module" | "block") { + break; + } + node = parent; + } + (node.start_byte() == byte && node.parent().is_some_and(|p| matches!(p.kind(), "module" | "block"))).then_some(node) } /// The methods declared directly in `class`. @@ -115,6 +211,7 @@ fn methods_of(class: Node, text: &str, idx: &LineIndex, imports: &ImportBindings 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)), @@ -435,4 +532,50 @@ mod tests { let other = SYNTAX.get_or_init(Syntax::new).python_facts(&LanguageId::new("rust"), "class C {}"); assert_eq!(other.classes.len(), 0); } + + fn covered(f: &PythonFacts) -> Vec<(Vec<&str>, u32, u32)> { + f.suppressions + .iter() + .map(|s| (s.ids.iter().map(String::as_str).collect(), s.range.start.line, s.range.end.line)) + .collect() + } + + #[test] + fn noinspection_covers_the_statement_below() { + let f = facts( + "class C:\n # noinspection PyAbstractClass, PyOverrideDecorator\n # another comment\n @dec\n def m(self):\n pass\n\n def n(self): # noinspection PyAbstractClass\n x = 1\n # noinspection ALL\n y = (1,\n 2)\n", + ); + assert_eq!(covered(&f), [(vec!["PyAbstractClass", "PyOverrideDecorator"], 3, 5), (vec!["ALL"], 10, 11)]); + assert_eq!(method(&f, "C", "m").definition_line, 3); + assert_eq!(method(&f, "C", "n").definition_line, 7); + assert_eq!(f.classes[0].definition_line, 0); + } + + #[test] + fn noinspection_in_the_file_header_covers_the_file() { + let f = facts("#!/usr/bin/env python\n# noinspection PyAbstractClass\n\nclass C:\n pass\n"); + assert_eq!(covered(&f), [(vec!["PyAbstractClass"], 0, 5)]); + // Right above the first statement it is that statement's. + let f = facts("# noinspection PyAbstractClass\nclass C:\n pass\n\nclass D:\n pass\n"); + assert_eq!(covered(&f), [(vec!["PyAbstractClass"], 1, 2)]); + // Followed by a blank line further down, it covers nothing. + let f = facts("x = 1\n# noinspection PyAbstractClass\n\nclass C:\n pass\n"); + assert!(covered(&f).is_empty()); + let f = facts("# noinspection\nclass C:\n pass\n# noinspectionX A\nclass D:\n pass\n"); + assert!(covered(&f).is_empty()); + } + + #[test] + fn noinspection_does_not_cross_a_block_boundary() { + let f = facts("def wrapper():\n pass\n # noinspection ALL\nclass Other:\n pass\n"); + assert!(covered(&f).is_empty()); + let f = facts("values = [\n # noinspection ALL\n 1,\n]\n"); + assert!(covered(&f).is_empty()); + } + + #[test] + fn decorated_classes_start_at_their_decorator() { + let f = facts("@dataclass\nclass C:\n x: int\n"); + assert_eq!(f.classes[0].definition_line, 0); + } } diff --git a/src/bindings.ts b/src/bindings.ts index d528599498..b088148737 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -11375,6 +11375,8 @@ export type PythonClassFacts = { name: string, /** The class name identifier (selection range). */ selection: Range, + /** First line of the definition, its decorators included. */ + definitionLine: number, /** Base names as written, a qualified name reduced to its last segment. */ bases: string[], methods: PythonMethodFacts[], @@ -11389,6 +11391,8 @@ export type PythonDebuggerSettings = { /** One Python module's classes, in source order. */ export type PythonFacts = { classes: PythonClassFacts[], + /** `# noinspection` comments, in source order. */ + suppressions: PythonSuppression[], }; /** A method definition the inspections can reason about. */ @@ -11396,6 +11400,8 @@ export type PythonMethodFacts = { name: string, /** The method name identifier (selection range). */ selection: Range, + /** First line of the definition, its decorators included. */ + definitionLine: number, /** * Parameter names in order; `None` for a form whose forwarding cannot be compared * (`*args`, `**kwargs`, keyword-only, positional-only). @@ -11458,6 +11464,16 @@ export type PythonStubLinks = { candidates: IpcPath[], }; +/** + * A `# noinspection Id1,Id2` comment (PyCharm's) and the code it covers: the statement + * right below it (a whole `def` / `class` with its decorators), or the whole file when it + * sits among the file's leading comments, followed by a blank line. + */ +export type PythonSuppression = { + ids: string[], + range: Range, +}; + /** Color Scheme › Language Defaults › Rainbow brackets: which delimiters are coloured. */ export type RainbowBracketKinds = { round?: boolean, diff --git a/src/editor/api.ts b/src/editor/api.ts index 70141373b2..233272d9a8 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -559,6 +559,13 @@ export function contributedQuickFixes(view: EditorView, from: number, to: number return view.state.facet(quickFixProviders).flatMap((provider) => provider(view, from, to)); } +/** + * Extra rows for the ⌥↵ submenu of inspection `inspectionId` at the caret (after Edit + * inspection profile setting and Disable inspection), such as Suppress for statement. + */ +export const inspectionControlProviders = + Facet.define<(view: EditorView, inspectionId: string) => readonly ContributedIntention[]>(); + /** Providers of `ContributedIntention`s for the caret of `view` (cheap and synchronous: also drives the light bulb). */ export const intentionProviders = Facet.define<(view: EditorView) => ContributedIntention[]>(); diff --git a/src/editor/lsp/intentions.test.ts b/src/editor/lsp/intentions.test.ts index dd48782799..5dc313a364 100644 --- a/src/editor/lsp/intentions.test.ts +++ b/src/editor/lsp/intentions.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { EditorState } from "@codemirror/state"; +import { EditorState, type Extension } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { setDiagnostics } from "@codemirror/lint"; import type { CodeAction, Diagnostic } from "@/bindings"; @@ -54,7 +54,7 @@ const { withInspectionControls, } = await import("./intentions"); const { useLspPopup, closePopup } = await import("./popupStore"); -const { asyncIntentionProviders } = await import("@/editor/api"); +const { asyncIntentionProviders, inspectionControlProviders } = await import("@/editor/api"); const { setFileDiagnostics, toLintDiagnostics } = await import("./diagnostics"); const { lspDoc } = await import("./lsp"); @@ -249,12 +249,12 @@ describe("context actions a feature finds through the language server", () => { }); describe("inspection controls in ⌥↵ (issue #42)", () => { - const editorAt = (path: string) => { + const editorAt = (path: string, extra: Extension = []) => { const view = new EditorView({ state: EditorState.create({ doc: "import os\n", selection: { anchor: 8 }, - extensions: [lspDoc.of({ doc: 1, path, language: "python", uiMode: null, readOnly: false })], + extensions: [lspDoc.of({ doc: 1, path, language: "python", uiMode: null, readOnly: false }), extra], }), }); views.push(view); @@ -293,6 +293,24 @@ describe("inspection controls in ⌥↵ (issue #42)", () => { expect(withInspectionControls(view, [])).toEqual([]); }); + it("adds the rows features contribute for the inspection", () => { + setFileDiagnostics("/p/three.py", "ruff", [unused]); + const suppress = vi.fn(); + const view = editorAt( + "/p/three.py", + inspectionControlProviders.of((_view, id) => + id === "lsp:ruff:F401" ? [{ id: "suppress", label: "Suppress for statement", run: suppress }] : [], + ), + ); + const [options] = withInspectionControls(view, []); + expect(options!.submenu?.map((s) => ("label" in s ? s.label : "-"))).toEqual([ + "Edit inspection profile setting", + "Disable inspection", + "Suppress for statement", + ]); + setFileDiagnostics("/p/three.py", "ruff", []); + }); + it.each(["info", "warning", "error"] as const)( "uses the effective %s severity for local and LSP fixes", (severity) => { diff --git a/src/editor/lsp/intentions.ts b/src/editor/lsp/intentions.ts index f9cfd5fb57..e809dc61ed 100644 --- a/src/editor/lsp/intentions.ts +++ b/src/editor/lsp/intentions.ts @@ -14,6 +14,7 @@ import { contributedIntentions, contributedIntentionsAsync, contributedQuickFixes, + inspectionControlProviders, intentionProviders, quickFixProviders, intentionsChanged, @@ -41,7 +42,7 @@ import { iconNode } from "@/ui/iconNode"; import { editorPrefs } from "@/platform/editorSettings"; import { spellingIntentions } from "./spelling"; import { inspectionsAt, type EditorDiagnostic } from "./diagnostics"; -import { SPELLING_INSPECTION } from "@/platform/inspections"; +import { SPELLING_INSPECTION, type InspectionRef } from "@/platform/inspections"; import { editInspectionSettings, intentionControls } from "@/platform/inspectionControls"; import { runInteractiveCodeAction } from "./interactiveCommand"; import { tx, txPart } from "@/platform/i18n"; @@ -498,8 +499,12 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[]) ); if (!inspections.length) return items; const fixes = items.filter((i) => isFixItem(i) && !i.submenu); + const controls = (inspection: InspectionRef) => [ + ...intentionControls(inspection), + ...view.state.facet(inspectionControlProviders).flatMap((provide) => provide(view, inspection.id)), + ]; if (inspections.length === 1 && fixes.length) { - const submenu = intentionControls(inspections[0]!); + const submenu = controls(inspections[0]!); return items.map((i) => (fixes.includes(i) ? { ...i, submenu } : i)); } return [ @@ -510,7 +515,7 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[]) section: { id: "inspection-options" }, icon: "settings", run: () => editInspectionSettings(inspection.id), - submenu: intentionControls(inspection), + submenu: controls(inspection), })), ]; } diff --git a/src/features/analysis/inheritanceInspections.test.ts b/src/features/analysis/inheritanceInspections.test.ts index 3e98172441..7185322557 100644 --- a/src/features/analysis/inheritanceInspections.test.ts +++ b/src/features/analysis/inheritanceInspections.test.ts @@ -47,6 +47,7 @@ const forward = (target: string, args: string[], returns = false): MethodBody => const methodFacts = (spec: MethodSpec): PythonMethodFacts => ({ name: spec.name, selection: range(spec.line, spec.col ?? 8), + definitionLine: spec.line, params: spec.params === undefined ? ["self"] : spec.params, abstractMethod: spec.abstract ?? false, overrideDecorated: spec.override ?? false, @@ -95,11 +96,17 @@ class Fixture { for (const spec of classes) { const col = spec.col ?? 6; const methods = (spec.methods ?? []).map(methodFacts); - classFacts.push({ name: spec.name, selection: range(spec.line, col), bases: spec.bases, methods }); + classFacts.push({ + name: spec.name, + selection: range(spec.line, col), + definitionLine: spec.line, + bases: spec.bases, + methods, + }); this.graph.push({ path, line: spec.line, col, name: spec.name, bases: spec.indexedBases ?? spec.bases }); this.outlines.set(path, [...(this.outlines.get(path) ?? []), classItem(spec, col, methods)]); } - this.facts.set(path, { classes: [...(this.facts.get(path)?.classes ?? []), ...classFacts] }); + this.facts.set(path, { classes: [...(this.facts.get(path)?.classes ?? []), ...classFacts], suppressions: [] }); return this; } diff --git a/src/features/analysis/inheritanceInspections.ts b/src/features/analysis/inheritanceInspections.ts index f946d312c5..05e0d2cc4f 100644 --- a/src/features/analysis/inheritanceInspections.ts +++ b/src/features/analysis/inheritanceInspections.ts @@ -10,7 +10,7 @@ */ import type { Extension } from "@codemirror/state"; import { ViewPlugin, type EditorView } from "@codemirror/view"; -import type { EditorDocContext } from "@/editor/api"; +import { inspectionControlProviders, type EditorDocContext } from "@/editor/api"; import { onServerSettled } from "@/editor/lsp/availability"; import { setFileDiagnostics } from "@/editor/lsp/diagnostics"; import { withDocument } from "@/editor/lsp/files"; @@ -52,6 +52,7 @@ import { type PythonMethodFacts, type Range, } from "@/platform/ipc"; +import { isSuppressed, suppressControls, type FactsOf } from "./pythonSuppression"; /** The inspection producers, one per rule. */ const PRODUCERS = [ @@ -414,6 +415,8 @@ function applyProfileTo(diagnostics: readonly Diagnostic[]): Diagnostic[] { } const viewers = new Map(); +/** Each editor view's facts of the last run, for the ⌥↵ Suppress rows. */ +const latestFacts = new WeakMap(); const hasClass = (items: readonly OutlineItem[]): boolean => items.some((item) => item.kind === "class" || hasClass(item.children)); @@ -421,7 +424,8 @@ const hasClass = (items: readonly OutlineItem[]): boolean => export function pythonInheritanceExtension(ctx: EditorDocContext): Extension { if (ctx.language !== "python" || ctx.virtual || ctx.doc < 0) return []; watchChanges(); - return ViewPlugin.define((view: EditorView) => { + const suppress = inspectionControlProviders.of((view, id) => suppressControls(view, id, latestFacts.get(view))); + const plugin = ViewPlugin.define((view: EditorView) => { if (!isTauri()) return {}; viewers.set(ctx.path, (viewers.get(ctx.path) ?? 0) + 1); let timer: ReturnType | undefined; @@ -440,6 +444,7 @@ export function pythonInheritanceExtension(ctx: EditorDocContext): Extension { const outline = await lspRequest(() => commands.docOutline(ctx.doc)); // Every rule is about a class: no class, nothing to fetch the graph for. if (!hasClass(outline)) { + latestFacts.delete(view); setFileDiagnostics(ctx.path, SOURCE, []); return; } @@ -458,8 +463,10 @@ export function pythonInheritanceExtension(ctx: EditorDocContext): Extension { outlineOf: (path) => withDocument(path, (doc) => lspRequest(() => commands.docOutline(doc))).catch(() => []), }); if (disposed || mine !== sequence || view.state.doc !== text) return; - // The profile decides what is shown and how strongly. - setFileDiagnostics(ctx.path, SOURCE, applyProfileTo(found)); + latestFacts.set(view, { facts, doc: text }); + // `# noinspection` comments, then the profile, decide what is shown and how strongly. + const shown = found.filter((d) => !isSuppressed(d, facts.suppressions)); + setFileDiagnostics(ctx.path, SOURCE, applyProfileTo(shown)); } catch (e) { if (!isCancelled(e)) console.debug("[inheritanceInspections]", e); } @@ -491,4 +498,5 @@ export function pythonInheritanceExtension(ctx: EditorDocContext): Extension { }, }; }); + return [plugin, suppress]; } diff --git a/src/features/analysis/pythonSuppression.test.ts b/src/features/analysis/pythonSuppression.test.ts new file mode 100644 index 0000000000..92b18cd6bb --- /dev/null +++ b/src/features/analysis/pythonSuppression.test.ts @@ -0,0 +1,117 @@ +import { EditorState, StateEffect, Text } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { expect, it } from "vitest"; +import type { Diagnostic, PythonFacts, Range } from "@/platform/ipc"; +import { isSuppressed, suppressChange, suppressControls, suppressTargets } from "./pythonSuppression"; + +const range = (sl: number, sc: number, el: number, ec: number): Range => ({ + start: { line: sl, col: sc }, + end: { line: el, col: ec }, +}); +const problem = (code: string, line: number): Diagnostic => ({ + range: range(line, 4, line, 8), + severity: "warning", + message: "", + source: "Python", + code, +}); + +it("drops problems a matching comment covers", () => { + const suppressions = [{ ids: ["PyAbstractClass"], range: range(2, 0, 5, 0) }]; + expect(isSuppressed(problem("builtin:python-abstract-method", 3), suppressions)).toBe(true); + expect(isSuppressed(problem("builtin:python-abstract-method", 6), suppressions)).toBe(false); + expect(isSuppressed(problem("builtin:python-override", 3), suppressions)).toBe(false); + expect(isSuppressed(problem("builtin:python-override", 3), [{ ids: ["ALL"], range: range(0, 0, 9, 0) }])).toBe(true); + // Inspections without a `# noinspection` id are never suppressed. + expect(isSuppressed(problem("builtin:spelling", 3), [{ ids: ["ALL"], range: range(0, 0, 9, 0) }])).toBe(false); +}); + +const FACTS: PythonFacts = { + suppressions: [], + classes: [ + { + name: "Shape", + selection: range(1, 6, 1, 11), + definitionLine: 0, + bases: [], + methods: [ + { + name: "area", + selection: range(4, 8, 4, 12), + definitionLine: 3, + params: ["self"], + abstractMethod: false, + overrideDecorated: true, + body: { kind: "empty" }, + }, + ], + }, + ], +}; + +it("targets the reported definition and its class", () => { + expect(suppressTargets(FACTS, { line: 4, col: 10 })).toEqual([ + { target: "statement", line: 3 }, + { target: "function", line: 3 }, + { target: "class", line: 0 }, + ]); + expect(suppressTargets(FACTS, { line: 1, col: 11 })).toEqual([ + { target: "statement", line: 0 }, + { target: "class", line: 0 }, + ]); + expect(suppressTargets(FACTS, { line: 2, col: 0 })).toEqual([]); +}); + +const apply = (doc: Text, change: ReturnType) => + doc.replace(change.from, change.to ?? change.from, Text.of(change.insert.split("\n"))).toString(); + +it("writes the comment above the target at its indentation, or adds to the one there", () => { + const doc = Text.of(["class Shape:", " @override", " def area(self):", " pass"]); + expect(apply(doc, suppressChange(doc, 1, "PyOverrideDecorator"))).toBe( + "class Shape:\n # noinspection PyOverrideDecorator\n @override\n def area(self):\n pass", + ); + const commented = Text.of(["class Shape:", " # noinspection PyAbstractClass", " def area(self):"]); + expect(apply(commented, suppressChange(commented, 2, "PyOverrideDecorator"))).toBe( + "class Shape:\n # noinspection PyAbstractClass,PyOverrideDecorator\n def area(self):", + ); + expect(apply(commented, suppressChange(commented, 2, "PyAbstractClass"))).toBe(commented.toString()); + const stacked = Text.of([ + "class Shape:", + " # noinspection PyAbstractClass", + " # keep this", + " def area(self):", + ]); + expect(apply(stacked, suppressChange(stacked, 3, "PyOverrideDecorator"))).toBe( + "class Shape:\n # noinspection PyAbstractClass,PyOverrideDecorator\n # keep this\n def area(self):", + ); + // A comment at another indentation belongs to other code. + expect(apply(commented, suppressChange(commented, 0, "PyAbstractClass"))).toBe( + "# noinspection PyAbstractClass\n" + commented.toString(), + ); +}); + +it("offers no Suppress rows once the text has changed since the facts were read", () => { + const doc = Text.of(["class Shape:", " pass", "", " @override", " def area(self):", " pass"]); + const view = new EditorView({ state: EditorState.create({ doc, selection: { anchor: doc.line(5).from + 10 } }) }); + const latest = { facts: FACTS, doc: view.state.doc }; + const rows = suppressControls(view, "builtin:python-override", latest); + expect(rows.map((r) => r.label)).toEqual(["Suppress for statement", "Suppress for function", "Suppress for class"]); + view.dispatch({ changes: { from: 0, insert: "import os\n" } }); + expect(suppressControls(view, "builtin:python-override", latest)).toEqual([]); + // A row picked from a menu opened before the edit does nothing. + rows[0]!.run(); + expect(view.state.doc.line(1).text).toBe("import os"); + view.destroy(); +}); + +it("keeps a read-only document unchanged", () => { + const doc = Text.of(["class Shape:", " pass", "", " @override", " def area(self):", " pass"]); + const view = new EditorView({ state: EditorState.create({ doc, selection: { anchor: doc.line(5).from + 10 } }) }); + const latest = { facts: FACTS, doc: view.state.doc }; + const [row] = suppressControls(view, "builtin:python-override", latest); + view.dispatch({ effects: StateEffect.appendConfig.of(EditorState.readOnly.of(true)) }); + expect(suppressControls(view, "builtin:python-override", latest)).toEqual([]); + row!.run(); + expect(view.state.doc).toBe(doc); + view.destroy(); +}); diff --git a/src/features/analysis/pythonSuppression.ts b/src/features/analysis/pythonSuppression.ts new file mode 100644 index 0000000000..a0b797521e --- /dev/null +++ b/src/features/analysis/pythonSuppression.ts @@ -0,0 +1,107 @@ +/** + * PyCharm's `# noinspection ` comments for the IDE's own Python inspections: the parser + * reports which code each comment covers (`PythonFacts.suppressions`), problems there are + * dropped, and ⌥↵ offers Suppress for statement / function / class to write the comment. + * Ruff and basedpyright have suppress fixes of their own (`# noqa`, `# pyright: ignore`). + */ +import type { Text } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import type { ContributedIntention } from "@/editor/api"; +import { suppressIdOf } from "@/platform/inspections"; +import type { Diagnostic, PythonFacts, PythonSuppression, Range } from "@/platform/ipc"; + +type Pos = Range["start"]; + +const before = (a: Pos, b: Pos) => a.line < b.line || (a.line === b.line && a.col <= b.col); +const within = (pos: Pos, range: Range) => before(range.start, pos) && before(pos, range.end); + +/** Whether a `# noinspection` comment covers `d` (its `code` is the inspection id). */ +export function isSuppressed(d: Diagnostic, suppressions: readonly PythonSuppression[]): boolean { + const id = suppressIdOf(d.code ?? ""); + return ( + !!id && suppressions.some((s) => (s.ids.includes(id) || s.ids.includes("ALL")) && within(d.range.start, s.range)) + ); +} + +export type SuppressTarget = "statement" | "function" | "class"; + +/** + * Where each Suppress fix writes its comment for a problem at `pos`: the line its + * definition starts on. The inspections report on class and method names, so the + * statement is that definition itself. + */ +export function suppressTargets(facts: PythonFacts, pos: Pos): { target: SuppressTarget; line: number }[] { + for (const cls of facts.classes) { + const method = cls.methods.find((m) => within(pos, m.selection)); + if (method) + return [ + { target: "statement", line: method.definitionLine }, + { target: "function", line: method.definitionLine }, + { target: "class", line: cls.definitionLine }, + ]; + } + const cls = facts.classes.find((c) => within(pos, c.selection)); + return cls + ? [ + { target: "statement", line: cls.definitionLine }, + { target: "class", line: cls.definitionLine }, + ] + : []; +} + +const NOINSPECTION = /^\s*#\s*noinspection\s+(.*?)\s*$/; + +/** The change that suppresses `id` above 0-based `line`: a new comment, or `id` added to the one there. */ +export function suppressChange(doc: Text, line: number, id: string): { from: number; to?: number; insert: string } { + const target = doc.line(line + 1); + const indent = /^\s*/.exec(target.text)![0]; + for (let row = line; row > 0; row--) { + const above = doc.line(row); + if (!above.text.startsWith(`${indent}#`)) break; + const m = NOINSPECTION.exec(above.text); + if (!m) continue; + const ids = m[1]! + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + if (ids.includes(id) || ids.includes("ALL")) return { from: above.from, insert: "" }; + return { from: above.from, to: above.to, insert: `${indent}# noinspection ${[...ids, id].join(",")}` }; + } + return { from: target.from, insert: `${indent}# noinspection ${id}\n` }; +} + +const LABELS: Record = { + statement: "Suppress for statement", + function: "Suppress for function", + class: "Suppress for class", +}; + +/** Facts of a document and the text they were read from. */ +export interface FactsOf { + facts: PythonFacts; + doc: Text; +} + +/** + * The ⌥↵ Suppress rows for inspection `inspectionId` at the caret, from the last run's facts. + * After an edit their lines are stale: nothing is offered until the next run. + */ +export function suppressControls( + view: EditorView, + inspectionId: string, + latest: FactsOf | undefined, +): ContributedIntention[] { + const id = suppressIdOf(inspectionId); + if (!id || !latest || latest.doc !== view.state.doc || view.state.readOnly) return []; + const { facts, doc } = latest; + const head = view.state.selection.main.head; + const line = view.state.doc.lineAt(head); + return suppressTargets(facts, { line: line.number - 1, col: head - line.from }).map(({ target, line }) => ({ + id: `inspection.suppress.${target}`, + label: LABELS[target], + run: () => { + if (view.state.doc === doc && !view.state.readOnly) + view.dispatch({ changes: suppressChange(doc, line, id), userEvent: "input" }); + }, + })); +} diff --git a/src/platform/inspectionControls.test.ts b/src/platform/inspectionControls.test.ts index a5ba00bb3c..3b224fc6f7 100644 --- a/src/platform/inspectionControls.test.ts +++ b/src/platform/inspectionControls.test.ts @@ -46,6 +46,11 @@ describe("inspection controls", () => { }); expect(diagnosticInspection("phpstan", { code: null })).toEqual({ id: "builtin:phpstan", name: "PHPStan" }); expect(diagnosticInspection("build", { code: "E0308" })).toEqual({ id: "builtin:build", name: "Build problems" }); + // The Python inheritance checks publish under one producer, each with its inspection id as the code. + expect(diagnosticInspection("Python", { code: "builtin:python-abstract-method" })).toEqual({ + id: "builtin:python-abstract-method", + name: "Abstract method not implemented", + }); }); it("writes to the profile in effect, at its level", async () => { diff --git a/src/platform/inspections.ts b/src/platform/inspections.ts index 08ca2ef7d8..e531237282 100644 --- a/src/platform/inspections.ts +++ b/src/platform/inspections.ts @@ -221,6 +221,8 @@ export interface BuiltinInspection { /** Each diagnostic code is an inspection of its own (`:`), as a language server's are. */ byCode?: boolean; options?: readonly InspectionOptionSpec[]; + /** Id a `# noinspection` comment names to suppress it (PyCharm's, where PyCharm has the inspection). */ + suppressId?: string; } /** Turned on, the Java language server's compiler reports it (`ide-sdk` `SERIAL_VERSION_INSPECTION`). */ @@ -346,6 +348,7 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [ }, { id: PYTHON_CIRCULAR_BASES_INSPECTION, + suppressId: "PyCircularInheritance", producer: PYTHON_CIRCULAR_BASES_PRODUCER, name: "Circular inheritance", group: "Python", @@ -355,6 +358,7 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [ }, { id: PYTHON_OVERRIDE_INSPECTION, + suppressId: "PyOverrideDecorator", producer: PYTHON_OVERRIDE_PRODUCER, name: "Inconsistent '@override'", group: "Python", @@ -364,6 +368,7 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [ }, { id: PYTHON_ABSTRACT_METHOD_INSPECTION, + suppressId: "PyAbstractClass", producer: PYTHON_ABSTRACT_METHOD_PRODUCER, name: "Abstract method not implemented", group: "Python", @@ -373,6 +378,7 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [ }, { id: PYTHON_REDUNDANT_OVERRIDE_INSPECTION, + suppressId: "PyRedundantOverride", producer: PYTHON_REDUNDANT_OVERRIDE_PRODUCER, name: "Redundant override", group: "Python", @@ -427,6 +433,9 @@ export interface InspectionRef { export function diagnosticInspection(producer: string, d: Pick): InspectionRef | null { if (!producer) return null; + // Producers that publish several inspections (the Python inheritance checks) set each one's id as the code. + const own = d.code ? BUILTIN_BY_ID.get(d.code) : undefined; + if (own) return { id: own.id, name: own.name }; const builtin = BUILTIN_BY_PRODUCER.get(producer); if (builtin && !(builtin.byCode && d.code)) return { id: builtin.id, name: builtin.name }; const base = producerInspectionId(producer); @@ -434,6 +443,11 @@ export function diagnosticInspection(producer: string, d: Pick