Skip to content

Commit

Permalink
[red-knot] Do not panic on f-string format spec expressions
Browse files Browse the repository at this point in the history
Previously, we panicked on expressions like `f"{v:{f'0.2f'}}"` because
we did not infer types for expressions nested inside format spec
elements.
  • Loading branch information
sharkdp committed Nov 18, 2024
1 parent 3642381 commit b884b0a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
11 changes: 10 additions & 1 deletion crates/red_knot_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2289,7 +2289,16 @@ impl<'db> TypeInferenceBuilder<'db> {
// (`Type::format`?) that handles the `__format__` method.
// Conversion flags should be handled before calling `__format__`.
// https://docs.python.org/3/library/string.html#format-string-syntax
if !conversion.is_none() || format_spec.is_some() {
if !conversion.is_none() {
collector.add_expression();
} else if let Some(ref format_spec) = format_spec {
for element in &format_spec.elements {
if let ast::FStringElement::Expression(expression) = element
{
self.infer_expression(&expression.expression);
}
}

collector.add_expression();
} else {
if let Type::StringLiteral(literal) = ty.str(self.db) {
Expand Down
2 changes: 0 additions & 2 deletions crates/red_knot_workspace/tests/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,7 @@ const KNOWN_FAILURES: &[(&str, bool, bool)] = &[
("crates/ruff_linter/resources/test/fixtures/pyflakes/F821_20.py", true, true),
("crates/ruff_linter/resources/test/fixtures/pyflakes/F821_26.py", true, false),
// Fails for unknown reasons:
("crates/ruff_linter/resources/test/fixtures/pyflakes/F541.py", true, true),
("crates/ruff_linter/resources/test/fixtures/pyflakes/F632.py", true, true),
("crates/ruff_linter/resources/test/fixtures/pyflakes/F811_19.py", true, false),
("crates/ruff_linter/resources/test/fixtures/pyupgrade/UP039.py", true, false),
("crates/ruff_python_parser/resources/valid/expressions/f_string.py", true, true),
];

0 comments on commit b884b0a

Please sign in to comment.