Skip to content

Commit

Permalink
Add a resolve_binding method to Context
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Mar 28, 2023
1 parent ec8ca66 commit aed248b
Show file tree
Hide file tree
Showing 10 changed files with 211 additions and 109 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,10 @@
def main():
exit(1)
quit(1)


def main():
exit = 1

exit(1)
quit(1)
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
import functools
from functools import lru_cache


@functools.lru_cache(maxsize=None)
def fixme():
pass


@lru_cache(maxsize=None)
def fixme():
pass


@other_decorator
@functools.lru_cache(maxsize=None)
def fixme():
Expand All @@ -29,31 +23,16 @@ def ok():
pass


@lru_cache()
def ok():
pass


@functools.lru_cache(maxsize=64)
def ok():
pass


@lru_cache(maxsize=64)
def ok():
pass


def user_func():
pass


@lru_cache(user_func)
def ok():
pass


@lru_cache(user_func, maxsize=None)
@functools.lru_cache(user_func)
def ok():
pass

Expand Down
51 changes: 51 additions & 0 deletions crates/ruff/resources/test/fixtures/pyupgrade/UP033_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from functools import lru_cache


@lru_cache(maxsize=None)
def fixme():
pass


@other_decorator
@lru_cache(maxsize=None)
def fixme():
pass


@lru_cache(maxsize=None)
@other_decorator
def fixme():
pass


@lru_cache()
def ok():
pass


@lru_cache(maxsize=64)
def ok():
pass


def user_func():
pass


@lru_cache(user_func)
def ok():
pass


@lru_cache(user_func, maxsize=None)
def ok():
pass


def lru_cache(maxsize=None):
pass


@lru_cache(maxsize=None)
def ok():
pass
51 changes: 2 additions & 49 deletions crates/ruff/src/rules/pylint/rules/sys_exit_alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use rustpython_parser::ast::{Expr, ExprKind};

use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::scope::{BindingKind, FromImportation, Importation, SubmoduleImportation};
use ruff_python_ast::types::Range;

use crate::checkers::ast::Checker;
Expand All @@ -27,52 +26,6 @@ impl Violation for SysExitAlias {
}
}

/// Return the appropriate `sys.exit` reference based on the current set of
/// imports, or `None` is `sys.exit` hasn't been imported.
fn get_member_import_name_alias(checker: &Checker, module: &str, member: &str) -> Option<String> {
checker.ctx.scopes().find_map(|scope| {
scope
.binding_ids()
.find_map(|index| match &checker.ctx.bindings[*index].kind {
// e.g. module=sys object=exit
// `import sys` -> `sys.exit`
// `import sys as sys2` -> `sys2.exit`
BindingKind::Importation(Importation { name, full_name }) => {
if full_name == &module {
Some(format!("{name}.{member}"))
} else {
None
}
}
// e.g. module=os.path object=join
// `from os.path import join` -> `join`
// `from os.path import join as join2` -> `join2`
BindingKind::FromImportation(FromImportation { name, full_name }) => {
let mut parts = full_name.split('.');
if parts.next() == Some(module)
&& parts.next() == Some(member)
&& parts.next().is_none()
{
Some((*name).to_string())
} else {
None
}
}
// e.g. module=os.path object=join
// `import os.path ` -> `os.path.join`
BindingKind::SubmoduleImportation(SubmoduleImportation { full_name, .. }) => {
if full_name == &module {
Some(format!("{full_name}.{member}"))
} else {
None
}
}
// Non-imports.
_ => None,
})
})
}

/// PLR1722
pub fn sys_exit_alias(checker: &mut Checker, func: &Expr) {
let ExprKind::Name { id, .. } = &func.node else {
Expand All @@ -92,9 +45,9 @@ pub fn sys_exit_alias(checker: &mut Checker, func: &Expr) {
Range::from(func),
);
if checker.patch(diagnostic.kind.rule()) {
if let Some(content) = get_member_import_name_alias(checker, "sys", "exit") {
if let Some(binding) = checker.ctx.resolve_binding("sys", "exit") {
diagnostic.set_fix(Edit::replacement(
content,
binding,
func.location,
func.end_location.unwrap(),
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,18 @@ expression: diagnostics
row: 9
column: 8
parent: ~
- kind:
name: SysExitAlias
body: "Use `sys.exit()` instead of `quit`"
suggestion: "Replace `quit` with `sys.exit()`"
fixable: true
location:
row: 16
column: 4
end_location:
row: 16
column: 8
fix:
edits: []
parent: ~

3 changes: 2 additions & 1 deletion crates/ruff/src/rules/pyupgrade/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ mod tests {
#[test_case(Rule::PrintfStringFormatting, Path::new("UP031_0.py"); "UP031_0")]
#[test_case(Rule::PrintfStringFormatting, Path::new("UP031_1.py"); "UP031_1")]
#[test_case(Rule::FString, Path::new("UP032.py"); "UP032")]
#[test_case(Rule::LRUCacheWithMaxsizeNone, Path::new("UP033.py"); "UP033")]
#[test_case(Rule::LRUCacheWithMaxsizeNone, Path::new("UP033_0.py"); "UP033_0")]
#[test_case(Rule::LRUCacheWithMaxsizeNone, Path::new("UP033_1.py"); "UP033_1")]
#[test_case(Rule::ExtraneousParentheses, Path::new("UP034.py"); "UP034")]
#[test_case(Rule::DeprecatedImport, Path::new("UP035.py"); "UP035")]
#[test_case(Rule::OutdatedVersionBlock, Path::new("UP036_0.py"); "UP036_0")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use rustpython_parser::ast::{Constant, Expr, ExprKind, KeywordData};

use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::{create_expr, unparse_expr};
use ruff_python_ast::types::Range;

use crate::checkers::ast::Checker;
Expand Down Expand Up @@ -58,16 +57,9 @@ pub fn lru_cache_with_maxsize_none(checker: &mut Checker, decorator_list: &[Expr
Range::new(func.end_location.unwrap(), expr.end_location.unwrap()),
);
if checker.patch(diagnostic.kind.rule()) {
if let ExprKind::Attribute { value, ctx, .. } = &func.node {
if let Some(binding) = checker.ctx.resolve_binding("functools", "cache") {
diagnostic.set_fix(Edit::replacement(
unparse_expr(
&create_expr(ExprKind::Attribute {
value: value.clone(),
attr: "cache".to_string(),
ctx: ctx.clone(),
}),
checker.stylist,
),
binding,
expr.location,
expr.end_location.unwrap(),
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ expression: diagnostics
suggestion: "Rewrite with `@functools.cache"
fixable: true
location:
row: 5
row: 4
column: 20
end_location:
row: 5
row: 4
column: 34
fix:
edits:
- content: functools.cache
location:
row: 5
row: 4
column: 1
end_location:
row: 5
row: 4
column: 34
parent: ~
- kind:
Expand All @@ -30,32 +30,18 @@ expression: diagnostics
fixable: true
location:
row: 10
column: 10
end_location:
row: 10
column: 24
fix:
edits: []
parent: ~
- kind:
name: LRUCacheWithMaxsizeNone
body: "Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)`"
suggestion: "Rewrite with `@functools.cache"
fixable: true
location:
row: 16
column: 20
end_location:
row: 16
row: 10
column: 34
fix:
edits:
- content: functools.cache
location:
row: 16
row: 10
column: 1
end_location:
row: 16
row: 10
column: 34
parent: ~
- kind:
Expand All @@ -64,19 +50,19 @@ expression: diagnostics
suggestion: "Rewrite with `@functools.cache"
fixable: true
location:
row: 21
row: 15
column: 20
end_location:
row: 21
row: 15
column: 34
fix:
edits:
- content: functools.cache
location:
row: 21
row: 15
column: 1
end_location:
row: 21
row: 15
column: 34
parent: ~

Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
source: crates/ruff/src/rules/pyupgrade/mod.rs
expression: diagnostics
---
- kind:
name: LRUCacheWithMaxsizeNone
body: "Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)`"
suggestion: "Rewrite with `@functools.cache"
fixable: true
location:
row: 4
column: 10
end_location:
row: 4
column: 24
fix:
edits: []
parent: ~
- kind:
name: LRUCacheWithMaxsizeNone
body: "Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)`"
suggestion: "Rewrite with `@functools.cache"
fixable: true
location:
row: 10
column: 10
end_location:
row: 10
column: 24
fix:
edits: []
parent: ~
- kind:
name: LRUCacheWithMaxsizeNone
body: "Use `@functools.cache` instead of `@functools.lru_cache(maxsize=None)`"
suggestion: "Rewrite with `@functools.cache"
fixable: true
location:
row: 15
column: 10
end_location:
row: 15
column: 24
fix:
edits: []
parent: ~

0 comments on commit aed248b

Please sign in to comment.