Array literals REALLY should be immutable

Don nospam at nospam.com
Fri Nov 13 02:30:33 PST 2009


Denis Koroskin wrote:
> On Fri, 13 Nov 2009 12:57:52 +0300, Don <nospam at nospam.com> wrote:
> 
>> Walter Bright wrote:
>>> Don wrote:
>>>> Especially when it's creating an inconsistency with string literals.
>>>   The inconsistency bothers me, too, but then there's the case:
>>>     int x;
>>>    ...
>>>    [1, 2, x]
>>>  That can't be made immutable. Shouldn't it work? There's no analog 
>>> for that for string literals, so the inconsistency isn't quite complete.
>>
>> I don't think it should work.
>>
>> [1, 2, x] is totally different from, and a far more complicated beast 
>> than [1, 2, 3]. [1, 2, x] either allocates memory and performs some 
>> form of memory copy, or else it pokes the 'x' value into a 
>> half-initialised static array, exposing the code to a possible race 
>> condition.
> 
> With thread-local-by-default in mind, this is not an issue.

You mean the race condition is not an issue? It is an issue because the 
compiler needs to deal with it (perhaps by using thread local 
variables!) But the second case is not implemented in DMD anyway.


>> The latter is just a standard lookup table, that results in no code 
>> generation.
>> I don't see why these two very different operations should share the 
>> same syntax -- they don't actually have much in common.
>>
>> It'd be nice to able to say that "abcd" and ['a', 'b', 'c', 'd'] are 
>> completely identical.
>>
> 
> They aren't: "abcd" has a null-terminator past the string, and ['a', 
> 'b', 'c', 'd'] doesn't.

You're right. Though, it'd be easy to add a null terminator to the end 
of memory allocated to char-typed array literals, and make them 
identical in every respect.

>> C++ got away with using the same syntax for these two totally 
>> different things, because (1) it doesn't have any kind of constant 
>> folding/CTFE, so it can look at the array entries and determine 
>> whether it's immutable or not; and (2) it ignores multi-core issues.
>>
>> The fact that the language doesn't have any syntax for an immutable 
>> array literal is really a problem. Some people are getting around it 
>> by using a CTFE function to convert all the values to a string 
>> literal, then casting that string literal to (say) an array of ints. 
>> That's currently the only way to make the compiler generate decent 
>> code, and it's quite dreadful.
>>
>> BTW, I'm pretty sure that making array literals immutable would 
>> simplify the compiler. EG, I've noticed that mutable array literals 
>> cause many problems for the interpreter.



More information about the Digitalmars-d mailing list