Implicit cast to immutable

Steven Schveighoffer schveiguy at yahoo.com
Mon Oct 17 07:00:14 PDT 2011


On Sat, 15 Oct 2011 23:05:43 -0400, Daniel Murphy  
<yebblies at nospamgmail.com> wrote:

> The implicit conversion to immutable is only possible inside strongly  
> pure
> functions.  When the parameter is 'in int[]' foo cannot be strongly pure,
> only const pure.  As 'in int[2]' is a value type, the second foo can be
> strongly pure.
>
> 'new' expressions will hopefully be able to be converted to immutable
> eventually, along with array concatenation and array.dup.
>
> It is also likely that the following will be valid code (const pure foo
> called with immutable arguments)
>
> int[] foo(in int[] x) pure {
>    return new int[1];
> }
>
> void main() {
>   immutable x = foo([1, 2, 3].idup);
> }

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.

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 should compile:

void main() {
    immutable x = foo([1, 2, 3]);
}

-Steve


More information about the Digitalmars-d-learn mailing list