coroutine.lua 33 KB

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