refactor(fstring): make whole decimal spec optional

This commit is contained in:
2026-02-07 23:23:56 +01:00
parent c09f749284
commit 017df98297
3 changed files with 13 additions and 9 deletions

View File

@@ -86,7 +86,7 @@ class FormatSpecParser:
def number(self) -> FormatSpecNumber:
integral: FormatSpecIntegral = self.integral()
decimal: FormatSpecDecimal = self.decimal()
decimal: Optional[FormatSpecDecimal] = self.decimal()
return FormatSpecNumber(integral=integral, decimal=decimal)
def integral(self) -> FormatSpecIntegral:
@@ -101,15 +101,18 @@ class FormatSpecParser:
grouping=grouping
)
def decimal(self) -> FormatSpecDecimal:
def decimal(self) -> Optional[FormatSpecDecimal]:
if not self.match(TokenType.DOT):
return None
dot: Token = self.previous()
precision: Optional[int] = None
grouping: Optional[Token] = None
if self.match(TokenType.DOT):
if self.match(TokenType.NUMBER):
precision = self.previous().value
if self.match(TokenType.COMMA, TokenType.UNDERSCORE):
grouping = self.previous()
if self.match(TokenType.NUMBER):
precision = self.previous().value
if self.match(TokenType.COMMA, TokenType.UNDERSCORE):
grouping = self.previous()
return FormatSpecDecimal(
dot=dot,
precision=precision,
grouping=grouping
)

View File

@@ -17,6 +17,7 @@ class FormatSpecIntegral:
@dataclass(frozen=True)
class FormatSpecDecimal:
dot: Token
precision: Optional[int]
grouping: Optional[Token]
@@ -24,7 +25,7 @@ class FormatSpecDecimal:
@dataclass(frozen=True)
class FormatSpecNumber:
integral: FormatSpecIntegral
decimal: FormatSpecDecimal
decimal: Optional[FormatSpecDecimal]
@dataclass(frozen=True)

View File

@@ -200,7 +200,7 @@ class Formatter(Expr.Visitor[str], Stmt.Visitor[str]):
res += str(spec.number.integral.width)
if spec.number.integral.grouping is not None:
res += spec.number.integral.grouping.lexeme
if spec.number.decimal.precision is not None or spec.number.decimal.grouping is not None:
if spec.number.decimal is not None:
res += "."
if spec.number.decimal.precision is not None:
res += str(spec.number.decimal.precision)