Improvement in pure functions specification
Andrei Alexandrescu via Digitalmars-d
digitalmars-d at puremagic.com
Wed Dec 21 13:34:04 PST 2016
On 12/21/2016 03:04 PM, Johan Engelen wrote:
> On Wednesday, 21 December 2016 at 15:40:42 UTC, Andrei Alexandrescu wrote:
>> On 12/20/2016 05:49 PM, Andrei Alexandrescu wrote:
>>> https://github.com/dlang/dlang.org/pull/1528 -- Andrei
>>
>> Dropped the void functions. On to the next scandal:
>
> I think you should be very careful in making sure that `pure` does not
> become a pessimization keyword.
>
> ```
> $(P Any `pure` function that is not strongly pure cannot be memoized. The
> compiler is required to honor all calls to the function, even if it
> appears
> to do nothing. (Example: a pure function taking no arguments and
> returning
> `int*` cannot be memoized. It also should not because it may be a
> typical
> factory function returning a fresh pointer with each call.))
> ```
> I don't know what "required to honor all calls" means, but I guess it means
> ```
> auto a = foo(); // int* foo() pure;
> auto b = foo();
> ```
> cannot be transformed to
> ```
> auto a = foo(); // int* foo() pure;
> auto b = a;
> ```
That is correct.
> Super contrived, but I hope you get my drift:
> ```
> int *awesome() pure {
> static if (ohSoAwesome) {
> return new int;
> } else {
> return null;
> }
> }
> ```
Where does ohSoAwesome come from?
> Tagging this function with `pure` would be a pessimization.
Not to worry. It's all up to what can be detected. If inlining is in
effect then definitely things can be optimized appropriately.
> Instead of
> "Any `pure` function that is not strongly pure cannot be memoized."
> why not
> "Any `pure` function that is not strongly pure _may not be assumed to
> be_ memoizable."
Got it. Good point. Will do.
> Another example:
> ```
> /// Note: need to mark this function as non-pure, because otherwise the
> compiler deduces it as pure and then pessimizes our code.
> int *bar(bool returnNull) nonpure {
> if (returnNull) {
> return null;
> } else {
> return new ...;
> }
> }
>
> auto a = bar(true);
> auto b = bar(true);
> auto c = bar(true);
> ```
>
> My concern with the current wording (like for the void function thing)
> is that it actively prohibits the compiler to do a transformation even
> if that is valid.
Yah, we kind of assume without stating that whole "observable behavior"
that C++ does.
Andrei
More information about the Digitalmars-d
mailing list