1-- $Id: testes/errors.lua $
  2-- See Copyright Notice in file all.lua
  3
  4print("testing errors")
  5
  6local debug = require"debug"
  7
  8-- avoid problems with 'strict' module (which may generate other error messages)
  9local mt = getmetatable(_G) or {}
 10local oldmm = mt.__index
 11mt.__index = nil
 12
 13local function checkerr (msg, f, ...)
 14  local st, err = pcall(f, ...)
 15  assert(not st and string.find(err, msg))
 16end
 17
 18
 19local function doit (s)
 20  local f, msg = load(s)
 21  if not f then return msg end
 22  local cond, msg = pcall(f)
 23  return (not cond) and msg
 24end
 25
 26
 27local function checkmessage (prog, msg, debug)
 28  local m = doit(prog)
 29  if debug then print(m, msg) end
 30  assert(string.find(m, msg, 1, true))
 31end
 32
 33local function checksyntax (prog, extra, token, line)
 34  local msg = doit(prog)
 35  if not string.find(token, "^<%a") and not string.find(token, "^char%(")
 36    then token = "'"..token.."'" end
 37  token = string.gsub(token, "(%p)", "%%%1")
 38  local pt = string.format([[^%%[string ".*"%%]:%d: .- near %s$]],
 39                           line, token)
 40  assert(string.find(msg, pt))
 41  assert(string.find(msg, msg, 1, true))
 42end
 43
 44
 45-- test error message with no extra info
 46assert(doit("error('hi', 0)") == 'hi')
 47
 48-- test error message with no info
 49assert(doit("error()") == nil)
 50
 51
 52-- test common errors/errors that crashed in the past
 53assert(doit("table.unpack({}, 1, n=2^30)"))
 54assert(doit("a=math.sin()"))
 55assert(not doit("tostring(1)") and doit("tostring()"))
 56assert(doit"tonumber()")
 57assert(doit"repeat until 1; a")
 58assert(doit"return;;")
 59assert(doit"assert(false)")
 60assert(doit"assert(nil)")
 61assert(doit("function a (... , ...) end"))
 62assert(doit("function a (, ...) end"))
 63assert(doit("local t={}; t = t[#t] + 1"))
 64
 65checksyntax([[
 66  local a = {4
 67
 68]], "'}' expected (to close '{' at line 1)", "<eof>", 3)
 69
 70
 71do   -- testing errors in goto/break
 72  local function checksyntax (prog, msg, line)
 73    local st, err = load(prog)
 74    assert(string.find(err, "line " .. line))
 75    assert(string.find(err, msg, 1, true))
 76  end
 77
 78  checksyntax([[
 79    ::A:: a = 1
 80    ::A::
 81  ]], "label 'A' already defined", 1)
 82
 83  checksyntax([[
 84    a = 1
 85    goto A
 86    do ::A:: end
 87  ]], "no visible label 'A'", 2)
 88
 89end
 90
 91
 92if not T then
 93  (Message or print)
 94    ('\n >>> testC not active: skipping tests for messages in C <<<\n')
 95else
 96  print "testing memory error message"
 97  local a = {}
 98  for i = 1, 10000 do a[i] = true end   -- preallocate array
 99  collectgarbage()
100  T.totalmem(T.totalmem() + 10000)
101  -- force a memory error (by a small margin)
102  local st, msg = pcall(function()
103    for i = 1, 100000 do a[i] = tostring(i) end
104  end)
105  T.totalmem(0)
106  assert(not st and msg == "not enough" .. " memory")
107
108  -- stack space for luaL_traceback (bug in 5.4.6)
109  local res = T.testC[[
110    # push 16 elements on the stack
111    pushnum 1; pushnum 1; pushnum 1; pushnum 1; pushnum 1;
112    pushnum 1; pushnum 1; pushnum 1; pushnum 1; pushnum 1;
113    pushnum 1; pushnum 1; pushnum 1; pushnum 1; pushnum 1;
114    pushnum 1;
115    # traceback should work with 4 remaining slots
116    traceback xuxu 1;
117    return 1
118  ]]
119  assert(string.find(res, "xuxu.-main chunk"))
120end
121
122
123-- tests for better error messages
124
125checkmessage("a = {} + 1", "arithmetic")
126checkmessage("a = {} | 1", "bitwise operation")
127checkmessage("a = {} < 1", "attempt to compare")
128checkmessage("a = {} <= 1", "attempt to compare")
129
130checkmessage("aaa=1; bbbb=2; aaa=math.sin(3)+bbbb(3)", "global 'bbbb'")
131checkmessage("aaa={}; do local aaa=1 end aaa:bbbb(3)", "method 'bbbb'")
132checkmessage("local a={}; a.bbbb(3)", "field 'bbbb'")
133assert(not string.find(doit"aaa={13}; local bbbb=1; aaa[bbbb](3)", "'bbbb'"))
134checkmessage("aaa={13}; local bbbb=1; aaa[bbbb](3)", "number")
135checkmessage("aaa=(1)..{}", "a table value")
136
137-- bug in 5.4.6
138checkmessage("a = {_ENV = {}}; print(a._ENV.x + 1)", "field 'x'")
139
140_G.aaa, _G.bbbb = nil
141
142-- calls
143checkmessage("local a; a(13)", "local 'a'")
144checkmessage([[
145  local a = setmetatable({}, {__add = 34})
146  a = a + 1
147]], "metamethod 'add'")
148checkmessage([[
149  local a = setmetatable({}, {__lt = {}})
150  a = a > a
151]], "metamethod 'lt'")
152
153-- tail calls
154checkmessage("local a={}; return a.bbbb(3)", "field 'bbbb'")
155checkmessage("aaa={}; do local aaa=1 end; return aaa:bbbb(3)", "method 'bbbb'")
156
157checkmessage("aaa = #print", "length of a function value")
158checkmessage("aaa = #3", "length of a number value")
159
160_G.aaa = nil
161
162checkmessage("aaa.bbb:ddd(9)", "global 'aaa'")
163checkmessage("local aaa={bbb=1}; aaa.bbb:ddd(9)", "field 'bbb'")
164checkmessage("local aaa={bbb={}}; aaa.bbb:ddd(9)", "method 'ddd'")
165checkmessage("local a,b,c; (function () a = b+1.1 end)()", "upvalue 'b'")
166assert(not doit"local aaa={bbb={ddd=next}}; aaa.bbb:ddd(nil)")
167
168-- upvalues being indexed do not go to the stack
169checkmessage("local a,b,cc; (function () a = cc[1] end)()", "upvalue 'cc'")
170checkmessage("local a,b,cc; (function () a.x = 1 end)()", "upvalue 'a'")
171
172checkmessage("local _ENV = {x={}}; a = a + 1", "global 'a'")
173
174checkmessage("BB=1; local aaa={}; x=aaa+BB", "local 'aaa'")
175checkmessage("aaa={}; x=3.3/aaa", "global 'aaa'")
176checkmessage("aaa=2; BB=nil;x=aaa*BB", "global 'BB'")
177checkmessage("aaa={}; x=-aaa", "global 'aaa'")
178
179-- short circuit
180checkmessage("aaa=1; local aaa,bbbb=2,3; aaa = math.sin(1) and bbbb(3)",
181       "local 'bbbb'")
182checkmessage("aaa=1; local aaa,bbbb=2,3; aaa = bbbb(1) or aaa(3)",
183             "local 'bbbb'")
184checkmessage("local a,b,c,f = 1,1,1; f((a and b) or c)", "local 'f'")
185checkmessage("local a,b,c = 1,1,1; ((a and b) or c)()", "call a number value")
186assert(not string.find(doit"aaa={}; x=(aaa or aaa)+(aaa and aaa)", "'aaa'"))
187assert(not string.find(doit"aaa={}; (aaa or aaa)()", "'aaa'"))
188
189checkmessage("print(print < 10)", "function with number")
190checkmessage("print(print < print)", "two function values")
191checkmessage("print('10' < 10)", "string with number")
192checkmessage("print(10 < '23')", "number with string")
193
194-- float->integer conversions
195checkmessage("local a = 2.0^100; x = a << 2", "local a")
196checkmessage("local a = 1 >> 2.0^100", "has no integer representation")
197checkmessage("local a = 10.1 << 2.0^100", "has no integer representation")
198checkmessage("local a = 2.0^100 & 1", "has no integer representation")
199checkmessage("local a = 2.0^100 & 1e100", "has no integer representation")
200checkmessage("local a = 2.0 | 1e40", "has no integer representation")
201checkmessage("local a = 2e100 ~ 1", "has no integer representation")
202checkmessage("string.sub('a', 2.0^100)", "has no integer representation")
203checkmessage("string.rep('a', 3.3)", "has no integer representation")
204checkmessage("return 6e40 & 7", "has no integer representation")
205checkmessage("return 34 << 7e30", "has no integer representation")
206checkmessage("return ~-3e40", "has no integer representation")
207checkmessage("return ~-3.009", "has no integer representation")
208checkmessage("return 3.009 & 1", "has no integer representation")
209checkmessage("return 34 >> {}", "table value")
210checkmessage("aaa = 24 // 0", "divide by zero")
211checkmessage("aaa = 1 % 0", "'n%0'")
212
213
214-- type error for an object which is neither in an upvalue nor a register.
215-- The following code will try to index the value 10 that is stored in
216-- the metatable, without moving it to a register.
217checkmessage("local a = setmetatable({}, {__index = 10}).x",
218             "attempt to index a number value")
219
220
221-- numeric for loops
222checkmessage("for i = {}, 10 do end", "table")
223checkmessage("for i = io.stdin, 10 do end", "FILE")
224checkmessage("for i = {}, 10 do end", "initial value")
225checkmessage("for i = 1, 'x', 10 do end", "string")
226checkmessage("for i = 1, {}, 10 do end", "limit")
227checkmessage("for i = 1, {} do end", "limit")
228checkmessage("for i = 1, 10, print do end", "step")
229checkmessage("for i = 1, 10, print do end", "function")
230
231-- passing light userdata instead of full userdata
232_G.D = debug
233checkmessage([[
234  -- create light udata
235  local x = D.upvalueid(function () return debug end, 1)
236  D.setuservalue(x, {})
237]], "light userdata")
238_G.D = nil
239
240do   -- named objects (field '__name')
241  checkmessage("math.sin(io.input())", "(number expected, got FILE*)")
242  _G.XX = setmetatable({}, {__name = "My Type"})
243  assert(string.find(tostring(XX), "^My Type"))
244  checkmessage("io.input(XX)", "(FILE* expected, got My Type)")
245  checkmessage("return XX + 1", "on a My Type value")
246  checkmessage("return ~io.stdin", "on a FILE* value")
247  checkmessage("return XX < XX", "two My Type values")
248  checkmessage("return {} < XX", "table with My Type")
249  checkmessage("return XX < io.stdin", "My Type with FILE*")
250  _G.XX = nil
251
252  if T then   -- extra tests for 'luaL_tolstring'
253    -- bug in 5.4.3; 'luaL_tolstring' with negative indices
254    local x = setmetatable({}, {__name="TABLE"})
255    assert(T.testC("Ltolstring -1; return 1", x) == tostring(x))
256
257    local a, b = T.testC("pushint 10; Ltolstring -2; return 2", x)
258    assert(a == 10 and b == tostring(x))
259
260    setmetatable(x, {__tostring=function (o)
261      assert(o == x)
262      return "ABC"
263    end})
264    local a, b, c = T.testC("pushint 10; Ltolstring -2; return 3", x)
265    assert(a == x and b == 10 and c == "ABC")
266  end
267end
268
269-- global functions
270checkmessage("(io.write or print){}", "io.write")
271checkmessage("(collectgarbage or print){}", "collectgarbage")
272
273-- errors in functions without debug info
274do
275  local f = function (a) return a + 1 end
276  f = assert(load(string.dump(f, true)))
277  assert(f(3) == 4)
278  checkerr("^%?:%-1:", f, {})
279
280  -- code with a move to a local var ('OP_MOV A B' with A<B)
281  f = function () local a; a = {}; return a + 2 end
282  -- no debug info (so that 'a' is unknown)
283  f = assert(load(string.dump(f, true)))
284  -- symbolic execution should not get lost
285  checkerr("^%?:%-1:.*table value", f)
286end
287
288
289-- tests for field accesses after RK limit
290local t = {}
291for i = 1, 1000 do
292  t[i] = "aaa = x" .. i
293end
294local s = table.concat(t, "; ")
295t = nil
296checkmessage(s.."; aaa = bbb + 1", "global 'bbb'")
297checkmessage("local _ENV=_ENV;"..s.."; aaa = bbb + 1", "global 'bbb'")
298checkmessage(s.."; local t = {}; aaa = t.bbb + 1", "field 'bbb'")
299checkmessage(s.."; local t = {}; t:bbb()", "method 'bbb'")
300
301checkmessage([[aaa=9
302repeat until 3==3
303local x=math.sin(math.cos(3))
304if math.sin(1) == x then return math.sin(1) end   -- tail call
305local a,b = 1, {
306  {x='a'..'b'..'c', y='b', z=x},
307  {1,2,3,4,5} or 3+3<=3+3,
308  3+1>3+1,
309  {d = x and aaa[x or y]}}
310]], "global 'aaa'")
311
312checkmessage([[
313local x,y = {},1
314if math.sin(1) == 0 then return 3 end    -- return
315x.a()]], "field 'a'")
316
317checkmessage([[
318prefix = nil
319insert = nil
320while 1 do
321  local a
322  if nil then break end
323  insert(prefix, a)
324end]], "global 'insert'")
325
326checkmessage([[  -- tail call
327  return math.sin("a")
328]], "sin")
329
330checkmessage([[collectgarbage("nooption")]], "invalid option")
331
332checkmessage([[x = print .. "a"]], "concatenate")
333checkmessage([[x = "a" .. false]], "concatenate")
334checkmessage([[x = {} .. 2]], "concatenate")
335
336checkmessage("getmetatable(io.stdin).__gc()", "no value")
337
338checkmessage([[
339local Var
340local function main()
341  NoSuchName (function() Var=0 end)
342end
343main()
344]], "global 'NoSuchName'")
345print'+'
346
347aaa = {}; setmetatable(aaa, {__index = string})
348checkmessage("aaa:sub()", "bad self")
349checkmessage("string.sub('a', {})", "#2")
350checkmessage("('a'):sub{}", "#1")
351
352checkmessage("table.sort({1,2,3}, table.sort)", "'table.sort'")
353checkmessage("string.gsub('s', 's', setmetatable)", "'setmetatable'")
354
355_G.aaa = nil
356
357
358-- tests for errors in coroutines
359
360local function f (n)
361  local c = coroutine.create(f)
362  local a,b = coroutine.resume(c)
363  return b
364end
365assert(string.find(f(), "C stack overflow"))
366
367checkmessage("coroutine.yield()", "outside a coroutine")
368
369f = coroutine.wrap(function () table.sort({1,2,3}, coroutine.yield) end)
370checkerr("yield across", f)
371
372
373-- testing size of 'source' info; size of buffer for that info is
374-- LUA_IDSIZE, declared as 60 in luaconf. Get one position for '\0'.
375local idsize = 60 - 1
376local function checksize (source)
377  -- syntax error
378  local _, msg = load("x", source)
379  msg = string.match(msg, "^([^:]*):")   -- get source (1st part before ':')
380  assert(msg:len() <= idsize)
381end
382
383for i = 60 - 10, 60 + 10 do   -- check border cases around 60
384  checksize("@" .. string.rep("x", i))   -- file names
385  checksize(string.rep("x", i - 10))     -- string sources
386  checksize("=" .. string.rep("x", i))   -- exact sources
387end
388
389
390-- testing line error
391
392local function lineerror (s, l)
393  local err,msg = pcall(load(s))
394  local line = tonumber(string.match(msg, ":(%d+):"))
395  assert(line == l or (not line and not l))
396end
397
398lineerror("local a\n for i=1,'a' do \n print(i) \n end", 2)
399lineerror("\n local a \n for k,v in 3 \n do \n print(k) \n end", 3)
400lineerror("\n\n for k,v in \n 3 \n do \n print(k) \n end", 4)
401lineerror("function a.x.y ()\na=a+1\nend", 1)
402
403lineerror("a = \na\n+\n{}", 3)
404lineerror("a = \n3\n+\n(\n4\n/\nprint)", 6)
405lineerror("a = \nprint\n+\n(\n4\n/\n7)", 3)
406
407lineerror("a\n=\n-\n\nprint\n;", 3)
408
409lineerror([[
410a
411(     -- <<
41223)
413]], 2)
414
415lineerror([[
416local a = {x = 13}
417a
418.
419x
420(     -- <<
42123
422)
423]], 5)
424
425lineerror([[
426local a = {x = 13}
427a
428.
429x
430(
43123 + a
432)
433]], 6)
434
435local p = [[
436  function g() f() end
437  function f(x) error('a', XX) end
438g()
439]]
440XX=3;lineerror((p), 3)
441XX=0;lineerror((p), false)
442XX=1;lineerror((p), 2)
443XX=2;lineerror((p), 1)
444_G.XX, _G.g, _G.f = nil
445
446
447lineerror([[
448local b = false
449if not b then
450  error 'test'
451end]], 3)
452
453lineerror([[
454local b = false
455if not b then
456  if not b then
457    if not b then
458      error 'test'
459    end
460  end
461end]], 5)
462
463
464-- bug in 5.4.0
465lineerror([[
466  local a = 0
467  local b = 1
468  local c = b % a
469]], 3)
470
471do
472  -- Force a negative estimate for base line. Error in instruction 2
473  -- (after VARARGPREP, GETGLOBAL), with first absolute line information
474  -- (forced by too many lines) in instruction 0.
475  local s = string.format("%s return __A.x", string.rep("\n", 300))
476  lineerror(s, 301)
477end
478
479
480if not _soft then
481  -- several tests that exaust the Lua stack
482  collectgarbage()
483  print"testing stack overflow"
484  local C = 0
485  -- get line where stack overflow will happen
486  local l = debug.getinfo(1, "l").currentline + 1
487  local function auxy () C=C+1; auxy() end     -- produce a stack overflow
488  function YY ()
489    collectgarbage("stop")   -- avoid running finalizers without stack space
490    auxy()
491    collectgarbage("restart")
492  end
493
494  local function checkstackmessage (m)
495    print("(expected stack overflow after " .. C .. " calls)")
496    C = 0    -- prepare next count
497    return (string.find(m, "stack overflow"))
498  end
499  -- repeated stack overflows (to check stack recovery)
500  assert(checkstackmessage(doit('YY()')))
501  assert(checkstackmessage(doit('YY()')))
502  assert(checkstackmessage(doit('YY()')))
503
504  _G.YY = nil
505
506
507  -- error lines in stack overflow
508  local l1
509  local function g(x)
510    l1 = debug.getinfo(x, "l").currentline + 2
511    collectgarbage("stop")   -- avoid running finalizers without stack space
512    auxy()
513    collectgarbage("restart")
514  end
515  local _, stackmsg = xpcall(g, debug.traceback, 1)
516  print('+')
517  local stack = {}
518  for line in string.gmatch(stackmsg, "[^\n]*") do
519    local curr = string.match(line, ":(%d+):")
520    if curr then table.insert(stack, tonumber(curr)) end
521  end
522  local i=1
523  while stack[i] ~= l1 do
524    assert(stack[i] == l)
525    i = i+1
526  end
527  assert(i > 15)
528
529
530  -- error in error handling
531  local res, msg = xpcall(error, error)
532  assert(not res and type(msg) == 'string')
533  print('+')
534
535  local function f (x)
536    if x==0 then error('a\n')
537    else
538      local aux = function () return f(x-1) end
539      local a,b = xpcall(aux, aux)
540      return a,b
541    end
542  end
543  f(3)
544
545  local function loop (x,y,z) return 1 + loop(x, y, z) end
546 
547  local res, msg = xpcall(loop, function (m)
548    assert(string.find(m, "stack overflow"))
549    checkerr("error handling", loop)
550    assert(math.sin(0) == 0)
551    return 15
552  end)
553  assert(msg == 15)
554
555  local f = function ()
556    for i = 999900, 1000000, 1 do table.unpack({}, 1, i) end
557  end
558  checkerr("too many results", f)
559
560end
561
562
563do
564  -- non string messages
565  local t = {}
566  local res, msg = pcall(function () error(t) end)
567  assert(not res and msg == t)
568
569  res, msg = pcall(function () error(nil) end)
570  assert(not res and msg == nil)
571
572  local function f() error{msg='x'} end
573  res, msg = xpcall(f, function (r) return {msg=r.msg..'y'} end)
574  assert(msg.msg == 'xy')
575
576  -- 'assert' with extra arguments
577  res, msg = pcall(assert, false, "X", t)
578  assert(not res and msg == "X")
579 
580  -- 'assert' with no message
581  res, msg = pcall(function () assert(false) end)
582  local line = string.match(msg, "%w+%.lua:(%d+): assertion failed!$")
583  assert(tonumber(line) == debug.getinfo(1, "l").currentline - 2)
584
585  -- 'assert' with non-string messages
586  res, msg = pcall(assert, false, t)
587  assert(not res and msg == t)
588
589  res, msg = pcall(assert, nil, nil)
590  assert(not res and msg == nil)
591
592  -- 'assert' without arguments
593  res, msg = pcall(assert)
594  assert(not res and string.find(msg, "value expected"))
595end
596
597-- xpcall with arguments
598local a, b, c = xpcall(string.find, error, "alo", "al")
599assert(a and b == 1 and c == 2)
600a, b, c = xpcall(string.find, function (x) return {} end, true, "al")
601assert(not a and type(b) == "table" and c == nil)
602
603
604print("testing tokens in error messages")
605checksyntax("syntax error", "", "error", 1)
606checksyntax("1.000", "", "1.000", 1)
607checksyntax("[[a]]", "", "[[a]]", 1)
608checksyntax("'aa'", "", "'aa'", 1)
609checksyntax("while << do end", "", "<<", 1)
610checksyntax("for >> do end", "", ">>", 1)
611
612-- test invalid non-printable char in a chunk
613checksyntax("a\1a = 1", "", "<\\1>", 1)
614
615-- test 255 as first char in a chunk
616checksyntax("\255a = 1", "", "<\\255>", 1)
617
618doit('I = load("a=9+"); aaa=3')
619assert(_G.aaa==3 and not _G.I)
620_G.I,_G.aaa = nil
621print('+')
622
623local lim = 1000
624if _soft then lim = 100 end
625for i=1,lim do
626  doit('a = ')
627  doit('a = 4+nil')
628end
629
630
631-- testing syntax limits
632
633local function testrep (init, rep, close, repc, finalresult)
634  local s = init .. string.rep(rep, 100) .. close .. string.rep(repc, 100)
635  local res, msg = load(s)
636  assert(res)   -- 100 levels is OK
637  if (finalresult) then
638    assert(res() == finalresult)
639  end
640  s = init .. string.rep(rep, 500)
641  local res, msg = load(s)   -- 500 levels not ok
642  assert(not res and (string.find(msg, "too many") or
643                      string.find(msg, "overflow")))
644end
645
646testrep("local a; a", ",a", "= 1", ",1")    -- multiple assignment
647testrep("local a; a=", "{", "0", "}")
648testrep("return ", "(", "2", ")", 2)
649testrep("local function a (x) return x end; return ", "a(", "2.2", ")", 2.2)
650testrep("", "do ", "", " end")
651testrep("", "while a do ", "", " end")
652testrep("local a; ", "if a then else ", "", " end")
653testrep("", "function foo () ", "", " end")
654testrep("local a = ''; return ", "a..", "'a'", "", "a")
655testrep("local a = 1; return ", "a^", "a", "", 1)
656
657checkmessage("a = f(x" .. string.rep(",x", 260) .. ")", "too many registers")
658
659
660-- testing other limits
661
662-- upvalues
663local lim = 127
664local  s = "local function fooA ()\n  local "
665for j = 1,lim do
666  s = s.."a"..j..", "
667end
668s = s.."b,c\n"
669s = s.."local function fooB ()\n  local "
670for j = 1,lim do
671  s = s.."b"..j..", "
672end
673s = s.."b\n"
674s = s.."function fooC () return b+c"
675local c = 1+2
676for j = 1,lim do
677  s = s.."+a"..j.."+b"..j
678  c = c + 2
679end
680s = s.."\nend  end end"
681local a,b = load(s)
682assert(c > 255 and string.find(b, "too many upvalues") and
683       string.find(b, "line 5"))
684
685-- local variables
686s = "\nfunction foo ()\n  local "
687for j = 1,300 do
688  s = s.."a"..j..", "
689end
690s = s.."b\n"
691local a,b = load(s)
692assert(string.find(b, "line 2") and string.find(b, "too many local variables"))
693
694mt.__index = oldmm
695
696print('OK')