Getting the error from __traits(compiles, ...)
Bill Baxter
wbaxter at gmail.com
Fri Nov 13 08:31:14 PST 2009
On Fri, Nov 13, 2009 at 12:09 AM, Don <nospam at nospam.com> wrote:
> Bill Baxter wrote:
>>
>> We can pretty much already use __traits(compiles,{...}) to implement
>> static interface checking.
>>
>> template checkInterface(T) {
>> enum bool checkInterface =
>> __traits(compiles,
>> {
>> T x;
>> // some code exercising various aspects of the interface
>> });
>> }
>>
>> The main problem with this is that a static "implements interface"
>> check is done like so:
>>
>> static assert(checkInterface!(myType));
>>
>> And all it tells you is a single yes or no. It would help in
>> debugging if you could somehow get the reason for the failure.
>>
>> So how to do it? All that comes to mind is something like the evil
>> Errno from C. A global that gets set by the last failure.
>> Let's call it __errmsg, but it could be a pragma, or a __traits thing.
>> If you had that then you could write this:
>>
>> assertImplements!(checkInterface!(myType));
>>
>> With:
>> template assertImplements(bool v)
>> {
>> static if (!v) {
>> pragma(msg, __errmsg);
>> static assert(false);
>> }
>> }
>>
>> There are lots of ways you could provide such a concept-checker, but
>> they all require the basic ability to get the reason for the
>> __traits(compiles) failure.
>>
>> Any other thoughts about how to get the failure info? This is
>> probably the main complaint against __traits(compiles), that there's
>> no way to find out what went wrong if the code doesn't compile. Often
>> it can just be a typo. I know I've spent plenty of time looking at
>> static if(__traits(compiles, ...)) checks that weren't working only to
>> discover I switched an x for a y somewhere. Or passed the wrong
>> number of arguments.
>>
>> --bb
>
> I think you might be asking for:
>
> static try {
> xxx;
> }
> catch( CompilerError[] errors){
> pragma(msg, "Failure in Frobozz!");
> pragma(msg, errors[0].msg);
> }
Heh heh. Well I proposed something along those lines before, and it
didn't catch on, so I decided to avoid mentioning it this time. :-)
http://digitalmars.com/d/archives/digitalmars/D/static_try_catch_construct_would_be_helpful_66794.html
But yeh, actually now that you mention it that handles both problems I
brought up recently.
1) how to run code only if it compiles and avoid repeating yourself.
(the original reason I proposed it)
2) how to get and report errors related to failure to compile some
code. (this one I hadn't thought of back then)
But yeh, it looks like that could solve both problems.
--bb
More information about the Digitalmars-d
mailing list