coroutine.lua 27 KB

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