1-- $Id: testes/calls.lua $
  2-- See Copyright Notice in file all.lua
  3
  4print("testing functions and calls")
  5
  6local debug = require "debug"
  7
  8-- get the opportunity to test 'type' too ;)
  9
 10assert(type(1<2) == 'boolean')
 11assert(type(true) == 'boolean' and type(false) == 'boolean')
 12assert(type(nil) == 'nil'
 13   and type(-3) == 'number'
 14   and type'x' == 'string'
 15   and type{} == 'table'
 16   and type(type) == 'function')
 17
 18assert(type(assert) == type(print))
 19local function f (x) return a:x (x) end
 20assert(type(f) == 'function')
 21assert(not pcall(type))
 22
 23
 24-- testing local-function recursion
 25fact = false
 26do
 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)
 34end
 35assert(fact == false)
 36fact = nil
 37
 38-- testing declarations
 39local a = {i = 10}
 40local self = 20
 41function a:x (x) return x+self.i end
 42function a.y (x) return x+self end
 43
 44assert(a:x(1)+10 == a.y(1))
 45
 46a.t = {i=-100}
 47a["t"].x = function (self, a,b) return self.i+a+b end
 48
 49assert(a.t:x(2,3) == -95)
 50
 51do
 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)
 55end
 56
 57local a = {b={c={}}}
 58
 59function a.b.c.f1 (x) return x+1 end
 60function a.b.c:f2 (x,y) self[x] = y end
 61assert(a.b.c.f1(4) == 5)
 62a.b.c:f2('k', 12); assert(a.b.c.k == 12)
 63
 64print('+')
 65
 66t = nil   -- 'declare' t
 67function f(a,b,c) local d = 'a'; t={a,b,c,d} end
 68
 69f(      -- this line change must be valid
 70  1,2)
 71assert(t[1] == 1 and t[2] == 2 and t[3] == nil and t[4] == 'a')
 72f(1,2,   -- this one too
 73      3,4)
 74assert(t[1] == 1 and t[2] == 2 and t[3] == 3 and t[4] == 'a')
 75
 76t = nil   -- delete 't'
 77
 78function fat(x)
 79  if x <= 1 then return 1
 80  else return x*load("return fat(" .. x-1 .. ")", "")()
 81  end
 82end
 83
 84assert(load "load 'assert(fat(6)==720)' () ")()
 85a = load('return fat(5), 3')
 86local a,b = a()
 87assert(a == 120 and b == 3)
 88fat = nil
 89print('+')
 90
 91local function err_on_n (n)
 92  if n==0 then error(); exit(1);
 93  else err_on_n (n-1); exit(1);
 94  end
 95end
 96
 97do
 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)
106end
107
108_G.deep = nil   -- "declaration"  (used by 'all.lua')
109
110function deep (n)
111  if n>0 then deep(n-1) end
112end
113deep(10)
114deep(180)
115
116
117print"testing tail calls"
118
119function deep (n) if n>0 then return deep(n-1) else return 101 end end
120assert(deep(30000) == 101)
121a = {}
122function a:deep (n) if n>0 then return self:deep(n-1) else return 101 end end
123assert(a:deep(30000) == 101)
124
125do   -- 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)
157end
158
159
160do   -- 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"))
167end
168
169
170
171do   -- 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, 100 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)
188end
189
190print('+')
191
192
193do  -- testing chains of '__call'
194  local N = 20
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")
207end
208
209
210a = nil
211(function (x) a=x end)(23)
212assert(a == 23 and (function (x) return x*2 end)(20) == 40)
213
214
215-- testing closures
216
217-- fixed-point operator
218local Z = function (le)
219      local function a (f)
220        return le(function (x) return f(f)(x) end)
221      end
222      return a(a)
223    end
224
225
226-- non-recursive factorial
227
228local F = function (f)
229      return function (n)
230               if n == 0 then return 1
231               else return n*f(n-1) end
232             end
233    end
234
235local fat = Z(F)
236
237assert(fat(0) == 1 and fat(4) == 24 and Z(F)(5)==5*Z(F)(4))
238
239local function g (z)
240  local function f (a,b,c,d)
241    return function (x,y) return a+b+c+d+a+x+y+z end
242  end
243  return f(z,z+1,z+2,z+3)
244end
245
246local f = g(10)
247assert(f(9, 16) == 10+11+12+13+10+9+16+10)
248
249print('+')
250
251-- testing multiple returns
252
253local function unlpack (t, i)
254  i = i or 1
255  if (i <= #t) then
256    return t[i], unlpack(t, i+1)
257  end
258end
259
260local function equaltab (t1, t2)
261  assert(#t1 == #t2)
262  for i = 1, #t1 do
263    assert(t1[i] == t2[i])
264  end
265end
266
267local pack = function (...) return (table.pack(...)) end
268
269local function f() return 1,2,30,4 end
270local function ret2 (a,b) return a,b end
271
272local a,b,c,d = unlpack{1,2,3}
273assert(a==1 and b==2 and c==3 and d==nil)
274a = {1,2,3,4,false,10,'alo',false,assert}
275equaltab(pack(unlpack(a)), a)
276equaltab(pack(unlpack(a), -1), {1,-1})
277a,b,c,d = ret2(f()), ret2(f())
278assert(a==1 and b==1 and c==2 and d==nil)
279a,b,c,d = unlpack(pack(ret2(f()), ret2(f())))
280assert(a==1 and b==1 and c==2 and d==nil)
281a,b,c,d = unlpack(pack(ret2(f()), (ret2(f()))))
282assert(a==1 and b==1 and c==nil and d==nil)
283
284a = ret2{ unlpack{1,2,3}, unlpack{3,2,1}, unlpack{"a", "b"}}
285assert(a[1] == 1 and a[2] == 3 and a[3] == "a" and a[4] == "b")
286
287
288-- testing calls with 'incorrect' arguments
289rawget({}, "x", 1)
290rawset({}, "x", 1, 2)
291assert(math.sin(1,2) == math.sin(1))
292table.sort({10,9,8,4,19,23,0,0}, function (a,b) return a<b end, "extra arg")
293
294
295-- test for generic load
296local x = "-- a comment\0\0\0\n  x = 10 + \n23; \
297     local a = function () x = 'hi' end; \
298     return '\0'"
299local function read1 (x)
300  local i = 0
301  return function ()
302    collectgarbage()
303    i=i+1
304    return string.sub(x, i, i)
305  end
306end
307
308local function cannotload (msg, a,b)
309  assert(not a and string.find(b, msg))
310end
311
312a = assert(load(read1(x), "modname", "t", _G))
313assert(a() == "\0" and _G.x == 33)
314assert(debug.getinfo(a).source == "modname")
315-- cannot read text in binary mode
316cannotload("attempt to load a text chunk", load(read1(x), "modname", "b", {}))
317cannotload("attempt to load a text chunk", load(x, "modname", "b"))
318
319a = assert(load(function () return nil end))
320a()  -- empty chunk
321
322assert(not load(function () return true end))
323
324
325-- small bug
326local t = {nil, "return ", "3"}
327f, msg = load(function () return table.remove(t, 1) end)
328assert(f() == nil)   -- should read the empty chunk
329
330-- another small bug (in 5.2.1)
331f = load(string.dump(function () return 1 end), nil, "b", {})
332assert(type(f) == "function" and f() == 1)
333
334
335do   -- another bug (in 5.4.0)
336  -- loading a binary long string interrupted by GC cycles
337  local f = string.dump(function ()
338    return '01234567890123456789012345678901234567890123456789'
339  end)
340  f = load(read1(f))
341  assert(f() == '01234567890123456789012345678901234567890123456789')
342end
343
344
345x = string.dump(load("x = 1; return x"))
346a = assert(load(read1(x), nil, "b"))
347assert(a() == 1 and _G.x == 1)
348cannotload("attempt to load a binary chunk", load(read1(x), nil, "t"))
349cannotload("attempt to load a binary chunk", load(x, nil, "t"))
350_G.x = nil
351
352assert(not pcall(string.dump, print))  -- no dump of C functions
353
354cannotload("unexpected symbol", load(read1("*a = 123")))
355cannotload("unexpected symbol", load("*a = 123"))
356cannotload("hhi", load(function () error("hhi") end))
357
358-- any value is valid for _ENV
359assert(load("return _ENV", nil, nil, 123)() == 123)
360
361
362-- load when _ENV is not first upvalue
363local x; XX = 123
364local function h ()
365  local y=x   -- use 'x', so that it becomes 1st upvalue
366  return XX   -- global name
367end
368local d = string.dump(h)
369x = load(d, "", "b")
370assert(debug.getupvalue(x, 2) == '_ENV')
371debug.setupvalue(x, 2, _G)
372assert(x() == 123)
373
374assert(assert(load("return XX + ...", nil, nil, {XX = 13}))(4) == 17)
375XX = nil
376
377-- test generic load with nested functions
378x = [[
379  return function (x)
380    return function (y)
381     return function (z)
382       return x+y+z
383     end
384   end
385  end
386]]
387a = assert(load(read1(x), "read", "t"))
388assert(a()(2)(3)(10) == 15)
389
390-- repeat the test loading a binary chunk
391x = string.dump(a)
392a = assert(load(read1(x), "read", "b"))
393assert(a()(2)(3)(10) == 15)
394
395
396-- test for dump/undump with upvalues
397local a, b = 20, 30
398x = load(string.dump(function (x)
399  if x == "set" then a = 10+b; b = b+1 else
400  return a
401  end
402end), "", "b", nil)
403assert(x() == nil)
404assert(debug.setupvalue(x, 1, "hi") == "a")
405assert(x() == "hi")
406assert(debug.setupvalue(x, 2, 13) == "b")
407assert(not debug.setupvalue(x, 3, 10))   -- only 2 upvalues
408x("set")
409assert(x() == 23)
410x("set")
411assert(x() == 24)
412
413-- test for dump/undump with many upvalues
414do
415  local nup = 200    -- maximum number of local variables
416  local prog = {"local a1"}
417  for i = 2, nup do prog[#prog + 1] = ", a" .. i end
418  prog[#prog + 1] = " = 1"
419  for i = 2, nup do prog[#prog + 1] = ", " .. i end
420  local sum = 1
421  prog[#prog + 1] = "; return function () return a1"
422  for i = 2, nup do prog[#prog + 1] = " + a" .. i; sum = sum + i end
423  prog[#prog + 1] = " end"
424  prog = table.concat(prog)
425  local f = assert(load(prog))()
426  assert(f() == sum)
427
428  f = load(string.dump(f))   -- main chunk now has many upvalues
429  local a = 10
430  local h = function () return a end
431  for i = 1, nup do
432    debug.upvaluejoin(f, i, h, 1)
433  end
434  assert(f() == 10 * nup)
435end
436
437-- test for long method names
438do
439  local t = {x = 1}
440  function t:_012345678901234567890123456789012345678901234567890123456789 ()
441    return self.x
442  end
443  assert(t:_012345678901234567890123456789012345678901234567890123456789() == 1)
444end
445
446
447-- test for bug in parameter adjustment
448assert((function () return nil end)(4) == nil)
449assert((function () local a; return a end)(4) == nil)
450assert((function (a) return a end)() == nil)
451
452
453print("testing binary chunks")
454do
455  local header = string.pack("c4BBc6BBB",
456    "\27Lua",                                  -- signature
457    0x54,                                      -- version 5.4 (0x54)
458    0,                                         -- format
459    "\x19\x93\r\n\x1a\n",                      -- data
460    4,                                         -- size of instruction
461    string.packsize("j"),                      -- sizeof(lua integer)
462    string.packsize("n")                       -- sizeof(lua number)
463  )
464  local c = string.dump(function ()
465    local a = 1; local b = 3;
466    local f = function () return a + b + _ENV.c; end    -- upvalues
467    local s1 = "a constant"
468    local s2 = "another constant"
469    return a + b * 3
470  end)
471
472  assert(assert(load(c))() == 10)
473
474  -- check header
475  assert(string.sub(c, 1, #header) == header)
476  -- check LUAC_INT and LUAC_NUM
477  local ci, cn = string.unpack("jn", c, #header + 1)
478  assert(ci == 0x5678 and cn == 370.5)
479
480  -- corrupted header
481  for i = 1, #header do
482    local s = string.sub(c, 1, i - 1) ..
483              string.char(string.byte(string.sub(c, i, i)) + 1) ..
484              string.sub(c, i + 1, -1)
485    assert(#s == #c)
486    assert(not load(s))
487  end
488
489  -- loading truncated binary chunks
490  for i = 1, #c - 1 do
491    local st, msg = load(string.sub(c, 1, i))
492    assert(not st and string.find(msg, "truncated"))
493  end
494end
495
496print('OK')
497return deep