Purely stack-based generators

Walter Bright newshound1 at digitalmars.com
Thu Mar 18 12:27:47 PDT 2010


Andrei Alexandrescu wrote:
> On 03/18/2010 01:49 PM, Walter Bright wrote:
>> Norbert Nemec wrote:
>>> Regan Heath wrote:
>>>> So, these generators are essentially inline functions?
>>>
>>> No. They may be inlined, but this is just an optimization just like
>>> for regular functions. If they are not inlined, these generators are
>>> simply functions with a special calling convention that allows them to
>>> retain their local data and execution point on the stack in between
>>> calls.
>>>
>>> I did work out the assembly code for this some time ago and it worked
>>> nicely. Very similar to what is needed for co-routines, but it is
>>> possible to do everything on the stack.
>>
>> How is that different from a local delegate that refers to local
>> variables of the function it is lexically nested in?
> 
> I think the difference is that e.g. a coroutine can repeatedly return 
> values from a loop. In contrast, the delegate must keep the state 
> separate, which may be a tad more complicated.

Right, the delegate would have to keep its persistent state in outer locals.

The trouble with a generator using the caller's stack is that then the generator 
cannot recursively call itself (such as if it was walking a tree). In order to 
work properly in the general case, a generator has to allocate all its local 
variables on the heap.



More information about the Digitalmars-d mailing list