Closures and closures iterators


At a low-level

Closures and closures iterators are implemented via a pointer + an environment that stores the captured state necessary to execute the function.

The Nim compiler has a limited form of borrow checking and prevents capturing mutable variable or openArray (pointer+length pair).

It otherwise copies the capture variables in case of objects with value semantics or increment the reference count in case of ref object.

The Chronos library needs to generate a closure iterator for all async proc instantiated which may lead to long-lived ref objects and unreclaimable memory.

This may also extend to other resources like socket connections or file descriptors and a significant effort is underway to track memory usage and detect such scenarios: