-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[
refurb
] implement hardcoded-string-charset (FURB156)
- Loading branch information
Showing
9 changed files
with
474 additions
and
1 deletion.
There are no files selected for viewing
20 changes: 20 additions & 0 deletions
20
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,20 @@ | ||
# Errors | ||
|
||
_ = "0123456789" | ||
_ = "01234567" | ||
_ = "0123456789abcdefABCDEF" | ||
_ = "abcdefghijklmnopqrstuvwxyz" | ||
_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | ||
_ = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | ||
_ = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" | ||
_ = " \t\n\r\v\f" | ||
|
||
_ = "" in "1234567890" | ||
_ = "" in "12345670" | ||
_ = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' | ||
|
||
# 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
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
168 changes: 168 additions & 0 deletions
168
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,168 @@ | ||
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::{CmpOp, Expr, ExprStringLiteral, StringLike}; | ||
use ruff_text_size::{Ranged, 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 Charset { | ||
name: &'static str, | ||
bytes: &'static [u8], | ||
bitset: u128, | ||
} | ||
|
||
impl Charset { | ||
const fn new(name: &'static str, value: &'static str) -> Self { | ||
let bytes = value.as_bytes(); | ||
|
||
// let bitset = bytes.iter().fold(0, |acc, &byte| acc | (1 << byte)); | ||
// TODO: replace with ^ or for-loop, when these features will be supported in `const` fn | ||
// - https://github.com/rust-lang/rust/issues/67792 | ||
// - https://github.com/rust-lang/rust/issues/87575 | ||
let mut bitset = 0; | ||
let mut i = 0; | ||
while i < bytes.len() { | ||
bitset |= 1 << bytes[i]; | ||
i += 1; | ||
} | ||
|
||
Self { | ||
name, | ||
bytes, | ||
bitset, | ||
} | ||
} | ||
} | ||
|
||
const KNOWN_CHARSETS: [Charset; 9] = [ | ||
Charset::new( | ||
"ascii_letters", | ||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", | ||
), | ||
Charset::new("ascii_lowercase", "abcdefghijklmnopqrstuvwxyz"), | ||
Charset::new("ascii_uppercase", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), | ||
Charset::new("digits", "0123456789"), | ||
Charset::new("hexdigits", "0123456789abcdefABCDEF"), | ||
Charset::new("octdigits", "01234567"), | ||
Charset::new("punctuation", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"), | ||
Charset::new( | ||
"printable", | ||
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"\ | ||
#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c", | ||
), | ||
Charset::new("whitespace", " \t\n\r\x0b\x0c"), | ||
]; | ||
|
||
fn check_charset_as_set(s: &str) -> Option<&Charset> { | ||
if !s.is_ascii() { | ||
return None; | ||
} | ||
let bitset = s | ||
.as_bytes() | ||
.iter() | ||
.try_fold(0, |acc, &byte| (byte < 128).then(|| acc | (1_u128 << byte)))?; | ||
|
||
KNOWN_CHARSETS | ||
.iter() | ||
.find(|&charset| charset.bitset == bitset) | ||
} | ||
|
||
fn check_charset_exact(bytes: &[u8]) -> Option<&Charset> { | ||
KNOWN_CHARSETS | ||
.iter() | ||
.find(|&charset| charset.bytes == bytes) | ||
} | ||
|
||
fn push_diagnostic(checker: &mut Checker, range: TextRange, charset: &Charset) { | ||
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, | ||
ops: &[CmpOp], | ||
comparators: &[Expr], | ||
) { | ||
let ([op], [comp]) = (ops, comparators) else { | ||
return; | ||
}; | ||
if !matches!(op, CmpOp::In | CmpOp::NotIn) { | ||
return; | ||
} | ||
let Expr::StringLiteral(ExprStringLiteral { value, .. }) = comp else { | ||
return; | ||
}; | ||
let Some(charset) = check_charset_as_set(value.to_str()) else { | ||
return; | ||
}; | ||
|
||
// In this case the diagnostic will be emitted via string_like check. | ||
if check_charset_exact(value.to_str().as_bytes()).is_some() { | ||
return; | ||
} | ||
|
||
push_diagnostic(checker, comp.range(), charset); | ||
} | ||
|
||
/// FURB156 | ||
pub(crate) fn hardcoded_string_charset_literal(checker: &mut Checker, string_like: StringLike) { | ||
let StringLike::String(expr) = string_like else { | ||
return; | ||
}; | ||
let Some(charset) = check_charset_exact(expr.value.to_str().as_bytes()) else { | ||
return; | ||
}; | ||
push_diagnostic(checker, string_like.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.