coroutine.lua 34 KB

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