Mixin Expressions, can't evalutate string variable

Steven Schveighoffer schveiguy at yahoo.com
Thu Aug 5 12:48:50 PDT 2010


On Thu, 05 Aug 2010 15:34:44 -0400, Tomek Sowiński <just at ask.me> wrote:

> Andrej Mitrovic napisał:
>
>> Hmm.. ok. Adding immutable helps. I'm still a bit confused tho,
>>  because this will not compile:
>>
>> string input2 = "int y;";
>> mixin(input2);
>
> input2 is mutable, so theoretically there's no telling what value it  
> holds.

Before you respond with more WTF, there is a subtlety here :)

A string is aliased to immutable(char)[].  This means that the *data*  
pointed at is immutable but the *array* is mutable.  You can reassign a  
string to point at some other immutable data, or change the length of the  
array.  To illustrate this:

string input2 = "int y;";

static this()
{
    input2 = "int x;"; // perfectly legal
}

mixin(input2); // what does this do?

Now, immutable string means:

immutable(immutable(char)[]), which reduces to immutable(char[]), meaning  
both the data pointed at *and* the array are immutable (note the  
distinction of where the parentheses are).  This can be used in CTFE and  
mixins because the compiler knows the value is completely defined at  
compile-time.

strings (the kind where the array part is mutable) can be used as mixins  
as long as they are rvalues, such as the returns from functions which are  
CTFE capable.

-Steve


More information about the Digitalmars-d mailing list