locals.lua 28 KB

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