On Thursday, 10 March 2016 at 23:31:22 UTC, FatalCatharsis wrote:
On Thursday, 10 March 2016 at 22:57:41 UTC, Jonathan M Davis wrote:
If/Once we get more features in the compiler which take advantage of contracts, then I'll likely change my tune on that one, but for now, IMHO, they're really only of value in classes.

I'm curious, what kind of features might come out of contracts in the future? They seem somewhat helpful in terms of QA and organization, but what kind of compiler or performance gains could you gain from this system?

Well, if you had something like

    auto foo(int i)
    in
    {
        assert(i > 10 && i < short.max + 5);
    }
    body
    {
        ...
    }

and the the code called it with a value that's known at compile time - e.g. foo(2) - and that value clearly fails the contract, then the compiler could treat that as an error. Similarly, it would know the valid range of i within the function body, which might help with optimizations or with VRP (value range propagation - i.e. how it can know that an integral value can fit in a smaller integral type and use an implicit cast rather than requiring an explicit cast).

Or if you do something with out contracts, e.g.

    int foo(int i)
    out(result)
    {
        assert(result => 0 && result < 100);
    }
    body
    {
        ...
    }

then in theory, the compiler could assume that the result passed the out contract and optimize based on that. For instance, with the code above, maybe it would then treat the result of foo as fitting it a ubyte without a cast, because it would know that as long as the contract passed, it would fit. e.g.

    ubyte bar = foo(9);

Now, I suspect that stuff like that tends to be restricted to basic examples, particularly since you usually pass variables to functions, not literals, and at the moment, I can't think of much useful other than VRP for what could be done with out contracts, but in theory, the compiler would know more about what the function parameters and return value, and in at least some cases, it could optimize based on that or allow certain operations that might not be done implicitly in the general case.

So, at this point, I think that it's pretty much all theoretical, but we might benefit from it at some point. And given that we don't know when such improvements might be made or exactly what code they'd benefit, it's arguably better to just use in and out contracts now just in case we get those improvements later, and the code then benefits without you having to change it, but personally, I don't think that that's worth the extra syntactic mess, particularly since while such improvements have been discussed upon occasion, it's not at all clear that we're ever going to get anything like them.

- Jonathan M Davis

Reply via email to