www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - pure functions calling impure functions at compile-time

reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
...do not compile. Because, you know, having done impure things, they are
tainted for life.

Example:

string foo( ) {
     return "O HAI";
}

pure void bar( ) {
     enum tmp = foo( ); // Error: pure function 'bar' cannot call impure  
function 'foo'
}

Should this be filed as a bug, or is the plan that only pure functions be
ctfe-able? (or has someone already filed it, perhaps)
May 23 2012
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Simen Kjaeraas:

 Should this be filed as a bug, or is the plan that only pure 
 functions be
 ctfe-able? (or has someone already filed it, perhaps)

It's already in Bugzilla, see issue 7994 and 6169. But I think there is a semantic hole in some of the discussions about this problem. Is a future compile-time JIT allowed to perform purity-derived optimizations in CTFE? Bye, bearophile
May 23 2012
parent Don Clugston <dac nospam.com> writes:
On 23/05/12 11:41, bearophile wrote:
 Simen Kjaeraas:

 Should this be filed as a bug, or is the plan that only pure functions be
 ctfe-able? (or has someone already filed it, perhaps)

It's already in Bugzilla, see issue 7994 and 6169.

It's just happening because the purity checking is currently being done in a very unsophisticated way.
 But I think there is a semantic hole in some of the discussions about
 this problem. Is a future compile-time JIT allowed to perform
 purity-derived optimizations in CTFE?

Some, definitely. Eg. foo(n) + foo(n) can be changed to 2*foo(n), where n is an integer, regardless of what foo does. It does need to be a bit conservative, but I think the issues aren't CTFE specific. Eg, something like this currently gives an assert at runtime: pure nothrow void check(int n) pure nothrow { assert(n == 4); } void main() { check(3); } even though check() can do nothing other than cause an error, it still cannot be optimized away. But you can get rid of all subsequent calls to it, because they'll produce the same error every time.
May 24 2012