[fpc-devel] Progress on pure functions
J. Gareth Moreton
gareth at moreton-family.com
Tue Dec 13 22:09:37 CET 2022
The next big milestone that I want to achieve is to make this a pure
function:
procedure int_str_unsigned(l:longword;out s:shortstring); pure;
var
m1 : longword;
pcstart,
pc2start,
pc,pc2 : pchar;
hs : string[32];
overflow : longint;
begin
pc2start:=@s[1];
pc2:=pc2start;
pcstart:=pchar(@hs[0]);
pc:=pcstart;
repeat
inc(pc);
m1:=l div 10;
pc^:=char(l-(m1*10)+byte('0'));
l:=m1;
until l=0;
overflow:=(pc-pcstart)-high(s);
if overflow>0 then
inc(pcstart,overflow);
while (pc>pcstart) do
begin
pc2^:=pc^;
inc(pc2);
dec(pc);
end;
s[0]:=char(pc2-pc2start);
end;
This is essentially the core internal function that drives IntToStr and
similar functions. The challenges here include:
- A repeat...until loop with no obvious termination sequence.
- Using a pointer to access an array offset of a local variable.
- Writing characters (and the length field) one at a time to a shortstring.
The reason for wishing to make IntToStr a pure function is that for a
given input, the output will never change, and it's perfectly feasible
for some other function to call IntToStr as part of a string generation
routine and which would otherwise itself be a pure function (if a pure
function wishes to call another function, it must also be determined to
be pure... see pure1b.pp for the recursive example where the actual
parameter isn't even a constant, but is nonetheless deterministic).
Kit
On 13/12/2022 06:21, J. Gareth Moreton via fpc-devel wrote:
> 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
>
> _______________________________________________
> fpc-devel maillist - fpc-devel at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel
More information about the fpc-devel
mailing list