robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
34.2 KiB1129 linesraw
1local util = require('vim._core.util')
2local future = require('vim.async._future')
3local runtime = require('vim.async._runtime')
4
5local is_callable = vim.is_callable
6local validate = vim.validate
7local pcall = pcall
8local coroutine_running = coroutine.running
9do
10  local ok, coxpcall = pcall(require, 'coxpcall')
11  if ok and type(coxpcall) == 'table' then
12    if type(coxpcall.pcall) == 'function' then
13      pcall = coxpcall.pcall
14    end
15    if type(coxpcall.running) == 'function' then
16      coroutine_running = coxpcall.running
17    end
18  end
19end
20local maxint = 2 ^ 32 - 1
21local pack_len = vim.F.pack_len
22local unpack_len = vim.F.unpack_len
23
24--- @class vim.async._core
25--- @nodoc
26local M = {}
27
28--- Weak table to keep track of running tasks
29--- @type table<thread, vim.async.Task<any>?>
30local threads = setmetatable({}, { __mode = 'k' })
31
32--- Returns the currently running task.
33--- @return vim.async.Task<any>?
34local function running()
35  --- @diagnostic disable-next-line: invisible, undefined-field
36  local task = threads[coroutine_running()]
37  if task and not task:completed() then
38    return task
39  end
40end
41
42--- Internal marker used to identify that a yielded value is an asynchronous yielding.
43local yield_marker = {}
44local resume_marker = {}
45
46local resume_error = 'Unexpected coroutine.resume()'
47local yield_error = 'Unexpected coroutine.yield()'
48
49--- @return vim.async.Task<any>
50local function current_task()
51  return (assert(running(), 'Not in async context'))
52end
53
54--- Checks the arguments of a `coroutine.resume`.
55--- This is used to ensure that a resume is expected.
56--- @generic T
57--- @param marker any
58--- @param err? any
59--- @param ... T...
60--- @return T...
61local function check_yield(marker, err, ...)
62  if marker ~= resume_marker then
63    current_task():_raise(resume_error)
64    -- Return an error to the caller. This will also leave the task in a dead
65    -- and unfinished state.
66    error(resume_error, 0)
67  elseif err ~= nil then
68    error(err, 0)
69  end
70  return ...
71end
72
73--- @class vim.async.Closable
74--- @field close fun(self, callback?: fun())
75--- @field is_closing? fun(self): boolean
76
77--- A coroutine-backed async operation and concurrency scope.
78---
79--- Use [vim.async.run()] to create tasks. A task may be awaited by more than
80--- one waiter. When a task is created inside another task, it is attached to
81--- that parent and becomes part of the parent's concurrency scope.
82---
83--- @class vim.async.Task<R>: vim.async.Closable
84--- @field package _thread thread
85--- @field package _future vim.async.Future<R>
86--- @field package _closing boolean
87--- @field package _error? any
88--- @field package _finalizing_children boolean
89--- @field package _started boolean
90---
91--- Reference to parent to handle attaching/detaching.
92--- @field package _parent? vim.async.Task<any>
93--- @field package _parent_children_idx? integer
94---
95--- Name of the task
96--- @field name? string
97---
98--- Hide implementation tasks from user-facing inspection output.
99--- @field package _hidden? boolean
100---
101--- The source line that created this task, used for inspect().
102--- @field package _caller? string
103---
104--- Maintain children as an array to preserve closure order.
105--- @field package _children table<integer, vim.async.Task<any>?>
106---
107--- Pointer to last child in children
108--- @field package _children_idx integer
109---
110--- Tasks can await other async functions (task of callback functions)
111--- when we are waiting on a child, we store the handle to it here so we can
112--- close it.
113--- @field package _awaiting? vim.async.Task<any> | vim.async.Closable
114--- Removes the completion callback when a Task await is abandoned.
115--- @field package _awaiting_unsubscribe? fun()
116local Task = {}
117
118--- @return_cast x vim.async.Task<any>
119--- @param x any
120local function is_task(x)
121  return getmetatable(x) == Task
122end
123
124do --- Task
125  Task.__index = Task
126
127  --- @package
128  --- @param name? string
129  --- @param func async fun(...: any)
130  --- @return vim.async.Task<any>
131  function Task._new(name, func, ...)
132    local func_args = pack_len(...) --[[@as any[]? ]]
133    local thread = coroutine.create(function(marker, err)
134      -- Drop the packed vararg table before user code can suspend; otherwise
135      -- the coroutine closure retains it for the task lifetime.
136      local args = assert(func_args)
137      func_args = nil
138      check_yield(marker, err)
139      return func(unpack_len(args))
140    end)
141
142    local self = setmetatable({
143      name = name,
144      _closing = false,
145      _finalizing_children = false,
146      _started = false,
147      _thread = thread,
148      _future = future(),
149      _children = {},
150      _children_idx = 0,
151    }, Task)
152
153    threads[thread] = self
154
155    return self
156  end
157
158  --- Returns whether the Task has completed.
159  --- @return boolean
160  function Task:completed()
161    return self._future:completed()
162  end
163
164  --- Add a callback to be run when the Task has completed.
165  ---
166  --- If the Task is already done when this method is called, the callback is
167  --- called immediately with the results.
168  ---
169  --- This only observes completion. It does not start a pending task.
170  --- @param callback fun(err?: any, ...: R...)
171  --- @return fun() unsubscribe
172  function Task:on_complete(callback)
173    validate('callback', callback, 'callable')
174    return self._future:on_complete(callback)
175  end
176
177  --- Synchronously wait for the Task to complete.
178  ---
179  --- If a timeout is provided, waits for the given time in milliseconds before
180  --- failing with `"timeout"`. With no timeout, waits indefinitely.
181  ---
182  --- This is for synchronous code. Inside a task, prefer [vim.async.await()] so
183  --- the current task suspends instead of pumping the event loop itself.
184  ---
185  --- ```lua
186  --- local result = task:wait(10) -- wait for 10ms or raise "timeout"
187  ---
188  --- local result = task:wait() -- wait indefinitely
189  --- ```
190  --- @param timeout integer?
191  --- @return R...
192  function Task:wait(timeout)
193    validate('timeout', timeout, 'number', true)
194    self:_start()
195
196    if not runtime.wait(timeout or maxint, function()
197      return self:completed()
198    end) then
199      error('timeout', 2)
200    end
201    local res = pack_len(self._future:result())
202
203    assert(self:status() == 'completed' or res[2] == yield_error)
204
205    if not res[1] then
206      error(res[2], 2)
207    end
208
209    return unpack(res, 2, res.n)
210  end
211
212  --- Protected-call version of [Task:wait()].
213  ---
214  --- Equivalent to `pcall(task.wait, task, timeout)`.
215  ---
216  --- ```lua
217  --- local ok, result_or_err = task:pwait(1000)
218  --- if not ok then
219  ---   vim.notify(tostring(result_or_err), vim.log.levels.ERROR)
220  --- end
221  --- ```
222  --- @param timeout integer?
223  --- @return boolean, R...
224  function Task:pwait(timeout)
225    validate('timeout', timeout, 'number', true)
226    return pcall(self.wait, self, timeout)
227  end
228
229  --- @package
230  --- @param parent? vim.async.Task<any>
231  function Task:_attach(parent)
232    if parent then
233      -- Attach to parent
234      parent._children_idx = parent._children_idx + 1
235      parent._children[parent._children_idx] = self
236
237      -- Keep track of the parent and this tasks index so we can detach
238      self._parent = parent
239      self._parent_children_idx = parent._children_idx
240    end
241  end
242
243  --- Remove this task from its parent without changing execution state.
244  --- @private
245  --- @return boolean removed
246  function Task:_detach()
247    if not self._parent then
248      return false
249    end
250
251    self._parent._children[self._parent_children_idx] = nil
252    self._parent = nil
253    self._parent_children_idx = nil
254    return true
255  end
256
257  --- Detach a task from its parent.
258  ---
259  --- The task becomes a top-level task.
260  --- If it was waiting for a parent checkpoint, it is scheduled to start.
261  ---
262  --- Use this for background work that should not be cancelled when the
263  --- current task finishes. Detached task failures no longer fail the original
264  --- parent, so observe them explicitly with [Task:on_complete()],
265  --- [Task:wait()], or [vim.async.await()].
266  ---
267  --- ```lua
268  --- vim.async.run(function()
269  ---   while true do
270  ---     refresh_index()
271  ---     vim.async.sleep(1000)
272  ---   end
273  --- end):detach()
274  --- ```
275  --- @return vim.async.Task<R>
276  function Task:detach()
277    local should_start = self._parent and not self._started and not self:completed()
278    self:_detach()
279    if should_start then
280      runtime.schedule(function()
281        self:_start()
282      end)
283    end
284    return self
285  end
286
287  --- Get the traceback of a task when it is not active.
288  --- Will also get the traceback of nested tasks.
289  ---
290  --- @param msg? string
291  --- @param level? integer
292  --- @return string traceback
293  function Task:traceback(msg, level)
294    level = level or 0
295
296    local thread = '[' .. tostring(self._thread) .. '] '
297
298    local awaiting = self._awaiting
299    if is_task(awaiting) then
300      msg = awaiting:traceback(msg, level + 1)
301    end
302
303    local tblvl = is_task(awaiting) and 2 or nil
304    local tb = debug.traceback(self._thread, '', tblvl) or ''
305    msg = (msg == nil and '' or tostring(msg)) .. tb:gsub('\n\t', '\n\t' .. thread)
306
307    if level == 0 then
308      --- @type string
309      msg = msg
310        :gsub('\nstack traceback:\n', '\nSTACK TRACEBACK:\n', 1)
311        :gsub('\nstack traceback:\n', '\n')
312        :gsub('\nSTACK TRACEBACK:\n', '\nstack traceback:\n', 1)
313    end
314
315    return msg
316  end
317
318  --- Raise this task's error when it completes.
319  ---
320  --- Use this for detached or top-level fire-and-forget tasks whose completion
321  --- will not otherwise be observed. Attached task errors already propagate to
322  --- their parent.
323  ---
324  --- Detached tasks do not raise errors automatically. Detaching changes
325  --- ownership only; their completion can still be handled with
326  --- [vim.async.await()], [Task:wait()], [Task:pwait()], or [Task:on_complete()].
327  --- @return vim.async.Task<R> self
328  function Task:raise_on_error()
329    self:on_complete(function(err)
330      if err ~= nil then
331        error(self:traceback(err), 0)
332      end
333    end)
334    return self
335  end
336
337  --- @package
338  function Task:_start()
339    if self._started or self:completed() then
340      return
341    end
342
343    self._started = true
344    self:_resume()
345  end
346
347  --- Start children whose first resume was deferred by `run()`.
348  ---
349  --- Deferring child start lets `await()` or `pawait()` claim the task boundary
350  --- before child code runs. At await checkpoints and successful parent finish,
351  --- any remaining pending children must start so implicit waits, cancellation,
352  --- and inspection see the full task tree.
353  --- @package
354  function Task:_start_pending_children()
355    for i = 1, self._children_idx do
356      local child = self._children[i]
357      if child then
358        child:_start()
359      end
360    end
361  end
362
363  --- @private
364  function Task:_close_children()
365    for i = 1, self._children_idx do
366      local child = self._children[i]
367      if child then
368        child:close()
369      end
370    end
371  end
372
373  --- Keep the first task error. The error can be any non-nil Lua value.
374  --- @package
375  --- @param err any
376  --- @return any
377  function Task:_set_error(err)
378    if self._error == nil then
379      self._error = err
380    end
381    return self._error
382  end
383
384  --- @package
385  --- @param err any
386  function Task:_raise(err)
387    if self:status() == 'running' then
388      -- A running coroutine cannot be resumed recursively, so deliver the
389      -- error on a later event-loop turn after the current stack unwinds.
390      runtime.schedule(function()
391        if not self:completed() then
392          self:_resume(err)
393        end
394      end)
395    else
396      self:_resume(err)
397    end
398  end
399
400  --- Request cooperative close for the task and all of its children.
401  ---
402  --- The optional callback observes task completion and may run immediately if
403  --- the task has already completed.
404  ---
405  --- Closing is cooperative. The task observes the close request at a
406  --- checkpoint such as [vim.async.await()] or [vim.async.checkpoint()]. If the
407  --- task is suspended on an owned closable operation, that operation is closed
408  --- before the task reports `"closed"`.
409  ---
410  --- @param callback? fun()
411  function Task:close(callback)
412    if not self:completed() and not self._closing then
413      self._closing = true
414      self:_raise('closed')
415    end
416    if callback then
417      self:on_complete(function()
418        callback()
419      end)
420    end
421  end
422
423  --- Record a child failure on this task and either deliver it to a live
424  --- parent or close sibling children during finalization.
425  --- @package
426  --- @param child vim.async.Task<any>
427  --- @param err any
428  --- @param child_was_awaited boolean?
429  function Task:_child_failed(child, err, child_was_awaited)
430    -- A parent close turns child "closed" results into cleanup, not failure.
431    if child._closing or child_was_awaited or (self._closing and err == 'closed') then
432      return
433    end
434
435    local task_err = self:_set_error('child error: ' .. util._stringify_error(err))
436    if self._finalizing_children then
437      -- The parent coroutine is already dead, so sibling cleanup must wake the
438      -- finalizer instead of trying to resume the parent.
439      self:_close_children()
440    else
441      self:_raise(task_err)
442    end
443  end
444
445  --- Checks if an object is closable, i.e., has a `close` method.
446  --- @param obj any
447  --- @return boolean
448  --- @return_cast obj vim.async.Closable
449  local function is_closable(obj)
450    local ty = type(obj)
451    return (ty == 'table' or ty == 'userdata') and is_callable(obj.close)
452  end
453
454  do -- Task:_resume()
455    --- Complete this task with an error and propagate it to the parent if the
456    --- parent did not explicitly await this task.
457    --- @param parent? vim.async.Task<any>
458    --- @param err any
459    function Task:_finish_error(parent, err)
460      if err == nil then
461        err = self._error
462      end
463      err = util._normalize_error(err)
464      if parent then
465        parent:_child_failed(self, err, parent._awaiting == self)
466      end
467      self._future:complete(err)
468    end
469
470    --- @private
471    --- @param stat boolean
472    --- @param ... R... result
473    function Task:_finish(stat, ...)
474      if self:completed() then
475        return
476      end
477
478      local parent = self._parent
479      self:_detach()
480
481      threads[self._thread] = nil
482
483      if not stat then
484        self:_finish_error(parent, ...)
485      else
486        if self._error ~= nil then
487          self:_finish_error(parent, self._error)
488        else
489          self._future:complete(nil, ...)
490        end
491      end
492    end
493
494    --- @package
495    --- @param stat boolean
496    --- @param ... R... result
497    function Task:_finalize(stat, ...)
498      if next(self._children) == nil then
499        self:_finish(stat, ...)
500        return
501      end
502
503      local finish_args = pack_len(stat, ...)
504      self._finalizing_children = true
505      -- Only spawn the helper after the no-child path; an empty helper task
506      -- would otherwise finalize by recursively spawning another helper.
507      local await_children = Task._new('await_children', function()
508        -- TODO(lewis6991): should we collect all errors?
509        local close_remaining = not stat
510
511        if close_remaining then
512          self:_close_children()
513        else
514          self:_start_pending_children()
515        end
516
517        for i = 1, self._children_idx do
518          local child = self._children[i]
519          if child then
520            -- Child failures are recorded on `self`. Protect this helper so one
521            -- failed child cannot stop it awaiting the remaining cleanup.
522            local ok, err = M.pawait(child)
523            -- A close can arrive while normal finalization is awaiting
524            -- children; from that point child errors are cleanup results.
525            if not close_remaining and not self._closing and not ok and not child._closing then
526              self:_set_error('child error: ' .. util._stringify_error(err))
527              close_remaining = true
528              self:_close_children()
529            end
530          end
531        end
532
533        self._finalizing_children = false
534        if stat and self._closing and self._error == nil then
535          self:_finish(false, 'closed')
536        else
537          self:_finish(unpack_len(finish_args))
538        end
539      end)
540      await_children._hidden = true
541      await_children:_start()
542    end
543
544    --- Resume a task with the raw or protected result of an await.
545    --- @param task vim.async.Task<any>
546    --- @param yielded vim.async.Task<any>|fun(callback: fun(err?: any, ...: any)): vim.async.Closable?
547    --- @param protected boolean?
548    --- @param err? any
549    --- @param ... any
550    local function resume_from_await(task, yielded, protected, err, ...)
551      -- An error from `await(task)` also marks the waiting task as failed, even
552      -- if the error raised by `await()` is caught.
553      if not protected and is_task(yielded) and err ~= nil then
554        task:_set_error(err)
555      end
556
557      if protected then
558        if err ~= nil then
559          return task:_resume(nil, false, err)
560        end
561        return task:_resume(nil, true, ...)
562      end
563
564      return task:_resume(err, ...)
565    end
566
567    --- Begin waiting on a yielded awaitable.
568    --- @param task vim.async.Task<any>
569    --- @param yielded vim.async.Task<any>|fun(callback: fun(err?: any, ...: any)): vim.async.Closable?
570    --- @param protected boolean?
571    local function start_await(task, yielded, protected)
572      -- TODO(#36): Defer task control until setup returns its cleanup handle.
573      -- The first callback or setup failure settles the await.
574      -- Ignore any callback that arrives afterwards.
575      local settled = false
576      local setup_ok --- @type boolean?
577
578      -- Await setup may invoke the callback before `_awaiting` is installed.
579      -- Save those arguments so the task resumes only after setup finishes.
580      -- `sync_args` has three states:
581      -- - `nil`: the callback did not fire during setup;
582      -- - `false`: `callback(nil)`, the common no-error/no-result case,
583      --   avoiding a table allocation;
584      -- - a table: every other argument list, packed to preserve nils.
585      local sync_args --- @type false|{[integer]: any, n: integer}?
586      local awaiting --- @type vim.async.Task<any>|vim.async.Closable?
587
588      --- @param err? any
589      --- @param ... any
590      local function complete_await(err, ...)
591        -- Cancellation and child failures resume through `_raise()`. Ignore a
592        -- racing result so `_resume()` can finish awaitable cleanup first.
593        if settled or task._closing or task._error ~= nil then
594          return
595        end
596        settled = true
597
598        if setup_ok == nil then
599          if err == nil and select('#', ...) == 0 then
600            sync_args = false
601          else
602            sync_args = pack_len(err, ...)
603          end
604        else
605          -- The callback has fired. Keep `_awaiting` so `_resume()` can close a
606          -- callback-style handle or retain a failed Task for its traceback.
607          task._awaiting_unsubscribe = nil
608
609          if not task:completed() then
610            return resume_from_await(task, yielded, protected, err, ...)
611          end
612        end
613      end
614
615      local unsubscribe
616      local task_await --- @type boolean
617      local setup_result
618      -- Either call below may invoke `complete_await()` before returning. In that
619      -- case, `unsubscribe` or `awaiting` has not yet received the returned cleanup
620      -- handle. While `setup_ok` is nil, `complete_await()` saves its arguments
621      -- in `sync_args`. This lets the code below handle setup errors and install the
622      -- cleanup state before using the buffered result.
623      if is_task(yielded) then
624        task_await = true
625        --- @diagnostic disable-next-line: cast-local-type
626        awaiting = yielded
627        setup_ok, setup_result = pcall(yielded._future.on_complete, yielded._future, complete_await)
628      else
629        task_await = false
630        -- Callback setup has one result: the optional closable.
631        --- @type fun(callback: fun(err?: any, ...: any)): vim.async.Closable?
632        local awaitable = yielded
633        setup_ok, setup_result = pcall(awaitable, complete_await)
634      end
635
636      if not setup_ok then
637        local err = util._normalize_error(setup_result)
638        if protected and settled then
639          -- The first synchronous callback wins over a later setup error.
640          awaiting = nil
641        else
642          settled = true
643          return resume_from_await(task, yielded, protected, err)
644        end
645      elseif task_await then
646        unsubscribe = setup_result
647      else
648        awaiting = setup_result
649      end
650
651      if not is_closable(awaiting) then
652        awaiting = nil
653      end
654      --- @diagnostic disable-next-line: assign-type-mismatch
655      task._awaiting = awaiting
656
657      if is_task(awaiting) then
658        if not settled and unsubscribe then
659          --- @diagnostic disable-next-line: assign-type-mismatch
660          task._awaiting_unsubscribe = unsubscribe
661        end
662        awaiting:_start()
663      end
664
665      if task:completed() then
666        return
667      end
668
669      task:_start_pending_children()
670
671      if sync_args == false then
672        return resume_from_await(task, yielded, protected)
673      elseif sync_args then
674        return resume_from_await(task, yielded, protected, unpack_len(sync_args))
675      end
676    end
677
678    --- Finalize a completed coroutine or start its yielded await.
679    --- Keep results in varargs to preserve nils without packing them.
680    --- @param task vim.async.Task<any>
681    --- @param stat boolean
682    --- @param ... any
683    local function handle_resume(task, stat, ...)
684      if coroutine.status(task._thread) == 'dead' then
685        -- The coroutine finished during resume. A normal return must not
686        -- overwrite a pending task failure.
687        if task._error ~= nil and stat then
688          task:_finalize(false, task._error)
689        elseif task._closing and stat then
690          task:_finalize(false, 'closed')
691        else
692          task:_finalize(stat, ...)
693        end
694        return
695      end
696
697      local marker, yielded, protected = ...
698      if marker ~= yield_marker or (not is_task(yielded) and not is_callable(yielded)) then
699        task:_finalize(false, yield_error)
700        return
701      end
702
703      return start_await(task, yielded, protected)
704    end
705
706    --- Clear an await boundary and remove its Task completion callback.
707    --- @param task vim.async.Task<any>
708    local function clear_awaiting(task)
709      local unsubscribe = task._awaiting_unsubscribe
710      task._awaiting = nil
711      task._awaiting_unsubscribe = nil
712      if unsubscribe then
713        unsubscribe()
714      end
715    end
716
717    --- @package
718    --- @param err? any
719    --- @param ... any resume values
720    function Task:_resume(err, ...)
721      -- Clear self._awaiting when either:
722      -- - this task resumes before a non-child finishes, so its callback
723      --   cannot retain this task; or
724      -- - there is no raw error needing its traceback frames and
725      --   self._awaiting is finished.
726      if
727        is_task(self._awaiting)
728        and (
729          (self._awaiting._parent ~= self and self._awaiting_unsubscribe)
730          or (err == nil and self._awaiting:completed())
731        )
732      then
733        clear_awaiting(self)
734      end
735
736      local awaiting = self._awaiting
737      -- Only close awaitables owned by this task; external tasks are observed.
738      if awaiting and (not is_task(awaiting) or awaiting._parent == self) then
739        local already_closing = false
740        if type(awaiting.is_closing) == 'function' then
741          already_closing = awaiting:is_closing()
742        end
743
744        if already_closing then
745          clear_awaiting(self)
746          return self:_resume(err, ...)
747        end
748
749        local args = pack_len(err, ...)
750        -- We must close the closable child before we resume to ensure
751        -- all resources are collected.
752        --- @diagnostic disable-next-line: param-type-mismatch
753        local close_ok, close_err = pcall(awaiting.close, awaiting, function()
754          clear_awaiting(self)
755          return self:_resume(unpack_len(args))
756        end)
757
758        if close_ok then
759          return
760        end
761        clear_awaiting(self)
762        return self:_resume(util._normalize_error(close_err))
763      end
764
765      -- An external coroutine.resume() may have already killed the coroutine.
766      -- Finalize its pending failure instead of trying to resume it again.
767      if coroutine.status(self._thread) == 'dead' then
768        self:_finalize(false, err, ...)
769        return
770      end
771
772      return handle_resume(self, coroutine.resume(self._thread, resume_marker, err, ...))
773    end
774  end
775
776  --- @package
777  function Task:_log(...)
778    print(tostring(self._thread), ...)
779  end
780
781  --- Returns the status of the task:
782  ---
783  --- - `"running"`: task is currently executing Lua code
784  --- - `"normal"`: task is active but another coroutine is running
785  --- - `"awaiting"`: task is suspended at a checkpoint or waiting for children
786  --- - `"completed"`: task and all attached children have completed
787  --- @return "running" | "awaiting" | "normal" | "completed"
788  function Task:status()
789    if self:completed() then
790      return 'completed'
791    end
792
793    local co_status = coroutine.status(self._thread)
794    if co_status == 'dead' then
795      return 'awaiting'
796    elseif co_status == 'suspended' then
797      return 'awaiting'
798    elseif co_status == 'normal' then
799      -- TODO(lewis6991): This state is a bit ambiguous. If all tasks
800      -- are started from the main thread, then we can remove this state.
801      -- Though it still may be possible if the user resumes a non-task
802      -- coroutine.
803      return 'normal'
804    end
805    assert(co_status == 'running')
806    return 'running'
807  end
808end
809
810--- @generic T, R
811--- @param name? string
812--- @param func async fun(...: T...): R... Function to run in an async context
813--- @param ... T... Arguments to pass to the function
814--- @return vim.async.Task<R...>
815local function run(name, func, ...)
816  validate('func', func, 'callable')
817  local task = Task._new(name, func, ...)
818  task:_attach(running())
819  if runtime.debug then
820    local info = debug.getinfo(2, 'Sl')
821    if info and info.currentline then
822      task._caller = ('%s:%d'):format(info.source, info.currentline)
823    end
824  end
825
826  -- Top-level tasks have no parent checkpoint to start them, so they start
827  -- immediately. Attached children start when their parent next reaches an
828  -- await checkpoint, or when the parent finishes successfully and implicitly
829  -- waits for its children. If the parent errors or closes, pending children
830  -- are closed without running user code.
831  if not task._parent then
832    task:_start()
833  end
834
835  return task
836end
837
838--- Create a task from an async function.
839---
840--- Top-level tasks start immediately. Child tasks are attached immediately and
841--- first run when their parent reaches a checkpoint.
842---
843--- Creating a task decides ownership. Awaiting the task later only observes
844--- its result; it does not attach the task to the awaiter.
845---
846--- ```lua
847--- local async = vim.async
848---
849--- async.run(function()
850---   local child = async.run(function()
851---     return read_file('notes.txt')
852---   end)
853---
854---   local text = async.await(child)
855---   show_buffer(text)
856--- end)
857--- ```
858---
859--- A task created from synchronous code is top-level:
860---
861--- ```lua
862--- local task = vim.async.run(function()
863---   vim.async.sleep(100)
864---   return 'done'
865--- end)
866---
867--- print(task:wait())
868--- ```
869--- @generic T, R
870--- @param func async fun(...: T...): R...
871--- @param ... T... Arguments to pass to the function
872--- @return vim.async.Task<R...>
873--- @overload fun(name: string, func: async fun(...: T...), ...: T...): vim.async.Task<R...>
874function M.run(func, ...)
875  if type(func) == 'string' then
876    --- @diagnostic disable-next-line: param-type-mismatch
877    return run(func, ...)
878  elseif is_callable(func) then
879    return run(nil, func, ...)
880  end
881  error('Invalid arguments')
882end
883
884--- @generic T, R
885--- @param argc integer
886--- @param fun fun(...: T..., callback: fun(...: R...))
887--- @param ... T... func arguments
888--- @return fun(callback: fun(...: R...))
889local function norm_cb_fun(argc, fun, ...)
890  if argc == 1 and select('#', ...) == 0 then
891    -- Avoid allocating an empty argument table for the common await(func) shape.
892    local cb_fun = fun
893    --- @cast cb_fun fun(callback: fun(...: any)): any?
894    --- @param callback fun(...: any)
895    --- @return any?
896    return function(callback)
897      return cb_fun(function(...)
898        callback(nil, ...)
899      end)
900    end
901  end
902
903  local args = pack_len(...)
904
905  --- @param callback fun(...: any)
906  --- @return any?
907  return function(callback)
908    args[argc] = function(...)
909      callback(nil, ...)
910    end
911    args.n = math.max(args.n, argc)
912    return fun(unpack_len(args))
913  end
914end
915
916--- Get the current task, failing before an operation yields if it is closing or
917--- failed.
918--- @return vim.async.Task<any>
919local function check_current_task()
920  local task = current_task()
921
922  if task._closing then
923    error('closed', 0)
924  elseif task._error ~= nil then
925    error(task._error, 0)
926  end
927
928  return task
929end
930
931--- Convert the public await forms into a Task or callback awaitable.
932---
933--- Callback-style APIs do not have an error slot, so `norm_cb_fun()` inserts
934--- `nil`; the scheduler observes Task futures directly.
935--- @param ... any
936--- @return vim.async.Task<any>|fun(callback: fun(err?: any, ...: any)): vim.async.Closable?
937local function to_awaitable(...)
938  local arg1 = select(1, ...)
939
940  if type(arg1) == 'number' then
941    return norm_cb_fun(...)
942  elseif type(arg1) == 'function' then
943    return norm_cb_fun(1, arg1)
944  elseif is_task(arg1) then
945    return arg1
946  else
947    error('Invalid arguments, expected Task or (argc, func) got: ' .. tostring(arg1), 2)
948  end
949end
950
951--- Suspend the current task until an awaitable completes.
952---
953--- Accepts a task, a callback-taking function, or an argument position plus a
954--- callback-taking function. Raises awaited errors and current task-control
955--- errors.
956---
957--- The callback forms return callback arguments unchanged:
958---
959--- ```lua
960--- local async = vim.async
961---
962--- async.run(function()
963---   local err, stat = async.await(2, vim.uv.fs_stat, 'notes.txt')
964---   if err then
965---     error(err, 0)
966---   end
967---   print(stat.size)
968--- end)
969--- ```
970---
971--- If a callback API starts cancellable work, return a closable handle from the
972--- await callback. [Task:close()] will close that handle if cancellation
973--- arrives while the task is suspended there.
974---
975--- ```lua
976--- local async = vim.async
977---
978--- async.run(function()
979---   local lines = async.await(function(done)
980---     return start_read_lines('notes.txt', done)
981---   end)
982---   render(lines)
983--- end)
984--- ```
985--- @async
986--- @generic T, R
987--- @param ... any see overloads
988--- @overload async fun(func: (fun(callback: fun(...: R...)): vim.async.Closable?)): R...
989--- @overload async fun(argc: integer, func: (fun(...: T..., callback: fun(...: R...)): vim.async.Closable?), ...: T...): R...
990--- @overload async fun(task: vim.async.Task<R>): R...
991--- @return R...
992function M.await(...)
993  check_current_task()
994  return check_yield(coroutine.yield(yield_marker, to_awaitable(...)))
995end
996
997--- Protected await.
998---
999--- Async counterpart to `pcall()`. Accepts the same forms as
1000--- [vim.async.await()], but returns a leading `ok` boolean for
1001--- awaited-operation failures.
1002---
1003--- Use this when the awaited task or operation is allowed to fail and the
1004--- current task should continue. Cancellation or already pending failure from
1005--- the current task is not protected.
1006---
1007--- ```lua
1008--- local async = vim.async
1009---
1010--- async.run(function()
1011---   local ok, text_or_err = async.pawait(async.run(read_file, 'notes.txt'))
1012---   if not ok then
1013---     text_or_err = ''
1014---   end
1015---
1016---   show_buffer(text_or_err)
1017--- end)
1018--- ```
1019--- @async
1020--- @generic T, R
1021--- @param ... any see overloads
1022--- @overload async fun(func: (fun(callback: fun(...: R...)): vim.async.Closable?)): boolean, R...
1023--- @overload async fun(argc: integer, func: (fun(...: T..., callback: fun(...: R...)): vim.async.Closable?), ...: T...): boolean, R...
1024--- @overload async fun(task: vim.async.Task<R>): boolean, R...
1025--- @return boolean ok
1026--- @return R... ... result or error
1027--- @return_overload true, R...
1028--- @return_overload false, any
1029function M.pawait(...)
1030  check_current_task()
1031  return check_yield(coroutine.yield(yield_marker, to_awaitable(...), true))
1032end
1033
1034--- Start pending child tasks and deliver pending cancellation or task failure
1035--- from the current task.
1036---
1037--- This does not yield to the event loop.
1038---
1039--- Use this after cleanup code that catches an async failure or close signal,
1040--- so persistent task state is delivered again before normal execution
1041--- continues.
1042---
1043--- ```lua
1044--- local ok, err = pcall(cleanup_sensitive_work)
1045--- cleanup_resources()
1046--- vim.async.checkpoint()
1047--- if not ok then
1048---   error(err, 0)
1049--- end
1050--- ```
1051--- @async
1052function M.checkpoint()
1053  M.await(function(callback)
1054    callback()
1055  end)
1056end
1057
1058--- Returns true if the current task has been closed.
1059---
1060--- Can be used in an async function to do cleanup when a task is closing.
1061---
1062--- ```lua
1063--- while not vim.async.is_closing() do
1064---   poll_once()
1065---   vim.async.sleep(1000)
1066--- end
1067--- ```
1068--- @return boolean
1069function M.is_closing()
1070  local task = running()
1071  return task and task._closing or false
1072end
1073
1074--- @private
1075--- @param parent? vim.async.Task<any>
1076--- @param prefix? string
1077--- @return string[]
1078local function inspect(parent, prefix)
1079  local tasks = {} --- @type table<any, vim.async.Task<any>?>
1080  if parent then
1081    for _, task in pairs(parent._children) do
1082      if not task._hidden then
1083        tasks[#tasks + 1] = task
1084      end
1085    end
1086  else
1087    -- Gather for all detached tasks
1088    for _, task in pairs(threads) do
1089      if not task._parent and not task._hidden then
1090        tasks[#tasks + 1] = task
1091      end
1092    end
1093  end
1094
1095  local r = {} --- @type string[]
1096  for i, task in ipairs(tasks) do
1097    local last = i == #tasks
1098    local label = task.name or ''
1099    if task._caller then
1100      label = label .. task._caller
1101    end
1102    if label ~= '' then
1103      label = label .. ' '
1104    end
1105    r[#r + 1] = ('%s%s%s[%s]'):format(
1106      prefix or '',
1107      parent and (last and '└─ ' or '├─ ') or '',
1108      label,
1109      task:status()
1110    )
1111    local child_prefix = (prefix or '') .. (parent and (last and '   ' or '│  ') or '')
1112    for _, line in ipairs(inspect(task, child_prefix)) do
1113      r[#r + 1] = line
1114    end
1115  end
1116  return r
1117end
1118
1119--- Inspect the current async task tree.
1120---
1121--- Returns a string representation of the task tree, showing the names and
1122--- statuses of each task.
1123--- @return string
1124function M._inspect_tree()
1125  -- Inspired by https://docs.python.org/3.14/whatsnew/3.14.html#asyncio-introspection-capabilities
1126  return table.concat(inspect(), '\n')
1127end
1128
1129return M