Skip to content

Closure iterators #1822

@blackmius

Description

@blackmius

still not sure should closure iterator change its api from what it is in nim2.0

first option is to preserve old api, which also makes cps transform easier for calls, but requires lambdalift and cps handle it together and looks it will work slower than in nim 2.0

second option is to transform iterators so they start returning next continutation and result at once via tuple, but it will require to transform each call site and it totaly changes logic of calling x twice and etc

import std/syncio

block:
    proc myiter1(): proc(): int {.closure, passive.} =
        var cont = Continuation()
        var iter_result = 0
        proc body() {.passive, closure.} =
            iter_result = 1
            cont = delay()
            suspend cont.env.caller
            iter_result = 2
            cont = delay()
            suspend cont.env.caller
            iter_result = 3
            cont = Continuation()
        cont = delay body()
        return proc(): int {.closure, passive.} =
            var this = delay()
            cont.env.caller = this
            suspend cont
            return iter_result

    type 
        EnvData = object of RootObj
            cont: Continuation
            iterResult: int64
        Env = object of RootObj
            d: EnvData
        Closure = tuple
            fn: proc ()
            env: ptr Env
        
    var x = myiter1()
    while cast[ptr Closure](x.addr)[].env[].d.cont.fn != nil:
        echo x()

block:
    proc myiter2(): (proc(): (Continuation, int) {.closure, passive.}) =
        var cont = Continuation()
        proc (): (Continuation, int) {.closure, passive.} =
            cont = delay()
            result = (cont, 1)
            suspend()
            cont = delay()
            result = (cont, 2)
            suspend()
            result = (Continuation(), 3)

    var x = myiter2()
    var iter = x()
    while true:
        echo iter[1]
        if iter[0].fn == nil:
            break
        iter[0].complete()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions