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

Enable automatic rewrites of typing.Deque and typing.DefaultDict #4420

Merged
merged 2 commits into from
May 15, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 8 additions & 0 deletions crates/ruff/resources/test/fixtures/pyupgrade/UP006.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,11 @@ def f(x: "List['Li' 'st[str]']") -> None:

def f(x: "Li" "st['List[str]']") -> None:
...


def f(x: typing.Deque[str]) -> None:
...


def f(x: typing.DefaultDict[str, str]) -> None:
...
162 changes: 100 additions & 62 deletions crates/ruff/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2257,26 +2257,40 @@ where
match &expr.node {
ExprKind::Subscript(ast::ExprSubscript { value, slice, .. }) => {
// Ex) Optional[...], Union[...]
if self
.settings
.rules
.enabled(Rule::MissingFutureAnnotationsImport)
&& (self.settings.target_version < PythonVersion::Py310
&& (self.settings.target_version >= PythonVersion::Py37
&& !self.ctx.future_annotations()
&& self.ctx.in_annotation()))
&& analyze::typing::is_pep604_builtin(value, &self.ctx)
{
flake8_future_annotations::rules::missing_future_annotations(self, value);
}
if self.settings.rules.enabled(Rule::NonPEP604Annotation)
&& (self.settings.target_version >= PythonVersion::Py310
|| (self.settings.target_version >= PythonVersion::Py37
&& self.ctx.future_annotations()
&& self.ctx.in_annotation()))
&& analyze::typing::is_pep604_builtin(value, &self.ctx)
{
pyupgrade::rules::use_pep604_annotation(self, expr, value, slice);
if self.settings.rules.any_enabled(&[
Rule::MissingFutureAnnotationsImport,
Rule::NonPEP604Annotation,
]) {
if let Some(operator) =
analyze::typing::to_pep604_operator(value, slice, &self.ctx)
{
if self
.settings
.rules
.enabled(Rule::MissingFutureAnnotationsImport)
{
if self.settings.target_version < PythonVersion::Py310
&& self.settings.target_version >= PythonVersion::Py37
&& !self.ctx.future_annotations()
&& self.ctx.in_annotation()
{
flake8_future_annotations::rules::missing_future_annotations(
self, value,
);
}
}
if self.settings.rules.enabled(Rule::NonPEP604Annotation) {
if self.settings.target_version >= PythonVersion::Py310
|| (self.settings.target_version >= PythonVersion::Py37
&& self.ctx.future_annotations()
&& self.ctx.in_annotation())
{
pyupgrade::rules::use_pep604_annotation(
self, expr, slice, operator,
);
}
}
}
}

if self.ctx.match_typing_expr(value, "Literal") {
Expand Down Expand Up @@ -2332,28 +2346,42 @@ where
}

// Ex) List[...]
if self
.settings
.rules
.enabled(Rule::MissingFutureAnnotationsImport)
&& (self.settings.target_version < PythonVersion::Py39
&& (self.settings.target_version >= PythonVersion::Py37
&& !self.ctx.future_annotations()
&& self.ctx.in_annotation()))
&& analyze::typing::is_pep585_builtin(expr, &self.ctx)
{
flake8_future_annotations::rules::missing_future_annotations(
self, expr,
);
}
if self.settings.rules.enabled(Rule::NonPEP585Annotation)
&& (self.settings.target_version >= PythonVersion::Py39
|| (self.settings.target_version >= PythonVersion::Py37
&& self.ctx.future_annotations()
&& self.ctx.in_annotation()))
&& analyze::typing::is_pep585_builtin(expr, &self.ctx)
{
pyupgrade::rules::use_pep585_annotation(self, expr);
if self.settings.rules.any_enabled(&[
Rule::MissingFutureAnnotationsImport,
Rule::NonPEP585Annotation,
]) {
if let Some(replacement) =
analyze::typing::to_pep585_generic(expr, &self.ctx)
{
if self
.settings
.rules
.enabled(Rule::MissingFutureAnnotationsImport)
{
if self.settings.target_version < PythonVersion::Py39
&& self.settings.target_version >= PythonVersion::Py37
&& !self.ctx.future_annotations()
&& self.ctx.in_annotation()
{
flake8_future_annotations::rules::missing_future_annotations(
self, expr,
);
}
}
if self.settings.rules.enabled(Rule::NonPEP585Annotation) {
if self.settings.target_version >= PythonVersion::Py39
|| (self.settings.target_version >= PythonVersion::Py37
&& self.ctx.future_annotations()
&& self.ctx.in_annotation())
{
pyupgrade::rules::use_pep585_annotation(
self,
expr,
&replacement,
);
}
}
}
}

self.handle_node_load(expr);
Expand Down Expand Up @@ -2396,26 +2424,36 @@ where
}
ExprKind::Attribute(ast::ExprAttribute { attr, value, .. }) => {
// Ex) typing.List[...]
if self
.settings
.rules
.enabled(Rule::MissingFutureAnnotationsImport)
&& (self.settings.target_version < PythonVersion::Py39
&& (self.settings.target_version >= PythonVersion::Py37
&& !self.ctx.future_annotations()
&& self.ctx.in_annotation()))
&& analyze::typing::is_pep585_builtin(expr, &self.ctx)
{
flake8_future_annotations::rules::missing_future_annotations(self, expr);
}
if self.settings.rules.enabled(Rule::NonPEP585Annotation)
&& (self.settings.target_version >= PythonVersion::Py39
|| (self.settings.target_version >= PythonVersion::Py37
&& self.ctx.future_annotations()
&& self.ctx.in_annotation()))
&& analyze::typing::is_pep585_builtin(expr, &self.ctx)
{
pyupgrade::rules::use_pep585_annotation(self, expr);
if self.settings.rules.any_enabled(&[
Rule::MissingFutureAnnotationsImport,
Rule::NonPEP585Annotation,
]) {
if let Some(replacement) = analyze::typing::to_pep585_generic(expr, &self.ctx) {
if self
.settings
.rules
.enabled(Rule::MissingFutureAnnotationsImport)
{
if self.settings.target_version < PythonVersion::Py39
&& self.settings.target_version >= PythonVersion::Py37
&& !self.ctx.future_annotations()
&& self.ctx.in_annotation()
{
flake8_future_annotations::rules::missing_future_annotations(
self, expr,
);
}
}
if self.settings.rules.enabled(Rule::NonPEP585Annotation) {
if self.settings.target_version >= PythonVersion::Py39
|| (self.settings.target_version >= PythonVersion::Py37
&& self.ctx.future_annotations()
&& self.ctx.in_annotation())
{
pyupgrade::rules::use_pep585_annotation(self, expr, &replacement);
}
}
}
}
if self.settings.rules.enabled(Rule::DatetimeTimezoneUTC)
&& self.settings.target_version >= PythonVersion::Py311
Expand Down
82 changes: 51 additions & 31 deletions crates/ruff/src/rules/pyupgrade/rules/use_pep585_annotation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,58 +2,78 @@ use rustpython_parser::ast::Expr;

use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::call_path::compose_call_path;
use ruff_python_semantic::analyze::typing::ModuleMember;

use crate::autofix::actions::get_or_import_symbol;
use crate::checkers::ast::Checker;
use crate::registry::AsRule;

#[violation]
pub struct NonPEP585Annotation {
name: String,
from: String,
to: String,
}

impl Violation for NonPEP585Annotation {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes;

#[derive_message_formats]
fn message(&self) -> String {
let NonPEP585Annotation { name } = self;
format!(
"Use `{}` instead of `{}` for type annotations",
name.to_lowercase(),
name,
)
let NonPEP585Annotation { from, to } = self;
format!("Use `{to}` instead of `{from}` for type annotation")
}

fn autofix_title(&self) -> Option<String> {
let NonPEP585Annotation { name } = self;
Some(format!("Replace `{name}` with `{}`", name.to_lowercase()))
let NonPEP585Annotation { to, .. } = self;
Some(format!("Replace with `{to}`"))
}
}

/// UP006
pub(crate) fn use_pep585_annotation(checker: &mut Checker, expr: &Expr) {
if let Some(binding) = checker
.ctx
.resolve_call_path(expr)
.and_then(|call_path| call_path.last().copied())
{
let fixable = !checker.ctx.in_complex_string_type_definition();
let mut diagnostic = Diagnostic::new(
NonPEP585Annotation {
name: binding.to_string(),
},
expr.range(),
);
if fixable && checker.patch(diagnostic.kind.rule()) {
let binding = binding.to_lowercase();
if checker.ctx.is_builtin(&binding) {
#[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
binding,
expr.range(),
)));
pub(crate) fn use_pep585_annotation(
checker: &mut Checker,
expr: &Expr,
replacement: &ModuleMember,
) {
let Some(from) = compose_call_path(expr) else {
return;
};
let mut diagnostic = Diagnostic::new(
NonPEP585Annotation {
from,
to: replacement.to_string(),
},
expr.range(),
);
let fixable = !checker.ctx.in_complex_string_type_definition();
if fixable && checker.patch(diagnostic.kind.rule()) {
match replacement {
ModuleMember::BuiltIn(name) => {
// Built-in type, like `list`.
if checker.ctx.is_builtin(name) {
diagnostic.set_fix(Fix::automatic(Edit::range_replacement(
(*name).to_string(),
expr.range(),
)));
}
}
ModuleMember::Member(module, member) => {
// Imported type, like `collections.deque`.
diagnostic.try_set_fix(|| {
let (import_edit, binding) = get_or_import_symbol(
module,
member,
expr.start(),
&checker.ctx,
&checker.importer,
checker.locator,
)?;
let reference_edit = Edit::range_replacement(binding, expr.range());
Ok(Fix::suggested_edits(import_edit, [reference_edit]))
});
}
}
checker.diagnostics.push(diagnostic);
}
checker.diagnostics.push(diagnostic);
}
46 changes: 5 additions & 41 deletions crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprKind, Operator};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use ruff_python_semantic::analyze::typing::Pep604Operator;

use crate::checkers::ast::Checker;
use crate::registry::AsRule;
Expand Down Expand Up @@ -56,55 +57,18 @@ fn union(elts: &[Expr]) -> Expr {
}
}

/// Returns `true` if any argument in the slice is a string.
fn any_arg_is_str(slice: &Expr) -> bool {
match &slice.node {
ExprKind::Constant(ast::ExprConstant {
value: Constant::Str(_),
..
}) => true,
ExprKind::Tuple(ast::ExprTuple { elts, .. }) => elts.iter().any(any_arg_is_str),
_ => false,
}
}

#[derive(Copy, Clone)]
enum TypingMember {
Union,
Optional,
}

/// UP007
pub(crate) fn use_pep604_annotation(
checker: &mut Checker,
expr: &Expr,
value: &Expr,
slice: &Expr,
operator: Pep604Operator,
) {
// If any of the _arguments_ are forward references, we can't use PEP 604.
// Ex) `Union["str", "int"]` can't be converted to `"str" | "int"`.
if any_arg_is_str(slice) {
return;
}

let Some(typing_member) = checker.ctx.resolve_call_path(value).as_ref().and_then(|call_path| {
if checker.ctx.match_typing_call_path(call_path, "Optional") {
Some(TypingMember::Optional)
} else if checker.ctx.match_typing_call_path(call_path, "Union") {
Some(TypingMember::Union)
} else {
None
}
}) else {
return;
};

// Avoid fixing forward references, or types not in an annotation.
let fixable =
checker.ctx.in_type_definition() && !checker.ctx.in_complex_string_type_definition();

match typing_member {
TypingMember::Optional => {
match operator {
Pep604Operator::Optional => {
let mut diagnostic = Diagnostic::new(NonPEP604Annotation, expr.range());
if fixable && checker.patch(diagnostic.kind.rule()) {
#[allow(deprecated)]
Expand All @@ -115,7 +79,7 @@ pub(crate) fn use_pep604_annotation(
}
checker.diagnostics.push(diagnostic);
}
TypingMember::Union => {
Pep604Operator::Union => {
let mut diagnostic = Diagnostic::new(NonPEP604Annotation, expr.range());
if fixable && checker.patch(diagnostic.kind.rule()) {
match &slice.node {
Expand Down
Loading