Skip to content

Commit

Permalink
Analysis: Make typeof on a type userdata return "type"
Browse files Browse the repository at this point in the history
This change introduces a flag (LuauUserTypeFunTypeofReturnsType) that, when enabled, sets __type on the type userdata's metatable to "type".
This behaviour was described in the user-defined type function RFC (https://rfcs.luau.org/user-defined-type-functions.html), but seems to have been missed; this change implements that behaviour.
  • Loading branch information
nothing1649 committed Dec 16, 2024
1 parent 2e6fdd9 commit 43c0316
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Analysis/src/TypeFunctionRuntime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ LUAU_DYNAMIC_FASTINT(LuauTypeFunctionSerdeIterationLimit)
LUAU_FASTFLAGVARIABLE(LuauUserTypeFunPrintToError)
LUAU_FASTFLAGVARIABLE(LuauUserTypeFunFixNoReadWrite)
LUAU_FASTFLAGVARIABLE(LuauUserTypeFunThreadBuffer)
LUAU_FASTFLAGVARIABLE(LuauUserTypeFunTypeofReturnsType)

namespace Luau
{
Expand Down Expand Up @@ -1504,6 +1505,12 @@ void registerTypeUserData(lua_State* L)

// Create and register metatable for type userdata
luaL_newmetatable(L, "type");

if (FFlag::LuauUserTypeFunTypeofReturnsType)
{
lua_pushstring(L, "type");
lua_setfield(L, -2, "__type");
}

// Protect metatable from being changed
lua_pushstring(L, "The metatable is locked");
Expand Down
20 changes: 20 additions & 0 deletions tests/TypeFunction.user.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ LUAU_FASTFLAG(LuauUserTypeFunExportedAndLocal)
LUAU_FASTFLAG(LuauUserDefinedTypeFunParseExport)
LUAU_FASTFLAG(LuauUserTypeFunThreadBuffer)
LUAU_FASTFLAG(LuauUserTypeFunUpdateAllEnvs)
LUAU_FASTFLAG(LuauUserTypeFunTypeofReturnsType)

TEST_SUITE_BEGIN("UserDefinedTypeFunctionTests");

Expand Down Expand Up @@ -1393,4 +1394,23 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "print_to_error_plus_no_result")
CHECK(toString(result.errors[3]) == R"(Type function instance t0<string> is uninhabited)");
}

TEST_CASE_FIXTURE(BuiltinsFixture, "typeof_type_userdata_returns_type")
{
ScopedFastFlag solverV2{FFlag::LuauSolverV2, true};
ScopedFastFlag luauUserTypeFunPrintToError{FFlag::LuauUserTypeFunPrintToError, true};
ScopedFastFlag luauUserTypeFunTypeofReturnsType{FFlag::LuauUserTypeFunTypeofReturnsType, true};

CheckResult result = check(R"(
type function test(t)
print(typeof(t))
return t
end
local _:test<number>
)");

LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK(toString(result.errors[0]) == R"(type)");
}

TEST_SUITE_END();

0 comments on commit 43c0316

Please sign in to comment.