Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[flake8-pyi] Implement PYI046 #6098

Merged
merged 6 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_pyi/PYI046.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import typing
from typing import Protocol


class _Foo(Protocol):
bar: int


class _Bar(typing.Protocol):
bar: int


# OK
class _UsedPrivateProtocol(Protocol):
bar: int


def uses__UsedPrivateProtocol(arg: _UsedPrivateProtocol) -> None: ...
18 changes: 18 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_pyi/PYI046.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import typing
from typing import Protocol


class _Foo(object, Protocol):
bar: int


class _Bar(typing.Protocol):
bar: int


# OK
class _UsedPrivateProtocol(Protocol):
bar: int


def uses__UsedPrivateProtocol(arg: _UsedPrivateProtocol) -> None: ...
8 changes: 8 additions & 0 deletions crates/ruff/src/checkers/ast/analyze/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub(crate) fn bindings(checker: &mut Checker) {
Rule::UnaliasedCollectionsAbcSetImport,
Rule::UnconventionalImportAlias,
Rule::UnusedVariable,
Rule::UnusedPrivateProtocol,
]) {
return;
}
Expand Down Expand Up @@ -63,6 +64,13 @@ pub(crate) fn bindings(checker: &mut Checker) {
checker.diagnostics.push(diagnostic);
}
}
if checker.enabled(Rule::UnusedPrivateProtocol) {
if let Some(diagnostic) =
flake8_pyi::rules::unused_private_protocol(checker, binding)
{
checker.diagnostics.push(diagnostic);
}
}
}
}
}
15 changes: 13 additions & 2 deletions crates/ruff/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -722,16 +722,27 @@ where
BindingFlags::empty(),
);
}
Stmt::ClassDef(ast::StmtClassDef { name, .. }) => {
Stmt::ClassDef(ast::StmtClassDef { name, bases, .. }) => {
let mut flags = BindingFlags::empty();
let scope_id = self.semantic.scope_id;
self.deferred.scopes.push(scope_id);
self.semantic.pop_scope();
self.semantic.pop_definition();

if name.starts_with('_') {
if bases
.iter()
.any(|base| self.semantic.match_typing_expr(base, "Protocol"))
{
flags |= BindingFlags::PRIVATE_TYPE_PROTOCOL;
}
}

self.add_binding(
name,
stmt.identifier(),
BindingKind::ClassDefinition(scope_id),
BindingFlags::empty(),
flags,
);
}
_ => {}
Expand Down
1 change: 1 addition & 0 deletions crates/ruff/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Flake8Pyi, "043") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::TSuffixedTypeAlias),
(Flake8Pyi, "044") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::FutureAnnotationsInStub),
(Flake8Pyi, "045") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::IterMethodReturnIterable),
(Flake8Pyi, "046") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::UnusedPrivateProtocol),
(Flake8Pyi, "048") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::StubBodyMultipleStatements),
(Flake8Pyi, "050") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::NoReturnArgumentAnnotationInStub),
(Flake8Pyi, "052") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::UnannotatedAssignmentInStub),
Expand Down
2 changes: 2 additions & 0 deletions crates/ruff/src/rules/flake8_pyi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ mod tests {
#[test_case(Rule::TypeAliasWithoutAnnotation, Path::new("PYI026.pyi"))]
#[test_case(Rule::UnsupportedMethodCallOnAll, Path::new("PYI056.py"))]
#[test_case(Rule::UnsupportedMethodCallOnAll, Path::new("PYI056.pyi"))]
#[test_case(Rule::UnusedPrivateProtocol, Path::new("PYI046.py"))]
#[test_case(Rule::UnusedPrivateProtocol, Path::new("PYI046.pyi"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Expand Down
2 changes: 2 additions & 0 deletions crates/ruff/src/rules/flake8_pyi/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub(crate) use unnecessary_literal_union::*;
pub(crate) use unrecognized_platform::*;
pub(crate) use unrecognized_version_info::*;
pub(crate) use unsupported_method_call_on_all::*;
pub(crate) use unused_private_type_declaration::*;

mod any_eq_ne_annotation;
mod bad_version_info_comparison;
Expand Down Expand Up @@ -61,3 +62,4 @@ mod unnecessary_literal_union;
mod unrecognized_platform;
mod unrecognized_version_info;
mod unsupported_method_call_on_all;
mod unused_private_type_declaration;
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_semantic::Binding;

use crate::checkers::ast::Checker;

/// ## What it does
/// Checks for the presence of unused private `typing.Protocol` definitions.
///
/// ## Why is this bad?
/// A private `typing.Protocol` that is defined but not used is likely a mistake, and should
/// be removed to avoid confusion.
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
///
/// ## Example
/// ```python
/// import typing
///
/// class _PrivateProtocol(typing.Protocol):
/// foo: int
/// ```
///
/// Use instead:
/// ```python
/// import typing
///
/// class _PrivateProtocol(typing.Protocol):
/// foo: int
///
/// def func(arg: _PrivateProtocol) -> None: ...
/// ```
#[violation]
pub struct UnusedPrivateProtocol {
name: String,
}

impl Violation for UnusedPrivateProtocol {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedPrivateProtocol { name } = self;
format!("Protocol `{name}` is never used")
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
}
}

/// PYI046
pub(crate) fn unused_private_protocol(checker: &Checker, binding: &Binding) -> Option<Diagnostic> {
if !binding.kind.is_class_definition() {
return None;
}
if !binding.is_private_protocol() {
return None;
}
if binding.is_used() {
return None;
}

Some(Diagnostic::new(
UnusedPrivateProtocol {
name: binding.name(checker.locator()).to_string(),
},
binding.range,
))
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
source: crates/ruff/src/rules/flake8_pyi/mod.rs
---

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
source: crates/ruff/src/rules/flake8_pyi/mod.rs
---
PYI046.pyi:5:7: PYI046 Protocol `_Foo` is never used
|
5 | class _Foo(object, Protocol):
| ^^^^ PYI046
6 | bar: int
|

PYI046.pyi:9:7: PYI046 Protocol `_Bar` is never used
|
9 | class _Bar(typing.Protocol):
| ^^^^ PYI046
10 | bar: int
|


16 changes: 16 additions & 0 deletions crates/ruff_python_semantic/src/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ impl<'a> Binding<'a> {
)
}

/// Return `true` if this [`Binding`] represents a `typing.Protocol` definition.
pub const fn is_private_protocol(&self) -> bool {
self.flags.intersects(BindingFlags::PRIVATE_TYPE_PROTOCOL)
}

/// Return `true` if this binding redefines the given binding.
pub fn redefines(&self, existing: &'a Binding) -> bool {
match &self.kind {
Expand Down Expand Up @@ -264,6 +269,17 @@ bitflags! {
/// __all__ = [1]
/// ```
const INVALID_ALL_OBJECT = 1 << 6;

/// The binding represents a private `typing.Protocol`.
///
/// For example, the binding could be `_PrivateProtocol` in:
/// ```python
/// import typing
///
/// class _PrivateProtocol(typing.Protocol):
/// foo: int
/// ```
const PRIVATE_TYPE_PROTOCOL = 1 << 7;
}
}

Expand Down
1 change: 1 addition & 0 deletions ruff.schema.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.