feat(lua): add vim.async

Problem: Nvim has many Lua APIs that start callback-driven work: timers,
jobs, libuv handles, and other event-loop tasks. Callers that need to
sequence or cancel that work have to build their own coroutine wrappers,
task bookkeeping, and cleanup rules. This makes async control flow hard
to share, test, and document.

Solution: Add `vim.async`, a structured-concurrency module vendored from
async.nvim. It provides task handles, await/pawait helpers,
sleep/timeout helpers, completion-order iteration, and semaphores on top
of Nvim's event loop.

The API follows the same broad model as Trio: async work has an owner,
tasks are awaited explicitly, and cancellation is cooperative. Include
generated vimdoc with an introductory overview and examples, a news
entry, and functional tests for the new module.

AI-assisted
This commit is contained in:
Lewis Russell
2026-08-25 17:37:27 +01:00
committed by Lewis Russell
parent da4355ab8f
commit ce8a897f98
17 changed files with 5315 additions and 7 deletions

View File

@@ -21,6 +21,7 @@ for k, v in pairs({
secure = true,
snippet = true,
pack = true,
async = true,
_watch = true,
net = true,
pos = true,

View File

@@ -2,6 +2,27 @@
local M = {}
-- Generated from async.nvim/lua/async/_errors.lua: start
local nil_error = 'error(nil)'
--- Normalize a failed Lua operation for error slots where `nil` means success.
--- @param err any
--- @return any
--- @private
function M._normalize_error(err)
return err == nil and nil_error or err
end
--- Convert an error to a string without letting its metamethod interrupt cleanup.
--- @param err any
--- @return string
--- @private
function M._stringify_error(err)
local ok, message = pcall(tostring, err)
return ok and message or '<unprintable error>'
end
-- Generated from async.nvim/lua/async/_errors.lua: end
--- Adds one or more blank lines above or below the cursor.
--- @param above? boolean Place blank line(s) above the cursor
local function add_blank(above)

View File

@@ -66,6 +66,8 @@ vim.uv = ...
vim.F = require('vim.F')
vim._watch = require('vim._watch')
---@diagnostic disable-next-line: no-unknown
vim.async = require('vim.async')
vim.diagnostic = require('vim.diagnostic')
vim.filetype = require('vim.filetype')
vim.fs = require('vim.fs')

317
runtime/lua/vim/async.lua Normal file
View File

@@ -0,0 +1,317 @@
local core = require('vim.async._core')
local validate = vim.validate
local new_queue = require('vim.async._queue')
local runtime = require('vim.async._runtime')
local F = vim.F
--- Structured async API for Lua code that waits on event-loop work.
---
--- `vim.async` lets Lua code wait for timers, callbacks, and other tasks
--- without blocking Nvim's event loop. Async work runs inside tasks, which can
--- pause at checkpoints and manage child tasks created while they are running.
---
--- Start async work with [vim.async.run()]. Inside a task, use
--- [vim.async.await()] to wait for callback-style APIs or other tasks without
--- blocking the event loop. Use [vim.async.pawait()] when an awaited operation
--- can fail and the current task should continue.
---
--- Examples in this help use `local async = vim.async` for brevity.
---
--- Example: run async work without blocking Nvim:
---
--- ```lua
--- local async = vim.async
---
--- async.run(function()
--- vim.notify('waiting...')
--- async.sleep(1000)
--- vim.notify('done')
--- end)
--- ```
---
--- Example: await a callback-style API. Callback results are returned
--- unchanged, so an error-first callback still returns `err, value`:
---
--- ```lua
--- local async = vim.async
---
--- async.run(function()
--- local err, stat = async.await(2, fs_stat, 'notes.txt')
--- if err then
--- error(err, 0)
--- end
--- print(('notes.txt is %d bytes'):format(stat.size))
--- end)
--- ```
---
--- A task has two roles:
---
--- - it is a handle that can be awaited, waited for, or closed
--- - it is a scope for child tasks created while the task is running
---
--- [vim.async.run()] creates a task. A top-level task starts immediately. A
--- task created while another task is running becomes a child of that task, and
--- its function starts when the parent reaches its next checkpoint. A parent
--- task finishes only after its attached children finish. If a child fails
--- without being handled, the parent fails and closes the remaining children.
---
--- Use [Task:detach()] for background work that should keep running after the
--- current task finishes. A detached task becomes top-level work; the original
--- parent no longer waits for it or closes it.
---
--- Awaiting a task observes that task's result; it does not attach the task to
--- the awaiter or change which task owns it. Ownership is decided when the task
--- is created.
---
--- Scheduling is cooperative. When a task awaits a timer, I/O operation,
--- callback, or another task, `vim.async` saves the Lua stack and returns
--- control to the event loop. Other callbacks can run while the task is paused.
--- Nothing interrupts synchronous Lua code in the middle of a stack frame.
---
--- Checkpoints are the places where a task can pause, start pending child
--- tasks, observe cancellation, and receive unhandled child failures. Inside a
--- task, these operations are checkpoints:
---
--- - `vim.async.await(...)`
--- - `vim.async.pawait(...)`
--- - `vim.async.checkpoint()`
--- - successful return from the task function, which is the final checkpoint
--- for child management
---
--- Convenience APIs such as [vim.async.sleep()] and [vim.async.timeout()] can
--- also checkpoint because they call checkpointing APIs internally.
---
--- Closing a task closes its attached children. Cancellation is cooperative:
--- [Task:close()] marks a task as closing, and the task observes that state at
--- a checkpoint. If a task is suspended on a closable operation such as a timer
--- or child task, `vim.async` closes that operation before reporting the
--- cancellation.
---
--- Use [vim.async.await()] inside a task to suspend until work completes. It
--- accepts a task, a callback-taking function, or an argument position plus a
--- callback-taking function. `await(task)` returns the task result or raises
--- the task failure. [vim.async.pawait()] is the async counterpart to `pcall()`
--- for recoverable awaited-operation failures; it returns `ok, ...` instead of
--- failing the current task for that awaited operation. It does not suppress
--- cancellation or a failure already pending on the current task.
---
--- From synchronous code, use [Task:wait()] or [Task:pwait()] to pump the event
--- loop until the task completes. Use [Task:on_complete()] to observe
--- completion without blocking.
---
--- Coordination helpers work with task handles. [vim.async.iter()] yields
--- completed task handles in completion order, [vim.async.timeout()] awaits a
--- task with a deadline, and `vim.async.semaphore(permits)` creates a
--- [vim.async.Semaphore] that limits how many tasks can hold a permit for a
--- section at once.
--- @class vim.async: vim.async._core
local M = setmetatable({}, { __index = core })
M.semaphore = require('vim.async._semaphore')
--- @param unsubscribe fun()[]
local function unsubscribe_all(unsubscribe)
for _, unsub in ipairs(unsubscribe) do
unsub()
end
end
--- Create an async function from a callback-style function.
---
--- The callback is inserted at argument position `argc`. If `func` returns a
--- closable handle, it is closed when the awaiting task is cancelled.
---
--- This is a reusable wrapper around [vim.async.await()]. Use it when the same
--- callback API is awaited from more than one place.
---
--- ```lua
--- local async = vim.async
--- local fs_stat = async.wrap(2, vim.uv.fs_stat)
---
--- async.run(function()
--- local err, stat = fs_stat(vim.api.nvim_buf_get_name(0))
--- if not err and stat then
--- print(stat.size)
--- end
--- end)
--- ```
---
--- @generic T, R
--- @param argc integer
--- @param func fun(...: T..., callback: fun(...: R...)): vim.async.Closable?
--- @return async fun(...: T...): R...
function M.wrap(argc, func)
validate('argc', argc, 'number')
validate('func', func, 'callable')
--- @async
return function(...)
return M.await(argc, func, ...)
end
end
--- Iterate completed tasks in completion order.
---
--- The iterator yields task handles, not task results. Use
--- [vim.async.await()] or [vim.async.pawait()] to retrieve each result. The
--- tasks are observed in the order they complete, regardless of the order in
--- the input list.
---
--- ```lua
--- local async = vim.async
---
--- async.run(function()
--- local tasks = {
--- async.run(function() return 'cache', read_cache() end):detach(),
--- async.run(function() return 'disk', read_file() end):detach(),
--- }
---
--- for task in async.iter(tasks) do
--- local ok, source, text = async.pawait(task)
--- if ok then
--- for _, other in ipairs(tasks) do
--- if other ~= task then
--- other:close()
--- end
--- end
--- print(('loaded from %s'):format(source))
--- return text
--- end
--- end
--- end)
--- ```
---
--- If code must support PUC Lua 5.1, use the direct-call form instead of a
--- generic `for` loop. The iterator may need to suspend while waiting for the
--- next completed task, and PUC Lua 5.1 cannot yield from a generic-for
--- iterator call.
---
--- ```lua
--- local next_task = async.iter(tasks)
--- while true do
--- local task = next_task()
--- if task == nil then
--- break
--- end
--- async.await(task)
--- end
--- ```
--- @async
--- @generic R
--- @param tasks vim.async.Task<R>[] A list of tasks to wait for and iterate over.
--- @return async fun(): vim.async.Task<R>? iterator that yields each completed task.
function M.iter(tasks)
validate('tasks', tasks, 'table')
local remaining = #tasks
local queue = new_queue()
local unsubscribe = {} --- @type fun()[]
if remaining == 0 then
queue:put_nowait()
else
for _, task in ipairs(tasks) do
unsubscribe[#unsubscribe + 1] = task:on_complete(function()
remaining = remaining - 1
queue:put_nowait(task)
if remaining == 0 then
queue:put_nowait()
end
end)
end
end
local proxy = newproxy(true)
getmetatable(proxy).__gc = function()
unsubscribe_all(unsubscribe)
end
--- @async
return function()
local _ = proxy -- Keep the GC proxy alive with the iterator.
return queue:get()
end
end
--- Asynchronously sleep for a given duration.
---
--- Suspends the current task for the given duration without blocking the event
--- loop. After the delay and timer cleanup complete, `sleep()` returns to its
--- caller through the runtime's `schedule` hook.
---
--- ```lua
--- vim.async.run(function()
--- vim.async.sleep(100)
--- vim.notify('resumed later')
--- end)
--- ```
--- @async
--- @param duration integer ms
function M.sleep(duration)
validate('duration', duration, 'number')
M.await(function(callback)
local timer = runtime.new_timer()
timer:start(duration, 0, callback)
return timer
end)
-- Timer cleanup resumes this function directly from its close callback.
-- Yield once more so M.sleep() returns through the runtime scheduler.
M.await(runtime.schedule)
end
--- Await a task with a timeout.
---
--- If the task completes first, returns or raises the task result as
--- [vim.async.await()] would. If the deadline wins, closes the task and raises
--- `"timeout"` after the target task finishes cancellation cleanup.
---
--- ```lua
--- local async = vim.async
---
--- async.run(function()
--- local task = async.run(read_file, 'notes.txt')
--- local text = async.timeout(5000, task)
--- show_buffer(text)
--- end)
--- ```
--- @async
--- @generic R
--- @param duration integer Timeout duration in milliseconds
--- @param task vim.async.Task<R>
--- @return R...
function M.timeout(duration, task)
validate('duration', duration, 'number')
validate('task', task, 'table')
local timed_out = false
local timer = M.run('__timeout', function()
M.sleep(duration)
timed_out = true
task:close()
end)
--- @diagnostic disable-next-line: invisible
timer._hidden = true
local result = F.pack_len(M.pawait(task))
timer:close()
M.pawait(timer)
if timed_out then
error('timeout', 0)
end
if not result[1] then
error(result[2], 0)
end
return unpack(result, 2, result.n)
end
if type(vim) == 'table' then
runtime.config({
wait = vim.wait,
schedule = vim.schedule,
new_timer = vim.uv.new_timer,
})
end
return M

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,125 @@
-- LuaLS cannot model the generic annotations used by this vendored implementation.
---@diagnostic disable: no-unknown, undefined-doc-name, luadoc-miss-symbol, missing-return, missing-return-value, param-type-mismatch, return-type-mismatch, redundant-return-value, undefined-field, need-check-nil, await-in-sync
local async = require('vim.async._core')
local runtime = require('vim.async._runtime')
--- An event can be used to notify multiple tasks that some event has
--- happened. An Event object manages an internal flag that can be set to true
--- with the `set()` method and reset to `false` with the `clear()` method.
--- The `wait()` method blocks until the flag is set to `true`. The flag is
--- set to `false` initially.
--- @class vim.async.Event
--- @field private _is_set boolean
--- @field private _waiters (function|false)[]
local Event = {}
Event.__index = Event
--- @param waiters (function|false)[]
--- @return boolean
local function has_waiters(waiters)
for _, waiter in ipairs(waiters) do
if waiter then
return true
end
end
return false
end
--- Set the event.
---
--- All tasks waiting for event to be set will be awakened on a later event-loop
--- turn.
---
--- If `max_woken` is provided, only up to `max_woken` waiters will be woken.
--- If waiters are woken this way, the event is reset because the signal is
--- reserved for those waiters.
--- @param max_woken? integer
function Event:set(max_woken)
if self._is_set then
return
end
local limited = max_woken ~= nil
if not has_waiters(self._waiters) then
self._is_set = true
return
end
self._is_set = true
if limited then
-- The signal is reserved for existing waiters and will be assigned on the
-- scheduled turn. New waiters must not consume it first.
self._is_set = false
end
runtime.schedule(function()
local waiters = self._waiters
local waiters_to_notify = {} --- @type function[]
local limit = max_woken or math.huge
while #waiters > 0 and #waiters_to_notify < limit do
local waiter = table.remove(waiters, 1)
if waiter then
waiters_to_notify[#waiters_to_notify + 1] = waiter
end
end
if limited and #waiters_to_notify == 0 and not has_waiters(waiters) then
self._is_set = true
end
for _, waiter in ipairs(waiters_to_notify) do
waiter()
end
end)
end
--- Wait until the event is set.
---
--- If the event is set, return immediately. Otherwise block until another
--- task calls set().
--- @async
function Event:wait()
async.await(function(callback)
if self._is_set then
callback()
else
table.insert(self._waiters, callback)
return {
close = function(_, on_close)
-- set() compacts the waiter list, so cancellation cannot rely on the
-- original insertion index still pointing at this callback.
for i, waiter in ipairs(self._waiters) do
if waiter == callback then
self._waiters[i] = false
break
end
end
if on_close then
on_close()
end
end,
}
end
end)
end
--- Clear (unset) the event.
---
--- Tasks awaiting on wait() will now block until the set() method is called
--- again.
function Event:clear()
self._is_set = false
end
--- Create a new event.
---
--- An event can signal to multiple listeners to resume execution.
--- The event can be set from a non-async context.
--- @return vim.async.Event
return function()
return setmetatable({
_waiters = {},
_is_set = false,
}, Event)
end

View File

@@ -0,0 +1,77 @@
-- LuaLS cannot model the generic annotations used by this vendored implementation.
---@diagnostic disable: no-unknown, undefined-doc-name, luadoc-miss-symbol, missing-return, missing-return-value, param-type-mismatch, return-type-mismatch, redundant-return-value, undefined-field, need-check-nil, await-in-sync
local F = vim.F
local util = require('vim._core.util')
local Future = {}
Future.__index = Future
function Future:completed()
return self._err ~= nil or self._result ~= nil
end
function Future:result()
if not self:completed() then
error('Future has not completed', 2)
end
if self._err ~= nil then
return false, self._err
else
return true, F.unpack_len(self._result)
end
end
function Future:on_complete(callback)
if self:completed() then
-- Already completed or closed
if self._err ~= nil then
callback(self._err)
else
callback(nil, F.unpack_len(self._result))
end
return function() end
end
local id = self._callback_pos
self._callback_pos = id + 1
self._callbacks[id] = callback
return function()
self._callbacks[id] = nil
end
end
function Future:complete(err, ...)
if self:completed() then
error('Future is already completed', 2)
end
if err ~= nil then
self._err = err
else
self._result = F.pack_len(...)
end
local callbacks = self._callbacks
self._callbacks = {}
local errs = {} -- Need to use pairs to avoid gaps caused by removed callbacks
for _, cb in pairs(callbacks) do
local ok, cb_err = pcall(cb, err, ...)
if not ok then
errs[#errs + 1] = util._stringify_error(util._normalize_error(cb_err))
end
end
if #errs > 0 then
error(table.concat(errs, '\n'), 0)
end
end
return function()
return setmetatable({
_callbacks = {},
_callback_pos = 1,
}, Future)
end

View File

@@ -0,0 +1,107 @@
-- LuaLS cannot model the generic annotations used by this vendored implementation.
---@diagnostic disable: no-unknown, undefined-doc-name, luadoc-miss-symbol, missing-return, missing-return-value, param-type-mismatch, return-type-mismatch, redundant-return-value, undefined-field, need-check-nil, await-in-sync
local new_event = require('vim.async._event')
--- An optionally bounded FIFO queue for passing values between async tasks.
---
--- `put()` suspends the current task while the queue is full, and `get()`
--- suspends it while the queue is empty. The `put_nowait()` and `get_nowait()`
--- variants never suspend and raise an error when the operation cannot proceed.
--- @class vim.async.Queue<R>
--- @field private _non_empty vim.async.Event
--- @field package _non_full vim.async.Event
--- @field private _max_size? integer
--- @field private _items R[]
--- @field private _right_i integer
--- @field private _left_i integer
local Queue = {}
Queue.__index = Queue
--- Returns the number of items in the queue.
--- @return integer
function Queue:size()
return self._right_i - self._left_i
end
--- Returns the maximum number of items in the queue.
--- @return integer?
function Queue:max_size()
return self._max_size
end
--- Put an item into the queue.
---
--- If the queue is full, wait until a free slot is available.
--- @async
--- @param value any
function Queue:put(value)
while self:size() == self:max_size() do
self._non_full:wait()
end
self:put_nowait(value)
end
--- Get an item from the queue.
---
--- If the queue is empty, wait until an item is available.
--- @async
--- @return any
function Queue:get()
while self:size() == 0 do
self._non_empty:wait()
end
return self:get_nowait()
end
--- Get an item from the queue without blocking.
---
--- If the queue is empty, raise an error.
--- @return any
function Queue:get_nowait()
if self:size() == 0 then
error('Queue is empty', 2)
end
-- TODO(lewis6991): For a long_running queue, _left_i might overflow.
self._left_i = self._left_i + 1
local item = self._items[self._left_i]
self._items[self._left_i] = nil
if self._left_i == self._right_i then
self._non_empty:clear()
end
self._non_full:set(1)
return item
end
--- Put an item into the queue without blocking.
--- If no free slot is immediately available, raise "Queue is full" error.
--- @param value any
function Queue:put_nowait(value)
if self:size() == self:max_size() then
error('Queue is full', 2)
end
self._right_i = self._right_i + 1
self._items[self._right_i] = value
self._non_empty:set(1)
if self:size() == self:max_size() then
self._non_full:clear()
end
end
--- Create a new FIFO queue with async support.
--- @param max_size? integer The maximum number of items in the queue, defaults to no limit
--- @return vim.async.Queue<any>
return function(max_size)
local self = setmetatable({
_items = {},
_left_i = 0,
_right_i = 0,
_max_size = max_size,
_non_empty = new_event(),
_non_full = new_event(),
}, Queue)
self._non_full:set()
return self
end

View File

@@ -0,0 +1,46 @@
-- LuaLS cannot model the generic annotations used by this vendored implementation.
---@diagnostic disable: no-unknown, undefined-doc-name, luadoc-miss-symbol, missing-return, missing-return-value, param-type-mismatch, return-type-mismatch, redundant-return-value, undefined-field, need-check-nil, await-in-sync
local validate = vim.validate
--- @class vim.async.Timer: vim.async.Closable
--- @nodoc
--- @field start fun(self, timeout: integer, repeat_interval: integer, callback: fun())
--- @alias vim.async.TimerFactory fun(): vim.async.Timer
--- @nodoc
--- @class vim.async.ConfigOpts
--- @nodoc
--- @field wait? fun(timeout: integer, predicate: fun(): boolean): boolean Run the event loop until the predicate succeeds or the timeout expires.
--- @field schedule? fun(callback: fun()) Queue a callback to run once on a later event-loop turn.
--- @field new_timer? vim.async.TimerFactory Create libuv-compatible timers for `sleep()` and `timeout()`.
--- @field debug? boolean Capture task creation metadata for debugging.
--- @class vim.async.Runtime
--- @nodoc
--- @field wait fun(timeout: integer, predicate: fun(): boolean): boolean
--- @field schedule fun(callback: fun())
--- @field new_timer vim.async.TimerFactory
--- @field debug boolean
local M = {}
M.debug = false
--- @nodoc
--- @param opts vim.async.ConfigOpts
function M.config(opts)
validate('opts', opts, 'table')
validate('opts.wait', opts.wait, 'callable', true)
validate('opts.schedule', opts.schedule, 'callable', true)
validate('opts.new_timer', opts.new_timer, 'callable', true)
validate('opts.debug', opts.debug, 'boolean', true)
M.wait = opts.wait or M.wait
M.schedule = opts.schedule or M.schedule
M.new_timer = opts.new_timer or M.new_timer
if opts.debug ~= nil then
M.debug = opts.debug
end
end
return M

View File

@@ -0,0 +1,133 @@
-- LuaLS cannot model the generic annotations used by this vendored implementation.
---@diagnostic disable: no-unknown, undefined-doc-name, luadoc-miss-symbol, missing-return, missing-return-value, param-type-mismatch, return-type-mismatch, redundant-return-value, undefined-field, need-check-nil, await-in-sync
local F = vim.F
local new_event = require('vim.async._event')
local pcall = pcall
do
local ok, coxpcall = pcall(require, 'coxpcall')
if ok and type(coxpcall) == 'table' and type(coxpcall.pcall) == 'function' then
pcall = coxpcall.pcall
end
end
local validate = vim.validate
--- A semaphore manages an internal permit counter. [Semaphore:acquire()]
--- consumes one permit and [Semaphore:release()] returns one permit. If no
--- permits are available, `acquire()` suspends the current task until another
--- task releases one.
---
--- The preferred way to use a Semaphore is with the `with()` method, which
--- automatically acquires and releases the semaphore around a function call.
--- This is useful for limiting sections that start external work and then
--- await it, such as file reads, requests, or subprocesses.
---
--- ```lua
--- local async = vim.async
---
--- async.run(function()
--- local limit = async.semaphore(4)
--- local tasks = {}
---
--- for _, path in ipairs(paths) do
--- table.insert(tasks, async.run(function()
--- return limit:with(function()
--- return read_file(path)
--- end)
--- end))
--- end
---
--- local next_task = async.iter(tasks)
--- while true do
--- local task = next_task()
--- if task == nil then
--- break
--- end
--- async.await(task)
--- end
--- end)
--- ```
--- @class vim.async.Semaphore
--- @field private _permits integer
--- @field private _max_permits integer
--- @field package _event vim.async.Event
local Semaphore = {}
Semaphore.__index = Semaphore
--- Executes a function while holding one semaphore permit.
---
--- This acquires the semaphore before running the function and releases it
--- after the function completes, even if it errors or the current task is
--- closed.
--- @async
--- @generic R
--- @param fn async fun(): R... # Function to execute within the semaphore's context.
--- @return R... # Result(s) of the executed function.
function Semaphore:with(fn)
self:acquire()
-- This pcall is only a try/finally guard for release(); all errors are
-- immediately rethrown so it is not an async recovery boundary.
local r = F.pack_len(pcall(fn))
self:release()
local stat = r[1]
if not stat then
local err = r[2]
error(err, 0)
end
return unpack(r, 2, r.n)
end
--- Acquire a semaphore permit.
---
--- If the internal counter is greater than zero, decrement it by `1` and
--- return immediately. If it is `0`, wait until [Semaphore:release()] is
--- called.
--- @async
function Semaphore:acquire()
self._event:wait()
self._permits = self._permits - 1
assert(self._permits >= 0, 'Semaphore value is negative')
if self._permits == 0 then
self._event:clear()
end
end
--- Release a semaphore permit.
---
--- Increments the internal counter by `1` and can wake a task waiting in
--- [Semaphore:acquire()].
---
--- Calling this more times than permits were acquired raises an error.
function Semaphore:release()
if self._permits >= self._max_permits then
error('Semaphore value is greater than max permits', 2)
end
self._permits = self._permits + 1
self._event:set(1)
end
--- Create an async semaphore that allows up to a given number of acquisitions.
---
--- Prefer [Semaphore:with()] for most uses so permits are released reliably.
--- Use [Semaphore:acquire()] and [Semaphore:release()] directly only when the
--- acquire and release points cannot be expressed as one function call.
--- @param permits? integer (default: 1)
--- @return vim.async.Semaphore
local function new_semaphore(permits)
validate('permits', permits, 'number', true)
permits = permits or 1
if permits < 1 or permits % 1 ~= 0 then
error('permits: expected positive integer', 2)
end
local obj = setmetatable({
_max_permits = permits,
_permits = permits,
_event = new_event(),
}, Semaphore)
obj._event:set()
return obj
end
return new_semaphore