[fpc-devel] Pure function development

Jonas Maebe jonas at freepascal.org
Wed Apr 29 23:38:44 CEST 2020


On 29/04/2020 23:15, Sven Barth via fpc-devel wrote:
> Assuming we want to have support for constant evaluation of functions
> (and I do admit that sometimes that is a really nice to have), I don't
> really see a way around marking such functions somehow, cause otherwise
> we'd have to store the node trees of all functions that we detect as
> pure in the PPU.

Detection of pure functions (or what LLVM calls read-only) functions is
useful in its own right, e.g. for loop hoisting (like in Gareth's
example). You preferably don't limit that to functions that have been
manually annotated as "pure".

And if you have to do that anyway, then also storing the node tree is
not that much extra work. Whether or not you actually evaluate/inline
that entire node tree, depends on the inline settings (most compilers
have tuning parameters that allow you to set complexity limits for that).

Being able to call arbitrary functions (marked as "pure") in
declarations of constants is indeed also the only real use-case I see
for manually marking them as "pure". After all, you don't want to be in
the situation where you call a function from a third party unit as part
of a constant declaration, and then get a compile error with the next
version of that unit because that same function happens to be no longer
pure (or the compiler can't prove it anymore). It's part of an interface
contract in that way.

However, that is also it's biggest downside: I think this can easily
lead to issues if the clean way to implement a change would be by making
a previously "pure" function non-pure. You then can't do that because it
would break users of your code that rely on this function being pure, so
you have to program around that (i.e., you painted yourself into a
corner). It's similar to how you can easily get into issues with
non-trivial "const" methods in C++, where one removal of "const" can
cascade into hundreds of errors all over the place.

And while I have encountered cases where I would have liked to be able
to call a particular function in a constant declaration, it doesn't
happen often enough that I perceive it as something that is really missing.


Jonas


More information about the fpc-devel mailing list