I just got it! (invariant/const)

Georg Wrede georg at nospam.org
Wed Apr 9 11:29:16 PDT 2008


Steven Schveighoffer wrote:
> "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?

Well, the localness of c is established with char[] c on the preceding 
line. And since D relies on bounds checking (not in release code, but in 
its Philosophy), c[0] is "local" too, for the purposes of this discussion.

> 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...

The compiler has to keep track of local variables anyhow.



More information about the Digitalmars-d mailing list