Skip to content

Commit

Permalink
make compatibility of functions with optionals more lax
Browse files Browse the repository at this point in the history
Fixes #827.
  • Loading branch information
hishamhm committed Oct 23, 2024
1 parent 994c005 commit 815de09
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
41 changes: 41 additions & 0 deletions spec/lang/assignment/to_function_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,45 @@ describe("assignment to function", function()
chunk = my_load("")
end
]]))

it("bivariant type checking for functions with optional arguments (regression test for #827)", util.check([[
local fcts: {string:function(val: any, opt?: string)}
fcts['foo'] = function (val: string)
print(val)
end
fcts['foo2'] = function (val: string, val2: string) -- in assignment: incompatible number of arguments: got 2 (string, string), expected at least 1 and at most 2 (<any type>, string)
print(val, val2)
end
fcts['bar'] = function (val: number)
print(val)
end
fcts['bar2'] = function (val: number, val2: string) -- in assignment: incompatible number of arguments: got 2 (number, string), expected at least 1 and at most 2 (<any type>, string)
print(val, val2)
end
]]))

it("bivariant type checking for functions with missing arguments (regression test for #827)", util.check([[
local fcts2: {string:function(val: any, val2: string)}
fcts2['foo'] = function (val: string)
print(val)
end
fcts2['foo2'] = function (val: string, val2: string)
print(val, val2)
end
fcts2['bar'] = function (val: number)
print(val)
end
fcts2['bar2'] = function (val: number, val2: string)
print(val, val2)
end
]]))

end)
2 changes: 1 addition & 1 deletion tl.lua
Original file line number Diff line number Diff line change
Expand Up @@ -8937,7 +8937,7 @@ a.types[i], b.types[i]), }
local errs = {}

local aa, ba = a.args.tuple, b.args.tuple
if (not b.args.is_va) and (self.feat_arity and a.min_arity > b.min_arity) then
if (not b.args.is_va) and (self.feat_arity and (#aa > #ba and a.min_arity > b.min_arity)) then
table.insert(errs, Err("incompatible number of arguments: got " .. show_arity(a) .. " %s, expected " .. show_arity(b) .. " %s", a.args, b.args))
else
for i = ((a.is_method or b.is_method) and 2 or 1), #aa do
Expand Down
2 changes: 1 addition & 1 deletion tl.tl
Original file line number Diff line number Diff line change
Expand Up @@ -8937,7 +8937,7 @@ do
local errs = {}

local aa, ba = a.args.tuple, b.args.tuple
if (not b.args.is_va) and (self.feat_arity and a.min_arity > b.min_arity) then
if (not b.args.is_va) and (self.feat_arity and (#aa > #ba and a.min_arity > b.min_arity)) then
table.insert(errs, Err("incompatible number of arguments: got " .. show_arity(a) .. " %s, expected " .. show_arity(b) .. " %s", a.args, b.args))
else
for i = ((a.is_method or b.is_method) and 2 or 1), #aa do
Expand Down

0 comments on commit 815de09

Please sign in to comment.