coroutine.lua 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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. -- access to locals of erroneous coroutines
  414. local x = coroutine.create (function ()
  415. local a = 10
  416. _G.F = function () a=a+1; return a end
  417. error('x')
  418. end)
  419. assert(not coroutine.resume(x))
  420. -- overwrite previous position of local `a'
  421. assert(not coroutine.resume(x, 1, 1, 1, 1, 1, 1, 1))
  422. assert(_G.F() == 11)
  423. assert(_G.F() == 12)
  424. _G.F = nil
  425. if not T then
  426. (Message or print)
  427. ('\n >>> testC not active: skipping coroutine API tests <<<\n')
  428. else
  429. print "testing yields inside hooks"
  430. local turn
  431. local function fact (t, x)
  432. assert(turn == t)
  433. if x == 0 then return 1
  434. else return x*fact(t, x-1)
  435. end
  436. end
  437. local A, B = 0, 0
  438. local x = coroutine.create(function ()
  439. T.sethook("yield 0", "", 2)
  440. A = fact("A", 6)
  441. end)
  442. local y = coroutine.create(function ()
  443. T.sethook("yield 0", "", 3)
  444. B = fact("B", 7)
  445. end)
  446. while A==0 or B==0 do -- A ~= 0 when 'x' finishes (similar for 'B','y')
  447. if A==0 then turn = "A"; assert(T.resume(x)) end
  448. if B==0 then turn = "B"; assert(T.resume(y)) end
  449. -- check that traceback works correctly after yields inside hooks
  450. debug.traceback(x)
  451. debug.traceback(y)
  452. end
  453. assert(B // A == 7) -- fact(7) // fact(6)
  454. do -- hooks vs. multiple values
  455. local done
  456. local function test (n)
  457. done = false
  458. return coroutine.wrap(function ()
  459. local a = {}
  460. for i = 1, n do a[i] = i end
  461. -- 'pushint' just to perturb the stack
  462. T.sethook("pushint 10; yield 0", "", 1) -- yield at each op.
  463. local a1 = {table.unpack(a)} -- must keep top between ops.
  464. assert(#a1 == n)
  465. for i = 1, n do assert(a[i] == i) end
  466. done = true
  467. end)
  468. end
  469. -- arguments to the coroutine are just to perturb its stack
  470. local co = test(0); while not done do co(30) end
  471. co = test(1); while not done do co(20, 10) end
  472. co = test(3); while not done do co() end
  473. co = test(100); while not done do co() end
  474. end
  475. local line = debug.getinfo(1, "l").currentline + 2 -- get line number
  476. local function foo ()
  477. local x = 10 --<< this line is 'line'
  478. x = x + 10
  479. _G.XX = x
  480. end
  481. -- testing yields in line hook
  482. local co = coroutine.wrap(function ()
  483. T.sethook("setglobal X; yield 0", "l", 0); foo(); return 10 end)
  484. _G.XX = nil;
  485. _G.X = nil; co(); assert(_G.X == line)
  486. _G.X = nil; co(); assert(_G.X == line + 1)
  487. _G.X = nil; co(); assert(_G.X == line + 2 and _G.XX == nil)
  488. _G.X = nil; co(); assert(_G.X == line + 3 and _G.XX == 20)
  489. assert(co() == 10)
  490. _G.X = nil
  491. -- testing yields in count hook
  492. co = coroutine.wrap(function ()
  493. T.sethook("yield 0", "", 1); foo(); return 10 end)
  494. _G.XX = nil;
  495. local c = 0
  496. repeat c = c + 1; local a = co() until a == 10
  497. assert(_G.XX == 20 and c >= 5)
  498. co = coroutine.wrap(function ()
  499. T.sethook("yield 0", "", 2); foo(); return 10 end)
  500. _G.XX = nil;
  501. local c = 0
  502. repeat c = c + 1; local a = co() until a == 10
  503. assert(_G.XX == 20 and c >= 5)
  504. _G.X = nil; _G.XX = nil
  505. do
  506. -- testing debug library on a coroutine suspended inside a hook
  507. -- (bug in 5.2/5.3)
  508. c = coroutine.create(function (a, ...)
  509. T.sethook("yield 0", "l") -- will yield on next two lines
  510. assert(a == 10)
  511. return ...
  512. end)
  513. assert(coroutine.resume(c, 1, 2, 3)) -- start coroutine
  514. local n,v = debug.getlocal(c, 0, 1) -- check its local
  515. assert(n == "a" and v == 1)
  516. assert(debug.setlocal(c, 0, 1, 10)) -- test 'setlocal'
  517. local t = debug.getinfo(c, 0) -- test 'getinfo'
  518. assert(t.currentline == t.linedefined + 1)
  519. assert(not debug.getinfo(c, 1)) -- no other level
  520. assert(coroutine.resume(c)) -- run next line
  521. v = {coroutine.resume(c)} -- finish coroutine
  522. assert(v[1] == true and v[2] == 2 and v[3] == 3 and v[4] == undef)
  523. assert(not coroutine.resume(c))
  524. end
  525. do
  526. -- testing debug library on last function in a suspended coroutine
  527. -- (bug in 5.2/5.3)
  528. local c = coroutine.create(function () T.testC("yield 1", 10, 20) end)
  529. local a, b = coroutine.resume(c)
  530. assert(a and b == 20)
  531. assert(debug.getinfo(c, 0).linedefined == -1)
  532. a, b = debug.getlocal(c, 0, 2)
  533. assert(b == 10)
  534. end
  535. print "testing coroutine API"
  536. -- reusing a thread
  537. assert(T.testC([[
  538. newthread # create thread
  539. pushvalue 2 # push body
  540. pushstring 'a a a' # push argument
  541. xmove 0 3 2 # move values to new thread
  542. resume -1, 1 # call it first time
  543. pushstatus
  544. xmove 3 0 0 # move results back to stack
  545. setglobal X # result
  546. setglobal Y # status
  547. pushvalue 2 # push body (to call it again)
  548. pushstring 'b b b'
  549. xmove 0 3 2
  550. resume -1, 1 # call it again
  551. pushstatus
  552. xmove 3 0 0
  553. return 1 # return result
  554. ]], function (...) return ... end) == 'b b b')
  555. assert(X == 'a a a' and Y == 'OK')
  556. X, Y = nil
  557. -- resuming running coroutine
  558. C = coroutine.create(function ()
  559. return T.testC([[
  560. pushnum 10;
  561. pushnum 20;
  562. resume -3 2;
  563. pushstatus
  564. gettop;
  565. return 3]], C)
  566. end)
  567. local a, b, c, d = coroutine.resume(C)
  568. assert(a == true and string.find(b, "non%-suspended") and
  569. c == "ERRRUN" and d == 4)
  570. a, b, c, d = T.testC([[
  571. rawgeti R 1 # get main thread
  572. pushnum 10;
  573. pushnum 20;
  574. resume -3 2;
  575. pushstatus
  576. gettop;
  577. return 4]])
  578. assert(a == coroutine.running() and string.find(b, "non%-suspended") and
  579. c == "ERRRUN" and d == 4)
  580. -- using a main thread as a coroutine (dubious use!)
  581. local state = T.newstate()
  582. -- check that yielddable is working correctly
  583. assert(T.testC(state, "newthread; isyieldable -1; remove 1; return 1"))
  584. -- main thread is not yieldable
  585. assert(not T.testC(state, "rawgeti R 1; isyieldable -1; remove 1; return 1"))
  586. T.testC(state, "settop 0")
  587. T.loadlib(state)
  588. assert(T.doremote(state, [[
  589. coroutine = require'coroutine';
  590. X = function (x) coroutine.yield(x, 'BB'); return 'CC' end;
  591. return 'ok']]))
  592. local t = table.pack(T.testC(state, [[
  593. rawgeti R 1 # get main thread
  594. pushstring 'XX'
  595. getglobal X # get function for body
  596. pushstring AA # arg
  597. resume 1 1 # 'resume' shadows previous stack!
  598. gettop
  599. setglobal T # top
  600. setglobal B # second yielded value
  601. setglobal A # fist yielded value
  602. rawgeti R 1 # get main thread
  603. pushnum 5 # arg (noise)
  604. resume 1 1 # after coroutine ends, previous stack is back
  605. pushstatus
  606. return *
  607. ]]))
  608. assert(t.n == 4 and t[2] == 'XX' and t[3] == 'CC' and t[4] == 'OK')
  609. assert(T.doremote(state, "return T") == '2')
  610. assert(T.doremote(state, "return A") == 'AA')
  611. assert(T.doremote(state, "return B") == 'BB')
  612. T.closestate(state)
  613. print'+'
  614. end
  615. -- leaving a pending coroutine open
  616. _G.TO_SURVIVE = coroutine.wrap(function ()
  617. local a = 10
  618. local x = function () a = a+1 end
  619. coroutine.yield()
  620. end)
  621. _G.TO_SURVIVE()
  622. if not _soft then
  623. -- bug (stack overflow)
  624. local lim = 1000000 -- stack limit; assume 32-bit machine
  625. local t = {lim - 10, lim - 5, lim - 1, lim, lim + 1, lim + 5}
  626. for i = 1, #t do
  627. local j = t[i]
  628. local co = coroutine.create(function()
  629. return table.unpack({}, 1, j)
  630. end)
  631. local r, msg = coroutine.resume(co)
  632. -- must fail for unpacking larger than stack limit
  633. assert(j < lim or not r)
  634. end
  635. end
  636. assert(coroutine.running() == main)
  637. print"+"
  638. print"testing yields inside metamethods"
  639. local function val(x)
  640. if type(x) == "table" then return x.x else return x end
  641. end
  642. local mt = {
  643. __eq = function(a,b) coroutine.yield(nil, "eq"); return val(a) == val(b) end,
  644. __lt = function(a,b) coroutine.yield(nil, "lt"); return val(a) < val(b) end,
  645. __le = function(a,b) coroutine.yield(nil, "le"); return a - b <= 0 end,
  646. __add = function(a,b) coroutine.yield(nil, "add");
  647. return val(a) + val(b) end,
  648. __sub = function(a,b) coroutine.yield(nil, "sub"); return val(a) - val(b) end,
  649. __mul = function(a,b) coroutine.yield(nil, "mul"); return val(a) * val(b) end,
  650. __div = function(a,b) coroutine.yield(nil, "div"); return val(a) / val(b) end,
  651. __idiv = function(a,b) coroutine.yield(nil, "idiv");
  652. return val(a) // val(b) end,
  653. __pow = function(a,b) coroutine.yield(nil, "pow"); return val(a) ^ val(b) end,
  654. __mod = function(a,b) coroutine.yield(nil, "mod"); return val(a) % val(b) end,
  655. __unm = function(a,b) coroutine.yield(nil, "unm"); return -val(a) end,
  656. __bnot = function(a,b) coroutine.yield(nil, "bnot"); return ~val(a) end,
  657. __shl = function(a,b) coroutine.yield(nil, "shl");
  658. return val(a) << val(b) end,
  659. __shr = function(a,b) coroutine.yield(nil, "shr");
  660. return val(a) >> val(b) end,
  661. __band = function(a,b)
  662. coroutine.yield(nil, "band")
  663. return val(a) & val(b)
  664. end,
  665. __bor = function(a,b) coroutine.yield(nil, "bor");
  666. return val(a) | val(b) end,
  667. __bxor = function(a,b) coroutine.yield(nil, "bxor");
  668. return val(a) ~ val(b) end,
  669. __concat = function(a,b)
  670. coroutine.yield(nil, "concat");
  671. return val(a) .. val(b)
  672. end,
  673. __index = function (t,k) coroutine.yield(nil, "idx"); return t.k[k] end,
  674. __newindex = function (t,k,v) coroutine.yield(nil, "nidx"); t.k[k] = v end,
  675. }
  676. local function new (x)
  677. return setmetatable({x = x, k = {}}, mt)
  678. end
  679. local a = new(10)
  680. local b = new(12)
  681. local c = new"hello"
  682. local function run (f, t)
  683. local i = 1
  684. local c = coroutine.wrap(f)
  685. while true do
  686. local res, stat = c()
  687. if res then assert(t[i] == undef); return res, t end
  688. assert(stat == t[i])
  689. i = i + 1
  690. end
  691. end
  692. assert(run(function () if (a>=b) then return '>=' else return '<' end end,
  693. {"le", "sub"}) == "<")
  694. assert(run(function () if (a<=b) then return '<=' else return '>' end end,
  695. {"le", "sub"}) == "<=")
  696. assert(run(function () if (a==b) then return '==' else return '~=' end end,
  697. {"eq"}) == "~=")
  698. assert(run(function () return a & b + a end, {"add", "band"}) == 2)
  699. assert(run(function () return 1 + a end, {"add"}) == 11)
  700. assert(run(function () return a - 25 end, {"sub"}) == -15)
  701. assert(run(function () return 2 * a end, {"mul"}) == 20)
  702. assert(run(function () return a ^ 2 end, {"pow"}) == 100)
  703. assert(run(function () return a / 2 end, {"div"}) == 5)
  704. assert(run(function () return a % 6 end, {"mod"}) == 4)
  705. assert(run(function () return a // 3 end, {"idiv"}) == 3)
  706. assert(run(function () return a + b end, {"add"}) == 22)
  707. assert(run(function () return a - b end, {"sub"}) == -2)
  708. assert(run(function () return a * b end, {"mul"}) == 120)
  709. assert(run(function () return a ^ b end, {"pow"}) == 10^12)
  710. assert(run(function () return a / b end, {"div"}) == 10/12)
  711. assert(run(function () return a % b end, {"mod"}) == 10)
  712. assert(run(function () return a // b end, {"idiv"}) == 0)
  713. -- repeat tests with larger constants (to use 'K' opcodes)
  714. local a1000 = new(1000)
  715. assert(run(function () return a1000 + 1000 end, {"add"}) == 2000)
  716. assert(run(function () return a1000 - 25000 end, {"sub"}) == -24000)
  717. assert(run(function () return 2000 * a end, {"mul"}) == 20000)
  718. assert(run(function () return a1000 / 1000 end, {"div"}) == 1)
  719. assert(run(function () return a1000 % 600 end, {"mod"}) == 400)
  720. assert(run(function () return a1000 // 500 end, {"idiv"}) == 2)
  721. assert(run(function () return a % b end, {"mod"}) == 10)
  722. assert(run(function () return ~a & b end, {"bnot", "band"}) == ~10 & 12)
  723. assert(run(function () return a | b end, {"bor"}) == 10 | 12)
  724. assert(run(function () return a ~ b end, {"bxor"}) == 10 ~ 12)
  725. assert(run(function () return a << b end, {"shl"}) == 10 << 12)
  726. assert(run(function () return a >> b end, {"shr"}) == 10 >> 12)
  727. assert(run(function () return 10 & b end, {"band"}) == 10 & 12)
  728. assert(run(function () return a | 2 end, {"bor"}) == 10 | 2)
  729. assert(run(function () return a ~ 2 end, {"bxor"}) == 10 ~ 2)
  730. assert(run(function () return a >> 2 end, {"shr"}) == 10 >> 2)
  731. assert(run(function () return 1 >> a end, {"shr"}) == 1 >> 10)
  732. assert(run(function () return a << 2 end, {"shl"}) == 10 << 2)
  733. assert(run(function () return 1 << a end, {"shl"}) == 1 << 10)
  734. assert(run(function () return 2 ~ a end, {"bxor"}) == 2 ~ 10)
  735. assert(run(function () return a..b end, {"concat"}) == "1012")
  736. assert(run(function() return a .. b .. c .. a end,
  737. {"concat", "concat", "concat"}) == "1012hello10")
  738. assert(run(function() return "a" .. "b" .. a .. "c" .. c .. b .. "x" end,
  739. {"concat", "concat", "concat"}) == "ab10chello12x")
  740. do -- a few more tests for comparison operators
  741. local mt1 = {
  742. __le = function (a,b)
  743. coroutine.yield(10)
  744. return (val(a) <= val(b))
  745. end,
  746. __lt = function (a,b)
  747. coroutine.yield(10)
  748. return val(a) < val(b)
  749. end,
  750. }
  751. local mt2 = { __lt = mt1.__lt, __le = mt1.__le }
  752. local function run (f)
  753. local co = coroutine.wrap(f)
  754. local res
  755. repeat
  756. res = co()
  757. until res ~= 10
  758. return res
  759. end
  760. local function test ()
  761. local a1 = setmetatable({x=1}, mt1)
  762. local a2 = setmetatable({x=2}, mt2)
  763. assert(a1 < a2)
  764. assert(a1 <= a2)
  765. assert(1 < a2)
  766. assert(1 <= a2)
  767. assert(2 > a1)
  768. assert(2 >= a2)
  769. return true
  770. end
  771. run(test)
  772. end
  773. assert(run(function ()
  774. a.BB = print
  775. return a.BB
  776. end, {"nidx", "idx"}) == print)
  777. -- getuptable & setuptable
  778. do local _ENV = _ENV
  779. f = function () AAA = BBB + 1; return AAA end
  780. end
  781. local g = new(10); g.k.BBB = 10;
  782. debug.setupvalue(f, 1, g)
  783. assert(run(f, {"idx", "nidx", "idx"}) == 11)
  784. assert(g.k.AAA == 11)
  785. print"+"
  786. print"testing yields inside 'for' iterators"
  787. local f = function (s, i)
  788. if i%2 == 0 then coroutine.yield(nil, "for") end
  789. if i < s then return i + 1 end
  790. end
  791. assert(run(function ()
  792. local s = 0
  793. for i in f, 4, 0 do s = s + i end
  794. return s
  795. end, {"for", "for", "for"}) == 10)
  796. -- tests for coroutine API
  797. if T==nil then
  798. (Message or print)('\n >>> testC not active: skipping coroutine API tests <<<\n')
  799. print "OK"; return
  800. end
  801. print('testing coroutine API')
  802. local function apico (...)
  803. local x = {...}
  804. return coroutine.wrap(function ()
  805. return T.testC(table.unpack(x))
  806. end)
  807. end
  808. local a = {apico(
  809. [[
  810. pushstring errorcode
  811. pcallk 1 0 2;
  812. invalid command (should not arrive here)
  813. ]],
  814. [[return *]],
  815. "stackmark",
  816. error
  817. )()}
  818. assert(#a == 4 and
  819. a[3] == "stackmark" and
  820. a[4] == "errorcode" and
  821. _G.status == "ERRRUN" and
  822. _G.ctx == 2) -- 'ctx' to pcallk
  823. local co = apico(
  824. "pushvalue 2; pushnum 10; pcallk 1 2 3; invalid command;",
  825. coroutine.yield,
  826. "getglobal status; getglobal ctx; pushvalue 2; pushstring a; pcallk 1 0 4; invalid command",
  827. "getglobal status; getglobal ctx; return *")
  828. assert(co() == 10)
  829. assert(co(20, 30) == 'a')
  830. a = {co()}
  831. assert(#a == 10 and
  832. a[2] == coroutine.yield and
  833. a[5] == 20 and a[6] == 30 and
  834. a[7] == "YIELD" and a[8] == 3 and
  835. a[9] == "YIELD" and a[10] == 4)
  836. assert(not pcall(co)) -- coroutine is dead now
  837. f = T.makeCfunc("pushnum 3; pushnum 5; yield 1;")
  838. co = coroutine.wrap(function ()
  839. assert(f() == 23); assert(f() == 23); return 10
  840. end)
  841. assert(co(23,16) == 5)
  842. assert(co(23,16) == 5)
  843. assert(co(23,16) == 10)
  844. -- testing coroutines with C bodies
  845. f = T.makeCfunc([[
  846. pushnum 102
  847. yieldk 1 U2
  848. cannot be here!
  849. ]],
  850. [[ # continuation
  851. pushvalue U3 # accessing upvalues inside a continuation
  852. pushvalue U4
  853. return *
  854. ]], 23, "huu")
  855. x = coroutine.wrap(f)
  856. assert(x() == 102)
  857. eqtab({x()}, {23, "huu"})
  858. f = T.makeCfunc[[pushstring 'a'; pushnum 102; yield 2; ]]
  859. a, b, c, d = T.testC([[newthread; pushvalue 2; xmove 0 3 1; resume 3 0;
  860. pushstatus; xmove 3 0 0; resume 3 0; pushstatus;
  861. return 4; ]], f)
  862. assert(a == 'YIELD' and b == 'a' and c == 102 and d == 'OK')
  863. -- testing chain of suspendable C calls
  864. local count = 3 -- number of levels
  865. f = T.makeCfunc([[
  866. remove 1; # remove argument
  867. pushvalue U3; # get selection function
  868. call 0 1; # call it (result is 'f' or 'yield')
  869. pushstring hello # single argument for selected function
  870. pushupvalueindex 2; # index of continuation program
  871. callk 1 -1 .; # call selected function
  872. errorerror # should never arrive here
  873. ]],
  874. [[
  875. # continuation program
  876. pushnum 34 # return value
  877. return * # return all results
  878. ]],
  879. function () -- selection function
  880. count = count - 1
  881. if count == 0 then return coroutine.yield
  882. else return f
  883. end
  884. end
  885. )
  886. co = coroutine.wrap(function () return f(nil) end)
  887. assert(co() == "hello") -- argument to 'yield'
  888. a = {co()}
  889. -- three '34's (one from each pending C call)
  890. assert(#a == 3 and a[1] == a[2] and a[2] == a[3] and a[3] == 34)
  891. -- testing yields with continuations
  892. local y
  893. co = coroutine.wrap(function (...) return
  894. T.testC([[ # initial function
  895. yieldk 1 2
  896. cannot be here!
  897. ]],
  898. [[ # 1st continuation
  899. yieldk 0 3
  900. cannot be here!
  901. ]],
  902. [[ # 2nd continuation
  903. yieldk 0 4
  904. cannot be here!
  905. ]],
  906. [[ # 3th continuation
  907. pushvalue 6 # function which is last arg. to 'testC' here
  908. pushnum 10; pushnum 20;
  909. pcall 2 0 0 # call should throw an error and return to next line
  910. pop 1 # remove error message
  911. pushvalue 6
  912. getglobal status; getglobal ctx
  913. pcallk 2 2 5 # call should throw an error and jump to continuation
  914. cannot be here!
  915. ]],
  916. [[ # 4th (and last) continuation
  917. return *
  918. ]],
  919. -- function called by 3th continuation
  920. function (a,b) x=a; y=b; error("errmsg") end,
  921. ...
  922. )
  923. end)
  924. local a = {co(3,4,6)}
  925. assert(a[1] == 6 and a[2] == undef)
  926. a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 2)
  927. a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 3)
  928. a = {co(7,8)};
  929. -- original arguments
  930. assert(type(a[1]) == 'string' and type(a[2]) == 'string' and
  931. type(a[3]) == 'string' and type(a[4]) == 'string' and
  932. type(a[5]) == 'string' and type(a[6]) == 'function')
  933. -- arguments left from fist resume
  934. assert(a[7] == 3 and a[8] == 4)
  935. -- arguments to last resume
  936. assert(a[9] == 7 and a[10] == 8)
  937. -- error message and nothing more
  938. assert(a[11]:find("errmsg") and #a == 11)
  939. -- check arguments to pcallk
  940. assert(x == "YIELD" and y == 4)
  941. assert(not pcall(co)) -- coroutine should be dead
  942. _G.ctx = nil
  943. _G.status = nil
  944. -- bug in nCcalls
  945. local co = coroutine.wrap(function ()
  946. local a = {pcall(pcall,pcall,pcall,pcall,pcall,pcall,pcall,error,"hi")}
  947. return pcall(assert, table.unpack(a))
  948. end)
  949. local a = {co()}
  950. assert(a[10] == "hi")
  951. print'OK'