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 PYI026 #5844

Merged
merged 7 commits into from
Jul 20, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

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

NewAny = Any
OptinalStr = typing.Optional[str]
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
Foo = Literal["foo"]
IntOrStr = int | str
AliasNone = None

NewAny: typing.TypeAlias = Any
OptinalStr: TypeAlias = typing.Optional[str]
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
Foo: typing.TypeAlias = Literal["foo"]
IntOrStr: TypeAlias = int | str
AliasNone: typing.TypeAlias = None

# these are ok
VarAlias = str
AliasFoo = Foo
18 changes: 18 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_pyi/PYI026.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import typing
from typing import TypeAlias, Literal, Any

NewAny = Any
OptinalStr = typing.Optional[str]
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
Foo = Literal["foo"]
IntOrStr = int | str
AliasNone = None

NewAny: typing.TypeAlias = Any
OptinalStr: TypeAlias = typing.Optional[str]
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
Foo: typing.TypeAlias = Literal["foo"]
IntOrStr: TypeAlias = int | str
AliasNone: typing.TypeAlias = None

LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
# these are ok
VarAlias = str
AliasFoo = Foo
4 changes: 4 additions & 0 deletions crates/ruff/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1549,6 +1549,7 @@ where
Rule::UnprefixedTypeParam,
Rule::AssignmentDefaultInStub,
Rule::UnannotatedAssignmentInStub,
Rule::TypeAliasCheck,
]) {
// Ignore assignments in function bodies; those are covered by other rules.
if !self
Expand All @@ -1567,6 +1568,9 @@ where
self, targets, value,
);
}
if self.enabled(Rule::TypeAliasCheck) {
flake8_pyi::rules::type_alias_check(self, value, targets);
}
}
}
}
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 @@ -633,6 +633,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Flake8Pyi, "021") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::DocstringInStub),
(Flake8Pyi, "024") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::CollectionsNamedTuple),
(Flake8Pyi, "025") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::UnaliasedCollectionsAbcSetImport),
(Flake8Pyi, "026") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::TypeAliasCheck),
(Flake8Pyi, "029") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::StrOrReprDefinedInStub),
(Flake8Pyi, "030") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::UnnecessaryLiteralUnion),
(Flake8Pyi, "032") => (RuleGroup::Unspecified, rules::flake8_pyi::rules::AnyEqNeAnnotation),
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 @@ -87,6 +87,8 @@ mod tests {
#[test_case(Rule::UnrecognizedVersionInfoCheck, Path::new("PYI003.pyi"))]
#[test_case(Rule::WrongTupleLengthVersionComparison, Path::new("PYI005.py"))]
#[test_case(Rule::WrongTupleLengthVersionComparison, Path::new("PYI005.pyi"))]
#[test_case(Rule::TypeAliasCheck, Path::new("PYI026.py"))]
#[test_case(Rule::TypeAliasCheck, Path::new("PYI026.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
73 changes: 69 additions & 4 deletions crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,36 @@ impl Violation for UnassignedSpecialVariableInStub {
}
}

/// ## What it does
/// Checks for `typehint.TypeAlias` annotation in type aliases.
///
/// ## Why is this bad?
/// It makes harder for someone reading the code to differentiate
/// between a value assignment and a type alias.
///
/// ## Example
/// ```python
/// IntOrStr = int | str
/// ```
///
/// Use instead:
/// ```python
/// IntOrStr: TypeAlias = int | str
/// ```
#[violation]
pub struct TypeAliasCheck {
name: String,
value: String,
}

impl Violation for TypeAliasCheck {
#[derive_message_formats]
fn message(&self) -> String {
let TypeAliasCheck { name, value } = self;
format!("Use `typing.TypeAlias` for type aliases in `{name}`, e.g. \"{name}: typing.TypeAlias = {value}\"")
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
}
}

fn is_allowed_negated_math_attribute(call_path: &CallPath) -> bool {
matches!(call_path.as_slice(), ["math", "inf" | "e" | "pi" | "tau"])
}
Expand Down Expand Up @@ -399,9 +429,10 @@ pub(crate) fn argument_simple_defaults(checker: &mut Checker, arguments: &Argume

/// PYI015
pub(crate) fn assignment_default_in_stub(checker: &mut Checker, targets: &[Expr], value: &Expr) {
let [target] = targets else {
if targets.len() != 1 {
return;
};
}
let target = &targets[0];
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
if !target.is_name_expr() {
return;
}
Expand Down Expand Up @@ -470,9 +501,10 @@ pub(crate) fn unannotated_assignment_in_stub(
targets: &[Expr],
value: &Expr,
) {
let [target] = targets else {
if targets.len() != 1 {
return;
};
}
let target = &targets[0];
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
let Expr::Name(ast::ExprName { id, .. }) = target else {
return;
};
Expand Down Expand Up @@ -523,3 +555,36 @@ pub(crate) fn unassigned_special_variable_in_stub(
stmt.range(),
));
}

/// PIY026
pub(crate) fn type_alias_check(checker: &mut Checker, value: &Expr, targets: &[Expr]) {
let is_any = |expr: &Expr| {
let Expr::Name(ast::ExprName { id, .. }) = expr else {
return false;
};
id == "Any"
};

let target = &targets[0];
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
if is_special_assignment(target, checker.semantic()) {
return;
}
if matches!(value, Expr::Name(_)) && !is_any(value) {
return;
}
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reordered these operations from least- to most-expensive.

if !is_valid_pep_604_union(value) {
return;
}

let Expr::Name(ast::ExprName { id, .. }) = target else {
return;
};

checker.diagnostics.push(Diagnostic::new(
TypeAliasCheck {
name: id.to_string(),
value: checker.generator().expr(value),
},
target.range(),
));
}
LaBatata101 marked this conversation as resolved.
Show resolved Hide resolved
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,52 @@
---
source: crates/ruff/src/rules/flake8_pyi/mod.rs
---
PYI026.pyi:4:1: PYI026 Use `typing.TypeAlias` for type aliases in `NewAny`, e.g. "NewAny: typing.TypeAlias = Any"
|
2 | from typing import TypeAlias, Literal, Any
3 |
4 | NewAny = Any
| ^^^^^^ PYI026
5 | OptinalStr = typing.Optional[str]
6 | Foo = Literal["foo"]
|

PYI026.pyi:5:1: PYI026 Use `typing.TypeAlias` for type aliases in `OptinalStr`, e.g. "OptinalStr: typing.TypeAlias = typing.Optional[str]"
|
4 | NewAny = Any
5 | OptinalStr = typing.Optional[str]
| ^^^^^^^^^^ PYI026
6 | Foo = Literal["foo"]
7 | IntOrStr = int | str
|

PYI026.pyi:6:1: PYI026 Use `typing.TypeAlias` for type aliases in `Foo`, e.g. "Foo: typing.TypeAlias = Literal["foo"]"
|
4 | NewAny = Any
5 | OptinalStr = typing.Optional[str]
6 | Foo = Literal["foo"]
| ^^^ PYI026
7 | IntOrStr = int | str
8 | AliasNone = None
|

PYI026.pyi:7:1: PYI026 Use `typing.TypeAlias` for type aliases in `IntOrStr`, e.g. "IntOrStr: typing.TypeAlias = int | str"
|
5 | OptinalStr = typing.Optional[str]
6 | Foo = Literal["foo"]
7 | IntOrStr = int | str
| ^^^^^^^^ PYI026
8 | AliasNone = None
|

PYI026.pyi:8:1: PYI026 Use `typing.TypeAlias` for type aliases in `AliasNone`, e.g. "AliasNone: typing.TypeAlias = None"
|
6 | Foo = Literal["foo"]
7 | IntOrStr = int | str
8 | AliasNone = None
| ^^^^^^^^^ PYI026
9 |
10 | NewAny: typing.TypeAlias = Any
|


2 changes: 1 addition & 1 deletion ruff.schema.json

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

Loading