diff --git a/changelog.md b/changelog.md index daefdb5ae..55f172fc4 100644 --- a/changelog.md +++ b/changelog.md @@ -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. ## 3.19.2 diff --git a/script/vm/compiler.lua b/script/vm/compiler.lua index 20ab3ac41..93bc76eb6 100644 --- a/script/vm/compiler.lua +++ b/script/vm/compiler.lua @@ -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) diff --git a/test/type_inference/generic_operator.lua b/test/type_inference/generic_operator.lua index 69c1c931e..dff76198a 100644 --- a/test/type_inference/generic_operator.lua +++ b/test/type_inference/generic_operator.lua @@ -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 in iterator do +end +]] + +-- Same through an instantiated generic callable class +TEST 'string' [[ +---@class Iterator +---@operator call(): T? + +---@type Iterator +local b + +for in b do +end +]] + +-- Nil is not doubled up +TEST 'string' [[ +---@class Iterator +---@operator call(): T? + +---@type Iterator +local b + +for in b do +end +]] + +-- Bad iterators don't error +TEST 'unknown' [[ +---@class Iterator + +---@type Iterator +local b + +for in b do +end +]] + +-- Multiple returns don't have incorrect inference +TEST 'unknown' [[ +---@class Iterator +---@operator call(): string + +---@type Iterator +local b + +for k, in b do +end +]]