robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 10local ok , coxpcall =pcall ( require , 'coxpcall' ) 11if ok and type ( coxpcall ) == 'table' then 12if type ( coxpcall . pcall ) == 'function' then 13pcall =coxpcall . pcall 14end 15if type ( coxpcall . running ) == 'function' then 16coroutine_running =coxpcall . running 17end 18end 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 36local task =threads [ coroutine_running ()] 37if task and not task : completed () then 38return task 39end 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 () 51return ( 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 , ... ) 62if marker ~= resume_marker then 63current_task (): _raise ( resume_error ) 64-- Return an error to the caller. This will also leave the task in a dead 65-- and unfinished state. 66error ( resume_error , 0 ) 67elseif err ~= nil then 68error ( err , 0 ) 69end 70return ... 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 ) 121return getmetatable ( x ) == Task 122end 123 124do --- Task 125Task . __index =Task 126 127--- @package 128--- @param name? string 129--- @param func async fun(...: any) 130--- @return vim.async.Task<any> 131function Task . _new ( name , func , ... ) 132local func_args =pack_len ( ... ) --[[@as any[]? ]] 133local 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. 136local args =assert ( func_args ) 137func_args =nil 138check_yield ( marker , err ) 139return func ( unpack_len ( args )) 140end ) 141 142local self =setmetatable ( { 143name =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 153threads [ thread ] =self 154 155return self 156end 157 158--- Returns whether the Task has completed. 159--- @return boolean 160function Task : completed () 161return self . _future : completed () 162end 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 172function Task : on_complete ( callback ) 173validate ( 'callback' , callback , 'callable' ) 174return self . _future : on_complete ( callback ) 175end 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... 192function Task : wait ( timeout ) 193validate ( 'timeout' , timeout , 'number' , true ) 194self : _start () 195 196if not runtime . wait ( timeout or maxint , function () 197return self : completed () 198end ) then 199error ( 'timeout' , 2 ) 200end 201local res =pack_len ( self . _future : result ()) 202 203assert ( self : status () == 'completed' or res [ 2 ] == yield_error ) 204 205if not res [ 1 ] then 206error ( res [ 2 ], 2 ) 207end 208 209return unpack ( res , 2 , res . n ) 210end 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... 224function Task : pwait ( timeout ) 225validate ( 'timeout' , timeout , 'number' , true ) 226return pcall ( self . wait , self , timeout ) 227end 228 229--- @package 230--- @param parent? vim.async.Task<any> 231function Task : _attach ( parent ) 232if parent then 233-- Attach to parent 234parent . _children_idx =parent . _children_idx + 1 235parent . _children [ parent . _children_idx ] =self 236 237-- Keep track of the parent and this tasks index so we can detach 238self . _parent =parent 239self . _parent_children_idx =parent . _children_idx 240end 241end 242 243--- Remove this task from its parent without changing execution state. 244--- @private 245--- @return boolean removed 246function Task : _detach () 247if not self . _parent then 248return false 249end 250 251self . _parent . _children [ self . _parent_children_idx ] =nil 252self . _parent =nil 253self . _parent_children_idx =nil 254return true 255end 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> 276function Task : detach () 277local should_start =self . _parent and not self . _started and not self : completed () 278self : _detach () 279if should_start then 280runtime . schedule ( function () 281self : _start () 282end ) 283end 284return self 285end 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 293function Task : traceback ( msg , level ) 294level =level or 0 295 296local thread ='[' .. tostring ( self . _thread ) .. '] ' 297 298local awaiting =self . _awaiting 299if is_task ( awaiting ) then 300msg =awaiting : traceback ( msg , level + 1 ) 301end 302 303local tblvl =is_task ( awaiting ) and 2 or nil 304local tb =debug . traceback ( self . _thread , '' , tblvl ) or '' 305msg =( msg == nil and '' or tostring ( msg )) .. tb : gsub ( '\n\t' , '\n\t' .. thread ) 306 307if level == 0 then 308--- @type string 309msg =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 ) 313end 314 315return msg 316end 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 328function Task : raise_on_error () 329self : on_complete ( function ( err ) 330if err ~= nil then 331error ( self : traceback ( err ), 0 ) 332end 333end ) 334return self 335end 336 337--- @package 338function Task : _start () 339if self . _started or self : completed () then 340return 341end 342 343self . _started =true 344self : _resume () 345end 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 354function Task : _start_pending_children () 355for i =1 , self . _children_idx do 356local child =self . _children [ i ] 357if child then 358child : _start () 359end 360end 361end 362 363--- @private 364function Task : _close_children () 365for i =1 , self . _children_idx do 366local child =self . _children [ i ] 367if child then 368child : close () 369end 370end 371end 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 377function Task : _set_error ( err ) 378if self . _error == nil then 379self . _error =err 380end 381return self . _error 382end 383 384--- @package 385--- @param err any 386function Task : _raise ( err ) 387if 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. 390runtime . schedule ( function () 391if not self : completed () then 392self : _resume ( err ) 393end 394end ) 395else 396self : _resume ( err ) 397end 398end 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() 411function Task : close ( callback ) 412if not self : completed () and not self . _closing then 413self . _closing =true 414self : _raise ( 'closed' ) 415end 416if callback then 417self : on_complete ( function () 418callback () 419end ) 420end 421end 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? 429function Task : _child_failed ( child , err , child_was_awaited ) 430-- A parent close turns child "closed" results into cleanup, not failure. 431if child . _closing or child_was_awaited or ( self . _closing and err == 'closed' ) then 432return 433end 434 435local task_err =self : _set_error ( 'child error: ' .. util . _stringify_error ( err )) 436if 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. 439self : _close_children () 440else 441self : _raise ( task_err ) 442end 443end 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 449local function is_closable ( obj ) 450local ty =type ( obj ) 451return ( ty == 'table' or ty == 'userdata' ) and is_callable ( obj . close ) 452end 453 454do -- 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 459function Task : _finish_error ( parent , err ) 460if err == nil then 461err =self . _error 462end 463err =util . _normalize_error ( err ) 464if parent then 465parent : _child_failed ( self , err , parent . _awaiting == self ) 466end 467self . _future : complete ( err ) 468end 469 470--- @private 471--- @param stat boolean 472--- @param ... R... result 473function Task : _finish ( stat , ... ) 474if self : completed () then 475return 476end 477 478local parent =self . _parent 479self : _detach () 480 481threads [ self . _thread ] =nil 482 483if not stat then 484self : _finish_error ( parent , ... ) 485else 486if self . _error ~= nil then 487self : _finish_error ( parent , self . _error ) 488else 489self . _future : complete ( nil , ... ) 490end 491end 492end 493 494--- @package 495--- @param stat boolean 496--- @param ... R... result 497function Task : _finalize ( stat , ... ) 498if next ( self . _children ) == nil then 499self : _finish ( stat , ... ) 500return 501end 502 503local finish_args =pack_len ( stat , ... ) 504self . _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. 507local await_children =Task . _new ( 'await_children' , function () 508-- TODO(lewis6991): should we collect all errors? 509local close_remaining =not stat 510 511if close_remaining then 512self : _close_children () 513else 514self : _start_pending_children () 515end 516 517for i =1 , self . _children_idx do 518local child =self . _children [ i ] 519if child then 520-- Child failures are recorded on `self`. Protect this helper so one 521-- failed child cannot stop it awaiting the remaining cleanup. 522local 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. 525if not close_remaining and not self . _closing and not ok and not child . _closing then 526self : _set_error ( 'child error: ' .. util . _stringify_error ( err )) 527close_remaining =true 528self : _close_children () 529end 530end 531end 532 533self . _finalizing_children =false 534if stat and self . _closing and self . _error == nil then 535self : _finish ( false , 'closed' ) 536else 537self : _finish ( unpack_len ( finish_args )) 538end 539end ) 540await_children . _hidden =true 541await_children : _start () 542end 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 550local 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. 553if not protected and is_task ( yielded ) and err ~= nil then 554task : _set_error ( err ) 555end 556 557if protected then 558if err ~= nil then 559return task : _resume ( nil , false , err ) 560end 561return task : _resume ( nil , true , ... ) 562end 563 564return task : _resume ( err , ... ) 565end 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? 571local 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. 575local settled =false 576local 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. 585local sync_args --- @type false|{[integer]: any, n: integer}? 586local awaiting --- @type vim.async.Task<any>|vim.async.Closable? 587 588--- @param err? any 589--- @param ... any 590local function complete_await ( err , ... ) 591-- Cancellation and child failures resume through `_raise()`. Ignore a 592-- racing result so `_resume()` can finish awaitable cleanup first. 593if settled or task . _closing or task . _error ~= nil then 594return 595end 596settled =true 597 598if setup_ok == nil then 599if err == nil and select ( '#' , ... ) == 0 then 600sync_args =false 601else 602sync_args =pack_len ( err , ... ) 603end 604else 605-- The callback has fired. Keep `_awaiting` so `_resume()` can close a 606-- callback-style handle or retain a failed Task for its traceback. 607task . _awaiting_unsubscribe =nil 608 609if not task : completed () then 610return resume_from_await ( task , yielded , protected , err , ... ) 611end 612end 613end 614 615local unsubscribe 616local task_await --- @type boolean 617local 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. 623if is_task ( yielded ) then 624task_await =true 625--- @diagnostic disable-next-line: cast-local-type 626awaiting =yielded 627setup_ok , setup_result =pcall ( yielded . _future . on_complete , yielded . _future , complete_await ) 628else 629task_await =false 630-- Callback setup has one result: the optional closable. 631--- @type fun(callback: fun(err?: any, ...: any)): vim.async.Closable? 632local awaitable =yielded 633setup_ok , setup_result =pcall ( awaitable , complete_await ) 634end 635 636if not setup_ok then 637local err =util . _normalize_error ( setup_result ) 638if protected and settled then 639-- The first synchronous callback wins over a later setup error. 640awaiting =nil 641else 642settled =true 643return resume_from_await ( task , yielded , protected , err ) 644end 645elseif task_await then 646unsubscribe =setup_result 647else 648awaiting =setup_result 649end 650 651if not is_closable ( awaiting ) then 652awaiting =nil 653end 654--- @diagnostic disable-next-line: assign-type-mismatch 655task . _awaiting =awaiting 656 657if is_task ( awaiting ) then 658if not settled and unsubscribe then 659--- @diagnostic disable-next-line: assign-type-mismatch 660task . _awaiting_unsubscribe =unsubscribe 661end 662awaiting : _start () 663end 664 665if task : completed () then 666return 667end 668 669task : _start_pending_children () 670 671if sync_args == false then 672return resume_from_await ( task , yielded , protected ) 673elseif sync_args then 674return resume_from_await ( task , yielded , protected , unpack_len ( sync_args )) 675end 676end 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 683local function handle_resume ( task , stat , ... ) 684if coroutine . status ( task . _thread ) == 'dead' then 685-- The coroutine finished during resume. A normal return must not 686-- overwrite a pending task failure. 687if task . _error ~= nil and stat then 688task : _finalize ( false , task . _error ) 689elseif task . _closing and stat then 690task : _finalize ( false , 'closed' ) 691else 692task : _finalize ( stat , ... ) 693end 694return 695end 696 697local marker , yielded , protected =... 698if marker ~= yield_marker or ( not is_task ( yielded ) and not is_callable ( yielded )) then 699task : _finalize ( false , yield_error ) 700return 701end 702 703return start_await ( task , yielded , protected ) 704end 705 706--- Clear an await boundary and remove its Task completion callback. 707--- @param task vim.async.Task<any> 708local function clear_awaiting ( task ) 709local unsubscribe =task . _awaiting_unsubscribe 710task . _awaiting =nil 711task . _awaiting_unsubscribe =nil 712if unsubscribe then 713unsubscribe () 714end 715end 716 717--- @package 718--- @param err? any 719--- @param ... any resume values 720function 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. 726if 727is_task ( self . _awaiting ) 728and ( 729( self . _awaiting . _parent ~= self and self . _awaiting_unsubscribe ) 730or ( err == nil and self . _awaiting : completed ()) 731) 732then 733clear_awaiting ( self ) 734end 735 736local awaiting =self . _awaiting 737-- Only close awaitables owned by this task; external tasks are observed. 738if awaiting and ( not is_task ( awaiting ) or awaiting . _parent == self ) then 739local already_closing =false 740if type ( awaiting . is_closing ) == 'function' then 741already_closing =awaiting : is_closing () 742end 743 744if already_closing then 745clear_awaiting ( self ) 746return self : _resume ( err , ... ) 747end 748 749local 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 753local close_ok , close_err =pcall ( awaiting . close , awaiting , function () 754clear_awaiting ( self ) 755return self : _resume ( unpack_len ( args )) 756end ) 757 758if close_ok then 759return 760end 761clear_awaiting ( self ) 762return self : _resume ( util . _normalize_error ( close_err )) 763end 764 765-- An external coroutine.resume() may have already killed the coroutine. 766-- Finalize its pending failure instead of trying to resume it again. 767if coroutine . status ( self . _thread ) == 'dead' then 768self : _finalize ( false , err , ... ) 769return 770end 771 772return handle_resume ( self , coroutine . resume ( self . _thread , resume_marker , err , ... )) 773end 774end 775 776--- @package 777function Task : _log ( ... ) 778( tostring ( self . _thread ), ... ) 779end 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" 788function Task : status () 789if self : completed () then 790return 'completed' 791end 792 793local co_status =coroutine . status ( self . _thread ) 794if co_status == 'dead' then 795return 'awaiting' 796elseif co_status == 'suspended' then 797return 'awaiting' 798elseif 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. 803return 'normal' 804end 805assert ( co_status == 'running' ) 806return 'running' 807end 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 , ... ) 816validate ( 'func' , func , 'callable' ) 817local task =Task . _new ( name , func , ... ) 818task : _attach ( running ()) 819if runtime . debug then 820local info =debug . getinfo ( 2 , 'Sl' ) 821if info and info . currentline then 822task . _caller =( '%s:%d' ): format ( info . source , info . currentline ) 823end 824end 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. 831if not task . _parent then 832task : _start () 833end 834 835return 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 , ... ) 875if type ( func ) == 'string' then 876--- @diagnostic disable-next-line: param-type-mismatch 877return run ( func , ... ) 878elseif is_callable ( func ) then 879return run ( nil , func , ... ) 880end 881error ( '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 , ... ) 890if argc == 1 and select ( '#' , ... ) == 0 then 891-- Avoid allocating an empty argument table for the common await(func) shape. 892local cb_fun =fun 893--- @cast cb_fun fun(callback: fun(...: any)): any? 894--- @param callback fun(...: any) 895--- @return any? 896return function ( callback ) 897return cb_fun ( function ( ... ) 898callback ( nil , ... ) 899end ) 900end 901end 902 903local args =pack_len ( ... ) 904 905--- @param callback fun(...: any) 906--- @return any? 907return function ( callback ) 908args [ argc ] =function ( ... ) 909callback ( nil , ... ) 910end 911args . n =math . max ( args . n , argc ) 912return fun ( unpack_len ( args )) 913end 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 () 920local task =current_task () 921 922if task . _closing then 923error ( 'closed' , 0 ) 924elseif task . _error ~= nil then 925error ( task . _error , 0 ) 926end 927 928return 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 ( ... ) 938local arg1 =select ( 1 , ... ) 939 940if type ( arg1 ) == 'number' then 941return norm_cb_fun ( ... ) 942elseif type ( arg1 ) == 'function' then 943return norm_cb_fun ( 1 , arg1 ) 944elseif is_task ( arg1 ) then 945return arg1 946else 947error ( 'Invalid arguments, expected Task or (argc, func) got: ' .. tostring ( arg1 ), 2 ) 948end 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 ( ... ) 993check_current_task () 994return 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 ( ... ) 1030check_current_task () 1031return 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 () 1053M . await ( function ( callback ) 1054callback () 1055end ) 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 () 1070local task =running () 1071return 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 ) 1079local tasks ={} --- @type table<any, vim.async.Task<any>?> 1080if parent then 1081for _ , task in pairs ( parent . _children ) do 1082if not task . _hidden then 1083tasks [ # tasks + 1 ] =task 1084end 1085end 1086else 1087-- Gather for all detached tasks 1088for _ , task in pairs ( threads ) do 1089if not task . _parent and not task . _hidden then 1090tasks [ # tasks + 1 ] =task 1091end 1092end 1093end 1094 1095local r ={} --- @type string[] 1096for i , task in ipairs ( tasks ) do 1097local last =i == # tasks 1098local label =task . name or '' 1099if task . _caller then 1100label =label .. task . _caller 1101end 1102if label ~= '' then 1103label =label .. ' ' 1104end 1105r [ # r + 1 ] =( '%s%s%s[%s]' ): format ( 1106prefix or '' , 1107parent and ( last and '└─ ' or '├─ ' ) or '' , 1108label , 1109task : status () 1110) 1111local child_prefix =( prefix or '' ) .. ( parent and ( last and ' ' or '│ ' ) or '' ) 1112for _ , line in ipairs ( inspect ( task , child_prefix )) do 1113r [ # r + 1 ] =line 1114end 1115end 1116return 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 1126return table . concat ( inspect (), '\n' ) 1127end 1128 1129return M