I just got it! (invariant/const)

Steven Schveighoffer schveiguy at yahoo.com
Wed Apr 9 10:49:31 PDT 2008


"Georg Wrede" wrote
> Steven Schveighoffer wrote:
>>
>> There are interesting puzzles that I'm not sure how they will be solved. 
>> For example:
>>
>> pure int f()
>> {
>>    char[] c = new char[15];
>>    c[0] = 'h'; // does this compile?
>> }
>>
>> Does c need to be invariant to access members of the array?  Clearly from 
>> this code, you can see that c is private to f.  But under the rules, the 
>> data c references is not invariant, and so should be inaccessible.  How 
>> will the compiler make this distinction?
>
> Before commenting on the rest,
>
> to me it is obvious that c is solely owned by f (because no references to 
> c can exist outside of f), and therefore c is considered internal to f, so 
> it's legal.

The whole problem comes from the parsing.  I'm not a guru when it comes to 
how D's grammar is structured, but I think it's supposed to be 'context 
free'?

So in the single statement:

c[0] = 'h';

and c's type is char[], how can the compiler be sure it's pointing to local 
data without context/analysis?

In my mind, I think that it should be allowed, but I'm just not sure how 
that can be implemented in a guaranteed fashion, and still keep the grammar 
context-free.  If c has it's own special 'pure' type, that's one thing, but 
I'm not sure how that works.  Maybe it just tags c as being local 
internally, just to check for purity...

-Steve 





More information about the Digitalmars-d mailing list