Store mutable indirections in immutable data with this one weird trick!

Dukc ajieskola at gmail.com
Sat Nov 13 15:01:08 UTC 2021


On Saturday, 13 November 2021 at 14:32:15 UTC, Paul Backus wrote:
> In a language where valid programs cannot distinguish between 
> different pointers to the same value, or observe the side 
> effects of memory allocation, it is natural to define `pure` 
> such that it allows memory allocation.
>
> D is not that kind of language.

I think it's supposed to be. Quoting the language spec:

> Implementation Defined: An implementation may assume that a 
> strongly pure function that returns a result without mutable 
> indirections will have the same effect for all invocations with 
> equivalent arguments. It is allowed to memoize the result of 
> the function under the assumption that equivalent parameters 
> always produce equivalent results. A strongly pure function may 
> still have behavior inconsistent with memoization by e.g. using 
> casts or by changing behavior depending on the address of its 
> parameters. An implementation is currently not required to 
> enforce validity of memoization in all cases. If a strongly 
> pure function throws an Exception or an Error, the assumptions 
> related to memoization do not carry to the thrown exception.

I think this means that while the language lets you to change 
what `pure auto foo(immutable(int)[])` returns based on the 
address of the argument, the language is allowed to cache the 
result as if you could not do that. The spec only talks about 
immutable references, but still.

>
> [1] Actually, the spec says that the compiler is allowed to 
> assume referential transparency anyway, which turns this from 
> an unfortunate limitation into a loaded foot-gun.

Ah, you already realized what I just said above. Yeah, it's an 
unfortunate trap but what do you do? Compiler optimisation is 
based on assumptions and assumptions usually necessiate pitfalls 
like this.

I think it would be a good idea to provide a compiler switch to 
disable `pure` assumptions for programs that want to give 
optimisations away for more reliability, but it shouldn't be a 
language rule.

Fortunately it's "only" implementation-defined thing - not fully 
undefined behaviour.


More information about the Digitalmars-d mailing list