assert and static assert and code generation
Quirin Schroll
qs.il.paperinik at gmail.com
Fri Jun 16 16:55:01 UTC 2023
On Wednesday, 14 June 2023 at 13:00:39 UTC, Cecil Ward wrote:
> The compilers should surely be able to use the presence of
> static asserts to enable better code generation since the
> direction of some later conditional branches can be known,
> value ranges can be known, all kinds of potential good stuff.
> Is that correct?
“the presence of static asserts to enable better code generation”
→ the presence of [non-static] asserts to enable better code
generation
In principle, yes. IMO it’s a big issue that D doesn’t actually
require the expression and message in an `assert` to be `pure`
and `const`. That would alleviate the probably rare, but
annoying-to-debug case where the side-effect of an `assert` does
do things.
What you suggest is implemented in C++23: [C++ attribute:
`assume`](https://en.cppreference.com/w/cpp/language/attributes/assume)
C and C++ had `assert` as a macro for ages. The C++ committee
came to the conclusion that validating contracts and giving the
compiler optimization hints are two different intentions and in
fact so different that they warrant separate syntax.
The cppreference page says:
> Since assumptions cause undefined behavior if they do not hold,
> they should be used sparingly. They are not intended as a
> mechanism to document the preconditions of a function or to
> diagnose violations of preconditions. Also, it should not be
> presumed, without checking, that the compiler actually makes
> use of any particular assumption.
For D, the catch would be: If an `assert` incurred undefined
behavior, which it has to for the condition to meaningfully
affect the optimization, `assert` would be invalid to use in
`@safe` code. Consider that in `@safe` functions, array bounds
checking is enabled even in release mode, because it wouldn’t be
`@safe` if it wasn’t.
We could add to D a construct that does what C++23’s `assume`
does; making `assert` mean that was decided against in the past.
A pragma is ideal because a compiler is free to ignore it and
ignoring an optimization hint is factually perfectly okay. Also,
a pragma can be applied to individual statements and blocks of
statements.
I filed an enhancement issue:
https://issues.dlang.org/show_bug.cgi?id=23996
More information about the Digitalmars-d
mailing list