Passive procs are Nimony's mechanism for structured concurrency and asynchronous IO
without callbacks, futures, or colored functions. A proc annotated with .passive
is transformed by the compiler into a state machine via CPS (Continuation Passing Style).
type
ContinuationProc* = proc (coro: ptr CoroutineBase): Continuation {.nimcall.}
Continuation* = object
fn*: ContinuationProc
env*: ptr CoroutineBase
CoroutineBase* = object of RootObj
caller*: ContinuationA Continuation is a pair of (function pointer, environment pointer). When fn is nil,
the coroutine is finished. The caller field links back to the calling coroutine so that
when a passive proc completes, execution returns to its caller.
Not all continuations are freely movable across threads. Continuations produced by
delay(call) may be scheduled on another thread, subject to sendability checks for the
captured environment. Continuations produced by delay() capture the continuation for
the code following the nearest suspend() and are thread-affine: they are expected to
resume on the same thread.
Because the continuation delay(call) produces is owned by a scheduler rather than by
the code that built it, the callee's parameters must not be aliases of the building
frame. A var, out or lent parameter is exactly that: the coroutine frame stores it
as a bare pointer into the caller, and in the spawn shape
submit(delay(handle(c)), -1) # `handle` runs later, possibly on another threadthe caller has moved on — reassigned c, or returned and run its destructors — long
before the chain reads it. Nothing at the point of use says so, and the failure is a
read of freed memory, so delay rejects such a callee outright:
Error: `delay` hands `handle` to a scheduler, so its continuation can outlive this
frame; parameter `c: var HttpConnection` would alias a location that is already gone.
Take it as `sink` instead
sink is the answer: it moves ownership into the coroutine frame, which is what makes
the frame's lifetime self-sufficient. The rule is specific to delay — an ordinary
passive call suspends its caller, whose frame is therefore alive for the whole of the
callee, so var parameters stay legal there.
A passive proc looks like ordinary sequential code:
proc myecho(x: string) {.passive.} =
echo x
proc greet(name: string) {.passive.} =
for i in 0..<3:
myecho "hello " & nameCalling one passive proc from another is a suspension point — the compiler splits the caller into states around each such call. The programmer does not need to think about this.
- NJ (control flow graph): The proc body is lowered to NJ IR with structured control flow
(
loop,ite,mflag/vflagguards). - CPS transform (
src/hexer/cps.nim): The NJ graph is split at suspension points (calls to other passive procs) into state functions. Local variables are lifted into a heap-allocated coroutine environment object.
For a passive proc foo(x: int), the compiler generates:
- A coroutine type:
FooCoroutine = object of CoroutineBasecontaining lifted locals. - A wrapper function (
foo_init) that allocates the coroutine frame viaallocFrameand delegates to the entry function. The wrapper signature isfoo_init(x: int, result: ptr int, caller: Continuation). This wrapper is essential for method calls where the concrete type is unknown at compile time. - An entry function (
foo) that takes the pre-allocated frame, initializes the environment (this[] = FooCoroutine(...)), and runs the first state. - State functions
s0,s1, ... that each execute code up to the next suspension point and return aContinuationpointing to the next state (or tocallerwhen done).
Running a passive proc is a simple loop:
var c = c
while not stopping(c):
c = scheduler(c)Each call to scheduler(c) executes one state transition (advance(c) does exactly one).
The default scheduler is trivialTick which simply calls c.fn(c.env). The loop stops
when the continuation has no next step — when the coroutine finished or parked.
complete(c) runs c, fresh from delay(call), to completion, parks included, and
it is what a call from regular, non-passive code turns into (see Non-passive calls
below). It makes itself the coroutine's caller — a system.Join on its own stack — and
runs the loop above; if the coroutine parked, it then waits until the coroutine's last
state has run that Join, on whichever thread resumed it. The call is mediated by the
active scheduler rather than by a direct stack call; with the default scheduler it behaves
like ordinary synchronous execution, and when the callee parks on I/O the regular caller
waits for it like a blocking call would.
The scheduler is a pluggable function:
type Scheduler* = proc (c: Continuation): Continuation {.nimcall.}
proc setScheduler*(handler: Scheduler)A custom scheduler can integrate with a thread pool or bridge to an IO event loop.
Interleaving unrelated continuations belongs at enqueue/resume boundaries (for example
submit on the thread pool), not by keeping a trampoline running across unreturned
regular-proc stack frames.
When a coroutine parks (suspend() returns Continuation(fn: nil, env: frame)) or
yields to other work, the scheduler lets the current trampoline stop:
- Store the continuation that should resume later (for example in an IoRing slot via
delay(), or on the thread-pool run queue). - Return the parked continuation (or let
trivialTickpass it through) so that the trampoline can detect parking viaparked(c)and exit. - Resume later from a clean entry point (for example
submit(cont)on a pool worker or the loop above on the captured resume continuation).
A park never ends a call made from a regular proc: that caller keeps waiting (and, with
the thread pool running, keeps doing a worker's turn — setPassiveWaitHook) until the
callee's last state has run. So a regular proc between two passive calls holds its
hardware stack frame for as long as its callee is parked, exactly like a blocking call.
A scheduler must not dispatch unrelated continuations inside a trampoline. A
pathological example is a scheduler that, on every suspend(), pops the next continuation
from a shared queue and feeds it back into the same loop: every
passive → regular → passive link it runs through keeps a regular proc's frame alive, so
thousands of such interleavings can overflow the hardware stack even though
passive-to-passive depth is bounded by the heap. The production thread pool avoids this
by taking one continuation step per dequeue, not going through setScheduler, and not
resubmitting after suspend().
Practical rule: on suspend or when handing off, enqueue and return; interleave at
submit() boundaries where stacks are clean. On hot paths, mark regular procs between two
suspending passive calls {.passive.} as well so the chain stays on heap-allocated frames
and a park frees the thread instead of blocking it.
Passive procs define the language-level suspension and continuation mechanism. The active scheduler decides how runnable continuations are interleaved and how external events resume them.
Language-level semantics:
- Calls to passive procs are suspension points for passive callers.
delay(call)captures a child continuation and may require sendability checks.delay()captures the continuation for the code following the nearestsuspend()and keeps thread affinity.- Regular procs can call passive procs; the compiler drives them to completion through the active scheduler.
Scheduler/runtime policy:
- On
suspend()or yield: enqueue the continuation and return so hardware stack frames unwind before unrelated work runs (see Scheduler contract above). - Fairness and run-queue strategy.
- Thread-pool work stealing and placement.
- IO backend details (
epoll,kqueue,io_uring, etc.). - Timeouts, retries, registration strategy, and wakeup policy.
- Integration with a reactor, executor, or custom runtime.
The fundamental IO primitive is a passive proc that suspends the coroutine and registers interest in a file descriptor:
proc ioWait(fd: cint) {.passive.} =
let c = delay() # capture: continuation for code after suspend()
ioRing.store(fd, c) # register with the event loop
suspend() # stop the trampoline; ioRing resumes c when fd is readyHigher-level IO operations compose on top of ioWait:
proc readLine(fd: cint): string {.passive.} =
ioWait(fd) # suspend until fd is readable
result = ""
var ch: char = '\0'
while true:
let n = posixRead(fd, addr ch, 1)
if n <= 0 or ch == '\n':
break
result.add chApplication code reads like blocking IO:
proc handleClient(fd: cint) {.passive.} =
while true:
let line = readLine(fd)
if line.len == 0: break
echo "echo: " & lineThe key insight is that readLine looks identical to a blocking implementation. The compiler
handles the suspension mechanics. There are no callbacks, no await, no future types.
The scheduler bridges passive procs to the OS event loop:
- A passive proc calls
ioWait(fd). ioWaitstores the current continuation in the IoRing's slot for that fd and parks viasuspend()—Continuation(fn: nil, env: this).- The IoRing polls (
epoll/kqueue/io_uring) for ready file descriptors. - When an fd becomes ready, the IoRing retrieves the stored continuation and feeds it
back into the pool (
submit), resuming the coroutine from where it left off.
This model means a single thread can handle thousands of concurrent connections with each handler written as a simple sequential loop.
delay(passiveCall())captures a passive call as aContinuationwithout running it. Think of it astoTaskfor coroutines. Because this continuation may be handed to another thread, the compiler checks that the captured environment is sendable (for example, unique or atomically reference-counted).delay()without any argument captures the continuation for the code following the nearestsuspend()— "the rest of me from that point" as aContinuation. The CPS transform replaces it withContinuation(fn: s_next, env: this)pointing at the state function after thesuspend(). This form is thread-affine: it assumes the continuation will later resume on the same thread that captured it. Always used together with a followingsuspend()call, with setup code (e.g. registering with an IO backend) in between.suspend()parks the coroutine by returningContinuation(fn: nil, env: this). This stops the trampoline but preserves coroutine identity so schedulers can distinguish parked (fn == nil,env != nil) from finished (fn == nil,env == nil). Always paired with a precedingdelay()that captures the resume point first. The code betweendelay()andsuspend()is the setup window — it runs synchronously before suspension and must not contain calls to other passive procs.advance(c)single-steps through one state transition. Useful for interleaving coroutines manually.
delay(call) and delay() combine to give real fork semantics. delay(call) captures a child
task, delay() captures the parent's continuation. Both are handed to the scheduler
and neither runs until the scheduler picks them up:
template spawn(call: typed) =
let taskA = delay(call) # child coroutine's continuation
let taskB = delay() # MY OWN continuation (code after the `suspend` call)
scheduler.run taskA
scheduler.run taskB
suspend()After spawn, the current coroutine is suspended — it does not continue past the spawn
point. Instead, both the child and the parent's "rest" are placed in the scheduler's
run queue. The scheduler decides the execution order.
Example:
proc worker(x: int) {.passive.} =
echo "worker: ", x
proc main() {.passive.} =
echo "before spawn"
spawn worker(42)
echo "after spawn" # runs when the scheduler picks up taskBThe CPS transform splits main at the spawn point into two states. The code before
spawn runs immediately; the code after spawn becomes a separate state function that
only runs when the scheduler resumes it. This means:
- Controlled concurrency: The child and parent are independent continuations. A thread-pool
scheduler may run the child on another thread if its captured environment is sendable,
while the parent's own continuation remains thread-affine because it comes from
delay(). - No implicit ordering: Unlike async/await where the parent continues until it hits an await, here the parent yields immediately. The scheduler has full control.
- Composable with IO: A spawned task can call
ioWait,readLine, etc. The scheduler manages both compute tasks and IO-blocked tasks uniformly.
A .passive iterator's caller is the loop's Join (system), just like a regular
proc's complete. A yield records
where the iterator continues (iterYield) and hands control to that caller; finishing
leaves the record empty. So a loop learns that a step ended because its own continuation
runs — never by comparing frames: a passive proc the iterator calls returns into the
iterator's frame without that being a yield.
- In a regular routine each step is
iterNext: the step runs to its end the waycompleteruns a call, parks included. - In a passive routine advancing the iterator is a suspension point
(
iterAdvance, lowered toiterSwitch, which makes the loop's next state theJoin's owncaller): the loop is laid out as ordinary code before the CPS split, so a park in the iterator parks the enclosing coroutine and the loop body may suspend too.
Leaving a loop early closes the iterator through Join's =destroy. Lambdalifting
declares the cell as an ordinary local, before the destroyer runs, so the destroyer covers
every way out of its scope — break, return, raise — even in a passive loop that
spans several state procs.
.closure iterators keep their own protocol (caller.fn as the resume slot).
Join and the iter* procs are compiler-internal: nothing in system exports them,
and no program names them. setPassiveWaitHook is the one exported addition, because the
thread pool installs it.
Every passive proc's coroutine environment (FooCoroutine) is either heap-allocated or
stack-allocated depending on the calling context.
When a passive proc calls another passive proc, the callee's environment is allocated with
allocFrame (heap). The generated init function stores a self-pointer in the callee field
of CoroutineBase during initialization. When the callee finishes its final state function,
it calls deallocFrame:
proc deallocFrame*(frame: ptr CoroutineBase) =
if frame.callee != nil and frame.caller.fn != nil:
dealloc(frame)Both conditions must hold:
callee != nil— the frame is heap-allocated (set toselfduring init).caller.fn != nil— the frame was invoked with a real continuation (passive-to-passive), not from a non-passive caller with a nil stop-continuation.
When non-passive code calls a passive proc, the compiler generates a local stack variable for
the environment, passes its address to the init function, and then runs the passive call to
completion via complete:
var coroVar: FooCoroutine # on the caller's hardware stack
let contVar = `foo`(args, addr coroVar, stopContinuation)
complete(contVar)complete makes its Join the callee's caller. Running it — which is what the callee's
last state does, on whichever thread resumed it — marks the call as done. complete
first trampolines on this thread; if the callee parked, it then waits for that mark,
calling the wait hook meanwhile (setPassiveWaitHook). The thread pool installs one
that does a worker's turn: run queued tasks and poll this thread's I/O lane — which is
required, since a non-worker's ring ops complete only through its own poll.
The wait is not optional. The frame and the callee's result pointer both point into the regular caller's stack frame, so returning while the callee is parked would leave it writing into a frame that is gone.
coroVar.callee is set to nil, which marks the frame as stack-allocated: deallocFrame
leaves it alone when the callee finishes.
A regular proc that wants the continuation without waiting for it asks for it
explicitly with delay foo(args) and drives it itself (advance), or hands it to the
pool (submit); a park is then the scheduler's (or the caller's) business to resume.
Note: This optimization only applies to regular procedure calls. For passive methods, dynamic dispatch prevents the inlining strategy above, so we must still call via the wrapper and allocate on heap.
CoroutineBase.callee serves two purposes: it is a self-pointer in heap-allocated frames
(enabling deallocFrame to detect them), and it is reserved for future cancellation support
to walk the chain of active coroutines.
Non-void passive procs pass their return value through a pointer parameter. The caller
allocates a field for the result in its own coroutine environment and passes addr to that
field when invoking the callee.
For example, proc io2(): int {.passive.} is compiled as:
# Generated wrapper for io2 (allocates frame, delegates to entry)
proc io2_init(result: ptr int; caller: Continuation): Continuation =
let this = cast[ptr Io2Coro](allocFrame(sizeof(Io2Coro)))
return io2(this, result, caller)
# Entry function (takes pre-allocated frame, initializes environment)
proc io2(this: ptr Io2Coro; result: ptr int; caller: Continuation): Continuation =
this[] = Io2Coro(resultPtr: result, caller: caller, callee: cast[ptr CoroutineBase](this))
return io2_s0(this)
# State s0: runs to completion (no suspension points in this example)
proc io2_s0(this: ptr Io2Coro): Continuation =
this.resultPtr[] = 0 # return 0
let tmpCaller = this.caller
deallocFrame(cast[ptr CoroutineBase](this))
return tmpCallerThe wrapper signature is foo_init(...args, result: ptr int, caller: Continuation) for non-void,
or foo_init(...args, caller: Continuation) for void. It allocates the frame and delegates to
foo(...args, this, ...).
On the calling side, main2 stores the return value in a lifted field of its own coro struct and reads it after the callee completes:
# Generated state for main2
proc main2_s0(caller: Continuation): Continuation =
# ...
let contVar = io2_init(
addr this.x, # result pointer into main2's coro struct
Continuation(fn: main2_s1, env: cast[ptr CoroutineBase](this))) # resume when done
return contVar
# State function: runs after io2 completes
proc main2_s1(this: ptr Main2Coro): Continuation =
# this.x is now populated by io2
echo this.x
# ...This eliminates any need for dynamic allocation to return values across suspension points. The result lives in the caller's already-heap-allocated environment and is valid as long as the caller is alive.
- No colored functions: Passive procs can call regular procs freely. Regular procs
can also call passive procs — the compiler inserts a
completecall automatically so the call is driven to completion through the active scheduler, parks included. With the default scheduler this is synchronous; while the callee is parked the waiting thread does pool work and drives its own I/O.delay(call)is the explicit override when you want the continuation without running it. - Zero-overhead when not used: If a program has no
.passiveprocs, no CPS transform runs and no runtime types are involved. - Composable: Passive procs call other passive procs with ordinary call syntax. The compiler chains the continuations automatically.
- Destructor safety: Destructors are injected before CPS lowering. After lifting locals into the coroutine environment, destroying them at scope exit remains ordinary transformed code rather than a special case invented by the CPS pass.
- Cancellation: Cancellation semantics are intentionally left unspecified for now. Different schedulers may choose different policies; the language mechanism only needs the ability to stop rescheduling a continuation and eventually destroy its environment safely.
- Stack safety: The trampoline loop means no deep recursion. Each state function returns to the trampoline rather than calling the next state directly.