Inherited mutability, freeze, thaw and more in Rust

Chris Cain clcain at uncg.edu
Thu Jul 26 10:07:18 PDT 2012


On Thursday, 26 July 2012 at 14:54:59 UTC, bearophile wrote:
> struct Foo {
>     immutable int x;
>     int y;
> }
> void main() {
>     Foo f = Foo(5, 10);
>     f = Foo(20, 30);
> }

There's problems with this which would have significant 
consequences in D. It would destroy the ability to reason about 
code and make many different possible optimizations.

A quick example of one of the problems that would be raised by 
this:

int calc(immutable int * input) {
    auto result = input * 7;

    // ... lots of other things

    result += input + otherThing;
    return result;
}

void main() {
     Foo f = Foo(5, 10);
     auto bar = task!calc(&f.x);
     bar.executeInNewThread();

     // do some things...

     f = Foo(20, 30);

     // do some other things...

     writeln(bar.yieldForce()); // Oops.
}


In this case, the problem is pretty clear. Even though calc takes 
an immutable int pointer, we have no idea whether calc will use 5 
or 20 in its calculation. It may even **change while calc is 
running!**

Furthermore, the compiler might generate code that *is not 
equivalent to the program as written* as a side effect to that 
unpredictable state of affairs. For instance, it might choose to 
cache the int in a register and therefore wouldn't change while 
calc is running ... which is clearly not equivalent, but *should* 
be correct if we assume that the input couldn't change ... which 
is what immutable normally guarantees.


Now Rust may have other features/limitations which make this not 
a problem (and even correct), but it could have far reaching 
consequences for D.


More information about the Digitalmars-d mailing list