[fpc-pascal] Creating capturers

Sven Barth pascaldragon at googlemail.com
Thu Nov 2 07:44:10 CET 2023


Am 01.11.2023 um 06:18 schrieb Hairy Pixels via fpc-pascal:
> I'm curious how the capturer is created in the case of anonymous functions. I know the function needs to create a capturer when nested functions are declared but what happens if there is an anonymous function which is declared in the code section?
>
> I think the compiler will only know about the requirement to create a capturer at this point but local variables have already been assigned so do they need to do an extra copy to the capturer when it's created?
>
> With nested function this is not a problem since the capturer can be created before any locals are assigned and thus not copying is needed, if I understand correctly.

The most important piece of knowledge is that in a routine with nested 
(or anonymous) routines the nested (or anonymous) routines aren't 
compiled down to machine code right away. The compiler first parses the 
whole hierarchy until it's on the global/method level again and only 
*then* it compiles the outermost routine followed by the nested ones.

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.

If the routine requires a capturer then after the whole hierarchy has 
been parsed, then all the captured variables will be moved from the 
local symtable of the routine to the capturer or corresponding capture 
variables for parameters will be introduced and then the whole nodetree 
will be walked to adjust usages of the involved symbols.

So, no, there is no copy involved (except for parameter values right at 
the start of a routine where a parameter is captured) as the whole 
variables are relocated into the capturer and they're only ever accessed 
from there.

Regards,
Sven


More information about the fpc-pascal mailing list