trusted purity?

monarch_dodra monarchdodra at gmail.com
Mon Aug 19 08:00:39 PDT 2013


On Monday, 19 August 2013 at 12:55:54 UTC, bearophile wrote:
> The problem is that while writing down the proof of the purity 
> of foo3 is probably not too much hard, later the D compiler is 
> not able to verify such proof.
>
> Bye,
> bearophile

Right, that is pretty much it. EG:

//----
import core.stdc.stdlib;

int* myPureFun(int i) pure
{
     auto p = cast(int*) malloc(int.sizeof);
     if (!p) assert(0);
     *p = i;
     return p;
}
//----

I can solve this the same way (kind of) as with safety, by 
marking the function as I can mark a function as trusted, by 
casting the function as pure:

//----
int* myPureFun(int i) pure
{
     alias extern (C) void* function(size_t) pure PureF_t;
     auto p = cast(int*) (cast(PureF_t)&malloc)(int.sizeof);
     if (!p) assert(0);
     *p = i;
     return p;
}
//----

A basic "I know what I'm doing compiler" kind of assertion.

My only issue with doing this is I'm afraid it might be wrong: A 
"trusted" function means nothing to the compiler.

However, in the above example, I *marked* malloc as pure, and 
even though "myPureFun" is conceptually pure, *malloc* remains 
impure, and I don't know how the compiler deals with being told 
it is pure.

Is that code snippet wrong?


More information about the Digitalmars-d mailing list