-
Notifications
You must be signed in to change notification settings - Fork 899
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
[refurb
] New rule to suggest min/max over sorted() (FURB192
)
#10868
Merged
charliermarsh
merged 32 commits into
astral-sh:main
from
ottaviohartman:thartman/furb192
Apr 23, 2024
Merged
Changes from 24 commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
9320b66
init
ottaviohartman c3813a3
first stab
ottaviohartman 0e94732
impl nearly done
ottaviohartman 129ef99
impl nearly done
ottaviohartman 928b3bc
compiling
ottaviohartman 8e84731
refactor
ottaviohartman 5be22a4
is_reversed
ottaviohartman 5e073fd
simplification
ottaviohartman 6d73582
update py
ottaviohartman 8af13c6
working
ottaviohartman 3519d24
fmt
ottaviohartman cf59390
clippy
ottaviohartman b0f0384
reverse edge case
ottaviohartman 2140e17
basic cases working
ottaviohartman b212e87
updated rules
ottaviohartman e10e15a
add snap
ottaviohartman 2dcd134
Merge branch 'main' of github.com:astral-sh/ruff into thartman/furb192
ottaviohartman bec8502
generate schema
ottaviohartman 7fe30b4
add docs
ottaviohartman 22fae02
another test
ottaviohartman b73e47c
cleanup
ottaviohartman f8df98a
another test
ottaviohartman 2b3db42
fix list expr
ottaviohartman 02f754e
Merge branch 'main' of github.com:astral-sh/ruff into thartman/furb192
ottaviohartman a5be688
crashign
ottaviohartman 049dd85
increase size of bitset array
ottaviohartman eb6462b
clippy
ottaviohartman e804774
Merge branch 'main' of github.com:astral-sh/ruff into thartman/furb192
ottaviohartman 850faaa
rename is_builtin
ottaviohartman e659492
Merge branch 'main' into thartman/furb192
charliermarsh 96a5536
Rebase; reformat
charliermarsh da36bfc
Minor tweaks
charliermarsh File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
crates/ruff_linter/resources/test/fixtures/refurb/FURB192.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
# Errors | ||
|
||
sorted(l)[0] | ||
|
||
sorted(l)[-1] | ||
|
||
sorted(l, reverse=True)[0] | ||
|
||
sorted(l, reverse=True)[-1] | ||
|
||
sorted(l, reverse=False)[-1] | ||
|
||
sorted(l, key=lambda x: x)[0] | ||
|
||
sorted(l, key=key_fn, reverse=True)[-1] | ||
|
||
sorted(l, key=key_fn)[0] | ||
|
||
sorted([1, 2, 3])[0] | ||
|
||
# Non-errors | ||
|
||
sorted(l, reverse=foo())[0] | ||
|
||
sorted(l)[1] | ||
|
||
sorted(get_list())[1] | ||
|
||
sorted()[0] | ||
|
||
sorted(l)[1] | ||
|
||
sorted(l)[-2] | ||
|
||
b = True | ||
|
||
sorted(l, reverse=b)[0] | ||
|
||
sorted(l, invalid_kwarg=True)[0] | ||
|
||
def sorted(): | ||
pass | ||
|
||
sorted(l)[0] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
204 changes: 204 additions & 0 deletions
204
crates/ruff_linter/src/rules/refurb/rules/sorted_min_max.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,204 @@ | ||
use ruff_diagnostics::Diagnostic; | ||
use ruff_diagnostics::Edit; | ||
use ruff_diagnostics::Fix; | ||
use ruff_diagnostics::FixAvailability; | ||
use ruff_diagnostics::Violation; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_python_ast::{self as ast, Expr}; | ||
|
||
use crate::checkers::ast::Checker; | ||
use ruff_python_ast::Number; | ||
use ruff_text_size::Ranged; | ||
|
||
/// ## What it does | ||
/// Checks for uses of `sorted()` to get the min and max values of a list. | ||
/// | ||
/// ## Why is this bad? | ||
/// Using `sorted()` to get the min and max values of a list is inefficient. | ||
/// | ||
/// ## Example | ||
/// ```python | ||
/// nums = [3, 1, 4, 1, 5] | ||
/// lowest = sorted(nums)[0] | ||
/// highest = sorted(nums)[-1] | ||
/// highest = sorted(nums, reverse=True)[0] | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// nums = [3, 1, 4, 1, 5] | ||
/// lowest = min(nums) | ||
/// highest = max(nums) | ||
/// ``` | ||
/// | ||
/// ## Note | ||
/// | ||
/// If the original statement uses `reverse=True`, the `min` and `max` replacement will not | ||
/// be equivalent if the intended result is to get a non-stable min and max. | ||
/// | ||
/// In other words, `sorted(data, key=itemgetter(0), reverse=True)[0]` is not a stable min, | ||
/// but `min(data, key=itemgetter(0))` is a stable min. | ||
/// | ||
/// ## References | ||
/// - [Python documentation: `min`](https://docs.python.org/3/library/functions.html#min) | ||
/// - [Python documentation: `max`](https://docs.python.org/3/library/functions.html#max) | ||
#[violation] | ||
pub struct SortedMinMax; | ||
|
||
impl Violation for SortedMinMax { | ||
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always; | ||
|
||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
format!("Prefer `min` or `max` over `sorted()` to get the min and max values of a list") | ||
} | ||
|
||
fn fix_title(&self) -> Option<String> { | ||
Some(format!("Replace with `min` or `max`")) | ||
} | ||
} | ||
|
||
/// FURB192 | ||
pub(crate) fn sorted_min_max(checker: &mut Checker, subscript: &ast::ExprSubscript) { | ||
if subscript.ctx.is_store() || subscript.ctx.is_del() { | ||
return; | ||
} | ||
|
||
let ast::ExprSubscript { slice, value, .. } = &subscript; | ||
|
||
// Early return if index is not unary or a number literal. | ||
if !(slice.is_number_literal_expr() || slice.is_unary_op_expr()) { | ||
return; | ||
} | ||
|
||
let Expr::Call(ast::ExprCall { | ||
func, arguments, .. | ||
}) = value.as_ref() | ||
else { | ||
return; | ||
}; | ||
|
||
// Check if the value is a call to `sorted()`. | ||
if !matches!(func.as_ref(), Expr::Name(name) if name.id == "sorted" && checker.semantic().is_builtin(name.id.as_str())) | ||
{ | ||
return; | ||
}; | ||
|
||
let index = match slice.as_ref() { | ||
// [0] | ||
Expr::NumberLiteral(ast::ExprNumberLiteral { | ||
value: Number::Int(index), | ||
.. | ||
}) if *index == 0 => Index::First, | ||
|
||
// [-1] | ||
Expr::UnaryOp(ast::ExprUnaryOp { | ||
op: ast::UnaryOp::USub, | ||
operand, | ||
.. | ||
}) => { | ||
match operand.as_ref() { | ||
// [-1] | ||
Expr::NumberLiteral(ast::ExprNumberLiteral { | ||
value: Number::Int(index), | ||
.. | ||
}) if *index == 1 => Index::Last, | ||
_ => return, | ||
} | ||
} | ||
_ => return, | ||
}; | ||
|
||
let mut reverse_keyword = None; | ||
let mut key_keyword_expr = None; | ||
|
||
// Check if the call to `sorted()` has the `reverse` and `key` keywords. | ||
for keyword in arguments.keywords.iter() { | ||
if reverse_keyword.is_none() | ||
&& keyword | ||
.arg | ||
.as_ref() | ||
.map_or(false, |arg| arg.as_str() == "reverse") | ||
{ | ||
reverse_keyword = Some(keyword); | ||
} else if key_keyword_expr.is_none() | ||
&& keyword | ||
.arg | ||
.as_ref() | ||
.map_or(false, |arg| arg.as_str() == "key") | ||
{ | ||
key_keyword_expr = Some(&keyword.value); | ||
} else { | ||
// If unexpected keyword is found, return. | ||
return; | ||
} | ||
} | ||
|
||
let is_reversed = if let Some(reverse_keyword) = reverse_keyword { | ||
match reverse_keyword.value.as_boolean_literal_expr() { | ||
Some(ast::ExprBooleanLiteral { value, .. }) => *value, | ||
// If the value is not a boolean literal, we can't determine if it is reversed. | ||
_ => return, | ||
} | ||
} else { | ||
// No reverse keyword, so it is not reversed. | ||
false | ||
}; | ||
|
||
let min_max = match (index, is_reversed) { | ||
(Index::First, false) => MinMax::Min, | ||
(Index::First, true) => MinMax::Max, | ||
(Index::Last, false) => MinMax::Max, | ||
(Index::Last, true) => MinMax::Min, | ||
}; | ||
|
||
let Some(list_expr) = arguments.args.first() else { | ||
return; | ||
}; | ||
|
||
let replacement = if let Some(key) = &key_keyword_expr { | ||
format!( | ||
"{}({}, key={})", | ||
min_max.as_str(), | ||
checker.generator().expr(list_expr), | ||
checker.generator().expr(key) | ||
) | ||
} else { | ||
format!( | ||
"{}({})", | ||
min_max.as_str(), | ||
checker.generator().expr(list_expr) | ||
) | ||
}; | ||
|
||
let mut diagnostic = Diagnostic::new(SortedMinMax, subscript.range()); | ||
diagnostic.set_fix(Fix::safe_edit(Edit::replacement( | ||
replacement, | ||
subscript.start(), | ||
subscript.end(), | ||
))); | ||
checker.diagnostics.push(diagnostic); | ||
} | ||
|
||
#[derive(Debug, Copy, Clone, PartialEq, Eq)] | ||
enum MinMax { | ||
Min, | ||
Max, | ||
} | ||
|
||
impl MinMax { | ||
fn as_str(self) -> &'static str { | ||
match self { | ||
Self::Min => "min", | ||
Self::Max => "max", | ||
} | ||
} | ||
} | ||
|
||
#[derive(Debug, Copy, Clone, PartialEq, Eq)] | ||
enum Index { | ||
// 0 | ||
First, | ||
// -1 | ||
Last, | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there a cleaner or more canonical way to generate this?