Should pure functions be prevented from reading changeable immutable
Don
nospam at nospam.com
Sat Nov 6 05:18:03 PDT 2010
bearophile wrote:
> Don:
>
>> Pure functions are allowed to read immutable global variables.
>> Currently, this even includes globals which are initialized from inside
>> 'static this()'.
>> Here's an example of how this can be a problem:
>>
>> immutable int unstable;
>>
>> pure int buggy() { return unstable; }
>>
>> static this() {
>> // fails even though buggy is pure
>> assert( buggy() == ( ++unstable , buggy() ) );
>> }
>>
>> I suspect that such functions should be forbidden from being 'pure'.
>> Note that they cannot be used in CTFE (conceptually, all other @safe
>> pure functions could be used in CTFE, even though the current
>> implementation doesn't always allow it).
>
> I don't understand what exactly you propose to ban.
> Do you want to ban any function to be pure if such function reads any global immutable/const variable? Or do you want to just ban pure functions that read global immutables if an only if such global immutables are initialized inside static this()?
The second. Consider:
immutable int x;
immutable int y = 2;
static this() { x = 3; }
y should be usable from inside pure, x should not.
More information about the Digitalmars-d
mailing list