DIP 1027--String Interpolation--Final Review Feedback Thread
Steven Schveighoffer
schveiguy at gmail.com
Mon Feb 3 15:48:53 UTC 2020
I propose an incremental change to this DIP.
Instead of
i"a, $b, ${%d}c"
lowering to the tuple
("a, %s, %d", b, c)
it lowers instead to the tuple
(__d_interpString!("a, ", __d_formatItem.init, ", ",
__d_formatItem("%d")), b, c)
The item returned from __d_interpString shall be defined by the library,
but one that implicitly converts to a string or immutable(char)*, with
the string contents being identical to the current DIP's format string.
It also will provide access to the original sequence as parsed.
__d_formatItem should be essentially a typedef of string, with a default
value of "%s".
The rationale for this change is twofold:
1. Providing an alternative type that decays to a simple string allows
specialized handling of such an interpolation via overloading. Some
current problems that can be alleviated by this (as identified in the
DIP discussion):
a. multiple interpolated strings as parameters to writefln. e.g.:
writefln(i" ... $a ... ", i" ... $b ... ") can be handled.
b. Escaping of "%" characters in formatted strings. e.g.:
writefln(i"$percentage% complete") will assume the "% c" is a format
specifier, but could be overloaded to ignore that '%' if it knows the
format string came from an interpolated string.
c. alternative default format specifiers. For example MySQL uses
only the '?' specifier for parameters, so one must prefix EVERY string
interpolation parameter with ${?}. If a function overload knows you are
using string interpolation, it can generate a proper SQL query without
needing those prefixes.
2. The compiler is already doing the work of splitting up the parameters
and string data. If the format string is simply passed as a string, then
determining the original parsed form (of string + format specifiers) is
difficult, if not impossible, and definitely unnecessary if the compiler
has already done it.
It should be noted that this shouldn't affect any other items in the DIP
-- everything as written in the DIP for examples should work exactly the
same. But if we don't add this mechanism first, it will be more
difficult to add it later. Most obvious would be that templates that
accept any type as its first parameter would change to a new type from
string. This may not break anything, but it would potentially be a
breaking change.
Also, the names of the identifiers __d_interpString and __d_formatItem
are subject to debate.
-Steve
More information about the Digitalmars-d
mailing list