`@safe` by default. What about `@pure` and `immutable` by default?

Meta jared771 at gmail.com
Wed Apr 17 23:39:02 UTC 2019


On Tuesday, 16 April 2019 at 21:33:54 UTC, Jonathan M Davis wrote:
> On Monday, April 15, 2019 9:59:38 PM MDT Mike Franklin via 
> Digitalmars-d wrote:
>> I think I may have found a simple migration path to @safe by 
>> default.  I'm still thinking it through, but if I can justify 
>> it, I will write a DIP.
>>
>> `@safe` by default is a no-brainer in my opinion, but `pure` 
>> and `immutable` by default are less obvious.  With the 
>> aforementioned potential DIP, I have an opportunity to correct 
>> purity and mutability defaults as well...but is that something 
>> we want to do?
>>
>> Can anyone save me some trouble and articulate why it would be 
>> bad to have `pure` and/or `immutable` by default?
>
> if you have a bunch of code, and it turns out that you need to 
> do something in it that isn't pure, you'd be screwed unless you 
> go and mark a ton of code with impure (or whatever the opposite 
> of pure would be). It's not like you can just opt-out in the 
> middle like you can with @safe by using @trusted to use @system 
> code.

That's a good point that I almost always forget when we talk 
about making these attributes the default. To follow the 
safe/trusted/system model we'd need something like 
pure/almostPure/impure.

Weak purity also might be able to provide some partial respite:

int pure1(int n, ref IOWrapper io) pure
{
     return pure2(n.to!string(), io); //The chain continues
}

int pure2(string s, ref IOWrapper io) pure
{
     //Can't do this because writeln is impure
     //writeln("The value of s is ", s);

     io.writeln("The value of s is ", s);

     int result;
     //Do some other work

     return result;
}

struct IOWrapper
{
     string[] writeQueue;

     void writeln(Args...)(Args args) pure
     {
         foreach (arg; args)
             writeQueue ~= args.to!string();
         writeQueue ~= '\n';
     }

     void writeAll()
     {
         foreach (msg; writeQueue)
             writeln(msg);
     }
}

And if you don't like that, you can instead accept IOWrappers by 
value and return them along with the result of your calculation 
in a Tuple. It's not pretty, but it works.


More information about the Digitalmars-d mailing list