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

Jonathan M Davis jmdavisProg at gmx.com
Fri Nov 5 19:24:11 PDT 2010


On Friday 05 November 2010 18:32:47 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.

It's probably simplest to say that they can't be pure since they're accessing 
global state, but would it be possible to treat them as non-pure in any static 
constructors and then pure during the rest of the program? Perhaps just outright 
disabling purity optimizations in static constructors would solve the problem. 
Then you could treat such functions as pure quite easily without having the 
problems that it could cause within a static constructor. It wouldn't suprise me 
though if it were a bit of a pain to special case static constructors like that.

- Jonathan M Davis


More information about the Digitalmars-d mailing list