Safety/purity and assert/enforce error messages

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Sep 12 15:02:54 PDT 2013


On Thu, Sep 12, 2013 at 11:45:07PM +0200, Meta wrote:
> On Thursday, 12 September 2013 at 20:07:40 UTC, Jonathan M Davis
> wrote:
[...]
> >format can't be nothrow, because it throws when you screw up the
> >format specifiers. You have to wrap it in a try-catch block and
> >assert(0) in the catch block if you want to put it in a nothrow
> >function. std.datetime does this in at least a few places.
> >
> >- Jonathan M Davis
> 
> Why don't we have a format function that is statically checked?

Currently, this is not possible, because the format string may be a
runtime-computed value. For example:

	void main(string[] args) {
		// fmtString is only known at runtime.
		auto fmtString = File("fmtstrings.cfg").byLine().front.idup;

		// This will throw if command-line arguments don't match
		// format string.
		writefln(fmtString, args[1..$]);
	}

It *is* true, however, that the vast majority of format usage uses a
static format string. In those cases, it *would* be nice to have a
nothrow variant of format(). Arguably, we could have this variant of
format:

	string staticFormat(string fmt, T...)(T args) { ... }

which takes a compile-time format string. Then it can be statically
verified to be pure, @safe, nothrow, etc..

This is actually more tricky than it sounds, though. Specifiers like
"%s" are parsed into Format!char objects, which may be passed to a
user-defined type's toString method, so the nothrow-ness of
staticFormat() may change depending on whether the user-defined toString
throws.


T

-- 
Старый друг лучше новых двух.


More information about the Digitalmars-d-learn mailing list