Implicit cast to immutable

Daniel Murphy yebblies at nospamgmail.com
Mon Oct 17 23:40:12 PDT 2011


"Steven Schveighoffer" <schveiguy at yahoo.com> wrote in message 
news:op.v3h06olweav7ka at localhost.localdomain...
>
> That sounds like an incorrect restriction.  The implicit cast to immutable 
> should depend on whether the function being *called* qualifies, not if the 
> function you are calling *from* qualifies.
>

I think you've misunderstood what I'm saying.  The patch I made implemented 
two ways to implicly convert to immutable: the result of a pure function 
returning immutable and a return statement inside a pure function.

1)
int[] fun() { return new int[]; }
immutable x = fun(); // conversion happens here

2)
immutable(int[]) fun() { return new int[]; } // conversion happens here
immutable x  = fun();

Bearophile's example is of the second, where it definately matters what the 
purity of the function is.

> Qualifying means the return type should be mutable, and cannot be derived 
> from the parameters without requiring casts.  The easiest way to do this 
> is to ensure the parameters are all const, immutable, or implicitly cast 
> to immutable.  You could do funky things like assume for instance an int[] 
> cannot possibly be implicit-casted to a char[], so therefore int[] 
> foo(char[] data) pure can be implicitly casted to immutable, but that 
> might be flirting with dangerous situations.
>
> The one exception should be allocating memory, which should always 
> qualify, even though it's not a pure function.
>

This is valid, but becomes very complicated with complex return types.  I 
doubt this will ever make it into the language.

I've got the beginnings of a patch to enable a sort of 'pure expression', 
such as new, array.dup and array concatenation expressions.  The result of a 
call to a const-pure function using immutable arguments can be converted to 
immutable, while calling it with mutable or const arguments cannot, without 
searching the return type for anything the arguments can implicitly convert 
to (or create).

Eg. I can't see a great way to detect situations like this:

struct S { const void* p; }
S[] fun(int[] arr)
{
    return [ S(arr.ptr) ];
}
immutable x = fun([1, 2, 3]); 




More information about the Digitalmars-d-learn mailing list