[Issue 6169] [CTFE] pure functions cannot compute constants using functions not marked as pure

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Jun 16 18:47:32 PDT 2011


http://d.puremagic.com/issues/show_bug.cgi?id=6169


bearophile_hugs at eml.cc changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |bearophile_hugs at eml.cc


--- Comment #1 from bearophile_hugs at eml.cc 2011-06-16 18:42:49 PDT ---
I think you have just made D a bit more complex :-)

In D compile time and run time are fully separated (and computing an enum
inside a CTFE function spans a fully separated and fully enclosed
sub-computation), so there is no way compile-time constants can break the
purity of a pure function. So this looks OK regarding run-time purity.

Currently in D in a function the path of compile-time execution has to be pure,
even if the whole function is not pure, so you are right saying this program
has to compile:


int x = 10;
int foo(bool b) {
    if (b)
        x++;
    return 0;
}
pure void main() {
    enum y = foo(false);
}


If in future D compilers CTFE will be allowed to modify global variables too,
then I think your idea is in troubles. Otherwise at first sight it seems OK,
but more thinking is required because future D compilers are allowed to perform
pure-related optimizations on pure functions even in CTFE. Is nonpurity able to
cause troubles to pure functions at compile-time?

In this program spam is pure, and it calls bar, that's not pure, to compute z.
But this program doesn't cause troubles even if a smart D compiler applies pure
optimization of spam()+spam() replacing it with spam()*2 because z is computed
only once, because bar() is called in a sub-computation that's fully sealed:


pure nothrow int foo() {
    int x = 1;
    nothrow int bar(int y) { // nonpure
        x++;
        return x + y;
    }

    pure nothrow int spam() {
        enum z = bar(1); // calls a nonpure
        return z;
    }
    return spam() + spam();
}

enum r = foo();
void main() {}


So if I am right, then this proposal is safe :-)

One problem left is that this proposal introduces another special case in D,
because the rules of purity have to say a pure function is allowed to call an
impure one at compile-time. Is it worth it? I think it's acceptable.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list