coroutine.lua 30 KB

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