Skip to content

Commit

Permalink
Ensure format specifiers are valid when checking for f-string syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
snowsignal committed Feb 2, 2024
1 parent f39a956 commit 9d4336e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use memchr::memchr2_iter;
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast};
use ruff_python_literal::format::FormatSpec;
use ruff_python_parser::parse_expression;
use ruff_python_semantic::SemanticModel;
use ruff_source_file::Locator;
Expand Down Expand Up @@ -125,6 +126,12 @@ pub(super) fn should_be_fstring(
}
has_name = true;
}
if let Some(spec) = &element.format_spec {
let spec = locator.slice(spec.range());
if FormatSpec::parse(spec).is_err() {
return false;
}
}
}
if !has_name {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ RUF027.py:48:9: RUF027 [*] Possible f-string without an `f` prefix
47 | a = 4
48 | b = "{a}" "+" "{b}" r" \\ " # RUF027 for the first part only
| ^^^^^ RUF027
49 | print(f"{a}" "{a}" f"{b}")
49 | print(f"{a}" "{a}" f"{b}") # RUF027
|
= help: Add an `f` prefix to the f-string

Expand All @@ -251,15 +251,15 @@ RUF027.py:48:9: RUF027 [*] Possible f-string without an `f` prefix
47 47 | a = 4
48 |- b = "{a}" "+" "{b}" r" \\ " # RUF027 for the first part only
48 |+ b = f"{a}" "+" "{b}" r" \\ " # RUF027 for the first part only
49 49 | print(f"{a}" "{a}" f"{b}")
49 49 | print(f"{a}" "{a}" f"{b}") # RUF027
50 50 |
51 51 | def escaped_chars():

RUF027.py:49:18: RUF027 [*] Possible f-string without an `f` prefix
|
47 | a = 4
48 | b = "{a}" "+" "{b}" r" \\ " # RUF027 for the first part only
49 | print(f"{a}" "{a}" f"{b}")
49 | print(f"{a}" "{a}" f"{b}") # RUF027
| ^^^^^ RUF027
50 |
51 | def escaped_chars():
Expand All @@ -270,8 +270,8 @@ RUF027.py:49:18: RUF027 [*] Possible f-string without an `f` prefix
46 46 | def implicit_concat():
47 47 | a = 4
48 48 | b = "{a}" "+" "{b}" r" \\ " # RUF027 for the first part only
49 |- print(f"{a}" "{a}" f"{b}")
49 |+ print(f"{a}" f"{a}" f"{b}")
49 |- print(f"{a}" "{a}" f"{b}") # RUF027
49 |+ print(f"{a}" f"{a}" f"{b}") # RUF027
50 50 |
51 51 | def escaped_chars():
52 52 | a = 4
Expand Down

0 comments on commit 9d4336e

Please sign in to comment.