Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# changelog

## Unreleased
* `FIX` Generic `for` loops now infer loop variables from the result of calling a callable iterator (e.g. a class with `---@operator call(): ...`) instead of requiring an actual function.
<!-- Add all new changes here. They will be moved under a version at release -->

## 3.19.2
Expand Down
8 changes: 8 additions & 0 deletions script/vm/compiler.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2391,6 +2391,14 @@ local compilerSwitch = util.switch()
end
end
end
-- Classes can have a call operator which we need to check
-- TODO: when @operator call() can have multiple returns this should be updated.
if index == 1 then
local operatorNode = vm.runOperator('call', func)
if operatorNode then
vm.setNode(source, operatorNode)
end
end
end)
: case 'main'
: call(function (source)
Expand Down
60 changes: 60 additions & 0 deletions test/type_inference/generic_operator.lua
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,63 @@ TESTGENERICNAMES '' [[
---@operator call(): integer
local Plain
]]

-- Generic for loop over a callable class: the loop variable comes from the
-- result of calling the iterator, not from a function return.
TEST 'string' [[
---@class StringIterator
---@operator call(): string?

---@type StringIterator
local iterator

for <?v?> in iterator do
end
]]

-- Same through an instantiated generic callable class
TEST 'string' [[
---@class Iterator<T>
---@operator call(): T?

---@type Iterator<string>
local b

for <?v?> in b do
end
]]

-- Nil is not doubled up
TEST 'string' [[
---@class Iterator<T>
---@operator call(): T?

---@type Iterator<string?>
local b

for <?v?> in b do
end
]]

-- Bad iterators don't error
TEST 'unknown' [[
---@class Iterator

---@type Iterator
local b

for <?v?> in b do
end
]]

-- Multiple returns don't have incorrect inference
TEST 'unknown' [[
---@class Iterator
---@operator call(): string

---@type Iterator
local b

for k, <?v?> in b do
end
]]
Loading