]> git.lizzy.rs Git - metalua.git/blob - checks.lua
ast_to_src: format function calls and unary operators without space
[metalua.git] / checks.lua
1 --------------------------------------------------------------------------------
2 -- Copyright (c) 2006-2013 Fabien Fleutot and others.
3 --
4 -- All rights reserved.
5 --
6 -- This program and the accompanying materials are made available
7 -- under the terms of the Eclipse Public License v1.0 which
8 -- accompanies this distribution, and is available at
9 -- http://www.eclipse.org/legal/epl-v10.html
10 --
11 -- This program and the accompanying materials are also made available
12 -- under the terms of the MIT public license which accompanies this
13 -- distribution, and is available at http://www.lua.org/license.html
14 --
15 -- Contributors:
16 --     Fabien Fleutot - API and implementation
17 --
18 --------------------------------------------------------------------------------
19
20 -- Alternative implementation of checks() in Lua. Slower than
21 -- the C counterpart, but no compilation/porting concerns.
22
23 checkers = { }
24
25 local function check_one(expected, val)
26     if type(val)==expected then return true end
27     local mt = getmetatable(val)
28     if mt and mt.__type==expected then return true end
29     local f = checkers[expected]
30     if f and f(val) then return true end
31     return false
32 end
33
34 local function check_many(name, expected, val)
35     if expected=='?' then return true
36     elseif expected=='!' then return (val~=nil)
37     elseif type(expected) ~= 'string' then
38         error 'strings expected by checks()'
39     elseif val==nil and expected :sub(1,1) == '?' then return true end
40     for one in expected :gmatch "[^|?]+" do
41         if check_one(one, val) then return true end
42     end
43     return false
44 end
45
46 function checks(...)
47     for i, arg in ipairs{...} do
48         local name, val = debug.getlocal(2, i)
49         local success = check_many(name, arg, val)
50         if not success then
51             local fname = debug.getinfo(2, 'n').name
52             local fmt = "bad argument #%d to '%s' (%s expected, got %s)"
53             local msg = string.format(fmt, i, fname or "?", arg, type(val))
54             error(msg, 3)
55         end
56     end
57 end
58
59 return checks