-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
] implement hardcoded-string-charset
(FURB156)
#13530
Open
alex-700
wants to merge
3
commits into
astral-sh:main
Choose a base branch
from
alex-700:latyshev/furb-156
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+615
−1
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
crates/ruff_linter/resources/test/fixtures/refurb/FURB156.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,31 @@ | ||
# Errors | ||
|
||
_ = "0123456789" | ||
_ = "01234567" | ||
_ = "0123456789abcdefABCDEF" | ||
_ = "abcdefghijklmnopqrstuvwxyz" | ||
_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | ||
_ = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | ||
_ = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" | ||
_ = " \t\n\r\v\f" | ||
|
||
_ = "" in "1234567890" | ||
_ = "" in "12345670" | ||
_ = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' | ||
_ = ( | ||
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&' | ||
"'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c" | ||
) | ||
_ = id("0123" | ||
"4567" | ||
"89") | ||
_ = "" in ("123" | ||
"456" | ||
"789" | ||
"0") | ||
|
||
# Ok | ||
|
||
_ = "1234567890" | ||
_ = "1234" | ||
_ = "" in "1234" |
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
197 changes: 197 additions & 0 deletions
197
crates/ruff_linter/src/rules/refurb/rules/hardcoded_string_charset.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,197 @@ | ||
use crate::checkers::ast::Checker; | ||
use crate::importer::ImportRequest; | ||
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_python_ast::parenthesize::parenthesized_range; | ||
use ruff_python_ast::{CmpOp, Expr, ExprCall, ExprCompare, ExprStringLiteral}; | ||
use ruff_text_size::TextRange; | ||
|
||
/// ## What it does | ||
/// Checks for uses of hardcoded charsets, which are defined in Python string module. | ||
/// | ||
/// ## Why is this bad? | ||
/// Usage of named charsets from the standard library is more readable and less error-prone. | ||
/// | ||
/// ## Example | ||
/// ```python | ||
/// x = "0123456789" | ||
/// y in "abcdefghijklmnopqrstuvwxyz" | ||
/// ``` | ||
/// | ||
/// Use instead | ||
/// ```python | ||
/// import string | ||
/// | ||
/// x = string.digits | ||
/// y in string.ascii_lowercase | ||
/// ``` | ||
/// | ||
/// ## References | ||
/// - [Python documentation: String constants](https://docs.python.org/3/library/string.html#string-constants) | ||
#[violation] | ||
pub struct HardcodedStringCharset { | ||
name: &'static str, | ||
} | ||
|
||
impl AlwaysFixableViolation for HardcodedStringCharset { | ||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
format!("Use of hardcoded string charset") | ||
} | ||
|
||
fn fix_title(&self) -> String { | ||
let HardcodedStringCharset { name } = self; | ||
format!("Replace hardcoded charset with `string.{name}`") | ||
} | ||
} | ||
|
||
struct NamedCharset { | ||
name: &'static str, | ||
bytes: &'static [u8], | ||
ascii_char_set: AsciiCharSet, | ||
} | ||
|
||
/// Represents the set of ascii characters in form of a bitset. | ||
#[derive(Copy, Clone, Eq, PartialEq)] | ||
struct AsciiCharSet(u128); | ||
|
||
impl AsciiCharSet { | ||
/// Creates the set of ascii characters from `bytes`. | ||
/// Returns None if there is non-ascii byte. | ||
const fn from_bytes(bytes: &[u8]) -> Option<Self> { | ||
// TODO: simplify implementation, when const-traits are supported | ||
// https://github.com/rust-lang/rust-project-goals/issues/106 | ||
let mut bitset = 0; | ||
let mut i = 0; | ||
while i < bytes.len() { | ||
if !bytes[i].is_ascii() { | ||
return None; | ||
} | ||
bitset |= 1 << bytes[i]; | ||
MichaReiser marked this conversation as resolved.
Show resolved
Hide resolved
|
||
i += 1; | ||
} | ||
Some(Self(bitset)) | ||
} | ||
} | ||
|
||
impl NamedCharset { | ||
const fn new(name: &'static str, bytes: &'static [u8]) -> Self { | ||
Self { | ||
name, | ||
bytes, | ||
// SAFETY: The named charset is guaranteed to have only ascii bytes. | ||
// TODO: replace with `.unwrap()`, when `Option::unwrap` will be stable in `const fn` | ||
// https://github.com/rust-lang/rust/issues/67441 | ||
ascii_char_set: match AsciiCharSet::from_bytes(bytes) { | ||
Some(ascii_char_set) => ascii_char_set, | ||
None => unreachable!(), | ||
}, | ||
} | ||
} | ||
} | ||
|
||
const KNOWN_NAMED_CHARSETS: [NamedCharset; 9] = [ | ||
NamedCharset::new( | ||
"ascii_letters", | ||
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", | ||
), | ||
NamedCharset::new("ascii_lowercase", b"abcdefghijklmnopqrstuvwxyz"), | ||
NamedCharset::new("ascii_uppercase", b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"), | ||
NamedCharset::new("digits", b"0123456789"), | ||
NamedCharset::new("hexdigits", b"0123456789abcdefABCDEF"), | ||
NamedCharset::new("octdigits", b"01234567"), | ||
NamedCharset::new("punctuation", b"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"), | ||
NamedCharset::new( | ||
"printable", | ||
b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"\ | ||
#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c", | ||
), | ||
NamedCharset::new("whitespace", b" \t\n\r\x0b\x0c"), | ||
]; | ||
|
||
fn check_charset_as_set(bytes: &[u8]) -> Option<&NamedCharset> { | ||
let ascii_char_set = AsciiCharSet::from_bytes(bytes)?; | ||
|
||
KNOWN_NAMED_CHARSETS | ||
.iter() | ||
.find(|&charset| charset.ascii_char_set == ascii_char_set) | ||
} | ||
|
||
fn check_charset_exact(bytes: &[u8]) -> Option<&NamedCharset> { | ||
KNOWN_NAMED_CHARSETS | ||
.iter() | ||
.find(|&charset| charset.bytes == bytes) | ||
} | ||
|
||
fn push_diagnostic(checker: &mut Checker, range: TextRange, charset: &NamedCharset) { | ||
let name = charset.name; | ||
let mut diagnostic = Diagnostic::new(HardcodedStringCharset { name }, range); | ||
diagnostic.try_set_fix(|| { | ||
let (edit, binding) = checker.importer().get_or_import_symbol( | ||
&ImportRequest::import("string", name), | ||
range.start(), | ||
checker.semantic(), | ||
)?; | ||
Ok(Fix::safe_edits( | ||
Edit::range_replacement(binding, range), | ||
[edit], | ||
)) | ||
}); | ||
checker.diagnostics.push(diagnostic); | ||
} | ||
|
||
/// FURB156 | ||
pub(crate) fn hardcoded_string_charset_comparison(checker: &mut Checker, compare: &ExprCompare) { | ||
let ( | ||
[CmpOp::In | CmpOp::NotIn], | ||
[Expr::StringLiteral(string_literal @ ExprStringLiteral { value, .. })], | ||
) = (compare.ops.as_ref(), compare.comparators.as_ref()) | ||
else { | ||
return; | ||
}; | ||
|
||
let bytes = value.to_str().as_bytes(); | ||
|
||
let Some(charset) = check_charset_as_set(bytes) else { | ||
return; | ||
}; | ||
|
||
// In this case the diagnostic will be emitted via string_literal check. | ||
if charset.bytes == bytes { | ||
return; | ||
} | ||
|
||
let range = parenthesized_range( | ||
string_literal.into(), | ||
compare.into(), | ||
checker.comment_ranges(), | ||
checker.locator().contents(), | ||
) | ||
.unwrap_or(string_literal.range); | ||
|
||
push_diagnostic(checker, range, charset); | ||
} | ||
|
||
/// FURB156 | ||
pub(crate) fn hardcoded_string_charset_literal(checker: &mut Checker, expr: &ExprStringLiteral) { | ||
if let Some(charset) = check_charset_exact(expr.value.to_str().as_bytes()) { | ||
let range = parenthesized_range( | ||
expr.into(), | ||
checker.semantic().current_expression_parent().map_or_else( | ||
|| checker.semantic().current_statement().into(), | ||
|parent| { | ||
if let Expr::Call(ExprCall { arguments, .. }) = parent { | ||
arguments.into() | ||
} else { | ||
parent.into() | ||
} | ||
}, | ||
), | ||
checker.comment_ranges(), | ||
checker.locator().contents(), | ||
) | ||
.unwrap_or(expr.range); | ||
|
||
push_diagnostic(checker, range, charset); | ||
} | ||
} |
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
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.
Could you add a test for a case where the string is parenthesized
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.
066e700
I added the test and "took a look" on
parenthesized_range
, but its usage was really not intuitive for me in that special case. Could I somehow simplify "getting the parent" here?