Some time ago I have suggested the idea of running the pre-conditions at compile-time where possible:
http://d.puremagic.com/issues/show_bug.cgi?id=5906

This helps turn some run-time errors in compile-time errors, when the inputs are statically known. This is expecially handy for literals of user-defined subtypes.

But Walter answered a problem:

The user must make an explicit choice if code is to be run at compile
time or run time.


They have just accepted the Ada 2012 standard, that among other things (like the "old" (prestate) for contract programming) introduces a "Static_Predicate" aspect (this page is not very readable):

http://www.ada-auth.org/standards/12rm/html/RM-3-2-4.html

Static_Predicate allows to attach a compile-time predicate that verifies the validity of a subtype (there is also "Dynamic_Predicate").


So an idea to remove the problem found by Walter is to introduce "static preconditions" in D (there is a "static" before the "in", currently this code is a syntax error):



import std.ascii: isDigit;

struct Digit {
    char d;
    alias this = d;

    this(in dchar c)
    static in {
        assert(isDigit(c));
    } body {
        // Currently this cast is necessary,
        // despite the pre-condition.
        d = cast(char)c;
    }
}

void main() {
    // Currently not allowed handy syntax:
    // Digit[] d = ['5', '6'];

    // Becomes a compile-time error:
    Digit[] d = [Digit('5'), Digit('x')];
}



Adding "static" to a precondition means the compiler will try to run the precondition at compile-time where possible, and at run-time where it's not possible. (So a "static in" does not mean the pre-condition will always run at compile-time).

If you don't add a "static" before "in" the precondition will be run only at run time, as usual. This avoids the unwanted growth of compilation times that Walter wants to avoid.

Bye,
bearophile

Reply via email to