interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / testes / locals.lua

1246 lines · 31244 bytes Raw Blame History
1-- $Id: testes/locals.lua $
2-- See Copyright Notice in file lua.h
3
4global <const> *
5
6print('testing local variables and environments')
7
8local debug = require"debug"
9
10local tracegc = require"tracegc"
11
12
13-- bug in 5.1:
14
15local function f(x) x = nil; return x end
16assert(f(10) == nil)
17
18local function f() local x; return x end
19assert(f(10) == nil)
20
21local function f(x) x = nil; local y; return x, y end
22assert(f(10) == nil and select(2, f(20)) == nil)
23
24do
25 local i = 10
26 do local i = 100; assert(i==100) end
27 do local i = 1000; assert(i==1000) end
28 assert(i == 10)
29 if i ~= 10 then
30 local i = 20
31 else
32 local i = 30
33 assert(i == 30)
34 end
35end
36
37
38
39f = nil
40
41local f
42local x = 1
43
44do
45 global a; a = nil
46 load('local a = {}')()
47 assert(a == nil)
48end
49
50function f (a)
51 local _1, _2, _3, _4, _5
52 local _6, _7, _8, _9, _10
53 local x = 3
54 local b = a
55 local c,d = a,b
56 if (d == b) then
57 local x = 'q'
58 x = b
59 assert(x == 2)
60 else
61 assert(nil)
62 end
63 assert(x == 3)
64 local f = 10
65end
66
67local b=10
68local a; repeat local b; a,b=1,2; assert(a+1==b); until a+b==3
69
70
71assert(x == 1)
72
73f(2)
74assert(type(f) == 'function')
75
76
77local function getenv (f)
78 local a,b = debug.getupvalue(f, 1)
79 assert(a == '_ENV')
80 return b
81end
82
83-- test for global table of loaded chunks
84assert(getenv(load"a=3") == _G)
85local c = {}; local f = load("a = 3", nil, nil, c)
86assert(getenv(f) == c)
87assert(c.a == nil)
88f()
89assert(c.a == 3)
90
91-- old test for limits for special instructions
92do
93 local i = 2
94 local p = 4 -- p == 2^i
95 repeat
96 for j=-3,3 do
97 assert(load(string.format([[local a=%s;
98 a=a+%s;
99 assert(a ==2^%s)]], j, p-j, i), '')) ()
100 assert(load(string.format([[local a=%s;
101 a=a-%s;
102 assert(a==-2^%s)]], -j, p-j, i), '')) ()
103 assert(load(string.format([[local a,b=0,%s;
104 a=b-%s;
105 assert(a==-2^%s)]], -j, p-j, i), '')) ()
106 end
107 p = 2 * p; i = i + 1
108 until p <= 0
109end
110
111print'+'
112
113
114if rawget(_G, "T") then
115 -- testing clearing of dead elements from tables
116 collectgarbage("stop") -- stop GC
117 local a = {[{}] = 4, [3] = 0, alo = 1,
118 a1234567890123456789012345678901234567890 = 10}
119
120 local t = T.querytab(a)
121
122 for k,_ in pairs(a) do a[k] = undef end
123 collectgarbage() -- restore GC and collect dead fields in 'a'
124 for i=0,t-1 do
125 local k = querytab(a, i)
126 assert(k == nil or type(k) == 'number' or k == 'alo')
127 end
128
129 -- testing allocation errors during table insertions
130 local a = {}
131 local function additems ()
132 a.x = true; a.y = true; a.z = true
133 a[1] = true
134 a[2] = true
135 end
136 for i = 1, math.huge do
137 T.alloccount(i)
138 local st, msg = pcall(additems)
139 T.alloccount()
140 local count = 0
141 for k, v in pairs(a) do
142 assert(a[k] == v)
143 count = count + 1
144 end
145 if st then assert(count == 5); break end
146 end
147end
148
149
150-- testing lexical environments
151
152assert(_ENV == _G)
153
154do
155local dummy
156local _ENV = (function (...) return ... end)(_G, dummy) -- {
157
158do local _ENV = {assert=assert}; assert(true) end
159local mt = {_G = _G}
160local foo,x
161global A; A = false -- "declare" A
162do local _ENV = mt
163 function foo (x)
164 A = x
165 do local _ENV = _G; A = 1000 end
166 return function (x) return A .. x end
167 end
168end
169assert(getenv(foo) == mt)
170x = foo('hi'); assert(mt.A == 'hi' and A == 1000)
171assert(x('*') == mt.A .. '*')
172
173do local _ENV = {assert=assert, A=10};
174 do local _ENV = {assert=assert, A=20};
175 assert(A==20);x=A
176 end
177 assert(A==10 and x==20)
178end
179assert(x==20)
180
181A = nil
182
183
184do print("testing local constants")
185 global assert<const>, load, string, X
186 X = 1 -- not a constant
187 local a<const>, b, c<const> = 10, 20, 30
188 b = a + c + b -- 'b' is not constant
189 assert(a == 10 and b == 60 and c == 30)
190
191 local function checkro (name, code)
192 local st, msg = load(code)
193 local gab = string.format("attempt to assign to const variable '%s'", name)
194 assert(not st and string.find(msg, gab))
195 end
196
197 checkro("y", "local x, y <const>, z = 10, 20, 30; x = 11; y = 12")
198 checkro("x", "local x <const>, y, z <const> = 10, 20, 30; x = 11")
199 checkro("z", "local x <const>, y, z <const> = 10, 20, 30; y = 10; z = 11")
200 checkro("foo", "local<const> foo = 10; function foo() end")
201 checkro("foo", "local<const> foo <const> = {}; function foo() end")
202 checkro("foo", "global<const> foo <const>; function foo() end")
203 checkro("XX", "global XX <const>; XX = 10")
204 checkro("XX", "local _ENV; global XX <const>; XX = 10")
205
206 checkro("z", [[
207 local a, z <const>, b = 10;
208 function foo() a = 20; z = 32; end
209 ]])
210
211 checkro("var1", [[
212 local a, var1 <const> = 10;
213 function foo() a = 20; z = function () var1 = 12; end end
214 ]])
215
216 checkro("var1", [[
217 global a, var1 <const>, z;
218 local function foo() a = 20; z = function () var1 = 12; end end
219 ]])
220end
221
222
223
224print"testing to-be-closed variables"
225
226
227do
228 local st, msg = load("local <close> a, b")
229 assert(not st and string.find(msg, "multiple"))
230
231 local st, msg = load("local a<close>, b<close>")
232 assert(not st and string.find(msg, "multiple"))
233end
234
235local function stack(n) n = ((n == 0) or stack(n - 1)) end
236
237local function func2close (f, x, y)
238 local obj = setmetatable({}, {__close = f})
239 if x then
240 return x, obj, y
241 else
242 return obj
243 end
244end
245
246
247do
248 local a = {}
249 do
250 local b <close> = false -- not to be closed
251 local x <close> = setmetatable({"x"}, {__close = function (self)
252 a[#a + 1] = self[1] end})
253 local w, y <close>, z = func2close(function (self, err)
254 assert(err == nil); a[#a + 1] = "y"
255 end, 10, 20)
256 local c <close> = nil -- not to be closed
257 a[#a + 1] = "in"
258 assert(w == 10 and z == 20)
259 end
260 a[#a + 1] = "out"
261 assert(a[1] == "in" and a[2] == "y" and a[3] == "x" and a[4] == "out")
262end
263
264do
265 local X = false
266
267 local x, closescope = func2close(function (_, msg)
268 stack(10);
269 assert(msg == nil)
270 X = true
271 end, 100)
272 assert(x == 100); x = 101; -- 'x' is not read-only
273
274 -- closing functions do not corrupt returning values
275 local function foo (x)
276 local _ <close> = closescope
277 return x, X, 23
278 end
279
280 local a, b, c = foo(1.5)
281 assert(a == 1.5 and b == false and c == 23 and X == true)
282
283 X = false
284 foo = function (x)
285 local _<close> = func2close(function (_, msg)
286 -- without errors, enclosing function should be still active when
287 -- __close is called
288 assert(debug.getinfo(2).name == "foo")
289 assert(msg == nil)
290 end)
291 local _<close> = closescope
292 local y = 15
293 return y
294 end
295
296 assert(foo() == 15 and X == true)
297
298 X = false
299 foo = function ()
300 local x <close> = closescope
301 return x
302 end
303
304 assert(foo() == closescope and X == true)
305
306end
307
308
309do -- testing presence of second argument
310 local function foo (howtoclose, obj, n)
311 local ca -- copy of 'a' visible inside its close metamethod
312 do
313 local a <close> = func2close(function (...t)
314 assert(select("#", ...) == n)
315 assert(t.n == n and t[1] == ca and (t.n < 2 or t[2] == obj))
316 ca = 15 -- final value to be returned if howtoclose=="scope"
317 end)
318 ca = a
319 if howtoclose == "ret" then return obj -- 'a' closed by return
320 elseif howtoclose == "err" then error(obj) -- 'a' closed by error
321 end
322 end -- 'a' closed by end of scope
323 return ca -- ca now should be 15
324 end
325 -- with no errors, closing methods receive no extra argument
326 assert(foo("scope", nil, 1) == 15) -- close by end of scope
327 assert(foo("ret", 32, 1) == 32) -- close by return
328 -- with errors, they do
329 local st, msg = pcall(foo, "err", 23, 2) -- close by error
330 assert(not st and msg == 23)
331end
332
333
334-- testing to-be-closed x compile-time constants
335-- (there were some bugs here in Lua 5.4-rc3, due to a confusion
336-- between compile levels and stack levels of variables)
337do
338 local flag = false
339 local x = setmetatable({},
340 {__close = function() assert(flag == false); flag = true end})
341 local y <const> = nil
342 local z <const> = nil
343 do
344 local a <close> = x
345 end
346 assert(flag) -- 'x' must be closed here
347end
348
349do
350 -- similar problem, but with implicit close in for loops
351 local flag = false
352 local x = setmetatable({},
353 {__close = function () assert(flag == false); flag = true end})
354 -- return an empty iterator, nil, nil, and 'x' to be closed
355 local function a ()
356 return (function () return nil end), nil, nil, x
357 end
358 local v <const> = 1
359 local w <const> = 1
360 local x <const> = 1
361 local y <const> = 1
362 local z <const> = 1
363 for k in a() do
364 a = k
365 end -- ending the loop must close 'x'
366 assert(flag) -- 'x' must be closed here
367end
368
369
370
371do
372 -- calls cannot be tail in the scope of to-be-closed variables
373 local X, Y
374 local function foo ()
375 local _ <close> = func2close(function () Y = 10 end)
376 assert(X == true and Y == nil) -- 'X' not closed yet
377 return 1,2,3
378 end
379
380 local function bar ()
381 local _ <close> = func2close(function () X = false end)
382 X = true
383 do
384 return foo() -- not a tail call!
385 end
386 end
387
388 local a, b, c, d = bar()
389 assert(a == 1 and b == 2 and c == 3 and X == false and Y == 10 and d == nil)
390end
391
392
393do
394 -- bug in 5.4.3: previous condition (calls cannot be tail in the
395 -- scope of to-be-closed variables) must be valid for tbc variables
396 -- created by 'for' loops.
397
398 local closed = false
399
400 local function foo ()
401 return function () return true end, 0, 0,
402 func2close(function () closed = true end)
403 end
404
405 local function tail() return closed end
406
407 local function foo1 ()
408 for k in foo() do return tail() end
409 end
410
411 assert(foo1() == false)
412 assert(closed == true)
413end
414
415
416do
417 -- bug in 5.4.4: 'break' may generate wrong 'close' instruction when
418 -- leaving a loop block.
419
420 local closed = false
421
422 local o1 = setmetatable({}, {__close=function() closed = true end})
423
424 local function test()
425 for k, v in next, {}, nil, o1 do
426 local function f() return k end -- create an upvalue
427 break
428 end
429 assert(closed)
430 end
431
432 test()
433end
434
435
436do print("testing errors in __close")
437
438 -- original error is in __close
439 local function foo ()
440
441 local x <close> =
442 func2close(function (self, msg)
443 assert(string.find(msg, "@y"))
444 error("@x")
445 end)
446
447 local x1 <close> =
448 func2close(function (self, msg)
449 assert(string.find(msg, "@y"))
450 end)
451
452 local gc <close> = func2close(function () collectgarbage() end)
453
454 local y <close> =
455 func2close(function (self, msg)
456 assert(string.find(msg, "@z")) -- error in 'z'
457 error("@y")
458 end)
459
460 local z <close> =
461 func2close(function (self, msg)
462 assert(msg == nil)
463 error("@z")
464 end)
465
466 return 200
467 end
468
469 local stat, msg = pcall(foo, false)
470 assert(string.find(msg, "@x"))
471
472
473 -- original error not in __close
474 local function foo ()
475
476 local x <close> =
477 func2close(function (self, msg)
478 -- after error, 'foo' was discarded, so caller now
479 -- must be 'pcall'
480 assert(debug.getinfo(2).name == "pcall")
481 assert(string.find(msg, "@x1"))
482 end)
483
484 local x1 <close> =
485 func2close(function (self, msg)
486 assert(debug.getinfo(2).name == "pcall")
487 assert(string.find(msg, "@y"))
488 error("@x1")
489 end)
490
491 local gc <close> = func2close(function () collectgarbage() end)
492
493 local y <close> =
494 func2close(function (self, msg)
495 assert(debug.getinfo(2).name == "pcall")
496 assert(string.find(msg, "@z"))
497 error("@y")
498 end)
499
500 local first = true
501 local z <close> =
502 func2close(function (self, msg)
503 assert(debug.getinfo(2).name == "pcall")
504 -- 'z' close is called once
505 assert(first and msg == 4)
506 first = false
507 error("@z")
508 end)
509
510 error(4) -- original error
511 end
512
513 local stat, msg = pcall(foo, true)
514 assert(string.find(msg, "@x1"))
515
516 -- error leaving a block
517 local function foo (...)
518 do
519 local x1 <close> =
520 func2close(function (self, msg)
521 assert(string.find(msg, "@X"))
522 error("@Y")
523 end)
524
525 local x123 <close> =
526 func2close(function (_, msg)
527 assert(msg == nil)
528 error("@X")
529 end)
530 end
531 os.exit(false) -- should not run
532 end
533
534 local st, msg = xpcall(foo, debug.traceback)
535 assert(string.match(msg, "^[^ ]* @Y"))
536
537 -- error in toclose in vararg function
538 local function foo (...)
539 local x123 <close> = func2close(function () error("@x123") end)
540 end
541
542 local st, msg = xpcall(foo, debug.traceback)
543 assert(string.match(msg, "^[^ ]* @x123"))
544 assert(string.find(msg, "in metamethod 'close'"))
545end
546
547
548do -- errors due to non-closable values
549 local function foo ()
550 local x <close> = {}
551 os.exit(false) -- should not run
552 end
553 local stat, msg = pcall(foo)
554 assert(not stat and
555 string.find(msg, "variable 'x' got a non%-closable value"))
556
557 local function foo ()
558 local xyz <close> = setmetatable({}, {__close = print})
559 getmetatable(xyz).__close = nil -- remove metamethod
560 end
561 local stat, msg = pcall(foo)
562 assert(not stat and string.find(msg, "metamethod 'close'"))
563
564 local function foo ()
565 local a1 <close> = func2close(function (_, msg)
566 assert(string.find(msg, "number value"))
567 error(12)
568 end)
569 local a2 <close> = setmetatable({}, {__close = print})
570 local a3 <close> = func2close(function (_, msg)
571 assert(msg == nil)
572 error(123)
573 end)
574 getmetatable(a2).__close = 4 -- invalidate metamethod
575 end
576 local stat, msg = pcall(foo)
577 assert(not stat and msg == 12)
578end
579
580
581do -- tbc inside close methods
582 local track = {}
583 local function foo ()
584 local x <close> = func2close(function ()
585 local xx <close> = func2close(function (_, msg)
586 assert(msg == nil)
587 track[#track + 1] = "xx"
588 end)
589 track[#track + 1] = "x"
590 end)
591 track[#track + 1] = "foo"
592 return 20, 30, 40
593 end
594 local a, b, c, d = foo()
595 assert(a == 20 and b == 30 and c == 40 and d == nil)
596 assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx")
597
598 -- again, with errors
599 local track = {}
600 local function foo ()
601 local x0 <close> = func2close(function (_, msg)
602 assert(msg == 202)
603 track[#track + 1] = "x0"
604 end)
605 local x <close> = func2close(function ()
606 local xx <close> = func2close(function (_, msg)
607 assert(msg == 101)
608 track[#track + 1] = "xx"
609 error(202)
610 end)
611 track[#track + 1] = "x"
612 error(101)
613 end)
614 track[#track + 1] = "foo"
615 return 20, 30, 40
616 end
617 local st, msg = pcall(foo)
618 assert(not st and msg == 202)
619 assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx" and
620 track[4] == "x0")
621end
622
623
624local function checktable (t1, t2)
625 assert(#t1 == #t2)
626 for i = 1, #t1 do
627 assert(t1[i] == t2[i])
628 end
629end
630
631
632do -- test for tbc variable high in the stack
633
634 -- function to force a stack overflow
635 local function overflow (n)
636 overflow(n + 1)
637 end
638
639 -- error handler will create tbc variable handling a stack overflow,
640 -- high in the stack
641 local function errorh (m)
642 assert(string.find(m, "stack overflow"))
643 local x <close> = func2close(function (o) o[1] = 10 end)
644 return x
645 end
646
647 local flag
648 local st, obj
649 -- run test in a coroutine so as not to swell the main stack
650 local co = coroutine.wrap(function ()
651 -- tbc variable down the stack
652 local y <close> = func2close(function (obj, msg)
653 assert(msg == nil)
654 obj[1] = 100
655 flag = obj
656 end)
657 tracegc.stop()
658 st, obj = xpcall(overflow, errorh, 0)
659 tracegc.start()
660 end)
661 co()
662 assert(not st and obj[1] == 10 and flag[1] == 100)
663end
664
665
666if rawget(_G, "T") then
667
668 do
669 -- bug in 5.4.3
670 -- 'lua_settop' may use a pointer to stack invalidated by 'luaF_close'
671
672 -- reduce stack size
673 collectgarbage(); collectgarbage(); collectgarbage()
674
675 -- force a stack reallocation
676 local function loop (n)
677 if n < 400 then loop(n + 1) end
678 end
679
680 -- close metamethod will reallocate the stack
681 local o = setmetatable({}, {__close = function () loop(0) end})
682
683 local script = [[toclose 2; settop 1; return 1]]
684
685 assert(T.testC(script, o) == script)
686
687 end
688
689
690 -- memory error inside closing function
691 local function foo ()
692 local y <close> = func2close(function () T.alloccount() end)
693 local x <close> = setmetatable({}, {__close = function ()
694 T.alloccount(0); local x = {} -- force a memory error
695 end})
696 error(1000) -- common error inside the function's body
697 end
698
699 stack(5) -- ensure a minimal number of CI structures
700
701 -- despite memory error, 'y' will be executed and
702 -- memory limit will be lifted
703 local _, msg = pcall(foo)
704 assert(msg == "not enough memory")
705
706 local closemsg
707 local close = func2close(function (self, msg)
708 T.alloccount()
709 closemsg = msg
710 end)
711
712 -- set a memory limit and return a closing object to remove the limit
713 local function enter (count)
714 stack(10) -- reserve some stack space
715 T.alloccount(count)
716 closemsg = nil
717 return close
718 end
719
720 local function test ()
721 local x <close> = enter(0) -- set a memory limit
722 local y = {} -- raise a memory error
723 end
724
725 local _, msg = pcall(test)
726 assert(msg == "not enough memory" and closemsg == "not enough memory")
727
728
729 -- repeat test with extra closing upvalues
730 local function test ()
731 local xxx <close> = func2close(function (self, msg)
732 assert(msg == "not enough memory");
733 error(1000) -- raise another error
734 end)
735 local xx <close> = func2close(function (self, msg)
736 assert(msg == "not enough memory");
737 end)
738 local x <close> = enter(0) -- set a memory limit
739 local y = {} -- raise a memory error
740 end
741
742 local _, msg = pcall(test)
743 assert(msg == 1000 and closemsg == "not enough memory")
744
745 do -- testing 'toclose' in C string buffer
746 collectgarbage()
747 local s = string.rep('a', 10000) -- large string
748 local m = T.totalmem()
749 collectgarbage("stop")
750 s = string.upper(s) -- allocate buffer + new string (10K each)
751 -- ensure buffer was deallocated
752 assert(T.totalmem() - m <= 11000)
753 collectgarbage("restart")
754 end
755
756 do -- now some tests for freeing buffer in case of errors
757 local lim = 10000 -- some size larger than the static buffer
758 local extra = 2000 -- some extra memory (for callinfo, etc.)
759
760 local s = string.rep("a", lim)
761
762 -- concat this table needs two buffer resizes (one for each 's')
763 local a = {s, s}
764
765 collectgarbage(); collectgarbage()
766
767 local m = T.totalmem()
768 collectgarbage("stop")
769
770 -- error in the first buffer allocation
771 T. totalmem(m + extra)
772 assert(not pcall(table.concat, a))
773 -- first buffer was not even allocated
774 assert(T.totalmem() - m <= extra)
775
776 -- error in the second buffer allocation
777 T. totalmem(m + lim + extra)
778 assert(not pcall(table.concat, a))
779 -- first buffer was released by 'toclose'
780 assert(T.totalmem() - m <= extra)
781
782 -- userdata, buffer, final string
783 T.totalmem(m + 2*lim + extra)
784 assert(#table.concat(a) == 2*lim)
785
786 T.totalmem(0) -- remove memory limit
787 collectgarbage("restart")
788
789 print'+'
790 end
791
792
793 do
794 -- '__close' vs. return hooks in C functions
795 local trace = {}
796
797 local function hook (event)
798 trace[#trace + 1] = event .. " " .. (debug.getinfo(2).name or "?")
799 end
800
801 -- create tbc variables to be used by C function
802 local x = func2close(function (_,msg)
803 trace[#trace + 1] = "x"
804 end)
805
806 local y = func2close(function (_,msg)
807 trace[#trace + 1] = "y"
808 end)
809
810 debug.sethook(hook, "r")
811 local t = {T.testC([[
812 toclose 2 # x
813 pushnum 10
814 pushint 20
815 toclose 3 # y
816 return 2
817 ]], x, y)}
818 debug.sethook()
819
820 -- hooks ran before return hook from 'testC'
821 checktable(trace,
822 {"return sethook", "y", "return ?", "x", "return ?", "return testC"})
823 -- results are correct
824 checktable(t, {10, 20})
825 end
826end
827
828
829do -- '__close' vs. return hooks in Lua functions
830 local trace = {}
831
832 local function hook (event)
833 trace[#trace + 1] = event .. " " .. debug.getinfo(2).name
834 end
835
836 local function foo (...)
837 local x <close> = func2close(function (_,msg)
838 trace[#trace + 1] = "x"
839 end)
840
841 local y <close> = func2close(function (_,msg)
842 debug.sethook(hook, "r")
843 end)
844
845 return ...
846 end
847
848 local t = {foo(10,20,30)}
849 debug.sethook()
850 checktable(t, {10, 20, 30})
851 checktable(trace,
852 {"return sethook", "return close", "x", "return close", "return foo"})
853end
854
855
856print "to-be-closed variables in coroutines"
857
858do
859 -- yielding inside closing metamethods
860
861 local trace = {}
862 local co = coroutine.wrap(function ()
863
864 trace[#trace + 1] = "nowX"
865
866 -- will be closed after 'y'
867 local x <close> = func2close(function (_, msg)
868 assert(msg == nil)
869 trace[#trace + 1] = "x1"
870 coroutine.yield("x")
871 trace[#trace + 1] = "x2"
872 end)
873
874 return pcall(function ()
875 do -- 'z' will be closed first
876 local z <close> = func2close(function (_, msg)
877 assert(msg == nil)
878 trace[#trace + 1] = "z1"
879 coroutine.yield("z")
880 trace[#trace + 1] = "z2"
881 end)
882 end
883
884 trace[#trace + 1] = "nowY"
885
886 -- will be closed after 'z'
887 local y <close> = func2close(function(_, msg)
888 assert(msg == nil)
889 trace[#trace + 1] = "y1"
890 coroutine.yield("y")
891 trace[#trace + 1] = "y2"
892 end)
893
894 return 10, 20, 30
895 end)
896 end)
897
898 assert(co() == "z")
899 assert(co() == "y")
900 assert(co() == "x")
901 checktable({co()}, {true, 10, 20, 30})
902 checktable(trace, {"nowX", "z1", "z2", "nowY", "y1", "y2", "x1", "x2"})
903
904end
905
906
907do
908 -- yielding inside closing metamethods while returning
909 -- (bug in 5.4.3)
910
911 local extrares -- result from extra yield (if any)
912
913 local function check (body, extra, ...t)
914 local co = coroutine.wrap(body)
915 if extra then
916 extrares = co() -- runs until first (extra) yield
917 end
918 local res = table.pack(co()) -- runs until "regular" yield
919 -- regular yield will yield all values passed to the close function;
920 -- without errors, that is only the object being closed.
921 assert(res.n == 1 and type(res[1]) == "table")
922 local res2 = table.pack(co()) -- runs until end of function
923 assert(res2.n == t.n)
924 for i = 1, #t do
925 if t[i] == "x" then
926 assert(res2[i] == res[1]) -- value that was closed
927 else
928 assert(res2[i] == t[i])
929 end
930 end
931 end
932
933 local function foo ()
934 local x <close> = func2close(coroutine.yield) -- "regular" yield
935 local extra <close> = func2close(function (self)
936 assert(self == extrares)
937 coroutine.yield(100) -- first (extra) yield
938 end)
939 extrares = extra
940 return table.unpack{10, x, 30}
941 end
942 check(foo, true, 10, "x", 30)
943 assert(extrares == 100)
944
945 local function foo ()
946 local x <close> = func2close(coroutine.yield) -- "regular" yield
947 return
948 end
949 check(foo, false)
950
951 local function foo ()
952 local x <close> = func2close(coroutine.yield) -- "regular" yield
953 local y, z = 20, 30
954 return x
955 end
956 check(foo, false, "x")
957
958 local function foo ()
959 local x <close> = func2close(coroutine.yield) -- "regular" yield
960 local extra <close> = func2close(coroutine.yield) -- extra yield
961 return table.unpack({}, 1, 100) -- 100 nils
962 end
963 check(foo, true, table.unpack({}, 1, 100))
964
965end
966
967do
968 -- yielding inside closing metamethods after an error
969
970 local co = coroutine.wrap(function ()
971
972 local function foo (err)
973
974 local z <close> = func2close(function(_, msg)
975 assert(msg == nil or msg == err + 20)
976 coroutine.yield("z")
977 return 100, 200
978 end)
979
980 local y <close> = func2close(function(_, msg)
981 -- still gets the original error (if any)
982 assert(msg == err or (msg == nil and err == 1))
983 coroutine.yield("y")
984 if err then error(err + 20) end -- creates or changes the error
985 end)
986
987 local x <close> = func2close(function(_, msg)
988 assert(msg == err or (msg == nil and err == 1))
989 coroutine.yield("x")
990 return 100, 200
991 end)
992
993 if err == 10 then error(err) else return 10, 20 end
994 end
995
996 coroutine.yield(pcall(foo, nil)) -- no error
997 coroutine.yield(pcall(foo, 1)) -- error in __close
998 return pcall(foo, 10) -- 'foo' will raise an error
999 end)
1000
1001 local a, b = co() -- first foo: no error
1002 assert(a == "x" and b == nil) -- yields inside 'x'; Ok
1003 a, b = co()
1004 assert(a == "y" and b == nil) -- yields inside 'y'; Ok
1005 a, b = co()
1006 assert(a == "z" and b == nil) -- yields inside 'z'; Ok
1007 local a, b, c = co()
1008 assert(a and b == 10 and c == 20) -- returns from 'pcall(foo, nil)'
1009
1010 local a, b = co() -- second foo: error in __close
1011 assert(a == "x" and b == nil) -- yields inside 'x'; Ok
1012 a, b = co()
1013 assert(a == "y" and b == nil) -- yields inside 'y'; Ok
1014 a, b = co()
1015 assert(a == "z" and b == nil) -- yields inside 'z'; Ok
1016 local st, msg = co() -- reports the error in 'y'
1017 assert(not st and msg == 21)
1018
1019 local a, b = co() -- third foo: error in function body
1020 assert(a == "x" and b == nil) -- yields inside 'x'; Ok
1021 a, b = co()
1022 assert(a == "y" and b == nil) -- yields inside 'y'; Ok
1023 a, b = co()
1024 assert(a == "z" and b == nil) -- yields inside 'z'; Ok
1025 local st, msg = co() -- gets final error
1026 assert(not st and msg == 10 + 20)
1027
1028end
1029
1030
1031do
1032 -- an error in a wrapped coroutine closes variables
1033 local x = false
1034 local y = false
1035 local co = coroutine.wrap(function ()
1036 local xv <close> = func2close(function () x = true end)
1037 do
1038 local yv <close> = func2close(function () y = true end)
1039 coroutine.yield(100) -- yield doesn't close variable
1040 end
1041 coroutine.yield(200) -- yield doesn't close variable
1042 error(23) -- error does
1043 end)
1044
1045 local b = co()
1046 assert(b == 100 and not x and not y)
1047 b = co()
1048 assert(b == 200 and not x and y)
1049 local a, b = pcall(co)
1050 assert(not a and b == 23 and x and y)
1051end
1052
1053
1054do
1055
1056 -- error in a wrapped coroutine raising errors when closing a variable
1057 local x = 0
1058 local co = coroutine.wrap(function ()
1059 local xx <close> = func2close(function (_, msg)
1060 x = x + 1;
1061 assert(string.find(msg, "@XXX"))
1062 error("@YYY")
1063 end)
1064 local xv <close> = func2close(function () x = x + 1; error("@XXX") end)
1065 coroutine.yield(100)
1066 error(200)
1067 end)
1068 assert(co() == 100); assert(x == 0)
1069 local st, msg = pcall(co); assert(x == 2)
1070 assert(not st and string.find(msg, "@YYY")) -- should get error raised
1071
1072 local x = 0
1073 local y = 0
1074 co = coroutine.wrap(function ()
1075 local xx <close> = func2close(function (_, err)
1076 y = y + 1;
1077 assert(string.find(err, "XXX"))
1078 error("YYY")
1079 end)
1080 local xv <close> = func2close(function ()
1081 x = x + 1; error("XXX")
1082 end)
1083 coroutine.yield(100)
1084 return 200
1085 end)
1086 assert(co() == 100); assert(x == 0)
1087 local st, msg = pcall(co)
1088 assert(x == 1 and y == 1)
1089 -- should get first error raised
1090 assert(not st and string.find(msg, "%w+%.%w+:%d+: YYY"))
1091
1092end
1093
1094
1095-- a suspended coroutine should not close its variables when collected
1096local co
1097co = coroutine.wrap(function()
1098 -- should not run
1099 local x <close> = func2close(function () os.exit(false) end)
1100 co = nil
1101 coroutine.yield()
1102end)
1103co() -- start coroutine
1104assert(co == nil) -- eventually it will be collected
1105collectgarbage()
1106
1107
1108if rawget(_G, "T") then
1109 print("to-be-closed variables x coroutines in C")
1110 do
1111 local token = 0
1112 local count = 0
1113 local f = T.makeCfunc[[
1114 toclose 1
1115 toclose 2
1116 return .
1117 ]]
1118
1119 local obj = func2close(function (_, msg)
1120 count = count + 1
1121 token = coroutine.yield(count, token)
1122 end)
1123
1124 local co = coroutine.wrap(f)
1125 local ct, res = co(obj, obj, 10, 20, 30, 3) -- will return 10, 20, 30
1126 -- initial token value, after closing 2nd obj
1127 assert(ct == 1 and res == 0)
1128 -- run until yield when closing 1st obj
1129 ct, res = co(100)
1130 assert(ct == 2 and res == 100)
1131 res = {co(200)} -- run until end
1132 assert(res[1] == 10 and res[2] == 20 and res[3] == 30 and res[4] == nil)
1133 assert(token == 200)
1134 end
1135
1136 do
1137 local f = T.makeCfunc[[
1138 toclose 1
1139 return .
1140 ]]
1141
1142 local obj = func2close(function ()
1143 local temp
1144 local x <close> = func2close(function ()
1145 coroutine.yield(temp)
1146 return 1,2,3 -- to be ignored
1147 end)
1148 temp = coroutine.yield("closing obj")
1149 return 1,2,3 -- to be ignored
1150 end)
1151
1152 local co = coroutine.wrap(f)
1153 local res = co(obj, 10, 30, 1) -- will return only 30
1154 assert(res == "closing obj")
1155 res = co("closing x")
1156 assert(res == "closing x")
1157 res = {co()}
1158 assert(res[1] == 30 and res[2] == nil)
1159 end
1160
1161 do
1162 -- still cannot yield inside 'closeslot'
1163 local f = T.makeCfunc[[
1164 toclose 1
1165 closeslot 1
1166 ]]
1167 local obj = func2close(coroutine.yield)
1168 local co = coroutine.create(f)
1169 local st, msg = coroutine.resume(co, obj)
1170 assert(not st and string.find(msg, "attempt to yield across"))
1171
1172 -- nor outside a coroutine
1173 local f = T.makeCfunc[[
1174 toclose 1
1175 ]]
1176 local st, msg = pcall(f, obj)
1177 assert(not st and string.find(msg, "attempt to yield from outside"))
1178 end
1179end
1180
1181
1182do
1183 -- detail in scopes of variables in the loop of 'repeat-until'
1184 local res = {}
1185 local function foo (a)
1186 repeat
1187 local x
1188 local i <close> = setmetatable({}, {__close = function ()
1189 res[#res + 1] = debug.getlocal(2, 2) -- get 'x'
1190 res[#res + 1] = debug.getlocal(2, 3) -- get 'i'
1191 a = true
1192 end})
1193 until a
1194 end
1195 foo(false)
1196 -- loop variables still in scope when closing 'i', both when 'repeat'
1197 -- repeats and when 'repeat' stops.
1198 assert(res[1] == "x" and res[2] == "i" and res[3] == "x" and res[4] == "i")
1199end
1200
1201
1202-- to-be-closed variables in generic for loops
1203do
1204 local numopen = 0
1205 local function open (x)
1206 numopen = numopen + 1
1207 return
1208 function () -- iteration function
1209 x = x - 1
1210 if x > 0 then return x end
1211 end,
1212 nil, -- state
1213 nil, -- control variable
1214 func2close(function () numopen = numopen - 1 end) -- closing function
1215 end
1216
1217 local s = 0
1218 for i in open(10) do
1219 s = s + i
1220 end
1221 assert(s == 45 and numopen == 0)
1222
1223 local s = 0
1224 for i in open(10) do
1225 if i < 5 then break end
1226 s = s + i
1227 end
1228 assert(s == 35 and numopen == 0)
1229
1230 local s = 0
1231 for i in open(10) do
1232 for j in open(10) do
1233 if i + j < 5 then goto endloop end
1234 s = s + i
1235 end
1236 end
1237 ::endloop::
1238 assert(s == 375 and numopen == 0)
1239end
1240
1241print('OK')
1242
1243return 5,f
1244
1245end -- }
1246