Should pure functions be prevented from reading changeable immutable static variables?

Lutger lutger.blijdestijn at gmail.com
Sat Nov 6 03:30:40 PDT 2010


Don wrote:

> 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).
> 
> The motivation for wanting to ban them is to prevent the optimiser from
> generating bad code. But if they were disallowed, there would also be
> benefits for breaking circular module dependencies:
> * if module A imports only pure functions from module B,
> we know that the static this() of A does not directly depend on the
> static this() of module B.
> (Note though it might still depend on C, which depends on B).
> * if the static this() of module A only calls pure functions, it does
> not depend on the static this() of any other module.
> 
> Probably, this would only avoid the most trivial circular module
> dependencies, so not a huge win, but still a nice bonus.

Ideally the compiler could still allow such functions when called after 
static this() is finished. Is this realistic? Probably not. I would vote 
for ban if not.



More information about the Digitalmars-d mailing list