feat(formatter): add format spec to formatter

This commit is contained in:
2026-02-07 19:25:39 +01:00
parent 34873c7e0e
commit eb5c731ee5

View File

@@ -5,6 +5,7 @@ from src.ast.expr import Expr, VariableExpr, LiteralExpr, GroupingExpr, UnaryExp
CallExpr, SetExpr, GetExpr, ThisExpr, SuperExpr, FStringExpr, FStringEmbedExpr
from src.ast.stmt import Stmt, LetStmt, IfStmt, ExpressionStmt, BlockStmt, WhileStmt, ForStmt, FunctionStmt, \
ReturnStmt, BreakStmt, ContinueStmt, ClassStmt
from src.core.format_spec.spec import FormatSpec
class ClassType(Enum):
@@ -88,7 +89,11 @@ class Formatter(Expr.Visitor[str], Stmt.Visitor[str]):
return res
def visit_fstring_embed_expr(self, expr: FStringEmbedExpr) -> str:
return "{" + self.format(expr.expression) + "}"
res: str = "{" + self.format(expr.expression)
if expr.spec is not None:
res += ":" + self.format_format_spec(expr.spec)
res += "}"
return res
def visit_variable_expr(self, expr: VariableExpr) -> str:
return expr.name.lexeme
@@ -185,3 +190,22 @@ class Formatter(Expr.Visitor[str], Stmt.Visitor[str]):
def visit_continue_stmt(self, stmt: ContinueStmt) -> str:
return self.indented(f"{stmt.keyword.lexeme}\n")
def format_format_spec(self, spec: FormatSpec) -> str:
print(spec)
res: str = ""
if spec.options.sign is not None:
res += spec.options.sign.lexeme
if spec.number.integral.width is not None:
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:
res += "."
if spec.number.decimal.precision is not None:
res += str(spec.number.decimal.precision)
if spec.number.decimal.grouping is not None:
res += spec.number.decimal.grouping.lexeme
if spec.type is not None:
res += spec.type.lexeme
return res