locals.lua 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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("foo", "local foo <const> = 10; function foo() end")
  154. checkro("foo", "local foo <const> = {}; function foo() end")
  155. checkro("z", [[
  156. local a, z <const>, b = 10;
  157. function foo() a = 20; z = 32; end
  158. ]])
  159. checkro("var1", [[
  160. local a, var1 <const> = 10;
  161. function foo() a = 20; z = function () var1 = 12; end end
  162. ]])
  163. end
  164. print"testing to-be-closed variables"
  165. local function stack(n) n = ((n == 0) or stack(n - 1)) end
  166. local function func2close (f, x, y)
  167. local obj = setmetatable({}, {__close = f})
  168. if x then
  169. return x, obj, y
  170. else
  171. return obj
  172. end
  173. end
  174. do
  175. local a = {}
  176. do
  177. local b <close> = false -- not to be closed
  178. local x <close> = setmetatable({"x"}, {__close = function (self)
  179. a[#a + 1] = self[1] end})
  180. local w, y <close>, z = func2close(function (self, err)
  181. assert(err == nil); a[#a + 1] = "y"
  182. end, 10, 20)
  183. local c <close> = nil -- not to be closed
  184. a[#a + 1] = "in"
  185. assert(w == 10 and z == 20)
  186. end
  187. a[#a + 1] = "out"
  188. assert(a[1] == "in" and a[2] == "y" and a[3] == "x" and a[4] == "out")
  189. end
  190. do
  191. local X = false
  192. local x, closescope = func2close(function (_, msg)
  193. stack(10);
  194. assert(msg == nil)
  195. X = true
  196. end, 100)
  197. assert(x == 100); x = 101; -- 'x' is not read-only
  198. -- closing functions do not corrupt returning values
  199. local function foo (x)
  200. local _ <close> = closescope
  201. return x, X, 23
  202. end
  203. local a, b, c = foo(1.5)
  204. assert(a == 1.5 and b == false and c == 23 and X == true)
  205. X = false
  206. foo = function (x)
  207. local _<close> = func2close(function (_, msg)
  208. -- without errors, enclosing function should be still active when
  209. -- __close is called
  210. assert(debug.getinfo(2).name == "foo")
  211. assert(msg == nil)
  212. end)
  213. local _<close> = closescope
  214. local y = 15
  215. return y
  216. end
  217. assert(foo() == 15 and X == true)
  218. X = false
  219. foo = function ()
  220. local x <close> = closescope
  221. return x
  222. end
  223. assert(foo() == closescope and X == true)
  224. end
  225. -- testing to-be-closed x compile-time constants
  226. -- (there were some bugs here in Lua 5.4-rc3, due to a confusion
  227. -- between compile levels and stack levels of variables)
  228. do
  229. local flag = false
  230. local x = setmetatable({},
  231. {__close = function() assert(flag == false); flag = true end})
  232. local y <const> = nil
  233. local z <const> = nil
  234. do
  235. local a <close> = x
  236. end
  237. assert(flag) -- 'x' must be closed here
  238. end
  239. do
  240. -- similar problem, but with implicit close in for loops
  241. local flag = false
  242. local x = setmetatable({},
  243. {__close = function () assert(flag == false); flag = true end})
  244. -- return an empty iterator, nil, nil, and 'x' to be closed
  245. local function a ()
  246. return (function () return nil end), nil, nil, x
  247. end
  248. local v <const> = 1
  249. local w <const> = 1
  250. local x <const> = 1
  251. local y <const> = 1
  252. local z <const> = 1
  253. for k in a() do
  254. a = k
  255. end -- ending the loop must close 'x'
  256. assert(flag) -- 'x' must be closed here
  257. end
  258. do
  259. -- calls cannot be tail in the scope of to-be-closed variables
  260. local X, Y
  261. local function foo ()
  262. local _ <close> = func2close(function () Y = 10 end)
  263. assert(X == true and Y == nil) -- 'X' not closed yet
  264. return 1,2,3
  265. end
  266. local function bar ()
  267. local _ <close> = func2close(function () X = false end)
  268. X = true
  269. do
  270. return foo() -- not a tail call!
  271. end
  272. end
  273. local a, b, c, d = bar()
  274. assert(a == 1 and b == 2 and c == 3 and X == false and Y == 10 and d == nil)
  275. end
  276. do
  277. -- bug in 5.4.3: previous condition (calls cannot be tail in the
  278. -- scope of to-be-closed variables) must be valid for tbc variables
  279. -- created by 'for' loops.
  280. local closed = false
  281. local function foo ()
  282. return function () return true end, 0, 0,
  283. func2close(function () closed = true end)
  284. end
  285. local function tail() return closed end
  286. local function foo1 ()
  287. for k in foo() do return tail() end
  288. end
  289. assert(foo1() == false)
  290. assert(closed == true)
  291. end
  292. do print("testing errors in __close")
  293. -- original error is in __close
  294. local function foo ()
  295. local x <close> =
  296. func2close(function (self, msg)
  297. assert(string.find(msg, "@y"))
  298. error("@x")
  299. end)
  300. local x1 <close> =
  301. func2close(function (self, msg)
  302. assert(string.find(msg, "@y"))
  303. end)
  304. local gc <close> = func2close(function () collectgarbage() end)
  305. local y <close> =
  306. func2close(function (self, msg)
  307. assert(string.find(msg, "@z")) -- error in 'z'
  308. error("@y")
  309. end)
  310. local z <close> =
  311. func2close(function (self, msg)
  312. assert(msg == nil)
  313. error("@z")
  314. end)
  315. return 200
  316. end
  317. local stat, msg = pcall(foo, false)
  318. assert(string.find(msg, "@x"))
  319. -- original error not in __close
  320. local function foo ()
  321. local x <close> =
  322. func2close(function (self, msg)
  323. -- after error, 'foo' was discarded, so caller now
  324. -- must be 'pcall'
  325. assert(debug.getinfo(2).name == "pcall")
  326. assert(string.find(msg, "@x1"))
  327. end)
  328. local x1 <close> =
  329. func2close(function (self, msg)
  330. assert(debug.getinfo(2).name == "pcall")
  331. assert(string.find(msg, "@y"))
  332. error("@x1")
  333. end)
  334. local gc <close> = func2close(function () collectgarbage() end)
  335. local y <close> =
  336. func2close(function (self, msg)
  337. assert(debug.getinfo(2).name == "pcall")
  338. assert(string.find(msg, "@z"))
  339. error("@y")
  340. end)
  341. local first = true
  342. local z <close> =
  343. func2close(function (self, msg)
  344. assert(debug.getinfo(2).name == "pcall")
  345. -- 'z' close is called once
  346. assert(first and msg == 4)
  347. first = false
  348. error("@z")
  349. end)
  350. error(4) -- original error
  351. end
  352. local stat, msg = pcall(foo, true)
  353. assert(string.find(msg, "@x1"))
  354. -- error leaving a block
  355. local function foo (...)
  356. do
  357. local x1 <close> =
  358. func2close(function (self, msg)
  359. assert(string.find(msg, "@X"))
  360. error("@Y")
  361. end)
  362. local x123 <close> =
  363. func2close(function (_, msg)
  364. assert(msg == nil)
  365. error("@X")
  366. end)
  367. end
  368. os.exit(false) -- should not run
  369. end
  370. local st, msg = xpcall(foo, debug.traceback)
  371. assert(string.match(msg, "^[^ ]* @Y"))
  372. -- error in toclose in vararg function
  373. local function foo (...)
  374. local x123 <close> = func2close(function () error("@x123") end)
  375. end
  376. local st, msg = xpcall(foo, debug.traceback)
  377. assert(string.match(msg, "^[^ ]* @x123"))
  378. assert(string.find(msg, "in metamethod 'close'"))
  379. end
  380. do -- errors due to non-closable values
  381. local function foo ()
  382. local x <close> = {}
  383. os.exit(false) -- should not run
  384. end
  385. local stat, msg = pcall(foo)
  386. assert(not stat and
  387. string.find(msg, "variable 'x' got a non%-closable value"))
  388. local function foo ()
  389. local xyz <close> = setmetatable({}, {__close = print})
  390. getmetatable(xyz).__close = nil -- remove metamethod
  391. end
  392. local stat, msg = pcall(foo)
  393. assert(not stat and string.find(msg, "metamethod 'close'"))
  394. local function foo ()
  395. local a1 <close> = func2close(function (_, msg)
  396. assert(string.find(msg, "number value"))
  397. error(12)
  398. end)
  399. local a2 <close> = setmetatable({}, {__close = print})
  400. local a3 <close> = func2close(function (_, msg)
  401. assert(msg == nil)
  402. error(123)
  403. end)
  404. getmetatable(a2).__close = 4 -- invalidate metamethod
  405. end
  406. local stat, msg = pcall(foo)
  407. assert(not stat and msg == 12)
  408. end
  409. do -- tbc inside close methods
  410. local track = {}
  411. local function foo ()
  412. local x <close> = func2close(function ()
  413. local xx <close> = func2close(function (_, msg)
  414. assert(msg == nil)
  415. track[#track + 1] = "xx"
  416. end)
  417. track[#track + 1] = "x"
  418. end)
  419. track[#track + 1] = "foo"
  420. return 20, 30, 40
  421. end
  422. local a, b, c, d = foo()
  423. assert(a == 20 and b == 30 and c == 40 and d == nil)
  424. assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx")
  425. -- again, with errors
  426. local track = {}
  427. local function foo ()
  428. local x0 <close> = func2close(function (_, msg)
  429. assert(msg == 202)
  430. track[#track + 1] = "x0"
  431. end)
  432. local x <close> = func2close(function ()
  433. local xx <close> = func2close(function (_, msg)
  434. assert(msg == 101)
  435. track[#track + 1] = "xx"
  436. error(202)
  437. end)
  438. track[#track + 1] = "x"
  439. error(101)
  440. end)
  441. track[#track + 1] = "foo"
  442. return 20, 30, 40
  443. end
  444. local st, msg = pcall(foo)
  445. assert(not st and msg == 202)
  446. assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx" and
  447. track[4] == "x0")
  448. end
  449. local function checktable (t1, t2)
  450. assert(#t1 == #t2)
  451. for i = 1, #t1 do
  452. assert(t1[i] == t2[i])
  453. end
  454. end
  455. do -- test for tbc variable high in the stack
  456. -- function to force a stack overflow
  457. local function overflow (n)
  458. overflow(n + 1)
  459. end
  460. -- error handler will create tbc variable handling a stack overflow,
  461. -- high in the stack
  462. local function errorh (m)
  463. assert(string.find(m, "stack overflow"))
  464. local x <close> = func2close(function (o) o[1] = 10 end)
  465. return x
  466. end
  467. local flag
  468. local st, obj
  469. -- run test in a coroutine so as not to swell the main stack
  470. local co = coroutine.wrap(function ()
  471. -- tbc variable down the stack
  472. local y <close> = func2close(function (obj, msg)
  473. assert(msg == nil)
  474. obj[1] = 100
  475. flag = obj
  476. end)
  477. tracegc.stop()
  478. st, obj = xpcall(overflow, errorh, 0)
  479. tracegc.start()
  480. end)
  481. co()
  482. assert(not st and obj[1] == 10 and flag[1] == 100)
  483. end
  484. if rawget(_G, "T") then
  485. -- memory error inside closing function
  486. local function foo ()
  487. local y <close> = func2close(function () T.alloccount() end)
  488. local x <close> = setmetatable({}, {__close = function ()
  489. T.alloccount(0); local x = {} -- force a memory error
  490. end})
  491. error(1000) -- common error inside the function's body
  492. end
  493. stack(5) -- ensure a minimal number of CI structures
  494. -- despite memory error, 'y' will be executed and
  495. -- memory limit will be lifted
  496. local _, msg = pcall(foo)
  497. assert(msg == "not enough memory")
  498. local closemsg
  499. local close = func2close(function (self, msg)
  500. T.alloccount()
  501. closemsg = msg
  502. end)
  503. -- set a memory limit and return a closing object to remove the limit
  504. local function enter (count)
  505. stack(10) -- reserve some stack space
  506. T.alloccount(count)
  507. closemsg = nil
  508. return close
  509. end
  510. local function test ()
  511. local x <close> = enter(0) -- set a memory limit
  512. local y = {} -- raise a memory error
  513. end
  514. local _, msg = pcall(test)
  515. assert(msg == "not enough memory" and closemsg == "not enough memory")
  516. -- repeat test with extra closing upvalues
  517. local function test ()
  518. local xxx <close> = func2close(function (self, msg)
  519. assert(msg == "not enough memory");
  520. error(1000) -- raise another error
  521. end)
  522. local xx <close> = func2close(function (self, msg)
  523. assert(msg == "not enough memory");
  524. end)
  525. local x <close> = enter(0) -- set a memory limit
  526. local y = {} -- raise a memory error
  527. end
  528. local _, msg = pcall(test)
  529. assert(msg == 1000 and closemsg == "not enough memory")
  530. do -- testing 'toclose' in C string buffer
  531. collectgarbage()
  532. local s = string.rep('a', 10000) -- large string
  533. local m = T.totalmem()
  534. collectgarbage("stop")
  535. s = string.upper(s) -- allocate buffer + new string (10K each)
  536. -- ensure buffer was deallocated
  537. assert(T.totalmem() - m <= 11000)
  538. collectgarbage("restart")
  539. end
  540. do -- now some tests for freeing buffer in case of errors
  541. local lim = 10000 -- some size larger than the static buffer
  542. local extra = 2000 -- some extra memory (for callinfo, etc.)
  543. local s = string.rep("a", lim)
  544. -- concat this table needs two buffer resizes (one for each 's')
  545. local a = {s, s}
  546. collectgarbage(); collectgarbage()
  547. m = T.totalmem()
  548. collectgarbage("stop")
  549. -- error in the first buffer allocation
  550. T. totalmem(m + extra)
  551. assert(not pcall(table.concat, a))
  552. -- first buffer was not even allocated
  553. assert(T.totalmem() - m <= extra)
  554. -- error in the second buffer allocation
  555. T. totalmem(m + lim + extra)
  556. assert(not pcall(table.concat, a))
  557. -- first buffer was released by 'toclose'
  558. assert(T.totalmem() - m <= extra)
  559. -- error in creation of final string
  560. T.totalmem(m + 2 * lim + extra)
  561. assert(not pcall(table.concat, a))
  562. -- second buffer was released by 'toclose'
  563. assert(T.totalmem() - m <= extra)
  564. -- userdata, buffer, buffer, final string
  565. T.totalmem(m + 4*lim + extra)
  566. assert(#table.concat(a) == 2*lim)
  567. T.totalmem(0) -- remove memory limit
  568. collectgarbage("restart")
  569. print'+'
  570. end
  571. do
  572. -- '__close' vs. return hooks in C functions
  573. local trace = {}
  574. local function hook (event)
  575. trace[#trace + 1] = event .. " " .. (debug.getinfo(2).name or "?")
  576. end
  577. -- create tbc variables to be used by C function
  578. local x = func2close(function (_,msg)
  579. trace[#trace + 1] = "x"
  580. end)
  581. local y = func2close(function (_,msg)
  582. trace[#trace + 1] = "y"
  583. end)
  584. debug.sethook(hook, "r")
  585. local t = {T.testC([[
  586. toclose 2 # x
  587. pushnum 10
  588. pushint 20
  589. toclose 3 # y
  590. return 2
  591. ]], x, y)}
  592. debug.sethook()
  593. -- hooks ran before return hook from 'testC'
  594. checktable(trace,
  595. {"return sethook", "y", "return ?", "x", "return ?", "return testC"})
  596. -- results are correct
  597. checktable(t, {10, 20})
  598. end
  599. end
  600. do -- '__close' vs. return hooks in Lua functions
  601. local trace = {}
  602. local function hook (event)
  603. trace[#trace + 1] = event .. " " .. debug.getinfo(2).name
  604. end
  605. local function foo (...)
  606. local x <close> = func2close(function (_,msg)
  607. trace[#trace + 1] = "x"
  608. end)
  609. local y <close> = func2close(function (_,msg)
  610. debug.sethook(hook, "r")
  611. end)
  612. return ...
  613. end
  614. local t = {foo(10,20,30)}
  615. debug.sethook()
  616. checktable(t, {10, 20, 30})
  617. checktable(trace,
  618. {"return sethook", "return close", "x", "return close", "return foo"})
  619. end
  620. print "to-be-closed variables in coroutines"
  621. do
  622. -- yielding inside closing metamethods
  623. local trace = {}
  624. local co = coroutine.wrap(function ()
  625. trace[#trace + 1] = "nowX"
  626. -- will be closed after 'y'
  627. local x <close> = func2close(function (_, msg)
  628. assert(msg == nil)
  629. trace[#trace + 1] = "x1"
  630. coroutine.yield("x")
  631. trace[#trace + 1] = "x2"
  632. end)
  633. return pcall(function ()
  634. do -- 'z' will be closed first
  635. local z <close> = func2close(function (_, msg)
  636. assert(msg == nil)
  637. trace[#trace + 1] = "z1"
  638. coroutine.yield("z")
  639. trace[#trace + 1] = "z2"
  640. end)
  641. end
  642. trace[#trace + 1] = "nowY"
  643. -- will be closed after 'z'
  644. local y <close> = func2close(function(_, msg)
  645. assert(msg == nil)
  646. trace[#trace + 1] = "y1"
  647. coroutine.yield("y")
  648. trace[#trace + 1] = "y2"
  649. end)
  650. return 10, 20, 30
  651. end)
  652. end)
  653. assert(co() == "z")
  654. assert(co() == "y")
  655. assert(co() == "x")
  656. checktable({co()}, {true, 10, 20, 30})
  657. checktable(trace, {"nowX", "z1", "z2", "nowY", "y1", "y2", "x1", "x2"})
  658. end
  659. do
  660. -- yielding inside closing metamethods while returning
  661. -- (bug in 5.4.3)
  662. local extrares -- result from extra yield (if any)
  663. local function check (body, extra, ...)
  664. local t = table.pack(...) -- expected returns
  665. local co = coroutine.wrap(body)
  666. if extra then
  667. extrares = co() -- runs until first (extra) yield
  668. end
  669. local res = table.pack(co()) -- runs until yield inside '__close'
  670. assert(res.n == 2 and res[2] == nil)
  671. local res2 = table.pack(co()) -- runs until end of function
  672. assert(res2.n == t.n)
  673. for i = 1, #t do
  674. if t[i] == "x" then
  675. assert(res2[i] == res[1]) -- value that was closed
  676. else
  677. assert(res2[i] == t[i])
  678. end
  679. end
  680. end
  681. local function foo ()
  682. local x <close> = func2close(coroutine.yield)
  683. local extra <close> = func2close(function (self)
  684. assert(self == extrares)
  685. coroutine.yield(100)
  686. end)
  687. extrares = extra
  688. return table.unpack{10, x, 30}
  689. end
  690. check(foo, true, 10, "x", 30)
  691. assert(extrares == 100)
  692. local function foo ()
  693. local x <close> = func2close(coroutine.yield)
  694. return
  695. end
  696. check(foo, false)
  697. local function foo ()
  698. local x <close> = func2close(coroutine.yield)
  699. local y, z = 20, 30
  700. return x
  701. end
  702. check(foo, false, "x")
  703. local function foo ()
  704. local x <close> = func2close(coroutine.yield)
  705. local extra <close> = func2close(coroutine.yield)
  706. return table.unpack({}, 1, 100) -- 100 nils
  707. end
  708. check(foo, true, table.unpack({}, 1, 100))
  709. end
  710. do
  711. -- yielding inside closing metamethods after an error
  712. local co = coroutine.wrap(function ()
  713. local function foo (err)
  714. local z <close> = func2close(function(_, msg)
  715. assert(msg == nil or msg == err + 20)
  716. coroutine.yield("z")
  717. return 100, 200
  718. end)
  719. local y <close> = func2close(function(_, msg)
  720. -- still gets the original error (if any)
  721. assert(msg == err or (msg == nil and err == 1))
  722. coroutine.yield("y")
  723. if err then error(err + 20) end -- creates or changes the error
  724. end)
  725. local x <close> = func2close(function(_, msg)
  726. assert(msg == err or (msg == nil and err == 1))
  727. coroutine.yield("x")
  728. return 100, 200
  729. end)
  730. if err == 10 then error(err) else return 10, 20 end
  731. end
  732. coroutine.yield(pcall(foo, nil)) -- no error
  733. coroutine.yield(pcall(foo, 1)) -- error in __close
  734. return pcall(foo, 10) -- 'foo' will raise an error
  735. end)
  736. local a, b = co() -- first foo: no error
  737. assert(a == "x" and b == nil) -- yields inside 'x'; Ok
  738. a, b = co()
  739. assert(a == "y" and b == nil) -- yields inside 'y'; Ok
  740. a, b = co()
  741. assert(a == "z" and b == nil) -- yields inside 'z'; Ok
  742. local a, b, c = co()
  743. assert(a and b == 10 and c == 20) -- returns from 'pcall(foo, nil)'
  744. local a, b = co() -- second foo: error in __close
  745. assert(a == "x" and b == nil) -- yields inside 'x'; Ok
  746. a, b = co()
  747. assert(a == "y" and b == nil) -- yields inside 'y'; Ok
  748. a, b = co()
  749. assert(a == "z" and b == nil) -- yields inside 'z'; Ok
  750. local st, msg = co() -- reports the error in 'y'
  751. assert(not st and msg == 21)
  752. local a, b = co() -- third foo: error in function body
  753. assert(a == "x" and b == nil) -- yields inside 'x'; Ok
  754. a, b = co()
  755. assert(a == "y" and b == nil) -- yields inside 'y'; Ok
  756. a, b = co()
  757. assert(a == "z" and b == nil) -- yields inside 'z'; Ok
  758. local st, msg = co() -- gets final error
  759. assert(not st and msg == 10 + 20)
  760. end
  761. do
  762. -- an error in a wrapped coroutine closes variables
  763. local x = false
  764. local y = false
  765. local co = coroutine.wrap(function ()
  766. local xv <close> = func2close(function () x = true end)
  767. do
  768. local yv <close> = func2close(function () y = true end)
  769. coroutine.yield(100) -- yield doesn't close variable
  770. end
  771. coroutine.yield(200) -- yield doesn't close variable
  772. error(23) -- error does
  773. end)
  774. local b = co()
  775. assert(b == 100 and not x and not y)
  776. b = co()
  777. assert(b == 200 and not x and y)
  778. local a, b = pcall(co)
  779. assert(not a and b == 23 and x and y)
  780. end
  781. do
  782. -- error in a wrapped coroutine raising errors when closing a variable
  783. local x = 0
  784. local co = coroutine.wrap(function ()
  785. local xx <close> = func2close(function (_, msg)
  786. x = x + 1;
  787. assert(string.find(msg, "@XXX"))
  788. error("@YYY")
  789. end)
  790. local xv <close> = func2close(function () x = x + 1; error("@XXX") end)
  791. coroutine.yield(100)
  792. error(200)
  793. end)
  794. assert(co() == 100); assert(x == 0)
  795. local st, msg = pcall(co); assert(x == 2)
  796. assert(not st and string.find(msg, "@YYY")) -- should get error raised
  797. local x = 0
  798. local y = 0
  799. co = coroutine.wrap(function ()
  800. local xx <close> = func2close(function (_, err)
  801. y = y + 1;
  802. assert(string.find(err, "XXX"))
  803. error("YYY")
  804. end)
  805. local xv <close> = func2close(function ()
  806. x = x + 1; error("XXX")
  807. end)
  808. coroutine.yield(100)
  809. return 200
  810. end)
  811. assert(co() == 100); assert(x == 0)
  812. local st, msg = pcall(co)
  813. assert(x == 1 and y == 1)
  814. -- should get first error raised
  815. assert(not st and string.find(msg, "%w+%.%w+:%d+: YYY"))
  816. end
  817. -- a suspended coroutine should not close its variables when collected
  818. local co
  819. co = coroutine.wrap(function()
  820. -- should not run
  821. local x <close> = func2close(function () os.exit(false) end)
  822. co = nil
  823. coroutine.yield()
  824. end)
  825. co() -- start coroutine
  826. assert(co == nil) -- eventually it will be collected
  827. collectgarbage()
  828. if rawget(_G, "T") then
  829. print("to-be-closed variables x coroutines in C")
  830. do
  831. local token = 0
  832. local count = 0
  833. local f = T.makeCfunc[[
  834. toclose 1
  835. toclose 2
  836. return .
  837. ]]
  838. local obj = func2close(function (_, msg)
  839. count = count + 1
  840. token = coroutine.yield(count, token)
  841. end)
  842. local co = coroutine.wrap(f)
  843. local ct, res = co(obj, obj, 10, 20, 30, 3) -- will return 10, 20, 30
  844. -- initial token value, after closing 2nd obj
  845. assert(ct == 1 and res == 0)
  846. -- run until yield when closing 1st obj
  847. ct, res = co(100)
  848. assert(ct == 2 and res == 100)
  849. res = {co(200)} -- run until end
  850. assert(res[1] == 10 and res[2] == 20 and res[3] == 30 and res[4] == nil)
  851. assert(token == 200)
  852. end
  853. do
  854. local f = T.makeCfunc[[
  855. toclose 1
  856. return .
  857. ]]
  858. local obj = func2close(function ()
  859. local temp
  860. local x <close> = func2close(function ()
  861. coroutine.yield(temp)
  862. return 1,2,3 -- to be ignored
  863. end)
  864. temp = coroutine.yield("closing obj")
  865. return 1,2,3 -- to be ignored
  866. end)
  867. local co = coroutine.wrap(f)
  868. local res = co(obj, 10, 30, 1) -- will return only 30
  869. assert(res == "closing obj")
  870. res = co("closing x")
  871. assert(res == "closing x")
  872. res = {co()}
  873. assert(res[1] == 30 and res[2] == nil)
  874. end
  875. do
  876. -- still cannot yield inside 'closeslot'
  877. local f = T.makeCfunc[[
  878. toclose 1
  879. closeslot 1
  880. ]]
  881. local obj = func2close(coroutine.yield)
  882. local co = coroutine.create(f)
  883. local st, msg = coroutine.resume(co, obj)
  884. assert(not st and string.find(msg, "attempt to yield across"))
  885. -- nor outside a coroutine
  886. local f = T.makeCfunc[[
  887. toclose 1
  888. ]]
  889. local st, msg = pcall(f, obj)
  890. assert(not st and string.find(msg, "attempt to yield from outside"))
  891. end
  892. end
  893. -- to-be-closed variables in generic for loops
  894. do
  895. local numopen = 0
  896. local function open (x)
  897. numopen = numopen + 1
  898. return
  899. function () -- iteraction function
  900. x = x - 1
  901. if x > 0 then return x end
  902. end,
  903. nil, -- state
  904. nil, -- control variable
  905. func2close(function () numopen = numopen - 1 end) -- closing function
  906. end
  907. local s = 0
  908. for i in open(10) do
  909. s = s + i
  910. end
  911. assert(s == 45 and numopen == 0)
  912. local s = 0
  913. for i in open(10) do
  914. if i < 5 then break end
  915. s = s + i
  916. end
  917. assert(s == 35 and numopen == 0)
  918. local s = 0
  919. for i in open(10) do
  920. for j in open(10) do
  921. if i + j < 5 then goto endloop end
  922. s = s + i
  923. end
  924. end
  925. ::endloop::
  926. assert(s == 375 and numopen == 0)
  927. end
  928. print('OK')
  929. return 5,f
  930. end -- }