Skip to content

Fix bad-string-format-character when a placeholder occurs within a format spec part #6773

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

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@

"{:*^30s}".format("centered") # OK
"{:{s}}".format("hello", s="s") # OK (nested replacement value not checked)

"{:{s:y}}".format("hello", s="s") # [bad-format-character] (nested replacement format spec checked)
"{0:.{prec}g}".format(1.23, prec=15) # OK
"{0:.{foo}x{bar}y{foobar}g}".format(...) # OK (all nested replacements are consumed without considering in between chars)
"{0:.{foo}{bar}{foobar}y}".format(...) # [bad-format-character] (check value after replacements)

## f-strings

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,24 @@ bad_string_format_character.py:15:1: PLE1300 Unsupported format character 'y'
17 | "{:*^30s}".format("centered") # OK
|

bad_string_format_character.py:20:1: PLE1300 Unsupported format character 'y'
bad_string_format_character.py:19:1: PLE1300 Unsupported format character 'y'
|
17 | "{:*^30s}".format("centered") # OK
18 | "{:{s}}".format("hello", s="s") # OK (nested replacement value not checked)
19 |
20 | "{:{s:y}}".format("hello", s="s") # [bad-format-character] (nested replacement format spec checked)
19 | "{:{s:y}}".format("hello", s="s") # [bad-format-character] (nested replacement format spec checked)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PLE1300
21 |
22 | ## f-strings
20 | "{0:.{prec}g}".format(1.23, prec=15) # OK
21 | "{0:.{foo}x{bar}y{foobar}g}".format(...) # OK (all nested replacements are consumed without considering in between chars)
|

bad_string_format_character.py:22:1: PLE1300 Unsupported format character 'y'
|
20 | "{0:.{prec}g}".format(1.23, prec=15) # OK
21 | "{0:.{foo}x{bar}y{foobar}g}".format(...) # OK (all nested replacements are consumed without considering in between chars)
22 | "{0:.{foo}{bar}{foobar}y}".format(...) # [bad-format-character] (check value after replacements)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PLE1300
23 |
24 | ## f-strings
|


36 changes: 31 additions & 5 deletions crates/ruff_python_literal/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,26 +318,52 @@ fn parse_precision(text: &str) -> Result<(Option<usize>, &str), FormatSpecError>
})
}

/// Parses a format part within a format spec
/// Parses a placeholder within a format spec
fn parse_nested_placeholder<'a>(
parts: &mut Vec<FormatPart>,
placeholders: &mut Vec<FormatPart>,
text: &'a str,
) -> Result<&'a str, FormatSpecError> {
match FormatString::parse_spec(text, AllowPlaceholderNesting::No) {
// Not a nested replacement, OK
Err(FormatParseError::MissingStartBracket) => Ok(text),
Err(err) => Err(FormatSpecError::InvalidPlaceholder(err)),
Ok((format_part, text)) => {
parts.push(format_part);
placeholders.push(format_part);
Ok(text)
}
}
}

/// Parse and consume all placeholders in a format spec
///
/// This will also consume any intermediate characters such as `x` and `y` in
/// ```
/// "x{foo}y{bar}z"
/// ```
fn consume_all_placeholders<'a>(
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The following implementation is a little clunky. I'm guessing there's a more idiomatic way to do this?

placeholders: &mut Vec<FormatPart>,
text: &'a str,
) -> Result<&'a str, FormatSpecError> {
let mut chars = text.chars();
let mut text = text;
let mut placeholder_count = placeholders.len();

while chars.clone().contains(&'{') {
text = parse_nested_placeholder(placeholders, chars.as_str())?;
chars = text.chars();
// If we did not parse a placeholder, consume a character
if placeholder_count == placeholders.len() {
chars.next();
} else {
placeholder_count = placeholders.len();
}
}
Ok(text)
}

impl FormatSpec {
pub fn parse(text: &str) -> Result<Self, FormatSpecError> {
let mut replacements = vec![];
// get_integer in CPython
let text = parse_nested_placeholder(&mut replacements, text)?;
let (conversion, text) = FormatConversion::parse(text);
let text = parse_nested_placeholder(&mut replacements, text)?;
Expand All @@ -354,7 +380,7 @@ impl FormatSpec {
let (grouping_option, text) = FormatGrouping::parse(text);
let text = parse_nested_placeholder(&mut replacements, text)?;
let (precision, text) = parse_precision(text)?;
let text = parse_nested_placeholder(&mut replacements, text)?;
let text = consume_all_placeholders(&mut replacements, text)?;

let (format_type, _text) = if text.is_empty() {
(None, text)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
is_async: false,
items: [
WithItem {
range: 239..243,
range: 239..240,
context_expr: Constant(
ExprConstant {
range: 239..240,
Expand All @@ -490,7 +490,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
optional_vars: None,
},
WithItem {
range: 239..243,
range: 242..243,
context_expr: Constant(
ExprConstant {
range: 242..243,
Expand Down