Hairy Pixels <generic...@gmail.com> schrieb am Fr., 3. Nov. 2023, 02:00:

>
>
> > On Nov 2, 2023, at 1:44 PM, Sven Barth <pascaldra...@googlemail.com>
> wrote:
> >
> > Now for nested as well as anonymous routines the compiler determines
> whether a capturer is required at the point that the nested or anonymous
> routine is assigned to a function reference (cause otherwise it can be
> handled as a nested function or even a function or method pointer). This
> requirement is detected during the parsing of the routine.
>
> On second thought I had some questions about this part. From what I see
> FPC always allocates the interface when reference pointers are used but
> what you write suggests maybe the compiler will demote the type to
> something more optimized (like a nested function). We talked about this at
> length before but I don't think anything was decided yet.
>
> for example:
>
> procedure DoThis;
> var
>   proc: reference to procedure;
> begin
>   proc := procedure
>           begin
>           end;
>   proc();
> end;
>
> doesn't need the heap allocated instance because the function reference
> never escapes the scope and it has no captured variables so it could be
> demoted to a global function even of nested.
>

As soon as an anonymous function gets assigned to a function reference it
*must* be converted to a method of the capturer and an interface to that
must be assigned to the function reference. Because that's what function
references are: interfaces.

If you don't want that then call the anonymous function directly without
assigning it to anything or assign it to a nested function pointer and call
that.

In *theory* the compiler could detect that "proc" doesn't leave the scope
and that it's value is "constant" (namely a function) and thus could
optimize that, but that requires quite some improvements to the optimizer.


> In fact Swift requires you to mark closures types as "@escaping" if they
> can escape the current scope so that the compiler can be optimize them.
> This is the feature I was thinking FPC needs.
>

By default the purpose of anonymous functions assigned to function
references *is* that they can escape their scope. This will not change,
because they were after all introduced for Delphi-compatibility and there
won't be any designations that the value can't escape. If the compiler
can't figure it out by its own (see above) then tough luck; use a feature
better suited for that.

Regards,
Sven

>
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to