www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: Should pure functions be prevented from reading changeable immutable

reply bearophile <bearophileHUGS lycos.com> writes:
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()? :-) I suspect this is a silly question.
 The motivation for wanting to ban them is to prevent the optimiser from 
 generating bad code.

Sounds like a worth goal. Bye, bearophile
Nov 06 2010
parent Don <nospam nospam.com> writes:
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.
Nov 06 2010