ruff
d23b7e88 - [`pylint`] Fix false positives and negatives with `%b` format character (`PLE1300`, `PLE1307`) (#27560)

Commit
1 day ago
[`pylint`] Fix false positives and negatives with `%b` format character (`PLE1300`, `PLE1307`) (#27560) ## Summary Noticed case below with possible false positive/negative when handling `%b` format character by rules https://docs.astral.sh/ruff/rules/bad-string-format-character/ and https://docs.astral.sh/ruff/rules/bad-string-format-type/ ```python # False negative: not flagged by bad-string-format-character # Runtime: ValueError: unsupported format character 'b' (0x62) at index 7 a = "hello %b" % 25 # False positive: bad-string-format-type # Runtime: ValueError: unsupported format character 'b' (0x62) at index 7 # It should report nothing, since the problem is not mismatching # formatter and provided value, but use of invalid format character in general. a = "hello %b" % "23" ``` This fix resolves both issues - first case is now reported and second results in no diagnostic. The root cause for was `bad-string-format-character` issue was `CFormatString` parser always parsing `%b` as `Bytes` type, while for bytes literals it's actually just an invalid character. Added `CFormatContext` enum, so parser can parse `%b` only when invoked from `CFormatBytes` and not from `CFormatString` and report issue when finds `%b` in string literals formatters. Second issue was caused by `bad-string-format-type` assuming `%b` is allowed only for integers, so it was reporting any other type as a mismatch. Now it just ignores `%b`, since it will be handled by `bad-string-format-character`. https://github.com/astral-sh/ruff/blob/17a00de2e298612201a8fe30790e9399204af1b9/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_type.rs#L100 For completeness I also refactored `FormatType::from` in that rule to rely on `CFormatType` variants instead of hardcoding formatter characters It really just made it more clean without any functional changes: - `Ascii` is now handled explicitly as `Repr`, instead of assuming it's unknown - dropped non-existing formatters `n` and `%`, they are present from the original implementation https://github.com/astral-sh/ruff/pull/2572 and are not valid formatters (possibly `%` is artifact from old cformat parser quirks). ## Test Plan Added tests for both rules, updated snapshots. All previous tests pass too.
Author
Parents
Loading