Documentation
¶
Overview ¶
Package scriptprintf is the string formatting a managed script's `%` operator and str.format method run (#2048).
Starlark's own `%` takes bare verbs only and its str.format takes no format spec, so "%02X" % b, "%.2f" % rate and "{:>10}".format(name) fail at run time with "unknown conversion". Every Python-shaped language an author knows accepts them, and the failure surfaces on the first run that reaches the line, often a branch no draft took. This package implements the printf subset (flags - 0 + space #, width, precision, * for either) and Python's format-spec mini-language, and Rewrite routes a script's `%` and .format through them before the script is compiled. A left operand that is not a string, and a .format on anything but a string, go to Starlark's own.
The package knows nothing about runs or the platform; CheckPercent and CheckFormat let the authoring gates refuse a literal format string that would still fail, at save rather than mid-run.
Index ¶
- Constants
- func Bind(env starlark.StringDict) starlark.StringDict
- func CheckFormat(template string) error
- func CheckPercent(format string) error
- func Format(template string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error)
- func Percent(x, y starlark.Value) (starlark.Value, error)
- func Rewrite(file *syntax.File)
Constants ¶
const ( PercentName = "%" FormatName = ".format" )
PercentName and FormatName are the globals Rewrite routes `%` and .format through. Neither is an identifier a script can write, so a script can neither call nor shadow them: the resolver looks a name up by its text and does not check that it could have been typed.
Variables ¶
This section is empty.
Functions ¶
func Bind ¶
func Bind(env starlark.StringDict) starlark.StringDict
Bind returns env with PercentName and FormatName bound, for the module a rewritten file is compiled against.
func CheckFormat ¶
CheckFormat reports why template would be refused by str.format, or nil. It reads the template alone: whether the arguments fit is the run's to find out.
func CheckPercent ¶
CheckPercent reports why format would be refused as the left operand of `%`, or nil. It reads the format alone: whether the arguments fit is the run's to find out.
func Percent ¶
Percent is `x % y`: Python's printf-style formatting when x is a string, and Starlark's own operator otherwise.
func Rewrite ¶
Rewrite routes every `x % y`, `name %= y` and `x.format(...)` in file through PercentName and FormatName, in place. Positions are kept: the call is placed at the operator or the method name, so an error is reported where the script wrote it.
It has to be a rewrite. Starlark evaluates `%` and a string's methods inside the interpreter, with no hook a predeclared value can take, and the alternative is a fork of the interpreter.
A `%=` whose target is not a plain name (d["k"] %= v) is left to Starlark: rewriting it would evaluate the target twice.
Types ¶
This section is empty.