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

Eugene Wissner belka at caraus.de
Thu Apr 18 18:33:33 UTC 2019


On Thursday, 18 April 2019 at 14:52:53 UTC, Jonathan M Davis 
wrote:
> pure means that the function does not access mutable, global 
> state except via the function's arguments. That's it. nd the 
> compiler _is_ able to do stuff with that and does so right now.

That compiler actually does something with pure is new to me. So 
I was wrong here.

> It will elide function calls (though under such restricted 
> circumstances that it's not really worth it), but the bigger 
> gains come from how it helps the type system. For instance,
>
> Foo* foo(int i) pure { return new Foo(i); }
>
> immutable f = foo();

I'm not really convinced this pattern is useful, but fine there 
are may be different use cases, I'm not familiar with. But this 
doesn't even work under similar circumstances:

int* foo() pure
{
     return new int(5);
}

immutable f = foo();

gives: cannot use non-constant CTFE pointer in an initializer 
`&[5][0]`

> Something like func(42) * func(42) will result in a call being 
> elided if func is pure, but even splitting it up onto two lines 
> kills that. e.g.
>
> auto f = func(42);
> f = func(42) * f;

I've just tested it and if I don't miss something, no call 
elision is done. GDC eliminates actually the call if it has the 
source code, but GDC does it whether the function is pure or not. 
I also don't see how it may be possible.

size_t foo() pure
{
     return cast(size_t) new int(5);
}

It is a perfectly valid pure function, that doesn't depend on any 
global state, doesn't have arguments, without casting away the 
impurity, but it returns different values every time.

> I don't get this. pure is fairly well understood.

Thinking of the last discussion about pure, just before 
pureMalloc was introduced, I got a different feeling, but well, 
it kind of does, what the specification says.

I also don't find Haskell's purity "insane", but actually very 
useful and solid, so I might be biased torwards "strong purity" 
or "no purity at all".




More information about the Digitalmars-d mailing list