coroutine.lua 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. -- $Id: testes/coroutine.lua $
  2. -- See Copyright Notice in file all.lua
  3. print "testing coroutines"
  4. local debug = require'debug'
  5. local f
  6. local main, ismain = coroutine.running()
  7. assert(type(main) == "thread" and ismain)
  8. assert(not coroutine.resume(main))
  9. assert(not coroutine.isyieldable(main) and not coroutine.isyieldable())
  10. assert(not pcall(coroutine.yield))
  11. -- trivial errors
  12. assert(not pcall(coroutine.resume, 0))
  13. assert(not pcall(coroutine.status, 0))
  14. -- tests for multiple yield/resume arguments
  15. local function eqtab (t1, t2)
  16. assert(#t1 == #t2)
  17. for i = 1, #t1 do
  18. local v = t1[i]
  19. assert(t2[i] == v)
  20. end
  21. end
  22. _G.x = nil -- declare x
  23. _G.f = nil -- declare f
  24. local function foo (a, ...)
  25. local x, y = coroutine.running()
  26. assert(x == f and y == false)
  27. -- next call should not corrupt coroutine (but must fail,
  28. -- as it attempts to resume the running coroutine)
  29. assert(coroutine.resume(f) == false)
  30. assert(coroutine.status(f) == "running")
  31. local arg = {...}
  32. assert(coroutine.isyieldable(x))
  33. for i=1,#arg do
  34. _G.x = {coroutine.yield(table.unpack(arg[i]))}
  35. end
  36. return table.unpack(a)
  37. end
  38. f = coroutine.create(foo)
  39. assert(coroutine.isyieldable(f))
  40. assert(type(f) == "thread" and coroutine.status(f) == "suspended")
  41. assert(string.find(tostring(f), "thread"))
  42. local s,a,b,c,d
  43. s,a,b,c,d = coroutine.resume(f, {1,2,3}, {}, {1}, {'a', 'b', 'c'})
  44. assert(coroutine.isyieldable(f))
  45. assert(s and a == nil and coroutine.status(f) == "suspended")
  46. s,a,b,c,d = coroutine.resume(f)
  47. eqtab(_G.x, {})
  48. assert(s and a == 1 and b == nil)
  49. assert(coroutine.isyieldable(f))
  50. s,a,b,c,d = coroutine.resume(f, 1, 2, 3)
  51. eqtab(_G.x, {1, 2, 3})
  52. assert(s and a == 'a' and b == 'b' and c == 'c' and d == nil)
  53. s,a,b,c,d = coroutine.resume(f, "xuxu")
  54. eqtab(_G.x, {"xuxu"})
  55. assert(s and a == 1 and b == 2 and c == 3 and d == nil)
  56. assert(coroutine.status(f) == "dead")
  57. s, a = coroutine.resume(f, "xuxu")
  58. assert(not s and string.find(a, "dead") and coroutine.status(f) == "dead")
  59. _G.f = nil
  60. -- yields in tail calls
  61. local function foo (i) return coroutine.yield(i) end
  62. local f = coroutine.wrap(function ()
  63. for i=1,10 do
  64. assert(foo(i) == _G.x)
  65. end
  66. return 'a'
  67. end)
  68. for i=1,10 do _G.x = i; assert(f(i) == i) end
  69. _G.x = 'xuxu'; assert(f('xuxu') == 'a')
  70. _G.x = nil
  71. -- recursive
  72. local function pf (n, i)
  73. coroutine.yield(n)
  74. pf(n*i, i+1)
  75. end
  76. f = coroutine.wrap(pf)
  77. local s=1
  78. for i=1,10 do
  79. assert(f(1, 1) == s)
  80. s = s*i
  81. end
  82. -- sieve
  83. local function gen (n)
  84. return coroutine.wrap(function ()
  85. for i=2,n do coroutine.yield(i) end
  86. end)
  87. end
  88. local function filter (p, g)
  89. return coroutine.wrap(function ()
  90. while 1 do
  91. local n = g()
  92. if n == nil then return end
  93. if math.fmod(n, p) ~= 0 then coroutine.yield(n) end
  94. end
  95. end)
  96. end
  97. local x = gen(80)
  98. local a = {}
  99. while 1 do
  100. local n = x()
  101. if n == nil then break end
  102. table.insert(a, n)
  103. x = filter(n, x)
  104. end
  105. assert(#a == 22 and a[#a] == 79)
  106. x, a = nil
  107. print("to-be-closed variables in coroutines")
  108. local function func2close (f)
  109. return setmetatable({}, {__close = f})
  110. end
  111. do
  112. -- ok to close a dead coroutine
  113. local co = coroutine.create(print)
  114. assert(coroutine.resume(co, "testing 'coroutine.close'"))
  115. assert(coroutine.status(co) == "dead")
  116. local st, msg = coroutine.close(co)
  117. assert(st and msg == nil)
  118. -- also ok to close it again
  119. st, msg = coroutine.close(co)
  120. assert(st and msg == nil)
  121. -- cannot close the running coroutine
  122. local st, msg = pcall(coroutine.close, coroutine.running())
  123. assert(not st and string.find(msg, "running"))
  124. local main = coroutine.running()
  125. -- cannot close a "normal" coroutine
  126. ;(coroutine.wrap(function ()
  127. local st, msg = pcall(coroutine.close, main)
  128. assert(not st and string.find(msg, "normal"))
  129. end))()
  130. -- cannot close a coroutine while closing it
  131. do
  132. local co
  133. co = coroutine.create(
  134. function()
  135. local x <close> = func2close(function()
  136. coroutine.close(co) -- try to close it again
  137. end)
  138. coroutine.yield(20)
  139. end)
  140. local st, msg = coroutine.resume(co)
  141. assert(st and msg == 20)
  142. st, msg = coroutine.close(co)
  143. assert(not st and string.find(msg, "running coroutine"))
  144. end
  145. -- to-be-closed variables in coroutines
  146. local X
  147. -- closing a coroutine after an error
  148. local co = coroutine.create(error)
  149. local st, msg = coroutine.resume(co, 100)
  150. assert(not st and msg == 100)
  151. st, msg = coroutine.close(co)
  152. assert(not st and msg == 100)
  153. -- after closing, no more errors
  154. st, msg = coroutine.close(co)
  155. assert(st and msg == nil)
  156. co = coroutine.create(function ()
  157. local x <close> = func2close(function (self, err)
  158. assert(err == nil); X = false
  159. end)
  160. X = true
  161. coroutine.yield()
  162. end)
  163. coroutine.resume(co)
  164. assert(X)
  165. assert(coroutine.close(co))
  166. assert(not X and coroutine.status(co) == "dead")
  167. -- error closing a coroutine
  168. local x = 0
  169. co = coroutine.create(function()
  170. local y <close> = func2close(function (self,err)
  171. assert(err == 111)
  172. x = 200
  173. error(200)
  174. end)
  175. local x <close> = func2close(function (self, err)
  176. assert(err == nil); error(111)
  177. end)
  178. coroutine.yield()
  179. end)
  180. coroutine.resume(co)
  181. assert(x == 0)
  182. local st, msg = coroutine.close(co)
  183. assert(st == false and coroutine.status(co) == "dead" and msg == 200)
  184. assert(x == 200)
  185. -- after closing, no more errors
  186. st, msg = coroutine.close(co)
  187. assert(st and msg == nil)
  188. end
  189. do
  190. -- <close> versus pcall in coroutines
  191. local X = false
  192. local Y = false
  193. local function foo ()
  194. local x <close> = func2close(function (self, err)
  195. Y = debug.getinfo(2)
  196. X = err
  197. end)
  198. error(43)
  199. end
  200. local co = coroutine.create(function () return pcall(foo) end)
  201. local st1, st2, err = coroutine.resume(co)
  202. assert(st1 and not st2 and err == 43)
  203. assert(X == 43 and Y.what == "C")
  204. -- recovering from errors in __close metamethods
  205. local track = {}
  206. local function h (o)
  207. local hv <close> = o
  208. return 1
  209. end
  210. local function foo ()
  211. local x <close> = func2close(function(_,msg)
  212. track[#track + 1] = msg or false
  213. error(20)
  214. end)
  215. local y <close> = func2close(function(_,msg)
  216. track[#track + 1] = msg or false
  217. return 1000
  218. end)
  219. local z <close> = func2close(function(_,msg)
  220. track[#track + 1] = msg or false
  221. error(10)
  222. end)
  223. coroutine.yield(1)
  224. h(func2close(function(_,msg)
  225. track[#track + 1] = msg or false
  226. error(2)
  227. end))
  228. end
  229. local co = coroutine.create(pcall)
  230. local st, res = coroutine.resume(co, foo) -- call 'foo' protected
  231. assert(st and res == 1) -- yield 1
  232. local st, res1, res2 = coroutine.resume(co) -- continue
  233. assert(coroutine.status(co) == "dead")
  234. assert(st and not res1 and res2 == 20) -- last error (20)
  235. assert(track[1] == false and track[2] == 2 and track[3] == 10 and
  236. track[4] == 10)
  237. end
  238. -- yielding across C boundaries
  239. local co = coroutine.wrap(function()
  240. assert(not pcall(table.sort,{1,2,3}, coroutine.yield))
  241. assert(coroutine.isyieldable())
  242. coroutine.yield(20)
  243. return 30
  244. end)
  245. assert(co() == 20)
  246. assert(co() == 30)
  247. local f = function (s, i) return coroutine.yield(i) end
  248. local f1 = coroutine.wrap(function ()
  249. return xpcall(pcall, function (...) return ... end,
  250. function ()
  251. local s = 0
  252. for i in f, nil, 1 do pcall(function () s = s + i end) end
  253. error({s})
  254. end)
  255. end)
  256. f1()
  257. for i = 1, 10 do assert(f1(i) == i) end
  258. local r1, r2, v = f1(nil)
  259. assert(r1 and not r2 and v[1] == (10 + 1)*10/2)
  260. local function f (a, b) a = coroutine.yield(a); error{a + b} end
  261. local function g(x) return x[1]*2 end
  262. co = coroutine.wrap(function ()
  263. coroutine.yield(xpcall(f, g, 10, 20))
  264. end)
  265. assert(co() == 10)
  266. local r, msg = co(100)
  267. assert(not r and msg == 240)
  268. -- unyieldable C call
  269. do
  270. local function f (c)
  271. assert(not coroutine.isyieldable())
  272. return c .. c
  273. end
  274. local co = coroutine.wrap(function (c)
  275. assert(coroutine.isyieldable())
  276. local s = string.gsub("a", ".", f)
  277. return s
  278. end)
  279. assert(co() == "aa")
  280. end
  281. do -- testing single trace of coroutines
  282. local X
  283. local co = coroutine.create(function ()
  284. coroutine.yield(10)
  285. return 20;
  286. end)
  287. local trace = {}
  288. local function dotrace (event)
  289. trace[#trace + 1] = event
  290. end
  291. debug.sethook(co, dotrace, "clr")
  292. repeat until not coroutine.resume(co)
  293. local correcttrace = {"call", "line", "call", "return", "line", "return"}
  294. assert(#trace == #correcttrace)
  295. for k, v in pairs(trace) do
  296. assert(v == correcttrace[k])
  297. end
  298. end
  299. -- errors in coroutines
  300. function foo ()
  301. assert(debug.getinfo(1).currentline == debug.getinfo(foo).linedefined + 1)
  302. assert(debug.getinfo(2).currentline == debug.getinfo(goo).linedefined)
  303. coroutine.yield(3)
  304. error(foo)
  305. end
  306. function goo() foo() end
  307. x = coroutine.wrap(goo)
  308. assert(x() == 3)
  309. local a,b = pcall(x)
  310. assert(not a and b == foo)
  311. x = coroutine.create(goo)
  312. a,b = coroutine.resume(x)
  313. assert(a and b == 3)
  314. a,b = coroutine.resume(x)
  315. assert(not a and b == foo and coroutine.status(x) == "dead")
  316. a,b = coroutine.resume(x)
  317. assert(not a and string.find(b, "dead") and coroutine.status(x) == "dead")
  318. goo = nil
  319. -- co-routines x for loop
  320. local function all (a, n, k)
  321. if k == 0 then coroutine.yield(a)
  322. else
  323. for i=1,n do
  324. a[k] = i
  325. all(a, n, k-1)
  326. end
  327. end
  328. end
  329. local a = 0
  330. for t in coroutine.wrap(function () all({}, 5, 4) end) do
  331. a = a+1
  332. end
  333. assert(a == 5^4)
  334. -- access to locals of collected corroutines
  335. local C = {}; setmetatable(C, {__mode = "kv"})
  336. local x = coroutine.wrap (function ()
  337. local a = 10
  338. local function f () a = a+10; return a end
  339. while true do
  340. a = a+1
  341. coroutine.yield(f)
  342. end
  343. end)
  344. C[1] = x;
  345. local f = x()
  346. assert(f() == 21 and x()() == 32 and x() == f)
  347. x = nil
  348. collectgarbage()
  349. assert(C[1] == undef)
  350. assert(f() == 43 and f() == 53)
  351. -- old bug: attempt to resume itself
  352. local function co_func (current_co)
  353. assert(coroutine.running() == current_co)
  354. assert(coroutine.resume(current_co) == false)
  355. coroutine.yield(10, 20)
  356. assert(coroutine.resume(current_co) == false)
  357. coroutine.yield(23)
  358. return 10
  359. end
  360. local co = coroutine.create(co_func)
  361. local a,b,c = coroutine.resume(co, co)
  362. assert(a == true and b == 10 and c == 20)
  363. a,b = coroutine.resume(co, co)
  364. assert(a == true and b == 23)
  365. a,b = coroutine.resume(co, co)
  366. assert(a == true and b == 10)
  367. assert(coroutine.resume(co, co) == false)
  368. assert(coroutine.resume(co, co) == false)
  369. -- other old bug when attempting to resume itself
  370. -- (trigger C-code assertions)
  371. do
  372. local A = coroutine.running()
  373. local B = coroutine.create(function() return coroutine.resume(A) end)
  374. local st, res = coroutine.resume(B)
  375. assert(st == true and res == false)
  376. local X = false
  377. A = coroutine.wrap(function()
  378. local _ <close> = func2close(function () X = true end)
  379. return pcall(A, 1)
  380. end)
  381. st, res = A()
  382. assert(not st and string.find(res, "non%-suspended") and X == true)
  383. end
  384. -- bug in 5.4.1
  385. do
  386. -- coroutine ran close metamethods with invalid status during a
  387. -- reset.
  388. local co
  389. co = coroutine.wrap(function()
  390. local x <close> = func2close(function() return pcall(co) end)
  391. error(111)
  392. end)
  393. local st, errobj = pcall(co)
  394. assert(not st and errobj == 111)
  395. st, errobj = pcall(co)
  396. assert(not st and string.find(errobj, "dead coroutine"))
  397. end
  398. -- attempt to resume 'normal' coroutine
  399. local co1, co2
  400. co1 = coroutine.create(function () return co2() end)
  401. co2 = coroutine.wrap(function ()
  402. assert(coroutine.status(co1) == 'normal')
  403. assert(not coroutine.resume(co1))
  404. coroutine.yield(3)
  405. end)
  406. a,b = coroutine.resume(co1)
  407. assert(a and b == 3)
  408. assert(coroutine.status(co1) == 'dead')
  409. -- infinite recursion of coroutines
  410. a = function(a) coroutine.wrap(a)(a) end
  411. assert(not pcall(a, a))
  412. a = nil
  413. do
  414. -- bug in 5.4: thread can use message handler higher in the stack
  415. -- than the variable being closed
  416. local c = coroutine.create(function()
  417. local clo <close> = setmetatable({}, {__close=function()
  418. local x = 134 -- will overwrite message handler
  419. error(x)
  420. end})
  421. -- yields coroutine but leaves a new message handler for it,
  422. -- that would be used when closing the coroutine (except that it
  423. -- will be overwritten)
  424. xpcall(coroutine.yield, function() return "XXX" end)
  425. end)
  426. assert(coroutine.resume(c)) -- start coroutine
  427. local st, msg = coroutine.close(c)
  428. assert(not st and msg == 134)
  429. end
  430. -- access to locals of erroneous coroutines
  431. local x = coroutine.create (function ()
  432. local a = 10
  433. _G.F = function () a=a+1; return a end
  434. error('x')
  435. end)
  436. assert(not coroutine.resume(x))
  437. -- overwrite previous position of local `a'
  438. assert(not coroutine.resume(x, 1, 1, 1, 1, 1, 1, 1))
  439. assert(_G.F() == 11)
  440. assert(_G.F() == 12)
  441. _G.F = nil
  442. if not T then
  443. (Message or print)
  444. ('\n >>> testC not active: skipping coroutine API tests <<<\n')
  445. else
  446. print "testing yields inside hooks"
  447. local turn
  448. local function fact (t, x)
  449. assert(turn == t)
  450. if x == 0 then return 1
  451. else return x*fact(t, x-1)
  452. end
  453. end
  454. local A, B = 0, 0
  455. local x = coroutine.create(function ()
  456. T.sethook("yield 0", "", 2)
  457. A = fact("A", 6)
  458. end)
  459. local y = coroutine.create(function ()
  460. T.sethook("yield 0", "", 3)
  461. B = fact("B", 7)
  462. end)
  463. while A==0 or B==0 do -- A ~= 0 when 'x' finishes (similar for 'B','y')
  464. if A==0 then turn = "A"; assert(T.resume(x)) end
  465. if B==0 then turn = "B"; assert(T.resume(y)) end
  466. -- check that traceback works correctly after yields inside hooks
  467. debug.traceback(x)
  468. debug.traceback(y)
  469. end
  470. assert(B // A == 7) -- fact(7) // fact(6)
  471. do -- hooks vs. multiple values
  472. local done
  473. local function test (n)
  474. done = false
  475. return coroutine.wrap(function ()
  476. local a = {}
  477. for i = 1, n do a[i] = i end
  478. -- 'pushint' just to perturb the stack
  479. T.sethook("pushint 10; yield 0", "", 1) -- yield at each op.
  480. local a1 = {table.unpack(a)} -- must keep top between ops.
  481. assert(#a1 == n)
  482. for i = 1, n do assert(a[i] == i) end
  483. done = true
  484. end)
  485. end
  486. -- arguments to the coroutine are just to perturb its stack
  487. local co = test(0); while not done do co(30) end
  488. co = test(1); while not done do co(20, 10) end
  489. co = test(3); while not done do co() end
  490. co = test(100); while not done do co() end
  491. end
  492. local line = debug.getinfo(1, "l").currentline + 2 -- get line number
  493. local function foo ()
  494. local x = 10 --<< this line is 'line'
  495. x = x + 10
  496. _G.XX = x
  497. end
  498. -- testing yields in line hook
  499. local co = coroutine.wrap(function ()
  500. T.sethook("setglobal X; yield 0", "l", 0); foo(); return 10 end)
  501. _G.XX = nil;
  502. _G.X = nil; co(); assert(_G.X == line)
  503. _G.X = nil; co(); assert(_G.X == line + 1)
  504. _G.X = nil; co(); assert(_G.X == line + 2 and _G.XX == nil)
  505. _G.X = nil; co(); assert(_G.X == line + 3 and _G.XX == 20)
  506. assert(co() == 10)
  507. _G.X = nil
  508. -- testing yields in count hook
  509. co = coroutine.wrap(function ()
  510. T.sethook("yield 0", "", 1); foo(); return 10 end)
  511. _G.XX = nil;
  512. local c = 0
  513. repeat c = c + 1; local a = co() until a == 10
  514. assert(_G.XX == 20 and c >= 5)
  515. co = coroutine.wrap(function ()
  516. T.sethook("yield 0", "", 2); foo(); return 10 end)
  517. _G.XX = nil;
  518. local c = 0
  519. repeat c = c + 1; local a = co() until a == 10
  520. assert(_G.XX == 20 and c >= 5)
  521. _G.X = nil; _G.XX = nil
  522. do
  523. -- testing debug library on a coroutine suspended inside a hook
  524. -- (bug in 5.2/5.3)
  525. c = coroutine.create(function (a, ...)
  526. T.sethook("yield 0", "l") -- will yield on next two lines
  527. local b = a
  528. return ...
  529. end)
  530. assert(coroutine.resume(c, 1, 2, 3)) -- start coroutine
  531. local n,v = debug.getlocal(c, 0, 1) -- check its local
  532. assert(n == "a" and v == 1 and debug.getlocal(c, 0, 2) ~= "b")
  533. assert(debug.setlocal(c, 0, 1, 10)) -- test 'setlocal'
  534. local t = debug.getinfo(c, 0) -- test 'getinfo'
  535. assert(t.currentline == t.linedefined + 2)
  536. assert(not debug.getinfo(c, 1)) -- no other level
  537. assert(coroutine.resume(c)) -- run next line
  538. local n,v = debug.getlocal(c, 0, 2) -- check next local
  539. assert(n == "b" and v == 10)
  540. v = {coroutine.resume(c)} -- finish coroutine
  541. assert(v[1] == true and v[2] == 2 and v[3] == 3 and v[4] == undef)
  542. assert(not coroutine.resume(c))
  543. end
  544. do
  545. -- testing debug library on last function in a suspended coroutine
  546. -- (bug in 5.2/5.3)
  547. local c = coroutine.create(function () T.testC("yield 1", 10, 20) end)
  548. local a, b = coroutine.resume(c)
  549. assert(a and b == 20)
  550. assert(debug.getinfo(c, 0).linedefined == -1)
  551. a, b = debug.getlocal(c, 0, 2)
  552. assert(b == 10)
  553. end
  554. print "testing coroutine API"
  555. -- reusing a thread
  556. assert(T.testC([[
  557. newthread # create thread
  558. pushvalue 2 # push body
  559. pushstring 'a a a' # push argument
  560. xmove 0 3 2 # move values to new thread
  561. resume -1, 1 # call it first time
  562. pushstatus
  563. xmove 3 0 0 # move results back to stack
  564. setglobal X # result
  565. setglobal Y # status
  566. pushvalue 2 # push body (to call it again)
  567. pushstring 'b b b'
  568. xmove 0 3 2
  569. resume -1, 1 # call it again
  570. pushstatus
  571. xmove 3 0 0
  572. return 1 # return result
  573. ]], function (...) return ... end) == 'b b b')
  574. assert(X == 'a a a' and Y == 'OK')
  575. X, Y = nil
  576. -- resuming running coroutine
  577. C = coroutine.create(function ()
  578. return T.testC([[
  579. pushnum 10;
  580. pushnum 20;
  581. resume -3 2;
  582. pushstatus
  583. gettop;
  584. return 3]], C)
  585. end)
  586. local a, b, c, d = coroutine.resume(C)
  587. assert(a == true and string.find(b, "non%-suspended") and
  588. c == "ERRRUN" and d == 4)
  589. a, b, c, d = T.testC([[
  590. rawgeti R 1 # get main thread
  591. pushnum 10;
  592. pushnum 20;
  593. resume -3 2;
  594. pushstatus
  595. gettop;
  596. return 4]])
  597. assert(a == coroutine.running() and string.find(b, "non%-suspended") and
  598. c == "ERRRUN" and d == 4)
  599. -- using a main thread as a coroutine (dubious use!)
  600. local state = T.newstate()
  601. -- check that yielddable is working correctly
  602. assert(T.testC(state, "newthread; isyieldable -1; remove 1; return 1"))
  603. -- main thread is not yieldable
  604. assert(not T.testC(state, "rawgeti R 1; isyieldable -1; remove 1; return 1"))
  605. T.testC(state, "settop 0")
  606. T.loadlib(state)
  607. assert(T.doremote(state, [[
  608. coroutine = require'coroutine';
  609. X = function (x) coroutine.yield(x, 'BB'); return 'CC' end;
  610. return 'ok']]))
  611. local t = table.pack(T.testC(state, [[
  612. rawgeti R 1 # get main thread
  613. pushstring 'XX'
  614. getglobal X # get function for body
  615. pushstring AA # arg
  616. resume 1 1 # 'resume' shadows previous stack!
  617. gettop
  618. setglobal T # top
  619. setglobal B # second yielded value
  620. setglobal A # fist yielded value
  621. rawgeti R 1 # get main thread
  622. pushnum 5 # arg (noise)
  623. resume 1 1 # after coroutine ends, previous stack is back
  624. pushstatus
  625. return *
  626. ]]))
  627. assert(t.n == 4 and t[2] == 'XX' and t[3] == 'CC' and t[4] == 'OK')
  628. assert(T.doremote(state, "return T") == '2')
  629. assert(T.doremote(state, "return A") == 'AA')
  630. assert(T.doremote(state, "return B") == 'BB')
  631. T.closestate(state)
  632. print'+'
  633. end
  634. -- leaving a pending coroutine open
  635. _G.TO_SURVIVE = coroutine.wrap(function ()
  636. local a = 10
  637. local x = function () a = a+1 end
  638. coroutine.yield()
  639. end)
  640. _G.TO_SURVIVE()
  641. if not _soft then
  642. -- bug (stack overflow)
  643. local lim = 1000000 -- stack limit; assume 32-bit machine
  644. local t = {lim - 10, lim - 5, lim - 1, lim, lim + 1, lim + 5}
  645. for i = 1, #t do
  646. local j = t[i]
  647. local co = coroutine.create(function()
  648. return table.unpack({}, 1, j)
  649. end)
  650. local r, msg = coroutine.resume(co)
  651. -- must fail for unpacking larger than stack limit
  652. assert(j < lim or not r)
  653. end
  654. end
  655. assert(coroutine.running() == main)
  656. print"+"
  657. print"testing yields inside metamethods"
  658. local function val(x)
  659. if type(x) == "table" then return x.x else return x end
  660. end
  661. local mt = {
  662. __eq = function(a,b) coroutine.yield(nil, "eq"); return val(a) == val(b) end,
  663. __lt = function(a,b) coroutine.yield(nil, "lt"); return val(a) < val(b) end,
  664. __le = function(a,b) coroutine.yield(nil, "le"); return a - b <= 0 end,
  665. __add = function(a,b) coroutine.yield(nil, "add");
  666. return val(a) + val(b) end,
  667. __sub = function(a,b) coroutine.yield(nil, "sub"); return val(a) - val(b) end,
  668. __mul = function(a,b) coroutine.yield(nil, "mul"); return val(a) * val(b) end,
  669. __div = function(a,b) coroutine.yield(nil, "div"); return val(a) / val(b) end,
  670. __idiv = function(a,b) coroutine.yield(nil, "idiv");
  671. return val(a) // val(b) end,
  672. __pow = function(a,b) coroutine.yield(nil, "pow"); return val(a) ^ val(b) end,
  673. __mod = function(a,b) coroutine.yield(nil, "mod"); return val(a) % val(b) end,
  674. __unm = function(a,b) coroutine.yield(nil, "unm"); return -val(a) end,
  675. __bnot = function(a,b) coroutine.yield(nil, "bnot"); return ~val(a) end,
  676. __shl = function(a,b) coroutine.yield(nil, "shl");
  677. return val(a) << val(b) end,
  678. __shr = function(a,b) coroutine.yield(nil, "shr");
  679. return val(a) >> val(b) end,
  680. __band = function(a,b)
  681. coroutine.yield(nil, "band")
  682. return val(a) & val(b)
  683. end,
  684. __bor = function(a,b) coroutine.yield(nil, "bor");
  685. return val(a) | val(b) end,
  686. __bxor = function(a,b) coroutine.yield(nil, "bxor");
  687. return val(a) ~ val(b) end,
  688. __concat = function(a,b)
  689. coroutine.yield(nil, "concat");
  690. return val(a) .. val(b)
  691. end,
  692. __index = function (t,k) coroutine.yield(nil, "idx"); return t.k[k] end,
  693. __newindex = function (t,k,v) coroutine.yield(nil, "nidx"); t.k[k] = v end,
  694. }
  695. local function new (x)
  696. return setmetatable({x = x, k = {}}, mt)
  697. end
  698. local a = new(10)
  699. local b = new(12)
  700. local c = new"hello"
  701. local function run (f, t)
  702. local i = 1
  703. local c = coroutine.wrap(f)
  704. while true do
  705. local res, stat = c()
  706. if res then assert(t[i] == undef); return res, t end
  707. assert(stat == t[i])
  708. i = i + 1
  709. end
  710. end
  711. assert(run(function () if (a>=b) then return '>=' else return '<' end end,
  712. {"le", "sub"}) == "<")
  713. assert(run(function () if (a<=b) then return '<=' else return '>' end end,
  714. {"le", "sub"}) == "<=")
  715. assert(run(function () if (a==b) then return '==' else return '~=' end end,
  716. {"eq"}) == "~=")
  717. assert(run(function () return a & b + a end, {"add", "band"}) == 2)
  718. assert(run(function () return 1 + a end, {"add"}) == 11)
  719. assert(run(function () return a - 25 end, {"sub"}) == -15)
  720. assert(run(function () return 2 * a end, {"mul"}) == 20)
  721. assert(run(function () return a ^ 2 end, {"pow"}) == 100)
  722. assert(run(function () return a / 2 end, {"div"}) == 5)
  723. assert(run(function () return a % 6 end, {"mod"}) == 4)
  724. assert(run(function () return a // 3 end, {"idiv"}) == 3)
  725. assert(run(function () return a + b end, {"add"}) == 22)
  726. assert(run(function () return a - b end, {"sub"}) == -2)
  727. assert(run(function () return a * b end, {"mul"}) == 120)
  728. assert(run(function () return a ^ b end, {"pow"}) == 10^12)
  729. assert(run(function () return a / b end, {"div"}) == 10/12)
  730. assert(run(function () return a % b end, {"mod"}) == 10)
  731. assert(run(function () return a // b end, {"idiv"}) == 0)
  732. -- repeat tests with larger constants (to use 'K' opcodes)
  733. local a1000 = new(1000)
  734. assert(run(function () return a1000 + 1000 end, {"add"}) == 2000)
  735. assert(run(function () return a1000 - 25000 end, {"sub"}) == -24000)
  736. assert(run(function () return 2000 * a end, {"mul"}) == 20000)
  737. assert(run(function () return a1000 / 1000 end, {"div"}) == 1)
  738. assert(run(function () return a1000 % 600 end, {"mod"}) == 400)
  739. assert(run(function () return a1000 // 500 end, {"idiv"}) == 2)
  740. assert(run(function () return a % b end, {"mod"}) == 10)
  741. assert(run(function () return ~a & b end, {"bnot", "band"}) == ~10 & 12)
  742. assert(run(function () return a | b end, {"bor"}) == 10 | 12)
  743. assert(run(function () return a ~ b end, {"bxor"}) == 10 ~ 12)
  744. assert(run(function () return a << b end, {"shl"}) == 10 << 12)
  745. assert(run(function () return a >> b end, {"shr"}) == 10 >> 12)
  746. assert(run(function () return 10 & b end, {"band"}) == 10 & 12)
  747. assert(run(function () return a | 2 end, {"bor"}) == 10 | 2)
  748. assert(run(function () return a ~ 2 end, {"bxor"}) == 10 ~ 2)
  749. assert(run(function () return a >> 2 end, {"shr"}) == 10 >> 2)
  750. assert(run(function () return 1 >> a end, {"shr"}) == 1 >> 10)
  751. assert(run(function () return a << 2 end, {"shl"}) == 10 << 2)
  752. assert(run(function () return 1 << a end, {"shl"}) == 1 << 10)
  753. assert(run(function () return 2 ~ a end, {"bxor"}) == 2 ~ 10)
  754. assert(run(function () return a..b end, {"concat"}) == "1012")
  755. assert(run(function() return a .. b .. c .. a end,
  756. {"concat", "concat", "concat"}) == "1012hello10")
  757. assert(run(function() return "a" .. "b" .. a .. "c" .. c .. b .. "x" end,
  758. {"concat", "concat", "concat"}) == "ab10chello12x")
  759. do -- a few more tests for comparison operators
  760. local mt1 = {
  761. __le = function (a,b)
  762. coroutine.yield(10)
  763. return (val(a) <= val(b))
  764. end,
  765. __lt = function (a,b)
  766. coroutine.yield(10)
  767. return val(a) < val(b)
  768. end,
  769. }
  770. local mt2 = { __lt = mt1.__lt, __le = mt1.__le }
  771. local function run (f)
  772. local co = coroutine.wrap(f)
  773. local res
  774. repeat
  775. res = co()
  776. until res ~= 10
  777. return res
  778. end
  779. local function test ()
  780. local a1 = setmetatable({x=1}, mt1)
  781. local a2 = setmetatable({x=2}, mt2)
  782. assert(a1 < a2)
  783. assert(a1 <= a2)
  784. assert(1 < a2)
  785. assert(1 <= a2)
  786. assert(2 > a1)
  787. assert(2 >= a2)
  788. return true
  789. end
  790. run(test)
  791. end
  792. assert(run(function ()
  793. a.BB = print
  794. return a.BB
  795. end, {"nidx", "idx"}) == print)
  796. -- getuptable & setuptable
  797. do local _ENV = _ENV
  798. f = function () AAA = BBB + 1; return AAA end
  799. end
  800. local g = new(10); g.k.BBB = 10;
  801. debug.setupvalue(f, 1, g)
  802. assert(run(f, {"idx", "nidx", "idx"}) == 11)
  803. assert(g.k.AAA == 11)
  804. print"+"
  805. print"testing yields inside 'for' iterators"
  806. local f = function (s, i)
  807. if i%2 == 0 then coroutine.yield(nil, "for") end
  808. if i < s then return i + 1 end
  809. end
  810. assert(run(function ()
  811. local s = 0
  812. for i in f, 4, 0 do s = s + i end
  813. return s
  814. end, {"for", "for", "for"}) == 10)
  815. -- tests for coroutine API
  816. if T==nil then
  817. (Message or print)('\n >>> testC not active: skipping coroutine API tests <<<\n')
  818. print "OK"; return
  819. end
  820. print('testing coroutine API')
  821. local function apico (...)
  822. local x = {...}
  823. return coroutine.wrap(function ()
  824. return T.testC(table.unpack(x))
  825. end)
  826. end
  827. local a = {apico(
  828. [[
  829. pushstring errorcode
  830. pcallk 1 0 2;
  831. invalid command (should not arrive here)
  832. ]],
  833. [[return *]],
  834. "stackmark",
  835. error
  836. )()}
  837. assert(#a == 4 and
  838. a[3] == "stackmark" and
  839. a[4] == "errorcode" and
  840. _G.status == "ERRRUN" and
  841. _G.ctx == 2) -- 'ctx' to pcallk
  842. local co = apico(
  843. "pushvalue 2; pushnum 10; pcallk 1 2 3; invalid command;",
  844. coroutine.yield,
  845. "getglobal status; getglobal ctx; pushvalue 2; pushstring a; pcallk 1 0 4; invalid command",
  846. "getglobal status; getglobal ctx; return *")
  847. assert(co() == 10)
  848. assert(co(20, 30) == 'a')
  849. a = {co()}
  850. assert(#a == 10 and
  851. a[2] == coroutine.yield and
  852. a[5] == 20 and a[6] == 30 and
  853. a[7] == "YIELD" and a[8] == 3 and
  854. a[9] == "YIELD" and a[10] == 4)
  855. assert(not pcall(co)) -- coroutine is dead now
  856. f = T.makeCfunc("pushnum 3; pushnum 5; yield 1;")
  857. co = coroutine.wrap(function ()
  858. assert(f() == 23); assert(f() == 23); return 10
  859. end)
  860. assert(co(23,16) == 5)
  861. assert(co(23,16) == 5)
  862. assert(co(23,16) == 10)
  863. -- testing coroutines with C bodies
  864. f = T.makeCfunc([[
  865. pushnum 102
  866. yieldk 1 U2
  867. cannot be here!
  868. ]],
  869. [[ # continuation
  870. pushvalue U3 # accessing upvalues inside a continuation
  871. pushvalue U4
  872. return *
  873. ]], 23, "huu")
  874. x = coroutine.wrap(f)
  875. assert(x() == 102)
  876. eqtab({x()}, {23, "huu"})
  877. f = T.makeCfunc[[pushstring 'a'; pushnum 102; yield 2; ]]
  878. a, b, c, d = T.testC([[newthread; pushvalue 2; xmove 0 3 1; resume 3 0;
  879. pushstatus; xmove 3 0 0; resume 3 0; pushstatus;
  880. return 4; ]], f)
  881. assert(a == 'YIELD' and b == 'a' and c == 102 and d == 'OK')
  882. -- testing chain of suspendable C calls
  883. local count = 3 -- number of levels
  884. f = T.makeCfunc([[
  885. remove 1; # remove argument
  886. pushvalue U3; # get selection function
  887. call 0 1; # call it (result is 'f' or 'yield')
  888. pushstring hello # single argument for selected function
  889. pushupvalueindex 2; # index of continuation program
  890. callk 1 -1 .; # call selected function
  891. errorerror # should never arrive here
  892. ]],
  893. [[
  894. # continuation program
  895. pushnum 34 # return value
  896. return * # return all results
  897. ]],
  898. function () -- selection function
  899. count = count - 1
  900. if count == 0 then return coroutine.yield
  901. else return f
  902. end
  903. end
  904. )
  905. co = coroutine.wrap(function () return f(nil) end)
  906. assert(co() == "hello") -- argument to 'yield'
  907. a = {co()}
  908. -- three '34's (one from each pending C call)
  909. assert(#a == 3 and a[1] == a[2] and a[2] == a[3] and a[3] == 34)
  910. -- testing yields with continuations
  911. local y
  912. co = coroutine.wrap(function (...) return
  913. T.testC([[ # initial function
  914. yieldk 1 2
  915. cannot be here!
  916. ]],
  917. [[ # 1st continuation
  918. yieldk 0 3
  919. cannot be here!
  920. ]],
  921. [[ # 2nd continuation
  922. yieldk 0 4
  923. cannot be here!
  924. ]],
  925. [[ # 3th continuation
  926. pushvalue 6 # function which is last arg. to 'testC' here
  927. pushnum 10; pushnum 20;
  928. pcall 2 0 0 # call should throw an error and return to next line
  929. pop 1 # remove error message
  930. pushvalue 6
  931. getglobal status; getglobal ctx
  932. pcallk 2 2 5 # call should throw an error and jump to continuation
  933. cannot be here!
  934. ]],
  935. [[ # 4th (and last) continuation
  936. return *
  937. ]],
  938. -- function called by 3th continuation
  939. function (a,b) x=a; y=b; error("errmsg") end,
  940. ...
  941. )
  942. end)
  943. local a = {co(3,4,6)}
  944. assert(a[1] == 6 and a[2] == undef)
  945. a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 2)
  946. a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 3)
  947. a = {co(7,8)};
  948. -- original arguments
  949. assert(type(a[1]) == 'string' and type(a[2]) == 'string' and
  950. type(a[3]) == 'string' and type(a[4]) == 'string' and
  951. type(a[5]) == 'string' and type(a[6]) == 'function')
  952. -- arguments left from fist resume
  953. assert(a[7] == 3 and a[8] == 4)
  954. -- arguments to last resume
  955. assert(a[9] == 7 and a[10] == 8)
  956. -- error message and nothing more
  957. assert(a[11]:find("errmsg") and #a == 11)
  958. -- check arguments to pcallk
  959. assert(x == "YIELD" and y == 4)
  960. assert(not pcall(co)) -- coroutine should be dead
  961. _G.ctx = nil
  962. _G.status = nil
  963. -- bug in nCcalls
  964. local co = coroutine.wrap(function ()
  965. local a = {pcall(pcall,pcall,pcall,pcall,pcall,pcall,pcall,error,"hi")}
  966. return pcall(assert, table.unpack(a))
  967. end)
  968. local a = {co()}
  969. assert(a[10] == "hi")
  970. print'OK'