[fpc-devel] Progress on pure functions

Sven Barth pascaldragon at googlemail.com
Wed Dec 14 11:18:54 CET 2022


J. Gareth Moreton via fpc-devel <fpc-devel at lists.freepascal.org> schrieb am
Di., 13. Dez. 2022, 22:09:

> 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).
>

Wouldn't it make more sense to ensure that the Str() and Val() intrinsic
work correctly inside "pure" functions? After all the compiler can then
simply evaluate the inlinen nodes and does not have to "interpret" a ton of
other code as well.

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20221214/05c1e705/attachment.htm>


More information about the fpc-devel mailing list