On Friday, 1 August 2014 at 03:17:06 UTC, Walter Bright wrote:
In fact, the whole reason assert is a core language feature
rather than
a library notion is I was anticipating making use of assert
for
optimization hints.
So why is this not documented?
Frankly, it never occurred to me that it wasn't obvious. When
something is ASSERTED to be true, then it is available to the
optimizer. After all, that is what optimizers do - rewrite code
into a mathematically equivalent form that is provably the same
(but cheaper to compute). Its inputs are things that are known
to be true.
For example, if a piece of code ASSERTS that x is 3, thereafter
the optimizer knows that x must be 3. After all, if the
optimizer encounters:
x = 3;
do I need to then add a note saying the optimizer can now make
use of that fact afterwards? The use of "assert" is a very
strong word, it is not "maybe" or "possibly" or "sometimes" or
"sort of".
When you write:
assert(x == 3);
then at that point, if x is not 3, then the program is
irretrievably, irredeemably, undeniably broken, and the default
action is that the program is terminated.
The idea expressed here by more than one that this is not the
case in their code is astonishing to me.
This is enough to convince me.
assert - in D - is for documenting assumptions and checking them
in non-release builds. It's a reasonable definition - if
unexpected to some - and allows good optimisation opportunities.
Do these guidelines sound reasonable:
Don't want the optimiser to use the information from your asserts
when the asserts are gone?
Wrap them in a version block and version them out in your release
builds. Write a wrapper for assert that does this if you like.
You could even write a no-op wrapper for assert and call it
assume, if you really want to.
Don't want your defensive checks to ever be removed from a
certain bit of code?
Use std.exception.enforce or, if you really insist on assert, put
a
version(assert) {} else
static assert(false, "Must be compiled with assertions
enabled");
in the relevant place to prevent people accidentally disabling
them.