Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/lua/blob/master/testes/coroutine.lua # lua [Ported from github.com/lua/lua] Cast in 'rl_readline_name' Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `lua / testes / coroutine.lua` 1279 lines ยท 35198 bytes Raw Blame History 1 -- $Id: testes/coroutine.lua $ 2 -- See Copyright Notice in file lua.h 3 4 print "testing coroutines" 5 6 local debug = require'debug' 7 8 local f 9 10 local main, ismain = coroutine.running() 11 assert(type(main) == "thread" and ismain) 12 assert(not coroutine.resume(main)) 13 assert(not coroutine.isyieldable(main) and not coroutine.isyieldable()) 14 assert(not pcall(coroutine.yield)) 15 16 17 -- trivial errors 18 assert(not pcall(coroutine.resume, 0)) 19 assert(not pcall(coroutine.status, 0)) 20 21 22 -- tests for multiple yield/resume arguments 23 24 local function eqtab (t1, t2) 25 assert(#t1 == #t2) 26 for i = 1, #t1 do 27 local v = t1[i] 28 assert(t2[i] == v) 29 end 30 end 31 32 _G.x = nil -- declare x 33 _G.f = nil -- declare f 34 local function foo (a, ...) 35 local x, y = coroutine.running() 36 assert(x == f and y == false) 37 -- next call should not corrupt coroutine (but must fail, 38 -- as it attempts to resume the running coroutine) 39 assert(coroutine.resume(f) == false) 40 assert(coroutine.status(f) == "running") 41 local arg = {...} 42 assert(coroutine.isyieldable(x)) 43 for i=1,#arg do 44 _G.x = {coroutine.yield(table.unpack(arg[i]))} 45 end 46 return table.unpack(a) 47 end 48 49 f = coroutine.create(foo) 50 assert(coroutine.isyieldable(f)) 51 assert(type(f) == "thread" and coroutine.status(f) == "suspended") 52 assert(string.find(tostring(f), "thread")) 53 local s,a,b,c,d 54 s,a,b,c,d = coroutine.resume(f, {1,2,3}, {}, {1}, {'a', 'b', 'c'}) 55 assert(coroutine.isyieldable(f)) 56 assert(s and a == nil and coroutine.status(f) == "suspended") 57 s,a,b,c,d = coroutine.resume(f) 58 eqtab(_G.x, {}) 59 assert(s and a == 1 and b == nil) 60 assert(coroutine.isyieldable(f)) 61 s,a,b,c,d = coroutine.resume(f, 1, 2, 3) 62 eqtab(_G.x, {1, 2, 3}) 63 assert(s and a == 'a' and b == 'b' and c == 'c' and d == nil) 64 s,a,b,c,d = coroutine.resume(f, "xuxu") 65 eqtab(_G.x, {"xuxu"}) 66 assert(s and a == 1 and b == 2 and c == 3 and d == nil) 67 assert(coroutine.status(f) == "dead") 68 s, a = coroutine.resume(f, "xuxu") 69 assert(not s and string.find(a, "dead") and coroutine.status(f) == "dead") 70 71 _G.f = nil 72 73 -- yields in tail calls 74 local function foo (i) return coroutine.yield(i) end 75 local f = coroutine.wrap(function () 76 for i=1,10 do 77 assert(foo(i) == _G.x) 78 end 79 return 'a' 80 end) 81 for i=1,10 do _G.x = i; assert(f(i) == i) end 82 _G.x = 'xuxu'; assert(f('xuxu') == 'a') 83 84 _G.x = nil 85 86 -- recursive 87 local function pf (n, i) 88 coroutine.yield(n) 89 pf(n*i, i+1) 90 end 91 92 f = coroutine.wrap(pf) 93 local s=1 94 for i=1,10 do 95 assert(f(1, 1) == s) 96 s = s*i 97 end 98 99 -- sieve 100 local function gen (n) 101 return coroutine.wrap(function () 102 for i=2,n do coroutine.yield(i) end 103 end) 104 end 105 106 107 local function filter (p, g) 108 return coroutine.wrap(function () 109 while 1 do 110 local n = g() 111 if n == nil then return end 112 if math.fmod(n, p) ~= 0 then coroutine.yield(n) end 113 end 114 end) 115 end 116 117 local x = gen(80) 118 local a = {} 119 while 1 do 120 local n = x() 121 if n == nil then break end 122 table.insert(a, n) 123 x = filter(n, x) 124 end 125 126 assert(#a == 22 and a[#a] == 79) 127 x, a = nil 128 129 130 do -- "bug" in 5.4.2 131 local function foo () foo () end -- just create a stack overflow 132 local co = coroutine.create(foo) 133 -- running this coroutine would overflow the unsigned short 'nci', the 134 -- counter of CallInfo structures available to the thread. 135 -- (The issue only manifests in an 'assert'.) 136 local st, msg = coroutine.resume(co) 137 assert(string.find(msg, "stack overflow")) 138 assert(coroutine.status(co) == "dead") 139 end 140 141 142 print("to-be-closed variables in coroutines") 143 144 local function func2close (f) 145 return setmetatable({}, {__close = f}) 146 end 147 148 do 149 -- ok to close a dead coroutine 150 local co = coroutine.create(print) 151 assert(coroutine.resume(co, "testing 'coroutine.close'")) 152 assert(coroutine.status(co) == "dead") 153 local st, msg = coroutine.close(co) 154 assert(st and msg == nil) 155 -- also ok to close it again 156 st, msg = coroutine.close(co) 157 assert(st and msg == nil) 158 159 -- cannot close 'main' 160 local st, msg = pcall(coroutine.close, main); 161 assert(not st and string.find(msg, "main")) 162 163 164 -- cannot close a "normal" coroutine 165 ;(coroutine.wrap(function () 166 local st, msg = pcall(coroutine.close, main) 167 assert(not st and string.find(msg, "normal")) 168 end))() 169 170 do -- close a coroutine while closing it 171 local co 172 co = coroutine.create( 173 function() 174 local x = func2close(function() 175 coroutine.close(co) -- close it again 176 end) 177 coroutine.yield(20) 178 end) 179 local st, msg = coroutine.resume(co) 180 assert(st and msg == 20) 181 st, msg = coroutine.close(co) 182 assert(st and msg == nil) 183 end 184 185 186 do 187 -- again close a coroutine while closing it, but with the 188 -- coroutine in error mode. 189 190 -- after the error, the function created by 'wrap' will close the 191 -- coroutine. The close inside 'a' overrides the original close 192 -- and finishes the coroutine with no errors. 193 local co = coroutine.wrap(function() 194 local a = func2close(function() 195 coroutine.close() 196 end) 197 error("y") 198 end) 199 co() -- no errors 200 end 201 202 203 -- to-be-closed variables in coroutines 204 local X 205 206 -- closing a coroutine after an error 207 local co = coroutine.create(error) 208 local st, msg = coroutine.resume(co, 100) 209 assert(not st and msg == 100) 210 st, msg = coroutine.close(co) 211 assert(not st and msg == 100) 212 -- after closing, no more errors 213 st, msg = coroutine.close(co) 214 assert(st and msg == nil) 215 216 co = coroutine.create(function () 217 local x = func2close(function (self, err) 218 assert(err == nil); X = false 219 end) 220 X = true 221 coroutine.yield() 222 end) 223 coroutine.resume(co) 224 assert(X) 225 assert(coroutine.close(co)) 226 assert(not X and coroutine.status(co) == "dead") 227 228 -- error closing a coroutine 229 local x = 0 230 co = coroutine.create(function() 231 local y = func2close(function (self,err) 232 assert(err == 111) 233 x = 200 234 error(200) 235 end) 236 local x = func2close(function (self, err) 237 assert(err == nil); error(111) 238 end) 239 coroutine.yield() 240 end) 241 coroutine.resume(co) 242 assert(x == 0) 243 local st, msg = coroutine.close(co) 244 assert(st == false and coroutine.status(co) == "dead" and msg == 200) 245 assert(x == 200) 246 -- after closing, no more errors 247 st, msg = coroutine.close(co) 248 assert(st and msg == nil) 249 end 250 251 do 252 -- versus pcall in coroutines 253 local X = false 254 local Y = false 255 local function foo () 256 local x = func2close(function (self, err) 257 Y = debug.getinfo(2) 258 X = err 259 end) 260 error(43) 261 end 262 local co = coroutine.create(function () return pcall(foo) end) 263 local st1, st2, err = coroutine.resume(co) 264 assert(st1 and not st2 and err == 43) 265 assert(X == 43 and Y.what == "C") 266 267 -- recovering from errors in __close metamethods 268 local track = {} 269 270 local function h (o) 271 local hv = o 272 return 1 273 end 274 275 local function foo () 276 local x = func2close(function(_,msg) 277 track[#track + 1] = msg or false 278 error(20) 279 end) 280 local y = func2close(function(_,msg) 281 track[#track + 1] = msg or false 282 return 1000 283 end) 284 local z = func2close(function(_,msg) 285 track[#track + 1] = msg or false 286 error(10) 287 end) 288 coroutine.yield(1) 289 h(func2close(function(_,msg) 290 track[#track + 1] = msg or false 291 error(2) 292 end)) 293 end 294 295 local co = coroutine.create(pcall) 296 297 local st, res = coroutine.resume(co, foo) -- call 'foo' protected 298 assert(st and res == 1) -- yield 1 299 local st, res1, res2 = coroutine.resume(co) -- continue 300 assert(coroutine.status(co) == "dead") 301 assert(st and not res1 and res2 == 20) -- last error (20) 302 assert(track[1] == false and track[2] == 2 and track[3] == 10 and 303 track[4] == 10) 304 end 305 306 307 do print("coroutines closing itself") 308 global coroutine, string, os 309 global assert, error, pcall 310 311 local X = nil 312 313 local function new () 314 return coroutine.create(function (what) 315 316 local var = func2close(function (t, err) 317 if what == "yield" then 318 coroutine.yield() 319 elseif what == "error" then 320 error(200) 321 else 322 X = "Ok" 323 return X 324 end 325 end) 326 327 -- do an unprotected call so that coroutine becomes non-yieldable 328 string.gsub("a", "a", function () 329 assert(not coroutine.isyieldable()) 330 -- do protected calls while non-yieldable, to add recovery 331 -- entries (setjmp) to the stack 332 assert(pcall(pcall, function () 333 -- 'close' works even while non-yieldable 334 coroutine.close() -- close itself 335 os.exit(false) -- not reacheable 336 end)) 337 end) 338 end) 339 end 340 341 local co = new() 342 local st, msg = coroutine.resume(co, "ret") 343 assert(st and msg == nil) 344 assert(X == "Ok") 345 346 local co = new() 347 local st, msg = coroutine.resume(co, "error") 348 assert(not st and msg == 200) 349 350 local co = new() 351 local st, msg = coroutine.resume(co, "yield") 352 assert(not st and string.find(msg, "attempt to yield")) 353 354 end 355 356 357 -- yielding across C boundaries 358 359 local co = coroutine.wrap(function() 360 assert(not pcall(table.sort,{1,2,3}, coroutine.yield)) 361 assert(coroutine.isyieldable()) 362 coroutine.yield(20) 363 return 30 364 end) 365 366 assert(co() == 20) 367 assert(co() == 30) 368 369 370 local f = function (s, i) return coroutine.yield(i) end 371 372 local f1 = coroutine.wrap(function () 373 return xpcall(pcall, function (...) return ... end, 374 function () 375 local s = 0 376 for i in f, nil, 1 do pcall(function () s = s + i end) end 377 error({s}) 378 end) 379 end) 380 381 f1() 382 for i = 1, 10 do assert(f1(i) == i) end 383 local r1, r2, v = f1(nil) 384 assert(r1 and not r2 and v[1] == (10 + 1)*10/2) 385 386 387 local function f (a, b) a = coroutine.yield(a); error{a + b} end 388 local function g(x) return x[1]*2 end 389 390 co = coroutine.wrap(function () 391 coroutine.yield(xpcall(f, g, 10, 20)) 392 end) 393 394 assert(co() == 10) 395 local r, msg = co(100) 396 assert(not r and msg == 240) 397 398 399 -- unyieldable C call 400 do 401 local function f (c) 402 assert(not coroutine.isyieldable()) 403 return c .. c 404 end 405 406 local co = coroutine.wrap(function (c) 407 assert(coroutine.isyieldable()) 408 local s = string.gsub("a", ".", f) 409 return s 410 end) 411 assert(co() == "aa") 412 end 413 414 415 416 do -- testing single trace of coroutines 417 local X 418 local co = coroutine.create(function () 419 coroutine.yield(10) 420 return 20; 421 end) 422 local trace = {} 423 local function dotrace (event) 424 trace[#trace + 1] = event 425 end 426 debug.sethook(co, dotrace, "clr") 427 repeat until not coroutine.resume(co) 428 local correcttrace = {"call", "line", "call", "return", "line", "return"} 429 assert(#trace == #correcttrace) 430 for k, v in pairs(trace) do 431 assert(v == correcttrace[k]) 432 end 433 end 434 435 -- errors in coroutines 436 function foo () 437 assert(debug.getinfo(1).currentline == debug.getinfo(foo).linedefined + 1) 438 assert(debug.getinfo(2).currentline == debug.getinfo(goo).linedefined) 439 coroutine.yield(3) 440 error(foo) 441 end 442 443 function goo() foo() end 444 x = coroutine.wrap(goo) 445 assert(x() == 3) 446 local a,b = pcall(x) 447 assert(not a and b == foo) 448 449 x = coroutine.create(goo) 450 a,b = coroutine.resume(x) 451 assert(a and b == 3) 452 a,b = coroutine.resume(x) 453 assert(not a and b == foo and coroutine.status(x) == "dead") 454 a,b = coroutine.resume(x) 455 assert(not a and string.find(b, "dead") and coroutine.status(x) == "dead") 456 457 goo = nil 458 459 -- co-routines x for loop 460 local function all (a, n, k) 461 if k == 0 then coroutine.yield(a) 462 else 463 for i=1,n do 464 a[k] = i 465 all(a, n, k-1) 466 end 467 end 468 end 469 470 local a = 0 471 for t in coroutine.wrap(function () all({}, 5, 4) end) do 472 a = a+1 473 end 474 assert(a == 5^4) 475 476 477 -- access to locals of collected corroutines 478 local C = {}; setmetatable(C, {__mode = "kv"}) 479 local x = coroutine.wrap (function () 480 local a = 10 481 local function f () a = a+10; return a end 482 while true do 483 a = a+1 484 coroutine.yield(f) 485 end 486 end) 487 488 C[1] = x; 489 490 local f = x() 491 assert(f() == 21 and x()() == 32 and x() == f) 492 x = nil 493 collectgarbage() 494 assert(C[1] == undef) 495 assert(f() == 43 and f() == 53) 496 497 498 -- old bug: attempt to resume itself 499 500 local function co_func (current_co) 501 assert(coroutine.running() == current_co) 502 assert(coroutine.resume(current_co) == false) 503 coroutine.yield(10, 20) 504 assert(coroutine.resume(current_co) == false) 505 coroutine.yield(23) 506 return 10 507 end 508 509 local co = coroutine.create(co_func) 510 local a,b,c = coroutine.resume(co, co) 511 assert(a == true and b == 10 and c == 20) 512 a,b = coroutine.resume(co, co) 513 assert(a == true and b == 23) 514 a,b = coroutine.resume(co, co) 515 assert(a == true and b == 10) 516 assert(coroutine.resume(co, co) == false) 517 assert(coroutine.resume(co, co) == false) 518 519 520 -- other old bug when attempting to resume itself 521 -- (trigger C-code assertions) 522 do 523 local A = coroutine.running() 524 local B = coroutine.create(function() return coroutine.resume(A) end) 525 local st, res = coroutine.resume(B) 526 assert(st == true and res == false) 527 528 local X = false 529 A = coroutine.wrap(function() 530 local _ = func2close(function () X = true end) 531 return pcall(A, 1) 532 end) 533 st, res = A() 534 assert(not st and string.find(res, "non%-suspended") and X == true) 535 end 536 537 538 -- bug in 5.4.1 539 do 540 -- coroutine ran close metamethods with invalid status during a 541 -- reset. 542 local co 543 co = coroutine.wrap(function() 544 local x = func2close(function() return pcall(co) end) 545 error(111) 546 end) 547 local st, errobj = pcall(co) 548 assert(not st and errobj == 111) 549 st, errobj = pcall(co) 550 assert(not st and string.find(errobj, "dead coroutine")) 551 end 552 553 554 -- attempt to resume 'normal' coroutine 555 local co1, co2 556 co1 = coroutine.create(function () return co2() end) 557 co2 = coroutine.wrap(function () 558 assert(coroutine.status(co1) == 'normal') 559 assert(not coroutine.resume(co1)) 560 coroutine.yield(3) 561 end) 562 563 a,b = coroutine.resume(co1) 564 assert(a and b == 3) 565 assert(coroutine.status(co1) == 'dead') 566 567 -- infinite recursion of coroutines 568 a = function(a) coroutine.wrap(a)(a) end 569 assert(not pcall(a, a)) 570 a = nil 571 572 573 do 574 -- bug in 5.4: thread can use message handler higher in the stack 575 -- than the variable being closed 576 local c = coroutine.create(function() 577 local clo = setmetatable({}, {__close=function() 578 local x = 134 -- will overwrite message handler 579 error(x) 580 end}) 581 -- yields coroutine but leaves a new message handler for it, 582 -- that would be used when closing the coroutine (except that it 583 -- will be overwritten) 584 xpcall(coroutine.yield, function() return "XXX" end) 585 end) 586 587 assert(coroutine.resume(c)) -- start coroutine 588 local st, msg = coroutine.close(c) 589 assert(not st and msg == 134) 590 end 591 592 -- access to locals of erroneous coroutines 593 local x = coroutine.create (function () 594 local a = 10 595 _G.F = function () a=a+1; return a end 596 error('x') 597 end) 598 599 assert(not coroutine.resume(x)) 600 -- overwrite previous position of local `a' 601 assert(not coroutine.resume(x, 1, 1, 1, 1, 1, 1, 1)) 602 assert(_G.F() == 11) 603 assert(_G.F() == 12) 604 _G.F = nil 605 606 607 if not T then 608 (Message or print) 609 ('\n >>> testC not active: skipping coroutine API tests <<<\n') 610 else 611 print "testing yields inside hooks" 612 613 local turn 614 615 local function fact (t, x) 616 assert(turn == t) 617 if x == 0 then return 1 618 else return x*fact(t, x-1) 619 end 620 end 621 622 local A, B = 0, 0 623 624 local x = coroutine.create(function () 625 T.sethook("yield 0", "", 2) 626 A = fact("A", 6) 627 end) 628 629 local y = coroutine.create(function () 630 T.sethook("yield 0", "", 3) 631 B = fact("B", 7) 632 end) 633 634 while A==0 or B==0 do -- A ~= 0 when 'x' finishes (similar for 'B','y') 635 if A==0 then turn = "A"; assert(T.resume(x)) end 636 if B==0 then turn = "B"; assert(T.resume(y)) end 637 638 -- check that traceback works correctly after yields inside hooks 639 debug.traceback(x) 640 debug.traceback(y) 641 end 642 643 assert(B // A == 7) -- fact(7) // fact(6) 644 645 do -- hooks vs. multiple values 646 local done 647 local function test (n) 648 done = false 649 return coroutine.wrap(function () 650 local a = {} 651 for i = 1, n do a[i] = i end 652 -- 'pushint' just to perturb the stack 653 T.sethook("pushint 10; yield 0", "", 1) -- yield at each op. 654 local a1 = {table.unpack(a)} -- must keep top between ops. 655 assert(#a1 == n) 656 for i = 1, n do assert(a[i] == i) end 657 done = true 658 end) 659 end 660 -- arguments to the coroutine are just to perturb its stack 661 local co = test(0); while not done do co(30) end 662 co = test(1); while not done do co(20, 10) end 663 co = test(3); while not done do co() end 664 co = test(100); while not done do co() end 665 end 666 667 local line = debug.getinfo(1, "l").currentline + 2 -- get line number 668 local function foo () 669 local x = 10 --<< this line is 'line' 670 x = x + 10 671 _G.XX = x 672 end 673 674 -- testing yields in line hook 675 local co = coroutine.wrap(function () 676 T.sethook("setglobal X; yield 0", "l", 0); foo(); return 10 end) 677 678 _G.XX = nil; 679 _G.X = nil; co(); assert(_G.X == line) 680 _G.X = nil; co(); assert(_G.X == line + 1) 681 _G.X = nil; co(); assert(_G.X == line + 2 and _G.XX == nil) 682 _G.X = nil; co(); assert(_G.X == line + 3 and _G.XX == 20) 683 assert(co() == 10) 684 _G.X = nil 685 686 -- testing yields in count hook 687 co = coroutine.wrap(function () 688 T.sethook("yield 0", "", 1); foo(); return 10 end) 689 690 _G.XX = nil; 691 local c = 0 692 repeat c = c + 1; local a = co() until a == 10 693 assert(_G.XX == 20 and c >= 5) 694 695 co = coroutine.wrap(function () 696 T.sethook("yield 0", "", 2); foo(); return 10 end) 697 698 _G.XX = nil; 699 local c = 0 700 repeat c = c + 1; local a = co() until a == 10 701 assert(_G.XX == 20 and c >= 5) 702 _G.X = nil; _G.XX = nil 703 704 do 705 -- testing debug library on a coroutine suspended inside a hook 706 -- (bug in 5.2/5.3) 707 c = coroutine.create(function (a, ...) 708 T.sethook("yield 0", "l") -- will yield on next two lines 709 local b = a 710 return ... 711 end) 712 713 assert(coroutine.resume(c, 1, 2, 3)) -- start coroutine 714 local n,v = debug.getlocal(c, 0, 1) -- check its local 715 assert(n == "a" and v == 1 and debug.getlocal(c, 0, 2) ~= "b") 716 assert(debug.setlocal(c, 0, 1, 10)) -- test 'setlocal' 717 local t = debug.getinfo(c, 0) -- test 'getinfo' 718 assert(t.currentline == t.linedefined + 2) 719 assert(not debug.getinfo(c, 1)) -- no other level 720 assert(coroutine.resume(c)) -- run next line 721 local n,v = debug.getlocal(c, 0, 2) -- check vararg table 722 assert(n == "(vararg table)" and v == nil) 723 local n,v = debug.getlocal(c, 0, 3) -- check next local 724 assert(n == "b" and v == 10) 725 v = {coroutine.resume(c)} -- finish coroutine 726 assert(v[1] == true and v[2] == 2 and v[3] == 3 and v[4] == undef) 727 assert(not coroutine.resume(c)) 728 end 729 730 do 731 -- testing debug library on last function in a suspended coroutine 732 -- (bug in 5.2/5.3) 733 local c = coroutine.create(function () T.testC("yield 1", 10, 20) end) 734 local a, b = coroutine.resume(c) 735 assert(a and b == 20) 736 assert(debug.getinfo(c, 0).linedefined == -1) 737 a, b = debug.getlocal(c, 0, 2) 738 assert(b == 10) 739 end 740 741 742 print "testing coroutine API" 743 744 -- reusing a thread 745 assert(T.testC([[ 746 newthread # create thread 747 pushvalue 2 # push body 748 pushstring 'a a a' # push argument 749 xmove 0 3 2 # move values to new thread 750 resume -1, 1 # call it first time 751 pushstatus 752 xmove 3 0 0 # move results back to stack 753 setglobal X # result 754 setglobal Y # status 755 pushvalue 2 # push body (to call it again) 756 pushstring 'b b b' 757 xmove 0 3 2 758 resume -1, 1 # call it again 759 pushstatus 760 xmove 3 0 0 761 return 1 # return result 762 ]], function (...) return ... end) == 'b b b') 763 764 assert(X == 'a a a' and Y == 'OK') 765 766 X, Y = nil 767 768 769 -- resuming running coroutine 770 C = coroutine.create(function () 771 return T.testC([[ 772 pushnum 10; 773 pushnum 20; 774 resume -3 2; 775 pushstatus 776 gettop; 777 return 3]], C) 778 end) 779 local a, b, c, d = coroutine.resume(C) 780 assert(a == true and string.find(b, "non%-suspended") and 781 c == "ERRRUN" and d == 4) 782 783 a, b, c, d = T.testC([[ 784 rawgeti R !M # get main thread 785 pushnum 10; 786 pushnum 20; 787 resume -3 2; 788 pushstatus 789 gettop; 790 return 4]]) 791 assert(a == coroutine.running() and string.find(b, "non%-suspended") and 792 c == "ERRRUN" and d == 4) 793 794 795 -- using a main thread as a coroutine (dubious use!) 796 local state = T.newstate() 797 798 -- check that yielddable is working correctly 799 assert(T.testC(state, "newthread; isyieldable -1; remove 1; return 1")) 800 801 -- main thread is not yieldable 802 assert(not T.testC(state, "rawgeti R !M; isyieldable -1; remove 1; return 1")) 803 804 T.testC(state, "settop 0") 805 806 T.loadlib(state, 1 | 2, 4) -- load _G and 'package', preload 'coroutine' 807 808 assert(T.doremote(state, [[ 809 coroutine = require'coroutine'; 810 X = function (x) coroutine.yield(x, 'BB'); return 'CC' end; 811 return 'ok']])) 812 813 local t = table.pack(T.testC(state, [[ 814 rawgeti R !M # get main thread 815 pushstring 'XX' 816 getglobal X # get function for body 817 pushstring AA # arg 818 resume 1 1 # 'resume' shadows previous stack! 819 gettop 820 setglobal T # top 821 setglobal B # second yielded value 822 setglobal A # fist yielded value 823 rawgeti R !M # get main thread 824 pushnum 5 # arg (noise) 825 resume 1 1 # after coroutine ends, previous stack is back 826 pushstatus 827 return * 828 ]])) 829 assert(t.n == 4 and t[2] == 'XX' and t[3] == 'CC' and t[4] == 'OK') 830 assert(T.doremote(state, "return T") == '2') 831 assert(T.doremote(state, "return A") == 'AA') 832 assert(T.doremote(state, "return B") == 'BB') 833 834 T.closestate(state) 835 836 print'+' 837 838 end 839 840 841 -- leaving a pending coroutine open 842 _G.TO_SURVIVE = coroutine.wrap(function () 843 local a = 10 844 local x = function () a = a+1 end 845 coroutine.yield() 846 end) 847 848 _G.TO_SURVIVE() 849 850 851 if not _soft then 852 -- bug (stack overflow) 853 local lim = `1000000` -- stack limit; assume 32-bit machine 854 local t = {lim - 10, lim - 5, lim - 1, lim, lim + 1, lim + 5} 855 for i = 1, #t do 856 local j = t[i] 857 local co = coroutine.create(function() 858 return table.unpack({}, 1, j) 859 end) 860 local r, msg = coroutine.resume(co) 861 -- must fail for unpacking larger than stack limit 862 assert(j < lim or not r) 863 end 864 end 865 866 867 assert(coroutine.running() == main) 868 869 print"+" 870 871 872 print"testing yields inside metamethods" 873 874 local function val(x) 875 if type(x) == "table" then return x.x else return x end 876 end 877 878 local mt = { 879 __eq = function(a,b) coroutine.yield(nil, "eq"); return val(a) == val(b) end, 880 __lt = function(a,b) coroutine.yield(nil, "lt"); return val(a) < val(b) end, 881 __le = function(a,b) coroutine.yield(nil, "le"); return a - b <= 0 end, 882 __add = function(a,b) coroutine.yield(nil, "add"); 883 return val(a) + val(b) end, 884 __sub = function(a,b) coroutine.yield(nil, "sub"); return val(a) - val(b) end, 885 __mul = function(a,b) coroutine.yield(nil, "mul"); return val(a) * val(b) end, 886 __div = function(a,b) coroutine.yield(nil, "div"); return val(a) / val(b) end, 887 __idiv = function(a,b) coroutine.yield(nil, "idiv"); 888 return val(a) // val(b) end, 889 __pow = function(a,b) coroutine.yield(nil, "pow"); return val(a) ^ val(b) end, 890 __mod = function(a,b) coroutine.yield(nil, "mod"); return val(a) % val(b) end, 891 __unm = function(a,b) coroutine.yield(nil, "unm"); return -val(a) end, 892 __bnot = function(a,b) coroutine.yield(nil, "bnot"); return ~val(a) end, 893 __shl = function(a,b) coroutine.yield(nil, "shl"); 894 return val(a) << val(b) end, 895 __shr = function(a,b) coroutine.yield(nil, "shr"); 896 return val(a) >> val(b) end, 897 __band = function(a,b) 898 coroutine.yield(nil, "band") 899 return val(a) & val(b) 900 end, 901 __bor = function(a,b) coroutine.yield(nil, "bor"); 902 return val(a) | val(b) end, 903 __bxor = function(a,b) coroutine.yield(nil, "bxor"); 904 return val(a) ~ val(b) end, 905 906 __concat = function(a,b) 907 coroutine.yield(nil, "concat"); 908 return val(a) .. val(b) 909 end, 910 __index = function (t,k) coroutine.yield(nil, "idx"); return t.k[k] end, 911 __newindex = function (t,k,v) coroutine.yield(nil, "nidx"); t.k[k] = v end, 912 } 913 914 915 local function new (x) 916 return setmetatable({x = x, k = {}}, mt) 917 end 918 919 920 local a = new(10) 921 local b = new(12) 922 local c = new"hello" 923 924 local function run (f, t) 925 local i = 1 926 local c = coroutine.wrap(f) 927 while true do 928 local res, stat = c() 929 if res then assert(t[i] == undef); return res, t end 930 assert(stat == t[i]) 931 i = i + 1 932 end 933 end 934 935 936 assert(run(function () if (a>=b) then return '>=' else return '<' end end, 937 {"le", "sub"}) == "<") 938 assert(run(function () if (a<=b) then return '<=' else return '>' end end, 939 {"le", "sub"}) == "<=") 940 assert(run(function () if (a==b) then return '==' else return '~=' end end, 941 {"eq"}) == "~=") 942 943 assert(run(function () return a & b + a end, {"add", "band"}) == 2) 944 945 assert(run(function () return 1 + a end, {"add"}) == 11) 946 assert(run(function () return a - 25 end, {"sub"}) == -15) 947 assert(run(function () return 2 * a end, {"mul"}) == 20) 948 assert(run(function () return a ^ 2 end, {"pow"}) == 100) 949 assert(run(function () return a / 2 end, {"div"}) == 5) 950 assert(run(function () return a % 6 end, {"mod"}) == 4) 951 assert(run(function () return a // 3 end, {"idiv"}) == 3) 952 953 assert(run(function () return a + b end, {"add"}) == 22) 954 assert(run(function () return a - b end, {"sub"}) == -2) 955 assert(run(function () return a * b end, {"mul"}) == 120) 956 assert(run(function () return a ^ b end, {"pow"}) == 10^12) 957 assert(run(function () return a / b end, {"div"}) == 10/12) 958 assert(run(function () return a % b end, {"mod"}) == 10) 959 assert(run(function () return a // b end, {"idiv"}) == 0) 960 961 -- repeat tests with larger constants (to use 'K' opcodes) 962 local a1000 = new(1000) 963 964 assert(run(function () return a1000 + 1000 end, {"add"}) == 2000) 965 assert(run(function () return a1000 - 25000 end, {"sub"}) == -24000) 966 assert(run(function () return 2000 * a end, {"mul"}) == 20000) 967 assert(run(function () return a1000 / 1000 end, {"div"}) == 1) 968 assert(run(function () return a1000 % 600 end, {"mod"}) == 400) 969 assert(run(function () return a1000 // 500 end, {"idiv"}) == 2) 970 971 972 973 assert(run(function () return a % b end, {"mod"}) == 10) 974 975 assert(run(function () return ~a & b end, {"bnot", "band"}) == ~10 & 12) 976 assert(run(function () return a | b end, {"bor"}) == 10 | 12) 977 assert(run(function () return a ~ b end, {"bxor"}) == 10 ~ 12) 978 assert(run(function () return a << b end, {"shl"}) == 10 << 12) 979 assert(run(function () return a >> b end, {"shr"}) == 10 >> 12) 980 981 assert(run(function () return 10 & b end, {"band"}) == 10 & 12) 982 assert(run(function () return a | 2 end, {"bor"}) == 10 | 2) 983 assert(run(function () return a ~ 2 end, {"bxor"}) == 10 ~ 2) 984 assert(run(function () return a >> 2 end, {"shr"}) == 10 >> 2) 985 assert(run(function () return 1 >> a end, {"shr"}) == 1 >> 10) 986 assert(run(function () return a << 2 end, {"shl"}) == 10 << 2) 987 assert(run(function () return 1 << a end, {"shl"}) == 1 << 10) 988 assert(run(function () return 2 ~ a end, {"bxor"}) == 2 ~ 10) 989 990 991 assert(run(function () return a..b end, {"concat"}) == "1012") 992 993 assert(run(function() return a .. b .. c .. a end, 994 {"concat", "concat", "concat"}) == "1012hello10") 995 996 assert(run(function() return "a" .. "b" .. a .. "c" .. c .. b .. "x" end, 997 {"concat", "concat", "concat"}) == "ab10chello12x") 998 999 1000 do -- a few more tests for comparison operators 1001 local mt1 = { 1002 __le = function (a,b) 1003 coroutine.yield(10) 1004 return (val(a) <= val(b)) 1005 end, 1006 __lt = function (a,b) 1007 coroutine.yield(10) 1008 return val(a) < val(b) 1009 end, 1010 } 1011 local mt2 = { __lt = mt1.__lt, __le = mt1.__le } 1012 1013 local function run (f) 1014 local co = coroutine.wrap(f) 1015 local res 1016 repeat 1017 res = co() 1018 until res ~= 10 1019 return res 1020 end 1021 1022 local function test () 1023 local a1 = setmetatable({x=1}, mt1) 1024 local a2 = setmetatable({x=2}, mt2) 1025 assert(a1 < a2) 1026 assert(a1 <= a2) 1027 assert(1 < a2) 1028 assert(1 <= a2) 1029 assert(2 > a1) 1030 assert(2 >= a2) 1031 return true 1032 end 1033 1034 run(test) 1035 1036 end 1037 1038 assert(run(function () 1039 a.BB = print 1040 return a.BB 1041 end, {"nidx", "idx"}) == print) 1042 1043 -- getuptable & setuptable 1044 do local _ENV = _ENV 1045 f = function () AAA = BBB + 1; return AAA end 1046 end 1047 local g = new(10); g.k.BBB = 10; 1048 debug.setupvalue(f, 1, g) 1049 assert(run(f, {"idx", "nidx", "idx"}) == 11) 1050 assert(g.k.AAA == 11) 1051 1052 print"+" 1053 1054 print"testing yields inside 'for' iterators" 1055 1056 local f = function (s, i) 1057 if i%2 == 0 then coroutine.yield(nil, "for") end 1058 if i < s then return i + 1 end 1059 end 1060 1061 assert(run(function () 1062 local s = 0 1063 for i in f, 4, 0 do s = s + i end 1064 return s 1065 end, {"for", "for", "for"}) == 10) 1066 1067 1068 1069 -- tests for coroutine API 1070 if T==nil then 1071 (Message or print)('\n >>> testC not active: skipping coroutine API tests <<<\n') 1072 print "OK"; return 1073 end 1074 1075 print('testing coroutine API') 1076 1077 local function apico (...) 1078 local x = {...} 1079 return coroutine.wrap(function () 1080 return T.testC(table.unpack(x)) 1081 end) 1082 end 1083 1084 local a = {apico( 1085 [[ 1086 pushstring errorcode 1087 pcallk 1 0 2; 1088 invalid command (should not arrive here) 1089 ]], 1090 [[return *]], 1091 "stackmark", 1092 error 1093 )()} 1094 assert(#a == 4 and 1095 a[3] == "stackmark" and 1096 a[4] == "errorcode" and 1097 _G.status == "ERRRUN" and 1098 _G.ctx == 2) -- 'ctx' to pcallk 1099 1100 local co = apico( 1101 "pushvalue 2; pushnum 10; pcallk 1 2 3; invalid command;", 1102 coroutine.yield, 1103 "getglobal status; getglobal ctx; pushvalue 2; pushstring a; pcallk 1 0 4; invalid command", 1104 "getglobal status; getglobal ctx; return *") 1105 1106 assert(co() == 10) 1107 assert(co(20, 30) == 'a') 1108 a = {co()} 1109 assert(#a == 10 and 1110 a[2] == coroutine.yield and 1111 a[5] == 20 and a[6] == 30 and 1112 a[7] == "YIELD" and a[8] == 3 and 1113 a[9] == "YIELD" and a[10] == 4) 1114 assert(not pcall(co)) -- coroutine is dead now 1115 1116 1117 f = T.makeCfunc("pushnum 3; pushnum 5; yield 1;") 1118 co = coroutine.wrap(function () 1119 assert(f() == 23); assert(f() == 23); return 10 1120 end) 1121 assert(co(23,16) == 5) 1122 assert(co(23,16) == 5) 1123 assert(co(23,16) == 10) 1124 1125 1126 -- testing coroutines with C bodies 1127 f = T.makeCfunc([[ 1128 pushnum 102 1129 yieldk 1 U2 1130 cannot be here! 1131 ]], 1132 [[ # continuation 1133 pushvalue U3 # accessing upvalues inside a continuation 1134 pushvalue U4 1135 return * 1136 ]], 23, "huu") 1137 1138 1139 do -- testing bug introduced in commit `f407b3c4a` 1140 local X = false -- flag "to be closed" 1141 local coro = coroutine.wrap(T.testC) 1142 -- runs it until 'pcallk' (that yields) 1143 -- 4th argument (at index 4): object to be closed 1144 local res1, res2 = coro( 1145 [[ 1146 toclose 3 # this could break the next 'pcallk' 1147 pushvalue 2 # push function 'yield' to call it 1148 pushint 22; pushint 33 # arguments to yield 1149 # calls 'yield' (2 args; 2 results; continuation function at index 4) 1150 pcallk 2 2 4 1151 invalid command (should not arrive here) 1152 ]], -- 1st argument (at index 1): code; 1153 coroutine.yield, -- (at index 2): function to be called 1154 func2close(function () X = true end), -- (index 3): TBC slot 1155 "pushint 43; return 3" -- (index 4): code for continuation function 1156 ) 1157 1158 assert(res1 == 22 and res2 == 33 and not X) 1159 local res1, res2, res3 = coro(34, "hi") -- runs continuation function 1160 assert(res1 == 34 and res2 == "hi" and res3 == 43 and X) 1161 end 1162 1163 x = coroutine.wrap(f) 1164 assert(x() == 102) 1165 eqtab({x()}, {23, "huu"}) 1166 1167 1168 f = T.makeCfunc[[pushstring 'a'; pushnum 102; yield 2; ]] 1169 1170 a, b, c, d = T.testC([[newthread; pushvalue 2; xmove 0 3 1; resume 3 0; 1171 pushstatus; xmove 3 0 0; resume 3 0; pushstatus; 1172 return 4; ]], f) 1173 1174 assert(a == 'YIELD' and b == 'a' and c == 102 and d == 'OK') 1175 1176 1177 -- testing chain of suspendable C calls 1178 1179 local count = 3 -- number of levels 1180 1181 f = T.makeCfunc([[ 1182 remove 1; # remove argument 1183 pushvalue U3; # get selection function 1184 call 0 1; # call it (result is 'f' or 'yield') 1185 pushstring hello # single argument for selected function 1186 pushupvalueindex 2; # index of continuation program 1187 callk 1 -1 .; # call selected function 1188 errorerror # should never arrive here 1189 ]], 1190 [[ 1191 # continuation program 1192 pushnum 34 # return value 1193 return * # return all results 1194 ]], 1195 function () -- selection function 1196 count = count - 1 1197 if count == 0 then return coroutine.yield 1198 else return f 1199 end 1200 end 1201 ) 1202 1203 co = coroutine.wrap(function () return f(nil) end) 1204 assert(co() == "hello") -- argument to 'yield' 1205 a = {co()} 1206 -- three '34's (one from each pending C call) 1207 assert(#a == 3 and a[1] == a[2] and a[2] == a[3] and a[3] == 34) 1208 1209 1210 -- testing yields with continuations 1211 1212 local y 1213 1214 co = coroutine.wrap(function (...) return 1215 T.testC([[ # initial function 1216 yieldk 1 2 1217 cannot be here! 1218 ]], 1219 [[ # 1st continuation 1220 yieldk 0 3 1221 cannot be here! 1222 ]], 1223 [[ # 2nd continuation 1224 yieldk 0 4 1225 cannot be here! 1226 ]], 1227 [[ # 3th continuation 1228 pushvalue 6 # function which is last arg. to 'testC' here 1229 pushnum 10; pushnum 20; 1230 pcall 2 0 0 # call should throw an error and return to next line 1231 pop 1 # remove error message 1232 pushvalue 6 1233 getglobal status; getglobal ctx 1234 pcallk 2 2 5 # call should throw an error and jump to continuation 1235 cannot be here! 1236 ]], 1237 [[ # 4th (and last) continuation 1238 return * 1239 ]], 1240 -- function called by 3th continuation 1241 function (a,b) x=a; y=b; error("errmsg") end, 1242 ... 1243 ) 1244 end) 1245 1246 local a = {co(3,4,6)} 1247 assert(a[1] == 6 and a[2] == undef) 1248 a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 2) 1249 a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 3) 1250 a = {co(7,8)}; 1251 -- original arguments 1252 assert(type(a[1]) == 'string' and type(a[2]) == 'string' and 1253 type(a[3]) == 'string' and type(a[4]) == 'string' and 1254 type(a[5]) == 'string' and type(a[6]) == 'function') 1255 -- arguments left from fist resume 1256 assert(a[7] == 3 and a[8] == 4) 1257 -- arguments to last resume 1258 assert(a[9] == 7 and a[10] == 8) 1259 -- error message and nothing more 1260 assert(a[11]:find("errmsg") and #a == 11) 1261 -- check arguments to pcallk 1262 assert(x == "YIELD" and y == 4) 1263 1264 assert(not pcall(co)) -- coroutine should be dead 1265 1266 _G.ctx = nil 1267 _G.status = nil 1268 1269 1270 -- bug in nCcalls 1271 local co = coroutine.wrap(function () 1272 local a = {pcall(pcall,pcall,pcall,pcall,pcall,pcall,pcall,error,"hi")} 1273 return pcall(assert, table.unpack(a)) 1274 end) 1275 1276 local a = {co()} 1277 assert(a[10] == "hi") 1278 1279 print'OK'