assume, assert, enforce, @safe

David Bregman via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 31 15:07:56 PDT 2014


On Thursday, 31 July 2014 at 18:58:11 UTC, Walter Bright wrote:
> On 7/31/2014 4:28 AM, David Bregman wrote:
>> Sigh. Of course you can assume the condition after a runtime 
>> check has been
>> inserted. You just showed that
>>
>> assert(x); assume(x);
>>
>> is semantically equivalent to
>> assert(x);
>>
>> as long as the runtime check is not elided. (no -release)
>
> No. I showed that you cannot have an assert without the assume. 
> That makes them equivalent that direction.

That is only true if assert always generates a runtime check. 
i.e. it is not true for C/C++ assert (and so far, D assert) in 
release mode.

> For the other direction, adding in a runtime check for an 
> assume is going to be expected of an implementation.

No. It is expected that assume does /not/ have a runtime check. 
Assume is used to help the compiler optimize based on trusted 
facts, doing a runtime check could easily defeat the purpose of 
such micro optimizations.

> And, in fact, since the runtime check won't change the 
> semantics if the assume is correct, they are equivalent.

Right, only "if the assume is correct". So they aren't equivalent 
if it isn't correct.

Q.E.D. ?

>> But you still want to assert to become assume in release mode? 
>> How
>> will you handle the safety issue?
>
> I don't know yet.

I would think the easiest way is to just not inject the 
assumption when inside @safe code, but I don't know anything 
about the compiler internals.

Even for @system code, I'm on the fence about whether asserts 
should affect codegen in release, it doesn't seem like a clear 
tradeoff to make: safety vs some dubious optimization gains. Do 
we really want to go down the same road as C with undefined 
behavior?

I would need to think about it more, but if D adopted that route, 
I would at least feel like I need to be much more careful with 
asserts, so I'm not accidentally making my code more buggy 
instead of less. I think it warrants discussion, anyways.


More information about the Digitalmars-d mailing list