Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix values preserving nil in iterators #1550

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
14 changes: 13 additions & 1 deletion Analysis/src/TypeInfer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ LUAU_FASTFLAGVARIABLE(DebugLuauFreezeDuringUnification)
LUAU_FASTFLAG(LuauInstantiateInSubtyping)
LUAU_FASTFLAGVARIABLE(LuauMetatableFollow)
LUAU_FASTFLAGVARIABLE(LuauRequireCyclesDontAlwaysReturnAny)
LUAU_FASTFLAGVARIABLE(LuauNilInForLoops)

namespace Luau
{
Expand Down Expand Up @@ -1285,7 +1286,18 @@ ControlFlow TypeChecker::check(const ScopePtr& scope, const AstStatForIn& forin)
unify(iterTable->indexer->indexType, varTypes[0], scope, forin.location);

if (varTypes.size() > 1)
unify(iterTable->indexer->indexResultType, varTypes[1], scope, forin.location);
{
if (FFlag::LuauNilInForLoops)
{
std::optional<TypeId> withoutNilTy = tryStripUnionFromNil(iterTable->indexer->indexResultType);

unify(withoutNilTy ? *withoutNilTy : iterTable->indexer->indexResultType, varTypes[1], scope, forin.location);
}
else
{
unify(iterTable->indexer->indexResultType, varTypes[1], scope, forin.location);
}
}

for (size_t i = 2; i < varTypes.size(); ++i)
unify(nilType, varTypes[i], scope, forin.location);
Expand Down
31 changes: 31 additions & 0 deletions tests/TypeInfer.loops.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using namespace Luau;

LUAU_FASTFLAG(LuauSolverV2)
LUAU_FASTFLAG(LuauNilInForLoops)

TEST_SUITE_BEGIN("TypeInferLoops");

Expand Down Expand Up @@ -1255,4 +1256,34 @@ end
)");
}

TEST_CASE_FIXTURE(Fixture, "nil_in_for_loops")
{
ScopedFastFlag sff = {FFlag::LuauNilInForLoops, true};

LUAU_REQUIRE_NO_ERRORS(check(R"(
--!strict
local function f(x: { [string]: string? })
for key, value in x do
local v: string = value
end
end
)"));
}

// Custom iterators can return nil, just not without
TEST_CASE_FIXTURE(BuiltinsFixture, "nil_in_for_loops_iter")
{
LUAU_REQUIRE_NO_ERRORS(check(R"(
--!strict
type T = typeof(setmetatable({}, {} :: {
__iter: (any) -> () -> (boolean, string?)
}))

local function f(x: T)
for a: boolean, b: string? in x do
end
end
)"));
}

TEST_SUITE_END();
Loading