June 19, 2009
== Repost the article of Jeroen Dirks (jeroen.dirks@sympatico.ca) == Posted at 2009/06/18 10:22 to digitalmars.D

It seems that we are back to making copied all over the place because the compiler can not tell if we would modify something shared.

If the compiler would be smarter and maybe with the help of some annotations on the functions called can figure out what data is owned by a pure operation then you might have a real killer feature here.

1 Compiler guarantees related to locality of changes (without need for
locks everywhere)
2 Still write imperative style code.
3 Not having to do copy on write all the time so that old object is
not changed.

Maybe something like this could be added:

class TestObj
{
   init( int v )
   {
      value = v;
   }
   int value;
}

class Log
{
   internal string[] msg;
   internal TestObj[] values;
   local addMsg( string s ) // marked local since it only changes
internal data
   {
      msg ~= s;
   }
   local addValue( int v )
   {
      values != new TestObj( v )
   }
   local incValues()
   {
      for ( v; values ) {
         v.value += 1;
      }
   }
   pure string[] getMsgs() {
      return msg.dup();  // have to make a copy since it is internal
   }
   // following would be compiler errors:
   string[] getMsg2()
   {
      return msg;  // error: references to internal can not be
returned or exported somehow
   }
   local addValue2( TestObj t )
   {
      values ~= tl // error: can not assign external object to
internal data
   }
};

pure Log WorkWithObj()
{
   Log l = new Log();
   l.addMsg("Hello");
   l.addMsg("World");
   l.addValue( 41 );
   l.addValue( 9 );
   l.incValues();
   return l;
}