__traits(compileError, {})
Timon Gehr via Digitalmars-d
digitalmars-d at puremagic.com
Mon Sep 11 04:07:46 PDT 2017
On 08.09.2017 03:18, bitwise wrote:
> Lately, I've been hit by several compilation errors when phobos fails to
> construct an instance of a class or struct I've pass it. Regardless of
> what the exact failure is, phobos usually gives you some generic error
> that isn't helpful.
>
> Example:
>
> class Test {
> @disable this();
> }
>
> int main(string[] argv) {
> auto sz = __traits(classInstanceSize, Test);
> auto mem = malloc(sz)[0..sz];
> emplace!Test(mem);
> return 0;
> }
>
> The above code fails with this error:
>
> 'Error: static assert "Don't know how to initialize an object of type
> Test with arguments ()"'
>
> @disable'd constructors are only one of the reasons I've hit this snag.
> Once though, I was having an extremely hard time figuring out what was
> wrong, and the fix was simply to modify emplace(). I removed the line
> below from emplace(), and forced the constructor call, which led to a
> much more helpful error.
>
> `// static if (is(typeof(result.__ctor(args1))))`
>
> If you simply did that though, it may not be obvious to everyone what
> happened, but if you had __traits(compilerError, {}) then you could
> dress the error up as appropriate:
>
> "Emplace failed with error:\n\t'" ~ __traits(compileError, {
> result.__ctor(args1) }) ~ "."
>
> The alternative would be to manually code redundant error checks that
> the compiler already does into everything in phobos that needs to
> construct objects, which seems much worse than implementing something
> like __traits(compileError, {}).
>
> Thoughts?
The dangerous thing about this suggestion is that it makes the
compilation errors DMD implements de facto part of the semantics of the
D language. I.e. improving compiler diagnostics becomes a breaking
language change.
More information about the Digitalmars-d
mailing list