lua

A copy of the Lua development repository
Log | Files | Refs | README

calls.lua (13776B)


      1 -- $Id: testes/calls.lua $
      2 -- See Copyright Notice in file all.lua
      3 
      4 print("testing functions and calls")
      5 
      6 local debug = require "debug"
      7 
      8 -- get the opportunity to test 'type' too ;)
      9 
     10 assert(type(1<2) == 'boolean')
     11 assert(type(true) == 'boolean' and type(false) == 'boolean')
     12 assert(type(nil) == 'nil'
     13    and type(-3) == 'number'
     14    and type'x' == 'string'
     15    and type{} == 'table'
     16    and type(type) == 'function')
     17 
     18 assert(type(assert) == type(print))
     19 local function f (x) return a:x (x) end
     20 assert(type(f) == 'function')
     21 assert(not pcall(type))
     22 
     23 
     24 -- testing local-function recursion
     25 fact = false
     26 do
     27   local res = 1
     28   local function fact (n)
     29     if n==0 then return res
     30     else return n*fact(n-1)
     31     end
     32   end
     33   assert(fact(5) == 120)
     34 end
     35 assert(fact == false)
     36 fact = nil
     37 
     38 -- testing declarations
     39 local a = {i = 10}
     40 local self = 20
     41 function a:x (x) return x+self.i end
     42 function a.y (x) return x+self end
     43 
     44 assert(a:x(1)+10 == a.y(1))
     45 
     46 a.t = {i=-100}
     47 a["t"].x = function (self, a,b) return self.i+a+b end
     48 
     49 assert(a.t:x(2,3) == -95)
     50 
     51 do
     52   local a = {x=0}
     53   function a:add (x) self.x, a.y = self.x+x, 20; return self end
     54   assert(a:add(10):add(20):add(30).x == 60 and a.y == 20)
     55 end
     56 
     57 local a = {b={c={}}}
     58 
     59 function a.b.c.f1 (x) return x+1 end
     60 function a.b.c:f2 (x,y) self[x] = y end
     61 assert(a.b.c.f1(4) == 5)
     62 a.b.c:f2('k', 12); assert(a.b.c.k == 12)
     63 
     64 print('+')
     65 
     66 t = nil   -- 'declare' t
     67 function f(a,b,c) local d = 'a'; t={a,b,c,d} end
     68 
     69 f(      -- this line change must be valid
     70   1,2)
     71 assert(t[1] == 1 and t[2] == 2 and t[3] == nil and t[4] == 'a')
     72 f(1,2,   -- this one too
     73       3,4)
     74 assert(t[1] == 1 and t[2] == 2 and t[3] == 3 and t[4] == 'a')
     75 
     76 t = nil   -- delete 't'
     77 
     78 function fat(x)
     79   if x <= 1 then return 1
     80   else return x*load("return fat(" .. x-1 .. ")", "")()
     81   end
     82 end
     83 
     84 assert(load "load 'assert(fat(6)==720)' () ")()
     85 a = load('return fat(5), 3')
     86 local a,b = a()
     87 assert(a == 120 and b == 3)
     88 fat = nil
     89 print('+')
     90 
     91 local function err_on_n (n)
     92   if n==0 then error(); exit(1);
     93   else err_on_n (n-1); exit(1);
     94   end
     95 end
     96 
     97 do
     98   local function dummy (n)
     99     if n > 0 then
    100       assert(not pcall(err_on_n, n))
    101       dummy(n-1)
    102     end
    103   end
    104 
    105   dummy(10)
    106 end
    107 
    108 _G.deep = nil   -- "declaration"  (used by 'all.lua')
    109 
    110 function deep (n)
    111   if n>0 then deep(n-1) end
    112 end
    113 deep(10)
    114 deep(180)
    115 
    116 
    117 print"testing tail calls"
    118 
    119 function deep (n) if n>0 then return deep(n-1) else return 101 end end
    120 assert(deep(30000) == 101)
    121 a = {}
    122 function a:deep (n) if n>0 then return self:deep(n-1) else return 101 end end
    123 assert(a:deep(30000) == 101)
    124 
    125 do   -- tail calls x varargs
    126   local function foo (x, ...) local a = {...}; return x, a[1], a[2] end
    127 
    128   local function foo1 (x) return foo(10, x, x + 1) end
    129 
    130   local a, b, c = foo1(-2)
    131   assert(a == 10 and b == -2 and c == -1)
    132 
    133   -- tail calls x metamethods
    134   local t = setmetatable({}, {__call = foo})
    135   local function foo2 (x) return t(10, x) end
    136   a, b, c = foo2(100)
    137   assert(a == t and b == 10 and c == 100)
    138 
    139   a, b = (function () return foo() end)()
    140   assert(a == nil and b == nil)
    141 
    142   local X, Y, A
    143   local function foo (x, y, ...) X = x; Y = y; A = {...} end
    144   local function foo1 (...) return foo(...) end
    145 
    146   local a, b, c = foo1()
    147   assert(X == nil and Y == nil and #A == 0)
    148 
    149   a, b, c = foo1(10)
    150   assert(X == 10 and Y == nil and #A == 0)
    151 
    152   a, b, c = foo1(10, 20)
    153   assert(X == 10 and Y == 20 and #A == 0)
    154 
    155   a, b, c = foo1(10, 20, 30)
    156   assert(X == 10 and Y == 20 and #A == 1 and A[1] == 30)
    157 end
    158 
    159 
    160 do   -- C-stack overflow while handling C-stack overflow
    161   local function loop ()
    162     assert(pcall(loop))
    163   end
    164 
    165   local err, msg = xpcall(loop, loop)
    166   assert(not err and string.find(msg, "error"))
    167 end
    168 
    169 
    170 
    171 do   -- tail calls x chain of __call
    172   local n = 10000   -- depth
    173 
    174   local function foo ()
    175     if n == 0 then return 1023
    176     else n = n - 1; return foo()
    177     end
    178   end
    179 
    180   -- build a chain of __call metamethods ending in function 'foo'
    181   for i = 1, 15 do
    182     foo = setmetatable({}, {__call = foo})
    183   end
    184 
    185   -- call the first one as a tail call in a new coroutine
    186   -- (to ensure stack is not preallocated)
    187   assert(coroutine.wrap(function() return foo() end)() == 1023)
    188 end
    189 
    190 print('+')
    191 
    192 
    193 do   print"testing chains of '__call'"
    194   local N = 15
    195   local u = table.pack
    196   for i = 1, N do
    197     u = setmetatable({i}, {__call = u})
    198   end
    199 
    200   local Res = u("a", "b", "c")
    201 
    202   assert(Res.n == N + 3)
    203   for i = 1, N do
    204     assert(Res[i][1] == i)
    205   end
    206   assert(Res[N + 1] == "a" and Res[N + 2] == "b" and Res[N + 3] == "c")
    207 
    208   local function u (...)
    209     local n = debug.getinfo(1, 't').extraargs
    210     assert(select("#", ...) == n)
    211     return n
    212   end
    213 
    214   for i = 0, N do
    215     assert(u() == i)
    216     u = setmetatable({}, {__call = u})
    217   end
    218 end
    219 
    220 
    221 do    -- testing chains too long
    222   local a = {}
    223   for i = 1, 16 do    -- one too many
    224     a = setmetatable({}, {__call = a})
    225   end
    226   local status, msg = pcall(a)
    227   assert(not status and string.find(msg, "too long"))
    228 
    229   setmetatable(a, {__call = a})   -- infinite chain
    230   local status, msg = pcall(a)
    231   assert(not status and string.find(msg, "too long"))
    232 
    233   -- again, with a tail call
    234   local status, msg = pcall(function () return a() end)
    235   assert(not status and string.find(msg, "too long"))
    236 end
    237 
    238 a = nil
    239 (function (x) a=x end)(23)
    240 assert(a == 23 and (function (x) return x*2 end)(20) == 40)
    241 
    242 
    243 -- testing closures
    244 
    245 -- fixed-point operator
    246 local Z = function (le)
    247       local function a (f)
    248         return le(function (x) return f(f)(x) end)
    249       end
    250       return a(a)
    251     end
    252 
    253 
    254 -- non-recursive factorial
    255 
    256 local F = function (f)
    257       return function (n)
    258                if n == 0 then return 1
    259                else return n*f(n-1) end
    260              end
    261     end
    262 
    263 local fat = Z(F)
    264 
    265 assert(fat(0) == 1 and fat(4) == 24 and Z(F)(5)==5*Z(F)(4))
    266 
    267 local function g (z)
    268   local function f (a,b,c,d)
    269     return function (x,y) return a+b+c+d+a+x+y+z end
    270   end
    271   return f(z,z+1,z+2,z+3)
    272 end
    273 
    274 local f = g(10)
    275 assert(f(9, 16) == 10+11+12+13+10+9+16+10)
    276 
    277 print('+')
    278 
    279 -- testing multiple returns
    280 
    281 local function unlpack (t, i)
    282   i = i or 1
    283   if (i <= #t) then
    284     return t[i], unlpack(t, i+1)
    285   end
    286 end
    287 
    288 local function equaltab (t1, t2)
    289   assert(#t1 == #t2)
    290   for i = 1, #t1 do
    291     assert(t1[i] == t2[i])
    292   end
    293 end
    294 
    295 local pack = function (...) return (table.pack(...)) end
    296 
    297 local function f() return 1,2,30,4 end
    298 local function ret2 (a,b) return a,b end
    299 
    300 local a,b,c,d = unlpack{1,2,3}
    301 assert(a==1 and b==2 and c==3 and d==nil)
    302 a = {1,2,3,4,false,10,'alo',false,assert}
    303 equaltab(pack(unlpack(a)), a)
    304 equaltab(pack(unlpack(a), -1), {1,-1})
    305 a,b,c,d = ret2(f()), ret2(f())
    306 assert(a==1 and b==1 and c==2 and d==nil)
    307 a,b,c,d = unlpack(pack(ret2(f()), ret2(f())))
    308 assert(a==1 and b==1 and c==2 and d==nil)
    309 a,b,c,d = unlpack(pack(ret2(f()), (ret2(f()))))
    310 assert(a==1 and b==1 and c==nil and d==nil)
    311 
    312 a = ret2{ unlpack{1,2,3}, unlpack{3,2,1}, unlpack{"a", "b"}}
    313 assert(a[1] == 1 and a[2] == 3 and a[3] == "a" and a[4] == "b")
    314 
    315 
    316 -- testing calls with 'incorrect' arguments
    317 rawget({}, "x", 1)
    318 rawset({}, "x", 1, 2)
    319 assert(math.sin(1,2) == math.sin(1))
    320 table.sort({10,9,8,4,19,23,0,0}, function (a,b) return a<b end, "extra arg")
    321 
    322 
    323 -- test for generic load
    324 local x = "-- a comment\0\0\0\n  x = 10 + \n23; \
    325      local a = function () x = 'hi' end; \
    326      return '\0'"
    327 local function read1 (x)
    328   local i = 0
    329   return function ()
    330     collectgarbage()
    331     i=i+1
    332     return string.sub(x, i, i)
    333   end
    334 end
    335 
    336 local function cannotload (msg, a,b)
    337   assert(not a and string.find(b, msg))
    338 end
    339 
    340 a = assert(load(read1(x), "modname", "t", _G))
    341 assert(a() == "\0" and _G.x == 33)
    342 assert(debug.getinfo(a).source == "modname")
    343 -- cannot read text in binary mode
    344 cannotload("attempt to load a text chunk", load(read1(x), "modname", "b", {}))
    345 cannotload("attempt to load a text chunk", load(x, "modname", "b"))
    346 
    347 a = assert(load(function () return nil end))
    348 a()  -- empty chunk
    349 
    350 assert(not load(function () return true end))
    351 
    352 
    353 -- small bug
    354 local t = {nil, "return ", "3"}
    355 f, msg = load(function () return table.remove(t, 1) end)
    356 assert(f() == nil)   -- should read the empty chunk
    357 
    358 -- another small bug (in 5.2.1)
    359 f = load(string.dump(function () return 1 end), nil, "b", {})
    360 assert(type(f) == "function" and f() == 1)
    361 
    362 
    363 do   -- another bug (in 5.4.0)
    364   -- loading a binary long string interrupted by GC cycles
    365   local f = string.dump(function ()
    366     return '01234567890123456789012345678901234567890123456789'
    367   end)
    368   f = load(read1(f))
    369   assert(f() == '01234567890123456789012345678901234567890123456789')
    370 end
    371 
    372 
    373 x = string.dump(load("x = 1; return x"))
    374 a = assert(load(read1(x), nil, "b"))
    375 assert(a() == 1 and _G.x == 1)
    376 cannotload("attempt to load a binary chunk", load(read1(x), nil, "t"))
    377 cannotload("attempt to load a binary chunk", load(x, nil, "t"))
    378 _G.x = nil
    379 
    380 assert(not pcall(string.dump, print))  -- no dump of C functions
    381 
    382 cannotload("unexpected symbol", load(read1("*a = 123")))
    383 cannotload("unexpected symbol", load("*a = 123"))
    384 cannotload("hhi", load(function () error("hhi") end))
    385 
    386 -- any value is valid for _ENV
    387 assert(load("return _ENV", nil, nil, 123)() == 123)
    388 
    389 
    390 -- load when _ENV is not first upvalue
    391 local x; XX = 123
    392 local function h ()
    393   local y=x   -- use 'x', so that it becomes 1st upvalue
    394   return XX   -- global name
    395 end
    396 local d = string.dump(h)
    397 x = load(d, "", "b")
    398 assert(debug.getupvalue(x, 2) == '_ENV')
    399 debug.setupvalue(x, 2, _G)
    400 assert(x() == 123)
    401 
    402 assert(assert(load("return XX + ...", nil, nil, {XX = 13}))(4) == 17)
    403 XX = nil
    404 
    405 -- test generic load with nested functions
    406 x = [[
    407   return function (x)
    408     return function (y)
    409      return function (z)
    410        return x+y+z
    411      end
    412    end
    413   end
    414 ]]
    415 a = assert(load(read1(x), "read", "t"))
    416 assert(a()(2)(3)(10) == 15)
    417 
    418 -- repeat the test loading a binary chunk
    419 x = string.dump(a)
    420 a = assert(load(read1(x), "read", "b"))
    421 assert(a()(2)(3)(10) == 15)
    422 
    423 
    424 -- test for dump/undump with upvalues
    425 local a, b = 20, 30
    426 x = load(string.dump(function (x)
    427   if x == "set" then a = 10+b; b = b+1 else
    428   return a
    429   end
    430 end), "", "b", nil)
    431 assert(x() == nil)
    432 assert(debug.setupvalue(x, 1, "hi") == "a")
    433 assert(x() == "hi")
    434 assert(debug.setupvalue(x, 2, 13) == "b")
    435 assert(not debug.setupvalue(x, 3, 10))   -- only 2 upvalues
    436 x("set")
    437 assert(x() == 23)
    438 x("set")
    439 assert(x() == 24)
    440 
    441 -- test for dump/undump with many upvalues
    442 do
    443   local nup = 200    -- maximum number of local variables
    444   local prog = {"local a1"}
    445   for i = 2, nup do prog[#prog + 1] = ", a" .. i end
    446   prog[#prog + 1] = " = 1"
    447   for i = 2, nup do prog[#prog + 1] = ", " .. i end
    448   local sum = 1
    449   prog[#prog + 1] = "; return function () return a1"
    450   for i = 2, nup do prog[#prog + 1] = " + a" .. i; sum = sum + i end
    451   prog[#prog + 1] = " end"
    452   prog = table.concat(prog)
    453   local f = assert(load(prog))()
    454   assert(f() == sum)
    455 
    456   f = load(string.dump(f))   -- main chunk now has many upvalues
    457   local a = 10
    458   local h = function () return a end
    459   for i = 1, nup do
    460     debug.upvaluejoin(f, i, h, 1)
    461   end
    462   assert(f() == 10 * nup)
    463 end
    464 
    465 -- test for long method names
    466 do
    467   local t = {x = 1}
    468   function t:_012345678901234567890123456789012345678901234567890123456789 ()
    469     return self.x
    470   end
    471   assert(t:_012345678901234567890123456789012345678901234567890123456789() == 1)
    472 end
    473 
    474 
    475 -- test for bug in parameter adjustment
    476 assert((function () return nil end)(4) == nil)
    477 assert((function () local a; return a end)(4) == nil)
    478 assert((function (a) return a end)() == nil)
    479 
    480 
    481 print("testing binary chunks")
    482 do
    483   local header = string.pack("c4BBc6BBB",
    484     "\27Lua",                                  -- signature
    485     0x55,                                      -- version 5.5 (0x55)
    486     0,                                         -- format
    487     "\x19\x93\r\n\x1a\n",                      -- data
    488     4,                                         -- size of instruction
    489     string.packsize("j"),                      -- sizeof(lua integer)
    490     string.packsize("n")                       -- sizeof(lua number)
    491   )
    492   local c = string.dump(function ()
    493     local a = 1; local b = 3;
    494     local f = function () return a + b + _ENV.c; end    -- upvalues
    495     local s1 = "a constant"
    496     local s2 = "another constant"
    497     return a + b * 3
    498   end)
    499 
    500   assert(assert(load(c))() == 10)
    501 
    502   -- check header
    503   assert(string.sub(c, 1, #header) == header)
    504   -- check LUAC_INT and LUAC_NUM
    505   local ci, cn = string.unpack("jn", c, #header + 1)
    506   assert(ci == 0x5678 and cn == 370.5)
    507 
    508   -- corrupted header
    509   for i = 1, #header do
    510     local s = string.sub(c, 1, i - 1) ..
    511               string.char(string.byte(string.sub(c, i, i)) + 1) ..
    512               string.sub(c, i + 1, -1)
    513     assert(#s == #c)
    514     assert(not load(s))
    515   end
    516 
    517   -- loading truncated binary chunks
    518   for i = 1, #c - 1 do
    519     local st, msg = load(string.sub(c, 1, i))
    520     assert(not st and string.find(msg, "truncated"))
    521   end
    522 end
    523 
    524 
    525 do   -- check reuse of strings in dumps
    526   local str = "|" .. string.rep("X", 50) .. "|"
    527   local foo = load(string.format([[
    528     local str <const> = "%s"
    529     return {
    530       function () return str end,
    531       function () return str end,
    532       function () return str end
    533     }
    534   ]], str))
    535   -- count occurrences of 'str' inside the dump
    536   local dump = string.dump(foo)
    537   local _, count = string.gsub(dump, str, {})
    538   -- there should be only two occurrences:
    539   -- one inside the source, other the string itself.
    540   assert(count == 2)
    541 
    542   if T then  -- check reuse of strings in undump
    543     local funcs = load(dump)()
    544     assert(string.format("%p", T.listk(funcs[1])[1]) ==
    545            string.format("%p", T.listk(funcs[3])[1]))
    546   end
    547 end
    548 
    549 
    550 do   -- test limit of multiple returns (254 values)
    551   local code = "return 10" .. string.rep(",10", 253)
    552   local res = {assert(load(code))()}
    553   assert(#res == 254 and res[254] == 10)
    554 
    555   code = code .. ",10"
    556   local status, msg = load(code)
    557   assert(not status and string.find(msg, "too many returns"))
    558 end
    559 
    560 print('OK')
    561 return deep