Issue 13568: Add CT-checked format string overloads to std.format#5288
Issue 13568: Add CT-checked format string overloads to std.format#5288dlang-bot merged 3 commits intodlang:masterfrom
Conversation
* Add overloads for formattedWrite, formattedRead, format, sformat. * Throw FormatError when formatValue is called with floating points. The latter allows `snprintf` to be avoided in CTFE when checking format strings so floating point arguments can be checked.
std/format.d
Outdated
| try | ||
| .format(fmt, Args.init); | ||
| catch (Exception e) | ||
| return (e.msg is ctfpMessage) ? null : e; |
There was a problem hiding this comment.
Hmm. Are you sure the is will work? Since ctfpMessage is declared as an enum, wouldn't it produce a new instance every time it's referenced?
| * Params: fmt = Format string. For detailed specification, see $(LREF formattedWrite). | ||
| * args = Variadic list of arguments to _format into returned string. | ||
| */ | ||
| typeof(fmt) format(alias fmt, Args...)(Args args) |
There was a problem hiding this comment.
Might be a good idea to add sig constraints here to constrain what the user passes in fmt.
There was a problem hiding this comment.
Ditto for the other places where alias fmt is used.
There was a problem hiding this comment.
Now done. Forgot yesterday :-/
|
There's actually a preapproved enhancement ticket for this: https://issues.dlang.org/show_bug.cgi?id=13568 |
|
Overall, I very much like this. Once the above comments are addressed, this is good to go. This is a good first step towards implementing issue 13568. The second half of issue 13568 is not addressed by this PR, that is, to remove dependencies on formatting code that is actually not used by the specified format string. But this is a good first step. Implementing the latter will require extensive refactoring of |
| * A $(LREF FormatException) if the length of `args` is different | ||
| * than the number of format specifiers in `fmt`. | ||
| */ | ||
| char[] sformat(alias fmt, Args...)(char[] buf, Args args) |
There was a problem hiding this comment.
Why is this specialized for char?
| } | ||
|
|
||
| /// ditto | ||
| char[] sformat(Char, Args...)(char[] buf, in Char[] fmt, Args args) |
|
nice work btw |
|
Thanks for reviews. Added quickfur's suggestions plus a changelog entry. |
Check compile-time format strings match the given argument types. I'm using CTFE to evaluate
format(fmtStr, Args.init)and see if an exception was thrown; the actual runtime code is unchanged. This is not optimal but makes this PR easy to implement and avoids code duplication/refactoring offormattedWrite. Users can start to pass format strings as compile-time arguments.This allows
snprintfto be avoided in CTFE when checking format strings so floating point arguments can be checked.@quickfur