Gentoo Archives: gentoo-commits

From: David Seifert <soap@g.o>
To: gentoo-commits@l.g.o
Subject: [gentoo-commits] proj/lua-patches:5.4.4 commit in: tests/
Date: Tue, 06 Sep 2022 10:39:18
Message-Id: 1662459002.dfe9df99ef9e201e9b9ad1e5faa2d9432c09aa3b.soap@gentoo
1 commit: dfe9df99ef9e201e9b9ad1e5faa2d9432c09aa3b
2 Author: David Seifert <soap <AT> gentoo <DOT> org>
3 AuthorDate: Tue Sep 6 10:10:02 2022 +0000
4 Commit: David Seifert <soap <AT> gentoo <DOT> org>
5 CommitDate: Tue Sep 6 10:10:02 2022 +0000
6 URL: https://gitweb.gentoo.org/proj/lua-patches.git/commit/?id=dfe9df99
7
8 Add upstream tests
9
10 * Only add tests/*.lua for now
11
12 Signed-off-by: David Seifert <soap <AT> gentoo.org>
13
14 tests/all.lua | 311 ++++++++++
15 tests/api.lua | 1533 ++++++++++++++++++++++++++++++++++++++++++++++++++
16 tests/attrib.lua | 515 +++++++++++++++++
17 tests/big.lua | 82 +++
18 tests/bitwise.lua | 351 ++++++++++++
19 tests/bwcoercion.lua | 78 +++
20 tests/calls.lua | 481 ++++++++++++++++
21 tests/closure.lua | 270 +++++++++
22 tests/code.lua | 449 +++++++++++++++
23 tests/constructs.lua | 377 +++++++++++++
24 tests/coroutine.lua | 1143 +++++++++++++++++++++++++++++++++++++
25 tests/cstack.lua | 171 ++++++
26 tests/db.lua | 1036 ++++++++++++++++++++++++++++++++++
27 tests/errors.lua | 661 ++++++++++++++++++++++
28 tests/events.lua | 488 ++++++++++++++++
29 tests/files.lua | 940 +++++++++++++++++++++++++++++++
30 tests/gc.lua | 691 +++++++++++++++++++++++
31 tests/gengc.lua | 172 ++++++
32 tests/goto.lua | 271 +++++++++
33 tests/heavy.lua | 173 ++++++
34 tests/literals.lua | 342 +++++++++++
35 tests/locals.lua | 1137 +++++++++++++++++++++++++++++++++++++
36 tests/main.lua | 528 +++++++++++++++++
37 tests/math.lua | 1024 +++++++++++++++++++++++++++++++++
38 tests/nextvar.lua | 805 ++++++++++++++++++++++++++
39 tests/pm.lua | 421 ++++++++++++++
40 tests/sort.lua | 310 ++++++++++
41 tests/strings.lua | 518 +++++++++++++++++
42 tests/tpack.lua | 322 +++++++++++
43 tests/tracegc.lua | 40 ++
44 tests/utf8.lua | 247 ++++++++
45 tests/vararg.lua | 151 +++++
46 tests/verybig.lua | 152 +++++
47 33 files changed, 16190 insertions(+)
48
49 diff --git a/tests/all.lua b/tests/all.lua
50 new file mode 100644
51 index 0000000..a8e4402
52 --- /dev/null
53 +++ b/tests/all.lua
54 @@ -0,0 +1,311 @@
55 +#!../lua
56 +-- $Id: testes/all.lua $
57 +-- See Copyright Notice at the end of this file
58 +
59 +
60 +local version = "Lua 5.4"
61 +if _VERSION ~= version then
62 + io.stderr:write("This test suite is for ", version,
63 + ", not for ", _VERSION, "\nExiting tests")
64 + return
65 +end
66 +
67 +
68 +_G.ARG = arg -- save arg for other tests
69 +
70 +
71 +-- next variables control the execution of some tests
72 +-- true means no test (so an undefined variable does not skip a test)
73 +-- defaults are for Linux; test everything.
74 +-- Make true to avoid long or memory consuming tests
75 +_soft = rawget(_G, "_soft") or false
76 +-- Make true to avoid non-portable tests
77 +_port = rawget(_G, "_port") or false
78 +-- Make true to avoid messages about tests not performed
79 +_nomsg = rawget(_G, "_nomsg") or false
80 +
81 +
82 +local usertests = rawget(_G, "_U")
83 +
84 +if usertests then
85 + -- tests for sissies ;) Avoid problems
86 + _soft = true
87 + _port = true
88 + _nomsg = true
89 +end
90 +
91 +-- tests should require debug when needed
92 +debug = nil
93 +
94 +
95 +if usertests then
96 + T = nil -- no "internal" tests for user tests
97 +else
98 + T = rawget(_G, "T") -- avoid problems with 'strict' module
99 +end
100 +
101 +
102 +--[=[
103 + example of a long [comment],
104 + [[spanning several [lines]]]
105 +
106 +]=]
107 +
108 +print("\n\tStarting Tests")
109 +
110 +do
111 + -- set random seed
112 + local random_x, random_y = math.randomseed()
113 + print(string.format("random seeds: %d, %d", random_x, random_y))
114 +end
115 +
116 +print("current path:\n****" .. package.path .. "****\n")
117 +
118 +
119 +local initclock = os.clock()
120 +local lastclock = initclock
121 +local walltime = os.time()
122 +
123 +local collectgarbage = collectgarbage
124 +
125 +do -- (
126 +
127 +-- track messages for tests not performed
128 +local msgs = {}
129 +function Message (m)
130 + if not _nomsg then
131 + print(m)
132 + msgs[#msgs+1] = string.sub(m, 3, -3)
133 + end
134 +end
135 +
136 +assert(os.setlocale"C")
137 +
138 +local T,print,format,write,assert,type,unpack,floor =
139 + T,print,string.format,io.write,assert,type,table.unpack,math.floor
140 +
141 +-- use K for 1000 and M for 1000000 (not 2^10 -- 2^20)
142 +local function F (m)
143 + local function round (m)
144 + m = m + 0.04999
145 + return format("%.1f", m) -- keep one decimal digit
146 + end
147 + if m < 1000 then return m
148 + else
149 + m = m / 1000
150 + if m < 1000 then return round(m).."K"
151 + else
152 + return round(m/1000).."M"
153 + end
154 + end
155 +end
156 +
157 +local Cstacklevel
158 +
159 +local showmem
160 +if not T then
161 + local max = 0
162 + showmem = function ()
163 + local m = collectgarbage("count") * 1024
164 + max = (m > max) and m or max
165 + print(format(" ---- total memory: %s, max memory: %s ----\n",
166 + F(m), F(max)))
167 + end
168 + Cstacklevel = function () return 0 end -- no info about stack level
169 +else
170 + showmem = function ()
171 + T.checkmemory()
172 + local total, numblocks, maxmem = T.totalmem()
173 + local count = collectgarbage("count")
174 + print(format(
175 + "\n ---- total memory: %s (%.0fK), max use: %s, blocks: %d\n",
176 + F(total), count, F(maxmem), numblocks))
177 + print(format("\t(strings: %d, tables: %d, functions: %d, "..
178 + "\n\tudata: %d, threads: %d)",
179 + T.totalmem"string", T.totalmem"table", T.totalmem"function",
180 + T.totalmem"userdata", T.totalmem"thread"))
181 + end
182 +
183 + Cstacklevel = function ()
184 + local _, _, ncalls = T.stacklevel()
185 + return ncalls -- number of C calls
186 + end
187 +end
188 +
189 +
190 +local Cstack = Cstacklevel()
191 +
192 +--
193 +-- redefine dofile to run files through dump/undump
194 +--
195 +local function report (n) print("\n***** FILE '"..n.."'*****") end
196 +local olddofile = dofile
197 +local dofile = function (n, strip)
198 + showmem()
199 + local c = os.clock()
200 + print(string.format("time: %g (+%g)", c - initclock, c - lastclock))
201 + lastclock = c
202 + report(n)
203 + local f = assert(loadfile(n))
204 + local b = string.dump(f, strip)
205 + f = assert(load(b))
206 + return f()
207 +end
208 +
209 +dofile('main.lua')
210 +
211 +-- trace GC cycles
212 +require"tracegc".start()
213 +
214 +report"gc.lua"
215 +local f = assert(loadfile('gc.lua'))
216 +f()
217 +
218 +dofile('db.lua')
219 +assert(dofile('calls.lua') == deep and deep)
220 +olddofile('strings.lua')
221 +olddofile('literals.lua')
222 +dofile('tpack.lua')
223 +assert(dofile('attrib.lua') == 27)
224 +dofile('gengc.lua')
225 +assert(dofile('locals.lua') == 5)
226 +dofile('constructs.lua')
227 +dofile('code.lua', true)
228 +if not _G._soft then
229 + report('big.lua')
230 + local f = coroutine.wrap(assert(loadfile('big.lua')))
231 + assert(f() == 'b')
232 + assert(f() == 'a')
233 +end
234 +dofile('cstack.lua')
235 +dofile('nextvar.lua')
236 +dofile('pm.lua')
237 +dofile('utf8.lua')
238 +dofile('api.lua')
239 +assert(dofile('events.lua') == 12)
240 +dofile('vararg.lua')
241 +dofile('closure.lua')
242 +dofile('coroutine.lua')
243 +dofile('goto.lua', true)
244 +dofile('errors.lua')
245 +dofile('math.lua')
246 +dofile('sort.lua', true)
247 +dofile('bitwise.lua')
248 +assert(dofile('verybig.lua', true) == 10); collectgarbage()
249 +dofile('files.lua')
250 +
251 +if #msgs > 0 then
252 + local m = table.concat(msgs, "\n ")
253 + warn("#tests not performed:\n ", m, "\n")
254 +end
255 +
256 +print("(there should be two warnings now)")
257 +warn("@on")
258 +warn("#This is ", "an expected", " warning")
259 +warn("@off")
260 +warn("******** THIS WARNING SHOULD NOT APPEAR **********")
261 +warn("******** THIS WARNING ALSO SHOULD NOT APPEAR **********")
262 +warn("@on")
263 +warn("#This is", " another one")
264 +
265 +-- no test module should define 'debug'
266 +assert(debug == nil)
267 +
268 +local debug = require "debug"
269 +
270 +print(string.format("%d-bit integers, %d-bit floats",
271 + string.packsize("j") * 8, string.packsize("n") * 8))
272 +
273 +debug.sethook(function (a) assert(type(a) == 'string') end, "cr")
274 +
275 +-- to survive outside block
276 +_G.showmem = showmem
277 +
278 +
279 +assert(Cstack == Cstacklevel(),
280 + "should be at the same C-stack level it was when started the tests")
281 +
282 +end --)
283 +
284 +local _G, showmem, print, format, clock, time, difftime,
285 + assert, open, warn =
286 + _G, showmem, print, string.format, os.clock, os.time, os.difftime,
287 + assert, io.open, warn
288 +
289 +-- file with time of last performed test
290 +local fname = T and "time-debug.txt" or "time.txt"
291 +local lasttime
292 +
293 +if not usertests then
294 + -- open file with time of last performed test
295 + local f = io.open(fname)
296 + if f then
297 + lasttime = assert(tonumber(f:read'a'))
298 + f:close();
299 + else -- no such file; assume it is recording time for first time
300 + lasttime = nil
301 + end
302 +end
303 +
304 +-- erase (almost) all globals
305 +print('cleaning all!!!!')
306 +for n in pairs(_G) do
307 + if not ({___Glob = 1, tostring = 1})[n] then
308 + _G[n] = undef
309 + end
310 +end
311 +
312 +
313 +collectgarbage()
314 +collectgarbage()
315 +collectgarbage()
316 +collectgarbage()
317 +collectgarbage()
318 +collectgarbage();showmem()
319 +
320 +local clocktime = clock() - initclock
321 +walltime = difftime(time(), walltime)
322 +
323 +print(format("\n\ntotal time: %.2fs (wall time: %gs)\n", clocktime, walltime))
324 +
325 +if not usertests then
326 + lasttime = lasttime or clocktime -- if no last time, ignore difference
327 + -- check whether current test time differs more than 5% from last time
328 + local diff = (clocktime - lasttime) / lasttime
329 + local tolerance = 0.05 -- 5%
330 + if (diff >= tolerance or diff <= -tolerance) then
331 + warn(format("#time difference from previous test: %+.1f%%",
332 + diff * 100))
333 + end
334 + assert(open(fname, "w")):write(clocktime):close()
335 +end
336 +
337 +print("final OK !!!")
338 +
339 +
340 +
341 +--[[
342 +*****************************************************************************
343 +* Copyright (C) 1994-2016 Lua.org, PUC-Rio.
344 +*
345 +* Permission is hereby granted, free of charge, to any person obtaining
346 +* a copy of this software and associated documentation files (the
347 +* "Software"), to deal in the Software without restriction, including
348 +* without limitation the rights to use, copy, modify, merge, publish,
349 +* distribute, sublicense, and/or sell copies of the Software, and to
350 +* permit persons to whom the Software is furnished to do so, subject to
351 +* the following conditions:
352 +*
353 +* The above copyright notice and this permission notice shall be
354 +* included in all copies or substantial portions of the Software.
355 +*
356 +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
357 +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
358 +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
359 +* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
360 +* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
361 +* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
362 +* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
363 +*****************************************************************************
364 +]]
365 +
366
367 diff --git a/tests/api.lua b/tests/api.lua
368 new file mode 100644
369 index 0000000..bd85a92
370 --- /dev/null
371 +++ b/tests/api.lua
372 @@ -0,0 +1,1533 @@
373 +-- $Id: testes/api.lua $
374 +-- See Copyright Notice in file all.lua
375 +
376 +if T==nil then
377 + (Message or print)('\n >>> testC not active: skipping API tests <<<\n')
378 + return
379 +end
380 +
381 +local debug = require "debug"
382 +
383 +local pack = table.pack
384 +
385 +
386 +-- standard error message for memory errors
387 +local MEMERRMSG = "not enough memory"
388 +
389 +function tcheck (t1, t2)
390 + assert(t1.n == (t2.n or #t2) + 1)
391 + for i = 2, t1.n do assert(t1[i] == t2[i - 1]) end
392 +end
393 +
394 +
395 +local function checkerr (msg, f, ...)
396 + local stat, err = pcall(f, ...)
397 + assert(not stat and string.find(err, msg))
398 +end
399 +
400 +
401 +print('testing C API')
402 +
403 +a = T.testC("pushvalue R; return 1")
404 +assert(a == debug.getregistry())
405 +
406 +
407 +-- absindex
408 +assert(T.testC("settop 10; absindex -1; return 1") == 10)
409 +assert(T.testC("settop 5; absindex -5; return 1") == 1)
410 +assert(T.testC("settop 10; absindex 1; return 1") == 1)
411 +assert(T.testC("settop 10; absindex R; return 1") < -10)
412 +
413 +-- testing alignment
414 +a = T.d2s(12458954321123.0)
415 +assert(a == string.pack("d", 12458954321123.0))
416 +assert(T.s2d(a) == 12458954321123.0)
417 +
418 +a,b,c = T.testC("pushnum 1; pushnum 2; pushnum 3; return 2")
419 +assert(a == 2 and b == 3 and not c)
420 +
421 +f = T.makeCfunc("pushnum 1; pushnum 2; pushnum 3; return 2")
422 +a,b,c = f()
423 +assert(a == 2 and b == 3 and not c)
424 +
425 +-- test that all trues are equal
426 +a,b,c = T.testC("pushbool 1; pushbool 2; pushbool 0; return 3")
427 +assert(a == b and a == true and c == false)
428 +a,b,c = T.testC"pushbool 0; pushbool 10; pushnil;\
429 + tobool -3; tobool -3; tobool -3; return 3"
430 +assert(a==false and b==true and c==false)
431 +
432 +
433 +a,b,c = T.testC("gettop; return 2", 10, 20, 30, 40)
434 +assert(a == 40 and b == 5 and not c)
435 +
436 +t = pack(T.testC("settop 5; return *", 2, 3))
437 +tcheck(t, {n=4,2,3})
438 +
439 +t = pack(T.testC("settop 0; settop 15; return 10", 3, 1, 23))
440 +assert(t.n == 10 and t[1] == nil and t[10] == nil)
441 +
442 +t = pack(T.testC("remove -2; return *", 2, 3, 4))
443 +tcheck(t, {n=2,2,4})
444 +
445 +t = pack(T.testC("insert -1; return *", 2, 3))
446 +tcheck(t, {n=2,2,3})
447 +
448 +t = pack(T.testC("insert 3; return *", 2, 3, 4, 5))
449 +tcheck(t, {n=4,2,5,3,4})
450 +
451 +t = pack(T.testC("replace 2; return *", 2, 3, 4, 5))
452 +tcheck(t, {n=3,5,3,4})
453 +
454 +t = pack(T.testC("replace -2; return *", 2, 3, 4, 5))
455 +tcheck(t, {n=3,2,3,5})
456 +
457 +t = pack(T.testC("remove 3; return *", 2, 3, 4, 5))
458 +tcheck(t, {n=3,2,4,5})
459 +
460 +t = pack(T.testC("copy 3 4; return *", 2, 3, 4, 5))
461 +tcheck(t, {n=4,2,3,3,5})
462 +
463 +t = pack(T.testC("copy -3 -1; return *", 2, 3, 4, 5))
464 +tcheck(t, {n=4,2,3,4,3})
465 +
466 +do -- testing 'rotate'
467 + local t = {10, 20, 30, 40, 50, 60}
468 + for i = -6, 6 do
469 + local s = string.format("rotate 2 %d; return 7", i)
470 + local t1 = pack(T.testC(s, 10, 20, 30, 40, 50, 60))
471 + tcheck(t1, t)
472 + table.insert(t, 1, table.remove(t))
473 + end
474 +
475 + t = pack(T.testC("rotate -2 1; return *", 10, 20, 30, 40))
476 + tcheck(t, {10, 20, 40, 30})
477 + t = pack(T.testC("rotate -2 -1; return *", 10, 20, 30, 40))
478 + tcheck(t, {10, 20, 40, 30})
479 +
480 + -- some corner cases
481 + t = pack(T.testC("rotate -1 0; return *", 10, 20, 30, 40))
482 + tcheck(t, {10, 20, 30, 40})
483 + t = pack(T.testC("rotate -1 1; return *", 10, 20, 30, 40))
484 + tcheck(t, {10, 20, 30, 40})
485 + t = pack(T.testC("rotate 5 -1; return *", 10, 20, 30, 40))
486 + tcheck(t, {10, 20, 30, 40})
487 +end
488 +
489 +
490 +-- testing warnings
491 +T.testC([[
492 + warningC "#This shold be a"
493 + warningC " single "
494 + warning "warning"
495 + warningC "#This should be "
496 + warning "another one"
497 +]])
498 +
499 +
500 +-- testing message handlers
501 +do
502 + local f = T.makeCfunc[[
503 + getglobal error
504 + pushstring bola
505 + pcall 1 1 1 # call 'error' with given handler
506 + pushstatus
507 + return 2 # return error message and status
508 + ]]
509 +
510 + local msg, st = f(string.upper) -- function handler
511 + assert(st == "ERRRUN" and msg == "BOLA")
512 + local msg, st = f(string.len) -- function handler
513 + assert(st == "ERRRUN" and msg == 4)
514 +
515 +end
516 +
517 +t = pack(T.testC("insert 3; pushvalue 3; remove 3; pushvalue 2; remove 2; \
518 + insert 2; pushvalue 1; remove 1; insert 1; \
519 + insert -2; pushvalue -2; remove -3; return *",
520 + 2, 3, 4, 5, 10, 40, 90))
521 +tcheck(t, {n=7,2,3,4,5,10,40,90})
522 +
523 +t = pack(T.testC("concat 5; return *", "alo", 2, 3, "joao", 12))
524 +tcheck(t, {n=1,"alo23joao12"})
525 +
526 +-- testing MULTRET
527 +t = pack(T.testC("call 2,-1; return *",
528 + function (a,b) return 1,2,3,4,a,b end, "alo", "joao"))
529 +tcheck(t, {n=6,1,2,3,4,"alo", "joao"})
530 +
531 +do -- test returning more results than fit in the caller stack
532 + local a = {}
533 + for i=1,1000 do a[i] = true end; a[999] = 10
534 + local b = T.testC([[pcall 1 -1 0; pop 1; tostring -1; return 1]],
535 + table.unpack, a)
536 + assert(b == "10")
537 +end
538 +
539 +
540 +-- testing globals
541 +_G.a = 14; _G.b = "a31"
542 +local a = {T.testC[[
543 + getglobal a;
544 + getglobal b;
545 + getglobal b;
546 + setglobal a;
547 + return *
548 +]]}
549 +assert(a[2] == 14 and a[3] == "a31" and a[4] == nil and _G.a == "a31")
550 +
551 +
552 +-- testing arith
553 +assert(T.testC("pushnum 10; pushnum 20; arith /; return 1") == 0.5)
554 +assert(T.testC("pushnum 10; pushnum 20; arith -; return 1") == -10)
555 +assert(T.testC("pushnum 10; pushnum -20; arith *; return 1") == -200)
556 +assert(T.testC("pushnum 10; pushnum 3; arith ^; return 1") == 1000)
557 +assert(T.testC("pushnum 10; pushstring 20; arith /; return 1") == 0.5)
558 +assert(T.testC("pushstring 10; pushnum 20; arith -; return 1") == -10)
559 +assert(T.testC("pushstring 10; pushstring -20; arith *; return 1") == -200)
560 +assert(T.testC("pushstring 10; pushstring 3; arith ^; return 1") == 1000)
561 +assert(T.testC("arith /; return 1", 2, 0) == 10.0/0)
562 +a = T.testC("pushnum 10; pushint 3; arith \\; return 1")
563 +assert(a == 3.0 and math.type(a) == "float")
564 +a = T.testC("pushint 10; pushint 3; arith \\; return 1")
565 +assert(a == 3 and math.type(a) == "integer")
566 +a = assert(T.testC("pushint 10; pushint 3; arith +; return 1"))
567 +assert(a == 13 and math.type(a) == "integer")
568 +a = assert(T.testC("pushnum 10; pushint 3; arith +; return 1"))
569 +assert(a == 13 and math.type(a) == "float")
570 +a,b,c = T.testC([[pushnum 1;
571 + pushstring 10; arith _;
572 + pushstring 5; return 3]])
573 +assert(a == 1 and b == -10 and c == "5")
574 +mt = {__add = function (a,b) return setmetatable({a[1] + b[1]}, mt) end,
575 + __mod = function (a,b) return setmetatable({a[1] % b[1]}, mt) end,
576 + __unm = function (a) return setmetatable({a[1]* 2}, mt) end}
577 +a,b,c = setmetatable({4}, mt),
578 + setmetatable({8}, mt),
579 + setmetatable({-3}, mt)
580 +x,y,z = T.testC("arith +; return 2", 10, a, b)
581 +assert(x == 10 and y[1] == 12 and z == nil)
582 +assert(T.testC("arith %; return 1", a, c)[1] == 4%-3)
583 +assert(T.testC("arith _; arith +; arith %; return 1", b, a, c)[1] ==
584 + 8 % (4 + (-3)*2))
585 +
586 +-- errors in arithmetic
587 +checkerr("divide by zero", T.testC, "arith \\", 10, 0)
588 +checkerr("%%0", T.testC, "arith %", 10, 0)
589 +
590 +
591 +-- testing lessthan and lessequal
592 +assert(T.testC("compare LT 2 5, return 1", 3, 2, 2, 4, 2, 2))
593 +assert(T.testC("compare LE 2 5, return 1", 3, 2, 2, 4, 2, 2))
594 +assert(not T.testC("compare LT 3 4, return 1", 3, 2, 2, 4, 2, 2))
595 +assert(T.testC("compare LE 3 4, return 1", 3, 2, 2, 4, 2, 2))
596 +assert(T.testC("compare LT 5 2, return 1", 4, 2, 2, 3, 2, 2))
597 +assert(not T.testC("compare LT 2 -3, return 1", "4", "2", "2", "3", "2", "2"))
598 +assert(not T.testC("compare LT -3 2, return 1", "3", "2", "2", "4", "2", "2"))
599 +
600 +-- non-valid indices produce false
601 +assert(not T.testC("compare LT 1 4, return 1"))
602 +assert(not T.testC("compare LE 9 1, return 1"))
603 +assert(not T.testC("compare EQ 9 9, return 1"))
604 +
605 +local b = {__lt = function (a,b) return a[1] < b[1] end}
606 +local a1,a3,a4 = setmetatable({1}, b),
607 + setmetatable({3}, b),
608 + setmetatable({4}, b)
609 +assert(T.testC("compare LT 2 5, return 1", a3, 2, 2, a4, 2, 2))
610 +assert(T.testC("compare LE 2 5, return 1", a3, 2, 2, a4, 2, 2))
611 +assert(T.testC("compare LT 5 -6, return 1", a4, 2, 2, a3, 2, 2))
612 +a,b = T.testC("compare LT 5 -6, return 2", a1, 2, 2, a3, 2, 20)
613 +assert(a == 20 and b == false)
614 +a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a3, 2, 20)
615 +assert(a == 20 and b == false)
616 +a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a1, 2, 20)
617 +assert(a == 20 and b == true)
618 +
619 +
620 +do -- testing lessthan and lessequal with metamethods
621 + local mt = {__lt = function (a,b) return a[1] < b[1] end,
622 + __le = function (a,b) return a[1] <= b[1] end,
623 + __eq = function (a,b) return a[1] == b[1] end}
624 + local function O (x)
625 + return setmetatable({x}, mt)
626 + end
627 +
628 + local a, b = T.testC("compare LT 2 3; pushint 10; return 2", O(1), O(2))
629 + assert(a == true and b == 10)
630 + local a, b = T.testC("compare LE 2 3; pushint 10; return 2", O(3), O(2))
631 + assert(a == false and b == 10)
632 + local a, b = T.testC("compare EQ 2 3; pushint 10; return 2", O(3), O(3))
633 + assert(a == true and b == 10)
634 +end
635 +
636 +-- testing length
637 +local t = setmetatable({x = 20}, {__len = function (t) return t.x end})
638 +a,b,c = T.testC([[
639 + len 2;
640 + Llen 2;
641 + objsize 2;
642 + return 3
643 +]], t)
644 +assert(a == 20 and b == 20 and c == 0)
645 +
646 +t.x = "234"; t[1] = 20
647 +a,b,c = T.testC([[
648 + len 2;
649 + Llen 2;
650 + objsize 2;
651 + return 3
652 +]], t)
653 +assert(a == "234" and b == 234 and c == 1)
654 +
655 +t.x = print; t[1] = 20
656 +a,c = T.testC([[
657 + len 2;
658 + objsize 2;
659 + return 2
660 +]], t)
661 +assert(a == print and c == 1)
662 +
663 +
664 +-- testing __concat
665 +
666 +a = setmetatable({x="u"}, {__concat = function (a,b) return a.x..'.'..b.x end})
667 +x,y = T.testC([[
668 + pushnum 5
669 + pushvalue 2;
670 + pushvalue 2;
671 + concat 2;
672 + pushvalue -2;
673 + return 2;
674 +]], a, a)
675 +assert(x == a..a and y == 5)
676 +
677 +-- concat with 0 elements
678 +assert(T.testC("concat 0; return 1") == "")
679 +
680 +-- concat with 1 element
681 +assert(T.testC("concat 1; return 1", "xuxu") == "xuxu")
682 +
683 +
684 +
685 +-- testing lua_is
686 +
687 +function B(x) return x and 1 or 0 end
688 +
689 +function count (x, n)
690 + n = n or 2
691 + local prog = [[
692 + isnumber %d;
693 + isstring %d;
694 + isfunction %d;
695 + iscfunction %d;
696 + istable %d;
697 + isuserdata %d;
698 + isnil %d;
699 + isnull %d;
700 + return 8
701 + ]]
702 + prog = string.format(prog, n, n, n, n, n, n, n, n)
703 + local a,b,c,d,e,f,g,h = T.testC(prog, x)
704 + return B(a)+B(b)+B(c)+B(d)+B(e)+B(f)+B(g)+(100*B(h))
705 +end
706 +
707 +assert(count(3) == 2)
708 +assert(count('alo') == 1)
709 +assert(count('32') == 2)
710 +assert(count({}) == 1)
711 +assert(count(print) == 2)
712 +assert(count(function () end) == 1)
713 +assert(count(nil) == 1)
714 +assert(count(io.stdin) == 1)
715 +assert(count(nil, 15) == 100)
716 +
717 +
718 +-- testing lua_to...
719 +
720 +function to (s, x, n)
721 + n = n or 2
722 + return T.testC(string.format("%s %d; return 1", s, n), x)
723 +end
724 +
725 +local null = T.pushuserdata(0)
726 +local hfunc = string.gmatch("", "") -- a "heavy C function" (with upvalues)
727 +assert(debug.getupvalue(hfunc, 1))
728 +assert(to("tostring", {}) == nil)
729 +assert(to("tostring", "alo") == "alo")
730 +assert(to("tostring", 12) == "12")
731 +assert(to("tostring", 12, 3) == nil)
732 +assert(to("objsize", {}) == 0)
733 +assert(to("objsize", {1,2,3}) == 3)
734 +assert(to("objsize", "alo\0\0a") == 6)
735 +assert(to("objsize", T.newuserdata(0)) == 0)
736 +assert(to("objsize", T.newuserdata(101)) == 101)
737 +assert(to("objsize", 124) == 0)
738 +assert(to("objsize", true) == 0)
739 +assert(to("tonumber", {}) == 0)
740 +assert(to("tonumber", "12") == 12)
741 +assert(to("tonumber", "s2") == 0)
742 +assert(to("tonumber", 1, 20) == 0)
743 +assert(to("topointer", 10) == null)
744 +assert(to("topointer", true) == null)
745 +assert(to("topointer", nil) == null)
746 +assert(to("topointer", "abc") ~= null)
747 +assert(to("topointer", string.rep("x", 10)) ==
748 + to("topointer", string.rep("x", 10))) -- short strings
749 +do -- long strings
750 + local s1 = string.rep("x", 300)
751 + local s2 = string.rep("x", 300)
752 + assert(to("topointer", s1) ~= to("topointer", s2))
753 +end
754 +assert(to("topointer", T.pushuserdata(20)) ~= null)
755 +assert(to("topointer", io.read) ~= null) -- light C function
756 +assert(to("topointer", hfunc) ~= null) -- "heavy" C function
757 +assert(to("topointer", function () end) ~= null) -- Lua function
758 +assert(to("topointer", io.stdin) ~= null) -- full userdata
759 +assert(to("func2num", 20) == 0)
760 +assert(to("func2num", T.pushuserdata(10)) == 0)
761 +assert(to("func2num", io.read) ~= 0) -- light C function
762 +assert(to("func2num", hfunc) ~= 0) -- "heavy" C function (with upvalue)
763 +a = to("tocfunction", math.deg)
764 +assert(a(3) == math.deg(3) and a == math.deg)
765 +
766 +
767 +print("testing panic function")
768 +do
769 + -- trivial error
770 + assert(T.checkpanic("pushstring hi; error") == "hi")
771 +
772 + -- using the stack inside panic
773 + assert(T.checkpanic("pushstring hi; error;",
774 + [[checkstack 5 XX
775 + pushstring ' alo'
776 + pushstring ' mundo'
777 + concat 3]]) == "hi alo mundo")
778 +
779 + -- "argerror" without frames
780 + assert(T.checkpanic("loadstring 4") ==
781 + "bad argument #4 (string expected, got no value)")
782 +
783 +
784 + -- memory error
785 + T.totalmem(T.totalmem()+10000) -- set low memory limit (+10k)
786 + assert(T.checkpanic("newuserdata 20000") == MEMERRMSG)
787 + T.totalmem(0) -- restore high limit
788 +
789 + -- stack error
790 + if not _soft then
791 + local msg = T.checkpanic[[
792 + pushstring "function f() f() end"
793 + loadstring -1; call 0 0
794 + getglobal f; call 0 0
795 + ]]
796 + assert(string.find(msg, "stack overflow"))
797 + end
798 +
799 + -- exit in panic still close to-be-closed variables
800 + assert(T.checkpanic([[
801 + pushstring "return {__close = function () Y = 'ho'; end}"
802 + newtable
803 + loadstring -2
804 + call 0 1
805 + setmetatable -2
806 + toclose -1
807 + pushstring "hi"
808 + error
809 + ]],
810 + [[
811 + getglobal Y
812 + concat 2 # concat original error with global Y
813 + ]]) == "hiho")
814 +
815 +
816 +end
817 +
818 +-- testing deep C stack
819 +if not _soft then
820 + print("testing stack overflow")
821 + collectgarbage("stop")
822 + checkerr("XXXX", T.testC, "checkstack 1000023 XXXX") -- too deep
823 + -- too deep (with no message)
824 + checkerr("^stack overflow$", T.testC, "checkstack 1000023 ''")
825 + local s = string.rep("pushnil;checkstack 1 XX;", 1000000)
826 + checkerr("overflow", T.testC, s)
827 + collectgarbage("restart")
828 + print'+'
829 +end
830 +
831 +local lim = _soft and 500 or 12000
832 +local prog = {"checkstack " .. (lim * 2 + 100) .. "msg", "newtable"}
833 +for i = 1,lim do
834 + prog[#prog + 1] = "pushnum " .. i
835 + prog[#prog + 1] = "pushnum " .. i * 10
836 +end
837 +
838 +prog[#prog + 1] = "rawgeti R 2" -- get global table in registry
839 +prog[#prog + 1] = "insert " .. -(2*lim + 2)
840 +
841 +for i = 1,lim do
842 + prog[#prog + 1] = "settable " .. -(2*(lim - i + 1) + 1)
843 +end
844 +
845 +prog[#prog + 1] = "return 2"
846 +
847 +prog = table.concat(prog, ";")
848 +local g, t = T.testC(prog)
849 +assert(g == _G)
850 +for i = 1,lim do assert(t[i] == i*10); t[i] = undef end
851 +assert(next(t) == nil)
852 +prog, g, t = nil
853 +
854 +-- testing errors
855 +
856 +a = T.testC([[
857 + loadstring 2; pcall 0 1 0;
858 + pushvalue 3; insert -2; pcall 1 1 0;
859 + pcall 0 0 0;
860 + return 1
861 +]], "x=150", function (a) assert(a==nil); return 3 end)
862 +
863 +assert(type(a) == 'string' and x == 150)
864 +
865 +function check3(p, ...)
866 + local arg = {...}
867 + assert(#arg == 3)
868 + assert(string.find(arg[3], p))
869 +end
870 +check3(":1:", T.testC("loadstring 2; return *", "x="))
871 +check3("%.", T.testC("loadfile 2; return *", "."))
872 +check3("xxxx", T.testC("loadfile 2; return *", "xxxx"))
873 +
874 +-- test errors in non protected threads
875 +function checkerrnopro (code, msg)
876 + local th = coroutine.create(function () end) -- create new thread
877 + local stt, err = pcall(T.testC, th, code) -- run code there
878 + assert(not stt and string.find(err, msg))
879 +end
880 +
881 +if not _soft then
882 + collectgarbage("stop") -- avoid __gc with full stack
883 + checkerrnopro("pushnum 3; call 0 0", "attempt to call")
884 + print"testing stack overflow in unprotected thread"
885 + function f () f() end
886 + checkerrnopro("getglobal 'f'; call 0 0;", "stack overflow")
887 + collectgarbage("restart")
888 +end
889 +print"+"
890 +
891 +
892 +-- testing table access
893 +
894 +do -- getp/setp
895 + local a = {}
896 + local a1 = T.testC("rawsetp 2 1; return 1", a, 20)
897 + assert(a == a1)
898 + assert(a[T.pushuserdata(1)] == 20)
899 + local a1, res = T.testC("rawgetp -1 1; return 2", a)
900 + assert(a == a1 and res == 20)
901 +end
902 +
903 +
904 +do -- using the table itself as index
905 + local a = {}
906 + a[a] = 10
907 + local prog = "gettable -1; return *"
908 + local res = {T.testC(prog, a)}
909 + assert(#res == 2 and res[1] == prog and res[2] == 10)
910 +
911 + local prog = "settable -2; return *"
912 + local res = {T.testC(prog, a, 20)}
913 + assert(a[a] == 20)
914 + assert(#res == 1 and res[1] == prog)
915 +
916 + -- raw
917 + a[a] = 10
918 + local prog = "rawget -1; return *"
919 + local res = {T.testC(prog, a)}
920 + assert(#res == 2 and res[1] == prog and res[2] == 10)
921 +
922 + local prog = "rawset -2; return *"
923 + local res = {T.testC(prog, a, 20)}
924 + assert(a[a] == 20)
925 + assert(#res == 1 and res[1] == prog)
926 +
927 + -- using the table as the value to set
928 + local prog = "rawset -1; return *"
929 + local res = {T.testC(prog, 30, a)}
930 + assert(a[30] == a)
931 + assert(#res == 1 and res[1] == prog)
932 +
933 + local prog = "settable -1; return *"
934 + local res = {T.testC(prog, 40, a)}
935 + assert(a[40] == a)
936 + assert(#res == 1 and res[1] == prog)
937 +
938 + local prog = "rawseti -1 100; return *"
939 + local res = {T.testC(prog, a)}
940 + assert(a[100] == a)
941 + assert(#res == 1 and res[1] == prog)
942 +
943 + local prog = "seti -1 200; return *"
944 + local res = {T.testC(prog, a)}
945 + assert(a[200] == a)
946 + assert(#res == 1 and res[1] == prog)
947 +end
948 +
949 +a = {x=0, y=12}
950 +x, y = T.testC("gettable 2; pushvalue 4; gettable 2; return 2",
951 + a, 3, "y", 4, "x")
952 +assert(x == 0 and y == 12)
953 +T.testC("settable -5", a, 3, 4, "x", 15)
954 +assert(a.x == 15)
955 +a[a] = print
956 +x = T.testC("gettable 2; return 1", a) -- table and key are the same object!
957 +assert(x == print)
958 +T.testC("settable 2", a, "x") -- table and key are the same object!
959 +assert(a[a] == "x")
960 +
961 +b = setmetatable({p = a}, {})
962 +getmetatable(b).__index = function (t, i) return t.p[i] end
963 +k, x = T.testC("gettable 3, return 2", 4, b, 20, 35, "x")
964 +assert(x == 15 and k == 35)
965 +k = T.testC("getfield 2 y, return 1", b)
966 +assert(k == 12)
967 +getmetatable(b).__index = function (t, i) return a[i] end
968 +getmetatable(b).__newindex = function (t, i,v ) a[i] = v end
969 +y = T.testC("insert 2; gettable -5; return 1", 2, 3, 4, "y", b)
970 +assert(y == 12)
971 +k = T.testC("settable -5, return 1", b, 3, 4, "x", 16)
972 +assert(a.x == 16 and k == 4)
973 +a[b] = 'xuxu'
974 +y = T.testC("gettable 2, return 1", b)
975 +assert(y == 'xuxu')
976 +T.testC("settable 2", b, 19)
977 +assert(a[b] == 19)
978 +
979 +--
980 +do -- testing getfield/setfield with long keys
981 + local t = {_012345678901234567890123456789012345678901234567890123456789 = 32}
982 + local a = T.testC([[
983 + getfield 2 _012345678901234567890123456789012345678901234567890123456789
984 + return 1
985 + ]], t)
986 + assert(a == 32)
987 + local a = T.testC([[
988 + pushnum 33
989 + setglobal _012345678901234567890123456789012345678901234567890123456789
990 + ]])
991 + assert(_012345678901234567890123456789012345678901234567890123456789 == 33)
992 + _012345678901234567890123456789012345678901234567890123456789 = nil
993 +end
994 +
995 +-- testing next
996 +a = {}
997 +t = pack(T.testC("next; return *", a, nil))
998 +tcheck(t, {n=1,a})
999 +a = {a=3}
1000 +t = pack(T.testC("next; return *", a, nil))
1001 +tcheck(t, {n=3,a,'a',3})
1002 +t = pack(T.testC("next; pop 1; next; return *", a, nil))
1003 +tcheck(t, {n=1,a})
1004 +
1005 +
1006 +
1007 +-- testing upvalues
1008 +
1009 +do
1010 + local A = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
1011 + t, b, c = A([[pushvalue U0; pushvalue U1; pushvalue U2; return 3]])
1012 + assert(b == 10 and c == 20 and type(t) == 'table')
1013 + a, b = A([[tostring U3; tonumber U4; return 2]])
1014 + assert(a == nil and b == 0)
1015 + A([[pushnum 100; pushnum 200; replace U2; replace U1]])
1016 + b, c = A([[pushvalue U1; pushvalue U2; return 2]])
1017 + assert(b == 100 and c == 200)
1018 + A([[replace U2; replace U1]], {x=1}, {x=2})
1019 + b, c = A([[pushvalue U1; pushvalue U2; return 2]])
1020 + assert(b.x == 1 and c.x == 2)
1021 + T.checkmemory()
1022 +end
1023 +
1024 +
1025 +-- testing absent upvalues from C-function pointers
1026 +assert(T.testC[[isnull U1; return 1]] == true)
1027 +assert(T.testC[[isnull U100; return 1]] == true)
1028 +assert(T.testC[[pushvalue U1; return 1]] == nil)
1029 +
1030 +local f = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
1031 +assert(T.upvalue(f, 1) == 10 and
1032 + T.upvalue(f, 2) == 20 and
1033 + T.upvalue(f, 3) == nil)
1034 +T.upvalue(f, 2, "xuxu")
1035 +assert(T.upvalue(f, 2) == "xuxu")
1036 +
1037 +
1038 +-- large closures
1039 +do
1040 + local A = "checkstack 300 msg;" ..
1041 + string.rep("pushnum 10;", 255) ..
1042 + "pushcclosure 255; return 1"
1043 + A = T.testC(A)
1044 + for i=1,255 do
1045 + assert(A(("pushvalue U%d; return 1"):format(i)) == 10)
1046 + end
1047 + assert(A("isnull U256; return 1"))
1048 + assert(not A("isnil U256; return 1"))
1049 +end
1050 +
1051 +
1052 +
1053 +-- testing get/setuservalue
1054 +-- bug in 5.1.2
1055 +checkerr("got number", debug.setuservalue, 3, {})
1056 +checkerr("got nil", debug.setuservalue, nil, {})
1057 +checkerr("got light userdata", debug.setuservalue, T.pushuserdata(1), {})
1058 +
1059 +-- testing multiple user values
1060 +local b = T.newuserdata(0, 10)
1061 +for i = 1, 10 do
1062 + local v, p = debug.getuservalue(b, i)
1063 + assert(v == nil and p)
1064 +end
1065 +do -- indices out of range
1066 + local v, p = debug.getuservalue(b, -2)
1067 + assert(v == nil and not p)
1068 + local v, p = debug.getuservalue(b, 11)
1069 + assert(v == nil and not p)
1070 +end
1071 +local t = {true, false, 4.56, print, {}, b, "XYZ"}
1072 +for k, v in ipairs(t) do
1073 + debug.setuservalue(b, v, k)
1074 +end
1075 +for k, v in ipairs(t) do
1076 + local v1, p = debug.getuservalue(b, k)
1077 + assert(v1 == v and p)
1078 +end
1079 +
1080 +assert(not debug.getuservalue(4))
1081 +
1082 +debug.setuservalue(b, function () return 10 end, 10)
1083 +collectgarbage() -- function should not be collected
1084 +assert(debug.getuservalue(b, 10)() == 10)
1085 +
1086 +debug.setuservalue(b, 134)
1087 +collectgarbage() -- number should not be a problem for collector
1088 +assert(debug.getuservalue(b) == 134)
1089 +
1090 +
1091 +-- test barrier for uservalues
1092 +do
1093 + local oldmode = collectgarbage("incremental")
1094 + T.gcstate("atomic")
1095 + assert(T.gccolor(b) == "black")
1096 + debug.setuservalue(b, {x = 100})
1097 + T.gcstate("pause") -- complete collection
1098 + assert(debug.getuservalue(b).x == 100) -- uvalue should be there
1099 + collectgarbage(oldmode)
1100 +end
1101 +
1102 +-- long chain of userdata
1103 +for i = 1, 1000 do
1104 + local bb = T.newuserdata(0, 1)
1105 + debug.setuservalue(bb, b)
1106 + b = bb
1107 +end
1108 +collectgarbage() -- nothing should not be collected
1109 +for i = 1, 1000 do
1110 + b = debug.getuservalue(b)
1111 +end
1112 +assert(debug.getuservalue(b).x == 100)
1113 +b = nil
1114 +
1115 +
1116 +-- testing locks (refs)
1117 +
1118 +-- reuse of references
1119 +local i = T.ref{}
1120 +T.unref(i)
1121 +assert(T.ref{} == i)
1122 +
1123 +Arr = {}
1124 +Lim = 100
1125 +for i=1,Lim do -- lock many objects
1126 + Arr[i] = T.ref({})
1127 +end
1128 +
1129 +assert(T.ref(nil) == -1 and T.getref(-1) == nil)
1130 +T.unref(-1); T.unref(-1)
1131 +
1132 +for i=1,Lim do -- unlock all them
1133 + T.unref(Arr[i])
1134 +end
1135 +
1136 +function printlocks ()
1137 + local f = T.makeCfunc("gettable R; return 1")
1138 + local n = f("n")
1139 + print("n", n)
1140 + for i=0,n do
1141 + print(i, f(i))
1142 + end
1143 +end
1144 +
1145 +
1146 +for i=1,Lim do -- lock many objects
1147 + Arr[i] = T.ref({})
1148 +end
1149 +
1150 +for i=1,Lim,2 do -- unlock half of them
1151 + T.unref(Arr[i])
1152 +end
1153 +
1154 +assert(type(T.getref(Arr[2])) == 'table')
1155 +
1156 +
1157 +assert(T.getref(-1) == nil)
1158 +
1159 +
1160 +a = T.ref({})
1161 +
1162 +collectgarbage()
1163 +
1164 +assert(type(T.getref(a)) == 'table')
1165 +
1166 +
1167 +-- colect in cl the `val' of all collected userdata
1168 +tt = {}
1169 +cl = {n=0}
1170 +A = nil; B = nil
1171 +local F
1172 +F = function (x)
1173 + local udval = T.udataval(x)
1174 + table.insert(cl, udval)
1175 + local d = T.newuserdata(100) -- create garbage
1176 + d = nil
1177 + assert(debug.getmetatable(x).__gc == F)
1178 + assert(load("table.insert({}, {})"))() -- create more garbage
1179 + assert(not collectgarbage()) -- GC during GC (no op)
1180 + local dummy = {} -- create more garbage during GC
1181 + if A ~= nil then
1182 + assert(type(A) == "userdata")
1183 + assert(T.udataval(A) == B)
1184 + debug.getmetatable(A) -- just access it
1185 + end
1186 + A = x -- ressurect userdata
1187 + B = udval
1188 + return 1,2,3
1189 +end
1190 +tt.__gc = F
1191 +
1192 +-- test whether udate collection frees memory in the right time
1193 +do
1194 + collectgarbage();
1195 + collectgarbage();
1196 + local x = collectgarbage("count");
1197 + local a = T.newuserdata(5001)
1198 + assert(T.testC("objsize 2; return 1", a) == 5001)
1199 + assert(collectgarbage("count") >= x+4)
1200 + a = nil
1201 + collectgarbage();
1202 + assert(collectgarbage("count") <= x+1)
1203 + -- udata without finalizer
1204 + x = collectgarbage("count")
1205 + collectgarbage("stop")
1206 + for i=1,1000 do T.newuserdata(0) end
1207 + assert(collectgarbage("count") > x+10)
1208 + collectgarbage()
1209 + assert(collectgarbage("count") <= x+1)
1210 + -- udata with finalizer
1211 + collectgarbage()
1212 + x = collectgarbage("count")
1213 + collectgarbage("stop")
1214 + a = {__gc = function () end}
1215 + for i=1,1000 do debug.setmetatable(T.newuserdata(0), a) end
1216 + assert(collectgarbage("count") >= x+10)
1217 + collectgarbage() -- this collection only calls TM, without freeing memory
1218 + assert(collectgarbage("count") >= x+10)
1219 + collectgarbage() -- now frees memory
1220 + assert(collectgarbage("count") <= x+1)
1221 + collectgarbage("restart")
1222 +end
1223 +
1224 +
1225 +collectgarbage("stop")
1226 +
1227 +-- create 3 userdatas with tag `tt'
1228 +a = T.newuserdata(0); debug.setmetatable(a, tt); na = T.udataval(a)
1229 +b = T.newuserdata(0); debug.setmetatable(b, tt); nb = T.udataval(b)
1230 +c = T.newuserdata(0); debug.setmetatable(c, tt); nc = T.udataval(c)
1231 +
1232 +-- create userdata without meta table
1233 +x = T.newuserdata(4)
1234 +y = T.newuserdata(0)
1235 +
1236 +checkerr("FILE%* expected, got userdata", io.input, a)
1237 +checkerr("FILE%* expected, got userdata", io.input, x)
1238 +
1239 +assert(debug.getmetatable(x) == nil and debug.getmetatable(y) == nil)
1240 +
1241 +d=T.ref(a);
1242 +e=T.ref(b);
1243 +f=T.ref(c);
1244 +t = {T.getref(d), T.getref(e), T.getref(f)}
1245 +assert(t[1] == a and t[2] == b and t[3] == c)
1246 +
1247 +t=nil; a=nil; c=nil;
1248 +T.unref(e); T.unref(f)
1249 +
1250 +collectgarbage()
1251 +
1252 +-- check that unref objects have been collected
1253 +assert(#cl == 1 and cl[1] == nc)
1254 +
1255 +x = T.getref(d)
1256 +assert(type(x) == 'userdata' and debug.getmetatable(x) == tt)
1257 +x =nil
1258 +tt.b = b -- create cycle
1259 +tt=nil -- frees tt for GC
1260 +A = nil
1261 +b = nil
1262 +T.unref(d);
1263 +n5 = T.newuserdata(0)
1264 +debug.setmetatable(n5, {__gc=F})
1265 +n5 = T.udataval(n5)
1266 +collectgarbage()
1267 +assert(#cl == 4)
1268 +-- check order of collection
1269 +assert(cl[2] == n5 and cl[3] == nb and cl[4] == na)
1270 +
1271 +collectgarbage"restart"
1272 +
1273 +
1274 +a, na = {}, {}
1275 +for i=30,1,-1 do
1276 + a[i] = T.newuserdata(0)
1277 + debug.setmetatable(a[i], {__gc=F})
1278 + na[i] = T.udataval(a[i])
1279 +end
1280 +cl = {}
1281 +a = nil; collectgarbage()
1282 +assert(#cl == 30)
1283 +for i=1,30 do assert(cl[i] == na[i]) end
1284 +na = nil
1285 +
1286 +
1287 +for i=2,Lim,2 do -- unlock the other half
1288 + T.unref(Arr[i])
1289 +end
1290 +
1291 +x = T.newuserdata(41); debug.setmetatable(x, {__gc=F})
1292 +assert(T.testC("objsize 2; return 1", x) == 41)
1293 +cl = {}
1294 +a = {[x] = 1}
1295 +x = T.udataval(x)
1296 +collectgarbage()
1297 +-- old `x' cannot be collected (`a' still uses it)
1298 +assert(#cl == 0)
1299 +for n in pairs(a) do a[n] = undef end
1300 +collectgarbage()
1301 +assert(#cl == 1 and cl[1] == x) -- old `x' must be collected
1302 +
1303 +-- testing lua_equal
1304 +assert(T.testC("compare EQ 2 4; return 1", print, 1, print, 20))
1305 +assert(T.testC("compare EQ 3 2; return 1", 'alo', "alo"))
1306 +assert(T.testC("compare EQ 2 3; return 1", nil, nil))
1307 +assert(not T.testC("compare EQ 2 3; return 1", {}, {}))
1308 +assert(not T.testC("compare EQ 2 3; return 1"))
1309 +assert(not T.testC("compare EQ 2 3; return 1", 3))
1310 +
1311 +-- testing lua_equal with fallbacks
1312 +do
1313 + local map = {}
1314 + local t = {__eq = function (a,b) return map[a] == map[b] end}
1315 + local function f(x)
1316 + local u = T.newuserdata(0)
1317 + debug.setmetatable(u, t)
1318 + map[u] = x
1319 + return u
1320 + end
1321 + assert(f(10) == f(10))
1322 + assert(f(10) ~= f(11))
1323 + assert(T.testC("compare EQ 2 3; return 1", f(10), f(10)))
1324 + assert(not T.testC("compare EQ 2 3; return 1", f(10), f(20)))
1325 + t.__eq = nil
1326 + assert(f(10) ~= f(10))
1327 +end
1328 +
1329 +print'+'
1330 +
1331 +
1332 +
1333 +-- testing changing hooks during hooks
1334 +_G.t = {}
1335 +T.sethook([[
1336 + # set a line hook after 3 count hooks
1337 + sethook 4 0 '
1338 + getglobal t;
1339 + pushvalue -3; append -2
1340 + pushvalue -2; append -2
1341 + ']], "c", 3)
1342 +local a = 1 -- counting
1343 +a = 1 -- counting
1344 +a = 1 -- count hook (set line hook)
1345 +a = 1 -- line hook
1346 +a = 1 -- line hook
1347 +debug.sethook()
1348 +t = _G.t
1349 +assert(t[1] == "line")
1350 +line = t[2]
1351 +assert(t[3] == "line" and t[4] == line + 1)
1352 +assert(t[5] == "line" and t[6] == line + 2)
1353 +assert(t[7] == nil)
1354 +
1355 +
1356 +-------------------------------------------------------------------------
1357 +do -- testing errors during GC
1358 + warn("@off")
1359 + collectgarbage("stop")
1360 + local a = {}
1361 + for i=1,20 do
1362 + a[i] = T.newuserdata(i) -- creates several udata
1363 + end
1364 + for i=1,20,2 do -- mark half of them to raise errors during GC
1365 + debug.setmetatable(a[i],
1366 + {__gc = function (x) error("@expected error in gc") end})
1367 + end
1368 + for i=2,20,2 do -- mark the other half to count and to create more garbage
1369 + debug.setmetatable(a[i], {__gc = function (x) load("A=A+1")() end})
1370 + end
1371 + a = nil
1372 + _G.A = 0
1373 + collectgarbage()
1374 + assert(A == 10) -- number of normal collections
1375 + collectgarbage("restart")
1376 + warn("@on")
1377 +end
1378 +-------------------------------------------------------------------------
1379 +-- test for userdata vals
1380 +do
1381 + local a = {}; local lim = 30
1382 + for i=0,lim do a[i] = T.pushuserdata(i) end
1383 + for i=0,lim do assert(T.udataval(a[i]) == i) end
1384 + for i=0,lim do assert(T.pushuserdata(i) == a[i]) end
1385 + for i=0,lim do a[a[i]] = i end
1386 + for i=0,lim do a[T.pushuserdata(i)] = i end
1387 + assert(type(tostring(a[1])) == "string")
1388 +end
1389 +
1390 +
1391 +-------------------------------------------------------------------------
1392 +-- testing multiple states
1393 +T.closestate(T.newstate());
1394 +L1 = T.newstate()
1395 +assert(L1)
1396 +
1397 +assert(T.doremote(L1, "X='a'; return 'a'") == 'a')
1398 +
1399 +
1400 +assert(#pack(T.doremote(L1, "function f () return 'alo', 3 end; f()")) == 0)
1401 +
1402 +a, b = T.doremote(L1, "return f()")
1403 +assert(a == 'alo' and b == '3')
1404 +
1405 +T.doremote(L1, "_ERRORMESSAGE = nil")
1406 +-- error: `sin' is not defined
1407 +a, _, b = T.doremote(L1, "return sin(1)")
1408 +assert(a == nil and b == 2) -- 2 == run-time error
1409 +
1410 +-- error: syntax error
1411 +a, b, c = T.doremote(L1, "return a+")
1412 +assert(a == nil and c == 3 and type(b) == "string") -- 3 == syntax error
1413 +
1414 +T.loadlib(L1)
1415 +a, b, c = T.doremote(L1, [[
1416 + string = require'string'
1417 + a = require'_G'; assert(a == _G and require("_G") == a)
1418 + io = require'io'; assert(type(io.read) == "function")
1419 + assert(require("io") == io)
1420 + a = require'table'; assert(type(a.insert) == "function")
1421 + a = require'debug'; assert(type(a.getlocal) == "function")
1422 + a = require'math'; assert(type(a.sin) == "function")
1423 + return string.sub('okinama', 1, 2)
1424 +]])
1425 +assert(a == "ok")
1426 +
1427 +T.closestate(L1);
1428 +
1429 +
1430 +L1 = T.newstate()
1431 +T.loadlib(L1)
1432 +T.doremote(L1, "a = {}")
1433 +T.testC(L1, [[getglobal "a"; pushstring "x"; pushint 1;
1434 + settable -3]])
1435 +assert(T.doremote(L1, "return a.x") == "1")
1436 +
1437 +T.closestate(L1)
1438 +
1439 +L1 = nil
1440 +
1441 +print('+')
1442 +-------------------------------------------------------------------------
1443 +-- testing to-be-closed variables
1444 +-------------------------------------------------------------------------
1445 +print"testing to-be-closed variables"
1446 +
1447 +do
1448 + local openresource = {}
1449 +
1450 + local function newresource ()
1451 + local x = setmetatable({10}, {__close = function(y)
1452 + assert(openresource[#openresource] == y)
1453 + openresource[#openresource] = nil
1454 + y[1] = y[1] + 1
1455 + end})
1456 + openresource[#openresource + 1] = x
1457 + return x
1458 + end
1459 +
1460 + local a, b = T.testC([[
1461 + call 0 1 # create resource
1462 + pushnil
1463 + toclose -2 # mark call result to be closed
1464 + toclose -1 # mark nil to be closed (will be ignored)
1465 + return 2
1466 + ]], newresource)
1467 + assert(a[1] == 11 and b == nil)
1468 + assert(#openresource == 0) -- was closed
1469 +
1470 + -- repeat the test, but calling function in a 'multret' context
1471 + local a = {T.testC([[
1472 + call 0 1 # create resource
1473 + toclose 2 # mark it to be closed
1474 + return 2
1475 + ]], newresource)}
1476 + assert(type(a[1]) == "string" and a[2][1] == 11)
1477 + assert(#openresource == 0) -- was closed
1478 +
1479 + -- closing by error
1480 + local a, b = pcall(T.makeCfunc[[
1481 + call 0 1 # create resource
1482 + toclose -1 # mark it to be closed
1483 + error # resource is the error object
1484 + ]], newresource)
1485 + assert(a == false and b[1] == 11)
1486 + assert(#openresource == 0) -- was closed
1487 +
1488 + -- non-closable value
1489 + local a, b = pcall(T.makeCfunc[[
1490 + newtable # create non-closable object
1491 + toclose -1 # mark it to be closed (should raise an error)
1492 + abort # will not be executed
1493 + ]])
1494 + assert(a == false and
1495 + string.find(b, "non%-closable value"))
1496 +
1497 + local function check (n)
1498 + assert(#openresource == n)
1499 + end
1500 +
1501 + -- closing resources with 'closeslot'
1502 + _ENV.xxx = true
1503 + local a = T.testC([[
1504 + pushvalue 2 # stack: S, NR, CH, NR
1505 + call 0 1 # create resource; stack: S, NR, CH, R
1506 + toclose -1 # mark it to be closed
1507 + pushvalue 2 # stack: S, NR, CH, R, NR
1508 + call 0 1 # create another resource; stack: S, NR, CH, R, R
1509 + toclose -1 # mark it to be closed
1510 + pushvalue 3 # stack: S, NR, CH, R, R, CH
1511 + pushint 2 # there should be two open resources
1512 + call 1 0 # stack: S, NR, CH, R, R
1513 + closeslot -1 # close second resource
1514 + pushvalue 3 # stack: S, NR, CH, R, R, CH
1515 + pushint 1 # there should be one open resource
1516 + call 1 0 # stack: S, NR, CH, R, R
1517 + closeslot 4
1518 + setglobal "xxx" # previous op. erased the slot
1519 + pop 1 # pop other resource from the stack
1520 + pushint *
1521 + return 1 # return stack size
1522 + ]], newresource, check)
1523 + assert(a == 3 and _ENV.xxx == nil) -- no extra items left in the stack
1524 +
1525 + -- closing resources with 'pop'
1526 + local a = T.testC([[
1527 + pushvalue 2 # stack: S, NR, CH, NR
1528 + call 0 1 # create resource; stack: S, NR, CH, R
1529 + toclose -1 # mark it to be closed
1530 + pushvalue 2 # stack: S, NR, CH, R, NR
1531 + call 0 1 # create another resource; stack: S, NR, CH, R, R
1532 + toclose -1 # mark it to be closed
1533 + pushvalue 3 # stack: S, NR, CH, R, R, CH
1534 + pushint 2 # there should be two open resources
1535 + call 1 0 # stack: S, NR, CH, R, R
1536 + pop 1 # pop second resource
1537 + pushvalue 3 # stack: S, NR, CH, R, CH
1538 + pushint 1 # there should be one open resource
1539 + call 1 0 # stack: S, NR, CH, R
1540 + pop 1 # pop other resource from the stack
1541 + pushvalue 3 # stack: S, NR, CH, CH
1542 + pushint 0 # there should be no open resources
1543 + call 1 0 # stack: S, NR, CH
1544 + pushint *
1545 + return 1 # return stack size
1546 + ]], newresource, check)
1547 + assert(a == 3) -- no extra items left in the stack
1548 +
1549 + -- non-closable value
1550 + local a, b = pcall(T.makeCfunc[[
1551 + pushint 32
1552 + toclose -1
1553 + ]])
1554 + assert(not a and string.find(b, "(C temporary)"))
1555 +
1556 +end
1557 +
1558 +
1559 +--[[
1560 +** {==================================================================
1561 +** Testing memory limits
1562 +** ===================================================================
1563 +--]]
1564 +
1565 +print("memory-allocation errors")
1566 +
1567 +checkerr("block too big", T.newuserdata, math.maxinteger)
1568 +collectgarbage()
1569 +local f = load"local a={}; for i=1,100000 do a[i]=i end"
1570 +T.alloccount(10)
1571 +checkerr(MEMERRMSG, f)
1572 +T.alloccount() -- remove limit
1573 +
1574 +
1575 +-- test memory errors; increase limit for maximum memory by steps,
1576 +-- o that we get memory errors in all allocations of a given
1577 +-- task, until there is enough memory to complete the task without
1578 +-- errors.
1579 +function testbytes (s, f)
1580 + collectgarbage()
1581 + local M = T.totalmem()
1582 + local oldM = M
1583 + local a,b = nil
1584 + while true do
1585 + collectgarbage(); collectgarbage()
1586 + T.totalmem(M)
1587 + a, b = T.testC("pcall 0 1 0; pushstatus; return 2", f)
1588 + T.totalmem(0) -- remove limit
1589 + if a and b == "OK" then break end -- stop when no more errors
1590 + if b ~= "OK" and b ~= MEMERRMSG then -- not a memory error?
1591 + error(a, 0) -- propagate it
1592 + end
1593 + M = M + 7 -- increase memory limit
1594 + end
1595 + print(string.format("minimum memory for %s: %d bytes", s, M - oldM))
1596 + return a
1597 +end
1598 +
1599 +-- test memory errors; increase limit for number of allocations one
1600 +-- by one, so that we get memory errors in all allocations of a given
1601 +-- task, until there is enough allocations to complete the task without
1602 +-- errors.
1603 +
1604 +function testalloc (s, f)
1605 + collectgarbage()
1606 + local M = 0
1607 + local a,b = nil
1608 + while true do
1609 + collectgarbage(); collectgarbage()
1610 + T.alloccount(M)
1611 + a, b = T.testC("pcall 0 1 0; pushstatus; return 2", f)
1612 + T.alloccount() -- remove limit
1613 + if a and b == "OK" then break end -- stop when no more errors
1614 + if b ~= "OK" and b ~= MEMERRMSG then -- not a memory error?
1615 + error(a, 0) -- propagate it
1616 + end
1617 + M = M + 1 -- increase allocation limit
1618 + end
1619 + print(string.format("minimum allocations for %s: %d allocations", s, M))
1620 + return a
1621 +end
1622 +
1623 +
1624 +local function testamem (s, f)
1625 + testalloc(s, f)
1626 + return testbytes(s, f)
1627 +end
1628 +
1629 +
1630 +-- doing nothing
1631 +b = testamem("doing nothing", function () return 10 end)
1632 +assert(b == 10)
1633 +
1634 +-- testing memory errors when creating a new state
1635 +
1636 +testamem("state creation", function ()
1637 + local st = T.newstate()
1638 + if st then T.closestate(st) end -- close new state
1639 + return st
1640 +end)
1641 +
1642 +testamem("empty-table creation", function ()
1643 + return {}
1644 +end)
1645 +
1646 +testamem("string creation", function ()
1647 + return "XXX" .. "YYY"
1648 +end)
1649 +
1650 +testamem("coroutine creation", function()
1651 + return coroutine.create(print)
1652 +end)
1653 +
1654 +
1655 +-- testing to-be-closed variables
1656 +testamem("to-be-closed variables", function()
1657 + local flag
1658 + do
1659 + local x <close> =
1660 + setmetatable({}, {__close = function () flag = true end})
1661 + flag = false
1662 + local x = {}
1663 + end
1664 + return flag
1665 +end)
1666 +
1667 +
1668 +-- testing threads
1669 +
1670 +-- get main thread from registry (at index LUA_RIDX_MAINTHREAD == 1)
1671 +mt = T.testC("rawgeti R 1; return 1")
1672 +assert(type(mt) == "thread" and coroutine.running() == mt)
1673 +
1674 +
1675 +
1676 +function expand (n,s)
1677 + if n==0 then return "" end
1678 + local e = string.rep("=", n)
1679 + return string.format("T.doonnewstack([%s[ %s;\n collectgarbage(); %s]%s])\n",
1680 + e, s, expand(n-1,s), e)
1681 +end
1682 +
1683 +G=0; collectgarbage(); a =collectgarbage("count")
1684 +load(expand(20,"G=G+1"))()
1685 +assert(G==20); collectgarbage(); -- assert(gcinfo() <= a+1)
1686 +
1687 +testamem("running code on new thread", function ()
1688 + return T.doonnewstack("x=1") == 0 -- try to create thread
1689 +end)
1690 +
1691 +
1692 +-- testing memory x compiler
1693 +
1694 +testamem("loadstring", function ()
1695 + return load("x=1") -- try to do load a string
1696 +end)
1697 +
1698 +
1699 +local testprog = [[
1700 +local function foo () return end
1701 +local t = {"x"}
1702 +a = "aaa"
1703 +for i = 1, #t do a=a..t[i] end
1704 +return true
1705 +]]
1706 +
1707 +-- testing memory x dofile
1708 +_G.a = nil
1709 +local t =os.tmpname()
1710 +local f = assert(io.open(t, "w"))
1711 +f:write(testprog)
1712 +f:close()
1713 +testamem("dofile", function ()
1714 + local a = loadfile(t)
1715 + return a and a()
1716 +end)
1717 +assert(os.remove(t))
1718 +assert(_G.a == "aaax")
1719 +
1720 +
1721 +-- other generic tests
1722 +
1723 +testamem("gsub", function ()
1724 + local a, b = string.gsub("alo alo", "(a)", function (x) return x..'b' end)
1725 + return (a == 'ablo ablo')
1726 +end)
1727 +
1728 +testamem("dump/undump", function ()
1729 + local a = load(testprog)
1730 + local b = a and string.dump(a)
1731 + a = b and load(b)
1732 + return a and a()
1733 +end)
1734 +
1735 +local t = os.tmpname()
1736 +testamem("file creation", function ()
1737 + local f = assert(io.open(t, 'w'))
1738 + assert (not io.open"nomenaoexistente")
1739 + io.close(f);
1740 + return not loadfile'nomenaoexistente'
1741 +end)
1742 +assert(os.remove(t))
1743 +
1744 +testamem("table creation", function ()
1745 + local a, lim = {}, 10
1746 + for i=1,lim do a[i] = i; a[i..'a'] = {} end
1747 + return (type(a[lim..'a']) == 'table' and a[lim] == lim)
1748 +end)
1749 +
1750 +testamem("constructors", function ()
1751 + local a = {10, 20, 30, 40, 50; a=1, b=2, c=3, d=4, e=5}
1752 + return (type(a) == 'table' and a.e == 5)
1753 +end)
1754 +
1755 +local a = 1
1756 +close = nil
1757 +testamem("closure creation", function ()
1758 + function close (b)
1759 + return function (x) return b + x end
1760 + end
1761 + return (close(2)(4) == 6)
1762 +end)
1763 +
1764 +testamem("using coroutines", function ()
1765 + local a = coroutine.wrap(function ()
1766 + coroutine.yield(string.rep("a", 10))
1767 + return {}
1768 + end)
1769 + assert(string.len(a()) == 10)
1770 + return a()
1771 +end)
1772 +
1773 +do -- auxiliary buffer
1774 + local lim = 100
1775 + local a = {}; for i = 1, lim do a[i] = "01234567890123456789" end
1776 + testamem("auxiliary buffer", function ()
1777 + return (#table.concat(a, ",") == 20*lim + lim - 1)
1778 + end)
1779 +end
1780 +
1781 +testamem("growing stack", function ()
1782 + local function foo (n)
1783 + if n == 0 then return 1 else return 1 + foo(n - 1) end
1784 + end
1785 + return foo(100)
1786 +end)
1787 +
1788 +-- }==================================================================
1789 +
1790 +
1791 +do -- testing failing in 'lua_checkstack'
1792 + local res = T.testC([[rawcheckstack 500000; return 1]])
1793 + assert(res == false)
1794 + local L = T.newstate()
1795 + T.alloccount(0) -- will be unable to reallocate the stack
1796 + res = T.testC(L, [[rawcheckstack 5000; return 1]])
1797 + T.alloccount()
1798 + T.closestate(L)
1799 + assert(res == false)
1800 +end
1801 +
1802 +do -- closing state with no extra memory
1803 + local L = T.newstate()
1804 + T.alloccount(0)
1805 + T.closestate(L)
1806 + T.alloccount()
1807 +end
1808 +
1809 +do -- garbage collection with no extra memory
1810 + local L = T.newstate()
1811 + T.loadlib(L)
1812 + local res = (T.doremote(L, [[
1813 + _ENV = require"_G"
1814 + local T = require"T"
1815 + local a = {}
1816 + for i = 1, 1000 do a[i] = 'i' .. i end -- grow string table
1817 + local stsize, stuse = T.querystr()
1818 + assert(stuse > 1000)
1819 + local function foo (n)
1820 + if n > 0 then foo(n - 1) end
1821 + end
1822 + foo(180) -- grow stack
1823 + local _, stksize = T.stacklevel()
1824 + assert(stksize > 180)
1825 + a = nil
1826 + T.alloccount(0)
1827 + collectgarbage()
1828 + T.alloccount()
1829 + -- stack and string table could not be reallocated,
1830 + -- so they kept their sizes (without errors)
1831 + assert(select(2, T.stacklevel()) == stksize)
1832 + assert(T.querystr() == stsize)
1833 + return 'ok'
1834 + ]]))
1835 + assert(res == 'ok')
1836 + T.closestate(L)
1837 +end
1838 +
1839 +print'+'
1840 +
1841 +-- testing some auxlib functions
1842 +local function gsub (a, b, c)
1843 + a, b = T.testC("gsub 2 3 4; gettop; return 2", a, b, c)
1844 + assert(b == 5)
1845 + return a
1846 +end
1847 +
1848 +assert(gsub("alo.alo.uhuh.", ".", "//") == "alo//alo//uhuh//")
1849 +assert(gsub("alo.alo.uhuh.", "alo", "//") == "//.//.uhuh.")
1850 +assert(gsub("", "alo", "//") == "")
1851 +assert(gsub("...", ".", "/.") == "/././.")
1852 +assert(gsub("...", "...", "") == "")
1853 +
1854 +
1855 +-- testing luaL_newmetatable
1856 +local mt_xuxu, res, top = T.testC("newmetatable xuxu; gettop; return 3")
1857 +assert(type(mt_xuxu) == "table" and res and top == 3)
1858 +local d, res, top = T.testC("newmetatable xuxu; gettop; return 3")
1859 +assert(mt_xuxu == d and not res and top == 3)
1860 +d, res, top = T.testC("newmetatable xuxu1; gettop; return 3")
1861 +assert(mt_xuxu ~= d and res and top == 3)
1862 +
1863 +x = T.newuserdata(0);
1864 +y = T.newuserdata(0);
1865 +T.testC("pushstring xuxu; gettable R; setmetatable 2", x)
1866 +assert(getmetatable(x) == mt_xuxu)
1867 +
1868 +-- testing luaL_testudata
1869 +-- correct metatable
1870 +local res1, res2, top = T.testC([[testudata -1 xuxu
1871 + testudata 2 xuxu
1872 + gettop
1873 + return 3]], x)
1874 +assert(res1 and res2 and top == 4)
1875 +
1876 +-- wrong metatable
1877 +res1, res2, top = T.testC([[testudata -1 xuxu1
1878 + testudata 2 xuxu1
1879 + gettop
1880 + return 3]], x)
1881 +assert(not res1 and not res2 and top == 4)
1882 +
1883 +-- non-existent type
1884 +res1, res2, top = T.testC([[testudata -1 xuxu2
1885 + testudata 2 xuxu2
1886 + gettop
1887 + return 3]], x)
1888 +assert(not res1 and not res2 and top == 4)
1889 +
1890 +-- userdata has no metatable
1891 +res1, res2, top = T.testC([[testudata -1 xuxu
1892 + testudata 2 xuxu
1893 + gettop
1894 + return 3]], y)
1895 +assert(not res1 and not res2 and top == 4)
1896 +
1897 +-- erase metatables
1898 +do
1899 + local r = debug.getregistry()
1900 + assert(r.xuxu == mt_xuxu and r.xuxu1 == d)
1901 + r.xuxu = nil; r.xuxu1 = nil
1902 +end
1903 +
1904 +print'OK'
1905 +
1906
1907 diff --git a/tests/attrib.lua b/tests/attrib.lua
1908 new file mode 100644
1909 index 0000000..b1076c7
1910 --- /dev/null
1911 +++ b/tests/attrib.lua
1912 @@ -0,0 +1,515 @@
1913 +-- $Id: testes/attrib.lua $
1914 +-- See Copyright Notice in file all.lua
1915 +
1916 +print "testing require"
1917 +
1918 +assert(require"string" == string)
1919 +assert(require"math" == math)
1920 +assert(require"table" == table)
1921 +assert(require"io" == io)
1922 +assert(require"os" == os)
1923 +assert(require"coroutine" == coroutine)
1924 +
1925 +assert(type(package.path) == "string")
1926 +assert(type(package.cpath) == "string")
1927 +assert(type(package.loaded) == "table")
1928 +assert(type(package.preload) == "table")
1929 +
1930 +assert(type(package.config) == "string")
1931 +print("package config: "..string.gsub(package.config, "\n", "|"))
1932 +
1933 +do
1934 + -- create a path with 'max' templates,
1935 + -- each with 1-10 repetitions of '?'
1936 + local max = _soft and 100 or 2000
1937 + local t = {}
1938 + for i = 1,max do t[i] = string.rep("?", i%10 + 1) end
1939 + t[#t + 1] = ";" -- empty template
1940 + local path = table.concat(t, ";")
1941 + -- use that path in a search
1942 + local s, err = package.searchpath("xuxu", path)
1943 + -- search fails; check that message has an occurrence of
1944 + -- '??????????' with ? replaced by xuxu and at least 'max' lines
1945 + assert(not s and
1946 + string.find(err, string.rep("xuxu", 10)) and
1947 + #string.gsub(err, "[^\n]", "") >= max)
1948 + -- path with one very long template
1949 + local path = string.rep("?", max)
1950 + local s, err = package.searchpath("xuxu", path)
1951 + assert(not s and string.find(err, string.rep('xuxu', max)))
1952 +end
1953 +
1954 +do
1955 + local oldpath = package.path
1956 + package.path = {}
1957 + local s, err = pcall(require, "no-such-file")
1958 + assert(not s and string.find(err, "package.path"))
1959 + package.path = oldpath
1960 +end
1961 +
1962 +
1963 +do print"testing 'require' message"
1964 + local oldpath = package.path
1965 + local oldcpath = package.cpath
1966 +
1967 + package.path = "?.lua;?/?"
1968 + package.cpath = "?.so;?/init"
1969 +
1970 + local st, msg = pcall(require, 'XXX')
1971 +
1972 + local expected = [[module 'XXX' not found:
1973 + no field package.preload['XXX']
1974 + no file 'XXX.lua'
1975 + no file 'XXX/XXX'
1976 + no file 'XXX.so'
1977 + no file 'XXX/init']]
1978 +
1979 + assert(msg == expected)
1980 +
1981 + package.path = oldpath
1982 + package.cpath = oldcpath
1983 +end
1984 +
1985 +print('+')
1986 +
1987 +
1988 +-- The next tests for 'require' assume some specific directories and
1989 +-- libraries.
1990 +
1991 +if not _port then --[
1992 +
1993 +local dirsep = string.match(package.config, "^([^\n]+)\n")
1994 +
1995 +-- auxiliary directory with C modules and temporary files
1996 +local DIR = "libs" .. dirsep
1997 +
1998 +-- prepend DIR to a name and correct directory separators
1999 +local function D (x)
2000 + x = string.gsub(x, "/", dirsep)
2001 + return DIR .. x
2002 +end
2003 +
2004 +-- prepend DIR and pospend proper C lib. extension to a name
2005 +local function DC (x)
2006 + local ext = (dirsep == '\\') and ".dll" or ".so"
2007 + return D(x .. ext)
2008 +end
2009 +
2010 +
2011 +local function createfiles (files, preextras, posextras)
2012 + for n,c in pairs(files) do
2013 + io.output(D(n))
2014 + io.write(string.format(preextras, n))
2015 + io.write(c)
2016 + io.write(string.format(posextras, n))
2017 + io.close(io.output())
2018 + end
2019 +end
2020 +
2021 +function removefiles (files)
2022 + for n in pairs(files) do
2023 + os.remove(D(n))
2024 + end
2025 +end
2026 +
2027 +local files = {
2028 + ["names.lua"] = "do return {...} end\n",
2029 + ["err.lua"] = "B = 15; a = a + 1;",
2030 + ["synerr.lua"] = "B =",
2031 + ["A.lua"] = "",
2032 + ["B.lua"] = "assert(...=='B');require 'A'",
2033 + ["A.lc"] = "",
2034 + ["A"] = "",
2035 + ["L"] = "",
2036 + ["XXxX"] = "",
2037 + ["C.lua"] = "package.loaded[...] = 25; require'C'",
2038 +}
2039 +
2040 +AA = nil
2041 +local extras = [[
2042 +NAME = '%s'
2043 +REQUIRED = ...
2044 +return AA]]
2045 +
2046 +createfiles(files, "", extras)
2047 +
2048 +-- testing explicit "dir" separator in 'searchpath'
2049 +assert(package.searchpath("C.lua", D"?", "", "") == D"C.lua")
2050 +assert(package.searchpath("C.lua", D"?", ".", ".") == D"C.lua")
2051 +assert(package.searchpath("--x-", D"?", "-", "X") == D"XXxX")
2052 +assert(package.searchpath("---xX", D"?", "---", "XX") == D"XXxX")
2053 +assert(package.searchpath(D"C.lua", "?", dirsep) == D"C.lua")
2054 +assert(package.searchpath(".\\C.lua", D"?", "\\") == D"./C.lua")
2055 +
2056 +local oldpath = package.path
2057 +
2058 +package.path = string.gsub("D/?.lua;D/?.lc;D/?;D/??x?;D/L", "D/", DIR)
2059 +
2060 +local try = function (p, n, r, ext)
2061 + NAME = nil
2062 + local rr, x = require(p)
2063 + assert(NAME == n)
2064 + assert(REQUIRED == p)
2065 + assert(rr == r)
2066 + assert(ext == x)
2067 +end
2068 +
2069 +a = require"names"
2070 +assert(a[1] == "names" and a[2] == D"names.lua")
2071 +
2072 +_G.a = nil
2073 +local st, msg = pcall(require, "err")
2074 +assert(not st and string.find(msg, "arithmetic") and B == 15)
2075 +st, msg = pcall(require, "synerr")
2076 +assert(not st and string.find(msg, "error loading module"))
2077 +
2078 +assert(package.searchpath("C", package.path) == D"C.lua")
2079 +assert(require"C" == 25)
2080 +assert(require"C" == 25)
2081 +AA = nil
2082 +try('B', 'B.lua', true, "libs/B.lua")
2083 +assert(package.loaded.B)
2084 +assert(require"B" == true)
2085 +assert(package.loaded.A)
2086 +assert(require"C" == 25)
2087 +package.loaded.A = nil
2088 +try('B', nil, true, nil) -- should not reload package
2089 +try('A', 'A.lua', true, "libs/A.lua")
2090 +package.loaded.A = nil
2091 +os.remove(D'A.lua')
2092 +AA = {}
2093 +try('A', 'A.lc', AA, "libs/A.lc") -- now must find second option
2094 +assert(package.searchpath("A", package.path) == D"A.lc")
2095 +assert(require("A") == AA)
2096 +AA = false
2097 +try('K', 'L', false, "libs/L") -- default option
2098 +try('K', 'L', false, "libs/L") -- default option (should reload it)
2099 +assert(rawget(_G, "_REQUIREDNAME") == nil)
2100 +
2101 +AA = "x"
2102 +try("X", "XXxX", AA, "libs/XXxX")
2103 +
2104 +
2105 +removefiles(files)
2106 +
2107 +
2108 +-- testing require of sub-packages
2109 +
2110 +local _G = _G
2111 +
2112 +package.path = string.gsub("D/?.lua;D/?/init.lua", "D/", DIR)
2113 +
2114 +files = {
2115 + ["P1/init.lua"] = "AA = 10",
2116 + ["P1/xuxu.lua"] = "AA = 20",
2117 +}
2118 +
2119 +createfiles(files, "_ENV = {}\n", "\nreturn _ENV\n")
2120 +AA = 0
2121 +
2122 +local m, ext = assert(require"P1")
2123 +assert(ext == "libs/P1/init.lua")
2124 +assert(AA == 0 and m.AA == 10)
2125 +assert(require"P1" == m)
2126 +assert(require"P1" == m)
2127 +
2128 +assert(package.searchpath("P1.xuxu", package.path) == D"P1/xuxu.lua")
2129 +m.xuxu, ext = assert(require"P1.xuxu")
2130 +assert(AA == 0 and m.xuxu.AA == 20)
2131 +assert(ext == "libs/P1/xuxu.lua")
2132 +assert(require"P1.xuxu" == m.xuxu)
2133 +assert(require"P1.xuxu" == m.xuxu)
2134 +assert(require"P1" == m and m.AA == 10)
2135 +
2136 +
2137 +removefiles(files)
2138 +
2139 +
2140 +package.path = ""
2141 +assert(not pcall(require, "file_does_not_exist"))
2142 +package.path = "??\0?"
2143 +assert(not pcall(require, "file_does_not_exist1"))
2144 +
2145 +package.path = oldpath
2146 +
2147 +-- check 'require' error message
2148 +local fname = "file_does_not_exist2"
2149 +local m, err = pcall(require, fname)
2150 +for t in string.gmatch(package.path..";"..package.cpath, "[^;]+") do
2151 + t = string.gsub(t, "?", fname)
2152 + assert(string.find(err, t, 1, true))
2153 +end
2154 +
2155 +do -- testing 'package.searchers' not being a table
2156 + local searchers = package.searchers
2157 + package.searchers = 3
2158 + local st, msg = pcall(require, 'a')
2159 + assert(not st and string.find(msg, "must be a table"))
2160 + package.searchers = searchers
2161 +end
2162 +
2163 +local function import(...)
2164 + local f = {...}
2165 + return function (m)
2166 + for i=1, #f do m[f[i]] = _G[f[i]] end
2167 + end
2168 +end
2169 +
2170 +-- cannot change environment of a C function
2171 +assert(not pcall(module, 'XUXU'))
2172 +
2173 +
2174 +
2175 +-- testing require of C libraries
2176 +
2177 +
2178 +local p = "" -- On Mac OS X, redefine this to "_"
2179 +
2180 +-- check whether loadlib works in this system
2181 +local st, err, when = package.loadlib(DC"lib1", "*")
2182 +if not st then
2183 + local f, err, when = package.loadlib("donotexist", p.."xuxu")
2184 + assert(not f and type(err) == "string" and when == "absent")
2185 + ;(Message or print)('\n >>> cannot load dynamic library <<<\n')
2186 + print(err, when)
2187 +else
2188 + -- tests for loadlib
2189 + local f = assert(package.loadlib(DC"lib1", p.."onefunction"))
2190 + local a, b = f(15, 25)
2191 + assert(a == 25 and b == 15)
2192 +
2193 + f = assert(package.loadlib(DC"lib1", p.."anotherfunc"))
2194 + assert(f(10, 20) == "10%20\n")
2195 +
2196 + -- check error messages
2197 + local f, err, when = package.loadlib(DC"lib1", p.."xuxu")
2198 + assert(not f and type(err) == "string" and when == "init")
2199 + f, err, when = package.loadlib("donotexist", p.."xuxu")
2200 + assert(not f and type(err) == "string" and when == "open")
2201 +
2202 + -- symbols from 'lib1' must be visible to other libraries
2203 + f = assert(package.loadlib(DC"lib11", p.."luaopen_lib11"))
2204 + assert(f() == "exported")
2205 +
2206 + -- test C modules with prefixes in names
2207 + package.cpath = DC"?"
2208 + local lib2, ext = require"lib2-v2"
2209 + assert(string.find(ext, "libs/lib2-v2", 1, true))
2210 + -- check correct access to global environment and correct
2211 + -- parameters
2212 + assert(_ENV.x == "lib2-v2" and _ENV.y == DC"lib2-v2")
2213 + assert(lib2.id("x") == true) -- a different "id" implementation
2214 +
2215 + -- test C submodules
2216 + local fs, ext = require"lib1.sub"
2217 + assert(_ENV.x == "lib1.sub" and _ENV.y == DC"lib1")
2218 + assert(string.find(ext, "libs/lib1", 1, true))
2219 + assert(fs.id(45) == 45)
2220 +end
2221 +
2222 +_ENV = _G
2223 +
2224 +
2225 +-- testing preload
2226 +
2227 +do
2228 + local p = package
2229 + package = {}
2230 + p.preload.pl = function (...)
2231 + local _ENV = {...}
2232 + function xuxu (x) return x+20 end
2233 + return _ENV
2234 + end
2235 +
2236 + local pl, ext = require"pl"
2237 + assert(require"pl" == pl)
2238 + assert(pl.xuxu(10) == 30)
2239 + assert(pl[1] == "pl" and pl[2] == ":preload:" and ext == ":preload:")
2240 +
2241 + package = p
2242 + assert(type(package.path) == "string")
2243 +end
2244 +
2245 +print('+')
2246 +
2247 +end --]
2248 +
2249 +print("testing assignments, logical operators, and constructors")
2250 +
2251 +local res, res2 = 27
2252 +
2253 +a, b = 1, 2+3
2254 +assert(a==1 and b==5)
2255 +a={}
2256 +function f() return 10, 11, 12 end
2257 +a.x, b, a[1] = 1, 2, f()
2258 +assert(a.x==1 and b==2 and a[1]==10)
2259 +a[f()], b, a[f()+3] = f(), a, 'x'
2260 +assert(a[10] == 10 and b == a and a[13] == 'x')
2261 +
2262 +do
2263 + local f = function (n) local x = {}; for i=1,n do x[i]=i end;
2264 + return table.unpack(x) end;
2265 + local a,b,c
2266 + a,b = 0, f(1)
2267 + assert(a == 0 and b == 1)
2268 + A,b = 0, f(1)
2269 + assert(A == 0 and b == 1)
2270 + a,b,c = 0,5,f(4)
2271 + assert(a==0 and b==5 and c==1)
2272 + a,b,c = 0,5,f(0)
2273 + assert(a==0 and b==5 and c==nil)
2274 +end
2275 +
2276 +a, b, c, d = 1 and nil, 1 or nil, (1 and (nil or 1)), 6
2277 +assert(not a and b and c and d==6)
2278 +
2279 +d = 20
2280 +a, b, c, d = f()
2281 +assert(a==10 and b==11 and c==12 and d==nil)
2282 +a,b = f(), 1, 2, 3, f()
2283 +assert(a==10 and b==1)
2284 +
2285 +assert(a<b == false and a>b == true)
2286 +assert((10 and 2) == 2)
2287 +assert((10 or 2) == 10)
2288 +assert((10 or assert(nil)) == 10)
2289 +assert(not (nil and assert(nil)))
2290 +assert((nil or "alo") == "alo")
2291 +assert((nil and 10) == nil)
2292 +assert((false and 10) == false)
2293 +assert((true or 10) == true)
2294 +assert((false or 10) == 10)
2295 +assert(false ~= nil)
2296 +assert(nil ~= false)
2297 +assert(not nil == true)
2298 +assert(not not nil == false)
2299 +assert(not not 1 == true)
2300 +assert(not not a == true)
2301 +assert(not not (6 or nil) == true)
2302 +assert(not not (nil and 56) == false)
2303 +assert(not not (nil and true) == false)
2304 +assert(not 10 == false)
2305 +assert(not {} == false)
2306 +assert(not 0.5 == false)
2307 +assert(not "x" == false)
2308 +
2309 +assert({} ~= {})
2310 +print('+')
2311 +
2312 +a = {}
2313 +a[true] = 20
2314 +a[false] = 10
2315 +assert(a[1<2] == 20 and a[1>2] == 10)
2316 +
2317 +function f(a) return a end
2318 +
2319 +local a = {}
2320 +for i=3000,-3000,-1 do a[i + 0.0] = i; end
2321 +a[10e30] = "alo"; a[true] = 10; a[false] = 20
2322 +assert(a[10e30] == 'alo' and a[not 1] == 20 and a[10<20] == 10)
2323 +for i=3000,-3000,-1 do assert(a[i] == i); end
2324 +a[print] = assert
2325 +a[f] = print
2326 +a[a] = a
2327 +assert(a[a][a][a][a][print] == assert)
2328 +a[print](a[a[f]] == a[print])
2329 +assert(not pcall(function () local a = {}; a[nil] = 10 end))
2330 +assert(not pcall(function () local a = {[nil] = 10} end))
2331 +assert(a[nil] == undef)
2332 +a = nil
2333 +
2334 +a = {10,9,8,7,6,5,4,3,2; [-3]='a', [f]=print, a='a', b='ab'}
2335 +a, a.x, a.y = a, a[-3]
2336 +assert(a[1]==10 and a[-3]==a.a and a[f]==print and a.x=='a' and not a.y)
2337 +a[1], f(a)[2], b, c = {['alo']=assert}, 10, a[1], a[f], 6, 10, 23, f(a), 2
2338 +a[1].alo(a[2]==10 and b==10 and c==print)
2339 +
2340 +a.aVeryLongName012345678901234567890123456789012345678901234567890123456789 = 10
2341 +local function foo ()
2342 + return a.aVeryLongName012345678901234567890123456789012345678901234567890123456789
2343 +end
2344 +assert(foo() == 10 and
2345 +a.aVeryLongName012345678901234567890123456789012345678901234567890123456789 ==
2346 +10)
2347 +
2348 +
2349 +
2350 +-- test of large float/integer indices
2351 +
2352 +-- compute maximum integer where all bits fit in a float
2353 +local maxint = math.maxinteger
2354 +
2355 +-- trim (if needed) to fit in a float
2356 +while maxint ~= (maxint + 0.0) or (maxint - 1) ~= (maxint - 1.0) do
2357 + maxint = maxint // 2
2358 +end
2359 +
2360 +maxintF = maxint + 0.0 -- float version
2361 +
2362 +assert(maxintF == maxint and math.type(maxintF) == "float" and
2363 + maxintF >= 2.0^14)
2364 +
2365 +-- floats and integers must index the same places
2366 +a[maxintF] = 10; a[maxintF - 1.0] = 11;
2367 +a[-maxintF] = 12; a[-maxintF + 1.0] = 13;
2368 +
2369 +assert(a[maxint] == 10 and a[maxint - 1] == 11 and
2370 + a[-maxint] == 12 and a[-maxint + 1] == 13)
2371 +
2372 +a[maxint] = 20
2373 +a[-maxint] = 22
2374 +
2375 +assert(a[maxintF] == 20 and a[maxintF - 1.0] == 11 and
2376 + a[-maxintF] == 22 and a[-maxintF + 1.0] == 13)
2377 +
2378 +a = nil
2379 +
2380 +
2381 +-- test conflicts in multiple assignment
2382 +do
2383 + local a,i,j,b
2384 + a = {'a', 'b'}; i=1; j=2; b=a
2385 + i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i
2386 + assert(i == 2 and b[1] == 1 and a == 1 and j == b and b[2] == 2 and
2387 + b[3] == 1)
2388 + a = {}
2389 + local function foo () -- assigining to upvalues
2390 + b, a.x, a = a, 10, 20
2391 + end
2392 + foo()
2393 + assert(a == 20 and b.x == 10)
2394 +end
2395 +
2396 +-- repeat test with upvalues
2397 +do
2398 + local a,i,j,b
2399 + a = {'a', 'b'}; i=1; j=2; b=a
2400 + local function foo ()
2401 + i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i
2402 + end
2403 + foo()
2404 + assert(i == 2 and b[1] == 1 and a == 1 and j == b and b[2] == 2 and
2405 + b[3] == 1)
2406 + local t = {}
2407 + (function (a) t[a], a = 10, 20 end)(1);
2408 + assert(t[1] == 10)
2409 +end
2410 +
2411 +-- bug in 5.2 beta
2412 +local function foo ()
2413 + local a
2414 + return function ()
2415 + local b
2416 + a, b = 3, 14 -- local and upvalue have same index
2417 + return a, b
2418 + end
2419 +end
2420 +
2421 +local a, b = foo()()
2422 +assert(a == 3 and b == 14)
2423 +
2424 +print('OK')
2425 +
2426 +return res
2427 +
2428
2429 diff --git a/tests/big.lua b/tests/big.lua
2430 new file mode 100644
2431 index 0000000..39e293e
2432 --- /dev/null
2433 +++ b/tests/big.lua
2434 @@ -0,0 +1,82 @@
2435 +-- $Id: testes/big.lua $
2436 +-- See Copyright Notice in file all.lua
2437 +
2438 +if _soft then
2439 + return 'a'
2440 +end
2441 +
2442 +print "testing large tables"
2443 +
2444 +local debug = require"debug"
2445 +
2446 +local lim = 2^18 + 1000
2447 +local prog = { "local y = {0" }
2448 +for i = 1, lim do prog[#prog + 1] = i end
2449 +prog[#prog + 1] = "}\n"
2450 +prog[#prog + 1] = "X = y\n"
2451 +prog[#prog + 1] = ("assert(X[%d] == %d)"):format(lim - 1, lim - 2)
2452 +prog[#prog + 1] = "return 0"
2453 +prog = table.concat(prog, ";")
2454 +
2455 +local env = {string = string, assert = assert}
2456 +local f = assert(load(prog, nil, nil, env))
2457 +
2458 +f()
2459 +assert(env.X[lim] == lim - 1 and env.X[lim + 1] == lim)
2460 +for k in pairs(env) do env[k] = undef end
2461 +
2462 +-- yields during accesses larger than K (in RK)
2463 +setmetatable(env, {
2464 + __index = function (t, n) coroutine.yield('g'); return _G[n] end,
2465 + __newindex = function (t, n, v) coroutine.yield('s'); _G[n] = v end,
2466 +})
2467 +
2468 +X = nil
2469 +co = coroutine.wrap(f)
2470 +assert(co() == 's')
2471 +assert(co() == 'g')
2472 +assert(co() == 'g')
2473 +assert(co() == 0)
2474 +
2475 +assert(X[lim] == lim - 1 and X[lim + 1] == lim)
2476 +
2477 +-- errors in accesses larger than K (in RK)
2478 +getmetatable(env).__index = function () end
2479 +getmetatable(env).__newindex = function () end
2480 +local e, m = pcall(f)
2481 +assert(not e and m:find("global 'X'"))
2482 +
2483 +-- errors in metamethods
2484 +getmetatable(env).__newindex = function () error("hi") end
2485 +local e, m = xpcall(f, debug.traceback)
2486 +assert(not e and m:find("'newindex'"))
2487 +
2488 +f, X = nil
2489 +
2490 +coroutine.yield'b'
2491 +
2492 +if 2^32 == 0 then -- (small integers) {
2493 +
2494 +print "testing string length overflow"
2495 +
2496 +local repstrings = 192 -- number of strings to be concatenated
2497 +local ssize = math.ceil(2.0^32 / repstrings) + 1 -- size of each string
2498 +
2499 +assert(repstrings * ssize > 2.0^32) -- it should be larger than maximum size
2500 +
2501 +local longs = string.rep("\0", ssize) -- create one long string
2502 +
2503 +-- create function to concatenate 'repstrings' copies of its argument
2504 +local rep = assert(load(
2505 + "local a = ...; return " .. string.rep("a", repstrings, "..")))
2506 +
2507 +local a, b = pcall(rep, longs) -- call that function
2508 +
2509 +-- it should fail without creating string (result would be too large)
2510 +assert(not a and string.find(b, "overflow"))
2511 +
2512 +end -- }
2513 +
2514 +print'OK'
2515 +
2516 +return 'a'
2517
2518 diff --git a/tests/bitwise.lua b/tests/bitwise.lua
2519 new file mode 100644
2520 index 0000000..9509f7f
2521 --- /dev/null
2522 +++ b/tests/bitwise.lua
2523 @@ -0,0 +1,351 @@
2524 +-- $Id: testes/bitwise.lua $
2525 +-- See Copyright Notice in file all.lua
2526 +
2527 +print("testing bitwise operations")
2528 +
2529 +require "bwcoercion"
2530 +
2531 +local numbits = string.packsize('j') * 8
2532 +
2533 +assert(~0 == -1)
2534 +
2535 +assert((1 << (numbits - 1)) == math.mininteger)
2536 +
2537 +-- basic tests for bitwise operators;
2538 +-- use variables to avoid constant folding
2539 +local a, b, c, d
2540 +a = 0xFFFFFFFFFFFFFFFF
2541 +assert(a == -1 and a & -1 == a and a & 35 == 35)
2542 +a = 0xF0F0F0F0F0F0F0F0
2543 +assert(a | -1 == -1)
2544 +assert(a ~ a == 0 and a ~ 0 == a and a ~ ~a == -1)
2545 +assert(a >> 4 == ~a)
2546 +a = 0xF0; b = 0xCC; c = 0xAA; d = 0xFD
2547 +assert(a | b ~ c & d == 0xF4)
2548 +
2549 +a = 0xF0.0; b = 0xCC.0; c = "0xAA.0"; d = "0xFD.0"
2550 +assert(a | b ~ c & d == 0xF4)
2551 +
2552 +a = 0xF0000000; b = 0xCC000000;
2553 +c = 0xAA000000; d = 0xFD000000
2554 +assert(a | b ~ c & d == 0xF4000000)
2555 +assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1)
2556 +
2557 +a = a << 32
2558 +b = b << 32
2559 +c = c << 32
2560 +d = d << 32
2561 +assert(a | b ~ c & d == 0xF4000000 << 32)
2562 +assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1)
2563 +
2564 +assert(-1 >> 1 == (1 << (numbits - 1)) - 1 and 1 << 31 == 0x80000000)
2565 +assert(-1 >> (numbits - 1) == 1)
2566 +assert(-1 >> numbits == 0 and
2567 + -1 >> -numbits == 0 and
2568 + -1 << numbits == 0 and
2569 + -1 << -numbits == 0)
2570 +
2571 +assert(1 >> math.mininteger == 0)
2572 +assert(1 >> math.maxinteger == 0)
2573 +assert(1 << math.mininteger == 0)
2574 +assert(1 << math.maxinteger == 0)
2575 +
2576 +assert((2^30 - 1) << 2^30 == 0)
2577 +assert((2^30 - 1) >> 2^30 == 0)
2578 +
2579 +assert(1 >> -3 == 1 << 3 and 1000 >> 5 == 1000 << -5)
2580 +
2581 +
2582 +-- coercion from strings to integers
2583 +assert("0xffffffffffffffff" | 0 == -1)
2584 +assert("0xfffffffffffffffe" & "-1" == -2)
2585 +assert(" \t-0xfffffffffffffffe\n\t" & "-1" == 2)
2586 +assert(" \n -45 \t " >> " -2 " == -45 * 4)
2587 +assert("1234.0" << "5.0" == 1234 * 32)
2588 +assert("0xffff.0" ~ "0xAAAA" == 0x5555)
2589 +assert(~"0x0.000p4" == -1)
2590 +
2591 +assert(("7" .. 3) << 1 == 146)
2592 +assert(0xffffffff >> (1 .. "9") == 0x1fff)
2593 +assert(10 | (1 .. "9") == 27)
2594 +
2595 +do
2596 + local st, msg = pcall(function () return 4 & "a" end)
2597 + assert(string.find(msg, "'band'"))
2598 +
2599 + local st, msg = pcall(function () return ~"a" end)
2600 + assert(string.find(msg, "'bnot'"))
2601 +end
2602 +
2603 +
2604 +-- out of range number
2605 +assert(not pcall(function () return "0xffffffffffffffff.0" | 0 end))
2606 +
2607 +-- embedded zeros
2608 +assert(not pcall(function () return "0xffffffffffffffff\0" | 0 end))
2609 +
2610 +print'+'
2611 +
2612 +
2613 +package.preload.bit32 = function () --{
2614 +
2615 +-- no built-in 'bit32' library: implement it using bitwise operators
2616 +
2617 +local bit = {}
2618 +
2619 +function bit.bnot (a)
2620 + return ~a & 0xFFFFFFFF
2621 +end
2622 +
2623 +
2624 +--
2625 +-- in all vararg functions, avoid creating 'arg' table when there are
2626 +-- only 2 (or less) parameters, as 2 parameters is the common case
2627 +--
2628 +
2629 +function bit.band (x, y, z, ...)
2630 + if not z then
2631 + return ((x or -1) & (y or -1)) & 0xFFFFFFFF
2632 + else
2633 + local arg = {...}
2634 + local res = x & y & z
2635 + for i = 1, #arg do res = res & arg[i] end
2636 + return res & 0xFFFFFFFF
2637 + end
2638 +end
2639 +
2640 +function bit.bor (x, y, z, ...)
2641 + if not z then
2642 + return ((x or 0) | (y or 0)) & 0xFFFFFFFF
2643 + else
2644 + local arg = {...}
2645 + local res = x | y | z
2646 + for i = 1, #arg do res = res | arg[i] end
2647 + return res & 0xFFFFFFFF
2648 + end
2649 +end
2650 +
2651 +function bit.bxor (x, y, z, ...)
2652 + if not z then
2653 + return ((x or 0) ~ (y or 0)) & 0xFFFFFFFF
2654 + else
2655 + local arg = {...}
2656 + local res = x ~ y ~ z
2657 + for i = 1, #arg do res = res ~ arg[i] end
2658 + return res & 0xFFFFFFFF
2659 + end
2660 +end
2661 +
2662 +function bit.btest (...)
2663 + return bit.band(...) ~= 0
2664 +end
2665 +
2666 +function bit.lshift (a, b)
2667 + return ((a & 0xFFFFFFFF) << b) & 0xFFFFFFFF
2668 +end
2669 +
2670 +function bit.rshift (a, b)
2671 + return ((a & 0xFFFFFFFF) >> b) & 0xFFFFFFFF
2672 +end
2673 +
2674 +function bit.arshift (a, b)
2675 + a = a & 0xFFFFFFFF
2676 + if b <= 0 or (a & 0x80000000) == 0 then
2677 + return (a >> b) & 0xFFFFFFFF
2678 + else
2679 + return ((a >> b) | ~(0xFFFFFFFF >> b)) & 0xFFFFFFFF
2680 + end
2681 +end
2682 +
2683 +function bit.lrotate (a ,b)
2684 + b = b & 31
2685 + a = a & 0xFFFFFFFF
2686 + a = (a << b) | (a >> (32 - b))
2687 + return a & 0xFFFFFFFF
2688 +end
2689 +
2690 +function bit.rrotate (a, b)
2691 + return bit.lrotate(a, -b)
2692 +end
2693 +
2694 +local function checkfield (f, w)
2695 + w = w or 1
2696 + assert(f >= 0, "field cannot be negative")
2697 + assert(w > 0, "width must be positive")
2698 + assert(f + w <= 32, "trying to access non-existent bits")
2699 + return f, ~(-1 << w)
2700 +end
2701 +
2702 +function bit.extract (a, f, w)
2703 + local f, mask = checkfield(f, w)
2704 + return (a >> f) & mask
2705 +end
2706 +
2707 +function bit.replace (a, v, f, w)
2708 + local f, mask = checkfield(f, w)
2709 + v = v & mask
2710 + a = (a & ~(mask << f)) | (v << f)
2711 + return a & 0xFFFFFFFF
2712 +end
2713 +
2714 +return bit
2715 +
2716 +end --}
2717 +
2718 +
2719 +print("testing bitwise library")
2720 +
2721 +local bit32 = require'bit32'
2722 +
2723 +assert(bit32.band() == bit32.bnot(0))
2724 +assert(bit32.btest() == true)
2725 +assert(bit32.bor() == 0)
2726 +assert(bit32.bxor() == 0)
2727 +
2728 +assert(bit32.band() == bit32.band(0xffffffff))
2729 +assert(bit32.band(1,2) == 0)
2730 +
2731 +
2732 +-- out-of-range numbers
2733 +assert(bit32.band(-1) == 0xffffffff)
2734 +assert(bit32.band((1 << 33) - 1) == 0xffffffff)
2735 +assert(bit32.band(-(1 << 33) - 1) == 0xffffffff)
2736 +assert(bit32.band((1 << 33) + 1) == 1)
2737 +assert(bit32.band(-(1 << 33) + 1) == 1)
2738 +assert(bit32.band(-(1 << 40)) == 0)
2739 +assert(bit32.band(1 << 40) == 0)
2740 +assert(bit32.band(-(1 << 40) - 2) == 0xfffffffe)
2741 +assert(bit32.band((1 << 40) - 4) == 0xfffffffc)
2742 +
2743 +assert(bit32.lrotate(0, -1) == 0)
2744 +assert(bit32.lrotate(0, 7) == 0)
2745 +assert(bit32.lrotate(0x12345678, 0) == 0x12345678)
2746 +assert(bit32.lrotate(0x12345678, 32) == 0x12345678)
2747 +assert(bit32.lrotate(0x12345678, 4) == 0x23456781)
2748 +assert(bit32.rrotate(0x12345678, -4) == 0x23456781)
2749 +assert(bit32.lrotate(0x12345678, -8) == 0x78123456)
2750 +assert(bit32.rrotate(0x12345678, 8) == 0x78123456)
2751 +assert(bit32.lrotate(0xaaaaaaaa, 2) == 0xaaaaaaaa)
2752 +assert(bit32.lrotate(0xaaaaaaaa, -2) == 0xaaaaaaaa)
2753 +for i = -50, 50 do
2754 + assert(bit32.lrotate(0x89abcdef, i) == bit32.lrotate(0x89abcdef, i%32))
2755 +end
2756 +
2757 +assert(bit32.lshift(0x12345678, 4) == 0x23456780)
2758 +assert(bit32.lshift(0x12345678, 8) == 0x34567800)
2759 +assert(bit32.lshift(0x12345678, -4) == 0x01234567)
2760 +assert(bit32.lshift(0x12345678, -8) == 0x00123456)
2761 +assert(bit32.lshift(0x12345678, 32) == 0)
2762 +assert(bit32.lshift(0x12345678, -32) == 0)
2763 +assert(bit32.rshift(0x12345678, 4) == 0x01234567)
2764 +assert(bit32.rshift(0x12345678, 8) == 0x00123456)
2765 +assert(bit32.rshift(0x12345678, 32) == 0)
2766 +assert(bit32.rshift(0x12345678, -32) == 0)
2767 +assert(bit32.arshift(0x12345678, 0) == 0x12345678)
2768 +assert(bit32.arshift(0x12345678, 1) == 0x12345678 // 2)
2769 +assert(bit32.arshift(0x12345678, -1) == 0x12345678 * 2)
2770 +assert(bit32.arshift(-1, 1) == 0xffffffff)
2771 +assert(bit32.arshift(-1, 24) == 0xffffffff)
2772 +assert(bit32.arshift(-1, 32) == 0xffffffff)
2773 +assert(bit32.arshift(-1, -1) == bit32.band(-1 * 2, 0xffffffff))
2774 +
2775 +assert(0x12345678 << 4 == 0x123456780)
2776 +assert(0x12345678 << 8 == 0x1234567800)
2777 +assert(0x12345678 << -4 == 0x01234567)
2778 +assert(0x12345678 << -8 == 0x00123456)
2779 +assert(0x12345678 << 32 == 0x1234567800000000)
2780 +assert(0x12345678 << -32 == 0)
2781 +assert(0x12345678 >> 4 == 0x01234567)
2782 +assert(0x12345678 >> 8 == 0x00123456)
2783 +assert(0x12345678 >> 32 == 0)
2784 +assert(0x12345678 >> -32 == 0x1234567800000000)
2785 +
2786 +print("+")
2787 +-- some special cases
2788 +local c = {0, 1, 2, 3, 10, 0x80000000, 0xaaaaaaaa, 0x55555555,
2789 + 0xffffffff, 0x7fffffff}
2790 +
2791 +for _, b in pairs(c) do
2792 + assert(bit32.band(b) == b)
2793 + assert(bit32.band(b, b) == b)
2794 + assert(bit32.band(b, b, b, b) == b)
2795 + assert(bit32.btest(b, b) == (b ~= 0))
2796 + assert(bit32.band(b, b, b) == b)
2797 + assert(bit32.band(b, b, b, ~b) == 0)
2798 + assert(bit32.btest(b, b, b) == (b ~= 0))
2799 + assert(bit32.band(b, bit32.bnot(b)) == 0)
2800 + assert(bit32.bor(b, bit32.bnot(b)) == bit32.bnot(0))
2801 + assert(bit32.bor(b) == b)
2802 + assert(bit32.bor(b, b) == b)
2803 + assert(bit32.bor(b, b, b) == b)
2804 + assert(bit32.bor(b, b, 0, ~b) == 0xffffffff)
2805 + assert(bit32.bxor(b) == b)
2806 + assert(bit32.bxor(b, b) == 0)
2807 + assert(bit32.bxor(b, b, b) == b)
2808 + assert(bit32.bxor(b, b, b, b) == 0)
2809 + assert(bit32.bxor(b, 0) == b)
2810 + assert(bit32.bnot(b) ~= b)
2811 + assert(bit32.bnot(bit32.bnot(b)) == b)
2812 + assert(bit32.bnot(b) == (1 << 32) - 1 - b)
2813 + assert(bit32.lrotate(b, 32) == b)
2814 + assert(bit32.rrotate(b, 32) == b)
2815 + assert(bit32.lshift(bit32.lshift(b, -4), 4) == bit32.band(b, bit32.bnot(0xf)))
2816 + assert(bit32.rshift(bit32.rshift(b, 4), -4) == bit32.band(b, bit32.bnot(0xf)))
2817 +end
2818 +
2819 +-- for this test, use at most 24 bits (mantissa of a single float)
2820 +c = {0, 1, 2, 3, 10, 0x800000, 0xaaaaaa, 0x555555, 0xffffff, 0x7fffff}
2821 +for _, b in pairs(c) do
2822 + for i = -40, 40 do
2823 + local x = bit32.lshift(b, i)
2824 + local y = math.floor(math.fmod(b * 2.0^i, 2.0^32))
2825 + assert(math.fmod(x - y, 2.0^32) == 0)
2826 + end
2827 +end
2828 +
2829 +assert(not pcall(bit32.band, {}))
2830 +assert(not pcall(bit32.bnot, "a"))
2831 +assert(not pcall(bit32.lshift, 45))
2832 +assert(not pcall(bit32.lshift, 45, print))
2833 +assert(not pcall(bit32.rshift, 45, print))
2834 +
2835 +print("+")
2836 +
2837 +
2838 +-- testing extract/replace
2839 +
2840 +assert(bit32.extract(0x12345678, 0, 4) == 8)
2841 +assert(bit32.extract(0x12345678, 4, 4) == 7)
2842 +assert(bit32.extract(0xa0001111, 28, 4) == 0xa)
2843 +assert(bit32.extract(0xa0001111, 31, 1) == 1)
2844 +assert(bit32.extract(0x50000111, 31, 1) == 0)
2845 +assert(bit32.extract(0xf2345679, 0, 32) == 0xf2345679)
2846 +
2847 +assert(not pcall(bit32.extract, 0, -1))
2848 +assert(not pcall(bit32.extract, 0, 32))
2849 +assert(not pcall(bit32.extract, 0, 0, 33))
2850 +assert(not pcall(bit32.extract, 0, 31, 2))
2851 +
2852 +assert(bit32.replace(0x12345678, 5, 28, 4) == 0x52345678)
2853 +assert(bit32.replace(0x12345678, 0x87654321, 0, 32) == 0x87654321)
2854 +assert(bit32.replace(0, 1, 2) == 2^2)
2855 +assert(bit32.replace(0, -1, 4) == 2^4)
2856 +assert(bit32.replace(-1, 0, 31) == (1 << 31) - 1)
2857 +assert(bit32.replace(-1, 0, 1, 2) == (1 << 32) - 7)
2858 +
2859 +
2860 +-- testing conversion of floats
2861 +
2862 +assert(bit32.bor(3.0) == 3)
2863 +assert(bit32.bor(-4.0) == 0xfffffffc)
2864 +
2865 +-- large floats and large-enough integers?
2866 +if 2.0^50 < 2.0^50 + 1.0 and 2.0^50 < (-1 >> 1) then
2867 + assert(bit32.bor(2.0^32 - 5.0) == 0xfffffffb)
2868 + assert(bit32.bor(-2.0^32 - 6.0) == 0xfffffffa)
2869 + assert(bit32.bor(2.0^48 - 5.0) == 0xfffffffb)
2870 + assert(bit32.bor(-2.0^48 - 6.0) == 0xfffffffa)
2871 +end
2872 +
2873 +print'OK'
2874 +
2875
2876 diff --git a/tests/bwcoercion.lua b/tests/bwcoercion.lua
2877 new file mode 100644
2878 index 0000000..cd735ab
2879 --- /dev/null
2880 +++ b/tests/bwcoercion.lua
2881 @@ -0,0 +1,78 @@
2882 +local tonumber, tointeger = tonumber, math.tointeger
2883 +local type, getmetatable, rawget, error = type, getmetatable, rawget, error
2884 +local strsub = string.sub
2885 +
2886 +local print = print
2887 +
2888 +_ENV = nil
2889 +
2890 +-- Try to convert a value to an integer, without assuming any coercion.
2891 +local function toint (x)
2892 + x = tonumber(x) -- handle numerical strings
2893 + if not x then
2894 + return false -- not coercible to a number
2895 + end
2896 + return tointeger(x)
2897 +end
2898 +
2899 +
2900 +-- If operation fails, maybe second operand has a metamethod that should
2901 +-- have been called if not for this string metamethod, so try to
2902 +-- call it.
2903 +local function trymt (x, y, mtname)
2904 + if type(y) ~= "string" then -- avoid recalling original metamethod
2905 + local mt = getmetatable(y)
2906 + local mm = mt and rawget(mt, mtname)
2907 + if mm then
2908 + return mm(x, y)
2909 + end
2910 + end
2911 + -- if any test fails, there is no other metamethod to be called
2912 + error("attempt to '" .. strsub(mtname, 3) ..
2913 + "' a " .. type(x) .. " with a " .. type(y), 4)
2914 +end
2915 +
2916 +
2917 +local function checkargs (x, y, mtname)
2918 + local xi = toint(x)
2919 + local yi = toint(y)
2920 + if xi and yi then
2921 + return xi, yi
2922 + else
2923 + return trymt(x, y, mtname), nil
2924 + end
2925 +end
2926 +
2927 +
2928 +local smt = getmetatable("")
2929 +
2930 +smt.__band = function (x, y)
2931 + local x, y = checkargs(x, y, "__band")
2932 + return y and x & y or x
2933 +end
2934 +
2935 +smt.__bor = function (x, y)
2936 + local x, y = checkargs(x, y, "__bor")
2937 + return y and x | y or x
2938 +end
2939 +
2940 +smt.__bxor = function (x, y)
2941 + local x, y = checkargs(x, y, "__bxor")
2942 + return y and x ~ y or x
2943 +end
2944 +
2945 +smt.__shl = function (x, y)
2946 + local x, y = checkargs(x, y, "__shl")
2947 + return y and x << y or x
2948 +end
2949 +
2950 +smt.__shr = function (x, y)
2951 + local x, y = checkargs(x, y, "__shr")
2952 + return y and x >> y or x
2953 +end
2954 +
2955 +smt.__bnot = function (x)
2956 + local x, y = checkargs(x, x, "__bnot")
2957 + return y and ~x or x
2958 +end
2959 +
2960
2961 diff --git a/tests/calls.lua b/tests/calls.lua
2962 new file mode 100644
2963 index 0000000..ff72d8f
2964 --- /dev/null
2965 +++ b/tests/calls.lua
2966 @@ -0,0 +1,481 @@
2967 +-- $Id: testes/calls.lua $
2968 +-- See Copyright Notice in file all.lua
2969 +
2970 +print("testing functions and calls")
2971 +
2972 +local debug = require "debug"
2973 +
2974 +-- get the opportunity to test 'type' too ;)
2975 +
2976 +assert(type(1<2) == 'boolean')
2977 +assert(type(true) == 'boolean' and type(false) == 'boolean')
2978 +assert(type(nil) == 'nil'
2979 + and type(-3) == 'number'
2980 + and type'x' == 'string'
2981 + and type{} == 'table'
2982 + and type(type) == 'function')
2983 +
2984 +assert(type(assert) == type(print))
2985 +function f (x) return a:x (x) end
2986 +assert(type(f) == 'function')
2987 +assert(not pcall(type))
2988 +
2989 +
2990 +-- testing local-function recursion
2991 +fact = false
2992 +do
2993 + local res = 1
2994 + local function fact (n)
2995 + if n==0 then return res
2996 + else return n*fact(n-1)
2997 + end
2998 + end
2999 + assert(fact(5) == 120)
3000 +end
3001 +assert(fact == false)
3002 +
3003 +-- testing declarations
3004 +a = {i = 10}
3005 +self = 20
3006 +function a:x (x) return x+self.i end
3007 +function a.y (x) return x+self end
3008 +
3009 +assert(a:x(1)+10 == a.y(1))
3010 +
3011 +a.t = {i=-100}
3012 +a["t"].x = function (self, a,b) return self.i+a+b end
3013 +
3014 +assert(a.t:x(2,3) == -95)
3015 +
3016 +do
3017 + local a = {x=0}
3018 + function a:add (x) self.x, a.y = self.x+x, 20; return self end
3019 + assert(a:add(10):add(20):add(30).x == 60 and a.y == 20)
3020 +end
3021 +
3022 +local a = {b={c={}}}
3023 +
3024 +function a.b.c.f1 (x) return x+1 end
3025 +function a.b.c:f2 (x,y) self[x] = y end
3026 +assert(a.b.c.f1(4) == 5)
3027 +a.b.c:f2('k', 12); assert(a.b.c.k == 12)
3028 +
3029 +print('+')
3030 +
3031 +t = nil -- 'declare' t
3032 +function f(a,b,c) local d = 'a'; t={a,b,c,d} end
3033 +
3034 +f( -- this line change must be valid
3035 + 1,2)
3036 +assert(t[1] == 1 and t[2] == 2 and t[3] == nil and t[4] == 'a')
3037 +f(1,2, -- this one too
3038 + 3,4)
3039 +assert(t[1] == 1 and t[2] == 2 and t[3] == 3 and t[4] == 'a')
3040 +
3041 +function fat(x)
3042 + if x <= 1 then return 1
3043 + else return x*load("return fat(" .. x-1 .. ")", "")()
3044 + end
3045 +end
3046 +
3047 +assert(load "load 'assert(fat(6)==720)' () ")()
3048 +a = load('return fat(5), 3')
3049 +a,b = a()
3050 +assert(a == 120 and b == 3)
3051 +print('+')
3052 +
3053 +function err_on_n (n)
3054 + if n==0 then error(); exit(1);
3055 + else err_on_n (n-1); exit(1);
3056 + end
3057 +end
3058 +
3059 +do
3060 + function dummy (n)
3061 + if n > 0 then
3062 + assert(not pcall(err_on_n, n))
3063 + dummy(n-1)
3064 + end
3065 + end
3066 +end
3067 +
3068 +dummy(10)
3069 +
3070 +function deep (n)
3071 + if n>0 then deep(n-1) end
3072 +end
3073 +deep(10)
3074 +deep(180)
3075 +
3076 +
3077 +print"testing tail calls"
3078 +
3079 +function deep (n) if n>0 then return deep(n-1) else return 101 end end
3080 +assert(deep(30000) == 101)
3081 +a = {}
3082 +function a:deep (n) if n>0 then return self:deep(n-1) else return 101 end end
3083 +assert(a:deep(30000) == 101)
3084 +
3085 +do -- tail calls x varargs
3086 + local function foo (x, ...) local a = {...}; return x, a[1], a[2] end
3087 +
3088 + local function foo1 (x) return foo(10, x, x + 1) end
3089 +
3090 + local a, b, c = foo1(-2)
3091 + assert(a == 10 and b == -2 and c == -1)
3092 +
3093 + -- tail calls x metamethods
3094 + local t = setmetatable({}, {__call = foo})
3095 + local function foo2 (x) return t(10, x) end
3096 + a, b, c = foo2(100)
3097 + assert(a == t and b == 10 and c == 100)
3098 +
3099 + a, b = (function () return foo() end)()
3100 + assert(a == nil and b == nil)
3101 +
3102 + local X, Y, A
3103 + local function foo (x, y, ...) X = x; Y = y; A = {...} end
3104 + local function foo1 (...) return foo(...) end
3105 +
3106 + local a, b, c = foo1()
3107 + assert(X == nil and Y == nil and #A == 0)
3108 +
3109 + a, b, c = foo1(10)
3110 + assert(X == 10 and Y == nil and #A == 0)
3111 +
3112 + a, b, c = foo1(10, 20)
3113 + assert(X == 10 and Y == 20 and #A == 0)
3114 +
3115 + a, b, c = foo1(10, 20, 30)
3116 + assert(X == 10 and Y == 20 and #A == 1 and A[1] == 30)
3117 +end
3118 +
3119 +
3120 +
3121 +do -- tail calls x chain of __call
3122 + local n = 10000 -- depth
3123 +
3124 + local function foo ()
3125 + if n == 0 then return 1023
3126 + else n = n - 1; return foo()
3127 + end
3128 + end
3129 +
3130 + -- build a chain of __call metamethods ending in function 'foo'
3131 + for i = 1, 100 do
3132 + foo = setmetatable({}, {__call = foo})
3133 + end
3134 +
3135 + -- call the first one as a tail call in a new coroutine
3136 + -- (to ensure stack is not preallocated)
3137 + assert(coroutine.wrap(function() return foo() end)() == 1023)
3138 +end
3139 +
3140 +print('+')
3141 +
3142 +
3143 +do -- testing chains of '__call'
3144 + local N = 20
3145 + local u = table.pack
3146 + for i = 1, N do
3147 + u = setmetatable({i}, {__call = u})
3148 + end
3149 +
3150 + local Res = u("a", "b", "c")
3151 +
3152 + assert(Res.n == N + 3)
3153 + for i = 1, N do
3154 + assert(Res[i][1] == i)
3155 + end
3156 + assert(Res[N + 1] == "a" and Res[N + 2] == "b" and Res[N + 3] == "c")
3157 +end
3158 +
3159 +
3160 +a = nil
3161 +(function (x) a=x end)(23)
3162 +assert(a == 23 and (function (x) return x*2 end)(20) == 40)
3163 +
3164 +
3165 +-- testing closures
3166 +
3167 +-- fixed-point operator
3168 +Z = function (le)
3169 + local function a (f)
3170 + return le(function (x) return f(f)(x) end)
3171 + end
3172 + return a(a)
3173 + end
3174 +
3175 +
3176 +-- non-recursive factorial
3177 +
3178 +F = function (f)
3179 + return function (n)
3180 + if n == 0 then return 1
3181 + else return n*f(n-1) end
3182 + end
3183 + end
3184 +
3185 +fat = Z(F)
3186 +
3187 +assert(fat(0) == 1 and fat(4) == 24 and Z(F)(5)==5*Z(F)(4))
3188 +
3189 +local function g (z)
3190 + local function f (a,b,c,d)
3191 + return function (x,y) return a+b+c+d+a+x+y+z end
3192 + end
3193 + return f(z,z+1,z+2,z+3)
3194 +end
3195 +
3196 +f = g(10)
3197 +assert(f(9, 16) == 10+11+12+13+10+9+16+10)
3198 +
3199 +Z, F, f = nil
3200 +print('+')
3201 +
3202 +-- testing multiple returns
3203 +
3204 +function unlpack (t, i)
3205 + i = i or 1
3206 + if (i <= #t) then
3207 + return t[i], unlpack(t, i+1)
3208 + end
3209 +end
3210 +
3211 +function equaltab (t1, t2)
3212 + assert(#t1 == #t2)
3213 + for i = 1, #t1 do
3214 + assert(t1[i] == t2[i])
3215 + end
3216 +end
3217 +
3218 +local pack = function (...) return (table.pack(...)) end
3219 +
3220 +function f() return 1,2,30,4 end
3221 +function ret2 (a,b) return a,b end
3222 +
3223 +local a,b,c,d = unlpack{1,2,3}
3224 +assert(a==1 and b==2 and c==3 and d==nil)
3225 +a = {1,2,3,4,false,10,'alo',false,assert}
3226 +equaltab(pack(unlpack(a)), a)
3227 +equaltab(pack(unlpack(a), -1), {1,-1})
3228 +a,b,c,d = ret2(f()), ret2(f())
3229 +assert(a==1 and b==1 and c==2 and d==nil)
3230 +a,b,c,d = unlpack(pack(ret2(f()), ret2(f())))
3231 +assert(a==1 and b==1 and c==2 and d==nil)
3232 +a,b,c,d = unlpack(pack(ret2(f()), (ret2(f()))))
3233 +assert(a==1 and b==1 and c==nil and d==nil)
3234 +
3235 +a = ret2{ unlpack{1,2,3}, unlpack{3,2,1}, unlpack{"a", "b"}}
3236 +assert(a[1] == 1 and a[2] == 3 and a[3] == "a" and a[4] == "b")
3237 +
3238 +
3239 +-- testing calls with 'incorrect' arguments
3240 +rawget({}, "x", 1)
3241 +rawset({}, "x", 1, 2)
3242 +assert(math.sin(1,2) == math.sin(1))
3243 +table.sort({10,9,8,4,19,23,0,0}, function (a,b) return a<b end, "extra arg")
3244 +
3245 +
3246 +-- test for generic load
3247 +local x = "-- a comment\0\0\0\n x = 10 + \n23; \
3248 + local a = function () x = 'hi' end; \
3249 + return '\0'"
3250 +function read1 (x)
3251 + local i = 0
3252 + return function ()
3253 + collectgarbage()
3254 + i=i+1
3255 + return string.sub(x, i, i)
3256 + end
3257 +end
3258 +
3259 +function cannotload (msg, a,b)
3260 + assert(not a and string.find(b, msg))
3261 +end
3262 +
3263 +a = assert(load(read1(x), "modname", "t", _G))
3264 +assert(a() == "\0" and _G.x == 33)
3265 +assert(debug.getinfo(a).source == "modname")
3266 +-- cannot read text in binary mode
3267 +cannotload("attempt to load a text chunk", load(read1(x), "modname", "b", {}))
3268 +cannotload("attempt to load a text chunk", load(x, "modname", "b"))
3269 +
3270 +a = assert(load(function () return nil end))
3271 +a() -- empty chunk
3272 +
3273 +assert(not load(function () return true end))
3274 +
3275 +
3276 +-- small bug
3277 +local t = {nil, "return ", "3"}
3278 +f, msg = load(function () return table.remove(t, 1) end)
3279 +assert(f() == nil) -- should read the empty chunk
3280 +
3281 +-- another small bug (in 5.2.1)
3282 +f = load(string.dump(function () return 1 end), nil, "b", {})
3283 +assert(type(f) == "function" and f() == 1)
3284 +
3285 +
3286 +do -- another bug (in 5.4.0)
3287 + -- loading a binary long string interrupted by GC cycles
3288 + local f = string.dump(function ()
3289 + return '01234567890123456789012345678901234567890123456789'
3290 + end)
3291 + f = load(read1(f))
3292 + assert(f() == '01234567890123456789012345678901234567890123456789')
3293 +end
3294 +
3295 +
3296 +x = string.dump(load("x = 1; return x"))
3297 +a = assert(load(read1(x), nil, "b"))
3298 +assert(a() == 1 and _G.x == 1)
3299 +cannotload("attempt to load a binary chunk", load(read1(x), nil, "t"))
3300 +cannotload("attempt to load a binary chunk", load(x, nil, "t"))
3301 +
3302 +assert(not pcall(string.dump, print)) -- no dump of C functions
3303 +
3304 +cannotload("unexpected symbol", load(read1("*a = 123")))
3305 +cannotload("unexpected symbol", load("*a = 123"))
3306 +cannotload("hhi", load(function () error("hhi") end))
3307 +
3308 +-- any value is valid for _ENV
3309 +assert(load("return _ENV", nil, nil, 123)() == 123)
3310 +
3311 +
3312 +-- load when _ENV is not first upvalue
3313 +local x; XX = 123
3314 +local function h ()
3315 + local y=x -- use 'x', so that it becomes 1st upvalue
3316 + return XX -- global name
3317 +end
3318 +local d = string.dump(h)
3319 +x = load(d, "", "b")
3320 +assert(debug.getupvalue(x, 2) == '_ENV')
3321 +debug.setupvalue(x, 2, _G)
3322 +assert(x() == 123)
3323 +
3324 +assert(assert(load("return XX + ...", nil, nil, {XX = 13}))(4) == 17)
3325 +
3326 +
3327 +-- test generic load with nested functions
3328 +x = [[
3329 + return function (x)
3330 + return function (y)
3331 + return function (z)
3332 + return x+y+z
3333 + end
3334 + end
3335 + end
3336 +]]
3337 +a = assert(load(read1(x), "read", "t"))
3338 +assert(a()(2)(3)(10) == 15)
3339 +
3340 +-- repeat the test loading a binary chunk
3341 +x = string.dump(a)
3342 +a = assert(load(read1(x), "read", "b"))
3343 +assert(a()(2)(3)(10) == 15)
3344 +
3345 +
3346 +-- test for dump/undump with upvalues
3347 +local a, b = 20, 30
3348 +x = load(string.dump(function (x)
3349 + if x == "set" then a = 10+b; b = b+1 else
3350 + return a
3351 + end
3352 +end), "", "b", nil)
3353 +assert(x() == nil)
3354 +assert(debug.setupvalue(x, 1, "hi") == "a")
3355 +assert(x() == "hi")
3356 +assert(debug.setupvalue(x, 2, 13) == "b")
3357 +assert(not debug.setupvalue(x, 3, 10)) -- only 2 upvalues
3358 +x("set")
3359 +assert(x() == 23)
3360 +x("set")
3361 +assert(x() == 24)
3362 +
3363 +-- test for dump/undump with many upvalues
3364 +do
3365 + local nup = 200 -- maximum number of local variables
3366 + local prog = {"local a1"}
3367 + for i = 2, nup do prog[#prog + 1] = ", a" .. i end
3368 + prog[#prog + 1] = " = 1"
3369 + for i = 2, nup do prog[#prog + 1] = ", " .. i end
3370 + local sum = 1
3371 + prog[#prog + 1] = "; return function () return a1"
3372 + for i = 2, nup do prog[#prog + 1] = " + a" .. i; sum = sum + i end
3373 + prog[#prog + 1] = " end"
3374 + prog = table.concat(prog)
3375 + local f = assert(load(prog))()
3376 + assert(f() == sum)
3377 +
3378 + f = load(string.dump(f)) -- main chunk now has many upvalues
3379 + local a = 10
3380 + local h = function () return a end
3381 + for i = 1, nup do
3382 + debug.upvaluejoin(f, i, h, 1)
3383 + end
3384 + assert(f() == 10 * nup)
3385 +end
3386 +
3387 +-- test for long method names
3388 +do
3389 + local t = {x = 1}
3390 + function t:_012345678901234567890123456789012345678901234567890123456789 ()
3391 + return self.x
3392 + end
3393 + assert(t:_012345678901234567890123456789012345678901234567890123456789() == 1)
3394 +end
3395 +
3396 +
3397 +-- test for bug in parameter adjustment
3398 +assert((function () return nil end)(4) == nil)
3399 +assert((function () local a; return a end)(4) == nil)
3400 +assert((function (a) return a end)() == nil)
3401 +
3402 +
3403 +print("testing binary chunks")
3404 +do
3405 + local header = string.pack("c4BBc6BBB",
3406 + "\27Lua", -- signature
3407 + 0x54, -- version 5.4 (0x54)
3408 + 0, -- format
3409 + "\x19\x93\r\n\x1a\n", -- data
3410 + 4, -- size of instruction
3411 + string.packsize("j"), -- sizeof(lua integer)
3412 + string.packsize("n") -- sizeof(lua number)
3413 + )
3414 + local c = string.dump(function ()
3415 + local a = 1; local b = 3;
3416 + local f = function () return a + b + _ENV.c; end -- upvalues
3417 + local s1 = "a constant"
3418 + local s2 = "another constant"
3419 + return a + b * 3
3420 + end)
3421 +
3422 + assert(assert(load(c))() == 10)
3423 +
3424 + -- check header
3425 + assert(string.sub(c, 1, #header) == header)
3426 + -- check LUAC_INT and LUAC_NUM
3427 + local ci, cn = string.unpack("jn", c, #header + 1)
3428 + assert(ci == 0x5678 and cn == 370.5)
3429 +
3430 + -- corrupted header
3431 + for i = 1, #header do
3432 + local s = string.sub(c, 1, i - 1) ..
3433 + string.char(string.byte(string.sub(c, i, i)) + 1) ..
3434 + string.sub(c, i + 1, -1)
3435 + assert(#s == #c)
3436 + assert(not load(s))
3437 + end
3438 +
3439 + -- loading truncated binary chunks
3440 + for i = 1, #c - 1 do
3441 + local st, msg = load(string.sub(c, 1, i))
3442 + assert(not st and string.find(msg, "truncated"))
3443 + end
3444 +end
3445 +
3446 +print('OK')
3447 +return deep
3448
3449 diff --git a/tests/closure.lua b/tests/closure.lua
3450 new file mode 100644
3451 index 0000000..c245367
3452 --- /dev/null
3453 +++ b/tests/closure.lua
3454 @@ -0,0 +1,270 @@
3455 +-- $Id: testes/closure.lua $
3456 +-- See Copyright Notice in file all.lua
3457 +
3458 +print "testing closures"
3459 +
3460 +local A,B = 0,{g=10}
3461 +function f(x)
3462 + local a = {}
3463 + for i=1,1000 do
3464 + local y = 0
3465 + do
3466 + a[i] = function () B.g = B.g+1; y = y+x; return y+A end
3467 + end
3468 + end
3469 + local dummy = function () return a[A] end
3470 + collectgarbage()
3471 + A = 1; assert(dummy() == a[1]); A = 0;
3472 + assert(a[1]() == x)
3473 + assert(a[3]() == x)
3474 + collectgarbage()
3475 + assert(B.g == 12)
3476 + return a
3477 +end
3478 +
3479 +local a = f(10)
3480 +-- force a GC in this level
3481 +local x = {[1] = {}} -- to detect a GC
3482 +setmetatable(x, {__mode = 'kv'})
3483 +while x[1] do -- repeat until GC
3484 + local a = A..A..A..A -- create garbage
3485 + A = A+1
3486 +end
3487 +assert(a[1]() == 20+A)
3488 +assert(a[1]() == 30+A)
3489 +assert(a[2]() == 10+A)
3490 +collectgarbage()
3491 +assert(a[2]() == 20+A)
3492 +assert(a[2]() == 30+A)
3493 +assert(a[3]() == 20+A)
3494 +assert(a[8]() == 10+A)
3495 +assert(getmetatable(x).__mode == 'kv')
3496 +assert(B.g == 19)
3497 +
3498 +
3499 +-- testing equality
3500 +a = {}
3501 +
3502 +for i = 1, 5 do a[i] = function (x) return i + a + _ENV end end
3503 +assert(a[3] ~= a[4] and a[4] ~= a[5])
3504 +
3505 +do
3506 + local a = function (x) return math.sin(_ENV[x]) end
3507 + local function f()
3508 + return a
3509 + end
3510 + assert(f() == f())
3511 +end
3512 +
3513 +
3514 +-- testing closures with 'for' control variable
3515 +a = {}
3516 +for i=1,10 do
3517 + a[i] = {set = function(x) i=x end, get = function () return i end}
3518 + if i == 3 then break end
3519 +end
3520 +assert(a[4] == undef)
3521 +a[1].set(10)
3522 +assert(a[2].get() == 2)
3523 +a[2].set('a')
3524 +assert(a[3].get() == 3)
3525 +assert(a[2].get() == 'a')
3526 +
3527 +a = {}
3528 +local t = {"a", "b"}
3529 +for i = 1, #t do
3530 + local k = t[i]
3531 + a[i] = {set = function(x, y) i=x; k=y end,
3532 + get = function () return i, k end}
3533 + if i == 2 then break end
3534 +end
3535 +a[1].set(10, 20)
3536 +local r,s = a[2].get()
3537 +assert(r == 2 and s == 'b')
3538 +r,s = a[1].get()
3539 +assert(r == 10 and s == 20)
3540 +a[2].set('a', 'b')
3541 +r,s = a[2].get()
3542 +assert(r == "a" and s == "b")
3543 +
3544 +
3545 +-- testing closures with 'for' control variable x break
3546 +for i=1,3 do
3547 + f = function () return i end
3548 + break
3549 +end
3550 +assert(f() == 1)
3551 +
3552 +for k = 1, #t do
3553 + local v = t[k]
3554 + f = function () return k, v end
3555 + break
3556 +end
3557 +assert(({f()})[1] == 1)
3558 +assert(({f()})[2] == "a")
3559 +
3560 +
3561 +-- testing closure x break x return x errors
3562 +
3563 +local b
3564 +function f(x)
3565 + local first = 1
3566 + while 1 do
3567 + if x == 3 and not first then return end
3568 + local a = 'xuxu'
3569 + b = function (op, y)
3570 + if op == 'set' then
3571 + a = x+y
3572 + else
3573 + return a
3574 + end
3575 + end
3576 + if x == 1 then do break end
3577 + elseif x == 2 then return
3578 + else if x ~= 3 then error() end
3579 + end
3580 + first = nil
3581 + end
3582 +end
3583 +
3584 +for i=1,3 do
3585 + f(i)
3586 + assert(b('get') == 'xuxu')
3587 + b('set', 10); assert(b('get') == 10+i)
3588 + b = nil
3589 +end
3590 +
3591 +pcall(f, 4);
3592 +assert(b('get') == 'xuxu')
3593 +b('set', 10); assert(b('get') == 14)
3594 +
3595 +
3596 +local w
3597 +-- testing multi-level closure
3598 +function f(x)
3599 + return function (y)
3600 + return function (z) return w+x+y+z end
3601 + end
3602 +end
3603 +
3604 +y = f(10)
3605 +w = 1.345
3606 +assert(y(20)(30) == 60+w)
3607 +
3608 +
3609 +-- testing closures x break
3610 +do
3611 + local X, Y
3612 + local a = math.sin(0)
3613 +
3614 + while a do
3615 + local b = 10
3616 + X = function () return b end -- closure with upvalue
3617 + if a then break end
3618 + end
3619 +
3620 + do
3621 + local b = 20
3622 + Y = function () return b end -- closure with upvalue
3623 + end
3624 +
3625 + -- upvalues must be different
3626 + assert(X() == 10 and Y() == 20)
3627 +end
3628 +
3629 +
3630 +-- testing closures x repeat-until
3631 +
3632 +local a = {}
3633 +local i = 1
3634 +repeat
3635 + local x = i
3636 + a[i] = function () i = x+1; return x end
3637 +until i > 10 or a[i]() ~= x
3638 +assert(i == 11 and a[1]() == 1 and a[3]() == 3 and i == 4)
3639 +
3640 +
3641 +-- testing closures created in 'then' and 'else' parts of 'if's
3642 +a = {}
3643 +for i = 1, 10 do
3644 + if i % 3 == 0 then
3645 + local y = 0
3646 + a[i] = function (x) local t = y; y = x; return t end
3647 + elseif i % 3 == 1 then
3648 + goto L1
3649 + error'not here'
3650 + ::L1::
3651 + local y = 1
3652 + a[i] = function (x) local t = y; y = x; return t end
3653 + elseif i % 3 == 2 then
3654 + local t
3655 + goto l4
3656 + ::l4a:: a[i] = t; goto l4b
3657 + error("should never be here!")
3658 + ::l4::
3659 + local y = 2
3660 + t = function (x) local t = y; y = x; return t end
3661 + goto l4a
3662 + error("should never be here!")
3663 + ::l4b::
3664 + end
3665 +end
3666 +
3667 +for i = 1, 10 do
3668 + assert(a[i](i * 10) == i % 3 and a[i]() == i * 10)
3669 +end
3670 +
3671 +print'+'
3672 +
3673 +
3674 +-- test for correctly closing upvalues in tail calls of vararg functions
3675 +local function t ()
3676 + local function c(a,b) assert(a=="test" and b=="OK") end
3677 + local function v(f, ...) c("test", f() ~= 1 and "FAILED" or "OK") end
3678 + local x = 1
3679 + return v(function() return x end)
3680 +end
3681 +t()
3682 +
3683 +
3684 +-- test for debug manipulation of upvalues
3685 +local debug = require'debug'
3686 +
3687 +do
3688 + local a , b, c = 3, 5, 7
3689 + foo1 = function () return a+b end;
3690 + foo2 = function () return b+a end;
3691 + do
3692 + local a = 10
3693 + foo3 = function () return a+b end;
3694 + end
3695 +end
3696 +
3697 +assert(debug.upvalueid(foo1, 1))
3698 +assert(debug.upvalueid(foo1, 2))
3699 +assert(not debug.upvalueid(foo1, 3))
3700 +assert(debug.upvalueid(foo1, 1) == debug.upvalueid(foo2, 2))
3701 +assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo2, 1))
3702 +assert(debug.upvalueid(foo3, 1))
3703 +assert(debug.upvalueid(foo1, 1) ~= debug.upvalueid(foo3, 1))
3704 +assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo3, 2))
3705 +
3706 +assert(debug.upvalueid(string.gmatch("x", "x"), 1) ~= nil)
3707 +
3708 +assert(foo1() == 3 + 5 and foo2() == 5 + 3)
3709 +debug.upvaluejoin(foo1, 2, foo2, 2)
3710 +assert(foo1() == 3 + 3 and foo2() == 5 + 3)
3711 +assert(foo3() == 10 + 5)
3712 +debug.upvaluejoin(foo3, 2, foo2, 1)
3713 +assert(foo3() == 10 + 5)
3714 +debug.upvaluejoin(foo3, 2, foo2, 2)
3715 +assert(foo3() == 10 + 3)
3716 +
3717 +assert(not pcall(debug.upvaluejoin, foo1, 3, foo2, 1))
3718 +assert(not pcall(debug.upvaluejoin, foo1, 1, foo2, 3))
3719 +assert(not pcall(debug.upvaluejoin, foo1, 0, foo2, 1))
3720 +assert(not pcall(debug.upvaluejoin, print, 1, foo2, 1))
3721 +assert(not pcall(debug.upvaluejoin, {}, 1, foo2, 1))
3722 +assert(not pcall(debug.upvaluejoin, foo1, 1, print, 1))
3723 +
3724 +print'OK'
3725
3726 diff --git a/tests/code.lua b/tests/code.lua
3727 new file mode 100644
3728 index 0000000..543743f
3729 --- /dev/null
3730 +++ b/tests/code.lua
3731 @@ -0,0 +1,449 @@
3732 +-- $Id: testes/code.lua $
3733 +-- See Copyright Notice in file all.lua
3734 +
3735 +if T==nil then
3736 + (Message or print)('\n >>> testC not active: skipping opcode tests <<<\n')
3737 + return
3738 +end
3739 +print "testing code generation and optimizations"
3740 +
3741 +-- to test constant propagation
3742 +local k0aux <const> = 0
3743 +local k0 <const> = k0aux
3744 +local k1 <const> = 1
3745 +local k3 <const> = 3
3746 +local k6 <const> = k3 + (k3 << k0)
3747 +local kFF0 <const> = 0xFF0
3748 +local k3_78 <const> = 3.78
3749 +local x, k3_78_4 <const> = 10, k3_78 / 4
3750 +assert(x == 10)
3751 +
3752 +local kx <const> = "x"
3753 +
3754 +local kTrue <const> = true
3755 +local kFalse <const> = false
3756 +
3757 +local kNil <const> = nil
3758 +
3759 +-- this code gave an error for the code checker
3760 +do
3761 + local function f (a)
3762 + for k,v,w in a do end
3763 + end
3764 +end
3765 +
3766 +
3767 +-- testing reuse in constant table
3768 +local function checkKlist (func, list)
3769 + local k = T.listk(func)
3770 + assert(#k == #list)
3771 + for i = 1, #k do
3772 + assert(k[i] == list[i] and math.type(k[i]) == math.type(list[i]))
3773 + end
3774 +end
3775 +
3776 +local function foo ()
3777 + local a
3778 + a = k3;
3779 + a = 0; a = 0.0; a = -7 + 7
3780 + a = k3_78/4; a = k3_78_4
3781 + a = -k3_78/4; a = k3_78/4; a = -3.78/4
3782 + a = -3.79/4; a = 0.0; a = -0;
3783 + a = k3; a = 3.0; a = 3; a = 3.0
3784 +end
3785 +
3786 +checkKlist(foo, {3.78/4, -3.78/4, -3.79/4})
3787 +
3788 +
3789 +foo = function (f, a)
3790 + f(100 * 1000)
3791 + f(100.0 * 1000)
3792 + f(-100 * 1000)
3793 + f(-100 * 1000.0)
3794 + f(100000)
3795 + f(100000.0)
3796 + f(-100000)
3797 + f(-100000.0)
3798 + end
3799 +
3800 +checkKlist(foo, {100000, 100000.0, -100000, -100000.0})
3801 +
3802 +
3803 +-- floats x integers
3804 +foo = function (t, a)
3805 + t[a] = 1; t[a] = 1.0
3806 + t[a] = 1; t[a] = 1.0
3807 + t[a] = 2; t[a] = 2.0
3808 + t[a] = 0; t[a] = 0.0
3809 + t[a] = 1; t[a] = 1.0
3810 + t[a] = 2; t[a] = 2.0
3811 + t[a] = 0; t[a] = 0.0
3812 +end
3813 +
3814 +checkKlist(foo, {1, 1.0, 2, 2.0, 0, 0.0})
3815 +
3816 +
3817 +-- testing opcodes
3818 +
3819 +-- check that 'f' opcodes match '...'
3820 +function check (f, ...)
3821 + local arg = {...}
3822 + local c = T.listcode(f)
3823 + for i=1, #arg do
3824 + local opcode = string.match(c[i], "%u%w+")
3825 + -- print(arg[i], opcode)
3826 + assert(arg[i] == opcode)
3827 + end
3828 + assert(c[#arg+2] == undef)
3829 +end
3830 +
3831 +
3832 +-- check that 'f' opcodes match '...' and that 'f(p) == r'.
3833 +function checkR (f, p, r, ...)
3834 + local r1 = f(p)
3835 + assert(r == r1 and math.type(r) == math.type(r1))
3836 + check(f, ...)
3837 +end
3838 +
3839 +
3840 +-- check that 'a' and 'b' has the same opcodes
3841 +function checkequal (a, b)
3842 + a = T.listcode(a)
3843 + b = T.listcode(b)
3844 + assert(#a == #b)
3845 + for i = 1, #a do
3846 + a[i] = string.gsub(a[i], '%b()', '') -- remove line number
3847 + b[i] = string.gsub(b[i], '%b()', '') -- remove line number
3848 + assert(a[i] == b[i])
3849 + end
3850 +end
3851 +
3852 +
3853 +-- some basic instructions
3854 +check(function () -- function does not create upvalues
3855 + (function () end){f()}
3856 +end, 'CLOSURE', 'NEWTABLE', 'EXTRAARG', 'GETTABUP', 'CALL',
3857 + 'SETLIST', 'CALL', 'RETURN0')
3858 +
3859 +check(function (x) -- function creates upvalues
3860 + (function () return x end){f()}
3861 +end, 'CLOSURE', 'NEWTABLE', 'EXTRAARG', 'GETTABUP', 'CALL',
3862 + 'SETLIST', 'CALL', 'RETURN')
3863 +
3864 +
3865 +-- sequence of LOADNILs
3866 +check(function ()
3867 + local kNil <const> = nil
3868 + local a,b,c
3869 + local d; local e;
3870 + local f,g,h;
3871 + d = nil; d=nil; b=nil; a=kNil; c=nil;
3872 +end, 'LOADNIL', 'RETURN0')
3873 +
3874 +check(function ()
3875 + local a,b,c,d = 1,1,1,1
3876 + d=nil;c=nil;b=nil;a=nil
3877 +end, 'LOADI', 'LOADI', 'LOADI', 'LOADI', 'LOADNIL', 'RETURN0')
3878 +
3879 +do
3880 + local a,b,c,d = 1,1,1,1
3881 + d=nil;c=nil;b=nil;a=nil
3882 + assert(a == nil and b == nil and c == nil and d == nil)
3883 +end
3884 +
3885 +
3886 +-- single return
3887 +check (function (a,b,c) return a end, 'RETURN1')
3888 +
3889 +
3890 +-- infinite loops
3891 +check(function () while kTrue do local a = -1 end end,
3892 +'LOADI', 'JMP', 'RETURN0')
3893 +
3894 +check(function () while 1 do local a = -1 end end,
3895 +'LOADI', 'JMP', 'RETURN0')
3896 +
3897 +check(function () repeat local x = 1 until true end,
3898 +'LOADI', 'RETURN0')
3899 +
3900 +
3901 +-- concat optimization
3902 +check(function (a,b,c,d) return a..b..c..d end,
3903 + 'MOVE', 'MOVE', 'MOVE', 'MOVE', 'CONCAT', 'RETURN1')
3904 +
3905 +-- not
3906 +check(function () return not not nil end, 'LOADFALSE', 'RETURN1')
3907 +check(function () return not not kFalse end, 'LOADFALSE', 'RETURN1')
3908 +check(function () return not not true end, 'LOADTRUE', 'RETURN1')
3909 +check(function () return not not k3 end, 'LOADTRUE', 'RETURN1')
3910 +
3911 +-- direct access to locals
3912 +check(function ()
3913 + local a,b,c,d
3914 + a = b*a
3915 + c.x, a[b] = -((a + d/b - a[b]) ^ a.x), b
3916 +end,
3917 + 'LOADNIL',
3918 + 'MUL', 'MMBIN',
3919 + 'DIV', 'MMBIN', 'ADD', 'MMBIN', 'GETTABLE', 'SUB', 'MMBIN',
3920 + 'GETFIELD', 'POW', 'MMBIN', 'UNM', 'SETTABLE', 'SETFIELD', 'RETURN0')
3921 +
3922 +
3923 +-- direct access to constants
3924 +check(function ()
3925 + local a,b
3926 + local c = kNil
3927 + a[kx] = 3.2
3928 + a.x = b
3929 + a[b] = 'x'
3930 +end,
3931 + 'LOADNIL', 'SETFIELD', 'SETFIELD', 'SETTABLE', 'RETURN0')
3932 +
3933 +-- "get/set table" with numeric indices
3934 +check(function (a)
3935 + local k255 <const> = 255
3936 + a[1] = a[100]
3937 + a[k255] = a[256]
3938 + a[256] = 5
3939 +end,
3940 + 'GETI', 'SETI',
3941 + 'LOADI', 'GETTABLE', 'SETI',
3942 + 'LOADI', 'SETTABLE', 'RETURN0')
3943 +
3944 +check(function ()
3945 + local a,b
3946 + a = a - a
3947 + b = a/a
3948 + b = 5-4
3949 +end,
3950 + 'LOADNIL', 'SUB', 'MMBIN', 'DIV', 'MMBIN', 'LOADI', 'RETURN0')
3951 +
3952 +check(function ()
3953 + local a,b
3954 + a[kTrue] = false
3955 +end,
3956 + 'LOADNIL', 'LOADTRUE', 'SETTABLE', 'RETURN0')
3957 +
3958 +
3959 +-- equalities
3960 +checkR(function (a) if a == 1 then return 2 end end, 1, 2,
3961 + 'EQI', 'JMP', 'LOADI', 'RETURN1')
3962 +
3963 +checkR(function (a) if -4.0 == a then return 2 end end, -4, 2,
3964 + 'EQI', 'JMP', 'LOADI', 'RETURN1')
3965 +
3966 +checkR(function (a) if a == "hi" then return 2 end end, 10, nil,
3967 + 'EQK', 'JMP', 'LOADI', 'RETURN1')
3968 +
3969 +checkR(function (a) if a == 10000 then return 2 end end, 1, nil,
3970 + 'EQK', 'JMP', 'LOADI', 'RETURN1') -- number too large
3971 +
3972 +checkR(function (a) if -10000 == a then return 2 end end, -10000, 2,
3973 + 'EQK', 'JMP', 'LOADI', 'RETURN1') -- number too large
3974 +
3975 +-- comparisons
3976 +
3977 +checkR(function (a) if -10 <= a then return 2 end end, -10, 2,
3978 + 'GEI', 'JMP', 'LOADI', 'RETURN1')
3979 +
3980 +checkR(function (a) if 128.0 > a then return 2 end end, 129, nil,
3981 + 'LTI', 'JMP', 'LOADI', 'RETURN1')
3982 +
3983 +checkR(function (a) if -127.0 < a then return 2 end end, -127, nil,
3984 + 'GTI', 'JMP', 'LOADI', 'RETURN1')
3985 +
3986 +checkR(function (a) if 10 < a then return 2 end end, 11, 2,
3987 + 'GTI', 'JMP', 'LOADI', 'RETURN1')
3988 +
3989 +checkR(function (a) if 129 < a then return 2 end end, 130, 2,
3990 + 'LOADI', 'LT', 'JMP', 'LOADI', 'RETURN1')
3991 +
3992 +checkR(function (a) if a >= 23.0 then return 2 end end, 25, 2,
3993 + 'GEI', 'JMP', 'LOADI', 'RETURN1')
3994 +
3995 +checkR(function (a) if a >= 23.1 then return 2 end end, 0, nil,
3996 + 'LOADK', 'LE', 'JMP', 'LOADI', 'RETURN1')
3997 +
3998 +checkR(function (a) if a > 2300.0 then return 2 end end, 0, nil,
3999 + 'LOADF', 'LT', 'JMP', 'LOADI', 'RETURN1')
4000 +
4001 +
4002 +-- constant folding
4003 +local function checkK (func, val)
4004 + check(func, 'LOADK', 'RETURN1')
4005 + checkKlist(func, {val})
4006 + assert(func() == val)
4007 +end
4008 +
4009 +local function checkI (func, val)
4010 + check(func, 'LOADI', 'RETURN1')
4011 + checkKlist(func, {})
4012 + assert(func() == val)
4013 +end
4014 +
4015 +local function checkF (func, val)
4016 + check(func, 'LOADF', 'RETURN1')
4017 + checkKlist(func, {})
4018 + assert(func() == val)
4019 +end
4020 +
4021 +checkF(function () return 0.0 end, 0.0)
4022 +checkI(function () return k0 end, 0)
4023 +checkI(function () return -k0//1 end, 0)
4024 +checkK(function () return 3^-1 end, 1/3)
4025 +checkK(function () return (1 + 1)^(50 + 50) end, 2^100)
4026 +checkK(function () return (-2)^(31 - 2) end, -0x20000000 + 0.0)
4027 +checkF(function () return (-k3^0 + 5) // 3.0 end, 1.0)
4028 +checkI(function () return -k3 % 5 end, 2)
4029 +checkF(function () return -((2.0^8 + -(-1)) % 8)/2 * 4 - 3 end, -5.0)
4030 +checkF(function () return -((2^8 + -(-1)) % 8)//2 * 4 - 3 end, -7.0)
4031 +checkI(function () return 0xF0.0 | 0xCC.0 ~ 0xAA & 0xFD end, 0xF4)
4032 +checkI(function () return ~(~kFF0 | kFF0) end, 0)
4033 +checkI(function () return ~~-1024.0 end, -1024)
4034 +checkI(function () return ((100 << k6) << -4) >> 2 end, 100)
4035 +
4036 +-- borders around MAXARG_sBx ((((1 << 17) - 1) >> 1) == 65535)
4037 +local a = 17; local sbx = ((1 << a) - 1) >> 1 -- avoid folding
4038 +local border <const> = 65535
4039 +checkI(function () return border end, sbx)
4040 +checkI(function () return -border end, -sbx)
4041 +checkI(function () return border + 1 end, sbx + 1)
4042 +checkK(function () return border + 2 end, sbx + 2)
4043 +checkK(function () return -(border + 1) end, -(sbx + 1))
4044 +
4045 +local border <const> = 65535.0
4046 +checkF(function () return border end, sbx + 0.0)
4047 +checkF(function () return -border end, -sbx + 0.0)
4048 +checkF(function () return border + 1 end, (sbx + 1.0))
4049 +checkK(function () return border + 2 end, (sbx + 2.0))
4050 +checkK(function () return -(border + 1) end, -(sbx + 1.0))
4051 +
4052 +
4053 +-- immediate operands
4054 +checkR(function (x) return x + k1 end, 10, 11, 'ADDI', 'MMBINI', 'RETURN1')
4055 +checkR(function (x) return x - 127 end, 10, -117, 'ADDI', 'MMBINI', 'RETURN1')
4056 +checkR(function (x) return 128 + x end, 0.0, 128.0,
4057 + 'ADDI', 'MMBINI', 'RETURN1')
4058 +checkR(function (x) return x * -127 end, -1.0, 127.0,
4059 + 'MULK', 'MMBINK', 'RETURN1')
4060 +checkR(function (x) return 20 * x end, 2, 40, 'MULK', 'MMBINK', 'RETURN1')
4061 +checkR(function (x) return x ^ -2 end, 2, 0.25, 'POWK', 'MMBINK', 'RETURN1')
4062 +checkR(function (x) return x / 40 end, 40, 1.0, 'DIVK', 'MMBINK', 'RETURN1')
4063 +checkR(function (x) return x // 1 end, 10.0, 10.0,
4064 + 'IDIVK', 'MMBINK', 'RETURN1')
4065 +checkR(function (x) return x % (100 - 10) end, 91, 1,
4066 + 'MODK', 'MMBINK', 'RETURN1')
4067 +checkR(function (x) return k1 << x end, 3, 8, 'SHLI', 'MMBINI', 'RETURN1')
4068 +checkR(function (x) return x << 127 end, 10, 0, 'SHRI', 'MMBINI', 'RETURN1')
4069 +checkR(function (x) return x << -127 end, 10, 0, 'SHRI', 'MMBINI', 'RETURN1')
4070 +checkR(function (x) return x >> 128 end, 8, 0, 'SHRI', 'MMBINI', 'RETURN1')
4071 +checkR(function (x) return x >> -127 end, 8, 0, 'SHRI', 'MMBINI', 'RETURN1')
4072 +checkR(function (x) return x & 1 end, 9, 1, 'BANDK', 'MMBINK', 'RETURN1')
4073 +checkR(function (x) return 10 | x end, 1, 11, 'BORK', 'MMBINK', 'RETURN1')
4074 +checkR(function (x) return -10 ~ x end, -1, 9, 'BXORK', 'MMBINK', 'RETURN1')
4075 +
4076 +-- K operands in arithmetic operations
4077 +checkR(function (x) return x + 0.0 end, 1, 1.0, 'ADDK', 'MMBINK', 'RETURN1')
4078 +-- check(function (x) return 128 + x end, 'ADDK', 'MMBINK', 'RETURN1')
4079 +checkR(function (x) return x * -10000 end, 2, -20000,
4080 + 'MULK', 'MMBINK', 'RETURN1')
4081 +-- check(function (x) return 20 * x end, 'MULK', 'MMBINK', 'RETURN1')
4082 +checkR(function (x) return x ^ 0.5 end, 4, 2.0, 'POWK', 'MMBINK', 'RETURN1')
4083 +checkR(function (x) return x / 2.0 end, 4, 2.0, 'DIVK', 'MMBINK', 'RETURN1')
4084 +checkR(function (x) return x // 10000 end, 10000, 1,
4085 + 'IDIVK', 'MMBINK', 'RETURN1')
4086 +checkR(function (x) return x % (100.0 - 10) end, 91, 1.0,
4087 + 'MODK', 'MMBINK', 'RETURN1')
4088 +
4089 +-- no foldings (and immediate operands)
4090 +check(function () return -0.0 end, 'LOADF', 'UNM', 'RETURN1')
4091 +check(function () return k3/0 end, 'LOADI', 'DIVK', 'MMBINK', 'RETURN1')
4092 +check(function () return 0%0 end, 'LOADI', 'MODK', 'MMBINK', 'RETURN1')
4093 +check(function () return -4//0 end, 'LOADI', 'IDIVK', 'MMBINK', 'RETURN1')
4094 +check(function (x) return x >> 2.0 end, 'LOADF', 'SHR', 'MMBIN', 'RETURN1')
4095 +check(function (x) return x << 128 end, 'LOADI', 'SHL', 'MMBIN', 'RETURN1')
4096 +check(function (x) return x & 2.0 end, 'LOADF', 'BAND', 'MMBIN', 'RETURN1')
4097 +
4098 +-- basic 'for' loops
4099 +check(function () for i = -10, 10.5 do end end,
4100 +'LOADI', 'LOADK', 'LOADI', 'FORPREP', 'FORLOOP', 'RETURN0')
4101 +check(function () for i = 0xfffffff, 10.0, 1 do end end,
4102 +'LOADK', 'LOADF', 'LOADI', 'FORPREP', 'FORLOOP', 'RETURN0')
4103 +
4104 +-- bug in constant folding for 5.1
4105 +check(function () return -nil end, 'LOADNIL', 'UNM', 'RETURN1')
4106 +
4107 +
4108 +check(function ()
4109 + local a,b,c
4110 + b[c], a = c, b
4111 + b[a], a = c, b
4112 + a, b = c, a
4113 + a = a
4114 +end,
4115 + 'LOADNIL',
4116 + 'MOVE', 'MOVE', 'SETTABLE',
4117 + 'MOVE', 'MOVE', 'MOVE', 'SETTABLE',
4118 + 'MOVE', 'MOVE', 'MOVE',
4119 + -- no code for a = a
4120 + 'RETURN0')
4121 +
4122 +
4123 +-- x == nil , x ~= nil
4124 +-- checkequal(function (b) if (a==nil) then a=1 end; if a~=nil then a=1 end end,
4125 +-- function () if (a==9) then a=1 end; if a~=9 then a=1 end end)
4126 +
4127 +-- check(function () if a==nil then a='a' end end,
4128 +-- 'GETTABUP', 'EQ', 'JMP', 'SETTABUP', 'RETURN')
4129 +
4130 +do -- tests for table access in upvalues
4131 + local t
4132 + check(function () t[kx] = t.y end, 'GETTABUP', 'SETTABUP')
4133 + check(function (a) t[a()] = t[a()] end,
4134 + 'MOVE', 'CALL', 'GETUPVAL', 'MOVE', 'CALL',
4135 + 'GETUPVAL', 'GETTABLE', 'SETTABLE')
4136 +end
4137 +
4138 +-- de morgan
4139 +checkequal(function () local a; if not (a or b) then b=a end end,
4140 + function () local a; if (not a and not b) then b=a end end)
4141 +
4142 +checkequal(function (l) local a; return 0 <= a and a <= l end,
4143 + function (l) local a; return not (not(a >= 0) or not(a <= l)) end)
4144 +
4145 +
4146 +-- if-break optimizations
4147 +check(function (a, b)
4148 + while a do
4149 + if b then break else a = a + 1 end
4150 + end
4151 + end,
4152 +'TEST', 'JMP', 'TEST', 'JMP', 'ADDI', 'MMBINI', 'JMP', 'RETURN0')
4153 +
4154 +checkequal(function () return 6 or true or nil end,
4155 + function () return k6 or kTrue or kNil end)
4156 +
4157 +checkequal(function () return 6 and true or nil end,
4158 + function () return k6 and kTrue or kNil end)
4159 +
4160 +
4161 +do -- string constants
4162 + local k0 <const> = "00000000000000000000000000000000000000000000000000"
4163 + local function f1 ()
4164 + local k <const> = k0
4165 + return function ()
4166 + return function () return k end
4167 + end
4168 + end
4169 +
4170 + local f2 = f1()
4171 + local f3 = f2()
4172 + assert(f3() == k0)
4173 + checkK(f3, k0)
4174 + -- string is not needed by other functions
4175 + assert(T.listk(f1)[1] == nil)
4176 + assert(T.listk(f2)[1] == nil)
4177 +end
4178 +
4179 +print 'OK'
4180 +
4181
4182 diff --git a/tests/constructs.lua b/tests/constructs.lua
4183 new file mode 100644
4184 index 0000000..a74a8c0
4185 --- /dev/null
4186 +++ b/tests/constructs.lua
4187 @@ -0,0 +1,377 @@
4188 +-- $Id: testes/constructs.lua $
4189 +-- See Copyright Notice in file all.lua
4190 +
4191 +;;print "testing syntax";;
4192 +
4193 +local debug = require "debug"
4194 +
4195 +
4196 +local function checkload (s, msg)
4197 + assert(string.find(select(2, load(s)), msg))
4198 +end
4199 +
4200 +-- testing semicollons
4201 +do ;;; end
4202 +; do ; a = 3; assert(a == 3) end;
4203 +;
4204 +
4205 +
4206 +-- invalid operations should not raise errors when not executed
4207 +if false then a = 3 // 0; a = 0 % 0 end
4208 +
4209 +
4210 +-- testing priorities
4211 +
4212 +assert(2^3^2 == 2^(3^2));
4213 +assert(2^3*4 == (2^3)*4);
4214 +assert(2.0^-2 == 1/4 and -2^- -2 == - - -4);
4215 +assert(not nil and 2 and not(2>3 or 3<2));
4216 +assert(-3-1-5 == 0+0-9);
4217 +assert(-2^2 == -4 and (-2)^2 == 4 and 2*2-3-1 == 0);
4218 +assert(-3%5 == 2 and -3+5 == 2)
4219 +assert(2*1+3/3 == 3 and 1+2 .. 3*1 == "33");
4220 +assert(not(2+1 > 3*1) and "a".."b" > "a");
4221 +
4222 +assert(0xF0 | 0xCC ~ 0xAA & 0xFD == 0xF4)
4223 +assert(0xFD & 0xAA ~ 0xCC | 0xF0 == 0xF4)
4224 +assert(0xF0 & 0x0F + 1 == 0x10)
4225 +
4226 +assert(3^4//2^3//5 == 2)
4227 +
4228 +assert(-3+4*5//2^3^2//9+4%10/3 == (-3)+(((4*5)//(2^(3^2)))//9)+((4%10)/3))
4229 +
4230 +assert(not ((true or false) and nil))
4231 +assert( true or false and nil)
4232 +
4233 +-- old bug
4234 +assert((((1 or false) and true) or false) == true)
4235 +assert((((nil and true) or false) and true) == false)
4236 +
4237 +local a,b = 1,nil;
4238 +assert(-(1 or 2) == -1 and (1 and 2)+(-1.25 or -4) == 0.75);
4239 +x = ((b or a)+1 == 2 and (10 or a)+1 == 11); assert(x);
4240 +x = (((2<3) or 1) == true and (2<3 and 4) == 4); assert(x);
4241 +
4242 +x,y=1,2;
4243 +assert((x>y) and x or y == 2);
4244 +x,y=2,1;
4245 +assert((x>y) and x or y == 2);
4246 +
4247 +assert(1234567890 == tonumber('1234567890') and 1234567890+1 == 1234567891)
4248 +
4249 +do -- testing operators with diffent kinds of constants
4250 + -- operands to consider:
4251 + -- * fit in register
4252 + -- * constant doesn't fit in register
4253 + -- * floats with integral values
4254 + local operand = {3, 100, 5.0, -10, -5.0, 10000, -10000}
4255 + local operator = {"+", "-", "*", "/", "//", "%", "^",
4256 + "&", "|", "^", "<<", ">>",
4257 + "==", "~=", "<", ">", "<=", ">=",}
4258 + for _, op in ipairs(operator) do
4259 + local f = assert(load(string.format([[return function (x,y)
4260 + return x %s y
4261 + end]], op)))();
4262 + for _, o1 in ipairs(operand) do
4263 + for _, o2 in ipairs(operand) do
4264 + local gab = f(o1, o2)
4265 +
4266 + _ENV.XX = o1
4267 + code = string.format("return XX %s %s", op, o2)
4268 + res = assert(load(code))()
4269 + assert(res == gab)
4270 +
4271 + _ENV.XX = o2
4272 + local code = string.format("return (%s) %s XX", o1, op)
4273 + local res = assert(load(code))()
4274 + assert(res == gab)
4275 +
4276 + code = string.format("return (%s) %s %s", o1, op, o2)
4277 + res = assert(load(code))()
4278 + assert(res == gab)
4279 + end
4280 + end
4281 + end
4282 +end
4283 +
4284 +
4285 +-- silly loops
4286 +repeat until 1; repeat until true;
4287 +while false do end; while nil do end;
4288 +
4289 +do -- test old bug (first name could not be an `upvalue')
4290 + local a; function f(x) x={a=1}; x={x=1}; x={G=1} end
4291 +end
4292 +
4293 +function f (i)
4294 + if type(i) ~= 'number' then return i,'jojo'; end;
4295 + if i > 0 then return i, f(i-1); end;
4296 +end
4297 +
4298 +x = {f(3), f(5), f(10);};
4299 +assert(x[1] == 3 and x[2] == 5 and x[3] == 10 and x[4] == 9 and x[12] == 1);
4300 +assert(x[nil] == nil)
4301 +x = {f'alo', f'xixi', nil};
4302 +assert(x[1] == 'alo' and x[2] == 'xixi' and x[3] == nil);
4303 +x = {f'alo'..'xixi'};
4304 +assert(x[1] == 'aloxixi')
4305 +x = {f{}}
4306 +assert(x[2] == 'jojo' and type(x[1]) == 'table')
4307 +
4308 +
4309 +local f = function (i)
4310 + if i < 10 then return 'a';
4311 + elseif i < 20 then return 'b';
4312 + elseif i < 30 then return 'c';
4313 + end;
4314 +end
4315 +
4316 +assert(f(3) == 'a' and f(12) == 'b' and f(26) == 'c' and f(100) == nil)
4317 +
4318 +for i=1,1000 do break; end;
4319 +n=100;
4320 +i=3;
4321 +t = {};
4322 +a=nil
4323 +while not a do
4324 + a=0; for i=1,n do for i=i,1,-1 do a=a+1; t[i]=1; end; end;
4325 +end
4326 +assert(a == n*(n+1)/2 and i==3);
4327 +assert(t[1] and t[n] and not t[0] and not t[n+1])
4328 +
4329 +function f(b)
4330 + local x = 1;
4331 + repeat
4332 + local a;
4333 + if b==1 then local b=1; x=10; break
4334 + elseif b==2 then x=20; break;
4335 + elseif b==3 then x=30;
4336 + else local a,b,c,d=math.sin(1); x=x+1;
4337 + end
4338 + until x>=12;
4339 + return x;
4340 +end;
4341 +
4342 +assert(f(1) == 10 and f(2) == 20 and f(3) == 30 and f(4)==12)
4343 +
4344 +
4345 +local f = function (i)
4346 + if i < 10 then return 'a'
4347 + elseif i < 20 then return 'b'
4348 + elseif i < 30 then return 'c'
4349 + else return 8
4350 + end
4351 +end
4352 +
4353 +assert(f(3) == 'a' and f(12) == 'b' and f(26) == 'c' and f(100) == 8)
4354 +
4355 +local a, b = nil, 23
4356 +x = {f(100)*2+3 or a, a or b+2}
4357 +assert(x[1] == 19 and x[2] == 25)
4358 +x = {f=2+3 or a, a = b+2}
4359 +assert(x.f == 5 and x.a == 25)
4360 +
4361 +a={y=1}
4362 +x = {a.y}
4363 +assert(x[1] == 1)
4364 +
4365 +function f(i)
4366 + while 1 do
4367 + if i>0 then i=i-1;
4368 + else return; end;
4369 + end;
4370 +end;
4371 +
4372 +function g(i)
4373 + while 1 do
4374 + if i>0 then i=i-1
4375 + else return end
4376 + end
4377 +end
4378 +
4379 +f(10); g(10);
4380 +
4381 +do
4382 + function f () return 1,2,3; end
4383 + local a, b, c = f();
4384 + assert(a==1 and b==2 and c==3)
4385 + a, b, c = (f());
4386 + assert(a==1 and b==nil and c==nil)
4387 +end
4388 +
4389 +local a,b = 3 and f();
4390 +assert(a==1 and b==nil)
4391 +
4392 +function g() f(); return; end;
4393 +assert(g() == nil)
4394 +function g() return nil or f() end
4395 +a,b = g()
4396 +assert(a==1 and b==nil)
4397 +
4398 +print'+';
4399 +
4400 +do -- testing constants
4401 + local prog <const> = [[local x <XXX> = 10]]
4402 + checkload(prog, "unknown attribute 'XXX'")
4403 +
4404 + checkload([[local xxx <const> = 20; xxx = 10]],
4405 + ":1: attempt to assign to const variable 'xxx'")
4406 +
4407 + checkload([[
4408 + local xx;
4409 + local xxx <const> = 20;
4410 + local yyy;
4411 + local function foo ()
4412 + local abc = xx + yyy + xxx;
4413 + return function () return function () xxx = yyy end end
4414 + end
4415 + ]], ":6: attempt to assign to const variable 'xxx'")
4416 +
4417 + checkload([[
4418 + local x <close> = nil
4419 + x = io.open()
4420 + ]], ":2: attempt to assign to const variable 'x'")
4421 +end
4422 +
4423 +f = [[
4424 +return function ( a , b , c , d , e )
4425 + local x = a >= b or c or ( d and e ) or nil
4426 + return x
4427 +end , { a = 1 , b = 2 >= 1 , } or { 1 };
4428 +]]
4429 +f = string.gsub(f, "%s+", "\n"); -- force a SETLINE between opcodes
4430 +f,a = load(f)();
4431 +assert(a.a == 1 and a.b)
4432 +
4433 +function g (a,b,c,d,e)
4434 + if not (a>=b or c or d and e or nil) then return 0; else return 1; end;
4435 +end
4436 +
4437 +function h (a,b,c,d,e)
4438 + while (a>=b or c or (d and e) or nil) do return 1; end;
4439 + return 0;
4440 +end;
4441 +
4442 +assert(f(2,1) == true and g(2,1) == 1 and h(2,1) == 1)
4443 +assert(f(1,2,'a') == 'a' and g(1,2,'a') == 1 and h(1,2,'a') == 1)
4444 +assert(f(1,2,'a')
4445 +~= -- force SETLINE before nil
4446 +nil, "")
4447 +assert(f(1,2,'a') == 'a' and g(1,2,'a') == 1 and h(1,2,'a') == 1)
4448 +assert(f(1,2,nil,1,'x') == 'x' and g(1,2,nil,1,'x') == 1 and
4449 + h(1,2,nil,1,'x') == 1)
4450 +assert(f(1,2,nil,nil,'x') == nil and g(1,2,nil,nil,'x') == 0 and
4451 + h(1,2,nil,nil,'x') == 0)
4452 +assert(f(1,2,nil,1,nil) == nil and g(1,2,nil,1,nil) == 0 and
4453 + h(1,2,nil,1,nil) == 0)
4454 +
4455 +assert(1 and 2<3 == true and 2<3 and 'a'<'b' == true)
4456 +x = 2<3 and not 3; assert(x==false)
4457 +x = 2<1 or (2>1 and 'a'); assert(x=='a')
4458 +
4459 +
4460 +do
4461 + local a; if nil then a=1; else a=2; end; -- this nil comes as PUSHNIL 2
4462 + assert(a==2)
4463 +end
4464 +
4465 +function F(a)
4466 + assert(debug.getinfo(1, "n").name == 'F')
4467 + return a,2,3
4468 +end
4469 +
4470 +a,b = F(1)~=nil; assert(a == true and b == nil);
4471 +a,b = F(nil)==nil; assert(a == true and b == nil)
4472 +
4473 +----------------------------------------------------------------
4474 +------------------------------------------------------------------
4475 +
4476 +-- sometimes will be 0, sometimes will not...
4477 +_ENV.GLOB1 = math.random(0, 1)
4478 +
4479 +-- basic expressions with their respective values
4480 +local basiccases = {
4481 + {"nil", nil},
4482 + {"false", false},
4483 + {"true", true},
4484 + {"10", 10},
4485 + {"(0==_ENV.GLOB1)", 0 == _ENV.GLOB1},
4486 +}
4487 +
4488 +local prog
4489 +
4490 +if _ENV.GLOB1 == 0 then
4491 + basiccases[2][1] = "F" -- constant false
4492 +
4493 + prog = [[
4494 + local F <const> = false
4495 + if %s then IX = true end
4496 + return %s
4497 +]]
4498 +else
4499 + basiccases[4][1] = "k10" -- constant 10
4500 +
4501 + prog = [[
4502 + local k10 <const> = 10
4503 + if %s then IX = true end
4504 + return %s
4505 + ]]
4506 +end
4507 +
4508 +print('testing short-circuit optimizations (' .. _ENV.GLOB1 .. ')')
4509 +
4510 +
4511 +-- operators with their respective values
4512 +local binops <const> = {
4513 + {" and ", function (a,b) if not a then return a else return b end end},
4514 + {" or ", function (a,b) if a then return a else return b end end},
4515 +}
4516 +
4517 +local cases <const> = {}
4518 +
4519 +-- creates all combinations of '(cases[i] op cases[n-i])' plus
4520 +-- 'not(cases[i] op cases[n-i])' (syntax + value)
4521 +local function createcases (n)
4522 + local res = {}
4523 + for i = 1, n - 1 do
4524 + for _, v1 in ipairs(cases[i]) do
4525 + for _, v2 in ipairs(cases[n - i]) do
4526 + for _, op in ipairs(binops) do
4527 + local t = {
4528 + "(" .. v1[1] .. op[1] .. v2[1] .. ")",
4529 + op[2](v1[2], v2[2])
4530 + }
4531 + res[#res + 1] = t
4532 + res[#res + 1] = {"not" .. t[1], not t[2]}
4533 + end
4534 + end
4535 + end
4536 + end
4537 + return res
4538 +end
4539 +
4540 +-- do not do too many combinations for soft tests
4541 +local level = _soft and 3 or 4
4542 +
4543 +cases[1] = basiccases
4544 +for i = 2, level do cases[i] = createcases(i) end
4545 +print("+")
4546 +
4547 +local i = 0
4548 +for n = 1, level do
4549 + for _, v in pairs(cases[n]) do
4550 + local s = v[1]
4551 + local p = load(string.format(prog, s, s), "")
4552 + IX = false
4553 + assert(p() == v[2] and IX == not not v[2])
4554 + i = i + 1
4555 + if i % 60000 == 0 then print('+') end
4556 + end
4557 +end
4558 +------------------------------------------------------------------
4559 +
4560 +-- testing some syntax errors (chosen through 'gcov')
4561 +checkload("for x do", "expected")
4562 +checkload("x:call", "expected")
4563 +
4564 +print'OK'
4565
4566 diff --git a/tests/coroutine.lua b/tests/coroutine.lua
4567 new file mode 100644
4568 index 0000000..76c9d6e
4569 --- /dev/null
4570 +++ b/tests/coroutine.lua
4571 @@ -0,0 +1,1143 @@
4572 +-- $Id: testes/coroutine.lua $
4573 +-- See Copyright Notice in file all.lua
4574 +
4575 +print "testing coroutines"
4576 +
4577 +local debug = require'debug'
4578 +
4579 +local f
4580 +
4581 +local main, ismain = coroutine.running()
4582 +assert(type(main) == "thread" and ismain)
4583 +assert(not coroutine.resume(main))
4584 +assert(not coroutine.isyieldable(main) and not coroutine.isyieldable())
4585 +assert(not pcall(coroutine.yield))
4586 +
4587 +
4588 +-- trivial errors
4589 +assert(not pcall(coroutine.resume, 0))
4590 +assert(not pcall(coroutine.status, 0))
4591 +
4592 +
4593 +-- tests for multiple yield/resume arguments
4594 +
4595 +local function eqtab (t1, t2)
4596 + assert(#t1 == #t2)
4597 + for i = 1, #t1 do
4598 + local v = t1[i]
4599 + assert(t2[i] == v)
4600 + end
4601 +end
4602 +
4603 +_G.x = nil -- declare x
4604 +function foo (a, ...)
4605 + local x, y = coroutine.running()
4606 + assert(x == f and y == false)
4607 + -- next call should not corrupt coroutine (but must fail,
4608 + -- as it attempts to resume the running coroutine)
4609 + assert(coroutine.resume(f) == false)
4610 + assert(coroutine.status(f) == "running")
4611 + local arg = {...}
4612 + assert(coroutine.isyieldable(x))
4613 + for i=1,#arg do
4614 + _G.x = {coroutine.yield(table.unpack(arg[i]))}
4615 + end
4616 + return table.unpack(a)
4617 +end
4618 +
4619 +f = coroutine.create(foo)
4620 +assert(coroutine.isyieldable(f))
4621 +assert(type(f) == "thread" and coroutine.status(f) == "suspended")
4622 +assert(string.find(tostring(f), "thread"))
4623 +local s,a,b,c,d
4624 +s,a,b,c,d = coroutine.resume(f, {1,2,3}, {}, {1}, {'a', 'b', 'c'})
4625 +assert(coroutine.isyieldable(f))
4626 +assert(s and a == nil and coroutine.status(f) == "suspended")
4627 +s,a,b,c,d = coroutine.resume(f)
4628 +eqtab(_G.x, {})
4629 +assert(s and a == 1 and b == nil)
4630 +assert(coroutine.isyieldable(f))
4631 +s,a,b,c,d = coroutine.resume(f, 1, 2, 3)
4632 +eqtab(_G.x, {1, 2, 3})
4633 +assert(s and a == 'a' and b == 'b' and c == 'c' and d == nil)
4634 +s,a,b,c,d = coroutine.resume(f, "xuxu")
4635 +eqtab(_G.x, {"xuxu"})
4636 +assert(s and a == 1 and b == 2 and c == 3 and d == nil)
4637 +assert(coroutine.status(f) == "dead")
4638 +s, a = coroutine.resume(f, "xuxu")
4639 +assert(not s and string.find(a, "dead") and coroutine.status(f) == "dead")
4640 +
4641 +
4642 +-- yields in tail calls
4643 +local function foo (i) return coroutine.yield(i) end
4644 +f = coroutine.wrap(function ()
4645 + for i=1,10 do
4646 + assert(foo(i) == _G.x)
4647 + end
4648 + return 'a'
4649 +end)
4650 +for i=1,10 do _G.x = i; assert(f(i) == i) end
4651 +_G.x = 'xuxu'; assert(f('xuxu') == 'a')
4652 +
4653 +-- recursive
4654 +function pf (n, i)
4655 + coroutine.yield(n)
4656 + pf(n*i, i+1)
4657 +end
4658 +
4659 +f = coroutine.wrap(pf)
4660 +local s=1
4661 +for i=1,10 do
4662 + assert(f(1, 1) == s)
4663 + s = s*i
4664 +end
4665 +
4666 +-- sieve
4667 +function gen (n)
4668 + return coroutine.wrap(function ()
4669 + for i=2,n do coroutine.yield(i) end
4670 + end)
4671 +end
4672 +
4673 +
4674 +function filter (p, g)
4675 + return coroutine.wrap(function ()
4676 + while 1 do
4677 + local n = g()
4678 + if n == nil then return end
4679 + if math.fmod(n, p) ~= 0 then coroutine.yield(n) end
4680 + end
4681 + end)
4682 +end
4683 +
4684 +local x = gen(80)
4685 +local a = {}
4686 +while 1 do
4687 + local n = x()
4688 + if n == nil then break end
4689 + table.insert(a, n)
4690 + x = filter(n, x)
4691 +end
4692 +
4693 +assert(#a == 22 and a[#a] == 79)
4694 +x, a = nil
4695 +
4696 +
4697 +print("to-be-closed variables in coroutines")
4698 +
4699 +local function func2close (f)
4700 + return setmetatable({}, {__close = f})
4701 +end
4702 +
4703 +do
4704 + -- ok to close a dead coroutine
4705 + local co = coroutine.create(print)
4706 + assert(coroutine.resume(co, "testing 'coroutine.close'"))
4707 + assert(coroutine.status(co) == "dead")
4708 + local st, msg = coroutine.close(co)
4709 + assert(st and msg == nil)
4710 + -- also ok to close it again
4711 + st, msg = coroutine.close(co)
4712 + assert(st and msg == nil)
4713 +
4714 +
4715 + -- cannot close the running coroutine
4716 + local st, msg = pcall(coroutine.close, coroutine.running())
4717 + assert(not st and string.find(msg, "running"))
4718 +
4719 + local main = coroutine.running()
4720 +
4721 + -- cannot close a "normal" coroutine
4722 + ;(coroutine.wrap(function ()
4723 + local st, msg = pcall(coroutine.close, main)
4724 + assert(not st and string.find(msg, "normal"))
4725 + end))()
4726 +
4727 + -- cannot close a coroutine while closing it
4728 + do
4729 + local co
4730 + co = coroutine.create(
4731 + function()
4732 + local x <close> = func2close(function()
4733 + coroutine.close(co) -- try to close it again
4734 + end)
4735 + coroutine.yield(20)
4736 + end)
4737 + local st, msg = coroutine.resume(co)
4738 + assert(st and msg == 20)
4739 + st, msg = coroutine.close(co)
4740 + assert(not st and string.find(msg, "running coroutine"))
4741 + end
4742 +
4743 + -- to-be-closed variables in coroutines
4744 + local X
4745 +
4746 + -- closing a coroutine after an error
4747 + local co = coroutine.create(error)
4748 + local st, msg = coroutine.resume(co, 100)
4749 + assert(not st and msg == 100)
4750 + st, msg = coroutine.close(co)
4751 + assert(not st and msg == 100)
4752 + -- after closing, no more errors
4753 + st, msg = coroutine.close(co)
4754 + assert(st and msg == nil)
4755 +
4756 + co = coroutine.create(function ()
4757 + local x <close> = func2close(function (self, err)
4758 + assert(err == nil); X = false
4759 + end)
4760 + X = true
4761 + coroutine.yield()
4762 + end)
4763 + coroutine.resume(co)
4764 + assert(X)
4765 + assert(coroutine.close(co))
4766 + assert(not X and coroutine.status(co) == "dead")
4767 +
4768 + -- error closing a coroutine
4769 + local x = 0
4770 + co = coroutine.create(function()
4771 + local y <close> = func2close(function (self,err)
4772 + assert(err == 111)
4773 + x = 200
4774 + error(200)
4775 + end)
4776 + local x <close> = func2close(function (self, err)
4777 + assert(err == nil); error(111)
4778 + end)
4779 + coroutine.yield()
4780 + end)
4781 + coroutine.resume(co)
4782 + assert(x == 0)
4783 + local st, msg = coroutine.close(co)
4784 + assert(st == false and coroutine.status(co) == "dead" and msg == 200)
4785 + assert(x == 200)
4786 + -- after closing, no more errors
4787 + st, msg = coroutine.close(co)
4788 + assert(st and msg == nil)
4789 +end
4790 +
4791 +do
4792 + -- <close> versus pcall in coroutines
4793 + local X = false
4794 + local Y = false
4795 + function foo ()
4796 + local x <close> = func2close(function (self, err)
4797 + Y = debug.getinfo(2)
4798 + X = err
4799 + end)
4800 + error(43)
4801 + end
4802 + co = coroutine.create(function () return pcall(foo) end)
4803 + local st1, st2, err = coroutine.resume(co)
4804 + assert(st1 and not st2 and err == 43)
4805 + assert(X == 43 and Y.what == "C")
4806 +
4807 + -- recovering from errors in __close metamethods
4808 + local track = {}
4809 +
4810 + local function h (o)
4811 + local hv <close> = o
4812 + return 1
4813 + end
4814 +
4815 + local function foo ()
4816 + local x <close> = func2close(function(_,msg)
4817 + track[#track + 1] = msg or false
4818 + error(20)
4819 + end)
4820 + local y <close> = func2close(function(_,msg)
4821 + track[#track + 1] = msg or false
4822 + return 1000
4823 + end)
4824 + local z <close> = func2close(function(_,msg)
4825 + track[#track + 1] = msg or false
4826 + error(10)
4827 + end)
4828 + coroutine.yield(1)
4829 + h(func2close(function(_,msg)
4830 + track[#track + 1] = msg or false
4831 + error(2)
4832 + end))
4833 + end
4834 +
4835 + local co = coroutine.create(pcall)
4836 +
4837 + local st, res = coroutine.resume(co, foo) -- call 'foo' protected
4838 + assert(st and res == 1) -- yield 1
4839 + local st, res1, res2 = coroutine.resume(co) -- continue
4840 + assert(coroutine.status(co) == "dead")
4841 + assert(st and not res1 and res2 == 20) -- last error (20)
4842 + assert(track[1] == false and track[2] == 2 and track[3] == 10 and
4843 + track[4] == 10)
4844 +end
4845 +
4846 +
4847 +-- yielding across C boundaries
4848 +
4849 +co = coroutine.wrap(function()
4850 + assert(not pcall(table.sort,{1,2,3}, coroutine.yield))
4851 + assert(coroutine.isyieldable())
4852 + coroutine.yield(20)
4853 + return 30
4854 + end)
4855 +
4856 +assert(co() == 20)
4857 +assert(co() == 30)
4858 +
4859 +
4860 +local f = function (s, i) return coroutine.yield(i) end
4861 +
4862 +local f1 = coroutine.wrap(function ()
4863 + return xpcall(pcall, function (...) return ... end,
4864 + function ()
4865 + local s = 0
4866 + for i in f, nil, 1 do pcall(function () s = s + i end) end
4867 + error({s})
4868 + end)
4869 + end)
4870 +
4871 +f1()
4872 +for i = 1, 10 do assert(f1(i) == i) end
4873 +local r1, r2, v = f1(nil)
4874 +assert(r1 and not r2 and v[1] == (10 + 1)*10/2)
4875 +
4876 +
4877 +function f (a, b) a = coroutine.yield(a); error{a + b} end
4878 +function g(x) return x[1]*2 end
4879 +
4880 +co = coroutine.wrap(function ()
4881 + coroutine.yield(xpcall(f, g, 10, 20))
4882 + end)
4883 +
4884 +assert(co() == 10)
4885 +r, msg = co(100)
4886 +assert(not r and msg == 240)
4887 +
4888 +
4889 +-- unyieldable C call
4890 +do
4891 + local function f (c)
4892 + assert(not coroutine.isyieldable())
4893 + return c .. c
4894 + end
4895 +
4896 + local co = coroutine.wrap(function (c)
4897 + assert(coroutine.isyieldable())
4898 + local s = string.gsub("a", ".", f)
4899 + return s
4900 + end)
4901 + assert(co() == "aa")
4902 +end
4903 +
4904 +
4905 +
4906 +do -- testing single trace of coroutines
4907 + local X
4908 + local co = coroutine.create(function ()
4909 + coroutine.yield(10)
4910 + return 20;
4911 + end)
4912 + local trace = {}
4913 + local function dotrace (event)
4914 + trace[#trace + 1] = event
4915 + end
4916 + debug.sethook(co, dotrace, "clr")
4917 + repeat until not coroutine.resume(co)
4918 + local correcttrace = {"call", "line", "call", "return", "line", "return"}
4919 + assert(#trace == #correcttrace)
4920 + for k, v in pairs(trace) do
4921 + assert(v == correcttrace[k])
4922 + end
4923 +end
4924 +
4925 +-- errors in coroutines
4926 +function foo ()
4927 + assert(debug.getinfo(1).currentline == debug.getinfo(foo).linedefined + 1)
4928 + assert(debug.getinfo(2).currentline == debug.getinfo(goo).linedefined)
4929 + coroutine.yield(3)
4930 + error(foo)
4931 +end
4932 +
4933 +function goo() foo() end
4934 +x = coroutine.wrap(goo)
4935 +assert(x() == 3)
4936 +local a,b = pcall(x)
4937 +assert(not a and b == foo)
4938 +
4939 +x = coroutine.create(goo)
4940 +a,b = coroutine.resume(x)
4941 +assert(a and b == 3)
4942 +a,b = coroutine.resume(x)
4943 +assert(not a and b == foo and coroutine.status(x) == "dead")
4944 +a,b = coroutine.resume(x)
4945 +assert(not a and string.find(b, "dead") and coroutine.status(x) == "dead")
4946 +
4947 +
4948 +-- co-routines x for loop
4949 +function all (a, n, k)
4950 + if k == 0 then coroutine.yield(a)
4951 + else
4952 + for i=1,n do
4953 + a[k] = i
4954 + all(a, n, k-1)
4955 + end
4956 + end
4957 +end
4958 +
4959 +local a = 0
4960 +for t in coroutine.wrap(function () all({}, 5, 4) end) do
4961 + a = a+1
4962 +end
4963 +assert(a == 5^4)
4964 +
4965 +
4966 +-- access to locals of collected corroutines
4967 +local C = {}; setmetatable(C, {__mode = "kv"})
4968 +local x = coroutine.wrap (function ()
4969 + local a = 10
4970 + local function f () a = a+10; return a end
4971 + while true do
4972 + a = a+1
4973 + coroutine.yield(f)
4974 + end
4975 + end)
4976 +
4977 +C[1] = x;
4978 +
4979 +local f = x()
4980 +assert(f() == 21 and x()() == 32 and x() == f)
4981 +x = nil
4982 +collectgarbage()
4983 +assert(C[1] == undef)
4984 +assert(f() == 43 and f() == 53)
4985 +
4986 +
4987 +-- old bug: attempt to resume itself
4988 +
4989 +function co_func (current_co)
4990 + assert(coroutine.running() == current_co)
4991 + assert(coroutine.resume(current_co) == false)
4992 + coroutine.yield(10, 20)
4993 + assert(coroutine.resume(current_co) == false)
4994 + coroutine.yield(23)
4995 + return 10
4996 +end
4997 +
4998 +local co = coroutine.create(co_func)
4999 +local a,b,c = coroutine.resume(co, co)
5000 +assert(a == true and b == 10 and c == 20)
5001 +a,b = coroutine.resume(co, co)
5002 +assert(a == true and b == 23)
5003 +a,b = coroutine.resume(co, co)
5004 +assert(a == true and b == 10)
5005 +assert(coroutine.resume(co, co) == false)
5006 +assert(coroutine.resume(co, co) == false)
5007 +
5008 +
5009 +-- other old bug when attempting to resume itself
5010 +-- (trigger C-code assertions)
5011 +do
5012 + local A = coroutine.running()
5013 + local B = coroutine.create(function() return coroutine.resume(A) end)
5014 + local st, res = coroutine.resume(B)
5015 + assert(st == true and res == false)
5016 +
5017 + local X = false
5018 + A = coroutine.wrap(function()
5019 + local _ <close> = func2close(function () X = true end)
5020 + return pcall(A, 1)
5021 + end)
5022 + st, res = A()
5023 + assert(not st and string.find(res, "non%-suspended") and X == true)
5024 +end
5025 +
5026 +
5027 +-- bug in 5.4.1
5028 +do
5029 + -- coroutine ran close metamethods with invalid status during a
5030 + -- reset.
5031 + local co
5032 + co = coroutine.wrap(function()
5033 + local x <close> = func2close(function() return pcall(co) end)
5034 + error(111)
5035 + end)
5036 + local st, errobj = pcall(co)
5037 + assert(not st and errobj == 111)
5038 + st, errobj = pcall(co)
5039 + assert(not st and string.find(errobj, "dead coroutine"))
5040 +end
5041 +
5042 +
5043 +-- attempt to resume 'normal' coroutine
5044 +local co1, co2
5045 +co1 = coroutine.create(function () return co2() end)
5046 +co2 = coroutine.wrap(function ()
5047 + assert(coroutine.status(co1) == 'normal')
5048 + assert(not coroutine.resume(co1))
5049 + coroutine.yield(3)
5050 + end)
5051 +
5052 +a,b = coroutine.resume(co1)
5053 +assert(a and b == 3)
5054 +assert(coroutine.status(co1) == 'dead')
5055 +
5056 +-- infinite recursion of coroutines
5057 +a = function(a) coroutine.wrap(a)(a) end
5058 +assert(not pcall(a, a))
5059 +a = nil
5060 +
5061 +
5062 +-- access to locals of erroneous coroutines
5063 +local x = coroutine.create (function ()
5064 + local a = 10
5065 + _G.f = function () a=a+1; return a end
5066 + error('x')
5067 + end)
5068 +
5069 +assert(not coroutine.resume(x))
5070 +-- overwrite previous position of local `a'
5071 +assert(not coroutine.resume(x, 1, 1, 1, 1, 1, 1, 1))
5072 +assert(_G.f() == 11)
5073 +assert(_G.f() == 12)
5074 +
5075 +
5076 +if not T then
5077 + (Message or print)
5078 + ('\n >>> testC not active: skipping coroutine API tests <<<\n')
5079 +else
5080 + print "testing yields inside hooks"
5081 +
5082 + local turn
5083 +
5084 + function fact (t, x)
5085 + assert(turn == t)
5086 + if x == 0 then return 1
5087 + else return x*fact(t, x-1)
5088 + end
5089 + end
5090 +
5091 + local A, B = 0, 0
5092 +
5093 + local x = coroutine.create(function ()
5094 + T.sethook("yield 0", "", 2)
5095 + A = fact("A", 6)
5096 + end)
5097 +
5098 + local y = coroutine.create(function ()
5099 + T.sethook("yield 0", "", 3)
5100 + B = fact("B", 7)
5101 + end)
5102 +
5103 + while A==0 or B==0 do -- A ~= 0 when 'x' finishes (similar for 'B','y')
5104 + if A==0 then turn = "A"; assert(T.resume(x)) end
5105 + if B==0 then turn = "B"; assert(T.resume(y)) end
5106 +
5107 + -- check that traceback works correctly after yields inside hooks
5108 + debug.traceback(x)
5109 + debug.traceback(y)
5110 + end
5111 +
5112 + assert(B // A == 7) -- fact(7) // fact(6)
5113 +
5114 + do -- hooks vs. multiple values
5115 + local done
5116 + local function test (n)
5117 + done = false
5118 + return coroutine.wrap(function ()
5119 + local a = {}
5120 + for i = 1, n do a[i] = i end
5121 + -- 'pushint' just to perturb the stack
5122 + T.sethook("pushint 10; yield 0", "", 1) -- yield at each op.
5123 + local a1 = {table.unpack(a)} -- must keep top between ops.
5124 + assert(#a1 == n)
5125 + for i = 1, n do assert(a[i] == i) end
5126 + done = true
5127 + end)
5128 + end
5129 + -- arguments to the coroutine are just to perturb its stack
5130 + local co = test(0); while not done do co(30) end
5131 + co = test(1); while not done do co(20, 10) end
5132 + co = test(3); while not done do co() end
5133 + co = test(100); while not done do co() end
5134 + end
5135 +
5136 + local line = debug.getinfo(1, "l").currentline + 2 -- get line number
5137 + local function foo ()
5138 + local x = 10 --<< this line is 'line'
5139 + x = x + 10
5140 + _G.XX = x
5141 + end
5142 +
5143 + -- testing yields in line hook
5144 + local co = coroutine.wrap(function ()
5145 + T.sethook("setglobal X; yield 0", "l", 0); foo(); return 10 end)
5146 +
5147 + _G.XX = nil;
5148 + _G.X = nil; co(); assert(_G.X == line)
5149 + _G.X = nil; co(); assert(_G.X == line + 1)
5150 + _G.X = nil; co(); assert(_G.X == line + 2 and _G.XX == nil)
5151 + _G.X = nil; co(); assert(_G.X == line + 3 and _G.XX == 20)
5152 + assert(co() == 10)
5153 +
5154 + -- testing yields in count hook
5155 + co = coroutine.wrap(function ()
5156 + T.sethook("yield 0", "", 1); foo(); return 10 end)
5157 +
5158 + _G.XX = nil;
5159 + local c = 0
5160 + repeat c = c + 1; local a = co() until a == 10
5161 + assert(_G.XX == 20 and c >= 5)
5162 +
5163 + co = coroutine.wrap(function ()
5164 + T.sethook("yield 0", "", 2); foo(); return 10 end)
5165 +
5166 + _G.XX = nil;
5167 + local c = 0
5168 + repeat c = c + 1; local a = co() until a == 10
5169 + assert(_G.XX == 20 and c >= 5)
5170 + _G.X = nil; _G.XX = nil
5171 +
5172 + do
5173 + -- testing debug library on a coroutine suspended inside a hook
5174 + -- (bug in 5.2/5.3)
5175 + c = coroutine.create(function (a, ...)
5176 + T.sethook("yield 0", "l") -- will yield on next two lines
5177 + assert(a == 10)
5178 + return ...
5179 + end)
5180 +
5181 + assert(coroutine.resume(c, 1, 2, 3)) -- start coroutine
5182 + local n,v = debug.getlocal(c, 0, 1) -- check its local
5183 + assert(n == "a" and v == 1)
5184 + assert(debug.setlocal(c, 0, 1, 10)) -- test 'setlocal'
5185 + local t = debug.getinfo(c, 0) -- test 'getinfo'
5186 + assert(t.currentline == t.linedefined + 1)
5187 + assert(not debug.getinfo(c, 1)) -- no other level
5188 + assert(coroutine.resume(c)) -- run next line
5189 + v = {coroutine.resume(c)} -- finish coroutine
5190 + assert(v[1] == true and v[2] == 2 and v[3] == 3 and v[4] == undef)
5191 + assert(not coroutine.resume(c))
5192 + end
5193 +
5194 + do
5195 + -- testing debug library on last function in a suspended coroutine
5196 + -- (bug in 5.2/5.3)
5197 + local c = coroutine.create(function () T.testC("yield 1", 10, 20) end)
5198 + local a, b = coroutine.resume(c)
5199 + assert(a and b == 20)
5200 + assert(debug.getinfo(c, 0).linedefined == -1)
5201 + a, b = debug.getlocal(c, 0, 2)
5202 + assert(b == 10)
5203 + end
5204 +
5205 +
5206 + print "testing coroutine API"
5207 +
5208 + -- reusing a thread
5209 + assert(T.testC([[
5210 + newthread # create thread
5211 + pushvalue 2 # push body
5212 + pushstring 'a a a' # push argument
5213 + xmove 0 3 2 # move values to new thread
5214 + resume -1, 1 # call it first time
5215 + pushstatus
5216 + xmove 3 0 0 # move results back to stack
5217 + setglobal X # result
5218 + setglobal Y # status
5219 + pushvalue 2 # push body (to call it again)
5220 + pushstring 'b b b'
5221 + xmove 0 3 2
5222 + resume -1, 1 # call it again
5223 + pushstatus
5224 + xmove 3 0 0
5225 + return 1 # return result
5226 + ]], function (...) return ... end) == 'b b b')
5227 +
5228 + assert(X == 'a a a' and Y == 'OK')
5229 +
5230 +
5231 + -- resuming running coroutine
5232 + C = coroutine.create(function ()
5233 + return T.testC([[
5234 + pushnum 10;
5235 + pushnum 20;
5236 + resume -3 2;
5237 + pushstatus
5238 + gettop;
5239 + return 3]], C)
5240 + end)
5241 + local a, b, c, d = coroutine.resume(C)
5242 + assert(a == true and string.find(b, "non%-suspended") and
5243 + c == "ERRRUN" and d == 4)
5244 +
5245 + a, b, c, d = T.testC([[
5246 + rawgeti R 1 # get main thread
5247 + pushnum 10;
5248 + pushnum 20;
5249 + resume -3 2;
5250 + pushstatus
5251 + gettop;
5252 + return 4]])
5253 + assert(a == coroutine.running() and string.find(b, "non%-suspended") and
5254 + c == "ERRRUN" and d == 4)
5255 +
5256 +
5257 + -- using a main thread as a coroutine (dubious use!)
5258 + local state = T.newstate()
5259 +
5260 + -- check that yielddable is working correctly
5261 + assert(T.testC(state, "newthread; isyieldable -1; remove 1; return 1"))
5262 +
5263 + -- main thread is not yieldable
5264 + assert(not T.testC(state, "rawgeti R 1; isyieldable -1; remove 1; return 1"))
5265 +
5266 + T.testC(state, "settop 0")
5267 +
5268 + T.loadlib(state)
5269 +
5270 + assert(T.doremote(state, [[
5271 + coroutine = require'coroutine';
5272 + X = function (x) coroutine.yield(x, 'BB'); return 'CC' end;
5273 + return 'ok']]))
5274 +
5275 + t = table.pack(T.testC(state, [[
5276 + rawgeti R 1 # get main thread
5277 + pushstring 'XX'
5278 + getglobal X # get function for body
5279 + pushstring AA # arg
5280 + resume 1 1 # 'resume' shadows previous stack!
5281 + gettop
5282 + setglobal T # top
5283 + setglobal B # second yielded value
5284 + setglobal A # fist yielded value
5285 + rawgeti R 1 # get main thread
5286 + pushnum 5 # arg (noise)
5287 + resume 1 1 # after coroutine ends, previous stack is back
5288 + pushstatus
5289 + return *
5290 + ]]))
5291 + assert(t.n == 4 and t[2] == 'XX' and t[3] == 'CC' and t[4] == 'OK')
5292 + assert(T.doremote(state, "return T") == '2')
5293 + assert(T.doremote(state, "return A") == 'AA')
5294 + assert(T.doremote(state, "return B") == 'BB')
5295 +
5296 + T.closestate(state)
5297 +
5298 + print'+'
5299 +
5300 +end
5301 +
5302 +
5303 +-- leaving a pending coroutine open
5304 +_X = coroutine.wrap(function ()
5305 + local a = 10
5306 + local x = function () a = a+1 end
5307 + coroutine.yield()
5308 + end)
5309 +
5310 +_X()
5311 +
5312 +
5313 +if not _soft then
5314 + -- bug (stack overflow)
5315 + local j = 2^9
5316 + local lim = 1000000 -- (C stack limit; assume 32-bit machine)
5317 + local t = {lim - 10, lim - 5, lim - 1, lim, lim + 1}
5318 + for i = 1, #t do
5319 + local j = t[i]
5320 + co = coroutine.create(function()
5321 + local t = {}
5322 + for i = 1, j do t[i] = i end
5323 + return table.unpack(t)
5324 + end)
5325 + local r, msg = coroutine.resume(co)
5326 + assert(not r)
5327 + end
5328 + co = nil
5329 +end
5330 +
5331 +
5332 +assert(coroutine.running() == main)
5333 +
5334 +print"+"
5335 +
5336 +
5337 +print"testing yields inside metamethods"
5338 +
5339 +local function val(x)
5340 + if type(x) == "table" then return x.x else return x end
5341 +end
5342 +
5343 +local mt = {
5344 + __eq = function(a,b) coroutine.yield(nil, "eq"); return val(a) == val(b) end,
5345 + __lt = function(a,b) coroutine.yield(nil, "lt"); return val(a) < val(b) end,
5346 + __le = function(a,b) coroutine.yield(nil, "le"); return a - b <= 0 end,
5347 + __add = function(a,b) coroutine.yield(nil, "add");
5348 + return val(a) + val(b) end,
5349 + __sub = function(a,b) coroutine.yield(nil, "sub"); return val(a) - val(b) end,
5350 + __mul = function(a,b) coroutine.yield(nil, "mul"); return val(a) * val(b) end,
5351 + __div = function(a,b) coroutine.yield(nil, "div"); return val(a) / val(b) end,
5352 + __idiv = function(a,b) coroutine.yield(nil, "idiv");
5353 + return val(a) // val(b) end,
5354 + __pow = function(a,b) coroutine.yield(nil, "pow"); return val(a) ^ val(b) end,
5355 + __mod = function(a,b) coroutine.yield(nil, "mod"); return val(a) % val(b) end,
5356 + __unm = function(a,b) coroutine.yield(nil, "unm"); return -val(a) end,
5357 + __bnot = function(a,b) coroutine.yield(nil, "bnot"); return ~val(a) end,
5358 + __shl = function(a,b) coroutine.yield(nil, "shl");
5359 + return val(a) << val(b) end,
5360 + __shr = function(a,b) coroutine.yield(nil, "shr");
5361 + return val(a) >> val(b) end,
5362 + __band = function(a,b)
5363 + coroutine.yield(nil, "band")
5364 + return val(a) & val(b)
5365 + end,
5366 + __bor = function(a,b) coroutine.yield(nil, "bor");
5367 + return val(a) | val(b) end,
5368 + __bxor = function(a,b) coroutine.yield(nil, "bxor");
5369 + return val(a) ~ val(b) end,
5370 +
5371 + __concat = function(a,b)
5372 + coroutine.yield(nil, "concat");
5373 + return val(a) .. val(b)
5374 + end,
5375 + __index = function (t,k) coroutine.yield(nil, "idx"); return t.k[k] end,
5376 + __newindex = function (t,k,v) coroutine.yield(nil, "nidx"); t.k[k] = v end,
5377 +}
5378 +
5379 +
5380 +local function new (x)
5381 + return setmetatable({x = x, k = {}}, mt)
5382 +end
5383 +
5384 +
5385 +local a = new(10)
5386 +local b = new(12)
5387 +local c = new"hello"
5388 +
5389 +local function run (f, t)
5390 + local i = 1
5391 + local c = coroutine.wrap(f)
5392 + while true do
5393 + local res, stat = c()
5394 + if res then assert(t[i] == undef); return res, t end
5395 + assert(stat == t[i])
5396 + i = i + 1
5397 + end
5398 +end
5399 +
5400 +
5401 +assert(run(function () if (a>=b) then return '>=' else return '<' end end,
5402 + {"le", "sub"}) == "<")
5403 +assert(run(function () if (a<=b) then return '<=' else return '>' end end,
5404 + {"le", "sub"}) == "<=")
5405 +assert(run(function () if (a==b) then return '==' else return '~=' end end,
5406 + {"eq"}) == "~=")
5407 +
5408 +assert(run(function () return a & b + a end, {"add", "band"}) == 2)
5409 +
5410 +assert(run(function () return 1 + a end, {"add"}) == 11)
5411 +assert(run(function () return a - 25 end, {"sub"}) == -15)
5412 +assert(run(function () return 2 * a end, {"mul"}) == 20)
5413 +assert(run(function () return a ^ 2 end, {"pow"}) == 100)
5414 +assert(run(function () return a / 2 end, {"div"}) == 5)
5415 +assert(run(function () return a % 6 end, {"mod"}) == 4)
5416 +assert(run(function () return a // 3 end, {"idiv"}) == 3)
5417 +
5418 +assert(run(function () return a + b end, {"add"}) == 22)
5419 +assert(run(function () return a - b end, {"sub"}) == -2)
5420 +assert(run(function () return a * b end, {"mul"}) == 120)
5421 +assert(run(function () return a ^ b end, {"pow"}) == 10^12)
5422 +assert(run(function () return a / b end, {"div"}) == 10/12)
5423 +assert(run(function () return a % b end, {"mod"}) == 10)
5424 +assert(run(function () return a // b end, {"idiv"}) == 0)
5425 +
5426 +-- repeat tests with larger constants (to use 'K' opcodes)
5427 +local a1000 = new(1000)
5428 +
5429 +assert(run(function () return a1000 + 1000 end, {"add"}) == 2000)
5430 +assert(run(function () return a1000 - 25000 end, {"sub"}) == -24000)
5431 +assert(run(function () return 2000 * a end, {"mul"}) == 20000)
5432 +assert(run(function () return a1000 / 1000 end, {"div"}) == 1)
5433 +assert(run(function () return a1000 % 600 end, {"mod"}) == 400)
5434 +assert(run(function () return a1000 // 500 end, {"idiv"}) == 2)
5435 +
5436 +
5437 +
5438 +assert(run(function () return a % b end, {"mod"}) == 10)
5439 +
5440 +assert(run(function () return ~a & b end, {"bnot", "band"}) == ~10 & 12)
5441 +assert(run(function () return a | b end, {"bor"}) == 10 | 12)
5442 +assert(run(function () return a ~ b end, {"bxor"}) == 10 ~ 12)
5443 +assert(run(function () return a << b end, {"shl"}) == 10 << 12)
5444 +assert(run(function () return a >> b end, {"shr"}) == 10 >> 12)
5445 +
5446 +assert(run(function () return 10 & b end, {"band"}) == 10 & 12)
5447 +assert(run(function () return a | 2 end, {"bor"}) == 10 | 2)
5448 +assert(run(function () return a ~ 2 end, {"bxor"}) == 10 ~ 2)
5449 +assert(run(function () return a >> 2 end, {"shr"}) == 10 >> 2)
5450 +assert(run(function () return 1 >> a end, {"shr"}) == 1 >> 10)
5451 +assert(run(function () return a << 2 end, {"shl"}) == 10 << 2)
5452 +assert(run(function () return 1 << a end, {"shl"}) == 1 << 10)
5453 +assert(run(function () return 2 ~ a end, {"bxor"}) == 2 ~ 10)
5454 +
5455 +
5456 +assert(run(function () return a..b end, {"concat"}) == "1012")
5457 +
5458 +assert(run(function() return a .. b .. c .. a end,
5459 + {"concat", "concat", "concat"}) == "1012hello10")
5460 +
5461 +assert(run(function() return "a" .. "b" .. a .. "c" .. c .. b .. "x" end,
5462 + {"concat", "concat", "concat"}) == "ab10chello12x")
5463 +
5464 +
5465 +do -- a few more tests for comparison operators
5466 + local mt1 = {
5467 + __le = function (a,b)
5468 + coroutine.yield(10)
5469 + return (val(a) <= val(b))
5470 + end,
5471 + __lt = function (a,b)
5472 + coroutine.yield(10)
5473 + return val(a) < val(b)
5474 + end,
5475 + }
5476 + local mt2 = { __lt = mt1.__lt, __le = mt1.__le }
5477 +
5478 + local function run (f)
5479 + local co = coroutine.wrap(f)
5480 + local res
5481 + repeat
5482 + res = co()
5483 + until res ~= 10
5484 + return res
5485 + end
5486 +
5487 + local function test ()
5488 + local a1 = setmetatable({x=1}, mt1)
5489 + local a2 = setmetatable({x=2}, mt2)
5490 + assert(a1 < a2)
5491 + assert(a1 <= a2)
5492 + assert(1 < a2)
5493 + assert(1 <= a2)
5494 + assert(2 > a1)
5495 + assert(2 >= a2)
5496 + return true
5497 + end
5498 +
5499 + run(test)
5500 +
5501 +end
5502 +
5503 +assert(run(function ()
5504 + a.BB = print
5505 + return a.BB
5506 + end, {"nidx", "idx"}) == print)
5507 +
5508 +-- getuptable & setuptable
5509 +do local _ENV = _ENV
5510 + f = function () AAA = BBB + 1; return AAA end
5511 +end
5512 +g = new(10); g.k.BBB = 10;
5513 +debug.setupvalue(f, 1, g)
5514 +assert(run(f, {"idx", "nidx", "idx"}) == 11)
5515 +assert(g.k.AAA == 11)
5516 +
5517 +print"+"
5518 +
5519 +print"testing yields inside 'for' iterators"
5520 +
5521 +local f = function (s, i)
5522 + if i%2 == 0 then coroutine.yield(nil, "for") end
5523 + if i < s then return i + 1 end
5524 + end
5525 +
5526 +assert(run(function ()
5527 + local s = 0
5528 + for i in f, 4, 0 do s = s + i end
5529 + return s
5530 + end, {"for", "for", "for"}) == 10)
5531 +
5532 +
5533 +
5534 +-- tests for coroutine API
5535 +if T==nil then
5536 + (Message or print)('\n >>> testC not active: skipping coroutine API tests <<<\n')
5537 + print "OK"; return
5538 +end
5539 +
5540 +print('testing coroutine API')
5541 +
5542 +local function apico (...)
5543 + local x = {...}
5544 + return coroutine.wrap(function ()
5545 + return T.testC(table.unpack(x))
5546 + end)
5547 +end
5548 +
5549 +local a = {apico(
5550 +[[
5551 + pushstring errorcode
5552 + pcallk 1 0 2;
5553 + invalid command (should not arrive here)
5554 +]],
5555 +[[return *]],
5556 +"stackmark",
5557 +error
5558 +)()}
5559 +assert(#a == 4 and
5560 + a[3] == "stackmark" and
5561 + a[4] == "errorcode" and
5562 + _G.status == "ERRRUN" and
5563 + _G.ctx == 2) -- 'ctx' to pcallk
5564 +
5565 +local co = apico(
5566 + "pushvalue 2; pushnum 10; pcallk 1 2 3; invalid command;",
5567 + coroutine.yield,
5568 + "getglobal status; getglobal ctx; pushvalue 2; pushstring a; pcallk 1 0 4; invalid command",
5569 + "getglobal status; getglobal ctx; return *")
5570 +
5571 +assert(co() == 10)
5572 +assert(co(20, 30) == 'a')
5573 +a = {co()}
5574 +assert(#a == 10 and
5575 + a[2] == coroutine.yield and
5576 + a[5] == 20 and a[6] == 30 and
5577 + a[7] == "YIELD" and a[8] == 3 and
5578 + a[9] == "YIELD" and a[10] == 4)
5579 +assert(not pcall(co)) -- coroutine is dead now
5580 +
5581 +
5582 +f = T.makeCfunc("pushnum 3; pushnum 5; yield 1;")
5583 +co = coroutine.wrap(function ()
5584 + assert(f() == 23); assert(f() == 23); return 10
5585 +end)
5586 +assert(co(23,16) == 5)
5587 +assert(co(23,16) == 5)
5588 +assert(co(23,16) == 10)
5589 +
5590 +
5591 +-- testing coroutines with C bodies
5592 +f = T.makeCfunc([[
5593 + pushnum 102
5594 + yieldk 1 U2
5595 + cannot be here!
5596 +]],
5597 +[[ # continuation
5598 + pushvalue U3 # accessing upvalues inside a continuation
5599 + pushvalue U4
5600 + return *
5601 +]], 23, "huu")
5602 +
5603 +x = coroutine.wrap(f)
5604 +assert(x() == 102)
5605 +eqtab({x()}, {23, "huu"})
5606 +
5607 +
5608 +f = T.makeCfunc[[pushstring 'a'; pushnum 102; yield 2; ]]
5609 +
5610 +a, b, c, d = T.testC([[newthread; pushvalue 2; xmove 0 3 1; resume 3 0;
5611 + pushstatus; xmove 3 0 0; resume 3 0; pushstatus;
5612 + return 4; ]], f)
5613 +
5614 +assert(a == 'YIELD' and b == 'a' and c == 102 and d == 'OK')
5615 +
5616 +
5617 +-- testing chain of suspendable C calls
5618 +
5619 +local count = 3 -- number of levels
5620 +
5621 +f = T.makeCfunc([[
5622 + remove 1; # remove argument
5623 + pushvalue U3; # get selection function
5624 + call 0 1; # call it (result is 'f' or 'yield')
5625 + pushstring hello # single argument for selected function
5626 + pushupvalueindex 2; # index of continuation program
5627 + callk 1 -1 .; # call selected function
5628 + errorerror # should never arrive here
5629 +]],
5630 +[[
5631 + # continuation program
5632 + pushnum 34 # return value
5633 + return * # return all results
5634 +]],
5635 +function () -- selection function
5636 + count = count - 1
5637 + if count == 0 then return coroutine.yield
5638 + else return f
5639 + end
5640 +end
5641 +)
5642 +
5643 +co = coroutine.wrap(function () return f(nil) end)
5644 +assert(co() == "hello") -- argument to 'yield'
5645 +a = {co()}
5646 +-- three '34's (one from each pending C call)
5647 +assert(#a == 3 and a[1] == a[2] and a[2] == a[3] and a[3] == 34)
5648 +
5649 +
5650 +-- testing yields with continuations
5651 +
5652 +co = coroutine.wrap(function (...) return
5653 + T.testC([[ # initial function
5654 + yieldk 1 2
5655 + cannot be here!
5656 + ]],
5657 + [[ # 1st continuation
5658 + yieldk 0 3
5659 + cannot be here!
5660 + ]],
5661 + [[ # 2nd continuation
5662 + yieldk 0 4
5663 + cannot be here!
5664 + ]],
5665 + [[ # 3th continuation
5666 + pushvalue 6 # function which is last arg. to 'testC' here
5667 + pushnum 10; pushnum 20;
5668 + pcall 2 0 0 # call should throw an error and return to next line
5669 + pop 1 # remove error message
5670 + pushvalue 6
5671 + getglobal status; getglobal ctx
5672 + pcallk 2 2 5 # call should throw an error and jump to continuation
5673 + cannot be here!
5674 + ]],
5675 + [[ # 4th (and last) continuation
5676 + return *
5677 + ]],
5678 + -- function called by 3th continuation
5679 + function (a,b) x=a; y=b; error("errmsg") end,
5680 + ...
5681 +)
5682 +end)
5683 +
5684 +local a = {co(3,4,6)}
5685 +assert(a[1] == 6 and a[2] == undef)
5686 +a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 2)
5687 +a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 3)
5688 +a = {co(7,8)};
5689 +-- original arguments
5690 +assert(type(a[1]) == 'string' and type(a[2]) == 'string' and
5691 + type(a[3]) == 'string' and type(a[4]) == 'string' and
5692 + type(a[5]) == 'string' and type(a[6]) == 'function')
5693 +-- arguments left from fist resume
5694 +assert(a[7] == 3 and a[8] == 4)
5695 +-- arguments to last resume
5696 +assert(a[9] == 7 and a[10] == 8)
5697 +-- error message and nothing more
5698 +assert(a[11]:find("errmsg") and #a == 11)
5699 +-- check arguments to pcallk
5700 +assert(x == "YIELD" and y == 4)
5701 +
5702 +assert(not pcall(co)) -- coroutine should be dead
5703 +
5704 +
5705 +-- bug in nCcalls
5706 +local co = coroutine.wrap(function ()
5707 + local a = {pcall(pcall,pcall,pcall,pcall,pcall,pcall,pcall,error,"hi")}
5708 + return pcall(assert, table.unpack(a))
5709 +end)
5710 +
5711 +local a = {co()}
5712 +assert(a[10] == "hi")
5713 +
5714 +print'OK'
5715
5716 diff --git a/tests/cstack.lua b/tests/cstack.lua
5717 new file mode 100644
5718 index 0000000..ca76c87
5719 --- /dev/null
5720 +++ b/tests/cstack.lua
5721 @@ -0,0 +1,171 @@
5722 +-- $Id: testes/cstack.lua $
5723 +-- See Copyright Notice in file all.lua
5724 +
5725 +
5726 +local tracegc = require"tracegc"
5727 +
5728 +print"testing stack overflow detection"
5729 +
5730 +-- Segmentation faults in these tests probably result from a C-stack
5731 +-- overflow. To avoid these errors, you should set a smaller limit for
5732 +-- the use of C stack by Lua, by changing the constant 'LUAI_MAXCCALLS'.
5733 +-- Alternatively, you can ensure a larger stack for the program.
5734 +
5735 +
5736 +local function checkerror (msg, f, ...)
5737 + local s, err = pcall(f, ...)
5738 + assert(not s and string.find(err, msg))
5739 +end
5740 +
5741 +do print("testing stack overflow in message handling")
5742 + local count = 0
5743 + local function loop (x, y, z)
5744 + count = count + 1
5745 + return 1 + loop(x, y, z)
5746 + end
5747 + tracegc.stop() -- __gc should not be called with a full stack
5748 + local res, msg = xpcall(loop, loop)
5749 + tracegc.start()
5750 + assert(msg == "error in error handling")
5751 + print("final count: ", count)
5752 +end
5753 +
5754 +
5755 +-- bug since 2.5 (C-stack overflow in recursion inside pattern matching)
5756 +do print("testing recursion inside pattern matching")
5757 + local function f (size)
5758 + local s = string.rep("a", size)
5759 + local p = string.rep(".?", size)
5760 + return string.match(s, p)
5761 + end
5762 + local m = f(80)
5763 + assert(#m == 80)
5764 + checkerror("too complex", f, 2000)
5765 +end
5766 +
5767 +
5768 +do print("testing stack-overflow in recursive 'gsub'")
5769 + local count = 0
5770 + local function foo ()
5771 + count = count + 1
5772 + string.gsub("a", ".", foo)
5773 + end
5774 + checkerror("stack overflow", foo)
5775 + print("final count: ", count)
5776 +
5777 + print("testing stack-overflow in recursive 'gsub' with metatables")
5778 + local count = 0
5779 + local t = setmetatable({}, {__index = foo})
5780 + foo = function ()
5781 + count = count + 1
5782 + string.gsub("a", ".", t)
5783 + end
5784 + checkerror("stack overflow", foo)
5785 + print("final count: ", count)
5786 +end
5787 +
5788 +
5789 +do -- bug in 5.4.0
5790 + print("testing limits in coroutines inside deep calls")
5791 + local count = 0
5792 + local lim = 1000
5793 + local function stack (n)
5794 + if n > 0 then return stack(n - 1) + 1
5795 + else coroutine.wrap(function ()
5796 + count = count + 1
5797 + stack(lim)
5798 + end)()
5799 + end
5800 + end
5801 +
5802 + local st, msg = xpcall(stack, function () return "ok" end, lim)
5803 + assert(not st and msg == "ok")
5804 + print("final count: ", count)
5805 +end
5806 +
5807 +
5808 +do
5809 + print("nesting of resuming yielded coroutines")
5810 + local count = 0
5811 +
5812 + local function body ()
5813 + coroutine.yield()
5814 + local f = coroutine.wrap(body)
5815 + f(); -- start new coroutine (will stop in previous yield)
5816 + count = count + 1
5817 + f() -- call it recursively
5818 + end
5819 +
5820 + local f = coroutine.wrap(body)
5821 + f()
5822 + assert(not pcall(f))
5823 + print("final count: ", count)
5824 +end
5825 +
5826 +
5827 +do -- bug in 5.4.2
5828 + print("nesting coroutines running after recoverable errors")
5829 + local count = 0
5830 + local function foo()
5831 + count = count + 1
5832 + pcall(1) -- create an error
5833 + -- running now inside 'precover' ("protected recover")
5834 + coroutine.wrap(foo)() -- call another coroutine
5835 + end
5836 + checkerror("C stack overflow", foo)
5837 + print("final count: ", count)
5838 +end
5839 +
5840 +
5841 +if T then
5842 + print("testing stack recovery")
5843 + local N = 0 -- trace number of calls
5844 + local LIM = -1 -- will store N just before stack overflow
5845 +
5846 + -- trace stack size; after stack overflow, it should be
5847 + -- the maximum allowed stack size.
5848 + local stack1
5849 + local dummy
5850 +
5851 + local function err(msg)
5852 + assert(string.find(msg, "stack overflow"))
5853 + local _, stacknow = T.stacklevel()
5854 + assert(stacknow == stack1 + 200)
5855 + end
5856 +
5857 + -- When LIM==-1, the 'if' is not executed, so this function only
5858 + -- counts and stores the stack limits up to overflow. Then, LIM
5859 + -- becomes N, and then the 'if' code is run when the stack is
5860 + -- full. Then, there is a stack overflow inside 'xpcall', after which
5861 + -- the stack must have been restored back to its maximum normal size.
5862 + local function f()
5863 + dummy, stack1 = T.stacklevel()
5864 + if N == LIM then
5865 + xpcall(f, err)
5866 + local _, stacknow = T.stacklevel()
5867 + assert(stacknow == stack1)
5868 + return
5869 + end
5870 + N = N + 1
5871 + f()
5872 + end
5873 +
5874 + local topB, sizeB -- top and size Before overflow
5875 + local topA, sizeA -- top and size After overflow
5876 + topB, sizeB = T.stacklevel()
5877 + tracegc.stop() -- __gc should not be called with a full stack
5878 + xpcall(f, err)
5879 + tracegc.start()
5880 + topA, sizeA = T.stacklevel()
5881 + -- sizes should be comparable
5882 + assert(topA == topB and sizeA < sizeB * 2)
5883 + print(string.format("maximum stack size: %d", stack1))
5884 + LIM = N -- will stop recursion at maximum level
5885 + N = 0 -- to count again
5886 + tracegc.stop() -- __gc should not be called with a full stack
5887 + f()
5888 + tracegc.start()
5889 + print"+"
5890 +end
5891 +
5892 +print'OK'
5893
5894 diff --git a/tests/db.lua b/tests/db.lua
5895 new file mode 100644
5896 index 0000000..f891e9b
5897 --- /dev/null
5898 +++ b/tests/db.lua
5899 @@ -0,0 +1,1036 @@
5900 +-- $Id: testes/db.lua $
5901 +-- See Copyright Notice in file all.lua
5902 +
5903 +-- testing debug library
5904 +
5905 +local debug = require "debug"
5906 +
5907 +local function dostring(s) return assert(load(s))() end
5908 +
5909 +print"testing debug library and debug information"
5910 +
5911 +do
5912 +local a=1
5913 +end
5914 +
5915 +assert(not debug.gethook())
5916 +
5917 +local testline = 19 -- line where 'test' is defined
5918 +function test (s, l, p) -- this must be line 19
5919 + collectgarbage() -- avoid gc during trace
5920 + local function f (event, line)
5921 + assert(event == 'line')
5922 + local l = table.remove(l, 1)
5923 + if p then print(l, line) end
5924 + assert(l == line, "wrong trace!!")
5925 + end
5926 + debug.sethook(f,"l"); load(s)(); debug.sethook()
5927 + assert(#l == 0)
5928 +end
5929 +
5930 +
5931 +do
5932 + assert(not pcall(debug.getinfo, print, "X")) -- invalid option
5933 + assert(not pcall(debug.getinfo, 0, ">")) -- invalid option
5934 + assert(not debug.getinfo(1000)) -- out of range level
5935 + assert(not debug.getinfo(-1)) -- out of range level
5936 + local a = debug.getinfo(print)
5937 + assert(a.what == "C" and a.short_src == "[C]")
5938 + a = debug.getinfo(print, "L")
5939 + assert(a.activelines == nil)
5940 + local b = debug.getinfo(test, "SfL")
5941 + assert(b.name == nil and b.what == "Lua" and b.linedefined == testline and
5942 + b.lastlinedefined == b.linedefined + 10 and
5943 + b.func == test and not string.find(b.short_src, "%["))
5944 + assert(b.activelines[b.linedefined + 1] and
5945 + b.activelines[b.lastlinedefined])
5946 + assert(not b.activelines[b.linedefined] and
5947 + not b.activelines[b.lastlinedefined + 1])
5948 +end
5949 +
5950 +
5951 +-- test file and string names truncation
5952 +a = "function f () end"
5953 +local function dostring (s, x) return load(s, x)() end
5954 +dostring(a)
5955 +assert(debug.getinfo(f).short_src == string.format('[string "%s"]', a))
5956 +dostring(a..string.format("; %s\n=1", string.rep('p', 400)))
5957 +assert(string.find(debug.getinfo(f).short_src, '^%[string [^\n]*%.%.%."%]$'))
5958 +dostring(a..string.format("; %s=1", string.rep('p', 400)))
5959 +assert(string.find(debug.getinfo(f).short_src, '^%[string [^\n]*%.%.%."%]$'))
5960 +dostring("\n"..a)
5961 +assert(debug.getinfo(f).short_src == '[string "..."]')
5962 +dostring(a, "")
5963 +assert(debug.getinfo(f).short_src == '[string ""]')
5964 +dostring(a, "@xuxu")
5965 +assert(debug.getinfo(f).short_src == "xuxu")
5966 +dostring(a, "@"..string.rep('p', 1000)..'t')
5967 +assert(string.find(debug.getinfo(f).short_src, "^%.%.%.p*t$"))
5968 +dostring(a, "=xuxu")
5969 +assert(debug.getinfo(f).short_src == "xuxu")
5970 +dostring(a, string.format("=%s", string.rep('x', 500)))
5971 +assert(string.find(debug.getinfo(f).short_src, "^x*$"))
5972 +dostring(a, "=")
5973 +assert(debug.getinfo(f).short_src == "")
5974 +a = nil; f = nil;
5975 +
5976 +
5977 +repeat
5978 + local g = {x = function ()
5979 + local a = debug.getinfo(2)
5980 + assert(a.name == 'f' and a.namewhat == 'local')
5981 + a = debug.getinfo(1)
5982 + assert(a.name == 'x' and a.namewhat == 'field')
5983 + return 'xixi'
5984 + end}
5985 + local f = function () return 1+1 and (not 1 or g.x()) end
5986 + assert(f() == 'xixi')
5987 + g = debug.getinfo(f)
5988 + assert(g.what == "Lua" and g.func == f and g.namewhat == "" and not g.name)
5989 +
5990 + function f (x, name) -- local!
5991 + name = name or 'f'
5992 + local a = debug.getinfo(1)
5993 + assert(a.name == name and a.namewhat == 'local')
5994 + return x
5995 + end
5996 +
5997 + -- breaks in different conditions
5998 + if 3>4 then break end; f()
5999 + if 3<4 then a=1 else break end; f()
6000 + while 1 do local x=10; break end; f()
6001 + local b = 1
6002 + if 3>4 then return math.sin(1) end; f()
6003 + a = 3<4; f()
6004 + a = 3<4 or 1; f()
6005 + repeat local x=20; if 4>3 then f() else break end; f() until 1
6006 + g = {}
6007 + f(g).x = f(2) and f(10)+f(9)
6008 + assert(g.x == f(19))
6009 + function g(x) if not x then return 3 end return (x('a', 'x')) end
6010 + assert(g(f) == 'a')
6011 +until 1
6012 +
6013 +test([[if
6014 +math.sin(1)
6015 +then
6016 + a=1
6017 +else
6018 + a=2
6019 +end
6020 +]], {2,3,4,7})
6021 +
6022 +test([[
6023 +local function foo()
6024 +end
6025 +foo()
6026 +A = 1
6027 +A = 2
6028 +A = 3
6029 +]], {2, 3, 2, 4, 5, 6})
6030 +
6031 +
6032 +test([[--
6033 +if nil then
6034 + a=1
6035 +else
6036 + a=2
6037 +end
6038 +]], {2,5,6})
6039 +
6040 +test([[a=1
6041 +repeat
6042 + a=a+1
6043 +until a==3
6044 +]], {1,3,4,3,4})
6045 +
6046 +test([[ do
6047 + return
6048 +end
6049 +]], {2})
6050 +
6051 +test([[local a
6052 +a=1
6053 +while a<=3 do
6054 + a=a+1
6055 +end
6056 +]], {1,2,3,4,3,4,3,4,3,5})
6057 +
6058 +test([[while math.sin(1) do
6059 + if math.sin(1)
6060 + then break
6061 + end
6062 +end
6063 +a=1]], {1,2,3,6})
6064 +
6065 +test([[for i=1,3 do
6066 + a=i
6067 +end
6068 +]], {1,2,1,2,1,2,1,3})
6069 +
6070 +test([[for i,v in pairs{'a','b'} do
6071 + a=tostring(i) .. v
6072 +end
6073 +]], {1,2,1,2,1,3})
6074 +
6075 +test([[for i=1,4 do a=1 end]], {1,1,1,1})
6076 +
6077 +
6078 +do -- testing line info/trace with large gaps in source
6079 +
6080 + local a = {1, 2, 3, 10, 124, 125, 126, 127, 128, 129, 130,
6081 + 255, 256, 257, 500, 1000}
6082 + local s = [[
6083 + local b = {10}
6084 + a = b[1] X + Y b[1]
6085 + b = 4
6086 + ]]
6087 + for _, i in ipairs(a) do
6088 + local subs = {X = string.rep("\n", i)}
6089 + for _, j in ipairs(a) do
6090 + subs.Y = string.rep("\n", j)
6091 + local s = string.gsub(s, "[XY]", subs)
6092 + test(s, {1, 2 + i, 2 + i + j, 2 + i, 2 + i + j, 3 + i + j})
6093 + end
6094 + end
6095 +end
6096 +
6097 +
6098 +do -- testing active lines
6099 + local function checkactivelines (f, lines)
6100 + local t = debug.getinfo(f, "SL")
6101 + for _, l in pairs(lines) do
6102 + l = l + t.linedefined
6103 + assert(t.activelines[l])
6104 + t.activelines[l] = undef
6105 + end
6106 + assert(next(t.activelines) == nil) -- no extra lines
6107 + end
6108 +
6109 + checkactivelines(function (...) -- vararg function
6110 + -- 1st line is empty
6111 + -- 2nd line is empty
6112 + -- 3th line is empty
6113 + local a = 20
6114 + -- 5th line is empty
6115 + local b = 30
6116 + -- 7th line is empty
6117 + end, {4, 6, 8})
6118 +
6119 + checkactivelines(function (a)
6120 + -- 1st line is empty
6121 + -- 2nd line is empty
6122 + local a = 20
6123 + local b = 30
6124 + -- 5th line is empty
6125 + end, {3, 4, 6})
6126 +
6127 + checkactivelines(function (a, b, ...) end, {0})
6128 +
6129 + checkactivelines(function (a, b)
6130 + end, {1})
6131 +
6132 + for _, n in pairs{0, 1, 2, 10, 50, 100, 1000, 10000} do
6133 + checkactivelines(
6134 + load(string.format("%s return 1", string.rep("\n", n))),
6135 + {n + 1})
6136 + end
6137 +
6138 +end
6139 +
6140 +print'+'
6141 +
6142 +-- invalid levels in [gs]etlocal
6143 +assert(not pcall(debug.getlocal, 20, 1))
6144 +assert(not pcall(debug.setlocal, -1, 1, 10))
6145 +
6146 +
6147 +-- parameter names
6148 +local function foo (a,b,...) local d, e end
6149 +local co = coroutine.create(foo)
6150 +
6151 +assert(debug.getlocal(foo, 1) == 'a')
6152 +assert(debug.getlocal(foo, 2) == 'b')
6153 +assert(not debug.getlocal(foo, 3))
6154 +assert(debug.getlocal(co, foo, 1) == 'a')
6155 +assert(debug.getlocal(co, foo, 2) == 'b')
6156 +assert(not debug.getlocal(co, foo, 3))
6157 +
6158 +assert(not debug.getlocal(print, 1))
6159 +
6160 +
6161 +local function foo () return (debug.getlocal(1, -1)) end
6162 +assert(not foo(10))
6163 +
6164 +
6165 +-- varargs
6166 +local function foo (a, ...)
6167 + local t = table.pack(...)
6168 + for i = 1, t.n do
6169 + local n, v = debug.getlocal(1, -i)
6170 + assert(n == "(vararg)" and v == t[i])
6171 + end
6172 + assert(not debug.getlocal(1, -(t.n + 1)))
6173 + assert(not debug.setlocal(1, -(t.n + 1), 30))
6174 + if t.n > 0 then
6175 + (function (x)
6176 + assert(debug.setlocal(2, -1, x) == "(vararg)")
6177 + assert(debug.setlocal(2, -t.n, x) == "(vararg)")
6178 + end)(430)
6179 + assert(... == 430)
6180 + end
6181 +end
6182 +
6183 +foo()
6184 +foo(print)
6185 +foo(200, 3, 4)
6186 +local a = {}
6187 +for i = 1, (_soft and 100 or 1000) do a[i] = i end
6188 +foo(table.unpack(a))
6189 +a = nil
6190 +
6191 +
6192 +
6193 +do -- test hook presence in debug info
6194 + assert(not debug.gethook())
6195 + local count = 0
6196 + local function f ()
6197 + assert(debug.getinfo(1).namewhat == "hook")
6198 + local sndline = string.match(debug.traceback(), "\n(.-)\n")
6199 + assert(string.find(sndline, "hook"))
6200 + count = count + 1
6201 + end
6202 + debug.sethook(f, "l")
6203 + local a = 0
6204 + _ENV.a = a
6205 + a = 1
6206 + debug.sethook()
6207 + assert(count == 4)
6208 +end
6209 +
6210 +
6211 +-- hook table has weak keys
6212 +assert(getmetatable(debug.getregistry()._HOOKKEY).__mode == 'k')
6213 +
6214 +
6215 +a = {}; L = nil
6216 +local glob = 1
6217 +local oldglob = glob
6218 +debug.sethook(function (e,l)
6219 + collectgarbage() -- force GC during a hook
6220 + local f, m, c = debug.gethook()
6221 + assert(m == 'crl' and c == 0)
6222 + if e == "line" then
6223 + if glob ~= oldglob then
6224 + L = l-1 -- get the first line where "glob" has changed
6225 + oldglob = glob
6226 + end
6227 + elseif e == "call" then
6228 + local f = debug.getinfo(2, "f").func
6229 + a[f] = 1
6230 + else assert(e == "return")
6231 + end
6232 +end, "crl")
6233 +
6234 +
6235 +function f(a,b)
6236 + collectgarbage()
6237 + local _, x = debug.getlocal(1, 1)
6238 + local _, y = debug.getlocal(1, 2)
6239 + assert(x == a and y == b)
6240 + assert(debug.setlocal(2, 3, "pera") == "AA".."AA")
6241 + assert(debug.setlocal(2, 4, "maçã") == "B")
6242 + x = debug.getinfo(2)
6243 + assert(x.func == g and x.what == "Lua" and x.name == 'g' and
6244 + x.nups == 2 and string.find(x.source, "^@.*db%.lua$"))
6245 + glob = glob+1
6246 + assert(debug.getinfo(1, "l").currentline == L+1)
6247 + assert(debug.getinfo(1, "l").currentline == L+2)
6248 +end
6249 +
6250 +function foo()
6251 + glob = glob+1
6252 + assert(debug.getinfo(1, "l").currentline == L+1)
6253 +end; foo() -- set L
6254 +-- check line counting inside strings and empty lines
6255 +
6256 +_ = 'alo\
6257 +alo' .. [[
6258 +
6259 +]]
6260 +--[[
6261 +]]
6262 +assert(debug.getinfo(1, "l").currentline == L+11) -- check count of lines
6263 +
6264 +
6265 +function g (...)
6266 + local arg = {...}
6267 + do local a,b,c; a=math.sin(40); end
6268 + local feijao
6269 + local AAAA,B = "xuxu", "mamão"
6270 + f(AAAA,B)
6271 + assert(AAAA == "pera" and B == "maçã")
6272 + do
6273 + local B = 13
6274 + local x,y = debug.getlocal(1,5)
6275 + assert(x == 'B' and y == 13)
6276 + end
6277 +end
6278 +
6279 +g()
6280 +
6281 +
6282 +assert(a[f] and a[g] and a[assert] and a[debug.getlocal] and not a[print])
6283 +
6284 +
6285 +-- tests for manipulating non-registered locals (C and Lua temporaries)
6286 +
6287 +local n, v = debug.getlocal(0, 1)
6288 +assert(v == 0 and n == "(C temporary)")
6289 +local n, v = debug.getlocal(0, 2)
6290 +assert(v == 2 and n == "(C temporary)")
6291 +assert(not debug.getlocal(0, 3))
6292 +assert(not debug.getlocal(0, 0))
6293 +
6294 +function f()
6295 + assert(select(2, debug.getlocal(2,3)) == 1)
6296 + assert(not debug.getlocal(2,4))
6297 + debug.setlocal(2, 3, 10)
6298 + return 20
6299 +end
6300 +
6301 +function g(a,b) return (a+1) + f() end
6302 +
6303 +assert(g(0,0) == 30)
6304 +
6305 +
6306 +debug.sethook(nil);
6307 +assert(not debug.gethook())
6308 +
6309 +
6310 +-- minimal tests for setuservalue/getuservalue
6311 +do
6312 + assert(not debug.setuservalue(io.stdin, 10))
6313 + local a, b = debug.getuservalue(io.stdin, 10)
6314 + assert(a == nil and not b)
6315 +end
6316 +
6317 +-- testing iteraction between multiple values x hooks
6318 +do
6319 + local function f(...) return 3, ... end
6320 + local count = 0
6321 + local a = {}
6322 + for i = 1, 100 do a[i] = i end
6323 + debug.sethook(function () count = count + 1 end, "", 1)
6324 + local t = {table.unpack(a)}
6325 + assert(#t == 100)
6326 + t = {table.unpack(a, 1, 3)}
6327 + assert(#t == 3)
6328 + t = {f(table.unpack(a, 1, 30))}
6329 + assert(#t == 31)
6330 +end
6331 +
6332 +
6333 +-- testing access to function arguments
6334 +
6335 +local function collectlocals (level)
6336 + local tab = {}
6337 + for i = 1, math.huge do
6338 + local n, v = debug.getlocal(level + 1, i)
6339 + if not (n and string.find(n, "^[a-zA-Z0-9_]+$")) then
6340 + break -- consider only real variables
6341 + end
6342 + tab[n] = v
6343 + end
6344 + return tab
6345 +end
6346 +
6347 +
6348 +X = nil
6349 +a = {}
6350 +function a:f (a, b, ...) local arg = {...}; local c = 13 end
6351 +debug.sethook(function (e)
6352 + assert(e == "call")
6353 + dostring("XX = 12") -- test dostring inside hooks
6354 + -- testing errors inside hooks
6355 + assert(not pcall(load("a='joao'+1")))
6356 + debug.sethook(function (e, l)
6357 + assert(debug.getinfo(2, "l").currentline == l)
6358 + local f,m,c = debug.gethook()
6359 + assert(e == "line")
6360 + assert(m == 'l' and c == 0)
6361 + debug.sethook(nil) -- hook is called only once
6362 + assert(not X) -- check that
6363 + X = collectlocals(2)
6364 + end, "l")
6365 +end, "c")
6366 +
6367 +a:f(1,2,3,4,5)
6368 +assert(X.self == a and X.a == 1 and X.b == 2 and X.c == nil)
6369 +assert(XX == 12)
6370 +assert(not debug.gethook())
6371 +
6372 +
6373 +-- testing access to local variables in return hook (bug in 5.2)
6374 +do
6375 + local X = false
6376 +
6377 + local function foo (a, b, ...)
6378 + do local x,y,z end
6379 + local c, d = 10, 20
6380 + return
6381 + end
6382 +
6383 + local function aux ()
6384 + if debug.getinfo(2).name == "foo" then
6385 + X = true -- to signal that it found 'foo'
6386 + local tab = {a = 100, b = 200, c = 10, d = 20}
6387 + for n, v in pairs(collectlocals(2)) do
6388 + assert(tab[n] == v)
6389 + tab[n] = undef
6390 + end
6391 + assert(next(tab) == nil) -- 'tab' must be empty
6392 + end
6393 + end
6394 +
6395 + debug.sethook(aux, "r"); foo(100, 200); debug.sethook()
6396 + assert(X)
6397 +
6398 +end
6399 +
6400 +
6401 +local function eqseq (t1, t2)
6402 + assert(#t1 == #t2)
6403 + for i = 1, #t1 do
6404 + assert(t1[i] == t2[i])
6405 + end
6406 +end
6407 +
6408 +
6409 +do print("testing inspection of parameters/returned values")
6410 + local on = false
6411 + local inp, out
6412 +
6413 + local function hook (event)
6414 + if not on then return end
6415 + local ar = debug.getinfo(2, "ruS")
6416 + local t = {}
6417 + for i = ar.ftransfer, ar.ftransfer + ar.ntransfer - 1 do
6418 + local _, v = debug.getlocal(2, i)
6419 + t[#t + 1] = v
6420 + end
6421 + if event == "return" then
6422 + out = t
6423 + else
6424 + inp = t
6425 + end
6426 + end
6427 +
6428 + debug.sethook(hook, "cr")
6429 +
6430 + on = true; math.sin(3); on = false
6431 + eqseq(inp, {3}); eqseq(out, {math.sin(3)})
6432 +
6433 + on = true; select(2, 10, 20, 30, 40); on = false
6434 + eqseq(inp, {2, 10, 20, 30, 40}); eqseq(out, {20, 30, 40})
6435 +
6436 + local function foo (a, ...) return ... end
6437 + local function foo1 () on = not on; return foo(20, 10, 0) end
6438 + foo1(); on = false
6439 + eqseq(inp, {20}); eqseq(out, {10, 0})
6440 +
6441 + debug.sethook()
6442 +end
6443 +
6444 +
6445 +
6446 +-- testing upvalue access
6447 +local function getupvalues (f)
6448 + local t = {}
6449 + local i = 1
6450 + while true do
6451 + local name, value = debug.getupvalue(f, i)
6452 + if not name then break end
6453 + assert(not t[name])
6454 + t[name] = value
6455 + i = i + 1
6456 + end
6457 + return t
6458 +end
6459 +
6460 +local a,b,c = 1,2,3
6461 +local function foo1 (a) b = a; return c end
6462 +local function foo2 (x) a = x; return c+b end
6463 +assert(not debug.getupvalue(foo1, 3))
6464 +assert(not debug.getupvalue(foo1, 0))
6465 +assert(not debug.setupvalue(foo1, 3, "xuxu"))
6466 +local t = getupvalues(foo1)
6467 +assert(t.a == nil and t.b == 2 and t.c == 3)
6468 +t = getupvalues(foo2)
6469 +assert(t.a == 1 and t.b == 2 and t.c == 3)
6470 +assert(debug.setupvalue(foo1, 1, "xuxu") == "b")
6471 +assert(({debug.getupvalue(foo2, 3)})[2] == "xuxu")
6472 +-- upvalues of C functions are allways "called" "" (the empty string)
6473 +assert(debug.getupvalue(string.gmatch("x", "x"), 1) == "")
6474 +
6475 +
6476 +-- testing count hooks
6477 +local a=0
6478 +debug.sethook(function (e) a=a+1 end, "", 1)
6479 +a=0; for i=1,1000 do end; assert(1000 < a and a < 1012)
6480 +debug.sethook(function (e) a=a+1 end, "", 4)
6481 +a=0; for i=1,1000 do end; assert(250 < a and a < 255)
6482 +local f,m,c = debug.gethook()
6483 +assert(m == "" and c == 4)
6484 +debug.sethook(function (e) a=a+1 end, "", 4000)
6485 +a=0; for i=1,1000 do end; assert(a == 0)
6486 +
6487 +do
6488 + debug.sethook(print, "", 2^24 - 1) -- count upperbound
6489 + local f,m,c = debug.gethook()
6490 + assert(({debug.gethook()})[3] == 2^24 - 1)
6491 +end
6492 +
6493 +debug.sethook()
6494 +
6495 +
6496 +-- tests for tail calls
6497 +local function f (x)
6498 + if x then
6499 + assert(debug.getinfo(1, "S").what == "Lua")
6500 + assert(debug.getinfo(1, "t").istailcall == true)
6501 + local tail = debug.getinfo(2)
6502 + assert(tail.func == g1 and tail.istailcall == true)
6503 + assert(debug.getinfo(3, "S").what == "main")
6504 + print"+"
6505 + end
6506 +end
6507 +
6508 +function g(x) return f(x) end
6509 +
6510 +function g1(x) g(x) end
6511 +
6512 +local function h (x) local f=g1; return f(x) end
6513 +
6514 +h(true)
6515 +
6516 +local b = {}
6517 +debug.sethook(function (e) table.insert(b, e) end, "cr")
6518 +h(false)
6519 +debug.sethook()
6520 +local res = {"return", -- first return (from sethook)
6521 + "call", "tail call", "call", "tail call",
6522 + "return", "return",
6523 + "call", -- last call (to sethook)
6524 +}
6525 +for i = 1, #res do assert(res[i] == table.remove(b, 1)) end
6526 +
6527 +b = 0
6528 +debug.sethook(function (e)
6529 + if e == "tail call" then
6530 + b = b + 1
6531 + assert(debug.getinfo(2, "t").istailcall == true)
6532 + else
6533 + assert(debug.getinfo(2, "t").istailcall == false)
6534 + end
6535 + end, "c")
6536 +h(false)
6537 +debug.sethook()
6538 +assert(b == 2) -- two tail calls
6539 +
6540 +lim = _soft and 3000 or 30000
6541 +local function foo (x)
6542 + if x==0 then
6543 + assert(debug.getinfo(2).what == "main")
6544 + local info = debug.getinfo(1)
6545 + assert(info.istailcall == true and info.func == foo)
6546 + else return foo(x-1)
6547 + end
6548 +end
6549 +
6550 +foo(lim)
6551 +
6552 +
6553 +print"+"
6554 +
6555 +
6556 +-- testing local function information
6557 +co = load[[
6558 + local A = function ()
6559 + return x
6560 + end
6561 + return
6562 +]]
6563 +
6564 +local a = 0
6565 +-- 'A' should be visible to debugger only after its complete definition
6566 +debug.sethook(function (e, l)
6567 + if l == 3 then a = a + 1; assert(debug.getlocal(2, 1) == "(temporary)")
6568 + elseif l == 4 then a = a + 1; assert(debug.getlocal(2, 1) == "A")
6569 + end
6570 +end, "l")
6571 +co() -- run local function definition
6572 +debug.sethook() -- turn off hook
6573 +assert(a == 2) -- ensure all two lines where hooked
6574 +
6575 +-- testing traceback
6576 +
6577 +assert(debug.traceback(print) == print)
6578 +assert(debug.traceback(print, 4) == print)
6579 +assert(string.find(debug.traceback("hi", 4), "^hi\n"))
6580 +assert(string.find(debug.traceback("hi"), "^hi\n"))
6581 +assert(not string.find(debug.traceback("hi"), "'debug.traceback'"))
6582 +assert(string.find(debug.traceback("hi", 0), "'debug.traceback'"))
6583 +assert(string.find(debug.traceback(), "^stack traceback:\n"))
6584 +
6585 +do -- C-function names in traceback
6586 + local st, msg = (function () return pcall end)()(debug.traceback)
6587 + assert(st == true and string.find(msg, "pcall"))
6588 +end
6589 +
6590 +
6591 +-- testing nparams, nups e isvararg
6592 +local t = debug.getinfo(print, "u")
6593 +assert(t.isvararg == true and t.nparams == 0 and t.nups == 0)
6594 +
6595 +t = debug.getinfo(function (a,b,c) end, "u")
6596 +assert(t.isvararg == false and t.nparams == 3 and t.nups == 0)
6597 +
6598 +t = debug.getinfo(function (a,b,...) return t[a] end, "u")
6599 +assert(t.isvararg == true and t.nparams == 2 and t.nups == 1)
6600 +
6601 +t = debug.getinfo(1) -- main
6602 +assert(t.isvararg == true and t.nparams == 0 and t.nups == 1 and
6603 + debug.getupvalue(t.func, 1) == "_ENV")
6604 +
6605 +t = debug.getinfo(math.sin) -- C function
6606 +assert(t.isvararg == true and t.nparams == 0 and t.nups == 0)
6607 +
6608 +t = debug.getinfo(string.gmatch("abc", "a")) -- C closure
6609 +assert(t.isvararg == true and t.nparams == 0 and t.nups > 0)
6610 +
6611 +
6612 +
6613 +-- testing debugging of coroutines
6614 +
6615 +local function checktraceback (co, p, level)
6616 + local tb = debug.traceback(co, nil, level)
6617 + local i = 0
6618 + for l in string.gmatch(tb, "[^\n]+\n?") do
6619 + assert(i == 0 or string.find(l, p[i]))
6620 + i = i+1
6621 + end
6622 + assert(p[i] == undef)
6623 +end
6624 +
6625 +
6626 +local function f (n)
6627 + if n > 0 then f(n-1)
6628 + else coroutine.yield() end
6629 +end
6630 +
6631 +local co = coroutine.create(f)
6632 +coroutine.resume(co, 3)
6633 +checktraceback(co, {"yield", "db.lua", "db.lua", "db.lua", "db.lua"})
6634 +checktraceback(co, {"db.lua", "db.lua", "db.lua", "db.lua"}, 1)
6635 +checktraceback(co, {"db.lua", "db.lua", "db.lua"}, 2)
6636 +checktraceback(co, {"db.lua"}, 4)
6637 +checktraceback(co, {}, 40)
6638 +
6639 +
6640 +co = coroutine.create(function (x)
6641 + local a = 1
6642 + coroutine.yield(debug.getinfo(1, "l"))
6643 + coroutine.yield(debug.getinfo(1, "l").currentline)
6644 + return a
6645 + end)
6646 +
6647 +local tr = {}
6648 +local foo = function (e, l) if l then table.insert(tr, l) end end
6649 +debug.sethook(co, foo, "lcr")
6650 +
6651 +local _, l = coroutine.resume(co, 10)
6652 +local x = debug.getinfo(co, 1, "lfLS")
6653 +assert(x.currentline == l.currentline and x.activelines[x.currentline])
6654 +assert(type(x.func) == "function")
6655 +for i=x.linedefined + 1, x.lastlinedefined do
6656 + assert(x.activelines[i])
6657 + x.activelines[i] = undef
6658 +end
6659 +assert(next(x.activelines) == nil) -- no 'extra' elements
6660 +assert(not debug.getinfo(co, 2))
6661 +local a,b = debug.getlocal(co, 1, 1)
6662 +assert(a == "x" and b == 10)
6663 +a,b = debug.getlocal(co, 1, 2)
6664 +assert(a == "a" and b == 1)
6665 +debug.setlocal(co, 1, 2, "hi")
6666 +assert(debug.gethook(co) == foo)
6667 +assert(#tr == 2 and
6668 + tr[1] == l.currentline-1 and tr[2] == l.currentline)
6669 +
6670 +a,b,c = pcall(coroutine.resume, co)
6671 +assert(a and b and c == l.currentline+1)
6672 +checktraceback(co, {"yield", "in function <"})
6673 +
6674 +a,b = coroutine.resume(co)
6675 +assert(a and b == "hi")
6676 +assert(#tr == 4 and tr[4] == l.currentline+2)
6677 +assert(debug.gethook(co) == foo)
6678 +assert(not debug.gethook())
6679 +checktraceback(co, {})
6680 +
6681 +
6682 +-- check get/setlocal in coroutines
6683 +co = coroutine.create(function (x)
6684 + local a, b = coroutine.yield(x)
6685 + assert(a == 100 and b == nil)
6686 + return x
6687 +end)
6688 +a, b = coroutine.resume(co, 10)
6689 +assert(a and b == 10)
6690 +a, b = debug.getlocal(co, 1, 1)
6691 +assert(a == "x" and b == 10)
6692 +assert(not debug.getlocal(co, 1, 5))
6693 +assert(debug.setlocal(co, 1, 1, 30) == "x")
6694 +assert(not debug.setlocal(co, 1, 5, 40))
6695 +a, b = coroutine.resume(co, 100)
6696 +assert(a and b == 30)
6697 +
6698 +
6699 +-- check traceback of suspended (or dead with error) coroutines
6700 +
6701 +function f(i)
6702 + if i == 0 then error(i)
6703 + else coroutine.yield(); f(i-1)
6704 + end
6705 +end
6706 +
6707 +
6708 +co = coroutine.create(function (x) f(x) end)
6709 +a, b = coroutine.resume(co, 3)
6710 +t = {"'coroutine.yield'", "'f'", "in function <"}
6711 +while coroutine.status(co) == "suspended" do
6712 + checktraceback(co, t)
6713 + a, b = coroutine.resume(co)
6714 + table.insert(t, 2, "'f'") -- one more recursive call to 'f'
6715 +end
6716 +t[1] = "'error'"
6717 +checktraceback(co, t)
6718 +
6719 +
6720 +-- test acessing line numbers of a coroutine from a resume inside
6721 +-- a C function (this is a known bug in Lua 5.0)
6722 +
6723 +local function g(x)
6724 + coroutine.yield(x)
6725 +end
6726 +
6727 +local function f (i)
6728 + debug.sethook(function () end, "l")
6729 + for j=1,1000 do
6730 + g(i+j)
6731 + end
6732 +end
6733 +
6734 +local co = coroutine.wrap(f)
6735 +co(10)
6736 +pcall(co)
6737 +pcall(co)
6738 +
6739 +
6740 +assert(type(debug.getregistry()) == "table")
6741 +
6742 +
6743 +-- test tagmethod information
6744 +local a = {}
6745 +local function f (t)
6746 + local info = debug.getinfo(1);
6747 + assert(info.namewhat == "metamethod")
6748 + a.op = info.name
6749 + return info.name
6750 +end
6751 +setmetatable(a, {
6752 + __index = f; __add = f; __div = f; __mod = f; __concat = f; __pow = f;
6753 + __mul = f; __idiv = f; __unm = f; __len = f; __sub = f;
6754 + __shl = f; __shr = f; __bor = f; __bxor = f;
6755 + __eq = f; __le = f; __lt = f; __unm = f; __len = f; __band = f;
6756 + __bnot = f;
6757 +})
6758 +
6759 +local b = setmetatable({}, getmetatable(a))
6760 +
6761 +assert(a[3] == "index" and a^3 == "pow" and a..a == "concat")
6762 +assert(a/3 == "div" and 3%a == "mod")
6763 +assert(a+3 == "add" and 3-a == "sub" and a*3 == "mul" and
6764 + -a == "unm" and #a == "len" and a&3 == "band")
6765 +assert(a + 30000 == "add" and a - 3.0 == "sub" and a * 3.0 == "mul" and
6766 + -a == "unm" and #a == "len" and a & 3 == "band")
6767 +assert(a|3 == "bor" and 3~a == "bxor" and a<<3 == "shl" and a>>1 == "shr")
6768 +assert (a==b and a.op == "eq")
6769 +assert (a>=b and a.op == "le")
6770 +assert ("x">=a and a.op == "le")
6771 +assert (a>b and a.op == "lt")
6772 +assert (a>10 and a.op == "lt")
6773 +assert(~a == "bnot")
6774 +
6775 +do -- testing for-iterator name
6776 + local function f()
6777 + assert(debug.getinfo(1).name == "for iterator")
6778 + end
6779 +
6780 + for i in f do end
6781 +end
6782 +
6783 +
6784 +do -- testing debug info for finalizers
6785 + local name = nil
6786 +
6787 + -- create a piece of garbage with a finalizer
6788 + setmetatable({}, {__gc = function ()
6789 + local t = debug.getinfo(1) -- get function information
6790 + assert(t.namewhat == "metamethod")
6791 + name = t.name
6792 + end})
6793 +
6794 + -- repeat until previous finalizer runs (setting 'name')
6795 + repeat local a = {} until name
6796 + assert(name == "__gc")
6797 +end
6798 +
6799 +
6800 +do
6801 + print("testing traceback sizes")
6802 +
6803 + local function countlines (s)
6804 + return select(2, string.gsub(s, "\n", ""))
6805 + end
6806 +
6807 + local function deep (lvl, n)
6808 + if lvl == 0 then
6809 + return (debug.traceback("message", n))
6810 + else
6811 + return (deep(lvl-1, n))
6812 + end
6813 + end
6814 +
6815 + local function checkdeep (total, start)
6816 + local s = deep(total, start)
6817 + local rest = string.match(s, "^message\nstack traceback:\n(.*)$")
6818 + local cl = countlines(rest)
6819 + -- at most 10 lines in first part, 11 in second, plus '...'
6820 + assert(cl <= 10 + 11 + 1)
6821 + local brk = string.find(rest, "%.%.%.")
6822 + if brk then -- does message have '...'?
6823 + local rest1 = string.sub(rest, 1, brk)
6824 + local rest2 = string.sub(rest, brk, #rest)
6825 + assert(countlines(rest1) == 10 and countlines(rest2) == 11)
6826 + else
6827 + assert(cl == total - start + 2)
6828 + end
6829 + end
6830 +
6831 + for d = 1, 51, 10 do
6832 + for l = 1, d do
6833 + -- use coroutines to ensure complete control of the stack
6834 + coroutine.wrap(checkdeep)(d, l)
6835 + end
6836 + end
6837 +
6838 +end
6839 +
6840 +
6841 +print("testing debug functions on chunk without debug info")
6842 +prog = [[-- program to be loaded without debug information (strip)
6843 +local debug = require'debug'
6844 +local a = 12 -- a local variable
6845 +
6846 +local n, v = debug.getlocal(1, 1)
6847 +assert(n == "(temporary)" and v == debug) -- unkown name but known value
6848 +n, v = debug.getlocal(1, 2)
6849 +assert(n == "(temporary)" and v == 12) -- unkown name but known value
6850 +
6851 +-- a function with an upvalue
6852 +local f = function () local x; return a end
6853 +n, v = debug.getupvalue(f, 1)
6854 +assert(n == "(no name)" and v == 12)
6855 +assert(debug.setupvalue(f, 1, 13) == "(no name)")
6856 +assert(a == 13)
6857 +
6858 +local t = debug.getinfo(f)
6859 +assert(t.name == nil and t.linedefined > 0 and
6860 + t.lastlinedefined == t.linedefined and
6861 + t.short_src == "?")
6862 +assert(debug.getinfo(1).currentline == -1)
6863 +
6864 +t = debug.getinfo(f, "L").activelines
6865 +assert(next(t) == nil) -- active lines are empty
6866 +
6867 +-- dump/load a function without debug info
6868 +f = load(string.dump(f))
6869 +
6870 +t = debug.getinfo(f)
6871 +assert(t.name == nil and t.linedefined > 0 and
6872 + t.lastlinedefined == t.linedefined and
6873 + t.short_src == "?")
6874 +assert(debug.getinfo(1).currentline == -1)
6875 +
6876 +return a
6877 +]]
6878 +
6879 +
6880 +-- load 'prog' without debug info
6881 +local f = assert(load(string.dump(load(prog), true)))
6882 +
6883 +assert(f() == 13)
6884 +
6885 +do -- bug in 5.4.0: line hooks in stripped code
6886 + local function foo ()
6887 + local a = 1
6888 + local b = 2
6889 + return b
6890 + end
6891 +
6892 + local s = load(string.dump(foo, true))
6893 + local line = true
6894 + debug.sethook(function (e, l)
6895 + assert(e == "line")
6896 + line = l
6897 + end, "l")
6898 + assert(s() == 2); debug.sethook(nil)
6899 + assert(line == nil) -- hook called withoug debug info for 1st instruction
6900 +end
6901 +
6902 +do -- tests for 'source' in binary dumps
6903 + local prog = [[
6904 + return function (x)
6905 + return function (y)
6906 + return x + y
6907 + end
6908 + end
6909 + ]]
6910 + local name = string.rep("x", 1000)
6911 + local p = assert(load(prog, name))
6912 + -- load 'p' as a binary chunk with debug information
6913 + local c = string.dump(p)
6914 + assert(#c > 1000 and #c < 2000) -- no repetition of 'source' in dump
6915 + local f = assert(load(c))
6916 + local g = f()
6917 + local h = g(3)
6918 + assert(h(5) == 8)
6919 + assert(debug.getinfo(f).source == name and -- all functions have 'source'
6920 + debug.getinfo(g).source == name and
6921 + debug.getinfo(h).source == name)
6922 + -- again, without debug info
6923 + local c = string.dump(p, true)
6924 + assert(#c < 500) -- no 'source' in dump
6925 + local f = assert(load(c))
6926 + local g = f()
6927 + local h = g(30)
6928 + assert(h(50) == 80)
6929 + assert(debug.getinfo(f).source == '=?' and -- no function has 'source'
6930 + debug.getinfo(g).source == '=?' and
6931 + debug.getinfo(h).source == '=?')
6932 +end
6933 +
6934 +print"OK"
6935 +
6936
6937 diff --git a/tests/errors.lua b/tests/errors.lua
6938 new file mode 100644
6939 index 0000000..55bdab8
6940 --- /dev/null
6941 +++ b/tests/errors.lua
6942 @@ -0,0 +1,661 @@
6943 +-- $Id: testes/errors.lua $
6944 +-- See Copyright Notice in file all.lua
6945 +
6946 +print("testing errors")
6947 +
6948 +local debug = require"debug"
6949 +
6950 +-- avoid problems with 'strict' module (which may generate other error messages)
6951 +local mt = getmetatable(_G) or {}
6952 +local oldmm = mt.__index
6953 +mt.__index = nil
6954 +
6955 +local function checkerr (msg, f, ...)
6956 + local st, err = pcall(f, ...)
6957 + assert(not st and string.find(err, msg))
6958 +end
6959 +
6960 +
6961 +local function doit (s)
6962 + local f, msg = load(s)
6963 + if not f then return msg end
6964 + local cond, msg = pcall(f)
6965 + return (not cond) and msg
6966 +end
6967 +
6968 +
6969 +local function checkmessage (prog, msg, debug)
6970 + local m = doit(prog)
6971 + if debug then print(m, msg) end
6972 + assert(string.find(m, msg, 1, true))
6973 +end
6974 +
6975 +local function checksyntax (prog, extra, token, line)
6976 + local msg = doit(prog)
6977 + if not string.find(token, "^<%a") and not string.find(token, "^char%(")
6978 + then token = "'"..token.."'" end
6979 + token = string.gsub(token, "(%p)", "%%%1")
6980 + local pt = string.format([[^%%[string ".*"%%]:%d: .- near %s$]],
6981 + line, token)
6982 + assert(string.find(msg, pt))
6983 + assert(string.find(msg, msg, 1, true))
6984 +end
6985 +
6986 +
6987 +-- test error message with no extra info
6988 +assert(doit("error('hi', 0)") == 'hi')
6989 +
6990 +-- test error message with no info
6991 +assert(doit("error()") == nil)
6992 +
6993 +
6994 +-- test common errors/errors that crashed in the past
6995 +assert(doit("table.unpack({}, 1, n=2^30)"))
6996 +assert(doit("a=math.sin()"))
6997 +assert(not doit("tostring(1)") and doit("tostring()"))
6998 +assert(doit"tonumber()")
6999 +assert(doit"repeat until 1; a")
7000 +assert(doit"return;;")
7001 +assert(doit"assert(false)")
7002 +assert(doit"assert(nil)")
7003 +assert(doit("function a (... , ...) end"))
7004 +assert(doit("function a (, ...) end"))
7005 +assert(doit("local t={}; t = t[#t] + 1"))
7006 +
7007 +checksyntax([[
7008 + local a = {4
7009 +
7010 +]], "'}' expected (to close '{' at line 1)", "<eof>", 3)
7011 +
7012 +
7013 +do -- testing errors in goto/break
7014 + local function checksyntax (prog, msg, line)
7015 + local st, err = load(prog)
7016 + assert(string.find(err, "line " .. line))
7017 + assert(string.find(err, msg, 1, true))
7018 + end
7019 +
7020 + checksyntax([[
7021 + ::A:: a = 1
7022 + ::A::
7023 + ]], "label 'A' already defined", 1)
7024 +
7025 + checksyntax([[
7026 + a = 1
7027 + goto A
7028 + do ::A:: end
7029 + ]], "no visible label 'A'", 2)
7030 +
7031 +end
7032 +
7033 +
7034 +if not T then
7035 + (Message or print)
7036 + ('\n >>> testC not active: skipping memory message test <<<\n')
7037 +else
7038 + print "testing memory error message"
7039 + local a = {}
7040 + for i = 1, 10000 do a[i] = true end -- preallocate array
7041 + collectgarbage()
7042 + T.totalmem(T.totalmem() + 10000)
7043 + -- force a memory error (by a small margin)
7044 + local st, msg = pcall(function()
7045 + for i = 1, 100000 do a[i] = tostring(i) end
7046 + end)
7047 + T.totalmem(0)
7048 + assert(not st and msg == "not enough" .. " memory")
7049 +end
7050 +
7051 +
7052 +-- tests for better error messages
7053 +
7054 +checkmessage("a = {} + 1", "arithmetic")
7055 +checkmessage("a = {} | 1", "bitwise operation")
7056 +checkmessage("a = {} < 1", "attempt to compare")
7057 +checkmessage("a = {} <= 1", "attempt to compare")
7058 +
7059 +checkmessage("a=1; bbbb=2; a=math.sin(3)+bbbb(3)", "global 'bbbb'")
7060 +checkmessage("a={}; do local a=1 end a:bbbb(3)", "method 'bbbb'")
7061 +checkmessage("local a={}; a.bbbb(3)", "field 'bbbb'")
7062 +assert(not string.find(doit"a={13}; local bbbb=1; a[bbbb](3)", "'bbbb'"))
7063 +checkmessage("a={13}; local bbbb=1; a[bbbb](3)", "number")
7064 +checkmessage("a=(1)..{}", "a table value")
7065 +
7066 +-- calls
7067 +checkmessage("local a; a(13)", "local 'a'")
7068 +checkmessage([[
7069 + local a = setmetatable({}, {__add = 34})
7070 + a = a + 1
7071 +]], "metamethod 'add'")
7072 +checkmessage([[
7073 + local a = setmetatable({}, {__lt = {}})
7074 + a = a > a
7075 +]], "metamethod 'lt'")
7076 +
7077 +-- tail calls
7078 +checkmessage("local a={}; return a.bbbb(3)", "field 'bbbb'")
7079 +checkmessage("a={}; do local a=1 end; return a:bbbb(3)", "method 'bbbb'")
7080 +
7081 +checkmessage("a = #print", "length of a function value")
7082 +checkmessage("a = #3", "length of a number value")
7083 +
7084 +aaa = nil
7085 +checkmessage("aaa.bbb:ddd(9)", "global 'aaa'")
7086 +checkmessage("local aaa={bbb=1}; aaa.bbb:ddd(9)", "field 'bbb'")
7087 +checkmessage("local aaa={bbb={}}; aaa.bbb:ddd(9)", "method 'ddd'")
7088 +checkmessage("local a,b,c; (function () a = b+1.1 end)()", "upvalue 'b'")
7089 +assert(not doit"local aaa={bbb={ddd=next}}; aaa.bbb:ddd(nil)")
7090 +
7091 +-- upvalues being indexed do not go to the stack
7092 +checkmessage("local a,b,cc; (function () a = cc[1] end)()", "upvalue 'cc'")
7093 +checkmessage("local a,b,cc; (function () a.x = 1 end)()", "upvalue 'a'")
7094 +
7095 +checkmessage("local _ENV = {x={}}; a = a + 1", "global 'a'")
7096 +
7097 +checkmessage("b=1; local aaa={}; x=aaa+b", "local 'aaa'")
7098 +checkmessage("aaa={}; x=3.3/aaa", "global 'aaa'")
7099 +checkmessage("aaa=2; b=nil;x=aaa*b", "global 'b'")
7100 +checkmessage("aaa={}; x=-aaa", "global 'aaa'")
7101 +
7102 +-- short circuit
7103 +checkmessage("a=1; local a,bbbb=2,3; a = math.sin(1) and bbbb(3)",
7104 + "local 'bbbb'")
7105 +checkmessage("a=1; local a,bbbb=2,3; a = bbbb(1) or a(3)", "local 'bbbb'")
7106 +checkmessage("local a,b,c,f = 1,1,1; f((a and b) or c)", "local 'f'")
7107 +checkmessage("local a,b,c = 1,1,1; ((a and b) or c)()", "call a number value")
7108 +assert(not string.find(doit"aaa={}; x=(aaa or aaa)+(aaa and aaa)", "'aaa'"))
7109 +assert(not string.find(doit"aaa={}; (aaa or aaa)()", "'aaa'"))
7110 +
7111 +checkmessage("print(print < 10)", "function with number")
7112 +checkmessage("print(print < print)", "two function values")
7113 +checkmessage("print('10' < 10)", "string with number")
7114 +checkmessage("print(10 < '23')", "number with string")
7115 +
7116 +-- float->integer conversions
7117 +checkmessage("local a = 2.0^100; x = a << 2", "local a")
7118 +checkmessage("local a = 1 >> 2.0^100", "has no integer representation")
7119 +checkmessage("local a = 10.1 << 2.0^100", "has no integer representation")
7120 +checkmessage("local a = 2.0^100 & 1", "has no integer representation")
7121 +checkmessage("local a = 2.0^100 & 1e100", "has no integer representation")
7122 +checkmessage("local a = 2.0 | 1e40", "has no integer representation")
7123 +checkmessage("local a = 2e100 ~ 1", "has no integer representation")
7124 +checkmessage("string.sub('a', 2.0^100)", "has no integer representation")
7125 +checkmessage("string.rep('a', 3.3)", "has no integer representation")
7126 +checkmessage("return 6e40 & 7", "has no integer representation")
7127 +checkmessage("return 34 << 7e30", "has no integer representation")
7128 +checkmessage("return ~-3e40", "has no integer representation")
7129 +checkmessage("return ~-3.009", "has no integer representation")
7130 +checkmessage("return 3.009 & 1", "has no integer representation")
7131 +checkmessage("return 34 >> {}", "table value")
7132 +checkmessage("a = 24 // 0", "divide by zero")
7133 +checkmessage("a = 1 % 0", "'n%0'")
7134 +
7135 +
7136 +-- type error for an object which is neither in an upvalue nor a register.
7137 +-- The following code will try to index the value 10 that is stored in
7138 +-- the metatable, without moving it to a register.
7139 +checkmessage("local a = setmetatable({}, {__index = 10}).x",
7140 + "attempt to index a number value")
7141 +
7142 +
7143 +-- numeric for loops
7144 +checkmessage("for i = {}, 10 do end", "table")
7145 +checkmessage("for i = io.stdin, 10 do end", "FILE")
7146 +checkmessage("for i = {}, 10 do end", "initial value")
7147 +checkmessage("for i = 1, 'x', 10 do end", "string")
7148 +checkmessage("for i = 1, {}, 10 do end", "limit")
7149 +checkmessage("for i = 1, {} do end", "limit")
7150 +checkmessage("for i = 1, 10, print do end", "step")
7151 +checkmessage("for i = 1, 10, print do end", "function")
7152 +
7153 +-- passing light userdata instead of full userdata
7154 +_G.D = debug
7155 +checkmessage([[
7156 + -- create light udata
7157 + local x = D.upvalueid(function () return debug end, 1)
7158 + D.setuservalue(x, {})
7159 +]], "light userdata")
7160 +_G.D = nil
7161 +
7162 +do -- named objects (field '__name')
7163 + checkmessage("math.sin(io.input())", "(number expected, got FILE*)")
7164 + _G.XX = setmetatable({}, {__name = "My Type"})
7165 + assert(string.find(tostring(XX), "^My Type"))
7166 + checkmessage("io.input(XX)", "(FILE* expected, got My Type)")
7167 + checkmessage("return XX + 1", "on a My Type value")
7168 + checkmessage("return ~io.stdin", "on a FILE* value")
7169 + checkmessage("return XX < XX", "two My Type values")
7170 + checkmessage("return {} < XX", "table with My Type")
7171 + checkmessage("return XX < io.stdin", "My Type with FILE*")
7172 + _G.XX = nil
7173 +
7174 + if T then -- extra tests for 'luaL_tolstring'
7175 + -- bug in 5.4.3; 'luaL_tolstring' with negative indices
7176 + local x = setmetatable({}, {__name="TABLE"})
7177 + assert(T.testC("Ltolstring -1; return 1", x) == tostring(x))
7178 +
7179 + local a, b = T.testC("pushint 10; Ltolstring -2; return 2", x)
7180 + assert(a == 10 and b == tostring(x))
7181 +
7182 + setmetatable(x, {__tostring=function (o)
7183 + assert(o == x)
7184 + return "ABC"
7185 + end})
7186 + local a, b, c = T.testC("pushint 10; Ltolstring -2; return 3", x)
7187 + assert(a == x and b == 10 and c == "ABC")
7188 + end
7189 +end
7190 +
7191 +-- global functions
7192 +checkmessage("(io.write or print){}", "io.write")
7193 +checkmessage("(collectgarbage or print){}", "collectgarbage")
7194 +
7195 +-- errors in functions without debug info
7196 +do
7197 + local f = function (a) return a + 1 end
7198 + f = assert(load(string.dump(f, true)))
7199 + assert(f(3) == 4)
7200 + checkerr("^%?:%-1:", f, {})
7201 +
7202 + -- code with a move to a local var ('OP_MOV A B' with A<B)
7203 + f = function () local a; a = {}; return a + 2 end
7204 + -- no debug info (so that 'a' is unknown)
7205 + f = assert(load(string.dump(f, true)))
7206 + -- symbolic execution should not get lost
7207 + checkerr("^%?:%-1:.*table value", f)
7208 +end
7209 +
7210 +
7211 +-- tests for field accesses after RK limit
7212 +local t = {}
7213 +for i = 1, 1000 do
7214 + t[i] = "a = x" .. i
7215 +end
7216 +local s = table.concat(t, "; ")
7217 +t = nil
7218 +checkmessage(s.."; a = bbb + 1", "global 'bbb'")
7219 +checkmessage("local _ENV=_ENV;"..s.."; a = bbb + 1", "global 'bbb'")
7220 +checkmessage(s.."; local t = {}; a = t.bbb + 1", "field 'bbb'")
7221 +checkmessage(s.."; local t = {}; t:bbb()", "method 'bbb'")
7222 +
7223 +checkmessage([[aaa=9
7224 +repeat until 3==3
7225 +local x=math.sin(math.cos(3))
7226 +if math.sin(1) == x then return math.sin(1) end -- tail call
7227 +local a,b = 1, {
7228 + {x='a'..'b'..'c', y='b', z=x},
7229 + {1,2,3,4,5} or 3+3<=3+3,
7230 + 3+1>3+1,
7231 + {d = x and aaa[x or y]}}
7232 +]], "global 'aaa'")
7233 +
7234 +checkmessage([[
7235 +local x,y = {},1
7236 +if math.sin(1) == 0 then return 3 end -- return
7237 +x.a()]], "field 'a'")
7238 +
7239 +checkmessage([[
7240 +prefix = nil
7241 +insert = nil
7242 +while 1 do
7243 + local a
7244 + if nil then break end
7245 + insert(prefix, a)
7246 +end]], "global 'insert'")
7247 +
7248 +checkmessage([[ -- tail call
7249 + return math.sin("a")
7250 +]], "sin")
7251 +
7252 +checkmessage([[collectgarbage("nooption")]], "invalid option")
7253 +
7254 +checkmessage([[x = print .. "a"]], "concatenate")
7255 +checkmessage([[x = "a" .. false]], "concatenate")
7256 +checkmessage([[x = {} .. 2]], "concatenate")
7257 +
7258 +checkmessage("getmetatable(io.stdin).__gc()", "no value")
7259 +
7260 +checkmessage([[
7261 +local Var
7262 +local function main()
7263 + NoSuchName (function() Var=0 end)
7264 +end
7265 +main()
7266 +]], "global 'NoSuchName'")
7267 +print'+'
7268 +
7269 +a = {}; setmetatable(a, {__index = string})
7270 +checkmessage("a:sub()", "bad self")
7271 +checkmessage("string.sub('a', {})", "#2")
7272 +checkmessage("('a'):sub{}", "#1")
7273 +
7274 +checkmessage("table.sort({1,2,3}, table.sort)", "'table.sort'")
7275 +checkmessage("string.gsub('s', 's', setmetatable)", "'setmetatable'")
7276 +
7277 +-- tests for errors in coroutines
7278 +
7279 +local function f (n)
7280 + local c = coroutine.create(f)
7281 + local a,b = coroutine.resume(c)
7282 + return b
7283 +end
7284 +assert(string.find(f(), "C stack overflow"))
7285 +
7286 +checkmessage("coroutine.yield()", "outside a coroutine")
7287 +
7288 +f = coroutine.wrap(function () table.sort({1,2,3}, coroutine.yield) end)
7289 +checkerr("yield across", f)
7290 +
7291 +
7292 +-- testing size of 'source' info; size of buffer for that info is
7293 +-- LUA_IDSIZE, declared as 60 in luaconf. Get one position for '\0'.
7294 +idsize = 60 - 1
7295 +local function checksize (source)
7296 + -- syntax error
7297 + local _, msg = load("x", source)
7298 + msg = string.match(msg, "^([^:]*):") -- get source (1st part before ':')
7299 + assert(msg:len() <= idsize)
7300 +end
7301 +
7302 +for i = 60 - 10, 60 + 10 do -- check border cases around 60
7303 + checksize("@" .. string.rep("x", i)) -- file names
7304 + checksize(string.rep("x", i - 10)) -- string sources
7305 + checksize("=" .. string.rep("x", i)) -- exact sources
7306 +end
7307 +
7308 +
7309 +-- testing line error
7310 +
7311 +local function lineerror (s, l)
7312 + local err,msg = pcall(load(s))
7313 + local line = tonumber(string.match(msg, ":(%d+):"))
7314 + assert(line == l or (not line and not l))
7315 +end
7316 +
7317 +lineerror("local a\n for i=1,'a' do \n print(i) \n end", 2)
7318 +lineerror("\n local a \n for k,v in 3 \n do \n print(k) \n end", 3)
7319 +lineerror("\n\n for k,v in \n 3 \n do \n print(k) \n end", 4)
7320 +lineerror("function a.x.y ()\na=a+1\nend", 1)
7321 +
7322 +lineerror("a = \na\n+\n{}", 3)
7323 +lineerror("a = \n3\n+\n(\n4\n/\nprint)", 6)
7324 +lineerror("a = \nprint\n+\n(\n4\n/\n7)", 3)
7325 +
7326 +lineerror("a\n=\n-\n\nprint\n;", 3)
7327 +
7328 +lineerror([[
7329 +a
7330 +(
7331 +23)
7332 +]], 1)
7333 +
7334 +lineerror([[
7335 +local a = {x = 13}
7336 +a
7337 +.
7338 +x
7339 +(
7340 +23
7341 +)
7342 +]], 2)
7343 +
7344 +lineerror([[
7345 +local a = {x = 13}
7346 +a
7347 +.
7348 +x
7349 +(
7350 +23 + a
7351 +)
7352 +]], 6)
7353 +
7354 +local p = [[
7355 + function g() f() end
7356 + function f(x) error('a', X) end
7357 +g()
7358 +]]
7359 +X=3;lineerror((p), 3)
7360 +X=0;lineerror((p), false)
7361 +X=1;lineerror((p), 2)
7362 +X=2;lineerror((p), 1)
7363 +
7364 +
7365 +lineerror([[
7366 +local b = false
7367 +if not b then
7368 + error 'test'
7369 +end]], 3)
7370 +
7371 +lineerror([[
7372 +local b = false
7373 +if not b then
7374 + if not b then
7375 + if not b then
7376 + error 'test'
7377 + end
7378 + end
7379 +end]], 5)
7380 +
7381 +do
7382 + -- Force a negative estimate for base line. Error in instruction 2
7383 + -- (after VARARGPREP, GETGLOBAL), with first absolute line information
7384 + -- (forced by too many lines) in instruction 0.
7385 + local s = string.format("%s return __A.x", string.rep("\n", 300))
7386 + lineerror(s, 301)
7387 +end
7388 +
7389 +
7390 +if not _soft then
7391 + -- several tests that exaust the Lua stack
7392 + collectgarbage()
7393 + print"testing stack overflow"
7394 + C = 0
7395 + -- get line where stack overflow will happen
7396 + local l = debug.getinfo(1, "l").currentline + 1
7397 + local function auxy () C=C+1; auxy() end -- produce a stack overflow
7398 + function y ()
7399 + collectgarbage("stop") -- avoid running finalizers without stack space
7400 + auxy()
7401 + collectgarbage("restart")
7402 + end
7403 +
7404 + local function checkstackmessage (m)
7405 + print("(expected stack overflow after " .. C .. " calls)")
7406 + C = 0 -- prepare next count
7407 + return (string.find(m, "stack overflow"))
7408 + end
7409 + -- repeated stack overflows (to check stack recovery)
7410 + assert(checkstackmessage(doit('y()')))
7411 + assert(checkstackmessage(doit('y()')))
7412 + assert(checkstackmessage(doit('y()')))
7413 +
7414 +
7415 + -- error lines in stack overflow
7416 + local l1
7417 + local function g(x)
7418 + l1 = debug.getinfo(x, "l").currentline + 2
7419 + collectgarbage("stop") -- avoid running finalizers without stack space
7420 + auxy()
7421 + collectgarbage("restart")
7422 + end
7423 + local _, stackmsg = xpcall(g, debug.traceback, 1)
7424 + print('+')
7425 + local stack = {}
7426 + for line in string.gmatch(stackmsg, "[^\n]*") do
7427 + local curr = string.match(line, ":(%d+):")
7428 + if curr then table.insert(stack, tonumber(curr)) end
7429 + end
7430 + local i=1
7431 + while stack[i] ~= l1 do
7432 + assert(stack[i] == l)
7433 + i = i+1
7434 + end
7435 + assert(i > 15)
7436 +
7437 +
7438 + -- error in error handling
7439 + local res, msg = xpcall(error, error)
7440 + assert(not res and type(msg) == 'string')
7441 + print('+')
7442 +
7443 + local function f (x)
7444 + if x==0 then error('a\n')
7445 + else
7446 + local aux = function () return f(x-1) end
7447 + local a,b = xpcall(aux, aux)
7448 + return a,b
7449 + end
7450 + end
7451 + f(3)
7452 +
7453 + local function loop (x,y,z) return 1 + loop(x, y, z) end
7454 +
7455 + local res, msg = xpcall(loop, function (m)
7456 + assert(string.find(m, "stack overflow"))
7457 + checkerr("error handling", loop)
7458 + assert(math.sin(0) == 0)
7459 + return 15
7460 + end)
7461 + assert(msg == 15)
7462 +
7463 + local f = function ()
7464 + for i = 999900, 1000000, 1 do table.unpack({}, 1, i) end
7465 + end
7466 + checkerr("too many results", f)
7467 +
7468 +end
7469 +
7470 +
7471 +do
7472 + -- non string messages
7473 + local t = {}
7474 + local res, msg = pcall(function () error(t) end)
7475 + assert(not res and msg == t)
7476 +
7477 + res, msg = pcall(function () error(nil) end)
7478 + assert(not res and msg == nil)
7479 +
7480 + local function f() error{msg='x'} end
7481 + res, msg = xpcall(f, function (r) return {msg=r.msg..'y'} end)
7482 + assert(msg.msg == 'xy')
7483 +
7484 + -- 'assert' with extra arguments
7485 + res, msg = pcall(assert, false, "X", t)
7486 + assert(not res and msg == "X")
7487 +
7488 + -- 'assert' with no message
7489 + res, msg = pcall(function () assert(false) end)
7490 + local line = string.match(msg, "%w+%.lua:(%d+): assertion failed!$")
7491 + assert(tonumber(line) == debug.getinfo(1, "l").currentline - 2)
7492 +
7493 + -- 'assert' with non-string messages
7494 + res, msg = pcall(assert, false, t)
7495 + assert(not res and msg == t)
7496 +
7497 + res, msg = pcall(assert, nil, nil)
7498 + assert(not res and msg == nil)
7499 +
7500 + -- 'assert' without arguments
7501 + res, msg = pcall(assert)
7502 + assert(not res and string.find(msg, "value expected"))
7503 +end
7504 +
7505 +-- xpcall with arguments
7506 +a, b, c = xpcall(string.find, error, "alo", "al")
7507 +assert(a and b == 1 and c == 2)
7508 +a, b, c = xpcall(string.find, function (x) return {} end, true, "al")
7509 +assert(not a and type(b) == "table" and c == nil)
7510 +
7511 +
7512 +print("testing tokens in error messages")
7513 +checksyntax("syntax error", "", "error", 1)
7514 +checksyntax("1.000", "", "1.000", 1)
7515 +checksyntax("[[a]]", "", "[[a]]", 1)
7516 +checksyntax("'aa'", "", "'aa'", 1)
7517 +checksyntax("while << do end", "", "<<", 1)
7518 +checksyntax("for >> do end", "", ">>", 1)
7519 +
7520 +-- test invalid non-printable char in a chunk
7521 +checksyntax("a\1a = 1", "", "<\\1>", 1)
7522 +
7523 +-- test 255 as first char in a chunk
7524 +checksyntax("\255a = 1", "", "<\\255>", 1)
7525 +
7526 +doit('I = load("a=9+"); a=3')
7527 +assert(a==3 and not I)
7528 +print('+')
7529 +
7530 +lim = 1000
7531 +if _soft then lim = 100 end
7532 +for i=1,lim do
7533 + doit('a = ')
7534 + doit('a = 4+nil')
7535 +end
7536 +
7537 +
7538 +-- testing syntax limits
7539 +
7540 +local function testrep (init, rep, close, repc, finalresult)
7541 + local s = init .. string.rep(rep, 100) .. close .. string.rep(repc, 100)
7542 + local res, msg = load(s)
7543 + assert(res) -- 100 levels is OK
7544 + if (finalresult) then
7545 + assert(res() == finalresult)
7546 + end
7547 + s = init .. string.rep(rep, 500)
7548 + local res, msg = load(s) -- 500 levels not ok
7549 + assert(not res and (string.find(msg, "too many") or
7550 + string.find(msg, "overflow")))
7551 +end
7552 +
7553 +testrep("local a; a", ",a", "= 1", ",1") -- multiple assignment
7554 +testrep("local a; a=", "{", "0", "}")
7555 +testrep("return ", "(", "2", ")", 2)
7556 +testrep("local function a (x) return x end; return ", "a(", "2.2", ")", 2.2)
7557 +testrep("", "do ", "", " end")
7558 +testrep("", "while a do ", "", " end")
7559 +testrep("local a; ", "if a then else ", "", " end")
7560 +testrep("", "function foo () ", "", " end")
7561 +testrep("local a = ''; return ", "a..", "'a'", "", "a")
7562 +testrep("local a = 1; return ", "a^", "a", "", 1)
7563 +
7564 +checkmessage("a = f(x" .. string.rep(",x", 260) .. ")", "too many registers")
7565 +
7566 +
7567 +-- testing other limits
7568 +
7569 +-- upvalues
7570 +local lim = 127
7571 +local s = "local function fooA ()\n local "
7572 +for j = 1,lim do
7573 + s = s.."a"..j..", "
7574 +end
7575 +s = s.."b,c\n"
7576 +s = s.."local function fooB ()\n local "
7577 +for j = 1,lim do
7578 + s = s.."b"..j..", "
7579 +end
7580 +s = s.."b\n"
7581 +s = s.."function fooC () return b+c"
7582 +local c = 1+2
7583 +for j = 1,lim do
7584 + s = s.."+a"..j.."+b"..j
7585 + c = c + 2
7586 +end
7587 +s = s.."\nend end end"
7588 +local a,b = load(s)
7589 +assert(c > 255 and string.find(b, "too many upvalues") and
7590 + string.find(b, "line 5"))
7591 +
7592 +-- local variables
7593 +s = "\nfunction foo ()\n local "
7594 +for j = 1,300 do
7595 + s = s.."a"..j..", "
7596 +end
7597 +s = s.."b\n"
7598 +local a,b = load(s)
7599 +assert(string.find(b, "line 2") and string.find(b, "too many local variables"))
7600 +
7601 +mt.__index = oldmm
7602 +
7603 +print('OK')
7604
7605 diff --git a/tests/events.lua b/tests/events.lua
7606 new file mode 100644
7607 index 0000000..17a7366
7608 --- /dev/null
7609 +++ b/tests/events.lua
7610 @@ -0,0 +1,488 @@
7611 +-- $Id: testes/events.lua $
7612 +-- See Copyright Notice in file all.lua
7613 +
7614 +print('testing metatables')
7615 +
7616 +local debug = require'debug'
7617 +
7618 +X = 20; B = 30
7619 +
7620 +_ENV = setmetatable({}, {__index=_G})
7621 +
7622 +collectgarbage()
7623 +
7624 +X = X+10
7625 +assert(X == 30 and _G.X == 20)
7626 +B = false
7627 +assert(B == false)
7628 +_ENV["B"] = undef
7629 +assert(B == 30)
7630 +
7631 +assert(getmetatable{} == nil)
7632 +assert(getmetatable(4) == nil)
7633 +assert(getmetatable(nil) == nil)
7634 +a={name = "NAME"}; setmetatable(a, {__metatable = "xuxu",
7635 + __tostring=function(x) return x.name end})
7636 +assert(getmetatable(a) == "xuxu")
7637 +assert(tostring(a) == "NAME")
7638 +-- cannot change a protected metatable
7639 +assert(pcall(setmetatable, a, {}) == false)
7640 +a.name = "gororoba"
7641 +assert(tostring(a) == "gororoba")
7642 +
7643 +local a, t = {10,20,30; x="10", y="20"}, {}
7644 +assert(setmetatable(a,t) == a)
7645 +assert(getmetatable(a) == t)
7646 +assert(setmetatable(a,nil) == a)
7647 +assert(getmetatable(a) == nil)
7648 +assert(setmetatable(a,t) == a)
7649 +
7650 +
7651 +function f (t, i, e)
7652 + assert(not e)
7653 + local p = rawget(t, "parent")
7654 + return (p and p[i]+3), "dummy return"
7655 +end
7656 +
7657 +t.__index = f
7658 +
7659 +a.parent = {z=25, x=12, [4] = 24}
7660 +assert(a[1] == 10 and a.z == 28 and a[4] == 27 and a.x == "10")
7661 +
7662 +collectgarbage()
7663 +
7664 +a = setmetatable({}, t)
7665 +function f(t, i, v) rawset(t, i, v-3) end
7666 +setmetatable(t, t) -- causes a bug in 5.1 !
7667 +t.__newindex = f
7668 +a[1] = 30; a.x = "101"; a[5] = 200
7669 +assert(a[1] == 27 and a.x == 98 and a[5] == 197)
7670 +
7671 +do -- bug in Lua 5.3.2
7672 + local mt = {}
7673 + mt.__newindex = mt
7674 + local t = setmetatable({}, mt)
7675 + t[1] = 10 -- will segfault on some machines
7676 + assert(mt[1] == 10)
7677 +end
7678 +
7679 +
7680 +local c = {}
7681 +a = setmetatable({}, t)
7682 +t.__newindex = c
7683 +t.__index = c
7684 +a[1] = 10; a[2] = 20; a[3] = 90;
7685 +for i = 4, 20 do a[i] = i * 10 end
7686 +assert(a[1] == 10 and a[2] == 20 and a[3] == 90)
7687 +for i = 4, 20 do assert(a[i] == i * 10) end
7688 +assert(next(a) == nil)
7689 +
7690 +
7691 +do
7692 + local a;
7693 + a = setmetatable({}, {__index = setmetatable({},
7694 + {__index = setmetatable({},
7695 + {__index = function (_,n) return a[n-3]+4, "lixo" end})})})
7696 + a[0] = 20
7697 + for i=0,10 do
7698 + assert(a[i*3] == 20 + i*4)
7699 + end
7700 +end
7701 +
7702 +
7703 +do -- newindex
7704 + local foi
7705 + local a = {}
7706 + for i=1,10 do a[i] = 0; a['a'..i] = 0; end
7707 + setmetatable(a, {__newindex = function (t,k,v) foi=true; rawset(t,k,v) end})
7708 + foi = false; a[1]=0; assert(not foi)
7709 + foi = false; a['a1']=0; assert(not foi)
7710 + foi = false; a['a11']=0; assert(foi)
7711 + foi = false; a[11]=0; assert(foi)
7712 + foi = false; a[1]=undef; assert(not foi)
7713 + a[1] = undef
7714 + foi = false; a[1]=nil; assert(foi)
7715 +end
7716 +
7717 +
7718 +setmetatable(t, nil)
7719 +function f (t, ...) return t, {...} end
7720 +t.__call = f
7721 +
7722 +do
7723 + local x,y = a(table.unpack{'a', 1})
7724 + assert(x==a and y[1]=='a' and y[2]==1 and y[3]==undef)
7725 + x,y = a()
7726 + assert(x==a and y[1]==undef)
7727 +end
7728 +
7729 +
7730 +local b = setmetatable({}, t)
7731 +setmetatable(b,t)
7732 +
7733 +function f(op)
7734 + return function (...) cap = {[0] = op, ...} ; return (...) end
7735 +end
7736 +t.__add = f("add")
7737 +t.__sub = f("sub")
7738 +t.__mul = f("mul")
7739 +t.__div = f("div")
7740 +t.__idiv = f("idiv")
7741 +t.__mod = f("mod")
7742 +t.__unm = f("unm")
7743 +t.__pow = f("pow")
7744 +t.__len = f("len")
7745 +t.__band = f("band")
7746 +t.__bor = f("bor")
7747 +t.__bxor = f("bxor")
7748 +t.__shl = f("shl")
7749 +t.__shr = f("shr")
7750 +t.__bnot = f("bnot")
7751 +t.__lt = f("lt")
7752 +t.__le = f("le")
7753 +
7754 +
7755 +local function checkcap (t)
7756 + assert(#cap + 1 == #t)
7757 + for i = 1, #t do
7758 + assert(cap[i - 1] == t[i])
7759 + assert(math.type(cap[i - 1]) == math.type(t[i]))
7760 + end
7761 +end
7762 +
7763 +-- Some tests are done inside small anonymous functions to ensure
7764 +-- that constants go to constant table even in debug compilation,
7765 +-- when the constant table is very small.
7766 +assert(b+5 == b); checkcap{"add", b, 5}
7767 +assert(5.2 + b == 5.2); checkcap{"add", 5.2, b}
7768 +assert(b+'5' == b); checkcap{"add", b, '5'}
7769 +assert(5+b == 5); checkcap{"add", 5, b}
7770 +assert('5'+b == '5'); checkcap{"add", '5', b}
7771 +b=b-3; assert(getmetatable(b) == t); checkcap{"sub", b, 3}
7772 +assert(5-a == 5); checkcap{"sub", 5, a}
7773 +assert('5'-a == '5'); checkcap{"sub", '5', a}
7774 +assert(a*a == a); checkcap{"mul", a, a}
7775 +assert(a/0 == a); checkcap{"div", a, 0}
7776 +assert(a/0.0 == a); checkcap{"div", a, 0.0}
7777 +assert(a%2 == a); checkcap{"mod", a, 2}
7778 +assert(a // (1/0) == a); checkcap{"idiv", a, 1/0}
7779 +;(function () assert(a & "hi" == a) end)(); checkcap{"band", a, "hi"}
7780 +;(function () assert(10 & a == 10) end)(); checkcap{"band", 10, a}
7781 +;(function () assert(a | 10 == a) end)(); checkcap{"bor", a, 10}
7782 +assert(a | "hi" == a); checkcap{"bor", a, "hi"}
7783 +assert("hi" ~ a == "hi"); checkcap{"bxor", "hi", a}
7784 +;(function () assert(10 ~ a == 10) end)(); checkcap{"bxor", 10, a}
7785 +assert(-a == a); checkcap{"unm", a, a}
7786 +assert(a^4.0 == a); checkcap{"pow", a, 4.0}
7787 +assert(a^'4' == a); checkcap{"pow", a, '4'}
7788 +assert(4^a == 4); checkcap{"pow", 4, a}
7789 +assert('4'^a == '4'); checkcap{"pow", '4', a}
7790 +assert(#a == a); checkcap{"len", a, a}
7791 +assert(~a == a); checkcap{"bnot", a, a}
7792 +assert(a << 3 == a); checkcap{"shl", a, 3}
7793 +assert(1.5 >> a == 1.5); checkcap{"shr", 1.5, a}
7794 +
7795 +-- for comparison operators, all results are true
7796 +assert(5.0 > a); checkcap{"lt", a, 5.0}
7797 +assert(a >= 10); checkcap{"le", 10, a}
7798 +assert(a <= -10.0); checkcap{"le", a, -10.0}
7799 +assert(a < -10); checkcap{"lt", a, -10}
7800 +
7801 +
7802 +-- test for rawlen
7803 +t = setmetatable({1,2,3}, {__len = function () return 10 end})
7804 +assert(#t == 10 and rawlen(t) == 3)
7805 +assert(rawlen"abc" == 3)
7806 +assert(not pcall(rawlen, io.stdin))
7807 +assert(not pcall(rawlen, 34))
7808 +assert(not pcall(rawlen))
7809 +
7810 +-- rawlen for long strings
7811 +assert(rawlen(string.rep('a', 1000)) == 1000)
7812 +
7813 +
7814 +t = {}
7815 +t.__lt = function (a,b,c)
7816 + collectgarbage()
7817 + assert(c == nil)
7818 + if type(a) == 'table' then a = a.x end
7819 + if type(b) == 'table' then b = b.x end
7820 + return a<b, "dummy"
7821 +end
7822 +
7823 +t.__le = function (a,b,c)
7824 + assert(c == nil)
7825 + if type(a) == 'table' then a = a.x end
7826 + if type(b) == 'table' then b = b.x end
7827 + return a<=b, "dummy"
7828 +end
7829 +
7830 +t.__eq = function (a,b,c)
7831 + assert(c == nil)
7832 + if type(a) == 'table' then a = a.x end
7833 + if type(b) == 'table' then b = b.x end
7834 + return a == b, "dummy"
7835 +end
7836 +
7837 +function Op(x) return setmetatable({x=x}, t) end
7838 +
7839 +local function test (a, b, c)
7840 + assert(not(Op(1)<Op(1)) and (Op(1)<Op(2)) and not(Op(2)<Op(1)))
7841 + assert(not(1 < Op(1)) and (Op(1) < 2) and not(2 < Op(1)))
7842 + assert(not(Op('a')<Op('a')) and (Op('a')<Op('b')) and not(Op('b')<Op('a')))
7843 + assert(not('a' < Op('a')) and (Op('a') < 'b') and not(Op('b') < Op('a')))
7844 + assert((Op(1)<=Op(1)) and (Op(1)<=Op(2)) and not(Op(2)<=Op(1)))
7845 + assert((Op('a')<=Op('a')) and (Op('a')<=Op('b')) and not(Op('b')<=Op('a')))
7846 + assert(not(Op(1)>Op(1)) and not(Op(1)>Op(2)) and (Op(2)>Op(1)))
7847 + assert(not(Op('a')>Op('a')) and not(Op('a')>Op('b')) and (Op('b')>Op('a')))
7848 + assert((Op(1)>=Op(1)) and not(Op(1)>=Op(2)) and (Op(2)>=Op(1)))
7849 + assert((1 >= Op(1)) and not(1 >= Op(2)) and (Op(2) >= 1))
7850 + assert((Op('a')>=Op('a')) and not(Op('a')>=Op('b')) and (Op('b')>=Op('a')))
7851 + assert(('a' >= Op('a')) and not(Op('a') >= 'b') and (Op('b') >= Op('a')))
7852 + assert(Op(1) == Op(1) and Op(1) ~= Op(2))
7853 + assert(Op('a') == Op('a') and Op('a') ~= Op('b'))
7854 + assert(a == a and a ~= b)
7855 + assert(Op(3) == c)
7856 +end
7857 +
7858 +test(Op(1), Op(2), Op(3))
7859 +
7860 +
7861 +-- test `partial order'
7862 +
7863 +local function rawSet(x)
7864 + local y = {}
7865 + for _,k in pairs(x) do y[k] = 1 end
7866 + return y
7867 +end
7868 +
7869 +local function Set(x)
7870 + return setmetatable(rawSet(x), t)
7871 +end
7872 +
7873 +t.__lt = function (a,b)
7874 + for k in pairs(a) do
7875 + if not b[k] then return false end
7876 + b[k] = undef
7877 + end
7878 + return next(b) ~= nil
7879 +end
7880 +
7881 +t.__le = function (a,b)
7882 + for k in pairs(a) do
7883 + if not b[k] then return false end
7884 + end
7885 + return true
7886 +end
7887 +
7888 +assert(Set{1,2,3} < Set{1,2,3,4})
7889 +assert(not(Set{1,2,3,4} < Set{1,2,3,4}))
7890 +assert((Set{1,2,3,4} <= Set{1,2,3,4}))
7891 +assert((Set{1,2,3,4} >= Set{1,2,3,4}))
7892 +assert(not (Set{1,3} <= Set{3,5}))
7893 +assert(not(Set{1,3} <= Set{3,5}))
7894 +assert(not(Set{1,3} >= Set{3,5}))
7895 +
7896 +
7897 +t.__eq = function (a,b)
7898 + for k in pairs(a) do
7899 + if not b[k] then return false end
7900 + b[k] = undef
7901 + end
7902 + return next(b) == nil
7903 +end
7904 +
7905 +local s = Set{1,3,5}
7906 +assert(s == Set{3,5,1})
7907 +assert(not rawequal(s, Set{3,5,1}))
7908 +assert(rawequal(s, s))
7909 +assert(Set{1,3,5,1} == rawSet{3,5,1})
7910 +assert(rawSet{1,3,5,1} == Set{3,5,1})
7911 +assert(Set{1,3,5} ~= Set{3,5,1,6})
7912 +
7913 +-- '__eq' is not used for table accesses
7914 +t[Set{1,3,5}] = 1
7915 +assert(t[Set{1,3,5}] == undef)
7916 +
7917 +
7918 +do -- test invalidating flags
7919 + local mt = {__eq = true}
7920 + local a = setmetatable({10}, mt)
7921 + local b = setmetatable({10}, mt)
7922 + mt.__eq = nil
7923 + assert(a ~= b) -- no metamethod
7924 + mt.__eq = function (x,y) return x[1] == y[1] end
7925 + assert(a == b) -- must use metamethod now
7926 +end
7927 +
7928 +
7929 +if not T then
7930 + (Message or print)('\n >>> testC not active: skipping tests for \z
7931 +userdata <<<\n')
7932 +else
7933 + local u1 = T.newuserdata(0, 1)
7934 + local u2 = T.newuserdata(0, 1)
7935 + local u3 = T.newuserdata(0, 1)
7936 + assert(u1 ~= u2 and u1 ~= u3)
7937 + debug.setuservalue(u1, 1);
7938 + debug.setuservalue(u2, 2);
7939 + debug.setuservalue(u3, 1);
7940 + debug.setmetatable(u1, {__eq = function (a, b)
7941 + return debug.getuservalue(a) == debug.getuservalue(b)
7942 + end})
7943 + debug.setmetatable(u2, {__eq = function (a, b)
7944 + return true
7945 + end})
7946 + assert(u1 == u3 and u3 == u1 and u1 ~= u2)
7947 + assert(u2 == u1 and u2 == u3 and u3 == u2)
7948 + assert(u2 ~= {}) -- different types cannot be equal
7949 + assert(rawequal(u1, u1) and not rawequal(u1, u3))
7950 +
7951 + local mirror = {}
7952 + debug.setmetatable(u3, {__index = mirror, __newindex = mirror})
7953 + for i = 1, 10 do u3[i] = i end
7954 + for i = 1, 10 do assert(u3[i] == i) end
7955 +end
7956 +
7957 +
7958 +t.__concat = function (a,b,c)
7959 + assert(c == nil)
7960 + if type(a) == 'table' then a = a.val end
7961 + if type(b) == 'table' then b = b.val end
7962 + if A then return a..b
7963 + else
7964 + return setmetatable({val=a..b}, t)
7965 + end
7966 +end
7967 +
7968 +c = {val="c"}; setmetatable(c, t)
7969 +d = {val="d"}; setmetatable(d, t)
7970 +
7971 +A = true
7972 +assert(c..d == 'cd')
7973 +assert(0 .."a".."b"..c..d.."e".."f"..(5+3).."g" == "0abcdef8g")
7974 +
7975 +A = false
7976 +assert((c..d..c..d).val == 'cdcd')
7977 +x = c..d
7978 +assert(getmetatable(x) == t and x.val == 'cd')
7979 +x = 0 .."a".."b"..c..d.."e".."f".."g"
7980 +assert(x.val == "0abcdefg")
7981 +
7982 +
7983 +-- concat metamethod x numbers (bug in 5.1.1)
7984 +c = {}
7985 +local x
7986 +setmetatable(c, {__concat = function (a,b)
7987 + assert(type(a) == "number" and b == c or type(b) == "number" and a == c)
7988 + return c
7989 +end})
7990 +assert(c..5 == c and 5 .. c == c)
7991 +assert(4 .. c .. 5 == c and 4 .. 5 .. 6 .. 7 .. c == c)
7992 +
7993 +
7994 +-- test comparison compatibilities
7995 +local t1, t2, c, d
7996 +t1 = {}; c = {}; setmetatable(c, t1)
7997 +d = {}
7998 +t1.__eq = function () return true end
7999 +t1.__lt = function () return true end
8000 +t1.__le = function () return false end
8001 +setmetatable(d, t1)
8002 +assert(c == d and c < d and not(d <= c))
8003 +t2 = {}
8004 +t2.__eq = t1.__eq
8005 +t2.__lt = t1.__lt
8006 +setmetatable(d, t2)
8007 +assert(c == d and c < d and not(d <= c))
8008 +
8009 +
8010 +
8011 +-- test for several levels of calls
8012 +local i
8013 +local tt = {
8014 + __call = function (t, ...)
8015 + i = i+1
8016 + if t.f then return t.f(...)
8017 + else return {...}
8018 + end
8019 + end
8020 +}
8021 +
8022 +local a = setmetatable({}, tt)
8023 +local b = setmetatable({f=a}, tt)
8024 +local c = setmetatable({f=b}, tt)
8025 +
8026 +i = 0
8027 +x = c(3,4,5)
8028 +assert(i == 3 and x[1] == 3 and x[3] == 5)
8029 +
8030 +
8031 +assert(_G.X == 20)
8032 +
8033 +print'+'
8034 +
8035 +local _g = _G
8036 +_ENV = setmetatable({}, {__index=function (_,k) return _g[k] end})
8037 +
8038 +
8039 +a = {}
8040 +rawset(a, "x", 1, 2, 3)
8041 +assert(a.x == 1 and rawget(a, "x", 3) == 1)
8042 +
8043 +print '+'
8044 +
8045 +-- testing metatables for basic types
8046 +mt = {__index = function (a,b) return a+b end,
8047 + __len = function (x) return math.floor(x) end}
8048 +debug.setmetatable(10, mt)
8049 +assert(getmetatable(-2) == mt)
8050 +assert((10)[3] == 13)
8051 +assert((10)["3"] == 13)
8052 +assert(#3.45 == 3)
8053 +debug.setmetatable(23, nil)
8054 +assert(getmetatable(-2) == nil)
8055 +
8056 +debug.setmetatable(true, mt)
8057 +assert(getmetatable(false) == mt)
8058 +mt.__index = function (a,b) return a or b end
8059 +assert((true)[false] == true)
8060 +assert((false)[false] == false)
8061 +debug.setmetatable(false, nil)
8062 +assert(getmetatable(true) == nil)
8063 +
8064 +debug.setmetatable(nil, mt)
8065 +assert(getmetatable(nil) == mt)
8066 +mt.__add = function (a,b) return (a or 1) + (b or 2) end
8067 +assert(10 + nil == 12)
8068 +assert(nil + 23 == 24)
8069 +assert(nil + nil == 3)
8070 +debug.setmetatable(nil, nil)
8071 +assert(getmetatable(nil) == nil)
8072 +
8073 +debug.setmetatable(nil, {})
8074 +
8075 +
8076 +-- loops in delegation
8077 +a = {}; setmetatable(a, a); a.__index = a; a.__newindex = a
8078 +assert(not pcall(function (a,b) return a[b] end, a, 10))
8079 +assert(not pcall(function (a,b,c) a[b] = c end, a, 10, true))
8080 +
8081 +-- bug in 5.1
8082 +T, K, V = nil
8083 +grandparent = {}
8084 +grandparent.__newindex = function(t,k,v) T=t; K=k; V=v end
8085 +
8086 +parent = {}
8087 +parent.__newindex = parent
8088 +setmetatable(parent, grandparent)
8089 +
8090 +child = setmetatable({}, parent)
8091 +child.foo = 10 --> CRASH (on some machines)
8092 +assert(T == parent and K == "foo" and V == 10)
8093 +
8094 +print 'OK'
8095 +
8096 +return 12
8097 +
8098 +
8099
8100 diff --git a/tests/files.lua b/tests/files.lua
8101 new file mode 100644
8102 index 0000000..16cf9b6
8103 --- /dev/null
8104 +++ b/tests/files.lua
8105 @@ -0,0 +1,940 @@
8106 +-- $Id: testes/files.lua $
8107 +-- See Copyright Notice in file all.lua
8108 +
8109 +local debug = require "debug"
8110 +
8111 +local maxint = math.maxinteger
8112 +
8113 +assert(type(os.getenv"PATH") == "string")
8114 +
8115 +assert(io.input(io.stdin) == io.stdin)
8116 +assert(not pcall(io.input, "non-existent-file"))
8117 +assert(io.output(io.stdout) == io.stdout)
8118 +
8119 +
8120 +local function testerr (msg, f, ...)
8121 + local stat, err = pcall(f, ...)
8122 + return (not stat and string.find(err, msg, 1, true))
8123 +end
8124 +
8125 +
8126 +local function checkerr (msg, f, ...)
8127 + assert(testerr(msg, f, ...))
8128 +end
8129 +
8130 +
8131 +-- cannot close standard files
8132 +assert(not io.close(io.stdin) and
8133 + not io.stdout:close() and
8134 + not io.stderr:close())
8135 +
8136 +-- cannot call close method without an argument (new in 5.3.5)
8137 +checkerr("got no value", io.stdin.close)
8138 +
8139 +
8140 +assert(type(io.input()) == "userdata" and io.type(io.output()) == "file")
8141 +assert(type(io.stdin) == "userdata" and io.type(io.stderr) == "file")
8142 +assert(not io.type(8))
8143 +local a = {}; setmetatable(a, {})
8144 +assert(not io.type(a))
8145 +
8146 +assert(getmetatable(io.input()).__name == "FILE*")
8147 +
8148 +local a,b,c = io.open('xuxu_nao_existe')
8149 +assert(not a and type(b) == "string" and type(c) == "number")
8150 +
8151 +a,b,c = io.open('/a/b/c/d', 'w')
8152 +assert(not a and type(b) == "string" and type(c) == "number")
8153 +
8154 +local file = os.tmpname()
8155 +local f, msg = io.open(file, "w")
8156 +if not f then
8157 + (Message or print)("'os.tmpname' file cannot be open; skipping file tests")
8158 +
8159 +else --{ most tests here need tmpname
8160 +f:close()
8161 +
8162 +print('testing i/o')
8163 +
8164 +local otherfile = os.tmpname()
8165 +
8166 +checkerr("invalid mode", io.open, file, "rw")
8167 +checkerr("invalid mode", io.open, file, "rb+")
8168 +checkerr("invalid mode", io.open, file, "r+bk")
8169 +checkerr("invalid mode", io.open, file, "")
8170 +checkerr("invalid mode", io.open, file, "+")
8171 +checkerr("invalid mode", io.open, file, "b")
8172 +assert(io.open(file, "r+b")):close()
8173 +assert(io.open(file, "r+")):close()
8174 +assert(io.open(file, "rb")):close()
8175 +
8176 +assert(os.setlocale('C', 'all'))
8177 +
8178 +io.input(io.stdin); io.output(io.stdout);
8179 +
8180 +os.remove(file)
8181 +assert(not loadfile(file))
8182 +checkerr("", dofile, file)
8183 +assert(not io.open(file))
8184 +io.output(file)
8185 +assert(io.output() ~= io.stdout)
8186 +
8187 +if not _port then -- invalid seek
8188 + local status, msg, code = io.stdin:seek("set", 1000)
8189 + assert(not status and type(msg) == "string" and type(code) == "number")
8190 +end
8191 +
8192 +assert(io.output():seek() == 0)
8193 +assert(io.write("alo alo"):seek() == string.len("alo alo"))
8194 +assert(io.output():seek("cur", -3) == string.len("alo alo")-3)
8195 +assert(io.write("joao"))
8196 +assert(io.output():seek("end") == string.len("alo joao"))
8197 +
8198 +assert(io.output():seek("set") == 0)
8199 +
8200 +assert(io.write('"álo"', "{a}\n", "second line\n", "third line \n"))
8201 +assert(io.write('çfourth_line'))
8202 +io.output(io.stdout)
8203 +collectgarbage() -- file should be closed by GC
8204 +assert(io.input() == io.stdin and rawequal(io.output(), io.stdout))
8205 +print('+')
8206 +
8207 +-- test GC for files
8208 +collectgarbage()
8209 +for i=1,120 do
8210 + for i=1,5 do
8211 + io.input(file)
8212 + assert(io.open(file, 'r'))
8213 + io.lines(file)
8214 + end
8215 + collectgarbage()
8216 +end
8217 +
8218 +io.input():close()
8219 +io.close()
8220 +
8221 +assert(os.rename(file, otherfile))
8222 +assert(not os.rename(file, otherfile))
8223 +
8224 +io.output(io.open(otherfile, "ab"))
8225 +assert(io.write("\n\n\t\t ", 3450, "\n"));
8226 +io.close()
8227 +
8228 +
8229 +do
8230 + -- closing file by scope
8231 + local F = nil
8232 + do
8233 + local f <close> = assert(io.open(file, "w"))
8234 + F = f
8235 + end
8236 + assert(tostring(F) == "file (closed)")
8237 +end
8238 +assert(os.remove(file))
8239 +
8240 +
8241 +do
8242 + -- test writing/reading numbers
8243 + local f <close> = assert(io.open(file, "w"))
8244 + f:write(maxint, '\n')
8245 + f:write(string.format("0X%x\n", maxint))
8246 + f:write("0xABCp-3", '\n')
8247 + f:write(0, '\n')
8248 + f:write(-maxint, '\n')
8249 + f:write(string.format("0x%X\n", -maxint))
8250 + f:write("-0xABCp-3", '\n')
8251 + assert(f:close())
8252 + local f <close> = assert(io.open(file, "r"))
8253 + assert(f:read("n") == maxint)
8254 + assert(f:read("n") == maxint)
8255 + assert(f:read("n") == 0xABCp-3)
8256 + assert(f:read("n") == 0)
8257 + assert(f:read("*n") == -maxint) -- test old format (with '*')
8258 + assert(f:read("n") == -maxint)
8259 + assert(f:read("*n") == -0xABCp-3) -- test old format (with '*')
8260 +end
8261 +assert(os.remove(file))
8262 +
8263 +
8264 +-- testing multiple arguments to io.read
8265 +do
8266 + local f <close> = assert(io.open(file, "w"))
8267 + f:write[[
8268 +a line
8269 +another line
8270 +1234
8271 +3.45
8272 +one
8273 +two
8274 +three
8275 +]]
8276 + local l1, l2, l3, l4, n1, n2, c, dummy
8277 + assert(f:close())
8278 + local f <close> = assert(io.open(file, "r"))
8279 + l1, l2, n1, n2, dummy = f:read("l", "L", "n", "n")
8280 + assert(l1 == "a line" and l2 == "another line\n" and
8281 + n1 == 1234 and n2 == 3.45 and dummy == nil)
8282 + assert(f:close())
8283 + local f <close> = assert(io.open(file, "r"))
8284 + l1, l2, n1, n2, c, l3, l4, dummy = f:read(7, "l", "n", "n", 1, "l", "l")
8285 + assert(l1 == "a line\n" and l2 == "another line" and c == '\n' and
8286 + n1 == 1234 and n2 == 3.45 and l3 == "one" and l4 == "two"
8287 + and dummy == nil)
8288 + assert(f:close())
8289 + local f <close> = assert(io.open(file, "r"))
8290 + -- second item failing
8291 + l1, n1, n2, dummy = f:read("l", "n", "n", "l")
8292 + assert(l1 == "a line" and not n1)
8293 +end
8294 +assert(os.remove(file))
8295 +
8296 +
8297 +
8298 +-- test yielding during 'dofile'
8299 +f = assert(io.open(file, "w"))
8300 +f:write[[
8301 +local x, z = coroutine.yield(10)
8302 +local y = coroutine.yield(20)
8303 +return x + y * z
8304 +]]
8305 +assert(f:close())
8306 +f = coroutine.wrap(dofile)
8307 +assert(f(file) == 10)
8308 +assert(f(100, 101) == 20)
8309 +assert(f(200) == 100 + 200 * 101)
8310 +assert(os.remove(file))
8311 +
8312 +
8313 +f = assert(io.open(file, "w"))
8314 +-- test number termination
8315 +f:write[[
8316 +-12.3- -0xffff+ .3|5.E-3X +234e+13E 0xDEADBEEFDEADBEEFx
8317 +0x1.13Ap+3e
8318 +]]
8319 +-- very long number
8320 +f:write("1234"); for i = 1, 1000 do f:write("0") end; f:write("\n")
8321 +-- invalid sequences (must read and discard valid prefixes)
8322 +f:write[[
8323 +.e+ 0.e; --; 0xX;
8324 +]]
8325 +assert(f:close())
8326 +f = assert(io.open(file, "r"))
8327 +assert(f:read("n") == -12.3); assert(f:read(1) == "-")
8328 +assert(f:read("n") == -0xffff); assert(f:read(2) == "+ ")
8329 +assert(f:read("n") == 0.3); assert(f:read(1) == "|")
8330 +assert(f:read("n") == 5e-3); assert(f:read(1) == "X")
8331 +assert(f:read("n") == 234e13); assert(f:read(1) == "E")
8332 +assert(f:read("n") == 0Xdeadbeefdeadbeef); assert(f:read(2) == "x\n")
8333 +assert(f:read("n") == 0x1.13aP3); assert(f:read(1) == "e")
8334 +
8335 +do -- attempt to read too long number
8336 + assert(not f:read("n")) -- fails
8337 + local s = f:read("L") -- read rest of line
8338 + assert(string.find(s, "^00*\n$")) -- lots of 0's left
8339 +end
8340 +
8341 +assert(not f:read("n")); assert(f:read(2) == "e+")
8342 +assert(not f:read("n")); assert(f:read(1) == ";")
8343 +assert(not f:read("n")); assert(f:read(2) == "-;")
8344 +assert(not f:read("n")); assert(f:read(1) == "X")
8345 +assert(not f:read("n")); assert(f:read(1) == ";")
8346 +assert(not f:read("n")); assert(not f:read(0)) -- end of file
8347 +assert(f:close())
8348 +assert(os.remove(file))
8349 +
8350 +
8351 +-- test line generators
8352 +assert(not pcall(io.lines, "non-existent-file"))
8353 +assert(os.rename(otherfile, file))
8354 +io.output(otherfile)
8355 +local n = 0
8356 +local f = io.lines(file)
8357 +while f() do n = n + 1 end;
8358 +assert(n == 6) -- number of lines in the file
8359 +checkerr("file is already closed", f)
8360 +checkerr("file is already closed", f)
8361 +-- copy from file to otherfile
8362 +n = 0
8363 +for l in io.lines(file) do io.write(l, "\n"); n = n + 1 end
8364 +io.close()
8365 +assert(n == 6)
8366 +-- copy from otherfile back to file
8367 +local f = assert(io.open(otherfile))
8368 +assert(io.type(f) == "file")
8369 +io.output(file)
8370 +assert(not io.output():read())
8371 +n = 0
8372 +for l in f:lines() do io.write(l, "\n"); n = n + 1 end
8373 +assert(tostring(f):sub(1, 5) == "file ")
8374 +assert(f:close()); io.close()
8375 +assert(n == 6)
8376 +checkerr("closed file", io.close, f)
8377 +assert(tostring(f) == "file (closed)")
8378 +assert(io.type(f) == "closed file")
8379 +io.input(file)
8380 +f = io.open(otherfile):lines()
8381 +n = 0
8382 +for l in io.lines() do assert(l == f()); n = n + 1 end
8383 +f = nil; collectgarbage()
8384 +assert(n == 6)
8385 +assert(os.remove(otherfile))
8386 +
8387 +do -- bug in 5.3.1
8388 + io.output(otherfile)
8389 + io.write(string.rep("a", 300), "\n")
8390 + io.close()
8391 + local t ={}; for i = 1, 250 do t[i] = 1 end
8392 + t = {io.lines(otherfile, table.unpack(t))()}
8393 + -- everything ok here
8394 + assert(#t == 250 and t[1] == 'a' and t[#t] == 'a')
8395 + t[#t + 1] = 1 -- one too many
8396 + checkerr("too many arguments", io.lines, otherfile, table.unpack(t))
8397 + collectgarbage() -- ensure 'otherfile' is closed
8398 + assert(os.remove(otherfile))
8399 +end
8400 +
8401 +io.input(file)
8402 +do -- test error returns
8403 + local a,b,c = io.input():write("xuxu")
8404 + assert(not a and type(b) == "string" and type(c) == "number")
8405 +end
8406 +checkerr("invalid format", io.read, "x")
8407 +assert(io.read(0) == "") -- not eof
8408 +assert(io.read(5, 'l') == '"álo"')
8409 +assert(io.read(0) == "")
8410 +assert(io.read() == "second line")
8411 +local x = io.input():seek()
8412 +assert(io.read() == "third line ")
8413 +assert(io.input():seek("set", x))
8414 +assert(io.read('L') == "third line \n")
8415 +assert(io.read(1) == "ç")
8416 +assert(io.read(string.len"fourth_line") == "fourth_line")
8417 +assert(io.input():seek("cur", -string.len"fourth_line"))
8418 +assert(io.read() == "fourth_line")
8419 +assert(io.read() == "") -- empty line
8420 +assert(io.read('n') == 3450)
8421 +assert(io.read(1) == '\n')
8422 +assert(not io.read(0)) -- end of file
8423 +assert(not io.read(1)) -- end of file
8424 +assert(not io.read(30000)) -- end of file
8425 +assert(({io.read(1)})[2] == undef)
8426 +assert(not io.read()) -- end of file
8427 +assert(({io.read()})[2] == undef)
8428 +assert(not io.read('n')) -- end of file
8429 +assert(({io.read('n')})[2] == undef)
8430 +assert(io.read('a') == '') -- end of file (OK for 'a')
8431 +assert(io.read('a') == '') -- end of file (OK for 'a')
8432 +collectgarbage()
8433 +print('+')
8434 +io.close(io.input())
8435 +checkerr(" input file is closed", io.read)
8436 +
8437 +assert(os.remove(file))
8438 +
8439 +local t = '0123456789'
8440 +for i=1,10 do t = t..t; end
8441 +assert(string.len(t) == 10*2^10)
8442 +
8443 +io.output(file)
8444 +io.write("alo"):write("\n")
8445 +io.close()
8446 +checkerr(" output file is closed", io.write)
8447 +local f = io.open(file, "a+b")
8448 +io.output(f)
8449 +collectgarbage()
8450 +
8451 +assert(io.write(' ' .. t .. ' '))
8452 +assert(io.write(';', 'end of file\n'))
8453 +f:flush(); io.flush()
8454 +f:close()
8455 +print('+')
8456 +
8457 +io.input(file)
8458 +assert(io.read() == "alo")
8459 +assert(io.read(1) == ' ')
8460 +assert(io.read(string.len(t)) == t)
8461 +assert(io.read(1) == ' ')
8462 +assert(io.read(0))
8463 +assert(io.read('a') == ';end of file\n')
8464 +assert(not io.read(0))
8465 +assert(io.close(io.input()))
8466 +
8467 +
8468 +-- test errors in read/write
8469 +do
8470 + local function ismsg (m)
8471 + -- error message is not a code number
8472 + return (type(m) == "string" and not tonumber(m))
8473 + end
8474 +
8475 + -- read
8476 + local f = io.open(file, "w")
8477 + local r, m, c = f:read()
8478 + assert(not r and ismsg(m) and type(c) == "number")
8479 + assert(f:close())
8480 + -- write
8481 + f = io.open(file, "r")
8482 + r, m, c = f:write("whatever")
8483 + assert(not r and ismsg(m) and type(c) == "number")
8484 + assert(f:close())
8485 + -- lines
8486 + f = io.open(file, "w")
8487 + r, m = pcall(f:lines())
8488 + assert(r == false and ismsg(m))
8489 + assert(f:close())
8490 +end
8491 +
8492 +assert(os.remove(file))
8493 +
8494 +-- test for L format
8495 +io.output(file); io.write"\n\nline\nother":close()
8496 +io.input(file)
8497 +assert(io.read"L" == "\n")
8498 +assert(io.read"L" == "\n")
8499 +assert(io.read"L" == "line\n")
8500 +assert(io.read"L" == "other")
8501 +assert(not io.read"L")
8502 +io.input():close()
8503 +
8504 +local f = assert(io.open(file))
8505 +local s = ""
8506 +for l in f:lines("L") do s = s .. l end
8507 +assert(s == "\n\nline\nother")
8508 +f:close()
8509 +
8510 +io.input(file)
8511 +s = ""
8512 +for l in io.lines(nil, "L") do s = s .. l end
8513 +assert(s == "\n\nline\nother")
8514 +io.input():close()
8515 +
8516 +s = ""
8517 +for l in io.lines(file, "L") do s = s .. l end
8518 +assert(s == "\n\nline\nother")
8519 +
8520 +s = ""
8521 +for l in io.lines(file, "l") do s = s .. l end
8522 +assert(s == "lineother")
8523 +
8524 +io.output(file); io.write"a = 10 + 34\na = 2*a\na = -a\n":close()
8525 +local t = {}
8526 +assert(load(io.lines(file, "L"), nil, nil, t))()
8527 +assert(t.a == -((10 + 34) * 2))
8528 +
8529 +
8530 +do -- testing closing file in line iteration
8531 +
8532 + -- get the to-be-closed variable from a loop
8533 + local function gettoclose (lv)
8534 + lv = lv + 1
8535 + local stvar = 0 -- to-be-closed is 4th state variable in the loop
8536 + for i = 1, 1000 do
8537 + local n, v = debug.getlocal(lv, i)
8538 + if n == "(for state)" then
8539 + stvar = stvar + 1
8540 + if stvar == 4 then return v end
8541 + end
8542 + end
8543 + end
8544 +
8545 + local f
8546 + for l in io.lines(file) do
8547 + f = gettoclose(1)
8548 + assert(io.type(f) == "file")
8549 + break
8550 + end
8551 + assert(io.type(f) == "closed file")
8552 +
8553 + f = nil
8554 + local function foo (name)
8555 + for l in io.lines(name) do
8556 + f = gettoclose(1)
8557 + assert(io.type(f) == "file")
8558 + error(f) -- exit loop with an error
8559 + end
8560 + end
8561 + local st, msg = pcall(foo, file)
8562 + assert(st == false and io.type(msg) == "closed file")
8563 +
8564 +end
8565 +
8566 +
8567 +-- test for multipe arguments in 'lines'
8568 +io.output(file); io.write"0123456789\n":close()
8569 +for a,b in io.lines(file, 1, 1) do
8570 + if a == "\n" then assert(not b)
8571 + else assert(tonumber(a) == tonumber(b) - 1)
8572 + end
8573 +end
8574 +
8575 +for a,b,c in io.lines(file, 1, 2, "a") do
8576 + assert(a == "0" and b == "12" and c == "3456789\n")
8577 +end
8578 +
8579 +for a,b,c in io.lines(file, "a", 0, 1) do
8580 + if a == "" then break end
8581 + assert(a == "0123456789\n" and not b and not c)
8582 +end
8583 +collectgarbage() -- to close file in previous iteration
8584 +
8585 +io.output(file); io.write"00\n10\n20\n30\n40\n":close()
8586 +for a, b in io.lines(file, "n", "n") do
8587 + if a == 40 then assert(not b)
8588 + else assert(a == b - 10)
8589 + end
8590 +end
8591 +
8592 +
8593 +-- test load x lines
8594 +io.output(file);
8595 +io.write[[
8596 +local y
8597 += X
8598 +X =
8599 +X *
8600 +2 +
8601 +X;
8602 +X =
8603 +X
8604 +- y;
8605 +]]:close()
8606 +_G.X = 1
8607 +assert(not load((io.lines(file))))
8608 +collectgarbage() -- to close file in previous iteration
8609 +load((io.lines(file, "L")))()
8610 +assert(_G.X == 2)
8611 +load((io.lines(file, 1)))()
8612 +assert(_G.X == 4)
8613 +load((io.lines(file, 3)))()
8614 +assert(_G.X == 8)
8615 +
8616 +print('+')
8617 +
8618 +local x1 = "string\n\n\\com \"\"''coisas [[estranhas]] ]]'"
8619 +io.output(file)
8620 +assert(io.write(string.format("x2 = %q\n-- comment without ending EOS", x1)))
8621 +io.close()
8622 +assert(loadfile(file))()
8623 +assert(x1 == x2)
8624 +print('+')
8625 +assert(os.remove(file))
8626 +assert(not os.remove(file))
8627 +assert(not os.remove(otherfile))
8628 +
8629 +-- testing loadfile
8630 +local function testloadfile (s, expres)
8631 + io.output(file)
8632 + if s then io.write(s) end
8633 + io.close()
8634 + local res = assert(loadfile(file))()
8635 + assert(os.remove(file))
8636 + assert(res == expres)
8637 +end
8638 +
8639 +-- loading empty file
8640 +testloadfile(nil, nil)
8641 +
8642 +-- loading file with initial comment without end of line
8643 +testloadfile("# a non-ending comment", nil)
8644 +
8645 +
8646 +-- checking Unicode BOM in files
8647 +testloadfile("\xEF\xBB\xBF# some comment\nreturn 234", 234)
8648 +testloadfile("\xEF\xBB\xBFreturn 239", 239)
8649 +testloadfile("\xEF\xBB\xBF", nil) -- empty file with a BOM
8650 +
8651 +
8652 +-- checking line numbers in files with initial comments
8653 +testloadfile("# a comment\nreturn require'debug'.getinfo(1).currentline", 2)
8654 +
8655 +
8656 +-- loading binary file
8657 +io.output(io.open(file, "wb"))
8658 +assert(io.write(string.dump(function () return 10, '\0alo\255', 'hi' end)))
8659 +io.close()
8660 +a, b, c = assert(loadfile(file))()
8661 +assert(a == 10 and b == "\0alo\255" and c == "hi")
8662 +assert(os.remove(file))
8663 +
8664 +-- bug in 5.2.1
8665 +do
8666 + io.output(io.open(file, "wb"))
8667 + -- save function with no upvalues
8668 + assert(io.write(string.dump(function () return 1 end)))
8669 + io.close()
8670 + f = assert(loadfile(file, "b", {}))
8671 + assert(type(f) == "function" and f() == 1)
8672 + assert(os.remove(file))
8673 +end
8674 +
8675 +-- loading binary file with initial comment
8676 +io.output(io.open(file, "wb"))
8677 +assert(io.write("#this is a comment for a binary file\0\n",
8678 + string.dump(function () return 20, '\0\0\0' end)))
8679 +io.close()
8680 +a, b, c = assert(loadfile(file))()
8681 +assert(a == 20 and b == "\0\0\0" and c == nil)
8682 +assert(os.remove(file))
8683 +
8684 +
8685 +-- 'loadfile' with 'env'
8686 +do
8687 + local f = io.open(file, 'w')
8688 + f:write[[
8689 + if (...) then a = 15; return b, c, d
8690 + else return _ENV
8691 + end
8692 + ]]
8693 + f:close()
8694 + local t = {b = 12, c = "xuxu", d = print}
8695 + local f = assert(loadfile(file, 't', t))
8696 + local b, c, d = f(1)
8697 + assert(t.a == 15 and b == 12 and c == t.c and d == print)
8698 + assert(f() == t)
8699 + f = assert(loadfile(file, 't', nil))
8700 + assert(f() == nil)
8701 + f = assert(loadfile(file))
8702 + assert(f() == _G)
8703 + assert(os.remove(file))
8704 +end
8705 +
8706 +
8707 +-- 'loadfile' x modes
8708 +do
8709 + io.open(file, 'w'):write("return 10"):close()
8710 + local s, m = loadfile(file, 'b')
8711 + assert(not s and string.find(m, "a text chunk"))
8712 + io.open(file, 'w'):write("\27 return 10"):close()
8713 + local s, m = loadfile(file, 't')
8714 + assert(not s and string.find(m, "a binary chunk"))
8715 + assert(os.remove(file))
8716 +end
8717 +
8718 +
8719 +io.output(file)
8720 +assert(io.write("qualquer coisa\n"))
8721 +assert(io.write("mais qualquer coisa"))
8722 +io.close()
8723 +assert(io.output(assert(io.open(otherfile, 'wb')))
8724 + :write("outra coisa\0\1\3\0\0\0\0\255\0")
8725 + :close())
8726 +
8727 +local filehandle = assert(io.open(file, 'r+'))
8728 +local otherfilehandle = assert(io.open(otherfile, 'rb'))
8729 +assert(filehandle ~= otherfilehandle)
8730 +assert(type(filehandle) == "userdata")
8731 +assert(filehandle:read('l') == "qualquer coisa")
8732 +io.input(otherfilehandle)
8733 +assert(io.read(string.len"outra coisa") == "outra coisa")
8734 +assert(filehandle:read('l') == "mais qualquer coisa")
8735 +filehandle:close();
8736 +assert(type(filehandle) == "userdata")
8737 +io.input(otherfilehandle)
8738 +assert(io.read(4) == "\0\1\3\0")
8739 +assert(io.read(3) == "\0\0\0")
8740 +assert(io.read(0) == "") -- 255 is not eof
8741 +assert(io.read(1) == "\255")
8742 +assert(io.read('a') == "\0")
8743 +assert(not io.read(0))
8744 +assert(otherfilehandle == io.input())
8745 +otherfilehandle:close()
8746 +assert(os.remove(file))
8747 +assert(os.remove(otherfile))
8748 +collectgarbage()
8749 +
8750 +io.output(file)
8751 + :write[[
8752 + 123.4 -56e-2 not a number
8753 +second line
8754 +third line
8755 +
8756 +and the rest of the file
8757 +]]
8758 + :close()
8759 +io.input(file)
8760 +local _,a,b,c,d,e,h,__ = io.read(1, 'n', 'n', 'l', 'l', 'l', 'a', 10)
8761 +assert(io.close(io.input()))
8762 +assert(_ == ' ' and not __)
8763 +assert(type(a) == 'number' and a==123.4 and b==-56e-2)
8764 +assert(d=='second line' and e=='third line')
8765 +assert(h==[[
8766 +
8767 +and the rest of the file
8768 +]])
8769 +assert(os.remove(file))
8770 +collectgarbage()
8771 +
8772 +-- testing buffers
8773 +do
8774 + local f = assert(io.open(file, "w"))
8775 + local fr = assert(io.open(file, "r"))
8776 + assert(f:setvbuf("full", 2000))
8777 + f:write("x")
8778 + assert(fr:read("all") == "") -- full buffer; output not written yet
8779 + f:close()
8780 + fr:seek("set")
8781 + assert(fr:read("all") == "x") -- `close' flushes it
8782 + f = assert(io.open(file), "w")
8783 + assert(f:setvbuf("no"))
8784 + f:write("x")
8785 + fr:seek("set")
8786 + assert(fr:read("all") == "x") -- no buffer; output is ready
8787 + f:close()
8788 + f = assert(io.open(file, "a"))
8789 + assert(f:setvbuf("line"))
8790 + f:write("x")
8791 + fr:seek("set", 1)
8792 + assert(fr:read("all") == "") -- line buffer; no output without `\n'
8793 + f:write("a\n"):seek("set", 1)
8794 + assert(fr:read("all") == "xa\n") -- now we have a whole line
8795 + f:close(); fr:close()
8796 + assert(os.remove(file))
8797 +end
8798 +
8799 +
8800 +if not _soft then
8801 + print("testing large files (> BUFSIZ)")
8802 + io.output(file)
8803 + for i=1,5001 do io.write('0123456789123') end
8804 + io.write('\n12346'):close()
8805 + io.input(file)
8806 + local x = io.read('a')
8807 + io.input():seek('set', 0)
8808 + local y = io.read(30001)..io.read(1005)..io.read(0)..
8809 + io.read(1)..io.read(100003)
8810 + assert(x == y and string.len(x) == 5001*13 + 6)
8811 + io.input():seek('set', 0)
8812 + y = io.read() -- huge line
8813 + assert(x == y..'\n'..io.read())
8814 + assert(not io.read())
8815 + io.close(io.input())
8816 + assert(os.remove(file))
8817 + x = nil; y = nil
8818 +end
8819 +
8820 +if not _port then
8821 + local progname
8822 + do -- get name of running executable
8823 + local arg = arg or ARG
8824 + local i = 0
8825 + while arg[i] do i = i - 1 end
8826 + progname = '"' .. arg[i + 1] .. '"'
8827 + end
8828 + print("testing popen/pclose and execute")
8829 + -- invalid mode for popen
8830 + checkerr("invalid mode", io.popen, "cat", "")
8831 + checkerr("invalid mode", io.popen, "cat", "r+")
8832 + checkerr("invalid mode", io.popen, "cat", "rw")
8833 + do -- basic tests for popen
8834 + local file = os.tmpname()
8835 + local f = assert(io.popen("cat - > " .. file, "w"))
8836 + f:write("a line")
8837 + assert(f:close())
8838 + local f = assert(io.popen("cat - < " .. file, "r"))
8839 + assert(f:read("a") == "a line")
8840 + assert(f:close())
8841 + assert(os.remove(file))
8842 + end
8843 +
8844 + local tests = {
8845 + -- command, what, code
8846 + {"ls > /dev/null", "ok"},
8847 + {"not-to-be-found-command", "exit"},
8848 + {"exit 3", "exit", 3},
8849 + {"exit 129", "exit", 129},
8850 + {"kill -s HUP $$", "signal", 1},
8851 + {"kill -s KILL $$", "signal", 9},
8852 + {"sh -c 'kill -s HUP $$'", "exit"},
8853 + {progname .. ' -e " "', "ok"},
8854 + {progname .. ' -e "os.exit(0, true)"', "ok"},
8855 + {progname .. ' -e "os.exit(20, true)"', "exit", 20},
8856 + }
8857 + print("\n(some error messages are expected now)")
8858 + for _, v in ipairs(tests) do
8859 + local x, y, z = io.popen(v[1]):close()
8860 + local x1, y1, z1 = os.execute(v[1])
8861 + assert(x == x1 and y == y1 and z == z1)
8862 + if v[2] == "ok" then
8863 + assert(x and y == 'exit' and z == 0)
8864 + else
8865 + assert(not x and y == v[2]) -- correct status and 'what'
8866 + -- correct code if known (but always different from 0)
8867 + assert((v[3] == nil and z > 0) or v[3] == z)
8868 + end
8869 + end
8870 +end
8871 +
8872 +
8873 +-- testing tmpfile
8874 +f = io.tmpfile()
8875 +assert(io.type(f) == "file")
8876 +f:write("alo")
8877 +f:seek("set")
8878 +assert(f:read"a" == "alo")
8879 +
8880 +end --}
8881 +
8882 +print'+'
8883 +
8884 +print("testing date/time")
8885 +
8886 +assert(os.date("") == "")
8887 +assert(os.date("!") == "")
8888 +assert(os.date("\0\0") == "\0\0")
8889 +assert(os.date("!\0\0") == "\0\0")
8890 +local x = string.rep("a", 10000)
8891 +assert(os.date(x) == x)
8892 +local t = os.time()
8893 +D = os.date("*t", t)
8894 +assert(os.date(string.rep("%d", 1000), t) ==
8895 + string.rep(os.date("%d", t), 1000))
8896 +assert(os.date(string.rep("%", 200)) == string.rep("%", 100))
8897 +
8898 +local function checkDateTable (t)
8899 + _G.D = os.date("*t", t)
8900 + assert(os.time(D) == t)
8901 + load(os.date([[assert(D.year==%Y and D.month==%m and D.day==%d and
8902 + D.hour==%H and D.min==%M and D.sec==%S and
8903 + D.wday==%w+1 and D.yday==%j)]], t))()
8904 + _G.D = nil
8905 +end
8906 +
8907 +checkDateTable(os.time())
8908 +if not _port then
8909 + -- assume that time_t can represent these values
8910 + checkDateTable(0)
8911 + checkDateTable(1)
8912 + checkDateTable(1000)
8913 + checkDateTable(0x7fffffff)
8914 + checkDateTable(0x80000000)
8915 +end
8916 +
8917 +checkerr("invalid conversion specifier", os.date, "%")
8918 +checkerr("invalid conversion specifier", os.date, "%9")
8919 +checkerr("invalid conversion specifier", os.date, "%")
8920 +checkerr("invalid conversion specifier", os.date, "%O")
8921 +checkerr("invalid conversion specifier", os.date, "%E")
8922 +checkerr("invalid conversion specifier", os.date, "%Ea")
8923 +
8924 +checkerr("not an integer", os.time, {year=1000, month=1, day=1, hour='x'})
8925 +checkerr("not an integer", os.time, {year=1000, month=1, day=1, hour=1.5})
8926 +
8927 +checkerr("missing", os.time, {hour = 12}) -- missing date
8928 +
8929 +
8930 +if string.packsize("i") == 4 then -- 4-byte ints
8931 + checkerr("field 'year' is out-of-bound", os.time,
8932 + {year = -(1 << 31) + 1899, month = 1, day = 1})
8933 +end
8934 +
8935 +if not _port then
8936 + -- test Posix-specific modifiers
8937 + assert(type(os.date("%Ex")) == 'string')
8938 + assert(type(os.date("%Oy")) == 'string')
8939 +
8940 + -- test large dates (assume at least 4-byte ints and time_t)
8941 + local t0 = os.time{year = 1970, month = 1, day = 0}
8942 + local t1 = os.time{year = 1970, month = 1, day = 0, sec = (1 << 31) - 1}
8943 + assert(t1 - t0 == (1 << 31) - 1)
8944 + t0 = os.time{year = 1970, month = 1, day = 1}
8945 + t1 = os.time{year = 1970, month = 1, day = 1, sec = -(1 << 31)}
8946 + assert(t1 - t0 == -(1 << 31))
8947 +
8948 + -- test out-of-range dates (at least for Unix)
8949 + if maxint >= 2^62 then -- cannot do these tests in Small Lua
8950 + -- no arith overflows
8951 + checkerr("out-of-bound", os.time, {year = -maxint, month = 1, day = 1})
8952 + if string.packsize("i") == 4 then -- 4-byte ints
8953 + if testerr("out-of-bound", os.date, "%Y", 2^40) then
8954 + -- time_t has 4 bytes and therefore cannot represent year 4000
8955 + print(" 4-byte time_t")
8956 + checkerr("cannot be represented", os.time, {year=4000, month=1, day=1})
8957 + else
8958 + -- time_t has 8 bytes; an int year cannot represent a huge time
8959 + print(" 8-byte time_t")
8960 + checkerr("cannot be represented", os.date, "%Y", 2^60)
8961 +
8962 + -- this is the maximum year
8963 + assert(tonumber(os.time
8964 + {year=(1 << 31) + 1899, month=12, day=31, hour=23, min=59, sec=59}))
8965 +
8966 + -- this is too much
8967 + checkerr("represented", os.time,
8968 + {year=(1 << 31) + 1899, month=12, day=31, hour=23, min=59, sec=60})
8969 + end
8970 +
8971 + -- internal 'int' fields cannot hold these values
8972 + checkerr("field 'day' is out-of-bound", os.time,
8973 + {year = 0, month = 1, day = 2^32})
8974 +
8975 + checkerr("field 'month' is out-of-bound", os.time,
8976 + {year = 0, month = -((1 << 31) + 1), day = 1})
8977 +
8978 + checkerr("field 'year' is out-of-bound", os.time,
8979 + {year = (1 << 31) + 1900, month = 1, day = 1})
8980 +
8981 + else -- 8-byte ints
8982 + -- assume time_t has 8 bytes too
8983 + print(" 8-byte time_t")
8984 + assert(tonumber(os.date("%Y", 2^60)))
8985 +
8986 + -- but still cannot represent a huge year
8987 + checkerr("cannot be represented", os.time, {year=2^60, month=1, day=1})
8988 + end
8989 + end
8990 +end
8991 +
8992 +do
8993 + local D = os.date("*t")
8994 + local t = os.time(D)
8995 + if D.isdst == nil then
8996 + print("no daylight saving information")
8997 + else
8998 + assert(type(D.isdst) == 'boolean')
8999 + end
9000 + D.isdst = nil
9001 + local t1 = os.time(D)
9002 + assert(t == t1) -- if isdst is absent uses correct default
9003 +end
9004 +
9005 +local D = os.date("*t")
9006 +t = os.time(D)
9007 +D.year = D.year-1;
9008 +local t1 = os.time(D)
9009 +-- allow for leap years
9010 +assert(math.abs(os.difftime(t,t1)/(24*3600) - 365) < 2)
9011 +
9012 +-- should not take more than 1 second to execute these two lines
9013 +t = os.time()
9014 +t1 = os.time(os.date("*t"))
9015 +local diff = os.difftime(t1,t)
9016 +assert(0 <= diff and diff <= 1)
9017 +diff = os.difftime(t,t1)
9018 +assert(-1 <= diff and diff <= 0)
9019 +
9020 +local t1 = os.time{year=2000, month=10, day=1, hour=23, min=12}
9021 +local t2 = os.time{year=2000, month=10, day=1, hour=23, min=10, sec=19}
9022 +assert(os.difftime(t1,t2) == 60*2-19)
9023 +
9024 +-- since 5.3.3, 'os.time' normalizes table fields
9025 +t1 = {year = 2005, month = 1, day = 1, hour = 1, min = 0, sec = -3602}
9026 +os.time(t1)
9027 +assert(t1.day == 31 and t1.month == 12 and t1.year == 2004 and
9028 + t1.hour == 23 and t1.min == 59 and t1.sec == 58 and
9029 + t1.yday == 366)
9030 +
9031 +io.output(io.stdout)
9032 +local t = os.date('%d %m %Y %H %M %S')
9033 +local d, m, a, h, min, s = string.match(t,
9034 + "(%d+) (%d+) (%d+) (%d+) (%d+) (%d+)")
9035 +d = tonumber(d)
9036 +m = tonumber(m)
9037 +a = tonumber(a)
9038 +h = tonumber(h)
9039 +min = tonumber(min)
9040 +s = tonumber(s)
9041 +io.write(string.format('test done on %2.2d/%2.2d/%d', d, m, a))
9042 +io.write(string.format(', at %2.2d:%2.2d:%2.2d\n', h, min, s))
9043 +io.write(string.format('%s\n', _VERSION))
9044 +
9045 +
9046
9047 diff --git a/tests/gc.lua b/tests/gc.lua
9048 new file mode 100644
9049 index 0000000..381c554
9050 --- /dev/null
9051 +++ b/tests/gc.lua
9052 @@ -0,0 +1,691 @@
9053 +-- $Id: testes/gc.lua $
9054 +-- See Copyright Notice in file all.lua
9055 +
9056 +print('testing incremental garbage collection')
9057 +
9058 +local debug = require"debug"
9059 +
9060 +assert(collectgarbage("isrunning"))
9061 +
9062 +collectgarbage()
9063 +
9064 +local oldmode = collectgarbage("incremental")
9065 +
9066 +-- changing modes should return previous mode
9067 +assert(collectgarbage("generational") == "incremental")
9068 +assert(collectgarbage("generational") == "generational")
9069 +assert(collectgarbage("incremental") == "generational")
9070 +assert(collectgarbage("incremental") == "incremental")
9071 +
9072 +
9073 +local function nop () end
9074 +
9075 +local function gcinfo ()
9076 + return collectgarbage"count" * 1024
9077 +end
9078 +
9079 +
9080 +-- test weird parameters to 'collectgarbage'
9081 +do
9082 + -- save original parameters
9083 + local a = collectgarbage("setpause", 200)
9084 + local b = collectgarbage("setstepmul", 200)
9085 + local t = {0, 2, 10, 90, 500, 5000, 30000, 0x7ffffffe}
9086 + for i = 1, #t do
9087 + local p = t[i]
9088 + for j = 1, #t do
9089 + local m = t[j]
9090 + collectgarbage("setpause", p)
9091 + collectgarbage("setstepmul", m)
9092 + collectgarbage("step", 0)
9093 + collectgarbage("step", 10000)
9094 + end
9095 + end
9096 + -- restore original parameters
9097 + collectgarbage("setpause", a)
9098 + collectgarbage("setstepmul", b)
9099 + collectgarbage()
9100 +end
9101 +
9102 +
9103 +_G["while"] = 234
9104 +
9105 +
9106 +--
9107 +-- tests for GC activation when creating different kinds of objects
9108 +--
9109 +local function GC1 ()
9110 + local u
9111 + local b -- (above 'u' it in the stack)
9112 + local finish = false
9113 + u = setmetatable({}, {__gc = function () finish = true end})
9114 + b = {34}
9115 + repeat u = {} until finish
9116 + assert(b[1] == 34) -- 'u' was collected, but 'b' was not
9117 +
9118 + finish = false; local i = 1
9119 + u = setmetatable({}, {__gc = function () finish = true end})
9120 + repeat i = i + 1; u = tostring(i) .. tostring(i) until finish
9121 + assert(b[1] == 34) -- 'u' was collected, but 'b' was not
9122 +
9123 + finish = false
9124 + u = setmetatable({}, {__gc = function () finish = true end})
9125 + repeat local i; u = function () return i end until finish
9126 + assert(b[1] == 34) -- 'u' was collected, but 'b' was not
9127 +end
9128 +
9129 +local function GC2 ()
9130 + local u
9131 + local finish = false
9132 + u = {setmetatable({}, {__gc = function () finish = true end})}
9133 + local b = {34}
9134 + repeat u = {{}} until finish
9135 + assert(b[1] == 34) -- 'u' was collected, but 'b' was not
9136 +
9137 + finish = false; local i = 1
9138 + u = {setmetatable({}, {__gc = function () finish = true end})}
9139 + repeat i = i + 1; u = {tostring(i) .. tostring(i)} until finish
9140 + assert(b[1] == 34) -- 'u' was collected, but 'b' was not
9141 +
9142 + finish = false
9143 + u = {setmetatable({}, {__gc = function () finish = true end})}
9144 + repeat local i; u = {function () return i end} until finish
9145 + assert(b[1] == 34) -- 'u' was collected, but 'b' was not
9146 +end
9147 +
9148 +local function GC() GC1(); GC2() end
9149 +
9150 +
9151 +do
9152 + print("creating many objects")
9153 +
9154 + local limit = 5000
9155 +
9156 + for i = 1, limit do
9157 + local a = {}; a = nil
9158 + end
9159 +
9160 + local a = "a"
9161 +
9162 + for i = 1, limit do
9163 + a = i .. "b";
9164 + a = string.gsub(a, '(%d%d*)', "%1 %1")
9165 + a = "a"
9166 + end
9167 +
9168 +
9169 +
9170 + a = {}
9171 +
9172 + function a:test ()
9173 + for i = 1, limit do
9174 + load(string.format("function temp(a) return 'a%d' end", i), "")()
9175 + assert(temp() == string.format('a%d', i))
9176 + end
9177 + end
9178 +
9179 + a:test()
9180 +
9181 +end
9182 +
9183 +
9184 +-- collection of functions without locals, globals, etc.
9185 +do local f = function () end end
9186 +
9187 +
9188 +print("functions with errors")
9189 +prog = [[
9190 +do
9191 + a = 10;
9192 + function foo(x,y)
9193 + a = sin(a+0.456-0.23e-12);
9194 + return function (z) return sin(%x+z) end
9195 + end
9196 + local x = function (w) a=a+w; end
9197 +end
9198 +]]
9199 +do
9200 + local step = 1
9201 + if _soft then step = 13 end
9202 + for i=1, string.len(prog), step do
9203 + for j=i, string.len(prog), step do
9204 + pcall(load(string.sub(prog, i, j), ""))
9205 + end
9206 + end
9207 +end
9208 +
9209 +foo = nil
9210 +print('long strings')
9211 +x = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"
9212 +assert(string.len(x)==80)
9213 +s = ''
9214 +k = math.min(300, (math.maxinteger // 80) // 2)
9215 +for n = 1, k do s = s..x; j=tostring(n) end
9216 +assert(string.len(s) == k*80)
9217 +s = string.sub(s, 1, 10000)
9218 +s, i = string.gsub(s, '(%d%d%d%d)', '')
9219 +assert(i==10000 // 4)
9220 +s = nil
9221 +x = nil
9222 +
9223 +assert(_G["while"] == 234)
9224 +
9225 +
9226 +--
9227 +-- test the "size" of basic GC steps (whatever they mean...)
9228 +--
9229 +do
9230 +print("steps")
9231 +
9232 + print("steps (2)")
9233 +
9234 + local function dosteps (siz)
9235 + collectgarbage()
9236 + local a = {}
9237 + for i=1,100 do a[i] = {{}}; local b = {} end
9238 + local x = gcinfo()
9239 + local i = 0
9240 + repeat -- do steps until it completes a collection cycle
9241 + i = i+1
9242 + until collectgarbage("step", siz)
9243 + assert(gcinfo() < x)
9244 + return i -- number of steps
9245 + end
9246 +
9247 + collectgarbage"stop"
9248 +
9249 + if not _port then
9250 + assert(dosteps(10) < dosteps(2))
9251 + end
9252 +
9253 + -- collector should do a full collection with so many steps
9254 + assert(dosteps(20000) == 1)
9255 + assert(collectgarbage("step", 20000) == true)
9256 + assert(collectgarbage("step", 20000) == true)
9257 +
9258 + assert(not collectgarbage("isrunning"))
9259 + collectgarbage"restart"
9260 + assert(collectgarbage("isrunning"))
9261 +
9262 +end
9263 +
9264 +
9265 +if not _port then
9266 + -- test the pace of the collector
9267 + collectgarbage(); collectgarbage()
9268 + local x = gcinfo()
9269 + collectgarbage"stop"
9270 + repeat
9271 + local a = {}
9272 + until gcinfo() > 3 * x
9273 + collectgarbage"restart"
9274 + assert(collectgarbage("isrunning"))
9275 + repeat
9276 + local a = {}
9277 + until gcinfo() <= x * 2
9278 +end
9279 +
9280 +
9281 +print("clearing tables")
9282 +lim = 15
9283 +a = {}
9284 +-- fill a with `collectable' indices
9285 +for i=1,lim do a[{}] = i end
9286 +b = {}
9287 +for k,v in pairs(a) do b[k]=v end
9288 +-- remove all indices and collect them
9289 +for n in pairs(b) do
9290 + a[n] = undef
9291 + assert(type(n) == 'table' and next(n) == nil)
9292 + collectgarbage()
9293 +end
9294 +b = nil
9295 +collectgarbage()
9296 +for n in pairs(a) do error'cannot be here' end
9297 +for i=1,lim do a[i] = i end
9298 +for i=1,lim do assert(a[i] == i) end
9299 +
9300 +
9301 +print('weak tables')
9302 +a = {}; setmetatable(a, {__mode = 'k'});
9303 +-- fill a with some `collectable' indices
9304 +for i=1,lim do a[{}] = i end
9305 +-- and some non-collectable ones
9306 +for i=1,lim do a[i] = i end
9307 +for i=1,lim do local s=string.rep('@', i); a[s] = s..'#' end
9308 +collectgarbage()
9309 +local i = 0
9310 +for k,v in pairs(a) do assert(k==v or k..'#'==v); i=i+1 end
9311 +assert(i == 2*lim)
9312 +
9313 +a = {}; setmetatable(a, {__mode = 'v'});
9314 +a[1] = string.rep('b', 21)
9315 +collectgarbage()
9316 +assert(a[1]) -- strings are *values*
9317 +a[1] = undef
9318 +-- fill a with some `collectable' values (in both parts of the table)
9319 +for i=1,lim do a[i] = {} end
9320 +for i=1,lim do a[i..'x'] = {} end
9321 +-- and some non-collectable ones
9322 +for i=1,lim do local t={}; a[t]=t end
9323 +for i=1,lim do a[i+lim]=i..'x' end
9324 +collectgarbage()
9325 +local i = 0
9326 +for k,v in pairs(a) do assert(k==v or k-lim..'x' == v); i=i+1 end
9327 +assert(i == 2*lim)
9328 +
9329 +a = {}; setmetatable(a, {__mode = 'kv'});
9330 +local x, y, z = {}, {}, {}
9331 +-- keep only some items
9332 +a[1], a[2], a[3] = x, y, z
9333 +a[string.rep('$', 11)] = string.rep('$', 11)
9334 +-- fill a with some `collectable' values
9335 +for i=4,lim do a[i] = {} end
9336 +for i=1,lim do a[{}] = i end
9337 +for i=1,lim do local t={}; a[t]=t end
9338 +collectgarbage()
9339 +assert(next(a) ~= nil)
9340 +local i = 0
9341 +for k,v in pairs(a) do
9342 + assert((k == 1 and v == x) or
9343 + (k == 2 and v == y) or
9344 + (k == 3 and v == z) or k==v);
9345 + i = i+1
9346 +end
9347 +assert(i == 4)
9348 +x,y,z=nil
9349 +collectgarbage()
9350 +assert(next(a) == string.rep('$', 11))
9351 +
9352 +
9353 +-- 'bug' in 5.1
9354 +a = {}
9355 +local t = {x = 10}
9356 +local C = setmetatable({key = t}, {__mode = 'v'})
9357 +local C1 = setmetatable({[t] = 1}, {__mode = 'k'})
9358 +a.x = t -- this should not prevent 't' from being removed from
9359 + -- weak table 'C' by the time 'a' is finalized
9360 +
9361 +setmetatable(a, {__gc = function (u)
9362 + assert(C.key == nil)
9363 + assert(type(next(C1)) == 'table')
9364 + end})
9365 +
9366 +a, t = nil
9367 +collectgarbage()
9368 +collectgarbage()
9369 +assert(next(C) == nil and next(C1) == nil)
9370 +C, C1 = nil
9371 +
9372 +
9373 +-- ephemerons
9374 +local mt = {__mode = 'k'}
9375 +a = {{10},{20},{30},{40}}; setmetatable(a, mt)
9376 +x = nil
9377 +for i = 1, 100 do local n = {}; a[n] = {k = {x}}; x = n end
9378 +GC()
9379 +local n = x
9380 +local i = 0
9381 +while n do n = a[n].k[1]; i = i + 1 end
9382 +assert(i == 100)
9383 +x = nil
9384 +GC()
9385 +for i = 1, 4 do assert(a[i][1] == i * 10); a[i] = undef end
9386 +assert(next(a) == nil)
9387 +
9388 +local K = {}
9389 +a[K] = {}
9390 +for i=1,10 do a[K][i] = {}; a[a[K][i]] = setmetatable({}, mt) end
9391 +x = nil
9392 +local k = 1
9393 +for j = 1,100 do
9394 + local n = {}; local nk = k%10 + 1
9395 + a[a[K][nk]][n] = {x, k = k}; x = n; k = nk
9396 +end
9397 +GC()
9398 +local n = x
9399 +local i = 0
9400 +while n do local t = a[a[K][k]][n]; n = t[1]; k = t.k; i = i + 1 end
9401 +assert(i == 100)
9402 +K = nil
9403 +GC()
9404 +-- assert(next(a) == nil)
9405 +
9406 +
9407 +-- testing errors during GC
9408 +if T then
9409 + collectgarbage("stop") -- stop collection
9410 + local u = {}
9411 + local s = {}; setmetatable(s, {__mode = 'k'})
9412 + setmetatable(u, {__gc = function (o)
9413 + local i = s[o]
9414 + s[i] = true
9415 + assert(not s[i - 1]) -- check proper finalization order
9416 + if i == 8 then error("@expected@") end -- error during GC
9417 + end})
9418 +
9419 + for i = 6, 10 do
9420 + local n = setmetatable({}, getmetatable(u))
9421 + s[n] = i
9422 + end
9423 +
9424 + warn("@on"); warn("@store")
9425 + collectgarbage()
9426 + assert(string.find(_WARN, "error in __gc"))
9427 + assert(string.match(_WARN, "@(.-)@") == "expected"); _WARN = false
9428 + for i = 8, 10 do assert(s[i]) end
9429 +
9430 + for i = 1, 5 do
9431 + local n = setmetatable({}, getmetatable(u))
9432 + s[n] = i
9433 + end
9434 +
9435 + collectgarbage()
9436 + for i = 1, 10 do assert(s[i]) end
9437 +
9438 + getmetatable(u).__gc = nil
9439 + warn("@normal")
9440 +
9441 +end
9442 +print '+'
9443 +
9444 +
9445 +-- testing userdata
9446 +if T==nil then
9447 + (Message or print)('\n >>> testC not active: skipping userdata GC tests <<<\n')
9448 +
9449 +else
9450 +
9451 + local function newproxy(u)
9452 + return debug.setmetatable(T.newuserdata(0), debug.getmetatable(u))
9453 + end
9454 +
9455 + collectgarbage("stop") -- stop collection
9456 + local u = newproxy(nil)
9457 + debug.setmetatable(u, {__gc = true})
9458 + local s = 0
9459 + local a = {[u] = 0}; setmetatable(a, {__mode = 'vk'})
9460 + for i=1,10 do a[newproxy(u)] = i end
9461 + for k in pairs(a) do assert(getmetatable(k) == getmetatable(u)) end
9462 + local a1 = {}; for k,v in pairs(a) do a1[k] = v end
9463 + for k,v in pairs(a1) do a[v] = k end
9464 + for i =1,10 do assert(a[i]) end
9465 + getmetatable(u).a = a1
9466 + getmetatable(u).u = u
9467 + do
9468 + local u = u
9469 + getmetatable(u).__gc = function (o)
9470 + assert(a[o] == 10-s)
9471 + assert(a[10-s] == undef) -- udata already removed from weak table
9472 + assert(getmetatable(o) == getmetatable(u))
9473 + assert(getmetatable(o).a[o] == 10-s)
9474 + s=s+1
9475 + end
9476 + end
9477 + a1, u = nil
9478 + assert(next(a) ~= nil)
9479 + collectgarbage()
9480 + assert(s==11)
9481 + collectgarbage()
9482 + assert(next(a) == nil) -- finalized keys are removed in two cycles
9483 +end
9484 +
9485 +
9486 +-- __gc x weak tables
9487 +local u = setmetatable({}, {__gc = true})
9488 +-- __gc metamethod should be collected before running
9489 +setmetatable(getmetatable(u), {__mode = "v"})
9490 +getmetatable(u).__gc = function (o) os.exit(1) end -- cannot happen
9491 +u = nil
9492 +collectgarbage()
9493 +
9494 +local u = setmetatable({}, {__gc = true})
9495 +local m = getmetatable(u)
9496 +m.x = {[{0}] = 1; [0] = {1}}; setmetatable(m.x, {__mode = "kv"});
9497 +m.__gc = function (o)
9498 + assert(next(getmetatable(o).x) == nil)
9499 + m = 10
9500 +end
9501 +u, m = nil
9502 +collectgarbage()
9503 +assert(m==10)
9504 +
9505 +do -- tests for string keys in weak tables
9506 + collectgarbage(); collectgarbage()
9507 + local m = collectgarbage("count") -- current memory
9508 + local a = setmetatable({}, {__mode = "kv"})
9509 + a[string.rep("a", 2^22)] = 25 -- long string key -> number value
9510 + a[string.rep("b", 2^22)] = {} -- long string key -> colectable value
9511 + a[{}] = 14 -- colectable key
9512 + assert(collectgarbage("count") > m + 2^13) -- 2^13 == 2 * 2^22 in KB
9513 + collectgarbage()
9514 + assert(collectgarbage("count") >= m + 2^12 and
9515 + collectgarbage("count") < m + 2^13) -- one key was collected
9516 + local k, v = next(a) -- string key with number value preserved
9517 + assert(k == string.rep("a", 2^22) and v == 25)
9518 + assert(next(a, k) == nil) -- everything else cleared
9519 + assert(a[string.rep("b", 2^22)] == undef)
9520 + a[k] = undef -- erase this last entry
9521 + k = nil
9522 + collectgarbage()
9523 + assert(next(a) == nil)
9524 + -- make sure will not try to compare with dead key
9525 + assert(a[string.rep("b", 100)] == undef)
9526 + assert(collectgarbage("count") <= m + 1) -- eveything collected
9527 +end
9528 +
9529 +
9530 +-- errors during collection
9531 +if T then
9532 + warn("@store")
9533 + u = setmetatable({}, {__gc = function () error "@expected error" end})
9534 + u = nil
9535 + collectgarbage()
9536 + assert(string.find(_WARN, "@expected error")); _WARN = false
9537 + warn("@normal")
9538 +end
9539 +
9540 +
9541 +if not _soft then
9542 + print("long list")
9543 + local a = {}
9544 + for i = 1,200000 do
9545 + a = {next = a}
9546 + end
9547 + a = nil
9548 + collectgarbage()
9549 +end
9550 +
9551 +-- create many threads with self-references and open upvalues
9552 +print("self-referenced threads")
9553 +local thread_id = 0
9554 +local threads = {}
9555 +
9556 +local function fn (thread)
9557 + local x = {}
9558 + threads[thread_id] = function()
9559 + thread = x
9560 + end
9561 + coroutine.yield()
9562 +end
9563 +
9564 +while thread_id < 1000 do
9565 + local thread = coroutine.create(fn)
9566 + coroutine.resume(thread, thread)
9567 + thread_id = thread_id + 1
9568 +end
9569 +
9570 +
9571 +-- Create a closure (function inside 'f') with an upvalue ('param') that
9572 +-- points (through a table) to the closure itself and to the thread
9573 +-- ('co' and the initial value of 'param') where closure is running.
9574 +-- Then, assert that table (and therefore everything else) will be
9575 +-- collected.
9576 +do
9577 + local collected = false -- to detect collection
9578 + collectgarbage(); collectgarbage("stop")
9579 + do
9580 + local function f (param)
9581 + ;(function ()
9582 + assert(type(f) == 'function' and type(param) == 'thread')
9583 + param = {param, f}
9584 + setmetatable(param, {__gc = function () collected = true end})
9585 + coroutine.yield(100)
9586 + end)()
9587 + end
9588 + local co = coroutine.create(f)
9589 + assert(coroutine.resume(co, co))
9590 + end
9591 + -- Now, thread and closure are not reacheable any more.
9592 + collectgarbage()
9593 + assert(collected)
9594 + collectgarbage("restart")
9595 +end
9596 +
9597 +
9598 +do
9599 + collectgarbage()
9600 + collectgarbage"stop"
9601 + collectgarbage("step", 0) -- steps should not unblock the collector
9602 + local x = gcinfo()
9603 + repeat
9604 + for i=1,1000 do _ENV.a = {} end -- no collection during the loop
9605 + until gcinfo() > 2 * x
9606 + collectgarbage"restart"
9607 +end
9608 +
9609 +
9610 +if T then -- tests for weird cases collecting upvalues
9611 +
9612 + local function foo ()
9613 + local a = {x = 20}
9614 + coroutine.yield(function () return a.x end) -- will run collector
9615 + assert(a.x == 20) -- 'a' is 'ok'
9616 + a = {x = 30} -- create a new object
9617 + assert(T.gccolor(a) == "white") -- of course it is new...
9618 + coroutine.yield(100) -- 'a' is still local to this thread
9619 + end
9620 +
9621 + local t = setmetatable({}, {__mode = "kv"})
9622 + collectgarbage(); collectgarbage('stop')
9623 + -- create coroutine in a weak table, so it will never be marked
9624 + t.co = coroutine.wrap(foo)
9625 + local f = t.co() -- create function to access local 'a'
9626 + T.gcstate("atomic") -- ensure all objects are traversed
9627 + assert(T.gcstate() == "atomic")
9628 + assert(t.co() == 100) -- resume coroutine, creating new table for 'a'
9629 + assert(T.gccolor(t.co) == "white") -- thread was not traversed
9630 + T.gcstate("pause") -- collect thread, but should mark 'a' before that
9631 + assert(t.co == nil and f() == 30) -- ensure correct access to 'a'
9632 +
9633 + collectgarbage("restart")
9634 +
9635 + -- test barrier in sweep phase (backing userdata to gray)
9636 + local u = T.newuserdata(0, 1) -- create a userdata
9637 + collectgarbage()
9638 + collectgarbage"stop"
9639 + local a = {} -- avoid 'u' as first element in 'allgc'
9640 + T.gcstate"atomic"
9641 + T.gcstate"sweepallgc"
9642 + local x = {}
9643 + assert(T.gccolor(u) == "black") -- userdata is "old" (black)
9644 + assert(T.gccolor(x) == "white") -- table is "new" (white)
9645 + debug.setuservalue(u, x) -- trigger barrier
9646 + assert(T.gccolor(u) == "gray") -- userdata changed back to gray
9647 + collectgarbage"restart"
9648 +
9649 + print"+"
9650 +end
9651 +
9652 +
9653 +if T then
9654 + local debug = require "debug"
9655 + collectgarbage("stop")
9656 + local x = T.newuserdata(0)
9657 + local y = T.newuserdata(0)
9658 + debug.setmetatable(y, {__gc = nop}) -- bless the new udata before...
9659 + debug.setmetatable(x, {__gc = nop}) -- ...the old one
9660 + assert(T.gccolor(y) == "white")
9661 + T.checkmemory()
9662 + collectgarbage("restart")
9663 +end
9664 +
9665 +
9666 +if T then
9667 + print("emergency collections")
9668 + collectgarbage()
9669 + collectgarbage()
9670 + T.totalmem(T.totalmem() + 200)
9671 + for i=1,200 do local a = {} end
9672 + T.totalmem(0)
9673 + collectgarbage()
9674 + local t = T.totalmem("table")
9675 + local a = {{}, {}, {}} -- create 4 new tables
9676 + assert(T.totalmem("table") == t + 4)
9677 + t = T.totalmem("function")
9678 + a = function () end -- create 1 new closure
9679 + assert(T.totalmem("function") == t + 1)
9680 + t = T.totalmem("thread")
9681 + a = coroutine.create(function () end) -- create 1 new coroutine
9682 + assert(T.totalmem("thread") == t + 1)
9683 +end
9684 +
9685 +
9686 +-- create an object to be collected when state is closed
9687 +do
9688 + local setmetatable,assert,type,print,getmetatable =
9689 + setmetatable,assert,type,print,getmetatable
9690 + local tt = {}
9691 + tt.__gc = function (o)
9692 + assert(getmetatable(o) == tt)
9693 + -- create new objects during GC
9694 + local a = 'xuxu'..(10+3)..'joao', {}
9695 + ___Glob = o -- ressurrect object!
9696 + setmetatable({}, tt) -- creates a new one with same metatable
9697 + print(">>> closing state " .. "<<<\n")
9698 + end
9699 + local u = setmetatable({}, tt)
9700 + ___Glob = {u} -- avoid object being collected before program end
9701 +end
9702 +
9703 +-- create several objects to raise errors when collected while closing state
9704 +if T then
9705 + local error, assert, find, warn = error, assert, string.find, warn
9706 + local n = 0
9707 + local lastmsg
9708 + local mt = {__gc = function (o)
9709 + n = n + 1
9710 + assert(n == o[1])
9711 + if n == 1 then
9712 + _WARN = false
9713 + elseif n == 2 then
9714 + assert(find(_WARN, "@expected warning"))
9715 + lastmsg = _WARN -- get message from previous error (first 'o')
9716 + else
9717 + assert(lastmsg == _WARN) -- subsequent error messages are equal
9718 + end
9719 + warn("@store"); _WARN = false
9720 + error"@expected warning"
9721 + end}
9722 + for i = 10, 1, -1 do
9723 + -- create object and preserve it until the end
9724 + table.insert(___Glob, setmetatable({i}, mt))
9725 + end
9726 +end
9727 +
9728 +-- just to make sure
9729 +assert(collectgarbage'isrunning')
9730 +
9731 +do -- check that the collector is not reentrant in incremental mode
9732 + local res = true
9733 + setmetatable({}, {__gc = function ()
9734 + res = collectgarbage()
9735 + end})
9736 + collectgarbage()
9737 + assert(not res)
9738 +end
9739 +
9740 +
9741 +collectgarbage(oldmode)
9742 +
9743 +print('OK')
9744
9745 diff --git a/tests/gengc.lua b/tests/gengc.lua
9746 new file mode 100644
9747 index 0000000..3d4f67f
9748 --- /dev/null
9749 +++ b/tests/gengc.lua
9750 @@ -0,0 +1,172 @@
9751 +-- $Id: testes/gengc.lua $
9752 +-- See Copyright Notice in file all.lua
9753 +
9754 +print('testing generational garbage collection')
9755 +
9756 +local debug = require"debug"
9757 +
9758 +assert(collectgarbage("isrunning"))
9759 +
9760 +collectgarbage()
9761 +
9762 +local oldmode = collectgarbage("generational")
9763 +
9764 +
9765 +-- ensure that table barrier evolves correctly
9766 +do
9767 + local U = {}
9768 + -- full collection makes 'U' old
9769 + collectgarbage()
9770 + assert(not T or T.gcage(U) == "old")
9771 +
9772 + -- U refers to a new table, so it becomes 'touched1'
9773 + U[1] = {x = {234}}
9774 + assert(not T or (T.gcage(U) == "touched1" and T.gcage(U[1]) == "new"))
9775 +
9776 + -- both U and the table survive one more collection
9777 + collectgarbage("step", 0)
9778 + assert(not T or (T.gcage(U) == "touched2" and T.gcage(U[1]) == "survival"))
9779 +
9780 + -- both U and the table survive yet another collection
9781 + -- now everything is old
9782 + collectgarbage("step", 0)
9783 + assert(not T or (T.gcage(U) == "old" and T.gcage(U[1]) == "old1"))
9784 +
9785 + -- data was not corrupted
9786 + assert(U[1].x[1] == 234)
9787 +end
9788 +
9789 +
9790 +do
9791 + -- ensure that 'firstold1' is corrected when object is removed from
9792 + -- the 'allgc' list
9793 + local function foo () end
9794 + local old = {10}
9795 + collectgarbage() -- make 'old' old
9796 + assert(not T or T.gcage(old) == "old")
9797 + setmetatable(old, {}) -- new table becomes OLD0 (barrier)
9798 + assert(not T or T.gcage(getmetatable(old)) == "old0")
9799 + collectgarbage("step", 0) -- new table becomes OLD1 and firstold1
9800 + assert(not T or T.gcage(getmetatable(old)) == "old1")
9801 + setmetatable(getmetatable(old), {__gc = foo}) -- get it out of allgc list
9802 + collectgarbage("step", 0) -- should not seg. fault
9803 +end
9804 +
9805 +
9806 +do -- bug in 5.4.0
9807 +-- When an object aged OLD1 is finalized, it is moved from the list
9808 +-- 'finobj' to the *beginning* of the list 'allgc', but that part of the
9809 +-- list was not being visited by 'markold'.
9810 + local A = {}
9811 + A[1] = false -- old anchor for object
9812 +
9813 + -- obj finalizer
9814 + local function gcf (obj)
9815 + A[1] = obj -- anchor object
9816 + assert(not T or T.gcage(obj) == "old1")
9817 + obj = nil -- remove it from the stack
9818 + collectgarbage("step", 0) -- do a young collection
9819 + print(getmetatable(A[1]).x) -- metatable was collected
9820 + end
9821 +
9822 + collectgarbage() -- make A old
9823 + local obj = {} -- create a new object
9824 + collectgarbage("step", 0) -- make it a survival
9825 + assert(not T or T.gcage(obj) == "survival")
9826 + setmetatable(obj, {__gc = gcf, x = "+"}) -- create its metatable
9827 + assert(not T or T.gcage(getmetatable(obj)) == "new")
9828 + obj = nil -- clear object
9829 + collectgarbage("step", 0) -- will call obj's finalizer
9830 +end
9831 +
9832 +
9833 +do -- another bug in 5.4.0
9834 + local old = {10}
9835 + collectgarbage() -- make 'old' old
9836 + local co = coroutine.create(
9837 + function ()
9838 + local x = nil
9839 + local f = function ()
9840 + return x[1]
9841 + end
9842 + x = coroutine.yield(f)
9843 + coroutine.yield()
9844 + end
9845 + )
9846 + local _, f = coroutine.resume(co) -- create closure over 'x' in coroutine
9847 + collectgarbage("step", 0) -- make upvalue a survival
9848 + old[1] = {"hello"} -- 'old' go to grayagain as 'touched1'
9849 + coroutine.resume(co, {123}) -- its value will be new
9850 + co = nil
9851 + collectgarbage("step", 0) -- hit the barrier
9852 + assert(f() == 123 and old[1][1] == "hello")
9853 + collectgarbage("step", 0) -- run the collector once more
9854 + -- make sure old[1] was not collected
9855 + assert(f() == 123 and old[1][1] == "hello")
9856 +end
9857 +
9858 +
9859 +do -- bug introduced in commit 9cf3299fa
9860 + local t = setmetatable({}, {__mode = "kv"}) -- all-weak table
9861 + collectgarbage() -- full collection
9862 + assert(not T or T.gcage(t) == "old")
9863 + t[1] = {10}
9864 + assert(not T or (T.gcage(t) == "touched1" and T.gccolor(t) == "gray"))
9865 + collectgarbage("step", 0) -- minor collection
9866 + assert(not T or (T.gcage(t) == "touched2" and T.gccolor(t) == "black"))
9867 + collectgarbage("step", 0) -- minor collection
9868 + assert(not T or T.gcage(t) == "old") -- t should be black, but it was gray
9869 + t[1] = {10} -- no barrier here, so t was still old
9870 + collectgarbage("step", 0) -- minor collection
9871 + -- t, being old, is ignored by the collection, so it is not cleared
9872 + assert(t[1] == nil) -- fails with the bug
9873 +end
9874 +
9875 +
9876 +if T == nil then
9877 + (Message or print)('\n >>> testC not active: \z
9878 + skipping some generational tests <<<\n')
9879 + print 'OK'
9880 + return
9881 +end
9882 +
9883 +
9884 +-- ensure that userdata barrier evolves correctly
9885 +do
9886 + local U = T.newuserdata(0, 1)
9887 + -- full collection makes 'U' old
9888 + collectgarbage()
9889 + assert(T.gcage(U) == "old")
9890 +
9891 + -- U refers to a new table, so it becomes 'touched1'
9892 + debug.setuservalue(U, {x = {234}})
9893 + assert(T.gcage(U) == "touched1" and
9894 + T.gcage(debug.getuservalue(U)) == "new")
9895 +
9896 + -- both U and the table survive one more collection
9897 + collectgarbage("step", 0)
9898 + assert(T.gcage(U) == "touched2" and
9899 + T.gcage(debug.getuservalue(U)) == "survival")
9900 +
9901 + -- both U and the table survive yet another collection
9902 + -- now everything is old
9903 + collectgarbage("step", 0)
9904 + assert(T.gcage(U) == "old" and
9905 + T.gcage(debug.getuservalue(U)) == "old1")
9906 +
9907 + -- data was not corrupted
9908 + assert(debug.getuservalue(U).x[1] == 234)
9909 +end
9910 +
9911 +-- just to make sure
9912 +assert(collectgarbage'isrunning')
9913 +
9914 +
9915 +
9916 +-- just to make sure
9917 +assert(collectgarbage'isrunning')
9918 +
9919 +collectgarbage(oldmode)
9920 +
9921 +print('OK')
9922 +
9923
9924 diff --git a/tests/goto.lua b/tests/goto.lua
9925 new file mode 100644
9926 index 0000000..4ac6d7d
9927 --- /dev/null
9928 +++ b/tests/goto.lua
9929 @@ -0,0 +1,271 @@
9930 +-- $Id: testes/goto.lua $
9931 +-- See Copyright Notice in file all.lua
9932 +
9933 +collectgarbage()
9934 +
9935 +local function errmsg (code, m)
9936 + local st, msg = load(code)
9937 + assert(not st and string.find(msg, m))
9938 +end
9939 +
9940 +-- cannot see label inside block
9941 +errmsg([[ goto l1; do ::l1:: end ]], "label 'l1'")
9942 +errmsg([[ do ::l1:: end goto l1; ]], "label 'l1'")
9943 +
9944 +-- repeated label
9945 +errmsg([[ ::l1:: ::l1:: ]], "label 'l1'")
9946 +errmsg([[ ::l1:: do ::l1:: end]], "label 'l1'")
9947 +
9948 +
9949 +-- undefined label
9950 +errmsg([[ goto l1; local aa ::l1:: ::l2:: print(3) ]], "local 'aa'")
9951 +
9952 +-- jumping over variable definition
9953 +errmsg([[
9954 +do local bb, cc; goto l1; end
9955 +local aa
9956 +::l1:: print(3)
9957 +]], "local 'aa'")
9958 +
9959 +-- jumping into a block
9960 +errmsg([[ do ::l1:: end goto l1 ]], "label 'l1'")
9961 +errmsg([[ goto l1 do ::l1:: end ]], "label 'l1'")
9962 +
9963 +-- cannot continue a repeat-until with variables
9964 +errmsg([[
9965 + repeat
9966 + if x then goto cont end
9967 + local xuxu = 10
9968 + ::cont::
9969 + until xuxu < x
9970 +]], "local 'xuxu'")
9971 +
9972 +-- simple gotos
9973 +local x
9974 +do
9975 + local y = 12
9976 + goto l1
9977 + ::l2:: x = x + 1; goto l3
9978 + ::l1:: x = y; goto l2
9979 +end
9980 +::l3:: ::l3_1:: assert(x == 13)
9981 +
9982 +
9983 +-- long labels
9984 +do
9985 + local prog = [[
9986 + do
9987 + local a = 1
9988 + goto l%sa; a = a + 1
9989 + ::l%sa:: a = a + 10
9990 + goto l%sb; a = a + 2
9991 + ::l%sb:: a = a + 20
9992 + return a
9993 + end
9994 + ]]
9995 + local label = string.rep("0123456789", 40)
9996 + prog = string.format(prog, label, label, label, label)
9997 + assert(assert(load(prog))() == 31)
9998 +end
9999 +
10000 +
10001 +-- ok to jump over local dec. to end of block
10002 +do
10003 + goto l1
10004 + local a = 23
10005 + x = a
10006 + ::l1::;
10007 +end
10008 +
10009 +while true do
10010 + goto l4
10011 + goto l1 -- ok to jump over local dec. to end of block
10012 + goto l1 -- multiple uses of same label
10013 + local x = 45
10014 + ::l1:: ;;;
10015 +end
10016 +::l4:: assert(x == 13)
10017 +
10018 +if print then
10019 + goto l1 -- ok to jump over local dec. to end of block
10020 + error("should not be here")
10021 + goto l2 -- ok to jump over local dec. to end of block
10022 + local x
10023 + ::l1:: ; ::l2:: ;;
10024 +else end
10025 +
10026 +-- to repeat a label in a different function is OK
10027 +local function foo ()
10028 + local a = {}
10029 + goto l3
10030 + ::l1:: a[#a + 1] = 1; goto l2;
10031 + ::l2:: a[#a + 1] = 2; goto l5;
10032 + ::l3::
10033 + ::l3a:: a[#a + 1] = 3; goto l1;
10034 + ::l4:: a[#a + 1] = 4; goto l6;
10035 + ::l5:: a[#a + 1] = 5; goto l4;
10036 + ::l6:: assert(a[1] == 3 and a[2] == 1 and a[3] == 2 and
10037 + a[4] == 5 and a[5] == 4)
10038 + if not a[6] then a[6] = true; goto l3a end -- do it twice
10039 +end
10040 +
10041 +::l6:: foo()
10042 +
10043 +
10044 +do -- bug in 5.2 -> 5.3.2
10045 + local x
10046 + ::L1::
10047 + local y -- cannot join this SETNIL with previous one
10048 + assert(y == nil)
10049 + y = true
10050 + if x == nil then
10051 + x = 1
10052 + goto L1
10053 + else
10054 + x = x + 1
10055 + end
10056 + assert(x == 2 and y == true)
10057 +end
10058 +
10059 +-- bug in 5.3
10060 +do
10061 + local first = true
10062 + local a = false
10063 + if true then
10064 + goto LBL
10065 + ::loop::
10066 + a = true
10067 + ::LBL::
10068 + if first then
10069 + first = false
10070 + goto loop
10071 + end
10072 + end
10073 + assert(a)
10074 +end
10075 +
10076 +do -- compiling infinite loops
10077 + goto escape -- do not run the infinite loops
10078 + ::a:: goto a
10079 + ::b:: goto c
10080 + ::c:: goto b
10081 +end
10082 +::escape::
10083 +--------------------------------------------------------------------------------
10084 +-- testing closing of upvalues
10085 +
10086 +local debug = require 'debug'
10087 +
10088 +local function foo ()
10089 + local t = {}
10090 + do
10091 + local i = 1
10092 + local a, b, c, d
10093 + t[1] = function () return a, b, c, d end
10094 + ::l1::
10095 + local b
10096 + do
10097 + local c
10098 + t[#t + 1] = function () return a, b, c, d end -- t[2], t[4], t[6]
10099 + if i > 2 then goto l2 end
10100 + do
10101 + local d
10102 + t[#t + 1] = function () return a, b, c, d end -- t[3], t[5]
10103 + i = i + 1
10104 + local a
10105 + goto l1
10106 + end
10107 + end
10108 + end
10109 + ::l2:: return t
10110 +end
10111 +
10112 +local a = foo()
10113 +assert(#a == 6)
10114 +
10115 +-- all functions share same 'a'
10116 +for i = 2, 6 do
10117 + assert(debug.upvalueid(a[1], 1) == debug.upvalueid(a[i], 1))
10118 +end
10119 +
10120 +-- 'b' and 'c' are shared among some of them
10121 +for i = 2, 6 do
10122 + -- only a[1] uses external 'b'/'b'
10123 + assert(debug.upvalueid(a[1], 2) ~= debug.upvalueid(a[i], 2))
10124 + assert(debug.upvalueid(a[1], 3) ~= debug.upvalueid(a[i], 3))
10125 +end
10126 +
10127 +for i = 3, 5, 2 do
10128 + -- inner functions share 'b'/'c' with previous ones
10129 + assert(debug.upvalueid(a[i], 2) == debug.upvalueid(a[i - 1], 2))
10130 + assert(debug.upvalueid(a[i], 3) == debug.upvalueid(a[i - 1], 3))
10131 + -- but not with next ones
10132 + assert(debug.upvalueid(a[i], 2) ~= debug.upvalueid(a[i + 1], 2))
10133 + assert(debug.upvalueid(a[i], 3) ~= debug.upvalueid(a[i + 1], 3))
10134 +end
10135 +
10136 +-- only external 'd' is shared
10137 +for i = 2, 6, 2 do
10138 + assert(debug.upvalueid(a[1], 4) == debug.upvalueid(a[i], 4))
10139 +end
10140 +
10141 +-- internal 'd's are all different
10142 +for i = 3, 5, 2 do
10143 + for j = 1, 6 do
10144 + assert((debug.upvalueid(a[i], 4) == debug.upvalueid(a[j], 4))
10145 + == (i == j))
10146 + end
10147 +end
10148 +
10149 +--------------------------------------------------------------------------------
10150 +-- testing if x goto optimizations
10151 +
10152 +local function testG (a)
10153 + if a == 1 then
10154 + goto l1
10155 + error("should never be here!")
10156 + elseif a == 2 then goto l2
10157 + elseif a == 3 then goto l3
10158 + elseif a == 4 then
10159 + goto l1 -- go to inside the block
10160 + error("should never be here!")
10161 + ::l1:: a = a + 1 -- must go to 'if' end
10162 + else
10163 + goto l4
10164 + ::l4a:: a = a * 2; goto l4b
10165 + error("should never be here!")
10166 + ::l4:: goto l4a
10167 + error("should never be here!")
10168 + ::l4b::
10169 + end
10170 + do return a end
10171 + ::l2:: do return "2" end
10172 + ::l3:: do return "3" end
10173 + ::l1:: return "1"
10174 +end
10175 +
10176 +assert(testG(1) == "1")
10177 +assert(testG(2) == "2")
10178 +assert(testG(3) == "3")
10179 +assert(testG(4) == 5)
10180 +assert(testG(5) == 10)
10181 +
10182 +do
10183 + -- if x back goto out of scope of upvalue
10184 + local X
10185 + goto L1
10186 +
10187 + ::L2:: goto L3
10188 +
10189 + ::L1:: do
10190 + local a <close> = setmetatable({}, {__close = function () X = true end})
10191 + assert(X == nil)
10192 + if a then goto L2 end -- jumping back out of scope of 'a'
10193 + end
10194 +
10195 + ::L3:: assert(X == true) -- checks that 'a' was correctly closed
10196 +end
10197 +--------------------------------------------------------------------------------
10198 +
10199 +
10200 +print'OK'
10201
10202 diff --git a/tests/heavy.lua b/tests/heavy.lua
10203 new file mode 100644
10204 index 0000000..4731c74
10205 --- /dev/null
10206 +++ b/tests/heavy.lua
10207 @@ -0,0 +1,173 @@
10208 +-- $Id: heavy.lua,v 1.7 2017/12/29 15:42:15 roberto Exp $
10209 +-- See Copyright Notice in file all.lua
10210 +
10211 +local function teststring ()
10212 + print("creating a string too long")
10213 + do
10214 + local a = "x"
10215 + local st, msg = pcall(function ()
10216 + while true do
10217 + a = a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10218 + .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10219 + .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10220 + .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10221 + .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10222 + .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10223 + .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10224 + .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10225 + .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10226 + .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
10227 + print(string.format("string with %d bytes", #a))
10228 + end
10229 + end)
10230 + assert(not st and
10231 + (string.find(msg, "string length overflow") or
10232 + string.find(msg, "not enough memory")))
10233 + print("string length overflow with " .. #a * 100)
10234 + end
10235 + print('+')
10236 +end
10237 +
10238 +local function loadrep (x, what)
10239 + local p = 1<<20
10240 + local s = string.rep(x, p)
10241 + local count = 0
10242 + local function f()
10243 + count = count + p
10244 + if count % (0x80*p) == 0 then
10245 + io.stderr:write("(", count // 2^20, " M)")
10246 + end
10247 + return s
10248 + end
10249 + local st, msg = load(f, "=big")
10250 + print("\nmemory: ", collectgarbage'count' * 1024)
10251 + msg = string.match(msg, "^[^\n]+") -- get only first line
10252 + print(string.format("total: 0x%x %s ('%s')", count, what, msg))
10253 + return st, msg
10254 +end
10255 +
10256 +
10257 +function controlstruct ()
10258 + print("control structure too long")
10259 + local lim = ((1 << 24) - 2) // 3
10260 + local s = string.rep("a = a + 1\n", lim)
10261 + s = "while true do " .. s .. "end"
10262 + assert(load(s))
10263 + print("ok with " .. lim .. " lines")
10264 + lim = lim + 3
10265 + s = string.rep("a = a + 1\n", lim)
10266 + s = "while true do " .. s .. "end"
10267 + local st, msg = load(s)
10268 + assert(not st and string.find(msg, "too long"))
10269 + print(msg)
10270 +end
10271 +
10272 +
10273 +function manylines ()
10274 + print("loading chunk with too many lines")
10275 + local st, msg = loadrep("\n", "lines")
10276 + assert(not st and string.find(msg, "too many lines"))
10277 + print('+')
10278 +end
10279 +
10280 +
10281 +function hugeid ()
10282 + print("loading chunk with huge identifier")
10283 + local st, msg = loadrep("a", "chars")
10284 + assert(not st and
10285 + (string.find(msg, "lexical element too long") or
10286 + string.find(msg, "not enough memory")))
10287 + print('+')
10288 +end
10289 +
10290 +function toomanyinst ()
10291 + print("loading chunk with too many instructions")
10292 + local st, msg = loadrep("a = 10; ", "instructions")
10293 + print('+')
10294 +end
10295 +
10296 +
10297 +local function loadrepfunc (prefix, f)
10298 + local count = -1
10299 + local function aux ()
10300 + count = count + 1
10301 + if count == 0 then
10302 + return prefix
10303 + else
10304 + if count % (0x100000) == 0 then
10305 + io.stderr:write("(", count // 2^20, " M)")
10306 + end
10307 + return f(count)
10308 + end
10309 + end
10310 + local st, msg = load(aux, "k")
10311 + print("\nmemory: ", collectgarbage'count' * 1024)
10312 + msg = string.match(msg, "^[^\n]+") -- get only first line
10313 + print("expected error: ", msg)
10314 +end
10315 +
10316 +
10317 +function toomanyconst ()
10318 + print("loading function with too many constants")
10319 + loadrepfunc("function foo () return {0,",
10320 + function (n)
10321 + -- convert 'n' to a string in the format [["...",]],
10322 + -- where '...' is a kind of number in base 128
10323 + -- (in a range that does not include either the double quote
10324 + -- and the escape.)
10325 + return string.char(34,
10326 + ((n // 128^0) & 127) + 128,
10327 + ((n // 128^1) & 127) + 128,
10328 + ((n // 128^2) & 127) + 128,
10329 + ((n // 128^3) & 127) + 128,
10330 + ((n // 128^4) & 127) + 128,
10331 + 34, 44)
10332 + end)
10333 +end
10334 +
10335 +
10336 +function toomanystr ()
10337 + local a = {}
10338 + local st, msg = pcall(function ()
10339 + for i = 1, math.huge do
10340 + if i % (0x100000) == 0 then
10341 + io.stderr:write("(", i // 2^20, " M)")
10342 + end
10343 + a[i] = string.pack("I", i)
10344 + end
10345 + end)
10346 + local size = #a
10347 + a = collectgarbage'count'
10348 + print("\nmemory:", a * 1024)
10349 + print("expected error:", msg)
10350 + print("size:", size)
10351 +end
10352 +
10353 +
10354 +function toomanyidx ()
10355 + local a = {}
10356 + local st, msg = pcall(function ()
10357 + for i = 1, math.huge do
10358 + if i % (0x100000) == 0 then
10359 + io.stderr:write("(", i // 2^20, " M)")
10360 + end
10361 + a[i] = i
10362 + end
10363 + end)
10364 + print("\nmemory: ", collectgarbage'count' * 1024)
10365 + print("expected error: ", msg)
10366 + print("size:", #a)
10367 +end
10368 +
10369 +
10370 +
10371 +-- teststring()
10372 +-- controlstruct()
10373 +-- manylines()
10374 +-- hugeid()
10375 +-- toomanyinst()
10376 +-- toomanyconst()
10377 +-- toomanystr()
10378 +toomanyidx()
10379 +
10380 +print "OK"
10381
10382 diff --git a/tests/literals.lua b/tests/literals.lua
10383 new file mode 100644
10384 index 0000000..d5a769e
10385 --- /dev/null
10386 +++ b/tests/literals.lua
10387 @@ -0,0 +1,342 @@
10388 +-- $Id: testes/literals.lua $
10389 +-- See Copyright Notice in file all.lua
10390 +
10391 +print('testing scanner')
10392 +
10393 +local debug = require "debug"
10394 +
10395 +
10396 +local function dostring (x) return assert(load(x), "")() end
10397 +
10398 +dostring("x \v\f = \t\r 'a\0a' \v\f\f")
10399 +assert(x == 'a\0a' and string.len(x) == 3)
10400 +
10401 +-- escape sequences
10402 +assert('\n\"\'\\' == [[
10403 +
10404 +"'\]])
10405 +
10406 +assert(string.find("\a\b\f\n\r\t\v", "^%c%c%c%c%c%c%c$"))
10407 +
10408 +-- assume ASCII just for tests:
10409 +assert("\09912" == 'c12')
10410 +assert("\99ab" == 'cab')
10411 +assert("\099" == '\99')
10412 +assert("\099\n" == 'c\10')
10413 +assert('\0\0\0alo' == '\0' .. '\0\0' .. 'alo')
10414 +
10415 +assert(010 .. 020 .. -030 == "1020-30")
10416 +
10417 +-- hexadecimal escapes
10418 +assert("\x00\x05\x10\x1f\x3C\xfF\xe8" == "\0\5\16\31\60\255\232")
10419 +
10420 +local function lexstring (x, y, n)
10421 + local f = assert(load('return ' .. x ..
10422 + ', require"debug".getinfo(1).currentline', ''))
10423 + local s, l = f()
10424 + assert(s == y and l == n)
10425 +end
10426 +
10427 +lexstring("'abc\\z \n efg'", "abcefg", 2)
10428 +lexstring("'abc\\z \n\n\n'", "abc", 4)
10429 +lexstring("'\\z \n\t\f\v\n'", "", 3)
10430 +lexstring("[[\nalo\nalo\n\n]]", "alo\nalo\n\n", 5)
10431 +lexstring("[[\nalo\ralo\n\n]]", "alo\nalo\n\n", 5)
10432 +lexstring("[[\nalo\ralo\r\n]]", "alo\nalo\n", 4)
10433 +lexstring("[[\ralo\n\ralo\r\n]]", "alo\nalo\n", 4)
10434 +lexstring("[[alo]\n]alo]]", "alo]\n]alo", 2)
10435 +
10436 +assert("abc\z
10437 + def\z
10438 + ghi\z
10439 + " == 'abcdefghi')
10440 +
10441 +
10442 +-- UTF-8 sequences
10443 +assert("\u{0}\u{00000000}\x00\0" == string.char(0, 0, 0, 0))
10444 +
10445 +-- limits for 1-byte sequences
10446 +assert("\u{0}\u{7F}" == "\x00\x7F")
10447 +
10448 +-- limits for 2-byte sequences
10449 +assert("\u{80}\u{7FF}" == "\xC2\x80\xDF\xBF")
10450 +
10451 +-- limits for 3-byte sequences
10452 +assert("\u{800}\u{FFFF}" == "\xE0\xA0\x80\xEF\xBF\xBF")
10453 +
10454 +-- limits for 4-byte sequences
10455 +assert("\u{10000}\u{1FFFFF}" == "\xF0\x90\x80\x80\xF7\xBF\xBF\xBF")
10456 +
10457 +-- limits for 5-byte sequences
10458 +assert("\u{200000}\u{3FFFFFF}" == "\xF8\x88\x80\x80\x80\xFB\xBF\xBF\xBF\xBF")
10459 +
10460 +-- limits for 6-byte sequences
10461 +assert("\u{4000000}\u{7FFFFFFF}" ==
10462 + "\xFC\x84\x80\x80\x80\x80\xFD\xBF\xBF\xBF\xBF\xBF")
10463 +
10464 +
10465 +-- Error in escape sequences
10466 +local function lexerror (s, err)
10467 + local st, msg = load('return ' .. s, '')
10468 + if err ~= '<eof>' then err = err .. "'" end
10469 + assert(not st and string.find(msg, "near .-" .. err))
10470 +end
10471 +
10472 +lexerror([["abc\x"]], [[\x"]])
10473 +lexerror([["abc\x]], [[\x]])
10474 +lexerror([["\x]], [[\x]])
10475 +lexerror([["\x5"]], [[\x5"]])
10476 +lexerror([["\x5]], [[\x5]])
10477 +lexerror([["\xr"]], [[\xr]])
10478 +lexerror([["\xr]], [[\xr]])
10479 +lexerror([["\x.]], [[\x.]])
10480 +lexerror([["\x8%"]], [[\x8%%]])
10481 +lexerror([["\xAG]], [[\xAG]])
10482 +lexerror([["\g"]], [[\g]])
10483 +lexerror([["\g]], [[\g]])
10484 +lexerror([["\."]], [[\%.]])
10485 +
10486 +lexerror([["\999"]], [[\999"]])
10487 +lexerror([["xyz\300"]], [[\300"]])
10488 +lexerror([[" \256"]], [[\256"]])
10489 +
10490 +-- errors in UTF-8 sequences
10491 +lexerror([["abc\u{100000000}"]], [[abc\u{100000000]]) -- too large
10492 +lexerror([["abc\u11r"]], [[abc\u1]]) -- missing '{'
10493 +lexerror([["abc\u"]], [[abc\u"]]) -- missing '{'
10494 +lexerror([["abc\u{11r"]], [[abc\u{11r]]) -- missing '}'
10495 +lexerror([["abc\u{11"]], [[abc\u{11"]]) -- missing '}'
10496 +lexerror([["abc\u{11]], [[abc\u{11]]) -- missing '}'
10497 +lexerror([["abc\u{r"]], [[abc\u{r]]) -- no digits
10498 +
10499 +-- unfinished strings
10500 +lexerror("[=[alo]]", "<eof>")
10501 +lexerror("[=[alo]=", "<eof>")
10502 +lexerror("[=[alo]", "<eof>")
10503 +lexerror("'alo", "<eof>")
10504 +lexerror("'alo \\z \n\n", "<eof>")
10505 +lexerror("'alo \\z", "<eof>")
10506 +lexerror([['alo \98]], "<eof>")
10507 +
10508 +-- valid characters in variable names
10509 +for i = 0, 255 do
10510 + local s = string.char(i)
10511 + assert(not string.find(s, "[a-zA-Z_]") == not load(s .. "=1", ""))
10512 + assert(not string.find(s, "[a-zA-Z_0-9]") ==
10513 + not load("a" .. s .. "1 = 1", ""))
10514 +end
10515 +
10516 +
10517 +-- long variable names
10518 +
10519 +var1 = string.rep('a', 15000) .. '1'
10520 +var2 = string.rep('a', 15000) .. '2'
10521 +prog = string.format([[
10522 + %s = 5
10523 + %s = %s + 1
10524 + return function () return %s - %s end
10525 +]], var1, var2, var1, var1, var2)
10526 +local f = dostring(prog)
10527 +assert(_G[var1] == 5 and _G[var2] == 6 and f() == -1)
10528 +var1, var2, f = nil
10529 +print('+')
10530 +
10531 +-- escapes --
10532 +assert("\n\t" == [[
10533 +
10534 + ]])
10535 +assert([[
10536 +
10537 + $debug]] == "\n $debug")
10538 +assert([[ [ ]] ~= [[ ] ]])
10539 +-- long strings --
10540 +b = "001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789"
10541 +assert(string.len(b) == 960)
10542 +prog = [=[
10543 +print('+')
10544 +
10545 +a1 = [["this is a 'string' with several 'quotes'"]]
10546 +a2 = "'quotes'"
10547 +
10548 +assert(string.find(a1, a2) == 34)
10549 +print('+')
10550 +
10551 +a1 = [==[temp = [[an arbitrary value]]; ]==]
10552 +assert(load(a1))()
10553 +assert(temp == 'an arbitrary value')
10554 +-- long strings --
10555 +b = "001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789"
10556 +assert(string.len(b) == 960)
10557 +print('+')
10558 +
10559 +a = [[00123456789012345678901234567890123456789123456789012345678901234567890123456789
10560 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10561 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10562 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10563 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10564 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10565 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10566 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10567 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10568 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10569 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10570 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10571 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10572 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10573 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10574 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10575 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10576 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10577 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10578 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10579 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10580 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10581 +00123456789012345678901234567890123456789123456789012345678901234567890123456789
10582 +]]
10583 +assert(string.len(a) == 1863)
10584 +assert(string.sub(a, 1, 40) == string.sub(b, 1, 40))
10585 +x = 1
10586 +]=]
10587 +
10588 +print('+')
10589 +x = nil
10590 +dostring(prog)
10591 +assert(x)
10592 +
10593 +prog = nil
10594 +a = nil
10595 +b = nil
10596 +
10597 +
10598 +do -- reuse of long strings
10599 +
10600 + -- get the address of a string
10601 + local function getadd (s) return string.format("%p", s) end
10602 +
10603 + local s1 <const> = "01234567890123456789012345678901234567890123456789"
10604 + local s2 <const> = "01234567890123456789012345678901234567890123456789"
10605 + local s3 = "01234567890123456789012345678901234567890123456789"
10606 + local function foo() return s1 end
10607 + local function foo1() return s3 end
10608 + local function foo2()
10609 + return "01234567890123456789012345678901234567890123456789"
10610 + end
10611 + local a1 = getadd(s1)
10612 + assert(a1 == getadd(s2))
10613 + assert(a1 == getadd(foo()))
10614 + assert(a1 == getadd(foo1()))
10615 + assert(a1 == getadd(foo2()))
10616 +
10617 + local sd = "0123456789" .. "0123456789012345678901234567890123456789"
10618 + assert(sd == s1 and getadd(sd) ~= a1)
10619 +end
10620 +
10621 +
10622 +-- testing line ends
10623 +prog = [[
10624 +a = 1 -- a comment
10625 +b = 2
10626 +
10627 +
10628 +x = [=[
10629 +hi
10630 +]=]
10631 +y = "\
10632 +hello\r\n\
10633 +"
10634 +return require"debug".getinfo(1).currentline
10635 +]]
10636 +
10637 +for _, n in pairs{"\n", "\r", "\n\r", "\r\n"} do
10638 + local prog, nn = string.gsub(prog, "\n", n)
10639 + assert(dostring(prog) == nn)
10640 + assert(_G.x == "hi\n" and _G.y == "\nhello\r\n\n")
10641 +end
10642 +
10643 +
10644 +-- testing comments and strings with long brackets
10645 +a = [==[]=]==]
10646 +assert(a == "]=")
10647 +
10648 +a = [==[[===[[=[]]=][====[]]===]===]==]
10649 +assert(a == "[===[[=[]]=][====[]]===]===")
10650 +
10651 +a = [====[[===[[=[]]=][====[]]===]===]====]
10652 +assert(a == "[===[[=[]]=][====[]]===]===")
10653 +
10654 +a = [=[]]]]]]]]]=]
10655 +assert(a == "]]]]]]]]")
10656 +
10657 +
10658 +--[===[
10659 +x y z [==[ blu foo
10660 +]==
10661 +]
10662 +]=]==]
10663 +error error]=]===]
10664 +
10665 +-- generate all strings of four of these chars
10666 +local x = {"=", "[", "]", "\n"}
10667 +local len = 4
10668 +local function gen (c, n)
10669 + if n==0 then coroutine.yield(c)
10670 + else
10671 + for _, a in pairs(x) do
10672 + gen(c..a, n-1)
10673 + end
10674 + end
10675 +end
10676 +
10677 +for s in coroutine.wrap(function () gen("", len) end) do
10678 + assert(s == load("return [====[\n"..s.."]====]", "")())
10679 +end
10680 +
10681 +
10682 +-- testing decimal point locale
10683 +if os.setlocale("pt_BR") or os.setlocale("ptb") then
10684 + assert(tonumber("3,4") == 3.4 and tonumber"3.4" == 3.4)
10685 + assert(tonumber(" -.4 ") == -0.4)
10686 + assert(tonumber(" +0x.41 ") == 0X0.41)
10687 + assert(not load("a = (3,4)"))
10688 + assert(assert(load("return 3.4"))() == 3.4)
10689 + assert(assert(load("return .4,3"))() == .4)
10690 + assert(assert(load("return 4."))() == 4.)
10691 + assert(assert(load("return 4.+.5"))() == 4.5)
10692 +
10693 + assert(" 0x.1 " + " 0x,1" + "-0X.1\t" == 0x0.1)
10694 +
10695 + assert(not tonumber"inf" and not tonumber"NAN")
10696 +
10697 + assert(assert(load(string.format("return %q", 4.51)))() == 4.51)
10698 +
10699 + local a,b = load("return 4.5.")
10700 + assert(string.find(b, "'4%.5%.'"))
10701 +
10702 + assert(os.setlocale("C"))
10703 +else
10704 + (Message or print)(
10705 + '\n >>> pt_BR locale not available: skipping decimal point tests <<<\n')
10706 +end
10707 +
10708 +
10709 +-- testing %q x line ends
10710 +local s = "a string with \r and \n and \r\n and \n\r"
10711 +local c = string.format("return %q", s)
10712 +assert(assert(load(c))() == s)
10713 +
10714 +-- testing errors
10715 +assert(not load"a = 'non-ending string")
10716 +assert(not load"a = 'non-ending string\n'")
10717 +assert(not load"a = '\\345'")
10718 +assert(not load"a = [=x]")
10719 +
10720 +local function malformednum (n, exp)
10721 + local s, msg = load("return " .. n)
10722 + assert(not s and string.find(msg, exp))
10723 +end
10724 +
10725 +malformednum("0xe-", "near <eof>")
10726 +malformednum("0xep-p", "malformed number")
10727 +malformednum("1print()", "malformed number")
10728 +
10729 +print('OK')
10730
10731 diff --git a/tests/locals.lua b/tests/locals.lua
10732 new file mode 100644
10733 index 0000000..62a88df
10734 --- /dev/null
10735 +++ b/tests/locals.lua
10736 @@ -0,0 +1,1137 @@
10737 +-- $Id: testes/locals.lua $
10738 +-- See Copyright Notice in file all.lua
10739 +
10740 +print('testing local variables and environments')
10741 +
10742 +local debug = require"debug"
10743 +
10744 +local tracegc = require"tracegc"
10745 +
10746 +
10747 +-- bug in 5.1:
10748 +
10749 +local function f(x) x = nil; return x end
10750 +assert(f(10) == nil)
10751 +
10752 +local function f() local x; return x end
10753 +assert(f(10) == nil)
10754 +
10755 +local function f(x) x = nil; local y; return x, y end
10756 +assert(f(10) == nil and select(2, f(20)) == nil)
10757 +
10758 +do
10759 + local i = 10
10760 + do local i = 100; assert(i==100) end
10761 + do local i = 1000; assert(i==1000) end
10762 + assert(i == 10)
10763 + if i ~= 10 then
10764 + local i = 20
10765 + else
10766 + local i = 30
10767 + assert(i == 30)
10768 + end
10769 +end
10770 +
10771 +
10772 +
10773 +f = nil
10774 +
10775 +local f
10776 +x = 1
10777 +
10778 +a = nil
10779 +load('local a = {}')()
10780 +assert(a == nil)
10781 +
10782 +function f (a)
10783 + local _1, _2, _3, _4, _5
10784 + local _6, _7, _8, _9, _10
10785 + local x = 3
10786 + local b = a
10787 + local c,d = a,b
10788 + if (d == b) then
10789 + local x = 'q'
10790 + x = b
10791 + assert(x == 2)
10792 + else
10793 + assert(nil)
10794 + end
10795 + assert(x == 3)
10796 + local f = 10
10797 +end
10798 +
10799 +local b=10
10800 +local a; repeat local b; a,b=1,2; assert(a+1==b); until a+b==3
10801 +
10802 +
10803 +assert(x == 1)
10804 +
10805 +f(2)
10806 +assert(type(f) == 'function')
10807 +
10808 +
10809 +local function getenv (f)
10810 + local a,b = debug.getupvalue(f, 1)
10811 + assert(a == '_ENV')
10812 + return b
10813 +end
10814 +
10815 +-- test for global table of loaded chunks
10816 +assert(getenv(load"a=3") == _G)
10817 +local c = {}; local f = load("a = 3", nil, nil, c)
10818 +assert(getenv(f) == c)
10819 +assert(c.a == nil)
10820 +f()
10821 +assert(c.a == 3)
10822 +
10823 +-- old test for limits for special instructions
10824 +do
10825 + local i = 2
10826 + local p = 4 -- p == 2^i
10827 + repeat
10828 + for j=-3,3 do
10829 + assert(load(string.format([[local a=%s;
10830 + a=a+%s;
10831 + assert(a ==2^%s)]], j, p-j, i), '')) ()
10832 + assert(load(string.format([[local a=%s;
10833 + a=a-%s;
10834 + assert(a==-2^%s)]], -j, p-j, i), '')) ()
10835 + assert(load(string.format([[local a,b=0,%s;
10836 + a=b-%s;
10837 + assert(a==-2^%s)]], -j, p-j, i), '')) ()
10838 + end
10839 + p = 2 * p; i = i + 1
10840 + until p <= 0
10841 +end
10842 +
10843 +print'+'
10844 +
10845 +
10846 +if rawget(_G, "T") then
10847 + -- testing clearing of dead elements from tables
10848 + collectgarbage("stop") -- stop GC
10849 + local a = {[{}] = 4, [3] = 0, alo = 1,
10850 + a1234567890123456789012345678901234567890 = 10}
10851 +
10852 + local t = T.querytab(a)
10853 +
10854 + for k,_ in pairs(a) do a[k] = undef end
10855 + collectgarbage() -- restore GC and collect dead fields in 'a'
10856 + for i=0,t-1 do
10857 + local k = querytab(a, i)
10858 + assert(k == nil or type(k) == 'number' or k == 'alo')
10859 + end
10860 +
10861 + -- testing allocation errors during table insertions
10862 + local a = {}
10863 + local function additems ()
10864 + a.x = true; a.y = true; a.z = true
10865 + a[1] = true
10866 + a[2] = true
10867 + end
10868 + for i = 1, math.huge do
10869 + T.alloccount(i)
10870 + local st, msg = pcall(additems)
10871 + T.alloccount()
10872 + local count = 0
10873 + for k, v in pairs(a) do
10874 + assert(a[k] == v)
10875 + count = count + 1
10876 + end
10877 + if st then assert(count == 5); break end
10878 + end
10879 +end
10880 +
10881 +
10882 +-- testing lexical environments
10883 +
10884 +assert(_ENV == _G)
10885 +
10886 +do
10887 +local dummy
10888 +local _ENV = (function (...) return ... end)(_G, dummy) -- {
10889 +
10890 +do local _ENV = {assert=assert}; assert(true) end
10891 +mt = {_G = _G}
10892 +local foo,x
10893 +A = false -- "declare" A
10894 +do local _ENV = mt
10895 + function foo (x)
10896 + A = x
10897 + do local _ENV = _G; A = 1000 end
10898 + return function (x) return A .. x end
10899 + end
10900 +end
10901 +assert(getenv(foo) == mt)
10902 +x = foo('hi'); assert(mt.A == 'hi' and A == 1000)
10903 +assert(x('*') == mt.A .. '*')
10904 +
10905 +do local _ENV = {assert=assert, A=10};
10906 + do local _ENV = {assert=assert, A=20};
10907 + assert(A==20);x=A
10908 + end
10909 + assert(A==10 and x==20)
10910 +end
10911 +assert(x==20)
10912 +
10913 +
10914 +do -- constants
10915 + local a<const>, b, c<const> = 10, 20, 30
10916 + b = a + c + b -- 'b' is not constant
10917 + assert(a == 10 and b == 60 and c == 30)
10918 + local function checkro (name, code)
10919 + local st, msg = load(code)
10920 + local gab = string.format("attempt to assign to const variable '%s'", name)
10921 + assert(not st and string.find(msg, gab))
10922 + end
10923 + checkro("y", "local x, y <const>, z = 10, 20, 30; x = 11; y = 12")
10924 + checkro("x", "local x <const>, y, z <const> = 10, 20, 30; x = 11")
10925 + checkro("z", "local x <const>, y, z <const> = 10, 20, 30; y = 10; z = 11")
10926 + checkro("foo", "local foo <const> = 10; function foo() end")
10927 + checkro("foo", "local foo <const> = {}; function foo() end")
10928 +
10929 + checkro("z", [[
10930 + local a, z <const>, b = 10;
10931 + function foo() a = 20; z = 32; end
10932 + ]])
10933 +
10934 + checkro("var1", [[
10935 + local a, var1 <const> = 10;
10936 + function foo() a = 20; z = function () var1 = 12; end end
10937 + ]])
10938 +end
10939 +
10940 +
10941 +print"testing to-be-closed variables"
10942 +
10943 +local function stack(n) n = ((n == 0) or stack(n - 1)) end
10944 +
10945 +local function func2close (f, x, y)
10946 + local obj = setmetatable({}, {__close = f})
10947 + if x then
10948 + return x, obj, y
10949 + else
10950 + return obj
10951 + end
10952 +end
10953 +
10954 +
10955 +do
10956 + local a = {}
10957 + do
10958 + local b <close> = false -- not to be closed
10959 + local x <close> = setmetatable({"x"}, {__close = function (self)
10960 + a[#a + 1] = self[1] end})
10961 + local w, y <close>, z = func2close(function (self, err)
10962 + assert(err == nil); a[#a + 1] = "y"
10963 + end, 10, 20)
10964 + local c <close> = nil -- not to be closed
10965 + a[#a + 1] = "in"
10966 + assert(w == 10 and z == 20)
10967 + end
10968 + a[#a + 1] = "out"
10969 + assert(a[1] == "in" and a[2] == "y" and a[3] == "x" and a[4] == "out")
10970 +end
10971 +
10972 +do
10973 + local X = false
10974 +
10975 + local x, closescope = func2close(function (_, msg)
10976 + stack(10);
10977 + assert(msg == nil)
10978 + X = true
10979 + end, 100)
10980 + assert(x == 100); x = 101; -- 'x' is not read-only
10981 +
10982 + -- closing functions do not corrupt returning values
10983 + local function foo (x)
10984 + local _ <close> = closescope
10985 + return x, X, 23
10986 + end
10987 +
10988 + local a, b, c = foo(1.5)
10989 + assert(a == 1.5 and b == false and c == 23 and X == true)
10990 +
10991 + X = false
10992 + foo = function (x)
10993 + local _<close> = func2close(function (_, msg)
10994 + -- without errors, enclosing function should be still active when
10995 + -- __close is called
10996 + assert(debug.getinfo(2).name == "foo")
10997 + assert(msg == nil)
10998 + end)
10999 + local _<close> = closescope
11000 + local y = 15
11001 + return y
11002 + end
11003 +
11004 + assert(foo() == 15 and X == true)
11005 +
11006 + X = false
11007 + foo = function ()
11008 + local x <close> = closescope
11009 + return x
11010 + end
11011 +
11012 + assert(foo() == closescope and X == true)
11013 +
11014 +end
11015 +
11016 +
11017 +-- testing to-be-closed x compile-time constants
11018 +-- (there were some bugs here in Lua 5.4-rc3, due to a confusion
11019 +-- between compile levels and stack levels of variables)
11020 +do
11021 + local flag = false
11022 + local x = setmetatable({},
11023 + {__close = function() assert(flag == false); flag = true end})
11024 + local y <const> = nil
11025 + local z <const> = nil
11026 + do
11027 + local a <close> = x
11028 + end
11029 + assert(flag) -- 'x' must be closed here
11030 +end
11031 +
11032 +do
11033 + -- similar problem, but with implicit close in for loops
11034 + local flag = false
11035 + local x = setmetatable({},
11036 + {__close = function () assert(flag == false); flag = true end})
11037 + -- return an empty iterator, nil, nil, and 'x' to be closed
11038 + local function a ()
11039 + return (function () return nil end), nil, nil, x
11040 + end
11041 + local v <const> = 1
11042 + local w <const> = 1
11043 + local x <const> = 1
11044 + local y <const> = 1
11045 + local z <const> = 1
11046 + for k in a() do
11047 + a = k
11048 + end -- ending the loop must close 'x'
11049 + assert(flag) -- 'x' must be closed here
11050 +end
11051 +
11052 +
11053 +
11054 +do
11055 + -- calls cannot be tail in the scope of to-be-closed variables
11056 + local X, Y
11057 + local function foo ()
11058 + local _ <close> = func2close(function () Y = 10 end)
11059 + assert(X == true and Y == nil) -- 'X' not closed yet
11060 + return 1,2,3
11061 + end
11062 +
11063 + local function bar ()
11064 + local _ <close> = func2close(function () X = false end)
11065 + X = true
11066 + do
11067 + return foo() -- not a tail call!
11068 + end
11069 + end
11070 +
11071 + local a, b, c, d = bar()
11072 + assert(a == 1 and b == 2 and c == 3 and X == false and Y == 10 and d == nil)
11073 +end
11074 +
11075 +
11076 +do
11077 + -- bug in 5.4.3: previous condition (calls cannot be tail in the
11078 + -- scope of to-be-closed variables) must be valid for tbc variables
11079 + -- created by 'for' loops.
11080 +
11081 + local closed = false
11082 +
11083 + local function foo ()
11084 + return function () return true end, 0, 0,
11085 + func2close(function () closed = true end)
11086 + end
11087 +
11088 + local function tail() return closed end
11089 +
11090 + local function foo1 ()
11091 + for k in foo() do return tail() end
11092 + end
11093 +
11094 + assert(foo1() == false)
11095 + assert(closed == true)
11096 +end
11097 +
11098 +
11099 +do print("testing errors in __close")
11100 +
11101 + -- original error is in __close
11102 + local function foo ()
11103 +
11104 + local x <close> =
11105 + func2close(function (self, msg)
11106 + assert(string.find(msg, "@y"))
11107 + error("@x")
11108 + end)
11109 +
11110 + local x1 <close> =
11111 + func2close(function (self, msg)
11112 + assert(string.find(msg, "@y"))
11113 + end)
11114 +
11115 + local gc <close> = func2close(function () collectgarbage() end)
11116 +
11117 + local y <close> =
11118 + func2close(function (self, msg)
11119 + assert(string.find(msg, "@z")) -- error in 'z'
11120 + error("@y")
11121 + end)
11122 +
11123 + local z <close> =
11124 + func2close(function (self, msg)
11125 + assert(msg == nil)
11126 + error("@z")
11127 + end)
11128 +
11129 + return 200
11130 + end
11131 +
11132 + local stat, msg = pcall(foo, false)
11133 + assert(string.find(msg, "@x"))
11134 +
11135 +
11136 + -- original error not in __close
11137 + local function foo ()
11138 +
11139 + local x <close> =
11140 + func2close(function (self, msg)
11141 + -- after error, 'foo' was discarded, so caller now
11142 + -- must be 'pcall'
11143 + assert(debug.getinfo(2).name == "pcall")
11144 + assert(string.find(msg, "@x1"))
11145 + end)
11146 +
11147 + local x1 <close> =
11148 + func2close(function (self, msg)
11149 + assert(debug.getinfo(2).name == "pcall")
11150 + assert(string.find(msg, "@y"))
11151 + error("@x1")
11152 + end)
11153 +
11154 + local gc <close> = func2close(function () collectgarbage() end)
11155 +
11156 + local y <close> =
11157 + func2close(function (self, msg)
11158 + assert(debug.getinfo(2).name == "pcall")
11159 + assert(string.find(msg, "@z"))
11160 + error("@y")
11161 + end)
11162 +
11163 + local first = true
11164 + local z <close> =
11165 + func2close(function (self, msg)
11166 + assert(debug.getinfo(2).name == "pcall")
11167 + -- 'z' close is called once
11168 + assert(first and msg == 4)
11169 + first = false
11170 + error("@z")
11171 + end)
11172 +
11173 + error(4) -- original error
11174 + end
11175 +
11176 + local stat, msg = pcall(foo, true)
11177 + assert(string.find(msg, "@x1"))
11178 +
11179 + -- error leaving a block
11180 + local function foo (...)
11181 + do
11182 + local x1 <close> =
11183 + func2close(function (self, msg)
11184 + assert(string.find(msg, "@X"))
11185 + error("@Y")
11186 + end)
11187 +
11188 + local x123 <close> =
11189 + func2close(function (_, msg)
11190 + assert(msg == nil)
11191 + error("@X")
11192 + end)
11193 + end
11194 + os.exit(false) -- should not run
11195 + end
11196 +
11197 + local st, msg = xpcall(foo, debug.traceback)
11198 + assert(string.match(msg, "^[^ ]* @Y"))
11199 +
11200 + -- error in toclose in vararg function
11201 + local function foo (...)
11202 + local x123 <close> = func2close(function () error("@x123") end)
11203 + end
11204 +
11205 + local st, msg = xpcall(foo, debug.traceback)
11206 + assert(string.match(msg, "^[^ ]* @x123"))
11207 + assert(string.find(msg, "in metamethod 'close'"))
11208 +end
11209 +
11210 +
11211 +do -- errors due to non-closable values
11212 + local function foo ()
11213 + local x <close> = {}
11214 + os.exit(false) -- should not run
11215 + end
11216 + local stat, msg = pcall(foo)
11217 + assert(not stat and
11218 + string.find(msg, "variable 'x' got a non%-closable value"))
11219 +
11220 + local function foo ()
11221 + local xyz <close> = setmetatable({}, {__close = print})
11222 + getmetatable(xyz).__close = nil -- remove metamethod
11223 + end
11224 + local stat, msg = pcall(foo)
11225 + assert(not stat and string.find(msg, "metamethod 'close'"))
11226 +
11227 + local function foo ()
11228 + local a1 <close> = func2close(function (_, msg)
11229 + assert(string.find(msg, "number value"))
11230 + error(12)
11231 + end)
11232 + local a2 <close> = setmetatable({}, {__close = print})
11233 + local a3 <close> = func2close(function (_, msg)
11234 + assert(msg == nil)
11235 + error(123)
11236 + end)
11237 + getmetatable(a2).__close = 4 -- invalidate metamethod
11238 + end
11239 + local stat, msg = pcall(foo)
11240 + assert(not stat and msg == 12)
11241 +end
11242 +
11243 +
11244 +do -- tbc inside close methods
11245 + local track = {}
11246 + local function foo ()
11247 + local x <close> = func2close(function ()
11248 + local xx <close> = func2close(function (_, msg)
11249 + assert(msg == nil)
11250 + track[#track + 1] = "xx"
11251 + end)
11252 + track[#track + 1] = "x"
11253 + end)
11254 + track[#track + 1] = "foo"
11255 + return 20, 30, 40
11256 + end
11257 + local a, b, c, d = foo()
11258 + assert(a == 20 and b == 30 and c == 40 and d == nil)
11259 + assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx")
11260 +
11261 + -- again, with errors
11262 + local track = {}
11263 + local function foo ()
11264 + local x0 <close> = func2close(function (_, msg)
11265 + assert(msg == 202)
11266 + track[#track + 1] = "x0"
11267 + end)
11268 + local x <close> = func2close(function ()
11269 + local xx <close> = func2close(function (_, msg)
11270 + assert(msg == 101)
11271 + track[#track + 1] = "xx"
11272 + error(202)
11273 + end)
11274 + track[#track + 1] = "x"
11275 + error(101)
11276 + end)
11277 + track[#track + 1] = "foo"
11278 + return 20, 30, 40
11279 + end
11280 + local st, msg = pcall(foo)
11281 + assert(not st and msg == 202)
11282 + assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx" and
11283 + track[4] == "x0")
11284 +end
11285 +
11286 +
11287 +local function checktable (t1, t2)
11288 + assert(#t1 == #t2)
11289 + for i = 1, #t1 do
11290 + assert(t1[i] == t2[i])
11291 + end
11292 +end
11293 +
11294 +
11295 +do -- test for tbc variable high in the stack
11296 +
11297 + -- function to force a stack overflow
11298 + local function overflow (n)
11299 + overflow(n + 1)
11300 + end
11301 +
11302 + -- error handler will create tbc variable handling a stack overflow,
11303 + -- high in the stack
11304 + local function errorh (m)
11305 + assert(string.find(m, "stack overflow"))
11306 + local x <close> = func2close(function (o) o[1] = 10 end)
11307 + return x
11308 + end
11309 +
11310 + local flag
11311 + local st, obj
11312 + -- run test in a coroutine so as not to swell the main stack
11313 + local co = coroutine.wrap(function ()
11314 + -- tbc variable down the stack
11315 + local y <close> = func2close(function (obj, msg)
11316 + assert(msg == nil)
11317 + obj[1] = 100
11318 + flag = obj
11319 + end)
11320 + tracegc.stop()
11321 + st, obj = xpcall(overflow, errorh, 0)
11322 + tracegc.start()
11323 + end)
11324 + co()
11325 + assert(not st and obj[1] == 10 and flag[1] == 100)
11326 +end
11327 +
11328 +
11329 +if rawget(_G, "T") then
11330 +
11331 + -- memory error inside closing function
11332 + local function foo ()
11333 + local y <close> = func2close(function () T.alloccount() end)
11334 + local x <close> = setmetatable({}, {__close = function ()
11335 + T.alloccount(0); local x = {} -- force a memory error
11336 + end})
11337 + error(1000) -- common error inside the function's body
11338 + end
11339 +
11340 + stack(5) -- ensure a minimal number of CI structures
11341 +
11342 + -- despite memory error, 'y' will be executed and
11343 + -- memory limit will be lifted
11344 + local _, msg = pcall(foo)
11345 + assert(msg == "not enough memory")
11346 +
11347 + local closemsg
11348 + local close = func2close(function (self, msg)
11349 + T.alloccount()
11350 + closemsg = msg
11351 + end)
11352 +
11353 + -- set a memory limit and return a closing object to remove the limit
11354 + local function enter (count)
11355 + stack(10) -- reserve some stack space
11356 + T.alloccount(count)
11357 + closemsg = nil
11358 + return close
11359 + end
11360 +
11361 + local function test ()
11362 + local x <close> = enter(0) -- set a memory limit
11363 + local y = {} -- raise a memory error
11364 + end
11365 +
11366 + local _, msg = pcall(test)
11367 + assert(msg == "not enough memory" and closemsg == "not enough memory")
11368 +
11369 +
11370 + -- repeat test with extra closing upvalues
11371 + local function test ()
11372 + local xxx <close> = func2close(function (self, msg)
11373 + assert(msg == "not enough memory");
11374 + error(1000) -- raise another error
11375 + end)
11376 + local xx <close> = func2close(function (self, msg)
11377 + assert(msg == "not enough memory");
11378 + end)
11379 + local x <close> = enter(0) -- set a memory limit
11380 + local y = {} -- raise a memory error
11381 + end
11382 +
11383 + local _, msg = pcall(test)
11384 + assert(msg == 1000 and closemsg == "not enough memory")
11385 +
11386 + do -- testing 'toclose' in C string buffer
11387 + collectgarbage()
11388 + local s = string.rep('a', 10000) -- large string
11389 + local m = T.totalmem()
11390 + collectgarbage("stop")
11391 + s = string.upper(s) -- allocate buffer + new string (10K each)
11392 + -- ensure buffer was deallocated
11393 + assert(T.totalmem() - m <= 11000)
11394 + collectgarbage("restart")
11395 + end
11396 +
11397 + do -- now some tests for freeing buffer in case of errors
11398 + local lim = 10000 -- some size larger than the static buffer
11399 + local extra = 2000 -- some extra memory (for callinfo, etc.)
11400 +
11401 + local s = string.rep("a", lim)
11402 +
11403 + -- concat this table needs two buffer resizes (one for each 's')
11404 + local a = {s, s}
11405 +
11406 + collectgarbage(); collectgarbage()
11407 +
11408 + m = T.totalmem()
11409 + collectgarbage("stop")
11410 +
11411 + -- error in the first buffer allocation
11412 + T. totalmem(m + extra)
11413 + assert(not pcall(table.concat, a))
11414 + -- first buffer was not even allocated
11415 + assert(T.totalmem() - m <= extra)
11416 +
11417 + -- error in the second buffer allocation
11418 + T. totalmem(m + lim + extra)
11419 + assert(not pcall(table.concat, a))
11420 + -- first buffer was released by 'toclose'
11421 + assert(T.totalmem() - m <= extra)
11422 +
11423 + -- error in creation of final string
11424 + T.totalmem(m + 2 * lim + extra)
11425 + assert(not pcall(table.concat, a))
11426 + -- second buffer was released by 'toclose'
11427 + assert(T.totalmem() - m <= extra)
11428 +
11429 + -- userdata, buffer, buffer, final string
11430 + T.totalmem(m + 4*lim + extra)
11431 + assert(#table.concat(a) == 2*lim)
11432 +
11433 + T.totalmem(0) -- remove memory limit
11434 + collectgarbage("restart")
11435 +
11436 + print'+'
11437 + end
11438 +
11439 +
11440 + do
11441 + -- '__close' vs. return hooks in C functions
11442 + local trace = {}
11443 +
11444 + local function hook (event)
11445 + trace[#trace + 1] = event .. " " .. (debug.getinfo(2).name or "?")
11446 + end
11447 +
11448 + -- create tbc variables to be used by C function
11449 + local x = func2close(function (_,msg)
11450 + trace[#trace + 1] = "x"
11451 + end)
11452 +
11453 + local y = func2close(function (_,msg)
11454 + trace[#trace + 1] = "y"
11455 + end)
11456 +
11457 + debug.sethook(hook, "r")
11458 + local t = {T.testC([[
11459 + toclose 2 # x
11460 + pushnum 10
11461 + pushint 20
11462 + toclose 3 # y
11463 + return 2
11464 + ]], x, y)}
11465 + debug.sethook()
11466 +
11467 + -- hooks ran before return hook from 'testC'
11468 + checktable(trace,
11469 + {"return sethook", "y", "return ?", "x", "return ?", "return testC"})
11470 + -- results are correct
11471 + checktable(t, {10, 20})
11472 + end
11473 +end
11474 +
11475 +
11476 +do -- '__close' vs. return hooks in Lua functions
11477 + local trace = {}
11478 +
11479 + local function hook (event)
11480 + trace[#trace + 1] = event .. " " .. debug.getinfo(2).name
11481 + end
11482 +
11483 + local function foo (...)
11484 + local x <close> = func2close(function (_,msg)
11485 + trace[#trace + 1] = "x"
11486 + end)
11487 +
11488 + local y <close> = func2close(function (_,msg)
11489 + debug.sethook(hook, "r")
11490 + end)
11491 +
11492 + return ...
11493 + end
11494 +
11495 + local t = {foo(10,20,30)}
11496 + debug.sethook()
11497 + checktable(t, {10, 20, 30})
11498 + checktable(trace,
11499 + {"return sethook", "return close", "x", "return close", "return foo"})
11500 +end
11501 +
11502 +
11503 +print "to-be-closed variables in coroutines"
11504 +
11505 +do
11506 + -- yielding inside closing metamethods
11507 +
11508 + local trace = {}
11509 + local co = coroutine.wrap(function ()
11510 +
11511 + trace[#trace + 1] = "nowX"
11512 +
11513 + -- will be closed after 'y'
11514 + local x <close> = func2close(function (_, msg)
11515 + assert(msg == nil)
11516 + trace[#trace + 1] = "x1"
11517 + coroutine.yield("x")
11518 + trace[#trace + 1] = "x2"
11519 + end)
11520 +
11521 + return pcall(function ()
11522 + do -- 'z' will be closed first
11523 + local z <close> = func2close(function (_, msg)
11524 + assert(msg == nil)
11525 + trace[#trace + 1] = "z1"
11526 + coroutine.yield("z")
11527 + trace[#trace + 1] = "z2"
11528 + end)
11529 + end
11530 +
11531 + trace[#trace + 1] = "nowY"
11532 +
11533 + -- will be closed after 'z'
11534 + local y <close> = func2close(function(_, msg)
11535 + assert(msg == nil)
11536 + trace[#trace + 1] = "y1"
11537 + coroutine.yield("y")
11538 + trace[#trace + 1] = "y2"
11539 + end)
11540 +
11541 + return 10, 20, 30
11542 + end)
11543 + end)
11544 +
11545 + assert(co() == "z")
11546 + assert(co() == "y")
11547 + assert(co() == "x")
11548 + checktable({co()}, {true, 10, 20, 30})
11549 + checktable(trace, {"nowX", "z1", "z2", "nowY", "y1", "y2", "x1", "x2"})
11550 +
11551 +end
11552 +
11553 +
11554 +do
11555 + -- yielding inside closing metamethods while returning
11556 + -- (bug in 5.4.3)
11557 +
11558 + local extrares -- result from extra yield (if any)
11559 +
11560 + local function check (body, extra, ...)
11561 + local t = table.pack(...) -- expected returns
11562 + local co = coroutine.wrap(body)
11563 + if extra then
11564 + extrares = co() -- runs until first (extra) yield
11565 + end
11566 + local res = table.pack(co()) -- runs until yield inside '__close'
11567 + assert(res.n == 2 and res[2] == nil)
11568 + local res2 = table.pack(co()) -- runs until end of function
11569 + assert(res2.n == t.n)
11570 + for i = 1, #t do
11571 + if t[i] == "x" then
11572 + assert(res2[i] == res[1]) -- value that was closed
11573 + else
11574 + assert(res2[i] == t[i])
11575 + end
11576 + end
11577 + end
11578 +
11579 + local function foo ()
11580 + local x <close> = func2close(coroutine.yield)
11581 + local extra <close> = func2close(function (self)
11582 + assert(self == extrares)
11583 + coroutine.yield(100)
11584 + end)
11585 + extrares = extra
11586 + return table.unpack{10, x, 30}
11587 + end
11588 + check(foo, true, 10, "x", 30)
11589 + assert(extrares == 100)
11590 +
11591 + local function foo ()
11592 + local x <close> = func2close(coroutine.yield)
11593 + return
11594 + end
11595 + check(foo, false)
11596 +
11597 + local function foo ()
11598 + local x <close> = func2close(coroutine.yield)
11599 + local y, z = 20, 30
11600 + return x
11601 + end
11602 + check(foo, false, "x")
11603 +
11604 + local function foo ()
11605 + local x <close> = func2close(coroutine.yield)
11606 + local extra <close> = func2close(coroutine.yield)
11607 + return table.unpack({}, 1, 100) -- 100 nils
11608 + end
11609 + check(foo, true, table.unpack({}, 1, 100))
11610 +
11611 +end
11612 +
11613 +do
11614 + -- yielding inside closing metamethods after an error
11615 +
11616 + local co = coroutine.wrap(function ()
11617 +
11618 + local function foo (err)
11619 +
11620 + local z <close> = func2close(function(_, msg)
11621 + assert(msg == nil or msg == err + 20)
11622 + coroutine.yield("z")
11623 + return 100, 200
11624 + end)
11625 +
11626 + local y <close> = func2close(function(_, msg)
11627 + -- still gets the original error (if any)
11628 + assert(msg == err or (msg == nil and err == 1))
11629 + coroutine.yield("y")
11630 + if err then error(err + 20) end -- creates or changes the error
11631 + end)
11632 +
11633 + local x <close> = func2close(function(_, msg)
11634 + assert(msg == err or (msg == nil and err == 1))
11635 + coroutine.yield("x")
11636 + return 100, 200
11637 + end)
11638 +
11639 + if err == 10 then error(err) else return 10, 20 end
11640 + end
11641 +
11642 + coroutine.yield(pcall(foo, nil)) -- no error
11643 + coroutine.yield(pcall(foo, 1)) -- error in __close
11644 + return pcall(foo, 10) -- 'foo' will raise an error
11645 + end)
11646 +
11647 + local a, b = co() -- first foo: no error
11648 + assert(a == "x" and b == nil) -- yields inside 'x'; Ok
11649 + a, b = co()
11650 + assert(a == "y" and b == nil) -- yields inside 'y'; Ok
11651 + a, b = co()
11652 + assert(a == "z" and b == nil) -- yields inside 'z'; Ok
11653 + local a, b, c = co()
11654 + assert(a and b == 10 and c == 20) -- returns from 'pcall(foo, nil)'
11655 +
11656 + local a, b = co() -- second foo: error in __close
11657 + assert(a == "x" and b == nil) -- yields inside 'x'; Ok
11658 + a, b = co()
11659 + assert(a == "y" and b == nil) -- yields inside 'y'; Ok
11660 + a, b = co()
11661 + assert(a == "z" and b == nil) -- yields inside 'z'; Ok
11662 + local st, msg = co() -- reports the error in 'y'
11663 + assert(not st and msg == 21)
11664 +
11665 + local a, b = co() -- third foo: error in function body
11666 + assert(a == "x" and b == nil) -- yields inside 'x'; Ok
11667 + a, b = co()
11668 + assert(a == "y" and b == nil) -- yields inside 'y'; Ok
11669 + a, b = co()
11670 + assert(a == "z" and b == nil) -- yields inside 'z'; Ok
11671 + local st, msg = co() -- gets final error
11672 + assert(not st and msg == 10 + 20)
11673 +
11674 +end
11675 +
11676 +
11677 +do
11678 + -- an error in a wrapped coroutine closes variables
11679 + local x = false
11680 + local y = false
11681 + local co = coroutine.wrap(function ()
11682 + local xv <close> = func2close(function () x = true end)
11683 + do
11684 + local yv <close> = func2close(function () y = true end)
11685 + coroutine.yield(100) -- yield doesn't close variable
11686 + end
11687 + coroutine.yield(200) -- yield doesn't close variable
11688 + error(23) -- error does
11689 + end)
11690 +
11691 + local b = co()
11692 + assert(b == 100 and not x and not y)
11693 + b = co()
11694 + assert(b == 200 and not x and y)
11695 + local a, b = pcall(co)
11696 + assert(not a and b == 23 and x and y)
11697 +end
11698 +
11699 +
11700 +do
11701 +
11702 + -- error in a wrapped coroutine raising errors when closing a variable
11703 + local x = 0
11704 + local co = coroutine.wrap(function ()
11705 + local xx <close> = func2close(function (_, msg)
11706 + x = x + 1;
11707 + assert(string.find(msg, "@XXX"))
11708 + error("@YYY")
11709 + end)
11710 + local xv <close> = func2close(function () x = x + 1; error("@XXX") end)
11711 + coroutine.yield(100)
11712 + error(200)
11713 + end)
11714 + assert(co() == 100); assert(x == 0)
11715 + local st, msg = pcall(co); assert(x == 2)
11716 + assert(not st and string.find(msg, "@YYY")) -- should get error raised
11717 +
11718 + local x = 0
11719 + local y = 0
11720 + co = coroutine.wrap(function ()
11721 + local xx <close> = func2close(function (_, err)
11722 + y = y + 1;
11723 + assert(string.find(err, "XXX"))
11724 + error("YYY")
11725 + end)
11726 + local xv <close> = func2close(function ()
11727 + x = x + 1; error("XXX")
11728 + end)
11729 + coroutine.yield(100)
11730 + return 200
11731 + end)
11732 + assert(co() == 100); assert(x == 0)
11733 + local st, msg = pcall(co)
11734 + assert(x == 1 and y == 1)
11735 + -- should get first error raised
11736 + assert(not st and string.find(msg, "%w+%.%w+:%d+: YYY"))
11737 +
11738 +end
11739 +
11740 +
11741 +-- a suspended coroutine should not close its variables when collected
11742 +local co
11743 +co = coroutine.wrap(function()
11744 + -- should not run
11745 + local x <close> = func2close(function () os.exit(false) end)
11746 + co = nil
11747 + coroutine.yield()
11748 +end)
11749 +co() -- start coroutine
11750 +assert(co == nil) -- eventually it will be collected
11751 +collectgarbage()
11752 +
11753 +
11754 +if rawget(_G, "T") then
11755 + print("to-be-closed variables x coroutines in C")
11756 + do
11757 + local token = 0
11758 + local count = 0
11759 + local f = T.makeCfunc[[
11760 + toclose 1
11761 + toclose 2
11762 + return .
11763 + ]]
11764 +
11765 + local obj = func2close(function (_, msg)
11766 + count = count + 1
11767 + token = coroutine.yield(count, token)
11768 + end)
11769 +
11770 + local co = coroutine.wrap(f)
11771 + local ct, res = co(obj, obj, 10, 20, 30, 3) -- will return 10, 20, 30
11772 + -- initial token value, after closing 2nd obj
11773 + assert(ct == 1 and res == 0)
11774 + -- run until yield when closing 1st obj
11775 + ct, res = co(100)
11776 + assert(ct == 2 and res == 100)
11777 + res = {co(200)} -- run until end
11778 + assert(res[1] == 10 and res[2] == 20 and res[3] == 30 and res[4] == nil)
11779 + assert(token == 200)
11780 + end
11781 +
11782 + do
11783 + local f = T.makeCfunc[[
11784 + toclose 1
11785 + return .
11786 + ]]
11787 +
11788 + local obj = func2close(function ()
11789 + local temp
11790 + local x <close> = func2close(function ()
11791 + coroutine.yield(temp)
11792 + return 1,2,3 -- to be ignored
11793 + end)
11794 + temp = coroutine.yield("closing obj")
11795 + return 1,2,3 -- to be ignored
11796 + end)
11797 +
11798 + local co = coroutine.wrap(f)
11799 + local res = co(obj, 10, 30, 1) -- will return only 30
11800 + assert(res == "closing obj")
11801 + res = co("closing x")
11802 + assert(res == "closing x")
11803 + res = {co()}
11804 + assert(res[1] == 30 and res[2] == nil)
11805 + end
11806 +
11807 + do
11808 + -- still cannot yield inside 'closeslot'
11809 + local f = T.makeCfunc[[
11810 + toclose 1
11811 + closeslot 1
11812 + ]]
11813 + local obj = func2close(coroutine.yield)
11814 + local co = coroutine.create(f)
11815 + local st, msg = coroutine.resume(co, obj)
11816 + assert(not st and string.find(msg, "attempt to yield across"))
11817 +
11818 + -- nor outside a coroutine
11819 + local f = T.makeCfunc[[
11820 + toclose 1
11821 + ]]
11822 + local st, msg = pcall(f, obj)
11823 + assert(not st and string.find(msg, "attempt to yield from outside"))
11824 + end
11825 +end
11826 +
11827 +
11828 +
11829 +-- to-be-closed variables in generic for loops
11830 +do
11831 + local numopen = 0
11832 + local function open (x)
11833 + numopen = numopen + 1
11834 + return
11835 + function () -- iteraction function
11836 + x = x - 1
11837 + if x > 0 then return x end
11838 + end,
11839 + nil, -- state
11840 + nil, -- control variable
11841 + func2close(function () numopen = numopen - 1 end) -- closing function
11842 + end
11843 +
11844 + local s = 0
11845 + for i in open(10) do
11846 + s = s + i
11847 + end
11848 + assert(s == 45 and numopen == 0)
11849 +
11850 + local s = 0
11851 + for i in open(10) do
11852 + if i < 5 then break end
11853 + s = s + i
11854 + end
11855 + assert(s == 35 and numopen == 0)
11856 +
11857 + local s = 0
11858 + for i in open(10) do
11859 + for j in open(10) do
11860 + if i + j < 5 then goto endloop end
11861 + s = s + i
11862 + end
11863 + end
11864 + ::endloop::
11865 + assert(s == 375 and numopen == 0)
11866 +end
11867 +
11868 +print('OK')
11869 +
11870 +return 5,f
11871 +
11872 +end -- }
11873 +
11874
11875 diff --git a/tests/main.lua b/tests/main.lua
11876 new file mode 100644
11877 index 0000000..9def638
11878 --- /dev/null
11879 +++ b/tests/main.lua
11880 @@ -0,0 +1,528 @@
11881 +# testing special comment on first line
11882 +-- $Id: testes/main.lua $
11883 +-- See Copyright Notice in file all.lua
11884 +
11885 +-- most (all?) tests here assume a reasonable "Unix-like" shell
11886 +if _port then return end
11887 +
11888 +-- use only "double quotes" inside shell scripts (better change to
11889 +-- run on Windows)
11890 +
11891 +
11892 +print ("testing stand-alone interpreter")
11893 +
11894 +assert(os.execute()) -- machine has a system command
11895 +
11896 +local arg = arg or ARG
11897 +
11898 +local prog = os.tmpname()
11899 +local otherprog = os.tmpname()
11900 +local out = os.tmpname()
11901 +
11902 +local progname
11903 +do
11904 + local i = 0
11905 + while arg[i] do i=i-1 end
11906 + progname = arg[i+1]
11907 +end
11908 +print("progname: "..progname)
11909 +
11910 +local prepfile = function (s, p)
11911 + p = p or prog
11912 + io.output(p)
11913 + io.write(s)
11914 + assert(io.close())
11915 +end
11916 +
11917 +local function getoutput ()
11918 + io.input(out)
11919 + local t = io.read("a")
11920 + io.input():close()
11921 + assert(os.remove(out))
11922 + return t
11923 +end
11924 +
11925 +local function checkprogout (s)
11926 + -- expected result must end with new line
11927 + assert(string.sub(s, -1) == "\n")
11928 + local t = getoutput()
11929 + for line in string.gmatch(s, ".-\n") do
11930 + assert(string.find(t, line, 1, true))
11931 + end
11932 +end
11933 +
11934 +local function checkout (s)
11935 + local t = getoutput()
11936 + if s ~= t then print(string.format("'%s' - '%s'\n", s, t)) end
11937 + assert(s == t)
11938 + return t
11939 +end
11940 +
11941 +
11942 +local function RUN (p, ...)
11943 + p = string.gsub(p, "lua", '"'..progname..'"', 1)
11944 + local s = string.format(p, ...)
11945 + assert(os.execute(s))
11946 +end
11947 +
11948 +local function NoRun (msg, p, ...)
11949 + p = string.gsub(p, "lua", '"'..progname..'"', 1)
11950 + local s = string.format(p, ...)
11951 + s = string.format("%s 2> %s", s, out) -- will send error to 'out'
11952 + assert(not os.execute(s))
11953 + assert(string.find(getoutput(), msg, 1, true)) -- check error message
11954 +end
11955 +
11956 +RUN('lua -v')
11957 +
11958 +print(string.format("(temporary program file used in these tests: %s)", prog))
11959 +
11960 +-- running stdin as a file
11961 +prepfile""
11962 +RUN('lua - < %s > %s', prog, out)
11963 +checkout("")
11964 +
11965 +prepfile[[
11966 + print(
11967 +1, a
11968 +)
11969 +]]
11970 +RUN('lua - < %s > %s', prog, out)
11971 +checkout("1\tnil\n")
11972 +
11973 +RUN('echo "print(10)\nprint(2)\n" | lua > %s', out)
11974 +checkout("10\n2\n")
11975 +
11976 +
11977 +-- test option '-'
11978 +RUN('echo "print(arg[1])" | lua - -h > %s', out)
11979 +checkout("-h\n")
11980 +
11981 +-- test environment variables used by Lua
11982 +
11983 +prepfile("print(package.path)")
11984 +
11985 +-- test LUA_PATH
11986 +RUN('env LUA_INIT= LUA_PATH=x lua %s > %s', prog, out)
11987 +checkout("x\n")
11988 +
11989 +-- test LUA_PATH_version
11990 +RUN('env LUA_INIT= LUA_PATH_5_4=y LUA_PATH=x lua %s > %s', prog, out)
11991 +checkout("y\n")
11992 +
11993 +-- test LUA_CPATH
11994 +prepfile("print(package.cpath)")
11995 +RUN('env LUA_INIT= LUA_CPATH=xuxu lua %s > %s', prog, out)
11996 +checkout("xuxu\n")
11997 +
11998 +-- test LUA_CPATH_version
11999 +RUN('env LUA_INIT= LUA_CPATH_5_4=yacc LUA_CPATH=x lua %s > %s', prog, out)
12000 +checkout("yacc\n")
12001 +
12002 +-- test LUA_INIT (and its access to 'arg' table)
12003 +prepfile("print(X)")
12004 +RUN('env LUA_INIT="X=tonumber(arg[1])" lua %s 3.2 > %s', prog, out)
12005 +checkout("3.2\n")
12006 +
12007 +-- test LUA_INIT_version
12008 +prepfile("print(X)")
12009 +RUN('env LUA_INIT_5_4="X=10" LUA_INIT="X=3" lua %s > %s', prog, out)
12010 +checkout("10\n")
12011 +
12012 +-- test LUA_INIT for files
12013 +prepfile("x = x or 10; print(x); x = x + 1")
12014 +RUN('env LUA_INIT="@%s" lua %s > %s', prog, prog, out)
12015 +checkout("10\n11\n")
12016 +
12017 +-- test errors in LUA_INIT
12018 +NoRun('LUA_INIT:1: msg', 'env LUA_INIT="error(\'msg\')" lua')
12019 +
12020 +-- test option '-E'
12021 +local defaultpath, defaultCpath
12022 +
12023 +do
12024 + prepfile("print(package.path, package.cpath)")
12025 + RUN('env LUA_INIT="error(10)" LUA_PATH=xxx LUA_CPATH=xxx lua -E %s > %s',
12026 + prog, out)
12027 + local output = getoutput()
12028 + defaultpath = string.match(output, "^(.-)\t")
12029 + defaultCpath = string.match(output, "\t(.-)$")
12030 +
12031 + -- running with an empty environment
12032 + RUN('env -i lua %s > %s', prog, out)
12033 + local out = getoutput()
12034 + assert(defaultpath == string.match(output, "^(.-)\t"))
12035 + assert(defaultCpath == string.match(output, "\t(.-)$"))
12036 +end
12037 +
12038 +-- paths did not change
12039 +assert(not string.find(defaultpath, "xxx") and
12040 + string.find(defaultpath, "lua") and
12041 + not string.find(defaultCpath, "xxx") and
12042 + string.find(defaultCpath, "lua"))
12043 +
12044 +
12045 +-- test replacement of ';;' to default path
12046 +local function convert (p)
12047 + prepfile("print(package.path)")
12048 + RUN('env LUA_PATH="%s" lua %s > %s', p, prog, out)
12049 + local expected = getoutput()
12050 + expected = string.sub(expected, 1, -2) -- cut final end of line
12051 + if string.find(p, ";;") then
12052 + p = string.gsub(p, ";;", ";"..defaultpath..";")
12053 + p = string.gsub(p, "^;", "") -- remove ';' at the beginning
12054 + p = string.gsub(p, ";$", "") -- remove ';' at the end
12055 + end
12056 + assert(p == expected)
12057 +end
12058 +
12059 +convert(";")
12060 +convert(";;")
12061 +convert("a;;b")
12062 +convert(";;b")
12063 +convert("a;;")
12064 +convert("a;b;;c")
12065 +
12066 +
12067 +-- test -l over multiple libraries
12068 +prepfile("print(1); a=2; return {x=15}")
12069 +prepfile(("print(a); print(_G['%s'].x)"):format(prog), otherprog)
12070 +RUN('env LUA_PATH="?;;" lua -l %s -l%s -lstring -l io %s > %s', prog, otherprog, otherprog, out)
12071 +checkout("1\n2\n15\n2\n15\n")
12072 +
12073 +-- test explicit global names in -l
12074 +prepfile("print(str.upper'alo alo', m.max(10, 20))")
12075 +RUN("lua -l 'str=string' '-lm=math' -e 'print(m.sin(0))' %s > %s", prog, out)
12076 +checkout("0.0\nALO ALO\t20\n")
12077 +
12078 +-- test 'arg' table
12079 +local a = [[
12080 + assert(#arg == 3 and arg[1] == 'a' and
12081 + arg[2] == 'b' and arg[3] == 'c')
12082 + assert(arg[-1] == '--' and arg[-2] == "-e " and arg[-3] == '%s')
12083 + assert(arg[4] == undef and arg[-4] == undef)
12084 + local a, b, c = ...
12085 + assert(... == 'a' and a == 'a' and b == 'b' and c == 'c')
12086 +]]
12087 +a = string.format(a, progname)
12088 +prepfile(a)
12089 +RUN('lua "-e " -- %s a b c', prog) -- "-e " runs an empty command
12090 +
12091 +-- test 'arg' availability in libraries
12092 +prepfile"assert(arg)"
12093 +prepfile("assert(arg)", otherprog)
12094 +RUN('env LUA_PATH="?;;" lua -l%s - < %s', prog, otherprog)
12095 +
12096 +-- test messing up the 'arg' table
12097 +RUN('echo "print(...)" | lua -e "arg[1] = 100" - > %s', out)
12098 +checkout("100\n")
12099 +NoRun("'arg' is not a table", 'echo "" | lua -e "arg = 1" -')
12100 +
12101 +-- test error in 'print'
12102 +RUN('echo 10 | lua -e "print=nil" -i > /dev/null 2> %s', out)
12103 +assert(string.find(getoutput(), "error calling 'print'"))
12104 +
12105 +-- test 'debug.debug'
12106 +RUN('echo "io.stderr:write(1000)\ncont" | lua -e "require\'debug\'.debug()" 2> %s', out)
12107 +checkout("lua_debug> 1000lua_debug> ")
12108 +
12109 +
12110 +print("testing warnings")
12111 +
12112 +-- no warnings by default
12113 +RUN('echo "io.stderr:write(1); warn[[XXX]]" | lua 2> %s', out)
12114 +checkout("1")
12115 +
12116 +prepfile[[
12117 +warn("@allow") -- unknown control, ignored
12118 +warn("@off", "XXX", "@off") -- these are not control messages
12119 +warn("@off") -- this one is
12120 +warn("@on", "YYY", "@on") -- not control, but warn is off
12121 +warn("@off") -- keep it off
12122 +warn("@on") -- restart warnings
12123 +warn("", "@on") -- again, no control, real warning
12124 +warn("@on") -- keep it "started"
12125 +warn("Z", "Z", "Z") -- common warning
12126 +]]
12127 +RUN('lua -W %s 2> %s', prog, out)
12128 +checkout[[
12129 +Lua warning: @offXXX@off
12130 +Lua warning: @on
12131 +Lua warning: ZZZ
12132 +]]
12133 +
12134 +prepfile[[
12135 +warn("@allow")
12136 +-- create two objects to be finalized when closing state
12137 +-- the errors in the finalizers must generate warnings
12138 +u1 = setmetatable({}, {__gc = function () error("XYZ") end})
12139 +u2 = setmetatable({}, {__gc = function () error("ZYX") end})
12140 +]]
12141 +RUN('lua -W %s 2> %s', prog, out)
12142 +checkprogout("ZYX)\nXYZ)\n")
12143 +
12144 +-- bug since 5.2: finalizer called when closing a state could
12145 +-- subvert finalization order
12146 +prepfile[[
12147 +-- should be called last
12148 +print("creating 1")
12149 +setmetatable({}, {__gc = function () print(1) end})
12150 +
12151 +print("creating 2")
12152 +setmetatable({}, {__gc = function ()
12153 + print("2")
12154 + print("creating 3")
12155 + -- this finalizer should not be called, as object will be
12156 + -- created after 'lua_close' has been called
12157 + setmetatable({}, {__gc = function () print(3) end})
12158 + print(collectgarbage()) -- cannot call collector here
12159 + os.exit(0, true)
12160 +end})
12161 +]]
12162 +RUN('lua -W %s > %s', prog, out)
12163 +checkout[[
12164 +creating 1
12165 +creating 2
12166 +2
12167 +creating 3
12168 +nil
12169 +1
12170 +]]
12171 +
12172 +
12173 +-- test many arguments
12174 +prepfile[[print(({...})[30])]]
12175 +RUN('lua %s %s > %s', prog, string.rep(" a", 30), out)
12176 +checkout("a\n")
12177 +
12178 +RUN([[lua "-eprint(1)" -ea=3 -e "print(a)" > %s]], out)
12179 +checkout("1\n3\n")
12180 +
12181 +-- test iteractive mode
12182 +prepfile[[
12183 +(6*2-6) -- ===
12184 +a =
12185 +10
12186 +print(a)
12187 +a]]
12188 +RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
12189 +checkprogout("6\n10\n10\n\n")
12190 +
12191 +prepfile("a = [[b\nc\nd\ne]]\n=a")
12192 +RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
12193 +checkprogout("b\nc\nd\ne\n\n")
12194 +
12195 +prompt = "alo"
12196 +prepfile[[ --
12197 +a = 2
12198 +]]
12199 +RUN([[lua "-e_PROMPT='%s'" -i < %s > %s]], prompt, prog, out)
12200 +local t = getoutput()
12201 +assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
12202 +
12203 +-- using the prompt default
12204 +prepfile[[ --
12205 +a = 2
12206 +]]
12207 +RUN([[lua -i < %s > %s]], prog, out)
12208 +local t = getoutput()
12209 +prompt = "> " -- the default
12210 +assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
12211 +
12212 +
12213 +-- non-string prompt
12214 +prompt =
12215 + "local C = 0;\z
12216 + _PROMPT=setmetatable({},{__tostring = function () \z
12217 + C = C + 1; return C end})"
12218 +prepfile[[ --
12219 +a = 2
12220 +]]
12221 +RUN([[lua -e "%s" -i < %s > %s]], prompt, prog, out)
12222 +local t = getoutput()
12223 +assert(string.find(t, [[
12224 +1 --
12225 +2a = 2
12226 +3
12227 +]], 1, true))
12228 +
12229 +
12230 +-- test for error objects
12231 +prepfile[[
12232 +debug = require "debug"
12233 +m = {x=0}
12234 +setmetatable(m, {__tostring = function(x)
12235 + return tostring(debug.getinfo(4).currentline + x.x)
12236 +end})
12237 +error(m)
12238 +]]
12239 +NoRun(progname .. ": 6\n", [[lua %s]], prog)
12240 +
12241 +prepfile("error{}")
12242 +NoRun("error object is a table value", [[lua %s]], prog)
12243 +
12244 +
12245 +-- chunk broken in many lines
12246 +s = [=[ --
12247 +function f ( x )
12248 + local a = [[
12249 +xuxu
12250 +]]
12251 + local b = "\
12252 +xuxu\n"
12253 + if x == 11 then return 1 + 12 , 2 + 20 end --[[ test multiple returns ]]
12254 + return x + 1
12255 + --\\
12256 +end
12257 +return( f( 100 ) )
12258 +assert( a == b )
12259 +do return f( 11 ) end ]=]
12260 +s = string.gsub(s, ' ', '\n\n') -- change all spaces for newlines
12261 +prepfile(s)
12262 +RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
12263 +checkprogout("101\n13\t22\n\n")
12264 +
12265 +prepfile[[#comment in 1st line without \n at the end]]
12266 +RUN('lua %s', prog)
12267 +
12268 +prepfile[[#test line number when file starts with comment line
12269 +debug = require"debug"
12270 +print(debug.getinfo(1).currentline)
12271 +]]
12272 +RUN('lua %s > %s', prog, out)
12273 +checkprogout('3\n')
12274 +
12275 +-- close Lua with an open file
12276 +prepfile(string.format([[io.output(%q); io.write('alo')]], out))
12277 +RUN('lua %s', prog)
12278 +checkout('alo')
12279 +
12280 +-- bug in 5.2 beta (extra \0 after version line)
12281 +RUN([[lua -v -e"print'hello'" > %s]], out)
12282 +t = getoutput()
12283 +assert(string.find(t, "PUC%-Rio\nhello"))
12284 +
12285 +
12286 +-- testing os.exit
12287 +prepfile("os.exit(nil, true)")
12288 +RUN('lua %s', prog)
12289 +prepfile("os.exit(0, true)")
12290 +RUN('lua %s', prog)
12291 +prepfile("os.exit(true, true)")
12292 +RUN('lua %s', prog)
12293 +prepfile("os.exit(1, true)")
12294 +NoRun("", "lua %s", prog) -- no message
12295 +prepfile("os.exit(false, true)")
12296 +NoRun("", "lua %s", prog) -- no message
12297 +
12298 +
12299 +-- to-be-closed variables in main chunk
12300 +prepfile[[
12301 + local x <close> = setmetatable({},
12302 + {__close = function (self, err)
12303 + assert(err == nil)
12304 + print("Ok")
12305 + end})
12306 + local e1 <close> = setmetatable({}, {__close = function () print(120) end})
12307 + os.exit(true, true)
12308 +]]
12309 +RUN('lua %s > %s', prog, out)
12310 +checkprogout("120\nOk\n")
12311 +
12312 +
12313 +-- remove temporary files
12314 +assert(os.remove(prog))
12315 +assert(os.remove(otherprog))
12316 +assert(not os.remove(out))
12317 +
12318 +-- invalid options
12319 +NoRun("unrecognized option '-h'", "lua -h")
12320 +NoRun("unrecognized option '---'", "lua ---")
12321 +NoRun("unrecognized option '-Ex'", "lua -Ex")
12322 +NoRun("unrecognized option '-vv'", "lua -vv")
12323 +NoRun("unrecognized option '-iv'", "lua -iv")
12324 +NoRun("'-e' needs argument", "lua -e")
12325 +NoRun("syntax error", "lua -e a")
12326 +NoRun("'-l' needs argument", "lua -l")
12327 +
12328 +
12329 +if T then -- test library?
12330 + print("testing 'not enough memory' to create a state")
12331 + NoRun("not enough memory", "env MEMLIMIT=100 lua")
12332 +
12333 + -- testing 'warn'
12334 + warn("@store")
12335 + warn("@123", "456", "789")
12336 + assert(_WARN == "@123456789"); _WARN = false
12337 +
12338 + warn("zip", "", " ", "zap")
12339 + assert(_WARN == "zip zap"); _WARN = false
12340 + warn("ZIP", "", " ", "ZAP")
12341 + assert(_WARN == "ZIP ZAP"); _WARN = false
12342 + warn("@normal")
12343 +end
12344 +
12345 +do
12346 + -- 'warn' must get at least one argument
12347 + local st, msg = pcall(warn)
12348 + assert(string.find(msg, "string expected"))
12349 +
12350 + -- 'warn' does not leave unfinished warning in case of errors
12351 + -- (message would appear in next warning)
12352 + st, msg = pcall(warn, "SHOULD NOT APPEAR", {})
12353 + assert(string.find(msg, "string expected"))
12354 +end
12355 +
12356 +print('+')
12357 +
12358 +print('testing Ctrl C')
12359 +do
12360 + -- interrupt a script
12361 + local function kill (pid)
12362 + return os.execute(string.format('kill -INT %s 2> /dev/null', pid))
12363 + end
12364 +
12365 + -- function to run a script in background, returning its output file
12366 + -- descriptor and its pid
12367 + local function runback (luaprg)
12368 + -- shell script to run 'luaprg' in background and echo its pid
12369 + local shellprg = string.format('%s -e "%s" & echo $!', progname, luaprg)
12370 + local f = io.popen(shellprg, "r") -- run shell script
12371 + local pid = f:read() -- get pid for Lua script
12372 + print("(if test fails now, it may leave a Lua script running in \z
12373 + background, pid " .. pid .. ")")
12374 + return f, pid
12375 + end
12376 +
12377 + -- Lua script that runs protected infinite loop and then prints '42'
12378 + local f, pid = runback[[
12379 + pcall(function () print(12); while true do end end); print(42)]]
12380 + -- wait until script is inside 'pcall'
12381 + assert(f:read() == "12")
12382 + kill(pid) -- send INT signal to Lua script
12383 + -- check that 'pcall' captured the exception and script continued running
12384 + assert(f:read() == "42") -- expected output
12385 + assert(f:close())
12386 + print("done")
12387 +
12388 + -- Lua script in a long unbreakable search
12389 + local f, pid = runback[[
12390 + print(15); string.find(string.rep('a', 100000), '.*b')]]
12391 + -- wait (so script can reach the loop)
12392 + assert(f:read() == "15")
12393 + assert(os.execute("sleep 1"))
12394 + -- must send at least two INT signals to stop this Lua script
12395 + local n = 100
12396 + for i = 0, 100 do -- keep sending signals
12397 + if not kill(pid) then -- until it fails
12398 + n = i -- number of non-failed kills
12399 + break
12400 + end
12401 + end
12402 + assert(f:close())
12403 + assert(n >= 2)
12404 + print(string.format("done (with %d kills)", n))
12405 +
12406 +end
12407 +
12408 +print("OK")
12409
12410 diff --git a/tests/math.lua b/tests/math.lua
12411 new file mode 100644
12412 index 0000000..48c1efe
12413 --- /dev/null
12414 +++ b/tests/math.lua
12415 @@ -0,0 +1,1024 @@
12416 +-- $Id: testes/math.lua $
12417 +-- See Copyright Notice in file all.lua
12418 +
12419 +print("testing numbers and math lib")
12420 +
12421 +local minint <const> = math.mininteger
12422 +local maxint <const> = math.maxinteger
12423 +
12424 +local intbits <const> = math.floor(math.log(maxint, 2) + 0.5) + 1
12425 +assert((1 << intbits) == 0)
12426 +
12427 +assert(minint == 1 << (intbits - 1))
12428 +assert(maxint == minint - 1)
12429 +
12430 +-- number of bits in the mantissa of a floating-point number
12431 +local floatbits = 24
12432 +do
12433 + local p = 2.0^floatbits
12434 + while p < p + 1.0 do
12435 + p = p * 2.0
12436 + floatbits = floatbits + 1
12437 + end
12438 +end
12439 +
12440 +local function isNaN (x)
12441 + return (x ~= x)
12442 +end
12443 +
12444 +assert(isNaN(0/0))
12445 +assert(not isNaN(1/0))
12446 +
12447 +
12448 +do
12449 + local x = 2.0^floatbits
12450 + assert(x > x - 1.0 and x == x + 1.0)
12451 +
12452 + print(string.format("%d-bit integers, %d-bit (mantissa) floats",
12453 + intbits, floatbits))
12454 +end
12455 +
12456 +assert(math.type(0) == "integer" and math.type(0.0) == "float"
12457 + and not math.type("10"))
12458 +
12459 +
12460 +local function checkerror (msg, f, ...)
12461 + local s, err = pcall(f, ...)
12462 + assert(not s and string.find(err, msg))
12463 +end
12464 +
12465 +local msgf2i = "number.* has no integer representation"
12466 +
12467 +-- float equality
12468 +function eq (a,b,limit)
12469 + if not limit then
12470 + if floatbits >= 50 then limit = 1E-11
12471 + else limit = 1E-5
12472 + end
12473 + end
12474 + -- a == b needed for +inf/-inf
12475 + return a == b or math.abs(a-b) <= limit
12476 +end
12477 +
12478 +
12479 +-- equality with types
12480 +function eqT (a,b)
12481 + return a == b and math.type(a) == math.type(b)
12482 +end
12483 +
12484 +
12485 +-- basic float notation
12486 +assert(0e12 == 0 and .0 == 0 and 0. == 0 and .2e2 == 20 and 2.E-1 == 0.2)
12487 +
12488 +do
12489 + local a,b,c = "2", " 3e0 ", " 10 "
12490 + assert(a+b == 5 and -b == -3 and b+"2" == 5 and "10"-c == 0)
12491 + assert(type(a) == 'string' and type(b) == 'string' and type(c) == 'string')
12492 + assert(a == "2" and b == " 3e0 " and c == " 10 " and -c == -" 10 ")
12493 + assert(c%a == 0 and a^b == 08)
12494 + a = 0
12495 + assert(a == -a and 0 == -0)
12496 +end
12497 +
12498 +do
12499 + local x = -1
12500 + local mz = 0/x -- minus zero
12501 + t = {[0] = 10, 20, 30, 40, 50}
12502 + assert(t[mz] == t[0] and t[-0] == t[0])
12503 +end
12504 +
12505 +do -- tests for 'modf'
12506 + local a,b = math.modf(3.5)
12507 + assert(a == 3.0 and b == 0.5)
12508 + a,b = math.modf(-2.5)
12509 + assert(a == -2.0 and b == -0.5)
12510 + a,b = math.modf(-3e23)
12511 + assert(a == -3e23 and b == 0.0)
12512 + a,b = math.modf(3e35)
12513 + assert(a == 3e35 and b == 0.0)
12514 + a,b = math.modf(-1/0) -- -inf
12515 + assert(a == -1/0 and b == 0.0)
12516 + a,b = math.modf(1/0) -- inf
12517 + assert(a == 1/0 and b == 0.0)
12518 + a,b = math.modf(0/0) -- NaN
12519 + assert(isNaN(a) and isNaN(b))
12520 + a,b = math.modf(3) -- integer argument
12521 + assert(eqT(a, 3) and eqT(b, 0.0))
12522 + a,b = math.modf(minint)
12523 + assert(eqT(a, minint) and eqT(b, 0.0))
12524 +end
12525 +
12526 +assert(math.huge > 10e30)
12527 +assert(-math.huge < -10e30)
12528 +
12529 +
12530 +-- integer arithmetic
12531 +assert(minint < minint + 1)
12532 +assert(maxint - 1 < maxint)
12533 +assert(0 - minint == minint)
12534 +assert(minint * minint == 0)
12535 +assert(maxint * maxint * maxint == maxint)
12536 +
12537 +
12538 +-- testing floor division and conversions
12539 +
12540 +for _, i in pairs{-16, -15, -3, -2, -1, 0, 1, 2, 3, 15} do
12541 + for _, j in pairs{-16, -15, -3, -2, -1, 1, 2, 3, 15} do
12542 + for _, ti in pairs{0, 0.0} do -- try 'i' as integer and as float
12543 + for _, tj in pairs{0, 0.0} do -- try 'j' as integer and as float
12544 + local x = i + ti
12545 + local y = j + tj
12546 + assert(i//j == math.floor(i/j))
12547 + end
12548 + end
12549 + end
12550 +end
12551 +
12552 +assert(1//0.0 == 1/0)
12553 +assert(-1 // 0.0 == -1/0)
12554 +assert(eqT(3.5 // 1.5, 2.0))
12555 +assert(eqT(3.5 // -1.5, -3.0))
12556 +
12557 +do -- tests for different kinds of opcodes
12558 + local x, y
12559 + x = 1; assert(x // 0.0 == 1/0)
12560 + x = 1.0; assert(x // 0 == 1/0)
12561 + x = 3.5; assert(eqT(x // 1, 3.0))
12562 + assert(eqT(x // -1, -4.0))
12563 +
12564 + x = 3.5; y = 1.5; assert(eqT(x // y, 2.0))
12565 + x = 3.5; y = -1.5; assert(eqT(x // y, -3.0))
12566 +end
12567 +
12568 +assert(maxint // maxint == 1)
12569 +assert(maxint // 1 == maxint)
12570 +assert((maxint - 1) // maxint == 0)
12571 +assert(maxint // (maxint - 1) == 1)
12572 +assert(minint // minint == 1)
12573 +assert(minint // minint == 1)
12574 +assert((minint + 1) // minint == 0)
12575 +assert(minint // (minint + 1) == 1)
12576 +assert(minint // 1 == minint)
12577 +
12578 +assert(minint // -1 == -minint)
12579 +assert(minint // -2 == 2^(intbits - 2))
12580 +assert(maxint // -1 == -maxint)
12581 +
12582 +
12583 +-- negative exponents
12584 +do
12585 + assert(2^-3 == 1 / 2^3)
12586 + assert(eq((-3)^-3, 1 / (-3)^3))
12587 + for i = -3, 3 do -- variables avoid constant folding
12588 + for j = -3, 3 do
12589 + -- domain errors (0^(-n)) are not portable
12590 + if not _port or i ~= 0 or j > 0 then
12591 + assert(eq(i^j, 1 / i^(-j)))
12592 + end
12593 + end
12594 + end
12595 +end
12596 +
12597 +-- comparison between floats and integers (border cases)
12598 +if floatbits < intbits then
12599 + assert(2.0^floatbits == (1 << floatbits))
12600 + assert(2.0^floatbits - 1.0 == (1 << floatbits) - 1.0)
12601 + assert(2.0^floatbits - 1.0 ~= (1 << floatbits))
12602 + -- float is rounded, int is not
12603 + assert(2.0^floatbits + 1.0 ~= (1 << floatbits) + 1)
12604 +else -- floats can express all integers with full accuracy
12605 + assert(maxint == maxint + 0.0)
12606 + assert(maxint - 1 == maxint - 1.0)
12607 + assert(minint + 1 == minint + 1.0)
12608 + assert(maxint ~= maxint - 1.0)
12609 +end
12610 +assert(maxint + 0.0 == 2.0^(intbits - 1) - 1.0)
12611 +assert(minint + 0.0 == minint)
12612 +assert(minint + 0.0 == -2.0^(intbits - 1))
12613 +
12614 +
12615 +-- order between floats and integers
12616 +assert(1 < 1.1); assert(not (1 < 0.9))
12617 +assert(1 <= 1.1); assert(not (1 <= 0.9))
12618 +assert(-1 < -0.9); assert(not (-1 < -1.1))
12619 +assert(1 <= 1.1); assert(not (-1 <= -1.1))
12620 +assert(-1 < -0.9); assert(not (-1 < -1.1))
12621 +assert(-1 <= -0.9); assert(not (-1 <= -1.1))
12622 +assert(minint <= minint + 0.0)
12623 +assert(minint + 0.0 <= minint)
12624 +assert(not (minint < minint + 0.0))
12625 +assert(not (minint + 0.0 < minint))
12626 +assert(maxint < minint * -1.0)
12627 +assert(maxint <= minint * -1.0)
12628 +
12629 +do
12630 + local fmaxi1 = 2^(intbits - 1)
12631 + assert(maxint < fmaxi1)
12632 + assert(maxint <= fmaxi1)
12633 + assert(not (fmaxi1 <= maxint))
12634 + assert(minint <= -2^(intbits - 1))
12635 + assert(-2^(intbits - 1) <= minint)
12636 +end
12637 +
12638 +if floatbits < intbits then
12639 + print("testing order (floats cannot represent all integers)")
12640 + local fmax = 2^floatbits
12641 + local ifmax = fmax | 0
12642 + assert(fmax < ifmax + 1)
12643 + assert(fmax - 1 < ifmax)
12644 + assert(-(fmax - 1) > -ifmax)
12645 + assert(not (fmax <= ifmax - 1))
12646 + assert(-fmax > -(ifmax + 1))
12647 + assert(not (-fmax >= -(ifmax - 1)))
12648 +
12649 + assert(fmax/2 - 0.5 < ifmax//2)
12650 + assert(-(fmax/2 - 0.5) > -ifmax//2)
12651 +
12652 + assert(maxint < 2^intbits)
12653 + assert(minint > -2^intbits)
12654 + assert(maxint <= 2^intbits)
12655 + assert(minint >= -2^intbits)
12656 +else
12657 + print("testing order (floats can represent all integers)")
12658 + assert(maxint < maxint + 1.0)
12659 + assert(maxint < maxint + 0.5)
12660 + assert(maxint - 1.0 < maxint)
12661 + assert(maxint - 0.5 < maxint)
12662 + assert(not (maxint + 0.0 < maxint))
12663 + assert(maxint + 0.0 <= maxint)
12664 + assert(not (maxint < maxint + 0.0))
12665 + assert(maxint + 0.0 <= maxint)
12666 + assert(maxint <= maxint + 0.0)
12667 + assert(not (maxint + 1.0 <= maxint))
12668 + assert(not (maxint + 0.5 <= maxint))
12669 + assert(not (maxint <= maxint - 1.0))
12670 + assert(not (maxint <= maxint - 0.5))
12671 +
12672 + assert(minint < minint + 1.0)
12673 + assert(minint < minint + 0.5)
12674 + assert(minint <= minint + 0.5)
12675 + assert(minint - 1.0 < minint)
12676 + assert(minint - 1.0 <= minint)
12677 + assert(not (minint + 0.0 < minint))
12678 + assert(not (minint + 0.5 < minint))
12679 + assert(not (minint < minint + 0.0))
12680 + assert(minint + 0.0 <= minint)
12681 + assert(minint <= minint + 0.0)
12682 + assert(not (minint + 1.0 <= minint))
12683 + assert(not (minint + 0.5 <= minint))
12684 + assert(not (minint <= minint - 1.0))
12685 +end
12686 +
12687 +do
12688 + local NaN <const> = 0/0
12689 + assert(not (NaN < 0))
12690 + assert(not (NaN > minint))
12691 + assert(not (NaN <= -9))
12692 + assert(not (NaN <= maxint))
12693 + assert(not (NaN < maxint))
12694 + assert(not (minint <= NaN))
12695 + assert(not (minint < NaN))
12696 + assert(not (4 <= NaN))
12697 + assert(not (4 < NaN))
12698 +end
12699 +
12700 +
12701 +-- avoiding errors at compile time
12702 +local function checkcompt (msg, code)
12703 + checkerror(msg, assert(load(code)))
12704 +end
12705 +checkcompt("divide by zero", "return 2 // 0")
12706 +checkcompt(msgf2i, "return 2.3 >> 0")
12707 +checkcompt(msgf2i, ("return 2.0^%d & 1"):format(intbits - 1))
12708 +checkcompt("field 'huge'", "return math.huge << 1")
12709 +checkcompt(msgf2i, ("return 1 | 2.0^%d"):format(intbits - 1))
12710 +checkcompt(msgf2i, "return 2.3 ~ 0.0")
12711 +
12712 +
12713 +-- testing overflow errors when converting from float to integer (runtime)
12714 +local function f2i (x) return x | x end
12715 +checkerror(msgf2i, f2i, math.huge) -- +inf
12716 +checkerror(msgf2i, f2i, -math.huge) -- -inf
12717 +checkerror(msgf2i, f2i, 0/0) -- NaN
12718 +
12719 +if floatbits < intbits then
12720 + -- conversion tests when float cannot represent all integers
12721 + assert(maxint + 1.0 == maxint + 0.0)
12722 + assert(minint - 1.0 == minint + 0.0)
12723 + checkerror(msgf2i, f2i, maxint + 0.0)
12724 + assert(f2i(2.0^(intbits - 2)) == 1 << (intbits - 2))
12725 + assert(f2i(-2.0^(intbits - 2)) == -(1 << (intbits - 2)))
12726 + assert((2.0^(floatbits - 1) + 1.0) // 1 == (1 << (floatbits - 1)) + 1)
12727 + -- maximum integer representable as a float
12728 + local mf = maxint - (1 << (floatbits - intbits)) + 1
12729 + assert(f2i(mf + 0.0) == mf) -- OK up to here
12730 + mf = mf + 1
12731 + assert(f2i(mf + 0.0) ~= mf) -- no more representable
12732 +else
12733 + -- conversion tests when float can represent all integers
12734 + assert(maxint + 1.0 > maxint)
12735 + assert(minint - 1.0 < minint)
12736 + assert(f2i(maxint + 0.0) == maxint)
12737 + checkerror("no integer rep", f2i, maxint + 1.0)
12738 + checkerror("no integer rep", f2i, minint - 1.0)
12739 +end
12740 +
12741 +-- 'minint' should be representable as a float no matter the precision
12742 +assert(f2i(minint + 0.0) == minint)
12743 +
12744 +
12745 +-- testing numeric strings
12746 +
12747 +assert("2" + 1 == 3)
12748 +assert("2 " + 1 == 3)
12749 +assert(" -2 " + 1 == -1)
12750 +assert(" -0xa " + 1 == -9)
12751 +
12752 +
12753 +-- Literal integer Overflows (new behavior in 5.3.3)
12754 +do
12755 + -- no overflows
12756 + assert(eqT(tonumber(tostring(maxint)), maxint))
12757 + assert(eqT(tonumber(tostring(minint)), minint))
12758 +
12759 + -- add 1 to last digit as a string (it cannot be 9...)
12760 + local function incd (n)
12761 + local s = string.format("%d", n)
12762 + s = string.gsub(s, "%d$", function (d)
12763 + assert(d ~= '9')
12764 + return string.char(string.byte(d) + 1)
12765 + end)
12766 + return s
12767 + end
12768 +
12769 + -- 'tonumber' with overflow by 1
12770 + assert(eqT(tonumber(incd(maxint)), maxint + 1.0))
12771 + assert(eqT(tonumber(incd(minint)), minint - 1.0))
12772 +
12773 + -- large numbers
12774 + assert(eqT(tonumber("1"..string.rep("0", 30)), 1e30))
12775 + assert(eqT(tonumber("-1"..string.rep("0", 30)), -1e30))
12776 +
12777 + -- hexa format still wraps around
12778 + assert(eqT(tonumber("0x1"..string.rep("0", 30)), 0))
12779 +
12780 + -- lexer in the limits
12781 + assert(minint == load("return " .. minint)())
12782 + assert(eqT(maxint, load("return " .. maxint)()))
12783 +
12784 + assert(eqT(10000000000000000000000.0, 10000000000000000000000))
12785 + assert(eqT(-10000000000000000000000.0, -10000000000000000000000))
12786 +end
12787 +
12788 +
12789 +-- testing 'tonumber'
12790 +
12791 +-- 'tonumber' with numbers
12792 +assert(tonumber(3.4) == 3.4)
12793 +assert(eqT(tonumber(3), 3))
12794 +assert(eqT(tonumber(maxint), maxint) and eqT(tonumber(minint), minint))
12795 +assert(tonumber(1/0) == 1/0)
12796 +
12797 +-- 'tonumber' with strings
12798 +assert(tonumber("0") == 0)
12799 +assert(not tonumber(""))
12800 +assert(not tonumber(" "))
12801 +assert(not tonumber("-"))
12802 +assert(not tonumber(" -0x "))
12803 +assert(not tonumber{})
12804 +assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and
12805 + tonumber'.01' == 0.01 and tonumber'-1.' == -1 and
12806 + tonumber'+1.' == 1)
12807 +assert(not tonumber'+ 0.01' and not tonumber'+.e1' and
12808 + not tonumber'1e' and not tonumber'1.0e+' and
12809 + not tonumber'.')
12810 +assert(tonumber('-012') == -010-2)
12811 +assert(tonumber('-1.2e2') == - - -120)
12812 +
12813 +assert(tonumber("0xffffffffffff") == (1 << (4*12)) - 1)
12814 +assert(tonumber("0x"..string.rep("f", (intbits//4))) == -1)
12815 +assert(tonumber("-0x"..string.rep("f", (intbits//4))) == 1)
12816 +
12817 +-- testing 'tonumber' with base
12818 +assert(tonumber(' 001010 ', 2) == 10)
12819 +assert(tonumber(' 001010 ', 10) == 001010)
12820 +assert(tonumber(' -1010 ', 2) == -10)
12821 +assert(tonumber('10', 36) == 36)
12822 +assert(tonumber(' -10 ', 36) == -36)
12823 +assert(tonumber(' +1Z ', 36) == 36 + 35)
12824 +assert(tonumber(' -1z ', 36) == -36 + -35)
12825 +assert(tonumber('-fFfa', 16) == -(10+(16*(15+(16*(15+(16*15)))))))
12826 +assert(tonumber(string.rep('1', (intbits - 2)), 2) + 1 == 2^(intbits - 2))
12827 +assert(tonumber('ffffFFFF', 16)+1 == (1 << 32))
12828 +assert(tonumber('0ffffFFFF', 16)+1 == (1 << 32))
12829 +assert(tonumber('-0ffffffFFFF', 16) - 1 == -(1 << 40))
12830 +for i = 2,36 do
12831 + local i2 = i * i
12832 + local i10 = i2 * i2 * i2 * i2 * i2 -- i^10
12833 + assert(tonumber('\t10000000000\t', i) == i10)
12834 +end
12835 +
12836 +if not _soft then
12837 + -- tests with very long numerals
12838 + assert(tonumber("0x"..string.rep("f", 13)..".0") == 2.0^(4*13) - 1)
12839 + assert(tonumber("0x"..string.rep("f", 150)..".0") == 2.0^(4*150) - 1)
12840 + assert(tonumber("0x"..string.rep("f", 300)..".0") == 2.0^(4*300) - 1)
12841 + assert(tonumber("0x"..string.rep("f", 500)..".0") == 2.0^(4*500) - 1)
12842 + assert(tonumber('0x3.' .. string.rep('0', 1000)) == 3)
12843 + assert(tonumber('0x' .. string.rep('0', 1000) .. 'a') == 10)
12844 + assert(tonumber('0x0.' .. string.rep('0', 13).."1") == 2.0^(-4*14))
12845 + assert(tonumber('0x0.' .. string.rep('0', 150).."1") == 2.0^(-4*151))
12846 + assert(tonumber('0x0.' .. string.rep('0', 300).."1") == 2.0^(-4*301))
12847 + assert(tonumber('0x0.' .. string.rep('0', 500).."1") == 2.0^(-4*501))
12848 +
12849 + assert(tonumber('0xe03' .. string.rep('0', 1000) .. 'p-4000') == 3587.0)
12850 + assert(tonumber('0x.' .. string.rep('0', 1000) .. '74p4004') == 0x7.4)
12851 +end
12852 +
12853 +-- testing 'tonumber' for invalid formats
12854 +
12855 +local function f (...)
12856 + if select('#', ...) == 1 then
12857 + return (...)
12858 + else
12859 + return "***"
12860 + end
12861 +end
12862 +
12863 +assert(not f(tonumber('fFfa', 15)))
12864 +assert(not f(tonumber('099', 8)))
12865 +assert(not f(tonumber('1\0', 2)))
12866 +assert(not f(tonumber('', 8)))
12867 +assert(not f(tonumber(' ', 9)))
12868 +assert(not f(tonumber(' ', 9)))
12869 +assert(not f(tonumber('0xf', 10)))
12870 +
12871 +assert(not f(tonumber('inf')))
12872 +assert(not f(tonumber(' INF ')))
12873 +assert(not f(tonumber('Nan')))
12874 +assert(not f(tonumber('nan')))
12875 +
12876 +assert(not f(tonumber(' ')))
12877 +assert(not f(tonumber('')))
12878 +assert(not f(tonumber('1 a')))
12879 +assert(not f(tonumber('1 a', 2)))
12880 +assert(not f(tonumber('1\0')))
12881 +assert(not f(tonumber('1 \0')))
12882 +assert(not f(tonumber('1\0 ')))
12883 +assert(not f(tonumber('e1')))
12884 +assert(not f(tonumber('e 1')))
12885 +assert(not f(tonumber(' 3.4.5 ')))
12886 +
12887 +
12888 +-- testing 'tonumber' for invalid hexadecimal formats
12889 +
12890 +assert(not tonumber('0x'))
12891 +assert(not tonumber('x'))
12892 +assert(not tonumber('x3'))
12893 +assert(not tonumber('0x3.3.3')) -- two decimal points
12894 +assert(not tonumber('00x2'))
12895 +assert(not tonumber('0x 2'))
12896 +assert(not tonumber('0 x2'))
12897 +assert(not tonumber('23x'))
12898 +assert(not tonumber('- 0xaa'))
12899 +assert(not tonumber('-0xaaP ')) -- no exponent
12900 +assert(not tonumber('0x0.51p'))
12901 +assert(not tonumber('0x5p+-2'))
12902 +
12903 +
12904 +-- testing hexadecimal numerals
12905 +
12906 +assert(0x10 == 16 and 0xfff == 2^12 - 1 and 0XFB == 251)
12907 +assert(0x0p12 == 0 and 0x.0p-3 == 0)
12908 +assert(0xFFFFFFFF == (1 << 32) - 1)
12909 +assert(tonumber('+0x2') == 2)
12910 +assert(tonumber('-0xaA') == -170)
12911 +assert(tonumber('-0xffFFFfff') == -(1 << 32) + 1)
12912 +
12913 +-- possible confusion with decimal exponent
12914 +assert(0E+1 == 0 and 0xE+1 == 15 and 0xe-1 == 13)
12915 +
12916 +
12917 +-- floating hexas
12918 +
12919 +assert(tonumber(' 0x2.5 ') == 0x25/16)
12920 +assert(tonumber(' -0x2.5 ') == -0x25/16)
12921 +assert(tonumber(' +0x0.51p+8 ') == 0x51)
12922 +assert(0x.FfffFFFF == 1 - '0x.00000001')
12923 +assert('0xA.a' + 0 == 10 + 10/16)
12924 +assert(0xa.aP4 == 0XAA)
12925 +assert(0x4P-2 == 1)
12926 +assert(0x1.1 == '0x1.' + '+0x.1')
12927 +assert(0Xabcdef.0 == 0x.ABCDEFp+24)
12928 +
12929 +
12930 +assert(1.1 == 1.+.1)
12931 +assert(100.0 == 1E2 and .01 == 1e-2)
12932 +assert(1111111111 - 1111111110 == 1000.00e-03)
12933 +assert(1.1 == '1.'+'.1')
12934 +assert(tonumber'1111111111' - tonumber'1111111110' ==
12935 + tonumber" +0.001e+3 \n\t")
12936 +
12937 +assert(0.1e-30 > 0.9E-31 and 0.9E30 < 0.1e31)
12938 +
12939 +assert(0.123456 > 0.123455)
12940 +
12941 +assert(tonumber('+1.23E18') == 1.23*10.0^18)
12942 +
12943 +-- testing order operators
12944 +assert(not(1<1) and (1<2) and not(2<1))
12945 +assert(not('a'<'a') and ('a'<'b') and not('b'<'a'))
12946 +assert((1<=1) and (1<=2) and not(2<=1))
12947 +assert(('a'<='a') and ('a'<='b') and not('b'<='a'))
12948 +assert(not(1>1) and not(1>2) and (2>1))
12949 +assert(not('a'>'a') and not('a'>'b') and ('b'>'a'))
12950 +assert((1>=1) and not(1>=2) and (2>=1))
12951 +assert(('a'>='a') and not('a'>='b') and ('b'>='a'))
12952 +assert(1.3 < 1.4 and 1.3 <= 1.4 and not (1.3 < 1.3) and 1.3 <= 1.3)
12953 +
12954 +-- testing mod operator
12955 +assert(eqT(-4 % 3, 2))
12956 +assert(eqT(4 % -3, -2))
12957 +assert(eqT(-4.0 % 3, 2.0))
12958 +assert(eqT(4 % -3.0, -2.0))
12959 +assert(eqT(4 % -5, -1))
12960 +assert(eqT(4 % -5.0, -1.0))
12961 +assert(eqT(4 % 5, 4))
12962 +assert(eqT(4 % 5.0, 4.0))
12963 +assert(eqT(-4 % -5, -4))
12964 +assert(eqT(-4 % -5.0, -4.0))
12965 +assert(eqT(-4 % 5, 1))
12966 +assert(eqT(-4 % 5.0, 1.0))
12967 +assert(eqT(4.25 % 4, 0.25))
12968 +assert(eqT(10.0 % 2, 0.0))
12969 +assert(eqT(-10.0 % 2, 0.0))
12970 +assert(eqT(-10.0 % -2, 0.0))
12971 +assert(math.pi - math.pi % 1 == 3)
12972 +assert(math.pi - math.pi % 0.001 == 3.141)
12973 +
12974 +do -- very small numbers
12975 + local i, j = 0, 20000
12976 + while i < j do
12977 + local m = (i + j) // 2
12978 + if 10^-m > 0 then
12979 + i = m + 1
12980 + else
12981 + j = m
12982 + end
12983 + end
12984 + -- 'i' is the smallest possible ten-exponent
12985 + local b = 10^-(i - (i // 10)) -- a very small number
12986 + assert(b > 0 and b * b == 0)
12987 + local delta = b / 1000
12988 + assert(eq((2.1 * b) % (2 * b), (0.1 * b), delta))
12989 + assert(eq((-2.1 * b) % (2 * b), (2 * b) - (0.1 * b), delta))
12990 + assert(eq((2.1 * b) % (-2 * b), (0.1 * b) - (2 * b), delta))
12991 + assert(eq((-2.1 * b) % (-2 * b), (-0.1 * b), delta))
12992 +end
12993 +
12994 +
12995 +-- basic consistency between integer modulo and float modulo
12996 +for i = -10, 10 do
12997 + for j = -10, 10 do
12998 + if j ~= 0 then
12999 + assert((i + 0.0) % j == i % j)
13000 + end
13001 + end
13002 +end
13003 +
13004 +for i = 0, 10 do
13005 + for j = -10, 10 do
13006 + if j ~= 0 then
13007 + assert((2^i) % j == (1 << i) % j)
13008 + end
13009 + end
13010 +end
13011 +
13012 +do -- precision of module for large numbers
13013 + local i = 10
13014 + while (1 << i) > 0 do
13015 + assert((1 << i) % 3 == i % 2 + 1)
13016 + i = i + 1
13017 + end
13018 +
13019 + i = 10
13020 + while 2^i < math.huge do
13021 + assert(2^i % 3 == i % 2 + 1)
13022 + i = i + 1
13023 + end
13024 +end
13025 +
13026 +assert(eqT(minint % minint, 0))
13027 +assert(eqT(maxint % maxint, 0))
13028 +assert((minint + 1) % minint == minint + 1)
13029 +assert((maxint - 1) % maxint == maxint - 1)
13030 +assert(minint % maxint == maxint - 1)
13031 +
13032 +assert(minint % -1 == 0)
13033 +assert(minint % -2 == 0)
13034 +assert(maxint % -2 == -1)
13035 +
13036 +-- non-portable tests because Windows C library cannot compute
13037 +-- fmod(1, huge) correctly
13038 +if not _port then
13039 + local function anan (x) assert(isNaN(x)) end -- assert Not a Number
13040 + anan(0.0 % 0)
13041 + anan(1.3 % 0)
13042 + anan(math.huge % 1)
13043 + anan(math.huge % 1e30)
13044 + anan(-math.huge % 1e30)
13045 + anan(-math.huge % -1e30)
13046 + assert(1 % math.huge == 1)
13047 + assert(1e30 % math.huge == 1e30)
13048 + assert(1e30 % -math.huge == -math.huge)
13049 + assert(-1 % math.huge == math.huge)
13050 + assert(-1 % -math.huge == -1)
13051 +end
13052 +
13053 +
13054 +-- testing unsigned comparisons
13055 +assert(math.ult(3, 4))
13056 +assert(not math.ult(4, 4))
13057 +assert(math.ult(-2, -1))
13058 +assert(math.ult(2, -1))
13059 +assert(not math.ult(-2, -2))
13060 +assert(math.ult(maxint, minint))
13061 +assert(not math.ult(minint, maxint))
13062 +
13063 +
13064 +assert(eq(math.sin(-9.8)^2 + math.cos(-9.8)^2, 1))
13065 +assert(eq(math.tan(math.pi/4), 1))
13066 +assert(eq(math.sin(math.pi/2), 1) and eq(math.cos(math.pi/2), 0))
13067 +assert(eq(math.atan(1), math.pi/4) and eq(math.acos(0), math.pi/2) and
13068 + eq(math.asin(1), math.pi/2))
13069 +assert(eq(math.deg(math.pi/2), 90) and eq(math.rad(90), math.pi/2))
13070 +assert(math.abs(-10.43) == 10.43)
13071 +assert(eqT(math.abs(minint), minint))
13072 +assert(eqT(math.abs(maxint), maxint))
13073 +assert(eqT(math.abs(-maxint), maxint))
13074 +assert(eq(math.atan(1,0), math.pi/2))
13075 +assert(math.fmod(10,3) == 1)
13076 +assert(eq(math.sqrt(10)^2, 10))
13077 +assert(eq(math.log(2, 10), math.log(2)/math.log(10)))
13078 +assert(eq(math.log(2, 2), 1))
13079 +assert(eq(math.log(9, 3), 2))
13080 +assert(eq(math.exp(0), 1))
13081 +assert(eq(math.sin(10), math.sin(10%(2*math.pi))))
13082 +
13083 +
13084 +assert(tonumber(' 1.3e-2 ') == 1.3e-2)
13085 +assert(tonumber(' -1.00000000000001 ') == -1.00000000000001)
13086 +
13087 +-- testing constant limits
13088 +-- 2^23 = 8388608
13089 +assert(8388609 + -8388609 == 0)
13090 +assert(8388608 + -8388608 == 0)
13091 +assert(8388607 + -8388607 == 0)
13092 +
13093 +
13094 +
13095 +do -- testing floor & ceil
13096 + assert(eqT(math.floor(3.4), 3))
13097 + assert(eqT(math.ceil(3.4), 4))
13098 + assert(eqT(math.floor(-3.4), -4))
13099 + assert(eqT(math.ceil(-3.4), -3))
13100 + assert(eqT(math.floor(maxint), maxint))
13101 + assert(eqT(math.ceil(maxint), maxint))
13102 + assert(eqT(math.floor(minint), minint))
13103 + assert(eqT(math.floor(minint + 0.0), minint))
13104 + assert(eqT(math.ceil(minint), minint))
13105 + assert(eqT(math.ceil(minint + 0.0), minint))
13106 + assert(math.floor(1e50) == 1e50)
13107 + assert(math.ceil(1e50) == 1e50)
13108 + assert(math.floor(-1e50) == -1e50)
13109 + assert(math.ceil(-1e50) == -1e50)
13110 + for _, p in pairs{31,32,63,64} do
13111 + assert(math.floor(2^p) == 2^p)
13112 + assert(math.floor(2^p + 0.5) == 2^p)
13113 + assert(math.ceil(2^p) == 2^p)
13114 + assert(math.ceil(2^p - 0.5) == 2^p)
13115 + end
13116 + checkerror("number expected", math.floor, {})
13117 + checkerror("number expected", math.ceil, print)
13118 + assert(eqT(math.tointeger(minint), minint))
13119 + assert(eqT(math.tointeger(minint .. ""), minint))
13120 + assert(eqT(math.tointeger(maxint), maxint))
13121 + assert(eqT(math.tointeger(maxint .. ""), maxint))
13122 + assert(eqT(math.tointeger(minint + 0.0), minint))
13123 + assert(not math.tointeger(0.0 - minint))
13124 + assert(not math.tointeger(math.pi))
13125 + assert(not math.tointeger(-math.pi))
13126 + assert(math.floor(math.huge) == math.huge)
13127 + assert(math.ceil(math.huge) == math.huge)
13128 + assert(not math.tointeger(math.huge))
13129 + assert(math.floor(-math.huge) == -math.huge)
13130 + assert(math.ceil(-math.huge) == -math.huge)
13131 + assert(not math.tointeger(-math.huge))
13132 + assert(math.tointeger("34.0") == 34)
13133 + assert(not math.tointeger("34.3"))
13134 + assert(not math.tointeger({}))
13135 + assert(not math.tointeger(0/0)) -- NaN
13136 +end
13137 +
13138 +
13139 +-- testing fmod for integers
13140 +for i = -6, 6 do
13141 + for j = -6, 6 do
13142 + if j ~= 0 then
13143 + local mi = math.fmod(i, j)
13144 + local mf = math.fmod(i + 0.0, j)
13145 + assert(mi == mf)
13146 + assert(math.type(mi) == 'integer' and math.type(mf) == 'float')
13147 + if (i >= 0 and j >= 0) or (i <= 0 and j <= 0) or mi == 0 then
13148 + assert(eqT(mi, i % j))
13149 + end
13150 + end
13151 + end
13152 +end
13153 +assert(eqT(math.fmod(minint, minint), 0))
13154 +assert(eqT(math.fmod(maxint, maxint), 0))
13155 +assert(eqT(math.fmod(minint + 1, minint), minint + 1))
13156 +assert(eqT(math.fmod(maxint - 1, maxint), maxint - 1))
13157 +
13158 +checkerror("zero", math.fmod, 3, 0)
13159 +
13160 +
13161 +do -- testing max/min
13162 + checkerror("value expected", math.max)
13163 + checkerror("value expected", math.min)
13164 + assert(eqT(math.max(3), 3))
13165 + assert(eqT(math.max(3, 5, 9, 1), 9))
13166 + assert(math.max(maxint, 10e60) == 10e60)
13167 + assert(eqT(math.max(minint, minint + 1), minint + 1))
13168 + assert(eqT(math.min(3), 3))
13169 + assert(eqT(math.min(3, 5, 9, 1), 1))
13170 + assert(math.min(3.2, 5.9, -9.2, 1.1) == -9.2)
13171 + assert(math.min(1.9, 1.7, 1.72) == 1.7)
13172 + assert(math.min(-10e60, minint) == -10e60)
13173 + assert(eqT(math.min(maxint, maxint - 1), maxint - 1))
13174 + assert(eqT(math.min(maxint - 2, maxint, maxint - 1), maxint - 2))
13175 +end
13176 +-- testing implicit conversions
13177 +
13178 +local a,b = '10', '20'
13179 +assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20)
13180 +assert(a == '10' and b == '20')
13181 +
13182 +
13183 +do
13184 + print("testing -0 and NaN")
13185 + local mz <const> = -0.0
13186 + local z <const> = 0.0
13187 + assert(mz == z)
13188 + assert(1/mz < 0 and 0 < 1/z)
13189 + local a = {[mz] = 1}
13190 + assert(a[z] == 1 and a[mz] == 1)
13191 + a[z] = 2
13192 + assert(a[z] == 2 and a[mz] == 2)
13193 + local inf = math.huge * 2 + 1
13194 + local mz <const> = -1/inf
13195 + local z <const> = 1/inf
13196 + assert(mz == z)
13197 + assert(1/mz < 0 and 0 < 1/z)
13198 + local NaN <const> = inf - inf
13199 + assert(NaN ~= NaN)
13200 + assert(not (NaN < NaN))
13201 + assert(not (NaN <= NaN))
13202 + assert(not (NaN > NaN))
13203 + assert(not (NaN >= NaN))
13204 + assert(not (0 < NaN) and not (NaN < 0))
13205 + local NaN1 <const> = 0/0
13206 + assert(NaN ~= NaN1 and not (NaN <= NaN1) and not (NaN1 <= NaN))
13207 + local a = {}
13208 + assert(not pcall(rawset, a, NaN, 1))
13209 + assert(a[NaN] == undef)
13210 + a[1] = 1
13211 + assert(not pcall(rawset, a, NaN, 1))
13212 + assert(a[NaN] == undef)
13213 + -- strings with same binary representation as 0.0 (might create problems
13214 + -- for constant manipulation in the pre-compiler)
13215 + local a1, a2, a3, a4, a5 = 0, 0, "\0\0\0\0\0\0\0\0", 0, "\0\0\0\0\0\0\0\0"
13216 + assert(a1 == a2 and a2 == a4 and a1 ~= a3)
13217 + assert(a3 == a5)
13218 +end
13219 +
13220 +
13221 +print("testing 'math.random'")
13222 +
13223 +local random, max, min = math.random, math.max, math.min
13224 +
13225 +local function testnear (val, ref, tol)
13226 + return (math.abs(val - ref) < ref * tol)
13227 +end
13228 +
13229 +
13230 +-- low-level!! For the current implementation of random in Lua,
13231 +-- the first call after seed 1007 should return 0x7a7040a5a323c9d6
13232 +do
13233 + -- all computations should work with 32-bit integers
13234 + local h <const> = 0x7a7040a5 -- higher half
13235 + local l <const> = 0xa323c9d6 -- lower half
13236 +
13237 + math.randomseed(1007)
13238 + -- get the low 'intbits' of the 64-bit expected result
13239 + local res = (h << 32 | l) & ~(~0 << intbits)
13240 + assert(random(0) == res)
13241 +
13242 + math.randomseed(1007, 0)
13243 + -- using higher bits to generate random floats; (the '% 2^32' converts
13244 + -- 32-bit integers to floats as unsigned)
13245 + local res
13246 + if floatbits <= 32 then
13247 + -- get all bits from the higher half
13248 + res = (h >> (32 - floatbits)) % 2^32
13249 + else
13250 + -- get 32 bits from the higher half and the rest from the lower half
13251 + res = (h % 2^32) * 2^(floatbits - 32) + ((l >> (64 - floatbits)) % 2^32)
13252 + end
13253 + local rand = random()
13254 + assert(eq(rand, 0x0.7a7040a5a323c9d6, 2^-floatbits))
13255 + assert(rand * 2^floatbits == res)
13256 +end
13257 +
13258 +do
13259 + -- testing return of 'randomseed'
13260 + local x, y = math.randomseed()
13261 + local res = math.random(0)
13262 + x, y = math.randomseed(x, y) -- should repeat the state
13263 + assert(math.random(0) == res)
13264 + math.randomseed(x, y) -- again should repeat the state
13265 + assert(math.random(0) == res)
13266 + -- keep the random seed for following tests
13267 + print(string.format("random seeds: %d, %d", x, y))
13268 +end
13269 +
13270 +do -- test random for floats
13271 + local randbits = math.min(floatbits, 64) -- at most 64 random bits
13272 + local mult = 2^randbits -- to make random float into an integral
13273 + local counts = {} -- counts for bits
13274 + for i = 1, randbits do counts[i] = 0 end
13275 + local up = -math.huge
13276 + local low = math.huge
13277 + local rounds = 100 * randbits -- 100 times for each bit
13278 + local totalrounds = 0
13279 + ::doagain:: -- will repeat test until we get good statistics
13280 + for i = 0, rounds do
13281 + local t = random()
13282 + assert(0 <= t and t < 1)
13283 + up = max(up, t)
13284 + low = min(low, t)
13285 + assert(t * mult % 1 == 0) -- no extra bits
13286 + local bit = i % randbits -- bit to be tested
13287 + if (t * 2^bit) % 1 >= 0.5 then -- is bit set?
13288 + counts[bit + 1] = counts[bit + 1] + 1 -- increment its count
13289 + end
13290 + end
13291 + totalrounds = totalrounds + rounds
13292 + if not (eq(up, 1, 0.001) and eq(low, 0, 0.001)) then
13293 + goto doagain
13294 + end
13295 + -- all bit counts should be near 50%
13296 + local expected = (totalrounds / randbits / 2)
13297 + for i = 1, randbits do
13298 + if not testnear(counts[i], expected, 0.10) then
13299 + goto doagain
13300 + end
13301 + end
13302 + print(string.format("float random range in %d calls: [%f, %f]",
13303 + totalrounds, low, up))
13304 +end
13305 +
13306 +
13307 +do -- test random for full integers
13308 + local up = 0
13309 + local low = 0
13310 + local counts = {} -- counts for bits
13311 + for i = 1, intbits do counts[i] = 0 end
13312 + local rounds = 100 * intbits -- 100 times for each bit
13313 + local totalrounds = 0
13314 + ::doagain:: -- will repeat test until we get good statistics
13315 + for i = 0, rounds do
13316 + local t = random(0)
13317 + up = max(up, t)
13318 + low = min(low, t)
13319 + local bit = i % intbits -- bit to be tested
13320 + -- increment its count if it is set
13321 + counts[bit + 1] = counts[bit + 1] + ((t >> bit) & 1)
13322 + end
13323 + totalrounds = totalrounds + rounds
13324 + local lim = maxint >> 10
13325 + if not (maxint - up < lim and low - minint < lim) then
13326 + goto doagain
13327 + end
13328 + -- all bit counts should be near 50%
13329 + local expected = (totalrounds / intbits / 2)
13330 + for i = 1, intbits do
13331 + if not testnear(counts[i], expected, 0.10) then
13332 + goto doagain
13333 + end
13334 + end
13335 + print(string.format(
13336 + "integer random range in %d calls: [minint + %.0fppm, maxint - %.0fppm]",
13337 + totalrounds, (minint - low) / minint * 1e6,
13338 + (maxint - up) / maxint * 1e6))
13339 +end
13340 +
13341 +do
13342 + -- test distribution for a dice
13343 + local count = {0, 0, 0, 0, 0, 0}
13344 + local rep = 200
13345 + local totalrep = 0
13346 + ::doagain::
13347 + for i = 1, rep * 6 do
13348 + local r = random(6)
13349 + count[r] = count[r] + 1
13350 + end
13351 + totalrep = totalrep + rep
13352 + for i = 1, 6 do
13353 + if not testnear(count[i], totalrep, 0.05) then
13354 + goto doagain
13355 + end
13356 + end
13357 +end
13358 +
13359 +do
13360 + local function aux (x1, x2) -- test random for small intervals
13361 + local mark = {}; local count = 0 -- to check that all values appeared
13362 + while true do
13363 + local t = random(x1, x2)
13364 + assert(x1 <= t and t <= x2)
13365 + if not mark[t] then -- new value
13366 + mark[t] = true
13367 + count = count + 1
13368 + if count == x2 - x1 + 1 then -- all values appeared; OK
13369 + goto ok
13370 + end
13371 + end
13372 + end
13373 + ::ok::
13374 + end
13375 +
13376 + aux(-10,0)
13377 + aux(1, 6)
13378 + aux(1, 2)
13379 + aux(1, 13)
13380 + aux(1, 31)
13381 + aux(1, 32)
13382 + aux(1, 33)
13383 + aux(-10, 10)
13384 + aux(-10,-10) -- unit set
13385 + aux(minint, minint) -- unit set
13386 + aux(maxint, maxint) -- unit set
13387 + aux(minint, minint + 9)
13388 + aux(maxint - 3, maxint)
13389 +end
13390 +
13391 +do
13392 + local function aux(p1, p2) -- test random for large intervals
13393 + local max = minint
13394 + local min = maxint
13395 + local n = 100
13396 + local mark = {}; local count = 0 -- to count how many different values
13397 + ::doagain::
13398 + for _ = 1, n do
13399 + local t = random(p1, p2)
13400 + if not mark[t] then -- new value
13401 + assert(p1 <= t and t <= p2)
13402 + max = math.max(max, t)
13403 + min = math.min(min, t)
13404 + mark[t] = true
13405 + count = count + 1
13406 + end
13407 + end
13408 + -- at least 80% of values are different
13409 + if not (count >= n * 0.8) then
13410 + goto doagain
13411 + end
13412 + -- min and max not too far from formal min and max
13413 + local diff = (p2 - p1) >> 4
13414 + if not (min < p1 + diff and max > p2 - diff) then
13415 + goto doagain
13416 + end
13417 + end
13418 + aux(0, maxint)
13419 + aux(1, maxint)
13420 + aux(3, maxint // 3)
13421 + aux(minint, -1)
13422 + aux(minint // 2, maxint // 2)
13423 + aux(minint, maxint)
13424 + aux(minint + 1, maxint)
13425 + aux(minint, maxint - 1)
13426 + aux(0, 1 << (intbits - 5))
13427 +end
13428 +
13429 +
13430 +assert(not pcall(random, 1, 2, 3)) -- too many arguments
13431 +
13432 +-- empty interval
13433 +assert(not pcall(random, minint + 1, minint))
13434 +assert(not pcall(random, maxint, maxint - 1))
13435 +assert(not pcall(random, maxint, minint))
13436 +
13437 +
13438 +
13439 +print('OK')
13440
13441 diff --git a/tests/nextvar.lua b/tests/nextvar.lua
13442 new file mode 100644
13443 index 0000000..9e23e57
13444 --- /dev/null
13445 +++ b/tests/nextvar.lua
13446 @@ -0,0 +1,805 @@
13447 +-- $Id: testes/nextvar.lua $
13448 +-- See Copyright Notice in file all.lua
13449 +
13450 +print('testing tables, next, and for')
13451 +
13452 +local function checkerror (msg, f, ...)
13453 + local s, err = pcall(f, ...)
13454 + assert(not s and string.find(err, msg))
13455 +end
13456 +
13457 +
13458 +local a = {}
13459 +
13460 +-- make sure table has lots of space in hash part
13461 +for i=1,100 do a[i.."+"] = true end
13462 +for i=1,100 do a[i.."+"] = undef end
13463 +-- fill hash part with numeric indices testing size operator
13464 +for i=1,100 do
13465 + a[i] = true
13466 + assert(#a == i)
13467 +end
13468 +
13469 +-- testing ipairs
13470 +local x = 0
13471 +for k,v in ipairs{10,20,30;x=12} do
13472 + x = x + 1
13473 + assert(k == x and v == x * 10)
13474 +end
13475 +
13476 +for _ in ipairs{x=12, y=24} do assert(nil) end
13477 +
13478 +-- test for 'false' x ipair
13479 +x = false
13480 +local i = 0
13481 +for k,v in ipairs{true,false,true,false} do
13482 + i = i + 1
13483 + x = not x
13484 + assert(x == v)
13485 +end
13486 +assert(i == 4)
13487 +
13488 +-- iterator function is always the same
13489 +assert(type(ipairs{}) == 'function' and ipairs{} == ipairs{})
13490 +
13491 +
13492 +do -- overflow (must wrap-around)
13493 + local f = ipairs{}
13494 + local k, v = f({[math.mininteger] = 10}, math.maxinteger)
13495 + assert(k == math.mininteger and v == 10)
13496 + k, v = f({[math.mininteger] = 10}, k)
13497 + assert(k == nil)
13498 +end
13499 +
13500 +if not T then
13501 + (Message or print)
13502 + ('\n >>> testC not active: skipping tests for table sizes <<<\n')
13503 +else --[
13504 +-- testing table sizes
13505 +
13506 +
13507 +local function mp2 (n) -- minimum power of 2 >= n
13508 + local mp = 2^math.ceil(math.log(n, 2))
13509 + assert(n == 0 or (mp/2 < n and n <= mp))
13510 + return mp
13511 +end
13512 +
13513 +
13514 +local function check (t, na, nh)
13515 + local a, h = T.querytab(t)
13516 + if a ~= na or h ~= nh then
13517 + print(na, nh, a, h)
13518 + assert(nil)
13519 + end
13520 +end
13521 +
13522 +
13523 +-- testing C library sizes
13524 +do
13525 + local s = 0
13526 + for _ in pairs(math) do s = s + 1 end
13527 + check(math, 0, mp2(s))
13528 +end
13529 +
13530 +
13531 +-- testing constructor sizes
13532 +local sizes = {0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17,
13533 + 30, 31, 32, 33, 34, 254, 255, 256, 500, 1000}
13534 +
13535 +for _, sa in ipairs(sizes) do -- 'sa' is size of the array part
13536 + local arr = {"return {"}
13537 + for i = 1, sa do arr[1 + i] = "1," end -- build array part
13538 + for _, sh in ipairs(sizes) do -- 'sh' is size of the hash part
13539 + for j = 1, sh do -- build hash part
13540 + arr[1 + sa + j] = string.format('k%x=%d,', j, j)
13541 + end
13542 + arr[1 + sa + sh + 1] = "}"
13543 + local prog = table.concat(arr)
13544 + local f = assert(load(prog))
13545 + collectgarbage("stop")
13546 + f() -- call once to ensure stack space
13547 + -- make sure table is not resized after being created
13548 + if sa == 0 or sh == 0 then
13549 + T.alloccount(2); -- header + array or hash part
13550 + else
13551 + T.alloccount(3); -- header + array part + hash part
13552 + end
13553 + local t = f()
13554 + T.alloccount();
13555 + collectgarbage("restart")
13556 + assert(#t == sa)
13557 + check(t, sa, mp2(sh))
13558 + end
13559 +end
13560 +
13561 +
13562 +-- tests with unknown number of elements
13563 +local a = {}
13564 +for i=1,sizes[#sizes] do a[i] = i end -- build auxiliary table
13565 +for k in ipairs(sizes) do
13566 + local t = {table.unpack(a,1,k)}
13567 + assert(#t == k)
13568 + check(t, k, 0)
13569 + t = {1,2,3,table.unpack(a,1,k)}
13570 + check(t, k+3, 0)
13571 + assert(#t == k + 3)
13572 +end
13573 +
13574 +
13575 +-- testing tables dynamically built
13576 +local lim = 130
13577 +local a = {}; a[2] = 1; check(a, 0, 1)
13578 +a = {}; a[0] = 1; check(a, 0, 1); a[2] = 1; check(a, 0, 2)
13579 +a = {}; a[0] = 1; a[1] = 1; check(a, 1, 1)
13580 +a = {}
13581 +for i = 1,lim do
13582 + a[i] = 1
13583 + assert(#a == i)
13584 + check(a, mp2(i), 0)
13585 +end
13586 +
13587 +a = {}
13588 +for i = 1,lim do
13589 + a['a'..i] = 1
13590 + assert(#a == 0)
13591 + check(a, 0, mp2(i))
13592 +end
13593 +
13594 +a = {}
13595 +for i=1,16 do a[i] = i end
13596 +check(a, 16, 0)
13597 +do
13598 + for i=1,11 do a[i] = undef end
13599 + for i=30,50 do a[i] = true; a[i] = undef end -- force a rehash (?)
13600 + check(a, 0, 8) -- 5 elements in the table
13601 + a[10] = 1
13602 + for i=30,50 do a[i] = true; a[i] = undef end -- force a rehash (?)
13603 + check(a, 0, 8) -- only 6 elements in the table
13604 + for i=1,14 do a[i] = true; a[i] = undef end
13605 + for i=18,50 do a[i] = true; a[i] = undef end -- force a rehash (?)
13606 + check(a, 0, 4) -- only 2 elements ([15] and [16])
13607 +end
13608 +
13609 +-- reverse filling
13610 +for i=1,lim do
13611 + local a = {}
13612 + for i=i,1,-1 do a[i] = i end -- fill in reverse
13613 + check(a, mp2(i), 0)
13614 +end
13615 +
13616 +-- size tests for vararg
13617 +lim = 35
13618 +function foo (n, ...)
13619 + local arg = {...}
13620 + check(arg, n, 0)
13621 + assert(select('#', ...) == n)
13622 + arg[n+1] = true
13623 + check(arg, mp2(n+1), 0)
13624 + arg.x = true
13625 + check(arg, mp2(n+1), 1)
13626 +end
13627 +local a = {}
13628 +for i=1,lim do a[i] = true; foo(i, table.unpack(a)) end
13629 +
13630 +
13631 +-- Table length with limit smaller than maximum value at array
13632 +local a = {}
13633 +for i = 1,64 do a[i] = true end -- make its array size 64
13634 +for i = 1,64 do a[i] = nil end -- erase all elements
13635 +assert(T.querytab(a) == 64) -- array part has 64 elements
13636 +a[32] = true; a[48] = true; -- binary search will find these ones
13637 +a[51] = true -- binary search will miss this one
13638 +assert(#a == 48) -- this will set the limit
13639 +assert(select(4, T.querytab(a)) == 48) -- this is the limit now
13640 +a[50] = true -- this will set a new limit
13641 +assert(select(4, T.querytab(a)) == 50) -- this is the limit now
13642 +-- but the size is larger (and still inside the array part)
13643 +assert(#a == 51)
13644 +
13645 +end --]
13646 +
13647 +
13648 +-- test size operation on tables with nils
13649 +assert(#{} == 0)
13650 +assert(#{nil} == 0)
13651 +assert(#{nil, nil} == 0)
13652 +assert(#{nil, nil, nil} == 0)
13653 +assert(#{nil, nil, nil, nil} == 0)
13654 +assert(#{1, 2, 3, nil, nil} == 3)
13655 +print'+'
13656 +
13657 +
13658 +local nofind = {}
13659 +
13660 +a,b,c = 1,2,3
13661 +a,b,c = nil
13662 +
13663 +
13664 +-- next uses always the same iteraction function
13665 +assert(next{} == next{})
13666 +
13667 +local function find (name)
13668 + local n,v
13669 + while 1 do
13670 + n,v = next(_G, n)
13671 + if not n then return nofind end
13672 + assert(_G[n] ~= undef)
13673 + if n == name then return v end
13674 + end
13675 +end
13676 +
13677 +local function find1 (name)
13678 + for n,v in pairs(_G) do
13679 + if n==name then return v end
13680 + end
13681 + return nil -- not found
13682 +end
13683 +
13684 +
13685 +assert(print==find("print") and print == find1("print"))
13686 +assert(_G["print"]==find("print"))
13687 +assert(assert==find1("assert"))
13688 +assert(nofind==find("return"))
13689 +assert(not find1("return"))
13690 +_G["ret" .. "urn"] = undef
13691 +assert(nofind==find("return"))
13692 +_G["xxx"] = 1
13693 +assert(xxx==find("xxx"))
13694 +
13695 +-- invalid key to 'next'
13696 +checkerror("invalid key", next, {10,20}, 3)
13697 +
13698 +-- both 'pairs' and 'ipairs' need an argument
13699 +checkerror("bad argument", pairs)
13700 +checkerror("bad argument", ipairs)
13701 +
13702 +print('+')
13703 +
13704 +a = {}
13705 +for i=0,10000 do
13706 + if math.fmod(i,10) ~= 0 then
13707 + a['x'..i] = i
13708 + end
13709 +end
13710 +
13711 +n = {n=0}
13712 +for i,v in pairs(a) do
13713 + n.n = n.n+1
13714 + assert(i and v and a[i] == v)
13715 +end
13716 +assert(n.n == 9000)
13717 +a = nil
13718 +
13719 +do -- clear global table
13720 + local a = {}
13721 + for n,v in pairs(_G) do a[n]=v end
13722 + for n,v in pairs(a) do
13723 + if not package.loaded[n] and type(v) ~= "function" and
13724 + not string.find(n, "^[%u_]") then
13725 + _G[n] = undef
13726 + end
13727 + collectgarbage()
13728 + end
13729 +end
13730 +
13731 +
13732 +--
13733 +
13734 +local function checknext (a)
13735 + local b = {}
13736 + do local k,v = next(a); while k do b[k] = v; k,v = next(a,k) end end
13737 + for k,v in pairs(b) do assert(a[k] == v) end
13738 + for k,v in pairs(a) do assert(b[k] == v) end
13739 +end
13740 +
13741 +checknext{1,x=1,y=2,z=3}
13742 +checknext{1,2,x=1,y=2,z=3}
13743 +checknext{1,2,3,x=1,y=2,z=3}
13744 +checknext{1,2,3,4,x=1,y=2,z=3}
13745 +checknext{1,2,3,4,5,x=1,y=2,z=3}
13746 +
13747 +assert(#{} == 0)
13748 +assert(#{[-1] = 2} == 0)
13749 +for i=0,40 do
13750 + local a = {}
13751 + for j=1,i do a[j]=j end
13752 + assert(#a == i)
13753 +end
13754 +
13755 +-- 'maxn' is now deprecated, but it is easily defined in Lua
13756 +function table.maxn (t)
13757 + local max = 0
13758 + for k in pairs(t) do
13759 + max = (type(k) == 'number') and math.max(max, k) or max
13760 + end
13761 + return max
13762 +end
13763 +
13764 +assert(table.maxn{} == 0)
13765 +assert(table.maxn{["1000"] = true} == 0)
13766 +assert(table.maxn{["1000"] = true, [24.5] = 3} == 24.5)
13767 +assert(table.maxn{[1000] = true} == 1000)
13768 +assert(table.maxn{[10] = true, [100*math.pi] = print} == 100*math.pi)
13769 +
13770 +table.maxn = nil
13771 +
13772 +-- int overflow
13773 +a = {}
13774 +for i=0,50 do a[2^i] = true end
13775 +assert(a[#a])
13776 +
13777 +print('+')
13778 +
13779 +
13780 +do -- testing 'next' with all kinds of keys
13781 + local a = {
13782 + [1] = 1, -- integer
13783 + [1.1] = 2, -- float
13784 + ['x'] = 3, -- short string
13785 + [string.rep('x', 1000)] = 4, -- long string
13786 + [print] = 5, -- C function
13787 + [checkerror] = 6, -- Lua function
13788 + [coroutine.running()] = 7, -- thread
13789 + [true] = 8, -- boolean
13790 + [io.stdin] = 9, -- userdata
13791 + [{}] = 10, -- table
13792 + }
13793 + local b = {}; for i = 1, 10 do b[i] = true end
13794 + for k, v in pairs(a) do
13795 + assert(b[v]); b[v] = undef
13796 + end
13797 + assert(next(b) == nil) -- 'b' now is empty
13798 +end
13799 +
13800 +
13801 +-- erasing values
13802 +local t = {[{1}] = 1, [{2}] = 2, [string.rep("x ", 4)] = 3,
13803 + [100.3] = 4, [4] = 5}
13804 +
13805 +local n = 0
13806 +for k, v in pairs( t ) do
13807 + n = n+1
13808 + assert(t[k] == v)
13809 + t[k] = undef
13810 + collectgarbage()
13811 + assert(t[k] == undef)
13812 +end
13813 +assert(n == 5)
13814 +
13815 +
13816 +do
13817 + print("testing next x GC of deleted keys")
13818 + -- bug in 5.4.1
13819 + local co = coroutine.wrap(function (t)
13820 + for k, v in pairs(t) do
13821 + local k1 = next(t) -- all previous keys were deleted
13822 + assert(k == k1) -- current key is the first in the table
13823 + t[k] = nil
13824 + local expected = (type(k) == "table" and k[1] or
13825 + type(k) == "function" and k() or
13826 + string.sub(k, 1, 1))
13827 + assert(expected == v)
13828 + coroutine.yield(v)
13829 + end
13830 + end)
13831 + local t = {}
13832 + t[{1}] = 1 -- add several unanchored, collectable keys
13833 + t[{2}] = 2
13834 + t[string.rep("a", 50)] = "a" -- long string
13835 + t[string.rep("b", 50)] = "b"
13836 + t[{3}] = 3
13837 + t[string.rep("c", 10)] = "c" -- short string
13838 + t[function () return 10 end] = 10
13839 + local count = 7
13840 + while co(t) do
13841 + collectgarbage("collect") -- collect dead keys
13842 + count = count - 1
13843 + end
13844 + assert(count == 0 and next(t) == nil) -- traversed the whole table
13845 +end
13846 +
13847 +
13848 +local function test (a)
13849 + assert(not pcall(table.insert, a, 2, 20));
13850 + table.insert(a, 10); table.insert(a, 2, 20);
13851 + table.insert(a, 1, -1); table.insert(a, 40);
13852 + table.insert(a, #a+1, 50)
13853 + table.insert(a, 2, -2)
13854 + assert(a[2] ~= undef)
13855 + assert(a["2"] == undef)
13856 + assert(not pcall(table.insert, a, 0, 20));
13857 + assert(not pcall(table.insert, a, #a + 2, 20));
13858 + assert(table.remove(a,1) == -1)
13859 + assert(table.remove(a,1) == -2)
13860 + assert(table.remove(a,1) == 10)
13861 + assert(table.remove(a,1) == 20)
13862 + assert(table.remove(a,1) == 40)
13863 + assert(table.remove(a,1) == 50)
13864 + assert(table.remove(a,1) == nil)
13865 + assert(table.remove(a) == nil)
13866 + assert(table.remove(a, #a) == nil)
13867 +end
13868 +
13869 +a = {n=0, [-7] = "ban"}
13870 +test(a)
13871 +assert(a.n == 0 and a[-7] == "ban")
13872 +
13873 +a = {[-7] = "ban"};
13874 +test(a)
13875 +assert(a.n == nil and #a == 0 and a[-7] == "ban")
13876 +
13877 +a = {[-1] = "ban"}
13878 +test(a)
13879 +assert(#a == 0 and table.remove(a) == nil and a[-1] == "ban")
13880 +
13881 +a = {[0] = "ban"}
13882 +assert(#a == 0 and table.remove(a) == "ban" and a[0] == undef)
13883 +
13884 +table.insert(a, 1, 10); table.insert(a, 1, 20); table.insert(a, 1, -1)
13885 +assert(table.remove(a) == 10)
13886 +assert(table.remove(a) == 20)
13887 +assert(table.remove(a) == -1)
13888 +assert(table.remove(a) == nil)
13889 +
13890 +a = {'c', 'd'}
13891 +table.insert(a, 3, 'a')
13892 +table.insert(a, 'b')
13893 +assert(table.remove(a, 1) == 'c')
13894 +assert(table.remove(a, 1) == 'd')
13895 +assert(table.remove(a, 1) == 'a')
13896 +assert(table.remove(a, 1) == 'b')
13897 +assert(table.remove(a, 1) == nil)
13898 +assert(#a == 0 and a.n == nil)
13899 +
13900 +a = {10,20,30,40}
13901 +assert(table.remove(a, #a + 1) == nil)
13902 +assert(not pcall(table.remove, a, 0))
13903 +assert(a[#a] == 40)
13904 +assert(table.remove(a, #a) == 40)
13905 +assert(a[#a] == 30)
13906 +assert(table.remove(a, 2) == 20)
13907 +assert(a[#a] == 30 and #a == 2)
13908 +
13909 +do -- testing table library with metamethods
13910 + local function test (proxy, t)
13911 + for i = 1, 10 do
13912 + table.insert(proxy, 1, i)
13913 + end
13914 + assert(#proxy == 10 and #t == 10 and proxy[1] ~= undef)
13915 + for i = 1, 10 do
13916 + assert(t[i] == 11 - i)
13917 + end
13918 + table.sort(proxy)
13919 + for i = 1, 10 do
13920 + assert(t[i] == i and proxy[i] == i)
13921 + end
13922 + assert(table.concat(proxy, ",") == "1,2,3,4,5,6,7,8,9,10")
13923 + for i = 1, 8 do
13924 + assert(table.remove(proxy, 1) == i)
13925 + end
13926 + assert(#proxy == 2 and #t == 2)
13927 + local a, b, c = table.unpack(proxy)
13928 + assert(a == 9 and b == 10 and c == nil)
13929 + end
13930 +
13931 + -- all virtual
13932 + local t = {}
13933 + local proxy = setmetatable({}, {
13934 + __len = function () return #t end,
13935 + __index = t,
13936 + __newindex = t,
13937 + })
13938 + test(proxy, t)
13939 +
13940 + -- only __newindex
13941 + local count = 0
13942 + t = setmetatable({}, {
13943 + __newindex = function (t,k,v) count = count + 1; rawset(t,k,v) end})
13944 + test(t, t)
13945 + assert(count == 10) -- after first 10, all other sets are not new
13946 +
13947 + -- no __newindex
13948 + t = setmetatable({}, {
13949 + __index = function (_,k) return k + 1 end,
13950 + __len = function (_) return 5 end})
13951 + assert(table.concat(t, ";") == "2;3;4;5;6")
13952 +
13953 +end
13954 +
13955 +
13956 +do -- testing overflow in table.insert (must wrap-around)
13957 +
13958 + local t = setmetatable({},
13959 + {__len = function () return math.maxinteger end})
13960 + table.insert(t, 20)
13961 + local k, v = next(t)
13962 + assert(k == math.mininteger and v == 20)
13963 +end
13964 +
13965 +if not T then
13966 + (Message or print)
13967 + ('\n >>> testC not active: skipping tests for table library on non-tables <<<\n')
13968 +else --[
13969 + local debug = require'debug'
13970 + local tab = {10, 20, 30}
13971 + local mt = {}
13972 + local u = T.newuserdata(0)
13973 + checkerror("table expected", table.insert, u, 40)
13974 + checkerror("table expected", table.remove, u)
13975 + debug.setmetatable(u, mt)
13976 + checkerror("table expected", table.insert, u, 40)
13977 + checkerror("table expected", table.remove, u)
13978 + mt.__index = tab
13979 + checkerror("table expected", table.insert, u, 40)
13980 + checkerror("table expected", table.remove, u)
13981 + mt.__newindex = tab
13982 + checkerror("table expected", table.insert, u, 40)
13983 + checkerror("table expected", table.remove, u)
13984 + mt.__len = function () return #tab end
13985 + table.insert(u, 40)
13986 + assert(#u == 4 and #tab == 4 and u[4] == 40 and tab[4] == 40)
13987 + assert(table.remove(u) == 40)
13988 + table.insert(u, 1, 50)
13989 + assert(#u == 4 and #tab == 4 and u[4] == 30 and tab[1] == 50)
13990 +
13991 + mt.__newindex = nil
13992 + mt.__len = nil
13993 + local tab2 = {}
13994 + local u2 = T.newuserdata(0)
13995 + debug.setmetatable(u2, {__newindex = function (_, k, v) tab2[k] = v end})
13996 + table.move(u, 1, 4, 1, u2)
13997 + assert(#tab2 == 4 and tab2[1] == tab[1] and tab2[4] == tab[4])
13998 +
13999 +end -- ]
14000 +
14001 +print('+')
14002 +
14003 +a = {}
14004 +for i=1,1000 do
14005 + a[i] = i; a[i - 1] = undef
14006 +end
14007 +assert(next(a,nil) == 1000 and next(a,1000) == nil)
14008 +
14009 +assert(next({}) == nil)
14010 +assert(next({}, nil) == nil)
14011 +
14012 +for a,b in pairs{} do error"not here" end
14013 +for i=1,0 do error'not here' end
14014 +for i=0,1,-1 do error'not here' end
14015 +a = nil; for i=1,1 do assert(not a); a=1 end; assert(a)
14016 +a = nil; for i=1,1,-1 do assert(not a); a=1 end; assert(a)
14017 +
14018 +do
14019 + print("testing floats in numeric for")
14020 + local a
14021 + -- integer count
14022 + a = 0; for i=1, 1, 1 do a=a+1 end; assert(a==1)
14023 + a = 0; for i=10000, 1e4, -1 do a=a+1 end; assert(a==1)
14024 + a = 0; for i=1, 0.99999, 1 do a=a+1 end; assert(a==0)
14025 + a = 0; for i=9999, 1e4, -1 do a=a+1 end; assert(a==0)
14026 + a = 0; for i=1, 0.99999, -1 do a=a+1 end; assert(a==1)
14027 +
14028 + -- float count
14029 + a = 0; for i=0, 0.999999999, 0.1 do a=a+1 end; assert(a==10)
14030 + a = 0; for i=1.0, 1, 1 do a=a+1 end; assert(a==1)
14031 + a = 0; for i=-1.5, -1.5, 1 do a=a+1 end; assert(a==1)
14032 + a = 0; for i=1e6, 1e6, -1 do a=a+1 end; assert(a==1)
14033 + a = 0; for i=1.0, 0.99999, 1 do a=a+1 end; assert(a==0)
14034 + a = 0; for i=99999, 1e5, -1.0 do a=a+1 end; assert(a==0)
14035 + a = 0; for i=1.0, 0.99999, -1 do a=a+1 end; assert(a==1)
14036 +end
14037 +
14038 +do -- changing the control variable
14039 + local a
14040 + a = 0; for i = 1, 10 do a = a + 1; i = "x" end; assert(a == 10)
14041 + a = 0; for i = 10.0, 1, -1 do a = a + 1; i = "x" end; assert(a == 10)
14042 +end
14043 +
14044 +-- conversion
14045 +a = 0; for i="10","1","-2" do a=a+1 end; assert(a==5)
14046 +
14047 +do -- checking types
14048 + local c
14049 + local function checkfloat (i)
14050 + assert(math.type(i) == "float")
14051 + c = c + 1
14052 + end
14053 +
14054 + c = 0; for i = 1.0, 10 do checkfloat(i) end
14055 + assert(c == 10)
14056 +
14057 + c = 0; for i = -1, -10, -1.0 do checkfloat(i) end
14058 + assert(c == 10)
14059 +
14060 + local function checkint (i)
14061 + assert(math.type(i) == "integer")
14062 + c = c + 1
14063 + end
14064 +
14065 + local m = math.maxinteger
14066 + c = 0; for i = m, m - 10, -1 do checkint(i) end
14067 + assert(c == 11)
14068 +
14069 + c = 0; for i = 1, 10.9 do checkint(i) end
14070 + assert(c == 10)
14071 +
14072 + c = 0; for i = 10, 0.001, -1 do checkint(i) end
14073 + assert(c == 10)
14074 +
14075 + c = 0; for i = 1, "10.8" do checkint(i) end
14076 + assert(c == 10)
14077 +
14078 + c = 0; for i = 9, "3.4", -1 do checkint(i) end
14079 + assert(c == 6)
14080 +
14081 + c = 0; for i = 0, " -3.4 ", -1 do checkint(i) end
14082 + assert(c == 4)
14083 +
14084 + c = 0; for i = 100, "96.3", -2 do checkint(i) end
14085 + assert(c == 2)
14086 +
14087 + c = 0; for i = 1, math.huge do if i > 10 then break end; checkint(i) end
14088 + assert(c == 10)
14089 +
14090 + c = 0; for i = -1, -math.huge, -1 do
14091 + if i < -10 then break end; checkint(i)
14092 + end
14093 + assert(c == 10)
14094 +
14095 +
14096 + for i = math.mininteger, -10e100 do assert(false) end
14097 + for i = math.maxinteger, 10e100, -1 do assert(false) end
14098 +
14099 +end
14100 +
14101 +
14102 +do -- testing other strange cases for numeric 'for'
14103 +
14104 + local function checkfor (from, to, step, t)
14105 + local c = 0
14106 + for i = from, to, step do
14107 + c = c + 1
14108 + assert(i == t[c])
14109 + end
14110 + assert(c == #t)
14111 + end
14112 +
14113 + local maxi = math.maxinteger
14114 + local mini = math.mininteger
14115 +
14116 + checkfor(mini, maxi, maxi, {mini, -1, maxi - 1})
14117 +
14118 + checkfor(mini, math.huge, maxi, {mini, -1, maxi - 1})
14119 +
14120 + checkfor(maxi, mini, mini, {maxi, -1})
14121 +
14122 + checkfor(maxi, mini, -maxi, {maxi, 0, -maxi})
14123 +
14124 + checkfor(maxi, -math.huge, mini, {maxi, -1})
14125 +
14126 + checkfor(maxi, mini, 1, {})
14127 + checkfor(mini, maxi, -1, {})
14128 +
14129 + checkfor(maxi - 6, maxi, 3, {maxi - 6, maxi - 3, maxi})
14130 + checkfor(mini + 4, mini, -2, {mini + 4, mini + 2, mini})
14131 +
14132 + local step = maxi // 10
14133 + local c = mini
14134 + for i = mini, maxi, step do
14135 + assert(i == c)
14136 + c = c + step
14137 + end
14138 +
14139 + c = maxi
14140 + for i = maxi, mini, -step do
14141 + assert(i == c)
14142 + c = c - step
14143 + end
14144 +
14145 + checkfor(maxi, maxi, maxi, {maxi})
14146 + checkfor(maxi, maxi, mini, {maxi})
14147 + checkfor(mini, mini, maxi, {mini})
14148 + checkfor(mini, mini, mini, {mini})
14149 +end
14150 +
14151 +
14152 +checkerror("'for' step is zero", function ()
14153 + for i = 1, 10, 0 do end
14154 +end)
14155 +
14156 +checkerror("'for' step is zero", function ()
14157 + for i = 1, -10, 0 do end
14158 +end)
14159 +
14160 +checkerror("'for' step is zero", function ()
14161 + for i = 1.0, -10, 0.0 do end
14162 +end)
14163 +
14164 +collectgarbage()
14165 +
14166 +
14167 +-- testing generic 'for'
14168 +
14169 +local function f (n, p)
14170 + local t = {}; for i=1,p do t[i] = i*10 end
14171 + return function (_, n, ...)
14172 + assert(select("#", ...) == 0) -- no extra arguments
14173 + if n > 0 then
14174 + n = n-1
14175 + return n, table.unpack(t)
14176 + end
14177 + end, nil, n
14178 +end
14179 +
14180 +local x = 0
14181 +for n,a,b,c,d in f(5,3) do
14182 + x = x+1
14183 + assert(a == 10 and b == 20 and c == 30 and d == nil)
14184 +end
14185 +assert(x == 5)
14186 +
14187 +
14188 +
14189 +-- testing __pairs and __ipairs metamethod
14190 +a = {}
14191 +do
14192 + local x,y,z = pairs(a)
14193 + assert(type(x) == 'function' and y == a and z == nil)
14194 +end
14195 +
14196 +local function foo (e,i)
14197 + assert(e == a)
14198 + if i <= 10 then return i+1, i+2 end
14199 +end
14200 +
14201 +local function foo1 (e,i)
14202 + i = i + 1
14203 + assert(e == a)
14204 + if i <= e.n then return i,a[i] end
14205 +end
14206 +
14207 +setmetatable(a, {__pairs = function (x) return foo, x, 0 end})
14208 +
14209 +local i = 0
14210 +for k,v in pairs(a) do
14211 + i = i + 1
14212 + assert(k == i and v == k+1)
14213 +end
14214 +
14215 +a.n = 5
14216 +a[3] = 30
14217 +
14218 +-- testing ipairs with metamethods
14219 +a = {n=10}
14220 +setmetatable(a, { __index = function (t,k)
14221 + if k <= t.n then return k * 10 end
14222 + end})
14223 +i = 0
14224 +for k,v in ipairs(a) do
14225 + i = i + 1
14226 + assert(k == i and v == i * 10)
14227 +end
14228 +assert(i == a.n)
14229 +
14230 +
14231 +-- testing yield inside __pairs
14232 +do
14233 + local t = setmetatable({10, 20, 30}, {__pairs = function (t)
14234 + local inc = coroutine.yield()
14235 + return function (t, i)
14236 + if i > 1 then return i - inc, t[i - inc] else return nil end
14237 + end, t, #t + 1
14238 + end})
14239 +
14240 + local res = {}
14241 + local co = coroutine.wrap(function ()
14242 + for i,p in pairs(t) do res[#res + 1] = p end
14243 + end)
14244 +
14245 + co() -- start coroutine
14246 + co(1) -- continue after yield
14247 + assert(res[1] == 30 and res[2] == 20 and res[3] == 10 and #res == 3)
14248 +
14249 +end
14250 +
14251 +print"OK"
14252
14253 diff --git a/tests/pm.lua b/tests/pm.lua
14254 new file mode 100644
14255 index 0000000..94bb63c
14256 --- /dev/null
14257 +++ b/tests/pm.lua
14258 @@ -0,0 +1,421 @@
14259 +-- $Id: testes/pm.lua $
14260 +-- See Copyright Notice in file all.lua
14261 +
14262 +print('testing pattern matching')
14263 +
14264 +local function checkerror (msg, f, ...)
14265 + local s, err = pcall(f, ...)
14266 + assert(not s and string.find(err, msg))
14267 +end
14268 +
14269 +
14270 +function f(s, p)
14271 + local i,e = string.find(s, p)
14272 + if i then return string.sub(s, i, e) end
14273 +end
14274 +
14275 +a,b = string.find('', '') -- empty patterns are tricky
14276 +assert(a == 1 and b == 0);
14277 +a,b = string.find('alo', '')
14278 +assert(a == 1 and b == 0)
14279 +a,b = string.find('a\0o a\0o a\0o', 'a', 1) -- first position
14280 +assert(a == 1 and b == 1)
14281 +a,b = string.find('a\0o a\0o a\0o', 'a\0o', 2) -- starts in the midle
14282 +assert(a == 5 and b == 7)
14283 +a,b = string.find('a\0o a\0o a\0o', 'a\0o', 9) -- starts in the midle
14284 +assert(a == 9 and b == 11)
14285 +a,b = string.find('a\0a\0a\0a\0\0ab', '\0ab', 2); -- finds at the end
14286 +assert(a == 9 and b == 11);
14287 +a,b = string.find('a\0a\0a\0a\0\0ab', 'b') -- last position
14288 +assert(a == 11 and b == 11)
14289 +assert(not string.find('a\0a\0a\0a\0\0ab', 'b\0')) -- check ending
14290 +assert(not string.find('', '\0'))
14291 +assert(string.find('alo123alo', '12') == 4)
14292 +assert(not string.find('alo123alo', '^12'))
14293 +
14294 +assert(string.match("aaab", ".*b") == "aaab")
14295 +assert(string.match("aaa", ".*a") == "aaa")
14296 +assert(string.match("b", ".*b") == "b")
14297 +
14298 +assert(string.match("aaab", ".+b") == "aaab")
14299 +assert(string.match("aaa", ".+a") == "aaa")
14300 +assert(not string.match("b", ".+b"))
14301 +
14302 +assert(string.match("aaab", ".?b") == "ab")
14303 +assert(string.match("aaa", ".?a") == "aa")
14304 +assert(string.match("b", ".?b") == "b")
14305 +
14306 +assert(f('aloALO', '%l*') == 'alo')
14307 +assert(f('aLo_ALO', '%a*') == 'aLo')
14308 +
14309 +assert(f(" \n\r*&\n\r xuxu \n\n", "%g%g%g+") == "xuxu")
14310 +
14311 +assert(f('aaab', 'a*') == 'aaa');
14312 +assert(f('aaa', '^.*$') == 'aaa');
14313 +assert(f('aaa', 'b*') == '');
14314 +assert(f('aaa', 'ab*a') == 'aa')
14315 +assert(f('aba', 'ab*a') == 'aba')
14316 +assert(f('aaab', 'a+') == 'aaa')
14317 +assert(f('aaa', '^.+$') == 'aaa')
14318 +assert(not f('aaa', 'b+'))
14319 +assert(not f('aaa', 'ab+a'))
14320 +assert(f('aba', 'ab+a') == 'aba')
14321 +assert(f('a$a', '.$') == 'a')
14322 +assert(f('a$a', '.%$') == 'a$')
14323 +assert(f('a$a', '.$.') == 'a$a')
14324 +assert(not f('a$a', '$$'))
14325 +assert(not f('a$b', 'a$'))
14326 +assert(f('a$a', '$') == '')
14327 +assert(f('', 'b*') == '')
14328 +assert(not f('aaa', 'bb*'))
14329 +assert(f('aaab', 'a-') == '')
14330 +assert(f('aaa', '^.-$') == 'aaa')
14331 +assert(f('aabaaabaaabaaaba', 'b.*b') == 'baaabaaabaaab')
14332 +assert(f('aabaaabaaabaaaba', 'b.-b') == 'baaab')
14333 +assert(f('alo xo', '.o$') == 'xo')
14334 +assert(f(' \n isto é assim', '%S%S*') == 'isto')
14335 +assert(f(' \n isto é assim', '%S*$') == 'assim')
14336 +assert(f(' \n isto é assim', '[a-z]*$') == 'assim')
14337 +assert(f('um caracter ? extra', '[^%sa-z]') == '?')
14338 +assert(f('', 'a?') == '')
14339 +assert(f('á', 'á?') == 'á')
14340 +assert(f('ábl', 'á?b?l?') == 'ábl')
14341 +assert(f(' ábl', 'á?b?l?') == '')
14342 +assert(f('aa', '^aa?a?a') == 'aa')
14343 +assert(f(']]]áb', '[^]]') == 'á')
14344 +assert(f("0alo alo", "%x*") == "0a")
14345 +assert(f("alo alo", "%C+") == "alo alo")
14346 +print('+')
14347 +
14348 +
14349 +function f1(s, p)
14350 + p = string.gsub(p, "%%([0-9])", function (s)
14351 + return "%" .. (tonumber(s)+1)
14352 + end)
14353 + p = string.gsub(p, "^(^?)", "%1()", 1)
14354 + p = string.gsub(p, "($?)$", "()%1", 1)
14355 + local t = {string.match(s, p)}
14356 + return string.sub(s, t[1], t[#t] - 1)
14357 +end
14358 +
14359 +assert(f1('alo alx 123 b\0o b\0o', '(..*) %1') == "b\0o b\0o")
14360 +assert(f1('axz123= 4= 4 34', '(.+)=(.*)=%2 %1') == '3= 4= 4 3')
14361 +assert(f1('=======', '^(=*)=%1$') == '=======')
14362 +assert(not string.match('==========', '^([=]*)=%1$'))
14363 +
14364 +local function range (i, j)
14365 + if i <= j then
14366 + return i, range(i+1, j)
14367 + end
14368 +end
14369 +
14370 +local abc = string.char(range(0, 127)) .. string.char(range(128, 255));
14371 +
14372 +assert(string.len(abc) == 256)
14373 +
14374 +function strset (p)
14375 + local res = {s=''}
14376 + string.gsub(abc, p, function (c) res.s = res.s .. c end)
14377 + return res.s
14378 +end;
14379 +
14380 +assert(string.len(strset('[\200-\210]')) == 11)
14381 +
14382 +assert(strset('[a-z]') == "abcdefghijklmnopqrstuvwxyz")
14383 +assert(strset('[a-z%d]') == strset('[%da-uu-z]'))
14384 +assert(strset('[a-]') == "-a")
14385 +assert(strset('[^%W]') == strset('[%w]'))
14386 +assert(strset('[]%%]') == '%]')
14387 +assert(strset('[a%-z]') == '-az')
14388 +assert(strset('[%^%[%-a%]%-b]') == '-[]^ab')
14389 +assert(strset('%Z') == strset('[\1-\255]'))
14390 +assert(strset('.') == strset('[\1-\255%z]'))
14391 +print('+');
14392 +
14393 +assert(string.match("alo xyzK", "(%w+)K") == "xyz")
14394 +assert(string.match("254 K", "(%d*)K") == "")
14395 +assert(string.match("alo ", "(%w*)$") == "")
14396 +assert(not string.match("alo ", "(%w+)$"))
14397 +assert(string.find("(álo)", "%(á") == 1)
14398 +local a, b, c, d, e = string.match("âlo alo", "^(((.).).* (%w*))$")
14399 +assert(a == 'âlo alo' and b == 'âl' and c == 'â' and d == 'alo' and e == nil)
14400 +a, b, c, d = string.match('0123456789', '(.+(.?)())')
14401 +assert(a == '0123456789' and b == '' and c == 11 and d == nil)
14402 +print('+')
14403 +
14404 +assert(string.gsub('ülo ülo', 'ü', 'x') == 'xlo xlo')
14405 +assert(string.gsub('alo úlo ', ' +$', '') == 'alo úlo') -- trim
14406 +assert(string.gsub(' alo alo ', '^%s*(.-)%s*$', '%1') == 'alo alo') -- double trim
14407 +assert(string.gsub('alo alo \n 123\n ', '%s+', ' ') == 'alo alo 123 ')
14408 +t = "abç d"
14409 +a, b = string.gsub(t, '(.)', '%1@')
14410 +assert('@'..a == string.gsub(t, '', '@') and b == 5)
14411 +a, b = string.gsub('abçd', '(.)', '%0@', 2)
14412 +assert(a == 'a@b@çd' and b == 2)
14413 +assert(string.gsub('alo alo', '()[al]', '%1') == '12o 56o')
14414 +assert(string.gsub("abc=xyz", "(%w*)(%p)(%w+)", "%3%2%1-%0") ==
14415 + "xyz=abc-abc=xyz")
14416 +assert(string.gsub("abc", "%w", "%1%0") == "aabbcc")
14417 +assert(string.gsub("abc", "%w+", "%0%1") == "abcabc")
14418 +assert(string.gsub('áéí', '$', '\0óú') == 'áéí\0óú')
14419 +assert(string.gsub('', '^', 'r') == 'r')
14420 +assert(string.gsub('', '$', 'r') == 'r')
14421 +print('+')
14422 +
14423 +
14424 +do -- new (5.3.3) semantics for empty matches
14425 + assert(string.gsub("a b cd", " *", "-") == "-a-b-c-d-")
14426 +
14427 + local res = ""
14428 + local sub = "a \nbc\t\td"
14429 + local i = 1
14430 + for p, e in string.gmatch(sub, "()%s*()") do
14431 + res = res .. string.sub(sub, i, p - 1) .. "-"
14432 + i = e
14433 + end
14434 + assert(res == "-a-b-c-d-")
14435 +end
14436 +
14437 +
14438 +assert(string.gsub("um (dois) tres (quatro)", "(%(%w+%))", string.upper) ==
14439 + "um (DOIS) tres (QUATRO)")
14440 +
14441 +do
14442 + local function setglobal (n,v) rawset(_G, n, v) end
14443 + string.gsub("a=roberto,roberto=a", "(%w+)=(%w%w*)", setglobal)
14444 + assert(_G.a=="roberto" and _G.roberto=="a")
14445 +end
14446 +
14447 +function f(a,b) return string.gsub(a,'.',b) end
14448 +assert(string.gsub("trocar tudo em |teste|b| é |beleza|al|", "|([^|]*)|([^|]*)|", f) ==
14449 + "trocar tudo em bbbbb é alalalalalal")
14450 +
14451 +local function dostring (s) return load(s, "")() or "" end
14452 +assert(string.gsub("alo $a='x'$ novamente $return a$",
14453 + "$([^$]*)%$",
14454 + dostring) == "alo novamente x")
14455 +
14456 +x = string.gsub("$x=string.gsub('alo', '.', string.upper)$ assim vai para $return x$",
14457 + "$([^$]*)%$", dostring)
14458 +assert(x == ' assim vai para ALO')
14459 +
14460 +t = {}
14461 +s = 'a alo jose joao'
14462 +r = string.gsub(s, '()(%w+)()', function (a,w,b)
14463 + assert(string.len(w) == b-a);
14464 + t[a] = b-a;
14465 + end)
14466 +assert(s == r and t[1] == 1 and t[3] == 3 and t[7] == 4 and t[13] == 4)
14467 +
14468 +
14469 +function isbalanced (s)
14470 + return not string.find(string.gsub(s, "%b()", ""), "[()]")
14471 +end
14472 +
14473 +assert(isbalanced("(9 ((8))(\0) 7) \0\0 a b ()(c)() a"))
14474 +assert(not isbalanced("(9 ((8) 7) a b (\0 c) a"))
14475 +assert(string.gsub("alo 'oi' alo", "%b''", '"') == 'alo " alo')
14476 +
14477 +
14478 +local t = {"apple", "orange", "lime"; n=0}
14479 +assert(string.gsub("x and x and x", "x", function () t.n=t.n+1; return t[t.n] end)
14480 + == "apple and orange and lime")
14481 +
14482 +t = {n=0}
14483 +string.gsub("first second word", "%w%w*", function (w) t.n=t.n+1; t[t.n] = w end)
14484 +assert(t[1] == "first" and t[2] == "second" and t[3] == "word" and t.n == 3)
14485 +
14486 +t = {n=0}
14487 +assert(string.gsub("first second word", "%w+",
14488 + function (w) t.n=t.n+1; t[t.n] = w end, 2) == "first second word")
14489 +assert(t[1] == "first" and t[2] == "second" and t[3] == undef)
14490 +
14491 +checkerror("invalid replacement value %(a table%)",
14492 + string.gsub, "alo", ".", {a = {}})
14493 +checkerror("invalid capture index %%2", string.gsub, "alo", ".", "%2")
14494 +checkerror("invalid capture index %%0", string.gsub, "alo", "(%0)", "a")
14495 +checkerror("invalid capture index %%1", string.gsub, "alo", "(%1)", "a")
14496 +checkerror("invalid use of '%%'", string.gsub, "alo", ".", "%x")
14497 +
14498 +
14499 +if not _soft then
14500 + print("big strings")
14501 + local a = string.rep('a', 300000)
14502 + assert(string.find(a, '^a*.?$'))
14503 + assert(not string.find(a, '^a*.?b$'))
14504 + assert(string.find(a, '^a-.?$'))
14505 +
14506 + -- bug in 5.1.2
14507 + a = string.rep('a', 10000) .. string.rep('b', 10000)
14508 + assert(not pcall(string.gsub, a, 'b'))
14509 +end
14510 +
14511 +-- recursive nest of gsubs
14512 +function rev (s)
14513 + return string.gsub(s, "(.)(.+)", function (c,s1) return rev(s1)..c end)
14514 +end
14515 +
14516 +local x = "abcdef"
14517 +assert(rev(rev(x)) == x)
14518 +
14519 +
14520 +-- gsub with tables
14521 +assert(string.gsub("alo alo", ".", {}) == "alo alo")
14522 +assert(string.gsub("alo alo", "(.)", {a="AA", l=""}) == "AAo AAo")
14523 +assert(string.gsub("alo alo", "(.).", {a="AA", l="K"}) == "AAo AAo")
14524 +assert(string.gsub("alo alo", "((.)(.?))", {al="AA", o=false}) == "AAo AAo")
14525 +
14526 +assert(string.gsub("alo alo", "().", {'x','yy','zzz'}) == "xyyzzz alo")
14527 +
14528 +t = {}; setmetatable(t, {__index = function (t,s) return string.upper(s) end})
14529 +assert(string.gsub("a alo b hi", "%w%w+", t) == "a ALO b HI")
14530 +
14531 +
14532 +-- tests for gmatch
14533 +local a = 0
14534 +for i in string.gmatch('abcde', '()') do assert(i == a+1); a=i end
14535 +assert(a==6)
14536 +
14537 +t = {n=0}
14538 +for w in string.gmatch("first second word", "%w+") do
14539 + t.n=t.n+1; t[t.n] = w
14540 +end
14541 +assert(t[1] == "first" and t[2] == "second" and t[3] == "word")
14542 +
14543 +t = {3, 6, 9}
14544 +for i in string.gmatch ("xuxx uu ppar r", "()(.)%2") do
14545 + assert(i == table.remove(t, 1))
14546 +end
14547 +assert(#t == 0)
14548 +
14549 +t = {}
14550 +for i,j in string.gmatch("13 14 10 = 11, 15= 16, 22=23", "(%d+)%s*=%s*(%d+)") do
14551 + t[tonumber(i)] = tonumber(j)
14552 +end
14553 +a = 0
14554 +for k,v in pairs(t) do assert(k+1 == v+0); a=a+1 end
14555 +assert(a == 3)
14556 +
14557 +
14558 +do -- init parameter in gmatch
14559 + local s = 0
14560 + for k in string.gmatch("10 20 30", "%d+", 3) do
14561 + s = s + tonumber(k)
14562 + end
14563 + assert(s == 50)
14564 +
14565 + s = 0
14566 + for k in string.gmatch("11 21 31", "%d+", -4) do
14567 + s = s + tonumber(k)
14568 + end
14569 + assert(s == 32)
14570 +
14571 + -- there is an empty string at the end of the subject
14572 + s = 0
14573 + for k in string.gmatch("11 21 31", "%w*", 9) do
14574 + s = s + 1
14575 + end
14576 + assert(s == 1)
14577 +
14578 + -- there are no empty strings after the end of the subject
14579 + s = 0
14580 + for k in string.gmatch("11 21 31", "%w*", 10) do
14581 + s = s + 1
14582 + end
14583 + assert(s == 0)
14584 +end
14585 +
14586 +
14587 +-- tests for `%f' (`frontiers')
14588 +
14589 +assert(string.gsub("aaa aa a aaa a", "%f[%w]a", "x") == "xaa xa x xaa x")
14590 +assert(string.gsub("[[]] [][] [[[[", "%f[[].", "x") == "x[]] x]x] x[[[")
14591 +assert(string.gsub("01abc45de3", "%f[%d]", ".") == ".01abc.45de.3")
14592 +assert(string.gsub("01abc45 de3x", "%f[%D]%w", ".") == "01.bc45 de3.")
14593 +assert(string.gsub("function", "%f[\1-\255]%w", ".") == ".unction")
14594 +assert(string.gsub("function", "%f[^\1-\255]", ".") == "function.")
14595 +
14596 +assert(string.find("a", "%f[a]") == 1)
14597 +assert(string.find("a", "%f[^%z]") == 1)
14598 +assert(string.find("a", "%f[^%l]") == 2)
14599 +assert(string.find("aba", "%f[a%z]") == 3)
14600 +assert(string.find("aba", "%f[%z]") == 4)
14601 +assert(not string.find("aba", "%f[%l%z]"))
14602 +assert(not string.find("aba", "%f[^%l%z]"))
14603 +
14604 +local i, e = string.find(" alo aalo allo", "%f[%S].-%f[%s].-%f[%S]")
14605 +assert(i == 2 and e == 5)
14606 +local k = string.match(" alo aalo allo", "%f[%S](.-%f[%s].-%f[%S])")
14607 +assert(k == 'alo ')
14608 +
14609 +local a = {1, 5, 9, 14, 17,}
14610 +for k in string.gmatch("alo alo th02 is 1hat", "()%f[%w%d]") do
14611 + assert(table.remove(a, 1) == k)
14612 +end
14613 +assert(#a == 0)
14614 +
14615 +
14616 +-- malformed patterns
14617 +local function malform (p, m)
14618 + m = m or "malformed"
14619 + local r, msg = pcall(string.find, "a", p)
14620 + assert(not r and string.find(msg, m))
14621 +end
14622 +
14623 +malform("(.", "unfinished capture")
14624 +malform(".)", "invalid pattern capture")
14625 +malform("[a")
14626 +malform("[]")
14627 +malform("[^]")
14628 +malform("[a%]")
14629 +malform("[a%")
14630 +malform("%b")
14631 +malform("%ba")
14632 +malform("%")
14633 +malform("%f", "missing")
14634 +
14635 +-- \0 in patterns
14636 +assert(string.match("ab\0\1\2c", "[\0-\2]+") == "\0\1\2")
14637 +assert(string.match("ab\0\1\2c", "[\0-\0]+") == "\0")
14638 +assert(string.find("b$a", "$\0?") == 2)
14639 +assert(string.find("abc\0efg", "%\0") == 4)
14640 +assert(string.match("abc\0efg\0\1e\1g", "%b\0\1") == "\0efg\0\1e\1")
14641 +assert(string.match("abc\0\0\0", "%\0+") == "\0\0\0")
14642 +assert(string.match("abc\0\0\0", "%\0%\0?") == "\0\0")
14643 +
14644 +-- magic char after \0
14645 +assert(string.find("abc\0\0","\0.") == 4)
14646 +assert(string.find("abcx\0\0abc\0abc","x\0\0abc\0a.") == 4)
14647 +
14648 +
14649 +do -- test reuse of original string in gsub
14650 + local s = string.rep("a", 100)
14651 + local r = string.gsub(s, "b", "c") -- no match
14652 + assert(string.format("%p", s) == string.format("%p", r))
14653 +
14654 + r = string.gsub(s, ".", {x = "y"}) -- no substitutions
14655 + assert(string.format("%p", s) == string.format("%p", r))
14656 +
14657 + local count = 0
14658 + r = string.gsub(s, ".", function (x)
14659 + assert(x == "a")
14660 + count = count + 1
14661 + return nil -- no substitution
14662 + end)
14663 + r = string.gsub(r, ".", {b = 'x'}) -- "a" is not a key; no subst.
14664 + assert(count == 100)
14665 + assert(string.format("%p", s) == string.format("%p", r))
14666 +
14667 + count = 0
14668 + r = string.gsub(s, ".", function (x)
14669 + assert(x == "a")
14670 + count = count + 1
14671 + return x -- substitution...
14672 + end)
14673 + assert(count == 100)
14674 + -- no reuse in this case
14675 + assert(r == s and string.format("%p", s) ~= string.format("%p", r))
14676 +end
14677 +
14678 +print('OK')
14679 +
14680
14681 diff --git a/tests/sort.lua b/tests/sort.lua
14682 new file mode 100644
14683 index 0000000..ef405d9
14684 --- /dev/null
14685 +++ b/tests/sort.lua
14686 @@ -0,0 +1,310 @@
14687 +-- $Id: testes/sort.lua $
14688 +-- See Copyright Notice in file all.lua
14689 +
14690 +print "testing (parts of) table library"
14691 +
14692 +print "testing unpack"
14693 +
14694 +local unpack = table.unpack
14695 +
14696 +local maxI = math.maxinteger
14697 +local minI = math.mininteger
14698 +
14699 +
14700 +local function checkerror (msg, f, ...)
14701 + local s, err = pcall(f, ...)
14702 + assert(not s and string.find(err, msg))
14703 +end
14704 +
14705 +
14706 +checkerror("wrong number of arguments", table.insert, {}, 2, 3, 4)
14707 +
14708 +local x,y,z,a,n
14709 +a = {}; lim = _soft and 200 or 2000
14710 +for i=1, lim do a[i]=i end
14711 +assert(select(lim, unpack(a)) == lim and select('#', unpack(a)) == lim)
14712 +x = unpack(a)
14713 +assert(x == 1)
14714 +x = {unpack(a)}
14715 +assert(#x == lim and x[1] == 1 and x[lim] == lim)
14716 +x = {unpack(a, lim-2)}
14717 +assert(#x == 3 and x[1] == lim-2 and x[3] == lim)
14718 +x = {unpack(a, 10, 6)}
14719 +assert(next(x) == nil) -- no elements
14720 +x = {unpack(a, 11, 10)}
14721 +assert(next(x) == nil) -- no elements
14722 +x,y = unpack(a, 10, 10)
14723 +assert(x == 10 and y == nil)
14724 +x,y,z = unpack(a, 10, 11)
14725 +assert(x == 10 and y == 11 and z == nil)
14726 +a,x = unpack{1}
14727 +assert(a==1 and x==nil)
14728 +a,x = unpack({1,2}, 1, 1)
14729 +assert(a==1 and x==nil)
14730 +
14731 +do
14732 + local maxi = (1 << 31) - 1 -- maximum value for an int (usually)
14733 + local mini = -(1 << 31) -- minimum value for an int (usually)
14734 + checkerror("too many results", unpack, {}, 0, maxi)
14735 + checkerror("too many results", unpack, {}, 1, maxi)
14736 + checkerror("too many results", unpack, {}, 0, maxI)
14737 + checkerror("too many results", unpack, {}, 1, maxI)
14738 + checkerror("too many results", unpack, {}, mini, maxi)
14739 + checkerror("too many results", unpack, {}, -maxi, maxi)
14740 + checkerror("too many results", unpack, {}, minI, maxI)
14741 + unpack({}, maxi, 0)
14742 + unpack({}, maxi, 1)
14743 + unpack({}, maxI, minI)
14744 + pcall(unpack, {}, 1, maxi + 1)
14745 + local a, b = unpack({[maxi] = 20}, maxi, maxi)
14746 + assert(a == 20 and b == nil)
14747 + a, b = unpack({[maxi] = 20}, maxi - 1, maxi)
14748 + assert(a == nil and b == 20)
14749 + local t = {[maxI - 1] = 12, [maxI] = 23}
14750 + a, b = unpack(t, maxI - 1, maxI); assert(a == 12 and b == 23)
14751 + a, b = unpack(t, maxI, maxI); assert(a == 23 and b == nil)
14752 + a, b = unpack(t, maxI, maxI - 1); assert(a == nil and b == nil)
14753 + t = {[minI] = 12.3, [minI + 1] = 23.5}
14754 + a, b = unpack(t, minI, minI + 1); assert(a == 12.3 and b == 23.5)
14755 + a, b = unpack(t, minI, minI); assert(a == 12.3 and b == nil)
14756 + a, b = unpack(t, minI + 1, minI); assert(a == nil and b == nil)
14757 +end
14758 +
14759 +do -- length is not an integer
14760 + local t = setmetatable({}, {__len = function () return 'abc' end})
14761 + assert(#t == 'abc')
14762 + checkerror("object length is not an integer", table.insert, t, 1)
14763 +end
14764 +
14765 +print "testing pack"
14766 +
14767 +a = table.pack()
14768 +assert(a[1] == undef and a.n == 0)
14769 +
14770 +a = table.pack(table)
14771 +assert(a[1] == table and a.n == 1)
14772 +
14773 +a = table.pack(nil, nil, nil, nil)
14774 +assert(a[1] == nil and a.n == 4)
14775 +
14776 +
14777 +-- testing move
14778 +do
14779 +
14780 + checkerror("table expected", table.move, 1, 2, 3, 4)
14781 +
14782 + local function eqT (a, b)
14783 + for k, v in pairs(a) do assert(b[k] == v) end
14784 + for k, v in pairs(b) do assert(a[k] == v) end
14785 + end
14786 +
14787 + local a = table.move({10,20,30}, 1, 3, 2) -- move forward
14788 + eqT(a, {10,10,20,30})
14789 +
14790 + -- move forward with overlap of 1
14791 + a = table.move({10, 20, 30}, 1, 3, 3)
14792 + eqT(a, {10, 20, 10, 20, 30})
14793 +
14794 + -- moving to the same table (not being explicit about it)
14795 + a = {10, 20, 30, 40}
14796 + table.move(a, 1, 4, 2, a)
14797 + eqT(a, {10, 10, 20, 30, 40})
14798 +
14799 + a = table.move({10,20,30}, 2, 3, 1) -- move backward
14800 + eqT(a, {20,30,30})
14801 +
14802 + a = {} -- move to new table
14803 + assert(table.move({10,20,30}, 1, 3, 1, a) == a)
14804 + eqT(a, {10,20,30})
14805 +
14806 + a = {}
14807 + assert(table.move({10,20,30}, 1, 0, 3, a) == a) -- empty move (no move)
14808 + eqT(a, {})
14809 +
14810 + a = table.move({10,20,30}, 1, 10, 1) -- move to the same place
14811 + eqT(a, {10,20,30})
14812 +
14813 + -- moving on the fringes
14814 + a = table.move({[maxI - 2] = 1, [maxI - 1] = 2, [maxI] = 3},
14815 + maxI - 2, maxI, -10, {})
14816 + eqT(a, {[-10] = 1, [-9] = 2, [-8] = 3})
14817 +
14818 + a = table.move({[minI] = 1, [minI + 1] = 2, [minI + 2] = 3},
14819 + minI, minI + 2, -10, {})
14820 + eqT(a, {[-10] = 1, [-9] = 2, [-8] = 3})
14821 +
14822 + a = table.move({45}, 1, 1, maxI)
14823 + eqT(a, {45, [maxI] = 45})
14824 +
14825 + a = table.move({[maxI] = 100}, maxI, maxI, minI)
14826 + eqT(a, {[minI] = 100, [maxI] = 100})
14827 +
14828 + a = table.move({[minI] = 100}, minI, minI, maxI)
14829 + eqT(a, {[minI] = 100, [maxI] = 100})
14830 +
14831 + a = setmetatable({}, {
14832 + __index = function (_,k) return k * 10 end,
14833 + __newindex = error})
14834 + local b = table.move(a, 1, 10, 3, {})
14835 + eqT(a, {})
14836 + eqT(b, {nil,nil,10,20,30,40,50,60,70,80,90,100})
14837 +
14838 + b = setmetatable({""}, {
14839 + __index = error,
14840 + __newindex = function (t,k,v)
14841 + t[1] = string.format("%s(%d,%d)", t[1], k, v)
14842 + end})
14843 + table.move(a, 10, 13, 3, b)
14844 + assert(b[1] == "(3,100)(4,110)(5,120)(6,130)")
14845 + local stat, msg = pcall(table.move, b, 10, 13, 3, b)
14846 + assert(not stat and msg == b)
14847 +end
14848 +
14849 +do
14850 + -- for very long moves, just check initial accesses and interrupt
14851 + -- move with an error
14852 + local function checkmove (f, e, t, x, y)
14853 + local pos1, pos2
14854 + local a = setmetatable({}, {
14855 + __index = function (_,k) pos1 = k end,
14856 + __newindex = function (_,k) pos2 = k; error() end, })
14857 + local st, msg = pcall(table.move, a, f, e, t)
14858 + assert(not st and not msg and pos1 == x and pos2 == y)
14859 + end
14860 + checkmove(1, maxI, 0, 1, 0)
14861 + checkmove(0, maxI - 1, 1, maxI - 1, maxI)
14862 + checkmove(minI, -2, -5, -2, maxI - 6)
14863 + checkmove(minI + 1, -1, -2, -1, maxI - 3)
14864 + checkmove(minI, -2, 0, minI, 0) -- non overlapping
14865 + checkmove(minI + 1, -1, 1, minI + 1, 1) -- non overlapping
14866 +end
14867 +
14868 +checkerror("too many", table.move, {}, 0, maxI, 1)
14869 +checkerror("too many", table.move, {}, -1, maxI - 1, 1)
14870 +checkerror("too many", table.move, {}, minI, -1, 1)
14871 +checkerror("too many", table.move, {}, minI, maxI, 1)
14872 +checkerror("wrap around", table.move, {}, 1, maxI, 2)
14873 +checkerror("wrap around", table.move, {}, 1, 2, maxI)
14874 +checkerror("wrap around", table.move, {}, minI, -2, 2)
14875 +
14876 +
14877 +print"testing sort"
14878 +
14879 +
14880 +-- strange lengths
14881 +local a = setmetatable({}, {__len = function () return -1 end})
14882 +assert(#a == -1)
14883 +table.sort(a, error) -- should not compare anything
14884 +a = setmetatable({}, {__len = function () return maxI end})
14885 +checkerror("too big", table.sort, a)
14886 +
14887 +-- test checks for invalid order functions
14888 +local function check (t)
14889 + local function f(a, b) assert(a and b); return true end
14890 + checkerror("invalid order function", table.sort, t, f)
14891 +end
14892 +
14893 +check{1,2,3,4}
14894 +check{1,2,3,4,5}
14895 +check{1,2,3,4,5,6}
14896 +
14897 +
14898 +function check (a, f)
14899 + f = f or function (x,y) return x<y end;
14900 + for n = #a, 2, -1 do
14901 + assert(not f(a[n], a[n-1]))
14902 + end
14903 +end
14904 +
14905 +a = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
14906 + "Oct", "Nov", "Dec"}
14907 +
14908 +table.sort(a)
14909 +check(a)
14910 +
14911 +function perm (s, n)
14912 + n = n or #s
14913 + if n == 1 then
14914 + local t = {unpack(s)}
14915 + table.sort(t)
14916 + check(t)
14917 + else
14918 + for i = 1, n do
14919 + s[i], s[n] = s[n], s[i]
14920 + perm(s, n - 1)
14921 + s[i], s[n] = s[n], s[i]
14922 + end
14923 + end
14924 +end
14925 +
14926 +perm{}
14927 +perm{1}
14928 +perm{1,2}
14929 +perm{1,2,3}
14930 +perm{1,2,3,4}
14931 +perm{2,2,3,4}
14932 +perm{1,2,3,4,5}
14933 +perm{1,2,3,3,5}
14934 +perm{1,2,3,4,5,6}
14935 +perm{2,2,3,3,5,6}
14936 +
14937 +function timesort (a, n, func, msg, pre)
14938 + local x = os.clock()
14939 + table.sort(a, func)
14940 + x = (os.clock() - x) * 1000
14941 + pre = pre or ""
14942 + print(string.format("%ssorting %d %s elements in %.2f msec.", pre, n, msg, x))
14943 + check(a, func)
14944 +end
14945 +
14946 +limit = 50000
14947 +if _soft then limit = 5000 end
14948 +
14949 +a = {}
14950 +for i=1,limit do
14951 + a[i] = math.random()
14952 +end
14953 +
14954 +timesort(a, limit, nil, "random")
14955 +
14956 +timesort(a, limit, nil, "sorted", "re-")
14957 +
14958 +a = {}
14959 +for i=1,limit do
14960 + a[i] = math.random()
14961 +end
14962 +
14963 +x = os.clock(); i=0
14964 +table.sort(a, function(x,y) i=i+1; return y<x end)
14965 +x = (os.clock() - x) * 1000
14966 +print(string.format("Invert-sorting other %d elements in %.2f msec., with %i comparisons",
14967 + limit, x, i))
14968 +check(a, function(x,y) return y<x end)
14969 +
14970 +
14971 +table.sort{} -- empty array
14972 +
14973 +for i=1,limit do a[i] = false end
14974 +timesort(a, limit, function(x,y) return nil end, "equal")
14975 +
14976 +for i,v in pairs(a) do assert(v == false) end
14977 +
14978 +A = {"álo", "\0first :-)", "alo", "then this one", "45", "and a new"}
14979 +table.sort(A)
14980 +check(A)
14981 +
14982 +table.sort(A, function (x, y)
14983 + load(string.format("A[%q] = ''", x), "")()
14984 + collectgarbage()
14985 + return x<y
14986 + end)
14987 +
14988 +
14989 +tt = {__lt = function (a,b) return a.val < b.val end}
14990 +a = {}
14991 +for i=1,10 do a[i] = {val=math.random(100)}; setmetatable(a[i], tt); end
14992 +table.sort(a)
14993 +check(a, tt.__lt)
14994 +check(a)
14995 +
14996 +print"OK"
14997
14998 diff --git a/tests/strings.lua b/tests/strings.lua
14999 new file mode 100644
15000 index 0000000..184fa65
15001 --- /dev/null
15002 +++ b/tests/strings.lua
15003 @@ -0,0 +1,518 @@
15004 +-- $Id: testes/strings.lua $
15005 +-- See Copyright Notice in file all.lua
15006 +
15007 +print('testing strings and string library')
15008 +
15009 +local maxi <const> = math.maxinteger
15010 +local mini <const> = math.mininteger
15011 +
15012 +
15013 +local function checkerror (msg, f, ...)
15014 + local s, err = pcall(f, ...)
15015 + assert(not s and string.find(err, msg))
15016 +end
15017 +
15018 +
15019 +-- testing string comparisons
15020 +assert('alo' < 'alo1')
15021 +assert('' < 'a')
15022 +assert('alo\0alo' < 'alo\0b')
15023 +assert('alo\0alo\0\0' > 'alo\0alo\0')
15024 +assert('alo' < 'alo\0')
15025 +assert('alo\0' > 'alo')
15026 +assert('\0' < '\1')
15027 +assert('\0\0' < '\0\1')
15028 +assert('\1\0a\0a' <= '\1\0a\0a')
15029 +assert(not ('\1\0a\0b' <= '\1\0a\0a'))
15030 +assert('\0\0\0' < '\0\0\0\0')
15031 +assert(not('\0\0\0\0' < '\0\0\0'))
15032 +assert('\0\0\0' <= '\0\0\0\0')
15033 +assert(not('\0\0\0\0' <= '\0\0\0'))
15034 +assert('\0\0\0' <= '\0\0\0')
15035 +assert('\0\0\0' >= '\0\0\0')
15036 +assert(not ('\0\0b' < '\0\0a\0'))
15037 +
15038 +-- testing string.sub
15039 +assert(string.sub("123456789",2,4) == "234")
15040 +assert(string.sub("123456789",7) == "789")
15041 +assert(string.sub("123456789",7,6) == "")
15042 +assert(string.sub("123456789",7,7) == "7")
15043 +assert(string.sub("123456789",0,0) == "")
15044 +assert(string.sub("123456789",-10,10) == "123456789")
15045 +assert(string.sub("123456789",1,9) == "123456789")
15046 +assert(string.sub("123456789",-10,-20) == "")
15047 +assert(string.sub("123456789",-1) == "9")
15048 +assert(string.sub("123456789",-4) == "6789")
15049 +assert(string.sub("123456789",-6, -4) == "456")
15050 +assert(string.sub("123456789", mini, -4) == "123456")
15051 +assert(string.sub("123456789", mini, maxi) == "123456789")
15052 +assert(string.sub("123456789", mini, mini) == "")
15053 +assert(string.sub("\000123456789",3,5) == "234")
15054 +assert(("\000123456789"):sub(8) == "789")
15055 +
15056 +-- testing string.find
15057 +assert(string.find("123456789", "345") == 3)
15058 +a,b = string.find("123456789", "345")
15059 +assert(string.sub("123456789", a, b) == "345")
15060 +assert(string.find("1234567890123456789", "345", 3) == 3)
15061 +assert(string.find("1234567890123456789", "345", 4) == 13)
15062 +assert(not string.find("1234567890123456789", "346", 4))
15063 +assert(string.find("1234567890123456789", ".45", -9) == 13)
15064 +assert(not string.find("abcdefg", "\0", 5, 1))
15065 +assert(string.find("", "") == 1)
15066 +assert(string.find("", "", 1) == 1)
15067 +assert(not string.find("", "", 2))
15068 +assert(not string.find('', 'aaa', 1))
15069 +assert(('alo(.)alo'):find('(.)', 1, 1) == 4)
15070 +
15071 +assert(string.len("") == 0)
15072 +assert(string.len("\0\0\0") == 3)
15073 +assert(string.len("1234567890") == 10)
15074 +
15075 +assert(#"" == 0)
15076 +assert(#"\0\0\0" == 3)
15077 +assert(#"1234567890" == 10)
15078 +
15079 +-- testing string.byte/string.char
15080 +assert(string.byte("a") == 97)
15081 +assert(string.byte("\xe4") > 127)
15082 +assert(string.byte(string.char(255)) == 255)
15083 +assert(string.byte(string.char(0)) == 0)
15084 +assert(string.byte("\0") == 0)
15085 +assert(string.byte("\0\0alo\0x", -1) == string.byte('x'))
15086 +assert(string.byte("ba", 2) == 97)
15087 +assert(string.byte("\n\n", 2, -1) == 10)
15088 +assert(string.byte("\n\n", 2, 2) == 10)
15089 +assert(string.byte("") == nil)
15090 +assert(string.byte("hi", -3) == nil)
15091 +assert(string.byte("hi", 3) == nil)
15092 +assert(string.byte("hi", 9, 10) == nil)
15093 +assert(string.byte("hi", 2, 1) == nil)
15094 +assert(string.char() == "")
15095 +assert(string.char(0, 255, 0) == "\0\255\0")
15096 +assert(string.char(0, string.byte("\xe4"), 0) == "\0\xe4\0")
15097 +assert(string.char(string.byte("\xe4l\0óu", 1, -1)) == "\xe4l\0óu")
15098 +assert(string.char(string.byte("\xe4l\0óu", 1, 0)) == "")
15099 +assert(string.char(string.byte("\xe4l\0óu", -10, 100)) == "\xe4l\0óu")
15100 +
15101 +checkerror("out of range", string.char, 256)
15102 +checkerror("out of range", string.char, -1)
15103 +checkerror("out of range", string.char, math.maxinteger)
15104 +checkerror("out of range", string.char, math.mininteger)
15105 +
15106 +assert(string.upper("ab\0c") == "AB\0C")
15107 +assert(string.lower("\0ABCc%$") == "\0abcc%$")
15108 +assert(string.rep('teste', 0) == '')
15109 +assert(string.rep('tés\00tê', 2) == 'tés\0têtés\000tê')
15110 +assert(string.rep('', 10) == '')
15111 +
15112 +if string.packsize("i") == 4 then
15113 + -- result length would be 2^31 (int overflow)
15114 + checkerror("too large", string.rep, 'aa', (1 << 30))
15115 + checkerror("too large", string.rep, 'a', (1 << 30), ',')
15116 +end
15117 +
15118 +-- repetitions with separator
15119 +assert(string.rep('teste', 0, 'xuxu') == '')
15120 +assert(string.rep('teste', 1, 'xuxu') == 'teste')
15121 +assert(string.rep('\1\0\1', 2, '\0\0') == '\1\0\1\0\0\1\0\1')
15122 +assert(string.rep('', 10, '.') == string.rep('.', 9))
15123 +assert(not pcall(string.rep, "aa", maxi // 2 + 10))
15124 +assert(not pcall(string.rep, "", maxi // 2 + 10, "aa"))
15125 +
15126 +assert(string.reverse"" == "")
15127 +assert(string.reverse"\0\1\2\3" == "\3\2\1\0")
15128 +assert(string.reverse"\0001234" == "4321\0")
15129 +
15130 +for i=0,30 do assert(string.len(string.rep('a', i)) == i) end
15131 +
15132 +assert(type(tostring(nil)) == 'string')
15133 +assert(type(tostring(12)) == 'string')
15134 +assert(string.find(tostring{}, 'table:'))
15135 +assert(string.find(tostring(print), 'function:'))
15136 +assert(#tostring('\0') == 1)
15137 +assert(tostring(true) == "true")
15138 +assert(tostring(false) == "false")
15139 +assert(tostring(-1203) == "-1203")
15140 +assert(tostring(1203.125) == "1203.125")
15141 +assert(tostring(-0.5) == "-0.5")
15142 +assert(tostring(-32767) == "-32767")
15143 +if math.tointeger(2147483647) then -- no overflow? (32 bits)
15144 + assert(tostring(-2147483647) == "-2147483647")
15145 +end
15146 +if math.tointeger(4611686018427387904) then -- no overflow? (64 bits)
15147 + assert(tostring(4611686018427387904) == "4611686018427387904")
15148 + assert(tostring(-4611686018427387904) == "-4611686018427387904")
15149 +end
15150 +
15151 +if tostring(0.0) == "0.0" then -- "standard" coercion float->string
15152 + assert('' .. 12 == '12' and 12.0 .. '' == '12.0')
15153 + assert(tostring(-1203 + 0.0) == "-1203.0")
15154 +else -- compatible coercion
15155 + assert(tostring(0.0) == "0")
15156 + assert('' .. 12 == '12' and 12.0 .. '' == '12')
15157 + assert(tostring(-1203 + 0.0) == "-1203")
15158 +end
15159 +
15160 +do -- tests for '%p' format
15161 + -- not much to test, as C does not specify what '%p' does.
15162 + -- ("The value of the pointer is converted to a sequence of printing
15163 + -- characters, in an implementation-defined manner.")
15164 + local null = "(null)" -- nulls are formatted by Lua
15165 + assert(string.format("%p", 4) == null)
15166 + assert(string.format("%p", true) == null)
15167 + assert(string.format("%p", nil) == null)
15168 + assert(string.format("%p", {}) ~= null)
15169 + assert(string.format("%p", print) ~= null)
15170 + assert(string.format("%p", coroutine.running()) ~= null)
15171 + assert(string.format("%p", io.stdin) ~= null)
15172 + assert(string.format("%p", io.stdin) == string.format("%p", io.stdin))
15173 + assert(string.format("%p", print) == string.format("%p", print))
15174 + assert(string.format("%p", print) ~= string.format("%p", assert))
15175 +
15176 + assert(#string.format("%90p", {}) == 90)
15177 + assert(#string.format("%-60p", {}) == 60)
15178 + assert(string.format("%10p", false) == string.rep(" ", 10 - #null) .. null)
15179 + assert(string.format("%-12p", 1.5) == null .. string.rep(" ", 12 - #null))
15180 +
15181 + do
15182 + local t1 = {}; local t2 = {}
15183 + assert(string.format("%p", t1) ~= string.format("%p", t2))
15184 + end
15185 +
15186 + do -- short strings are internalized
15187 + local s1 = string.rep("a", 10)
15188 + local s2 = string.rep("aa", 5)
15189 + assert(string.format("%p", s1) == string.format("%p", s2))
15190 + end
15191 +
15192 + do -- long strings aren't internalized
15193 + local s1 = string.rep("a", 300); local s2 = string.rep("a", 300)
15194 + assert(string.format("%p", s1) ~= string.format("%p", s2))
15195 + end
15196 +end
15197 +
15198 +x = '"ílo"\n\\'
15199 +assert(string.format('%q%s', x, x) == '"\\"ílo\\"\\\n\\\\""ílo"\n\\')
15200 +assert(string.format('%q', "\0") == [["\0"]])
15201 +assert(load(string.format('return %q', x))() == x)
15202 +x = "\0\1\0023\5\0009"
15203 +assert(load(string.format('return %q', x))() == x)
15204 +assert(string.format("\0%c\0%c%x\0", string.byte("\xe4"), string.byte("b"), 140) ==
15205 + "\0\xe4\0b8c\0")
15206 +assert(string.format('') == "")
15207 +assert(string.format("%c",34)..string.format("%c",48)..string.format("%c",90)..string.format("%c",100) ==
15208 + string.format("%1c%-c%-1c%c", 34, 48, 90, 100))
15209 +assert(string.format("%s\0 is not \0%s", 'not be', 'be') == 'not be\0 is not \0be')
15210 +assert(string.format("%%%d %010d", 10, 23) == "%10 0000000023")
15211 +assert(tonumber(string.format("%f", 10.3)) == 10.3)
15212 +assert(string.format('"%-50s"', 'a') == '"a' .. string.rep(' ', 49) .. '"')
15213 +
15214 +assert(string.format("-%.20s.20s", string.rep("%", 2000)) ==
15215 + "-"..string.rep("%", 20)..".20s")
15216 +assert(string.format('"-%20s.20s"', string.rep("%", 2000)) ==
15217 + string.format("%q", "-"..string.rep("%", 2000)..".20s"))
15218 +
15219 +do
15220 + local function checkQ (v)
15221 + local s = string.format("%q", v)
15222 + local nv = load("return " .. s)()
15223 + assert(v == nv and math.type(v) == math.type(nv))
15224 + end
15225 + checkQ("\0\0\1\255\u{234}")
15226 + checkQ(math.maxinteger)
15227 + checkQ(math.mininteger)
15228 + checkQ(math.pi)
15229 + checkQ(0.1)
15230 + checkQ(true)
15231 + checkQ(nil)
15232 + checkQ(false)
15233 + checkQ(math.huge)
15234 + checkQ(-math.huge)
15235 + assert(string.format("%q", 0/0) == "(0/0)") -- NaN
15236 + checkerror("no literal", string.format, "%q", {})
15237 +end
15238 +
15239 +assert(string.format("\0%s\0", "\0\0\1") == "\0\0\0\1\0")
15240 +checkerror("contains zeros", string.format, "%10s", "\0")
15241 +
15242 +-- format x tostring
15243 +assert(string.format("%s %s", nil, true) == "nil true")
15244 +assert(string.format("%s %.4s", false, true) == "false true")
15245 +assert(string.format("%.3s %.3s", false, true) == "fal tru")
15246 +local m = setmetatable({}, {__tostring = function () return "hello" end,
15247 + __name = "hi"})
15248 +assert(string.format("%s %.10s", m, m) == "hello hello")
15249 +getmetatable(m).__tostring = nil -- will use '__name' from now on
15250 +assert(string.format("%.4s", m) == "hi: ")
15251 +
15252 +getmetatable(m).__tostring = function () return {} end
15253 +checkerror("'__tostring' must return a string", tostring, m)
15254 +
15255 +
15256 +assert(string.format("%x", 0.0) == "0")
15257 +assert(string.format("%02x", 0.0) == "00")
15258 +assert(string.format("%08X", 0xFFFFFFFF) == "FFFFFFFF")
15259 +assert(string.format("%+08d", 31501) == "+0031501")
15260 +assert(string.format("%+08d", -30927) == "-0030927")
15261 +
15262 +
15263 +do -- longest number that can be formatted
15264 + local i = 1
15265 + local j = 10000
15266 + while i + 1 < j do -- binary search for maximum finite float
15267 + local m = (i + j) // 2
15268 + if 10^m < math.huge then i = m else j = m end
15269 + end
15270 + assert(10^i < math.huge and 10^j == math.huge)
15271 + local s = string.format('%.99f', -(10^i))
15272 + assert(string.len(s) >= i + 101)
15273 + assert(tonumber(s) == -(10^i))
15274 +
15275 + -- limit for floats
15276 + assert(10^38 < math.huge)
15277 + local s = string.format('%.99f', -(10^38))
15278 + assert(string.len(s) >= 38 + 101)
15279 + assert(tonumber(s) == -(10^38))
15280 +end
15281 +
15282 +
15283 +-- testing large numbers for format
15284 +do -- assume at least 32 bits
15285 + local max, min = 0x7fffffff, -0x80000000 -- "large" for 32 bits
15286 + assert(string.sub(string.format("%8x", -1), -8) == "ffffffff")
15287 + assert(string.format("%x", max) == "7fffffff")
15288 + assert(string.sub(string.format("%x", min), -8) == "80000000")
15289 + assert(string.format("%d", max) == "2147483647")
15290 + assert(string.format("%d", min) == "-2147483648")
15291 + assert(string.format("%u", 0xffffffff) == "4294967295")
15292 + assert(string.format("%o", 0xABCD) == "125715")
15293 +
15294 + max, min = 0x7fffffffffffffff, -0x8000000000000000
15295 + if max > 2.0^53 then -- only for 64 bits
15296 + assert(string.format("%x", (2^52 | 0) - 1) == "fffffffffffff")
15297 + assert(string.format("0x%8X", 0x8f000003) == "0x8F000003")
15298 + assert(string.format("%d", 2^53) == "9007199254740992")
15299 + assert(string.format("%i", -2^53) == "-9007199254740992")
15300 + assert(string.format("%x", max) == "7fffffffffffffff")
15301 + assert(string.format("%x", min) == "8000000000000000")
15302 + assert(string.format("%d", max) == "9223372036854775807")
15303 + assert(string.format("%d", min) == "-9223372036854775808")
15304 + assert(string.format("%u", ~(-1 << 64)) == "18446744073709551615")
15305 + assert(tostring(1234567890123) == '1234567890123')
15306 + end
15307 +end
15308 +
15309 +
15310 +do print("testing 'format %a %A'")
15311 + local function matchhexa (n)
15312 + local s = string.format("%a", n)
15313 + -- result matches ISO C requirements
15314 + assert(string.find(s, "^%-?0x[1-9a-f]%.?[0-9a-f]*p[-+]?%d+$"))
15315 + assert(tonumber(s) == n) -- and has full precision
15316 + s = string.format("%A", n)
15317 + assert(string.find(s, "^%-?0X[1-9A-F]%.?[0-9A-F]*P[-+]?%d+$"))
15318 + assert(tonumber(s) == n)
15319 + end
15320 + for _, n in ipairs{0.1, -0.1, 1/3, -1/3, 1e30, -1e30,
15321 + -45/247, 1, -1, 2, -2, 3e-20, -3e-20} do
15322 + matchhexa(n)
15323 + end
15324 +
15325 + assert(string.find(string.format("%A", 0.0), "^0X0%.?0*P%+?0$"))
15326 + assert(string.find(string.format("%a", -0.0), "^%-0x0%.?0*p%+?0$"))
15327 +
15328 + if not _port then -- test inf, -inf, NaN, and -0.0
15329 + assert(string.find(string.format("%a", 1/0), "^inf"))
15330 + assert(string.find(string.format("%A", -1/0), "^%-INF"))
15331 + assert(string.find(string.format("%a", 0/0), "^%-?nan"))
15332 + assert(string.find(string.format("%a", -0.0), "^%-0x0"))
15333 + end
15334 +
15335 + if not pcall(string.format, "%.3a", 0) then
15336 + (Message or print)("\n >>> modifiers for format '%a' not available <<<\n")
15337 + else
15338 + assert(string.find(string.format("%+.2A", 12), "^%+0X%x%.%x0P%+?%d$"))
15339 + assert(string.find(string.format("%.4A", -12), "^%-0X%x%.%x000P%+?%d$"))
15340 + end
15341 +end
15342 +
15343 +
15344 +-- testing some flags (all these results are required by ISO C)
15345 +assert(string.format("%#12o", 10) == " 012")
15346 +assert(string.format("%#10x", 100) == " 0x64")
15347 +assert(string.format("%#-17X", 100) == "0X64 ")
15348 +assert(string.format("%013i", -100) == "-000000000100")
15349 +assert(string.format("%2.5d", -100) == "-00100")
15350 +assert(string.format("%.u", 0) == "")
15351 +assert(string.format("%+#014.0f", 100) == "+000000000100.")
15352 +assert(string.format("% 1.0E", 100) == " 1E+02")
15353 +assert(string.format("%-16c", 97) == "a ")
15354 +assert(string.format("%+.3G", 1.5) == "+1.5")
15355 +assert(string.format("% .1g", 2^10) == " 1e+03")
15356 +assert(string.format("%.0s", "alo") == "")
15357 +assert(string.format("%.s", "alo") == "")
15358 +
15359 +-- errors in format
15360 +
15361 +local function check (fmt, msg)
15362 + checkerror(msg, string.format, fmt, 10)
15363 +end
15364 +
15365 +local aux = string.rep('0', 600)
15366 +check("%100.3d", "invalid conversion")
15367 +check("%1"..aux..".3d", "too long")
15368 +check("%1.100d", "invalid conversion")
15369 +check("%10.1"..aux.."004d", "too long")
15370 +check("%t", "invalid conversion")
15371 +check("%"..aux.."d", "too long")
15372 +check("%d %d", "no value")
15373 +check("%010c", "invalid conversion")
15374 +check("%.10c", "invalid conversion")
15375 +check("%0.34s", "invalid conversion")
15376 +check("%#i", "invalid conversion")
15377 +check("%3.1p", "invalid conversion")
15378 +check("%0.s", "invalid conversion")
15379 +check("%10q", "cannot have modifiers")
15380 +check("%F", "invalid conversion") -- useless and not in C89
15381 +
15382 +
15383 +assert(load("return 1\n--comment without ending EOL")() == 1)
15384 +
15385 +
15386 +checkerror("table expected", table.concat, 3)
15387 +checkerror("at index " .. maxi, table.concat, {}, " ", maxi, maxi)
15388 +-- '%' escapes following minus signal
15389 +checkerror("at index %" .. mini, table.concat, {}, " ", mini, mini)
15390 +assert(table.concat{} == "")
15391 +assert(table.concat({}, 'x') == "")
15392 +assert(table.concat({'\0', '\0\1', '\0\1\2'}, '.\0.') == "\0.\0.\0\1.\0.\0\1\2")
15393 +local a = {}; for i=1,300 do a[i] = "xuxu" end
15394 +assert(table.concat(a, "123").."123" == string.rep("xuxu123", 300))
15395 +assert(table.concat(a, "b", 20, 20) == "xuxu")
15396 +assert(table.concat(a, "", 20, 21) == "xuxuxuxu")
15397 +assert(table.concat(a, "x", 22, 21) == "")
15398 +assert(table.concat(a, "3", 299) == "xuxu3xuxu")
15399 +assert(table.concat({}, "x", maxi, maxi - 1) == "")
15400 +assert(table.concat({}, "x", mini + 1, mini) == "")
15401 +assert(table.concat({}, "x", maxi, mini) == "")
15402 +assert(table.concat({[maxi] = "alo"}, "x", maxi, maxi) == "alo")
15403 +assert(table.concat({[maxi] = "alo", [maxi - 1] = "y"}, "-", maxi - 1, maxi)
15404 + == "y-alo")
15405 +
15406 +assert(not pcall(table.concat, {"a", "b", {}}))
15407 +
15408 +a = {"a","b","c"}
15409 +assert(table.concat(a, ",", 1, 0) == "")
15410 +assert(table.concat(a, ",", 1, 1) == "a")
15411 +assert(table.concat(a, ",", 1, 2) == "a,b")
15412 +assert(table.concat(a, ",", 2) == "b,c")
15413 +assert(table.concat(a, ",", 3) == "c")
15414 +assert(table.concat(a, ",", 4) == "")
15415 +
15416 +if not _port then
15417 +
15418 + local locales = { "ptb", "pt_BR.iso88591", "ISO-8859-1" }
15419 + local function trylocale (w)
15420 + for i = 1, #locales do
15421 + if os.setlocale(locales[i], w) then
15422 + print(string.format("'%s' locale set to '%s'", w, locales[i]))
15423 + return locales[i]
15424 + end
15425 + end
15426 + print(string.format("'%s' locale not found", w))
15427 + return false
15428 + end
15429 +
15430 + if trylocale("collate") then
15431 + assert("alo" < "álo" and "álo" < "amo")
15432 + end
15433 +
15434 + if trylocale("ctype") then
15435 + assert(string.gsub("áéíóú", "%a", "x") == "xxxxx")
15436 + assert(string.gsub("áÁéÉ", "%l", "x") == "xÁxÉ")
15437 + assert(string.gsub("áÁéÉ", "%u", "x") == "áxéx")
15438 + assert(string.upper"áÁé{xuxu}ção" == "ÁÁÉ{XUXU}ÇÃO")
15439 + end
15440 +
15441 + os.setlocale("C")
15442 + assert(os.setlocale() == 'C')
15443 + assert(os.setlocale(nil, "numeric") == 'C')
15444 +
15445 +end
15446 +
15447 +
15448 +-- bug in Lua 5.3.2
15449 +-- 'gmatch' iterator does not work across coroutines
15450 +do
15451 + local f = string.gmatch("1 2 3 4 5", "%d+")
15452 + assert(f() == "1")
15453 + co = coroutine.wrap(f)
15454 + assert(co() == "2")
15455 +end
15456 +
15457 +
15458 +if T==nil then
15459 + (Message or print)
15460 + ("\n >>> testC not active: skipping 'pushfstring' tests <<<\n")
15461 +else
15462 +
15463 + print"testing 'pushfstring'"
15464 +
15465 + -- formats %U, %f, %I already tested elsewhere
15466 +
15467 + local blen = 200 -- internal buffer length in 'luaO_pushfstring'
15468 +
15469 + local function callpfs (op, fmt, n)
15470 + local x = {T.testC("pushfstring" .. op .. "; return *", fmt, n)}
15471 + -- stack has code, 'fmt', 'n', and result from operation
15472 + assert(#x == 4) -- make sure nothing else was left in the stack
15473 + return x[4]
15474 + end
15475 +
15476 + local function testpfs (op, fmt, n)
15477 + assert(callpfs(op, fmt, n) == string.format(fmt, n))
15478 + end
15479 +
15480 + testpfs("I", "", 0)
15481 + testpfs("I", string.rep("a", blen - 1), 0)
15482 + testpfs("I", string.rep("a", blen), 0)
15483 + testpfs("I", string.rep("a", blen + 1), 0)
15484 +
15485 + local str = string.rep("ab", blen) .. "%d" .. string.rep("d", blen / 2)
15486 + testpfs("I", str, 2^14)
15487 + testpfs("I", str, -2^15)
15488 +
15489 + str = "%d" .. string.rep("cd", blen)
15490 + testpfs("I", str, 2^14)
15491 + testpfs("I", str, -2^15)
15492 +
15493 + str = string.rep("c", blen - 2) .. "%d"
15494 + testpfs("I", str, 2^14)
15495 + testpfs("I", str, -2^15)
15496 +
15497 + for l = 12, 14 do
15498 + local str1 = string.rep("a", l)
15499 + for i = 0, 500, 13 do
15500 + for j = 0, 500, 13 do
15501 + str = string.rep("a", i) .. "%s" .. string.rep("d", j)
15502 + testpfs("S", str, str1)
15503 + testpfs("S", str, str)
15504 + end
15505 + end
15506 + end
15507 +
15508 + str = "abc %c def"
15509 + testpfs("I", str, string.byte("A"))
15510 + testpfs("I", str, 255)
15511 +
15512 + str = string.rep("a", blen - 1) .. "%p" .. string.rep("cd", blen)
15513 + testpfs("P", str, {})
15514 +
15515 + str = string.rep("%%", 3 * blen) .. "%p" .. string.rep("%%", 2 * blen)
15516 + testpfs("P", str, {})
15517 +end
15518 +
15519 +
15520 +print('OK')
15521 +
15522
15523 diff --git a/tests/tpack.lua b/tests/tpack.lua
15524 new file mode 100644
15525 index 0000000..2b9953f
15526 --- /dev/null
15527 +++ b/tests/tpack.lua
15528 @@ -0,0 +1,322 @@
15529 +-- $Id: testes/tpack.lua $
15530 +-- See Copyright Notice in file all.lua
15531 +
15532 +local pack = string.pack
15533 +local packsize = string.packsize
15534 +local unpack = string.unpack
15535 +
15536 +print "testing pack/unpack"
15537 +
15538 +-- maximum size for integers
15539 +local NB = 16
15540 +
15541 +local sizeshort = packsize("h")
15542 +local sizeint = packsize("i")
15543 +local sizelong = packsize("l")
15544 +local sizesize_t = packsize("T")
15545 +local sizeLI = packsize("j")
15546 +local sizefloat = packsize("f")
15547 +local sizedouble = packsize("d")
15548 +local sizenumber = packsize("n")
15549 +local little = (pack("i2", 1) == "\1\0")
15550 +local align = packsize("!xXi16")
15551 +
15552 +assert(1 <= sizeshort and sizeshort <= sizeint and sizeint <= sizelong and
15553 + sizefloat <= sizedouble)
15554 +
15555 +print("platform:")
15556 +print(string.format(
15557 + "\tshort %d, int %d, long %d, size_t %d, float %d, double %d,\n\z
15558 + \tlua Integer %d, lua Number %d",
15559 + sizeshort, sizeint, sizelong, sizesize_t, sizefloat, sizedouble,
15560 + sizeLI, sizenumber))
15561 +print("\t" .. (little and "little" or "big") .. " endian")
15562 +print("\talignment: " .. align)
15563 +
15564 +
15565 +-- check errors in arguments
15566 +function checkerror (msg, f, ...)
15567 + local status, err = pcall(f, ...)
15568 + -- print(status, err, msg)
15569 + assert(not status and string.find(err, msg))
15570 +end
15571 +
15572 +-- minimum behavior for integer formats
15573 +assert(unpack("B", pack("B", 0xff)) == 0xff)
15574 +assert(unpack("b", pack("b", 0x7f)) == 0x7f)
15575 +assert(unpack("b", pack("b", -0x80)) == -0x80)
15576 +
15577 +assert(unpack("H", pack("H", 0xffff)) == 0xffff)
15578 +assert(unpack("h", pack("h", 0x7fff)) == 0x7fff)
15579 +assert(unpack("h", pack("h", -0x8000)) == -0x8000)
15580 +
15581 +assert(unpack("L", pack("L", 0xffffffff)) == 0xffffffff)
15582 +assert(unpack("l", pack("l", 0x7fffffff)) == 0x7fffffff)
15583 +assert(unpack("l", pack("l", -0x80000000)) == -0x80000000)
15584 +
15585 +
15586 +for i = 1, NB do
15587 + -- small numbers with signal extension ("\xFF...")
15588 + local s = string.rep("\xff", i)
15589 + assert(pack("i" .. i, -1) == s)
15590 + assert(packsize("i" .. i) == #s)
15591 + assert(unpack("i" .. i, s) == -1)
15592 +
15593 + -- small unsigned number ("\0...\xAA")
15594 + s = "\xAA" .. string.rep("\0", i - 1)
15595 + assert(pack("<I" .. i, 0xAA) == s)
15596 + assert(unpack("<I" .. i, s) == 0xAA)
15597 + assert(pack(">I" .. i, 0xAA) == s:reverse())
15598 + assert(unpack(">I" .. i, s:reverse()) == 0xAA)
15599 +end
15600 +
15601 +do
15602 + local lnum = 0x13121110090807060504030201
15603 + local s = pack("<j", lnum)
15604 + assert(unpack("<j", s) == lnum)
15605 + assert(unpack("<i" .. sizeLI + 1, s .. "\0") == lnum)
15606 + assert(unpack("<i" .. sizeLI + 1, s .. "\0") == lnum)
15607 +
15608 + for i = sizeLI + 1, NB do
15609 + local s = pack("<j", -lnum)
15610 + assert(unpack("<j", s) == -lnum)
15611 + -- strings with (correct) extra bytes
15612 + assert(unpack("<i" .. i, s .. ("\xFF"):rep(i - sizeLI)) == -lnum)
15613 + assert(unpack(">i" .. i, ("\xFF"):rep(i - sizeLI) .. s:reverse()) == -lnum)
15614 + assert(unpack("<I" .. i, s .. ("\0"):rep(i - sizeLI)) == -lnum)
15615 +
15616 + -- overflows
15617 + checkerror("does not fit", unpack, "<I" .. i, ("\x00"):rep(i - 1) .. "\1")
15618 + checkerror("does not fit", unpack, ">i" .. i, "\1" .. ("\x00"):rep(i - 1))
15619 + end
15620 +end
15621 +
15622 +for i = 1, sizeLI do
15623 + local lstr = "\1\2\3\4\5\6\7\8\9\10\11\12\13"
15624 + local lnum = 0x13121110090807060504030201
15625 + local n = lnum & (~(-1 << (i * 8)))
15626 + local s = string.sub(lstr, 1, i)
15627 + assert(pack("<i" .. i, n) == s)
15628 + assert(pack(">i" .. i, n) == s:reverse())
15629 + assert(unpack(">i" .. i, s:reverse()) == n)
15630 +end
15631 +
15632 +-- sign extension
15633 +do
15634 + local u = 0xf0
15635 + for i = 1, sizeLI - 1 do
15636 + assert(unpack("<i"..i, "\xf0"..("\xff"):rep(i - 1)) == -16)
15637 + assert(unpack(">I"..i, "\xf0"..("\xff"):rep(i - 1)) == u)
15638 + u = u * 256 + 0xff
15639 + end
15640 +end
15641 +
15642 +-- mixed endianness
15643 +do
15644 + assert(pack(">i2 <i2", 10, 20) == "\0\10\20\0")
15645 + local a, b = unpack("<i2 >i2", "\10\0\0\20")
15646 + assert(a == 10 and b == 20)
15647 + assert(pack("=i4", 2001) == pack("i4", 2001))
15648 +end
15649 +
15650 +print("testing invalid formats")
15651 +
15652 +checkerror("out of limits", pack, "i0", 0)
15653 +checkerror("out of limits", pack, "i" .. NB + 1, 0)
15654 +checkerror("out of limits", pack, "!" .. NB + 1, 0)
15655 +checkerror("%(17%) out of limits %[1,16%]", pack, "Xi" .. NB + 1)
15656 +checkerror("invalid format option 'r'", pack, "i3r", 0)
15657 +checkerror("16%-byte integer", unpack, "i16", string.rep('\3', 16))
15658 +checkerror("not power of 2", pack, "!4i3", 0);
15659 +checkerror("missing size", pack, "c", "")
15660 +checkerror("variable%-length format", packsize, "s")
15661 +checkerror("variable%-length format", packsize, "z")
15662 +
15663 +-- overflow in option size (error will be in digit after limit)
15664 +checkerror("invalid format", packsize, "c1" .. string.rep("0", 40))
15665 +
15666 +if packsize("i") == 4 then
15667 + -- result would be 2^31 (2^3 repetitions of 2^28 strings)
15668 + local s = string.rep("c268435456", 2^3)
15669 + checkerror("too large", packsize, s)
15670 + -- one less is OK
15671 + s = string.rep("c268435456", 2^3 - 1) .. "c268435455"
15672 + assert(packsize(s) == 0x7fffffff)
15673 +end
15674 +
15675 +-- overflow in packing
15676 +for i = 1, sizeLI - 1 do
15677 + local umax = (1 << (i * 8)) - 1
15678 + local max = umax >> 1
15679 + local min = ~max
15680 + checkerror("overflow", pack, "<I" .. i, -1)
15681 + checkerror("overflow", pack, "<I" .. i, min)
15682 + checkerror("overflow", pack, ">I" .. i, umax + 1)
15683 +
15684 + checkerror("overflow", pack, ">i" .. i, umax)
15685 + checkerror("overflow", pack, ">i" .. i, max + 1)
15686 + checkerror("overflow", pack, "<i" .. i, min - 1)
15687 +
15688 + assert(unpack(">i" .. i, pack(">i" .. i, max)) == max)
15689 + assert(unpack("<i" .. i, pack("<i" .. i, min)) == min)
15690 + assert(unpack(">I" .. i, pack(">I" .. i, umax)) == umax)
15691 +end
15692 +
15693 +-- Lua integer size
15694 +assert(unpack(">j", pack(">j", math.maxinteger)) == math.maxinteger)
15695 +assert(unpack("<j", pack("<j", math.mininteger)) == math.mininteger)
15696 +assert(unpack("<J", pack("<j", -1)) == -1) -- maximum unsigned integer
15697 +
15698 +if little then
15699 + assert(pack("f", 24) == pack("<f", 24))
15700 +else
15701 + assert(pack("f", 24) == pack(">f", 24))
15702 +end
15703 +
15704 +print "testing pack/unpack of floating-point numbers"
15705 +
15706 +for _, n in ipairs{0, -1.1, 1.9, 1/0, -1/0, 1e20, -1e20, 0.1, 2000.7} do
15707 + assert(unpack("n", pack("n", n)) == n)
15708 + assert(unpack("<n", pack("<n", n)) == n)
15709 + assert(unpack(">n", pack(">n", n)) == n)
15710 + assert(pack("<f", n) == pack(">f", n):reverse())
15711 + assert(pack(">d", n) == pack("<d", n):reverse())
15712 +end
15713 +
15714 +-- for non-native precisions, test only with "round" numbers
15715 +for _, n in ipairs{0, -1.5, 1/0, -1/0, 1e10, -1e9, 0.5, 2000.25} do
15716 + assert(unpack("<f", pack("<f", n)) == n)
15717 + assert(unpack(">f", pack(">f", n)) == n)
15718 + assert(unpack("<d", pack("<d", n)) == n)
15719 + assert(unpack(">d", pack(">d", n)) == n)
15720 +end
15721 +
15722 +print "testing pack/unpack of strings"
15723 +do
15724 + local s = string.rep("abc", 1000)
15725 + assert(pack("zB", s, 247) == s .. "\0\xF7")
15726 + local s1, b = unpack("zB", s .. "\0\xF9")
15727 + assert(b == 249 and s1 == s)
15728 + s1 = pack("s", s)
15729 + assert(unpack("s", s1) == s)
15730 +
15731 + checkerror("does not fit", pack, "s1", s)
15732 +
15733 + checkerror("contains zeros", pack, "z", "alo\0");
15734 +
15735 + checkerror("unfinished string", unpack, "zc10000000", "alo")
15736 +
15737 + for i = 2, NB do
15738 + local s1 = pack("s" .. i, s)
15739 + assert(unpack("s" .. i, s1) == s and #s1 == #s + i)
15740 + end
15741 +end
15742 +
15743 +do
15744 + local x = pack("s", "alo")
15745 + checkerror("too short", unpack, "s", x:sub(1, -2))
15746 + checkerror("too short", unpack, "c5", "abcd")
15747 + checkerror("out of limits", pack, "s100", "alo")
15748 +end
15749 +
15750 +do
15751 + assert(pack("c0", "") == "")
15752 + assert(packsize("c0") == 0)
15753 + assert(unpack("c0", "") == "")
15754 + assert(pack("<! c3", "abc") == "abc")
15755 + assert(packsize("<! c3") == 3)
15756 + assert(pack(">!4 c6", "abcdef") == "abcdef")
15757 + assert(pack("c3", "123") == "123")
15758 + assert(pack("c0", "") == "")
15759 + assert(pack("c8", "123456") == "123456\0\0")
15760 + assert(pack("c88", "") == string.rep("\0", 88))
15761 + assert(pack("c188", "ab") == "ab" .. string.rep("\0", 188 - 2))
15762 + local a, b, c = unpack("!4 z c3", "abcdefghi\0xyz")
15763 + assert(a == "abcdefghi" and b == "xyz" and c == 14)
15764 + checkerror("longer than", pack, "c3", "1234")
15765 +end
15766 +
15767 +
15768 +-- testing multiple types and sequence
15769 +do
15770 + local x = pack("<b h b f d f n i", 1, 2, 3, 4, 5, 6, 7, 8)
15771 + assert(#x == packsize("<b h b f d f n i"))
15772 + local a, b, c, d, e, f, g, h = unpack("<b h b f d f n i", x)
15773 + assert(a == 1 and b == 2 and c == 3 and d == 4 and e == 5 and f == 6 and
15774 + g == 7 and h == 8)
15775 +end
15776 +
15777 +print "testing alignment"
15778 +do
15779 + assert(pack(" < i1 i2 ", 2, 3) == "\2\3\0") -- no alignment by default
15780 + local x = pack(">!8 b Xh i4 i8 c1 Xi8", -12, 100, 200, "\xEC")
15781 + assert(#x == packsize(">!8 b Xh i4 i8 c1 Xi8"))
15782 + assert(x == "\xf4" .. "\0\0\0" ..
15783 + "\0\0\0\100" ..
15784 + "\0\0\0\0\0\0\0\xC8" ..
15785 + "\xEC" .. "\0\0\0\0\0\0\0")
15786 + local a, b, c, d, pos = unpack(">!8 c1 Xh i4 i8 b Xi8 XI XH", x)
15787 + assert(a == "\xF4" and b == 100 and c == 200 and d == -20 and (pos - 1) == #x)
15788 +
15789 + x = pack(">!4 c3 c4 c2 z i4 c5 c2 Xi4",
15790 + "abc", "abcd", "xz", "hello", 5, "world", "xy")
15791 + assert(x == "abcabcdxzhello\0\0\0\0\0\5worldxy\0")
15792 + local a, b, c, d, e, f, g, pos = unpack(">!4 c3 c4 c2 z i4 c5 c2 Xh Xi4", x)
15793 + assert(a == "abc" and b == "abcd" and c == "xz" and d == "hello" and
15794 + e == 5 and f == "world" and g == "xy" and (pos - 1) % 4 == 0)
15795 +
15796 + x = pack(" b b Xd b Xb x", 1, 2, 3)
15797 + assert(packsize(" b b Xd b Xb x") == 4)
15798 + assert(x == "\1\2\3\0")
15799 + a, b, c, pos = unpack("bbXdb", x)
15800 + assert(a == 1 and b == 2 and c == 3 and pos == #x)
15801 +
15802 + -- only alignment
15803 + assert(packsize("!8 xXi8") == 8)
15804 + local pos = unpack("!8 xXi8", "0123456701234567"); assert(pos == 9)
15805 + assert(packsize("!8 xXi2") == 2)
15806 + local pos = unpack("!8 xXi2", "0123456701234567"); assert(pos == 3)
15807 + assert(packsize("!2 xXi2") == 2)
15808 + local pos = unpack("!2 xXi2", "0123456701234567"); assert(pos == 3)
15809 + assert(packsize("!2 xXi8") == 2)
15810 + local pos = unpack("!2 xXi8", "0123456701234567"); assert(pos == 3)
15811 + assert(packsize("!16 xXi16") == 16)
15812 + local pos = unpack("!16 xXi16", "0123456701234567"); assert(pos == 17)
15813 +
15814 + checkerror("invalid next option", pack, "X")
15815 + checkerror("invalid next option", unpack, "XXi", "")
15816 + checkerror("invalid next option", unpack, "X i", "")
15817 + checkerror("invalid next option", pack, "Xc1")
15818 +end
15819 +
15820 +do -- testing initial position
15821 + local x = pack("i4i4i4i4", 1, 2, 3, 4)
15822 + for pos = 1, 16, 4 do
15823 + local i, p = unpack("i4", x, pos)
15824 + assert(i == pos//4 + 1 and p == pos + 4)
15825 + end
15826 +
15827 + -- with alignment
15828 + for pos = 0, 12 do -- will always round position to power of 2
15829 + local i, p = unpack("!4 i4", x, pos + 1)
15830 + assert(i == (pos + 3)//4 + 1 and p == i*4 + 1)
15831 + end
15832 +
15833 + -- negative indices
15834 + local i, p = unpack("!4 i4", x, -4)
15835 + assert(i == 4 and p == 17)
15836 + local i, p = unpack("!4 i4", x, -7)
15837 + assert(i == 4 and p == 17)
15838 + local i, p = unpack("!4 i4", x, -#x)
15839 + assert(i == 1 and p == 5)
15840 +
15841 + -- limits
15842 + for i = 1, #x + 1 do
15843 + assert(unpack("c0", x, i) == "")
15844 + end
15845 + checkerror("out of string", unpack, "c0", x, #x + 2)
15846 +
15847 +end
15848 +
15849 +print "OK"
15850 +
15851
15852 diff --git a/tests/tracegc.lua b/tests/tracegc.lua
15853 new file mode 100644
15854 index 0000000..9c5c1b3
15855 --- /dev/null
15856 +++ b/tests/tracegc.lua
15857 @@ -0,0 +1,40 @@
15858 +-- track collections
15859 +
15860 +local M = {}
15861 +
15862 +-- import list
15863 +local setmetatable, stderr, collectgarbage =
15864 + setmetatable, io.stderr, collectgarbage
15865 +
15866 +_ENV = nil
15867 +
15868 +local active = false
15869 +
15870 +
15871 +-- each time a table is collected, remark it for finalization on next
15872 +-- cycle
15873 +local mt = {}
15874 +function mt.__gc (o)
15875 + stderr:write'.' -- mark progress
15876 + if active then
15877 + setmetatable(o, mt) -- remark object for finalization
15878 + end
15879 +end
15880 +
15881 +
15882 +function M.start ()
15883 + if not active then
15884 + active = true
15885 + setmetatable({}, mt) -- create initial object
15886 + end
15887 +end
15888 +
15889 +
15890 +function M.stop ()
15891 + if active then
15892 + active = false
15893 + collectgarbage() -- call finalizer for the last time
15894 + end
15895 +end
15896 +
15897 +return M
15898
15899 diff --git a/tests/utf8.lua b/tests/utf8.lua
15900 new file mode 100644
15901 index 0000000..461e223
15902 --- /dev/null
15903 +++ b/tests/utf8.lua
15904 @@ -0,0 +1,247 @@
15905 +-- $Id: testes/utf8.lua $
15906 +-- See Copyright Notice in file all.lua
15907 +
15908 +print "testing UTF-8 library"
15909 +
15910 +local utf8 = require'utf8'
15911 +
15912 +
15913 +local function checkerror (msg, f, ...)
15914 + local s, err = pcall(f, ...)
15915 + assert(not s and string.find(err, msg))
15916 +end
15917 +
15918 +
15919 +local function len (s)
15920 + return #string.gsub(s, "[\x80-\xBF]", "")
15921 +end
15922 +
15923 +
15924 +local justone = "^" .. utf8.charpattern .. "$"
15925 +
15926 +-- 't' is the list of codepoints of 's'
15927 +local function checksyntax (s, t)
15928 + -- creates a string "return '\u{t[1]}...\u{t[n]}'"
15929 + local ts = {"return '"}
15930 + for i = 1, #t do ts[i + 1] = string.format("\\u{%x}", t[i]) end
15931 + ts[#t + 2] = "'"
15932 + ts = table.concat(ts)
15933 + -- its execution should result in 's'
15934 + assert(assert(load(ts))() == s)
15935 +end
15936 +
15937 +assert(not utf8.offset("alo", 5))
15938 +assert(not utf8.offset("alo", -4))
15939 +
15940 +-- 'check' makes several tests over the validity of string 's'.
15941 +-- 't' is the list of codepoints of 's'.
15942 +local function check (s, t, nonstrict)
15943 + local l = utf8.len(s, 1, -1, nonstrict)
15944 + assert(#t == l and len(s) == l)
15945 + assert(utf8.char(table.unpack(t)) == s) -- 't' and 's' are equivalent
15946 +
15947 + assert(utf8.offset(s, 0) == 1)
15948 +
15949 + checksyntax(s, t)
15950 +
15951 + -- creates new table with all codepoints of 's'
15952 + local t1 = {utf8.codepoint(s, 1, -1, nonstrict)}
15953 + assert(#t == #t1)
15954 + for i = 1, #t do assert(t[i] == t1[i]) end -- 't' is equal to 't1'
15955 +
15956 + for i = 1, l do -- for all codepoints
15957 + local pi = utf8.offset(s, i) -- position of i-th char
15958 + local pi1 = utf8.offset(s, 2, pi) -- position of next char
15959 + assert(string.find(string.sub(s, pi, pi1 - 1), justone))
15960 + assert(utf8.offset(s, -1, pi1) == pi)
15961 + assert(utf8.offset(s, i - l - 1) == pi)
15962 + assert(pi1 - pi == #utf8.char(utf8.codepoint(s, pi, pi, nonstrict)))
15963 + for j = pi, pi1 - 1 do
15964 + assert(utf8.offset(s, 0, j) == pi)
15965 + end
15966 + for j = pi + 1, pi1 - 1 do
15967 + assert(not utf8.len(s, j))
15968 + end
15969 + assert(utf8.len(s, pi, pi, nonstrict) == 1)
15970 + assert(utf8.len(s, pi, pi1 - 1, nonstrict) == 1)
15971 + assert(utf8.len(s, pi, -1, nonstrict) == l - i + 1)
15972 + assert(utf8.len(s, pi1, -1, nonstrict) == l - i)
15973 + assert(utf8.len(s, 1, pi, nonstrict) == i)
15974 + end
15975 +
15976 + local i = 0
15977 + for p, c in utf8.codes(s, nonstrict) do
15978 + i = i + 1
15979 + assert(c == t[i] and p == utf8.offset(s, i))
15980 + assert(utf8.codepoint(s, p, p, nonstrict) == c)
15981 + end
15982 + assert(i == #t)
15983 +
15984 + i = 0
15985 + for c in string.gmatch(s, utf8.charpattern) do
15986 + i = i + 1
15987 + assert(c == utf8.char(t[i]))
15988 + end
15989 + assert(i == #t)
15990 +
15991 + for i = 1, l do
15992 + assert(utf8.offset(s, i) == utf8.offset(s, i - l - 1, #s + 1))
15993 + end
15994 +
15995 +end
15996 +
15997 +
15998 +do -- error indication in utf8.len
15999 + local function check (s, p)
16000 + local a, b = utf8.len(s)
16001 + assert(not a and b == p)
16002 + end
16003 + check("abc\xE3def", 4)
16004 + check("汉字\x80", #("汉字") + 1)
16005 + check("\xF4\x9F\xBF", 1)
16006 + check("\xF4\x9F\xBF\xBF", 1)
16007 +end
16008 +
16009 +-- errors in utf8.codes
16010 +do
16011 + local function errorcodes (s)
16012 + checkerror("invalid UTF%-8 code",
16013 + function ()
16014 + for c in utf8.codes(s) do assert(c) end
16015 + end)
16016 + end
16017 + errorcodes("ab\xff")
16018 + errorcodes("\u{110000}")
16019 +
16020 + -- calling interation function with invalid arguments
16021 + local f = utf8.codes("")
16022 + assert(f("", 2) == nil)
16023 + assert(f("", -1) == nil)
16024 + assert(f("", math.mininteger) == nil)
16025 +end
16026 +
16027 +-- error in initial position for offset
16028 +checkerror("position out of bounds", utf8.offset, "abc", 1, 5)
16029 +checkerror("position out of bounds", utf8.offset, "abc", 1, -4)
16030 +checkerror("position out of bounds", utf8.offset, "", 1, 2)
16031 +checkerror("position out of bounds", utf8.offset, "", 1, -1)
16032 +checkerror("continuation byte", utf8.offset, "𦧺", 1, 2)
16033 +checkerror("continuation byte", utf8.offset, "𦧺", 1, 2)
16034 +checkerror("continuation byte", utf8.offset, "\x80", 1)
16035 +
16036 +-- error in indices for len
16037 +checkerror("out of bounds", utf8.len, "abc", 0, 2)
16038 +checkerror("out of bounds", utf8.len, "abc", 1, 4)
16039 +
16040 +
16041 +local s = "hello World"
16042 +local t = {string.byte(s, 1, -1)}
16043 +for i = 1, utf8.len(s) do assert(t[i] == string.byte(s, i)) end
16044 +check(s, t)
16045 +
16046 +check("汉字/漢字", {27721, 23383, 47, 28450, 23383,})
16047 +
16048 +do
16049 + local s = "áéí\128"
16050 + local t = {utf8.codepoint(s,1,#s - 1)}
16051 + assert(#t == 3 and t[1] == 225 and t[2] == 233 and t[3] == 237)
16052 + checkerror("invalid UTF%-8 code", utf8.codepoint, s, 1, #s)
16053 + checkerror("out of bounds", utf8.codepoint, s, #s + 1)
16054 + t = {utf8.codepoint(s, 4, 3)}
16055 + assert(#t == 0)
16056 + checkerror("out of bounds", utf8.codepoint, s, -(#s + 1), 1)
16057 + checkerror("out of bounds", utf8.codepoint, s, 1, #s + 1)
16058 + -- surrogates
16059 + assert(utf8.codepoint("\u{D7FF}") == 0xD800 - 1)
16060 + assert(utf8.codepoint("\u{E000}") == 0xDFFF + 1)
16061 + assert(utf8.codepoint("\u{D800}", 1, 1, true) == 0xD800)
16062 + assert(utf8.codepoint("\u{DFFF}", 1, 1, true) == 0xDFFF)
16063 + assert(utf8.codepoint("\u{7FFFFFFF}", 1, 1, true) == 0x7FFFFFFF)
16064 +end
16065 +
16066 +assert(utf8.char() == "")
16067 +assert(utf8.char(0, 97, 98, 99, 1) == "\0abc\1")
16068 +
16069 +assert(utf8.codepoint(utf8.char(0x10FFFF)) == 0x10FFFF)
16070 +assert(utf8.codepoint(utf8.char(0x7FFFFFFF), 1, 1, true) == (1<<31) - 1)
16071 +
16072 +checkerror("value out of range", utf8.char, 0x7FFFFFFF + 1)
16073 +checkerror("value out of range", utf8.char, -1)
16074 +
16075 +local function invalid (s)
16076 + checkerror("invalid UTF%-8 code", utf8.codepoint, s)
16077 + assert(not utf8.len(s))
16078 +end
16079 +
16080 +-- UTF-8 representation for 0x11ffff (value out of valid range)
16081 +invalid("\xF4\x9F\xBF\xBF")
16082 +
16083 +-- surrogates
16084 +invalid("\u{D800}")
16085 +invalid("\u{DFFF}")
16086 +
16087 +-- overlong sequences
16088 +invalid("\xC0\x80") -- zero
16089 +invalid("\xC1\xBF") -- 0x7F (should be coded in 1 byte)
16090 +invalid("\xE0\x9F\xBF") -- 0x7FF (should be coded in 2 bytes)
16091 +invalid("\xF0\x8F\xBF\xBF") -- 0xFFFF (should be coded in 3 bytes)
16092 +
16093 +
16094 +-- invalid bytes
16095 +invalid("\x80") -- continuation byte
16096 +invalid("\xBF") -- continuation byte
16097 +invalid("\xFE") -- invalid byte
16098 +invalid("\xFF") -- invalid byte
16099 +
16100 +
16101 +-- empty string
16102 +check("", {})
16103 +
16104 +-- minimum and maximum values for each sequence size
16105 +s = "\0 \x7F\z
16106 + \xC2\x80 \xDF\xBF\z
16107 + \xE0\xA0\x80 \xEF\xBF\xBF\z
16108 + \xF0\x90\x80\x80 \xF4\x8F\xBF\xBF"
16109 +s = string.gsub(s, " ", "")
16110 +check(s, {0,0x7F, 0x80,0x7FF, 0x800,0xFFFF, 0x10000,0x10FFFF})
16111 +
16112 +do
16113 + -- original UTF-8 values
16114 + local s = "\u{4000000}\u{7FFFFFFF}"
16115 + assert(#s == 12)
16116 + check(s, {0x4000000, 0x7FFFFFFF}, true)
16117 +
16118 + s = "\u{200000}\u{3FFFFFF}"
16119 + assert(#s == 10)
16120 + check(s, {0x200000, 0x3FFFFFF}, true)
16121 +
16122 + s = "\u{10000}\u{1fffff}"
16123 + assert(#s == 8)
16124 + check(s, {0x10000, 0x1FFFFF}, true)
16125 +end
16126 +
16127 +x = "日本語a-4\0éó"
16128 +check(x, {26085, 26412, 35486, 97, 45, 52, 0, 233, 243})
16129 +
16130 +
16131 +-- Supplementary Characters
16132 +check("𣲷𠜎𠱓𡁻𠵼ab𠺢",
16133 + {0x23CB7, 0x2070E, 0x20C53, 0x2107B, 0x20D7C, 0x61, 0x62, 0x20EA2,})
16134 +
16135 +check("𨳊𩶘𦧺𨳒𥄫𤓓\xF4\x8F\xBF\xBF",
16136 + {0x28CCA, 0x29D98, 0x269FA, 0x28CD2, 0x2512B, 0x244D3, 0x10ffff})
16137 +
16138 +
16139 +local i = 0
16140 +for p, c in string.gmatch(x, "()(" .. utf8.charpattern .. ")") do
16141 + i = i + 1
16142 + assert(utf8.offset(x, i) == p)
16143 + assert(utf8.len(x, p) == utf8.len(x) - i + 1)
16144 + assert(utf8.len(c) == 1)
16145 + for j = 1, #c - 1 do
16146 + assert(utf8.offset(x, 0, p + j - 1) == p)
16147 + end
16148 +end
16149 +
16150 +print'ok'
16151 +
16152
16153 diff --git a/tests/vararg.lua b/tests/vararg.lua
16154 new file mode 100644
16155 index 0000000..44848d2
16156 --- /dev/null
16157 +++ b/tests/vararg.lua
16158 @@ -0,0 +1,151 @@
16159 +-- $Id: testes/vararg.lua $
16160 +-- See Copyright Notice in file all.lua
16161 +
16162 +print('testing vararg')
16163 +
16164 +function f(a, ...)
16165 + local x = {n = select('#', ...), ...}
16166 + for i = 1, x.n do assert(a[i] == x[i]) end
16167 + return x.n
16168 +end
16169 +
16170 +function c12 (...)
16171 + assert(arg == _G.arg) -- no local 'arg'
16172 + local x = {...}; x.n = #x
16173 + local res = (x.n==2 and x[1] == 1 and x[2] == 2)
16174 + if res then res = 55 end
16175 + return res, 2
16176 +end
16177 +
16178 +function vararg (...) return {n = select('#', ...), ...} end
16179 +
16180 +local call = function (f, args) return f(table.unpack(args, 1, args.n)) end
16181 +
16182 +assert(f() == 0)
16183 +assert(f({1,2,3}, 1, 2, 3) == 3)
16184 +assert(f({"alo", nil, 45, f, nil}, "alo", nil, 45, f, nil) == 5)
16185 +
16186 +assert(vararg().n == 0)
16187 +assert(vararg(nil, nil).n == 2)
16188 +
16189 +assert(c12(1,2)==55)
16190 +a,b = assert(call(c12, {1,2}))
16191 +assert(a == 55 and b == 2)
16192 +a = call(c12, {1,2;n=2})
16193 +assert(a == 55 and b == 2)
16194 +a = call(c12, {1,2;n=1})
16195 +assert(not a)
16196 +assert(c12(1,2,3) == false)
16197 +local a = vararg(call(next, {_G,nil;n=2}))
16198 +local b,c = next(_G)
16199 +assert(a[1] == b and a[2] == c and a.n == 2)
16200 +a = vararg(call(call, {c12, {1,2}}))
16201 +assert(a.n == 2 and a[1] == 55 and a[2] == 2)
16202 +a = call(print, {'+'})
16203 +assert(a == nil)
16204 +
16205 +local t = {1, 10}
16206 +function t:f (...) local arg = {...}; return self[...]+#arg end
16207 +assert(t:f(1,4) == 3 and t:f(2) == 11)
16208 +print('+')
16209 +
16210 +lim = 20
16211 +local i, a = 1, {}
16212 +while i <= lim do a[i] = i+0.3; i=i+1 end
16213 +
16214 +function f(a, b, c, d, ...)
16215 + local more = {...}
16216 + assert(a == 1.3 and more[1] == 5.3 and
16217 + more[lim-4] == lim+0.3 and not more[lim-3])
16218 +end
16219 +
16220 +function g(a,b,c)
16221 + assert(a == 1.3 and b == 2.3 and c == 3.3)
16222 +end
16223 +
16224 +call(f, a)
16225 +call(g, a)
16226 +
16227 +a = {}
16228 +i = 1
16229 +while i <= lim do a[i] = i; i=i+1 end
16230 +assert(call(math.max, a) == lim)
16231 +
16232 +print("+")
16233 +
16234 +
16235 +-- new-style varargs
16236 +
16237 +function oneless (a, ...) return ... end
16238 +
16239 +function f (n, a, ...)
16240 + local b
16241 + assert(arg == _G.arg) -- no local 'arg'
16242 + if n == 0 then
16243 + local b, c, d = ...
16244 + return a, b, c, d, oneless(oneless(oneless(...)))
16245 + else
16246 + n, b, a = n-1, ..., a
16247 + assert(b == ...)
16248 + return f(n, a, ...)
16249 + end
16250 +end
16251 +
16252 +a,b,c,d,e = assert(f(10,5,4,3,2,1))
16253 +assert(a==5 and b==4 and c==3 and d==2 and e==1)
16254 +
16255 +a,b,c,d,e = f(4)
16256 +assert(a==nil and b==nil and c==nil and d==nil and e==nil)
16257 +
16258 +
16259 +-- varargs for main chunks
16260 +f = load[[ return {...} ]]
16261 +x = f(2,3)
16262 +assert(x[1] == 2 and x[2] == 3 and x[3] == undef)
16263 +
16264 +
16265 +f = load[[
16266 + local x = {...}
16267 + for i=1,select('#', ...) do assert(x[i] == select(i, ...)) end
16268 + assert(x[select('#', ...)+1] == undef)
16269 + return true
16270 +]]
16271 +
16272 +assert(f("a", "b", nil, {}, assert))
16273 +assert(f())
16274 +
16275 +a = {select(3, table.unpack{10,20,30,40})}
16276 +assert(#a == 2 and a[1] == 30 and a[2] == 40)
16277 +a = {select(1)}
16278 +assert(next(a) == nil)
16279 +a = {select(-1, 3, 5, 7)}
16280 +assert(a[1] == 7 and a[2] == undef)
16281 +a = {select(-2, 3, 5, 7)}
16282 +assert(a[1] == 5 and a[2] == 7 and a[3] == undef)
16283 +pcall(select, 10000)
16284 +pcall(select, -10000)
16285 +
16286 +
16287 +-- bug in 5.2.2
16288 +
16289 +function f(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10,
16290 +p11, p12, p13, p14, p15, p16, p17, p18, p19, p20,
16291 +p21, p22, p23, p24, p25, p26, p27, p28, p29, p30,
16292 +p31, p32, p33, p34, p35, p36, p37, p38, p39, p40,
16293 +p41, p42, p43, p44, p45, p46, p48, p49, p50, ...)
16294 + local a1,a2,a3,a4,a5,a6,a7
16295 + local a8,a9,a10,a11,a12,a13,a14
16296 +end
16297 +
16298 +-- assertion fail here
16299 +f()
16300 +
16301 +-- missing arguments in tail call
16302 +do
16303 + local function f(a,b,c) return c, b end
16304 + local function g() return f(1,2) end
16305 + local a, b = g()
16306 + assert(a == nil and b == 2)
16307 +end
16308 +print('OK')
16309 +
16310
16311 diff --git a/tests/verybig.lua b/tests/verybig.lua
16312 new file mode 100644
16313 index 0000000..8fb7b13
16314 --- /dev/null
16315 +++ b/tests/verybig.lua
16316 @@ -0,0 +1,152 @@
16317 +-- $Id: testes/verybig.lua $
16318 +-- See Copyright Notice in file all.lua
16319 +
16320 +print "testing RK"
16321 +
16322 +-- testing opcodes with RK arguments larger than K limit
16323 +local function foo ()
16324 + local dummy = {
16325 + -- fill first 256 entries in table of constants
16326 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
16327 + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
16328 + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
16329 + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
16330 + 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
16331 + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
16332 + 97, 98, 99, 100, 101, 102, 103, 104,
16333 + 105, 106, 107, 108, 109, 110, 111, 112,
16334 + 113, 114, 115, 116, 117, 118, 119, 120,
16335 + 121, 122, 123, 124, 125, 126, 127, 128,
16336 + 129, 130, 131, 132, 133, 134, 135, 136,
16337 + 137, 138, 139, 140, 141, 142, 143, 144,
16338 + 145, 146, 147, 148, 149, 150, 151, 152,
16339 + 153, 154, 155, 156, 157, 158, 159, 160,
16340 + 161, 162, 163, 164, 165, 166, 167, 168,
16341 + 169, 170, 171, 172, 173, 174, 175, 176,
16342 + 177, 178, 179, 180, 181, 182, 183, 184,
16343 + 185, 186, 187, 188, 189, 190, 191, 192,
16344 + 193, 194, 195, 196, 197, 198, 199, 200,
16345 + 201, 202, 203, 204, 205, 206, 207, 208,
16346 + 209, 210, 211, 212, 213, 214, 215, 216,
16347 + 217, 218, 219, 220, 221, 222, 223, 224,
16348 + 225, 226, 227, 228, 229, 230, 231, 232,
16349 + 233, 234, 235, 236, 237, 238, 239, 240,
16350 + 241, 242, 243, 244, 245, 246, 247, 248,
16351 + 249, 250, 251, 252, 253, 254, 255, 256,
16352 + }
16353 + assert(24.5 + 0.6 == 25.1)
16354 + local t = {foo = function (self, x) return x + self.x end, x = 10}
16355 + t.t = t
16356 + assert(t:foo(1.5) == 11.5)
16357 + assert(t.t:foo(0.5) == 10.5) -- bug in 5.2 alpha
16358 + assert(24.3 == 24.3)
16359 + assert((function () return t.x end)() == 10)
16360 +end
16361 +
16362 +
16363 +foo()
16364 +foo = nil
16365 +
16366 +if _soft then return 10 end
16367 +
16368 +print "testing large programs (>64k)"
16369 +
16370 +-- template to create a very big test file
16371 +prog = [[$
16372 +
16373 +local a,b
16374 +
16375 +b = {$1$
16376 + b30009 = 65534,
16377 + b30010 = 65535,
16378 + b30011 = 65536,
16379 + b30012 = 65537,
16380 + b30013 = 16777214,
16381 + b30014 = 16777215,
16382 + b30015 = 16777216,
16383 + b30016 = 16777217,
16384 + b30017 = 0x7fffff,
16385 + b30018 = -0x7fffff,
16386 + b30019 = 0x1ffffff,
16387 + b30020 = -0x1ffffd,
16388 + b30021 = -65534,
16389 + b30022 = -65535,
16390 + b30023 = -65536,
16391 + b30024 = -0xffffff,
16392 + b30025 = 15012.5,
16393 + $2$
16394 +};
16395 +
16396 +assert(b.a50008 == 25004 and b["a11"] == -5.5)
16397 +assert(b.a33007 == -16503.5 and b.a50009 == -25004.5)
16398 +assert(b["b"..30024] == -0xffffff)
16399 +
16400 +function b:xxx (a,b) return a+b end
16401 +assert(b:xxx(10, 12) == 22) -- pushself with non-constant index
16402 +b["xxx"] = undef
16403 +
16404 +s = 0; n=0
16405 +for a,b in pairs(b) do s=s+b; n=n+1 end
16406 +-- with 32-bit floats, exact value of 's' depends on summation order
16407 +assert(81800000.0 < s and s < 81860000 and n == 70001)
16408 +
16409 +a = nil; b = nil
16410 +print'+'
16411 +
16412 +function f(x) b=x end
16413 +
16414 +a = f{$3$} or 10
16415 +
16416 +assert(a==10)
16417 +assert(b[1] == "a10" and b[2] == 5 and b[#b-1] == "a50009")
16418 +
16419 +
16420 +function xxxx (x) return b[x] end
16421 +
16422 +assert(xxxx(3) == "a11")
16423 +
16424 +a = nil; b=nil
16425 +xxxx = nil
16426 +
16427 +return 10
16428 +
16429 +]]
16430 +
16431 +-- functions to fill in the $n$
16432 +
16433 +local function sig (x)
16434 + return (x % 2 == 0) and '' or '-'
16435 +end
16436 +
16437 +F = {
16438 +function () -- $1$
16439 + for i=10,50009 do
16440 + io.write('a', i, ' = ', sig(i), 5+((i-10)/2), ',\n')
16441 + end
16442 +end,
16443 +
16444 +function () -- $2$
16445 + for i=30026,50009 do
16446 + io.write('b', i, ' = ', sig(i), 15013+((i-30026)/2), ',\n')
16447 + end
16448 +end,
16449 +
16450 +function () -- $3$
16451 + for i=10,50009 do
16452 + io.write('"a', i, '", ', sig(i), 5+((i-10)/2), ',\n')
16453 + end
16454 +end,
16455 +}
16456 +
16457 +file = os.tmpname()
16458 +io.output(file)
16459 +for s in string.gmatch(prog, "$([^$]+)") do
16460 + local n = tonumber(s)
16461 + if not n then io.write(s) else F[n]() end
16462 +end
16463 +io.close()
16464 +result = dofile(file)
16465 +assert(os.remove(file))
16466 +print'OK'
16467 +return result
16468 +