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

Simen kjaeraas simen.kjaras at gmail.com
Sat Nov 6 07:02:47 PDT 2010


Don <nospam at nospam.com> 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.

This feels a bit wrong to me - the only time when that needs to be
disallowed is in static constructors, so it seems like an edge case.

As you say, there are benefits to this solution, but I'm not sure they
outweigh the disadvantages. It all comes down to a case of 'I feel' vs.
'you feel', though.

-- 
Simen


More information about the Digitalmars-d mailing list