Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add support for nested replacements inside format specifications (#6616)
Closes #6442 Python string formatting like `"hello {place}".format(place="world")` supports format specifications for replaced content such as `"hello {place:>10}".format(place="world")` which will align the text to the right in a container filled up to ten characters. Ruff parses formatted strings into `FormatPart`s each of which is either a `Field` (content in `{...}`) or a `Literal` (the normal content). Fields are parsed into name and format specifier sections (we'll ignore conversion specifiers for now). There are a myriad of specifiers that can be used in a `FormatSpec`. Unfortunately for linters, the specifier values can be dynamically set. For example, `"hello {place:{align}{width}}".format(place="world", align=">", width=10)` and `"hello {place:{fmt}}".format(place="world", fmt=">10")` will yield the same string as before but variables can be used to determine the formatting. In this case, when parsing the format specifier we can't know what _kind_ of specifier is being used as their meaning is determined by both position and value. Ruff does not support nested replacements and our current data model does not support the concept. Here the data model is updated to support this concept, although linting of specifications with replacements will be inherently limited. We could split format specifications into two types, one without any replacements that we can perform lints with and one with replacements that we cannot inspect. However, it seems excessive to drop all parsing of format specifiers due to the presence of a replacement. Instead, I've opted to parse replacements eagerly and ignore their possible effect on other format specifiers. This will allow us to retain a simple interface for `FormatSpec` and most syntax checks. We may need to add some handling to relax errors if a replacement was seen previously. It's worth noting that the nested replacement _can_ also include a format specification although it may fail at runtime if you produce an invalid outer format specification. For example, `"hello {place:{fmt:<2}}".format(place="world", fmt=">10")` is valid so we need to represent each nested replacement as a full `FormatPart`. ## Test plan Adding unit tests for `FormatSpec` parsing and snapshots for PLE1300
- Loading branch information