On 6/21/15 12:31 AM, Edmund Smith wrote:
This idea makes sense with the type checker, although I'm not sure how it fits D's current memory model. On the page detailing const and immutable (dlang.org/const3.html) it mentions that immutable data 'can be placed in ROM (Read Only Memory) or in memory pages marked by the hardware as read only', which may be problematic if an immutable's mutable reference counter is placed in a read-only page. Would this potentially be changed? It suggests that the compiler needs a way of telling if the struct is a typical immutable struct or is privately-mutable, publicly-immutable.
Yah, that would need to be changed. That's why we need a way to tell the typesystem about that kind of data. It can't be put in read-protected memory of any kind.
As for the language level, it helps to look at how an immutable value propagates. It can be passed by value or by reference, passed between threads without issue and its value never changes. The thread safety strongly implies that what isn't immutable is shared, so that every field in an immutable struct is still thread-safe. Its exposed value never changing is also crucial IMO, to the point where I think it should be a compiler error if the 'facade' of immutability collapses (e.g. mutable data is public or modifies a public function's result).
So, shared data member of immutable object would remain shared. Sensible. Interesting, I'll keep that in mind. Thanks.
Passing copies also raises a point about the current state of 'immutable struct S', which has a few things different to normal structs (and block anything but POD types. Is this intentional?). Currently, D lacks destructors and postblit constructors on immutable structs, giving the error 'Error: immutable method SomeStruct.__postblit is not callable using a mutable object'. Throwing an immutable qualifier makes it no longer recognisable as a postblit constructor, so that doesn't work either. This makes perfect sense under the current assumption that 'immutable struct' implies it is a POD struct, but if/when under-the-bonnet mutability goes ahead, this assumption will no longer hold (and postblit constructors are pretty useful with refcounting). The same goes for destructors, too. Without these, passing immutable refcounts by copy isn't safe - the copy keeps the pointer, but doesn't increase the counter. This leads to a potential use-after-free if the copy outlives every 'proper' reference. I'm not sure whether this is all necessary, however - it is possible to just ignore 'immutable struct' and use 'alias MyStruct = immutable(MyActualStruct);', in which case the previous paragraph can be ignored.
Yah, we need immutable and const for ctors, postblit, and dtors with specific typechecking rules.
Andrei
