feat: add f-string literals (f"…{expr}…") to Starlark#625
feat: add f-string literals (f"…{expr}…") to Starlark#625IgorShishkin12 wants to merge 23 commits into
f"…{expr}…") to Starlark#625Conversation
Feature fstring
|
Thanks for contributing to Starlark. If you haven't already, please do read the Contributing section of the project home page:
There is an open spec issue for improved string formatting support at bazelbuild/starlark#91. We should establish a consensus there before committing to any particular implementation, though I'm sure your experience developing this PR will have given you valuable insights on how that issue should be decided. |
This change implements Python-style f-string literals for Starlark.
An f-string such as
f"hello {name}"is parsed as a single expression that evaluates to the string"hello Starlark"whenname = "Starlark".Only the interpolation syntax
{expr}is supported; conversion flags (!r,!s), format specifiers (:>10,:.2f) and the raw+f combination (rf"…") are left for future work.Reasoning:
.format()calls are noisy and error-prone.formatcall is faster than creating intermediate strings for each+operator, and it avoids the temporary allocations that show up in macro-generated code.!r,!s) and format specifiers (:>10) can be added later without breaking existing programs.What is new:
f'…',f"…",f'''…''',f"""…""".FStringExprnode that keeps the literal segments and the interpolated expressions.formatmethod (same strategy Python uses).testdata/fstring.star.Breaking changes:
None – f-strings are purely additive.
Implementation notes:
fcomp.argssignature changed from(*syntax.CallExpr)to[]syntax.Exprso it can be re-used for the implicitformatcall generated by f-strings.Future work (not in this PR)
!r,!s,:fmtconversion / format specs.rf"…"combination.