locals.lua 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. -- $Id: testes/locals.lua $
  2. -- See Copyright Notice in file all.lua
  3. print('testing local variables and environments')
  4. local debug = require"debug"
  5. local tracegc = require"tracegc"
  6. -- bug in 5.1:
  7. local function f(x) x = nil; return x end
  8. assert(f(10) == nil)
  9. local function f() local x; return x end
  10. assert(f(10) == nil)
  11. local function f(x) x = nil; local y; return x, y end
  12. assert(f(10) == nil and select(2, f(20)) == nil)
  13. do
  14. local i = 10
  15. do local i = 100; assert(i==100) end
  16. do local i = 1000; assert(i==1000) end
  17. assert(i == 10)
  18. if i ~= 10 then
  19. local i = 20
  20. else
  21. local i = 30
  22. assert(i == 30)
  23. end
  24. end
  25. f = nil
  26. local f
  27. x = 1
  28. a = nil
  29. load('local a = {}')()
  30. assert(a == nil)
  31. function f (a)
  32. local _1, _2, _3, _4, _5
  33. local _6, _7, _8, _9, _10
  34. local x = 3
  35. local b = a
  36. local c,d = a,b
  37. if (d == b) then
  38. local x = 'q'
  39. x = b
  40. assert(x == 2)
  41. else
  42. assert(nil)
  43. end
  44. assert(x == 3)
  45. local f = 10
  46. end
  47. local b=10
  48. local a; repeat local b; a,b=1,2; assert(a+1==b); until a+b==3
  49. assert(x == 1)
  50. f(2)
  51. assert(type(f) == 'function')
  52. local function getenv (f)
  53. local a,b = debug.getupvalue(f, 1)
  54. assert(a == '_ENV')
  55. return b
  56. end
  57. -- test for global table of loaded chunks
  58. assert(getenv(load"a=3") == _G)
  59. local c = {}; local f = load("a = 3", nil, nil, c)
  60. assert(getenv(f) == c)
  61. assert(c.a == nil)
  62. f()
  63. assert(c.a == 3)
  64. -- old test for limits for special instructions
  65. do
  66. local i = 2
  67. local p = 4 -- p == 2^i
  68. repeat
  69. for j=-3,3 do
  70. assert(load(string.format([[local a=%s;
  71. a=a+%s;
  72. assert(a ==2^%s)]], j, p-j, i), '')) ()
  73. assert(load(string.format([[local a=%s;
  74. a=a-%s;
  75. assert(a==-2^%s)]], -j, p-j, i), '')) ()
  76. assert(load(string.format([[local a,b=0,%s;
  77. a=b-%s;
  78. assert(a==-2^%s)]], -j, p-j, i), '')) ()
  79. end
  80. p = 2 * p; i = i + 1
  81. until p <= 0
  82. end
  83. print'+'
  84. if rawget(_G, "T") then
  85. -- testing clearing of dead elements from tables
  86. collectgarbage("stop") -- stop GC
  87. local a = {[{}] = 4, [3] = 0, alo = 1,
  88. a1234567890123456789012345678901234567890 = 10}
  89. local t = T.querytab(a)
  90. for k,_ in pairs(a) do a[k] = undef end
  91. collectgarbage() -- restore GC and collect dead fields in 'a'
  92. for i=0,t-1 do
  93. local k = querytab(a, i)
  94. assert(k == nil or type(k) == 'number' or k == 'alo')
  95. end
  96. -- testing allocation errors during table insertions
  97. local a = {}
  98. local function additems ()
  99. a.x = true; a.y = true; a.z = true
  100. a[1] = true
  101. a[2] = true
  102. end
  103. for i = 1, math.huge do
  104. T.alloccount(i)
  105. local st, msg = pcall(additems)
  106. T.alloccount()
  107. local count = 0
  108. for k, v in pairs(a) do
  109. assert(a[k] == v)
  110. count = count + 1
  111. end
  112. if st then assert(count == 5); break end
  113. end
  114. end
  115. -- testing lexical environments
  116. assert(_ENV == _G)
  117. do
  118. local dummy
  119. local _ENV = (function (...) return ... end)(_G, dummy) -- {
  120. do local _ENV = {assert=assert}; assert(true) end
  121. mt = {_G = _G}
  122. local foo,x
  123. A = false -- "declare" A
  124. do local _ENV = mt
  125. function foo (x)
  126. A = x
  127. do local _ENV = _G; A = 1000 end
  128. return function (x) return A .. x end
  129. end
  130. end
  131. assert(getenv(foo) == mt)
  132. x = foo('hi'); assert(mt.A == 'hi' and A == 1000)
  133. assert(x('*') == mt.A .. '*')
  134. do local _ENV = {assert=assert, A=10};
  135. do local _ENV = {assert=assert, A=20};
  136. assert(A==20);x=A
  137. end
  138. assert(A==10 and x==20)
  139. end
  140. assert(x==20)
  141. do -- constants
  142. local a<const>, b, c<const> = 10, 20, 30
  143. b = a + c + b -- 'b' is not constant
  144. assert(a == 10 and b == 60 and c == 30)
  145. local function checkro (name, code)
  146. local st, msg = load(code)
  147. local gab = string.format("attempt to assign to const variable '%s'", name)
  148. assert(not st and string.find(msg, gab))
  149. end
  150. checkro("y", "local x, y <const>, z = 10, 20, 30; x = 11; y = 12")
  151. checkro("x", "local x <const>, y, z <const> = 10, 20, 30; x = 11")
  152. checkro("z", "local x <const>, y, z <const> = 10, 20, 30; y = 10; z = 11")
  153. checkro("z", [[
  154. local a, z <const>, b = 10;
  155. function foo() a = 20; z = 32; end
  156. ]])
  157. checkro("var1", [[
  158. local a, var1 <const> = 10;
  159. function foo() a = 20; z = function () var1 = 12; end end
  160. ]])
  161. end
  162. print"testing to-be-closed variables"
  163. local function stack(n) n = ((n == 0) or stack(n - 1)) end
  164. local function func2close (f, x, y)
  165. local obj = setmetatable({}, {__close = f})
  166. if x then
  167. return x, obj, y
  168. else
  169. return obj
  170. end
  171. end
  172. do
  173. local a = {}
  174. do
  175. local b <close> = false -- not to be closed
  176. local x <close> = setmetatable({"x"}, {__close = function (self)
  177. a[#a + 1] = self[1] end})
  178. local w, y <close>, z = func2close(function (self, err)
  179. assert(err == nil); a[#a + 1] = "y"
  180. end, 10, 20)
  181. local c <close> = nil -- not to be closed
  182. a[#a + 1] = "in"
  183. assert(w == 10 and z == 20)
  184. end
  185. a[#a + 1] = "out"
  186. assert(a[1] == "in" and a[2] == "y" and a[3] == "x" and a[4] == "out")
  187. end
  188. do
  189. local X = false
  190. local x, closescope = func2close(function (_, msg)
  191. stack(10);
  192. assert(msg == nil)
  193. X = true
  194. end, 100)
  195. assert(x == 100); x = 101; -- 'x' is not read-only
  196. -- closing functions do not corrupt returning values
  197. local function foo (x)
  198. local _ <close> = closescope
  199. return x, X, 23
  200. end
  201. local a, b, c = foo(1.5)
  202. assert(a == 1.5 and b == false and c == 23 and X == true)
  203. X = false
  204. foo = function (x)
  205. local _<close> = func2close(function (_, msg)
  206. -- without errors, enclosing function should be still active when
  207. -- __close is called
  208. assert(debug.getinfo(2).name == "foo")
  209. assert(msg == nil)
  210. end)
  211. local _<close> = closescope
  212. local y = 15
  213. return y
  214. end
  215. assert(foo() == 15 and X == true)
  216. X = false
  217. foo = function ()
  218. local x <close> = closescope
  219. return x
  220. end
  221. assert(foo() == closescope and X == true)
  222. end
  223. -- testing to-be-closed x compile-time constants
  224. -- (there were some bugs here in Lua 5.4-rc3, due to a confusion
  225. -- between compile levels and stack levels of variables)
  226. do
  227. local flag = false
  228. local x = setmetatable({},
  229. {__close = function() assert(flag == false); flag = true end})
  230. local y <const> = nil
  231. local z <const> = nil
  232. do
  233. local a <close> = x
  234. end
  235. assert(flag) -- 'x' must be closed here
  236. end
  237. do
  238. -- similar problem, but with implicit close in for loops
  239. local flag = false
  240. local x = setmetatable({},
  241. {__close = function () assert(flag == false); flag = true end})
  242. -- return an empty iterator, nil, nil, and 'x' to be closed
  243. local function a ()
  244. return (function () return nil end), nil, nil, x
  245. end
  246. local v <const> = 1
  247. local w <const> = 1
  248. local x <const> = 1
  249. local y <const> = 1
  250. local z <const> = 1
  251. for k in a() do
  252. a = k
  253. end -- ending the loop must close 'x'
  254. assert(flag) -- 'x' must be closed here
  255. end
  256. do
  257. -- calls cannot be tail in the scope of to-be-closed variables
  258. local X, Y
  259. local function foo ()
  260. local _ <close> = func2close(function () Y = 10 end)
  261. assert(X == true and Y == nil) -- 'X' not closed yet
  262. return 1,2,3
  263. end
  264. local function bar ()
  265. local _ <close> = func2close(function () X = false end)
  266. X = true
  267. do
  268. return foo() -- not a tail call!
  269. end
  270. end
  271. local a, b, c, d = bar()
  272. assert(a == 1 and b == 2 and c == 3 and X == false and Y == 10 and d == nil)
  273. end
  274. do print("testing errors in __close")
  275. -- original error is in __close
  276. local function foo ()
  277. local x <close> =
  278. func2close(function (self, msg)
  279. assert(string.find(msg, "@y"))
  280. error("@x")
  281. end)
  282. local x1 <close> =
  283. func2close(function (self, msg)
  284. assert(string.find(msg, "@y"))
  285. end)
  286. local gc <close> = func2close(function () collectgarbage() end)
  287. local y <close> =
  288. func2close(function (self, msg)
  289. assert(string.find(msg, "@z")) -- error in 'z'
  290. error("@y")
  291. end)
  292. local z <close> =
  293. func2close(function (self, msg)
  294. assert(msg == nil)
  295. error("@z")
  296. end)
  297. return 200
  298. end
  299. local stat, msg = pcall(foo, false)
  300. assert(string.find(msg, "@x"))
  301. -- original error not in __close
  302. local function foo ()
  303. local x <close> =
  304. func2close(function (self, msg)
  305. -- after error, 'foo' was discarded, so caller now
  306. -- must be 'pcall'
  307. assert(debug.getinfo(2).name == "pcall")
  308. assert(string.find(msg, "@x1"))
  309. end)
  310. local x1 <close> =
  311. func2close(function (self, msg)
  312. assert(debug.getinfo(2).name == "pcall")
  313. assert(string.find(msg, "@y"))
  314. error("@x1")
  315. end)
  316. local gc <close> = func2close(function () collectgarbage() end)
  317. local y <close> =
  318. func2close(function (self, msg)
  319. assert(debug.getinfo(2).name == "pcall")
  320. assert(string.find(msg, "@z"))
  321. error("@y")
  322. end)
  323. local first = true
  324. local z <close> =
  325. func2close(function (self, msg)
  326. assert(debug.getinfo(2).name == "pcall")
  327. -- 'z' close is called once
  328. assert(first and msg == 4)
  329. first = false
  330. error("@z")
  331. end)
  332. error(4) -- original error
  333. end
  334. local stat, msg = pcall(foo, true)
  335. assert(string.find(msg, "@x1"))
  336. -- error leaving a block
  337. local function foo (...)
  338. do
  339. local x1 <close> =
  340. func2close(function (self, msg)
  341. assert(string.find(msg, "@X"))
  342. error("@Y")
  343. end)
  344. local x123 <close> =
  345. func2close(function (_, msg)
  346. assert(msg == nil)
  347. error("@X")
  348. end)
  349. end
  350. os.exit(false) -- should not run
  351. end
  352. local st, msg = xpcall(foo, debug.traceback)
  353. assert(string.match(msg, "^[^ ]* @Y"))
  354. -- error in toclose in vararg function
  355. local function foo (...)
  356. local x123 <close> = func2close(function () error("@x123") end)
  357. end
  358. local st, msg = xpcall(foo, debug.traceback)
  359. assert(string.match(msg, "^[^ ]* @x123"))
  360. assert(string.find(msg, "in metamethod 'close'"))
  361. end
  362. do -- errors due to non-closable values
  363. local function foo ()
  364. local x <close> = {}
  365. os.exit(false) -- should not run
  366. end
  367. local stat, msg = pcall(foo)
  368. assert(not stat and
  369. string.find(msg, "variable 'x' got a non%-closable value"))
  370. local function foo ()
  371. local xyz <close> = setmetatable({}, {__close = print})
  372. getmetatable(xyz).__close = nil -- remove metamethod
  373. end
  374. local stat, msg = pcall(foo)
  375. assert(not stat and string.find(msg, "metamethod 'close'"))
  376. local function foo ()
  377. local a1 <close> = func2close(function (_, msg)
  378. assert(string.find(msg, "number value"))
  379. error(12)
  380. end)
  381. local a2 <close> = setmetatable({}, {__close = print})
  382. local a3 <close> = func2close(function (_, msg)
  383. assert(msg == nil)
  384. error(123)
  385. end)
  386. getmetatable(a2).__close = 4 -- invalidate metamethod
  387. end
  388. local stat, msg = pcall(foo)
  389. assert(not stat and msg == 12)
  390. end
  391. do -- tbc inside close methods
  392. local track = {}
  393. local function foo ()
  394. local x <close> = func2close(function ()
  395. local xx <close> = func2close(function (_, msg)
  396. assert(msg == nil)
  397. track[#track + 1] = "xx"
  398. end)
  399. track[#track + 1] = "x"
  400. end)
  401. track[#track + 1] = "foo"
  402. return 20, 30, 40
  403. end
  404. local a, b, c, d = foo()
  405. assert(a == 20 and b == 30 and c == 40 and d == nil)
  406. assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx")
  407. -- again, with errors
  408. local track = {}
  409. local function foo ()
  410. local x0 <close> = func2close(function (_, msg)
  411. assert(msg == 202)
  412. track[#track + 1] = "x0"
  413. end)
  414. local x <close> = func2close(function ()
  415. local xx <close> = func2close(function (_, msg)
  416. assert(msg == 101)
  417. track[#track + 1] = "xx"
  418. error(202)
  419. end)
  420. track[#track + 1] = "x"
  421. error(101)
  422. end)
  423. track[#track + 1] = "foo"
  424. return 20, 30, 40
  425. end
  426. local st, msg = pcall(foo)
  427. assert(not st and msg == 202)
  428. assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx" and
  429. track[4] == "x0")
  430. end
  431. local function checktable (t1, t2)
  432. assert(#t1 == #t2)
  433. for i = 1, #t1 do
  434. assert(t1[i] == t2[i])
  435. end
  436. end
  437. do -- test for tbc variable high in the stack
  438. -- function to force a stack overflow
  439. local function overflow (n)
  440. overflow(n + 1)
  441. end
  442. -- error handler will create tbc variable handling a stack overflow,
  443. -- high in the stack
  444. local function errorh (m)
  445. assert(string.find(m, "stack overflow"))
  446. local x <close> = func2close(function (o) o[1] = 10 end)
  447. return x
  448. end
  449. local flag
  450. local st, obj
  451. -- run test in a coroutine so as not to swell the main stack
  452. local co = coroutine.wrap(function ()
  453. -- tbc variable down the stack
  454. local y <close> = func2close(function (obj, msg)
  455. assert(msg == nil)
  456. obj[1] = 100
  457. flag = obj
  458. end)
  459. tracegc.stop()
  460. st, obj = xpcall(overflow, errorh, 0)
  461. tracegc.start()
  462. end)
  463. co()
  464. assert(not st and obj[1] == 10 and flag[1] == 100)
  465. end
  466. if rawget(_G, "T") then
  467. -- memory error inside closing function
  468. local function foo ()
  469. local y <close> = func2close(function () T.alloccount() end)
  470. local x <close> = setmetatable({}, {__close = function ()
  471. T.alloccount(0); local x = {} -- force a memory error
  472. end})
  473. error(1000) -- common error inside the function's body
  474. end
  475. stack(5) -- ensure a minimal number of CI structures
  476. -- despite memory error, 'y' will be executed and
  477. -- memory limit will be lifted
  478. local _, msg = pcall(foo)
  479. assert(msg == "not enough memory")
  480. local closemsg
  481. local close = func2close(function (self, msg)
  482. T.alloccount()
  483. closemsg = msg
  484. end)
  485. -- set a memory limit and return a closing object to remove the limit
  486. local function enter (count)
  487. stack(10) -- reserve some stack space
  488. T.alloccount(count)
  489. closemsg = nil
  490. return close
  491. end
  492. local function test ()
  493. local x <close> = enter(0) -- set a memory limit
  494. local y = {} -- raise a memory error
  495. end
  496. local _, msg = pcall(test)
  497. assert(msg == "not enough memory" and closemsg == "not enough memory")
  498. -- repeat test with extra closing upvalues
  499. local function test ()
  500. local xxx <close> = func2close(function (self, msg)
  501. assert(msg == "not enough memory");
  502. error(1000) -- raise another error
  503. end)
  504. local xx <close> = func2close(function (self, msg)
  505. assert(msg == "not enough memory");
  506. end)
  507. local x <close> = enter(0) -- set a memory limit
  508. local y = {} -- raise a memory error
  509. end
  510. local _, msg = pcall(test)
  511. assert(msg == 1000 and closemsg == "not enough memory")
  512. do -- testing 'toclose' in C string buffer
  513. collectgarbage()
  514. local s = string.rep('a', 10000) -- large string
  515. local m = T.totalmem()
  516. collectgarbage("stop")
  517. s = string.upper(s) -- allocate buffer + new string (10K each)
  518. -- ensure buffer was deallocated
  519. assert(T.totalmem() - m <= 11000)
  520. collectgarbage("restart")
  521. end
  522. do -- now some tests for freeing buffer in case of errors
  523. local lim = 10000 -- some size larger than the static buffer
  524. local extra = 2000 -- some extra memory (for callinfo, etc.)
  525. local s = string.rep("a", lim)
  526. -- concat this table needs two buffer resizes (one for each 's')
  527. local a = {s, s}
  528. collectgarbage(); collectgarbage()
  529. m = T.totalmem()
  530. collectgarbage("stop")
  531. -- error in the first buffer allocation
  532. T. totalmem(m + extra)
  533. assert(not pcall(table.concat, a))
  534. -- first buffer was not even allocated
  535. assert(T.totalmem() - m <= extra)
  536. -- error in the second buffer allocation
  537. T. totalmem(m + lim + extra)
  538. assert(not pcall(table.concat, a))
  539. -- first buffer was released by 'toclose'
  540. assert(T.totalmem() - m <= extra)
  541. -- error in creation of final string
  542. T.totalmem(m + 2 * lim + extra)
  543. assert(not pcall(table.concat, a))
  544. -- second buffer was released by 'toclose'
  545. assert(T.totalmem() - m <= extra)
  546. -- userdata, buffer, buffer, final string
  547. T.totalmem(m + 4*lim + extra)
  548. assert(#table.concat(a) == 2*lim)
  549. T.totalmem(0) -- remove memory limit
  550. collectgarbage("restart")
  551. print'+'
  552. end
  553. do
  554. -- '__close' vs. return hooks in C functions
  555. local trace = {}
  556. local function hook (event)
  557. trace[#trace + 1] = event .. " " .. (debug.getinfo(2).name or "?")
  558. end
  559. -- create tbc variables to be used by C function
  560. local x = func2close(function (_,msg)
  561. trace[#trace + 1] = "x"
  562. end)
  563. local y = func2close(function (_,msg)
  564. trace[#trace + 1] = "y"
  565. end)
  566. debug.sethook(hook, "r")
  567. local t = {T.testC([[
  568. toclose 2 # x
  569. pushnum 10
  570. pushint 20
  571. toclose 3 # y
  572. return 2
  573. ]], x, y)}
  574. debug.sethook()
  575. -- hooks ran before return hook from 'testC'
  576. checktable(trace,
  577. {"return sethook", "y", "return ?", "x", "return ?", "return testC"})
  578. -- results are correct
  579. checktable(t, {10, 20})
  580. end
  581. end
  582. do -- '__close' vs. return hooks in Lua functions
  583. local trace = {}
  584. local function hook (event)
  585. trace[#trace + 1] = event .. " " .. debug.getinfo(2).name
  586. end
  587. local function foo (...)
  588. local x <close> = func2close(function (_,msg)
  589. trace[#trace + 1] = "x"
  590. end)
  591. local y <close> = func2close(function (_,msg)
  592. debug.sethook(hook, "r")
  593. end)
  594. return ...
  595. end
  596. local t = {foo(10,20,30)}
  597. debug.sethook()
  598. checktable(t, {10, 20, 30})
  599. checktable(trace,
  600. {"return sethook", "return close", "x", "return close", "return foo"})
  601. end
  602. print "to-be-closed variables in coroutines"
  603. do
  604. -- yielding inside closing metamethods
  605. local trace = {}
  606. local co = coroutine.wrap(function ()
  607. trace[#trace + 1] = "nowX"
  608. -- will be closed after 'y'
  609. local x <close> = func2close(function (_, msg)
  610. assert(msg == nil)
  611. trace[#trace + 1] = "x1"
  612. coroutine.yield("x")
  613. trace[#trace + 1] = "x2"
  614. end)
  615. return pcall(function ()
  616. do -- 'z' will be closed first
  617. local z <close> = func2close(function (_, msg)
  618. assert(msg == nil)
  619. trace[#trace + 1] = "z1"
  620. coroutine.yield("z")
  621. trace[#trace + 1] = "z2"
  622. end)
  623. end
  624. trace[#trace + 1] = "nowY"
  625. -- will be closed after 'z'
  626. local y <close> = func2close(function(_, msg)
  627. assert(msg == nil)
  628. trace[#trace + 1] = "y1"
  629. coroutine.yield("y")
  630. trace[#trace + 1] = "y2"
  631. end)
  632. return 10, 20, 30
  633. end)
  634. end)
  635. assert(co() == "z")
  636. assert(co() == "y")
  637. assert(co() == "x")
  638. checktable({co()}, {true, 10, 20, 30})
  639. checktable(trace, {"nowX", "z1", "z2", "nowY", "y1", "y2", "x1", "x2"})
  640. end
  641. do
  642. -- yielding inside closing metamethods after an error
  643. local co = coroutine.wrap(function ()
  644. local function foo (err)
  645. local z <close> = func2close(function(_, msg)
  646. assert(msg == nil or msg == err + 20)
  647. coroutine.yield("z")
  648. return 100, 200
  649. end)
  650. local y <close> = func2close(function(_, msg)
  651. -- still gets the original error (if any)
  652. assert(msg == err or (msg == nil and err == 1))
  653. coroutine.yield("y")
  654. if err then error(err + 20) end -- creates or changes the error
  655. end)
  656. local x <close> = func2close(function(_, msg)
  657. assert(msg == err or (msg == nil and err == 1))
  658. coroutine.yield("x")
  659. return 100, 200
  660. end)
  661. if err == 10 then error(err) else return 10, 20 end
  662. end
  663. coroutine.yield(pcall(foo, nil)) -- no error
  664. coroutine.yield(pcall(foo, 1)) -- error in __close
  665. return pcall(foo, 10) -- 'foo' will raise an error
  666. end)
  667. local a, b = co() -- first foo: no error
  668. assert(a == "x" and b == nil) -- yields inside 'x'; Ok
  669. a, b = co()
  670. assert(a == "y" and b == nil) -- yields inside 'y'; Ok
  671. a, b = co()
  672. assert(a == "z" and b == nil) -- yields inside 'z'; Ok
  673. local a, b, c = co()
  674. assert(a and b == 10 and c == 20) -- returns from 'pcall(foo, nil)'
  675. local a, b = co() -- second foo: error in __close
  676. assert(a == "x" and b == nil) -- yields inside 'x'; Ok
  677. a, b = co()
  678. assert(a == "y" and b == nil) -- yields inside 'y'; Ok
  679. a, b = co()
  680. assert(a == "z" and b == nil) -- yields inside 'z'; Ok
  681. local st, msg = co() -- reports the error in 'y'
  682. assert(not st and msg == 21)
  683. local a, b = co() -- third foo: error in function body
  684. assert(a == "x" and b == nil) -- yields inside 'x'; Ok
  685. a, b = co()
  686. assert(a == "y" and b == nil) -- yields inside 'y'; Ok
  687. a, b = co()
  688. assert(a == "z" and b == nil) -- yields inside 'z'; Ok
  689. local st, msg = co() -- gets final error
  690. assert(not st and msg == 10 + 20)
  691. end
  692. do
  693. -- an error in a wrapped coroutine closes variables
  694. local x = false
  695. local y = false
  696. local co = coroutine.wrap(function ()
  697. local xv <close> = func2close(function () x = true end)
  698. do
  699. local yv <close> = func2close(function () y = true end)
  700. coroutine.yield(100) -- yield doesn't close variable
  701. end
  702. coroutine.yield(200) -- yield doesn't close variable
  703. error(23) -- error does
  704. end)
  705. local b = co()
  706. assert(b == 100 and not x and not y)
  707. b = co()
  708. assert(b == 200 and not x and y)
  709. local a, b = pcall(co)
  710. assert(not a and b == 23 and x and y)
  711. end
  712. do
  713. -- error in a wrapped coroutine raising errors when closing a variable
  714. local x = 0
  715. local co = coroutine.wrap(function ()
  716. local xx <close> = func2close(function (_, msg)
  717. x = x + 1;
  718. assert(string.find(msg, "@XXX"))
  719. error("@YYY")
  720. end)
  721. local xv <close> = func2close(function () x = x + 1; error("@XXX") end)
  722. coroutine.yield(100)
  723. error(200)
  724. end)
  725. assert(co() == 100); assert(x == 0)
  726. local st, msg = pcall(co); assert(x == 2)
  727. assert(not st and string.find(msg, "@YYY")) -- should get error raised
  728. local x = 0
  729. local y = 0
  730. co = coroutine.wrap(function ()
  731. local xx <close> = func2close(function (_, err)
  732. y = y + 1;
  733. assert(string.find(err, "XXX"))
  734. error("YYY")
  735. end)
  736. local xv <close> = func2close(function ()
  737. x = x + 1; error("XXX")
  738. end)
  739. coroutine.yield(100)
  740. return 200
  741. end)
  742. assert(co() == 100); assert(x == 0)
  743. local st, msg = pcall(co)
  744. assert(x == 1 and y == 1)
  745. -- should get first error raised
  746. assert(not st and string.find(msg, "%w+%.%w+:%d+: YYY"))
  747. end
  748. -- a suspended coroutine should not close its variables when collected
  749. local co
  750. co = coroutine.wrap(function()
  751. -- should not run
  752. local x <close> = func2close(function () os.exit(false) end)
  753. co = nil
  754. coroutine.yield()
  755. end)
  756. co() -- start coroutine
  757. assert(co == nil) -- eventually it will be collected
  758. collectgarbage()
  759. if rawget(_G, "T") then
  760. print("to-be-closed variables x coroutines in C")
  761. do
  762. local token = 0
  763. local count = 0
  764. local f = T.makeCfunc[[
  765. toclose 1
  766. toclose 2
  767. return .
  768. ]]
  769. local obj = func2close(function (_, msg)
  770. count = count + 1
  771. token = coroutine.yield(count, token)
  772. end)
  773. local co = coroutine.wrap(f)
  774. local ct, res = co(obj, obj, 10, 20, 30, 3) -- will return 10, 20, 30
  775. -- initial token value, after closing 2nd obj
  776. assert(ct == 1 and res == 0)
  777. -- run until yield when closing 1st obj
  778. ct, res = co(100)
  779. assert(ct == 2 and res == 100)
  780. res = {co(200)} -- run until end
  781. assert(res[1] == 10 and res[2] == 20 and res[3] == 30 and res[4] == nil)
  782. assert(token == 200)
  783. end
  784. do
  785. local f = T.makeCfunc[[
  786. toclose 1
  787. return .
  788. ]]
  789. local obj = func2close(function ()
  790. local temp
  791. local x <close> = func2close(function ()
  792. coroutine.yield(temp)
  793. return 1,2,3 -- to be ignored
  794. end)
  795. temp = coroutine.yield("closing obj")
  796. return 1,2,3 -- to be ignored
  797. end)
  798. local co = coroutine.wrap(f)
  799. local res = co(obj, 10, 30, 1) -- will return only 30
  800. assert(res == "closing obj")
  801. res = co("closing x")
  802. assert(res == "closing x")
  803. res = {co()}
  804. assert(res[1] == 30 and res[2] == nil)
  805. end
  806. do
  807. -- still cannot yield inside 'closeslot'
  808. local f = T.makeCfunc[[
  809. toclose 1
  810. closeslot 1
  811. ]]
  812. local obj = func2close(coroutine.yield)
  813. local co = coroutine.create(f)
  814. local st, msg = coroutine.resume(co, obj)
  815. assert(not st and string.find(msg, "attempt to yield across"))
  816. -- nor outside a coroutine
  817. local f = T.makeCfunc[[
  818. toclose 1
  819. ]]
  820. local st, msg = pcall(f, obj)
  821. assert(not st and string.find(msg, "attempt to yield from outside"))
  822. end
  823. end
  824. -- to-be-closed variables in generic for loops
  825. do
  826. local numopen = 0
  827. local function open (x)
  828. numopen = numopen + 1
  829. return
  830. function () -- iteraction function
  831. x = x - 1
  832. if x > 0 then return x end
  833. end,
  834. nil, -- state
  835. nil, -- control variable
  836. func2close(function () numopen = numopen - 1 end) -- closing function
  837. end
  838. local s = 0
  839. for i in open(10) do
  840. s = s + i
  841. end
  842. assert(s == 45 and numopen == 0)
  843. local s = 0
  844. for i in open(10) do
  845. if i < 5 then break end
  846. s = s + i
  847. end
  848. assert(s == 35 and numopen == 0)
  849. local s = 0
  850. for i in open(10) do
  851. for j in open(10) do
  852. if i + j < 5 then goto endloop end
  853. s = s + i
  854. end
  855. end
  856. ::endloop::
  857. assert(s == 375 and numopen == 0)
  858. end
  859. print('OK')
  860. return 5,f
  861. end -- }