Avoid panic when comment is preceded by Unicode (#9331)

Closes https://github.com/astral-sh/ruff/issues/9328.
This commit is contained in:
Charlie Marsh 2023-12-31 08:54:31 -04:00 committed by GitHub
parent 1c9268d2ff
commit 003851c41d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 4 deletions

View File

@ -51,3 +51,8 @@ x = 1
#
##
#
# This should be removed.
α = 1
α#

View File

@ -88,10 +88,13 @@ fn empty_comment(range: TextRange, locator: &Locator) -> Option<Diagnostic> {
.slice(TextRange::new(line.start(), first_hash_col))
.char_indices()
.rev()
.find(|&(_, c)| !is_python_whitespace(c) && c != '#')
.map(|(last_non_whitespace_non_comment_col, _)| {
// SAFETY: (last_non_whitespace_non_comment_col + 1) <= first_hash_col
TextSize::try_from(last_non_whitespace_non_comment_col).unwrap() + TextSize::new(1)
.find_map(|(index, char)| {
if is_python_whitespace(char) || char == '#' {
None
} else {
// SAFETY: <= first_hash_col
Some(TextSize::try_from(index + char.len_utf8()).unwrap())
}
});
Some(

View File

@ -115,4 +115,19 @@ empty_comment.py:45:1: PLR2044 [*] Line with empty comment
47 46 | # These should also be removed.
48 47 |
empty_comment.py:58:2: PLR2044 [*] Line with empty comment
|
57 | α = 1
58 | α#
| ^ PLR2044
|
= help: Delete the empty comment
Safe fix
55 55 | # This should be removed.
56 56 |
57 57 | α = 1
58 |-α#
58 |+α