Comment #0 by bearophile_hugs — 2010-05-12T04:09:05Z
To define a std.math.log() function that works at compile time (see bug 3749 ) it can be used __ctfe, but there are problems:
pure real log(real x) {
if (__ctfe)
return 0.0;
else
return 1.0;
}
enum x = log(4.0);
void main() {}
dmd v2.045 prints:
test.d(2): Error: variable __ctfe forward referenced
test.d(2): Error: pure nested function 'log' cannot access mutable data '__ctfe'
test.d(7): Error: cannot evaluate log(4L) at compile time
test.d(7): Error: cannot evaluate log(4L) at compile time
I'd like __ctfe to work in pure functions too.
I think it can be done because it's an immutable value that I think can't break the purity of the function/method, even if as in that example the function can give different outouts at compile and run time.
Comment #1 by clugdbug — 2010-06-08T11:38:37Z
Since __ctfe is so magical and unique, it seems justified to give it one more
special case. Other approaches I tried (changing the storage_class of __ctfe)
were far more complicated.
PATCH expression.c, VarExp::semantic(), line 4397.
+ /* Magic variable __ctfe never violates pure or safe
+ */
+ if (v->ident == Id::ctfe)
+ return this;
/* If ANY of its enclosing functions are pure,
* it cannot do anything impure.
* If it is pure, it cannot access any mutable variables other
* than those inside itself
*/