Skip to content

Commit

Permalink
Add typecheck.tablecheck
Browse files Browse the repository at this point in the history
  • Loading branch information
semyon422 committed Jan 24, 2024
1 parent 8d7eac7 commit b0d178a
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
36 changes: 36 additions & 0 deletions tests/tablecheck_test.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
local tablecheck = require("typecheck.tablecheck")

local test = {}

function test.all(t)
local tt = tablecheck([[(
a: number,
b: string,
c: string?
)]])

tt({
a = 1,
b = "",
})
tt({
a = 1,
b = "",
c = "",
})

t:has_error(tt, {
a = 1,
b = "",
c = 1,
})
t:has_error(tt, {
a = "",
b = "",
})
t:has_error(tt, {
a = 1,
})
end

return test
37 changes: 37 additions & 0 deletions typecheck/tablecheck.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
local class = require("class")
local lexer = require("typecheck.lexer")
local Type = require("typecheck.Type")

local nil_type = Type(nil)

local tablecheck = class()

function tablecheck:new(types)
local tokens = assert(lexer.lex(types))
self.param_names, self.param_types = assert(tokens:parse_params())
self.params_map = {}
for i, name in ipairs(self.param_names) do
self.params_map[name] = self.param_types[i]
end
end

local exp_got = "bad argument '%s' (%s expected, got %s)"

function tablecheck:__call(t)
local params_map = self.params_map
local keys = {}
for k in pairs(t) do
keys[k] = true
end
for k in pairs(params_map) do
keys[k] = true
end
for k in pairs(keys) do
local _type = params_map[k] or nil_type
local v = t[k]
assert(_type:check(v), exp_got:format(k, _type, type(v)))
end
return t
end

return tablecheck

0 comments on commit b0d178a

Please sign in to comment.