`restricted` member variables
The Zealot
zod at zod.zod
Tue Jun 21 12:19:32 UTC 2022
On Tuesday, 21 June 2022 at 11:20:46 UTC, Ola Fosheim Grøstad
wrote:
> On Tuesday, 21 June 2022 at 10:36:32 UTC, The Zealot wrote:
>> if anything, i'd like to see more control over when invariants
>> are actually checked.
>>
>> something like
>> ```
>> invariant(default)
>> {
>> assert(1 <= day && day <= 31);
>> assert(0 <= hour && hour < 24);
>> }
>> invariant(always) {
>> assert(1 <= sec && sec <= 60);
>> }
>> ```
>
> You can already do this, just add an or-clause to a compile
> time boolean constant.
>
> ```d
> assert((!precise_invariant) || (1 <= day && day <= 31));
> ```
>
> But the class invariant should only be tested on
> member-function entry in debug-mode.
>
> In release mode the invariant should be assumed to hold on
> entry and can be used for optimizations (it should still be
> tested on exit).
>
> So this:
>
> ```d
>
> class always_even {
> private int x;
> invariant { assert(x%2==0); }
> void triple(){
> x *= 3;
> if (x&1) writeln("found one");
> }
> // more code
> }
>
> ```
>
> should become this:
>
> ```d
>
> class always_even {
> private int x;
> tripple(){
> // assume(x%2==0)
> x *= 3;
> assert(x%2==0);
> }
> …
> }
>
> ```
>
> Or even this (with a decent optimizer):
> ```d
>
> class always_even {
> private int x;
> tripple(){
> // assume(x%2==0)
> x *= 3;
> // assert(x%2==0);
> }
> …
> }
>
> ```
>
> With invariants turned off, the result will be worse as there
> is no indication that the lowest bit of x is constant 0:
>
> ```d
> class always_even {
> private int x;
> void triple(){
> x *= 3;
> if (x&1) writeln("found one");
> }
> …
> }
>
> ```
sorry, i wasn't clear what i meant. i meant add the ability to
control when invariants checks are inserted by the compiler. for
example a way to specify that you want the invariant checked
after each access to any member, as well as "the class invariant
should only be tested on member-function entry in debug-mode".
but it's mainly a suggestion for performance reasons.
More information about the Digitalmars-d
mailing list