should pure functions accept/deal with shared data?

Steven Schveighoffer schveiguy at yahoo.com
Wed Jun 6 14:39:50 PDT 2012


An interesting situation, the current compiler happily will compile pure  
functions that accept shared data.

I believed when we relaxed purity rules, shared data should be taboo for  
pure functions, even weak-pure ones.  Note that at least at the time, Don  
agreed with me: http://forum.dlang.org/post/i7d60m$2smf$1@digitalmars.com

Now, technically, there's nothing really *horrible* about this, I mean you  
can't really have truly shared data inside a strong-pure function.  Any  
data that's marked as 'shared' will not be shared because a strong-pure  
function cannot receive any shared data.

So if you then were to call a weak-pure function that had shared  
parameters from a strong-pure function, you simply would be wasting cycles  
locking or using a memory-barrier on data that is not truly shared.  I  
don't really see a compelling reason to have weak-pure functions accept  
shared data explicitly.

*Except* that template functions which use IFTI have good reason to be  
able to be marked pure.

For example:

void inc(T)(ref T i) pure
{
    ++i;
}

Now, we have a template function that we know only will affect i, and the  
compiler enforces that.

But what happens here?

shared int x;

void main()
{
    x.inc();
}

here, T == shared int.

One solution (if shared isn't allowed on pure functions) is, don't mark  
inc pure, let it be inferred.  But then we are losing the contract to have  
the compiler help us enforce purity.

I'll also point out that inc isn't a valid function for data that is  
actually shared: ++i is not atomic.  So disallowing shared actually helps  
us in this regard, by refusing to compile a function that would be  
dangerous when used on shared data.

The compiler *currently* however, will simply compile this just fine.

I'm strongly leaning towards this being a bug, and needs to be fixed in  
the compiler.

Some background of why this got brought up:  
https://github.com/D-Programming-Language/druntime/pull/147

Opinions?

-Steve


More information about the Digitalmars-d mailing list