Skip to content

Commit

Permalink
Add tests for __call metamethod
Browse files Browse the repository at this point in the history
  • Loading branch information
edubart committed Sep 22, 2024
1 parent 10194b4 commit ff7a42c
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions docs/pages/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -1328,6 +1328,7 @@ Complete list of metamethods that can be defined for records:
| `__index` | `a[b]`{:.language-nelua} | indexing | array index |
| `__atindex` | `a[b]`{:.language-nelua} | indexing | array index via reference |
| `__tostring` | tostring(a) | cast | explicit/implicit cast to string |
| `__call` | `a(...)`{:.language-nelua} | call | call a record |
| `__convert` | | cast | implicit cast from anything |
| `__gc` | | gc | called when collected by the GC |
| `__close` | | close | called when `<close>` variables goes out of scope |
Expand Down
5 changes: 2 additions & 3 deletions lualib/nelua/analyzer.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1318,11 +1318,10 @@ local function visitor_Call(context, node, argnodes, calleetype, calleesym, call
local attr = node.attr
if calleetype then
local sideeffect
local origintype = calleetype
if calleetype.is_record and calleetype.metafields.__call ~= nil then
if calleetype.is_record and calleetype.metafields.__call then
calleetype = calleetype.metafields.__call.type
if not calleetype.is_procedure then
node:raisef("invalid metamethod __call in '%s'", calleetype)
node:raisef("in record call: expected meta field '__call' to be a procedure but is of type '%s'", calleetype)
end
attr.ismetacall = true
calleeobjnode = node[2]
Expand Down
6 changes: 6 additions & 0 deletions spec/analyzer_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1306,6 +1306,12 @@ it("records metamethods", function()
r[0] = x
local len = #r
]])
expect.analyze_error([[
local R = @record{}
global R.__call: integer = 1
local r: R
r()
]], "expected meta field '__call' to be a procedure")
expect.analyze_error([[
local R = @record{}
function R:__atindex(x: integer): integer return 0 end
Expand Down
7 changes: 7 additions & 0 deletions spec/cgenerator_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2557,6 +2557,13 @@ it("record metametods", function()
assert(3 == a)
assert(0 ~= a)
]])

expect.run_c([[
local Foo = @record{value: number}
function Foo:__call(a: number, b: number): number return a + b + self.value end
local foo: Foo = {1}
assert(foo(2, 3) == 6)
]])
end)

it("record operator overloading", function()
Expand Down

0 comments on commit ff7a42c

Please sign in to comment.