robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- @brief 2--- 3--- [vim.iter()]() is an interface for [iterable]s: it wraps a table or function argument into an 4--- [Iter]() object with methods (such as [Iter:filter()] and [Iter:map()]) that transform the 5--- underlying source data. These methods can be chained to create iterator "pipelines": the output 6--- of each pipeline stage is input to the next stage. The first stage depends on the type passed to 7--- `vim.iter()`: 8--- 9--- - Lists or arrays (|lua-list|) yield only the value of each element. 10--- - Holes (nil values) are allowed (but discarded). 11--- - Use pairs() to treat array/list tables as dicts (preserve holes and non-contiguous integer 12--- keys): `vim.iter(pairs(…))`. 13--- - Use |Iter:enumerate()| to also pass the index to the next stage. 14--- - Or initialize with ipairs(): `vim.iter(ipairs(…))`. 15--- - Non-list tables (|lua-dict|) yield both the key and value of each element. 16--- - Function |iterator|s yield all values returned by the underlying function. 17--- - Tables with a |__call()| metamethod are treated as function iterators. 18--- 19--- The iterator pipeline terminates when the underlying |iterable| is exhausted (for function 20--- iterators this means it returned nil). 21--- 22--- Note: `vim.iter()` scans table input to decide if it is a list or a dict; to avoid this cost you 23--- can wrap the table with an iterator e.g. `vim.iter(ipairs({…}))`, but that precludes the use of 24--- |list-iterator| operations such as |IterArray:rev()|). 25--- 26--- Examples: 27--- 28--- ```lua 29--- local it = vim.iter({ 1, 2, 3, 4, 5 }) 30--- it:map(function(v) 31--- return v * 3 32--- end) 33--- it:rev() 34--- it:skip(2) 35--- it:totable() 36--- -- { 9, 6, 3 } 37--- 38--- -- ipairs() is a function iterator which returns both the index (i) and the value (v) 39--- vim.iter(ipairs({ 1, 2, 3, 4, 5 })):map(function(i, v) 40--- if i > 2 then return v end 41--- end):totable() 42--- -- { 3, 4, 5 } 43--- 44--- local it = vim.iter(vim.gsplit('1,2,3,4,5', ',')) 45--- it:map(function(s) return tonumber(s) end) 46--- for i, d in it:enumerate() do 47--- print(string.format("Column %d is %d", i, d)) 48--- end 49--- -- Column 1 is 1 50--- -- Column 2 is 2 51--- -- Column 3 is 3 52--- -- Column 4 is 4 53--- -- Column 5 is 5 54--- 55--- vim.iter({ a = 1, b = 2, c = 3, z = 26 }):any(function(k, v) 56--- return k == 'z' 57--- end) 58--- -- true 59--- 60--- local rb = vim.ringbuf(3) 61--- rb:push("a") 62--- rb:push("b") 63--- vim.iter(rb):totable() 64--- -- { "a", "b" } 65--- ``` 66 67-- `never` represents an empty tail for single-value iterators. 68--- @nodoc 69--- @class vim.IterModule 70--- @operator call: vim.Iter<any, any...> 71--- @overload fun<T>(src: T[]): vim.IterArray<T, never> 72--- @overload fun<K, V>(src: table<K, V>): vim.Iter<K, V> 73--- @overload fun(src: table, ...): vim.Iter<any, any...> 74--- @overload fun<S, C, R1, R...>(src: (fun(state: S, control: C): R1, R...), state?: S, control?: C): vim.Iter<R1, R...> 75local M ={} 76 77--- @nodoc 78--- @class vim.Iter<V1, V...> 79--- @field private _peeked V1|[V1, V...]? Cached peek value, if any. Nil if no value is peeked. 80--- @field private _next fun(): V1, V... The underlying function that returns the next packed value from the source. 81--- @overload fun(self: vim.Iter<V1, V...>): V1?, V... 82local Iter ={} 83Iter . __index =Iter 84 85function Iter : __call () 86return self : next () 87end 88 89-- Special case implementations for iterators on list tables. 90--- @nodoc 91--- @class vim.IterArray<V1, V...> : vim.Iter<V1, V...> 92--- @field private _table (V1|[V1, V...])[] Underlying table data. Items may be packed tuples after transforms. 93--- @field private _head integer Index to the front of a table iterator 94--- @field private _tail integer Index to the end of a table iterator (exclusive) 95local IterArray =setmetatable ( {} , Iter ) 96IterArray . __index =IterArray 97IterArray . __call =Iter . __call 98 99--- Packed tables use this as their metatable 100local packedmt ={} 101 102--- @generic V1, V... 103--- @param t V1|([V1, V...] & { n: integer }) 104--- @return V1?, V... 105local function unpack ( t ) 106if type ( t ) == 'table' and getmetatable ( t ) == packedmt then 107return _G . unpack ( t , 1 , t . n ) 108end 109return t 110end 111 112--- @generic T... 113--- @param ... T... Values to pack 114--- @return T|[T...] 115local function pack ( ... ) 116local n =select ( '#' , ... ) 117if n > 1 then 118return setmetatable ( { n =n , ... } , packedmt ) 119end 120return ... 121end 122 123--- @generic T 124--- @param t T 125local function sanitize ( t ) 126if type ( t ) == 'table' and getmetatable ( t ) == packedmt then 127--- @cast t table 128-- Remove length tag and metatable 129t . n =nil 130setmetatable ( t , nil ) 131end 132return t 133end 134 135--- Flattens a single array-like table. Errors if it attempts to flatten a 136--- dict-like table 137--- @param t any value which should be flattened 138--- @param max_depth integer depth to which the table should be flattened 139--- @param depth integer current iteration depth 140--- @param result table output table that contains flattened result 141--- @return table? flattened table if it can be flattened, otherwise nil 142local function flatten ( t , max_depth , depth , result ) 143if depth < max_depth and type ( t ) == 'table' then 144for k , v in pairs ( t ) do 145if type ( k ) ~= 'number' or k <= 0 or math . floor ( k ) ~= k then 146-- short-circuit: this is not a list like table 147return nil 148end 149 150if flatten ( v , max_depth , depth + 1 , result ) == nil then 151return nil 152end 153end 154elseif t ~= nil then 155result [ # result + 1 ] =t 156end 157 158return result 159end 160 161--- Determine if the current iterator stage should continue. 162--- 163--- If any arguments are passed to this function, then return those arguments 164--- and stop the current iterator stage. Otherwise, return true to signal that 165--- the current stage should continue. 166--- 167--- @param ... any Function arguments. 168--- @return boolean True if the iterator stage should continue, false otherwise 169--- @return any Function arguments. 170local function continue ( ... ) 171if select ( 1 , ... ) ~= nil then 172return false , ... 173end 174return true 175end 176 177--- If no input arguments are given return false, indicating the current 178--- iterator stage should stop. Otherwise, apply the arguments to the function 179--- f. If that function returns no values, the current iterator stage continues. 180--- Otherwise, those values are returned. 181--- 182--- @generic T, R 183--- @param f fun(...:T...): R... Function to call with the given arguments 184--- @param ... T... Arguments to apply to f 185--- @return boolean : True if the iterator pipeline should continue, false otherwise 186--- @return R... : Return values of f 187local function apply ( f , ... ) 188if select ( 1 , ... ) ~= nil then 189return continue ( f ( ... )) 190end 191return false 192end 193 194--- Filters an iterator pipeline. 195--- 196--- Example: 197--- 198--- ```lua 199--- local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded) 200--- ``` 201--- 202--- @param f fun(v: V1, ...: V...): boolean Takes all values returned from the previous stage 203--- in the pipeline and returns false or nil if the 204--- current iterator element should be removed. 205--- @return vim.Iter<V1, V...> 206--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>, f: fun(v: V1, ...: V...): boolean): vim.IterArray<V1, V...> 207function Iter : filter ( f ) 208return self : map ( function ( ... ) 209if f ( ... ) then 210return ... 211end 212end ) 213end 214 215--- @nodoc 216--- @param f fun(v: V1, ...: V...): boolean 217--- @return vim.IterArray<V1, V...> 218function IterArray : filter ( f ) 219local inc =self . _head < self . _tail and 1 or - 1 220local n =self . _head 221for i =self . _head , self . _tail - inc , inc do 222local v =self . _table [ i ] 223if f ( unpack ( v )) then 224self . _table [ n ] =v 225n =n + inc 226end 227end 228self . _tail =n 229return self 230end 231 232--- Removes duplicate values from an iterator pipeline. 233--- 234--- Only the first occurrence of each value is kept. 235--- 236--- Accepts an optional `key` argument, which if provided is called for each 237--- value in the iterator to compute a hash key for uniqueness comparison. This is 238--- useful for deduplicating table values or complex objects. 239--- If `key` returns `nil` for a value, that value will be considered unique, 240--- even if multiple values return `nil`. 241--- 242--- If a function-based iterator returns multiple arguments, uniqueness is 243--- checked based on the first return value. To change this behavior, specify 244--- `key`. 245--- 246--- Examples: 247--- 248--- ```lua 249--- vim.iter({ 1, 2, 2, 3, 2 }):unique():totable() 250--- -- { 1, 2, 3 } 251--- 252--- vim.iter({ {id=1}, {id=2}, {id=1} }) 253--- :unique(function(x) 254--- return x.id 255--- end) 256--- :totable() 257--- -- { {id=1}, {id=2} } 258--- ``` 259--- 260--- @since 14 261--- @param key? fun(v: V1, ...: V...): any Optional hash function to determine uniqueness of values. 262--- @return vim.Iter<V1, V...> 263--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>, key: fun(v: V1, ...: V...): any?): vim.IterArray<V1, V...> 264--- @see |vim.list.unique()| 265function Iter : unique ( key ) 266local seen ={} --- @type table<any,boolean> 267 268key =key or function ( a ) 269return a 270end 271 272return self : filter ( function ( ... ) 273local hash =key ( ... ) 274if hash == nil then 275return true 276elseif not seen [ hash ] then 277seen [ hash ] =true 278return true 279else 280return false 281end 282end ) 283end 284 285--- @nodoc 286--- @diagnostic disable-next-line:unused 287--- @param depth? integer 288function Iter : flatten ( depth ) 289error ( 'flatten() requires an array-like table' ) 290end 291 292--- Flattens a |list-iterator|, un-nesting nested values up to the given {depth}. 293--- Errors if it attempts to flatten a dict-like value. 294--- 295--- Examples: 296--- 297--- ```lua 298--- vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable() 299--- -- { 1, 2, { 3 } } 300--- 301--- vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable() 302--- -- { 1, { a = 2 }, 3 } 303--- 304--- vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable() 305--- -- error: attempt to flatten a dict-like table 306--- ``` 307--- 308--- @since 12 309--- @param depth? integer Depth to which |list-iterator| should be flattened 310--- (defaults to 1) 311--- @return vim.IterArray<V1, V...> 312function IterArray : flatten ( depth ) 313depth =depth or 1 314local inc =self . _head < self . _tail and 1 or - 1 315local target ={} 316 317for i =self . _head , self . _tail - inc , inc do 318local flattened =flatten ( self . _table [ i ], depth , 0 , {} ) 319 320-- exit early if we try to flatten a dict-like table 321if flattened == nil then 322error ( 'flatten() requires an array-like table' ) 323end 324 325for _ , v in pairs ( flattened ) do 326target [ # target + 1 ] =v 327end 328end 329 330self . _head =1 331self . _tail =# target + 1 332self . _table =target 333return self 334end 335 336--- Maps the items of an iterator pipeline to the values returned by `f`. 337--- 338--- If the map function returns nil, the value is filtered from the iterator. 339--- 340--- Example: 341--- 342--- ```lua 343--- local it = vim.iter({ 1, 2, 3, 4 }):map(function(v) 344--- if v % 2 == 0 then 345--- return v * 3 346--- end 347--- end) 348--- it:totable() 349--- -- { 6, 12 } 350--- ``` 351--- 352--- @since 12 353--- @generic K2, V2... 354--- @param f fun(v: V1, ...: V...): K2, V2... Mapping function. Takes all values returned from 355--- the previous stage in the pipeline as arguments 356--- and returns one or more new values, which are used 357--- in the next pipeline stage. Nil return values 358--- are filtered from the output. 359--- @return vim.Iter<K2, V2...> 360--- @overload fun<V1, V..., K1, K...>(self: vim.IterArray<V1, V...>, f: fun(v: V1, ...: V...): K1, K...): vim.IterArray<K1, K...> 361function Iter : map ( f ) 362-- Implementation note: the reader may be forgiven for observing that this 363-- function appears excessively convoluted. The problem to solve is that each 364-- stage of the iterator pipeline can return any number of values, and the 365-- number of values could even change per iteration. And the return values 366-- must be checked to determine if the pipeline has ended, so we cannot 367-- naively forward them along to the next stage. 368-- 369-- A simple approach is to pack all of the return values into a table, check 370-- for nil, then unpack the table for the next stage. However, packing and 371-- unpacking tables is quite slow. There is no other way in Lua to handle an 372-- unknown number of function return values than to simply forward those 373-- values along to another function. Hence the intricate function passing you 374-- see here. 375 376local next =self . next 377 378--- Drain values from the upstream iterator source until a value can be 379--- returned. 380--- 381--- This is a recursive function. The base case is when the first argument is 382--- false, which indicates that the rest of the arguments should be returned 383--- as the values for the current iteration stage. 384--- 385--- @param cont boolean If true, the current iterator stage should continue to 386--- pull values from its upstream pipeline stage. 387--- Otherwise, this stage is complete and returns the 388--- values passed. 389--- @param ... any Values to return if cont is false. 390--- @return any 391local function fn ( cont , ... ) 392if cont then 393return fn ( apply ( f , next ( self ))) 394end 395return ... 396end 397 398--- @diagnostic disable-next-line: duplicate-set-field 399self . next =function () 400return fn ( apply ( f , next ( self ))) 401end 402return self 403end 404 405--- @nodoc 406--- @generic K1, K... 407--- @param f fun(v: V1, ...: V...): K1, K... 408--- @return vim.IterArray<K1, K...> 409function IterArray : map ( f ) 410local inc =self . _head < self . _tail and 1 or - 1 411local n =self . _head 412for i =self . _head , self . _tail - inc , inc do 413local v =pack ( f ( unpack ( self . _table [ i ]))) 414if v ~= nil then 415self . _table [ n ] =v 416n =n + inc 417end 418end 419self . _tail =n 420return self 421end 422 423--- Calls a function once for each item in the pipeline, draining the iterator. 424--- 425--- For functions with side effects. To modify the values in the iterator, use |Iter:map()|. 426--- 427--- @since 12 428--- @param f fun(v: V1, ...: V...) Function to execute for each item in the pipeline. 429--- Takes all of the values returned by the previous stage 430--- in the pipeline as arguments. 431function Iter : each ( f ) 432--- @param ... any 433local function fn ( ... ) 434if select ( 1 , ... ) ~= nil then 435f ( ... ) 436return true 437end 438end 439while fn ( self : next ()) do 440end 441end 442 443--- @nodoc 444--- @param f fun(v: V1, ...: V...) 445function IterArray : each ( f ) 446local inc =self . _head < self . _tail and 1 or - 1 447for i =self . _head , self . _tail - inc , inc do 448f ( unpack ( self . _table [ i ])) 449end 450self . _head =self . _tail 451end 452 453--- Collect the iterator into a table. 454--- 455--- The resulting table depends on the initial source in the iterator pipeline. 456--- Array-like tables and function iterators will be collected into an array-like 457--- table. If multiple values are returned from the final stage in the iterator 458--- pipeline, each value will be included in a table. 459--- 460--- Examples: 461--- 462--- ```lua 463--- vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable() 464--- -- { 100, 20, 50 } 465--- 466--- vim.iter({ 1, 2, 3 }):map(function(v) return v, 2 * v end):totable() 467--- -- { { 1, 2 }, { 2, 4 }, { 3, 6 } } 468--- 469--- vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable() 470--- -- { { 'a', 1 }, { 'c', 3 } } 471--- ``` 472--- 473--- The generated table is an array-like table with consecutive, numeric indices. 474--- To create a map-like table with arbitrary keys, use |Iter:fold()|. 475--- 476--- 477--- @since 12 478--- @return any[] 479function Iter : totable () 480local t ={} 481 482while true do 483local args =pack ( self : next ()) 484if args == nil then 485break 486end 487 488t [ # t + 1 ] =sanitize ( args ) 489end 490return t 491end 492 493--- @nodoc 494--- @return any[] 495function IterArray : totable () 496if self . next ~= IterArray . next or self . _head >= self . _tail then 497return Iter . totable ( self ) 498end 499 500local needs_sanitize =getmetatable ( self . _table [ self . _head ]) == packedmt 501 502-- Reindex and sanitize. 503local len =self . _tail - self . _head 504 505if needs_sanitize then 506for i =1 , len do 507self . _table [ i ] =sanitize ( self . _table [ self . _head - 1 + i ]) 508end 509else 510for i =1 , len do 511self . _table [ i ] =self . _table [ self . _head - 1 + i ] 512end 513end 514 515for i =len + 1 , table . maxn ( self . _table ) do 516self . _table [ i ] =nil 517end 518 519self . _head =1 520self . _tail =len + 1 521 522return self . _table 523end 524 525--- Collect the iterator into a delimited string. 526--- 527--- Each element in the iterator is joined into a string separated by {delim}. 528--- 529--- Consumes the iterator. 530--- 531--- @since 12 532--- @param delim string Delimiter 533--- @return string 534function Iter : join ( delim ) 535return table . concat ( self : totable (), delim ) 536end 537 538--- Folds ("reduces") an iterator into a single value. [Iter:reduce()]() 539--- 540--- Examples: 541--- 542--- ```lua 543--- -- Create a new table with only even values 544--- vim.iter({ a = 1, b = 2, c = 3, d = 4 }) 545--- :filter(function(k, v) return v % 2 == 0 end) 546--- :fold({}, function(acc, k, v) 547--- acc[k] = v 548--- return acc 549--- end) --> { b = 2, d = 4 } 550--- 551--- -- Get the "maximum" item of an iterable. 552--- vim.iter({ -99, -4, 3, 42, 0, 0, 7 }) 553--- :fold({}, function(acc, v) 554--- acc.max = math.max(v, acc.max or v) 555--- return acc 556--- end) --> { max = 42 } 557--- ``` 558--- 559--- 560--- @since 12 561--- @generic A 562--- @param init A Initial value of the accumulator. 563--- @param f fun(acc: A, v: V1, ...: V...): A Accumulation function. 564--- @return A 565function Iter : fold ( init , f ) 566local acc =init 567 568--- Use a closure to handle var args returned from iterator 569--- @param ... any 570local function fn ( ... ) 571if select ( 1 , ... ) ~= nil then 572acc =f ( acc , ... ) 573return true 574end 575end 576 577while fn ( self : next ()) do 578end 579return acc 580end 581 582--- @nodoc 583--- @generic A 584--- @param init A 585--- @param f fun(acc: A, v: V1, ...: V...): A 586--- @return A 587function IterArray : fold ( init , f ) 588local acc =init 589local inc =self . _head < self . _tail and 1 or - 1 590for i =self . _head , self . _tail - inc , inc do 591acc =f ( acc , unpack ( self . _table [ i ])) 592end 593return acc 594end 595 596--- @diagnostic disable-next-line: duplicate-set-field 597--- Gets the next value from the iterator. 598--- 599--- Example: 600--- 601--- ```lua 602--- 603--- local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber) 604--- it:next() 605--- -- 1 606--- it:next() 607--- -- 2 608--- it:next() 609--- -- 3 610--- 611--- ``` 612--- 613--- @since 12 614--- @return V1?, V... 615function Iter : next () 616if self . _peeked then 617local v =self . _peeked 618self . _peeked =nil 619 620return unpack ( v ) 621end 622 623return self . _next () 624end 625 626--- @nodoc 627--- @return V1?, V... 628function IterArray : next () 629if self . _head ~= self . _tail then 630local v =self . _table [ self . _head ] 631local inc =self . _head < self . _tail and 1 or - 1 632self . _head =self . _head + inc 633return unpack ( v ) 634end 635end 636 637--- @nodoc 638--- @diagnostic disable-next-line: unused 639function Iter : rev () 640error ( 'rev() requires an array-like table' ) 641end 642 643--- Reverses a |list-iterator| pipeline. 644--- 645--- Example: 646--- 647--- ```lua 648--- 649--- local it = vim.iter({ 3, 6, 9, 12 }):rev() 650--- it:totable() 651--- -- { 12, 9, 6, 3 } 652--- 653--- ``` 654--- 655--- @since 12 656--- @return vim.IterArray<V1, V...> 657function IterArray : rev () 658local inc =self . _head < self . _tail and 1 or - 1 659self . _head , self . _tail =self . _tail - inc , self . _head - inc 660return self 661end 662 663--- Gets the next value from the iterator without consuming it. 664--- 665--- The value returned by |Iter:peek()| will be returned again by the next call 666--- to |Iter:next()|. 667--- 668--- Example: 669--- 670--- ```lua 671--- 672--- local it = vim.iter({ 3, 6, 9, 12 }) 673--- it:peek() 674--- -- 3 675--- it:peek() 676--- -- 3 677--- it:next() 678--- -- 3 679--- 680--- ``` 681--- 682--- @since 12 683--- @return V1?, V... 684function Iter : peek () 685if not self . _peeked then 686self . _peeked =pack ( self : next ()) 687end 688 689return unpack ( self . _peeked ) 690end 691 692--- @nodoc 693--- @return V1?, V... 694function IterArray : peek () 695if self . _head ~= self . _tail then 696return unpack ( self . _table [ self . _head ]) 697end 698end 699 700--- Find the first value in the iterator that satisfies the given predicate. 701--- 702--- Advances the iterator. Returns nil and drains the iterator if no value is found. 703--- 704--- Examples: 705--- 706--- ```lua 707--- 708--- local it = vim.iter({ 3, 6, 9, 12 }) 709--- it:find(12) 710--- -- 12 711--- 712--- local it = vim.iter({ 3, 6, 9, 12 }) 713--- it:find(20) 714--- -- nil 715--- 716--- local it = vim.iter({ 3, 6, 9, 12 }) 717--- it:find(function(v) return v % 4 == 0 end) 718--- -- 12 719--- 720--- ``` 721--- @since 12 722--- @param f V1|fun(v: V1, ...: V...): any 723--- @return V1?, V... 724function Iter : find ( f ) 725if type ( f ) ~= 'function' then 726local val =f 727--- @param v V1 728f =function ( v ) 729return v == val 730end 731end 732 733local result =nil 734 735--- Use a closure to handle var args returned from iterator 736--- @param ... any 737local function fn ( ... ) 738if select ( 1 , ... ) ~= nil then 739if f ( ... ) then 740result =pack ( ... ) 741else 742return true 743end 744end 745end 746 747while fn ( self : next ()) do 748end 749return unpack ( result ) 750end 751 752--- @nodoc 753--- @diagnostic disable-next-line:unused 754--- @param f V1|fun(v: V1, ...: V...): boolean 755function Iter : rfind ( f ) 756error ( 'rfind() requires an array-like table' ) 757end 758 759--- Gets the first value satisfying a predicate, from the end of a |list-iterator|. 760--- 761--- Advances the iterator. Returns nil and drains the iterator if no value is found. 762--- 763--- Examples: 764--- 765--- ```lua 766--- 767--- local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate() 768--- it:rfind(1) 769--- -- 5 1 770--- it:rfind(1) 771--- -- 1 1 772--- 773--- ``` 774--- 775--- @see |Iter:find()| 776--- 777--- @since 12 778--- @param f V1|fun(v: V1, ...: V...): boolean 779--- @return V1?, V... 780function IterArray : rfind ( f ) 781if type ( f ) ~= 'function' then 782local val =f 783--- @param v V1 784f =function ( v ) 785return v == val 786end 787end 788 789local inc =self . _head < self . _tail and 1 or - 1 790for i =self . _tail - inc , self . _head , - inc do 791local v =self . _table [ i ] 792if f ( unpack ( v )) then 793self . _tail =i 794return unpack ( v ) 795end 796end 797self . _head =self . _tail 798end 799 800--- Transforms an iterator to yield only the first n values, or all values 801--- satisfying a predicate. 802--- 803--- Example: 804--- 805--- ```lua 806--- local it = vim.iter({ 1, 2, 3, 4 }):take(2) 807--- it:next() 808--- -- 1 809--- it:next() 810--- -- 2 811--- it:next() 812--- -- nil 813--- 814--- local function pred(x) return x < 2 end 815--- local it2 = vim.iter({ 1, 2, 3, 4 }):take(pred) 816--- it2:next() 817--- -- 1 818--- it2:next() 819--- -- nil 820--- ``` 821--- 822--- @since 12 823--- @param n integer|fun(v: V1, ...: V...): boolean Number of values to take or a predicate. 824--- @return vim.Iter<V1, V...> 825--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>, n: integer|fun(v: V1, ...: V...): boolean): vim.IterArray<V1, V...> 826function Iter : take ( n ) 827local i =0 828local pred --- @type fun(...): boolean 829if type ( n ) == 'function' then 830pred =n 831else 832local limit =n 833pred =function () 834return i < limit 835end 836end 837 838local stop =false 839 840--- @generic A... 841--- @param ... A... 842--- @return A... 843local function fn ( ... ) 844if not stop and select ( 1 , ... ) ~= nil and pred ( ... ) then 845i =i + 1 846return ... 847else 848stop =true 849end 850end 851 852local next =self . next 853--- @diagnostic disable-next-line:duplicate-set-field 854self . next =function () 855return fn ( next ( self )) 856end 857return self 858end 859 860--- @nodoc 861--- @param n integer|fun(v: V1, ...: V...): boolean 862--- @return vim.IterArray<V1, V...> 863function IterArray : take ( n ) 864if type ( n ) == 'function' then 865local inc =self . _head < self . _tail and 1 or - 1 866for i =self . _head , self . _tail - inc , inc do 867if not n ( unpack ( self . _table [ i ])) then 868self . _tail =i 869break 870end 871end 872return self 873end 874 875local inc =self . _head < self . _tail and n or - n 876local cmp =self . _head < self . _tail and math . min or math . max 877self . _tail =cmp ( self . _tail , self . _head + inc ) 878return self 879end 880 881--- @nodoc 882--- @diagnostic disable-next-line: unused 883function Iter : pop () 884error ( 'pop() requires an array-like table' ) 885end 886 887--- "Pops" a value from a |list-iterator| (gets the last value and decrements the tail). 888--- 889--- Example: 890--- 891--- ```lua 892--- local it = vim.iter({1, 2, 3, 4}) 893--- it:pop() 894--- -- 4 895--- it:pop() 896--- -- 3 897--- ``` 898--- 899--- @since 12 900--- @return V1?, V... 901function IterArray : pop () 902if self . _head ~= self . _tail then 903local inc =self . _head < self . _tail and 1 or - 1 904self . _tail =self . _tail - inc 905return unpack ( self . _table [ self . _tail ]) 906end 907end 908 909--- @nodoc 910--- @diagnostic disable-next-line: unused 911function Iter : rpeek () 912error ( 'rpeek() requires an array-like table' ) 913end 914 915--- Gets the last value of a |list-iterator| without consuming it. 916--- 917--- Example: 918--- 919--- ```lua 920--- local it = vim.iter({1, 2, 3, 4}) 921--- it:rpeek() 922--- -- 4 923--- it:rpeek() 924--- -- 4 925--- it:pop() 926--- -- 4 927--- ``` 928--- 929--- @see |Iter:last()| 930--- 931--- @since 12 932--- @return V1?, V... 933function IterArray : rpeek () 934if self . _head ~= self . _tail then 935local inc =self . _head < self . _tail and 1 or - 1 936return unpack ( self . _table [ self . _tail - inc ]) 937end 938end 939 940--- Skips `n` values of an iterator pipeline, or skips values while a predicate returns |lua-truthy|. 941--- 942--- When a predicate is used, skipping stops at the first value for which the 943--- predicate returns non-truthy. That value is not consumed and will be returned 944--- by the next call to |Iter:next()| 945--- 946--- Example: 947--- 948--- ```lua 949--- 950--- local it = vim.iter({ 3, 6, 9, 12 }):skip(2) 951--- it:next() 952--- -- 9 953--- 954--- local function pred(x) return x < 10 end 955--- local it2 = vim.iter({ 3, 6, 9, 12 }):skip(pred) 956--- it2:next() 957--- -- 12 958--- ``` 959--- 960--- @since 12 961--- @param n integer|fun(v: V1, ...: V...): boolean Number of values to skip or a predicate. 962--- @return vim.Iter<V1, V...> 963--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>, n: integer|fun(v: V1, ...: V...): boolean): vim.IterArray<V1, V...> 964function Iter : skip ( n ) 965if type ( n ) == 'number' then 966for _ =1 , n do 967self . _peeked =nil 968local _ =self : next () 969end 970elseif type ( n ) == 'function' then 971local next =self . next 972 973--- @return V1?, V... 974--- @diagnostic disable-next-line:duplicate-set-field 975self . next =function () 976while true do 977local peeked =self . _peeked or pack ( next ( self )) 978 979if not peeked then 980return nil 981end 982 983if not n ( unpack ( peeked )) then 984self . _peeked =nil 985return unpack ( peeked ) 986end 987 988self . _peeked =nil 989end 990end 991end 992return self 993end 994 995--- @nodoc 996--- @param n integer|fun(v: V1, ...: V...): boolean 997--- @return vim.IterArray<V1, V...> 998function IterArray : skip ( n ) 999if type ( n ) == 'function' then 1000while self . _head ~= self . _tail do 1001local v =self . _table [ self . _head ] 1002if not n ( unpack ( v )) then 1003break 1004end 1005 1006self . _head =self . _head + ( self . _head < self . _tail and 1 or - 1 ) 1007end 1008return self 1009end 1010 1011local inc =self . _head < self . _tail and n or - n 1012self . _head =self . _head + inc 1013if ( inc > 0 and self . _head > self . _tail ) or ( inc < 0 and self . _head < self . _tail ) then 1014self . _head =self . _tail 1015end 1016return self 1017end 1018 1019--- @nodoc 1020--- @diagnostic disable-next-line:unused 1021--- @param n integer 1022function Iter : rskip ( n ) 1023error ( 'rskip() requires an array-like table' ) 1024end 1025 1026--- Discards `n` values from the end of a |list-iterator| pipeline. 1027--- 1028--- Example: 1029--- 1030--- ```lua 1031--- local it = vim.iter({ 1, 2, 3, 4, 5 }):rskip(2) 1032--- it:next() 1033--- -- 1 1034--- it:pop() 1035--- -- 3 1036--- ``` 1037--- 1038--- @since 12 1039--- @param n integer 1040--- @return vim.IterArray<V1, V...> 1041function IterArray : rskip ( n ) 1042local inc =self . _head < self . _tail and n or vim . _assert_integer ( - n ) 1043self . _tail =vim . _assert_integer ( self . _tail - inc ) 1044if ( inc > 0 and self . _head > self . _tail ) or ( inc < 0 and self . _head < self . _tail ) then 1045self . _head =self . _tail 1046end 1047return self 1048end 1049 1050--- Gets the nth value of an iterator (and advances to it). 1051--- 1052--- If `n` is negative, offsets from the end of a |list-iterator|. 1053--- 1054--- Example: 1055--- 1056--- ```lua 1057--- local it = vim.iter({ 3, 6, 9, 12 }) 1058--- it:nth(2) 1059--- -- 6 1060--- it:nth(2) 1061--- -- 12 1062--- 1063--- local it2 = vim.iter({ 3, 6, 9, 12 }) 1064--- it2:nth(-2) 1065--- -- 9 1066--- it2:nth(-2) 1067--- -- 3 1068--- ``` 1069--- 1070--- @since 12 1071--- @param n integer Index of the value to return. May be negative if the source is a |list-iterator|. 1072--- @return V1?, V... 1073function Iter : nth ( n ) 1074if n > 0 then 1075return self : skip ( n - 1 ): next () 1076elseif n < 0 then 1077return self : rskip ( math . abs ( n ) - 1 ): pop () 1078end 1079end 1080 1081--- @nodoc 1082--- @diagnostic disable-next-line:unused 1083--- @param first integer 1084--- @param last integer 1085function Iter : slice ( first , last ) 1086error ( 'slice() requires an array-like table' ) 1087end 1088 1089--- Sets the start and end of a |list-iterator| pipeline. 1090--- 1091--- Equivalent to `:skip(first - 1):rskip(len - last + 1)`. 1092--- 1093--- @since 12 1094--- @param first integer 1095--- @param last integer 1096--- @return vim.IterArray<V1, V...> 1097function IterArray : slice ( first , last ) 1098local left =vim . _assert_integer ( math . max ( 0 , first - 1 )) 1099local right =vim . _assert_integer ( math . max ( 0 , self . _tail - last - 1 )) 1100return self : skip ( left ): rskip ( right ) 1101end 1102 1103--- Returns true if any of the items in the iterator match the given predicate. 1104--- 1105--- @since 12 1106--- @param pred fun(v: V1, ...: V...): boolean Predicate function. Takes all values returned from the previous 1107--- stage in the pipeline as arguments and returns true if the 1108--- predicate matches. 1109function Iter : any ( pred ) 1110local any =false 1111 1112--- Use a closure to handle var args returned from iterator 1113--- @param ... any 1114local function fn ( ... ) 1115if select ( 1 , ... ) ~= nil then 1116if pred ( ... ) then 1117any =true 1118else 1119return true 1120end 1121end 1122end 1123 1124while fn ( self : next ()) do 1125end 1126return any 1127end 1128 1129--- Returns true if all items in the iterator match the given predicate. 1130--- 1131--- @since 12 1132--- @param pred fun(v: V1, ...: V...): boolean Predicate function. Takes all values returned from the previous 1133--- stage in the pipeline as arguments and returns true if the 1134--- predicate matches. 1135function Iter : all ( pred ) 1136local all =true 1137 1138--- @param ... any 1139local function fn ( ... ) 1140if select ( 1 , ... ) ~= nil then 1141if not pred ( ... ) then 1142all =false 1143else 1144return true 1145end 1146end 1147end 1148 1149while fn ( self : next ()) do 1150end 1151return all 1152end 1153 1154--- Drains the iterator and returns the last item. 1155--- 1156--- Example: 1157--- 1158--- ```lua 1159--- 1160--- local it = vim.iter(vim.gsplit('abcdefg', '')) 1161--- it:last() 1162--- -- 'g' 1163--- 1164--- local it = vim.iter({ 3, 6, 9, 12, 15 }) 1165--- it:last() 1166--- -- 15 1167--- 1168--- ``` 1169--- 1170--- @since 12 1171--- @see |IterArray:rpeek()| 1172--- @return V1?, V... 1173function Iter : last () 1174local last =self : next () 1175local cur =self : next () 1176while cur do 1177last =cur 1178cur =self : next () 1179end 1180return last 1181end 1182 1183--- @nodoc 1184--- @return V1?, V... 1185function IterArray : last () 1186if self . _head == self . _tail then 1187return nil 1188end 1189local inc =self . _head < self . _tail and 1 or - 1 1190local v =self . _table [ self . _tail - inc ] 1191self . _head =self . _tail 1192return unpack ( v ) 1193end 1194 1195--- Yields the item index (count) and value for each item of an iterator pipeline. 1196--- 1197--- For list tables, this is more efficient: 1198--- 1199--- ```lua 1200--- vim.iter(ipairs(t)) 1201--- ``` 1202--- 1203--- instead of: 1204--- 1205--- ```lua 1206--- vim.iter(t):enumerate() 1207--- ``` 1208--- 1209--- Example: 1210--- 1211--- ```lua 1212--- 1213--- local it = vim.iter(vim.gsplit('abc', '')):enumerate() 1214--- it:next() 1215--- -- 1 'a' 1216--- it:next() 1217--- -- 2 'b' 1218--- it:next() 1219--- -- 3 'c' 1220--- 1221--- ``` 1222--- 1223--- @since 12 1224--- @overload fun<V1, V...>(self: vim.IterArray<V1, V...>): vim.IterArray<integer, V1, V...> 1225--- @return vim.Iter<integer, V1, V...> 1226function Iter : enumerate () 1227local i =0 1228return self : map ( function ( ... ) 1229i =i + 1 1230return i , ... 1231end ) 1232end 1233 1234--- @nodoc 1235--- @return vim.IterArray<integer, V1, V...> 1236function IterArray : enumerate () 1237local inc =self . _head < self . _tail and 1 or - 1 1238local n =0 1239for i =self . _head , self . _tail - inc , inc do 1240n =n + 1 1241local v =self . _table [ i ] 1242self . _table [ i ] =pack ( n , unpack ( v )) 1243end 1244return self 1245end 1246 1247--- Drains the iterator, counting the number of iterations and returning it. 1248--- 1249--- @since 15 1250--- @return integer 1251function Iter : count () 1252return self : fold ( 0 , function ( acc ) 1253return acc + 1 1254end ) 1255end 1256 1257--- @nodoc 1258--- @return integer 1259function IterArray : count () 1260local count =math . abs ( self . _tail - self . _head ) 1261self . _head =self . _tail 1262return count 1263end 1264 1265--- Creates a new Iter object from a table or other |iterable|. 1266--- 1267--- @generic R1, R... 1268--- @param src table<R1, R>|fun(s: table, v: any): R1, R... Table or iterator to drain values from 1269--- @return vim.Iter<R1, R...> 1270--- @overload fun<T>(src: T[]): vim.IterArray<T, never> 1271--- @overload fun<K, V>(src: table<K, V>): vim.Iter<K, V> 1272--- @private 1273function Iter . new ( src , ... ) 1274local it ={} 1275if type ( src ) == 'table' then 1276local mt =getmetatable ( src ) 1277if mt and type ( mt . __call ) == 'function' then 1278--- @private 1279it . _next =function () 1280return mt . __call ( src ) 1281end 1282 1283return setmetatable ( it , Iter ) 1284end 1285 1286local t ={} 1287 1288-- O(n): scan the source table to decide if it is an array (only positive integer indices). 1289for k , v in pairs ( src ) do 1290if type ( k ) ~= 'number' or k <= 0 or math . floor ( k ) ~= k then 1291return Iter . new ( pairs ( src )) 1292end 1293t [ # t + 1 ] =v -- Coerce to list-like table. 1294end 1295return IterArray . new ( t ) 1296elseif type ( src ) ~= 'function' then 1297error ( 'src must be a table or function' ) 1298end 1299 1300local s , var =... 1301 1302--- Use a closure to handle var args returned from iterator 1303local function fn ( ... ) 1304-- Per the Lua 5.1 reference manual, an iterator is complete when the first returned value is 1305-- nil (even if there are other, non-nil return values). See |for-in|. 1306if select ( 1 , ... ) ~= nil then 1307var =select ( 1 , ... ) 1308return ... 1309end 1310end 1311 1312--- @private 1313it . _next =function () 1314return fn ( src ( s , var )) 1315end 1316 1317return setmetatable ( it , Iter ) 1318end 1319 1320--- Create a new IterArray 1321--- 1322--- @generic V1, V... 1323--- @param t (V1|[V1, V...])[] List-like table. Caller guarantees that this table is a valid 1324--- internal list buffer. 1325--- @return vim.IterArray<V1, V...> 1326--- @private 1327function IterArray . new ( t ) 1328return setmetatable ( { 1329_table =t , 1330_head =1 , 1331_tail =# t + 1 , 1332} , IterArray ) 1333end 1334 1335setmetatable ( M , { 1336__call =function ( _ , ... ) 1337return Iter . new ( ... ) 1338end , 1339} ) 1340 1341-- Return M separately to work around EmmyLuaLs/emmylua-analyzer-rust#1240. 1342return M