[fpc-devel] Progress on pure functions
J. Gareth Moreton
gareth at moreton-family.com
Tue Dec 13 07:21:40 CET 2022
Hi everyone,
I've made a bit of a breakthrough with the development of pure
functions. I've successfully managed to get the compiler to calculate
the factorial as a pure function in two different forms... one usig a
for-loop, and one using a recursive call (which is where it differs from
'inline').
It's nowhere near ready and I haven't tested floating point numbers or
strings yet (and error messages and warnings etc. are still lacking).
Only const and value parameters are accepted currently. I haven't
included support for "out" parameters because functions that return a
value and have an "out" parameter aren't inlined and would be a little
bit tricky to build a valid node tree for.
Find it here: https://gitlab.com/CuriousKit/optimisations/-/commits/pure
I welcome anyone to test it out and try to break it! To confirm if the
compiler has interpreted a subroutine as a pure function, the best way
is to look at the node tree with DEBUG_NODE_XML, specifically the result
of the "firstpass" section.
I've also attached two code examples that contain the factorial functions.
Kit
-------------- next part --------------
program pure1a;
{$MODE OBJFPC}
{$COPERATORS ON}
function Factorial(N: Cardinal): Cardinal; pure;
var
X: Integer;
begin
Result := 1;
for X := N downto 2 do
Result *= X;
end;
begin
WriteLn(Factorial(5));
end.
-------------- next part --------------
program pure1b;
{$MODE OBJFPC}
function Factorial(N: Cardinal): Cardinal; pure;
var
X: Integer;
begin
if N < 2 then
Result := 1
else
Result := N * Factorial(N - 1);
end;
begin
WriteLn(Factorial(5));
end.
More information about the fpc-devel
mailing list