Prettiful error messages with templates

Lutger lutger.blijdestin at gmail.com
Mon May 5 03:42:38 PDT 2008


Not sure how this works in D2 and it doesn't solve the biggest problems but
here's a possible begin:

char[] assertCompiles(uint line, char[] file, char[] code)
{
    return `debug { static if (!__traits(compiles, ` ~ code ~ `))` 
            `{` 
                `pragma(msg, "Failed instantiating template in file ` ~ file
~ ` on line ` ~ ctfeToString(line) ~ `");` 
                `static assert(false);` 
            `}}`;
}

iirc I adapted ctfeToString from phobos' std.string: 

const char[10] digits    = "0123456789";            /// 0..9

/// ditto
char[] ctfeToString(ulong u)
{
    char[] buffer;
    auto buflen = ulong.sizeof * 3;
    while (buflen--)
        buffer ~= ' ';
    int ndigits;

    ndigits = 0;
    if (u < 10)
    // Avoid storage allocation for simple stuff
        return digits[u .. u + 1];
    else
    {
        while (u)
        {
            uint c = (u % 10) + '0';
            u /= 10;
            ndigits++;
            buffer[buffer.length - ndigits] = cast(char)c;

        }
        return buffer[buffer.length - ndigits .. buffer.length].dup;
    }
}

it'll help a bit with the verbosity, used as:

int opAdd(U, uint line = __LINE__, char[] file = __FILE__ ) (U args)
{
    mixin( assertCompiles(line, file, code));
    ...
}


Will you post back when you found some good solutions? Thanks.

Good luck and happy hacking ;)



More information about the Digitalmars-d-learn mailing list