From 6d36d483cb88973276af611198169f76f3ce05b0 Mon Sep 17 00:00:00 2001 From: Iqbal F Date: Wed, 21 Oct 2026 03:55:20 +0700 Subject: [PATCH 01/13] Implement FASTCALL for `table.create` and `table.clear` (#2365) Co-authored-by: Vyacheslav Egorov Co-authored-by: vegorov-rbx <75688451+vegorov-rbx@users.noreply.github.com> --- CodeGen/src/BytecodeAnalysis.cpp | 8 +++++ CodeGen/src/OptimizeConstProp.cpp | 5 +++ Common/include/Luau/Bytecode.h | 4 +++ Compiler/src/Builtins.cpp | 11 +++++++ Compiler/src/Types.cpp | 2 ++ VM/src/lbuiltins.cpp | 46 ++++++++++++++++++++++++++++ tests/Compiler.test.cpp | 51 +++++++++++++++++++++++++++++++ 7 files changed, 127 insertions(+) diff --git a/CodeGen/src/BytecodeAnalysis.cpp b/CodeGen/src/BytecodeAnalysis.cpp index 268656b46..33f302037 100644 --- a/CodeGen/src/BytecodeAnalysis.cpp +++ b/CodeGen/src/BytecodeAnalysis.cpp @@ -522,6 +522,14 @@ static void applyBuiltinCall(LuauBuiltinFunction bfid, BytecodeTypes& types) types.result = LBC_TYPE_NIL; types.a = LBC_TYPE_TABLE; break; + case LBF_TABLE_CREATE: + types.result = LBC_TYPE_TABLE; + types.a = LBC_TYPE_NUMBER; + break; + case LBF_TABLE_CLEAR: + types.result = LBC_TYPE_NIL; + types.a = LBC_TYPE_TABLE; + break; case LBF_RAWSET: types.result = LBC_TYPE_ANY; types.a = LBC_TYPE_TABLE; diff --git a/CodeGen/src/OptimizeConstProp.cpp b/CodeGen/src/OptimizeConstProp.cpp index 3e299ebc8..0b77b869a 100644 --- a/CodeGen/src/OptimizeConstProp.cpp +++ b/CodeGen/src/OptimizeConstProp.cpp @@ -1584,6 +1584,11 @@ static void handleBuiltinEffects(ConstPropState& state, LuauBuiltinFunction bfid case LBF_TABLE_INSERT: state.invalidateHeap(); return; // table.insert does not modify result registers. + case LBF_TABLE_CLEAR: + state.invalidateHeap(); + return; // table.clear does not modify result registers. + case LBF_TABLE_CREATE: + break; case LBF_RAWSET: state.invalidateHeap(); break; diff --git a/Common/include/Luau/Bytecode.h b/Common/include/Luau/Bytecode.h index 638bd2421..1286f06c8 100644 --- a/Common/include/Luau/Bytecode.h +++ b/Common/include/Luau/Bytecode.h @@ -774,6 +774,10 @@ enum LuauBuiltinFunction // buffer.readinteger / buffer.writeinteger (int64_t) LBF_BUFFER_READINTEGER, LBF_BUFFER_WRITEINTEGER, + + // table.create / table.clear + LBF_TABLE_CREATE, + LBF_TABLE_CLEAR, }; // Capture type, used in LOP_CAPTURE diff --git a/Compiler/src/Builtins.cpp b/Compiler/src/Builtins.cpp index 2a71058d4..d163a6774 100644 --- a/Compiler/src/Builtins.cpp +++ b/Compiler/src/Builtins.cpp @@ -9,6 +9,7 @@ LUAU_FASTFLAGVARIABLE(LuauIntegerFastcalls) LUAU_FASTFLAGVARIABLE(LuauIntegerBufferFastcalls) +LUAU_FASTFLAGVARIABLE(LuauCompileTableBuiltinsCreateClear) namespace Luau { @@ -225,6 +226,10 @@ static int getBuiltinFunctionId(const Builtin& builtin, const CompileOptions& op return LBF_TABLE_INSERT; if (builtin.method == "unpack") return LBF_TABLE_UNPACK; + if (FFlag::LuauCompileTableBuiltinsCreateClear && builtin.method == "create") + return LBF_TABLE_CREATE; + if (FFlag::LuauCompileTableBuiltinsCreateClear && builtin.method == "clear") + return LBF_TABLE_CLEAR; } if (builtin.object == "buffer") @@ -604,6 +609,12 @@ BuiltinInfo getBuiltinInfo(int bfid) case LBF_TABLE_UNPACK: return {-1, -1}; // 1, 2 or 3 parameters + case LBF_TABLE_CREATE: + return {-1, 1}; // 1 or 2 parameters + + case LBF_TABLE_CLEAR: + return {1, 0}; + case LBF_VECTOR: return {-1, 1}; // 3 or 4 parameters in some configurations diff --git a/Compiler/src/Types.cpp b/Compiler/src/Types.cpp index 4182db245..c83f79292 100644 --- a/Compiler/src/Types.cpp +++ b/Compiler/src/Types.cpp @@ -761,6 +761,8 @@ struct TypeMapVisitor : AstVisitor case LBF_RAWGET: case LBF_TABLE_INSERT: case LBF_TABLE_UNPACK: + case LBF_TABLE_CREATE: + case LBF_TABLE_CLEAR: case LBF_SELECT_VARARG: case LBF_GETMETATABLE: case LBF_SETMETATABLE: diff --git a/VM/src/lbuiltins.cpp b/VM/src/lbuiltins.cpp index a8b036976..f386d36a0 100644 --- a/VM/src/lbuiltins.cpp +++ b/VM/src/lbuiltins.cpp @@ -2565,6 +2565,49 @@ static bool luau_hassse41() } #endif +static int luauF_tablecreate(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) +{ + if (nparams >= 1 && nresults <= 1 && ttisnumber(arg0)) + { + double n = nvalue(arg0); + int size; + luai_num2int(size, n); + + if (size < 0 || luaC_needsGC(L)) + return -1; + + LuaTable* t = luaH_new(L, size, 0); + + if (nparams >= 2) + { + TValue* v = args; + for (int i = 0; i < size; ++i) + setobj2t(L, &t->array[i], v); + } + + sethvalue(L, res, t); + return 1; + } + + return -1; +} + +static int luauF_tableclear(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) +{ + if (nparams >= 1 && nresults <= 0 && ttistable(arg0)) + { + LuaTable* t = hvalue(arg0); + + if (t->readonly) + return -1; + + luaH_clear(t); + return 0; + } + + return -1; +} + const luau_FastFunction luauF_table[256] = { NULL, luauF_assert, @@ -2741,6 +2784,9 @@ const luau_FastFunction luauF_table[256] = { luauF_bufferreadlong, luauF_bufferwritelong, + luauF_tablecreate, + luauF_tableclear, + // When adding builtins, add them above this line; what follows is 64 "dummy" entries with luauF_missing fallback. // This is important so that older versions of the runtime that don't support newer builtins automatically fall back via luauF_missing. // Given the builtin addition velocity this should always provide a larger compatibility window than bytecode versions suggest. diff --git a/tests/Compiler.test.cpp b/tests/Compiler.test.cpp index ae13f88d9..036990c61 100644 --- a/tests/Compiler.test.cpp +++ b/tests/Compiler.test.cpp @@ -41,6 +41,7 @@ LUAU_FASTFLAG(LuauExportedTypesParticipateInScc) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauCompileNoFoldVectorEqW) LUAU_FASTFLAG(LuauCompileReuseLocalRegs) +LUAU_FASTFLAG(LuauCompileTableBuiltinsCreateClear) LUAU_FASTFLAG(LuauCompileReuseLowersLimit) using namespace Luau; @@ -13145,6 +13146,56 @@ RETURN R0 1 ); } +TEST_CASE("TableFastcall") +{ + ScopedFastFlag luauTableBuiltins{FFlag::LuauCompileTableBuiltinsCreateClear, true}; + + // table.create with 1 arg + CHECK_EQ( + "\n" + compileFunction0(R"( +return table.create(42) +)"), + R"( +LOADN R1 42 +FASTCALL1 133 R1 L0 +GETIMPORT R0 2 [table.create] +CALL R0 1 -1 +L0: RETURN R0 -1 +)" + ); + + // table.create with 2 args + CHECK_EQ( + "\n" + compileFunction0(R"( +return table.create(10, 0) +)"), + R"( +LOADN R1 10 +FASTCALL2K 133 R1 K0 L0 [0] +LOADK R2 K0 [0] +GETIMPORT R0 3 [table.create] +CALL R0 2 -1 +L0: RETURN R0 -1 +)" + ); + + // table.clear with 1 arg + CHECK_EQ( + "\n" + compileFunction0(R"( +local t = {} +table.clear(t) +)"), + R"( +NEWTABLE R0 0 0 +FASTCALL1 134 R0 L0 +MOVE R2 R0 +GETIMPORT R1 2 [table.clear] +CALL R1 1 0 +L0: RETURN R0 0 +)" + ); +} + TEST_CASE("BufferIntegerFastcall") { ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; From 32c28089305f488f901aaf1dbf3fd1cb65fa3d11 Mon Sep 17 00:00:00 2001 From: "NotoriousV.I.G" Date: Fri, 23 Oct 2026 14:02:05 -0700 Subject: [PATCH 02/13] Sync to upstream/release/744 (#3071) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Boo! 🦇 🎃 In the lead up to next weeks spooky season, we've fixed a few bugs that have been lurking deep in the bowels of the runtime. ## Runtime Changes - Fix a bug in DSE(Dead Store Elimination) caused by not invalidating tags when the corresponding load was overwritten - Fix an Arm64 crash caused by functions w/ more than 256 constants overflowing the arm64 immediate size. - Support Intel Mac libunwind (we just assume you're using libc++) - INVOKE_FASTPCALL should be registered as being able to invalidate SafeEnv - Fix a crash found by our fuzzer due to slot allocations. - Handful of correctness fixes to Luau integer and bit32 operations - this affects bit32.lrotate, integer.lrotate, integer.extract/replace. - Fix a bug caused by silently casting a uint8_t to an int8_t in the compiler. - Fixes a bug in FORGLOOP register reservation. ## Type System Changes - Width subtyping should not inject `nil` as a type for a stand-in property. Fixes #2625, #2644. - Fix type pack handling in call tail argument position in nonstrict ## Prototype/Experimental projects - Added runtime support for private class fields --- Co-authored-by: Andy Friesen Co-authored-by: Ariel Weiss Co-authored-by: David Cope Co-authored-by: Hunter Goldstein Co-authored-by: Ilya Rezvov Co-authored-by: Sora Kanosue Co-authored-by: Thomas Schollenberger Co-authored-by: Varun Saini Co-authored-by: Vighnesh Vijay Co-authored-by: Vyacheslav Egorov ) { } - else if constexpr (std::is_same_v) - { - e.inferredTy = clone(e.inferredTy); - } else if constexpr (std::is_same_v) { } diff --git a/Analysis/src/IostreamHelpers.cpp b/Analysis/src/IostreamHelpers.cpp index d1c492e86..b84d7afe2 100644 --- a/Analysis/src/IostreamHelpers.cpp +++ b/Analysis/src/IostreamHelpers.cpp @@ -324,8 +324,6 @@ static void errorToString(std::ostream& stream, const T& err) stream << "AmbiguousFunctionCall { " << toString(err.function) << ", " << toString(err.arguments) << " }"; else if constexpr (std::is_same_v) stream << "UninitializedFieldAccess { " << (err.fieldName ? *err.fieldName : "self") << " }"; - else if constexpr (std::is_same_v) - stream << "TypeAnnotationRequired { " << toString(err.inferredTy) << " }"; else if constexpr (std::is_same_v) stream << "ConstructorsShouldNotReturnAnything {}"; else if constexpr (std::is_same_v) diff --git a/Analysis/src/NonStrictTypeChecker.cpp b/Analysis/src/NonStrictTypeChecker.cpp index c2c315ff6..ad2fdb14b 100644 --- a/Analysis/src/NonStrictTypeChecker.cpp +++ b/Analysis/src/NonStrictTypeChecker.cpp @@ -23,6 +23,7 @@ LUAU_FASTFLAG(DebugLuauMagicTypes) LUAU_FASTINTVARIABLE(LuauNonStrictTypeCheckerRecursionLimit, 300) LUAU_FASTFLAGVARIABLE(LuauAddRecursionCounterToNonStrictTypeChecker) +LUAU_FASTFLAGVARIABLE(LuauNonStrictCallTypePacks) LUAU_FASTFLAG(LuauTypeFunctionsAbsenceCache) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) @@ -756,8 +757,24 @@ struct NonStrictTypeChecker } arguments.insert(arguments.end(), call->args.begin(), call->args.end()); + size_t argumentCount = arguments.size(); + bool hasVariadicTail = false; + + if (FFlag::LuauNonStrictCallTypePacks && !arguments.empty()) + { + AstExpr* last = arguments.back(); + TypePackId* tp = module->astTypePacks.find(last); + + if (tp && (last->is() || last->is())) + { + auto [head, tail] = flatten(*tp); + argumentCount = arguments.size() - 1 + head.size(); + hasVariadicTail = tail.has_value(); + } + } + std::vector argTypes; - argTypes.reserve(arguments.size()); + argTypes.reserve(argumentCount); // Move all the types over from the argument typepack for `fn` TypePackIterator curr = begin(fn->argTypes); @@ -770,7 +787,7 @@ struct NonStrictTypeChecker { if (const VariadicTypePack* vtp = get(follow(*argTail))) { - while (argTypes.size() < arguments.size()) + while (argTypes.size() < argumentCount) { argTypes.push_back(vtp->ty); } @@ -778,14 +795,14 @@ struct NonStrictTypeChecker } std::string functionName = getFunctionNameAsString(*call->func).value_or(""); - if (arguments.size() > argTypes.size()) + if (argumentCount > argTypes.size()) { // We are passing more arguments than we expect, so we should error - reportError(CheckedFunctionIncorrectArgs{std::move(functionName), argTypes.size(), arguments.size()}, call->location); + reportError(CheckedFunctionIncorrectArgs{std::move(functionName), argTypes.size(), argumentCount}, call->location); return fresh; } - for (size_t i = 0; i < arguments.size(); i++) + for (size_t i = 0; i < arguments.size() && (!FFlag::LuauNonStrictCallTypePacks || i < argumentCount); i++) { // For example, if the arg is "hi" // The actual arg type is string @@ -820,17 +837,17 @@ struct NonStrictTypeChecker reportError(CheckedFunctionCallError{argTypes[i], *runTimeFailureType, functionName, i}, arg->location); } } - if (arguments.size() < argTypes.size()) + if (argumentCount < argTypes.size() && !hasVariadicTail) { // We are passing fewer arguments than we expect // so we need to ensure that the rest of the args are optional. bool remainingArgsOptional = true; - for (size_t i = arguments.size(); i < argTypes.size(); i++) + for (size_t i = argumentCount; i < argTypes.size(); i++) remainingArgsOptional = remainingArgsOptional && isOptional(argTypes[i]); if (!remainingArgsOptional) { - reportError(CheckedFunctionIncorrectArgs{std::move(functionName), argTypes.size(), arguments.size()}, call->location); + reportError(CheckedFunctionIncorrectArgs{std::move(functionName), argTypes.size(), argumentCount}, call->location); return fresh; } } diff --git a/Analysis/src/OverloadResolver.cpp b/Analysis/src/OverloadResolver.cpp index dc9a14076..18896ceaf 100644 --- a/Analysis/src/OverloadResolver.cpp +++ b/Analysis/src/OverloadResolver.cpp @@ -14,7 +14,6 @@ LUAU_FASTFLAG(LuauFixCallMetamethodErrorReporting) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) -LUAU_FASTFLAGVARIABLE(LuauPropertyModifierMismatchErrorsInArgs) namespace Luau { @@ -731,7 +730,7 @@ void OverloadResolver::maybeEmplaceError( break; } - if (FFlag::LuauPropertyModifierMismatchErrorsInArgs && reason->isPropertyModifierViolation) + if (reason->isPropertyModifierViolation) { std::string reasonStr = explainPropertyModifierViolation(reason->subPath); errors->emplace_back(argLocation, moduleName, TypeMismatch{*wantedType, *givenType, std::move(reasonStr), context}); diff --git a/Analysis/src/Subtyping.cpp b/Analysis/src/Subtyping.cpp index b2618bf8f..bfdd21acc 100644 --- a/Analysis/src/Subtyping.cpp +++ b/Analysis/src/Subtyping.cpp @@ -23,12 +23,11 @@ LUAU_DYNAMIC_FASTINTVARIABLE(LuauSubtypingRecursionLimit, 100) LUAU_FASTFLAGVARIABLE(DebugLuauSubtypingCheckPathValidity) LUAU_FASTINTVARIABLE(LuauSubtypingReasoningLimit, 100) LUAU_FASTINTVARIABLE(LuauSubtypingIterationLimit, 20000) -LUAU_FASTFLAG(LuauPropertyModifierMismatchErrors) LUAU_FASTFLAGVARIABLE(LuauImproveUniqueTableWidthSubtyping) LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) LUAU_FASTFLAG(DebugLuauExactTableTypes) -LUAU_FASTFLAGVARIABLE(LuauDoNotIceForBindingGeneric) LUAU_FASTFLAGVARIABLE(LuauSubtypingSkipUnreadReasoning) +LUAU_FASTFLAGVARIABLE(LuauOnlyCheckWidthSubtypingForReadOnlyProperty) namespace Luau @@ -2157,16 +2156,29 @@ SubtypingResult Subtyping::isCovariantWith( { SubtypingResult result; - if (FFlag::LuauImproveUniqueTableWidthSubtyping) + if (FFlag::LuauOnlyCheckWidthSubtypingForReadOnlyProperty) { - if (forceCovariantTest) - result = isCovariantWith(env, Property::rw(builtinTypes->nilType), superProp, name, forceCovariantTest, scope); + // Under width subtyping, {} <: { read X: T } if `X` is + // *exactly* `unknown` (or `any`). In any other case + // subtyping will fail. + if (superProp.isReadOnly()) + result = isCovariantWith(env, Property::readonly(builtinTypes->unknownType), superProp, name, forceCovariantTest, scope); else - result = isCovariantWith(env, Property::readonly(builtinTypes->nilType), superProp, name, forceCovariantTest, scope); + result = { false }; } else { - result = isCovariantWith(env, Property::readonly(builtinTypes->nilType), superProp, name, forceCovariantTest, scope); + if (FFlag::LuauImproveUniqueTableWidthSubtyping) + { + if (forceCovariantTest) + result = isCovariantWith(env, Property::rw(builtinTypes->nilType), superProp, name, forceCovariantTest, scope); + else + result = isCovariantWith(env, Property::readonly(builtinTypes->nilType), superProp, name, forceCovariantTest, scope); + } + else + { + result = isCovariantWith(env, Property::readonly(builtinTypes->nilType), superProp, name, forceCovariantTest, scope); + } } // We must ignore the actual reasoning from here because the subtype doesn't have a property to traverse into later. @@ -2611,8 +2623,7 @@ SubtypingResult Subtyping::isCovariantWith( if (subIndexer.isReadOnly && !superIndexer.isReadOnly) { result.withBothComponent(TypePath::TypeField::IndexResult); - if (FFlag::LuauPropertyModifierMismatchErrors) - result.withPropertyModifierViolation(); + result.withPropertyModifierViolation(); return result; } @@ -2659,19 +2670,9 @@ SubtypingResult Subtyping::isCovariantWith( if (superProp.isReadWrite()) { if (subProp.isReadOnly()) - { - if (FFlag::LuauPropertyModifierMismatchErrors) - res.andAlso(SubtypingResult{false}.withBothComponent(TypePath::Property::read(name)).withPropertyModifierViolation()); - else - res.andAlso(SubtypingResult{false}.withBothComponent(TypePath::Property::read(name))); - } + res.andAlso(SubtypingResult{false}.withBothComponent(TypePath::Property::read(name)).withPropertyModifierViolation()); else if (subProp.isWriteOnly()) - { - if (FFlag::LuauPropertyModifierMismatchErrors) - res.andAlso(SubtypingResult{false}.withBothComponent(TypePath::Property::write(name)).withPropertyModifierViolation()); - else - res.andAlso(SubtypingResult{false}.withBothComponent(TypePath::Property::write(name))); - } + res.andAlso(SubtypingResult{false}.withBothComponent(TypePath::Property::write(name)).withPropertyModifierViolation()); } } @@ -2897,8 +2898,6 @@ bool Subtyping::bindGeneric(SubtypingEnvironment& env, TypeId subTy, TypeId supe else upperSubBounds.insert(superTy); } - else if (!FFlag::LuauDoNotIceForBindingGeneric && env.containsMappedType(subTy)) - iceReporter->ice("attempting to modify bounds of a potentially visited generic"); if (const auto superBounds = env.mappedGenerics.find(superTy); superBounds && !superBounds->empty()) { @@ -2917,8 +2916,6 @@ bool Subtyping::bindGeneric(SubtypingEnvironment& env, TypeId subTy, TypeId supe else lowerSuperBounds.insert(subTy); } - else if (!FFlag::LuauDoNotIceForBindingGeneric && env.containsMappedType(superTy)) - iceReporter->ice("attempting to modify bounds of a potentially visited generic"); return true; } diff --git a/Analysis/src/TypeChecker2.cpp b/Analysis/src/TypeChecker2.cpp index 503fab5f1..87e5ca90c 100644 --- a/Analysis/src/TypeChecker2.cpp +++ b/Analysis/src/TypeChecker2.cpp @@ -38,12 +38,9 @@ LUAU_FASTFLAGVARIABLE(LuauSkipUnusedTypeTraversals) LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAGVARIABLE(LuauFixCallMetamethodErrorReporting) LUAU_FASTFLAGVARIABLE(LuauCheckFunctionStatementTypes) -LUAU_FASTFLAGVARIABLE(LuauPropertyModifierMismatchErrors) -LUAU_FASTFLAGVARIABLE(DebugLuauWarnOnUnannotatedTopLevelFunctions) LUAU_FASTFLAG(LuauImproveUniqueTableWidthSubtyping) LUAU_FASTFLAGVARIABLE(LuauCallErrorReportingRecoversArgumentLocationsForPacks) LUAU_FASTFLAGVARIABLE(LuauCompoundAssignSeedsAstTypes) -LUAU_FASTFLAGVARIABLE(LuauCannotAddIndexerToTablePrimitive) LUAU_FASTFLAG(LuauNormalizeGuardAgainstNonTestableNegations) LUAU_FASTFLAGVARIABLE(LuauDontUseInnermostScope) LUAU_FASTFLAG(LuauTypeFunctionsAbsenceCache) @@ -1348,56 +1345,6 @@ void TypeChecker2::visit(AstStatCompoundAssign* stat) testIsSubtype(*resultTy, varTy, stat->location); } -void TypeChecker2::checkFunctionAnnotations(AstExprFunction* func, AnnotationCheckMode mode, Location nameLocation) -{ - TypeId ty = lookupType(func); - const FunctionType* ft = get(ty); - - bool missing = false; - - if (ft) - { - TypePack args = extendTypePack(*module->internalTypes, builtinTypes, ft->argTypes, func->args.size); - - for (size_t i = 0; i < func->args.size; ++i) - { - const AstLocal* arg = func->args.data[i]; - if (i == 0 && arg->name == "self" && mode != AnnotationCheckMode::Function) - { - // Annotating the self parameter is already a syntax error. We - // don't need to report anything here. - } - else if (!arg->annotation && i < args.head.size()) - missing = true; - } - - if (func->vararg && !func->varargAnnotation && args.tail.has_value()) - missing = true; - - if (mode == AnnotationCheckMode::Constructor && func->returnAnnotation) - { - reportError(ConstructorsShouldNotReturnAnything{}, func->returnAnnotation->location); - } - else if (!func->returnAnnotation) - { - auto [head, tail] = flatten(ft->retTypes); - - if (!head.empty() || tail.has_value()) - missing = true; - } - } - - if (missing) - { - Location location = nameLocation; - if (func->argLocation) - location.extend(*func->argLocation); - if (func->returnAnnotation) - location.extend(func->returnAnnotation->location); - reportError(TypeAnnotationRequired{ty}, location); - } -} - void TypeChecker2::visit(AstStatFunction* stat) { visit(stat->name, ValueContext::LValue); @@ -1420,17 +1367,11 @@ void TypeChecker2::visit(AstStatFunction* stat) auto rhsType = lookupType(stat->func); testIsSubtype(rhsType, lhsType, stat->func->location); } - - if (FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions && stack.size() == 1) - checkFunctionAnnotations(stat->func, AnnotationCheckMode::Function, stat->name->location); } void TypeChecker2::visit(AstStatLocalFunction* stat) { visit(stat->func); - - if (FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions && stack.size() == 1) - checkFunctionAnnotations(stat->func, AnnotationCheckMode::Function, stat->name->location); } void TypeChecker2::visit(const AstTypeList* typeList) @@ -1602,12 +1543,7 @@ void TypeChecker2::visit(AstStatClass* stat) visit(method->function); if (method->functionName == "__init") - { - checkFunctionAnnotations(method->function, AnnotationCheckMode::Constructor, method->nameLocation); visitConstructor(stat, method); - } - else - checkFunctionAnnotations(method->function, AnnotationCheckMode::Method, method->nameLocation); } else LUAU_ASSERT(!"Unknown class member!"); @@ -2557,8 +2493,7 @@ void TypeChecker2::visit(AstExprIndexExpr* indexExpr, ValueContext context) { return indexExprMetatableHelper(indexExpr, mt, exprType, indexType); } - else if (const auto primitive = get(exprType); - FFlag::LuauCannotAddIndexerToTablePrimitive && primitive && primitive->type == PrimitiveType::Table) + else if (const auto primitive = get(exprType); primitive && primitive->type == PrimitiveType::Table) reportError(CannotExtendTable{exprType, CannotExtendTable::Indexer, "indexer??"}, indexExpr->location); else if (auto cls = get(exprType)) { @@ -3729,7 +3664,7 @@ Reasonings TypeChecker2::explainReasonings_(TID subTy, TID superTy, Location loc std::stringstream reason; - if (FFlag::LuauPropertyModifierMismatchErrors && reasoning.isPropertyModifierViolation) + if (reasoning.isPropertyModifierViolation) { reason << explainPropertyModifierViolation(reasoning.subPath); } diff --git a/Analysis/src/TypeFunctionRuntime.cpp b/Analysis/src/TypeFunctionRuntime.cpp index b31272430..dad947b30 100644 --- a/Analysis/src/TypeFunctionRuntime.cpp +++ b/Analysis/src/TypeFunctionRuntime.cpp @@ -28,7 +28,6 @@ LUAU_FASTINTVARIABLE(DebugLuauTypeFunctionRuntimeHeapLimit, 0) LUAU_DYNAMIC_FASTINT(LuauTypeFunctionSerdeIterationLimit) LUAU_FASTFLAG(LuauIntegerType2) -LUAU_FASTFLAGVARIABLE(LuauTypeFunctionSerializeArgNames) LUAU_FASTFLAGVARIABLE(LuauUdtfFixTypeNameTypo) LUAU_FASTFLAGVARIABLE(LuauUdtfTerseChunkNames) @@ -2874,8 +2873,7 @@ class TypeFunctionCloner f2->argTypes = shallowClone(f1->argTypes); f2->retTypes = shallowClone(f1->retTypes); - if (FFlag::LuauTypeFunctionSerializeArgNames) - f2->argNames = f1->argNames; + f2->argNames = f1->argNames; } void cloneChildren(TypeFunctionExternType* c1, TypeFunctionExternType* c2) diff --git a/Analysis/src/TypeFunctionRuntimeBuilder.cpp b/Analysis/src/TypeFunctionRuntimeBuilder.cpp index 82787ad38..d9015be8a 100644 --- a/Analysis/src/TypeFunctionRuntimeBuilder.cpp +++ b/Analysis/src/TypeFunctionRuntimeBuilder.cpp @@ -20,8 +20,6 @@ // currently, controls serialization, deserialization, and `type.copy` LUAU_DYNAMIC_FASTINTVARIABLE(LuauTypeFunctionSerdeIterationLimit, 100'000); -LUAU_FASTFLAG(LuauTypeFunctionSerializeArgNames) - namespace Luau { @@ -415,16 +413,13 @@ class TypeFunctionSerializer f2->argTypes = shallowSerialize(f1->argTypes); f2->retTypes = shallowSerialize(f1->retTypes); - if (FFlag::LuauTypeFunctionSerializeArgNames) + f2->argNames.reserve(f1->argNames.size()); + for (const auto& argName : f1->argNames) { - f2->argNames.reserve(f1->argNames.size()); - for (const auto& argName : f1->argNames) - { - if (argName) - f2->argNames.emplace_back(argName->name); - else - f2->argNames.emplace_back(); - } + if (argName) + f2->argNames.emplace_back(argName->name); + else + f2->argNames.emplace_back(); } } @@ -1028,16 +1023,13 @@ class TypeFunctionDeserializer if (f2->retTypes) f1->retTypes = shallowDeserialize(f2->retTypes); - if (FFlag::LuauTypeFunctionSerializeArgNames) + f1->argNames.reserve(f2->argNames.size()); + for (const auto& name : f2->argNames) { - f1->argNames.reserve(f2->argNames.size()); - for (const auto& name : f2->argNames) - { - if (name) - f1->argNames.emplace_back(FunctionArgument{*name, {}}); - else - f1->argNames.emplace_back(); - } + if (name) + f1->argNames.emplace_back(FunctionArgument{*name, {}}); + else + f1->argNames.emplace_back(); } } diff --git a/Ast/include/Luau/Ast.h b/Ast/include/Luau/Ast.h index 85e362d65..178af326d 100644 --- a/Ast/include/Luau/Ast.h +++ b/Ast/include/Luau/Ast.h @@ -486,7 +486,8 @@ class AstExprIndexName : public AstExpr const AstName& index, const Location& indexLocation, const Position& opPosition, - char op + char op, + bool privateAccess = false ); void visit(AstVisitor* visitor) override; @@ -496,6 +497,8 @@ class AstExprIndexName : public AstExpr Location indexLocation; Position opPosition; char op = '.'; + // Indicates a private field/method access made within a class method body + bool privateAccess = false; }; class AstExprIndexExpr : public AstExpr @@ -1141,6 +1144,12 @@ struct AstDeclaredExternTypeProperty AstTableAccess access = AstTableAccess::ReadWrite; }; +enum class AstClassAccess +{ + Public, + Private, +}; + struct AstClassProperty { Location qualifierLocation; @@ -1148,15 +1157,18 @@ struct AstClassProperty Location nameLocation; std::optional typeColonLocation = std::nullopt; AstType* ty = nullptr; + AstClassAccess access = AstClassAccess::Public; }; struct AstClassMethod { + // Methods with no access modifiers are public by default. std::optional qualifierLocation; Location keywordLocation; AstName functionName; Location nameLocation; - AstExprFunction* function; + AstExprFunction* function = nullptr; + AstClassAccess access = AstClassAccess::Public; }; using AstClassMember = Variant; diff --git a/Ast/include/Luau/Parser.h b/Ast/include/Luau/Parser.h index 10d9223d2..d0a6f3180 100644 --- a/Ast/include/Luau/Parser.h +++ b/Ast/include/Luau/Parser.h @@ -559,6 +559,10 @@ class Parser std::vector functionStack; size_t typeFunctionDepth = 0; + // True while parsing the body of a class method, which is the only context where `._x` / `:_x` denotes a private member access. Set exclusively + // by parseClassStat. + bool inClassMethodBody = false; + DenseHashMap localMap; std::vector localStack; DenseHashSet classesWithinModule; diff --git a/Ast/src/Ast.cpp b/Ast/src/Ast.cpp index 0a6739f61..19ec34389 100644 --- a/Ast/src/Ast.cpp +++ b/Ast/src/Ast.cpp @@ -270,7 +270,8 @@ AstExprIndexName::AstExprIndexName( const AstName& index, const Location& indexLocation, const Position& opPosition, - char op + char op, + bool privateAccess ) : AstExpr(ClassIndex(), location) , expr(expr) @@ -278,6 +279,7 @@ AstExprIndexName::AstExprIndexName( , indexLocation(indexLocation) , opPosition(opPosition) , op(op) + , privateAccess(privateAccess) { } diff --git a/Ast/src/Parser.cpp b/Ast/src/Parser.cpp index 5c4a22f73..36ccbb4ae 100644 --- a/Ast/src/Parser.cpp +++ b/Ast/src/Parser.cpp @@ -1527,6 +1527,37 @@ const std::unordered_set kExplicitlyDisallowedMetamethods{ "__type", }; +constexpr size_t kMaxClassPrivateProperties = 255; + +// A single leading underscore marks a private member. Metamethod names begin with +// '__' and are public, so they are deliberately excluded: `self.__tostring` inside +// a method body must remain an ordinary property access. +bool isPrivateFieldName(const AstName& name) +{ + return name.value && name.value[0] == '_' && name.value[1] != '_'; +} + +// Returns the diagnostic for a class member whose name is illegal for its access +// modifier, or nullptr when the name is acceptable. Public '__' names are reported +// as nullptr here because they are metamethods, validated against +// kAllowedMetamethods / kExplicitlyDisallowedMetamethods instead. +const char* getClassFieldNameError(const AstName& name, AstClassAccess access) +{ + LUAU_ASSERT(name.value); + + if (access == AstClassAccess::Private) + { + if (strncmp(name.value, "__", 2) == 0) + return "Private class properties cannot start with '__'"; + else if (name.value[0] != '_') + return "Private class properties must begin with '_'"; + } + else if (isPrivateFieldName(name)) + return "Public class properties cannot begin with '_'"; + + return nullptr; +} + } // namespace // classStatement ::= [`open`] `class` Name classProps `end` @@ -1569,18 +1600,33 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export // slightly more performant here (e.g.: a "scratch" set). DenseHashSet classMemberNamespace; + size_t privateFieldCount = 0; + size_t privateMethodCount = 0; + while (lexer.current().type != Lexeme::ReservedEnd && lexer.current().type != Lexeme::Eof) { + std::optional access; std::optional qualifierLocation; - if (lexer.current().type == Lexeme::Name && AstName(lexer.current().name) == "public") + if (lexer.current().type == Lexeme::Name) { - qualifierLocation = lexer.current().location; - nextLexeme(); + AstName currName = AstName(lexer.current().name); + if (currName == "public") + { + access = AstClassAccess::Public; + qualifierLocation = lexer.current().location; + nextLexeme(); + } + else if (currName == "private") + { + access = AstClassAccess::Private; + qualifierLocation = lexer.current().location; + nextLexeme(); + } } // If we saw a qualifier _and_ the current token is not `function`, // assume this is a property. - if (qualifierLocation && lexer.current().type != Lexeme::ReservedFunction) + if (access && lexer.current().type != Lexeme::ReservedFunction) { std::optional propName = parseNameOpt("class property name"); if (!propName) @@ -1596,7 +1642,9 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export propType = parseType(); } - if (strncmp(propName->name.value, "__", 2) == 0) + if (const char* nameError = getClassFieldNameError(propName->name, *access)) + report(propName->location, "%s", nameError); + else if (strncmp(propName->name.value, "__", 2) == 0) report(propName->location, "Class properties cannot start with '__'"); else if (classMemberNamespace.contains(propName->name)) report(propName->location, "Duplicate class member '%s'", propName->name.value); @@ -1604,6 +1652,9 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export { classMemberNamespace.insert(propName->name); + if (*access == AstClassAccess::Private) + privateFieldCount++; + // Either both of these are present or neither are. LUAU_ASSERT((bool)propType == (bool)typeColonLocation); declarations.push_back( @@ -1613,12 +1664,16 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export propName->location, typeColonLocation, propType, + *access, } ); } } else if (lexer.current().type == Lexeme::ReservedFunction) { + if (!access.has_value()) + access = AstClassAccess::Public; + auto matchFunction = lexer.current(); nextLexeme(); @@ -1637,14 +1692,21 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export // the class' print. That would be `self.print`. matchRecoveryStopOnToken[Lexeme::ReservedEnd]++; + bool oldInClassMethodBody = inClassMethodBody; + inClassMethodBody = true; + auto [body, _] = parseFunctionBody(false, matchFunction, name.name, nullptr, {}); + inClassMethodBody = oldInClassMethodBody; + matchRecoveryStopOnToken[Lexeme::ReservedEnd]--; if (body->args.size > 0 && body->args.data[0]->name == "self" && body->args.data[0]->annotation != nullptr) report(body->args.data[0]->annotation->location, "The 'self' parameter cannot have a type annotation"); - if (strncmp(name.name.value, "__", 2) == 0) + if (const char* nameError = getClassFieldNameError(name.name, *access)) + report(name.location, "%s", nameError); + else if (strncmp(name.name.value, "__", 2) == 0) { if (kExplicitlyDisallowedMetamethods.count(name.name.value) > 0) report(name.location, "Classes cannot define '%s' as a metamethod", name.name.value); @@ -1652,8 +1714,7 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export report(name.location, "Cannot use '%s' as a method name: names starting with '__' are reserved", name.name.value); } - // TODO CLI-200853: We should support attributes, we do not need - // to support them prior to the full launch. + // TODO CLI-200853: We should support attributes, we do not need to support them prior to the full launch. if (classMemberNamespace.contains(name.name)) { report(name.location, "Duplicate class member '%s'", name.name.value); @@ -1662,6 +1723,9 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export { classMemberNamespace.insert(name.name); + if (*access == AstClassAccess::Private) + privateMethodCount++; + declarations.push_back( AstClassMethod{ qualifierLocation, @@ -1669,6 +1733,7 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export name.name, name.location, body, + *access, } ); } @@ -1680,6 +1745,12 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export } } + if (privateFieldCount > kMaxClassPrivateProperties) + report(name->location, "Exceeded the maximum of %zu private fields in a class", kMaxClassPrivateProperties); + + if (privateMethodCount > kMaxClassPrivateProperties) + report(name->location, "Exceeded the maximum of %zu private methods in a class", kMaxClassPrivateProperties); + // TODO: We should use `expectMatchEndAndConsume`. It is difficult as we // are treating "class" as a contextual keyword (and we must as we also) // plan to add a `class` library. @@ -3808,7 +3879,18 @@ AstExpr* Parser::parsePrimaryExpr(bool asStatement) Name index = parseIndexName(nullptr, opPosition); - expr = allocator.alloc(Location(start, index.location.end), expr, index.name, index.location, opPosition, '.'); + if (inClassMethodBody) + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + expr = allocator.alloc( + Location(start, index.location.end), + expr, + index.name, + index.location, + opPosition, + '.', + inClassMethodBody && isPrivateFieldName(index.name) + ); } else if (lexer.current().type == '[') { @@ -3876,7 +3958,14 @@ AstExpr* Parser::parseMethodCall(Position start, AstExpr* expr) nextLexeme(); Name index = parseIndexName("method name", opPosition); - AstExpr* func = allocator.alloc(Location(start, index.location.end), expr, index.name, index.location, opPosition, ':'); + + // See the equivalent '.' access in parsePrimaryExpr for why the bool is tested first. + if (inClassMethodBody) + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + AstExpr* func = allocator.alloc( + Location(start, index.location.end), expr, index.name, index.location, opPosition, ':', inClassMethodBody && isPrivateFieldName(index.name) + ); AstArray typeArguments; CstTypeInstantiation* cstTypeArguments = options.storeCstData ? allocator.alloc() : nullptr; diff --git a/Ast/src/PrettyPrinter.cpp b/Ast/src/PrettyPrinter.cpp index 343cb4a46..4e9b62569 100644 --- a/Ast/src/PrettyPrinter.cpp +++ b/Ast/src/PrettyPrinter.cpp @@ -1382,7 +1382,7 @@ struct Printer [&](const AstClassProperty& prop) { writer.advance(prop.qualifierLocation.begin); - writer.keyword("public"); + writer.keyword(prop.access == AstClassAccess::Private ? "private" : "public"); writer.advance(prop.nameLocation.begin); writer.identifier(prop.name.value); if (writeTypes && prop.ty) @@ -1398,7 +1398,7 @@ struct Printer if (method.qualifierLocation) { writer.advance(method.qualifierLocation->begin); - writer.keyword("public"); + writer.keyword(method.access == AstClassAccess::Private ? "private" : "public"); } writer.advance(method.keywordLocation.begin); writer.keyword("function"); diff --git a/Bytecode/include/Luau/BytecodeBuilder.h b/Bytecode/include/Luau/BytecodeBuilder.h index 3cfc61516..fd5b6d665 100644 --- a/Bytecode/include/Luau/BytecodeBuilder.h +++ b/Bytecode/include/Luau/BytecodeBuilder.h @@ -63,6 +63,9 @@ class BytecodeBuilder struct ClassShape { int32_t className; + uint8_t numPrivateInstanceProps = 0; + uint8_t numPrivateStaticProps = 0; + // We only keep names for public properties. Private fields are indexed by their statically determined offsets std::vector propertyNames; std::vector methodNames; }; diff --git a/Bytecode/include/Luau/BytecodeCallInliner.h b/Bytecode/include/Luau/BytecodeCallInliner.h index d482270e6..b33210ddf 100644 --- a/Bytecode/include/Luau/BytecodeCallInliner.h +++ b/Bytecode/include/Luau/BytecodeCallInliner.h @@ -10,6 +10,7 @@ #include LUAU_FASTFLAG(LuauInlinerNamecallSelfFromMove) +LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) namespace Luau { @@ -748,6 +749,17 @@ struct CallInliner if (target.nups > 0) return false; + if (FFlag::DebugLuauUserDefinedClassesRuntime) + { + // inlining private field namecalls is not supported yet + if (BcOp callTarget = call.Target(); callTarget.kind == BcOpKind::Proj) + { + BcOp producer = caller.projOp(callTarget).op; + if (producer.kind == BcOpKind::Inst && caller.instOp(producer).op == LOP_GETPRIVATEFIELD) + return false; + } + } + caller.maxstacksize = newMaxStackSize; auto [prevBlock, nextBlock] = splitBlockOnOp(call.op()); diff --git a/Bytecode/include/Luau/BytecodeSlotAllocation.h b/Bytecode/include/Luau/BytecodeSlotAllocation.h index f045bcca1..29dcebde5 100644 --- a/Bytecode/include/Luau/BytecodeSlotAllocation.h +++ b/Bytecode/include/Luau/BytecodeSlotAllocation.h @@ -70,6 +70,8 @@ inline bool isLayoutBarrier(LuauOpcode op) case LOP_GETVARARGS: case LOP_CAPTURE: case LOP_CLOSEUPVALS: + // NEWCLASS writes A before reading its superclass from B, so the two must not share a slot + case LOP_NEWCLASS: return true; default: return false; @@ -248,6 +250,16 @@ struct SlotAllocator reserve(operand); } + if (instruction.op == LOP_CALL || instruction.op == LOP_CALLFB) + { + // fixed calls write every encoded result even when no projection reads it + // inlining only materializes used projections + std::optional results = immediate(instruction, 1); + if (std::optional base = inheritedSlot(instructionOp); base && results && *results > 0) + for (uint32_t slot = *base; slot < std::min(*base + uint32_t(*results), inheritedFrame); ++slot) + reserve(slot); + } + if (instruction.op == LOP_FORNPREP) { // numeric for uses four consecutive slots starting at the instruction result @@ -258,10 +270,19 @@ struct SlotAllocator if (instruction.op == LOP_FORGLOOP && !instruction.ops.empty()) { - // the generic for fast paths store a key/value pair to A+3/A+4 even for one variable, beyond the projections the graph has + // the generic-for fast paths store a key/value pair to A+3/A+4 even for one variable + // larger loops also write every encoded result through A+2+vars if (std::optional base = inheritedSlot(instruction.ops[0])) - for (uint32_t slot = *base; slot < std::min(*base + 5, inheritedFrame); ++slot) + { + std::optional vars = immediate(instruction, 4); + if (!vars || *vars < 1) + // per Compiler.cpp, "note that we reserve at least 2 variables; this allows our fast path to assume that we need 2 variables instead of 1 or 2" + vars = 2; + + uint32_t width = std::max(5, uint32_t(*vars) + 3); + for (uint32_t slot = *base; slot < std::min(*base + width, inheritedFrame); ++slot) reserve(slot); + } } bool openProducer = isProducer(instruction); diff --git a/Bytecode/src/BytecodeBuilder.cpp b/Bytecode/src/BytecodeBuilder.cpp index 3b3ad9485..d3e6c5ccc 100644 --- a/Bytecode/src/BytecodeBuilder.cpp +++ b/Bytecode/src/BytecodeBuilder.cpp @@ -1,6 +1,7 @@ // This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details #include "Luau/BytecodeBuilder.h" +#include "Luau/Bytecode.h" #include "Luau/BytecodeUtils.h" #include "Luau/SmallVector.h" #include "Luau/StringUtils.h" @@ -18,8 +19,6 @@ LUAU_FASTFLAGVARIABLE(LuauCompileRefactorFeedback) LUAU_FASTFLAGVARIABLE(LuauBytecodeCostModel) LUAU_FASTFLAGVARIABLE(LuauCompileCallFbRemap) LUAU_FLAGVERSION(LuauBytecodeCostModel, 2) -LUAU_FASTFLAGVARIABLE(LuauCompileEmitVectorDouble) -LUAU_FLAGVERSION(LuauCompileEmitVectorDouble, 2) LUAU_FASTFLAGVARIABLE(LuauCompileFastpcall) LUAU_FLAGVERSION(LuauCompileFastpcall, 2) @@ -836,8 +835,7 @@ void BytecodeBuilder::finalize() for (const Function& func : functions) { - if (FFlag::LuauBytecodeCostModel || FFlag::LuauCompileEmitVectorDouble || FFlag::LuauCompileFastpcall || FFlag::DebugLuauUserDefinedClasses) - writeVarInt(bytecode, func.data.size()); + writeVarInt(bytecode, func.data.size()); bytecode += func.data; } @@ -938,22 +936,11 @@ void BytecodeBuilder::writeFunction(std::string& ss, uint32_t id, uint8_t flags, break; case Constant::Type_Vectord: - if (FFlag::LuauCompileEmitVectorDouble) - { - writeByte(ss, LBC_CONSTANT_VECTORD); - writeDouble(ss, c.valueVectord[0]); - writeDouble(ss, c.valueVectord[1]); - writeDouble(ss, c.valueVectord[2]); - writeDouble(ss, c.valueVectord[3]); - } - else - { - writeByte(ss, LBC_CONSTANT_VECTOR); - writeFloat(ss, float(c.valueVectord[0])); - writeFloat(ss, float(c.valueVectord[1])); - writeFloat(ss, float(c.valueVectord[2])); - writeFloat(ss, float(c.valueVectord[3])); - } + writeByte(ss, LBC_CONSTANT_VECTORD); + writeDouble(ss, c.valueVectord[0]); + writeDouble(ss, c.valueVectord[1]); + writeDouble(ss, c.valueVectord[2]); + writeDouble(ss, c.valueVectord[3]); break; case Constant::Type_String: @@ -1091,13 +1078,12 @@ void BytecodeBuilder::writeFunction(std::string& ss, uint32_t id, uint8_t flags, } } } - else if (FFlag::LuauBytecodeCostModel || FFlag::LuauCompileEmitVectorDouble || FFlag::LuauCompileFastpcall || FFlag::DebugLuauUserDefinedClasses) + else { writeVarInt(ss, 0); // Empty feedback vector } - if ((FFlag::LuauBytecodeCostModel || FFlag::LuauCompileEmitVectorDouble || FFlag::LuauCompileFastpcall || FFlag::DebugLuauUserDefinedClasses) && - (flags & LPF_INLINABLE) != 0) + if ((flags & LPF_INLINABLE) != 0) { writeVarInt(ss, cost); } @@ -1106,8 +1092,10 @@ void BytecodeBuilder::writeFunction(std::string& ss, uint32_t id, uint8_t flags, void BytecodeBuilder::writeClassShape(std::string& ss, const ClassShape& cs) const { writeVarInt(ss, cs.className); - writeVarInt(ss, cs.propertyNames.size()); - writeVarInt(ss, cs.methodNames.size()); + writeByte(ss, cs.numPrivateInstanceProps); + writeByte(ss, cs.numPrivateStaticProps); + writeVarInt(ss, cs.propertyNames.size() + cs.numPrivateInstanceProps); + writeVarInt(ss, cs.methodNames.size() + cs.numPrivateStaticProps); for (const auto propName : cs.propertyNames) writeVarInt(ss, propName); for (const auto methodName : cs.methodNames) @@ -1517,13 +1505,6 @@ uint8_t BytecodeBuilder::getVersion() if (FFlag::LuauCompileFastpcall) return 14; - if (FFlag::LuauCompileEmitVectorDouble) - return 13; - if (FFlag::LuauBytecodeCostModel) - return 12; - - if (FFlag::LuauEmitCallFeedback) - return 11; return LBC_VERSION_TARGET; } @@ -1968,11 +1949,16 @@ void BytecodeBuilder::validateInstructions() const break; case LOP_NEWCLASSMEMBER: + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); VREG(LUAU_INSN_A(insn)); - LUAU_ASSERT(LUAU_INSN_B(insn) == 0); + LuauClassMemberVisibility visibility = LuauClassMemberVisibility(LUAU_INSN_B(insn)); + LUAU_ASSERT(visibility == LuauClassMemberVisibility::LCMV_PUBLIC || visibility == LuauClassMemberVisibility::LCMV_PRIVATE); VREG(LUAU_INSN_C(insn)); - VCONST(insns[i + 1], String); - break; + if (visibility == LuauClassMemberVisibility::LCMV_PUBLIC) + VCONST(insns[i + 1], String); + } + break; case LOP_GETUDATAKS: case LOP_SETUDATAKS: @@ -2023,6 +2009,30 @@ void BytecodeBuilder::validateInstructions() const LUAU_ASSERT(LUAU_INSN_OP(insns[i + 1 + LUAU_INSN_C(insn)]) == LOP_CALL); break; + case LOP_GETPRIVATEFIELD: + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + VREG(LUAU_INSN_A(insn)); + VREG(LUAU_INSN_B(insn)); + VUPVAL(LUAU_INSN_C(insn)); + uint32_t reserved = insns[i + 1] >> 10; + LUAU_ASSERT(reserved == 0); + if (LUAU_INSN_AUX_NAMECALL(insns[i + 1])) + { + VREG(LUAU_INSN_A(insn) + 1); + LUAU_ASSERT(LUAU_INSN_OP(insns[i + 2]) == LOP_CALLFB || LUAU_INSN_OP(insns[i + 2]) == LOP_CALL); + } + } + break; + + case LOP_SETPRIVATEFIELD: + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + VREG(LUAU_INSN_A(insn)); + VREG(LUAU_INSN_B(insn)); + VUPVAL(LUAU_INSN_C(insn)); + LUAU_ASSERT(insns[i + 1] >> 8 == 0); + break; + default: LUAU_ASSERT(!"Unsupported opcode"); } @@ -2381,31 +2391,13 @@ void BytecodeBuilder::dumpConstant(std::string& result, int k, bool detailed) co formatAppend(result, "%.9g, %.9g, %.9g, %.9g", data.valueVectorf[0], data.valueVectorf[1], data.valueVectorf[2], data.valueVectorf[3]); break; case Constant::Type_Vectord: - if (FFlag::LuauCompileEmitVectorDouble) - { - // 3-vectors is the most common configuration, so truncate to three components if possible - if (data.valueVectord[3] == 0.0) - formatAppend(result, "%.17g, %.17g, %.17g", data.valueVectord[0], data.valueVectord[1], data.valueVectord[2]); - else - formatAppend( - result, "%.17g, %.17g, %.17g, %.17g", data.valueVectord[0], data.valueVectord[1], data.valueVectord[2], data.valueVectord[3] - ); - } + // 3-vectors is the most common configuration, so truncate to three components if possible + if (data.valueVectord[3] == 0.0) + formatAppend(result, "%.17g, %.17g, %.17g", data.valueVectord[0], data.valueVectord[1], data.valueVectord[2]); else - { - // 3-vectors is the most common configuration, so truncate to three components if possible - if (data.valueVectord[3] == 0.0f) - formatAppend(result, "%.9g, %.9g, %.9g", float(data.valueVectord[0]), float(data.valueVectord[1]), float(data.valueVectord[2])); - else - formatAppend( - result, - "%.9g, %.9g, %.9g, %.9g", - float(data.valueVectord[0]), - float(data.valueVectord[1]), - float(data.valueVectord[2]), - float(data.valueVectord[3]) - ); - } + formatAppend( + result, "%.17g, %.17g, %.17g, %.17g", data.valueVectord[0], data.valueVectord[1], data.valueVectord[2], data.valueVectord[3] + ); break; case Constant::Type_String: { @@ -2556,7 +2548,16 @@ void BytecodeBuilder::dumpConstant(std::string& result, int k, bool detailed) co // This should always be printable, in fact this should always be a // valid Luau identifier! LUAU_ASSERT(printableStringConstant(str.data, str.length)); - formatAppend(result, "class %.*s (props: %zu, methods: %zu)", int(str.length), str.data, cs.propertyNames.size(), cs.methodNames.size()); + formatAppend( + result, + "class %.*s (public fields: %zu, public methods: %zu, private fields: %u, private methods: %u)", + int(str.length), + str.data, + cs.propertyNames.size(), + cs.methodNames.size(), + cs.numPrivateInstanceProps, + cs.numPrivateStaticProps + ); if (detailed) { @@ -3013,9 +3014,17 @@ void BytecodeBuilder::dumpInstruction(const uint32_t* code, std::string& result, break; case LOP_NEWCLASSMEMBER: - formatAppend(result, "NEWCLASSMEMBER R%d R%d [", LUAU_INSN_A(insn), LUAU_INSN_C(insn)); - dumpConstant(result, *code, false); - result.append("]\n"); + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + if (LuauClassMemberVisibility(LUAU_INSN_B(insn)) == LuauClassMemberVisibility::LCMV_PRIVATE) + formatAppend(result, "NEWCLASSMEMBER R%d R%d %d [private]\n", LUAU_INSN_A(insn), LUAU_INSN_C(insn), LUAU_INSN_AUX_A(*code)); + else + { + formatAppend(result, "NEWCLASSMEMBER R%d R%d [public] [", LUAU_INSN_A(insn), LUAU_INSN_C(insn)); + dumpConstant(result, *code, false); + result.append("]\n"); + } + code++; break; @@ -3028,6 +3037,8 @@ void BytecodeBuilder::dumpInstruction(const uint32_t* code, std::string& result, break; case LOP_NEWCLASS: + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + if (LUAU_INSN_B(insn) == 0xff) formatAppend(result, "NEWCLASS R%d no_base K%d %d [", LUAU_INSN_A(insn), *code, LUAU_INSN_C(insn)); else @@ -3047,6 +3058,22 @@ void BytecodeBuilder::dumpInstruction(const uint32_t* code, std::string& result, formatAppend(result, "FINCONSTRUCT R%d L%d\n", LUAU_INSN_A(insn), targetLabel); break; + case LOP_GETPRIVATEFIELD: + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + formatAppend(result, "GETPRIVATEFIELD R%d R%d U%d %d [", LUAU_INSN_A(insn), LUAU_INSN_B(insn), LUAU_INSN_C(insn), LUAU_INSN_AUX_A(*code)); + formatAppend(result, "%s]%s\n", LUAU_INSN_AUX_STATIC(*code) ? "static" : "instance", LUAU_INSN_AUX_NAMECALL(*code) ? " [namecall]" : ""); + code++; + break; + + case LOP_SETPRIVATEFIELD: + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + formatAppend(result, "SETPRIVATEFIELD R%d R%d U%d %d\n", LUAU_INSN_A(insn), LUAU_INSN_B(insn), LUAU_INSN_C(insn), LUAU_INSN_AUX_A(*code)); + + code++; + break; + default: LUAU_ASSERT(!"Unsupported opcode"); } diff --git a/Bytecode/src/BytecodeDump.cpp b/Bytecode/src/BytecodeDump.cpp index d5fdd9a12..4669116ff 100644 --- a/Bytecode/src/BytecodeDump.cpp +++ b/Bytecode/src/BytecodeDump.cpp @@ -249,6 +249,10 @@ const char* getLuauOpcodeName(LuauOpcode cmd) return "CONSTRUCT"; case LOP_FINCONSTRUCT: return "FINCONSTRUCT"; + case LOP_GETPRIVATEFIELD: + return "GETPRIVATEFIELD"; + case LOP_SETPRIVATEFIELD: + return "SETPRIVATEFIELD"; default: LUAU_ASSERT(!"Unsupported opcode"); return "unknown"; diff --git a/Bytecode/src/BytecodeGraph.cpp b/Bytecode/src/BytecodeGraph.cpp index d0cc91289..5c3e9dcb4 100644 --- a/Bytecode/src/BytecodeGraph.cpp +++ b/Bytecode/src/BytecodeGraph.cpp @@ -177,8 +177,11 @@ std::optional fromFunctionBytecode(std::string bytecode, std BytecodeBuilder::ClassShape shape; shape.className = readVarInt(data, offset); - uint32_t numProps = readVarInt(data, offset); - uint32_t numMethods = readVarInt(data, offset); + shape.numPrivateInstanceProps = read(data, offset); + shape.numPrivateStaticProps = read(data, offset); + + uint32_t numProps = readVarInt(data, offset) - shape.numPrivateInstanceProps; + uint32_t numMethods = readVarInt(data, offset) - shape.numPrivateStaticProps; shape.propertyNames.reserve(numProps); shape.methodNames.reserve(numMethods); diff --git a/Bytecode/src/BytecodeGraphParser.h b/Bytecode/src/BytecodeGraphParser.h index c52ac63ff..bc5d44f4c 100644 --- a/Bytecode/src/BytecodeGraphParser.h +++ b/Bytecode/src/BytecodeGraphParser.h @@ -1022,11 +1022,18 @@ struct BytecodeGraphParser break; case LOP_NEWCLASSMEMBER: + { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); addVmRegInput(node, LUAU_INSN_A(insn)); + uint8_t flags = LUAU_INSN_B(insn); + addImmInput(node, static_cast(flags)); addVmRegInput(node, LUAU_INSN_C(insn)); - addVmConstInput(node, aux); - break; + if (flags & 0x1) + addImmInput(node, aux); + else + addVmConstInput(node, aux); + } + break; case LOP_FASTPCALL: addImmInput(node, static_cast(LUAU_INSN_A(insn))); @@ -1034,6 +1041,7 @@ struct BytecodeGraphParser // turn it in BcOp to CALL BcInst&. addImmInput(node, static_cast(LUAU_INSN_C(insn))); break; + case LOP_NEWCLASS: LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); @@ -1059,6 +1067,32 @@ struct BytecodeGraphParser addVmRegInput(node, LUAU_INSN_A(insn)); addImmInput(node, static_cast(LUAU_INSN_C(insn))); break; + + case LOP_GETPRIVATEFIELD: + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + addVmRegInput(node, LUAU_INSN_B(insn)); + addUpvalInput(node, LUAU_INSN_C(insn)); + addImmInput(node, aux); + + if (LUAU_INSN_AUX_NAMECALL(aux)) + { + func.regs[nodeOp] = LUAU_INSN_A(insn); + addProducer(LUAU_INSN_A(insn), func.addProj(nodeOp, 0)); + addProducer(LUAU_INSN_A(insn) + 1, func.addProj(nodeOp, 1)); + } + else + addProducer(LUAU_INSN_A(insn), nodeOp); + break; + + case LOP_SETPRIVATEFIELD: + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + addVmRegInput(node, LUAU_INSN_A(insn)); + addVmRegInput(node, LUAU_INSN_B(insn)); + addUpvalInput(node, LUAU_INSN_C(insn)); + addImmInput(node, aux); + break; case LOP__COUNT: LUAU_UNREACHABLE(); diff --git a/Bytecode/src/BytecodeGraphSerializer.h b/Bytecode/src/BytecodeGraphSerializer.h index fa5e93c54..8e52be673 100644 --- a/Bytecode/src/BytecodeGraphSerializer.h +++ b/Bytecode/src/BytecodeGraphSerializer.h @@ -1,6 +1,7 @@ // This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details #pragma once +#include "Luau/Bytecode.h" #include "Luau/BytecodeGraph.h" #include "Luau/BytecodeUtils.h" #include "Luau/BytecodeOps.h" @@ -654,10 +655,13 @@ struct BytecodeGraphSerializer break; case LOP_NEWCLASSMEMBER: + { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); - bcb.emitABC(LOP_NEWCLASSMEMBER, getRegInput(insn, 0), 0, getRegInput(insn, 1)); - bcb.emitAux(getVmConstInputAux(insn, 2)); - break; + int32_t flags = getImmInt(insn, 1); + bcb.emitABC(LOP_NEWCLASSMEMBER, getRegInput(insn, 0), flags, getRegInput(insn, 2)); + bcb.emitAux(flags & 0x1 ? getImmImport(insn, 3) : getVmConstInputAux(insn, 3)); + } + break; case LOP_CMPPROTO: recordJump(insn, 2); @@ -689,6 +693,22 @@ struct BytecodeGraphSerializer bcb.emitABC(LOP_FINCONSTRUCT, getRegInput(insn, 0), 0, getImmInt(insn, 1)); break; + case LOP_GETPRIVATEFIELD: + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + bcb.emitABC(LOP_GETPRIVATEFIELD, getRegister(insnOp), getRegInput(insn, 0), getUpvalInput(insn, 1)); + + bcb.emitAux(getImmImport(insn, 2)); + break; + + case LOP_SETPRIVATEFIELD: + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + bcb.emitABC(LOP_SETPRIVATEFIELD, getRegInput(insn, 0), getRegInput(insn, 1), getUpvalInput(insn, 2)); + + bcb.emitAux(getImmImport(insn, 3)); + break; + case LOP__COUNT: LUAU_UNREACHABLE(); } diff --git a/CLI/src/Analyze.cpp b/CLI/src/Analyze.cpp index 9f86a618f..610ecc829 100644 --- a/CLI/src/Analyze.cpp +++ b/CLI/src/Analyze.cpp @@ -1,9 +1,12 @@ // This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details #include "Luau/BuiltinDefinitions.h" #include "Luau/Config.h" +#include "Luau/ControlFlowGraph.h" +#include "Luau/DumpCFG.h" #include "Luau/Frontend.h" #include "Luau/LuauConfig.h" #include "Luau/ModuleResolver.h" +#include "Luau/Parser.h" #include "Luau/PrettyPrinter.h" #include "Luau/StringUtils.h" #include "Luau/TimeTrace.h" @@ -34,6 +37,7 @@ LUAU_FASTFLAG(DebugLuauTimeTracing) LUAU_FASTFLAG(DebugLuauLogSolverToJsonFile) +LUAU_FASTFLAG(DebugLuauAnalyzeDumpsCFG) enum class ReportFormat { @@ -129,6 +133,42 @@ static bool reportModuleResult(Luau::Frontend& frontend, const Luau::ModuleName& return cr->errors.empty() && cr->lintResult.errors.empty(); } +static int dumpControlFlowGraphs(const std::vector& paths) +{ + int failed = 0; + + for (const std::string& path : paths) + { + std::optional source = readFile(path); + if (!source) + { + fprintf(stderr, "Error opening %s\n", path.c_str()); + ++failed; + continue; + } + + Luau::Allocator allocator; + Luau::AstNameTable names{allocator}; + Luau::ParseOptions options; + options.allowDeclarationSyntax = true; + Luau::ParseResult parseResult = Luau::Parser::parse(source->data(), source->size(), names, allocator, options); + + if (!parseResult.errors.empty()) + { + for (const Luau::ParseError& error : parseResult.errors) + report(ReportFormat::Default, path.c_str(), error.getLocation(), "SyntaxError", error.getMessage().c_str()); + ++failed; + continue; + } + + Luau::CFG::CFGAllocator cfgAllocator; + auto cfg = Luau::CFG::CFGBuilder::makeCFG(Luau::NotNull{&cfgAllocator}, parseResult.root); + printf("%s", Luau::dumpCFG(*cfg).c_str()); + } + + return failed > 0 ? 1 : 0; +} + static void displayHelp(const char* argv0) { printf("Usage: %s [--mode] [options] [file list]\n", argv0); @@ -413,7 +453,6 @@ int main(int argc, char** argv) int threadCount = 0; std::string basePath = ""; Luau::SolverMode solverMode = Luau::SolverMode::New; - for (int i = 1; i < argc; ++i) { if (argv[i][0] != '-') @@ -494,6 +533,9 @@ int main(int argc, char** argv) std::vector files = getSourceFiles(argc, argv); + if (FFlag::DebugLuauAnalyzeDumpsCFG) + return dumpControlFlowGraphs(files); + for (const std::string& path : files) frontend.queueModuleCheck(path); diff --git a/CLI/src/Flags.cpp b/CLI/src/Flags.cpp index 2ebe94d91..be0ef552f 100644 --- a/CLI/src/Flags.cpp +++ b/CLI/src/Flags.cpp @@ -8,6 +8,8 @@ #include #include +LUAU_FASTFLAGVARIABLE(DebugLuauAnalyzeDumpsCFG) + static void setLuauFlag(std::string_view name, bool state) { for (Luau::FValue* flag = Luau::FValue::list; flag; flag = flag->next) diff --git a/CodeGen/include/Luau/IrUtils.h b/CodeGen/include/Luau/IrUtils.h index 3a486a772..92fda776d 100644 --- a/CodeGen/include/Luau/IrUtils.h +++ b/CodeGen/include/Luau/IrUtils.h @@ -7,6 +7,8 @@ #include +LUAU_FASTFLAG(LuauCodegenUpdateSafeEnvList) + namespace Luau { namespace CodeGen @@ -107,6 +109,8 @@ inline bool canInvalidateSafeEnv(IrCmd cmd) case IrCmd::FALLBACK_NAMECALL: case IrCmd::FALLBACK_FORGPREP: return true; + case IrCmd::INVOKE_FASTPCALL: + return FFlag::LuauCodegenUpdateSafeEnvList; default: break; } diff --git a/CodeGen/src/BytecodeAnalysis.cpp b/CodeGen/src/BytecodeAnalysis.cpp index 33f302037..1065e0369 100644 --- a/CodeGen/src/BytecodeAnalysis.cpp +++ b/CodeGen/src/BytecodeAnalysis.cpp @@ -1514,6 +1514,8 @@ void analyzeBytecodeTypes(IrFunction& function, const HostIrHooks& hostHooks) case LOP_NEWCLASS: case LOP_NEWCLASSMEMBER: case LOP_FASTPCALL: + case LOP_GETPRIVATEFIELD: + case LOP_SETPRIVATEFIELD: break; case LOP_CONSTRUCT: { diff --git a/CodeGen/src/CodeBlockUnwind.cpp b/CodeGen/src/CodeBlockUnwind.cpp index 86882dc11..de69fde1a 100644 --- a/CodeGen/src/CodeBlockUnwind.cpp +++ b/CodeGen/src/CodeBlockUnwind.cpp @@ -8,6 +8,8 @@ #include #include +LUAU_FASTFLAGVARIABLE(LuauCodegenIntelMacUnwind) + #if defined(_WIN32) && defined(CODEGEN_TARGET_X64) #ifndef WIN32_LEAN_AND_MEAN @@ -36,6 +38,7 @@ extern "C" void __register_frame(const void*) REGISTER_FRAME_WEAK; extern "C" void __deregister_frame(const void*) REGISTER_FRAME_WEAK; +// TODO: wrap under defined(__linux__) after removal of FFlag::LuauCodegenIntelMacUnwind extern "C" void __unw_add_dynamic_fde() __attribute__((weak)); #endif @@ -84,12 +87,27 @@ static int findDynamicUnwindSections(uintptr_t addr, unw_dynamic_unwind_sections #if (defined(__linux__) || defined(__APPLE__)) && (defined(CODEGEN_TARGET_X64) || defined(CODEGEN_TARGET_A64)) static void visitFdeEntries(char* pos, void (*cb)(const void*)) { - // When using glibc++ unwinder, we need to call __register_frame/__deregister_frame on the entire .eh_frame data - // When using libc++ unwinder (libunwind), each FDE has to be handled separately - // libc++ unwinder is the macOS unwinder, but on Linux the unwinder depends on the library the executable is linked with - // __unw_add_dynamic_fde is specific to libc++ unwinder, as such we determine the library based on its existence - if (__unw_add_dynamic_fde == nullptr) - return cb(pos); + if (FFlag::LuauCodegenIntelMacUnwind) + { + // When using glibc++ unwinder, we need to call __register_frame/__deregister_frame on the entire .eh_frame data + // When using libc++ unwinder (libunwind), each FDE has to be handled separately + // On Linux the unwinder depends on the library the executable is linked with + // __unw_add_dynamic_fde is specific to libc++ unwinder, as such we determine the library based on its existence + // On macOS, libc++ unwinder is the official one, but older version did not expose __unw_add_dynamic_fde for detection +#if defined(__linux__) + if (__unw_add_dynamic_fde == nullptr) + return cb(pos); +#endif + } + else + { + // When using glibc++ unwinder, we need to call __register_frame/__deregister_frame on the entire .eh_frame data + // When using libc++ unwinder (libunwind), each FDE has to be handled separately + // libc++ unwinder is the macOS unwinder, but on Linux the unwinder depends on the library the executable is linked with + // __unw_add_dynamic_fde is specific to libc++ unwinder, as such we determine the library based on its existence + if (__unw_add_dynamic_fde == nullptr) + return cb(pos); + } for (;;) { diff --git a/CodeGen/src/IrBuilder.cpp b/CodeGen/src/IrBuilder.cpp index 95360b2c4..4422a9485 100644 --- a/CodeGen/src/IrBuilder.cpp +++ b/CodeGen/src/IrBuilder.cpp @@ -672,6 +672,8 @@ void IrBuilder::translateInst(LuauOpcode op, const Instruction* pc, int i) // operation then unconditionally exit to the VM. case LOP_NEWCLASSMEMBER: case LOP_NEWCLASS: + case LOP_GETPRIVATEFIELD: + case LOP_SETPRIVATEFIELD: inst(IrCmd::JUMP, vmExit(i)); break; diff --git a/CodeGen/src/IrLoweringA64.cpp b/CodeGen/src/IrLoweringA64.cpp index afa0f6c42..58d87450b 100644 --- a/CodeGen/src/IrLoweringA64.cpp +++ b/CodeGen/src/IrLoweringA64.cpp @@ -13,7 +13,7 @@ #include "lgc.h" LUAU_FASTFLAGVARIABLE(LuauCodegenA64ForgLoopArray) -LUAU_FASTFLAG(LuauCodegenConstPropMinOffset) +LUAU_FASTFLAGVARIABLE(LuauCodegenA64BitlrotateSelf) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) namespace Luau @@ -2718,8 +2718,7 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) ConditionA64 failCond = ConditionA64::UnsignedLess; // Constant folding can take care of it, but for safety we avoid overflow/underflow cases here - if (offset < 0 || (FFlag::LuauCodegenConstPropMinOffset && offset + minOffset < 0) || - unsigned(offset) + unsigned(endOffset) >= unsigned(INT_MAX)) + if (offset < 0 || offset + minOffset < 0 || unsigned(offset) + unsigned(endOffset) >= unsigned(INT_MAX)) { build.b(target); } @@ -3482,7 +3481,7 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) } case IrCmd::BITLROTATE_INT64: { - inst.regA64 = regs.allocReuse(KindA64::x, index, {OP_B(inst)}); // can't reuse A because it would be clobbered by neg + inst.regA64 = regs.allocReg(KindA64::x, index); // can't reuse A or B because either could be clobbered by neg RegisterA64 source = tempInt64(OP_A(inst)); RegisterA64 amount = tempInt64(OP_B(inst)); // left rotate = rotate by negative @@ -3617,7 +3616,10 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) } else { - inst.regA64 = regs.allocReuse(KindA64::w, index, {OP_B(inst)}); // can't reuse a because it would be clobbered by neg + if (FFlag::LuauCodegenA64BitlrotateSelf) + inst.regA64 = regs.allocReg(KindA64::w, index); // can't reuse A or B because either could be clobbered by neg + else + inst.regA64 = regs.allocReuse(KindA64::w, index, {OP_B(inst)}); // can't reuse a because it would be clobbered by neg RegisterA64 temp1 = tempUint(OP_A(inst)); RegisterA64 temp2 = tempUint(OP_B(inst)); build.neg(inst.regA64, temp2); diff --git a/CodeGen/src/IrLoweringX64.cpp b/CodeGen/src/IrLoweringX64.cpp index 9a97ddd1e..bc7f6ed9e 100644 --- a/CodeGen/src/IrLoweringX64.cpp +++ b/CodeGen/src/IrLoweringX64.cpp @@ -17,7 +17,6 @@ #include "lgc.h" LUAU_FASTFLAG(LuauCodegenExitSyncUpdate) -LUAU_FASTFLAG(LuauCodegenConstPropMinOffset) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) namespace Luau @@ -2551,8 +2550,7 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) int endOffset = maxOffset; // Constant folding can take care of it, but for safety we avoid overflow/underflow cases here - if (offset < 0 || (FFlag::LuauCodegenConstPropMinOffset && offset + minOffset < 0) || - unsigned(offset) + unsigned(endOffset) >= unsigned(INT_MAX)) + if (offset < 0 || offset + minOffset < 0 || unsigned(offset) + unsigned(endOffset) >= unsigned(INT_MAX)) jumpOrAbortOnUndefNoFinalize(ConditionX64::Count, OP_F(inst), index, next, fresh); else build.cmp(dword[regA + offsetof(Buffer, len)], offset + endOffset); @@ -3412,11 +3410,10 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) if (shift < 0) { // Negative left shift = right shift by -amount - uint8_t amount = uint8_t(-shift); - if (amount > 63) + if (shift < -63) build.xor_(inst.regX64, inst.regX64); else - build.shr(inst.regX64, int8_t(amount)); + build.shr(inst.regX64, int8_t(-shift)); } else if (shift > 63) { @@ -3481,11 +3478,10 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) if (shift < 0) { // Negative right shift = left shift by -amount - uint8_t amount = uint8_t(-shift); - if (amount > 63) + if (shift < -63) build.xor_(inst.regX64, inst.regX64); else - build.shl(inst.regX64, int8_t(amount)); + build.shl(inst.regX64, int8_t(-shift)); } else if (shift > 63) { diff --git a/CodeGen/src/IrRegAllocA64.cpp b/CodeGen/src/IrRegAllocA64.cpp index fe6013bae..885e53b46 100644 --- a/CodeGen/src/IrRegAllocA64.cpp +++ b/CodeGen/src/IrRegAllocA64.cpp @@ -15,6 +15,7 @@ LUAU_FASTFLAGVARIABLE(LuauCodegenExitSyncUpdate) LUAU_FASTFLAGVARIABLE(DebugCodegenChaosA64) LUAU_FASTFLAGVARIABLE(LuauCodegenScopedSpillKeepLazy) LUAU_FASTFLAGVARIABLE(DebugCodegenLimitRegs) +LUAU_FASTFLAGVARIABLE(LuauCodegenA64ReloadLargeConstOffset) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) namespace Luau @@ -105,6 +106,21 @@ static AddressA64 getReloadAddress(ValueRestoreLocation location) return AddressA64(xzr); // dummy } +static void emitAddOffset(AssemblyBuilderA64& build, RegisterA64 dst, RegisterA64 src, size_t offset) +{ + CODEGEN_ASSERT(dst != src); + + if (offset <= AssemblyBuilderA64::kMaxImmediate) + { + build.add(dst, src, uint16_t(offset)); + } + else + { + build.mov(dst, int(offset)); + build.add(dst, dst, src); + } +} + IrRegAllocA64::IrRegAllocA64( LogBuilder* logger, AssemblyBuilderA64& build, @@ -603,7 +619,22 @@ void IrRegAllocA64::restore(const IrRegAllocA64::Spill& s, RegisterA64 reg) ValueRestoreLocation restoreLocation = function.findRestoreLocation(inst, /*limitToCurrentBlock*/ false); AddressA64 addr = getReloadAddress(restoreLocation); - CODEGEN_ASSERT(addr.base != xzr); + + CODEGEN_ASSERT(FFlag::LuauCodegenA64ReloadLargeConstOffset || addr.base != xzr); + + RegisterA64 addrTemp = noreg; + + if (FFlag::LuauCodegenA64ReloadLargeConstOffset) + { + if (addr.base == xzr) + { + CODEGEN_ASSERT(restoreLocation.op.kind == IrOpKind::VmConst); + + addrTemp = allocTemp(KindA64::x); + emitAddOffset(build, addrTemp, rConstants, vmConstOp(restoreLocation.op) * sizeof(TValue) + getReloadOffset(restoreLocation.kind)); + addr = addrTemp; + } + } IrValueKind spillValueKind = getCmdValueKind(inst.cmd); @@ -628,6 +659,9 @@ void IrRegAllocA64::restore(const IrRegAllocA64::Spill& s, RegisterA64 reg) build.ldr(reg, addr); } + if (FFlag::LuauCodegenA64ReloadLargeConstOffset && addrTemp != noreg) + freeTemp(addrTemp); + if (logger && logger->options.includeRegSpills) { const char* conv = getConversionCmdSuffix(restoreLocation.conversionCmd); diff --git a/CodeGen/src/IrRegAllocX64.cpp b/CodeGen/src/IrRegAllocX64.cpp index 74acb5218..aee68a71d 100644 --- a/CodeGen/src/IrRegAllocX64.cpp +++ b/CodeGen/src/IrRegAllocX64.cpp @@ -689,6 +689,7 @@ OperandX64 IrRegAllocX64::getRestoreAddress(const IrInst& inst, ValueRestoreLoca case IrValueKind::None: case IrValueKind::Float: case IrValueKind::Count: + break; case IrValueKind::Int64: return restoreLocation.op.kind == IrOpKind::VmReg ? luauRegValueInt64(vmRegOp(op)) : luauConstantValue(vmConstOp(op)); case IrValueKind::Tag: diff --git a/CodeGen/src/IrTranslation.cpp b/CodeGen/src/IrTranslation.cpp index d925f9ba9..5b6a41c84 100644 --- a/CodeGen/src/IrTranslation.cpp +++ b/CodeGen/src/IrTranslation.cpp @@ -14,7 +14,6 @@ LUAU_FASTFLAG(LuauCodegenInteger3) LUAU_FASTFLAGVARIABLE(LuauCodegenIntegerCompare) -LUAU_FASTFLAG(LuauFastpcallInterrupt) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) namespace Luau @@ -1278,8 +1277,7 @@ std::optional translateFastPcall(IrBuilder& build, const Instruction* pc, IrOp fallback = build.fallbackBlock(pcpos); - if (FFlag::LuauFastpcallInterrupt) - build.inst(IrCmd::INTERRUPT, build.constUint(pcpos)); + build.inst(IrCmd::INTERRUPT, build.constUint(pcpos)); // In unsafe environment, instead of retrying fastcall at 'pcpos' we side-exit directly to fallback sequence build.checkSafeEnv(pcpos + getOpLength(opcode)); diff --git a/CodeGen/src/IrUtils.cpp b/CodeGen/src/IrUtils.cpp index d601cbd30..2f9d9bbc3 100644 --- a/CodeGen/src/IrUtils.cpp +++ b/CodeGen/src/IrUtils.cpp @@ -20,6 +20,7 @@ #include LUAU_FASTFLAG(LuauCodegenPropagateFallbackTags) +LUAU_FASTFLAGVARIABLE(LuauCodegenUpdateSafeEnvList) namespace Luau { @@ -63,6 +64,8 @@ int getOpLength(LuauOpcode op) case LOP_CMPPROTO: case LOP_NEWCLASS: case LOP_CONSTRUCT: + case LOP_GETPRIVATEFIELD: + case LOP_SETPRIVATEFIELD: return 2; default: diff --git a/CodeGen/src/OptimizeConstProp.cpp b/CodeGen/src/OptimizeConstProp.cpp index 0b77b869a..da8893fca 100644 --- a/CodeGen/src/OptimizeConstProp.cpp +++ b/CodeGen/src/OptimizeConstProp.cpp @@ -28,9 +28,6 @@ LUAU_FASTFLAGVARIABLE(DebugLuauAbortingChecks) LUAU_FASTFLAGVARIABLE(LuauCodegenPropagateFallbackTags) LUAU_FASTFLAGVARIABLE(LuauCodegenNoZeroScale) LUAU_FLAGVERSION(LuauCodegenPropagateFallbackTags, 2) -LUAU_FASTFLAGVARIABLE(LuauCodegenNoLinearFastpcall) -LUAU_FASTFLAGVARIABLE(LuauCodegenConstPropMinOffset) -LUAU_FASTFLAGVARIABLE(LuauCodegenLimitVersions) LUAU_FASTFLAGVARIABLE(LuauCodegenLimitVersionsExtra) namespace Luau @@ -184,7 +181,7 @@ struct ConstPropState info->tag = tag; info->version++; - if (FFlag::LuauCodegenLimitVersions && info->version == kRegisterVersionLimit) + if (info->version == kRegisterVersionLimit) reachedLimits = true; } } @@ -209,7 +206,7 @@ struct ConstPropState info->value = value; info->version++; - if (FFlag::LuauCodegenLimitVersions && info->version == kRegisterVersionLimit) + if (info->version == kRegisterVersionLimit) reachedLimits = true; } } @@ -229,7 +226,7 @@ struct ConstPropState reg.version++; - if (FFlag::LuauCodegenLimitVersions && reg.version == kRegisterVersionLimit) + if (reg.version == kRegisterVersionLimit) reachedLimits = true; } @@ -2384,8 +2381,7 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& if (bufferOffset) { // Negative offsets and offsets overflowing signed integer will jump to fallback, no need to keep the check - if (*bufferOffset < 0 || (FFlag::LuauCodegenConstPropMinOffset && *bufferOffset + minOffset < 0) || - unsigned(*bufferOffset) + unsigned(accessSize) >= unsigned(INT_MAX)) + if (*bufferOffset < 0 || *bufferOffset + minOffset < 0 || unsigned(*bufferOffset) + unsigned(accessSize) >= unsigned(INT_MAX)) { replace(function, block, index, {IrCmd::JUMP, {OP_F(inst)}}); break; @@ -2977,12 +2973,6 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& { IrInst* src = function.asInstOp(OP_A(inst)); - if (src && src->cmd == IrCmd::INT64_TO_NUM) - { - substitute(function, inst, OP_A(src)); - break; - } - if (src && src->cmd == IrCmd::ADD_NUM) { if (std::optional arg = function.asDoubleOp(OP_B(src)); arg && *arg == 0.0) @@ -3663,7 +3653,7 @@ static bool includeBlockInLinearPath(IrFunction& function, const IrBlock& block) return false; // Same rule applies to fast pcall path as it acts as a call - if (FFlag::LuauCodegenNoLinearFastpcall && inst.cmd == IrCmd::INVOKE_FASTPCALL) + if (inst.cmd == IrCmd::INVOKE_FASTPCALL) return false; } diff --git a/CodeGen/src/OptimizeDeadStore.cpp b/CodeGen/src/OptimizeDeadStore.cpp index d3336c869..2b0a5b759 100644 --- a/CodeGen/src/OptimizeDeadStore.cpp +++ b/CodeGen/src/OptimizeDeadStore.cpp @@ -10,7 +10,7 @@ #include "lobject.h" -// TODO: optimization can be improved by knowing which registers are live in at each VM exit +LUAU_FASTFLAGVARIABLE(LuauCodegenDseTrackTagInvalidation) namespace Luau { @@ -86,6 +86,7 @@ struct StoreRegInfo // Knowing the last stored tag can help safely remove additional unused partial stores uint8_t knownTag = kUnknownTag; + uint32_t tagSourceInstIdx = ~0u; // Load location of the known tag }; struct RemoveDeadStoreState @@ -149,6 +150,7 @@ struct RemoveDeadStoreState function.recordStoreLocationHint(storeInstIdx, {dest, value.index, kind}); } + void killTagStore(StoreRegInfo& regInfo) { if (regInfo.tagInstIdx != ~0u) @@ -236,6 +238,7 @@ struct RemoveDeadStoreState // Opaque register definition removes the knowledge of the actual tag value regInfo.knownTag = kUnknownTag; + regInfo.tagSourceInstIdx = ~0u; // New value defined, before MARK_DEAD is used again, it might be used in a VM exit regInfo.ignoreAtExit = false; @@ -695,6 +698,7 @@ static bool tryReplaceTagWithFullStore( regInfo.tvalueInstIdx = instIndex; regInfo.maybeGco = isGCO(tag); regInfo.knownTag = tag; + regInfo.tagSourceInstIdx = ~0u; state.hasGcoToClear |= regInfo.maybeGco; return true; } @@ -721,6 +725,7 @@ static bool tryReplaceTagWithFullStore( regInfo.tvalueInstIdx = instIndex; regInfo.maybeGco = isGCO(tag); regInfo.knownTag = tag; + regInfo.tagSourceInstIdx = ~0u; state.hasGcoToClear |= regInfo.maybeGco; return true; } @@ -741,6 +746,7 @@ static bool tryReplaceTagWithFullStore( regInfo.tvalueInstIdx = instIndex; regInfo.maybeGco = isGCO(tag); regInfo.knownTag = tag; + regInfo.tagSourceInstIdx = ~0u; state.hasGcoToClear |= regInfo.maybeGco; return true; } @@ -934,6 +940,17 @@ static void markDeadStoresInInst(RemoveDeadStoreState& state, IrBuilder& build, switch (inst.cmd) { + case IrCmd::LOAD_TAG: + visitVmRegDefsUses(state, function, inst); + + if (FFlag::LuauCodegenDseTrackTagInvalidation) + { + // Associate this LOAD_TAG with a source or the register tag + // Duplicate LOAD_TAG instructions would be replaced by previous optimization passes, so generally we have one source active + if (OP_A(inst).kind == IrOpKind::VmReg && !function.cfg.captured.regs.test(vmRegOp(OP_A(inst)))) + state.info[vmRegOp(OP_A(inst))].tagSourceInstIdx = index; + } + break; case IrCmd::STORE_TAG: if (OP_A(inst).kind == IrOpKind::VmReg) { @@ -963,6 +980,7 @@ static void markDeadStoresInInst(RemoveDeadStoreState& state, IrBuilder& build, regInfo.maybeGco = isGCO(tag); regInfo.knownTag = tag; + regInfo.tagSourceInstIdx = ~0u; state.hasGcoToClear |= regInfo.maybeGco; } break; @@ -1092,6 +1110,7 @@ static void markDeadStoresInInst(RemoveDeadStoreState& state, IrBuilder& build, regInfo.tvalueInstIdx = index; regInfo.knownTag = tryGetOperandTag(function, OP_B(inst)).value_or(kUnknownTag); + regInfo.tagSourceInstIdx = ~0u; regInfo.maybeGco = regInfo.knownTag == kUnknownTag || isGCO(regInfo.knownTag); state.hasGcoToClear |= regInfo.maybeGco; @@ -1118,6 +1137,7 @@ static void markDeadStoresInInst(RemoveDeadStoreState& state, IrBuilder& build, regInfo.tvalueInstIdx = index; regInfo.maybeGco = isGCO(function.tagOp(OP_B(inst))); regInfo.knownTag = function.tagOp(OP_B(inst)); + regInfo.tagSourceInstIdx = ~0u; state.hasGcoToClear |= regInfo.maybeGco; } break; @@ -1133,7 +1153,9 @@ static void markDeadStoresInInst(RemoveDeadStoreState& state, IrBuilder& build, StoreRegInfo& regInfo = state.info[reg]; - regInfo.knownTag = function.tagOp(OP_B(inst)); + // Check that the LOAD_TAG instruction is still an active source of the tag in this register + if (!FFlag::LuauCodegenDseTrackTagInvalidation || regInfo.tagSourceInstIdx == function.getInstIndex(*load)) + regInfo.knownTag = function.tagOp(OP_B(inst)); } break; case IrCmd::TRY_NUM_TO_INDEX: diff --git a/Common/include/Luau/Bytecode.h b/Common/include/Luau/Bytecode.h index 1286f06c8..0574fbee4 100644 --- a/Common/include/Luau/Bytecode.h +++ b/Common/include/Luau/Bytecode.h @@ -57,7 +57,7 @@ // Version 14: Adds FASTPCALL. Currently supported. // WIP Versions: Used for in-progress features that might require multiple changes to bytecode. Since these versions are higher than the non-WIP versions, they are responsible for maintaining compatibility with them. For example, tests exercising WIP bytecode versions may need to enable flags for unreleased but non-WIP bytecode versions. -// Version 100: Adds NEWCLASS for use with Luau Classes. Future class-related bytecode changes should go in this version before release. Experimental. +// Version 100: Adds NEWCLASS, CONSTRUCT, FINCONSTRUCT, GETPRIVATEFIELD, and SETPRIVATEFIELD for use with Luau Classes. Future class-related bytecode changes should go in this version before release. Experimental. // # Bytecode type information history // Version 1: (from bytecode version 4) Type information for function signature. Currently supported. @@ -439,10 +439,10 @@ enum LuauOpcode LOP_NAMECALLUDATA, // NEWCLASSMEMBER: register this method on a class object. - // A: target register of class - // B: reserved + // A: source register of class + // B: member visibility, see LuauClassMemberVisibility // C: initial value of this member. currently must be a function. - // AUX: The name of this member as a constant string + // AUX: If method is public, the name of this member as a constant string. If private, the bottom 8 bits contain the private method index, and the upper 24 bits are reserved. LOP_NEWCLASSMEMBER, // CALLFB: call specified function with collecting runtime stats in a feedback slot @@ -488,6 +488,23 @@ enum LuauOpcode // C: jump offset to get to following CALL LOP_FINCONSTRUCT, + // GETPRIVATEFIELD: retrieve the value of a private field from a class instance or its class + // A: target register of field value + // B: source register with class instance or class object + // C: upvalue index with expected class of instance or class object + // AUX: bottom 8 bits contain private field offset. + // bit 9 is 1 if the field is static, else 0; + // bit 10 is 1 if retrieval is for a namecall, else 0; + // remaining 22 bits are reserved + LOP_GETPRIVATEFIELD, + + // SETPRIVATEFIELD: set the value of a private field on a class instance + // A: source register of field value + // B: source register with class instance + // C: upvalue index with expected class of instance + // AUX: bottom 8 bits contain private field offset. remaining 24 bits are reserved + LOP_SETPRIVATEFIELD, + // Enum entry for number of opcodes, not a valid opcode by itself! LOP__COUNT }; @@ -529,6 +546,11 @@ enum LuauOpcode #define LUAU_INSN_AUX_KV16(aux) ((aux) & 0xffffu) #define LUAU_INSN_AUX_SLOT(aux) ((aux) >> 16) +// Auxiliary NAMECALL, STATIC: 1-bit flags indicating if field is static or access is for namecall +// Used in LOP_GETPRIVATEFIELD +#define LUAU_INSN_AUX_STATIC(aux) (((aux) >> 8) & 0x1u) +#define LUAU_INSN_AUX_NAMECALL(aux) (((aux) >> 9) & 0x1u) + #define LUAU_INSN_FBSLOT_SEALED 0xFFFFFFFF // Bytecode tags, used internally for bytecode encoded as a string @@ -537,7 +559,7 @@ enum LuauBytecodeTag // Bytecode version; runtime supports [MIN, MAX], compiler emits TARGET by default but may emit a higher version when flags are enabled LBC_VERSION_MIN = 3, LBC_VERSION_MAX = 14, - LBC_VERSION_TARGET = 9, + LBC_VERSION_TARGET = 13, LBC_VERSION_CLASSES = 100, // Type encoding version LBC_TYPE_VERSION_MIN = 1, @@ -788,6 +810,14 @@ enum LuauCaptureType LCT_UPVAL, }; +// Class member visibility, used in LOP_NEWCLASSMEMBER +// Encoded in the bottom bit of B; the upper 7 bits are reserved and must be 0 +enum LuauClassMemberVisibility +{ + LCMV_PUBLIC = 0, + LCMV_PRIVATE = 1, +}; + // Proto flag bitmask, stored in Proto::flags enum LuauProtoFlag { diff --git a/Common/include/Luau/BytecodeUtils.h b/Common/include/Luau/BytecodeUtils.h index 9c15149b5..0159650c3 100644 --- a/Common/include/Luau/BytecodeUtils.h +++ b/Common/include/Luau/BytecodeUtils.h @@ -43,6 +43,8 @@ inline int getOpLength(LuauOpcode op) case LOP_CMPPROTO: case LOP_NEWCLASS: case LOP_CONSTRUCT: + case LOP_GETPRIVATEFIELD: + case LOP_SETPRIVATEFIELD: return 2; default: diff --git a/Compiler/src/Compiler.cpp b/Compiler/src/Compiler.cpp index 32cfe3441..1a70b7eb4 100644 --- a/Compiler/src/Compiler.cpp +++ b/Compiler/src/Compiler.cpp @@ -2,6 +2,7 @@ #include "Luau/Compiler.h" #include "Luau/Ast.h" +#include "Luau/Bytecode.h" #include "Luau/BytecodeBuilder.h" #include "Luau/Common.h" #include "Luau/Parser.h" @@ -361,7 +362,7 @@ struct Compiler return getFunctionExpr(lv->init); } - else if (AstExprIndexName* expr = node->as()) + else if (AstExprIndexName* expr = node->as(); expr && (FFlag::DebugLuauUserDefinedClasses ? !expr->privateAccess : true)) { if (AstExpr* value = tryIndexConstantTable(expr)) return getFunctionExpr(value); @@ -383,7 +384,7 @@ struct Compiler LUAU_ASSERT(currentFunction); AstExprFunction* locNode = currentFunction; - int8_t tableReg; + uint8_t tableReg; if (!exports.isEmpty()) { @@ -1580,15 +1581,26 @@ struct Compiler setDebugLine(fi->indexLocation); - BytecodeBuilder::StringRef iname = sref(fi->index); - int32_t cid = bytecode.addConstantString(iname); - if (cid < 0) - CompileError::raise(fi->location, "Exceeded constant limit; simplify the code to compile"); + if (FFlag::DebugLuauUserDefinedClasses && fi->privateAccess) + { + // The parser shouldn't even set expr->privateAccess unless it was parsing a class body, so we just assert on currClass here rather + // than erroring if it's not set + LUAU_ASSERT(currClass); - bytecode.emitABC(LOP_NAMECALL, regs, selfreg, uint8_t(BytecodeBuilder::getStringHash(iname))); - bytecode.emitAux(cid); + compilePrivateFieldAccess(fi, regs, selfreg, true); + } + else + { + BytecodeBuilder::StringRef iname = sref(fi->index); + int32_t cid = bytecode.addConstantString(iname); + if (cid < 0) + CompileError::raise(fi->location, "Exceeded constant limit; simplify the code to compile"); + + bytecode.emitABC(LOP_NAMECALL, regs, selfreg, uint8_t(BytecodeBuilder::getStringHash(iname))); + bytecode.emitAux(cid); - hintTemporaryExprRegType(fi->expr, selfreg, LBC_TYPE_TABLE, /* instLength */ 2); + hintTemporaryExprRegType(fi->expr, selfreg, LBC_TYPE_TABLE, /* instLength */ 2); + } } else if (bfid >= 0 || (FFlag::LuauCompileFastpcall && fastPcallId >= 0)) { @@ -1813,11 +1825,9 @@ struct Compiler else // The range of valid registers is 0-254, so we use 0xFF (255) to indicate the absence of a superclass. bytecode.emitABC(LOP_NEWCLASS, dest, kInvalidReg, instrCVal); - // We want to load the class constant up front, but in order to load - // the class constant we need to build it first. To avoid a second - // pass, we start by emitting the LOADKX bytecode and a dummy - // constant (0xDEADBEEF), which we will patch later once we - // have added the class constant to the constant table. + // We want to load the class constant up front, but in order to load the class constant we need to build it first. To avoid a second pass, we + // start by emitting the NEWCLASS bytecode and a dummy constant (0xDEADBEEF), which we will patch later once we have added the class constant + // to the constant table. size_t auxOffset = bytecode.emitLabel(); bytecode.emitAux(0xDEADBEEF); @@ -1839,10 +1849,19 @@ struct Compiler overloaded{ [&](const AstClassProperty& prop) { - // Properties we only need to store the name, for now. - int propNameCid = bytecode.addConstantString(sref(prop.name)); - checkConstant(propNameCid, prop.nameLocation); - shape.propertyNames.emplace_back(propNameCid); + switch (prop.access) + { + case AstClassAccess::Public: + { + int propNameCid = bytecode.addConstantString(sref(prop.name)); + checkConstant(propNameCid, prop.nameLocation); + shape.propertyNames.emplace_back(propNameCid); + } + break; + case AstClassAccess::Private: + shape.numPrivateInstanceProps++; + break; + } }, [&](const AstClassMethod& method) { @@ -1856,14 +1875,29 @@ struct Compiler // a local or a global, we use `NEWCLASSMEMBER` to add it to // our class definition. compileExprFunction(method.function, temp); - int methodNameCid = bytecode.addConstantString(sref(method.functionName)); - checkConstant(methodNameCid, method.function->location); - shape.methodNames.emplace_back(methodNameCid); - bytecode.emitABC(LOP_NEWCLASSMEMBER, dest, 0, temp); - bytecode.emitAux(methodNameCid); + switch (method.access) + { + case AstClassAccess::Public: + { + int methodNameCid = bytecode.addConstantString(sref(method.functionName)); + checkConstant(methodNameCid, method.function->location); + shape.methodNames.emplace_back(methodNameCid); + bytecode.emitABC(LOP_NEWCLASSMEMBER, dest, LuauClassMemberVisibility::LCMV_PUBLIC, temp); + bytecode.emitAux(methodNameCid); + } + break; + case AstClassAccess::Private: + bytecode.emitABC(LOP_NEWCLASSMEMBER, dest, LuauClassMemberVisibility::LCMV_PRIVATE, temp); + bytecode.emitAux(static_cast(shape.numPrivateStaticProps++)); + break; + } if (method.functionName == "__init") + { + // Private constructors are not yet supported + LUAU_ASSERT(method.access == AstClassAccess::Public); hasExplicitConstructor = true; + } } }, member @@ -2978,6 +3012,31 @@ struct Compiler return options.optimizationLevel >= 1 && getGlobalState(globals, expr->name) == Global::Default; } + uint8_t getCurClassUpval() + { + LUAU_ASSERT(currClass); + + return getUpval(currClass->name); + } + + void compilePrivateFieldAccess(AstExprIndexName* expr, uint8_t target, uint8_t source, bool namecall = false) + { + if (!classPrivateFieldOffsets.contains(currClass)) + CompileError::raise(expr->location, "Attempt to access private field of a class with no private fields"); + + DenseHashMap>& offsets = classPrivateFieldOffsets[currClass]; + + if (!offsets.contains(expr->index)) + CompileError::raise(expr->location, "Attempt to access undefined private field"); + + auto [offset, isStatic] = offsets[expr->index]; + + uint8_t classUpval = getCurClassUpval(); + + bytecode.emitABC(LOP_GETPRIVATEFIELD, target, source, classUpval); + bytecode.emitAux((static_cast(namecall) << 9) | (static_cast(isStatic) << 8) | offset); + } + void compileExprIndexName(AstExprIndexName* expr, uint8_t target, bool targetTemp = false) { setDebugLine(expr); // normally compileExpr sets up line info, but compileExprIndexName can be called directly @@ -3001,6 +3060,9 @@ struct Compiler if (importRoot && canImportChain(importRoot)) { + if (FFlag::DebugLuauUserDefinedClasses && (import1->privateAccess || (import2 && import2->privateAccess))) + CompileError::raise(expr->location, "Attempt to access private field of a global"); + int32_t id0 = bytecode.addConstantString(sref(importRoot->name)); int32_t id1 = bytecode.addConstantString(sref(import1->index)); int32_t id2 = import2 ? bytecode.addConstantString(sref(import2->index)) : -1; @@ -3038,6 +3100,15 @@ struct Compiler setDebugLine(expr->indexLocation); + if (FFlag::DebugLuauUserDefinedClasses && expr->privateAccess) + { + // The parser shouldn't even set expr->privateAccess unless it was parsing a class body, so we just assert on currClass here rather than + // erroring if it's not set + LUAU_ASSERT(currClass); + + return compilePrivateFieldAccess(expr, target, reg); + } + BytecodeBuilder::StringRef iname = sref(expr->index); int32_t cid = bytecode.addConstantString(iname); if (cid < 0) @@ -3265,7 +3336,6 @@ struct Compiler { if (FFlag::LuauExportValueSyntax && expr->local->isExported && !exports.exportedClasses.contains(expr->local) && (!FFlag::LuauOptimizeExportTable || !exports.exportedFunctions.contains(expr->local))) - { BytecodeBuilder::StringRef name = sref(expr->local->name); int32_t cid = bytecode.addConstantString(name); @@ -3519,6 +3589,7 @@ struct Compiler Kind_IndexName, Kind_IndexNumber, Kind_IndexExpr, + Kind_PrivateField, }; Kind kind; @@ -3526,7 +3597,10 @@ struct Compiler uint8_t upval; uint8_t index; // register for index in IndexExpr uint8_t number; // index-1 (0-255) in IndexNumber - BytecodeBuilder::StringRef name; + + AstName astName; + BytecodeBuilder::StringRef name = {}; + Location location; }; @@ -3612,9 +3686,12 @@ struct Compiler } else if (AstExprIndexName* expr = node->as()) { - LValue result = {LValue::Kind_IndexName}; + LValue result = {FFlag::DebugLuauUserDefinedClasses && expr->privateAccess ? LValue::Kind_PrivateField : LValue::Kind_IndexName}; result.reg = compileExprAuto(expr->expr, rs); - result.name = sref(expr->index); + if (FFlag::DebugLuauUserDefinedClasses && expr->privateAccess) + result.astName = expr->index; + else + result.name = sref(expr->index); result.location = node->location; return result; @@ -3701,6 +3778,28 @@ struct Compiler } break; + case LValue::Kind_PrivateField: + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses && currClass); + + if (!classPrivateFieldOffsets.contains(currClass)) + CompileError::raise(lv.location, "Attempt to %s private field of a class with no private fields", set ? "assign" : "access"); + + DenseHashMap>& offsets = classPrivateFieldOffsets[currClass]; + + if (!offsets.contains(lv.astName)) + CompileError::raise(lv.location, "Attempt to %s undefined private field", set ? "assign" : "access"); + + auto [offset, isStatic] = offsets[lv.astName]; + + if (isStatic && set) + CompileError::raise(lv.location, "Attempt to assign static field of a class"); + + bytecode.emitABC(set ? LOP_SETPRIVATEFIELD : LOP_GETPRIVATEFIELD, reg, lv.reg, getCurClassUpval()); + bytecode.emitAux(static_cast(offset)); + } + break; + default: LUAU_ASSERT(!"Unknown lvalue kind"); } @@ -4632,7 +4731,8 @@ struct Compiler { const LValue& li = var.lvalue; - if ((li.kind == LValue::Kind_IndexName || li.kind == LValue::Kind_IndexNumber || li.kind == LValue::Kind_IndexExpr) && + if ((li.kind == LValue::Kind_IndexName || li.kind == LValue::Kind_IndexNumber || li.kind == LValue::Kind_IndexExpr || + (FFlag::DebugLuauUserDefinedClasses && li.kind == LValue::Kind_PrivateField)) && visitor.assigned[li.reg]) visitor.conflict[li.reg] = true; @@ -5685,6 +5785,67 @@ struct Compiler } }; + struct ClassVisitor : AstVisitor + { + DenseHashMap& enclosingClasses; + DenseHashMap>>& classPrivateFieldOffsets; + + // TODO: CLI-226024 this needs to become a stack to handle nested classes properly. + AstStatClass* currClass = nullptr; + + ClassVisitor( + DenseHashMap& enclosingClasses, + DenseHashMap>>& classPrivateFieldOffsets + ) + : enclosingClasses(enclosingClasses) + , classPrivateFieldOffsets(classPrivateFieldOffsets) + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + } + + bool visit(AstStatClass* cls) override + { + currClass = cls; + + DenseHashMap> privateOffsets; + uint8_t numPrivateInstanceProps = 0; + uint8_t numPrivateStaticProps = 0; + + for (const auto& member : cls->members) + { + Luau::visit( + overloaded{ + [&](const AstClassProperty& prop) + { + if (prop.access == AstClassAccess::Private) + privateOffsets[prop.name] = {numPrivateInstanceProps++, false}; + }, + [&](const AstClassMethod& method) + { + if (method.access == AstClassAccess::Private) + privateOffsets[method.functionName] = {numPrivateStaticProps++, true}; + + method.function->visit(this); + } + }, + member + ); + } + + if (!privateOffsets.empty()) + classPrivateFieldOffsets[cls] = std::move(privateOffsets); + currClass = nullptr; + + return false; + } + + bool visit(AstExprFunction* func) override + { + enclosingClasses[func] = currClass; + return true; + } + }; + struct RegScope { RegScope(Compiler* self) @@ -5866,6 +6027,13 @@ struct Compiler }; Exports exports; + + // Maps functions to the class they are enclosed in, if any. This is used to determine the context for private field access. + // TODO: CLI-226024 this should map to std::vector instead to support nested classes + DenseHashMap enclosingClasses; + // Maps classes to their private field offsets. Classes are mapped to a mapping from field name to offset/whether the field is static. + DenseHashMap>> classPrivateFieldOffsets; + AstStatClass* currClass = nullptr; }; static void setCompileOptionsForNativeCompilation(CompileOptions& options) @@ -6002,11 +6170,24 @@ void compileOrThrow(BytecodeBuilder& bytecode, const ParseResult& parseResult, A bytecode ); + if (FFlag::DebugLuauUserDefinedClasses) + { + Compiler::ClassVisitor classVisitor(compiler.enclosingClasses, compiler.classPrivateFieldOffsets); + root->visit(&classVisitor); + } + for (AstExprFunction* expr : functions) { uint8_t protoflags = 0; + + if (FFlag::DebugLuauUserDefinedClasses && compiler.enclosingClasses.contains(expr)) + compiler.currClass = compiler.enclosingClasses[expr]; + compiler.compileFunction(expr, protoflags); + if (FFlag::DebugLuauUserDefinedClasses) + compiler.currClass = nullptr; + // If a function has native attribute and the whole module is not native, we set LPF_NATIVE_FUNCTION flag // This ensures that LPF_NATIVE_MODULE and LPF_NATIVE_FUNCTION are exclusive. if ((protoflags & LPF_NATIVE_FUNCTION) && !(mainFlags & LPF_NATIVE_MODULE)) diff --git a/VM/src/lapi.cpp b/VM/src/lapi.cpp index 80b7a39f6..428079a22 100644 --- a/VM/src/lapi.cpp +++ b/VM/src/lapi.cpp @@ -20,9 +20,7 @@ #include LUAU_FASTFLAG(LuauGcTraceUdata) -LUAU_FASTFLAGVARIABLE(LuauNewPointerEncode) LUAU_FASTFLAGVARIABLE(LuauCoroutineFinally) -LUAU_FASTFLAGVARIABLE(LuauFrozenMetaButterfly) /* * This file contains most implementations of core Lua APIs from lua.h. @@ -911,10 +909,7 @@ void lua_setreadonly(lua_State* L, int objindex, int enabled) LuaTable* t = hvalue(o); api_check(L, t != hvalue(registry(L))); - if (FFlag::LuauFrozenMetaButterfly) - luaH_setreadonly(L, t, enabled != 0); - else - t->readonly = bool(enabled); + luaH_setreadonly(L, t, enabled != 0); } int lua_getreadonly(lua_State* L, int objindex) @@ -923,15 +918,7 @@ int lua_getreadonly(lua_State* L, int objindex) api_check(L, ttistable(o)); LuaTable* t = hvalue(o); - if (FFlag::LuauFrozenMetaButterfly) - { - return luaH_getreadonly(t); - } - else - { - int res = t->readonly; - return res; - } + return luaH_getreadonly(t); } void lua_setsafeenv(lua_State* L, int objindex, int enabled) @@ -1842,26 +1829,16 @@ void lua_setpointerencodekey(lua_State* L, uint64_t a, uint64_t b, uint64_t c, u { global_State* g = L->global; - if (FFlag::LuauNewPointerEncode) - { - // Two keys have historically made the encoding an identity - bool identity = (a == 1 && b == 0 && c == 0 && d == 0) || (a == 0 && b == 1 && c == 0 && d == 0); + // Two keys have historically made the encoding an identity + bool identity = (a == 1 && b == 0 && c == 0 && d == 0) || (a == 0 && b == 1 && c == 0 && d == 0); - g->ptrencactive = !identity; + g->ptrencactive = !identity; - // Derive a 512-bit key from the provided seed - for (int i = 0; i < 4; i++) - { - g->ptrenckeynew[2 * i + 0] = siphash24(a, b, i); - g->ptrenckeynew[2 * i + 1] = siphash24(c, d, i); - } - } - else + // Derive a 512-bit key from the provided seed + for (int i = 0; i < 4; i++) { - g->ptrenckey[0] = a & ~1ull; - g->ptrenckey[1] = b | 1ull; - g->ptrenckey[2] = c; - g->ptrenckey[3] = d; + g->ptrenckeynew[2 * i + 0] = siphash24(a, b, i); + g->ptrenckeynew[2 * i + 1] = siphash24(c, d, i); } } @@ -1869,36 +1846,29 @@ uintptr_t lua_encodepointer(lua_State* L, uintptr_t p) { global_State* g = L->global; - if (FFlag::LuauNewPointerEncode) - { - if (!g->ptrencactive) - return p; - - // Feistel cipher transforms the scrambling SipHash into a permutation - // 64-bit platforms split into two 32-bit pieces, 32-bit platforms into two 16-bit pieces - int halfbits = int(sizeof(p) * 4); - uintptr_t mask = (uintptr_t(1) << halfbits) - 1; + if (!g->ptrencactive) + return p; - // Split the block into two pieces - uintptr_t l0 = p & mask; - uintptr_t r0 = p >> halfbits; - - // Perform the minimal required four rounds - for (int i = 0; i < 4; i++) - { - uintptr_t f = siphash24(g->ptrenckeynew[i * 2 + 0], g->ptrenckeynew[i * 2 + 1], uint32_t(r0)) & mask; + // Feistel cipher transforms the scrambling SipHash into a permutation + // 64-bit platforms split into two 32-bit pieces, 32-bit platforms into two 16-bit pieces + int halfbits = int(sizeof(p) * 4); + uintptr_t mask = (uintptr_t(1) << halfbits) - 1; - uintptr_t rnext = l0 ^ f; - l0 = r0; - r0 = rnext; - } + // Split the block into two pieces + uintptr_t l0 = p & mask; + uintptr_t r0 = p >> halfbits; - return (r0 << halfbits) | l0; - } - else + // Perform the minimal required four rounds + for (int i = 0; i < 4; i++) { - return uintptr_t((g->ptrenckey[0] * p + g->ptrenckey[2]) ^ (g->ptrenckey[1] * p + g->ptrenckey[3])); + uintptr_t f = siphash24(g->ptrenckeynew[i * 2 + 0], g->ptrenckeynew[i * 2 + 1], uint32_t(r0)) & mask; + + uintptr_t rnext = l0 ^ f; + l0 = r0; + r0 = rnext; } + + return (r0 << halfbits) | l0; } int lua_ref(lua_State* L, int idx) diff --git a/VM/src/lbaselib.cpp b/VM/src/lbaselib.cpp index 58134249f..548cd2158 100644 --- a/VM/src/lbaselib.cpp +++ b/VM/src/lbaselib.cpp @@ -13,7 +13,6 @@ #include LUAU_FASTFLAGVARIABLE(LuauFastpcall) -LUAU_FASTFLAGVARIABLE(LuauPcallOptimize) static void writestring(const char* s, size_t l) { @@ -291,53 +290,33 @@ static int luaB_pcally(lua_State* L) static int luaB_pcallcont(lua_State* L, int status) { - if (FFlag::LuauPcallOptimize) - { - luaD_checkstack(L, 1); - - if (status == 0) - { - StkId base = L->base; - StkId top = L->top; + luaD_checkstack(L, 1); - // Move results 1 right to make space for the 'true' status - for (StkId q = top; q > base; q--) - setobj2s(L, q, q - 1); - - setbvalue(base, 1); - L->top = top + 1; - - return cast_int(L->top - base); - } - else - { - StkId top = L->top; + if (status == 0) + { + StkId base = L->base; + StkId top = L->top; - // Move error 1 right to make space for the 'false' status - setobj2s(L, top, top - 1); + // Move results 1 right to make space for the 'true' status + for (StkId q = top; q > base; q--) + setobj2s(L, q, q - 1); - setbvalue(top - 1, 0); - L->top = top + 1; + setbvalue(base, 1); + L->top = top + 1; - return 2; - } + return cast_int(L->top - base); } else { - if (status == 0) - { - lua_rawcheckstack(L, 1); - lua_pushboolean(L, true); - lua_insert(L, 1); // insert status before all results - return lua_gettop(L); - } - else - { - lua_rawcheckstack(L, 1); - lua_pushboolean(L, false); - lua_insert(L, -2); // insert status before error object - return 2; - } + StkId top = L->top; + + // Move error 1 right to make space for the 'false' status + setobj2s(L, top, top - 1); + + setbvalue(top - 1, 0); + L->top = top + 1; + + return 2; } } @@ -359,46 +338,26 @@ static int luaB_xpcallcont(lua_State* L, int status) { if (status == 0) { - if (FFlag::LuauPcallOptimize) - { - StkId base = L->base; + StkId base = L->base; - // xpcall had an 'errfunc' before the results, so we just replace it with 'true' status - setbvalue(base, 1); + // xpcall had an 'errfunc' before the results, so we just replace it with 'true' status + setbvalue(base, 1); - return cast_int(L->top - base); - } - else - { - lua_rawcheckstack(L, 1); - lua_pushboolean(L, true); - lua_replace(L, 1); // replace error function with status - return lua_gettop(L); // return status + all results - } + return cast_int(L->top - base); } else { - if (FFlag::LuauPcallOptimize) - { - luaD_checkstack(L, 1); + luaD_checkstack(L, 1); - StkId top = L->top; + StkId top = L->top; - // Move error 1 right to make space for the 'false' status - setobj2s(L, top, top - 1); + // Move error 1 right to make space for the 'false' status + setobj2s(L, top, top - 1); - setbvalue(top - 1, 0); - L->top = top + 1; + setbvalue(top - 1, 0); + L->top = top + 1; - return 2; - } - else - { - lua_rawcheckstack(L, 1); - lua_pushboolean(L, false); - lua_insert(L, -2); // place status before the error that was on top of the stack - return 2; - } + return 2; } } diff --git a/VM/src/lclass.cpp b/VM/src/lclass.cpp index 7c8cc0257..441a1a28c 100644 --- a/VM/src/lclass.cpp +++ b/VM/src/lclass.cpp @@ -28,12 +28,16 @@ LuauClass* luaR_newblankclass(lua_State* L, TString* name, bool isopen) classobject->super = NULL; classobject->staticmembers = NULL; + classobject->privatestaticmembers = NULL; classobject->memberstooffset = NULL; classobject->offsettomember = NULL; classobject->metatable = NULL; classobject->instancemetatable = NULL; - classobject->numberofinstancemembers = 0; - classobject->numberofallmembers = 0; + classobject->numberofinstancemembers = 0u; + classobject->numberofmembers = 0u; + classobject->numberofprivatefields = 0u; + classobject->ownprivatefieldsstart = 0u; + classobject->numberofprivatestaticmembers = 0u; classobject->isopen = isopen; classobject->hasuserinitinchain = false; @@ -78,7 +82,7 @@ static void luaR_setupconstructor(lua_State* L, LuauClass* classobject, LuaTable TString* initKey = luaS_new(L, "__init"); const TValue* initIndex = luaH_getstr(classobject->memberstooffset, initKey); const double initDouble = nvalue(initIndex); - LUAU_ASSERT(initDouble >= classobject->numberofinstancemembers && initDouble < classobject->numberofallmembers); + LUAU_ASSERT(initDouble >= classobject->numberofinstancemembers && initDouble < classobject->numberofmembers); const uint32_t initOffset = uint32_t(initDouble) - classobject->numberofinstancemembers; setclvalue(L, &classobject->staticmembers[initOffset], defaultCtor); @@ -91,6 +95,8 @@ LuauClass* luaR_newclass( TString** offsettomember, uint32_t numberofinstancemembers, uint32_t numberofstaticmembers, + uint8_t numberofprivatefields, + uint8_t numberofprivatemethods, LuaTable* envt ) { @@ -106,7 +112,15 @@ LuauClass* luaR_newclass( classobject->offsettomember = offsettomember; classobject->numberofinstancemembers = numberofinstancemembers; - classobject->numberofallmembers = numberofinstancemembers + numberofstaticmembers; + classobject->numberofmembers = numberofinstancemembers + numberofstaticmembers; + + classobject->numberofprivatefields = static_cast(numberofprivatefields); + LUAU_ASSERT(numberofprivatefields <= numberofinstancemembers); + classobject->ownprivatefieldsstart = numberofinstancemembers - static_cast(numberofprivatefields); + + LUAU_ASSERT(numberofprivatemethods <= numberofstaticmembers); + classobject->numberofprivatestaticmembers = numberofprivatemethods; + classobject->privatestaticmembers = classobject->staticmembers + (numberofstaticmembers - static_cast(numberofprivatemethods)); luaR_setupconstructor(L, classobject, envt); @@ -124,6 +138,7 @@ void luaR_registerstaticmember( ) { LUAU_ASSERT(iswhite(obj2gco(classObject))); + LUAU_ASSERT(memberName != NULL); setobj2class(L, &classObject->staticmembers[staticMemberOffset], val); @@ -143,7 +158,8 @@ This is done in the following steps: - Count how many static members we'll need to copy from parent, so we know how much space to allocate for the new class. - Copy the parent's instance members. - Copy the child's instance members. -- Copy the parent's non-overridden static members. +- Set numberofprivatefields and ownprivatefieldsstart +- Copy the parent's non-overridden public static members. - Copy the child's static members. - Add the class metatable to the new class. - Copy the parent's instance metatable if it exists. The child doesn't have an instance metatable yet because it gets created by future NEWCLASSMEMBER @@ -163,17 +179,20 @@ LuauClass* luaR_inheritclass(lua_State* L, const LuauClass* child, LuauClass* pa for (uint32_t idx = 0; idx < parent->numberofinstancemembers; idx++) { TString* memberName = parent->offsettomember[idx]; + if (!memberName) + continue; + const TValue* existing = luaH_getstr(child->memberstooffset, memberName); - if (!ttisnil(existing)) - { - luaG_runerror( - L, - "Cannot override instance member '%s' of parent class '%s' in child class '%s'", - getstr(memberName), - getstr(parent->name), - getstr(child->name) - ); - } + if (ttisnil(existing)) + continue; + + luaG_runerror( + L, + "Cannot override instance member '%s' of parent class '%s' in child class '%s'", + getstr(memberName), + getstr(parent->name), + getstr(child->name) + ); } } @@ -184,22 +203,27 @@ LuauClass* luaR_inheritclass(lua_State* L, const LuauClass* child, LuauClass* pa // Count how many static members we'll actually need to copy from parent, ie non-overridden ones uint32_t numStaticMembersToCopy = 0; - // We start at numberofinstancemembers so we only look at static members - for (uint32_t idx = parent->numberofinstancemembers; idx < parent->numberofallmembers; idx++) + // We start at numberofinstancemembers so we only look at static members, and stop before private static members + const uint32_t parentPublicStaticsEnd = luaR_offsettomemberlength(parent); + for (uint32_t idx = parent->numberofinstancemembers; idx < parentPublicStaticsEnd; idx++) { TString* memberName = parent->offsettomember[idx]; + LUAU_ASSERT(memberName); const TValue* existing = luaH_getstr(child->memberstooffset, memberName); if (ttisnil(existing)) numStaticMembersToCopy++; // TODO: Throw an error if we overwrite a static member with an instance member? } - uint32_t numMembers = child->numberofallmembers + parent->numberofinstancemembers + numStaticMembersToCopy; + uint32_t numMembers = child->numberofmembers + parent->numberofinstancemembers + numStaticMembersToCopy; - newClass->offsettomember = luaM_newarray(L, numMembers, TString*, newClass->memcat); - newClass->numberofallmembers = numMembers; + // Private methods don't need offsettomember entries + newClass->offsettomember = luaM_newarray(L, numMembers - child->numberofprivatestaticmembers, TString*, newClass->memcat); + newClass->numberofmembers = numMembers; - newClass->memberstooffset = luaH_new(L, 0, numMembers); + // Private fields don't need memberstooffset entries + newClass->memberstooffset = + luaH_new(L, 0, numMembers - child->numberofprivatefields - parent->numberofprivatefields - child->numberofprivatestaticmembers); newClass->hasuserinitinchain = parent->hasuserinitinchain; @@ -213,8 +237,12 @@ LuauClass* luaR_inheritclass(lua_State* L, const LuauClass* child, LuauClass* pa newClass->offsettomember[offset] = memberName; - TValue* val = luaH_setstr(L, newClass->memberstooffset, memberName); - setnvalue(val, offset); + // Only public fields have names at runtime + if (memberName) + { + TValue* val = luaH_setstr(L, newClass->memberstooffset, memberName); + setnvalue(val, offset); + } } } @@ -226,20 +254,33 @@ LuauClass* luaR_inheritclass(lua_State* L, const LuauClass* child, LuauClass* pa newClass->offsettomember[offset] = memberName; - TValue* val = luaH_setstr(L, newClass->memberstooffset, memberName); - setnvalue(val, offset); + // Only public fields have names at runtime + if (memberName) + { + TValue* val = luaH_setstr(L, newClass->memberstooffset, memberName); + setnvalue(val, offset); + } } } + newClass->numberofprivatefields = child->numberofprivatefields + parent->numberofprivatefields; + newClass->ownprivatefieldsstart = child->ownprivatefieldsstart + parent->numberofinstancemembers; + // We've just copied all instance members, so offset is the total number of instance members in the final class newClass->staticmembers = luaM_newarray(L, numMembers - offset, TValue, newClass->memcat); + // Number of public methods in child + methods to copy from parent + uint32_t privateMethodOffset = + child->numberofmembers - child->numberofinstancemembers - static_cast(child->numberofprivatestaticmembers) + numStaticMembersToCopy; + newClass->privatestaticmembers = newClass->staticmembers + privateMethodOffset; + newClass->numberofprivatestaticmembers = child->numberofprivatestaticmembers; newClass->numberofinstancemembers = offset; // Copy static members from parent that aren't overridden in child. uint32_t numStaticMembersCopied = 0; - for (uint32_t idx = parent->numberofinstancemembers; idx < parent->numberofallmembers; idx++) + for (uint32_t idx = parent->numberofinstancemembers; idx < parentPublicStaticsEnd; idx++) { TString* memberName = parent->offsettomember[idx]; + LUAU_ASSERT(memberName); // This lookup duplicates the one we did earlier, when we counted how many static members we needed to copy. We could optimize by caching the // indices with static members to copy. const TValue* existing = luaH_getstr(child->memberstooffset, memberName); @@ -255,20 +296,25 @@ LuauClass* luaR_inheritclass(lua_State* L, const LuauClass* child, LuauClass* pa } } - // Copy child's static members over to newClass - for (uint32_t idx = child->numberofinstancemembers; idx < child->numberofallmembers; idx++) + // Copy child's public static members + const uint32_t childPublicStaticsEnd = luaR_offsettomemberlength(child); + for (uint32_t idx = child->numberofinstancemembers; idx < childPublicStaticsEnd; idx++) { TString* memberName = child->offsettomember[idx]; - const TValue* childVal = &child->staticmembers[idx - child->numberofinstancemembers]; - luaR_registerstaticmember(L, newClass, memberName, childVal, offset, numStaticMembersCopied); - offset++; numStaticMembersCopied++; } - LUAU_ASSERT(numStaticMembersCopied == numStaticMembersToCopy + (child->numberofallmembers - child->numberofinstancemembers)); + // Private methods have no offsettomember/memberstooffset entries + for (uint32_t i = 0; i < child->numberofprivatestaticmembers; i++) + { + setobj2class(L, &newClass->privatestaticmembers[i], &child->privatestaticmembers[i]); + numStaticMembersCopied++; + } + + LUAU_ASSERT(numStaticMembersCopied == numStaticMembersToCopy + (child->numberofmembers - child->numberofinstancemembers)); // Copy instance metatable // Ignoring the child's instance metatable is sound because it is only ever created during NEWCLASSMEMBER instructions, which are only @@ -281,12 +327,12 @@ LuauClass* luaR_inheritclass(lua_State* L, const LuauClass* child, LuauClass* pa return newClass; } -void luaR_addclassmember(lua_State* L, LuauClass* classobject, TString* name, TValue* value) +void luaR_addpublicstaticmember(lua_State* L, LuauClass* classobject, TString* name, TValue* value) { LUAU_ASSERT(classobject->staticmembers != nullptr); const TValue* offset = luaH_getstr(classobject->memberstooffset, name); const uint32_t offsetint = uint32_t(nvalue(offset)); - LUAU_ASSERT(offsetint >= classobject->numberofinstancemembers && offsetint < classobject->numberofallmembers); + LUAU_ASSERT(offsetint >= classobject->numberofinstancemembers && offsetint < classobject->numberofmembers); LUAU_ASSERT(ttisfunction(value) && value->value.gc->gch.tt == LUA_TFUNCTION); setobj2class(L, &classobject->staticmembers[offsetint - classobject->numberofinstancemembers], value); luaC_barrier(L, classobject, value); @@ -338,6 +384,14 @@ LuauObject* luaR_newblankobject(lua_State* L, LuauClass* classobject) return object; } +void luaR_addprivatestaticmember(lua_State* L, LuauClass* classobject, uint8_t pindex, TValue* value) +{ + LUAU_ASSERT(classobject->staticmembers != nullptr); + TValue* slot = luaR_privatestaticmember(classobject, pindex); + setobj2class(L, slot, value); + luaC_barrier(L, classobject, value); +} + int luaR_constructobject(lua_State* L) { // This runs as the class's `__call` metamethod, so luaV_tryfuncTM has inserted the class being called ahead of the call arguments. @@ -345,7 +399,7 @@ int luaR_constructobject(lua_State* L) LuauObject* self = luaR_newblankobject(L, classobject); - for (uint32_t idx = 0; idx < classobject->numberofinstancemembers; idx++) + for (uint32_t idx = 0; idx < self->numberofmembers; idx++) setnilvalue(&self->members[idx]); TString* initKey = luaS_new(L, "__init"); @@ -389,6 +443,13 @@ int luaR_defaultcreateobject(lua_State* L) if (classobject->hasuserinitinchain) luaL_error(L, "Class %s must define a constructor because it is derived from a class that defines one", getstr(classobject->name)); + else if (classobject->numberofprivatefields != 0) + { + if (classobject->super) + luaL_error(L, "Class %s must define a constructor because it or a class it inherits from has private fields", getstr(classobject->name)); + else + luaL_error(L, "Class %s must define a constructor because it has private fields", getstr(classobject->name)); + } int numargs = lua_gettop(L); if (numargs != 2) @@ -415,6 +476,9 @@ int luaR_defaultcreateobject(lua_State* L) // Use the second argument to initialize all class members. for (uint32_t idx = 0; idx < classobject->numberofinstancemembers; idx++) { + if (classobject->offsettomember[idx] == NULL) + continue; + TValue key; setsvalue(L, &key, classobject->offsettomember[idx]); luaV_gettable(L, L->base + propSlot, &key, L->top - 1); @@ -430,7 +494,7 @@ int luaR_defaultcreateobject(lua_State* L) static LuauClassConstructMatch luaR_classmatchesshape(LuauClass* klass, LuaTable* shape) { // custom constructor means we cannot directly construct from a shape - if (klass->hasuserinitinchain) + if (klass->hasuserinitinchain || klass->numberofprivatefields > 0) return LCM_MISMATCH; uint32_t membercount = 0; @@ -527,23 +591,48 @@ void luaR_tryconstructobject(lua_State* L, StkId target, StkId maybeclass, uint3 sethvalue(L, target, luaH_clone(L, shapeTable)); } +bool luaR_isinstance(const LuauObject* inst, const LuauClass* cls) +{ + for (LuauClass* objClass = inst->lclass; objClass != NULL; objClass = objClass->super) + { + if (objClass == cls) + return true; + } + + return false; +} + +bool luaR_issubclass(const LuauClass* child, const LuauClass* ancestor) +{ + for (const LuauClass* objClass = child; objClass != NULL; objClass = objClass->super) + { + if (objClass == ancestor) + return true; + } + + return false; +} + + void luaR_freeclass(lua_State* L, LuauClass* classobject, lua_Page* page) { if (classobject->staticmembers) { luaM_freearray( - L, classobject->staticmembers, classobject->numberofallmembers - classobject->numberofinstancemembers, TValue, classobject->memcat + L, classobject->staticmembers, classobject->numberofmembers - classobject->numberofinstancemembers, TValue, classobject->memcat ); } if (classobject->offsettomember) - luaM_freearray(L, classobject->offsettomember, classobject->numberofallmembers, TString*, classobject->memcat); + luaM_freearray(L, classobject->offsettomember, luaR_offsettomemberlength(classobject), TString*, classobject->memcat); luaM_freegco(L, classobject, sizeof(LuauClass), classobject->memcat, page); } void luaR_freeobject(lua_State* L, LuauObject* classinstance, lua_Page* page) { - luaM_freearray(L, classinstance->members, classinstance->numberofmembers, TValue, classinstance->memcat); + if (classinstance->members) + luaM_freearray(L, classinstance->members, classinstance->numberofmembers, TValue, classinstance->memcat); + luaM_freegco(L, classinstance, sizeof(LuauObject), classinstance->memcat, page); } diff --git a/VM/src/lclass.h b/VM/src/lclass.h index b96cc986c..1736b0468 100644 --- a/VM/src/lclass.h +++ b/VM/src/lclass.h @@ -21,6 +21,8 @@ LUAI_FUNC LuauClass* luaR_newclass( TString** offsettomember, uint32_t numberofinstancemembers, uint32_t numberofstaticmembers, + uint8_t numberofprivatefields, + uint8_t numberofprivatemethods, LuaTable* envt ); @@ -30,9 +32,14 @@ LUAI_FUNC LuauClass* luaR_newclass( LUAI_FUNC LuauClass* luaR_inheritclass(lua_State* L, const LuauClass* child, LuauClass* parent); /** - * Add a new class member to `classobject` named `name` and with value `value`. + * Add a new public static class member to `classobject` named `name` and with value `value`. */ -LUAI_FUNC void luaR_addclassmember(lua_State* L, LuauClass* classobject, TString* name, TValue* value); +LUAI_FUNC void luaR_addpublicstaticmember(lua_State* L, LuauClass* classobject, TString* name, TValue* value); + +/** + * Add a new private static class member to `classobject` at the specified private index and with value `value`. + */ +LUAI_FUNC void luaR_addprivatestaticmember(lua_State* L, LuauClass* classobject, uint8_t pindex, TValue* value); LUAI_FUNC void luaR_freeclass(lua_State* L, LuauClass* classobject, lua_Page* page); @@ -58,9 +65,22 @@ LUAI_FUNC void luaR_tryconstructobject(lua_State* L, StkId target, StkId maybecl LUAI_FUNC void luaR_freeobject(lua_State* L, LuauObject* classinstance, lua_Page* page); -#define luaR_checkoffsetinbounds(inst, offset) (offset < (inst)->lclass->numberofallmembers) +LUAI_FUNC bool luaR_isinstance(const LuauObject* inst, const LuauClass* cls); + +LUAI_FUNC bool luaR_issubclass(const LuauClass* child, const LuauClass* ancestor); + +#define luaR_offsettomemberlength(cls) ((cls)->numberofmembers - static_cast((cls)->numberofprivatestaticmembers)) + +#define luaR_checkpublicmemberoffset(inst, offset) \ + (offset < luaR_offsettomemberlength((inst)->lclass) && (inst)->lclass->offsettomember[offset] != NULL) + +// Number of static members, including this class's private ones. +#define luaR_numstaticmembers(cls) ((cls)->numberofmembers - (cls)->numberofinstancemembers) + +// Private static members are addressed by index and live in the last luaR_numprivatestaticmembers slots of staticmembers. +#define luaR_privatestaticmember(cls, pindex) (LUAU_ASSERT((pindex) < (cls)->numberofprivatestaticmembers), &(cls)->privatestaticmembers[pindex]) #define luaR_lookupmemberatoffset(inst, offset) \ - (LUAU_ASSERT(luaR_checkoffsetinbounds(inst, offset)), \ + (LUAU_ASSERT(luaR_checkpublicmemberoffset(inst, offset)), \ offset < (inst)->lclass->numberofinstancemembers ? &(inst)->members[offset] \ : &(inst)->lclass->staticmembers[offset - inst->lclass->numberofinstancemembers]) diff --git a/VM/src/lclasslib.cpp b/VM/src/lclasslib.cpp index 76ae3cab2..9b7d21868 100644 --- a/VM/src/lclasslib.cpp +++ b/VM/src/lclasslib.cpp @@ -1,4 +1,5 @@ #include "lapi.h" +#include "lclass.h" #include "lobject.h" #include "lua.h" #include "lualib.h" @@ -24,16 +25,8 @@ static int class_isinstance(lua_State* L) const LuauClass* lclass = classvalue(cls); - for (LuauClass* objClass = objectvalue(obj)->lclass; objClass != NULL; objClass = objClass->super) - { - if (objClass == lclass) - { - lua_pushboolean(L, true); - return 1; - } - } + lua_pushboolean(L, luaR_isinstance(objectvalue(obj), lclass)); - lua_pushboolean(L, false); return 1; } diff --git a/VM/src/ldo.cpp b/VM/src/ldo.cpp index 7b7035fcc..6262d7aed 100644 --- a/VM/src/ldo.cpp +++ b/VM/src/ldo.cpp @@ -20,6 +20,7 @@ LUAU_FASTFLAG(LuauFastpcall) LUAU_FASTFLAGVARIABLE(LuauPcallErrorContinuationReentry) +LUAU_FASTFLAGVARIABLE(LuauIsYieldableSimplify) // keep max stack allocation request under 1GB #define MAX_STACK_SIZE (int(1024 / sizeof(TValue)) * 1024 * 1024) @@ -878,7 +879,11 @@ int lua_break(lua_State* L) int lua_isyieldable(lua_State* L) { - return (L->nCcalls <= L->baseCcalls); + if (!FFlag::LuauIsYieldableSimplify) + return L->nCcalls <= L->baseCcalls; + + LUAU_ASSERT(L->nCcalls >= L->baseCcalls); + return L->nCcalls == L->baseCcalls; } int luaD_pcall(lua_State* L, Pfunc func, void* u, ptrdiff_t old_top, ptrdiff_t ef) @@ -916,7 +921,7 @@ int luaD_pcall(lua_State* L, Pfunc func, void* u, ptrdiff_t old_top, ptrdiff_t e if (!oldactive) L->isactive = false; - bool yieldable = L->nCcalls <= L->baseCcalls; // Inlined logic from 'lua_isyieldable' to avoid potential for an out of line call. + bool yieldable = FFlag::LuauIsYieldableSimplify ? lua_isyieldable(L) : (L->nCcalls <= L->baseCcalls); // restore nCcalls and baseCcalls before calling the debugprotectederror callback which may rely on the proper value to have been restored. L->nCcalls = oldnCcalls; diff --git a/VM/src/lgc.cpp b/VM/src/lgc.cpp index a5215bba9..5425a42a7 100644 --- a/VM/src/lgc.cpp +++ b/VM/src/lgc.cpp @@ -22,7 +22,6 @@ LUAU_FASTFLAGVARIABLE(LuauGcTraceUdata) LUAU_FLAGVERSION(LuauGcTraceUdata, 4) LUAU_FASTFLAG(LuauFastpcall) LUAU_FASTFLAG(LuauCoroutineFinally) -LUAU_FASTFLAG(LuauFrozenMetaButterfly) LUAU_DYNAMIC_FASTFLAGVARIABLE(LuauGcHeapShrinkFix, false) /* @@ -471,9 +470,13 @@ static void traverseclass(global_State* g, LuauClass* classobject) if (classobject->super) markobject(g, classobject->super); markobject(g, classobject->memberstooffset); - for (uint32_t i = 0; i < classobject->numberofallmembers; i++) - markobject(g, classobject->offsettomember[i]); - for (uint32_t i = 0; i < classobject->numberofallmembers - classobject->numberofinstancemembers; i++) + for (uint32_t i = 0; i < luaR_offsettomemberlength(classobject); i++) + { + if (TString* str = classobject->offsettomember[i]) + markobject(g, str); + } + // Includes this class's private static members, which live at the tail of staticmembers. + for (uint32_t i = 0; i < luaR_numstaticmembers(classobject); i++) markvalue(g, &classobject->staticmembers[i]); if (classobject->metatable) markobject(g, classobject->metatable); @@ -609,19 +612,17 @@ static size_t propagatemark(global_State* g) // We've traversed the "object" itself ... return sizeof(LuauClass) + // ... plus the method closures, each a `TValue` wide ... - ((classobject->numberofallmembers - classobject->numberofinstancemembers) * sizeof(TValue)) + - // ... plus a string pointer for each method or property, each a pointer wide. - (classobject->numberofallmembers * sizeof(TString*)); + (luaR_numstaticmembers(classobject) * sizeof(TValue)) + + // ... plus a string pointer for each method or property except for private static members, each a pointer wide. + (luaR_offsettomemberlength(classobject) * sizeof(TString*)); } case LUA_TOBJECT: { LuauObject* classinst = gco2object(o); g->gray = classinst->gclist; traverseobject(g, classinst); - // We've traversed the instance ... - return sizeof(LuauObject) + - // ... plus all of the instance fields. - classinst->numberofmembers * sizeof(TValue); + // We've traversed the instance and its instance fields + return sizeof(LuauObject) + classinst->numberofmembers * sizeof(TValue); } default: LUAU_ASSERT(0); @@ -746,10 +747,10 @@ static size_t cleartable(lua_State* L, GCObject* l) } } - if (FFlag::LuauFrozenMetaButterfly && hasmetacache(h)) + if (hasmetacache(h)) rebuildmetacache(L, h); - if (!FFlag::LuauFrozenMetaButterfly || !h->readonly) // frozen tables do not shrink + if (!h->readonly) // frozen tables do not shrink { if (const char* modev = gettablemode(L->global, h)) { diff --git a/VM/src/lgcdebug.cpp b/VM/src/lgcdebug.cpp index e898b73cd..da235123a 100644 --- a/VM/src/lgcdebug.cpp +++ b/VM/src/lgcdebug.cpp @@ -2,6 +2,7 @@ // This code is based on Lua 5.x implementation licensed under MIT License; see lua_LICENSE.txt for details #include "lgc.h" +#include "lclass.h" #include "lfunc.h" #include "lmem.h" #include "lobject.h" @@ -14,8 +15,6 @@ #include #include -LUAU_FASTFLAG(LuauFrozenMetaButterfly) - static void validateobjref(global_State* g, GCObject* f, GCObject* t) { LUAU_ASSERT(!isdead(g, t)); @@ -144,18 +143,26 @@ static void validateproto(global_State* g, Proto* f) static void validateclass(global_State* g, LuauClass* lco) { GCObject* obj = obj2gco(lco); + validateobjref(g, obj, obj2gco(lco->name)); + if (lco->super) validateobjref(g, obj, obj2gco(lco->super)); + validateobjref(g, obj, obj2gco(lco->memberstooffset)); - for (uint32_t i = 0; i < lco->numberofallmembers; i++) + + for (uint32_t i = 0; i < luaR_offsettomemberlength(lco); i++) { - validateobjref(g, obj, obj2gco(lco->offsettomember[i])); - if (i >= lco->numberofinstancemembers) - validateref(g, obj, &lco->staticmembers[i - lco->numberofinstancemembers]); + if (TString* str = lco->offsettomember[i]) + validateobjref(g, obj, obj2gco(str)); } + + for (uint32_t i = lco->numberofinstancemembers; i < lco->numberofmembers; i++) + validateref(g, obj, &lco->staticmembers[i - lco->numberofinstancemembers]); + if (lco->metatable) validateobjref(g, obj, obj2gco(lco->metatable)); + if (lco->instancemetatable) validateobjref(g, obj, obj2gco(lco->instancemetatable)); } @@ -361,7 +368,7 @@ static void dumptable(FILE* f, LuaTable* h) { size_t size = sizeof(LuaTable) + (h->node == &luaH_dummynode ? 0 : sizenode(h) * sizeof(LuaNode)) + h->sizearray * sizeof(TValue); - if (FFlag::LuauFrozenMetaButterfly && hasmetacache(h)) + if (hasmetacache(h)) size += TM_N * sizeof(TValue); fprintf(f, "{\"type\":\"table\",\"cat\":%d,\"size\":%d", h->memcat, int(size)); @@ -617,14 +624,20 @@ static void dumpclass(FILE* f, LuauClass* lco) else fprintf(f, "null"); fprintf(f, R"(,"membernames":[)"); - for (uint32_t i = 0; i < lco->numberofallmembers; i++) + bool memberNameDumped = false; + for (uint32_t i = 0; i < luaR_offsettomemberlength(lco); i++) { - if (i != 0) + // Private fields have NULL entries in offsettomember + if (lco->offsettomember[i] == NULL) + continue; + + if (memberNameDumped) fputc(',', f); dumpref(f, (GCObject*)lco->offsettomember[i]); + memberNameDumped = true; } fprintf(f, R"(],"staticmembers":[)"); - dumprefs(f, lco->staticmembers, lco->numberofallmembers - lco->numberofinstancemembers); + dumprefs(f, lco->staticmembers, luaR_numstaticmembers(lco)); fprintf(f, R"(],"metatable":)"); if (lco->metatable) dumpref(f, obj2gco(lco->metatable)); @@ -785,7 +798,7 @@ static void enumtable(EnumContext* ctx, LuaTable* h) { size_t size = sizeof(LuaTable) + (h->node == &luaH_dummynode ? 0 : sizenode(h) * sizeof(LuaNode)) + h->sizearray * sizeof(TValue); - if (FFlag::LuauFrozenMetaButterfly && hasmetacache(h)) + if (hasmetacache(h)) size += TM_N * sizeof(TValue); // Provide a name for a special registry table @@ -1022,7 +1035,7 @@ static void enumclass(EnumContext* ctx, LuauClass* lco) GCObject* obj = obj2gco(lco); char buf[LUA_IDSIZE]; - snprintf(buf, sizeof(buf), "class object %s", getstr(lco->name)); + snprintf(buf, sizeof(buf), "class %s", getstr(lco->name)); enumnode(ctx, obj, sizeof(LuauClass), buf); enumedge(ctx, obj, obj2gco(lco->name), "classname"); @@ -1030,7 +1043,8 @@ static void enumclass(EnumContext* ctx, LuauClass* lco) enumedge(ctx, obj, obj2gco(lco->super), "super"); enumedge(ctx, obj, obj2gco(lco->memberstooffset), "classoffsets"); - uint32_t numberofstaticmembers = lco->numberofallmembers - lco->numberofinstancemembers; + uint32_t numberofstaticmembers = luaR_numstaticmembers(lco); + uint32_t numberofpublicstaticmembers = numberofstaticmembers - lco->numberofprivatestaticmembers; for (uint32_t i = 0; i < numberofstaticmembers; i++) { @@ -1038,12 +1052,18 @@ static void enumclass(EnumContext* ctx, LuauClass* lco) continue; char membername[32]; - snprintf(membername, sizeof(membername), "%s", getstr(lco->offsettomember[i + lco->numberofinstancemembers])); + if (i < numberofpublicstaticmembers) + snprintf(membername, sizeof(membername), "%s", getstr(lco->offsettomember[i + lco->numberofinstancemembers])); + else + snprintf(membername, sizeof(membername), "privatestaticmember%u", i - numberofpublicstaticmembers); enumedge(ctx, obj, gcvalue(&lco->staticmembers[i]), membername); } - for (uint32_t i = 0; i < lco->numberofallmembers; i++) - enumedge(ctx, obj, obj2gco(lco->offsettomember[i]), "membername"); + for (uint32_t i = 0; i < luaR_offsettomemberlength(lco); i++) + { + if (TString* str = lco->offsettomember[i]) + enumedge(ctx, obj, obj2gco(str), "membername"); + } if (lco->metatable) enumedge(ctx, obj, obj2gco(lco->metatable), "metatable"); @@ -1060,18 +1080,23 @@ static void enumobject(EnumContext* ctx, LuauObject* inst) snprintf(buf, sizeof(buf), "object %s", getstr(inst->lclass->name)); enumnode(ctx, obj, sizeof(LuauObject), buf); - for (uint32_t i = 0; i < inst->lclass->numberofinstancemembers; i++) + if (inst->lclass) + enumedge(ctx, obj, obj2gco(inst->lclass), "class"); + + uint32_t privatefieldsenumerated = 0; + for (uint32_t i = 0; i < inst->numberofmembers; i++) { if (!iscollectable(&inst->members[i])) continue; char membername[32]; - snprintf(membername, sizeof(membername), "%s", getstr(inst->lclass->offsettomember[i])); + TString* nametstring = inst->lclass->offsettomember[i]; + if (nametstring != NULL) + snprintf(membername, sizeof(membername), "%s", getstr(nametstring)); + else + snprintf(membername, sizeof(membername), "privatefield%u", privatefieldsenumerated++); enumedge(ctx, obj, gcvalue(&inst->members[i]), membername); } - - if (inst->lclass) - enumedge(ctx, obj, obj2gco(inst->lclass), "class"); } static void enumobj(EnumContext* ctx, GCObject* o) diff --git a/VM/src/lintlib.cpp b/VM/src/lintlib.cpp index 62824338b..90039a237 100644 --- a/VM/src/lintlib.cpp +++ b/VM/src/lintlib.cpp @@ -434,9 +434,9 @@ static int int64_extract(lua_State* L) int64_t f = luaL_checkinteger64(L, 2); int64_t w = luaL_optinteger64(L, 3, 1); - luaL_argcheck(L, 0 <= f && f <= 63, 2, "field cannot be negative"); + luaL_argcheck(L, 0 <= f, 2, "field cannot be negative"); luaL_argcheck(L, 0 < w, 3, "width must be positive"); - if (f + w > 64) + if (w > 64 - f) luaL_error(L, "trying to access non-existent bits"); lua_pushinteger64(L, ((uint64_t)n >> f) & mask64(w)); @@ -451,9 +451,9 @@ static int int64_replace(lua_State* L) int64_t f = luaL_checkinteger64(L, 3); int64_t w = luaL_optinteger64(L, 4, 1); - luaL_argcheck(L, 0 <= f && f <= 63, 3, "field cannot be negative"); + luaL_argcheck(L, 0 <= f, 3, "field cannot be negative"); luaL_argcheck(L, 0 < w, 4, "width must be positive"); - if (f + w > 64) + if (w > 64 - f) luaL_error(L, "trying to access non-existent bits"); uint64_t baseMask = ((0xFFFFFFFFFFFFFFFFULL) >> (64 - w)); diff --git a/VM/src/lmem.cpp b/VM/src/lmem.cpp index 401a4d522..aa7a52bab 100644 --- a/VM/src/lmem.cpp +++ b/VM/src/lmem.cpp @@ -355,6 +355,8 @@ static void freepage(lua_State* L, lua_Page** pageset, lua_Page* page) *pageset = page->listnext; } + ASAN_UNPOISON_MEMORY_REGION(page, page->pageSize); + // so long pagealloc(g, page, page->pageSize, 0); } diff --git a/VM/src/lobject.h b/VM/src/lobject.h index 3d588a103..84d2d54bd 100644 --- a/VM/src/lobject.h +++ b/VM/src/lobject.h @@ -583,14 +583,17 @@ typedef struct LuauClass // The superclass of this class. NULL if this class doesn't inherit. LuauClass* super; - // Mapping from offset to static members (only methods for now). + // Mapping from offset to static members (only methods for now). Private members at the end. TValue* staticmembers; + // We store a pointer to the private static members separately as an optimization to avoid computing an overall offset into static members. + TValue* privatestaticmembers; - // Mapping from member name to offset. + // Mapping from public member name to offset. // For static members, subtracting numberofinstancemembers from the offset gives the actual index into staticmembers. LuaTable* memberstooffset; - // Mapping from offset to member name. Instance member offsets are stored before static member offsets. + // Mapping from offset to member name. Instance member offsets are stored before static member offsets. Offsets corresponding to private + // fields are NULL, and there are no entries for private static members. TString** offsettomember; // Metatable for this *class object*. At time of writing this only contains __call @@ -600,19 +603,23 @@ typedef struct LuauClass // is added via luaR_addclassmember. LuaTable* instancemetatable; - // Number of instance members that we expect instances of this class object - // to have. + // Number of public and private instance members that we expect instances of this class object to have. uint32_t numberofinstancemembers; - // Total number of members that we expect this class object to have between - // instance and static members. + // Total number of members that we expect this class object to have between instance and static members. // // We store this number as an optimization. It's pretty rare that we need // to reference the specific number of static members, but it's very common // to reference the total number of members (for validating hot paths in // the interpreter) and the number of instance members (branching on // instance or static members, creating class instances). - uint32_t numberofallmembers; + uint32_t numberofmembers; + + uint32_t numberofprivatefields; + // If this class inherits, its ancestors' private fields come before this class's, so we track where its own private fields start. + uint32_t ownprivatefieldsstart; + + uint8_t numberofprivatestaticmembers; // Can this class be extended? bool isopen; @@ -633,14 +640,13 @@ typedef struct LuauObject // The class object that this value is an instance of. LuauClass* lclass; - // The number of members that this instance contains. We need this in order - // to free ourselves if we got swept in the same GC cycle as our class + // The number of members that this instance contains. We need these in order to free ourselves if we get swept in the same GC cycle as our class // pointer. uint32_t numberofmembers; - // The fields of this instance. + // The fields of this instance. Members are ordered according to inheritance chain, with base classes coming first. For each class, public members + // come first, then privates. TValue* members; - } LuauObject; /* diff --git a/VM/src/lstate.cpp b/VM/src/lstate.cpp index 3a31926b3..e2021ee3e 100644 --- a/VM/src/lstate.cpp +++ b/VM/src/lstate.cpp @@ -14,7 +14,6 @@ #include LUAU_FASTFLAG(LuauGcTraceUdata) -LUAU_FASTFLAGVARIABLE(LuauEasyStateInit) LUAU_FASTFLAGVARIABLE(LuauBufferCage) /* @@ -86,28 +85,6 @@ static void f_luaopen(lua_State* L, void* ud) g->GCthreshold = 4 * g->totalbytes; } -static void preinit_state(lua_State* L, global_State* g) -{ - LUAU_ASSERT(!FFlag::LuauEasyStateInit); - - L->global = g; - L->stack = NULL; - L->stacksize = 0; - L->gt = NULL; - L->openupval = NULL; - L->size_ci = 0; - L->nCcalls = L->baseCcalls = 0; - L->status = 0; - L->base_ci = L->ci = NULL; - L->namecall = NULL; - L->cachedslot = 0; - L->singlestep = false; - L->isactive = false; - L->activememcat = 0; - L->finalizers = NULL; - L->userdata = NULL; -} - static void close_state(lua_State* L) { global_State* g = L->global; @@ -138,17 +115,11 @@ static void close_state(lua_State* L) lua_State* luaE_newthread(lua_State* L) { lua_State* L1 = luaM_newgco(L, lua_State, sizeof(lua_State), L->activememcat, LUA_TTHREAD); - - if (FFlag::LuauEasyStateInit) - memset(L1, 0, sizeof(lua_State)); + memset(L1, 0, sizeof(lua_State)); luaC_init(L, L1, LUA_TTHREAD); - if (FFlag::LuauEasyStateInit) - L1->global = L->global; - else - preinit_state(L1, L->global); - + L1->global = L->global; L1->activememcat = L->activememcat; // inherit the active memory category stack_init(L1, L); // init stack L1->gt = L->gt; // share table of globals @@ -212,180 +183,56 @@ void lua_setmemorycage(lua_State* L, lua_CageAlloc alloc, void* ud) lua_State* lua_newstate(lua_Alloc allocator, void* ud) { - if (FFlag::LuauEasyStateInit) - { - void* l = allocator(ud, nullptr, 0, sizeof(LG)); - if (l == nullptr) - return nullptr; + void* l = allocator(ud, nullptr, 0, sizeof(LG)); + if (l == nullptr) + return nullptr; - memset(l, 0, sizeof(LG)); + memset(l, 0, sizeof(LG)); - lua_State* L = &((LG*)l)->l; - global_State* g = &((LG*)l)->g; + lua_State* L = &((LG*)l)->l; + global_State* g = &((LG*)l)->g; - L->tt = LUA_TTHREAD; - L->marked = g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); + L->tt = LUA_TTHREAD; + L->marked = g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); - L->global = g; - g->mainthread = L; + L->global = g; + g->mainthread = L; - g->frealloc = allocator; - g->ud = ud; + g->frealloc = allocator; + g->ud = ud; - g->uvhead.u.open.prev = &g->uvhead; - g->uvhead.u.open.next = &g->uvhead; + g->uvhead.u.open.prev = &g->uvhead; + g->uvhead.u.open.next = &g->uvhead; - g->ptrenckey[0] = 1; + g->ptrenckey[0] = 1; - g->totalbytes = sizeof(LG); - g->memcatbytes[0] = sizeof(LG); + g->totalbytes = sizeof(LG); + g->memcatbytes[0] = sizeof(LG); - g->gcstate = GCSpause; - g->gcgoal = LUAI_GCGOAL; - g->gcstepmul = LUAI_GCSTEPMUL; - g->gcstepsize = LUAI_GCSTEPSIZE << 10; + g->gcstate = GCSpause; + g->gcgoal = LUAI_GCGOAL; + g->gcstepmul = LUAI_GCSTEPMUL; + g->gcstepsize = LUAI_GCSTEPSIZE << 10; - g->cb = lua_Callbacks(); - g->ecb = lua_ExecutionCallbacks(); - g->gcstats = GCStats(); + g->cb = lua_Callbacks(); + g->ecb = lua_ExecutionCallbacks(); + g->gcstats = GCStats(); - g->lastprotoid = 1; - g->lastclassid = 1; + g->lastprotoid = 1; + g->lastclassid = 1; #ifdef LUAI_GCMETRICS - g->gcmetrics = GCMetrics(); + g->gcmetrics = GCMetrics(); #endif - if (luaD_rawrunprotected(L, f_luaopen, nullptr) != 0) - { - // memory allocation error: free partial state - close_state(L); - L = nullptr; - } - return L; - } - else + if (luaD_rawrunprotected(L, f_luaopen, nullptr) != 0) { - int i; - lua_State* L; - global_State* g; - void* l = (*allocator)(ud, NULL, 0, sizeof(LG)); - if (l == NULL) - return NULL; - L = (lua_State*)l; - g = &((LG*)L)->g; - L->tt = LUA_TTHREAD; - L->marked = g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); - L->memcat = 0; - preinit_state(L, g); - g->frealloc = allocator; - g->ud = ud; - g->mainthread = L; - g->uvhead.u.open.prev = &g->uvhead; - g->uvhead.u.open.next = &g->uvhead; - g->GCthreshold = 0; // mark it as unfinished state - g->registryfree = 0; - g->errorjmp = NULL; - g->rngstate = 0; - g->ptrenckey[0] = 1; - g->ptrenckey[1] = 0; - g->ptrenckey[2] = 0; - g->ptrenckey[3] = 0; - for (int i = 0; i < 8; i++) - g->ptrenckeynew[i] = 0; - g->ptrencactive = 0; - g->strt.size = 0; - g->strt.nuse = 0; - g->strt.hash = NULL; - setnilvalue(&g->pseudotemp); - setnilvalue(registry(L)); - setnilvalue(&g->weakregistry); - g->weakregistryfree = 0; - g->weakregistrytop = 0; - g->embeddergc = NULL; - g->gcstate = GCSpause; - g->gray = NULL; - g->grayagain = NULL; - g->weak = NULL; - g->totalbytes = sizeof(LG); - g->gcgoal = LUAI_GCGOAL; - g->gcstepmul = LUAI_GCSTEPMUL; - g->gcstepsize = LUAI_GCSTEPSIZE << 10; - - for (i = 0; i < LUA_SIZECLASSES; i++) - { - g->freepages[i] = NULL; - g->freegcopages[i] = NULL; - g->freegcopages_cage[i] = NULL; - } - - g->allpages = NULL; - g->allgcopages = NULL; - g->sweepgcopage = NULL; - g->cagealloc = NULL; - g->cageud = NULL; - g->allgcopages_cage = NULL; - g->sweepgcopage_cage = NULL; - - for (i = 0; i < LUA_T_COUNT; i++) - g->mt[i] = NULL; - - for (i = 0; i < LUA_UTAG_LIMIT; i++) - { - g->udatagc[i] = NULL; - g->udatamark[i] = NULL; - g->udatamt[i] = NULL; - } - - for (i = 0; i < UTAG_INTERNAL_LIMIT; i++) - { - lua_UdataDirectAccessData& udatadirect = L->global->udatadirect[i]; - - setnilvalue(&udatadirect.indextm); - setnilvalue(&udatadirect.newindextm); - setnilvalue(&udatadirect.namecalltm); - udatadirect.index = NULL; - udatadirect.newindex = NULL; - udatadirect.namecall = NULL; - } - - for (i = 0; i < LUA_LUTAG_LIMIT; i++) - g->lightuserdataname[i] = NULL; - - for (i = 0; i < UTAG_INTERNAL_LIMIT; i++) - g->udatadirectfields[i] = NULL; - - for (i = 0; i < LUA_MEMORY_CATEGORIES; i++) - g->memcatbytes[i] = 0; - - g->memcatbytes[0] = sizeof(LG); - - g->cb = lua_Callbacks(); - - g->ecb = lua_ExecutionCallbacks(); - - memset(g->ecbdata, 0, LUA_EXECUTION_CALLBACK_STORAGE * sizeof(g->ecbdata[0])); - - g->gcstats = GCStats(); - g->lastprotoid = 1; - g->lastclassid = 1; - - g->builtinPcall = NULL; - g->builtinXpcall = NULL; - -#ifdef LUAI_GCMETRICS - g->gcmetrics = GCMetrics(); -#endif - - if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) - { - // memory allocation error: free partial state - close_state(L); - L = NULL; - } - return L; + // memory allocation error: free partial state + close_state(L); + L = nullptr; } + return L; } void lua_close(lua_State* L) diff --git a/VM/src/ltable.cpp b/VM/src/ltable.cpp index 9da56e5ae..01d058d13 100644 --- a/VM/src/ltable.cpp +++ b/VM/src/ltable.cpp @@ -34,10 +34,7 @@ #include -LUAU_FASTFLAG(LuauFrozenMetaButterfly) LUAU_DYNAMIC_FASTFLAG(LuauTableFindImprovement) -LUAU_DYNAMIC_FASTFLAGVARIABLE(LuauSplitTableLookups, false) -LUAU_FASTFLAGVARIABLE(LuauTableArrayShrinkOrder) LUAU_DYNAMIC_FASTFLAGVARIABLE(LuauTableRobustOom, false) // Set this to 1 to change the hash function to something different (and possibly trivial). Useful @@ -693,26 +690,8 @@ static void setnodevector(lua_State* L, LuaTable* t, int size) t->lastfree = size; // all positions are free } -// TODO: forward declaration not needed with DFFlagLuauSplitTableLookups removal -static TValue* newkey_DEPRECATED(lua_State* L, LuaTable* t, const TValue* key); - static TValue* reinsertkey(lua_State* L, LuaTable* t, const TValue* key, bool checkarraypart); -// TODO: remove with DFFlagLuauSplitTableLookups -static TValue* arrayornewkey_DEPRECATED(lua_State* L, LuaTable* t, const TValue* key) -{ - if (ttisnumber(key)) - { - int k; - double n = nvalue(key); - luai_num2int(k, n); - if (luai_numeq(cast_num(k), n) && unsigned(k) - 1 < unsigned(t->sizearray)) - return &t->array[k - 1]; - } - - return newkey_DEPRECATED(L, t, key); -} - static void resize(lua_State* L, LuaTable* t, int nasize, int nhsize) { LUAU_ASSERT(!hasmetacache(t)); @@ -809,15 +788,8 @@ static void resize(lua_State* L, LuaTable* t, int nasize, int nhsize) { TValue ok; setnvalue(&ok, cast_num(i + 1)); - if (DFFlag::LuauSplitTableLookups) - { - // integer number keys from a shrinking slice cannot get into the new array part - setobjt2t(L, reinsertkey(L, t, &ok, false), &oldarray[i]); - } - else - { - setobjt2t(L, newkey_DEPRECATED(L, t, &ok), &oldarray[i]); - } + // integer number keys from a shrinking slice cannot get into the new array part + setobjt2t(L, reinsertkey(L, t, &ok, false), &oldarray[i]); } } @@ -829,15 +801,7 @@ static void resize(lua_State* L, LuaTable* t, int nasize, int nhsize) { TValue ok; getnodekey(L, &ok, old); - - if (DFFlag::LuauSplitTableLookups) - { - setobjt2t(L, reinsertkey(L, t, &ok, true), gval(old)); - } - else - { - setobjt2t(L, arrayornewkey_DEPRECATED(L, t, &ok), gval(old)); - } + setobjt2t(L, reinsertkey(L, t, &ok, true), gval(old)); } } @@ -867,64 +831,29 @@ static void resize(lua_State* L, LuaTable* t, int nasize, int nhsize) LuaNode* nnew = t->node; if (nasize < oldasize) { // array part must shrink? - if (FFlag::LuauTableArrayShrinkOrder) - { - TValue* oldarray = t->array; - - // shrink array - t->array = luaM_newarray(L, nasize, TValue, t->memcat); - t->sizearray = nasize; + TValue* oldarray = t->array; - // copy elements from remaining slice - if (nasize != 0) - memcpy(t->array, oldarray, nasize * sizeof(TValue)); + // shrink array + t->array = luaM_newarray(L, nasize, TValue, t->memcat); + t->sizearray = nasize; - // re-insert elements from vanishing slice (landing into the hash part) - for (int i = nasize; i < oldasize; i++) - { - if (!ttisnil(&oldarray[i])) - { - TValue ok; - setnvalue(&ok, cast_num(i + 1)); - if (DFFlag::LuauSplitTableLookups) - { - // integer number keys from a shrinking slice cannot get into the new array part - setobjt2t(L, reinsertkey(L, t, &ok, false), &oldarray[i]); - } - else - { - setobjt2t(L, newkey_DEPRECATED(L, t, &ok), &oldarray[i]); - } - } - } + // copy elements from remaining slice + if (nasize != 0) + memcpy(t->array, oldarray, nasize * sizeof(TValue)); - luaM_freearray(L, oldarray, oldasize, TValue, t->memcat); - } - else + // re-insert elements from vanishing slice (landing into the hash part) + for (int i = nasize; i < oldasize; i++) { - t->sizearray = nasize; - // re-insert elements from vanishing slice - for (int i = nasize; i < oldasize; i++) + if (!ttisnil(&oldarray[i])) { - if (!ttisnil(&t->array[i])) - { - TValue ok; - setnvalue(&ok, cast_num(i + 1)); - - if (DFFlag::LuauSplitTableLookups) - { - // integer number keys from a shrinking slice cannot get into the new array part - setobjt2t(L, reinsertkey(L, t, &ok, false), &t->array[i]); - } - else - { - setobjt2t(L, newkey_DEPRECATED(L, t, &ok), &t->array[i]); - } - } + TValue ok; + setnvalue(&ok, cast_num(i + 1)); + // integer number keys from a shrinking slice cannot get into the new array part + setobjt2t(L, reinsertkey(L, t, &ok, false), &oldarray[i]); } - // shrink array - luaM_reallocarray(L, t->array, oldasize, nasize, TValue, t->memcat); } + + luaM_freearray(L, oldarray, oldasize, TValue, t->memcat); } // used for the migration check at the end TValue* anew = t->array; @@ -936,15 +865,7 @@ static void resize(lua_State* L, LuaTable* t, int nasize, int nhsize) { TValue ok; getnodekey(L, &ok, old); - - if (DFFlag::LuauSplitTableLookups) - { - setobjt2t(L, reinsertkey(L, t, &ok, true), gval(old)); - } - else - { - setobjt2t(L, arrayornewkey_DEPRECATED(L, t, &ok), gval(old)); - } + setobjt2t(L, reinsertkey(L, t, &ok, true), gval(old)); } } @@ -956,16 +877,6 @@ static void resize(lua_State* L, LuaTable* t, int nasize, int nhsize) luaM_freearray(L, nold, twoto(oldhsize), LuaNode, t->memcat); // free old array } -static int adjustasize_DEPRECATED(LuaTable* t, int size, const TValue* ek) -{ - bool tbound = t->node != dummynode || size < t->sizearray; - int ekindex = ek && ttisnumber(ek) ? arrayindex(nvalue(ek)) : -1; - // move the array size up until the boundary is guaranteed to be inside the array part - while (size + 1 == ekindex || (tbound && !ttisnil(luaH_getnum(t, size + 1)))) - size++; - return size; -} - // When we already know that new key is an integer number static int adjustasize(LuaTable* t, int size, int extraintkey) { @@ -982,7 +893,7 @@ void luaH_resizearray(lua_State* L, LuaTable* t, int nasize) luaG_runerror(L, "table overflow"); int nsize = (t->node == dummynode) ? 0 : sizenode(t); - int asize = DFFlag::LuauSplitTableLookups ? adjustasize(t, nasize, -1) : adjustasize_DEPRECATED(t, nasize, NULL); + int asize = adjustasize(t, nasize, -1); resize(L, t, asize, nsize); } @@ -991,47 +902,6 @@ void luaH_resizehash(lua_State* L, LuaTable* t, int nhsize) resize(L, t, t->sizearray, nhsize); } -static void rehash_DEPRECATED(lua_State* L, LuaTable* t, const TValue* ek) -{ - int nums[MAXBITS + 1]; // nums[i] = number of keys between 2^(i-1) and 2^i - for (int i = 0; i <= MAXBITS; i++) - nums[i] = 0; // reset counts - int nasize = numusearray(t, nums); // count keys in array part - int totaluse = nasize; // all those keys are integer keys - totaluse += numusehash(t, nums, &nasize); // count keys in hash part - - // count extra key - if (ttisnumber(ek)) - nasize += countint(nvalue(ek), nums); - totaluse++; - - // compute new size for array part - int na = computesizes(nums, &nasize); - int nh = totaluse - na; - - // enforce the boundary invariant; for performance, only do hash lookups if we must - int nadjusted = adjustasize_DEPRECATED(t, nasize, ek); - - // count how many extra elements belong to array part instead of hash part - int aextra = nadjusted - nasize; - - if (aextra != 0) - { - // we no longer need to store those extra array elements in hash part - nh -= aextra; - - // because hash nodes are twice as large as array nodes, the memory we saved for hash parts can be used by array part - // this follows the general sparse array part optimization where array is allocated when 50% occupation is reached - nasize = nadjusted + aextra; - - // since the size was changed, it's again important to enforce the boundary invariant at the new size - nasize = adjustasize_DEPRECATED(t, nasize, ek); - } - - // resize the table to new computed sizes - resize(L, t, nasize, nh); -} - template static void rehash(lua_State* L, LuaTable* t, int newintkey) { @@ -1127,19 +997,11 @@ void luaH_free(lua_State* L, LuaTable* t, lua_Page* page) if (t->node != dummynode) luaM_freearray(L, t->node, sizenode(t), LuaNode, t->memcat); - if (FFlag::LuauFrozenMetaButterfly) + if (t->array) { - if (t->array) - { - if (hasmetacache(t)) - luaM_freearray(L, t->array - TM_N, t->sizearray + TM_N, TValue, t->memcat); - else - luaM_freearray(L, t->array, t->sizearray, TValue, t->memcat); - } - } - else - { - if (t->array) + if (hasmetacache(t)) + luaM_freearray(L, t->array - TM_N, t->sizearray + TM_N, TValue, t->memcat); + else luaM_freearray(L, t->array, t->sizearray, TValue, t->memcat); } @@ -1199,64 +1061,6 @@ static LuaNode* newcollidingkey(lua_State* L, LuaTable* t, LuaNode* mp, LuaNode* } } -static TValue* newkey_DEPRECATED(lua_State* L, LuaTable* t, const TValue* key) -{ - // enforce boundary invariant - if (ttisnumber(key) && nvalue(key) == t->sizearray + 1) - { - rehash_DEPRECATED(L, t, key); // grow table - - // after rehash, numeric keys might be located in the new array part, but won't be found in the node part - return arrayornewkey_DEPRECATED(L, t, key); - } - - LuaNode* mp = mainposition(t, key); - if (!ttisnil(gval(mp)) || mp == dummynode) - { - LuaNode* n = getfreepos(t); // get a free place - if (n == NULL) - { // cannot find a free place? - rehash_DEPRECATED(L, t, key); // grow table - - // after rehash, numeric keys might be located in the new array part, but won't be found in the node part - return arrayornewkey_DEPRECATED(L, t, key); - } - LUAU_ASSERT(n != dummynode); - TValue mk; - getnodekey(L, &mk, mp); - LuaNode* othern = mainposition(t, &mk); - if (othern != mp) - { // is colliding node out of its main position? - // yes; move colliding node into free position - while (othern + gnext(othern) != mp) - othern += gnext(othern); // find previous - gnext(othern) = cast_int(n - othern); // redo the chain with `n' in place of `mp' - *n = *mp; // copy colliding node into free pos. (mp->next also goes) - if (gnext(mp) != 0) - { - gnext(n) += cast_int(mp - n); // correct 'next' - gnext(mp) = 0; // now 'mp' is free - } - setnilvalue(gval(mp)); - } - else - { // colliding node is in its own main position - // new node will go into free position - if (gnext(mp) != 0) - gnext(n) = cast_int((mp + gnext(mp)) - n); // chain new position - else - LUAU_ASSERT(gnext(n) == 0); - gnext(mp) = cast_int(n - mp); - mp = n; - } - } - - setnodekey(L, mp, key); - luaC_barriert(L, t, key); - LUAU_ASSERT(ttisnil(gval(mp))); - return gval(mp); -} - /* ** inserts a new key into a hash table; first, check whether key's main ** position is free. If not, check whether colliding node is in its main @@ -1398,7 +1202,7 @@ const TValue* luaH_getp(LuaTable* t, void* key, int tag) */ const TValue* luaH_get(LuaTable* t, const TValue* key) { - if (DFFlag::LuauSplitTableLookups && DFFlag::LuauTableFindImprovement) + if (DFFlag::LuauTableFindImprovement) { switch (ttype(key)) { @@ -1428,7 +1232,7 @@ const TValue* luaH_get(LuaTable* t, const TValue* key) return chainsearchtagged(t, gcvalue(key), ttype(key)); } } - else if (DFFlag::LuauSplitTableLookups) + else { switch (ttype(key)) { @@ -1458,38 +1262,6 @@ const TValue* luaH_get(LuaTable* t, const TValue* key) return chainsearchtagged_DEPRECATED(t, gcvalue(key), ttype(key)); } } - else - { - switch (ttype(key)) - { - case LUA_TNIL: - return luaO_nilobject; - case LUA_TSTRING: - return luaH_getstr(t, tsvalue(key)); - case LUA_TNUMBER: - { - int k; - double n = nvalue(key); - luai_num2int(k, n); - if (luai_numeq(cast_num(k), nvalue(key))) // index is int? - return luaH_getnum(t, k); // use specialized version - LUAU_FALLTHROUGH; // else go through - } - default: - { - LuaNode* n = mainposition(t, key); - for (;;) - { // check whether `key' is somewhere in the chain - if (luaO_rawequalKey(gkey(n), key)) - return gval(n); // that's it - if (gnext(n) == 0) - break; - n += gnext(n); - } - return luaO_nilobject; - } - } - } } TValue* luaH_set(lua_State* L, LuaTable* t, const TValue* key) @@ -1504,53 +1276,40 @@ TValue* luaH_set(lua_State* L, LuaTable* t, const TValue* key) TValue* luaH_newkey(lua_State* L, LuaTable* t, const TValue* key) { - if (DFFlag::LuauSplitTableLookups) + switch (ttype(key)) { - switch (ttype(key)) - { - case LUA_TNIL: - luaG_runerror(L, "table index is nil"); - break; - case LUA_TBOOLEAN: - return newkeytagged(L, t, key, bvalue(key), -1); - case LUA_TLIGHTUSERDATA: - return newkeytagged(L, t, key, pvalue(key), -1); - case LUA_TNUMBER: - { - double n = nvalue(key); - - if (luai_numisnan(n)) - luaG_runerror(L, "table index is NaN"); + case LUA_TNIL: + luaG_runerror(L, "table index is nil"); + break; + case LUA_TBOOLEAN: + return newkeytagged(L, t, key, bvalue(key), -1); + case LUA_TLIGHTUSERDATA: + return newkeytagged(L, t, key, pvalue(key), -1); + case LUA_TNUMBER: + { + double n = nvalue(key); - int k; - luai_num2int(k, n); - if (luai_numeq(cast_num(k), n)) - return newkeytagged(L, t, key, n, k); + if (luai_numisnan(n)) + luaG_runerror(L, "table index is NaN"); - return newkeytagged(L, t, key, n, -1); - } - case LUA_TINTEGER: - return newkeytagged(L, t, key, lvalue(key), -1); - case LUA_TVECTOR: - if (luai_vecisnan(vvalue(key))) - luaG_runerror(L, "table index contains NaN"); + int k; + luai_num2int(k, n); + if (luai_numeq(cast_num(k), n)) + return newkeytagged(L, t, key, n, k); - return newkeytagged(L, t, key, (const LUA_VECTOR_TYPE*)vvalue(key), -1); - case LUA_TSTRING: - return newkeytagged(L, t, key, tsvalue(key), -1); - default: - return newkeytagged(L, t, key, gcvalue(key), -1); - } + return newkeytagged(L, t, key, n, -1); } - else - { - if (ttisnil(key)) - luaG_runerror(L, "table index is nil"); - else if (ttisnumber(key) && luai_numisnan(nvalue(key))) - luaG_runerror(L, "table index is NaN"); - else if (ttisvector(key) && luai_vecisnan(vvalue(key))) + case LUA_TINTEGER: + return newkeytagged(L, t, key, lvalue(key), -1); + case LUA_TVECTOR: + if (luai_vecisnan(vvalue(key))) luaG_runerror(L, "table index contains NaN"); - return newkey_DEPRECATED(L, t, key); + + return newkeytagged(L, t, key, (const LUA_VECTOR_TYPE*)vvalue(key), -1); + case LUA_TSTRING: + return newkeytagged(L, t, key, tsvalue(key), -1); + default: + return newkeytagged(L, t, key, gcvalue(key), -1); } } @@ -1565,20 +1324,11 @@ TValue* luaH_setnum(lua_State* L, LuaTable* t, int key) return cast_to(TValue*, p); else { - if (DFFlag::LuauSplitTableLookups) - { - double n = cast_num(key); + double n = cast_num(key); - TValue k; - setnvalue(&k, n); - return newkeytagged(L, t, &k, n, key); - } - else - { - TValue k; - setnvalue(&k, cast_num(key)); - return newkey_DEPRECATED(L, t, &k); - } + TValue k; + setnvalue(&k, n); + return newkeytagged(L, t, &k, n, key); } } @@ -1592,11 +1342,7 @@ TValue* luaH_setstr(lua_State* L, LuaTable* t, TString* key) { TValue k; setsvalue(L, &k, key); - - if (DFFlag::LuauSplitTableLookups) - return newkeytagged(L, t, &k, key, -1); - else - return newkey_DEPRECATED(L, t, &k); + return newkeytagged(L, t, &k, key, -1); } } @@ -1609,11 +1355,7 @@ TValue* luaH_setp(lua_State* L, LuaTable* t, void* key, int tag) { TValue k; setpvalue(&k, key, tag); - - if (DFFlag::LuauSplitTableLookups) - return newkeytagged(L, t, &k, key, -1); - else - return newkey_DEPRECATED(L, t, &k); + return newkeytagged(L, t, &k, key, -1); } } diff --git a/VM/src/ltm.cpp b/VM/src/ltm.cpp index 016113d67..1d89fa117 100644 --- a/VM/src/ltm.cpp +++ b/VM/src/ltm.cpp @@ -13,8 +13,6 @@ #include -LUAU_FASTFLAG(LuauFrozenMetaButterfly) - // clang-format off const char* const luaT_typenames[] = { // ORDER TYPE @@ -138,7 +136,7 @@ const TValue* luaT_gettmbyobj(lua_State* L, const TValue* o, TMS event) mt = L->global->mt[ttype(o)]; } - if (FFlag::LuauFrozenMetaButterfly && mt && hasmetacache(mt)) + if (mt && hasmetacache(mt)) return getmetacache(mt, event); return (mt ? luaH_getstr(mt, L->global->tmname[event]) : luaO_nilobject); diff --git a/VM/src/ltm.h b/VM/src/ltm.h index 44fe5c2ee..3af009b78 100644 --- a/VM/src/ltm.h +++ b/VM/src/ltm.h @@ -4,8 +4,6 @@ #include "lobject.h" -LUAU_FASTFLAG(LuauFrozenMetaButterfly) - /* * WARNING: if you change the order of this enumeration, * grep "ORDER TM" @@ -43,10 +41,7 @@ typedef enum // clang-format on #define gfasttm(g, et, e) \ - ((et) == NULL ? NULL \ - : ((et)->tmcache & (1u << (e))) \ - ? NULL \ - : (FFlag::LuauFrozenMetaButterfly && hasmetacache(et) ? getmetacache(et, e) : luaT_gettm(et, e, (g)->tmname[e]))) + ((et) == NULL ? NULL : ((et)->tmcache & (1u << (e))) ? NULL : (hasmetacache(et) ? getmetacache(et, e) : luaT_gettm(et, e, (g)->tmname[e]))) #define fasttm(l, et, e) gfasttm(l->global, et, e) #define fastnotm(et, e) ((et) == NULL || ((et)->tmcache & (1u << (e)))) diff --git a/VM/src/lvmexecute.cpp b/VM/src/lvmexecute.cpp index 7a6b4bffb..d197919ad 100644 --- a/VM/src/lvmexecute.cpp +++ b/VM/src/lvmexecute.cpp @@ -21,7 +21,6 @@ LUAU_FASTFLAGVARIABLE(DebugLuauUserDefinedClassesRuntime) LUAU_FASTFLAGVARIABLE(LuauPromoteProto) LUAU_FASTFLAG(LuauFastpcall) -LUAU_FASTFLAGVARIABLE(LuauFastpcallInterrupt) // Disable c99-designator to avoid the warning in computed goto dispatch table #ifdef __clang__ @@ -126,7 +125,7 @@ LUAU_FASTFLAGVARIABLE(LuauFastpcallInterrupt) VM_DISPATCH_OP(LOP_JUMPXEQKB), VM_DISPATCH_OP(LOP_JUMPXEQKN), VM_DISPATCH_OP(LOP_JUMPXEQKS), VM_DISPATCH_OP(LOP_IDIV), \ VM_DISPATCH_OP(LOP_IDIVK), VM_DISPATCH_OP(LOP_GETUDATAKS), VM_DISPATCH_OP(LOP_SETUDATAKS), VM_DISPATCH_OP(LOP_NAMECALLUDATA), \ VM_DISPATCH_OP(LOP_NEWCLASSMEMBER), VM_DISPATCH_OP(LOP_CALLFB), VM_DISPATCH_OP(LOP_CMPPROTO), VM_DISPATCH_OP(LOP_FASTPCALL), \ - VM_DISPATCH_OP(LOP_NEWCLASS), VM_DISPATCH_OP(LOP_CONSTRUCT), VM_DISPATCH_OP(LOP_FINCONSTRUCT), + VM_DISPATCH_OP(LOP_NEWCLASS), VM_DISPATCH_OP(LOP_CONSTRUCT), VM_DISPATCH_OP(LOP_FINCONSTRUCT), VM_DISPATCH_OP(LOP_GETPRIVATEFIELD), VM_DISPATCH_OP(LOP_SETPRIVATEFIELD), #if defined(__GNUC__) || defined(__clang__) #define VM_USE_CGOTO 1 @@ -654,7 +653,7 @@ static void luau_execute(lua_State* L) // to the class member with the same name. uint8_t slot = LUAU_INSN_C(insn); LuauObject* inst = objectvalue(rb); - if (LUAU_LIKELY(slot < inst->lclass->numberofallmembers && tsvalue(kv) == inst->lclass->offsettomember[slot])) + if (LUAU_LIKELY(slot < luaR_offsettomemberlength(inst->lclass) && tsvalue(kv) == inst->lclass->offsettomember[slot])) { setobj2s(L, ra, luaR_lookupmemberatoffset(inst, slot)); VM_NEXT(); @@ -1011,7 +1010,7 @@ static void luau_execute(lua_State* L) { uint8_t slot = LUAU_INSN_C(insn); LuauObject* inst = objectvalue(rb); - if (slot < inst->lclass->numberofallmembers && tsvalue(kv) == inst->lclass->offsettomember[slot]) + if (slot < luaR_offsettomemberlength(inst->lclass) && tsvalue(kv) == inst->lclass->offsettomember[slot]) { // note: order of copies allows rb to alias ra+1 or ra setobj2s(L, ra + 1, rb); @@ -3642,15 +3641,24 @@ static void luau_execute(lua_State* L) VM_CASE(LOP_NEWCLASSMEMBER) { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClassesRuntime); VM_CASE_INSTRUCTION insn = *pc++; uint32_t aux = *pc++; VM_CASE_STKID ra = VM_REG(LUAU_INSN_A(insn)); - TValue* membername = VM_KV(aux); - LUAU_ASSERT(ttisstring(membername)); - LUAU_ASSERT(LUAU_INSN_B(insn) == 0); + uint8_t visibility = LuauClassMemberVisibility(LUAU_INSN_B(insn)); + LUAU_ASSERT(visibility == LuauClassMemberVisibility::LCMV_PUBLIC || visibility == LuauClassMemberVisibility::LCMV_PRIVATE); VM_CASE_STKID rc = VM_REG(LUAU_INSN_C(insn)); VM_PROTECT_PC(); - luaR_addclassmember(L, classvalue(ra), tsvalue(membername), rc); + if (visibility == LuauClassMemberVisibility::LCMV_PUBLIC) + { + TValue* membername = VM_KV(aux); + luaR_addpublicstaticmember(L, classvalue(ra), tsvalue(membername), rc); + } + else + { + uint8_t pindex = LUAU_INSN_AUX_A(aux); + luaR_addprivatestaticmember(L, classvalue(ra), pindex, rc); + } VM_NEXT(); } @@ -3683,8 +3691,7 @@ static void luau_execute(lua_State* L) if (!FFlag::LuauFastpcall) VM_NEXT(); - if (FFlag::LuauFastpcallInterrupt) - VM_INTERRUPT(); + VM_INTERRUPT(); int pfid = LUAU_INSN_A(insn); int skip = LUAU_INSN_C(insn); @@ -3752,6 +3759,7 @@ static void luau_execute(lua_State* L) VM_CASE(LOP_NEWCLASS) { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClassesRuntime); VM_CASE_INSTRUCTION insn = *pc++; VM_CASE_STKID ra = VM_REG(LUAU_INSN_A(insn)); uint8_t super = LUAU_INSN_B(insn); @@ -3823,6 +3831,107 @@ static void luau_execute(lua_State* L) VM_NEXT(); } + VM_CASE(LOP_GETPRIVATEFIELD) + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClassesRuntime); + + VM_CASE_INSTRUCTION insn = *pc++; + uint32_t aux = *pc++; + + VM_PROTECT_PC(); + + VM_CASE_STKID ra = VM_REG(LUAU_INSN_A(insn)); + + VM_CASE_STKID rb = VM_REG(LUAU_INSN_B(insn)); + if (LUAU_UNLIKELY(!(ttisobject(rb) || ttisclass(rb)))) + luaG_typeerror(L, rb, "access private field of"); + + TValue* clsuv = VM_UV(LUAU_INSN_C(insn)); + TValue* clsv = ttisupval(clsuv) ? upvalue(clsuv)->v : clsuv; + if (LUAU_UNLIKELY(!ttisclass(clsv))) + luaG_typeerror(L, clsv, "verify object is an instance of"); + + LuauClass* cls = classvalue(clsv); + + if (ttisobject(rb)) + { + LuauObject* inst = objectvalue(rb); + + if (!luaR_isinstance(inst, cls)) + luaG_runerror(L, "attempt to illegally access private field"); + + if (LUAU_INSN_AUX_STATIC(aux)) + { + uint8_t pindex = LUAU_INSN_AUX_A(aux); + // If namecall flag is set, put class instance/object into register after target + if (LUAU_INSN_AUX_NAMECALL(aux)) + setobj2s(L, ra + 1, rb); + setobj2s(L, ra, luaR_privatestaticmember(cls, pindex)); + } + else + { + uint32_t pindex = LUAU_INSN_AUX_A(aux) + cls->ownprivatefieldsstart; + LUAU_ASSERT(pindex < inst->numberofmembers); + // If namecall flag is set, put class instance/object into register after target + if (LUAU_INSN_AUX_NAMECALL(aux)) + setobj2s(L, ra + 1, rb); + setobj2s(L, ra, &inst->members[pindex]); + } + } + else + { + LuauClass* srccls = classvalue(rb); + + if (LUAU_UNLIKELY(!luaR_issubclass(srccls, cls))) + luaG_runerror(L, "attempt to illegally access private field of a class"); + if (LUAU_UNLIKELY(!LUAU_INSN_AUX_STATIC(aux))) + luaG_runerror(L, "attempt to access private instance field of a class"); + + uint8_t pindex = LUAU_INSN_AUX_A(aux); + // If namecall flag is set, put class instance/object into register after target + if (LUAU_INSN_AUX_NAMECALL(aux)) + setobj2s(L, ra + 1, rb); + setobj2s(L, ra, luaR_privatestaticmember(cls, pindex)); + } + + VM_NEXT(); + } + + VM_CASE(LOP_SETPRIVATEFIELD) + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClassesRuntime); + + VM_CASE_INSTRUCTION insn = *pc++; + uint32_t aux = *pc++; + + VM_CASE_STKID ra = VM_REG(LUAU_INSN_A(insn)); + VM_CASE_STKID rb = VM_REG(LUAU_INSN_B(insn)); + + VM_PROTECT_PC(); + + if (!ttisobject(rb)) + luaG_typeerror(L, rb, "assign private field of"); + + TValue* clsuv = VM_UV(LUAU_INSN_C(insn)); + TValue* clsv = ttisupval(clsuv) ? upvalue(clsuv)->v : clsuv; + if (!ttisclass(clsv)) + luaG_typeerror(L, clsv, "assign private field of"); + + LuauObject* inst = objectvalue(rb); + LuauClass* cls = classvalue(clsv); + + if (!luaR_isinstance(inst, cls)) + luaG_runerror(L, "attempt to assign private field of an object with a different class"); + + uint32_t pindex = (aux & 0xffu) + cls->ownprivatefieldsstart; + LUAU_ASSERT(pindex < inst->numberofmembers); + + setobj2class(L, &inst->members[pindex], ra); + luaC_barrier(L, inst, ra); + + VM_NEXT(); + } + #if !VM_USE_CGOTO default: LUAU_ASSERT(!"Unknown opcode"); diff --git a/VM/src/lvmload.cpp b/VM/src/lvmload.cpp index 6926b7122..13b564cfe 100644 --- a/VM/src/lvmload.cpp +++ b/VM/src/lvmload.cpp @@ -631,13 +631,30 @@ static int loadsafe( uint32_t cnid = readVarInt(data, size, offset); TValue* classname = &p->k[cnid]; LUAU_ASSERT(ttisstring(classname)); + uint8_t numPrivateFields = read(data, size, offset); + uint8_t numPrivateMethods = read(data, size, offset); uint32_t numProperties = readVarInt(data, size, offset); uint32_t numMethods = readVarInt(data, size, offset); uint32_t numMembers = numMethods + numProperties; - TString** offsetToMember = luaM_newarray(L, numMembers, TString*, L->activememcat); - LuaTable* membersToOffset = luaH_new(L, 0, numMembers); + uint32_t membersWithoutPrivateMethods = numMembers - static_cast(numPrivateMethods); + TString** offsetToMember = luaM_newarray(L, membersWithoutPrivateMethods, TString*, L->activememcat); + memset(offsetToMember, 0, membersWithoutPrivateMethods * sizeof(TString*)); + LuaTable* membersToOffset = luaH_new(L, 0, membersWithoutPrivateMethods - static_cast(numPrivateFields)); + + uint32_t idx = 0; + // Set public field names + for (; idx < numProperties - static_cast(numPrivateFields); idx++) + { + uint32_t mid = readVarInt(data, size, offset); + TValue* memberName = &p->k[mid]; + LUAU_ASSERT(ttisstring(memberName)); + offsetToMember[idx] = tsvalue(memberName); + TValue* val = luaH_setstr(L, membersToOffset, tsvalue(memberName)); + setnvalue(val, idx); + } - for (uint32_t idx = 0; idx < numMembers; idx++) + // Set public method names + for (idx = numProperties; idx < membersWithoutPrivateMethods; idx++) { uint32_t mid = readVarInt(data, size, offset); TValue* memberName = &p->k[mid]; @@ -649,7 +666,9 @@ static int loadsafe( membersToOffset->readonly = true; - LuauClass* lco = luaR_newclass(L, tsvalue(classname), membersToOffset, offsetToMember, numProperties, numMethods, envt); + LuauClass* lco = luaR_newclass( + L, tsvalue(classname), membersToOffset, offsetToMember, numProperties, numMethods, numPrivateFields, numPrivateMethods, envt + ); setclassvalue(L, &p->k[j], lco); break; } diff --git a/VM/src/lvmutils.cpp b/VM/src/lvmutils.cpp index 1219ed435..4addd9ba0 100644 --- a/VM/src/lvmutils.cpp +++ b/VM/src/lvmutils.cpp @@ -17,10 +17,8 @@ // limit for table tag-method chains (to avoid loops) #define MAXTAGLOOP 100 -LUAU_FASTFLAG(LuauFrozenMetaButterfly) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) LUAU_FASTFLAG(LuauPromoteProto) -LUAU_FASTFLAGVARIABLE(LuauCallLuauTm) const TValue* luaV_tonumber(const TValue* obj, TValue* n) { @@ -108,37 +106,24 @@ static StkId callTMres(lua_State* L, StkId res, const TValue* f, const TValue* p // * we cannot use savestack/restorestack because the arguments are sometimes on the C++ stack // * during stack reallocation all of the allocated stack is copied (even beyond stack_last) so these // values will be preserved even if they go past stack_last - if (FFlag::LuauCallLuauTm) + StkId top = L->top; + LUAU_ASSERT((top + 3) < (L->stack + L->stacksize)); + setobj2s(L, top, f); // push function + setobj2s(L, top + 1, p1); // 1st argument + setobj2s(L, top + 2, p2); // 2nd argument + + // fast-path for Luau to Luau calls + if (L->isactive && isLua(L->ci) && ttisfunction(top) && !clvalue(top)->isC) { - StkId top = L->top; - LUAU_ASSERT((top + 3) < (L->stack + L->stacksize)); - setobj2s(L, top, f); // push function - setobj2s(L, top + 1, p1); // 1st argument - setobj2s(L, top + 2, p2); // 2nd argument - - // fast-path for Luau to Luau calls - if (L->isactive && isLua(L->ci) && ttisfunction(top) && !clvalue(top)->isC) - { - L->top += 3; - callTMluau(L, top, clvalue(top), 1); - } - else - { - luaD_checkstack(L, 3); - StkId func = L->top; - L->top += 3; - luaD_call(L, func, 1); - } + L->top += 3; + callTMluau(L, top, clvalue(top), 1); } else { - LUAU_ASSERT((L->top + 3) < (L->stack + L->stacksize)); - setobj2s(L, L->top, f); // push function - setobj2s(L, L->top + 1, p1); // 1st argument - setobj2s(L, L->top + 2, p2); // 2nd argument luaD_checkstack(L, 3); + StkId func = L->top; L->top += 3; - luaD_call(L, L->top - 3, 1); + luaD_call(L, func, 1); } res = restorestack(L, result); @@ -157,39 +142,25 @@ static LUAU_NOINLINE void callTM(lua_State* L, const TValue* f, const TValue* p1 // * we cannot use savestack/restorestack because the arguments are sometimes on the C++ stack // * during stack reallocation all of the allocated stack is copied (even beyond stack_last) so these // values will be preserved even if they go past stack_last - if (FFlag::LuauCallLuauTm) + StkId top = L->top; + LUAU_ASSERT((top + 4) < (L->stack + L->stacksize)); + setobj2s(L, top, f); // push function + setobj2s(L, top + 1, p1); // 1st argument + setobj2s(L, top + 2, p2); // 2nd argument + setobj2s(L, top + 3, p3); // 3th argument + + // fast-path for Luau to Luau calls + if (L->isactive && isLua(L->ci) && ttisfunction(top) && !clvalue(top)->isC) { - StkId top = L->top; - LUAU_ASSERT((top + 4) < (L->stack + L->stacksize)); - setobj2s(L, top, f); // push function - setobj2s(L, top + 1, p1); // 1st argument - setobj2s(L, top + 2, p2); // 2nd argument - setobj2s(L, top + 3, p3); // 3th argument - - // fast-path for Luau to Luau calls - if (L->isactive && isLua(L->ci) && ttisfunction(top) && !clvalue(top)->isC) - { - L->top += 4; - callTMluau(L, top, clvalue(top), 0); - } - else - { - luaD_checkstack(L, 4); - StkId func = L->top; - L->top += 4; - luaD_call(L, func, 0); - } + L->top += 4; + callTMluau(L, top, clvalue(top), 0); } else { - LUAU_ASSERT((L->top + 4) < (L->stack + L->stacksize)); - setobj2s(L, L->top, f); // push function - setobj2s(L, L->top + 1, p1); // 1st argument - setobj2s(L, L->top + 2, p2); // 2nd argument - setobj2s(L, L->top + 3, p3); // 3th argument luaD_checkstack(L, 4); + StkId func = L->top; L->top += 4; - luaD_call(L, L->top - 4, 0); + luaD_call(L, func, 0); } } @@ -208,28 +179,16 @@ void luaV_gettable(lua_State* L, const TValue* t, TValue* key, StkId val) if (res != luaO_nilobject) L->cachedslot = gval2slot(h, res); // remember slot to accelerate future lookups - if (FFlag::LuauFrozenMetaButterfly) + if (LUAU_LIKELY(!ttisnil(res))) { - if (LUAU_LIKELY(!ttisnil(res))) - { - setobj2s(L, val, res); - return; - } - - if ((tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) - { - setnilvalue(val); - return; - } + setobj2s(L, val, res); + return; } - else + + if ((tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { - if (!ttisnil(res) // result is no nil? - || (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) - { // or no TM? - setobj2s(L, val, res); - return; - } + setnilvalue(val); + return; } // t isn't a table, so see if it has an INDEX meta-method to look up the key with @@ -259,7 +218,7 @@ void luaV_gettable(lua_State* L, const TValue* t, TValue* key, StkId val) luaG_missingmembererror(L, t, key); const uint32_t offset = uint32_t(nvalue(res)); - LUAU_ASSERT(offset < lco->numberofallmembers); + LUAU_ASSERT(offset < lco->numberofmembers); // This is the case where we try to access an instance member on a // class object, for example: @@ -327,7 +286,7 @@ void luaV_settable(lua_State* L, const TValue* t, TValue* key, StkId val) if (ttisnil(offset)) luaG_missingmembererror(L, t, key); const uint32_t offsetnum = uint32_t(nvalue(offset)); - LUAU_ASSERT(offsetnum < inst->lclass->numberofallmembers); + LUAU_ASSERT(offsetnum < inst->lclass->numberofmembers); if (offsetnum >= inst->lclass->numberofinstancemembers) luaG_indexerror(L, t, key); setobj2class(L, &inst->members[offsetnum], val); diff --git a/bench/bench.py b/bench/bench.py index 63f4da0d8..4ae9948fe 100644 --- a/bench/bench.py +++ b/bench/bench.py @@ -1,4 +1,5 @@ -#!/usr/bin/python3 +#!/usr/bin/env python3 +# PYTHON_ARGCOMPLETE_OK # This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details import argparse import os @@ -30,6 +31,12 @@ scriptdir = os.path.dirname(os.path.realpath(__file__)) defaultVm = 'luau.exe' if os.name == "nt" else './luau' +METRIC_LABELS = { + 'time': ('Time', 'ms'), + 'cycles': ('Cycles', 'Mcyc'), + 'instructions': ('Instructions', 'Minstr'), +} + argumentParser = argparse.ArgumentParser(description='Benchmark Lua script execution with an option to compare different VMs') argumentParser.add_argument('--vm', dest='vm',default=defaultVm,help='Lua executable to test (' + defaultVm + ' by default)') @@ -41,6 +48,7 @@ argumentParser.add_argument('--filename', action='store',type=str,default='bench', help='File name for graph and results file') argumentParser.add_argument('--callgrind', dest='callgrind',action='store_const',const=1,default=0,help='Use callgrind to run benchmarks') argumentParser.add_argument('--show-commands', dest='show_commands',action='store_const',const=1,default=0,help='Show the command line used to launch the VM and tests') +argumentParser.add_argument('--metric', dest='metric', choices=list(METRIC_LABELS), default=None, help="Metric to benchmark, 'cycles' and 'instructions' are only supported on macOS") if matplotlib != None: argumentParser.add_argument('--absolute', dest='absolute',action='store_const',const=1,default=0,help='Display absolute values instead of relative (enabled by default when benchmarking a single VM)') @@ -59,6 +67,28 @@ # Assume 2.5 IPC on a 4 GHz CPU; this is obviously incorrect but it allows us to display simulated instruction counts using regular time units CALLGRIND_INSN_PER_SEC = 2.5 * 4e9 +# Counter names as printed by macOS `/usr/bin/time -l` +COUNTER_METRICS = { + 'cycles': 'cycles elapsed', + 'instructions': 'instructions retired', +} + +# Increase runs for short benchmarks to reduce the relative impact of startup/setup noise, capped to limit the run count +COUNTER_TARGET_MS = 500 +COUNTER_MIN_RUNS = 20 +COUNTER_MAX_RUNS = 100000 + +valueMetric = 'time' + +def setMetric(metric): + global valueMetric + if metric not in METRIC_LABELS: + sys.exit('Unknown benchmark metric: ' + str(metric)) + valueMetric = metric + +def formatValue(value): + return '{:8.3f}'.format(value) + METRIC_LABELS[valueMetric][1] + def arrayRange(count): result = [] @@ -162,6 +192,90 @@ def getVmOutput(cmd): return p.communicate()[0] +def getLuauCliCounterArgs(vm, filepath, programArgs): + """Default counterArgsCallback for the Luau CLI. + + Program args are only visible to top-level scripts, so bench_support.lua runs first and forwards them to the + module instance that the test file requires.""" + return "{} {} -a {}".format(os.path.join(scriptdir, "bench_support.lua"), filepath, programArgs) + +def launchWithCounter(cmd): + """Run cmd under `/usr/bin/time -l`. + + Returns (stdout, counter value) or None if the launch failed or the counter was not reported.""" + fullCmd = "/usr/bin/time -l " + cmd + conditionallyShowCommand(fullCmd) + + p = subprocess.run(fullCmd, shell=True, capture_output=True, text=True, cwd=scriptdir) + + match = re.search(r"^\s*(\d+)\s+" + COUNTER_METRICS[valueMetric] + r"\s*$", p.stderr, re.MULTILINE) + if p.returncode != 0 or match is None: + return None + + return p.stdout, int(match.group(1)) + +# Keyed by (test file, benchmark index) so every VM uses the same run count for a benchmark +counterRunsCache = {} + +def getCounterRuns(filepath, index, lowOutput): + """Returns the run count for a benchmark, scaled from the time of the single run in its low launch.""" + key = (filepath, index) + if key not in counterRunsCache: + runs = COUNTER_MIN_RUNS + try: + runMs = float(lowOutput.split("||_||")[index].split("|><|")[2]) + if runMs > 0: + runs = max(runs, min(COUNTER_MAX_RUNS, math.ceil(COUNTER_TARGET_MS / runMs))) + except (IndexError, ValueError): + pass + counterRunsCache[key] = runs + + return counterRunsCache[key] + +def getCounterOutput(vm, cmd, filepath): + """Measures with process-wide CPU counters instead of the timings reported by bench_support.lua. + + Counters cover the whole process, including startup and test setup. That fixed cost is removed by launching + each benchmark twice, with 1 and 1 + N runs, and dividing the difference by N (see getCounterRuns). Files with + several benchmarks launch once per benchmark, selected by index (see bench_support.lua). + + Returns output in the same format as bench_support.lua, with one value per benchmark in millions of counter + events per run; runTest merges additional samples from --extra-loops.""" + def launch(only, runs): + programArgs = "LUAU_BENCH_ONLY={} LUAU_BENCH_RUNS={}".format(only, runs) + return launchWithCounter(cmd + " " + counterArgsCallback(vm, filepath, programArgs)) + + # Selecting benchmark 0 skips every benchmark, which lists their names and warms the disk cache; a cold launch of a + # large VM can cost hundreds of millions of extra cycles and would skew the first sample. + warmup = launch(0, 0) + if warmup is None: + return "" + + entries = [el.split("|><|") for el in warmup[0].split("||_||")[:-1]] + if any(len(el) > 2 for el in entries): + sys.exit("--metric {} requires a VM that passes LUAU_BENCH_ONLY and LUAU_BENCH_RUNS program args to bench_support.lua: {}".format(valueMetric, cmd)) + + names = [el[1] for el in entries] + + output = "" + for index, name in enumerate(names): + low = launch(index + 1, 1) + if low is None: + return "" + + runs = getCounterRuns(filepath, index, low[0]) + high = launch(index + 1, 1 + runs) + if high is None: + return "" + + value = (high[1] - low[1]) / runs / 1e6 + if value <= 0: + print("{}: '{}' measured no work above per-launch noise with {} runs".format(colored(Color.YELLOW, 'WARNING'), name, runs)) + return "" + + output += "|><|" + name + "|><|" + str(value) + "||_||" + return output + def getShortVmName(name): # Hope that the path to executable doesn't contain spaces argumentPos = name.find(" ") @@ -365,8 +479,8 @@ def analyzeResult(subdir, main, comparisons): if arguments.vmNext != None: resultPrinter.add_row({ 'Test': main.name, - 'Min': '{:8.3f}ms'.format(main.min), - 'Average': '{:8.3f}ms'.format(main.avg), + 'Min': formatValue(main.min), + 'Average': formatValue(main.avg), 'StdDev%': '{:8.3f}%'.format(main.sampleConfidenceInterval / main.avg * 100), 'Driver': main.shortVm, 'Speedup': "", @@ -376,8 +490,8 @@ def analyzeResult(subdir, main, comparisons): else: resultPrinter.add_row({ 'Test': main.name, - 'Min': '{:8.3f}ms'.format(main.min), - 'Average': '{:8.3f}ms'.format(main.avg), + 'Min': formatValue(main.min), + 'Average': formatValue(main.avg), 'StdDev%': '{:8.3f}%'.format(main.sampleConfidenceInterval / main.avg * 100), 'Driver': main.shortVm }) @@ -385,7 +499,7 @@ def analyzeResult(subdir, main, comparisons): if reporter != None: reporter.report_result(subdir, main.name, main.filename, "SUCCESS", main.min, main.avg, main.max, main.sampleConfidenceInterval, main.shortVm, main.vm) - print(colored(Color.GREEN, 'SUCCESS') + ': {:<40}'.format(main.name) + ": " + '{:8.3f}'.format(main.avg) + "ms +/- " + + print(colored(Color.GREEN, 'SUCCESS') + ': {:<40}'.format(main.name) + ": " + formatValue(main.avg) + " +/- " + '{:6.3f}'.format(main.sampleConfidenceInterval / main.avg * 100) + "% on " + main.shortVm) plotLabels.append(main.name) @@ -473,8 +587,8 @@ def analyzeResult(subdir, main, comparisons): resultPrinter.add_row({ 'Test': main.name, - 'Min': '{:8.3f}ms'.format(compare.min), - 'Average': '{:8.3f}ms'.format(compare.avg), + 'Min': formatValue(compare.min), + 'Average': formatValue(compare.avg), 'StdDev%': '{:8.3f}%'.format(compare.sampleConfidenceInterval / compare.avg * 100), 'Driver': compare.shortVm, 'Speedup': colored(speedupColor, '{:8.3f}%'.format(speedup * 100)), @@ -482,7 +596,7 @@ def analyzeResult(subdir, main, comparisons): 'P(T<=t)': '---' if pValue < 0 else '{:.0f}%'.format(pValue * 100) }) - print(colored(Color.GREEN, 'SUCCESS') + ': {:<40}'.format(main.name) + ": " + '{:8.3f}'.format(compare.avg) + "ms +/- " + + print(colored(Color.GREEN, 'SUCCESS') + ': {:<40}'.format(main.name) + ": " + formatValue(compare.avg) + " +/- " + '{:6.3f}'.format(compare.sampleConfidenceInterval / compare.avg * 100) + "% on " + compare.shortVm + ' ({:+7.3f}%, '.format(speedup * 100) + verdict + ")") @@ -506,13 +620,21 @@ def analyzeResult(subdir, main, comparisons): vmTotalImprovement[index] += math.log(main.avg / compare.avg) vmTotalResults[index] += 1 +def getTestOutput(vm, filepath): + cmd = substituteArguments(vm, getExtraArguments(filepath)) + + if valueMetric != 'time': + return getCounterOutput(vm, cmd, filepath) + + return getVmOutput(cmd + " " + filepath) + def runTest(subdir, filename, filepath): filepath = os.path.abspath(filepath) mainVm = os.path.abspath(arguments.vm) # Process output will contain the test name and execution times - mainOutput = getVmOutput(substituteArguments(mainVm, getExtraArguments(filepath)) + " " + filepath) + mainOutput = getTestOutput(mainVm, filepath) mainResultSet = extractResults(filename, mainVm, mainOutput, False) if len(mainResultSet) == 0: @@ -533,7 +655,7 @@ def runTest(subdir, filename, filepath): for compareVm in arguments.vmNext: compareVm = os.path.abspath(compareVm) - compareOutput = getVmOutput(substituteArguments(compareVm, getExtraArguments(filepath)) + " " + filepath) + compareOutput = getTestOutput(compareVm, filepath) compareResultSet = extractResults(filename, compareVm, compareOutput, True) compareResultSets.append(compareResultSet) @@ -541,7 +663,7 @@ def runTest(subdir, filename, filepath): if arguments.extra_loops > 0: # get more results for i in range(arguments.extra_loops): - extraMainOutput = getVmOutput(substituteArguments(mainVm, getExtraArguments(filepath)) + " " + filepath) + extraMainOutput = getTestOutput(mainVm, filepath) extraMainResultSet = extractResults(filename, mainVm, extraMainOutput, False) mergeResults(mainResultSet, extraMainResultSet) @@ -551,7 +673,7 @@ def runTest(subdir, filename, filepath): for compareVm in arguments.vmNext: compareVm = os.path.abspath(compareVm) - extraCompareOutput = getVmOutput(substituteArguments(compareVm, getExtraArguments(filepath)) + " " + filepath) + extraCompareOutput = getTestOutput(compareVm, filepath) extraCompareResultSet = extractResults(filename, compareVm, extraCompareOutput, True) mergeResults(compareResultSets[i], extraCompareResultSet) @@ -637,6 +759,13 @@ def graph(): ind = arrayRange(len(plotLabels)) width = 0.8 / len(plotValueLists) + valueLabel, valueUnit = METRIC_LABELS[valueMetric] + if arguments.absolute: + axisLabel = valueLabel + ' (' + valueUnit + ')' + elif arguments.speedup: + axisLabel = 'Speedup (%)' + else: + axisLabel = 'Relative ' + valueLabel.lower() + ' (%)' if arguments.graph_vertical: # Extend graph width when we have a lot of tests to draw @@ -661,12 +790,7 @@ def graph(): bar = plt.bar(arrayRangeOffset(len(plotLabels), i * width), plotValueLists[i], width, yerr=plotConfIntLists[i]) plotBars.append(bar[0]) - if arguments.absolute: - plt.ylabel('Time (ms)') - elif arguments.speedup: - plt.ylabel('Speedup (%)') - else: - plt.ylabel('Relative time (%)') + plt.ylabel(axisLabel) plt.title('Benchmark') plt.xticks(ind, plotLabels, rotation='vertical') @@ -679,12 +803,7 @@ def graph(): bar = plt.barh(arrayRangeOffset(len(plotLabels), i * width), plotValueLists[i], width, xerr=plotConfIntLists[i]) plotBars.append(bar[0]) - if arguments.absolute: - plt.xlabel('Time (ms)') - elif arguments.speedup: - plt.xlabel('Speedup (%)') - else: - plt.xlabel('Relative time (%)') + plt.xlabel(axisLabel) plt.title('Benchmark') plt.yticks(ind, plotLabels) @@ -756,8 +875,8 @@ def addTotalsToTable(): resultPrinter.add_row({ 'Test': 'Total', - 'Min': '{:8.3f}ms'.format(vmTotalMin[index]), - 'Average': '{:8.3f}ms'.format(vmTotalAverage[index]), + 'Min': formatValue(vmTotalMin[index]), + 'Average': formatValue(vmTotalAverage[index]), 'StdDev%': "---", 'Driver': getShortVmName(os.path.abspath(arguments.vm)), 'Speedup': "", @@ -772,8 +891,8 @@ def addTotalsToTable(): resultPrinter.add_row({ 'Test': 'Total', - 'Min': '{:8.3f}ms'.format(vmTotalMin[index]), - 'Average': '{:8.3f}ms'.format(vmTotalAverage[index]), + 'Min': formatValue(vmTotalMin[index]), + 'Average': formatValue(vmTotalAverage[index]), 'StdDev%': "---", 'Driver': getShortVmName(os.path.abspath(compareVm)), 'Speedup': colored(Color.RED if speedup < 0 else Color.GREEN if speedup > 0 else Color.YELLOW, '{:8.3f}%'.format(speedup)), @@ -783,8 +902,8 @@ def addTotalsToTable(): else: resultPrinter.add_row({ 'Test': 'Total', - 'Min': '{:8.3f}ms'.format(vmTotalMin[0]), - 'Average': '{:8.3f}ms'.format(vmTotalAverage[0]), + 'Min': formatValue(vmTotalMin[0]), + 'Average': formatValue(vmTotalAverage[0]), 'StdDev%': "---", 'Driver': getShortVmName(os.path.abspath(arguments.vm)) }) @@ -819,8 +938,8 @@ def addGeomeanToTable(): if arguments.vmNext != None: resultPrinter.add_row({ 'Test': 'Geomean', - 'Min': '{:8.3f}ms'.format(mainGeomean.min), - 'Average': '{:8.3f}ms'.format(mainGeomean.avg), + 'Min': formatValue(mainGeomean.min), + 'Average': formatValue(mainGeomean.avg), 'StdDev%': '{:8.3f}%'.format(mainGeomean.sampleConfidenceInterval / mainGeomean.avg * 100), 'Driver': mainGeomean.shortVm, 'Speedup': "", @@ -839,8 +958,8 @@ def addGeomeanToTable(): resultPrinter.add_row({ 'Test': 'Geomean', - 'Min': '{:8.3f}ms'.format(compareGeomean.min), - 'Average': '{:8.3f}ms'.format(compareGeomean.avg), + 'Min': formatValue(compareGeomean.min), + 'Average': formatValue(compareGeomean.avg), 'StdDev%': '{:8.3f}%'.format(compareGeomean.sampleConfidenceInterval / compareGeomean.avg * 100), 'Driver': compareGeomean.shortVm, 'Speedup': colored(Color.RED if speedup < 0 else Color.GREEN if speedup > 0 else Color.YELLOW, '{:8.3f}%'.format(speedup)), @@ -850,8 +969,8 @@ def addGeomeanToTable(): else: resultPrinter.add_row({ 'Test': 'Geomean', - 'Min': '{:8.3f}ms'.format(mainGeomean.min), - 'Average': '{:8.3f}ms'.format(mainGeomean.avg), + 'Min': formatValue(mainGeomean.min), + 'Average': formatValue(mainGeomean.avg), 'StdDev%': '{:8.3f}%'.format(mainGeomean.sampleConfidenceInterval / mainGeomean.avg * 100), 'Driver': mainGeomean.shortVm }) @@ -864,26 +983,30 @@ def default(self, obj): return json.JSONEncoder.default(self, obj) try: - with open(arguments.filename + ".json", "w") as allResultsFile: - allResultsFile.write(json.dumps(allResults, cls=TestResultEncoder)) + with open(arguments.filename + ".json", "w", encoding="utf-8") as allResultsFile: + allResultsFile.write(json.dumps({'metric': valueMetric, 'results': allResults}, cls=TestResultEncoder)) except: print("Failed to write results to a file") -def run(args, argsubcb, reporter_factory=None): - global arguments, resultPrinter, reporter, argumentSubstituionCallback, allResults +def run(args, argsubcb, reporter_factory=None, counterargscb=getLuauCliCounterArgs): + """counterargscb(vm, filepath, programArgs) returns the command line tail that runs filepath and passes programArgs + (LUAU_BENCH_ONLY= LUAU_BENCH_RUNS=) to bench_support.lua when measuring with CPU counters.""" + global arguments, resultPrinter, reporter, argumentSubstituionCallback, counterArgsCallback, allResults arguments = args argumentSubstituionCallback = argsubcb + counterArgsCallback = counterargscb + expectedMetric = arguments.metric + setMetric(expectedMetric or 'time') if os.name == "nt" and arguments.callgrind: print(f"{colored(Color.RED, 'ERROR')}: --callgrind is not supported on Windows. Please consider using this option on another OS, or Linux using WSL.") sys.exit(1) - if reporter_factory: - reporter = reporter_factory(arguments) - elif arguments.report_metrics or arguments.print_influx_debugging: - reporter = influxbench.InfluxReporter(arguments) - else: - reporter = None + if arguments.results is None and valueMetric != 'time': + if sys.platform != "darwin": + sys.exit("--metric {} is only supported on macOS".format(valueMetric)) + if arguments.callgrind: + sys.exit("--metric {} can't be combined with --callgrind".format(valueMetric)) if matplotlib == None: arguments.absolute = 0 @@ -896,8 +1019,16 @@ def run(args, argsubcb, reporter_factory=None): vmList = [] for result in arguments.results: - with open(result) as resultsFile: - resultArray = json.load(resultsFile) + with open(result, encoding="utf-8") as resultsFile: + resultData = json.load(resultsFile) + + # Legacy result arrays contain timings in milliseconds. + resultMetric = resultData['metric'] if isinstance(resultData, dict) else 'time' + resultArray = resultData['results'] if isinstance(resultData, dict) else resultData + if expectedMetric is not None and resultMetric != expectedMetric: + sys.exit("{}: metric '{}' does not match '{}'".format(result, resultMetric, expectedMetric)) + setMetric(resultMetric) + expectedMetric = resultMetric for test in resultArray: for i in range(len(test)): @@ -958,6 +1089,15 @@ def run(args, argsubcb, reporter_factory=None): else: arguments.vmNext.append(vmList[i]) + if valueMetric != 'time' and (reporter_factory or arguments.report_metrics or arguments.print_influx_debugging): + sys.exit('Counter results cannot be sent to time-based metric reporters') + if reporter_factory: + reporter = reporter_factory(arguments) + elif arguments.report_metrics or arguments.print_influx_debugging: + reporter = influxbench.InfluxReporter(arguments) + else: + reporter = None + plotLegend.append(getShortVmName(arguments.vm)) if arguments.vmNext != None: @@ -1055,5 +1195,11 @@ def run(args, argsubcb, reporter_factory=None): if __name__ == "__main__": + try: + import argcomplete + argcomplete.autocomplete(argumentParser) + except ImportError: + pass + arguments = argumentParser.parse_args() run(arguments, None) diff --git a/bench/bench_support.lua b/bench/bench_support.lua index b731c2fc0..72e19d0fa 100644 --- a/bench/bench_support.lua +++ b/bench/bench_support.lua @@ -4,7 +4,43 @@ local bench = {} bench.runs = 20 bench.extraRuns = 4 +-- bench.py passes LUAU_BENCH_ONLY= and LUAU_BENCH_RUNS= when measuring with external process-wide CPU counters. +-- Hosts that share _G across scripts can set them as globals; the Luau CLI passes them as program args, which only +-- top-level scripts receive (see the end of this file). +local function parseNamedArgs(args) + local named = {} + for _, arg in ipairs(args) do + local name, value = string.match(arg, "^([%w_]+)=(.*)$") + if name then + named[name] = value + end + end + return named +end + +-- 1-based index of the only runCode call to execute, so that files with several benchmarks can be measured one at a +-- time; other calls just print their description, and 0 executes none +local counterOnly = tonumber(_G.LUAU_BENCH_ONLY) + +-- Exact run count for each runCode call, with no extra runs, so that counter totals cover a known number of runs +local counterRuns = tonumber(_G.LUAU_BENCH_RUNS) + +local runCodeCount = 0 + +function bench.setCounterOptions(args) + local named = parseNamedArgs(args) + counterOnly = tonumber(named.LUAU_BENCH_ONLY) + counterRuns = tonumber(named.LUAU_BENCH_RUNS) +end + function bench.runCode(f, description) + runCodeCount = runCodeCount + 1 + + if counterOnly and counterOnly ~= runCodeCount then + print("|><|"..description.."||_||") + return + end + -- Under Callgrind, run the test only once and measure just the execution cost if callgrind and callgrind("running") then if collectgarbage then collectgarbage() end @@ -16,8 +52,10 @@ function bench.runCode(f, description) end local timeTable = {} + local runs = counterRuns or bench.runs + local extraRuns = counterRuns and 0 or bench.extraRuns - for i = 1,bench.runs + bench.extraRuns do + for i = 1,runs + extraRuns do -- try to run GC if it's available if collectgarbage then pcall(function() @@ -41,7 +79,7 @@ function bench.runCode(f, description) table.sort(timeTable) - for i = 1,bench.extraRuns do + for i = 1,extraRuns do table.remove(timeTable, #timeTable) end @@ -100,4 +138,12 @@ function bench.runScriptCodeUnderActor(scriptInstance, f, description) end end +-- Under the Luau CLI, bench.py runs this file as a top-level script before the test file, since only top-level scripts +-- receive program args. `bench` here is then a separate instance from the one the test file requires, so the args are +-- forwarded to that cached module instance. +local programArgs = { ... } +if parseNamedArgs(programArgs).LUAU_BENCH_ONLY then + require("./bench_support").setCounterOptions(programArgs) +end + return bench diff --git a/bench/tests/vibemark67/qoi.luau b/bench/tests/vibemark67/qoi.luau index 6206ea250..ea8f3f81e 100644 --- a/bench/tests/vibemark67/qoi.luau +++ b/bench/tests/vibemark67/qoi.luau @@ -333,8 +333,6 @@ assert(decodedChannels == 4 and decodedColorspace == 0) assertEqualPixels(source, decoded) assertAllOpcodes(encoded, encodedSize) -local sink = 0 - local function preallocatedRoundTrips() local checksum = 0 @@ -344,7 +342,7 @@ local function preallocatedRoundTrips() checksum += size + width + height + buffer.readu32(decoded, PIXEL_BYTES - 4) end - sink = checksum + assert(checksum ~= 0) end local function allocatingRoundTrips() @@ -360,10 +358,8 @@ local function allocatingRoundTrips() checksum += size + width + height + buffer.readu32(iterationDecoded, PIXEL_BYTES - 4) end - sink = checksum + assert(checksum ~= 0) end bench.runCode(preallocatedRoundTrips, "qoi-preallocated") bench.runCode(allocatingRoundTrips, "qoi-allocate") - -assert(sink ~= 0) diff --git a/tests/AstQuery.test.cpp b/tests/AstQuery.test.cpp index 5f355fd65..4dea790f8 100644 --- a/tests/AstQuery.test.cpp +++ b/tests/AstQuery.test.cpp @@ -409,8 +409,6 @@ TEST_CASE_FIXTURE(Fixture, "interior_binding_location_is_consistent_with_exterio abcd(0) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); std::optional declBinding = findBindingAtPosition(*getMainModule(), *getMainSourceModule(), {1, 26}); diff --git a/tests/Autocomplete.test.cpp b/tests/Autocomplete.test.cpp index 0dc8532b1..b16fa39a7 100644 --- a/tests/Autocomplete.test.cpp +++ b/tests/Autocomplete.test.cpp @@ -2148,7 +2148,6 @@ return {a = a, b = b} )"; CheckResult result = getFrontend().check("Module/A"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); fileResolver.source["Module/B"] = R"( @@ -2184,7 +2183,6 @@ return {a = a, b = b} )"; CheckResult result = getFrontend().check("Module/A"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); fileResolver.source["Module/B"] = R"( diff --git a/tests/BytecodeCallInliner.test.cpp b/tests/BytecodeCallInliner.test.cpp index b72da0401..37f801caf 100644 --- a/tests/BytecodeCallInliner.test.cpp +++ b/tests/BytecodeCallInliner.test.cpp @@ -2091,6 +2091,134 @@ RETURN R1 1 )"); } +TEST_CASE_FIXTURE(BytecodeInlinerFixture, "slot_allocation_keeps_all_generic_for_results_in_frame") +{ + ScopedFastFlag emitCallFb{FFlag::LuauEmitCallFeedback, true}; + + std::optional> result = compileAndInline(R"( + local function inlinee(values) + for first, second, third in values do + return first, second, third + end + end + + local function caller(x) + local first, second, third = inlinee(x) + return first or second or third + end + )"); + REQUIRE(result); + + CompTimeBcFunction& caller = result->second; + REQUIRE(allocateSlots(caller)); + + // The inlined loop starts at R3 and FORGLOOP writes its third result to R8. + CHECK_GE(caller.maxstacksize, 9); +} + +TEST_CASE_FIXTURE(BytecodeInlinerFixture, "slot_allocation_keeps_unread_call_results_in_frame") +{ + ScopedFastFlag emitCallFb{FFlag::LuauEmitCallFeedback, true}; + + // most results are never read, so inlining materializes no projection for them, yet CALL still writes all five + std::optional> result = compileAndInline(R"( + local function inlinee(a) + local p, q, r, s, t = os.clock() + end + + local function caller(x) + inlinee(x) + end + )"); + REQUIRE(result); + + CompTimeBcFunction& caller = result->second; + REQUIRE(allocateSlots(caller)); + // important that this is maxstacksize = 8 + // if we don't keep the unused projections in mind, maxstacksize becomes 4 + CHECK_EQ( + "\n" + toString(caller, true), + R"( +; function caller($arg0) line 6 maxstacksize: 8 upvalues: 1 flags: 0 +; feedback slot 0: CALLTARGET %2 +; feedback slot 1: CALLTARGET %7 +bb_0 (entry): +; successors: bb_4 [fallthrough], bb_2 [branch] + %0 = GETUPVAL U0 ; uses: %2, %4 + %1 = MOVE R0 ; uses: %2 + %4 = CMPPROTO %0, 0, bb_2 + +bb_4: +; predecessors: bb_0 [fallthrough] +; successors: bb_3 [fallthrough] + %5 = GETGLOBAL 10, K0 ('os') ; uses: %6 + %6 = GETTABLEKS %5, 140, K1 ('clock') ; uses: %7 + %7 = CALLFB 0, 5, 1, %6 + +bb_2: +; predecessors: bb_0 [branch] +; successors: bb_3 [fallthrough] + %2 = CALLFB 1, 0, -1, %0, %1 + +bb_3: +; predecessors: bb_2 [fallthrough], bb_4 [fallthrough] +; successors: bb_1 [fallthrough] + %3 = RETURN 0, R0 + +bb_1 (exit): +; predecessors: bb_3 [fallthrough] +)" + ); +} + +TEST_CASE_FIXTURE(BytecodeInlinerFixture, "slot_allocation_keeps_newclass_superclass_apart_from_result") +{ + ScopedFastFlag debugLuauUserDefinedClasses{FFlag::DebugLuauUserDefinedClasses, true}; + + std::vector graphs = buildGraphs( + R"( + open class Base + public x + end + local t = {x = Base} + class Derived extends t.x + public y + end + local a, b = Derived.foo, Derived.bar + t.y = a + t.z = b + )", + 1 + ); + + bool sawDerivedClass = false; + for (CompTimeBcFunction& graph : graphs) + { + allocateSlots(graph); + + for (const BcBlock& block : graph.blocks) + { + if (block.flags & BcBlockFlag::Dead) + continue; + + for (BcOp instructionOp : block.ops) + { + const BcInst& instruction = graph.instOp(instructionOp); + if (instruction.op != LOP_NEWCLASS || instruction.ops.empty() || instruction.ops[0].kind == BcOpKind::None) + continue; + + auto result = graph.regs.find(instructionOp); + auto super = graph.regs.find(instruction.ops[0]); + REQUIRE(result != graph.regs.end()); + REQUIRE(super != graph.regs.end()); + CHECK_NE(result->second, super->second); + sawDerivedClass = true; + } + } + } + CHECK(sawDerivedClass); +} + TEST_CASE_FIXTURE(BytecodeInlinerFixture, "slot_allocation_keeps_inlined_namecall_self_in_register") { ScopedFastFlag emitCallFb{FFlag::LuauEmitCallFeedback, true}; diff --git a/tests/BytecodeCompiler.test.cpp b/tests/BytecodeCompiler.test.cpp index 9c2256b46..6ece1e472 100644 --- a/tests/BytecodeCompiler.test.cpp +++ b/tests/BytecodeCompiler.test.cpp @@ -924,7 +924,6 @@ TEST_CASE_FIXTURE(BytecodeCompilerFixture, "bytecode_roundtrip") TEST_CASE_FIXTURE(BytecodeCompilerFixture, "classes_bytecode_roundtrips") { - ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; checkRoundtrip(R"( @@ -1014,7 +1013,7 @@ K3: '__tostring' K4: function live K5: 'live' K6: '__init' -K7: class Animal (props: 1, methods: 3) +K7: class Animal (public fields: 1, public methods: 3, private fields: 0, private methods: 0) props: K1 ['species'] methods: @@ -1024,7 +1023,7 @@ K7: class Animal (props: 1, methods: 3) K8: 'Cat' K9: 'breed' K10: function __tostring -K11: class Cat (props: 1, methods: 2) +K11: class Cat (public fields: 1, public methods: 2, private fields: 0, private methods: 0) props: K9 ['breed'] methods: @@ -1033,15 +1032,15 @@ K11: class Cat (props: 1, methods: 2) K12: 'print' K13: print K14: {['Animal'] #1, ['Cat'] #0} sizenode=2 -NEWCLASS R0 no_base K7 1 [class Animal (props: 1, methods: 3)] +NEWCLASS R0 no_base K7 1 [class Animal (public fields: 1, public methods: 3, private fields: 0, private methods: 0)] DUPCLOSURE R1 K2 ['__tostring'] -NEWCLASSMEMBER R0 R1 ['__tostring'] +NEWCLASSMEMBER R0 R1 [public] ['__tostring'] DUPCLOSURE R1 K4 ['live'] -NEWCLASSMEMBER R0 R1 ['live'] -NEWCLASS R1 R0 K11 0 [class Cat (props: 1, methods: 2)] +NEWCLASSMEMBER R0 R1 [public] ['live'] +NEWCLASS R1 R0 K11 0 [class Cat (public fields: 1, public methods: 2, private fields: 0, private methods: 0)] DUPCLOSURE R2 K10 ['__tostring'] CAPTURE VAL R0 -NEWCLASSMEMBER R1 R2 ['__tostring'] +NEWCLASSMEMBER R1 R2 [public] ['__tostring'] GETIMPORT R2 13 [print] MOVE R3 R1 CALL R2 1 0 @@ -1052,6 +1051,74 @@ RETURN R2 1 )"); } +TEST_CASE_FIXTURE(BytecodeCompilerFixture, "private_class_fields_bytecode_roundtrips") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string_view source = R"( +class Counter + public label: string + private _count: number + private _step: number + + private function _peek(self) + return self._count + end + + function __init(self, label) + self.label = label + self._count = 0 + self._step = 1 + end + + function bump(self) + self._count += self._step + end + + function reset(self) + self._count, self._step = 0, 1 + end + + function copyFrom(self, other) + other._count = self._count + end + + function report(self) + local peek = self._peek + return self.label, peek(self), self._count + end +end + +return { Counter = Counter } + )"; + + checkRoundtrip(source); + + source = R"( +class PrivateCallback + private _cb + public str: string + + function __init(self, str, prefix) + self._cb = function(self, suffix) + return prefix .. self.str .. suffix + end + self.str = str + end + + function rebind(self, cb) + self._cb = cb + end + + function invoke(self, suffix) + return self:_cb(suffix) + end +end +)"; + + checkRoundtrip(source); +} + TEST_CASE_FIXTURE(BytecodeCompilerFixture, "fastpcall_roundtrip") { ScopedFastFlag luauCompileFastpcall{FFlag::LuauCompileFastpcall, true}; diff --git a/tests/Compiler.test.cpp b/tests/Compiler.test.cpp index 036990c61..fb32b2319 100644 --- a/tests/Compiler.test.cpp +++ b/tests/Compiler.test.cpp @@ -27,7 +27,6 @@ LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauCompileTableFoldFix) LUAU_FASTFLAG(LuauIntegerFastcalls) LUAU_FASTFLAG(LuauIntegerBufferFastcalls) -LUAU_FASTFLAG(LuauCompileEmitVectorDouble) LUAU_FASTFLAG(LuauCompileMoveElision) LUAU_FASTFLAG(LuauCompileNoDebugConst) LUAU_FASTFLAG(LuauCompileMoveElisionFix) @@ -994,7 +993,7 @@ K1: 'species' K2: function live K3: 'live' K4: '__init' -K5: class Animal (props: 1, methods: 2) +K5: class Animal (public fields: 1, public methods: 2, private fields: 0, private methods: 0) props: K1 ['species'] methods: @@ -1004,7 +1003,7 @@ K6: 'Cat' K7: 'breed' K8: function describe K9: 'describe' -K10: class Cat (props: 1, methods: 2) +K10: class Cat (public fields: 1, public methods: 2, private fields: 0, private methods: 0) props: K7 ['breed'] methods: @@ -1012,12 +1011,12 @@ K10: class Cat (props: 1, methods: 2) K4 ['__init'] K11: 'print' K12: print -NEWCLASS R0 no_base K5 1 [class Animal (props: 1, methods: 2)] +NEWCLASS R0 no_base K5 1 [class Animal (public fields: 1, public methods: 2, private fields: 0, private methods: 0)] DUPCLOSURE R1 K2 ['live'] -NEWCLASSMEMBER R0 R1 ['live'] -NEWCLASS R1 R0 K10 0 [class Cat (props: 1, methods: 2)] +NEWCLASSMEMBER R0 R1 [public] ['live'] +NEWCLASS R1 R0 K10 0 [class Cat (public fields: 1, public methods: 2, private fields: 0, private methods: 0)] DUPCLOSURE R2 K8 ['describe'] -NEWCLASSMEMBER R1 R2 ['describe'] +NEWCLASSMEMBER R1 R2 [public] ['describe'] GETIMPORT R2 12 [print] MOVE R3 R1 CALL R2 1 0 @@ -12276,7 +12275,7 @@ TEST_CASE("ClassDeclBasic") )"; auto res0 = "\n" + compileFunction(source.c_str(), 0, 0, 0); CHECK(R"( -NEWCLASS R0 no_base K4 0 [class Point (props: 2, methods: 1)] +NEWCLASS R0 no_base K4 0 [class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0)] GETGLOBAL R1 K5 ['print'] MOVE R2 R0 CALL R1 1 0 @@ -12311,9 +12310,9 @@ RETURN R1 1 )" == res0); auto res1 = "\n" + compileFunction(source.c_str(), 1, 0, 0); CHECK(R"( -NEWCLASS R0 no_base K5 0 [class Point (props: 2, methods: 2)] +NEWCLASS R0 no_base K5 0 [class Point (public fields: 2, public methods: 2, private fields: 0, private methods: 0)] NEWCLOSURE R1 P0 -NEWCLASSMEMBER R0 R1 ['magnitude'] +NEWCLASSMEMBER R0 R1 [public] ['magnitude'] GETGLOBAL R1 K6 ['print'] MOVE R2 R0 CALL R1 1 0 @@ -12351,9 +12350,9 @@ RETURN R0 0 )" == res0); auto res1 = "\n" + compileFunction(source.c_str(), 1, 0, 0); CHECK(res1 == R"( -NEWCLASS R0 no_base K5 0 [class Point (props: 2, methods: 2)] +NEWCLASS R0 no_base K5 0 [class Point (public fields: 2, public methods: 2, private fields: 0, private methods: 0)] NEWCLOSURE R1 P0 -NEWCLASSMEMBER R0 R1 ['print'] +NEWCLASSMEMBER R0 R1 [public] ['print'] DUPTABLE R1 6 LOADK R2 K0 ['Point'] SETTABLE R0 R1 R2 @@ -12387,9 +12386,9 @@ RETURN R0 0 )" == res0); auto res1 = "\n" + compileFunction(source.c_str(), 1, 0, 0); CHECK(res1 == R"( -NEWCLASS R0 no_base K4 0 [class Point (props: 2, methods: 1)] +NEWCLASS R0 no_base K4 0 [class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0)] NEWCLOSURE R1 P0 -NEWCLASSMEMBER R0 R1 ['__init'] +NEWCLASSMEMBER R0 R1 [public] ['__init'] DUPTABLE R1 5 LOADK R2 K0 ['Point'] SETTABLE R0 R1 R2 @@ -12397,6 +12396,932 @@ RETURN R1 1 )"); } +TEST_CASE("ClassPrivateFieldRead") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class Point + private _x: number + private _y: number + function getX(self) + return self._x + end + function getY(self) + return self._y + end + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETPRIVATEFIELD R1 R0 U0 0 [instance] +RETURN R1 1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +GETPRIVATEFIELD R1 R0 U0 1 [instance] +RETURN R1 1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +NEWCLASS R0 no_base K4 0 [class Point (public fields: 0, public methods: 3, private fields: 2, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['getX'] +NEWCLOSURE R1 P1 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['getY'] +RETURN R0 0 +)"); +} + +TEST_CASE("ClassPrivateFieldReadInExpression") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class Point + private _x: number + private _y: number + function magnitude(self) + return self._x * self._x + self._y * self._y + end + end + print(Point) + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETPRIVATEFIELD R3 R0 U0 0 [instance] +GETPRIVATEFIELD R4 R0 U0 0 [instance] +MUL R2 R3 R4 +GETPRIVATEFIELD R4 R0 U0 1 [instance] +GETPRIVATEFIELD R5 R0 U0 1 [instance] +MUL R3 R4 R5 +ADD R1 R2 R3 +RETURN R1 1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLASS R0 no_base K3 0 [class Point (public fields: 0, public methods: 2, private fields: 2, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['magnitude'] +GETGLOBAL R1 K4 ['print'] +MOVE R2 R0 +CALL R1 1 0 +RETURN R0 0 +)"); +} + +TEST_CASE("ClassPrivateFieldSlotsDontCountPublicFields") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + // Slot indices count just private fields + std::string source = R"( + class Account + public owner: string + private _balance: number + public id: number + private _pin: number + function peek(self) + return self.owner, self._balance, self.id, self._pin + end + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETTABLEKS R1 R0 K0 ['owner'] +GETPRIVATEFIELD R2 R0 U0 0 [instance] +GETTABLEKS R3 R0 K1 ['id'] +GETPRIVATEFIELD R4 R0 U0 1 [instance] +RETURN R1 4 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLASS R0 no_base K5 0 [class Account (public fields: 2, public methods: 2, private fields: 2, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['peek'] +RETURN R0 0 +)"); +} + +TEST_CASE("ClassPrivateMethodAsValue") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + // Private methods live on the class rather than the instance, so reading one sets the AUX + // 'static' bit. Their slots are numbered independently of the instance fields. + std::string source = R"( + class C + private function _first(self) + return 0 + end + private function _second(self) + return 1 + end + function pick(self) + return self._first, self._second + end + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +GETPRIVATEFIELD R1 R0 U0 0 [static] +GETPRIVATEFIELD R2 R0 U0 1 [static] +RETURN R1 2 +)"); + + // A private member carries no name constant, so its NEWCLASSMEMBER AUX slot is 0 and the dump + // shows constant 0 -- the class name -- rather than the member name. + CHECK_EQ("\n" + bcb.dumpFunction(3), R"( +NEWCLASS R0 no_base K3 0 [class C (public fields: 0, public methods: 2, private fields: 0, private methods: 2)] +NEWCLOSURE R1 P0 +NEWCLASSMEMBER R0 R1 0 [private] +NEWCLOSURE R1 P1 +NEWCLASSMEMBER R0 R1 1 [private] +NEWCLOSURE R1 P2 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['pick'] +RETURN R0 0 +)"); +} + +TEST_CASE("ClassPrivateMethodCallDoesNotUseNamecall") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class C + private _x: number + private function _helper(self) + return self._x + end + function get(self) + return self:_helper() + end + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +GETPRIVATEFIELD R1 R0 U0 0 [static] [namecall] +CALL R1 1 -1 +RETURN R1 -1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +NEWCLASS R0 no_base K3 0 [class C (public fields: 0, public methods: 2, private fields: 1, private methods: 1)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 0 [private] +NEWCLOSURE R1 P1 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['get'] +RETURN R0 0 +)"); +} + +TEST_CASE("ClassMetamethodNamesAreNotPrivate") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + // A single leading underscore marks a private member; '__' names are metamethods and stay + // ordinary property accesses even inside a method body. + std::string source = R"( + class Point + private _x: number + function describe(self) + return self.__tostring, self._x + end + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETTABLEKS R1 R0 K0 ['__tostring'] +GETPRIVATEFIELD R2 R0 U0 0 [instance] +RETURN R1 2 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLASS R0 no_base K3 0 [class Point (public fields: 0, public methods: 2, private fields: 1, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['describe'] +RETURN R0 0 +)"); +} + +TEST_CASE("ClassPrivateFieldInNestedClosure") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + // Closures nested inside a method body are still class-method context, so a private read + // through a captured 'self' compiles to GETPRIVATEFIELD. + std::string source = R"( + class Point + private _x: number + function makeGetter(self) + return function() + return self._x + end + end + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETUPVAL R0 U0 +GETPRIVATEFIELD R0 R0 U1 0 [instance] +RETURN R0 1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +CAPTURE UPVAL U0 +RETURN R1 1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +NEWCLASS R0 no_base K3 0 [class Point (public fields: 0, public methods: 2, private fields: 1, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['makeGetter'] +RETURN R0 0 +)"); +} + +TEST_CASE("ClassPrivateFieldOutsideClassBodyIsPlainIndex") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + // An underscore-prefixed name only denotes a private member inside a class method body. + std::string source = R"( + class Point + private _x: number + end + local function peek(p) + return p._x + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETTABLEKS R1 R0 K0 ['_x'] +RETURN R1 1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLASS R0 no_base K2 0 [class Point (public fields: 0, public methods: 1, private fields: 1, private methods: 0)] +NEWCLOSURE R1 P0 +RETURN R0 0 +)"); +} + +TEST_CASE("ClassUndeclaredPrivateFieldProducesError") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class Point + private _x: number + function get(self) + return self._y + end + end + )"; + + try + { + compileFunction(source.c_str(), 0, 0, 0); + FAIL("Expected compile error"); + } + catch (const std::exception& e) + { + std::string msg = e.what(); + CHECK(msg == "Attempt to access undefined private field"); + } +} + +TEST_CASE("ClassUndeclaredPrivateFieldNotInlined") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class Point + private _x: number + function get(self) + local t = { _f = function() return 42 end } + return t._f() + end + end + )"; + + try + { + compileFunction(source.c_str(), 0, 2, 0); + FAIL("Expected compile error"); + } + catch (const std::exception& e) + { + std::string msg = e.what(); + CHECK(msg == "Attempt to access undefined private field"); + } +} + +TEST_CASE("ClassPrivateFieldDeclaredAfterUseProducesError") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + // Private slots are computed before the class body is fully compiled, so a field declared after its use is still recognized. + std::string source = R"( + class Point + function get(self) + return self._x + end + private _x: number + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETPRIVATEFIELD R1 R0 U0 0 [instance] +RETURN R1 1 +)"); +} + +TEST_CASE("ClassPrivateFieldAssignment") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class Point + private _x: number + private _y: number + function __init(self, x, y) + self._x = x + self._y = y + end + end + + local p = Point(3, 4) + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::CompileOptions options; + options.optimizationLevel = 0; + + Luau::compileOrThrow(bcb, source, options); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +SETPRIVATEFIELD R1 R0 U0 0 +SETPRIVATEFIELD R2 R0 U0 1 +RETURN R0 0 +)"); + + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLASS R0 no_base K2 0 [class Point (public fields: 0, public methods: 1, private fields: 2, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['__init'] +MOVE R1 R0 +LOADK R2 K3 [3] +LOADK R3 K4 [4] +CALL R1 2 1 +RETURN R0 0 +)"); +} + +TEST_CASE("ClassPrivateFieldAssignmentFromPrivateField") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( + class Point + private _x: number + private _y: number + function mirror(self) + self._y = self._x + end + end + )"), + R"( +GETPRIVATEFIELD R1 R0 U0 0 [instance] +SETPRIVATEFIELD R1 R0 U0 1 +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassPrivateFieldCompoundAssignment") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( + class Counter + private _n: number + function bump(self) + self._n += 1 + end + end + )"), + R"( +GETPRIVATEFIELD R1 R0 U0 0 [instance] +ADDK R1 R1 K0 [1] +SETPRIVATEFIELD R1 R0 U0 0 +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassPrivateFieldMultipleAssignment") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( + class Point + private _x: number + private _y: number + function reset(self) + self._x, self._y = 0, 0 + end + end + )"), + R"( +LOADN R1 0 +LOADN R2 0 +SETPRIVATEFIELD R1 R0 U0 0 +SETPRIVATEFIELD R2 R0 U0 1 +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassPrivateFieldMultipleAssignmentConflict") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + // Make sure multiple assignemnt with private fields does operations in the correct order + CHECK_EQ( + "\n" + compileFunction0(R"( + class Point + private _x: number + function reassign(self, other) + other, other._x = self, 1 + end + end + )"), + R"( +MOVE R2 R0 +LOADN R3 1 +SETPRIVATEFIELD R3 R1 U0 0 +MOVE R1 R2 +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassPrivateFieldAssignmentInNestedClosure") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( + class Point + private _x: number + function makeSetter(self) + return function(v) + self._x = v + end + end + end + )"), + R"( +GETUPVAL R1 U0 +SETPRIVATEFIELD R0 R1 U1 0 +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassPrivateFieldAssignmentOnOtherInstance") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( + class Point + private _x: number + function copyTo(self, other) + other._x = self._x + end + end + )"), + R"( +GETPRIVATEFIELD R2 R0 U0 0 [instance] +SETPRIVATEFIELD R2 R1 U0 0 +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassPrivateFieldAssignmentDeclaredAfterUse") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( + class Point + function set(self, x) + self._x = x + end + private _x: number + end + )"), + R"( +SETPRIVATEFIELD R1 R0 U0 0 +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassPrivateFieldAssignmentOutsideClassBodyIsPlainIndex") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( + class Point + private _x: number + end + local function poke(p) + p._x = 1 + end + )"), + R"( +LOADN R1 1 +SETTABLEKS R1 R0 K0 ['_x'] +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassMetamethodNameAssignmentIsNotPrivate") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( + class Point + private _x: number + function rig(self, f) + self.__tostring = f + end + end + )"), + R"( +SETTABLEKS R1 R0 K0 ['__tostring'] +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassPrivateMethodAssignmentProducesError") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class Point + private function _helper(self) + end + function rig(self, f) + self._helper = f + end + end + )"; + + try + { + compileFunction(source.c_str(), 0, 0, 0); + FAIL("Expected compile error"); + } + catch (const std::exception& e) + { + CHECK(std::string(e.what()) == "Attempt to assign static field of a class"); + } +} + +TEST_CASE("ClassUndeclaredPrivateFieldAssignmentProducesError") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class Point + private _x: number + function set(self, y) + self._y = y + end + end + )"; + + try + { + compileFunction(source.c_str(), 0, 0, 0); + FAIL("Expected compile error"); + } + catch (const std::exception& e) + { + CHECK(std::string(e.what()) == "Attempt to assign undefined private field"); + } +} + +TEST_CASE("ClassPrivateFieldAssignmentWithNoPrivateMembersProducesError") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class Point + public x: number + function set(self, y) + self._y = y + end + end + )"; + + try + { + compileFunction(source.c_str(), 0, 0, 0); + FAIL("Expected compile error"); + } + catch (const std::exception& e) + { + CHECK(std::string(e.what()) == "Attempt to assign private field of a class with no private fields"); + } +} + + +TEST_CASE("ClassPrivateFieldIndexGlobal") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = R"( + class C + private _x + function f(self) + return string._x + end + end + )"; + + try + { + compileFunction(source.c_str(), 0, 1, 0); + FAIL("Expected compile error"); + } + catch (const std::exception& e) + { + CHECK(std::string(e.what()) == "Attempt to access private field of a global"); + } + + source = R"( + class C + private _x + function f(self) + return string._x.y + end + end + )"; + + try + { + compileFunction(source.c_str(), 0, 1, 0); + FAIL("Expected compile error"); + } + catch (const std::exception& e) + { + CHECK(std::string(e.what()) == "Attempt to access private field of a global"); + } +} + + +TEST_CASE("ClassConstructedInsidePrivateMethod") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + ScopedFastFlag reuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; + + std::string source = R"( + class Vec + private _x + private _y + + private function _scaled(self, k) + return Vec(self._x * k, self._y * k) + end + + function __init(self, x, y) + self._x = x + self._y = y + end + + function double(self) + return self:_scaled(2) + end + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::compileOrThrow(bcb, source); + + // _scaled: the class name resolves to the captured class upvalue, so the construction inside a + // private method is an ordinary call on that upvalue. + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETUPVAL R2 U0 +GETPRIVATEFIELD R4 R0 U0 0 [instance] +MUL R3 R4 R1 +GETPRIVATEFIELD R5 R0 U0 1 [instance] +MUL R4 R5 R1 +CALL R2 2 -1 +RETURN R2 -1 +)"); + + // __init + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +SETPRIVATEFIELD R1 R0 U0 0 +SETPRIVATEFIELD R2 R0 U0 1 +RETURN R0 0 +)"); + + // double: the private method is fetched as a private static member instead of via NAMECALL. CALL + // passes R2 and R3 as the two arguments, and R3 holds the literal 2, so R2 is the 'self' slot that + // NAMECALL would have filled by moving the object into ra+1 — GETPRIVATEFIELD only writes ra, so + // nothing ever stores into R2. + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +LOADN R3 2 +GETPRIVATEFIELD R1 R0 U0 0 [static] [namecall] +CALL R1 2 -1 +RETURN R1 -1 +)"); + + // main chunk: the class is built in a local that every method captures by reference, which is the + // upvalue the private accesses above index through. + CHECK_EQ("\n" + bcb.dumpFunction(3), R"( +NEWCLASS R0 no_base K6 0 [class Vec (public fields: 0, public methods: 2, private fields: 2, private methods: 1)] +DUPCLOSURE R1 K1 ['_scaled'] +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 0 [private] +DUPCLOSURE R1 K2 ['__init'] +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['__init'] +DUPCLOSURE R1 K4 ['double'] +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['double'] +RETURN R0 0 +)"); +} + +TEST_CASE("ClassPrivateStaticMethodNamecallOnClassObject") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + ScopedFastFlag reuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; + + std::string source = R"( + class StaticNamecall + private _x + + private function _receiver(receiver) + return receiver + end + + function __init(self, x) + self._x = x + end + + function staticReceiver(self) + return StaticNamecall:_receiver() + end + end + )"; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + + Luau::compileOrThrow(bcb, source); + + // _receiver: it touches no private field and does not name its own class, so it captures nothing. + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +RETURN R0 1 +)"); + + // __init + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +SETPRIVATEFIELD R1 R0 U0 0 +RETURN R0 0 +)"); + + // staticReceiver: the receiver of the namecall is the class object, which lives in an upvalue rather + // than a local, so it is computed into the call's base register R1 — the same register + // GETPRIVATEFIELD writes the callee into. The instance form (self:_method()) instead uses the + // receiver's own local register as the source and so does not alias the callee register. + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +GETUPVAL R1 U0 +GETPRIVATEFIELD R1 R1 U0 0 [static] [namecall] +CALL R1 1 -1 +RETURN R1 -1 +)"); + + // main chunk + CHECK_EQ("\n" + bcb.dumpFunction(3), R"( +NEWCLASS R0 no_base K6 0 [class StaticNamecall (public fields: 0, public methods: 2, private fields: 1, private methods: 1)] +DUPCLOSURE R1 K1 ['_receiver'] +NEWCLASSMEMBER R0 R1 0 [private] +DUPCLOSURE R1 K2 ['__init'] +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['__init'] +DUPCLOSURE R1 K4 ['staticReceiver'] +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['staticReceiver'] +RETURN R0 0 +)"); +} + TEST_CASE("IntegerType") { if (!FFlag::LuauIntegerType2) @@ -13345,6 +14270,51 @@ TEST_CASE("ExportSyntaxRegression") )")); } +TEST_CASE("ExportSyntaxRegression2") +{ + ScopedFastFlag sffs[] = {{FFlag::LuauExportValueSyntax, true}}; + + CHECK_NOTHROW(compileFunction0(R"( +-- 130 top-level locals push regTop past 127 before the export table is lazily allocated +local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 +local a11, a12, a13, a14, a15, a16, a17, a18, a19, a20 = 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 +local a21, a22, a23, a24, a25, a26, a27, a28, a29, a30 = 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 +local a31, a32, a33, a34, a35, a36, a37, a38, a39, a40 = 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 +local a41, a42, a43, a44, a45, a46, a47, a48, a49, a50 = 41, 42, 43, 44, 45, 46, 47, 48, 49, 50 +local a51, a52, a53, a54, a55, a56, a57, a58, a59, a60 = 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 +local a61, a62, a63, a64, a65, a66, a67, a68, a69, a70 = 61, 62, 63, 64, 65, 66, 67, 68, 69, 70 +local a71, a72, a73, a74, a75, a76, a77, a78, a79, a80 = 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 +local a81, a82, a83, a84, a85, a86, a87, a88, a89, a90 = 81, 82, 83, 84, 85, 86, 87, 88, 89, 90 +local a91, a92, a93, a94, a95, a96, a97, a98, a99, a100 = 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 +local a101, a102, a103, a104, a105, a106, a107, a108, a109, a110 = 101, 102, 103, 104, 105, 106, 107, 108, 109, 110 +local a111, a112, a113, a114, a115, a116, a117, a118, a119, a120 = 111, 112, 113, 114, 115, 116, 117, 118, 119, 120 +local a121, a122, a123, a124, a125, a126, a127, a128, a129, a130 = 121, 122, 123, 124, 125, 126, 127, 128, 129, 130 + +-- a1 is mutable (written below), so this is not folded into the constant export shape +export local first = a1 + +-- every local is written after the export, so none are constant and all stay live past it +a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 = a1 + 1, a2 + 1, a3 + 1, a4 + 1, a5 + 1, a6 + 1, a7 + 1, a8 + 1, a9 + 1, a10 + 1 +a11, a12, a13, a14, a15, a16, a17, a18, a19, a20 = a11 + 1, a12 + 1, a13 + 1, a14 + 1, a15 + 1, a16 + 1, a17 + 1, a18 + 1, a19 + 1, a20 + 1 +a21, a22, a23, a24, a25, a26, a27, a28, a29, a30 = a21 + 1, a22 + 1, a23 + 1, a24 + 1, a25 + 1, a26 + 1, a27 + 1, a28 + 1, a29 + 1, a30 + 1 +a31, a32, a33, a34, a35, a36, a37, a38, a39, a40 = a31 + 1, a32 + 1, a33 + 1, a34 + 1, a35 + 1, a36 + 1, a37 + 1, a38 + 1, a39 + 1, a40 + 1 +a41, a42, a43, a44, a45, a46, a47, a48, a49, a50 = a41 + 1, a42 + 1, a43 + 1, a44 + 1, a45 + 1, a46 + 1, a47 + 1, a48 + 1, a49 + 1, a50 + 1 +a51, a52, a53, a54, a55, a56, a57, a58, a59, a60 = a51 + 1, a52 + 1, a53 + 1, a54 + 1, a55 + 1, a56 + 1, a57 + 1, a58 + 1, a59 + 1, a60 + 1 +a61, a62, a63, a64, a65, a66, a67, a68, a69, a70 = a61 + 1, a62 + 1, a63 + 1, a64 + 1, a65 + 1, a66 + 1, a67 + 1, a68 + 1, a69 + 1, a70 + 1 +a71, a72, a73, a74, a75, a76, a77, a78, a79, a80 = a71 + 1, a72 + 1, a73 + 1, a74 + 1, a75 + 1, a76 + 1, a77 + 1, a78 + 1, a79 + 1, a80 + 1 +a81, a82, a83, a84, a85, a86, a87, a88, a89, a90 = a81 + 1, a82 + 1, a83 + 1, a84 + 1, a85 + 1, a86 + 1, a87 + 1, a88 + 1, a89 + 1, a90 + 1 +a91, a92, a93, a94, a95, a96, a97, a98, a99, a100 = a91 + 1, a92 + 1, a93 + 1, a94 + 1, a95 + 1, a96 + 1, a97 + 1, a98 + 1, a99 + 1, a100 + 1 +a101, a102, a103, a104, a105, a106, a107, a108, a109, a110 = a101 + 1, a102 + 1, a103 + 1, a104 + 1, a105 + 1, a106 + 1, a107 + 1, a108 + 1, a109 + 1, a110 + 1 +a111, a112, a113, a114, a115, a116, a117, a118, a119, a120 = a111 + 1, a112 + 1, a113 + 1, a114 + 1, a115 + 1, a116 + 1, a117 + 1, a118 + 1, a119 + 1, a120 + 1 +a121, a122, a123, a124, a125, a126, a127, a128, a129, a130 = a121 + 1, a122 + 1, a123 + 1, a124 + 1, a125 + 1, a126 + 1, a127 + 1, a128 + 1, a129 + 1, a130 + 1 + +export function getFirst() + assert(first == 1) + return first +end + )")); +} + TEST_CASE("ExportTypeOnlyNoReturnEmitsEmptyTable") { ScopedFastFlag sffs[] = {{FFlag::LuauExportValueSyntax, true}, {FFlag::LuauExportedTypesParticipateInScc, true}}; @@ -13414,7 +14384,7 @@ end )"), R"( NEWTABLE R1 0 0 -NEWCLASS R0 no_base K4 0 [class Point (props: 2, methods: 1)] +NEWCLASS R0 no_base K4 0 [class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0)] SETTABLEKS R0 R1 K0 ['Point'] GETIMPORT R2 7 [table.freeze] MOVE R3 R1 @@ -13443,11 +14413,11 @@ end ), R"( NEWTABLE R1 0 0 -NEWCLASS R0 no_base K8 0 [class Point (props: 2, methods: 3)] +NEWCLASS R0 no_base K8 0 [class Point (public fields: 2, public methods: 3, private fields: 0, private methods: 0)] DUPCLOSURE R2 K3 ['getX'] -NEWCLASSMEMBER R0 R2 ['getX'] +NEWCLASSMEMBER R0 R2 [public] ['getX'] DUPCLOSURE R2 K5 ['getY'] -NEWCLASSMEMBER R0 R2 ['getY'] +NEWCLASSMEMBER R0 R2 [public] ['getY'] SETTABLEKS R0 R1 K0 ['Point'] GETIMPORT R2 11 [table.freeze] MOVE R3 R1 @@ -13471,7 +14441,7 @@ local p = Point.new({x = 1, y = 2}) ), R"( NEWTABLE R1 0 0 -NEWCLASS R0 no_base K4 0 [class Point (props: 2, methods: 1)] +NEWCLASS R0 no_base K4 0 [class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0)] GETTABLEKS R2 R0 K5 ['new'] DUPTABLE R3 8 CALL R2 1 1 @@ -13503,61 +14473,8 @@ RETURN R0 1 ); } -TEST_CASE("VectorOptionsDoubleUnsupported") -{ - // Until flag is enabled, bytecode is the same for vectors of any precision - ScopedFastFlag luauCompileEmitVectorDouble{FFlag::LuauCompileEmitVectorDouble, false}; - - std::string bytecode1, bytecode2; - - { - Luau::BytecodeBuilder bcb; - bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code | Luau::BytecodeBuilder::Dump_Constants); - - Luau::CompileOptions opts; - opts.optimizationLevel = 2; - Luau::compileOrThrow(bcb, "return vector.create(1, 1/2^32, 1/2^256)", opts); - - bytecode1 = bcb.getBytecode(); - - CHECK_EQ( - "\n" + bcb.dumpFunction(0), - R"( -K0: 1, 2.32830644e-10, 0 -LOADK R0 K0 [1, 2.32830644e-10, 0] -RETURN R0 1 -)" - ); - } - - { - Luau::BytecodeBuilder bcb; - bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code | Luau::BytecodeBuilder::Dump_Constants); - - Luau::CompileOptions opts; - opts.optimizationLevel = 2; - opts.vectorPrecision = 1; - Luau::compileOrThrow(bcb, "return vector.create(1, 1/2^32, 1/2^256)", opts); - - bytecode2 = bcb.getBytecode(); - - CHECK_EQ( - "\n" + bcb.dumpFunction(0), - R"( -K0: 1, 2.32830644e-10, 0 -LOADK R0 K0 [1, 2.32830644e-10, 0] -RETURN R0 1 -)" - ); - } - - CHECK(bytecode1 == bytecode2); -} - TEST_CASE("VectorOptionsDouble") { - ScopedFastFlag luauCompileEmitVectorDouble{FFlag::LuauCompileEmitVectorDouble, true}; - Luau::BytecodeBuilder bcb; bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code | Luau::BytecodeBuilder::Dump_Constants); @@ -13594,8 +14511,8 @@ print(Cat) auto res0 = "\n" + compileFunction(source.c_str(), 0, 0, 0); CHECK(R"( -NEWCLASS R0 no_base K3 1 [class Animal (props: 1, methods: 1)] -NEWCLASS R1 R0 K6 0 [class Cat (props: 1, methods: 1)] +NEWCLASS R0 no_base K3 1 [class Animal (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] +NEWCLASS R1 R0 K6 0 [class Cat (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] GETGLOBAL R2 K7 ['print'] MOVE R3 R1 CALL R2 1 0 @@ -13644,12 +14561,12 @@ RETURN R1 1 // Function 2: main chunk auto res2 = "\n" + compileFunction(source.c_str(), 2, 0, 0); CHECK(R"( -NEWCLASS R0 no_base K4 1 [class Animal (props: 1, methods: 2)] +NEWCLASS R0 no_base K4 1 [class Animal (public fields: 1, public methods: 2, private fields: 0, private methods: 0)] NEWCLOSURE R1 P0 -NEWCLASSMEMBER R0 R1 ['live'] -NEWCLASS R1 R0 K8 0 [class Cat (props: 1, methods: 2)] +NEWCLASSMEMBER R0 R1 [public] ['live'] +NEWCLASS R1 R0 K8 0 [class Cat (public fields: 1, public methods: 2, private fields: 0, private methods: 0)] NEWCLOSURE R2 P1 -NEWCLASSMEMBER R1 R2 ['describe'] +NEWCLASSMEMBER R1 R2 [public] ['describe'] GETGLOBAL R2 K9 ['print'] MOVE R3 R1 CALL R2 1 0 @@ -13679,9 +14596,9 @@ print(C) auto res0 = "\n" + compileFunction(source.c_str(), 0, 0, 0); CHECK(R"( -NEWCLASS R0 no_base K3 1 [class A (props: 1, methods: 1)] -NEWCLASS R1 R0 K6 1 [class B (props: 1, methods: 1)] -NEWCLASS R2 R1 K9 0 [class C (props: 1, methods: 1)] +NEWCLASS R0 no_base K3 1 [class A (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] +NEWCLASS R1 R0 K6 1 [class B (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] +NEWCLASS R2 R1 K9 0 [class C (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] GETGLOBAL R3 K10 ['print'] MOVE R4 R2 CALL R3 1 0 @@ -13707,9 +14624,9 @@ export class Cat extends Animal end )"), R"( -NEWCLASS R0 no_base K3 1 [class Animal (props: 1, methods: 1)] +NEWCLASS R0 no_base K3 1 [class Animal (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] NEWTABLE R2 0 0 -NEWCLASS R1 R0 K6 0 [class Cat (props: 1, methods: 1)] +NEWCLASS R1 R0 K6 0 [class Cat (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] SETTABLEKS R1 R2 K4 ['Cat'] GETIMPORT R3 9 [table.freeze] MOVE R4 R2 @@ -13731,9 +14648,9 @@ class l0 extends _ end )"), R"( -NEWCLASS R0 no_base K2 0 [class _ (props: 0, methods: 1)] +NEWCLASS R0 no_base K2 0 [class _ (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] LOADNIL R2 -NEWCLASS R1 R2 K4 0 [class l0 (props: 0, methods: 1)] +NEWCLASS R1 R2 K4 0 [class l0 (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] RETURN R0 0 )" ); @@ -13763,7 +14680,7 @@ K0: 'Point' K1: 'x' K2: 'y' K3: '__init' -K4: class Point (props: 2, methods: 1) +K4: class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0) props: K1 ['x'] K2 ['y'] @@ -13781,7 +14698,7 @@ slot 1: shape K9 slot 2: shape K10 slot 3: shape K11 GETVARARGS R0 2 -NEWCLASS R2 no_base K4 0 [class Point (props: 2, methods: 1)] +NEWCLASS R2 no_base K4 0 [class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0)] MOVE R3 R2 CONSTRUCT R4 R3 slot 0 FINCONSTRUCT R4 L0 diff --git a/tests/Conformance.test.cpp b/tests/Conformance.test.cpp index a590d0783..ee1aaaae0 100644 --- a/tests/Conformance.test.cpp +++ b/tests/Conformance.test.cpp @@ -58,29 +58,28 @@ void luaC_validate(lua_State* L); LUAU_FASTFLAG(DebugLuauAbortingChecks) LUAU_FASTFLAG(LuauBytecodeFold) LUAU_FASTFLAG(LuauBytecodeSlotAlloc) +LUAU_FASTFLAG(LuauCodegenA64BitlrotateSelf) LUAU_FASTFLAG(LuauEmitCallFeedback) LUAU_FASTINT(CodegenHeuristicsInstructionLimit) LUAU_FASTFLAG(LuauIntegerLibrary) LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(LuauCodegenBufferInteger) +LUAU_FASTFLAG(LuauCodegenA64ReloadLargeConstOffset) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) -LUAU_FASTFLAG(LuauCompileEmitVectorDouble) LUAU_FASTFLAG(LuauCompileNoFoldVectorEqW) LUAU_FASTFLAG(LuauGcTraceUdata) LUAU_DYNAMIC_FASTFLAG(LuauGcHeapShrinkFix) -LUAU_FASTFLAG(LuauFastpcallInterrupt) LUAU_FASTFLAG(LuauPcallErrorContinuationReentry) LUAU_FASTFLAG(LuauEmitCallFeedback) LUAU_FASTFLAG(LuauBytecodeCostModel) -LUAU_FASTFLAG(LuauNewPointerEncode) -LUAU_FASTFLAG(LuauSandboxFreezesVectorMetatable) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauSandboxFreezesVectorMetatable) LUAU_FASTFLAG(LuauBufferCage) LUAU_FASTFLAG(LuauCoroutineFinally) LUAU_FASTFLAG(LuauCoroutineFinallyAnalysis) +LUAU_FASTFLAG(LuauCodegenDseTrackTagInvalidation) LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(LuauCompileCallFbRemap) LUAU_DYNAMIC_FASTFLAG(LuauTableRobustOom) @@ -1619,6 +1618,8 @@ TEST_CASE("GC") TEST_CASE("Bitwise") { + ScopedFastFlag luauCodegenA64BitlrotateSelf{FFlag::LuauCodegenA64BitlrotateSelf, true}; + runConformance("bitwise.luau"); } @@ -2031,7 +2032,6 @@ TEST_CASE("CYield") TEST_CASE("Vector") { - ScopedFastFlag luauCompileEmitVectorDouble{FFlag::LuauCompileEmitVectorDouble, true}; ScopedFastFlag luauCompileNoFoldVectorEqW{FFlag::LuauCompileNoFoldVectorEqW, true}; lua_CompileOptions copts = defaultOptions(); @@ -2090,8 +2090,6 @@ TEST_CASE("Vector") TEST_CASE("VectorLibrary") { - ScopedFastFlag luauCompileEmitVectorDouble{FFlag::LuauCompileEmitVectorDouble, true}; - lua_CompileOptions copts = defaultOptions(); SUBCASE("O0") @@ -3375,8 +3373,6 @@ TEST_CASE("ApiEncode") CHECK(a == b); } - ScopedFastFlag luauNewPointerEncode{FFlag::LuauNewPointerEncode, true}; - // A few exact value tests if (sizeof(void*) == 8) { @@ -3777,8 +3773,22 @@ foo() class HeapClass public value + private _hidden + + public function __init(self, val) + self.value = val + self._hidden = val + end + + private function _tag(self) + return self._hidden + end + + function tag(self) + return self:_tag() + end end -local object = HeapClass { value = x } +local object = HeapClass(x) return f, object )"; @@ -3830,11 +3840,14 @@ return f, object if (tt == LUA_TUSERDATA) CHECK(sv == "u42"); else if (tt == LUA_TPROTO) - CHECK((sv == "proto unnamed:1 =GCDump" || sv == "proto foo:7 =GCDump" || sv == "proto f:4 =GCDump")); + CHECK( + (sv == "proto unnamed:1 =GCDump" || sv == "proto foo:7 =GCDump" || sv == "proto f:4 =GCDump" || + sv == "proto __init:17 =GCDump" || sv == "proto _tag:22 =GCDump" || sv == "proto tag:26 =GCDump") + ); else if (tt == LUA_TFUNCTION) CHECK( - (sv == "test" || sv == "unnamed:1 =GCDump" || sv == "foo:7 =GCDump" || sv == "f:4 =GCDump" || - sv == "luaR_defaultcreateobject" || sv == "luaR_constructobject") + (sv == "test" || sv == "unnamed:1 =GCDump" || sv == "foo:7 =GCDump" || sv == "f:4 =GCDump" || sv == "__init:17 =GCDump" || + sv == "_tag:22 =GCDump" || sv == "tag:26 =GCDump" || sv == "luaR_defaultcreateobject" || sv == "luaR_constructobject") ); else if (tt == LUA_TTHREAD) CHECK(sv == "thread at unnamed:1 =GCDump"); @@ -3885,8 +3898,6 @@ return f, object TEST_CASE("Interrupt") { - ScopedFastFlag luauFastpcallInterrupt{FFlag::LuauFastpcallInterrupt, true}; - lua_CompileOptions copts = defaultOptions(); copts.optimizationLevel = 1; // disable loop unrolling to get fixed expected hit results @@ -4713,6 +4724,9 @@ TEST_CASE("SafeEnv") TEST_CASE("Native") { + ScopedFastFlag reloadLargeConstOffset{FFlag::LuauCodegenA64ReloadLargeConstOffset, true}; + ScopedFastFlag luauCodegenDseTrackTagInvalidation{FFlag::LuauCodegenDseTrackTagInvalidation, true}; + // This tests requires code to run natively, otherwise all 'is_native' checks will fail if (!codegen || !luau_codegen_supported()) return; diff --git a/tests/Fixture.cpp b/tests/Fixture.cpp index 733949b0a..e2aa87477 100644 --- a/tests/Fixture.cpp +++ b/tests/Fixture.cpp @@ -774,19 +774,6 @@ void Fixture::limitStackSize(size_t size) dynamicScopedInts.emplace_back(FInt::LuauStackGuardThreshold, (int)(addressSpaceSize - size)); } -void Fixture::ignoreMissingAnnotations(CheckResult& result) -{ - auto it = std::remove_if( - result.errors.begin(), - result.errors.end(), - [](const TypeError& err) - { - return get(err); - } - ); - result.errors.erase(it, result.errors.end()); -} - BuiltinsFixture::BuiltinsFixture(bool prepareAutocomplete) : Fixture(prepareAutocomplete) { diff --git a/tests/Fixture.h b/tests/Fixture.h index c59bd4fc1..25c8e5eaa 100644 --- a/tests/Fixture.h +++ b/tests/Fixture.h @@ -240,11 +240,6 @@ struct Fixture // use this to test the stack guard itself. void limitStackSize(size_t size); - // Edits the result, pruning any warnings about missing annotations. This - // is useful for tests that are specifically about how we infer unannotated - // symbols. - void ignoreMissingAnnotations(CheckResult& result); - private: bool hasDumpedErrors = false; diff --git a/tests/Frontend.test.cpp b/tests/Frontend.test.cpp index c6c1b959e..17f343bcc 100644 --- a/tests/Frontend.test.cpp +++ b/tests/Frontend.test.cpp @@ -2076,8 +2076,6 @@ TEST_CASE_FIXTURE(FrontendFixture, "generic_P_widening_with_cross_module_recursi CheckResult result = getFrontend().check("game/Gui/Modules/B"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/Generalization.test.cpp b/tests/Generalization.test.cpp index 191202ceb..48613242b 100644 --- a/tests/Generalization.test.cpp +++ b/tests/Generalization.test.cpp @@ -435,7 +435,7 @@ TEST_CASE_FIXTURE(Fixture, "generic_argument_with_singleton_oss_1808") end test(false) )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -464,7 +464,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "avoid_cross_module_mutation_in_bidirectional CheckResult result = getFrontend().check("Module/ListFns"); - ignoreMissingAnnotations(result); auto modListFns = getFrontend().moduleResolver.getModule("Module/ListFns"); freeze(modListFns->interfaceTypes); freeze(*modListFns->internalTypes); @@ -596,7 +595,6 @@ TEST_CASE_FIXTURE(Fixture, "mixed_polarity_is_recovered") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); auto ty = requireType("identity"); diff --git a/tests/IrBuilder.test.cpp b/tests/IrBuilder.test.cpp index 83f461caa..c6263c736 100644 --- a/tests/IrBuilder.test.cpp +++ b/tests/IrBuilder.test.cpp @@ -18,8 +18,6 @@ LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauIntegerLibrary) LUAU_FASTFLAG(LuauCodegenPropagateFallbackTags) LUAU_FASTFLAG(LuauCodegenNoZeroScale) -LUAU_FASTFLAG(LuauCodegenNoLinearFastpcall) -LUAU_FASTFLAG(LuauCodegenLimitVersions) LUAU_FASTFLAG(LuauCodegenLimitVersionsExtra) using namespace Luau::CodeGen; @@ -2533,7 +2531,7 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64NumRoundtripElimination") build.beginBlock(block); - // NUM_TO_INT64(INT64_TO_NUM(x)) => x + // NUM_TO_INT64(INT64_TO_NUM(x)) != x IrOp intVal = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); IrOp dblVal = build.inst(IrCmd::INT64_TO_NUM, intVal); IrOp backToInt = build.inst(IrCmd::NUM_TO_INT64, dblVal); @@ -2547,7 +2545,9 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64NumRoundtripElimination") CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( bb_0: %0 = LOAD_INT64 R0 - STORE_INT64 R1, %0 + %1 = INT64_TO_NUM %0 + %2 = NUM_TO_INT64 %1 + STORE_INT64 R1, %2 RETURN 0u )"); @@ -4727,8 +4727,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "NoLinearExtractionForChainWithCall") TEST_CASE_FIXTURE(IrBuilderFixture, "NoLinearExtractionForChainWithPcall") { - ScopedFastFlag luauCodegenNoLinearFastpcall{FFlag::LuauCodegenNoLinearFastpcall, true}; - IrOp block1 = build.block(IrBlockKind::Internal); IrOp fallback1 = build.fallbackBlock(0u); IrOp block2 = build.block(IrBlockKind::Internal); @@ -7009,7 +7007,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "IndirectFloatLoadExtractionMustRespectVersi TEST_CASE_FIXTURE(IrBuilderFixture, "VersionLimitChecks") { - ScopedFastFlag luauCodegenLimitVersions{FFlag::LuauCodegenLimitVersions, true}; ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; ScopedFastFlag luauCodegenLimitVersionsExtra{FFlag::LuauCodegenLimitVersionsExtra, true}; diff --git a/tests/IrLowering.test.cpp b/tests/IrLowering.test.cpp index cbfd56aab..c2323115f 100644 --- a/tests/IrLowering.test.cpp +++ b/tests/IrLowering.test.cpp @@ -28,7 +28,6 @@ LUAU_FASTFLAG(LuauCodegenIntegerCompare) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) LUAU_FASTFLAG(LuauCompileReuseLocalRegs) LUAU_FASTFLAG(LuauLoadRemapOptionalUserdata) -LUAU_FASTFLAG(LuauCodegenConstPropMinOffset) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) #define ensureVectorSize3() \ @@ -5895,7 +5894,6 @@ end TEST_CASE_FIXTURE(LoweringFixture, "BufferRelatedIndicesConstantRange") { - ScopedFastFlag luauCodegenConstPropMinOffset{FFlag::LuauCodegenConstPropMinOffset, true}; ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; CHECK_EQ( diff --git a/tests/Module.test.cpp b/tests/Module.test.cpp index f775d08a0..3cfa8df38 100644 --- a/tests/Module.test.cpp +++ b/tests/Module.test.cpp @@ -113,8 +113,6 @@ TEST_CASE_FIXTURE(Fixture, "deepClone_cyclic_table") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); /* The inferred type of Cyclic is {get: () -> Cyclic} diff --git a/tests/NonStrictTypeChecker.test.cpp b/tests/NonStrictTypeChecker.test.cpp index a6d60e5a6..725402504 100644 --- a/tests/NonStrictTypeChecker.test.cpp +++ b/tests/NonStrictTypeChecker.test.cpp @@ -787,8 +787,6 @@ function passThrough(module) end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(0, result); // We should still warn about dynamic requires in strict mode result = check(Mode::Strict, R"( @@ -797,8 +795,6 @@ function passThrough(module) end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); const UnknownRequire* req = get(result.errors[0]); CHECK(req != nullptr); diff --git a/tests/NonstrictMode.test.cpp b/tests/NonstrictMode.test.cpp index e7bccc5ff..f6404de82 100644 --- a/tests/NonstrictMode.test.cpp +++ b/tests/NonstrictMode.test.cpp @@ -69,8 +69,6 @@ TEST_CASE_FIXTURE(Fixture, "return_annotation_is_still_checked") function foo(x): number return 'hello' end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK("any" != toString(requireType("foo"))); diff --git a/tests/Normalize.test.cpp b/tests/Normalize.test.cpp index 2a43fdf96..1feabd971 100644 --- a/tests/Normalize.test.cpp +++ b/tests/Normalize.test.cpp @@ -987,8 +987,6 @@ TEST_CASE_FIXTURE(Fixture, "cyclic_table_normalizes_sensibly") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); TypeId ty = requireType("Cyclic"); diff --git a/tests/Parser.test.cpp b/tests/Parser.test.cpp index fb4510371..93557f81c 100644 --- a/tests/Parser.test.cpp +++ b/tests/Parser.test.cpp @@ -80,6 +80,33 @@ std::string_view stringAtLocation(std::string_view source, const Location& locat return source.substr(byteStart, byteEnd - byteStart); } + +// Returns the AstExprIndexName that the sole statement of the sole method of the +// sole class in `source` returns. Used by private field parsing tests +// class C +// function m(self) return end +// end +const AstExprIndexName* getMethodReturnIndexName(const ParseResult& result) +{ + REQUIRE(result.root->body.size >= 1); + + const AstStatClass* cls = result.root->body.data[0]->as(); + REQUIRE(cls); + REQUIRE(cls->members.size == 1); + + auto method = cls->members.data[0].get_if(); + REQUIRE(method); + + const AstStatBlock* body = method->function->body; + REQUIRE(body->body.size == 1); + + const AstStatReturn* ret = body->body.data[0]->as(); + REQUIRE(ret); + REQUIRE(ret->list.size == 1); + + return ret->list.data[0]->as(); +} + } // namespace TEST_SUITE_BEGIN("AllocatorTests"); @@ -3782,8 +3809,6 @@ TEST_CASE_FIXTURE(Fixture, "allowed_metamethods_still_work") function __tostring(self) end function __add(self, other) end function __eq(self, other) end - -- Silly, but allowed. - function _(self) end end )"); @@ -4078,6 +4103,327 @@ TEST_CASE_FIXTURE(Fixture, "export_class") CHECK(classDecl->exported); } +TEST_CASE_FIXTURE(Fixture, "class_private_property") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + class Point + private _x: number + public y: number + end + )"); + + REQUIRE(result.errors.empty()); + + const AstStatClass* cls = result.root->body.data[0]->as(); + REQUIRE(cls); + REQUIRE(cls->members.size == 2); + + auto priv = cls->members.data[0].get_if(); + REQUIRE(priv); + CHECK(priv->name == "_x"); + CHECK(priv->access == AstClassAccess::Private); + + auto pub = cls->members.data[1].get_if(); + REQUIRE(pub); + CHECK(pub->name == "y"); + CHECK(pub->access == AstClassAccess::Public); +} + +TEST_CASE_FIXTURE(Fixture, "class_private_method") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + class Point + private function _helper(self) end + public function visible(self) end + function unqualified(self) end + end + )"); + + REQUIRE(result.errors.empty()); + + const AstStatClass* cls = result.root->body.data[0]->as(); + REQUIRE(cls); + REQUIRE(cls->members.size == 3); + + auto priv = cls->members.data[0].get_if(); + REQUIRE(priv); + CHECK(priv->functionName == "_helper"); + CHECK(priv->access == AstClassAccess::Private); + + auto pub = cls->members.data[1].get_if(); + REQUIRE(pub); + CHECK(pub->access == AstClassAccess::Public); + + // A method with no qualifier at all is public. + auto unqualified = cls->members.data[2].get_if(); + REQUIRE(unqualified); + CHECK(!unqualified->qualifierLocation.has_value()); + CHECK(unqualified->access == AstClassAccess::Public); +} + +TEST_CASE_FIXTURE(Fixture, "class_private_field_access") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + class Point + function getX(self) return self._x end + end + )"); + + REQUIRE(result.errors.empty()); + + const AstExprIndexName* index = getMethodReturnIndexName(result); + REQUIRE(index); + CHECK(index->index == "_x"); + CHECK(index->op == '.'); + CHECK(index->privateAccess); +} + +TEST_CASE_FIXTURE(Fixture, "class_private_method_call") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + class Point + function getMag(self) + return self:_mag() + end + end + )"); + + REQUIRE(result.errors.empty()); + + REQUIRE(result.root->body.size == 1); + const AstStatClass* cls = result.root->body.data[0]->as(); + REQUIRE(cls); + REQUIRE(cls->members.size == 1); + + auto method = cls->members.data[0].get_if(); + REQUIRE(method); + REQUIRE(method->function->body->body.size == 1); + + const AstStatReturn* ret = method->function->body->body.data[0]->as(); + REQUIRE(ret); + REQUIRE(ret->list.size == 1); + + const AstExprCall* call = ret->list.data[0]->as(); + REQUIRE(call); + CHECK(call->self); + + const AstExprIndexName* func = call->func->as(); + REQUIRE(func); + CHECK(func->index == "_mag"); + CHECK(func->op == ':'); + CHECK(func->privateAccess); +} + +TEST_CASE_FIXTURE(Fixture, "class_private_access_in_nested_closure") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + class Point + function each(self) + return function() return self._x end + end + end + )"); + + REQUIRE(result.errors.empty()); + + REQUIRE(result.root->body.size == 1); + const AstStatClass* cls = result.root->body.data[0]->as(); + REQUIRE(cls); + REQUIRE(cls->members.size == 1); + + auto method = cls->members.data[0].get_if(); + REQUIRE(method); + REQUIRE(method->function->body->body.size == 1); + + const AstStatReturn* outerReturn = method->function->body->body.data[0]->as(); + REQUIRE(outerReturn); + REQUIRE(outerReturn->list.size == 1); + + const AstExprFunction* closure = outerReturn->list.data[0]->as(); + REQUIRE(closure); + REQUIRE(closure->body->body.size == 1); + + const AstStatReturn* innerReturn = closure->body->body.data[0]->as(); + REQUIRE(innerReturn); + REQUIRE(innerReturn->list.size == 1); + + const AstExprIndexName* index = innerReturn->list.data[0]->as(); + REQUIRE(index); + CHECK(index->privateAccess); +} + +TEST_CASE_FIXTURE(Fixture, "class_private_access_only_inside_method_body") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + class Point + end + local t = {} + return t._x + )"); + + REQUIRE(result.errors.empty()); + + REQUIRE(result.root->body.size == 3); + const AstStatReturn* ret = result.root->body.data[2]->as(); + REQUIRE(ret); + REQUIRE(ret->list.size == 1); + + const AstExprIndexName* index = ret->list.data[0]->as(); + REQUIRE(index); + CHECK(index->index == "_x"); + CHECK(!index->privateAccess); +} + +TEST_CASE_FIXTURE(Fixture, "class_metamethod_access_is_not_private") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + // `__`-prefixed names are metamethods and stay public even inside a method body. + // tests/conformance/classes.luau relies on this: it calls Animal.__tostring(self) + // from within a method. + ParseResult result = tryParse(R"( + class Point + function describe(self) return self.__tostring end + end + )"); + + REQUIRE(result.errors.empty()); + + const AstExprIndexName* index = getMethodReturnIndexName(result); + REQUIRE(index); + CHECK(index->index == "__tostring"); + CHECK(!index->privateAccess); +} + +TEST_CASE_FIXTURE(Fixture, "private_class_field_must_begin_with_underscore") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + matchParseError( + R"( +class Hello + private x: number +end + )", + "Private class properties must begin with '_'" + ); + + matchParseError( + R"( +class Hello + private function helper(self) end +end + )", + "Private class properties must begin with '_'" + ); +} + +TEST_CASE_FIXTURE(Fixture, "private_class_field_cannot_start_with_double_underscore") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + matchParseError( + R"( +class Hello + private __x: number +end + )", + "Private class properties cannot start with '__'" + ); + + // Takes precedence over the metamethod allowlist: `__eq` is a valid metamethod name, but not a valid private field name. + matchParseError( + R"( +class Hello + private function __eq(self, other) end +end + )", + "Private class properties cannot start with '__'" + ); +} + +TEST_CASE_FIXTURE(Fixture, "public_class_field_cannot_begin_with_underscore") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + matchParseError( + R"( +class Hello + public _x: number +end + )", + "Public class properties cannot begin with '_'" + ); + + matchParseError( + R"( +class Hello + public function _helper(self) end +end + )", + "Public class properties cannot begin with '_'" + ); + + // An unqualified method is public, so the same rule applies. + matchParseError( + R"( +class Hello + function _helper(self) end +end + )", + "Public class properties cannot begin with '_'" + ); +} + +TEST_CASE_FIXTURE(Fixture, "public_metamethods_are_allowed") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + class Hello + function __tostring(self) return "hello" end + end + )"); + + CHECK(result.errors.empty()); +} + +TEST_CASE_FIXTURE(Fixture, "class_cannot_declare_more_than_256_private_properties") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = "class Hello\n"; + for (int i = 0; i < 257; i++) + source += " private _p" + std::to_string(i) + "\n"; + source += "end\n"; + + matchParseError(source, "Exceeded the maximum of 255 private fields in a class"); +} + +TEST_CASE_FIXTURE(Fixture, "class_cannot_declare_more_than_256_private_methods") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = "class Hello\n"; + for (int i = 0; i < 257; i++) + source += " private function _m" + std::to_string(i) + "(self) end\n"; + source += "end\n"; + + matchParseError(source, "Exceeded the maximum of 255 private methods in a class"); +} + TEST_CASE_FIXTURE(Fixture, "expr_group_with_cst") { ParseOptions parseOptions; diff --git a/tests/PrettyPrinter.test.cpp b/tests/PrettyPrinter.test.cpp index f558a9936..8550d1c17 100644 --- a/tests/PrettyPrinter.test.cpp +++ b/tests/PrettyPrinter.test.cpp @@ -2329,6 +2329,25 @@ end CHECK_EQ(code, prettyPrint(code, {}, true).code); } +TEST_CASE("class_with_private_members") +{ + ScopedFastFlag fflag{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string code = R"( +class Point + private _x: number + public y: number + private function _mag(self) + return self._x + end + public function getMag(self) + return self:_mag() + end +end + )"; + CHECK_EQ(code, prettyPrint(code, {}, true).code); +} + TEST_CASE("prettyPrint_function_attributes") { ScopedFastFlag sff{FFlag::LuauExportValueSyntax, true}; diff --git a/tests/RuntimeLimits.test.cpp b/tests/RuntimeLimits.test.cpp index 97f2c502e..26a6943e4 100644 --- a/tests/RuntimeLimits.test.cpp +++ b/tests/RuntimeLimits.test.cpp @@ -503,7 +503,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "test_generic_pruning_recursion_limit") print(scale.Do.Re.Mi) end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("({ read Do: { read Re: { read Mi: T } } }) -> ()", toString(requireType("get"))); } diff --git a/tests/ToDot.test.cpp b/tests/ToDot.test.cpp index 6c7a4f851..c10c2bf97 100644 --- a/tests/ToDot.test.cpp +++ b/tests/ToDot.test.cpp @@ -139,8 +139,6 @@ TEST_CASE_FIXTURE(Fixture, "function") local function f(a, ...: string) return a end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(T, ...string) -> T", toString(requireType("f"))); diff --git a/tests/ToString.test.cpp b/tests/ToString.test.cpp index f22afe892..779026ae4 100644 --- a/tests/ToString.test.cpp +++ b/tests/ToString.test.cpp @@ -17,7 +17,6 @@ LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(DebugLuauParseExactTables) LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAG(LuauExportValueSyntax) -LUAU_FASTFLAG(DebugLuauWarnOnUnannotatedTopLevelFunctions) TEST_SUITE_BEGIN("ToString"); @@ -389,8 +388,6 @@ TEST_CASE_FIXTURE(Fixture, "quit_stringifying_type_when_length_is_exceeded") function f3(f) return f or f2 end )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_NO_ERRORS(result); @@ -426,8 +423,6 @@ TEST_CASE_FIXTURE(Fixture, "stringifying_type_is_still_capped_when_exhaustive") function f3(f) return f or f2 end )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_NO_ERRORS(result); @@ -556,7 +551,6 @@ type Foo = typeof(tbl.foo) local u: Foo )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); @@ -576,7 +570,6 @@ TEST_CASE_FIXTURE(Fixture, "generate_friendly_names_for_inferred_generics") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); @@ -598,8 +591,6 @@ TEST_CASE_FIXTURE(Fixture, "toStringDetailed") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); ToStringOptions opts; @@ -638,8 +629,6 @@ TEST_CASE_FIXTURE(Fixture, "toStringGenericPack") function foo(a, b) return a(b) end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ(toString(requireType("foo")), "((T) -> (U...), T) -> (U...)"); } @@ -690,8 +679,6 @@ TEST_CASE_FIXTURE(Fixture, "no_parentheses_around_cyclic_function_type_in_union" local g: F = f )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("t1 where t1 = ((() -> number)?) -> t1?", toString(requireType("g"))); @@ -704,8 +691,6 @@ TEST_CASE_FIXTURE(Fixture, "no_parentheses_around_cyclic_function_type_in_inters local a: ((number) -> ()) & typeof(f) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("((number) -> ()) & t1 where t1 = () -> t1", toString(requireType("a"))); @@ -1316,72 +1301,4 @@ TEST_CASE_FIXTURE(Fixture, "tables_with_indexers_and_props") } } -TEST_CASE_FIXTURE(Fixture, "suggest_syntactically_legal_annotation") -{ - DOES_NOT_PASS_WITH_EXACT_TABLES(); - - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - ScopedFastFlag sff[] = { - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - CheckResult result = check(R"( - export function foo(t) - t.x = 10 - end - )"); - - LUAU_REQUIRE_ERROR_COUNT(1, result); - auto e = findError(result); - REQUIRE(e.has_value()); - CHECK("Type annotation required here. Consider (t: { x: number }) -> ()" == toString(*e)); -} - -TEST_CASE_FIXTURE(Fixture, "dont_suggest_syntactically_illegal_annotation") -{ - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - ScopedFastFlag sff[] = { - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - CheckResult result = check(R"( - export function foo(t) - t.x = is_not_defined - end - )"); - - LUAU_REQUIRE_ERROR_COUNT(2, result); - LUAU_REQUIRE_ERROR(result, UnknownSymbol); - auto e = findError(result); - REQUIRE(e.has_value()); - CHECK("Type annotation required here. Unable to infer the type of this function." == toString(*e)); -} - -TEST_CASE_FIXTURE(Fixture, "dont_suggest_type_that_is_too_long") -{ - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - ScopedFastFlag sff[] = { - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - ScopedFastInt sfi{FInt::LuauTypeMaximumStringifierLength, 3}; - - CheckResult result = check(R"( - export function foo(t) - t.x.x.x.x.x.x = true - end - )"); - - LUAU_REQUIRE_ERROR_COUNT(1, result); - auto e = findError(result); - REQUIRE(e.has_value()); - CHECK("Type annotation required here. Unable to infer the type of this function." == toString(*e)); -} - TEST_SUITE_END(); diff --git a/tests/TypeFunction.test.cpp b/tests/TypeFunction.test.cpp index 77df3842b..4d5c1b1c0 100644 --- a/tests/TypeFunction.test.cpp +++ b/tests/TypeFunction.test.cpp @@ -209,8 +209,6 @@ TEST_CASE_FIXTURE(Fixture, "add_function_at_work") local c = add("foo", 1) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(2, result); CHECK(toString(requireType("a")) == "number"); CHECK(toString(requireType("b")) == "add"); @@ -292,8 +290,6 @@ TEST_CASE_FIXTURE(Fixture, "internal_functions_raise_errors") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK( toString(result.errors[0]) == @@ -320,8 +316,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "type_functions_can_be_shadowed") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK(toString(requireType("hi")) == "(string) -> string"); @@ -902,8 +896,6 @@ local function Use(Mode) end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1066,8 +1058,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cyclic_metatable_should_not_crash_index") type IndexFromT = index )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(2, result); CHECK_EQ("Type 't' does not have key 'p'", toString(result.errors[0])); CHECK_EQ("Property '\"p\"' does not exist on type 't'", toString(result.errors[1])); @@ -2081,7 +2071,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2144_type_instantiation_on_type_function local t: any = {} local _b = access<<"Member1">>(t, "Member1") )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("number", toString(requireType("_b"))); @@ -2124,14 +2114,12 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "exporting_erroneous_type_function_is_error_t )"; CheckResult aResult = getFrontend().check("game/A"); - ignoreMissingAnnotations(aResult); LUAU_REQUIRE_ERROR_COUNT(3, aResult); CheckResult bResult = check(R"( local Test = require(game.A); local x = Test.get("hello", "world") )"); - ignoreMissingAnnotations(bResult); LUAU_REQUIRE_NO_ERRORS(bResult); CHECK(toString(requireType("x")) == "*error-type*"); diff --git a/tests/TypeFunction.user.test.cpp b/tests/TypeFunction.user.test.cpp index 50c95e4ac..f48c67177 100644 --- a/tests/TypeFunction.user.test.cpp +++ b/tests/TypeFunction.user.test.cpp @@ -11,7 +11,6 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauForceOldSolver) -LUAU_FASTFLAG(LuauTypeFunctionSerializeArgNames) LUAU_FASTFLAG(LuauIntegerType2) LUAU_DYNAMIC_FASTINT(LuauTypeFunctionSerdeIterationLimit) LUAU_FASTFLAG(LuauUdtfFixTypeNameTypo) @@ -1666,7 +1665,6 @@ end local a = test() )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK(toString(requireType("a")) == R"("hi")"); @@ -1920,7 +1918,6 @@ type test = typeof(m) local function ok(idx: pass): test return idx end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -2113,7 +2110,6 @@ type test = typeof(m) local function ok(idx: pass): (T) -> (U) return idx end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -3184,7 +3180,6 @@ type function test(t: type) return t end TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_identity_preserves_parameter_names") { ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; - ScopedFastFlag serializeArgNames{FFlag::LuauTypeFunctionSerializeArgNames, true}; CheckResult result = check(R"( type function identity(t) diff --git a/tests/TypeInfer.aliases.test.cpp b/tests/TypeInfer.aliases.test.cpp index c46582b45..6651696e5 100644 --- a/tests/TypeInfer.aliases.test.cpp +++ b/tests/TypeInfer.aliases.test.cpp @@ -37,8 +37,6 @@ TEST_CASE_FIXTURE(Fixture, "cyclic_function_type_in_type_alias") local g: F = f )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("t1 where t1 = () -> t1?", toString(requireType("g"))); } @@ -383,8 +381,6 @@ TEST_CASE_FIXTURE(Fixture, "corecursive_types_generic") CHECK_EQ(expected, decorateWithTypes(code)); CheckResult result = check(code); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -668,8 +664,6 @@ end export type f = typeof(get()) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -683,8 +677,6 @@ end export type f = typeof(get()) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -751,8 +743,6 @@ TEST_CASE_FIXTURE(Fixture, "free_variables_from_typeof_in_aliases") type ContainsContainsFree = { that: ContainsFree } )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -803,8 +793,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "do_not_quantify_unresolved_aliases") export type Key = typeof(newkey(newKeyPool(), 1)) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -843,8 +831,6 @@ TEST_CASE_FIXTURE(Fixture, "forward_declared_alias_is_not_clobbered_by_prior_uni local d: FutureType = { smth = true } -- missing error, 'd' is resolved to 'any' )"); - ignoreMissingAnnotations(result); - CHECK_EQ("{ foo: number }", toString(requireType("d"), {true})); LUAU_REQUIRE_ERROR_COUNT(1, result); diff --git a/tests/TypeInfer.annotations.test.cpp b/tests/TypeInfer.annotations.test.cpp index 692574ca5..20cf0d70c 100644 --- a/tests/TypeInfer.annotations.test.cpp +++ b/tests/TypeInfer.annotations.test.cpp @@ -88,8 +88,6 @@ TEST_CASE_FIXTURE(Fixture, "assignments_to_unannotated_parameters_can_transform_ end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK("(unknown) -> number" == toString(requireType("f"))); @@ -106,8 +104,6 @@ TEST_CASE_FIXTURE(Fixture, "assignments_to_annotated_parameters_are_checked") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK(Location{{2, 16}, {2, 17}} == result.errors[0].location); @@ -150,8 +146,6 @@ TEST_CASE_FIXTURE(Fixture, "function_parameters_can_have_annotations") local four = double(2) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -165,8 +159,6 @@ TEST_CASE_FIXTURE(Fixture, "function_parameter_annotations_are_checked") local four = double("two") )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); } @@ -454,8 +446,6 @@ TEST_CASE_FIXTURE(Fixture, "type_annotations_inside_function_bodies") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); dumpErrors(result); } @@ -619,8 +609,6 @@ TEST_CASE_FIXTURE(Fixture, "typeof_expr") local m: typeof(id(77)) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("number", toString(requireType("m"))); } @@ -975,8 +963,6 @@ TEST_CASE_FIXTURE(Fixture, "pulling_a_type_from_value_dont_falsely_create_occurs end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/TypeInfer.anyerror.test.cpp b/tests/TypeInfer.anyerror.test.cpp index 5cb7302cf..fb57f4c17 100644 --- a/tests/TypeInfer.anyerror.test.cpp +++ b/tests/TypeInfer.anyerror.test.cpp @@ -148,8 +148,6 @@ TEST_CASE_FIXTURE(Fixture, "for_in_loop_iterator_is_error2") end )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { // CLI-97375(awe): `bar()` is returning `nil` here, which isn't wrong necessarily, @@ -355,8 +353,6 @@ function T:construct(index) end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/TypeInfer.builtins.test.cpp b/tests/TypeInfer.builtins.test.cpp index 0a68ffff1..509d2e410 100644 --- a/tests/TypeInfer.builtins.test.cpp +++ b/tests/TypeInfer.builtins.test.cpp @@ -137,8 +137,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "sort_with_predicate") table.sort(t, p) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -560,8 +558,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "coroutine_resume_anything_goes") local answer = coroutine.resume(co, 3) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -611,8 +607,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "string_format_arg_types_inference") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(number, number, string) -> string", toString(requireType("f"))); } @@ -670,8 +664,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "string_format_tostring_specifier_type_constr end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(string) -> string", toString(requireType("f"))); } @@ -1110,8 +1102,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "assert_removes_falsy_types") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -1141,8 +1131,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "assert_removes_falsy_types3") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) CHECK_EQ("((boolean | number)?) -> number | true", toString(requireType("f"))); @@ -1442,8 +1430,6 @@ local function f(x: string) end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1703,7 +1689,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "string_find_should_not_crash") end end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -1747,8 +1733,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_clone_should_not_break") return Immutable )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1764,8 +1748,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_clone_should_not_break_2") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/TypeInfer.classes.test.cpp b/tests/TypeInfer.classes.test.cpp index f4287d787..1944d241e 100644 --- a/tests/TypeInfer.classes.test.cpp +++ b/tests/TypeInfer.classes.test.cpp @@ -532,7 +532,7 @@ TEST_CASE_FIXTURE(ClassesFixture, "class_refers_to_later_type_alias") return f.bar end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(Foo) -> number | string", toString(requireType("getbar"))); @@ -555,7 +555,7 @@ TEST_CASE_FIXTURE(ClassesFixture, "accept_read_only_tables") return Foo(tbl) end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("({ bar: number }) -> Foo", toString(requireType("ofnumbertbl"))); @@ -1105,37 +1105,6 @@ TEST_CASE_FIXTURE(ClassesFixture, "variadic_constructor_with_leading_positional_ CHECK(13 == result.errors[0].location.begin.line); } -TEST_CASE_FIXTURE(ClassesFixture, "class_methods_should_be_annotated_except_for_self") -{ - CheckResult result = check(R"( - class Foo - public x: number - - function __init(self, x) - self.x = x - end - - function double(this) - return Foo(this.x * 2) - end - - function double2(self): Foo - return Foo(self.x * 2) - end - end - )"); - - LUAU_REQUIRE_ERROR_COUNT(3, result); - CHECK_ERROR_IS(result.errors.at(0), TypeAnnotationRequired); - // We can't figure out the multiplication - CHECK_ERROR_IS(result.errors.at(1), UninhabitedTypeFunction); - CHECK_ERROR_IS(result.errors.at(2), TypeAnnotationRequired); - - CHECK(4 == result.errors.at(0).location.begin.line); - CHECK(9 == result.errors.at(1).location.begin.line); - CHECK(8 == result.errors.at(2).location.begin.line); -} - TEST_CASE_FIXTURE(ClassesFixture, "fuzzer_duplicate_class_definition") { CheckResult result = check(R"( @@ -1215,7 +1184,7 @@ TEST_CASE_FIXTURE(ClassesFixture, "fuzzer_self_referential_class_definition") { CheckResult result = check(R"( class l0 - public _:typeof(l0) + public l1:typeof(l0) end )"); @@ -1253,7 +1222,7 @@ TEST_CASE_FIXTURE(ClassesFixture, "prop_with_typeof_reassigned_class") class Animal end Animal = nil class l0 -public _:typeof(Animal) +public l1:typeof(Animal) end )" ); diff --git a/tests/TypeInfer.const.test.cpp b/tests/TypeInfer.const.test.cpp index d43cc74b8..bff2c09fe 100644 --- a/tests/TypeInfer.const.test.cpp +++ b/tests/TypeInfer.const.test.cpp @@ -142,8 +142,6 @@ TEST_CASE_FIXTURE(Fixture, "const_recursive_function_works") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) CHECK_EQ("(unknown) -> ()", toString(requireType("f"))); @@ -165,8 +163,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "const_tables_are_still_mutable") return TABLE )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (FFlag::DebugLuauForceOldSolver) CHECK_EQ("{| TAU: number, callback: (number, string) -> boolean, foobar: string |}", toString(requireType("TABLE"), {/* exhaustive */ true})); diff --git a/tests/TypeInfer.externTypes.test.cpp b/tests/TypeInfer.externTypes.test.cpp index 2bdb8416c..84f34dd0a 100644 --- a/tests/TypeInfer.externTypes.test.cpp +++ b/tests/TypeInfer.externTypes.test.cpp @@ -145,8 +145,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "we_can_report_when_someone_is_trying_to_us makeClone(oopsies) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); TypeMismatch* tm = get(result.errors.at(0)); REQUIRE(tm != nullptr); @@ -175,8 +173,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "we_can_report_when_someone_is_trying_to_us makeClone(oopsies) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); TypeMismatch* tm = get(result.errors.at(0)); REQUIRE(tm != nullptr); @@ -323,8 +319,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "higher_order_function_return_values_are_co end) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -340,8 +334,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "higher_order_function_return_type_is_not_c end) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -406,8 +398,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "table_class_unification_reports_sane_error foo(a) )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_ERROR_COUNT(1, result); @@ -465,8 +455,6 @@ local b = foo b(a) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); @@ -916,8 +904,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "cyclic_tables_are_assumed_to_be_compatible c.Touched:Connect(onTouch) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1031,8 +1017,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "extern_type_check_key_becomes_never") end )"); - ignoreMissingAnnotations(results); - LUAU_REQUIRE_NO_ERRORS(results); CHECK_EQ("(Bing | Foobar) -> Bing", toString(requireType("update"))); } @@ -1056,8 +1040,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "extern_type_check_key_becomes_intersection") end )"); - ignoreMissingAnnotations(results); - LUAU_REQUIRE_NO_ERRORS(results); CHECK_EQ("(Foobar) -> Foobar & { read IsEnabled: string }", toString(requireType("update"))); } @@ -1079,8 +1061,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "extern_type_check_key_superset") end )"); - ignoreMissingAnnotations(results); - LUAU_REQUIRE_NO_ERRORS(results); CHECK_EQ("(Foobar) -> Foobar", toString(requireType("update"))); } @@ -1102,8 +1082,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "extern_type_check_key_idempotent") end )"); - ignoreMissingAnnotations(results); - LUAU_REQUIRE_NO_ERRORS(results); CHECK_EQ("(Foobar) -> Foobar", toString(requireType("update"))); } @@ -1141,7 +1119,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "extern_type_with_indexer_intersect_table") return obj end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(Foobar) -> Foobar & { read Baz: number }", toString(requireType("update"))); @@ -1303,7 +1281,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_intersected_against_extern_type_2") return Ownership end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(number) -> { PlayerData: { Settings: { Audio: Folder & { } } } }", toString(requireType("Spread"))); diff --git a/tests/TypeInfer.functions.test.cpp b/tests/TypeInfer.functions.test.cpp index 3a9f81e71..ff50d10a1 100644 --- a/tests/TypeInfer.functions.test.cpp +++ b/tests/TypeInfer.functions.test.cpp @@ -23,7 +23,6 @@ LUAU_FASTINT(LuauTarjanChildLimit) LUAU_FASTFLAG(LuauCheckFunctionStatementTypes) LUAU_FASTFLAG(LuauBidirectionalInferenceBetterLambdaHandling) LUAU_FASTFLAG(LuauExportValueSyntax) -LUAU_FASTFLAG(DebugLuauWarnOnUnannotatedTopLevelFunctions) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) LUAU_FASTFLAG(LuauDoNotLeakGenericsInIndexer) @@ -48,8 +47,6 @@ local Foo = {bar = "$$$"} f({[Foo.bar] = 0}) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -64,8 +61,6 @@ TEST_CASE_FIXTURE(Fixture, "overload_resolution") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); TypeId t = requireType("foo"); const FunctionType* fooType = get(requireType("foo")); @@ -78,8 +73,6 @@ TEST_CASE_FIXTURE(Fixture, "tc_function") { CheckResult result = check("function five() return 5 end"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* fiveType = get(requireType("five")); @@ -150,8 +143,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_return_type") { CheckResult result = check("function take_five() return 5 end"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* takeFiveType = get(requireType("take_five")); @@ -167,8 +158,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_from_function_return_type") { CheckResult result = check("function take_five() return 5 end local five = take_five()"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK("number" == toString(requireType("five"))); @@ -184,8 +173,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_that_function_does_not_return_a_table") take_five().prop = 888 )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ(result.errors[0], (TypeError{Location{Position{5, 8}, Position{5, 24}}, NotATable{getBuiltins()->numberType}})); } @@ -221,7 +208,6 @@ TEST_CASE_FIXTURE(Fixture, "vararg_functions_should_allow_calls_of_any_types_and f("foo", 2) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -245,8 +231,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "vararg_function_is_quantified") return T )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); auto r = first(getMainModule()->returnType); @@ -384,8 +368,6 @@ TEST_CASE_FIXTURE(Fixture, "too_many_arguments_error_location") getmyfunction()() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(2, result); { @@ -424,8 +406,6 @@ TEST_CASE_FIXTURE(Fixture, "recursive_function") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -450,8 +430,6 @@ TEST_CASE_FIXTURE(Fixture, "recursive_local_function") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -470,8 +448,6 @@ TEST_CASE_FIXTURE(Fixture, "another_recursive_local_function") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -499,8 +475,6 @@ TEST_CASE_FIXTURE(Fixture, "cyclic_function_type_in_rets") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("t1 where t1 = () -> t1", toString(requireType("f"))); } @@ -522,8 +496,6 @@ TEST_CASE_FIXTURE(Fixture, "another_higher_order_function") )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -538,8 +510,6 @@ TEST_CASE_FIXTURE(Fixture, "another_other_higher_order_function") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } else @@ -550,8 +520,6 @@ TEST_CASE_FIXTURE(Fixture, "another_other_higher_order_function") d:foo() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } } @@ -573,8 +541,6 @@ TEST_CASE_FIXTURE(Fixture, "local_function") local h = g() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); TypeId h = follow(requireType("h")); @@ -611,8 +577,6 @@ TEST_CASE_FIXTURE(Fixture, "first_argument_can_be_optional") local m = T.new() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); dumpErrors(result); } @@ -625,8 +589,6 @@ TEST_CASE_FIXTURE(Fixture, "it_is_ok_not_to_supply_enough_retvals") local a = get_two() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); dumpErrors(result); } @@ -719,8 +681,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_higher_order_function") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* ftv = get(requireType("apply")); @@ -758,8 +718,6 @@ TEST_CASE_FIXTURE(Fixture, "higher_order_function_2") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* ftv = get(requireType("bottomupmerge")); @@ -798,8 +756,6 @@ TEST_CASE_FIXTURE(Fixture, "higher_order_function_3") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); // FIXME CLI-180636: Previously, the generic leaking from `swap` caused this @@ -847,8 +803,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "higher_order_function_4") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); /* @@ -1020,8 +974,6 @@ TEST_CASE_FIXTURE(Fixture, "report_exiting_without_return_strict") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(2, result); FunctionExitsWithoutReturning* annotatedErr = get(result.errors[0]); CHECK(annotatedErr); @@ -1164,8 +1116,6 @@ TEST_CASE_FIXTURE(Fixture, "too_many_return_values") local a, b = f() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CountMismatch* acm = get(result.errors[0]); @@ -1231,8 +1181,6 @@ TEST_CASE_FIXTURE(Fixture, "ignored_return_values") local a = f() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(0, result); } @@ -1280,8 +1228,6 @@ TEST_CASE_FIXTURE(Fixture, "function_cast_error_uses_correct_language") local c: (string, number)->number = foo -- no error )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(2, result); auto tm1 = get(result.errors[0]); @@ -1315,8 +1261,6 @@ TEST_CASE_FIXTURE(Fixture, "no_lossy_function_type") -- | Column 14 )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); TypeId type = requireTypeAtPosition(Position(6, 14)); if (!FFlag::DebugLuauForceOldSolver) @@ -1580,8 +1524,6 @@ TEST_CASE_FIXTURE(Fixture, "variadic_any_is_compatible_with_a_generic_TypePack") local g = function(...) return f(...) end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1814,8 +1756,6 @@ TEST_CASE_FIXTURE(Fixture, "inferred_higher_order_functions_are_quantified_at_th end )"); - ignoreMissingAnnotations(result); - // LUAU_REQUIRE_NO_ERRORS is particularly unhelpful when this test is broken. // You get a TypeMismatch error where both types stringify the same. @@ -1888,8 +1828,6 @@ TEST_CASE_FIXTURE(Fixture, "too_few_arguments_variadic") test(1) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); auto err = result.errors[0]; @@ -1966,8 +1904,6 @@ TEST_CASE_FIXTURE(Fixture, "occurs_check_failure_in_function_return_type") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK(nullptr != get(result.errors[0])); @@ -2007,8 +1943,6 @@ TEST_CASE_FIXTURE(Fixture, "dont_infer_parameter_types_for_functions_from_their_ local f = t.f )"); - ignoreMissingAnnotations(result); - CHECK_EQ("(T) -> T", toString(requireType("f"))); if (!FFlag::DebugLuauForceOldSolver) @@ -2034,8 +1968,6 @@ TEST_CASE_FIXTURE(Fixture, "dont_mutate_the_underlying_head_of_typepack_when_cal t:m(f()) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -2067,8 +1999,6 @@ local x = (u.a).foo() u.b().foo() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(9, result); if (!FFlag::DebugLuauForceOldSolver) { @@ -2174,8 +2104,6 @@ TEST_CASE_FIXTURE(Fixture, "function_is_supertype_of_concrete_functions") foo(foo) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -2281,8 +2209,6 @@ TEST_CASE_FIXTURE(Fixture, "instantiated_type_packs_must_have_a_non_null_scope") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -2298,8 +2224,6 @@ TEST_CASE_FIXTURE(Fixture, "inner_frees_become_generic_in_dcr") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); std::optional ty = findTypeAtPosition(Position{3, 19}); REQUIRE(ty); @@ -2339,8 +2263,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "param_1_and_2_both_takes_the_same_generic_bu local ret: number = foo(vec2, { x = 5 }) )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_ERROR_COUNT(1, result); @@ -2566,8 +2488,6 @@ TEST_CASE_FIXTURE(Fixture, "generic_packs_are_not_variadic") apply(add, 5) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK(Location{{2, 21}, {2, 22}} == result.errors.at(0).location); auto err = get(result.errors[0]); @@ -2592,8 +2512,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "num_is_solved_before_num_or_str") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ("Expected this to be 'number', but got 'string'", toString(result.errors[0])); @@ -2616,8 +2534,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "num_is_solved_after_num_or_str") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ("Expected this to be 'number', but got 'string'", toString(result.errors[0])); @@ -2634,8 +2550,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "apply_of_lambda_with_inferred_and_explicit_t local x = apply_explicit(function(x: string): number return 5 end, "hello!") )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -2742,8 +2656,6 @@ function odd(n: number) end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(number) -> boolean", toString(requireType("even"))); @@ -2768,8 +2680,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "tf_suggest_return_type") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); auto err = get(result.errors.back()); LUAU_ASSERT(err); @@ -2935,7 +2845,6 @@ TEST_CASE_FIXTURE(Fixture, "function_inference_notes_generic_return") get(u) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(t1) -> () where t1 = { read Find: (t1, string) -> (T...) }", toString(requireType("get"))); @@ -2959,8 +2868,6 @@ TEST_CASE_FIXTURE(Fixture, "dont_infer_overloaded_functions") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -2977,8 +2884,6 @@ TEST_CASE_FIXTURE(Fixture, "param_y_is_bounded_by_x_of_type_string") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK("(string, string) -> ()" == toString(requireType("f"))); @@ -3000,8 +2905,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "function_that_could_return_anything_is_compa a(foo) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -3131,8 +3034,6 @@ TEST_CASE_FIXTURE(Fixture, "unifier_should_not_bind_free_types") end )"); - ignoreMissingAnnotations(result); - // The new solver should ideally be able to do better here, but this is no worse than the old solver. LUAU_REQUIRE_ERROR_COUNT(1, result); auto tm1 = get(result.errors[0]); @@ -3165,8 +3066,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "error_suppression_propagates_through_functio end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK("(any) -> (any?, any)" == toString(requireType("first"))); @@ -3232,8 +3131,6 @@ end local u,v = id(3), id(id(44)) )"); - ignoreMissingAnnotations(result); - CHECK_EQ(getBuiltins()->numberType, requireType("v")); LUAU_REQUIRE_NO_ERRORS(result); } @@ -3285,8 +3182,6 @@ TEST_CASE_FIXTURE(Fixture, "recursive_function_calls_should_not_use_the_generali end )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) LUAU_REQUIRE_NO_ERRORS(result); else @@ -3309,8 +3204,6 @@ TEST_CASE_FIXTURE(Fixture, "recursive_function_calls_should_not_use_the_generali end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -3370,8 +3263,6 @@ TEST_CASE_FIXTURE(Fixture, "table_annotated_explicit_self") end )"); - ignoreMissingAnnotations(results); - LUAU_REQUIRE_ERROR_COUNT(1, results); LUAU_REQUIRE_ERROR(results, FunctionExitsWithoutReturning); // `Foo:fn` should return a `number` CHECK_EQ("MyObject", toString(requireTypeAtPosition({9, 24}))); @@ -3393,7 +3284,7 @@ TEST_CASE_FIXTURE(Fixture, "oss_1871") local _ = Param end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("string", toString(requireTypeAtPosition({8, 25}))); @@ -3428,7 +3319,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "io_manager_oop_ish") return IO )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("IOManager", toString(requireTypeAtPosition({15, 25}))); CHECK_EQ("string", toString(requireTypeAtPosition({16, 25}))); @@ -3453,7 +3344,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "generic_function_statement") return dunno end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("number", toString(requireTypeAtPosition({7, 24}))); @@ -3529,7 +3420,7 @@ TEST_CASE_FIXTURE(Fixture, "call_function_with_nothing_but_nil") f(n) end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -3622,7 +3513,7 @@ TEST_CASE_FIXTURE(Fixture, "bidirectionally_infer_lambda_with_partially_resolved return 42 end) )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("number", toString(requireTypeAtPosition({7, 23}))); @@ -3746,8 +3637,6 @@ TEST_CASE_FIXTURE(Fixture, "overload_selection_union_of_functions") local g = foo(nil :: any) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); // FIXME CLI-180824 @@ -3773,8 +3662,6 @@ TEST_CASE_FIXTURE(Fixture, "overload_selection_needs_to_retry") end )"); - ignoreMissingAnnotations(results); - // FIXME: We do something reasonable and pick the first overload, but this // could be undesirable if, say, there's a later constraint that tells us that // `Color` in `Lightning` is a `string`. @@ -3795,7 +3682,7 @@ TEST_CASE_FIXTURE(Fixture, "overload_selection_unambiguous_with_constraint") f(x, 42) end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(string) -> ()", toString(requireType("g"))); @@ -3956,8 +3843,6 @@ TEST_CASE_FIXTURE(Fixture, "oss_2143") local a = values[1] )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -4041,7 +3926,7 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "bidirectional_function_statement_inference local _ = foobar end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("ClassWithGenericMethod", toString(requireTypeAtPosition({4, 23}))); @@ -4062,7 +3947,7 @@ TEST_CASE_FIXTURE(Fixture, "table_containing_factorial_standalone") return coolmath.factorial(n - 1) * n end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -4085,8 +3970,6 @@ TEST_CASE_FIXTURE(Fixture, "table_containing_factorial_assign_later") coolmath.factorial = function (s: string) end )"); - ignoreMissingAnnotations(results); - LUAU_REQUIRE_ERROR_COUNT(1, results); auto err = get(results.errors[0]); CHECK_EQ("(number) -> number", toString(err->wantedType)); @@ -4110,8 +3993,6 @@ TEST_CASE_FIXTURE(Fixture, "table_containing_factorial_assign_with_correct_typin coolmath.factorial = "not a function" )"); - ignoreMissingAnnotations(results); - // In the future, we should consider disallowing assignment to // table members that were initialized as function statements. // But for now, we allow assignment as long as the type of the @@ -4136,8 +4017,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "recursive_static_method_must_refer_to_the_un end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -4189,8 +4068,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cli_187542_recursive_call_in_loop") end )"); - ignoreMissingAnnotations(result); - // This will have some other errors, but all we care about is that // this finished solving all constraints without forcing any. // FIXME CLI-188000: We infer `a: (never) -> never`, which is incorrect. @@ -4210,8 +4087,6 @@ TEST_CASE_FIXTURE(Fixture, "global_function_redefinition") fact = "huh" )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); auto err = get(result.errors[0]); CHECK_EQ("(number) -> number", toString(err->wantedType)); @@ -4295,7 +4170,6 @@ TEST_CASE_FIXTURE(Fixture, "global_function_blocked") )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -4333,7 +4207,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "lute_tasklib_createtask") return data end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); // FIXME CLI-192091: This is wrong but it's less wrong than before where we @@ -4384,8 +4258,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "are_we_in_the_new_solver") local b = add(vec2.new(0, 0), vec2.new(1, 1)) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("number", toString(requireType("a"))); CHECK_EQ("{ x: number, y: number }", toString(requireType("b"))); @@ -4416,9 +4288,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "dont_leak_generics_keyof") local otherthing = makeThing({b = 42, c = 13}) otherthing.Test("b") otherthing.Test("c") - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("{ Input: { Stuff: { a: number } }, Test: (\"a\") -> () }", toString(requireType("thing"))); CHECK_EQ("{ Input: { Stuff: { b: number, c: number } }, Test: (\"b\" | \"c\") -> () }", toString(requireType("otherthing"))); @@ -4622,8 +4492,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "pass_generic_function_to_pcall") local ok, result = pcall(identity, 42) )"); - - ignoreMissingAnnotations(result); LUAU_CHECK_NO_ERRORS(result); CHECK("number" == toString(requireType("result"))); @@ -4647,197 +4515,6 @@ TEST_CASE_FIXTURE(Fixture, "call_with_any_arg_and_optional_return_arg") CHECK_EQ(result.errors[0].location, Location{{5, 17}, {5, 22}}); } -TEST_CASE_FIXTURE(Fixture, "methods_of_exported_tables_require_annotations") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - CheckResult result = check(R"( - function abs(a: number): number - return if a < 0 then -a else a - end - - export local T = {} - - function T.foo(argumentOne) - return function(y) -- No warning here - return abs(argumentOne), abs(y) - end - end - )"); - - LUAU_CHECK_ERROR_COUNT(1, result); - CHECK(get(result.errors.at(0))); - CHECK((Location{{7, 17}, {7, 35}}) == result.errors.at(0).location); -} - -TEST_CASE_FIXTURE(Fixture, "indicate_an_inferred_generic") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - CheckResult result = check(R"( - export function id(x) - return x - end - )"); - - LUAU_CHECK_ERROR_COUNT(1, result); - CHECK("Type annotation required here. Consider (x: T) -> T" == toString(result.errors.at(0))); -} - -TEST_CASE_FIXTURE(Fixture, "inner_functions_dont_require_annotations") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - CheckResult result = check(R"( - function abs(a: number): number - return if a < 0 then -a else a - end - - export function foo(argumentOne): (number) -> (number, number) - return function(y) -- No warning here - return abs(argumentOne), abs(y) - end - end - - function inner() -- no warning here - end - )"); - - LUAU_CHECK_ERROR_COUNT(1, result); - CHECK((Location{{5, 24}, {5, 70}}) == result.errors.at(0).location); - CHECK("Type annotation required here. Consider (argumentOne: number) -> (number) -> (number, number)" == toString(result.errors.at(0))); -} - -TEST_CASE_FIXTURE(Fixture, "function_return_types_might_require_annotations") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - CheckResult result = check(R"( - function abs(a: number) - return if a < 0 then -a else a - end - - export function foo(argumentOne) - return function(y) -- No warning here - return abs(argumentOne), abs(y) - end - end - - function take_five() - return 5 - end - )"); - - LUAU_CHECK_ERROR_COUNT(3, result); - CHECK((Location{{1, 17}, {1, 31}}) == result.errors.at(0).location); - CHECK((Location{{5, 24}, {5, 40}}) == result.errors.at(1).location); - CHECK((Location{{11, 17}, {11, 28}}) == result.errors.at(2).location); -} - -TEST_CASE_FIXTURE(Fixture, "non_exported_functions_might_also_require_annotations") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - CheckResult result = check(R"( - function abs(a: number): number - return if a < 0 then -a else a - end - - export function foo(argumentOne): (number) -> (number, number) - return function(y) - return abs(argumentOne), abs(y) - end - end - - function inner(_x) - end - )"); - - LUAU_CHECK_ERROR_COUNT(2, result); - CHECK(get(result.errors.at(0))); - CHECK((Location{{5, 24}, {5, 70}}) == result.errors.at(0).location); - - CHECK(get(result.errors.at(1))); - CHECK((Location{{11, 17}, {11, 26}}) == result.errors.at(1).location); -} - -TEST_CASE_FIXTURE(Fixture, "vararg_needs_annotation") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - CheckResult result = check(R"( - export function sum(a, ...): number - if a == nil then - return 0 - else - return a + sum(...) - end - end - - export function sum2(a: number?, ...: number): number - if a == nil then - return 0 - else - return a + sum(...) - end - end - )"); - - LUAU_CHECK_ERROR_COUNT(2, result); - CHECK(get(result.errors.at(0))); - CHECK((Location{{5, 23}, {5, 35}}) == result.errors.at(0).location); - - CHECK(get(result.errors.at(1))); - CHECK((Location{{1, 24}, {1, 43}}) == result.errors.at(1).location); -} - -TEST_CASE_FIXTURE(Fixture, "vararg_specified_but_inferred_empty") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauExportValueSyntax, true}, - {FFlag::DebugLuauWarnOnUnannotatedTopLevelFunctions, true}, - }; - - CheckResult result = check(R"( - local abs: (number) -> number = function(a: number) - return if a < 0 then -a else a - end - - export function abs2(a: number, ...) - return abs(a, ...) - end - )"); - - LUAU_CHECK_ERROR_COUNT(1, result); - CHECK(get(result.errors.at(0))); - CHECK((Location{{5, 24}, {5, 44}}) == result.errors.at(0).location); -} - TEST_CASE_FIXTURE(Fixture, "semantic_subtyping_not_working") { ScopedFastFlag _{FFlag::LuauRefactorStringSemanticSubtyping, true}; @@ -4848,8 +4525,6 @@ TEST_CASE_FIXTURE(Fixture, "semantic_subtyping_not_working") local function f(a) return a end local function g(a) s(f(a)) end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -4868,8 +4543,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2623_double_negate_string") local node: Foo = { tag = "str" } )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -5069,8 +4742,6 @@ TEST_CASE_FIXTURE(Fixture, "let_generalization_second_layer") local g = f(42) local h = f("hmmm") )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("number", toString(requireType("g"), {true})); @@ -5111,8 +4782,6 @@ TEST_CASE_FIXTURE(Fixture, "weakoptional_reduces_over_generic") return r end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); // TODO CLI-195995: This does not seem right, we should be inferring: @@ -5136,8 +4805,6 @@ TEST_CASE_FIXTURE(Fixture, "generalize_type_in_if_body_scope") end end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -5154,8 +4821,6 @@ TEST_CASE_FIXTURE(Fixture, "extend_typepack_bound_indirection_preserves_referenc local n: number? = g() end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/TypeInfer.generics.test.cpp b/tests/TypeInfer.generics.test.cpp index fff90188d..2b6a7bbfe 100644 --- a/tests/TypeInfer.generics.test.cpp +++ b/tests/TypeInfer.generics.test.cpp @@ -185,8 +185,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "inferred_local_vars_can_be_polytypes") local y: number = f(37) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -199,8 +197,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "local_vars_can_be_instantiated_polytypes") local g: (string)->string = id )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -288,8 +284,6 @@ TEST_CASE_FIXTURE(Fixture, "check_mutual_generic_functions_unannotated") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -312,8 +306,6 @@ TEST_CASE_FIXTURE(Fixture, "check_mutual_generic_functions_errors") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(4, result); // odd errors @@ -402,8 +394,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_generic_function") local y: number = id(37) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); TypeId idType = requireType("id"); @@ -428,8 +418,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_generic_local_function") local y: number = id(37) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); TypeId idType = requireType("id"); @@ -533,8 +521,6 @@ TEST_CASE_FIXTURE(Fixture, "dont_leak_generic_types") local b: boolean = f(true) )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_NO_ERRORS(result); @@ -559,8 +545,6 @@ TEST_CASE_FIXTURE(Fixture, "dont_leak_inferred_generic_types") end )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_NO_ERRORS(result); @@ -666,8 +650,6 @@ TEST_CASE_FIXTURE(Fixture, "rank_N_types_via_typeof") local b: number = f(37) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -742,8 +724,6 @@ TEST_CASE_FIXTURE(Fixture, "better_mismatch_error_messages") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(2, result); SwappedGenericTypeParameter* fErr = get(result.errors[0]); SwappedGenericTypeParameter* gErr = get(result.errors[1]); @@ -785,8 +765,6 @@ TEST_CASE_FIXTURE(Fixture, "instantiation_sharing_types") local x2, y2, z2 = o2.x, o2.y, o2.z )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK(requireType("x1") != requireType("x2")); CHECK(requireType("y1") == requireType("y2")); @@ -802,8 +780,6 @@ TEST_CASE_FIXTURE(Fixture, "quantification_sharing_types") local z2 = g(true, "hi") )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK(requireType("z1") == requireType("z2")); } @@ -1088,8 +1064,6 @@ end wrapper(test) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); if (!FFlag::DebugLuauForceOldSolver) { @@ -1116,8 +1090,6 @@ end wrapper(test2, 1, "", 3) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); if (!FFlag::DebugLuauForceOldSolver) { @@ -1144,8 +1116,6 @@ end wrapper(test2, 1, "") )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1162,8 +1132,6 @@ TEST_CASE_FIXTURE(Fixture, "generic_argument_pack_type_inferred_from_return") wrapper(test2, 1) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); if (!FFlag::DebugLuauForceOldSolver) @@ -1192,8 +1160,6 @@ end wrapper(test2, "hello") )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1222,8 +1188,6 @@ wrapper(foo, test2) -- not ok (not enough args) wrapper(foo, test2, "3") -- not ok (type mismatch, string instead of number) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(3, result); if (!FFlag::DebugLuauForceOldSolver) { @@ -1263,8 +1227,6 @@ TEST_CASE_FIXTURE(Fixture, "generic_function") local b = id(nil) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(T) -> T", toString(requireType("id"))); @@ -1282,8 +1244,6 @@ TEST_CASE_FIXTURE(Fixture, "generic_table_method") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); TypeId tType = requireType("T"); @@ -1321,8 +1281,6 @@ TEST_CASE_FIXTURE(Fixture, "correctly_instantiate_polymorphic_member_functions") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); dumpErrors(result); @@ -1404,8 +1362,6 @@ TEST_CASE_FIXTURE(Fixture, "instantiate_generic_function_in_assignments") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); TypeMismatch* tm = get(result.errors[0]); @@ -1433,8 +1389,6 @@ TEST_CASE_FIXTURE(Fixture, "instantiate_generic_function_in_assignments2") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); TypeMismatch* tm = get(result.errors[0]); @@ -1506,8 +1460,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "infer_generic_function_function_argument") return sum(2, 3, function(a: T, b: T): add return a + b end) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } else @@ -1519,8 +1471,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "infer_generic_function_function_argument") return sum(2, 3, function(a, b) return a + b end) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } } @@ -1559,8 +1509,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "infer_generic_function_function_argument_3") local r = foldl(a, {s=0,c=0}, function(a: {s: number, c: number}, b: number) return {s = a.s + b, c = a.c + 1} end) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) REQUIRE_EQ("{ c: number, s: number } | { c: number, s: number }", toString(requireType("r"))); @@ -1658,8 +1606,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "do_not_infer_generic_functions") )"); } - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1826,8 +1772,6 @@ return function(array: {T}): {T} end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -2151,8 +2095,6 @@ TEST_CASE_FIXTURE(Fixture, "ensure_that_invalid_generic_instantiations_error_1") local b = insert(a, "five") )"); - ignoreMissingAnnotations(res); - LUAU_REQUIRE_ERROR_COUNT(1, res); CHECK(get(res.errors[0])); } @@ -2276,9 +2218,7 @@ TEST_CASE_FIXTURE(Fixture, "id_function_do_not_leak_generic") local function foo(x) id(x) end - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(unknown) -> ()", toString(requireType("foo"))); } @@ -2314,9 +2254,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cli_185450_instantiate_generics_prior_to_pus function Child:Func() if math.random() > 0.5 then return self else return nil end end - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_SUITE_END(); diff --git a/tests/TypeInfer.intersectionTypes.test.cpp b/tests/TypeInfer.intersectionTypes.test.cpp index c9438f23b..036cd7b27 100644 --- a/tests/TypeInfer.intersectionTypes.test.cpp +++ b/tests/TypeInfer.intersectionTypes.test.cpp @@ -26,8 +26,6 @@ TEST_CASE_FIXTURE(Fixture, "select_correct_union_fn") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(((number) -> string) & ((string) -> number)) -> (string, number)", toString(requireType("foo"))); @@ -94,8 +92,6 @@ TEST_CASE_FIXTURE(Fixture, "fx_intersection_as_argument") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -139,8 +135,6 @@ TEST_CASE_FIXTURE(Fixture, "should_still_pick_an_overload_whose_arguments_are_un end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(((number) -> string) & ((string) -> number)) -> (string, number)", toString(requireType("foo"))); @@ -180,8 +174,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_an_intersection_type_with_property_guarante end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -201,8 +193,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_an_intersection_type_works_at_arbitrary_dep end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -222,8 +212,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_an_intersection_type_with_mixed_types") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -243,8 +231,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_an_intersection_type_with_one_part_missing_ end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(A & B) -> number", toString(requireType("f"))); } @@ -260,8 +246,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_an_intersection_type_with_one_property_of_t end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(A & B) -> any", toString(requireType("f"))); } @@ -1338,8 +1322,6 @@ TEST_CASE_FIXTURE(Fixture, "less_greedy_unification_with_intersection_types") end )"); - ignoreMissingAnnotations(result); - // We have one error here for the parameter being reduced to never, and // then three bits of extra information indicating the three upper // bound contributors: `{ x: number }`, `{ x: string }`, and `{ x: a }` @@ -1360,8 +1342,6 @@ TEST_CASE_FIXTURE(Fixture, "less_greedy_unification_with_intersection_types_2") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("({ x: number } & { x: string }) -> never", toString(requireType("f"))); @@ -1379,8 +1359,6 @@ function f(x: Foo) end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1396,8 +1374,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "index_property_table_intersection_2") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/TypeInfer.loops.test.cpp b/tests/TypeInfer.loops.test.cpp index f764b92a0..914bec71b 100644 --- a/tests/TypeInfer.loops.test.cpp +++ b/tests/TypeInfer.loops.test.cpp @@ -257,7 +257,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "for_in_with_just_one_iterator_is_ok") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -290,7 +289,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "for_in_with_a_custom_iterator_should_type_ch end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); } @@ -309,7 +307,6 @@ TEST_CASE_FIXTURE(Fixture, "for_in_loop_on_error") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(2, result); TypeId p = requireType("p"); @@ -424,7 +421,6 @@ TEST_CASE_FIXTURE(Fixture, "for_in_loop_with_incompatible_args_to_iterator") end )"); - ignoreMissingAnnotations(result); // TODO, CLI-177651: The rough bidirectional rule with for-in loops ought to be: // @@ -457,7 +453,6 @@ TEST_CASE_FIXTURE(Fixture, "for_in_loop_with_custom_iterator") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); TypeMismatch* tm = get(result.errors[0]); @@ -536,7 +531,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "varlist_declared_by_for_in_loop_should_be_fr end )"); - ignoreMissingAnnotations(result); if (!FFlag::DebugLuauForceOldSolver) { @@ -684,7 +678,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "unreachable_code_after_infinite_loop") unreachablecodepath(4) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(0, result); } @@ -701,7 +694,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "unreachable_code_after_infinite_loop") reachablecodepath(4) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERRORS(result); CHECK(get(result.errors[0])); } @@ -718,7 +710,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "unreachable_code_after_infinite_loop") unreachablecodepath(4) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(0, result); } @@ -736,7 +727,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "unreachable_code_after_infinite_loop") reachablecodepath(4) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERRORS(result); CHECK(get(result.errors[0])); } @@ -753,7 +743,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "unreachable_code_after_infinite_loop") unreachablecodepath(4) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(0, result); } } @@ -1012,7 +1001,6 @@ TEST_CASE_FIXTURE(Fixture, "iterate_over_free_table") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -1043,7 +1031,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "dcr_iteration_minimized_fragmented_keys_1") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -1057,7 +1044,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "dcr_iteration_minimized_fragmented_keys_2") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -1071,7 +1057,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "dcr_iteration_minimized_fragmented_keys_3") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -1110,7 +1095,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "dcr_iteration_fragmented_keys") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -1443,7 +1427,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "while_loop_error_in_body") return x end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("() -> string", toString(requireType("foo"))); @@ -1466,7 +1449,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "while_loop_assign_different_type") return x end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("() -> string?", toString(requireType("foo"))); diff --git a/tests/TypeInfer.metatableOOP.test.cpp b/tests/TypeInfer.metatableOOP.test.cpp index 4602b5229..fb6080023 100644 --- a/tests/TypeInfer.metatableOOP.test.cpp +++ b/tests/TypeInfer.metatableOOP.test.cpp @@ -40,8 +40,6 @@ TEST_CASE_FIXTURE(Fixture, "dont_suggest_using_colon_rather_than_dot_if_not_defi someTable.Function1() -- Argument count mismatch )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); REQUIRE(get(result.errors[0])); } @@ -67,8 +65,6 @@ TEST_CASE_FIXTURE(Fixture, "dont_suggest_using_colon_rather_than_dot_if_it_wont_ someTable.Function2() -- Argument count mismatch )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); REQUIRE(get(result.errors[0])); } @@ -116,8 +112,6 @@ TEST_CASE_FIXTURE(Fixture, "methods_are_topologically_sorted") local a, b = T:foo() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); dumpErrors(result); @@ -242,8 +236,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "object_constructor_can_refer_to_method_of_se -- foo.fooConn() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -334,8 +326,6 @@ function test() end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -444,8 +434,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "react_style_oo") local hello = i.props.hello )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK("string" == toString(requireType("iName"))); @@ -578,8 +566,6 @@ TEST_CASE_FIXTURE(Fixture, "method_should_not_create_cyclic_type") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -602,8 +588,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cross_module_metatable") CheckResult result = getFrontend().check("game/B"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); ModulePtr b = getFrontend().moduleResolver.getModule("game/B"); @@ -643,8 +627,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "textbook_class_pattern") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -690,8 +672,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "textbook_class_pattern_2") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -717,9 +697,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oop_invoke_with_inferred_self_type") local container = ItemContainer.new() container:removeItem(0, "magic") - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "oop_invoke_with_inferred_self_and_property") @@ -745,9 +723,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oop_invoke_with_inferred_self_and_property") local container = ItemContainer.new("library") container:removeItem(0, "magic") - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_field_allows_upcast") diff --git a/tests/TypeInfer.modules.test.cpp b/tests/TypeInfer.modules.test.cpp index 4e2cfe036..af06e4db0 100644 --- a/tests/TypeInfer.modules.test.cpp +++ b/tests/TypeInfer.modules.test.cpp @@ -302,8 +302,6 @@ end return m )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -655,9 +653,7 @@ return ReactShallowRenderer CheckResult result = check(R"( local ReactShallowRenderer = require(game.A); - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "untitled_segfault_number_13") @@ -688,9 +684,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "untitled_segfault_number_13") CheckResult result = check(R"( local _ = require(game.A); - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "spooky_blocked_type_laundered_by_bound_type") @@ -749,8 +743,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "spooky_blocked_type_laundered_by_bound_type" local _ = require(game.A); )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -781,8 +773,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "leaky_generics") return Cache )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK("(unknown) -> unknown" == toString(requireTypeAtPosition({13, 23}))); @@ -850,8 +840,6 @@ return wrapper(test2, 1, "") CheckResult result = getFrontend().check("game/B"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1147,13 +1135,9 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "exported_module_mutual_recursive_functions") )"; CheckResult aResult = getFrontend().check("game/A"); - - ignoreMissingAnnotations(aResult); LUAU_REQUIRE_NO_ERRORS(aResult); CheckResult bResult = getFrontend().check("game/B"); - - ignoreMissingAnnotations(bResult); LUAU_REQUIRE_NO_ERRORS(bResult); ModulePtr b = getFrontend().moduleResolver.getModule("game/B"); @@ -1287,12 +1271,10 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "exported_multret") CheckResult aResult = getFrontend().check("game/A"); - ignoreMissingAnnotations(aResult); LUAU_REQUIRE_NO_ERRORS(aResult); CheckResult bResult = getFrontend().check("game/B"); - ignoreMissingAnnotations(bResult); LUAU_REQUIRE_NO_ERRORS(bResult); ModulePtr b = getFrontend().moduleResolver.getModule("game/B"); @@ -1325,12 +1307,10 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "exported_partial_multret") CheckResult aResult = getFrontend().check("game/A"); - ignoreMissingAnnotations(aResult); LUAU_REQUIRE_NO_ERRORS(aResult); CheckResult bResult = getFrontend().check("game/B"); - ignoreMissingAnnotations(bResult); LUAU_REQUIRE_NO_ERRORS(bResult); ModulePtr b = getFrontend().moduleResolver.getModule("game/B"); diff --git a/tests/TypeInfer.negations.test.cpp b/tests/TypeInfer.negations.test.cpp index dc75d7cb1..90f014ec1 100644 --- a/tests/TypeInfer.negations.test.cpp +++ b/tests/TypeInfer.negations.test.cpp @@ -62,7 +62,6 @@ TEST_CASE_FIXTURE(Fixture, "cofinite_strings_can_be_compared_for_equality") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK("(string) -> string" == toString(requireType("f"))); } diff --git a/tests/TypeInfer.operators.test.cpp b/tests/TypeInfer.operators.test.cpp index 204514eaa..4a894e8e9 100644 --- a/tests/TypeInfer.operators.test.cpp +++ b/tests/TypeInfer.operators.test.cpp @@ -116,8 +116,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "primitive_arith_no_metatable") end local n, s = add(2,"3") )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* functionType = get(requireType("add")); @@ -148,8 +146,6 @@ TEST_CASE_FIXTURE(Fixture, "primitive_arith_possible_metatable") end local t = add(1,2) )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("any", toString(requireType("t"))); } @@ -213,8 +209,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "typecheck_overloaded_multiply_that_is_an_int local d = a * 2 local e = a * 'cabbage' )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK("Vec3" == toString(requireType("a"))); @@ -252,8 +246,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "typecheck_overloaded_multiply_that_is_an_int local d = 2 * a local e = 'cabbage' * a )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK("Vec3" == toString(requireType("a"))); @@ -324,8 +316,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cannot_indirectly_compare_types_that_do_not_ local b = M.new() local c = a < b )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); if (!FFlag::DebugLuauForceOldSolver) @@ -355,8 +345,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cannot_compare_tables_that_do_not_have_the_s local c = a < b -- line 10 local d = b < a -- line 11 )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(2, result); REQUIRE_EQ((Location{{10, 18}, {10, 23}}), result.errors[0].location); @@ -379,8 +367,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "produce_the_correct_error_message_when_compa local b = {} local c = a < b -- line 10 )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); auto err = get(result.errors[0]); @@ -535,8 +521,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "compound_assign_metatable_with_changing_retu local u = t + 3 t += 3 )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); TypeMismatch* tm = get(result.errors[0]); @@ -563,8 +547,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "compound_assign_result_must_be_compatible_wi v += x -- okay: number + x -> number x += v -- not okay: x "); @@ -1680,9 +1628,7 @@ local function sortKeysForPrinting(a: any, b) -- sort the rest by type name return typeofA < typeofB end -)"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); +)"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "compare_singleton_string_to_string") @@ -1699,8 +1645,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "compare_singleton_string_to_string") end )"); - ignoreMissingAnnotations(result); - // There is a flag to gate turning this off, and this warning is not // implemented in the new solver, so assert there are no errors. LUAU_REQUIRE_NO_ERRORS(result); diff --git a/tests/TypeInfer.provisional.test.cpp b/tests/TypeInfer.provisional.test.cpp index 13ccac463..5bd023826 100644 --- a/tests/TypeInfer.provisional.test.cpp +++ b/tests/TypeInfer.provisional.test.cpp @@ -173,8 +173,6 @@ TEST_CASE_FIXTURE(Fixture, "weirditer_should_not_loop_forever") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -191,8 +189,6 @@ TEST_CASE_FIXTURE(Fixture, "it_should_be_agnostic_of_actual_size") f(3, 2, 1, 0) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -415,8 +411,6 @@ TEST_CASE_FIXTURE(Fixture, "specialization_binds_with_prototypes_too_early") local s2s: (string) -> string = id )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) LUAU_REQUIRE_NO_ERRORS(result); else @@ -508,8 +502,6 @@ TEST_CASE_FIXTURE(Fixture, "dcr_can_partially_dispatch_a_constraint") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); // Solving this requires recognizing that we can't dispatch a constraint @@ -888,8 +880,6 @@ TEST_CASE_FIXTURE(Fixture, "lookup_prop_of_intersection_containing_unions_of_tab end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); // LUAU_REQUIRE_ERROR_COUNT(1, result); @@ -1074,8 +1064,6 @@ end CheckResult result = getFrontend().check("Module/Map"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1180,8 +1168,6 @@ TEST_CASE_FIXTURE(Fixture, "luau_roact_useState_nilable_state_1") end )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) LUAU_REQUIRE_NO_ERRORS(result); else @@ -1306,8 +1292,6 @@ TEST_CASE_FIXTURE(Fixture, "we_cannot_infer_functions_that_return_inconsistently end )"); - ignoreMissingAnnotations(result); - #if 0 // This #if block describes what should happen. LUAU_CHECK_NO_ERRORS(result); @@ -1430,9 +1414,7 @@ TEST_CASE_FIXTURE(Fixture, "indexing_union_of_indexers") ) return t[true] end - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "unions_should_work_with_bidirectional_typechecking") @@ -1457,8 +1439,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "unions_should_work_with_bidirectional_typech bark{ [molly] = { left = laika }, [draco] = { right = cindy } } )"); - ignoreMissingAnnotations(result); - // FIXME(CLI-178738): This should actually be no errors. LUAU_REQUIRE_ERROR_COUNT(2, result); diff --git a/tests/TypeInfer.refinements.test.cpp b/tests/TypeInfer.refinements.test.cpp index ffece4dcd..a7cef940c 100644 --- a/tests/TypeInfer.refinements.test.cpp +++ b/tests/TypeInfer.refinements.test.cpp @@ -15,7 +15,6 @@ LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) LUAU_FASTFLAG(DebugLuauCFG) -LUAU_FASTFLAG(LuauCannotAddIndexerToTablePrimitive) LUAU_FASTFLAG(LuauIterativeTypeSearcher) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauRefineNotNilWaitsForBlockedTarget) @@ -370,8 +369,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "typeguard_in_assert_position") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -517,7 +514,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "indexing_unknown_refined_to_table_reports_mi DOES_NOT_PASS_WITH_EXACT_TABLES(); ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; - ScopedFastFlag fix{FFlag::LuauCannotAddIndexerToTablePrimitive, true}; CheckResult result = check(R"( local empty: {} = {} @@ -628,8 +624,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "call_to_undefined_method_is_not_a_refinement end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); auto unknownProp = get(result.errors[0]); @@ -661,8 +655,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "call_an_incompatible_function_after_using_ty end )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_ERROR_COUNT(1, result); @@ -843,8 +835,6 @@ TEST_CASE_FIXTURE(Fixture, "free_type_is_equal_to_an_lvalue") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -931,8 +921,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "type_narrow_to_vector") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -1085,8 +1073,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "type_guard_narrowed_into_nothingness") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -1247,8 +1233,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "merge_should_be_fully_agnostic_of_hashmap_or end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("string", toString(requireTypeAtPosition({6, 28}))); @@ -1280,8 +1264,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "is_truthy_constraint_ifelse_expression") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("string", toString(requireTypeAtPosition({2, 29}))); @@ -1296,8 +1278,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "invert_is_truthy_constraint_ifelse_expressio end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("nil", toString(requireTypeAtPosition({2, 42}))); @@ -1320,8 +1300,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "type_comparison_ifelse_expression") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -1530,8 +1508,6 @@ TEST_CASE_FIXTURE(Fixture, "and_or_peephole_refinement") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1583,8 +1559,6 @@ TEST_CASE_FIXTURE(Fixture, "refine_a_property_not_to_be_nil_through_an_intersect end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1820,8 +1794,6 @@ TEST_CASE_FIXTURE(RefinementExternTypeFixture, "isa_type_refinement_must_be_know end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -1909,8 +1881,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "typeguard_doesnt_leak_to_elseif") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -2020,8 +1990,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "what_nonsensical_condition") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("never", toString(requireTypeAtPosition({3, 28}))); @@ -2282,8 +2250,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "type_annotations_arent_relevant_when_doing_d end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); // Function calls are treated as (potentially) `nil`, the same as table @@ -2372,8 +2338,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_unknown_to_table") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(unknown) -> (~nil, unknown)", toString(requireType("f"))); @@ -2426,8 +2390,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "luau_polyfill_isindexkey_refine_conjunction" end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -2443,8 +2405,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "check_refinement_to_primitive_and_compare") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(unknown) -> boolean", toString(requireType("comesAfterLuau"))); } @@ -2462,8 +2422,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "luau_polyfill_isindexkey_refine_conjunction_ end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -2493,8 +2451,6 @@ TEST_CASE_FIXTURE(RefinementExternTypeFixture, "mutate_prop_of_some_refined_symb end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -3034,8 +2990,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_by_no_refine_should_always_reduce") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -3107,8 +3061,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refinements_from_and_should_not_refine_to_ne end )"); - ignoreMissingAnnotations(results); - LUAU_REQUIRE_NO_ERRORS(results); CHECK_EQ("(Config & { read KeyboardEnabled: false? }) | (Config & { read MouseEnabled: false? })", toString(requireTypeAtPosition({6, 24}))); @@ -3134,8 +3086,6 @@ TEST_CASE_FIXTURE(Fixture, "force_simplify_constraint_doesnt_drop_blocked_type") return isCharacter end )"); - - ignoreMissingAnnotations(results); LUAU_REQUIRE_NO_ERRORS(results); } @@ -3308,8 +3258,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "assert_call_should_not_refine_despite_typeof end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ("Type 'table' does not have key 'bar'", toString(result.errors[0])); } @@ -3358,9 +3306,7 @@ TEST_CASE_FIXTURE(Fixture, "type_function_reduction_with_union_type_application" if time > toolAnimTime then end end - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "refine_any_and_unknown_should_still_be_any") @@ -3378,9 +3324,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_any_and_unknown_should_still_be_any") and __type["$$typeof"] end end - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "cli_181100_fast_track_refinement_against_unknown") @@ -3525,8 +3469,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "unification_with_refinements_doesnt_impact_f table.sort(keys, sorter) )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/TypeInfer.singletons.test.cpp b/tests/TypeInfer.singletons.test.cpp index da168ad88..fcd032e52 100644 --- a/tests/TypeInfer.singletons.test.cpp +++ b/tests/TypeInfer.singletons.test.cpp @@ -149,8 +149,6 @@ TEST_CASE_FIXTURE(Fixture, "overloaded_function_call_with_singletons") g(false, 37) )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -164,8 +162,6 @@ TEST_CASE_FIXTURE(Fixture, "overloaded_function_resolution_singleton_parameters" return f("A"), f("B") end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); TypeId t = requireType("foo"); const FunctionType* fooType = get(requireType("foo")); @@ -858,9 +854,7 @@ TEST_CASE_FIXTURE(Fixture, "pass_singleton_through_to_identity") local function foobar(): "hello" return id("hello") end - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "singleton_when_type_is_blocked") @@ -871,9 +865,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "singleton_when_type_is_blocked") local function foobar() return id("hello") end - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/TypeInfer.tables.test.cpp b/tests/TypeInfer.tables.test.cpp index cbac72a67..523c5264e 100644 --- a/tests/TypeInfer.tables.test.cpp +++ b/tests/TypeInfer.tables.test.cpp @@ -24,7 +24,6 @@ LUAU_FASTFLAG(LuauInstantiateInSubtyping) LUAU_FASTFLAG(LuauFixIndexerSubtypingOrdering) LUAU_FASTFLAG(DebugLuauAssertOnForcedConstraint) LUAU_FASTINT(LuauPrimitiveInferenceInTableLimit) -LUAU_FASTFLAG(LuauPropertyModifierMismatchErrors) LUAU_FASTFLAG(LuauRemoveConstraintSolverEmplace) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) LUAU_FASTFLAG(DebugLuauParseExactTables) @@ -195,7 +194,6 @@ TEST_CASE_FIXTURE(Fixture, "cannot_augment_sealed_table") t.foo = 'bar' )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); TypeError& err = result.errors[0]; @@ -271,7 +269,6 @@ TEST_CASE_FIXTURE(Fixture, "function_calls_can_produce_tables") { CheckResult result = check("function get_table() return {prop=999} end get_table().prop = 0"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -282,7 +279,6 @@ TEST_CASE_FIXTURE(Fixture, "function_calls_produces_sealed_table_given_unsealed_ f().foo = 'fail' )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); } @@ -290,7 +286,6 @@ TEST_CASE_FIXTURE(Fixture, "tc_member_function") { CheckResult result = check("local T = {} function T:foo() return 5 end"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); const TableType* tableType = get(requireType("T")); @@ -308,7 +303,6 @@ TEST_CASE_FIXTURE(Fixture, "tc_member_function_2") { CheckResult result = check("local T = {U={}} function T.U:foo() return 5 end"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); const TableType* tableType = get(requireType("T")); @@ -349,7 +343,6 @@ TEST_CASE_FIXTURE(Fixture, "call_method") local a = T:method() )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK("number" == toString(requireType("a"))); @@ -368,7 +361,6 @@ TEST_CASE_FIXTURE(Fixture, "call_method_with_explicit_self_argument") local a = T.method(T) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -422,7 +414,6 @@ TEST_CASE_FIXTURE(Fixture, "used_dot_instead_of_colon_but_correctly") local a = T.method(T, 6, 7) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -520,7 +511,6 @@ TEST_CASE_FIXTURE(Fixture, "table_param_width_subtyping_1") foo({x=55, y=nil, w=3.14159}) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -536,7 +526,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_param_width_subtyping_2") foo({bar='bar'}) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); MissingProperties* error = get(result.errors[0]); @@ -613,7 +602,6 @@ TEST_CASE_FIXTURE(Fixture, "ok_to_add_property_to_free_table") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); dumpErrors(result); } @@ -728,7 +716,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_array_2") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -744,7 +731,6 @@ TEST_CASE_FIXTURE(Fixture, "indexers_get_quantified_too") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -781,7 +767,6 @@ TEST_CASE_FIXTURE(Fixture, "indexers_quantification_2") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* ftv = get(requireType("mergesort")); @@ -838,7 +823,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_indexer_from_value_property_in_literal") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* fType = get(requireType("f")); @@ -996,7 +980,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_type_when_indexing_from_a_table_indexer") local s = f({}) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK("string" == toString(requireType("s"))); @@ -1075,7 +1058,6 @@ TEST_CASE_FIXTURE(Fixture, "disallow_indexing_into_an_unsealed_table_with_no_ind local k1 = getConstant("key1") )"); - ignoreMissingAnnotations(result); if (!FFlag::DebugLuauForceOldSolver) CHECK("unknown" == toString(requireType("k1"))); @@ -1129,7 +1111,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oop_indexer_works") local words = me:speak() )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK("string" == toString(requireType("words"))); @@ -1229,7 +1210,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "meta_add_both_ways_lti") local c = 2 + a )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("Vector", toString(requireType("a"))); @@ -1298,7 +1278,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oop_polymorphic") local speed = scoops:speed() )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK("boolean" == toString(requireType("alive"))); @@ -1380,7 +1359,6 @@ TEST_CASE_FIXTURE(Fixture, "inequality_operators_imply_exactly_matching_types") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(number) -> number", toString(requireType("abs"))); } @@ -1423,7 +1401,6 @@ TEST_CASE_FIXTURE(Fixture, "defining_a_method_for_a_local_sealed_table_must_fail function t.m() end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); } @@ -1435,7 +1412,6 @@ TEST_CASE_FIXTURE(Fixture, "defining_a_self_method_for_a_local_sealed_table_must function t:m() end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); } @@ -1496,7 +1472,6 @@ TEST_CASE_FIXTURE(Fixture, "passing_compatible_unions_to_a_generic_table_without end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -1780,7 +1755,6 @@ TEST_CASE_FIXTURE(Fixture, "casting_sealed_tables_with_props_into_table_with_ind local rt: StringToStringMap = mkrt() )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); ToStringOptions o{/* exhaustive= */ true}; @@ -1834,7 +1808,6 @@ TEST_CASE_FIXTURE(Fixture, "casting_tables_with_props_into_table_with_indexer4") local hi: number = foo({ a = "hi" }, "a") -- shouldn't typecheck since at runtime hi is "hi" )"); - ignoreMissingAnnotations(result); // This typechecks but shouldn't LUAU_REQUIRE_NO_ERRORS(result); } @@ -1909,7 +1882,6 @@ TEST_CASE_FIXTURE(Fixture, "table_subtyping_with_extra_props_dont_report_multipl vec1 = vec3 )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); TypeMismatch* tm = get(result.errors[0]); @@ -2047,7 +2019,6 @@ TEST_CASE_FIXTURE(Fixture, "key_setting_inference_given_nil_upper_bound") t[k] = nil end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ(toString(requireType("setkey_object")), "({ [string]: number }, number) -> ()"); CHECK_EQ(toString(requireType("setkey_constindex")), "({ [string]: number }, number) -> ()"); @@ -2060,7 +2031,6 @@ TEST_CASE_FIXTURE(Fixture, "key_setting_inference_given_nil_upper_bound") on_number(v) end )"); - ignoreMissingAnnotations(result2); LUAU_REQUIRE_NO_ERRORS(result2); CHECK_EQ(toString(requireType("setkey_object")), "({ [string]: number }, number) -> ()"); } @@ -2100,7 +2070,6 @@ TEST_CASE_FIXTURE(Fixture, "reasonable_error_when_adding_a_nonexistent_property_ A.B = "Hello" )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); if (!FFlag::DebugLuauForceOldSolver) @@ -2169,7 +2138,6 @@ TEST_CASE_FIXTURE(Fixture, "hide_table_error_properties") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(2, result); CHECK_EQ("Cannot add property 'a' to table '{ x: number }'", toString(result.errors[0])); @@ -2306,7 +2274,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "quantifying_a_bound_var_works") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); TypeId ty = requireType("clazz"); TableType* ttv = getMutable(ty); @@ -2394,7 +2361,6 @@ TEST_CASE_FIXTURE(Fixture, "invariant_table_properties_means_instantiating_table local c : string = t.m("hi") )"); - ignoreMissingAnnotations(result); if (!FFlag::DebugLuauForceOldSolver) { @@ -2816,7 +2782,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "dont_hang_when_trying_to_look_up_in_cyclic_m end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ("Type 't' does not have key 'p'", toString(result.errors[0])); } @@ -2848,7 +2813,6 @@ TEST_CASE_FIXTURE(Fixture, "confusing_indexing") local foo = f({p = "string"}) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("number | string", toString(requireType("foo"))); } @@ -2866,7 +2830,6 @@ TEST_CASE_FIXTURE(Fixture, "pass_a_union_of_tables_to_a_function_that_requires_a local b = f(a) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver && FFlag::DebugLuauExactTableTypes) @@ -2890,7 +2853,6 @@ TEST_CASE_FIXTURE(Fixture, "pass_a_union_of_tables_to_a_function_that_requires_a local b = f(a) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver && FFlag::DebugLuauExactTableTypes) @@ -3059,7 +3021,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_unifies_into_map") )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -3106,7 +3067,6 @@ TEST_CASE_FIXTURE(Fixture, "generalize_table_argument") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* fooType = get(requireType("foo")); @@ -3156,7 +3116,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "dont_quantify_table_that_belongs_to_outer_sc print(self:incr()) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); TableType* counterType = getMutable(requireType("Counter")); @@ -3195,7 +3154,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "instantiate_tables_at_scope_level") return Option )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -3577,7 +3535,6 @@ function t.x(value) end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -3602,7 +3559,6 @@ TEST_CASE_FIXTURE(Fixture, "inferred_properties_of_a_table_should_start_with_the end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -3628,7 +3584,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "dont_leak_free_table_props") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver && FFlag::DebugLuauExactTableTypes) @@ -3770,7 +3725,6 @@ TEST_CASE_FIXTURE(Fixture, "scalar_is_not_a_subtype_of_a_compatible_polymorphic_ f("baz" :: "bar" | "baz") )"); - ignoreMissingAnnotations(result); if (!FFlag::DebugLuauForceOldSolver) { @@ -3857,7 +3811,6 @@ TEST_CASE_FIXTURE(Fixture, "a_free_shape_cannot_turn_into_a_scalar_if_it_is_not_ end )"); - ignoreMissingAnnotations(result); if (!FFlag::DebugLuauForceOldSolver) { @@ -3938,7 +3891,6 @@ TEST_CASE_FIXTURE(Fixture, "invariant_table_properties_means_instantiating_table local c : string = t.m("hi") )"); - ignoreMissingAnnotations(result); if (!FFlag::DebugLuauForceOldSolver) { @@ -3976,7 +3928,6 @@ end local g : ({ p : number, q : string }) -> ({ p : number, r : boolean }) = f )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); if (!FFlag::DebugLuauForceOldSolver) @@ -4253,7 +4204,6 @@ TEST_CASE_FIXTURE(Fixture, "certain_properties_of_table_literal_arguments_can_be }) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -4281,7 +4231,6 @@ TEST_CASE_FIXTURE(Fixture, "subproperties_can_also_be_covariantly_tested") }) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -4373,7 +4322,6 @@ TEST_CASE_FIXTURE(Fixture, "simple_method_definition") return T )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -4475,7 +4423,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_write_property") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK("({ y: number, ... }) -> ()" == toString(requireType("f"))); @@ -4627,7 +4574,6 @@ TEST_CASE_FIXTURE(Fixture, "write_to_unusually_named_read_only_property") TEST_CASE_FIXTURE(Fixture, "read_only_property_with_type_mismatch_reports_both_errors") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag sff{FFlag::LuauPropertyModifierMismatchErrors, true}; // When a property is both read-only AND has a type mismatch, both issues are reported // independently so the user knows they need to fix both. @@ -4647,7 +4593,6 @@ TEST_CASE_FIXTURE(Fixture, "read_only_property_with_type_mismatch_reports_both_e TEST_CASE_FIXTURE(Fixture, "read_only_property_subtype_mismatch_error_message") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag sff{FFlag::LuauPropertyModifierMismatchErrors, true}; CheckResult result = check(R"( local function f(t: { read woof: number }): { woof: number } @@ -4669,7 +4614,6 @@ TEST_CASE_FIXTURE(Fixture, "read_only_property_subtype_mismatch_error_message") TEST_CASE_FIXTURE(Fixture, "write_only_property_subtype_mismatch_error_message") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag sff{FFlag::LuauPropertyModifierMismatchErrors, true}; CheckResult result = check(R"( local function f(t: { write woof: number }): { woof: number } @@ -4937,7 +4881,6 @@ TEST_CASE_FIXTURE(Fixture, "table_writes_introduce_write_properties") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK( @@ -4980,7 +4923,6 @@ TEST_CASE_FIXTURE(Fixture, "refined_thing_can_be_an_array") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK("({T}, T) -> T" == toString(requireType("foo"))); } @@ -4997,7 +4939,6 @@ TEST_CASE_FIXTURE(Fixture, "parameter_was_set_an_indexer_and_bounded_by_string") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(3, result); CHECK_EQ("Parameter 't' has been reduced to never. This function is not callable with any possible value.", toString(result.errors[0])); @@ -5022,7 +4963,6 @@ TEST_CASE_FIXTURE(Fixture, "parameter_was_set_an_indexer_and_bounded_by_another_ end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); // FIXME CLI-114134. We need to simplify types more consistently. @@ -5162,7 +5102,6 @@ TEST_CASE_FIXTURE(Fixture, "setindexer_multiple_tables_intersection") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(2, result); CHECK("({ [string]: number } & { [thread]: boolean }, never) -> ()" == toString(requireType("f"))); } @@ -5180,7 +5119,6 @@ TEST_CASE_FIXTURE(Fixture, "insert_a_and_f_of_a_into_table_res_in_a_loop") end )"); - ignoreMissingAnnotations(result); if (!FFlag::DebugLuauForceOldSolver) { @@ -5430,7 +5368,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_union_type") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ( "Cannot add indexer to table 'setmetatable<(nil & ~(false?)) | { }, t1> where t1 = { new: (T) -> setmetatable<(T & ~(false?)) | { }, " @@ -5640,7 +5577,6 @@ TEST_CASE_FIXTURE(Fixture, "empty_union_container_overflow") } end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -5652,7 +5588,6 @@ TEST_CASE_FIXTURE(Fixture, "inference_in_constructor") return t end )"); - ignoreMissingAnnotations(result); LUAU_CHECK_NO_ERRORS(result); CHECK_EQ("(number) -> { x: number }", toString(requireType("new"))); } @@ -5789,7 +5724,6 @@ TEST_CASE_FIXTURE(Fixture, "generic_index_syntax_bidirectional_infer_with_tables } )")); - ignoreMissingAnnotations(result); LUAU_CHECK_ERROR_COUNT(3, result); auto err0 = get(result.errors[0]); REQUIRE(err0); @@ -5828,7 +5762,6 @@ TEST_CASE_FIXTURE(Fixture, "deeply_nested_classish_inference") end end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -6373,7 +6306,6 @@ TEST_CASE_FIXTURE(Fixture, "free_types_with_sealed_table_upper_bounds_can_still_ end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK("({ read nope: () -> (...unknown), ... } & { x: number }) -> ()" == toString(requireType("foo"))); } @@ -6623,7 +6555,6 @@ TEST_CASE_FIXTURE(Fixture, "oss_1953") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); auto err = get(result.errors[0]); CHECK_EQ("kind", err->key); @@ -6785,7 +6716,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "allow_indexing_into_error_or_not_nil") end end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -6934,7 +6864,6 @@ TEST_CASE_FIXTURE(Fixture, "table_inference_one_incorrect_member") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ("(number) -> { x: number, y: string }", toString(requireType("makeTable"))); } @@ -7047,7 +6976,6 @@ TEST_CASE_FIXTURE(Fixture, "large_data_like_array_can_simplify") stream << "end" << '\n'; CheckResult result = check(stream.str()); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("() -> {{ bar: number } | { foo: number } | {number}}", toString(requireType("get"))); } @@ -7201,7 +7129,6 @@ TEST_CASE_FIXTURE(Fixture, "oss_1890") } )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -7455,7 +7382,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "indexer_and_subsequent_constraint") return math.abs(x) end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("({ [string]: number, ... }, string) -> number", toString(requireType("getnumberandabs"))); @@ -7561,7 +7487,6 @@ TEST_CASE_FIXTURE(Fixture, "read_only_indexer_mismatch") { ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauPropertyModifierMismatchErrors, true}, }; CheckResult result = check(R"( @@ -7630,7 +7555,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "normalization_always_intersects_table") end end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -7687,7 +7611,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "test_inferring_generalized_iteration_1") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("({ read RootToDescendantCountMap: { [string?]: number, ... }, ... }) -> ()", toString(requireType("setupRootMappingMove"))); @@ -7707,7 +7630,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "test_inferring_generalized_iteration_2") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("({ read RootToDescendantCountMap: { [T]: U, ... }, ... }) -> ()", toString(requireType("setupRootMappingMove"))); @@ -7923,7 +7845,6 @@ TEST_CASE_FIXTURE(Fixture, "function_calls_preserve_potential_mutations_1") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -7938,7 +7859,6 @@ TEST_CASE_FIXTURE(Fixture, "function_calls_preserve_potential_mutations_2") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -7953,7 +7873,6 @@ TEST_CASE_FIXTURE(Fixture, "function_calls_preserve_potential_mutations_3") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/TypeInfer.test.cpp b/tests/TypeInfer.test.cpp index 69f762d87..04dad61a8 100644 --- a/tests/TypeInfer.test.cpp +++ b/tests/TypeInfer.test.cpp @@ -28,7 +28,6 @@ LUAU_FASTINT(LuauTypeInferRecursionLimit) LUAU_FASTFLAG(DebugLuauMagicTypes) LUAU_FASTFLAG(DebugLuauForbidInternalTypes) LUAU_FASTFLAG(LuauImproveUniqueTableWidthSubtyping) -LUAU_FASTFLAG(LuauDoNotIceForBindingGeneric) using namespace Luau; @@ -134,7 +133,7 @@ TEST_CASE_FIXTURE(Fixture, "infer_locals_via_assignment_from_its_call_site") f("foo") )"); - ignoreMissingAnnotations(result); + if (!FFlag::DebugLuauForceOldSolver) { @@ -224,7 +223,7 @@ TEST_CASE_FIXTURE(Fixture, "statements_are_topologically_sorted") end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); dumpErrors(result); @@ -268,7 +267,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "weird_case") local d = math.deg(f()) )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -294,7 +293,7 @@ TEST_CASE_FIXTURE(Fixture, "occurs_check_does_not_recurse_forever_if_asked_to_tr end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -346,7 +345,7 @@ TEST_CASE_FIXTURE(Fixture, "should_be_able_to_infer_this_without_stack_overflowi end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -381,7 +380,7 @@ TEST_CASE_FIXTURE(Fixture, "exponential_blowup_from_copying_types") return x4 )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); ModulePtr module = getMainModule(); @@ -881,7 +880,7 @@ local function f() end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -919,7 +918,7 @@ local function f(a: (number, number) -> number) return a(1, 3) end f(((function(a, b) return a + b end))) )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -983,7 +982,7 @@ local function times(n: any, f: () -> T) end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -1122,7 +1121,7 @@ local b = getIt() local c = a or b )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -1419,7 +1418,7 @@ function f(x, c) -- x : X end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -1608,7 +1607,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "lti_must_record_contributing_locations") end )"); - ignoreMissingAnnotations(result); + // We inspect the actual errors in other tests; this test verifies that we // actually recorded breadcrumbs for a. @@ -1808,7 +1807,7 @@ TEST_CASE_FIXTURE(Fixture, "avoid_blocking_type_function") return b:upper() end )"); - ignoreMissingAnnotations(result); + LUAU_CHECK_NO_ERRORS(result); } @@ -1894,7 +1893,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "getmetatable_infer_any_ret") return getmetatable(x) end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(any) -> any", toString(requireType("spooky"))); @@ -1971,7 +1969,7 @@ TEST_CASE_FIXTURE(Fixture, "concat_string_with_string_union") return x .. y end )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -2686,8 +2684,6 @@ TEST_CASE_FIXTURE(Fixture, "nested_functions_can_depend_on_outer_generics") local out = funcTest(1) -- Doesn't report type mismatch error anymore )"); - ignoreMissingAnnotations(result); - CHECK("(nil) -> nil" == toString(requireType("funcTest"))); LUAU_REQUIRE_ERROR_COUNT(1, result); @@ -3044,7 +3040,6 @@ TEST_CASE_FIXTURE(Fixture, "generic_P_inference_with_optional_param_does_not_lea createElement(MyComponent, { x = 1 }) )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -3072,7 +3067,7 @@ TEST_CASE_FIXTURE(Fixture, "generic_P_with_intersection_props_and_partial_table" local _x = createElement(Image, { tag = "test" }) )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -3096,7 +3091,7 @@ TEST_CASE_FIXTURE(Fixture, "generic_P_widening_with_recursive_optional_field") end local _x = createElement(View, { tag = "hello" }) )"); - ignoreMissingAnnotations(result); + LUAU_REQUIRE_NO_ERRORS(result); } @@ -3130,8 +3125,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "fuzzer_relate_extern_table_2") TEST_CASE_FIXTURE(BuiltinsFixture, "fuzzer_generic_binding_ice") { - ScopedFastFlag _{FFlag::LuauDoNotIceForBindingGeneric, true}; - LUAU_REQUIRE_ERRORS(check(R"( local l0: any l32 = l0.new { @@ -3142,9 +3135,9 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "fuzzer_generic_binding_ice") _ = n0({fill=_,n33=_,},_,table.find,optional,_(_,_,n0,function,_,optional,""),), n0 = if _ then _, _ = n0({fill=_,n33=_,},_,table.find,optional,_(_,_,n0,function,_,optional,""),), - _ = if _ then _, + _ = if _ then _, n0 = n0({fill=_,n33=_,},_,table.find,optional,_(_,_,n0,function,_,optional,""),), - n0 = if _ then _, + n0 = if _ then _, _ = n0({fill=_,n33=_,},_,table.find,optional,_(_,_,n0,function,_,optional,""),) } )")); diff --git a/tests/TypeInfer.tryUnify.test.cpp b/tests/TypeInfer.tryUnify.test.cpp index a96038fa4..4ed0a435c 100644 --- a/tests/TypeInfer.tryUnify.test.cpp +++ b/tests/TypeInfer.tryUnify.test.cpp @@ -232,7 +232,6 @@ TEST_CASE_FIXTURE(Fixture, "typepack_unification_should_trim_free_tails") end )"); - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ("(number) -> boolean", toString(requireType("f"))); } diff --git a/tests/TypeInfer.typeInstantiations.test.cpp b/tests/TypeInfer.typeInstantiations.test.cpp index 7abe78756..9036a923e 100644 --- a/tests/TypeInfer.typeInstantiations.test.cpp +++ b/tests/TypeInfer.typeInstantiations.test.cpp @@ -73,8 +73,6 @@ TEST_CASE_FIXTURE(Fixture, "as_stmt_correct") f<>(1, "a") )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } } @@ -92,8 +90,6 @@ TEST_CASE_FIXTURE(Fixture, "as_stmt_incorrect") f<>(1, "a") )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_ERROR_COUNT(1, result); @@ -522,8 +518,6 @@ TEST_CASE_FIXTURE(Fixture, "replacing_generic_with_generic") local baz, quxx = bar<>() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("string", toString(requireType("baz"))); CHECK_EQ("number", toString(requireType("quxx"))); diff --git a/tests/TypeInfer.typePacks.test.cpp b/tests/TypeInfer.typePacks.test.cpp index a5f2dd674..9191d01ed 100644 --- a/tests/TypeInfer.typePacks.test.cpp +++ b/tests/TypeInfer.typePacks.test.cpp @@ -23,8 +23,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_multi_return") return 2, 2 end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* takeTwoType = get(requireType("take_two")); @@ -55,8 +53,6 @@ TEST_CASE_FIXTURE(Fixture, "self_and_varargs_should_work") function t:f(...) end t:f(1) )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -71,8 +67,6 @@ TEST_CASE_FIXTURE(Fixture, "last_element_of_return_statement_can_itself_be_a_pac return 1, take_two() end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); dumpErrors(result); @@ -96,8 +90,6 @@ TEST_CASE_FIXTURE(Fixture, "higher_order_function") return f(g(x)) end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) @@ -130,9 +122,7 @@ TEST_CASE_FIXTURE(Fixture, "no_return_size_should_be_zero") g(h()) f(g(),h()) - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); const FunctionType* fTy = get(requireType("f")); REQUIRE(fTy != nullptr); @@ -159,8 +149,6 @@ TEST_CASE_FIXTURE(Fixture, "varargs_inference_through_multiple_scopes") f("foo") )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -177,8 +165,6 @@ TEST_CASE_FIXTURE(Fixture, "multiple_varargs_inference_are_not_confused") f("foo", "bar")(1, 2) )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } @@ -192,8 +178,6 @@ TEST_CASE_FIXTURE(Fixture, "parenthesized_varargs_returns_any") value = ... end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("any", toString(requireType("value"))); } @@ -1121,8 +1105,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "detect_cyclic_typepacks2") _(_,_,_) end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_ERROR_COUNT(2, result); CHECK("Unknown type 't0'" == toString(result.errors[0])); @@ -1226,8 +1208,6 @@ function test(name, searchTerm) local found = string.find(name:lower(), searchTerm:lower()) end )"); - - ignoreMissingAnnotations(result); LUAU_REQUIRE_NO_ERRORS(result); } diff --git a/tests/TypeInfer.typestates.test.cpp b/tests/TypeInfer.typestates.test.cpp index 715df720f..75153aba1 100644 --- a/tests/TypeInfer.typestates.test.cpp +++ b/tests/TypeInfer.typestates.test.cpp @@ -146,8 +146,6 @@ TEST_CASE_FIXTURE(TypeStateFixture, "recursive_local_function") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -159,8 +157,6 @@ TEST_CASE_FIXTURE(TypeStateFixture, "recursive_function") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -216,8 +212,6 @@ TEST_CASE_FIXTURE(TypeStateFixture, "parameter_x_was_constrained_by_two_types_2" end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK("(nil) -> number?" == toString(requireType("f"))); } @@ -231,8 +225,6 @@ TEST_CASE_FIXTURE(TypeStateFixture, "parameter_x_is_some_type_or_optional_then_a end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK("(number?) -> number" == toString(requireType("f"))); } @@ -645,9 +637,7 @@ TEST_CASE_FIXTURE(Fixture, "capture_upvalue_in_returned_function") end return Counter end - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("() -> () -> number", toString(requireType("def"))); } diff --git a/tests/TypeInfer.unionTypes.test.cpp b/tests/TypeInfer.unionTypes.test.cpp index 3f6c3f036..8988f893f 100644 --- a/tests/TypeInfer.unionTypes.test.cpp +++ b/tests/TypeInfer.unionTypes.test.cpp @@ -164,8 +164,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_a_union_type_with_property_guaranteed_to_ex end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(A | B) -> number", toString(requireType("f"))); } @@ -181,8 +179,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_a_union_type_with_mixed_types") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(A | B) -> number | string", toString(requireType("f"))); } @@ -198,8 +194,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_a_union_type_works_at_arbitrary_depth") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(A | B) -> number | string", toString(requireType("f"))); } @@ -215,8 +209,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_a_union_type_with_one_optional_property") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(A | B) -> number?", toString(requireType("f"))); } @@ -232,8 +224,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_a_union_type_with_missing_property") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); MissingUnionProperty* mup = get(result.errors[0]); @@ -257,8 +247,6 @@ TEST_CASE_FIXTURE(Fixture, "index_on_a_union_type_with_one_property_of_type_any" end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("(A | B) -> any", toString(requireType("f"))); } @@ -292,8 +280,6 @@ TEST_CASE_FIXTURE(Fixture, "optional_union_members") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ("Value of type 'A?' could be nil", toString(result.errors[0])); @@ -311,8 +297,6 @@ TEST_CASE_FIXTURE(Fixture, "optional_union_functions") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ("Value of type 'A?' could be nil", toString(result.errors[0])); @@ -330,8 +314,6 @@ TEST_CASE_FIXTURE(Fixture, "optional_union_methods") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); CHECK_EQ("Value of type 'A?' could be nil", toString(result.errors[0])); @@ -347,8 +329,6 @@ TEST_CASE_FIXTURE(Fixture, "optional_union_follow") return f() )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); auto acm = get(result.errors[0]); @@ -622,8 +602,6 @@ TEST_CASE_FIXTURE(Fixture, "dont_allow_cyclic_unions_to_be_inferred") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -661,8 +639,6 @@ TEST_CASE_FIXTURE(Fixture, "indexing_into_a_cyclic_union_doesnt_crash") end )"); - ignoreMissingAnnotations(result); - // this is a cyclic union of number arrays, so it _is_ a table, even if it's a nonsense type. // no need to generate a NotATable error here. The new solver automatically handles this and // correctly reports no errors. @@ -922,8 +898,6 @@ TEST_CASE_FIXTURE(Fixture, "less_greedy_unification_with_union_types") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ( @@ -942,8 +916,6 @@ TEST_CASE_FIXTURE(Fixture, "less_greedy_unification_with_union_types_2") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("({ x: number } | { x: string }) -> number | string", toString(requireType("f"))); @@ -962,8 +934,6 @@ TEST_CASE_FIXTURE(Fixture, "union_table_any_property") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); } @@ -1017,8 +987,6 @@ TEST_CASE_FIXTURE(Fixture, "lookup_prop_of_intersection_containing_unions") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(1, result); const UnknownProperty* unknownProp = get(result.errors[0]); @@ -1113,9 +1081,7 @@ TEST_CASE_FIXTURE(Fixture, "oss_2134") local mapTest = addIndex(map) local mapResult = mapTest(mapWithIndex, myArr) - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(Fixture, "oss_2393") @@ -1137,9 +1103,7 @@ TEST_CASE_FIXTURE(Fixture, "oss_2393") end process(ex) - )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); + )"); LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2025") diff --git a/tests/TypeInfer.unknownnever.test.cpp b/tests/TypeInfer.unknownnever.test.cpp index 52f4995f3..23e365fd6 100644 --- a/tests/TypeInfer.unknownnever.test.cpp +++ b/tests/TypeInfer.unknownnever.test.cpp @@ -118,8 +118,6 @@ TEST_CASE_FIXTURE(Fixture, "type_packs_containing_never_is_itself_uninhabitable" local x, y, z = f() )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_ERROR_COUNT(1, result); @@ -335,8 +333,6 @@ TEST_CASE_FIXTURE(Fixture, "dont_unify_operands_if_one_of_the_operand_is_never_i end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) CHECK_EQ("(nil, nil & ~nil) -> boolean", toString(requireType("ord"))); @@ -352,8 +348,6 @@ TEST_CASE_FIXTURE(Fixture, "math_operators_and_never") end )"); - ignoreMissingAnnotations(result); - if (!FFlag::DebugLuauForceOldSolver) { LUAU_REQUIRE_ERROR_COUNT(1, result); @@ -378,8 +372,6 @@ TEST_CASE_FIXTURE(Fixture, "compare_never") end )"); - ignoreMissingAnnotations(result); - LUAU_CHECK_NO_ERRORS(result); CHECK_EQ("(nil, number) -> boolean", toString(requireType("cmp"))); } @@ -402,8 +394,6 @@ TEST_CASE_FIXTURE(Fixture, "lti_error_at_declaration_for_never_normalizations") end )"); - ignoreMissingAnnotations(result); - LUAU_REQUIRE_ERROR_COUNT(3, result); CHECK(toString(result.errors[0]) == "Parameter 'a' has been reduced to never. This function is not callable with any possible value."); CHECK(toString(result.errors[1]) == "Parameter 'a' is required to be a subtype of 'number' here."); diff --git a/tests/conformance/bitwise.luau b/tests/conformance/bitwise.luau index 430677c5f..94c2ff52c 100644 --- a/tests/conformance/bitwise.luau +++ b/tests/conformance/bitwise.luau @@ -56,6 +56,12 @@ for i = -50, 50 do assert(bit32.lrotate(0x89abcdef, i) == bit32.lrotate(0x89abcdef, i%32)) end +local function lrotateregression1(x: number) + local y = bit32.bxor(x, 0x12345) + return bit32.lrotate(y, y) +end +assert(lrotateregression1(noinline(0)) == 0x2468a0) + assert(bit32.lshift(0x12345678, 4) == 0x23456780) assert(bit32.lshift(0x12345678, 8) == 0x34567800) assert(bit32.lshift(0x12345678, -4) == 0x01234567) diff --git a/tests/conformance/classes.luau b/tests/conformance/classes.luau index 1ab9e7d1e..23977ad38 100644 --- a/tests/conformance/classes.luau +++ b/tests/conformance/classes.luau @@ -968,4 +968,629 @@ expectpass("A class must define a constructor if any ancestor defines one.", fun GrandChildDefinesAConstructor() end) +class PrivatePoint + private _x: number + private _y: number + + function __init(self, x, y) + self._x = x + self._y = y + end + + function getX(self) + return self._x + end + + function getY(self) + return self._y + end + + function setX(self, x) + self._x = x + end +end + +expectpass("private fields are readable and writable from methods of the declaring class", function() + local p = PrivatePoint(3, 4) + assert(p:getX() == 3) + assert(p:getY() == 4) + p:setX(10) + assert(p:getX() == 10) + assert(p:getY() == 4) +end) + +class PartialPrivate + private _a + private _b + + function __init(self, a) + self._a = a + end + + function values(self) + return self._a, self._b + end +end + +expectpass("private fields left uninitialized by the constructor are nil", function() + local a, b = PartialPrivate(1):values() + assert(a == 1) + assert(b == nil) +end) + +class Vec + private _x + private _y + + private function _magnitudeOf(x, y) + return math.sqrt(x * x + y * y) + end + + private function _scaled(self, k) + return Vec(self._x * k, self._y * k) + end + + function __init(self, x, y) + self._x = x + self._y = y + end + + function coords(self) + return self._x, self._y + end + + function magnitude(self) + return Vec._magnitudeOf(self._x, self._y) + end + + function double(self) + return self:_scaled(2) + end +end + +expectpass("private instance methods are callable from methods of the declaring class", function() + local x, y = Vec(3, 4):double():coords() + assert(x == 6 and y == 8) +end) + +expectpass("private static methods are callable from methods of the declaring class", function() + assert(Vec(3, 4):magnitude() == 5) + assert(Vec(0, 0):magnitude() == 0) +end) + +class StaticNamecall + private _x + + -- Namecall syntax on the class object passes the class object itself as the first + -- argument, since there is no instance involved. + private function _receiver(receiver) + return receiver + end + + function __init(self, x) + self._x = x + end + + function staticReceiver(self) + return StaticNamecall:_receiver() + end +end + +expectpass("private static methods are callable on the class object with namecall syntax", function() + local s = StaticNamecall(1) + local receiver = s:staticReceiver() + assert(typeof(receiver) == "class") + assert(receiver == StaticNamecall) +end) + +open class Money + private _cents: number + + function __init(self, cents) + self._cents = cents + end + + -- Private fields of any instance of the enclosing class are available, not just self's. + function __eq(self, other) + return self._cents == other._cents + end + + function plus(self, other) + return Money(self._cents + other._cents) + end + + function cents(self) + return self._cents + end +end + +expectpass("methods can read private fields of any instance of the declaring class", function() + assert(Money(150):plus(Money(25)):cents() == 175) +end) + +expectpass("__eq can read private fields of the other operand", function() + assert(Money(100) == Money(100)) + assert(Money(100) ~= Money(101)) +end) + +class PrivateStringy + private _name + + function __init(self, name) + self._name = name + end + + function __tostring(self) + return `PrivateStringy({self._name})` + end +end + +expectpass("metamethods can read private fields", function() + assert(tostring(PrivateStringy("hi")) == "PrivateStringy(hi)") + assert(`{PrivateStringy("interp")}` == "PrivateStringy(interp)") +end) + +expectfail("private fields are not readable outside the declaring class", "this object does not have a key named '_x'", function() + local p = PrivatePoint(1, 2) + return p._x +end) + +expectfail("private fields are not writable outside the declaring class", "this object does not have a key named '_x'", function() + local p = PrivatePoint(1, 2) + p._x = 5 +end) + +expectfail("private instance methods are not callable outside the declaring class", "this object does not have a key named '_scaled'", function() + return Vec(1, 2):_scaled(2) +end) + +expectfail("private static methods are not accessible on the class object", "this class does not have a key named '_magnitudeOf'", function() + return Vec._magnitudeOf(3, 4) +end) + +class Impostor + public x + public y +end + +expectfail("private field access on an instance of an unrelated class raises", "access private field", function() + -- PrivatePoint.getX reads self._x, so it must reject a receiver that is not a PrivatePoint + -- even though Impostor has similarly-named public fields. + PrivatePoint.getX(Impostor { x = 1, y = 2 }) +end) + +expectfail("private field access on a table raises", "access private field", function() + PrivatePoint.getX({ _x = 1, _y = 2 }) +end) + +expectfail("private field access on a number raises", "access private field", function() + PrivatePoint.getX(42) +end) + +expectfail("private field read on an unrelated class declaring the same private field raises", "access private field", function() + PrivatePoint.getX(Vec(1, 2)) +end) + +expectfail("private field write on an unrelated class declaring the same private field raises", "assign private field", function() + PrivatePoint.setX(Vec(1, 2), 5) +end) + +open class HasPrivateAndConstructor + private _secret + + function __init(self, secret) + self._secret = secret + end + + function secret(self) + return self._secret + end +end + +class DerivesFromPrivateWithConstructor extends HasPrivateAndConstructor + public label + + function __init(self, secret, label) + HasPrivateAndConstructor.__init(self, secret) + self.label = label + end +end + +expectpass("a derived class initializes base private fields by delegating to the base constructor", function() + local d = DerivesFromPrivateWithConstructor("shh", "tag") + assert(d:secret() == "shh") + assert(d.label == "tag") +end) + +open class ShadowBase + private _v + + function __init(self, v) + self._v = v + end + + function baseV(self) + return self._v + end + + function setBaseV(self, v) + self._v = v + end +end + +class ShadowDerived extends ShadowBase + private _v + + function __init(self, baseVal, derivedVal) + ShadowBase.__init(self, baseVal) + self._v = derivedVal + end + + function derivedV(self) + return self._v + end + + function setDerivedV(self, v) + self._v = v + end +end + +expectpass("base and derived private fields with the same name do not collide", function() + local d = ShadowDerived("base", "derived") + assert(d:baseV() == "base") + assert(d:derivedV() == "derived") + d:setDerivedV("derived2") + assert(d:baseV() == "base") + assert(d:derivedV() == "derived2") + d:setBaseV("base2") + assert(d:baseV() == "base2") + assert(d:derivedV() == "derived2") +end) + +open class Vector1 + private _x: number + + function __init(self, x) + self._x = x + end + + function privateX(self) + return self._x + end + + -- Reads of other._x resolve to the private field of Vector1, never to a + -- public field that a subclass happens to declare. + function comparePrivateX(self, other) + return self._x == other._x + end +end + +class Vector1WithPublicX extends Vector1 + public x: number + + function __init(self, privateX, publicX) + Vector1.__init(self, privateX) + self.x = publicX + end +end + +expectpass("a derived class's public field does not shadow the base class's private field", function() + local base = Vector1(5) + local derived = Vector1WithPublicX(5, 99) + assert(derived.x == 99) + assert(derived:privateX() == 5) + -- Base methods still see the private _x of the derived instance, not its public x. + assert(base:comparePrivateX(derived)) + assert(derived:comparePrivateX(base)) + assert(not Vector1(1):comparePrivateX(derived)) +end) + +open class PrivateGrandparent + private _g + + function __init(self, g) + self._g = g + end + + function g(self) + return self._g + end +end + +open class PrivateParent extends PrivateGrandparent + private _p + + function __init(self, g, p) + PrivateGrandparent.__init(self, g) + self._p = p + end + + function p(self) + return self._p + end +end + +class PrivateChild extends PrivateParent + private _c + + function __init(self, g, p, c) + PrivateParent.__init(self, g, p) + self._c = c + end + + function c(self) + return self._c + end +end + +expectpass("private fields are allocated for every class in the ancestry chain", function() + local child = PrivateChild(1, 2, 3) + assert(child:g() == 1) + assert(child:p() == 2) + assert(child:c() == 3) + local parent = PrivateParent(10, 20) + assert(parent:g() == 10) + assert(parent:p() == 20) +end) + +class TableUser + private _data + + function __init(self) + self._data = { _key = "value" } + end + + -- Inside a method body, `.` on an underscore-prefixed name is private property + -- access, so an underscore-prefixed table key must be reached via index notation. + function readKey(self) + return self._data["_key"] + end + + function writeKey(self, v) + self._data["_key"] = v + return self._data["_key"] + end +end + +expectpass("underscore-prefixed table keys are reachable from method bodies via index notation", function() + local t = TableUser() + assert(t:readKey() == "value") + assert(t:writeKey("replaced") == "replaced") +end) + +class PrivateCallback + private _cb + public str: string + + function __init(self, str, prefix) + self._cb = function(self, suffix) + return prefix .. self.str .. suffix + end + self.str = str + end + + function rebind(self, cb) + self._cb = cb + end + + function invoke(self, suffix) + return self:_cb(suffix) + end +end + +expectpass("closures stored in private fields are callable from methods of the declaring class", function() + local c = PrivateCallback("hello ", "prefix-") + assert(c:invoke("world") == "prefix-hello world") + c:rebind(function(self, suffix) + return `prefix-{self.str}{suffix}` + end) + assert(c:invoke("world") == "prefix-hello world") + collectgarbage() + assert(c:invoke("again") == "prefix-hello again") +end) + +expectfail("closures stored in private fields are not callable outside the declaring class", "this object does not have a key named '_cb'", function() + local c = PrivateCallback("hello ", "prefix-") + return c._cb("world") +end) + +expectpass("classof and isinstance work on classes with private fields", function() + local p = PrivatePoint(1, 2) + assert(typeof(p) == "object") + assert(class.classof(p) == PrivatePoint) + assert(class.isinstance(p, PrivatePoint)) + assert(not class.isinstance(p, Vec)) + local d = ShadowDerived("base", "derived") + assert(class.classof(d) == ShadowDerived) + assert(class.isinstance(d, ShadowDerived)) + assert(class.isinstance(d, ShadowBase)) +end) + +class PrivateBox + private _x + + public function __init(self, x) + self._x = x + end + + public function get(self) + return self._x + end + + public function set(self, val) + self._x = val + end +end + +expectpass("classes with private fields have referential equality by default", function() + local b1 = PrivateBox("same") + local b2 = PrivateBox("same") + assert(b1 == b1) + assert(b1 ~= b2) +end) + +expectpass("private fields of an inherited instance survive GC", function() + local kept = {} + for i = 1, 50 do + kept[i] = PrivateChild({i}, {i + 1}, {i + 2}) + if i % 10 == 0 then + collectgarbage() + end + end + collectgarbage() + for i = 1, 50 do + assert(kept[i]:g()[1] == i) + assert(kept[i]:p()[1] == i + 1) + assert(kept[i]:c()[1] == i + 2) + end +end) + +-- 255 is the parser's maximum number of private fields per class, so this class sits +-- exactly on the boundary of what the private field storage must be able to represent. +open class ManyPrivate + private _p1 private _p2 private _p3 private _p4 private _p5 private _p6 private _p7 private _p8 private _p9 private _p10 private _p11 private _p12 private _p13 private _p14 private _p15 private _p16 + private _p17 private _p18 private _p19 private _p20 private _p21 private _p22 private _p23 private _p24 private _p25 private _p26 private _p27 private _p28 private _p29 private _p30 private _p31 private _p32 + private _p33 private _p34 private _p35 private _p36 private _p37 private _p38 private _p39 private _p40 private _p41 private _p42 private _p43 private _p44 private _p45 private _p46 private _p47 private _p48 + private _p49 private _p50 private _p51 private _p52 private _p53 private _p54 private _p55 private _p56 private _p57 private _p58 private _p59 private _p60 private _p61 private _p62 private _p63 private _p64 + private _p65 private _p66 private _p67 private _p68 private _p69 private _p70 private _p71 private _p72 private _p73 private _p74 private _p75 private _p76 private _p77 private _p78 private _p79 private _p80 + private _p81 private _p82 private _p83 private _p84 private _p85 private _p86 private _p87 private _p88 private _p89 private _p90 private _p91 private _p92 private _p93 private _p94 private _p95 private _p96 + private _p97 private _p98 private _p99 private _p100 private _p101 private _p102 private _p103 private _p104 private _p105 private _p106 private _p107 private _p108 private _p109 private _p110 private _p111 private _p112 + private _p113 private _p114 private _p115 private _p116 private _p117 private _p118 private _p119 private _p120 private _p121 private _p122 private _p123 private _p124 private _p125 private _p126 private _p127 private _p128 + private _p129 private _p130 private _p131 private _p132 private _p133 private _p134 private _p135 private _p136 private _p137 private _p138 private _p139 private _p140 private _p141 private _p142 private _p143 private _p144 + private _p145 private _p146 private _p147 private _p148 private _p149 private _p150 private _p151 private _p152 private _p153 private _p154 private _p155 private _p156 private _p157 private _p158 private _p159 private _p160 + private _p161 private _p162 private _p163 private _p164 private _p165 private _p166 private _p167 private _p168 private _p169 private _p170 private _p171 private _p172 private _p173 private _p174 private _p175 private _p176 + private _p177 private _p178 private _p179 private _p180 private _p181 private _p182 private _p183 private _p184 private _p185 private _p186 private _p187 private _p188 private _p189 private _p190 private _p191 private _p192 + private _p193 private _p194 private _p195 private _p196 private _p197 private _p198 private _p199 private _p200 private _p201 private _p202 private _p203 private _p204 private _p205 private _p206 private _p207 private _p208 + private _p209 private _p210 private _p211 private _p212 private _p213 private _p214 private _p215 private _p216 private _p217 private _p218 private _p219 private _p220 private _p221 private _p222 private _p223 private _p224 + private _p225 private _p226 private _p227 private _p228 private _p229 private _p230 private _p231 private _p232 private _p233 private _p234 private _p235 private _p236 private _p237 private _p238 private _p239 private _p240 + private _p241 private _p242 private _p243 private _p244 private _p245 private _p246 private _p247 private _p248 private _p249 private _p250 private _p251 private _p252 private _p253 private _p254 private _p255 + + function __init(self) + self._p1 = 1 + self._p254 = 254 + self._p255 = 255 + end + + function first(self) + return self._p1 + end + + function middle(self) + return self._p128 + end + + function secondToLast(self) + return self._p254 + end + + function last(self) + return self._p255 + end +end + +expectpass("a class can have the maximum number of private fields", function() + local m = ManyPrivate() + assert(m:first() == 1) + assert(m:middle() == nil) + assert(m:secondToLast() == 254) + assert(m:last() == 255) + collectgarbage() + assert(m:last() == 255) +end) + +class OneMorePrivate extends ManyPrivate + private _myPrivate + + function __init(self) + ManyPrivate.__init(self) + self._myPrivate = 256 + end + + function getMyPrivate(self) + return self._myPrivate + end +end + +expectpass("why we need more than 8 bits for number of private instance fields", function() + local p = OneMorePrivate() + assert(p:getMyPrivate() == 256) +end) + +open class Base + public a + + function __init(self, a) self.a = a end +end + +class Child extends Base + private _q + + private function _m1(self) return 1 end + private function _m2(self) return 2 end + private function _m3(self) return 3 end + + function __init(self) + self.a = 0 + self._q = 5 + end + + function sum(self) + return self:_m1() + self:_m2() + self:_m3() + self._q + end +end + +expectpass("Child class with private methods and fields", function() + for i = 1, 100 do + local c = Child() + assert(c:sum() == 11) + end +end) + +open class PrivateWithoutConstructor + private _x + public y + + function getX(self) + return self._x + end +end + +expectfail("a class with private fields must define a constructor", "must define a constructor because it has private fields", function() + PrivateWithoutConstructor { y = 1 } +end) + +class DerivesFromPrivateWithoutConstructor extends PrivateWithoutConstructor + public z +end + +expectfail("a class must define a constructor if a base class has private fields", "must define a constructor because it or a class it inherits from has private fields", function() + DerivesFromPrivateWithoutConstructor { z = 1 } +end) + +open class PublicOnlyBase + public a +end + +class PrivateDerivedFromPublicOnly extends PublicOnlyBase + private _b +end + +expectfail("a derived class with private fields must define a constructor even if its base class does not", "must define a constructor because it or a class it inherits from has private fields", function() + PrivateDerivedFromPublicOnly { a = 1 } +end) + +open class BaseOther + private function _secret(cls) return "secret" end + function create(cls) return cls:_secret() end +end + +class DerivedOther extends BaseOther +end + +expectpass("subclasses can access private static methods of their base class", function() + BaseOther.create(BaseOther) -- class access to private static `_secret` is allowed for base class + BaseOther.create(DerivedOther{}) -- object access to private static `_secret` is allowed for derived object + BaseOther.create(DerivedOther) -- class access to private static `_secret` is allowed for derived class +end) + return 'OK' diff --git a/tests/conformance/integers.luau b/tests/conformance/integers.luau index 9407a68c4..bee907387 100644 --- a/tests/conformance/integers.luau +++ b/tests/conformance/integers.luau @@ -2,6 +2,7 @@ print("testing integers") local function noinline(x: integer): integer local s, r = pcall(function(y) return y end, x) return r end +local function noinlinenum(x: number): number local s, r = pcall(function(y) return y end, x) return r end -- Integers have the 'integer' type assert(type(123i)=="integer") @@ -25,23 +26,31 @@ assert(not rawequal(76i, 32i)) assert(not rawequal(76i, 76)) -- integer.create -assert(typeof(integer.create(4711))=="integer") +assert(typeof(integer.create(4711)) == "integer") + assert(integer.create(4711) == 4711i) assert(integer.create(-3) == -3i) assert(integer.create(1e18) == 1000000000000000000i) assert(integer.create(-1e18) == -1000000000000000000i) +assert(integer.create(noinlinenum(4711)) == 4711i) +assert(integer.create(noinlinenum(-3)) == -3i) +assert(integer.create(noinlinenum(1e18)) == 1000000000000000000i) +assert(integer.create(noinlinenum(-1e18)) == -1000000000000000000i) + -- isolate tests which take a VM exit in native code -function testCreateVmExit() - assert(integer.create(2.5) == nil) - assert(integer.create(1e30) == nil) - assert(integer.create(0/0) == nil) - assert(integer.create(math.huge) == nil) - assert(integer.create(-math.huge) == nil) - assert(integer.create(1.0000000005) == nil) - assert(integer.create(0.9999999995) == nil) +function testCreateVmExit(x) + local y = integer.create(x) + return y end -testCreateVmExit() + +assert(testCreateVmExit(2.5) == nil) +assert(testCreateVmExit(1e30) == nil) +assert(testCreateVmExit(0/0) == nil) +assert(testCreateVmExit(math.huge) == nil) +assert(testCreateVmExit(-math.huge) == nil) +assert(testCreateVmExit(1.0000000005) == nil) +assert(testCreateVmExit(0.9999999995) == nil) -- integer.fromstring assert(integer.fromstring("30") == 30i) @@ -348,6 +357,15 @@ assert(integer.arshift(noinline(512i), 3i) == 64i) assert(integer.arshift(noinline(-256i), 64i) == -1i) assert(integer.arshift(noinline(-1i), -3i) == -8i) +assert(integer.lshift(noinline(12345i), -256i) == 0i) +assert(integer.rshift(noinline(12345i), -256i) == 0i) +assert(integer.lshift(noinline(12345i), 256i) == 0i) +assert(integer.rshift(noinline(12345i), 256i) == 0i) +assert(integer.lshift(noinline(12345i), 0x8000000000000000i) == 0i) +assert(integer.rshift(noinline(12345i), 0x8000000000000000i) == 0i) +assert(integer.arshift(noinline(12345i), -256i) == 0i) +assert(integer.arshift(noinline(-12345i), 256i) == -1i) + -- Rotations assert(integer.lrotate(0x6003000000000000i, 4i) == 0x0030000000000006i) assert(integer.lrotate(0x1000200000000000i, 69i) == 0x0004000000000002i) @@ -401,8 +419,12 @@ assert(not success) assert(string.find(errmsg, "trying to access non%-existent bits")) local success,errmsg = pcall(function() integer.extract(1i, 64i, 1i) end) assert(not success) +assert(string.find(errmsg, "trying to access non%-existent bits")) local success,errmsg = pcall(function() integer.extract(1i, integer.maxsigned, 1i) end) assert(not success) +local success,errmsg = pcall(function() integer.extract(-1i, 1i, integer.maxsigned) end) +assert(not success) +assert(string.find(errmsg, "trying to access non%-existent bits")) -- replace assert(integer.replace(0xBADBEEFi, 0x500Di, 16i, 16i) == 0x500DBEEFi) @@ -426,8 +448,12 @@ assert(not success) assert(string.find(errmsg, "trying to access non%-existent bits")) local success,errmsg = pcall(function() integer.replace(1i, 2i, 64i, 1i) end) assert(not success) +assert(string.find(errmsg, "trying to access non%-existent bits")) local success,errmsg = pcall(function() integer.replace(1i, 2i, integer.maxsigned, 1i) end) assert(not success) +local success,errmsg = pcall(function() integer.replace(0i, -1i, 63i, integer.maxsigned) end) +assert(not success) +assert(string.find(errmsg, "trying to access non%-existent bits")) -- btest assert(not integer.btest(0xAAAAi, 0x5555i)) @@ -466,6 +492,15 @@ assert(integer.bswap(0x0BADBEEFC001D00Di) == 0x0DD001C0EFBEAD0Bi) assert(integer.bswap(noinline(0x1122334455667748i)) == 0x4877665544332211i) assert(integer.bswap(noinline(0x0BADBEEFC001D00Di)) == 0x0DD001C0EFBEAD0Bi) +-- roundtrip regression test +local function roundtrip(i: integer) + local d = integer.tonumber(i) + return integer.create(d) +end + +assert(roundtrip(9007199254740993i) == 9007199254740992i) +assert(roundtrip(4711i) == 4711i) + -- table indexing and hashes local x = {} x[3i] = 5 diff --git a/tests/conformance/native.luau b/tests/conformance/native.luau index 5d34147c2..f4b2c08d2 100644 --- a/tests/conformance/native.luau +++ b/tests/conformance/native.luau @@ -299,6 +299,18 @@ end assert(fuzzfail29() == false) +local function fuzzfail30(a4, a5, a6) + for v7 = 0, 4 do + const v10 = v9 .. v9 + array = v10 + local v11 = not v10 + local v12 = v10 % v10 + v9 = self + end +end + +assert(pcall(fuzzfail30) == false) + local function arraySizeInv1() local t = {1, 2, nil, nil, nil, nil, nil, nil, nil, true} @@ -855,4 +867,41 @@ end assert(guard4(4) == 0) assert(guard4({}) == 4) +local function constantReload() + local function late_fn() + return "RESULT" + end + + local t = { + k000 = 0.5, k001 = 1.5, k002 = 2.5, k003 = 3.5, k004 = 4.5, k005 = 5.5, k006 = 6.5, k007 = 7.5, + k008 = 8.5, k009 = 9.5, k010 = 10.5, k011 = 11.5, k012 = 12.5, k013 = 13.5, k014 = 14.5, k015 = 15.5, + k016 = 16.5, k017 = 17.5, k018 = 18.5, k019 = 19.5, k020 = 20.5, k021 = 21.5, k022 = 22.5, k023 = 23.5, + k024 = 24.5, k025 = 25.5, k026 = 26.5, k027 = 27.5, k028 = 28.5, k029 = 29.5, k030 = 30.5, k031 = 31.5, + k032 = 32.5, k033 = 33.5, k034 = 34.5, k035 = 35.5, k036 = 36.5, k037 = 37.5, k038 = 38.5, k039 = 39.5, + k040 = 40.5, k041 = 41.5, k042 = 42.5, k043 = 43.5, k044 = 44.5, k045 = 45.5, k046 = 46.5, k047 = 47.5, + k048 = 48.5, k049 = 49.5, k050 = 50.5, k051 = 51.5, k052 = 52.5, k053 = 53.5, k054 = 54.5, k055 = 55.5, + k056 = 56.5, k057 = 57.5, k058 = 58.5, k059 = 59.5, k060 = 60.5, k061 = 61.5, k062 = 62.5, k063 = 63.5, + k064 = 64.5, k065 = 65.5, k066 = 66.5, k067 = 67.5, k068 = 68.5, k069 = 69.5, k070 = 70.5, k071 = 71.5, + k072 = 72.5, k073 = 73.5, k074 = 74.5, k075 = 75.5, k076 = 76.5, k077 = 77.5, k078 = 78.5, k079 = 79.5, + k080 = 80.5, k081 = 81.5, k082 = 82.5, k083 = 83.5, k084 = 84.5, k085 = 85.5, k086 = 86.5, k087 = 87.5, + k088 = 88.5, k089 = 89.5, k090 = 90.5, k091 = 91.5, k092 = 92.5, k093 = 93.5, k094 = 94.5, k095 = 95.5, + k096 = 96.5, k097 = 97.5, k098 = 98.5, k099 = 99.5, k100 = 100.5, k101 = 101.5, k102 = 102.5, k103 = 103.5, + k104 = 104.5, k105 = 105.5, k106 = 106.5, k107 = 107.5, k108 = 108.5, k109 = 109.5, k110 = 110.5, k111 = 111.5, + k112 = 112.5, k113 = 113.5, k114 = 114.5, k115 = 115.5, k116 = 116.5, k117 = 117.5, k118 = 118.5, k119 = 119.5, + k120 = 120.5, k121 = 121.5, k122 = 122.5, k123 = 123.5, k124 = 124.5, k125 = 125.5, k126 = 126.5, k127 = 127.5, + } + + local first = {} + late_fn() + local dead = { x = 1 } + local arr = { SomeGlobal } + dead = arr + + assert(dead[1] == nil) + assert(t.k000 == 0.5) + assert(t.k127 == 127.5) +end + +constantReload() + return('OK') diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-off.nonstrict.output new file mode 100644 index 000000000..2b820ef23 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/basic_join.flags-off.nonstrict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local t-0 = 8 +Block 1 (linear "then branch") -> [B3]: + t-1 = 9 +Block 2 (linear "else branch") -> [B3]: + t-2 = "hello" +Block 3 (linear "merge"): + t-3 = join(t-1, t-2) + local y-0 = t-3 diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-off.strict.output new file mode 100644 index 000000000..2b820ef23 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/basic_join.flags-off.strict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local t-0 = 8 +Block 1 (linear "then branch") -> [B3]: + t-1 = 9 +Block 2 (linear "else branch") -> [B3]: + t-2 = "hello" +Block 3 (linear "merge"): + t-3 = join(t-1, t-2) + local y-0 = t-3 diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-on.nonstrict.output new file mode 100644 index 000000000..2b820ef23 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/basic_join.flags-on.nonstrict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local t-0 = 8 +Block 1 (linear "then branch") -> [B3]: + t-1 = 9 +Block 2 (linear "else branch") -> [B3]: + t-2 = "hello" +Block 3 (linear "merge"): + t-3 = join(t-1, t-2) + local y-0 = t-3 diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-on.strict.output new file mode 100644 index 000000000..2b820ef23 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/basic_join.flags-on.strict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local t-0 = 8 +Block 1 (linear "then branch") -> [B3]: + t-1 = 9 +Block 2 (linear "else branch") -> [B3]: + t-2 = "hello" +Block 3 (linear "merge"): + t-3 = join(t-1, t-2) + local y-0 = t-3 diff --git a/tests/golden/analysis/cfgconstruction/basic_join.luau b/tests/golden/analysis/cfgconstruction/basic_join.luau new file mode 100644 index 000000000..2d140ff25 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/basic_join.luau @@ -0,0 +1,8 @@ +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local t = 8 +if true then + t = 9 +else + t = "hello" +end +local y = t \ No newline at end of file diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.nonstrict.output new file mode 100644 index 000000000..fc61bc0a1 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.nonstrict.output @@ -0,0 +1,4 @@ +Block 0 (entry "Entry Block"): + local f-0 = + local x-0 = 1 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.strict.output new file mode 100644 index 000000000..fc61bc0a1 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.strict.output @@ -0,0 +1,4 @@ +Block 0 (entry "Entry Block"): + local f-0 = + local x-0 = 1 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.nonstrict.output new file mode 100644 index 000000000..fc61bc0a1 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.nonstrict.output @@ -0,0 +1,4 @@ +Block 0 (entry "Entry Block"): + local f-0 = + local x-0 = 1 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.strict.output new file mode 100644 index 000000000..fc61bc0a1 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.strict.output @@ -0,0 +1,4 @@ +Block 0 (entry "Entry Block"): + local f-0 = + local x-0 = 1 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.luau b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.luau new file mode 100644 index 000000000..66f5a2678 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.luau @@ -0,0 +1,5 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local f = tostring +local x = 1 +local y = f(x) diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.nonstrict.output new file mode 100644 index 000000000..27906e321 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.nonstrict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 1 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.strict.output new file mode 100644 index 000000000..27906e321 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.strict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 1 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.nonstrict.output new file mode 100644 index 000000000..27906e321 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.nonstrict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 1 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.strict.output new file mode 100644 index 000000000..27906e321 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.strict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 1 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.luau b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.luau new file mode 100644 index 000000000..1f10c7d39 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.luau @@ -0,0 +1,4 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 1 +local y = (x) diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.nonstrict.output new file mode 100644 index 000000000..41428fb9d --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.nonstrict.output @@ -0,0 +1,5 @@ +Block 0 (entry "Entry Block"): + local a-0 = 1 + local b-0 = 2 + a-1 = b-0 + b-1 = a-0 diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.strict.output new file mode 100644 index 000000000..41428fb9d --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.strict.output @@ -0,0 +1,5 @@ +Block 0 (entry "Entry Block"): + local a-0 = 1 + local b-0 = 2 + a-1 = b-0 + b-1 = a-0 diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.nonstrict.output new file mode 100644 index 000000000..41428fb9d --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.nonstrict.output @@ -0,0 +1,5 @@ +Block 0 (entry "Entry Block"): + local a-0 = 1 + local b-0 = 2 + a-1 = b-0 + b-1 = a-0 diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.strict.output new file mode 100644 index 000000000..41428fb9d --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.strict.output @@ -0,0 +1,5 @@ +Block 0 (entry "Entry Block"): + local a-0 = 1 + local b-0 = 2 + a-1 = b-0 + b-1 = a-0 diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.luau b/tests/golden/analysis/cfgconstruction/multi_assignment.luau new file mode 100644 index 000000000..1bd7339c6 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/multi_assignment.luau @@ -0,0 +1,4 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local a, b = 1, 2 +a, b = b, a diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.nonstrict.output new file mode 100644 index 000000000..7a461a058 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.nonstrict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = 1 +Block 1 (linear "then branch") -> [B3]: + x-1 = 2 +Block 2 (linear "else branch") -> [B3]: +Block 3 (linear "merge"): + x-2 = join(x-1, x-0) + local w-0 = x-2 diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.strict.output new file mode 100644 index 000000000..7a461a058 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.strict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = 1 +Block 1 (linear "then branch") -> [B3]: + x-1 = 2 +Block 2 (linear "else branch") -> [B3]: +Block 3 (linear "merge"): + x-2 = join(x-1, x-0) + local w-0 = x-2 diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.nonstrict.output new file mode 100644 index 000000000..7a461a058 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.nonstrict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = 1 +Block 1 (linear "then branch") -> [B3]: + x-1 = 2 +Block 2 (linear "else branch") -> [B3]: +Block 3 (linear "merge"): + x-2 = join(x-1, x-0) + local w-0 = x-2 diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.strict.output new file mode 100644 index 000000000..7a461a058 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.strict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = 1 +Block 1 (linear "then branch") -> [B3]: + x-1 = 2 +Block 2 (linear "else branch") -> [B3]: +Block 3 (linear "merge"): + x-2 = join(x-1, x-0) + local w-0 = x-2 diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.luau b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.luau new file mode 100644 index 000000000..cdb9e9887 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.luau @@ -0,0 +1,7 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 1 +if true then + x = 2 +end +local w = x diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.nonstrict.output new file mode 100644 index 000000000..420750e92 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.nonstrict.output @@ -0,0 +1,4 @@ +Block 0 (entry "Entry Block"): + local x-0 = 1 + local y-0 = 2 + x-1 = y-0 diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.strict.output new file mode 100644 index 000000000..420750e92 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.strict.output @@ -0,0 +1,4 @@ +Block 0 (entry "Entry Block"): + local x-0 = 1 + local y-0 = 2 + x-1 = y-0 diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.nonstrict.output new file mode 100644 index 000000000..420750e92 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.nonstrict.output @@ -0,0 +1,4 @@ +Block 0 (entry "Entry Block"): + local x-0 = 1 + local y-0 = 2 + x-1 = y-0 diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.strict.output new file mode 100644 index 000000000..420750e92 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.strict.output @@ -0,0 +1,4 @@ +Block 0 (entry "Entry Block"): + local x-0 = 1 + local y-0 = 2 + x-1 = y-0 diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.luau b/tests/golden/analysis/cfgconstruction/reassignment_from_local.luau new file mode 100644 index 000000000..c940e790a --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/reassignment_from_local.luau @@ -0,0 +1,5 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 1 +local y = 2 +x = y diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.nonstrict.output new file mode 100644 index 000000000..8fab2de84 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.nonstrict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 + x-1 = 5 diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.strict.output new file mode 100644 index 000000000..8fab2de84 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.strict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 + x-1 = 5 diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.nonstrict.output new file mode 100644 index 000000000..8fab2de84 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.nonstrict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 + x-1 = 5 diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.strict.output new file mode 100644 index 000000000..8fab2de84 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.strict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 + x-1 = 5 diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.luau b/tests/golden/analysis/cfgconstruction/simple_reassignment.luau new file mode 100644 index 000000000..045ed0ba9 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/simple_reassignment.luau @@ -0,0 +1,4 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 4 +x = 5 diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/single_local.flags-off.nonstrict.output new file mode 100644 index 000000000..707f79b44 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/single_local.flags-off.nonstrict.output @@ -0,0 +1,2 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/single_local.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/single_local.flags-off.strict.output new file mode 100644 index 000000000..707f79b44 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/single_local.flags-off.strict.output @@ -0,0 +1,2 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/single_local.flags-on.nonstrict.output new file mode 100644 index 000000000..707f79b44 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/single_local.flags-on.nonstrict.output @@ -0,0 +1,2 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/single_local.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/single_local.flags-on.strict.output new file mode 100644 index 000000000..707f79b44 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/single_local.flags-on.strict.output @@ -0,0 +1,2 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 diff --git a/tests/golden/analysis/cfgconstruction/single_local.luau b/tests/golden/analysis/cfgconstruction/single_local.luau new file mode 100644 index 000000000..c09dc6253 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/single_local.luau @@ -0,0 +1,3 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 4 diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.nonstrict.output new file mode 100644 index 000000000..f32083dca --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.nonstrict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = 1 +Block 1 (linear "then branch") -> [B3]: + local y-0 = 2 +Block 2 (linear "else branch") -> [B3]: + local z-0 = 3 +Block 3 (linear "merge"): + local w-0 = x-0 diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.strict.output new file mode 100644 index 000000000..f32083dca --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.strict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = 1 +Block 1 (linear "then branch") -> [B3]: + local y-0 = 2 +Block 2 (linear "else branch") -> [B3]: + local z-0 = 3 +Block 3 (linear "merge"): + local w-0 = x-0 diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.nonstrict.output new file mode 100644 index 000000000..f32083dca --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.nonstrict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = 1 +Block 1 (linear "then branch") -> [B3]: + local y-0 = 2 +Block 2 (linear "else branch") -> [B3]: + local z-0 = 3 +Block 3 (linear "merge"): + local w-0 = x-0 diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.strict.output new file mode 100644 index 000000000..f32083dca --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.strict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = 1 +Block 1 (linear "then branch") -> [B3]: + local y-0 = 2 +Block 2 (linear "else branch") -> [B3]: + local z-0 = 3 +Block 3 (linear "merge"): + local w-0 = x-0 diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.luau b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.luau new file mode 100644 index 000000000..0a1a11071 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.luau @@ -0,0 +1,9 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 1 +if true then + local y = 2 +else + local z = 3 +end +local w = x diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.nonstrict.output new file mode 100644 index 000000000..b2a84db94 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.nonstrict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = 1 + local iterations-0 = 0 +Block 1 (condition "while-loop condition") -> [B2, B3]: + iterations-1 = join(iterations-0, iterations-2) +Block 2 (linear "while-loop body") -> [B1]: + local y-0 = x-0 + iterations-2 = iterations-1 + 1 +Block 3 (linear "while-loop exit"): diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.strict.output new file mode 100644 index 000000000..b2a84db94 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.strict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = 1 + local iterations-0 = 0 +Block 1 (condition "while-loop condition") -> [B2, B3]: + iterations-1 = join(iterations-0, iterations-2) +Block 2 (linear "while-loop body") -> [B1]: + local y-0 = x-0 + iterations-2 = iterations-1 + 1 +Block 3 (linear "while-loop exit"): diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.nonstrict.output new file mode 100644 index 000000000..b2a84db94 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.nonstrict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = 1 + local iterations-0 = 0 +Block 1 (condition "while-loop condition") -> [B2, B3]: + iterations-1 = join(iterations-0, iterations-2) +Block 2 (linear "while-loop body") -> [B1]: + local y-0 = x-0 + iterations-2 = iterations-1 + 1 +Block 3 (linear "while-loop exit"): diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.strict.output new file mode 100644 index 000000000..b2a84db94 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.strict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = 1 + local iterations-0 = 0 +Block 1 (condition "while-loop condition") -> [B2, B3]: + iterations-1 = join(iterations-0, iterations-2) +Block 2 (linear "while-loop body") -> [B1]: + local y-0 = x-0 + iterations-2 = iterations-1 + 1 +Block 3 (linear "while-loop exit"): diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.luau b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.luau new file mode 100644 index 000000000..345813076 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.luau @@ -0,0 +1,8 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 1 +local iterations = 0 +while iterations < 1 do + local y = x + iterations = iterations + 1 +end diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-off.nonstrict.output new file mode 100644 index 000000000..877b47cea --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/two_locals.flags-off.nonstrict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 + local y-0 = 5 diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-off.strict.output new file mode 100644 index 000000000..877b47cea --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/two_locals.flags-off.strict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 + local y-0 = 5 diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-on.nonstrict.output new file mode 100644 index 000000000..877b47cea --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/two_locals.flags-on.nonstrict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 + local y-0 = 5 diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-on.strict.output new file mode 100644 index 000000000..877b47cea --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/two_locals.flags-on.strict.output @@ -0,0 +1,3 @@ +Block 0 (entry "Entry Block"): + local x-0 = 4 + local y-0 = 5 diff --git a/tests/golden/analysis/cfgconstruction/two_locals.luau b/tests/golden/analysis/cfgconstruction/two_locals.luau new file mode 100644 index 000000000..892c2f69f --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/two_locals.luau @@ -0,0 +1,4 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 4 +local y = 5 diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-off.nonstrict.output new file mode 100644 index 000000000..e4aa9c0d1 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_loop.flags-off.nonstrict.output @@ -0,0 +1,10 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = nil +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-3) +Block 2 (linear "while-loop body") -> [B1]: + x-2 = refine(x-1 falsy) + x-3 = 5 +Block 3 (linear "while-loop exit"): + x-4 = refine(x-1 truthy) + local y-0 = x-4 diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-off.strict.output new file mode 100644 index 000000000..e4aa9c0d1 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_loop.flags-off.strict.output @@ -0,0 +1,10 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = nil +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-3) +Block 2 (linear "while-loop body") -> [B1]: + x-2 = refine(x-1 falsy) + x-3 = 5 +Block 3 (linear "while-loop exit"): + x-4 = refine(x-1 truthy) + local y-0 = x-4 diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-on.nonstrict.output new file mode 100644 index 000000000..e4aa9c0d1 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_loop.flags-on.nonstrict.output @@ -0,0 +1,10 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = nil +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-3) +Block 2 (linear "while-loop body") -> [B1]: + x-2 = refine(x-1 falsy) + x-3 = 5 +Block 3 (linear "while-loop exit"): + x-4 = refine(x-1 truthy) + local y-0 = x-4 diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-on.strict.output new file mode 100644 index 000000000..e4aa9c0d1 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_loop.flags-on.strict.output @@ -0,0 +1,10 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = nil +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-3) +Block 2 (linear "while-loop body") -> [B1]: + x-2 = refine(x-1 falsy) + x-3 = 5 +Block 3 (linear "while-loop exit"): + x-4 = refine(x-1 truthy) + local y-0 = x-4 diff --git a/tests/golden/analysis/cfgconstruction/while_loop.luau b/tests/golden/analysis/cfgconstruction/while_loop.luau new file mode 100644 index 000000000..d213c9c33 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_loop.luau @@ -0,0 +1,7 @@ +--!golden ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = nil +while not x do + x = 5 +end +local y = x diff --git a/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-off.nonstrict.output b/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-off.runtime.output b/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-off.strict.output b/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-off.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-on.nonstrict.output b/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-on.runtime.output b/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-on.strict.output b/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.luau b/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.luau new file mode 100644 index 000000000..243346476 --- /dev/null +++ b/tests/golden/analysis/functions/oss_2456_incorrect_generic_inference.luau @@ -0,0 +1,18 @@ +type Object = { + Name: string, +} + +type Foo = { + IsFoo: true, +} + +local function duplicate(obj: Object & T): Object & T + return nil :: any +end + +local function doFooThing(obj: Object & Foo) +end + +local x: Object & Foo = ... +local y = duplicate(x) +doFooThing(y) \ No newline at end of file diff --git a/tests/golden/analysis/property-modifiers/frozen_table_argument.flags-off.strict.output b/tests/golden/analysis/property-modifiers/frozen_table_argument.flags-off.strict.output index 991950680..8495e7741 100644 --- a/tests/golden/analysis/property-modifiers/frozen_table_argument.flags-off.strict.output +++ b/tests/golden/analysis/property-modifiers/frozen_table_argument.flags-off.strict.output @@ -1 +1 @@ -./analysis/property-modifiers/frozen_table_argument.luau(3,1): TypeError: Expected this to be 'number', but got 'number' +./analysis/property-modifiers/frozen_table_argument.luau(3,1): TypeError: Expected this to be 'number', but got 'number'; `id` is a read-only property in the latter type, but the former type requires a read-write property diff --git a/tests/golden/analysis/property-modifiers/frozen_table_method_argument.flags-off.strict.output b/tests/golden/analysis/property-modifiers/frozen_table_method_argument.flags-off.strict.output index 7e08fe25f..f919d71fe 100644 --- a/tests/golden/analysis/property-modifiers/frozen_table_method_argument.flags-off.strict.output +++ b/tests/golden/analysis/property-modifiers/frozen_table_method_argument.flags-off.strict.output @@ -1 +1 @@ -./analysis/property-modifiers/frozen_table_method_argument.luau(4,1): TypeError: Expected this to be 'number', but got 'number' +./analysis/property-modifiers/frozen_table_method_argument.luau(4,1): TypeError: Expected this to be 'number', but got 'number'; `id` is a read-only property in the latter type, but the former type requires a read-write property diff --git a/tests/golden/analysis/property-modifiers/frozen_table_number_field.flags-off.strict.output b/tests/golden/analysis/property-modifiers/frozen_table_number_field.flags-off.strict.output index f1e7647cb..ecabcba48 100644 --- a/tests/golden/analysis/property-modifiers/frozen_table_number_field.flags-off.strict.output +++ b/tests/golden/analysis/property-modifiers/frozen_table_number_field.flags-off.strict.output @@ -1 +1 @@ -./analysis/property-modifiers/frozen_table_number_field.luau(3,1): TypeError: Expected this to be 'number', but got 'number' +./analysis/property-modifiers/frozen_table_number_field.luau(3,1): TypeError: Expected this to be 'number', but got 'number'; `id` is a read-only property in the latter type, but the former type requires a read-write property diff --git a/tests/golden/analysis/property-modifiers/frozen_table_string_field.flags-off.strict.output b/tests/golden/analysis/property-modifiers/frozen_table_string_field.flags-off.strict.output index 6960a01a5..b8e11a2f0 100644 --- a/tests/golden/analysis/property-modifiers/frozen_table_string_field.flags-off.strict.output +++ b/tests/golden/analysis/property-modifiers/frozen_table_string_field.flags-off.strict.output @@ -1 +1 @@ -./analysis/property-modifiers/frozen_table_string_field.luau(3,1): TypeError: Expected this to be 'string', but got 'string' +./analysis/property-modifiers/frozen_table_string_field.luau(3,1): TypeError: Expected this to be 'string', but got 'string'; `name` is a read-only property in the latter type, but the former type requires a read-write property diff --git a/tests/golden/analysis/property-modifiers/read_only_indexer_argument.flags-off.strict.output b/tests/golden/analysis/property-modifiers/read_only_indexer_argument.flags-off.strict.output index d91298bd0..a511905bc 100644 --- a/tests/golden/analysis/property-modifiers/read_only_indexer_argument.flags-off.strict.output +++ b/tests/golden/analysis/property-modifiers/read_only_indexer_argument.flags-off.strict.output @@ -1,2 +1,2 @@ ./analysis/property-modifiers/read_only_indexer_argument.luau(4,3): TypeError: Expected this to be 'T', but got '{ read [string]: number }'; -Expected the indexer result to be `number`, but got `number` +the indexer is read-only in the latter type, but the former type requires a read-write indexer diff --git a/tests/golden/analysis/property-modifiers/write_only_property_argument.flags-off.strict.output b/tests/golden/analysis/property-modifiers/write_only_property_argument.flags-off.strict.output index 547cb2ec1..70796e537 100644 --- a/tests/golden/analysis/property-modifiers/write_only_property_argument.flags-off.strict.output +++ b/tests/golden/analysis/property-modifiers/write_only_property_argument.flags-off.strict.output @@ -1,2 +1,2 @@ ./analysis/property-modifiers/write_only_property_argument.luau(4,3): TypeError: Expected this to be 'T', but got '{ write count: number }'; -Expected values assigned to property `count` to be `number`, but got `number` +`count` is a write-only property in the latter type, but the former type requires a read-write property diff --git a/tests/golden/analysis/refinements/index_unknown_refined_with_type.flags-off.strict.output b/tests/golden/analysis/refinements/index_unknown_refined_with_type.flags-off.strict.output index 44092ce88..40bf898ef 100644 --- a/tests/golden/analysis/refinements/index_unknown_refined_with_type.flags-off.strict.output +++ b/tests/golden/analysis/refinements/index_unknown_refined_with_type.flags-off.strict.output @@ -1 +1 @@ -./analysis/refinements/index_unknown_refined_with_type.luau(6,12): TypeError: Expected type table, got 'table' instead +./analysis/refinements/index_unknown_refined_with_type.luau(6,12): TypeError: Cannot add indexer to table 'table' diff --git a/tests/golden/analysis/refinements/index_unknown_refined_with_typeof.flags-off.strict.output b/tests/golden/analysis/refinements/index_unknown_refined_with_typeof.flags-off.strict.output index 762e32845..878400551 100644 --- a/tests/golden/analysis/refinements/index_unknown_refined_with_typeof.flags-off.strict.output +++ b/tests/golden/analysis/refinements/index_unknown_refined_with_typeof.flags-off.strict.output @@ -1 +1 @@ -./analysis/refinements/index_unknown_refined_with_typeof.luau(6,12): TypeError: Expected type table, got 'table' instead +./analysis/refinements/index_unknown_refined_with_typeof.luau(6,12): TypeError: Cannot add indexer to table 'table' diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-off.nonstrict.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-off.runtime.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-off.strict.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-off.strict.output new file mode 100644 index 000000000..dc219fa7d --- /dev/null +++ b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-off.strict.output @@ -0,0 +1,5 @@ +./analysis/tables/oss_2625_generic_instantiation_avoids_nil.luau(9,20): TypeError: No valid instantiation could be inferred for generic type parameter T. It was expected to be at least: + nil | number +and at most: + number +but these types are not compatible with one another. diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-on.nonstrict.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-on.runtime.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-on.strict.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.luau b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.luau new file mode 100644 index 000000000..6cce44a2b --- /dev/null +++ b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil.luau @@ -0,0 +1,9 @@ +type Base = { createdAt: number } +type Holder = Base & { value: T } + +local function get(holder: Holder): T + return holder.value +end + +local h: Holder = { createdAt = 1, value = 5 } +local _n: number = get(h) \ No newline at end of file diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-off.nonstrict.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-off.runtime.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-off.strict.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-off.strict.output new file mode 100644 index 000000000..d8fac16af --- /dev/null +++ b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-off.strict.output @@ -0,0 +1,2 @@ +_luau_print (9, 9): number + diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-on.nonstrict.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-on.runtime.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-on.strict.output b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-on.strict.output new file mode 100644 index 000000000..d8fac16af --- /dev/null +++ b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.flags-on.strict.output @@ -0,0 +1,2 @@ +_luau_print (9, 9): number + diff --git a/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.luau b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.luau new file mode 100644 index 000000000..42cec2be9 --- /dev/null +++ b/tests/golden/analysis/tables/oss_2625_generic_instantiation_avoids_nil_variation.luau @@ -0,0 +1,10 @@ +type Base = { createdAt: number } +type Holder = Base & { read value: T } + +local function get(holder: Holder): T + return holder.value +end + +local h: Holder = { createdAt = 1, value = 5 } +local n = get(h) +local _: _luau_print \ No newline at end of file diff --git a/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-off.nonstrict.output b/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-off.runtime.output b/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-off.runtime.output new file mode 100644 index 000000000..3771ada48 --- /dev/null +++ b/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-off.runtime.output @@ -0,0 +1,3 @@ +./analysis/tables/react_minimzed_example_number_24601.luau:16: attempt to call a nil value +stacktrace: +./analysis/tables/react_minimzed_example_number_24601.luau:16 diff --git a/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-off.strict.output b/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-off.strict.output new file mode 100644 index 000000000..cfb678dd8 --- /dev/null +++ b/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-off.strict.output @@ -0,0 +1,5 @@ +./analysis/tables/react_minimzed_example_number_24601.luau(16,18): TypeError: No valid instantiation could be inferred for generic type parameter P. It was expected to be at least: + { displayOrder: number } +and at most: + CustomTitleBarPortalProps +but these types are not compatible with one another. diff --git a/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-on.nonstrict.output b/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-on.runtime.output b/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-on.runtime.output new file mode 100644 index 000000000..3771ada48 --- /dev/null +++ b/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-on.runtime.output @@ -0,0 +1,3 @@ +./analysis/tables/react_minimzed_example_number_24601.luau:16: attempt to call a nil value +stacktrace: +./analysis/tables/react_minimzed_example_number_24601.luau:16 diff --git a/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-on.strict.output b/tests/golden/analysis/tables/react_minimzed_example_number_24601.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/react_minimzed_example_number_24601.luau b/tests/golden/analysis/tables/react_minimzed_example_number_24601.luau new file mode 100644 index 000000000..784b79dd9 --- /dev/null +++ b/tests/golden/analysis/tables/react_minimzed_example_number_24601.luau @@ -0,0 +1,18 @@ +type ReactElement = { type: T, props: P?, key: string | number | nil, ref: any } +type ReactNode = nil | boolean | number | string | ReactElement | { ReactNode? } | { [string]: ReactNode?, UNIQUE_TAG: any? } +type FunctionComponent

= (P, any) -> ReactNode +type ClassComponent

= { props: P, render: (ClassComponent

) -> ReactNode } +type AbstractComponent = { render: (P, T) -> ReactNode } +type CreateElement = ( FunctionComponent

| ClassComponent

| AbstractComponent, P?, ...ReactNode) -> ReactElement + +local createElement: CreateElement = nil :: any + +type CustomTitleBarPortalProps = { displayOrder: number, title: string? } + +local function CustomTitleBarPortal(props: CustomTitleBarPortalProps): ReactNode + return nil +end + +local _element = createElement(CustomTitleBarPortal, { + displayOrder = 151, +}) diff --git a/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-off.nonstrict.output b/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-off.runtime.output b/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-off.strict.output b/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-off.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-on.nonstrict.output b/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-on.runtime.output b/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-on.strict.output b/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-on.strict.output new file mode 100644 index 000000000..7812c8b10 --- /dev/null +++ b/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/tables/table_width_subtyping_soundness_hole.luau(5,12): TypeError: Expected this to be 'Y', but got 'X' diff --git a/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.luau b/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.luau new file mode 100644 index 000000000..6b9fed938 --- /dev/null +++ b/tests/golden/analysis/tables/table_width_subtyping_soundness_hole.luau @@ -0,0 +1,6 @@ +type X = {} +type Y = { read Z: number? } + +local function _make(tbl: X): Y + return tbl +end \ No newline at end of file diff --git a/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack.flags-off.nonstrict.output b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack.flags-off.nonstrict.output new file mode 100644 index 000000000..d00ff2061 --- /dev/null +++ b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack.flags-off.nonstrict.output @@ -0,0 +1,8 @@ +./analysis/type-packs/nonstrict_checked_call_tail_pack.luau(37,1): TypeError: the function 'math.clamp' will error at runtime if it is not called with 3 arguments, but we are calling it here with 1 arguments +./analysis/type-packs/nonstrict_checked_call_tail_pack.luau(36,10): TypeError: the function 'math.abs' expects to get a number as its 1st argument, but is being given a string +./analysis/type-packs/nonstrict_checked_call_tail_pack.luau(32,14): TypeError: the function 'math.abs' expects to get a number as its 1st argument, but is being given a nil +./analysis/type-packs/nonstrict_checked_call_tail_pack.luau(28,5): TypeError: the function 'math.abs' will error at runtime if it is not called with 1 arguments, but we are calling it here with 2 arguments +./analysis/type-packs/nonstrict_checked_call_tail_pack.luau(25,5): TypeError: the function 'math.clamp' will error at runtime if it is not called with 3 arguments, but we are calling it here with 1 arguments +./analysis/type-packs/nonstrict_checked_call_tail_pack.luau(21,1): TypeError: the function 'math.abs' will error at runtime if it is not called with 1 arguments, but we are calling it here with 2 arguments +./analysis/type-packs/nonstrict_checked_call_tail_pack.luau(18,1): TypeError: the function 'math.clamp' will error at runtime if it is not called with 3 arguments, but we are calling it here with 2 arguments +./analysis/type-packs/nonstrict_checked_call_tail_pack.luau(17,1): TypeError: the function 'math.clamp' will error at runtime if it is not called with 3 arguments, but we are calling it here with 1 arguments diff --git a/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack.flags-on.nonstrict.output b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack.luau b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack.luau new file mode 100644 index 000000000..d64c77665 --- /dev/null +++ b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack.luau @@ -0,0 +1,37 @@ +local function two(): (number, number) + return 1, 2 +end +local function three(): (number, number, number) + return 1, 2, 3 +end +local function none(): () +end +local function strings(): ...string + return "a" +end +local function numberThenStrings(): (number, ...string) + return 1, "b" +end + +-- a call in the last argument position passes all of its values +math.clamp(three()) +math.clamp(1, two()) + +-- an empty pack doesn't add an argument +math.abs(3, none()) + +local function _forward(...: any) + -- while ... can have <3 values, we don't want to complain when it has >=3 for nonstrict + math.clamp(...) + + -- while ... can have values, we don't want to complain when it has 0 for nonstrict + math.abs(3, ...) +end + +local function _generic(...: T...) + math.abs(...) +end + +-- while ...string has a value here, from types alone the pack could be empty +math.abs(strings()) +math.clamp(numberThenStrings()) diff --git a/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack_errors.flags-off.nonstrict.output b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack_errors.flags-off.nonstrict.output new file mode 100644 index 000000000..6d381f2ed --- /dev/null +++ b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack_errors.flags-off.nonstrict.output @@ -0,0 +1,4 @@ +./analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau(18,1): TypeError: the function 'math.abs' will error at runtime if it is not called with 1 arguments, but we are calling it here with 2 arguments +./analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau(15,1): TypeError: the function 'math.clamp' will error at runtime if it is not called with 3 arguments, but we are calling it here with 1 arguments +./analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau(14,10): TypeError: the function 'math.abs' expects to get a number as its 1st argument, but is being given a nil +./analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau(11,10): TypeError: the function 'math.abs' expects to get a number as its 1st argument, but is being given a nil diff --git a/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack_errors.flags-on.nonstrict.output b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack_errors.flags-on.nonstrict.output new file mode 100644 index 000000000..5feb22728 --- /dev/null +++ b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack_errors.flags-on.nonstrict.output @@ -0,0 +1,4 @@ +./analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau(18,1): TypeError: the function 'math.abs' will error at runtime if it is not called with 1 arguments, but we are calling it here with 3 arguments +./analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau(15,1): TypeError: the function 'math.clamp' will error at runtime if it is not called with 3 arguments, but we are calling it here with 1 arguments +./analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau(14,10): TypeError: the function 'math.abs' expects to get a number as its 1st argument, but is being given a nil +./analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau(11,1): TypeError: the function 'math.abs' will error at runtime if it is not called with 1 arguments, but we are calling it here with 0 arguments diff --git a/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau new file mode 100644 index 000000000..077730ed8 --- /dev/null +++ b/tests/golden/analysis/type-packs/nonstrict_checked_call_tail_pack_errors.luau @@ -0,0 +1,18 @@ +local function two(): (number, number) + return 1, 2 +end +local function three(): (number, number, number) + return 1, 2, 3 +end +local function none(): () +end + +-- an empty pack passes no arguments +math.abs(none()) + +-- a group truncates a call to a single value +math.abs((none())) +math.clamp((three())) + +-- every value of a call in the last argument position is passed +math.abs(3, two()) diff --git a/tools/golden/cli.py b/tools/golden/cli.py index a3081c790..82876effa 100644 --- a/tools/golden/cli.py +++ b/tools/golden/cli.py @@ -311,4 +311,5 @@ def main( args.jobs, args.dump, fflags=args.fflags, + environ=actual_environ, ) diff --git a/tools/golden/expectations.py b/tools/golden/expectations.py index cda5b0f87..5487512a0 100644 --- a/tools/golden/expectations.py +++ b/tools/golden/expectations.py @@ -2,7 +2,6 @@ from __future__ import annotations -import difflib import os import shlex import stat @@ -12,6 +11,7 @@ from pathlib import Path from .models import COMMANDS, ConfigResult, GoldenTest, UpdateMode +from .text import unified_diff def _captured_output(command: str, text: str) -> str: @@ -20,18 +20,6 @@ def _captured_output(command: str, text: str) -> str: return f"captured {command}.output:\n---\n{text}\n---" -def _unified_diff(expected_path: Path, expected: str, actual: str) -> str: - diff = "".join( - difflib.unified_diff( - expected.splitlines(keepends=True), - actual.splitlines(keepends=True), - fromfile=str(expected_path), - tofile="captured output", - ) - ) - return diff or f"expected {expected!r}, captured {actual!r}" - - def _will_update( test: GoldenTest, config: str, @@ -55,6 +43,8 @@ def validate_configuration( config: str, result: ConfigResult, update: UpdateMode | None, + *, + color: bool = False, ) -> list[str]: errors: list[str] = [] for command, command_result in result.commands.items(): @@ -97,7 +87,7 @@ def validate_configuration( path, expected = exact if expected != actual: message = f"{test.test_id} [{config}] exact output mismatch for {command}.output:\n" - message += _unified_diff(path, expected, actual) + message += unified_diff(path, expected, actual, color=color) errors.append(message) return errors diff --git a/tools/golden/selftest.py b/tools/golden/selftest.py index 0b9c205e0..823a6d8a9 100644 --- a/tools/golden/selftest.py +++ b/tools/golden/selftest.py @@ -6,6 +6,7 @@ import argparse import io import os +import re import subprocess import sys import tempfile @@ -15,7 +16,7 @@ from pathlib import Path from unittest import mock -from . import cli, execution, suite +from . import cli, execution, suite, text from .cli import create_argument_parser, main from .directives import directives_from_file, parse_directives from .discovery import ( @@ -43,6 +44,7 @@ UpdateMode, ) from .suite import run_suite +from .text import diff_color_enabled, unified_diff class _IntegrationArgs(argparse.Namespace): @@ -570,6 +572,130 @@ def test_execute_configuration_orders_runner_and_test_fflags_after_base_configur self.assertEqual("case.luau", argv[-1]) +class DiffTests(unittest.TestCase): + def setUp(self) -> None: + self.colors = mock.Mock( + Fore=mock.Mock(RED="\x1b[31m", GREEN="\x1b[32m"), + Style=mock.Mock(RESET_ALL="\x1b[0m"), + ) + patcher = mock.patch.object(text, "colorama", self.colors) + _ = patcher.start() + self.addCleanup(patcher.stop) + + def test_terminal_color_policy(self) -> None: + for is_terminal, environ, enabled in ( + (True, {}, True), + (False, {}, False), + (True, {"NO_COLOR": "1"}, False), + (True, {"NO_COLOR": ""}, False), + (True, {"NO_COLOR": "0", "FORCE_COLOR": "1"}, False), + (True, {"TERM": "dumb"}, False), + ): + with self.subTest(is_terminal=is_terminal, environ=environ): + self.colors.just_fix_windows_console.reset_mock() + stream = io.StringIO() + with mock.patch.object(stream, "isatty", return_value=is_terminal): + self.assertEqual(enabled, diff_color_enabled(stream, environ)) + self.assertEqual(int(enabled), self.colors.just_fix_windows_console.call_count) + + def test_missing_colorama_falls_back_to_plain_diff(self) -> None: + with mock.patch.object(text, "colorama", None): + stream = io.StringIO() + with mock.patch.object(stream, "isatty", return_value=True): + self.assertFalse(diff_color_enabled(stream, {})) + self.assertEqual( + unified_diff(Path("expected"), "old\n", "new\n"), + unified_diff(Path("expected"), "old\n", "new\n", color=True), + ) + + def test_replacement_highlights_only_changed_characters(self) -> None: + diff = unified_diff(Path("expected"), "value: cat!\n", "value: cot?\n", color=True) + + self.assertIn("\x1b[31m--- expected\x1b[0m\n", diff) + self.assertIn("\x1b[32m+++ captured output\x1b[0m\n", diff) + self.assertIn("@@ -1 +1 @@\n", diff) + self.assertIn("\x1b[38;5;16m\x1b[48;5;224m-value: c\x1b[48;5;217ma\x1b[48;5;224mt", diff) + self.assertIn("\x1b[38;5;16m\x1b[48;5;194m+value: c\x1b[48;5;157mo\x1b[48;5;194mt", diff) + self.assertIn("\x1b[48;5;217m!\x1b[48;5;224m\x1b[0m\n", diff) + self.assertIn("\x1b[48;5;157m?\x1b[48;5;194m\x1b[0m\n", diff) + + def test_insertions_and_deletions_keep_line_colors(self) -> None: + for expected, actual, line in ( + ("", "added\n", "\x1b[38;5;16m\x1b[48;5;194m+added\x1b[0m\n"), + ("removed\n", "", "\x1b[38;5;16m\x1b[48;5;224m-removed\x1b[0m\n"), + ): + with self.subTest(expected=expected, actual=actual): + self.assertIn(line, unified_diff(Path("expected"), expected, actual, color=True)) + + def test_color_preserves_unified_diff_text(self) -> None: + context = "".join(f"context {index}\n" for index in range(10)) + for expected, actual in ( + ("same\n", "same\n"), + ("", "added\n"), + ("removed\n", ""), + ("no newline", "no new line"), + ("trailing\n", "trailing"), + ("--prefix\nold\n", "++prefix\nnew\nextra\n"), + ("old\nextra\n", "new\n"), + ("x y\n", "x y\n"), + ("café\n", "cafe\n"), + ("before\n" + context + "after\n", "BEFORE\n" + context + "AFTER\n"), + ): + with self.subTest(expected=expected, actual=actual): + plain = unified_diff(Path("expected"), expected, actual) + colored = unified_diff(Path("expected"), expected, actual, color=True) + self.assertEqual(plain, re.sub(r"\x1b\[[0-9;]*m", "", colored)) + + def test_long_lines_skip_character_matching(self) -> None: + expected = "x" * (text.MAX_HIGHLIGHT_LINE_LENGTH + 1) + "\n" + actual = "y" + expected + diff = unified_diff(Path("expected"), expected, actual, color=True) + + self.assertIn("\x1b[38;5;16m\x1b[48;5;224m-" + expected.removesuffix("\n") + "\x1b[0m\n", diff) + self.assertIn("\x1b[38;5;16m\x1b[48;5;194m+" + actual.removesuffix("\n") + "\x1b[0m\n", diff) + self.assertNotIn("\x1b[48;5;217m", diff) + self.assertNotIn("\x1b[48;5;157m", diff) + + def test_cli_colors_stderr_and_keeps_dump_files_plain(self) -> None: + for is_terminal, environ, enabled in ( + (True, {}, True), + (False, {}, False), + (True, {"NO_COLOR": "1"}, False), + (True, {"NO_COLOR": ""}, False), + ): + with self.subTest(is_terminal=is_terminal, environ=environ), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + test = _test_case(root) + for config in CONFIGURATIONS: + _write(test.exact_path(config, "strict"), "value: old\n") + errors = io.StringIO() + output = io.StringIO() + with ( + mock.patch.object(errors, "isatty", return_value=is_terminal), + mock.patch.object(output, "isatty", return_value=not is_terminal), + mock.patch.object( + cli, "resolve_executables", return_value=Executables(Path("luau"), Path("luau-analyze")) + ), + mock.patch.object( + suite, "execute_configuration", return_value=_result(strict_output="value: new\n") + ), + redirect_stdout(output), + redirect_stderr(errors), + ): + code = main(["--dump", "--jobs=1"], source_root=root, test_root=root, cwd=root, environ=environ) + + self.assertEqual(1, code) + self.assertEqual(enabled, "\x1b[31m" in errors.getvalue()) + self.assertEqual(enabled, "\x1b[32m" in errors.getvalue()) + self.assertEqual(enabled, "\x1b[48;5;224m" in errors.getvalue()) + self.assertEqual(enabled, "\x1b[48;5;194m" in errors.getvalue()) + self.assertNotIn("\x1b[", output.getvalue()) + for config in CONFIGURATIONS: + self.assertIn(f"[{config}] exact output mismatch", errors.getvalue()) + self.assertEqual("value: new\n", test.actual_path(config, "strict").read_text(encoding="utf-8")) + self.assertEqual("value: old\n", test.exact_path(config, "strict").read_text(encoding="utf-8")) + + class ValidationAndUpdateTests(unittest.TestCase): def test_exact_only_test_does_not_validate_status(self) -> None: with tempfile.TemporaryDirectory() as temporary: diff --git a/tools/golden/suite.py b/tools/golden/suite.py index c9707b4ff..cbf7d0189 100644 --- a/tools/golden/suite.py +++ b/tools/golden/suite.py @@ -2,15 +2,17 @@ from __future__ import annotations +import os import sys -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from concurrent.futures import ThreadPoolExecutor from pathlib import Path from .execution import execute_configuration from .expectations import update_configuration, validate_configuration, write_actual_outputs from .models import ConfigResult, Executables, GoldenTest, UpdateMode +from .text import diff_color_enabled def run_suite( @@ -23,6 +25,7 @@ def run_suite( jobs: int, dump: bool = False, fflags: Sequence[str] = (), + environ: Mapping[str, str] | None = None, ) -> int: # Each `(test, config)` run is an independent batch of processes for the CLI, so they # execute will concurrently. Validation and file writes then run sequentially in @@ -42,10 +45,11 @@ def execute(item: tuple[GoldenTest, str]) -> ConfigResult: results = list(pool.map(execute, work)) errors: list[str] = [] + color = diff_color_enabled(sys.stderr, os.environ if environ is None else environ) writes = 0 actual_writes = 0 for (test, config), result in zip(work, results, strict=True): - errors.extend(validate_configuration(test, config, result, update)) + errors.extend(validate_configuration(test, config, result, update, color=color)) if update is not None: update_errors, update_writes = update_configuration(test, config, result, update) errors.extend(update_errors) diff --git a/tools/golden/text.py b/tools/golden/text.py index 0a8dab212..a57634c04 100644 --- a/tools/golden/text.py +++ b/tools/golden/text.py @@ -1,9 +1,107 @@ -"""Text decoding and newline normalization helpers.""" +"""Text decoding, newline normalization, and diff formatting helpers.""" +import difflib + +from collections.abc import Mapping from pathlib import Path from .models import GoldenError +from typing import TextIO + +try: + import colorama +except ImportError: + colorama = None + +MAX_HIGHLIGHT_LINE_LENGTH = 4096 + +# The 256-color cube avoids theme-defined ANSI normal/bright colors, which can +# have identical shades. Each highlight is darker than its line background. +DIFF_FOREGROUND = "\x1b[38;5;16m" +REMOVED_BACKGROUND = "\x1b[48;5;224m" +REMOVED_HIGHLIGHT = "\x1b[48;5;217m" +ADDED_BACKGROUND = "\x1b[48;5;194m" +ADDED_HIGHLIGHT = "\x1b[48;5;157m" + + +def diff_color_enabled(stream: TextIO, environ: Mapping[str, str]) -> bool: + """Enable optional terminal colors, honoring even an empty NO_COLOR value.""" + if colorama is None or "NO_COLOR" in environ or environ.get("TERM") == "dumb" or not stream.isatty(): + return False + colorama.just_fix_windows_console() + return True + + +def _highlight_pair(removed: str, added: str) -> tuple[str, str]: + if colorama is None: + return removed, added + + # SequenceMatcher can be quadratic; long diagnostics still get line colors. + if max(len(removed), len(added)) > MAX_HIGHLIGHT_LINE_LENGTH: + return removed, added + + matcher = difflib.SequenceMatcher(None, removed, added, autojunk=False) + old_parts: list[str] = [] + new_parts: list[str] = [] + for tag, old_start, old_end, new_start, new_end in matcher.get_opcodes(): + old = removed[old_start:old_end] + new = added[new_start:new_end] + if tag != "equal": + if old: + old = f"{REMOVED_HIGHLIGHT}{old}{REMOVED_BACKGROUND}" + if new: + new = f"{ADDED_HIGHLIGHT}{new}{ADDED_BACKGROUND}" + old_parts.append(old) + new_parts.append(new) + return "".join(old_parts), "".join(new_parts) + + +def unified_diff(expected_path: Path, expected: str, actual: str, *, color: bool = False) -> str: + """Format a unified diff; optional color affects only the displayed text.""" + lines = list( + difflib.unified_diff( + expected.splitlines(keepends=True), + actual.splitlines(keepends=True), + fromfile=str(expected_path), + tofile="captured output", + ) + ) + if not lines: + return f"expected {expected!r}, captured {actual!r}" + + if color and colorama is not None: + # Pair replacements within each change block, excluding the file headers. + index = 2 + while index < len(lines): + if not lines[index].startswith("-"): + index += 1 + continue + old_start = index + while index < len(lines) and lines[index].startswith("-"): + index += 1 + new_start = index + while index < len(lines) and lines[index].startswith("+"): + index += 1 + for old_index, new_index in zip(range(old_start, new_start), range(new_start, index), strict=False): + old, new = _highlight_pair( + lines[old_index][1:].removesuffix("\n"), lines[new_index][1:].removesuffix("\n") + ) + lines[old_index] = "-" + old + ("\n" if lines[old_index].endswith("\n") else "") + lines[new_index] = "+" + new + ("\n" if lines[new_index].endswith("\n") else "") + + for index, line in enumerate(lines): + if line.startswith("-"): + style = colorama.Fore.RED if index < 2 else DIFF_FOREGROUND + REMOVED_BACKGROUND + elif line.startswith("+"): + style = colorama.Fore.GREEN if index < 2 else DIFF_FOREGROUND + ADDED_BACKGROUND + else: + continue + ending = "\n" if line.endswith("\n") else "" + lines[index] = style + line.removesuffix("\n") + colorama.Style.RESET_ALL + ending + + return "".join(lines) + def normalize_newlines(text: str) -> str: return text.replace("\r\n", "\n").replace("\r", "\n") From a4818b6678822bb726a0eb2299cae751d3017a6a Mon Sep 17 00:00:00 2001 From: vegorov-rbx <75688451+vegorov-rbx@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:32:00 +0200 Subject: [PATCH 03/13] Provide extra details for issues we consider out of scope in SECURITY.md (#3077) --- SECURITY.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/SECURITY.md b/SECURITY.md index 7b190324d..26566cb76 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -11,4 +11,33 @@ doesn't come with any security guarantees; make sure to sign and/or encrypt the # Reporting a Vulnerability -You can report security bugs via [HackerOne](https://hackerone.com/roblox). Please refer to the linked page for rules of the bounty program. +You can report security bugs via [HackerOne](https://hackerone.com/roblox). Please refer to the linked page for the rules of the bounty program, which defines scope and criteria for Roblox. + +Alternatively, you can report issues privately through [GitHub Security Advisories](https://github.com/luau-lang/luau/security/advisories/new) page. +Note that reports submitted through GitHub are not eligible for bounty rewards of the HackerOne program. + +## Scope + +The areas listed in this section are explicitly out of scope. + +We reserve the right to tell you when a report should be opened as a regular issue and update this list with new cases. + +### Custom bytecode provided to `luau_load` + +The runtime assumes that bytecode is produced by Luau compiler and is not designed to consume arbitrary input. +Please see the [sandboxing documentation](https://luau.org/sandbox/#library) for details. +Embedders are responsible for ensuring the bytecode that is being loaded has been produced by the Luau compiler. + +### Features under a Debug* flag + +Features enabled by flags starting with Debug* are experimental and in development. +Open a regular issue if you found a bug under such a flag. + +### Stack overflows + +Stack size is a parameter of an environment which might not be configured to an appropriate size by the embedder and also highly dependant on the build options. +We do not consider these to be security vulnerabilities and will ask you to open a regular issue. + +### Low severity Analysis/ issues + +Resource exhaustion and null pointer access crashes in the type checking should be reported as regular issues. From 2a3d8937c19c8fd9f7b72b6ec9068c62760e6588 Mon Sep 17 00:00:00 2001 From: Ilya Rezvov Date: Fri, 30 Oct 2026 13:12:54 -0600 Subject: [PATCH 04/13] Sync to upstream/release/745 (#3093) ## New week, new Luau! ### Syntax - Added support for `while local`/`while const` loops, allowing a single binding to be declared and scoped to the loop condition and body. (note: this is behind an experimental flag) For example: ```lua while local line = reader:nextLine() do process(line) end ``` ### Runtime & performance - `table.create` and `table.clear` are now recognized as fast calls. - Native code generation can now auto-promote frequently-executed functions to native based on call and loop-iteration counts. ### Type checking - Implemented normalization of negated intersection types. - Fixed class method context not being reset in the parser when entering type functions. - Fixed an analysis blow-up on moderately large table-like literals. ### C API / embedding - `lua_EmbedderGc` now returns `int`: the embedder returns nonzero while it is still making progress, and the GC repeatedly re-invokes it to reach a fixed point across the VM and embedder heaps. --------- Co-authored-by: Vyacheslav Egorov Co-authored-by: Ariel Weiss Co-authored-by: Andy Friesen Co-authored-by: Hunter Goldstein Co-authored-by: Varun Saini <61795485+vrn-sn@users.noreply.github.com> Co-authored-by: Sora Kanosue Co-authored-by: Annie Tang Co-authored-by: Annie Tang <98965493+annieetang@users.noreply.github.com> Co-authored-by: Vighnesh Vijay Co-authored-by: Andreas Haeberlen Co-authored-by: Thomas Schollenberger --- Analysis/include/Luau/AstUtils.h | 15 - Analysis/include/Luau/ConstraintGenerator.h | 19 +- Analysis/include/Luau/ConstraintSolver.h | 25 +- Analysis/include/Luau/ControlFlowGraph.h | 598 ++++-- Analysis/include/Luau/DumpCFG.h | 23 +- Analysis/include/Luau/Normalize.h | 2 + Analysis/include/Luau/OverloadResolver.h | 15 +- Analysis/include/Luau/Subtyping.h | 5 +- Analysis/include/Luau/TypeStateMap.h | 39 +- Analysis/src/AstJsonEncoder.cpp | 5 + Analysis/src/AstUtils.cpp | 69 - Analysis/src/AutocompleteCore.cpp | 7 + Analysis/src/BuiltinTypeFunctions.cpp | 16 +- Analysis/src/ConstraintGenerator.cpp | 615 +++---- Analysis/src/ConstraintSolver.cpp | 469 ++++- Analysis/src/ControlFlowGraph.cpp | 1603 +++++++++++++---- Analysis/src/DataFlowGraph.cpp | 10 + Analysis/src/DumpCFG.cpp | 276 ++- Analysis/src/FragmentAutocomplete.cpp | 12 + Analysis/src/Frontend.cpp | 13 +- Analysis/src/Normalize.cpp | 42 +- Analysis/src/OverloadResolver.cpp | 245 ++- Analysis/src/Simplify.cpp | 13 +- Analysis/src/Subtyping.cpp | 93 +- Analysis/src/TypeChecker2.cpp | 50 +- Analysis/src/TypeFunctionRuntime.cpp | 3 +- Analysis/src/TypeInfer.cpp | 16 +- Analysis/src/TypeStateMap.cpp | 417 ++++- Analysis/src/Unifier2.cpp | 8 + Ast/include/Luau/Ast.h | 20 + Ast/include/Luau/Cst.h | 11 + Ast/include/Luau/Parser.h | 4 + Ast/src/Ast.cpp | 27 + Ast/src/Cst.cpp | 6 + Ast/src/Parser.cpp | 75 + Ast/src/PrettyPrinter.cpp | 15 + CLI/src/Analyze.cpp | 4 +- CLI/src/Compile.cpp | 8 +- CLI/src/Repl.cpp | 16 +- CLI/src/ReplRequirer.cpp | 2 + CodeGen/include/Luau/CodeGen.h | 5 + CodeGen/include/Luau/CodeGenOptions.h | 3 + CodeGen/include/Luau/IrData.h | 5 +- CodeGen/include/Luau/IrUtils.h | 4 + CodeGen/src/CodeGenAssembly.cpp | 9 + CodeGen/src/CodeGenContext.cpp | 286 ++- CodeGen/src/CodeGenContext.h | 43 +- CodeGen/src/CodeGenUtils.cpp | 7 + CodeGen/src/IrBuilder.cpp | 11 +- CodeGen/src/IrLoweringA64.cpp | 7 + CodeGen/src/IrLoweringX64.cpp | 10 +- CodeGen/src/IrRegAllocA64.cpp | 10 +- CodeGen/src/IrRegAllocX64.cpp | 31 +- CodeGen/src/IrUtils.cpp | 3 +- CodeGen/src/OptimizeConstProp.cpp | 140 +- CodeGen/src/OptimizeDeadStore.cpp | 21 + CodeGen/src/SharedCodeAllocator.cpp | 16 +- Compiler/src/Compiler.cpp | 63 + Compiler/src/CostModel.cpp | 3 + Inliner/src/JitInliner.cpp | 21 +- Makefile | 4 +- VM/include/lua.h | 6 +- VM/src/lbuffer.cpp | 45 +- VM/src/ldebug.cpp | 25 +- VM/src/lfunc.cpp | 2 + VM/src/lgc.cpp | 168 +- VM/src/lmem.cpp | 270 ++- VM/src/lmem.h | 16 + VM/src/lobject.h | 9 + VM/src/lstate.cpp | 7 + VM/src/lstate.h | 19 + VM/src/lvmexecute.cpp | 50 +- VM/src/lvmutils.cpp | 4 + tests/AssemblyBuilderA64.test.cpp | 48 + tests/AstJsonEncoder.test.cpp | 38 + tests/AstVisitor.test.cpp | 41 + tests/Autocomplete.test.cpp | 154 ++ tests/Compiler.test.cpp | 65 + tests/Conformance.test.cpp | 165 +- tests/ControlFlowGraph.test.cpp | 871 ++++++++- tests/CostModel.test.cpp | 40 + tests/FragmentAutocomplete.test.cpp | 148 ++ tests/IrAssembly.test.cpp | 9 - tests/IrBuilder.test.cpp | 33 +- tests/IrLowering.test.cpp | 91 +- tests/IrRegAllocX64.test.cpp | 4 - tests/Normalize.test.cpp | 119 ++ tests/OverloadResolver.test.cpp | 36 +- tests/Parser.test.cpp | 209 +++ tests/PrettyPrinter.test.cpp | 53 + tests/Subtyping.test.cpp | 5 +- tests/TypeFunction.test.cpp | 7 - tests/TypeFunction.user.test.cpp | 2 - tests/TypeInfer.aliases.test.cpp | 3 - tests/TypeInfer.classes.test.cpp | 13 + tests/TypeInfer.functions.test.cpp | 13 - tests/TypeInfer.refinements.test.cpp | 54 +- tests/TypeInfer.tables.test.cpp | 20 +- tests/conformance/native.luau | 31 + tests/conformance/whilelocal.luau | 240 +++ .../basic_join.flags-off.nonstrict.output | 12 +- .../basic_join.flags-off.strict.output | 12 +- .../basic_join.flags-on.nonstrict.output | 12 +- .../basic_join.flags-on.strict.output | 12 +- ...on_records_uses.flags-off.nonstrict.output | 2 +- ...sion_records_uses.flags-off.runtime.output | 3 + ...ssion_records_uses.flags-off.strict.output | 2 +- ...ion_records_uses.flags-on.nonstrict.output | 2 +- ...ssion_records_uses.flags-on.runtime.output | 3 + ...ession_records_uses.flags-on.strict.output | 2 +- .../call_expression_records_uses.luau | 4 +- ...ubprop_mismatch.flags-off.nonstrict.output | 2 + ..._subprop_mismatch.flags-off.runtime.output | 0 ...e_subprop_mismatch.flags-off.strict.output | 3 + ...subprop_mismatch.flags-on.nonstrict.output | 2 + ...e_subprop_mismatch.flags-on.runtime.output | 0 ...le_subprop_mismatch.flags-on.strict.output | 3 + ...ments_and_test_table_subprop_mismatch.luau | 4 + .../for_break.flags-off.nonstrict.output | 12 + .../for_break.flags-off.runtime.output | 0 .../for_break.flags-off.strict.output | 12 + .../for_break.flags-on.nonstrict.output | 12 + .../for_break.flags-on.runtime.output | 0 .../for_break.flags-on.strict.output | 12 + .../analysis/cfgconstruction/for_break.luau | 9 + .../for_in_break.flags-off.nonstrict.output | 14 + .../for_in_break.flags-off.runtime.output | 0 .../for_in_break.flags-off.strict.output | 14 + .../for_in_break.flags-on.nonstrict.output | 14 + .../for_in_break.flags-on.runtime.output | 0 .../for_in_break.flags-on.strict.output | 14 + .../cfgconstruction/for_in_break.luau | 11 + .../for_loop.flags-off.nonstrict.output | 9 + .../for_loop.flags-off.runtime.output | 0 .../for_loop.flags-off.strict.output | 9 + .../for_loop.flags-on.nonstrict.output | 9 + .../for_loop.flags-on.runtime.output | 0 .../for_loop.flags-on.strict.output | 9 + .../analysis/cfgconstruction/for_loop.luau | 6 + ...ion_records_use.flags-off.nonstrict.output | 2 +- ...ession_records_use.flags-off.strict.output | 2 +- ...sion_records_use.flags-on.nonstrict.output | 2 +- ...ression_records_use.flags-on.strict.output | 2 +- ...else_expression.flags-off.nonstrict.output | 8 + ...f_else_expression.flags-off.runtime.output | 0 ...if_else_expression.flags-off.strict.output | 8 + ..._else_expression.flags-on.nonstrict.output | 8 + ...if_else_expression.flags-on.runtime.output | 0 .../if_else_expression.flags-on.strict.output | 8 + .../cfgconstruction/if_else_expression.luau | 3 + ...ulti_assignment.flags-off.nonstrict.output | 8 +- .../multi_assignment.flags-off.strict.output | 8 +- ...multi_assignment.flags-on.nonstrict.output | 8 +- .../multi_assignment.flags-on.strict.output | 8 +- ...branch_modifies.flags-off.nonstrict.output | 10 +- ...ne_branch_modifies.flags-off.strict.output | 10 +- ..._branch_modifies.flags-on.nonstrict.output | 10 +- ...one_branch_modifies.flags-on.strict.output | 10 +- ...ment_from_local.flags-off.nonstrict.output | 6 +- ...ignment_from_local.flags-off.strict.output | 6 +- ...nment_from_local.flags-on.nonstrict.output | 6 +- ...signment_from_local.flags-on.strict.output | 6 +- .../repeat_break.flags-off.nonstrict.output | 16 + .../repeat_break.flags-off.runtime.output | 0 .../repeat_break.flags-off.strict.output | 16 + .../repeat_break.flags-on.nonstrict.output | 16 + .../repeat_break.flags-on.runtime.output | 0 .../repeat_break.flags-on.strict.output | 16 + .../cfgconstruction/repeat_break.luau | 9 + ...repeat_continue.flags-off.nonstrict.output | 16 + .../repeat_continue.flags-off.runtime.output | 0 .../repeat_continue.flags-off.strict.output | 16 + .../repeat_continue.flags-on.nonstrict.output | 16 + .../repeat_continue.flags-on.runtime.output | 0 .../repeat_continue.flags-on.strict.output | 16 + .../cfgconstruction/repeat_continue.luau | 9 + .../repeat_until.flags-off.nonstrict.output | 11 + .../repeat_until.flags-off.runtime.output | 0 .../repeat_until.flags-off.strict.output | 11 + .../repeat_until.flags-on.nonstrict.output | 11 + .../repeat_until.flags-on.runtime.output | 0 .../repeat_until.flags-on.strict.output | 11 + .../cfgconstruction/repeat_until.luau | 6 + ...le_reassignment.flags-off.nonstrict.output | 4 +- ...imple_reassignment.flags-off.strict.output | 4 +- ...ple_reassignment.flags-on.nonstrict.output | 4 +- ...simple_reassignment.flags-on.strict.output | 4 +- .../single_local.flags-off.nonstrict.output | 2 +- .../single_local.flags-off.strict.output | 2 +- .../single_local.flags-on.nonstrict.output | 2 +- .../single_local.flags-on.strict.output | 2 +- ...else_unmodified.flags-off.nonstrict.output | 12 +- ...if_else_unmodified.flags-off.strict.output | 12 +- ..._else_unmodified.flags-on.nonstrict.output | 12 +- ..._if_else_unmodified.flags-on.strict.output | 12 +- ...loop_unmodified.flags-off.nonstrict.output | 8 +- ...le_loop_unmodified.flags-off.strict.output | 8 +- ..._loop_unmodified.flags-on.nonstrict.output | 8 +- ...ile_loop_unmodified.flags-on.strict.output | 8 +- .../two_locals.flags-off.nonstrict.output | 4 +- .../two_locals.flags-off.strict.output | 4 +- .../two_locals.flags-on.nonstrict.output | 4 +- .../two_locals.flags-on.strict.output | 4 +- .../while_break.flags-off.nonstrict.output | 11 + .../while_break.flags-off.runtime.output | 0 .../while_break.flags-off.strict.output | 11 + .../while_break.flags-on.nonstrict.output | 11 + .../while_break.flags-on.runtime.output | 0 .../while_break.flags-on.strict.output | 11 + .../analysis/cfgconstruction/while_break.luau | 9 + .../while_continue.flags-off.nonstrict.output | 12 + .../while_continue.flags-off.runtime.output | 0 .../while_continue.flags-off.strict.output | 12 + .../while_continue.flags-on.nonstrict.output | 12 + .../while_continue.flags-on.runtime.output | 0 .../while_continue.flags-on.strict.output | 12 + .../cfgconstruction/while_continue.luau | 10 + .../while_loop.flags-off.nonstrict.output | 12 +- .../while_loop.flags-off.strict.output | 12 +- .../while_loop.flags-on.nonstrict.output | 12 +- .../while_loop.flags-on.strict.output | 12 +- ...ction_and_union.flags-off.nonstrict.output | 1 + ...section_and_union.flags-off.runtime.output | 3 + ...rsection_and_union.flags-off.strict.output | 1 + ...ection_and_union.flags-on.nonstrict.output | 0 ...rsection_and_union.flags-on.runtime.output | 3 + ...ersection_and_union.flags-on.strict.output | 0 ...ization_negate_intersection_and_union.luau | 2 + ...optional_source.flags-off.nonstrict.output | 0 ...ts_optional_source.flags-off.strict.output | 2 + ..._optional_source.flags-on.nonstrict.output | 0 ...cts_optional_source.flags-on.strict.output | 2 + ...al_annotation_rejects_optional_source.luau | 9 + ...basic_typecheck.flags-off.nonstrict.output | 0 ...al_basic_typecheck.flags-off.strict.output | 0 ..._basic_typecheck.flags-on.nonstrict.output | 0 ...cal_basic_typecheck.flags-on.strict.output | 0 .../while_local_basic_typecheck.luau | 10 + ...ble_after_block.flags-off.nonstrict.output | 2 + ...isible_after_block.flags-off.strict.output | 2 + ...ible_after_block.flags-on.nonstrict.output | 2 + ...visible_after_block.flags-on.strict.output | 2 + ...local_binding_not_visible_after_block.luau | 10 + ...rrows_to_truthy.flags-off.nonstrict.output | 0 ..._narrows_to_truthy.flags-off.strict.output | 0 ...arrows_to_truthy.flags-on.nonstrict.output | 0 ...l_narrows_to_truthy.flags-on.strict.output | 0 .../while_local_narrows_to_truthy.luau | 11 + ..._annotated_type.flags-off.nonstrict.output | 0 ...nes_annotated_type.flags-off.strict.output | 0 ...s_annotated_type.flags-on.nonstrict.output | 0 ...ines_annotated_type.flags-on.strict.output | 0 .../while_local_refines_annotated_type.luau | 11 + ...tation_mismatch.flags-off.nonstrict.output | 0 ...nnotation_mismatch.flags-off.strict.output | 6 + ...otation_mismatch.flags-on.nonstrict.output | 0 ...annotation_mismatch.flags-on.strict.output | 6 + ...while_local_table_annotation_mismatch.luau | 6 + ...emory_explosion.flags-off.nonstrict.output | 0 ..._memory_explosion.flags-off.runtime.output | 2 + ...e_memory_explosion.flags-off.strict.output | 0 ...memory_explosion.flags-on.nonstrict.output | 0 ...e_memory_explosion.flags-on.runtime.output | 2 + ...le_memory_explosion.flags-on.strict.output | 0 ...de_13358_large_table_memory_explosion.luau | 701 +++++++ ...nd_access_union.flags-off.nonstrict.output | 0 ...mond_access_union.flags-off.runtime.output | 0 ...amond_access_union.flags-off.strict.output | 2 + ...ond_access_union.flags-on.nonstrict.output | 0 ...amond_access_union.flags-on.runtime.output | 0 ...iamond_access_union.flags-on.strict.output | 2 + .../ride_13358_diamond_access_union.luau | 11 + ...ction_of_tables.flags-off.nonstrict.output | 0 ...section_of_tables.flags-off.runtime.output | 3 + ...rsection_of_tables.flags-off.strict.output | 1 + ...ection_of_tables.flags-on.nonstrict.output | 0 ...rsection_of_tables.flags-on.runtime.output | 3 + ...ersection_of_tables.flags-on.strict.output | 1 + .../write_to_intersection_of_tables.luau | 9 + ...table_overrides.flags-off.nonstrict.output | 0 ...tatable_overrides.flags-off.runtime.output | 0 ...etatable_overrides.flags-off.strict.output | 11 + ...atable_overrides.flags-on.nonstrict.output | 0 ...etatable_overrides.flags-on.runtime.output | 0 ...metatable_overrides.flags-on.strict.output | 8 + .../oss_3053_setmetatable_overrides.luau | 20 + ..._missing_equals.flags-off.nonstrict.output | 1 + ...or_missing_equals.flags-off.runtime.output | 2 + ...ror_missing_equals.flags-off.strict.output | 1 + ...r_missing_equals.flags-on.nonstrict.output | 1 + ...ror_missing_equals.flags-on.runtime.output | 2 + ...rror_missing_equals.flags-on.strict.output | 1 + .../while-local/error_missing_equals.luau | 3 + ...ltiple_bindings.flags-off.nonstrict.output | 4 + ...multiple_bindings.flags-off.runtime.output | 2 + ..._multiple_bindings.flags-off.strict.output | 4 + ...ultiple_bindings.flags-on.nonstrict.output | 4 + ..._multiple_bindings.flags-on.runtime.output | 2 + ...r_multiple_bindings.flags-on.strict.output | 4 + .../while-local/error_multiple_bindings.luau | 3 + 300 files changed, 8682 insertions(+), 1825 deletions(-) create mode 100644 tests/conformance/whilelocal.luau create mode 100644 tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau create mode 100644 tests/golden/analysis/cfgconstruction/for_break.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_break.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/for_break.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_break.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_break.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/for_break.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_break.luau create mode 100644 tests/golden/analysis/cfgconstruction/for_in_break.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_in_break.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/for_in_break.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_in_break.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_in_break.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/for_in_break.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_in_break.luau create mode 100644 tests/golden/analysis/cfgconstruction/for_loop.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_loop.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/for_loop.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_loop.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_loop.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/for_loop.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/for_loop.luau create mode 100644 tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/if_else_expression.luau create mode 100644 tests/golden/analysis/cfgconstruction/repeat_break.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_break.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_break.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_break.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_break.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_break.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_break.luau create mode 100644 tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_continue.luau create mode 100644 tests/golden/analysis/cfgconstruction/repeat_until.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_until.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_until.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_until.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_until.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_until.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/repeat_until.luau create mode 100644 tests/golden/analysis/cfgconstruction/while_break.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/while_break.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/while_break.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/while_break.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/while_break.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/while_break.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/while_break.luau create mode 100644 tests/golden/analysis/cfgconstruction/while_continue.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/while_continue.flags-off.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/while_continue.flags-off.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/while_continue.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/cfgconstruction/while_continue.flags-on.runtime.output create mode 100644 tests/golden/analysis/cfgconstruction/while_continue.flags-on.strict.output create mode 100644 tests/golden/analysis/cfgconstruction/while_continue.luau create mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.runtime.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.strict.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.runtime.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.strict.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau create mode 100644 tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.luau create mode 100644 tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_basic_typecheck.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_basic_typecheck.flags-on.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_basic_typecheck.luau create mode 100644 tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.luau create mode 100644 tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-on.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_narrows_to_truthy.luau create mode 100644 tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-on.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_refines_annotated_type.luau create mode 100644 tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.strict.output create mode 100644 tests/golden/analysis/refinements/while_local_table_annotation_mismatch.luau create mode 100644 tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.runtime.output create mode 100644 tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.strict.output create mode 100644 tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.runtime.output create mode 100644 tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.strict.output create mode 100644 tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.luau create mode 100644 tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.runtime.output create mode 100644 tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.strict.output create mode 100644 tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.runtime.output create mode 100644 tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.strict.output create mode 100644 tests/golden/analysis/tables/ride_13358_diamond_access_union.luau create mode 100644 tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.runtime.output create mode 100644 tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.strict.output create mode 100644 tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.runtime.output create mode 100644 tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.strict.output create mode 100644 tests/golden/analysis/tables/write_to_intersection_of_tables.luau create mode 100644 tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.runtime.output create mode 100644 tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.strict.output create mode 100644 tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.runtime.output create mode 100644 tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.strict.output create mode 100644 tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.luau create mode 100644 tests/golden/syntax/while-local/error_missing_equals.flags-off.nonstrict.output create mode 100644 tests/golden/syntax/while-local/error_missing_equals.flags-off.runtime.output create mode 100644 tests/golden/syntax/while-local/error_missing_equals.flags-off.strict.output create mode 100644 tests/golden/syntax/while-local/error_missing_equals.flags-on.nonstrict.output create mode 100644 tests/golden/syntax/while-local/error_missing_equals.flags-on.runtime.output create mode 100644 tests/golden/syntax/while-local/error_missing_equals.flags-on.strict.output create mode 100644 tests/golden/syntax/while-local/error_missing_equals.luau create mode 100644 tests/golden/syntax/while-local/error_multiple_bindings.flags-off.nonstrict.output create mode 100644 tests/golden/syntax/while-local/error_multiple_bindings.flags-off.runtime.output create mode 100644 tests/golden/syntax/while-local/error_multiple_bindings.flags-off.strict.output create mode 100644 tests/golden/syntax/while-local/error_multiple_bindings.flags-on.nonstrict.output create mode 100644 tests/golden/syntax/while-local/error_multiple_bindings.flags-on.runtime.output create mode 100644 tests/golden/syntax/while-local/error_multiple_bindings.flags-on.strict.output create mode 100644 tests/golden/syntax/while-local/error_multiple_bindings.luau diff --git a/Analysis/include/Luau/AstUtils.h b/Analysis/include/Luau/AstUtils.h index 9ee175700..d1715fefc 100644 --- a/Analysis/include/Luau/AstUtils.h +++ b/Analysis/include/Luau/AstUtils.h @@ -22,19 +22,4 @@ struct TypeGuard std::optional matchTypeGuard(AstExprBinary::Op op, AstExpr* left, AstExpr* right); -// Search through the expression 'expr' for typeArguments that are known to represent -// uniquely held references. Append these typeArguments to 'uniqueTypes'. -void findUniqueTypes(NotNull> uniqueTypes, AstExpr* expr, NotNull> astTypes); - -void findUniqueTypes( - NotNull> uniqueTypes, - AstArray exprs, - NotNull> astTypes -); -void findUniqueTypes( - NotNull> uniqueTypes, - const std::vector& exprs, - NotNull> astTypes -); - } // namespace Luau diff --git a/Analysis/include/Luau/ConstraintGenerator.h b/Analysis/include/Luau/ConstraintGenerator.h index 8a3fd64d2..da6691de2 100644 --- a/Analysis/include/Luau/ConstraintGenerator.h +++ b/Analysis/include/Luau/ConstraintGenerator.h @@ -170,10 +170,10 @@ struct ConstraintGenerator NotNull cgraph; + TypeStateMap* typestate = nullptr; // Defer module-level generalization constraints to the solver so that we can generalize them after all other constraints have been solved. ConstraintPtr moduleGeneralizationConstraint; - CFG::TypeStateMap* typestate = nullptr; ConstraintGenerator( ModulePtr module, NotNull normalizer, @@ -188,7 +188,7 @@ struct ConstraintGenerator NotNull dfg, std::vector requireCycles, NotNull cgraph, - CFG::TypeStateMap* typestate = nullptr + TypeStateMap* typestate = nullptr ); ConstraintSet run(AstStatBlock* block); @@ -263,9 +263,6 @@ struct ConstraintGenerator * @param cv the constraint variant to add. * @return the pointer to the inserted constraint */ - TypeId resolveRHSType(const ScopePtr& scope, Location location, AstExpr* expr); - TypeId resolveLHSType(const ScopePtr& scope, Location location, const CFG::LValue& lv); - NotNull addConstraint(const ScopePtr& scope, const Location& location, ConstraintV cv); /** @@ -339,8 +336,6 @@ struct ConstraintGenerator bool generalize ); - InferencePack checkPack_DEPRECATED(const ScopePtr& scope, AstArray exprs, const std::vector>& expectedTypes = {}); - InferencePack checkPack( const ScopePtr& scope, AstExpr* expr, @@ -398,8 +393,6 @@ struct ConstraintGenerator Inference check(const ScopePtr& scope, AstExprInterpString* interpString); Inference check(const ScopePtr& scope, AstExprInstantiate* explicitTypeInstantiation); - Inference check_DEPRECATED(const ScopePtr& scope, AstExprTable* expr, std::optional expectedType); - Inference check(const ScopePtr& scope, AstExprTable* expr, std::optional expectedType, bool generalize); std::tuple checkBinary( @@ -594,6 +587,14 @@ struct ConstraintGenerator void updateRValueRefinements(const ScopePtr& scope, DefId def, TypeId ty) const; void updateRValueRefinements(Scope* scope, DefId def, TypeId ty) const; void resolveGenericDefaultParameters(const ScopePtr& defnScope, AstStatTypeAlias* alias, const TypeFun& fun); + + // Takes an expression and returns the reaching definition + TypeId getRHSType(AstExpr* expr) const; + // Takes a symbol and returns the type representing the total domain of that local variable + TypeId getLocalDomain(Symbol sym) const; + void expandDomain(AstExpr* l, TypeId rhs) const; + void expandDomain(AstLocal* l, TypeId rhs) const; + void expandDomain(AstExprGlobal* global, TypeId rhs) const; }; } // namespace Luau diff --git a/Analysis/include/Luau/ConstraintSolver.h b/Analysis/include/Luau/ConstraintSolver.h index 9dbeabd0f..b059a320b 100644 --- a/Analysis/include/Luau/ConstraintSolver.h +++ b/Analysis/include/Luau/ConstraintSolver.h @@ -209,6 +209,18 @@ struct ConstraintSolver template void DEPRECATED_emplace(NotNull constraint, TypePackId tp, Args&&... args); + std::optional> lookupTablePropHelper( + NotNull constraint, + TypeId subjectType, + const std::string& propName, + ValueContext context, + TypeIds& blockedTypes, + DenseHashMap>>& cache, + bool inConditional, + bool suppressSimplification + ); + + public: /** Attempt to dispatch a constraint. Returns true if it was successful. If * tryDispatch() returns false, the constraint remains in the unsolved set @@ -256,7 +268,7 @@ struct ConstraintSolver // for a, ... in next_function, t, ... do bool tryDispatchIterableFunction(TypeId nextTy, TypeId tableTy, const IterableConstraint& c, NotNull constraint); - TablePropLookupResult lookupTableProp( + TablePropLookupResult lookupTableProp_DEPRECATED( NotNull constraint, TypeId subjectType, const std::string& propName, @@ -265,7 +277,7 @@ struct ConstraintSolver bool suppressSimplification = false ); - TablePropLookupResult lookupTableProp( + TablePropLookupResult lookupTableProp_DEPRECATED( NotNull constraint, TypeId subjectType, const std::string& propName, @@ -275,6 +287,15 @@ struct ConstraintSolver DenseHashSet& seen ); + TablePropLookupResult lookupTableProp( + NotNull constraint, + TypeId subjectType, + const std::string& propName, + ValueContext context, + bool inConditional, + bool suppressSimplification + ); + /** * Generate constraints to unpack the types of srcTypes and assign each * value to the corresponding BlockedType in destTypes. diff --git a/Analysis/include/Luau/ControlFlowGraph.h b/Analysis/include/Luau/ControlFlowGraph.h index 1ff70747d..ac7c705ba 100644 --- a/Analysis/include/Luau/ControlFlowGraph.h +++ b/Analysis/include/Luau/ControlFlowGraph.h @@ -2,45 +2,62 @@ #pragma once #include "Luau/Ast.h" +#include "Luau/ControlFlow.h" #include "Luau/DenseHash.h" +#include "Luau/HashUtil.h" #include "Luau/NotNull.h" +#include "Luau/InsertionOrderedMap.h" #include "Luau/Symbol.h" #include "Luau/TypedAllocator.h" #include "Luau/Variant.h" -#include #include -#include -#include -namespace Luau::CFG +namespace Luau { // The control flow graph is a layer over the existing AST that models // explicit control flow for a single file of luau code // The CFG maintains an SSA mapping from a source AST to definition version - -struct Block; struct SymDef; +struct Definition; +struct Block; struct CFGAllocator; -using Definition = SymDef; struct Declare; +struct LocalFunction; +struct GlobalFunction; + +struct Arg; +struct Upvalue; + struct Assign; struct Join; struct Refine; struct Dead; -using Instruction = Variant; + +using Instruction = Variant; using BlockId = NotNull; -using DefId = NotNull; -using InstrId = NotNull; +using SSAId = NotNull; +using InstructionId = NotNull; -using LValue = Variant; +struct Index +{ + Symbol source; + AstExpr* sourceExpr = nullptr; + std::vector path; + + // Walks an index chain (x.y.z or x["y"]["z"]) back to a root local/global. + // Returns nullopt if the chain has a non-static index or non-local/global root. + static std::optional fromExpr(AstExpr* expr); +}; -struct LValueHash +using LHS = Variant; + +struct LHSHash { - size_t operator()(const LValue& lvalue) const + size_t operator()(const LHS& lvalue) const { size_t seed = std::hash()(lvalue.index()); if (auto* sym = lvalue.get_if()) @@ -51,68 +68,159 @@ struct LValueHash } }; -namespace CFGRefinement +struct Truthy { + bool operator==(const Truthy&) const + { + return true; + } +}; -struct Proposition; -struct Conjunction; -struct Disjunction; -struct Negation; +struct Falsy +{ + bool operator==(const Falsy&) const + { + return true; + } +}; -using Refinement = Variant; -using RefinementId = NotNull; +struct TypeEq +{ + std::string type; + bool isTypeOf; -// Proposition about a def: -// - if type is not nil: sense = true => ptr == type, sense = false => ptr ~- type -// - `type` nullopt: `def` & truthy when sense, `def` & falsy when !sense -struct Proposition + bool operator==(const TypeEq& other) const + { + return type == other.type && isTypeOf == other.isTypeOf; + } +}; + +struct TypeNeq { - DefId ptr; - std::optional type; - // Distinguishes between type and typeof - bool isTypeof; - bool sense; + std::string type; + bool isTypeOf; + + bool operator==(const TypeNeq& other) const + { + return type == other.type && isTypeOf == other.isTypeOf; + } }; -struct Conjunction +struct StringSingletonValue { - RefinementId lhs; - RefinementId rhs; + std::string value; + + bool operator==(const StringSingletonValue& other) const + { + return value == other.value; + } }; -struct Disjunction +struct BooleanSingletonValue { - RefinementId lhs; - RefinementId rhs; + bool value; + + bool operator==(const BooleanSingletonValue& other) const + { + return value == other.value; + } }; -struct Negation +struct NilSingletonValue { - RefinementId refinement; + bool operator==(const NilSingletonValue& other) const + { + return true; + } }; -template -const T* get(RefinementId r) +using SingletonValue = Variant; + +struct SingletonEq { - return get_if(r.get()); -} + SingletonValue v; -struct RefinementArena + bool operator==(const SingletonEq& other) const + { + return v == other.v; + } +}; + +struct SingletonNeq { - RefinementId proposition(DefId def, bool sense); - RefinementId typeProposition(DefId def, std::optional type, bool isTypeof, bool sense); + SingletonValue v; + bool operator==(const SingletonNeq& other) const + { + return v == other.v; + } +}; - RefinementId conjunction(RefinementId lhs, RefinementId rhs); - RefinementId disjunction(RefinementId lhs, RefinementId rhs); - RefinementId negation(RefinementId r); +using LeafConstraint = Variant; - void freeze(); +struct HasShape +{ + std::vector path; + LeafConstraint constraint; -private: - TypedAllocator allocator; + bool operator==(const HasShape& other) const + { + return path == other.path && constraint == other.constraint; + } }; -} // namespace CFGRefinement +using NarrowingConstraint = Variant; + +} // namespace Luau + +template<> +struct std::hash +{ + size_t operator()(const Luau::NarrowingConstraint& c) const + { + size_t seed = std::hash()(c.index()); + auto hashSingletonValue = [&seed](const Luau::SingletonValue& value) + { + Luau::hashCombine(seed, std::hash()(value.index())); + if (auto* stringValue = value.get_if()) + Luau::hashCombine(seed, std::hash()(stringValue->value)); + else if (auto* booleanValue = value.get_if()) + Luau::hashCombine(seed, std::hash()(booleanValue->value)); + }; + + if (auto* eq = c.get_if()) + { + Luau::hashCombine(seed, std::hash()(eq->type)); + Luau::hashCombine(seed, std::hash()(eq->isTypeOf)); + } + else if (auto* neq = c.get_if()) + { + Luau::hashCombine(seed, std::hash()(neq->type)); + Luau::hashCombine(seed, std::hash()(neq->isTypeOf)); + } + else if (auto eq = c.get_if()) + { + hashSingletonValue(eq->v); + } + else if (auto* neq = c.get_if()) + { + hashSingletonValue(neq->v); + } + else if (auto* hs = c.get_if()) + { + for (const auto& p : hs->path) + Luau::hashCombine(seed, std::hash()(p)); + Luau::hashCombine(seed, std::hash()(hs->constraint.index())); + if (auto* eq = hs->constraint.get_if()) + hashSingletonValue(eq->v); + else if (auto* neq = hs->constraint.get_if()) + hashSingletonValue(neq->v); + } + return seed; + } +}; + +namespace Luau +{ // A versioned identity for a local variable at a specific point in the program struct SymDef @@ -148,76 +256,164 @@ struct SymDef } }; -// Declarations turn into one declaration per line -// E.g. local x, y, z ... -// local x_i -// local y_j -// local z_k -// Each of these are defs +struct Definition +{ + explicit Definition(SymDef&& d) + : d(std::move(d)) + { + } + std::string versionedName() const + { + return d.versionedName(); + } + + std::string name() const + { + return d.name(); + } + + Symbol getSym() const + { + return d.sym; + } + + void redirect(Definition* other) + { + this->follow = other; + } + + Definition* materialize() + { + Definition* curr = this; + while (curr->follow != nullptr) + curr = curr->follow; + return curr; + } + +private: + SymDef d; + Definition* follow = nullptr; +}; + +// v1 := Declare +// Declare instructions observe a `local/const ...` statement and introduce a new SSA definition for the declared variable. struct Declare { - Declare(DefId def, AstStatLocal* source) + explicit Declare(SSAId def) : def(def) - , source(source) { } - DefId def; - AstStatLocal* source; + SSAId def; }; -// Assignments turn into one 're-def' per line -// E.g. x, y, z = .... -// x_i . -// y_j . -// z_k . +// v1 := LocalFunction +// Local functions introduce a new definition for their name's domain, but unlike +// Declare they have no rhs expression: the function's type is produced by the +// ConstraintGenerator, which owns and binds the domain placeholder directly. +struct LocalFunction +{ + explicit LocalFunction(SSAId def) + : def(def) + { + } + + SSAId def; +}; + +// v1 := GlobalFunction +// Global functions introduce a new definition for their name's domain, but unlike +// Declare they have no rhs expression: the function's type is produced by the +// ConstraintGenerator, which owns and binds the domain placeholder directly. +struct GlobalFunction +{ + explicit GlobalFunction(SSAId def) + : def(def) + { + } + + SSAId def; +}; + +// Function parameters introduce a new definition for their name's domain like a +// Declare, but their initial value has no rhs expression: the ConstraintGenerator +// binds it from the function signature. The parameter remains a mutable local, so +// its domain can still be extended by later assignments. +struct Arg +{ + explicit Arg(SSAId def) + : def(def) + { + } + + SSAId def; +}; + +// def := Upvalue symbol +// Upvalues are captured values in functions that must not participate in type stating. +// They are introduced as SSA definitions for the captured variable. +struct Upvalue +{ + explicit Upvalue(SSAId def) + : def(def) + { + } + SSAId def; + Symbol s; +}; + + +// def := Assign +// Assign instructions observe the result of assignments in the source ast struct Assign { - Assign(DefId def, AstStatAssign* source) + explicit Assign(SSAId def) : def(def) - , source(source) { } - DefId def; - AstStatAssign* source; + SSAId def; }; +// A dead instruction is one that is eliminated from the final CFG +// Dead instructions are produced as a result of the braun SSA algorithm +// eliminating trivial phi nodes. struct Dead { }; +// v2 := Join(v_0, v_1) // phi nodes - When multiple control flow paths hit this point, this denotes that // a definition is influenced by multiple distinct control flow paths. struct Join { - explicit Join(DefId definition) + explicit Join(SSAId definition) : definition(definition) { } - DefId definition; - std::vector operands; + SSAId definition; + std::vector operands; }; -// Refine instructions attach type refinements to def. The attached -// Proposition tells you how to interpret the def. The Proposition is owned by -// the RefinementArena (lives inside a Refinement variant slot). + +// definition := Refine target constraint +// where constraint is a NarrowingConstraint +// e.g. v1 := Refine v0 HasShape { x = { y = { z isTruthy }}} +// in other words v1 is the result of refining v0.x.y.z and applying the `isTruthy` constraint +// to the property struct Refine { - Refine(DefId definition, const CFGRefinement::Proposition& prop) + Refine(SSAId definition, SSAId target, NarrowingConstraint&& c) : definition(definition) - , toRefine(prop.ptr) - , type(prop.type) - , isTypeof(prop.isTypeof) - , sense(prop.sense) + , target(target) + , constraint(std::move(c)) { } + SSAId getTarget() const; - DefId definition; - DefId toRefine; - std::optional type; - bool isTypeof; - bool sense; + SSAId definition; + SSAId target; + NarrowingConstraint constraint; }; enum class BlockKind @@ -235,10 +431,10 @@ struct Block bool containsDefinition(Symbol sym) const; Definition* getReachingDefinition(Symbol sym) const; - void setReachingDefinition(Symbol sym, DefId def); + void setReachingDefinition(Symbol sym, SSAId def); - const std::vector& getInstructions() const; + const std::vector& getInstructions() const; const std::vector& getPredecessors() const; const std::vector& getSuccessors() const; @@ -246,11 +442,10 @@ struct Block std::string debugName; private: - std::vector instructions; + std::vector instructions; std::vector predecessors; std::vector successors; DenseHashMap reachingDefinitions; - friend struct CFGBuilder; }; @@ -259,23 +454,37 @@ struct CFGAllocator Block* newBlock(BlockKind kind, std::string debugName); template - InstrId newInstruction(Args&&... args) + InstructionId newInstruction(Args&&... args) { LUAU_ASSERT(!frozen); Instruction* inst = instructions.allocate(T{std::forward(args)...}); return NotNull{inst}; } - DefId newDefinition(Symbol sym, size_t version); - CFGRefinement::RefinementArena refinementArena; + SSAId newDefinition(Symbol sym); void freeze(); private: + size_t nextVersionIndex(Symbol sym) + { + if (auto ref = versionCounter.find(sym)) + { + *ref += 1; + return *ref; + } + + versionCounter[sym] = 0; + return 0; + } + + TypedAllocator block; TypedAllocator instructions; TypedAllocator defs; bool frozen = false; + + DenseHashMap versionCounter; }; struct ControlFlowGraph @@ -286,10 +495,11 @@ struct ControlFlowGraph } Definition* getUseDef(AstExpr* expr) const; - Definition* getLhsDef(const LValue& lv) const; - Definition* resolve(Definition* def) const; + Definition* getLhsDef(const LHS& lv) const; std::vector blocks; + std::vector functionBlocks; + size_t entryIdx = 0; const std::vector& rpo() const @@ -299,9 +509,9 @@ struct ControlFlowGraph private: DenseHashMap useDefs; - DenseHashMap lhsDefs; - DenseHashMap forwards; + DenseHashMap lhsDefs; + std::vector postOrderAtRoot(BlockId root, DenseHashSet& visited); BlockId newBlock(BlockKind kind, std::string debugName = ""); void computeRPO(); @@ -310,75 +520,144 @@ struct ControlFlowGraph friend struct CFGBuilder; }; -struct CFGBuilder +struct LoweringResult { - static std::unique_ptr makeCFG(NotNull allocator, AstStatBlock* block); + LoweringResult(SSAId def, NarrowingConstraint&& c) + : def(def) + , constraint(std::move(c)) + { + } -private: - explicit CFGBuilder(NotNull allocator); + explicit LoweringResult(SSAId def) + : def(def) + , constraint(std::nullopt) + { + } - void lower(AstStat* statement); - void lower(AstStatBlock* statement); - void lower(AstStatLocal* local); - void lower(AstStatAssign* assn); - void lower(AstStatIf* statIf); - void lower(AstStatWhile* statWhile); - void lower(AstStatExpr* stat); - void lowerExpr(AstExpr* expression); - void lowerExpr(AstExprLocal* local); - void lowerExpr(AstExprCall* call); + SSAId def; + std::optional constraint = std::nullopt; +}; - bool tryLowerAssertion(AstExprCall* call); +struct LoweringExprContext +{ + Block* thenBlock = nullptr; + Block* elseBlock = nullptr; + bool inConditionalContext = false; + bool sense = true; +}; + +struct CFGBuilder +{ + static std::unique_ptr makeCFG(NotNull allocator, AstStatBlock* block); - // Returns a refinement tree describing the truthy interpretation of `condition`, - // or nullopt if no refinement can be extracted. Records use->def for any reads. - std::optional resolveCondition(AstExpr* condition); - // Walks `refinement` and emits one Refine instruction per Proposition into `block`, - // each with a fresh def for the refined symbol. - void emitRefineInstruction(Block* block, CFGRefinement::RefinementId refinement); +private: + explicit CFGBuilder(NotNull allocator); + void finalize(AstStatBlock* root); + void validate(AstStatBlock* root); + + ControlFlow lower(AstStat* statement); + ControlFlow lower(AstStatBlock* block); + ControlFlow lower(AstStatLocal* local); + ControlFlow lower(AstStatAssign* assn); + ControlFlow lower(AstStatIf* statIf); + ControlFlow lower(AstStatWhile* statWhile); + ControlFlow lower(AstStatRepeat* statRepeat); + ControlFlow lower(AstStatBreak* statBreak); + ControlFlow lower(AstStatContinue* statContinue); + ControlFlow lower(AstStatReturn* statReturn); + ControlFlow lower(AstStatExpr* stat); + ControlFlow lower(AstStatFor* statFor); + ControlFlow lower(AstStatForIn* statForIn); + ControlFlow lower(AstStatCompoundAssign* compAssn); + ControlFlow lower(AstStatFunction* statFn); + ControlFlow lower(AstStatLocalFunction* localFn); + ControlFlow lower(AstStatTypeAlias* typeAlias); + ControlFlow lower(AstStatTypeFunction* typeFn); + ControlFlow lower(AstStatDeclareGlobal* declGlobal); + ControlFlow lower(AstStatDeclareFunction* declFn); + ControlFlow lower(AstStatClass* declClass); + ControlFlow lower(AstStatDeclareExternType* declExternType); + ControlFlow lower(AstStatError* err); + + + std::optional lowerExpr(LoweringExprContext& ctx, AstExpr* expression); + + std::optional lowerExpr(LoweringExprContext& ctx, AstExprGroup* group); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprLocal* local); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprGlobal* global); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprVarargs* varargs); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprCall* call); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprIndexName* indexName); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprIndexExpr* indexExpr); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprFunction* func); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprTable* table); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprUnary* unary); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprBinary* binop); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprTypeAssertion* typeAssertion); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprIfElse* ifElse); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprInterpString* interpStr); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprInstantiate* instantiate); + std::optional lowerExpr(LoweringExprContext& ctx, AstExprError* err); + + // Discriminates the LValue form and emits the appropriate SSA instruction. + void lowerLValue(LoweringExprContext& ctx, AstExpr* target); + + std::optional handleAssert(LoweringExprContext& ctx, const AstExprCall& call); + + // Wires currentBlock to truthyDest/falsyDest and emits Refine instructions + // using the LowerResult's constraint (and its inverse). + void emitConditionalRefine(LoweringResult& result, Block* truthyDest, Block* falsyDest); // Allocates a fresh unsealed block. If `pred` is non-null, wires `pred -> b`. - Block* newBlock(BlockKind kind, std::string debugName, Block* pred = nullptr); + BlockId newUnsealedBlock(BlockKind kind, std::string debugName, Block* pred = nullptr); + // Allocates a freshly sealed block. + BlockId newSealedBlock(BlockKind kind, std::string debugName, Block* pred = nullptr); // Allocates an Instruction of type T and appends it to `block`. template - InstrId emit(Block* block, Args&&... args) + InstructionId emit(Block* block, Args&&... args) { - InstrId inst = allocator->newInstruction(std::forward(args)...); - recordUses(inst); + InstructionId inst = allocator->newInstruction(std::forward(args)...); block->instructions.emplace_back(inst); return inst; } - std::pair> emitJoin(Block* block, Symbol sym); + template + SSAId emitDefHelper(Symbol symbol, Block* block, Args&&... args) + { + static_assert(std::is_constructible_v, "defining instructions take their SSAId first"); + SSAId def = newDefinition(symbol); + emit(block, def, std::forward(args)...); + block->setReachingDefinition(symbol, def); + return def; + }; + + std::pair> emitJoin(BlockId block, Symbol sym); // Mints a fresh SymDef with a monotonically increasing version per symbol. - DefId newDefinition(Symbol sym); + SSAId newDefinition(Symbol sym); // Def lookup for `sym` at `block`. // If the block is unsealed: emits an incomplete phi and returns that def, since the block might // be given a predecessor that would causes us to gain a new phi operand // If block is sealed + single predecessor: recurses into the pred. // If block is sealed + multiple predecessors: emits a complete phi and fills operands. - DefId readVariable(BlockId block, Symbol sym); + SSAId readVariable(BlockId block, Symbol sym); // Reads `sym` from each predecessor of `block` to populate `j->operands`, // then attempts to trim if the join collapses to a single def. - DefId fillJoinOperands(Block* block, InstrId instr, Join* j); + SSAId fillJoinOperands(Block* block, InstructionId instr, Join* j); - DefId trimTrivialJoin(InstrId inst, Join* j); - - // Registers which defs `inst` consumes into the usingInstructions map. - void recordUses(InstrId inst); + SSAId trimTrivialJoin(InstructionId inst, Join* j); // Returns the next version index for `sym`; first call returns 0. size_t nextVersionIndex(Symbol sym); // True iff `seal` has been called on `b` (no more predecessors will be added). - bool isSealed(Block* b); + bool isSealed(BlockId b); // Marks `b` as sealed and flushes any incomplete phis by filling their operands. - void seal(Block* b); + void seal(BlockId b); // RAII guard: switches currentBlock on construction, restores on destruction. // Read currentBlock before the scope ends to capture the exit block. @@ -403,15 +682,56 @@ struct CFGBuilder Block* saved; }; + struct LoopContext + { + LoopContext(BlockId loopHeader, BlockId loopExit) + : loopHeader(loopHeader) + , loopExit(loopExit) + { + } + BlockId loopHeader; + BlockId loopExit; + }; + + std::vector loopStack; + + + struct PushLoopContext + { + PushLoopContext(std::vector& context, BlockId loopHeader, BlockId loopExit) + : context(context) + { + context.emplace_back(loopHeader, loopExit); + } + + ~PushLoopContext() + { + context.pop_back(); + } + + PushLoopContext(const PushLoopContext&) = delete; + PushLoopContext& operator=(const PushLoopContext&) = delete; + + std::vector& context; + }; + + LoopContext* currentLoop() + { + if (loopStack.empty()) + { + return nullptr; + } + return &loopStack.back(); + } + + std::unique_ptr cfg; NotNull allocator; - NotNull currentBlock; - DenseHashSet sealedBlocks; - DenseHashMap> incompleteJoins; - DenseHashMap versionCounter; - // Maps defs to the Instructions that use them - DenseHashMap> usingInstructions; + DenseHashSet sealedBlocks; + DenseHashMap> incompleteJoins; + NotNull currentBlock; + DenseHashMap> functionCaptures; }; -} // namespace Luau::CFG +} // namespace Luau diff --git a/Analysis/include/Luau/DumpCFG.h b/Analysis/include/Luau/DumpCFG.h index a82c77abe..6114732a4 100644 --- a/Analysis/include/Luau/DumpCFG.h +++ b/Analysis/include/Luau/DumpCFG.h @@ -1,22 +1,29 @@ // This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details #pragma once -#include -namespace Luau::CFG -{ -struct Block; -struct ControlFlowGraph; -} // namespace Luau::CFG +#include "Luau/ControlFlowGraph.h" +#include "Luau/NotNull.h" + +#include namespace Luau { -std::string dumpCFG(const CFG::ControlFlowGraph& cfg); +std::string dumpCFG(const ControlFlowGraph& cfg); // Emits a single-line JSON representation of the CFG in the format consumed by // mozilla-spidermonkey/iongraph. Paste the output into a file and upload it to // the iongraph viewer here: https://mozilla-spidermonkey.github.io/iongraph/ -std::string dumpCFGJson(const CFG::ControlFlowGraph& cfg); +std::string dumpCFGJson(const ControlFlowGraph& cfg); + +// lldb helpers — call from the debugger: `p dump(def)`pp, `p dump(instr)`, etc. +std::string dump(const Definition* def); +std::string dump(const Instruction* inst); +void dump(const Block* block); + +std::string dump(SSAId def); +std::string dump(InstructionId inst); +void dump(BlockId block); } // namespace Luau diff --git a/Analysis/include/Luau/Normalize.h b/Analysis/include/Luau/Normalize.h index c8cc3272f..4701be6c1 100644 --- a/Analysis/include/Luau/Normalize.h +++ b/Analysis/include/Luau/Normalize.h @@ -392,6 +392,8 @@ class Normalizer void subtractSingleton(NormalizedType& here, TypeId ty); NormalizationResult intersectNormalWithNegationTy(TypeId toNegate, NormalizedType& intersect); + NormalizationResult unionNormalWithNegationTy(NormalizedType& here, TypeId there); + // ------- Normalizing intersections TypeId intersectionOfTops(TypeId here, TypeId there); TypeId intersectionOfBools(TypeId here, TypeId there); diff --git a/Analysis/include/Luau/OverloadResolver.h b/Analysis/include/Luau/OverloadResolver.h index 92438cf30..28fe8bafe 100644 --- a/Analysis/include/Luau/OverloadResolver.h +++ b/Analysis/include/Luau/OverloadResolver.h @@ -90,7 +90,11 @@ struct OverloadResolution std::vector nonFunctions; // Overloads that could match, but require that other constraints also be satisfied. - std::vector>> potentialOverloads; + std::vector potentialOverloads; + + // Overloads that could match, but require that other constraints also be satisfied. + // Clip with LuauOneBitAssumedConstraintTracking + std::vector>> potentialOverloads_DEPRECATED; // Overloads that have the correct arity, but do not work. std::vector> incompatibleOverloads; @@ -138,7 +142,6 @@ struct OverloadResolver TypeId fnTy, TypePackId args, Location fnLocation, - NotNull> uniqueTypes, bool useFreeTypeBounds ); @@ -157,18 +160,16 @@ struct OverloadResolver OverloadResolution& result, TypeId fnTy, TypePackId argsPack, - Location fnLocation, - NotNull> uniqueTypes + Location fnLocation ); - void testFunction(OverloadResolution& result, TypeId fnTy, TypePackId argsPack, Location fnLocation, NotNull> uniqueTypes); + void testFunction(OverloadResolution& result, TypeId fnTy, TypePackId argsPack, Location fnLocation); void testFunctionOrCallMetamethod( OverloadResolution& result, TypeId fnTy, TypePackId argsPack, - Location fnLocation, - NotNull> uniqueTypes + Location fnLocation ); void maybeEmplaceError( diff --git a/Analysis/include/Luau/Subtyping.h b/Analysis/include/Luau/Subtyping.h index ac514d5c9..a2ed01635 100644 --- a/Analysis/include/Luau/Subtyping.h +++ b/Analysis/include/Luau/Subtyping.h @@ -118,6 +118,7 @@ struct SubtypingResult bool normalizationTooComplex = false; bool isCacheable = true; bool isErrorSuppressing = false; + bool assumingConstraints = false; ErrorVec errors; /// The reason for isSubtype to be false. May not be present even if /// isSubtype is false, depending on the input types. @@ -126,7 +127,7 @@ struct SubtypingResult // If this subtype result required testing free types, we might be making // assumptions about what the free type eventually resolves to. If so, // those assumptions are recorded here. - std::vector assumedConstraints; + std::vector assumedConstraints_DEPRECATED; /// If any generic bounds were invalid, report them here std::vector genericBoundsMismatches; @@ -309,7 +310,6 @@ struct Subtyping SubtypingEnvironment& env, const TableType* subTable, const TableType* superTable, - bool forceCovariantTest, NotNull scope ); @@ -351,7 +351,6 @@ struct Subtyping const Property& subProperty, const Property& superProperty, const std::string& name, - bool forceCovariantTest, NotNull scope ); diff --git a/Analysis/include/Luau/TypeStateMap.h b/Analysis/include/Luau/TypeStateMap.h index 677c9e357..af45a08c6 100644 --- a/Analysis/include/Luau/TypeStateMap.h +++ b/Analysis/include/Luau/TypeStateMap.h @@ -10,14 +10,11 @@ #include "Luau/TypeFwd.h" #include "Luau/Scope.h" -#include +#include namespace Luau { -namespace CFG -{ - // TypeStateMap walks a ControlFlowGraph in SSA form and assigns a TypeId to every // Definition. The mapping is keyed on the definition. // @@ -35,21 +32,40 @@ struct TypeStateMap { TypeStateMap(NotNull arena, NotNull globalScope, NotNull builtinTypes, NotNull g); void computeTypes(); + void finalizeDomains(); TypeId getRHSType(AstExpr* expr); - TypeId getLHSType(const LValue& lv) const; - std::optional getOptionalConstraint(TypeId ty) const; + TypeId getDomain(Symbol sym) const; + void expandDomain(const LHS& lv, TypeId rhs); + std::vector getConstraints(TypeId ty) const; + + std::vector flushConstraintsRequiringFinalization(); + private: - TypeId getType(Definition* def) const; - void handleInstruction(InstrId id); - TypeId getDiscriminantOf(const Refine& refine); + TypeId getType(SSAId def) const; + void handleInstruction(InstructionId id); + TypeId getDiscriminantOf(const NarrowingConstraint& constraint); + void addConstraintForType(TypeId ty, ConstraintV&& constraint); + void transferConstraints(TypeId from, TypeId to); + - DenseHashMap defTypes; + TypeId newBlockedType(SSAId d); + // This tracks a mapping from AstLocal/Global -> placeholder. + DenseHashMap lvalueDomain; + // This tracks the SSA defs that participate in the domain of a given local + DenseHashMap> domainStates; + + + DenseHashMap defTypes; + + DenseHashMap constraints; // Mapping from types to the constraints they require to be solved // Join instructions will require simplification constraints // Refine instructions will require refinement constraints - DenseHashMap typesRequiringConstraint; + + DenseHashMap> typesRequiringConstraints; + DenseHashMap> locals; NotNull arena; NotNull builtinTypes; @@ -57,6 +73,5 @@ struct TypeStateMap NotNull globalScope; }; -} // namespace CFG } // namespace Luau diff --git a/Analysis/src/AstJsonEncoder.cpp b/Analysis/src/AstJsonEncoder.cpp index 99f24cd72..872031353 100644 --- a/Analysis/src/AstJsonEncoder.cpp +++ b/Analysis/src/AstJsonEncoder.cpp @@ -9,6 +9,7 @@ #include LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) +LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) namespace Luau { @@ -763,6 +764,10 @@ struct AstJsonEncoder : public AstVisitor PROP(condition); PROP(body); PROP(hasDo); + if (FFlag::DebugLuauWhileLocalAnalysis && node->conditionLocal) + { + write("conditionLocal", node->conditionLocal); + } } ); } diff --git a/Analysis/src/AstUtils.cpp b/Analysis/src/AstUtils.cpp index 6cec8a01b..ae6833163 100644 --- a/Analysis/src/AstUtils.cpp +++ b/Analysis/src/AstUtils.cpp @@ -40,73 +40,4 @@ std::optional matchTypeGuard(AstExprBinary::Op op, AstExpr* left, Ast }; } -struct AstExprTableFinder : AstVisitor -{ - NotNull> result; - NotNull> astTypes; - - explicit AstExprTableFinder(NotNull> result, NotNull> astTypes) - : result(result) - , astTypes(astTypes) - { - } - - bool visit(AstExpr* expr) override - { - return false; - } - - bool visit(AstExprTable* tbl) override - { - const TypeId* ty = astTypes->find(tbl); - LUAU_ASSERT(ty); - if (ty) - result->insert(*ty); - - return true; - } -}; - -void findUniqueTypes(NotNull> uniqueTypes, AstExpr* expr, NotNull> astTypes) -{ - AstExprTableFinder finder{uniqueTypes, astTypes}; - expr->visit(&finder); -} - -template -void findUniqueTypes( - NotNull> uniqueTypes, - Iter startIt, - Iter endIt, - NotNull> astTypes -) -{ - while (startIt != endIt) - { - AstExpr* expr = *startIt; - if (expr->is()) - findUniqueTypes(uniqueTypes, expr, astTypes); - ++startIt; - } -} - - -void findUniqueTypes( - NotNull> uniqueTypes, - AstArray exprs, - NotNull> astTypes -) -{ - findUniqueTypes(uniqueTypes, exprs.begin(), exprs.end(), astTypes); -} - -void findUniqueTypes( - NotNull> uniqueTypes, - const std::vector& exprs, - NotNull> astTypes -) -{ - findUniqueTypes(uniqueTypes, exprs.begin(), exprs.end(), astTypes); -} - } // namespace Luau diff --git a/Analysis/src/AutocompleteCore.cpp b/Analysis/src/AutocompleteCore.cpp index edacd1af5..0b0675968 100644 --- a/Analysis/src/AutocompleteCore.cpp +++ b/Analysis/src/AutocompleteCore.cpp @@ -31,6 +31,7 @@ LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAGVARIABLE(LuauUseExplicitTypeArgsInGenerics) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauRefactorAutocompleteAncestry) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) static constexpr std::array kStatementStartingKeywords = {"while", "if", "local", "repeat", "function", "do", "for", "return", "break", "continue", "type", "export", "const"}; @@ -2297,6 +2298,12 @@ AutocompleteResult autocomplete_( { return autocompleteExpression(*module, builtinTypes, typeArena, ancestry, scopeAtPosition, position); } + else if (AstStatWhile* statWhile = node->as(); + FFlag::DebugLuauWhileLocalSyntax && statWhile && statWhile->conditionLocal && statWhile->conditionEqualsLocation && + position >= statWhile->conditionEqualsLocation->end && (!statWhile->hasDo || position < statWhile->doLocation.begin)) + { + return autocompleteExpression(*module, builtinTypes, typeArena, ancestry, scopeAtPosition, position); + } else if (AstStatIf* statIf = node->as(); statIf && !statIf->elseLocation.has_value()) { return { diff --git a/Analysis/src/BuiltinTypeFunctions.cpp b/Analysis/src/BuiltinTypeFunctions.cpp index 9dcb78444..fbef723cb 100644 --- a/Analysis/src/BuiltinTypeFunctions.cpp +++ b/Analysis/src/BuiltinTypeFunctions.cpp @@ -28,6 +28,7 @@ LUAU_FASTFLAGVARIABLE(LuauRefineNotNilWaitsForBlockedTarget) LUAU_FASTFLAGVARIABLE(LuauSetmetatableOverrides) LUAU_FLAGVERSION(LuauSetmetatableOverrides, 2) LUAU_FASTFLAG(LuauTraverseScopeToFunction) +LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) namespace Luau { @@ -130,11 +131,18 @@ static std::optional solveFunctionCall(NotNull ctx->builtins, ctx->arena, ctx->normalizer, ctx->typeFunctionRuntime, ctx->scope, ctx->ice, ctx->limits, location ); - DenseHashSet uniqueTypes; - OverloadResolution resolution = resolver->resolveOverload(fnTy, argsPack, location, NotNull{&uniqueTypes}, /* useFreeTypeBounds */ false); + OverloadResolution resolution = resolver->resolveOverload(fnTy, argsPack, location, /* useFreeTypeBounds */ false); - if (resolution.ok.empty() && resolution.potentialOverloads.empty()) - return std::nullopt; + if (FFlag::LuauOneBitAssumedConstraintTracking) + { + if (resolution.ok.empty() && resolution.potentialOverloads.empty()) + return std::nullopt; + } + else + { + if (resolution.ok.empty() && resolution.potentialOverloads_DEPRECATED.empty()) + return std::nullopt; + } SelectedOverload selected = resolution.getUnambiguousOverload(); diff --git a/Analysis/src/ConstraintGenerator.cpp b/Analysis/src/ConstraintGenerator.cpp index fc1115056..dce172f87 100644 --- a/Analysis/src/ConstraintGenerator.cpp +++ b/Analysis/src/ConstraintGenerator.cpp @@ -47,11 +47,11 @@ LUAU_FASTFLAGVARIABLE(DebugLuauCFG) LUAU_FASTFLAG(LuauCyclicRequireTypeInference) LUAU_FASTFLAGVARIABLE(DebugLuauExactTableTypes) LUAU_FASTFLAG(LuauSetmetatableOverrides) -LUAU_FASTFLAGVARIABLE(LuauThreadGeneralizeThroughConstraintGeneration) LUAU_FASTFLAGVARIABLE(LuauExperimentalIfLocalAnalysis) LUAU_FLAGVERSION(LuauExperimentalIfLocalAnalysis, 2) LUAU_FASTFLAG(LuauTraverseScopeToFunction) LUAU_FASTFLAGVARIABLE(LuauUnconditionallyVisitTypeAliasParams) +LUAU_FASTFLAGVARIABLE(DebugLuauWhileLocalAnalysis) namespace Luau { @@ -312,7 +312,7 @@ ConstraintGenerator::ConstraintGenerator( NotNull dfg, std::vector requireCycles, NotNull cgraph, - CFG::TypeStateMap* typestate + TypeStateMap* typestate ) : module(module) , sharedModuleName(std::make_shared(module->name)) @@ -339,6 +339,13 @@ ConstraintSet ConstraintGenerator::run(AstStatBlock* block) { visitModuleRoot(block); + if (FFlag::DebugLuauCFG) + { + typestate->finalizeDomains(); + for (auto& cv : typestate->flushConstraintsRequiringFinalization()) + addConstraint(scopes.front().second, block->location, std::move(cv)); + } + if (FFlag::LuauCyclicRequireTypeInference) { std::vector deferred; @@ -431,22 +438,24 @@ void ConstraintGenerator::visitModuleRoot(AstStatBlock* block) if (logger) logger->captureGenerationModule(module); - for (const auto& [ty, domain] : localTypes) + if (!FFlag::DebugLuauCFG) { - // FIXME: This isn't the most efficient thing. - TypeId domainTy = builtinTypes->neverType; - for (TypeId d : domain) + for (const auto& [ty, domain] : localTypes) { - d = follow(d); - if (d == ty) - continue; - domainTy = simplifyUnion(scope, Location{}, domainTy, d); - } + // FIXME: This isn't the most efficient thing. + TypeId domainTy = builtinTypes->neverType; + for (TypeId d : domain) + { + d = follow(d); + if (d == ty) + continue; + domainTy = simplifyUnion(scope, Location{}, domainTy, d); + } - LUAU_ASSERT(get(ty)); - asMutable(ty)->ty.emplace(domainTy); + LUAU_ASSERT(get(ty)); + asMutable(ty)->ty.emplace(domainTy); + } } - for (TypeId ty : unionsToSimplify) addConstraint(scope, block->location, SimplifyConstraint{ty}); } @@ -467,20 +476,23 @@ void ConstraintGenerator::visitFragmentRoot(const ScopePtr& resumeScope, AstStat if (logger) logger->captureGenerationModule(module); - for (const auto& [ty, domain] : localTypes) + if (!FFlag::DebugLuauCFG) { - // FIXME: This isn't the most efficient thing. - TypeId domainTy = builtinTypes->neverType; - for (TypeId d : domain) + for (const auto& [ty, domain] : localTypes) { - d = follow(d); - if (d == ty) - continue; - domainTy = simplifyUnion(resumeScope, resumeScope->location, domainTy, d); - } + // FIXME: This isn't the most efficient thing. + TypeId domainTy = builtinTypes->neverType; + for (TypeId d : domain) + { + d = follow(d); + if (d == ty) + continue; + domainTy = simplifyUnion(resumeScope, resumeScope->location, domainTy, d); + } - LUAU_ASSERT(get(ty)); - asMutable(ty)->ty.emplace(domainTy); + LUAU_ASSERT(get(ty)); + asMutable(ty)->ty.emplace(domainTy); + } } } @@ -570,36 +582,39 @@ std::optional ConstraintGenerator::lookup(const ScopePtr& scope, Locatio ice->ice("ConstraintGenerator::lookup is inexhaustive?"); } -TypeId ConstraintGenerator::resolveRHSType(const ScopePtr& scope, Location location, AstExpr* expr) +TypeId ConstraintGenerator::getRHSType(AstExpr* expr) const { LUAU_ASSERT(FFlag::DebugLuauCFG); TypeId ty = typestate->getRHSType(expr); LUAU_ASSERT(ty); - ty = follow(ty); - if (auto c = typestate->getOptionalConstraint(ty)) - { - auto oc = addConstraint(scope, location, std::move(*c)); - if (auto bt = getMutable(ty)) - bt->setOwner(oc.get()); - } - - return ty; + return follow(ty); } -TypeId ConstraintGenerator::resolveLHSType(const ScopePtr& scope, Location location, const CFG::LValue& lv) +// Takes a symbol and returns the type representing the total domain of that local variable +TypeId ConstraintGenerator::getLocalDomain(Symbol sym) const { LUAU_ASSERT(FFlag::DebugLuauCFG); - TypeId ty = typestate->getLHSType(lv); + TypeId ty = typestate->getDomain(sym); LUAU_ASSERT(ty); - ty = follow(ty); - if (auto c = typestate->getOptionalConstraint(ty)) - { - auto oc = addConstraint(scope, location, std::move(*c)); - if (auto bt = getMutable(ty)) - bt->setOwner(oc.get()); - } + return follow(ty); +} - return ty; +void ConstraintGenerator::expandDomain(AstExpr* l, TypeId rhs) const +{ + LUAU_ASSERT(FFlag::DebugLuauCFG); + typestate->expandDomain(LHS{l}, rhs); +} + +void ConstraintGenerator::expandDomain(AstLocal* l, TypeId rhs) const +{ + LUAU_ASSERT(FFlag::DebugLuauCFG); + typestate->expandDomain(LHS{Symbol{l}}, rhs); +} + +void ConstraintGenerator::expandDomain(AstExprGlobal* global, TypeId rhs) const +{ + LUAU_ASSERT(FFlag::DebugLuauCFG); + typestate->expandDomain(LHS{Symbol{global->name}}, rhs); } NotNull ConstraintGenerator::addConstraint(const ScopePtr& scope, const Location& location, ConstraintV cv) @@ -1439,63 +1454,74 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatLocal* stat // for the purpose of synthetic name attribution. std::optional firstValueType; - for (AstLocal* local : statLocal->vars) + if (FFlag::DebugLuauCFG) { - const Location location = local->location; - - TypeId assignee; - if (FFlag::DebugLuauCFG) + for (AstLocal* local : statLocal->vars) { - assignee = resolveLHSType(scope, location, CFG::LValue{Symbol{local}}); - } - else - { - assignee = arena->addType(BlockedType{}); - } - - localTypes.try_insert(assignee, {}); - assignees.push_back(assignee); + const Location location = local->location; + TypeId assignee = getLocalDomain(local); + assignees.emplace_back(assignee); - if (!firstValueType) - firstValueType = assignee; + if (!firstValueType) + firstValueType = assignee; - if (local->annotation) - { - hasAnnotation = true; - TypeId annotationTy = resolveType(scope, local->annotation, /* inTypeArguments */ false); - annotatedTypes.push_back(annotationTy); - expectedTypes.emplace_back(annotationTy); - scope->bindings[local] = Binding{annotationTy, location}; + if (local->annotation) + { + hasAnnotation = true; + TypeId annotationTy = resolveType(scope, local->annotation, /* inTypeArguments */ false); + annotatedTypes.push_back(annotationTy); + expectedTypes.emplace_back(annotationTy); + scope->bindings[local] = Binding{annotationTy, location}; + } + else + { + // annotatedTypes must contain one type per local. If a particular + // local has no annotation at, assume the most conservative thing. + annotatedTypes.push_back(builtinTypes->unknownType); + expectedTypes.emplace_back(std::nullopt); + // The TypeState map tracks the domain of locals for us, so we can just emplace the assignee here. + scope->bindings[local] = Binding{assignee, location}; + } } - else + } + else + { + for (AstLocal* local : statLocal->vars) { - // annotatedTypes must contain one type per local. If a particular - // local has no annotation at, assume the most conservative thing. - annotatedTypes.push_back(builtinTypes->unknownType); + const Location location = local->location; + TypeId assignee = arena->addType(BlockedType{}); - expectedTypes.emplace_back(std::nullopt); - scope->bindings[local] = Binding{builtinTypes->unknownType, location}; + localTypes.try_insert(assignee, {}); + assignees.push_back(assignee); - inferredBindings[local] = {scope.get(), location, {assignee}}; - } + if (!firstValueType) + firstValueType = assignee; + + if (local->annotation) + { + hasAnnotation = true; + TypeId annotationTy = resolveType(scope, local->annotation, /* inTypeArguments */ false); + annotatedTypes.push_back(annotationTy); + expectedTypes.emplace_back(annotationTy); + scope->bindings[local] = Binding{annotationTy, location}; + } + else + { + // annotatedTypes must contain one type per local. If a particular + // local has no annotation at, assume the most conservative thing. + annotatedTypes.push_back(builtinTypes->unknownType); + expectedTypes.emplace_back(std::nullopt); + scope->bindings[local] = Binding{builtinTypes->unknownType, location}; + inferredBindings[local] = {scope.get(), location, {assignee}}; + } - if (!FFlag::DebugLuauCFG) - { DefId def = dfg->getDef(local); scope->lvalueTypes[def] = assignee; } } Checkpoint start = checkpoint(this); - TypePackId rvaluePack = nullptr; - if (FFlag::LuauThreadGeneralizeThroughConstraintGeneration) - { - rvaluePack = checkPack(scope, statLocal->values, expectedTypes, /* generalize */ true).tp; - } - else - { - rvaluePack = checkPack_DEPRECATED(scope, statLocal->values, expectedTypes).tp; - } + TypePackId rvaluePack = checkPack(scope, statLocal->values, expectedTypes, /* generalize */ true).tp; Checkpoint end = checkpoint(this); std::vector deferredTypes; @@ -1505,34 +1531,69 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatLocal* stat for (size_t i = 0; i < statLocal->vars.size; ++i) { - LUAU_ASSERT(get(assignees[i])); - TypeIds* localDomain = localTypes.find(assignees[i]); - LUAU_ASSERT(localDomain); - - if (statLocal->vars.data[i]->annotation) + if (FFlag::DebugLuauCFG) { - localDomain->insert(annotatedTypes[i]); - if (i >= head.size() && tail) + AstLocal* local = statLocal->vars.data[i]; + + if (local->annotation) { - deferredTypes.push_back(arena->addType(BlockedType{})); - freshBlockedTypes.insert(getMutable(deferredTypes.back())); + expandDomain(local, annotatedTypes[i]); + if (i >= head.size() && tail) + { + deferredTypes.push_back(arena->addType(BlockedType{})); + freshBlockedTypes.insert(getMutable(deferredTypes.back())); + } + } + else + { + if (i < head.size()) + { + expandDomain(local, head[i]); + } + else if (tail) + { + deferredTypes.push_back(arena->addType(BlockedType{})); + expandDomain(local, deferredTypes.back()); + freshBlockedTypes.insert(getMutable(deferredTypes.back())); + } + else + { + expandDomain(local, builtinTypes->nilType); + } } } else { - if (i < head.size()) - { - localDomain->insert(head[i]); - } - else if (tail) + // Decide how to extend the domains. + LUAU_ASSERT(get(assignees[i])); + TypeIds* localDomain = localTypes.find(assignees[i]); + LUAU_ASSERT(localDomain); + + if (statLocal->vars.data[i]->annotation) { - deferredTypes.push_back(arena->addType(BlockedType{})); - localDomain->insert(deferredTypes.back()); - freshBlockedTypes.insert(getMutable(deferredTypes.back())); + localDomain->insert(annotatedTypes[i]); + if (i >= head.size() && tail) + { + deferredTypes.push_back(arena->addType(BlockedType{})); + freshBlockedTypes.insert(getMutable(deferredTypes.back())); + } } else { - localDomain->insert(builtinTypes->nilType); + if (i < head.size()) + { + localDomain->insert(head[i]); + } + else if (tail) + { + deferredTypes.push_back(arena->addType(BlockedType{})); + localDomain->insert(deferredTypes.back()); + freshBlockedTypes.insert(getMutable(deferredTypes.back())); + } + else + { + localDomain->insert(builtinTypes->nilType); + } } } } @@ -1648,15 +1709,7 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatFor* for_) ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatForIn* forIn) { ScopePtr loopScope = childScope(forIn, scope); - TypePackId iterator = nullptr; - if (FFlag::LuauThreadGeneralizeThroughConstraintGeneration) - { - iterator = checkPack(scope, forIn->values, {}, true).tp; - } - else - { - iterator = checkPack_DEPRECATED(scope, forIn->values).tp; - } + TypePackId iterator = checkPack(scope, forIn->values, {}, true).tp; std::vector variableTypes; variableTypes.reserve(forIn->vars.size); @@ -1727,10 +1780,36 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatWhile* whil return ControlFlow::None; } - RefinementId refinement = check(scope, while_->condition).refinement; + const bool isWhileLocal = FFlag::DebugLuauWhileLocalAnalysis && (while_->conditionLocal != nullptr); + ScopePtr whileScope = isWhileLocal ? childScope(while_->body, scope) : childScope(while_, scope); + + if (isWhileLocal) + { + std::optional annotatedType; + if (while_->conditionLocal->annotation) + annotatedType = resolveType(scope, while_->conditionLocal->annotation, /* inTypeArguments */ false); + + TypeId initType = [&]() + { + InConditionalContext flipper{&typeContext}; + return check(scope, while_->condition, annotatedType).ty; + }(); + + TypeId baseType = annotatedType ? *annotatedType : initType; + TypeId boundType = createTypeFunctionInstance( + builtinTypes->typeFunctions->refineFunc, {baseType, builtinTypes->truthyType}, {}, whileScope, while_->conditionLocal->location + ); - ScopePtr whileScope = childScope(while_, scope); - applyRefinements(whileScope, while_->condition->location, refinement); + whileScope->bindings[while_->conditionLocal] = Binding{boundType, while_->conditionLocal->location}; + + DefId def = dfg->getDef(while_->conditionLocal); + whileScope->lvalueTypes[def] = boundType; + } + else + { + RefinementId refinement = check(scope, while_->condition).refinement; + applyRefinements(whileScope, while_->condition->location, refinement); + } visit(whileScope, while_->body); @@ -1771,20 +1850,34 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatLocalFuncti // Self? TypeId functionType = nullptr; + auto ty = scope->lookup(function->name); LUAU_ASSERT(!ty.has_value()); // The parser ensures that every local function has a distinct Symbol for its name. - functionType = arena->addType(BlockedType{}); + if (FFlag::DebugLuauCFG) + { + // TODO: does this need to be its own CFG Node? + functionType = getLocalDomain(function->name); + } + else + { + functionType = arena->addType(BlockedType{}); + } + + scope->bindings[function->name] = Binding{functionType, function->name->location}; FunctionSignature sig = checkFunctionSignature(scope, nullptr, function->func, /* expectedType */ std::nullopt, function->name->location); sig.bodyScope->bindings[function->name] = Binding{sig.signature, function->name->location}; - DefId def = dfg->getDef(function->name); - scope->lvalueTypes[def] = functionType; - updateRValueRefinements(scope, def, functionType); - sig.bodyScope->lvalueTypes[def] = sig.signature; - updateRValueRefinements(sig.bodyScope, def, sig.signature); + if (!FFlag::DebugLuauCFG) + { + DefId def = dfg->getDef(function->name); + scope->lvalueTypes[def] = functionType; + updateRValueRefinements(scope, def, functionType); + sig.bodyScope->lvalueTypes[def] = sig.signature; + updateRValueRefinements(sig.bodyScope, def, sig.signature); + } Checkpoint start = checkpoint(this); checkFunctionBody(sig.bodyScope, function->func); @@ -1925,15 +2018,7 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatReturn* ret std::vector> expectedTypes; for (TypeId ty : scope->returnType) expectedTypes.emplace_back(ty); - TypePackId exprTypes = nullptr; - if (FFlag::LuauThreadGeneralizeThroughConstraintGeneration) - { - exprTypes = checkPack(scope, ret->list, expectedTypes, false).tp; - } - else - { - exprTypes = checkPack_DEPRECATED(scope, ret->list, expectedTypes).tp; - } + TypePackId exprTypes = checkPack(scope, ret->list, expectedTypes, false).tp; addConstraint(scope, ret->location, PackSubtypeConstraint{exprTypes, scope->returnType, /*returns*/ true}); return ControlFlow::Returns; @@ -1977,15 +2062,7 @@ static void bindFreeType(TypeId a, TypeId b) ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatAssign* assign) { - TypePackId resultPack; - if (FFlag::LuauThreadGeneralizeThroughConstraintGeneration) - { - resultPack = checkPack(scope, assign->values, {}, true).tp; - } - else - { - resultPack = checkPack_DEPRECATED(scope, assign->values).tp; - } + TypePackId resultPack = checkPack(scope, assign->values, {}, true).tp; std::vector valueTypes; valueTypes.reserve(assign->vars.size); @@ -2034,8 +2111,14 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatIf* ifState { if (FFlag::DebugLuauCFG) { - // TODO CLI-222927: `if local`/`if const` support in CFG branch left for later as its design isn't fully complete - check(scope, ifStatement->condition, std::nullopt); + std::optional annotatedType; + if (ifStatement->conditionLocal && ifStatement->conditionLocal->annotation) + annotatedType = resolveType(scope, ifStatement->conditionLocal->annotation, /* inTypeArguments */ false); + [&]() + { + InConditionalContext flipper{&typeContext}; + check(scope, ifStatement->condition, std::nullopt); + }(); ScopePtr thenScope = childScope(ifStatement->thenbody, scope); visit(thenScope, ifStatement->thenbody); @@ -2606,7 +2689,6 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatClass* stat Checkpoint end = checkpoint(this); NotNull constraintScope{sig.signatureScope ? sig.signatureScope.get() : sig.bodyScope.get()}; - NotNull genConstraint = addConstraint( scope, FFlag::LuauCyclicRequireTypeInference @@ -2810,7 +2892,6 @@ InferencePack ConstraintGenerator::checkPack( bool generalize ) { - LUAU_ASSERT(FFlag::LuauThreadGeneralizeThroughConstraintGeneration); std::vector head; std::optional tail; @@ -2836,38 +2917,6 @@ InferencePack ConstraintGenerator::checkPack( return InferencePack{addTypePack(std::move(head), tail)}; } -InferencePack ConstraintGenerator::checkPack_DEPRECATED( - const ScopePtr& scope, - AstArray exprs, - const std::vector>& expectedTypes -) -{ - LUAU_ASSERT(!FFlag::LuauThreadGeneralizeThroughConstraintGeneration); - std::vector head; - std::optional tail; - - for (size_t i = 0; i < exprs.size; ++i) - { - AstExpr* expr = exprs.data[i]; - if (i < exprs.size - 1) - { - std::optional expectedType; - if (i < expectedTypes.size()) - expectedType = expectedTypes[i]; - head.push_back(check(scope, expr, expectedType).ty); - } - else - { - std::vector> expectedTailTypes; - if (i < expectedTypes.size()) - expectedTailTypes.assign(begin(expectedTypes) + i, end(expectedTypes)); - tail = checkPack(scope, expr, expectedTailTypes).tp; - } - } - - return InferencePack{addTypePack(std::move(head), tail)}; -} - InferencePack ConstraintGenerator::checkPack( const ScopePtr& scope, AstExpr* expr, @@ -2904,19 +2953,10 @@ InferencePack ConstraintGenerator::checkPack( std::optional expectedType; if (!expectedTypes.empty()) expectedType = expectedTypes[0]; - TypeId t = nullptr; - if (FFlag::LuauThreadGeneralizeThroughConstraintGeneration) - { - // If we are given an expected type, then we will use the ungeneralized type of - // any lambdas that are children of this expression. If we are not given an - // expected type, then we check what value of generalize was passed in. - t = check(scope, expr, expectedType, /* forceSingleton */ false, !expectedType.has_value() && generalize).ty; - } - else - { - t = check(scope, expr, expectedType, /*forceSingletons*/ false, generalize).ty; - } - + // If we are given an expected type, then we will use the ungeneralized type of + // any lambdas that are children of this expression. If we are not given an + // expected type, then we check what value of generalize was passed in. + TypeId t = check(scope, expr, expectedType, /* forceSingleton */ false, !expectedType.has_value() && generalize).ty; result = InferencePack{arena->addTypePack({t})}; } @@ -3330,12 +3370,7 @@ Inference ConstraintGenerator::check(const ScopePtr& scope, AstExpr* expr, std:: else if (auto indexExpr = expr->as()) result = check(scope, indexExpr); else if (auto table = expr->as()) - { - if (FFlag::LuauThreadGeneralizeThroughConstraintGeneration) - result = check(scope, table, expectedType, generalize); - else - result = check_DEPRECATED(scope, table, expectedType); - } + result = check(scope, table, expectedType, generalize); else if (auto unary = expr->as()) result = check(scope, unary); else if (auto binary = expr->as()) @@ -3431,7 +3466,16 @@ Inference ConstraintGenerator::check(const ScopePtr& scope, AstExprConstantBool* Inference ConstraintGenerator::check(const ScopePtr& scope, AstExprLocal* local) { if (FFlag::DebugLuauCFG) - return Inference{resolveRHSType(scope, local->location, local), nullptr}; + { + TypeId ty = getRHSType(local); + if (!ty) + { + LUAU_ASSERT(!"Tried to lookup a local in the CFG, but it was not found!"); + return Inference{builtinTypes->errorType, nullptr}; + } + + return Inference{ty, nullptr}; + } else { const RefinementKey* key = dfg->getRefinementKey(local); @@ -3534,6 +3578,32 @@ Inference ConstraintGenerator::checkIndexName( Inference ConstraintGenerator::check(const ScopePtr& scope, AstExprIndexName* indexName) { + if (FFlag::DebugLuauCFG) + { + AstExpr* indexee = indexName->expr; + std::string index{indexName->index.value}; + TypeId obj = check(scope, indexee).ty; + + // We optimize away the HasProp constraint in simple cases so that we can + // reason about updates to unsealed tables more accurately. + if (const TableType* tt = getTableType(obj)) + { + auto it = tt->props.find(index); + if (it != tt->props.end() && it->second.readTy.has_value()) + return Inference{*it->second.readTy}; + } + + if (auto cachedHasPropResult = propIndexPairsSeen.find({obj, index})) + return Inference{*cachedHasPropResult}; + + TypeId result = arena->addType(BlockedType{}); + auto c = addConstraint(scope, indexee->location, HasPropConstraint{result, obj, index, inConditional(typeContext)}); + getMutable(result)->setOwner(c); + propIndexPairsSeen[{obj, index}] = result; + + return Inference{result}; + } + const RefinementKey* key = dfg->getRefinementKey(indexName); return checkIndexName(scope, key, indexName->expr, indexName->index.value, indexName->indexLocation); } @@ -3870,6 +3940,13 @@ std::tuple ConstraintGenerator::checkBinary( std::optional expectedType ) { + if (FFlag::DebugLuauCFG) + { + TypeId leftType = check(scope, left, expectedType).ty; + TypeId rightType = check(scope, right, expectedType).ty; + return {leftType, rightType, nullptr}; + } + std::optional inContext; if (op != AstExprBinary::And && op != AstExprBinary::Or && op != AstExprBinary::CompareEq && op != AstExprBinary::CompareNe) inContext.emplace(&typeContext, TypeContext::Default); @@ -4017,10 +4094,8 @@ void ConstraintGenerator::visitLValue(const ScopePtr& scope, AstExprLocal* local { if (FFlag::DebugLuauCFG) { - TypeId assignTy = resolveLHSType(scope, local->location, CFG::LValue{static_cast(local)}); - localTypes.try_insert(assignTy, {}); - localTypes[assignTy].insert(rhsType); - + // visiting the lvalue here extends the domain of the local + expandDomain(local->asExpr(), rhsType); std::optional annotatedTy = scope->lookup(local->local); if (annotatedTy) addConstraint(scope, local->location, SubtypeConstraint{rhsType, *annotatedTy}); @@ -4137,7 +4212,6 @@ void ConstraintGenerator::visitLValue(const ScopePtr& scope, AstExprIndexExpr* e Inference ConstraintGenerator::check(const ScopePtr& scope, AstExprTable* expr, std::optional expectedType, bool generalize) { - LUAU_ASSERT(FFlag::LuauThreadGeneralizeThroughConstraintGeneration); InConditionalContext inContext(&typeContext, TypeContext::Default); TypeId ty = arena->addType(TableType{}); @@ -4264,135 +4338,6 @@ Inference ConstraintGenerator::check(const ScopePtr& scope, AstExprTable* expr, return Inference{ty}; } -Inference ConstraintGenerator::check_DEPRECATED(const ScopePtr& scope, AstExprTable* expr, std::optional expectedType) -{ - LUAU_ASSERT(!FFlag::LuauThreadGeneralizeThroughConstraintGeneration); - InConditionalContext inContext(&typeContext, TypeContext::Default); - - TypeId ty = arena->addType(TableType{}); - TableType* ttv = getMutable(ty); - LUAU_ASSERT(ttv); - - ttv->state = TableState::Unsealed; - ttv->definitionModuleName = module->name; - ttv->definitionLocation = expr->location; - ttv->scope = scope.get(); - - if (FInt::LuauPrimitiveInferenceInTableLimit > 0 && expr->items.size > size_t(FInt::LuauPrimitiveInferenceInTableLimit)) - largeTableDepth++; - - interiorFreeTypes.back().types.push_back(ty); - - TypeIds indexKeyLowerBound; - TypeIds indexValueLowerBound; - - auto createIndexer = [&indexKeyLowerBound, &indexValueLowerBound](const Location& location, TypeId currentIndexType, TypeId currentResultType) - { - indexKeyLowerBound.insert(follow(currentIndexType)); - indexValueLowerBound.insert(follow(currentResultType)); - }; - - TypeIds valuesLowerBound; - - Checkpoint start = checkpoint(this); - - for (const AstExprTable::Item& item : expr->items) - { - // Expected typeArguments are threaded through table literals separately via the - // function matchLiteralType. - - // generalize is false here as we want to be able to push typeArguments into lambdas in a situation like: - // - // type Callback = (string) -> () - // - // local t: { Callback } = { - // function (s) - // -- s should have type `string` here - // end - // } - TypeId itemTy = check(scope, item.value, /* expectedType */ std::nullopt, /* forceSingleton */ false, /* generalize */ false).ty; - - if (item.key) - { - // Even though we don't need to use the type of the item's key if - // it's a string constant, we still want to check it to populate - // astTypes. - TypeId keyTy = check(scope, item.key).ty; - - if (AstExprConstantString* key = item.key->as()) - { - std::string propName{key->value.data, key->value.size}; - ttv->props[propName] = {itemTy, /*deprecated*/ false, {}, key->location}; - } - else - { - createIndexer(item.key->location, keyTy, itemTy); - } - } - else - { - TypeId numberType = builtinTypes->numberType; - // FIXME? The location isn't quite right here. Not sure what is - // right. - createIndexer(item.value->location, numberType, itemTy); - } - } - - Checkpoint end = checkpoint(this); - - if (!indexKeyLowerBound.empty()) - { - LUAU_ASSERT(!indexValueLowerBound.empty()); - - TypeId indexKey = nullptr; - TypeId indexValue = nullptr; - - if (indexKeyLowerBound.size() == 1) - { - indexKey = *indexKeyLowerBound.begin(); - } - else - { - indexKey = arena->addType(UnionType{std::vector(indexKeyLowerBound.begin(), indexKeyLowerBound.end())}); - unionsToSimplify.push_back(indexKey); - } - - if (indexValueLowerBound.size() == 1) - { - indexValue = *indexValueLowerBound.begin(); - } - else - { - indexValue = arena->addType(UnionType{std::vector(indexValueLowerBound.begin(), indexValueLowerBound.end())}); - unionsToSimplify.push_back(indexValue); - } - - ttv->indexer = TableIndexer{indexKey, indexValue}; - } - - if (expectedType) - { - auto ptc = addConstraint( - scope, - expr->location, - PushTypeConstraint{ - /* expectedType */ *expectedType, - /* targetType */ ty, - /* astTypes */ NotNull{&module->astTypes}, - /* astExpectedTypes */ NotNull{&module->astExpectedTypes}, - /* expr */ NotNull{expr}, - } - ); - - addAllAsReverseDependencies(start, end, this, ptc); - } - - if (FInt::LuauPrimitiveInferenceInTableLimit > 0 && expr->items.size > size_t(FInt::LuauPrimitiveInferenceInTableLimit)) - largeTableDepth--; - - return Inference{ty}; -} - ConstraintGenerator::FunctionSignature ConstraintGenerator::checkFunctionSignature( const ScopePtr& parent, ClassDeclRecord* enclosingClass, @@ -4555,6 +4500,14 @@ ConstraintGenerator::FunctionSignature ConstraintGenerator::checkFunctionSignatu signatureScope->bindings[local] = Binding{argTy, local->location}; + if (FFlag::DebugLuauCFG) + { + // A parameter's Arg instruction introduces a blocked initial value with no + // rhs expression; bind it to the resolved signature type here where argTy is + // known. No-ops for functions whose args aren't lowered into the CFG. + expandDomain(local, argTy); + } + DefId def = dfg->getDef(local); signatureScope->lvalueTypes[def] = argTy; updateRValueRefinements(signatureScope, def, argTy); diff --git a/Analysis/src/ConstraintSolver.cpp b/Analysis/src/ConstraintSolver.cpp index b58859767..ca899ae8a 100644 --- a/Analysis/src/ConstraintSolver.cpp +++ b/Analysis/src/ConstraintSolver.cpp @@ -46,10 +46,11 @@ LUAU_FASTFLAGVARIABLE(LuauRemoveConstraintSolverEmplace) LUAU_FASTFLAGVARIABLE(LuauForceLess) LUAU_FASTFLAG(LuauCyclicRequireTypeInference) LUAU_FASTFLAG(DebugLuauExactTableTypes) -LUAU_FASTFLAGVARIABLE(LuauBlockingTypeAliasExpansion) LUAU_FASTFLAGVARIABLE(LuauTraverseScopeToFunction) LUAU_FASTFLAG(LuauReferenceCountInitializerIsIterative) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) +LUAU_FASTFLAGVARIABLE(LuauNonreentrantLookupTableProp) +LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) namespace Luau { @@ -88,6 +89,7 @@ static void dump(ConstraintSolver* cs, ToStringOptions& opts); if (auto blocked = get(ty)) { const Constraint* owner = blocked->getOwner(); + LUAU_ASSERT(owner); return owner == constraint; } @@ -1307,7 +1309,7 @@ bool ConstraintSolver::tryDispatch(const TypeAliasExpansionConstraint& c, NotNul // If the type function itself is still blocked, we have to wait for it // Not using 'isBlocked' as this constraint has special handling of pending and TypeFunctionInstanceType - if (FFlag::LuauBlockingTypeAliasExpansion && get(follow(tf->type))) + if (get(follow(tf->type))) return block(tf->type, constraint); // Adding ReduceConstraint on type function for the constraint solver @@ -1664,15 +1666,6 @@ bool ConstraintSolver::tryDispatch(const FunctionCallConstraint& c, NotNulllocation }; - DenseHashSet uniqueTypes; - if (c.callSite) - { - if (FFlag::LuauCyclicRequireTypeInference) - findUniqueTypes(NotNull{&uniqueTypes}, c.callSite->args, NotNull{c.astTypes}); - else - findUniqueTypes(NotNull{&uniqueTypes}, c.callSite->args, NotNull{&module->astTypes}); - } - TypeId overloadToUse = fn; // If the function we have is already a function type, then there's no @@ -1683,12 +1676,13 @@ bool ConstraintSolver::tryDispatch(const FunctionCallConstraint& c, NotNullfunc->location : Location{}, - NotNull{&uniqueTypes}, /* useFreeTypeBounds */ true ); // For now we never retry as it's prohibitively expensive. - auto [overload, _constraints, _shouldRetry] = res.getUnambiguousOverload(); + auto [overload, constraints, _shouldRetry] = res.getUnambiguousOverload(); + + LUAU_ASSERT(!FFlag::LuauOneBitAssumedConstraintTracking || constraints.empty()); if (overload) { @@ -1988,9 +1982,13 @@ bool ConstraintSolver::tryDispatch(const HasPropConstraint& c, NotNullanyType)); + return true; } @@ -2357,11 +2356,16 @@ bool ConstraintSolver::tryDispatch(const AssignPropConstraint& c, NotNull(lhsType)) { auto lhsFreeUpperBound = follow(lhsFree->upperBound); - const auto [blocked, maybeTy, isIndex] = lookupTableProp(constraint, lhsType, propName, ValueContext::LValue); + const auto [blocked, maybeTy, isIndex] = + FFlag::LuauNonreentrantLookupTableProp + ? lookupTableProp(constraint, lhsType, propName, ValueContext::LValue, /* inConditional */ false, /* suppressSimplification */ false) + : lookupTableProp_DEPRECATED(constraint, lhsType, propName, ValueContext::LValue); + if (!blocked.empty()) { for (TypeId t : blocked) @@ -2395,7 +2399,11 @@ bool ConstraintSolver::tryDispatch(const AssignPropConstraint& c, NotNull constraint, bool force) { TypeId ty = follow(c.ty); - TypeFunctionContext context{NotNull{this}, constraint->scope, constraint, subtyping}; FunctionGraphReductionResult result = reduceTypeFunctions(ty, constraint->location, NotNull{&context}, force); @@ -3343,7 +3350,7 @@ NotNull ConstraintSolver::unpackAndAssign( return c; } -TablePropLookupResult ConstraintSolver::lookupTableProp( +TablePropLookupResult ConstraintSolver::lookupTableProp_DEPRECATED( NotNull constraint, TypeId subjectType, const std::string& propName, @@ -3352,11 +3359,12 @@ TablePropLookupResult ConstraintSolver::lookupTableProp( bool suppressSimplification ) { + LUAU_ASSERT(!FFlag::LuauNonreentrantLookupTableProp); DenseHashSet seen; - return lookupTableProp(constraint, subjectType, propName, context, inConditional, suppressSimplification, seen); + return lookupTableProp_DEPRECATED(constraint, subjectType, propName, context, inConditional, suppressSimplification, seen); } -TablePropLookupResult ConstraintSolver::lookupTableProp( +TablePropLookupResult ConstraintSolver::lookupTableProp_DEPRECATED( NotNull constraint, TypeId subjectType, const std::string& propName, @@ -3366,6 +3374,7 @@ TablePropLookupResult ConstraintSolver::lookupTableProp( DenseHashSet& seen ) { + LUAU_ASSERT(!FFlag::LuauNonreentrantLookupTableProp); if (seen.contains(subjectType)) return {}; @@ -3458,11 +3467,11 @@ TablePropLookupResult ConstraintSolver::lookupTableProp( else if (auto mt = get(subjectType); mt && context == ValueContext::LValue) { // TODO __newindex: CLI-199848 - return lookupTableProp(constraint, mt->table, propName, context, inConditional, suppressSimplification, seen); + return lookupTableProp_DEPRECATED(constraint, mt->table, propName, context, inConditional, suppressSimplification, seen); } else if (auto mt = get(subjectType); mt && context == ValueContext::RValue) { - auto result = lookupTableProp(constraint, mt->table, propName, context, inConditional, suppressSimplification, seen); + auto result = lookupTableProp_DEPRECATED(constraint, mt->table, propName, context, inConditional, suppressSimplification, seen); if (!result.blockedTypes.empty() || result.propType) return result; @@ -3497,10 +3506,10 @@ TablePropLookupResult ConstraintSolver::lookupTableProp( } } else - return lookupTableProp(constraint, indexType, propName, context, inConditional, suppressSimplification, seen); + return lookupTableProp_DEPRECATED(constraint, indexType, propName, context, inConditional, suppressSimplification, seen); } else if (get(mtt)) - return lookupTableProp(constraint, mtt, propName, context, inConditional, suppressSimplification, seen); + return lookupTableProp_DEPRECATED(constraint, mtt, propName, context, inConditional, suppressSimplification, seen); } else if (auto ct = get(subjectType)) { @@ -3539,7 +3548,7 @@ TablePropLookupResult ConstraintSolver::lookupTableProp( if (indexProp->second.isWriteOnly()) return {{}, builtinTypes->errorType}; - return lookupTableProp(constraint, *indexProp->second.readTy, propName, context, inConditional, suppressSimplification, seen); + return lookupTableProp_DEPRECATED(constraint, *indexProp->second.readTy, propName, context, inConditional, suppressSimplification, seen); } else if (auto ft = get(subjectType)) { @@ -3547,7 +3556,8 @@ TablePropLookupResult ConstraintSolver::lookupTableProp( if (get(upperBound) || get(upperBound)) { - TablePropLookupResult res = lookupTableProp(constraint, upperBound, propName, context, inConditional, suppressSimplification, seen); + TablePropLookupResult res = + lookupTableProp_DEPRECATED(constraint, upperBound, propName, context, inConditional, suppressSimplification, seen); // Here, res.propType is empty if res is a sealed table or a primitive that lacks the property. // When this happens, we still want to add to the upper bound of the type. if (res.propType) @@ -3586,7 +3596,7 @@ TablePropLookupResult ConstraintSolver::lookupTableProp( for (TypeId ty : utv) { - auto result = lookupTableProp(constraint, ty, propName, context, inConditional, suppressSimplification, seen); + auto result = lookupTableProp_DEPRECATED(constraint, ty, propName, context, inConditional, suppressSimplification, seen); blocked.insert(blocked.end(), result.blockedTypes.begin(), result.blockedTypes.end()); if (result.propType) options.insert(*result.propType); @@ -3623,7 +3633,7 @@ TablePropLookupResult ConstraintSolver::lookupTableProp( for (TypeId ty : itv) { - auto result = lookupTableProp(constraint, ty, propName, context, inConditional, suppressSimplification, seen); + auto result = lookupTableProp_DEPRECATED(constraint, ty, propName, context, inConditional, suppressSimplification, seen); blocked.insert(blocked.end(), result.blockedTypes.begin(), result.blockedTypes.end()); if (result.propType) options.insert(*result.propType); @@ -3657,6 +3667,409 @@ TablePropLookupResult ConstraintSolver::lookupTableProp( return {{}, std::nullopt}; } +TablePropLookupResult ConstraintSolver::lookupTableProp( + NotNull constraint, + TypeId subjectType, + const std::string& propName, + ValueContext context, + bool inConditional, + bool suppressSimplification +) +{ + LUAU_ASSERT(FFlag::LuauNonreentrantLookupTableProp); + DenseHashMap>> cache; + TypeIds blockedTypes; + + if (auto result = lookupTablePropHelper(constraint, subjectType, propName, context, blockedTypes, cache, inConditional, suppressSimplification)) + { + return {blockedTypes.take(), result->first, result->second}; + } + + return {blockedTypes.take(), std::nullopt, false}; +} + + +std::optional> ConstraintSolver::lookupTablePropHelper( + NotNull constraint, + TypeId subjectType, + const std::string& propName, + ValueContext context, + TypeIds& blockedTypes, + DenseHashMap>>& cache, + bool inConditional, + bool suppressSimplification +) +{ + LUAU_ASSERT(FFlag::LuauNonreentrantLookupTableProp); + + subjectType = follow(subjectType); + + if (auto entry = cache.find(subjectType)) + return *entry; + + cache[subjectType] = std::nullopt; + + auto aux = [&]() -> std::optional> + { + if (isBlocked(subjectType)) + { + blockedTypes.insert(subjectType); + return std::nullopt; + } + else if (get(subjectType) || get(subjectType) || get(subjectType)) + { + return {{subjectType, false}}; + } + else if (auto ttv = getMutable(subjectType)) + { + if (auto prop = ttv->props.find(propName); prop != ttv->props.end()) + { + switch (context) + { + case ValueContext::RValue: + if (auto rt = prop->second.readTy) + return {{*rt, false}}; + break; + case ValueContext::LValue: + if (auto wt = prop->second.writeTy) + return {{*wt, false}}; + break; + } + } + + if (ttv->indexer) + { + if (isBlocked(ttv->indexer->indexType)) + { + blockedTypes.insert(ttv->indexer->indexType); + return std::nullopt; + } + + // CLI-169235: This is silly but this needs to use the same + // logic as `index<_, _>` + TypeId fauxLiteral = arena->addType(SingletonType{StringSingleton{propName}}); + if (fastIsSubtype(fauxLiteral, ttv->indexer->indexType)) + return {{ttv->indexer->indexResultType, true}}; + } + + if (ttv->state == TableState::Free) + { + TypeId result = freshType(arena, builtinTypes, ttv->scope, Polarity::Mixed); + trackInteriorFreeType(ttv->scope, result); + switch (context) + { + case ValueContext::RValue: + ttv->props[propName].readTy = result; + break; + case ValueContext::LValue: + if (auto it = ttv->props.find(propName); it != ttv->props.end() && it->second.isReadOnly()) + { + // We do infer read-only properties, but we do not infer + // separate read and write types. + // + // If we encounter a case where a free table has a read-only + // property that we subsequently sense a write to, we make + // the judgement that the property is read-write and that + // both the read and write types are the same. + + Property& prop = it->second; + + prop.writeTy = prop.readTy; + return {{*prop.readTy, false}}; + } + else + ttv->props[propName] = Property::rw(result); + + break; + } + return {{result, false}}; + } + + // If we are in a conditional context, we treat the property as present + // and `unknown` because we may be _refining_ a table to include that + // property. + if (FFlag::DebugLuauExactTableTypes) + { + if (inConditional && ttv->state != TableState::Exact) + return {{builtinTypes->unknownType, false}}; + } + else + { + if (inConditional) + return {{builtinTypes->unknownType, false}}; + } + } + else if (auto mt = get(subjectType); mt && context == ValueContext::LValue) + { + // TODO __newindex: CLI-199848 + return lookupTablePropHelper(constraint, mt->table, propName, context, blockedTypes, cache, inConditional, suppressSimplification); + } + else if (auto mt = get(subjectType); mt && context == ValueContext::RValue) + { + auto result = lookupTablePropHelper(constraint, mt->table, propName, context, blockedTypes, cache, inConditional, suppressSimplification); + if (result || !blockedTypes.empty()) + return result; + + TypeId mtt = follow(mt->metatable); + + if (get(mtt)) + { + blockedTypes.insert(mtt); + return {}; + } + else if (auto metatable = get(mtt)) + { + auto indexProp = metatable->props.find("__index"); + if (indexProp == metatable->props.end()) + return result; + + // TODO: __index can be an overloaded function. + + // if the property is write-only, then surely we cannot read from it. + if (indexProp->second.isWriteOnly()) + return {{builtinTypes->errorType, false}}; + + TypeId indexType = follow(*indexProp->second.readTy); + + if (auto ft = get(indexType)) + { + TypePack rets = extendTypePack(*arena, builtinTypes, ft->retTypes, 1); + if (1 == rets.head.size()) + return {{rets.head[0], false}}; + else + { + // This should probably be an error: We need the first result of the MT.__index method, + // but it returns 0 values. See CLI-68672 + return {{builtinTypes->nilType, false}}; + } + } + else + return lookupTablePropHelper( + constraint, indexType, propName, context, blockedTypes, cache, inConditional, suppressSimplification + ); + } + else if (get(mtt)) + return lookupTablePropHelper(constraint, mtt, propName, context, blockedTypes, cache, inConditional, suppressSimplification); + } + else if (auto ct = get(subjectType)) + { + if (auto p = lookupExternTypeProp(ct, propName)) + { + switch (context) + { + case ValueContext::RValue: + if (p->readTy) + return {{*p->readTy, false}}; + break; + case ValueContext::LValue: + if (p->writeTy) + return {{*p->writeTy, false}}; + break; + default: + LUAU_UNREACHABLE(); + } + return std::nullopt; + } + + if (FFlag::DebugLuauUserDefinedClasses) + { + if (ct->metatable) + { + if (const TableType* tt = get(*ct->metatable)) + { + // For user-defined classes, the instance metatable holds metamethods (e.g. __add) + // directly in its props rather than under an __index table. + if (auto prop = tt->props.find(propName); prop != tt->props.end()) + { + switch (context) + { + case ValueContext::RValue: + if (prop->second.readTy) + return {{*prop->second.readTy, false}}; + break; + case ValueContext::LValue: + if (prop->second.writeTy) + return {{*prop->second.writeTy, false}}; + break; + default: + LUAU_UNREACHABLE(); + } + return std::nullopt; + } + } + } + } + + if (ct->indexer) + return {{ct->indexer->indexResultType, true}}; + } + else if (auto pt = get(subjectType); pt && pt->metatable) + { + const TableType* metatable = get(follow(*pt->metatable)); + LUAU_ASSERT(metatable); + + auto indexProp = metatable->props.find("__index"); + if (indexProp == metatable->props.end()) + return std::nullopt; + + // if the property is write-only, then surely we cannot read from it. + if (indexProp->second.isWriteOnly()) + return {{builtinTypes->errorType, false}}; + + return lookupTablePropHelper( + constraint, *indexProp->second.readTy, propName, context, blockedTypes, cache, inConditional, suppressSimplification + ); + } + else if (auto ft = get(subjectType)) + { + const TypeId upperBound = follow(ft->upperBound); + + if (get(upperBound) || get(upperBound)) + { + // Here, res is empty if res is a sealed table or a primitive that lacks the property. + // When this happens, we still want to add to the upper bound of the type. + if (auto res = + lookupTablePropHelper(constraint, upperBound, propName, context, blockedTypes, cache, inConditional, suppressSimplification)) + return res; + } + + NotNull scope{ft->scope}; + + const TypeId newUpperBound = arena->addType(TableType{TableState::Free, TypeLevel{}, scope}); + + trackInteriorFreeType(constraint->scope, newUpperBound); + + TableType* tt = getMutable(newUpperBound); + LUAU_ASSERT(tt); + TypeId propType = freshType(arena, builtinTypes, scope, Polarity::Mixed); + trackInteriorFreeType(scope, propType); + + switch (context) + { + case ValueContext::RValue: + tt->props[propName] = Property::readonly(propType); + break; + case ValueContext::LValue: + tt->props[propName] = Property::rw(propType); + break; + } + + unify(constraint, subjectType, newUpperBound); + + return {{propType, false}}; + } + else if (auto utv = get(subjectType)) + { + std::set options; + + if (context == ValueContext::LValue) + { + bool isIndex = true; + + for (TypeId ty : utv) + { + if (auto res = + lookupTablePropHelper(constraint, ty, propName, context, blockedTypes, cache, inConditional, suppressSimplification)) + { + options.insert(res->first); + isIndex &= res->second; + } + } + + + // If we're in an lvalue context, we need the common type here, + // so if there are more than one result types then we mint an + // intersection. + + if (options.empty()) + return std::nullopt; + else if (options.size() == 1) + return {{*begin(options), isIndex}}; + else if (options.size() == 2 && !suppressSimplification) + { + TypeId one = *begin(options); + TypeId two = *(++begin(options)); + + return {{simplifyIntersection(constraint->scope, constraint->location, one, two), isIndex}}; + } + else + return {{arena->addType(IntersectionType{std::vector(begin(options), end(options))}), isIndex}}; + } + else + { + LUAU_ASSERT(context == ValueContext::RValue); + bool isIndex = false; + + for (TypeId ty : utv) + { + if (auto res = + lookupTablePropHelper(constraint, ty, propName, context, blockedTypes, cache, inConditional, suppressSimplification)) + { + options.insert(res->first); + isIndex |= res->second; + } + } + + if (options.empty()) + return std::nullopt; + else if (options.size() == 1) + return {{*begin(options), isIndex}}; + else if (options.size() == 2 && !suppressSimplification) + { + TypeId one = *begin(options); + TypeId two = *(++begin(options)); + + return {{simplifyUnion(constraint->scope, constraint->location, one, two), isIndex}}; + } + else + return {{arena->addType(UnionType{std::vector(begin(options), end(options))}), isIndex}}; + } + } + else if (auto itv = get(subjectType)) + { + std::set options; + bool isIndex = true; + + for (TypeId ty : itv) + { + if (auto res = lookupTablePropHelper(constraint, ty, propName, context, blockedTypes, cache, inConditional, suppressSimplification)) + { + + options.insert(res->first); + isIndex &= res->second; + } + } + + if (options.empty()) + return std::nullopt; + else if (options.size() == 1) + return {{*begin(options), isIndex}}; + else if (options.size() == 2 && !suppressSimplification) + { + TypeId one = *begin(options); + TypeId two = *(++begin(options)); + return {{simplifyIntersection(constraint->scope, constraint->location, one, two), isIndex}}; + } + else + return {{arena->addType(IntersectionType{std::vector(begin(options), end(options))}), isIndex}}; + } + else if (auto pt = get(subjectType)) + { + // if we are in a conditional context, we treat the property as present + // and `unknown` because we may be _refining_ a table to include that + // property. + if (inConditional && pt->type == PrimitiveType::Table) + return {{builtinTypes->unknownType, false}}; + } + + return std::nullopt; + }; + + auto result = aux(); + cache[subjectType] = result; + return result; +} + template bool ConstraintSolver::unify(NotNull constraint, TID subTy, TID superTy) { diff --git a/Analysis/src/ControlFlowGraph.cpp b/Analysis/src/ControlFlowGraph.cpp index abde1efe9..866cec903 100644 --- a/Analysis/src/ControlFlowGraph.cpp +++ b/Analysis/src/ControlFlowGraph.cpp @@ -3,6 +3,7 @@ #include "Luau/Ast.h" #include "Luau/AstUtils.h" #include "Luau/Common.h" +#include "Luau/Variant.h" #include #include @@ -10,52 +11,127 @@ LUAU_FASTFLAG(DebugLuauFreezeArena) -namespace Luau::CFG +namespace Luau { -namespace CFGRefinement +static LeafConstraint invert(const LeafConstraint& c) { - -RefinementId RefinementArena::proposition(DefId def, bool sense) -{ - return NotNull{allocator.allocate(Proposition{def, std::nullopt, /*isTypeof*/ false, sense})}; + return visit( + overloaded{ + [](const Truthy&) -> LeafConstraint + { + return Falsy{}; + }, + [](const Falsy&) -> LeafConstraint + { + return Truthy{}; + }, + [](const TypeEq& eq) -> LeafConstraint + { + return TypeNeq{eq.type, eq.isTypeOf}; + }, + [](const TypeNeq& neq) -> LeafConstraint + { + return TypeEq{neq.type, neq.isTypeOf}; + }, + [](const SingletonEq& eq) -> LeafConstraint + { + return SingletonNeq{eq.v}; + }, + [](const SingletonNeq& neq) -> LeafConstraint + { + return SingletonEq{neq.v}; + }, + }, + c + ); } -RefinementId RefinementArena::typeProposition(DefId def, std::optional type, bool isTypeof, bool sense) +static NarrowingConstraint invert(const NarrowingConstraint& c) { - return NotNull{allocator.allocate(Proposition{def, std::move(type), isTypeof, sense})}; + return visit( + overloaded{ + [](const Truthy&) -> NarrowingConstraint + { + return Falsy{}; + }, + [](const Falsy&) -> NarrowingConstraint + { + return Truthy{}; + }, + [](const TypeEq& eq) -> NarrowingConstraint + { + return TypeNeq{eq.type, eq.isTypeOf}; + }, + [](const TypeNeq& neq) -> NarrowingConstraint + { + return TypeEq{neq.type, neq.isTypeOf}; + }, + [](const SingletonEq& eq) -> NarrowingConstraint + { + return SingletonNeq{eq.v}; + }, + [](const SingletonNeq& neq) -> NarrowingConstraint + { + return SingletonEq{neq.v}; + }, + [](const HasShape& hs) -> NarrowingConstraint + { + return HasShape{hs.path, invert(hs.constraint)}; + }, + }, + c + ); } -RefinementId RefinementArena::conjunction(RefinementId lhs, RefinementId rhs) +std::optional Index::fromExpr(AstExpr* expr) { - return NotNull{allocator.allocate(Conjunction{lhs, rhs})}; -} + std::vector path; + AstExpr* curr = expr; -RefinementId RefinementArena::disjunction(RefinementId lhs, RefinementId rhs) -{ - return NotNull{allocator.allocate(Disjunction{lhs, rhs})}; -} + while (true) + { + if (auto indexName = curr->as()) + { + path.emplace_back(indexName->index.value); + curr = indexName->expr; + } + else if (auto indexExpr = curr->as()) + { + if (auto str = indexExpr->index->as()) + { + path.emplace_back(str->value.data, str->value.size); + curr = indexExpr->expr; + } + else + { + return std::nullopt; + } + } + else + { + break; + } + } -RefinementId RefinementArena::negation(RefinementId r) -{ - if (auto* conj = get(r)) - return disjunction(negation(conj->lhs), negation(conj->rhs)); - if (auto* disj = get(r)) - return conjunction(negation(disj->lhs), negation(disj->rhs)); - if (auto* neg = get(r)) - return neg->refinement; + std::optional rootSym; + if (auto local = curr->as()) + rootSym = Symbol(local->local); + else if (auto global = curr->as()) + rootSym = Symbol(global->name); - LUAU_ASSERT(get(r)); - return NotNull{allocator.allocate(Negation{r})}; + if (!rootSym) + return std::nullopt; + + std::reverse(path.begin(), path.end()); + return Index{*rootSym, curr, std::move(path)}; } -void RefinementArena::freeze() +SSAId Refine::getTarget() const { - allocator.freeze(); + return target; } -} // namespace CFGRefinement - Block::Block(BlockKind kind, std::string debugName) : kind(kind) , debugName(debugName) @@ -80,12 +156,12 @@ Definition* Block::getReachingDefinition(Symbol sym) const return nullptr; } -void Block::setReachingDefinition(Symbol sym, DefId def) +void Block::setReachingDefinition(Symbol sym, SSAId def) { reachingDefinitions[sym] = def; } -const std::vector& Block::getInstructions() const +const std::vector& Block::getInstructions() const { return instructions; } @@ -105,16 +181,15 @@ Block* CFGAllocator::newBlock(BlockKind kind, std::string debugName) return block.allocate(kind, debugName); } -DefId CFGAllocator::newDefinition(Symbol sym, size_t version) +SSAId CFGAllocator::newDefinition(Symbol sym) { - return NotNull{defs.allocate(SymDef{sym, version})}; + return NotNull{defs.allocate(SymDef{sym, nextVersionIndex(sym)})}; } void CFGAllocator::freeze() { block.freeze(); defs.freeze(); - refinementArena.freeze(); frozen = true; } @@ -124,12 +199,11 @@ BlockId ControlFlowGraph::newBlock(BlockKind kind, std::string debugName) return blocks.emplace_back(b); } -void ControlFlowGraph::computeRPO() +std::vector ControlFlowGraph::postOrderAtRoot(BlockId root, DenseHashSet& visited) { - std::vector stack; - DenseHashSet visited; + std::vector stack{root}; + std::vector ordering; - stack.push_back(blocks[0]); while (!stack.empty()) { auto& curr = stack.back(); @@ -146,32 +220,45 @@ void ControlFlowGraph::computeRPO() if (added) continue; - rpoOrder.emplace_back(curr); + ordering.emplace_back(curr); stack.pop_back(); } - std::reverse(rpoOrder.begin(), rpoOrder.end()); + return ordering; } -Definition* ControlFlowGraph::resolve(Definition* def) const +void ControlFlowGraph::computeRPO() { - // It's possible that we could do path compression here as an easy optimization. - while (auto* fwd = forwards.find(def)) - def = *fwd; - return def; + // TODO: Should this live on the CFGBuilder + std::vector roots; + + DenseHashSet visited; + roots.emplace_back(blocks[0]); + roots.insert(roots.end(), functionBlocks.begin(), functionBlocks.end()); + + // Concatenate each subgraph's postorder, then reverse once to get reverse + // postorder. RPO guarantees a block's definitions are visited before their + // uses (except across loop back-edges), which the TypeStateMap relies on. + for (auto& root : roots) + { + auto ordering = postOrderAtRoot(root, visited); + rpoOrder.insert(rpoOrder.end(), ordering.begin(), ordering.end()); + } + + std::reverse(rpoOrder.begin(), rpoOrder.end()); } Definition* ControlFlowGraph::getUseDef(AstExpr* expr) const { if (auto* def = useDefs.find(expr)) - return resolve(*def); + return *def; return nullptr; } -Definition* ControlFlowGraph::getLhsDef(const LValue& lv) const +Definition* ControlFlowGraph::getLhsDef(const LHS& lv) const { if (auto* def = lhsDefs.find(lv)) - return resolve(*def); + return *def; return nullptr; } @@ -179,23 +266,141 @@ Definition* ControlFlowGraph::getLhsDef(const LValue& lv) const CFGBuilder::CFGBuilder(NotNull allocator) : cfg(std::make_unique(allocator)) , allocator(allocator) - , currentBlock(cfg->newBlock(BlockKind::Entry, "Entry Block")) + , currentBlock(newSealedBlock(BlockKind::Entry, "Entry Block")) +{ +} + +void CFGBuilder::finalize(AstStatBlock* root) { - seal(currentBlock); + // This pass tidies up the CFG by + // a) removing dead instructions + // b) materializing each definition to allow for the CFG to be in a valid ssa state. + // The reason to do this is to guarantee that the final CFG does not have any unused instructions + // or unused definitions left behind. + + auto materializeDef = [](SSAId def) + { + return NotNull{def->materialize()}; + }; + for (auto& blk : cfg->blocks) + { + std::vector undead; + for (auto& instrId : blk->instructions) + { + if (instrId->get_if()) + continue; + + visit( + overloaded{ + [&](Dead&) {}, + [&](Declare& d) + { + d.def = materializeDef(d.def); + }, + [&](LocalFunction& fn) + { + fn.def = materializeDef(fn.def); + }, + [&](GlobalFunction& fn) + { + fn.def = materializeDef(fn.def); + }, + [&](Arg& a) + { + a.def = materializeDef(a.def); + }, + [&](Upvalue& u) + { + u.def = materializeDef(u.def); + }, + [&](Assign& d) + { + d.def = materializeDef(d.def); + }, + [&](Join& j) + { + j.definition = materializeDef(j.definition); + for (auto& op : j.operands) + op = materializeDef(op); + }, + [&](Refine& r) + { + r.definition = materializeDef(r.definition); + r.target = materializeDef(r.target); + }, + }, + *instrId + ); + + undead.emplace_back(instrId); + } + + std::swap(blk->instructions, undead); + } + + for (auto& [expr, def] : cfg->useDefs) + def = materializeDef(NotNull{def}); + for (auto& [lv, def] : cfg->lhsDefs) + def = materializeDef(NotNull{def}); + +#ifdef LUAU_ASSERTENABLED + validate(root); +#endif +} + +void CFGBuilder::validate(AstStatBlock* root) +{ + // Properties we want to assert about the CFG + // 1) No Dead Instructions + // 2) No trivial phis + // 3) Every variable reference in the AST has a definition + for (const auto& blocks : cfg->blocks) + { + for (const auto& instruction : blocks->instructions) + { + if (instruction->get_if()) + LUAU_ASSERT(!"Unfinalized CFG: No Dead instructions allowed"); + + if (const Join* join = instruction->get_if()) + { + auto joinArgs = join->operands.size(); + if (joinArgs == 0) + LUAU_ASSERT( + !"Malformed CFG: Trivial Phi Node with no arguments - this definitions should have been replaced with a Dead instruction" + ); + else if (joinArgs == 1) + LUAU_ASSERT(!"Malformed CFG: Trivial Phi Node with one argument - this definition should have been short circuited"); + DenseHashSet args; + for (const auto& ssaId : join->operands) + { + if (args.contains(ssaId)) + LUAU_ASSERT(!"Malformed CFG: Phi node with a duplicate operand - we emitted something like v-1 = Join(v-0, v-0)"); + else + args.insert(ssaId); + } + if (args.contains(join->definition)) + { + LUAU_ASSERT(!"Malformed CFG: self referential phi-node - we emitted something like v-1 := Join(v-1, v-2)"); + } + } + } + } } std::unique_ptr CFGBuilder::makeCFG(NotNull allocator, AstStatBlock* block) { CFGBuilder builder(allocator); builder.lower(block); + builder.finalize(block); auto cfg = std::move(builder.cfg); cfg->computeRPO(); + if (FFlag::DebugLuauFreezeArena) allocator->freeze(); return cfg; } -bool CFGBuilder::isSealed(Block* b) +bool CFGBuilder::isSealed(BlockId b) { return sealedBlocks.contains(b); } @@ -209,8 +414,9 @@ bool CFGBuilder::isSealed(Block* b) // E.g. When lowering a while loop, the condition block might have a back edge from the body of the while loop // You can only seal this when the body has finished lowering, since that is the last // predecessor that must be added -void CFGBuilder::seal(Block* b) +void CFGBuilder::seal(BlockId b) { + LUAU_ASSERT(!isSealed(b)); auto joinsToFill = incompleteJoins.find(b); if (joinsToFill != nullptr) { @@ -221,137 +427,448 @@ void CFGBuilder::seal(Block* b) // In this case, we should check if the incomplete instruction is still a join if (auto join = inst->get_if()) { - DefId resolved = fillJoinOperands(b, NotNull{inst}, join); - b->setReachingDefinition(resolved->sym, resolved); + fillJoinOperands(b, NotNull{inst}, join); } } - incompleteJoins[b] = DenseHashSet{}; + incompleteJoins[b] = DenseHashSet{}; } sealedBlocks.insert(b); } -void CFGBuilder::lower(AstStat* statement) +ControlFlow CFGBuilder::lower(AstStat* statement) { if (auto blk = statement->as()) - lower(blk); + return lower(blk); else if (auto local = statement->as()) - lower(local); + return lower(local); else if (auto assn = statement->as()) - lower(assn); + return lower(assn); else if (auto statIf = statement->as()) - lower(statIf); + return lower(statIf); else if (auto statWhile = statement->as()) - lower(statWhile); + return lower(statWhile); + else if (auto statRepeat = statement->as()) + return lower(statRepeat); + else if (auto statBreak = statement->as()) + return lower(statBreak); + else if (auto statContinue = statement->as()) + return lower(statContinue); + else if (auto statReturn = statement->as()) + return lower(statReturn); else if (auto expr = statement->as()) - lower(expr); + return lower(expr); + else if (auto statFor = statement->as()) + return lower(statFor); + else if (auto statForIn = statement->as()) + return lower(statForIn); + else if (auto compAssn = statement->as()) + return lower(compAssn); + else if (auto statFn = statement->as()) + return lower(statFn); + else if (auto localFn = statement->as()) + return lower(localFn); + else if (auto typeAlias = statement->as()) + return lower(typeAlias); + else if (auto typeFn = statement->as()) + return lower(typeFn); + else if (auto declGlobal = statement->as()) + return lower(declGlobal); + else if (auto declFn = statement->as()) + return lower(declFn); + else if (auto declClass = statement->as()) + return lower(declClass); + else if (auto declExternType = statement->as()) + return lower(declExternType); + else if (auto err = statement->as()) + return lower(err); else - { LUAU_ASSERT(!"Unhandled statement"); + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatExpr* stat) +{ + LoweringExprContext ctx; + lowerExpr(ctx, stat->expr); + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatRepeat* statRepeat) +{ + Block* entryToCurrent = currentBlock.get(); + + // current -> body -> condition -> exit + // \------> body (back-edge) + // + // `continue` in a repeat loop jumps to the condition, not the body. + BlockId bodyBlock = newUnsealedBlock(BlockKind::Linear, "repeat-loop body", entryToCurrent); + BlockId loopCondition = newUnsealedBlock(BlockKind::Condition, "repeat-loop condition"); + BlockId loopExit = newUnsealedBlock(BlockKind::Linear, "repeat-loop exit"); + PushLoopContext plc(loopStack, loopCondition, loopExit); + + Block* bodyExit; + ControlFlow bodyFlow; + { + BlockScope scope{*this, bodyBlock}; + bodyFlow = lower(statRepeat->body); + bodyExit = currentBlock.get(); } + + if (bodyFlow == ControlFlow::None) + bodyExit->addSuccessor(loopCondition); + + + seal(loopCondition); + if (!loopCondition->getPredecessors().empty()) + { + BlockId conditionTruthy = newUnsealedBlock(BlockKind::Linear, "repeat-loop condition truthy"); + BlockId conditionFalsy = newUnsealedBlock(BlockKind::Linear, "repeat-loop condition falsy"); + + LoweringExprContext ctx; + ctx.inConditionalContext = true; + ctx.sense = true; + ctx.thenBlock = conditionTruthy; + ctx.elseBlock = conditionFalsy; + + std::optional condResult; + { + BlockScope scope{*this, loopCondition}; + condResult = lowerExpr(ctx, statRepeat->condition); + + if (condResult && condResult->constraint) + emitConditionalRefine(*condResult, conditionTruthy, conditionFalsy); + else if (currentBlock->getSuccessors().empty()) + { + currentBlock->addSuccessor(conditionTruthy); + currentBlock->addSuccessor(conditionFalsy); + } + } + + conditionTruthy->addSuccessor(loopExit); + conditionFalsy->addSuccessor(bodyBlock); + seal(conditionTruthy); + seal(conditionFalsy); + } + + seal(bodyBlock); + seal(loopExit); + + currentBlock = NotNull{loopExit}; + // CLI-233788 - Control flow for 'throws' is incorrectly modelled in CFG + return matches(bodyFlow, ControlFlow::Breaks | ControlFlow::Continues) ? ControlFlow::None : bodyFlow; } -void CFGBuilder::lower(AstStatExpr* stat) +ControlFlow CFGBuilder::lower(AstStatBreak*) { - lowerExpr(stat->expr); + if (LoopContext* loop = currentLoop()) + currentBlock->addSuccessor(loop->loopExit); + return ControlFlow::Breaks; } -bool CFGBuilder::tryLowerAssertion(AstExprCall* call) +ControlFlow CFGBuilder::lower(AstStatContinue*) { - if (call->args.size == 0) - return false; + if (LoopContext* loop = currentLoop()) + currentBlock->addSuccessor(loop->loopHeader); + return ControlFlow::Continues; +} - auto global = call->func->as(); - if (!global || global->name != "assert") - return false; +ControlFlow CFGBuilder::lower(AstStatReturn* statReturn) +{ + for (auto& returnItem : statReturn->list) + { + LoweringExprContext ctx{nullptr, nullptr, false, true}; + lowerExpr(ctx, returnItem); + } - AstExpr* cond = call->args.data[0]; - for (size_t i = 0; i < call->args.size; i++) + // TODO: unimplemented + return ControlFlow::Returns; +} + +ControlFlow CFGBuilder::lower(AstStatFor* statFor) +{ + Block* entryToCurrent = currentBlock.get(); + LoweringExprContext ctx; + // for var = from, to, step do body end + // Lower the bound expressions in the current block before entering the loop. + lowerExpr(ctx, statFor->from); + lowerExpr(ctx, statFor->to); + if (statFor->step) + lowerExpr(ctx, statFor->step); + + // Structure mirrors while: header -> body -> header (back-edge) + // header -> exit + BlockId loopHeader = newUnsealedBlock(BlockKind::Condition, "for-loop condition", entryToCurrent); + BlockId loopExit = newUnsealedBlock(BlockKind::Linear, "for-loop exit", loopHeader); + PushLoopContext plc(loopStack, loopHeader, loopExit); + + // Declare the loop variable in the body (scoped to the loop). + BlockId bodyBlock = newSealedBlock(BlockKind::Linear, "for-loop body", loopHeader); + { + Symbol sym{statFor->var}; + emitDefHelper(sym, bodyBlock); + } + + Block* bodyExit; + ControlFlow bodyFlow; + { + BlockScope scope{*this, bodyBlock}; + bodyFlow = lower(statFor->body); + bodyExit = currentBlock.get(); + } + + if (bodyFlow == ControlFlow::None) + bodyExit->addSuccessor(loopHeader); + seal(loopHeader); + seal(loopExit); + + currentBlock = NotNull{loopExit}; + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatForIn* statForIn) +{ + Block* entryToCurrent = currentBlock.get(); + LoweringExprContext ctx; + // for vars in values do body end + // Lower the iterator expressions in the current block. + for (size_t i = 0; i < statForIn->values.size; i++) + lowerExpr(ctx, statForIn->values.data[i]); + + BlockId loopHeader = newUnsealedBlock(BlockKind::Condition, "for-in-loop condition", entryToCurrent); + BlockId loopExit = newUnsealedBlock(BlockKind::Linear, "for-in-loop exit", loopHeader); + PushLoopContext plc(loopStack, loopHeader, loopExit); + + // Declare loop variables in the body (scoped to the loop). + BlockId bodyBlock = newSealedBlock(BlockKind::Linear, "for-in-loop body", loopHeader); + for (size_t i = 0; i < statForIn->vars.size; i++) { - lowerExpr(call->args.data[i]); - if (i == 0) + AstLocal* loc = statForIn->vars.data[i]; + Symbol sym{loc}; + emitDefHelper(sym, bodyBlock); + } + + Block* bodyExit; + ControlFlow bodyFlow; + { + BlockScope scope{*this, bodyBlock}; + bodyFlow = lower(statForIn->body); + bodyExit = currentBlock.get(); + } + + if (bodyFlow == ControlFlow::None) + bodyExit->addSuccessor(loopHeader); + seal(loopHeader); + seal(loopExit); + + currentBlock = NotNull{loopExit}; + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatCompoundAssign* compAssn) +{ + // TODO: Unimplemented + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatFunction* fn) +{ + // function f() ... end + // turns into GlobalFunction F w/ a child block for the function body + + AstName n; + if (auto glob = fn->name->as()) + { + n = glob->name; + } + else + { + LUAU_ASSERT(!"AstStatFunction with a non-global name Unimplemented"); + } + + + SSAId functionNameDef = emitDefHelper(Symbol{n}, currentBlock); + // TODO: lower the definition into + + std::string fnName = std::string(n.value ? n.value : "empty global"); + BlockId fnBlock = newSealedBlock(BlockKind::Linear, "function " + fnName); + // Arguments lower into the function + { + BlockScope scope{*this, fnBlock}; + currentBlock->setReachingDefinition(n, functionNameDef); + for (const auto& arg : fn->func->args) { - if (auto ref = resolveCondition(cond)) - emitRefineInstruction(currentBlock, *ref); + Symbol argSym{arg}; + SSAId argDef = emitDefHelper(argSym, currentBlock); + // Record the parameter's initial def so the ConstraintGenerator can + // bind it to the signature's argument type. + cfg->lhsDefs[LHS{argSym}] = argDef.get(); } + + lower(fn->func->body); } - return true; + cfg->functionBlocks.emplace_back(fnBlock); + return ControlFlow::None; } -void CFGBuilder::lower(AstStatBlock* statement) +ControlFlow CFGBuilder::lower(AstStatLocalFunction* localFn) { - for (auto st : statement->body) - lower(st); + // local function f() ... end + // turns into LocalFunction F + // there is a child block + SSAId functionNameDef = emitDefHelper(localFn->name, currentBlock); + + std::string fnName = std::string(localFn->name->name.value); + BlockId fnBlock = newSealedBlock(BlockKind::Linear, "function " + fnName); + // Arguments lower into the function + { + BlockScope scope{*this, fnBlock}; + currentBlock->setReachingDefinition(localFn->name, functionNameDef); + for (const auto& arg : localFn->func->args) + { + Symbol argSym{arg}; + SSAId argDef = emitDefHelper(argSym, currentBlock); + // Record the parameter's initial def so the ConstraintGenerator can + // bind it to the signature's argument type. + cfg->lhsDefs[LHS{argSym}] = argDef.get(); + } + + lower(localFn->func->body); + } + + cfg->functionBlocks.emplace_back(fnBlock); + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatTypeAlias* alias) +{ + // TODO: Unimplemented + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatTypeFunction*) +{ + // TODO: Unimplemented + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatDeclareGlobal*) +{ + // TODO: Unimplemented + return ControlFlow::None; } -void CFGBuilder::lower(AstStatLocal* local) +ControlFlow CFGBuilder::lower(AstStatDeclareFunction*) { + // TODO: Unimplemented + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatClass*) +{ + // TODO: Unimplemented + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatDeclareExternType*) +{ + // TODO: Unimplemented + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatError* err) +{ + for (const auto& stat : err->statements) + lower(stat); + + LoweringExprContext ctx; + for (const auto& expr : err->expressions) + lowerExpr(ctx, expr); + + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatBlock* block) +{ + for (auto st : block->body) + { + ControlFlow cf = lower(st); + if (cf != ControlFlow::None) + return cf; + } + return ControlFlow::None; +} + +ControlFlow CFGBuilder::lower(AstStatLocal* local) +{ + for (size_t i = 0; i < local->vars.size; i++) { AstLocal* loc = local->vars.data[i]; AstExpr* expr = i < local->values.size ? local->values.data[i] : nullptr; - + LoweringExprContext ctx; if (expr) - lowerExpr(expr); + lowerExpr(ctx, expr); - Symbol sym(loc); - DefId def = newDefinition(sym); - emit(currentBlock, def, local); - currentBlock->setReachingDefinition(sym, def); - cfg->lhsDefs[LValue{sym}] = def.get(); + Symbol sym{loc}; + SSAId def = emitDefHelper(sym, currentBlock); + cfg->lhsDefs[LHS{sym}] = def.get(); } + return ControlFlow::None; } -std::optional extractLValueSymbol(AstExpr* target) +void CFGBuilder::lowerLValue(LoweringExprContext& ctx, AstExpr* target) { if (auto local = target->as()) - return Symbol(local->local); + { + Symbol sym{local->local}; + SSAId def = emitDefHelper(sym, currentBlock); + cfg->lhsDefs[LHS{target}] = def.get(); + } else if (auto global = target->as()) - return Symbol(global->name); - - return std::nullopt; + { + Symbol sym{global->name}; + SSAId def = emitDefHelper(sym, currentBlock); + cfg->lhsDefs[LHS{target}] = def.get(); + } } -void CFGBuilder::lower(AstStatAssign* assn) +ControlFlow CFGBuilder::lower(AstStatAssign* assn) { + LoweringExprContext ctx; for (size_t i = 0; i < assn->values.size; i++) - lowerExpr(assn->values.data[i]); + lowerExpr(ctx, assn->values.data[i]); for (size_t i = 0; i < assn->vars.size; i++) - { - AstExpr* target = assn->vars.data[i]; + lowerLValue(ctx, assn->vars.data[i]); - if (auto sym = extractLValueSymbol(target)) - { - DefId def = newDefinition(*sym); - emit(currentBlock, def, assn); - currentBlock->setReachingDefinition(*sym, def); - cfg->lhsDefs[LValue{target}] = def.get(); - } - else - { - LUAU_ASSERT(!"Unhandled lvalue type"); - } - } + return ControlFlow::None; +} + +BlockId CFGBuilder::newSealedBlock(BlockKind kind, std::string debugName, Block* pred) +{ + BlockId b = newUnsealedBlock(kind, debugName, pred); + seal(b); + return b; } -Block* CFGBuilder::newBlock(BlockKind kind, std::string debugName, Block* pred) +BlockId CFGBuilder::newUnsealedBlock(BlockKind kind, std::string debugName, Block* pred) { - Block* b = cfg->newBlock(kind, debugName); + BlockId b = cfg->newBlock(kind, debugName); if (pred) pred->addSuccessor(b); return b; } -DefId CFGBuilder::newDefinition(Symbol sym) +SSAId CFGBuilder::newDefinition(Symbol sym) { - return allocator->newDefinition(sym, nextVersionIndex(sym)); + return allocator->newDefinition(sym); } -std::pair> CFGBuilder::emitJoin(Block* block, Symbol sym) +std::pair> CFGBuilder::emitJoin(BlockId block, Symbol sym) { - DefId def = newDefinition(sym); - InstrId jInstr = emit(block, def); + SSAId def = newDefinition(sym); + InstructionId jInstr = emit(block, def); Join* j = jInstr->get_if(); LUAU_ASSERT(j); @@ -360,219 +877,711 @@ std::pair> CFGBuilder::emitJoin(Block* block, Symbol sym) return {jInstr, NotNull{j}}; } -void CFGBuilder::lower(AstStatIf* statIf) +ControlFlow CFGBuilder::lower(AstStatIf* statIf) { - Block* currBlock = currentBlock.get(); - - Block* thenBlock = newBlock(BlockKind::Linear, "then branch", currBlock); - auto ref = resolveCondition(statIf->condition); - if (ref) - emitRefineInstruction(thenBlock, *ref); + BlockId thenBlock = newUnsealedBlock(BlockKind::Linear, "then block"); + BlockId elseBlock = newUnsealedBlock(BlockKind::Linear, "else block"); + + LoweringExprContext ctx; + ctx.inConditionalContext = true; + ctx.thenBlock = thenBlock; + ctx.elseBlock = elseBlock; + ctx.sense = true; + auto result = lowerExpr(ctx, statIf->condition); + + if (result && result->constraint) + emitConditionalRefine(*result, thenBlock, elseBlock); + else if (statIf->conditionLocal) + { + SSAId binding = readVariable(currentBlock, statIf->conditionLocal); + cfg->lhsDefs[LHS{Symbol(statIf->conditionLocal)}] = binding; + LoweringResult ifLocal{binding, Truthy{}}; + emitConditionalRefine(ifLocal, thenBlock, elseBlock); + } + else if (currentBlock->getSuccessors().empty()) + { + currentBlock->addSuccessor(thenBlock); + currentBlock->addSuccessor(elseBlock); + } - // Then only has one predecessor seal(thenBlock); + seal(elseBlock); + Block* thenExit; + ControlFlow thenFlow; { - BlockScope scope(*this, thenBlock); - lower(statIf->thenbody); + BlockScope scope{*this, thenBlock}; + thenFlow = lower(statIf->thenbody); thenExit = currentBlock.get(); } - // Else branch (may be nullptr, another AstStatIf for elseif, or a block) - Block* elseBlock = newBlock(BlockKind::Linear, "else branch", currBlock); - Block* elseExit = elseBlock; // If there is an else body, overwrite this - seal(elseBlock); - if (ref) - emitRefineInstruction(elseBlock, allocator->refinementArena.negation(*ref)); - - - if (statIf->elsebody) + Block* elseExit; + ControlFlow elseFlow = ControlFlow::None; { BlockScope scope(*this, elseBlock); - lower(statIf->elsebody); + if (statIf->elsebody) + elseFlow = lower(statIf->elsebody); elseExit = currentBlock.get(); } - // Merge block — all paths converge here - // Predecessors are wired up below once we know which branches reach here. - Block* mergeBlock = newBlock(BlockKind::Linear, "merge"); - thenExit->addSuccessor(mergeBlock); - elseExit->addSuccessor(mergeBlock); + BlockId mergeBlock = newUnsealedBlock(BlockKind::Linear, "merge"); + if (thenFlow == ControlFlow::None) + thenExit->addSuccessor(mergeBlock); + if (elseFlow == ControlFlow::None) + elseExit->addSuccessor(mergeBlock); seal(mergeBlock); currentBlock = NotNull{mergeBlock}; + if (thenFlow == elseFlow) + return thenFlow; + else if (matches(thenFlow, ControlFlow::Returns | ControlFlow::Throws) && matches(elseFlow, ControlFlow::Returns | ControlFlow::Throws)) + return ControlFlow::Returns; + else + return ControlFlow::None; } -void CFGBuilder::lower(AstStatWhile* statWhile) +ControlFlow CFGBuilder::lower(AstStatWhile* statWhile) { - Block* preLoop = currentBlock.get(); - - // Loop header — receives the back-edge so we don't seal it yet. Resolve the - // condition inside the header's scope so reads of variables mutated in the - // body hit this unsealed block, emit an incomplete Join, and get their - // operands filled in when the header is sealed after the back-edge. - Block* loopHeader = newBlock(BlockKind::Condition, "while-loop condition", preLoop); - std::optional ref; + Block* entryToCurrent = currentBlock.get(); + + // current -> loopHeader -> body -> loopHeader (back-edge) + // -> loopExit + BlockId loopHeader = newUnsealedBlock(BlockKind::Condition, "while-loop condition", entryToCurrent); + BlockId bodyBlock = newUnsealedBlock(BlockKind::Linear, "while-loop body"); + BlockId loopExit = newUnsealedBlock(BlockKind::Linear, "while-loop exit"); + PushLoopContext plc(loopStack, loopHeader, loopExit); + + // Lower the condition in the header with conditional context + LoweringExprContext ctx; + ctx.inConditionalContext = true; + ctx.sense = true; + ctx.thenBlock = bodyBlock; + ctx.elseBlock = loopExit; + std::optional condResult; { - BlockScope scope(*this, loopHeader); - ref = resolveCondition(statWhile->condition); + BlockScope scope{*this, loopHeader}; + condResult = lowerExpr(ctx, statWhile->condition); + + if (condResult && condResult->constraint) + emitConditionalRefine(*condResult, bodyBlock, loopExit); + else if (currentBlock->getSuccessors().empty()) + { + currentBlock->addSuccessor(bodyBlock); + currentBlock->addSuccessor(loopExit); + } } - Block* bodyBlock = newBlock(BlockKind::Linear, "while-loop body", loopHeader); - if (ref) - emitRefineInstruction(bodyBlock, *ref); seal(bodyBlock); + Block* bodyExit; + ControlFlow bodyFlow; { - BlockScope scope(*this, bodyBlock); - lower(statWhile->body); + BlockScope scope{*this, bodyBlock}; + bodyFlow = lower(statWhile->body); bodyExit = currentBlock.get(); } - // You can seal the loop header now because no predecessors will be added to it. - bodyExit->addSuccessor(loopHeader); + if (bodyFlow == ControlFlow::None) + bodyExit->addSuccessor(loopHeader); seal(loopHeader); + seal(loopExit); - Block* exitBlock = newBlock(BlockKind::Linear, "while-loop exit", loopHeader); - if (ref) - emitRefineInstruction(exitBlock, allocator->refinementArena.negation(*ref)); - seal(exitBlock); - currentBlock = NotNull{exitBlock}; + currentBlock = NotNull{loopExit}; + return ControlFlow::None; } -void CFGBuilder::lowerExpr(AstExpr* expr) +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExpr* expr) { - if (auto local = expr->as()) + if (auto group = expr->as()) + return lowerExpr(ctx, group); + else if (auto nil = expr->as()) + return std::nullopt; + else if (auto boolExpr = expr->as()) + return std::nullopt; + else if (auto num = expr->as()) + return std::nullopt; + else if (auto intExpr = expr->as()) + return std::nullopt; + else if (auto str = expr->as()) + return std::nullopt; + else if (auto local = expr->as()) + return lowerExpr(ctx, local); + else if (auto global = expr->as()) + return lowerExpr(ctx, global); + else if (auto varargs = expr->as()) + return lowerExpr(ctx, varargs); + else if (auto call = expr->as()) + return lowerExpr(ctx, call); + else if (auto indexName = expr->as()) + return lowerExpr(ctx, indexName); + else if (auto indexExpr = expr->as()) + return lowerExpr(ctx, indexExpr); + else if (auto func = expr->as()) + return lowerExpr(ctx, func); + else if (auto table = expr->as()) + return lowerExpr(ctx, table); + else if (auto unary = expr->as()) + return lowerExpr(ctx, unary); + else if (auto binop = expr->as()) + return lowerExpr(ctx, binop); + else if (auto typeAssertion = expr->as()) + return lowerExpr(ctx, typeAssertion); + else if (auto ifElse = expr->as()) + return lowerExpr(ctx, ifElse); + else if (auto interpStr = expr->as()) + return lowerExpr(ctx, interpStr); + else if (auto instantiate = expr->as()) + return lowerExpr(ctx, instantiate); + else if (auto err = expr->as()) + return lowerExpr(ctx, err); + else + LUAU_ASSERT(!"Unhandled expression type"); + + return std::nullopt; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprGroup* group) +{ + return lowerExpr(ctx, group->expr); +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprLocal* local) +{ + if (local->upvalue) { - lowerExpr(local); + SSAId def = emitDefHelper(local->local, currentBlock); + return LoweringResult{def}; } - else if (auto binop = expr->as()) + SSAId def = readVariable(currentBlock, Symbol(local->local)); + cfg->useDefs[local] = def; + return LoweringResult{def, Truthy{}}; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprGlobal* global) +{ + SSAId def = readVariable(currentBlock, Symbol(global->name)); + cfg->useDefs[global] = def; + return LoweringResult{def, Truthy{}}; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprVarargs* args) +{ + return std::nullopt; +} + + +std::optional CFGBuilder::handleAssert(LoweringExprContext& ctx, const AstExprCall& call) +{ + if (call.args.size == 0) + return std::nullopt; + + auto global = call.func->as(); + if (!global || global->name != "assert") + return std::nullopt; + + BlockId resumeBlock = newUnsealedBlock(BlockKind::Condition, "assertion-finish"); + BlockId elseBlock = newUnsealedBlock(BlockKind::Condition, "assertion-err-else"); + + LoweringExprContext c; + c.inConditionalContext = true; + c.sense = true; + c.thenBlock = resumeBlock; + c.elseBlock = elseBlock; + // TODO: Handle additional arguments to assert, such as the error message. + // Also traverse through the function associated with assert. + auto result = lowerExpr(c, call.args.data[0]); + + if (result && result->constraint) + emitConditionalRefine(*result, resumeBlock, elseBlock); + else if (currentBlock->getSuccessors().empty()) { - lowerExpr(binop->left); - lowerExpr(binop->right); + currentBlock->addSuccessor(resumeBlock); + currentBlock->addSuccessor(elseBlock); } - else if (auto call = expr->as()) + + seal(resumeBlock); + seal(elseBlock); + currentBlock = resumeBlock; + return result; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprCall* call) +{ + if (auto loweringResult = handleAssert(ctx, *call)) + return loweringResult; + lowerExpr(ctx, call->func); + for (size_t i = 0; i < call->args.size; i++) + lowerExpr(ctx, call->args.data[i]); + return std::nullopt; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprIndexName* indexName) +{ + auto idx = Index::fromExpr(indexName); + if (!idx || idx->path.empty()) { - lowerExpr(call); + LoweringExprContext subCtx; + lowerExpr(subCtx, indexName->expr); + return std::nullopt; } - else if (auto group = expr->as()) + + SSAId def = readVariable(currentBlock, idx->source); + cfg->useDefs[idx->sourceExpr] = def; + + return LoweringResult{def, HasShape{std::move(idx->path), Truthy{}}}; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprIndexExpr* indexExpr) +{ + // TODO: Unimplemented + return std::nullopt; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprFunction*) +{ + // TODO: Unimplemented + return std::nullopt; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprTable* table) +{ + + // TODO: Unimplemented + return std::nullopt; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprUnary* unary) +{ + if (unary->op == AstExprUnary::Op::Not) { - lowerExpr(group->expr); + ctx.sense = !ctx.sense; + auto result = lowerExpr(ctx, unary->expr); + if (result && result->constraint) + return LoweringResult{result->def, invert(*result->constraint)}; + return result; } + + LoweringExprContext subCtx; + lowerExpr(subCtx, unary->expr); + return std::nullopt; } -void CFGBuilder::lowerExpr(AstExprLocal* local) +// Wires currentBlock to truthyDest and falsyDest, emitting Refine instructions +// based on the LowerResult's constraint. +void CFGBuilder::emitConditionalRefine(LoweringResult& result, Block* truthyDest, Block* falsyDest) { - DefId def = readVariable(currentBlock, Symbol(local->local)); - cfg->useDefs[local] = def; + currentBlock->addSuccessor(truthyDest); + currentBlock->addSuccessor(falsyDest); + + Symbol sym = result.def->getSym(); + + emitDefHelper(sym, truthyDest, result.def, NarrowingConstraint{*result.constraint}); + emitDefHelper(sym, falsyDest, result.def, invert(*result.constraint)); } -void CFGBuilder::lowerExpr(AstExprCall* call) +static std::optional lowerSingletonExpr(AstExpr* expr, bool sense) { - if (tryLowerAssertion(call)) - return; - lowerExpr(call->func); - for (size_t i = 0; i < call->args.size; i++) - lowerExpr(call->args.data[i]); + if (auto grp = expr->as()) + return lowerSingletonExpr(grp->expr, sense); + else if (auto str = expr->as()) + { + auto stringleton = StringSingletonValue{std::string(str->value.data, str->value.size)}; + if (sense) + return SingletonEq{std::move(stringleton)}; + else + return SingletonNeq{std::move(stringleton)}; + } + else if (auto b = expr->as()) + { + auto boolsingleton = BooleanSingletonValue{b->value}; + if (sense) + return SingletonEq{std::move(boolsingleton)}; + else + return SingletonNeq{std::move(boolsingleton)}; + } + else if (auto n = expr->as()) + { + if (sense) + return SingletonEq{NilSingletonValue{}}; + else + return SingletonNeq{NilSingletonValue{}}; + } + + return std::nullopt; } -std::optional CFGBuilder::resolveCondition(AstExpr* condition) +struct SingletonGuard +{ + SingletonGuard(AstExpr* toLower, LeafConstraint c) + : toLower(toLower) + , c(std::move(c)) + { + } + AstExpr* toLower; + LeafConstraint c; +}; + +static std::optional matchSingletonGuard(AstExprBinary* expr) { - auto& arena = allocator->refinementArena; + if (expr->op != AstExprBinary::CompareEq && expr->op != AstExprBinary::CompareNe) + return std::nullopt; + + bool sense = expr->op == AstExprBinary::CompareEq; + if (auto lhs = lowerSingletonExpr(expr->left, sense)) + return SingletonGuard{expr->right, *lhs}; - if (auto group = condition->as()) + if (auto rhs = lowerSingletonExpr(expr->right, sense)) + return SingletonGuard{expr->left, *rhs}; + + return std::nullopt; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprBinary* binop) +{ + if (auto tg = matchTypeGuard(binop->op, binop->left, binop->right)) { - return resolveCondition(group->expr); + AstExpr* target = tg->target; + + if (auto idx = Index::fromExpr(target)) + { + SSAId def = readVariable(currentBlock, idx->source); + cfg->useDefs[idx->sourceExpr] = def; + + if (idx->path.empty()) + { + if (binop->op == AstExprBinary::CompareEq) + return LoweringResult{def, TypeEq{tg->type, tg->isTypeof}}; + else + return LoweringResult{def, TypeNeq{tg->type, tg->isTypeof}}; + } + else + { + LeafConstraint leaf = (binop->op == AstExprBinary::CompareEq) ? LeafConstraint{TypeEq{tg->type, tg->isTypeof}} + : LeafConstraint{TypeNeq{tg->type, tg->isTypeof}}; + return LoweringResult{def, HasShape{idx->path, std::move(leaf)}}; + } + } + + LoweringExprContext subCtx; + lowerExpr(subCtx, target); + return std::nullopt; } - else if (auto loc = condition->as()) + + if (auto sg = matchSingletonGuard(binop)) { - DefId def = readVariable(currentBlock, Symbol(loc->local)); - cfg->useDefs[loc] = def; - return arena.proposition(def, /* sense */ true); + if (auto idx = Index::fromExpr(sg->toLower)) + { + SSAId def = readVariable(currentBlock, idx->source); + cfg->useDefs[idx->sourceExpr] = def; + + if (idx->path.empty()) + { + if (auto eq = sg->c.get_if()) + return LoweringResult{def, SingletonEq{eq->v}}; + else if (auto neq = sg->c.get_if()) + return LoweringResult{def, SingletonNeq{neq->v}}; + + LUAU_ASSERT(!"singleton guard should only produce singleton constraints"); + return std::nullopt; + } + + return LoweringResult{def, HasShape{idx->path, std::move(sg->c)}}; + } + + LoweringExprContext subCtx; + lowerExpr(subCtx, sg->toLower); + return std::nullopt; } - else if (auto binop = condition->as()) + + if (binop->op == AstExprBinary::And) { - if (auto tg = matchTypeGuard(binop->op, binop->left, binop->right)) + if (ctx.inConditionalContext) { - if (auto tgtLocal = tg->target->as()) + // and short-circuits on falsy + Block* shortCircuitDest = ctx.sense ? ctx.elseBlock : ctx.thenBlock; + Block* truthyDest = ctx.sense ? ctx.thenBlock : ctx.elseBlock; + BlockId continueBlock = newUnsealedBlock(BlockKind::Linear, "and-rhs"); + + // Intermediate block for lhs falsy refinement lives here, flows to shortCircuitDest + BlockId lhsFalsyBlock = newUnsealedBlock(BlockKind::Linear, "and-lhs-falsy"); + + // Lower lhs — compound operands need conditional context to wire internally + LoweringExprContext lhsCtx; + lhsCtx.inConditionalContext = true; + lhsCtx.sense = true; + lhsCtx.thenBlock = continueBlock; + lhsCtx.elseBlock = lhsFalsyBlock; + auto lhsResult = lowerExpr(lhsCtx, binop->left); + + // curr -> continue(and lhs truthy) block + //. -> continue(and lhs falsy) block -> dest + // + if (lhsResult && lhsResult->constraint) + emitConditionalRefine(*lhsResult, continueBlock, lhsFalsyBlock); + else if (currentBlock->getSuccessors().empty()) { - auto def = readVariable(currentBlock, Symbol(tgtLocal->local)); - cfg->useDefs[tgtLocal] = def; - bool sense = binop->op == AstExprBinary::CompareEq; - return arena.typeProposition(def, tg->type, tg->isTypeof, sense); + currentBlock->addSuccessor(continueBlock); + currentBlock->addSuccessor(lhsFalsyBlock); } + + lhsFalsyBlock->addSuccessor(shortCircuitDest); + seal(lhsFalsyBlock); + seal(continueBlock); + + { + BlockScope scope{*this, continueBlock}; + auto rhsResult = lowerExpr(ctx, binop->right); + + if (rhsResult && rhsResult->constraint) + { + // Intermediate block for rhs falsy refinement lives here, flows to shortCircuitDest + BlockId rhsFalsyBlock = newSealedBlock(BlockKind::Linear, "and-rhs-falsy", currentBlock.get()); + { + Symbol sym = rhsResult->def->getSym(); + emitDefHelper(sym, rhsFalsyBlock, rhsResult->def, invert(*rhsResult->constraint)); + } + rhsFalsyBlock->addSuccessor(shortCircuitDest); + + // Intermediate block for rhs truthy refinement lives here, flows to truthyDest + BlockId rhsTruthyBlock = newSealedBlock(BlockKind::Linear, "and-rhs-truthy", currentBlock.get()); + { + Symbol sym = rhsResult->def->getSym(); + emitDefHelper(sym, rhsTruthyBlock, rhsResult->def, NarrowingConstraint{*rhsResult->constraint}); + } + rhsTruthyBlock->addSuccessor(truthyDest); + } + else if (currentBlock->getSuccessors().empty()) + { + currentBlock->addSuccessor(truthyDest); + currentBlock->addSuccessor(shortCircuitDest); + } + } + return std::nullopt; } - auto lRef = resolveCondition(binop->left); - auto rRef = resolveCondition(binop->right); - if (binop->op == AstExprBinary::And) + // Non-conditional: value-producing `and` + Block* currBlock = currentBlock.get(); + LoweringExprContext subCtx; + auto lhs = lowerExpr(subCtx, binop->left); + if (!lhs || !lhs->constraint) { - // (A and B) truthy => both truthy; a missing side still preserves the other. - if (lRef && rRef) - return arena.conjunction(*lRef, *rRef); - return lRef ? lRef : rRef; + lowerExpr(subCtx, binop->right); + return std::nullopt; } - else if (binop->op == AstExprBinary::Or) + + BlockId rhsBlock = newSealedBlock(BlockKind::Linear, "and-rhs", currBlock); + BlockId shortCircuitBlock = newSealedBlock(BlockKind::Linear, "and-short-circuit", currBlock); + + std::optional rhsResult; { - // (A or B) truthy => at least one truthy; an unrefined side means we can't narrow. - if (lRef && rRef) - return arena.disjunction(*lRef, *rRef); + BlockScope scope{*this, rhsBlock}; + Symbol sym = lhs->def->getSym(); + emitDefHelper(sym, rhsBlock, lhs->def, NarrowingConstraint{*lhs->constraint}); + rhsResult = lowerExpr(subCtx, binop->right); } + + { + BlockScope scope{*this, shortCircuitBlock}; + Symbol sym = lhs->def->getSym(); + emitDefHelper(sym, shortCircuitBlock, lhs->def, invert(*lhs->constraint)); + } + + BlockId mergeBlock = newUnsealedBlock(BlockKind::Linear, "and-merge"); + rhsBlock.get()->addSuccessor(mergeBlock); + shortCircuitBlock.get()->addSuccessor(mergeBlock); + seal(mergeBlock); + currentBlock = mergeBlock; + + return rhsResult; } - else if (auto unop = condition->as()) + + if (binop->op == AstExprBinary::Or) { - if (unop->op == AstExprUnary::Op::Not) + if (ctx.inConditionalContext) + { + // or short-circuits on truthy + Block* shortCircuitDest = ctx.sense ? ctx.thenBlock : ctx.elseBlock; + Block* falsyDest = ctx.sense ? ctx.elseBlock : ctx.thenBlock; + BlockId continueBlock = newUnsealedBlock(BlockKind::Linear, "or-rhs"); + + // Intermediate block for lhs truthy — refinement lives here, flows to shortCircuitDest + BlockId lhsTruthyBlock = newUnsealedBlock(BlockKind::Linear, "or-lhs-truthy"); + + // Lower lhs — for `or`, truthy → short-circuit, falsy → continue + LoweringExprContext lhsCtx; + lhsCtx.inConditionalContext = true; + lhsCtx.sense = true; + lhsCtx.thenBlock = lhsTruthyBlock; + lhsCtx.elseBlock = continueBlock; + auto lhsResult = lowerExpr(lhsCtx, binop->left); + + if (lhsResult && lhsResult->constraint) + emitConditionalRefine(*lhsResult, lhsTruthyBlock, continueBlock); + else if (currentBlock->getSuccessors().empty()) + { + currentBlock->addSuccessor(lhsTruthyBlock); + currentBlock->addSuccessor(continueBlock); + } + + lhsTruthyBlock->addSuccessor(shortCircuitDest); + seal(lhsTruthyBlock); + seal(continueBlock); + + { + BlockScope scope{*this, continueBlock}; + auto rhsResult = lowerExpr(ctx, binop->right); + + if (rhsResult && rhsResult->constraint) + { + // Intermediate block for rhs truthy — refinement lives here, flows to shortCircuitDest + BlockId rhsTruthyBlock = newSealedBlock(BlockKind::Linear, "or-rhs-truthy", currentBlock.get()); + { + Symbol sym = rhsResult->def->getSym(); + emitDefHelper(sym, rhsTruthyBlock, rhsResult->def, NarrowingConstraint{*rhsResult->constraint}); + } + rhsTruthyBlock->addSuccessor(shortCircuitDest); + + // Intermediate block for rhs falsy — refinement lives here, flows to falsyDest + BlockId rhsFalsyBlock = newSealedBlock(BlockKind::Linear, "or-rhs-falsy", currentBlock.get()); + { + Symbol sym = rhsResult->def->getSym(); + emitDefHelper(sym, rhsFalsyBlock, rhsResult->def, invert(*rhsResult->constraint)); + } + rhsFalsyBlock->addSuccessor(falsyDest); + } + else if (currentBlock->getSuccessors().empty()) + { + currentBlock->addSuccessor(shortCircuitDest); + currentBlock->addSuccessor(falsyDest); + } + } + + return std::nullopt; + } + + // Non-conditional: value-producing `or` + Block* currBlock = currentBlock.get(); + LoweringExprContext subCtx; + auto lhs = lowerExpr(subCtx, binop->left); + if (!lhs || !lhs->constraint) + { + lowerExpr(subCtx, binop->right); + return std::nullopt; + } + + BlockId shortCircuitBlock = newSealedBlock(BlockKind::Linear, "or-short-circuit", currBlock); + BlockId rhsBlock = newSealedBlock(BlockKind::Linear, "or-rhs", currBlock); + + { + BlockScope scope{*this, shortCircuitBlock}; + Symbol sym = lhs->def->getSym(); + emitDefHelper(sym, shortCircuitBlock, lhs->def, NarrowingConstraint{*lhs->constraint}); + } + + std::optional rhsResult; { - if (auto inner = resolveCondition(unop->expr)) - return arena.negation(*inner); + BlockScope scope{*this, rhsBlock}; + Symbol sym = lhs->def->getSym(); + emitDefHelper(sym, rhsBlock, lhs->def, invert(*lhs->constraint)); + rhsResult = lowerExpr(subCtx, binop->right); } + + BlockId mergeBlock = newUnsealedBlock(BlockKind::Linear, "or-merge"); + shortCircuitBlock.get()->addSuccessor(mergeBlock); + rhsBlock.get()->addSuccessor(mergeBlock); + seal(mergeBlock); + currentBlock = mergeBlock; + + return rhsResult; } + LoweringExprContext subCtx; + lowerExpr(subCtx, binop->left); + lowerExpr(subCtx, binop->right); return std::nullopt; } -void CFGBuilder::emitRefineInstruction(Block* block, CFGRefinement::RefinementId refinement) +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprTypeAssertion* typeAssertion) { - // This function walks the refinement tree and, at every - // Proposition, emits a refinement into the block with a fresh definition. - // This differs only slightly from SSI form, which introduces a virtual `sigma` - // definition as a terminator, which then gets written in subsequent blocks. - // I've chosen to elide this terminator in favor of just emitting the fresh def + refinement - // explicitly into the block. A consequence of this is that this representation will mint a - // empty block with only refinement information, but this just makes it easier to handle phi emission. - visit( - overloaded{ - [&](const CFGRefinement::Proposition& prop) - { - DefId refined = newDefinition(prop.ptr->sym); - emit(block, refined, prop); - block->setReachingDefinition(prop.ptr->sym, refined); - }, - [&](const CFGRefinement::Conjunction& conj) - { - emitRefineInstruction(block, conj.lhs); - emitRefineInstruction(block, conj.rhs); - }, - [&](const CFGRefinement::Negation& neg) - { - // RefinementArena::negation pushes through And/Or via DeMorgan and cancels - // double negation, so the only shape that reaches here is Negation(Proposition). - auto prop = neg.refinement->get_if(); - LUAU_ASSERT(prop != nullptr); - emitRefineInstruction(block, allocator->refinementArena.typeProposition(prop->ptr, prop->type, prop->isTypeof, !prop->sense)); - }, - [&](const CFGRefinement::Disjunction&) - { - // CLI-205330 tracks the work needed to handle Disjunctions (e.g. we need to calculate sets of propositions on individual defs - // For the most part, this would just re-implement the existing refinement calculation logic in constraint generation. - }, - }, - *refinement - ); + LoweringExprContext subCtx; + lowerExpr(subCtx, typeAssertion->expr); + return std::nullopt; } -DefId CFGBuilder::readVariable(BlockId block, Symbol sym) +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprIfElse* ifElse) +{ + BlockId thenBlock = newUnsealedBlock(BlockKind::Linear, "if-else expr then"); + BlockId elseBlock = newUnsealedBlock(BlockKind::Linear, "if-else expr else"); + + LoweringExprContext condCtx; + condCtx.inConditionalContext = true; + condCtx.thenBlock = thenBlock; + condCtx.elseBlock = elseBlock; + condCtx.sense = true; + auto condResult = lowerExpr(condCtx, ifElse->condition); + + if (condResult && condResult->constraint) + emitConditionalRefine(*condResult, thenBlock, elseBlock); + else if (ifElse->conditionLocal) + { + SSAId binding = readVariable(currentBlock, ifElse->conditionLocal); + cfg->lhsDefs[LHS{Symbol(ifElse->conditionLocal)}] = binding; + LoweringResult ifLocal{binding, Truthy{}}; + emitConditionalRefine(ifLocal, thenBlock, elseBlock); + } + else if (currentBlock->getSuccessors().empty()) + { + currentBlock->addSuccessor(thenBlock); + currentBlock->addSuccessor(elseBlock); + } + + seal(thenBlock); + seal(elseBlock); + + { + BlockScope scope{*this, thenBlock}; + LoweringExprContext subCtx; + lowerExpr(subCtx, ifElse->trueExpr); + } + + { + BlockScope scope{*this, elseBlock}; + LoweringExprContext subCtx; + lowerExpr(subCtx, ifElse->falseExpr); + } + + BlockId mergeBlock = newUnsealedBlock(BlockKind::Linear, "if-else expr merge"); + thenBlock.get()->addSuccessor(mergeBlock); + elseBlock.get()->addSuccessor(mergeBlock); + seal(mergeBlock); + currentBlock = mergeBlock; + + return std::nullopt; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprInterpString* interpStr) +{ + for (size_t i = 0; i < interpStr->expressions.size; i++) + lowerExpr(ctx, interpStr->expressions.data[i]); + return std::nullopt; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprInstantiate* instantiate) +{ + lowerExpr(ctx, instantiate->expr); + return std::nullopt; +} + +std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, AstExprError* err) +{ + for (size_t i = 0; i < err->expressions.size; i++) + lowerExpr(ctx, err->expressions.data[i]); + + return std::nullopt; +} + +SSAId CFGBuilder::readVariable(BlockId block, Symbol sym) { if (auto v = block->getReachingDefinition(sym); v != nullptr) return NotNull{v}; @@ -593,94 +1602,58 @@ DefId CFGBuilder::readVariable(BlockId block, Symbol sym) auto [inst, join] = emitJoin(block, sym); block->setReachingDefinition(sym, join->definition); auto d = fillJoinOperands(block, inst, join); - block->setReachingDefinition(d->sym, d); + block->setReachingDefinition(d->getSym(), d); return d; } } -DefId CFGBuilder::fillJoinOperands(Block* block, InstrId instr, Join* j) +SSAId CFGBuilder::fillJoinOperands(Block* block, InstructionId instr, Join* j) { for (BlockId pred : block->getPredecessors()) { - auto def = readVariable(pred, j->definition->sym); + auto def = readVariable(pred, j->definition->getSym()); j->operands.emplace_back(def); } - recordUses(instr); return trimTrivialJoin(instr, j); } -DefId CFGBuilder::trimTrivialJoin(InstrId inst, Join* j) +SSAId CFGBuilder::trimTrivialJoin(InstructionId inst, Join* j) { LUAU_ASSERT(j); - auto curr = j->definition; - // Tracks the duplicated or unreachable phi nodes - Definition* same = nullptr; - // Phis have two operands (by construction) + SSAId curr = j->definition; + + // Collect unique operands, excluding self-references + InsertionOrderedMap unique; for (auto& op : j->operands) { - if (op == same || op == curr) - continue; - if (same != nullptr) - return curr; - same = op; + if (op != curr) + unique.insert(op, true); } - DenseHashSet tmp_; - DenseHashSet& usingInsts = tmp_; - if (DenseHashSet* uses = usingInstructions.find(curr)) - usingInsts = *uses; - usingInsts.erase(inst); - - if (same == nullptr) + // All operands are self-references (unreachable back-edge only) + if (unique.size() == 0) return curr; - inst->emplace(); - // The current join is trivial, so we can replace it with the single op that isn't itself - cfg->forwards[curr.get()] = same; - - for (auto& usingInst : usingInsts) + // Exactly one distinct non-self operand — join is trivial, redirect to it + if (unique.size() == 1) { - if (Join* j = usingInst->get_if()) - trimTrivialJoin(NotNull{usingInst}, j); - } - - return NotNull{same}; -} + Definition* same = nullptr; + for (auto& op : unique) + same = op.first; -void CFGBuilder::recordUses(InstrId inst) -{ - visit( - overloaded{ - [&](const Declare&) {}, - [&](const Assign&) {}, - [&](const Dead&) {}, - [&](const Join& join) - { - for (auto& op : join.operands) - usingInstructions[op].insert(inst); - }, - [&](const Refine& refine) - { - usingInstructions[refine.toRefine.get()].insert(inst); - }, - }, - *inst.get() - ); -} - -size_t CFGBuilder::nextVersionIndex(Symbol sym) -{ - if (!versionCounter.contains(sym)) - { - versionCounter[sym] = 0; - return 0; + inst->emplace(); + curr->redirect(same); + return NotNull{same}; } - auto ref = versionCounter.find(sym); - *ref += 1; - return *ref; + // Multiple distinct operands — keep the join with deduplicated operands + std::vector newOps; + for (auto& op : unique) + newOps.emplace_back(op.first); + j->operands = std::move(newOps); + return curr; } -} // namespace Luau::CFG +} // namespace Luau diff --git a/Analysis/src/DataFlowGraph.cpp b/Analysis/src/DataFlowGraph.cpp index db42beba1..2bfb0aa31 100644 --- a/Analysis/src/DataFlowGraph.cpp +++ b/Analysis/src/DataFlowGraph.cpp @@ -13,6 +13,7 @@ LUAU_FASTFLAG(DebugLuauFreezeArena) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) +LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) namespace Luau { @@ -538,6 +539,15 @@ ControlFlow DataFlowGraphBuilder::visit(AstStatWhile* w) { PushScope ps{scopeStack, whileScope}; visitExpr(w->condition); + + if (FFlag::DebugLuauWhileLocalAnalysis && w->conditionLocal) + { + DefId def = defArena->freshCell(w->conditionLocal, w->conditionLocal->location, false); + graph.localDefs[w->conditionLocal] = def; + whileScope->bindings[w->conditionLocal] = def; + captures[w->conditionLocal].allVersions.push_back(def); + } + cf = visit(w->body); } diff --git a/Analysis/src/DumpCFG.cpp b/Analysis/src/DumpCFG.cpp index 714c0cb00..ed440bc3a 100644 --- a/Analysis/src/DumpCFG.cpp +++ b/Analysis/src/DumpCFG.cpp @@ -8,7 +8,6 @@ LUAU_FASTFLAGVARIABLE(DebugLuauLogCFG) LUAU_FASTFLAGVARIABLE(DebugLuauDumpCFGJson) -using namespace Luau::CFG; namespace Luau { @@ -94,50 +93,67 @@ struct ExprPrinter : AstVisitor } }; -static std::string dumpExpr(AstExpr* expr, NotNull cfg) +[[maybe_unused]] static std::string dumpExpr(AstExpr* expr, NotNull cfg) { ExprPrinter printer(cfg); expr->visit(&printer); return printer.result; } -static AstExpr* findRhsExpr(Symbol sym, AstStatLocal* source) +static std::string dumpSingletonValue(const SingletonValue& value) { - if (!sym.local) - return nullptr; - for (size_t i = 0; i < source->vars.size; i++) - { - if (source->vars.data[i] == sym.local && i < source->values.size) - return source->values.data[i]; - } - return nullptr; + return Luau::visit( + overloaded{ + [](const StringSingletonValue& stringValue) -> std::string + { + return "\"" + stringValue.value + "\""; + }, + [](const BooleanSingletonValue& booleanValue) -> std::string + { + return booleanValue.value ? "true" : "false"; + }, + [](const NilSingletonValue& nilValue) -> std::string + { + return "nil"; + }, + }, + value + ); } -static AstExpr* findRhsExpr(Symbol sym, AstStatAssign* source) +static std::string dumpLeafConstraint(const std::string& target, const LeafConstraint& constraint) { - for (size_t i = 0; i < source->vars.size; i++) - { - if (i >= source->values.size) - continue; - AstExpr* var = source->vars.data[i]; - if (sym.local) - { - if (auto* exprLocal = var->as()) + return Luau::visit( + overloaded{ + [&](const Truthy&) -> std::string { - if (exprLocal->local == sym.local) - return source->values.data[i]; - } - } - else if (sym.global.value) - { - if (auto* exprGlobal = var->as()) + return target + " is truthy"; + }, + [&](const Falsy&) -> std::string { - if (exprGlobal->name == sym.global) - return source->values.data[i]; - } - } - } - return nullptr; + return target + " is falsy"; + }, + [&](const TypeEq& eq) -> std::string + { + std::string fn = eq.isTypeOf ? "typeof" : "type"; + return fn + "(" + target + ") == \"" + eq.type + "\""; + }, + [&](const TypeNeq& neq) -> std::string + { + std::string fn = neq.isTypeOf ? "typeof" : "type"; + return fn + "(" + target + ") ~= \"" + neq.type + "\""; + }, + [&](const SingletonEq& eq) -> std::string + { + return target + " == " + dumpSingletonValue(eq.v); + }, + [&](const SingletonNeq& neq) -> std::string + { + return target + " ~= " + dumpSingletonValue(neq.v); + }, + }, + constraint + ); } static std::string dumpInstruction(const Instruction* inst, NotNull cfg) @@ -146,17 +162,27 @@ static std::string dumpInstruction(const Instruction* inst, NotNull std::string { - std::string result = "local " + dumpDef(decl.def); - if (AstExpr* rhs = findRhsExpr(decl.def->sym, decl.source)) - result += " = " + dumpExpr(rhs, cfg); - return result; + return "local " + dumpDef(decl.def) + " = "; + }, + [&](const LocalFunction& fn) -> std::string + { + return "local function " + dumpDef(fn.def); + }, + [&](const GlobalFunction& fn) -> std::string + { + return "global function " + dumpDef(fn.def); + }, + [&](const Arg& arg) -> std::string + { + return "param " + dumpDef(arg.def); + }, + [&](const Upvalue& uv) -> std::string + { + return dumpDef(uv.def) + " = upvalue"; }, [&](const Assign& assign) -> std::string { - std::string result = dumpDef(assign.def); - if (AstExpr* rhs = findRhsExpr(assign.def->sym, assign.source)) - result += " = " + dumpExpr(rhs, cfg); - return result; + return dumpDef(assign.def) + " = "; }, [](const Join& join) -> std::string { @@ -170,25 +196,54 @@ static std::string dumpInstruction(const Instruction* inst, NotNull std::string + [](const Refine& refine) -> std::string { - std::string rhs; - if (flow.type) - { - const char* guard = flow.isTypeof ? "typeof" : "type"; - const char* cmp = flow.sense ? "==" : "~="; - rhs = std::string(guard) + "(" + dumpDef(flow.toRefine) + ") " + cmp + " \"" + *flow.type + "\""; - } - else - { - rhs = dumpDef(flow.toRefine) + " " + (flow.sense ? "truthy" : "falsy"); - } - return dumpDef(flow.definition) + " = refine(" + rhs + ")"; + std::string target = dumpDef(refine.target); + std::string constraint = Luau::visit( + overloaded{ + [&](const Truthy&) -> std::string + { + return target + " is truthy"; + }, + [&](const Falsy&) -> std::string + { + return target + " is falsy"; + }, + [&](const TypeEq& eq) -> std::string + { + std::string fn = eq.isTypeOf ? "typeof" : "type"; + return fn + "(" + target + ") == \"" + eq.type + "\""; + }, + [&](const TypeNeq& neq) -> std::string + { + std::string fn = neq.isTypeOf ? "typeof" : "type"; + return fn + "(" + target + ") ~= \"" + neq.type + "\""; + }, + [&](const SingletonEq& eq) -> std::string + { + return target + " == " + dumpSingletonValue(eq.v); + }, + [&](const SingletonNeq& neq) -> std::string + { + return target + " ~= " + dumpSingletonValue(neq.v); + }, + [&](const HasShape& hs) -> std::string + { + std::string path = target; + for (const auto& p : hs.path) + path += "." + p; + + return dumpLeafConstraint(path, hs.constraint); + }, + }, + refine.constraint + ); + return dumpDef(refine.definition) + " = refine(" + constraint + ")"; }, [](const Dead&) -> std::string { return ""; - }, + } }, *inst ); @@ -349,7 +404,7 @@ std::string dumpCFGJson(const ControlFlowGraph& cfg) std::string out = "{\"functions\":[{\"name\":\"cfg\",\"passes\":[{\"name\":\"CFG\",\"mir\":{\"blocks\":["; - int nextInstrId = 1; + int nextInstructionId = 1; for (size_t i = 0; i < cfg.blocks.size(); i++) { const Block* block = cfg.blocks[i]; @@ -395,12 +450,12 @@ std::string dumpCFGJson(const ControlFlowGraph& cfg) out += "]"; out += ",\"instructions\":["; - const std::vector& instructions = block->getInstructions(); + const std::vector& instructions = block->getInstructions(); for (size_t j = 0; j < instructions.size(); j++) { if (j > 0) out += ','; - out += "{\"id\":" + std::to_string(nextInstrId++); + out += "{\"id\":" + std::to_string(nextInstructionId++); out += ",\"opcode\":\"" + jsonEscape(dumpInstruction(instructions[j], NotNull{&cfg})) + "\""; out += ",\"attributes\":[],\"inputs\":[],\"uses\":[],\"memInputs\":[],\"type\":\"\"}"; } @@ -414,4 +469,109 @@ std::string dumpCFGJson(const ControlFlowGraph& cfg) return out; } +std::string dump(const Definition* def) +{ + if (!def) + return "(null)"; + char buf[128]; + snprintf(buf, sizeof(buf), "%p %s", static_cast(def), def->versionedName().c_str()); + printf("%s\n", buf); + return buf; +} + +std::string dump(const Instruction* inst) +{ + if (!inst) + { + printf("(null)\n"); + return "(null)"; + } + std::string result = Luau::visit( + overloaded{ + [&](const Declare& decl) -> std::string + { + return "local " + dumpDef(decl.def); + }, + [&](const LocalFunction& fn) -> std::string + { + return "local function " + dumpDef(fn.def); + }, + [&](const GlobalFunction& fn) -> std::string + { + return "global function " + dumpDef(fn.def); + }, + [&](const Arg& arg) -> std::string + { + return "param " + dumpDef(arg.def); + }, + [&](const Upvalue& uv) -> std::string + { + return dumpDef(uv.def) + " = upvalue"; + }, + [&](const Assign& assign) -> std::string + { + return dumpDef(assign.def) + " = "; + }, + [](const Join& join) -> std::string + { + std::string r = dumpDef(join.definition) + " = join("; + for (size_t i = 0; i < join.operands.size(); i++) + { + if (i > 0) + r += ", "; + r += dumpDef(join.operands[i]); + } + return r + ")"; + }, + [](const Refine& refine) -> std::string + { + return dumpDef(refine.definition) + " = refine(" + dumpDef(refine.target) + ")"; + }, + [](const Dead&) -> std::string + { + return ""; + }, + }, + *inst + ); + printf("%s\n", result.c_str()); + return result; +} + +void dump(const Block* block) +{ + if (!block) + { + printf("(null)\n"); + return; + } + printf( + "%p %s \"%s\" [%zu instrs]\n", + static_cast(block), + blockKindName(block->kind), + block->debugName.c_str(), + block->getInstructions().size() + ); + for (const Instruction* inst : block->getInstructions()) + { + if (inst->get_if()) + continue; + printf(" "); + dump(inst); + } +} + +std::string dump(SSAId def) +{ + return dump(def.get()); +} +std::string dump(InstructionId inst) +{ + return dump(inst.get()); +} +void dump(BlockId block) +{ + return dump(block.get()); +} + } // namespace Luau diff --git a/Analysis/src/FragmentAutocomplete.cpp b/Analysis/src/FragmentAutocomplete.cpp index bc5b77912..d10b8ab33 100644 --- a/Analysis/src/FragmentAutocomplete.cpp +++ b/Analysis/src/FragmentAutocomplete.cpp @@ -36,6 +36,7 @@ LUAU_FASTFLAG(LuauCyclicRequireTypeInference) LUAU_FASTFLAGVARIABLE(LuauFragmentACLocalAutocompleteFix) LUAU_FASTFLAGVARIABLE(LuauAutocompleteIfSlurpsCond) LUAU_FASTFLAG(LuauSplitIceHandler) +LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) namespace Luau { @@ -546,6 +547,17 @@ FragmentAutocompleteAncestryResult findAncestryForFragmentParse(AstStatBlock* st localMap[ifStat->conditionLocal->name] = ifStat->conditionLocal; } } + + // Add the `while local` binding to the local map if the cursor is in the body of the `AstStatWhile` + if (FFlag::DebugLuauWhileLocalAnalysis) + { + if (auto whileStat = node->as(); + whileStat && whileStat->conditionLocal && whileStat->body->location.containsClosed(cursorPos)) + { + localStack.push_back(whileStat->conditionLocal); + localMap[whileStat->conditionLocal->name] = whileStat->conditionLocal; + } + } } return {std::move(localMap), std::move(localStack), std::move(ancestry), region.nearestStatement, region.parentBlock, region.fragmentLocation}; diff --git a/Analysis/src/Frontend.cpp b/Analysis/src/Frontend.cpp index 3791ee8d5..44bcd5b17 100644 --- a/Analysis/src/Frontend.cpp +++ b/Analysis/src/Frontend.cpp @@ -2335,18 +2335,17 @@ ModulePtr check( std::unique_ptr cgraph = std::make_unique(builtinTypes); - CFG::CFGAllocator cfgAllocator; - std::unique_ptr cfg; - std::unique_ptr state; - if (FFlag::DebugLuauCFG && mode != Mode::Definition) + CFGAllocator cfgAllocator; + std::unique_ptr cfg; + std::unique_ptr state; + if (FFlag::DebugLuauCFG) { - cfg = CFG::CFGBuilder::makeCFG(NotNull{&cfgAllocator}, sourceModule.root); + cfg = CFGBuilder::makeCFG(NotNull{&cfgAllocator}, sourceModule.root); if (FFlag::DebugLuauLogCFG) printf("%s", dumpCFG(*cfg).c_str()); if (FFlag::DebugLuauDumpCFGJson) printf("%s\n", dumpCFGJson(*cfg).c_str()); - state = - std::make_unique(NotNull{module->internalTypes.get()}, NotNull{parentScope.get()}, builtinTypes, NotNull{cfg.get()}); + state = std::make_unique(NotNull{module->internalTypes.get()}, NotNull{parentScope.get()}, builtinTypes, NotNull{cfg.get()}); state->computeTypes(); } diff --git a/Analysis/src/Normalize.cpp b/Analysis/src/Normalize.cpp index f065e7a78..a4dd3177a 100644 --- a/Analysis/src/Normalize.cpp +++ b/Analysis/src/Normalize.cpp @@ -22,8 +22,8 @@ LUAU_FASTINTVARIABLE(LuauNormalizerInitialFuel, 3000) LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAGVARIABLE(LuauRefactorStringSemanticSubtyping) -LUAU_FASTFLAGVARIABLE(LuauNormalizeGuardAgainstNonTestableNegations) LUAU_FASTFLAGVARIABLE(LuauFixNormalizeFunctionIntersections) +LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) namespace Luau { @@ -1849,7 +1849,7 @@ NormalizationResult Normalizer::intersectNormalWithNegationTy(TypeId toNegate, N std::shared_ptr normal = normalize(toNegate); - if (FFlag::LuauNormalizeGuardAgainstNonTestableNegations && !normal) + if (!normal) return NormalizationResult::False; negated = negateNormal(*normal); @@ -1860,6 +1860,26 @@ NormalizationResult Normalizer::intersectNormalWithNegationTy(TypeId toNegate, N return NormalizationResult::True; } +NormalizationResult Normalizer::unionNormalWithNegationTy(NormalizedType& here, TypeId there) +{ + consumeFuel(); + + std::optional negated; + + std::shared_ptr normal = normalize(there); + + if (!normal) + return NormalizationResult::False; + + negated = negateNormal(*normal); + + if (!negated) + return NormalizationResult::False; + + unionNormals(here, *negated); + return NormalizationResult::True; +} + // See above for an explanation of `ignoreSmallerTyvars`. NormalizationResult Normalizer::unionNormalWithTy( NormalizedType& here, @@ -4020,10 +4040,24 @@ NormalizationResult Normalizer::intersectNormalWithTy( here.tyvars = std::move(tyvars); return intersectNormalWithTy(here, nt->ty, seenTablePropPairs, seenSetTypes); } + else if (auto itv = get(t); FFlag::LuauDecomposeIntersectionOfFreeType && itv) + { + // ~(A & B & C) => ~A | ~B | ~C + NormalizedType thereNorm{builtinTypes}; + for (auto part : itv) + { + if (auto res = unionNormalWithNegationTy(thereNorm, part); shouldEarlyExit(res)) + return res; + } + + if (auto res = intersectNormals(here, thereNorm); shouldEarlyExit(res)) + return res; + } else { - // TODO negated unions, intersections, table, and function. - // Report a TypeError for other types. + // TODO(CLI-234319): The rest of the types here (explicit tables + // and functions) are not negateable, so we probably should claim + // normalizing them fails. LUAU_ASSERT(!"Unimplemented"); } } diff --git a/Analysis/src/OverloadResolver.cpp b/Analysis/src/OverloadResolver.cpp index 18896ceaf..cb5f01ed6 100644 --- a/Analysis/src/OverloadResolver.cpp +++ b/Analysis/src/OverloadResolver.cpp @@ -14,57 +14,110 @@ LUAU_FASTFLAG(LuauFixCallMetamethodErrorReporting) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) +LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) namespace Luau { SelectedOverload OverloadResolution::getUnambiguousOverload() const { - if (ok.size() == 1 && potentialOverloads.size() == 0) + if (FFlag::LuauOneBitAssumedConstraintTracking) { - // Unambiguously: there is exactly one overload that matches - // without dispatching any more constraints. - return { - ok.front(), - {}, - false, - }; - } + if (ok.size() == 1 && potentialOverloads.size() == 0) + { + // Unambiguously: there is exactly one overload that matches + // without dispatching any more constraints. + return { + ok.front(), + {}, + false, + }; + } - if (ok.size() == 0 && potentialOverloads.size() == 1) - { - // Unambiguously: there are _no_ overloads that match without - // dispatching constraints, but there's exactly one that does - // match without dispatching constraints. - return {potentialOverloads.front().first, potentialOverloads.front().second, false}; - } + if (ok.size() == 0 && potentialOverloads.size() == 1) + { + // Unambiguously: there are _no_ overloads that match without + // dispatching constraints, but there's exactly one that does + // match without dispatching constraints. + return {potentialOverloads.front(), {}, false}; + } - if (ok.size() > 1) - { - // FIXME CLI-180645: We should try to infer a union of return - // types here so that we get better autocomplete / type - // inference for the rest of the function. - return {std::nullopt, {}, false}; - } + if (ok.size() > 1) + { + // FIXME CLI-180645: We should try to infer a union of return + // types here so that we get better autocomplete / type + // inference for the rest of the function. + return {std::nullopt, {}, false}; + } - if (potentialOverloads.size() + ok.size() > 1) - { - // This is a first case of "ambiguous" overloads: we have at least - // one overload that matches without constraints, and one that matches - // with extra constraints. - // - // This is the one spot where we return `true`, which callers may use - // to determine whether they should emit an error or try again later. - if (ok.empty()) - return {potentialOverloads.front().first, potentialOverloads.front().second, true}; - else + if (potentialOverloads.size() + ok.size() > 1) { - LUAU_ASSERT(ok.size() == 1); - return {ok.front(), {}, true}; + // This is a first case of "ambiguous" overloads: we have at least + // one overload that matches without constraints, and one that matches + // with extra constraints. + // + // This is the one spot where we return `true`, which callers may use + // to determine whether they should emit an error or try again later. + if (ok.empty()) + return {potentialOverloads.front(), {}, true}; + else + { + LUAU_ASSERT(ok.size() == 1); + return {ok.front(), {}, true}; + } } + + LUAU_ASSERT(potentialOverloads.size() + ok.size() == 0); } + else + { + + if (ok.size() == 1 && potentialOverloads_DEPRECATED.size() == 0) + { + // Unambiguously: there is exactly one overload that matches + // without dispatching any more constraints. + return { + ok.front(), + {}, + false, + }; + } + + if (ok.size() == 0 && potentialOverloads_DEPRECATED.size() == 1) + { + // Unambiguously: there are _no_ overloads that match without + // dispatching constraints, but there's exactly one that does + // match without dispatching constraints. + return {potentialOverloads_DEPRECATED.front().first, potentialOverloads_DEPRECATED.front().second, false}; + } + + if (ok.size() > 1) + { + // FIXME CLI-180645: We should try to infer a union of return + // types here so that we get better autocomplete / type + // inference for the rest of the function. + return {std::nullopt, {}, false}; + } + + if (potentialOverloads_DEPRECATED.size() + ok.size() > 1) + { + // This is a first case of "ambiguous" overloads: we have at least + // one overload that matches without constraints, and one that matches + // with extra constraints. + // + // This is the one spot where we return `true`, which callers may use + // to determine whether they should emit an error or try again later. + if (ok.empty()) + return {potentialOverloads_DEPRECATED.front().first, potentialOverloads_DEPRECATED.front().second, true}; + else + { + LUAU_ASSERT(ok.size() == 1); + return {ok.front(), {}, true}; + } + } - LUAU_ASSERT(potentialOverloads.size() + ok.size() == 0); + LUAU_ASSERT(potentialOverloads_DEPRECATED.size() + ok.size() == 0); + } // In this case, no overloads are valid. Let's try to pick the one that // will cause us to report the most legible errors. @@ -179,7 +232,6 @@ OverloadResolution OverloadResolver::resolveOverload( TypeId ty, TypePackId argsPack, Location fnLocation, - NotNull> uniqueTypes, bool useFreeTypeBounds ) { @@ -190,10 +242,10 @@ OverloadResolution OverloadResolver::resolveOverload( if (auto it = get(ty)) { for (TypeId component : it) - testFunctionOrUnion(result, component, argsPack, fnLocation, uniqueTypes); + testFunctionOrUnion(result, component, argsPack, fnLocation); } else - testFunctionOrUnion(result, ty, argsPack, fnLocation, uniqueTypes); + testFunctionOrUnion(result, ty, argsPack, fnLocation); return result; } @@ -495,8 +547,7 @@ void OverloadResolver::testFunction( OverloadResolution& result, TypeId fnTy, TypePackId argsPack, - Location fnLocation, - NotNull> uniqueTypes + Location fnLocation ) { fnTy = follow(fnTy); @@ -504,15 +555,29 @@ void OverloadResolver::testFunction( // TODO: This seems like the wrong spot to do this check. if (is(fnTy)) { - std::vector constraints; // TODO. Luckily, these constraints are not yet used. - result.potentialOverloads.emplace_back(fnTy, std::move(constraints)); + if (FFlag::LuauOneBitAssumedConstraintTracking) + { + result.potentialOverloads.emplace_back(fnTy); + } + else + { + std::vector constraints; // TODO. Luckily, these constraints are not yet used. + result.potentialOverloads_DEPRECATED.emplace_back(fnTy, std::move(constraints)); + } return; } if (auto tfit = get(fnTy); tfit && tfit->state == TypeFunctionInstanceState::Unsolved) { - std::vector constraints; // TODO. Luckily, these constraints are not yet used. - result.potentialOverloads.emplace_back(fnTy, std::move(constraints)); + if (FFlag::LuauOneBitAssumedConstraintTracking) + { + result.potentialOverloads.emplace_back(fnTy); + } + else + { + std::vector constraints; // TODO. Luckily, these constraints are not yet used. + result.potentialOverloads_DEPRECATED.emplace_back(fnTy, std::move(constraints)); + } return; } @@ -553,10 +618,20 @@ void OverloadResolver::testFunction( if (r.isSubtype) { - if (r.assumedConstraints.empty()) - result.ok.emplace_back(fnTy); + if (FFlag::LuauOneBitAssumedConstraintTracking) + { + if (!r.assumingConstraints) + result.ok.emplace_back(fnTy); + else + result.potentialOverloads.emplace_back(fnTy); + } else - result.potentialOverloads.emplace_back(fnTy, std::move(r.assumedConstraints)); + { + if (r.assumedConstraints_DEPRECATED.empty()) + result.ok.emplace_back(fnTy); + else + result.potentialOverloads_DEPRECATED.emplace_back(fnTy, std::move(r.assumedConstraints_DEPRECATED)); + } } else { @@ -573,10 +648,20 @@ void OverloadResolver::testFunction( // optional arguments. If the only reason subtyping // failed is because optional arguments were not provided, // then this overload is actually okay. - if (r.assumedConstraints.empty()) - result.ok.emplace_back(fnTy); + if (FFlag::LuauOneBitAssumedConstraintTracking) + { + if (!r.assumingConstraints) + result.ok.emplace_back(fnTy); + else + result.potentialOverloads.emplace_back(fnTy); + } else - result.potentialOverloads.emplace_back(fnTy, std::move(r.assumedConstraints)); + { + if (r.assumedConstraints_DEPRECATED.empty()) + result.ok.emplace_back(fnTy); + else + result.potentialOverloads_DEPRECATED.emplace_back(fnTy, std::move(r.assumedConstraints_DEPRECATED)); + } } else result.incompatibleOverloads.emplace_back(fnTy, std::move(r.reasoning)); @@ -587,8 +672,7 @@ void OverloadResolver::testFunctionOrUnion( OverloadResolution& result, TypeId fnTy, TypePackId argsPack, - Location fnLocation, - NotNull> uniqueTypes + Location fnLocation ) { LUAU_ASSERT(fnTy == follow(fnTy)); @@ -602,30 +686,46 @@ void OverloadResolver::testFunctionOrUnion( for (TypeId t : ut) { ++count; - testFunctionOrCallMetamethod(innerResult, t, argsPack, fnLocation, uniqueTypes); + testFunctionOrCallMetamethod(innerResult, t, argsPack, fnLocation); } - if (count == innerResult.ok.size()) + if (FFlag::LuauOneBitAssumedConstraintTracking) { - result.ok.emplace_back(fnTy); - } - else if (count == innerResult.ok.size() + innerResult.potentialOverloads.size()) - { - std::vector allConstraints; - for (const auto& [_t, constraints] : innerResult.potentialOverloads) - allConstraints.insert(allConstraints.end(), constraints.begin(), constraints.end()); - - result.potentialOverloads.emplace_back(fnTy, std::move(allConstraints)); + if (count == innerResult.ok.size()) + result.ok.emplace_back(fnTy); + else if (count == innerResult.ok.size() + innerResult.potentialOverloads.size()) + result.potentialOverloads.emplace_back(fnTy); + else + { + // FIXME CLI-234745: We should probably report something better here, but it's + // important for type checking that we include this. + result.incompatibleOverloads.emplace_back(fnTy, ErrorVec{{fnLocation, CannotCallNonFunction{fnTy}}}); + } } else { - // FIXME: We should probably report something better here, but it's - // important for type checking that we include this. - result.incompatibleOverloads.emplace_back(fnTy, ErrorVec{{fnLocation, CannotCallNonFunction{fnTy}}}); + if (count == innerResult.ok.size()) + { + result.ok.emplace_back(fnTy); + } + else if (count == innerResult.ok.size() + innerResult.potentialOverloads_DEPRECATED.size()) + { + std::vector allConstraints; + for (const auto& [_t, constraints] : innerResult.potentialOverloads_DEPRECATED) + allConstraints.insert(allConstraints.end(), constraints.begin(), constraints.end()); + + result.potentialOverloads_DEPRECATED.emplace_back(fnTy, std::move(allConstraints)); + } + else + { + // FIXME CLI-234745: We should probably report something better here, but it's + // important for type checking that we include this. + result.incompatibleOverloads.emplace_back(fnTy, ErrorVec{{fnLocation, CannotCallNonFunction{fnTy}}}); + } } } else - testFunctionOrCallMetamethod(result, fnTy, argsPack, fnLocation, uniqueTypes); + testFunctionOrCallMetamethod(result, fnTy, argsPack, fnLocation); } /* @@ -641,8 +741,7 @@ void OverloadResolver::testFunctionOrCallMetamethod( OverloadResolution& result, TypeId fnTy, TypePackId argsPack, - Location fnLocation, - NotNull> uniqueTypes + Location fnLocation ) { fnTy = follow(fnTy); @@ -666,7 +765,7 @@ void OverloadResolver::testFunctionOrCallMetamethod( if (fn && !isArityCompatible(argsPack, fn->argTypes, builtinTypes)) result.arityMismatches.emplace_back(component); else - testFunction(result, component, argsPack, fnLocation, uniqueTypes); + testFunction(result, component, argsPack, fnLocation); } return; } @@ -675,7 +774,7 @@ void OverloadResolver::testFunctionOrCallMetamethod( } // Handle non-metamethods and metamethods which aren't overloaded. - testFunction(result, fnTy, argsPack, fnLocation, uniqueTypes); + testFunction(result, fnTy, argsPack, fnLocation); } void OverloadResolver::maybeEmplaceError( diff --git a/Analysis/src/Simplify.cpp b/Analysis/src/Simplify.cpp index 48d5a7955..0f51c8977 100644 --- a/Analysis/src/Simplify.cpp +++ b/Analysis/src/Simplify.cpp @@ -18,7 +18,6 @@ LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_DYNAMIC_FASTINTVARIABLE(LuauSimplificationComplexityLimit, 8) LUAU_DYNAMIC_FASTINTVARIABLE(LuauTypeSimplificationIterationLimit, 128) -LUAU_FASTFLAGVARIABLE(LuauRelateIndexersTypo) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) namespace Luau @@ -407,16 +406,8 @@ Relation relateTables_DEPRECATED(const TableType* leftTable, const TableType* ri if (relate(leftTable->indexer->indexType, rightTable->indexer->indexType, seen) != Relation::Coincident) return Relation::Intersects; - if (FFlag::LuauRelateIndexersTypo) - { - if (relate(leftTable->indexer->indexResultType, rightTable->indexer->indexResultType, seen) != Relation::Coincident) - return Relation::Intersects; - } - else - { - if (relate(leftTable->indexer->indexType, rightTable->indexer->indexType, seen) != Relation::Coincident) - return Relation::Intersects; - } + if (relate(leftTable->indexer->indexResultType, rightTable->indexer->indexResultType, seen) != Relation::Coincident) + return Relation::Intersects; return hasSubset ? Relation::Subset : Relation::Coincident; } diff --git a/Analysis/src/Subtyping.cpp b/Analysis/src/Subtyping.cpp index bfdd21acc..597ab467d 100644 --- a/Analysis/src/Subtyping.cpp +++ b/Analysis/src/Subtyping.cpp @@ -28,6 +28,7 @@ LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAGVARIABLE(LuauSubtypingSkipUnreadReasoning) LUAU_FASTFLAGVARIABLE(LuauOnlyCheckWidthSubtypingForReadOnlyProperty) +LUAU_FASTFLAGVARIABLE(LuauOneBitAssumedConstraintTracking) namespace Luau @@ -232,7 +233,12 @@ SubtypingResult& SubtypingResult::andAlso(SubtypingResult other) isCacheable &= other.isCacheable; errors.insert(errors.end(), other.errors.begin(), other.errors.end()); genericBoundsMismatches.insert(genericBoundsMismatches.end(), other.genericBoundsMismatches.begin(), other.genericBoundsMismatches.end()); - assumedConstraints.insert(assumedConstraints.end(), other.assumedConstraints.begin(), other.assumedConstraints.end()); + if (FFlag::LuauOneBitAssumedConstraintTracking) + assumingConstraints |= other.assumingConstraints; + else + assumedConstraints_DEPRECATED.insert( + assumedConstraints_DEPRECATED.end(), other.assumedConstraints_DEPRECATED.begin(), other.assumedConstraints_DEPRECATED.end() + ); return *this; } @@ -248,7 +254,10 @@ SubtypingResult& SubtypingResult::orElse(SubtypingResult other) if (other.isSubtype) { reasoning.clear(); - assumedConstraints = std::move(other.assumedConstraints); + if (FFlag::LuauOneBitAssumedConstraintTracking) + assumingConstraints = other.assumingConstraints; + else + assumedConstraints_DEPRECATED = std::move(other.assumedConstraints_DEPRECATED); } else { @@ -258,10 +267,13 @@ SubtypingResult& SubtypingResult::orElse(SubtypingResult other) } else if (other.isSubtype) { - // If the other result has assumed constraints, we drop ours (given - // we represent a failed subtype) and then take the constraints of - // the other check. - assumedConstraints = std::move(other.assumedConstraints); + if (FFlag::LuauOneBitAssumedConstraintTracking) + assumingConstraints = assumingConstraints && other.assumingConstraints; + else + // If the other result has assumed constraints, we drop ours (given + // we represent a failed subtype) and then take the constraints of + // the other check. + assumedConstraints_DEPRECATED = std::move(other.assumedConstraints_DEPRECATED); } isSubtype |= other.isSubtype; @@ -408,7 +420,10 @@ std::string explainPropertyModifierViolation(const Path& subPath) SubtypingResult& SubtypingResult::withAssumedConstraint(ConstraintV constraint) { - assumedConstraints.push_back(std::move(constraint)); + if (FFlag::LuauOneBitAssumedConstraintTracking) + assumingConstraints = true; + else + assumedConstraints_DEPRECATED.push_back(std::move(constraint)); return *this; } @@ -788,7 +803,10 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, TypeId sub // Any two free types are potentially subtypes of one another because // both of them could be narrowed to never. result = {true}; - result.assumedConstraints.emplace_back(SubtypeConstraint{subTy, superTy}); + if (FFlag::LuauOneBitAssumedConstraintTracking) + result.assumingConstraints = true; + else + result.assumedConstraints_DEPRECATED.emplace_back(SubtypeConstraint{subTy, superTy}); } else if (auto superFree = get(superTy)) { @@ -805,7 +823,12 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, TypeId sub result = isCovariantWith(env, subTy, superFree->upperBound, scope); if (result.isSubtype) - result.assumedConstraints.emplace_back(SubtypeConstraint{subTy, superTy}); + { + if (FFlag::LuauOneBitAssumedConstraintTracking) + result.assumingConstraints = true; + else + result.assumedConstraints_DEPRECATED.emplace_back(SubtypeConstraint{subTy, superTy}); + } } else if (auto subFree = get(subTy)) { @@ -829,7 +852,10 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, TypeId sub if (isCovariantWith(env, subFree->lowerBound, superTy, scope).isSubtype) { result = {true}; - result.assumedConstraints.emplace_back(SubtypeConstraint{subTy, superTy}); + if (FFlag::LuauOneBitAssumedConstraintTracking) + result.assumingConstraints = true; + else + result.assumedConstraints_DEPRECATED.emplace_back(SubtypeConstraint{subTy, superTy}); } else result = {false}; @@ -837,7 +863,10 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, TypeId sub else if ((is(subTy) || is(superTy))) { result = {true}; - result.assumedConstraints.emplace_back(SubtypeConstraint{subTy, superTy}); + if (FFlag::LuauOneBitAssumedConstraintTracking) + result.assumingConstraints = true; + else + result.assumedConstraints_DEPRECATED.emplace_back(SubtypeConstraint{subTy, superTy}); } // TODO: These branches are entirely incorrect. We should never consider // generic types to "always" be a sub type or super type of another type @@ -974,9 +1003,7 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, TypeId sub result = isCovariantWith(env, p, scope); else if (auto p = get2(subTy, superTy)) { - const bool forceCovariantTest = false; - result = isCovariantWith(env, p.first, p.second, forceCovariantTest, scope); - + result = isCovariantWith(env, p.first, p.second, scope); bool tableIsMutable = p.first->state != TableState::Sealed; if (FFlag::DebugLuauExactTableTypes && p.first->state == TableState::Exact) tableIsMutable = false; @@ -992,7 +1019,10 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, TypeId sub // {| ... |} <: { [A]: B ... } // // Then add an assumed constraint stating such. - result.assumedConstraints.emplace_back(SubtypeConstraint{subTy, superTy}); + if (FFlag::LuauOneBitAssumedConstraintTracking) + result.assumingConstraints = true; + else + result.assumedConstraints_DEPRECATED.emplace_back(SubtypeConstraint{subTy, superTy}); } } else if (auto p = get2(subTy, superTy)) @@ -2040,15 +2070,11 @@ SubtypingResult Subtyping::isCovariantWith( SubtypingEnvironment& env, const TableType* subTable, const TableType* superTable, - bool forceCovariantTest, NotNull scope ) { SubtypingResult result{true}; - // Either this flag is off or `forceCovariantTest` is false. - LUAU_ASSERT(!forceCovariantTest); - if (subTable->props.empty() && !subTable->indexer && subTable->state == TableState::Sealed && superTable->indexer) { // While it is certainly the case that {} props.find(name); subIter != subTable->props.end()) { - record(isCovariantWith(env, subIter->second, superProp, name, forceCovariantTest, scope)); + record(isCovariantWith(env, subIter->second, superProp, name, scope)); } // Otherwise, if the sub table has an indexer where the key type is a // super type of string, then use that as the "property" type, e.g. @@ -2162,7 +2188,7 @@ SubtypingResult Subtyping::isCovariantWith( // *exactly* `unknown` (or `any`). In any other case // subtyping will fail. if (superProp.isReadOnly()) - result = isCovariantWith(env, Property::readonly(builtinTypes->unknownType), superProp, name, forceCovariantTest, scope); + result = isCovariantWith(env, Property::readonly(builtinTypes->unknownType), superProp, name, scope); else result = { false }; } @@ -2170,14 +2196,11 @@ SubtypingResult Subtyping::isCovariantWith( { if (FFlag::LuauImproveUniqueTableWidthSubtyping) { - if (forceCovariantTest) - result = isCovariantWith(env, Property::rw(builtinTypes->nilType), superProp, name, forceCovariantTest, scope); - else - result = isCovariantWith(env, Property::readonly(builtinTypes->nilType), superProp, name, forceCovariantTest, scope); + result = isCovariantWith(env, Property::readonly(builtinTypes->nilType), superProp, name, scope); } else { - result = isCovariantWith(env, Property::readonly(builtinTypes->nilType), superProp, name, forceCovariantTest, scope); + result = isCovariantWith(env, Property::readonly(builtinTypes->nilType), superProp, name, scope); } } @@ -2243,7 +2266,7 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, const Meta { auto doDefault = [&]() { - return isCovariantWith(env, subTable, superTable, /* forceCovariantTest */ false, scope); + return isCovariantWith(env, subTable, superTable, scope); }; // My kingdom for `do` notation. @@ -2318,7 +2341,7 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, const Meta if (prop.readTy && fauxSubTable.props.find(name) == fauxSubTable.props.end()) fauxSubTable.props[name] = Property::readonly(*prop.readTy); } - return isCovariantWith(env, &fauxSubTable, superTable, /* forceCovariantTest */ false, scope); + return isCovariantWith(env, &fauxSubTable, superTable, scope); } else { @@ -2377,7 +2400,7 @@ SubtypingResult Subtyping::isCovariantWith( { if (auto classProp = lookupExternTypeProp(subExternType, name)) { - result.andAlso(isCovariantWith(env, *classProp, prop, name, /*forceCovariantTest*/ false, scope)); + result.andAlso(isCovariantWith(env, *classProp, prop, name, scope)); } else { @@ -2561,7 +2584,7 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, const Prim if (auto stringTable = get(*it->second.readTy)) { - result.orElse(isCovariantWith(env, stringTable, superTable, /*forceCovariantTest*/ false, scope) + result.orElse(isCovariantWith(env, stringTable, superTable, scope) .withSubPath(TypePath::PathBuilder().mt().readProp("__index").build())); } } @@ -2602,7 +2625,7 @@ SubtypingResult Subtyping::isCovariantWith( if (auto stringTable = get(*it->second.readTy)) { - result.orElse(isCovariantWith(env, stringTable, superTable, /*forceCovariantTest*/ false, scope) + result.orElse(isCovariantWith(env, stringTable, superTable, scope) .withSubPath(TypePath::PathBuilder().mt().readProp("__index").build())); } } @@ -2647,7 +2670,6 @@ SubtypingResult Subtyping::isCovariantWith( const Property& subProp, const Property& superProp, const std::string& name, - bool forceCovariantTest, NotNull scope ) { @@ -2655,16 +2677,13 @@ SubtypingResult Subtyping::isCovariantWith( if (superProp.isShared() && subProp.isShared()) { - if (forceCovariantTest) - res.andAlso(isCovariantWith(env, *subProp.readTy, *superProp.readTy, scope).withBothComponent(TypePath::Property::read(name))); - else - res.andAlso(isInvariantWith(env, *subProp.readTy, *superProp.readTy, scope).withBothComponent(TypePath::Property::read(name))); + res.andAlso(isInvariantWith(env, *subProp.readTy, *superProp.readTy, scope).withBothComponent(TypePath::Property::read(name))); } else { if (superProp.readTy.has_value() && subProp.readTy.has_value()) res.andAlso(isCovariantWith(env, *subProp.readTy, *superProp.readTy, scope).withBothComponent(TypePath::Property::read(name))); - if (superProp.writeTy.has_value() && subProp.writeTy.has_value() && !forceCovariantTest) + if (superProp.writeTy.has_value() && subProp.writeTy.has_value()) res.andAlso(isContravariantWith(env, *subProp.writeTy, *superProp.writeTy, scope).withBothComponent(TypePath::Property::write(name))); if (superProp.isReadWrite()) diff --git a/Analysis/src/TypeChecker2.cpp b/Analysis/src/TypeChecker2.cpp index 87e5ca90c..d3195967b 100644 --- a/Analysis/src/TypeChecker2.cpp +++ b/Analysis/src/TypeChecker2.cpp @@ -41,13 +41,14 @@ LUAU_FASTFLAGVARIABLE(LuauCheckFunctionStatementTypes) LUAU_FASTFLAG(LuauImproveUniqueTableWidthSubtyping) LUAU_FASTFLAGVARIABLE(LuauCallErrorReportingRecoversArgumentLocationsForPacks) LUAU_FASTFLAGVARIABLE(LuauCompoundAssignSeedsAstTypes) -LUAU_FASTFLAG(LuauNormalizeGuardAgainstNonTestableNegations) LUAU_FASTFLAGVARIABLE(LuauDontUseInnermostScope) LUAU_FASTFLAG(LuauTypeFunctionsAbsenceCache) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) +LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) +LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) namespace Luau { @@ -754,6 +755,14 @@ void TypeChecker2::visit(AstStatIf* ifStatement) void TypeChecker2::visit(AstStatWhile* whileStatement) { visit(whileStatement->condition, ValueContext::RValue); + + if (FFlag::DebugLuauWhileLocalAnalysis && whileStatement->conditionLocal && whileStatement->conditionLocal->annotation) + { + TypeId annotationType = lookupAnnotation(whileStatement->conditionLocal->annotation); + testPotentialLiteralIsSubtype(whileStatement->condition, annotationType); + visit(whileStatement->conditionLocal->annotation); + } + visit(whileStatement->body); } @@ -2197,14 +2206,20 @@ void TypeChecker2::visitCall(AstExprCall* call) limits, call->location, }; - DenseHashSet uniqueTypes; - findUniqueTypes(NotNull{&uniqueTypes}, argExprs, NotNull{&module->astTypes}); TypePackId argsPack = module->internalTypes->addTypePack(args); - const OverloadResolution result2 = resolver.resolveOverload(fnTy, argsPack, call->func->location, NotNull{&uniqueTypes}, false); + const OverloadResolution result2 = resolver.resolveOverload(fnTy, argsPack, call->func->location, false); - if (!result2.potentialOverloads.empty()) - reportError(InternalError{"Internal error: outstanding free or blocked type in function call"}, call->location); + if (FFlag::LuauOneBitAssumedConstraintTracking) + { + if (!result2.potentialOverloads.empty()) + reportError(InternalError{"Internal error: outstanding free or blocked type in function call"}, call->location); + } + else + { + if (!result2.potentialOverloads_DEPRECATED.empty()) + reportError(InternalError{"Internal error: outstanding free or blocked type in function call"}, call->location); + } /* * If one overload matches, stop. Nothing to report. @@ -2327,22 +2342,11 @@ void TypeChecker2::visitCall(AstExprCall* call) if (!result2.nonFunctions.empty()) { auto norm = normalizer.normalize(fnTy); - if (FFlag::LuauNormalizeGuardAgainstNonTestableNegations) - { - if (!norm || normalizer.isInhabited(norm.get()) == NormalizationResult::HitLimits) - reportError(NormalizationTooComplex{}, call->func->location); - // At this point norm is non-null and inhabited. - else if (!norm->shouldSuppressErrors()) - reportError(CannotCallNonFunction{fnTy}, call->func->location); - } - else - { - if (!norm || normalizer.isInhabited(norm.get()) == NormalizationResult::HitLimits) - reportError(NormalizationTooComplex{}, call->func->location); - // At this point norm is non-null and inhabited. - if (!norm->shouldSuppressErrors()) - reportError(CannotCallNonFunction{fnTy}, call->func->location); - } + if (!norm || normalizer.isInhabited(norm.get()) == NormalizationResult::HitLimits) + reportError(NormalizationTooComplex{}, call->func->location); + // At this point norm is non-null and inhabited. + else if (!norm->shouldSuppressErrors()) + reportError(CannotCallNonFunction{fnTy}, call->func->location); return; } } @@ -2795,7 +2799,7 @@ static bool isOkToCompare( if (NormalizationResult::False != typesHaveIntersection) return true; - if (FFlag::LuauNormalizeGuardAgainstNonTestableNegations && (!normLeft || !normRight)) + if (!normLeft || !normRight) return true; // We allow anything to be compared to nil. diff --git a/Analysis/src/TypeFunctionRuntime.cpp b/Analysis/src/TypeFunctionRuntime.cpp index dad947b30..12c37f412 100644 --- a/Analysis/src/TypeFunctionRuntime.cpp +++ b/Analysis/src/TypeFunctionRuntime.cpp @@ -28,7 +28,6 @@ LUAU_FASTINTVARIABLE(DebugLuauTypeFunctionRuntimeHeapLimit, 0) LUAU_DYNAMIC_FASTINT(LuauTypeFunctionSerdeIterationLimit) LUAU_FASTFLAG(LuauIntegerType2) -LUAU_FASTFLAGVARIABLE(LuauUdtfFixTypeNameTypo) LUAU_FASTFLAGVARIABLE(LuauUdtfTerseChunkNames) namespace Luau @@ -364,7 +363,7 @@ std::optional checkResultForError(lua_State* L, const char* t Location{}, RuntimeError{format("'%s' type function errored at runtime: %s", typeFunctionName, lua_tostring(L, -1))} }; - const char* tname = FFlag::LuauUdtfFixTypeNameTypo ? luaL_typename(L, -1) : lua_typename(L, -1); + const char* tname = luaL_typename(L, -1); return TypeFunctionError{ Location{}, RuntimeError{format("'%s' type function errored at runtime: raised an error of type %s", typeFunctionName, tname)} }; diff --git a/Analysis/src/TypeInfer.cpp b/Analysis/src/TypeInfer.cpp index ec92781a6..c557ed0a7 100644 --- a/Analysis/src/TypeInfer.cpp +++ b/Analysis/src/TypeInfer.cpp @@ -36,6 +36,7 @@ LUAU_FASTFLAG(LuauExportValueTypecheck) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAGVARIABLE(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) +LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) namespace Luau { @@ -717,7 +718,7 @@ WithPredicate TypeChecker::checkLocalBinding( std::optional expectedType ) { - LUAU_ASSERT(FFlag::LuauExperimentalIfLocalAnalysis); + LUAU_ASSERT(FFlag::LuauExperimentalIfLocalAnalysis || FFlag::DebugLuauWhileLocalAnalysis); LUAU_ASSERT(local); TypeId lhs = nullptr; @@ -796,9 +797,20 @@ ErrorVec TypeChecker::canUnify(TypePackId subTy, TypePackId superTy, const Scope ControlFlow TypeChecker::check(const ScopePtr& scope, const AstStatWhile& statement) { - WithPredicate result = checkExpr(scope, *statement.condition); + std::optional expectedType = std::nullopt; + if (FFlag::DebugLuauWhileLocalAnalysis && statement.conditionLocal && statement.conditionLocal->annotation) + expectedType.emplace(resolveType(scope, *statement.conditionLocal->annotation)); + + WithPredicate result = checkExpr(scope, *statement.condition, expectedType); ScopePtr whileScope = childScope(scope, statement.body->location); + + if (FFlag::DebugLuauWhileLocalAnalysis && statement.conditionLocal != nullptr) + { + WithPredicate bindingPred = checkLocalBinding(scope, whileScope, statement.conditionLocal, result, expectedType); + resolve(bindingPred.predicates, whileScope, true); + } + resolve(result.predicates, whileScope, true); check(whileScope, *statement.body); diff --git a/Analysis/src/TypeStateMap.cpp b/Analysis/src/TypeStateMap.cpp index 2ef5acf5f..9431221c6 100644 --- a/Analysis/src/TypeStateMap.cpp +++ b/Analysis/src/TypeStateMap.cpp @@ -7,13 +7,17 @@ #include "Luau/Type.h" #include "Luau/TypeArena.h" #include "Luau/BuiltinTypeFunctions.h" +#include "Luau/TypeFunction.h" #include "Luau/TypeUtils.h" -#include +#include "Luau/ToString.h" +#include "Luau/Variant.h" +#include "Luau/DumpCFG.h" +#include LUAU_FASTINTVARIABLE(LuauMaxCFGDataflowIterations, 2); - -namespace Luau::CFG +LUAU_FASTFLAG(DebugLuauLogCFG) +namespace Luau { TypeStateMap::TypeStateMap(NotNull arena, NotNull globalScope, NotNull builtinTypes, NotNull g) @@ -24,29 +28,71 @@ TypeStateMap::TypeStateMap(NotNull arena, NotNull globalScope, { } +std::vector TypeStateMap::flushConstraintsRequiringFinalization() +{ + std::vector allConstraints; + for (auto& [ty, constraints] : typesRequiringConstraints) + { + for (auto& cv : constraints) + allConstraints.emplace_back(std::move(cv)); + } + typesRequiringConstraints.clear(); + return allConstraints; +} + TypeId TypeStateMap::getRHSType(AstExpr* expr) { if (Definition* def = g->getUseDef(expr)) - return getType(def); + return getType(NotNull{def}); return builtinTypes->errorType; } -TypeId TypeStateMap::getLHSType(const LValue& lv) const +TypeId TypeStateMap::getDomain(Symbol sym) const { - if (Definition* def = g->getLhsDef(lv)) - return getType(def); + if (auto domain = lvalueDomain.find(sym)) + return *domain; return builtinTypes->anyType; } -std::optional TypeStateMap::getOptionalConstraint(TypeId ty) const +void TypeStateMap::expandDomain(const LHS& lv, TypeId rhs) +{ + Definition* def = g->getLhsDef(lv); + if (!def) + return; + + SSAId ssa = NotNull{def}; + TypeId* stateTy = defTypes.find(ssa); + if (!stateTy) + { + LUAU_ASSERT(!"Couldn't find type for LHS definition - TypeStateMap was not fully populated"); + return; + } + + TypeId followedStateTy = follow(*stateTy); + if (auto bt = get(followedStateTy)) + { + if (bt->getOwner() != nullptr) + { + LUAU_ASSERT(!"Expected the blocked type having it's domain expanded to have no owner - this means it came from somewhere outside the " + "typestate map"); + return; + } + + + emplaceType(asMutable(followedStateTy), rhs); + } +} + +std::vector TypeStateMap::getConstraints(TypeId ty) const { - if (auto cv = typesRequiringConstraint.find(ty)) - return {*cv}; - return std::nullopt; + if (auto constraints = typesRequiringConstraints.find(ty)) + return *constraints; + return {}; } -TypeId TypeStateMap::getType(Definition* def) const +TypeId TypeStateMap::getType(SSAId def) const { + LUAU_ASSERT(def->materialize() == def); if (auto ty = defTypes.find(def)) return *ty; else @@ -56,6 +102,20 @@ TypeId TypeStateMap::getType(Definition* def) const } } +void TypeStateMap::addConstraintForType(TypeId ty, ConstraintV&& constraint) +{ + std::vector& constraints = typesRequiringConstraints[ty]; + constraints.emplace_back(std::move(constraint)); +} + +TypeId TypeStateMap::newBlockedType(SSAId d) +{ + TypeId t = arena->addType(BlockedType{}); + if (FFlag::DebugLuauLogCFG) + printf("%s -> %s\n", d->versionedName().c_str(), toString(t).c_str()); + return t; +} + void TypeStateMap::computeTypes() { for (int iter = 0; iter < FInt::LuauMaxCFGDataflowIterations; iter++) @@ -66,46 +126,133 @@ void TypeStateMap::computeTypes() handleInstruction(inst); } } + + if (FFlag::DebugLuauLogCFG) + { + fprintf(stderr, "=== TypeStateMap: def -> type assignments ===\n"); + for (const auto& [def, ty] : defTypes) + { + TypeId followed = follow(ty); + fprintf(stderr, " %s -> %s\n", def->versionedName().c_str(), toString(followed).c_str()); + } + fprintf(stderr, "=== end TypeStateMap ===\n"); + } } -void TypeStateMap::handleInstruction(InstrId id) +void TypeStateMap::finalizeDomains() +{ + for (const auto& [domain, states] : domainStates) + { + UnionBuilder ub{arena, builtinTypes}; + ub.reserve(states.size()); + + for (const auto& state : states) + ub.add(state.second); + + TypeId domainTy = follow(domain); + if (get(domainTy)) + emplaceType(asMutable(domainTy), ub.build()); + + addConstraintForType(domain, SimplifyConstraint{domain}); + } +} + +void TypeStateMap::handleInstruction(InstructionId id) { visit( overloaded{ - [&](const Dead&) {}, + [&](const Dead&) + { + LUAU_ASSERT(!"Impossible - dead instructions cannot exist in a well formed CFG"); + }, [&](const Declare& decl) { - if (defTypes.find(decl.def.get())) + if (defTypes.find(decl.def)) + return; + TypeId rvalue = newBlockedType(decl.def); + defTypes[decl.def] = rvalue; + + TypeId domainPlaceholder = arena->addType(BlockedType{}); + lvalueDomain[decl.def->getSym()] = domainPlaceholder; + domainStates[domainPlaceholder][decl.def] = rvalue; + }, + [&](const GlobalFunction& fn) + { + return; + }, + [&](const LocalFunction& fn) + { + if (defTypes.find(fn.def)) + return; + + // A local function introduces the domain of its name but no rhs type: + // the function's type is produced by the ConstraintGenerator, which owns + // and binds this domain placeholder. Because there is no rhs state to + // union over, we skip domainStates so finalizeDomains leaves the + // placeholder blocked for the ConstraintGenerator to resolve. + TypeId domainPlaceholder = arena->addType(BlockedType{}); + lvalueDomain[fn.def->getSym()] = domainPlaceholder; + defTypes[fn.def] = domainPlaceholder; + }, + [&](const Arg& arg) + { + if (defTypes.find(arg.def)) + return; + // A parameter behaves like a Declare (mutable local with a domain), but + // its initial value has no rhs expression - the ConstraintGenerator binds + // this blocked type to the signature's argument type. + TypeId argValue = newBlockedType(arg.def); + defTypes[arg.def] = argValue; + + TypeId domainPlaceholder = arena->addType(BlockedType{}); + lvalueDomain[arg.def->getSym()] = domainPlaceholder; + domainStates[domainPlaceholder][arg.def] = argValue; + }, + [&](const Upvalue& upval) + { + // When a def is sourced as a capture, it does not participate in type stating. + // Instead, it obtains the same type as its domain. + // Future reads/writes that kill this def will cause the typestate to change + if (defTypes.find(upval.def)) return; - defTypes[decl.def.get()] = arena->addType(BlockedType{}); + if (auto t = lvalueDomain.find(upval.s)) + { + defTypes[upval.def] = *t; + } }, [&](const Assign& assign) { - if (defTypes.find(assign.def.get())) + if (defTypes.find(assign.def)) return; - defTypes[assign.def.get()] = arena->addType(BlockedType{}); + TypeId rvalue = newBlockedType(assign.def); + defTypes[assign.def] = rvalue; + + // Assignment instructions extend the domain we observe + if (auto* domainPlaceholder = lvalueDomain.find(assign.def->getSym())) + domainStates[*domainPlaceholder][assign.def] = rvalue; }, [&](const Refine& refine) { if (defTypes.find(refine.definition)) return; - if (auto ty = defTypes.find(refine.toRefine)) + if (auto ty = defTypes.find(refine.target)) { - auto dt = getDiscriminantOf(refine); + auto dt = getDiscriminantOf(refine.constraint); TypeId result = arena->addTypeFunction(builtinTypes->typeFunctions->refineFunc, {*ty, dt}, {}); defTypes[refine.definition] = result; - typesRequiringConstraint[result] = ReduceConstraint{result}; + addConstraintForType(result, ReduceConstraint{result}); } else { - fprintf(stderr, "Refine: could not find type for def '%s'\n", refine.toRefine->versionedName().c_str()); + fprintf(stderr, "Refine: could not find type for def '%s'\n", refine.target->versionedName().c_str()); LUAU_ASSERT(false); } }, + [&](const Join& join) { - auto existingTy = defTypes.find(join.definition.get()); + auto existingTy = defTypes.find(join.definition); // We resolved a type for this join instruction on the first pass so there is nothing to do here if (existingTy && !get(*existingTy)) return; @@ -115,8 +262,7 @@ void TypeStateMap::handleInstruction(InstrId id) bool missingOp = false; for (const auto& op : join.operands) { - Definition* resolved = g->resolve(op); - if (auto opTy = defTypes.find(resolved)) + if (auto opTy = defTypes.find(NotNull{op})) operands.emplace_back(*opTy); else { @@ -127,7 +273,7 @@ void TypeStateMap::handleInstruction(InstrId id) if (missingOp) { - defTypes[join.definition.get()] = arena->addType(BlockedType{}); + defTypes[join.definition] = newBlockedType(join.definition); return; } @@ -145,73 +291,184 @@ void TypeStateMap::handleInstruction(InstrId id) if (existingTy) emplaceType(asMutable(*existingTy), result); else - defTypes[join.definition.get()] = result; + defTypes[join.definition] = result; auto typeToConstrain = existingTy ? *existingTy : result; - typesRequiringConstraint[typeToConstrain] = SimplifyConstraint{typeToConstrain}; - } - }, + + addConstraintForType(typeToConstrain, SimplifyConstraint{typeToConstrain}); + }, + } // namespace Luau + , *id.get() ); } -TypeId TypeStateMap::getDiscriminantOf(const Refine& refine) +TypeId TypeStateMap::getDiscriminantOf(const NarrowingConstraint& constraint) { - if (!refine.type.has_value()) - return refine.sense ? builtinTypes->truthyType : builtinTypes->falsyType; - - LUAU_ASSERT(refine.type.has_value()); - const std::string& name = *refine.type; - - TypeId discriminantTy = builtinTypes->neverType; - if (name == "nil") - discriminantTy = builtinTypes->nilType; - else if (name == "string") - discriminantTy = builtinTypes->stringType; - else if (name == "number") - discriminantTy = builtinTypes->numberType; - else if (name == "integer") - discriminantTy = builtinTypes->integerType; - else if (name == "boolean") - discriminantTy = builtinTypes->booleanType; - else if (name == "thread") - discriminantTy = builtinTypes->threadType; - else if (name == "buffer") - discriminantTy = builtinTypes->bufferType; - else if (name == "table") - discriminantTy = builtinTypes->tableType; - else if (name == "function") - discriminantTy = builtinTypes->functionType; - else if (name == "userdata") + auto getDiscriminant = [&](std::string_view name, bool isTypeOf, bool sense) -> TypeId { - // typeof("userdata") collapses to the extern-type root; the precise - // class hierarchy is irrelevant for the purposes of refinement. - discriminantTy = builtinTypes->externType; - } - else if (auto typeFun = globalScope->lookupType(name); typeFun && typeFun->typeParams.empty() && typeFun->typePackParams.empty()) - { - TypeId ty = follow(typeFun->type); + TypeId discriminantTy = builtinTypes->neverType; + if (name == "nil") + discriminantTy = builtinTypes->nilType; + else if (name == "string") + discriminantTy = builtinTypes->stringType; + else if (name == "number") + discriminantTy = builtinTypes->numberType; + else if (name == "integer") + discriminantTy = builtinTypes->integerType; + else if (name == "boolean") + discriminantTy = builtinTypes->booleanType; + else if (name == "thread") + discriminantTy = builtinTypes->threadType; + else if (name == "buffer") + discriminantTy = builtinTypes->bufferType; + else if (name == "table") + discriminantTy = builtinTypes->tableType; + else if (name == "function") + discriminantTy = builtinTypes->functionType; + else if (name == "userdata") + { + discriminantTy = builtinTypes->externType; + } + else if (name == "vector" && !isTypeOf) + { + // `vector` is defined in EmbeddedBuiltinDefinitions, not as an actual built-in type + if (auto typeFun = globalScope->lookupType("vector")) + discriminantTy = follow(typeFun->type); + } + else if (!isTypeOf) + discriminantTy = builtinTypes->neverType; + else if (auto typeFun = globalScope->lookupType(std::string(name)); typeFun && typeFun->typeParams.empty() && typeFun->typePackParams.empty()) + { + TypeId ty = follow(typeFun->type); - // Only accept the root of an extern-type chain (or anything tagged as a - // typeof root). Anything else stays `never` and produces an empty - // refinement. - if (auto etv = get(ty); etv && (etv->parent == builtinTypes->externType || hasTag(ty, kTypeofRootTag))) - discriminantTy = ty; - } + // Only accept the root of an extern-type chain (or anything tagged as a + // typeof root). Anything else stays `never` and produces an empty + // refinement. + if (auto etv = get(ty); etv && (etv->parent == builtinTypes->externType || hasTag(ty, kTypeofRootTag))) + discriminantTy = ty; + } - // sense=false flips the proposition: the branch is taken when the def is - // *not* of `discriminantTy`, so the discriminant we feed to refine<...> is - // the negation. - if (!refine.sense) + // sense=false flips the proposition: the branch is taken when the def is + // *not* of `discriminantTy`, so the discriminant we feed to refine<...> is + // the negation. + if (!sense) + { + if (auto nt = get(discriminantTy)) + discriminantTy = nt->ty; + // Avoids allocating a new negation + else if (discriminantTy == builtinTypes->falsyType) + discriminantTy = builtinTypes->truthyType; + else + discriminantTy = arena->addType(NegationType{discriminantTy}); + } + + return discriminantTy; + }; + + auto getSingletonDiscriminant = [&](const SingletonValue& value, bool sense) -> TypeId { - if (auto nt = get(discriminantTy)) - discriminantTy = nt->ty; - else + TypeId discriminantTy = Luau::visit( + overloaded{ + [&](const StringSingletonValue& stringValue) -> TypeId + { + return arena->addType(SingletonType{StringSingleton{stringValue.value}}); + }, + [&](const BooleanSingletonValue& booleanValue) -> TypeId + { + return arena->addType(SingletonType{BooleanSingleton{booleanValue.value}}); + }, + [&](const NilSingletonValue& nilValue) -> TypeId + { + return builtinTypes->nilType; + }, + }, + value + ); + + if (!sense) discriminantTy = arena->addType(NegationType{discriminantTy}); - } + return discriminantTy; + }; + + TypeId disc = Luau::visit( + overloaded{ + + [&](const Truthy&) -> TypeId + { + return builtinTypes->truthyType; + }, + [&](const Falsy&) -> TypeId + { + return builtinTypes->falsyType; + }, + [&](const TypeEq& eq) -> TypeId + { + return getDiscriminant(eq.type, eq.isTypeOf, true); + }, + [&](const TypeNeq& neq) -> TypeId + { + return getDiscriminant(neq.type, neq.isTypeOf, false); + }, + [&](const SingletonEq& eq) -> TypeId + { + return getSingletonDiscriminant(eq.v, true); + }, + [&](const SingletonNeq& neq) -> TypeId + { + return getSingletonDiscriminant(neq.v, false); + }, + [&](const HasShape& hs) -> TypeId + { + // Resolve the leaf constraint to a discriminant type + TypeId leafDisc = Luau::visit( + overloaded{ + [&](const Truthy&) -> TypeId + { + return builtinTypes->truthyType; + }, + [&](const Falsy&) -> TypeId + { + return builtinTypes->falsyType; + }, + [&](const TypeEq& eq) -> TypeId + { + return getDiscriminant(eq.type, eq.isTypeOf, true); + }, + [&](const TypeNeq& neq) -> TypeId + { + return getDiscriminant(neq.type, neq.isTypeOf, false); + }, + [&](const SingletonEq& eq) -> TypeId + { + return getSingletonDiscriminant(eq.v, true); + }, + [&](const SingletonNeq& neq) -> TypeId + { + return getSingletonDiscriminant(neq.v, false); + }, + }, + hs.constraint + ); + + // Build nested table type inside-out: {path[n-1]: {... {path[0]: leafDisc}}} + TypeId inner = leafDisc; + for (auto it = hs.path.rbegin(); it != hs.path.rend(); ++it) + { + TypeId tab = arena->addType(TableType{}); + TableType* tt = getMutable(tab); + tt->state = TableState::Sealed; + tt->props[*it] = Property::readonly(inner); + inner = tab; + } + return inner; + }, + }, + constraint + ); - return discriminantTy; + return disc; } -} // namespace Luau::CFG +} // namespace Luau diff --git a/Analysis/src/Unifier2.cpp b/Analysis/src/Unifier2.cpp index c8e4e3960..12dc34aae 100644 --- a/Analysis/src/Unifier2.cpp +++ b/Analysis/src/Unifier2.cpp @@ -26,7 +26,9 @@ LUAU_DYNAMIC_FASTINTVARIABLE(LuauUnifierRecursionLimit, 100) LUAU_FASTFLAGVARIABLE(LuauDoNotLeakGenericsInIndexer) LUAU_FASTFLAGVARIABLE(LuauInferReadOnlyIndexers) +LUAU_FASTFLAGVARIABLE(LuauEarlyExitUnifierInstantiation) LUAU_FASTFLAGVARIABLE(LuauDecomposeIntersectionOfFreeType) +LUAU_FLAGVERSION(LuauDecomposeIntersectionOfFreeType, 2) namespace Luau { @@ -543,6 +545,12 @@ template TypePackId Unifier2::instantiateWithBoundTypes(TypePackId ty); template TID Unifier2::instantiateWithBoundTypes(TID ty) { + // If `genericSubstitutions` and `genericPackSubstitutions` are both empty, + // then we don't need to do any instantiation for `ty`, we can return it + // immediately. + if (FFlag::LuauEarlyExitUnifierInstantiation && genericSubstitutions.empty() && genericPackSubstitutions.empty()) + return ty; + Replacer r{arena, NotNull{&genericSubstitutions}, NotNull{&genericPackSubstitutions}}; if (auto newTy = r.substitute(ty)) return *newTy; diff --git a/Ast/include/Luau/Ast.h b/Ast/include/Luau/Ast.h index 178af326d..8c551a87f 100644 --- a/Ast/include/Luau/Ast.h +++ b/Ast/include/Luau/Ast.h @@ -808,6 +808,18 @@ class AstStatWhile : public AstStat AstStatWhile(const Location& location, AstExpr* condition, AstStatBlock* body, bool hasDo, const Location& doLocation); + AstStatWhile( + const Location& location, + AstExpr* condition, + AstStatBlock* body, + bool hasDo, + const Location& doLocation, + AstLocal* conditionLocal, + bool conditionIsConst, + const std::optional& conditionKeywordLocation, + const std::optional& conditionEqualsLocation + ); + void visit(AstVisitor* visitor) override; AstExpr* condition; @@ -815,6 +827,14 @@ class AstStatWhile : public AstStat bool hasDo = false; Location doLocation; + + // Active for `while local` and `while const`; conditionLocal is bound to `condition` and re-evaluated each iteration in scope for `body` only + AstLocal* conditionLocal = nullptr; + bool conditionIsConst = false; + std::optional conditionKeywordLocation; + + // Location of the `=` in a `while local`/`while const` binding + std::optional conditionEqualsLocation; }; class AstStatRepeat : public AstStat diff --git a/Ast/include/Luau/Cst.h b/Ast/include/Luau/Cst.h index ec00a7295..56d159098 100644 --- a/Ast/include/Luau/Cst.h +++ b/Ast/include/Luau/Cst.h @@ -350,6 +350,17 @@ class CstStatIf : public CstNode Position annotationColonPosition; }; +class CstStatWhile : public CstNode +{ +public: + LUAU_CST_RTTI(CstStatWhile) + + explicit CstStatWhile(Position annotationColonPosition); + + // Colon before the `while local` binding's type annotation + Position annotationColonPosition; +}; + class CstStatAssign : public CstNode { public: diff --git a/Ast/include/Luau/Parser.h b/Ast/include/Luau/Parser.h index d0a6f3180..da3f92655 100644 --- a/Ast/include/Luau/Parser.h +++ b/Ast/include/Luau/Parser.h @@ -137,6 +137,10 @@ class Parser // while exp do block end AstStat* parseWhile(); + // while `local' binding `=' exp do block end -- parses an entire `while local`. + // `start` is the location of the already-consumed `while` keyword; the current lexeme is `local`. + AstStat* parseWhileLocalCondition(const Location& start); + // repeat block until exp AstStat* parseRepeat(); diff --git a/Ast/src/Ast.cpp b/Ast/src/Ast.cpp index 19ec34389..af2356313 100644 --- a/Ast/src/Ast.cpp +++ b/Ast/src/Ast.cpp @@ -4,6 +4,7 @@ #include "Luau/Common.h" LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) namespace Luau { @@ -694,10 +695,36 @@ AstStatWhile::AstStatWhile(const Location& location, AstExpr* condition, AstStat { } +AstStatWhile::AstStatWhile( + const Location& location, + AstExpr* condition, + AstStatBlock* body, + bool hasDo, + const Location& doLocation, + AstLocal* conditionLocal, + bool conditionIsConst, + const std::optional& conditionKeywordLocation, + const std::optional& conditionEqualsLocation +) + : AstStat(ClassIndex(), location) + , condition(condition) + , body(body) + , hasDo(hasDo) + , doLocation(doLocation) + , conditionLocal(conditionLocal) + , conditionIsConst(conditionIsConst) + , conditionKeywordLocation(conditionKeywordLocation) + , conditionEqualsLocation(conditionEqualsLocation) +{ +} + void AstStatWhile::visit(AstVisitor* visitor) { if (visitor->visit(this)) { + if (FFlag::DebugLuauWhileLocalSyntax && conditionLocal && conditionLocal->annotation) + conditionLocal->annotation->visit(visitor); + condition->visit(visitor); body->visit(visitor); } diff --git a/Ast/src/Cst.cpp b/Ast/src/Cst.cpp index 932c05261..035aee640 100644 --- a/Ast/src/Cst.cpp +++ b/Ast/src/Cst.cpp @@ -174,6 +174,12 @@ CstStatIf::CstStatIf(Position annotationColonPosition) { } +CstStatWhile::CstStatWhile(Position annotationColonPosition) + : CstNode(CstClassIndex()) + , annotationColonPosition(annotationColonPosition) +{ +} + CstStatAssign::CstStatAssign(AstArray varsCommaPositions, Position equalsPosition, AstArray valuesCommaPositions) : CstNode(CstClassIndex()) , varsCommaPositions(varsCommaPositions) diff --git a/Ast/src/Parser.cpp b/Ast/src/Parser.cpp index 36ccbb4ae..1e5e3aafb 100644 --- a/Ast/src/Parser.cpp +++ b/Ast/src/Parser.cpp @@ -34,6 +34,7 @@ LUAU_FASTFLAGVARIABLE(LuauSingleTypeOptionalPackReturnsAttributeParens) LUAU_FASTFLAGVARIABLE(DebugLuauParseExactTables) LUAU_FASTFLAGVARIABLE(LuauExperimentalIfLocalSyntax) LUAU_FLAGVERSION(LuauExperimentalIfLocalSyntax, 2) +LUAU_FASTFLAGVARIABLE(DebugLuauWhileLocalSyntax) // Clip with DebugLuauReportReturnTypeVariadicWithTypeSuffix bool luau_telemetry_parsed_return_type_variadic_with_type_suffix = false; @@ -717,6 +718,15 @@ AstStat* Parser::parseWhile() nextLexeme(); // while + if (FFlag::DebugLuauWhileLocalSyntax) + { + if (lexer.current().type == Lexeme::ReservedLocal) + return parseWhileLocalCondition(start); + + if (lexer.current().type == Lexeme::Name && AstName(lexer.current().name) == "const" && lexer.lookahead().type == Lexeme::Name) + return parseWhileLocalCondition(start); + } + AstExpr* cond = parseExpr(); Lexeme matchDo = lexer.current(); @@ -736,6 +746,59 @@ AstStat* Parser::parseWhile() return allocator.alloc(Location(start, end), cond, body, hasDo, matchDo.location); } +// while (`local' | `const') binding `=' exp do block end +// +// LUAU_NOINLINE keeps the `while local`/`while const` locals off parseWhile's frame since this variant is rarely taken. +// `start` is the location of the already-consumed `while` keyword; the current lexeme is the `local`/`const` keyword. +LUAU_NOINLINE AstStat* Parser::parseWhileLocalCondition(const Location& start) +{ + LUAU_ASSERT(FFlag::DebugLuauWhileLocalSyntax); + + bool condIsConst = (lexer.current().type == Lexeme::Name && AstName(lexer.current().name) == "const"); + std::optional condKeywordLocation = lexer.current().location; + nextLexeme(); // consume 'local' or 'const' + + Binding binding = parseBinding(condIsConst); + + if (lexer.current().type == ',') + report(lexer.current().location, "Expected '=' after variable name in 'while local', got ','; only a single binding is allowed"); + + std::optional equalsPosition; + if (lexer.current().type == '=') + equalsPosition = lexer.current().location; + expectAndConsume('=', "while local declaration"); + + // The binding is not visible in its own condition expression; it is re-evaluated each iteration. + AstExpr* cond = parseExpr(); + + Lexeme matchDo = lexer.current(); + bool hasDo = expectAndConsume(Lexeme::ReservedDo, "while loop"); + + // Push the binding so it is in scope for the loop body only, then restore after the body. + unsigned int localsBegin = saveLocals(); + AstLocal* condLocal = pushLocal(binding); + + functionStack.back().loopDepth++; + + AstStatBlock* body = parseBlock(); + + functionStack.back().loopDepth--; + + restoreLocals(localsBegin); + + Location end = lexer.current().location; + + bool hasEnd = expectMatchEndAndConsume(Lexeme::ReservedEnd, matchDo); + body->hasEnd = hasEnd; + + AstStatWhile* node = allocator.alloc( + Location{start, end}, cond, body, hasDo, matchDo.location, condLocal, condIsConst, condKeywordLocation, equalsPosition + ); + if (options.storeCstData) + cstNodeMap[node] = allocator.alloc(binding.annotation ? binding.colonPosition : Position::missing()); + return node; +} + // repeat block until exp AstStat* Parser::parseRepeat() { @@ -1797,10 +1860,22 @@ AstStat* Parser::parseTypeFunction(const Location& start, bool exported, Positio size_t oldTypeFunctionDepth = typeFunctionDepth; typeFunctionDepth = functionStack.size(); + bool oldInClassMethodBody = false; + if (FFlag::DebugLuauUserDefinedClasses) + { + oldInClassMethodBody = inClassMethodBody; + // We don't support capturing classes outside the type function for private field accesses + // Classes defined inside the type function are ok though + inClassMethodBody = false; + } + AstExprFunction* body = parseFunctionBody(/* hasself */ false, matchFn, fnName->name, nullptr, AstArray({nullptr, 0})).first; typeFunctionDepth = oldTypeFunctionDepth; + if (FFlag::DebugLuauUserDefinedClasses) + inClassMethodBody = oldInClassMethodBody; + matchRecoveryStopOnToken[Lexeme::ReservedEnd]--; bool hasErrors = parseErrors.size() > errorsAtStart; diff --git a/Ast/src/PrettyPrinter.cpp b/Ast/src/PrettyPrinter.cpp index 4e9b62569..5a063fdfe 100644 --- a/Ast/src/PrettyPrinter.cpp +++ b/Ast/src/PrettyPrinter.cpp @@ -15,6 +15,7 @@ LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) namespace { @@ -936,6 +937,20 @@ struct Printer else if (const auto& a = program.as()) { writer.keyword("while"); + if (FFlag::DebugLuauWhileLocalSyntax && a->conditionLocal) + { + const auto cstNode = lookupCstNode(a); + + if (a->conditionKeywordLocation) + advance(a->conditionKeywordLocation->begin); + writer.keyword(a->conditionIsConst ? "const" : "local"); + + visualize(*a->conditionLocal, cstNode ? cstNode->annotationColonPosition : Position::missing()); + + if (a->conditionEqualsLocation) + advance(a->conditionEqualsLocation->begin); + writer.symbol("="); + } visualize(*a->condition); // TODO: what if 'hasDo = false'? advance(a->doLocation.begin); diff --git a/CLI/src/Analyze.cpp b/CLI/src/Analyze.cpp index 610ecc829..a7b3d239c 100644 --- a/CLI/src/Analyze.cpp +++ b/CLI/src/Analyze.cpp @@ -161,8 +161,8 @@ static int dumpControlFlowGraphs(const std::vector& paths) continue; } - Luau::CFG::CFGAllocator cfgAllocator; - auto cfg = Luau::CFG::CFGBuilder::makeCFG(Luau::NotNull{&cfgAllocator}, parseResult.root); + Luau::CFGAllocator cfgAllocator; + auto cfg = Luau::CFGBuilder::makeCFG(Luau::NotNull{&cfgAllocator}, parseResult.root); printf("%s", Luau::dumpCFG(*cfg).c_str()); } diff --git a/CLI/src/Compile.cpp b/CLI/src/Compile.cpp index 46901efb0..0c063c928 100644 --- a/CLI/src/Compile.cpp +++ b/CLI/src/Compile.cpp @@ -58,6 +58,7 @@ struct GlobalOptions bool parseCst = false; bool dumpRegSpills = false; + bool dumpOutlined = false; } globalOptions; static Luau::CompileOptions copts() @@ -336,7 +337,7 @@ static bool compileFile( options.includeIr = format != CompileFormat::CodegenAsm; options.includeIrTypes = format != CompileFormat::CodegenAsm; - options.includeOutlinedCode = format == CompileFormat::CodegenVerbose; + options.includeOutlinedCode = globalOptions.dumpOutlined || format == CompileFormat::CodegenVerbose; options.includeRegSpills = globalOptions.dumpRegSpills; } @@ -447,6 +448,7 @@ static void displayHelp(const char* argv0) printf(" --bytecode-summary: Compute bytecode operation distribution.\n"); printf(" --dump-constants: Dump constant table for each function (text mode only).\n"); printf(" --dump-regspills: include register spill events in codegen output.\n"); + printf(" --dump-outlined: include outlined code in codegen output.\n"); printf(" --stats-file=: file in which compilation stats will be recored (default 'stats.json').\n"); printf(" --vector-lib=: name of the library providing vector type operations.\n"); printf(" --vector-ctor=: name of the function constructing a vector value.\n"); @@ -586,6 +588,10 @@ int main(int argc, char** argv) { globalOptions.dumpRegSpills = true; } + else if (strcmp(argv[i], "--dump-outlined") == 0) + { + globalOptions.dumpOutlined = true; + } else if (strncmp(argv[i], "--stats-file=", 13) == 0) { statsFile = argv[i] + 13; diff --git a/CLI/src/Repl.cpp b/CLI/src/Repl.cpp index 066308726..10d6fcffd 100644 --- a/CLI/src/Repl.cpp +++ b/CLI/src/Repl.cpp @@ -51,6 +51,7 @@ constexpr int MaxTraversalLimit = 50; static bool codegen = false; static bool codegenCold = false; +static bool codegenLazy = false; static bool jitInliner = false; static int program_argc = 0; char** program_argv = nullptr; @@ -187,7 +188,7 @@ void* createCliRequireContext(lua_State* L) coverageActive, []() { - return codegen; + return codegen && !codegenLazy; }, coverageTrack, countersActive, @@ -620,7 +621,12 @@ static bool runFile(const char* name, lua_State* GL, bool repl) if (countersActive()) nativeOptions.recordCounters = true; - Luau::CodeGen::compile(L, -1, nativeOptions); + nativeOptions.runtimeFeedback = true; + + Luau::CodeGen::enableRuntimeCompilation(L, nativeOptions, codegenLazy); + + if (!codegenLazy) + Luau::CodeGen::compile(L, -1, nativeOptions); } if (coverageActive()) @@ -681,6 +687,7 @@ static void displayHelp(const char* argv0) printf(" --timetrace: record compiler time tracing information into trace.json\n"); printf(" --codegen: execute code using native code generation\n"); printf(" --codegen-cold: execute code using native code generation, including any functions deemed not profitable to natively compile\n"); + printf(" --codegen-lazy: execute code in the VM and compile hot functions to native automatically\n"); printf(" --codegen-perf: execute code using native code generation and profile using perf (only on Linux)\n"); printf(" --program-args,-a: declare start of arguments to be passed to the Luau program\n"); printf(" --fflags=: comma-separated list of fast flags to enable/disable (--fflags=true,false,LuauFlag1=true,LuauFlag2=false).\n"); @@ -756,6 +763,11 @@ int replMain(int argc, char** argv) codegen = true; codegenCold = true; } + else if (strcmp(argv[i], "--codegen-lazy") == 0) + { + codegen = true; + codegenLazy = true; + } else if (strcmp(argv[i], "--codegen-perf") == 0) { codegen = true; diff --git a/CLI/src/ReplRequirer.cpp b/CLI/src/ReplRequirer.cpp index 05da2809d..cc7dce302 100644 --- a/CLI/src/ReplRequirer.cpp +++ b/CLI/src/ReplRequirer.cpp @@ -177,6 +177,8 @@ static int load(lua_State* L, void* ctx, const char* path, const char* chunkname if (req->countersActive()) nativeOptions.recordCounters = true; + nativeOptions.runtimeFeedback = true; + Luau::CodeGen::compile(ML, -1, nativeOptions); } diff --git a/CodeGen/include/Luau/CodeGen.h b/CodeGen/include/Luau/CodeGen.h index bd9139d60..3da5ba667 100644 --- a/CodeGen/include/Luau/CodeGen.h +++ b/CodeGen/include/Luau/CodeGen.h @@ -127,6 +127,11 @@ using UserdataRemapperCallback = uint8_t(void* context, const char* name, size_t void setUserdataRemapper(lua_State* L, void* context, UserdataRemapperCallback cb); +// Enables automatic runtime function recompilation with the specified compilation options +// When promoteVmFunctions is enabled, recompilation also applies to functions running in the VM +// 'userdataTypes' in options has to survive until all VMs using target CodeGenContext are closed +void enableRuntimeCompilation(lua_State* L, const CompilationOptions& options, bool promoteVmFunctions); + using ModuleId = std::array; // Builds target function and all inner functions diff --git a/CodeGen/include/Luau/CodeGenOptions.h b/CodeGen/include/Luau/CodeGenOptions.h index bd7007ff2..c0224e29d 100644 --- a/CodeGen/include/Luau/CodeGenOptions.h +++ b/CodeGen/include/Luau/CodeGenOptions.h @@ -129,6 +129,9 @@ struct CompilationOptions bool recordCounters = false; + // Compile with runtime counters which will guide further recompilation of native code + bool runtimeFeedback = false; + // When true, random NOP sleds are inserted between blocks to // make intra-function gadget offsets unpredictable. bool nopPadding = false; diff --git a/CodeGen/include/Luau/IrData.h b/CodeGen/include/Luau/IrData.h index 6475e3d10..2ca62eb3c 100644 --- a/CodeGen/include/Luau/IrData.h +++ b/CodeGen/include/Luau/IrData.h @@ -2,6 +2,7 @@ #pragma once #include "Luau/Bytecode.h" +#include "Luau/CodeGenOptions.h" #include "Luau/DenseHash.h" #include "Luau/IrAnalysis.h" #include "Luau/Label.h" @@ -1504,7 +1505,9 @@ struct IrFunction LoweringStats* stats = nullptr; - bool recordCounters = false; // Taken from CompilationOptions for easy access + // Taken from CompilationOptions for easy access + bool recordCounters = false; + bool recordFeedback = false; uint64_t jitRngState = 0; // PCG32 state for NOP padding; seeded per-function in lowerFunction diff --git a/CodeGen/include/Luau/IrUtils.h b/CodeGen/include/Luau/IrUtils.h index 92fda776d..51f49ba4a 100644 --- a/CodeGen/include/Luau/IrUtils.h +++ b/CodeGen/include/Luau/IrUtils.h @@ -8,6 +8,7 @@ #include LUAU_FASTFLAG(LuauCodegenUpdateSafeEnvList) +LUAU_FASTFLAG(LuauCodegenCmpAnySideEffecting) namespace Luau { @@ -129,6 +130,9 @@ inline bool hasSideEffects(IrCmd cmd) if (cmd == IrCmd::INVOKE_FASTCALL) return true; + if (FFlag::LuauCodegenCmpAnySideEffecting && cmd == IrCmd::CMP_ANY) + return true; + if (isPseudo(cmd)) return false; diff --git a/CodeGen/src/CodeGenAssembly.cpp b/CodeGen/src/CodeGenAssembly.cpp index 9560191ea..fbe57f990 100644 --- a/CodeGen/src/CodeGenAssembly.cpp +++ b/CodeGen/src/CodeGenAssembly.cpp @@ -11,6 +11,8 @@ #include "lapi.h" +LUAU_FASTFLAG(LuauRuntimeFeedback) + namespace Luau { namespace CodeGen @@ -192,6 +194,13 @@ static std::string getAssemblyImpl( for (Proto* p : protos) { IrBuilder ir(options.compilationOptions.hooks, envInfo); + + if (FFlag::LuauRuntimeFeedback) + { + ir.function.recordCounters = options.compilationOptions.recordCounters; + ir.function.recordFeedback = options.compilationOptions.runtimeFeedback; + } + ir.buildFunctionIr(p); unsigned asmSize = build.getCodeSize(); unsigned asmCount = build.getInstructionCount(); diff --git a/CodeGen/src/CodeGenContext.cpp b/CodeGen/src/CodeGenContext.cpp index 0281d4c82..9fa016b2e 100644 --- a/CodeGen/src/CodeGenContext.cpp +++ b/CodeGen/src/CodeGenContext.cpp @@ -12,11 +12,18 @@ #include "Luau/UnwindBuilderWin.h" #include "lapi.h" +#include "ldo.h" +#include "lfunc.h" +#include "lgc.h" +#include "lmem.h" + +#include #include LUAU_FASTINTVARIABLE(LuauCodeGenBlockSize, 4 * 1024 * 1024) LUAU_FASTINTVARIABLE(LuauCodeGenMaxTotalSize, 256 * 1024 * 1024) +LUAU_FASTFLAG(LuauRuntimeFeedback) namespace Luau { @@ -46,6 +53,14 @@ uint32_t jitRngRandom(uint64_t& state) static const Instruction kCodeEntryInsn = LOP_NATIVECALL; +// TODO: could be promoted to flags or compilation option fields + +// Maximum number of times a single function can be rebuilt +constexpr uint32_t kMaxFunctionRebuilds = 5; + +// Number of VM hits after which we will natively compile if promoteVmFunctions is enabled +constexpr uint32_t kNativeCompilationHitThreshold = 100'000; + // From CodeGen.cpp static void* gPerfLogContext = nullptr; static PerfLogFn gPerfLogFn = nullptr; @@ -104,6 +119,9 @@ static void logPerfFunctions( CODEGEN_ASSERT(protoIt != moduleProtos.end()); logPerfFunction(*protoIt, uintptr_t(header.entryOffsetOrAddress), uint32_t(header.nativeCodeSize)); + + if (FFlag::LuauRuntimeFeedback) + ++protoIt; } } @@ -146,6 +164,9 @@ template proto->codeentry = &kCodeEntryInsn; ++protosBound; + + if (FFlag::LuauRuntimeFeedback) + ++protoIt; } return protosBound; @@ -233,7 +254,12 @@ StandaloneCodeGenContext::StandaloneCodeGenContext( return {CodeGenCompilationResult::Success, protosBound}; } -void StandaloneCodeGenContext::onCloseState() noexcept +VmCodeGenData& StandaloneCodeGenContext::getVmData(lua_State* L) +{ + return vmData; +} + +void StandaloneCodeGenContext::onCloseState(lua_State* L) noexcept { // The StandaloneCodeGenContext is owned by the one VM that owns it, so when // that VM is destroyed, we destroy *this as well: @@ -312,11 +338,31 @@ SharedCodeGenContext::SharedCodeGenContext( return {CodeGenCompilationResult::Success, protosBound}; } -void SharedCodeGenContext::onCloseState() noexcept +VmCodeGenData& SharedCodeGenContext::getVmData(lua_State* L) +{ + CODEGEN_ASSERT(L == L->global->mainthread); + + std::unique_lock lock{vmDataMutex}; + std::unique_ptr& data = vmData[L]; + + if (!data) + data = std::make_unique(); + + return *data; +} + +void SharedCodeGenContext::onCloseState(lua_State* L) noexcept { - // The lifetime of the SharedCodeGenContext is managed separately from the - // VMs that use it. When a VM is destroyed, we don't need to do anything - // here. + CODEGEN_ASSERT(L == L->global->mainthread); + + if (FFlag::LuauRuntimeFeedback) + { + // The lifetime of the SharedCodeGenContext is managed separately from the VMs that use it + // When a VM is destroyed, only its runtime build data is removed + std::unique_lock lock{vmDataMutex}; + + vmData.erase(L); + } } void SharedCodeGenContext::onDestroyFunction(void* execdata) noexcept @@ -324,7 +370,6 @@ void SharedCodeGenContext::onDestroyFunction(void* execdata) noexcept getNativeProtoExecDataHeader(static_cast(execdata)).nativeModule->release(); } - [[nodiscard]] UniqueSharedCodeGenContext createSharedCodeGenContext() { return createSharedCodeGenContext(size_t(FInt::LuauCodeGenBlockSize), size_t(FInt::LuauCodeGenMaxTotalSize), nullptr, nullptr); @@ -370,13 +415,29 @@ void SharedCodeGenContextDeleter::operator()(const SharedCodeGenContext* codeGen static void onCloseState(lua_State* L) { - getCodeGenContext(L)->onCloseState(); + CODEGEN_ASSERT(L == L->global->mainthread); + getCodeGenContext(L)->onCloseState(L); L->global->ecb = lua_ExecutionCallbacks{}; } static void onDestroyFunction(lua_State* L, Proto* proto) { - getCodeGenContext(L)->onDestroyFunction(proto->execdata); + if (FFlag::LuauRuntimeFeedback) + { + BaseCodeGenContext* codeGenContext = getCodeGenContext(L); + VmCodeGenData& vmData = codeGenContext->getVmData(L->global->mainthread); + + // If latest function is destroyed, clear its build history + if (proto->funid != 0 && proto->optimized == nullptr) + vmData.buildHistory.erase(proto->funid); + + codeGenContext->onDestroyFunction(proto->execdata); + } + else + { + getCodeGenContext(L)->onDestroyFunction(proto->execdata); + } + proto->execdata = nullptr; proto->exectarget = 0; proto->codeentry = proto->code; @@ -428,6 +489,160 @@ static char* getCounterData(lua_State* L, Proto* proto, size_t* count) return reinterpret_cast(static_cast(proto->execdata) + proto->sizecode); } +static void examineFunction(lua_State* L, Proto* proto) +{ + // Fast exit if target function never executed + if (proto->execcount == 0) + return; + + if ((proto->execflags & PEF_DEBUGLOCKED) != 0 || proto->optimized != nullptr || proto->funid == 0) + { + proto->execflags |= PEF_EXECLOCKED; + return; + } + + BaseCodeGenContext* codeGenContext = getCodeGenContext(L); + VmCodeGenData& vmData = codeGenContext->getVmData(L->global->mainthread); + + if (!vmData.runtimeRebuildEnabled) + { + proto->execflags |= PEF_EXECLOCKED; + return; + } + + // If function is not native, we check if VM promotion is enabled and we reached the threshold + if (proto->execdata == nullptr) + { + if (vmData.promoteVmFunctions) + { + if (proto->execcount >= kNativeCompilationHitThreshold) + vmData.protosToRebuild.insert(proto); + } + else + { + proto->execflags |= PEF_EXECLOCKED; + } + + return; + } + + // Rebuild based on feedback counters will be detected here +} + +[[nodiscard]] static CompilationResult compileProtos( + const std::optional& moduleId, + lua_State* L, + BaseCodeGenContext* codeGenContext, + const std::vector& protos, + const CompilationOptions& options, + CompilationStats* stats +); + +static void commitFunctions(lua_State* L) +{ + BaseCodeGenContext* codeGenContext = getCodeGenContext(L); + + VmCodeGenData& vmData = codeGenContext->getVmData(L->global->mainthread); + + // Interpreted functions are compiled in place, native functions are rebuilt into a copy + struct PendingBuild + { + Proto* proto = nullptr; + Proto* copy = nullptr; + uint32_t execCount = 0; + }; + + std::vector builds; + std::vector buildProtos; + + for (Proto* proto : vmData.protosToRebuild) + { + CODEGEN_ASSERT(proto->funid != 0); + + // Rechecking failure conditions since the time function was examined + if ((proto->execflags & PEF_DEBUGLOCKED) != 0 || proto->optimized != nullptr) + { + proto->execflags |= PEF_EXECLOCKED; + continue; + } + + // Promote VM function to native + if (proto->execdata == nullptr) + { + builds.push_back({proto, nullptr, proto->execcount}); + buildProtos.push_back(proto); + proto->execcount = 0; + continue; + } + + // Function rebuild based on feedback counters will be here + } + + vmData.protosToRebuild.clear(); + + if (builds.empty()) + return; + + CompilationResult result = compileProtos({}, L, codeGenContext, buildProtos, vmData.options, nullptr); + + // TODO: callback function for host telemetry recording + if (result.result != CodeGenCompilationResult::Success) + return; + + for (size_t i = 0; i < builds.size(); i++) + { + Proto* proto = builds[i].proto; + Proto* copy = builds[i].copy; + + // Initial VM to native promotion is performed inplace, so we don't need to swith Proto to the optimized version + if (copy == nullptr) + continue; + + // This function failed to compile natively + if (copy->execdata == nullptr) + continue; + + FunctionBuildHistory& history = vmData.buildHistory[proto->funid]; + + copy->deoptimized = proto; + proto->optimized = copy; + luaC_objbarrier(L, proto, copy); + + history.rebuildCount++; + + if (history.rebuildCount >= kMaxFunctionRebuilds) + { + copy->execflags |= PEF_EXECLOCKED; + vmData.buildHistory.erase(proto->funid); + } + } +} + +static void examineFunctionSafe(lua_State* L, Proto* proto) noexcept +{ + try + { + examineFunction(L, proto); + } + catch (const std::exception&) + { + // Function will be examined again later + } +} + +static void commitFunctionsSafe(lua_State* L) noexcept +{ + try + { + commitFunctions(L); + } + catch (const std::exception&) + { + // Pending functions are dropped, they will be examined again when they reach the thresholds + getCodeGenContext(L)->getVmData(L->global->mainthread).protosToRebuild.clear(); + } +} + static void initializeExecutionCallbacks(lua_State* L, BaseCodeGenContext* codeGenContext) noexcept { CODEGEN_ASSERT(codeGenContext != nullptr); @@ -441,6 +656,12 @@ static void initializeExecutionCallbacks(lua_State* L, BaseCodeGenContext* codeG ecb->disable = onDisable; ecb->getmemorysize = getMemorySize; ecb->getcounterdata = getCounterData; + + if (FFlag::LuauRuntimeFeedback) + { + ecb->examinefunction = examineFunctionSafe; + ecb->commitfunctions = commitFunctionsSafe; + } } void create(lua_State* L) @@ -461,11 +682,23 @@ void create(lua_State* L, size_t blockSize, size_t maxTotalSize, AllocationCallb if (!codeGenContext->initHeaderFunctions()) return; + if (FFlag::LuauRuntimeFeedback) + { + // Reserve VM data + codeGenContext->getVmData(L->global->mainthread); + } + initializeExecutionCallbacks(L, codeGenContext.release()); } void create(lua_State* L, SharedCodeGenContext* codeGenContext) { + if (FFlag::LuauRuntimeFeedback) + { + // Reserve VM data + codeGenContext->getVmData(L->global->mainthread); + } + initializeExecutionCallbacks(L, codeGenContext); } @@ -520,6 +753,12 @@ template ) { IrBuilder ir(options.hooks, envInfo); + + if (FFlag::LuauRuntimeFeedback) + { + ir.function.recordFeedback = options.runtimeFeedback; + } + ir.buildFunctionIr(proto); unsigned instCount = unsigned(ir.function.instructions.size()); @@ -596,6 +835,18 @@ template } } + return compileProtos(moduleId, L, codeGenContext, protos, options, stats); +} + +[[nodiscard]] static CompilationResult compileProtos( + const std::optional& moduleId, + lua_State* L, + BaseCodeGenContext* codeGenContext, + const std::vector& protos, + const CompilationOptions& options, + CompilationStats* stats +) +{ #if defined(CODEGEN_TARGET_A64) static unsigned int cpuFeatures = getCpuFeaturesA64(); A64::AssemblyBuilderA64 build(/* logger= */ nullptr, cpuFeatures); @@ -620,6 +871,10 @@ template std::vector nativeProtos; nativeProtos.reserve(protos.size()); + std::vector compiledProtos; + if (FFlag::LuauRuntimeFeedback) + compiledProtos.reserve(protos.size()); + uint32_t totalIrInstCount = 0; for (size_t i = 0; i != protos.size(); ++i) @@ -631,6 +886,8 @@ template if (nativeExecData != nullptr) { nativeProtos.push_back(std::move(nativeExecData)); + if (FFlag::LuauRuntimeFeedback) + compiledProtos.push_back(protos[i]); } else { @@ -684,7 +941,7 @@ template const ModuleBindResult bindResult = codeGenContext->bindModule( moduleId, - protos, + !FFlag::LuauRuntimeFeedback || moduleId ? protos : compiledProtos, std::move(nativeProtos), reinterpret_cast(build.data.data()), build.data.size(), @@ -756,5 +1013,16 @@ void setUserdataRemapper(lua_State* L, void* context, UserdataRemapperCallback c } } +void enableRuntimeCompilation(lua_State* L, const CompilationOptions& options, bool promoteVmFunctions) +{ + if (BaseCodeGenContext* codeGenContext = getCodeGenContext(L)) + { + VmCodeGenData& vmData = codeGenContext->getVmData(L->global->mainthread); + vmData.options = options; + vmData.runtimeRebuildEnabled = true; + vmData.promoteVmFunctions = promoteVmFunctions; + } +} + } // namespace CodeGen } // namespace Luau diff --git a/CodeGen/src/CodeGenContext.h b/CodeGen/src/CodeGenContext.h index bfa1fa0c8..1e7c955a0 100644 --- a/CodeGen/src/CodeGenContext.h +++ b/CodeGen/src/CodeGenContext.h @@ -1,12 +1,18 @@ // This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details #pragma once +#include "Luau/CodeGenOptions.h" #include "Luau/SharedCodeAllocator.h" +#include "Luau/DenseHash.h" +#include "Luau/IrData.h" #include "NativeState.h" #include +#include #include +#include + #include namespace Luau @@ -28,6 +34,26 @@ struct ModuleBindResult uint32_t functionsBound = 0; }; +struct FunctionBuildHistory +{ + uint32_t rebuildCount = 0; + + // If Proto size changes, history has to be invalidated + int sizecode = 0; +}; + +struct VmCodeGenData +{ + DenseHashSet protosToRebuild; + DenseHashMap buildHistory; + + // Functions are only rebuilt or promoted at runtime after these options are provided + CompilationOptions options; + + bool runtimeRebuildEnabled = false; + bool promoteVmFunctions = false; +}; + class BaseCodeGenContext { public: @@ -51,7 +77,9 @@ class BaseCodeGenContext size_t codeSize ) = 0; - virtual void onCloseState() noexcept = 0; + virtual VmCodeGenData& getVmData(lua_State* L) = 0; + + virtual void onCloseState(lua_State* L) noexcept = 0; virtual void onDestroyFunction(void* execdata) noexcept = 0; CodeAllocator codeAllocator; @@ -82,11 +110,15 @@ class StandaloneCodeGenContext final : public BaseCodeGenContext size_t codeSize ) override; - void onCloseState() noexcept override; + VmCodeGenData& getVmData(lua_State* L) override; + + void onCloseState(lua_State* L) noexcept override; void onDestroyFunction(void* execdata) noexcept override; private: SharedCodeAllocator sharedAllocator; + + VmCodeGenData vmData; }; class SharedCodeGenContext final : public BaseCodeGenContext @@ -106,11 +138,16 @@ class SharedCodeGenContext final : public BaseCodeGenContext size_t codeSize ) override; - void onCloseState() noexcept override; + VmCodeGenData& getVmData(lua_State* L) override; + + void onCloseState(lua_State* L) noexcept override; void onDestroyFunction(void* execdata) noexcept override; private: SharedCodeAllocator sharedAllocator; + + std::mutex vmDataMutex; + DenseHashMap> vmData; }; // JIT layout randomization helpers diff --git a/CodeGen/src/CodeGenUtils.cpp b/CodeGen/src/CodeGenUtils.cpp index 7cb305b64..c5b20e071 100644 --- a/CodeGen/src/CodeGenUtils.cpp +++ b/CodeGen/src/CodeGenUtils.cpp @@ -20,6 +20,7 @@ #include LUAU_FASTFLAG(LuauPromoteProto) +LUAU_FASTFLAG(LuauRuntimeFeedback) // All external function calls that can cause stack realloc or Lua calls have to be wrapped in VM_PROTECT // This makes sure that we save the pc (in case the Lua call needs to generate a backtrace) before the call, @@ -224,6 +225,9 @@ Closure* callProlog(lua_State* L, TValue* ra, StkId argtop, int nresults) // crucially, we can't use ra/argtop after this line luaD_checkstackfornewci(L, ccl->stacksize); + if (FFlag::LuauRuntimeFeedback && ci->p) + ci->p->execcount++; + return ccl; } @@ -314,6 +318,9 @@ Closure* callFallback(lua_State* L, StkId ra, StkId argtop, int nresults) { Proto* p = ccl->l.p; + if (FFlag::LuauRuntimeFeedback) + p->execcount++; + // fill unused parameters with nil StkId argi = L->top; StkId argend = L->base + p->numparams; diff --git a/CodeGen/src/IrBuilder.cpp b/CodeGen/src/IrBuilder.cpp index 4422a9485..c284b96c7 100644 --- a/CodeGen/src/IrBuilder.cpp +++ b/CodeGen/src/IrBuilder.cpp @@ -14,6 +14,7 @@ LUAU_FASTFLAGVARIABLE(LuauCodeGenFastpcall) LUAU_FLAGVERSION(LuauCodeGenFastpcall, 2) +LUAU_FASTFLAG(LuauCodegenMarkUsed) namespace Luau { @@ -239,6 +240,13 @@ void IrBuilder::buildFunctionIr(Proto* proto) // Now that all has been generated, compute use counts updateUseCounts(function); + + if (FFlag::LuauCodegenCmpAnySideEffecting) + { + // Check that no instructions with a result have been generated without a use + for (IrInst& inst : function.instructions) + CODEGEN_ASSERT(inst.useCount != 0 || !hasResult(inst.cmd)); + } } void IrBuilder::rebuildBytecodeBasicBlocks(Proto* proto) @@ -815,7 +823,8 @@ void IrBuilder::clone(std::vector sourceIdxs, bool removeCurrentTermin IrInst clone = function.instructions[index]; // Skip pseudo instructions to make clone more compact, but validate that they have no users - if (isPseudo(clone.cmd)) + // Also keep instructions marking register liveness + if (isPseudo(clone.cmd) && (!FFlag::LuauCodegenMarkUsed || (clone.cmd != IrCmd::MARK_DEAD && clone.cmd != IrCmd::MARK_USED))) { CODEGEN_ASSERT(clone.useCount == 0); continue; diff --git a/CodeGen/src/IrLoweringA64.cpp b/CodeGen/src/IrLoweringA64.cpp index 58d87450b..da1332163 100644 --- a/CodeGen/src/IrLoweringA64.cpp +++ b/CodeGen/src/IrLoweringA64.cpp @@ -3907,6 +3907,13 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) regs.freeLastUseRegs(inst, index); regs.freeTempRegs(); + + // Free register if there is no user of the result + if (FFlag::LuauCodegenCmpAnySideEffecting && inst.lastUse == 0 && hasResult(inst.cmd)) + { + regs.freeReg(inst.regA64); + inst.regA64 = noreg; + } } void IrLoweringA64::startBlock(const IrBlock& curr) diff --git a/CodeGen/src/IrLoweringX64.cpp b/CodeGen/src/IrLoweringX64.cpp index bc7f6ed9e..c099b0ea4 100644 --- a/CodeGen/src/IrLoweringX64.cpp +++ b/CodeGen/src/IrLoweringX64.cpp @@ -16,7 +16,6 @@ #include "lstate.h" #include "lgc.h" -LUAU_FASTFLAG(LuauCodegenExitSyncUpdate) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) namespace Luau @@ -3734,6 +3733,13 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) regs.currInstIdx = kInvalidInstIdx; regs.freeLastUseRegs(inst, index); + + // Free register if there is no user of the result + if (FFlag::LuauCodegenCmpAnySideEffecting && inst.lastUse == 0 && hasResult(inst.cmd)) + { + regs.freeReg(inst.regX64); + inst.regX64 = noreg; + } } void IrLoweringX64::startBlock(const IrBlock& curr) @@ -3830,7 +3836,7 @@ bool IrLoweringX64::hasError() const if (regs.maxUsedSlot > kSpillSlots) return true; - if (FFlag::LuauCodegenExitSyncUpdate && regs.error) + if (regs.error) return true; return false; diff --git a/CodeGen/src/IrRegAllocA64.cpp b/CodeGen/src/IrRegAllocA64.cpp index 885e53b46..e0e1a23e1 100644 --- a/CodeGen/src/IrRegAllocA64.cpp +++ b/CodeGen/src/IrRegAllocA64.cpp @@ -11,9 +11,7 @@ #include -LUAU_FASTFLAGVARIABLE(LuauCodegenExitSyncUpdate) LUAU_FASTFLAGVARIABLE(DebugCodegenChaosA64) -LUAU_FASTFLAGVARIABLE(LuauCodegenScopedSpillKeepLazy) LUAU_FASTFLAGVARIABLE(DebugCodegenLimitRegs) LUAU_FASTFLAGVARIABLE(LuauCodegenA64ReloadLargeConstOffset) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) @@ -401,7 +399,7 @@ void IrRegAllocA64::setupExitSyncEntry(uint32_t blockIdx) SmallVector argumentsToRestore; - if (FFlag::LuauCodegenExitSyncUpdate && !FFlag::LuauCodegenImprovedExitSync) + if (!FFlag::LuauCodegenImprovedExitSync) { if (const uint32_t* guardInstIdx = function.blockToVmExitMap.find(blockIdx)) syncInfo = function.vmExitInfo.find(*guardInstIdx); @@ -445,7 +443,7 @@ void IrRegAllocA64::setupExitSyncEntry(uint32_t blockIdx) spills.push_back({arg.instIdx, arg.originalReg, arg.slot}); // If the restore VM register will be clobbered by a store in this block, restore it immediately - if (FFlag::LuauCodegenExitSyncUpdate && !FFlag::LuauCodegenImprovedExitSync && syncInfo && arg.restoreLocation.op.kind == IrOpKind::VmReg) + if (!FFlag::LuauCodegenImprovedExitSync && syncInfo && arg.restoreLocation.op.kind == IrOpKind::VmReg) { uint8_t vmReg = vmRegOp(arg.restoreLocation.op); @@ -475,7 +473,7 @@ void IrRegAllocA64::setupExitSyncEntry(uint32_t blockIdx) } } - if (FFlag::LuauCodegenExitSyncUpdate && !FFlag::LuauCodegenImprovedExitSync) + if (!FFlag::LuauCodegenImprovedExitSync) { for (uint32_t instIdx : argumentsToRestore) restoreReg(function.instructions[instIdx]); @@ -711,7 +709,7 @@ void IrRegAllocA64::spill(Set& set, uint32_t index, uint32_t targetInstIdx, bool if (loc.kind != IrValueKind::Tvalue) build.str(wzr, mem(rBase, storeReg * sizeof(TValue) + offsetof(TValue, tt))); - if (!FFlag::LuauCodegenScopedSpillKeepLazy || !keepLazyLocations) + if (!keepLazyLocations) function.materializeRestoreLocation(targetInstIdx); } diff --git a/CodeGen/src/IrRegAllocX64.cpp b/CodeGen/src/IrRegAllocX64.cpp index aee68a71d..f7d430bff 100644 --- a/CodeGen/src/IrRegAllocX64.cpp +++ b/CodeGen/src/IrRegAllocX64.cpp @@ -9,10 +9,7 @@ #include "lstate.h" -LUAU_FASTFLAG(LuauCodegenExitSyncUpdate) LUAU_FASTFLAG(DebugCodegenLimitRegs) -LUAU_FASTFLAGVARIABLE(LuauCodegenX64IntSpillRestore) -LUAU_FASTFLAG(LuauCodegenScopedSpillKeepLazy) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) namespace Luau @@ -96,8 +93,7 @@ RegisterX64 IrRegAllocX64::allocReg(SizeX64 size, uint32_t instIdx) return takeReg(reg, instIdx); } - if (FFlag::LuauCodegenExitSyncUpdate) - error = true; + error = true; CODEGEN_ASSERT(!"Out of registers to allocate"); return noreg; @@ -293,7 +289,7 @@ void IrRegAllocX64::setupExitSyncEntry(uint32_t blockIdx) SmallVector argumentsToRestore; - if (FFlag::LuauCodegenExitSyncUpdate && !FFlag::LuauCodegenImprovedExitSync) + if (!FFlag::LuauCodegenImprovedExitSync) { if (const uint32_t* guardInstIdx = function.blockToVmExitMap.find(blockIdx)) syncInfo = function.vmExitInfo.find(*guardInstIdx); @@ -353,7 +349,7 @@ void IrRegAllocX64::setupExitSyncEntry(uint32_t blockIdx) spills.push_back(spill); // If the restore VM register will be clobbered by a different store in this block, restore it immediately - if (FFlag::LuauCodegenExitSyncUpdate && !FFlag::LuauCodegenImprovedExitSync && syncInfo && arg.restoreLocation.op.kind == IrOpKind::VmReg) + if (!FFlag::LuauCodegenImprovedExitSync && syncInfo && arg.restoreLocation.op.kind == IrOpKind::VmReg) { uint8_t vmReg = vmRegOp(arg.restoreLocation.op); @@ -383,7 +379,7 @@ void IrRegAllocX64::setupExitSyncEntry(uint32_t blockIdx) } } - if (FFlag::LuauCodegenExitSyncUpdate && !FFlag::LuauCodegenImprovedExitSync) + if (!FFlag::LuauCodegenImprovedExitSync) { for (uint32_t instIdx : argumentsToRestore) restore(function.instructions[instIdx], /*intoOriginalLocation*/ false); @@ -469,7 +465,7 @@ void IrRegAllocX64::preserve(IrInst& inst) if (spill.valueKind != IrValueKind::Tvalue) build.mov(luauRegTag(storeReg), 0); - if (!FFlag::LuauCodegenScopedSpillKeepLazy || !keepLazyLocations) + if (!keepLazyLocations) function.materializeRestoreLocation(spill.instIdx); } @@ -552,8 +548,7 @@ void IrRegAllocX64::restore(IrInst& inst, bool intoOriginalLocation) { build.vmovsd(reg, restoreAddr); } - else if (spill.valueKind == IrValueKind::Int && restoreLocation.kind == IrValueKind::Double && - (!FFlag::LuauCodegenX64IntSpillRestore || spill.stackSlot == kNoStackSlot)) + else if (spill.valueKind == IrValueKind::Int && restoreLocation.kind == IrValueKind::Double && spill.stackSlot == kNoStackSlot) { // Handle restore of an int/uint value from a location storing a double number if (restoreLocation.conversionCmd == IrCmd::INT_TO_NUM) @@ -816,11 +811,8 @@ RegisterX64 ScopedRegX64::release() ScopedSpills::ScopedSpills(IrRegAllocX64& owner) : owner(owner) { - if (FFlag::LuauCodegenScopedSpillKeepLazy) - { - CODEGEN_ASSERT(!owner.keepLazyLocations); - owner.keepLazyLocations = true; - } + CODEGEN_ASSERT(!owner.keepLazyLocations); + owner.keepLazyLocations = true; startSpillId = owner.nextSpillId; } @@ -851,11 +843,8 @@ ScopedSpills::~ScopedSpills() } } - if (FFlag::LuauCodegenScopedSpillKeepLazy) - { - CODEGEN_ASSERT(owner.keepLazyLocations); - owner.keepLazyLocations = false; - } + CODEGEN_ASSERT(owner.keepLazyLocations); + owner.keepLazyLocations = false; } } // namespace X64 diff --git a/CodeGen/src/IrUtils.cpp b/CodeGen/src/IrUtils.cpp index 2f9d9bbc3..ccda7db89 100644 --- a/CodeGen/src/IrUtils.cpp +++ b/CodeGen/src/IrUtils.cpp @@ -21,6 +21,7 @@ LUAU_FASTFLAG(LuauCodegenPropagateFallbackTags) LUAU_FASTFLAGVARIABLE(LuauCodegenUpdateSafeEnvList) +LUAU_FASTFLAGVARIABLE(LuauCodegenCmpAnySideEffecting) namespace Luau { @@ -461,7 +462,7 @@ static void removeInstUse(IrFunction& function, uint32_t instIdx) CODEGEN_ASSERT(inst.useCount); inst.useCount--; - if (inst.useCount == 0) + if (inst.useCount == 0 && (!FFlag::LuauCodegenCmpAnySideEffecting || !hasSideEffects(inst.cmd))) kill(function, inst); } diff --git a/CodeGen/src/OptimizeConstProp.cpp b/CodeGen/src/OptimizeConstProp.cpp index da8893fca..01fdd6f45 100644 --- a/CodeGen/src/OptimizeConstProp.cpp +++ b/CodeGen/src/OptimizeConstProp.cpp @@ -26,9 +26,8 @@ LUAU_FASTINTVARIABLE(LuauCodeGenReuseUdataTagLimit, 64) LUAU_FASTINTVARIABLE(LuauCodeGenLiveSlotReuseLimit, 8) LUAU_FASTFLAGVARIABLE(DebugLuauAbortingChecks) LUAU_FASTFLAGVARIABLE(LuauCodegenPropagateFallbackTags) -LUAU_FASTFLAGVARIABLE(LuauCodegenNoZeroScale) LUAU_FLAGVERSION(LuauCodegenPropagateFallbackTags, 2) -LUAU_FASTFLAGVARIABLE(LuauCodegenLimitVersionsExtra) +LUAU_FASTFLAGVARIABLE(LuauCodegenMarkUsed) namespace Luau { @@ -212,6 +211,19 @@ struct ConstPropState } } + void killStore(IrBlock& block, IrInst& inst) + { + if (OP_A(inst).kind == IrOpKind::VmReg && markedDead[vmRegOp(OP_A(inst))]) + { + markedDead.reset(vmRegOp(OP_A(inst))); + replace(function, block, function.getInstIndex(inst), {IrCmd::MARK_USED, {OP_A(inst), build.constInt(1)}}); + } + else + { + kill(function, inst); + } + } + void invalidate(RegisterInfo& reg, bool invalidateTag, bool invalidateValue) { if (invalidateTag) @@ -759,14 +771,12 @@ struct ConstPropState base.offset -= int(*rhsNum) * base.scale; base.op = OP_A(inst); } - else if (inst.cmd == IrCmd::MUL_NUM && lhsNum && isValidDoubleForImmediate(*lhsNum) && - (!FFlag::LuauCodegenNoZeroScale || int(*lhsNum) != 0)) + else if (inst.cmd == IrCmd::MUL_NUM && lhsNum && isValidDoubleForImmediate(*lhsNum) && int(*lhsNum) != 0) { base.scale *= int(*lhsNum); base.op = OP_B(inst); } - else if (inst.cmd == IrCmd::MUL_NUM && rhsNum && isValidDoubleForImmediate(*rhsNum) && - (!FFlag::LuauCodegenNoZeroScale || int(*rhsNum) != 0)) + else if (inst.cmd == IrCmd::MUL_NUM && rhsNum && isValidDoubleForImmediate(*rhsNum) && int(*rhsNum) != 0) { base.scale *= int(*rhsNum); base.op = OP_A(inst); @@ -1376,6 +1386,8 @@ struct ConstPropState instNoMetatable.clear(); instArraySize.clear(); + markedDead.reset(); + invalidateValuePropagation(); invalidateHeapTableData(); invalidateHeapBufferData(); @@ -1437,6 +1449,8 @@ struct ConstPropState DenseHashSet instNoMetatable; DenseHashMap instArraySize; + std::bitset<256> markedDead; + std::vector rangeEndTemp; }; @@ -1858,7 +1872,10 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& if (state.tryGetTag(source) == value) { - kill(function, inst); + if (FFlag::LuauCodegenMarkUsed) + state.killStore(block, inst); + else + kill(function, inst); } else { @@ -1892,7 +1909,10 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& { if (*prevIdx == OP_B(inst).index) { - kill(function, inst); + if (FFlag::LuauCodegenMarkUsed) + state.killStore(block, inst); + else + kill(function, inst); break; } } @@ -1910,9 +1930,16 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& if (OP_B(inst).kind == IrOpKind::Constant) { if (state.tryGetValue(OP_A(inst)) == OP_B(inst)) - kill(function, inst); + { + if (FFlag::LuauCodegenMarkUsed) + state.killStore(block, inst); + else + kill(function, inst); + } else + { state.saveValue(OP_A(inst), OP_B(inst)); + } } else { @@ -1920,7 +1947,10 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& { if (*prevIdx == OP_B(inst).index) { - kill(function, inst); + if (FFlag::LuauCodegenMarkUsed) + state.killStore(block, inst); + else + kill(function, inst); break; } } @@ -1940,9 +1970,16 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& if (OP_B(inst).kind == IrOpKind::Constant) { if (state.tryGetValue(OP_A(inst)) == OP_B(inst)) - kill(function, inst); + { + if (FFlag::LuauCodegenMarkUsed) + state.killStore(block, inst); + else + kill(function, inst); + } else + { state.saveValue(OP_A(inst), OP_B(inst)); + } } else { @@ -1950,7 +1987,10 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& { if (*prevIdx == OP_B(inst).index) { - kill(function, inst); + if (FFlag::LuauCodegenMarkUsed) + state.killStore(block, inst); + else + kill(function, inst); break; } } @@ -1969,9 +2009,16 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& if (OP_B(inst).kind == IrOpKind::Constant) { if (state.tryGetValue(OP_A(inst)) == OP_B(inst)) - kill(function, inst); + { + if (FFlag::LuauCodegenMarkUsed) + state.killStore(block, inst); + else + kill(function, inst); + } else + { state.saveValue(OP_A(inst), OP_B(inst)); + } } else { @@ -1979,7 +2026,10 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& { if (*prevIdx == OP_B(inst).index) { - kill(function, inst); + if (FFlag::LuauCodegenMarkUsed) + state.killStore(block, inst); + else + kill(function, inst); break; } } @@ -2014,7 +2064,10 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& { if (*prevIdx == OP_B(inst).index) { - kill(function, inst); + if (FFlag::LuauCodegenMarkUsed) + state.killStore(block, inst); + else + kill(function, inst); break; } } @@ -3219,6 +3272,35 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& state.substituteOrRecord(inst, index); break; + case IrCmd::MARK_USED: + { + if (FFlag::LuauCodegenMarkUsed) + { + int startReg = vmRegOp(OP_A(inst)); + int count = function.intOp(OP_B(inst)); + + int end = count == -1 ? state.maxReg : std::min(startReg + count - 1, state.maxReg); + + for (int i = startReg; i <= end; i++) + state.markedDead.reset(i); + } + break; + } + case IrCmd::MARK_DEAD: + { + if (FFlag::LuauCodegenMarkUsed) + { + int startReg = vmRegOp(OP_A(inst)); + int count = function.intOp(OP_B(inst)); + + int end = count == -1 ? state.maxReg : std::min(startReg + count - 1, state.maxReg); + + for (int i = startReg; i <= end; i++) + state.markedDead.set(i); + } + break; + } + case IrCmd::CHECK_NODE_NO_NEXT: case IrCmd::CHECK_NODE_VALUE: case IrCmd::BARRIER_TABLE_BACK: @@ -3228,8 +3310,6 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& case IrCmd::CLOSE_UPVALS: // Doesn't change memory that we track case IrCmd::CAPTURE: case IrCmd::SUBSTITUTE: - case IrCmd::MARK_USED: - case IrCmd::MARK_DEAD: case IrCmd::ADJUST_STACK_TO_REG: // Changes stack top, but not the values case IrCmd::ADJUST_STACK_TO_TOP: // Changes stack top, but not the values case IrCmd::CHECK_FASTCALL_RES: // Changes stack top, but not the values @@ -3512,17 +3592,14 @@ static void constPropInBlock(IrBuilder& build, IrBlock& block, ConstPropState& s foldConstants(build, function, block, index); - if (FFlag::LuauCodegenLimitVersionsExtra) + // If limits have been reached, substitutions and folds still apply + if (state.reachedLimits) { - // If limits have been reached, substitutions and folds still apply - if (state.reachedLimits) - { - // Fallback entry data is no longer available - if (FFlag::LuauCodegenPropagateFallbackTags && !isPseudo(inst.cmd)) - invalidateFallbackEntryTags(function, inst); + // Fallback entry data is no longer available + if (FFlag::LuauCodegenPropagateFallbackTags && !isPseudo(inst.cmd)) + invalidateFallbackEntryTags(function, inst); - continue; - } + continue; } if (FFlag::LuauCodegenPropagateFallbackTags && !isPseudo(inst.cmd)) @@ -3531,7 +3608,7 @@ static void constPropInBlock(IrBuilder& build, IrBlock& block, ConstPropState& s constPropInInst(state, build, function, block, inst, index); // Optimizations might have killed the current block - if (block.kind == IrBlockKind::Dead || (!FFlag::LuauCodegenLimitVersionsExtra && state.reachedLimits)) + if (block.kind == IrBlockKind::Dead) break; } } @@ -3560,7 +3637,7 @@ static void constPropInBlockChain(IrBuilder& build, std::vector& visite constPropInBlock(build, *block, state); // Optimizations might have killed the current block - if (block->kind == IrBlockKind::Dead || (!FFlag::LuauCodegenLimitVersionsExtra && state.reachedLimits)) + if (block->kind == IrBlockKind::Dead) break; // Blocks in a chain are guaranteed to follow each other @@ -3568,11 +3645,8 @@ static void constPropInBlockChain(IrBuilder& build, std::vector& visite block->sortkey = startSortkey; block->chainkey = chainPos++; - if (FFlag::LuauCodegenLimitVersionsExtra) - { - if (state.reachedLimits) - break; - } + if (state.reachedLimits) + break; IrInst& termInst = function.instructions[block->finish]; diff --git a/CodeGen/src/OptimizeDeadStore.cpp b/CodeGen/src/OptimizeDeadStore.cpp index 2b0a5b759..09995b734 100644 --- a/CodeGen/src/OptimizeDeadStore.cpp +++ b/CodeGen/src/OptimizeDeadStore.cpp @@ -11,6 +11,7 @@ #include "lobject.h" LUAU_FASTFLAGVARIABLE(LuauCodegenDseTrackTagInvalidation) +LUAU_FASTFLAG(LuauCodegenMarkUsed) namespace Luau { @@ -515,6 +516,16 @@ struct RemoveDeadStoreState } } + void markUsedAtExit(int start, int count) + { + CODEGEN_ASSERT(count != 0); + + int e = count == -1 ? maxReg : start + count - 1; + + for (int i = start; i <= e; i++) + info[i].ignoreAtExit = false; + } + // Common instruction visitor handling void defVarargs(uint8_t varargStart) { @@ -1276,6 +1287,16 @@ static void markDeadStoresInInst(RemoveDeadStoreState& state, IrBuilder& build, case IrCmd::MARK_DEAD: state.markUnusedAtExit(vmRegOp(OP_A(inst)), function.intOp(OP_B(inst))); break; + case IrCmd::MARK_USED: + if (FFlag::LuauCodegenMarkUsed) + { + state.markUsedAtExit(vmRegOp(OP_A(inst)), function.intOp(OP_B(inst))); + } + else + { + visitVmRegDefsUses(state, function, inst); + } + break; default: // Guards have to be covered explicitly diff --git a/CodeGen/src/SharedCodeAllocator.cpp b/CodeGen/src/SharedCodeAllocator.cpp index fb49a7015..ee684c2fb 100644 --- a/CodeGen/src/SharedCodeAllocator.cpp +++ b/CodeGen/src/SharedCodeAllocator.cpp @@ -8,6 +8,8 @@ #include #include +LUAU_FASTFLAG(LuauRuntimeFeedback) + namespace Luau { namespace CodeGen @@ -61,12 +63,16 @@ NativeModule::NativeModule( header.entryOffsetOrAddress = codeAllocationData.codeStart + reinterpret_cast(header.entryOffsetOrAddress); } - std::sort(this->nativeProtos.begin(), this->nativeProtos.end(), NativeProtoBytecodeIdLess{}); + // Anonymous 'modules' can have function sets in compilation order (from multiple source files) + if (!FFlag::LuauRuntimeFeedback || moduleId) + { + std::sort(this->nativeProtos.begin(), this->nativeProtos.end(), NativeProtoBytecodeIdLess{}); - // We should not have two NativeProtos for the same bytecode id: - CODEGEN_ASSERT( - std::adjacent_find(this->nativeProtos.begin(), this->nativeProtos.end(), NativeProtoBytecodeIdEqual{}) == this->nativeProtos.end() - ); + // We should not have two NativeProtos for the same bytecode id: + CODEGEN_ASSERT( + std::adjacent_find(this->nativeProtos.begin(), this->nativeProtos.end(), NativeProtoBytecodeIdEqual{}) == this->nativeProtos.end() + ); + } } NativeModule::~NativeModule() noexcept diff --git a/Compiler/src/Compiler.cpp b/Compiler/src/Compiler.cpp index 1a70b7eb4..a525b0b65 100644 --- a/Compiler/src/Compiler.cpp +++ b/Compiler/src/Compiler.cpp @@ -50,6 +50,7 @@ LUAU_FASTFLAGVARIABLE(LuauExportedTypesParticipateInScc) LUAU_FLAGVERSION(LuauExportedTypesParticipateInScc, 3) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAGVARIABLE(LuauCompileReuseLocalRegs) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) namespace Luau { @@ -4003,8 +4004,70 @@ struct Compiler } } + void compileStatWhileLocal(AstStatWhile* stat) + { + LUAU_ASSERT(stat->conditionLocal); + + // Optimization: condition is always false => the body never runs and the binding never matters. + if (isConstantFalse(stat->condition)) + return; + + RegScope rs(this); + + size_t oldJumps = loopJumps.size(); + size_t oldLocals = localStack.size(); + + loops.push_back({oldLocals, oldLocals, nullptr}); + hasLoops = true; + + // The condition value is re-evaluated into this register on every iteration and bound to + // conditionLocal for the duration of the body; the register persists across iterations. + uint8_t reg = allocReg(stat, 1u); + uint32_t allocpc = bytecode.getDebugPC(); + + size_t loopLabel = bytecode.emitLabel(); + + compileExprTemp(stat->condition, reg); + pushLocal(stat->conditionLocal, reg, allocpc); + + size_t exitJump = bytecode.emitLabel(); + bytecode.emitAD(LOP_JUMPIFNOT, reg, 0); + + compileStat(stat->body); + + // Close any upvalues capturing the loop-scoped binding so each iteration observes a fresh cell, + // then drop the binding from the compile-time scope. + closeLocals(oldLocals); + popLocals(oldLocals); + + size_t contLabel = bytecode.emitLabel(); + + size_t backLabel = bytecode.emitLabel(); + + setDebugLine(stat->condition); + + // Note: JUMPBACK rather than JUMP so the loop has an interruptible instruction (see compileStatWhile). + bytecode.emitAD(LOP_JUMPBACK, 0, 0); + + size_t endLabel = bytecode.emitLabel(); + + patchJump(stat, backLabel, loopLabel); + patchJump(stat, exitJump, endLabel); + + patchLoopJumps(stat, oldJumps, endLabel, contLabel); + loopJumps.resize(oldJumps); + + loops.pop_back(); + } + void compileStatWhile(AstStatWhile* stat) { + if (FFlag::DebugLuauWhileLocalSyntax && stat->conditionLocal) + { + compileStatWhileLocal(stat); + return; + } + // Optimization: condition is always false => there's no loop! if (isConstantFalse(stat->condition)) return; diff --git a/Compiler/src/CostModel.cpp b/Compiler/src/CostModel.cpp index d56bc233e..b0420554b 100644 --- a/Compiler/src/CostModel.cpp +++ b/Compiler/src/CostModel.cpp @@ -291,6 +291,9 @@ struct CostVisitor : AstVisitor { Cost condition = model(node->condition); + if (node->conditionLocal && condition.constant != 0) + vars[node->conditionLocal] = condition.constant; + loop(node->body, condition); return false; } diff --git a/Inliner/src/JitInliner.cpp b/Inliner/src/JitInliner.cpp index 277bc896f..2feaec7b5 100644 --- a/Inliner/src/JitInliner.cpp +++ b/Inliner/src/JitInliner.cpp @@ -32,6 +32,8 @@ LUAU_FASTFLAG(LuauCompileRefactorFeedback) LUAU_FASTFLAGVARIABLE(LuauBytecodeFold) LUAU_FASTFLAGVARIABLE(LuauBytecodeSlotAlloc) LUAU_FASTFLAGVARIABLE(DebugLuauBytecodeSlotAllocStats) +LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauSkipDebugLocked) using namespace Luau::Bytecode; @@ -246,6 +248,9 @@ Proto* createInlinedProto(lua_State* L, Proto* caller, Proto* target, RuntimeBcF p->bytecodeid = caller->bytecodeid; p->cost = caller->cost; + if (FFlag::LuauRuntimeFeedback || FFlag::LuauSkipDebugLocked) + p->execflags = caller->execflags; + uint32_t feedbackvecsize = caller->feedbackvecsize + target->feedbackvecsize; p->feedbackvec = luaM_newarray(L, feedbackvecsize, FeedbackVectorSlot, L->activememcat); p->feedbackvecsize = feedbackvecsize; @@ -421,13 +426,25 @@ Proto* onInlineFunction(lua_State* L, Closure* caller, Closure* target, uint32_t if (caller->env->safeenv == 0 || target->env->safeenv == 0) return nullptr; - if (isEnvDependentOrUsesSelect(targetProto, caller->env != target->env)) - return nullptr; + if (!FFlag::LuauSkipDebugLocked) + { + if (isEnvDependentOrUsesSelect(targetProto, caller->env != target->env)) + return nullptr; + } // pick the latest optimized version for inlining while (targetProto->optimized != nullptr) targetProto = targetProto->optimized; + if (FFlag::LuauSkipDebugLocked) + { + if (((callerProto->execflags | targetProto->execflags) & PEF_DEBUGLOCKED) != 0) + return nullptr; + + if (isEnvDependentOrUsesSelect(targetProto, caller->env != target->env)) + return nullptr; + } + if (callerProto->sizecode > FInt::LuauJitInlineTooLongFunSize || targetProto->sizecode > FInt::LuauJitInlineTooLongFunSize) return nullptr; diff --git a/Makefile b/Makefile index 8b7060967..42756f150 100644 --- a/Makefile +++ b/Makefile @@ -229,9 +229,9 @@ coverage: $(TESTS_TARGET) $(COMPILE_CLI_TARGET) mv default.profraw codegen.profraw $(TESTS_TARGET) -ts=Conformance --codegen --fflags=true mv default.profraw codegen-flags.profraw - $(COMPILE_CLI_TARGET) --codegennull --target=a64 --fflags=DebugLuauUserDefinedClasses=true tests/conformance + $(COMPILE_CLI_TARGET) --codegennull --target=a64 --fflags=DebugLuauUserDefinedClasses=true,DebugLuauWhileLocalSyntax=true tests/conformance mv default.profraw codegen-a64.profraw - $(COMPILE_CLI_TARGET) --codegennull --target=x64 --fflags=DebugLuauUserDefinedClasses=true tests/conformance + $(COMPILE_CLI_TARGET) --codegennull --target=x64 --fflags=DebugLuauUserDefinedClasses=true,DebugLuauWhileLocalSyntax=true tests/conformance mv default.profraw codegen-x64.profraw llvm-profdata merge *.profraw -o default.profdata rm *.profraw diff --git a/VM/include/lua.h b/VM/include/lua.h index a79f3d100..fbf8f2acf 100644 --- a/VM/include/lua.h +++ b/VM/include/lua.h @@ -386,7 +386,9 @@ LUA_API lua_Destructor lua_getuserdatadtor(lua_State* L, int tag); // 1. Cycle reset (markref == NULL): clear accumulated information about marked // native objects. // 2. Mark phase (markref != NULL): embedder must call markref for each new ref -// that is reachable from a marked native object. +// that is reachable from a marked native object and return nonzero if it +// made any progress. The GC propagates marks and repeatedly calls again +// until the embedder returns zero. // // Together, these are used to implement a fixed-point reachability algorithm // across both heaps. @@ -397,7 +399,7 @@ LUA_API lua_Destructor lua_getuserdatadtor(lua_State* L, int tag); typedef void (*lua_UserdataMark)(lua_State* L, void* ud); LUA_API void lua_setuserdatamark(lua_State* L, int tag, lua_UserdataMark markfn); typedef void (*lua_EmbedderMark)(lua_State* L, int ref); -typedef void (*lua_EmbedderGc)(lua_State* L, lua_EmbedderMark markref); +typedef int (*lua_EmbedderGc)(lua_State* L, lua_EmbedderMark markref); LUA_API void lua_setembeddergc(lua_State* L, lua_EmbedderGc fn); // APIs for interacting with embedder-managed weak references. diff --git a/VM/src/lbuffer.cpp b/VM/src/lbuffer.cpp index 0690fa7ba..adeb47bc3 100644 --- a/VM/src/lbuffer.cpp +++ b/VM/src/lbuffer.cpp @@ -7,6 +7,7 @@ #include LUAU_FASTFLAG(LuauBufferCage) +LUAU_FASTFLAG(LuauBufferSweep) Buffer* luaB_newbuffer(lua_State* L, size_t s) { @@ -14,20 +15,46 @@ Buffer* luaB_newbuffer(lua_State* L, size_t s) luaM_toobig(L); global_State* g = L->global; - Buffer* b = (FFlag::LuauBufferCage && g->cagealloc) ? luaM_newgcocaged(L, Buffer, sizebuffer(s), L->activememcat, LUA_TBUFFER) - : luaM_newgco(L, Buffer, sizebuffer(s), L->activememcat, LUA_TBUFFER); - luaC_init(L, b, LUA_TBUFFER); - b->len = unsigned(s); - memset(b->data, 0, b->len); - return b; + if (FFlag::LuauBufferSweep) + { + Buffer* b = (FFlag::LuauBufferCage && g->cagealloc) + ? luaM_newgcotagged(L, Buffer, sizebuffer(s), L->activememcat, AllocationPath::CagedRealloc, LUA_TBUFFER) + : luaM_newgcotagged(L, Buffer, sizebuffer(s), L->activememcat, AllocationPath::Frealloc, LUA_TBUFFER); + + luaC_init(L, b, LUA_TBUFFER); + b->len = unsigned(s); + memset(b->data, 0, b->len); + return b; + } + else + { + Buffer* b = (FFlag::LuauBufferCage && g->cagealloc) ? luaM_newgcocaged(L, Buffer, sizebuffer(s), L->activememcat, LUA_TBUFFER) + : luaM_newgco(L, Buffer, sizebuffer(s), L->activememcat, LUA_TBUFFER); + + luaC_init(L, b, LUA_TBUFFER); + b->len = unsigned(s); + memset(b->data, 0, b->len); + return b; + } } void luaB_freebuffer(lua_State* L, Buffer* b, lua_Page* page) { global_State* g = L->global; - if (FFlag::LuauBufferCage && g->cagealloc) - luaM_freegcocaged(L, b, sizebuffer(b->len), b->memcat, page); + + if (FFlag::LuauBufferSweep) + { + if (FFlag::LuauBufferCage && g->cagealloc) + luaM_freegcotagged(L, b, sizebuffer(b->len), b->memcat, AllocationPath::CagedRealloc, LUA_TBUFFER, page); + else + luaM_freegcotagged(L, b, sizebuffer(b->len), b->memcat, AllocationPath::Frealloc, LUA_TBUFFER, page); + } else - luaM_freegco(L, b, sizebuffer(b->len), b->memcat, page); + { + if (FFlag::LuauBufferCage && g->cagealloc) + luaM_freegcocaged(L, b, sizebuffer(b->len), b->memcat, page); + else + luaM_freegco(L, b, sizebuffer(b->len), b->memcat, page); + } } diff --git a/VM/src/ldebug.cpp b/VM/src/ldebug.cpp index 1594be1b2..b91a42102 100644 --- a/VM/src/ldebug.cpp +++ b/VM/src/ldebug.cpp @@ -13,8 +13,22 @@ #include #include +LUAU_FASTFLAG(LuauPromoteProto) +LUAU_FASTFLAGVARIABLE(LuauSkipDebugLocked) + static const char* getfuncname(Closure* cl); +static Proto* getlatestproto(Proto* p) +{ + if (FFlag::LuauPromoteProto) + { + while (p->optimized) + p = p->optimized; + } + + return p; +} + static int currentpc(lua_State* L, CallInfo* ci) { return pcRel(ci->savedpc, ci->p); @@ -406,6 +420,9 @@ void luaG_breakpoint(lua_State* L, Proto* p, int line, bool enable) p->code[i] |= op; LUAU_ASSERT(LUAU_INSN_OP(p->code[i]) == op); + if (FFlag::LuauSkipDebugLocked && enable) + p->execflags |= PEF_DEBUGLOCKED; + // currently we don't restore native code when breakpoint is disabled. // this will be addressed in the future. if (enable && p->execdata && ondisable) @@ -420,7 +437,7 @@ void luaG_breakpoint(lua_State* L, Proto* p, int line, bool enable) for (int i = 0; i < p->sizep; ++i) { - luaG_breakpoint(L, p->p[i], line, enable); + luaG_breakpoint(L, FFlag::LuauSkipDebugLocked ? getlatestproto(p->p[i]) : p->p[i], line, enable); } } @@ -517,7 +534,7 @@ static int getnextline(Proto* p, int line) for (int i = 0; i < p->sizep; ++i) { - int candidate = getnextline(p->p[i], line); + int candidate = getnextline(FFlag::LuauSkipDebugLocked ? getlatestproto(p->p[i]) : p->p[i], line); if (candidate == line) return line; @@ -534,7 +551,7 @@ int lua_breakpoint(lua_State* L, int funcindex, int line, int enabled) const TValue* func = luaA_toobject(L, funcindex); api_check(L, ttisfunction(func) && !clvalue(func)->isC); - Proto* p = clvalue(func)->l.p; + Proto* p = FFlag::LuauSkipDebugLocked ? getlatestproto(clvalue(func)->l.p) : clvalue(func)->l.p; // set the breakpoint to the next closest line with valid instructions int target = getnextline(p, line); @@ -596,6 +613,8 @@ void lua_getcoverage(lua_State* L, int funcindex, void* context, lua_Coverage ca static void getcounters(lua_State* L, Proto* p, void* context, lua_CounterFunction functionvisit, lua_CounterValue countervisit) { + p = getlatestproto(p); + if (p->execdata != nullptr && L->global->ecb.getcounterdata != nullptr) { size_t count = 0; diff --git a/VM/src/lfunc.cpp b/VM/src/lfunc.cpp index b898467b0..ce1c43317 100644 --- a/VM/src/lfunc.cpp +++ b/VM/src/lfunc.cpp @@ -27,6 +27,8 @@ Proto* luaF_newproto(lua_State* L) f->execdata = NULL; f->exectarget = 0; + f->execcount = 0; + f->execflags = 0; f->lineinfo = NULL; f->abslineinfo = NULL; diff --git a/VM/src/lgc.cpp b/VM/src/lgc.cpp index 5425a42a7..67e3e71cf 100644 --- a/VM/src/lgc.cpp +++ b/VM/src/lgc.cpp @@ -19,10 +19,12 @@ #include LUAU_FASTFLAGVARIABLE(LuauGcTraceUdata) -LUAU_FLAGVERSION(LuauGcTraceUdata, 4) +LUAU_FLAGVERSION(LuauGcTraceUdata, 5) LUAU_FASTFLAG(LuauFastpcall) LUAU_FASTFLAG(LuauCoroutineFinally) LUAU_DYNAMIC_FASTFLAGVARIABLE(LuauGcHeapShrinkFix, false) +LUAU_FASTFLAGVARIABLE(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauBufferSweep) /* * Luau uses an incremental non-generational non-moving mark&sweep garbage collector. @@ -419,6 +421,12 @@ static void traverseproto(global_State* g, Proto* f) if (f->deoptimized) markobject(g, f->deoptimized); + + if (FFlag::LuauRuntimeFeedback && g->ecb.examinefunction) + { + if ((f->execflags & PEF_EXECLOCKED) == 0) + g->ecb.examinefunction(g->mainthread, f); + } } static void traverseclosure(global_State* g, Closure* cl) @@ -812,6 +820,21 @@ static void freeobj(lua_State* L, GCObject* o, lua_Page* page) } } +template +static void freeobjtagged(lua_State* L, GCObject* o, lua_Page* page); + +template<> +void freeobjtagged(lua_State* L, GCObject* o, lua_Page* page) +{ + luaB_freebuffer(L, gco2buf(o), page); +} + +template<> +void freeobjtagged<-1>(lua_State* L, GCObject* o, lua_Page* page) +{ + freeobj(L, o, page); +} + static void stringresizeprotected(lua_State* L, int newsize) { struct CallContext @@ -1056,11 +1079,9 @@ static size_t atomic(lua_State* L) // fixed-point algorithm for embedder references if (FFlag::LuauGcTraceUdata && g->embeddergc) { - g->embeddergc(g->mainthread, embeddermarkref); - while (g->gray) + while (g->embeddergc(g->mainthread, embeddermarkref) != 0) { work += propagateall(g); - g->embeddergc(g->mainthread, embeddermarkref); } } @@ -1088,12 +1109,22 @@ static size_t atomic(lua_State* L) g->currentwhite = cast_byte(otherwhite(g)); g->sweepgcopage = g->allgcopages; g->sweepgcopage_cage = g->allgcopages_cage; + + if (FFlag::LuauBufferSweep) + { + g->sweeppageset = 0; + + for (int i = 0; i < TAGGED_PAGESET_SIZE; i++) + g->taggedpageset[i].sweeppage = g->taggedpageset[i].allpages; + } + g->gcstate = GCSsweep; return work; } // a version of generic luaM_visitpage specialized for the main sweep stage +template static int sweepgcopage(lua_State* L, lua_Page* page) { char* start; @@ -1129,7 +1160,18 @@ static int sweepgcopage(lua_State* L, lua_Page* page) else { LUAU_ASSERT(isdead(g, gco)); - freeobj(L, gco, page); + + if (FFlag::LuauBufferSweep) + { + if (Type == -1) + freeobj(L, gco, page); + else + freeobjtagged(L, gco, page); + } + else + { + freeobj(L, gco, page); + } // if the last block was removed, page would be removed as well if (--busyBlocks == 0) @@ -1140,6 +1182,34 @@ static int sweepgcopage(lua_State* L, lua_Page* page) return int(end - start) / blockSize; } +static size_t sweeppageset(lua_State* L, lua_Page*& pageset, size_t cost, size_t limit, int type) +{ + while (pageset && cost < limit) + { + lua_Page* next = luaM_getnextpage(pageset); // page sweep might destroy the page + + int steps = 0; + + switch (type) + { + case -1: + steps = sweepgcopage<-1>(L, pageset); + break; + case LUA_TBUFFER: + steps = sweepgcopage(L, pageset); + break; + default: + LUAU_ASSERT(!"unexpected sweep pageset type"); + break; + } + + pageset = next; + cost += static_cast(steps * GC_SWEEPPAGESTEPCOST); + } + + return cost; +} + static size_t gcstep(lua_State* L, size_t limit) { size_t cost = 0; @@ -1208,36 +1278,75 @@ static size_t gcstep(lua_State* L, size_t limit) } case GCSsweep: { - while (g->sweepgcopage && cost < limit) + if (FFlag::LuauBufferSweep) { - lua_Page* next = luaM_getnextpage(g->sweepgcopage); // page sweep might destroy the page + bool done = false; - int steps = sweepgcopage(L, g->sweepgcopage); + while (cost < limit && !done) + { + if (g->sweepgcopage) + cost = sweeppageset(L, g->sweepgcopage, cost, limit, -1); + else if (g->sweepgcopage_cage) + cost = sweeppageset(L, g->sweepgcopage_cage, cost, limit, -1); + else if (g->sweeppageset < TAGGED_PAGESET_SIZE && g->taggedpageset[g->sweeppageset].sweeppage) + cost = sweeppageset(L, g->taggedpageset[g->sweeppageset].sweeppage, cost, limit, g->sweeppageset + TAGGED_PAGESET_BASE); + else if (g->sweeppageset < TAGGED_PAGESET_SIZE) + g->sweeppageset++; + else + done = true; + } - g->sweepgcopage = next; - cost += static_cast(steps * GC_SWEEPPAGESTEPCOST); - } + // nothing more to sweep? + if (done) + { + // don't forget to visit main thread, it's the only object not allocated in GCO pages + LUAU_ASSERT(!isdead(g, obj2gco(g->mainthread))); + makewhite(g, obj2gco(g->mainthread)); // make it white (for next cycle) - while (g->sweepgcopage_cage && cost < limit) - { - lua_Page* next = luaM_getnextpage(g->sweepgcopage_cage); // page sweep might destroy the page + shrinkbuffers(L); - int steps = sweepgcopage(L, g->sweepgcopage_cage); + g->gcstate = GCSpause; // end collection - g->sweepgcopage_cage = next; - cost += static_cast(steps * GC_SWEEPPAGESTEPCOST); + if (FFlag::LuauRuntimeFeedback && g->ecb.commitfunctions) + g->ecb.commitfunctions(g->mainthread); + } } - - // nothing more to sweep? - if (g->sweepgcopage == NULL && g->sweepgcopage_cage == NULL) + else { - // don't forget to visit main thread, it's the only object not allocated in GCO pages - LUAU_ASSERT(!isdead(g, obj2gco(g->mainthread))); - makewhite(g, obj2gco(g->mainthread)); // make it white (for next cycle) + while (g->sweepgcopage && cost < limit) + { + lua_Page* next = luaM_getnextpage(g->sweepgcopage); // page sweep might destroy the page + + int steps = sweepgcopage(L, g->sweepgcopage); + + g->sweepgcopage = next; + cost += static_cast(steps * GC_SWEEPPAGESTEPCOST); + } + + while (g->sweepgcopage_cage && cost < limit) + { + lua_Page* next = luaM_getnextpage(g->sweepgcopage_cage); // page sweep might destroy the page + + int steps = sweepgcopage(L, g->sweepgcopage_cage); + + g->sweepgcopage_cage = next; + cost += static_cast(steps * GC_SWEEPPAGESTEPCOST); + } + + // nothing more to sweep? + if (g->sweepgcopage == NULL && g->sweepgcopage_cage == NULL) + { + // don't forget to visit main thread, it's the only object not allocated in GCO pages + LUAU_ASSERT(!isdead(g, obj2gco(g->mainthread))); + makewhite(g, obj2gco(g->mainthread)); // make it white (for next cycle) - shrinkbuffers(L); + shrinkbuffers(L); - g->gcstate = GCSpause; // end collection + g->gcstate = GCSpause; // end collection + + if (FFlag::LuauRuntimeFeedback && g->ecb.commitfunctions) + g->ecb.commitfunctions(g->mainthread); + } } break; } @@ -1396,6 +1505,15 @@ void luaC_fullgc(lua_State* L) // reset sweep marks to sweep all elements (returning them to white) g->sweepgcopage = g->allgcopages; g->sweepgcopage_cage = g->allgcopages_cage; + + if (FFlag::LuauBufferSweep) + { + g->sweeppageset = 0; + + for (int i = 0; i < TAGGED_PAGESET_SIZE; i++) + g->taggedpageset[i].sweeppage = g->taggedpageset[i].allpages; + } + // reset other collector lists g->gray = NULL; g->grayagain = NULL; diff --git a/VM/src/lmem.cpp b/VM/src/lmem.cpp index aa7a52bab..c698256f1 100644 --- a/VM/src/lmem.cpp +++ b/VM/src/lmem.cpp @@ -9,6 +9,8 @@ #include LUAU_FASTFLAG(LuauBufferCage) +LUAU_FASTFLAGVARIABLE(LuauBufferSweep) +LUAU_FASTFLAGVARIABLE(LuauCageSplitData) /* * Luau heap uses a size-segregated page structure, with individual pages and large allocations @@ -225,11 +227,17 @@ struct lua_Page int freeNext; // next free block offset in this page, in bytes; when negative, freeList is used instead int busyBlocks; // number of blocks allocated out of this page + int flags; + // provide additional padding based on current object size to provide 16 byte alignment of data // later static_assert checks that this requirement is held - char padding[sizeof(void*) == 8 ? 8 : 12]; + char padding[sizeof(void*) == 8 ? 4 : 8]; - char data[1]; + union + { + char data[1]; + char* dataptr; + }; }; static_assert(offsetof(lua_Page, data) % 16 == 0, "data must be 16 byte aligned to provide properly aligned allocation of userdata objects"); @@ -239,39 +247,50 @@ l_noret luaM_toobig(lua_State* L) luaG_runerror(L, "memory allocation error: block too big"); } -enum class AllocationPath -{ - Frealloc, - BufferFrealloc -}; - +// Remove with FFlagLuauCageSplitData template -static LUAU_FORCEINLINE void* pagealloc(global_State* g, void* block, size_t oldsize, size_t newsize) +static LUAU_FORCEINLINE void* pagealloc_DEPRECATED(global_State* g, void* block, size_t oldsize, size_t newsize) { - if (path == AllocationPath::BufferFrealloc) + if (path == AllocationPath::CagedRealloc) return (*g->cagealloc)(g->cageud, block, oldsize, newsize, type); else return (*g->frealloc)(g->ud, block, oldsize, newsize); } -template +template static LUAU_FORCEINLINE lua_Page** freegcopages(global_State* g) { - if (path == AllocationPath::BufferFrealloc) + if (FFlag::LuauBufferSweep && type == LUA_TBUFFER) + { + LUAU_ASSERT(unsigned(type - TAGGED_PAGESET_BASE) < TAGGED_PAGESET_SIZE); + return g->taggedpageset[type - TAGGED_PAGESET_BASE].freepages; + } + + if (path == AllocationPath::CagedRealloc) return g->freegcopages_cage; else return g->freegcopages; } -template +template static LUAU_FORCEINLINE lua_Page** allgcopages(global_State* g) { - if (path == AllocationPath::BufferFrealloc) + if (FFlag::LuauBufferSweep && type == LUA_TBUFFER) + { + LUAU_ASSERT(unsigned(type - TAGGED_PAGESET_BASE) < TAGGED_PAGESET_SIZE); + return &g->taggedpageset[type - TAGGED_PAGESET_BASE].allpages; + } + + if (path == AllocationPath::CagedRealloc) return &g->allgcopages_cage; else return &g->allgcopages; } +template +static void* newblock(lua_State* L, int sizeClass); +static void freeblock(lua_State* L, int sizeClass, void* block); + template static lua_Page* newpage(lua_State* L, lua_Page** pageset, int pageSize, int blockSize, int blockCount) { @@ -279,7 +298,20 @@ static lua_Page* newpage(lua_State* L, lua_Page** pageset, int pageSize, int blo LUAU_ASSERT(pageSize - int(offsetof(lua_Page, data)) >= blockSize * blockCount); - lua_Page* page = (lua_Page*)pagealloc(g, NULL, 0, pageSize); + lua_Page* page; + + if (FFlag::LuauCageSplitData) + { + if (path == AllocationPath::CagedRealloc) + page = (lua_Page*)newblock(L, sizeclass(sizeof(lua_Page))); + else + page = (lua_Page*)(*g->frealloc)(g->ud, nullptr, 0, pageSize); + } + else + { + page = (lua_Page*)pagealloc_DEPRECATED(g, NULL, 0, pageSize); + } + if (!page) { if (nothrow) @@ -288,7 +320,27 @@ static lua_Page* newpage(lua_State* L, lua_Page** pageset, int pageSize, int blo luaD_throw(L, LUA_ERRMEM); } - ASAN_POISON_MEMORY_REGION(page->data, blockSize * blockCount); + if (FFlag::LuauCageSplitData && path == AllocationPath::CagedRealloc) + { + LUAU_ASSERT(g->cagealloc); + page->dataptr = (char*)(*g->cagealloc)(g->cageud, nullptr, 0, size_t(blockSize * blockCount), type); + + if (!page->dataptr) + { + freeblock(L, sizeclass(sizeof(lua_Page)), page); + + if (nothrow) + return nullptr; + else + luaD_throw(L, LUA_ERRMEM); + } + + ASAN_POISON_MEMORY_REGION(page->dataptr, size_t(blockSize * blockCount)); + } + else + { + ASAN_POISON_MEMORY_REGION(page->data, blockSize * blockCount); + } // setup page header page->prev = NULL; @@ -307,6 +359,9 @@ static lua_Page* newpage(lua_State* L, lua_Page** pageset, int pageSize, int blo page->freeNext = (blockCount - 1) * blockSize; page->busyBlocks = 0; + if (FFlag::LuauCageSplitData) + page->flags = path == AllocationPath::CagedRealloc ? 1 : 0; + if (pageset) { page->listnext = *pageset; @@ -355,10 +410,33 @@ static void freepage(lua_State* L, lua_Page** pageset, lua_Page* page) *pageset = page->listnext; } - ASAN_UNPOISON_MEMORY_REGION(page, page->pageSize); + if (FFlag::LuauCageSplitData) + { + if (path == AllocationPath::CagedRealloc) + { + int blockCount = (page->pageSize - offsetof(lua_Page, data)) / page->blockSize; + int dataSize = page->blockSize * blockCount; + + ASAN_UNPOISON_MEMORY_REGION(page->dataptr, dataSize); - // so long - pagealloc(g, page, page->pageSize, 0); + LUAU_ASSERT(g->cagealloc); + (*g->cagealloc)(g->cageud, page->dataptr, dataSize, 0, type); + freeblock(L, sizeclass(sizeof(lua_Page)), page); + } + else + { + ASAN_UNPOISON_MEMORY_REGION(page, page->pageSize); + + (*g->frealloc)(g->ud, page, page->pageSize, 0); + } + } + else + { + ASAN_UNPOISON_MEMORY_REGION(page, page->pageSize); + + // so long + pagealloc_DEPRECATED(g, page, page->pageSize, 0); + } } template @@ -434,8 +512,8 @@ template static LUAU_FORCEINLINE void* newgcoblock(lua_State* L, int sizeClass) { global_State* g = L->global; - lua_Page** freepages = freegcopages(g); - lua_Page** allpages = allgcopages(g); + lua_Page** freepages = freegcopages(g); + lua_Page** allpages = allgcopages(g); lua_Page* page = freepages[sizeClass]; @@ -451,7 +529,10 @@ static LUAU_FORCEINLINE void* newgcoblock(lua_State* L, int sizeClass) if (page->freeNext >= 0) { - block = &page->data + page->freeNext; + if (FFlag::LuauCageSplitData && path == AllocationPath::CagedRealloc) + block = page->dataptr + page->freeNext; + else + block = &page->data + page->freeNext; ASAN_UNPOISON_MEMORY_REGION(block, page->blockSize); page->freeNext -= page->blockSize; @@ -490,7 +571,11 @@ static void freeblock(lua_State* L, int sizeClass, void* block) lua_Page* page = (lua_Page*)metadata(block); LUAU_ASSERT(page && page->busyBlocks > 0); LUAU_ASSERT(size_t(page->blockSize) == kSizeClassConfig.sizeOfClass[sizeClass] + kBlockHeader); - LUAU_ASSERT(block >= page->data && block < (char*)page + page->pageSize); + + if (FFlag::LuauCageSplitData && page->flags == 1) + LUAU_ASSERT(block >= page->dataptr && block < page->dataptr + (page->pageSize - offsetof(lua_Page, data))); + else + LUAU_ASSERT(block >= page->data && block < (char*)page + page->pageSize); // if the page wasn't in the page free list, it should be now since it got a block! if (!page->freeList && page->freeNext < 0) @@ -522,11 +607,15 @@ static LUAU_FORCEINLINE void freegcoblock(lua_State* L, int sizeClass, void* blo { LUAU_ASSERT(page && page->busyBlocks > 0); LUAU_ASSERT(page->blockSize == kSizeClassConfig.sizeOfClass[sizeClass]); - LUAU_ASSERT(block >= page->data && block < (char*)page + page->pageSize); + + if (FFlag::LuauCageSplitData && path == AllocationPath::CagedRealloc) + LUAU_ASSERT(block >= page->dataptr && block < page->dataptr + (page->pageSize - offsetof(lua_Page, data))); + else + LUAU_ASSERT(block >= page->data && block < (char*)page + page->pageSize); global_State* g = L->global; - lua_Page** freepages = freegcopages(g); - lua_Page** allpages = allgcopages(g); + lua_Page** freepages = freegcopages(g); + lua_Page** allpages = allgcopages(g); // if the page wasn't in the page free list, it should be now since it got a block! if (!page->freeList && page->freeNext < 0) @@ -652,15 +741,17 @@ GCObject* luaM_newgcocaged_(lua_State* L, size_t nsize, uint8_t memcat, int tt, if (nclass >= 0) { - block = newgcoblock(L, nclass); + block = newgcoblock(L, nclass); } else { - lua_Page* page = newpage( - L, &g->allgcopages_cage, offsetof(lua_Page, data) + int(nsize), int(nsize), 1 - ); + lua_Page* page = + newpage(L, &g->allgcopages_cage, offsetof(lua_Page, data) + int(nsize), int(nsize), 1); - block = &page->data; + if (FFlag::LuauCageSplitData) + block = page->dataptr; + else + block = &page->data; ASAN_UNPOISON_MEMORY_REGION(block, page->blockSize); page->freeNext -= page->blockSize; @@ -681,6 +772,54 @@ GCObject* luaM_newgcocaged_(lua_State* L, size_t nsize, uint8_t memcat, int tt, return (GCObject*)block; } +template +GCObject* luaM_newgcotagged_(lua_State* L, size_t nsize, uint8_t memcat) +{ + // we need to accommodate space for link for free blocks (freegcolink) + LUAU_ASSERT(nsize >= kGCOLinkOffset + sizeof(void*)); + + global_State* g = L->global; + + int nclass = sizeclass(nsize); + + void* block = NULL; + + if (nclass >= 0) + { + block = newgcoblock(L, nclass); + } + else + { + lua_Page* page = newpage(L, allgcopages(g), offsetof(lua_Page, data) + int(nsize), int(nsize), 1); + + if (FFlag::LuauCageSplitData && path == AllocationPath::CagedRealloc) + block = page->dataptr; + else + block = &page->data; + ASAN_UNPOISON_MEMORY_REGION(block, page->blockSize); + + page->freeNext -= page->blockSize; + page->busyBlocks++; + } + + if (block == NULL && nsize > 0) + luaD_throw(L, LUA_ERRMEM); + + g->totalbytes += nsize; + g->memcatbytes[memcat] += nsize; + + if (LUAU_UNLIKELY(!!g->cb.onallocate)) + { + g->cb.onallocate(L, block, 0, nsize, memcat, type, 0); + } + + return (GCObject*)block; +} + +// Instantiations for known uses +template GCObject* luaM_newgcotagged_(lua_State* L, size_t, uint8_t); +template GCObject* luaM_newgcotagged_(lua_State* L, size_t, uint8_t); + GCObject* luaM_newgcofixed_(lua_State* L, size_t nsize, uint8_t memcat, int tt) { // we need to accommodate space for link for free blocks (freegcolink) @@ -797,21 +936,65 @@ void luaM_freegcocaged_(lua_State* L, GCObject* block, size_t osize, uint8_t mem { block->gch.tt = LUA_TNIL; - freegcoblock(L, oclass, block, page); + freegcoblock(L, oclass, block, page); } else { LUAU_ASSERT(page->busyBlocks == 1); LUAU_ASSERT(size_t(page->blockSize) == osize); - LUAU_ASSERT((void*)block == page->data); - freepage(L, &g->allgcopages_cage, page); + if (FFlag::LuauCageSplitData) + LUAU_ASSERT((void*)block == page->dataptr); + else + LUAU_ASSERT((void*)block == page->data); + + freepage(L, &g->allgcopages_cage, page); } g->totalbytes -= osize; g->memcatbytes[memcat] -= osize; } +template +LUAI_FUNC void luaM_freegcotagged_(lua_State* L, GCObject* block, size_t osize, uint8_t memcat, lua_Page* page) +{ + global_State* g = L->global; + LUAU_ASSERT((osize == 0) == (block == NULL)); + + if (LUAU_UNLIKELY(!!g->cb.onfree)) + { + g->cb.onfree(L, block); + } + + int oclass = sizeclass(page->blockSize); + + if (oclass >= 0) + { + block->gch.tt = LUA_TNIL; + + freegcoblock(L, oclass, block, page); + } + else + { + LUAU_ASSERT(page->busyBlocks == 1); + LUAU_ASSERT(size_t(page->blockSize) == osize); + + if (FFlag::LuauCageSplitData && path == AllocationPath::CagedRealloc) + LUAU_ASSERT((void*)block == page->dataptr); + else + LUAU_ASSERT((void*)block == page->data); + + freepage(L, allgcopages(g), page); + } + + g->totalbytes -= osize; + g->memcatbytes[memcat] -= osize; +} + +// Instantiations for known uses +template void luaM_freegcotagged_(lua_State* L, GCObject*, size_t, uint8_t, lua_Page*); +template void luaM_freegcotagged_(lua_State* L, GCObject*, size_t, uint8_t, lua_Page*); + void* luaM_realloc_(lua_State* L, void* block, size_t osize, size_t nsize, uint8_t memcat) { global_State* g = L->global; @@ -866,7 +1049,7 @@ void luaM_getpagewalkinfo(lua_Page* page, char** start, char** end, int* busyBlo LUAU_ASSERT(page->freeNext >= -page->blockSize && page->freeNext <= (blockCount - 1) * page->blockSize); - char* data = page->data; // silences ubsan when indexing page->data + char* data = FFlag::LuauCageSplitData && page->flags == 1 ? page->dataptr : page->data; // silences ubsan when indexing page->data *start = data + page->freeNext + page->blockSize; *end = data + blockCount * page->blockSize; @@ -936,4 +1119,21 @@ void luaM_visitgco(lua_State* L, void* context, bool (*visitor)(void* context, l curr = next; } + + if (FFlag::LuauBufferSweep) + { + for (int i = 0; i < TAGGED_PAGESET_SIZE; i++) + { + LuauPageset& pageset = g->taggedpageset[i]; + + for (lua_Page* curr = pageset.allpages; curr;) + { + lua_Page* next = curr->listnext; // block visit might destroy the page + + luaM_visitpage(curr, context, visitor); + + curr = next; + } + } + } } diff --git a/VM/src/lmem.h b/VM/src/lmem.h index 1b00ddab6..f0c2e5878 100644 --- a/VM/src/lmem.h +++ b/VM/src/lmem.h @@ -7,13 +7,21 @@ struct lua_Page; union GCObject; +enum class AllocationPath +{ + Frealloc, + CagedRealloc +}; + #define luaM_newgco(L, t, size, memcat, tt) cast_to(t*, luaM_newgco_(L, size, memcat, tt, 0)) #define luaM_newgcoudata(L, t, size, memcat, tt, tag) cast_to(t*, luaM_newgco_(L, size, memcat, tt, tag)) #define luaM_newgcofixed(L, t, size, memcat, tt) cast_to(t*, luaM_newgcofixed_(L, size, memcat, tt)) #define luaM_newgcocaged(L, t, size, memcat, tt) cast_to(t*, luaM_newgcocaged_(L, size, memcat, tt, 0)) +#define luaM_newgcotagged(L, t, size, memcat, path, tt) cast_to(t*, (luaM_newgcotagged_(L, size, memcat))) #define luaM_freegco(L, p, size, memcat, page) luaM_freegco_(L, obj2gco(p), size, memcat, page) #define luaM_freegcofixed(L, p, size, memcat, page) luaM_freegcofixed_(L, obj2gco(p), size, memcat, page) #define luaM_freegcocaged(L, p, size, memcat, page) luaM_freegcocaged_(L, obj2gco(p), size, memcat, page) +#define luaM_freegcotagged(L, p, size, memcat, path, tt, page) luaM_freegcotagged_(L, obj2gco(p), size, memcat, page) #define luaM_arraysize_(L, n, e) ((cast_to(size_t, (n)) <= SIZE_MAX / (e)) ? (n) * (e) : (luaM_toobig(L), SIZE_MAX)) @@ -28,10 +36,18 @@ LUAI_FUNC void* luaM_trynew_(lua_State* L, size_t nsize, uint8_t memcat); LUAI_FUNC GCObject* luaM_newgco_(lua_State* L, size_t nsize, uint8_t memcat, int tt, int tag); LUAI_FUNC GCObject* luaM_newgcofixed_(lua_State* L, size_t nsize, uint8_t memcat, int tt); LUAI_FUNC GCObject* luaM_newgcocaged_(lua_State* L, size_t nsize, uint8_t memcat, int tt, int tag); + +template +LUAI_FUNC GCObject* luaM_newgcotagged_(lua_State* L, size_t nsize, uint8_t memcat); + LUAI_FUNC void luaM_free_(lua_State* L, void* block, size_t osize, uint8_t memcat); LUAI_FUNC void luaM_freegco_(lua_State* L, GCObject* block, size_t osize, uint8_t memcat, lua_Page* page); LUAI_FUNC void luaM_freegcofixed_(lua_State* L, GCObject* block, size_t osize, uint8_t memcat, lua_Page* page); LUAI_FUNC void luaM_freegcocaged_(lua_State* L, GCObject* block, size_t osize, uint8_t memcat, lua_Page* page); + +template +LUAI_FUNC void luaM_freegcotagged_(lua_State* L, GCObject* block, size_t osize, uint8_t memcat, lua_Page* page); + LUAI_FUNC void* luaM_realloc_(lua_State* L, void* block, size_t osize, size_t nsize, uint8_t memcat); LUAI_FUNC l_noret luaM_toobig(lua_State* L); diff --git a/VM/src/lobject.h b/VM/src/lobject.h index 84d2d54bd..4039867e5 100644 --- a/VM/src/lobject.h +++ b/VM/src/lobject.h @@ -373,6 +373,12 @@ struct FeedbackVectorSlot }; }; +enum ProtoExecFlag +{ + PEF_EXECLOCKED = 1 << 0, // function will no longer be examined by custom execution + PEF_DEBUGLOCKED = 1 << 1, // bytecode can have breakpoints in it +}; + /* ** Function Prototypes */ @@ -395,6 +401,9 @@ typedef struct Proto void* execdata; uintptr_t exectarget; + uint32_t execcount; + uint8_t execflags; + uint8_t* lineinfo; // for each instruction, line number as a delta from baseline int* abslineinfo; // baseline line info, one entry for each 1<freepages[i] == NULL); LUAU_ASSERT(g->freegcopages[i] == NULL); LUAU_ASSERT(g->freegcopages_cage[i] == NULL); + + for (int set = 0; set < TAGGED_PAGESET_SIZE; set++) + LUAU_ASSERT(g->taggedpageset[set].freepages[i] == NULL); } LUAU_ASSERT(g->allgcopages == NULL); LUAU_ASSERT(g->allgcopages_cage == NULL); + + for (int set = 0; set < TAGGED_PAGESET_SIZE; set++) + LUAU_ASSERT(g->taggedpageset[set].allpages == NULL); + LUAU_ASSERT(g->totalbytes == sizeof(LG)); LUAU_ASSERT(g->memcatbytes[0] == sizeof(LG)); for (int i = 1; i < LUA_MEMORY_CATEGORIES; i++) diff --git a/VM/src/lstate.h b/VM/src/lstate.h index 15590cee8..f87c4655d 100644 --- a/VM/src/lstate.h +++ b/VM/src/lstate.h @@ -78,6 +78,9 @@ typedef struct CallInfo #define LUA_CALLINFO_OPYIELD (1 << 3) // call frame has yielded on a non-call opcode and requires luau_finishop #define LUA_CALLINFO_PCALL (1 << 4) // call frame was setup by a synthetic protected call and requires luau_pospcallsuccess +#define TAGGED_PAGESET_BASE (LUA_TSTRING) +#define TAGGED_PAGESET_SIZE (LUA_T_COUNT - TAGGED_PAGESET_BASE) + #define curr_func(L) (clvalue(L->ci->func)) #define ci_func(ci) (clvalue((ci)->func)) #define f_isLua(ci) (!ci_func(ci)->isC) @@ -171,6 +174,12 @@ struct lua_ExecutionCallbacks size_t* count ); // called to get the execution counter data and count {uint32_t, uint32_t, uint64_t} Proto* (*inlinefunction)(lua_State* L, Closure* caller, Closure* target, uint32_t pc); // called when inlining threshold is reached + + // called when GC marks the function unless opted out with PEF_EXECLOCKED to examine if an action on a function will be needed later + void (*examinefunction)(lua_State* L, Proto* proto); + // called when GC cycle has been completed and the collector is paused + // functions previoulsy recorded by 'examinefunction' can be processed safely + void (*commitfunctions)(lua_State* L); }; struct lua_UdataDirectAccessData @@ -183,6 +192,13 @@ struct lua_UdataDirectAccessData lua_UserdataDirectNamecall namecall; }; +struct LuauPageset +{ + struct lua_Page* freepages[LUA_SIZECLASSES]; // cage GCO free pages, per size class + struct lua_Page* allpages; // all cage GCO pages (sweep target) + struct lua_Page* sweeppage; // sweep cursor +}; + /* ** `global state', shared by all threads of this state */ @@ -245,6 +261,9 @@ typedef struct global_State // Set of userdata __index/__newindex/__namecall metamethods for a direct access lua_UdataDirectAccessData udatadirect[UTAG_INTERNAL_LIMIT]; + LuauPageset taggedpageset[TAGGED_PAGESET_SIZE]; // Page sets which only hold allocations for a specific GCO type + int sweeppageset; // Which array is being swept + size_t memcatbytes[LUA_MEMORY_CATEGORIES]; // total amount of memory used by each memory category void (*udatagc[LUA_UTAG_LIMIT])(lua_State*, void*); // for each userdata tag, a gc callback to be called immediately before freeing memory diff --git a/VM/src/lvmexecute.cpp b/VM/src/lvmexecute.cpp index d197919ad..4abccd2bd 100644 --- a/VM/src/lvmexecute.cpp +++ b/VM/src/lvmexecute.cpp @@ -21,6 +21,7 @@ LUAU_FASTFLAGVARIABLE(DebugLuauUserDefinedClassesRuntime) LUAU_FASTFLAGVARIABLE(LuauPromoteProto) LUAU_FASTFLAG(LuauFastpcall) +LUAU_FASTFLAG(LuauRuntimeFeedback) // Disable c99-designator to avoid the warning in computed goto dispatch table #ifdef __clang__ @@ -235,6 +236,15 @@ static LUAU_NOINLINE void luau_setupcci(lua_State* L, int nresults, StkId fun) LUAU_ASSERT(ttisfunction(ci->func)); } +// Batch addition of loop execution counter increments +static void luau_addexeccount(Proto* p, double count) +{ + // Leaving room for regular counter hits to not overflow too fast + uint32_t space = UINT32_MAX / 4 - p->execcount; + + p->execcount += count < double(space) ? uint32_t(count) : space; +} + template static void luau_execute(lua_State* L) { @@ -1090,6 +1100,9 @@ static void luau_execute(lua_State* L) { Proto* p = ccl->l.p; + if (FFlag::LuauRuntimeFeedback) + p->execcount++; + // fill unused parameters with nil StkId argi = L->top; StkId argend = L->base + p->numparams; @@ -1193,6 +1206,9 @@ static void luau_execute(lua_State* L) { Proto* p = ccl->l.p; + if (FFlag::LuauRuntimeFeedback) + p->execcount++; + if (feedback_slot != LUAU_INSN_FBSLOT_SEALED) { if (!luaF_recordhit(L, cl, ccl, feedback_slot)) @@ -2527,7 +2543,18 @@ static void luau_execute(lua_State* L) double idx = nvalue(ra + 2); // Note: make sure the loop condition is exactly the same between this and LOP_FORNLOOP so that we handle NaN/etc. consistently - pc += (step > 0 ? idx <= limit : limit <= idx) ? 0 : LUAU_INSN_D(insn); + if (FFlag::LuauRuntimeFeedback) + { + if (step > 0 ? idx <= limit : limit <= idx) + luau_addexeccount(L->ci->p, (limit - idx) / step + 1); + else + pc += LUAU_INSN_D(insn); + } + else + { + pc += (step > 0 ? idx <= limit : limit <= idx) ? 0 : LUAU_INSN_D(insn); + } + VM_ASSERT_PC(pc); VM_NEXT(); } @@ -2613,6 +2640,9 @@ static void luau_execute(lua_State* L) } else if (ttistable(ra)) { + if (FFlag::LuauRuntimeFeedback) + luau_addexeccount(L->ci->p, hvalue(ra)->sizearray + sizenode(hvalue(ra))); + // set up registers for builtin iteration setobj2s(L, ra + 1, ra); setpvalue(ra + 2, reinterpret_cast(uintptr_t(0)), LU_TAG_ITERATOR); @@ -2664,6 +2694,9 @@ static void luau_execute(lua_State* L) } else if (ttistable(ra)) { + if (FFlag::LuauRuntimeFeedback) + luau_addexeccount(L->ci->p, hvalue(ra)->sizearray + sizenode(hvalue(ra))); + // set up registers for builtin iteration setobj2s(L, ra + 1, ra); setpvalue(ra + 2, reinterpret_cast(uintptr_t(0)), LU_TAG_ITERATOR); @@ -2759,6 +2792,9 @@ static void luau_execute(lua_State* L) } else { + if (FFlag::LuauRuntimeFeedback) + L->ci->p->execcount++; + // note: it's safe to push arguments past top for complicated reasons (see top of the file) setobj2s(L, ra + 3 + 2, ra + 2); setobj2s(L, ra + 3 + 1, ra + 1); @@ -2796,6 +2832,9 @@ static void luau_execute(lua_State* L) // fast-path: ipairs/inext if (cl->env->safeenv && ttistable(ra + 1) && ttisnumber(ra + 2) && nvalue(ra + 2) == 0.0) { + if (FFlag::LuauRuntimeFeedback) + luau_addexeccount(L->ci->p, hvalue(ra + 1)->sizearray); + setnilvalue(ra); // ra+1 is already the table setpvalue(ra + 2, reinterpret_cast(uintptr_t(0)), LU_TAG_ITERATOR); @@ -2819,6 +2858,9 @@ static void luau_execute(lua_State* L) // fast-path: pairs/next if (cl->env->safeenv && ttistable(ra + 1) && ttisnil(ra + 2)) { + if (FFlag::LuauRuntimeFeedback) + luau_addexeccount(L->ci->p, hvalue(ra + 1)->sizearray + sizenode(hvalue(ra + 1))); + setnilvalue(ra); // ra+1 is already the table setpvalue(ra + 2, reinterpret_cast(uintptr_t(0)), LU_TAG_ITERATOR); @@ -2980,6 +3022,9 @@ static void luau_execute(lua_State* L) VM_CHECK_GC(L); VM_CASE_INSTRUCTION insn = *pc++; + if (FFlag::LuauRuntimeFeedback) + L->ci->p->execcount++; + pc += LUAU_INSN_D(insn); VM_ASSERT_PC(pc); VM_NEXT(); @@ -4012,6 +4057,9 @@ int luau_precall(lua_State* L, StkId func, int nresults) { Proto* p = ccl->l.p; + if (FFlag::LuauRuntimeFeedback) + p->execcount++; + // fill unused parameters with nil StkId argi = L->top; StkId argend = L->base + p->numparams; diff --git a/VM/src/lvmutils.cpp b/VM/src/lvmutils.cpp index 4addd9ba0..5de549a7d 100644 --- a/VM/src/lvmutils.cpp +++ b/VM/src/lvmutils.cpp @@ -19,6 +19,7 @@ LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) LUAU_FASTFLAG(LuauPromoteProto) +LUAU_FASTFLAG(LuauRuntimeFeedback) const TValue* luaV_tonumber(const TValue* obj, TValue* n) { @@ -65,6 +66,9 @@ static LUAU_FORCEINLINE void callTMluau(lua_State* L, StkId top, Closure* ccl, i ptrdiff_t funcoffset = savestack(L, top); Proto* p = getproto(ccl); + if (FFlag::LuauRuntimeFeedback) + p->execcount++; + CallInfo* ci = incr_ci(L); ci->func = top; ci->p = p; diff --git a/tests/AssemblyBuilderA64.test.cpp b/tests/AssemblyBuilderA64.test.cpp index 1cf76f65a..2c4b0b726 100644 --- a/tests/AssemblyBuilderA64.test.cpp +++ b/tests/AssemblyBuilderA64.test.cpp @@ -745,4 +745,52 @@ TEST_CASE_FIXTURE(AssemblyBuilderA64Fixture, "Nop") )); } +TEST_CASE_FIXTURE(AssemblyBuilderA64Fixture, "FarDataReferences") +{ + // Note: offset is based on the distance from code to data + // This can cause an 8 byte increase between constants to appear as an extra page offset increase + struct TestCase + { + uint32_t padding; + std::vector instructions; + } cases[] = { + // adr x0, #0xfffffffffff00010 + // adr x1, #0xfffffffffff00008 + {(1 << 20) - 24, {0x10800080, 0x10800021}}, + + // adr x0, #0xfffffffffff00004 + // adrp x1, #0xfffffffffff00000 ; -256 pages + // add x1, x1, #4080 + {(1 << 20) - 12, {0x10800020, 0x90fff801, 0x913fc021}}, + + // adrp x0, #0xfffffffffff00000 ; -256 pages + // add x0, x0, #4088 + // adrp x1, #0xffffffffffeff000 ; -257 pages + // add x1, x1, #4080 + {(1 << 20) - 8, {0x90fff800, 0x913fe000, 0xf0fff7e1, 0x913fc021}}, + + // adrp x0, #0xffffffffffeff000 ; -257 pages + // add x0, x0, #4088 + // adrp x1, #0xffffffffffeff000 ; -257 pages + // add x1, x1, #4080 + {(1 << 20) + 4, {0xf0fff7e0, 0x913fe000, 0xf0fff7e1, 0x913fc021}}, + }; + + for (const TestCase& test : cases) + { + AssemblyBuilderA64 build(/* logger= */ nullptr, /* features= */ 0); + + build.nop(test.padding); + + build.adr(x0, 0.1); + build.adr(x1, 0.3); + CHECK(build.finalize()); + + REQUIRE(build.code.size() == test.padding / 4 + test.instructions.size()); + + for (size_t i = 0; i < test.instructions.size(); ++i) + CHECK(build.code[test.padding / 4 + i] == test.instructions[i]); + } +} + TEST_SUITE_END(); diff --git a/tests/AstJsonEncoder.test.cpp b/tests/AstJsonEncoder.test.cpp index 91ae09db8..8769528f5 100644 --- a/tests/AstJsonEncoder.test.cpp +++ b/tests/AstJsonEncoder.test.cpp @@ -15,6 +15,8 @@ using namespace Luau; LUAU_FASTFLAG(LuauSingleTypeOptionalPackReturnsAttributeParens) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) struct JsonEncoderFixture { @@ -410,6 +412,42 @@ TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile") CHECK(toJson(statement) == expected); } +TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile_while_local") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + AstStat* statement = expectParseStatement("while local x = y do end"); + + std::string_view expected = + R"({"type":"AstStatWhile","location":"0,0 - 0,24","condition":{"type":"AstExprGlobal","location":"0,16 - 0,17","global":"y"},"body":{"type":"AstStatBlock","location":"0,20 - 0,21","hasEnd":true,"body":[]},"hasDo":true,"conditionLocal":{"luauType":null,"name":"x","isConst":false,"type":"AstLocal","location":"0,12 - 0,13"}})"; + + CHECK(toJson(statement) == expected); +} + +TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile_while_local_type") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + AstStat* statement = expectParseStatement("while local x: number = y do end"); + + std::string_view expected = + R"({"type":"AstStatWhile","location":"0,0 - 0,32","condition":{"type":"AstExprGlobal","location":"0,24 - 0,25","global":"y"},"body":{"type":"AstStatBlock","location":"0,28 - 0,29","hasEnd":true,"body":[]},"hasDo":true,"conditionLocal":{"luauType":{"type":"AstTypeReference","location":"0,15 - 0,21","name":"number","nameLocation":"0,15 - 0,21","parameters":[]},"name":"x","isConst":false,"type":"AstLocal","location":"0,12 - 0,13"}})"; + + CHECK(toJson(statement) == expected); +} + +TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile_while_const") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + AstStat* statement = expectParseStatement("while const x = y do end"); + + std::string_view expected = + R"({"type":"AstStatWhile","location":"0,0 - 0,24","condition":{"type":"AstExprGlobal","location":"0,16 - 0,17","global":"y"},"body":{"type":"AstStatBlock","location":"0,20 - 0,21","hasEnd":true,"body":[]},"hasDo":true,"conditionLocal":{"luauType":null,"name":"x","isConst":true,"type":"AstLocal","location":"0,12 - 0,13"}})"; + + CHECK(toJson(statement) == expected); +} + TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatRepeat") { AstStat* statement = expectParseStatement("repeat until true"); diff --git a/tests/AstVisitor.test.cpp b/tests/AstVisitor.test.cpp index 176b9a223..d5af45e24 100644 --- a/tests/AstVisitor.test.cpp +++ b/tests/AstVisitor.test.cpp @@ -6,6 +6,7 @@ #include "doctest.h" LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) using namespace Luau; @@ -136,4 +137,44 @@ TEST_CASE_FIXTURE(Fixture, "IfLocalAnnotationVisit") CHECK(v[6]->is()); } +TEST_CASE_FIXTURE(Fixture, "WhileLocalAnnotationVisit") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}}; + + AstStatBlock* block = parse(R"( + while local a: number = foo() do break end + )"); + + AstTypeVisitorTrackingWiths v; + block->visit(&v); + + CHECK(v[0]->is()); + CHECK(v[1]->is()); + CHECK(v[2]->is()); + CHECK(v[3]->is()); + CHECK(v[4]->is()); + CHECK(v[5]->is()); + CHECK(v[6]->is()); +} + +TEST_CASE_FIXTURE(Fixture, "WhileConstAnnotationVisit") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}}; + + AstStatBlock* block = parse(R"( + while const a: number = foo() do break end + )"); + + AstTypeVisitorTrackingWiths v; + block->visit(&v); + + CHECK(v[0]->is()); + CHECK(v[1]->is()); + CHECK(v[2]->is()); + CHECK(v[3]->is()); + CHECK(v[4]->is()); + CHECK(v[5]->is()); + CHECK(v[6]->is()); +} + TEST_SUITE_END(); diff --git a/tests/Autocomplete.test.cpp b/tests/Autocomplete.test.cpp index b16fa39a7..0209a35de 100644 --- a/tests/Autocomplete.test.cpp +++ b/tests/Autocomplete.test.cpp @@ -24,6 +24,8 @@ LUAU_FASTFLAG(LuauUseExplicitTypeArgsInGenerics) LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) LUAU_FASTFLAG(LuauRefactorAutocompleteAncestry) using namespace Luau; @@ -6255,4 +6257,156 @@ TEST_CASE_FIXTURE(ACFixture, "autocomplete_function_statement_with_index_2") CHECK(ac.entryMap.count("abs")); } +TEST_CASE_FIXTURE(ACFixture, "while_local_binding_is_in_scope_in_body") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + check(R"( + local t = {} + while local x = t do + @1 + end + @2 + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("x")); + + ac = autocomplete('2'); + CHECK(!ac.entryMap.count("x")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_const_binding_is_in_scope_in_body") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + check(R"( + local t = {} + while const x = t do + @1 + end + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("x")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_local_binding_offers_member_completion") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + check(R"( + local t = {foo = 1, bar = 2} + while local x = t do + x.@1 + end + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("foo")); + CHECK(ac.entryMap.count("bar")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_local_optional_binding_is_in_scope_in_body") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + check(R"( + type Test = {name: string, age: number} + local function getTester(): Test? return nil end + local function sample() + while local myTest = getTester() do + @1 + end + end + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("myTest")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_local_optional_binding_offers_member_completion") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + check(R"( + type Test = {name: string, age: number} + local function getTester(): Test? return nil end + local function sample() + while local myTest = getTester() do + myTest.@1 + end + end + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("name")); + CHECK(ac.entryMap.count("age")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_local_optional_binding_member_completion_in_call_arg") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + check(R"( + type Test = {name: string, age: number} + local function getTester(): Test? return nil end + local function sample() + while local myTest = getTester() do + print(myTest.@1) + end + end + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("name")); + CHECK(ac.entryMap.count("age")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_local_value_offers_expression_completion") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + check(R"( + local thing = {} + while local x = @1 do + end + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("thing")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_local_value_offers_member_completion") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + check(R"( + local t = {foo = 1, bar = 2} + while local x = t.@1 do + end + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("foo")); + CHECK(ac.entryMap.count("bar")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_local_annotation_correctly_suggests_types") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + check(R"( + local one = 4 + local two = "hello" + while local x: number = o@1 do + end + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("one")); + CHECK(ac.entryMap["one"].typeCorrect == TypeCorrectKind::Correct); + CHECK(ac.entryMap["two"].typeCorrect == TypeCorrectKind::None); +} + TEST_SUITE_END(); diff --git a/tests/Compiler.test.cpp b/tests/Compiler.test.cpp index fb32b2319..753fdc903 100644 --- a/tests/Compiler.test.cpp +++ b/tests/Compiler.test.cpp @@ -42,6 +42,7 @@ LUAU_FASTFLAG(LuauCompileNoFoldVectorEqW) LUAU_FASTFLAG(LuauCompileReuseLocalRegs) LUAU_FASTFLAG(LuauCompileTableBuiltinsCreateClear) LUAU_FASTFLAG(LuauCompileReuseLowersLimit) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) using namespace Luau; @@ -15268,6 +15269,70 @@ RETURN R0 1 ); } +TEST_CASE("WhileLocal") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( + while local x = getValue() do + print(x) + end + )"), + R"( +L0: GETIMPORT R0 1 [getValue] +CALL R0 0 1 +JUMPIFNOT R0 L1 +GETIMPORT R1 3 [print] +MOVE R2 R0 +CALL R1 1 0 +JUMPBACK L0 +L1: RETURN R0 0 +)" + ); +} + +TEST_CASE("WhileLocalConstantFalse") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + // A constant-false condition means the body never runs, so nothing is emitted for the loop. + CHECK_EQ( + "\n" + compileFunction0(R"( + while local x = false do + print(x) + end + )"), + R"( +RETURN R0 0 +)" + ); +} + +TEST_CASE("WhileConst") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + // `while const` should be identical to `while local` + CHECK_EQ( + "\n" + compileFunction0(R"( + while const x = getValue() do + print(x) + end + )"), + R"( +L0: GETIMPORT R0 1 [getValue] +CALL R0 0 1 +JUMPIFNOT R0 L1 +GETIMPORT R1 3 [print] +MOVE R2 R0 +CALL R1 1 0 +JUMPBACK L0 +L1: RETURN R0 0 +)" + ); +} + TEST_CASE("LocalRegisterReuse") { ScopedFastFlag luauCompileReuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; diff --git a/tests/Conformance.test.cpp b/tests/Conformance.test.cpp index ee1aaaae0..9290c8e6c 100644 --- a/tests/Conformance.test.cpp +++ b/tests/Conformance.test.cpp @@ -60,6 +60,7 @@ LUAU_FASTFLAG(LuauBytecodeFold) LUAU_FASTFLAG(LuauBytecodeSlotAlloc) LUAU_FASTFLAG(LuauCodegenA64BitlrotateSelf) LUAU_FASTFLAG(LuauEmitCallFeedback) +LUAU_FASTFLAG(LuauCodegenMarkUsed) LUAU_FASTINT(CodegenHeuristicsInstructionLimit) LUAU_FASTFLAG(LuauIntegerLibrary) LUAU_FASTFLAG(LuauIntegerType2) @@ -80,9 +81,11 @@ LUAU_FASTFLAG(LuauBufferCage) LUAU_FASTFLAG(LuauCoroutineFinally) LUAU_FASTFLAG(LuauCoroutineFinallyAnalysis) LUAU_FASTFLAG(LuauCodegenDseTrackTagInvalidation) +LUAU_FASTFLAG(LuauCodegenCmpAnySideEffecting) LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(LuauCompileCallFbRemap) LUAU_DYNAMIC_FASTFLAG(LuauTableRobustOom) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) #ifndef LUAU_CONFORMANCE_SOURCE_DIR // Walks up from the current directory looking for the Client folder, @@ -124,6 +127,7 @@ static Luau::CodeGen::CompilationOptions defaultCodegenOptions() { Luau::CodeGen::CompilationOptions opts = {}; opts.flags = Luau::CodeGen::CodeGen_ColdFunctions; + opts.runtimeFeedback = true; return opts; } @@ -387,6 +391,8 @@ static StateRef runConformance( if (result == 0 && codegen && !skipCodegen && luau_codegen_supported()) { + Luau::CodeGen::enableRuntimeCompilation(L, nativeOpts, /* promoteVmFunctions */ false); + Luau::CodeGen::CompilationResult result = Luau::CodeGen::compile(L, -1, nativeOpts); CHECK(result.result == Luau::CodeGen::CodeGenCompilationResult::Success); @@ -825,6 +831,25 @@ static int lua_vertex_namecall(lua_State* L) luaL_error(L, "%s is not a valid method of vertex", luaL_checkstring(L, 1)); } +static uint8_t remapUserdataTypes(void* context, const char* str, size_t len) +{ + const char** types = (const char**)context; + + uint8_t index = 0; + + std::string_view sv{str, len}; + + for (; *types; ++types) + { + if (sv == *types) + return index; + + index++; + } + + return 0xff; +} + void setupUserdataHelpers(lua_State* L) { // create metatable with all the metamethods @@ -3495,6 +3520,12 @@ TEST_CASE("IfLocal") runConformance("iflocal.luau"); } +TEST_CASE("WhileLocal") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}}; + runConformance("whilelocal.luau"); +} + // Optionally returns debug info for the first Luau stack frame that is encountered on the callstack. static std::optional getFirstLuauFrameDebugInfo(lua_State* L) { @@ -4186,6 +4217,7 @@ TEST_CASE("WeakRefSurvivesWhenMarked") struct State { int ref = LUA_REFNIL; + bool marked = false; }; State state; @@ -4200,10 +4232,24 @@ TEST_CASE("WeakRefSurvivesWhenMarked") lua_setembeddergc( L, - [](lua_State* L, lua_EmbedderMark markref) + [](lua_State* L, lua_EmbedderMark markref) -> int { - if (markref) - markref(L, static_cast(lua_getthreaddata(L))->ref); + State* s = static_cast(lua_getthreaddata(L)); + if (!markref) + { + // cycle reset + s->marked = false; + return 0; + } + else + { + // mark phase + if (s->marked) + return 0; + s->marked = true; + markref(L, s->ref); + return 1; + } } ); @@ -4229,8 +4275,13 @@ TEST_CASE("WeakRefCollectedWhenNotMarked") int ref = lua_weakref(L, -1); lua_pop(L, 1); - // An unsound embedder mark callback that fails to mark the embedder ref - lua_setembeddergc(L, [](lua_State*, lua_EmbedderMark) {}); + lua_setembeddergc( + L, + [](lua_State*, lua_EmbedderMark) -> int + { + return 0; + } + ); lua_gc(L, LUA_GCCOLLECT, 0); REQUIRE(lua_getweakref(L, ref) == LUA_TNIL); @@ -4270,7 +4321,7 @@ TEST_CASE("WeakRefFullChain") // If the native object is marked, mark the ref that it logically owns lua_setembeddergc( L, - [](lua_State* L, lua_EmbedderMark markref) + [](lua_State* L, lua_EmbedderMark markref) -> int { State* s = static_cast(lua_getthreaddata(L)); if (!markref) @@ -4279,16 +4330,19 @@ TEST_CASE("WeakRefFullChain") s->nativeObjectMarked = false; s->marksRequested = 0; s->marksPerformed = 0; + return 0; } else { // mark requested s->marksRequested++; - if (s->nativeObjectMarked) + if (s->nativeObjectMarked && s->marksPerformed == 0) { s->marksPerformed++; markref(L, s->callbackRef); + return 1; } + return 0; } } ); @@ -4310,7 +4364,7 @@ TEST_CASE("WeakRefFullChain") CHECK(lua_topointer(L, -1) == tablePtr); lua_pop(L, 1); CHECK(state.marksRequested == 2); - CHECK(state.marksPerformed == 2); + CHECK(state.marksPerformed == 1); // Cycle 2: userdata unreachable -> ... -> table never marked and collected lua_unref(L, udRef); @@ -4724,8 +4778,10 @@ TEST_CASE("SafeEnv") TEST_CASE("Native") { + ScopedFastFlag luauCodegenMarkUsed{FFlag::LuauCodegenMarkUsed, true}; ScopedFastFlag reloadLargeConstOffset{FFlag::LuauCodegenA64ReloadLargeConstOffset, true}; ScopedFastFlag luauCodegenDseTrackTagInvalidation{FFlag::LuauCodegenDseTrackTagInvalidation, true}; + ScopedFastFlag luauCodegenCmpAnySideEffecting{FFlag::LuauCodegenCmpAnySideEffecting, true}; // This tests requires code to run natively, otherwise all 'is_native' checks will fail if (!codegen || !luau_codegen_supported()) @@ -4876,28 +4932,7 @@ TEST_CASE("NativeUserdata") "native_userdata.luau", [](lua_State* L) { - Luau::CodeGen::setUserdataRemapper( - L, - kUserdataRunTypes, - [](void* context, const char* str, size_t len) -> uint8_t - { - const char** types = (const char**)context; - - uint8_t index = 0; - - std::string_view sv{str, len}; - - for (; *types; ++types) - { - if (sv == *types) - return index; - - index++; - } - - return 0xff; - } - ); + Luau::CodeGen::setUserdataRemapper(L, kUserdataRunTypes, remapUserdataTypes); setupVectorHelpers(L); setupUserdataHelpers(L); @@ -5225,76 +5260,6 @@ TEST_CASE("ExportEdgeCase") REQUIRE(status == 0); } -TEST_CASE("LargeModuleA64") -{ - std::string source; - - for (int i = 0; i < 60; i++) - { - source += "function filler" + std::to_string(i) + "(x: number)\n"; - - for (int k = 1; k <= 2000; k++) - source += " x = x + " + std::to_string(k) + "\n"; - - source += " return x\nend\n"; - } - - // Constants are chosen in a way that cannot be lowered for fmov and will allocate in the data section - source += "function trigger(x: number)\n"; - source += " x = x + 0.1\n"; - source += " x = x + 0.3\n"; - source += " return x\n"; - source += "end\n"; - - source += "return math.floor(trigger(1) * 100000)\n"; - - StateRef globalState(luaL_newstate(), lua_close); - lua_State* L = globalState.get(); - - if (luau_codegen_supported() != 0) - luau_codegen_create(L); - - luaL_openlibs(L); - - lua_CompileOptions opts = defaultOptions(); - opts.optimizationLevel = 2; - - size_t bytecodeSize = 0; - char* bytecode = luau_compile(source.data(), source.size(), &opts, &bytecodeSize); - int result = luau_load(L, "=LargeModuleA64", bytecode, bytecodeSize, 0); - free(bytecode); - - REQUIRE(result == 0); - - if (luau_codegen_supported() != 0) - { - Luau::CodeGen::AssemblyOptions assemblyOptions; - assemblyOptions.compilationOptions.flags = Luau::CodeGen::CodeGen_ColdFunctions; - assemblyOptions.includeAssembly = true; - - Luau::CodeGen::LoweringStats stats; - stats.functionStatsFlags = Luau::CodeGen::FunctionStatsFlags::FunctionStats_Enable; - - assemblyOptions.target = Luau::CodeGen::AssemblyOptions::A64; - std::string a64 = Luau::CodeGen::getAssembly(L, -1, assemblyOptions, &stats); - CHECK(!a64.empty()); - - CHECK(stats.regAllocErrors == 0); - CHECK(stats.loweringErrors == 0); - } - - if (codegen && luau_codegen_supported() != 0) - { - Luau::CodeGen::CompilationOptions nativeOptions{Luau::CodeGen::CodeGen_ColdFunctions}; - Luau::CodeGen::compile(L, -1, nativeOptions); - } - - int status = lua_resume(L, nullptr, 0); - REQUIRE(status == 0); - - CHECK(lua_tonumber(L, -1) == 140000); -} - TEST_CASE("IrInstructionLimit") { if (!codegen || !luau_codegen_supported()) diff --git a/tests/ControlFlowGraph.test.cpp b/tests/ControlFlowGraph.test.cpp index 7414ae799..7cd4a889f 100644 --- a/tests/ControlFlowGraph.test.cpp +++ b/tests/ControlFlowGraph.test.cpp @@ -3,6 +3,7 @@ #include "Luau/Ast.h" #include "Luau/AstQuery.h" #include "Luau/DumpCFG.h" +#include "Luau/Error.h" #include "Luau/Parser.h" #include "ScopedFlags.h" @@ -14,10 +15,12 @@ #ifdef _WIN32 #include // You need this include on MSVC for IWYU reasons #endif +#include #include #include #include #include +#include LUAU_FASTFLAG(DebugLuauLogCFG) LUAU_FASTFLAG(DebugLuauDumpCFGJson) @@ -25,7 +28,6 @@ LUAU_FASTFLAG(DebugLuauFreezeArena) LUAU_FASTFLAG(DebugLuauCFG) using namespace Luau; -using namespace Luau::CFG; namespace { @@ -72,9 +74,20 @@ void checkJoin(Join* j, std::string_view def, std::initializer_listdefinition->versionedName() == def); REQUIRE(j->operands.size() == operands.size()); - auto it = operands.begin(); - for (size_t i = 0; i < j->operands.size(); i++, ++it) - CHECK(j->operands[i]->versionedName() == *it); + + std::vector actual; + actual.reserve(j->operands.size()); + for (Definition* operand : j->operands) + actual.emplace_back(operand->versionedName()); + + std::vector expected; + expected.reserve(operands.size()); + for (std::string_view operand : operands) + expected.emplace_back(operand); + + std::sort(actual.begin(), actual.end()); + std::sort(expected.begin(), expected.end()); + CHECK(actual == expected); } // `type=nullopt` denotes a truthy/falsy refinement (no type guard); `isTypeof` is @@ -89,17 +102,31 @@ void checkRefine( ) { CHECK(r->definition->versionedName() == def); - CHECK(r->toRefine->versionedName() == source); - CHECK(r->sense == sense); + CHECK(r->getTarget()->versionedName() == source); + if (type) { - REQUIRE(r->type.has_value()); - CHECK(*r->type == *type); - CHECK(r->isTypeof == isTypeof); + if (sense) + { + auto* eq = r->constraint.get_if(); + REQUIRE(eq != nullptr); + CHECK(eq->type == *type); + CHECK(eq->isTypeOf == isTypeof); + } + else + { + auto* neq = r->constraint.get_if(); + REQUIRE(neq != nullptr); + CHECK(neq->type == *type); + CHECK(neq->isTypeOf == isTypeof); + } } else { - CHECK(!r->type.has_value()); + if (sense) + CHECK(r->constraint.get_if() != nullptr); + else + CHECK(r->constraint.get_if() != nullptr); } } @@ -153,6 +180,7 @@ struct CFGFixture TEST_SUITE_BEGIN("CFGConstruction"); + TEST_CASE_FIXTURE(CFGFixture, "single_local") { auto cfg = build(R"( @@ -251,22 +279,22 @@ TEST_CASE_FIXTURE(CFGFixture, "basic_join") REQUIRE(cfg->blocks.size() == 4); Block* entry = cfg->blocks[0]; - Block* thenBlk = cfg->blocks[1]; + Block* thenBlock = cfg->blocks[1]; Block* elseBlk = cfg->blocks[2]; Block* merge = cfg->blocks[3]; CHECK(entry->kind == BlockKind::Entry); - CHECK(thenBlk->kind == BlockKind::Linear); + CHECK(thenBlock->kind == BlockKind::Linear); CHECK(elseBlk->kind == BlockKind::Linear); CHECK(merge->kind == BlockKind::Linear); checkSuccessors(*cfg, entry, {1, 2}); - checkSuccessors(*cfg, thenBlk, {3}); + checkSuccessors(*cfg, thenBlock, {3}); checkSuccessors(*cfg, elseBlk, {3}); checkPredecessors(*cfg, merge, {1, 2}); CHECK(requireInst(entry, 0)->def->versionedName() == "t-0"); - CHECK(requireInst(thenBlk, 0)->def->versionedName() == "t-1"); + CHECK(requireInst(thenBlock, 0)->def->versionedName() == "t-1"); CHECK(requireInst(elseBlk, 0)->def->versionedName() == "t-2"); auto* phi = requireInst(merge, 0); @@ -292,6 +320,7 @@ TEST_CASE_FIXTURE(CFGFixture, "while_loop") Block* body = cfg->blocks[2]; Block* exit = cfg->blocks[3]; + CHECK(entry->kind == BlockKind::Entry); CHECK(header->kind == BlockKind::Condition); CHECK(body->kind == BlockKind::Linear); @@ -307,16 +336,16 @@ TEST_CASE_FIXTURE(CFGFixture, "while_loop") // The header block has two predecessors - the loop block and the entry block auto* phi = requireInst(header, 0); - checkJoin(phi, "x-1", {"x-0", "x-3"}); + checkJoin(phi, "x-1", {"x-0", "x-4"}); // `not x` truthy means x is falsy — body sigma takes the falsy refinement. auto* bodyRefine = requireInst(body, 0); checkRefine(bodyRefine, "x-2", "x-1", /*sense*/ false); - CHECK(requireInst(body, 1)->def->versionedName() == "x-3"); + CHECK(requireInst(body, 1)->def->versionedName() == "x-4"); // `not x` falsy on exit means x is truthy. auto* exitRefine = requireInst(exit, 0); - checkRefine(exitRefine, "x-4", "x-1", /*sense*/ true); + checkRefine(exitRefine, "x-3", "x-1", /*sense*/ true); CHECK(requireInst(exit, 1)->def->versionedName() == "y-0"); } @@ -390,10 +419,417 @@ TEST_CASE_FIXTURE(CFGFixture, "nontrivial_phi_one_branch_modifies") // The phi is non-trivial — the read should resolve to the phi's def, not x-0. Block* merge = cfg->blocks[3]; auto* phi = requireInst(merge, 0); - checkJoin(phi, "x-2", {"x-1", "x-0"}); + checkJoin(phi, "x-2", {"x-0", "x-1"}); CHECK_REACHING_DEF(Position(5, 18), "x-2"); } +TEST_CASE_FIXTURE(CFGFixture, "while_break") +{ + auto cfg = build(R"( + local x = 1 + while true do + if x > 0 then + break + end + x = x + 1 + end + local w = x + )"); + + // blocks[0]: Entry — declare x-0 + // blocks[1]: while-loop condition — join x-1 = (x-0, x-2) + // blocks[2]: while-loop body + // blocks[3]: while-loop exit — declare w-0 + // blocks[4]: then block — break edges to loopExit + // blocks[5]: else block + // blocks[6]: merge — assign x-2 + REQUIRE(cfg->blocks.size() == 7); + + Block* loopHeader = cfg->blocks[1]; + Block* loopExit = cfg->blocks[3]; + Block* thenBlock = cfg->blocks[4]; + Block* merge = cfg->blocks[6]; + + // The break in the then-branch should NOT wire to merge — only to loopExit. + checkSuccessors(*cfg, thenBlock, {3}); + // Merge only receives the else-branch (break prevents then from falling through). + checkPredecessors(*cfg, merge, {5}); + // Loop exit receives from header (condition false) and break (then-branch). + checkPredecessors(*cfg, loopExit, {1, 4}); + // Back-edge from merge to loop header. + checkSuccessors(*cfg, merge, {1}); + checkPredecessors(*cfg, loopHeader, {0, 6}); + + // Loop header phi merges entry (x-0) and back-edge (x-2). + auto* phi = requireInst(loopHeader, 0); + checkJoin(phi, "x-1", {"x-0", "x-2"}); + + // The assignment x = x + 1 lives in the merge block. + CHECK(requireInst(merge, 0)->def->versionedName() == "x-2"); + + // `local w = x` sees x-1 (the loop header phi) because the trivial join + // at loopExit (both predecessors provide x-1) is eliminated. + CHECK_REACHING_DEF(Position(8, 18), "x-1"); +} + +TEST_CASE_FIXTURE(CFGFixture, "while_continue") +{ + auto cfg = build(R"( + local x = 1 + while true do + if x > 0 then + continue + end + x = x + 1 + end + local w = x + )"); + + // blocks[0]: Entry — declare x-0 + // blocks[1]: while-loop condition — join x-1 = (x-0, x-2) + // blocks[2]: while-loop body + // blocks[3]: while-loop exit + // blocks[4]: then block — continue edges to loopHeader + // blocks[5]: else block + // blocks[6]: merge — assign x-2 + REQUIRE(cfg->blocks.size() == 7); + + Block* loopHeader = cfg->blocks[1]; + Block* loopExit = cfg->blocks[3]; + Block* thenBlock = cfg->blocks[4]; + Block* merge = cfg->blocks[6]; + + // Continue in the then-branch should edge to loopHeader, NOT merge. + checkSuccessors(*cfg, thenBlock, {1}); + // Merge only receives the else-branch. + checkPredecessors(*cfg, merge, {5}); + // Loop header receives from entry, continue (then-block), and back-edge (merge). + checkPredecessors(*cfg, loopHeader, {0, 4, 6}); + // Loop exit only receives from header (no break). + checkPredecessors(*cfg, loopExit, {1}); + + // The continue path does not change x, so the header join only records the distinct incoming defs. + auto* phi = requireInst(loopHeader, 0); + checkJoin(phi, "x-1", {"x-0", "x-2"}); + + // The assignment x = x + 1 lives in the merge block. + CHECK(requireInst(merge, 0)->def->versionedName() == "x-2"); + + // `local w = x` resolves to x-1 (single predecessor path from loopHeader). + CHECK_REACHING_DEF(Position(8, 18), "x-1"); +} + +TEST_CASE_FIXTURE(CFGFixture, "repeat_until") +{ + auto cfg = build(R"( + local x = nil + repeat + x = 5 + until x + local y = x + )"); + + // blocks[0]: Entry — declare x-0 + // blocks[1]: repeat-loop body — assign x-1 + // blocks[2]: repeat-loop condition + // blocks[3]: repeat-loop exit — declare y-0 + // blocks[4]: condition truthy — refine x-2, exits loop + // blocks[5]: condition falsy — refine x-3, back-edge to body + REQUIRE(cfg->blocks.size() == 6); + + Block* entry = cfg->blocks[0]; + Block* body = cfg->blocks[1]; + Block* cond = cfg->blocks[2]; + Block* exit = cfg->blocks[3]; + Block* truthy = cfg->blocks[4]; + Block* falsy = cfg->blocks[5]; + + CHECK(body->kind == BlockKind::Linear); + CHECK(cond->kind == BlockKind::Condition); + CHECK(exit->kind == BlockKind::Linear); + + checkSuccessors(*cfg, entry, {1}); + checkSuccessors(*cfg, body, {2}); + checkSuccessors(*cfg, cond, {4, 5}); + checkSuccessors(*cfg, truthy, {3}); + checkSuccessors(*cfg, falsy, {1}); + checkPredecessors(*cfg, body, {0, 5}); + checkPredecessors(*cfg, exit, {4}); + + CHECK(requireInst(entry, 0)->def->versionedName() == "x-0"); + CHECK(requireInst(body, 0)->def->versionedName() == "x-1"); + checkRefine(requireInst(truthy, 0), "x-2", "x-1", /*sense*/ true); + checkRefine(requireInst(falsy, 0), "x-3", "x-1", /*sense*/ false); + CHECK(requireInst(exit, 0)->def->versionedName() == "y-0"); + + CHECK_REACHING_DEF(Position(5, 18), "x-2"); +} + +TEST_CASE_FIXTURE(CFGFixture, "repeat_break") +{ + auto cfg = build(R"( + local x = 1 + repeat + if x > 0 then + break + end + x = x + 1 + until x + local w = x + )"); + + // blocks[0]: Entry — declare x-0 + // blocks[1]: repeat-loop body — join x-1 = (x-0, x-4) + // blocks[2]: repeat-loop condition + // blocks[3]: repeat-loop exit — join x-5 = (x-1, x-3), declare w-0 + // blocks[4]: then block — break to exit + // blocks[5]: else block + // blocks[6]: merge — assign x-2 + // blocks[7]: condition truthy — refine x-3, exits loop + // blocks[8]: condition falsy — refine x-4, back-edge to body + REQUIRE(cfg->blocks.size() == 9); + + Block* body = cfg->blocks[1]; + Block* cond = cfg->blocks[2]; + Block* exit = cfg->blocks[3]; + Block* thenBlock = cfg->blocks[4]; + Block* merge = cfg->blocks[6]; + Block* truthy = cfg->blocks[7]; + Block* falsy = cfg->blocks[8]; + + checkSuccessors(*cfg, thenBlock, {3}); + checkSuccessors(*cfg, merge, {2}); + checkSuccessors(*cfg, cond, {7, 8}); + checkSuccessors(*cfg, truthy, {3}); + checkSuccessors(*cfg, falsy, {1}); + + checkPredecessors(*cfg, body, {0, 8}); + checkPredecessors(*cfg, cond, {6}); + checkPredecessors(*cfg, exit, {4, 7}); + + checkJoin(requireInst(body, 0), "x-1", {"x-0", "x-4"}); + CHECK(requireInst(merge, 0)->def->versionedName() == "x-2"); + checkRefine(requireInst(truthy, 0), "x-3", "x-2", /*sense*/ true); + checkRefine(requireInst(falsy, 0), "x-4", "x-2", /*sense*/ false); + checkJoin(requireInst(exit, 0), "x-5", {"x-1", "x-3"}); + CHECK(requireInst(exit, 1)->def->versionedName() == "w-0"); + + CHECK_REACHING_DEF(Position(8, 18), "x-5"); +} + +TEST_CASE_FIXTURE(CFGFixture, "repeat_continue") +{ + auto cfg = build(R"( + local x = 1 + repeat + if x > 0 then + continue + end + x = x + 1 + until x + local w = x + )"); + + // blocks[0]: Entry — declare x-0 + // blocks[1]: repeat-loop body — join x-1 = (x-0, x-5) + // blocks[2]: repeat-loop condition — join x-3 = (x-1, x-2) + // blocks[3]: repeat-loop exit — declare w-0 + // blocks[4]: then block — continue to condition + // blocks[5]: else block + // blocks[6]: merge — assign x-2 + // blocks[7]: condition truthy — refine x-4, exits loop + // blocks[8]: condition falsy — refine x-5, back-edge to body + REQUIRE(cfg->blocks.size() == 9); + + Block* body = cfg->blocks[1]; + Block* cond = cfg->blocks[2]; + Block* exit = cfg->blocks[3]; + Block* thenBlock = cfg->blocks[4]; + Block* merge = cfg->blocks[6]; + Block* truthy = cfg->blocks[7]; + Block* falsy = cfg->blocks[8]; + + checkSuccessors(*cfg, thenBlock, {2}); + checkSuccessors(*cfg, merge, {2}); + checkSuccessors(*cfg, cond, {7, 8}); + checkSuccessors(*cfg, truthy, {3}); + checkSuccessors(*cfg, falsy, {1}); + + checkPredecessors(*cfg, body, {0, 8}); + checkPredecessors(*cfg, cond, {4, 6}); + checkPredecessors(*cfg, exit, {7}); + + checkJoin(requireInst(body, 0), "x-1", {"x-0", "x-5"}); + CHECK(requireInst(merge, 0)->def->versionedName() == "x-2"); + checkJoin(requireInst(cond, 0), "x-3", {"x-1", "x-2"}); + checkRefine(requireInst(truthy, 0), "x-4", "x-3", /*sense*/ true); + checkRefine(requireInst(falsy, 0), "x-5", "x-3", /*sense*/ false); + CHECK(requireInst(exit, 0)->def->versionedName() == "w-0"); + + CHECK_REACHING_DEF(Position(8, 18), "x-4"); +} + +TEST_CASE_FIXTURE(CFGFixture, "for_loop") +{ + auto cfg = build(R"( + local x = 0 + for i = 1, 10 do + x = x + i + end + local y = x + )"); + + // blocks[0]: Entry — declare x-0 + // blocks[1]: for-loop condition (header) + // blocks[2]: for-loop exit + // blocks[3]: for-loop body — declare i-0, assign x-2 + REQUIRE(cfg->blocks.size() == 4); + + Block* header = cfg->blocks[1]; + Block* body = cfg->blocks[3]; + + CHECK(header->kind == BlockKind::Condition); + checkSuccessors(*cfg, header, {2, 3}); + checkPredecessors(*cfg, header, {0, 3}); + checkSuccessors(*cfg, body, {1}); + + // Loop variable declared in body. + CHECK(requireInst(body, 0)->def->versionedName() == "i-0"); + + // Header phi for x: merges entry (x-0) and back-edge (x-2). + auto* phi = requireInst(header, 0); + checkJoin(phi, "x-1", {"x-0", "x-2"}); + + CHECK(requireInst(body, 1)->def->versionedName() == "x-2"); + + // After the loop, x resolves to the header phi. + CHECK_REACHING_DEF(Position(5, 18), "x-1"); +} + +TEST_CASE_FIXTURE(CFGFixture, "for_break") +{ + auto cfg = build(R"( + local x = 0 + for i = 1, 10 do + if x > 0 then + break + end + x = x + 1 + end + local w = x + )"); + + // blocks[0]: Entry — declare x-0 + // blocks[1]: for-loop condition (header) + // blocks[2]: for-loop exit + // blocks[3]: for-loop body — declare i-0 + // blocks[4]: then block — break to exit + // blocks[5]: else block + // blocks[6]: merge — assign x-2 + REQUIRE(cfg->blocks.size() == 7); + + Block* header = cfg->blocks[1]; + Block* exit = cfg->blocks[2]; + Block* thenBlock = cfg->blocks[4]; + Block* merge = cfg->blocks[6]; + + // Break wires then to exit, not merge. + checkSuccessors(*cfg, thenBlock, {2}); + checkPredecessors(*cfg, merge, {5}); + + // Exit receives from header (loop done) and break. + checkPredecessors(*cfg, exit, {1, 4}); + // Header phi: x-1 = join(x-0, x-2). + auto* phi = requireInst(header, 0); + checkJoin(phi, "x-1", {"x-0", "x-2"}); + + // `local w = x` — trivial join at exit collapses (both preds provide x-1). + CHECK_REACHING_DEF(Position(8, 18), "x-1"); +} + +TEST_CASE_FIXTURE(CFGFixture, "for_in_break") +{ + auto cfg = build(R"( + local x = 0 + local t + for k, v in t do + if x > 0 then + break + end + x = x + 1 + end + local w = x + )"); + + // blocks[0]: Entry — declare x-0 + // blocks[1]: for-in-loop condition (header) + // blocks[2]: for-in-loop exit + // blocks[3]: for-in-loop body — declare k-0, v-0 + // blocks[4]: then block — break to exit + // blocks[5]: else block + // blocks[6]: merge — assign x-2 + REQUIRE(cfg->blocks.size() == 7); + + Block* header = cfg->blocks[1]; + Block* exit = cfg->blocks[2]; + Block* body = cfg->blocks[3]; + Block* thenBlock = cfg->blocks[4]; + Block* merge = cfg->blocks[6]; + + // Break wires then to exit, not merge. + checkSuccessors(*cfg, thenBlock, {2}); + checkPredecessors(*cfg, merge, {5}); + + // Exit receives from header and break. + checkPredecessors(*cfg, exit, {1, 4}); + + // Loop variables declared in body. + CHECK(requireInst(body, 0)->def->versionedName() == "k-0"); + CHECK(requireInst(body, 1)->def->versionedName() == "v-0"); + + // Header phi: x-1 = join(x-0, x-2). + auto* phi = requireInst(header, 0); + checkJoin(phi, "x-1", {"x-0", "x-2"}); + + // `local w = x` — trivial join at exit collapses. + CHECK_REACHING_DEF(Position(9, 18), "x-1"); +} + +TEST_CASE_FIXTURE(CFGFixture, "if_else_expression") +{ + auto cfg = build(R"( + local x = nil + local y = if x then x else x + )"); + + // blocks[0]: Entry — declare x-0 + // blocks[1]: if-else expr then — refine x-1 (truthy) + // blocks[2]: if-else expr else — refine x-2 (falsy) + // blocks[3]: if-else expr merge — declare y-0 + REQUIRE(cfg->blocks.size() == 4); + + Block* condBlk = cfg->blocks[0]; + Block* thenBlock = cfg->blocks[1]; + Block* elseBlk = cfg->blocks[2]; + Block* merge = cfg->blocks[3]; + + checkSuccessors(*cfg, condBlk, {1, 2}); + checkPredecessors(*cfg, merge, {1, 2}); + + // Then branch: x refined to truthy. + auto* thenRefine = requireInst(thenBlock, 0); + checkRefine(thenRefine, "x-1", "x-0", /*sense*/ true); + + // Else branch: x refined to falsy. + auto* elseRefine = requireInst(elseBlk, 0); + checkRefine(elseRefine, "x-2", "x-0", /*sense*/ false); + + // The uses of x in the then/else branches see the refined defs. + // local y = if x then x else x + CHECK_REACHING_DEF(Position(2, 28), "x-1"); + CHECK_REACHING_DEF(Position(2, 35), "x-2"); +} + TEST_SUITE_END(); TEST_SUITE_BEGIN("CFGRefinement"); @@ -412,12 +848,12 @@ TEST_CASE_FIXTURE(CFGFixture, "if_truthy_both_branches") )"); REQUIRE(cfg->blocks.size() == 4); - Block* thenBlk = cfg->blocks[1]; + Block* thenBlock = cfg->blocks[1]; Block* elseBlk = cfg->blocks[2]; Block* merge = cfg->blocks[3]; - checkRefine(requireInst(thenBlk, 0), "x-1", "x-0", /*sense*/ true); - CHECK(requireInst(thenBlk, 1)->def->versionedName() == "y-0"); + checkRefine(requireInst(thenBlock, 0), "x-1", "x-0", /*sense*/ true); + CHECK(requireInst(thenBlock, 1)->def->versionedName() == "y-0"); checkRefine(requireInst(elseBlk, 0), "x-2", "x-0", /*sense*/ false); CHECK(requireInst(elseBlk, 1)->def->versionedName() == "z-0"); @@ -438,12 +874,12 @@ TEST_CASE_FIXTURE(CFGFixture, "if_falsy_single_branch") )"); REQUIRE(cfg->blocks.size() == 4); - Block* thenBlk = cfg->blocks[1]; + Block* thenBlock = cfg->blocks[1]; Block* elseBlk = cfg->blocks[2]; Block* merge = cfg->blocks[3]; // `not x` truthy → x is falsy in the then branch. - checkRefine(requireInst(thenBlk, 0), "x-1", "x-0", /*sense*/ false); + checkRefine(requireInst(thenBlock, 0), "x-1", "x-0", /*sense*/ false); // Negation flips on the else side — x is truthy. checkRefine(requireInst(elseBlk, 0), "x-2", "x-0", /*sense*/ true); @@ -461,10 +897,10 @@ TEST_CASE_FIXTURE(CFGFixture, "typeof_guard_emits_type_proposition") )"); REQUIRE(cfg->blocks.size() == 4); - Block* thenBlk = cfg->blocks[1]; + Block* thenBlock = cfg->blocks[1]; Block* elseBlk = cfg->blocks[2]; - checkRefine(requireInst(thenBlk, 0), "x-1", "x-0", /*sense*/ true, "string", /*isTypeof*/ true); + checkRefine(requireInst(thenBlock, 0), "x-1", "x-0", /*sense*/ true, "string", /*isTypeof*/ true); checkRefine(requireInst(elseBlk, 0), "x-2", "x-0", /*sense*/ false, "string", /*isTypeof*/ true); } @@ -499,10 +935,10 @@ TEST_CASE_FIXTURE(CFGFixture, "type_guard_inequality_flips_sense") )"); REQUIRE(cfg->blocks.size() == 4); - Block* thenBlk = cfg->blocks[1]; + Block* thenBlock = cfg->blocks[1]; Block* elseBlk = cfg->blocks[2]; - checkRefine(requireInst(thenBlk, 0), "x-1", "x-0", /*sense*/ false, "string", /*isTypeof*/ false); + checkRefine(requireInst(thenBlock, 0), "x-1", "x-0", /*sense*/ false, "string", /*isTypeof*/ false); checkRefine(requireInst(elseBlk, 0), "x-2", "x-0", /*sense*/ true, "string", /*isTypeof*/ false); } @@ -516,14 +952,29 @@ TEST_CASE_FIXTURE(CFGFixture, "conjunction_emits_flow_per_side") end )"); - REQUIRE(cfg->blocks.size() == 4); - Block* thenBlk = cfg->blocks[1]; - - checkRefine(requireInst(thenBlk, 0), "x-1", "x-0", /*sense*/ true); - checkRefine(requireInst(thenBlk, 1), "y-1", "y-0", /*sense*/ true); - CHECK(requireInst(thenBlk, 2)->def->versionedName() == "z-0"); + REQUIRE(cfg->blocks.size() == 8); + Block* thenBlock = cfg->blocks[1]; + Block* elseBlk = cfg->blocks[2]; + Block* andRhs = cfg->blocks[3]; + Block* lhsFalsy = cfg->blocks[4]; + Block* rhsFalsy = cfg->blocks[5]; + Block* rhsTruthy = cfg->blocks[6]; + Block* merge = cfg->blocks[7]; + + checkSuccessors(*cfg, cfg->blocks[0], {3, 4}); + checkSuccessors(*cfg, andRhs, {5, 6}); + checkSuccessors(*cfg, lhsFalsy, {2}); + checkSuccessors(*cfg, rhsFalsy, {2}); + checkSuccessors(*cfg, rhsTruthy, {1}); + checkPredecessors(*cfg, thenBlock, {6}); + checkPredecessors(*cfg, elseBlk, {4, 5}); + checkPredecessors(*cfg, merge, {1, 2}); - // Falsy side of conjunction is a disjunction (~x \/ ~y) which doesn't decompose yet + checkRefine(requireInst(andRhs, 0), "x-1", "x-0", /*sense*/ true); + checkRefine(requireInst(lhsFalsy, 0), "x-2", "x-0", /*sense*/ false); + checkRefine(requireInst(rhsFalsy, 0), "y-1", "y-0", /*sense*/ false); + checkRefine(requireInst(rhsTruthy, 0), "y-2", "y-0", /*sense*/ true); + CHECK(requireInst(thenBlock, 0)->def->versionedName() == "z-0"); } TEST_SUITE_END(); @@ -532,6 +983,7 @@ TEST_SUITE_BEGIN("CFGTypeCheckTest"); TEST_CASE_FIXTURE(Fixture, "is_truthy_constraint") { + DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; CheckResult result = check(R"( local v : string? @@ -548,6 +1000,7 @@ end TEST_CASE_FIXTURE(Fixture, "invert_is_truthy_constraint") { + DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; CheckResult result = check(R"( local v : string? @@ -564,6 +1017,7 @@ end TEST_CASE_FIXTURE(Fixture, "parenthesized_expressions_are_followed_through") { + DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; CheckResult result = check(R"( local v : string? @@ -580,6 +1034,7 @@ end TEST_CASE_FIXTURE(Fixture, "and_constraint") { + DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; CheckResult result = check(R"( local a : string? @@ -601,6 +1056,7 @@ end TEST_CASE_FIXTURE(Fixture, "not_and_constraint") { + DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; CheckResult result = check(R"( local a : string? @@ -620,21 +1076,233 @@ end LUAU_REQUIRE_NO_ERRORS(result); } -TEST_CASE_FIXTURE(Fixture, "is_truthy_while_loop") +TEST_CASE_FIXTURE(Fixture, "or_predicate_with_truthy_predicates") { + DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; CheckResult result = check(R"( -local v : string? -while v do - local s = v +local a: string? +local b: number? +if a or b then + local x = a + local y = b +else + local x = a + local y = b end )"); - CHECK_EQ("string", toString(requireTypeAtPosition({3, 14}))); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("string?", toString(requireTypeAtPosition({4, 14}))); + CHECK_EQ("number?", toString(requireTypeAtPosition({5, 14}))); + + CHECK_EQ("nil", toString(requireTypeAtPosition({7, 14}))); + CHECK_EQ("nil", toString(requireTypeAtPosition({8, 14}))); +} + +TEST_CASE_FIXTURE(Fixture, "truthy_constraint_on_properties") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local t: {x: number?} + +if t.x then + local y = t.x + local e = y +end + +local bar = t.x +)"); + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("number", toString(requireTypeAtPosition({5, 14}))); + CHECK_EQ("number?", toString(requireType("bar"))); +} + +TEST_CASE_FIXTURE(BuiltinsFixture, "index_on_a_refined_property") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local t: {x: {y: string}?} + +if t.x then + local y = t.x.y + local e = y +end +)"); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("string", toString(requireTypeAtPosition({5, 14}))); +} + +TEST_CASE_FIXTURE(Fixture, "a_and_b_or_a_and_c_simplified") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local a: string? +local b: number? +local c: boolean = true +if (a and b) or (a and c) then + local baz = c +else + local baz = c +end +)"); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("boolean", toString(requireTypeAtPosition({5, 16}))); + CHECK_EQ("boolean", toString(requireTypeAtPosition({7, 16}))); +} + +TEST_CASE_FIXTURE(Fixture, "a_and_b_or_a_and_c") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local a: string? +local b: number? +local c: boolean = true +if (a and b) or (a and c) then + local foo = a + local bar = b + local baz = c +else + local foo = a + local bar = b + local baz = c +end +)"); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("string", toString(requireTypeAtPosition({5, 16}))); + CHECK_EQ("number?", toString(requireTypeAtPosition({6, 16}))); + + // CLI-233402 - Refinements are wonky under the new solver x cfg + // This sucks .. TODO: figure out why + if (FFlag::DebugLuauCFG) + CHECK_EQ("boolean", toString(requireTypeAtPosition({7, 16}))); // oh no! :( + + CHECK_EQ("string?", toString(requireTypeAtPosition({9, 16}))); + CHECK_EQ("number?", toString(requireTypeAtPosition({10, 16}))); + CHECK_EQ("boolean", toString(requireTypeAtPosition({11, 16}))); +} + +TEST_CASE_FIXTURE(Fixture, "type_assertion_expr_carry_its_constraints") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local a: number? +local b: string? +if (a :: any) and (b :: any) then + local x = a + local y = b +end +)"); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("number?", toString(requireTypeAtPosition({4, 14}))); + CHECK_EQ("string?", toString(requireTypeAtPosition({5, 14}))); +} + +TEST_CASE_FIXTURE(BuiltinsFixture, "typeguard_in_if_condition_position") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local s: any +local t: unknown +if type(s) == "number" then + local n = s +end +if type(t) == "number" then + local n = t +end +)"); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("*error-type* | number", toString(requireTypeAtPosition({4, 14}))); + CHECK_EQ("number", toString(requireTypeAtPosition({7, 14}))); +} + + +TEST_CASE_FIXTURE(BuiltinsFixture, "refine_unknown_to_table_then_test_a_prop") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local x: unknown +if typeof(x) == "table" then + if typeof(x.foo) == "string" then + local y = x.foo + end +end +)"); + + LUAU_REQUIRE_NO_ERRORS(result); +} + +TEST_CASE_FIXTURE(BuiltinsFixture, "and_test_table_refine_subprop") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local x: unknown +if typeof(x) == "table" and typeof(x.foo) == "string" then + local y = x.foo +end +)"); + + LUAU_REQUIRE_NO_ERRORS(result); +} + +TEST_CASE_FIXTURE(BuiltinsFixture, "and_test_table_refine_subprop_mismatch") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local x: unknown +if typeof(x) == "table" and typeof(x.foo) == "string" then + local y : number = x.foo +end +)"); + + LUAU_REQUIRE_ERROR_COUNT(1, result); + LUAU_REQUIRE_ERROR(result, TypeMismatch); +} + +TEST_CASE_FIXTURE(BuiltinsFixture, "refine_unknown_to_table_then_test_a_nested_prop") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local x: unknown +if typeof(x) == "table" then + if typeof(x.foo.bar) == "string" then + local y = x.foo.bar + end +end +)"); + + LUAU_REQUIRE_ERROR_COUNT(1, result); + const UnknownProperty* up = get(result.errors[0]); + REQUIRE_EQ("bar", up->key); + REQUIRE_EQ("unknown", toString(up->table)); } TEST_CASE_FIXTURE(Fixture, "invert_is_truthy_while_loop") { + DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; CheckResult result = check(R"( local v : string? @@ -648,6 +1316,7 @@ end TEST_CASE_FIXTURE(BuiltinsFixture, "assert_truthy") { + DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; CheckResult result = check(R"( local foo : string? @@ -659,6 +1328,7 @@ local bar : string = foo TEST_CASE_FIXTURE(BuiltinsFixture, "assert_truthy_then_type_guard") { + DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; CheckResult result = check(R"( local a : (number | string)? @@ -672,6 +1342,115 @@ local c = a LUAU_REQUIRE_NO_ERRORS(result); } +TEST_CASE_FIXTURE(Fixture, "discriminate_tag") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( + type Cat = {tag: "Cat", name: string, catfood: string} + type Dog = {tag: "Dog", name: string, dogfood: string} + type Animal = Cat | Dog + local animal : Animal + if animal.tag == "Cat" then + local cat = animal + elseif animal.tag == "Dog" then + local dog = animal + end + )"); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("Cat", toString(requireTypeAtPosition({6, 24}))); + CHECK_EQ("Dog", toString(requireTypeAtPosition({8, 24}))); +} + +TEST_CASE_FIXTURE(Fixture, "discriminate_tag_with_implicit_else") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( + type Cat = {tag: "Cat", name: string, catfood: string} + type Dog = {tag: "Dog", name: string, dogfood: string} + type Animal = Cat | Dog + local animal : Animal + if animal.tag == "Cat" then + local cat = animal + else + local dog = animal + end + )"); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("Cat", toString(requireTypeAtPosition({6, 24}))); + CHECK_EQ("Dog", toString(requireTypeAtPosition({8, 24}))); +} + +TEST_CASE_FIXTURE(Fixture, "narrow_boolean_to_true_or_false") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( + local x : boolean + if x then + local foo = x + else + local foo = x + end + )"); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("true", toString(requireTypeAtPosition({3, 24}))); + CHECK_EQ("false", toString(requireTypeAtPosition({5, 24}))); +} + +TEST_CASE_FIXTURE(Fixture, "discriminate_on_properties_of_disjoint_tables_where_that_property_is_true_or_false") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( + type Ok = { ok: true, value: T } + type Err = { ok: false, error: E } + type Result = Ok | Err + local t : Result + if t.ok then + local a = t.value + local _ = a + else + local b = t.error + local _ = b + end + )"); + + LUAU_REQUIRE_NO_ERRORS(result); + CHECK_EQ("Ok", toString(requireTypeAtPosition({6, 22}))); + CHECK_EQ("number", toString(requireTypeAtPosition({7, 22}))); + CHECK_EQ("Err", toString(requireTypeAtPosition({9, 22}))); + CHECK_EQ("string", toString(requireTypeAtPosition({10, 22}))); +} + +TEST_CASE_FIXTURE(Fixture, "new_functions_work") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local function f(x: number?) + if not x then + x = 0 + end + local e = x > 0 +end +)"); + LUAU_REQUIRE_NO_ERRORS(result); +} + + + +TEST_SUITE_END(); + + +TEST_SUITE_BEGIN("NewCFGInference"); // Begin - stuff we aren't able to infer with the existing type inference system TEST_CASE_FIXTURE(Fixture, "interesting_refinement") { @@ -705,5 +1484,19 @@ end LUAU_REQUIRE_NO_ERRORS(result); } + +TEST_CASE_FIXTURE(Fixture, "is_truthy_while_loop") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + ScopedFastFlag sff{FFlag::DebugLuauCFG, true}; + CheckResult result = check(R"( +local v : string? +while v do + local s = v +end +)"); + CHECK_EQ("string", toString(requireTypeAtPosition({3, 14}))); + LUAU_REQUIRE_NO_ERRORS(result); +} // End - stuff we aren't able to infer with the existing type inference system TEST_SUITE_END(); diff --git a/tests/CostModel.test.cpp b/tests/CostModel.test.cpp index d11bd1bab..dc656ed29 100644 --- a/tests/CostModel.test.cpp +++ b/tests/CostModel.test.cpp @@ -6,6 +6,7 @@ #include "doctest.h" LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) using namespace Luau; @@ -251,4 +252,43 @@ end CHECK_EQ(1, Luau::Compile::computeCost(model, args2, 1)); } +TEST_CASE("WhileLocal") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + uint64_t model = modelFunction(R"( +function test(a) + while local b = a * a * a do + return b * b + end + return 0 +end +)"); + const bool args1[] = {false}; + const bool args2[] = {true}; + + CHECK_EQ(9, Luau::Compile::computeCost(model, args1, 1)); + CHECK_EQ(0, Luau::Compile::computeCost(model, args2, 1)); +} + +TEST_CASE("WhileConst") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + // `while const` should be identical to `while local` + uint64_t model = modelFunction(R"( +function test(a) + while const b = a * a * a do + return b * b + end + return 0 +end +)"); + const bool args1[] = {false}; + const bool args2[] = {true}; + + CHECK_EQ(9, Luau::Compile::computeCost(model, args1, 1)); + CHECK_EQ(0, Luau::Compile::computeCost(model, args2, 1)); +} + TEST_SUITE_END(); diff --git a/tests/FragmentAutocomplete.test.cpp b/tests/FragmentAutocomplete.test.cpp index b5774fdc4..c955a59d9 100644 --- a/tests/FragmentAutocomplete.test.cpp +++ b/tests/FragmentAutocomplete.test.cpp @@ -30,6 +30,8 @@ LUAU_FASTFLAG(LuauAutocompleteIfSlurpsCond) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) LUAU_FASTFLAG(LuauRefactorAutocompleteAncestry) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) static std::optional nullCallback(std::string tag, std::optional ptr, std::optional contents) { @@ -6014,4 +6016,150 @@ function tbl.a@1 ); } +TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "while_local_optional_binding_member_completion_in_body") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + const std::string source = R"( +type Test = {name: string, age: number} +local function getTester(): Test? return nil end +local function sample() + while local myTest = getTester() do + + end +end +)"; + const std::string updated = R"( +type Test = {name: string, age: number} +local function getTester(): Test? return nil end +local function sample() + while local myTest = getTester() do + myTest.@1 + end +end +)"; + + autocompleteFragmentInNewSolver( + source, + updated, + '1', + [](FragmentAutocompleteStatusResult& fragment) + { + REQUIRE(fragment.result); + CHECK(fragment.result->acResults.entryMap.count("name")); + CHECK(fragment.result->acResults.entryMap.count("age")); + } + ); +} + +TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "while_local_optional_binding_is_in_scope_in_body") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + const std::string source = R"( +type Test = {name: string, age: number} +local function getTester(): Test? return nil end +local function sample() + while local myTest = getTester() do + + end +end +)"; + const std::string updated = R"( +type Test = {name: string, age: number} +local function getTester(): Test? return nil end +local function sample() + while local myTest = getTester() do + @1 + end +end +)"; + + autocompleteFragmentInNewSolver( + source, + updated, + '1', + [](FragmentAutocompleteStatusResult& fragment) + { + REQUIRE(fragment.result); + CHECK(fragment.result->acResults.entryMap.count("myTest")); + } + ); +} + +TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "nested_while_local_bindings_are_both_in_scope") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + const std::string source = R"( +type Test = {name: string, age: number} +local function getTester(): Test? return nil end +local function sample() + while local outer = getTester() do + while local inner = getTester() do + + end + end +end +)"; + const std::string updated = R"( +type Test = {name: string, age: number} +local function getTester(): Test? return nil end +local function sample() + while local outer = getTester() do + while local inner = getTester() do + @1 + end + end +end +)"; + + autocompleteFragmentInNewSolver( + source, + updated, + '1', + [](FragmentAutocompleteStatusResult& fragment) + { + REQUIRE(fragment.result); + CHECK(fragment.result->acResults.entryMap.count("outer")); + CHECK(fragment.result->acResults.entryMap.count("inner")); + } + ); +} + +TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "while_local_binding_is_not_in_scope_after_while_statement") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + + const std::string source = R"( +type Test = {name: string, age: number} +local function getTester(): Test? return nil end +local function sample() + while local myTest = getTester() do + end + +end +)"; + const std::string updated = R"( +type Test = {name: string, age: number} +local function getTester(): Test? return nil end +local function sample() + while local myTest = getTester() do + end + @1 +end +)"; + + autocompleteFragmentInNewSolver( + source, + updated, + '1', + [](FragmentAutocompleteStatusResult& fragment) + { + REQUIRE(fragment.result); + LUAU_CHECK_HAS_NO_KEY(fragment.result->acResults.entryMap, "myTest"); + } + ); +} + TEST_SUITE_END(); diff --git a/tests/IrAssembly.test.cpp b/tests/IrAssembly.test.cpp index ef285db66..061471d04 100644 --- a/tests/IrAssembly.test.cpp +++ b/tests/IrAssembly.test.cpp @@ -9,9 +9,6 @@ #include -LUAU_FASTFLAG(LuauCodegenX64IntSpillRestore) -LUAU_FASTFLAG(LuauCodegenExitSyncUpdate) -LUAU_FASTFLAG(LuauCodegenScopedSpillKeepLazy) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) using namespace Luau::CodeGen; @@ -581,8 +578,6 @@ TEST_CASE_FIXTURE(IrAssemblyFixture, "DseHintUpdateRedirectsLazyRestoreToLaterRe TEST_CASE_FIXTURE(IrAssemblyFixture, "IntStackSpillIgnoresConvertedRestoreLocation") { - ScopedFastFlag luauCodegenX64IntSpillRestore{FFlag::LuauCodegenX64IntSpillRestore, true}; - options.includeRegSpills = true; IrOp entry = build.block(IrBlockKind::Internal); @@ -661,7 +656,6 @@ TEST_CASE_FIXTURE(IrAssemblyFixture, "IntStackSpillIgnoresConvertedRestoreLocati TEST_CASE_FIXTURE(IrAssemblyFixture, "ExitSyncRestoreConflictedRegisters") { - ScopedFastFlag luauCodegenExitSyncUpdate{FFlag::LuauCodegenExitSyncUpdate, true}; ScopedFastFlag luauCodegenImprovedExitSync{FFlag::LuauCodegenImprovedExitSync, true}; options.includeOutlinedCode = true; @@ -736,7 +730,6 @@ TEST_CASE_FIXTURE(IrAssemblyFixture, "ExitSyncRestoreConflictedRegisters") TEST_CASE_FIXTURE(IrAssemblyFixture, "ExitSyncRestoreConflictedDependent") { - ScopedFastFlag luauCodegenExitSyncUpdate{FFlag::LuauCodegenExitSyncUpdate, true}; ScopedFastFlag luauCodegenImprovedExitSync{FFlag::LuauCodegenImprovedExitSync, true}; options.includeOutlinedCode = true; @@ -826,8 +819,6 @@ TEST_CASE_FIXTURE(IrAssemblyFixture, "ExitSyncRestoreConflictedDependent") TEST_CASE_FIXTURE(IrAssemblyFixture, "LazyHintNotMaterializedInsideScopedSpills") { - ScopedFastFlag luauCodegenScopedSpillKeepLazy{FFlag::LuauCodegenScopedSpillKeepLazy, true}; - options.includeRegSpills = true; IrOp entry = build.block(IrBlockKind::Internal); diff --git a/tests/IrBuilder.test.cpp b/tests/IrBuilder.test.cpp index c6263c736..6f2ad3292 100644 --- a/tests/IrBuilder.test.cpp +++ b/tests/IrBuilder.test.cpp @@ -17,8 +17,7 @@ LUAU_FASTFLAG(LuauCodegenInteger3) LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauIntegerLibrary) LUAU_FASTFLAG(LuauCodegenPropagateFallbackTags) -LUAU_FASTFLAG(LuauCodegenNoZeroScale) -LUAU_FASTFLAG(LuauCodegenLimitVersionsExtra) +LUAU_FASTFLAG(LuauCodegenCmpAnySideEffecting) using namespace Luau::CodeGen; @@ -5739,8 +5738,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "BufferLengthChecksIntegerMatch2") TEST_CASE_FIXTURE(IrBuilderFixture, "BufferLengthCheckIntVsDouble") { - ScopedFastFlag luauCodegenNoZeroScale{FFlag::LuauCodegenNoZeroScale, true}; - IrOp block = build.block(IrBlockKind::Internal); IrOp fallback = build.fallbackBlock(0u); @@ -7008,7 +7005,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "IndirectFloatLoadExtractionMustRespectVersi TEST_CASE_FIXTURE(IrBuilderFixture, "VersionLimitChecks") { ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - ScopedFastFlag luauCodegenLimitVersionsExtra{FFlag::LuauCodegenLimitVersionsExtra, true}; IrOp entry = build.block(IrBlockKind::Internal); IrOp unrelated = build.block(IrBlockKind::Internal); @@ -8405,6 +8401,33 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "DsePartialStoreWithKnownTagFromPredecessors )"); } +TEST_CASE_FIXTURE(IrBuilderFixture, "DseCmpAnySideEffects") +{ + ScopedFastFlag luauCodegenCmpAnySideEffecting{FFlag::LuauCodegenCmpAnySideEffecting, true}; + + IrOp block = build.block(IrBlockKind::Internal); + + build.beginBlock(block); + + IrOp result = build.inst(IrCmd::CMP_ANY, build.vmReg(0), build.vmReg(0), build.cond(IrCondition::Equal)); + build.inst(IrCmd::STORE_INT, build.vmReg(1), result); + build.inst(IrCmd::STORE_TAG, build.vmReg(1), build.constTag(tboolean)); + build.inst(IrCmd::RETURN, build.vmReg(0), build.constInt(0)); + + updateUseCounts(build.function); + computeCfgInfo(build.function); + constPropInBlockChains(build); + markDeadStoresInBlockChains(build); + + CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( +bb_0: +; in regs: R0 + %0 = CMP_ANY R0, R0, eq + RETURN R0, 0i + +)"); +} + TEST_CASE_FIXTURE(IrBuilderFixture, "DseVmExitSyncBasic") { IrOp block = build.block(IrBlockKind::Internal); diff --git a/tests/IrLowering.test.cpp b/tests/IrLowering.test.cpp index c2323115f..d64dc6da6 100644 --- a/tests/IrLowering.test.cpp +++ b/tests/IrLowering.test.cpp @@ -20,6 +20,7 @@ LUAU_FASTFLAG(LuauIntegerFastcalls) LUAU_FASTFLAG(LuauCodegenInteger3) LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauCodegenBufferInteger) +LUAU_FASTFLAG(LuauCodegenMarkUsed) LUAU_FASTFLAG(LuauIntegerBufferFastcalls) LUAU_FASTFLAG(LuauEmitCallFeedback) LUAU_FASTFLAG(LuauCodegenPropagateFallbackTags) @@ -2820,6 +2821,7 @@ TEST_CASE_FIXTURE(LoweringFixture, "TableNodeLoadStoreProp5") ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; ScopedFastFlag luauCompileReuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; + ScopedFastFlag luauCodegenMarkUsed{FFlag::LuauCodegenMarkUsed, true}; CHECK_EQ( "\n" + getCodegenAssembly( @@ -2871,42 +2873,42 @@ end %263 = NUM_TO_FLOAT %261 STORE_VECTOR R2, %262, %263, 0 STORE_TAG R2, tvector - %266 = LOAD_TVALUE R1, 0i, tvector - %267 = LOAD_TVALUE R2, 0i, tvector - %268 = MUL_VEC %266, %267 - %271 = LOAD_TVALUE K5 (0.5, 0.5, 0), 0i, tvector - %273 = SUB_VEC %268, %271 - %276 = FLOOR_VEC %273 - %279 = CEIL_VEC %273 - %282 = SUB_VEC %273, %276 - %283 = TAG_VECTOR %282 - STORE_TVALUE R4, %283 - %285 = EXTRACT_VEC %276, 0i - %286 = FLOAT_TO_NUM %285 + %267 = LOAD_TVALUE R1, 0i, tvector + %268 = LOAD_TVALUE R2, 0i, tvector + %269 = MUL_VEC %267, %268 + %272 = LOAD_TVALUE K5 (0.5, 0.5, 0), 0i, tvector + %274 = SUB_VEC %269, %272 + %277 = FLOOR_VEC %274 + %281 = CEIL_VEC %274 + %285 = SUB_VEC %274, %277 + %286 = TAG_VECTOR %285 + STORE_TVALUE R4, %286 + %288 = EXTRACT_VEC %277, 0i + %289 = FLOAT_TO_NUM %288 STORE_TVALUE R7, %11 - %299 = MOD_NUM %286, %260 - STORE_DOUBLE R5, %299 + %302 = MOD_NUM %289, %260 + STORE_DOUBLE R5, %302 STORE_TAG R5, tnumber - %303 = EXTRACT_VEC %279, 0i - %304 = FLOAT_TO_NUM %303 - STORE_DOUBLE R7, %304 + %306 = EXTRACT_VEC %281, 0i + %307 = FLOAT_TO_NUM %306 + STORE_DOUBLE R7, %307 STORE_TVALUE R8, %11 - %317 = MOD_NUM %304, %260 - STORE_SPLIT_TVALUE R6, tnumber, %317 - %321 = EXTRACT_VEC %276, 1i - %322 = FLOAT_TO_NUM %321 - %335 = MOD_NUM %322, %261 - STORE_DOUBLE R8, %335 + %320 = MOD_NUM %307, %260 + STORE_SPLIT_TVALUE R6, tnumber, %320 + %324 = EXTRACT_VEC %277, 1i + %325 = FLOAT_TO_NUM %324 + %338 = MOD_NUM %325, %261 + STORE_DOUBLE R8, %338 STORE_TVALUE R9, %11 - %351 = MUL_NUM %335, %260 - STORE_DOUBLE R7, %351 - %355 = EXTRACT_VEC %279, 1i - %356 = FLOAT_TO_NUM %355 - STORE_DOUBLE R9, %356 - %369 = MOD_NUM %356, %261 - STORE_DOUBLE R8, %369 - %385 = MUL_NUM %369, %260 - STORE_SPLIT_TVALUE R8, tnumber, %385 + %354 = MUL_NUM %338, %260 + STORE_DOUBLE R7, %354 + %358 = EXTRACT_VEC %281, 1i + %359 = FLOAT_TO_NUM %358 + STORE_DOUBLE R9, %359 + %372 = MOD_NUM %359, %261 + STORE_DOUBLE R8, %372 + %388 = MUL_NUM %372, %260 + STORE_SPLIT_TVALUE R8, tnumber, %388 INTERRUPT 50u RETURN R4, 5i )" @@ -5574,6 +5576,8 @@ end TEST_CASE_FIXTURE(LoweringFixture, "BufferSanityPositive") { + ScopedFastFlag luauCodegenMarkUsed{FFlag::LuauCodegenMarkUsed, true}; + CHECK_EQ( "\n" + getCodegenAssembly(R"( local function foo(zero: number, b1: buffer, b2: buffer) @@ -5609,7 +5613,8 @@ end %70 = BUFFER_READU8 %25, %27, tbuffer BUFFER_WRITEI8 %25, %27, %70, tbuffer %107 = LOAD_POINTER R2 - CHECK_BUFFER_LEN %107, %27, 0i, 2i, %10, exit(32) + CHECK_BUFFER_LEN %107, %27, 0i, 2i, %10, bb_exit_20 + ; exit sync: R8, R5, {%10} %111 = BUFFER_READI8 %107, %27, tbuffer BUFFER_WRITEI8 %107, %27, %111, tbuffer %152 = BUFFER_READU8 %107, %27, tbuffer @@ -5631,6 +5636,8 @@ end TEST_CASE_FIXTURE(LoweringFixture, "BufferSanityNegative") { + ScopedFastFlag luauCodegenMarkUsed{FFlag::LuauCodegenMarkUsed, true}; + CHECK_EQ( "\n" + getCodegenAssembly(R"( local function foo(one: number, b1: buffer, b2: buffer) @@ -5667,7 +5674,8 @@ end %70 = BUFFER_READU8 %25, %27, tbuffer BUFFER_WRITEI8 %25, %27, %70, tbuffer %107 = LOAD_POINTER R2 - CHECK_BUFFER_LEN %107, %27, 0i, 2i, %11, exit(32) + CHECK_BUFFER_LEN %107, %27, 0i, 2i, %11, bb_exit_20 + ; exit sync: R8, R5, {%11} %111 = BUFFER_READI8 %107, %27, tbuffer BUFFER_WRITEI8 %107, %27, %111, tbuffer %152 = BUFFER_READU8 %107, %27, tbuffer @@ -6070,6 +6078,8 @@ end TEST_CASE_FIXTURE(LoweringFixture, "BufferEffects") { + ScopedFastFlag luauCodegenMarkUsed{FFlag::LuauCodegenMarkUsed, true}; + CHECK_EQ( "\n" + getCodegenAssembly( R"( @@ -6124,12 +6134,12 @@ end %112 = BUFFER_READF64 %15, 0i, tbuffer STORE_DOUBLE R4, %112 STORE_TAG R4, tnumber - %115 = LOAD_TVALUE R1 - STORE_TVALUE R5, %115 - %117 = LOAD_TVALUE R2 - STORE_TVALUE R6, %117 - %119 = LOAD_TVALUE R3 - STORE_TVALUE R7, %119 + %116 = LOAD_TVALUE R1 + STORE_TVALUE R5, %116 + %118 = LOAD_TVALUE R2 + STORE_TVALUE R6, %118 + %120 = LOAD_TVALUE R3 + STORE_TVALUE R7, %120 INTERRUPT 42u RETURN R4, 4i )" @@ -7073,6 +7083,7 @@ TEST_CASE_FIXTURE(LoweringFixture, "FuzzTest26") ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; + ScopedFastFlag luauCodegenImprovedExitSync{FFlag::LuauCodegenImprovedExitSync, true}; CHECK( getCodegenAssembly( diff --git a/tests/IrRegAllocX64.test.cpp b/tests/IrRegAllocX64.test.cpp index 3606cabda..3e4749ba5 100644 --- a/tests/IrRegAllocX64.test.cpp +++ b/tests/IrRegAllocX64.test.cpp @@ -7,8 +7,6 @@ using namespace Luau::CodeGen; using namespace Luau::CodeGen::X64; -LUAU_FASTFLAG(LuauCodegenX64IntSpillRestore) - class IrRegAllocX64Fixture { public: @@ -62,8 +60,6 @@ TEST_CASE_FIXTURE(IrRegAllocX64Fixture, "RelocateFix") TEST_CASE_FIXTURE(IrRegAllocX64Fixture, "RestoreStackSpillIgnoresLaterConvertedLocation") { - ScopedFastFlag luauCodegenX64IntSpillRestore{FFlag::LuauCodegenX64IntSpillRestore, true}; - IrInst irInst0{IrCmd::BUFFER_READI32}; irInst0.lastUse = 2; function.instructions.push_back(irInst0); diff --git a/tests/Normalize.test.cpp b/tests/Normalize.test.cpp index 1feabd971..466f50cb0 100644 --- a/tests/Normalize.test.cpp +++ b/tests/Normalize.test.cpp @@ -18,6 +18,7 @@ LUAU_FASTFLAG(LuauFixNormalizeFunctionIntersections) LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(DebugLuauParseExactTables) LUAU_FASTFLAG(DebugLuauExactTableTypes) +LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) using namespace Luau; @@ -1412,6 +1413,124 @@ TEST_CASE_FIXTURE(NormalizeFixture, "intersection_of_table_and_truthy") CHECK("(userdata & { x: number, ... }) | { x: number, ... }" == toString(ty)); } +TEST_CASE_FIXTURE(NormalizeFixture, "negation_of_testable_intersection_type_1") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + + ScopedFastFlag _{FFlag::LuauDecomposeIntersectionOfFreeType, true}; + + IntersectionBuilder ib{NotNull{&arena}, NotNull{getBuiltins()}}; + ib.add(getBuiltins()->numberType); + ib.add(arena.addType( + NegationType{arena.addType( + IntersectionType{{getBuiltins()->stringType, arena.addType(NegationType{arena.addType(SingletonType{StringSingleton{"foo"}})})}} + )} + )); + + // number & ~(string & ~"foo") => number + auto norm = normalize(ib.build()); + REQUIRE(norm); + TypeId ty = typeFromNormal(*norm); + + CHECK("number" == toString(ty)); +} + +TEST_CASE_FIXTURE(NormalizeFixture, "negation_of_testable_intersection_type_2") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + + ScopedFastFlag sffs[] = { + {FFlag::LuauDecomposeIntersectionOfFreeType, true}, + // This is forced on here so that I don't need to check the + // output string twice, it's not essential to the test. + {FFlag::LuauIntegerType2, true}, + }; + + + IntersectionBuilder ib{NotNull{&arena}, NotNull{getBuiltins()}}; + ib.add(getBuiltins()->unknownType); + ib.add(arena.addType( + NegationType{arena.addType( + IntersectionType{{getBuiltins()->stringType, arena.addType(NegationType{arena.addType(SingletonType{StringSingleton{"foo"}})})}} + )} + )); + + // unknown & ~(string & ~"foo") => ~(string & ~"foo") + auto norm = normalize(ib.build()); + REQUIRE(norm); + TypeId ty = typeFromNormal(*norm); + + CHECK("(\"foo\" | boolean | buffer | function | integer | number | table | thread | userdata)?" == toString(ty)); +} + +TEST_CASE_FIXTURE(NormalizeFixture, "negation_of_testable_intersection_type_3") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + + ScopedFastFlag _{FFlag::LuauDecomposeIntersectionOfFreeType, true}; + + IntersectionBuilder ib{NotNull{&arena}, NotNull{getBuiltins()}}; + ib.add(getBuiltins()->neverType); + ib.add(arena.addType( + NegationType{arena.addType( + IntersectionType{{getBuiltins()->stringType, arena.addType(NegationType{arena.addType(SingletonType{StringSingleton{"foo"}})})}} + )} + )); + + // never & ~(string & ~"foo") => never + auto norm = normalize(ib.build()); + REQUIRE(norm); + TypeId ty = typeFromNormal(*norm); + + CHECK("never" == toString(ty)); +} + +TEST_CASE_FIXTURE(NormalizeFixture, "negation_of_testable_intersection_type_4") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + + ScopedFastFlag _{FFlag::LuauDecomposeIntersectionOfFreeType, true}; + + IntersectionBuilder ib{NotNull{&arena}, NotNull{getBuiltins()}}; + auto fooTy = arena.addType(SingletonType{StringSingleton{"foo"}}); + ib.add(fooTy); + ib.add(arena.addType( + NegationType{arena.addType( + IntersectionType{{getBuiltins()->stringType, arena.addType(NegationType{fooTy})}} + )} + )); + + // "foo" & ~(string & ~"foo") => "foo" + auto norm = normalize(ib.build()); + REQUIRE(norm); + TypeId ty = typeFromNormal(*norm); + + CHECK("\"foo\"" == toString(ty)); +} + +TEST_CASE_FIXTURE(NormalizeFixture, "negation_of_testable_union_type") +{ + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + + IntersectionBuilder ib{NotNull{&arena}, NotNull{getBuiltins()}}; + ib.add(getBuiltins()->numberType); + ib.add(arena.addType( + NegationType{arena.addType( + UnionType{{ + getBuiltins()->stringType, + getBuiltins()->booleanType, + }} + )} + )); + + // number & ~(string | boolean) => number + auto norm = normalize(ib.build()); + REQUIRE(norm); + TypeId ty = typeFromNormal(*norm); + + CHECK("number" == toString(ty)); +} + TEST_CASE_FIXTURE(BuiltinsFixture, "normalizer_should_be_able_to_detect_cyclic_tables_and_not_stack_overflow") { if (FFlag::DebugLuauForceOldSolver) diff --git a/tests/OverloadResolver.test.cpp b/tests/OverloadResolver.test.cpp index a1f806d98..22871fdf6 100644 --- a/tests/OverloadResolver.test.cpp +++ b/tests/OverloadResolver.test.cpp @@ -8,6 +8,7 @@ #include "Luau/UnifierSharedState.h" LUAU_FASTFLAG(DebugLuauForceOldSolver) +LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) using namespace Luau; @@ -109,7 +110,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_basic_overload_selection") // ty: (number) -> number & (string) -> string // args: (number) OverloadResolution result = - resolver.resolveOverload(numberToNumberAndStringToString, pack({getBuiltins()->numberType}), Location{}, emptySet, false); + resolver.resolveOverload(numberToNumberAndStringToString, pack({getBuiltins()->numberType}), Location{}, false); CHECK(1 == result.ok.size()); CHECK(result.ok.at(0) == numberToNumber); @@ -120,7 +121,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_basic_overload_selection1") // ty: (number) -> number & (string) -> string // args: (string) OverloadResolution result = - resolver.resolveOverload(numberToNumberAndStringToString, pack({getBuiltins()->stringType}), Location{}, emptySet, false); + resolver.resolveOverload(numberToNumberAndStringToString, pack({getBuiltins()->stringType}), Location{}, false); CHECK(1 == result.ok.size()); CHECK(stringToString == result.ok.at(0)); @@ -135,7 +136,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_match_call_metamethod") TypeId callMm = fn({builtinTypes->unknownType, builtinTypes->numberType}, {builtinTypes->numberType}); TypeId tbl = tableWithCall(callMm); - OverloadResolution result = resolver.resolveOverload(tbl, pack({builtinTypes->numberType}), Location{}, emptySet, false); + OverloadResolution result = resolver.resolveOverload(tbl, pack({builtinTypes->numberType}), Location{}, false); // Possible design issue here: We're indicating that an overload matches, // but it clearly has a different arity than the type pack that was @@ -155,7 +156,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_metamethod_could_be_overloaded") TypeId overload2 = fn({builtinTypes->unknownType, builtinTypes->stringType}, {builtinTypes->stringType}); TypeId tbl = tableWithCall(meet(overload1, overload2)); - OverloadResolution result = resolver.resolveOverload(tbl, pack({builtinTypes->numberType}), Location{}, emptySet, false); + OverloadResolution result = resolver.resolveOverload(tbl, pack({builtinTypes->numberType}), Location{}, false); // Possible design issue here: We're indicating that an overload matches, // but it clearly has a different arity than the type pack that was @@ -180,7 +181,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_overload_group_could_include_met TypeId monstrosity = meet(tbl, fn({builtinTypes->booleanType}, {builtinTypes->booleanType})); - OverloadResolution result = resolver.resolveOverload(monstrosity, pack({builtinTypes->numberType}), Location{}, emptySet, false); + OverloadResolution result = resolver.resolveOverload(monstrosity, pack({builtinTypes->numberType}), Location{}, false); CHECK(1 == result.ok.size()); CHECK(overload1 == result.ok.at(0)); @@ -191,7 +192,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_overloads_with_different_arities // ty: (number) -> number & (number, number) -> number // args: (number) OverloadResolution result = - resolver.resolveOverload(numberToNumberAndNumberNumberToNumber, pack({getBuiltins()->numberType}), Location{}, emptySet, false); + resolver.resolveOverload(numberToNumberAndNumberNumberToNumber, pack({getBuiltins()->numberType}), Location{}, false); CHECK(1 == result.ok.size()); CHECK(numberToNumber == result.ok.at(0)); @@ -205,7 +206,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_overloads_with_different_arities // ty: (number) -> number & (number, number) -> number // args: (number, number) OverloadResolution result = resolver.resolveOverload( - numberToNumberAndNumberNumberToNumber, pack({getBuiltins()->numberType, getBuiltins()->numberType}), Location{}, emptySet, false + numberToNumberAndNumberNumberToNumber, pack({getBuiltins()->numberType, getBuiltins()->numberType}), Location{}, false ); CHECK(1 == result.ok.size()); @@ -222,7 +223,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_separate_non_viable_overloads_by const TypePack args = TypePack{{builtinTypes->stringType}, std::nullopt}; OverloadResolution resolution = resolver.resolveOverload( - meet({numberToNumber, numberToString, numberNumberToNumber}), pack({builtinTypes->stringType}), Location{}, emptySet, false + meet({numberToNumber, numberToString, numberNumberToNumber}), pack({builtinTypes->stringType}), Location{}, false ); CHECK(resolution.ok.empty()); @@ -253,13 +254,14 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_select") OverloadResolver r = mkResolver(); OverloadResolution resolution = - r.resolveOverload(selectTy, arena->addTypePack({numberOrString}, builtinTypes->anyTypePack), Location{}, emptySet, false); + r.resolveOverload(selectTy, arena->addTypePack({numberOrString}, builtinTypes->anyTypePack), Location{}, false); CHECK(1 == resolution.ok.size()); } TEST_CASE_FIXTURE(OverloadResolverFixture, "new_pass_table_with_indexer") { + ScopedFastFlag _{FFlag::LuauOneBitAssumedConstraintTracking, true}; // {[any]: number} TypeId anyNumberTable = arena->addType( TableType{TableType::Props{}, TableIndexer{builtinTypes->anyType, builtinTypes->numberType}, TypeLevel{}, &rootScope, TableState::Sealed} @@ -268,7 +270,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "new_pass_table_with_indexer") TypeId tableToTable = fn({anyNumberTable}, {anyNumberTable}); OverloadResolver r = mkResolver(); - OverloadResolution resolution = r.resolveOverload(tableToTable, pack({anyNumberTable}), Location{}, emptySet, false); + OverloadResolution resolution = r.resolveOverload(tableToTable, pack({anyNumberTable}), Location{}, false); CHECK(1 == resolution.ok.size()); CHECK(0 == resolution.potentialOverloads.size()); @@ -293,7 +295,7 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "generic_higher_order_function_called TypePackId callArgsPack = pack({numberNumberToNumber, builtinTypes->numberType}); OverloadResolver r = mkResolver(); - OverloadResolution resolution = r.resolveOverload(applyTy, callArgsPack, Location{}, emptySet, false); + OverloadResolution resolution = r.resolveOverload(applyTy, callArgsPack, Location{}, false); CHECK(1 == resolution.ok.size()); } @@ -311,38 +313,38 @@ TEST_CASE_FIXTURE(OverloadResolverFixture, "debug_traceback") SUBCASE("no_arguments") { - resolution = r.resolveOverload(debugTraceback, builtinTypes->emptyTypePack, Location{}, emptySet, false); + resolution = r.resolveOverload(debugTraceback, builtinTypes->emptyTypePack, Location{}, false); CHECK(1 == resolution.ok.size()); } SUBCASE("message_only") { - resolution = r.resolveOverload(debugTraceback, pack({builtinTypes->stringType}), Location{}, emptySet, false); + resolution = r.resolveOverload(debugTraceback, pack({builtinTypes->stringType}), Location{}, false); CHECK(1 == resolution.ok.size()); } SUBCASE("message_and_level") { - resolution = r.resolveOverload(debugTraceback, pack({builtinTypes->stringType, builtinTypes->numberType}), Location{}, emptySet, false); + resolution = r.resolveOverload(debugTraceback, pack({builtinTypes->stringType, builtinTypes->numberType}), Location{}, false); CHECK(1 == resolution.ok.size()); } SUBCASE("thread") { - resolution = r.resolveOverload(debugTraceback, pack({builtinTypes->threadType}), Location{}, emptySet, false); + resolution = r.resolveOverload(debugTraceback, pack({builtinTypes->threadType}), Location{}, false); CHECK(1 == resolution.ok.size()); } SUBCASE("thread_and_message") { - resolution = r.resolveOverload(debugTraceback, pack({builtinTypes->threadType, builtinTypes->stringType}), Location{}, emptySet, false); + resolution = r.resolveOverload(debugTraceback, pack({builtinTypes->threadType, builtinTypes->stringType}), Location{}, false); CHECK(1 == resolution.ok.size()); } SUBCASE("thread_message_and_level") { resolution = r.resolveOverload( - debugTraceback, pack({builtinTypes->threadType, builtinTypes->stringType, builtinTypes->numberType}), Location{}, emptySet, false + debugTraceback, pack({builtinTypes->threadType, builtinTypes->stringType, builtinTypes->numberType}), Location{}, false ); CHECK(1 == resolution.ok.size()); } diff --git a/tests/Parser.test.cpp b/tests/Parser.test.cpp index 93557f81c..7da77dd5d 100644 --- a/tests/Parser.test.cpp +++ b/tests/Parser.test.cpp @@ -26,6 +26,8 @@ LUAU_FASTFLAG(DebugLuauParseExactTables) LUAU_FASTFLAG(LuauSingleTypeOptionalPackReturnsAttributeParens) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) + // Clip with DebugLuauReportReturnTypeVariadicWithTypeSuffix extern bool luau_telemetry_parsed_return_type_variadic_with_type_suffix; @@ -7105,4 +7107,211 @@ TEST_CASE_FIXTURE(Fixture, "parse_if_local_expression_nested_in_true_branch") CHECK(inner->conditionLocal != outer->conditionLocal); } +TEST_CASE_FIXTURE(Fixture, "parse_while_local") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + AstStatBlock* block = parse(R"( + while local x = getValue() do + print(x) + end + )"); + + REQUIRE(block != nullptr); + REQUIRE(block->body.size == 1); + AstStatWhile* whileStat = block->body.data[0]->as(); + REQUIRE(whileStat != nullptr); + CHECK(whileStat->conditionLocal != nullptr); + CHECK(whileStat->conditionLocal->name == "x"); + CHECK(whileStat->condition != nullptr); + CHECK(whileStat->hasDo); + CHECK_FALSE(whileStat->conditionIsConst); +} + +TEST_CASE_FIXTURE(Fixture, "parse_while_const") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + AstStatBlock* block = parse(R"( + while const x = getValue() do + print(x) + end + )"); + + REQUIRE(block != nullptr); + REQUIRE(block->body.size == 1); + AstStatWhile* whileStat = block->body.data[0]->as(); + REQUIRE(whileStat != nullptr); + CHECK(whileStat->conditionLocal != nullptr); + CHECK(whileStat->conditionLocal->name == "x"); + CHECK(whileStat->conditionIsConst); +} + +TEST_CASE_FIXTURE(Fixture, "parse_while_const_with_annotation") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + AstStatBlock* block = parse(R"( + while const x: number = getValue() do + print(x) + end + )"); + + REQUIRE(block != nullptr); + REQUIRE(block->body.size == 1); + AstStatWhile* whileStat = block->body.data[0]->as(); + REQUIRE(whileStat != nullptr); + REQUIRE(whileStat->conditionLocal != nullptr); + CHECK(whileStat->conditionLocal->annotation != nullptr); + CHECK(whileStat->conditionIsConst); +} + +TEST_CASE_FIXTURE(Fixture, "parse_while_const_compat") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + // `const` not followed by a binding name is a plain condition expression (the global `const`), + // not a `while const` binding, keeping `const` usable as an ordinary identifier + AstStatBlock* block = parse(R"( + while const do + end + )"); + + REQUIRE(block != nullptr); + REQUIRE(block->body.size == 1); + AstStatWhile* whileStat = block->body.data[0]->as(); + REQUIRE(whileStat != nullptr); + CHECK(whileStat->conditionLocal == nullptr); + CHECK_FALSE(whileStat->conditionIsConst); + CHECK(whileStat->condition->as() != nullptr); +} + +TEST_CASE_FIXTURE(Fixture, "parse_while_local_with_annotation") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + AstStatBlock* block = parse(R"( + while local x: number = getValue() do + print(x) + end + )"); + + REQUIRE(block != nullptr); + REQUIRE(block->body.size == 1); + AstStatWhile* whileStat = block->body.data[0]->as(); + REQUIRE(whileStat != nullptr); + REQUIRE(whileStat->conditionLocal != nullptr); + CHECK(whileStat->conditionLocal->annotation != nullptr); +} + +TEST_CASE_FIXTURE(Fixture, "parse_while_local_binding_visible_in_body") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + AstStatBlock* block = parse(R"( + while local x = getValue() do + print(x) + end + )"); + + REQUIRE(block != nullptr); + AstStatWhile* whileStat = block->body.data[0]->as(); + REQUIRE(whileStat != nullptr); + REQUIRE(whileStat->conditionLocal != nullptr); + + // the `x` referenced inside the body resolves to the condition binding + AstStatExpr* stmt = whileStat->body->body.data[0]->as(); + REQUIRE(stmt != nullptr); + AstExprCall* call = stmt->expr->as(); + REQUIRE(call != nullptr); + REQUIRE(call->args.size == 1); + AstExprLocal* arg = call->args.data[0]->as(); + REQUIRE(arg != nullptr); + CHECK(arg->local == whileStat->conditionLocal); +} + +TEST_CASE_FIXTURE(Fixture, "parse_while_local_binding_not_visible_in_condition") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + // `x` in the condition is the outer global, not the loop binding, since the binding is pushed + // only after the condition is parsed + AstStatBlock* block = parse(R"( + while local x = x do + end + )"); + + REQUIRE(block != nullptr); + AstStatWhile* whileStat = block->body.data[0]->as(); + REQUIRE(whileStat != nullptr); + REQUIRE(whileStat->conditionLocal != nullptr); + CHECK(whileStat->condition->as() != nullptr); +} + +TEST_CASE_FIXTURE(Fixture, "parse_while_local_nested") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + AstStatBlock* block = parse(R"( + while local x = a() do + while local y = b() do + print(x, y) + end + end + )"); + + REQUIRE(block != nullptr); + AstStatWhile* outer = block->body.data[0]->as(); + REQUIRE(outer != nullptr); + REQUIRE(outer->conditionLocal != nullptr); + CHECK(outer->conditionLocal->name == "x"); + + AstStatWhile* inner = outer->body->body.data[0]->as(); + REQUIRE(inner != nullptr); + REQUIRE(inner->conditionLocal != nullptr); + CHECK(inner->conditionLocal->name == "y"); + CHECK(inner->conditionLocal != outer->conditionLocal); +} + +TEST_CASE_FIXTURE(Fixture, "parse_while_local_cst_annotation_colon_position") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + ParseOptions parseOptions; + parseOptions.storeCstData = true; + + ParseResult result = parseEx("while local x: number = y do end", parseOptions); + REQUIRE(result.root); + REQUIRE_EQ(1, result.root->body.size); + + auto whileStat = result.root->body.data[0]->as(); + REQUIRE(whileStat); + auto baseCstNode = result.cstNodeMap.find(whileStat); + REQUIRE(baseCstNode); + auto cstNode = (*baseCstNode)->as(); + REQUIRE(cstNode); + CHECK_EQ(cstNode->annotationColonPosition, Position{0, 13}); +} + +TEST_CASE_FIXTURE(Fixture, "parse_while_const_cst_annotation_colon_position") +{ + ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + + ParseOptions parseOptions; + parseOptions.storeCstData = true; + + // `const` and `local` are both 5 chars, so the annotation colon lands at the same column as while-local. + ParseResult result = parseEx("while const x: number = y do end", parseOptions); + REQUIRE(result.root); + REQUIRE_EQ(1, result.root->body.size); + + auto whileStat = result.root->body.data[0]->as(); + REQUIRE(whileStat); + auto baseCstNode = result.cstNodeMap.find(whileStat); + REQUIRE(baseCstNode); + auto cstNode = (*baseCstNode)->as(); + REQUIRE(cstNode); + CHECK_EQ(cstNode->annotationColonPosition, Position{0, 13}); +} + TEST_SUITE_END(); diff --git a/tests/PrettyPrinter.test.cpp b/tests/PrettyPrinter.test.cpp index 8550d1c17..acde29715 100644 --- a/tests/PrettyPrinter.test.cpp +++ b/tests/PrettyPrinter.test.cpp @@ -12,6 +12,7 @@ LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(DebugLuauNoInline) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) using namespace Luau; @@ -102,6 +103,58 @@ TEST_CASE("if_local") CHECK_EQ(chain, prettyPrint(chain).code); } +TEST_CASE("while_local") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + const std::string local = R"(while local item = next() do process(item) end)"; + CHECK_EQ(local, prettyPrint(local).code); +} + +TEST_CASE("while_local_preserves_interior_spacing") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + const std::string spaced = R"(while local item = next() do process(item) end)"; + CHECK_EQ(spaced, prettyPrint(spaced).code); +} + +TEST_CASE("while_local_type_annotation") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + const std::string typed = R"(while local res : string = foo() do print(res) end)"; + CHECK_EQ(typed, prettyPrint(typed, {}, /* withTypes */ true).code); + + const std::string stripped = prettyPrint(typed).code; + CHECK(stripped.find("string") == std::string::npos); + CHECK(stripped.find("foo()") != std::string::npos); +} + +TEST_CASE("while_local_without_annotation_with_types") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + const std::string local = R"(while local item = next() do process(item) end)"; + CHECK_EQ(local, prettyPrint(local, {}, /* withTypes */ true).code); +} + +TEST_CASE("while_const") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + const std::string konst = R"(while const item = next() do process(item) end)"; + CHECK_EQ(konst, prettyPrint(konst).code); +} + +TEST_CASE("while_const_type_annotation") +{ + ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + + const std::string typed = R"(while const res : string = foo() do print(res) end)"; + CHECK_EQ(typed, prettyPrint(typed, {}, /* withTypes */ true).code); +} + TEST_CASE("if_local_preserves_interior_spacing") { ScopedFastFlag sff{FFlag::LuauExperimentalIfLocalSyntax, true}; diff --git a/tests/Subtyping.test.cpp b/tests/Subtyping.test.cpp index 9fbb499d5..9293c6066 100644 --- a/tests/Subtyping.test.cpp +++ b/tests/Subtyping.test.cpp @@ -24,6 +24,7 @@ LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) LUAU_FASTFLAG(DebugLuauParseExactTables) LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAG(LuauSubtypingSkipUnreadReasoning) +LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) using namespace Luau; @@ -2255,6 +2256,8 @@ TEST_CASE_FIXTURE(SubtypeFixture, "substitute_a_generic_for_a_negation") TEST_CASE_FIXTURE(SubtypeFixture, "free_types_might_be_subtypes") { + ScopedFastFlag _{FFlag::LuauOneBitAssumedConstraintTracking, true}; + TypeId argTy = arena.freshType(getBuiltins(), moduleScope.get()); FreeType* freeArg = getMutable(argTy); REQUIRE(freeArg); @@ -2263,7 +2266,7 @@ TEST_CASE_FIXTURE(SubtypeFixture, "free_types_might_be_subtypes") SubtypingResult result = isSubtype(getBuiltins()->stringType, argTy); CHECK(result.isSubtype); - REQUIRE(1 == result.assumedConstraints.size()); + CHECK(result.assumingConstraints); } TEST_CASE_FIXTURE(Fixture, "variadic_any_pack_should_suppress_errors_during_overload_resolution") diff --git a/tests/TypeFunction.test.cpp b/tests/TypeFunction.test.cpp index 4d5c1b1c0..944e91d34 100644 --- a/tests/TypeFunction.test.cpp +++ b/tests/TypeFunction.test.cpp @@ -15,7 +15,6 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_DYNAMIC_FASTINT(LuauTypeFamilyApplicationCartesianProductLimit) LUAU_FASTFLAG(DebugLuauAssertOnForcedConstraint) -LUAU_FASTFLAG(LuauNormalizeGuardAgainstNonTestableNegations) LUAU_FASTFLAG(LuauReduceTypeFunctionToSyntheticError) struct TypeFunctionFixture : Fixture @@ -2129,8 +2128,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oss_negation_of_nontestable_type_doesnt_cras { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauNormalizeGuardAgainstNonTestableNegations, true}; - CheckResult result = check(R"( type function tf() local dn = types.negationof(types.unionof(types.newfunction(), types.number)) @@ -2148,8 +2145,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2634_negation_of_nontestable_type_doesnt { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauNormalizeGuardAgainstNonTestableNegations, true}; - CheckResult result = check(R"( type function mknot() return types.negationof(types.unionof(types.newfunction(), types.number)) @@ -2168,8 +2163,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2634_negation_of_nontestable_type_doesnt { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauNormalizeGuardAgainstNonTestableNegations, true}; - CheckResult result = check(R"( type function tf() local dn = types.negationof(types.unionof(types.newfunction(), types.number)) diff --git a/tests/TypeFunction.user.test.cpp b/tests/TypeFunction.user.test.cpp index f48c67177..ec80d21fd 100644 --- a/tests/TypeFunction.user.test.cpp +++ b/tests/TypeFunction.user.test.cpp @@ -13,7 +13,6 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(LuauIntegerType2) LUAU_DYNAMIC_FASTINT(LuauTypeFunctionSerdeIterationLimit) -LUAU_FASTFLAG(LuauUdtfFixTypeNameTypo) LUAU_FASTFLAG(LuauTypeFunctionsReturnAfterAllSerialized) LUAU_FASTFLAG(LuauUdtfTerseChunkNames) @@ -3810,7 +3809,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cross_type_function_type_check") TEST_CASE_FIXTURE(BuiltinsFixture, "non_string_error_value") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag fixTypeNameTypo{FFlag::LuauUdtfFixTypeNameTypo, true}; CheckResult result = check(R"( type function foo() diff --git a/tests/TypeInfer.aliases.test.cpp b/tests/TypeInfer.aliases.test.cpp index 6651696e5..a4e5daa3c 100644 --- a/tests/TypeInfer.aliases.test.cpp +++ b/tests/TypeInfer.aliases.test.cpp @@ -11,7 +11,6 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(LuauDisallowRedefiningBuiltinTypes) -LUAU_FASTFLAG(LuauBlockingTypeAliasExpansion) TEST_SUITE_BEGIN("TypeAliases"); @@ -1463,8 +1462,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "blocked_type_alias_do_not_leak_generic_argum { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag luauBlockingTypeAliasExpansion{FFlag::LuauBlockingTypeAliasExpansion, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( type Alias = typeof(getmetatable(... :: Generic)) diff --git a/tests/TypeInfer.classes.test.cpp b/tests/TypeInfer.classes.test.cpp index 1944d241e..0a5fb7b5e 100644 --- a/tests/TypeInfer.classes.test.cpp +++ b/tests/TypeInfer.classes.test.cpp @@ -1418,4 +1418,17 @@ TEST_CASE_FIXTURE(ClassesFixture, "writes_to_unknown_class_instance_properties_a CHECK(pav3->context == PropertyAccessViolation::CannotWrite); } +TEST_CASE_FIXTURE(ClassesFixture, "fuzzer_oct_20") +{ + LUAU_REQUIRE_NO_ERRORS(check(R"( + class C + function m() + type function t(x) + return x._hello + end + end + end + )")); +} + TEST_SUITE_END(); diff --git a/tests/TypeInfer.functions.test.cpp b/tests/TypeInfer.functions.test.cpp index ff50d10a1..3d4ec90d9 100644 --- a/tests/TypeInfer.functions.test.cpp +++ b/tests/TypeInfer.functions.test.cpp @@ -26,7 +26,6 @@ LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) LUAU_FASTFLAG(LuauDoNotLeakGenericsInIndexer) -LUAU_FASTFLAG(LuauThreadGeneralizeThroughConstraintGeneration) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauFixCallMetamethodErrorReporting) LUAU_FASTFLAG(LuauTraverseScopeToFunction) @@ -4615,8 +4614,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "let_generalization_direct") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauThreadGeneralizeThroughConstraintGeneration, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local Func = function(x, y) return x * y @@ -4633,8 +4630,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "let_generalization_direct_one_level") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauThreadGeneralizeThroughConstraintGeneration, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local tbl = { Func = function(x, y) @@ -4651,8 +4646,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "let_generalization_direct_one_level") TEST_CASE_FIXTURE(Fixture, "let_generalization_return_not_generalized") { - ScopedFastFlag _{FFlag::LuauThreadGeneralizeThroughConstraintGeneration, true}; - CheckResult result = check(R"( local f = function() return function(x) return x end @@ -4671,8 +4664,6 @@ TEST_CASE_FIXTURE(Fixture, "let_generalization_forin_iterator") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauThreadGeneralizeThroughConstraintGeneration, true}; - CheckResult result = check(R"( local makeIter = function(arr) local i = 0 @@ -4694,8 +4685,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "let_generalization_assign_statement") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauThreadGeneralizeThroughConstraintGeneration, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local Func Func = function(x, y) @@ -4711,8 +4700,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "let_generalization_assign_statement") TEST_CASE_FIXTURE(Fixture, "let_generalization_multiple_values") { - ScopedFastFlag _{FFlag::LuauThreadGeneralizeThroughConstraintGeneration, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local a, b = function(x) return x end, function(y) return y end local r1 = a(42) diff --git a/tests/TypeInfer.refinements.test.cpp b/tests/TypeInfer.refinements.test.cpp index a7cef940c..4fb2dfb48 100644 --- a/tests/TypeInfer.refinements.test.cpp +++ b/tests/TypeInfer.refinements.test.cpp @@ -18,6 +18,8 @@ LUAU_FASTFLAG(DebugLuauCFG) LUAU_FASTFLAG(LuauIterativeTypeSearcher) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauRefineNotNilWaitsForBlockedTarget) +LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) using namespace Luau; @@ -924,7 +926,16 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "type_narrow_to_vector") LUAU_REQUIRE_NO_ERRORS(result); if (!FFlag::DebugLuauForceOldSolver) - CHECK_EQ("unknown & vector", toString(requireTypeAtPosition({3, 28}))); + { + if (FFlag::DebugLuauCFG) + { + CHECK_EQ("vector", toString(requireTypeAtPosition({3, 28}))); + } + else + { + CHECK_EQ("unknown & vector", toString(requireTypeAtPosition({3, 28}))); + } + } else CHECK_EQ("*error-type*", toString(requireTypeAtPosition({3, 28}))); } @@ -4006,4 +4017,45 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_not_nil_waits_for_blocked_target") CHECK_EQ("string", toString(requireTypeAtPosition({13, 22}))); } +TEST_CASE_FIXTURE(BuiltinsFixture, "while_local_narrows_to_truthy_both_solvers") +{ + ScopedFastFlag sffs[] = { + {FFlag::DebugLuauWhileLocalSyntax, true}, + {FFlag::DebugLuauWhileLocalAnalysis, true}, + }; + + CheckResult result = check(R"( + local function f(v: number?) + while local x = v do + local s = x + end + end + )"); + + LUAU_REQUIRE_NO_ERRORS(result); + + // The binding narrows from `number?` to `number` inside the loop body under both solvers. + CHECK_EQ("number", toString(requireTypeAtPosition({3, 26}))); +} + +TEST_CASE_FIXTURE(BuiltinsFixture, "while_const_narrows_to_truthy") +{ + ScopedFastFlag sffs[] = { + {FFlag::DebugLuauWhileLocalSyntax, true}, + {FFlag::DebugLuauWhileLocalAnalysis, true}, + }; + + CheckResult result = check(R"( + local function f(v: number?) + while const x = v do + local s = x + end + end + )"); + + LUAU_REQUIRE_NO_ERRORS(result); + + CHECK_EQ("number", toString(requireTypeAtPosition({3, 26}))); +} + TEST_SUITE_END(); diff --git a/tests/TypeInfer.tables.test.cpp b/tests/TypeInfer.tables.test.cpp index 523c5264e..a4461ea1b 100644 --- a/tests/TypeInfer.tables.test.cpp +++ b/tests/TypeInfer.tables.test.cpp @@ -28,11 +28,11 @@ LUAU_FASTFLAG(LuauRemoveConstraintSolverEmplace) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) LUAU_FASTFLAG(DebugLuauParseExactTables) LUAU_FASTFLAG(DebugLuauExactTableTypes) -LUAU_FASTFLAG(LuauRelateIndexersTypo) LUAU_FASTFLAG(LuauTraverseScopeToFunction) LUAU_FASTFLAG(LuauInferReadOnlyIndexers) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) +LUAU_FASTFLAG(LuauNonreentrantLookupTableProp) namespace { @@ -4845,7 +4845,11 @@ TEST_CASE_FIXTURE(Fixture, "intersection_of_read_only_indexers_is_read_only") TEST_CASE_FIXTURE(Fixture, "intersection_of_read_only_and_read_write_indexer_allows_writes") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauForceOldSolver, false}}; + DOES_NOT_PASS_OLD_SOLVER_GUARD(); + + ScopedFastFlag _{ + FFlag::LuauNonreentrantLookupTableProp, true + }; // We now (correctly) note that you can always write nil to an indexer through an intersection. // {read [K]: V} & {[K]: W} normalizes to {[K]: V & W} — read-write with intersection value. // Write access comes from the read-write side; write type is the conservative intersection. @@ -4864,7 +4868,7 @@ TEST_CASE_FIXTURE(Fixture, "intersection_of_read_only_and_read_write_indexer_all auto tm = get(result.errors[0]); REQUIRE(tm); - CHECK("number" == toString(tm->wantedType)); + CHECK("number?" == toString(tm->wantedType)); CHECK("string" == toString(tm->givenType)); } @@ -6872,8 +6876,6 @@ TEST_CASE_FIXTURE(Fixture, "basic_data_like_array_1") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauRelateIndexersTypo, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local t = { {1, 2, 3}, @@ -6887,8 +6889,6 @@ TEST_CASE_FIXTURE(Fixture, "basic_data_like_array_2") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauRelateIndexersTypo, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local t = { {1, 2, 3}, @@ -6902,8 +6902,6 @@ TEST_CASE_FIXTURE(Fixture, "basic_data_like_array_3") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauRelateIndexersTypo, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local v: number? local t1 = { @@ -6925,8 +6923,6 @@ TEST_CASE_FIXTURE(Fixture, "basic_data_like_array_4") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauRelateIndexersTypo, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local v: number? local s: string? @@ -6943,8 +6939,6 @@ TEST_CASE_FIXTURE(Fixture, "basic_data_like_array_5") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauRelateIndexersTypo, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local v: number? local t = { diff --git a/tests/conformance/native.luau b/tests/conformance/native.luau index f4b2c08d2..66ee88636 100644 --- a/tests/conformance/native.luau +++ b/tests/conformance/native.luau @@ -311,6 +311,37 @@ end assert(pcall(fuzzfail30) == false) +local function cmpanyeffects() + local function f3() C6[nil] = 1 end + local v10 = setmetatable({}, { __eq = f3 }) + for _ = 0, 4 do local b = buffer.create(60) end + local v14 = v10 == v10 +end + +assert(pcall(cmpanyeffects) == false) + +local function fuzzfail31() + for _, v in {} do end + bit32.bnot(1e308) + bit32.arshift(1e308, 1e308) +end + +assert(pcall(fuzzfail31) == true) + +local function fuzzfail32() + if type(table) == "table" then + for _, v1 in table do end + end + local v4 = 10 + v4 = v4 .. 2 + local v7 = buffer.create(13) + local v10 = buffer.create(50) + buffer.writef32(v10, 0, -1.4967669563608148e+308) + buffer.writeu16(v7, 0, v4) +end + +assert(pcall(fuzzfail32) == true) + local function arraySizeInv1() local t = {1, 2, nil, nil, nil, nil, nil, nil, nil, true} diff --git a/tests/conformance/whilelocal.luau b/tests/conformance/whilelocal.luau new file mode 100644 index 000000000..f6b9ffe13 --- /dev/null +++ b/tests/conformance/whilelocal.luau @@ -0,0 +1,240 @@ +-- tests for while-local syntax + +-- basic loop: binding re-evaluated each iteration, exits when falsy +do + local counter = 3 + local seen = {} + local function next() + counter = counter - 1 + if counter < 0 then + return nil + end + return counter + end + + while local x = next() do + table.insert(seen, x) + end + + assert(#seen == 3) + assert(seen[1] == 2) + assert(seen[2] == 1) + assert(seen[3] == 0) +end + +-- loop that never runs: condition falsy on first evaluation (nil) +do + local entered = false + while local x = nil do + entered = true + end + assert(not entered) +end + +-- loop that never runs: condition falsy on first evaluation (false) +do + local entered = false + while local x = false do + entered = true + end + assert(not entered) +end + +-- binding is truthy inside the body even when 0 (0 is truthy in Luau) +do + local iterations = 0 + local limit = 2 + while local n = (iterations < limit) and iterations or false do + assert(type(n) == "number") + iterations = iterations + 1 + end + assert(iterations == 2) +end + +-- scoping: binding not visible after the loop ends +do + local x = "outer" + local ran = false + while local x = (not ran) and "inner" or false do + assert(x == "inner") + ran = true + end + assert(x == "outer") +end + +-- scoping: binding not visible in its own condition (reads the outer x each iteration) +do + local x = 2 + local count = 0 + while local y = x > 0 do + assert(y == true) + x = x - 1 + count = count + 1 + if count > 10 then + error("loop did not terminate") + end + end + assert(count == 2) +end + +-- break exits the loop +do + local count = 0 + while local x = true do + count = count + 1 + if count == 3 then + break + end + end + assert(count == 3) +end + +-- continue skips to the next iteration (and re-evaluates the condition) +do + local counter = 5 + local sum = 0 + local function next() + counter = counter - 1 + if counter < 0 then + return nil + end + return counter + end + + while local x = next() do + if x % 2 == 0 then + continue + end + sum = sum + x + end + -- odd values produced by next(): 3, 1 => sum 4 + assert(sum == 4) +end + +-- each iteration captures a fresh binding in a closure +do + local closures = {} + local counter = 3 + local function next() + counter = counter - 1 + if counter < 0 then + return nil + end + return counter + end + + while local x = next() do + table.insert(closures, function() + return x + end) + end + + assert(#closures == 3) + assert(closures[1]() == 2) + assert(closures[2]() == 1) + assert(closures[3]() == 0) +end + +-- nested while-local loops with independent bindings +do + local total = 0 + local i = 2 + local function nextI() + i = i - 1 + if i < 0 then + return nil + end + return i + end + + while local a = nextI() do + local j = 2 + local function nextJ() + j = j - 1 + if j < 0 then + return nil + end + return j + end + while local b = nextJ() do + total = total + a + b + end + end + -- a in {1,0}, b in {1,0} for each a => (1+1)+(1+0)+(0+1)+(0+0) = 4 + assert(total == 4) +end + +-- mutating the binding inside the body does not affect the next iteration's condition +do + local counter = 3 + local observed = {} + local function next() + counter = counter - 1 + if counter < 0 then + return nil + end + return counter + end + + while local x = next() do + table.insert(observed, x) + x = 999 + end + assert(#observed == 3) + assert(observed[1] == 2) +end + +-- while const basic +do + local counter = 3 + local seen = {} + local function next() + counter = counter - 1 + if counter < 0 then + return nil + end + return counter + end + + while const x = next() do + table.insert(seen, x) + end + + assert(#seen == 3) + assert(seen[1] == 2) + assert(seen[2] == 1) + assert(seen[3] == 0) +end + +-- while const: loop that never runs when condition is falsy on first evaluation +do + local entered = false + while const x = nil do + entered = true + end + assert(not entered) +end + +-- while const: binding scoped to the loop body only +do + local x = "outer" + local ran = false + while const x = (not ran) and "inner" or false do + assert(x == "inner") + ran = true + end + assert(x == "outer") +end + +-- backwards compatibility for context-sensitive const: `const` is still a usable identifier +do + local const = 2 + local count = 0 + while const > 0 do + const = const - 1 + count = count + 1 + end + assert(count == 2) +end + +return "OK" diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-off.nonstrict.output index 2b820ef23..f0586f143 100644 --- a/tests/golden/analysis/cfgconstruction/basic_join.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/basic_join.flags-off.nonstrict.output @@ -1,9 +1,9 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local t-0 = 8 -Block 1 (linear "then branch") -> [B3]: - t-1 = 9 -Block 2 (linear "else branch") -> [B3]: - t-2 = "hello" + local t-0 = +Block 1 (linear "then block") -> [B3]: + t-1 = +Block 2 (linear "else block") -> [B3]: + t-2 = Block 3 (linear "merge"): t-3 = join(t-1, t-2) - local y-0 = t-3 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-off.strict.output index 2b820ef23..f0586f143 100644 --- a/tests/golden/analysis/cfgconstruction/basic_join.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/basic_join.flags-off.strict.output @@ -1,9 +1,9 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local t-0 = 8 -Block 1 (linear "then branch") -> [B3]: - t-1 = 9 -Block 2 (linear "else branch") -> [B3]: - t-2 = "hello" + local t-0 = +Block 1 (linear "then block") -> [B3]: + t-1 = +Block 2 (linear "else block") -> [B3]: + t-2 = Block 3 (linear "merge"): t-3 = join(t-1, t-2) - local y-0 = t-3 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-on.nonstrict.output index 2b820ef23..f0586f143 100644 --- a/tests/golden/analysis/cfgconstruction/basic_join.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/basic_join.flags-on.nonstrict.output @@ -1,9 +1,9 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local t-0 = 8 -Block 1 (linear "then branch") -> [B3]: - t-1 = 9 -Block 2 (linear "else branch") -> [B3]: - t-2 = "hello" + local t-0 = +Block 1 (linear "then block") -> [B3]: + t-1 = +Block 2 (linear "else block") -> [B3]: + t-2 = Block 3 (linear "merge"): t-3 = join(t-1, t-2) - local y-0 = t-3 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/basic_join.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/basic_join.flags-on.strict.output index 2b820ef23..f0586f143 100644 --- a/tests/golden/analysis/cfgconstruction/basic_join.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/basic_join.flags-on.strict.output @@ -1,9 +1,9 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local t-0 = 8 -Block 1 (linear "then branch") -> [B3]: - t-1 = 9 -Block 2 (linear "else branch") -> [B3]: - t-2 = "hello" + local t-0 = +Block 1 (linear "then block") -> [B3]: + t-1 = +Block 2 (linear "else block") -> [B3]: + t-2 = Block 3 (linear "merge"): t-3 = join(t-1, t-2) - local y-0 = t-3 + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.nonstrict.output index fc61bc0a1..b17e7b2f2 100644 --- a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.nonstrict.output @@ -1,4 +1,4 @@ Block 0 (entry "Entry Block"): local f-0 = - local x-0 = 1 + local x-0 = local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.runtime.output index e69de29bb..10c706a28 100644 --- a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.runtime.output +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.runtime.output @@ -0,0 +1,3 @@ +./analysis/cfgconstruction/call_expression_records_uses.luau:5: attempt to call a nil value +stacktrace: +./analysis/cfgconstruction/call_expression_records_uses.luau:5 diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.strict.output index fc61bc0a1..b17e7b2f2 100644 --- a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-off.strict.output @@ -1,4 +1,4 @@ Block 0 (entry "Entry Block"): local f-0 = - local x-0 = 1 + local x-0 = local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.nonstrict.output index fc61bc0a1..b17e7b2f2 100644 --- a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.nonstrict.output @@ -1,4 +1,4 @@ Block 0 (entry "Entry Block"): local f-0 = - local x-0 = 1 + local x-0 = local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.runtime.output index e69de29bb..10c706a28 100644 --- a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.runtime.output +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.runtime.output @@ -0,0 +1,3 @@ +./analysis/cfgconstruction/call_expression_records_uses.luau:5: attempt to call a nil value +stacktrace: +./analysis/cfgconstruction/call_expression_records_uses.luau:5 diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.strict.output index fc61bc0a1..b17e7b2f2 100644 --- a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.flags-on.strict.output @@ -1,4 +1,4 @@ Block 0 (entry "Entry Block"): local f-0 = - local x-0 = 1 + local x-0 = local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.luau b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.luau index 66f5a2678..e9c05c91c 100644 --- a/tests/golden/analysis/cfgconstruction/call_expression_records_uses.luau +++ b/tests/golden/analysis/cfgconstruction/call_expression_records_uses.luau @@ -1,5 +1,5 @@ ---!golden ok +--!golden status: fail --!golden fflags=DebugLuauAnalyzeDumpsCFG=true -local f = tostring +local f = nil local x = 1 local y = f(x) diff --git a/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.nonstrict.output new file mode 100644 index 000000000..5885ed186 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(2,11): UninitializedLocal: Variable 'x' defined at line 1 is never initialized or assigned; initialize with 'nil' to silence +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(3,15): LocalUnused: Variable 'y' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.strict.output new file mode 100644 index 000000000..cdeb8ebec --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-off.strict.output @@ -0,0 +1,3 @@ +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(3,28): TypeError: Expected this to be 'number', but got 'string' +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(2,11): UninitializedLocal: Variable 'x' defined at line 1 is never initialized or assigned; initialize with 'nil' to silence +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(3,15): LocalUnused: Variable 'y' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.nonstrict.output new file mode 100644 index 000000000..5885ed186 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(2,11): UninitializedLocal: Variable 'x' defined at line 1 is never initialized or assigned; initialize with 'nil' to silence +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(3,15): LocalUnused: Variable 'y' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.strict.output new file mode 100644 index 000000000..cdeb8ebec --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.flags-on.strict.output @@ -0,0 +1,3 @@ +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(3,28): TypeError: Expected this to be 'number', but got 'string' +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(2,11): UninitializedLocal: Variable 'x' defined at line 1 is never initialized or assigned; initialize with 'nil' to silence +./analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau(3,15): LocalUnused: Variable 'y' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau new file mode 100644 index 000000000..c052ccbc6 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/cfg_refinements_and_test_table_subprop_mismatch.luau @@ -0,0 +1,4 @@ +local x: unknown +if typeof(x) == "table" and typeof(x.foo) == "string" then + local y : number = x.foo +end \ No newline at end of file diff --git a/tests/golden/analysis/cfgconstruction/for_break.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/for_break.flags-off.nonstrict.output new file mode 100644 index 000000000..828ea795e --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_break.flags-off.nonstrict.output @@ -0,0 +1,12 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "for-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-loop exit"): + local w-0 = +Block 3 (linear "for-loop body") -> [B4, B5]: + local i-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_break.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/for_break.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/for_break.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/for_break.flags-off.strict.output new file mode 100644 index 000000000..828ea795e --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_break.flags-off.strict.output @@ -0,0 +1,12 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "for-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-loop exit"): + local w-0 = +Block 3 (linear "for-loop body") -> [B4, B5]: + local i-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_break.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/for_break.flags-on.nonstrict.output new file mode 100644 index 000000000..828ea795e --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_break.flags-on.nonstrict.output @@ -0,0 +1,12 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "for-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-loop exit"): + local w-0 = +Block 3 (linear "for-loop body") -> [B4, B5]: + local i-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_break.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/for_break.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/for_break.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/for_break.flags-on.strict.output new file mode 100644 index 000000000..828ea795e --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_break.flags-on.strict.output @@ -0,0 +1,12 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "for-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-loop exit"): + local w-0 = +Block 3 (linear "for-loop body") -> [B4, B5]: + local i-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_break.luau b/tests/golden/analysis/cfgconstruction/for_break.luau new file mode 100644 index 000000000..a241e2fab --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_break.luau @@ -0,0 +1,9 @@ +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 0 +for i = 1, 10 do + if x > 0 then + break + end + x = x + 1 +end +local w = x diff --git a/tests/golden/analysis/cfgconstruction/for_in_break.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/for_in_break.flags-off.nonstrict.output new file mode 100644 index 000000000..e93281e79 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_in_break.flags-off.nonstrict.output @@ -0,0 +1,14 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = + local t-0 = +Block 1 (condition "for-in-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-in-loop exit"): + local w-0 = +Block 3 (linear "for-in-loop body") -> [B4, B5]: + local k-0 = + local v-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_in_break.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/for_in_break.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/for_in_break.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/for_in_break.flags-off.strict.output new file mode 100644 index 000000000..e93281e79 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_in_break.flags-off.strict.output @@ -0,0 +1,14 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = + local t-0 = +Block 1 (condition "for-in-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-in-loop exit"): + local w-0 = +Block 3 (linear "for-in-loop body") -> [B4, B5]: + local k-0 = + local v-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_in_break.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/for_in_break.flags-on.nonstrict.output new file mode 100644 index 000000000..e93281e79 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_in_break.flags-on.nonstrict.output @@ -0,0 +1,14 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = + local t-0 = +Block 1 (condition "for-in-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-in-loop exit"): + local w-0 = +Block 3 (linear "for-in-loop body") -> [B4, B5]: + local k-0 = + local v-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_in_break.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/for_in_break.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/for_in_break.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/for_in_break.flags-on.strict.output new file mode 100644 index 000000000..e93281e79 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_in_break.flags-on.strict.output @@ -0,0 +1,14 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = + local t-0 = +Block 1 (condition "for-in-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-in-loop exit"): + local w-0 = +Block 3 (linear "for-in-loop body") -> [B4, B5]: + local k-0 = + local v-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_in_break.luau b/tests/golden/analysis/cfgconstruction/for_in_break.luau new file mode 100644 index 000000000..3992fa194 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_in_break.luau @@ -0,0 +1,11 @@ +--!golden status: ok +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 0 +local t = {} +for k, v in t do + if x > 0 then + break + end + x = x + 1 +end +local w = x diff --git a/tests/golden/analysis/cfgconstruction/for_loop.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/for_loop.flags-off.nonstrict.output new file mode 100644 index 000000000..3ee11ee9b --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_loop.flags-off.nonstrict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "for-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-loop exit"): + local y-0 = +Block 3 (linear "for-loop body") -> [B1]: + local i-0 = + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_loop.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/for_loop.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/for_loop.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/for_loop.flags-off.strict.output new file mode 100644 index 000000000..3ee11ee9b --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_loop.flags-off.strict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "for-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-loop exit"): + local y-0 = +Block 3 (linear "for-loop body") -> [B1]: + local i-0 = + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_loop.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/for_loop.flags-on.nonstrict.output new file mode 100644 index 000000000..3ee11ee9b --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_loop.flags-on.nonstrict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "for-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-loop exit"): + local y-0 = +Block 3 (linear "for-loop body") -> [B1]: + local i-0 = + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_loop.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/for_loop.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/for_loop.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/for_loop.flags-on.strict.output new file mode 100644 index 000000000..3ee11ee9b --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_loop.flags-on.strict.output @@ -0,0 +1,9 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "for-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "for-loop exit"): + local y-0 = +Block 3 (linear "for-loop body") -> [B1]: + local i-0 = + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/for_loop.luau b/tests/golden/analysis/cfgconstruction/for_loop.luau new file mode 100644 index 000000000..12666d8c9 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/for_loop.luau @@ -0,0 +1,6 @@ +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 0 +for i = 1, 10 do + x = x + i +end +local y = x diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.nonstrict.output index 27906e321..5a5710589 100644 --- a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.nonstrict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 1 + local x-0 = local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.strict.output index 27906e321..5a5710589 100644 --- a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-off.strict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 1 + local x-0 = local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.nonstrict.output index 27906e321..5a5710589 100644 --- a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.nonstrict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 1 + local x-0 = local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.strict.output index 27906e321..5a5710589 100644 --- a/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/grouped_expression_records_use.flags-on.strict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 1 + local x-0 = local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.nonstrict.output new file mode 100644 index 000000000..0eb9fb25a --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.nonstrict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = +Block 1 (linear "if-else expr then") -> [B3]: + x-1 = refine(x-0 is truthy) +Block 2 (linear "if-else expr else") -> [B3]: + x-2 = refine(x-0 is falsy) +Block 3 (linear "if-else expr merge"): + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.strict.output new file mode 100644 index 000000000..0eb9fb25a --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-off.strict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = +Block 1 (linear "if-else expr then") -> [B3]: + x-1 = refine(x-0 is truthy) +Block 2 (linear "if-else expr else") -> [B3]: + x-2 = refine(x-0 is falsy) +Block 3 (linear "if-else expr merge"): + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.nonstrict.output new file mode 100644 index 000000000..0eb9fb25a --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.nonstrict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = +Block 1 (linear "if-else expr then") -> [B3]: + x-1 = refine(x-0 is truthy) +Block 2 (linear "if-else expr else") -> [B3]: + x-2 = refine(x-0 is falsy) +Block 3 (linear "if-else expr merge"): + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.strict.output new file mode 100644 index 000000000..0eb9fb25a --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/if_else_expression.flags-on.strict.output @@ -0,0 +1,8 @@ +Block 0 (entry "Entry Block") -> [B1, B2]: + local x-0 = +Block 1 (linear "if-else expr then") -> [B3]: + x-1 = refine(x-0 is truthy) +Block 2 (linear "if-else expr else") -> [B3]: + x-2 = refine(x-0 is falsy) +Block 3 (linear "if-else expr merge"): + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/if_else_expression.luau b/tests/golden/analysis/cfgconstruction/if_else_expression.luau new file mode 100644 index 000000000..aa8eeee8b --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/if_else_expression.luau @@ -0,0 +1,3 @@ +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = nil +local y = if x then x else x diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.nonstrict.output index 41428fb9d..7cb6e6931 100644 --- a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.nonstrict.output @@ -1,5 +1,5 @@ Block 0 (entry "Entry Block"): - local a-0 = 1 - local b-0 = 2 - a-1 = b-0 - b-1 = a-0 + local a-0 = + local b-0 = + a-1 = + b-1 = diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.strict.output index 41428fb9d..7cb6e6931 100644 --- a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-off.strict.output @@ -1,5 +1,5 @@ Block 0 (entry "Entry Block"): - local a-0 = 1 - local b-0 = 2 - a-1 = b-0 - b-1 = a-0 + local a-0 = + local b-0 = + a-1 = + b-1 = diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.nonstrict.output index 41428fb9d..7cb6e6931 100644 --- a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.nonstrict.output @@ -1,5 +1,5 @@ Block 0 (entry "Entry Block"): - local a-0 = 1 - local b-0 = 2 - a-1 = b-0 - b-1 = a-0 + local a-0 = + local b-0 = + a-1 = + b-1 = diff --git a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.strict.output index 41428fb9d..7cb6e6931 100644 --- a/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/multi_assignment.flags-on.strict.output @@ -1,5 +1,5 @@ Block 0 (entry "Entry Block"): - local a-0 = 1 - local b-0 = 2 - a-1 = b-0 - b-1 = a-0 + local a-0 = + local b-0 = + a-1 = + b-1 = diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.nonstrict.output index 7a461a058..e806537fd 100644 --- a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.nonstrict.output @@ -1,8 +1,8 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local x-0 = 1 -Block 1 (linear "then branch") -> [B3]: - x-1 = 2 -Block 2 (linear "else branch") -> [B3]: + local x-0 = +Block 1 (linear "then block") -> [B3]: + x-1 = +Block 2 (linear "else block") -> [B3]: Block 3 (linear "merge"): x-2 = join(x-1, x-0) - local w-0 = x-2 + local w-0 = diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.strict.output index 7a461a058..e806537fd 100644 --- a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-off.strict.output @@ -1,8 +1,8 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local x-0 = 1 -Block 1 (linear "then branch") -> [B3]: - x-1 = 2 -Block 2 (linear "else branch") -> [B3]: + local x-0 = +Block 1 (linear "then block") -> [B3]: + x-1 = +Block 2 (linear "else block") -> [B3]: Block 3 (linear "merge"): x-2 = join(x-1, x-0) - local w-0 = x-2 + local w-0 = diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.nonstrict.output index 7a461a058..e806537fd 100644 --- a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.nonstrict.output @@ -1,8 +1,8 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local x-0 = 1 -Block 1 (linear "then branch") -> [B3]: - x-1 = 2 -Block 2 (linear "else branch") -> [B3]: + local x-0 = +Block 1 (linear "then block") -> [B3]: + x-1 = +Block 2 (linear "else block") -> [B3]: Block 3 (linear "merge"): x-2 = join(x-1, x-0) - local w-0 = x-2 + local w-0 = diff --git a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.strict.output index 7a461a058..e806537fd 100644 --- a/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/nontrivial_phi_one_branch_modifies.flags-on.strict.output @@ -1,8 +1,8 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local x-0 = 1 -Block 1 (linear "then branch") -> [B3]: - x-1 = 2 -Block 2 (linear "else branch") -> [B3]: + local x-0 = +Block 1 (linear "then block") -> [B3]: + x-1 = +Block 2 (linear "else block") -> [B3]: Block 3 (linear "merge"): x-2 = join(x-1, x-0) - local w-0 = x-2 + local w-0 = diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.nonstrict.output index 420750e92..56bfec35b 100644 --- a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.nonstrict.output @@ -1,4 +1,4 @@ Block 0 (entry "Entry Block"): - local x-0 = 1 - local y-0 = 2 - x-1 = y-0 + local x-0 = + local y-0 = + x-1 = diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.strict.output index 420750e92..56bfec35b 100644 --- a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-off.strict.output @@ -1,4 +1,4 @@ Block 0 (entry "Entry Block"): - local x-0 = 1 - local y-0 = 2 - x-1 = y-0 + local x-0 = + local y-0 = + x-1 = diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.nonstrict.output index 420750e92..56bfec35b 100644 --- a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.nonstrict.output @@ -1,4 +1,4 @@ Block 0 (entry "Entry Block"): - local x-0 = 1 - local y-0 = 2 - x-1 = y-0 + local x-0 = + local y-0 = + x-1 = diff --git a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.strict.output index 420750e92..56bfec35b 100644 --- a/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/reassignment_from_local.flags-on.strict.output @@ -1,4 +1,4 @@ Block 0 (entry "Entry Block"): - local x-0 = 1 - local y-0 = 2 - x-1 = y-0 + local x-0 = + local y-0 = + x-1 = diff --git a/tests/golden/analysis/cfgconstruction/repeat_break.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/repeat_break.flags-off.nonstrict.output new file mode 100644 index 000000000..e6fbdd4e5 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_break.flags-off.nonstrict.output @@ -0,0 +1,16 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B4, B5]: + x-1 = join(x-0, x-4) +Block 2 (condition "repeat-loop condition") -> [B7, B8]: +Block 3 (linear "repeat-loop exit"): + x-5 = join(x-1, x-3) + local w-0 = +Block 4 (linear "then block") -> [B3]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B2]: + x-2 = +Block 7 (linear "repeat-loop condition truthy") -> [B3]: + x-3 = refine(x-2 is truthy) +Block 8 (linear "repeat-loop condition falsy") -> [B1]: + x-4 = refine(x-2 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_break.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/repeat_break.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/repeat_break.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/repeat_break.flags-off.strict.output new file mode 100644 index 000000000..e6fbdd4e5 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_break.flags-off.strict.output @@ -0,0 +1,16 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B4, B5]: + x-1 = join(x-0, x-4) +Block 2 (condition "repeat-loop condition") -> [B7, B8]: +Block 3 (linear "repeat-loop exit"): + x-5 = join(x-1, x-3) + local w-0 = +Block 4 (linear "then block") -> [B3]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B2]: + x-2 = +Block 7 (linear "repeat-loop condition truthy") -> [B3]: + x-3 = refine(x-2 is truthy) +Block 8 (linear "repeat-loop condition falsy") -> [B1]: + x-4 = refine(x-2 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_break.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/repeat_break.flags-on.nonstrict.output new file mode 100644 index 000000000..e6fbdd4e5 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_break.flags-on.nonstrict.output @@ -0,0 +1,16 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B4, B5]: + x-1 = join(x-0, x-4) +Block 2 (condition "repeat-loop condition") -> [B7, B8]: +Block 3 (linear "repeat-loop exit"): + x-5 = join(x-1, x-3) + local w-0 = +Block 4 (linear "then block") -> [B3]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B2]: + x-2 = +Block 7 (linear "repeat-loop condition truthy") -> [B3]: + x-3 = refine(x-2 is truthy) +Block 8 (linear "repeat-loop condition falsy") -> [B1]: + x-4 = refine(x-2 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_break.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/repeat_break.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/repeat_break.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/repeat_break.flags-on.strict.output new file mode 100644 index 000000000..e6fbdd4e5 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_break.flags-on.strict.output @@ -0,0 +1,16 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B4, B5]: + x-1 = join(x-0, x-4) +Block 2 (condition "repeat-loop condition") -> [B7, B8]: +Block 3 (linear "repeat-loop exit"): + x-5 = join(x-1, x-3) + local w-0 = +Block 4 (linear "then block") -> [B3]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B2]: + x-2 = +Block 7 (linear "repeat-loop condition truthy") -> [B3]: + x-3 = refine(x-2 is truthy) +Block 8 (linear "repeat-loop condition falsy") -> [B1]: + x-4 = refine(x-2 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_break.luau b/tests/golden/analysis/cfgconstruction/repeat_break.luau new file mode 100644 index 000000000..542fc21e6 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_break.luau @@ -0,0 +1,9 @@ +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 1 +repeat + if x > 0 then + break + end + x = x + 1 +until x +local w = x diff --git a/tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.nonstrict.output new file mode 100644 index 000000000..6eb2f2949 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.nonstrict.output @@ -0,0 +1,16 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B4, B5]: + x-1 = join(x-0, x-5) +Block 2 (condition "repeat-loop condition") -> [B7, B8]: + x-3 = join(x-1, x-2) +Block 3 (linear "repeat-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B2]: + x-2 = +Block 7 (linear "repeat-loop condition truthy") -> [B3]: + x-4 = refine(x-3 is truthy) +Block 8 (linear "repeat-loop condition falsy") -> [B1]: + x-5 = refine(x-3 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.strict.output new file mode 100644 index 000000000..6eb2f2949 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-off.strict.output @@ -0,0 +1,16 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B4, B5]: + x-1 = join(x-0, x-5) +Block 2 (condition "repeat-loop condition") -> [B7, B8]: + x-3 = join(x-1, x-2) +Block 3 (linear "repeat-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B2]: + x-2 = +Block 7 (linear "repeat-loop condition truthy") -> [B3]: + x-4 = refine(x-3 is truthy) +Block 8 (linear "repeat-loop condition falsy") -> [B1]: + x-5 = refine(x-3 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.nonstrict.output new file mode 100644 index 000000000..6eb2f2949 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.nonstrict.output @@ -0,0 +1,16 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B4, B5]: + x-1 = join(x-0, x-5) +Block 2 (condition "repeat-loop condition") -> [B7, B8]: + x-3 = join(x-1, x-2) +Block 3 (linear "repeat-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B2]: + x-2 = +Block 7 (linear "repeat-loop condition truthy") -> [B3]: + x-4 = refine(x-3 is truthy) +Block 8 (linear "repeat-loop condition falsy") -> [B1]: + x-5 = refine(x-3 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.strict.output new file mode 100644 index 000000000..6eb2f2949 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_continue.flags-on.strict.output @@ -0,0 +1,16 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B4, B5]: + x-1 = join(x-0, x-5) +Block 2 (condition "repeat-loop condition") -> [B7, B8]: + x-3 = join(x-1, x-2) +Block 3 (linear "repeat-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B2]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B2]: + x-2 = +Block 7 (linear "repeat-loop condition truthy") -> [B3]: + x-4 = refine(x-3 is truthy) +Block 8 (linear "repeat-loop condition falsy") -> [B1]: + x-5 = refine(x-3 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_continue.luau b/tests/golden/analysis/cfgconstruction/repeat_continue.luau new file mode 100644 index 000000000..daf32f27c --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_continue.luau @@ -0,0 +1,9 @@ +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 1 +repeat + if x > 0 then + continue + end + x = x + 1 +until x +local w = x diff --git a/tests/golden/analysis/cfgconstruction/repeat_until.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/repeat_until.flags-off.nonstrict.output new file mode 100644 index 000000000..f954f3ba8 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_until.flags-off.nonstrict.output @@ -0,0 +1,11 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B2]: + x-1 = +Block 2 (condition "repeat-loop condition") -> [B4, B5]: +Block 3 (linear "repeat-loop exit"): + local y-0 = +Block 4 (linear "repeat-loop condition truthy") -> [B3]: + x-2 = refine(x-1 is truthy) +Block 5 (linear "repeat-loop condition falsy") -> [B1]: + x-3 = refine(x-1 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_until.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/repeat_until.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/repeat_until.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/repeat_until.flags-off.strict.output new file mode 100644 index 000000000..f954f3ba8 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_until.flags-off.strict.output @@ -0,0 +1,11 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B2]: + x-1 = +Block 2 (condition "repeat-loop condition") -> [B4, B5]: +Block 3 (linear "repeat-loop exit"): + local y-0 = +Block 4 (linear "repeat-loop condition truthy") -> [B3]: + x-2 = refine(x-1 is truthy) +Block 5 (linear "repeat-loop condition falsy") -> [B1]: + x-3 = refine(x-1 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_until.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/repeat_until.flags-on.nonstrict.output new file mode 100644 index 000000000..f954f3ba8 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_until.flags-on.nonstrict.output @@ -0,0 +1,11 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B2]: + x-1 = +Block 2 (condition "repeat-loop condition") -> [B4, B5]: +Block 3 (linear "repeat-loop exit"): + local y-0 = +Block 4 (linear "repeat-loop condition truthy") -> [B3]: + x-2 = refine(x-1 is truthy) +Block 5 (linear "repeat-loop condition falsy") -> [B1]: + x-3 = refine(x-1 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_until.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/repeat_until.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/repeat_until.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/repeat_until.flags-on.strict.output new file mode 100644 index 000000000..f954f3ba8 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_until.flags-on.strict.output @@ -0,0 +1,11 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (linear "repeat-loop body") -> [B2]: + x-1 = +Block 2 (condition "repeat-loop condition") -> [B4, B5]: +Block 3 (linear "repeat-loop exit"): + local y-0 = +Block 4 (linear "repeat-loop condition truthy") -> [B3]: + x-2 = refine(x-1 is truthy) +Block 5 (linear "repeat-loop condition falsy") -> [B1]: + x-3 = refine(x-1 is falsy) diff --git a/tests/golden/analysis/cfgconstruction/repeat_until.luau b/tests/golden/analysis/cfgconstruction/repeat_until.luau new file mode 100644 index 000000000..8a3d66ad9 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/repeat_until.luau @@ -0,0 +1,6 @@ +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = nil +repeat + x = 5 +until x +local y = x diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.nonstrict.output index 8fab2de84..c5b7ea09b 100644 --- a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.nonstrict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 - x-1 = 5 + local x-0 = + x-1 = diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.strict.output index 8fab2de84..c5b7ea09b 100644 --- a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-off.strict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 - x-1 = 5 + local x-0 = + x-1 = diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.nonstrict.output index 8fab2de84..c5b7ea09b 100644 --- a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.nonstrict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 - x-1 = 5 + local x-0 = + x-1 = diff --git a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.strict.output index 8fab2de84..c5b7ea09b 100644 --- a/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/simple_reassignment.flags-on.strict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 - x-1 = 5 + local x-0 = + x-1 = diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/single_local.flags-off.nonstrict.output index 707f79b44..e15f9f11f 100644 --- a/tests/golden/analysis/cfgconstruction/single_local.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/single_local.flags-off.nonstrict.output @@ -1,2 +1,2 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 + local x-0 = diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/single_local.flags-off.strict.output index 707f79b44..e15f9f11f 100644 --- a/tests/golden/analysis/cfgconstruction/single_local.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/single_local.flags-off.strict.output @@ -1,2 +1,2 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 + local x-0 = diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/single_local.flags-on.nonstrict.output index 707f79b44..e15f9f11f 100644 --- a/tests/golden/analysis/cfgconstruction/single_local.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/single_local.flags-on.nonstrict.output @@ -1,2 +1,2 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 + local x-0 = diff --git a/tests/golden/analysis/cfgconstruction/single_local.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/single_local.flags-on.strict.output index 707f79b44..e15f9f11f 100644 --- a/tests/golden/analysis/cfgconstruction/single_local.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/single_local.flags-on.strict.output @@ -1,2 +1,2 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 + local x-0 = diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.nonstrict.output index f32083dca..783f00c51 100644 --- a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.nonstrict.output @@ -1,8 +1,8 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local x-0 = 1 -Block 1 (linear "then branch") -> [B3]: - local y-0 = 2 -Block 2 (linear "else branch") -> [B3]: - local z-0 = 3 + local x-0 = +Block 1 (linear "then block") -> [B3]: + local y-0 = +Block 2 (linear "else block") -> [B3]: + local z-0 = Block 3 (linear "merge"): - local w-0 = x-0 + local w-0 = diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.strict.output index f32083dca..783f00c51 100644 --- a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-off.strict.output @@ -1,8 +1,8 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local x-0 = 1 -Block 1 (linear "then branch") -> [B3]: - local y-0 = 2 -Block 2 (linear "else branch") -> [B3]: - local z-0 = 3 + local x-0 = +Block 1 (linear "then block") -> [B3]: + local y-0 = +Block 2 (linear "else block") -> [B3]: + local z-0 = Block 3 (linear "merge"): - local w-0 = x-0 + local w-0 = diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.nonstrict.output index f32083dca..783f00c51 100644 --- a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.nonstrict.output @@ -1,8 +1,8 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local x-0 = 1 -Block 1 (linear "then branch") -> [B3]: - local y-0 = 2 -Block 2 (linear "else branch") -> [B3]: - local z-0 = 3 + local x-0 = +Block 1 (linear "then block") -> [B3]: + local y-0 = +Block 2 (linear "else block") -> [B3]: + local z-0 = Block 3 (linear "merge"): - local w-0 = x-0 + local w-0 = diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.strict.output index f32083dca..783f00c51 100644 --- a/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_if_else_unmodified.flags-on.strict.output @@ -1,8 +1,8 @@ Block 0 (entry "Entry Block") -> [B1, B2]: - local x-0 = 1 -Block 1 (linear "then branch") -> [B3]: - local y-0 = 2 -Block 2 (linear "else branch") -> [B3]: - local z-0 = 3 + local x-0 = +Block 1 (linear "then block") -> [B3]: + local y-0 = +Block 2 (linear "else block") -> [B3]: + local z-0 = Block 3 (linear "merge"): - local w-0 = x-0 + local w-0 = diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.nonstrict.output index b2a84db94..428510948 100644 --- a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.nonstrict.output @@ -1,9 +1,9 @@ Block 0 (entry "Entry Block") -> [B1]: - local x-0 = 1 - local iterations-0 = 0 + local x-0 = + local iterations-0 = Block 1 (condition "while-loop condition") -> [B2, B3]: iterations-1 = join(iterations-0, iterations-2) Block 2 (linear "while-loop body") -> [B1]: - local y-0 = x-0 - iterations-2 = iterations-1 + 1 + local y-0 = + iterations-2 = Block 3 (linear "while-loop exit"): diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.strict.output index b2a84db94..428510948 100644 --- a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-off.strict.output @@ -1,9 +1,9 @@ Block 0 (entry "Entry Block") -> [B1]: - local x-0 = 1 - local iterations-0 = 0 + local x-0 = + local iterations-0 = Block 1 (condition "while-loop condition") -> [B2, B3]: iterations-1 = join(iterations-0, iterations-2) Block 2 (linear "while-loop body") -> [B1]: - local y-0 = x-0 - iterations-2 = iterations-1 + 1 + local y-0 = + iterations-2 = Block 3 (linear "while-loop exit"): diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.nonstrict.output index b2a84db94..428510948 100644 --- a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.nonstrict.output @@ -1,9 +1,9 @@ Block 0 (entry "Entry Block") -> [B1]: - local x-0 = 1 - local iterations-0 = 0 + local x-0 = + local iterations-0 = Block 1 (condition "while-loop condition") -> [B2, B3]: iterations-1 = join(iterations-0, iterations-2) Block 2 (linear "while-loop body") -> [B1]: - local y-0 = x-0 - iterations-2 = iterations-1 + 1 + local y-0 = + iterations-2 = Block 3 (linear "while-loop exit"): diff --git a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.strict.output index b2a84db94..428510948 100644 --- a/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/trivial_phi_while_loop_unmodified.flags-on.strict.output @@ -1,9 +1,9 @@ Block 0 (entry "Entry Block") -> [B1]: - local x-0 = 1 - local iterations-0 = 0 + local x-0 = + local iterations-0 = Block 1 (condition "while-loop condition") -> [B2, B3]: iterations-1 = join(iterations-0, iterations-2) Block 2 (linear "while-loop body") -> [B1]: - local y-0 = x-0 - iterations-2 = iterations-1 + 1 + local y-0 = + iterations-2 = Block 3 (linear "while-loop exit"): diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-off.nonstrict.output index 877b47cea..5a5710589 100644 --- a/tests/golden/analysis/cfgconstruction/two_locals.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/two_locals.flags-off.nonstrict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 - local y-0 = 5 + local x-0 = + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-off.strict.output index 877b47cea..5a5710589 100644 --- a/tests/golden/analysis/cfgconstruction/two_locals.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/two_locals.flags-off.strict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 - local y-0 = 5 + local x-0 = + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-on.nonstrict.output index 877b47cea..5a5710589 100644 --- a/tests/golden/analysis/cfgconstruction/two_locals.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/two_locals.flags-on.nonstrict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 - local y-0 = 5 + local x-0 = + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/two_locals.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/two_locals.flags-on.strict.output index 877b47cea..5a5710589 100644 --- a/tests/golden/analysis/cfgconstruction/two_locals.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/two_locals.flags-on.strict.output @@ -1,3 +1,3 @@ Block 0 (entry "Entry Block"): - local x-0 = 4 - local y-0 = 5 + local x-0 = + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/while_break.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/while_break.flags-off.nonstrict.output new file mode 100644 index 000000000..a254cec3b --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_break.flags-off.nonstrict.output @@ -0,0 +1,11 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "while-loop body") -> [B4, B5]: +Block 3 (linear "while-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B3]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/while_break.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/while_break.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/while_break.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/while_break.flags-off.strict.output new file mode 100644 index 000000000..a254cec3b --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_break.flags-off.strict.output @@ -0,0 +1,11 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "while-loop body") -> [B4, B5]: +Block 3 (linear "while-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B3]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/while_break.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/while_break.flags-on.nonstrict.output new file mode 100644 index 000000000..a254cec3b --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_break.flags-on.nonstrict.output @@ -0,0 +1,11 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "while-loop body") -> [B4, B5]: +Block 3 (linear "while-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B3]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/while_break.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/while_break.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/while_break.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/while_break.flags-on.strict.output new file mode 100644 index 000000000..a254cec3b --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_break.flags-on.strict.output @@ -0,0 +1,11 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2) +Block 2 (linear "while-loop body") -> [B4, B5]: +Block 3 (linear "while-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B3]: +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-2 = diff --git a/tests/golden/analysis/cfgconstruction/while_break.luau b/tests/golden/analysis/cfgconstruction/while_break.luau new file mode 100644 index 000000000..c18acf52d --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_break.luau @@ -0,0 +1,9 @@ +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 1 +while true do + if x > 0 then + break + end + x = x + 1 +end +local w = x diff --git a/tests/golden/analysis/cfgconstruction/while_continue.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/while_continue.flags-off.nonstrict.output new file mode 100644 index 000000000..0adee56d9 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_continue.flags-off.nonstrict.output @@ -0,0 +1,12 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2, x-3) +Block 2 (linear "while-loop body") -> [B4, B5]: +Block 3 (linear "while-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B1]: + x-2 = +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-3 = diff --git a/tests/golden/analysis/cfgconstruction/while_continue.flags-off.runtime.output b/tests/golden/analysis/cfgconstruction/while_continue.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/while_continue.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/while_continue.flags-off.strict.output new file mode 100644 index 000000000..0adee56d9 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_continue.flags-off.strict.output @@ -0,0 +1,12 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2, x-3) +Block 2 (linear "while-loop body") -> [B4, B5]: +Block 3 (linear "while-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B1]: + x-2 = +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-3 = diff --git a/tests/golden/analysis/cfgconstruction/while_continue.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/while_continue.flags-on.nonstrict.output new file mode 100644 index 000000000..0adee56d9 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_continue.flags-on.nonstrict.output @@ -0,0 +1,12 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2, x-3) +Block 2 (linear "while-loop body") -> [B4, B5]: +Block 3 (linear "while-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B1]: + x-2 = +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-3 = diff --git a/tests/golden/analysis/cfgconstruction/while_continue.flags-on.runtime.output b/tests/golden/analysis/cfgconstruction/while_continue.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/cfgconstruction/while_continue.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/while_continue.flags-on.strict.output new file mode 100644 index 000000000..0adee56d9 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_continue.flags-on.strict.output @@ -0,0 +1,12 @@ +Block 0 (entry "Entry Block") -> [B1]: + local x-0 = +Block 1 (condition "while-loop condition") -> [B2, B3]: + x-1 = join(x-0, x-2, x-3) +Block 2 (linear "while-loop body") -> [B4, B5]: +Block 3 (linear "while-loop exit"): + local w-0 = +Block 4 (linear "then block") -> [B1]: + x-2 = +Block 5 (linear "else block") -> [B6]: +Block 6 (linear "merge") -> [B1]: + x-3 = diff --git a/tests/golden/analysis/cfgconstruction/while_continue.luau b/tests/golden/analysis/cfgconstruction/while_continue.luau new file mode 100644 index 000000000..2f46c6f26 --- /dev/null +++ b/tests/golden/analysis/cfgconstruction/while_continue.luau @@ -0,0 +1,10 @@ +--!golden fflags=DebugLuauAnalyzeDumpsCFG=true +local x = 1 +while x > 0 do + if x > 0 then + x = 0 + continue + end + x = x + 1 +end +local w = x diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-off.nonstrict.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-off.nonstrict.output index e4aa9c0d1..365102af9 100644 --- a/tests/golden/analysis/cfgconstruction/while_loop.flags-off.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/while_loop.flags-off.nonstrict.output @@ -1,10 +1,10 @@ Block 0 (entry "Entry Block") -> [B1]: - local x-0 = nil + local x-0 = Block 1 (condition "while-loop condition") -> [B2, B3]: - x-1 = join(x-0, x-3) + x-1 = join(x-0, x-4) Block 2 (linear "while-loop body") -> [B1]: - x-2 = refine(x-1 falsy) - x-3 = 5 + x-2 = refine(x-1 is falsy) + x-4 = Block 3 (linear "while-loop exit"): - x-4 = refine(x-1 truthy) - local y-0 = x-4 + x-3 = refine(x-1 is truthy) + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-off.strict.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-off.strict.output index e4aa9c0d1..365102af9 100644 --- a/tests/golden/analysis/cfgconstruction/while_loop.flags-off.strict.output +++ b/tests/golden/analysis/cfgconstruction/while_loop.flags-off.strict.output @@ -1,10 +1,10 @@ Block 0 (entry "Entry Block") -> [B1]: - local x-0 = nil + local x-0 = Block 1 (condition "while-loop condition") -> [B2, B3]: - x-1 = join(x-0, x-3) + x-1 = join(x-0, x-4) Block 2 (linear "while-loop body") -> [B1]: - x-2 = refine(x-1 falsy) - x-3 = 5 + x-2 = refine(x-1 is falsy) + x-4 = Block 3 (linear "while-loop exit"): - x-4 = refine(x-1 truthy) - local y-0 = x-4 + x-3 = refine(x-1 is truthy) + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-on.nonstrict.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-on.nonstrict.output index e4aa9c0d1..365102af9 100644 --- a/tests/golden/analysis/cfgconstruction/while_loop.flags-on.nonstrict.output +++ b/tests/golden/analysis/cfgconstruction/while_loop.flags-on.nonstrict.output @@ -1,10 +1,10 @@ Block 0 (entry "Entry Block") -> [B1]: - local x-0 = nil + local x-0 = Block 1 (condition "while-loop condition") -> [B2, B3]: - x-1 = join(x-0, x-3) + x-1 = join(x-0, x-4) Block 2 (linear "while-loop body") -> [B1]: - x-2 = refine(x-1 falsy) - x-3 = 5 + x-2 = refine(x-1 is falsy) + x-4 = Block 3 (linear "while-loop exit"): - x-4 = refine(x-1 truthy) - local y-0 = x-4 + x-3 = refine(x-1 is truthy) + local y-0 = diff --git a/tests/golden/analysis/cfgconstruction/while_loop.flags-on.strict.output b/tests/golden/analysis/cfgconstruction/while_loop.flags-on.strict.output index e4aa9c0d1..365102af9 100644 --- a/tests/golden/analysis/cfgconstruction/while_loop.flags-on.strict.output +++ b/tests/golden/analysis/cfgconstruction/while_loop.flags-on.strict.output @@ -1,10 +1,10 @@ Block 0 (entry "Entry Block") -> [B1]: - local x-0 = nil + local x-0 = Block 1 (condition "while-loop condition") -> [B2, B3]: - x-1 = join(x-0, x-3) + x-1 = join(x-0, x-4) Block 2 (linear "while-loop body") -> [B1]: - x-2 = refine(x-1 falsy) - x-3 = 5 + x-2 = refine(x-1 is falsy) + x-4 = Block 3 (linear "while-loop exit"): - x-4 = refine(x-1 truthy) - local y-0 = x-4 + x-3 = refine(x-1 is truthy) + local y-0 = diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.nonstrict.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.nonstrict.output new file mode 100644 index 000000000..d3f301a0b --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.nonstrict.output @@ -0,0 +1 @@ +./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau(2,86): TypeError: Unknown global 'integer'; consider assigning to it first diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.runtime.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.runtime.output new file mode 100644 index 000000000..bba4c086a --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.runtime.output @@ -0,0 +1,3 @@ +./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau:2: attempt to index nil with nil +stacktrace: +./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau:2 diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.strict.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.strict.output new file mode 100644 index 000000000..d3f301a0b --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.strict.output @@ -0,0 +1 @@ +./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau(2,86): TypeError: Unknown global 'integer'; consider assigning to it first diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.nonstrict.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.runtime.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.runtime.output new file mode 100644 index 000000000..bba4c086a --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.runtime.output @@ -0,0 +1,3 @@ +./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau:2: attempt to index nil with nil +stacktrace: +./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau:2 diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.strict.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau new file mode 100644 index 000000000..03073567f --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau @@ -0,0 +1,2 @@ +--!nonstrict +X = if X[X] then X "" elseif "" == X then X elseif X then X else {[{[{X,n0=X,}]=X,n0=integer.add + X,}]=X,} \ No newline at end of file diff --git a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.strict.output new file mode 100644 index 000000000..5c8159de2 --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.strict.output @@ -0,0 +1,2 @@ +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(5,29): TypeError: Expected this to be 'string', but got 'string?'; +`nil` is not a subtype of `string` diff --git a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.nonstrict.output b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.strict.output b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.strict.output new file mode 100644 index 000000000..5c8159de2 --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.strict.output @@ -0,0 +1,2 @@ +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(5,29): TypeError: Expected this to be 'string', but got 'string?'; +`nil` is not a subtype of `string` diff --git a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.luau b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.luau new file mode 100644 index 000000000..b47e4c0c2 --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.luau @@ -0,0 +1,9 @@ +--!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true + +local function f(v: string?) + -- the annotation does not narrow the condition's value: `v` is still `string?` here + while local x: string = v do + end +end + +return f diff --git a/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-on.nonstrict.output b/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-on.strict.output b/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_basic_typecheck.luau b/tests/golden/analysis/refinements/while_local_basic_typecheck.luau new file mode 100644 index 000000000..26e2b229c --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_basic_typecheck.luau @@ -0,0 +1,10 @@ +--!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true + +local function f(v: number?) + while local x = v do + -- arithmetic requires `x` to have narrowed from `number?` to `number` + print(x + 1) + end +end + +return f diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.nonstrict.output new file mode 100644 index 000000000..ad5fd3bff --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/refinements/while_local_binding_not_visible_after_block.luau(10,7): TypeError: Unknown global 'x'; consider assigning to it first +./analysis/refinements/while_local_binding_not_visible_after_block.luau(4,13): LocalShadow: Variable 'x' shadows a global variable used at line 10 diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.strict.output new file mode 100644 index 000000000..ad5fd3bff --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.strict.output @@ -0,0 +1,2 @@ +./analysis/refinements/while_local_binding_not_visible_after_block.luau(10,7): TypeError: Unknown global 'x'; consider assigning to it first +./analysis/refinements/while_local_binding_not_visible_after_block.luau(4,13): LocalShadow: Variable 'x' shadows a global variable used at line 10 diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.nonstrict.output b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.nonstrict.output new file mode 100644 index 000000000..ad5fd3bff --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/refinements/while_local_binding_not_visible_after_block.luau(10,7): TypeError: Unknown global 'x'; consider assigning to it first +./analysis/refinements/while_local_binding_not_visible_after_block.luau(4,13): LocalShadow: Variable 'x' shadows a global variable used at line 10 diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.strict.output b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.strict.output new file mode 100644 index 000000000..ad5fd3bff --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.strict.output @@ -0,0 +1,2 @@ +./analysis/refinements/while_local_binding_not_visible_after_block.luau(10,7): TypeError: Unknown global 'x'; consider assigning to it first +./analysis/refinements/while_local_binding_not_visible_after_block.luau(4,13): LocalShadow: Variable 'x' shadows a global variable used at line 10 diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.luau b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.luau new file mode 100644 index 000000000..9ec3e1f11 --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.luau @@ -0,0 +1,10 @@ +--!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true + +local n = 0 +while local x = n < 3 do + n += 1 + -- `x` is narrowed to `true` in the body, so this would fail if it were `boolean` + local t: true = x + print(t) +end +print(x) diff --git a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-on.nonstrict.output b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-on.strict.output b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.luau b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.luau new file mode 100644 index 000000000..2de422db7 --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.luau @@ -0,0 +1,11 @@ +--!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true + +local function f(v: string?) + while local x = v do + -- `x` must have narrowed from `string?` to `string` to satisfy this annotation + local s: string = x + print(s) + end +end + +return f diff --git a/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-on.nonstrict.output b/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-on.strict.output b/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_refines_annotated_type.luau b/tests/golden/analysis/refinements/while_local_refines_annotated_type.luau new file mode 100644 index 000000000..44ef5ed3f --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_refines_annotated_type.luau @@ -0,0 +1,11 @@ +--!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true + +local function f(v: number?) + while local x: number? = v do + -- `x` is annotated `number?` but is still narrowed by `truthy` to `number` in the body + local n: number = x + print(n) + end +end + +return f diff --git a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.strict.output new file mode 100644 index 000000000..19e0e7a8f --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.strict.output @@ -0,0 +1,6 @@ +./analysis/refinements/while_local_table_annotation_mismatch.luau(4,32): TypeError: Expected this to be + '(false | { y: number })?' +but got + 'false | { y: string }'; +`{ y: string }` is not a subtype of `(false | { y: number })?` +./analysis/refinements/while_local_table_annotation_mismatch.luau(4,59): TypeError: Expected this to be '{ y: number }', but got 'nil' diff --git a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.nonstrict.output b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.strict.output b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.strict.output new file mode 100644 index 000000000..19e0e7a8f --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.strict.output @@ -0,0 +1,6 @@ +./analysis/refinements/while_local_table_annotation_mismatch.luau(4,32): TypeError: Expected this to be + '(false | { y: number })?' +but got + 'false | { y: string }'; +`{ y: string }` is not a subtype of `(false | { y: number })?` +./analysis/refinements/while_local_table_annotation_mismatch.luau(4,59): TypeError: Expected this to be '{ y: number }', but got 'nil' diff --git a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.luau b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.luau new file mode 100644 index 000000000..05842d0d3 --- /dev/null +++ b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.luau @@ -0,0 +1,6 @@ +--!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true + +local once = true +while local x: { y: number } = once and { y = "oops" } or nil do + once = false +end diff --git a/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.nonstrict.output b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.runtime.output b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.runtime.output new file mode 100644 index 000000000..9caa47219 --- /dev/null +++ b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.runtime.output @@ -0,0 +1,2 @@ +Warning: unrecognized flag 'LuauOneBitAssumedConstraintTracking'. +Warning: unrecognized flag 'LuauNonreentrantLookupTableProp'. diff --git a/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.strict.output b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-off.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.nonstrict.output b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.runtime.output b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.runtime.output new file mode 100644 index 000000000..9caa47219 --- /dev/null +++ b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.runtime.output @@ -0,0 +1,2 @@ +Warning: unrecognized flag 'LuauOneBitAssumedConstraintTracking'. +Warning: unrecognized flag 'LuauNonreentrantLookupTableProp'. diff --git a/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.strict.output b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.luau b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.luau new file mode 100644 index 000000000..10ae3ca9a --- /dev/null +++ b/tests/golden/analysis/runtime-limits/ride_13358_large_table_memory_explosion.luau @@ -0,0 +1,701 @@ +--!golden fflags=LuauOneBitAssumedConstraintTracking,LuauNonreentrantLookupTableProp +--!nonstrict +local function fromRGB(a: number, b: number, c: number): number + return 0 +end + +local ITEMS = { + { + id = "FI-01", + name = "Squire's Kit", + vibe = "Plain, sturdy, barely enchanted", + light = "Dawn", + color = fromRGB(246, 205, 190), + layers = { + { slot = "Armor", ids = { 208181851693040, 71495122908637, 218109918534565 }, label = "Padded gambeson" }, + { slot = "Armor", ids = { 972112624924788, 50031031217662, 312033150409647 }, label = "Leather jerkin" }, + { slot = "Weapon", ids = { 632636749961737, 95816258852859, 32565191941902 }, label = "Training sword" }, + { slot = "Helm", ids = { 64059976124987, 837152814833252, 389784772395793 }, label = "Iron cap" }, + { slot = "Ring", ids = { 576292574957372, 60047994727685, 61038321806754 }, label = "Copper band" }, + }, + }, + { + id = "FI-02", + name = "Hearth Knight", + vibe = "Warm steel, ember blade", + light = "Twilight", + color = fromRGB(196, 140, 112), + layers = { + { slot = "Amulet", ids = { 13663711715433, 129630023341309, 940216698769313 }, label = "Ember amulet" }, + { slot = "Amulet", ids = { 72569969202626, 71522839437197, 50123792762965 }, label = "Phoenix feather charm" }, + { slot = "Armor", ids = { 78140763592939, 227639966894414 }, label = "Bronze breastplate" }, + { slot = "Weapon", ids = { 160975041301694, 61738037705649, 881390141665671 }, label = "Flameforged longsword" }, + { slot = "Ring", ids = { 727891604384849, 827967081258816, 18886892846795 }, label = "Ring of kindling" }, + }, + }, + { + id = "FI-03", + name = "Frost Warden", + vibe = "Icy runes and thin circlets", + light = "Arcane", + color = fromRGB(150, 196, 246), + layers = { + { slot = "Amulet", ids = { 28346313405753, 679558326355812, 76460924069016 }, label = "Rimeheart amulet" }, + { slot = "Armor", ids = { 652358831195643, 87141750001692 }, label = "Frostweave mail" }, + { slot = "Weapon", ids = { 868481960281238, 766481657757826 }, label = "Glacier spear" }, + { slot = "Helm", ids = { 202940147165398, 26581397964443, 704734245617361 }, label = "Silver circlet" }, + }, + }, + { + id = "FI-04", + name = "Necromancer", + vibe = "Black bone, sharp sigils", + light = "Torchlight", + color = fromRGB(70, 56, 78), + layers = { + { slot = "Amulet", ids = { 353911041738282, 652036460032868, 994285490574392 }, label = "Skull phylactery" }, + { slot = "Amulet", ids = { 658852408512799, 698027666613053, 40929543539656 }, label = "Soulbound talisman" }, + { slot = "Armor", ids = { 642632809465606, 249231186539405 }, label = "Shadowsilk robes" }, + { slot = "Weapon", ids = { 279332613560120, 74477789645040, 191885111347958 }, label = "Bone staff" }, + { slot = "Helm", ids = { 356703481446940, 959038550795490 }, label = "Obsidian crown" }, + { slot = "Ring", ids = { 42599624448908, 41791839499194 }, label = "Ring of the grave" }, + }, + }, + { + id = "FI-05", + name = "Barbarian", + vibe = "Furs, warpaint, big axe", + light = "Forge", + color = fromRGB(104, 118, 84), + layers = { + { slot = "Armor", ids = { 685000907251741, 825995089028037, 50600610782209 }, label = "Wolf pelt" }, + { slot = "Armor", ids = { 71797792871890, 937433540648471 }, label = "Hide bracers" }, + { slot = "Amulet", ids = { 56864732760479, 478753098505980 }, label = "Tooth necklace" }, + }, + }, + { + id = "FI-06", + name = "Gem Hoarder", + vibe = "Jewels, gold, prismatic blade", + light = "Twilight", + color = fromRGB(232, 150, 220), + layers = { + { slot = "Armor", ids = { 79538286603217, 10189832931436 }, label = "Jewel-studded vest" }, + { slot = "Amulet", ids = { 42602140327930, 358259147477881, 255415630773467 }, label = "Dragon's hoard pendant" }, + { slot = "Weapon", ids = { 592317222070868, 983425098165412 }, label = "Prismatic dagger" }, + { slot = "Ring", ids = { 261493126434410, 419762371288839, 156296619353705 }, label = "Ring of many gems" }, + }, + }, + { + id = "FI-07", + name = "Bard", + vibe = "Starry charms, singing blade", + light = "Arcane", + color = fromRGB(248, 128, 168), + layers = { + { slot = "Amulet", ids = { 84672306018806, 29776962672935 }, label = "Starsong locket" }, + { slot = "Amulet", ids = { 74059731037055, 95215981954526, 461102699019489 }, label = "Silver lute pick" }, + { slot = "Armor", ids = { 949470969154507, 24336363353448 }, label = "Velvet doublet" }, + { slot = "Weapon", ids = { 34773254213368, 975128582125759 }, label = "Singing rapier" }, + { slot = "Ring", ids = { 24261004546780, 460112407329587 }, label = "Ring of encore" }, + }, + }, + { + id = "FI-08", + name = "Desert Nomad", + vibe = "Sand-worn, sun-scorched", + light = "Dawn", + color = fromRGB(236, 150, 120), + layers = { + { slot = "Armor", ids = { 18951561617074, 989580705888173, 954749806067875 }, label = "Sandcloth wraps" }, + { slot = "Armor", ids = { 36321139187069, 898346735706374, 127769972891697 }, label = "Sunscale vest" }, + { slot = "Weapon", ids = { 577401085656293, 60637336065071 }, label = "Curved scimitar" }, + { slot = "Helm", ids = { 15772184160726, 120637010371932 }, label = "Desert turban" }, + }, + }, + { + id = "FI-09", + name = "Vampire Lord", + vibe = "Blood rubies and fangs", + light = "Torchlight", + color = fromRGB(150, 30, 52), + layers = { + { slot = "Amulet", ids = { 752220539056039, 73179459563373 }, label = "Bloodstone amulet" }, + { slot = "Amulet", ids = { 700223438828399, 787095940906344 }, label = "Crimson vial" }, + { slot = "Armor", ids = { 249231186539405, 642632809465606 }, label = "Nightshade cloak" }, + { slot = "Weapon", ids = { 714747080963802, 870570075075700, 271655354451741 }, label = "Fanged sabre" }, + { slot = "Ring", ids = { 12808508269016, 42599624448908 }, label = "Ring of the eternal" }, + }, + }, + { + id = "FI-10", + name = "Artificer", + vibe = "Glowing runes, clockwork blade", + light = "Arcane", + color = fromRGB(80, 220, 230), + layers = { + { slot = "Armor", ids = { 11883539893344, 196014190283873 }, label = "Runeplate harness" }, + { slot = "Amulet", ids = { 14413258547480, 931892043056884 }, label = "Aether core" }, + { slot = "Weapon", ids = { 61406638214799, 609918948388946 }, label = "Clockwork crossbow" }, + { slot = "Ring", ids = { 792942505437807, 86775855339128 }, label = "Gearwork ring" }, + }, + }, + { + id = "FI-11", + name = "Battle-Worn Veteran", + vibe = "Just survived the siege", + light = "Forge", + color = fromRGB(120, 100, 140), + layers = { + { slot = "Armor", ids = { 68551493009437, 434101850403894 }, label = "Dented plate" }, + { slot = "Armor", ids = { 170935084494348, 27259268872900 }, label = "Patched chainmail" }, + { slot = "Armor", ids = { 940750000955808, 380905922719909 }, label = "Muddy tabard" }, + { slot = "Amulet", ids = { 194169170165655, 674574167348238 }, label = "Cracked medallion" }, + }, + }, + { + id = "FI-12", + name = "Pixie", + vibe = "Tiny wings, big sparkle", + light = "Dawn", + color = fromRGB(250, 186, 206), + layers = { + { slot = "Amulet", ids = { 248655662779244, 80135976550932 }, label = "Acorn charm" }, + { slot = "Armor", ids = { 424811367985788, 326240837592596, 83921044624572 }, label = "Petal tunic" }, + { slot = "Weapon", ids = { 454526025300225, 393586790153610, 845208900440573 }, label = "Thorn wand" }, + { slot = "Helm", ids = { 19345212124750, 86922230131682 }, label = "Flower crown" }, + { slot = "Ring", ids = { 255249791912159, 76735067369786, 608161558568789 }, label = "Dewdrop ring" }, + }, + }, + { + id = "FI-13", + name = "Tidecaller", + vibe = "Scales, teal, pearl glow", + light = "Twilight", + color = fromRGB(90, 196, 186), + layers = { + { slot = "Armor", ids = { 387961467204282 }, label = "Leviathan scale mail" }, + { slot = "Amulet", ids = { 843659714661449, 57826431013156 }, label = "Tidestone amulet" }, + { slot = "Armor", ids = { 18441101825596, 136505769080122 }, label = "Pearl pauldrons" }, + { slot = "Weapon", ids = { 592317222070868, 78252673782948 }, label = "Coral trident" }, + { slot = "Ring", ids = { 818183231921733, 95187614452371 }, label = "Kelp-wound ring" }, + }, + }, + { + id = "FI-14", + name = "Wraith", + vibe = "Pale shroud, hollow gaze", + light = "Torchlight", + color = fromRGB(226, 226, 232), + layers = { + { slot = "Armor", ids = { 76094278409331 }, label = "Spectral shroud" }, + { slot = "Amulet", ids = { 275126903057670, 498097524365309 }, label = "Hollow soulgem" }, + { slot = "Weapon", ids = { 51702062092679 }, label = "Faded scythe" }, + { slot = "Armor", ids = { 483373348592255 }, label = "Chain-bound wraps" }, + }, + }, + { + id = "FI-15", + name = "Sun Paladin", + vibe = "Gold radiance, holy hammer", + light = "Twilight", + color = fromRGB(226, 172, 84), + layers = { + { slot = "Armor", ids = { 350320636836104, 898346735706374 }, label = "Gilded plate" }, + { slot = "Amulet", ids = { 143370615575791, 358259147477881 }, label = "Sunburst holy symbol" }, + { slot = "Weapon", ids = { 32725032300761, 812255062127984, 80607968282299 }, label = "Dawnbringer warhammer" }, + { slot = "Helm", ids = { 91713069021248, 23393001979261 }, label = "Winged greathelm" }, + { slot = "Ring", ids = { 55147950910941 }, label = "Ring of radiance" }, + }, + }, + { + id = "FI-16", + name = "Beastmaster", + vibe = "Claws and tamed fury", + light = "Forge", + color = fromRGB(240, 140, 50), + layers = { + { slot = "Armor", ids = { 290323363473165, 880394199281285 }, label = "Tigerhide armor" }, + { slot = "Amulet", ids = { 405447873211627, 658852408512799 }, label = "Beast-call whistle" }, + { slot = "Armor", ids = { 206146655574703 }, label = "Claw gauntlets" }, + { slot = "Weapon", ids = { 34389768500616 }, label = "Fang glaive" }, + }, + }, + { + id = "FI-17", + name = "Winter Sovereign", + vibe = "White shimmer, frozen scepter", + light = "Dawn", + color = fromRGB(200, 226, 246), + layers = { + { slot = "Amulet", ids = { 99805051606181, 994137035610617, 786677172333952 }, label = "Snowfall pendant" }, + { slot = "Armor", ids = { 312033150409647, 136505769080122 }, label = "Hoarfrost gown" }, + { slot = "Weapon", ids = { 14156526882999, 267033715539969 }, label = "Icebound scepter" }, + { slot = "Helm", ids = { 580005657336635 }, label = "Crystal tiara" }, + { slot = "Ring", ids = { 642246627271167, 126027592326089 }, label = "Ring of winter" }, + }, + }, + { + id = "FI-18", + name = "Jester", + vibe = "Bells, motley, zero shame", + light = "Forge", + color = fromRGB(236, 72, 72), + layers = { + { slot = "Armor", ids = { 64387853035847, 517788954887147, 133472168561155 }, label = "Motley garb" }, + { slot = "Amulet", ids = { 90767657196967, 447882503199801 }, label = "Jingle-bell collar" }, + { slot = "Weapon", ids = { 450336192801408, 25293019151049, 263667028947062 }, label = "Squeaking scepter" }, + }, + }, + { + id = "FI-19", + name = "Peasant", + vibe = "Pitchfork, cap, done", + light = "Dawn", + color = fromRGB(222, 200, 180), + layers = { + { slot = "Helm", ids = { 245664076991006, 11238808198678 }, label = "Straw hat" }, + { slot = "Weapon", ids = { 32565191941902, 632636749961737 }, label = "Pitchfork" }, + { slot = "Armor", ids = { 309656396165076, 71495122908637 }, label = "Burlap tunic" }, + }, + }, + { + id = "FI-20", + name = "Archmage", + vibe = "Every school of magic at once", + light = "Arcane", + color = fromRGB(170, 110, 246), + layers = { + { slot = "Amulet", ids = { 146260050970738, 66853317388948 }, label = "Prismatic focus" }, + { slot = "Amulet", ids = { 709171872481188 }, label = "Starfall charm" }, + { slot = "Armor", ids = { 79538286603217 }, label = "Jewel-studded vest" }, + { slot = "Armor", ids = { 574150592220024 }, label = "Spellweave robe" }, + { slot = "Armor", ids = { 136505769080122 }, label = "Mantle of stars" }, + { slot = "Weapon", ids = { 99591300034845, 831483088901212 }, label = "Staff of the spectrum" }, + { slot = "Helm", ids = { 551410641654049, 62377217006119 }, label = "Pointed hat of wisdom" }, + { slot = "Ring", ids = { 33385805447001, 14176453660767 }, label = "Ring of all elements" }, + }, + }, + -- Expansion pack: new combinations built only from the vetted items above. + { + id = "FI-21", + name = "Alchemist", + vibe = "Bubbling flasks, copper tools", + light = "Twilight", + color = fromRGB(168, 112, 78), + layers = { + { slot = "Amulet", ids = { 13663711715433, 129630023341309, 940216698769313 }, label = "Ember amulet" }, + { slot = "Armor", ids = { 78140763592939, 227639966894414 }, label = "Acid-stained apron" }, + { slot = "Weapon", ids = { 32725032300761, 812255062127984, 80607968282299 }, label = "Copper pestle mace" }, + { slot = "Helm", ids = { 91713069021248, 23393001979261 }, label = "Brass goggles" }, + { slot = "Ring", ids = { 727891604384849, 827967081258816, 18886892846795 }, label = "Ring of kindling" }, + }, + }, + { + id = "FI-22", + name = "Druid", + vibe = "Moss, bark, berry-stained staff", + light = "Dawn", + color = fromRGB(242, 120, 140), + layers = { + { slot = "Armor", ids = { 18951561617074, 989580705888173, 954749806067875 }, label = "Barkskin vest" }, + { slot = "Armor", ids = { 424811367985788, 326240837592596, 83921044624572 }, label = "Mossweave cloak" }, + { slot = "Weapon", ids = { 34773254213368, 975128582125759 }, label = "Rowan staff" }, + { slot = "Helm", ids = { 15772184160726, 120637010371932 }, label = "Antler circlet" }, + { slot = "Ring", ids = { 255249791912159, 76735067369786, 608161558568789 }, label = "Dewdrop ring" }, + }, + }, + { + id = "FI-23", + name = "Royal Champion", + vibe = "Polished, gleaming, tourney-ready", + light = "Forge", + color = fromRGB(196, 52, 76), + layers = { + { + slot = "Amulet", + ids = { 42602140327930, 358259147477881, 255415630773467 }, + label = "Champion's laurel medal", + }, + { slot = "Armor", ids = { 350320636836104, 898346735706374 }, label = "Tourney plate" }, + { slot = "Weapon", ids = { 160975041301694, 61738037705649, 881390141665671 }, label = "Flameforged longsword" }, + { slot = "Helm", ids = { 91713069021248, 23393001979261 }, label = "Plumed helm" }, + { slot = "Ring", ids = { 261493126434410, 419762371288839, 156296619353705 }, label = "Ring of many gems" }, + }, + }, + { + id = "FI-24", + name = "Elder Duelist", + vibe = "Classic steel, pearl hilt, red blade", + light = "Torchlight", + color = fromRGB(176, 36, 48), + layers = { + { slot = "Amulet", ids = { 72569969202626, 71522839437197, 50123792762965 }, label = "Phoenix feather charm" }, + { slot = "Armor", ids = { 18441101825596, 136505769080122 }, label = "Pearl pauldrons" }, + { slot = "Weapon", ids = { 34773254213368, 975128582125759 }, label = "Crimson rapier" }, + { slot = "Helm", ids = { 245664076991006, 11238808198678 }, label = "Feathered cavalier hat" }, + { slot = "Ring", ids = { 24261004546780, 460112407329587 }, label = "Ring of encore" }, + }, + }, + { + id = "FI-25", + name = "Fae Courtier", + vibe = "Glamour, rosy petals, shimmering blade", + light = "Twilight", + color = fromRGB(210, 170, 240), + layers = { + { slot = "Amulet", ids = { 42602140327930, 358259147477881, 255415630773467 }, label = "Moonlit fae locket" }, + { slot = "Armor", ids = { 136505769080122 }, label = "Gossamer mantle" }, + { slot = "Armor", ids = { 424811367985788, 326240837592596, 83921044624572 }, label = "Rosepetal gown" }, + { slot = "Weapon", ids = { 592317222070868, 983425098165412 }, label = "Prismatic dagger" }, + { slot = "Helm", ids = { 19345212124750, 86922230131682 }, label = "Flower crown" }, + { slot = "Ring", ids = { 261493126434410, 419762371288839, 156296619353705 }, label = "Ring of glamour" }, + }, + }, + { + id = "FI-26", + name = "Astral Seer", + vibe = "Cosmic runes and star-gems", + light = "Arcane", + color = fromRGB(86, 92, 210), + layers = { + { slot = "Amulet", ids = { 28346313405753, 679558326355812, 76460924069016 }, label = "Orb of the cosmos" }, + { slot = "Armor", ids = { 652358831195643, 87141750001692 }, label = "Starwoven robe" }, + { slot = "Armor", ids = { 79538286603217, 10189832931436 }, label = "Constellation sash" }, + { slot = "Weapon", ids = { 592317222070868, 78252673782948 }, label = "Comet staff" }, + { slot = "Ring", ids = { 792942505437807, 86775855339128 }, label = "Gearwork ring" }, + }, + }, + { + id = "FI-27", + name = "Midnight Witch", + vibe = "Black hex with a blood-red curse", + light = "Torchlight", + color = fromRGB(88, 40, 100), + layers = { + { slot = "Amulet", ids = { 353911041738282, 652036460032868, 994285490574392 }, label = "Midnight hexstone" }, + { slot = "Amulet", ids = { 700223438828399, 787095940906344 }, label = "Cursed blood vial" }, + { slot = "Armor", ids = { 642632809465606, 249231186539405 }, label = "Shadowsilk robes" }, + { slot = "Weapon", ids = { 279332613560120, 74477789645040, 191885111347958 }, label = "Bone staff" }, + { slot = "Helm", ids = { 356703481446940, 959038550795490 }, label = "Wide-brim witch hat" }, + { slot = "Ring", ids = { 12808508269016, 42599624448908 }, label = "Ring of the eternal" }, + }, + }, + { + id = "FI-28", + name = "Lich Thrall", + vibe = "Hollow, rusted, risen", + light = "Torchlight", + color = fromRGB(118, 140, 96), + layers = { + { slot = "Amulet", ids = { 275126903057670, 498097524365309 }, label = "Hollow soulgem" }, + { slot = "Armor", ids = { 170935084494348, 27259268872900 }, label = "Rusted chainmail" }, + { slot = "Armor", ids = { 940750000955808, 380905922719909 }, label = "Grave-dirt tabard" }, + { slot = "Armor", ids = { 68551493009437, 434101850403894 }, label = "Broken plate" }, + { slot = "Weapon", ids = { 51702062092679 }, label = "Faded scythe" }, + }, + }, + { + id = "FI-29", + name = "Yeti Hunter", + vibe = "Frosty furs, windburned steel", + light = "Dawn", + color = fromRGB(226, 236, 250), + layers = { + { slot = "Amulet", ids = { 99805051606181, 994137035610617, 786677172333952 }, label = "Snowfall pendant" }, + { slot = "Armor", ids = { 36321139187069, 898346735706374, 127769972891697 }, label = "Windbreaker furs" }, + { slot = "Armor", ids = { 312033150409647, 136505769080122 }, label = "Hoarfrost mail" }, + { slot = "Weapon", ids = { 868481960281238, 766481657757826 }, label = "Glacier spear" }, + { slot = "Helm", ids = { 580005657336635 }, label = "Frosted fur hood" }, + { slot = "Ring", ids = { 642246627271167, 126027592326089 }, label = "Ring of winter" }, + }, + }, + { + id = "FI-30", + name = "Star Herald", + vibe = "Stars, fanfare, encore", + light = "Arcane", + color = fromRGB(255, 104, 196), + layers = { + { slot = "Amulet", ids = { 84672306018806, 29776962672935 }, label = "Starsong locket" }, + { slot = "Amulet", ids = { 709171872481188 }, label = "Starfall charm" }, + { slot = "Armor", ids = { 574150592220024 }, label = "Spellweave robe" }, + { slot = "Weapon", ids = { 868481960281238, 766481657757826 }, label = "Herald's lance" }, + { slot = "Ring", ids = { 33385805447001, 14176453660767 }, label = "Ring of all elements" }, + }, + }, + { + id = "FI-31", + name = "Ranger", + vibe = "Sun, trail dust, adventure", + light = "Dawn", + color = fromRGB(190, 152, 94), + layers = { + { slot = "Armor", ids = { 18951561617074, 989580705888173, 954749806067875 }, label = "Trailworn leathers" }, + { slot = "Armor", ids = { 36321139187069, 898346735706374, 127769972891697 }, label = "Sunscale vest" }, + { slot = "Armor", ids = { 940750000955808, 380905922719909 }, label = "Dusty cloak" }, + { slot = "Weapon", ids = { 577401085656293, 60637336065071 }, label = "Yew longbow" }, + { slot = "Helm", ids = { 15772184160726, 120637010371932 }, label = "Ranger's hood" }, + }, + }, + { + id = "FI-32", + name = "Abyssal Siren", + vibe = "Deep-sea scales, chrome trident", + light = "Arcane", + color = fromRGB(40, 150, 170), + layers = { + { slot = "Amulet", ids = { 843659714661449, 57826431013156 }, label = "Abyssal pearl" }, + { slot = "Armor", ids = { 387961467204282 }, label = "Siren scale mail" }, + { slot = "Armor", ids = { 18441101825596, 136505769080122 }, label = "Pearl pauldrons" }, + { slot = "Weapon", ids = { 61406638214799, 609918948388946 }, label = "Chrome trident" }, + { slot = "Ring", ids = { 818183231921733, 95187614452371 }, label = "Kelp-wound ring" }, + }, + }, + { + id = "FI-33", + name = "Runeblade", + vibe = "Glowing glyphs and prismatic edge", + light = "Arcane", + color = fromRGB(120, 255, 170), + layers = { + { slot = "Amulet", ids = { 14413258547480, 931892043056884 }, label = "Aether core" }, + { slot = "Armor", ids = { 11883539893344, 196014190283873 }, label = "Glyph-etched plate" }, + { slot = "Armor", ids = { 79538286603217, 10189832931436 }, label = "Runestone sash" }, + { slot = "Weapon", ids = { 99591300034845, 831483088901212 }, label = "Prismatic runeblade" }, + { slot = "Helm", ids = { 551410641654049, 62377217006119 }, label = "Rune-crested helm" }, + { slot = "Ring", ids = { 792942505437807, 86775855339128 }, label = "Gearwork ring" }, + }, + }, + { + id = "FI-34", + name = "Familiar Keeper", + vibe = "Whiskers, petals, tiny wand", + light = "Dawn", + color = fromRGB(255, 196, 214), + layers = { + { slot = "Amulet", ids = { 248655662779244, 80135976550932 }, label = "Cat-eye charm" }, + { slot = "Armor", ids = { 206146655574703 }, label = "Claw gauntlets" }, + { slot = "Armor", ids = { 424811367985788, 326240837592596, 83921044624572 }, label = "Petal tunic" }, + { slot = "Weapon", ids = { 454526025300225, 393586790153610, 845208900440573 }, label = "Thorn wand" }, + { slot = "Helm", ids = { 19345212124750, 86922230131682 }, label = "Flower crown" }, + { slot = "Ring", ids = { 255249791912159, 76735067369786, 608161558568789 }, label = "Dewdrop ring" }, + }, + }, + { + id = "FI-35", + name = "Valkyrie", + vibe = "Gold, warpaint and a fierce spear", + light = "Forge", + color = fromRGB(200, 150, 40), + layers = { + { slot = "Amulet", ids = { 658852408512799, 698027666613053, 40929543539656 }, label = "Valhalla talisman" }, + { slot = "Armor", ids = { 685000907251741, 825995089028037, 50600610782209 }, label = "Wolf pelt" }, + { slot = "Armor", ids = { 350320636836104, 898346735706374 }, label = "Gilded plate" }, + { slot = "Weapon", ids = { 160975041301694, 61738037705649, 881390141665671 }, label = "Royal war spear" }, + { slot = "Helm", ids = { 356703481446940, 959038550795490 }, label = "Winged helm" }, + { slot = "Ring", ids = { 42599624448908, 41791839499194 }, label = "Oathring" }, + }, + }, + { + id = "FI-36", + name = "Tavern Regular", + vibe = "Cozy, cheap, low effort", + light = "Dawn", + color = fromRGB(236, 214, 230), + layers = { + { slot = "Amulet", ids = { 248655662779244, 80135976550932 }, label = "Lucky coin" }, + { slot = "Armor", ids = { 309656396165076, 71495122908637 }, label = "Burlap tunic" }, + { slot = "Weapon", ids = { 632636749961737, 95816258852859, 32565191941902 }, label = "Training sword" }, + { slot = "Helm", ids = { 64059976124987, 837152814833252, 389784772395793 }, label = "Iron cap" }, + { slot = "Ring", ids = { 576292574957372, 60047994727685, 61038321806754 }, label = "Copper band" }, + }, + }, + { + id = "FI-37", + name = "Hexed Puppet", + vibe = "Sweet petals meet bone staff", + light = "Torchlight", + color = fromRGB(150, 70, 110), + layers = { + { slot = "Amulet", ids = { 658852408512799, 698027666613053, 40929543539656 }, label = "Soulbound talisman" }, + { slot = "Armor", ids = { 424811367985788, 326240837592596, 83921044624572 }, label = "Stitched petal tunic" }, + { slot = "Weapon", ids = { 279332613560120, 74477789645040, 191885111347958 }, label = "Bone staff" }, + { slot = "Helm", ids = { 202940147165398, 26581397964443, 704734245617361 }, label = "Silver circlet" }, + { slot = "Ring", ids = { 255249791912159, 76735067369786, 608161558568789 }, label = "Dewdrop ring" }, + }, + }, + { + id = "FI-38", + name = "Dusk Templar", + vibe = "Warm gold and fading sunlight", + light = "Twilight", + color = fromRGB(242, 140, 72), + layers = { + { slot = "Amulet", ids = { 143370615575791, 358259147477881 }, label = "Sunburst holy symbol" }, + { slot = "Armor", ids = { 208181851693040, 71495122908637, 218109918534565 }, label = "Padded gambeson" }, + { slot = "Armor", ids = { 350320636836104, 898346735706374 }, label = "Gilded plate" }, + { slot = "Weapon", ids = { 32725032300761, 812255062127984, 80607968282299 }, label = "Dawnbringer warhammer" }, + { slot = "Helm", ids = { 91713069021248, 23393001979261 }, label = "Winged greathelm" }, + { slot = "Ring", ids = { 55147950910941 }, label = "Ring of radiance" }, + }, + }, +} + +local FULL_SETS = { + { + id = "FS-01", + name = "Fairy Princess", + vibe = "Petals, pearls and moonlight", + light = "Dawn", + color = fromRGB(244, 176, 196), + enchantFrom = "FI-12", + boots = { 98621006812359, 461402267704402, 281953154745071 }, + layers = { + { slot = "Crown", ids = { 90715747415, 5695813008, 414898395586201 }, label = "Moonpetal diadem" }, + { slot = "Tunic", ids = { 1495549234 }, label = "Silken fae tunic" }, + { slot = "Robe", ids = { 25815766146, 98553416437 }, label = "Dewdrop gown" }, + { slot = "Pendant", ids = { 82246260785, 6002674043, 9983309737 }, label = "Pearl of the glade" }, + { slot = "Quiver", ids = { 6590217296, 84697271315 }, label = "Butterfly-wing quiver" }, + }, + }, + { + id = "FS-02", + name = "High Elf Noble", + vibe = "Cream silks, mithril, soft boots", + light = "Twilight", + color = fromRGB(214, 196, 166), + enchantFrom = "FI-19", + boots = { 304644628384396, 57944880763576, 629776122405359 }, + layers = { + { slot = "Crown", ids = { 3141185075, 83830593570, 2924330789 }, label = "Silver leaf circlet" }, + { slot = "Mantle", ids = { 1031216282, 12132636207, 40084481281 }, label = "Elvish silk mantle" }, + { slot = "Greaves", ids = { 313530722843279, 6326167251 }, label = "Mithril greaves" }, + { slot = "Pendant", ids = { 9983309737, 6429242477 }, label = "Evenstar pendant" }, + }, + }, + { + id = "FS-03", + name = "Storm Sorceress", + vibe = "Lightning vest, runed leggings, visor", + light = "Arcane", + color = fromRGB(246, 150, 210), + enchantFrom = "FI-03", + boots = { 775904436132559, 62688752945469 }, + layers = { + { slot = "Crown", ids = { 2470070413, 1273722458, 3358652109 }, label = "Thundercloud crown" }, + { slot = "Vest", ids = { 223924628869033, 86531365941, 573575714950238 }, label = "Stormcaller vest" }, + { slot = "Greaves", ids = { 8391688219 }, label = "Runed leggings" }, + { slot = "Mask", ids = { 6845360005, 8538934058 }, label = "Lightning visor" }, + { slot = "Pendant", ids = { 9418686418 }, label = "Storm-eye pendant" }, + }, + }, + { + id = "FS-04", + name = "Dragon Queen", + vibe = "Dragonhide, big crown, gold torcs", + light = "Torchlight", + color = fromRGB(120, 72, 52), + enchantFrom = "FI-24", + boots = { 47682953059812, 7051010952810 }, + layers = { + { slot = "Crown", ids = { 55239908103, 5194907712 }, label = "Horned dragon crown" }, + { slot = "Cloak", ids = { 92391910025648, 639459800750827 }, label = "Dragonhide cloak" }, + { slot = "Robe", ids = { 1472864784, 8094489873 }, label = "Obsidian gown" }, + { slot = "Mask", ids = { 47147908825, 87306953792 }, label = "Gilded drake mask" }, + }, + }, + { + id = "FS-05", + name = "Wandering Monk", + vibe = "Topknot, simple wraps, prayer beads", + light = "Dawn", + color = fromRGB(236, 220, 200), + enchantFrom = "FI-01", + boots = { 896376150622001, 180348079674054, 33396058654875 }, + layers = { + { slot = "Crown", ids = { 9968992800, 7672736069, 930426975 }, label = "Topknot band" }, + { slot = "Tunic", ids = { 73469369549, 6264437143 }, label = "Linen wraps" }, + { slot = "Greaves", ids = { 1370797772, 8391688219 }, label = "Loose trousers" }, + { slot = "Mask", ids = { 87306953792, 50719189638 }, label = "Meditation veil" }, + }, + }, + { + id = "FS-06", + name = "Hedge Witch", + vibe = "Herbs, shawl, sun-worn", + light = "Twilight", + color = fromRGB(196, 92, 84), + enchantFrom = "FI-08", + boots = { 355709413826523, 501236217226199 }, + layers = { + { slot = "Crown", ids = { 12550544673, 9492842975, 59732993893148 }, label = "Braided herb wreath" }, + { slot = "Robe", ids = { 293661955873302, 15802122160092, 5834191396 }, label = "Patchwork robe" }, + { slot = "Mantle", ids = { 40084481281, 12132636207 }, label = "Woolen shawl" }, + }, + }, + { + id = "FS-07", + name = "Cursed Marionette", + vibe = "Tattered cloak, black gown, chains", + light = "Torchlight", + color = fromRGB(70, 60, 64), + enchantFrom = "FI-37", + boots = { 88421452032255, 57158083917018, 415290404924357 }, + layers = { + { slot = "Crown", ids = { 9126284367, 3853947009 }, label = "Thorned tiara" }, + { slot = "Cloak", ids = { 1040433979, 760922876458311 }, label = "Tattered cloak" }, + { slot = "Robe", ids = { 8094489873, 25815766146 }, label = "Black lace gown" }, + { slot = "Belt", ids = { 3583684624, 2580387987 }, label = "Puppet-string chains" }, + }, + }, + { + id = "FS-08", + name = "Lighthouse Keeper", + vibe = "Sea-white linen, shawl, pearls", + light = "Dawn", + color = fromRGB(150, 186, 206), + enchantFrom = "FI-36", + boots = { 215979462575169, 743368527555344 }, + layers = { + { slot = "Crown", ids = { 16555359985, 7363337774, 62638191631 }, label = "Salt-crusted cap" }, + { slot = "Tunic", ids = { 3977327202 }, label = "Sailcloth tunic" }, + { slot = "Mantle", ids = { 12132636207, 40084481281 }, label = "Woolen shawl" }, + { slot = "Robe", ids = { 1493821505 }, label = "Long oilskin coat" }, + { slot = "Pendant", ids = { 9983309737 }, label = "Pearl of the glade" }, + }, + }, + { + id = "FS-09", + name = "Shadow Assassin", + vibe = "Leather cloak, wraps, smoked visor", + light = "Forge", + color = fromRGB(40, 38, 40), + enchantFrom = "FI-02", + boots = { 22150352993181, 923753057985291 }, + layers = { + { slot = "Crown", ids = { 5194907712, 55239908103 }, label = "Night hood" }, + { slot = "Cloak", ids = { 3435696948 }, label = "Black leather cloak" }, + { slot = "Tunic", ids = { 6264437143, 73469369549 }, label = "Silent wraps" }, + { slot = "Greaves", ids = { 832023957700758, 8391688219 }, label = "Shadowstep greaves" }, + { slot = "Mask", ids = { 8538934058, 6845360005 }, label = "Smoked-glass visor" }, + }, + }, +} + +local byId = {} +for _, item in ipairs(ITEMS) do + byId[item.id] = item +end +for index, set in ipairs(FULL_SETS) do + set.full = true + local source = byId[set.enchantFrom] + if source then + for _, layer in ipairs(source.layers) do + table.insert(set.layers, layer) + end + end + table.insert(ITEMS, index, set) +end + +return ITEMS \ No newline at end of file diff --git a/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.nonstrict.output b/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.runtime.output b/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.strict.output b/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.strict.output new file mode 100644 index 000000000..f6eb3bacb --- /dev/null +++ b/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-off.strict.output @@ -0,0 +1,2 @@ +_luau_print (7, 17): number + diff --git a/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.nonstrict.output b/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.runtime.output b/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.strict.output b/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.strict.output new file mode 100644 index 000000000..f6eb3bacb --- /dev/null +++ b/tests/golden/analysis/tables/ride_13358_diamond_access_union.flags-on.strict.output @@ -0,0 +1,2 @@ +_luau_print (7, 17): number + diff --git a/tests/golden/analysis/tables/ride_13358_diamond_access_union.luau b/tests/golden/analysis/tables/ride_13358_diamond_access_union.luau new file mode 100644 index 000000000..fafe8b52b --- /dev/null +++ b/tests/golden/analysis/tables/ride_13358_diamond_access_union.luau @@ -0,0 +1,11 @@ +export type Details = { Id: number } +export type AssetDetails = Details | { Id: number } +export type BundleDetails = Details | { Id: number } +export type CatalogPage = { AssetDetails | BundleDetails } + +local function _readwrite(tbl: CatalogPage) + for _, detail in tbl do + local _: _luau_print + detail.Id = 42 + end +end \ No newline at end of file diff --git a/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.nonstrict.output b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.runtime.output b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.runtime.output new file mode 100644 index 000000000..b4c9c7527 --- /dev/null +++ b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.runtime.output @@ -0,0 +1,3 @@ +./analysis/tables/write_to_intersection_of_tables.luau:8: attempt to index nil with 'Id' +stacktrace: +./analysis/tables/write_to_intersection_of_tables.luau:8 diff --git a/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.strict.output b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.strict.output new file mode 100644 index 000000000..41f07592f --- /dev/null +++ b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-off.strict.output @@ -0,0 +1 @@ +./analysis/tables/write_to_intersection_of_tables.luau(9,10): TypeError: Expected this to be 'number', but got 'nil' diff --git a/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.nonstrict.output b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.runtime.output b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.runtime.output new file mode 100644 index 000000000..b4c9c7527 --- /dev/null +++ b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.runtime.output @@ -0,0 +1,3 @@ +./analysis/tables/write_to_intersection_of_tables.luau:8: attempt to index nil with 'Id' +stacktrace: +./analysis/tables/write_to_intersection_of_tables.luau:8 diff --git a/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.strict.output b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.strict.output new file mode 100644 index 000000000..41f07592f --- /dev/null +++ b/tests/golden/analysis/tables/write_to_intersection_of_tables.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/tables/write_to_intersection_of_tables.luau(9,10): TypeError: Expected this to be 'number', but got 'nil' diff --git a/tests/golden/analysis/tables/write_to_intersection_of_tables.luau b/tests/golden/analysis/tables/write_to_intersection_of_tables.luau new file mode 100644 index 000000000..c4d9abfbe --- /dev/null +++ b/tests/golden/analysis/tables/write_to_intersection_of_tables.luau @@ -0,0 +1,9 @@ +export type Foo = { Id: number } +export type Bar = { [string]: number } + +export type Foobar = Foo & Bar + +local tbl: Foobar = nil :: any + +tbl.Id = 42 -- OK +tbl.Id = nil -- Not OK! \ No newline at end of file diff --git a/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.nonstrict.output b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.runtime.output b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.strict.output b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.strict.output new file mode 100644 index 000000000..954c5362b --- /dev/null +++ b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-off.strict.output @@ -0,0 +1,11 @@ +./analysis/type-functions/oss_3053_setmetatable_overrides.luau(4,16): TypeError: Type function instance setmetatable is uninhabited +./analysis/type-functions/oss_3053_setmetatable_overrides.luau(9,16): TypeError: Type function instance setmetatable is uninhabited +./analysis/type-functions/oss_3053_setmetatable_overrides.luau(16,26): TypeError: Type function instance setmetatable is uninhabited +_luau_print (15, 13): getmetatable> + +_luau_print (16, 13): object1 + +_luau_print (17, 13): object0 + +_luau_print (18, 13): nil + diff --git a/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.nonstrict.output b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.runtime.output b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.strict.output b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.strict.output new file mode 100644 index 000000000..73f9c55fe --- /dev/null +++ b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.flags-on.strict.output @@ -0,0 +1,8 @@ +_luau_print (15, 13): object2 + +_luau_print (16, 13): object1 + +_luau_print (17, 13): object0 + +_luau_print (18, 13): nil + diff --git a/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.luau b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.luau new file mode 100644 index 000000000..3fe888628 --- /dev/null +++ b/tests/golden/analysis/type-functions/oss_3053_setmetatable_overrides.luau @@ -0,0 +1,20 @@ +type object0 = {} +type object1 = setmetatable<{} & object0, object0> +type object2 = setmetatable<{} & object1, object1> +type object3 = setmetatable<{} & object2, object2> +type object3_1 = setmetatable<{}, object2> + +local function _f() + local x : object3 = nil :: any + local o5 = getmetatable(x) + + local y : object2 = nil :: any + local o4 = getmetatable(y) + local o3 = getmetatable(o4) + local o2 = getmetatable(o3) + + local _: _luau_print + local _: _luau_print + local _: _luau_print + local _: _luau_print +end \ No newline at end of file diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-off.nonstrict.output b/tests/golden/syntax/while-local/error_missing_equals.flags-off.nonstrict.output new file mode 100644 index 000000000..f7b308340 --- /dev/null +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-off.nonstrict.output @@ -0,0 +1 @@ +./syntax/while-local/error_missing_equals.luau(3,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-off.runtime.output b/tests/golden/syntax/while-local/error_missing_equals.flags-off.runtime.output new file mode 100644 index 000000000..338ff64cf --- /dev/null +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-off.runtime.output @@ -0,0 +1,2 @@ +./syntax/while-local/error_missing_equals.luau:3: Expected '=' when parsing while local declaration, got 'do' +stacktrace: diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-off.strict.output b/tests/golden/syntax/while-local/error_missing_equals.flags-off.strict.output new file mode 100644 index 000000000..f7b308340 --- /dev/null +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-off.strict.output @@ -0,0 +1 @@ +./syntax/while-local/error_missing_equals.luau(3,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-on.nonstrict.output b/tests/golden/syntax/while-local/error_missing_equals.flags-on.nonstrict.output new file mode 100644 index 000000000..f7b308340 --- /dev/null +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-on.nonstrict.output @@ -0,0 +1 @@ +./syntax/while-local/error_missing_equals.luau(3,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-on.runtime.output b/tests/golden/syntax/while-local/error_missing_equals.flags-on.runtime.output new file mode 100644 index 000000000..338ff64cf --- /dev/null +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-on.runtime.output @@ -0,0 +1,2 @@ +./syntax/while-local/error_missing_equals.luau:3: Expected '=' when parsing while local declaration, got 'do' +stacktrace: diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-on.strict.output b/tests/golden/syntax/while-local/error_missing_equals.flags-on.strict.output new file mode 100644 index 000000000..f7b308340 --- /dev/null +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-on.strict.output @@ -0,0 +1 @@ +./syntax/while-local/error_missing_equals.luau(3,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' diff --git a/tests/golden/syntax/while-local/error_missing_equals.luau b/tests/golden/syntax/while-local/error_missing_equals.luau new file mode 100644 index 000000000..a8a44b1ae --- /dev/null +++ b/tests/golden/syntax/while-local/error_missing_equals.luau @@ -0,0 +1,3 @@ +--!golden fflags=DebugLuauWhileLocalSyntax=true + +while local x do end diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.nonstrict.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.nonstrict.output new file mode 100644 index 000000000..946039b0b --- /dev/null +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.nonstrict.output @@ -0,0 +1,4 @@ +./syntax/while-local/error_multiple_bindings.luau(3,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +./syntax/while-local/error_multiple_bindings.luau(4,1): SyntaxError: Expected 'end' (to close ',' at line 3), got +./syntax/while-local/error_multiple_bindings.luau(3,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence +./syntax/while-local/error_multiple_bindings.luau(3,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.runtime.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.runtime.output new file mode 100644 index 000000000..c8b3f3062 --- /dev/null +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.runtime.output @@ -0,0 +1,2 @@ +./syntax/while-local/error_multiple_bindings.luau:3: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +stacktrace: diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.strict.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.strict.output new file mode 100644 index 000000000..946039b0b --- /dev/null +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.strict.output @@ -0,0 +1,4 @@ +./syntax/while-local/error_multiple_bindings.luau(3,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +./syntax/while-local/error_multiple_bindings.luau(4,1): SyntaxError: Expected 'end' (to close ',' at line 3), got +./syntax/while-local/error_multiple_bindings.luau(3,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence +./syntax/while-local/error_multiple_bindings.luau(3,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.nonstrict.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.nonstrict.output new file mode 100644 index 000000000..946039b0b --- /dev/null +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.nonstrict.output @@ -0,0 +1,4 @@ +./syntax/while-local/error_multiple_bindings.luau(3,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +./syntax/while-local/error_multiple_bindings.luau(4,1): SyntaxError: Expected 'end' (to close ',' at line 3), got +./syntax/while-local/error_multiple_bindings.luau(3,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence +./syntax/while-local/error_multiple_bindings.luau(3,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.runtime.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.runtime.output new file mode 100644 index 000000000..c8b3f3062 --- /dev/null +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.runtime.output @@ -0,0 +1,2 @@ +./syntax/while-local/error_multiple_bindings.luau:3: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +stacktrace: diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.strict.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.strict.output new file mode 100644 index 000000000..946039b0b --- /dev/null +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.strict.output @@ -0,0 +1,4 @@ +./syntax/while-local/error_multiple_bindings.luau(3,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +./syntax/while-local/error_multiple_bindings.luau(4,1): SyntaxError: Expected 'end' (to close ',' at line 3), got +./syntax/while-local/error_multiple_bindings.luau(3,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence +./syntax/while-local/error_multiple_bindings.luau(3,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.luau b/tests/golden/syntax/while-local/error_multiple_bindings.luau new file mode 100644 index 000000000..b6d4c3d2c --- /dev/null +++ b/tests/golden/syntax/while-local/error_multiple_bindings.luau @@ -0,0 +1,3 @@ +--!golden fflags=DebugLuauWhileLocalSyntax=true + +while local x, y = 1 do end From e3275c20972d97fd5b230b89b742770064004256 Mon Sep 17 00:00:00 2001 From: erin5 <86601049+5-erin@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:35:57 +0530 Subject: [PATCH 05/13] Report type error when iterating over type containing tables that is not itself a subtype of `table` (#3090) The following code now correctly reports a type error: ```luau local function foo(t: boolean | number | vector | {}) for i, v in t do end end ``` Flagged behind `LuauTypeCheckGeneralizedIterationSoundness`. Adds 3 golden tests. The error reporting for the original check (which only raised if the type had *no* tables at all) has been changed to use a new `NotIterable` kind instead of `CannotCallNonFunction`. This is flagged behind `LuauTypeCheckUseNotIterable`. Fixes #2541. --------- Co-authored-by: PhoenixWhitefire <86601049+PhoenixWhitefire@users.noreply.github.com> --- Analysis/include/Luau/Error.h | 10 +++++++++- Analysis/include/Luau/Normalize.h | 3 +++ Analysis/src/Error.cpp | 14 ++++++++++++++ Analysis/src/IostreamHelpers.cpp | 2 ++ Analysis/src/Normalize.cpp | 10 ++++++++++ Analysis/src/TypeChecker2.cpp | 18 +++++++++++++++++- tests/TypeInfer.loops.test.cpp | 8 +++++++- ...r_has_non_tables.flags-off.nonstrict.output | 0 ...ator_has_non_tables.flags-off.strict.output | 0 ...or_has_non_tables.flags-on.nonstrict.output | 0 ...rator_has_non_tables.flags-on.strict.output | 1 + .../type-loops/iterator_has_non_tables.luau | 4 ++++ ...tor_is_non_table.flags-off.nonstrict.output | 0 ...erator_is_non_table.flags-off.strict.output | 2 ++ ...ator_is_non_table.flags-on.nonstrict.output | 0 ...terator_is_non_table.flags-on.strict.output | 1 + .../type-loops/iterator_is_non_table.luau | 4 ++++ ...rror_surpression.flags-off.nonstrict.output | 0 ...r_error_surpression.flags-off.strict.output | 0 ...error_surpression.flags-on.nonstrict.output | 0 ...or_error_surpression.flags-on.strict.output | 0 .../non_table_iterator_error_surpression.luau | 4 ++++ 22 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 tests/golden/analysis/type-loops/iterator_has_non_tables.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/type-loops/iterator_has_non_tables.flags-off.strict.output create mode 100644 tests/golden/analysis/type-loops/iterator_has_non_tables.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/type-loops/iterator_has_non_tables.flags-on.strict.output create mode 100644 tests/golden/analysis/type-loops/iterator_has_non_tables.luau create mode 100644 tests/golden/analysis/type-loops/iterator_is_non_table.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/type-loops/iterator_is_non_table.flags-off.strict.output create mode 100644 tests/golden/analysis/type-loops/iterator_is_non_table.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/type-loops/iterator_is_non_table.flags-on.strict.output create mode 100644 tests/golden/analysis/type-loops/iterator_is_non_table.luau create mode 100644 tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-off.strict.output create mode 100644 tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-on.strict.output create mode 100644 tests/golden/analysis/type-loops/non_table_iterator_error_surpression.luau diff --git a/Analysis/include/Luau/Error.h b/Analysis/include/Luau/Error.h index 975a7f470..381fc9943 100644 --- a/Analysis/include/Luau/Error.h +++ b/Analysis/include/Luau/Error.h @@ -667,6 +667,13 @@ struct IllegalClassPropertyOverride bool operator==(const IllegalClassPropertyOverride& rhs) const; }; +struct NotIterable +{ + TypeId ty; + + bool operator==(const NotIterable& rhs) const; +}; + using TypeErrorData = Variant< TypeMismatch, UnknownSymbol, @@ -737,7 +744,8 @@ using TypeErrorData = Variant< CyclicClassInheritance, InvalidClassExtension, IncompatibleClassMethodOverride, - IllegalClassPropertyOverride>; + IllegalClassPropertyOverride, + NotIterable>; struct TypeErrorSummary { diff --git a/Analysis/include/Luau/Normalize.h b/Analysis/include/Luau/Normalize.h index 4701be6c1..4a4a6b26b 100644 --- a/Analysis/include/Luau/Normalize.h +++ b/Analysis/include/Luau/Normalize.h @@ -268,6 +268,9 @@ struct NormalizedType /// Returns true if the type is a subtype of boolean(it could be a singleton). Behaves like Type::isBoolean() bool isSubtypeOfBooleans() const; + /// Returns true if the type is a subtype of `table`. + bool isSubtypeOfTable() const; + /// Returns true if this type should result in error suppressing behavior. bool shouldSuppressErrors() const; diff --git a/Analysis/src/Error.cpp b/Analysis/src/Error.cpp index 96dcdd6ac..1d4664312 100644 --- a/Analysis/src/Error.cpp +++ b/Analysis/src/Error.cpp @@ -1086,6 +1086,11 @@ struct ErrorConverter { return "Illegal override of property '" + e.property + "' on class '" + e.className + "' inherited from superclass '" + e.superName + "'"; } + + std::string operator()(const NotIterable& e) const + { + return "`" + toString(e.ty) + "` is not iterable"; + } }; struct InvalidNameChecker @@ -1338,6 +1343,11 @@ bool IllegalClassPropertyOverride::operator==(const IllegalClassPropertyOverride return property == rhs.property && className == rhs.className && superName == rhs.superName; } +bool NotIterable::operator==(const NotIterable& rhs) const +{ + return ty == rhs.ty; +} + int TypeError::code() const { return minCode() + int(data.index()); @@ -1841,6 +1851,10 @@ void copyError(T& e, TypeArena& destArena, CloneState& cloneState) else if constexpr (std::is_same_v) { } + else if constexpr (std::is_same_v) + { + e.ty = clone(e.ty); + } else static_assert(always_false_v, "Non-exhaustive type switch"); } diff --git a/Analysis/src/IostreamHelpers.cpp b/Analysis/src/IostreamHelpers.cpp index b84d7afe2..3b29c2124 100644 --- a/Analysis/src/IostreamHelpers.cpp +++ b/Analysis/src/IostreamHelpers.cpp @@ -348,6 +348,8 @@ static void errorToString(std::ostream& stream, const T& err) else if constexpr (std::is_same_v) stream << "IllegalClassPropertyOverride { property = " << err.property << ", className = " << err.className << ", superName = " << err.superName << " }"; + else if constexpr (std::is_same_v) + stream << "NotIterable { " << toString(err.ty) << " }"; else static_assert(always_false_v, "Non-exhaustive type switch"); } diff --git a/Analysis/src/Normalize.cpp b/Analysis/src/Normalize.cpp index a4dd3177a..984c50873 100644 --- a/Analysis/src/Normalize.cpp +++ b/Analysis/src/Normalize.cpp @@ -321,6 +321,16 @@ bool NormalizedType::isSubtypeOfBooleans() const !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars(); } +bool NormalizedType::isSubtypeOfTable() const +{ + if (FFlag::LuauIntegerType2) + return hasTables() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasStrings() + && !hasThreads() && !hasBuffers() && !hasFunctions() && !hasTyvars() && !hasIntegers(); + else + return hasTables() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasStrings() + && !hasThreads() && !hasBuffers() && !hasFunctions() && !hasTyvars(); +} + bool NormalizedType::shouldSuppressErrors() const { return hasErrors() || get(tops); diff --git a/Analysis/src/TypeChecker2.cpp b/Analysis/src/TypeChecker2.cpp index d3195967b..fa3e51a4b 100644 --- a/Analysis/src/TypeChecker2.cpp +++ b/Analysis/src/TypeChecker2.cpp @@ -49,6 +49,8 @@ LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAGVARIABLE(LuauTypeCheckGeneralizedIterationSoundness) +LUAU_FASTFLAGVARIABLE(LuauTypeCheckUseNotIterable) namespace Luau { @@ -1235,11 +1237,25 @@ void TypeChecker2::visit(AstStatForIn* forInStatement) } else if (iteratorNorm && iteratorNorm->hasTables()) { + if (FFlag::LuauTypeCheckGeneralizedIterationSoundness) + { + if (!iteratorNorm->shouldSuppressErrors() && !iteratorNorm->isSubtypeOfTable()) + { + if (FFlag::LuauTypeCheckUseNotIterable) + reportError(NotIterable{iteratorTy}, forInStatement->values.data[0]->location); + else + reportError(CannotCallNonFunction{iteratorTy}, forInStatement->values.data[0]->location); + } + } + // Ok. All tables can be iterated. } else if (!iteratorNorm || !iteratorNorm->shouldSuppressErrors()) { - reportError(CannotCallNonFunction{iteratorTy}, forInStatement->values.data[0]->location); + if (FFlag::LuauTypeCheckUseNotIterable) + reportError(NotIterable{iteratorTy}, forInStatement->values.data[0]->location); + else + reportError(CannotCallNonFunction{iteratorTy}, forInStatement->values.data[0]->location); } } diff --git a/tests/TypeInfer.loops.test.cpp b/tests/TypeInfer.loops.test.cpp index 914bec71b..00705c754 100644 --- a/tests/TypeInfer.loops.test.cpp +++ b/tests/TypeInfer.loops.test.cpp @@ -17,6 +17,7 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauForceOldSolver) +LUAU_FASTFLAG(LuauTypeCheckUseNotIterable) TEST_SUITE_BEGIN("TypeInferLoops"); @@ -230,6 +231,8 @@ TEST_CASE_FIXTURE(Fixture, "for_in_with_an_iterator_of_type_any") TEST_CASE_FIXTURE(Fixture, "for_in_loop_should_fail_with_non_function_iterator") { + ScopedFastFlag useNotIterable(FFlag::LuauTypeCheckUseNotIterable, true); + CheckResult result = check(R"( local foo = "bar" for i, v in foo do @@ -238,7 +241,10 @@ TEST_CASE_FIXTURE(Fixture, "for_in_loop_should_fail_with_non_function_iterator") LUAU_REQUIRE_ERROR_COUNT(1, result); - CHECK_EQ("Cannot call a value of type string", toString(result.errors[0])); + if (FFlag::DebugLuauForceOldSolver) + CHECK_EQ("Cannot call a value of type string", toString(result.errors[0])); + else + CHECK_EQ("`string` is not iterable", toString(result.errors[0])); } TEST_CASE_FIXTURE(BuiltinsFixture, "for_in_with_just_one_iterator_is_ok") diff --git a/tests/golden/analysis/type-loops/iterator_has_non_tables.flags-off.nonstrict.output b/tests/golden/analysis/type-loops/iterator_has_non_tables.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-loops/iterator_has_non_tables.flags-off.strict.output b/tests/golden/analysis/type-loops/iterator_has_non_tables.flags-off.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-loops/iterator_has_non_tables.flags-on.nonstrict.output b/tests/golden/analysis/type-loops/iterator_has_non_tables.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-loops/iterator_has_non_tables.flags-on.strict.output b/tests/golden/analysis/type-loops/iterator_has_non_tables.flags-on.strict.output new file mode 100644 index 000000000..cf823a9e3 --- /dev/null +++ b/tests/golden/analysis/type-loops/iterator_has_non_tables.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/type-loops/iterator_has_non_tables.luau(2,17): TypeError: `boolean | number | {string}` is not iterable diff --git a/tests/golden/analysis/type-loops/iterator_has_non_tables.luau b/tests/golden/analysis/type-loops/iterator_has_non_tables.luau new file mode 100644 index 000000000..28b54bc67 --- /dev/null +++ b/tests/golden/analysis/type-loops/iterator_has_non_tables.luau @@ -0,0 +1,4 @@ +local function _f(x: boolean | number | { string }) + for k, v in x do + end +end diff --git a/tests/golden/analysis/type-loops/iterator_is_non_table.flags-off.nonstrict.output b/tests/golden/analysis/type-loops/iterator_is_non_table.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-loops/iterator_is_non_table.flags-off.strict.output b/tests/golden/analysis/type-loops/iterator_is_non_table.flags-off.strict.output new file mode 100644 index 000000000..7ddda2c4f --- /dev/null +++ b/tests/golden/analysis/type-loops/iterator_is_non_table.flags-off.strict.output @@ -0,0 +1,2 @@ +./analysis/type-loops/iterator_is_non_table.luau(2,17): TypeError: Cannot call a value of type boolean in union: + boolean | number diff --git a/tests/golden/analysis/type-loops/iterator_is_non_table.flags-on.nonstrict.output b/tests/golden/analysis/type-loops/iterator_is_non_table.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-loops/iterator_is_non_table.flags-on.strict.output b/tests/golden/analysis/type-loops/iterator_is_non_table.flags-on.strict.output new file mode 100644 index 000000000..b0e929b53 --- /dev/null +++ b/tests/golden/analysis/type-loops/iterator_is_non_table.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/type-loops/iterator_is_non_table.luau(2,17): TypeError: `boolean | number` is not iterable diff --git a/tests/golden/analysis/type-loops/iterator_is_non_table.luau b/tests/golden/analysis/type-loops/iterator_is_non_table.luau new file mode 100644 index 000000000..43371859d --- /dev/null +++ b/tests/golden/analysis/type-loops/iterator_is_non_table.luau @@ -0,0 +1,4 @@ +local function _f(x: boolean | number) + for k, v in x do + end +end diff --git a/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-off.nonstrict.output b/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-off.strict.output b/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-off.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-on.nonstrict.output b/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-on.strict.output b/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.luau b/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.luau new file mode 100644 index 000000000..3ac02f3da --- /dev/null +++ b/tests/golden/analysis/type-loops/non_table_iterator_error_surpression.luau @@ -0,0 +1,4 @@ +local function _f(x: boolean | {} | any) + for k, v in x do + end +end From 91acc8decfca5281fab4a8db46c894268fc70aac Mon Sep 17 00:00:00 2001 From: vegorov-rbx <75688451+vegorov-rbx@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:55:41 +0200 Subject: [PATCH 06/13] Sync to upstream/release/746 (#3105) A new release for Luau is ready and brings in the `while local` statement form support and a tag guided runtime native recompilation, among other smaller fixes and improvements! `while local` allows you to create a binding right inside the `while` statement condition: ```luau while local x = fetch() do ... end ``` ### Analysis * Fixed a case of equality constraint producing unnecessary type cycles * Added auto-complete suggestions for `local` and `const` after `if`, `elseif` and `while` * Globals that are read and never assigned no longer leak a blocked type * Globals used inside type functions no longer have effect on type inference outside them and report a typechecking error ### Runtime * Added hash salting for interning string table when `lua_setpointerencodekey` is called to avoid crafted string sets from slowing down string operations * Fixed a crash that could happen in `luau_load` if embedder exposes GC controls to Luau code * Functions calling `require` directly are no longer considered for runtime inlining because that can change require path resolution ### Native Code Generation * Runtime recompilation now gathers information on tags and userdata types to specialize the code in arithmetic, field access and namecalls * Inlining of memory operands into instructions on x64 is now performed only if there are no conflicting writes ### Classes (experimental) Ongoing work on [Classes RFC](https://github.com/luau-lang/rfcs/pull/242) prototype: * Fixed a crash when class was extending a different class with the same name, it now correctly refers to the outer class instead of the one being defined * An error is now reported when a class inherits a constructor instead of defining its own (required flags: DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true) Co-authored-by: Annie Tang Co-authored-by: Hunter Goldstein Co-authored-by: Ilya Rezvov Co-authored-by: Sora Kanosue Co-authored-by: Vyacheslav Egorov --- .github/workflows/build.yml | 2 +- Analysis/include/Luau/ConstraintGraph.h | 18 +- Analysis/include/Luau/ConstraintSolver.h | 8 - Analysis/include/Luau/Error.h | 9 + Analysis/include/Luau/TypeUtils.h | 2 + Analysis/src/AstJsonEncoder.cpp | 4 +- Analysis/src/AutocompleteCore.cpp | 42 +- Analysis/src/ConstraintGenerator.cpp | 46 +- Analysis/src/ConstraintGraph.cpp | 428 ++++++++++---- Analysis/src/ConstraintSolver.cpp | 265 ++++----- Analysis/src/DataFlowGraph.cpp | 6 +- Analysis/src/Error.cpp | 13 + Analysis/src/FragmentAutocomplete.cpp | 4 +- Analysis/src/IostreamHelpers.cpp | 2 + Analysis/src/NonStrictTypeChecker.cpp | 35 +- Analysis/src/TypeChecker2.cpp | 27 +- Analysis/src/TypeInfer.cpp | 8 +- Analysis/src/TypeUtils.cpp | 11 + Ast/src/Ast.cpp | 4 +- Ast/src/Parser.cpp | 20 +- Ast/src/PrettyPrinter.cpp | 4 +- CodeGen/include/Luau/AssemblyBuilderX64.h | 1 + CodeGen/include/Luau/CodeGenOptions.h | 3 + CodeGen/include/Luau/IrBuilder.h | 2 + CodeGen/include/Luau/IrData.h | 61 ++ CodeGen/include/Luau/IrDump.h | 1 + CodeGen/include/Luau/IrUtils.h | 6 + CodeGen/include/Luau/IrVisitUseDef.h | 37 ++ CodeGen/src/AssemblyBuilderX64.cpp | 15 + CodeGen/src/CodeGenContext.cpp | 320 ++++++++++- CodeGen/src/CodeGenContext.h | 22 + CodeGen/src/CodeGenLower.h | 4 +- CodeGen/src/IrBuilder.cpp | 28 + CodeGen/src/IrDump.cpp | 48 +- CodeGen/src/IrLoweringA64.cpp | 96 ++++ CodeGen/src/IrLoweringX64.cpp | 85 +++ CodeGen/src/IrTranslation.cpp | 537 ++++++++++++++++-- CodeGen/src/IrUtils.cpp | 86 +++ CodeGen/src/OptimizeConstProp.cpp | 2 + CodeGen/src/OptimizeFinalX64.cpp | 151 ++++- Compiler/src/Compiler.cpp | 17 +- Compiler/src/CostModel.cpp | 4 +- Compiler/src/Types.cpp | 8 +- Makefile | 4 +- VM/src/lapi.cpp | 15 + VM/src/lclass.cpp | 7 +- VM/src/lfunc.cpp | 76 +++ VM/src/lfunc.h | 1 + VM/src/lgc.cpp | 4 + VM/src/lstate.cpp | 2 + VM/src/lstate.h | 4 + VM/src/lstring.cpp | 167 +++++- VM/src/lstring.h | 1 + VM/src/ludata.cpp | 1 + VM/src/lvmload.cpp | 37 +- bench/gc/test_LB_mandel_classes.luau | 81 +++ ...ructor.lua => test_MT_OOP_constructor.lua} | 3 +- ...ccess.lua => test_MT_OOP_field_access.lua} | 3 +- ...ua => test_MT_OOP_field_access_random.lua} | 2 +- ...cess.lua => test_MT_OOP_method_access.lua} | 2 +- ...d_call.lua => test_MT_OOP_method_call.lua} | 2 +- ...ua => test_MT_OOP_virtual_constructor.lua} | 4 +- .../micro_tests/test_MethodCalls_classes.luau | 82 +++ ....lua => test_OOP_constructor_classes.luau} | 8 +- ... test_OOP_constructor_classes_direct.luau} | 8 +- .../test_OOP_constructor_inherited.luau | 30 + ...test_OOP_constructor_inherited_direct.luau | 23 + .../test_OOP_constructor_private.luau | 22 + ...lua => test_OOP_field_access_classes.luau} | 8 +- .../test_OOP_field_access_inherited.luau | 24 + .../test_OOP_field_access_private.luau | 29 + ....lua => test_OOP_field_access_random.luau} | 4 +- ...lasses.lua => test_OOP_method_access.luau} | 4 +- ...ll_class.lua => test_OOP_method_call.luau} | 4 +- .../test_OOP_method_call_inherited.luau | 27 + .../test_OOP_method_call_private.luau | 29 + .../{chess-classes.lua => chess-classes.luau} | 294 +++++----- bench/tests/sunspider/n-body-oop-classes.lua | 2 +- bench/tests/tictactoe-classes.luau | 197 +++++++ fuzz/luau.proto | 2 + fuzz/protoprint.cpp | 6 + tests/AssemblyBuilderX64.test.cpp | 5 + tests/AstJsonEncoder.test.cpp | 10 +- tests/AstVisitor.test.cpp | 6 +- tests/Autocomplete.test.cpp | 125 +++- tests/Compiler.test.cpp | 8 +- tests/Conformance.test.cpp | 296 +++++++++- tests/CostModel.test.cpp | 6 +- tests/FeedbackVector.test.cpp | 21 + tests/FragmentAutocomplete.test.cpp | 98 +++- tests/IrBuilder.test.cpp | 52 ++ tests/IrLowering.test.cpp | 65 +++ tests/Parser.test.cpp | 52 +- tests/PrettyPrinter.test.cpp | 14 +- tests/TypeFunction.user.test.cpp | 28 - tests/TypeInfer.classes.test.cpp | 11 + tests/TypeInfer.provisional.test.cpp | 2 - tests/TypeInfer.refinements.test.cpp | 48 +- tests/TypeInfer.tables.test.cpp | 16 +- tests/conformance/gc.luau | 27 + tests/conformance/promotion.luau | 280 +++++++++ ...ncestor_has_one.flags-off.nonstrict.output | 0 ..._ancestor_has_one.flags-off.runtime.output | 0 ...o_ancestor_has_one.flags-off.strict.output | 0 ...ancestor_has_one.flags-on.nonstrict.output | 0 ...o_ancestor_has_one.flags-on.runtime.output | 0 ...no_ancestor_has_one.flags-on.strict.output | 0 ...r_is_allowed_when_no_ancestor_has_one.luau | 23 + ...one_is_an_error.flags-off.nonstrict.output | 3 + ...s_one_is_an_error.flags-off.runtime.output | 0 ...es_one_is_an_error.flags-off.strict.output | 3 + ..._one_is_an_error.flags-on.nonstrict.output | 3 + ...es_one_is_an_error.flags-on.runtime.output | 0 ...nes_one_is_an_error.flags-on.strict.output | 3 + ...when_ancestor_defines_one_is_an_error.luau | 18 + ...ines_one_errors.flags-off.nonstrict.output | 1 + ...efines_one_errors.flags-off.runtime.output | 0 ...defines_one_errors.flags-off.strict.output | 1 + ...fines_one_errors.flags-on.nonstrict.output | 1 + ...defines_one_errors.flags-on.runtime.output | 0 ..._defines_one_errors.flags-on.strict.output | 1 + ...or_when_superclass_defines_one_errors.luau | 13 + ...lly_inherits_sqrt.flags-off.runtime.output | 2 +- ...ally_inherits_sqrt.flags-off.strict.output | 2 +- ...ally_inherits_sqrt.flags-on.runtime.output | 2 +- ...cally_inherits_sqrt.flags-on.strict.output | 2 +- ...med_comparisons.flags-off.nonstrict.output | 0 ...ormed_comparisons.flags-off.runtime.output | 0 ...formed_comparisons.flags-off.strict.output | 3 + ...rmed_comparisons.flags-on.nonstrict.output | 0 ...formed_comparisons.flags-on.runtime.output | 0 ...lformed_comparisons.flags-on.strict.output | 3 + .../refinements/malformed_comparisons.luau | 9 + ...optional_source.flags-off.nonstrict.output | 3 + ...ts_optional_source.flags-off.strict.output | 5 +- ...cts_optional_source.flags-on.strict.output | 2 +- ...al_annotation_rejects_optional_source.luau | 2 - ...basic_typecheck.flags-off.nonstrict.output | 2 + ...al_basic_typecheck.flags-off.strict.output | 3 + .../while_local_basic_typecheck.luau | 2 - ...ble_after_block.flags-off.nonstrict.output | 4 +- ...isible_after_block.flags-off.strict.output | 5 +- ...ible_after_block.flags-on.nonstrict.output | 4 +- ...visible_after_block.flags-on.strict.output | 4 +- ...local_binding_not_visible_after_block.luau | 2 - ...rrows_to_truthy.flags-off.nonstrict.output | 2 + ..._narrows_to_truthy.flags-off.strict.output | 4 + .../while_local_narrows_to_truthy.luau | 2 - ..._annotated_type.flags-off.nonstrict.output | 2 + ...nes_annotated_type.flags-off.strict.output | 4 + .../while_local_refines_annotated_type.luau | 2 - ...tation_mismatch.flags-off.nonstrict.output | 3 + ...nnotation_mismatch.flags-off.strict.output | 7 +- ...annotation_mismatch.flags-on.strict.output | 4 +- ...while_local_table_annotation_mismatch.luau | 2 - ...tion_avoids_nil.flags-off.nonstrict.output | 0 ...iation_avoids_nil.flags-off.runtime.output | 0 ...tiation_avoids_nil.flags-off.strict.output | 5 + ...ation_avoids_nil.flags-on.nonstrict.output | 0 ...tiation_avoids_nil.flags-on.runtime.output | 0 ...ntiation_avoids_nil.flags-on.strict.output | 0 ...2644_generic_instantiation_avoids_nil.luau | 11 + ...ssign_to_global.flags-off.nonstrict.output | 0 ..._assign_to_global.flags-off.runtime.output | 3 + ...l_assign_to_global.flags-off.strict.output | 9 + ...assign_to_global.flags-on.nonstrict.output | 0 ...l_assign_to_global.flags-on.runtime.output | 3 + ...al_assign_to_global.flags-on.strict.output | 9 + .../type-states/global_assign_to_global.luau | 15 + ...l_reassign_func.flags-off.nonstrict.output | 2 + ...bal_reassign_func.flags-off.runtime.output | 0 ...obal_reassign_func.flags-off.strict.output | 10 + ...al_reassign_func.flags-on.nonstrict.output | 2 + ...obal_reassign_func.flags-on.runtime.output | 0 ...lobal_reassign_func.flags-on.strict.output | 10 + .../type-states/global_reassign_func.luau | 11 + ...bal_self_assign.flags-off.nonstrict.output | 0 ...lobal_self_assign.flags-off.runtime.output | 0 ...global_self_assign.flags-off.strict.output | 3 + ...obal_self_assign.flags-on.nonstrict.output | 0 ...global_self_assign.flags-on.runtime.output | 0 .../global_self_assign.flags-on.strict.output | 3 + .../type-states/global_self_assign.luau | 2 + ...ls_in_type_funs.flags-off.nonstrict.output | 2 + ...bals_in_type_funs.flags-off.runtime.output | 1 + ...obals_in_type_funs.flags-off.strict.output | 4 + ...als_in_type_funs.flags-on.nonstrict.output | 2 + ...obals_in_type_funs.flags-on.runtime.output | 1 + ...lobals_in_type_funs.flags-on.strict.output | 4 + .../no_globals_in_type_funs.luau | 12 + ...no_shared_state.flags-off.nonstrict.output | 1 + ...f_no_shared_state.flags-off.runtime.output | 0 ...tf_no_shared_state.flags-off.strict.output | 6 + ..._no_shared_state.flags-on.nonstrict.output | 1 + ...tf_no_shared_state.flags-on.runtime.output | 0 ...dtf_no_shared_state.flags-on.strict.output | 10 + .../udtf_no_shared_state.luau | 21 + ..._missing_equals.flags-off.nonstrict.output | 4 +- ...or_missing_equals.flags-off.runtime.output | 2 +- ...ror_missing_equals.flags-off.strict.output | 4 +- ...r_missing_equals.flags-on.nonstrict.output | 2 +- ...ror_missing_equals.flags-on.runtime.output | 2 +- ...rror_missing_equals.flags-on.strict.output | 2 +- .../while-local/error_missing_equals.luau | 2 - ...ltiple_bindings.flags-off.nonstrict.output | 9 +- ...multiple_bindings.flags-off.runtime.output | 2 +- ..._multiple_bindings.flags-off.strict.output | 9 +- ...ultiple_bindings.flags-on.nonstrict.output | 8 +- ..._multiple_bindings.flags-on.runtime.output | 2 +- ...r_multiple_bindings.flags-on.strict.output | 8 +- .../while-local/error_multiple_bindings.luau | 2 - 211 files changed, 4425 insertions(+), 840 deletions(-) create mode 100644 bench/gc/test_LB_mandel_classes.luau rename bench/micro_tests/{test_OOP_constructor.lua => test_MT_OOP_constructor.lua} (93%) rename bench/micro_tests/{test_OOP_field_access.lua => test_MT_OOP_field_access.lua} (93%) rename bench/micro_tests/{test_OOP_field_access_random.lua => test_MT_OOP_field_access_random.lua} (95%) rename bench/micro_tests/{test_OOP_method_access.lua => test_MT_OOP_method_access.lua} (93%) rename bench/micro_tests/{test_OOP_method_call.lua => test_MT_OOP_method_call.lua} (94%) rename bench/micro_tests/{test_OOP_virtual_constructor.lua => test_MT_OOP_virtual_constructor.lua} (86%) create mode 100644 bench/micro_tests/test_MethodCalls_classes.luau rename bench/micro_tests/{test_OOP_constructor_classes.lua => test_OOP_constructor_classes.luau} (75%) rename bench/micro_tests/{test_OOP_constructor_classes_direct.lua => test_OOP_constructor_classes_direct.luau} (74%) create mode 100644 bench/micro_tests/test_OOP_constructor_inherited.luau create mode 100644 bench/micro_tests/test_OOP_constructor_inherited_direct.luau create mode 100644 bench/micro_tests/test_OOP_constructor_private.luau rename bench/micro_tests/{test_OOP_field_access_classes.lua => test_OOP_field_access_classes.luau} (75%) create mode 100644 bench/micro_tests/test_OOP_field_access_inherited.luau create mode 100644 bench/micro_tests/test_OOP_field_access_private.luau rename bench/micro_tests/{test_OOP_field_access_random_classes.lua => test_OOP_field_access_random.luau} (87%) rename bench/micro_tests/{test_OOP_method_access_classes.lua => test_OOP_method_access.luau} (83%) rename bench/micro_tests/{test_OOP_method_call_class.lua => test_OOP_method_call.luau} (83%) create mode 100644 bench/micro_tests/test_OOP_method_call_inherited.luau create mode 100644 bench/micro_tests/test_OOP_method_call_private.luau rename bench/tests/{chess-classes.lua => chess-classes.luau} (67%) create mode 100644 bench/tests/tictactoe-classes.luau create mode 100644 tests/conformance/promotion.luau create mode 100644 tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.luau create mode 100644 tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau create mode 100644 tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.luau create mode 100644 tests/golden/analysis/refinements/malformed_comparisons.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/refinements/malformed_comparisons.flags-off.runtime.output create mode 100644 tests/golden/analysis/refinements/malformed_comparisons.flags-off.strict.output create mode 100644 tests/golden/analysis/refinements/malformed_comparisons.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/refinements/malformed_comparisons.flags-on.runtime.output create mode 100644 tests/golden/analysis/refinements/malformed_comparisons.flags-on.strict.output create mode 100644 tests/golden/analysis/refinements/malformed_comparisons.luau create mode 100644 tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.runtime.output create mode 100644 tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.strict.output create mode 100644 tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-on.runtime.output create mode 100644 tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-on.strict.output create mode 100644 tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.luau create mode 100644 tests/golden/analysis/type-states/global_assign_to_global.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/type-states/global_assign_to_global.flags-off.runtime.output create mode 100644 tests/golden/analysis/type-states/global_assign_to_global.flags-off.strict.output create mode 100644 tests/golden/analysis/type-states/global_assign_to_global.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/type-states/global_assign_to_global.flags-on.runtime.output create mode 100644 tests/golden/analysis/type-states/global_assign_to_global.flags-on.strict.output create mode 100644 tests/golden/analysis/type-states/global_assign_to_global.luau create mode 100644 tests/golden/analysis/type-states/global_reassign_func.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/type-states/global_reassign_func.flags-off.runtime.output create mode 100644 tests/golden/analysis/type-states/global_reassign_func.flags-off.strict.output create mode 100644 tests/golden/analysis/type-states/global_reassign_func.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/type-states/global_reassign_func.flags-on.runtime.output create mode 100644 tests/golden/analysis/type-states/global_reassign_func.flags-on.strict.output create mode 100644 tests/golden/analysis/type-states/global_reassign_func.luau create mode 100644 tests/golden/analysis/type-states/global_self_assign.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/type-states/global_self_assign.flags-off.runtime.output create mode 100644 tests/golden/analysis/type-states/global_self_assign.flags-off.strict.output create mode 100644 tests/golden/analysis/type-states/global_self_assign.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/type-states/global_self_assign.flags-on.runtime.output create mode 100644 tests/golden/analysis/type-states/global_self_assign.flags-on.strict.output create mode 100644 tests/golden/analysis/type-states/global_self_assign.luau create mode 100644 tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.runtime.output create mode 100644 tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.strict.output create mode 100644 tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.runtime.output create mode 100644 tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.strict.output create mode 100644 tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.luau create mode 100644 tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.runtime.output create mode 100644 tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.strict.output create mode 100644 tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.runtime.output create mode 100644 tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.strict.output create mode 100644 tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.luau diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b90cadff2..1f3a17b53 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -20,7 +20,7 @@ jobs: unix: strategy: matrix: - os: [{name: ubuntu, version: ubuntu-latest}, {name: macos, version: macos-latest}, {name: macos-arm, version: macos-14}] + os: [{name: ubuntu, version: ubuntu-latest}, {name: macos, version: macos-latest}, {name: macos-arm, version: macos-15}] compiler: - name: Clang cc: clang diff --git a/Analysis/include/Luau/ConstraintGraph.h b/Analysis/include/Luau/ConstraintGraph.h index 589799a32..fcf0dfb1c 100644 --- a/Analysis/include/Luau/ConstraintGraph.h +++ b/Analysis/include/Luau/ConstraintGraph.h @@ -63,8 +63,14 @@ struct ConstraintList Iterator end(); private: - DenseHashMap present; - std::vector order; + // Clip with LuauTraverseScopeToFunction + DenseHashMap present_DEPRECATED; + // Clip with LuauTraverseScopeToFunction + std::vector order_DEPRECATED; + + DenseHashMap indices; + std::vector> order; + size_t entries = 0; }; @@ -237,16 +243,16 @@ struct ConstraintGraph * - Any constraint with no dependencies can be dispatched. */ ConstraintMap dependencies; - - - NotNull findDependencyList(ConstraintVertex vertex); + ConstraintList* findDependencyList(ConstraintVertex vertex); + NotNull findOrMakeDependencyList(ConstraintVertex vertex); /** * Inverse of the above mapping. Yes, the proper name for this is * "dependents," but naming it such will result in hellish typos. */ ConstraintMap reverseDependencies; - NotNull findReverseDependencyList(ConstraintVertex vertex); + ConstraintList* findReverseDependencyList(ConstraintVertex vertex); + NotNull findOrMakeReverseDependencyList(ConstraintVertex vertex); /** * We do the same pseudo-arena trick as constraints do right now. diff --git a/Analysis/include/Luau/ConstraintSolver.h b/Analysis/include/Luau/ConstraintSolver.h index b059a320b..5dbb36f0c 100644 --- a/Analysis/include/Luau/ConstraintSolver.h +++ b/Analysis/include/Luau/ConstraintSolver.h @@ -201,14 +201,6 @@ struct ConstraintSolver void generalizeOneType(TypeId ty); - // Clip with LuauRemoveConstraintSolverEmplace - template - void DEPRECATED_emplace(NotNull constraint, TypeId ty, Args&&... args); - - // Clip with LuauRemoveConstraintSolverEmplace - template - void DEPRECATED_emplace(NotNull constraint, TypePackId tp, Args&&... args); - std::optional> lookupTablePropHelper( NotNull constraint, TypeId subjectType, diff --git a/Analysis/include/Luau/Error.h b/Analysis/include/Luau/Error.h index 381fc9943..383131503 100644 --- a/Analysis/include/Luau/Error.h +++ b/Analysis/include/Luau/Error.h @@ -667,6 +667,14 @@ struct IllegalClassPropertyOverride bool operator==(const IllegalClassPropertyOverride& rhs) const; }; +struct MissingConstructor +{ + Name className; + Name superName; + + bool operator==(const MissingConstructor& rhs) const; +}; + struct NotIterable { TypeId ty; @@ -745,6 +753,7 @@ using TypeErrorData = Variant< InvalidClassExtension, IncompatibleClassMethodOverride, IllegalClassPropertyOverride, + MissingConstructor, NotIterable>; struct TypeErrorSummary diff --git a/Analysis/include/Luau/TypeUtils.h b/Analysis/include/Luau/TypeUtils.h index 44f987338..530ecae3f 100644 --- a/Analysis/include/Luau/TypeUtils.h +++ b/Analysis/include/Luau/TypeUtils.h @@ -406,4 +406,6 @@ bool isBlocked(TypeId ty); */ std::optional getApproximateReturnTypeForFunctionCall(TypeId ty); +std::optional propInInheritanceChain(const ExternType* cls, const std::string& prop); + } // namespace Luau diff --git a/Analysis/src/AstJsonEncoder.cpp b/Analysis/src/AstJsonEncoder.cpp index 872031353..70497bac1 100644 --- a/Analysis/src/AstJsonEncoder.cpp +++ b/Analysis/src/AstJsonEncoder.cpp @@ -9,7 +9,7 @@ #include LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) -LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) namespace Luau { @@ -764,7 +764,7 @@ struct AstJsonEncoder : public AstVisitor PROP(condition); PROP(body); PROP(hasDo); - if (FFlag::DebugLuauWhileLocalAnalysis && node->conditionLocal) + if (FFlag::LuauExperimentalWhileLocalAnalysis && node->conditionLocal) { write("conditionLocal", node->conditionLocal); } diff --git a/Analysis/src/AutocompleteCore.cpp b/Analysis/src/AutocompleteCore.cpp index 0b0675968..9c127bfd0 100644 --- a/Analysis/src/AutocompleteCore.cpp +++ b/Analysis/src/AutocompleteCore.cpp @@ -31,7 +31,7 @@ LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAGVARIABLE(LuauUseExplicitTypeArgsInGenerics) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauRefactorAutocompleteAncestry) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) static constexpr std::array kStatementStartingKeywords = {"while", "if", "local", "repeat", "function", "do", "for", "return", "break", "continue", "type", "export", "const"}; @@ -1660,6 +1660,38 @@ static bool autocompleteIfElseExpression( } } +// True when the cursor could start an `if local`/`while local` binding: the condition is empty or a single name. +static bool canStartConditionBinding(const AstNode* node, const std::vector& ancestry, Position position) +{ + LUAU_ASSERT(FFlag::LuauExperimentalWhileLocalSyntax && FFlag::LuauExperimentalIfLocalSyntax); + + if (ancestry.size() < 2) + return false; + + const AstNode* parent = ancestry.rbegin()[1]; + const AstExpr* condition = nullptr; + bool missingBodyKeyword = false; + if (const AstStatWhile* statWhile = parent->as(); statWhile && !statWhile->conditionLocal) + { + condition = statWhile->condition; + missingBodyKeyword = !statWhile->hasDo; + } + else if (const AstStatIf* statIf = parent->as(); statIf && !statIf->conditionLocal) + { + condition = statIf->condition; + missingBodyKeyword = !statIf->thenLocation; + } + + if (!condition) + return false; + + // An empty condition parses as an error expression past the cursor, so the ancestry ends at the body block. + if (node->is()) + return missingBodyKeyword && condition->is() && position <= condition->location.end; + + return condition->location == node->location && (node->is() || node->is() || node->is()); +} + static AutocompleteContext autocompleteExpression( const Module& module, NotNull builtinTypes, @@ -1757,6 +1789,12 @@ static AutocompleteContext autocompleteExpression( result["not"] = {AutocompleteEntryKind::Keyword}; result["function"] = {AutocompleteEntryKind::Keyword, std::nullopt, false, false, correctForFunction}; + if (FFlag::LuauExperimentalWhileLocalSyntax && FFlag::LuauExperimentalIfLocalSyntax && canStartConditionBinding(node, ancestry, position)) + { + result["local"] = {AutocompleteEntryKind::Keyword}; + result["const"] = {AutocompleteEntryKind::Keyword}; + } + if (auto ty = findExpectedTypeAt(module, node, position)) autocompleteStringSingleton(*ty, true, node, position, result); } @@ -2299,7 +2337,7 @@ AutocompleteResult autocomplete_( return autocompleteExpression(*module, builtinTypes, typeArena, ancestry, scopeAtPosition, position); } else if (AstStatWhile* statWhile = node->as(); - FFlag::DebugLuauWhileLocalSyntax && statWhile && statWhile->conditionLocal && statWhile->conditionEqualsLocation && + FFlag::LuauExperimentalWhileLocalSyntax && statWhile && statWhile->conditionLocal && statWhile->conditionEqualsLocation && position >= statWhile->conditionEqualsLocation->end && (!statWhile->hasDo || position < statWhile->doLocation.begin)) { return autocompleteExpression(*module, builtinTypes, typeArena, ancestry, scopeAtPosition, position); diff --git a/Analysis/src/ConstraintGenerator.cpp b/Analysis/src/ConstraintGenerator.cpp index dce172f87..70609497b 100644 --- a/Analysis/src/ConstraintGenerator.cpp +++ b/Analysis/src/ConstraintGenerator.cpp @@ -51,7 +51,9 @@ LUAU_FASTFLAGVARIABLE(LuauExperimentalIfLocalAnalysis) LUAU_FLAGVERSION(LuauExperimentalIfLocalAnalysis, 2) LUAU_FASTFLAG(LuauTraverseScopeToFunction) LUAU_FASTFLAGVARIABLE(LuauUnconditionallyVisitTypeAliasParams) -LUAU_FASTFLAGVARIABLE(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAGVARIABLE(LuauBanGlobalsInTypeFunctions) +LUAU_FASTFLAGVARIABLE(LuauFillInUninitializedGlobals) +LUAU_FASTFLAGVARIABLE(LuauExperimentalWhileLocalAnalysis) namespace Luau { @@ -456,8 +458,27 @@ void ConstraintGenerator::visitModuleRoot(AstStatBlock* block) asMutable(ty)->ty.emplace(domainTy); } } + for (TypeId ty : unionsToSimplify) addConstraint(scope, block->location, SimplifyConstraint{ty}); + + if (FFlag::LuauFillInUninitializedGlobals) + { + // It's ok for us to iterate over a hash set here: the order in which + // we initialize globals like this does not really matter. + for (auto name : uninitializedGlobals) + { + if (auto binding = scope->lookup(name)) + { + if (auto bt = get(*binding); bt && bt->getOwner() == nullptr) + emplaceType(asMutable(*binding), builtinTypes->errorType); + else + LUAU_ASSERT(!"Unexpected non-blocked type or owned blocked type."); + } + else + LUAU_ASSERT(!"Global was stated to be uninitialized but has no binding."); + } + } } void ConstraintGenerator::visitFragmentRoot(const ScopePtr& resumeScope, AstStatBlock* block) @@ -1780,7 +1801,7 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatWhile* whil return ControlFlow::None; } - const bool isWhileLocal = FFlag::DebugLuauWhileLocalAnalysis && (while_->conditionLocal != nullptr); + const bool isWhileLocal = FFlag::LuauExperimentalWhileLocalAnalysis && (while_->conditionLocal != nullptr); ScopePtr whileScope = isWhileLocal ? childScope(while_->body, scope) : childScope(while_, scope); if (isWhileLocal) @@ -5367,6 +5388,14 @@ struct GlobalPrepopulator : AstVisitor { return true; } + + bool visit(AstStatTypeFunction* node) override + { + // Type functions do not participate in global inference: + // - They receive fresh environments that are frozen, so users can't set globals; + // - They cannot access upvalues nor globals from the current file. + return !FFlag::LuauBanGlobalsInTypeFunctions; + } }; void ConstraintGenerator::prepopulateGlobalScopeForFragmentTypecheck(const ScopePtr& globalScope, const ScopePtr& resumeScope, AstStatBlock* program) @@ -5391,12 +5420,15 @@ void ConstraintGenerator::prepopulateGlobalScope(const ScopePtr& globalScope, As for (auto name : gp.uninitializedGlobals) uninitializedGlobals.insert(name); - // Handle type function globals as well, without preparing a module scope since they have a separate environment - GlobalPrepopulator tfgp{NotNull{typeFunctionRuntime->rootScope.get()}, arena, dfg}; - program->visit(&tfgp); + if (!FFlag::LuauBanGlobalsInTypeFunctions) + { + // Handle type function globals as well, without preparing a module scope since they have a separate environment + GlobalPrepopulator tfgp{NotNull{typeFunctionRuntime->rootScope.get()}, arena, dfg}; + program->visit(&tfgp); - for (auto name : tfgp.uninitializedGlobals) - uninitializedGlobals.insert(name); + for (auto name : tfgp.uninitializedGlobals) + uninitializedGlobals.insert(name); + } } bool ConstraintGenerator::recordPropertyAssignment(TypeId ty) diff --git a/Analysis/src/ConstraintGraph.cpp b/Analysis/src/ConstraintGraph.cpp index 1af987c06..5467de59d 100644 --- a/Analysis/src/ConstraintGraph.cpp +++ b/Analysis/src/ConstraintGraph.cpp @@ -67,10 +67,21 @@ ConstraintList::Iterator::Iterator(NotNull cl, size_t index) ConstraintList::Iterator& ConstraintList::Iterator::operator++() { - if (index < cl->order.size()) + if (FFlag::LuauTraverseScopeToFunction) { - index++; - advanceUntilPresentOrEnd(); + if (index < cl->order.size()) + { + index++; + advanceUntilPresentOrEnd(); + } + } + else + { + if (index < cl->order_DEPRECATED.size()) + { + index++; + advanceUntilPresentOrEnd(); + } } return *this; } @@ -87,13 +98,25 @@ bool ConstraintList::Iterator::operator!=(const Iterator& rhs) const ConstraintList::Iterator::value_type ConstraintList::Iterator::operator*() { - return cl->order[index]; + if (FFlag::LuauTraverseScopeToFunction) + return cl->order[index].first; + + return cl->order_DEPRECATED[index]; } void ConstraintList::Iterator::advanceUntilPresentOrEnd() { - while (index < cl->order.size() && !cl->contains(cl->order[index])) - index++; + if (FFlag::LuauTraverseScopeToFunction) + { + while (index < cl->order.size() && !cl->order[index].second) + index++; + } + else + { + + while (index < cl->order_DEPRECATED.size() && !cl->contains(cl->order_DEPRECATED[index])) + index++; + } return; } @@ -104,37 +127,88 @@ ConstraintGraph::ConstraintGraph(NotNull builtinTypes) bool ConstraintList::contains(ConstraintVertex vertex) const { - if (auto entry = present.find(vertex)) - return *entry; - return false; + if (FFlag::LuauTraverseScopeToFunction) + { + if (auto idx = indices.find(vertex)) + return order[*idx].second; + return false; + } + else + { + + if (auto entry = present_DEPRECATED.find(vertex)) + return *entry; + return false; + } } void ConstraintList::insert(ConstraintVertex vertex) { - auto [entry, fresh] = present.try_insert(vertex, true); - if (fresh) + if (FFlag::LuauTraverseScopeToFunction) { - order.emplace_back(vertex); - entries++; + auto [index, fresh] = indices.try_insert(vertex, order.size()); + if (fresh) + { + // If this insert is fresh, then we've seen this vertex for the first + // time, and need to make a new entry for it. + order.emplace_back(vertex, true); + entries++; + return; + } + + // Otherwise, if the insert is *not* fresh, check to see if we're + // adding a vertex we previously removed. If so, set the entry to + // true and increment the number of entries. + auto& entry = order[index]; + if (!entry.second) + { + entry.second = true; + entries++; + } } - else if (!entry) + else { - entry = true; - entries++; + auto [entry, fresh] = present_DEPRECATED.try_insert(vertex, true); + if (fresh) + { + order_DEPRECATED.emplace_back(vertex); + entries++; + } + else if (!entry) + { + entry = true; + entries++; + } + // If the entry was *not* fresh and its value was already true, then do + // nothing: the set state has not changed. } - // If the entry was *not* fresh and its value was already true, then do - // nothing: the set state has not changed. } void ConstraintList::remove(ConstraintVertex vertex) { - if (auto entry = present.find(vertex)) + if (FFlag::LuauTraverseScopeToFunction) + { + if (auto index = indices.find(vertex)) + { + // If the entry's second value is true, then we also need to + // decrement the number of entries in the constraint list. + if (auto& entry = order[*index]; entry.second) + { + entries--; + entry.second = false; + } + } + } + else { - // If the entry is true then we also need to decrement the number of - // entries in the constraint list. - if (*entry) - entries--; - *entry = false; + if (auto entry = present_DEPRECATED.find(vertex)) + { + // If the entry is true then we also need to decrement the number of + // entries in the constraint list. + if (*entry) + entries--; + *entry = false; + } } } @@ -145,8 +219,16 @@ size_t ConstraintList::size() const void ConstraintList::clear() { - order.clear(); - present.clear(); + if (FFlag::LuauTraverseScopeToFunction) + { + indices.clear(); + order.clear(); + } + else + { + order_DEPRECATED.clear(); + present_DEPRECATED.clear(); + } entries = 0; } @@ -157,13 +239,16 @@ ConstraintList::Iterator ConstraintList::begin() ConstraintList::Iterator ConstraintList::end() { - return Iterator{NotNull{this}, order.size()}; + if (FFlag::LuauTraverseScopeToFunction) + return Iterator{NotNull{this}, order.size()}; + else + return Iterator{NotNull{this}, order_DEPRECATED.size()}; } bool ConstraintGraph::addDependencyOf(ConstraintVertex dependency, ConstraintVertex target) { - auto deps = findDependencyList(target); - auto reverseDeps = findReverseDependencyList(dependency); + auto deps = findOrMakeDependencyList(target); + auto reverseDeps = findOrMakeReverseDependencyList(dependency); if (deps->contains(dependency)) { @@ -195,8 +280,8 @@ bool ConstraintGraph::addDependencyOf(Constraint* dependency, Constraint* target */ void ConstraintGraph::inheritBlocks(ConstraintVertex existingVertex, ConstraintVertex newVertex) { - auto existingReverseDeps = findReverseDependencyList(existingVertex); - auto newReverseDeps = findReverseDependencyList(newVertex); + auto existingReverseDeps = findOrMakeReverseDependencyList(existingVertex); + auto newReverseDeps = findOrMakeReverseDependencyList(newVertex); // For each reverse dependency of [existingVertex] ... for (auto existingRdep : *existingReverseDeps) @@ -204,7 +289,7 @@ void ConstraintGraph::inheritBlocks(ConstraintVertex existingVertex, ConstraintV // ... add it as a reverse dependency of [newVertex] newReverseDeps->insert(existingRdep); /// ... and add [newVertex] as a dependency. - auto newDeps = findDependencyList(existingRdep); + auto newDeps = findOrMakeDependencyList(existingRdep); newDeps->insert(newVertex); } } @@ -228,34 +313,71 @@ ConstraintGraph::UnblockedTypes ConstraintGraph::unblockConstraint(NotNull()) - { - result.types.insert(*ty); - auto deps = findDependencyList(*ty); - deps->remove(c.get()); - } - else if (auto tp = rdep.get_if()) + if (auto reverseDeps = findReverseDependencyList(c.get()); reverseDeps && reverseDeps->size() > 0) { - result.packs.insert(*tp); - auto deps = findDependencyList(*tp); - deps->remove(c.get()); - } - else if (auto depCons = rdep.get_if()) - { - auto deps = findDependencyList(*depCons); - deps->remove(c.get()); - if (FFlag::DebugLuauLogSolver) - printf("Unblocking count=%d\t%s\n", int(deps->size()), toString(**depCons, {/* exhaustive */ true}).c_str()); + for (auto rdep : *reverseDeps) + { + if (auto ty = rdep.get_if()) + { + result.types.insert(*ty); + if (auto deps = findDependencyList(*ty)) + deps->remove(c.get()); + } + else if (auto tp = rdep.get_if()) + { + result.packs.insert(*tp); + if (auto deps = findDependencyList(*tp)) + deps->remove(c.get()); + } + else if (auto depCons = rdep.get_if()) + { + if (auto deps = findDependencyList(*depCons)) + { + deps->remove(c.get()); + if (FFlag::DebugLuauLogSolver) + printf("Unblocking count=%d\t%s\n", int(deps->size()), toString(**depCons, {/* exhaustive */ true}).c_str()); + } + } + else + { + LUAU_ASSERT(!"Unknown constraint graph vertex."); + } + } } - else + } + else + { + + auto reverseDeps = findOrMakeReverseDependencyList(c.get()); + for (auto rdep : *reverseDeps) { - LUAU_ASSERT(!"Unknown constraint graph vertex."); + if (auto ty = rdep.get_if()) + { + result.types.insert(*ty); + auto deps = findOrMakeDependencyList(*ty); + deps->remove(c.get()); + } + else if (auto tp = rdep.get_if()) + { + result.packs.insert(*tp); + auto deps = findOrMakeDependencyList(*tp); + deps->remove(c.get()); + } + else if (auto depCons = rdep.get_if()) + { + auto deps = findOrMakeDependencyList(*depCons); + deps->remove(c.get()); + if (FFlag::DebugLuauLogSolver) + printf("Unblocking count=%d\t%s\n", int(deps->size()), toString(**depCons, {/* exhaustive */ true}).c_str()); + } + else + { + LUAU_ASSERT(!"Unknown constraint graph vertex."); + } } } - /** * This whole song and dance is to repair the constraint graph after we * dispatch a constraint. @@ -297,10 +419,19 @@ ConstraintGraph::UnblockedTypes ConstraintGraph::unblockConstraint(NotNull(type)) + + if (auto sourceDependencies = findDependencyList(type); sourceDependencies && sourceDependencies->size() > 0) { - copyDependenciesOf(type, follow(ft->upperBound)); - copyDependenciesOf(type, follow(ft->lowerBound)); + if (auto ft = get(type)) + { + TypeIds mutatedTypes; + TypePackIds mutatedTypePacks; + ReferenceCountInitializer rci{NotNull{type->owningArena}, NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; + rci.run(ft->lowerBound); + rci.run(ft->upperBound); + // We do not want to _delete_ the original vertex, so we pass nullopt here. + copyDependenciesToReachableTypes(std::nullopt, NotNull{sourceDependencies}, std::move(mutatedTypes), std::move(mutatedTypePacks)); + } } } } @@ -313,8 +444,17 @@ ConstraintGraph::UnblockedTypes ConstraintGraph::unblockConstraint(NotNullsize() > 0; + if (FFlag::LuauTraverseScopeToFunction) + { + if (auto deps = findDependencyList(vertex)) + return deps->size() > 0; + return false; + } + else + { + auto deps = findOrMakeDependencyList(vertex); + return deps->size() > 0; + } } /** @@ -336,14 +476,14 @@ void ConstraintGraph::copyDependenciesToReachableTypes( // NOTE: Technically we could express this function solely in terms // of [addDependencyOf], but we save some cycles by fetching the // reverse dependency list once. - auto vertexReverseDeps = findReverseDependencyList(vertex); + auto vertexReverseDeps = findOrMakeReverseDependencyList(vertex); if (originalVertex) vertexReverseDeps->remove(*originalVertex); for (auto subTarget : mutatedTypes) { - auto tyDeps = findDependencyList(subTarget); + auto tyDeps = findOrMakeDependencyList(subTarget); // Add this vertex to the list of dependencies for this type. tyDeps->insert(vertex); // ... and then add the same backwards edge. @@ -352,7 +492,7 @@ void ConstraintGraph::copyDependenciesToReachableTypes( for (auto subPackTarget : mutatedTypePacks) { - auto tpDeps = findDependencyList(subPackTarget); + auto tpDeps = findOrMakeDependencyList(subPackTarget); // Add this vertex to the list of dependencies for this type. tpDeps->insert(vertex); // ... and then add the same backwards edge. @@ -365,19 +505,40 @@ void ConstraintGraph::clearReverseDependenciesOf(ConstraintVertex vertex) { LUAU_ASSERT(vertex.get_if() == nullptr); - auto revDeps = findReverseDependencyList(vertex); - - // For all of the reverse dependencies of vertex (vertices that depend on vertex) ... - for (auto rdep : *revDeps) + if (FFlag::LuauTraverseScopeToFunction) { - // Remove vertex from the list of dependencies. - // TODO CLI-205496: We should assert that deps contains `vertex` - auto deps = findDependencyList(rdep); - deps->remove(vertex); + if (auto revDeps = findReverseDependencyList(vertex)) + { + // For all of the reverse dependencies of vertex (vertices that depend on vertex) ... + for (auto rdep : *revDeps) + { + // Remove vertex from the list of dependencies. + // TODO CLI-205496: We should assert that deps contains `vertex` + if (auto deps = findDependencyList(rdep)) + deps->remove(vertex); + } + + // Then clear this set. + revDeps->clear(); + } } + else + { + + auto revDeps = findOrMakeReverseDependencyList(vertex); - // Then clear this set. - revDeps->clear(); + // For all of the reverse dependencies of vertex (vertices that depend on vertex) ... + for (auto rdep : *revDeps) + { + // Remove vertex from the list of dependencies. + // TODO CLI-205496: We should assert that deps contains `vertex` + auto deps = findOrMakeDependencyList(rdep); + deps->remove(vertex); + } + + // Then clear this set. + revDeps->clear(); + } } template @@ -387,33 +548,52 @@ void ConstraintGraph::shiftReferences(T source, T target) if (source == target) return; - auto sourceDependencies = findDependencyList(source); - - // With nothing to copy, the types reachable from the target are never used. - if (FFlag::LuauSkipUnusedTypeTraversals && sourceDependencies->size() == 0) + if (FFlag::LuauTraverseScopeToFunction) { + if (auto sourceDependencies = findDependencyList(source); sourceDependencies && sourceDependencies->size() > 0) + { + TypeIds mutatedTypes; + TypePackIds mutatedTypePacks; + ReferenceCountInitializer rci{NotNull{source->owningArena}, NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; + rci.run(target); + copyDependenciesToReachableTypes(source, NotNull{sourceDependencies}, std::move(mutatedTypes), std::move(mutatedTypePacks)); + } + // Types in the constraint graph are always dynamically discovered, so + // when we shift a reference over, we'll remove it from the dependencies + // of our reverse dependencies and then delete the edge from the graph. clearReverseDependenciesOf(source); - return; - } - - TypeIds mutatedTypes; - TypePackIds mutatedTypePacks; - if (FFlag::LuauReferenceCountInitializerIsIterative) - { - ReferenceCountInitializer rci{NotNull{source->owningArena}, NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; - rci.run(target); } else { - ReferenceCountInitializer_DEPRECATED rci{NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; - rci.traverse(target); - } - copyDependenciesToReachableTypes(source, sourceDependencies, std::move(mutatedTypes), std::move(mutatedTypePacks)); - // Types in the constraint graph are always dynamically discovered, so - // when we shift a reference over, we'll remove it from the dependencies - // of our reverse dependencies and then delete the edge from the graph. - clearReverseDependenciesOf(source); + auto sourceDependencies = findOrMakeDependencyList(source); + + // With nothing to copy, the types reachable from the target are never used. + if (FFlag::LuauSkipUnusedTypeTraversals && sourceDependencies->size() == 0) + { + clearReverseDependenciesOf(source); + return; + } + + TypeIds mutatedTypes; + TypePackIds mutatedTypePacks; + if (FFlag::LuauReferenceCountInitializerIsIterative) + { + ReferenceCountInitializer rci{NotNull{source->owningArena}, NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; + rci.run(target); + } + else + { + ReferenceCountInitializer_DEPRECATED rci{NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; + rci.traverse(target); + } + copyDependenciesToReachableTypes(source, sourceDependencies, std::move(mutatedTypes), std::move(mutatedTypePacks)); + + // Types in the constraint graph are always dynamically discovered, so + // when we shift a reference over, we'll remove it from the dependencies + // of our reverse dependencies and then delete the edge from the graph. + clearReverseDependenciesOf(source); + } } template void ConstraintGraph::shiftReferences(TypePackId source, TypePackId target); @@ -459,28 +639,54 @@ template void ConstraintGraph::copyDependenciesOf(T source, T target) { static_assert(std::is_same_v || std::is_same_v, "Copying dependencies can only be used with types or type packs."); - auto sourceDependencies = findDependencyList(source); - TypeIds mutatedTypes; - TypePackIds mutatedTypePacks; - if (FFlag::LuauReferenceCountInitializerIsIterative) + if (FFlag::LuauTraverseScopeToFunction) { - ReferenceCountInitializer rci{NotNull{source->owningArena}, NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; - rci.run(target); + if (auto sourceDependencies = findDependencyList(source); sourceDependencies && sourceDependencies->size() > 0) + { + TypeIds mutatedTypes; + TypePackIds mutatedTypePacks; + ReferenceCountInitializer rci{NotNull{source->owningArena}, NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; + rci.run(target); + // We do not want to _delete_ the original vertex, so we pass nullopt here. + copyDependenciesToReachableTypes(std::nullopt, NotNull{sourceDependencies}, std::move(mutatedTypes), std::move(mutatedTypePacks)); + } } else { - ReferenceCountInitializer_DEPRECATED rci{NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; - rci.traverse(target); + + auto sourceDependencies = findOrMakeDependencyList(source); + TypeIds mutatedTypes; + TypePackIds mutatedTypePacks; + + if (FFlag::LuauReferenceCountInitializerIsIterative) + { + ReferenceCountInitializer rci{NotNull{source->owningArena}, NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; + rci.run(target); + } + else + { + ReferenceCountInitializer_DEPRECATED rci{NotNull{&mutatedTypes}, NotNull{&mutatedTypePacks}}; + rci.traverse(target); + } + // We do not want to _delete_ the original vertex, so we pass nullopt here. + copyDependenciesToReachableTypes(std::nullopt, sourceDependencies, std::move(mutatedTypes), std::move(mutatedTypePacks)); } - // We do not want to _delete_ the original vertex, so we pass nullopt here. - copyDependenciesToReachableTypes(std::nullopt, sourceDependencies, std::move(mutatedTypes), std::move(mutatedTypePacks)); } template void ConstraintGraph::copyDependenciesOf(TypeId source, TypeId target); template void ConstraintGraph::copyDependenciesOf(TypePackId source, TypePackId target); -NotNull ConstraintGraph::findDependencyList(ConstraintVertex vertex) + +ConstraintList* ConstraintGraph::findDependencyList(ConstraintVertex vertex) +{ + if (auto dep = dependencies.find(vertex)) + return *dep; + + return nullptr; +} + +NotNull ConstraintGraph::findOrMakeDependencyList(ConstraintVertex vertex) { if (auto dep = dependencies.find(vertex)) return NotNull{*dep}; @@ -492,7 +698,15 @@ NotNull ConstraintGraph::findDependencyList(ConstraintVertex ver return NotNull{newlist}; } -NotNull ConstraintGraph::findReverseDependencyList(ConstraintVertex vertex) +ConstraintList* ConstraintGraph::findReverseDependencyList(ConstraintVertex vertex) +{ + if (auto rdep = reverseDependencies.find(vertex)) + return *rdep; + + return nullptr; +} + +NotNull ConstraintGraph::findOrMakeReverseDependencyList(ConstraintVertex vertex) { if (auto rdep = reverseDependencies.find(vertex)) return NotNull{*rdep}; @@ -593,7 +807,7 @@ void ConstraintGraph::dump() void ConstraintGraph::dumpBlocked(NotNull c, ToStringOptions& opts) { printf("Blocked on:\n"); - auto deps = findDependencyList(c.get()); + auto deps = findOrMakeDependencyList(c.get()); for (auto dep : *deps) { Luau::visit( @@ -622,7 +836,7 @@ void ConstraintGraph::dumpWith(const std::vector>& uns printf("constraints:\n"); for (NotNull c : unsolvedConstraints) { - auto deps = findDependencyList(c.get()); + auto deps = findOrMakeDependencyList(c.get()); printf("\t%zu\t%s\n", deps->size(), toString(*c, opts).c_str()); for (auto dep : *deps) diff --git a/Analysis/src/ConstraintSolver.cpp b/Analysis/src/ConstraintSolver.cpp index ca899ae8a..e22a58646 100644 --- a/Analysis/src/ConstraintSolver.cpp +++ b/Analysis/src/ConstraintSolver.cpp @@ -42,13 +42,14 @@ LUAU_FASTFLAGVARIABLE(DebugLuauAssertOnForcedConstraint) LUAU_FASTFLAGVARIABLE(DebugLuauLogSolver) LUAU_FASTFLAGVARIABLE(DebugLuauLogBindings) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) -LUAU_FASTFLAGVARIABLE(LuauRemoveConstraintSolverEmplace) LUAU_FASTFLAGVARIABLE(LuauForceLess) LUAU_FASTFLAG(LuauCyclicRequireTypeInference) LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAGVARIABLE(LuauTraverseScopeToFunction) +LUAU_FLAGVERSION(LuauTraverseScopeToFunction, 2) LUAU_FASTFLAG(LuauReferenceCountInitializerIsIterative) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) +LUAU_FASTFLAGVARIABLE(LuauEqualityConstraintBinds) LUAU_FASTFLAGVARIABLE(LuauNonreentrantLookupTableProp) LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) @@ -859,30 +860,6 @@ void ConstraintSolver::bind(NotNull constraint, TypePackId tp, unblock(tp, constraint->location); } -template -void ConstraintSolver::DEPRECATED_emplace(NotNull constraint, TypeId ty, Args&&... args) -{ - static_assert(!std::is_same_v, "cannot use `emplace`! use `bind`"); - - LUAU_ASSERT(get(ty) || get(ty) || get(ty)); - LUAU_ASSERT(canMutate(ty, constraint)); - - emplaceType(asMutable(ty), std::forward(args)...); - unblock(ty, constraint->location); -} - -template -void ConstraintSolver::DEPRECATED_emplace(NotNull constraint, TypePackId tp, Args&&... args) -{ - static_assert(!std::is_same_v, "cannot use `emplace`! use `bind`"); - - LUAU_ASSERT(get(tp) || get(tp)); - LUAU_ASSERT(canMutate(tp, constraint)); - - emplaceTypePack(asMutable(tp), std::forward(args)...); - unblock(tp, constraint->location); -} - bool ConstraintSolver::tryDispatch(NotNull constraint, bool force) { @@ -2040,19 +2017,11 @@ bool ConstraintSolver::tryDispatchHasIndexer( else if (auto mt = get(follow(ft->upperBound))) return tryDispatchHasIndexer(recursionDepth, constraint, mt->table, indexType, resultType, seen); - if (FFlag::LuauRemoveConstraintSolverEmplace) - { - auto freeResult = freshType(arena, builtinTypes, ft->scope, Polarity::Mixed); - trackInteriorFreeType(ft->scope, freeResult); - bind(constraint, resultType, freeResult); - // We expect `resultType` to be followed later, so just reassign it here. - resultType = freeResult; - } - else - { - FreeType freeResult{ft->scope, builtinTypes->neverType, builtinTypes->unknownType, Polarity::Mixed}; - DEPRECATED_emplace(constraint, resultType, freeResult); - } + auto freeResult = freshType(arena, builtinTypes, ft->scope, Polarity::Mixed); + trackInteriorFreeType(ft->scope, freeResult); + bind(constraint, resultType, freeResult); + // We expect `resultType` to be followed later, so just reassign it here. + resultType = freeResult; const TableState ubState = FFlag::DebugLuauExactTableTypes ? TableState::Sealed : TableState::Unsealed; TypeId upperBound = arena->addType(TableType{/* props */ {}, TableIndexer{indexType, resultType}, TypeLevel{}, ft->scope, ubState}); @@ -2079,18 +2048,9 @@ bool ConstraintSolver::tryDispatchHasIndexer( { // FIXME this is greedy. - if (FFlag::LuauRemoveConstraintSolverEmplace) - { - auto freeResult = freshType(arena, builtinTypes, tt->scope, Polarity::Mixed); - trackInteriorFreeType(tt->scope, freeResult); - bind(constraint, resultType, freeResult); - } - else - { - FreeType freeResult{tt->scope, builtinTypes->neverType, builtinTypes->unknownType, Polarity::Mixed}; - DEPRECATED_emplace(constraint, resultType, freeResult); - trackInteriorFreeType(constraint->scope, resultType); - } + auto freeResult = freshType(arena, builtinTypes, tt->scope, Polarity::Mixed); + trackInteriorFreeType(tt->scope, freeResult); + bind(constraint, resultType, freeResult); tt->indexer = TableIndexer{indexType, resultType}; return true; @@ -2118,72 +2078,36 @@ bool ConstraintSolver::tryDispatchHasIndexer( // selection: for every type in the intersection where it is well typed // to index into _that_ type, we construct an intersection of said result // types. - if (FFlag::LuauRemoveConstraintSolverEmplace) - { - - IntersectionBuilder ib{arena, builtinTypes}; - bool success = false; - - for (TypeId part : it) - { - TypeId r = arena->addType(BlockedType{}); - getMutable(r)->setOwner(constraint.get()); - - bool ok = tryDispatchHasIndexer(recursionDepth, constraint, part, indexType, r, seen); - // If we've cut a recursive loop short, skip it. - if (!ok) - continue; - - r = follow(r); - if (!get(r)) - { - success = true; - ib.add(r); - } - } + IntersectionBuilder ib{arena, builtinTypes}; + bool success = false; - // We need to distinguish between the empty case (there - // were no valid indexable types) and the bottom type (one of the - // indexable result types was never). UnionBuilder will opt to - // only record that its seen a top type as an optimization. we - // add a flag to distinguish these cases. - if (success) - bind(constraint, resultType, ib.build()); - else - bind(constraint, resultType, builtinTypes->errorType); - } - else + for (TypeId part : it) { + TypeId r = arena->addType(BlockedType{}); + getMutable(r)->setOwner(constraint.get()); - DenseHashSet parts; - for (TypeId part : it) - parts.insert(follow(part)); - - DenseHashSet results; + bool ok = tryDispatchHasIndexer(recursionDepth, constraint, part, indexType, r, seen); + // If we've cut a recursive loop short, skip it. + if (!ok) + continue; - for (TypeId part : parts) + r = follow(r); + if (!get(r)) { - TypeId r = arena->addType(BlockedType{}); - getMutable(r)->setOwner(constraint.get()); - - bool ok = tryDispatchHasIndexer(recursionDepth, constraint, part, indexType, r, seen); - // If we've cut a recursive loop short, skip it. - if (!ok) - continue; - - r = follow(r); - if (!get(r)) - results.insert(r); + success = true; + ib.add(r); } - - if (0 == results.size()) - bind(constraint, resultType, builtinTypes->errorType); - else if (1 == results.size()) - bind(constraint, resultType, *results.begin()); - else - DEPRECATED_emplace(constraint, resultType, std::vector(results.begin(), results.end())); } + // We need to distinguish between the empty case (there + // were no valid indexable types) and the bottom type (one of the + // indexable result types was never). UnionBuilder will opt to + // only record that its seen a top type as an optimization. we + // add a flag to distinguish these cases. + if (success) + bind(constraint, resultType, ib.build()); + else + bind(constraint, resultType, builtinTypes->errorType); return true; } @@ -2191,70 +2115,34 @@ bool ConstraintSolver::tryDispatchHasIndexer( { // Indexing into a union of types means constructing a union of // results: we don't know _which_ type it could be. - if (FFlag::LuauRemoveConstraintSolverEmplace) - { - UnionBuilder ub{arena, builtinTypes}; - bool success = false; - - for (TypeId option : ut) - { - TypeId r = arena->addType(BlockedType{}); - getMutable(r)->setOwner(constraint.get()); - - bool ok = tryDispatchHasIndexer(recursionDepth, constraint, option, indexType, r, seen); - // If we've cut a recursive loop short, skip it. - if (!ok) - continue; + UnionBuilder ub{arena, builtinTypes}; + bool success = false; - r = follow(r); - success = true; - ub.add(r); - } - - // We need to distinguish between the empty case (there - // were no valid indexable types) and the top type (one of the - // indexable result types was unknown). UnionBuilder will opt to - // only record that its seen a top type as an optimization. we - // add a flag to distinguish these cases. - if (success) - bind(constraint, resultType, ub.build()); - else - bind(constraint, resultType, builtinTypes->errorType); - } - else + for (TypeId option : ut) { + TypeId r = arena->addType(BlockedType{}); + getMutable(r)->setOwner(constraint.get()); - DenseHashSet parts; - for (TypeId part : ut) - parts.insert(follow(part)); - - DenseHashSet results; - - for (TypeId part : parts) - { - TypeId r = arena->addType(BlockedType{}); - getMutable(r)->setOwner(constraint.get()); - - bool ok = tryDispatchHasIndexer(recursionDepth, constraint, part, indexType, r, seen); - // If we've cut a recursive loop short, skip it. - if (!ok) - continue; - - r = follow(r); - results.insert(r); - } + bool ok = tryDispatchHasIndexer(recursionDepth, constraint, option, indexType, r, seen); + // If we've cut a recursive loop short, skip it. + if (!ok) + continue; - if (0 == results.size()) - bind(constraint, resultType, builtinTypes->errorType); - else if (1 == results.size()) - { - TypeId firstResult = *results.begin(); - bind(constraint, resultType, firstResult); - } - else - DEPRECATED_emplace(constraint, resultType, std::vector(results.begin(), results.end())); + r = follow(r); + success = true; + ub.add(r); } + // We need to distinguish between the empty case (there + // were no valid indexable types) and the top type (one of the + // indexable result types was unknown). UnionBuilder will opt to + // only record that its seen a top type as an optimization. we + // add a flag to distinguish these cases. + if (success) + bind(constraint, resultType, ub.build()); + else + bind(constraint, resultType, builtinTypes->errorType); + return true; } @@ -2804,9 +2692,48 @@ bool ConstraintSolver::tryDispatch(const ReducePackConstraint& c, NotNull constraint) { - unify(constraint, c.resultType, c.assignmentType); - unify(constraint, c.assignmentType, c.resultType); - return true; + if (FFlag::LuauEqualityConstraintBinds) + { + // TODO CLI-234809: This is fairly conservative as it only fires when + // one free type is unbound. Consider something like: + // + // ('a <: number | string) ~ ('b <: string | boolean) + // + // ... in this case, we could consider a new free type 'c that has the + // upper bound `(number | string) & (string | boolean)` => `string`. + // Additionally, we could perform this check in the Unifier itself, so + // that this can be observed as, say, a result of two subtype constraints + // and not a single equality constraint. + auto hasNoBounds = [](const FreeType* ft) { + return is(follow(ft->lowerBound)) && is(follow(ft->upperBound)); + }; + + auto resultType = follow(c.resultType); + auto assignmentType = follow(c.assignmentType); + + if (auto ft = get(resultType); ft && hasNoBounds(ft)) + { + bind(constraint, resultType, assignmentType); + return true; + } + + if (auto ft = get(assignmentType); ft && hasNoBounds(ft)) + { + bind(constraint, assignmentType, resultType); + return true; + } + + unify(constraint, resultType, assignmentType); + unify(constraint, assignmentType, resultType); + return true; + + } + else + { + unify(constraint, c.resultType, c.assignmentType); + unify(constraint, c.assignmentType, c.resultType); + return true; + } } struct FindAllUnionMembers : TypeOnceVisitor diff --git a/Analysis/src/DataFlowGraph.cpp b/Analysis/src/DataFlowGraph.cpp index 2bfb0aa31..0e8ec0a5b 100644 --- a/Analysis/src/DataFlowGraph.cpp +++ b/Analysis/src/DataFlowGraph.cpp @@ -13,7 +13,7 @@ LUAU_FASTFLAG(DebugLuauFreezeArena) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) -LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) namespace Luau { @@ -540,9 +540,11 @@ ControlFlow DataFlowGraphBuilder::visit(AstStatWhile* w) PushScope ps{scopeStack, whileScope}; visitExpr(w->condition); - if (FFlag::DebugLuauWhileLocalAnalysis && w->conditionLocal) + if (FFlag::LuauExperimentalWhileLocalAnalysis && w->conditionLocal) { DefId def = defArena->freshCell(w->conditionLocal, w->conditionLocal->location, false); + if (w->conditionLocal->annotation) + visitType(w->conditionLocal->annotation); graph.localDefs[w->conditionLocal] = def; whileScope->bindings[w->conditionLocal] = def; captures[w->conditionLocal].allVersions.push_back(def); diff --git a/Analysis/src/Error.cpp b/Analysis/src/Error.cpp index 1d4664312..f921cf4ea 100644 --- a/Analysis/src/Error.cpp +++ b/Analysis/src/Error.cpp @@ -1087,6 +1087,11 @@ struct ErrorConverter return "Illegal override of property '" + e.property + "' on class '" + e.className + "' inherited from superclass '" + e.superName + "'"; } + std::string operator()(const MissingConstructor& e) const + { + return "'" + e.className + "' inherits a constructor from '" + e.superName + "', so it needs to define one too"; + } + std::string operator()(const NotIterable& e) const { return "`" + toString(e.ty) + "` is not iterable"; @@ -1343,6 +1348,11 @@ bool IllegalClassPropertyOverride::operator==(const IllegalClassPropertyOverride return property == rhs.property && className == rhs.className && superName == rhs.superName; } +bool MissingConstructor::operator==(const MissingConstructor& rhs) const +{ + return className == rhs.className && superName == rhs.superName; +} + bool NotIterable::operator==(const NotIterable& rhs) const { return ty == rhs.ty; @@ -1851,6 +1861,9 @@ void copyError(T& e, TypeArena& destArena, CloneState& cloneState) else if constexpr (std::is_same_v) { } + else if constexpr (std::is_same_v) + { + } else if constexpr (std::is_same_v) { e.ty = clone(e.ty); diff --git a/Analysis/src/FragmentAutocomplete.cpp b/Analysis/src/FragmentAutocomplete.cpp index d10b8ab33..71157cba4 100644 --- a/Analysis/src/FragmentAutocomplete.cpp +++ b/Analysis/src/FragmentAutocomplete.cpp @@ -36,7 +36,7 @@ LUAU_FASTFLAG(LuauCyclicRequireTypeInference) LUAU_FASTFLAGVARIABLE(LuauFragmentACLocalAutocompleteFix) LUAU_FASTFLAGVARIABLE(LuauAutocompleteIfSlurpsCond) LUAU_FASTFLAG(LuauSplitIceHandler) -LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) namespace Luau { @@ -549,7 +549,7 @@ FragmentAutocompleteAncestryResult findAncestryForFragmentParse(AstStatBlock* st } // Add the `while local` binding to the local map if the cursor is in the body of the `AstStatWhile` - if (FFlag::DebugLuauWhileLocalAnalysis) + if (FFlag::LuauExperimentalWhileLocalAnalysis) { if (auto whileStat = node->as(); whileStat && whileStat->conditionLocal && whileStat->body->location.containsClosed(cursorPos)) diff --git a/Analysis/src/IostreamHelpers.cpp b/Analysis/src/IostreamHelpers.cpp index 3b29c2124..857ff1038 100644 --- a/Analysis/src/IostreamHelpers.cpp +++ b/Analysis/src/IostreamHelpers.cpp @@ -348,6 +348,8 @@ static void errorToString(std::ostream& stream, const T& err) else if constexpr (std::is_same_v) stream << "IllegalClassPropertyOverride { property = " << err.property << ", className = " << err.className << ", superName = " << err.superName << " }"; + else if constexpr (std::is_same_v) + stream << "MissingConstructor { className = " << err.className << ", superName = " << err.superName << " }"; else if constexpr (std::is_same_v) stream << "NotIterable { " << toString(err.ty) << " }"; else diff --git a/Analysis/src/NonStrictTypeChecker.cpp b/Analysis/src/NonStrictTypeChecker.cpp index ad2fdb14b..519b2793a 100644 --- a/Analysis/src/NonStrictTypeChecker.cpp +++ b/Analysis/src/NonStrictTypeChecker.cpp @@ -553,31 +553,30 @@ struct NonStrictTypeChecker if (!superInstanceEtv) return {}; + bool constructorDefined = false; + for (auto prop : declClass->members) { if (auto property = get_if(&prop)) { - Name propName = Name{property->name.value}; // Slightly inefficient: we walk the inheritance chain for each property - for (const ExternType* curr = superInstanceEtv; curr; curr = get(follow(curr->parent))) + if (std::optional ancestor = propInInheritanceChain(superInstanceEtv, property->name.value)) { - if (curr->props.count(propName) != 0) - { - reportError( - IllegalClassPropertyOverride{propName, Name{declClass->name->name.value}, Name{curr->name}}, property->nameLocation - ); - break; - } + reportError( + IllegalClassPropertyOverride{property->name.value, Name{declClass->name->name.value}, *ancestor}, property->nameLocation + ); } } - else if (auto method = get_if(&prop); - method && (method->functionName == "__eq" || method->functionName == "__lt" || method->functionName == "__le")) + else if (auto method = get_if(&prop)) { - Name methodName = Name{method->functionName.value}; - for (const ExternType* curr = superInstanceEtv; curr; curr = get(follow(curr->parent))) + if (method->functionName == "__eq" || method->functionName == "__lt" || method->functionName == "__le") { - if (curr->metatable) + Name methodName = Name{method->functionName.value}; + for (const ExternType* curr = superInstanceEtv; curr; curr = get(follow(curr->parent))) { + if (!curr->metatable) + continue; + if (const TableType* mt = get(follow(*curr->metatable))) { if (mt->props.count(methodName) != 0) @@ -591,8 +590,16 @@ struct NonStrictTypeChecker } } } + else if (method->functionName == "__init") + constructorDefined = true; } } + + if (!constructorDefined) + { + if (std::optional ancestor = propInInheritanceChain(superInstanceEtv, "__init")) + reportError(MissingConstructor{Name(declClass->name->name.value), *ancestor}, declClass->location); + } } return {}; diff --git a/Analysis/src/TypeChecker2.cpp b/Analysis/src/TypeChecker2.cpp index fa3e51a4b..f602b003a 100644 --- a/Analysis/src/TypeChecker2.cpp +++ b/Analysis/src/TypeChecker2.cpp @@ -44,11 +44,10 @@ LUAU_FASTFLAGVARIABLE(LuauCompoundAssignSeedsAstTypes) LUAU_FASTFLAGVARIABLE(LuauDontUseInnermostScope) LUAU_FASTFLAG(LuauTypeFunctionsAbsenceCache) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) -LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) -LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) LUAU_FASTFLAGVARIABLE(LuauTypeCheckGeneralizedIterationSoundness) LUAU_FASTFLAGVARIABLE(LuauTypeCheckUseNotIterable) @@ -758,7 +757,7 @@ void TypeChecker2::visit(AstStatWhile* whileStatement) { visit(whileStatement->condition, ValueContext::RValue); - if (FFlag::DebugLuauWhileLocalAnalysis && whileStatement->conditionLocal && whileStatement->conditionLocal->annotation) + if (FFlag::LuauExperimentalWhileLocalAnalysis && whileStatement->conditionLocal && whileStatement->conditionLocal->annotation) { TypeId annotationType = lookupAnnotation(whileStatement->conditionLocal->annotation); testPotentialLiteralIsSubtype(whileStatement->condition, annotationType); @@ -1586,6 +1585,8 @@ void TypeChecker2::checkMemberOverrides(AstStatClass* stat) if (!superInstanceEtv) return; + bool constructorDefined = false; + for (const auto& member : stat->members) { Luau::visit( @@ -1596,25 +1597,27 @@ void TypeChecker2::checkMemberOverrides(AstStatClass* stat) }, [&](const AstClassMethod& method) { + if (method.functionName == "__init") + constructorDefined = true; + checkMethodOverride(stat, &method, superInstanceEtv); } }, member ); } + + if (!constructorDefined) + { + if (std::optional ancestor = propInInheritanceChain(superInstanceEtv, "__init")) + reportError(MissingConstructor{Name(stat->name->name.value), *ancestor}, stat->location); + } } void TypeChecker2::checkPropertyOverride(AstStatClass* stat, const AstClassProperty* property, const ExternType* superInstanceEtv) { - std::string propertyName{property->name.value}; - for (; superInstanceEtv; superInstanceEtv = get(follow(superInstanceEtv->parent))) - { - if (superInstanceEtv->props.count(propertyName) != 0) - { - reportError(IllegalClassPropertyOverride{propertyName, Name(stat->name->name.value), superInstanceEtv->name}, property->nameLocation); - return; - } - } + if (std::optional ancestor = propInInheritanceChain(superInstanceEtv, property->name.value)) + reportError(IllegalClassPropertyOverride{property->name.value, Name(stat->name->name.value), *ancestor}, property->nameLocation); } void TypeChecker2::checkMethodOverride(AstStatClass* stat, const AstClassMethod* method, const ExternType* superInstanceEtv) diff --git a/Analysis/src/TypeInfer.cpp b/Analysis/src/TypeInfer.cpp index c557ed0a7..e57685147 100644 --- a/Analysis/src/TypeInfer.cpp +++ b/Analysis/src/TypeInfer.cpp @@ -36,7 +36,7 @@ LUAU_FASTFLAG(LuauExportValueTypecheck) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAGVARIABLE(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) -LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) namespace Luau { @@ -718,7 +718,7 @@ WithPredicate TypeChecker::checkLocalBinding( std::optional expectedType ) { - LUAU_ASSERT(FFlag::LuauExperimentalIfLocalAnalysis || FFlag::DebugLuauWhileLocalAnalysis); + LUAU_ASSERT(FFlag::LuauExperimentalIfLocalAnalysis || FFlag::LuauExperimentalWhileLocalAnalysis); LUAU_ASSERT(local); TypeId lhs = nullptr; @@ -798,14 +798,14 @@ ErrorVec TypeChecker::canUnify(TypePackId subTy, TypePackId superTy, const Scope ControlFlow TypeChecker::check(const ScopePtr& scope, const AstStatWhile& statement) { std::optional expectedType = std::nullopt; - if (FFlag::DebugLuauWhileLocalAnalysis && statement.conditionLocal && statement.conditionLocal->annotation) + if (FFlag::LuauExperimentalWhileLocalAnalysis && statement.conditionLocal && statement.conditionLocal->annotation) expectedType.emplace(resolveType(scope, *statement.conditionLocal->annotation)); WithPredicate result = checkExpr(scope, *statement.condition, expectedType); ScopePtr whileScope = childScope(scope, statement.body->location); - if (FFlag::DebugLuauWhileLocalAnalysis && statement.conditionLocal != nullptr) + if (FFlag::LuauExperimentalWhileLocalAnalysis && statement.conditionLocal != nullptr) { WithPredicate bindingPred = checkLocalBinding(scope, whileScope, statement.conditionLocal, result, expectedType); resolve(bindingPred.predicates, whileScope, true); diff --git a/Analysis/src/TypeUtils.cpp b/Analysis/src/TypeUtils.cpp index 98054d267..f00f8f55b 100644 --- a/Analysis/src/TypeUtils.cpp +++ b/Analysis/src/TypeUtils.cpp @@ -12,6 +12,7 @@ #include "Luau/TypePack.h" #include +#include LUAU_FASTFLAG(LuauTraverseScopeToFunction) @@ -1064,5 +1065,15 @@ OccursCheckResult occursCheck(TypePackId needle, TypePackId haystack) return OccursCheckResult::Pass; } +std::optional propInInheritanceChain(const ExternType* cls, const std::string& prop) +{ + for (; cls; cls = get(follow(cls->parent))) + { + if (cls->props.count(prop) != 0) + return cls->name; + } + return std::nullopt; +} + } // namespace Luau diff --git a/Ast/src/Ast.cpp b/Ast/src/Ast.cpp index af2356313..d36373fb4 100644 --- a/Ast/src/Ast.cpp +++ b/Ast/src/Ast.cpp @@ -4,7 +4,7 @@ #include "Luau/Common.h" LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) namespace Luau { @@ -722,7 +722,7 @@ void AstStatWhile::visit(AstVisitor* visitor) { if (visitor->visit(this)) { - if (FFlag::DebugLuauWhileLocalSyntax && conditionLocal && conditionLocal->annotation) + if (FFlag::LuauExperimentalWhileLocalSyntax && conditionLocal && conditionLocal->annotation) conditionLocal->annotation->visit(visitor); condition->visit(visitor); diff --git a/Ast/src/Parser.cpp b/Ast/src/Parser.cpp index 1e5e3aafb..8410ecb67 100644 --- a/Ast/src/Parser.cpp +++ b/Ast/src/Parser.cpp @@ -34,7 +34,7 @@ LUAU_FASTFLAGVARIABLE(LuauSingleTypeOptionalPackReturnsAttributeParens) LUAU_FASTFLAGVARIABLE(DebugLuauParseExactTables) LUAU_FASTFLAGVARIABLE(LuauExperimentalIfLocalSyntax) LUAU_FLAGVERSION(LuauExperimentalIfLocalSyntax, 2) -LUAU_FASTFLAGVARIABLE(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAGVARIABLE(LuauExperimentalWhileLocalSyntax) // Clip with DebugLuauReportReturnTypeVariadicWithTypeSuffix bool luau_telemetry_parsed_return_type_variadic_with_type_suffix = false; @@ -718,7 +718,7 @@ AstStat* Parser::parseWhile() nextLexeme(); // while - if (FFlag::DebugLuauWhileLocalSyntax) + if (FFlag::LuauExperimentalWhileLocalSyntax) { if (lexer.current().type == Lexeme::ReservedLocal) return parseWhileLocalCondition(start); @@ -752,7 +752,7 @@ AstStat* Parser::parseWhile() // `start` is the location of the already-consumed `while` keyword; the current lexeme is the `local`/`const` keyword. LUAU_NOINLINE AstStat* Parser::parseWhileLocalCondition(const Location& start) { - LUAU_ASSERT(FFlag::DebugLuauWhileLocalSyntax); + LUAU_ASSERT(FFlag::LuauExperimentalWhileLocalSyntax); bool condIsConst = (lexer.current().type == Lexeme::Name && AstName(lexer.current().name) == "const"); std::optional condKeywordLocation = lexer.current().location; @@ -1623,7 +1623,7 @@ const char* getClassFieldNameError(const AstName& name, AstClassAccess access) } // namespace -// classStatement ::= [`open`] `class` Name classProps `end` +// classStatement ::= [`export`] [`open`] `class` Name classProps `end` // classProps ::= classProp [classProps] // classProp ::= name [: classQualifier* type] LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool exported, bool open) @@ -1635,11 +1635,8 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export if (!name) name = Name(nameError, lexer.current().location); - // We save the locals here as part of error recovery later. - auto savedLocals = saveLocals(); - - AstLocal* nameLocal = pushLocal(Binding(*name, nullptr, {0, 0}, true)); - + // The superclass is parsed before the class binding is pushed so that `class Foo extends Foo` refers to an outer `Foo` rather than to the class + // being declared. AstExpr* super = nullptr; if (lexer.current().type == Lexeme::Name && AstName(lexer.current().name) == "extends") { @@ -1648,6 +1645,11 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export super = parseClassRefExpr(); } + // We save the locals here as part of error recovery later. + auto savedLocals = saveLocals(); + + AstLocal* nameLocal = pushLocal(Binding(*name, nullptr, {0, 0}, true)); + TempVector declarations(scratchClassDeclarations); // TODO: This does not seem particularly performant, but we need to diff --git a/Ast/src/PrettyPrinter.cpp b/Ast/src/PrettyPrinter.cpp index 5a063fdfe..fae929303 100644 --- a/Ast/src/PrettyPrinter.cpp +++ b/Ast/src/PrettyPrinter.cpp @@ -15,7 +15,7 @@ LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) namespace { @@ -937,7 +937,7 @@ struct Printer else if (const auto& a = program.as()) { writer.keyword("while"); - if (FFlag::DebugLuauWhileLocalSyntax && a->conditionLocal) + if (FFlag::LuauExperimentalWhileLocalSyntax && a->conditionLocal) { const auto cstNode = lookupCstNode(a); diff --git a/CodeGen/include/Luau/AssemblyBuilderX64.h b/CodeGen/include/Luau/AssemblyBuilderX64.h index b862c6f16..56a445953 100644 --- a/CodeGen/include/Luau/AssemblyBuilderX64.h +++ b/CodeGen/include/Luau/AssemblyBuilderX64.h @@ -116,6 +116,7 @@ class AssemblyBuilderX64 void bsr(RegisterX64 dst, OperandX64 src); void bsf(RegisterX64 dst, OperandX64 src); + void bts(OperandX64 dst, RegisterX64 src); void bswap(RegisterX64 dst); // Code alignment diff --git a/CodeGen/include/Luau/CodeGenOptions.h b/CodeGen/include/Luau/CodeGenOptions.h index c0224e29d..4f23a6ae7 100644 --- a/CodeGen/include/Luau/CodeGenOptions.h +++ b/CodeGen/include/Luau/CodeGenOptions.h @@ -24,6 +24,9 @@ enum class CodeGenCounter : unsigned RegularBlockExecuted = 1, FallbackBlockExecuted = 2, VmExitTaken = 3, + + VmRegTagMismatch = 4, + VmRegUserdataTag = 5, }; using AllocationCallback = void(void* context, void* oldPointer, size_t oldSize, void* newPointer, size_t newSize); diff --git a/CodeGen/include/Luau/IrBuilder.h b/CodeGen/include/Luau/IrBuilder.h index 1b45a7599..6f94998e1 100644 --- a/CodeGen/include/Luau/IrBuilder.h +++ b/CodeGen/include/Luau/IrBuilder.h @@ -30,9 +30,11 @@ struct IrBuilder bool isInternalBlock(IrOp block); void beginBlock(IrOp block); + IrCounterSet& getBlockCounterSet(IrOp block); void loadAndCheckTag(IrOp loc, uint8_t tag, IrOp fallback); void checkSafeEnv(int pcpos); + IrCounterSet& addUpdateCounters(); // Clones all instructions into the current block // Source block that is cloned cannot use values coming in from a predecessor diff --git a/CodeGen/include/Luau/IrData.h b/CodeGen/include/Luau/IrData.h index 2ca62eb3c..860391bc8 100644 --- a/CodeGen/include/Luau/IrData.h +++ b/CodeGen/include/Luau/IrData.h @@ -763,6 +763,10 @@ enum class IrCmd : uint8_t // Check and run GC assist if necessary CHECK_GC, + // Update runtime counters from the counter set + // A: unsigned int (counter set index) + UPDATE_COUNTERS, + // Handle GC write barrier (forward) // A: pointer (GCObject) // B: Rn (TValue that was written to the object) @@ -1349,6 +1353,20 @@ struct IrInstEq } }; +struct IrEntryCounter +{ + CodeGenCounter kind = CodeGenCounter::VmRegTagMismatch; + IrOp operand; + uint32_t pcpos = ~0u; + + uint8_t expectedTag = kUnknownTag; // tag expected by fast path falling back to this counter +}; + +struct IrCounterSet +{ + SmallVector counters; +}; + enum class IrBlockKind : uint8_t { Bytecode, @@ -1384,6 +1402,8 @@ struct IrBlock uint32_t startpc = kBlockNoStartPc; Label label; + + uint32_t counterSet = ~0u; }; struct BytecodeMapping @@ -1426,6 +1446,44 @@ struct BytecodeTypeInfo std::vector regTypeOffsets; }; +// VM register tag that was recorded at the bytecode instruction at runtime +struct BytecodeTagFeedback +{ + uint32_t pcpos = 0; + uint8_t reg = 0; + uint8_t tag = 0; + + bool operator==(const BytecodeTagFeedback& rhs) const + { + return pcpos == rhs.pcpos && reg == rhs.reg && tag == rhs.tag; + } +}; + +struct BytecodeUserdataFeedback +{ + uint32_t pcpos = 0; + uint8_t reg = 0; + uint8_t tag = 0; // Runtime tag + uint8_t type = LBC_TYPE_ANY; // Bytecode type + + bool operator==(const BytecodeUserdataFeedback& rhs) const + { + return pcpos == rhs.pcpos && reg == rhs.reg && tag == rhs.tag && type == rhs.type; + } +}; + +// Feedback recorded about the function at runtime +struct BytecodeFeedback +{ + std::vector tags; // Sorted by pcpos + std::vector userdataTypes; // Sorted by pcpos + + bool operator==(const BytecodeFeedback& rhs) const + { + return tags == rhs.tags && userdataTypes == rhs.userdataTypes; + } +}; + struct ValueRestoreLocation { IrOp op; // Operand representing the location (Rn/Kn) @@ -1496,6 +1554,9 @@ struct IrFunction BytecodeTypeInfo bcOriginalTypeInfo; // Bytecode type information as loaded BytecodeTypeInfo bcTypeInfo; // Bytecode type information with additional inferences + std::vector counterSets; + BytecodeFeedback feedback; + VmEnvironmentInfo envInfo; Proto* proto = nullptr; diff --git a/CodeGen/include/Luau/IrDump.h b/CodeGen/include/Luau/IrDump.h index b1f8c58f1..3dd34332b 100644 --- a/CodeGen/include/Luau/IrDump.h +++ b/CodeGen/include/Luau/IrDump.h @@ -32,6 +32,7 @@ struct IrToStringContext const std::vector& constants; const CfgInfo& cfg; const DenseHashMap& vmExitInfo; + const std::vector& counterSets; Proto* proto = nullptr; }; diff --git a/CodeGen/include/Luau/IrUtils.h b/CodeGen/include/Luau/IrUtils.h index 51f49ba4a..dd5b3026b 100644 --- a/CodeGen/include/Luau/IrUtils.h +++ b/CodeGen/include/Luau/IrUtils.h @@ -215,6 +215,12 @@ bool isCustomUserdataBytecodeType(uint8_t ty); // Check that 'ty' is 'expected' or 'any' bool isExpectedOrUnknownBytecodeType(uint8_t ty, LuauBytecodeType expected); +// Tag recorded at runtime on the register at the bytecode instruction +LuauBytecodeType getTagFeedback(const IrFunction& function, int pcpos, int reg); + +// Userdata recorded at runtime on the register at the bytecode instruction +std::optional getUserdataFeedback(const IrFunction& function, int pcpos, int reg); + HostMetamethod tmToHostMetamethod(int tm); // Manually add or remove use of an operand diff --git a/CodeGen/include/Luau/IrVisitUseDef.h b/CodeGen/include/Luau/IrVisitUseDef.h index 35cb86559..b0bc56039 100644 --- a/CodeGen/include/Luau/IrVisitUseDef.h +++ b/CodeGen/include/Luau/IrVisitUseDef.h @@ -4,6 +4,8 @@ #include "Luau/Common.h" #include "Luau/IrData.h" +LUAU_FASTFLAG(LuauCodegenX64ConflictCheck) + namespace Luau { namespace CodeGen @@ -88,6 +90,14 @@ static void visitVmRegDefsUses(T& visitor, IrFunction& function, IrInst& inst) break; case IrCmd::INTERRUPT: break; + case IrCmd::UPDATE_COUNTERS: + { + IrCounterSet& counterSet = function.counterSets[function.uintOp(OP_A(inst))]; + + for (const IrEntryCounter& counter : counterSet.counters) + visitor.use(counter.operand); + break; + } case IrCmd::BARRIER_OBJ: case IrCmd::BARRIER_TABLE_FORWARD: visitor.maybeUse(OP_B(inst)); @@ -236,6 +246,33 @@ static void visitVmRegDefsUses(T& visitor, IrFunction& function, IrInst& inst) // Does not affect VM def/use info break; + // These instructions read VmReg only after optimizeMemoryOperandsX64 + case IrCmd::CHECK_TAG: + case IrCmd::FLOOR_NUM: + case IrCmd::CEIL_NUM: + case IrCmd::ROUND_NUM: + case IrCmd::SQRT_NUM: + case IrCmd::ABS_NUM: + if (FFlag::LuauCodegenX64ConflictCheck) + visitor.maybeUse(OP_A(inst)); + break; + case IrCmd::CHECK_TRUTHY: + case IrCmd::ADD_NUM: + case IrCmd::SUB_NUM: + case IrCmd::MUL_NUM: + case IrCmd::DIV_NUM: + case IrCmd::IDIV_NUM: + case IrCmd::MOD_NUM: + case IrCmd::MIN_NUM: + case IrCmd::MAX_NUM: + case IrCmd::JUMP_CMP_NUM: + if (FFlag::LuauCodegenX64ConflictCheck) + { + visitor.maybeUse(OP_A(inst)); + visitor.maybeUse(OP_B(inst)); + } + break; + default: // All instructions which reference registers have to be handled explicitly for (auto& op : inst.ops) diff --git a/CodeGen/src/AssemblyBuilderX64.cpp b/CodeGen/src/AssemblyBuilderX64.cpp index 93c115622..8d6b60f2b 100644 --- a/CodeGen/src/AssemblyBuilderX64.cpp +++ b/CodeGen/src/AssemblyBuilderX64.cpp @@ -581,6 +581,21 @@ void AssemblyBuilderX64::bsf(RegisterX64 dst, OperandX64 src) commit(); } +void AssemblyBuilderX64::bts(OperandX64 dst, RegisterX64 src) +{ + if (logText) + log("bts", dst, src); + + CODEGEN_ASSERT(src.size == SizeX64::dword || src.size == SizeX64::qword); + CODEGEN_ASSERT(dst.cat == CategoryX64::reg ? dst.base.size == src.size : dst.memSize == src.size); + + placeRex(src, dst); + place(0x0f); + place(0xab); + placeRegAndModRegMem(src, dst); + commit(); +} + void AssemblyBuilderX64::bswap(RegisterX64 dst) { if (logText) diff --git a/CodeGen/src/CodeGenContext.cpp b/CodeGen/src/CodeGenContext.cpp index 9fa016b2e..dcd14fde0 100644 --- a/CodeGen/src/CodeGenContext.cpp +++ b/CodeGen/src/CodeGenContext.cpp @@ -16,6 +16,7 @@ #include "lfunc.h" #include "lgc.h" #include "lmem.h" +#include "ltable.h" #include @@ -55,6 +56,12 @@ static const Instruction kCodeEntryInsn = LOP_NATIVECALL; // TODO: could be promoted to flags or compilation option fields +// Number of counter hits after which the function might be rebuilt +constexpr uint32_t kRebuildCounterHits = 100'000; + +// Number of counter hits after which the recorded register information is considered to be reliable +constexpr uint32_t kReliableFeedbackHits = 10'000; + // Maximum number of times a single function can be rebuilt constexpr uint32_t kMaxFunctionRebuilds = 5; @@ -489,6 +496,57 @@ static char* getCounterData(lua_State* L, Proto* proto, size_t* count) return reinterpret_cast(static_cast(proto->execdata) + proto->sizecode); } +struct NativeCounter +{ + uint32_t kind; // CodeGenCounter + uint32_t pcpos; + uint32_t hits; + uint32_t data; +}; +static_assert(sizeof(NativeCounter) == 4 * sizeof(uint32_t)); + +inline NativeCounter* getNativeCounters(Proto* proto, unsigned& count) +{ + const NativeProtoExecDataHeader& header = getNativeProtoExecDataHeader(static_cast(proto->execdata)); + + count = header.extraDataCount / 4; + return reinterpret_cast(static_cast(proto->execdata) + proto->sizecode); +} + +static bool matchesExpectedTag(uint32_t data) +{ + uint32_t expectedTag = data >> 24; + uint32_t tagMask = data & 0xffff; + + return expectedTag != 0 && tagMask == (1u << (expectedTag - 1)); +} + +static bool hasUserdataRecorded(uint32_t data) +{ + return (data >> 24) != 0; +} + +static uint8_t getFirstUserdata(uint32_t data) +{ + return uint8_t((data >> 24) - 1); // Tag is stored with +1 to recognize unset tag +} + +static bool isUserdataPolymorphic(uint32_t data) +{ + return (data & 1) == 1; +} + +static bool counterSignalsRebuild(CodeGenCounter kind, uint32_t data) +{ + if (kind == CodeGenCounter::VmRegTagMismatch) + return !matchesExpectedTag(data); + + if (kind == CodeGenCounter::VmRegUserdataTag) + return hasUserdataRecorded(data); + + return false; +} + static void examineFunction(lua_State* L, Proto* proto) { // Fast exit if target function never executed @@ -526,7 +584,192 @@ static void examineFunction(lua_State* L, Proto* proto) return; } - // Rebuild based on feedback counters will be detected here + unsigned counterCount = 0; + NativeCounter* counters = getNativeCounters(proto, counterCount); + + // If function compilation didn't get any counters, there is no need to examine it any more + if (counterCount == 0) + { + proto->execflags |= PEF_EXECLOCKED; + return; + } + + for (size_t i = 0; i < counterCount; i++) + { + NativeCounter& counter = counters[i]; + CodeGenCounter kind = CodeGenCounter(counter.kind); + + if (counter.hits >= kRebuildCounterHits && counterSignalsRebuild(kind, counter.data)) + { + vmData.protosToRebuild.insert(proto); + break; // one rebuild signal is enough for a whole Proto + } + } +} + +template +static T* findRecordedInfo(std::vector& items, uint32_t pcpos, uint8_t reg) +{ + auto it = std::find_if( + items.begin(), + items.end(), + [&](const T& item) + { + return item.pcpos == pcpos && item.reg == reg; + } + ); + + return it != items.end() ? &*it : nullptr; +} + +// Adds info recorded at runtime into the overall function history +static void mergeRecordedInfo(FunctionBuildHistory& history, Proto* proto) +{ + unsigned counterCount = 0; + NativeCounter* counters = getNativeCounters(proto, counterCount); + + for (size_t i = 0; i < counterCount; i++) + { + NativeCounter& counter = counters[i]; + CodeGenCounter kind = CodeGenCounter(counter.kind); + + if (counter.hits <= kReliableFeedbackHits) + continue; + + uint8_t vmReg = uint8_t(counter.data >> 16); + + switch (kind) + { + case CodeGenCounter::VmRegTagMismatch: + { + uint16_t tagMask = uint16_t(counter.data & 0xffff); + + if (tagMask == 0 || matchesExpectedTag(counter.data)) + break; + + if (RecordedRegTags* item = findRecordedInfo(history.recordedTags, counter.pcpos, vmReg)) + { + item->tagMask |= tagMask; + item->hits += counter.hits; + } + else + { + history.recordedTags.push_back({counter.pcpos, vmReg, tagMask, counter.hits}); + } + break; + } + case CodeGenCounter::VmRegUserdataTag: + { + if ((counter.data >> 24) == 0) + break; + + uint8_t tag = getFirstUserdata(counter.data); + bool polymorphic = isUserdataPolymorphic(counter.data); + + if (RecordedUserdataTag* item = findRecordedInfo(history.recordedUserdataTags, counter.pcpos, vmReg)) + { + item->polymorphic |= polymorphic || item->tag != tag; + item->hits += counter.hits; + } + else + { + history.recordedUserdataTags.push_back({counter.pcpos, vmReg, tag, polymorphic, counter.hits}); + } + break; + } + default: + break; + } + } +} + +// Clears the counters to get a fresh runtime recording and stop hitting the same function until new data is gathered +static void resetRecordedCounters(Proto* proto) +{ + unsigned counterCount = 0; + NativeCounter* counters = getNativeCounters(proto, counterCount); + + for (size_t i = 0; i < counterCount; i++) + { + NativeCounter& counter = counters[i]; + + switch (CodeGenCounter(counter.kind)) + { + case CodeGenCounter::VmRegTagMismatch: + counter.hits = 0; + counter.data &= ~0xffffu; // Keep the expected tag and the VM register, clear the tag mask + break; + case CodeGenCounter::VmRegUserdataTag: + counter.hits = 0; + counter.data &= 0xff0000u; // Keep the VM register, clear the tag and flags + break; + default: + break; + } + } +} + +static uint8_t getUserdataTagBytecodeType(lua_State* L, uint8_t utag) +{ + if (utag >= LUA_UTAG_LIMIT || L->global->ecb.gettypemapping == nullptr) + return LBC_TYPE_ANY; + + LuaTable* mt = L->global->udatamt[utag]; + + if (mt == nullptr) + return LBC_TYPE_ANY; + + const TValue* name = luaH_getstr(mt, L->global->tmname[TM_TYPE]); + + if (!ttisstring(name)) + return LBC_TYPE_ANY; + + uint8_t type = L->global->ecb.gettypemapping(L, svalue(name), tsvalue(name)->len); + + return isCustomUserdataBytecodeType(type) ? type : LBC_TYPE_ANY; +} + +// Converts aggregated recorded history into bytecode feedback usable at translation time +static void computeFeedback(lua_State* L, const FunctionBuildHistory& history, BytecodeFeedback& feedback) +{ + for (const RecordedRegTags& item : history.recordedTags) + { + // Polymorphic sites cannot be specialized for a single tag + if ((item.tagMask & (item.tagMask - 1)) != 0) + continue; + + uint8_t tag = 0; + while ((item.tagMask & (1u << tag)) == 0) + tag++; + + feedback.tags.push_back({item.pcpos, item.reg, tag}); + } + + std::sort( + feedback.tags.begin(), + feedback.tags.end(), + [](const BytecodeTagFeedback& a, const BytecodeTagFeedback& b) + { + return a.pcpos != b.pcpos ? a.pcpos < b.pcpos : a.reg < b.reg; + } + ); + + for (const RecordedUserdataTag& item : history.recordedUserdataTags) + { + if (item.polymorphic) + feedback.userdataTypes.push_back({item.pcpos, item.reg, 0, LBC_TYPE_ANY}); + else + feedback.userdataTypes.push_back({item.pcpos, item.reg, item.tag, getUserdataTagBytecodeType(L, item.tag)}); + } + + std::sort( + feedback.userdataTypes.begin(), + feedback.userdataTypes.end(), + [](const BytecodeUserdataFeedback& a, const BytecodeUserdataFeedback& b) + { + return a.pcpos != b.pcpos ? a.pcpos < b.pcpos : a.reg < b.reg; + } + ); } [[nodiscard]] static CompilationResult compileProtos( @@ -535,7 +778,8 @@ static void examineFunction(lua_State* L, Proto* proto) BaseCodeGenContext* codeGenContext, const std::vector& protos, const CompilationOptions& options, - CompilationStats* stats + CompilationStats* stats, + const std::vector* feedback ); static void commitFunctions(lua_State* L) @@ -554,6 +798,7 @@ static void commitFunctions(lua_State* L) std::vector builds; std::vector buildProtos; + std::vector buildFeedback; for (Proto* proto : vmData.protosToRebuild) { @@ -571,11 +816,58 @@ static void commitFunctions(lua_State* L) { builds.push_back({proto, nullptr, proto->execcount}); buildProtos.push_back(proto); + buildFeedback.emplace_back(); proto->execcount = 0; continue; } - // Function rebuild based on feedback counters will be here + FunctionBuildHistory& history = vmData.buildHistory[proto->funid]; + + // Initial history setup + if (history.sizecode == 0) + history.sizecode = proto->sizecode; + + // Reset history if it was recorded for a different form of the function + if (history.sizecode != proto->sizecode) + { + history.sizecode = proto->sizecode; + history.recordedTags.clear(); + history.recordedUserdataTags.clear(); + history.lastFeedback = {}; + } + + mergeRecordedInfo(history, proto); + resetRecordedCounters(proto); + + BytecodeFeedback feedback; + computeFeedback(L, history, feedback); + + // Rebuilding with the same feedback would produce the same code + if (feedback == history.lastFeedback) + continue; + + // Create a copy of the Proto so that already executing functions keep running old code + struct CopyContext + { + Proto* source = nullptr; + Proto* copy = nullptr; + + static void run(lua_State* L, void* ud) + { + CopyContext* ctx = static_cast(ud); + ctx->copy = luaF_cloneproto(L, ctx->source); + } + } ctx = {proto}; + + int status = luaD_rawrunprotected(L, &CopyContext::run, &ctx); + CODEGEN_ASSERT(status == LUA_OK || status == LUA_ERRMEM); + + if (status != LUA_OK) + continue; + + builds.push_back({proto, ctx.copy, 0}); + buildProtos.push_back(ctx.copy); + buildFeedback.push_back(std::move(feedback)); } vmData.protosToRebuild.clear(); @@ -583,7 +875,7 @@ static void commitFunctions(lua_State* L) if (builds.empty()) return; - CompilationResult result = compileProtos({}, L, codeGenContext, buildProtos, vmData.options, nullptr); + CompilationResult result = compileProtos({}, L, codeGenContext, buildProtos, vmData.options, nullptr, &buildFeedback); // TODO: callback function for host telemetry recording if (result.result != CodeGenCompilationResult::Success) @@ -594,7 +886,7 @@ static void commitFunctions(lua_State* L) Proto* proto = builds[i].proto; Proto* copy = builds[i].copy; - // Initial VM to native promotion is performed inplace, so we don't need to swith Proto to the optimized version + // Initial VM to native promotion is performed in place, so we don't need to switch Proto to the optimized version if (copy == nullptr) continue; @@ -609,6 +901,7 @@ static void commitFunctions(lua_State* L) luaC_objbarrier(L, proto, copy); history.rebuildCount++; + history.lastFeedback = std::move(buildFeedback[i]); if (history.rebuildCount >= kMaxFunctionRebuilds) { @@ -749,7 +1042,8 @@ template uint32_t& totalIrInstCount, const CompilationOptions& options, CodeGenCompilationResult& result, - const VmEnvironmentInfo& envInfo + const VmEnvironmentInfo& envInfo, + const BytecodeFeedback* feedback ) { IrBuilder ir(options.hooks, envInfo); @@ -757,6 +1051,9 @@ template if (FFlag::LuauRuntimeFeedback) { ir.function.recordFeedback = options.runtimeFeedback; + + if (feedback) + ir.function.feedback = *feedback; } ir.buildFunctionIr(proto); @@ -835,7 +1132,7 @@ template } } - return compileProtos(moduleId, L, codeGenContext, protos, options, stats); + return compileProtos(moduleId, L, codeGenContext, protos, options, stats, nullptr); } [[nodiscard]] static CompilationResult compileProtos( @@ -844,9 +1141,12 @@ template BaseCodeGenContext* codeGenContext, const std::vector& protos, const CompilationOptions& options, - CompilationStats* stats + CompilationStats* stats, + const std::vector* feedbacks ) { + CODEGEN_ASSERT(feedbacks == nullptr || feedbacks->size() == protos.size()); + #if defined(CODEGEN_TARGET_A64) static unsigned int cpuFeatures = getCpuFeaturesA64(); A64::AssemblyBuilderA64 build(/* logger= */ nullptr, cpuFeatures); @@ -881,8 +1181,10 @@ template { CodeGenCompilationResult protoResult = CodeGenCompilationResult::Success; + const BytecodeFeedback* feedback = feedbacks ? &(*feedbacks)[i] : nullptr; + NativeProtoExecDataPtr nativeExecData = - createNativeFunction(nullptr, build, helpers, protos[i], totalIrInstCount, options, protoResult, envInfo); + createNativeFunction(nullptr, build, helpers, protos[i], totalIrInstCount, options, protoResult, envInfo, feedback); if (nativeExecData != nullptr) { nativeProtos.push_back(std::move(nativeExecData)); diff --git a/CodeGen/src/CodeGenContext.h b/CodeGen/src/CodeGenContext.h index 1e7c955a0..f066e64a8 100644 --- a/CodeGen/src/CodeGenContext.h +++ b/CodeGen/src/CodeGenContext.h @@ -34,12 +34,34 @@ struct ModuleBindResult uint32_t functionsBound = 0; }; +struct RecordedRegTags +{ + uint32_t pcpos = 0; + uint8_t reg = 0; + uint16_t tagMask = 0; + uint64_t hits = 0; +}; + +struct RecordedUserdataTag +{ + uint32_t pcpos = 0; + uint8_t reg = 0; + uint8_t tag = 0; + bool polymorphic = false; + uint64_t hits = 0; +}; + struct FunctionBuildHistory { uint32_t rebuildCount = 0; // If Proto size changes, history has to be invalidated int sizecode = 0; + + std::vector recordedTags; + std::vector recordedUserdataTags; + + BytecodeFeedback lastFeedback; }; struct VmCodeGenData diff --git a/CodeGen/src/CodeGenLower.h b/CodeGen/src/CodeGenLower.h index 16d0bd424..b094988b4 100644 --- a/CodeGen/src/CodeGenLower.h +++ b/CodeGen/src/CodeGenLower.h @@ -104,7 +104,9 @@ inline bool lowerImpl( bool outputEnabled = options.includeAssembly || options.includeIr; std::string emptyLog; - IrToStringContext ctx{logger ? logger->text : emptyLog, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.proto}; + IrToStringContext ctx{ + logger ? logger->text : emptyLog, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.counterSets, function.proto + }; // We use this to skip outlined fallback blocks from IR/asm text output size_t textSize = ctx.result.length(); diff --git a/CodeGen/src/IrBuilder.cpp b/CodeGen/src/IrBuilder.cpp index c284b96c7..651a398ca 100644 --- a/CodeGen/src/IrBuilder.cpp +++ b/CodeGen/src/IrBuilder.cpp @@ -15,6 +15,7 @@ LUAU_FASTFLAGVARIABLE(LuauCodeGenFastpcall) LUAU_FLAGVERSION(LuauCodeGenFastpcall, 2) LUAU_FASTFLAG(LuauCodegenMarkUsed) +LUAU_FASTFLAG(LuauRuntimeFeedback) namespace Luau { @@ -760,6 +761,23 @@ void IrBuilder::beginBlock(IrOp block) target.sortkey = target.start; inTerminatedBlock = false; + + if (FFlag::LuauRuntimeFeedback && target.counterSet != ~0u && !function.counterSets[target.counterSet].counters.empty()) + inst(IrCmd::UPDATE_COUNTERS, constUint(target.counterSet)); +} + +IrCounterSet& IrBuilder::getBlockCounterSet(IrOp block) +{ + IrBlock& target = function.blockOp(block); + CODEGEN_ASSERT(target.start == ~0u && "block counters should only be reserved before building the block"); + + if (target.counterSet == ~0u) + { + target.counterSet = uint32_t(function.counterSets.size()); + function.counterSets.emplace_back(); + } + + return function.counterSets[target.counterSet]; } void IrBuilder::loadAndCheckTag(IrOp loc, uint8_t tag, IrOp fallback) @@ -782,6 +800,16 @@ void IrBuilder::checkSafeEnv(int pcpos) inst(IrCmd::CHECK_SAFE_ENV, vmExit(pcpos)); } +IrCounterSet& IrBuilder::addUpdateCounters() +{ + uint32_t index = uint32_t(function.counterSets.size()); + function.counterSets.emplace_back(); + + inst(IrCmd::UPDATE_COUNTERS, constUint(index)); + + return function.counterSets[index]; +} + void IrBuilder::clone(std::vector sourceIdxs, bool removeCurrentTerminator) { DenseHashMap instRedir; diff --git a/CodeGen/src/IrDump.cpp b/CodeGen/src/IrDump.cpp index 5c6df8996..5d780f31c 100644 --- a/CodeGen/src/IrDump.cpp +++ b/CodeGen/src/IrDump.cpp @@ -404,6 +404,8 @@ const char* getCmdName(IrCmd cmd) return "INTERRUPT"; case IrCmd::CHECK_GC: return "CHECK_GC"; + case IrCmd::UPDATE_COUNTERS: + return "UPDATE_COUNTERS"; case IrCmd::BARRIER_OBJ: return "BARRIER_OBJ"; case IrCmd::BARRIER_TABLE_BACK: @@ -1049,6 +1051,44 @@ void toStringDetailed(IrToStringContext& ctx, const IrBlock& block, uint32_t blo append(ctx.result, "\n"); } } + + if (inst.cmd == IrCmd::UPDATE_COUNTERS) + { + const IrCounterSet& counterSet = ctx.counterSets[ctx.constants[OP_A(inst).index].valueUint]; + + append(ctx.result, " ; counters: "); + + bool comma = false; + + for (const IrEntryCounter& counter : counterSet.counters) + { + if (comma) + append(ctx.result, ", "); + comma = true; + + toString(ctx, counter.operand); + + switch (counter.kind) + { + case CodeGenCounter::VmRegTagMismatch: + append(ctx.result, " tag"); + break; + case CodeGenCounter::VmRegUserdataTag: + append(ctx.result, " userdata"); + break; + default: + CODEGEN_ASSERT(!"unknown counter kind"); + break; + } + + append(ctx.result, " at pcpos %u", counter.pcpos); + + if (counter.expectedTag != kUnknownTag) + append(ctx.result, " (%s expected)", getTagName(counter.expectedTag)); + } + + append(ctx.result, "\n"); + } } void toStringDetailed( @@ -1142,7 +1182,7 @@ void toStringDetailed( std::string toString(IrFunction& function, IncludeUseInfo includeUseInfo) { std::string result; - IrToStringContext ctx{result, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.proto}; + IrToStringContext ctx{result, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.counterSets, function.proto}; for (size_t i = 0; i < function.blocks.size(); i++) { @@ -1259,7 +1299,7 @@ static void appendBlocks(IrToStringContext& ctx, const IrFunction& function, boo std::string toDot(const IrFunction& function, bool includeInst) { std::string result; - IrToStringContext ctx{result, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.proto}; + IrToStringContext ctx{result, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.counterSets, function.proto}; append(ctx.result, "digraph CFG {\n"); append(ctx.result, "node[shape=record]\n"); @@ -1301,7 +1341,7 @@ std::string toDot(const IrFunction& function, bool includeInst) std::string toDotCfg(const IrFunction& function) { std::string result; - IrToStringContext ctx{result, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.proto}; + IrToStringContext ctx{result, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.counterSets, function.proto}; append(ctx.result, "digraph CFG {\n"); append(ctx.result, "node[shape=record]\n"); @@ -1324,7 +1364,7 @@ std::string toDotCfg(const IrFunction& function) std::string toDotDjGraph(const IrFunction& function) { std::string result; - IrToStringContext ctx{result, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.proto}; + IrToStringContext ctx{result, function.blocks, function.constants, function.cfg, function.vmExitInfo, function.counterSets, function.proto}; append(ctx.result, "digraph CFG {\n"); diff --git a/CodeGen/src/IrLoweringA64.cpp b/CodeGen/src/IrLoweringA64.cpp index da1332163..32155bf01 100644 --- a/CodeGen/src/IrLoweringA64.cpp +++ b/CodeGen/src/IrLoweringA64.cpp @@ -2866,6 +2866,102 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.setLabel(skip); break; } + case IrCmd::UPDATE_COUNTERS: + { + const IrCounterSet& counterSet = function.counterSets[uintOp(OP_A(inst))]; + + if (counterSet.counters.empty()) + break; + + RegisterA64 base = regs.allocTemp(KindA64::x); + RegisterA64 slot = regs.allocTemp(KindA64::x); + RegisterA64 temp1 = regs.allocTemp(KindA64::w); + RegisterA64 temp2 = regs.allocTemp(KindA64::w); + + // Get counter slots + build.ldr(base, mem(rState, offsetof(lua_State, ci))); + build.ldr(base, mem(base, offsetof(CallInfo, p))); + build.ldr(base, mem(base, offsetof(Proto, execdata))); + + for (const IrEntryCounter& counter : counterSet.counters) + { + int vmReg = vmRegOp(counter.operand); + + // {uint32_t kind, uint32_t pcpos, uint32_t count, uint32_t metadata} + function.extraNativeData.push_back(uint32_t(counter.kind)); + function.extraNativeData.push_back(counter.pcpos); + uint32_t counterIndex = uint32_t(function.extraNativeData.size()); + function.extraNativeData.push_back(0); + + emitAddOffset(build, slot, base, size_t(function.proto->sizecode + counterIndex) * 4); + + switch (counter.kind) + { + case CodeGenCounter::VmRegTagMismatch: + { + // Counter high part is used for metadata, currently { uint8_t expectedTag + 1, uint8_t vmReg, uint16_t tagMask } + static_assert(LUA_T_COUNT <= 16, "tag mask has to fit into 16 bits"); + uint32_t expectedTag = counter.expectedTag == kUnknownTag ? 0 : counter.expectedTag + 1; + function.extraNativeData.push_back((expectedTag << 24) | (vmReg << 16)); + + // Increment (32 bit) + build.ldr(temp2, mem(slot, 0)); + build.add(temp2, temp2, uint16_t(1)); + build.str(temp2, mem(slot, 0)); + + // Record the tag in the tag mask + build.ldr(temp1, mem(rBase, vmReg * sizeof(TValue) + offsetof(TValue, tt))); + build.mov(temp2, 1); + build.lsl(temp2, temp2, temp1); + build.ldr(temp1, mem(slot, 4)); + build.orr(temp1, temp1, temp2); + build.str(temp1, mem(slot, 4)); + break; + } + case CodeGenCounter::VmRegUserdataTag: + { + // Counter high part is used for metadata, currently { uint8_t firstTag + 1, uint8_t vmReg, uint16_t flags } + // Flag bit 0 is set to mark positions with different userdata + function.extraNativeData.push_back(vmReg << 16); + + // Make sure it's actually a userdata type and count a hit if it is + Label skip, compare; + build.ldr(temp1, mem(rBase, vmReg * sizeof(TValue) + offsetof(TValue, tt))); + build.cmp(temp1, uint16_t(LUA_TUSERDATA)); + build.b(ConditionA64::NotEqual, skip); + + // Increment (32 bit) + build.ldr(temp2, mem(slot, 0)); + build.add(temp2, temp2, uint16_t(1)); + build.str(temp2, mem(slot, 0)); + + build.ldr(castReg(KindA64::x, temp1), mem(rBase, vmReg * sizeof(TValue) + offsetof(TValue, value.gc))); + build.ldrb(temp1, mem(castReg(KindA64::x, temp1), offsetof(Udata, tag))); + build.add(temp1, temp1, uint16_t(1)); + + // If the value is not yet set we record it, if it changes we mark it as polymorphic + build.ldrb(temp2, mem(slot, 7)); + build.cbnz(temp2, compare); + build.strb(temp1, mem(slot, 7)); + build.b(skip); + + build.setLabel(compare); + build.cmp(temp2, temp1); + build.b(ConditionA64::Equal, skip); + build.ldrb(temp2, mem(slot, 4)); + build.orr(temp2, temp2, 1u); + build.strb(temp2, mem(slot, 4)); + + build.setLabel(skip); + break; + } + default: + CODEGEN_ASSERT(!"unknown counter kind"); + break; + } + } + break; + } case IrCmd::BARRIER_OBJ: { RegisterA64 temp = regs.allocTemp(KindA64::x); diff --git a/CodeGen/src/IrLoweringX64.cpp b/CodeGen/src/IrLoweringX64.cpp index c099b0ea4..44e75077c 100644 --- a/CodeGen/src/IrLoweringX64.cpp +++ b/CodeGen/src/IrLoweringX64.cpp @@ -2632,6 +2632,91 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) case IrCmd::CHECK_GC: callStepGc(regs, build); break; + case IrCmd::UPDATE_COUNTERS: + { + const IrCounterSet& counterSet = function.counterSets[uintOp(OP_A(inst))]; + + if (counterSet.counters.empty()) + break; + + ScopedRegX64 tmp{regs, SizeX64::qword}; + ScopedRegX64 tmp2{regs, SizeX64::dword}; + ScopedRegX64 tmp3{regs, SizeX64::dword}; + + // Get counter slots + build.mov(tmp.reg, qword[rState + offsetof(lua_State, ci)]); + build.mov(tmp.reg, qword[tmp.reg + offsetof(CallInfo, p)]); + build.mov(tmp.reg, qword[tmp.reg + offsetof(Proto, execdata)]); + + for (const IrEntryCounter& counter : counterSet.counters) + { + // {uint32_t kind, uint32_t pcpos, uint32_t count, uint32_t data} + function.extraNativeData.push_back(uint32_t(counter.kind)); + function.extraNativeData.push_back(counter.pcpos); + uint32_t counterIndex = uint32_t(function.extraNativeData.size()); + function.extraNativeData.push_back(0); + + switch (counter.kind) + { + case CodeGenCounter::VmRegTagMismatch: + { + // Counter high part is used for metadata, currently { uint8_t expectedTag + 1, uint8_t vmReg, uint16_t tagMask } + uint32_t expectedTag = counter.expectedTag == kUnknownTag ? 0 : counter.expectedTag + 1; + function.extraNativeData.push_back((expectedTag << 24) | (vmRegOp(counter.operand) << 16)); + + // Increment counter (32 bit) + build.inc(dword[tmp.reg + uint32_t(function.proto->sizecode + counterIndex) * 4]); + + // Record the tag in the tag mask + OperandX64 metadata = dword[tmp.reg + uint32_t(function.proto->sizecode + counterIndex + 1) * 4]; + + build.mov(tmp2.reg, luauRegTag(vmRegOp(counter.operand))); + build.mov(tmp3.reg, metadata); + build.bts(tmp3.reg, tmp2.reg); + build.mov(metadata, tmp3.reg); + break; + } + case CodeGenCounter::VmRegUserdataTag: + { + // Counter high part is used for metadata, currently { uint8_t firstTag + 1, uint8_t vmReg, uint16_t flags } + // Flag bit 0 is set to mark positions with different userdata + function.extraNativeData.push_back(vmRegOp(counter.operand) << 16); + + uint32_t metadataOffset = uint32_t(function.proto->sizecode + counterIndex + 1) * 4; + + Label skip, compare; + + // Make sure it's actually a userdata type and count a hit if it is + build.cmp(luauRegTag(vmRegOp(counter.operand)), LUA_TUSERDATA); + build.jcc(ConditionX64::NotEqual, skip); + + // Increment counter (32 bit) + build.inc(dword[tmp.reg + uint32_t(function.proto->sizecode + counterIndex) * 4]); + + build.mov(qwordReg(tmp2.reg), luauRegValue(vmRegOp(counter.operand))); + build.movzx(tmp2.reg, byte[qwordReg(tmp2.reg) + offsetof(Udata, tag)]); + build.inc(tmp2.reg); + + // If the value is not yet set we record it, if it changes we mark it as polymorphic + build.cmp(byte[tmp.reg + metadataOffset + 3], 0); + build.jcc(ConditionX64::NotEqual, compare); + build.mov(byte[tmp.reg + metadataOffset + 3], byteReg(tmp2.reg)); + + build.setLabel(compare); + build.cmp(byte[tmp.reg + metadataOffset + 3], byteReg(tmp2.reg)); + build.jcc(ConditionX64::Equal, skip); + build.or_(byte[tmp.reg + metadataOffset], 1); + + build.setLabel(skip); + break; + } + default: + CODEGEN_ASSERT(!"unknown counter kind"); + break; + } + } + break; + } case IrCmd::BARRIER_OBJ: callBarrierObject(regs, build, regOp(OP_A(inst)), OP_A(inst), noreg, OP_B(inst), OP_C(inst).kind == IrOpKind::Undef ? -1 : tagOp(OP_C(inst))); break; diff --git a/CodeGen/src/IrTranslation.cpp b/CodeGen/src/IrTranslation.cpp index 5b6a41c84..13852003f 100644 --- a/CodeGen/src/IrTranslation.cpp +++ b/CodeGen/src/IrTranslation.cpp @@ -15,6 +15,7 @@ LUAU_FASTFLAG(LuauCodegenInteger3) LUAU_FASTFLAGVARIABLE(LuauCodegenIntegerCompare) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) +LUAU_FASTFLAG(LuauRuntimeFeedback) namespace Luau { @@ -52,6 +53,91 @@ static IrOp getInitializedFallback(IrBuilder& build, IrOp& fallback, int pcpos) return fallback; } +static void recordTagMismatchCounter(IrBuilder& build, IrCounterSet& counterSet, IrOp op, uint32_t pcpos, uint8_t expectedTag) +{ + IrEntryCounter counter; + counter.kind = CodeGenCounter::VmRegTagMismatch; + counter.operand = op; + counter.pcpos = pcpos; + counter.expectedTag = expectedTag; + + counterSet.counters.push_back(counter); +} + +static void recordFallbackTagMismatch(IrBuilder& build, IrOp fallback, IrOp op, uint32_t pcpos, uint8_t expectedTag) +{ + if (build.function.recordFeedback && fallback.kind != IrOpKind::None) + recordTagMismatchCounter(build, build.getBlockCounterSet(fallback), op, pcpos, expectedTag); +} + +static void recordUserdataTagCounter(IrBuilder& build, IrCounterSet& counterSet, IrOp op, uint32_t pcpos) +{ + IrEntryCounter counter; + counter.kind = CodeGenCounter::VmRegUserdataTag; + counter.operand = op; + counter.pcpos = pcpos; + + counterSet.counters.push_back(counter); +} + +static void recordFallbackUserdataTag(IrBuilder& build, IrOp fallback, IrOp op, uint32_t pcpos) +{ + if (build.function.recordFeedback && fallback.kind != IrOpKind::None) + recordUserdataTagCounter(build, build.getBlockCounterSet(fallback), op, pcpos); +} + +// On the main execution path, this places a recording of both the register tag and userdata tag +static void recordUserdataTag(IrBuilder& build, int reg, int pcpos) +{ + if (!build.function.recordFeedback) + return; + + IrCounterSet& counterSet = build.addUpdateCounters(); + + recordTagMismatchCounter(build, counterSet, build.vmReg(uint8_t(reg)), pcpos, LUA_TUSERDATA); + recordUserdataTagCounter(build, counterSet, build.vmReg(uint8_t(reg)), pcpos); +} + +static LuauBytecodeType getRecordedVmRegType(IrBuilder& build, uint8_t bcType, int pcpos, int reg) +{ + if (bcType != LBC_TYPE_ANY || reg == -1) + return LBC_TYPE_ANY; + + return getTagFeedback(build.function, pcpos, reg); +} + +static void checkUserdataWithFeedback(IrBuilder& build, const BytecodeUserdataFeedback& feedback, IrOp fallback, int pcpos) +{ + build.loadAndCheckTag(build.vmReg(feedback.reg), LUA_TUSERDATA, fallback); + recordFallbackTagMismatch(build, fallback, build.vmReg(feedback.reg), pcpos, LUA_TUSERDATA); + + IrOp udata = build.inst(IrCmd::LOAD_POINTER, build.vmReg(feedback.reg)); + build.inst(IrCmd::CHECK_USERDATA_TAG, udata, build.constInt(feedback.tag), fallback); + recordFallbackUserdataTag(build, fallback, build.vmReg(feedback.reg), pcpos); +} + +static bool isGenericArithFeedback(LuauBytecodeType recorded) +{ + return recorded != LBC_TYPE_ANY && recorded != LBC_TYPE_NUMBER && recorded != LBC_TYPE_VECTOR; +} + +static void checkArithOperandTag(IrBuilder& build, IrOp& fallback, int reg, uint8_t tag, uint8_t type, int pcpos) +{ + CODEGEN_ASSERT(tag == LUA_TNUMBER || tag == LUA_TVECTOR); + + IrOp tagOp = build.inst(IrCmd::LOAD_TAG, build.vmReg(reg)); + + if (type == (tag == LUA_TNUMBER ? LBC_TYPE_NUMBER : LBC_TYPE_VECTOR)) + { + build.inst(IrCmd::CHECK_TAG, tagOp, build.constTag(tag), build.vmExit(pcpos)); + } + else + { + build.inst(IrCmd::CHECK_TAG, tagOp, build.constTag(tag), getInitializedFallback(build, fallback, pcpos)); + recordFallbackTagMismatch(build, fallback, build.vmReg(reg), pcpos, tag); + } +} + static IrOp loadDoubleOrConstant(IrBuilder& build, IrOp arg) { if (arg.kind == IrOpKind::VmConst) @@ -628,12 +714,26 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, BytecodeTypes bcTypes = build.function.getBytecodeTypesAt(pcpos); + LuauBytecodeType recordedA = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; + LuauBytecodeType recordedB = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.b, pcpos, rc) : LBC_TYPE_ANY; + + bool vectorA = bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedA == LBC_TYPE_VECTOR); + bool vectorB = bcTypes.b == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedB == LBC_TYPE_VECTOR); + // Special fast-paths for vectors, matching the cases we have in VM - if (bcTypes.a == LBC_TYPE_VECTOR && bcTypes.b == LBC_TYPE_VECTOR && + if ((FFlag::LuauRuntimeFeedback ? vectorA && vectorB : bcTypes.a == LBC_TYPE_VECTOR && bcTypes.b == LBC_TYPE_VECTOR) && (tm == TM_ADD || tm == TM_SUB || tm == TM_MUL || tm == TM_DIV || tm == TM_IDIV)) { - build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); - build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rc)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + if (FFlag::LuauRuntimeFeedback) + { + checkArithOperandTag(build, fallback, rb, LUA_TVECTOR, bcTypes.a, pcpos); + checkArithOperandTag(build, fallback, rc, LUA_TVECTOR, bcTypes.b, pcpos); + } + else + { + build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rc)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + } if constexpr (LUA_VECTOR_DOUBLE == 1) { @@ -716,21 +816,37 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, build.inst(IrCmd::STORE_TVALUE, build.vmReg(ra), result); } + + if (FFlag::LuauRuntimeFeedback) + translateBinaryNumericFallbackIfRequired(build, fallback, ra, opb, opc, tm, pcpos); + return; } - else if (!isUserdataBytecodeType(bcTypes.a) && bcTypes.b == LBC_TYPE_VECTOR && (tm == TM_MUL || tm == TM_DIV || tm == TM_IDIV)) + else if (!isUserdataBytecodeType(bcTypes.a) && + (FFlag::LuauRuntimeFeedback ? !isGenericArithFeedback(recordedA) && vectorB : bcTypes.b == LBC_TYPE_VECTOR) && + (tm == TM_MUL || tm == TM_DIV || tm == TM_IDIV)) { - if (rb != -1) + if (FFlag::LuauRuntimeFeedback) { - build.inst( - IrCmd::CHECK_TAG, - build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)), - build.constTag(LUA_TNUMBER), - bcTypes.a == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) - ); + if (rb != -1) + checkArithOperandTag(build, fallback, rb, LUA_TNUMBER, bcTypes.a, pcpos); + + checkArithOperandTag(build, fallback, rc, LUA_TVECTOR, bcTypes.b, pcpos); } + else + { + if (rb != -1) + { + build.inst( + IrCmd::CHECK_TAG, + build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)), + build.constTag(LUA_TNUMBER), + bcTypes.a == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) + ); + } - build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rc)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rc)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + } if constexpr (LUA_VECTOR_DOUBLE == 1) { @@ -786,18 +902,30 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, translateBinaryNumericFallbackIfRequired(build, fallback, ra, opb, opc, tm, pcpos); return; } - else if (bcTypes.a == LBC_TYPE_VECTOR && !isUserdataBytecodeType(bcTypes.b) && (tm == TM_MUL || tm == TM_DIV || tm == TM_IDIV)) + else if ((FFlag::LuauRuntimeFeedback ? vectorA && !isUserdataBytecodeType(bcTypes.b) && !isGenericArithFeedback(recordedB) + : bcTypes.a == LBC_TYPE_VECTOR && !isUserdataBytecodeType(bcTypes.b)) && + (tm == TM_MUL || tm == TM_DIV || tm == TM_IDIV)) { - build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + if (FFlag::LuauRuntimeFeedback) + { + checkArithOperandTag(build, fallback, rb, LUA_TVECTOR, bcTypes.a, pcpos); - if (rc != -1) + if (rc != -1) + checkArithOperandTag(build, fallback, rc, LUA_TNUMBER, bcTypes.b, pcpos); + } + else { - build.inst( - IrCmd::CHECK_TAG, - build.inst(IrCmd::LOAD_TAG, build.vmReg(rc)), - build.constTag(LUA_TNUMBER), - bcTypes.b == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) - ); + build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + + if (rc != -1) + { + build.inst( + IrCmd::CHECK_TAG, + build.inst(IrCmd::LOAD_TAG, build.vmReg(rc)), + build.constTag(LUA_TNUMBER), + bcTypes.b == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) + ); + } } if constexpr (LUA_VECTOR_DOUBLE == 1) @@ -855,6 +983,45 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, return; } + // If we recorded a userdata at this position, we can do a fast path or record a detailed userdata type counter (or nothing) + if (FFlag::LuauRuntimeFeedback && (recordedA == LBC_TYPE_USERDATA || recordedB == LBC_TYPE_USERDATA) && build.hostHooks.userdataMetamethod) + { + auto feedbackA = recordedA == LBC_TYPE_USERDATA ? getUserdataFeedback(build.function, pcpos, rb) : std::nullopt; + auto feedbackB = recordedB == LBC_TYPE_USERDATA ? getUserdataFeedback(build.function, pcpos, rc) : std::nullopt; + + bool specializedA = recordedA != LBC_TYPE_USERDATA || (feedbackA && feedbackA->type != LBC_TYPE_ANY); + bool specializedB = recordedB != LBC_TYPE_USERDATA || (feedbackB && feedbackB->type != LBC_TYPE_ANY); + + if (specializedA && specializedB) + { + fallback = build.fallbackBlock(pcpos); + + if (feedbackA) + checkUserdataWithFeedback(build, *feedbackA, fallback, pcpos); + + if (feedbackB && rc != rb) + checkUserdataWithFeedback(build, *feedbackB, fallback, pcpos); + + uint8_t typeA = feedbackA ? feedbackA->type : bcTypes.a; + uint8_t typeB = feedbackB ? feedbackB->type : bcTypes.b; + + if (!build.hostHooks.userdataMetamethod(build, typeA, typeB, ra, opb, opc, tmToHostMetamethod(tm), pcpos)) + { + build.inst(IrCmd::SET_SAVEDPC, build.constUint(pcpos + 1)); + build.inst(IrCmd::DO_ARITH, build.vmReg(ra), opb, opc, build.constInt(tm)); + } + + translateBinaryNumericFallbackIfRequired(build, fallback, ra, opb, opc, tm, pcpos); + return; + } + + if (recordedA == LBC_TYPE_USERDATA && !feedbackA) + recordUserdataTag(build, rb, pcpos); + + if (recordedB == LBC_TYPE_USERDATA && !feedbackB && rc != rb) + recordUserdataTag(build, rc, pcpos); + } + if (isUserdataBytecodeType(bcTypes.a) || isUserdataBytecodeType(bcTypes.b)) { if (build.hostHooks.userdataMetamethod && @@ -866,27 +1033,46 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, return; } - // fast-path: number - if (rb != -1) + if (FFlag::LuauRuntimeFeedback && (isGenericArithFeedback(recordedA) || isGenericArithFeedback(recordedB))) { - IrOp tb = build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)); - build.inst( - IrCmd::CHECK_TAG, - tb, - build.constTag(LUA_TNUMBER), - bcTypes.a == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) - ); + build.inst(IrCmd::SET_SAVEDPC, build.constUint(pcpos + 1)); + build.inst(IrCmd::DO_ARITH, build.vmReg(ra), opb, opc, build.constInt(tm)); + return; } - if (rc != -1 && rc != rb) + if (FFlag::LuauRuntimeFeedback) { - IrOp tc = build.inst(IrCmd::LOAD_TAG, build.vmReg(rc)); - build.inst( - IrCmd::CHECK_TAG, - tc, - build.constTag(LUA_TNUMBER), - bcTypes.b == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) - ); + // fast-path: number + if (rb != -1) + checkArithOperandTag(build, fallback, rb, LUA_TNUMBER, bcTypes.a, pcpos); + + if (rc != -1 && rc != rb) + checkArithOperandTag(build, fallback, rc, LUA_TNUMBER, bcTypes.b, pcpos); + } + else + { + // fast-path: number + if (rb != -1) + { + IrOp tb = build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)); + build.inst( + IrCmd::CHECK_TAG, + tb, + build.constTag(LUA_TNUMBER), + bcTypes.a == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) + ); + } + + if (rc != -1 && rc != rb) + { + IrOp tc = build.inst(IrCmd::LOAD_TAG, build.vmReg(rc)); + build.inst( + IrCmd::CHECK_TAG, + tc, + build.constTag(LUA_TNUMBER), + bcTypes.b == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) + ); + } } IrOp vb = loadDoubleOrConstant(build, opb); @@ -997,9 +1183,15 @@ void translateInstMinus(IrBuilder& build, const Instruction* pc, int pcpos) int ra = LUAU_INSN_A(*pc); int rb = LUAU_INSN_B(*pc); - if (bcTypes.a == LBC_TYPE_VECTOR) + IrOp fallback; + LuauBytecodeType recordedA = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; + + if (bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedA == LBC_TYPE_VECTOR)) { - build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + if (FFlag::LuauRuntimeFeedback) + checkArithOperandTag(build, fallback, rb, LUA_TVECTOR, bcTypes.a, pcpos); + else + build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); if constexpr (LUA_VECTOR_DOUBLE == 1) { @@ -1023,6 +1215,10 @@ void translateInstMinus(IrBuilder& build, const Instruction* pc, int pcpos) va = build.inst(IrCmd::TAG_VECTOR, va); build.inst(IrCmd::STORE_TVALUE, build.vmReg(ra), va); } + + if (FFlag::LuauRuntimeFeedback) + translateBinaryNumericFallbackIfRequired(build, fallback, ra, build.vmReg(rb), build.vmReg(rb), TM_UNM, pcpos); + return; } @@ -1037,15 +1233,53 @@ void translateInstMinus(IrBuilder& build, const Instruction* pc, int pcpos) return; } - IrOp fallback; + // If we recorded a userdata at this position, we can do a fast path or record a detailed userdata type counter (or nothing) + if (FFlag::LuauRuntimeFeedback && recordedA == LBC_TYPE_USERDATA && build.hostHooks.userdataMetamethod) + { + auto feedback = getUserdataFeedback(build.function, pcpos, rb); - IrOp tb = build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)); - build.inst( - IrCmd::CHECK_TAG, - tb, - build.constTag(LUA_TNUMBER), - bcTypes.a == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) - ); + if (feedback && feedback->type != LBC_TYPE_ANY) + { + fallback = build.fallbackBlock(pcpos); + + checkUserdataWithFeedback(build, *feedback, fallback, pcpos); + + if (!build.hostHooks.userdataMetamethod(build, feedback->type, bcTypes.b, ra, build.vmReg(rb), {}, tmToHostMetamethod(TM_UNM), pcpos)) + { + build.inst(IrCmd::SET_SAVEDPC, build.constUint(pcpos + 1)); + build.inst(IrCmd::DO_ARITH, build.vmReg(ra), build.vmReg(rb), build.vmReg(rb), build.constInt(TM_UNM)); + } + + translateBinaryNumericFallbackIfRequired(build, fallback, ra, build.vmReg(rb), build.vmReg(rb), TM_UNM, pcpos); + return; + } + + if (!feedback) + recordUserdataTag(build, rb, pcpos); + } + + // If we recorded a type that doesn't have any fast paths, place the 'fallback' operation as the main one + if (FFlag::LuauRuntimeFeedback && isGenericArithFeedback(recordedA)) + { + build.inst(IrCmd::SET_SAVEDPC, build.constUint(pcpos + 1)); + build.inst(IrCmd::DO_ARITH, build.vmReg(ra), build.vmReg(rb), build.vmReg(rb), build.constInt(TM_UNM)); + return; + } + + if (FFlag::LuauRuntimeFeedback) + { + checkArithOperandTag(build, fallback, rb, LUA_TNUMBER, bcTypes.a, pcpos); + } + else + { + IrOp tb = build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)); + build.inst( + IrCmd::CHECK_TAG, + tb, + build.constTag(LUA_TNUMBER), + bcTypes.a == LBC_TYPE_NUMBER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) + ); + } // fast-path: number IrOp vb = build.inst(IrCmd::LOAD_DOUBLE, build.vmReg(rb)); @@ -1056,7 +1290,11 @@ void translateInstMinus(IrBuilder& build, const Instruction* pc, int pcpos) if (ra != rb) build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TNUMBER)); - if (fallback.kind != IrOpKind::None) + if (FFlag::LuauRuntimeFeedback) + { + translateBinaryNumericFallbackIfRequired(build, fallback, ra, build.vmReg(rb), build.vmReg(rb), TM_UNM, pcpos); + } + else if (fallback.kind != IrOpKind::None) { IrOp next = build.blockAtInst(pcpos + 1); FallbackStreamScope scope(build, fallback, next); @@ -1761,12 +1999,68 @@ void translateInstGetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) uint32_t aux = LUAU_INSN_OP(*pc) == LOP_GETUDATAKS ? LUAU_INSN_AUX_KV16(pc[1]) : pc[1]; BytecodeTypes bcTypes = build.function.getBytecodeTypesAt(pcpos); + LuauBytecodeType recordedType = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; + + // If we recorded a userdata at this position, we can do a fast path or record a detailed userdata type counter (or nothing) + if (FFlag::LuauRuntimeFeedback && recordedType == LBC_TYPE_USERDATA && build.hostHooks.userdataAccess) + { + auto feedback = getUserdataFeedback(build.function, pcpos, rb); + + if (feedback && feedback->type != LBC_TYPE_ANY) + { + IrOp fallback = build.fallbackBlock(pcpos); + + checkUserdataWithFeedback(build, *feedback, fallback, pcpos); + + TString* str = gco2ts(build.function.proto->k[aux].value.gc); + const char* field = getstr(str); + + if (!build.hostHooks.userdataAccess(build, feedback->type, field, str->len, ra, rb, pcpos)) + build.inst(IrCmd::FALLBACK_GETTABLEKS, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + + IrOp next = build.blockAtInst(pcpos + 2); + FallbackStreamScope scope(build, fallback, next); + + build.inst(IrCmd::FALLBACK_GETTABLEKS, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + build.inst(IrCmd::JUMP, next); + return; + } + + if (!feedback) + recordUserdataTag(build, rb, pcpos); + } + + // If we recorded a type that doesn't have any fast paths, place the 'fallback' operation as the main one + if (FFlag::LuauRuntimeFeedback && recordedType != LBC_TYPE_ANY && recordedType != LBC_TYPE_VECTOR && recordedType != LBC_TYPE_TABLE) + { + build.inst(IrCmd::FALLBACK_GETTABLEKS, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + return; + } IrOp tb = build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)); - if (bcTypes.a == LBC_TYPE_VECTOR) + if (bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedType == LBC_TYPE_VECTOR)) { - build.inst(IrCmd::CHECK_TAG, tb, build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + IrOp fallback; + + if (FFlag::LuauRuntimeFeedback) + { + if (bcTypes.a == LBC_TYPE_VECTOR) + { + build.inst(IrCmd::CHECK_TAG, tb, build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + } + else + { + fallback = build.fallbackBlock(pcpos); + + build.inst(IrCmd::CHECK_TAG, tb, build.constTag(LUA_TVECTOR), fallback); + recordFallbackTagMismatch(build, fallback, build.vmReg(rb), pcpos, LUA_TVECTOR); + } + } + else + { + build.inst(IrCmd::CHECK_TAG, tb, build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); + } TString* str = gco2ts(build.function.proto->k[aux].value.gc); const char* field = getstr(str); @@ -1823,10 +2117,29 @@ void translateInstGetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) } else { - if (build.hostHooks.vectorAccess && build.hostHooks.vectorAccess(build, field, str->len, ra, rb, pcpos)) - return; + if (FFlag::LuauRuntimeFeedback) + { + if (!build.hostHooks.vectorAccess || !build.hostHooks.vectorAccess(build, field, str->len, ra, rb, pcpos)) + { + build.inst(IrCmd::FALLBACK_GETTABLEKS, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + } + } + else + { + if (build.hostHooks.vectorAccess && build.hostHooks.vectorAccess(build, field, str->len, ra, rb, pcpos)) + return; + + build.inst(IrCmd::FALLBACK_GETTABLEKS, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + } + } + + if (FFlag::LuauRuntimeFeedback && fallback.kind != IrOpKind::None) + { + IrOp next = build.blockAtInst(pcpos + 2); + FallbackStreamScope scope(build, fallback, next); build.inst(IrCmd::FALLBACK_GETTABLEKS, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + build.inst(IrCmd::JUMP, next); } return; @@ -1853,6 +2166,9 @@ void translateInstGetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) build.inst(IrCmd::CHECK_TAG, tb, build.constTag(LUA_TTABLE), bcTypes.a == LBC_TYPE_TABLE ? build.vmExit(pcpos) : fallback); + if (FFlag::LuauRuntimeFeedback && bcTypes.a != LBC_TYPE_TABLE) + recordFallbackTagMismatch(build, fallback, build.vmReg(rb), pcpos, LUA_TTABLE); + IrOp vb = build.inst(IrCmd::LOAD_POINTER, build.vmReg(rb)); IrOp addrSlotEl = build.inst(IrCmd::GET_SLOT_NODE_ADDR, vb, build.constUint(pcpos), build.vmConst(aux)); @@ -1878,8 +2194,10 @@ void translateInstSetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) uint32_t aux = LUAU_INSN_OP(*pc) == LOP_SETUDATAKS ? LUAU_INSN_AUX_KV16(pc[1]) : pc[1]; BytecodeTypes bcTypes = build.function.getBytecodeTypesAt(pcpos); + LuauBytecodeType recordedType = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; - if (FFlag::DebugLuauUserDefinedClassesRuntime && bcTypes.a == LBC_TYPE_OBJECT) + if ((FFlag::DebugLuauUserDefinedClassesRuntime && bcTypes.a == LBC_TYPE_OBJECT) || + (FFlag::LuauRuntimeFeedback && recordedType != LBC_TYPE_ANY && recordedType != LBC_TYPE_TABLE)) { build.inst(IrCmd::FALLBACK_SETTABLEKS, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); return; @@ -1899,6 +2217,9 @@ void translateInstSetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) build.inst(IrCmd::CHECK_TAG, tb, build.constTag(LUA_TTABLE), bcTypes.a == LBC_TYPE_TABLE ? build.vmExit(pcpos) : fallback); + if (FFlag::LuauRuntimeFeedback && bcTypes.a != LBC_TYPE_TABLE) + recordFallbackTagMismatch(build, fallback, build.vmReg(rb), pcpos, LUA_TTABLE); + IrOp vb = build.inst(IrCmd::LOAD_POINTER, build.vmReg(rb)); IrOp addrSlotEl = build.inst(IrCmd::GET_SLOT_NODE_ADDR, vb, build.constUint(pcpos), build.vmConst(aux)); @@ -2001,6 +2322,42 @@ void translateInstCapture(IrBuilder& build, const Instruction* pc, int pcpos) } } +static void translateNamecallFallback(IrBuilder& build, const Instruction* pc, int pcpos, uint32_t aux, IrOp fallback) +{ + int ra = LUAU_INSN_A(*pc); + int rb = LUAU_INSN_B(*pc); + + IrOp next = build.blockAtInst(pcpos + getOpLength(LuauOpcode(LOP_NAMECALL))); + FallbackStreamScope scope(build, fallback, next); + + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + build.inst(IrCmd::JUMP, next); +} + +// Fast-paths skip both namecall and call, so their fallback needs both performed +static void translateNamecallFallbackWithCall(IrBuilder& build, const Instruction* pc, int pcpos, uint32_t aux, IrOp fallback) +{ + int ra = LUAU_INSN_A(*pc); + int rb = LUAU_INSN_B(*pc); + + Instruction call = pc[2]; + int callra = LUAU_INSN_A(call); + int nparams = LUAU_INSN_B(call) - 1; + int nresults = LUAU_INSN_C(call) - 1; + + int callpc = pcpos + getOpLength(LuauOpcode(LOP_NAMECALL)); + int nextpc = callpc + getOpLength(LuauOpcode(LUAU_INSN_OP(call))); + + IrOp next = build.blockAtInst(nextpc); + FallbackStreamScope scope(build, fallback, next); + + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + build.inst(IrCmd::INTERRUPT, build.constUint(callpc)); + build.inst(IrCmd::SET_SAVEDPC, build.constUint(nextpc)); + build.inst(IrCmd::CALL, build.vmReg(callra), build.constInt(nparams), build.constInt(nresults)); + build.inst(IrCmd::JUMP, next); +} + bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) { int ra = LUAU_INSN_A(*pc); @@ -2010,10 +2367,65 @@ bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) uint32_t aux = LUAU_INSN_OP(*pc) == LOP_NAMECALLUDATA ? LUAU_INSN_AUX_KV16(pc[1]) : pc[1]; BytecodeTypes bcTypes = build.function.getBytecodeTypesAt(pcpos); + LuauBytecodeType recordedType = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; - if (bcTypes.a == LBC_TYPE_VECTOR) + // If we recorded a userdata at this position, we can do a fast path or record a detailed userdata type counter (or nothing) + if (FFlag::LuauRuntimeFeedback && recordedType == LBC_TYPE_USERDATA && build.hostHooks.userdataNamecall) { - build.loadAndCheckTag(build.vmReg(rb), LUA_TVECTOR, build.vmExit(pcpos)); + auto feedback = getUserdataFeedback(build.function, pcpos, rb); + + if (feedback && feedback->type != LBC_TYPE_ANY) + { + IrOp fallback = build.fallbackBlock(pcpos); + checkUserdataWithFeedback(build, *feedback, fallback, pcpos); + + Instruction call = pc[2]; + CODEGEN_ASSERT(LUAU_INSN_OP(call) == LOP_CALLFB || LUAU_INSN_OP(call) == LOP_CALL); + + int callra = LUAU_INSN_A(call); + int nparams = LUAU_INSN_B(call) - 1; + int nresults = LUAU_INSN_C(call) - 1; + + TString* str = gco2ts(build.function.proto->k[aux].value.gc); + const char* field = getstr(str); + + if (build.hostHooks.userdataNamecall(build, feedback->type, field, str->len, callra, rb, nparams, nresults, pcpos)) + { + translateNamecallFallbackWithCall(build, pc, pcpos, aux, fallback); + return true; + } + + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + translateNamecallFallback(build, pc, pcpos, aux, fallback); + return false; + } + + if (!feedback) + recordUserdataTag(build, rb, pcpos); + } + + // If we recorded a type that doesn't have any fast paths, place the 'fallback' operation as the main one + if (FFlag::LuauRuntimeFeedback && recordedType != LBC_TYPE_ANY && recordedType != LBC_TYPE_VECTOR && recordedType != LBC_TYPE_TABLE) + { + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + return false; + } + + if (bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedType == LBC_TYPE_VECTOR)) + { + IrOp fallback; + + if (bcTypes.a == LBC_TYPE_VECTOR) + { + build.loadAndCheckTag(build.vmReg(rb), LUA_TVECTOR, build.vmExit(pcpos)); + } + else if (FFlag::LuauRuntimeFeedback) + { + fallback = build.fallbackBlock(pcpos); + + build.loadAndCheckTag(build.vmReg(rb), LUA_TVECTOR, fallback); + recordFallbackTagMismatch(build, fallback, build.vmReg(rb), pcpos, LUA_TVECTOR); + } if (build.hostHooks.vectorNamecall) { @@ -2028,10 +2440,19 @@ bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) const char* field = getstr(str); if (build.hostHooks.vectorNamecall(build, field, str->len, callra, rb, nparams, nresults, pcpos)) + { + if (FFlag::LuauRuntimeFeedback && fallback.kind != IrOpKind::None) + translateNamecallFallbackWithCall(build, pc, pcpos, aux, fallback); + return true; + } } build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + + if (FFlag::LuauRuntimeFeedback && fallback.kind != IrOpKind::None) + translateNamecallFallback(build, pc, pcpos, aux, fallback); + return false; } @@ -2065,6 +2486,10 @@ bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) IrOp secondFastPath = build.block(IrBlockKind::Internal); build.loadAndCheckTag(build.vmReg(rb), LUA_TTABLE, bcTypes.a == LBC_TYPE_TABLE ? build.vmExit(pcpos) : fallback); + + if (FFlag::LuauRuntimeFeedback && bcTypes.a != LBC_TYPE_TABLE) + recordFallbackTagMismatch(build, fallback, build.vmReg(rb), pcpos, LUA_TTABLE); + IrOp table = build.inst(IrCmd::LOAD_POINTER, build.vmReg(rb)); CODEGEN_ASSERT(build.function.proto); diff --git a/CodeGen/src/IrUtils.cpp b/CodeGen/src/IrUtils.cpp index ccda7db89..237b43420 100644 --- a/CodeGen/src/IrUtils.cpp +++ b/CodeGen/src/IrUtils.cpp @@ -356,6 +356,7 @@ IrValueKind getCmdValueKind(IrCmd cmd) case IrCmd::CHECK_CMP_INT64: case IrCmd::INTERRUPT: case IrCmd::CHECK_GC: + case IrCmd::UPDATE_COUNTERS: case IrCmd::BARRIER_OBJ: case IrCmd::BARRIER_TABLE_BACK: case IrCmd::BARRIER_TABLE_FORWARD: @@ -517,6 +518,91 @@ bool isExpectedOrUnknownBytecodeType(uint8_t ty, LuauBytecodeType expected) return ty == LBC_TYPE_ANY || ty == expected; } +static LuauBytecodeType getBytecodeTypeForTag(uint8_t tag) +{ + switch (tag) + { + case LUA_TNIL: + return LBC_TYPE_NIL; + case LUA_TBOOLEAN: + return LBC_TYPE_BOOLEAN; + case LUA_TLIGHTUSERDATA: + return LBC_TYPE_ANY; // Doesn't have an LBC mapping + case LUA_TNUMBER: + return LBC_TYPE_NUMBER; + case LUA_TINTEGER: + return LBC_TYPE_INTEGER; + case LUA_TVECTOR: + return LBC_TYPE_VECTOR; + case LUA_TSTRING: + return LBC_TYPE_STRING; + case LUA_TTABLE: + return LBC_TYPE_TABLE; + case LUA_TFUNCTION: + return LBC_TYPE_FUNCTION; + case LUA_TUSERDATA: + return LBC_TYPE_USERDATA; + case LUA_TTHREAD: + return LBC_TYPE_THREAD; + case LUA_TBUFFER: + return LBC_TYPE_BUFFER; + case LUA_TCLASS: + return LBC_TYPE_CLASS; + case LUA_TOBJECT: + return LBC_TYPE_OBJECT; + } + + return LBC_TYPE_ANY; +} + +LuauBytecodeType getTagFeedback(const IrFunction& function, int pcpos, int reg) +{ + const std::vector& tags = function.feedback.tags; + + auto it = std::lower_bound( + tags.begin(), + tags.end(), + uint32_t(pcpos), + [](const BytecodeTagFeedback& item, uint32_t pcpos) + { + return item.pcpos < pcpos; + } + ); + + // There could be multiple items at the position + for (; it != tags.end() && it->pcpos == uint32_t(pcpos); ++it) + { + if (it->reg == reg) + return getBytecodeTypeForTag(it->tag); + } + + return LBC_TYPE_ANY; +} + +std::optional getUserdataFeedback(const IrFunction& function, int pcpos, int reg) +{ + const std::vector& userdataTypes = function.feedback.userdataTypes; + + auto it = std::lower_bound( + userdataTypes.begin(), + userdataTypes.end(), + uint32_t(pcpos), + [](const BytecodeUserdataFeedback& item, uint32_t pcpos) + { + return item.pcpos < pcpos; + } + ); + + // There could be multiple items at the position + for (; it != userdataTypes.end() && it->pcpos == uint32_t(pcpos); ++it) + { + if (it->reg == reg) + return *it; + } + + return std::nullopt; +} + HostMetamethod tmToHostMetamethod(int tm) { switch (TMS(tm)) diff --git a/CodeGen/src/OptimizeConstProp.cpp b/CodeGen/src/OptimizeConstProp.cpp index 01fdd6f45..0d0e4ff76 100644 --- a/CodeGen/src/OptimizeConstProp.cpp +++ b/CodeGen/src/OptimizeConstProp.cpp @@ -3379,6 +3379,8 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& case IrCmd::INTERRUPT: // While interrupt can observe state and yield/error, interrupt handlers must never change state break; + case IrCmd::UPDATE_COUNTERS: + break; case IrCmd::SETLIST: // Find array size information through the pointer stored in the 'B' VM register if (uint32_t* loadIdx = state.getPreviousVersionedLoadIndex(IrCmd::LOAD_POINTER, OP_B(inst))) diff --git a/CodeGen/src/OptimizeFinalX64.cpp b/CodeGen/src/OptimizeFinalX64.cpp index 11c72ca5f..4a3ac8566 100644 --- a/CodeGen/src/OptimizeFinalX64.cpp +++ b/CodeGen/src/OptimizeFinalX64.cpp @@ -2,17 +2,109 @@ #include "Luau/OptimizeFinalX64.h" #include "Luau/IrUtils.h" +#include "Luau/IrVisitUseDef.h" #include +LUAU_FASTFLAGVARIABLE(LuauCodegenX64ConflictCheck) +LUAU_FLAGVERSION(LuauCodegenX64ConflictCheck, 2) + +// x64 assembly allows memory operands, but IR separates loads from uses +// To improve final x64 lowering, we try to 'inline' single-use register/constant loads into some of our instructions +// This pass might not be useful on different architectures + namespace Luau { namespace CodeGen { -// x64 assembly allows memory operands, but IR separates loads from uses -// To improve final x64 lowering, we try to 'inline' single-use register/constant loads into some of our instructions -// This pass might not be useful on different architectures +static constexpr uint32_t kMaxInlineDistance = 16; + +struct DefinitionVisitor +{ + explicit DefinitionVisitor(int targetReg) + : targetReg(targetReg) + { + } + + void def(IrOp op, int offset = 0) + { + matched |= (vmRegOp(op) + offset) == targetReg; + } + + void maybeDef(IrOp op) + { + if (op.kind == IrOpKind::VmReg) + def(op, 0); + } + + void defRange(int start, int count) + { + matched |= targetReg >= start && (count == -1 || targetReg < start + count); + } + + // Required for a full visitor interface + void use(IrOp op, int offset = 0) {} + void maybeUse(IrOp op) {} + void useVarargs(uint8_t varargStart) {} + void useRange(int start, int count) {} + void capture(int reg) {} + + int targetReg = 0; + bool matched = false; +}; + +static bool hasDefinitionInRange(IrFunction& function, int targetReg, uint32_t start, uint32_t end) +{ + DefinitionVisitor visitor{targetReg}; + + for (uint32_t instIdx = start; instIdx < end && !visitor.matched; instIdx++) + visitVmRegDefsUses(visitor, function, function.instructions[instIdx]); + + return visitor.matched; +} + +// Check that the operand value will be the same as it was at the load location +static bool canInlineOperand(IrFunction& function, uint32_t sourceInstIdx, IrBlock& useBlock, uint32_t useInstIdx, IrOp op) +{ + if (op.kind != IrOpKind::VmReg) + return true; + + // Simple check if the definition is inside our block + if (sourceInstIdx >= useBlock.start && sourceInstIdx < useInstIdx) + { + if (useInstIdx - sourceInstIdx > kMaxInlineDistance) + return false; + + return !hasDefinitionInRange(function, vmRegOp(op), sourceInstIdx + 1, useInstIdx); + } + + // Check source values coming from a previous block if there's a 1:1 relationship + uint32_t useBlockIdx = function.getBlockIndex(useBlock); + if (useBlockIdx >= function.cfg.predecessorsOffsets.size()) + return false; + + BlockIteratorWrapper preds = predecessors(function.cfg, useBlockIdx); + if (preds.size() != 1) + return false; + + IrBlock& predBlock = function.blocks[*preds.begin()]; + if (sourceInstIdx < predBlock.start || sourceInstIdx > predBlock.finish) + return false; + + if ((predBlock.finish - sourceInstIdx) + (useInstIdx - useBlock.start) > kMaxInlineDistance) + return false; + + return !hasDefinitionInRange(function, vmRegOp(op), sourceInstIdx + 1, predBlock.finish + 1) && + !hasDefinitionInRange(function, vmRegOp(op), useBlock.start, useInstIdx); +} + +static void replaceIfNoConflicts(IrFunction& function, IrInst& source, IrBlock& useBlock, uint32_t useInstIdx, IrOp& original, IrOp replacement) +{ + if (canInlineOperand(function, function.getInstIndex(source), useBlock, useInstIdx, replacement)) + replace(function, original, replacement); +} + static void optimizeMemoryOperandsX64(IrFunction& function, IrBlock& block) { CODEGEN_ASSERT(block.kind != IrBlockKind::Dead); @@ -31,7 +123,12 @@ static void optimizeMemoryOperandsX64(IrFunction& function, IrBlock& block) IrInst& tag = function.instOp(OP_A(inst)); if (tag.useCount == 1 && tag.cmd == IrCmd::LOAD_TAG && (OP_A(tag).kind == IrOpKind::VmReg || OP_A(tag).kind == IrOpKind::VmConst)) - replace(function, OP_A(inst), OP_A(tag)); + { + if (FFlag::LuauCodegenX64ConflictCheck) + replaceIfNoConflicts(function, tag, block, index, OP_A(inst), OP_A(tag)); + else + replace(function, OP_A(inst), OP_A(tag)); + } } break; } @@ -42,7 +139,12 @@ static void optimizeMemoryOperandsX64(IrFunction& function, IrBlock& block) IrInst& tag = function.instOp(OP_A(inst)); if (tag.useCount == 1 && tag.cmd == IrCmd::LOAD_TAG && (OP_A(tag).kind == IrOpKind::VmReg || OP_A(tag).kind == IrOpKind::VmConst)) - replace(function, OP_A(inst), OP_A(tag)); + { + if (FFlag::LuauCodegenX64ConflictCheck) + replaceIfNoConflicts(function, tag, block, index, OP_A(inst), OP_A(tag)); + else + replace(function, OP_A(inst), OP_A(tag)); + } } if (OP_B(inst).kind == IrOpKind::Inst) @@ -50,7 +152,12 @@ static void optimizeMemoryOperandsX64(IrFunction& function, IrBlock& block) IrInst& value = function.instOp(OP_B(inst)); if (value.useCount == 1 && value.cmd == IrCmd::LOAD_INT) - replace(function, OP_B(inst), OP_A(value)); + { + if (FFlag::LuauCodegenX64ConflictCheck) + replaceIfNoConflicts(function, value, block, index, OP_B(inst), OP_A(value)); + else + replace(function, OP_B(inst), OP_A(value)); + } } break; } @@ -68,7 +175,12 @@ static void optimizeMemoryOperandsX64(IrFunction& function, IrBlock& block) IrInst& rhs = function.instOp(OP_B(inst)); if (rhs.useCount == 1 && rhs.cmd == IrCmd::LOAD_DOUBLE && (OP_A(rhs).kind == IrOpKind::VmReg || OP_A(rhs).kind == IrOpKind::VmConst)) - replace(function, OP_B(inst), OP_A(rhs)); + { + if (FFlag::LuauCodegenX64ConflictCheck) + replaceIfNoConflicts(function, rhs, block, index, OP_B(inst), OP_A(rhs)); + else + replace(function, OP_B(inst), OP_A(rhs)); + } } break; } @@ -80,7 +192,10 @@ static void optimizeMemoryOperandsX64(IrFunction& function, IrBlock& block) if (tagA.useCount == 1 && tagA.cmd == IrCmd::LOAD_TAG && (OP_A(tagA).kind == IrOpKind::VmReg || OP_A(tagA).kind == IrOpKind::VmConst)) { - replace(function, OP_A(inst), OP_A(tagA)); + if (FFlag::LuauCodegenX64ConflictCheck) + replaceIfNoConflicts(function, tagA, block, index, OP_A(inst), OP_A(tagA)); + else + replace(function, OP_A(inst), OP_A(tagA)); break; } } @@ -92,7 +207,11 @@ static void optimizeMemoryOperandsX64(IrFunction& function, IrBlock& block) if (tagB.useCount == 1 && tagB.cmd == IrCmd::LOAD_TAG && (OP_A(tagB).kind == IrOpKind::VmReg || OP_A(tagB).kind == IrOpKind::VmConst)) { std::swap(OP_A(inst), OP_B(inst)); - replace(function, OP_A(inst), OP_A(tagB)); + + if (FFlag::LuauCodegenX64ConflictCheck) + replaceIfNoConflicts(function, tagB, block, index, OP_A(inst), OP_A(tagB)); + else + replace(function, OP_A(inst), OP_A(tagB)); } } break; @@ -104,7 +223,12 @@ static void optimizeMemoryOperandsX64(IrFunction& function, IrBlock& block) IrInst& num = function.instOp(OP_A(inst)); if (num.useCount == 1 && num.cmd == IrCmd::LOAD_DOUBLE) - replace(function, OP_A(inst), OP_A(num)); + { + if (FFlag::LuauCodegenX64ConflictCheck) + replaceIfNoConflicts(function, num, block, index, OP_A(inst), OP_A(num)); + else + replace(function, OP_A(inst), OP_A(num)); + } } break; } @@ -119,7 +243,12 @@ static void optimizeMemoryOperandsX64(IrFunction& function, IrBlock& block) IrInst& arg = function.instOp(OP_A(inst)); if (arg.useCount == 1 && arg.cmd == IrCmd::LOAD_DOUBLE && (OP_A(arg).kind == IrOpKind::VmReg || OP_A(arg).kind == IrOpKind::VmConst)) - replace(function, OP_A(inst), OP_A(arg)); + { + if (FFlag::LuauCodegenX64ConflictCheck) + replaceIfNoConflicts(function, arg, block, index, OP_A(inst), OP_A(arg)); + else + replace(function, OP_A(inst), OP_A(arg)); + } } break; } diff --git a/Compiler/src/Compiler.cpp b/Compiler/src/Compiler.cpp index a525b0b65..851915126 100644 --- a/Compiler/src/Compiler.cpp +++ b/Compiler/src/Compiler.cpp @@ -50,7 +50,8 @@ LUAU_FASTFLAGVARIABLE(LuauExportedTypesParticipateInScc) LUAU_FLAGVERSION(LuauExportedTypesParticipateInScc, 3) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAGVARIABLE(LuauCompileReuseLocalRegs) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) +LUAU_FASTFLAGVARIABLE(LuauCompileRequireNoInline) namespace Luau { @@ -634,6 +635,10 @@ struct Compiler protoflags |= LPF_USES_EXPORT; bool isInlinable = !hasMultiRet && !getfenvUsed && !setfenvUsed; + // Add to line above on flag removal. + if (FFlag::LuauCompileRequireNoInline && hasRequire) + isInlinable = false; + uint64_t costModel = 0; if (FFlag::LuauEmitCallFeedback && isInlinable && upvals.empty()) { @@ -692,6 +697,7 @@ struct Compiler hasLoops = false; hasMultiRet = false; + hasRequire = false; currentFunction = nullptr; return fid; @@ -1389,6 +1395,12 @@ struct Compiler setDebugLine(expr); // normally compileExpr sets up line info, but compileExprCall can be called directly + if (FFlag::LuauCompileRequireNoInline && !expr->self) + { + if (AstExprGlobal* g = expr->func->as(); g && g->name == "require") + hasRequire = true; + } + // try inlining the function if (options.optimizationLevel >= 2 && !expr->self) { @@ -4062,7 +4074,7 @@ struct Compiler void compileStatWhile(AstStatWhile* stat) { - if (FFlag::DebugLuauWhileLocalSyntax && stat->conditionLocal) + if (FFlag::LuauExperimentalWhileLocalSyntax && stat->conditionLocal) { compileStatWhileLocal(stat); return; @@ -6039,6 +6051,7 @@ struct Compiler size_t argCount = 0; bool hasLoops = false; bool hasMultiRet = false; + bool hasRequire = false; AstExprFunction* currentFunction = nullptr; size_t blockDepth = 0; diff --git a/Compiler/src/CostModel.cpp b/Compiler/src/CostModel.cpp index b0420554b..4595d7f6d 100644 --- a/Compiler/src/CostModel.cpp +++ b/Compiler/src/CostModel.cpp @@ -112,7 +112,7 @@ struct CostVisitor : AstVisitor Cost model(AstExpr* node) { - if (const Constant* c = constants.find(node)) + if (constants.contains(node)) return Cost(0, Cost::kLiteral); if (AstExprGroup* expr = node->as()) @@ -168,7 +168,7 @@ struct CostVisitor : AstVisitor { return model(expr->expr) + model(expr->index) + 1; } - else if (AstExprFunction* expr = node->as()) + else if (node->is()) { return 10; // high baseline cost due to allocation } diff --git a/Compiler/src/Types.cpp b/Compiler/src/Types.cpp index c83f79292..392a80c24 100644 --- a/Compiler/src/Types.cpp +++ b/Compiler/src/Types.cpp @@ -90,11 +90,11 @@ static LuauBytecodeType getType( // not primitive or alias or generic => host-provided, we assume userdata for now return LBC_TYPE_USERDATA; } - else if (const AstTypeTable* table = ty->as()) + else if (ty->is()) { return LBC_TYPE_TABLE; } - else if (const AstTypeFunction* func = ty->as()) + else if (ty->is()) { return LBC_TYPE_FUNCTION; } @@ -128,7 +128,7 @@ static LuauBytecodeType getType( return LuauBytecodeType(type | (optional && (type != LBC_TYPE_ANY) ? LBC_TYPE_OPTIONAL_BIT : 0)); } - else if (const AstTypeIntersection* inter = ty->as()) + else if (ty->is()) { return LBC_TYPE_ANY; } @@ -136,7 +136,7 @@ static LuauBytecodeType getType( { return getType(group->type, generics, typeAliases, hostVectorType, userdataTypes, bytecode, seenAliases); } - else if (const AstTypeOptional* optional = ty->as()) + else if (ty->is()) { return LBC_TYPE_NIL; } diff --git a/Makefile b/Makefile index 42756f150..8b7060967 100644 --- a/Makefile +++ b/Makefile @@ -229,9 +229,9 @@ coverage: $(TESTS_TARGET) $(COMPILE_CLI_TARGET) mv default.profraw codegen.profraw $(TESTS_TARGET) -ts=Conformance --codegen --fflags=true mv default.profraw codegen-flags.profraw - $(COMPILE_CLI_TARGET) --codegennull --target=a64 --fflags=DebugLuauUserDefinedClasses=true,DebugLuauWhileLocalSyntax=true tests/conformance + $(COMPILE_CLI_TARGET) --codegennull --target=a64 --fflags=DebugLuauUserDefinedClasses=true tests/conformance mv default.profraw codegen-a64.profraw - $(COMPILE_CLI_TARGET) --codegennull --target=x64 --fflags=DebugLuauUserDefinedClasses=true,DebugLuauWhileLocalSyntax=true tests/conformance + $(COMPILE_CLI_TARGET) --codegennull --target=x64 --fflags=DebugLuauUserDefinedClasses=true tests/conformance mv default.profraw codegen-x64.profraw llvm-profdata merge *.profraw -o default.profdata rm *.profraw diff --git a/VM/src/lapi.cpp b/VM/src/lapi.cpp index 428079a22..8da4dd7fd 100644 --- a/VM/src/lapi.cpp +++ b/VM/src/lapi.cpp @@ -21,6 +21,8 @@ LUAU_FASTFLAG(LuauGcTraceUdata) LUAU_FASTFLAGVARIABLE(LuauCoroutineFinally) +LUAU_FASTFLAG(LuauLoadExplicitGcDisable) +LUAU_FASTFLAG(LuauSaltedInterningTable) /* * This file contains most implementations of core Lua APIs from lua.h. @@ -1442,6 +1444,9 @@ int lua_gc(lua_State* L, int what, int data) } case LUA_GCCOLLECT: { + if (FFlag::LuauLoadExplicitGcDisable && g->gcdisabled != 0) + break; + luaC_fullgc(L); break; } @@ -1463,6 +1468,9 @@ int lua_gc(lua_State* L, int what, int data) } case LUA_GCSTEP: { + if (FFlag::LuauLoadExplicitGcDisable && g->gcdisabled != 0) + break; + size_t amount = (cast_to(size_t, data) << 10); ptrdiff_t oldcredit = g->gcstate == GCSpause ? 0 : g->GCthreshold - g->totalbytes; @@ -1840,6 +1848,13 @@ void lua_setpointerencodekey(lua_State* L, uint64_t a, uint64_t b, uint64_t c, u g->ptrenckeynew[2 * i + 0] = siphash24(a, b, i); g->ptrenckeynew[2 * i + 1] = siphash24(c, d, i); } + + // Derive an additional key for the string interning table + if (FFlag::LuauSaltedInterningTable && g->ptrencactive) + { + uint64_t salt = siphash24(a, b, 4); + luaS_sethashsalt(L, uint32_t(salt), uint32_t(salt >> 32)); + } } uintptr_t lua_encodepointer(lua_State* L, uintptr_t p) diff --git a/VM/src/lclass.cpp b/VM/src/lclass.cpp index 441a1a28c..d00851963 100644 --- a/VM/src/lclass.cpp +++ b/VM/src/lclass.cpp @@ -17,6 +17,8 @@ #include +LUAU_FASTFLAG(LuauLoadExplicitGcDisable) + LuauClass* luaR_newblankclass(lua_State* L, TString* name, bool isopen) { LuauClass* classobject = luaM_newgco(L, LuauClass, sizeof(LuauClass), L->activememcat, LUA_TCLASS); @@ -100,7 +102,10 @@ LuauClass* luaR_newclass( LuaTable* envt ) { - LUAU_ASSERT(L->global->GCthreshold == SIZE_MAX && "GC must be paused"); + if (FFlag::LuauLoadExplicitGcDisable) + LUAU_ASSERT(L->global->gcdisabled && "GC must be paused"); + else + LUAU_ASSERT(L->global->GCthreshold == SIZE_MAX && "GC must be paused"); LuauClass* classobject = luaR_newblankclass(L, name, false); classobject->staticmembers = luaM_newarray(L, numberofstaticmembers, TValue, classobject->memcat); diff --git a/VM/src/lfunc.cpp b/VM/src/lfunc.cpp index ce1c43317..0bcf0f064 100644 --- a/VM/src/lfunc.cpp +++ b/VM/src/lfunc.cpp @@ -66,6 +66,82 @@ Proto* luaF_newproto(lua_State* L) return f; } +template +static T* copyArray(lua_State* L, const T* source, int size, uint8_t memcat) +{ + T* result = luaM_newarray(L, size, T, memcat); + + if (size != 0) + memcpy(result, source, size * sizeof(T)); + + return result; +} + +Proto* luaF_cloneproto(lua_State* L, Proto* source) +{ + Proto* p = luaF_newproto(L); + uint8_t memcat = p->memcat; + + p->debugname = source->debugname; + p->maxstacksize = source->maxstacksize; + p->numparams = source->numparams; + p->nups = source->nups; + p->is_vararg = source->is_vararg; + p->flags = source->flags; + p->gclist = nullptr; + p->funid = source->funid; + p->userdata = source->userdata; + p->source = source->source; + p->linedefined = source->linedefined; + p->cost = source->cost; + p->execflags = source->execflags; + p->bytecodeid = source->bytecodeid; + + p->k = copyArray(L, source->k, source->sizek, memcat); + p->sizek = source->sizek; + + p->code = copyArray(L, source->code, source->sizecode, memcat); + p->sizecode = source->sizecode; + p->codeentry = p->code; + + p->p = copyArray(L, source->p, source->sizep, memcat); + p->sizep = source->sizep; + + if (source->lineinfo) + { + int absoffset = (source->sizecode + 3) & ~3; + + p->lineinfo = copyArray(L, source->lineinfo, source->sizelineinfo, memcat); + p->abslineinfo = (int*)(p->lineinfo + absoffset); + } + + p->sizelineinfo = source->sizelineinfo; + p->linegaplog2 = source->linegaplog2; + + p->locvars = copyArray(L, source->locvars, source->sizelocvars, memcat); + p->sizelocvars = source->sizelocvars; + + p->upvalues = copyArray(L, source->upvalues, source->sizeupvalues, memcat); + p->sizeupvalues = source->sizeupvalues; + + if (source->debuginsn) + p->debuginsn = copyArray(L, source->debuginsn, source->sizecode, memcat); + + if (source->typeinfo) + { + p->typeinfo = copyArray(L, source->typeinfo, source->sizetypeinfo, memcat); + p->sizetypeinfo = source->sizetypeinfo; + } + + if (source->feedbackvec) + { + p->feedbackvec = copyArray(L, source->feedbackvec, int(source->feedbackvecsize), memcat); + p->feedbackvecsize = source->feedbackvecsize; + } + + return p; +} + Closure* luaF_newLclosure(lua_State* L, int nelems, LuaTable* e, Proto* p) { Closure* c = luaM_newgco(L, Closure, sizeLclosure(nelems), L->activememcat, LUA_TFUNCTION); diff --git a/VM/src/lfunc.h b/VM/src/lfunc.h index 29639c6ed..2b5ef2cd4 100644 --- a/VM/src/lfunc.h +++ b/VM/src/lfunc.h @@ -9,6 +9,7 @@ #define getproto(cl) ((cl)->isC ? nullptr : (FFlag::LuauPromoteProto && cl->l.p->optimized ? luaF_promoteproto(cl) : (cl)->l.p)) LUAI_FUNC Proto* luaF_newproto(lua_State* L); +LUAI_FUNC Proto* luaF_cloneproto(lua_State* L, Proto* source); LUAI_FUNC Closure* luaF_newLclosure(lua_State* L, int nelems, LuaTable* e, Proto* p); LUAI_FUNC Closure* luaF_newCclosure(lua_State* L, int nelems, LuaTable* e); LUAI_FUNC UpVal* luaF_findupval(lua_State* L, StkId level); diff --git a/VM/src/lgc.cpp b/VM/src/lgc.cpp index 67e3e71cf..d480625d6 100644 --- a/VM/src/lgc.cpp +++ b/VM/src/lgc.cpp @@ -25,6 +25,7 @@ LUAU_FASTFLAG(LuauCoroutineFinally) LUAU_DYNAMIC_FASTFLAGVARIABLE(LuauGcHeapShrinkFix, false) LUAU_FASTFLAGVARIABLE(LuauRuntimeFeedback) LUAU_FASTFLAG(LuauBufferSweep) +LUAU_FASTFLAG(LuauLoadExplicitGcDisable) /* * Luau uses an incremental non-generational non-moving mark&sweep garbage collector. @@ -1424,6 +1425,9 @@ size_t luaC_step(lua_State* L, bool assist) { global_State* g = L->global; + if (g->gcdisabled != 0) + return 0; + size_t lim = g->gcstepsize * g->gcstepmul / 100; // how much to work LUAU_ASSERT(g->totalbytes >= g->GCthreshold); size_t debt = g->totalbytes - g->GCthreshold; diff --git a/VM/src/lstate.cpp b/VM/src/lstate.cpp index 4e6c63a70..6473d4176 100644 --- a/VM/src/lstate.cpp +++ b/VM/src/lstate.cpp @@ -214,6 +214,8 @@ lua_State* lua_newstate(lua_Alloc allocator, void* ud) g->ptrenckey[0] = 1; + g->strt.saltmult = 0x9e3779b9u; // default string table salt provides additional Fibonacci hash mixing + g->totalbytes = sizeof(LG); g->memcatbytes[0] = sizeof(LG); diff --git a/VM/src/lstate.h b/VM/src/lstate.h index f87c4655d..940449f6e 100644 --- a/VM/src/lstate.h +++ b/VM/src/lstate.h @@ -22,6 +22,9 @@ typedef struct stringtable TString** hash; uint32_t nuse; // number of elements int size; + uint32_t saltmult; + uint32_t saltadd; + uint8_t hashshift; } stringtable; // clang-format on @@ -212,6 +215,7 @@ typedef struct global_State uint8_t currentwhite; uint8_t gcstate; // state of garbage collector + uint8_t gcdisabled; GCObject* gray; // list of gray objects GCObject* grayagain; // list of objects to be traversed atomically diff --git a/VM/src/lstring.cpp b/VM/src/lstring.cpp index 5e8e768d5..05c618a9a 100644 --- a/VM/src/lstring.cpp +++ b/VM/src/lstring.cpp @@ -7,6 +7,11 @@ #include +LUAU_FASTFLAGVARIABLE(LuauSaltedInterningTable) + +#define salthash(hash, saltmult, saltadd) uint32_t((saltmult) * (hash) + (saltadd)) +#define tobucket(hash, hashshift) int((hash) >> (hashshift)) + unsigned int luaS_hash(const char* str, size_t len) { // Note that this hashing algorithm is replicated in BytecodeBuilder.cpp, BytecodeBuilder::getStringHash @@ -42,10 +47,12 @@ unsigned int luaS_hash(const char* str, size_t len) return h; } -void luaS_resize(lua_State* L, int newsize) +static void luaS_rehash(lua_State* L, int newsize, uint32_t saltmult, uint32_t saltadd) { + global_State* g = L->global; TString** newhash = luaM_newarray(L, newsize, TString*, 0); - stringtable* tb = &L->global->strt; + stringtable* tb = &g->strt; + uint8_t hashshift = uint8_t(32 - luaO_log2(unsigned(newsize))); for (int i = 0; i < newsize; i++) newhash[i] = NULL; // rehash @@ -56,8 +63,9 @@ void luaS_resize(lua_State* L, int newsize) { // for each node in the list TString* next = p->next; // save next unsigned int h = p->hash; - int h1 = lmod(h, newsize); // new position - LUAU_ASSERT(cast_int(h % newsize) == lmod(h, newsize)); + unsigned int saltedh = salthash(h, saltmult, saltadd); + int h1 = tobucket(saltedh, hashshift); // new position + LUAU_ASSERT(unsigned(h1) < unsigned(newsize)); p->next = newhash[h1]; // chain it newhash[h1] = p; p = next; @@ -66,9 +74,60 @@ void luaS_resize(lua_State* L, int newsize) luaM_freearray(L, tb->hash, tb->size, TString*, 0); tb->size = newsize; tb->hash = newhash; + tb->saltmult = saltmult; + tb->saltadd = saltadd; + tb->hashshift = hashshift; } -static TString* newlstr(lua_State* L, const char* str, size_t l, unsigned int h) +void luaS_resize(lua_State* L, int newsize) +{ + if (FFlag::LuauSaltedInterningTable) + { + stringtable* tb = &L->global->strt; + luaS_rehash(L, newsize, tb->saltmult, tb->saltadd); + } + else + { + TString** newhash = luaM_newarray(L, newsize, TString*, 0); + stringtable* tb = &L->global->strt; + for (int i = 0; i < newsize; i++) + newhash[i] = NULL; + // rehash + for (int i = 0; i < tb->size; i++) + { + TString* p = tb->hash[i]; + while (p) + { // for each node in the list + TString* next = p->next; // save next + unsigned int h = p->hash; + int h1 = lmod(h, newsize); // new position + LUAU_ASSERT(cast_int(h % newsize) == lmod(h, newsize)); + p->next = newhash[h1]; // chain it + newhash[h1] = p; + p = next; + } + } + luaM_freearray(L, tb->hash, tb->size, TString*, 0); + tb->size = newsize; + tb->hash = newhash; + } +} + +void luaS_sethashsalt(lua_State* L, uint32_t saltmult, uint32_t saltadd) +{ + LUAU_ASSERT(FFlag::LuauSaltedInterningTable); + + saltmult |= 1; // odd multiplier is required + + stringtable* tb = &L->global->strt; + + if (tb->saltmult == saltmult && tb->saltadd == saltadd) + return; + + luaS_rehash(L, tb->size, saltmult, saltadd); +} + +static TString* newlstr(lua_State* L, const char* str, size_t l, unsigned int h, unsigned int saltedh) { if (l > MAXSSIZE) luaM_toobig(L); @@ -83,9 +142,19 @@ static TString* newlstr(lua_State* L, const char* str, size_t l, unsigned int h) ts->data[l] = '\0'; // ending 0 stringtable* tb = &L->global->strt; - h = lmod(h, tb->size); - ts->next = tb->hash[h]; // chain new entry - tb->hash[h] = ts; + + if (FFlag::LuauSaltedInterningTable) + { + saltedh = tobucket(saltedh, tb->hashshift); + ts->next = tb->hash[saltedh]; // chain new entry + tb->hash[saltedh] = ts; + } + else + { + h = lmod(h, tb->size); + ts->next = tb->hash[h]; // chain new entry + tb->hash[h] = ts; + } tb->nuse++; if (tb->nuse > cast_to(uint32_t, tb->size) && tb->size <= INT_MAX / 2) @@ -114,7 +183,8 @@ TString* luaS_buffinish(lua_State* L, TString* ts) { unsigned int h = luaS_hash(ts->data, ts->len); stringtable* tb = &L->global->strt; - int bucket = lmod(h, tb->size); + unsigned int saltedh = FFlag::LuauSaltedInterningTable ? salthash(h, tb->saltmult, tb->saltadd) : 0; + int bucket = FFlag::LuauSaltedInterningTable ? int(tobucket(saltedh, tb->hashshift)) : lmod(h, tb->size); // search if we already have this string in the hash table for (TString* el = tb->hash[bucket]; el != NULL; el = el->next) @@ -146,36 +216,81 @@ TString* luaS_buffinish(lua_State* L, TString* ts) TString* luaS_newlstr(lua_State* L, const char* str, size_t l) { - unsigned int h = luaS_hash(str, l); - for (TString* el = L->global->strt.hash[lmod(h, L->global->strt.size)]; el != NULL; el = el->next) + if (FFlag::LuauSaltedInterningTable) { - if (el->len == l && (memcmp(str, getstr(el), l) == 0)) + global_State* g = L->global; + unsigned int h = luaS_hash(str, l); + unsigned int saltedh = salthash(h, g->strt.saltmult, g->strt.saltadd); + + for (TString* el = g->strt.hash[tobucket(saltedh, g->strt.hashshift)]; el != NULL; el = el->next) { - // string may be dead - if (isdead(L->global, obj2gco(el))) - changewhite(obj2gco(el)); - return el; + if (el->len == l && (memcmp(str, getstr(el), l) == 0)) + { + // string may be dead + if (isdead(g, obj2gco(el))) + changewhite(obj2gco(el)); + return el; + } + } + + return newlstr(L, str, l, h, saltedh); // not found + } + else + { + unsigned int h = luaS_hash(str, l); + for (TString* el = L->global->strt.hash[lmod(h, L->global->strt.size)]; el != NULL; el = el->next) + { + if (el->len == l && (memcmp(str, getstr(el), l) == 0)) + { + // string may be dead + if (isdead(L->global, obj2gco(el))) + changewhite(obj2gco(el)); + return el; + } } + return newlstr(L, str, l, h, 0); // not found } - return newlstr(L, str, l, h); // not found } static bool unlinkstr(lua_State* L, TString* ts) { - global_State* g = L->global; + if (FFlag::LuauSaltedInterningTable) + { + global_State* g = L->global; + unsigned int saltedh = salthash(ts->hash, g->strt.saltmult, g->strt.saltadd); - TString** p = &g->strt.hash[lmod(ts->hash, g->strt.size)]; + TString** p = &g->strt.hash[tobucket(saltedh, g->strt.hashshift)]; - while (TString* curr = *p) - { - if (curr == ts) + while (TString* curr = *p) { - *p = curr->next; - return true; + if (curr == ts) + { + *p = curr->next; + return true; + } + else + { + p = &curr->next; + } } - else + } + else + { + global_State* g = L->global; + + TString** p = &g->strt.hash[lmod(ts->hash, g->strt.size)]; + + while (TString* curr = *p) { - p = &curr->next; + if (curr == ts) + { + *p = curr->next; + return true; + } + else + { + p = &curr->next; + } } } diff --git a/VM/src/lstring.h b/VM/src/lstring.h index 7b33b6524..7725a35b9 100644 --- a/VM/src/lstring.h +++ b/VM/src/lstring.h @@ -27,6 +27,7 @@ LUAI_FUNC unsigned int luaS_hash(const char* str, size_t len); LUAI_FUNC void luaS_resize(lua_State* L, int newsize); +LUAI_FUNC void luaS_sethashsalt(lua_State* L, uint32_t saltmult, uint32_t saltadd); LUAI_FUNC TString* luaS_newlstr(lua_State* L, const char* str, size_t l); LUAI_FUNC void luaS_free(lua_State* L, TString* ts, struct lua_Page* page); diff --git a/VM/src/ludata.cpp b/VM/src/ludata.cpp index a01dc38e8..3204f46a8 100644 --- a/VM/src/ludata.cpp +++ b/VM/src/ludata.cpp @@ -34,5 +34,6 @@ void luaU_freeudata(lua_State* L, Udata* u, lua_Page* page) if (dtor) dtor(L, u->data); + luaM_freegco(L, u, sizeudata(u->len), u->memcat, page); } diff --git a/VM/src/lvmload.cpp b/VM/src/lvmload.cpp index 13b564cfe..593c73c49 100644 --- a/VM/src/lvmload.cpp +++ b/VM/src/lvmload.cpp @@ -19,6 +19,7 @@ LUAU_FASTFLAGVARIABLE(LuauCostModel) LUAU_FASTFLAGVARIABLE(LuauLoadRemapOptionalUserdata) +LUAU_FASTFLAGVARIABLE(LuauLoadExplicitGcDisable) template struct TempBuffer @@ -61,30 +62,42 @@ struct TempBuffer } }; -struct ScopedSetGCThreshold +struct ScopedDisableGC { public: - ScopedSetGCThreshold(global_State* global, size_t newThreshold) noexcept + ScopedDisableGC(global_State* global, size_t newThreshold_DEPRECATED) noexcept : global{global} { - originalThreshold = global->GCthreshold; - global->GCthreshold = newThreshold; + if (FFlag::LuauLoadExplicitGcDisable) + { + originalGcDisabled = global->gcdisabled; + global->gcdisabled = 1; + } + else + { + originalThreshold_DEPRECATED = global->GCthreshold; + global->GCthreshold = newThreshold_DEPRECATED; + } } - ScopedSetGCThreshold(const ScopedSetGCThreshold&) = delete; - ScopedSetGCThreshold(ScopedSetGCThreshold&&) = delete; + ScopedDisableGC(const ScopedDisableGC&) = delete; + ScopedDisableGC(ScopedDisableGC&&) = delete; - ScopedSetGCThreshold& operator=(const ScopedSetGCThreshold&) = delete; - ScopedSetGCThreshold& operator=(ScopedSetGCThreshold&&) = delete; + ScopedDisableGC& operator=(const ScopedDisableGC&) = delete; + ScopedDisableGC& operator=(ScopedDisableGC&&) = delete; - ~ScopedSetGCThreshold() noexcept + ~ScopedDisableGC() noexcept { - global->GCthreshold = originalThreshold; + if (FFlag::LuauLoadExplicitGcDisable) + global->gcdisabled = originalGcDisabled; + else + global->GCthreshold = originalThreshold_DEPRECATED; } private: global_State* global = nullptr; - size_t originalThreshold = 0; + size_t originalThreshold_DEPRECATED = 0; + uint8_t originalGcDisabled = 0; }; void luaV_getimport(lua_State* L, LuaTable* env, TValue* k, StkId res, uint32_t id, bool propagatenil) @@ -864,7 +877,7 @@ int luau_load(lua_State* L, const char* chunkname, const char* data, size_t size luaC_checkGC(L); // pause GC for the duration of deserialization - some objects we're creating aren't rooted - const ScopedSetGCThreshold pauseGC{L->global, SIZE_MAX}; + const ScopedDisableGC pauseGC{L->global, SIZE_MAX}; struct LoadContext { diff --git a/bench/gc/test_LB_mandel_classes.luau b/bench/gc/test_LB_mandel_classes.luau new file mode 100644 index 000000000..8388845ef --- /dev/null +++ b/bench/gc/test_LB_mandel_classes.luau @@ -0,0 +1,81 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +class Complex + private _re + private _im + + public function __init(self, re, im) + self._re = re + self._im = im + end + + function conj(x) + return Complex(x._re, -x._im) + end + + function norm2(x) + return (x * Complex.conj(x))._re + end + + function abs(x) + return math.sqrt(Complex.norm2(x)) + end + + private function _add(x,y) + return Complex(x._re+y._re,x._im+y._im) + end + + private function _mul(x,y) + return Complex(x._re*y._re-x._im*y._im, x._re*y._im+x._im*y._re) + end + + function __add(x,y) + return Complex._add(x,y) + end + + function __mul(x,y) + return Complex._mul(x,y) + end +end + +function test() + +local function abs(x) + return math.sqrt(Complex.norm2(x)) +end + +xmin=-2.0 xmax=2.0 ymin=-2.0 ymax=2.0 +N=(arg and arg[1]) or 64 + +function level(x,y) + local c=Complex(x, y) + local l=0 + local z=c + repeat + z=z*z+c + l=l+1 + until abs(z)>2.0 or l>255 + return l-1 +end + +dx=(xmax-xmin)/N +dy=(ymax-ymin)/N + +print("P2") +print("# mandelbrot set",xmin,xmax,ymin,ymax,N) +print(N,N,255) +local S = 0 +for i=1,N do + local x=xmin+(i-1)*dx + for j=1,N do + local y=ymin+(j-1)*dy + S = S + level(x,y) + end +end +print(S) + +end + +bench.runCode(test, "mandel classes") diff --git a/bench/micro_tests/test_OOP_constructor.lua b/bench/micro_tests/test_MT_OOP_constructor.lua similarity index 93% rename from bench/micro_tests/test_OOP_constructor.lua rename to bench/micro_tests/test_MT_OOP_constructor.lua index c3a12bc51..72722cba1 100644 --- a/bench/micro_tests/test_OOP_constructor.lua +++ b/bench/micro_tests/test_MT_OOP_constructor.lua @@ -2,7 +2,6 @@ local function prequire(name) local success, result = pcall(require, name); retu local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") function test() - local Number = {} Number.__index = Number @@ -27,4 +26,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: constructor") \ No newline at end of file +bench.runCode(test, "MT OOP: constructor") \ No newline at end of file diff --git a/bench/micro_tests/test_OOP_field_access.lua b/bench/micro_tests/test_MT_OOP_field_access.lua similarity index 93% rename from bench/micro_tests/test_OOP_field_access.lua rename to bench/micro_tests/test_MT_OOP_field_access.lua index d4898e423..9620c0280 100644 --- a/bench/micro_tests/test_OOP_field_access.lua +++ b/bench/micro_tests/test_MT_OOP_field_access.lua @@ -2,7 +2,6 @@ local function prequire(name) local success, result = pcall(require, name); retu local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") function test() - local Number = {} Number.__index = Number @@ -29,4 +28,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: field access") \ No newline at end of file +bench.runCode(test, "MT OOP: field access") \ No newline at end of file diff --git a/bench/micro_tests/test_OOP_field_access_random.lua b/bench/micro_tests/test_MT_OOP_field_access_random.lua similarity index 95% rename from bench/micro_tests/test_OOP_field_access_random.lua rename to bench/micro_tests/test_MT_OOP_field_access_random.lua index d28eb991a..6f612a9bd 100644 --- a/bench/micro_tests/test_OOP_field_access_random.lua +++ b/bench/micro_tests/test_MT_OOP_field_access_random.lua @@ -37,4 +37,4 @@ bench.runCode(function() end end -end, "OOP: field random access") +end, "MT OOP: field random access") diff --git a/bench/micro_tests/test_OOP_method_access.lua b/bench/micro_tests/test_MT_OOP_method_access.lua similarity index 93% rename from bench/micro_tests/test_OOP_method_access.lua rename to bench/micro_tests/test_MT_OOP_method_access.lua index bdfd32c3a..0fa165af8 100644 --- a/bench/micro_tests/test_OOP_method_access.lua +++ b/bench/micro_tests/test_MT_OOP_method_access.lua @@ -29,4 +29,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: method access") \ No newline at end of file +bench.runCode(test, "MT OOP: method access") \ No newline at end of file diff --git a/bench/micro_tests/test_OOP_method_call.lua b/bench/micro_tests/test_MT_OOP_method_call.lua similarity index 94% rename from bench/micro_tests/test_OOP_method_call.lua rename to bench/micro_tests/test_MT_OOP_method_call.lua index b67b19f59..f97595f69 100644 --- a/bench/micro_tests/test_OOP_method_call.lua +++ b/bench/micro_tests/test_MT_OOP_method_call.lua @@ -29,4 +29,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: method call") \ No newline at end of file +bench.runCode(test, "MT OOP: method call") \ No newline at end of file diff --git a/bench/micro_tests/test_OOP_virtual_constructor.lua b/bench/micro_tests/test_MT_OOP_virtual_constructor.lua similarity index 86% rename from bench/micro_tests/test_OOP_virtual_constructor.lua rename to bench/micro_tests/test_MT_OOP_virtual_constructor.lua index cd93e2948..0be1dd1f3 100644 --- a/bench/micro_tests/test_OOP_virtual_constructor.lua +++ b/bench/micro_tests/test_MT_OOP_virtual_constructor.lua @@ -1,4 +1,4 @@ --- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauCallFeedback,LuauEmitCallFeedback +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback local function prequire(name) local success, result = pcall(require, name); return success and result end local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") @@ -28,4 +28,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: virtual constructor") \ No newline at end of file +bench.runCode(test, "MT OOP: virtual constructor") \ No newline at end of file diff --git a/bench/micro_tests/test_MethodCalls_classes.luau b/bench/micro_tests/test_MethodCalls_classes.luau new file mode 100644 index 000000000..39c4e3d15 --- /dev/null +++ b/bench/micro_tests/test_MethodCalls_classes.luau @@ -0,0 +1,82 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +-- Port of test_MethodCalls.lua to user-defined classes + +open class Toggle + public state + + function __init(self, start_state) + self.state = start_state + end + + function value(self) + return self.state + end + + function activate(self) + self.state = not self.state + return self + end +end + +class NthToggle extends Toggle + public count_max + public counter + + function __init(self, start_state, max_counter) + Toggle.__init(self, start_state) + self.count_max = max_counter + self.counter = 0 + end + + function activate(self) + self.counter = self.counter + 1 + if self.counter >= self.count_max then + Toggle.activate(self) + self.counter = 0 + end + return self + end +end + +function test() + local start = os.clock() + local N = 30000 + + local val = 1 + local toggle = Toggle(val) + for i=1,N do + val = toggle:activate():value() + val = toggle:activate():value() + val = toggle:activate():value() + val = toggle:activate():value() + val = toggle:activate():value() + val = toggle:activate():value() + val = toggle:activate():value() + val = toggle:activate():value() + val = toggle:activate():value() + val = toggle:activate():value() + end + print(val and "true" or "false") + + val = 1 + local ntoggle = NthToggle(val, 3) + for i=1,N do + val = ntoggle:activate():value() + val = ntoggle:activate():value() + val = ntoggle:activate():value() + val = ntoggle:activate():value() + val = ntoggle:activate():value() + val = ntoggle:activate():value() + val = ntoggle:activate():value() + val = ntoggle:activate():value() + val = ntoggle:activate():value() + val = ntoggle:activate():value() + end + print(val and "true" or "false") + return os.clock() - start +end + +bench.runCode(test, "MethodCalls classes") diff --git a/bench/micro_tests/test_OOP_constructor_classes.lua b/bench/micro_tests/test_OOP_constructor_classes.luau similarity index 75% rename from bench/micro_tests/test_OOP_constructor_classes.lua rename to bench/micro_tests/test_OOP_constructor_classes.luau index fa91d314c..0471fe77a 100644 --- a/bench/micro_tests/test_OOP_constructor_classes.lua +++ b/bench/micro_tests/test_OOP_constructor_classes.luau @@ -1,4 +1,4 @@ --- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauCallFeedback,LuauEmitCallFeedback +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback local function prequire(name) local success, result = pcall(require, name); return success and result end local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") @@ -7,13 +7,9 @@ class Number function __init(self, x) self.x = x end - function Get(self) - return self.x - end end function test() - local ts0 = os.clock() for i=1,1_000_000 do local n = Number(42) @@ -23,4 +19,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: class factory constructor") +bench.runCode(test, "OOP: user-defined constructor") diff --git a/bench/micro_tests/test_OOP_constructor_classes_direct.lua b/bench/micro_tests/test_OOP_constructor_classes_direct.luau similarity index 74% rename from bench/micro_tests/test_OOP_constructor_classes_direct.lua rename to bench/micro_tests/test_OOP_constructor_classes_direct.luau index 50609705e..3be2668a3 100644 --- a/bench/micro_tests/test_OOP_constructor_classes_direct.lua +++ b/bench/micro_tests/test_OOP_constructor_classes_direct.luau @@ -1,16 +1,12 @@ --- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauCallFeedback,LuauEmitCallFeedback +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback local function prequire(name) local success, result = pcall(require, name); return success and result end local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") class Number public x - function Get(self) - return self.x - end end function test() - local ts0 = os.clock() for i=1,1_000_000 do local n = Number { x = 42 } @@ -20,4 +16,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: class constructor") +bench.runCode(test, "OOP: constructor") diff --git a/bench/micro_tests/test_OOP_constructor_inherited.luau b/bench/micro_tests/test_OOP_constructor_inherited.luau new file mode 100644 index 000000000..6aa49a7a4 --- /dev/null +++ b/bench/micro_tests/test_OOP_constructor_inherited.luau @@ -0,0 +1,30 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +open class Base + public x + function __init(self, x) + self.x = x + end +end + +class Derived extends Base + public y + function __init(self, x, y) + Base.__init(self, x) + self.y = y + end +end + +function test() + local ts0 = os.clock() + for i=1,1_000_000 do + local n = Derived(42, 24) + end + local ts1 = os.clock() + + return ts1-ts0 +end + +bench.runCode(test, "OOP: inherited user-defined constructor") diff --git a/bench/micro_tests/test_OOP_constructor_inherited_direct.luau b/bench/micro_tests/test_OOP_constructor_inherited_direct.luau new file mode 100644 index 000000000..d71dbe0c7 --- /dev/null +++ b/bench/micro_tests/test_OOP_constructor_inherited_direct.luau @@ -0,0 +1,23 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +open class Base + public x +end + +class Derived extends Base + public y +end + +function test() + local ts0 = os.clock() + for i=1,1_000_000 do + local n = Derived { x = 42, y = 24 } + end + local ts1 = os.clock() + + return ts1-ts0 +end + +bench.runCode(test, "OOP: inherited constructor") diff --git a/bench/micro_tests/test_OOP_constructor_private.luau b/bench/micro_tests/test_OOP_constructor_private.luau new file mode 100644 index 000000000..6251b978c --- /dev/null +++ b/bench/micro_tests/test_OOP_constructor_private.luau @@ -0,0 +1,22 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +class Number + private _x + function __init(self, x) + self._x = x + end +end + +function test() + local ts0 = os.clock() + for i=1,1_000_000 do + local n = Number(42) + end + local ts1 = os.clock() + + return ts1-ts0 +end + +bench.runCode(test, "OOP: private field constructor") diff --git a/bench/micro_tests/test_OOP_field_access_classes.lua b/bench/micro_tests/test_OOP_field_access_classes.luau similarity index 75% rename from bench/micro_tests/test_OOP_field_access_classes.lua rename to bench/micro_tests/test_OOP_field_access_classes.luau index 33cbfb20e..4beb411c4 100644 --- a/bench/micro_tests/test_OOP_field_access_classes.lua +++ b/bench/micro_tests/test_OOP_field_access_classes.luau @@ -1,16 +1,12 @@ --- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauCallFeedback,LuauEmitCallFeedback +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback local function prequire(name) local success, result = pcall(require, name); return success and result end local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") class Number public value - function Get(self) - return self.value - end end function test() - local n = Number { value = 42 } local ts0 = os.clock() @@ -22,4 +18,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: field access class") +bench.runCode(test, "OOP: field access") diff --git a/bench/micro_tests/test_OOP_field_access_inherited.luau b/bench/micro_tests/test_OOP_field_access_inherited.luau new file mode 100644 index 000000000..39438c8b6 --- /dev/null +++ b/bench/micro_tests/test_OOP_field_access_inherited.luau @@ -0,0 +1,24 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +open class Base + public value +end + +class Derived extends Base +end + +function test() + local n = Derived { value = 42 } + + local ts0 = os.clock() + for i=1,10_000_000 do + local _ = n.value + end + local ts1 = os.clock() + + return ts1-ts0 +end + +bench.runCode(test, "OOP: inherited field access") diff --git a/bench/micro_tests/test_OOP_field_access_private.luau b/bench/micro_tests/test_OOP_field_access_private.luau new file mode 100644 index 000000000..4a814de62 --- /dev/null +++ b/bench/micro_tests/test_OOP_field_access_private.luau @@ -0,0 +1,29 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +-- Private members are only accessible from methods of the declaring class, so the loop lives in a method +class Number + private _value + function __init(self, value) + self._value = value + end + + function Run(self, iterations) + for i=1,iterations do + local _ = self._value + end + end +end + +function test() + local n = Number(42) + + local ts0 = os.clock() + n:Run(10_000_000) + local ts1 = os.clock() + + return ts1-ts0 +end + +bench.runCode(test, "OOP: private field access") diff --git a/bench/micro_tests/test_OOP_field_access_random_classes.lua b/bench/micro_tests/test_OOP_field_access_random.luau similarity index 87% rename from bench/micro_tests/test_OOP_field_access_random_classes.lua rename to bench/micro_tests/test_OOP_field_access_random.luau index 2a8ebdce2..e10363b31 100644 --- a/bench/micro_tests/test_OOP_field_access_random_classes.lua +++ b/bench/micro_tests/test_OOP_field_access_random.luau @@ -1,4 +1,4 @@ --- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauCallFeedback,LuauEmitCallFeedback +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback local function prequire(name) local success, result = pcall(require, name) return success and result @@ -32,4 +32,4 @@ bench.runCode(function() end end -end, "OOP: field random access classes") +end, "OOP: field random access") diff --git a/bench/micro_tests/test_OOP_method_access_classes.lua b/bench/micro_tests/test_OOP_method_access.luau similarity index 83% rename from bench/micro_tests/test_OOP_method_access_classes.lua rename to bench/micro_tests/test_OOP_method_access.luau index c6571e620..7b22b4d44 100644 --- a/bench/micro_tests/test_OOP_method_access_classes.lua +++ b/bench/micro_tests/test_OOP_method_access.luau @@ -1,4 +1,4 @@ --- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauCallFeedback,LuauEmitCallFeedback +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback local function prequire(name) local success, result = pcall(require, name); return success and result end local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") @@ -22,4 +22,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: method access class") +bench.runCode(test, "OOP: method access") diff --git a/bench/micro_tests/test_OOP_method_call_class.lua b/bench/micro_tests/test_OOP_method_call.luau similarity index 83% rename from bench/micro_tests/test_OOP_method_call_class.lua rename to bench/micro_tests/test_OOP_method_call.luau index 792c2db46..2747b7ab8 100644 --- a/bench/micro_tests/test_OOP_method_call_class.lua +++ b/bench/micro_tests/test_OOP_method_call.luau @@ -1,4 +1,4 @@ --- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauCallFeedback,LuauEmitCallFeedback +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback local function prequire(name) local success, result = pcall(require, name); return success and result end local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") @@ -22,4 +22,4 @@ function test() return ts1-ts0 end -bench.runCode(test, "OOP: method call classes") +bench.runCode(test, "OOP: method call") diff --git a/bench/micro_tests/test_OOP_method_call_inherited.luau b/bench/micro_tests/test_OOP_method_call_inherited.luau new file mode 100644 index 000000000..704e5351a --- /dev/null +++ b/bench/micro_tests/test_OOP_method_call_inherited.luau @@ -0,0 +1,27 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +open class Base + public value + function Get(self) + return self.value + end +end + +class Derived extends Base +end + +function test() + local n = Derived { value = 42 } + + local ts0 = os.clock() + for i=1,10_000_000 do + local _ = n:Get() + end + local ts1 = os.clock() + + return ts1-ts0 +end + +bench.runCode(test, "OOP: inherited method call") diff --git a/bench/micro_tests/test_OOP_method_call_private.luau b/bench/micro_tests/test_OOP_method_call_private.luau new file mode 100644 index 000000000..374f6c488 --- /dev/null +++ b/bench/micro_tests/test_OOP_method_call_private.luau @@ -0,0 +1,29 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +-- Private members are only accessible from methods of the declaring class, so the loop lives in a method +class Number + public value + private function _get(self) + return self.value + end + + function Run(self, iterations) + for i=1,iterations do + local _ = self:_get() + end + end +end + +function test() + local n = Number { value = 42 } + + local ts0 = os.clock() + n:Run(10_000_000) + local ts1 = os.clock() + + return ts1-ts0 +end + +bench.runCode(test, "OOP: private method call") diff --git a/bench/tests/chess-classes.lua b/bench/tests/chess-classes.luau similarity index 67% rename from bench/tests/chess-classes.lua rename to bench/tests/chess-classes.luau index 2ea0f0533..e8c082971 100644 --- a/bench/tests/chess-classes.lua +++ b/bench/tests/chess-classes.luau @@ -1,4 +1,4 @@ --- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauCallFeedback,LuauEmitCallFeedback +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback local function prequire(name) local success, result = pcall(require, name); return success and result end local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") @@ -92,12 +92,12 @@ local FileG local FileH class Bitboard - public l: number - public h: number + private _l: number + private _h: number function toString(self) local out = {} - local src = self.h + local src = self._h for x=7,0,-1 do table.insert(out, RANKS:sub(x+1,x+1)) table.insert(out, " ") @@ -111,17 +111,22 @@ class Bitboard bit = bit32.lshift(bit, 1) end if x == 4 then - src = self.l + src = self._l end table.insert(out, "\n") end table.insert(out, ' ' .. FILES:gsub('.', '%1 ') .. '\n') - table.insert(out, '#: ' .. self:popcnt() .. "\tl:" .. self.l .. "\th:" .. self.h) + table.insert(out, '#: ' .. self:popcnt() .. "\tl:" .. self._l .. "\th:" .. self._h) return table.concat(out) end + function __init(self, l, h) + self._l = l + self._h = h + end + function from(l, h) - return Bitboard { l = l, h = h } + return Bitboard(l, h) end function up(self) @@ -152,41 +157,41 @@ class Bitboard end function popcnt(self) - return popcnt32(self.l) + popcnt32(self.h) + return popcnt32(self._l) + popcnt32(self._h) end function band(self, other) - return Bitboard.from(bit32.band(self.l,other.l), bit32.band(self.h, other.h)) + return Bitboard.from(bit32.band(self._l,other._l), bit32.band(self._h, other._h)) end function bandnot(self, other) - return Bitboard.from(bit32.band(self.l,bit32.bnot(other.l)), bit32.band(self.h, bit32.bnot(other.h))) + return Bitboard.from(bit32.band(self._l,bit32.bnot(other._l)), bit32.band(self._h, bit32.bnot(other._h))) end function bandempty(self, other) - return bit32.band(self.l,other.l) == 0 and bit32.band(self.h, other.h) == 0 + return bit32.band(self._l,other._l) == 0 and bit32.band(self._h, other._h) == 0 end function bor(self, other) - return Bitboard.from(bit32.bor(self.l,other.l), bit32.bor(self.h, other.h)) + return Bitboard.from(bit32.bor(self._l,other._l), bit32.bor(self._h, other._h)) end function bxor(self, other) - return Bitboard.from(bit32.bxor(self.l,other.l), bit32.bxor(self.h, other.h)) + return Bitboard.from(bit32.bxor(self._l,other._l), bit32.bxor(self._h, other._h)) end function inverse(self) - return Bitboard.from(bit32.bxor(self.l,0xFFFFFFFF), bit32.bxor(self.h, 0xFFFFFFFF)) + return Bitboard.from(bit32.bxor(self._l,0xFFFFFFFF), bit32.bxor(self._h, 0xFFFFFFFF)) end function empty(self) - return self.h == 0 and self.l == 0 + return self._h == 0 and self._l == 0 end function ctz(self) - local result = bit32.countrz(self.l) + local result = bit32.countrz(self._l) if result == 32 then - return bit32.countrz(self.h) + 32 + return bit32.countrz(self._h) + 32 else return result end @@ -202,13 +207,13 @@ class Bitboard if amt == 0 then return self end if amt > 31 then - return Bitboard.from(0, bit32.lshift(self.l, amt-32)) + return Bitboard.from(0, bit32.lshift(self._l, amt-32)) end - local l = bit32.lshift(self.l, amt) + local l = bit32.lshift(self._l, amt) local h = bit32.bor( - bit32.lshift(self.h, amt), - bit32.extract(self.l, 32-amt, amt) + bit32.lshift(self._h, amt), + bit32.extract(self._l, 32-amt, amt) ) return Bitboard.from(l, h) end @@ -216,27 +221,27 @@ class Bitboard function rshift(self, amt) assert(amt >= 0) if amt == 0 then return self end - local h = bit32.rshift(self.h, amt) + local h = bit32.rshift(self._h, amt) local l = bit32.bor( - bit32.rshift(self.l, amt), - bit32.lshift(bit32.extract(self.h, 0, amt), 32-amt) + bit32.rshift(self._l, amt), + bit32.lshift(bit32.extract(self._h, 0, amt), 32-amt) ) return Bitboard.from(l, h) end function index(self, i) if i > 31 then - return bit32.extract(self.h, i - 32) + return bit32.extract(self._h, i - 32) else - return bit32.extract(self.l, i) + return bit32.extract(self._l, i) end end function set(self, i, v) if i > 31 then - return Bitboard.from(self.l, bit32.replace(self.h, v, i - 32)) + return Bitboard.from(self._l, bit32.replace(self._h, v, i - 32)) else - return Bitboard.from(bit32.replace(self.l, v, i), self.h) + return Bitboard.from(bit32.replace(self._l, v, i), self._h) end end @@ -286,31 +291,30 @@ local KNIGHT_MOVES = {{2,1}, {2,-1}, {-2,1}, {-2,-1}, {1,2}, {1,-2}, {-1,2}, {-1 class Board - -- Spellcheck? - public ocupied: Bitboard - public white: Bitboard - public black: Bitboard - public unocupied: Bitboard - public ep: Bitboard - public castle: Bitboard - public toMove: number - public hm: number - public moves: number - public material: number - public state: { [number]: Bitboard } + private _occupied: Bitboard + private _white: Bitboard + private _black: Bitboard + private _unoccupied: Bitboard + private _ep: Bitboard + private _castle: Bitboard + private _toMove: number + private _hm: number + private _moves: number + private _material: number + private _state: { [number]: Bitboard } function __init(self) - self.ocupied = BITBOARD_ZERO - self.white = BITBOARD_ZERO - self.black = BITBOARD_ZERO - self.unocupied = BITBOARD_FULL - self.ep = BITBOARD_ZERO - self.castle = BITBOARD_ZERO - self.toMove = 1 - self.hm = 0 - self.moves = 0 - self.material = 0 - self.state = table.create(12, BITBOARD_ZERO) + self._occupied = BITBOARD_ZERO + self._white = BITBOARD_ZERO + self._black = BITBOARD_ZERO + self._unoccupied = BITBOARD_FULL + self._ep = BITBOARD_ZERO + self._castle = BITBOARD_ZERO + self._toMove = 1 + self._hm = 0 + self._moves = 0 + self._material = 0 + self._state = table.create(12, BITBOARD_ZERO) end function fromFen(fen) @@ -330,17 +334,17 @@ class Board else local pidx = PieceSymbols:find(p) if pidx == nil then break end - b.state[pidx] = b.state[pidx]:set(rank*8+file, 1) + b._state[pidx] = b._state[pidx]:set(rank*8+file, 1) file = file + 1 end end local move, castle, ep, hm, m = string.match(fen, "^ ([bw]) ([KQkq-]*) ([a-h-][0-9]?) (%d*) (%d*)", i) if move == nil then print(fen:sub(i)) end - b.toMove = move == 'w' and 1 or 2 + b._toMove = move == 'w' and 1 or 2 if ep ~= "-" then - b.ep = Bitboard.some(square(ep)) + b._ep = Bitboard.some(square(ep)) end if castle ~= "-" then @@ -358,27 +362,27 @@ class Board oo = oo:set(56, 1) end - b.castle = oo + b._castle = oo end - b.hm = hm - b.moves = m + b._hm = hm + b._moves = m - b:updateCache() + b:_updateCache() return b end - function index(self, idx) - if self.white:index(idx) == 1 then + private function _index(self, idx) + if self._white:index(idx) == 1 then for p=1,12,2 do - if self.state[p]:index(idx) == 1 then + if self._state[p]:index(idx) == 1 then return p end end else for p=2,12,2 do - if self.state[p]:index(idx) == 1 then + if self._state[p]:index(idx) == 1 then return p end end @@ -387,20 +391,20 @@ class Board return 0 end - function updateCache(self) + private function _updateCache(self) for i=1,11,2 do - self.white = self.white:bor(self.state[i]) - self.black = self.black:bor(self.state[i+1]) + self._white = self._white:bor(self._state[i]) + self._black = self._black:bor(self._state[i+1]) end - self.ocupied = self.black:bor(self.white) - self.unocupied = self.ocupied:inverse() - self.material = - 100*self.state[1]:popcnt() - 100*self.state[2]:popcnt() + - 500*self.state[3]:popcnt() - 500*self.state[4]:popcnt() + - 300*self.state[5]:popcnt() - 300*self.state[6]:popcnt() + - 300*self.state[7]:popcnt() - 300*self.state[8]:popcnt() + - 900*self.state[9]:popcnt() - 900*self.state[10]:popcnt() + self._occupied = self._black:bor(self._white) + self._unoccupied = self._occupied:inverse() + self._material = + 100*self._state[1]:popcnt() - 100*self._state[2]:popcnt() + + 500*self._state[3]:popcnt() - 500*self._state[4]:popcnt() + + 300*self._state[5]:popcnt() - 300*self._state[6]:popcnt() + + 300*self._state[7]:popcnt() - 300*self._state[8]:popcnt() + + 900*self._state[9]:popcnt() - 900*self._state[10]:popcnt() end @@ -417,7 +421,7 @@ class Board end table.insert(out, '/') end - local p = self:index(idx) + local p = self:_index(idx) if p == 0 then s = s + 1 else @@ -434,43 +438,43 @@ class Board table.insert(out, '' .. s) end - table.insert(out, self.toMove == 1 and ' w ' or ' b ') - if self.castle:empty() then + table.insert(out, self._toMove == 1 and ' w ' or ' b ') + if self._castle:empty() then table.insert(out, '-') else - if self.castle:index(7) == 1 then table.insert(out, 'K') end - if self.castle:index(0) == 1 then table.insert(out, 'Q') end - if self.castle:index(63) == 1 then table.insert(out, 'k') end - if self.castle:index(56) == 1 then table.insert(out, 'q') end + if self._castle:index(7) == 1 then table.insert(out, 'K') end + if self._castle:index(0) == 1 then table.insert(out, 'Q') end + if self._castle:index(63) == 1 then table.insert(out, 'k') end + if self._castle:index(56) == 1 then table.insert(out, 'q') end end table.insert(out, ' ') - if self.ep:empty() then + if self._ep:empty() then table.insert(out, '-') else - table.insert(out, squareName(self.ep:ctz())) + table.insert(out, squareName(self._ep:ctz())) end - table.insert(out, ' ' .. self.hm) - table.insert(out, ' ' .. self.moves) + table.insert(out, ' ' .. self._hm) + table.insert(out, ' ' .. self._moves) return table.concat(out) end - function pmoves(self, idx) - return self:generate(idx) + private function _pmoves(self, idx) + return self:_generate(idx) end - function pcaptures(self, idx) - return self:generate(idx):band(self.ocupied) + private function _pcaptures(self, idx) + return self:_generate(idx):band(self._occupied) end - function generate(self, idx) - local piece = self:index(idx) + private function _generate(self, idx) + local piece = self:_index(idx) local r = Bitboard.some(idx) local out = BITBOARD_ZERO local type = bit32.rshift(piece - 1, 1) - local cancapture = piece % 2 == 1 and self.black or self.white + local cancapture = piece % 2 == 1 and self._black or self._white if piece == 0 then return BITBOARD_ZERO end @@ -479,14 +483,14 @@ class Board local d = -(piece*2 - 3) local movetwo = piece == 1 and Rank3 or Rank6 - out = out:bor(r:move(0,d):band(self.unocupied)) - out = out:bor(out:band(movetwo):move(0,d):band(self.unocupied)) + out = out:bor(r:move(0,d):band(self._unoccupied)) + out = out:bor(out:band(movetwo):move(0,d):band(self._unoccupied)) local captures = r:move(0,d) captures = captures:right():bor(captures:left()) - if not captures:bandempty(self.ep) then - out = out:bor(self.ep) + if not captures:bandempty(self._ep) then + out = out:bor(self._ep) end captures = captures:band(cancapture) @@ -498,7 +502,7 @@ class Board for x=-1,1,1 do for y = -1,1,1 do local w = r:move(x,y) - if self.ocupied:bandempty(w) then + if self._occupied:bandempty(w) then out = out:bor(w) else if not cancapture:bandempty(w) then @@ -512,7 +516,7 @@ class Board for _,j in ipairs(KNIGHT_MOVES) do local w = r:move(j[1],j[2]) - if self.ocupied:bandempty(w) then + if self._occupied:bandempty(w) then out = out:bor(w) else if not cancapture:bandempty(w) then @@ -537,7 +541,7 @@ class Board w = w:move(op[1], op[2]) if w:empty() then break end - if self.ocupied:bandempty(w) then + if self._occupied:bandempty(w) then out = out:bor(w) else if not cancapture:bandempty(w) then @@ -570,7 +574,7 @@ class Board for y=1,8 do local n = 8*x+y-9 - local i = self:index(n) + local i = self:_index(n) if i == 0 then table.insert(out, '-') else @@ -589,25 +593,25 @@ class Board table.insert(out, "\n") end table.insert(out, ' ' .. FILES:gsub('.', '%1 ') .. '\n') - table.insert(out, (self.toMove == 1 and "White" or "Black") .. ' e:' .. (self.material/100) .. "\n") + table.insert(out, (self._toMove == 1 and "White" or "Black") .. ' e:' .. (self._material/100) .. "\n") return table.concat(out) end function moveList(self) - local tm = self.toMove == 1 and self.white or self.black - local castle_rank = self.toMove == 1 and Rank1 or Rank8 + local tm = self._toMove == 1 and self._white or self._black + local castle_rank = self._toMove == 1 and Rank1 or Rank8 local out = {} local function emit(id) - if not self:applyMove(id):illegalyChecked() then + if not self:applyMove(id):_illegalyChecked() then table.insert(out, id) end end - local cr = tm:band(self.castle):band(castle_rank) + local cr = tm:band(self._castle):band(castle_rank) if not cr:empty() then - local p = self.toMove == 1 and 11 or 12 - local tcolor = self.toMove == 1 and self.black or self.white - local kidx = self.state[p]:ctz() + local p = self._toMove == 1 and 11 or 12 + local tcolor = self._toMove == 1 and self._black or self._white + local kidx = self._state[p]:ctz() local castle = bit32.replace(0, p, 20, 4) @@ -616,11 +620,11 @@ class Board local mustbeemptyl = LeftMasks[4]:bxor(FileA):band(castle_rank) - local cantbethreatened = FileD:bor(FileC):band(castle_rank):bor(self.state[p]) + local cantbethreatened = FileD:bor(FileC):band(castle_rank):bor(self._state[p]) if not cr:bandempty(FileA) and - mustbeemptyl:bandempty(self.ocupied) and - not self:isSquareThreatened(cantbethreatened, tcolor) + mustbeemptyl:bandempty(self._occupied) and + not self:_isSquareThreatened(cantbethreatened, tcolor) then emit(bit32.replace(castle, kidx - 2, 0, 6)) end @@ -629,8 +633,8 @@ class Board local mustbeemptyr = RightMasks[3]:bxor(FileH):band(castle_rank) if not cr:bandempty(FileH) and - mustbeemptyr:bandempty(self.ocupied) and - not self:isSquareThreatened(mustbeemptyr:bor(self.state[p]), tcolor) + mustbeemptyr:bandempty(self._occupied) and + not self:_isSquareThreatened(mustbeemptyr:bor(self._state[p]), tcolor) then emit(bit32.replace(castle, kidx + 2, 0, 6)) end @@ -638,8 +642,8 @@ class Board local sq = tm:ctz() repeat - local p = self:index(sq) - local moves = self:pmoves(sq) + local p = self:_index(sq) + local moves = self:_pmoves(sq) while not moves:empty() do local m = moves:ctz() @@ -647,8 +651,8 @@ class Board local id = bit32.replace(m, sq, 6, 6) id = bit32.replace(id, p, 20, 4) local mbb = Bitboard.some(m) - if not self.ocupied:bandempty(mbb) then - id = bit32.replace(id, self:index(m), 25, 4) + if not self._occupied:bandempty(mbb) then + id = bit32.replace(id, self:_index(m), 25, 4) end -- Check if pawn needs to be promoted @@ -669,16 +673,16 @@ class Board return out end - function illegalyChecked(self) - local target = self.toMove == 1 and self.state[PieceSymbols:find("k")] or self.state[PieceSymbols:find("K")] - return self:isSquareThreatened(target, self.toMove == 1 and self.white or self.black) + private function _illegalyChecked(self) + local target = self._toMove == 1 and self._state[PieceSymbols:find("k")] or self._state[PieceSymbols:find("K")] + return self:_isSquareThreatened(target, self._toMove == 1 and self._white or self._black) end - function isSquareThreatened(self, target, color) + private function _isSquareThreatened(self, target, color) local tm = color local sq = tm:ctz() repeat - local moves = self:pmoves(sq) + local moves = self:_pmoves(sq) if not moves:bandempty(target) then return true end @@ -708,37 +712,37 @@ class Board function applyMove(self, move) local out = Board() - table.move(self.state, 1, 12, 1, out.state) + table.move(self._state, 1, 12, 1, out._state) local from = bit32.extract(move, 6, 6) local to = bit32.extract(move, 0, 6) local promote = bit32.extract(move, 15, 4) - local piece = self:index(from) - local captured = self:index(to) + local piece = self:_index(from) + local captured = self:_index(to) local tom = Bitboard.some(to) local isCastle = bit32.extract(move, 14) if piece % 2 == 0 then - out.moves = self.moves + 1 + out._moves = self._moves + 1 end if captured == 1 or piece < 3 then - out.hm = 0 + out._hm = 0 else - out.hm = self.hm + 1 + out._hm = self._hm + 1 end - out.castle = self.castle - out.toMove = self.toMove == 1 and 2 or 1 + out._castle = self._castle + out._toMove = self._toMove == 1 and 2 or 1 if isCastle == 1 then local rank = piece == 11 and Rank1 or Rank8 local colorOffset = piece - 11 - out.state[3 + colorOffset] = out.state[3 + colorOffset]:bandnot(from < to and FileH or FileA) - out.state[3 + colorOffset] = out.state[3 + colorOffset]:bor((from < to and FileF or FileD):band(rank)) + out._state[3 + colorOffset] = out._state[3 + colorOffset]:bandnot(from < to and FileH or FileA) + out._state[3 + colorOffset] = out._state[3 + colorOffset]:bor((from < to and FileF or FileD):band(rank)) - out.state[piece] = (from < to and FileG or FileC):band(rank) - out.castle = out.castle:bandnot(rank) - out:updateCache() + out._state[piece] = (from < to and FileG or FileC):band(rank) + out._castle = out._castle:bandnot(rank) + out:_updateCache() return out end @@ -746,40 +750,40 @@ class Board local dist = math.abs(to - from) -- Pawn moved two squares, set ep square if dist == 16 then - out.ep = Bitboard.some((from + to) / 2) + out._ep = Bitboard.some((from + to) / 2) end -- Remove enpasent capture - if not tom:bandempty(self.ep) then + if not tom:bandempty(self._ep) then if piece == 1 then - out.state[2] = out.state[2]:bandnot(self.ep:down()) + out._state[2] = out._state[2]:bandnot(self._ep:down()) end if piece == 2 then - out.state[1] = out.state[1]:bandnot(self.ep:up()) + out._state[1] = out._state[1]:bandnot(self._ep:up()) end end end if piece == 3 or piece == 4 then - out.castle = out.castle:set(from, 0) + out._castle = out._castle:set(from, 0) end if piece > 10 then local rank = piece == 11 and Rank1 or Rank8 - out.castle = out.castle:bandnot(rank) + out._castle = out._castle:bandnot(rank) end - out.state[piece] = out.state[piece]:set(from, 0) + out._state[piece] = out._state[piece]:set(from, 0) if promote == 0 then - out.state[piece] = out.state[piece]:set(to, 1) + out._state[piece] = out._state[piece]:set(to, 1) else - out.state[promote] = out.state[promote]:set(to, 1) + out._state[promote] = out._state[promote]:set(to, 1) end if captured ~= 0 then - out.state[captured] = out.state[captured]:set(to, 0) + out._state[captured] = out._state[captured]:set(to, 0) end - out:updateCache() + out:_updateCache() return out end diff --git a/bench/tests/sunspider/n-body-oop-classes.lua b/bench/tests/sunspider/n-body-oop-classes.lua index b5c2d7dec..ccbef2858 100644 --- a/bench/tests/sunspider/n-body-oop-classes.lua +++ b/bench/tests/sunspider/n-body-oop-classes.lua @@ -1,4 +1,4 @@ --- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauCallFeedback,LuauEmitCallFeedback +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback local function prequire(name) local success, result = pcall(require, name); return success and result end local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support") diff --git a/bench/tests/tictactoe-classes.luau b/bench/tests/tictactoe-classes.luau new file mode 100644 index 000000000..0817a1e47 --- /dev/null +++ b/bench/tests/tictactoe-classes.luau @@ -0,0 +1,197 @@ +-- --bench-args: --fflags=DebugLuauUserDefinedClasses,DebugLuauUserDefinedClassesRuntime,LuauEmitCallFeedback +local function prequire(name) local success, result = pcall(require, name); return success and result end +local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support") + +local function copy_board(board) + local copy = {} + for i = 1, #board do + copy[i] = board[i] + end + return copy +end + +local function is_board_full(board) + for i = 1, #board do + if board[i] == 0 then + return false + end + end + return true +end + +local index_quadruplets = { + {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, -- rows + {13,14,15,16}, {1,5,9,13}, {2,6,10,14}, -- cols + {3,7,11,15}, {4,8,12,16}, {1,6,11,16}, {4,7,10,13}, -- diags + {1,2,5,6}, {2,3,6,7}, {3,4,7,8}, -- squares + {5,6,9,10}, {6,7,10,11}, {7,8,11,12}, + {9,10,13,14}, {10,11,14,15}, {11,12,15,16} +} + +-- Game-agnostic negamax search; subclasses supply evaluate, move_candidates and make_move. +open class NegaMax + public maxdepth: number + public numsearchpos: number + + function evaluate(self, board, depth) + --[[ + What can be confusing is how the heuristic value of the current node is calculated. In this implementation, this value is always calculated from the point of view of player A, whose color value is one. In other words, higher heuristic values always represent situations more favorable for player A. This is the same behavior as the normal minimax algorithm. The heuristic value is not necessarily the same as a node's return value due to value negation by negamax and the color parameter. The negamax node's return value is a heuristic score from the point of view of the node's current player. + + Negamax scores match minimax scores for nodes where player A is about to play, and where player A is the maximizing player in the minimax equivalent. Negamax always searches for the maximum value for all its nodes. Hence for player B nodes, the minimax score is a negation of its negamax score. Player B is the minimizing player in the minimax equivalent. + + Variations in negamax implementations may omit the color parameter. In this case, the heuristic evaluation function must return values from the point of view of the node's current player. + --]] + print ("This function needs to be implemented!") + end + + function move_candidates(self, board, side_to_move) + print ("This function needs to be implemented!") + end + + function make_move(self, board, side_to_move, move) + print ("This function needs to be implemented!") + end + + function negaMax(self, board, side_to_move, depth, alpha, beta) -- side_to_move: e.g. 1 is blue, -1 is read + -- + -- init vars for root call + -- + if not depth then -- root call + depth = 0 + alpha = -math.huge + beta = math.huge + self.numsearchpos = 0 -- reset call counter + end + -- + -- test if the node is terminal (i.e. full board or win) + -- + local best_move = -1 + local score, is_term_node = self:evaluate(board, depth) + -- we abort the recursion if this is a terminal node, or if one of the search abort conditions are met + -- + if is_term_node or depth == self.maxdepth then + return side_to_move*score, best_move, is_term_node + end + -- + -- if not terminal node, eval child nodes + -- + local moves = self:move_candidates(board, side_to_move) + score = -math.huge + + for _, analyzed_move in pairs(moves) do -- iterate over all boards + self.numsearchpos = self.numsearchpos + 1 + local b = self:make_move(board, side_to_move, analyzed_move) + local move_score, _, _ = -self:negaMax(b, -side_to_move, depth+1, -beta, -alpha) + if move_score > score then + score = move_score + best_move = analyzed_move + end + alpha = math.max(alpha, score) + if alpha >= beta then + break + end + end + if depth == 0 then + print("Analyzed positions: " .. self.numsearchpos) + end + return score, best_move + end +end + +-- 4x4 tic-tac-toe where four in a row, column, diagonal or 2x2 square wins. +class Tic4 extends NegaMax + function evaluate(self, board, depth) -- return format is score, is_terminal_position + local player_plus_score, player_minus_score = 0, 0 + local game_won = false + for _, curr_qdr in pairs(index_quadruplets) do -- iterate over all index quadruplets + -- count the empty positions and positions occupied by the side whos move it is + local player_plus_fields, player_minus_fields, empties = 0, 0, 0 + for _, index in next, curr_qdr do -- iterate over all indices + if board[index] == 0 then + empties = empties + 1 + elseif board[index] == 1 then + player_plus_fields = player_plus_fields + 1 + elseif board[index] == -1 then + player_minus_fields = player_minus_fields + 1 + end + end + -- evaluate the quadruplets score by looking at empty vs occupied positions + if empties == 3 then + if player_plus_fields == 1 then + player_plus_score = player_plus_score + 3 + elseif player_minus_fields == 1 then + player_minus_score = player_minus_score + 3 + end + elseif empties == 2 then + if player_plus_fields == 2 then + player_plus_score = player_plus_score + 13 + elseif player_minus_fields == 2 then + player_minus_score = player_minus_score + 13 + end + elseif empties == 1 then + if player_plus_fields == 3 then + player_plus_score = player_plus_score + 31 + elseif player_minus_fields == 3 then + player_minus_score = player_minus_score + 31 + end + elseif empties == 0 then + -- check for winning situations + if player_plus_fields == 4 then + player_plus_score = 999-depth + player_minus_score = 0 + game_won = true + break + elseif player_minus_fields == 4 then + -- this should not happen if there is a proper terminal node detection! + player_plus_score = 0 + player_minus_score = 999-depth + game_won = true + break + end + end + end + -- return format is score, is_terminal_position + if not game_won and is_board_full(board) then + return 0, true -- DRAW + else + return (player_plus_score - player_minus_score), game_won -- >0 is good for player 1 [+], <0 means good for the other player (player 2 [-])) + end + end + + function move_candidates(self, board, side_to_move) + local moves = {} + for i = 1, #board do + if board[i] == 0 then -- empty? + moves[#moves + 1] = i -- save move that was made + end + end + return moves + end + + function make_move(self, board, side_to_move, move) + local copy = copy_board(board) + copy[move] = side_to_move + return copy + end +end + +local empty_board = {0,0,0,0, + 0,0,0,0, + 0,0,0,0, + 0,0,0,0} -- 16 empty positions + +local function test() + local human_player = 1 + local game_board = copy_board(empty_board) + local curr_player = human_player -- human player goes first + + local search = Tic4 { maxdepth = 5, numsearchpos = 0 } + + local t0 = os.clock() + search:negaMax(game_board, curr_player) + local t1 = os.clock() + + return t1-t0 +end + +bench.runCode(test, "tictactoe with classes") diff --git a/fuzz/luau.proto b/fuzz/luau.proto index 23bba4cfd..caf17e6c0 100644 --- a/fuzz/luau.proto +++ b/fuzz/luau.proto @@ -328,6 +328,8 @@ message StatWhile { required Expr cond = 1; required StatBlock body = 2; + optional Local condition_local = 3; + optional bool condition_is_const = 4 [ default = false ]; } message StatRepeat diff --git a/fuzz/protoprint.cpp b/fuzz/protoprint.cpp index 53dd82aab..062d0ee6d 100644 --- a/fuzz/protoprint.cpp +++ b/fuzz/protoprint.cpp @@ -928,6 +928,12 @@ struct ProtoToLuau void print(const luau::StatWhile& stat) { source += "while "; + if (stat.has_condition_local()) + { + source += stat.condition_is_const() ? "const " : "local "; + print(stat.condition_local()); + source += " = "; + } print(stat.cond()); source += " do\n"; diff --git a/tests/AssemblyBuilderX64.test.cpp b/tests/AssemblyBuilderX64.test.cpp index 30effb26f..e271fc8d2 100644 --- a/tests/AssemblyBuilderX64.test.cpp +++ b/tests/AssemblyBuilderX64.test.cpp @@ -616,6 +616,11 @@ TEST_CASE_FIXTURE(AssemblyBuilderX64Fixture, "MiscInstructions") SINGLE_COMPARE(ud2(), 0x0f, 0x0b); SINGLE_COMPARE(bsr(eax, edx), 0x0f, 0xbd, 0xc2); SINGLE_COMPARE(bsf(eax, edx), 0x0f, 0xbc, 0xc2); + SINGLE_COMPARE(bts(eax, edx), 0x0f, 0xab, 0xd0); + SINGLE_COMPARE(bts(rax, rdx), 0x48, 0x0f, 0xab, 0xd0); + SINGLE_COMPARE(bts(r12d, r9d), 0x45, 0x0f, 0xab, 0xcc); + SINGLE_COMPARE(bts(dword[rcx + 8], edx), 0x0f, 0xab, 0x51, 0x08); + SINGLE_COMPARE(bts(qword[r12 + rax * 4 + 0x40], r10), 0x4d, 0x0f, 0xab, 0x54, 0x84, 0x40); SINGLE_COMPARE(bswap(eax), 0x0f, 0xc8); SINGLE_COMPARE(bswap(r12d), 0x41, 0x0f, 0xcc); SINGLE_COMPARE(bswap(rax), 0x48, 0x0f, 0xc8); diff --git a/tests/AstJsonEncoder.test.cpp b/tests/AstJsonEncoder.test.cpp index 8769528f5..e2c62ad44 100644 --- a/tests/AstJsonEncoder.test.cpp +++ b/tests/AstJsonEncoder.test.cpp @@ -15,8 +15,8 @@ using namespace Luau; LUAU_FASTFLAG(LuauSingleTypeOptionalPackReturnsAttributeParens) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) struct JsonEncoderFixture { @@ -414,7 +414,7 @@ TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile") TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile_while_local") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; AstStat* statement = expectParseStatement("while local x = y do end"); @@ -426,7 +426,7 @@ TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile_while_local") TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile_while_local_type") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; AstStat* statement = expectParseStatement("while local x: number = y do end"); @@ -438,7 +438,7 @@ TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile_while_local_type") TEST_CASE_FIXTURE(JsonEncoderFixture, "encode_AstStatWhile_while_const") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; AstStat* statement = expectParseStatement("while const x = y do end"); diff --git a/tests/AstVisitor.test.cpp b/tests/AstVisitor.test.cpp index d5af45e24..bfdf511ec 100644 --- a/tests/AstVisitor.test.cpp +++ b/tests/AstVisitor.test.cpp @@ -6,7 +6,7 @@ #include "doctest.h" LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) using namespace Luau; @@ -139,7 +139,7 @@ TEST_CASE_FIXTURE(Fixture, "IfLocalAnnotationVisit") TEST_CASE_FIXTURE(Fixture, "WhileLocalAnnotationVisit") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}}; AstStatBlock* block = parse(R"( while local a: number = foo() do break end @@ -159,7 +159,7 @@ TEST_CASE_FIXTURE(Fixture, "WhileLocalAnnotationVisit") TEST_CASE_FIXTURE(Fixture, "WhileConstAnnotationVisit") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}}; AstStatBlock* block = parse(R"( while const a: number = foo() do break end diff --git a/tests/Autocomplete.test.cpp b/tests/Autocomplete.test.cpp index 0209a35de..b7221dd90 100644 --- a/tests/Autocomplete.test.cpp +++ b/tests/Autocomplete.test.cpp @@ -24,8 +24,8 @@ LUAU_FASTFLAG(LuauUseExplicitTypeArgsInGenerics) LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) LUAU_FASTFLAG(LuauRefactorAutocompleteAncestry) using namespace Luau; @@ -6259,7 +6259,7 @@ TEST_CASE_FIXTURE(ACFixture, "autocomplete_function_statement_with_index_2") TEST_CASE_FIXTURE(ACFixture, "while_local_binding_is_in_scope_in_body") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; check(R"( local t = {} @@ -6278,7 +6278,7 @@ TEST_CASE_FIXTURE(ACFixture, "while_local_binding_is_in_scope_in_body") TEST_CASE_FIXTURE(ACFixture, "while_const_binding_is_in_scope_in_body") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; check(R"( local t = {} @@ -6293,7 +6293,7 @@ TEST_CASE_FIXTURE(ACFixture, "while_const_binding_is_in_scope_in_body") TEST_CASE_FIXTURE(ACFixture, "while_local_binding_offers_member_completion") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; check(R"( local t = {foo = 1, bar = 2} @@ -6309,7 +6309,7 @@ TEST_CASE_FIXTURE(ACFixture, "while_local_binding_offers_member_completion") TEST_CASE_FIXTURE(ACFixture, "while_local_optional_binding_is_in_scope_in_body") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; check(R"( type Test = {name: string, age: number} @@ -6327,7 +6327,7 @@ TEST_CASE_FIXTURE(ACFixture, "while_local_optional_binding_is_in_scope_in_body") TEST_CASE_FIXTURE(ACFixture, "while_local_optional_binding_offers_member_completion") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; check(R"( type Test = {name: string, age: number} @@ -6346,7 +6346,7 @@ TEST_CASE_FIXTURE(ACFixture, "while_local_optional_binding_offers_member_complet TEST_CASE_FIXTURE(ACFixture, "while_local_optional_binding_member_completion_in_call_arg") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; check(R"( type Test = {name: string, age: number} @@ -6365,7 +6365,7 @@ TEST_CASE_FIXTURE(ACFixture, "while_local_optional_binding_member_completion_in_ TEST_CASE_FIXTURE(ACFixture, "while_local_value_offers_expression_completion") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; check(R"( local thing = {} @@ -6379,7 +6379,7 @@ TEST_CASE_FIXTURE(ACFixture, "while_local_value_offers_expression_completion") TEST_CASE_FIXTURE(ACFixture, "while_local_value_offers_member_completion") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; check(R"( local t = {foo = 1, bar = 2} @@ -6394,7 +6394,7 @@ TEST_CASE_FIXTURE(ACFixture, "while_local_value_offers_member_completion") TEST_CASE_FIXTURE(ACFixture, "while_local_annotation_correctly_suggests_types") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; check(R"( local one = 4 @@ -6409,4 +6409,107 @@ TEST_CASE_FIXTURE(ACFixture, "while_local_annotation_correctly_suggests_types") CHECK(ac.entryMap["two"].typeCorrect == TypeCorrectKind::None); } +TEST_CASE_FIXTURE(ACFixture, "while_condition_start_offers_local_and_const") +{ + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalIfLocalSyntax, true}}; + + check(R"( + while @1 + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("local")); + CHECK(ac.entryMap.count("const")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_condition_partial_name_offers_local_and_const") +{ + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalIfLocalSyntax, true}}; + + check(R"( + while l@1 do + end + while c@2 + )"); + + auto ac = autocomplete('1'); + CHECK(ac.entryMap.count("local")); + CHECK(ac.entryMap.count("const")); + + ac = autocomplete('2'); + CHECK(ac.entryMap.count("local")); + CHECK(ac.entryMap.count("const")); +} + +TEST_CASE_FIXTURE(ACFixture, "while_condition_subexpression_does_not_offer_local_or_const") +{ + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalIfLocalSyntax, true}}; + + check(R"( + local x = true + while x and @1 do + end + while not @2 do + end + )"); + + for (char marker : {'1', '2'}) + { + auto ac = autocomplete(marker); + CHECK(!ac.entryMap.count("local")); + CHECK(!ac.entryMap.count("const")); + } +} + +TEST_CASE_FIXTURE(ACFixture, "while_local_value_does_not_offer_local_or_const") +{ + ScopedFastFlag sffs[] = { + {FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}, {FFlag::LuauExperimentalIfLocalSyntax, true} + }; + + check(R"( + while local x = @1 do + end + )"); + + auto ac = autocomplete('1'); + CHECK(!ac.entryMap.count("local")); + CHECK(!ac.entryMap.count("const")); +} + +TEST_CASE_FIXTURE(ACFixture, "if_and_elseif_condition_start_offers_local_and_const") +{ + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalIfLocalSyntax, true}}; + + check(R"( + if l@1 then + elseif l@2 then + end + if @3 + )"); + + for (char marker : {'1', '2', '3'}) + { + auto ac = autocomplete(marker); + CHECK(ac.entryMap.count("local")); + CHECK(ac.entryMap.count("const")); + } +} + +TEST_CASE_FIXTURE(ACFixture, "if_local_value_does_not_offer_local_or_const") +{ + ScopedFastFlag sffs[] = { + {FFlag::LuauExperimentalIfLocalSyntax, true}, {FFlag::LuauExperimentalIfLocalAnalysis, true}, {FFlag::LuauExperimentalWhileLocalSyntax, true} + }; + + check(R"( + if local x = @1 then + end + )"); + + auto ac = autocomplete('1'); + CHECK(!ac.entryMap.count("local")); + CHECK(!ac.entryMap.count("const")); +} + TEST_SUITE_END(); diff --git a/tests/Compiler.test.cpp b/tests/Compiler.test.cpp index 753fdc903..5ca814d73 100644 --- a/tests/Compiler.test.cpp +++ b/tests/Compiler.test.cpp @@ -42,7 +42,7 @@ LUAU_FASTFLAG(LuauCompileNoFoldVectorEqW) LUAU_FASTFLAG(LuauCompileReuseLocalRegs) LUAU_FASTFLAG(LuauCompileTableBuiltinsCreateClear) LUAU_FASTFLAG(LuauCompileReuseLowersLimit) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) using namespace Luau; @@ -15271,7 +15271,7 @@ RETURN R0 1 TEST_CASE("WhileLocal") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; CHECK_EQ( "\n" + compileFunction0(R"( @@ -15294,7 +15294,7 @@ L1: RETURN R0 0 TEST_CASE("WhileLocalConstantFalse") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; // A constant-false condition means the body never runs, so nothing is emitted for the loop. CHECK_EQ( @@ -15311,7 +15311,7 @@ RETURN R0 0 TEST_CASE("WhileConst") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; // `while const` should be identical to `while local` CHECK_EQ( diff --git a/tests/Conformance.test.cpp b/tests/Conformance.test.cpp index 9290c8e6c..b2d532bcf 100644 --- a/tests/Conformance.test.cpp +++ b/tests/Conformance.test.cpp @@ -19,6 +19,7 @@ #include "Luau/BytecodeSummary.h" #include "Luau/BytecodeDump.h" #include "Luau/Parser.h" +#include "Luau/StringUtils.h" #include "doctest.h" #include "ScopedFlags.h" @@ -56,6 +57,8 @@ void luaC_validate(lua_State* L); #endif LUAU_FASTFLAG(DebugLuauAbortingChecks) +LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauPromoteProto) LUAU_FASTFLAG(LuauBytecodeFold) LUAU_FASTFLAG(LuauBytecodeSlotAlloc) LUAU_FASTFLAG(LuauCodegenA64BitlrotateSelf) @@ -85,7 +88,8 @@ LUAU_FASTFLAG(LuauCodegenCmpAnySideEffecting) LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(LuauCompileCallFbRemap) LUAU_DYNAMIC_FASTFLAG(LuauTableRobustOom) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) +LUAU_FASTFLAG(LuauLoadExplicitGcDisable) #ifndef LUAU_CONFORMANCE_SOURCE_DIR // Walks up from the current directory looking for the Client folder, @@ -978,6 +982,9 @@ void setupUserdataHelpers(lua_State* L) lua_pushvalue(L, -1); lua_setuserdatametatable(L, kTagVertex); + lua_pushliteral(L, "vertex"); + lua_setfield(L, -2, "__type"); + lua_pushcfunction(L, lua_vertex_index, nullptr); lua_setfield(L, -2, "__index"); @@ -1619,6 +1626,8 @@ static void* blockableRealloc(void* ud, void* ptr, size_t osize, size_t nsize) TEST_CASE("GC") { + ScopedFastFlag luauLoadExplicitGcDisable{FFlag::LuauLoadExplicitGcDisable, true}; + runConformance( "gc.luau", [](lua_State* L) @@ -3522,7 +3531,7 @@ TEST_CASE("IfLocal") TEST_CASE("WhileLocal") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}}; runConformance("whilelocal.luau"); } @@ -4945,6 +4954,266 @@ TEST_CASE("NativeUserdata") ); } +static std::string getRecordedFastPathCounters(lua_State* L, const char* global) +{ + struct Context + { + lua_State* L = nullptr; + std::string log; + + int lastLine = -1; + std::string lastInfo; + } context; + + context.L = L; + + lua_getglobal(L, global); + lua_getcounters( + L, + -1, + &context, + [](void* userdata, const char* function, int linedefined) {}, + [](void* userdata, int kind, int line, uint64_t hits) + { + Context& context = *static_cast(userdata); + std::string info; + + switch (Luau::CodeGen::CodeGenCounter(kind)) + { + case Luau::CodeGen::CodeGenCounter::VmRegTagMismatch: + { + // { uint32_t count, uint16_t tagMask, uint8_t vmReg, uint8_t expectedTag + 1 } + uint16_t tagMask = uint16_t(hits >> 32); + uint8_t expectedTag = uint8_t(hits >> 56); + + bool comma = false; + for (int tag = 0; tag < LUA_T_COUNT; tag++) + { + if ((tagMask & (1u << tag)) == 0) + continue; + + Luau::formatAppend(info, "%s%s", comma ? ", " : "", lua_typename(context.L, tag)); + comma = true; + } + + if (expectedTag != 0) + { + Luau::formatAppend(info, "(%s)", lua_typename(context.L, expectedTag - 1)); + comma = true; + } + + context.log += (context.log.empty() ? "" : "; ") + (context.lastLine != line ? Luau::format("line %d: ", line) : "") + info; + break; + } + case Luau::CodeGen::CodeGenCounter::VmRegUserdataTag: + { + // { uint32_t count, uint16_t flags, uint8_t vmReg, uint8_t firstTag + 1 } + uint8_t firstTag = uint8_t(hits >> 56); + bool polymorphic = (hits >> 32) & 1; + + if (firstTag == 0) + return; + + if (firstTag - 1 == kTagVec2) + info += "vec2"; + else if (firstTag - 1 == kTagVertex) + info += "vertex"; + else if (firstTag - 1 == LUA_UTAG_LIMIT + 1) + info += "proxy"; + else + info += std::to_string(firstTag - 1); + + if (polymorphic) + info += " polymorphic"; + + context.log += (context.log.empty() ? "" : "; ") + (context.lastLine != line ? Luau::format("line %d: ", line) : "") + info; + break; + } + default: + break; + } + + context.lastLine = line; + context.lastInfo = info; + } + ); + lua_pop(L, 1); + + return context.log; +} + +TEST_CASE("Promotion") +{ + ScopedFastFlag luauRuntimeFeedback{FFlag::LuauRuntimeFeedback, true}; + ScopedFastFlag luauPromoteProto{FFlag::LuauPromoteProto, true}; + + Luau::CodeGen::CompilationOptions nativeOpts = defaultCodegenOptions(); + + nativeOpts.hooks.vectorAccessBytecodeType = vectorAccessBytecodeType; + nativeOpts.hooks.vectorNamecallBytecodeType = vectorNamecallBytecodeType; + nativeOpts.hooks.vectorAccess = vectorAccess; + nativeOpts.hooks.vectorNamecall = vectorNamecall; + + nativeOpts.hooks.userdataAccess = userdataAccess; + nativeOpts.hooks.userdataMetamethod = userdataMetamethod; + nativeOpts.hooks.userdataNamecall = userdataNamecall; + + nativeOpts.userdataTypes = kUserdataRunTypes; + + StateRef globalState = runConformance( + "promotion.luau", + [](lua_State* L) + { + Luau::CodeGen::setUserdataRemapper(L, kUserdataRunTypes, remapUserdataTypes); + + setupVectorHelpers(L); + setupUserdataHelpers(L); + }, + nullptr, + nullptr, + nullptr, + false, + &nativeOpts + ); + lua_State* L = globalState.get(); + + bool checkTags = codegen && luau_codegen_supported() == 1; + + struct ExpectedCounters + { + int frame = 0; + std::string counters; + }; + + struct PromotionTest + { + const char* test = nullptr; + const char* function = nullptr; + std::vector expectations; + }; + + const PromotionTest tests[] = { + {"test1", + "sumvectors", + { + {0, "line 10: vector(number); vector(number)"}, + {1, "line 10: (vector); (vector)"}, + {9, "line 10: (vector); (vector)"}, + }}, + // vectors seen again after switching back to numbers do not cause another rebuild + {"test2", + "sumvalues", + { + {0, "line 35: (number); (number)"}, + {1, "line 35: vector(number); vector(number)"}, + {2, "line 35: number(vector); number(vector)"}, + {3, "line 35: vector(number); vector(number)"}, + {4, "line 35: (number); (number)"}, + }}, + {"test3", + "sumnumbers", + { + {0, "line 67: (number); (number)"}, + {9, "line 67: (number); (number)"}, + }}, + // switch to generic path with no counter + {"test4", + "iteratecomplex", + { + {0, "line 101: table(number); table(number); table(number)"}, + {1, ""}, + {9, ""}, + }}, + {"test5", + "scalevectors", + { + {0, "line 121: vector(number); number(number); vector(number); vector(number)"}, + {1, "line 121: (vector); (number); (vector); (vector)"}, + {9, "line 121: (vector); (number); (vector); (vector)"}, + }}, + {"test6", + "sumcomponents", + { + {0, "line 146: vector(table); (number); vector(table); (number); (number)"}, + {1, "line 146: (vector); (number); (vector); (number); (number)"}, + {9, "line 146: (vector); (number); (vector); (number); (number)"}, + }}, + // record userdata tags, then switch to the host lowering with no more observations + // tables arriving later go through the fallback, but are too rare to cause a rebuild + {"test7", + "vec2values", + { + {0, "line 171: userdata(table); userdata(table); (number); (number); (number)"}, + {1, "line 171: userdata(userdata); vec2; userdata(userdata); vec2; (number); (number); (number)"}, + {2, "line 171: (userdata); (userdata); (number); (number); (number)"}, + {5, "line 171: table(userdata); table(userdata); (number); (number); (number)"}, + {9, "line 171: table(userdata); table(userdata); (number); (number); (number)"}, + }}, + {"test8", + "vec2operators", + { + {0, "line 204: userdata(number); userdata(number); userdata(number); userdata(number); userdata(number); userdata(number)"}, + {1, + "line 204: userdata(userdata); vec2; userdata(userdata); vec2; userdata(userdata); vec2; " + "userdata(userdata); vec2; userdata(userdata); vec2; userdata(userdata); vec2"}, + {2, "line 204: (userdata); (userdata); (userdata); (userdata); (userdata); (userdata)"}, + {9, "line 204: (userdata); (userdata); (userdata); (userdata); (userdata); (userdata)"}, + }}, + // record userdata tags, then switch to generic path with no counter + {"test9", + "userdatasizes", + { + {0, "line 230: userdata(table); (number)"}, + {1, "line 230: userdata(userdata); vec2 polymorphic; (number)"}, + {2, "line 230: (number)"}, + {9, "line 230: (number)"}, + }}, + {"test10", + "proxysizes", + { + {0, "line 258: userdata(table); (number)"}, + {1, "line 258: userdata(userdata); proxy; (number)"}, + {2, "line 258: (number)"}, + {9, "line 258: (number)"}, + }}, + }; + + for (const PromotionTest& test : tests) + { + INFO(std::string(test.function)); + + int frameCount = test.expectations.back().frame + 1; + int expectedIdx = 0; + + for (int frame = 0; frame < frameCount; frame++) + { + lua_getglobal(L, test.test); + lua_pushinteger(L, frame); + + int status = lua_pcall(L, 1, 0, 0); + REQUIRE(status == LUA_OK); + + // get counter data before promotions might happen + std::string counters = getRecordedFastPathCounters(L, test.function); + + // full GC cycle examines the functions and commits the rebuilds + lua_gc(L, LUA_GCCOLLECT, 0); + + const auto& expected = test.expectations[expectedIdx]; + + if (expected.frame == frame) + { + INFO("frame " << frame); + + if (checkTags) + CHECK_EQ(counters, expected.counters); + + expectedIdx++; + } + } + } +} + TEST_CASE("UserdataDirectAccess") { // Reset global state @@ -5574,29 +5843,6 @@ TEST_CASE("BytecodeDumpLinked") CHECK_EQ(toString(rbc, true), "; function() maxstacksize: 0 upvalues: 0 flags: 0\n"); } -TEST_CASE("SandboxFreezesVectorMetatable") -{ - ScopedFastFlag freezeVectorMetatable{FFlag::LuauSandboxFreezesVectorMetatable, true}; - - StateRef globalState(luaL_newstate(), lua_close); - lua_State* L = globalState.get(); - - lua_pushvector3(L, 0.0f, 0.0f, 0.0f); - - luaL_newmetatable(L, "Vector7"); - lua_pushboolean(L, true); - lua_setfield(L, -2, "Supported"); - - lua_setmetatable(L, -2); - - luaL_sandbox(L); - - lua_pushvector3(L, 0.0f, 0.0f, 0.0f); - - CHECK(lua_getmetatable(L, -1)); - CHECK(lua_getreadonly(L, -1)); -} - TEST_CASE("ClassInheritanceRepeatedCallMemberOffsetCorruption") { // This test ensures that inheritance doesn't mutate the original class object loaded into the constant table. diff --git a/tests/CostModel.test.cpp b/tests/CostModel.test.cpp index dc656ed29..a2abc1c57 100644 --- a/tests/CostModel.test.cpp +++ b/tests/CostModel.test.cpp @@ -6,7 +6,7 @@ #include "doctest.h" LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) using namespace Luau; @@ -254,7 +254,7 @@ end TEST_CASE("WhileLocal") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; uint64_t model = modelFunction(R"( function test(a) @@ -273,7 +273,7 @@ end TEST_CASE("WhileConst") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; // `while const` should be identical to `while local` uint64_t model = modelFunction(R"( diff --git a/tests/FeedbackVector.test.cpp b/tests/FeedbackVector.test.cpp index 2e8a85b76..53033d891 100644 --- a/tests/FeedbackVector.test.cpp +++ b/tests/FeedbackVector.test.cpp @@ -15,6 +15,7 @@ LUAU_FASTINT(LuauInlineHitsThreshold) LUAU_FASTFLAG(LuauEmitCallFeedback) +LUAU_FASTFLAG(LuauCompileRequireNoInline) using namespace Luau; @@ -377,4 +378,24 @@ RETURN R1 1 CHECK_EQ(data->called, true); } +TEST_CASE_FIXTURE(FeedbackVectorFixture, "require_call_blocks_inline") +{ + ScopedFastFlag emitCallFb{FFlag::LuauEmitCallFeedback, true}; + ScopedFastFlag requireNoInline{FFlag::LuauCompileRequireNoInline, true}; + + compile(R"( + local function withRequire() require("mod") return 1 end + local function noRequire() return 1 end + withRequire() + noRequire() + )"); + + Proto* top = load(); + Proto* withRequire = top->p[0]; + Proto* noRequire = top->p[1]; + + CHECK_EQ(withRequire->flags & LPF_INLINABLE, 0); + CHECK_NE(noRequire->flags & LPF_INLINABLE, 0); +} + TEST_SUITE_END(); diff --git a/tests/FragmentAutocomplete.test.cpp b/tests/FragmentAutocomplete.test.cpp index c955a59d9..93ac3eb7e 100644 --- a/tests/FragmentAutocomplete.test.cpp +++ b/tests/FragmentAutocomplete.test.cpp @@ -30,8 +30,8 @@ LUAU_FASTFLAG(LuauAutocompleteIfSlurpsCond) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) LUAU_FASTFLAG(LuauRefactorAutocompleteAncestry) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) static std::optional nullCallback(std::string tag, std::optional ptr, std::optional contents) { @@ -6018,7 +6018,7 @@ function tbl.a@1 TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "while_local_optional_binding_member_completion_in_body") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; const std::string source = R"( type Test = {name: string, age: number} @@ -6054,7 +6054,7 @@ end TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "while_local_optional_binding_is_in_scope_in_body") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; const std::string source = R"( type Test = {name: string, age: number} @@ -6089,7 +6089,7 @@ end TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "nested_while_local_bindings_are_both_in_scope") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; const std::string source = R"( type Test = {name: string, age: number} @@ -6129,7 +6129,7 @@ end TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "while_local_binding_is_not_in_scope_after_while_statement") { - ScopedFastFlag sffs[] = {{FFlag::DebugLuauWhileLocalSyntax, true}, {FFlag::DebugLuauWhileLocalAnalysis, true}}; + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalWhileLocalAnalysis, true}}; const std::string source = R"( type Test = {name: string, age: number} @@ -6162,4 +6162,90 @@ end ); } +TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "while_condition_offers_local_and_const") +{ + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalIfLocalSyntax, true}}; + + const std::string source = R"( +local function sample() +end +)"; + + for (const char* updated : + {"\nlocal function sample()\n while @1\nend\n", + "\nlocal function sample()\n while l@1\nend\n", + "\nlocal function sample()\n while l@1 do\n end\nend\n"}) + { + autocompleteFragmentInBothSolvers( + source, + updated, + '1', + [](FragmentAutocompleteStatusResult& fragment) + { + REQUIRE(fragment.result); + LUAU_CHECK_HAS_KEY(fragment.result->acResults.entryMap, "local"); + LUAU_CHECK_HAS_KEY(fragment.result->acResults.entryMap, "const"); + } + ); + } +} + +TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "if_and_elseif_condition_offers_local_and_const") +{ + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalIfLocalSyntax, true}}; + + const std::string source = R"( +local function sample() +end +)"; + + for (const char* updated : + {"\nlocal function sample()\n if @1\nend\n", + "\nlocal function sample()\n if l@1 then\n end\nend\n", + "\nlocal function sample()\n if false then\n elseif l@1 then\n end\nend\n"}) + { + autocompleteFragmentInBothSolvers( + source, + updated, + '1', + [](FragmentAutocompleteStatusResult& fragment) + { + REQUIRE(fragment.result); + LUAU_CHECK_HAS_KEY(fragment.result->acResults.entryMap, "local"); + LUAU_CHECK_HAS_KEY(fragment.result->acResults.entryMap, "const"); + } + ); + } +} + +TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "while_condition_subexpression_does_not_offer_local_or_const") +{ + ScopedFastFlag sffs[] = {{FFlag::LuauExperimentalWhileLocalSyntax, true}, {FFlag::LuauExperimentalIfLocalSyntax, true}}; + + const std::string source = R"( +local function sample() + local x = true +end +)"; + const std::string updated = R"( +local function sample() + local x = true + while x and @1 do + end +end +)"; + + autocompleteFragmentInBothSolvers( + source, + updated, + '1', + [](FragmentAutocompleteStatusResult& fragment) + { + REQUIRE(fragment.result); + LUAU_CHECK_HAS_NO_KEY(fragment.result->acResults.entryMap, "local"); + LUAU_CHECK_HAS_NO_KEY(fragment.result->acResults.entryMap, "const"); + } + ); +} + TEST_SUITE_END(); diff --git a/tests/IrBuilder.test.cpp b/tests/IrBuilder.test.cpp index 6f2ad3292..5d2a9b888 100644 --- a/tests/IrBuilder.test.cpp +++ b/tests/IrBuilder.test.cpp @@ -18,6 +18,7 @@ LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauIntegerLibrary) LUAU_FASTFLAG(LuauCodegenPropagateFallbackTags) LUAU_FASTFLAG(LuauCodegenCmpAnySideEffecting) +LUAU_FASTFLAG(LuauCodegenX64ConflictCheck) using namespace Luau::CodeGen; @@ -330,6 +331,57 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "FinalX64OptJumpCmpNum") )"); } +TEST_CASE_FIXTURE(IrBuilderFixture, "FinalX64OptNoInlineAcrossStore") +{ + ScopedFastFlag luauCodegenX64ConflictCheck{FFlag::LuauCodegenX64ConflictCheck, true}; + + IrOp block = build.block(IrBlockKind::Internal); + IrOp fallback = build.fallbackBlock(0u); + + build.beginBlock(block); + + // Copy U0 into R4 and load it + build.inst(IrCmd::STORE_TVALUE, build.vmReg(4), build.inst(IrCmd::GET_UPVALUE, build.vmUpvalue(0))); + build.inst(IrCmd::CHECK_TAG, build.vmReg(4), build.constTag(tnumber), fallback); + IrOp x = build.inst(IrCmd::LOAD_DOUBLE, build.vmReg(4)); + + // Copy U1 into R4 and load it + build.inst(IrCmd::STORE_TVALUE, build.vmReg(4), build.inst(IrCmd::GET_UPVALUE, build.vmUpvalue(1))); + build.inst(IrCmd::CHECK_TAG, build.vmReg(4), build.constTag(tnumber), fallback); + IrOp y = build.inst(IrCmd::LOAD_DOUBLE, build.vmReg(4)); + + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(3), build.inst(IrCmd::MUL_NUM, y, x)); + build.inst(IrCmd::STORE_TAG, build.vmReg(3), build.constTag(tnumber)); + build.inst(IrCmd::RETURN, build.constUint(0)); + + build.beginBlock(fallback); + build.inst(IrCmd::RETURN, build.constUint(1)); + + updateUseCounts(build.function); + optimizeMemoryOperandsX64(build.function); + + // After second store to R4, MUL_NUM cannot use earlier R4 value directly on the RHS + CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( +bb_0: + %0 = GET_UPVALUE U0 + STORE_TVALUE R4, %0 + CHECK_TAG R4, tnumber, bb_fallback_1 + %3 = LOAD_DOUBLE R4 + %4 = GET_UPVALUE U1 + STORE_TVALUE R4, %4 + CHECK_TAG R4, tnumber, bb_fallback_1 + %7 = LOAD_DOUBLE R4 + %8 = MUL_NUM %7, %3 + STORE_DOUBLE R3, %8 + STORE_TAG R3, tnumber + RETURN 0u + +bb_fallback_1: + RETURN 1u + +)"); +} + TEST_SUITE_END(); TEST_SUITE_BEGIN("ConstantFolding"); diff --git a/tests/IrLowering.test.cpp b/tests/IrLowering.test.cpp index d64dc6da6..cb10b0d1e 100644 --- a/tests/IrLowering.test.cpp +++ b/tests/IrLowering.test.cpp @@ -30,6 +30,7 @@ LUAU_FASTFLAG(LuauCodegenImprovedExitSync) LUAU_FASTFLAG(LuauCompileReuseLocalRegs) LUAU_FASTFLAG(LuauLoadRemapOptionalUserdata) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) +LUAU_FASTFLAG(LuauRuntimeFeedback) #define ensureVectorSize3() \ if constexpr (LUA_VECTOR_SIZE != 3) \ @@ -7170,6 +7171,32 @@ integer.extract(integer.extract(integer.extract(...,_,_,_,not _,_),_,_,_),_,_,0i ); } +TEST_CASE_FIXTURE(LoweringFixture, "FuzzTest30") +{ + assemblyOptions.compilationOptions.flags = Luau::CodeGen::CodeGen_ColdFunctions; + + CHECK( + getCodegenAssembly( + R"( +--!optimize 1 +type t0 = {n0:any,[(any)&(()->true)]:Part} +export type function t0() +end +for l0=0,# "DoubDoub" do +do end +local _ = true + l0 +for l0=47,# "Doub" do +local _ = nil ~= not _ and ... % _ +do end +end +end +do end +)" + ) + .size() > 0 + ); +} + TEST_CASE_FIXTURE(LoweringFixture, "UpvalueAccessLoadStore1") { CHECK_EQ( @@ -8897,4 +8924,42 @@ end ); } +TEST_CASE_FIXTURE(LoweringFixture, "RuntimeFeedbackCounters") +{ + ScopedFastFlag luauCodeGenRuntimeFeedback{FFlag::LuauRuntimeFeedback, true}; + + assemblyOptions.compilationOptions.runtimeFeedback = true; + assemblyOptions.includeOutlinedCode = true; + + CHECK_EQ( + "\n" + getCodegenAssembly( + R"( +local function foo(a, b) + return a + b +end +)" + ), + R"( +; function foo($arg0, $arg1) line 2 +bb_bytecode_0: + CHECK_TAG R0, tnumber, bb_fallback_1 + CHECK_TAG R1, tnumber, bb_fallback_1 + %4 = LOAD_DOUBLE R0 + %6 = ADD_NUM %4, R1 + STORE_DOUBLE R2, %6 + STORE_TAG R2, tnumber + JUMP bb_2 +bb_2: + INTERRUPT 1u + RETURN R2, 1i +bb_fallback_1: + UPDATE_COUNTERS 0u + ; counters: R0 tag at pcpos 0 (tnumber expected), R1 tag at pcpos 0 (tnumber expected) + SET_SAVEDPC 1u + DO_ARITH R2, R0, R1, 8i + JUMP bb_2 +)" + ); +} + TEST_SUITE_END(); diff --git a/tests/Parser.test.cpp b/tests/Parser.test.cpp index 7da77dd5d..2509327b1 100644 --- a/tests/Parser.test.cpp +++ b/tests/Parser.test.cpp @@ -26,7 +26,7 @@ LUAU_FASTFLAG(DebugLuauParseExactTables) LUAU_FASTFLAG(LuauSingleTypeOptionalPackReturnsAttributeParens) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) // Clip with DebugLuauReportReturnTypeVariadicWithTypeSuffix extern bool luau_telemetry_parsed_return_type_variadic_with_type_suffix; @@ -3475,6 +3475,32 @@ end CHECK(superLocal->local == animal->name); } +TEST_CASE_FIXTURE(Fixture, "class_extends_same_name_refers_to_outer_binding") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( +local Foo = nil +class Foo extends Foo +end + )"); + + REQUIRE(result.errors.empty()); + REQUIRE_EQ(result.root->body.size, 2); + + const AstStatLocal* outer = result.root->body.data[0]->as(); + REQUIRE(outer); + + const AstStatClass* cls = result.root->body.data[1]->as(); + REQUIRE(cls); + REQUIRE(cls->super); + + const AstExprLocal* superLocal = cls->super->as(); + REQUIRE(superLocal); + CHECK(superLocal->local == outer->vars.data[0]); + CHECK(superLocal->local != cls->name); +} + TEST_CASE_FIXTURE(Fixture, "class_exported_open") { ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; @@ -4192,8 +4218,8 @@ TEST_CASE_FIXTURE(Fixture, "class_private_method_call") ParseResult result = tryParse(R"( class Point - function getMag(self) - return self:_mag() + function getMag(self) + return self:_mag() end end )"); @@ -7109,7 +7135,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_if_local_expression_nested_in_true_branch") TEST_CASE_FIXTURE(Fixture, "parse_while_local") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; AstStatBlock* block = parse(R"( while local x = getValue() do @@ -7130,7 +7156,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_while_local") TEST_CASE_FIXTURE(Fixture, "parse_while_const") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; AstStatBlock* block = parse(R"( while const x = getValue() do @@ -7149,7 +7175,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_while_const") TEST_CASE_FIXTURE(Fixture, "parse_while_const_with_annotation") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; AstStatBlock* block = parse(R"( while const x: number = getValue() do @@ -7168,7 +7194,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_while_const_with_annotation") TEST_CASE_FIXTURE(Fixture, "parse_while_const_compat") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; // `const` not followed by a binding name is a plain condition expression (the global `const`), // not a `while const` binding, keeping `const` usable as an ordinary identifier @@ -7188,7 +7214,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_while_const_compat") TEST_CASE_FIXTURE(Fixture, "parse_while_local_with_annotation") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; AstStatBlock* block = parse(R"( while local x: number = getValue() do @@ -7206,7 +7232,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_while_local_with_annotation") TEST_CASE_FIXTURE(Fixture, "parse_while_local_binding_visible_in_body") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; AstStatBlock* block = parse(R"( while local x = getValue() do @@ -7232,7 +7258,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_while_local_binding_visible_in_body") TEST_CASE_FIXTURE(Fixture, "parse_while_local_binding_not_visible_in_condition") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; // `x` in the condition is the outer global, not the loop binding, since the binding is pushed // only after the condition is parsed @@ -7250,7 +7276,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_while_local_binding_not_visible_in_condition") TEST_CASE_FIXTURE(Fixture, "parse_while_local_nested") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; AstStatBlock* block = parse(R"( while local x = a() do @@ -7275,7 +7301,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_while_local_nested") TEST_CASE_FIXTURE(Fixture, "parse_while_local_cst_annotation_colon_position") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; ParseOptions parseOptions; parseOptions.storeCstData = true; @@ -7295,7 +7321,7 @@ TEST_CASE_FIXTURE(Fixture, "parse_while_local_cst_annotation_colon_position") TEST_CASE_FIXTURE(Fixture, "parse_while_const_cst_annotation_colon_position") { - ScopedFastFlag sff = {FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff = {FFlag::LuauExperimentalWhileLocalSyntax, true}; ParseOptions parseOptions; parseOptions.storeCstData = true; diff --git a/tests/PrettyPrinter.test.cpp b/tests/PrettyPrinter.test.cpp index acde29715..9f9eb963b 100644 --- a/tests/PrettyPrinter.test.cpp +++ b/tests/PrettyPrinter.test.cpp @@ -12,7 +12,7 @@ LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(DebugLuauNoInline) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) using namespace Luau; @@ -105,7 +105,7 @@ TEST_CASE("if_local") TEST_CASE("while_local") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; const std::string local = R"(while local item = next() do process(item) end)"; CHECK_EQ(local, prettyPrint(local).code); @@ -113,7 +113,7 @@ TEST_CASE("while_local") TEST_CASE("while_local_preserves_interior_spacing") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; const std::string spaced = R"(while local item = next() do process(item) end)"; CHECK_EQ(spaced, prettyPrint(spaced).code); @@ -121,7 +121,7 @@ TEST_CASE("while_local_preserves_interior_spacing") TEST_CASE("while_local_type_annotation") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; const std::string typed = R"(while local res : string = foo() do print(res) end)"; CHECK_EQ(typed, prettyPrint(typed, {}, /* withTypes */ true).code); @@ -133,7 +133,7 @@ TEST_CASE("while_local_type_annotation") TEST_CASE("while_local_without_annotation_with_types") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; const std::string local = R"(while local item = next() do process(item) end)"; CHECK_EQ(local, prettyPrint(local, {}, /* withTypes */ true).code); @@ -141,7 +141,7 @@ TEST_CASE("while_local_without_annotation_with_types") TEST_CASE("while_const") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; const std::string konst = R"(while const item = next() do process(item) end)"; CHECK_EQ(konst, prettyPrint(konst).code); @@ -149,7 +149,7 @@ TEST_CASE("while_const") TEST_CASE("while_const_type_annotation") { - ScopedFastFlag sff{FFlag::DebugLuauWhileLocalSyntax, true}; + ScopedFastFlag sff{FFlag::LuauExperimentalWhileLocalSyntax, true}; const std::string typed = R"(while const res : string = foo() do print(res) end)"; CHECK_EQ(typed, prettyPrint(typed, {}, /* withTypes */ true).code); diff --git a/tests/TypeFunction.user.test.cpp b/tests/TypeFunction.user.test.cpp index ec80d21fd..a0b4d5ea5 100644 --- a/tests/TypeFunction.user.test.cpp +++ b/tests/TypeFunction.user.test.cpp @@ -1298,34 +1298,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_calling_each_other_unordered") CHECK(toString(tm->givenType) == "\"hi\""); } -TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_no_shared_state") -{ - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; - ScopedFastFlag terseChunkNames{FFlag::LuauUdtfTerseChunkNames, true}; - - CheckResult result = check(R"( - type function foo() - if not glob then - glob = 'a' - else - glob ..= 'b' - end - - return glob - end - type function bar(prefix) - return types.singleton(tostring(prefix:value()) .. foo()) - end - local function ok1(idx: bar<'x'>): nil return idx end - local function ok2(idx: bar<'y'>): nil return idx end - )"); - - // We are only checking first errors, others are mostly duplicates - LUAU_REQUIRE_ERROR_COUNT(5, result); - CHECK(toString(result.errors[0]) == R"(Unknown global 'glob'; consider assigning to it first)"); - CHECK(toString(result.errors[1]) == R"('bar' type function errored at runtime: foo:4: attempt to modify a readonly table)"); -} - TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_math_reset") { if (FFlag::DebugLuauForceOldSolver) diff --git a/tests/TypeInfer.classes.test.cpp b/tests/TypeInfer.classes.test.cpp index 0a5fb7b5e..031d54632 100644 --- a/tests/TypeInfer.classes.test.cpp +++ b/tests/TypeInfer.classes.test.cpp @@ -1431,4 +1431,15 @@ TEST_CASE_FIXTURE(ClassesFixture, "fuzzer_oct_20") )")); } +TEST_CASE_FIXTURE(ClassesFixture, "fuzzer_oct_21") +{ + LUAU_REQUIRE_ERRORS(check(R"( + export class l0 + end + local l0 = l0 + export class l0 extends l0 + end + )")); +} + TEST_SUITE_END(); diff --git a/tests/TypeInfer.provisional.test.cpp b/tests/TypeInfer.provisional.test.cpp index 5bd023826..11898ef6b 100644 --- a/tests/TypeInfer.provisional.test.cpp +++ b/tests/TypeInfer.provisional.test.cpp @@ -23,7 +23,6 @@ LUAU_FASTINT(LuauTypeInferRecursionLimit) LUAU_FASTINT(LuauTypeInferTypePackLoopLimit) LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauImproveUniqueTableWidthSubtyping) -LUAU_FASTFLAG(LuauRemoveConstraintSolverEmplace) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) TEST_SUITE_BEGIN("ProvisionalTests"); @@ -1504,7 +1503,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2305_keyof_index_example") { ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauRemoveConstraintSolverEmplace, true}, }; CheckResult results = check(R"( diff --git a/tests/TypeInfer.refinements.test.cpp b/tests/TypeInfer.refinements.test.cpp index 4fb2dfb48..09987e2c2 100644 --- a/tests/TypeInfer.refinements.test.cpp +++ b/tests/TypeInfer.refinements.test.cpp @@ -11,15 +11,14 @@ LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(DebugLuauAssertOnForcedConstraint) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) -LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) LUAU_FASTFLAG(DebugLuauCFG) LUAU_FASTFLAG(LuauIterativeTypeSearcher) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) LUAU_FASTFLAG(LuauRefineNotNilWaitsForBlockedTarget) -LUAU_FASTFLAG(DebugLuauWhileLocalSyntax) -LUAU_FASTFLAG(DebugLuauWhileLocalAnalysis) +LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) +LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) using namespace Luau; @@ -4020,8 +4019,8 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_not_nil_waits_for_blocked_target") TEST_CASE_FIXTURE(BuiltinsFixture, "while_local_narrows_to_truthy_both_solvers") { ScopedFastFlag sffs[] = { - {FFlag::DebugLuauWhileLocalSyntax, true}, - {FFlag::DebugLuauWhileLocalAnalysis, true}, + {FFlag::LuauExperimentalWhileLocalSyntax, true}, + {FFlag::LuauExperimentalWhileLocalAnalysis, true}, }; CheckResult result = check(R"( @@ -4041,8 +4040,8 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "while_local_narrows_to_truthy_both_solvers") TEST_CASE_FIXTURE(BuiltinsFixture, "while_const_narrows_to_truthy") { ScopedFastFlag sffs[] = { - {FFlag::DebugLuauWhileLocalSyntax, true}, - {FFlag::DebugLuauWhileLocalAnalysis, true}, + {FFlag::LuauExperimentalWhileLocalSyntax, true}, + {FFlag::LuauExperimentalWhileLocalAnalysis, true}, }; CheckResult result = check(R"( @@ -4058,4 +4057,39 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "while_const_narrows_to_truthy") CHECK_EQ("number", toString(requireTypeAtPosition({3, 26}))); } +TEST_CASE_FIXTURE(BuiltinsFixture, "while_local_doesnt_visit_annotation_1") +{ + ScopedFastFlag sffs[] = { + {FFlag::LuauExperimentalWhileLocalSyntax, true}, + {FFlag::LuauExperimentalWhileLocalAnalysis, true}, + }; + + // Prior this would assert as `y` was missing a refinement key. + CheckResult result = check(R"( + while local x: typeof(y) = nil :: any + end + )"); + + LUAU_REQUIRE_ERRORS(result); +} + +TEST_CASE_FIXTURE(BuiltinsFixture, "while_local_doesnt_visit_annotation_2") +{ + ScopedFastFlag sffs[] = { + {FFlag::LuauExperimentalWhileLocalSyntax, true}, + {FFlag::LuauExperimentalWhileLocalAnalysis, true}, + }; + + // Prior this would assert as `y` was missing a refinement key. + CheckResult result = check(R"( + y = {1,2,3} + while local x: typeof(y) = {} do + print("hi") + end + + )"); + + LUAU_REQUIRE_ERRORS(result); +} + TEST_SUITE_END(); diff --git a/tests/TypeInfer.tables.test.cpp b/tests/TypeInfer.tables.test.cpp index a4461ea1b..316a5df4a 100644 --- a/tests/TypeInfer.tables.test.cpp +++ b/tests/TypeInfer.tables.test.cpp @@ -24,7 +24,6 @@ LUAU_FASTFLAG(LuauInstantiateInSubtyping) LUAU_FASTFLAG(LuauFixIndexerSubtypingOrdering) LUAU_FASTFLAG(DebugLuauAssertOnForcedConstraint) LUAU_FASTINT(LuauPrimitiveInferenceInTableLimit) -LUAU_FASTFLAG(LuauRemoveConstraintSolverEmplace) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) LUAU_FASTFLAG(DebugLuauParseExactTables) LUAU_FASTFLAG(DebugLuauExactTableTypes) @@ -32,6 +31,7 @@ LUAU_FASTFLAG(LuauTraverseScopeToFunction) LUAU_FASTFLAG(LuauInferReadOnlyIndexers) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) +LUAU_FASTFLAG(LuauEqualityConstraintBinds) LUAU_FASTFLAG(LuauNonreentrantLookupTableProp) namespace @@ -1349,6 +1349,11 @@ TEST_CASE_FIXTURE(Fixture, "result_is_bool_for_equality_operators_if_lhs_is_any" TEST_CASE_FIXTURE(Fixture, "inequality_operators_imply_exactly_matching_types") { + ScopedFastFlag sffs[] = { + {FFlag::DebugLuauAssertOnForcedConstraint, true}, + {FFlag::LuauEqualityConstraintBinds, true}, + }; + CheckResult result = check(R"( function abs(n) if n < 0 then @@ -5264,8 +5269,6 @@ end TEST_CASE_FIXTURE(Fixture, "indexing_branching_table") { - ScopedFastFlag _{FFlag::LuauRemoveConstraintSolverEmplace, true}; - CheckResult result = check(R"( local test = if true then { "meow", "woof" } else { 4, 81 } local test2 = test[1] @@ -7385,7 +7388,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "intersection_of_indexers_1") { ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauRemoveConstraintSolverEmplace, true}, }; LUAU_REQUIRE_NO_ERRORS(check(R"( @@ -7401,7 +7403,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "intersection_of_indexers_2") { ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauRemoveConstraintSolverEmplace, true}, }; LUAU_REQUIRE_NO_ERRORS(check(R"( @@ -7417,7 +7418,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "intersection_of_indexers_3") { ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauRemoveConstraintSolverEmplace, true}, }; LUAU_REQUIRE_NO_ERRORS(check(R"( @@ -7433,7 +7433,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "union_of_indexers_1") { ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauRemoveConstraintSolverEmplace, true}, }; LUAU_REQUIRE_NO_ERRORS(check(R"( @@ -7449,7 +7448,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "union_of_indexers_2") { ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauRemoveConstraintSolverEmplace, true}, }; LUAU_REQUIRE_NO_ERRORS(check(R"( @@ -7465,7 +7463,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "union_of_indexers_3") { ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauRemoveConstraintSolverEmplace, true}, }; LUAU_REQUIRE_NO_ERRORS(check(R"( @@ -7499,7 +7496,6 @@ TEST_CASE_FIXTURE(Fixture, "test_indexing_into_unsealed_table") { ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::LuauRemoveConstraintSolverEmplace, true}, }; CheckResult results = check(R"( diff --git a/tests/conformance/gc.luau b/tests/conformance/gc.luau index abd01f933..b5766928d 100644 --- a/tests/conformance/gc.luau +++ b/tests/conformance/gc.luau @@ -243,6 +243,33 @@ do setblockallocations(false) end +-- explicit GC does not have effect during bytecode load +do + collectgarbage("restart") + + for i = 1,3 do + local called = false + gcimport = setmetatable({}, {__index = function(t, k) + if i == 2 then collectgarbage("restart") end + if i == 3 then + for k = 1,10000 do coroutine.create(function() end) end + else + collectgarbage("collect") + end + + called = true + return k + end}) + + local f = loadstring("local s = 'some' .. tostring(1); return gcimport.value, s") + assert(called) + + local a, b = f() + assert(a == "value" and b == "some1") + gcimport = nil + end +end + -- testing userdata collectgarbage("stop") -- stop collection local u = newproxy(true) diff --git a/tests/conformance/promotion.luau b/tests/conformance/promotion.luau new file mode 100644 index 000000000..d464d9a53 --- /dev/null +++ b/tests/conformance/promotion.luau @@ -0,0 +1,280 @@ +-- This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details +print("testing native code genearation auto-promotion and rebuild") + +@native +function sumvectors(start, table) + local sum = start + + for j = 1,1000 do + for i, v in table do + sum = sum + v + end + end + + return sum +end + +-- function should switch to vectors +function test1(frame) + local t = {} + + for j = 1, 100 do + table.insert(t, vector.create(1, 2, 3)) + end + + local res = sumvectors(vector.create(0, 0, 0), t) + assert(res == vector.create(100000, 200000, 300000)) +end + +@native +function sumvalues(start, table) + local sum = start + + for j = 1,1000 do + for i, v in table do + sum = sum + v + end + end + + return sum +end + +-- function is switches between numbers and vectors, so remains on the number-focused path +function test2(frame) + local usevectors = frame == 1 or frame == 3 + + local t = {} + + for j = 1, 100 do + table.insert(t, if usevectors then vector.create(1, 2, 3) else 1) + end + + local res = sumvalues(if usevectors then vector.create(0, 0, 0) else 0, t) + + if usevectors then + assert(res == vector.create(100000, 200000, 300000)) + else + assert(res == 100000) + end +end + +@native +function sumnumbers(start, table) + local sum = start + + for j = 1,1000 do + for i, v in table do + sum = sum + v + end + end + + return sum +end + +-- no rebuilds for expected path +function test3(frame) + local t = {} + + for j = 1, 100 do + table.insert(t, 1) + end + + local res = sumnumbers(0, t) + assert(res == 100000) +end + +local Complex = {} + +Complex.__add = function(a, b) + return setmetatable({ re = a.re + b.re, im = a.im + b.im }, Complex) +end + +Complex.__mul = function(a, b) + return setmetatable({ re = a.re * b.re - a.im * b.im, im = a.re * b.im + a.im * b.re }, Complex) +end + +@native +function iteratecomplex(c, count) + local z = c + + for i = 1, count do + z = z * z + c + end + + return z +end + +-- function is specialized for a generic case +function test4(frame) + for j = 1, 1000 do + local z = iteratecomplex(setmetatable({ re = 0, im = 0 }, Complex), 100) + assert(z.re == 0 and z.im == 0) + end +end + +@native +function scalevectors(start, table, scale) + local sum = start + + for j = 1,1000 do + for i, v in table do + sum = sum + v * scale + end + end + + return sum +end + +-- function is specialized for a number/vector mixed operation +function test5(frame) + local t = {} + + for j = 1, 100 do + table.insert(t, vector.create(1, 2, 3)) + end + + local res = scalevectors(vector.create(0, 0, 0), t, 2) + assert(res == vector.create(200000, 400000, 600000)) +end + +@native +function sumcomponents(table) + local sum = 0 + + for j = 1,1000 do + for i, v in table do + sum = sum + v.X + v.Y + end + end + + return sum +end + +-- field access should switch to vectors +function test6(frame) + local t = {} + + for j = 1, 100 do + table.insert(t, vector.create(1, 2, 3)) + end + + local res = sumcomponents(t) + assert(res == 300000) +end + +@native +function vec2values(values) + local sum = 0 + + for j = 1,1000 do + for _, v in values do + sum += v.X + v:Dot(v) + end + end + + return sum +end + +-- field access and method call should record the userdata tag and then switch to the host lowering of vec2 +-- later, tables with the same field and method go through the fallback +function test7(frame) + local values = {} + + for j = 1, 100 do + table.insert(values, vec2(1, 2)) + end + + local expected = 1000 * 100 * (1 + 5) + + if frame >= 5 then + table.insert(values, { X = 1, Dot = function(self, other) return 2 end }) + expected += 1000 * 3 + end + + local res = vec2values(values) + assert(res == expected) +end + +@native +function vec2operators(values) + local sum = vec2(0, 0) + + for j = 1,1000 do + for _, v in values do + sum = sum + v * v + -v + end + end + + return sum +end + +-- arithmetic should record the userdata tag and then switch to the host lowering of vec2 +function test8(frame) + local values = {} + + for j = 1, 100 do + table.insert(values, vec2(1, 2)) + end + + -- each value adds (1 * 1 - 1, 2 * 2 - 2) + local res = vec2operators(values) + assert(res.X == 0 and res.Y == 1000 * 100 * 2) +end + +@native +function userdatasizes(values) + local sum = 0 + + for j = 1,1000 do + for _, v in values do + sum += v.sizeof + end + end + + return sum +end + +-- field access sees userdata with different tags, so it switches to the generic path +function test9(frame) + local values = {} + + for j = 1, 50 do + table.insert(values, vec2(1, 2)) + table.insert(values, vertex(vector.create(0, 0, 0), vector.create(0, 1, 0), vec2(1, 2))) + end + + local expected = 1000 * 50 * (vec2(1, 2).sizeof + values[2].sizeof) + + local res = userdatasizes(values) + assert(res == expected) +end + +@native +function proxysizes(values) + local sum = 0 + + for j = 1,1000 do + for _, v in values do + sum += v.sizeof + end + end + + return sum +end + +-- field access sees a userdata which doesn't map to a host type, so it switches to the generic path +function test10(frame) + local proxy = newproxy(true) + getmetatable(proxy).__index = function(self, key) return 4 end + + local values = {} + + for j = 1, 100 do + table.insert(values, proxy) + end + + local res = proxysizes(values) + assert(res == 1000 * 100 * 4) +end + +return 'OK' diff --git a/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-off.nonstrict.output b/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-off.runtime.output b/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-off.strict.output b/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-off.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-on.nonstrict.output b/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-on.runtime.output b/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-on.strict.output b/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.luau b/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.luau new file mode 100644 index 000000000..d1db44ed7 --- /dev/null +++ b/tests/golden/analysis/classes/constructor_is_allowed_when_no_ancestor_has_one.luau @@ -0,0 +1,23 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true + +open class Base + public x: number +end + +open class Middle extends Base +end + +class Leaf extends Middle +end + +class ChildWithConstructor extends Base + function __init(self) end +end + +open class WithConstructor + function __init(self) end +end + +class ChildAlsoWithConstructor extends WithConstructor + function __init(self) end +end diff --git a/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.nonstrict.output b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.nonstrict.output new file mode 100644 index 000000000..46f014f02 --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.nonstrict.output @@ -0,0 +1,3 @@ +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(17,1): TypeError: 'OverridingLeaf' inherits a constructor from 'Overriding', so it needs to define one too +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(10,1): TypeError: 'Leaf' inherits a constructor from 'Base', so it needs to define one too +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(7,1): TypeError: 'Middle' inherits a constructor from 'Base', so it needs to define one too diff --git a/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.runtime.output b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.strict.output b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.strict.output new file mode 100644 index 000000000..39fc72d56 --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-off.strict.output @@ -0,0 +1,3 @@ +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(7,1): TypeError: 'Middle' inherits a constructor from 'Base', so it needs to define one too +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(10,1): TypeError: 'Leaf' inherits a constructor from 'Base', so it needs to define one too +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(17,1): TypeError: 'OverridingLeaf' inherits a constructor from 'Overriding', so it needs to define one too diff --git a/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.nonstrict.output b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.nonstrict.output new file mode 100644 index 000000000..46f014f02 --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.nonstrict.output @@ -0,0 +1,3 @@ +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(17,1): TypeError: 'OverridingLeaf' inherits a constructor from 'Overriding', so it needs to define one too +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(10,1): TypeError: 'Leaf' inherits a constructor from 'Base', so it needs to define one too +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(7,1): TypeError: 'Middle' inherits a constructor from 'Base', so it needs to define one too diff --git a/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.runtime.output b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.strict.output b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.strict.output new file mode 100644 index 000000000..39fc72d56 --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.flags-on.strict.output @@ -0,0 +1,3 @@ +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(7,1): TypeError: 'Middle' inherits a constructor from 'Base', so it needs to define one too +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(10,1): TypeError: 'Leaf' inherits a constructor from 'Base', so it needs to define one too +./analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau(17,1): TypeError: 'OverridingLeaf' inherits a constructor from 'Overriding', so it needs to define one too diff --git a/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau new file mode 100644 index 000000000..983dac53e --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_ancestor_defines_one_is_an_error.luau @@ -0,0 +1,18 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true + +open class Base + function __init(self) end +end + +open class Middle extends Base +end + +class Leaf extends Middle +end + +open class Overriding extends Base + function __init(self) end +end + +class OverridingLeaf extends Overriding +end diff --git a/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.nonstrict.output b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.nonstrict.output new file mode 100644 index 000000000..f0321d24d --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/missing_constructor_when_superclass_defines_one_errors.luau(11,1): TypeError: 'Dog' inherits a constructor from 'Animal', so it needs to define one too diff --git a/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.runtime.output b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.strict.output b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.strict.output new file mode 100644 index 000000000..f0321d24d --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-off.strict.output @@ -0,0 +1 @@ +./analysis/classes/missing_constructor_when_superclass_defines_one_errors.luau(11,1): TypeError: 'Dog' inherits a constructor from 'Animal', so it needs to define one too diff --git a/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.nonstrict.output b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.nonstrict.output new file mode 100644 index 000000000..f0321d24d --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/missing_constructor_when_superclass_defines_one_errors.luau(11,1): TypeError: 'Dog' inherits a constructor from 'Animal', so it needs to define one too diff --git a/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.runtime.output b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.strict.output b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.strict.output new file mode 100644 index 000000000..f0321d24d --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/classes/missing_constructor_when_superclass_defines_one_errors.luau(11,1): TypeError: 'Dog' inherits a constructor from 'Animal', so it needs to define one too diff --git a/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.luau b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.luau new file mode 100644 index 000000000..0795e2dfd --- /dev/null +++ b/tests/golden/analysis/classes/missing_constructor_when_superclass_defines_one_errors.luau @@ -0,0 +1,13 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true + +open class Animal + public name: string + + function __init(self, name: string) + self.name = name + end +end + +class Dog extends Animal + function bark(self) end +end diff --git a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.runtime.output b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.runtime.output index dc16dc86b..895584f2a 100644 --- a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.runtime.output +++ b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.runtime.output @@ -1,3 +1,3 @@ -./analysis/classes/sqrt_cyclically_inherits_sqrt.luau:3: Non-open class 'sqrt' cannot be extended +./analysis/classes/sqrt_cyclically_inherits_sqrt.luau:3: attempt to extend a nil value stacktrace: ./analysis/classes/sqrt_cyclically_inherits_sqrt.luau:3 diff --git a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.strict.output b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.strict.output index ccfa13588..a56aa0e54 100644 --- a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.strict.output +++ b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.strict.output @@ -1 +1 @@ -./analysis/classes/sqrt_cyclically_inherits_sqrt.luau(3,20): TypeError: Non-open class sqrt cannot be extended +./analysis/classes/sqrt_cyclically_inherits_sqrt.luau(3,20): TypeError: Unknown global 'sqrt'; consider assigning to it first diff --git a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.runtime.output b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.runtime.output index dc16dc86b..895584f2a 100644 --- a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.runtime.output +++ b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.runtime.output @@ -1,3 +1,3 @@ -./analysis/classes/sqrt_cyclically_inherits_sqrt.luau:3: Non-open class 'sqrt' cannot be extended +./analysis/classes/sqrt_cyclically_inherits_sqrt.luau:3: attempt to extend a nil value stacktrace: ./analysis/classes/sqrt_cyclically_inherits_sqrt.luau:3 diff --git a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.strict.output b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.strict.output index ccfa13588..a56aa0e54 100644 --- a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.strict.output +++ b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.strict.output @@ -1 +1 @@ -./analysis/classes/sqrt_cyclically_inherits_sqrt.luau(3,20): TypeError: Non-open class sqrt cannot be extended +./analysis/classes/sqrt_cyclically_inherits_sqrt.luau(3,20): TypeError: Unknown global 'sqrt'; consider assigning to it first diff --git a/tests/golden/analysis/refinements/malformed_comparisons.flags-off.nonstrict.output b/tests/golden/analysis/refinements/malformed_comparisons.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/malformed_comparisons.flags-off.runtime.output b/tests/golden/analysis/refinements/malformed_comparisons.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/malformed_comparisons.flags-off.strict.output b/tests/golden/analysis/refinements/malformed_comparisons.flags-off.strict.output new file mode 100644 index 000000000..7bb51c081 --- /dev/null +++ b/tests/golden/analysis/refinements/malformed_comparisons.flags-off.strict.output @@ -0,0 +1,3 @@ +./analysis/refinements/malformed_comparisons.luau(4,12): TypeError: Types number & string and string cannot be compared with > because they do not have the same metatable +_luau_print (8, 9): (number & string) -> () + diff --git a/tests/golden/analysis/refinements/malformed_comparisons.flags-on.nonstrict.output b/tests/golden/analysis/refinements/malformed_comparisons.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/malformed_comparisons.flags-on.runtime.output b/tests/golden/analysis/refinements/malformed_comparisons.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/refinements/malformed_comparisons.flags-on.strict.output b/tests/golden/analysis/refinements/malformed_comparisons.flags-on.strict.output new file mode 100644 index 000000000..458a2783f --- /dev/null +++ b/tests/golden/analysis/refinements/malformed_comparisons.flags-on.strict.output @@ -0,0 +1,3 @@ +./analysis/refinements/malformed_comparisons.luau(4,12): TypeError: Cannot compare unrelated types 'number' and 'string' with '>' +_luau_print (8, 9): (number) -> () + diff --git a/tests/golden/analysis/refinements/malformed_comparisons.luau b/tests/golden/analysis/refinements/malformed_comparisons.luau new file mode 100644 index 000000000..cd7542007 --- /dev/null +++ b/tests/golden/analysis/refinements/malformed_comparisons.luau @@ -0,0 +1,9 @@ +local function foo(x) + if x < 0 then + print("less than zero") + elseif x > "huh" then + print("more than 'huh'") + end +end + +local _: _luau_print \ No newline at end of file diff --git a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.nonstrict.output index e69de29bb..45fe2409b 100644 --- a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.nonstrict.output +++ b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.nonstrict.output @@ -0,0 +1,3 @@ +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(3,11): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(8,1): SyntaxError: Expected 'end' (to close 'function' at line 1), got ; did you forget to close 'do' at line 3? +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(3,17): LocalUnused: Variable 'x' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.strict.output index 5c8159de2..dc8708340 100644 --- a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.strict.output +++ b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-off.strict.output @@ -1,2 +1,5 @@ -./analysis/refinements/while_local_annotation_rejects_optional_source.luau(5,29): TypeError: Expected this to be 'string', but got 'string?'; +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(3,11): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(8,1): SyntaxError: Expected 'end' (to close 'function' at line 1), got ; did you forget to close 'do' at line 3? +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(3,29): TypeError: Expected this to be 'string', but got 'string?'; `nil` is not a subtype of `string` +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(3,17): LocalUnused: Variable 'x' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.strict.output b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.strict.output index 5c8159de2..265365c07 100644 --- a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.strict.output +++ b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.flags-on.strict.output @@ -1,2 +1,2 @@ -./analysis/refinements/while_local_annotation_rejects_optional_source.luau(5,29): TypeError: Expected this to be 'string', but got 'string?'; +./analysis/refinements/while_local_annotation_rejects_optional_source.luau(3,29): TypeError: Expected this to be 'string', but got 'string?'; `nil` is not a subtype of `string` diff --git a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.luau b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.luau index b47e4c0c2..cd220791f 100644 --- a/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.luau +++ b/tests/golden/analysis/refinements/while_local_annotation_rejects_optional_source.luau @@ -1,5 +1,3 @@ ---!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true - local function f(v: string?) -- the annotation does not narrow the condition's value: `v` is still `string?` here while local x: string = v do diff --git a/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.nonstrict.output index e69de29bb..4936da1eb 100644 --- a/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.nonstrict.output +++ b/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/refinements/while_local_basic_typecheck.luau(2,11): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_basic_typecheck.luau(9,1): SyntaxError: Expected 'end' (to close 'function' at line 1), got ; did you forget to close 'do' at line 2? diff --git a/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.strict.output index e69de29bb..643d5a476 100644 --- a/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.strict.output +++ b/tests/golden/analysis/refinements/while_local_basic_typecheck.flags-off.strict.output @@ -0,0 +1,3 @@ +./analysis/refinements/while_local_basic_typecheck.luau(2,11): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_basic_typecheck.luau(9,1): SyntaxError: Expected 'end' (to close 'function' at line 1), got ; did you forget to close 'do' at line 2? +./analysis/refinements/while_local_basic_typecheck.luau(4,15): TypeError: Operator '+' could not be applied to operands of types number? and number; there is no corresponding overload for __add diff --git a/tests/golden/analysis/refinements/while_local_basic_typecheck.luau b/tests/golden/analysis/refinements/while_local_basic_typecheck.luau index 26e2b229c..bed8065da 100644 --- a/tests/golden/analysis/refinements/while_local_basic_typecheck.luau +++ b/tests/golden/analysis/refinements/while_local_basic_typecheck.luau @@ -1,5 +1,3 @@ ---!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true - local function f(v: number?) while local x = v do -- arithmetic requires `x` to have narrowed from `number?` to `number` diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.nonstrict.output index ad5fd3bff..274582135 100644 --- a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.nonstrict.output +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.nonstrict.output @@ -1,2 +1,2 @@ -./analysis/refinements/while_local_binding_not_visible_after_block.luau(10,7): TypeError: Unknown global 'x'; consider assigning to it first -./analysis/refinements/while_local_binding_not_visible_after_block.luau(4,13): LocalShadow: Variable 'x' shadows a global variable used at line 10 +./analysis/refinements/while_local_binding_not_visible_after_block.luau(2,7): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_binding_not_visible_after_block.luau(9,1): SyntaxError: Expected 'end' (to close 'local' at line 2), got diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.strict.output index ad5fd3bff..3f434296d 100644 --- a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.strict.output +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-off.strict.output @@ -1,2 +1,3 @@ -./analysis/refinements/while_local_binding_not_visible_after_block.luau(10,7): TypeError: Unknown global 'x'; consider assigning to it first -./analysis/refinements/while_local_binding_not_visible_after_block.luau(4,13): LocalShadow: Variable 'x' shadows a global variable used at line 10 +./analysis/refinements/while_local_binding_not_visible_after_block.luau(2,7): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_binding_not_visible_after_block.luau(9,1): SyntaxError: Expected 'end' (to close 'local' at line 2), got +./analysis/refinements/while_local_binding_not_visible_after_block.luau(5,21): TypeError: Expected this to be 'true', but got 'boolean' diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.nonstrict.output b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.nonstrict.output index ad5fd3bff..7b9013dba 100644 --- a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.nonstrict.output +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.nonstrict.output @@ -1,2 +1,2 @@ -./analysis/refinements/while_local_binding_not_visible_after_block.luau(10,7): TypeError: Unknown global 'x'; consider assigning to it first -./analysis/refinements/while_local_binding_not_visible_after_block.luau(4,13): LocalShadow: Variable 'x' shadows a global variable used at line 10 +./analysis/refinements/while_local_binding_not_visible_after_block.luau(8,7): TypeError: Unknown global 'x'; consider assigning to it first +./analysis/refinements/while_local_binding_not_visible_after_block.luau(2,13): LocalShadow: Variable 'x' shadows a global variable used at line 8 diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.strict.output b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.strict.output index ad5fd3bff..7b9013dba 100644 --- a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.strict.output +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.flags-on.strict.output @@ -1,2 +1,2 @@ -./analysis/refinements/while_local_binding_not_visible_after_block.luau(10,7): TypeError: Unknown global 'x'; consider assigning to it first -./analysis/refinements/while_local_binding_not_visible_after_block.luau(4,13): LocalShadow: Variable 'x' shadows a global variable used at line 10 +./analysis/refinements/while_local_binding_not_visible_after_block.luau(8,7): TypeError: Unknown global 'x'; consider assigning to it first +./analysis/refinements/while_local_binding_not_visible_after_block.luau(2,13): LocalShadow: Variable 'x' shadows a global variable used at line 8 diff --git a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.luau b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.luau index 9ec3e1f11..ea25918b6 100644 --- a/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.luau +++ b/tests/golden/analysis/refinements/while_local_binding_not_visible_after_block.luau @@ -1,5 +1,3 @@ ---!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true - local n = 0 while local x = n < 3 do n += 1 diff --git a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.nonstrict.output index e69de29bb..08b36d2b1 100644 --- a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.nonstrict.output +++ b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/refinements/while_local_narrows_to_truthy.luau(2,11): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_narrows_to_truthy.luau(10,1): SyntaxError: Expected 'end' (to close 'function' at line 1), got ; did you forget to close 'do' at line 2? diff --git a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.strict.output index e69de29bb..1bd1c7550 100644 --- a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.strict.output +++ b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.flags-off.strict.output @@ -0,0 +1,4 @@ +./analysis/refinements/while_local_narrows_to_truthy.luau(2,11): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_narrows_to_truthy.luau(10,1): SyntaxError: Expected 'end' (to close 'function' at line 1), got ; did you forget to close 'do' at line 2? +./analysis/refinements/while_local_narrows_to_truthy.luau(4,27): TypeError: Expected this to be 'string', but got 'string?'; +`nil` is not a subtype of `string` diff --git a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.luau b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.luau index 2de422db7..8e8f773f7 100644 --- a/tests/golden/analysis/refinements/while_local_narrows_to_truthy.luau +++ b/tests/golden/analysis/refinements/while_local_narrows_to_truthy.luau @@ -1,5 +1,3 @@ ---!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true - local function f(v: string?) while local x = v do -- `x` must have narrowed from `string?` to `string` to satisfy this annotation diff --git a/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.nonstrict.output index e69de29bb..4c8cb5171 100644 --- a/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.nonstrict.output +++ b/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/refinements/while_local_refines_annotated_type.luau(2,11): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_refines_annotated_type.luau(10,1): SyntaxError: Expected 'end' (to close 'function' at line 1), got ; did you forget to close 'do' at line 2? diff --git a/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.strict.output index e69de29bb..f38ae798c 100644 --- a/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.strict.output +++ b/tests/golden/analysis/refinements/while_local_refines_annotated_type.flags-off.strict.output @@ -0,0 +1,4 @@ +./analysis/refinements/while_local_refines_annotated_type.luau(2,11): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_refines_annotated_type.luau(10,1): SyntaxError: Expected 'end' (to close 'function' at line 1), got ; did you forget to close 'do' at line 2? +./analysis/refinements/while_local_refines_annotated_type.luau(4,27): TypeError: Expected this to be 'number', but got 'number?'; +`nil` is not a subtype of `number` diff --git a/tests/golden/analysis/refinements/while_local_refines_annotated_type.luau b/tests/golden/analysis/refinements/while_local_refines_annotated_type.luau index 44ef5ed3f..72e181e7f 100644 --- a/tests/golden/analysis/refinements/while_local_refines_annotated_type.luau +++ b/tests/golden/analysis/refinements/while_local_refines_annotated_type.luau @@ -1,5 +1,3 @@ ---!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true - local function f(v: number?) while local x: number? = v do -- `x` is annotated `number?` but is still narrowed by `truthy` to `number` in the body diff --git a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.nonstrict.output b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.nonstrict.output index e69de29bb..c94adf552 100644 --- a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.nonstrict.output +++ b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.nonstrict.output @@ -0,0 +1,3 @@ +./analysis/refinements/while_local_table_annotation_mismatch.luau(2,7): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_table_annotation_mismatch.luau(5,1): SyntaxError: Expected 'end' (to close 'local' at line 2), got +./analysis/refinements/while_local_table_annotation_mismatch.luau(2,13): LocalUnused: Variable 'x' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.strict.output b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.strict.output index 19e0e7a8f..ddf3666eb 100644 --- a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.strict.output +++ b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-off.strict.output @@ -1,6 +1,9 @@ -./analysis/refinements/while_local_table_annotation_mismatch.luau(4,32): TypeError: Expected this to be +./analysis/refinements/while_local_table_annotation_mismatch.luau(2,7): SyntaxError: Expected identifier when parsing expression, got 'local' +./analysis/refinements/while_local_table_annotation_mismatch.luau(5,1): SyntaxError: Expected 'end' (to close 'local' at line 2), got +./analysis/refinements/while_local_table_annotation_mismatch.luau(2,32): TypeError: Expected this to be '(false | { y: number })?' but got 'false | { y: string }'; `{ y: string }` is not a subtype of `(false | { y: number })?` -./analysis/refinements/while_local_table_annotation_mismatch.luau(4,59): TypeError: Expected this to be '{ y: number }', but got 'nil' +./analysis/refinements/while_local_table_annotation_mismatch.luau(2,59): TypeError: Expected this to be '{ y: number }', but got 'nil' +./analysis/refinements/while_local_table_annotation_mismatch.luau(2,13): LocalUnused: Variable 'x' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.strict.output b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.strict.output index 19e0e7a8f..2bfa62e37 100644 --- a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.strict.output +++ b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.flags-on.strict.output @@ -1,6 +1,6 @@ -./analysis/refinements/while_local_table_annotation_mismatch.luau(4,32): TypeError: Expected this to be +./analysis/refinements/while_local_table_annotation_mismatch.luau(2,32): TypeError: Expected this to be '(false | { y: number })?' but got 'false | { y: string }'; `{ y: string }` is not a subtype of `(false | { y: number })?` -./analysis/refinements/while_local_table_annotation_mismatch.luau(4,59): TypeError: Expected this to be '{ y: number }', but got 'nil' +./analysis/refinements/while_local_table_annotation_mismatch.luau(2,59): TypeError: Expected this to be '{ y: number }', but got 'nil' diff --git a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.luau b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.luau index 05842d0d3..f10281287 100644 --- a/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.luau +++ b/tests/golden/analysis/refinements/while_local_table_annotation_mismatch.luau @@ -1,5 +1,3 @@ ---!golden fflags=DebugLuauWhileLocalSyntax=true,DebugLuauWhileLocalAnalysis=true - local once = true while local x: { y: number } = once and { y = "oops" } or nil do once = false diff --git a/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.nonstrict.output b/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.runtime.output b/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.strict.output b/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.strict.output new file mode 100644 index 000000000..4ec48b8d8 --- /dev/null +++ b/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-off.strict.output @@ -0,0 +1,5 @@ +./analysis/tables/oss_2644_generic_instantiation_avoids_nil.luau(10,16): TypeError: No valid instantiation could be inferred for generic type parameter T. It was expected to be at least: + number | nil +and at most: + number +but these types are not compatible with one another. diff --git a/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-on.nonstrict.output b/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-on.runtime.output b/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-on.strict.output b/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.flags-on.strict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.luau b/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.luau new file mode 100644 index 000000000..227ce39ad --- /dev/null +++ b/tests/golden/analysis/tables/oss_2644_generic_instantiation_avoids_nil.luau @@ -0,0 +1,11 @@ +const methods = table.freeze({ + getValue = function(self: Value): T + return self.val + end +}) + +type Value = { val: T } & typeof(methods) + +const function _test(v: Value) + const _raw = v:getValue() +end \ No newline at end of file diff --git a/tests/golden/analysis/type-states/global_assign_to_global.flags-off.nonstrict.output b/tests/golden/analysis/type-states/global_assign_to_global.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-states/global_assign_to_global.flags-off.runtime.output b/tests/golden/analysis/type-states/global_assign_to_global.flags-off.runtime.output new file mode 100644 index 000000000..2d8e65c86 --- /dev/null +++ b/tests/golden/analysis/type-states/global_assign_to_global.flags-off.runtime.output @@ -0,0 +1,3 @@ +A = 42 +B = 42 +C = 42 diff --git a/tests/golden/analysis/type-states/global_assign_to_global.flags-off.strict.output b/tests/golden/analysis/type-states/global_assign_to_global.flags-off.strict.output new file mode 100644 index 000000000..41c8f6388 --- /dev/null +++ b/tests/golden/analysis/type-states/global_assign_to_global.flags-off.strict.output @@ -0,0 +1,9 @@ +./analysis/type-states/global_assign_to_global.luau(1,1): TypeError: Unknown global 'A'; consider assigning to it first +./analysis/type-states/global_assign_to_global.luau(2,1): TypeError: Unknown global 'B'; consider assigning to it first +./analysis/type-states/global_assign_to_global.luau(3,1): TypeError: Unknown global 'C'; consider assigning to it first +_luau_print (10, 9): number + +_luau_print (11, 9): number + +_luau_print (12, 9): number + diff --git a/tests/golden/analysis/type-states/global_assign_to_global.flags-on.nonstrict.output b/tests/golden/analysis/type-states/global_assign_to_global.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-states/global_assign_to_global.flags-on.runtime.output b/tests/golden/analysis/type-states/global_assign_to_global.flags-on.runtime.output new file mode 100644 index 000000000..2d8e65c86 --- /dev/null +++ b/tests/golden/analysis/type-states/global_assign_to_global.flags-on.runtime.output @@ -0,0 +1,3 @@ +A = 42 +B = 42 +C = 42 diff --git a/tests/golden/analysis/type-states/global_assign_to_global.flags-on.strict.output b/tests/golden/analysis/type-states/global_assign_to_global.flags-on.strict.output new file mode 100644 index 000000000..41c8f6388 --- /dev/null +++ b/tests/golden/analysis/type-states/global_assign_to_global.flags-on.strict.output @@ -0,0 +1,9 @@ +./analysis/type-states/global_assign_to_global.luau(1,1): TypeError: Unknown global 'A'; consider assigning to it first +./analysis/type-states/global_assign_to_global.luau(2,1): TypeError: Unknown global 'B'; consider assigning to it first +./analysis/type-states/global_assign_to_global.luau(3,1): TypeError: Unknown global 'C'; consider assigning to it first +_luau_print (10, 9): number + +_luau_print (11, 9): number + +_luau_print (12, 9): number + diff --git a/tests/golden/analysis/type-states/global_assign_to_global.luau b/tests/golden/analysis/type-states/global_assign_to_global.luau new file mode 100644 index 000000000..f702acc52 --- /dev/null +++ b/tests/golden/analysis/type-states/global_assign_to_global.luau @@ -0,0 +1,15 @@ +A = 42 +B = A +C = B + +local function printit() + print("A = " .. A) + print("B = " .. B) + print("C = " .. B) +end + +local _: _luau_print +local _: _luau_print +local _: _luau_print + +printit() \ No newline at end of file diff --git a/tests/golden/analysis/type-states/global_reassign_func.flags-off.nonstrict.output b/tests/golden/analysis/type-states/global_reassign_func.flags-off.nonstrict.output new file mode 100644 index 000000000..83254461a --- /dev/null +++ b/tests/golden/analysis/type-states/global_reassign_func.flags-off.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/type-states/global_reassign_func.luau(7,10): FunctionUnused: Function 'f' is never used; prefix with '_' to silence +./analysis/type-states/global_reassign_func.luau(7,10): DuplicateFunction: Duplicate function definition: 'f' also defined on line 3 diff --git a/tests/golden/analysis/type-states/global_reassign_func.flags-off.runtime.output b/tests/golden/analysis/type-states/global_reassign_func.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-states/global_reassign_func.flags-off.strict.output b/tests/golden/analysis/type-states/global_reassign_func.flags-off.strict.output new file mode 100644 index 000000000..ed141b06c --- /dev/null +++ b/tests/golden/analysis/type-states/global_reassign_func.flags-off.strict.output @@ -0,0 +1,10 @@ +./analysis/type-states/global_reassign_func.luau(7,10): FunctionUnused: Function 'f' is never used; prefix with '_' to silence +./analysis/type-states/global_reassign_func.luau(7,10): DuplicateFunction: Duplicate function definition: 'f' also defined on line 3 +_luau_print (0, 9): *error-type* + +_luau_print (3, 13): () -> () + +_luau_print (7, 13): () -> () + +_luau_print (10, 9): () -> () + diff --git a/tests/golden/analysis/type-states/global_reassign_func.flags-on.nonstrict.output b/tests/golden/analysis/type-states/global_reassign_func.flags-on.nonstrict.output new file mode 100644 index 000000000..83254461a --- /dev/null +++ b/tests/golden/analysis/type-states/global_reassign_func.flags-on.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/type-states/global_reassign_func.luau(7,10): FunctionUnused: Function 'f' is never used; prefix with '_' to silence +./analysis/type-states/global_reassign_func.luau(7,10): DuplicateFunction: Duplicate function definition: 'f' also defined on line 3 diff --git a/tests/golden/analysis/type-states/global_reassign_func.flags-on.runtime.output b/tests/golden/analysis/type-states/global_reassign_func.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-states/global_reassign_func.flags-on.strict.output b/tests/golden/analysis/type-states/global_reassign_func.flags-on.strict.output new file mode 100644 index 000000000..ed141b06c --- /dev/null +++ b/tests/golden/analysis/type-states/global_reassign_func.flags-on.strict.output @@ -0,0 +1,10 @@ +./analysis/type-states/global_reassign_func.luau(7,10): FunctionUnused: Function 'f' is never used; prefix with '_' to silence +./analysis/type-states/global_reassign_func.luau(7,10): DuplicateFunction: Duplicate function definition: 'f' also defined on line 3 +_luau_print (0, 9): *error-type* + +_luau_print (3, 13): () -> () + +_luau_print (7, 13): () -> () + +_luau_print (10, 9): () -> () + diff --git a/tests/golden/analysis/type-states/global_reassign_func.luau b/tests/golden/analysis/type-states/global_reassign_func.luau new file mode 100644 index 000000000..6c4344ce5 --- /dev/null +++ b/tests/golden/analysis/type-states/global_reassign_func.luau @@ -0,0 +1,11 @@ +local _: _luau_print + +function f() + local _: _luau_print +end + +function f() + local _: _luau_print +end + +local _: _luau_print \ No newline at end of file diff --git a/tests/golden/analysis/type-states/global_self_assign.flags-off.nonstrict.output b/tests/golden/analysis/type-states/global_self_assign.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-states/global_self_assign.flags-off.runtime.output b/tests/golden/analysis/type-states/global_self_assign.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-states/global_self_assign.flags-off.strict.output b/tests/golden/analysis/type-states/global_self_assign.flags-off.strict.output new file mode 100644 index 000000000..88109106e --- /dev/null +++ b/tests/golden/analysis/type-states/global_self_assign.flags-off.strict.output @@ -0,0 +1,3 @@ +./analysis/type-states/global_self_assign.luau(1,1): TypeError: Unknown global 'foobar'; consider assigning to it first +_luau_print (1, 9): *blocked-103* + diff --git a/tests/golden/analysis/type-states/global_self_assign.flags-on.nonstrict.output b/tests/golden/analysis/type-states/global_self_assign.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-states/global_self_assign.flags-on.runtime.output b/tests/golden/analysis/type-states/global_self_assign.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/type-states/global_self_assign.flags-on.strict.output b/tests/golden/analysis/type-states/global_self_assign.flags-on.strict.output new file mode 100644 index 000000000..699365dac --- /dev/null +++ b/tests/golden/analysis/type-states/global_self_assign.flags-on.strict.output @@ -0,0 +1,3 @@ +./analysis/type-states/global_self_assign.luau(1,1): TypeError: Unknown global 'foobar'; consider assigning to it first +_luau_print (1, 9): *error-type* + diff --git a/tests/golden/analysis/type-states/global_self_assign.luau b/tests/golden/analysis/type-states/global_self_assign.luau new file mode 100644 index 000000000..5a6317cd8 --- /dev/null +++ b/tests/golden/analysis/type-states/global_self_assign.luau @@ -0,0 +1,2 @@ +foobar = foobar +local _: _luau_print diff --git a/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.nonstrict.output b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.nonstrict.output new file mode 100644 index 000000000..79d8cedfb --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(4,14): GlobalUsedAsLocal: Global 'f' is only used in the enclosing function 'g'; consider changing it to local +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(4,14): FunctionUnused: Function 'f' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.runtime.output b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.runtime.output new file mode 100644 index 000000000..c45e93f81 --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.runtime.output @@ -0,0 +1 @@ +Warning: unrecognized flag 'LuauBanGlobalsInTypeFunctions'. diff --git a/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.strict.output b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.strict.output new file mode 100644 index 000000000..c5ad3cca2 --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-off.strict.output @@ -0,0 +1,4 @@ +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(8,1): TypeError: Unknown global 'Foobar'; consider assigning to it first +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(10,11): TypeError: Unknown global 'Foobar'; consider assigning to it first +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(4,14): GlobalUsedAsLocal: Global 'f' is only used in the enclosing function 'g'; consider changing it to local +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(4,14): FunctionUnused: Function 'f' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.nonstrict.output b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.nonstrict.output new file mode 100644 index 000000000..79d8cedfb --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(4,14): GlobalUsedAsLocal: Global 'f' is only used in the enclosing function 'g'; consider changing it to local +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(4,14): FunctionUnused: Function 'f' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.runtime.output b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.runtime.output new file mode 100644 index 000000000..c45e93f81 --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.runtime.output @@ -0,0 +1 @@ +Warning: unrecognized flag 'LuauBanGlobalsInTypeFunctions'. diff --git a/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.strict.output b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.strict.output new file mode 100644 index 000000000..c5ad3cca2 --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.flags-on.strict.output @@ -0,0 +1,4 @@ +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(8,1): TypeError: Unknown global 'Foobar'; consider assigning to it first +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(10,11): TypeError: Unknown global 'Foobar'; consider assigning to it first +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(4,14): GlobalUsedAsLocal: Global 'f' is only used in the enclosing function 'g'; consider changing it to local +./analysis/user-defined-type-functions/no_globals_in_type_funs.luau(4,14): FunctionUnused: Function 'f' is never used; prefix with '_' to silence diff --git a/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.luau b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.luau new file mode 100644 index 000000000..594c7f932 --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/no_globals_in_type_funs.luau @@ -0,0 +1,12 @@ +--!golden fflags=LuauBanGlobalsInTypeFunctions=true +type function f() end +type function g() + function f() + end +end + +Foobar = "yo" +type function huh() + print(Foobar) +end + diff --git a/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.nonstrict.output b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.nonstrict.output new file mode 100644 index 000000000..b1f99eb69 --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.nonstrict.output @@ -0,0 +1 @@ +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(2,12): GlobalUsedAsLocal: Global 'glob' is only used in the enclosing function 'foo'; consider changing it to local diff --git a/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.runtime.output b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.strict.output b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.strict.output new file mode 100644 index 000000000..032ba7c8c --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-off.strict.output @@ -0,0 +1,6 @@ +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(2,12): TypeError: Unknown global 'glob'; consider assigning to it first +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(15,1): TypeError: 'bar' type function errored at runtime: [string "foo"]:3: attempt to modify a readonly table +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(15,26): TypeError: 'bar' type function errored at runtime: [string "foo"]:3: attempt to modify a readonly table +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(19,1): TypeError: 'bar' type function errored at runtime: [string "foo"]:3: attempt to modify a readonly table +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(19,26): TypeError: 'bar' type function errored at runtime: [string "foo"]:3: attempt to modify a readonly table +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(2,12): GlobalUsedAsLocal: Global 'glob' is only used in the enclosing function 'foo'; consider changing it to local diff --git a/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.nonstrict.output b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.nonstrict.output new file mode 100644 index 000000000..b1f99eb69 --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.nonstrict.output @@ -0,0 +1 @@ +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(2,12): GlobalUsedAsLocal: Global 'glob' is only used in the enclosing function 'foo'; consider changing it to local diff --git a/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.runtime.output b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.strict.output b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.strict.output new file mode 100644 index 000000000..239eeb022 --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.flags-on.strict.output @@ -0,0 +1,10 @@ +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(2,12): TypeError: Unknown global 'glob'; consider assigning to it first +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(3,9): TypeError: Unknown global 'glob'; consider assigning to it first +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(5,9): TypeError: Unknown global 'glob'; consider assigning to it first +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(5,9): TypeError: Unknown global 'glob'; consider assigning to it first +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(8,12): TypeError: Unknown global 'glob'; consider assigning to it first +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(15,1): TypeError: 'bar' type function errored at runtime: foo:3: attempt to modify a readonly table +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(15,26): TypeError: 'bar' type function errored at runtime: foo:3: attempt to modify a readonly table +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(19,1): TypeError: 'bar' type function errored at runtime: foo:3: attempt to modify a readonly table +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(19,26): TypeError: 'bar' type function errored at runtime: foo:3: attempt to modify a readonly table +./analysis/user-defined-type-functions/udtf_no_shared_state.luau(2,12): GlobalUsedAsLocal: Global 'glob' is only used in the enclosing function 'foo'; consider changing it to local diff --git a/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.luau b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.luau new file mode 100644 index 000000000..76e0be730 --- /dev/null +++ b/tests/golden/analysis/user-defined-type-functions/udtf_no_shared_state.luau @@ -0,0 +1,21 @@ +type function foo() + if not glob then + glob = "a" + else + glob ..= "b" + end + + return glob +end + +type function bar(prefix) + return types.singleton(tostring(prefix:value()) .. foo()) +end + +local function _ok1(idx: bar<"x">): nil + return idx +end + +local function _ok2(idx: bar<"y">): nil + return idx +end diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-off.nonstrict.output b/tests/golden/syntax/while-local/error_missing_equals.flags-off.nonstrict.output index f7b308340..4a14071f0 100644 --- a/tests/golden/syntax/while-local/error_missing_equals.flags-off.nonstrict.output +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-off.nonstrict.output @@ -1 +1,3 @@ -./syntax/while-local/error_missing_equals.luau(3,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' +./syntax/while-local/error_missing_equals.luau(1,7): SyntaxError: Expected identifier when parsing expression, got 'local' +./syntax/while-local/error_missing_equals.luau(2,1): SyntaxError: Expected 'end' (to close 'local' at line 1), got +./syntax/while-local/error_missing_equals.luau(1,13): LocalUnused: Variable 'x' is never used; prefix with '_' to silence diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-off.runtime.output b/tests/golden/syntax/while-local/error_missing_equals.flags-off.runtime.output index 338ff64cf..4009f1536 100644 --- a/tests/golden/syntax/while-local/error_missing_equals.flags-off.runtime.output +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-off.runtime.output @@ -1,2 +1,2 @@ -./syntax/while-local/error_missing_equals.luau:3: Expected '=' when parsing while local declaration, got 'do' +./syntax/while-local/error_missing_equals.luau:1: Expected identifier when parsing expression, got 'local' stacktrace: diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-off.strict.output b/tests/golden/syntax/while-local/error_missing_equals.flags-off.strict.output index f7b308340..4a14071f0 100644 --- a/tests/golden/syntax/while-local/error_missing_equals.flags-off.strict.output +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-off.strict.output @@ -1 +1,3 @@ -./syntax/while-local/error_missing_equals.luau(3,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' +./syntax/while-local/error_missing_equals.luau(1,7): SyntaxError: Expected identifier when parsing expression, got 'local' +./syntax/while-local/error_missing_equals.luau(2,1): SyntaxError: Expected 'end' (to close 'local' at line 1), got +./syntax/while-local/error_missing_equals.luau(1,13): LocalUnused: Variable 'x' is never used; prefix with '_' to silence diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-on.nonstrict.output b/tests/golden/syntax/while-local/error_missing_equals.flags-on.nonstrict.output index f7b308340..e0a5e052c 100644 --- a/tests/golden/syntax/while-local/error_missing_equals.flags-on.nonstrict.output +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-on.nonstrict.output @@ -1 +1 @@ -./syntax/while-local/error_missing_equals.luau(3,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' +./syntax/while-local/error_missing_equals.luau(1,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-on.runtime.output b/tests/golden/syntax/while-local/error_missing_equals.flags-on.runtime.output index 338ff64cf..c3cc8ca1f 100644 --- a/tests/golden/syntax/while-local/error_missing_equals.flags-on.runtime.output +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-on.runtime.output @@ -1,2 +1,2 @@ -./syntax/while-local/error_missing_equals.luau:3: Expected '=' when parsing while local declaration, got 'do' +./syntax/while-local/error_missing_equals.luau:1: Expected '=' when parsing while local declaration, got 'do' stacktrace: diff --git a/tests/golden/syntax/while-local/error_missing_equals.flags-on.strict.output b/tests/golden/syntax/while-local/error_missing_equals.flags-on.strict.output index f7b308340..e0a5e052c 100644 --- a/tests/golden/syntax/while-local/error_missing_equals.flags-on.strict.output +++ b/tests/golden/syntax/while-local/error_missing_equals.flags-on.strict.output @@ -1 +1 @@ -./syntax/while-local/error_missing_equals.luau(3,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' +./syntax/while-local/error_missing_equals.luau(1,15): SyntaxError: Expected '=' when parsing while local declaration, got 'do' diff --git a/tests/golden/syntax/while-local/error_missing_equals.luau b/tests/golden/syntax/while-local/error_missing_equals.luau index a8a44b1ae..a6c095cdf 100644 --- a/tests/golden/syntax/while-local/error_missing_equals.luau +++ b/tests/golden/syntax/while-local/error_missing_equals.luau @@ -1,3 +1 @@ ---!golden fflags=DebugLuauWhileLocalSyntax=true - while local x do end diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.nonstrict.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.nonstrict.output index 946039b0b..9322e2b2d 100644 --- a/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.nonstrict.output +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.nonstrict.output @@ -1,4 +1,5 @@ -./syntax/while-local/error_multiple_bindings.luau(3,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed -./syntax/while-local/error_multiple_bindings.luau(4,1): SyntaxError: Expected 'end' (to close ',' at line 3), got -./syntax/while-local/error_multiple_bindings.luau(3,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence -./syntax/while-local/error_multiple_bindings.luau(3,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence +./syntax/while-local/error_multiple_bindings.luau(1,7): SyntaxError: Expected identifier when parsing expression, got 'local' +./syntax/while-local/error_multiple_bindings.luau(2,1): SyntaxError: Expected 'end' (to close 'local' at line 1), got +./syntax/while-local/error_multiple_bindings.luau(1,7): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence +./syntax/while-local/error_multiple_bindings.luau(1,13): LocalUnused: Variable 'x' is never used; prefix with '_' to silence +./syntax/while-local/error_multiple_bindings.luau(1,16): LocalUnused: Variable 'y' is never used; prefix with '_' to silence diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.runtime.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.runtime.output index c8b3f3062..016ee1741 100644 --- a/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.runtime.output +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.runtime.output @@ -1,2 +1,2 @@ -./syntax/while-local/error_multiple_bindings.luau:3: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +./syntax/while-local/error_multiple_bindings.luau:1: Expected identifier when parsing expression, got 'local' stacktrace: diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.strict.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.strict.output index 946039b0b..9322e2b2d 100644 --- a/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.strict.output +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-off.strict.output @@ -1,4 +1,5 @@ -./syntax/while-local/error_multiple_bindings.luau(3,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed -./syntax/while-local/error_multiple_bindings.luau(4,1): SyntaxError: Expected 'end' (to close ',' at line 3), got -./syntax/while-local/error_multiple_bindings.luau(3,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence -./syntax/while-local/error_multiple_bindings.luau(3,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence +./syntax/while-local/error_multiple_bindings.luau(1,7): SyntaxError: Expected identifier when parsing expression, got 'local' +./syntax/while-local/error_multiple_bindings.luau(2,1): SyntaxError: Expected 'end' (to close 'local' at line 1), got +./syntax/while-local/error_multiple_bindings.luau(1,7): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence +./syntax/while-local/error_multiple_bindings.luau(1,13): LocalUnused: Variable 'x' is never used; prefix with '_' to silence +./syntax/while-local/error_multiple_bindings.luau(1,16): LocalUnused: Variable 'y' is never used; prefix with '_' to silence diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.nonstrict.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.nonstrict.output index 946039b0b..0c1b49620 100644 --- a/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.nonstrict.output +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.nonstrict.output @@ -1,4 +1,4 @@ -./syntax/while-local/error_multiple_bindings.luau(3,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed -./syntax/while-local/error_multiple_bindings.luau(4,1): SyntaxError: Expected 'end' (to close ',' at line 3), got -./syntax/while-local/error_multiple_bindings.luau(3,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence -./syntax/while-local/error_multiple_bindings.luau(3,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence +./syntax/while-local/error_multiple_bindings.luau(1,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +./syntax/while-local/error_multiple_bindings.luau(2,1): SyntaxError: Expected 'end' (to close ',' at line 1), got +./syntax/while-local/error_multiple_bindings.luau(1,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence +./syntax/while-local/error_multiple_bindings.luau(1,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.runtime.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.runtime.output index c8b3f3062..67ae9bc47 100644 --- a/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.runtime.output +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.runtime.output @@ -1,2 +1,2 @@ -./syntax/while-local/error_multiple_bindings.luau:3: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +./syntax/while-local/error_multiple_bindings.luau:1: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed stacktrace: diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.strict.output b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.strict.output index 946039b0b..0c1b49620 100644 --- a/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.strict.output +++ b/tests/golden/syntax/while-local/error_multiple_bindings.flags-on.strict.output @@ -1,4 +1,4 @@ -./syntax/while-local/error_multiple_bindings.luau(3,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed -./syntax/while-local/error_multiple_bindings.luau(4,1): SyntaxError: Expected 'end' (to close ',' at line 3), got -./syntax/while-local/error_multiple_bindings.luau(3,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence -./syntax/while-local/error_multiple_bindings.luau(3,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence +./syntax/while-local/error_multiple_bindings.luau(1,14): SyntaxError: Expected '=' after variable name in 'while local', got ','; only a single binding is allowed +./syntax/while-local/error_multiple_bindings.luau(2,1): SyntaxError: Expected 'end' (to close ',' at line 1), got +./syntax/while-local/error_multiple_bindings.luau(1,14): UnbalancedAssignment: Assigning 1 values to 2 variables initializes extra variables with nil; add 'nil' to value list to silence +./syntax/while-local/error_multiple_bindings.luau(1,22): SameLineStatement: A new statement is on the same line; add semi-colon on previous statement to silence diff --git a/tests/golden/syntax/while-local/error_multiple_bindings.luau b/tests/golden/syntax/while-local/error_multiple_bindings.luau index b6d4c3d2c..a87293c38 100644 --- a/tests/golden/syntax/while-local/error_multiple_bindings.luau +++ b/tests/golden/syntax/while-local/error_multiple_bindings.luau @@ -1,3 +1 @@ ---!golden fflags=DebugLuauWhileLocalSyntax=true - while local x, y = 1 do end From 12a6ba75883272c79b66b59815efef4c574196f6 Mon Sep 17 00:00:00 2001 From: vegorov-rbx <75688451+vegorov-rbx@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:05:50 +0200 Subject: [PATCH 07/13] Add missing include to TableLiteralInference.cpp (#3107) --- Analysis/src/TableLiteralInference.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Analysis/src/TableLiteralInference.cpp b/Analysis/src/TableLiteralInference.cpp index 0548eb9bb..4cafee702 100644 --- a/Analysis/src/TableLiteralInference.cpp +++ b/Analysis/src/TableLiteralInference.cpp @@ -15,6 +15,8 @@ #include "Luau/TypeUtils.h" #include "Luau/Unifier2.h" +#include + LUAU_FASTFLAGVARIABLE(LuauBidirectionalInferenceBetterLambdaHandling) namespace Luau @@ -77,8 +79,8 @@ struct FindFunctionTypeIn : IterativeTypeVisitor return false; } - int candidateDistance = std::abs(int(size(candidate->argTypes)) - numberOfLambdaParameters); - int thisDistance = std::abs(int(size(ftv.argTypes)) - numberOfLambdaParameters); + int candidateDistance = abs(int(size(candidate->argTypes)) - numberOfLambdaParameters); + int thisDistance = abs(int(size(ftv.argTypes)) - numberOfLambdaParameters); if (thisDistance < candidateDistance) { @@ -93,7 +95,7 @@ struct FindFunctionTypeIn : IterativeTypeVisitor else { if (candidate == nullptr || - std::abs(int(size(candidate->argTypes)) - numberOfLambdaParameters) > std::abs(int(size(ftv.argTypes)) - numberOfLambdaParameters)) + abs(int(size(candidate->argTypes)) - numberOfLambdaParameters) > abs(int(size(ftv.argTypes)) - numberOfLambdaParameters)) { candidate = get(ty); return false; From f46d879e28302a430029304f7f6a162aed66f103 Mon Sep 17 00:00:00 2001 From: Varun Saini <61795485+vrn-sn@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:39:36 -0800 Subject: [PATCH 08/13] Fix CI builds: remove all U+200E characters from Confusables.cpp and recursive calls in `std::any_of` (#3114) This is causing CI builds to fail. The problematic characters only show up in comments anyway, so the simplest solution is just removing them. Proof of correctness: ```bash > diff -s <(git show HEAD:Ast/src/Confusables.cpp | sed $'s/\xE2\x80\x8E//g') Ast/src/Confusables.cpp Files /dev/fd/11 and Ast/src/Confusables.cpp are identical ``` The `std::any_of` change addresses another failure that we're seeing in CI, and this one should be superseded by an incoming change soon. --- Analysis/src/TypeUtils.cpp | 21 ++++--- Ast/src/Confusables.cpp | 118 ++++++++++++++++++------------------- 2 files changed, 73 insertions(+), 66 deletions(-) diff --git a/Analysis/src/TypeUtils.cpp b/Analysis/src/TypeUtils.cpp index f00f8f55b..06bf0fd74 100644 --- a/Analysis/src/TypeUtils.cpp +++ b/Analysis/src/TypeUtils.cpp @@ -29,17 +29,24 @@ bool occursCheck(TypeId needle, TypeId haystack) LUAU_ASSERT(get(needle) || get(needle)); haystack = follow(haystack); - auto checkHaystack = [needle](TypeId haystack) - { - return occursCheck(needle, haystack); - }; - if (needle == haystack) return true; else if (auto ut = get(haystack)) - return std::any_of(begin(ut), end(ut), checkHaystack); + { + for (TypeId option : ut) + { + if (occursCheck(needle, option)) + return true; + } + } else if (auto it = get(haystack)) - return std::any_of(begin(it), end(it), checkHaystack); + { + for (TypeId part : it) + { + if (occursCheck(needle, part)) + return true; + } + } return false; } diff --git a/Ast/src/Confusables.cpp b/Ast/src/Confusables.cpp index 8f7fb56c4..816e424bc 100644 --- a/Ast/src/Confusables.cpp +++ b/Ast/src/Confusables.cpp @@ -206,44 +206,44 @@ static const Confusable kConfusables[] = {1412, "f"}, // MA# ( ք → f ) ARMENIAN SMALL LETTER KEH → LATIN SMALL LETTER F# {1413, "o"}, // MA# ( օ → o ) ARMENIAN SMALL LETTER OH → LATIN SMALL LETTER O# {1417, ":"}, // MA#* ( ։ → : ) ARMENIAN FULL STOP → COLON# - {1472, "l"}, // MA#* ( ‎׀‎ → l ) HEBREW PUNCTUATION PASEQ → LATIN SMALL LETTER L# →|→ - {1475, ":"}, // MA#* ( ‎׃‎ → : ) HEBREW PUNCTUATION SOF PASUQ → COLON# - {1493, "l"}, // MA# ( ‎ו‎ → l ) HEBREW LETTER VAV → LATIN SMALL LETTER L# - {1496, "v"}, // MA# ( ‎ט‎ → v ) HEBREW LETTER TET → LATIN SMALL LETTER V# - {1497, "'"}, // MA# ( ‎י‎ → ' ) HEBREW LETTER YOD → APOSTROPHE# - {1503, "l"}, // MA# ( ‎ן‎ → l ) HEBREW LETTER FINAL NUN → LATIN SMALL LETTER L# - {1505, "o"}, // MA# ( ‎ס‎ → o ) HEBREW LETTER SAMEKH → LATIN SMALL LETTER O# - {1520, "ll"}, // MA# ( ‎װ‎ → ll ) HEBREW LIGATURE YIDDISH DOUBLE VAV → LATIN SMALL LETTER L, LATIN SMALL LETTER L# →‎וו‎→ - {1521, "l'"}, // MA# ( ‎ױ‎ → l' ) HEBREW LIGATURE YIDDISH VAV YOD → LATIN SMALL LETTER L, APOSTROPHE# →‎וי‎→ - {1522, "\""}, // MA# ( ‎ײ‎ → '' ) HEBREW LIGATURE YIDDISH DOUBLE YOD → APOSTROPHE, APOSTROPHE# →‎יי‎→# Converted to a quote. - {1523, "'"}, // MA#* ( ‎׳‎ → ' ) HEBREW PUNCTUATION GERESH → APOSTROPHE# - {1524, "\""}, // MA#* ( ‎״‎ → '' ) HEBREW PUNCTUATION GERSHAYIM → APOSTROPHE, APOSTROPHE# →"→# Converted to a quote. - {1549, ","}, // MA#* ( ‎؍‎ → , ) ARABIC DATE SEPARATOR → COMMA# →‎٫‎→ - {1575, "l"}, // MA# ( ‎ا‎ → l ) ARABIC LETTER ALEF → LATIN SMALL LETTER L# →1→ - {1607, "o"}, // MA# ( ‎ه‎ → o ) ARABIC LETTER HEH → LATIN SMALL LETTER O# - {1632, "."}, // MA# ( ‎٠‎ → . ) ARABIC-INDIC DIGIT ZERO → FULL STOP# - {1633, "l"}, // MA# ( ‎١‎ → l ) ARABIC-INDIC DIGIT ONE → LATIN SMALL LETTER L# →1→ - {1637, "o"}, // MA# ( ‎٥‎ → o ) ARABIC-INDIC DIGIT FIVE → LATIN SMALL LETTER O# - {1639, "V"}, // MA# ( ‎٧‎ → V ) ARABIC-INDIC DIGIT SEVEN → LATIN CAPITAL LETTER V# - {1643, ","}, // MA#* ( ‎٫‎ → , ) ARABIC DECIMAL SEPARATOR → COMMA# - {1645, "*"}, // MA#* ( ‎٭‎ → * ) ARABIC FIVE POINTED STAR → ASTERISK# - {1726, "o"}, // MA# ( ‎ھ‎ → o ) ARABIC LETTER HEH DOACHASHMEE → LATIN SMALL LETTER O# →‎ه‎→ - {1729, "o"}, // MA# ( ‎ہ‎ → o ) ARABIC LETTER HEH GOAL → LATIN SMALL LETTER O# →‎ه‎→ - {1748, "-"}, // MA#* ( ‎۔‎ → - ) ARABIC FULL STOP → HYPHEN-MINUS# →‐→ - {1749, "o"}, // MA# ( ‎ە‎ → o ) ARABIC LETTER AE → LATIN SMALL LETTER O# →‎ه‎→ - {1776, "."}, // MA# ( ۰ → . ) EXTENDED ARABIC-INDIC DIGIT ZERO → FULL STOP# →‎٠‎→ + {1472, "l"}, // MA#* ( ׀ → l ) HEBREW PUNCTUATION PASEQ → LATIN SMALL LETTER L# →|→ + {1475, ":"}, // MA#* ( ׃ → : ) HEBREW PUNCTUATION SOF PASUQ → COLON# + {1493, "l"}, // MA# ( ו → l ) HEBREW LETTER VAV → LATIN SMALL LETTER L# + {1496, "v"}, // MA# ( ט → v ) HEBREW LETTER TET → LATIN SMALL LETTER V# + {1497, "'"}, // MA# ( י → ' ) HEBREW LETTER YOD → APOSTROPHE# + {1503, "l"}, // MA# ( ן → l ) HEBREW LETTER FINAL NUN → LATIN SMALL LETTER L# + {1505, "o"}, // MA# ( ס → o ) HEBREW LETTER SAMEKH → LATIN SMALL LETTER O# + {1520, "ll"}, // MA# ( װ → ll ) HEBREW LIGATURE YIDDISH DOUBLE VAV → LATIN SMALL LETTER L, LATIN SMALL LETTER L# →וו→ + {1521, "l'"}, // MA# ( ױ → l' ) HEBREW LIGATURE YIDDISH VAV YOD → LATIN SMALL LETTER L, APOSTROPHE# →וי→ + {1522, "\""}, // MA# ( ײ → '' ) HEBREW LIGATURE YIDDISH DOUBLE YOD → APOSTROPHE, APOSTROPHE# →יי→# Converted to a quote. + {1523, "'"}, // MA#* ( ׳ → ' ) HEBREW PUNCTUATION GERESH → APOSTROPHE# + {1524, "\""}, // MA#* ( ״ → '' ) HEBREW PUNCTUATION GERSHAYIM → APOSTROPHE, APOSTROPHE# →"→# Converted to a quote. + {1549, ","}, // MA#* ( ؍ → , ) ARABIC DATE SEPARATOR → COMMA# →٫→ + {1575, "l"}, // MA# ( ا → l ) ARABIC LETTER ALEF → LATIN SMALL LETTER L# →1→ + {1607, "o"}, // MA# ( ه → o ) ARABIC LETTER HEH → LATIN SMALL LETTER O# + {1632, "."}, // MA# ( ٠ → . ) ARABIC-INDIC DIGIT ZERO → FULL STOP# + {1633, "l"}, // MA# ( ١ → l ) ARABIC-INDIC DIGIT ONE → LATIN SMALL LETTER L# →1→ + {1637, "o"}, // MA# ( ٥ → o ) ARABIC-INDIC DIGIT FIVE → LATIN SMALL LETTER O# + {1639, "V"}, // MA# ( ٧ → V ) ARABIC-INDIC DIGIT SEVEN → LATIN CAPITAL LETTER V# + {1643, ","}, // MA#* ( ٫ → , ) ARABIC DECIMAL SEPARATOR → COMMA# + {1645, "*"}, // MA#* ( ٭ → * ) ARABIC FIVE POINTED STAR → ASTERISK# + {1726, "o"}, // MA# ( ھ → o ) ARABIC LETTER HEH DOACHASHMEE → LATIN SMALL LETTER O# →ه→ + {1729, "o"}, // MA# ( ہ → o ) ARABIC LETTER HEH GOAL → LATIN SMALL LETTER O# →ه→ + {1748, "-"}, // MA#* ( ۔ → - ) ARABIC FULL STOP → HYPHEN-MINUS# →‐→ + {1749, "o"}, // MA# ( ە → o ) ARABIC LETTER AE → LATIN SMALL LETTER O# →ه→ + {1776, "."}, // MA# ( ۰ → . ) EXTENDED ARABIC-INDIC DIGIT ZERO → FULL STOP# →٠→ {1777, "l"}, // MA# ( ۱ → l ) EXTENDED ARABIC-INDIC DIGIT ONE → LATIN SMALL LETTER L# →1→ - {1781, "o"}, // MA# ( ۵ → o ) EXTENDED ARABIC-INDIC DIGIT FIVE → LATIN SMALL LETTER O# →‎٥‎→ - {1783, "V"}, // MA# ( ۷ → V ) EXTENDED ARABIC-INDIC DIGIT SEVEN → LATIN CAPITAL LETTER V# →‎٧‎→ - {1793, "."}, // MA#* ( ‎܁‎ → . ) SYRIAC SUPRALINEAR FULL STOP → FULL STOP# - {1794, "."}, // MA#* ( ‎܂‎ → . ) SYRIAC SUBLINEAR FULL STOP → FULL STOP# - {1795, ":"}, // MA#* ( ‎܃‎ → : ) SYRIAC SUPRALINEAR COLON → COLON# - {1796, ":"}, // MA#* ( ‎܄‎ → : ) SYRIAC SUBLINEAR COLON → COLON# - {1984, "O"}, // MA# ( ‎߀‎ → O ) NKO DIGIT ZERO → LATIN CAPITAL LETTER O# →0→ - {1994, "l"}, // MA# ( ‎ߊ‎ → l ) NKO LETTER A → LATIN SMALL LETTER L# →∣→→ǀ→ - {2036, "'"}, // MA# ( ‎ߴ‎ → ' ) NKO HIGH TONE APOSTROPHE → APOSTROPHE# →’→ - {2037, "'"}, // MA# ( ‎ߵ‎ → ' ) NKO LOW TONE APOSTROPHE → APOSTROPHE# →‘→ - {2042, "_"}, // MA# ( ‎ߺ‎ → _ ) NKO LAJANYALAN → LOW LINE# + {1781, "o"}, // MA# ( ۵ → o ) EXTENDED ARABIC-INDIC DIGIT FIVE → LATIN SMALL LETTER O# →٥→ + {1783, "V"}, // MA# ( ۷ → V ) EXTENDED ARABIC-INDIC DIGIT SEVEN → LATIN CAPITAL LETTER V# →٧→ + {1793, "."}, // MA#* ( ܁ → . ) SYRIAC SUPRALINEAR FULL STOP → FULL STOP# + {1794, "."}, // MA#* ( ܂ → . ) SYRIAC SUBLINEAR FULL STOP → FULL STOP# + {1795, ":"}, // MA#* ( ܃ → : ) SYRIAC SUPRALINEAR COLON → COLON# + {1796, ":"}, // MA#* ( ܄ → : ) SYRIAC SUBLINEAR COLON → COLON# + {1984, "O"}, // MA# ( ߀ → O ) NKO DIGIT ZERO → LATIN CAPITAL LETTER O# →0→ + {1994, "l"}, // MA# ( ߊ → l ) NKO LETTER A → LATIN SMALL LETTER L# →∣→→ǀ→ + {2036, "'"}, // MA# ( ߴ → ' ) NKO HIGH TONE APOSTROPHE → APOSTROPHE# →’→ + {2037, "'"}, // MA# ( ߵ → ' ) NKO LOW TONE APOSTROPHE → APOSTROPHE# →‘→ + {2042, "_"}, // MA# ( ߺ → _ ) NKO LAJANYALAN → LOW LINE# {2307, ":"}, // MA# ( ः → : ) DEVANAGARI SIGN VISARGA → COLON# {2406, "o"}, // MA# ( ० → o ) DEVANAGARI DIGIT ZERO → LATIN SMALL LETTER O# {2429, "?"}, // MA# ( ॽ → ? ) DEVANAGARI LETTER GLOTTAL STOP → QUESTION MARK# @@ -749,14 +749,14 @@ static const Confusable kConfusables[] = {64259, "ffi"}, // MA# ( ffi → ffi ) LATIN SMALL LIGATURE FFI → LATIN SMALL LETTER F, LATIN SMALL LETTER F, LATIN SMALL LETTER I# {64260, "ffl"}, // MA# ( ffl → ffl ) LATIN SMALL LIGATURE FFL → LATIN SMALL LETTER F, LATIN SMALL LETTER F, LATIN SMALL LETTER L# {64262, "st"}, // MA# ( st → st ) LATIN SMALL LIGATURE ST → LATIN SMALL LETTER S, LATIN SMALL LETTER T# - {64422, "o"}, // MA# ( ‎ﮦ‎ → o ) ARABIC LETTER HEH GOAL ISOLATED FORM → LATIN SMALL LETTER O# →‎ه‎→ - {64423, "o"}, // MA# ( ‎ﮧ‎ → o ) ARABIC LETTER HEH GOAL FINAL FORM → LATIN SMALL LETTER O# →‎ہ‎→→‎ه‎→ - {64424, "o"}, // MA# ( ‎ﮨ‎ → o ) ARABIC LETTER HEH GOAL INITIAL FORM → LATIN SMALL LETTER O# →‎ہ‎→→‎ه‎→ - {64425, "o"}, // MA# ( ‎ﮩ‎ → o ) ARABIC LETTER HEH GOAL MEDIAL FORM → LATIN SMALL LETTER O# →‎ہ‎→→‎ه‎→ - {64426, "o"}, // MA# ( ‎ﮪ‎ → o ) ARABIC LETTER HEH DOACHASHMEE ISOLATED FORM → LATIN SMALL LETTER O# →‎ه‎→ - {64427, "o"}, // MA# ( ‎ﮫ‎ → o ) ARABIC LETTER HEH DOACHASHMEE FINAL FORM → LATIN SMALL LETTER O# →‎ﻪ‎→→‎ه‎→ - {64428, "o"}, // MA# ( ‎ﮬ‎ → o ) ARABIC LETTER HEH DOACHASHMEE INITIAL FORM → LATIN SMALL LETTER O# →‎ﻫ‎→→‎ه‎→ - {64429, "o"}, // MA# ( ‎ﮭ‎ → o ) ARABIC LETTER HEH DOACHASHMEE MEDIAL FORM → LATIN SMALL LETTER O# →‎ﻬ‎→→‎ه‎→ + {64422, "o"}, // MA# ( ﮦ → o ) ARABIC LETTER HEH GOAL ISOLATED FORM → LATIN SMALL LETTER O# →ه→ + {64423, "o"}, // MA# ( ﮧ → o ) ARABIC LETTER HEH GOAL FINAL FORM → LATIN SMALL LETTER O# →ہ→→ه→ + {64424, "o"}, // MA# ( ﮨ → o ) ARABIC LETTER HEH GOAL INITIAL FORM → LATIN SMALL LETTER O# →ہ→→ه→ + {64425, "o"}, // MA# ( ﮩ → o ) ARABIC LETTER HEH GOAL MEDIAL FORM → LATIN SMALL LETTER O# →ہ→→ه→ + {64426, "o"}, // MA# ( ﮪ → o ) ARABIC LETTER HEH DOACHASHMEE ISOLATED FORM → LATIN SMALL LETTER O# →ه→ + {64427, "o"}, // MA# ( ﮫ → o ) ARABIC LETTER HEH DOACHASHMEE FINAL FORM → LATIN SMALL LETTER O# →ﻪ→→ه→ + {64428, "o"}, // MA# ( ﮬ → o ) ARABIC LETTER HEH DOACHASHMEE INITIAL FORM → LATIN SMALL LETTER O# →ﻫ→→ه→ + {64429, "o"}, // MA# ( ﮭ → o ) ARABIC LETTER HEH DOACHASHMEE MEDIAL FORM → LATIN SMALL LETTER O# →ﻬ→→ه→ {64830, "("}, // MA#* ( ﴾ → ( ) ORNATE LEFT PARENTHESIS → LEFT PARENTHESIS# {64831, ")"}, // MA#* ( ﴿ → ) ) ORNATE RIGHT PARENTHESIS → RIGHT PARENTHESIS# {65072, ":"}, // MA#* ( ︰ → : ) PRESENTATION FORM FOR VERTICAL TWO DOT LEADER → COLON# @@ -765,12 +765,12 @@ static const Confusable kConfusables[] = {65103, "_"}, // MA# ( ﹏ → _ ) WAVY LOW LINE → LOW LINE# {65112, "-"}, // MA#* ( ﹘ → - ) SMALL EM DASH → HYPHEN-MINUS# {65128, "\\"}, // MA#* ( ﹨ → \ ) SMALL REVERSE SOLIDUS → REVERSE SOLIDUS# →∖→ - {65165, "l"}, // MA# ( ‎ﺍ‎ → l ) ARABIC LETTER ALEF ISOLATED FORM → LATIN SMALL LETTER L# →‎ا‎→→1→ - {65166, "l"}, // MA# ( ‎ﺎ‎ → l ) ARABIC LETTER ALEF FINAL FORM → LATIN SMALL LETTER L# →‎ا‎→→1→ - {65257, "o"}, // MA# ( ‎ﻩ‎ → o ) ARABIC LETTER HEH ISOLATED FORM → LATIN SMALL LETTER O# →‎ه‎→ - {65258, "o"}, // MA# ( ‎ﻪ‎ → o ) ARABIC LETTER HEH FINAL FORM → LATIN SMALL LETTER O# →‎ه‎→ - {65259, "o"}, // MA# ( ‎ﻫ‎ → o ) ARABIC LETTER HEH INITIAL FORM → LATIN SMALL LETTER O# →‎ه‎→ - {65260, "o"}, // MA# ( ‎ﻬ‎ → o ) ARABIC LETTER HEH MEDIAL FORM → LATIN SMALL LETTER O# →‎ه‎→ + {65165, "l"}, // MA# ( ﺍ → l ) ARABIC LETTER ALEF ISOLATED FORM → LATIN SMALL LETTER L# →ا→→1→ + {65166, "l"}, // MA# ( ﺎ → l ) ARABIC LETTER ALEF FINAL FORM → LATIN SMALL LETTER L# →ا→→1→ + {65257, "o"}, // MA# ( ﻩ → o ) ARABIC LETTER HEH ISOLATED FORM → LATIN SMALL LETTER O# →ه→ + {65258, "o"}, // MA# ( ﻪ → o ) ARABIC LETTER HEH FINAL FORM → LATIN SMALL LETTER O# →ه→ + {65259, "o"}, // MA# ( ﻫ → o ) ARABIC LETTER HEH INITIAL FORM → LATIN SMALL LETTER O# →ه→ + {65260, "o"}, // MA# ( ﻬ → o ) ARABIC LETTER HEH MEDIAL FORM → LATIN SMALL LETTER O# →ه→ {65281, "!"}, // MA#* ( ! → ! ) FULLWIDTH EXCLAMATION MARK → EXCLAMATION MARK# →ǃ→ {65282, "\""}, // MA#* ( " → '' ) FULLWIDTH QUOTATION MARK → APOSTROPHE, APOSTROPHE# →”→→"→# Converted to a quote. {65287, "'"}, // MA#* ( ' → ' ) FULLWIDTH APOSTROPHE → APOSTROPHE# →’→ @@ -863,7 +863,7 @@ static const Confusable kConfusables[] = {66853, "F"}, // MA# ( 𐔥 → F ) ELBASAN LETTER GHE → LATIN CAPITAL LETTER F# {66854, "L"}, // MA# ( 𐔦 → L ) ELBASAN LETTER GHAMMA → LATIN CAPITAL LETTER L# {66855, "X"}, // MA# ( 𐔧 → X ) ELBASAN LETTER KHE → LATIN CAPITAL LETTER X# - {68176, "."}, // MA#* ( ‎𐩐‎ → . ) KHAROSHTHI PUNCTUATION DOT → FULL STOP# + {68176, "."}, // MA#* ( 𐩐 → . ) KHAROSHTHI PUNCTUATION DOT → FULL STOP# {70864, "O"}, // MA# ( 𑓐 → O ) TIRHUTA DIGIT ZERO → LATIN CAPITAL LETTER O# →০→→0→ {71424, "rn"}, // MA# ( 𑜀 → rn ) AHOM LETTER KA → LATIN SMALL LETTER R, LATIN SMALL LETTER N# →m→ {71430, "v"}, // MA# ( 𑜆 → v ) AHOM LETTER PA → LATIN SMALL LETTER V# @@ -1751,13 +1751,13 @@ static const Confusable kConfusables[] = {120829, "7"}, // MA# ( 𝟽 → 7 ) MATHEMATICAL MONOSPACE DIGIT SEVEN → DIGIT SEVEN# {120830, "8"}, // MA# ( 𝟾 → 8 ) MATHEMATICAL MONOSPACE DIGIT EIGHT → DIGIT EIGHT# {120831, "9"}, // MA# ( 𝟿 → 9 ) MATHEMATICAL MONOSPACE DIGIT NINE → DIGIT NINE# - {125127, "l"}, // MA#* ( ‎𞣇‎ → l ) MENDE KIKAKUI DIGIT ONE → LATIN SMALL LETTER L# - {125131, "8"}, // MA#* ( ‎𞣋‎ → 8 ) MENDE KIKAKUI DIGIT FIVE → DIGIT EIGHT# - {126464, "l"}, // MA# ( ‎𞸀‎ → l ) ARABIC MATHEMATICAL ALEF → LATIN SMALL LETTER L# →‎ا‎→→1→ - {126500, "o"}, // MA# ( ‎𞸤‎ → o ) ARABIC MATHEMATICAL INITIAL HEH → LATIN SMALL LETTER O# →‎ه‎→ - {126564, "o"}, // MA# ( ‎𞹤‎ → o ) ARABIC MATHEMATICAL STRETCHED HEH → LATIN SMALL LETTER O# →‎ه‎→ - {126592, "l"}, // MA# ( ‎𞺀‎ → l ) ARABIC MATHEMATICAL LOOPED ALEF → LATIN SMALL LETTER L# →‎ا‎→→1→ - {126596, "o"}, // MA# ( ‎𞺄‎ → o ) ARABIC MATHEMATICAL LOOPED HEH → LATIN SMALL LETTER O# →‎ه‎→ + {125127, "l"}, // MA#* ( 𞣇 → l ) MENDE KIKAKUI DIGIT ONE → LATIN SMALL LETTER L# + {125131, "8"}, // MA#* ( 𞣋 → 8 ) MENDE KIKAKUI DIGIT FIVE → DIGIT EIGHT# + {126464, "l"}, // MA# ( 𞸀 → l ) ARABIC MATHEMATICAL ALEF → LATIN SMALL LETTER L# →ا→→1→ + {126500, "o"}, // MA# ( 𞸤 → o ) ARABIC MATHEMATICAL INITIAL HEH → LATIN SMALL LETTER O# →ه→ + {126564, "o"}, // MA# ( 𞹤 → o ) ARABIC MATHEMATICAL STRETCHED HEH → LATIN SMALL LETTER O# →ه→ + {126592, "l"}, // MA# ( 𞺀 → l ) ARABIC MATHEMATICAL LOOPED ALEF → LATIN SMALL LETTER L# →ا→→1→ + {126596, "o"}, // MA# ( 𞺄 → o ) ARABIC MATHEMATICAL LOOPED HEH → LATIN SMALL LETTER O# →ه→ {127232, "O."}, // MA#* ( 🄀 → O. ) DIGIT ZERO FULL STOP → LATIN CAPITAL LETTER O, FULL STOP# →0.→ {127233, "O,"}, // MA#* ( 🄁 → O, ) DIGIT ZERO COMMA → LATIN CAPITAL LETTER O, COMMA# →0,→ {127234, "l,"}, // MA#* ( 🄂 → l, ) DIGIT ONE COMMA → LATIN SMALL LETTER L, COMMA# →1,→ From c87565b8b0db5d5d5bfd2b8b00ad6573e5d06d9f Mon Sep 17 00:00:00 2001 From: Andy Friesen Date: Fri, 13 Nov 2026 14:01:47 -0700 Subject: [PATCH 09/13] Sync to upstream/release/747 (#3128) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✈️ !!! ## Analysis * Avoid stack overflow in degenerate unions and intersection types * Fix a bug where analysis would permit iteration over non-iterable types in certain circumstances: ```luau local function foo(t: boolean | number | vector | {}) -- This used to be erroneously permitted for i, v in t do end end ``` * Fix an ICE in certain scenarios involving global function definitions within type functions * Fix an issue where error suppression was too eager to fire. eg ```luau -- The error here used to be improperly suppressed. local _: { read [number]: "hello" } = ... :: { read [any]: string } ``` ## Runtime * Add `luau_loadlazy`: This function is the same as `luau_load`, but only the main function is built. Other functions are lazy stubs that are loaded on their first use. * Do not use removed collapsed phis in BytecodeGraphParser * Fix https://github.com/luau-lang/luau/issues/3082 * Implement `buffer.readvector*f32` and `buffer.writevector*f32` per https://github.com/luau-lang/rfcs/pull/198 * Clip all in-progress integer code. See https://github.com/luau-lang/rfcs/pull/269 for details ## Native Codegen * Add support accelerated direct userdata access * Add support for frozen metatable cache access * Improved runtime rebuild error handling and a loop trip fix * Exit sync restore for expected tags * Runtime rebuild log and result callbacks * Lower thresholds before promotion to native code * Add a runtime rebuild log and result callbacks to better track VM promotion. * Fix register array overflow in LOP_FASTCALL bytecode analysis * Perform store forwarding for split stores as well ## Classes (experimental) * Report an error if a class's base constructor isn't called before a read or write to `self` in its constructor * Add support for nested and `local` classes Co-authored-by: Andy Friesen Co-authored-by: Hunter Goldstein Co-authored-by: Ilya Rezvov Co-authored-by: Sora Kanosue Co-authored-by: Thomas Schollenberger Co-authored-by: Vyacheslav Egorov --------- Co-authored-by: Vyacheslav Egorov Co-authored-by: Ariel Weiss Co-authored-by: Hunter Goldstein Co-authored-by: Varun Saini <61795485+vrn-sn@users.noreply.github.com> Co-authored-by: Sora Kanosue Co-authored-by: Annie Tang Co-authored-by: Annie Tang <98965493+annieetang@users.noreply.github.com> Co-authored-by: Ilya Rezvov Co-authored-by: Vighnesh Vijay Co-authored-by: Andreas Haeberlen Co-authored-by: Thomas Schollenberger --- Analysis/include/Luau/ConstraintGenerator.h | 4 +- Analysis/include/Luau/Error.h | 8 - Analysis/include/Luau/Generalization.h | 2 +- Analysis/include/Luau/Normalize.h | 11 - Analysis/include/Luau/Subtyping.h | 8 + Analysis/include/Luau/Type.h | 8 - Analysis/include/Luau/TypeChecker2.h | 42 +- Analysis/include/Luau/TypeFunctionRuntime.h | 1 - Analysis/include/Luau/TypeInfer.h | 1 - Analysis/src/AstJsonEncoder.cpp | 18 - Analysis/src/BuiltinDefinitions.cpp | 8 +- Analysis/src/BuiltinTypeFunctions.cpp | 30 +- Analysis/src/ConstraintGenerator.cpp | 356 +++-- Analysis/src/ConstraintSolver.cpp | 46 +- Analysis/src/ControlFlowGraph.cpp | 2 - Analysis/src/DataFlowGraph.cpp | 30 +- Analysis/src/EmbeddedBuiltinDefinitions.cpp | 227 +-- Analysis/src/Error.cpp | 24 +- Analysis/src/FragmentAutocomplete.cpp | 21 +- Analysis/src/Generalization.cpp | 28 +- Analysis/src/GlobalTypes.cpp | 3 - Analysis/src/IostreamHelpers.cpp | 14 - Analysis/src/Linter.cpp | 4 - Analysis/src/Module.cpp | 20 +- Analysis/src/NonStrictTypeChecker.cpp | 13 +- Analysis/src/Normalize.cpp | 514 +------ Analysis/src/OverloadResolver.cpp | 3 +- Analysis/src/Simplify.cpp | 187 +-- Analysis/src/Subtyping.cpp | 104 +- Analysis/src/ToString.cpp | 48 +- Analysis/src/Type.cpp | 6 - Analysis/src/TypeAttach.cpp | 2 - Analysis/src/TypeChecker2.cpp | 274 ++-- Analysis/src/TypeFunctionRuntime.cpp | 23 - Analysis/src/TypeFunctionRuntimeBuilder.cpp | 6 - Analysis/src/TypeInfer.cpp | 7 +- Analysis/src/TypeStateMap.cpp | 2 - Analysis/src/TypeUtils.cpp | 76 +- Analysis/src/Unifier.cpp | 1 - Analysis/src/Unifier2.cpp | 23 +- Ast/include/Luau/Ast.h | 51 +- Ast/include/Luau/Cst.h | 10 - Ast/include/Luau/Parser.h | 7 +- Ast/src/Ast.cpp | 61 +- Ast/src/Cst.cpp | 6 - Ast/src/Parser.cpp | 279 ++-- Ast/src/PrettyPrinter.cpp | 58 +- Bytecode/include/Luau/BytecodeBuilder.h | 17 +- Bytecode/include/Luau/BytecodeGraph.h | 5 - Bytecode/src/BytecodeBuilder.cpp | 147 +- Bytecode/src/BytecodeDump.cpp | 3 - Bytecode/src/BytecodeGraph.cpp | 19 +- Bytecode/src/BytecodeGraphParser.h | 60 +- Bytecode/src/Sccp.cpp | 3 - CLI/src/Repl.cpp | 48 + CodeGen/include/Luau/AssemblyBuilderA64.h | 1 + CodeGen/include/Luau/CodeGen.h | 7 + CodeGen/include/Luau/CodeGenOptions.h | 10 + CodeGen/include/Luau/IrData.h | 127 +- CodeGen/include/Luau/IrUtils.h | 2 + CodeGen/include/Luau/IrVisitUseDef.h | 17 +- CodeGen/src/AssemblyBuilderA64.cpp | 7 + CodeGen/src/BytecodeAnalysis.cpp | 117 +- CodeGen/src/CodeGen.cpp | 1 - CodeGen/src/CodeGenAssembly.cpp | 4 +- CodeGen/src/CodeGenContext.cpp | 222 ++- CodeGen/src/CodeGenLower.h | 4 + CodeGen/src/CodeGenUtils.cpp | 243 ++- CodeGen/src/CodeGenUtils.h | 1 + CodeGen/src/EmitCommonX64.h | 5 - CodeGen/src/IrBuilder.cpp | 7 +- CodeGen/src/IrDump.cpp | 27 +- CodeGen/src/IrLoweringA64.cpp | 193 ++- CodeGen/src/IrLoweringX64.cpp | 187 ++- CodeGen/src/IrRegAllocA64.cpp | 3 +- CodeGen/src/IrRegAllocX64.cpp | 3 +- CodeGen/src/IrTranslateBuiltins.cpp | 868 ++--------- CodeGen/src/IrTranslation.cpp | 383 +++-- CodeGen/src/IrUtils.cpp | 22 +- CodeGen/src/IrValueLocationTracking.cpp | 10 +- CodeGen/src/NativeState.cpp | 1 + CodeGen/src/NativeState.h | 1 + CodeGen/src/OptimizeConstProp.cpp | 246 ++- CodeGen/src/OptimizeDeadStore.cpp | 36 +- CodeGen/src/SharedCodeAllocator.cpp | 4 +- Common/include/Luau/Bytecode.h | 71 +- Compiler/include/Luau/Compiler.h | 5 +- Compiler/include/luacode.h | 1 - Compiler/src/BuiltinFolding.cpp | 4 - Compiler/src/Builtins.cpp | 158 +- Compiler/src/Compiler.cpp | 645 ++++---- Compiler/src/ConstantFolding.cpp | 18 +- Compiler/src/ConstantFolding.h | 2 - Compiler/src/CostModel.cpp | 2 +- Compiler/src/Types.cpp | 77 +- Compiler/src/Types.h | 1 - Compiler/src/ValueTracking.cpp | 21 + Compiler/src/lcode.cpp | 5 - Inliner/src/JitInliner.cpp | 6 +- Inliner/src/RuntimeBytecodeBuilder.h | 12 +- Inliner/src/TValueVmConstImpl.cpp | 3 - Sources.cmake | 1 - VM/include/lua.h | 18 +- VM/include/lualib.h | 4 - VM/src/lapi.cpp | 30 - VM/src/laux.cpp | 28 - VM/src/lbaselib.cpp | 8 +- VM/src/lbuflib.cpp | 144 +- VM/src/lbuiltins.cpp | 853 ++--------- VM/src/ldebug.cpp | 20 +- VM/src/ldo.cpp | 37 +- VM/src/lfunc.cpp | 8 +- VM/src/lgc.cpp | 17 +- VM/src/lgcdebug.cpp | 6 + VM/src/linit.cpp | 25 +- VM/src/lintlib.cpp | 614 -------- VM/src/lnumprint.cpp | 24 - VM/src/lnumutils.h | 6 - VM/src/lobject.cpp | 31 - VM/src/lobject.h | 42 +- VM/src/lperf.cpp | 1 - VM/src/lstate.cpp | 1 - VM/src/lstrlib.cpp | 15 +- VM/src/ltable.cpp | 301 ++-- VM/src/ltm.cpp | 1 - VM/src/lvm.h | 5 + VM/src/lvmexecute.cpp | 48 +- VM/src/lvmload.cpp | 1212 ++++++++++----- VM/src/lvmutils.cpp | 2 - bench/tests/integers/blake2b_int64.lua | 184 --- bench/tests/integers/murmur128_int64.lua | 97 -- bench/tests/integers/pollard_rho_int64.lua | 85 -- bench/tests/integers/sha3_int64.lua | 162 -- bench/tests/integers/sha512_int64.lua | 136 -- bench/tests/integers/xxh64_bit32.lua | 2 +- bench/tests/integers/xxh64_int64.lua | 96 -- bench/tests/vibemark67/stinky/cpu.lua | 1 + bench/tests/vibemark67/stinky/decode.lua | 8 +- bench/tests/vibemark67/stinky/elf.lua | 1 + bench/tests/vibemark67/stinky/emu.lua | 1 + bench/tests/vibemark67/stinky/integer.lua | 382 ++--- .../tests/vibemark67/stinky/integer.test.lua | 97 ++ bench/tests/vibemark67/stinky/memory.lua | 6 +- bench/tests/vibemark67/stinky/syscall.lua | 1 + tests/AssemblyBuilderA64.test.cpp | 2 + tests/AstJsonEncoder.test.cpp | 6 - tests/Autocomplete.test.cpp | 7 +- tests/BytecodeCallInliner.test.cpp | 69 +- tests/BytecodeCompiler.test.cpp | 7 +- tests/ClassRuntimeErrors.test.cpp | 4 - tests/Compiler.test.cpp | 966 ++++++++---- tests/Conformance.test.cpp | 390 ++++- tests/Error.test.cpp | 2 - tests/Fixture.cpp | 7 - tests/Fixture.h | 15 - tests/FragmentAutocomplete.test.cpp | 4 - tests/Frontend.test.cpp | 2 - tests/Generalization.test.cpp | 2 - tests/IrAssembly.test.cpp | 1 - tests/IrBuilder.test.cpp | 1318 ++++------------- tests/IrLowering.test.cpp | 546 ++----- tests/Linter.test.cpp | 2 - tests/Normalize.test.cpp | 332 +---- tests/Parser.test.cpp | 789 +++++++--- tests/Repl.test.cpp | 1 - tests/RequireByString.test.cpp | 5 - tests/RuntimeLimits.test.cpp | 2 - tests/Simplify.test.cpp | 300 +--- tests/Subtyping.test.cpp | 335 ----- tests/ToString.test.cpp | 196 +-- tests/TypeFunction.test.cpp | 10 - tests/TypeFunction.user.test.cpp | 118 -- tests/TypeInfer.aliases.test.cpp | 2 - tests/TypeInfer.builtins.test.cpp | 32 +- tests/TypeInfer.classes.test.cpp | 173 ++- tests/TypeInfer.externTypes.test.cpp | 10 - tests/TypeInfer.functions.test.cpp | 46 - tests/TypeInfer.generics.test.cpp | 6 - tests/TypeInfer.intersectionTypes.test.cpp | 20 - tests/TypeInfer.loops.test.cpp | 10 - tests/TypeInfer.metatableOOP.test.cpp | 10 - tests/TypeInfer.modules.test.cpp | 8 - tests/TypeInfer.operators.test.cpp | 36 - tests/TypeInfer.provisional.test.cpp | 25 +- tests/TypeInfer.refinements.test.cpp | 28 +- tests/TypeInfer.tables.test.cpp | 985 +----------- tests/TypeInfer.test.cpp | 48 +- tests/TypeInfer.tryUnify.test.cpp | 2 - tests/TypeInfer.unionTypes.test.cpp | 12 +- tests/TypePath.test.cpp | 2 - tests/TypeVar.test.cpp | 2 - tests/VisitType.test.cpp | 4 - tests/conformance/buffers.luau | 68 + tests/conformance/classes.luau | 218 +++ tests/conformance/integers.luau | 705 --------- tests/conformance/integers_regspill.luau | 305 ---- tests/conformance/lazyload.luau | 62 + tests/conformance/native.luau | 20 + tests/conformance/native_integer_spills.luau | 521 ------- tests/conformance/promotion.luau | 6 +- tests/conformance/udata_direct.luau | 105 ++ ...ot_a_duplicate.flags-off.nonstrict.output} | 0 ..._not_a_duplicate.flags-off.runtime.output} | 0 ...is_not_a_duplicate.flags-off.strict.output | 3 + ..._not_a_duplicate.flags-on.nonstrict.output | 0 ...is_not_a_duplicate.flags-on.runtime.output | 0 ..._is_not_a_duplicate.flags-on.strict.output | 3 + ...ed_in_nested_block_is_not_a_duplicate.luau | 14 + ...lic_inheritance.flags-off.nonstrict.output | 1 + ...yclic_inheritance.flags-off.runtime.output | 3 + ...cyclic_inheritance.flags-off.strict.output | 2 + ...clic_inheritance.flags-on.nonstrict.output | 1 + ...cyclic_inheritance.flags-on.runtime.output | 3 + .../cyclic_inheritance.flags-on.strict.output | 2 + ...heritance.luau => cyclic_inheritance.luau} | 8 +- ..._shadowed_class.flags-off.nonstrict.output | 1 + ...ct_shadowed_class.flags-off.runtime.output | 0 ...ect_shadowed_class.flags-off.strict.output | 2 + ...t_shadowed_class.flags-on.nonstrict.output | 1 + ...ect_shadowed_class.flags-on.runtime.output | 0 ...fect_shadowed_class.flags-on.strict.output | 2 + ...ed_block_do_not_affect_shadowed_class.luau | 18 + ...nitions_are_any.flags-off.nonstrict.output | 1 + ...finitions_are_any.flags-off.runtime.output | 0 ...efinitions_are_any.flags-off.strict.output | 1 + ...initions_are_any.flags-on.nonstrict.output | 1 + ...efinitions_are_any.flags-on.runtime.output | 0 ...definitions_are_any.flags-on.strict.output | 1 + .../duplicate_class_definitions_are_any.luau | 10 + ...nitions_are_any.flags-off.nonstrict.output | 1 + ...finitions_are_any.flags-off.runtime.output | 0 ...efinitions_are_any.flags-off.strict.output | 1 + ...initions_are_any.flags-on.nonstrict.output | 1 + ...efinitions_are_any.flags-on.runtime.output | 0 ...definitions_are_any.flags-on.strict.output | 1 + ...icate_local_class_definitions_are_any.luau | 10 + ...al_class_is_any.flags-off.nonstrict.output | 2 + ...obal_class_is_any.flags-off.runtime.output | 0 ...lobal_class_is_any.flags-off.strict.output | 2 + ...bal_class_is_any.flags-on.nonstrict.output | 2 + ...lobal_class_is_any.flags-on.runtime.output | 0 ...global_class_is_any.flags-on.strict.output | 2 + ...class_duplicating_global_class_is_any.luau | 10 + ..._later_position.flags-off.nonstrict.output | 0 ...in_later_position.flags-off.runtime.output | 0 ..._in_later_position.flags-off.strict.output | 1 + ...n_later_position.flags-on.nonstrict.output | 0 ..._in_later_position.flags-on.runtime.output | 0 ...r_in_later_position.flags-on.strict.output | 1 + ...o_super_constructor_in_later_position.luau | 11 + ...tor_is_an_error.flags-off.nonstrict.output | 0 ...uctor_is_an_error.flags-off.runtime.output | 0 ...ructor_is_an_error.flags-off.strict.output | 1 + ...ctor_is_an_error.flags-on.nonstrict.output | 0 ...ructor_is_an_error.flags-on.runtime.output | 0 ...tructor_is_an_error.flags-on.strict.output | 1 + ..._before_super_constructor_is_an_error.luau | 15 + ...ally_inherits_sqrt.flags-off.strict.output | 2 +- ...cally_inherits_sqrt.flags-on.strict.output | 2 +- ...cyclic_inheritance.flags-off.strict.output | 3 - ..._cyclic_inheritance.flags-on.strict.output | 3 - ...tor_is_an_error.flags-off.nonstrict.output | 0 ...uctor_is_an_error.flags-off.runtime.output | 0 ...ructor_is_an_error.flags-off.strict.output | 1 + ...ctor_is_an_error.flags-on.nonstrict.output | 0 ...ructor_is_an_error.flags-on.runtime.output | 0 ...tructor_is_an_error.flags-on.strict.output | 1 + ..._before_super_constructor_is_an_error.luau | 15 + ...ction_and_union.flags-off.nonstrict.output | 1 - ...section_and_union.flags-off.runtime.output | 3 - ...rsection_and_union.flags-off.strict.output | 1 - ...rsection_and_union.flags-on.runtime.output | 3 - ...ization_negate_intersection_and_union.luau | 2 - ...on_occurs_check.flags-off.nonstrict.output | 1 + ...tion_occurs_check.flags-off.runtime.output | 1 + ...ction_occurs_check.flags-off.strict.output | 2 + ...ion_occurs_check.flags-on.nonstrict.output | 1 + ...ction_occurs_check.flags-on.runtime.output | 1 + ...ection_occurs_check.flags-on.strict.output | 2 + ...rsive_union_intersection_occurs_check.luau | 4 + ...te_union_of_options.flags-on.strict.output | 4 +- ...iadic_intersection.flags-off.strict.output | 4 + ...xer_suppression.flags-off.nonstrict.output | 0 ...dexer_suppression.flags-off.runtime.output | 0 ...ndexer_suppression.flags-off.strict.output | 2 + ...exer_suppression.flags-on.nonstrict.output | 0 ...ndexer_suppression.flags-on.runtime.output | 0 ...indexer_suppression.flags-on.strict.output | 46 + .../analysis/tables/indexer_suppression.luau | 18 + 289 files changed, 7310 insertions(+), 13392 deletions(-) delete mode 100644 VM/src/lintlib.cpp delete mode 100644 bench/tests/integers/blake2b_int64.lua delete mode 100644 bench/tests/integers/murmur128_int64.lua delete mode 100644 bench/tests/integers/pollard_rho_int64.lua delete mode 100644 bench/tests/integers/sha3_int64.lua delete mode 100644 bench/tests/integers/sha512_int64.lua delete mode 100644 bench/tests/integers/xxh64_int64.lua create mode 100644 bench/tests/vibemark67/stinky/integer.test.lua delete mode 100644 tests/conformance/integers.luau delete mode 100644 tests/conformance/integers_regspill.luau create mode 100644 tests/conformance/lazyload.luau delete mode 100644 tests/conformance/native_integer_spills.luau rename tests/golden/analysis/{fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.nonstrict.output => classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.nonstrict.output} (100%) rename tests/golden/analysis/{fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.strict.output => classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.runtime.output} (100%) create mode 100644 tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau create mode 100644 tests/golden/analysis/classes/cyclic_inheritance.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/cyclic_inheritance.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/cyclic_inheritance.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/cyclic_inheritance.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/cyclic_inheritance.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/cyclic_inheritance.flags-on.strict.output rename tests/golden/analysis/classes/{three_step_cyclic_inheritance.luau => cyclic_inheritance.luau} (68%) create mode 100644 tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau create mode 100644 tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/duplicate_class_definitions_are_any.luau create mode 100644 tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.luau create mode 100644 tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.luau create mode 100644 tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.luau create mode 100644 tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.luau delete mode 100644 tests/golden/analysis/classes/three_step_cyclic_inheritance.flags-off.strict.output delete mode 100644 tests/golden/analysis/classes/three_step_cyclic_inheritance.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.runtime.output create mode 100644 tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.strict.output create mode 100644 tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.runtime.output create mode 100644 tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.strict.output create mode 100644 tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.luau delete mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.nonstrict.output delete mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.runtime.output delete mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.strict.output delete mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.runtime.output delete mode 100644 tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau create mode 100644 tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.runtime.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.strict.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.runtime.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.strict.output create mode 100644 tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau create mode 100644 tests/golden/analysis/tables/indexer_suppression.flags-off.nonstrict.output create mode 100644 tests/golden/analysis/tables/indexer_suppression.flags-off.runtime.output create mode 100644 tests/golden/analysis/tables/indexer_suppression.flags-off.strict.output create mode 100644 tests/golden/analysis/tables/indexer_suppression.flags-on.nonstrict.output create mode 100644 tests/golden/analysis/tables/indexer_suppression.flags-on.runtime.output create mode 100644 tests/golden/analysis/tables/indexer_suppression.flags-on.strict.output create mode 100644 tests/golden/analysis/tables/indexer_suppression.luau diff --git a/Analysis/include/Luau/ConstraintGenerator.h b/Analysis/include/Luau/ConstraintGenerator.h index da6691de2..048d635ba 100644 --- a/Analysis/include/Luau/ConstraintGenerator.h +++ b/Analysis/include/Luau/ConstraintGenerator.h @@ -163,6 +163,7 @@ struct ConstraintGenerator DenseHashMap inferredExprCache; DenseHashMap> classDeclRecords; + DenseHashSet duplicateClassDecls; DcrLogger* logger; @@ -303,7 +304,8 @@ struct ConstraintGenerator void applyRefinements(const ScopePtr& scope, Location location, RefinementId refinement); LUAU_NOINLINE void prototypeTypeDefinitions(const ScopePtr& scope, AstStatBlock* block); - void prototypeClass(const ScopePtr& scope, AstStatClass* classDecl, TypeId classObjectTy); + ClassDeclRecord prototypeClass(const ScopePtr& scope, AstStatClass* classDecl, TypeId classObjectTy, Name className); + TypeId resolveSuperclass(const ScopePtr& scope, AstStatClass* statClass, TypeId superValueTy); ControlFlow visitBlockWithoutChildScope(const ScopePtr& scope, AstStatBlock* block); diff --git a/Analysis/include/Luau/Error.h b/Analysis/include/Luau/Error.h index 383131503..e83fb35d9 100644 --- a/Analysis/include/Luau/Error.h +++ b/Analysis/include/Luau/Error.h @@ -627,13 +627,6 @@ struct ConstructorsShouldNotReturnAnything } }; -struct CyclicClassInheritance -{ - std::vector cycle; - - bool operator==(const CyclicClassInheritance& rhs) const; -}; - struct InvalidClassExtension { enum Context @@ -749,7 +742,6 @@ using TypeErrorData = Variant< AmbiguousFunctionCall, UninitializedFieldAccess, ConstructorsShouldNotReturnAnything, - CyclicClassInheritance, InvalidClassExtension, IncompatibleClassMethodOverride, IllegalClassPropertyOverride, diff --git a/Analysis/include/Luau/Generalization.h b/Analysis/include/Luau/Generalization.h index 9ecc5c7eb..2d06fc090 100644 --- a/Analysis/include/Luau/Generalization.h +++ b/Analysis/include/Luau/Generalization.h @@ -50,7 +50,7 @@ GeneralizationResult generalizeTypePack( const GeneralizationParams& params ); -void sealTable(NotNull scope, TypeId ty, TableState targetState); +void sealTable(NotNull scope, TypeId ty); /** Attempt to generalize a type. diff --git a/Analysis/include/Luau/Normalize.h b/Analysis/include/Luau/Normalize.h index 4a4a6b26b..e42af22d2 100644 --- a/Analysis/include/Luau/Normalize.h +++ b/Analysis/include/Luau/Normalize.h @@ -214,10 +214,6 @@ struct NormalizedType // This type is either never or number. TypeId numbers; - // The integer part of the type. - // This type is either never or integer. - TypeId integers; - // The string part of the type. // This may be the `string` type, or a union of singletons. NormalizedStringType strings; @@ -287,7 +283,6 @@ struct NormalizedType bool hasErrors() const; bool hasNils() const; bool hasNumbers() const; - bool hasIntegers() const; bool hasStrings() const; bool hasThreads() const; bool hasBuffers() const; @@ -406,12 +401,6 @@ class Normalizer void intersectStrings(NormalizedStringType& here, const NormalizedStringType& there); bool hasStringIndexer(const TableType* tt); std::optional intersectionOfTables(TypeId here, TypeId there, SeenTablePropPairs& seenTablePropPairs, DenseHashSet& seenSet); - std::optional DEPRECATED_intersectionOfTables( - TypeId here, - TypeId there, - SeenTablePropPairs& seenTablePropPairs, - DenseHashSet& seenSet - ); void intersectTablesWithTable(TypeIds& heres, TypeId there, SeenTablePropPairs& seenTablePropPairs, DenseHashSet& seenSetTypes); void intersectTables(TypeIds& heres, const TypeIds& theres); std::optional intersectionOfFunctions(TypeId here, TypeId there); diff --git a/Analysis/include/Luau/Subtyping.h b/Analysis/include/Luau/Subtyping.h index a2ed01635..629811c2c 100644 --- a/Analysis/include/Luau/Subtyping.h +++ b/Analysis/include/Luau/Subtyping.h @@ -346,6 +346,14 @@ struct Subtyping const TableIndexer& superIndexer, NotNull scope ); + + SubtypingResult isCovariantWith_DEPRECATED( + SubtypingEnvironment& env, + const TableIndexer& subIndexer, + const TableIndexer& superIndexer, + NotNull scope + ); + SubtypingResult isCovariantWith( SubtypingEnvironment& env, const Property& subProperty, diff --git a/Analysis/include/Luau/Type.h b/Analysis/include/Luau/Type.h index c22a72e90..1a7c6f6e0 100644 --- a/Analysis/include/Luau/Type.h +++ b/Analysis/include/Luau/Type.h @@ -167,7 +167,6 @@ struct PrimitiveType NilType, // ObjC #defines Nil :( Boolean, Number, - Integer, String, Thread, Function, @@ -420,11 +419,6 @@ enum class TableState // properties are required, but we don't care about the full shape. Only // used in the old solver. Generic, - - // An exact table type is similar to a sealed table, but it does not - // participate in width subtyping. It describes the exact exhaustive shape - // of the whole table. - Exact, }; struct TableIndexer @@ -985,7 +979,6 @@ bool isPrim(TypeId ty, PrimitiveType::Type primType); bool isNil(TypeId ty); bool isBoolean(TypeId ty); bool isNumber(TypeId ty); -bool isInteger(TypeId ty); bool isString(TypeId ty); bool isThread(TypeId ty); bool isBuffer(TypeId ty); @@ -1044,7 +1037,6 @@ struct BuiltinTypes std::unique_ptr typeFunctions; const TypeId nilType; const TypeId numberType; - const TypeId integerType; const TypeId stringType; const TypeId booleanType; const TypeId threadType; diff --git a/Analysis/include/Luau/TypeChecker2.h b/Analysis/include/Luau/TypeChecker2.h index fa4c4fae1..c63e41045 100644 --- a/Analysis/include/Luau/TypeChecker2.h +++ b/Analysis/include/Luau/TypeChecker2.h @@ -159,8 +159,8 @@ struct TypeChecker2 void visit(AstStatDeclareExternType* stat); void checkExtendsClause(AstStatClass* stat); void visit(AstStatClass* stat); - void visitConstructor(AstStatClass* stat, const AstClassMethod* method); - void checkMemberOverrides(AstStatClass* stat); + void visitConstructor(AstStatClass* stat, const AstClassMethod* method, const ExternType* superInstanceEtv); + void checkMemberOverrides(AstStatClass* stat, const ExternType* superInstanceEtv); void checkPropertyOverride(AstStatClass* stat, const AstClassProperty* property, const ExternType* superInstanceEtv); void checkMethodOverride(AstStatClass* stat, const AstClassMethod* method, const ExternType* superInstanceEtv); void visit(AstStatError* stat); @@ -169,7 +169,6 @@ struct TypeChecker2 void visit(AstExprConstantNil* expr); void visit(AstExprConstantBool* expr); void visit(AstExprConstantNumber* expr); - void visit(AstExprConstantInteger* expr); void visit(AstExprConstantString* expr); void visit(AstExprLocal* expr); void visit(AstExprGlobal* expr); @@ -264,6 +263,43 @@ struct TypeChecker2 size_t argHeadSize, Location callLocation ); + + // Nested in TypeChecker2 so we can use lookupExpr + struct FindUninitializedAccesses : public AstVisitor + { + NotNull self; + NotNull> uninitializedFields; + DenseHashSet methodNames; + + std::optional violatingRef; + DenseHashMap violatingFields; + + // NULL if there is no base class constructor or it's been called + TypeId superConstructor; + NotNull checker; + + FindUninitializedAccesses( + AstLocal* self, + NotNull> uninitializedFields, + DenseHashSet methodNames, + TypeId superConstructor, + NotNull checker + ) + : self(self) + , uninitializedFields(uninitializedFields) + , methodNames(std::move(methodNames)) + , superConstructor(superConstructor) + , checker(checker) + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + } + + bool visit(AstExprLocal* local) override; + bool visit(AstExprIndexName* indexName) override; + bool visit(AstExprIndexExpr* indexName) override; + bool visit(AstExprTypeAssertion* expr) override; + bool visit(AstExprCall* call) override; + }; }; } // namespace Luau diff --git a/Analysis/include/Luau/TypeFunctionRuntime.h b/Analysis/include/Luau/TypeFunctionRuntime.h index 6c22d966a..d06144520 100644 --- a/Analysis/include/Luau/TypeFunctionRuntime.h +++ b/Analysis/include/Luau/TypeFunctionRuntime.h @@ -42,7 +42,6 @@ struct TypeFunctionPrimitiveType NilType, Boolean, Number, - Integer, String, Thread, Buffer, diff --git a/Analysis/include/Luau/TypeInfer.h b/Analysis/include/Luau/TypeInfer.h index a36c1469d..10c83cd9e 100644 --- a/Analysis/include/Luau/TypeInfer.h +++ b/Analysis/include/Luau/TypeInfer.h @@ -477,7 +477,6 @@ struct TypeChecker public: const TypeId nilType; const TypeId numberType; - const TypeId integerType; const TypeId stringType; const TypeId booleanType; const TypeId threadType; diff --git a/Analysis/src/AstJsonEncoder.cpp b/Analysis/src/AstJsonEncoder.cpp index 70497bac1..62747a941 100644 --- a/Analysis/src/AstJsonEncoder.cpp +++ b/Analysis/src/AstJsonEncoder.cpp @@ -333,18 +333,6 @@ struct AstJsonEncoder : public AstVisitor ); } - void write(class AstExprConstantInteger* node) - { - writeNode( - node, - "AstExprConstantInteger", - [&]() - { - write("value", node->value); - } - ); - } - void write(class AstExprConstantString* node) { writeNode( @@ -1267,12 +1255,6 @@ struct AstJsonEncoder : public AstVisitor return false; } - bool visit(class AstExprConstantInteger* node) override - { - write(node); - return false; - } - bool visit(class AstExprConstantString* node) override { write(node); diff --git a/Analysis/src/BuiltinDefinitions.cpp b/Analysis/src/BuiltinDefinitions.cpp index 6174b2ca2..16ad62d0d 100644 --- a/Analysis/src/BuiltinDefinitions.cpp +++ b/Analysis/src/BuiltinDefinitions.cpp @@ -26,7 +26,6 @@ LUAU_FASTFLAG(LuauCyclicRequireTypeInference) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) -LUAU_FASTFLAG(DebugLuauExactTableTypes) /** FIXME: Many of these type definitions are not quite completely accurate. * @@ -1263,7 +1262,7 @@ TypeId makeStringMetatable(NotNull builtinTypes, SolverMode mode) {}, {arena->addType( TableType{ - {}, TableIndexer{numberType, stringType}, TypeLevel{}, FFlag::DebugLuauExactTableTypes ? TableState::Exact : TableState::Sealed + {}, TableIndexer{numberType, stringType}, TypeLevel{}, TableState::Sealed } )}, /* checked */ true @@ -1694,10 +1693,7 @@ static std::optional freezeTable(TypeId inputType, const MagicFunctionCa // `clone` should not break this. LUAU_ASSERT(tableTy); - if (FFlag::DebugLuauExactTableTypes && (tableTy->state == TableState::Unsealed || tableTy->state == TableState::Exact)) - tableTy->state = TableState::Exact; - else - tableTy->state = TableState::Sealed; + tableTy->state = TableState::Sealed; // We'll mutate the table to make every property type read-only. for (auto iter = tableTy->props.begin(); iter != tableTy->props.end();) diff --git a/Analysis/src/BuiltinTypeFunctions.cpp b/Analysis/src/BuiltinTypeFunctions.cpp index fbef723cb..b246a7ead 100644 --- a/Analysis/src/BuiltinTypeFunctions.cpp +++ b/Analysis/src/BuiltinTypeFunctions.cpp @@ -24,7 +24,6 @@ LUAU_DYNAMIC_FASTINTVARIABLE(LuauStepRefineRecursionLimit, 64) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauCyclicRequireTypeInference) -LUAU_FASTFLAGVARIABLE(LuauRefineNotNilWaitsForBlockedTarget) LUAU_FASTFLAGVARIABLE(LuauSetmetatableOverrides) LUAU_FLAGVERSION(LuauSetmetatableOverrides, 2) LUAU_FASTFLAG(LuauTraverseScopeToFunction) @@ -1308,28 +1307,25 @@ TypeFunctionReductionResult refineTypeFunction( { SimplifyResult result = simplifyIntersection(ctx->builtins, ctx->arena, target, discriminant); - if (FFlag::LuauRefineNotNilWaitsForBlockedTarget) + std::vector blocked; + for (TypeId ty : result.blockedTypes) { - std::vector blocked; - for (TypeId ty : result.blockedTypes) - { - if (is(follow(ty))) - blocked.push_back(ty); - } + if (is(follow(ty))) + blocked.push_back(ty); + } - if (auto ut = get(follow(target))) + if (auto ut = get(follow(target))) + { + for (TypeId option : ut) { - for (TypeId option : ut) - { - if (isBlockedOrUnsolvedType(follow(option))) - blocked.push_back(option); - } + if (isBlockedOrUnsolvedType(follow(option))) + blocked.push_back(option); } - - if (!blocked.empty()) - return {nullptr, std::move(blocked)}; } + if (!blocked.empty()) + return {nullptr, std::move(blocked)}; + return {result.result, {}}; } } diff --git a/Analysis/src/ConstraintGenerator.cpp b/Analysis/src/ConstraintGenerator.cpp index 70609497b..76c1dc753 100644 --- a/Analysis/src/ConstraintGenerator.cpp +++ b/Analysis/src/ConstraintGenerator.cpp @@ -41,17 +41,16 @@ LUAU_FASTFLAG(DebugLuauLogSolverToJson) LUAU_FASTFLAG(DebugLuauMagicTypes) LUAU_FASTINTVARIABLE(LuauPrimitiveInferenceInTableLimit, 500) LUAU_FASTFLAGVARIABLE(LuauDisallowRedefiningBuiltinTypes) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAGVARIABLE(DebugLuauCFG) LUAU_FASTFLAG(LuauCyclicRequireTypeInference) -LUAU_FASTFLAGVARIABLE(DebugLuauExactTableTypes) LUAU_FASTFLAG(LuauSetmetatableOverrides) LUAU_FASTFLAGVARIABLE(LuauExperimentalIfLocalAnalysis) LUAU_FLAGVERSION(LuauExperimentalIfLocalAnalysis, 2) LUAU_FASTFLAG(LuauTraverseScopeToFunction) LUAU_FASTFLAGVARIABLE(LuauUnconditionallyVisitTypeAliasParams) LUAU_FASTFLAGVARIABLE(LuauBanGlobalsInTypeFunctions) +LUAU_FLAGVERSION(LuauBanGlobalsInTypeFunctions, 2) LUAU_FASTFLAGVARIABLE(LuauFillInUninitializedGlobals) LUAU_FASTFLAGVARIABLE(LuauExperimentalWhileLocalAnalysis) @@ -952,24 +951,11 @@ void ConstraintGenerator::applyRefinements(const ScopePtr& scope, Location locat void ConstraintGenerator::prototypeTypeDefinitions(const ScopePtr& scope, AstStatBlock* block) { DenseHashMap typeNameLocations; + DenseHashMap classDeclsByName; bool hasTypeFunction = false; ScopePtr typeFunctionEnvScope; - // Stub out class declarations so that they can refer to one another in any order. - DenseHashMap allClasses; - for (AstStat* stat : block->body) - { - if (auto classDecl = stat->as()) - { - TypeId classObjectTy = arena->addType( - ExternType{classDecl->name->name.value, {}, std::nullopt, std::nullopt, Tags{}, nullptr, module->name, classDecl->location} - ); - - allClasses[classDecl] = classObjectTy; - } - } - // In order to enable mutually-recursive type aliases, we need to // populate the type bindings before we actually check any of the // alias statements. @@ -1102,25 +1088,23 @@ void ConstraintGenerator::prototypeTypeDefinitions(const ScopePtr& scope, AstSta } else if (auto classDecl = stat->as()) { - Name declName = classDecl->name->name.value; - DefId theDef = dfg->getDef(classDecl->name); + Name declName = Name{classDecl->getName().value}; if (Location* loc = typeNameLocations.find(declName)) { reportError(classDecl->location, DuplicateTypeDefinition{declName, *loc}); - scope->bindings[classDecl->name] = Binding{builtinTypes->errorType, classDecl->location}; - scope->lvalueTypes[theDef] = builtinTypes->errorType; - continue; - } - typeNameLocations[declName] = classDecl->location; - TypeId* classObjectTy = allClasses.find(classDecl); - LUAU_ASSERT(classObjectTy && *classObjectTy); + if (AstStatClass** firstClassDecl = classDeclsByName.find(declName)) + { + duplicateClassDecls.insert(*firstClassDecl); + duplicateClassDecls.insert(classDecl); + } - scope->bindings[classDecl->name] = Binding{*classObjectTy, classDecl->name->location}; - scope->lvalueTypes[theDef] = *classObjectTy; + continue; + } - prototypeClass(scope, classDecl, *classObjectTy); + typeNameLocations[declName] = classDecl->location; + classDeclsByName[declName] = classDecl; } } @@ -1254,12 +1238,10 @@ void ConstraintGenerator::prototypeTypeDefinitions(const ScopePtr& scope, AstSta } } -void ConstraintGenerator::prototypeClass(const ScopePtr& scope, AstStatClass* classDecl, TypeId classObjectTy) +ClassDeclRecord ConstraintGenerator::prototypeClass(const ScopePtr& scope, AstStatClass* classDecl, TypeId classObjectTy, Name className) { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); - Name declName = classDecl->name->name.value; - // Objects are ExternTypes, where the metatable field represents the metamethods associated with the instance. // Class: ExternType { props, parent: top class type, metatable: constructor } // Object: ExternType { props, parent: top object type for now, metatable: instance metamethods } @@ -1303,8 +1285,7 @@ void ConstraintGenerator::prototypeClass(const ScopePtr& scope, AstStatClass* cl auto prop = Property::readonly(propertyType); prop.location = method.nameLocation; - if (method.function->args.size < 1 || method.function->args.data[0]->name != "self") - staticProps[method.functionName.value] = prop; + staticProps[method.functionName.value] = prop; // The parser will report an error for classes that define disallowed metamethods. // The RFC also requires that it is a syntax error for methods to have __ in their name whose name is not in the @@ -1328,7 +1309,7 @@ void ConstraintGenerator::prototypeClass(const ScopePtr& scope, AstStatClass* cl TypeId instanceMetatable = arena->addType(TableType{instanceMetatableProps, std::nullopt, TypeLevel{}, scope.get(), TableState::Sealed}); TypeId classInstanceTy = arena->addType( - ExternType{declName, std::move(props), builtinTypes->objectType, instanceMetatable, Tags{}, nullptr, module->name, classDecl->location} + ExternType{className, std::move(props), builtinTypes->objectType, instanceMetatable, Tags{}, nullptr, module->name, classDecl->location} ); // If the class does not define an explicit constructor, then we know the type of the default constructor at this point. @@ -1356,12 +1337,12 @@ void ConstraintGenerator::prototypeClass(const ScopePtr& scope, AstStatClass* cl getMutable(classObjectTy)->relation.emplace(Obj{classInstanceTy}); getMutable(classInstanceTy)->relation.emplace(Klass{classObjectTy}); - if (classDecl->exported) - scope->exportedTypeBindings[classDecl->name->name.value] = TypeFun{{}, {}, classInstanceTy, classDecl->location}; + if (classDecl->declModifier == AstStatClass::DeclModifier::Export) + scope->exportedTypeBindings[className] = TypeFun{{}, {}, classInstanceTy, classDecl->location}; else - scope->privateTypeBindings[classDecl->name->name.value] = TypeFun{{}, {}, classInstanceTy, classDecl->location}; + scope->privateTypeBindings[className] = TypeFun{{}, {}, classInstanceTy, classDecl->location}; - classDeclRecords[classDecl->name] = std::make_unique(classObjectTy, classInstanceTy, std::move(memberTypes)); + return ClassDeclRecord{classObjectTy, classInstanceTy, std::move(memberTypes)}; } ControlFlow ConstraintGenerator::visitBlockWithoutChildScope(const ScopePtr& scope, AstStatBlock* block) @@ -1999,19 +1980,41 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatFunction* f } else if (AstExprGlobal* globalName = function->name->as()) { - if (!existingFunctionTy) - ice->ice("prepopulateGlobalScope did not populate a global name", globalName->location); - - if (auto bt = get(*existingFunctionTy); bt && uninitializedGlobals.contains(globalName->name)) + if (FFlag::LuauBanGlobalsInTypeFunctions) { - LUAU_ASSERT(bt->getOwner() == nullptr); - uninitializedGlobals.erase(globalName->name); - emplaceType(asMutable(*existingFunctionTy), generalizedType); + // If we're inside a type function, then we might not have a + // prexisting function type that we should refer to, which is + // fine. + if (existingFunctionTy) + { + if (auto bt = get(*existingFunctionTy); bt && uninitializedGlobals.contains(globalName->name)) + { + LUAU_ASSERT(bt->getOwner() == nullptr); + uninitializedGlobals.erase(globalName->name); + emplaceType(asMutable(*existingFunctionTy), generalizedType); + } + + + scope->bindings[globalName->name] = Binding{sig.signature, globalName->location}; + scope->lvalueTypes[def] = sig.signature; + } } + else + { + if (!existingFunctionTy) + ice->ice("prepopulateGlobalScope did not populate a global name", globalName->location); + if (auto bt = get(*existingFunctionTy); bt && uninitializedGlobals.contains(globalName->name)) + { + LUAU_ASSERT(bt->getOwner() == nullptr); + uninitializedGlobals.erase(globalName->name); + emplaceType(asMutable(*existingFunctionTy), generalizedType); + } - scope->bindings[globalName->name] = Binding{sig.signature, globalName->location}; - scope->lvalueTypes[def] = sig.signature; + + scope->bindings[globalName->name] = Binding{sig.signature, globalName->location}; + scope->lvalueTypes[def] = sig.signature; + } } else if (AstExprIndexName* indexName = function->name->as()) { @@ -2656,15 +2659,60 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatClass* stat { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + // Resolved before the class binds its own name so that `local class Foo extends Foo` sees the shadowed Foo instead + // of inheriting from itself. + std::optional superTy; if (statClass->super) - check(scope, statClass->super); + { + TypeId superValueTy = check(scope, statClass->super).ty; + superTy = resolveSuperclass(scope, statClass, superValueTy); + } - const std::unique_ptr* classDeclRecordPtr = classDeclRecords.find(statClass->name); - // TODO CLI-199124: This is unpopulated in fragment autocomplete. - if (classDeclRecordPtr == nullptr) - return ControlFlow::None; + Name className{statClass->getName().value}; + + TypeId classObjectTy = arena->addType(ExternType{className, {}, std::nullopt, std::nullopt, Tags{}, nullptr, module->name, statClass->location}); + + // Duplicate classes still get a full ExternType so that their bodies are checked, but the name itself is bound to + // any so that uses of it don't pick an arbitrary winner. + TypeId boundTy = duplicateClassDecls.contains(statClass) ? builtinTypes->anyType : classObjectTy; + + if (statClass->declModifier == AstStatClass::DeclModifier::None) + { + DefId def = dfg->getDef(statClass->exprName); - NotNull classDeclRecord{classDeclRecordPtr->get()}; + if (AstExprLocal* localName = statClass->exprName->as()) + { + visitLValue(scope, localName, boundTy); + + scope->bindings[localName->local] = Binding{boundTy, localName->location}; + scope->lvalueTypes[def] = boundTy; + } + else if (AstExprGlobal* globalName = statClass->exprName->as()) + { + std::optional existingClassTy = follow(lookup(scope, globalName->location, def)); + + if (!existingClassTy) + ice->ice("prepopulateGlobalScope did not populate a global name", globalName->location); + + if (const BlockedType* bt = get(*existingClassTy); bt && uninitializedGlobals.contains(globalName->name)) + { + LUAU_ASSERT(bt->getOwner() == nullptr); + uninitializedGlobals.erase(globalName->name); + emplaceType(asMutable(*existingClassTy), boundTy); + } + + scope->bindings[globalName->name] = Binding{boundTy, globalName->location}; + scope->lvalueTypes[def] = boundTy; + } + } + else + { + DefId def = dfg->getDef(statClass->localName); + scope->bindings[statClass->localName] = Binding{boundTy, statClass->localName->location}; + scope->lvalueTypes[def] = boundTy; + } + + ClassDeclRecord classDeclRecord = prototypeClass(scope, statClass, classObjectTy, className); for (const auto& member : statClass->members) { @@ -2672,7 +2720,7 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatClass* stat overloaded{ [&](const AstClassProperty& classProp) { - auto entry = classDeclRecord->memberTypes.find(classProp.name); + auto entry = classDeclRecord.memberTypes.find(classProp.name); if (entry == nullptr) { LUAU_ASSERT(!"Unexpected missing class property type"); @@ -2688,7 +2736,7 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatClass* stat }, [&](const AstClassMethod& method) { - auto entry = classDeclRecord->memberTypes.find(method.functionName); + auto entry = classDeclRecord.memberTypes.find(method.functionName); if (entry == nullptr) { LUAU_ASSERT(!"Unexpected missing class method type"); @@ -2703,7 +2751,7 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatClass* stat return; FunctionSignature sig = - checkFunctionSignature(scope, classDeclRecord, method.function, /* expectedType */ std::nullopt, method.function->location); + checkFunctionSignature(scope, &classDeclRecord, method.function, /* expectedType */ std::nullopt, method.function->location); Checkpoint start = checkpoint(this); checkFunctionBody(sig.bodyScope, method.function); @@ -2729,7 +2777,7 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatClass* stat if (method.functionName == "__init") { - std::optional classTy_ = classDeclRecord->classTy; + std::optional classTy_ = classDeclRecord.classTy; LUAU_ASSERT(classTy_.has_value()); TypeId classTy = follow(*classTy_); @@ -2760,7 +2808,7 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatClass* stat FunctionType constructorFunction = *initFn; // __call metamethod implicitly passes the class as the first argument constructorFunction.argTypes = arena->addTypePack({classTy}, constructorArgs); - constructorFunction.retTypes = arena->addTypePack({classDeclRecord->instanceTy}); + constructorFunction.retTypes = arena->addTypePack({classDeclRecord.instanceTy}); constructorFunction.hasSelf = false; // Also clip self and the return pack from the generic list. @@ -2768,7 +2816,7 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatClass* stat { vec.erase(std::remove(vec.begin(), vec.end(), val), vec.end()); }; - eraseValue(constructorFunction.generics, classDeclRecord->instanceTy); + eraseValue(constructorFunction.generics, classDeclRecord.instanceTy); eraseValue(constructorFunction.genericPacks, initFn->retTypes); TypeId constructorFn = arena->addType(std::move(constructorFunction)); @@ -2788,112 +2836,106 @@ ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatClass* stat ); } - if (statClass->super) + if (superTy) { - const TypeId classInstanceTy = classDeclRecord->instanceTy; + ExternType* classExtern = getMutable(classDeclRecord.instanceTy); + classExtern->parent = *superTy; + } - TypeId superTy = builtinTypes->errorType; + return ControlFlow::None; +} - // The superclass is an "expression" but it's also a type. This is a - // bit kooky. - // - // * It could be a bare identifier which indicates a class type in the - // current scope. +TypeId ConstraintGenerator::resolveSuperclass(const ScopePtr& scope, AstStatClass* statClass, TypeId superValueTy) +{ + LUAU_ASSERT(statClass->super); + + TypeId superTy = builtinTypes->errorType; + + // The superclass is an "expression" but it's also a type. This is a + // bit kooky. We do some casing on node type to improve error messages. + // + // * It could be a bare identifier which indicates a class type in the + // current scope. - auto lookupClass = [&scope, this](AstName name) + auto lookupClass = [&scope, this](AstName name) + { + auto tf = scope->lookupType(name.value); + if (!tf.has_value()) { - auto tf = scope->lookupType(name.value); - if (!tf.has_value()) - { - // If there is no type by this name, but there is a value, the - // developer has probably extended something they shouldn't - // have. We grab it here and retain it anyway for error - // reporting. - return scope->lookup(name).value_or(builtinTypes->errorType); - } - else if (!tf->typePackParams.empty() || !tf->typeParams.empty()) - { - LUAU_ASSERT(!"Classes cannot yet inherit from generics"); - return builtinTypes->errorType; - } - else - { - TypeId t = follow(tf->type); - if (is(t)) - return t; + // If there is no type by this name, but there is a value, the + // developer has probably extended something they shouldn't + // have. We grab it here and retain it anyway for error + // reporting. + return scope->lookup(name).value_or(builtinTypes->errorType); + } + else if (!tf->typePackParams.empty() || !tf->typeParams.empty()) + { + LUAU_ASSERT(!"Classes cannot yet inherit from generics"); + return builtinTypes->errorType; + } + else + { + TypeId t = follow(tf->type); + if (is(t)) + return t; - return builtinTypes->errorType; - } - }; + return builtinTypes->errorType; + } + }; - if (auto astLocal = statClass->super->as()) - superTy = lookupClass(astLocal->local->name); - else if (auto astGlobal = statClass->super->as()) - superTy = lookupClass(astGlobal->name); + if (auto astLocal = statClass->super->as()) + superTy = lookupClass(astLocal->local->name); + else if (auto astGlobal = statClass->super->as()) + superTy = lookupClass(astGlobal->name); - // * It could be ModuleName.TypeName, which indicates a class in another - // module. + // * It could be ModuleName.TypeName, which indicates a class in another + // module. - else if (auto indexName = statClass->super->as()) + else if (auto indexName = statClass->super->as()) + { + if (auto baseLocal = indexName->expr->as()) { - if (auto baseLocal = indexName->expr->as()) + std::optional tf; + + if (auto imported = scope->importedTypeBindings.find(baseLocal->local->name.value); imported != scope->importedTypeBindings.end()) { - std::optional tf; + if (auto binding = imported->second.find(indexName->index.value); binding != imported->second.end()) + tf = binding->second; + } - if (auto imported = scope->importedTypeBindings.find(baseLocal->local->name.value); imported != scope->importedTypeBindings.end()) + if (!tf.has_value()) + superTy = builtinTypes->errorType; + else + { + if (!tf->typeParams.empty() || !tf->typePackParams.empty()) { - if (auto binding = imported->second.find(indexName->index.value); binding != imported->second.end()) - tf = binding->second; - } - - if (!tf.has_value()) + LUAU_ASSERT(!"Classes cannot yet inherit from generics"); superTy = builtinTypes->errorType; + } else { - if (!tf->typeParams.empty() || !tf->typePackParams.empty()) - { - LUAU_ASSERT(!"Classes cannot yet inherit from generics"); - superTy = builtinTypes->errorType; - } - else - { - TypeId t = follow(tf->type); - if (is(t)) - superTy = tf->type; - } + TypeId t = follow(tf->type); + if (is(t)) + superTy = tf->type; } } } + } + else + { + // We do some validation here to make sure superValueTy is an ExternType for a class type, not an object type + superTy = follow(superValueTy); - // * It could be something else entirely, in which case I think we just - // inherit from `error` and hope for the best. - - // Check for an inheritance cycle. If there is, this class's base class - // is then errorType. - TypeId cycleTest = superTy; - while (cycleTest) + if (const ExternType* superClass = get(superTy); superClass && superClass->relation) { - cycleTest = follow(cycleTest); - - if (cycleTest == classInstanceTy) - { - // Cyclic inheritance detected - superTy = arena->addType(ErrorType{superTy}); - break; - } - - auto et = get(follow(cycleTest)); - if (!et) - break; - - cycleTest = et->parent.value_or(nullptr); + if (const Obj* obj = superClass->relation->get_if()) + superTy = obj->ty; } - - ExternType* classExtern = getMutable(classInstanceTy); - classExtern->parent = superTy; } - return ControlFlow::None; + // In the failure case, we just inherit from `error` and hope for the best. + + return superTy; } ControlFlow ConstraintGenerator::visit(const ScopePtr& scope, AstStatError* error) @@ -3368,8 +3410,6 @@ Inference ConstraintGenerator::check(const ScopePtr& scope, AstExpr* expr, std:: result = check(scope, stringExpr, expectedType, forceSingleton); else if (expr->is()) result = Inference{builtinTypes->numberType}; - else if (expr->is()) - result = Inference{builtinTypes->integerType}; else if (auto boolExpr = expr->as()) result = check(scope, boolExpr, expectedType, forceSingleton); else if (expr->is()) @@ -3722,11 +3762,6 @@ Inference ConstraintGenerator::check(const ScopePtr& scope, AstExprUnary* unary) } case AstExprUnary::Op::Minus: { - // compileExprUnary folds `-1i` into one negative constant, so a negated integer literal is a value rather than - // an operation. A non-literal integer still reaches the runtime, which has no __unm, so it keeps the check. - if (FFlag::LuauIntegerType2 && unary->expr->is()) - return Inference{builtinTypes->integerType, std::move(refinement)}; - TypeId resultType = createTypeFunctionInstance(builtinTypes->typeFunctions->unmFunc, {operandType}, {}, scope, unary->location); return Inference{resultType, std::move(refinement)}; } @@ -4018,8 +4053,6 @@ std::tuple ConstraintGenerator::checkBinary( discriminantTy = builtinTypes->stringType; else if (typeguard->type == "number") discriminantTy = builtinTypes->numberType; - else if (typeguard->type == "integer") - discriminantTy = builtinTypes->integerType; else if (typeguard->type == "boolean") discriminantTy = builtinTypes->booleanType; else if (typeguard->type == "thread") @@ -4903,11 +4936,7 @@ TypeId ConstraintGenerator::resolveTableType(const ScopePtr& scope, AstType* ty, polarity = p; - TableState state = TableState::Sealed; - if (FFlag::DebugLuauExactTableTypes && tab->isExact) - state = TableState::Exact; - - TypeId tableTy = arena->addType(TableType{props, indexer, scope->level, scope.get(), state}); + TypeId tableTy = arena->addType(TableType{props, indexer, scope->level, scope.get(), TableState::Sealed}); TableType* ttv = getMutable(tableTy); ttv->definitionModuleName = module->name; @@ -5379,6 +5408,23 @@ struct GlobalPrepopulator : AstVisitor return true; } + bool visit(AstStatClass* cls) override + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + if (cls->declModifier != AstStatClass::DeclModifier::None) + return true; + + if (AstExprGlobal* g = cls->exprName->as()) + { + TypeId bt = arena->addType(BlockedType{}); + uninitializedGlobals.insert(g->name); + globalScope->bindings[g->name] = Binding{bt}; + } + + return true; + } + bool visit(AstType*) override { return true; diff --git a/Analysis/src/ConstraintSolver.cpp b/Analysis/src/ConstraintSolver.cpp index e22a58646..2ed7da2c6 100644 --- a/Analysis/src/ConstraintSolver.cpp +++ b/Analysis/src/ConstraintSolver.cpp @@ -44,7 +44,6 @@ LUAU_FASTFLAGVARIABLE(DebugLuauLogBindings) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAGVARIABLE(LuauForceLess) LUAU_FASTFLAG(LuauCyclicRequireTypeInference) -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAGVARIABLE(LuauTraverseScopeToFunction) LUAU_FLAGVERSION(LuauTraverseScopeToFunction, 2) LUAU_FASTFLAG(LuauReferenceCountInitializerIsIterative) @@ -1026,12 +1025,7 @@ bool ConstraintSolver::tryDispatch(const GeneralizationConstraint& c, NotNull(ty)) - { - TableState targetState = TableState::Sealed; - if (FFlag::DebugLuauExactTableTypes && tt->state == TableState::Unsealed) - targetState = TableState::Exact; - sealTable(constraint->scope, ty, targetState); - } + sealTable(constraint->scope, ty); unblock(ty, constraint->location); } @@ -1843,9 +1837,6 @@ bool ConstraintSolver::tryDispatch(const FunctionCheckConstraint& c, NotNull replacements; - DenseHashMap replacementPacks; - DenseHashSet genericTypesAndPacks; Unifier2 u2{arena, builtinTypes, constraint->scope, NotNull{&iceReporter}}; @@ -1855,17 +1846,11 @@ bool ConstraintSolver::tryDispatch(const FunctionCheckConstraint& c, NotNull(follow(generic))) - { - replacements[generic] = gty->polarity == Polarity::Negative ? builtinTypes->neverType : builtinTypes->unknownType; genericTypesAndPacks.insert(generic); - } } for (auto genericPack : ftv->genericPacks) - { - replacementPacks[genericPack] = builtinTypes->unknownTypePack; genericTypesAndPacks.insert(genericPack); - } // If this is a self call, the types will have more elements than the AST call. // We don't attempt to perform bidirectional inference on the self type. @@ -2023,7 +2008,7 @@ bool ConstraintSolver::tryDispatchHasIndexer( // We expect `resultType` to be followed later, so just reassign it here. resultType = freeResult; - const TableState ubState = FFlag::DebugLuauExactTableTypes ? TableState::Sealed : TableState::Unsealed; + const TableState ubState = TableState::Unsealed; TypeId upperBound = arena->addType(TableType{/* props */ {}, TableIndexer{indexType, resultType}, TypeLevel{}, ft->scope, ubState}); TypeId sr = follow(simplifyIntersection(constraint->scope, constraint->location, ft->upperBound, upperBound)); @@ -2726,7 +2711,6 @@ bool ConstraintSolver::tryDispatch(const EqualityConstraint& c, NotNullstate != TableState::Exact) - return {{}, builtinTypes->unknownType}; - } - else - { - if (inConditional) - return {{}, builtinTypes->unknownType}; - } + if (inConditional) + return {{}, builtinTypes->unknownType}; } else if (auto mt = get(subjectType); mt && context == ValueContext::LValue) { @@ -3715,16 +3691,8 @@ std::optional> ConstraintSolver::lookupTablePropHelper( // If we are in a conditional context, we treat the property as present // and `unknown` because we may be _refining_ a table to include that // property. - if (FFlag::DebugLuauExactTableTypes) - { - if (inConditional && ttv->state != TableState::Exact) - return {{builtinTypes->unknownType, false}}; - } - else - { - if (inConditional) - return {{builtinTypes->unknownType, false}}; - } + if (inConditional) + return {{builtinTypes->unknownType, false}}; } else if (auto mt = get(subjectType); mt && context == ValueContext::LValue) { diff --git a/Analysis/src/ControlFlowGraph.cpp b/Analysis/src/ControlFlowGraph.cpp index 866cec903..06088813d 100644 --- a/Analysis/src/ControlFlowGraph.cpp +++ b/Analysis/src/ControlFlowGraph.cpp @@ -1000,8 +1000,6 @@ std::optional CFGBuilder::lowerExpr(LoweringExprContext& ctx, As return std::nullopt; else if (auto num = expr->as()) return std::nullopt; - else if (auto intExpr = expr->as()) - return std::nullopt; else if (auto str = expr->as()) return std::nullopt; else if (auto local = expr->as()) diff --git a/Analysis/src/DataFlowGraph.cpp b/Analysis/src/DataFlowGraph.cpp index 0e8ec0a5b..8f67622b5 100644 --- a/Analysis/src/DataFlowGraph.cpp +++ b/Analysis/src/DataFlowGraph.cpp @@ -388,23 +388,6 @@ ControlFlow DataFlowGraphBuilder::visit(AstStatBlock* b) ControlFlow DataFlowGraphBuilder::visitBlockWithoutChildScope(AstStatBlock* b) { - // Classes are hoisted and so can be referred to before their declaration. - // Before we do anything, quickly zip through any classes and preallocate - // DefIds for them. - if (FFlag::DebugLuauUserDefinedClasses) - { - for (AstStat* stat : b->body) - { - if (auto d = stat->as()) - { - DefId def = defArena->freshCell(d->name, d->name->location); - graph.localDefs[d->name] = def; - currentScope()->bindings[d->name] = def; - captures[d->name].allVersions.push_back(def); - } - } - } - std::optional firstControlFlow; for (AstStat* stat : b->body) { @@ -904,9 +887,20 @@ ControlFlow DataFlowGraphBuilder::visit(AstStatClass* d) { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + // In `class A extends A`, the second `A` should refer to existing names, so we visit it first if (d->super) visitExpr(d->super); + if (d->declModifier == AstStatClass::DeclModifier::None) + visitLValue(d->exprName, defArena->freshCell(Symbol{}, d->exprName->location)); + else + { + DefId def = defArena->freshCell(d->localName, d->localName->location); + graph.localDefs[d->localName] = def; + currentScope()->bindings[d->localName] = def; + captures[d->localName].allVersions.push_back(def); + } + for (const auto& member : d->members) { Luau::visit( @@ -961,8 +955,6 @@ DataFlowResult DataFlowGraphBuilder::visitExpr(AstExpr* e) return {defArena->freshCell(Symbol{}, c->location), nullptr}; // ok else if (auto c = e->as()) return {defArena->freshCell(Symbol{}, c->location), nullptr}; // ok - else if (auto c = e->as()) - return {defArena->freshCell(Symbol{}, c->location), nullptr}; // ok else if (auto c = e->as()) return {defArena->freshCell(Symbol{}, c->location), nullptr}; // ok else if (auto l = e->as()) diff --git a/Analysis/src/EmbeddedBuiltinDefinitions.cpp b/Analysis/src/EmbeddedBuiltinDefinitions.cpp index 8ac6de4c9..65fb0eb69 100644 --- a/Analysis/src/EmbeddedBuiltinDefinitions.cpp +++ b/Analysis/src/EmbeddedBuiltinDefinitions.cpp @@ -1,10 +1,8 @@ // This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details #include "Luau/BuiltinDefinitions.h" -LUAU_FASTFLAG(LuauIntegerLibrary) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauAllowGlobalDeclarationToBeCalledClass) -LUAU_FASTFLAG(DebugLuauExactTableTypes) +LUAU_FASTFLAG(DebugLuauBufferVectorLibrary) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAGVARIABLE(LuauCoroutineFinallyAnalysis) LUAU_FASTFLAGVARIABLE(LuauRemoveLoadstringFromBuiltinDefinitions) @@ -286,32 +284,6 @@ declare table: { )BUILTIN_SRC"; -static constexpr const char* kBuiltinDefinitionTableSrc_EXACT_TABLES = R"BUILTIN_SRC( - -declare table: { - concat: (t: {V, ...}, sep: string?, i: number?, j: number?) -> string, - insert: ((t: {V, ...}, value: V) -> ()) & ((t: {V, ...}, pos: number, value: V) -> ()), - maxn: (t: {V, ...}) -> number, - remove: (t: {V, ...}, number?) -> V?, - sort: (t: {V, ...}, comp: ((V, V) -> boolean)?) -> (), - create: (count: number, value: V?) -> {V}, - find: (haystack: {V, ...}, needle: V, init: number?) -> number?, - - unpack: (list: {V, ...}, i: number?, j: number?) -> ...V, - pack: (...V) -> { n: number, [number]: V }, - - getn: (t: {V, ...}) -> number, - foreach: (t: {[K]: V, ...}, f: (K, V) -> ()) -> (), - foreachi: ({V, ...}, (number, V) -> ()) -> (), - - move: (src: {V, ...}, a: number, b: number, t: number, dst: {V, ...}?) -> {V, ...}, - - clear: (table: {...}) -> (), - isfrozen: (t: {...}) -> boolean, -} - -)BUILTIN_SRC"; - static constexpr const char* kBuiltinDefinitionDebugSrc = R"BUILTIN_SRC( declare debug: { @@ -334,7 +306,7 @@ declare utf8: { )BUILTIN_SRC"; -static constexpr const char* kBuiltinDefinitionBufferSrc = R"BUILTIN_SRC( +static constexpr const char* kBuiltinDefinitionBufferSrcPrefix = R"BUILTIN_SRC( --- Buffer API declare buffer: { create: @checked (size: number) -> buffer, @@ -351,41 +323,16 @@ declare buffer: { readu32: @checked (b: buffer, offset: number) -> number, readf32: @checked (b: buffer, offset: number) -> number, readf64: @checked (b: buffer, offset: number) -> number, - writei8: @checked (b: buffer, offset: number, value: number) -> (), - writeu8: @checked (b: buffer, offset: number, value: number) -> (), - writei16: @checked (b: buffer, offset: number, value: number) -> (), - writeu16: @checked (b: buffer, offset: number, value: number) -> (), - writei32: @checked (b: buffer, offset: number, value: number) -> (), - writeu32: @checked (b: buffer, offset: number, value: number) -> (), - writef32: @checked (b: buffer, offset: number, value: number) -> (), - writef64: @checked (b: buffer, offset: number, value: number) -> (), - readstring: @checked (b: buffer, offset: number, count: number) -> string, - writestring: @checked (b: buffer, offset: number, value: string, count: number?) -> (), - readbits: @checked (b: buffer, bitOffset: number, bitCount: number) -> number, - writebits: @checked (b: buffer, bitOffset: number, bitCount: number, value: number) -> (), - readinteger: @checked (b: buffer, offset: number) -> integer, - writeinteger: @checked (b: buffer, offset: number, value: integer) -> (), -} +)BUILTIN_SRC"; +static constexpr const char* kBuiltinDefinitionBufferVectorSrc = R"BUILTIN_SRC( + readvectorf32x2: @checked (b: buffer, offset: number) -> vector, + readvectorf32x3: @checked (b: buffer, offset: number) -> vector, + writevectorf32x2: @checked (b: buffer, offset: number, value: vector) -> (), + writevectorf32x3: @checked (b: buffer, offset: number, value: vector) -> (), )BUILTIN_SRC"; -static constexpr const char* kBuiltinDefinitionBufferSrc_NOINTEGER = R"BUILTIN_SRC( ---- Buffer API -declare buffer: { - create: @checked (size: number) -> buffer, - fromstring: @checked (str: string) -> buffer, - tostring: @checked (b: buffer) -> string, - len: @checked (b: buffer) -> number, - copy: @checked (target: buffer, targetOffset: number, source: buffer, sourceOffset: number?, count: number?) -> (), - fill: @checked (b: buffer, offset: number, value: number, count: number?) -> (), - readi8: @checked (b: buffer, offset: number) -> number, - readu8: @checked (b: buffer, offset: number) -> number, - readi16: @checked (b: buffer, offset: number) -> number, - readu16: @checked (b: buffer, offset: number) -> number, - readi32: @checked (b: buffer, offset: number) -> number, - readu32: @checked (b: buffer, offset: number) -> number, - readf32: @checked (b: buffer, offset: number) -> number, - readf64: @checked (b: buffer, offset: number) -> number, +static constexpr const char* kBuiltinDefinitionBufferSrcSuffix = R"BUILTIN_SRC( writei8: @checked (b: buffer, offset: number, value: number) -> (), writeu8: @checked (b: buffer, offset: number, value: number) -> (), writei16: @checked (b: buffer, offset: number, value: number) -> (), @@ -433,54 +380,6 @@ declare vector: { )BUILTIN_SRC"; -static const char* const kBuiltinDefinitionIntegerSrc = R"BUILTIN_SRC( - -declare integer: { - create: @checked (x: number) -> integer, - tonumber: @checked (x: integer) -> number, - neg: @checked (value: integer) -> integer, - add: @checked (x: integer, y: integer) -> integer, - sub: @checked (x: integer, y: integer) -> integer, - mul: @checked (x: integer, y: integer) -> integer, - div: @checked (x: integer, y: integer) -> integer, - rem: @checked (x: integer, y: integer) -> integer, - idiv: @checked (x: integer, y: integer) -> integer, - mod: @checked (x: integer, y: integer) -> integer, - udiv: @checked (x: integer, y: integer) -> integer, - urem: @checked (x: integer, y: integer) -> integer, - min: @checked (integer, ...integer) -> integer, - max: @checked (integer, ...integer) -> integer, - band: @checked (...integer) -> integer, - bor: @checked (...integer) -> integer, - bnot: @checked (x: integer) -> integer, - bxor: @checked (...integer) -> integer, - lt: @checked (x: integer, y: integer) -> boolean, - le: @checked (x: integer, y: integer) -> boolean, - ult: @checked (x: integer, y: integer) -> boolean, - ule: @checked (x: integer, y: integer) -> boolean, - gt: @checked (x: integer, y: integer) -> boolean, - ge: @checked (x: integer, y: integer) -> boolean, - ugt: @checked (x: integer, y: integer) -> boolean, - uge: @checked (x: integer, y: integer) -> boolean, - lshift: @checked (x: integer, numBitPositions: integer) -> integer, - rshift: @checked (x: integer, numBitPositions: integer) -> integer, - arshift: @checked (x: integer, numBitPositions: integer) -> integer, - lrotate: @checked (x: integer, numBitPositions: integer) -> integer, - rrotate: @checked (x: integer, numBitPositions: integer) -> integer, - extract: @checked (value: integer, bitPosition: integer, numBits: integer?) -> integer, - replace: @checked (value: integer, replacement: integer, bitPosition: integer, numBits: integer?) -> integer, - clamp: @checked (value: integer, min: integer, max: integer) -> integer, - btest: @checked (...integer) -> boolean, - countrz: @checked (x: integer) -> integer, - countlz: @checked (x: integer) -> integer, - bswap: @checked (x: integer) -> integer, - fromstring: @checked (str: string, base: number?) -> integer, - minsigned: integer, - maxsigned: integer -} - -)BUILTIN_SRC"; - static const char* kBuiltinDefinitionClassSrc = R"CLASS_SRC( declare class: { isinstance: @checked (o: unknown, c: class) -> boolean, @@ -501,24 +400,16 @@ std::string getBuiltinDefinitionSource() else result += kBuiltinDefinitionCoroutineSrc_DEPRECATED; - if (FFlag::DebugLuauExactTableTypes) - result += kBuiltinDefinitionTableSrc_EXACT_TABLES; - else - result += kBuiltinDefinitionTableSrc; + result += kBuiltinDefinitionTableSrc; result += kBuiltinDefinitionDebugSrc; result += kBuiltinDefinitionUtf8Src; - if (FFlag::LuauIntegerType2 && FFlag::LuauIntegerLibrary) - result += kBuiltinDefinitionBufferSrc; - else - result += kBuiltinDefinitionBufferSrc_NOINTEGER; + result += kBuiltinDefinitionBufferSrcPrefix; + if (FFlag::DebugLuauBufferVectorLibrary) + result += kBuiltinDefinitionBufferVectorSrc; + result += kBuiltinDefinitionBufferSrcSuffix; result += kBuiltinDefinitionVectorSrc; - if (FFlag::LuauIntegerType2 && FFlag::LuauIntegerLibrary) - { - result += kBuiltinDefinitionIntegerSrc; - } - if (FFlag::DebugLuauUserDefinedClasses && FFlag::LuauAllowGlobalDeclarationToBeCalledClass) { result += kBuiltinDefinitionClassSrc; @@ -530,60 +421,6 @@ std::string getBuiltinDefinitionSource() // TODO: split into separate tagged unions when the new solver can appropriately handle that. static constexpr const char* kBuiltinDefinitionTypeMethodSrc = R"BUILTIN_SRC( -export type type = { - tag: "nil" | "unknown" | "never" | "any" | "boolean" | "number" | "integer" | "string" | "buffer" | "thread" | - "singleton" | "negation" | "union" | "intersection" | "table" | "function" | "extern" | "generic", - - is: (self: type, arg: string) -> boolean, - issubtypeof: (self: type, arg: type) -> boolean, - - -- for singleton type - value: (self: type) -> (string | boolean | nil), - - -- for negation type - inner: (self: type) -> type, - - -- for union and intersection types - components: (self: type) -> {type}, - - -- for table type - setproperty: (self: type, key: type, value: type?) -> (), - setreadproperty: (self: type, key: type, value: type?) -> (), - setwriteproperty: (self: type, key: type, value: type?) -> (), - readproperty: (self: type, key: type) -> type?, - writeproperty: (self: type, key: type) -> type?, - properties: (self: type) -> { [type]: { read: type?, write: type? } }, - setindexer: (self: type, index: type, result: type) -> (), - setreadindexer: (self: type, index: type, result: type) -> (), - setwriteindexer: (self: type, index: type, result: type) -> (), - indexer: (self: type) -> { index: type, readresult: type, writeresult: type }?, - readindexer: (self: type) -> { index: type, result: type }?, - writeindexer: (self: type) -> { index: type, result: type }?, - setmetatable: (self: type, arg: type) -> (), - metatable: (self: type) -> type?, - - -- for function type - setparameters: (self: type, head: {type}?, tail: type?) -> (), - parameters: (self: type) -> { head: {type}?, tail: type? }, - setreturns: (self: type, head: {type}?, tail: type? ) -> (), - returns: (self: type) -> { head: {type}?, tail: type? }, - setgenerics: (self: type, {type}?) -> (), - generics: (self: type) -> {type}, - - -- for class type - -- 'properties', 'metatable', 'indexer', 'readindexer' and 'writeindexer' are shared with table type - readparent: (self: type) -> type?, - writeparent: (self: type) -> type?, - - -- for generic type - name: (self: type) -> string?, - ispack: (self: type) -> boolean, -} - -)BUILTIN_SRC"; - -static constexpr const char* kBuiltinDefinitionTypeMethodSrc_NOINTEGER = R"BUILTIN_SRC( - export type type = { tag: "nil" | "unknown" | "never" | "any" | "boolean" | "number" | "string" | "buffer" | "thread" | "singleton" | "negation" | "union" | "intersection" | "table" | "function" | "extern" | "generic", @@ -638,31 +475,6 @@ export type type = { static constexpr const char* kBuiltinDefinitionTypesLibSrc = R"BUILTIN_SRC( -declare types: { - unknown: type, - never: type, - any: type, - boolean: type, - number: type, - string: type, - thread: type, - buffer: type, - integer: type, - - singleton: @checked (arg: string | boolean | nil) -> type, - optional: @checked (arg: type) -> type, - generic: @checked (name: string, ispack: boolean?) -> type, - negationof: @checked (arg: type) -> type, - unionof: @checked (...type) -> type, - intersectionof: @checked (...type) -> type, - newtable: @checked (props: {[type]: type} | {[type]: { read: type?, write: type? } }?, indexer: { index: type, readresult: type, writeresult: type }?, metatable: type?) -> type, - newfunction: @checked (parameters: { head: {type}?, tail: type? }?, returns: { head: {type}?, tail: type? }?, generics: {type}?) -> type, - copy: @checked (arg: type) -> type, -} -)BUILTIN_SRC"; - -static constexpr const char* kBuiltinDefinitionTypesLibSrc_NOINTEGER = R"BUILTIN_SRC( - declare types: { unknown: type, never: type, @@ -689,15 +501,8 @@ std::string getTypeFunctionDefinitionSource() { std::string result; - if (FFlag::LuauIntegerType2) - result += kBuiltinDefinitionTypeMethodSrc; - else - result += kBuiltinDefinitionTypeMethodSrc_NOINTEGER; - - if (FFlag::LuauIntegerType2) - result += kBuiltinDefinitionTypesLibSrc; - else - result += kBuiltinDefinitionTypesLibSrc_NOINTEGER; + result += kBuiltinDefinitionTypeMethodSrc; + result += kBuiltinDefinitionTypesLibSrc; return result; } diff --git a/Analysis/src/Error.cpp b/Analysis/src/Error.cpp index f921cf4ea..41e218fa6 100644 --- a/Analysis/src/Error.cpp +++ b/Analysis/src/Error.cpp @@ -1037,21 +1037,6 @@ struct ErrorConverter return "Class constructors should not return anything."; } - std::string operator()(const CyclicClassInheritance& e) const - { - std::string s = "Cyclic class inheritance detected: "; - bool first = true; - for (const Name& name : e.cycle) - { - if (first) - first = false; - else - s += " -> "; - s += name; - } - return s; - } - std::string operator()(const InvalidClassExtension& e) const { switch (e.context) @@ -1328,11 +1313,6 @@ bool FunctionExitsWithoutReturning::operator==(const FunctionExitsWithoutReturni return expectedReturnType == rhs.expectedReturnType; } -bool CyclicClassInheritance::operator==(const CyclicClassInheritance& rhs) const -{ - return cycle.size() == rhs.cycle.size() && std::equal(cycle.begin(), cycle.end(), rhs.cycle.begin()); -} - bool InvalidClassExtension::operator==(const InvalidClassExtension& rhs) const { return context == rhs.context && baseClass == rhs.baseClass; @@ -1358,6 +1338,7 @@ bool NotIterable::operator==(const NotIterable& rhs) const return ty == rhs.ty; } + int TypeError::code() const { return minCode() + int(data.index()); @@ -1848,9 +1829,6 @@ void copyError(T& e, TypeArena& destArena, CloneState& cloneState) else if constexpr (std::is_same_v) { } - else if constexpr (std::is_same_v) - { - } else if constexpr (std::is_same_v) { e.baseClass = clone(e.baseClass); diff --git a/Analysis/src/FragmentAutocomplete.cpp b/Analysis/src/FragmentAutocomplete.cpp index 71157cba4..b9912d002 100644 --- a/Analysis/src/FragmentAutocomplete.cpp +++ b/Analysis/src/FragmentAutocomplete.cpp @@ -487,11 +487,22 @@ FragmentAutocompleteAncestryResult findAncestryForFragmentParse(AstStatBlock* st else if (auto classDecl = stat->as()) { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); - // We need to include the class name as part of the - // locals so that within the fragment the class name - // is defined. - localStack.push_back(classDecl->name); - localMap[classDecl->name->name] = classDecl->name; + // If it exists, we include the associated local as part of locals so that within the fragment the class name is defined + + if (classDecl->declModifier == AstStatClass::DeclModifier::None) + { + if (const AstExprLocal* local = classDecl->exprName->as()) + { + localStack.push_back(local->local); + localMap[local->local->name] = local->local; + } + } + else + { + localStack.push_back(classDecl->localName); + localMap[classDecl->localName->name] = classDecl->localName; + } + if (classDecl->location.containsClosed(cursorPos)) { AstExprFunction* currentMethod = nullptr; diff --git a/Analysis/src/Generalization.cpp b/Analysis/src/Generalization.cpp index e59dbb30d..b6e28db38 100644 --- a/Analysis/src/Generalization.cpp +++ b/Analysis/src/Generalization.cpp @@ -19,7 +19,6 @@ LUAU_FASTINTVARIABLE(LuauGenericCounterMaxDepth, 15) LUAU_FASTINTVARIABLE(LuauGenericCounterMaxSteps, 1500) -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAGVARIABLE(LuauIterativeTypeSearcher) LUAU_FLAGVERSION(LuauIterativeTypeSearcher, 2) @@ -1390,7 +1389,7 @@ GeneralizationResult generalizeTypePack( return {tp, /*wasReplacedByGeneric*/ false}; } -void sealTable(NotNull scope, TypeId ty, TableState targetState) +void sealTable(NotNull scope, TypeId ty) { TableType* tableTy = getMutable(follow(ty)); if (!tableTy) @@ -1400,12 +1399,7 @@ void sealTable(NotNull scope, TypeId ty, TableState targetState) return; if (tableTy->state == TableState::Unsealed || tableTy->state == TableState::Free) - { - if (FFlag::DebugLuauExactTableTypes) - tableTy->state = targetState; - else - tableTy->state = TableState::Sealed; - } + tableTy->state = TableState::Sealed; } std::optional generalize( @@ -1485,14 +1479,7 @@ std::optional generalize( if (generalizationTarget && unsealedTableTy != *generalizationTarget) continue; - TableState targetState = TableState::Sealed; - if (FFlag::DebugLuauExactTableTypes) - { - if (auto tt = get(unsealedTableTy); tt && tt->state == TableState::Unsealed) - targetState = TableState::Exact; - } - - sealTable(scope, unsealedTableTy, targetState); + sealTable(scope, unsealedTableTy); } for (const auto& [freePackId, params] : ftwp.typePacks) @@ -1574,14 +1561,7 @@ std::optional generalize( if (generalizationTarget && unsealedTableTy != *generalizationTarget) continue; - TableState targetState = TableState::Sealed; - if (FFlag::DebugLuauExactTableTypes) - { - if (auto tt = get(unsealedTableTy); tt && tt->state == TableState::Unsealed) - targetState = TableState::Exact; - } - - sealTable(scope, unsealedTableTy, targetState); + sealTable(scope, unsealedTableTy); } for (const auto& [freePackId, params] : fts.typePacks) diff --git a/Analysis/src/GlobalTypes.cpp b/Analysis/src/GlobalTypes.cpp index bd25428e5..af347c773 100644 --- a/Analysis/src/GlobalTypes.cpp +++ b/Analysis/src/GlobalTypes.cpp @@ -2,7 +2,6 @@ #include "Luau/GlobalTypes.h" -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) namespace Luau @@ -18,8 +17,6 @@ GlobalTypes::GlobalTypes(NotNull builtinTypes, SolverMode mode) globalScope->addBuiltinTypeBinding("any", TypeFun{{}, builtinTypes->anyType}); globalScope->addBuiltinTypeBinding("nil", TypeFun{{}, builtinTypes->nilType}); globalScope->addBuiltinTypeBinding("number", TypeFun{{}, builtinTypes->numberType}); - if (FFlag::LuauIntegerType2) - globalScope->addBuiltinTypeBinding("integer", TypeFun{{}, builtinTypes->integerType}); globalScope->addBuiltinTypeBinding("string", TypeFun{{}, builtinTypes->stringType}); globalScope->addBuiltinTypeBinding("boolean", TypeFun{{}, builtinTypes->booleanType}); globalScope->addBuiltinTypeBinding("thread", TypeFun{{}, builtinTypes->threadType}); diff --git a/Analysis/src/IostreamHelpers.cpp b/Analysis/src/IostreamHelpers.cpp index 857ff1038..f687b50f9 100644 --- a/Analysis/src/IostreamHelpers.cpp +++ b/Analysis/src/IostreamHelpers.cpp @@ -326,20 +326,6 @@ static void errorToString(std::ostream& stream, const T& err) stream << "UninitializedFieldAccess { " << (err.fieldName ? *err.fieldName : "self") << " }"; else if constexpr (std::is_same_v) stream << "ConstructorsShouldNotReturnAnything {}"; - else if constexpr (std::is_same_v) - { - stream << "CyclicClassInheritance { cycle = ["; - bool first = true; - for (const Name& name : err.cycle) - { - if (first) - first = false; - else - stream << ", "; - stream << name; - } - stream << "] }"; - } else if constexpr (std::is_same_v) stream << "InvalidExtension { ctx = " << err.context << ", ty = " << toString(err.baseClass) << " }"; else if constexpr (std::is_same_v) diff --git a/Analysis/src/Linter.cpp b/Analysis/src/Linter.cpp index a997eb1d9..aa1438d47 100644 --- a/Analysis/src/Linter.cpp +++ b/Analysis/src/Linter.cpp @@ -118,7 +118,6 @@ static bool similar(AstExpr* lhs, AstExpr* rhs) CASE(AstExprConstantNil) return true; CASE(AstExprConstantBool) return le->value == re->value; CASE(AstExprConstantNumber) return le->value == re->value; - CASE(AstExprConstantInteger) return le->value == re->value; CASE(AstExprConstantString) return le->value.size == re->value.size && memcmp(le->value.data, re->value.data, le->value.size) == 0; CASE(AstExprLocal) return le->local == re->local; CASE(AstExprGlobal) return le->name == re->name; @@ -3207,9 +3206,6 @@ class LintIntegerParsing : AstVisitor "Hexadecimal number literal exceeded available precision and was truncated to 2^64" ); break; - case ConstantNumberParseResult::IntOverflow: - emitWarning(*context, LintWarning::Code_IntegerParsing, node->location, "Integer number literal was clamped because it was out of range"); - break; } return true; diff --git a/Analysis/src/Module.cpp b/Analysis/src/Module.cpp index a45ee43ea..782719269 100644 --- a/Analysis/src/Module.cpp +++ b/Analysis/src/Module.cpp @@ -14,7 +14,6 @@ #include -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAGVARIABLE(LuauExportTypecheckTypepacks) LUAU_FASTFLAGVARIABLE(LuauExportAnnotationBinding) LUAU_FASTFLAGVARIABLE(LuauReduceTypeFunctionToSyntheticError) @@ -192,13 +191,7 @@ struct ClonePublicInterface : Substitution if (isNewSolver()) { ttv->scope = nullptr; - if (FFlag::DebugLuauExactTableTypes) - { - if (ttv->state != TableState::Sealed && ttv->state != TableState::Exact) - ttv->state = TableState::Sealed; - } - else - ttv->state = TableState::Sealed; + ttv->state = TableState::Sealed; } } @@ -507,11 +500,13 @@ void synthesizeExportReturn(NotNull builtinTypes, NotNull { if (AstStatClass* classStat = statement->as()) { - if (!classStat->exported) + if (classStat->declModifier != AstStatClass::DeclModifier::Export) continue; - props[classStat->name->name.value] = Property::readonly(lookupExportedBindingType(classStat->name)); - props[classStat->name->name.value].location = classStat->name->location; + Name className = Name{classStat->getName().value}; + + props[className] = Property::readonly(lookupExportedBindingType(classStat->localName)); + props[className].location = classStat->localName->location; } } } @@ -519,8 +514,7 @@ void synthesizeExportReturn(NotNull builtinTypes, NotNull if (props.empty()) return; - const TableState state = FFlag::DebugLuauExactTableTypes ? TableState::Exact : TableState::Sealed; - TableType tbl{props, std::nullopt, moduleScope->level, state}; + TableType tbl{props, std::nullopt, moduleScope->level, TableState::Sealed}; tbl.definitionModuleName = module->name; TypeId exports = module->internalTypes->addType(std::move(tbl)); moduleScope->returnType = module->internalTypes->addTypePack({exports}); diff --git a/Analysis/src/NonStrictTypeChecker.cpp b/Analysis/src/NonStrictTypeChecker.cpp index 519b2793a..d29a7b8dc 100644 --- a/Analysis/src/NonStrictTypeChecker.cpp +++ b/Analysis/src/NonStrictTypeChecker.cpp @@ -563,7 +563,7 @@ struct NonStrictTypeChecker if (std::optional ancestor = propInInheritanceChain(superInstanceEtv, property->name.value)) { reportError( - IllegalClassPropertyOverride{property->name.value, Name{declClass->name->name.value}, *ancestor}, property->nameLocation + IllegalClassPropertyOverride{property->name.value, Name{declClass->getName().value}, *ancestor}, property->nameLocation ); } } @@ -582,7 +582,7 @@ struct NonStrictTypeChecker if (mt->props.count(methodName) != 0) { reportError( - IncompatibleClassMethodOverride{methodName, Name{declClass->name->name.value}, Name{curr->name}}, + IncompatibleClassMethodOverride{methodName, Name{declClass->getName().value}, Name{curr->name}}, method->nameLocation ); break; @@ -598,7 +598,7 @@ struct NonStrictTypeChecker if (!constructorDefined) { if (std::optional ancestor = propInInheritanceChain(superInstanceEtv, "__init")) - reportError(MissingConstructor{Name(declClass->name->name.value), *ancestor}, declClass->location); + reportError(MissingConstructor{Name(declClass->getName().value), *ancestor}, declClass->location); } } @@ -634,8 +634,6 @@ struct NonStrictTypeChecker return visit(e); else if (auto e = expr->as()) return visit(e); - else if (auto e = expr->as()) - return visit(e); else if (auto e = expr->as()) return visit(e); else if (auto e = expr->as()) @@ -695,11 +693,6 @@ struct NonStrictTypeChecker return {}; } - NonStrictContext visit(AstExprConstantInteger* expr) - { - return {}; - } - NonStrictContext visit(AstExprConstantString* expr) { return {}; diff --git a/Analysis/src/Normalize.cpp b/Analysis/src/Normalize.cpp index 984c50873..00393b5fa 100644 --- a/Analysis/src/Normalize.cpp +++ b/Analysis/src/Normalize.cpp @@ -19,8 +19,6 @@ LUAU_FASTFLAGVARIABLE(DebugLuauCheckNormalizeInvariant) LUAU_FASTINTVARIABLE(LuauNormalizeCacheLimit, 100000) LUAU_FASTINTVARIABLE(LuauNormalizerInitialFuel, 3000) -LUAU_FASTFLAG(LuauIntegerType2) -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAGVARIABLE(LuauRefactorStringSemanticSubtyping) LUAU_FASTFLAGVARIABLE(LuauFixNormalizeFunctionIntersections) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) @@ -239,7 +237,6 @@ NormalizedType::NormalizedType(NotNull builtinTypes) , errors(builtinTypes->neverType) , nils(builtinTypes->neverType) , numbers(builtinTypes->neverType) - , integers(builtinTypes->neverType) , strings{NormalizedStringType::never} , threads(builtinTypes->neverType) , buffers(builtinTypes->neverType) @@ -252,17 +249,8 @@ bool NormalizedType::isUnknown() const return true; // Otherwise, we can still be unknown! - bool hasAllPrimitives; - if (FFlag::LuauIntegerType2) - { - hasAllPrimitives = isPrim(booleans, PrimitiveType::Boolean) && isPrim(nils, PrimitiveType::NilType) && isNumber(numbers) && - strings.isString() && isThread(threads) && isBuffer(buffers) && isInteger(integers); - } - else - { - hasAllPrimitives = isPrim(booleans, PrimitiveType::Boolean) && isPrim(nils, PrimitiveType::NilType) && isNumber(numbers) && - strings.isString() && isThread(threads) && isBuffer(buffers); - } + bool hasAllPrimitives = isPrim(booleans, PrimitiveType::Boolean) && isPrim(nils, PrimitiveType::NilType) && isNumber(numbers) && + strings.isString() && isThread(threads) && isBuffer(buffers); // Check is extern type bool isTopExternType = false; @@ -293,42 +281,26 @@ bool NormalizedType::isUnknown() const bool NormalizedType::isExactlyNumber() const { - if (FFlag::LuauIntegerType2) - return hasNumbers() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasStrings() && !hasThreads() && - !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars() && !hasIntegers(); - else - return hasNumbers() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasStrings() && !hasThreads() && - !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars(); + return hasNumbers() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasStrings() && !hasThreads() && + !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars(); } bool NormalizedType::isSubtypeOfString() const { - if (FFlag::LuauIntegerType2) - return hasStrings() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasThreads() && - !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars() && !hasIntegers(); - else - return hasStrings() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasThreads() && - !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars(); + return hasStrings() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasThreads() && + !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars(); } bool NormalizedType::isSubtypeOfBooleans() const { - if (FFlag::LuauIntegerType2) - return hasBooleans() && !hasTops() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasStrings() && !hasThreads() && - !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars() && !hasIntegers(); - else - return hasBooleans() && !hasTops() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasStrings() && !hasThreads() && - !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars(); + return hasBooleans() && !hasTops() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasStrings() && !hasThreads() && + !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars(); } bool NormalizedType::isSubtypeOfTable() const { - if (FFlag::LuauIntegerType2) - return hasTables() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasStrings() - && !hasThreads() && !hasBuffers() && !hasFunctions() && !hasTyvars() && !hasIntegers(); - else - return hasTables() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasStrings() - && !hasThreads() && !hasBuffers() && !hasFunctions() && !hasTyvars(); + return hasTables() && !hasTops() && !hasBooleans() && !hasExternTypes() && !hasErrors() && !hasNils() && !hasNumbers() && !hasStrings() && + !hasThreads() && !hasBuffers() && !hasFunctions() && !hasTyvars(); } bool NormalizedType::shouldSuppressErrors() const @@ -380,14 +352,6 @@ bool NormalizedType::hasNumbers() const return !get(numbers); } -bool NormalizedType::hasIntegers() const -{ - if (FFlag::LuauIntegerType2) - return get(integers) == nullptr; - else - return false; -} - bool NormalizedType::hasStrings() const { return !strings.isNever(); @@ -428,12 +392,8 @@ bool NormalizedType::isFalsy() const hasAFalse = !bs->value; } - if (FFlag::LuauIntegerType2) - return (hasAFalse || hasNils()) && (!hasTops() && !hasExternTypes() && !hasErrors() && !hasNumbers() && !hasStrings() && !hasThreads() && - !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars() && !hasIntegers()); - else - return (hasAFalse || hasNils()) && (!hasTops() && !hasExternTypes() && !hasErrors() && !hasNumbers() && !hasStrings() && !hasThreads() && - !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars()); + return (hasAFalse || hasNils()) && (!hasTops() && !hasExternTypes() && !hasErrors() && !hasNumbers() && !hasStrings() && !hasThreads() && + !hasBuffers() && !hasTables() && !hasFunctions() && !hasTyvars()); } bool NormalizedType::isTruthy() const @@ -446,30 +406,16 @@ bool NormalizedType::isNil() const if (!hasNils()) return false; - if (FFlag::LuauIntegerType2) - return !hasTops() && !hasBooleans() && !hasExternTypes() && !hasNumbers() && !hasStrings() && !hasThreads() && !hasBuffers() && - !hasTables() && !hasFunctions() && !hasTyvars() && !hasIntegers(); - else - return !hasTops() && !hasBooleans() && !hasExternTypes() && !hasNumbers() && !hasStrings() && !hasThreads() && !hasBuffers() && - !hasTables() && !hasFunctions() && !hasTyvars(); + return !hasTops() && !hasBooleans() && !hasExternTypes() && !hasNumbers() && !hasStrings() && !hasThreads() && !hasBuffers() && + !hasTables() && !hasFunctions() && !hasTyvars(); } static bool isShallowInhabited(const NormalizedType& norm) { // This test is just a shallow check, for example it returns `true` for `{ p : never }` - if (FFlag::LuauIntegerType2) - { - return !get(norm.tops) || !get(norm.booleans) || !norm.externTypes.isNever() || !get(norm.errors) || - !get(norm.nils) || !get(norm.numbers) || !norm.strings.isNever() || !get(norm.threads) || - (get(norm.buffers) == nullptr) || !norm.functions.isNever() || !norm.tables.empty() || !norm.tyvars.empty() || - (get(norm.integers) == nullptr); - } - else - { - return !get(norm.tops) || !get(norm.booleans) || !norm.externTypes.isNever() || !get(norm.errors) || - !get(norm.nils) || !get(norm.numbers) || !norm.strings.isNever() || !get(norm.threads) || - !get(norm.buffers) || !norm.functions.isNever() || !norm.tables.empty() || !norm.tyvars.empty(); - } + return !get(norm.tops) || !get(norm.booleans) || !norm.externTypes.isNever() || !get(norm.errors) || + !get(norm.nils) || !get(norm.numbers) || !norm.strings.isNever() || !get(norm.threads) || + !get(norm.buffers) || !norm.functions.isNever() || !norm.tables.empty() || !norm.tyvars.empty(); } NormalizationResult Normalizer::isInhabited(const NormalizedType* norm) @@ -494,20 +440,10 @@ NormalizationResult Normalizer::isInhabited(const NormalizedType* norm, DenseHas consumeFuel(); - if (FFlag::LuauIntegerType2) - { - if (!get(norm->tops) || !get(norm->booleans) || !get(norm->errors) || !get(norm->nils) || - !get(norm->numbers) || !get(norm->threads) || !get(norm->buffers) || !norm->externTypes.isNever() || - !get(norm->integers) || !norm->strings.isNever() || !norm->functions.isNever()) - return NormalizationResult::True; - } - else - { - if (!get(norm->tops) || !get(norm->booleans) || !get(norm->errors) || !get(norm->nils) || - !get(norm->numbers) || !get(norm->threads) || !get(norm->buffers) || !norm->externTypes.isNever() || - !norm->strings.isNever() || !norm->functions.isNever()) - return NormalizationResult::True; - } + if (!get(norm->tops) || !get(norm->booleans) || !get(norm->errors) || !get(norm->nils) || + !get(norm->numbers) || !get(norm->threads) || !get(norm->buffers) || !norm->externTypes.isNever() || + !norm->strings.isNever() || !norm->functions.isNever()) + return NormalizationResult::True; for (const auto& [_, intersect] : norm->tyvars) { @@ -746,16 +682,6 @@ static bool isNormalizedNumber(TypeId ty) return false; } -static bool isNormalizedInteger(TypeId ty) -{ - if (get(ty)) - return true; - else if (const PrimitiveType* ptv = get(ty)) - return ptv->type == PrimitiveType::Integer; - else - return false; -} - static bool isNormalizedString(const NormalizedStringType& ty) { if (ty.isString()) @@ -919,8 +845,6 @@ static void assertInvariant(const NormalizedType& norm) LUAU_ASSERT(isNormalizedError(norm.errors)); LUAU_ASSERT(isNormalizedNil(norm.nils)); LUAU_ASSERT(isNormalizedNumber(norm.numbers)); - if (FFlag::LuauIntegerType2) - LUAU_ASSERT(isNormalizedInteger(norm.integers)); LUAU_ASSERT(isNormalizedString(norm.strings)); LUAU_ASSERT(isNormalizedThread(norm.threads)); LUAU_ASSERT(isNormalizedBuffer(norm.buffers)); @@ -1081,7 +1005,6 @@ void Normalizer::clearNormal(NormalizedType& norm) norm.errors = builtinTypes->neverType; norm.nils = builtinTypes->neverType; norm.numbers = builtinTypes->neverType; - norm.integers = builtinTypes->neverType; norm.strings.resetToNever(); norm.threads = builtinTypes->neverType; norm.buffers = builtinTypes->neverType; @@ -1813,8 +1736,6 @@ NormalizationResult Normalizer::unionNormals(NormalizedType& here, const Normali here.errors = (get(there.errors) ? here.errors : there.errors); here.nils = (get(there.nils) ? here.nils : there.nils); here.numbers = (get(there.numbers) ? here.numbers : there.numbers); - if (FFlag::LuauIntegerType2) - here.integers = (get(there.integers) ? here.integers : there.integers); unionStrings(here.strings, there.strings); here.threads = (get(there.threads) ? here.threads : there.threads); here.buffers = (get(there.buffers) ? here.buffers : there.buffers); @@ -1994,8 +1915,6 @@ NormalizationResult Normalizer::unionNormalWithTy( here.nils = there; else if (ptv->type == PrimitiveType::Number) here.numbers = there; - else if (FFlag::LuauIntegerType2 && (ptv->type == PrimitiveType::Integer)) - here.integers = there; else if (ptv->type == PrimitiveType::String) here.strings.resetToString(); else if (ptv->type == PrimitiveType::Thread) @@ -2131,8 +2050,6 @@ std::optional Normalizer::negateNormal(const NormalizedType& her result.nils = get(here.nils) ? builtinTypes->nilType : builtinTypes->neverType; result.numbers = get(here.numbers) ? builtinTypes->numberType : builtinTypes->neverType; - if (FFlag::LuauIntegerType2) - result.integers = get(here.integers) ? builtinTypes->integerType : builtinTypes->neverType; result.strings = here.strings; result.strings.isCofinite = !result.strings.isCofinite; @@ -2228,9 +2145,6 @@ void Normalizer::subtractPrimitive(NormalizedType& here, TypeId ty) case PrimitiveType::Number: here.numbers = builtinTypes->neverType; break; - case PrimitiveType::Integer: - here.integers = builtinTypes->neverType; - break; case PrimitiveType::String: here.strings.resetToNever(); break; @@ -2822,382 +2736,6 @@ std::optional Normalizer::intersectionOfTables( SeenTablePropPairs& seenTablePropPairs, DenseHashSet& seenSet ) -{ - if (!FFlag::DebugLuauExactTableTypes) - return DEPRECATED_intersectionOfTables(here, there, seenTablePropPairs, seenSet); - - consumeFuel(); - - if (here == there) - return here; - - RecursionCounter _rc(&sharedState->counters.recursionCount); - if (sharedState->counters.recursionLimit > 0 && sharedState->counters.recursionLimit < sharedState->counters.recursionCount) - return std::nullopt; - - if (isPrim(here, PrimitiveType::Table)) - return there; - else if (isPrim(there, PrimitiveType::Table)) - return here; - - if (get(here)) - return there; - else if (get(there)) - return here; - else if (get(here)) - return there; - else if (get(there)) - return here; - - TypeId htable = here; - TypeId hmtable = nullptr; - if (const MetatableType* hmtv = get(here)) - { - htable = follow(hmtv->table); - hmtable = follow(hmtv->metatable); - } - TypeId ttable = there; - TypeId tmtable = nullptr; - if (const MetatableType* tmtv = get(there)) - { - ttable = follow(tmtv->table); - tmtable = follow(tmtv->metatable); - } - - const TableType* httv = get(htable); - if (!httv) - return std::nullopt; - - const TableType* tttv = get(ttable); - if (!tttv) - return std::nullopt; - - if (httv->state == TableState::Free || tttv->state == TableState::Free) - return std::nullopt; - if (httv->state == TableState::Generic || tttv->state == TableState::Generic) - return std::nullopt; - - const bool hereExact = httv->state == TableState::Exact; - const bool thereExact = tttv->state == TableState::Exact; - - TableState state = httv->state; - if (tttv->state == TableState::Unsealed) - state = tttv->state; - - // If either table is exact, the result is either an exact table or never. - if (hereExact || thereExact) - state = TableState::Exact; - - TypeLevel level = max(httv->level, tttv->level); - Scope* scope = max(httv->scope, tttv->scope); - - std::unique_ptr result = std::make_unique(state, level, scope); - - bool hereSubThere = true; - bool thereSubHere = true; - - // An inexact table is never a subtype of an exact table. - if (hereExact && !thereExact) - thereSubHere = false; - if (thereExact && !hereExact) - hereSubThere = false; - - // Handle props that are common between the two tables - for (const auto& [name, hprop] : httv->props) - { - auto it = tttv->props.find(name); - if (it == tttv->props.end()) - continue; - - const Property& tprop = it->second; - Property prop = hprop; - - if (hprop.readTy.has_value() && tprop.readTy.has_value()) - { - TypeId ty = simplifyIntersection(builtinTypes, NotNull{arena}, *hprop.readTy, *tprop.readTy).result; - - // If any property is going to get mapped to `never`, we can just call the entire table `never`. - // Since this check is syntactic, we may sometimes miss simplifying tables with complex uninhabited properties. - // Prior versions of this code attempted to do this semantically using the normalization machinery, but this - // mistakenly causes infinite loops when giving more complex recursive table types. As it stands, this approach - // will continue to scale as simplification is improved, but we may wish to reintroduce the semantic approach - // once we have revisited the usage of seen sets systematically (and possibly with some additional guarding to recognize - // when types are infinitely-recursive with non-pointer identical instances of them, or some guard to prevent that - // construction altogether). See also: `gh1632_no_infinite_recursion_in_normalization` - if (get(ty)) - return {builtinTypes->neverType}; - - prop.readTy = ty; - hereSubThere &= (ty == hprop.readTy); - thereSubHere &= (ty == tprop.readTy); - } - else if (hprop.readTy.has_value()) - { - prop.readTy = hprop.readTy; - thereSubHere = false; - } - else if (tprop.readTy.has_value()) - { - prop.readTy = tprop.readTy; - hereSubThere = false; - } - - if (hprop.writeTy.has_value() && tprop.writeTy.has_value()) - { - prop.writeTy = simplifyIntersection(builtinTypes, NotNull{arena}, *hprop.writeTy, *tprop.writeTy).result; - hereSubThere &= (prop.writeTy == hprop.writeTy); - thereSubHere &= (prop.writeTy == tprop.writeTy); - } - else if (hprop.writeTy.has_value()) - { - prop.writeTy = hprop.writeTy; - thereSubHere = false; - } - else if (tprop.writeTy.has_value()) - { - prop.writeTy = tprop.writeTy; - hereSubThere = false; - } - - LUAU_ASSERT(prop.readTy.has_value() || prop.writeTy.has_value()); - result->props[name] = prop; - } - - // When considering props that have no corresponding property on the other - // side, there are 3 situations to consider: - // - // * If the opposite table has a string indexer that intersects with the - // prop, the intersection is inhabited. - // * If the opposite table does not have a covering indexer and is exact, - // the intersection is uninhabited. - // * If both tables are inexact, the intersection is inhabited per width - // subtyping. - - const bool hereHasStringIndexer = hasStringIndexer(httv); - const bool thereHasStringIndexer = hasStringIndexer(tttv); - - enum class HandleResult - { - Uninhabited, - Ok - }; - - // Reconcile a prop in the left-side table that has no corresponding named prop in the right-side table. - // Returns CombineResult::Uninhabited if the indexer is incompatible or if the right side table is exact. - // Adds the prop to result->props otherwise. - auto handleUnmatchedProp = [&](bool leftExact, - bool rightExact, - bool rightHasStringIndexer, - const std::string& name, - const Property& leftProp, - const std::optional& rightIndexer) - { - if (rightHasStringIndexer) - { - TypeId indexResultType = result->indexer ? result->indexer->indexResultType : rightIndexer->indexResultType; - - if (leftProp.readTy) - { - if (NormalizationResult::True != isIntersectionInhabited(indexResultType, *leftProp.readTy)) - return HandleResult::Uninhabited; - - if (leftExact) - result->props[name].readTy = leftProp.readTy; - } - - const bool indexerIsReadOnly = rightIndexer && rightIndexer->isReadOnly; - if (leftProp.writeTy && indexerIsReadOnly) - result->props[name].writeTy = leftProp.writeTy; - - else if (leftProp.writeTy) - { - if (NormalizationResult::True != isIntersectionInhabited(indexResultType, *leftProp.writeTy)) - return HandleResult::Uninhabited; - - if (leftExact) - result->props[name].writeTy = leftProp.writeTy; - } - } - else if (rightExact) - return HandleResult::Uninhabited; - else - result->props[name] = leftProp; - - return HandleResult::Ok; - }; - - // Props only in `here` - for (const auto& [name, hprop] : httv->props) - { - if (0 != tttv->props.count(name)) - continue; - - thereSubHere = false; - - if (HandleResult::Uninhabited == handleUnmatchedProp(hereExact, thereExact, thereHasStringIndexer, name, hprop, tttv->indexer)) - return builtinTypes->neverType; - } - - // Props only in `there` - for (const auto& [name, tprop] : tttv->props) - { - if (0 != httv->props.count(name)) - continue; - - hereSubThere = false; - - if (HandleResult::Uninhabited == handleUnmatchedProp(thereExact, hereExact, hereHasStringIndexer, name, tprop, httv->indexer)) - return builtinTypes->neverType; - } - - // Lastly, the tails themselves. - - // Indexer? | Exact? | Outcome - // - // N/N | */* | OK. - // Y/Y | */* | If both indexers are writable, they must be coincident, else the table must be empty. If either is read-only, intersect. - // - // Y/N | Y/Y | Uninhabited - // Y/N | N/Y | The indexer may constrain the exact props, but do not copy it over. - // Y/N | Y/N | Copy the indexer into the result. - // Y/N | N/N | Copy the indexer into the result. - // - // N/Y | Y/Y | Uninhabited - // N/Y | Y/N | The indexer may constrain the exact props, but do not copy it over. - // N/Y | N/Y | Copy the indexer into the result. - // N/Y | N/N | Copy the indexer into the result. - - // * If neither table has an indexer, the intersection is inhabited. - // * If both tables have indexers and either is exact, the indexers must - // be coincident. - // * If both tables have indexers and neither is exact, we combine the - // indexers: Union the key type and intersect the value type. - // * If one table is exact and has no indexer and the other table has an - // indexer, the intersection is uninhabited. - // * If one table has an indexer and the other is inexact and lacks an - // indexer, the result is inhabited and has the indexer. - - // Compare the tails themselves - if (httv->indexer.has_value() && tttv->indexer.has_value()) - { - auto indexersCollide = [&]() - { - result->indexer.reset(); - result->state = TableState::Exact; - - hereSubThere = false; - thereSubHere = false; - }; - - if (httv->indexer->isReadOnly && !tttv->indexer->isReadOnly) - hereSubThere = false; - if (!httv->indexer->isReadOnly && tttv->indexer->isReadOnly) - thereSubHere = false; - - if (httv->indexer->isReadOnly || tttv->indexer->isReadOnly) - { - TypeId indexType = simplifyIntersection(builtinTypes, NotNull{arena}, httv->indexer->indexType, tttv->indexer->indexType).result; - TypeId indexResultType = - simplifyIntersection(builtinTypes, NotNull{arena}, httv->indexer->indexResultType, tttv->indexer->indexResultType).result; - if (is(indexType) || is(indexResultType)) - { - indexersCollide(); - } - else - { - if (indexType != httv->indexer->indexType || indexResultType != httv->indexer->indexResultType) - hereSubThere = false; - if (indexType != tttv->indexer->indexType || indexResultType != tttv->indexer->indexResultType) - thereSubHere = false; - - const bool isReadOnly = httv->indexer->isReadOnly && tttv->indexer->isReadOnly; - result->indexer.emplace(indexType, indexResultType, isReadOnly); - } - } - else - { - if ((Relation::Coincident != relate(httv->indexer->indexType, tttv->indexer->indexType)) || - (Relation::Coincident != relate(httv->indexer->indexResultType, tttv->indexer->indexResultType))) - { - indexersCollide(); - } - else - { - result->indexer.emplace(*httv->indexer); - } - } - } - else if (hereExact && tttv->indexer.has_value()) - hereSubThere = false; - else if (thereExact && httv->indexer.has_value()) - thereSubHere = false; - else if (tttv->indexer.has_value()) - { - result->indexer = tttv->indexer; - hereSubThere = false; - } - else if (httv->indexer.has_value()) - { - result->indexer = httv->indexer; - hereSubThere = false; - } - else if (!httv->indexer.has_value() && !tttv->indexer.has_value()) - { - // Everything is OK! - } - else - { - // All permutations should be handled above. - LUAU_ASSERT(!"Should be unreachable!"); - } - - TypeId table; - if (hereSubThere) - table = htable; - else if (thereSubHere) - table = ttable; - else - table = arena->addType(std::move(*result)); - - if (tmtable && hmtable) - { - // NOTE: this assumes metatables are invariant - if (std::optional mtable = intersectionOfTables(hmtable, tmtable, seenTablePropPairs, seenSet)) - { - if (table == htable && *mtable == hmtable) - return here; - else if (table == ttable && *mtable == tmtable) - return there; - else - return arena->addType(MetatableType{table, *mtable}); - } - else - return std::nullopt; - } - else if (hmtable) - { - if (table == htable) - return here; - else - return arena->addType(MetatableType{table, hmtable}); - } - else if (tmtable) - { - if (table == ttable) - return there; - else - return arena->addType(MetatableType{table, tmtable}); - } - else - return table; -} - -std::optional Normalizer::DEPRECATED_intersectionOfTables( - TypeId here, - TypeId there, - SeenTablePropPairs& seenTablePropPairs, - DenseHashSet& seenSet -) { consumeFuel(); @@ -3759,8 +3297,6 @@ NormalizationResult Normalizer::intersectNormals(NormalizedType& here, const Nor here.errors = (get(there.errors) ? there.errors : here.errors); here.nils = (get(there.nils) ? there.nils : here.nils); here.numbers = (get(there.numbers) ? there.numbers : here.numbers); - if (FFlag::LuauIntegerType2) - here.integers = (get(there.integers) ? there.integers : here.integers); intersectStrings(here.strings, there.strings); here.threads = (get(there.threads) ? there.threads : here.threads); here.buffers = (get(there.buffers) ? there.buffers : here.buffers); @@ -3945,7 +3481,6 @@ NormalizationResult Normalizer::intersectNormalWithTy( TypeId booleans = here.booleans; TypeId nils = here.nils; TypeId numbers = here.numbers; - TypeId integers = here.integers; NormalizedStringType strings = std::move(here.strings); NormalizedFunctionType functions = std::move(here.functions); TypeId threads = here.threads; @@ -3960,8 +3495,6 @@ NormalizationResult Normalizer::intersectNormalWithTy( here.nils = nils; else if (ptv->type == PrimitiveType::Number) here.numbers = numbers; - else if (FFlag::LuauIntegerType2 && (ptv->type == PrimitiveType::Integer)) - here.integers = integers; else if (ptv->type == PrimitiveType::String) here.strings = std::move(strings); else if (ptv->type == PrimitiveType::Thread) @@ -4205,11 +3738,6 @@ TypeId Normalizer::typeFromNormal(const NormalizedType& norm) result.push_back(norm.nils); if (!get(norm.numbers)) result.push_back(norm.numbers); - if (FFlag::LuauIntegerType2) - { - if (get(norm.integers) == nullptr) - result.push_back(norm.integers); - } if (norm.strings.isString()) result.push_back(builtinTypes->stringType); else if (norm.strings.isUnion()) diff --git a/Analysis/src/OverloadResolver.cpp b/Analysis/src/OverloadResolver.cpp index cb5f01ed6..e0dd657ef 100644 --- a/Analysis/src/OverloadResolver.cpp +++ b/Analysis/src/OverloadResolver.cpp @@ -12,7 +12,6 @@ #include "Luau/TypeUtils.h" #include "Luau/Unifier2.h" -LUAU_FASTFLAG(LuauFixCallMetamethodErrorReporting) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) @@ -374,7 +373,7 @@ void OverloadResolver::reportErrors( // A variadic parameter has no index of its own, so the subPath stops at the tail. The // argument that failed against it is the one the superPath names. - if (FFlag::LuauFixCallMetamethodErrorReporting && !argumentIndex) + if (!argumentIndex) { const TypeId given = arena->addType(FunctionType{argPack, builtinTypes->anyTypePack}); argumentIndex = getArgumentIndex(reason.superPath, given); diff --git a/Analysis/src/Simplify.cpp b/Analysis/src/Simplify.cpp index 0f51c8977..527792ecb 100644 --- a/Analysis/src/Simplify.cpp +++ b/Analysis/src/Simplify.cpp @@ -15,7 +15,6 @@ #include -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_DYNAMIC_FASTINTVARIABLE(LuauSimplificationComplexityLimit, 8) LUAU_DYNAMIC_FASTINTVARIABLE(LuauTypeSimplificationIterationLimit, 128) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) @@ -280,13 +279,6 @@ Relation relateTableToProp(const TableType* leftTable, const std::string& propNa } } - // Two read-only properties are covariant, so their table relation is the - // relation of their read types in either direction. The more general - // logic below deliberately treats a wider left read type conservatively: - // that is necessary when the left property is writable, but not here. - if (FFlag::DebugLuauExactTableTypes && leftProp->second.isReadOnly() && rightProp.isReadOnly()) - return relate(*leftProp->second.readTy, *rightProp.readTy, seen); - // Otherwise we want to hard match on the case of: // // { ..., x: T } & { read x: U } @@ -336,7 +328,7 @@ Relation relateTableToProp(const TableType* leftTable, const std::string& propNa } } -Relation relateTables_DEPRECATED(const TableType* leftTable, const TableType* rightTable, SimplifierSeenSet& seen) +Relation relateTables(const TableType* leftTable, const TableType* rightTable, SimplifierSeenSet& seen) { // FIXME CLI-189216: As noted in the body this is not complete. if (leftTable->state != TableState::Sealed || rightTable->state != TableState::Sealed) @@ -412,138 +404,6 @@ Relation relateTables_DEPRECATED(const TableType* leftTable, const TableType* ri return hasSubset ? Relation::Subset : Relation::Coincident; } -Relation relateTables(const TableType* leftTable, const TableType* rightTable, SimplifierSeenSet& seen) -{ - if (!FFlag::DebugLuauExactTableTypes) - return relateTables_DEPRECATED(leftTable, rightTable, seen); - - if (!(leftTable->state == TableState::Sealed || leftTable->state == TableState::Exact) || - !(rightTable->state == TableState::Sealed || rightTable->state == TableState::Exact)) - { - return Relation::Intersects; - } - - // Think of a table as a row of required fields plus an open (sealed) or - // closed (exact) tail. Track the three facts needed to classify the - // relationship rather than using the number of named fields as a proxy - // for the row relationship. - bool inhabited = true; - bool leftSubsetRight = true; - bool rightSubsetLeft = true; - - auto incorporate = [&inhabited, &leftSubsetRight, &rightSubsetLeft](Relation relation) - { - switch (relation) - { - case Relation::Disjoint: - inhabited = false; - break; - case Relation::Subset: - rightSubsetLeft = false; - break; - case Relation::Superset: - leftSubsetRight = false; - break; - case Relation::Intersects: - leftSubsetRight = false; - rightSubsetLeft = false; - break; - case Relation::Coincident: - break; - } - }; - - // Compare fields common to both rows. relateTableToProp contains the - // property read/write variance rules, so it is also the appropriate - // relation to fold into the table relation. - for (const auto& [name, rightProp] : rightTable->props) - { - if (leftTable->props.count(name) != 0) - incorporate(relateTableToProp(leftTable, name, rightProp, seen)); - } - - // A field required by one row but absent from the other closes the - // intersection only when the other row is exact. An indexer may cover a - // named field, but determining that precisely needs a singleton key type; - // keep that case conservative instead of declaring the tables disjoint. - for (const auto& [name, leftProp] : leftTable->props) - { - if (rightTable->props.count(name) != 0) - continue; - - if (rightTable->indexer) - { - leftSubsetRight = false; - rightSubsetLeft = false; - } - else if (rightTable->state == TableState::Exact) - return Relation::Disjoint; - else - rightSubsetLeft = false; - } - - for (const auto& [name, rightProp] : rightTable->props) - { - if (leftTable->props.count(name) != 0) - continue; - - if (leftTable->indexer) - { - leftSubsetRight = false; - rightSubsetLeft = false; - } - else if (leftTable->state == TableState::Exact) - return Relation::Disjoint; - else - leftSubsetRight = false; - } - - if (leftTable->indexer && rightTable->indexer) - { - // Index key types are invariant. Index result types are invariant - // unless both indexers are read-only, in which case their usual - // covariant relation is useful here. - if (relate(leftTable->indexer->indexType, rightTable->indexer->indexType, seen) != Relation::Coincident) - { - leftSubsetRight = false; - rightSubsetLeft = false; - } - - if (leftTable->indexer->isReadOnly && rightTable->indexer->isReadOnly) - incorporate(relate(leftTable->indexer->indexResultType, rightTable->indexer->indexResultType, seen)); - else if (relate(leftTable->indexer->indexResultType, rightTable->indexer->indexResultType, seen) != Relation::Coincident) - { - leftSubsetRight = false; - rightSubsetLeft = false; - } - } - else if (leftTable->indexer || rightTable->indexer) - { - // The row without an indexer does not establish the other indexer's - // contract. The intersection can still be inhabited, so this is not - // a disjointness conclusion. - leftSubsetRight = false; - rightSubsetLeft = false; - } - - // Sealed rows have an open tail, and therefore are never contained in an - // exact row. The converse is allowed after the field checks above. - if (leftTable->state == TableState::Sealed && rightTable->state == TableState::Exact) - leftSubsetRight = false; - if (rightTable->state == TableState::Sealed && leftTable->state == TableState::Exact) - rightSubsetLeft = false; - - if (!inhabited) - return Relation::Disjoint; - if (leftSubsetRight && rightSubsetLeft) - return Relation::Coincident; - if (leftSubsetRight) - return Relation::Subset; - if (rightSubsetLeft) - return Relation::Superset; - return Relation::Intersects; -} - // A cheap and approximate subtype test Relation relate(TypeId left, TypeId right, SimplifierSeenSet& seen) { @@ -1417,35 +1277,6 @@ TypeId TypeSimplifier::intersectIntersectionWithType(TypeId left, TypeId right) return intersectFromParts(std::move(newParts)); } -/* If at most one table has an indexer and if the property sets of the two - * tables do not coincide, return a fresh table that combines the two. - */ -static std::optional combineDisjointTables(const TableType* left, const TableType* right) -{ - if (left->state != TableState::Sealed || right->state != TableState::Sealed) - return std::nullopt; - if (left->indexer.has_value() && right->indexer.has_value()) - return std::nullopt; - - TableType res; - res.state = TableState::Sealed; - res.props = left->props; - - for (const auto& [name, prop] : right->props) - { - if (res.props.count(name) != 0) - return std::nullopt; - - res.props.emplace(name, prop); - } - - res.indexer = left->indexer; - if (right->indexer) - res.indexer = right->indexer; - - return res; -} - std::optional TypeSimplifier::basicIntersect(TypeId left, TypeId right) { left = follow(left); @@ -1501,7 +1332,7 @@ std::optional TypeSimplifier::basicIntersect(TypeId left, TypeId right) if (const auto [lt, rt] = get2(left, right); lt && rt) { - if (1 == lt->props.size() && (!FFlag::DebugLuauExactTableTypes || lt->state == TableState::Sealed)) + if (1 == lt->props.size() && lt->state == TableState::Sealed) { const auto [propName, leftProp] = *begin(lt->props); const bool leftPropIsRefinable = leftProp.isShared() || leftProp.isReadOnly(); @@ -1525,7 +1356,7 @@ std::optional TypeSimplifier::basicIntersect(TypeId left, TypeId right) // Then L & R == L // // This also holds if L is exact. - const bool rightIsSimple = 1 == rt->props.size() && (!FFlag::DebugLuauExactTableTypes || !rt->indexer.has_value()); + const bool rightIsSimple = 1 == rt->props.size() && !rt->indexer.has_value(); if (rightIsSimple && leftProp.isShared()) return left; break; @@ -1535,16 +1366,11 @@ std::optional TypeSimplifier::basicIntersect(TypeId left, TypeId right) } } } - else if (1 == rt->props.size() && (!FFlag::DebugLuauExactTableTypes || rt->state == TableState::Sealed)) + else if (1 == rt->props.size() && rt->state == TableState::Sealed) return basicIntersect(right, left); // If two tables have disjoint properties and indexers, we can combine them. - if (FFlag::DebugLuauExactTableTypes) - { - if (auto tbl = combineDisjointTables(lt, rt)) - return arena->addType(std::move(*tbl)); - } - else if (!lt->indexer && !rt->indexer && lt->state == TableState::Sealed && rt->state == TableState::Sealed) + if (!lt->indexer && !rt->indexer && lt->state == TableState::Sealed && rt->state == TableState::Sealed) { if (rt->props.empty()) return left; @@ -1571,8 +1397,7 @@ std::optional TypeSimplifier::basicIntersect(TypeId left, TypeId right) } } - if (!FFlag::DebugLuauExactTableTypes) - return std::nullopt; + return std::nullopt; } if (isApproximatelyTruthyType(left)) diff --git a/Analysis/src/Subtyping.cpp b/Analysis/src/Subtyping.cpp index 597ab467d..19855d33f 100644 --- a/Analysis/src/Subtyping.cpp +++ b/Analysis/src/Subtyping.cpp @@ -25,10 +25,10 @@ LUAU_FASTINTVARIABLE(LuauSubtypingReasoningLimit, 100) LUAU_FASTINTVARIABLE(LuauSubtypingIterationLimit, 20000) LUAU_FASTFLAGVARIABLE(LuauImproveUniqueTableWidthSubtyping) LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAGVARIABLE(LuauSubtypingSkipUnreadReasoning) LUAU_FASTFLAGVARIABLE(LuauOnlyCheckWidthSubtypingForReadOnlyProperty) LUAU_FASTFLAGVARIABLE(LuauOneBitAssumedConstraintTracking) +LUAU_FASTFLAGVARIABLE(LuauErrorSuppressionForIndexers) namespace Luau @@ -1004,9 +1004,7 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, TypeId sub else if (auto p = get2(subTy, superTy)) { result = isCovariantWith(env, p.first, p.second, scope); - bool tableIsMutable = p.first->state != TableState::Sealed; - if (FFlag::DebugLuauExactTableTypes && p.first->state == TableState::Exact) - tableIsMutable = false; + const bool tableIsMutable = p.first->state != TableState::Sealed; if (result.isSubtype && !p.first->indexer && p.second->indexer && tableIsMutable) { @@ -2086,18 +2084,6 @@ SubtypingResult Subtyping::isCovariantWith( return {false}; } - if (FFlag::DebugLuauExactTableTypes) - { - // Sealed state == TableState::Exact && subTable->state != TableState::Exact) - { - return {false}; - } - } - // This is an unfortunately complicated state machine. Consider something like: // // local function launderone(t: { propone: string }): { propone: any } @@ -2211,23 +2197,6 @@ SubtypingResult Subtyping::isCovariantWith( } } - if (FFlag::DebugLuauExactTableTypes && superTable->state == TableState::Exact) - { - // We have already handled the inexact state == TableState::Exact); - - if (subTable->indexer.has_value() != superTable->indexer.has_value()) - return {false}; - - for (const auto& [name, subProp] : subTable->props) - { - // If the supertype table is exact, then every subtype table - // property must map to the supertype somewhere. - if (0 == superTable->props.count(name)) - return {false}; - } - } - if (superTable->indexer) { if (subTable->indexer) @@ -2235,10 +2204,15 @@ SubtypingResult Subtyping::isCovariantWith( // We say covariant here, but the implementation of // isCovariantWith() properly handles variance of the index // result type. - record(isCovariantWith(env, *subTable->indexer, *superTable->indexer, scope)); + if (FFlag::LuauErrorSuppressionForIndexers) + { + record(isCovariantWith(env, *subTable->indexer, *superTable->indexer, scope)); + } + else + { + record(isCovariantWith_DEPRECATED(env, *subTable->indexer, *superTable->indexer, scope)); + } } - else if (subTable->state == TableState::Exact) - return {false}; else if (subTable->state != TableState::Sealed) { // As above, we assume that {| |} <: {T} because the unsealed table @@ -2413,7 +2387,14 @@ SubtypingResult Subtyping::isCovariantWith( { // NOTE: despite the name, this will internally check that the two // indexers are invariant with one another. - result.andAlso(isCovariantWith(env, *subExternType->indexer, *superTable->indexer, scope)); + if (FFlag::LuauErrorSuppressionForIndexers) + { + result.andAlso(isCovariantWith(env, *subExternType->indexer, *superTable->indexer, scope)); + } + else + { + result.andAlso(isCovariantWith_DEPRECATED(env, *subExternType->indexer, *superTable->indexer, scope)); + } } else if (superTable->indexer && !subExternType->indexer) { @@ -2593,11 +2574,7 @@ SubtypingResult Subtyping::isCovariantWith(SubtypingEnvironment& env, const Prim } else if (subPrim->type == PrimitiveType::Table) { - bool isSubtype = superTable->props.empty() && (!superTable->indexer.has_value() || superTable->state == TableState::Generic); - - if (FFlag::DebugLuauExactTableTypes && superTable->state == TableState::Exact) - isSubtype = false; - + const bool isSubtype = superTable->props.empty() && (!superTable->indexer.has_value() || superTable->state == TableState::Generic); return {isSubtype}; } @@ -2641,6 +2618,49 @@ SubtypingResult Subtyping::isCovariantWith( const TableIndexer& superIndexer, NotNull scope ) +{ + if (subIndexer.isReadOnly && !superIndexer.isReadOnly) + { + return SubtypingResult{false} + .withBothComponent(TypePath::TypeField::IndexResult) + .withPropertyModifierViolation(); + } + + bool hasErrorSuppression = false; + bool shouldSuppressErrors = true; + + SubtypingResult result{true}; + + auto record = [&](SubtypingResult subResult) + { + hasErrorSuppression |= subResult.isErrorSuppressing; + shouldSuppressErrors &= subResult.isSubtype || subResult.isErrorSuppressing; + result.andAlso(std::move(subResult)); + }; + + record(isInvariantWith(env, subIndexer.indexType, superIndexer.indexType, scope).withBothComponent(TypePath::TypeField::IndexLookup)); + + // Value-type variance: read-only super → covariant; read-write super → invariant. + if (superIndexer.isReadOnly) + record( + isCovariantWith(env, subIndexer.indexResultType, superIndexer.indexResultType, scope).withBothComponent(TypePath::TypeField::IndexResult) + ); + else + record( + isInvariantWith(env, subIndexer.indexResultType, superIndexer.indexResultType, scope).withBothComponent(TypePath::TypeField::IndexResult) + ); + + result.isErrorSuppressing = hasErrorSuppression && shouldSuppressErrors; + + return result; +} + +SubtypingResult Subtyping::isCovariantWith_DEPRECATED( + SubtypingEnvironment& env, + const TableIndexer& subIndexer, + const TableIndexer& superIndexer, + NotNull scope +) { SubtypingResult result{false}; if (subIndexer.isReadOnly && !superIndexer.isReadOnly) diff --git a/Analysis/src/ToString.cpp b/Analysis/src/ToString.cpp index bbf243753..9a67d6776 100644 --- a/Analysis/src/ToString.cpp +++ b/Analysis/src/ToString.cpp @@ -17,9 +17,7 @@ #include #include -LUAU_FASTFLAG(LuauIntegerType2) -LUAU_FASTFLAG(DebugLuauParseExactTables) -LUAU_FASTFLAG(DebugLuauExactTableTypes) + LUAU_FASTFLAGVARIABLE(LuauBetterInferredGenericNames) /* @@ -656,13 +654,6 @@ struct TypeStringifier case PrimitiveType::Table: state.emit("table"); return; - case PrimitiveType::Integer: - if (FFlag::LuauIntegerType2) - { - state.emit("integer"); - return; - } - [[fallthrough]]; default: LUAU_ASSERT(!"Unknown primitive type"); throw InternalCompilerError("Unknown primitive type " + std::to_string(ptv.type)); @@ -829,10 +820,6 @@ struct TypeStringifier openbrace = "{+"; closedbrace = "+}"; break; - case TableState::Exact: - openbrace = "{"; - closedbrace = "}"; - break; } // If this appears to be an array, we want to stringify it using the {T} syntax. @@ -843,8 +830,6 @@ struct TypeStringifier state.emit("read "); stringify(ttv.indexer->indexResultType); - if (FFlag::DebugLuauExactTableTypes && ttv.state == TableState::Sealed) - state.emit(", ..."); state.emit("}"); state.unsee(&ttv); @@ -895,36 +880,11 @@ struct TypeStringifier ++index; } - if (FFlag::DebugLuauParseExactTables && FFlag::DebugLuauExactTableTypes) - { - if (ttv.state == TableState::Sealed) - { - if (comma) - { - state.emit(","); - state.newline(); - } - else - state.emit(" "); - state.emit("..."); - } - } - state.dedent(); - if (FFlag::DebugLuauParseExactTables && FFlag::DebugLuauExactTableTypes) - { - if (comma) - state.newline(); - else - state.emit(" "); - } + if (comma) + state.newline(); else - { - if (comma) - state.newline(); - else - state.emit(" "); - } + state.emit(" "); state.emit(closedbrace); state.unsee(&ttv); diff --git a/Analysis/src/Type.cpp b/Analysis/src/Type.cpp index b8ee2f940..d3a6eedbf 100644 --- a/Analysis/src/Type.cpp +++ b/Analysis/src/Type.cpp @@ -190,11 +190,6 @@ bool isNumber(TypeId ty) return isPrim(ty, PrimitiveType::Number); } -bool isInteger(TypeId ty) -{ - return isPrim(ty, PrimitiveType::Integer); -} - // Returns true when ty is a subtype of string bool isString(TypeId ty) { @@ -846,7 +841,6 @@ BuiltinTypes::BuiltinTypes() , typeFunctions(std::make_unique()) , nilType(arena->addType(Type{PrimitiveType{PrimitiveType::NilType}, /*persistent*/ true})) , numberType(arena->addType(Type{PrimitiveType{PrimitiveType::Number}, /*persistent*/ true})) - , integerType(arena->addType(Type{PrimitiveType{PrimitiveType::Integer}, /*persistent*/ true})) , stringType(arena->addType(Type{PrimitiveType{PrimitiveType::String}, /*persistent*/ true})) , booleanType(arena->addType(Type{PrimitiveType{PrimitiveType::Boolean}, /*persistent*/ true})) , threadType(arena->addType(Type{PrimitiveType{PrimitiveType::Thread}, /*persistent*/ true})) diff --git a/Analysis/src/TypeAttach.cpp b/Analysis/src/TypeAttach.cpp index bd9c3e59e..facdf75f3 100644 --- a/Analysis/src/TypeAttach.cpp +++ b/Analysis/src/TypeAttach.cpp @@ -100,8 +100,6 @@ class TypeRehydrationVisitor return allocator->alloc(Location(), std::nullopt, AstName("boolean"), std::nullopt, Location()); case PrimitiveType::Number: return allocator->alloc(Location(), std::nullopt, AstName("number"), std::nullopt, Location()); - case PrimitiveType::Integer: - return allocator->alloc(Location(), std::nullopt, AstName("integer"), std::nullopt, Location()); case PrimitiveType::String: return allocator->alloc(Location(), std::nullopt, AstName("string"), std::nullopt, Location()); case PrimitiveType::Thread: diff --git a/Analysis/src/TypeChecker2.cpp b/Analysis/src/TypeChecker2.cpp index f602b003a..f942f527e 100644 --- a/Analysis/src/TypeChecker2.cpp +++ b/Analysis/src/TypeChecker2.cpp @@ -34,9 +34,6 @@ LUAU_FASTFLAG(DebugLuauMagicTypes) LUAU_FASTFLAGVARIABLE(LuauSkipUnusedTypeTraversals) - -LUAU_FASTFLAG(LuauIntegerType2) -LUAU_FASTFLAGVARIABLE(LuauFixCallMetamethodErrorReporting) LUAU_FASTFLAGVARIABLE(LuauCheckFunctionStatementTypes) LUAU_FASTFLAG(LuauImproveUniqueTableWidthSubtyping) LUAU_FASTFLAGVARIABLE(LuauCallErrorReportingRecoversArgumentLocationsForPacks) @@ -1473,13 +1470,6 @@ void TypeChecker2::checkExtendsClause(AstStatClass* stat) // lookupType() to yield to us a class type (not an instance type!) TypeId superClassTy = follow(lookupType(stat->super)); - // When constraint generation senses a cyclic inheritance chain, it replaces - // one of the links in the chain with an ErrorType that has a synthetic link - // to the stated base type. We chase that away here. - - if (auto e = get(superClassTy); e && e->synthetic) - superClassTy = *e->synthetic; - if (is(superClassTy)) return; @@ -1502,44 +1492,13 @@ void TypeChecker2::checkExtendsClause(AstStatClass* stat) return; } - TypeIds cycle; - - std::optional thisClassTy = scope->lookupType(stat->name->name.value); + Name className{stat->getName().value}; + std::optional thisClassTy = scope->lookupType(className); if (!thisClassTy.has_value()) { reportError( - InternalError{format("Internal error: Type inference failed to record the type of class '%s'", stat->name->name.value)}, - stat->name->location + InternalError{format("Internal error: Type inference failed to record the type of class '%s'", className.c_str())}, stat->location ); - return; - } - - TypeId ty = follow(thisClassTy->type); - cycle.insert(ty); - - while (ty) - { - if (auto ext = get(ty); ext && ext->parent) - ty = follow(*ext->parent); - else if (auto err = get(ty); err && err->synthetic) - ty = follow(*err->synthetic); - else - break; - - if (cycle.contains(ty)) - { - std::vector names; - for (TypeId t : cycle) - { - const ExternType* ext = get(t); - names.emplace_back(ext->name); - } - reportError(CyclicClassInheritance{std::move(names)}, stat->super->location); - break; - } - - if (is(ty)) - cycle.insert(ty); } } @@ -1547,12 +1506,19 @@ void TypeChecker2::visit(AstStatClass* stat) { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + const ExternType* superInstanceEtv = nullptr; + if (stat->super) { visit(stat->super, ValueContext::RValue); checkExtendsClause(stat); - checkMemberOverrides(stat); + // Subtlety: The extends clause names an expression, so the type of this + // expression will be the class object, not the instance type that we're + // inheriting from. + superInstanceEtv = getClassInstanceType(lookupType(stat->super)); + + checkMemberOverrides(stat, superInstanceEtv); } for (const auto& member : stat->members) @@ -1567,21 +1533,17 @@ void TypeChecker2::visit(AstStatClass* stat) visit(method->function); if (method->functionName == "__init") - visitConstructor(stat, method); + visitConstructor(stat, method, superInstanceEtv); } else LUAU_ASSERT(!"Unknown class member!"); } } -void TypeChecker2::checkMemberOverrides(AstStatClass* stat) +void TypeChecker2::checkMemberOverrides(AstStatClass* stat, const ExternType* superInstanceEtv) { LUAU_ASSERT(stat->super); - // Subtlety: The extends clause names an expression, so the type of this - // expression will be the class object, not the instance type that we're - // inheriting from. - const ExternType* superInstanceEtv = getClassInstanceType(lookupType(stat->super)); if (!superInstanceEtv) return; @@ -1610,14 +1572,14 @@ void TypeChecker2::checkMemberOverrides(AstStatClass* stat) if (!constructorDefined) { if (std::optional ancestor = propInInheritanceChain(superInstanceEtv, "__init")) - reportError(MissingConstructor{Name(stat->name->name.value), *ancestor}, stat->location); + reportError(MissingConstructor{Name(stat->getName().value), *ancestor}, stat->location); } } void TypeChecker2::checkPropertyOverride(AstStatClass* stat, const AstClassProperty* property, const ExternType* superInstanceEtv) { if (std::optional ancestor = propInInheritanceChain(superInstanceEtv, property->name.value)) - reportError(IllegalClassPropertyOverride{property->name.value, Name(stat->name->name.value), *ancestor}, property->nameLocation); + reportError(IllegalClassPropertyOverride{property->name.value, Name(stat->getName().value), *ancestor}, property->nameLocation); } void TypeChecker2::checkMethodOverride(AstStatClass* stat, const AstClassMethod* method, const ExternType* superInstanceEtv) @@ -1659,7 +1621,7 @@ void TypeChecker2::checkMethodOverride(AstStatClass* stat, const AstClassMethod* if (method->functionName == "__eq" || method->functionName == "__lt" || method->functionName == "__le") { reportError( - IncompatibleClassMethodOverride{Name(method->functionName.value), Name(stat->name->name.value), superInstanceEtv->name}, + IncompatibleClassMethodOverride{Name(method->functionName.value), Name(stat->getName().value), superInstanceEtv->name}, method->nameLocation ); return; @@ -1697,88 +1659,100 @@ void TypeChecker2::checkMethodOverride(AstStatClass* stat, const AstClassMethod* if (!result.isSubtype) { reportError( - IncompatibleClassMethodOverride{Name(method->functionName.value), Name(stat->name->name.value), superInstanceEtv->name}, + IncompatibleClassMethodOverride{Name(method->functionName.value), Name(stat->getName().value), superInstanceEtv->name}, method->nameLocation ); } } -struct FindUninitializedAccesses : public AstVisitor +bool TypeChecker2::FindUninitializedAccesses::visit(AstExprLocal* local) { - NotNull self; - NotNull> uninitializedFields; - DenseHashSet methodNames; + if (local->local == self && (!uninitializedFields->empty() || superConstructor != nullptr)) + violatingRef.emplace(local); - std::optional violatingRef; - DenseHashMap violatingFields; + return false; +} - FindUninitializedAccesses(AstLocal* self, NotNull> uninitializedFields, DenseHashSet methodNames) - : self(self) - , uninitializedFields(uninitializedFields) - , methodNames(std::move(methodNames)) +bool TypeChecker2::FindUninitializedAccesses::visit(AstExprIndexName* indexName) +{ + if (auto local = indexName->expr->as(); local && local->local == self) { - LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); - } + if (superConstructor != nullptr) + { + violatingRef.emplace(indexName); + return false; + } - bool visit(AstExprLocal* local) override - { - if (local->local == self && !uninitializedFields->empty()) - violatingRef.emplace(local); + // We don't report on fields that simply don't exist. Other machinery will report that. + // We just care about fields that do exist, haven't been initialized, and are being used as rvalues. + std::string fieldName = indexName->index.value; + + if (uninitializedFields->contains(fieldName)) + violatingFields.try_insert(fieldName, indexName); + else if (methodNames.contains(fieldName) && !uninitializedFields->empty()) + violatingRef.emplace(indexName); return false; } - bool visit(AstExprIndexName* indexName) override + return true; +} + +bool TypeChecker2::FindUninitializedAccesses::visit(AstExprIndexExpr* indexName) +{ + if (const AstExprLocal* local = indexName->expr->as(); local && local->local == self) { - if (auto local = indexName->expr->as(); local && local->local == self) + if (superConstructor != nullptr) { - // We don't report on fields that simply don't exist. Other machinery will report that. - // We just care about fields that do exist, haven't been initialized, and are being used as rvalues. - std::string fieldName = indexName->index.value; - - if (uninitializedFields->contains(fieldName)) - violatingFields.try_insert(fieldName, indexName); - else if (methodNames.contains(fieldName) && !uninitializedFields->empty()) + violatingRef.emplace(indexName); + return false; + } + else if (const AstExprConstantString* str = indexName->index->as()) + { + std::string key{str->value.data, str->value.size}; + if (uninitializedFields->contains(key)) + violatingFields.try_insert(key, indexName); + else if (methodNames.contains(key) && !uninitializedFields->empty()) violatingRef.emplace(indexName); return false; } - - return true; } - bool visit(AstExprIndexExpr* indexName) override - { - if (const AstExprLocal* local = indexName->expr->as(); local && local->local == self) - { - if (const AstExprConstantString* str = indexName->index->as()) - { - std::string key{str->value.data, str->value.size}; - if (uninitializedFields->contains(key)) - violatingFields.try_insert(key, indexName); - else if (methodNames.contains(key) && !uninitializedFields->empty()) - violatingRef.emplace(indexName); + return true; +} - return false; - } - } +bool TypeChecker2::FindUninitializedAccesses::visit(AstExprTypeAssertion* expr) +{ + // If self is cast, we don't report + if (const AstExprLocal* local = expr->expr->as(); local && local->local == self) + return false; + return true; +} +bool TypeChecker2::FindUninitializedAccesses::visit(AstExprCall* call) +{ + if (superConstructor == nullptr || superConstructor != checker->lookupType(call->func)) return true; - } - bool visit(AstExprTypeAssertion* expr) override - { - // If self is cast, we don't report - if (const AstExprLocal* local = expr->expr->as(); local && local->local == self) - return false; - return true; - } -}; + bool superConstructorCalled = false; + AstExpr* const* arg = call->args.begin() + 1; + if (const AstExprLocal* local = (*arg)->as(); local && local->local == self) + superConstructorCalled = true; + + for (; arg != call->args.end(); ++arg) + (*arg)->visit(this); -void TypeChecker2::visitConstructor(AstStatClass* stat, const AstClassMethod* method) + if (superConstructorCalled) + superConstructor = nullptr; + + return false; +} + + +void TypeChecker2::visitConstructor(AstStatClass* stat, const AstClassMethod* method, const ExternType* superInstanceEtv) { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); - LUAU_ASSERT(stat); if (method->function->args.size < 1) { @@ -1819,7 +1793,15 @@ void TypeChecker2::visitConstructor(AstStatClass* stat, const AstClassMethod* me methodNames.insert(method->functionName.value); } - FindUninitializedAccesses finder{self, NotNull{&uninitializedFields}, std::move(methodNames)}; + TypeId superConstructor = nullptr; + if (superInstanceEtv && superInstanceEtv->props.count("__init") != 0) + { + const Property& constructor = superInstanceEtv->props.at("__init"); + LUAU_ASSERT(constructor.readTy); + superConstructor = *constructor.readTy; + } + + FindUninitializedAccesses finder{self, NotNull{&uninitializedFields}, std::move(methodNames), superConstructor, NotNull{this}}; for (auto stat : method->function->body->body) { @@ -1892,8 +1874,6 @@ void TypeChecker2::visit(AstExpr* expr, ValueContext context) return visit(e); else if (auto e = expr->as()) return visit(e); - else if (auto e = expr->as()) - return visit(e); else if (auto e = expr->as()) return visit(e); else if (auto e = expr->as()) @@ -1981,18 +1961,6 @@ void TypeChecker2::visit(AstExprConstantNumber* expr) #endif } -void TypeChecker2::visit(AstExprConstantInteger* expr) -{ -#if defined(LUAU_ENABLE_ASSERT) - const TypeId bestType = builtinTypes->integerType; - const TypeId inferredType = lookupType(expr); - NotNull scope{FFlag::LuauDontUseInnermostScope ? stack.back() : findInnermostScope_DEPRECATED(expr->location)}; - - const SubtypingResult r = subtyping->isSubtype(bestType, inferredType, scope); - LUAU_ASSERT(r.isSubtype || isErrorSuppressing(expr->location, inferredType)); -#endif -} - void TypeChecker2::visit(AstExprConstantString* expr) { // strings use specialized inference logic for singleton typeArguments, which can lead to real type errors here. @@ -2266,45 +2234,28 @@ void TypeChecker2::visitCall(AstExprCall* call) { for (const auto& [ty, reasons] : result2.incompatibleOverloads) { - if (FFlag::LuauFixCallMetamethodErrorReporting) - { - // A metamethod is reasoned about with the callee prepended, so reporting - // traverses that same pack. Otherwise the lookup misses and the error is lost. - TypePackId reportedArgs = argsPack; - std::vector reportedExprs = argExprs; + // A metamethod is reasoned about with the callee prepended, so reporting + // traverses that same pack. Otherwise the lookup misses and the error is lost. + TypePackId reportedArgs = argsPack; + std::vector reportedExprs = argExprs; - if (result2.metamethods.contains(ty)) - { - reportedArgs = module->internalTypes->addTypePack(TypePack{{fnTy}, argsPack}); - reportedExprs.insert(reportedExprs.begin(), call->func); - } + if (result2.metamethods.contains(ty)) + { + reportedArgs = module->internalTypes->addTypePack(TypePack{{fnTy}, argsPack}); + reportedExprs.insert(reportedExprs.begin(), call->func); + } - if (const SubtypingReasonings* sr = get_if(&reasons)) - { - for (const SubtypingReasoning& reason : *sr) - resolver.reportErrors(module->errors, ty, call->func->location, module->name, reportedArgs, reportedExprs, reason); - } - else if (const auto errorVec = get_if(&reasons)) - { - reportErrors(*errorVec); - } - else - LUAU_ASSERT(!"Unreachable"); + if (const SubtypingReasonings* sr = get_if(&reasons)) + { + for (const SubtypingReasoning& reason : *sr) + resolver.reportErrors(module->errors, ty, call->func->location, module->name, reportedArgs, reportedExprs, reason); } - else + else if (const auto errorVec = get_if(&reasons)) { - if (const SubtypingReasonings* sr = get_if(&reasons)) - { - for (const SubtypingReasoning& reason : *sr) - resolver.reportErrors(module->errors, ty, call->func->location, module->name, argsPack, argExprs, reason); - } - else if (const auto errorVec = get_if(&reasons)) - { - reportErrors(*errorVec); - } - else - LUAU_ASSERT(!"Unreachable"); + reportErrors(*errorVec); } + else + LUAU_ASSERT(!"Unreachable"); } return; @@ -2789,11 +2740,7 @@ void TypeChecker2::visit(AstExprUnary* expr) } else if (expr->op == AstExprUnary::Op::Minus) { - // A negated integer literal is folded into one constant by the compiler, so it never negates anything. - if (FFlag::LuauIntegerType2 && expr->expr->is()) - testIsSubtype(operandType, builtinTypes->integerType, expr->location); - else - testIsSubtype(operandType, builtinTypes->numberType, expr->location); + testIsSubtype(operandType, builtinTypes->numberType, expr->location); } else if (expr->op == AstExprUnary::Op::Not) { @@ -4008,10 +3955,7 @@ bool TypeChecker2::testPotentialLiteralIsSubtype(AstExpr* expr, TypeId expectedT isSubtype &= testPotentialLiteralIsSubtype(item.value, expectedTableType->indexer->indexResultType); } - if (expectedTableType->state == TableState::Exact) - reportError(MissingProperties{expectedType, exprType, {keyStr}, MissingProperties::Extra}, item.key->location); - - // If there's not an indexer and the table is not exact, by width subtyping we can just do nothing :) + // If there's no indexer, by width subtyping we do nothing } else { diff --git a/Analysis/src/TypeFunctionRuntime.cpp b/Analysis/src/TypeFunctionRuntime.cpp index 12c37f412..fabefe279 100644 --- a/Analysis/src/TypeFunctionRuntime.cpp +++ b/Analysis/src/TypeFunctionRuntime.cpp @@ -26,7 +26,6 @@ LUAU_FASTINTVARIABLE(DebugLuauTypeFunctionRuntimeHeapLimit, 0) LUAU_DYNAMIC_FASTINT(LuauTypeFunctionSerdeIterationLimit) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAGVARIABLE(LuauUdtfTerseChunkNames) @@ -438,8 +437,6 @@ static std::string getTag(lua_State* L, TypeFunctionTypeId ty) return "boolean"; else if (auto n = get(ty); n && n->type == TypeFunctionPrimitiveType::Type::Number) return "number"; - else if (auto n = get(ty); n && (FFlag::LuauIntegerType2 && (n->type == TypeFunctionPrimitiveType::Type::Integer))) - return "integer"; else if (auto s = get(ty); s && s->type == TypeFunctionPrimitiveType::Type::String) return "string"; else if (auto s = get(ty); s && s->type == TypeFunctionPrimitiveType::Type::Thread) @@ -518,15 +515,6 @@ static int createNumber(lua_State* L) return 1; } -// Luau: `type.integer` -// Returns the type instance representing integer -static int createInteger(lua_State* L) -{ - allocTypeUserData(L, TypeFunctionPrimitiveType{TypeFunctionPrimitiveType::Integer}); - - return 1; -} - // Luau: `type.string` // Returns the type instance representing string static int createString(lua_State* L) @@ -1964,14 +1952,6 @@ void registerTypesLibrary(lua_State* L) lua_setfield(L, -2, l->name); } - // `integer` is only nameable in type annotations when the flag is on, so only expose a - // constructor for it under the same condition - if (FFlag::LuauIntegerType2) - { - createInteger(L); - lua_setfield(L, -2, "integer"); - } - lua_pop(L, 1); } @@ -2667,9 +2647,6 @@ class TypeFunctionCloner case TypeFunctionPrimitiveType::Number: target = typeFunctionRuntime->typeArena.allocate(TypeFunctionPrimitiveType(TypeFunctionPrimitiveType::Number)); break; - case TypeFunctionPrimitiveType::Integer: - target = typeFunctionRuntime->typeArena.allocate(TypeFunctionPrimitiveType(TypeFunctionPrimitiveType::Integer)); - break; case TypeFunctionPrimitiveType::String: target = typeFunctionRuntime->typeArena.allocate(TypeFunctionPrimitiveType(TypeFunctionPrimitiveType::String)); break; diff --git a/Analysis/src/TypeFunctionRuntimeBuilder.cpp b/Analysis/src/TypeFunctionRuntimeBuilder.cpp index d9015be8a..a90bc6aca 100644 --- a/Analysis/src/TypeFunctionRuntimeBuilder.cpp +++ b/Analysis/src/TypeFunctionRuntimeBuilder.cpp @@ -159,9 +159,6 @@ class TypeFunctionSerializer case PrimitiveType::Number: target = typeFunctionRuntime->typeArena.allocate(TypeFunctionPrimitiveType(TypeFunctionPrimitiveType::Number)); break; - case PrimitiveType::Integer: - target = typeFunctionRuntime->typeArena.allocate(TypeFunctionPrimitiveType(TypeFunctionPrimitiveType::Integer)); - break; case PrimitiveType::String: target = typeFunctionRuntime->typeArena.allocate(TypeFunctionPrimitiveType(TypeFunctionPrimitiveType::String)); break; @@ -694,9 +691,6 @@ class TypeFunctionDeserializer case TypeFunctionPrimitiveType::Type::Number: target = state->ctx->builtins->numberType; break; - case TypeFunctionPrimitiveType::Type::Integer: - target = state->ctx->builtins->integerType; - break; case TypeFunctionPrimitiveType::Type::String: target = state->ctx->builtins->stringType; break; diff --git a/Analysis/src/TypeInfer.cpp b/Analysis/src/TypeInfer.cpp index e57685147..4a7a61cc1 100644 --- a/Analysis/src/TypeInfer.cpp +++ b/Analysis/src/TypeInfer.cpp @@ -219,7 +219,6 @@ TypeChecker::TypeChecker(const ScopePtr& globalScope, ModuleResolver* resolver, , reusableInstantiation(TxnLog::empty(), nullptr, builtinTypes, {}, nullptr) , nilType(builtinTypes->nilType) , numberType(builtinTypes->numberType) - , integerType(builtinTypes->integerType) , stringType(builtinTypes->stringType) , booleanType(builtinTypes->booleanType) , threadType(builtinTypes->threadType) @@ -410,7 +409,7 @@ ControlFlow TypeChecker::check(const ScopePtr& scope, const AstStat& program) } else if (FFlag::DebugLuauUserDefinedClasses && program.is()) { - reportError(program.as()->name->location, GenericError{"class keyword is illegal here"}); + reportError(program.as()->location, GenericError{"class keyword is illegal here"}); return ControlFlow::None; } else @@ -1964,8 +1963,6 @@ WithPredicate TypeChecker::checkExpr(const ScopePtr& scope, const AstExp } else if (expr.is()) result = WithPredicate{numberType}; - else if (expr.is()) - result = WithPredicate{integerType}; else if (auto a = expr.as()) result = checkExpr(scope, *a); else if (auto a = expr.as()) @@ -6611,8 +6608,6 @@ void TypeChecker::resolve(const TypeGuardPredicate& typeguardP, RefinementMap& r return refine(isString, stringType); else if (typeguardP.kind == "number") return refine(isNumber, numberType); - else if (typeguardP.kind == "integer") - return refine(isInteger, integerType); else if (typeguardP.kind == "boolean") return refine(isBoolean, booleanType); else if (typeguardP.kind == "thread") diff --git a/Analysis/src/TypeStateMap.cpp b/Analysis/src/TypeStateMap.cpp index 9431221c6..a29614f75 100644 --- a/Analysis/src/TypeStateMap.cpp +++ b/Analysis/src/TypeStateMap.cpp @@ -314,8 +314,6 @@ TypeId TypeStateMap::getDiscriminantOf(const NarrowingConstraint& constraint) discriminantTy = builtinTypes->stringType; else if (name == "number") discriminantTy = builtinTypes->numberType; - else if (name == "integer") - discriminantTy = builtinTypes->integerType; else if (name == "boolean") discriminantTy = builtinTypes->booleanType; else if (name == "thread") diff --git a/Analysis/src/TypeUtils.cpp b/Analysis/src/TypeUtils.cpp index 06bf0fd74..d8c476691 100644 --- a/Analysis/src/TypeUtils.cpp +++ b/Analysis/src/TypeUtils.cpp @@ -15,6 +15,7 @@ #include LUAU_FASTFLAG(LuauTraverseScopeToFunction) +LUAU_FASTFLAGVARIABLE(LuauDoNotCrashOnRecursiveSetType) namespace Luau { @@ -24,31 +25,74 @@ bool inConditional(const TypeContext& context) return context == TypeContext::Condition; } -bool occursCheck(TypeId needle, TypeId haystack) +namespace { - LUAU_ASSERT(get(needle) || get(needle)); - haystack = follow(haystack); - if (needle == haystack) +struct OccursCheck : IterativeTypeVisitor +{ + TypeId needle; + bool found = false; + + explicit OccursCheck(TypeId needle) + : IterativeTypeVisitor("OccursCheck", /* skipBoundTypes */ true) + , needle(needle) + { + LUAU_ASSERT((is(needle))); + } + + bool visit(TypeId ty) override + { + found |= ty == needle; + return false; + } + + bool visit(TypeId, const UnionType&) override + { return true; - else if (auto ut = get(haystack)) + } + + bool visit(TypeId, const IntersectionType&) override { - for (TypeId option : ut) - { - if (occursCheck(needle, option)) - return true; - } + return true; } - else if (auto it = get(haystack)) +}; + +} // namespace + +bool occursCheck(TypeId needle, TypeId haystack) +{ + if (FFlag::LuauDoNotCrashOnRecursiveSetType) { - for (TypeId part : it) + OccursCheck oc{needle}; + oc.run(haystack); + return oc.found; + } + else + { + LUAU_ASSERT(get(needle) || get(needle)); + haystack = follow(haystack); + + if (needle == haystack) + return true; + else if (auto ut = get(haystack)) { - if (occursCheck(needle, part)) - return true; + for (TypeId option : ut) + { + if (occursCheck(needle, option)) + return true; + } + } + else if (auto it = get(haystack)) + { + for (TypeId part : it) + { + if (occursCheck(needle, part)) + return true; + } } - } - return false; + return false; + } } std::optional findMetatableEntry( diff --git a/Analysis/src/Unifier.cpp b/Analysis/src/Unifier.cpp index dc82c9911..16dae5062 100644 --- a/Analysis/src/Unifier.cpp +++ b/Analysis/src/Unifier.cpp @@ -2281,7 +2281,6 @@ void Unifier::tryUnifyWithMetatable(TypeId subTy, TypeId superTy, bool reversed) case TableState::Sealed: case TableState::Unsealed: case TableState::Generic: - case TableState::Exact: reportError(std::move(mismatchError)); } } diff --git a/Analysis/src/Unifier2.cpp b/Analysis/src/Unifier2.cpp index 12dc34aae..dfde1b8e1 100644 --- a/Analysis/src/Unifier2.cpp +++ b/Analysis/src/Unifier2.cpp @@ -843,25 +843,10 @@ UnifyResult Unifier2::unify_(TableType* subTable, const TableType* superTable) * same indexer. */ - if (FFlag::LuauDoNotLeakGenericsInIndexer) - { - subTable->indexer = TableIndexer{ - instantiateWithBoundTypes(superTable->indexer->indexType), - instantiateWithBoundTypes(superTable->indexer->indexResultType), - }; - } - else - { - TypeId indexType = superTable->indexer->indexType; - if (TypeId* subst = genericSubstitutions.find(indexType)) - indexType = *subst; - - TypeId indexResultType = superTable->indexer->indexResultType; - if (TypeId* subst = genericSubstitutions.find(indexResultType)) - indexResultType = *subst; - - subTable->indexer = TableIndexer{indexType, indexResultType}; - } + subTable->indexer = TableIndexer{ + instantiateWithBoundTypes(superTable->indexer->indexType), + instantiateWithBoundTypes(superTable->indexer->indexResultType), + }; if (FFlag::LuauInferReadOnlyIndexers) subTable->indexer->isReadOnly = superTable->indexer->isReadOnly; diff --git a/Ast/include/Luau/Ast.h b/Ast/include/Luau/Ast.h index 8c551a87f..b557f03a0 100644 --- a/Ast/include/Luau/Ast.h +++ b/Ast/include/Luau/Ast.h @@ -344,7 +344,6 @@ enum class ConstantNumberParseResult Malformed, BinOverflow, HexOverflow, - IntOverflow, }; class AstExprConstantNumber : public AstExpr @@ -360,18 +359,6 @@ class AstExprConstantNumber : public AstExpr ConstantNumberParseResult parseResult; }; -class AstExprConstantInteger : public AstExpr -{ -public: - LUAU_RTTI(AstExprConstantInteger) - - AstExprConstantInteger(const Location& location, int64_t value, ConstantNumberParseResult parseResult = ConstantNumberParseResult::Ok); - - void visit(AstVisitor* visitor) override; - - int64_t value; - ConstantNumberParseResult parseResult; -}; class AstExprConstantString : public AstExpr { public: @@ -1198,15 +1185,40 @@ class AstStatClass : public AstStat public: LUAU_RTTI(AstStatClass) - AstLocal* name; + // Neither functions nor classes currently support `export const` declarations, so we use an enum here + enum class DeclModifier + { + None, + Local, + Const, + Export + }; + + // exprName is populated if declModifier is None, otherwise localName is populated + union + { + AstExpr* exprName; + AstLocal* localName; + }; AstExpr* super; AstArray members; - bool exported; + DeclModifier declModifier; bool open; - AstStatClass(const Location& location, AstLocal* name, AstExpr* super, AstArray members, bool exported, bool open); + AstStatClass( + const Location& location, + AstExpr* exprName, + AstLocal* localName, + AstExpr* super, + AstArray members, + DeclModifier declModifier, + bool open + ); void visit(AstVisitor* visitor) override; + + AstName getName() const; + Location getNameLocation() const; }; struct AstTableIndexer @@ -1296,13 +1308,12 @@ class AstTypeTable : public AstType public: LUAU_RTTI(AstTypeTable) - AstTypeTable(const Location& location, const AstArray& props, AstTableIndexer* indexer = nullptr, bool isExact = false); + AstTypeTable(const Location& location, const AstArray& props, AstTableIndexer* indexer = nullptr); void visit(AstVisitor* visitor) override; AstArray props; AstTableIndexer* indexer; - bool isExact = false; }; class AstTypeFunction : public AstType @@ -1557,10 +1568,6 @@ class AstVisitor { return visit(static_cast(node)); } - virtual bool visit(class AstExprConstantInteger* node) - { - return visit(static_cast(node)); - } virtual bool visit(class AstExprConstantString* node) { return visit(static_cast(node)); diff --git a/Ast/include/Luau/Cst.h b/Ast/include/Luau/Cst.h index 56d159098..4f6666a0e 100644 --- a/Ast/include/Luau/Cst.h +++ b/Ast/include/Luau/Cst.h @@ -104,16 +104,6 @@ class CstExprConstantNumber : public CstNode AstArray value; }; -class CstExprConstantInteger : public CstNode -{ -public: - LUAU_CST_RTTI(CstExprConstantInteger) - - explicit CstExprConstantInteger(const AstArray& value); - - AstArray value; -}; - class CstExprConstantString : public CstNode { public: diff --git a/Ast/include/Luau/Parser.h b/Ast/include/Luau/Parser.h index da3f92655..257bbb807 100644 --- a/Ast/include/Luau/Parser.h +++ b/Ast/include/Luau/Parser.h @@ -207,7 +207,11 @@ class Parser // type Name `=' Type AstStat* parseTypeAlias(const Location& start, bool exported, Position typeKeywordPosition); - AstStat* parseClassStat(const Location& start, bool exported, bool open); + AstStat* parseClassStat(const Location& start, AstStatClass::DeclModifier declModifier, bool open); + + // True when the current lexeme begins a class declaration: `class Name` or `open class Name`. `class` and `open` are + // contextual keywords, so `local class = 5` must still parse as a binding list. + bool atClassKeyword(); // type function Name ... end AstStat* parseTypeFunction(const Location& start, bool exported, Position typeKeywordPosition); @@ -569,7 +573,6 @@ class Parser DenseHashMap localMap; std::vector localStack; - DenseHashSet classesWithinModule; std::vector parseErrors; diff --git a/Ast/src/Ast.cpp b/Ast/src/Ast.cpp index d36373fb4..6c38b6c1e 100644 --- a/Ast/src/Ast.cpp +++ b/Ast/src/Ast.cpp @@ -173,18 +173,6 @@ void AstExprConstantNumber::visit(AstVisitor* visitor) visitor->visit(this); } -AstExprConstantInteger::AstExprConstantInteger(const Location& location, int64_t value, ConstantNumberParseResult parseResult) - : AstExpr(ClassIndex(), location) - , value(value) - , parseResult(parseResult) -{ -} - -void AstExprConstantInteger::visit(AstVisitor* visitor) -{ - visitor->visit(this); -} - AstExprConstantString::AstExprConstantString(const Location& location, const AstArray& value, QuoteStyle quoteStyle) : AstExpr(ClassIndex(), location) , value(value) @@ -1067,15 +1055,32 @@ AstStatDeclareFunction::AstStatDeclareFunction( { } -AstStatClass::AstStatClass(const Location& location, AstLocal* name, AstExpr* super, AstArray members, bool exported, bool open) +AstStatClass::AstStatClass( + const Location& location, + AstExpr* exprName, + AstLocal* localName, + AstExpr* super, + AstArray members, + DeclModifier declModifier, + bool open +) : AstStat(ClassIndex(), location) - , name(name) , super(super) , members(members) - , exported(exported) + , declModifier(declModifier) , open(open) { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + if (declModifier == DeclModifier::None) + { + LUAU_ASSERT(exprName != nullptr); + this->exprName = exprName; + } + else + { + LUAU_ASSERT(localName != nullptr); + this->localName = localName; + } } void AstStatClass::visit(AstVisitor* visitor) @@ -1083,6 +1088,9 @@ void AstStatClass::visit(AstVisitor* visitor) LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); if (visitor->visit(this)) { + if (declModifier == DeclModifier::None) + exprName->visit(visitor); + if (super) super->visit(visitor); @@ -1106,6 +1114,26 @@ void AstStatClass::visit(AstVisitor* visitor) } } +AstName AstStatClass::getName() const +{ + if (declModifier != DeclModifier::None) + return localName->name; + else if (AstExprLocal* local = exprName->as()) + return local->local->name; + else if (AstExprGlobal* global = exprName->as()) + return global->name; + else if (exprName->is()) + return AstName{"*error*"}; + + LUAU_ASSERT(!"Unreachable"); + return AstName(); +} + +Location AstStatClass::getNameLocation() const +{ + return declModifier == DeclModifier::None ? exprName->location : localName->location; +} + AstStatDeclareFunction::AstStatDeclareFunction( const Location& location, const AstArray& attributes, @@ -1241,11 +1269,10 @@ void AstTypeReference::visit(AstVisitor* visitor) } } -AstTypeTable::AstTypeTable(const Location& location, const AstArray& props, AstTableIndexer* indexer, bool isExact) +AstTypeTable::AstTypeTable(const Location& location, const AstArray& props, AstTableIndexer* indexer) : AstType(ClassIndex(), location) , props(props) , indexer(indexer) - , isExact(isExact) { } diff --git a/Ast/src/Cst.cpp b/Ast/src/Cst.cpp index 035aee640..52cf869ce 100644 --- a/Ast/src/Cst.cpp +++ b/Ast/src/Cst.cpp @@ -50,12 +50,6 @@ CstExprConstantString::CstExprConstantString(AstArray sourceString, QuoteS LUAU_ASSERT(blockDepth == 0 || quoteStyle == QuoteStyle::QuotedRaw); } -CstExprConstantInteger::CstExprConstantInteger(const AstArray& value) - : CstNode(CstClassIndex()) - , value(value) -{ -} - CstExprCall::CstExprCall(Position openParens, Position closeParens, AstArray commaPositions) : CstNode(CstClassIndex()) , openParens(openParens) diff --git a/Ast/src/Parser.cpp b/Ast/src/Parser.cpp index 8410ecb67..51ed28b8d 100644 --- a/Ast/src/Parser.cpp +++ b/Ast/src/Parser.cpp @@ -23,7 +23,6 @@ LUAU_FASTINTVARIABLE(LuauParseErrorLimit, 100) // See docs/SyntaxChanges.md for an explanation. LUAU_FASTFLAGVARIABLE(LuauSolverV2) LUAU_DYNAMIC_FASTFLAGVARIABLE(DebugLuauReportReturnTypeVariadicWithTypeSuffix, false) -LUAU_FASTFLAGVARIABLE(LuauIntegerType2) LUAU_FASTFLAGVARIABLE(LuauExportValueSyntax) LUAU_FLAGVERSION(LuauExportValueSyntax, 5) @@ -31,7 +30,6 @@ LUAU_FASTFLAGVARIABLE(DebugLuauNoInline) LUAU_FASTFLAGVARIABLE(DebugLuauUserDefinedClasses) LUAU_FASTFLAGVARIABLE(LuauAllowGlobalDeclarationToBeCalledClass) LUAU_FASTFLAGVARIABLE(LuauSingleTypeOptionalPackReturnsAttributeParens) -LUAU_FASTFLAGVARIABLE(DebugLuauParseExactTables) LUAU_FASTFLAGVARIABLE(LuauExperimentalIfLocalSyntax) LUAU_FLAGVERSION(LuauExperimentalIfLocalSyntax, 2) LUAU_FASTFLAGVARIABLE(LuauExperimentalWhileLocalSyntax) @@ -439,6 +437,7 @@ AstStatBlock* Parser::parseBlockNoScope() // attributes function funcname funcbody | // local function Name funcbody | // local attributes function Name funcbody | +// [export | const | local] [open] class Name ... end | // local namelist [`=' explist] // laststat ::= return [explist] | break AstStat* Parser::parseStat() @@ -496,14 +495,14 @@ AstStat* Parser::parseStat() return parseTypeAlias(expr->location, /* exported= */ false, expr->location.begin); if (FFlag::DebugLuauUserDefinedClasses && ident == "class") - return parseClassStat(start, /* exported */ false, /* open */ false); + return parseClassStat(start, AstStatClass::DeclModifier::None, /* open */ false); else if (FFlag::DebugLuauUserDefinedClasses && ident == "open") { if (lexer.current().type != Lexeme::Name || AstName(lexer.current().name) != "class") return reportStatError(expr->location, copy({expr}), {}, "Incomplete statement: expected a class definition after 'open'"); nextLexeme(); // consume `class` - return parseClassStat(start, /* exported */ false, /* open */ true); + return parseClassStat(start, AstStatClass::DeclModifier::None, /* open */ true); } if (ident == "export") @@ -533,7 +532,7 @@ AstStat* Parser::parseStat() else if (FFlag::DebugLuauUserDefinedClasses && AstName(lexer.current().name) == "class") { nextLexeme(); - return parseClassStat(start, /* exported */ true, /* open */ false); + return parseClassStat(start, AstStatClass::DeclModifier::Export, /* open */ false); } else if (FFlag::DebugLuauUserDefinedClasses && AstName(lexer.current().name) == "open") { @@ -543,7 +542,7 @@ AstStat* Parser::parseStat() return reportStatError(expr->location, copy({expr}), {}, "Incomplete statement: expected a class definition after 'open'"); nextLexeme(); // consume `class` - return parseClassStat(start, /* exported */ true, /* open */ true); + return parseClassStat(start, AstStatClass::DeclModifier::Export, /* open */ true); } else { @@ -1391,6 +1390,21 @@ AstStat* Parser::parseLocal( if (!isConst) nextLexeme(); // local + if (FFlag::DebugLuauUserDefinedClasses && atClassKeyword()) + { + bool open = AstName(lexer.current().name) == "open"; + if (open) + nextLexeme(); // consume `open` + + nextLexeme(); // consume `class` + + // Attributes on classes are not supported yet (CLI-200853); report and keep parsing the body for recovery. + if (attributes.size != 0) + report(start, "Attributes are not supported on class declarations"); + + return parseClassStat(start, isConst ? AstStatClass::DeclModifier::Const : AstStatClass::DeclModifier::Local, open); + } + if (lexer.current().type == Lexeme::ReservedFunction) { Lexeme matchFunction = lexer.current(); @@ -1623,20 +1637,36 @@ const char* getClassFieldNameError(const AstName& name, AstClassAccess access) } // namespace -// classStatement ::= [`export`] [`open`] `class` Name classProps `end` +bool Parser::atClassKeyword() +{ + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + if (lexer.current().type != Lexeme::Name) + return false; + + // `class` and `open` are contextual keywords, so `local class = 5` and `local open, x = 1, 2` must keep parsing as + // binding lists. We commit to a class declaration only when a name follows, which is the same heuristic `const` uses. + if (AstName(lexer.current().name) == "class") + return lexer.lookahead().type == Lexeme::Name; + + if (AstName(lexer.current().name) == "open") + return lexer.lookahead().type == Lexeme::Name && AstName(lexer.lookahead().name) == "class"; + + return false; +} + +// classStatement ::= [`local` | `const` | `export`] [`open`] `class` Name classProps `end` // classProps ::= classProp [classProps] // classProp ::= name [: classQualifier* type] -LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool exported, bool open) +LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, AstStatClass::DeclModifier declModifier, bool open) { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); - std::optional name = parseNameOpt("type name"); + std::optional name = parseNameOpt("class name"); // Use error name if the name is missing if (!name) name = Name(nameError, lexer.current().location); - // The superclass is parsed before the class binding is pushed so that `class Foo extends Foo` refers to an outer `Foo` rather than to the class - // being declared. AstExpr* super = nullptr; if (lexer.current().type == Lexeme::Name && AstName(lexer.current().name) == "extends") { @@ -1645,10 +1675,32 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export super = parseClassRefExpr(); } - // We save the locals here as part of error recovery later. - auto savedLocals = saveLocals(); + AstLocal* nameLocal = nullptr; + AstExpr* nameExpr = nullptr; - AstLocal* nameLocal = pushLocal(Binding(*name, nullptr, {0, 0}, true)); + if (declModifier == AstStatClass::DeclModifier::None) + { + // The assignment form writes to an existing binding, so the name resolves exactly as it would in an expression. + if (AstLocal* const* existing = localMap.find(name->name); existing && *existing) + { + AstLocal* local = *existing; + if (local->functionDepth < typeFunctionDepth) + return reportStatError(lexer.current().location, {}, {}, "Type function cannot assign to outer local '%s'", local->name.value); + + nameExpr = allocator.alloc(name->location, local, local->functionDepth != functionStack.size() - 1); + } + else + nameExpr = allocator.alloc(name->location, name->name); + + if (!isExprLValue(nameExpr)) + nameExpr = reportLValueError(nameExpr); + } + else + { + nameLocal = pushLocal( + Binding(*name, nullptr, {0, 0}, declModifier == AstStatClass::DeclModifier::Const || declModifier == AstStatClass::DeclModifier::Export) + ); + } TempVector declarations(scratchClassDeclarations); @@ -1823,25 +1875,7 @@ LUAU_NOINLINE AstStat* Parser::parseClassStat(const Location& start, bool export expectAndConsume(Lexeme::ReservedEnd, "class"); Location location{start, end}; - // We only allow classes at the top level: we can make use of the - // recursion counter to check this, though it's a little clowny. - if (recursionCounter > 1) - report(nameLocal->location, "Cannot declare class '%s' inside another statement or expression", nameLocal->name.value); - - AstStat* cls = allocator.alloc(location, nameLocal, super, copy(declarations), exported, open); - if (classesWithinModule.contains(nameLocal->name)) - { - // We do not allow shadowing classes with the same name. However, we - // want to have a decent experience when editing classes that have - // the same name, so if we encounter this shadowing, we pop the local - // representing the class off the stack and return an error. - restoreLocals(savedLocals); - return reportStatError( - nameLocal->location, {}, copy({cls}), "A class named '%s' has already been declared in this module", nameLocal->name.value - ); - } - classesWithinModule.insert(nameLocal->name); - return cls; + return allocator.alloc(location, nameExpr, nameLocal, super, copy(declarations), declModifier, open); } // type function Name `(' arglist `)' `=' funcbody `end' @@ -2303,10 +2337,22 @@ AstStat* Parser::parseExportValue( if (lexer.lookahead().type == Lexeme::ReservedFunction) { - report(start, "'export' must be followed by an identifier or 'function'; try removing 'local'"); + report( + start, + FFlag::DebugLuauUserDefinedClasses + ? "'export' must be followed by an identifier, 'function', or a class declaration; try removing 'local'" + : "'export' must be followed by an identifier or 'function'; try removing 'local'" + ); // still parse the function for error recovery return parseLocal(start, localKeywordLocation.begin, {nullptr, 0}, true); } + else if (FFlag::DebugLuauUserDefinedClasses && lexer.lookahead().type == Lexeme::Name && AstName(lexer.lookahead().name) == "class") + { + report(start, "'export' must be followed by an identifier, 'function', or a class declaration; try removing 'local'"); + // still parse the class for error recovery + return parseLocal(start, localKeywordLocation.begin, {nullptr, 0}, true); + } + // TODO CLI-235561: better error reporting on `export local open class Foo` return exportLocalStat(parseLocal(start, keywordPosition, {nullptr, 0}, false), localKeywordLocation); } @@ -2331,17 +2377,27 @@ AstStat* Parser::parseExportValue( Location constKeywordLocation = lexer.current().location; nextLexeme(); - if (lexer.current().type == Lexeme::ReservedFunction) + if (FFlag::DebugLuauUserDefinedClasses && atClassKeyword()) { - report(start, "'export' must be followed by an identifier or 'function'"); + report(start, "'export' must be followed by an identifier, 'function', or a class declaration; try removing 'const'"); + // still parse the class for error recovery + return parseLocal(start, constKeywordLocation.begin, {nullptr, 0}, true); + } + else if (lexer.current().type == Lexeme::ReservedFunction) + { + report( + start, + FFlag::DebugLuauUserDefinedClasses + ? "'export' must be followed by an identifier, 'function', or a class declaration; try removing 'const'" + : "'export' must be followed by an identifier or 'function'" + ); // still parse the function for error recovery return parseLocal(start, constKeywordLocation.begin, {nullptr, 0}, true); } return exportLocalStat(parseLocal(start, constKeywordLocation.begin, {nullptr, 0}, true), constKeywordLocation); } - else if (FFlag::DebugLuauUserDefinedClasses && lexer.current().type == Lexeme::Name && - (AstName(lexer.current().name) == "class" || AstName(lexer.current().name) == "open")) + else if (FFlag::DebugLuauUserDefinedClasses && atClassKeyword()) { bool open = AstName(lexer.current().name) == "open"; @@ -2354,18 +2410,26 @@ AstStat* Parser::parseExportValue( nextLexeme(); // consume 'class' after 'open' } - auto stat = parseClassStat(start, /* exported */ true, open); + auto stat = parseClassStat(start, AstStatClass::DeclModifier::Export, open); if (auto classStat = stat->as()) { - if (!checkDuplicateExport(classStat->name->name, classStat->name->location)) - report(classStat->name->location, "Duplicate exported class '%s'", classStat->name->name.value); + AstLocal* classLocal = classStat->localName; + + if (!checkDuplicateExport(classLocal->name, classLocal->location)) + report(classLocal->location, "Duplicate exported identifier '%s'", classLocal->name.value); - classStat->name->isExported = true; + classLocal->isExported = true; } return stat; } - return reportStatError(start, {}, {}, "'export' must be followed by an identifier or 'function'"); + return reportStatError( + start, + {}, + {}, + FFlag::DebugLuauUserDefinedClasses ? "'export' must be followed by an identifier, 'function', or a class declaration" + : "'export' must be followed by an identifier or 'function'" + ); } // var [`+=' | `-=' | `*=' | `/=' | `%=' | `^=' | `..='] exp @@ -2937,22 +3001,12 @@ AstType* Parser::parseTableType(bool inDeclarationContext) expectAndConsume('{', "table type"); bool isArray = false; - // When the flag is set, tables are exact by default unless ... is present at the end. - bool isExact = FFlag::DebugLuauParseExactTables; while (lexer.current().type != '}') { AstTableAccess access = AstTableAccess::ReadWrite; std::optional accessLocation; - if (FFlag::DebugLuauParseExactTables && lexer.current().type == Lexeme::Dot3) - { - nextLexeme(); - isExact = false; - // ... is always last. - break; - } - if (lexer.current().type == Lexeme::Name && lexer.lookahead().type != ':') { if (AstName(lexer.current().name) == "read") @@ -3060,16 +3114,6 @@ AstType* Parser::parseTableType(bool inDeclarationContext) AstType* index = allocator.alloc(nullTypeLocation, std::nullopt, nameNumber, std::nullopt, nullTypeLocation); indexer = allocator.alloc(AstTableIndexer{index, type, type->location, access, accessLocation}); - if (FFlag::DebugLuauParseExactTables) - { - if (lexer.current().type == ',' && lexer.lookahead().type == Lexeme::Dot3) - { - nextLexeme(); - nextLexeme(); - isExact = false; - } - } - break; } else @@ -3117,7 +3161,7 @@ AstType* Parser::parseTableType(bool inDeclarationContext) if (!expectMatchAndConsume('}', matchBrace, /* searchForMissing = */ true)) end = lexer.previousLocation(); - AstTypeTable* node = allocator.alloc(Location(start, end), copy(props), indexer, isExact); + AstTypeTable* node = allocator.alloc(Location(start, end), copy(props), indexer); if (options.storeCstData) cstNodeMap[node] = allocator.alloc(copy(cstItems), isArray); return node; @@ -4126,58 +4170,6 @@ static ConstantNumberParseResult parseInteger(double& result, const char* data, return ConstantNumberParseResult::Ok; } -static ConstantNumberParseResult parseInteger64(int64_t& result, const char* data, int base) -{ - LUAU_ASSERT(base == 2 || base == 10 || base == 16); - - char* end = nullptr; - - if (base == 10) - { - result = strtoll(data, &end, 10); - - if (end == data || *end != 'i' || end[1] != '\0') - return ConstantNumberParseResult::Malformed; - - if (((result == LLONG_MIN) || (result == LLONG_MAX)) && (errno == ERANGE)) - { - // 'errno' might have been set before we called 'strtoll', but we don't want the overhead of resetting a TLS variable on each call - // so we only reset it when we get a result that might be an out-of-range error and parse again to make sure - errno = 0; - result = strtoll(data, &end, 10); - - if (errno == ERANGE) - return ConstantNumberParseResult::IntOverflow; - } - } - else - { - if (base == 2 && data[0] == '0' && (data[1] == 'b' || data[1] == 'B')) - return ConstantNumberParseResult::Malformed; - - // hex and binary literals represent bit patterns covering the full uint64 range - unsigned long long u = strtoull(data, &end, base); - - if (end == data || *end != 'i' || end[1] != '\0') - return ConstantNumberParseResult::Malformed; - - if ((u == ULLONG_MAX) && (errno == ERANGE)) - { - // 'errno' might have been set before we called 'strtoull', but we don't want the overhead of resetting a TLS variable on each call - // so we only reset it when we get a result that might be an out-of-range error and parse again to make sure - errno = 0; - u = strtoull(data, &end, base); - - if (errno == ERANGE) - return base == 2 ? ConstantNumberParseResult::BinOverflow : ConstantNumberParseResult::HexOverflow; - } - - result = (int64_t)u; - } - - return ConstantNumberParseResult::Ok; -} - static ConstantNumberParseResult parseDouble(double& result, const char* data) { // binary literal @@ -5211,7 +5203,15 @@ AstExpr* Parser::parseClassRefExpr() const Position& dotPosition = dotOrBracket.location.begin; Parser::Name index = parseIndexName("class reference expression", dotPosition); - return allocator.alloc(Location(start, index.location.end), name, index.name, index.location, dotPosition, '.'); + return allocator.alloc( + Location(start, index.location.end), + name, + index.name, + index.location, + dotPosition, + '.', + inClassMethodBody && isPrivateFieldName(index.name) + ); } else if (dotOrBracket.type == '[') { @@ -5279,44 +5279,17 @@ AstExpr* Parser::parseNumber() scratchData.erase(std::remove(scratchData.begin(), scratchData.end(), '_'), scratchData.end()); } - if (FFlag::LuauIntegerType2 && (scratchData.back() == 'i')) - { - int64_t value = 0; - ConstantNumberParseResult result; - if ((strncmp(scratchData.c_str(), "0x", 2) == 0) || (strncmp(scratchData.c_str(), "0X", 2) == 0)) - result = parseInteger64(value, scratchData.c_str(), 16); // pass in '0x' prefix, it's handled by strtoll - else if ((strncmp(scratchData.c_str(), "0b", 2) == 0) || (strncmp(scratchData.c_str(), "0B", 2) == 0)) - result = parseInteger64(value, scratchData.c_str() + 2, 2); - else - result = parseInteger64(value, scratchData.c_str(), 10); - - nextLexeme(); - - if (result == ConstantNumberParseResult::Malformed) - return reportExprError(start, {}, "Malformed integer"); - - if (result != ConstantNumberParseResult::Ok) - return reportExprError(start, {}, "Integer overflow"); - - AstExprConstantInteger* node = allocator.alloc(start, value, result); - if (options.storeCstData) - cstNodeMap[node] = allocator.alloc(sourceData); - return node; - } - else - { - double value = 0; - ConstantNumberParseResult result = parseDouble(value, scratchData.c_str()); - nextLexeme(); + double value = 0; + ConstantNumberParseResult result = parseDouble(value, scratchData.c_str()); + nextLexeme(); - if (result == ConstantNumberParseResult::Malformed) - return reportExprError(start, {}, "Malformed number"); + if (result == ConstantNumberParseResult::Malformed) + return reportExprError(start, {}, "Malformed number"); - AstExprConstantNumber* node = allocator.alloc(start, value, result); - if (options.storeCstData) - cstNodeMap[node] = allocator.alloc(sourceData); - return node; - } + AstExprConstantNumber* node = allocator.alloc(start, value, result); + if (options.storeCstData) + cstNodeMap[node] = allocator.alloc(sourceData); + return node; } AstLocal* Parser::pushLocal(const Binding& binding) diff --git a/Ast/src/PrettyPrinter.cpp b/Ast/src/PrettyPrinter.cpp index fae929303..91d9a1c87 100644 --- a/Ast/src/PrettyPrinter.cpp +++ b/Ast/src/PrettyPrinter.cpp @@ -523,28 +523,6 @@ struct Printer } } } - else if (const auto& a = expr.as()) - { - if (const auto cstNode = lookupCstNode(a)) - { - writer.literal(std::string_view(cstNode->value.data, cstNode->value.size)); - } - else - { - if (a->value >= 0) - { - char buffer[100]; - size_t len = snprintf(buffer, sizeof(buffer), "%lldi", (long long)a->value); - writer.literal(std::string_view{buffer, len}); - } - else - { - char buffer[100]; - size_t len = snprintf(buffer, sizeof(buffer), "0x%llxi", (unsigned long long)a->value); - writer.literal(std::string_view{buffer, len}); - } - } - } else if (const auto& a = expr.as()) { if (const auto cstNode = lookupCstNode(a)) @@ -903,6 +881,27 @@ struct Printer advance(newPos); } + void visualize(AstStatClass::DeclModifier modifier) + { + switch (modifier) + { + case AstStatClass::DeclModifier::None: + break; + case AstStatClass::DeclModifier::Export: + writer.keyword("export"); + break; + case AstStatClass::DeclModifier::Local: + writer.keyword("local"); + break; + case AstStatClass::DeclModifier::Const: + writer.keyword("const"); + break; + default: + LUAU_ASSERT(!"Unknown class declaration modifier"); + break; + } + } + void visualize(AstStat& program) { advance(program.location.begin); @@ -1381,9 +1380,20 @@ struct Printer } else if (const auto& c = program.as(); c && FFlag::DebugLuauUserDefinedClasses) { + visualize(c->declModifier); + + if (c->open) + writer.keyword("open"); + writer.keyword("class"); - writer.advance(c->name->location.begin); - writer.identifier(c->name->name.value); + if (c->declModifier == AstStatClass::DeclModifier::None) + visualize(*c->exprName); + else + { + writer.advance(c->localName->location.begin); + writer.identifier(c->localName->name.value); + } + if (c->super) { writer.keyword("extends"); diff --git a/Bytecode/include/Luau/BytecodeBuilder.h b/Bytecode/include/Luau/BytecodeBuilder.h index fd5b6d665..7506457b4 100644 --- a/Bytecode/include/Luau/BytecodeBuilder.h +++ b/Bytecode/include/Luau/BytecodeBuilder.h @@ -22,14 +22,6 @@ static const uint32_t kMaxClosureCount = 1 << 15; static const int kMaxJumpDistance = 1 << 23; -class BytecodeEncoder -{ -public: - virtual ~BytecodeEncoder() {} - - virtual void encode(uint32_t* data, size_t count) = 0; -}; - class BytecodeBuilder { public: @@ -70,7 +62,7 @@ class BytecodeBuilder std::vector methodNames; }; - BytecodeBuilder(BytecodeEncoder* encoder = 0); + BytecodeBuilder(); virtual ~BytecodeBuilder() = default; uint32_t beginFunction(uint8_t numparams, bool isvararg = false); @@ -81,7 +73,6 @@ class BytecodeBuilder int32_t addConstantNil(); int32_t addConstantBoolean(bool value); int32_t addConstantNumber(double value); - int32_t addConstantInteger(int64_t value); int32_t addConstantVectorf(float x, float y, float z, float w); int32_t addConstantVectord(double x, double y, double z, double w); int32_t addConstantString(StringRef value); @@ -89,8 +80,6 @@ class BytecodeBuilder int32_t addConstantTable(const TableShape& shape); int32_t addConstantClosure(uint32_t fid); - uint32_t addFbSlot_DEPRECATED(LuauFeedbackType t); - uint32_t addFbSlot_DEPRECATED(LuauFeedbackType t, uint32_t pc); uint32_t addCallTargetSlot(uint32_t pc); uint32_t addConstructSlot(uint32_t shapecid); @@ -212,7 +201,6 @@ class BytecodeBuilder Type_Nil, Type_Boolean, Type_Number, - Type_Integer, Type_Vectorf, Type_Vectord, Type_String, @@ -227,7 +215,6 @@ class BytecodeBuilder { bool valueBoolean; double valueNumber; - int64_t valueInteger64; float valueVectorf[4]; double valueVectord[4]; unsigned int valueString; // index into string table @@ -361,7 +348,6 @@ class BytecodeBuilder }; std::vector fbSlots; - std::vector fbSlots_DEPRECATED; bool hasLongJumps = false; @@ -385,7 +371,6 @@ class BytecodeBuilder std::vector> debugRemarks; std::string debugRemarkBuffer; - BytecodeEncoder* encoder = nullptr; std::string bytecode; uint32_t dumpFlags = 0; diff --git a/Bytecode/include/Luau/BytecodeGraph.h b/Bytecode/include/Luau/BytecodeGraph.h index 692b1a81c..56c811b0c 100644 --- a/Bytecode/include/Luau/BytecodeGraph.h +++ b/Bytecode/include/Luau/BytecodeGraph.h @@ -144,7 +144,6 @@ enum class BcVmConstKind : uint8_t Import, Table, Closure, - Integer, ClassShape }; @@ -162,7 +161,6 @@ struct BcVmConst uint32_t valueImport; uint32_t valueTable; uint32_t valueClosure; - int64_t valueInteger; uint32_t valueClassShape; }; @@ -208,9 +206,6 @@ struct BcVmConst case BcVmConstKind::Closure: return valueClosure == rhs.valueClosure; - case BcVmConstKind::Integer: - return valueInteger == rhs.valueInteger; - case BcVmConstKind::ClassShape: return valueClassShape == rhs.valueClassShape; diff --git a/Bytecode/src/BytecodeBuilder.cpp b/Bytecode/src/BytecodeBuilder.cpp index d3e6c5ccc..e0937af94 100644 --- a/Bytecode/src/BytecodeBuilder.cpp +++ b/Bytecode/src/BytecodeBuilder.cpp @@ -12,15 +12,8 @@ #include #include -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAGVARIABLE(LuauEmitCallFeedback) -LUAU_FASTFLAGVARIABLE(LuauCompileRefactorFeedback) -LUAU_FASTFLAGVARIABLE(LuauBytecodeCostModel) -LUAU_FASTFLAGVARIABLE(LuauCompileCallFbRemap) -LUAU_FLAGVERSION(LuauBytecodeCostModel, 2) -LUAU_FASTFLAGVARIABLE(LuauCompileFastpcall) -LUAU_FLAGVERSION(LuauCompileFastpcall, 2) namespace Luau { @@ -179,8 +172,7 @@ size_t BytecodeBuilder::TableShapeHash::operator()(const TableShape& v) const return hash; } -BytecodeBuilder::BytecodeBuilder(BytecodeEncoder* encoder) - : encoder(encoder) +BytecodeBuilder::BytecodeBuilder() { LUAU_ASSERT(stringTable.find(StringRef{"", 0}) == nullptr); @@ -220,10 +212,7 @@ void BytecodeBuilder::clearState() protos.clear(); jumps.clear(); - if (FFlag::LuauCompileRefactorFeedback || FFlag::DebugLuauUserDefinedClasses) - fbSlots.clear(); - else - fbSlots_DEPRECATED.clear(); + fbSlots.clear(); tableShapes.clear(); @@ -261,9 +250,6 @@ void BytecodeBuilder::endFunction(uint8_t maxstacksize, uint8_t numupvalues, uin // very approximate: 4 bytes per instruction for code, 1 byte for debug line, and 1-2 bytes for aux data like constants plus overhead func.data.reserve(32 + insns.size() * 7); - if (encoder) - encoder->encode(insns.data(), insns.size()); - writeFunction(func.data, currentFunction, flags, cost); currentFunction = ~0u; @@ -350,18 +336,6 @@ int32_t BytecodeBuilder::addConstantNumber(double value) return addConstant(k, c); } -int32_t BytecodeBuilder::addConstantInteger(int64_t value) -{ - Constant c = {Constant::Type_Integer}; - c.valueInteger64 = value; - - ConstantKey k = {Constant::Type_Integer}; - static_assert(sizeof(k.value) == sizeof(value), "Expecting integer to be 64-bit"); - memcpy(&k.value, &value, sizeof(value)); - - return addConstant(k, c); -} - int32_t BytecodeBuilder::addConstantVectorf(float x, float y, float z, float w) { Constant c = {Constant::Type_Vectorf}; @@ -455,25 +429,8 @@ int32_t BytecodeBuilder::addConstantClosure(uint32_t fid) return addConstant(k, c); } -uint32_t BytecodeBuilder::addFbSlot_DEPRECATED(LuauFeedbackType t) -{ - LUAU_ASSERT(!FFlag::LuauCompileRefactorFeedback); - LUAU_ASSERT(t == LuauFeedbackType::LFT_CALLTARGET); - fbSlots_DEPRECATED.push_back(uint32_t(getInstructionCount())); - return uint32_t(fbSlots_DEPRECATED.size() - 1); -} - -uint32_t BytecodeBuilder::addFbSlot_DEPRECATED(LuauFeedbackType t, uint32_t pc) -{ - LUAU_ASSERT(!FFlag::LuauCompileRefactorFeedback); - LUAU_ASSERT(t == LuauFeedbackType::LFT_CALLTARGET); - fbSlots_DEPRECATED.push_back(pc); - return uint32_t(fbSlots_DEPRECATED.size() - 1); -} - uint32_t BytecodeBuilder::addCallTargetSlot(uint32_t pc) { - LUAU_ASSERT(FFlag::LuauCompileRefactorFeedback || FFlag::DebugLuauUserDefinedClasses); fbSlots.push_back({}); fbSlots.back().kind = LFT_CALLTARGET; fbSlots.back().callTarget.pc = pc; @@ -482,7 +439,6 @@ uint32_t BytecodeBuilder::addCallTargetSlot(uint32_t pc) uint32_t BytecodeBuilder::addConstructSlot(uint32_t shapecid) { - LUAU_ASSERT(FFlag::LuauCompileRefactorFeedback || FFlag::DebugLuauUserDefinedClasses); fbSlots.push_back({}); fbSlots.back().kind = LFT_CONSTRUCT; fbSlots.back().construct.shape = shapecid; @@ -913,20 +869,6 @@ void BytecodeBuilder::writeFunction(std::string& ss, uint32_t id, uint8_t flags, writeDouble(ss, c.valueNumber); break; - case Constant::Type_Integer: - writeByte(ss, LBC_CONSTANT_INTEGER); - if (c.valueInteger64 < 0) - { - writeByte(ss, 1); - writeVarInt(ss, ~(uint64_t)c.valueInteger64 + 1); - } - else - { - writeByte(ss, 0); - writeVarInt(ss, c.valueInteger64); - } - break; - case Constant::Type_Vectorf: writeByte(ss, LBC_CONSTANT_VECTOR); writeFloat(ss, c.valueVectorf[0]); @@ -1053,29 +995,16 @@ void BytecodeBuilder::writeFunction(std::string& ss, uint32_t id, uint8_t flags, if (FFlag::LuauEmitCallFeedback || FFlag::DebugLuauUserDefinedClasses) { // Feedback Slots - if (FFlag::LuauCompileRefactorFeedback || FFlag::DebugLuauUserDefinedClasses) - { - writeVarInt(ss, fbSlots.size()); - - for (FeedbackSlot& slot : fbSlots) - { - writeByte(ss, slot.kind); + writeVarInt(ss, fbSlots.size()); - if (slot.kind == LFT_CALLTARGET) - writeVarInt(ss, slot.callTarget.pc); - else if (slot.kind == LFT_CONSTRUCT) - writeVarInt(ss, slot.construct.shape); - } - } - else + for (FeedbackSlot& slot : fbSlots) { - writeVarInt(ss, fbSlots_DEPRECATED.size()); + writeByte(ss, slot.kind); - for (uint32_t pc : fbSlots_DEPRECATED) - { - writeByte(ss, LFT_CALLTARGET); - writeVarInt(ss, pc); - } + if (slot.kind == LFT_CALLTARGET) + writeVarInt(ss, slot.callTarget.pc); + else if (slot.kind == LFT_CONSTRUCT) + writeVarInt(ss, slot.construct.shape); } } else @@ -1468,21 +1397,10 @@ std::vector BytecodeBuilder::expandJumps(bool& hasLongJumpError) typedLocal.startpc = remap[typedLocal.startpc]; } - if (FFlag::LuauCompileCallFbRemap) + for (FeedbackSlot& slot : fbSlots) { - if (FFlag::LuauCompileRefactorFeedback) - { - for (FeedbackSlot& slot : fbSlots) - { - if (slot.kind == LFT_CALLTARGET) - slot.callTarget.pc = remap[slot.callTarget.pc]; - } - } - else - { - for (uint32_t& pc : fbSlots_DEPRECATED) - pc = remap[pc]; - } + if (slot.kind == LFT_CALLTARGET) + slot.callTarget.pc = remap[slot.callTarget.pc]; } return remap; @@ -1503,9 +1421,6 @@ uint8_t BytecodeBuilder::getVersion() if (FFlag::DebugLuauUserDefinedClasses) return LBC_VERSION_CLASSES; - if (FFlag::LuauCompileFastpcall) - return 14; - return LBC_VERSION_TARGET; } @@ -1556,9 +1471,7 @@ void BytecodeBuilder::validateInstructions() const #define VCONST(v, kind) validateConst(v, Constant::Type_##kind) #define VCONSTANY(v) validateConst(v) #define VJUMP(v) LUAU_ASSERT(size_t(i + 1 + v) < insns.size() && insnvalid[i + 1 + v]) -#define VSLOT(v, k) \ - (FFlag::LuauCompileRefactorFeedback || FFlag::DebugLuauUserDefinedClasses ? LUAU_ASSERT(unsigned(v) < fbSlots.size() && fbSlots[v].kind == (k)) \ - : LUAU_ASSERT(unsigned(v) < fbSlots_DEPRECATED.size())) +#define VSLOT(v, k) LUAU_ASSERT(unsigned(v) < fbSlots.size() && fbSlots[v].kind == (k)) LUAU_ASSERT(currentFunction != ~0u); @@ -2380,9 +2293,6 @@ void BytecodeBuilder::dumpConstant(std::string& result, int k, bool detailed) co case Constant::Type_Number: formatAppend(result, "%.17g", data.valueNumber); break; - case Constant::Type_Integer: - formatAppend(result, "%lld", (long long)(int64_t)data.valueInteger64); - break; case Constant::Type_Vectorf: // 3-vectors is the most common configuration, so truncate to three components if possible if (data.valueVectorf[3] == 0.0f) @@ -3090,8 +3000,6 @@ static const char* getBaseTypeString(uint8_t type) return "boolean"; case LBC_TYPE_NUMBER: return "number"; - case LBC_TYPE_INTEGER: - return "integer"; case LBC_TYPE_STRING: return "string"; case LBC_TYPE_TABLE: @@ -3202,29 +3110,18 @@ std::string BytecodeBuilder::dumpCurrentFunction(std::vector& dumpinstoffs) formatAppend(result, "\n"); } - if (FFlag::LuauCompileRefactorFeedback || FFlag::DebugLuauUserDefinedClasses) + for (size_t i = 0; i < fbSlots.size(); ++i) { - for (size_t i = 0; i < fbSlots.size(); ++i) - { - const FeedbackSlot& data = fbSlots[i]; + const FeedbackSlot& data = fbSlots[i]; - switch (data.kind) - { - case LFT_CALLTARGET: - formatAppend(result, "slot %d: call target at pc %u\n", int(i), data.callTarget.pc); - break; - case LFT_CONSTRUCT: - formatAppend(result, "slot %d: shape K%u\n", int(i), data.construct.shape); - break; - } - } - } - else - { - for (size_t i = 0; i < fbSlots_DEPRECATED.size(); ++i) + switch (data.kind) { - uint32_t pc = fbSlots_DEPRECATED[i]; - formatAppend(result, "slot %d: call target at pc %u\n", int(i), pc); + case LFT_CALLTARGET: + formatAppend(result, "slot %d: call target at pc %u\n", int(i), data.callTarget.pc); + break; + case LFT_CONSTRUCT: + formatAppend(result, "slot %d: shape K%u\n", int(i), data.construct.shape); + break; } } } diff --git a/Bytecode/src/BytecodeDump.cpp b/Bytecode/src/BytecodeDump.cpp index 4669116ff..a53bf33e4 100644 --- a/Bytecode/src/BytecodeDump.cpp +++ b/Bytecode/src/BytecodeDump.cpp @@ -361,9 +361,6 @@ void toString(ToStringContext& ctx, BcFunction& function, const BcVmC // TODO: detailed mode append(ctx.result, "%u", data.valueClosure); break; - case BcVmConstKind::Integer: - append(ctx.result, "%lld", (long long)data.valueInteger); - break; case BcVmConstKind::ClassShape: const BytecodeBuilder::ClassShape& cs = function.classShapes[data.valueClassShape]; const BcVmConst& className = function.constants[cs.className]; diff --git a/Bytecode/src/BytecodeGraph.cpp b/Bytecode/src/BytecodeGraph.cpp index 5c3e9dcb4..ad1b235d5 100644 --- a/Bytecode/src/BytecodeGraph.cpp +++ b/Bytecode/src/BytecodeGraph.cpp @@ -8,7 +8,6 @@ LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauCostModel) LUAU_FASTFLAGVARIABLE(LuauInlinerNamecallSelfFromMove) -LUAU_FASTFLAG(LuauCompileRefactorFeedback) namespace Luau { @@ -158,15 +157,6 @@ std::optional fromFunctionBytecode(std::string bytecode, std break; } - case LBC_CONSTANT_INTEGER: - { - fn.constants[i].kind = BcVmConstKind::Integer; - bool isNegative = read(data, offset); - uint64_t magnitude = readVarInt64(data, offset); - fn.constants[i].valueInteger = isNegative ? (int64_t)(~magnitude + 1) : (int64_t)magnitude; - break; - } - case LBC_CONSTANT_CLASS_SHAPE: { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); @@ -402,10 +392,6 @@ std::string toFunctionBytecode(BytecodeBuilder& bcb, CompTimeBcFunction& fn) consts.push_back(bcb.addConstantClosure(c.valueClosure)); break; - case BcVmConstKind::Integer: - consts.push_back(bcb.addConstantInteger(c.valueInteger)); - break; - case BcVmConstKind::ClassShape: { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); @@ -432,10 +418,7 @@ std::string toFunctionBytecode(BytecodeBuilder& bcb, CompTimeBcFunction& fn) LUAU_ASSERT(slot.callTarget.inst < insnsPC.size()); LUAU_ASSERT(insnsPC[slot.callTarget.inst] != ~0u); - if (FFlag::LuauCompileRefactorFeedback || FFlag::DebugLuauUserDefinedClasses) - slotId = bcb.addCallTargetSlot(insnsPC[slot.callTarget.inst]); - else - slotId = bcb.addFbSlot_DEPRECATED(LFT_CALLTARGET, insnsPC[slot.callTarget.inst]); + slotId = bcb.addCallTargetSlot(insnsPC[slot.callTarget.inst]); } else if (slot.kind == LFT_CONSTRUCT) { diff --git a/Bytecode/src/BytecodeGraphParser.h b/Bytecode/src/BytecodeGraphParser.h index bc5d44f4c..82fbb0bb3 100644 --- a/Bytecode/src/BytecodeGraphParser.h +++ b/Bytecode/src/BytecodeGraphParser.h @@ -8,6 +8,7 @@ #include #include +#include #include LUAU_FASTFLAG(DebugLuauUserDefinedClasses) @@ -46,6 +47,7 @@ struct BytecodeGraphParser Producers producers; BcOp currentBlock; std::unordered_map phiBlock; + std::unordered_map removedPhiValue; BytecodeGraphParser(BcFunction& func) : func(func) @@ -214,12 +216,24 @@ struct BytecodeGraphParser { if (std::optional v = readVariable(pred, reg)) { - func.addUse(phi, *v); + func.addUse(phi, resolveRemovedPhi(*v)); } } return tryRemoveTrivialPhi(phiOp); } + BcOp resolveRemovedPhi(BcOp op) + { + while (op.kind == BcOpKind::Phi) + { + auto it = removedPhiValue.find(op); + if (it == removedPhiValue.end()) + break; + op = it->second; + } + return op; + } + // collapse a phi whose operands (ignoring self-references) are a single distinct value // NOTE: a self-referential loop phi left in place would make the serializer's getRegister recurse forever BcOp tryRemoveTrivialPhi(BcOp phiOp) @@ -240,6 +254,8 @@ struct BytecodeGraphParser if (!trivialValue.has_value()) trivialValue = BcOp{BcOpKind::VmReg, reg}; // unreachable or undefined, so we collapse to an VmReg read + removedPhiValue[phiOp] = *trivialValue; + BcRef phiRef = func.phi(phiOp); std::vector users = std::move(phiRef->uses); @@ -331,7 +347,7 @@ struct BytecodeGraphParser { auto staticRegOp = readVariable(block, reg); LUAU_ASSERT(staticRegOp); - res.push_back(*staticRegOp); + res.push_back(resolveRemovedPhi(*staticRegOp)); } res.push_back(blockProducers.multiReturn); // multireturn is consumed, clean it up @@ -452,7 +468,7 @@ struct BytecodeGraphParser return; } LUAU_ASSERT(source); - func.addUse(inst, *source); + func.addUse(inst, resolveRemovedPhi(*source)); } void addJumpInput(BcRef inst, int target) @@ -1111,6 +1127,44 @@ struct BytecodeGraphParser finalizeBlock(currentBlock); sealAllRemaining(); // seal any block whose predecessors were never all emitted + LUAU_ASSERT(noOperandReferencesRemovedPhi()); + return true; + } + + bool noOperandReferencesRemovedPhi() + { + std::unordered_set livePhis; + for (const BcBlock& block : func.blocks) + { + if (block.flags & BcBlockFlag::Dead) + continue; + for (BcOp phiOp : block.phis) + livePhis.insert(phiOp); + } + + auto operandsOk = [&](const BcOps& ops) + { + for (BcOp op : ops) + if (op.kind == BcOpKind::Phi && livePhis.count(op) == 0) + return false; + return true; + }; + + for (const BcBlock& block : func.blocks) + { + if (block.flags & BcBlockFlag::Dead) + continue; + for (BcOp phiOp : block.phis) + { + if (!operandsOk(func.phiOp(phiOp).ops)) + return false; + } + for (BcOp instOp : block.ops) + { + if (!operandsOk(func.instOp(instOp).ops)) + return false; + } + } return true; } }; diff --git a/Bytecode/src/Sccp.cpp b/Bytecode/src/Sccp.cpp index 78233780d..b7f8d800f 100644 --- a/Bytecode/src/Sccp.cpp +++ b/Bytecode/src/Sccp.cpp @@ -157,9 +157,6 @@ std::optional BcVmConstImpl::eq(const BcOp& lhsOp, const BcOp& rhsOp) cons if (lhs.kind != rhs.kind) return false; - if (lhs.kind == BcVmConstKind::Integer && rhs.kind == BcVmConstKind::Integer) - return lhs.valueInteger == rhs.valueInteger; - if (lhs.kind == BcVmConstKind::String && rhs.kind == BcVmConstKind::String) return lhs.valueString == rhs.valueString; } diff --git a/CLI/src/Repl.cpp b/CLI/src/Repl.cpp index 10d6fcffd..7ecaabc52 100644 --- a/CLI/src/Repl.cpp +++ b/CLI/src/Repl.cpp @@ -52,6 +52,7 @@ constexpr int MaxTraversalLimit = 50; static bool codegen = false; static bool codegenCold = false; static bool codegenLazy = false; +static bool dumpPromotion = false; static bool jitInliner = false; static int program_argc = 0; char** program_argv = nullptr; @@ -623,6 +624,48 @@ static bool runFile(const char* name, lua_State* GL, bool repl) nativeOptions.runtimeFeedback = true; + if (dumpPromotion) + { + nativeOptions.runtimeBuildLog = [](void* context, const std::string& message) + { + printf("[codegen] %s\n", message.c_str()); + }; + + nativeOptions.runtimeBuildResult = + [](void* context, const Luau::CodeGen::CompilationResult& result, const Luau::CodeGen::CompilationStats& stats) + { + printf("[codegen] status %s, %zu proto(s) failed\n", + Luau::CodeGen::toString(result.result).c_str(), + result.protoFailures.size() + ); + + for (const Luau::CodeGen::ProtoCompilationFailure& failure : result.protoFailures) + { + printf( + "[codegen] function '%s':%d failed: %s\n", + failure.debugname.c_str(), + failure.line, + Luau::CodeGen::toString(failure.result).c_str() + ); + } + + printf( + "[codegen] bytecode %zu bytes, native %zu + %zu bytes, meta %zu bytes\n", + stats.bytecodeSizeBytes, + stats.nativeCodeSizeBytes, + stats.nativeDataSizeBytes, + stats.nativeMetadataSizeBytes + ); + printf( + "[codegen] %u function(s) total, %u compiled, %u bound in %.3fms\n", + stats.functionsTotal, + stats.functionsCompiled, + stats.functionsBound, + stats.compilationTimeSec * 1000.0 + ); + }; + } + Luau::CodeGen::enableRuntimeCompilation(L, nativeOptions, codegenLazy); if (!codegenLazy) @@ -688,6 +731,7 @@ static void displayHelp(const char* argv0) printf(" --codegen: execute code using native code generation\n"); printf(" --codegen-cold: execute code using native code generation, including any functions deemed not profitable to natively compile\n"); printf(" --codegen-lazy: execute code in the VM and compile hot functions to native automatically\n"); + printf(" --dump-promotion: print runtime promotion and recompilation logs when codegen is enabled\n"); printf(" --codegen-perf: execute code using native code generation and profile using perf (only on Linux)\n"); printf(" --program-args,-a: declare start of arguments to be passed to the Luau program\n"); printf(" --fflags=: comma-separated list of fast flags to enable/disable (--fflags=true,false,LuauFlag1=true,LuauFlag2=false).\n"); @@ -773,6 +817,10 @@ int replMain(int argc, char** argv) codegen = true; codegenPerf = true; } + else if (strcmp(argv[i], "--dump-promotion") == 0) + { + dumpPromotion = true; + } else if (strcmp(argv[i], "--coverage") == 0) { coverage = true; diff --git a/CodeGen/include/Luau/AssemblyBuilderA64.h b/CodeGen/include/Luau/AssemblyBuilderA64.h index c2d29424b..fd911e0a5 100644 --- a/CodeGen/include/Luau/AssemblyBuilderA64.h +++ b/CodeGen/include/Luau/AssemblyBuilderA64.h @@ -176,6 +176,7 @@ class AssemblyBuilderA64 void fsqrt(RegisterA64 dst, RegisterA64 src); void fsub(RegisterA64 dst, RegisterA64 src1, RegisterA64 src2); void faddp(RegisterA64 dst, RegisterA64 src); + void faddp(RegisterA64 dst, RegisterA64 src1, RegisterA64 src2); void fmla(RegisterA64 dst, RegisterA64 src1, RegisterA64 src2); // Vector component manipulation diff --git a/CodeGen/include/Luau/CodeGen.h b/CodeGen/include/Luau/CodeGen.h index 3da5ba667..b45e2179a 100644 --- a/CodeGen/include/Luau/CodeGen.h +++ b/CodeGen/include/Luau/CodeGen.h @@ -47,6 +47,11 @@ struct ProtoCompilationFailure std::string debugname; int line = -1; + + int bytecodeid = 0; + uint32_t funid = 0; + + uint32_t irInstCount = 0; // Instruction count after the initial build }; struct CompilationResult @@ -71,6 +76,8 @@ struct CompilationStats uint32_t functionsTotal = 0; uint32_t functionsCompiled = 0; uint32_t functionsBound = 0; + + double compilationTimeSec = 0.0; }; bool isSupported(); diff --git a/CodeGen/include/Luau/CodeGenOptions.h b/CodeGen/include/Luau/CodeGenOptions.h index 4f23a6ae7..5de248e01 100644 --- a/CodeGen/include/Luau/CodeGenOptions.h +++ b/CodeGen/include/Luau/CodeGenOptions.h @@ -74,6 +74,9 @@ using HostUserdataNamecallHandler = bool (*)( int pcpos ); +using RuntimeBuildResultCallback = void (*)(void* context, const struct CompilationResult& result, const struct CompilationStats& stats); +using RuntimeBuildLogCallback = void (*)(void* context, const std::string& message); + struct HostIrHooks { // Suggest result type of a vector field access @@ -138,6 +141,13 @@ struct CompilationOptions // When true, random NOP sleds are inserted between blocks to // make intra-function gadget offsets unpredictable. bool nopPadding = false; + + // Callbacks for runtime build result and internal event log + RuntimeBuildResultCallback runtimeBuildResult = nullptr; + RuntimeBuildLogCallback runtimeBuildLog = nullptr; + + // Custom userdata provided to the callbacks + void* runtimeBuildContext = nullptr; }; using AnnotatorFn = void (*)(void* context, std::string& result, int fid, int instpos); diff --git a/CodeGen/include/Luau/IrData.h b/CodeGen/include/Luau/IrData.h index 860391bc8..5f5749fa9 100644 --- a/CodeGen/include/Luau/IrData.h +++ b/CodeGen/include/Luau/IrData.h @@ -67,10 +67,6 @@ enum class IrCmd : uint8_t // A: Rn LOAD_INT, - // Load an int64 from TValue - // A: Rn - LOAD_INT64, - // Load a float field from vector (use FLOAT_TO_NUM to convert to double) // A: Rn or Kn // B: int (offset from the start of TValue) @@ -132,11 +128,6 @@ enum class IrCmd : uint8_t // B: int STORE_INT, - // Store an int64 into TValue - // A: Rn - // B: int64 - STORE_INT64, - // Store a vector into TValue // When optional 'E' tag is present, it is written out to the TValue as well // A: Rn @@ -349,7 +340,8 @@ enum class IrCmd : uint8_t ABS_VEC, // Compute dot product between two vectors as a float number (use FLOAT_TO_NUM to convert to double) - // A, B: TValue (vector) + // A, B: TValue + // C: int (component count, 3 or 4) DOT_VEC, // Extract a component of a vector (use FLOAT_TO_NUM to convert to double) @@ -548,6 +540,10 @@ enum class IrCmd : uint8_t // A: TValue TAG_VECTOR, + // Clear the fourth lane to be zero, preserving X/Y/Z components + // A: TValue (vector) + UNTAG_VECTOR, + // Clear high register bits of an unsigned integer register. Used to sanitize value of 'producesDirtyHighRegisterBits' instructions. // A: uint TRUNCATE_UINT, @@ -595,6 +591,17 @@ enum class IrCmd : uint8_t // D: int (result count or -1 to preserve all results and adjust stack top) INVOKE_FASTPCALL, + // Call an object method (namecall lookup and the call itself) + // - if function yields, performs a yield + // - if a target Luau function needs to run, switches execution to it + // - continues if the target call resolved immediately + // A: unsigned int (pcpos) + // B: Rn (argument/result start) + // C: Rn (object) + // D: int (argument count or -1 to use all arguments up to stack top) + // E: int (result count or -1 to preserve all results and adjust stack top) + INVOKE_NAMECALL, + // Fallback functions // Perform an arithmetic operation on TValues of any type @@ -1003,82 +1010,125 @@ enum class IrCmd : uint8_t // A: Rn (level) FINDUPVAL, - // Read i8 (sign-extended to int) from buffer storage at specified offset - // A: pointer (buffer) + // Read i8 (sign-extended to int) from memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) + // C: tag (storage kind) BUFFER_READI8, - // Read u8 (zero-extended to int) from buffer storage at specified offset - // A: pointer (buffer) + // Read u8 (zero-extended to int) from memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) + // C: tag (storage kind) BUFFER_READU8, - // Write i8/u8 value (int argument is truncated) to buffer storage at specified offset - // A: pointer (buffer) + // Write i8/u8 value (int argument is truncated) to memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) // C: int (value) + // D: tag (storage kind) BUFFER_WRITEI8, - // Read i16 (sign-extended to int) from buffer storage at specified offset - // A: pointer (buffer) + // Read i16 (sign-extended to int) from memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) + // C: tag (storage kind) BUFFER_READI16, - // Read u16 (zero-extended to int) from buffer storage at specified offset - // A: pointer (buffer) + // Read u16 (zero-extended to int) from memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) + // C: tag (storage kind) BUFFER_READU16, - // Write i16/u16 value (int argument is truncated) to buffer storage at specified offset - // A: pointer (buffer) + // Write i16/u16 value (int argument is truncated) to memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) // C: int (value) + // D: tag (storage kind) BUFFER_WRITEI16, - // Read i32 value from buffer storage at specified offset - // A: pointer (buffer) + // Read i32 value from memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) + // C: tag (storage kind) BUFFER_READI32, - // Write i32/u32 value to buffer storage at specified offset - // A: pointer (buffer) + // Write i32/u32 value to memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) // C: int (value) + // D: tag (storage kind) BUFFER_WRITEI32, - // Read float value (use FLOAT_TO_NUM to convert to double) from buffer storage at specified offset - // A: pointer (buffer) + // Read float value (use FLOAT_TO_NUM to convert to double) from memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) + // C: tag (storage kind) BUFFER_READF32, - // Write float value (use NUM_TO_FLOAT to convert from double) to buffer storage at specified offset - // A: pointer (buffer) + // Write float value (use NUM_TO_FLOAT to convert from double) to memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) // C: float (value) + // D: tag (storage kind) BUFFER_WRITEF32, - // Read double value from buffer storage at specified offset - // A: pointer (buffer) + // Read double value from memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) + // C: tag (storage kind) BUFFER_READF64, - // Write double value to buffer storage at specified offset - // A: pointer (buffer) + // Write double value to memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) // C: double (value) + // D: tag (storage kind) BUFFER_WRITEF64, - // Read int64 value from buffer storage at specified offset - // A: pointer (buffer) + // Read int64 value from memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) + // C: tag (storage kind) BUFFER_READI64, - // Write i64/u64 value to buffer storage at specified offset - // A: pointer (buffer) + // Write i64/u64 value to memory storage at specified offset + // A: pointer (buffer/userdata) // B: int (offset) // C: int64 (value) + // D: tag (storage kind) BUFFER_WRITEI64, + // Read 'count' (2 or 3) contiguous f32 values from buffer storage into a vector value; unused lanes are zeroed + // A: pointer (buffer or userdata) + // B: int (offset) + // C: tag (LUA_TBUFFER or LUA_TUSERDATA) + // D: int (component count) + // Produces a vector value in a single SIMD register; combine with TAG_VECTOR before storing + BUFFER_READVECTOR, + + // Write 'count' (2 or 3) contiguous f32 values from a vector value to buffer storage + // A: pointer (buffer or userdata) + // B: int (offset) + // C: TValue (vector, only the lower 'count' f32 lanes are written) + // D: tag (LUA_TBUFFER or LUA_TUSERDATA) + // E: int (component count) + BUFFER_WRITEVECTOR, + + // Read 4 packed floats from memory storage at specified offset + // A: pointer (buffer/userdata) + // B: int (offset) + // C: tag (storage kind) + BUFFER_READF32X4, + + // Write 4 packed floats value to memory storage at specified offset + // A: pointer (buffer/userdata) + // B: int (offset) + // C: TValue (value) + // D: tag (storage kind) + BUFFER_WRITEF32X4, + // Perform a conditional jump based on the result of Proto ID comparison // A: closure pointer // B: protoid @@ -1509,6 +1559,7 @@ struct VmExitStoreRecord struct VmExitStoreInfo { uint8_t reg = 0; + uint8_t expectedTag = kUnknownTag; SmallVector stores; }; diff --git a/CodeGen/include/Luau/IrUtils.h b/CodeGen/include/Luau/IrUtils.h index dd5b3026b..ce84410ed 100644 --- a/CodeGen/include/Luau/IrUtils.h +++ b/CodeGen/include/Luau/IrUtils.h @@ -112,6 +112,8 @@ inline bool canInvalidateSafeEnv(IrCmd cmd) return true; case IrCmd::INVOKE_FASTPCALL: return FFlag::LuauCodegenUpdateSafeEnvList; + case IrCmd::INVOKE_NAMECALL: + return true; default: break; } diff --git a/CodeGen/include/Luau/IrVisitUseDef.h b/CodeGen/include/Luau/IrVisitUseDef.h index b0bc56039..3e57ec245 100644 --- a/CodeGen/include/Luau/IrVisitUseDef.h +++ b/CodeGen/include/Luau/IrVisitUseDef.h @@ -21,7 +21,6 @@ static void visitVmRegDefsUses(T& visitor, IrFunction& function, IrInst& inst) case IrCmd::LOAD_POINTER: case IrCmd::LOAD_DOUBLE: case IrCmd::LOAD_INT: - case IrCmd::LOAD_INT64: case IrCmd::LOAD_FLOAT: case IrCmd::LOAD_TVALUE: visitor.maybeUse(OP_A(inst)); // Argument can also be a VmConst @@ -31,7 +30,6 @@ static void visitVmRegDefsUses(T& visitor, IrFunction& function, IrInst& inst) case IrCmd::STORE_POINTER: case IrCmd::STORE_DOUBLE: case IrCmd::STORE_INT: - case IrCmd::STORE_INT64: case IrCmd::STORE_VECTOR: case IrCmd::STORE_TVALUE: case IrCmd::STORE_SPLIT_TVALUE: @@ -164,15 +162,26 @@ static void visitVmRegDefsUses(T& visitor, IrFunction& function, IrInst& inst) break; case IrCmd::INVOKE_FASTPCALL: - { // For a call, 'result start' register is also the register where the target function is // For fast protected calls, function is setup by the instruction itself visitor.useRange(vmRegOp(OP_A(inst)) + 1, function.intOp(OP_C(inst))); visitor.defRange(vmRegOp(OP_A(inst)), function.intOp(OP_D(inst))); break; - } + case IrCmd::INVOKE_NAMECALL: + // Instruction combines NAMECALL (use(C); def(B, 2)) and CALL (use(B), use(B+1, D), def(B, E)) set into a single use followed by def + visitor.use(OP_C(inst)); + if (function.intOp(OP_D(inst)) == -1) + visitor.useRange(vmRegOp(OP_B(inst)) + 2, -1); + else + visitor.useRange(vmRegOp(OP_B(inst)) + 2, function.intOp(OP_D(inst)) - 1); + + if (function.intOp(OP_E(inst)) == -1) + visitor.defRange(vmRegOp(OP_B(inst)), -1); + else + visitor.defRange(vmRegOp(OP_B(inst)), function.intOp(OP_E(inst)) > 2 ? function.intOp(OP_E(inst)) : 2); + break; case IrCmd::FORGLOOP: // First register is not used by instruction, we check that it's still 'nil' with CHECK_TAG visitor.use(OP_A(inst), 1); diff --git a/CodeGen/src/AssemblyBuilderA64.cpp b/CodeGen/src/AssemblyBuilderA64.cpp index d3a2edc60..aab590d76 100644 --- a/CodeGen/src/AssemblyBuilderA64.cpp +++ b/CodeGen/src/AssemblyBuilderA64.cpp @@ -829,6 +829,13 @@ void AssemblyBuilderA64::faddp(RegisterA64 dst, RegisterA64 src) placeR1("faddp", dst, src, 0b011'11110'0'0'11000'01101'10 | ((dst.kind == KindA64::d) << 12)); } +void AssemblyBuilderA64::faddp(RegisterA64 dst, RegisterA64 src1, RegisterA64 src2) +{ + CODEGEN_ASSERT(dst.kind == KindA64::q && src1.kind == KindA64::q && src2.kind == KindA64::q); + + placeVR("faddp", dst, src1, src2, 0b1'01110'0'0'1, 0b11010'1); +} + void AssemblyBuilderA64::fmla(RegisterA64 dst, RegisterA64 src1, RegisterA64 src2) { // There is no scalar version of FMLA instruction diff --git a/CodeGen/src/BytecodeAnalysis.cpp b/CodeGen/src/BytecodeAnalysis.cpp index 1065e0369..818df76a5 100644 --- a/CodeGen/src/BytecodeAnalysis.cpp +++ b/CodeGen/src/BytecodeAnalysis.cpp @@ -11,6 +11,8 @@ #include #include +LUAU_FASTFLAGVARIABLE(LuauCodegenFastcallAnalysisLimit) + namespace Luau { namespace CodeGen @@ -219,8 +221,6 @@ static uint8_t getBytecodeConstantTag(Proto* proto, unsigned ki) return LBC_TYPE_USERDATA; case LUA_TNUMBER: return LBC_TYPE_NUMBER; - case LUA_TINTEGER: - return LBC_TYPE_INTEGER; case LUA_TVECTOR: return LBC_TYPE_VECTOR; case LUA_TSTRING: @@ -507,16 +507,20 @@ static void applyBuiltinCall(LuauBuiltinFunction bfid, BytecodeTypes& types) types.b = LBC_TYPE_NUMBER; types.c = LBC_TYPE_NUMBER; break; - case LBF_BUFFER_READINTEGER: - types.result = LBC_TYPE_INTEGER; + case LBF_BUFFER_READVECTORF32X2: + case LBF_BUFFER_READVECTORF32X3: + case LBF_BUFFER_READVECTORF32X4: + types.result = LBC_TYPE_VECTOR; types.a = LBC_TYPE_BUFFER; types.b = LBC_TYPE_NUMBER; break; - case LBF_BUFFER_WRITEINTEGER: + case LBF_BUFFER_WRITEVECTORF32X2: + case LBF_BUFFER_WRITEVECTORF32X3: + case LBF_BUFFER_WRITEVECTORF32X4: types.result = LBC_TYPE_NIL; types.a = LBC_TYPE_BUFFER; types.b = LBC_TYPE_NUMBER; - types.c = LBC_TYPE_INTEGER; + types.c = LBC_TYPE_VECTOR; break; case LBF_TABLE_INSERT: types.result = LBC_TYPE_NIL; @@ -597,77 +601,6 @@ static void applyBuiltinCall(LuauBuiltinFunction bfid, BytecodeTypes& types) types.result = LBC_TYPE_BOOLEAN; types.a = LBC_TYPE_NUMBER; break; - case LBF_INTEGER_NEG: - case LBF_INTEGER_BSWAP: - case LBF_INTEGER_BNOT: - case LBF_INTEGER_COUNTLZ: - case LBF_INTEGER_COUNTRZ: - types.result = LBC_TYPE_INTEGER; - types.a = LBC_TYPE_INTEGER; - break; - - case LBF_INTEGER_MIN: - case LBF_INTEGER_MAX: - case LBF_INTEGER_BAND: - case LBF_INTEGER_BOR: - case LBF_INTEGER_BXOR: - types.a = LBC_TYPE_INTEGER; - types.b = LBC_TYPE_INTEGER; - types.c = LBC_TYPE_INTEGER; // We can mark optional arguments - types.result = LBC_TYPE_INTEGER; - break; - - case LBF_INTEGER_ADD: - case LBF_INTEGER_SUB: - case LBF_INTEGER_MUL: - case LBF_INTEGER_DIV: - case LBF_INTEGER_IDIV: - case LBF_INTEGER_REM: - case LBF_INTEGER_UDIV: - case LBF_INTEGER_UREM: - case LBF_INTEGER_MOD: - case LBF_INTEGER_LSHIFT: - case LBF_INTEGER_LROTATE: - case LBF_INTEGER_RROTATE: - case LBF_INTEGER_RSHIFT: - case LBF_INTEGER_ARSHIFT: - types.a = LBC_TYPE_INTEGER; - types.b = LBC_TYPE_INTEGER; - types.result = LBC_TYPE_INTEGER; - break; - case LBF_INTEGER_CLAMP: - case LBF_INTEGER_EXTRACT: - types.a = LBC_TYPE_INTEGER; - types.b = LBC_TYPE_INTEGER; - types.c = LBC_TYPE_INTEGER; - types.result = LBC_TYPE_INTEGER; - break; - case LBF_INTEGER_BTEST: - types.a = LBC_TYPE_INTEGER; - types.b = LBC_TYPE_INTEGER; - types.c = LBC_TYPE_INTEGER; // We can mark optional arguments - types.result = LBC_TYPE_BOOLEAN; - break; - case LBF_INTEGER_LT: - case LBF_INTEGER_LE: - case LBF_INTEGER_GT: - case LBF_INTEGER_GE: - case LBF_INTEGER_ULT: - case LBF_INTEGER_ULE: - case LBF_INTEGER_UGT: - case LBF_INTEGER_UGE: - types.a = LBC_TYPE_INTEGER; - types.b = LBC_TYPE_INTEGER; - types.result = LBC_TYPE_BOOLEAN; - break; - case LBF_INTEGER_TONUMBER: - types.a = LBC_TYPE_INTEGER; - types.result = LBC_TYPE_NUMBER; - break; - case LBF_INTEGER_CREATE: - types.a = LBC_TYPE_NUMBER; - types.result = LBC_TYPE_INTEGER; - break; } } @@ -1242,11 +1175,31 @@ void analyzeBytecodeTypes(IrFunction& function, const HostIrHooks& hostHooks) CODEGEN_ASSERT(LUAU_INSN_OP(call) == LOP_CALL); int ra = LUAU_INSN_A(call); - applyBuiltinCall(LuauBuiltinFunction(bfid), bcType); + if (FFlag::LuauCodegenFastcallAnalysisLimit) + { + int nparams = LUAU_INSN_B(call) - 1; + + applyBuiltinCall(LuauBuiltinFunction(bfid), bcType); + + // Argument registers are not annotated for variadic number of arguments + if (nparams >= 1) + regTags[ra + 1] = bcType.a; + + if (nparams >= 2) + regTags[ra + 2] = bcType.b; + + if (nparams >= 3) + regTags[ra + 3] = bcType.c; + } + else + { + applyBuiltinCall(LuauBuiltinFunction(bfid), bcType); + + regTags[ra + 1] = bcType.a; + regTags[ra + 2] = bcType.b; + regTags[ra + 3] = bcType.c; + } - regTags[ra + 1] = bcType.a; - regTags[ra + 2] = bcType.b; - regTags[ra + 3] = bcType.c; regTags[ra] = bcType.result; refineRegType(bcTypeInfo, ra, i, bcType.result); @@ -1529,6 +1482,8 @@ void analyzeBytecodeTypes(IrFunction& function, const HostIrHooks& hostHooks) } case LOP_FINCONSTRUCT: break; + case LOP_CMPPROTO: + break; default: CODEGEN_ASSERT(!"Unknown instruction"); } diff --git a/CodeGen/src/CodeGen.cpp b/CodeGen/src/CodeGen.cpp index bced442be..a0be9b1c9 100644 --- a/CodeGen/src/CodeGen.cpp +++ b/CodeGen/src/CodeGen.cpp @@ -55,7 +55,6 @@ LUAU_FASTINTVARIABLE(CodegenHeuristicsBlockLimit, 32'768) // 32 K // Per-block IR instruction limit LUAU_FASTINTVARIABLE(CodegenHeuristicsBlockInstructionLimit, 65'536) // 64 K -LUAU_FASTFLAGVARIABLE(LuauCodegenInteger3) namespace Luau { diff --git a/CodeGen/src/CodeGenAssembly.cpp b/CodeGen/src/CodeGenAssembly.cpp index fbe57f990..3aba6b295 100644 --- a/CodeGen/src/CodeGenAssembly.cpp +++ b/CodeGen/src/CodeGenAssembly.cpp @@ -11,7 +11,7 @@ #include "lapi.h" -LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauCodegenRuntimeFeedback) namespace Luau { @@ -195,7 +195,7 @@ static std::string getAssemblyImpl( { IrBuilder ir(options.compilationOptions.hooks, envInfo); - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { ir.function.recordCounters = options.compilationOptions.recordCounters; ir.function.recordFeedback = options.compilationOptions.runtimeFeedback; diff --git a/CodeGen/src/CodeGenContext.cpp b/CodeGen/src/CodeGenContext.cpp index dcd14fde0..6695021fc 100644 --- a/CodeGen/src/CodeGenContext.cpp +++ b/CodeGen/src/CodeGenContext.cpp @@ -10,6 +10,7 @@ #include "Luau/UnwindBuilder.h" #include "Luau/UnwindBuilderDwarf2.h" #include "Luau/UnwindBuilderWin.h" +#include "Luau/StringUtils.h" #include "lapi.h" #include "ldo.h" @@ -24,7 +25,7 @@ LUAU_FASTINTVARIABLE(LuauCodeGenBlockSize, 4 * 1024 * 1024) LUAU_FASTINTVARIABLE(LuauCodeGenMaxTotalSize, 256 * 1024 * 1024) -LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAGVARIABLE(LuauCodegenRuntimeFeedback) namespace Luau { @@ -57,16 +58,16 @@ static const Instruction kCodeEntryInsn = LOP_NATIVECALL; // TODO: could be promoted to flags or compilation option fields // Number of counter hits after which the function might be rebuilt -constexpr uint32_t kRebuildCounterHits = 100'000; +constexpr uint32_t kRebuildCounterHits = 10'000; // Number of counter hits after which the recorded register information is considered to be reliable -constexpr uint32_t kReliableFeedbackHits = 10'000; +constexpr uint32_t kReliableFeedbackHits = 2'000; // Maximum number of times a single function can be rebuilt constexpr uint32_t kMaxFunctionRebuilds = 5; // Number of VM hits after which we will natively compile if promoteVmFunctions is enabled -constexpr uint32_t kNativeCompilationHitThreshold = 100'000; +constexpr uint32_t kNativeCompilationHitThreshold = 20'000; // From CodeGen.cpp static void* gPerfLogContext = nullptr; @@ -127,7 +128,7 @@ static void logPerfFunctions( logPerfFunction(*protoIt, uintptr_t(header.entryOffsetOrAddress), uint32_t(header.nativeCodeSize)); - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) ++protoIt; } } @@ -172,7 +173,7 @@ template ++protosBound; - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) ++protoIt; } @@ -362,7 +363,7 @@ void SharedCodeGenContext::onCloseState(lua_State* L) noexcept { CODEGEN_ASSERT(L == L->global->mainthread); - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { // The lifetime of the SharedCodeGenContext is managed separately from the VMs that use it // When a VM is destroyed, only its runtime build data is removed @@ -429,7 +430,7 @@ static void onCloseState(lua_State* L) static void onDestroyFunction(lua_State* L, Proto* proto) { - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { BaseCodeGenContext* codeGenContext = getCodeGenContext(L); VmCodeGenData& vmData = codeGenContext->getVmData(L->global->mainthread); @@ -709,12 +710,12 @@ static void resetRecordedCounters(Proto* proto) } } -static uint8_t getUserdataTagBytecodeType(lua_State* L, uint8_t utag) +static uint8_t getUserdataTagBytecodeType(lua_State* L, uint8_t tag) { - if (utag >= LUA_UTAG_LIMIT || L->global->ecb.gettypemapping == nullptr) + if (tag >= LUA_UTAG_LIMIT || L->global->ecb.gettypemapping == nullptr) return LBC_TYPE_ANY; - LuaTable* mt = L->global->udatamt[utag]; + LuaTable* mt = L->global->udatamt[tag]; if (mt == nullptr) return LBC_TYPE_ANY; @@ -729,6 +730,27 @@ static uint8_t getUserdataTagBytecodeType(lua_State* L, uint8_t utag) return isCustomUserdataBytecodeType(type) ? type : LBC_TYPE_ANY; } +static const char* getUserdataName(lua_State* L, uint8_t tag) +{ + if (tag == LUA_UTAG_LIMIT + 1) + return "proxy"; + + if (tag >= LUA_UTAG_LIMIT) + return "invalid tag"; + + LuaTable* mt = L->global->udatamt[tag]; + + if (mt == nullptr) + return "no name assigned"; + + const TValue* name = luaH_getstr(mt, L->global->tmname[TM_TYPE]); + + if (!ttisstring(name)) + return "invalid name"; + + return svalue(name); +} + // Converts aggregated recorded history into bytecode feedback usable at translation time static void computeFeedback(lua_State* L, const FunctionBuildHistory& history, BytecodeFeedback& feedback) { @@ -782,6 +804,51 @@ static void computeFeedback(lua_State* L, const FunctionBuildHistory& history, B const std::vector* feedback ); +static void logEventSimple(VmCodeGenData& vmData, Proto* p, const char* message) +{ + const char* name = p->debugname ? getstr(p->debugname) : ""; + std::string full = format("%s:%d %s\n", name, p->linedefined, message); + + vmData.options.runtimeBuildLog(vmData.options.runtimeBuildContext, full); +} + +static void logEventFull(lua_State* L, VmCodeGenData& vmData, Proto* p, FunctionBuildHistory& history) +{ + const char* name = p->debugname ? getstr(p->debugname) : ""; + std::string full = format("%s:%d rebuild %u/%u\n", name, p->linedefined, history.rebuildCount, kMaxFunctionRebuilds); + + for (const auto& item : history.recordedTags) + { + formatAppend(full, " line %d R%d tags={", luaG_getline(p, item.pcpos), item.reg); + + bool comma = false; + + for (int tag = 0; tag < LUA_T_COUNT; tag++) + { + if ((item.tagMask & (1 << tag)) == 0) + continue; + + formatAppend(full, "%s%s", comma ? ", " : "", lua_typename(L, tag)); + comma = true; + } + + formatAppend(full, "} (%llu hits)\n", (unsigned long long)item.hits); + } + + for (const auto& item : history.recordedUserdataTags) + { + int line = luaG_getline(p, item.pcpos); + unsigned long long hits = (unsigned long long)item.hits; + + if (item.polymorphic) + full += format(" line %d R%d userdata tags polymorphic (%llu hits)\n", line, item.reg, hits); + else + full += format(" line %d R%d userdata tag %d (%s) (%llu hits)\n", line, item.reg, item.tag, getUserdataName(L, item.tag), hits); + } + + vmData.options.runtimeBuildLog(vmData.options.runtimeBuildContext, full); +} + static void commitFunctions(lua_State* L) { BaseCodeGenContext* codeGenContext = getCodeGenContext(L); @@ -830,6 +897,9 @@ static void commitFunctions(lua_State* L) // Reset history if it was recorded for a different form of the function if (history.sizecode != proto->sizecode) { + if (vmData.options.runtimeBuildLog) + logEventSimple(vmData, proto, "code size changed, resetting runtime feedback history"); + history.sizecode = proto->sizecode; history.recordedTags.clear(); history.recordedUserdataTags.clear(); @@ -846,6 +916,18 @@ static void commitFunctions(lua_State* L) if (feedback == history.lastFeedback) continue; + // Increase rebuild count immediately so that any errors in the process below don't skip an increment + ++history.rebuildCount; + + if (vmData.options.runtimeBuildLog) + logEventFull(L, vmData, proto, history); + + if (history.rebuildCount >= kMaxFunctionRebuilds) + { + proto->execflags |= PEF_EXECLOCKED; + vmData.buildHistory.erase(proto->funid); + } + // Create a copy of the Proto so that already executing functions keep running old code struct CopyContext { @@ -875,11 +957,56 @@ static void commitFunctions(lua_State* L) if (builds.empty()) return; - CompilationResult result = compileProtos({}, L, codeGenContext, buildProtos, vmData.options, nullptr, &buildFeedback); + if (vmData.options.runtimeBuildLog) + vmData.options.runtimeBuildLog(vmData.options.runtimeBuildContext, format("building %d proto(s)", int(buildProtos.size()))); + + CompilationStats stats{}; + CompilationResult result = compileProtos({}, L, codeGenContext, buildProtos, vmData.options, &stats, &buildFeedback); + + DenseHashSet failedFunctions; + + for (const ProtoCompilationFailure& failure : result.protoFailures) + { + switch (failure.result) + { + case CodeGenCompilationResult::CodeGenOverflowInstructionLimit: + // Instruction limit can be hit for the whole batch, so we recheck individual limit here + if (failure.irInstCount >= unsigned(FInt::CodegenHeuristicsInstructionLimit.value)) + failedFunctions.insert(failure.funid); + break; + case CodeGenCompilationResult::CodeGenOverflowBlockLimit: + case CodeGenCompilationResult::CodeGenOverflowBlockInstructionLimit: + case CodeGenCompilationResult::CodeGenLoweringFailure: + failedFunctions.insert(failure.funid); + break; + default: + break; + } + } + + for (const PendingBuild& build : builds) + { + // Finalization failure cannot be attributed to a specific function, so lock the entire batch + if (result.result == CodeGenCompilationResult::CodeGenAssemblerFinalizationFailure || failedFunctions.contains(build.proto->funid)) + { + build.proto->execflags |= PEF_EXECLOCKED; + vmData.buildHistory.erase(build.proto->funid); + + if (vmData.options.runtimeBuildLog) + logEventSimple(vmData, build.proto, "failed to compile"); + } + } + + if (vmData.options.runtimeBuildResult) + vmData.options.runtimeBuildResult(vmData.options.runtimeBuildContext, result, stats); - // TODO: callback function for host telemetry recording if (result.result != CodeGenCompilationResult::Success) + { + if (vmData.options.runtimeBuildLog) + vmData.options.runtimeBuildLog(vmData.options.runtimeBuildContext, format("batch failed to compile - status %d", int(result.result))); + return; + } for (size_t i = 0; i < builds.size(); i++) { @@ -894,19 +1021,15 @@ static void commitFunctions(lua_State* L) if (copy->execdata == nullptr) continue; - FunctionBuildHistory& history = vmData.buildHistory[proto->funid]; - copy->deoptimized = proto; proto->optimized = copy; luaC_objbarrier(L, proto, copy); - history.rebuildCount++; - history.lastFeedback = std::move(buildFeedback[i]); - - if (history.rebuildCount >= kMaxFunctionRebuilds) + // Only update history for the functions which haven't reached a limit + if ((proto->execflags & PEF_EXECLOCKED) == 0) { - copy->execflags |= PEF_EXECLOCKED; - vmData.buildHistory.erase(proto->funid); + FunctionBuildHistory& history = vmData.buildHistory[proto->funid]; + history.lastFeedback = std::move(buildFeedback[i]); } } } @@ -950,7 +1073,7 @@ static void initializeExecutionCallbacks(lua_State* L, BaseCodeGenContext* codeG ecb->getmemorysize = getMemorySize; ecb->getcounterdata = getCounterData; - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { ecb->examinefunction = examineFunctionSafe; ecb->commitfunctions = commitFunctionsSafe; @@ -975,7 +1098,7 @@ void create(lua_State* L, size_t blockSize, size_t maxTotalSize, AllocationCallb if (!codeGenContext->initHeaderFunctions()) return; - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { // Reserve VM data codeGenContext->getVmData(L->global->mainthread); @@ -986,7 +1109,7 @@ void create(lua_State* L, size_t blockSize, size_t maxTotalSize, AllocationCallb void create(lua_State* L, SharedCodeGenContext* codeGenContext) { - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { // Reserve VM data codeGenContext->getVmData(L->global->mainthread); @@ -1039,6 +1162,7 @@ template AssemblyBuilder& build, ModuleHelpers& helpers, Proto* proto, + uint32_t& irInstCount, uint32_t& totalIrInstCount, const CompilationOptions& options, CodeGenCompilationResult& result, @@ -1048,7 +1172,7 @@ template { IrBuilder ir(options.hooks, envInfo); - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { ir.function.recordFeedback = options.runtimeFeedback; @@ -1058,15 +1182,30 @@ template ir.buildFunctionIr(proto); - unsigned instCount = unsigned(ir.function.instructions.size()); - - if (totalIrInstCount + instCount >= unsigned(FInt::CodegenHeuristicsInstructionLimit.value)) + if (FFlag::LuauCodegenRuntimeFeedback) { - result = CodeGenCompilationResult::CodeGenOverflowInstructionLimit; - return {}; + irInstCount = uint32_t(ir.function.instructions.size()); + + if (totalIrInstCount + irInstCount >= unsigned(FInt::CodegenHeuristicsInstructionLimit.value)) + { + result = CodeGenCompilationResult::CodeGenOverflowInstructionLimit; + return {}; + } + + totalIrInstCount += irInstCount; } + else + { + unsigned instCount = unsigned(ir.function.instructions.size()); + + if (totalIrInstCount + instCount >= unsigned(FInt::CodegenHeuristicsInstructionLimit.value)) + { + result = CodeGenCompilationResult::CodeGenOverflowInstructionLimit; + return {}; + } - totalIrInstCount += instCount; + totalIrInstCount += instCount; + } AssemblyOptions assemblyOptions; assemblyOptions.compilationOptions = options; @@ -1147,6 +1286,8 @@ template { CODEGEN_ASSERT(feedbacks == nullptr || feedbacks->size() == protos.size()); + double startTime = lua_clock(); + #if defined(CODEGEN_TARGET_A64) static unsigned int cpuFeatures = getCpuFeaturesA64(); A64::AssemblyBuilderA64 build(/* logger= */ nullptr, cpuFeatures); @@ -1172,7 +1313,7 @@ template nativeProtos.reserve(protos.size()); std::vector compiledProtos; - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) compiledProtos.reserve(protos.size()); uint32_t totalIrInstCount = 0; @@ -1180,17 +1321,26 @@ template for (size_t i = 0; i != protos.size(); ++i) { CodeGenCompilationResult protoResult = CodeGenCompilationResult::Success; + uint32_t irInstCount = 0; const BytecodeFeedback* feedback = feedbacks ? &(*feedbacks)[i] : nullptr; NativeProtoExecDataPtr nativeExecData = - createNativeFunction(nullptr, build, helpers, protos[i], totalIrInstCount, options, protoResult, envInfo, feedback); + createNativeFunction(nullptr, build, helpers, protos[i], irInstCount, totalIrInstCount, options, protoResult, envInfo, feedback); + if (nativeExecData != nullptr) { nativeProtos.push_back(std::move(nativeExecData)); - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) compiledProtos.push_back(protos[i]); } + else if (FFlag::LuauCodegenRuntimeFeedback) + { + Proto* p = protos[i]; + const char* debugname = p->debugname ? getstr(p->debugname) : ""; + + compilationResult.protoFailures.push_back({protoResult, debugname, p->linedefined, p->bytecodeid, p->funid, irInstCount}); + } else { compilationResult.protoFailures.push_back( @@ -1226,6 +1376,8 @@ template stats->functionsCompiled += uint32_t(nativeProtos.size()); stats->nativeCodeSizeBytes += build.code.size() * sizeof(build.code[0]); stats->nativeDataSizeBytes += build.data.size(); + + stats->compilationTimeSec = lua_clock() - startTime; } for (size_t i = 0; i < nativeProtos.size(); ++i) @@ -1243,7 +1395,7 @@ template const ModuleBindResult bindResult = codeGenContext->bindModule( moduleId, - !FFlag::LuauRuntimeFeedback || moduleId ? protos : compiledProtos, + !FFlag::LuauCodegenRuntimeFeedback || moduleId ? protos : compiledProtos, std::move(nativeProtos), reinterpret_cast(build.data.data()), build.data.size(), diff --git a/CodeGen/src/CodeGenLower.h b/CodeGen/src/CodeGenLower.h index b094988b4..777aa1fbd 100644 --- a/CodeGen/src/CodeGenLower.h +++ b/CodeGen/src/CodeGenLower.h @@ -42,6 +42,10 @@ inline void gatherFunctionsHelper( const bool root ) { + // lazy-load stubs (luau_loadlazy) have no code yet; they run interpreted once built + if (proto->lazychunk) + return; + if (results.size() <= size_t(proto->bytecodeid)) results.resize(proto->bytecodeid + 1); diff --git a/CodeGen/src/CodeGenUtils.cpp b/CodeGen/src/CodeGenUtils.cpp index c5b20e071..a8cb5dd42 100644 --- a/CodeGen/src/CodeGenUtils.cpp +++ b/CodeGen/src/CodeGenUtils.cpp @@ -21,6 +21,7 @@ LUAU_FASTFLAG(LuauPromoteProto) LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauCodegenUserdataDirect) // All external function calls that can cause stack realloc or Lua calls have to be wrapped in VM_PROTECT // This makes sure that we save the pc (in case the Lua call needs to generate a backtrace) before the call, @@ -45,6 +46,8 @@ LUAU_FASTFLAG(LuauRuntimeFeedback) #define VM_PATCH_C(pc, slot) *const_cast(pc) = ((uint8_t(slot) << 24) | (0x00ffffffu & *(pc))) #define VM_PATCH_E(pc, slot) *const_cast(pc) = ((uint32_t(slot) << 8) | (0x000000ffu & *(pc))) +#define VM_PATCH_OP(pc, op) *const_cast(pc) = (uint8_t(op) | (0xffffff00u & *(pc))) +#define VM_PATCH_AUX_SLOT(pc, k, slot) *const_cast(pc) = ((k) | (uint32_t(slot) << 16)) #define VM_INTERRUPT() \ { \ @@ -210,6 +213,10 @@ Closure* callProlog(lua_State* L, TValue* ra, StkId argtop, int nresults) CallInfo* ci = incr_ci(L); ci->p = getproto(ccl); + + if (FFlag::LuauRuntimeFeedback && ci->p) + ci->p->execcount++; + ci->func = ra; ci->base = ra + 1; ci->top = argtop + ccl->stacksize; // note: technically UB since we haven't reallocated the stack yet @@ -225,9 +232,6 @@ Closure* callProlog(lua_State* L, TValue* ra, StkId argtop, int nresults) // crucially, we can't use ra/argtop after this line luaD_checkstackfornewci(L, ccl->stacksize); - if (FFlag::LuauRuntimeFeedback && ci->p) - ci->p->execcount++; - return ccl; } @@ -371,6 +375,103 @@ Closure* callFallback(lua_State* L, StkId ra, StkId argtop, int nresults) } } +Closure* callNamecall(lua_State* L, const Instruction* pc, StkId base, TValue* k) +{ + const Instruction* namecallpc = pc; + Instruction insn = *pc++; + uint32_t aux = *pc++; + Instruction call = *pc++; + LUAU_ASSERT(LUAU_INSN_OP(call) == LOP_CALL || LUAU_INSN_OP(call) == LOP_CALLFB); + if (LUAU_INSN_OP(call) == LOP_CALLFB) + pc++; + + int nparams = LUAU_INSN_B(call) - 1; + int nresults = LUAU_INSN_C(call) - 1; + LUAU_ASSERT(LUAU_INSN_A(call) == LUAU_INSN_A(insn)); + + if (LUAU_INSN_OP(insn) == LOP_NAMECALLUDATA) + { + uint32_t kidx = LUAU_INSN_AUX_KV16(aux); + StkId ra = VM_REG(LUAU_INSN_A(insn)); + StkId rb = VM_REG(LUAU_INSN_B(insn)); + + if (ttisuserdata(rb)) + { + int utag = uvalue(rb)->tag; + lua_UdataDirectAccessData& udatadirect = L->global->udatadirect[utag]; + lua_UserdataDirectNamecall onudatanamecall = udatadirect.namecall; + TValue* tm = &udatadirect.namecalltm; + + if (LUAU_LIKELY(onudatanamecall != nullptr && !ttisnil(tm))) + { + TString* name = tsvalue(VM_KV(kidx)); + void* udata = uvalue(rb)->data; + + // note: order of copies allows rb to alias ra+1 or ra + setobj2s(L, ra + 1, rb); + setobj2s(L, ra, tm); + + StkId callRa = VM_REG(LUAU_INSN_A(insn)); + LUAU_ASSERT(callRa == ra); + + L->ci->savedpc = pc; + L->namecall = name; + L->top = nparams == LUA_MULTRET ? L->top : ra + 1 + nparams; + + // note: namecalls do not increase C call number and allow yielding + + luau_setupcci(L, nresults, ra); + + LUAU_ASSERT(name->atom >= 0); + + uint16_t cachedslot = LUAU_INSN_AUX_SLOT(aux); + int results = onudatanamecall(L, udata, name->atom, &cachedslot, utag); + + // update cached slot if instruction didn't deoptimize + if (cachedslot != LUAU_INSN_AUX_SLOT(aux) && LUAU_INSN_OP(*namecallpc) == LOP_NAMECALLUDATA) + VM_PATCH_AUX_SLOT(namecallpc + 1, kidx, cachedslot); + + // yield + if (results < 0) + return (Closure*)CALL_FALLBACK_YIELD; + + CallInfo* ci = L->ci; + CallInfo* cip = ci - 1; + + StkId res = ci->func; + StkId vali = L->top - results; + StkId valend = L->top; + + int i; + for (i = nresults; i != 0 && vali < valend; i--) + setobj2s(L, res++, vali++); + while (i-- > 0) + setnilvalue(res++); + + L->ci = cip; + L->base = cip->base; + L->top = nresults == LUA_MULTRET ? res : cip->top; + + return nullptr; + } + } + + // Slow path - backpatch and dispatch to regular namecall + VM_PATCH_OP(namecallpc, LOP_NAMECALL); + VM_PATCH_AUX_SLOT(namecallpc + 1, kidx, 0); + } + + executeNAMECALL(L, namecallpc, base, k); + + base = L->base; + L->ci->savedpc = pc; + + StkId ra = VM_REG(LUAU_INSN_A(call)); + StkId argtop = nparams == LUA_MULTRET ? L->top : ra + 1 + nparams; + + return callFallback(L, ra, argtop, nresults); +} + int fastPcallSetup(lua_State* L, StkId ra, int pfid, int nparams, int nresults) { LUAU_ASSERT(pfid == 0 || pfid == 1); @@ -459,7 +560,77 @@ const Instruction* executeGETTABLEKS(lua_State* L, const Instruction* pc, StkId StkId ra = VM_REG(LUAU_INSN_A(insn)); StkId rb = VM_REG(LUAU_INSN_B(insn)); uint32_t aux = *pc++; - TValue* kv = VM_KV(op == LOP_GETUDATAKS ? LUAU_INSN_AUX_KV16(aux) : aux); + + if (FFlag::LuauCodegenUserdataDirect && op == LOP_GETUDATAKS) + { + uint32_t kidx = LUAU_INSN_AUX_KV16(aux); + TValue* kv = VM_KV(kidx); + LUAU_ASSERT(ttisstring(kv)); + + if (LUAU_LIKELY(ttisuserdata(rb))) + { + int utag = uvalue(rb)->tag; + lua_UdataDirectAccessData& udatadirect = L->global->udatadirect[utag]; + lua_UserdataDirectAccess onudataindex = udatadirect.index; + TValue* tm = &udatadirect.indextm; + + if (LUAU_LIKELY(onudataindex != nullptr && !ttisnil(tm))) + { + void* udata = uvalue(rb)->data; + + // note: it's safe to push arguments past top for complicated reasons (see top of the file) + LUAU_ASSERT(L->top + 3 < L->stack + L->stacksize); + StkId top = L->top; + setobj2s(L, top + 0, tm); + setobj2s(L, top + 1, rb); + setobj2s(L, top + 2, kv); + L->top += 3; + + L->ci->savedpc = pc; + + ++L->nCcalls; + + if (L->nCcalls >= LUAI_MAXCCALLS) + luaD_checkCstack(L); + + luau_setupcci(L, 1, top); + + uint16_t cachedslot = LUAU_INSN_AUX_SLOT(aux); + onudataindex(L, udata, tsvalue(kv)->atom, &cachedslot, utag); + + // update cached slot if instruction didn't deoptimize + if (cachedslot != LUAU_INSN_AUX_SLOT(aux) && LUAU_INSN_OP(*(pc - 2)) == LOP_GETUDATAKS) + VM_PATCH_AUX_SLOT(pc - 1, kidx, cachedslot); + + // ci is our callinfo, cip is our parent + CallInfo* ci = L->ci; + CallInfo* cip = ci - 1; + + L->ci = cip; + L->base = cip->base; + --L->nCcalls; + + // stack may have been reallocated, so we need to refresh base ptr + base = L->base; + ra = VM_REG(LUAU_INSN_A(insn)); + + // grab result while L->top is still pointed to the previous function frame + setobj2s(L, ra, L->top - 1); + + // then update top + L->top = cip->top; + + return pc; + } + } + + // Slow path - backpatch and dispatch to regular table access + VM_PATCH_OP(pc - 2, LOP_GETTABLEKS); + VM_PATCH_AUX_SLOT(pc - 1, kidx, 0); + aux = kidx; + } + + TValue* kv = FFlag::LuauCodegenUserdataDirect ? VM_KV(aux) : VM_KV(op == LOP_GETUDATAKS ? LUAU_INSN_AUX_KV16(aux) : aux); LUAU_ASSERT(ttisstring(kv)); // fast-path: built-in table @@ -609,7 +780,69 @@ const Instruction* executeSETTABLEKS(lua_State* L, const Instruction* pc, StkId StkId ra = VM_REG(LUAU_INSN_A(insn)); StkId rb = VM_REG(LUAU_INSN_B(insn)); uint32_t aux = *pc++; - TValue* kv = VM_KV(op == LOP_SETUDATAKS ? LUAU_INSN_AUX_KV16(aux) : aux); + + if (FFlag::LuauCodegenUserdataDirect && op == LOP_SETUDATAKS) + { + uint32_t kidx = LUAU_INSN_AUX_KV16(aux); + TValue* kv = VM_KV(kidx); + LUAU_ASSERT(ttisstring(kv)); + + if (LUAU_LIKELY(ttisuserdata(rb))) + { + int utag = uvalue(rb)->tag; + lua_UdataDirectAccessData& udatadirect = L->global->udatadirect[utag]; + lua_UserdataDirectAccess onudatanewindex = udatadirect.newindex; + TValue* tm = &udatadirect.newindextm; + + if (LUAU_LIKELY(onudatanewindex != nullptr && !ttisnil(tm))) + { + void* udata = uvalue(rb)->data; + + // note: it's safe to push arguments past top for complicated reasons (see top of the file) + LUAU_ASSERT(L->top + 4 < L->stack + L->stacksize); + StkId top = L->top; + setobj2s(L, top + 0, tm); + setobj2s(L, top + 1, rb); + setobj2s(L, top + 2, kv); + setobj2s(L, top + 3, ra); + L->top += 4; + + L->ci->savedpc = pc; + + ++L->nCcalls; + + if (L->nCcalls >= LUAI_MAXCCALLS) + luaD_checkCstack(L); + + luau_setupcci(L, 0, top); + + uint16_t cachedslot = LUAU_INSN_AUX_SLOT(aux); + onudatanewindex(L, udata, tsvalue(kv)->atom, &cachedslot, utag); + + // update cached slot if instruction didn't deoptimize + if (cachedslot != LUAU_INSN_AUX_SLOT(aux) && LUAU_INSN_OP(*(pc - 2)) == LOP_SETUDATAKS) + VM_PATCH_AUX_SLOT(pc - 1, kidx, cachedslot); + + // ci is our callinfo, cip is our parent + CallInfo* ci = L->ci; + CallInfo* cip = ci - 1; + + L->ci = cip; + L->base = cip->base; + L->top = cip->top; + --L->nCcalls; + + return pc; + } + } + + // Slow path - backpatch and dispatch to regular table access + VM_PATCH_OP(pc - 2, LOP_SETTABLEKS); + VM_PATCH_AUX_SLOT(pc - 1, kidx, 0); + aux = kidx; + } + + TValue* kv = FFlag::LuauCodegenUserdataDirect ? VM_KV(aux) : VM_KV(op == LOP_SETUDATAKS ? LUAU_INSN_AUX_KV16(aux) : aux); LUAU_ASSERT(ttisstring(kv)); // fast-path: built-in table diff --git a/CodeGen/src/CodeGenUtils.h b/CodeGen/src/CodeGenUtils.h index 9fa3090e9..d5c14ea88 100644 --- a/CodeGen/src/CodeGenUtils.h +++ b/CodeGen/src/CodeGenUtils.h @@ -26,6 +26,7 @@ void getImport(lua_State* L, StkId res, unsigned id, unsigned pc); #define CALL_FALLBACK_YIELD 1 Closure* callFallback(lua_State* L, StkId ra, StkId argtop, int nresults); +Closure* callNamecall(lua_State* L, const Instruction* pc, StkId base, TValue* k); int fastPcallSetup(lua_State* L, StkId ra, int pfid, int nparams, int nresults); const Instruction* executeGETGLOBAL(lua_State* L, const Instruction* pc, StkId base, TValue* k); diff --git a/CodeGen/src/EmitCommonX64.h b/CodeGen/src/EmitCommonX64.h index b7f2b0ce5..bbc5ff66c 100644 --- a/CodeGen/src/EmitCommonX64.h +++ b/CodeGen/src/EmitCommonX64.h @@ -121,11 +121,6 @@ inline OperandX64 luauRegValueInt(int ri) return dword[rBase + ri * sizeof(TValue) + offsetof(TValue, value)]; } -inline OperandX64 luauRegValueInt64(int ri) -{ - return qword[rBase + ri * sizeof(TValue) + offsetof(TValue, value.l)]; -} - inline OperandX64 luauRegValueVector(int ri, int index) { return dword[rBase + ri * sizeof(TValue) + offsetof(TValue, value) + (sizeof(float) * index)]; diff --git a/CodeGen/src/IrBuilder.cpp b/CodeGen/src/IrBuilder.cpp index 651a398ca..24502197f 100644 --- a/CodeGen/src/IrBuilder.cpp +++ b/CodeGen/src/IrBuilder.cpp @@ -15,7 +15,7 @@ LUAU_FASTFLAGVARIABLE(LuauCodeGenFastpcall) LUAU_FLAGVERSION(LuauCodeGenFastpcall, 2) LUAU_FASTFLAG(LuauCodegenMarkUsed) -LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauCodegenRuntimeFeedback) namespace Luau { @@ -84,9 +84,6 @@ static void buildArgumentTypeChecks(IrBuilder& build, IrOp entry) case LBC_TYPE_NUMBER: build.inst(IrCmd::CHECK_TAG, load, build.constTag(LUA_TNUMBER), build.vmExit(kVmExitEntryGuardPc)); break; - case LBC_TYPE_INTEGER: - build.inst(IrCmd::CHECK_TAG, load, build.constTag(LUA_TINTEGER), build.vmExit(kVmExitEntryGuardPc)); - break; case LBC_TYPE_STRING: build.inst(IrCmd::CHECK_TAG, load, build.constTag(LUA_TSTRING), build.vmExit(kVmExitEntryGuardPc)); break; @@ -762,7 +759,7 @@ void IrBuilder::beginBlock(IrOp block) inTerminatedBlock = false; - if (FFlag::LuauRuntimeFeedback && target.counterSet != ~0u && !function.counterSets[target.counterSet].counters.empty()) + if (FFlag::LuauCodegenRuntimeFeedback && target.counterSet != ~0u && !function.counterSets[target.counterSet].counters.empty()) inst(IrCmd::UPDATE_COUNTERS, constUint(target.counterSet)); } diff --git a/CodeGen/src/IrDump.cpp b/CodeGen/src/IrDump.cpp index 5d780f31c..df8a717ae 100644 --- a/CodeGen/src/IrDump.cpp +++ b/CodeGen/src/IrDump.cpp @@ -88,8 +88,6 @@ const char* getTagName(uint8_t tag) return "tclass"; case LUA_TOBJECT: return "tobject"; - case LUA_TINTEGER: - return "tinteger"; default: CODEGEN_ASSERT(!"Unknown type tag"); LUAU_UNREACHABLE(); @@ -110,8 +108,6 @@ const char* getCmdName(IrCmd cmd) return "LOAD_DOUBLE"; case IrCmd::LOAD_INT: return "LOAD_INT"; - case IrCmd::LOAD_INT64: - return "LOAD_INT64"; case IrCmd::LOAD_FLOAT: return "LOAD_FLOAT"; case IrCmd::LOAD_TVALUE: @@ -136,8 +132,6 @@ const char* getCmdName(IrCmd cmd) return "STORE_DOUBLE"; case IrCmd::STORE_INT: return "STORE_INT"; - case IrCmd::STORE_INT64: - return "STORE_INT64"; case IrCmd::STORE_VECTOR: return "STORE_VECTOR"; case IrCmd::STORE_TVALUE: @@ -338,6 +332,8 @@ const char* getCmdName(IrCmd cmd) return "FLOAT_TO_VEC"; case IrCmd::TAG_VECTOR: return "TAG_VECTOR"; + case IrCmd::UNTAG_VECTOR: + return "UNTAG_VECTOR"; case IrCmd::TRUNCATE_UINT: return "TRUNCATE_UINT"; case IrCmd::ADJUST_STACK_TO_REG: @@ -352,6 +348,8 @@ const char* getCmdName(IrCmd cmd) return "CHECK_FASTCALL_RES"; case IrCmd::INVOKE_FASTPCALL: return "INVOKE_FASTPCALL"; + case IrCmd::INVOKE_NAMECALL: + return "INVOKE_NAMECALL"; case IrCmd::DO_ARITH: return "DO_ARITH"; case IrCmd::DO_LEN: @@ -542,6 +540,14 @@ const char* getCmdName(IrCmd cmd) return "BUFFER_READI64"; case IrCmd::BUFFER_WRITEI64: return "BUFFER_WRITEI64"; + case IrCmd::BUFFER_READVECTOR: + return "BUFFER_READVECTOR"; + case IrCmd::BUFFER_WRITEVECTOR: + return "BUFFER_WRITEVECTOR"; + case IrCmd::BUFFER_READF32X4: + return "BUFFER_READF32X4"; + case IrCmd::BUFFER_WRITEF32X4: + return "BUFFER_WRITEF32X4"; case IrCmd::JUMP_CMP_PROTOID: return "JUMP_CMP_PROTOID"; } @@ -618,9 +624,6 @@ uint8_t parseTagName(std::string_view name) if (name == "tnumber") return LUA_TNUMBER; - if (name == "tinteger") - return LUA_TINTEGER; - if (name == "tvector") return LUA_TVECTOR; @@ -704,10 +707,6 @@ static void appendVmConstant(std::string& result, Proto* proto, int index) else append(result, "%.17g", constant.value.n); } - else if (constant.tt == LUA_TINTEGER) - { - append(result, "%lldi", (long long)constant.value.l); - } else if (constant.tt == LUA_TSTRING) { TString* str = gco2ts(constant.value.gc); @@ -860,8 +859,6 @@ const char* getBytecodeTypeName(uint8_t type, const char* const* userdataTypes) return "boolean"; case LBC_TYPE_NUMBER: return "number"; - case LBC_TYPE_INTEGER: - return "integer"; case LBC_TYPE_STRING: return "string"; case LBC_TYPE_TABLE: diff --git a/CodeGen/src/IrLoweringA64.cpp b/CodeGen/src/IrLoweringA64.cpp index 32155bf01..d19c250a4 100644 --- a/CodeGen/src/IrLoweringA64.cpp +++ b/CodeGen/src/IrLoweringA64.cpp @@ -12,9 +12,11 @@ #include "lstate.h" #include "lgc.h" +LUAU_FASTFLAG(LuauCodegenMetatableCache) LUAU_FASTFLAGVARIABLE(LuauCodegenA64ForgLoopArray) LUAU_FASTFLAGVARIABLE(LuauCodegenA64BitlrotateSelf) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) +LUAU_FASTFLAG(LuauCodegenMultiLaneDot) namespace Luau { @@ -370,13 +372,6 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.ldr(inst.regA64, addr); break; } - case IrCmd::LOAD_INT64: - { - inst.regA64 = regs.allocReg(KindA64::x, index); - AddressA64 addr = tempAddr(OP_A(inst), offsetof(TValue, value.l)); - build.ldr(inst.regA64, addr); - break; - } case IrCmd::LOAD_FLOAT: { inst.regA64 = regs.allocReg(KindA64::s, index); @@ -554,20 +549,6 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) } break; } - case IrCmd::STORE_INT64: - { - AddressA64 addr = tempAddr(OP_A(inst), offsetof(TValue, value)); - if (OP_B(inst).kind == IrOpKind::Constant && int64Op(OP_B(inst)) == 0) - { - build.str(xzr, addr); - } - else - { - RegisterA64 temp = tempInt64(OP_B(inst)); - build.str(temp, addr); - } - break; - } case IrCmd::STORE_VECTOR: { RegisterA64 temp1 = tempFloat(OP_B(inst)); @@ -623,11 +604,6 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) RegisterA64 temp = tempDouble(OP_C(inst)); build.str(temp, addr); } - else if (tagOp(OP_B(inst)) == LUA_TINTEGER) - { - RegisterA64 temp = tempInt64(OP_C(inst)); - build.str(temp, addr); - } else if (isGCO(tagOp(OP_B(inst)))) { build.str(regOp(OP_C(inst)), addr); @@ -1284,9 +1260,30 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) RegisterA64 temps = castReg(KindA64::s, temp); build.fmul(temp, regOp(OP_A(inst)), regOp(OP_B(inst))); - build.faddp(inst.regA64, temps); // x+y - build.dup_4s(temp, temp, 2); - build.fadd(inst.regA64, inst.regA64, temps); // +z + + if (FFlag::LuauCodegenMultiLaneDot) + { + int lanes = intOp(OP_C(inst)); + CODEGEN_ASSERT(lanes == 3 || lanes == 4); + + if (lanes == 4) + { + build.faddp(temp, temp, temp); // x+y, z+w + build.faddp(inst.regA64, temps); // (x+y) + (z+w) + } + else + { + build.faddp(inst.regA64, temps); // x+y + build.dup_4s(temp, temp, 2); + build.fadd(inst.regA64, inst.regA64, temps); // +z + } + } + else + { + build.faddp(inst.regA64, temps); // x+y + build.dup_4s(temp, temp, 2); + build.fadd(inst.regA64, inst.regA64, temps); // +z + } break; } case IrCmd::EXTRACT_VEC: @@ -1575,14 +1572,6 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.fcmp(temp1, temp2); build.cset(inst.regA64, getConditionFP(cond)); } - else if (tagOp(OP_B(inst)) == LUA_TINTEGER) - { - RegisterA64 temp1 = tempInt64(OP_C(inst)); - RegisterA64 temp2 = tempInt64(OP_D(inst)); - - build.cmp(temp1, temp2); - build.cset(inst.regA64, getConditionInt64(cond)); - } else { CODEGEN_ASSERT(!"unsupported type tag in CMP_SPLIT_TVALUE"); @@ -1942,16 +1931,53 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.tst(temp2, 1 << intOp(OP_B(inst))); // can't use tbz/tbnz because their jump offsets are too short build.b(ConditionA64::NotEqual, labelOp(OP_C(inst))); // Equal = Zero after tst; tmcache caches *absence* of metamethods - regs.spill(index, {temp1}); - build.mov(x0, temp1); - build.mov(w1, intOp(OP_B(inst))); - build.ldr(x2, mem(rGlobalState, offsetof(global_State, tmname) + intOp(OP_B(inst)) * sizeof(TString*))); - build.ldr(x3, mem(rNativeContext, offsetof(NativeContext, luaT_gettm))); - build.blr(x3); + if (FFlag::LuauCodegenMetatableCache) + { + inst.regA64 = regs.allocReg(KindA64::x, index); - build.cbz(x0, labelOp(OP_C(inst))); // no tag method + Label uncached, skip; + build.ldrb(temp2, mem(temp1, offsetof(LuaTable, readonly))); + build.tst(temp2, 2); + build.b(ConditionA64::Equal, uncached); + build.ldr(inst.regA64, mem(temp1, offsetof(LuaTable, array))); + build.sub(inst.regA64, inst.regA64, uint16_t((1 + intOp(OP_B(inst))) * sizeof(TValue))); + build.b(skip); + build.setLabel(uncached); - inst.regA64 = regs.takeReg(x0, index); + // we have reserved the result register, so we can free it now so it is not recorded in the spill sequence + regs.freeReg(inst.regA64); + + size_t spills = regs.spill(index, {temp1}, /* keepLazyLocations */ true); + + build.mov(x0, temp1); + build.mov(w1, intOp(OP_B(inst))); + build.ldr(x2, mem(rGlobalState, offsetof(global_State, tmname) + intOp(OP_B(inst)) * sizeof(TString*))); + build.ldr(x3, mem(rNativeContext, offsetof(NativeContext, luaT_gettm))); + build.blr(x3); + + if (inst.regA64 != x0) + build.mov(inst.regA64, x0); + + inst.regA64 = regs.takeReg(inst.regA64, index); + + regs.restore(spills); // need to restore before skip so that registers are in a consistent state + + build.cbz(inst.regA64, labelOp(OP_C(inst))); // no tag method + build.setLabel(skip); + } + else + { + regs.spill(index, {temp1}); + build.mov(x0, temp1); + build.mov(w1, intOp(OP_B(inst))); + build.ldr(x2, mem(rGlobalState, offsetof(global_State, tmname) + intOp(OP_B(inst)) * sizeof(TString*))); + build.ldr(x3, mem(rNativeContext, offsetof(NativeContext, luaT_gettm))); + build.blr(x3); + + build.cbz(x0, labelOp(OP_C(inst))); // no tag method + + inst.regA64 = regs.takeReg(x0, index); + } break; } case IrCmd::NEW_USERDATA: @@ -2092,6 +2118,18 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.ins_4s(inst.regA64, tempw, 3); break; } + case IrCmd::UNTAG_VECTOR: + { + inst.regA64 = regs.allocReuse(KindA64::q, index, {OP_A(inst)}); + + RegisterA64 reg = regOp(OP_A(inst)); + + if (inst.regA64 != reg) + build.mov(inst.regA64, reg); + + build.ins_4s(inst.regA64, wzr, 3); + break; + } case IrCmd::TRUNCATE_UINT: inst.regA64 = regs.allocReuse(KindA64::w, index, {OP_A(inst)}); @@ -2214,6 +2252,13 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.setLabel(cont); break; } + case IrCmd::INVOKE_NAMECALL: + regs.spill(index); + emitFallback(build, offsetof(NativeContext, callNamecall), uintOp(OP_A(inst))); + + // reentry with x0=closure (NULL implies C function; CALL_FALLBACK_YIELD will trigger exit) + build.cbnz(x0, helpers.continueCall); + break; case IrCmd::DO_ARITH: regs.spill(index); build.mov(x0, rState); @@ -3929,6 +3974,48 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) break; } + case IrCmd::BUFFER_READVECTOR: + { + CODEGEN_ASSERT(intOp(OP_D(inst)) == 2 || intOp(OP_D(inst)) == 3); + inst.regA64 = regs.allocReg(KindA64::q, index); + + AddressA64 addr = tempAddrBuffer(OP_A(inst), OP_B(inst), tagOp(OP_C(inst))); + // materialize an exact byte pointer so per-lane offsets (0/8) are always small and encodable regardless of a large constant index + RegisterA64 base = regs.allocTemp(KindA64::x); + build.add(base, addr.base, uint16_t(addr.data)); + + // loading into the 'd' view zeroes the upper 64 bits, so a 2-component read is already [x, y, 0, 0] + build.ldr(castReg(KindA64::d, inst.regA64), mem(base, 0)); + + if (intOp(OP_D(inst)) == 3) + { + RegisterA64 tempz = regs.allocTemp(KindA64::q); + build.ldr(castReg(KindA64::s, tempz), mem(base, 8)); + build.ins_4s(inst.regA64, 2, tempz, 0); // z into lane 2 + } + break; + } + + case IrCmd::BUFFER_WRITEVECTOR: + { + CODEGEN_ASSERT(intOp(OP_E(inst)) == 2 || intOp(OP_E(inst)) == 3); + RegisterA64 value = regOp(OP_C(inst)); + + AddressA64 addr = tempAddrBuffer(OP_A(inst), OP_B(inst), tagOp(OP_D(inst))); + RegisterA64 base = regs.allocTemp(KindA64::x); + build.add(base, addr.base, uint16_t(addr.data)); + + build.str(castReg(KindA64::d, value), mem(base, 0)); // x, y + + if (intOp(OP_E(inst)) == 3) + { + RegisterA64 tempz = regs.allocTemp(KindA64::q); + build.dup_4s(tempz, value, 2); // broadcast lane 2 (z) + build.str(castReg(KindA64::s, tempz), mem(base, 8)); + } + break; + } + case IrCmd::BUFFER_READF64: { inst.regA64 = regs.allocReg(KindA64::d, index); @@ -3965,6 +4052,22 @@ void IrLoweringA64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) break; } + case IrCmd::BUFFER_READF32X4: + { + inst.regA64 = regs.allocReg(KindA64::q, index); + AddressA64 addr = tempAddrBuffer(OP_A(inst), OP_B(inst), tagOp(OP_C(inst))); + + build.ldr(inst.regA64, addr); + break; + } + case IrCmd::BUFFER_WRITEF32X4: + { + AddressA64 addr = tempAddrBuffer(OP_A(inst), OP_B(inst), tagOp(OP_D(inst))); + + build.str(regOp(OP_C(inst)), addr); + break; + } + case IrCmd::JUMP_CMP_PROTOID: { LUAU_ASSERT(OP_A(inst).kind == IrOpKind::Inst && OP_B(inst).kind == IrOpKind::Constant); diff --git a/CodeGen/src/IrLoweringX64.cpp b/CodeGen/src/IrLoweringX64.cpp index 44e75077c..8fec69da9 100644 --- a/CodeGen/src/IrLoweringX64.cpp +++ b/CodeGen/src/IrLoweringX64.cpp @@ -16,7 +16,9 @@ #include "lstate.h" #include "lgc.h" +LUAU_FASTFLAGVARIABLE(LuauCodegenMetatableCache) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) +LUAU_FASTFLAG(LuauCodegenMultiLaneDot) namespace Luau { @@ -97,16 +99,6 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.mov(inst.regX64, luauRegValueInt(vmRegOp(OP_A(inst)))); break; - case IrCmd::LOAD_INT64: - inst.regX64 = regs.allocReg(SizeX64::qword, index); - - if (OP_A(inst).kind == IrOpKind::VmReg) - build.mov(inst.regX64, luauRegValueInt64(vmRegOp(OP_A(inst)))); - else if (OP_A(inst).kind == IrOpKind::VmConst) - build.mov(inst.regX64, luauConstantValue(vmConstOp(OP_A(inst)))); - else - CODEGEN_ASSERT(!"Unsupported instruction form"); - break; case IrCmd::LOAD_FLOAT: inst.regX64 = regs.allocReg(SizeX64::xmmword, index); @@ -286,29 +278,6 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) else CODEGEN_ASSERT(!"Unsupported instruction form"); break; - case IrCmd::STORE_INT64: - if (OP_B(inst).kind == IrOpKind::Constant) - { - int64_t value = int64Op(OP_B(inst)); - - // x64 mov r/m64, imm32 sign-extends - // otherwise we use register for values outside that range - if (value >= INT32_MIN && value <= INT32_MAX) - { - build.mov(luauRegValueInt64(vmRegOp(OP_A(inst))), int32_t(value)); - } - else - { - ScopedRegX64 tmp{regs, SizeX64::qword}; - build.mov64(tmp.reg, value); - build.mov(luauRegValueInt64(vmRegOp(OP_A(inst))), tmp.reg); - } - } - else if (OP_B(inst).kind == IrOpKind::Inst) - build.mov(luauRegValueInt64(vmRegOp(OP_A(inst))), regOp(OP_B(inst))); - else - CODEGEN_ASSERT(!"Unsupported instruction form"); - break; case IrCmd::STORE_VECTOR: storeFloat(luauRegValueVector(vmRegOp(OP_A(inst)), 0), OP_B(inst)); storeFloat(luauRegValueVector(vmRegOp(OP_A(inst)), 1), OP_C(inst)); @@ -360,32 +329,6 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.vmovsd(valueLhs, regOp(OP_C(inst))); } } - else if (tagOp(OP_B(inst)) == LUA_TINTEGER) - { - OperandX64 valueLhs = OP_A(inst).kind == IrOpKind::Inst ? qword[regOp(OP_A(inst)) + offsetof(TValue, value) + addrOffset] - : luauRegValueInt64(vmRegOp(OP_A(inst))); - - if (OP_C(inst).kind == IrOpKind::Constant) - { - int64_t value = int64Op(OP_C(inst)); - - // x64 mov r/m64, imm32 sign-extends - if (value >= INT32_MIN && value <= INT32_MAX) - { - build.mov(valueLhs, int32_t(value)); - } - else - { - ScopedRegX64 tmp{regs, SizeX64::qword}; - build.mov64(tmp.reg, value); - build.mov(valueLhs, tmp.reg); - } - } - else - { - build.mov(valueLhs, regOp(OP_C(inst))); - } - } else if (isGCO(tagOp(OP_B(inst)))) { OperandX64 valueLhs = OP_A(inst).kind == IrOpKind::Inst ? qword[regOp(OP_A(inst)) + offsetof(TValue, value) + addrOffset] @@ -1439,10 +1382,33 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) ScopedRegX64 tmp1{regs}; ScopedRegX64 tmp2{regs}; - RegisterX64 tmpa = vecOp(OP_A(inst), tmp1); - RegisterX64 tmpb = (OP_A(inst) == OP_B(inst)) ? tmpa : vecOp(OP_B(inst), tmp2); + if (FFlag::LuauCodegenMultiLaneDot) + { + int lanes = intOp(OP_C(inst)); + CODEGEN_ASSERT(lanes == 3 || lanes == 4); + + if (lanes == 4) + { + RegisterX64 tmpa = regOp(OP_A(inst)); + RegisterX64 tmpb = (OP_A(inst) == OP_B(inst)) ? tmpa : regOp(OP_B(inst)); + + build.vdpps(inst.regX64, tmpa, tmpb, lanes == 4 ? 0xf1 : 0x71); // 0xf = 0b0111, sum all 4 products into first float + } + else + { + RegisterX64 tmpa = vecOp(OP_A(inst), tmp1); + RegisterX64 tmpb = (OP_A(inst) == OP_B(inst)) ? tmpa : vecOp(OP_B(inst), tmp2); + + build.vdpps(inst.regX64, tmpa, tmpb, 0x71); // 0x7 = 0b0111, sum first 3 products into first float + } + } + else + { + RegisterX64 tmpa = vecOp(OP_A(inst), tmp1); + RegisterX64 tmpb = (OP_A(inst) == OP_B(inst)) ? tmpa : vecOp(OP_B(inst), tmp2); - build.vdpps(inst.regX64, tmpa, tmpb, 0x71); // 7 = 0b0111, sum first 3 products into first float + build.vdpps(inst.regX64, tmpa, tmpb, 0x71); // 7 = 0b0111, sum first 3 products into first float + } break; } case IrCmd::EXTRACT_VEC: @@ -1676,17 +1642,6 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) } } } - else if (tagOp(OP_B(inst)) == LUA_TINTEGER) - { - if (OP_C(inst).kind == IrOpKind::Constant) - build.cmp(regOp(OP_D(inst)), memRegInt64Op(OP_C(inst))); // swapped arguments - else if (OP_D(inst).kind == IrOpKind::Constant) - build.cmp(regOp(OP_C(inst)), memRegInt64Op(OP_D(inst))); - else - build.cmp(regOp(OP_C(inst)), regOp(OP_D(inst))); - - build.setcc(getConditionInt(cond), byteReg(inst.regX64)); - } else { CODEGEN_ASSERT(!"unsupported type tag in CMP_SPLIT_TVALUE"); @@ -1916,11 +1871,28 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.jcc(ConditionX64::NotZero, labelOp(OP_C(inst))); // No tag method ScopedRegX64 tmp2{regs, SizeX64::qword}; - build.mov(tmp2.reg, qword[rState + offsetof(lua_State, global)]); + + if (!FFlag::LuauCodegenMetatableCache) + build.mov(tmp2.reg, qword[rState + offsetof(lua_State, global)]); + + Label done; { ScopedSpills spillGuard(regs); + if (FFlag::LuauCodegenMetatableCache) + { + Label uncached; + build.test(byte[tmp.reg + offsetof(LuaTable, readonly)], 2); + build.jcc(ConditionX64::Zero, uncached); + build.mov(inst.regX64, qword[tmp.reg + offsetof(LuaTable, array)]); + build.lea(inst.regX64, addr[inst.regX64 - int32_t((1 + intOp(OP_B(inst))) * sizeof(TValue))]); + build.jmp(done); + build.setLabel(uncached); + + build.mov(tmp2.reg, qword[rState + offsetof(lua_State, global)]); + } + IrCallWrapperX64 callWrap(regs, build, index); callWrap.addArgument(SizeX64::qword, tmp); callWrap.addArgument(SizeX64::qword, intOp(OP_B(inst))); @@ -1931,6 +1903,9 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.test(inst.regX64, inst.regX64); build.jcc(ConditionX64::Zero, labelOp(OP_C(inst))); // No tag method + + if (FFlag::LuauCodegenMetatableCache) + build.setLabel(done); break; } case IrCmd::NEW_USERDATA: @@ -2038,6 +2013,11 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.vpinsrd(inst.regX64, regOp(OP_A(inst)), build.i32(LUA_TVECTOR), 3); break; + case IrCmd::UNTAG_VECTOR: + inst.regX64 = regs.allocRegOrReuse(SizeX64::xmmword, index, {OP_A(inst)}); + + build.vandps(inst.regX64, regOp(OP_A(inst)), vectorAndMaskOp()); + break; case IrCmd::TRUNCATE_UINT: inst.regX64 = regs.allocRegOrReuse(SizeX64::dword, index, {OP_A(inst)}); @@ -2190,6 +2170,23 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) build.setLabel(cont); break; } + case IrCmd::INVOKE_NAMECALL: + { + regs.assertAllFree(); + regs.assertNoSpills(); + + emitFallback(regs, build, offsetof(NativeContext, callNamecall), uintOp(OP_A(inst))); + + Label complete; + build.test(rax, rax); + build.jcc(ConditionX64::Zero, complete); + build.test(al, 1); // Check for CALL_FALLBACK_YIELD using lowest bit (closure pointers are aligned so it is never set for them) + build.jcc(ConditionX64::NotZero, helpers.exitNoContinueVm); + emitDispatchLuauCall(build, helpers); + + build.setLabel(complete); + break; + } case IrCmd::DO_ARITH: { OperandX64 opb = OP_B(inst).kind == IrOpKind::VmReg ? luauRegAddress(vmRegOp(OP_B(inst))) : luauConstantAddress(vmConstOp(OP_B(inst))); @@ -3309,6 +3306,35 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) storeFloat(dword[bufferAddrOp(OP_A(inst), OP_B(inst), tagOp(OP_D(inst)))], OP_C(inst)); break; + case IrCmd::BUFFER_READVECTOR: + { + CODEGEN_ASSERT(intOp(OP_D(inst)) == 2 || intOp(OP_D(inst)) == 3); + inst.regX64 = regs.allocReg(SizeX64::xmmword, index); + + // vmovsd loads x,y into the low 64 bits and zeroes the upper lanes, so a 2-component read is already [x, y, 0, 0] + build.vmovsd(inst.regX64, qword[bufferAddrOp(OP_A(inst), OP_B(inst), tagOp(OP_C(inst)))]); + + if (intOp(OP_D(inst)) == 3) + build.vpinsrd(inst.regX64, inst.regX64, dword[bufferAddrOp(OP_A(inst), OP_B(inst), tagOp(OP_C(inst))) + 8], 2); + break; + } + + case IrCmd::BUFFER_WRITEVECTOR: + { + CODEGEN_ASSERT(intOp(OP_E(inst)) == 2 || intOp(OP_E(inst)) == 3); + RegisterX64 value = regOp(OP_C(inst)); + + build.vmovsd(qword[bufferAddrOp(OP_A(inst), OP_B(inst), tagOp(OP_D(inst)))], value); // x, y + + if (intOp(OP_E(inst)) == 3) + { + ScopedRegX64 tmp{regs, SizeX64::xmmword}; + build.vpshufps(tmp.reg, value, value, 0b10); // move lane 2 (z) into lane 0 + build.vmovss(dword[bufferAddrOp(OP_A(inst), OP_B(inst), tagOp(OP_D(inst))) + 8], tmp.reg); + } + break; + } + case IrCmd::BUFFER_READF64: inst.regX64 = regs.allocReg(SizeX64::xmmword, index); @@ -3355,6 +3381,15 @@ void IrLoweringX64::lowerInst(IrInst& inst, uint32_t index, const IrBlock& next) CODEGEN_ASSERT(!"Unsupported instruction form"); } break; + case IrCmd::BUFFER_READF32X4: + inst.regX64 = regs.allocReg(SizeX64::xmmword, index); + + build.vmovups(inst.regX64, xmmword[bufferAddrOp(OP_A(inst), OP_B(inst), tagOp(OP_C(inst)))]); + break; + case IrCmd::BUFFER_WRITEF32X4: + + build.vmovups(xmmword[bufferAddrOp(OP_A(inst), OP_B(inst), tagOp(OP_D(inst)))], regOp(OP_C(inst))); + break; case IrCmd::CHECK_DIV_INT64: { @@ -4188,10 +4223,6 @@ OperandX64 IrLoweringX64::memRegInt64Op(IrOp op) return regOp(op); case IrOpKind::Constant: return build.i64(int64Op(op)); - case IrOpKind::VmReg: - return luauRegValueInt64(vmRegOp(op)); - case IrOpKind::VmConst: - return luauConstantValue(vmConstOp(op)); default: CODEGEN_ASSERT(!"Unsupported operand kind"); } diff --git a/CodeGen/src/IrRegAllocA64.cpp b/CodeGen/src/IrRegAllocA64.cpp index e0e1a23e1..66875e2f0 100644 --- a/CodeGen/src/IrRegAllocA64.cpp +++ b/CodeGen/src/IrRegAllocA64.cpp @@ -69,6 +69,7 @@ static int getReloadOffset(IrValueKind kind) case IrValueKind::Unknown: case IrValueKind::None: case IrValueKind::Float: + case IrValueKind::Int64: case IrValueKind::Count: CODEGEN_ASSERT(!"Invalid operand restore value kind"); break; @@ -76,8 +77,6 @@ static int getReloadOffset(IrValueKind kind) return offsetof(TValue, tt); case IrValueKind::Int: return offsetof(TValue, value); - case IrValueKind::Int64: - return offsetof(TValue, value.l); case IrValueKind::Pointer: return offsetof(TValue, value.gc); case IrValueKind::Double: diff --git a/CodeGen/src/IrRegAllocX64.cpp b/CodeGen/src/IrRegAllocX64.cpp index f7d430bff..bd74a73df 100644 --- a/CodeGen/src/IrRegAllocX64.cpp +++ b/CodeGen/src/IrRegAllocX64.cpp @@ -683,10 +683,9 @@ OperandX64 IrRegAllocX64::getRestoreAddress(const IrInst& inst, ValueRestoreLoca case IrValueKind::Unknown: case IrValueKind::None: case IrValueKind::Float: + case IrValueKind::Int64: case IrValueKind::Count: break; - case IrValueKind::Int64: - return restoreLocation.op.kind == IrOpKind::VmReg ? luauRegValueInt64(vmRegOp(op)) : luauConstantValue(vmConstOp(op)); case IrValueKind::Tag: return op.kind == IrOpKind::VmReg ? luauRegTag(vmRegOp(op)) : luauConstantTag(vmConstOp(op)); case IrValueKind::Int: diff --git a/CodeGen/src/IrTranslateBuiltins.cpp b/CodeGen/src/IrTranslateBuiltins.cpp index 010ff5427..748addc73 100644 --- a/CodeGen/src/IrTranslateBuiltins.cpp +++ b/CodeGen/src/IrTranslateBuiltins.cpp @@ -9,8 +9,7 @@ #include -LUAU_FASTFLAG(LuauCodegenInteger3) -LUAU_FASTFLAGVARIABLE(LuauCodegenBufferInteger) +LUAU_FASTFLAGVARIABLE(LuauCodegenMultiLaneDot) // TODO: when nresults is less than our actual result count, we can skip computing/writing unused results @@ -22,11 +21,6 @@ namespace Luau namespace CodeGen { -static bool isCompatibleConstant(IrBuilder& build, IrOp arg, IrConstKind expected) -{ - return arg.kind != IrOpKind::Constant || build.function.constOp(arg).kind == expected; -} - static void builtinCheckDouble(IrBuilder& build, IrOp arg, int pcpos) { if (arg.kind == IrOpKind::Constant) @@ -43,22 +37,6 @@ static IrOp builtinLoadDouble(IrBuilder& build, IrOp arg) return build.inst(IrCmd::LOAD_DOUBLE, arg); } -static void builtinCheckInt64(IrBuilder& build, IrOp arg, int pcpos) -{ - if (arg.kind == IrOpKind::Constant) - CODEGEN_ASSERT(build.function.constOp(arg).kind == IrConstKind::Int64); - else - build.loadAndCheckTag(arg, LUA_TINTEGER, build.vmExit(pcpos)); -} - -static IrOp builtinLoadInt64(IrBuilder& build, IrOp arg) -{ - if (arg.kind == IrOpKind::Constant) - return arg; - - return build.inst(IrCmd::LOAD_INT64, arg); -} - // Wrapper code for all builtins with a fixed signature and manual assembly lowering of the body static BuiltinImplResult translateBuiltinNumberToNumberLibm( @@ -934,20 +912,14 @@ static void translateBufferArgsAndCheckBounds( int size, int pcpos, IrOp& buf, - IrOp& intIndex, - bool loadInt64 = false + IrOp& intIndex ) { build.loadAndCheckTag(build.vmReg(arg), LUA_TBUFFER, build.vmExit(pcpos)); builtinCheckDouble(build, args, pcpos); if (nparams >= 3) - { - if (loadInt64) - builtinCheckInt64(build, arg3, pcpos); - else - builtinCheckDouble(build, arg3, pcpos); - } + builtinCheckDouble(build, arg3, pcpos); buf = build.inst(IrCmd::LOAD_POINTER, build.vmReg(arg)); @@ -968,21 +940,19 @@ static BuiltinImplResult translateBuiltinBufferRead( int pcpos, IrCmd readCmd, int size, - IrCmd convCmd, - IrCmd storeCmd = IrCmd::STORE_DOUBLE, - uint8_t storeTag = LUA_TNUMBER + IrCmd convCmd ) { if (nparams < 2 || nresults > 1) return {BuiltinImplType::None, -1}; IrOp buf, intIndex; - translateBufferArgsAndCheckBounds(build, nparams, arg, args, arg3, size, pcpos, buf, intIndex, false); + translateBufferArgsAndCheckBounds(build, nparams, arg, args, arg3, size, pcpos, buf, intIndex); IrOp result = build.inst(readCmd, buf, intIndex, build.constTag(LUA_TBUFFER)); - build.inst(storeCmd, build.vmReg(ra), convCmd == IrCmd::NOP ? result : build.inst(convCmd, result)); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(storeTag)); + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(ra), convCmd == IrCmd::NOP ? result : build.inst(convCmd, result)); + build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TNUMBER)); return {BuiltinImplType::Full, 1}; } @@ -998,23 +968,113 @@ static BuiltinImplResult translateBuiltinBufferWrite( int pcpos, IrCmd writeCmd, int size, - IrCmd convCmd, - bool loadInt64 = false + IrCmd convCmd ) { if (nparams < 3 || nresults > 0) return {BuiltinImplType::None, -1}; IrOp buf, intIndex; - translateBufferArgsAndCheckBounds(build, nparams, arg, args, arg3, size, pcpos, buf, intIndex, loadInt64); + translateBufferArgsAndCheckBounds(build, nparams, arg, args, arg3, size, pcpos, buf, intIndex); - IrOp numValue = loadInt64 ? builtinLoadInt64(build, arg3) : builtinLoadDouble(build, arg3); + IrOp numValue = builtinLoadDouble(build, arg3); build.inst(writeCmd, buf, intIndex, convCmd == IrCmd::NOP ? numValue : build.inst(convCmd, numValue), build.constTag(LUA_TBUFFER)); return {BuiltinImplType::Full, 0}; } +// buffer.readvectorf32x{2,3}: read 'count' contiguous f32 components and construct a vector (missing components are zeroed). +static BuiltinImplResult translateBuiltinBufferReadVector( + IrBuilder& build, + int nparams, + int ra, + int arg, + IrOp args, + IrOp arg3, + int nresults, + int pcpos, + int count +) +{ + if (nparams < 2 || nresults > 1) + return {BuiltinImplType::None, -1}; + + IrOp buf, intIndex; + translateBufferArgsAndCheckBounds(build, nparams, arg, args, arg3, count * 4, pcpos, buf, intIndex); + + if constexpr (LUA_VECTOR_DOUBLE == 1) + { + // vector components are stored as doubles; there is no single wide move, so read each f32 lane and widen + IrOp xd = build.inst(IrCmd::FLOAT_TO_NUM, build.inst(IrCmd::BUFFER_READF32, buf, intIndex, build.constTag(LUA_TBUFFER))); + IrOp yd = build.inst( + IrCmd::FLOAT_TO_NUM, build.inst(IrCmd::BUFFER_READF32, buf, build.inst(IrCmd::ADD_INT, intIndex, build.constInt(4)), build.constTag(LUA_TBUFFER)) + ); + IrOp zd = count >= 3 ? build.inst( + IrCmd::FLOAT_TO_NUM, + build.inst(IrCmd::BUFFER_READF32, buf, build.inst(IrCmd::ADD_INT, intIndex, build.constInt(8)), build.constTag(LUA_TBUFFER)) + ) + : build.constDouble(0.0); + build.inst(IrCmd::STORE_POINTER, build.vmReg(ra), build.inst(IrCmd::NEW_VECTOR, xd, yd, zd)); + build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TVECTOR)); + } + else + { + IrOp vec = build.inst(IrCmd::BUFFER_READVECTOR, buf, intIndex, build.constTag(LUA_TBUFFER), build.constInt(count)); + build.inst(IrCmd::STORE_TVALUE, build.vmReg(ra), build.inst(IrCmd::TAG_VECTOR, vec)); + } + + return {BuiltinImplType::Full, 1}; +} + +// buffer.writevectorf32x{2,3}: write 'count' contiguous f32 components from a vector argument. +static BuiltinImplResult translateBuiltinBufferWriteVector( + IrBuilder& build, + int nparams, + int ra, + int arg, + IrOp args, + IrOp arg3, + int nresults, + int pcpos, + int count +) +{ + if (nparams < 3 || nresults > 0 || arg3.kind == IrOpKind::Constant) + return {BuiltinImplType::None, -1}; + + build.loadAndCheckTag(build.vmReg(arg), LUA_TBUFFER, build.vmExit(pcpos)); + builtinCheckDouble(build, args, pcpos); + build.loadAndCheckTag(arg3, LUA_TVECTOR, build.vmExit(pcpos)); + + IrOp buf = build.inst(IrCmd::LOAD_POINTER, build.vmReg(arg)); + + IrOp numIndex = builtinLoadDouble(build, args); + IrOp intIndex = build.inst(IrCmd::NUM_TO_INT, numIndex); + + build.inst(IrCmd::CHECK_BUFFER_LEN, buf, intIndex, build.constInt(0), build.constInt(count * 4), build.undef(), build.vmExit(pcpos)); + + if constexpr (LUA_VECTOR_DOUBLE == 1) + { + // vector components are stored as doubles; narrow each to f32 and write the lanes individually + IrOp vptr = build.inst(IrCmd::LOAD_POINTER, arg3); + for (int i = 0; i < count; i++) + { + IrOp component = + build.inst(IrCmd::NUM_TO_FLOAT, build.inst(IrCmd::BUFFER_READF64, vptr, build.constInt(i * 8), build.constTag(LUA_TVECTOR))); + IrOp offset = i == 0 ? intIndex : build.inst(IrCmd::ADD_INT, intIndex, build.constInt(i * 4)); + build.inst(IrCmd::BUFFER_WRITEF32, buf, offset, component, build.constTag(LUA_TBUFFER)); + } + } + else + { + IrOp vec = build.inst(IrCmd::LOAD_TVALUE, arg3); + build.inst(IrCmd::BUFFER_WRITEVECTOR, buf, intIndex, vec, build.constTag(LUA_TBUFFER), build.constInt(count)); + } + + return {BuiltinImplType::Full, 0}; +} + static BuiltinImplResult translateBuiltinVectorMagnitude( IrBuilder& build, int nparams, @@ -1054,7 +1114,7 @@ static BuiltinImplResult translateBuiltinVectorMagnitude( { IrOp a = build.inst(IrCmd::LOAD_TVALUE, arg1, build.constInt(0)); - IrOp sum = build.inst(IrCmd::DOT_VEC, a, a); + IrOp sum = FFlag::LuauCodegenMultiLaneDot ? build.inst(IrCmd::DOT_VEC, a, a, build.constInt(3)) : build.inst(IrCmd::DOT_VEC, a, a); IrOp mag = build.inst(IrCmd::SQRT_FLOAT, sum); mag = build.inst(IrCmd::FLOAT_TO_NUM, mag); @@ -1109,7 +1169,7 @@ static BuiltinImplResult translateBuiltinVectorNormalize( else { IrOp a = build.inst(IrCmd::LOAD_TVALUE, arg1, build.constInt(0)); - IrOp sum = build.inst(IrCmd::DOT_VEC, a, a); + IrOp sum = FFlag::LuauCodegenMultiLaneDot ? build.inst(IrCmd::DOT_VEC, a, a, build.constInt(3)) : build.inst(IrCmd::DOT_VEC, a, a); IrOp mag = build.inst(IrCmd::SQRT_FLOAT, sum); IrOp inv = build.inst(IrCmd::DIV_FLOAT, build.constDouble(1.0f), mag); @@ -1230,7 +1290,7 @@ static BuiltinImplResult translateBuiltinVectorDot(IrBuilder& build, int nparams IrOp a = build.inst(IrCmd::LOAD_TVALUE, arg1, build.constInt(0)); IrOp b = build.inst(IrCmd::LOAD_TVALUE, args, build.constInt(0)); - IrOp sum = build.inst(IrCmd::DOT_VEC, a, b); + IrOp sum = FFlag::LuauCodegenMultiLaneDot ? build.inst(IrCmd::DOT_VEC, a, b, build.constInt(3)) : build.inst(IrCmd::DOT_VEC, a, b); sum = build.inst(IrCmd::FLOAT_TO_NUM, sum); @@ -1498,462 +1558,6 @@ static BuiltinImplResult translateBuiltinVectorMinMax( return {BuiltinImplType::Full, 1}; } -static BuiltinImplResult translateBuiltinInt64Create( - IrBuilder& build, - int nparams, - int ra, - int arg, // arg contains the LUA_TNUMBER representing the int64 to create - int nresults, - int pcpos -) -{ - if (nparams < 1 || nresults > 1) - return {BuiltinImplType::None, -1}; - - IrOp argReg = build.vmReg(arg); - builtinCheckDouble(build, argReg, pcpos); - - IrOp argValue = builtinLoadDouble(build, build.vmReg(arg)); - - IrOp integerValue = build.inst(IrCmd::NUM_TO_INT64, argValue); - // roundtrip check: ((double)l) == x - IrOp backToDouble = build.inst(IrCmd::INT64_TO_NUM, integerValue); - - build.inst(IrCmd::CHECK_CMP_NUM, backToDouble, argValue, build.cond(IrCondition::Equal), build.vmExit(pcpos)); - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), integerValue); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64ToNumber( - IrBuilder& build, - int nparams, - int ra, - int arg, // arg contains the int64 to cast to number - int nresults, - int pcpos -) -{ - if (nparams < 1 || nresults > 1) - return {BuiltinImplType::None, -1}; - - IrOp argReg = build.vmReg(arg); - builtinCheckInt64(build, argReg, pcpos); - IrOp argValue = builtinLoadInt64(build, argReg); - - build.inst(IrCmd::STORE_DOUBLE, build.vmReg(ra), build.inst(IrCmd::INT64_TO_NUM, argValue)); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TNUMBER)); - - return {BuiltinImplType::Full, 1}; -} - -enum class Int64Binary -{ - Add, - Sub, - Mul, - Div, - Idiv, - Udiv, - Rem, - Urem, - Mod, -}; - -static BuiltinImplResult translateBuiltinInt64Binary( - IrBuilder& build, - int nparams, - int ra, - int arg, - IrOp args, - int nresults, - int pcpos, - Int64Binary op -) -{ - if (nparams < 2 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - builtinCheckInt64(build, args, pcpos); - - IrOp va = builtinLoadInt64(build, build.vmReg(arg)); - IrOp vb = builtinLoadInt64(build, args); - - IrOp binOp; - switch (op) - { - case Int64Binary::Add: - binOp = build.inst(IrCmd::ADD_INT64, va, vb); - break; - - case Int64Binary::Sub: - binOp = build.inst(IrCmd::SUB_INT64, va, vb); - break; - case Int64Binary::Mul: - binOp = build.inst(IrCmd::MUL_INT64, va, vb); - break; - case Int64Binary::Div: - build.inst(IrCmd::CHECK_DIV_INT64, va, vb, build.vmExit(pcpos)); - binOp = build.inst(IrCmd::DIV_INT64, va, vb); - break; - case Int64Binary::Idiv: - build.inst(IrCmd::CHECK_DIV_INT64, va, vb, build.vmExit(pcpos)); - binOp = build.inst(IrCmd::IDIV_INT64, va, vb); - break; - case Int64Binary::Udiv: - build.inst(IrCmd::CHECK_CMP_INT64, vb, build.constInt64(0), build.cond(IrCondition::NotEqual), build.vmExit(pcpos)); - binOp = build.inst(IrCmd::UDIV_INT64, va, vb); - break; - case Int64Binary::Rem: - build.inst(IrCmd::CHECK_CMP_INT64, vb, build.constInt64(0), build.cond(IrCondition::NotEqual), build.vmExit(pcpos)); - // ARM64 sdiv wraps, producing rem=0. - binOp = build.inst(IrCmd::REM_INT64, va, vb); - break; - case Int64Binary::Urem: - build.inst(IrCmd::CHECK_CMP_INT64, vb, build.constInt64(0), build.cond(IrCondition::NotEqual), build.vmExit(pcpos)); - binOp = build.inst(IrCmd::UREM_INT64, va, vb); - break; - case Int64Binary::Mod: - build.inst(IrCmd::CHECK_CMP_INT64, vb, build.constInt64(0), build.cond(IrCondition::NotEqual), build.vmExit(pcpos)); - // ARM64 sdiv wraps, producing mod=0. - binOp = build.inst(IrCmd::MOD_INT64, va, vb); - break; - default: - CODEGEN_ASSERT(!"Unhandled Int64Binary kind"); - } - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), binOp); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64MinMax( - IrBuilder& build, - int nparams, - int ra, - int arg, - IrOp args, - IrOp arg3, - int nresults, - int pcpos, - bool min -) -{ - if (nparams < 2 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - builtinCheckInt64(build, args, pcpos); - - if (nparams >= 3) - builtinCheckInt64(build, arg3, pcpos); - - for (int i = 4; i <= nparams; ++i) - builtinCheckInt64(build, build.vmReg(vmRegOp(args) + (i - 2)), pcpos); - - IrOp va = builtinLoadInt64(build, build.vmReg(arg)); - IrOp vb = builtinLoadInt64(build, args); - - IrOp cond = min ? build.cond(IrCondition::LessEqual) : build.cond(IrCondition::Greater); - - // vb < va ? vb : va - IrOp selectOp = build.inst(IrCmd::SELECT_INT64, va, vb, vb, va, cond); - - if (nparams >= 3) - { - IrOp vc = builtinLoadInt64(build, arg3); - - selectOp = build.inst(IrCmd::SELECT_INT64, vc, selectOp, selectOp, vc, cond); - } - - for (int i = 4; i <= nparams; ++i) - { - IrOp vc = builtinLoadInt64(build, build.vmReg(vmRegOp(args) + (i - 2))); - - selectOp = build.inst(IrCmd::SELECT_INT64, vc, selectOp, selectOp, vc, cond); - } - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), selectOp); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64Neg(IrBuilder& build, int nparams, int ra, int arg, int nresults, int pcpos) -{ - if (nparams != 1 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - - IrOp va = builtinLoadInt64(build, build.vmReg(arg)); - IrOp result = build.inst(IrCmd::SUB_INT64, build.constInt64(0), va); - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), result); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - -// TODO: tune this -static const int kInt64BinaryOpUnrolledParams = 5; - -static BuiltinImplResult translateBuiltinInt64MultiargOp( - IrBuilder& build, - IrCmd cmd, - bool btest, - int64_t identity, - int nparams, - int ra, - int arg, - IrOp args, - IrOp arg3, - int nresults, - int pcpos -) -{ - if (nparams > kInt64BinaryOpUnrolledParams || nresults > 1) - return {BuiltinImplType::None, -1}; - - if (nparams == 0) - { - if (btest) - { - // btest() with no args: identity is -1 (all bits), -1 != 0 -> true (1) - build.inst(IrCmd::STORE_INT, build.vmReg(ra), build.constInt(1)); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TBOOLEAN)); - } - else - { - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), build.constInt64(identity)); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - } - return {BuiltinImplType::Full, 1}; - } - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - - if (nparams >= 2) - builtinCheckInt64(build, args, pcpos); - - if (nparams >= 3) - builtinCheckInt64(build, arg3, pcpos); - - for (int i = 4; i <= nparams; ++i) - builtinCheckInt64(build, build.vmReg(vmRegOp(args) + (i - 2)), pcpos); - - IrOp res = builtinLoadInt64(build, build.vmReg(arg)); - - if (nparams >= 2) - { - IrOp vb = builtinLoadInt64(build, args); - res = build.inst(cmd, res, vb); - } - - if (nparams >= 3) - { - IrOp vc = builtinLoadInt64(build, arg3); - res = build.inst(cmd, res, vc); - } - - for (int i = 4; i <= nparams; ++i) - { - IrOp vc = builtinLoadInt64(build, build.vmReg(vmRegOp(args) + (i - 2))); - res = build.inst(cmd, res, vc); - } - - if (btest) - { - IrOp result = build.inst(IrCmd::CMP_INT64, res, build.constInt64(0), build.cond(IrCondition::NotEqual)); - build.inst(IrCmd::STORE_INT, build.vmReg(ra), result); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TBOOLEAN)); - } - else - { - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), res); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - } - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64Extract(IrBuilder& build, int nparams, int ra, int arg, IrOp args, IrOp arg3, int nresults, int pcpos) -{ - if (nparams < 2 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - builtinCheckInt64(build, args, pcpos); - - IrOp n = builtinLoadInt64(build, build.vmReg(arg)); - IrOp f = builtinLoadInt64(build, args); - - IrOp value; - if (nparams == 2) - { - // extract(n, f): extract single bit at position f - // f >= 0 && f <= 63 - build.inst(IrCmd::CHECK_CMP_INT64, f, build.constInt64(0), build.cond(IrCondition::GreaterEqual), build.vmExit(pcpos)); - build.inst(IrCmd::CHECK_CMP_INT64, f, build.constInt64(63), build.cond(IrCondition::LessEqual), build.vmExit(pcpos)); - - IrOp shifted = build.inst(IrCmd::BITRSHIFT_INT64, n, f); - value = build.inst(IrCmd::BITAND_INT64, shifted, build.constInt64(1)); - } - else - { - // extract(n, f, w): extract w bits starting at position f - builtinCheckInt64(build, arg3, pcpos); - IrOp w = builtinLoadInt64(build, arg3); - IrOp fw = build.inst(IrCmd::ADD_INT64, f, w); - - // f >= 0 && f <= 63 && w >= 1 && f + w <= 64 - build.inst(IrCmd::CHECK_CMP_INT64, f, build.constInt64(0), build.cond(IrCondition::GreaterEqual), build.vmExit(pcpos)); - build.inst(IrCmd::CHECK_CMP_INT64, f, build.constInt64(63), build.cond(IrCondition::LessEqual), build.vmExit(pcpos)); - build.inst(IrCmd::CHECK_CMP_INT64, w, build.constInt64(1), build.cond(IrCondition::GreaterEqual), build.vmExit(pcpos)); - build.inst(IrCmd::CHECK_CMP_INT64, w, build.constInt64(64), build.cond(IrCondition::LessEqual), build.vmExit(pcpos)); - build.inst(IrCmd::CHECK_CMP_INT64, fw, build.constInt64(64), build.cond(IrCondition::LessEqual), build.vmExit(pcpos)); - - // mask = 0xFFFFFFFFFFFFFFFF >> (64 - w) - IrOp shiftAmount = build.inst(IrCmd::SUB_INT64, build.constInt64(64), w); - IrOp mask = build.inst(IrCmd::BITRSHIFT_INT64, build.constInt64(-1), shiftAmount); - - IrOp shifted = build.inst(IrCmd::BITRSHIFT_INT64, n, f); - value = build.inst(IrCmd::BITAND_INT64, shifted, mask); - } - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), value); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64Rotate(IrBuilder& build, IrCmd cmd, int nparams, int ra, int arg, IrOp args, int nresults, int pcpos) -{ - if (nparams < 2 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - builtinCheckInt64(build, args, pcpos); - - IrOp va = builtinLoadInt64(build, build.vmReg(arg)); - IrOp vb = builtinLoadInt64(build, args); - - IrOp result = build.inst(cmd, va, vb); - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), result); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64Unary(IrBuilder& build, IrCmd cmd, int nparams, int ra, int arg, int nresults, int pcpos) -{ - if (nparams < 1 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - - IrOp va = builtinLoadInt64(build, build.vmReg(arg)); - IrOp result = build.inst(cmd, va); - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), result); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64Shift(IrBuilder& build, IrCmd cmd, int nparams, int ra, int arg, IrOp args, int nresults, int pcpos) -{ - if (nparams < 2 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - builtinCheckInt64(build, args, pcpos); - - IrOp va = builtinLoadInt64(build, build.vmReg(arg)); - IrOp vb = builtinLoadInt64(build, args); - - IrOp result = build.inst(cmd, va, vb); - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), result); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64Bnot(IrBuilder& build, int nparams, int ra, int arg, int nresults, int pcpos) -{ - if (nparams < 1 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - - IrOp va = builtinLoadInt64(build, build.vmReg(arg)); - IrOp result = build.inst(IrCmd::BITNOT_INT64, va); - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), result); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64Compare( - IrBuilder& build, - int nparams, - int ra, - int arg, - IrOp args, - int nresults, - int pcpos, - IrCondition cond -) -{ - if (nparams < 2 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - builtinCheckInt64(build, args, pcpos); - - IrOp va = builtinLoadInt64(build, build.vmReg(arg)); - IrOp vb = builtinLoadInt64(build, args); - - IrOp result = build.inst(IrCmd::CMP_INT64, va, vb, build.cond(cond)); - build.inst(IrCmd::STORE_INT, build.vmReg(ra), result); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TBOOLEAN)); - - return {BuiltinImplType::Full, 1}; -} - -static BuiltinImplResult translateBuiltinInt64Clamp(IrBuilder& build, int nparams, int ra, int arg, IrOp args, IrOp arg3, int nresults, int pcpos) -{ - if (nparams < 3 || nresults > 1) - return {BuiltinImplType::None, -1}; - - builtinCheckInt64(build, build.vmReg(arg), pcpos); - builtinCheckInt64(build, args, pcpos); - builtinCheckInt64(build, arg3, pcpos); - - IrOp val = builtinLoadInt64(build, build.vmReg(arg)); - IrOp mi = builtinLoadInt64(build, args); - IrOp mx = builtinLoadInt64(build, arg3); - - // guard: min <= max - build.inst(IrCmd::CHECK_CMP_INT64, mi, mx, build.cond(IrCondition::LessEqual), build.vmExit(pcpos)); - - // clamp: if val < min, use min; then if result > max, use max - IrOp clamped = build.inst(IrCmd::SELECT_INT64, val, mi, val, mi, build.cond(IrCondition::Less)); - IrOp result = build.inst(IrCmd::SELECT_INT64, clamped, mx, clamped, mx, build.cond(IrCondition::Greater)); - - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), result); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - - return {BuiltinImplType::Full, 1}; -} - BuiltinImplResult translateBuiltin( IrBuilder& build, int bfid, @@ -1971,104 +1575,6 @@ BuiltinImplResult translateBuiltin( if (nparams == LUA_MULTRET) return {BuiltinImplType::None, -1}; - if (FFlag::LuauCodegenInteger3 && (args.kind == IrOpKind::Constant || arg3.kind == IrOpKind::Constant)) - { - switch (bfid) - { - case LBF_MATH_MIN: - case LBF_MATH_MAX: - case LBF_MATH_POW: - case LBF_MATH_FMOD: - case LBF_MATH_ATAN2: - case LBF_MATH_LDEXP: - case LBF_MATH_LERP: - case LBF_MATH_CLAMP: - case LBF_BIT32_BAND: - case LBF_BIT32_BOR: - case LBF_BIT32_BXOR: - case LBF_BIT32_BTEST: - case LBF_BIT32_LSHIFT: - case LBF_BIT32_RSHIFT: - case LBF_BIT32_ARSHIFT: - case LBF_BIT32_LROTATE: - case LBF_BIT32_RROTATE: - case LBF_BIT32_EXTRACT: - case LBF_BIT32_EXTRACTK: - case LBF_BIT32_REPLACE: - case LBF_VECTOR: - case LBF_TABLE_INSERT: - case LBF_BUFFER_READI8: - case LBF_BUFFER_READU8: - case LBF_BUFFER_WRITEU8: - case LBF_BUFFER_READI16: - case LBF_BUFFER_READU16: - case LBF_BUFFER_WRITEU16: - case LBF_BUFFER_READI32: - case LBF_BUFFER_READU32: - case LBF_BUFFER_WRITEU32: - case LBF_BUFFER_READF32: - case LBF_BUFFER_WRITEF32: - case LBF_BUFFER_READF64: - case LBF_BUFFER_WRITEF64: - case LBF_BUFFER_READINTEGER: - if (!isCompatibleConstant(build, args, IrConstKind::Double)) - return {BuiltinImplType::None, -1}; - - if (!isCompatibleConstant(build, arg3, IrConstKind::Double)) - return {BuiltinImplType::None, -1}; - - break; - - case LBF_BUFFER_WRITEINTEGER: - if (!isCompatibleConstant(build, args, IrConstKind::Double)) - return {BuiltinImplType::None, -1}; - - if (!isCompatibleConstant(build, arg3, IrConstKind::Int64)) - return {BuiltinImplType::None, -1}; - - break; - - case LBF_INTEGER_ADD: - case LBF_INTEGER_SUB: - case LBF_INTEGER_MUL: - case LBF_INTEGER_DIV: - case LBF_INTEGER_IDIV: - case LBF_INTEGER_UDIV: - case LBF_INTEGER_REM: - case LBF_INTEGER_UREM: - case LBF_INTEGER_MOD: - case LBF_INTEGER_MIN: - case LBF_INTEGER_MAX: - case LBF_INTEGER_CLAMP: - case LBF_INTEGER_LT: - case LBF_INTEGER_LE: - case LBF_INTEGER_GT: - case LBF_INTEGER_GE: - case LBF_INTEGER_ULT: - case LBF_INTEGER_ULE: - case LBF_INTEGER_UGT: - case LBF_INTEGER_UGE: - case LBF_INTEGER_BAND: - case LBF_INTEGER_BOR: - case LBF_INTEGER_BXOR: - case LBF_INTEGER_BNOT: - case LBF_INTEGER_BTEST: - case LBF_INTEGER_LSHIFT: - case LBF_INTEGER_RSHIFT: - case LBF_INTEGER_ARSHIFT: - case LBF_INTEGER_LROTATE: - case LBF_INTEGER_RROTATE: - case LBF_INTEGER_EXTRACT: - if (!isCompatibleConstant(build, args, IrConstKind::Int64)) - return {BuiltinImplType::None, -1}; - - if (!isCompatibleConstant(build, arg3, IrConstKind::Int64)) - return {BuiltinImplType::None, -1}; - - break; - } - } - switch (bfid) { case LBF_ASSERT: @@ -2185,16 +1691,14 @@ BuiltinImplResult translateBuiltin( return translateBuiltinBufferRead(build, nparams, ra, arg, args, arg3, nresults, pcpos, IrCmd::BUFFER_READF64, 8, IrCmd::NOP); case LBF_BUFFER_WRITEF64: return translateBuiltinBufferWrite(build, nparams, ra, arg, args, arg3, nresults, pcpos, IrCmd::BUFFER_WRITEF64, 8, IrCmd::NOP); - case LBF_BUFFER_READINTEGER: - if (FFlag::LuauCodegenBufferInteger) - return translateBuiltinBufferRead( - build, nparams, ra, arg, args, arg3, nresults, pcpos, IrCmd::BUFFER_READI64, 8, IrCmd::NOP, IrCmd::STORE_INT64, LUA_TINTEGER - ); - return {BuiltinImplType::None, -1}; - case LBF_BUFFER_WRITEINTEGER: - if (FFlag::LuauCodegenBufferInteger) - return translateBuiltinBufferWrite(build, nparams, ra, arg, args, arg3, nresults, pcpos, IrCmd::BUFFER_WRITEI64, 8, IrCmd::NOP, true); - return {BuiltinImplType::None, -1}; + case LBF_BUFFER_READVECTORF32X2: + return translateBuiltinBufferReadVector(build, nparams, ra, arg, args, arg3, nresults, pcpos, 2); + case LBF_BUFFER_READVECTORF32X3: + return translateBuiltinBufferReadVector(build, nparams, ra, arg, args, arg3, nresults, pcpos, 3); + case LBF_BUFFER_WRITEVECTORF32X2: + return translateBuiltinBufferWriteVector(build, nparams, ra, arg, args, arg3, nresults, pcpos, 2); + case LBF_BUFFER_WRITEVECTORF32X3: + return translateBuiltinBufferWriteVector(build, nparams, ra, arg, args, arg3, nresults, pcpos, 3); case LBF_VECTOR_MAGNITUDE: return translateBuiltinVectorMagnitude(build, nparams, ra, arg, args, arg3, nresults, pcpos); case LBF_VECTOR_NORMALIZE: @@ -2225,154 +1729,6 @@ BuiltinImplResult translateBuiltin( return translateBuiltinMathLerp(build, nparams, ra, arg, args, arg3, nresults, fallback, pcpos); case LBF_MATH_ISNAN: return translateBuiltinMathIsNan(build, nparams, ra, arg, args, nresults, pcpos); - case LBF_INTEGER_CREATE: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Create(build, nparams, ra, arg, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_TONUMBER: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64ToNumber(build, nparams, ra, arg, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_ADD: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Binary(build, nparams, ra, arg, args, nresults, pcpos, Int64Binary::Add); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_SUB: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Binary(build, nparams, ra, arg, args, nresults, pcpos, Int64Binary::Sub); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_MUL: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Binary(build, nparams, ra, arg, args, nresults, pcpos, Int64Binary::Mul); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_DIV: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Binary(build, nparams, ra, arg, args, nresults, pcpos, Int64Binary::Div); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_IDIV: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Binary(build, nparams, ra, arg, args, nresults, pcpos, Int64Binary::Idiv); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_UDIV: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Binary(build, nparams, ra, arg, args, nresults, pcpos, Int64Binary::Udiv); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_REM: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Binary(build, nparams, ra, arg, args, nresults, pcpos, Int64Binary::Rem); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_UREM: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Binary(build, nparams, ra, arg, args, nresults, pcpos, Int64Binary::Urem); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_MOD: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Binary(build, nparams, ra, arg, args, nresults, pcpos, Int64Binary::Mod); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_MIN: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64MinMax(build, nparams, ra, arg, args, arg3, nresults, pcpos, true); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_MAX: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64MinMax(build, nparams, ra, arg, args, arg3, nresults, pcpos, false); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_NEG: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Neg(build, nparams, ra, arg, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_CLAMP: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Clamp(build, nparams, ra, arg, args, arg3, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_LT: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Compare(build, nparams, ra, arg, args, nresults, pcpos, IrCondition::Less); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_LE: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Compare(build, nparams, ra, arg, args, nresults, pcpos, IrCondition::LessEqual); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_GT: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Compare(build, nparams, ra, arg, args, nresults, pcpos, IrCondition::Greater); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_GE: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Compare(build, nparams, ra, arg, args, nresults, pcpos, IrCondition::GreaterEqual); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_ULT: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Compare(build, nparams, ra, arg, args, nresults, pcpos, IrCondition::UnsignedLess); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_ULE: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Compare(build, nparams, ra, arg, args, nresults, pcpos, IrCondition::UnsignedLessEqual); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_UGT: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Compare(build, nparams, ra, arg, args, nresults, pcpos, IrCondition::UnsignedGreater); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_UGE: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Compare(build, nparams, ra, arg, args, nresults, pcpos, IrCondition::UnsignedGreaterEqual); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_BAND: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64MultiargOp(build, IrCmd::BITAND_INT64, false, int64_t(-1), nparams, ra, arg, args, arg3, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_BOR: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64MultiargOp(build, IrCmd::BITOR_INT64, false, int64_t(0), nparams, ra, arg, args, arg3, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_BXOR: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64MultiargOp(build, IrCmd::BITXOR_INT64, false, int64_t(0), nparams, ra, arg, args, arg3, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_BNOT: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Bnot(build, nparams, ra, arg, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_BTEST: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64MultiargOp(build, IrCmd::BITAND_INT64, true, int64_t(-1), nparams, ra, arg, args, arg3, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_LSHIFT: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Shift(build, IrCmd::BITLSHIFT_INT64, nparams, ra, arg, args, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_RSHIFT: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Shift(build, IrCmd::BITRSHIFT_INT64, nparams, ra, arg, args, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_ARSHIFT: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Shift(build, IrCmd::BITARSHIFT_INT64, nparams, ra, arg, args, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_LROTATE: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Rotate(build, IrCmd::BITLROTATE_INT64, nparams, ra, arg, args, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_RROTATE: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Rotate(build, IrCmd::BITRROTATE_INT64, nparams, ra, arg, args, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_COUNTLZ: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Unary(build, IrCmd::BITCOUNTLZ_INT64, nparams, ra, arg, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_COUNTRZ: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Unary(build, IrCmd::BITCOUNTRZ_INT64, nparams, ra, arg, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_BSWAP: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Unary(build, IrCmd::BYTESWAP_INT64, nparams, ra, arg, nresults, pcpos); - return {BuiltinImplType::None, -1}; - case LBF_INTEGER_EXTRACT: - if (FFlag::LuauCodegenInteger3) - return translateBuiltinInt64Extract(build, nparams, ra, arg, args, arg3, nresults, pcpos); - return {BuiltinImplType::None, -1}; default: return {BuiltinImplType::None, -1}; } diff --git a/CodeGen/src/IrTranslation.cpp b/CodeGen/src/IrTranslation.cpp index 13852003f..28d996a73 100644 --- a/CodeGen/src/IrTranslation.cpp +++ b/CodeGen/src/IrTranslation.cpp @@ -12,10 +12,9 @@ #include "lstate.h" #include "ltm.h" -LUAU_FASTFLAG(LuauCodegenInteger3) -LUAU_FASTFLAGVARIABLE(LuauCodegenIntegerCompare) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) -LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauCodegenRuntimeFeedback) +LUAU_FASTFLAGVARIABLE(LuauCodegenUserdataDirect) namespace Luau { @@ -193,11 +192,6 @@ static void translateInstLoadConstant(IrBuilder& build, int ra, int k) build.inst(IrCmd::STORE_INT, build.vmReg(ra), build.constInt(protok.value.b)); build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TBOOLEAN)); } - else if (FFlag::LuauCodegenInteger3 && protok.tt == LUA_TINTEGER) - { - build.inst(IrCmd::STORE_INT64, build.vmReg(ra), build.constInt64(protok.value.l)); - build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TINTEGER)); - } else if (protok.tt == LUA_TNUMBER) { build.inst(IrCmd::STORE_DOUBLE, build.vmReg(ra), build.constDouble(protok.value.n)); @@ -289,25 +283,6 @@ void translateInstJumpIfEq(IrBuilder& build, const Instruction* pc, int pcpos, b build.beginBlock(fallback); } - // fast-path: integer (when both operands are expected to be an integer or are unknown) - else if (FFlag::LuauCodegenInteger3 && FFlag::LuauCodegenIntegerCompare && isExpectedOrUnknownBytecodeType(bcTypes.a, LBC_TYPE_INTEGER) && - isExpectedOrUnknownBytecodeType(bcTypes.b, LBC_TYPE_INTEGER)) - { - IrOp fallback = build.fallbackBlock(pcpos); - - IrOp ta = build.inst(IrCmd::LOAD_TAG, build.vmReg(ra)); - build.inst(IrCmd::CHECK_TAG, ta, build.constTag(LUA_TINTEGER), fallback); - - IrOp tb = build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)); - build.inst(IrCmd::CHECK_TAG, tb, build.constTag(LUA_TINTEGER), fallback); - - IrOp va = build.inst(IrCmd::LOAD_INT64, build.vmReg(ra)); - IrOp vb = build.inst(IrCmd::LOAD_INT64, build.vmReg(rb)); - - build.inst(IrCmd::JUMP_CMP_INT64, va, vb, build.cond(IrCondition::NotEqual), not_ ? target : next, not_ ? next : target); - - build.beginBlock(fallback); - } build.inst(IrCmd::SET_SAVEDPC, build.constUint(pcpos + 1)); @@ -372,49 +347,6 @@ void translateInstJumpIfEqShortcut(IrBuilder& build, const Instruction* pc, int // Note that if the number fast-path is not taken at all code that would have been in the fallback is actually the main path build.beginBlock(fallback); } - else if (FFlag::LuauCodegenInteger3 && isExpectedOrUnknownBytecodeType(bcTypes.a, LBC_TYPE_INTEGER) && - isExpectedOrUnknownBytecodeType(bcTypes.b, LBC_TYPE_INTEGER)) - { - IrOp ta = build.inst(IrCmd::LOAD_TAG, build.vmReg(ra)); - build.inst( - IrCmd::CHECK_TAG, - ta, - build.constTag(LUA_TINTEGER), - bcTypes.a == LBC_TYPE_INTEGER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) - ); - - IrOp tb = build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)); - build.inst( - IrCmd::CHECK_TAG, - tb, - build.constTag(LUA_TINTEGER), - bcTypes.b == LBC_TYPE_INTEGER ? build.vmExit(pcpos) : getInitializedFallback(build, fallback, pcpos) - ); - - IrOp va = build.inst(IrCmd::LOAD_INT64, build.vmReg(ra)); - IrOp vb = build.inst(IrCmd::LOAD_INT64, build.vmReg(rb)); - - IrOp result = build.inst( - IrCmd::CMP_SPLIT_TVALUE, - build.constTag(LUA_TINTEGER), - build.constTag(LUA_TINTEGER), - va, - vb, - build.cond(not_ ? IrCondition::NotEqual : IrCondition::Equal) - ); - - build.inst(IrCmd::STORE_INT, build.vmReg(rr), result); - build.inst(IrCmd::STORE_TAG, build.vmReg(rr), build.constTag(LUA_TBOOLEAN)); - build.inst(IrCmd::JUMP, next); - - // If we don't need a fallback, we are done - if (fallback.kind == IrOpKind::None) - return; - - // Otherwise, start the fallback block - // Note that if the number fast-path is not taken at all code that would have been in the fallback is actually the main path - build.beginBlock(fallback); - } build.inst(IrCmd::SET_SAVEDPC, build.constUint(pcpos + 1)); @@ -714,17 +646,17 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, BytecodeTypes bcTypes = build.function.getBytecodeTypesAt(pcpos); - LuauBytecodeType recordedA = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; - LuauBytecodeType recordedB = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.b, pcpos, rc) : LBC_TYPE_ANY; + LuauBytecodeType recordedA = FFlag::LuauCodegenRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; + LuauBytecodeType recordedB = FFlag::LuauCodegenRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.b, pcpos, rc) : LBC_TYPE_ANY; - bool vectorA = bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedA == LBC_TYPE_VECTOR); - bool vectorB = bcTypes.b == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedB == LBC_TYPE_VECTOR); + bool vectorA = bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauCodegenRuntimeFeedback && recordedA == LBC_TYPE_VECTOR); + bool vectorB = bcTypes.b == LBC_TYPE_VECTOR || (FFlag::LuauCodegenRuntimeFeedback && recordedB == LBC_TYPE_VECTOR); // Special fast-paths for vectors, matching the cases we have in VM - if ((FFlag::LuauRuntimeFeedback ? vectorA && vectorB : bcTypes.a == LBC_TYPE_VECTOR && bcTypes.b == LBC_TYPE_VECTOR) && + if ((FFlag::LuauCodegenRuntimeFeedback ? vectorA && vectorB : bcTypes.a == LBC_TYPE_VECTOR && bcTypes.b == LBC_TYPE_VECTOR) && (tm == TM_ADD || tm == TM_SUB || tm == TM_MUL || tm == TM_DIV || tm == TM_IDIV)) { - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { checkArithOperandTag(build, fallback, rb, LUA_TVECTOR, bcTypes.a, pcpos); checkArithOperandTag(build, fallback, rc, LUA_TVECTOR, bcTypes.b, pcpos); @@ -817,16 +749,16 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, build.inst(IrCmd::STORE_TVALUE, build.vmReg(ra), result); } - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) translateBinaryNumericFallbackIfRequired(build, fallback, ra, opb, opc, tm, pcpos); return; } else if (!isUserdataBytecodeType(bcTypes.a) && - (FFlag::LuauRuntimeFeedback ? !isGenericArithFeedback(recordedA) && vectorB : bcTypes.b == LBC_TYPE_VECTOR) && + (FFlag::LuauCodegenRuntimeFeedback ? !isGenericArithFeedback(recordedA) && vectorB : bcTypes.b == LBC_TYPE_VECTOR) && (tm == TM_MUL || tm == TM_DIV || tm == TM_IDIV)) { - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { if (rb != -1) checkArithOperandTag(build, fallback, rb, LUA_TNUMBER, bcTypes.a, pcpos); @@ -902,11 +834,11 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, translateBinaryNumericFallbackIfRequired(build, fallback, ra, opb, opc, tm, pcpos); return; } - else if ((FFlag::LuauRuntimeFeedback ? vectorA && !isUserdataBytecodeType(bcTypes.b) && !isGenericArithFeedback(recordedB) - : bcTypes.a == LBC_TYPE_VECTOR && !isUserdataBytecodeType(bcTypes.b)) && + else if ((FFlag::LuauCodegenRuntimeFeedback ? vectorA && !isUserdataBytecodeType(bcTypes.b) && !isGenericArithFeedback(recordedB) + : bcTypes.a == LBC_TYPE_VECTOR && !isUserdataBytecodeType(bcTypes.b)) && (tm == TM_MUL || tm == TM_DIV || tm == TM_IDIV)) { - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { checkArithOperandTag(build, fallback, rb, LUA_TVECTOR, bcTypes.a, pcpos); @@ -984,7 +916,7 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, } // If we recorded a userdata at this position, we can do a fast path or record a detailed userdata type counter (or nothing) - if (FFlag::LuauRuntimeFeedback && (recordedA == LBC_TYPE_USERDATA || recordedB == LBC_TYPE_USERDATA) && build.hostHooks.userdataMetamethod) + if (FFlag::LuauCodegenRuntimeFeedback && (recordedA == LBC_TYPE_USERDATA || recordedB == LBC_TYPE_USERDATA) && build.hostHooks.userdataMetamethod) { auto feedbackA = recordedA == LBC_TYPE_USERDATA ? getUserdataFeedback(build.function, pcpos, rb) : std::nullopt; auto feedbackB = recordedB == LBC_TYPE_USERDATA ? getUserdataFeedback(build.function, pcpos, rc) : std::nullopt; @@ -1002,8 +934,8 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, if (feedbackB && rc != rb) checkUserdataWithFeedback(build, *feedbackB, fallback, pcpos); - uint8_t typeA = feedbackA ? feedbackA->type : bcTypes.a; - uint8_t typeB = feedbackB ? feedbackB->type : bcTypes.b; + uint8_t typeA = feedbackA ? feedbackA->type : (vectorA ? LBC_TYPE_VECTOR : bcTypes.a); + uint8_t typeB = feedbackB ? feedbackB->type : (vectorB ? LBC_TYPE_VECTOR : bcTypes.b); if (!build.hostHooks.userdataMetamethod(build, typeA, typeB, ra, opb, opc, tmToHostMetamethod(tm), pcpos)) { @@ -1024,23 +956,35 @@ static void translateInstBinaryNumeric(IrBuilder& build, int ra, int rb, int rc, if (isUserdataBytecodeType(bcTypes.a) || isUserdataBytecodeType(bcTypes.b)) { - if (build.hostHooks.userdataMetamethod && - build.hostHooks.userdataMetamethod(build, bcTypes.a, bcTypes.b, ra, opb, opc, tmToHostMetamethod(tm), pcpos)) - return; + if (FFlag::LuauCodegenRuntimeFeedback) + { + uint8_t typeA = vectorA ? LBC_TYPE_VECTOR : bcTypes.a; + uint8_t typeB = vectorB ? LBC_TYPE_VECTOR : bcTypes.b; + + if (build.hostHooks.userdataMetamethod && + build.hostHooks.userdataMetamethod(build, typeA, typeB, ra, opb, opc, tmToHostMetamethod(tm), pcpos)) + return; + } + else + { + if (build.hostHooks.userdataMetamethod && + build.hostHooks.userdataMetamethod(build, bcTypes.a, bcTypes.b, ra, opb, opc, tmToHostMetamethod(tm), pcpos)) + return; + } build.inst(IrCmd::SET_SAVEDPC, build.constUint(pcpos + 1)); build.inst(IrCmd::DO_ARITH, build.vmReg(ra), opb, opc, build.constInt(tm)); return; } - if (FFlag::LuauRuntimeFeedback && (isGenericArithFeedback(recordedA) || isGenericArithFeedback(recordedB))) + if (FFlag::LuauCodegenRuntimeFeedback && (isGenericArithFeedback(recordedA) || isGenericArithFeedback(recordedB))) { build.inst(IrCmd::SET_SAVEDPC, build.constUint(pcpos + 1)); build.inst(IrCmd::DO_ARITH, build.vmReg(ra), opb, opc, build.constInt(tm)); return; } - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { // fast-path: number if (rb != -1) @@ -1184,11 +1128,11 @@ void translateInstMinus(IrBuilder& build, const Instruction* pc, int pcpos) int rb = LUAU_INSN_B(*pc); IrOp fallback; - LuauBytecodeType recordedA = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; + LuauBytecodeType recordedA = FFlag::LuauCodegenRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; - if (bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedA == LBC_TYPE_VECTOR)) + if (bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauCodegenRuntimeFeedback && recordedA == LBC_TYPE_VECTOR)) { - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) checkArithOperandTag(build, fallback, rb, LUA_TVECTOR, bcTypes.a, pcpos); else build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)), build.constTag(LUA_TVECTOR), build.vmExit(pcpos)); @@ -1216,7 +1160,7 @@ void translateInstMinus(IrBuilder& build, const Instruction* pc, int pcpos) build.inst(IrCmd::STORE_TVALUE, build.vmReg(ra), va); } - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) translateBinaryNumericFallbackIfRequired(build, fallback, ra, build.vmReg(rb), build.vmReg(rb), TM_UNM, pcpos); return; @@ -1234,7 +1178,7 @@ void translateInstMinus(IrBuilder& build, const Instruction* pc, int pcpos) } // If we recorded a userdata at this position, we can do a fast path or record a detailed userdata type counter (or nothing) - if (FFlag::LuauRuntimeFeedback && recordedA == LBC_TYPE_USERDATA && build.hostHooks.userdataMetamethod) + if (FFlag::LuauCodegenRuntimeFeedback && recordedA == LBC_TYPE_USERDATA && build.hostHooks.userdataMetamethod) { auto feedback = getUserdataFeedback(build.function, pcpos, rb); @@ -1259,14 +1203,14 @@ void translateInstMinus(IrBuilder& build, const Instruction* pc, int pcpos) } // If we recorded a type that doesn't have any fast paths, place the 'fallback' operation as the main one - if (FFlag::LuauRuntimeFeedback && isGenericArithFeedback(recordedA)) + if (FFlag::LuauCodegenRuntimeFeedback && isGenericArithFeedback(recordedA)) { build.inst(IrCmd::SET_SAVEDPC, build.constUint(pcpos + 1)); build.inst(IrCmd::DO_ARITH, build.vmReg(ra), build.vmReg(rb), build.vmReg(rb), build.constInt(TM_UNM)); return; } - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { checkArithOperandTag(build, fallback, rb, LUA_TNUMBER, bcTypes.a, pcpos); } @@ -1290,7 +1234,7 @@ void translateInstMinus(IrBuilder& build, const Instruction* pc, int pcpos) if (ra != rb) build.inst(IrCmd::STORE_TAG, build.vmReg(ra), build.constTag(LUA_TNUMBER)); - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { translateBinaryNumericFallbackIfRequired(build, fallback, ra, build.vmReg(rb), build.vmReg(rb), TM_UNM, pcpos); } @@ -1425,8 +1369,6 @@ IrOp translateFastCallN(IrBuilder& build, const Instruction* pc, int pcpos, bool if (protok.tt == LUA_TNUMBER) builtinArgs = build.constDouble(protok.value.n); - else if (FFlag::LuauCodegenInteger3 && protok.tt == LUA_TINTEGER) - builtinArgs = build.constInt64(protok.value.l); } IrOp builtinArg3 = customParams ? customArg3 : build.vmReg(ra + 3); @@ -1999,10 +1941,10 @@ void translateInstGetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) uint32_t aux = LUAU_INSN_OP(*pc) == LOP_GETUDATAKS ? LUAU_INSN_AUX_KV16(pc[1]) : pc[1]; BytecodeTypes bcTypes = build.function.getBytecodeTypesAt(pcpos); - LuauBytecodeType recordedType = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; + LuauBytecodeType recordedType = FFlag::LuauCodegenRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; // If we recorded a userdata at this position, we can do a fast path or record a detailed userdata type counter (or nothing) - if (FFlag::LuauRuntimeFeedback && recordedType == LBC_TYPE_USERDATA && build.hostHooks.userdataAccess) + if (FFlag::LuauCodegenRuntimeFeedback && recordedType == LBC_TYPE_USERDATA && build.hostHooks.userdataAccess) { auto feedback = getUserdataFeedback(build.function, pcpos, rb); @@ -2031,7 +1973,7 @@ void translateInstGetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) } // If we recorded a type that doesn't have any fast paths, place the 'fallback' operation as the main one - if (FFlag::LuauRuntimeFeedback && recordedType != LBC_TYPE_ANY && recordedType != LBC_TYPE_VECTOR && recordedType != LBC_TYPE_TABLE) + if (FFlag::LuauCodegenRuntimeFeedback && recordedType != LBC_TYPE_ANY && recordedType != LBC_TYPE_VECTOR && recordedType != LBC_TYPE_TABLE) { build.inst(IrCmd::FALLBACK_GETTABLEKS, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); return; @@ -2039,11 +1981,11 @@ void translateInstGetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) IrOp tb = build.inst(IrCmd::LOAD_TAG, build.vmReg(rb)); - if (bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedType == LBC_TYPE_VECTOR)) + if (bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauCodegenRuntimeFeedback && recordedType == LBC_TYPE_VECTOR)) { IrOp fallback; - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { if (bcTypes.a == LBC_TYPE_VECTOR) { @@ -2117,7 +2059,7 @@ void translateInstGetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) } else { - if (FFlag::LuauRuntimeFeedback) + if (FFlag::LuauCodegenRuntimeFeedback) { if (!build.hostHooks.vectorAccess || !build.hostHooks.vectorAccess(build, field, str->len, ra, rb, pcpos)) { @@ -2133,7 +2075,7 @@ void translateInstGetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) } } - if (FFlag::LuauRuntimeFeedback && fallback.kind != IrOpKind::None) + if (FFlag::LuauCodegenRuntimeFeedback && fallback.kind != IrOpKind::None) { IrOp next = build.blockAtInst(pcpos + 2); FallbackStreamScope scope(build, fallback, next); @@ -2166,7 +2108,7 @@ void translateInstGetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) build.inst(IrCmd::CHECK_TAG, tb, build.constTag(LUA_TTABLE), bcTypes.a == LBC_TYPE_TABLE ? build.vmExit(pcpos) : fallback); - if (FFlag::LuauRuntimeFeedback && bcTypes.a != LBC_TYPE_TABLE) + if (FFlag::LuauCodegenRuntimeFeedback && bcTypes.a != LBC_TYPE_TABLE) recordFallbackTagMismatch(build, fallback, build.vmReg(rb), pcpos, LUA_TTABLE); IrOp vb = build.inst(IrCmd::LOAD_POINTER, build.vmReg(rb)); @@ -2194,10 +2136,10 @@ void translateInstSetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) uint32_t aux = LUAU_INSN_OP(*pc) == LOP_SETUDATAKS ? LUAU_INSN_AUX_KV16(pc[1]) : pc[1]; BytecodeTypes bcTypes = build.function.getBytecodeTypesAt(pcpos); - LuauBytecodeType recordedType = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; + LuauBytecodeType recordedType = FFlag::LuauCodegenRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; if ((FFlag::DebugLuauUserDefinedClassesRuntime && bcTypes.a == LBC_TYPE_OBJECT) || - (FFlag::LuauRuntimeFeedback && recordedType != LBC_TYPE_ANY && recordedType != LBC_TYPE_TABLE)) + (FFlag::LuauCodegenRuntimeFeedback && recordedType != LBC_TYPE_ANY && recordedType != LBC_TYPE_TABLE)) { build.inst(IrCmd::FALLBACK_SETTABLEKS, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); return; @@ -2217,7 +2159,7 @@ void translateInstSetTableKS(IrBuilder& build, const Instruction* pc, int pcpos) build.inst(IrCmd::CHECK_TAG, tb, build.constTag(LUA_TTABLE), bcTypes.a == LBC_TYPE_TABLE ? build.vmExit(pcpos) : fallback); - if (FFlag::LuauRuntimeFeedback && bcTypes.a != LBC_TYPE_TABLE) + if (FFlag::LuauCodegenRuntimeFeedback && bcTypes.a != LBC_TYPE_TABLE) recordFallbackTagMismatch(build, fallback, build.vmReg(rb), pcpos, LUA_TTABLE); IrOp vb = build.inst(IrCmd::LOAD_POINTER, build.vmReg(rb)); @@ -2322,7 +2264,7 @@ void translateInstCapture(IrBuilder& build, const Instruction* pc, int pcpos) } } -static void translateNamecallFallback(IrBuilder& build, const Instruction* pc, int pcpos, uint32_t aux, IrOp fallback) +static void translateNamecallFallback_DEPRECATED(IrBuilder& build, const Instruction* pc, int pcpos, uint32_t aux, IrOp fallback) { int ra = LUAU_INSN_A(*pc); int rb = LUAU_INSN_B(*pc); @@ -2335,7 +2277,7 @@ static void translateNamecallFallback(IrBuilder& build, const Instruction* pc, i } // Fast-paths skip both namecall and call, so their fallback needs both performed -static void translateNamecallFallbackWithCall(IrBuilder& build, const Instruction* pc, int pcpos, uint32_t aux, IrOp fallback) +static void translateNamecallFallbackWithCall_DEPRECATED(IrBuilder& build, const Instruction* pc, int pcpos, uint32_t aux, IrOp fallback) { int ra = LUAU_INSN_A(*pc); int rb = LUAU_INSN_B(*pc); @@ -2358,19 +2300,96 @@ static void translateNamecallFallbackWithCall(IrBuilder& build, const Instructio build.inst(IrCmd::JUMP, next); } +// Returns true for the full sequence and false for a sequence that still needs a call +static bool emitNamecallSequence(IrBuilder& build, bool isUdata, int pcpos, int ra, int rb, uint32_t aux, int nparams, int nresults) +{ + if (isUdata) + { + build.inst(IrCmd::INTERRUPT, build.constUint(pcpos)); + build.inst( + IrCmd::INVOKE_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.constInt(nparams), build.constInt(nresults) + ); + return true; + } + else + { + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + return false; + } +} + +static void emitNamecallFallback( + IrBuilder& build, + bool isUdata, + int callpc, + int nextpc, + int pcpos, + int ra, + int rb, + uint32_t aux, + int nparams, + int nresults, + IrOp fallback +) +{ + IrOp next = build.blockAtInst(isUdata ? nextpc : callpc); + FallbackStreamScope scope(build, fallback, next); + + emitNamecallSequence(build, isUdata, pcpos, ra, rb, aux, nparams, nresults); + build.inst(IrCmd::JUMP, next); +} + +static void emitNamecallFallbackFull( + IrBuilder& build, + bool isUdata, + int callpc, + int nextpc, + int pcpos, + int callra, + int ra, + int rb, + uint32_t aux, + int nparams, + int nresults, + IrOp fallback +) +{ + IrOp next = build.blockAtInst(nextpc); + FallbackStreamScope scope(build, fallback, next); + + if (!emitNamecallSequence(build, isUdata, pcpos, ra, rb, aux, nparams, nresults)) + { + build.inst(IrCmd::INTERRUPT, build.constUint(callpc)); + build.inst(IrCmd::SET_SAVEDPC, build.constUint(nextpc)); + build.inst(IrCmd::CALL, build.vmReg(callra), build.constInt(nparams), build.constInt(nresults)); + } + + build.inst(IrCmd::JUMP, next); +} + bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) { int ra = LUAU_INSN_A(*pc); int rb = LUAU_INSN_B(*pc); - // TODO: we keep the table access lowering for speculative userdata access instructions until a later date - uint32_t aux = LUAU_INSN_OP(*pc) == LOP_NAMECALLUDATA ? LUAU_INSN_AUX_KV16(pc[1]) : pc[1]; + bool isUdata = LUAU_INSN_OP(*pc) == LOP_NAMECALLUDATA; + uint32_t aux = isUdata ? LUAU_INSN_AUX_KV16(pc[1]) : pc[1]; + + Instruction call = pc[2]; + CODEGEN_ASSERT(LUAU_INSN_OP(call) == LOP_CALLFB || LUAU_INSN_OP(call) == LOP_CALL); + + int callra = LUAU_INSN_A(call); + int nparams = LUAU_INSN_B(call) - 1; + int nresults = LUAU_INSN_C(call) - 1; + + int callpc = pcpos + getOpLength(LuauOpcode(LOP_NAMECALL)); + int nextpc = callpc + getOpLength(LuauOpcode(LUAU_INSN_OP(call))); BytecodeTypes bcTypes = build.function.getBytecodeTypesAt(pcpos); - LuauBytecodeType recordedType = FFlag::LuauRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; + LuauBytecodeType recordedType = FFlag::LuauCodegenRuntimeFeedback ? getRecordedVmRegType(build, bcTypes.a, pcpos, rb) : LBC_TYPE_ANY; // If we recorded a userdata at this position, we can do a fast path or record a detailed userdata type counter (or nothing) - if (FFlag::LuauRuntimeFeedback && recordedType == LBC_TYPE_USERDATA && build.hostHooks.userdataNamecall) + if (FFlag::LuauCodegenRuntimeFeedback && recordedType == LBC_TYPE_USERDATA && build.hostHooks.userdataNamecall) { auto feedback = getUserdataFeedback(build.function, pcpos, rb); @@ -2379,25 +2398,30 @@ bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) IrOp fallback = build.fallbackBlock(pcpos); checkUserdataWithFeedback(build, *feedback, fallback, pcpos); - Instruction call = pc[2]; - CODEGEN_ASSERT(LUAU_INSN_OP(call) == LOP_CALLFB || LUAU_INSN_OP(call) == LOP_CALL); - - int callra = LUAU_INSN_A(call); - int nparams = LUAU_INSN_B(call) - 1; - int nresults = LUAU_INSN_C(call) - 1; - TString* str = gco2ts(build.function.proto->k[aux].value.gc); const char* field = getstr(str); if (build.hostHooks.userdataNamecall(build, feedback->type, field, str->len, callra, rb, nparams, nresults, pcpos)) { - translateNamecallFallbackWithCall(build, pc, pcpos, aux, fallback); + if (FFlag::LuauCodegenUserdataDirect) + emitNamecallFallbackFull(build, isUdata, callpc, nextpc, pcpos, callra, ra, rb, aux, nparams, nresults, fallback); + else + translateNamecallFallbackWithCall_DEPRECATED(build, pc, pcpos, aux, fallback); return true; } - build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); - translateNamecallFallback(build, pc, pcpos, aux, fallback); - return false; + if (FFlag::LuauCodegenUserdataDirect) + { + bool full = emitNamecallSequence(build, isUdata, pcpos, ra, rb, aux, nparams, nresults); + emitNamecallFallback(build, isUdata, callpc, nextpc, pcpos, ra, rb, aux, nparams, nresults, fallback); + return full; + } + else + { + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + translateNamecallFallback_DEPRECATED(build, pc, pcpos, aux, fallback); + return false; + } } if (!feedback) @@ -2405,13 +2429,20 @@ bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) } // If we recorded a type that doesn't have any fast paths, place the 'fallback' operation as the main one - if (FFlag::LuauRuntimeFeedback && recordedType != LBC_TYPE_ANY && recordedType != LBC_TYPE_VECTOR && recordedType != LBC_TYPE_TABLE) + if (FFlag::LuauCodegenRuntimeFeedback && recordedType != LBC_TYPE_ANY && recordedType != LBC_TYPE_VECTOR && recordedType != LBC_TYPE_TABLE) { - build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); - return false; + if (FFlag::LuauCodegenUserdataDirect) + { + return emitNamecallSequence(build, isUdata, pcpos, ra, rb, aux, nparams, nresults); + } + else + { + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + return false; + } } - if (bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauRuntimeFeedback && recordedType == LBC_TYPE_VECTOR)) + if (bcTypes.a == LBC_TYPE_VECTOR || (FFlag::LuauCodegenRuntimeFeedback && recordedType == LBC_TYPE_VECTOR)) { IrOp fallback; @@ -2419,7 +2450,7 @@ bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) { build.loadAndCheckTag(build.vmReg(rb), LUA_TVECTOR, build.vmExit(pcpos)); } - else if (FFlag::LuauRuntimeFeedback) + else if (FFlag::LuauCodegenRuntimeFeedback) { fallback = build.fallbackBlock(pcpos); @@ -2441,19 +2472,36 @@ bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) if (build.hostHooks.vectorNamecall(build, field, str->len, callra, rb, nparams, nresults, pcpos)) { - if (FFlag::LuauRuntimeFeedback && fallback.kind != IrOpKind::None) - translateNamecallFallbackWithCall(build, pc, pcpos, aux, fallback); + if (FFlag::LuauCodegenRuntimeFeedback && fallback.kind != IrOpKind::None) + { + if (FFlag::LuauCodegenUserdataDirect) + emitNamecallFallbackFull(build, isUdata, callpc, nextpc, pcpos, callra, ra, rb, aux, nparams, nresults, fallback); + else + translateNamecallFallbackWithCall_DEPRECATED(build, pc, pcpos, aux, fallback); + } return true; } } - build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + if (FFlag::LuauCodegenUserdataDirect) + { + bool full = emitNamecallSequence(build, isUdata, pcpos, ra, rb, aux, nparams, nresults); - if (FFlag::LuauRuntimeFeedback && fallback.kind != IrOpKind::None) - translateNamecallFallback(build, pc, pcpos, aux, fallback); + if (FFlag::LuauCodegenRuntimeFeedback && fallback.kind != IrOpKind::None) + emitNamecallFallback(build, isUdata, callpc, nextpc, pcpos, ra, rb, aux, nparams, nresults, fallback); - return false; + return full; + } + else + { + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + + if (FFlag::LuauCodegenRuntimeFeedback && fallback.kind != IrOpKind::None) + translateNamecallFallback_DEPRECATED(build, pc, pcpos, aux, fallback); + + return false; + } } if (isUserdataBytecodeType(bcTypes.a)) @@ -2476,19 +2524,48 @@ bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) return true; } - build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); - return false; + if (FFlag::LuauCodegenUserdataDirect) + { + return emitNamecallSequence(build, isUdata, pcpos, ra, rb, aux, nparams, nresults); + } + else + { + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); + return false; + } } IrOp next = build.blockAtInst(pcpos + getOpLength(LuauOpcode(LOP_NAMECALL))); IrOp fallback = build.fallbackBlock(pcpos); + IrOp nonTableFallback = fallback; IrOp firstFastPathSuccess = build.block(IrBlockKind::Internal); IrOp secondFastPath = build.block(IrBlockKind::Internal); - build.loadAndCheckTag(build.vmReg(rb), LUA_TTABLE, bcTypes.a == LBC_TYPE_TABLE ? build.vmExit(pcpos) : fallback); + if (FFlag::LuauCodegenUserdataDirect) + { + if (bcTypes.a == LBC_TYPE_TABLE) + { + build.loadAndCheckTag(build.vmReg(rb), LUA_TTABLE, build.vmExit(pcpos)); + } + else + { + // If we are lowering LOP_NAMECALLUDATA, generate a separate fallback block on a tag miss + if (isUdata) + nonTableFallback = build.fallbackBlock(pcpos); + + build.loadAndCheckTag(build.vmReg(rb), LUA_TTABLE, nonTableFallback); - if (FFlag::LuauRuntimeFeedback && bcTypes.a != LBC_TYPE_TABLE) - recordFallbackTagMismatch(build, fallback, build.vmReg(rb), pcpos, LUA_TTABLE); + if (FFlag::LuauCodegenRuntimeFeedback) + recordFallbackTagMismatch(build, nonTableFallback, build.vmReg(rb), pcpos, LUA_TTABLE); + } + } + else + { + build.loadAndCheckTag(build.vmReg(rb), LUA_TTABLE, bcTypes.a == LBC_TYPE_TABLE ? build.vmExit(pcpos) : fallback); + + if (FFlag::LuauCodegenRuntimeFeedback && bcTypes.a != LBC_TYPE_TABLE) + recordFallbackTagMismatch(build, fallback, build.vmReg(rb), pcpos, LUA_TTABLE); + } IrOp table = build.inst(IrCmd::LOAD_POINTER, build.vmReg(rb)); @@ -2530,12 +2607,28 @@ bool translateInstNamecall(IrBuilder& build, const Instruction* pc, int pcpos) build.inst(IrCmd::JUMP, next); build.beginBlock(fallback); + build.inst(IrCmd::FALLBACK_NAMECALL, build.constUint(pcpos), build.vmReg(ra), build.vmReg(rb), build.vmConst(aux)); build.inst(IrCmd::JUMP, next); build.beginBlock(next); - return false; + if (FFlag::LuauCodegenUserdataDirect) + { + build.inst(IrCmd::INTERRUPT, build.constUint(callpc)); + build.inst(IrCmd::SET_SAVEDPC, build.constUint(nextpc)); + build.inst(IrCmd::CALL, build.vmReg(callra), build.constInt(nparams), build.constInt(nresults)); + + // If we have a separate fallback for non-table path, generate a second fallback with a full namecall invoke + if (fallback != nonTableFallback) + emitNamecallFallbackFull(build, isUdata, callpc, nextpc, pcpos, callra, ra, rb, aux, nparams, nresults, nonTableFallback); + + return true; + } + else + { + return false; + } } void translateInstAndX(IrBuilder& build, const Instruction* pc, int pcpos, IrOp c) diff --git a/CodeGen/src/IrUtils.cpp b/CodeGen/src/IrUtils.cpp index 237b43420..5b67c2889 100644 --- a/CodeGen/src/IrUtils.cpp +++ b/CodeGen/src/IrUtils.cpp @@ -19,7 +19,6 @@ #include #include -LUAU_FASTFLAG(LuauCodegenPropagateFallbackTags) LUAU_FASTFLAGVARIABLE(LuauCodegenUpdateSafeEnvList) LUAU_FASTFLAGVARIABLE(LuauCodegenCmpAnySideEffecting) @@ -181,13 +180,11 @@ IrValueKind getCmdValueKind(IrCmd cmd) case IrCmd::STORE_POINTER: case IrCmd::STORE_DOUBLE: case IrCmd::STORE_INT: - case IrCmd::STORE_INT64: case IrCmd::STORE_VECTOR: case IrCmd::STORE_TVALUE: case IrCmd::STORE_SPLIT_TVALUE: case IrCmd::CHECK_DIV_INT64: return IrValueKind::None; - case IrCmd::LOAD_INT64: case IrCmd::ADD_INT64: case IrCmd::SUB_INT64: case IrCmd::MUL_INT64: @@ -316,6 +313,7 @@ IrValueKind getCmdValueKind(IrCmd cmd) return IrValueKind::Float; case IrCmd::FLOAT_TO_VEC: case IrCmd::TAG_VECTOR: + case IrCmd::UNTAG_VECTOR: return IrValueKind::Tvalue; case IrCmd::TRUNCATE_UINT: return IrValueKind::Int; @@ -328,6 +326,7 @@ IrValueKind getCmdValueKind(IrCmd cmd) return IrValueKind::Int; case IrCmd::CHECK_FASTCALL_RES: case IrCmd::INVOKE_FASTPCALL: + case IrCmd::INVOKE_NAMECALL: case IrCmd::DO_ARITH: case IrCmd::DO_LEN: case IrCmd::CONSTRUCT: @@ -422,11 +421,18 @@ IrValueKind getCmdValueKind(IrCmd cmd) case IrCmd::BUFFER_WRITEF32: case IrCmd::BUFFER_WRITEF64: case IrCmd::BUFFER_WRITEI64: + case IrCmd::BUFFER_WRITEF32X4: return IrValueKind::None; case IrCmd::BUFFER_READF32: return IrValueKind::Float; case IrCmd::BUFFER_READF64: return IrValueKind::Double; + case IrCmd::BUFFER_READVECTOR: + return IrValueKind::Tvalue; + case IrCmd::BUFFER_WRITEVECTOR: + return IrValueKind::None; + case IrCmd::BUFFER_READF32X4: + return IrValueKind::Tvalue; case IrCmd::JUMP_CMP_PROTOID: return IrValueKind::None; } @@ -530,8 +536,6 @@ static LuauBytecodeType getBytecodeTypeForTag(uint8_t tag) return LBC_TYPE_ANY; // Doesn't have an LBC mapping case LUA_TNUMBER: return LBC_TYPE_NUMBER; - case LUA_TINTEGER: - return LBC_TYPE_INTEGER; case LUA_TVECTOR: return LBC_TYPE_VECTOR; case LUA_TSTRING: @@ -1178,8 +1182,6 @@ void foldConstants(IrBuilder& build, IrFunction& function, IrBlock& block, uint3 sameValue = compare(function.intOp(OP_C(inst)), function.intOp(OP_D(inst)), IrCondition::Equal); else if (function.tagOp(OP_B(inst)) == LUA_TNUMBER) sameValue = compare(function.doubleOp(OP_C(inst)), function.doubleOp(OP_D(inst)), IrCondition::Equal); - else if (function.tagOp(OP_B(inst)) == LUA_TINTEGER) - sameValue = compare(function.int64Op(OP_C(inst)), function.int64Op(OP_D(inst)), IrCondition::Equal); else CODEGEN_ASSERT(!"unsupported type"); @@ -1207,8 +1209,6 @@ void foldConstants(IrBuilder& build, IrFunction& function, IrBlock& block, uint3 differentValue = compare(function.intOp(OP_C(inst)), function.intOp(OP_D(inst)), IrCondition::NotEqual); else if (function.tagOp(OP_B(inst)) == LUA_TNUMBER) differentValue = compare(function.doubleOp(OP_C(inst)), function.doubleOp(OP_D(inst)), IrCondition::NotEqual); - else if (function.tagOp(OP_B(inst)) == LUA_TINTEGER) - differentValue = compare(function.int64Op(OP_C(inst)), function.int64Op(OP_D(inst)), IrCondition::NotEqual); else CODEGEN_ASSERT(!"unsupported type"); @@ -1974,7 +1974,7 @@ void propagateTagsFromPredecessors( return; // Entry block has an implicit edge as the function start and it has no tag info at that moment - if (FFlag::LuauCodegenPropagateFallbackTags && function.entryBlock == blockIdx) + if (function.entryBlock == blockIdx) return; BlockIteratorWrapper preds = predecessors(function.cfg, blockIdx); @@ -2041,8 +2041,6 @@ std::optional tryGetLuauTagForBcType(uint8_t bcType, bool ignoreOptiona return LUA_TBOOLEAN; case LBC_TYPE_NUMBER: return LUA_TNUMBER; - case LBC_TYPE_INTEGER: - return LUA_TINTEGER; case LBC_TYPE_STRING: return LUA_TSTRING; case LBC_TYPE_TABLE: diff --git a/CodeGen/src/IrValueLocationTracking.cpp b/CodeGen/src/IrValueLocationTracking.cpp index 30416311e..5c019e109 100644 --- a/CodeGen/src/IrValueLocationTracking.cpp +++ b/CodeGen/src/IrValueLocationTracking.cpp @@ -115,7 +115,6 @@ void IrValueLocationTracking::beforeInstLowering(IrInst& inst) case IrCmd::STORE_POINTER: case IrCmd::STORE_DOUBLE: case IrCmd::STORE_INT: - case IrCmd::STORE_INT64: case IrCmd::STORE_VECTOR: case IrCmd::STORE_TVALUE: case IrCmd::STORE_SPLIT_TVALUE: @@ -135,6 +134,10 @@ void IrValueLocationTracking::beforeInstLowering(IrInst& inst) // Even if result count is limited, all registers starting from function (ra) might be modified invalidateRestoreVmRegs(vmRegOp(OP_A(inst)), -1); break; + case IrCmd::INVOKE_NAMECALL: + // Even if result count is limited, all registers starting from function (ra) might be modified + invalidateRestoreVmRegs(vmRegOp(OP_B(inst)), -1); + break; case IrCmd::DO_ARITH: case IrCmd::DO_LEN: case IrCmd::CONSTRUCT: @@ -177,7 +180,6 @@ void IrValueLocationTracking::beforeInstLowering(IrInst& inst) case IrCmd::LOAD_TAG: case IrCmd::LOAD_POINTER: case IrCmd::LOAD_DOUBLE: - case IrCmd::LOAD_INT64: case IrCmd::LOAD_INT: case IrCmd::LOAD_FLOAT: case IrCmd::LOAD_TVALUE: @@ -186,7 +188,6 @@ void IrValueLocationTracking::beforeInstLowering(IrInst& inst) case IrCmd::JUMP_IF_TRUTHY: case IrCmd::JUMP_IF_FALSY: case IrCmd::JUMP_EQ_TAG: - case IrCmd::SELECT_INT64: case IrCmd::SET_TABLE: case IrCmd::SET_UPVALUE: case IrCmd::INTERRUPT: @@ -241,7 +242,6 @@ void IrValueLocationTracking::afterInstLowering(IrInst& inst, uint32_t instIdx) case IrCmd::LOAD_POINTER: case IrCmd::LOAD_DOUBLE: case IrCmd::LOAD_INT: - case IrCmd::LOAD_INT64: case IrCmd::LOAD_TVALUE: if (OP_A(inst).kind == IrOpKind::VmReg) invalidateRestoreOp(OP_A(inst), /*skipValueInvalidation*/ false); @@ -251,7 +251,6 @@ void IrValueLocationTracking::afterInstLowering(IrInst& inst, uint32_t instIdx) case IrCmd::STORE_POINTER: case IrCmd::STORE_DOUBLE: case IrCmd::STORE_INT: - case IrCmd::STORE_INT64: case IrCmd::STORE_TVALUE: // If this is not the last use of the stored value, we can restore it from this new location // Additionally, even if it's a last use, it might allow its argument to be restored @@ -383,7 +382,6 @@ void IrValueLocationTracking::invalidateRestoreOp(IrOp location, bool skipValueI case IrValueKind::Double: case IrValueKind::Pointer: case IrValueKind::Int: - case IrValueKind::Int64: return; default: break; diff --git a/CodeGen/src/NativeState.cpp b/CodeGen/src/NativeState.cpp index f79b717db..d99a4ca4f 100644 --- a/CodeGen/src/NativeState.cpp +++ b/CodeGen/src/NativeState.cpp @@ -97,6 +97,7 @@ void initFunctions(NativeContext& context) context.getImport = getImport; context.callFallback = callFallback; + context.callNamecall = callNamecall; context.fastPcallSetup = fastPcallSetup; context.executeGETGLOBAL = executeGETGLOBAL; diff --git a/CodeGen/src/NativeState.h b/CodeGen/src/NativeState.h index 278cdb9a1..b3065abc1 100644 --- a/CodeGen/src/NativeState.h +++ b/CodeGen/src/NativeState.h @@ -100,6 +100,7 @@ struct NativeContext void (*getImport)(lua_State* L, StkId res, unsigned id, unsigned pc) = nullptr; Closure* (*callFallback)(lua_State* L, StkId ra, StkId argtop, int nresults) = nullptr; + Closure* (*callNamecall)(lua_State* L, const Instruction* pc, StkId base, TValue* k) = nullptr; int (*fastPcallSetup)(lua_State* L, StkId ra, int pfid, int nparams, int nresults) = nullptr; // Opcode fallbacks, implemented in C diff --git a/CodeGen/src/OptimizeConstProp.cpp b/CodeGen/src/OptimizeConstProp.cpp index 0d0e4ff76..c88eb077a 100644 --- a/CodeGen/src/OptimizeConstProp.cpp +++ b/CodeGen/src/OptimizeConstProp.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -25,9 +26,10 @@ LUAU_FASTINTVARIABLE(LuauCodeGenReuseSlotLimit, 64) LUAU_FASTINTVARIABLE(LuauCodeGenReuseUdataTagLimit, 64) LUAU_FASTINTVARIABLE(LuauCodeGenLiveSlotReuseLimit, 8) LUAU_FASTFLAGVARIABLE(DebugLuauAbortingChecks) -LUAU_FASTFLAGVARIABLE(LuauCodegenPropagateFallbackTags) -LUAU_FLAGVERSION(LuauCodegenPropagateFallbackTags, 2) +LUAU_FASTFLAGVARIABLE(LuauCodegenForwardSplitStore) LUAU_FASTFLAGVARIABLE(LuauCodegenMarkUsed) +LUAU_FASTFLAG(LuauCodegenUserdataDirect) +LUAU_FASTFLAG(LuauCodegenMultiLaneDot) namespace Luau { @@ -100,9 +102,6 @@ static uint8_t tryGetTagForTypename(std::string_view name, bool forTypeof) if (name == "number") return LUA_TNUMBER; - if (name == "integer") - return LUA_TINTEGER; - // typeof(vector) can be changed by environment // TODO: support the environment option if (name == "vector" && !forTypeof) @@ -470,11 +469,6 @@ struct ConstPropState if (uint32_t* prevIdx = getPreviousVersionedLoadIndex(IrCmd::LOAD_DOUBLE, vmReg)) return std::make_pair(IrCmd::LOAD_DOUBLE, *prevIdx); } - else if (tag == LUA_TINTEGER) - { - if (uint32_t* prevIdx = getPreviousVersionedLoadIndex(IrCmd::LOAD_INT64, vmReg)) - return std::make_pair(IrCmd::LOAD_INT64, *prevIdx); - } else if (LUA_VECTOR_DOUBLE == 0 && tag == LUA_TVECTOR) { if (uint32_t* prevIdx = getPreviousVersionedLoadIndex(IrCmd::LOAD_FLOAT, vmReg)) @@ -555,6 +549,33 @@ struct ConstPropState valueMap[versionedVmRegLoad(loadCmd, OP_A(storeInst))] = OP_B(storeInst).index; } + void forwardVmRegSplitStoreToLoad(IrInst& storeInst) + { + CODEGEN_ASSERT(storeInst.cmd == IrCmd::STORE_SPLIT_TVALUE); + CODEGEN_ASSERT(OP_A(storeInst).kind == IrOpKind::VmReg); + + // To avoid captured register invalidation tracking in lowering later, values from stores into captured registers are not propagated + // This prevents the case where store creates an alternative value location in case of a spill and is then clobbered in a user call + if (function.cfg.captured.regs.test(vmRegOp(OP_A(storeInst)))) + return; + + if (OP_C(storeInst).kind != IrOpKind::Inst) + return; + + uint8_t tag = function.tagOp(OP_B(storeInst)); + IrCmd loadCmd = IrCmd::NOP; + + if (tag == LUA_TBOOLEAN) + loadCmd = IrCmd::LOAD_INT; + else if (tag == LUA_TNUMBER) + loadCmd = IrCmd::LOAD_DOUBLE; + else if (isGCO(tag)) + loadCmd = IrCmd::LOAD_POINTER; + + if (loadCmd != IrCmd::NOP) + valueMap[versionedVmRegLoad(loadCmd, OP_A(storeInst))] = OP_C(storeInst).index; + } + // When loading from a VM register, there might be an instruction that has loaded the whole TValue // That TValue might have a CHECK_TAG data associated with it bool substituteTagLoadWithTValueData(IrBuilder& build, IrInst& loadInst) @@ -1068,6 +1089,13 @@ struct ConstPropState return; } break; + case IrCmd::BUFFER_READF32X4: + if (info.loadCmd == IrCmd::BUFFER_READF32X4) + { + substitute(function, loadInst, info.value); + return; + } + break; default: CODEGEN_ASSERT(!"unknown load instruction"); } @@ -1096,13 +1124,11 @@ struct ConstPropState bufferLoadStoreInfo.push_back(info); } - void forwardBufferStoreToLoad(IrInst& storeInst, IrCmd loadCmd, uint8_t accessSize) + bool invalidateBufferRange(IrInst& storeInst, uint8_t accessSize, uint8_t tag, std::optional offset) { - uint8_t tag = function.tagOp(OP_D(storeInst)); - // Writing at unknown offset removes everything in the same kind of memory (buffer/userdata) // For userdata, we could check where the pointer is coming from, but we don't have an example of such usage - if (OP_B(storeInst).kind != IrOpKind::Constant) + if (!offset) { for (size_t i = 0; i < bufferLoadStoreInfo.size();) { @@ -1119,17 +1145,15 @@ struct ConstPropState } } - return; + return false; } - int offset = function.intOp(OP_B(storeInst)); - // Write at a constant offset invalidates that range in every object unless we know the pointers are unrelated for (size_t i = 0; i < bufferLoadStoreInfo.size();) { BufferLoadStoreInfo& info = bufferLoadStoreInfo[i]; - bool intersectingRange = offset + accessSize - 1 >= info.offset && offset <= info.offset + info.accessSize - 1; + bool intersectingRange = *offset + accessSize - 1 >= info.offset && *offset <= info.offset + info.accessSize - 1; if (intersectingRange && info.tag == tag) { @@ -1153,6 +1177,17 @@ struct ConstPropState } } + return true; + } + + void forwardBufferStoreToLoad(IrInst& storeInst, IrCmd loadCmd, uint8_t accessSize) + { + uint8_t tag = function.tagOp(OP_D(storeInst)); + std::optional offset = function.asIntOp(OP_B(storeInst)); + + if (!invalidateBufferRange(storeInst, accessSize, tag, offset)) + return; + IrOp value = OP_C(storeInst); // Store of smaller type will truncate data @@ -1178,7 +1213,7 @@ struct ConstPropState info.address = OP_A(storeInst); info.value = value; - info.offset = offset; + info.offset = *offset; bufferLoadStoreInfo.push_back(info); } @@ -1529,7 +1564,6 @@ static void handleBuiltinEffects(ConstPropState& state, LuauBuiltinFunction bfid case LBF_BUFFER_READU32: case LBF_BUFFER_READF32: case LBF_BUFFER_READF64: - case LBF_BUFFER_READINTEGER: case LBF_VECTOR_MAGNITUDE: case LBF_VECTOR_NORMALIZE: case LBF_VECTOR_CROSS: @@ -1546,50 +1580,18 @@ static void handleBuiltinEffects(ConstPropState& state, LuauBuiltinFunction bfid case LBF_MATH_ISNAN: case LBF_MATH_ISINF: case LBF_MATH_ISFINITE: - case LBF_INTEGER_ADD: - case LBF_INTEGER_MUL: - case LBF_INTEGER_IDIV: - case LBF_INTEGER_LT: - case LBF_INTEGER_CREATE: - case LBF_INTEGER_MOD: - case LBF_INTEGER_SUB: - case LBF_INTEGER_LE: - case LBF_INTEGER_GT: - case LBF_INTEGER_GE: - case LBF_INTEGER_ULT: - case LBF_INTEGER_ULE: - case LBF_INTEGER_UGT: - case LBF_INTEGER_UGE: - case LBF_INTEGER_DIV: - case LBF_INTEGER_NEG: - case LBF_INTEGER_BSWAP: - case LBF_INTEGER_MIN: - case LBF_INTEGER_MAX: - case LBF_INTEGER_REM: - case LBF_INTEGER_UDIV: - case LBF_INTEGER_UREM: - case LBF_INTEGER_BAND: - case LBF_INTEGER_BOR: - case LBF_INTEGER_BNOT: - case LBF_INTEGER_BXOR: - case LBF_INTEGER_BTEST: - case LBF_INTEGER_COUNTRZ: - case LBF_INTEGER_COUNTLZ: - case LBF_INTEGER_LSHIFT: - case LBF_INTEGER_RSHIFT: - case LBF_INTEGER_ARSHIFT: - case LBF_INTEGER_LROTATE: - case LBF_INTEGER_RROTATE: - case LBF_INTEGER_CLAMP: - case LBF_INTEGER_EXTRACT: - case LBF_INTEGER_TONUMBER: + case LBF_BUFFER_READVECTORF32X2: + case LBF_BUFFER_READVECTORF32X3: + case LBF_BUFFER_READVECTORF32X4: break; case LBF_BUFFER_WRITEU8: case LBF_BUFFER_WRITEU16: case LBF_BUFFER_WRITEU32: case LBF_BUFFER_WRITEF32: case LBF_BUFFER_WRITEF64: - case LBF_BUFFER_WRITEINTEGER: + case LBF_BUFFER_WRITEVECTORF32X2: + case LBF_BUFFER_WRITEVECTORF32X3: + case LBF_BUFFER_WRITEVECTORF32X4: state.invalidateHeapBufferData(); break; case LBF_TABLE_INSERT: @@ -1683,25 +1685,6 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& } break; } - case IrCmd::LOAD_INT64: - { - IrOp value = state.tryGetValue(OP_A(inst)); - - if (function.asInt64Op(value)) - { - substitute(function, inst, value); - } - else if (OP_A(inst).kind == IrOpKind::VmReg) - { - if (state.substituteOrRecordValueLoadWithTValueData(build, inst)) - break; - - state.tryRedirectVmRegLoadToTValueOrigin(inst); - - state.substituteOrRecordVmRegLoad(inst); - } - break; - } case IrCmd::LOAD_FLOAT: if (OP_A(inst).kind == IrOpKind::VmReg) { @@ -2000,45 +1983,6 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& } } break; - case IrCmd::STORE_INT64: - // Unlike STORE_INT (32-bit), do NOT remove TRUNCATE_UINT here: - // a 64-bit store uses all bits, so truncation is meaningful. - - if (OP_A(inst).kind == IrOpKind::VmReg) - { - if (OP_B(inst).kind == IrOpKind::Constant) - { - if (state.tryGetValue(OP_A(inst)) == OP_B(inst)) - { - if (FFlag::LuauCodegenMarkUsed) - state.killStore(block, inst); - else - kill(function, inst); - } - else - { - state.saveValue(OP_A(inst), OP_B(inst)); - } - } - else - { - if (uint32_t* prevIdx = state.getPreviousVersionedLoadIndex(IrCmd::LOAD_INT64, OP_A(inst))) - { - if (*prevIdx == OP_B(inst).index) - { - if (FFlag::LuauCodegenMarkUsed) - state.killStore(block, inst); - else - kill(function, inst); - break; - } - } - - state.invalidateValue(OP_A(inst)); - state.forwardVmRegStoreToLoad(inst, IrCmd::LOAD_INT64); - } - } - break; case IrCmd::STORE_VECTOR: state.invalidateValue(OP_A(inst)); @@ -2121,9 +2065,6 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& else if (tag == LUA_TNUMBER && (value.kind == IrOpKind::Inst || (value.kind == IrOpKind::Constant && function.constOp(value).kind == IrConstKind::Double))) canSplitTvalueStore = true; - else if (tag == LUA_TINTEGER && - (value.kind == IrOpKind::Inst || (value.kind == IrOpKind::Constant && function.constOp(value).kind == IrConstKind::Int64))) - canSplitTvalueStore = true; else if (tag != 0xff && isGCO(tag) && value.kind == IrOpKind::Inst) canSplitTvalueStore = true; @@ -2160,6 +2101,9 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& if (OP_C(inst).kind == IrOpKind::Constant) state.saveValue(OP_A(inst), OP_C(inst)); + + if (FFlag::LuauCodegenForwardSplitStore) + state.forwardVmRegSplitStoreToLoad(inst); } else { @@ -2335,8 +2279,6 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& { if (function.constOp(value).kind == IrConstKind::Double) tag = LUA_TNUMBER; - else if (function.constOp(value).kind == IrConstKind::Int64) - tag = LUA_TINTEGER; } } @@ -2583,6 +2525,19 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& case IrCmd::BUFFER_WRITEI64: state.forwardBufferStoreToLoad(inst, IrCmd::BUFFER_READI64, 8); break; + case IrCmd::BUFFER_READVECTOR: + break; + case IrCmd::BUFFER_WRITEVECTOR: + CODEGEN_ASSERT(OP_E(inst).kind == IrOpKind::Constant); + state.invalidateBufferRange( + inst, uint8_t(function.intOp(OP_E(inst)) * sizeof(float)), function.tagOp(OP_D(inst)), function.asIntOp(OP_B(inst))); + break; + case IrCmd::BUFFER_READF32X4: + state.substituteOrRecordBufferLoad(block, index, inst, 16); + break; + case IrCmd::BUFFER_WRITEF32X4: + state.forwardBufferStoreToLoad(inst, IrCmd::BUFFER_READF32X4, 16); + break; case IrCmd::CHECK_GC: // It is enough to perform a GC check once in a block if (state.checkedGc) @@ -2643,6 +2598,10 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& state.invalidateRegistersFrom(vmRegOp(OP_A(inst))); state.invalidateUserCall(); break; + case IrCmd::INVOKE_NAMECALL: + state.invalidateRegistersFrom(vmRegOp(OP_B(inst))); + state.invalidateUserCall(); + break; // These instructions don't have an effect on register/memory state we are tracking case IrCmd::NOP: @@ -3241,7 +3200,6 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& case IrCmd::MUL_VEC: case IrCmd::DIV_VEC: case IrCmd::IDIV_VEC: - case IrCmd::DOT_VEC: case IrCmd::MIN_VEC: case IrCmd::MAX_VEC: if (IrInst* a = function.asInstOp(OP_A(inst)); a && a->cmd == IrCmd::TAG_VECTOR) @@ -3253,6 +3211,19 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& state.substituteOrRecord(inst, index); break; + case IrCmd::DOT_VEC: + if (!FFlag::LuauCodegenMultiLaneDot || function.intOp(OP_C(inst)) == 3) + { + if (IrInst* a = function.asInstOp(OP_A(inst)); a && a->cmd == IrCmd::TAG_VECTOR) + replace(function, OP_A(inst), OP_A(a)); + + if (IrInst* b = function.asInstOp(OP_B(inst)); b && b->cmd == IrCmd::TAG_VECTOR) + replace(function, OP_B(inst), OP_A(b)); + } + + state.substituteOrRecord(inst, index); + break; + case IrCmd::UNM_VEC: case IrCmd::FLOOR_VEC: case IrCmd::CEIL_VEC: @@ -3268,6 +3239,13 @@ static void constPropInInst(ConstPropState& state, IrBuilder& build, IrFunction& state.substituteOrRecord(inst, index); break; + case IrCmd::UNTAG_VECTOR: + if (IrInst* a = function.asInstOp(OP_A(inst)); a && a->cmd == IrCmd::UNTAG_VECTOR) + substitute(function, inst, OP_A(inst)); + else + state.substituteOrRecord(inst, index); + break; + case IrCmd::INVOKE_LIBM: state.substituteOrRecord(inst, index); break; @@ -3598,13 +3576,13 @@ static void constPropInBlock(IrBuilder& build, IrBlock& block, ConstPropState& s if (state.reachedLimits) { // Fallback entry data is no longer available - if (FFlag::LuauCodegenPropagateFallbackTags && !isPseudo(inst.cmd)) + if (!isPseudo(inst.cmd)) invalidateFallbackEntryTags(function, inst); continue; } - if (FFlag::LuauCodegenPropagateFallbackTags && !isPseudo(inst.cmd)) + if (!isPseudo(inst.cmd)) snapshotFallbackEntryTags(function, inst, state); constPropInInst(state, build, function, block, inst, index); @@ -3731,6 +3709,9 @@ static bool includeBlockInLinearPath(IrFunction& function, const IrBlock& block) // Same rule applies to fast pcall path as it acts as a call if (inst.cmd == IrCmd::INVOKE_FASTPCALL) return false; + + if (FFlag::LuauCodegenUserdataDirect && inst.cmd == IrCmd::INVOKE_NAMECALL) + return false; } return true; @@ -3949,29 +3930,20 @@ void constPropInBlockChains(IrBuilder& build) std::vector visited(function.blocks.size(), false); function.blockExitTags.resize(function.blocks.size()); - - if (FFlag::LuauCodegenPropagateFallbackTags) - function.fallbackEntryTags.resize(function.blocks.size()); + function.fallbackEntryTags.resize(function.blocks.size()); for (IrBlock& block : function.blocks) { - if ((!FFlag::LuauCodegenPropagateFallbackTags && block.kind == IrBlockKind::Fallback) || block.kind == IrBlockKind::Dead) + if (block.kind == IrBlockKind::Dead) continue; if (visited[function.getBlockIndex(block)]) continue; - if (FFlag::LuauCodegenPropagateFallbackTags) - { - if (block.kind == IrBlockKind::Fallback) - constPropInFallback(build, visited, block, state); - else - constPropInBlockChain(build, visited, &block, state); - } + if (block.kind == IrBlockKind::Fallback) + constPropInFallback(build, visited, block, state); else - { constPropInBlockChain(build, visited, &block, state); - } } } diff --git a/CodeGen/src/OptimizeDeadStore.cpp b/CodeGen/src/OptimizeDeadStore.cpp index 09995b734..df2a0c126 100644 --- a/CodeGen/src/OptimizeDeadStore.cpp +++ b/CodeGen/src/OptimizeDeadStore.cpp @@ -10,6 +10,7 @@ #include "lobject.h" +LUAU_FASTFLAGVARIABLE(LuauCodegenExitSyncExpectedTag) LUAU_FASTFLAGVARIABLE(LuauCodegenDseTrackTagInvalidation) LUAU_FASTFLAG(LuauCodegenMarkUsed) @@ -28,7 +29,6 @@ static bool isUnsafeToSink(IrCmd cmd) case IrCmd::LOAD_POINTER: case IrCmd::LOAD_DOUBLE: case IrCmd::LOAD_INT: - case IrCmd::LOAD_INT64: case IrCmd::LOAD_FLOAT: case IrCmd::LOAD_TVALUE: @@ -41,6 +41,8 @@ static bool isUnsafeToSink(IrCmd cmd) case IrCmd::BUFFER_READI64: case IrCmd::BUFFER_READF32: case IrCmd::BUFFER_READF64: + case IrCmd::BUFFER_READVECTOR: + case IrCmd::BUFFER_READF32X4: // Upvalue read: SET_UPVALUE to the same upvalue slot case IrCmd::GET_UPVALUE: @@ -121,10 +123,6 @@ struct RemoveDeadStoreState value = OP_B(storeInst); kind = IrValueKind::Int; break; - case IrCmd::STORE_INT64: - value = OP_B(storeInst); - kind = IrValueKind::Int64; - break; case IrCmd::STORE_POINTER: value = OP_B(storeInst); kind = IrValueKind::Pointer; @@ -389,6 +387,9 @@ struct RemoveDeadStoreState storeInfo.reg = uint8_t(i); + if (FFlag::LuauCodegenExitSyncExpectedTag && regInfo.tagInstIdx == kInvalidInstIdx) + storeInfo.expectedTag = regInfo.knownTag; + auto recordStore = [&](uint32_t instIdx) { IrInst& store = function.instructions[instIdx]; @@ -1045,7 +1046,6 @@ static void markDeadStoresInInst(RemoveDeadStoreState& state, IrBuilder& build, } break; case IrCmd::STORE_DOUBLE: - case IrCmd::STORE_INT64: case IrCmd::STORE_INT: if (OP_A(inst).kind == IrOpKind::VmReg) { @@ -1265,6 +1265,7 @@ static void markDeadStoresInInst(RemoveDeadStoreState& state, IrBuilder& build, case IrCmd::CHECK_GC: case IrCmd::CALL: case IrCmd::INVOKE_FASTPCALL: + case IrCmd::INVOKE_NAMECALL: case IrCmd::FORGLOOP_FALLBACK: case IrCmd::FALLBACK_GETGLOBAL: case IrCmd::FALLBACK_SETGLOBAL: @@ -1329,6 +1330,7 @@ static void markDeadStoresInInst(RemoveDeadStoreState& state, IrBuilder& build, // CALL directly executes a Luau function on the same native stack frame case IrCmd::CALL: case IrCmd::INVOKE_FASTPCALL: + case IrCmd::INVOKE_NAMECALL: // These instructions use lowering that is not aware of register allocator and demand no active values to exist case IrCmd::SETLIST: case IrCmd::FORGLOOP: @@ -1453,6 +1455,8 @@ static void markDeadStoresInBlockChain( case IrCmd::BUFFER_WRITEI64: case IrCmd::BUFFER_WRITEF32: case IrCmd::BUFFER_WRITEF64: + case IrCmd::BUFFER_WRITEVECTOR: + case IrCmd::BUFFER_WRITEF32X4: state.remainingUses[OP_A(inst).index]--; if (state.remainingUses[OP_A(inst).index] == 0) @@ -1483,6 +1487,8 @@ static void markDeadStoresInBlockChain( case IrCmd::BUFFER_WRITEI64: case IrCmd::BUFFER_WRITEF32: case IrCmd::BUFFER_WRITEF64: + case IrCmd::BUFFER_WRITEVECTOR: + case IrCmd::BUFFER_WRITEF32X4: if (state.remainingUses[OP_A(inst).index] == 0) { IrInst& pointer = function.instOp(OP_A(inst)); @@ -1589,9 +1595,25 @@ static void generateVmExitBlocks(IrBuilder& build, const std::vector& } }; - // Start with the store instruction we got + // Start with the store instructions we got for (auto& regStore : syncInfo.regStores) { + if (FFlag::LuauCodegenExitSyncExpectedTag && regStore.expectedTag != kUnknownTag) + { + for (auto& record : regStore.stores) + { + IrCmd cmd = record.backup.cmd; + bool partialStore = cmd == IrCmd::STORE_DOUBLE || cmd == IrCmd::STORE_INT || cmd == IrCmd::STORE_POINTER; + + // If it's only a partial store and could be used for a spill, restore the tag from the constant + if (partialStore && function.findStoreLocationHint(record.instIdx)) + { + storeInstructions.push_back({IrCmd::STORE_TAG, {build.vmReg(regStore.reg), build.constTag(regStore.expectedTag)}}); + break; + } + } + } + for (auto& record : regStore.stores) { storeInstructions.push_back(record.backup); diff --git a/CodeGen/src/SharedCodeAllocator.cpp b/CodeGen/src/SharedCodeAllocator.cpp index ee684c2fb..f6e3b85a8 100644 --- a/CodeGen/src/SharedCodeAllocator.cpp +++ b/CodeGen/src/SharedCodeAllocator.cpp @@ -8,7 +8,7 @@ #include #include -LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauCodegenRuntimeFeedback) namespace Luau { @@ -64,7 +64,7 @@ NativeModule::NativeModule( } // Anonymous 'modules' can have function sets in compilation order (from multiple source files) - if (!FFlag::LuauRuntimeFeedback || moduleId) + if (!FFlag::LuauCodegenRuntimeFeedback || moduleId) { std::sort(this->nativeProtos.begin(), this->nativeProtos.end(), NativeProtoBytecodeIdLess{}); diff --git a/Common/include/Luau/Bytecode.h b/Common/include/Luau/Bytecode.h index 0574fbee4..4d81cc8ac 100644 --- a/Common/include/Luau/Bytecode.h +++ b/Common/include/Luau/Bytecode.h @@ -48,12 +48,12 @@ // Version 5: Adds SUBRK/DIVRK and vector constants. Currently supported. // Version 6: Adds FASTCALL3. Currently supported. // Version 7: Adds LBC_CONSTANT_TABLE_WITH_CONSTANTS for DUPTABLE with pre-filled constant values. Currently supported. -// Version 8: Adds LBC_CONSTANT_INTEGER for 64-bit integer constants. Currently supported. +// Version 8: Adds LBC_CONSTANT_INTEGER for 64-bit integer constants. No longer supported when integers feature is enabled. // Version 9: Adds atom-based userdata field access acceleration. Currently supported. -// Version 10: Adds LBC_CONSTANT_CLASS_SHAPE and NEWCLASSMEMBER for use with Luau Classes. Experimental. -// Version 11: Adds CALLFB, CMPPROTO and feedback vector description. Experimental. -// Version 12: Adds cost function serialized for proto and prepend each proto with size in bytes. Experimental. -// Version 13: Adds support for double-precision vector constants. Experimental. +// Version 10: Adds LBC_CONSTANT_CLASS_SHAPE and NEWCLASSMEMBER for use with Luau Classes. No longer supported when class feature is enabled. +// Version 11: Adds CALLFB, CMPPROTO and feedback vector description. Currently supported. +// Version 12: Adds cost function serialized for proto and prepend each proto with size in bytes. Currently supported. +// Version 13: Adds support for double-precision vector constants. Currently supported. // Version 14: Adds FASTPCALL. Currently supported. // WIP Versions: Used for in-progress features that might require multiple changes to bytecode. Since these versions are higher than the non-WIP versions, they are responsible for maintaining compatibility with them. For example, tests exercising WIP bytecode versions may need to enable flags for unreleased but non-WIP bytecode versions. @@ -559,7 +559,7 @@ enum LuauBytecodeTag // Bytecode version; runtime supports [MIN, MAX], compiler emits TARGET by default but may emit a higher version when flags are enabled LBC_VERSION_MIN = 3, LBC_VERSION_MAX = 14, - LBC_VERSION_TARGET = 13, + LBC_VERSION_TARGET = 14, LBC_VERSION_CLASSES = 100, // Type encoding version LBC_TYPE_VERSION_MIN = 1, @@ -575,7 +575,7 @@ enum LuauBytecodeTag LBC_CONSTANT_CLOSURE, LBC_CONSTANT_VECTOR, LBC_CONSTANT_TABLE_WITH_CONSTANTS, - LBC_CONSTANT_INTEGER, + LBC_CONSTANT_INTEGER_DEPRECATED, // integers are no longer supported LBC_CONSTANT_CLASS_SHAPE, LBC_CONSTANT_VECTORD, @@ -596,7 +596,7 @@ enum LuauBytecodeType LBC_TYPE_USERDATA, LBC_TYPE_VECTOR, LBC_TYPE_BUFFER, - LBC_TYPE_INTEGER, + LBC_TYPE_INTEGER_DEPRECATED, // integers are no longer supported LBC_TYPE_CLASS, LBC_TYPE_OBJECT, @@ -754,52 +754,19 @@ enum LuauBuiltinFunction LBF_MATH_ISINF, LBF_MATH_ISFINITE, - // integer - LBF_INTEGER_CREATE, - LBF_INTEGER_TONUMBER, - LBF_INTEGER_NEG, - LBF_INTEGER_ADD, - LBF_INTEGER_SUB, - LBF_INTEGER_MUL, - LBF_INTEGER_DIV, - LBF_INTEGER_MIN, - LBF_INTEGER_MAX, - LBF_INTEGER_REM, - LBF_INTEGER_IDIV, - LBF_INTEGER_UDIV, - LBF_INTEGER_UREM, - LBF_INTEGER_MOD, - LBF_INTEGER_CLAMP, - LBF_INTEGER_BAND, - LBF_INTEGER_BOR, - LBF_INTEGER_BNOT, - LBF_INTEGER_BXOR, - LBF_INTEGER_LT, - LBF_INTEGER_LE, - LBF_INTEGER_ULT, - LBF_INTEGER_ULE, - LBF_INTEGER_GT, - LBF_INTEGER_GE, - LBF_INTEGER_UGT, - LBF_INTEGER_UGE, - LBF_INTEGER_LSHIFT, - LBF_INTEGER_RSHIFT, - LBF_INTEGER_ARSHIFT, - LBF_INTEGER_LROTATE, - LBF_INTEGER_RROTATE, - LBF_INTEGER_EXTRACT, - LBF_INTEGER_BTEST, - LBF_INTEGER_COUNTRZ, - LBF_INTEGER_COUNTLZ, - LBF_INTEGER_BSWAP, - - // buffer.readinteger / buffer.writeinteger (int64_t) - LBF_BUFFER_READINTEGER, - LBF_BUFFER_WRITEINTEGER, - // table.create / table.clear - LBF_TABLE_CREATE, + // IDs 94..132 are reserved for removed integer fastcalls + // when adding new fastcall functions, use slots above this to reclaim spots + LBF_TABLE_CREATE = 133, LBF_TABLE_CLEAR, + + // buffer.readvectorf32x* / buffer.writevectorf32x* (N contiguous f32 components) + LBF_BUFFER_READVECTORF32X2, + LBF_BUFFER_READVECTORF32X3, + LBF_BUFFER_READVECTORF32X4, + LBF_BUFFER_WRITEVECTORF32X2, + LBF_BUFFER_WRITEVECTORF32X3, + LBF_BUFFER_WRITEVECTORF32X4, }; // Capture type, used in LOP_CAPTURE diff --git a/Compiler/include/Luau/Compiler.h b/Compiler/include/Luau/Compiler.h index 4f805d2bf..beb8856d2 100644 --- a/Compiler/include/Luau/Compiler.h +++ b/Compiler/include/Luau/Compiler.h @@ -13,7 +13,6 @@ namespace Luau class AstNameTable; struct ParseResult; class BytecodeBuilder; -class BytecodeEncoder; using CompileConstant = void*; @@ -102,14 +101,12 @@ void compileOrThrow(BytecodeBuilder& bytecode, const std::string& source, const std::string compile( const std::string& source, const CompileOptions& options = {}, - const ParseOptions& parseOptions = {}, - BytecodeEncoder* encoder = nullptr + const ParseOptions& parseOptions = {} ); void setCompileConstantNil(CompileConstant* constant); void setCompileConstantBoolean(CompileConstant* constant, bool b); void setCompileConstantNumber(CompileConstant* constant, double n); -void setCompileConstantInteger64(CompileConstant* constant, int64_t l); void setCompileConstantVector(CompileConstant* constant, float x, float y, float z, float w); void setCompileConstantVectord(CompileConstant* constant, double x, double y, double z, double w); void setCompileConstantString(CompileConstant* constant, const char* s, size_t l); diff --git a/Compiler/include/luacode.h b/Compiler/include/luacode.h index a8ade84fa..1d932ae46 100644 --- a/Compiler/include/luacode.h +++ b/Compiler/include/luacode.h @@ -79,7 +79,6 @@ LUACODE_API char* luau_compile(const char* source, size_t size, lua_CompileOptio LUACODE_API void luau_set_compile_constant_nil(lua_CompileConstant* constant); LUACODE_API void luau_set_compile_constant_boolean(lua_CompileConstant* constant, int b); LUACODE_API void luau_set_compile_constant_number(lua_CompileConstant* constant, double n); -LUACODE_API void luau_set_compile_constant_integer64(lua_CompileConstant* constant, int64_t l); LUACODE_API void luau_set_compile_constant_vector(lua_CompileConstant* constant, float x, float y, float z, float w); LUACODE_API void luau_set_compile_constant_vectord(lua_CompileConstant* constant, double x, double y, double z, double w); LUACODE_API void luau_set_compile_constant_string(lua_CompileConstant* constant, const char* s, size_t l); diff --git a/Compiler/src/BuiltinFolding.cpp b/Compiler/src/BuiltinFolding.cpp index 007e0fdec..670071181 100644 --- a/Compiler/src/BuiltinFolding.cpp +++ b/Compiler/src/BuiltinFolding.cpp @@ -93,8 +93,6 @@ static Constant ctype(const Constant& c) case Constant::Type_Number: return cstring("number"); - case Constant::Type_Integer: - return cstring("integer"); case Constant::Type_Vectorf: case Constant::Type_Vectord: @@ -124,8 +122,6 @@ static Constant ctypeof(const Constant& c) case Constant::Type_Number: return cstring("number"); - case Constant::Type_Integer: - return cstring("integer"); case Constant::Type_Vectorf: case Constant::Type_Vectord: diff --git a/Compiler/src/Builtins.cpp b/Compiler/src/Builtins.cpp index d163a6774..4341c2e90 100644 --- a/Compiler/src/Builtins.cpp +++ b/Compiler/src/Builtins.cpp @@ -7,10 +7,10 @@ #include -LUAU_FASTFLAGVARIABLE(LuauIntegerFastcalls) -LUAU_FASTFLAGVARIABLE(LuauIntegerBufferFastcalls) +LUAU_FASTFLAGVARIABLE(DebugLuauBufferVectorFastcalls) LUAU_FASTFLAGVARIABLE(LuauCompileTableBuiltinsCreateClear) + namespace Luau { namespace Compile @@ -260,10 +260,21 @@ static int getBuiltinFunctionId(const Builtin& builtin, const CompileOptions& op return LBF_BUFFER_READF64; if (builtin.method == "writef64") return LBF_BUFFER_WRITEF64; - if (FFlag::LuauIntegerFastcalls && FFlag::LuauIntegerBufferFastcalls && builtin.method == "readinteger") - return LBF_BUFFER_READINTEGER; - if (FFlag::LuauIntegerFastcalls && FFlag::LuauIntegerBufferFastcalls && builtin.method == "writeinteger") - return LBF_BUFFER_WRITEINTEGER; + if (FFlag::DebugLuauBufferVectorFastcalls) + { + if (builtin.method == "readvectorf32x2") + return LBF_BUFFER_READVECTORF32X2; + if (builtin.method == "readvectorf32x3") + return LBF_BUFFER_READVECTORF32X3; + if (builtin.method == "readvectorf32x4") + return LBF_BUFFER_READVECTORF32X4; + if (builtin.method == "writevectorf32x2") + return LBF_BUFFER_WRITEVECTORF32X2; + if (builtin.method == "writevectorf32x3") + return LBF_BUFFER_WRITEVECTORF32X3; + if (builtin.method == "writevectorf32x4") + return LBF_BUFFER_WRITEVECTORF32X4; + } } if (builtin.object == "vector") @@ -296,84 +307,6 @@ static int getBuiltinFunctionId(const Builtin& builtin, const CompileOptions& op return LBF_VECTOR_LERP; } - if (FFlag::LuauIntegerFastcalls && builtin.object == "integer") - { - if (builtin.method == "add") - return LBF_INTEGER_ADD; - if (builtin.method == "sub") - return LBF_INTEGER_SUB; - if (builtin.method == "mod") - return LBF_INTEGER_MOD; - if (builtin.method == "mul") - return LBF_INTEGER_MUL; - if (builtin.method == "div") - return LBF_INTEGER_DIV; - if (builtin.method == "idiv") - return LBF_INTEGER_IDIV; - if (builtin.method == "udiv") - return LBF_INTEGER_UDIV; - if (builtin.method == "rem") - return LBF_INTEGER_REM; - if (builtin.method == "urem") - return LBF_INTEGER_UREM; - if (builtin.method == "min") - return LBF_INTEGER_MIN; - if (builtin.method == "max") - return LBF_INTEGER_MAX; - if (builtin.method == "neg") - return LBF_INTEGER_NEG; - if (builtin.method == "create") - return LBF_INTEGER_CREATE; - if (builtin.method == "clamp") - return LBF_INTEGER_CLAMP; - if (builtin.method == "band") - return LBF_INTEGER_BAND; - if (builtin.method == "bor") - return LBF_INTEGER_BOR; - if (builtin.method == "bxor") - return LBF_INTEGER_BXOR; - if (builtin.method == "bnot") - return LBF_INTEGER_BNOT; - if (builtin.method == "btest") - return LBF_INTEGER_BTEST; - if (builtin.method == "bswap") - return LBF_INTEGER_BSWAP; - if (builtin.method == "lt") - return LBF_INTEGER_LT; - if (builtin.method == "le") - return LBF_INTEGER_LE; - if (builtin.method == "ult") - return LBF_INTEGER_ULT; - if (builtin.method == "ule") - return LBF_INTEGER_ULE; - if (builtin.method == "gt") - return LBF_INTEGER_GT; - if (builtin.method == "ge") - return LBF_INTEGER_GE; - if (builtin.method == "ugt") - return LBF_INTEGER_UGT; - if (builtin.method == "uge") - return LBF_INTEGER_UGE; - if (builtin.method == "lshift") - return LBF_INTEGER_LSHIFT; - if (builtin.method == "rshift") - return LBF_INTEGER_RSHIFT; - if (builtin.method == "arshift") - return LBF_INTEGER_ARSHIFT; - if (builtin.method == "lrotate") - return LBF_INTEGER_LROTATE; - if (builtin.method == "rrotate") - return LBF_INTEGER_RROTATE; - if (builtin.method == "countrz") - return LBF_INTEGER_COUNTRZ; - if (builtin.method == "countlz") - return LBF_INTEGER_COUNTLZ; - if (builtin.method == "extract") - return LBF_INTEGER_EXTRACT; - if (builtin.method == "tonumber") - return LBF_INTEGER_TONUMBER; - } - if (options.vectorCtor) { if (options.vectorLib) @@ -661,12 +594,18 @@ BuiltinInfo getBuiltinInfo(int bfid) case LBF_BUFFER_WRITEU32: case LBF_BUFFER_WRITEF32: case LBF_BUFFER_WRITEF64: - case LBF_BUFFER_WRITEINTEGER: return {3, 0, BuiltinInfo::Flag_NoneSafe}; - case LBF_BUFFER_READINTEGER: + case LBF_BUFFER_READVECTORF32X2: + case LBF_BUFFER_READVECTORF32X3: + case LBF_BUFFER_READVECTORF32X4: return {2, 1, BuiltinInfo::Flag_NoneSafe}; + case LBF_BUFFER_WRITEVECTORF32X2: + case LBF_BUFFER_WRITEVECTORF32X3: + case LBF_BUFFER_WRITEVECTORF32X4: + return {3, 0, BuiltinInfo::Flag_NoneSafe}; + case LBF_VECTOR_MAGNITUDE: case LBF_VECTOR_NORMALIZE: return {1, 1, BuiltinInfo::Flag_NoneSafe}; @@ -694,53 +633,6 @@ BuiltinInfo getBuiltinInfo(int bfid) return {1, 1, BuiltinInfo::Flag_NoneSafe}; case LBF_MATH_ISFINITE: return {1, 1, BuiltinInfo::Flag_NoneSafe}; - - case LBF_INTEGER_BAND: - case LBF_INTEGER_BOR: - case LBF_INTEGER_BXOR: - case LBF_INTEGER_BTEST: - case LBF_INTEGER_MIN: - case LBF_INTEGER_MAX: - return {-1, 1}; // variadic - - case LBF_INTEGER_EXTRACT: - return {-1, 1}; // 2 or 3 parameters - - case LBF_INTEGER_BNOT: - case LBF_INTEGER_BSWAP: - case LBF_INTEGER_NEG: - case LBF_INTEGER_COUNTLZ: - case LBF_INTEGER_COUNTRZ: - case LBF_INTEGER_TONUMBER: - case LBF_INTEGER_CREATE: - return {1, 1, BuiltinInfo::Flag_NoneSafe}; - - case LBF_INTEGER_CLAMP: - return {3, 1, BuiltinInfo::Flag_NoneSafe}; - - case LBF_INTEGER_ADD: - case LBF_INTEGER_SUB: - case LBF_INTEGER_DIV: - case LBF_INTEGER_REM: - case LBF_INTEGER_UDIV: - case LBF_INTEGER_UREM: - case LBF_INTEGER_MOD: - case LBF_INTEGER_MUL: - case LBF_INTEGER_IDIV: - case LBF_INTEGER_LT: - case LBF_INTEGER_LE: - case LBF_INTEGER_ULT: - case LBF_INTEGER_ULE: - case LBF_INTEGER_GT: - case LBF_INTEGER_GE: - case LBF_INTEGER_UGT: - case LBF_INTEGER_UGE: - case LBF_INTEGER_LSHIFT: - case LBF_INTEGER_RSHIFT: - case LBF_INTEGER_ARSHIFT: - case LBF_INTEGER_LROTATE: - case LBF_INTEGER_RROTATE: - return {2, 1, BuiltinInfo::Flag_NoneSafe}; } LUAU_UNREACHABLE(); diff --git a/Compiler/src/Compiler.cpp b/Compiler/src/Compiler.cpp index 851915126..367177379 100644 --- a/Compiler/src/Compiler.cpp +++ b/Compiler/src/Compiler.cpp @@ -34,24 +34,21 @@ LUAU_FASTINTVARIABLE(LuauCompileInlineThresholdMaxBoost, 300) LUAU_FASTINTVARIABLE(LuauCompileInlineDepth, 5) LUAU_FASTFLAG(LuauExportValueSyntax) -LUAU_FASTFLAGVARIABLE(LuauCompileMoveElision) LUAU_FASTFLAGVARIABLE(LuauCompileRemoveStatLocalLoop) LUAU_FASTFLAGVARIABLE(LuauCompileMoveElisionFix) LUAU_FASTFLAGVARIABLE(LuauCompileNoDebugConst) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAGVARIABLE(LuauCompileConcatTargetTop) -LUAU_FASTFLAG(LuauCompileRefactorFeedback) LUAU_FASTFLAGVARIABLE(LuauCompileReuseLowersLimit) LUAU_FASTFLAG(DebugLuauNoInline) LUAU_FASTFLAG(LuauEmitCallFeedback) LUAU_FASTFLAGVARIABLE(LuauOptimizeExportTable) -LUAU_FASTFLAG(LuauCompileFastpcall) LUAU_FASTFLAGVARIABLE(LuauExportedTypesParticipateInScc) LUAU_FLAGVERSION(LuauExportedTypesParticipateInScc, 3) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAGVARIABLE(LuauCompileReuseLocalRegs) LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) LUAU_FASTFLAGVARIABLE(LuauCompileRequireNoInline) +LUAU_FASTFLAGVARIABLE(LuauCompileLoopUnrollNegativeZero) namespace Luau { @@ -59,6 +56,8 @@ namespace Luau using namespace Luau::Compile; static const uint32_t kDefaultAllocPc = ~0u; +static AstLocal* kInvalidUpvalue = nullptr; +static const size_t kMaxClassNest = 256; void escapeAndAppend(std::string& buffer, const char* str, size_t len) { @@ -169,18 +168,11 @@ struct Compiler if (v && v->written) { - if (FFlag::LuauCompileMoveElision) - { - Local& l = locals[local]; - l.captured = true; + Local& l = locals[local]; + l.captured = true; - if (l.allocated) - regCaptured[l.reg] = true; - } - else - { - locals[local].captured = true; - } + if (l.allocated) + regCaptured[l.reg] = true; } upvals.push_back(local); @@ -495,6 +487,14 @@ struct Compiler if (FFlag::LuauExportValueSyntax && FFlag::LuauOptimizeExportTable && atTopLevel()) buildExportTableShape(); + // For methods with private access nested in N classes, the first N upvalues are the enclosing classes, so push dummy values back so that + // other upvalue indexes still agree for "normal" upvalues + if (FFlag::DebugLuauUserDefinedClasses) + { + if (std::vector* classes = enclosingClasses.find(func)) + upvals.insert(upvals.end(), classes->size(), kInvalidUpvalue); + } + RegScope rs(this); bool self = func->self != 0; @@ -586,8 +586,26 @@ struct Compiler if (options.debugLevel >= 2 && !upvals.empty()) { - for (AstLocal* l : upvals) - bytecode.pushDebugUpval(sref(l->name)); + if (FFlag::DebugLuauUserDefinedClasses) + { + std::vector* classes = enclosingClasses.find(func); + for (size_t i = 0; i < upvals.size(); ++i) + { + const AstLocal* l = upvals[i]; + if (l == kInvalidUpvalue) + { + LUAU_ASSERT(classes); + bytecode.pushDebugUpval(sref((*classes)[i]->getName())); + } + else + bytecode.pushDebugUpval(sref(l->name)); + } + } + else + { + for (AstLocal* l : upvals) + bytecode.pushDebugUpval(sref(l->name)); + } } if (options.typeInfoLevel >= 1) @@ -672,17 +690,13 @@ struct Compiler ReturnVisitor returnVisitor(this, func); stat->visit(&returnVisitor); f.returnsOne = returnVisitor.returnsOne; + f.returnKind = returnVisitor.returnKind; + f.returnLocal = returnVisitor.returnLocal; - if (FFlag::LuauCompileMoveElision) + if (f.returnLocal) { - f.returnKind = returnVisitor.returnKind; - f.returnLocal = returnVisitor.returnLocal; - - if (f.returnLocal) - { - if (Local* lc = locals.find(f.returnLocal); lc && lc->captured) - f.returnLocalCaptured = true; - } + if (Local* lc = locals.find(f.returnLocal); lc && lc->captured) + f.returnLocalCaptured = true; } } } @@ -887,16 +901,9 @@ struct Compiler { args[i] = uint8_t(regs + 1 + i); - if (FFlag::LuauCompileMoveElision) - { - // We temporarily swap out regTop to have targetTop work correctly here, see compileExprTempTop for info - RegScope rs(this, args[i] + 1); - args[i] = compileExprAutoTemp(expr->args.data[i], uint8_t(args[i])); - } - else - { - compileExprTempTop(expr->args.data[i], uint8_t(args[i])); - } + // We temporarily swap out regTop to have targetTop work correctly here, see compileExprTempTop for info + RegScope rs(this, args[i] + 1); + args[i] = compileExprAutoTemp(expr->args.data[i], uint8_t(args[i])); } } @@ -982,6 +989,21 @@ struct Compiler return false; } + // The inlined body resolves private fields against the callee's enclosing classes but reads class objects from the caller's class + // upvalues, which only agree when the callee's classes are a prefix of the caller's. Lexical scoping guarantees this for local functions. + if (FFlag::DebugLuauUserDefinedClasses) + { + if (std::vector* calleeClasses = enclosingClasses.find(func)) + { + if (currClasses == nullptr || calleeClasses->size() > currClasses->size() || + !std::equal(calleeClasses->begin(), calleeClasses->end(), currClasses->begin())) + { + bytecode.addDebugRemark("inlining failed: mismatched enclosing classes"); + return false; + } + } + } + // we can't inline multret functions because the caller expects L->top to be adjusted: // - inlined return compiles to a JUMP, and we don't have an instruction that adjusts L->top arbitrarily // - even if we did, right now all L->top adjustments are immediately consumed by the next instruction, and for now we want to preserve that @@ -1123,33 +1145,25 @@ struct Compiler { FindRegisterUseByLocal visitor(this, reg); - if (FFlag::LuauCompileMoveElisionFix) - { - // Allow direct use of the target register in the current argument - if (arg && getExprLocalReg(arg) != reg) - expr->args.data[startArg]->visit(&visitor); + // Allow direct use of the target register in the current argument + if (arg && getExprLocalReg(arg) != reg) + expr->args.data[startArg]->visit(&visitor); - for (size_t i = startArg + 1; i < expr->args.size && !visitor.used; ++i) - expr->args.data[i]->visit(&visitor); - } - else - { - for (size_t i = startArg; i < expr->args.size && !visitor.used; ++i) - expr->args.data[i]->visit(&visitor); - } + for (size_t i = startArg + 1; i < expr->args.size && !visitor.used; ++i) + expr->args.data[i]->visit(&visitor); return visitor.used; } void compileInlinedCall(AstExprCall* expr, AstExprFunction* func, uint8_t target, uint8_t targetCount) { - Function* fi = FFlag::LuauCompileMoveElision ? functions.find(func) : nullptr; + Function* fi = functions.find(func); // We try to write result directly to the target register when possible, but there are a few blockers // - function captures a reference to the local that is being returned and might close it // - there might not be a target register (return value is unused) // - target register is captured and might be read before inlined function completes - bool noTargetMoveElision = FFlag::LuauCompileMoveElision && (fi->returnLocalCaptured || targetCount == 0 || regCaptured[target]); + bool noTargetMoveElision = fi->returnLocalCaptured || targetCount == 0 || regCaptured[target]; RegScope rs(this); @@ -1164,8 +1178,7 @@ struct Compiler { AstLocal* var = func->args.data[i]; AstExpr* arg = i < expr->args.size ? expr->args.data[i] : nullptr; - bool canUseParameterTarget = - FFlag::LuauCompileMoveElision && fi->returnKind == ReturnKind::Parameter && fi->returnLocal == var && !noTargetMoveElision; + bool canUseParameterTarget = fi->returnKind == ReturnKind::Parameter && fi->returnLocal == var && !noTargetMoveElision; if (i + 1 == expr->args.size && func->args.size > expr->args.size && isExprMultRet(arg)) { @@ -1189,7 +1202,7 @@ struct Compiler } else if (Variable* vv = variables.find(var); vv && vv->written) { - if (canUseParameterTarget && !isRegisterUsedInCallArguments(expr, arg, FFlag::LuauCompileMoveElisionFix ? i : i + 1, target)) + if (canUseParameterTarget && !isRegisterUsedInCallArguments(expr, arg, i, target)) { if (arg) compileExprTemp(arg, target); @@ -1232,7 +1245,7 @@ struct Compiler { args.push_back({var, uint8_t(reg), {Constant::Type_Unknown}, kDefaultAllocPc, lv ? lv->init : nullptr}); } - else if (canUseParameterTarget && !isRegisterUsedInCallArguments(expr, arg, FFlag::LuauCompileMoveElisionFix ? i : i + 1, target)) + else if (canUseParameterTarget && !isRegisterUsedInCallArguments(expr, arg, i, target)) { compileExprTemp(arg, target); @@ -1243,10 +1256,7 @@ struct Compiler uint8_t temp = allocReg(arg, 1u); uint32_t allocpc = bytecode.getDebugPC(); - if (FFlag::LuauCompileMoveElision) - temp = compileExprAutoTemp(arg, temp, target); - else - compileExprTemp(arg, temp); + temp = compileExprAutoTemp(arg, temp, target); args.push_back({var, temp, {Constant::Type_Unknown}, allocpc, arg}); } @@ -1277,8 +1287,7 @@ struct Compiler } } - AstLocal* resultLocal = - FFlag::LuauCompileMoveElision && fi->returnKind == ReturnKind::Local && !noTargetMoveElision ? fi->returnLocal : nullptr; + AstLocal* resultLocal = fi->returnKind == ReturnKind::Local && !noTargetMoveElision ? fi->returnLocal : nullptr; // the inline frame will be used to compile return statements as well as to reject recursive inlining attempts inlineFrames.push_back({func, oldLocals, target, targetCount, resultLocal}); @@ -1324,6 +1333,13 @@ struct Compiler bool terminatesEarly = false; + std::vector* callerClasses = currClasses; + if (FFlag::DebugLuauUserDefinedClasses) + { + if (std::vector* calleeClasses = enclosingClasses.find(func)) + currClasses = calleeClasses; + } + for (size_t i = 0; i < func->body->body.size; ++i) { AstStat* stat = func->body->body.data[i]; @@ -1348,6 +1364,8 @@ struct Compiler } } + currClasses = callerClasses; + // for the fallthrough path we need to ensure we clear out target registers if (!terminatesEarly) { @@ -1524,7 +1542,7 @@ struct Compiler // Optimization: pcall/xpcall functions have a special fastcall instruction int fastPcallId = -1; - if (FFlag::LuauCompileFastpcall && options.optimizationLevel >= 1 && !expr->self) + if (options.optimizationLevel >= 1 && !expr->self) { if (AstExprGlobal* g = expr->func->as(); g && canImport(g)) { @@ -1555,7 +1573,7 @@ struct Compiler compileExprTempTop(fi->expr, selfreg); } } - else if (bfid < 0 && (!FFlag::LuauCompileFastpcall || fastPcallId < 0)) + else if (bfid < 0 && fastPcallId < 0) { compileExprTempTop(expr->func, regs); } @@ -1595,13 +1613,7 @@ struct Compiler setDebugLine(fi->indexLocation); if (FFlag::DebugLuauUserDefinedClasses && fi->privateAccess) - { - // The parser shouldn't even set expr->privateAccess unless it was parsing a class body, so we just assert on currClass here rather - // than erroring if it's not set - LUAU_ASSERT(currClass); - compilePrivateFieldAccess(fi, regs, selfreg, true); - } else { BytecodeBuilder::StringRef iname = sref(fi->index); @@ -1615,11 +1627,11 @@ struct Compiler hintTemporaryExprRegType(fi->expr, selfreg, LBC_TYPE_TABLE, /* instLength */ 2); } } - else if (bfid >= 0 || (FFlag::LuauCompileFastpcall && fastPcallId >= 0)) + else if (bfid >= 0 || fastPcallId >= 0) { size_t fastcallLabel = bytecode.emitLabel(); - if (FFlag::LuauCompileFastpcall && fastPcallId >= 0) + if (fastPcallId >= 0) { uint8_t explicitArgs = uint8_t(expr->args.size - (multCall ? 1 : 0)); bytecode.emitABC(LOP_FASTPCALL, uint8_t(fastPcallId), explicitArgs, 0); @@ -1654,11 +1666,9 @@ struct Compiler // Without deoptimization we cannot break VARARG sequences. // So VARARG producer or consumer cannot be inlined, because it creates a diamond(with slow path). bool canInline = currentFunction->functionDepth != 0 && !multCall && !multRet; - if (FFlag::LuauEmitCallFeedback && (bfid < 0 && (!FFlag::LuauCompileFastpcall || fastPcallId < 0)) && canInline && !constructCall) + if (FFlag::LuauEmitCallFeedback && (bfid < 0 && fastPcallId < 0) && canInline && !constructCall) { - uint32_t fbSlot = FFlag::LuauCompileRefactorFeedback || FFlag::DebugLuauUserDefinedClasses - ? bytecode.addCallTargetSlot(uint32_t(bytecode.getInstructionCount())) - : bytecode.addFbSlot_DEPRECATED(LuauFeedbackType::LFT_CALLTARGET); + uint32_t fbSlot = bytecode.addCallTargetSlot(uint32_t(bytecode.getInstructionCount())); bytecode.emitABC(LOP_CALLFB, regs, multCall ? 0 : uint8_t(expr->self + expr->args.size + 1), multRet ? 0 : uint8_t(targetCount + 1)); bytecode.emitAux(fbSlot); } @@ -1687,6 +1697,10 @@ struct Compiler if (!f) return false; + // Functions with private field accesses capture classes by value so they can't share closures + if (FFlag::DebugLuauUserDefinedClasses && enclosingClasses.contains(func)) + return false; + for (AstLocal* uv : f->upvals) { Variable* ul = variables.find(uv); @@ -1716,7 +1730,7 @@ struct Compiler return true; } - void compileExprFunction(AstExprFunction* expr, uint8_t target) + void compileExprFunction(AstExprFunction* expr, uint8_t target, uint8_t classReg = kInvalidReg) { RegScope rs(this); @@ -1734,35 +1748,95 @@ struct Compiler captures.clear(); captures.reserve(f->upvals.size()); - for (AstLocal* uv : f->upvals) + if (FFlag::DebugLuauUserDefinedClasses) { - LUAU_ASSERT(uv->functionDepth < expr->functionDepth); - - if (int reg = getLocalReg(uv); reg >= 0) + size_t i = 0; + if (std::vector* classes = enclosingClasses.find(expr)) { - // note: we can't check if uv is an upvalue in the current frame because inlining can migrate from upvalues to locals - Variable* ul = variables.find(uv); - bool immutable = !ul || !ul->written; + i = classes->size(); + + // Each class is always stored at the same upvalue index + for (size_t j = 0; j < classes->size() - 1; ++j) + captures.push_back({LCT_UPVAL, static_cast(j)}); - captures.push_back({immutable ? LCT_VAL : LCT_REF, uint8_t(reg)}); + // If we're directly compiling a method, then the class defining it is in a register specified by classReg + captures.push_back( + classReg != kInvalidReg ? Capture{LCT_VAL, classReg} : Capture{LCT_UPVAL, static_cast(classes->size() - 1)} + ); } - else if (const Constant* uc = locstants.find(uv); uc && uc->type != Constant::Type_Unknown) + + for (; i < f->upvals.size(); ++i) { - // inlining can result in an upvalue capture of a constant, in which case we can't capture without a temporary register - uint8_t reg = allocReg(expr, 1u); - compileExprConstant(expr, uc, reg); + AstLocal* uv = f->upvals[i]; + LUAU_ASSERT(uv->functionDepth < expr->functionDepth); + + if (int reg = getLocalReg(uv); reg >= 0) + { + // note: we can't check if uv is an upvalue in the current frame because inlining can migrate from upvalues to locals + Variable* ul = variables.find(uv); + bool immutable = !ul || !ul->written; + + captures.push_back({immutable ? LCT_VAL : LCT_REF, uint8_t(reg)}); + } + else if (const Constant* uc = locstants.find(uv); uc && uc->type != Constant::Type_Unknown) + { + // inlining can result in an upvalue capture of a constant, in which case we can't capture without a temporary register + uint8_t reg = allocReg(expr, 1u); + compileExprConstant(expr, uc, reg); - captures.push_back({LCT_VAL, reg}); + captures.push_back({LCT_VAL, reg}); + } + else + { + LUAU_ASSERT(uv->functionDepth < expr->functionDepth - 1); + + // get upvalue from parent frame + // note: this will add uv to the current upvalue list if necessary + uint8_t uid = getUpval(uv); + + captures.push_back({LCT_UPVAL, uid}); + } } - else + + if (captures.size() >= kMaxUpvalueCount) + { + CompileError::raise( + expr->location, "Out of upvalue registers when trying to allocate %s: exceeded limit %d", expr->debugname.value, kMaxUpvalueCount + ); + } + } + else + { + for (AstLocal* uv : f->upvals) { - LUAU_ASSERT(uv->functionDepth < expr->functionDepth - 1); + LUAU_ASSERT(uv->functionDepth < expr->functionDepth); + + if (int reg = getLocalReg(uv); reg >= 0) + { + // note: we can't check if uv is an upvalue in the current frame because inlining can migrate from upvalues to locals + Variable* ul = variables.find(uv); + bool immutable = !ul || !ul->written; + + captures.push_back({immutable ? LCT_VAL : LCT_REF, uint8_t(reg)}); + } + else if (const Constant* uc = locstants.find(uv); uc && uc->type != Constant::Type_Unknown) + { + // inlining can result in an upvalue capture of a constant, in which case we can't capture without a temporary register + uint8_t reg = allocReg(expr, 1u); + compileExprConstant(expr, uc, reg); + + captures.push_back({LCT_VAL, reg}); + } + else + { + LUAU_ASSERT(uv->functionDepth < expr->functionDepth - 1); - // get upvalue from parent frame - // note: this will add uv to the current upvalue list if necessary - uint8_t uid = getUpval(uv); + // get upvalue from parent frame + // note: this will add uv to the current upvalue list if necessary + uint8_t uid = getUpval(uv); - captures.push_back({LCT_UPVAL, uid}); + captures.push_back({LCT_UPVAL, uid}); + } } } @@ -1793,11 +1867,9 @@ struct Compiler } } - void compileClassDeclaration(AstStatClass* decl) + void compileClassObject(AstStatClass* decl, uint8_t dest) { LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); - // We allocate one register to store the class object. - auto dest = allocReg(decl, 1u); // CLI-194693: We probably need to add something here to prevent: // @@ -1807,15 +1879,6 @@ struct Compiler // end // // ... properties and methods need to share a namespace. - - pushLocal(decl->name, dest, kDefaultAllocPc); - if (FFlag::LuauExportValueSyntax && decl->exported) - { - // we want to eagerly insert into the exported classes map, as the class may be referenced by one of its methods - ensureExportTable(decl); - exports.exportedClasses[decl->name] = dest; - } - RegScope _(this); // The bottom bit of the C slot indicates whether the class is open. @@ -1845,8 +1908,8 @@ struct Compiler bytecode.emitAux(0xDEADBEEF); BytecodeBuilder::ClassShape shape; - shape.className = bytecode.addConstantString(sref(decl->name->name)); - checkConstant(shape.className, decl->name->location); + shape.className = bytecode.addConstantString(sref(decl->getName())); + checkConstant(shape.className, decl->getNameLocation()); // We use this as temporary storage while we make all of the closures // associated with this particular class. Another option would be to @@ -1887,7 +1950,7 @@ struct Compiler // a free floating function, but instead of assigning it to // a local or a global, we use `NEWCLASSMEMBER` to add it to // our class definition. - compileExprFunction(method.function, temp); + compileExprFunction(method.function, temp, dest); switch (method.access) { case AstClassAccess::Public: @@ -1932,6 +1995,62 @@ struct Compiler bytecode.patchAux(auxOffset, classConst); } + void compileClassDeclaration(AstStatClass* decl) + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + // Optimization: if possible, compile class directly into target local register + if (decl->declModifier == AstStatClass::DeclModifier::None) + { + if (int reg = getExprLocalReg(decl->exprName); reg >= 0 && (decl->super == nullptr || reg != getExprLocalReg(decl->super))) + { + compileClassObject(decl, uint8_t(reg)); + return; + } + } + + + switch (decl->declModifier) + { + case AstStatClass::DeclModifier::None: + { + RegScope rs(this); + uint8_t reg = allocReg(decl, 1u); + compileClassObject(decl, reg); + + LValue var = compileLValue(decl->exprName, rs); + compileAssign(var, reg, decl->exprName); + } + break; + + case AstStatClass::DeclModifier::Export: + { + LUAU_ASSERT(FFlag::LuauExportValueSyntax); + uint8_t reg = allocReg(decl, 1u); + pushLocal(decl->localName, reg, kDefaultAllocPc); + checkExportedLocal(decl->localName, decl->location); + // we eagerly insert into the exported classes map, as the class may be referenced by one of its methods + ensureExportTable(decl); + exports.exportedClasses[decl->localName] = reg; + compileClassObject(decl, reg); + } + break; + + case AstStatClass::DeclModifier::Local: + case AstStatClass::DeclModifier::Const: + { + uint8_t reg = allocReg(decl, 1u); + pushLocal(decl->localName, reg, kDefaultAllocPc); + compileClassObject(decl, reg); + } + break; + + default: + LUAU_ASSERT(!"Unexpected class declaration modifier"); + break; + } + } + LuauOpcode getUnaryOp(AstExprUnary::Op op) { switch (op) @@ -2030,13 +2149,6 @@ struct Compiler return (cv != nullptr) && (cv->type == Constant::Type_Vectorf || cv->type == Constant::Type_Vectord); } - bool isConstantInteger(AstExpr* node) - { - const Constant* cv = constants.find(node); - - return cv && cv->type == Constant::Type_Integer; - } - Constant getConstant(AstExpr* node) { const Constant* cv = constants.find(node); @@ -2060,8 +2172,8 @@ struct Compiler std::swap(left, right); } - // disable fast path for vectors and integers because supporting it would require a new opcode - if (operandIsConstant && (isConstantVector(right) || (FFlag::LuauIntegerType2 && isConstantInteger(right)))) + // disable fast path for vectors because supporting it would require a new opcode + if (operandIsConstant && isConstantVector(right)) operandIsConstant = false; uint8_t rl = compileExprAuto(left, rs); @@ -2173,10 +2285,6 @@ struct Compiler cid = bytecode.addConstantNumber(c->valueNumber); break; - case Constant::Type_Integer: - cid = bytecode.addConstantInteger(c->valueInteger64); - break; - case Constant::Type_Vectorf: cid = bytecode.addConstantVectorf(c->valueVectorf[0], c->valueVectorf[1], c->valueVectorf[2], c->valueVectorf[3]); break; @@ -2417,18 +2525,6 @@ struct Compiler { RegScope rs(this); - // Special case for integer constants, like -1000000000i - AstExprConstantInteger* cint = expr->expr->as(); - if (FFlag::LuauIntegerType2 && (expr->op == AstExprUnary::Op::Minus) && (cint != nullptr)) - { - int32_t cid = bytecode.addConstantInteger((int64_t)(~(uint64_t)cint->value + 1)); - if (cid < 0) - CompileError::raise(expr->location, "Exceeded constant limit; simplify the code to compile"); - - emitLoadK(target, cid); - return; - } - uint8_t re = compileExprAuto(expr->expr, rs); bytecode.emitABC(getUnaryOp(expr->op), target, re, 0); @@ -3025,29 +3121,47 @@ struct Compiler return options.optimizationLevel >= 1 && getGlobalState(globals, expr->name) == Global::Default; } - uint8_t getCurClassUpval() + struct PrivateFieldInfo { - LUAU_ASSERT(currClass); - - return getUpval(currClass->name); - } + uint8_t offset; + uint8_t classNest; + bool isStatic; + }; - void compilePrivateFieldAccess(AstExprIndexName* expr, uint8_t target, uint8_t source, bool namecall = false) + PrivateFieldInfo computePrivateFieldInfo(const AstName& name, const Location& exprLocation) { - if (!classPrivateFieldOffsets.contains(currClass)) - CompileError::raise(expr->location, "Attempt to access private field of a class with no private fields"); + LUAU_ASSERT(currClasses && !currClasses->empty()); - DenseHashMap>& offsets = classPrivateFieldOffsets[currClass]; + // Walk enclosing classes until we find which one contains the private field being accessed + for (int32_t classIndex = static_cast(currClasses->size()) - 1; classIndex >= 0; --classIndex) + { + AstStatClass* currClass = (*currClasses)[classIndex]; - if (!offsets.contains(expr->index)) - CompileError::raise(expr->location, "Attempt to access undefined private field"); + // TODO CLI-234874: Ensure only classes with private fields are captured + if (!classPrivateFieldOffsets.contains(currClass)) + continue; - auto [offset, isStatic] = offsets[expr->index]; + DenseHashMap>& offsets = classPrivateFieldOffsets[currClass]; + + if (!offsets.contains(name)) + continue; - uint8_t classUpval = getCurClassUpval(); + std::pair& entry = offsets[name]; + return {entry.first, static_cast(classIndex), entry.second}; + } - bytecode.emitABC(LOP_GETPRIVATEFIELD, target, source, classUpval); - bytecode.emitAux((static_cast(namecall) << 9) | (static_cast(isStatic) << 8) | offset); + CompileError::raise(exprLocation, "Attempt to access undefined private field"); + } + + void compilePrivateFieldAccess(AstExprIndexName* expr, uint8_t target, uint8_t source, bool namecall = false) + { + PrivateFieldInfo fieldInfo = computePrivateFieldInfo(expr->index, expr->location); + + // Class upvalues are stored at the level of class nest they're defined at + bytecode.emitABC(LOP_GETPRIVATEFIELD, target, source, fieldInfo.classNest); + bytecode.emitAux( + (static_cast(namecall) << 9) | (static_cast(fieldInfo.isStatic) << 8) | static_cast(fieldInfo.offset) + ); } void compileExprIndexName(AstExprIndexName* expr, uint8_t target, bool targetTemp = false) @@ -3104,23 +3218,15 @@ struct Compiler if (int localReg = getExprLocalReg(expr->expr); localReg >= 0) // Locals can be indexed directly reg = uint8_t(localReg); - else if (targetTemp && FFlag::LuauCompileMoveElision) // If target is a temp register, we can compute the result directly into it + else if (targetTemp) // If target is a temp register, we can compute the result directly into it reg = compileExprAutoTemp(expr->expr, target); - else if (targetTemp && !FFlag::LuauCompileMoveElision) - compileExprTemp(expr->expr, target); else reg = compileExprAuto(expr->expr, rs); setDebugLine(expr->indexLocation); if (FFlag::DebugLuauUserDefinedClasses && expr->privateAccess) - { - // The parser shouldn't even set expr->privateAccess unless it was parsing a class body, so we just assert on currClass here rather than - // erroring if it's not set - LUAU_ASSERT(currClass); - return compilePrivateFieldAccess(expr, target, reg); - } BytecodeBuilder::StringRef iname = sref(expr->index); int32_t cid = bytecode.addConstantString(iname); @@ -3246,18 +3352,6 @@ struct Compiler } break; - case Constant::Type_Integer: - { - int64_t l = cv->valueInteger64; - - int32_t cid = bytecode.addConstantInteger(l); - if (cid < 0) - CompileError::raise(node->location, "Exceeded constant limit; simplify the code to compile"); - - emitLoadK(target, cid); - } - break; - case Constant::Type_Vectorf: { int32_t cid = bytecode.addConstantVectorf(cv->valueVectorf[0], cv->valueVectorf[1], cv->valueVectorf[2], cv->valueVectorf[3]); @@ -3329,14 +3423,6 @@ struct Compiler emitLoadK(target, cid); } - else if (AstExprConstantInteger* expr = node->as()) - { - int32_t cid = bytecode.addConstantInteger(expr->value); - if (cid < 0) - CompileError::raise(expr->location, "Exceeded constant limit; simplify the code to compile"); - - emitLoadK(target, cid); - } else if (AstExprConstantString* expr = node->as()) { int32_t cid = bytecode.addConstantString(sref(expr->value)); @@ -3456,8 +3542,6 @@ struct Compiler uint8_t compileExprAutoTemp(AstExpr* node, uint8_t target, uint8_t forbiddenSourceReg = kInvalidReg) { - LUAU_ASSERT(FFlag::LuauCompileMoveElision); - if (options.optimizationLevel == 0) { compileExprTemp(node, target); @@ -3497,17 +3581,7 @@ struct Compiler // note: the register is owned by the parent scope uint8_t reg = allocReg(node, 1u); - - if (FFlag::LuauCompileMoveElision) - { - return compileExprAutoTemp(node, reg); - } - else - { - compileExprTemp(node, reg); - - return reg; - } + return compileExprAutoTemp(node, reg); } void compileExprSide(AstExpr* node) @@ -3793,23 +3867,16 @@ struct Compiler case LValue::Kind_PrivateField: { - LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses && currClass); - - if (!classPrivateFieldOffsets.contains(currClass)) - CompileError::raise(lv.location, "Attempt to %s private field of a class with no private fields", set ? "assign" : "access"); - - DenseHashMap>& offsets = classPrivateFieldOffsets[currClass]; - - if (!offsets.contains(lv.astName)) - CompileError::raise(lv.location, "Attempt to %s undefined private field", set ? "assign" : "access"); + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); - auto [offset, isStatic] = offsets[lv.astName]; + PrivateFieldInfo fieldInfo = computePrivateFieldInfo(lv.astName, lv.location); - if (isStatic && set) + if (fieldInfo.isStatic && set) CompileError::raise(lv.location, "Attempt to assign static field of a class"); - bytecode.emitABC(set ? LOP_SETPRIVATEFIELD : LOP_GETPRIVATEFIELD, reg, lv.reg, getCurClassUpval()); - bytecode.emitAux(static_cast(offset)); + // Class upvalues are stored at the level of class nest they're defined at + bytecode.emitABC(set ? LOP_SETPRIVATEFIELD : LOP_GETPRIVATEFIELD, reg, lv.reg, fieldInfo.classNest); + bytecode.emitAux(static_cast(fieldInfo.offset)); } break; @@ -4300,7 +4367,7 @@ struct Compiler } } - if (FFlag::LuauCompileMoveElision && !consecutive && stat->list.size == 1 && !isExprMultRet(stat->list.data[0])) + if (!consecutive && stat->list.size == 1 && !isExprMultRet(stat->list.data[0])) { // Single expression return might be able to elide the extra move into the fresh register temp = allocReg(stat, 1u); @@ -4371,7 +4438,7 @@ struct Compiler } // Declaration of a local that becomes the inlined function result can use the return target register - if (FFlag::LuauCompileMoveElision && !inlineFrames.empty() && inlineFrames.back().resultLocal == stat->vars.data[0]) + if (!inlineFrames.empty() && inlineFrames.back().resultLocal == stat->vars.data[0]) { compileExprTemp(stat->values.data[0], inlineFrames.back().target); @@ -4508,7 +4575,11 @@ struct Compiler { // we need to re-fold constants in the loop body with the new value; this reuses computed constant values elsewhere in the tree locstants[var].type = Constant::Type_Number; - locstants[var].valueNumber = from + iv * step; + + if (FFlag::LuauCompileLoopUnrollNegativeZero) + locstants[var].valueNumber = iv == 0 ? from : from + iv * step; // first iteration preserves the 'from' number exactly + else + locstants[var].valueNumber = from + iv * step; if (iv == 0) foldConstants( @@ -5239,6 +5310,8 @@ struct Compiler { visitor.locals.insert(stat->name); } + else if (AstStatClass* stat = body->body.data[i]->as(); stat && stat->declModifier != AstStatClass::DeclModifier::None) + visitor.locals.insert(stat->localName); } condition->visit(&visitor); @@ -5284,8 +5357,7 @@ struct Compiler l.debugpc = bytecode.getDebugPC(); l.allocpc = allocpc == kDefaultAllocPc ? l.debugpc : allocpc; - if (FFlag::LuauCompileMoveElision) - regCaptured[reg] = l.captured; + regCaptured[reg] = l.captured; if (FFlag::LuauCompileReuseLocalRegs) localUses[reg]++; @@ -5373,8 +5445,7 @@ struct Compiler activeLocals--; } - if (FFlag::LuauCompileMoveElision) - regCaptured[l->reg] = false; + regCaptured[l->reg] = false; LUAU_ASSERT(localUses[l->reg] != 0); localUses[l->reg]--; @@ -5430,8 +5501,7 @@ struct Compiler activeLocals--; } - if (FFlag::LuauCompileMoveElision) - regCaptured[l->reg] = false; + regCaptured[l->reg] = false; if (options.debugLevel >= 2) { @@ -5723,6 +5793,9 @@ struct Compiler for (AstLocal* uv : f->upvals) { + if (uv == kInvalidUpvalue) + continue; + LUAU_ASSERT(uv->functionDepth < node->functionDepth); if (uv->functionDepth == node->functionDepth - 1) @@ -5796,64 +5869,57 @@ struct Compiler bool visit(AstStatReturn* stat) override { - if (FFlag::LuauCompileMoveElision) + if (stat->list.size == 1 && !self->isExprMultRet(stat->list.data[0])) { - if (stat->list.size == 1 && !self->isExprMultRet(stat->list.data[0])) + if (AstExprLocal* exprLocal = unwrapExprOfType(stat->list.data[0])) { - if (AstExprLocal* exprLocal = unwrapExprOfType(stat->list.data[0])) - { - ReturnKind kind = ReturnKind::Local; - AstLocal* local = exprLocal->local; + ReturnKind kind = ReturnKind::Local; + AstLocal* local = exprLocal->local; - for (auto el : func->args) + for (auto el : func->args) + { + if (el == local) { - if (el == local) - { - kind = ReturnKind::Parameter; - break; - } + kind = ReturnKind::Parameter; + break; } + } - if (exprLocal->upvalue) - { - kind = ReturnKind::Expression; - local = nullptr; - } + if (exprLocal->upvalue) + { + kind = ReturnKind::Expression; + local = nullptr; + } - if (returnKind == ReturnKind::None) - { - returnKind = kind; - returnLocal = local; - } - else if (returnKind != kind || returnLocal != local) - { - returnKind = ReturnKind::Unknown; - returnLocal = nullptr; - } + if (returnKind == ReturnKind::None) + { + returnKind = kind; + returnLocal = local; } - else + else if (returnKind != kind || returnLocal != local) { - if (returnKind == ReturnKind::None) - { - returnKind = ReturnKind::Expression; - } - else if (returnKind != ReturnKind::Expression) - { - returnKind = ReturnKind::Unknown; - returnLocal = nullptr; - } + returnKind = ReturnKind::Unknown; + returnLocal = nullptr; } } else { - returnsOne = false; - returnKind = ReturnKind::Unknown; - returnLocal = nullptr; + if (returnKind == ReturnKind::None) + { + returnKind = ReturnKind::Expression; + } + else if (returnKind != ReturnKind::Expression) + { + returnKind = ReturnKind::Unknown; + returnLocal = nullptr; + } } } else { - returnsOne &= stat->list.size == 1 && !self->isExprMultRet(stat->list.data[0]); + returnsOne = false; + returnKind = ReturnKind::Unknown; + returnLocal = nullptr; } return false; @@ -5862,14 +5928,15 @@ struct Compiler struct ClassVisitor : AstVisitor { - DenseHashMap& enclosingClasses; + DenseHashMap>& enclosingClasses; DenseHashMap>>& classPrivateFieldOffsets; - // TODO: CLI-226024 this needs to become a stack to handle nested classes properly. - AstStatClass* currClass = nullptr; + std::vector classStack; + std::vector funcStack; + bool currFuncShouldCapture = false; ClassVisitor( - DenseHashMap& enclosingClasses, + DenseHashMap>& enclosingClasses, DenseHashMap>>& classPrivateFieldOffsets ) : enclosingClasses(enclosingClasses) @@ -5880,7 +5947,13 @@ struct Compiler bool visit(AstStatClass* cls) override { - currClass = cls; + if (cls->super) + cls->super->visit(this); + + classStack.push_back(cls); + + if (classStack.size() > kMaxClassNest) + CompileError::raise(cls->location, "Class nest exceeded the maximum depth of %zu", kMaxClassNest); DenseHashMap> privateOffsets; uint8_t numPrivateInstanceProps = 0; @@ -5909,14 +5982,37 @@ struct Compiler if (!privateOffsets.empty()) classPrivateFieldOffsets[cls] = std::move(privateOffsets); - currClass = nullptr; + classStack.pop_back(); + + if (classStack.empty()) + currFuncShouldCapture = false; return false; } bool visit(AstExprFunction* func) override { - enclosingClasses[func] = currClass; + funcStack.push_back(func); + + // Skip visiting annotations + func->body->visit(this); + + funcStack.pop_back(); + + if (currFuncShouldCapture) + { + LUAU_ASSERT(!classStack.empty()); + enclosingClasses[func] = classStack; // Kinda wasteful: we copy classStack each time + } + + return false; + } + + bool visit(AstExprIndexName* index) override + { + if (index->privateAccess) + currFuncShouldCapture = true; + return true; } }; @@ -6104,12 +6200,13 @@ struct Compiler Exports exports; - // Maps functions to the class they are enclosed in, if any. This is used to determine the context for private field access. - // TODO: CLI-226024 this should map to std::vector instead to support nested classes - DenseHashMap enclosingClasses; + // Maps class methods with private field classes to a list of classes enclosing it, with the front of the vector containing the outermost + // enclosing class, This is used to know both which functions contain private field accesses and need to capture classes as upvalues, to know + // which entry in classPrivateFieldOffsets to use, and to know which upvalue index a class object will be in at runtime + DenseHashMap> enclosingClasses; // Maps classes to their private field offsets. Classes are mapped to a mapping from field name to offset/whether the field is static. DenseHashMap>> classPrivateFieldOffsets; - AstStatClass* currClass = nullptr; + std::vector* currClasses = nullptr; }; static void setCompileOptionsForNativeCompilation(CompileOptions& options) @@ -6257,12 +6354,12 @@ void compileOrThrow(BytecodeBuilder& bytecode, const ParseResult& parseResult, A uint8_t protoflags = 0; if (FFlag::DebugLuauUserDefinedClasses && compiler.enclosingClasses.contains(expr)) - compiler.currClass = compiler.enclosingClasses[expr]; + compiler.currClasses = compiler.enclosingClasses.find(expr); compiler.compileFunction(expr, protoflags); if (FFlag::DebugLuauUserDefinedClasses) - compiler.currClass = nullptr; + compiler.currClasses = nullptr; // If a function has native attribute and the whole module is not native, we set LPF_NATIVE_FUNCTION flag // This ensures that LPF_NATIVE_MODULE and LPF_NATIVE_FUNCTION are exclusive. @@ -6305,7 +6402,7 @@ void compileOrThrow(BytecodeBuilder& bytecode, const std::string& source, const compileOrThrow(bytecode, result, names, options); } -std::string compile(const std::string& source, const CompileOptions& options, const ParseOptions& parseOptions, BytecodeEncoder* encoder) +std::string compile(const std::string& source, const CompileOptions& options, const ParseOptions& parseOptions) { LUAU_TIMETRACE_SCOPE("compile", "Compiler"); @@ -6324,7 +6421,7 @@ std::string compile(const std::string& source, const CompileOptions& options, co try { - BytecodeBuilder bcb(encoder); + BytecodeBuilder bcb; compileOrThrow(bcb, result, names, options); return bcb.getBytecode(); @@ -6359,14 +6456,6 @@ void setCompileConstantNumber(CompileConstant* constant, double n) target->valueNumber = n; } -void setCompileConstantInteger64(CompileConstant* constant, int64_t l) -{ - Compile::Constant* target = reinterpret_cast(constant); - - target->type = Compile::Constant::Type_Integer; - target->valueInteger64 = l; -} - void setCompileConstantVector(CompileConstant* constant, float x, float y, float z, float w) { Compile::Constant* target = reinterpret_cast(constant); diff --git a/Compiler/src/ConstantFolding.cpp b/Compiler/src/ConstantFolding.cpp index d0bd65567..c54042aaf 100644 --- a/Compiler/src/ConstantFolding.cpp +++ b/Compiler/src/ConstantFolding.cpp @@ -9,9 +9,7 @@ #include #include -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) -LUAU_FASTFLAGVARIABLE(LuauCompileNoFoldVectorEqW) LUAU_FASTFLAGVARIABLE(LuauCompileTableFoldFix) namespace Luau @@ -50,11 +48,6 @@ static bool constantsEqual(const Constant& la, const Constant& ra) case Constant::Type_Table: return ra.type == Constant::Type_Table && la.valueTable == ra.valueTable; - case Constant::Type_Integer: - if (FFlag::LuauIntegerType2) - return ra.type == Constant::Type_Integer && la.valueInteger64 == ra.valueInteger64; - [[fallthrough]]; - default: LUAU_ASSERT(!"Unexpected constant type in comparison"); return false; @@ -490,8 +483,7 @@ static void foldBinary(Constant& result, AstExprBinary::Op op, const Constant& l break; case AstExprBinary::CompareNe: - if (la.type != Constant::Type_Unknown && ra.type != Constant::Type_Unknown && - !(FFlag::LuauCompileNoFoldVectorEqW && vectorsDifferOnlyInW(la, ra))) + if (la.type != Constant::Type_Unknown && ra.type != Constant::Type_Unknown && !vectorsDifferOnlyInW(la, ra)) { result.type = Constant::Type_Boolean; result.valueBoolean = !constantsEqual(la, ra); @@ -499,8 +491,7 @@ static void foldBinary(Constant& result, AstExprBinary::Op op, const Constant& l break; case AstExprBinary::CompareEq: - if (la.type != Constant::Type_Unknown && ra.type != Constant::Type_Unknown && - !(FFlag::LuauCompileNoFoldVectorEqW && vectorsDifferOnlyInW(la, ra))) + if (la.type != Constant::Type_Unknown && ra.type != Constant::Type_Unknown && !vectorsDifferOnlyInW(la, ra)) { result.type = Constant::Type_Boolean; result.valueBoolean = constantsEqual(la, ra); @@ -875,11 +866,6 @@ struct ConstantVisitor : AstVisitor result.type = Constant::Type_Number; result.valueNumber = expr->value; } - else if (AstExprConstantInteger* expr = node->as()) - { - result.type = Constant::Type_Integer; - result.valueInteger64 = expr->value; - } else if (AstExprConstantString* expr = node->as()) { result.type = Constant::Type_String; diff --git a/Compiler/src/ConstantFolding.h b/Compiler/src/ConstantFolding.h index dea659cd8..b0549fb53 100644 --- a/Compiler/src/ConstantFolding.h +++ b/Compiler/src/ConstantFolding.h @@ -20,7 +20,6 @@ struct Constant Type_Nil, Type_Boolean, Type_Number, - Type_Integer, Type_Vectorf, Type_Vectord, Type_String, @@ -34,7 +33,6 @@ struct Constant { bool valueBoolean; double valueNumber; - int64_t valueInteger64; float valueVectorf[4]; double valueVectord[4]; size_t valueTable; // index pointing to constant table entry with table's constant properties diff --git a/Compiler/src/CostModel.cpp b/Compiler/src/CostModel.cpp index 4595d7f6d..c4f4ce871 100644 --- a/Compiler/src/CostModel.cpp +++ b/Compiler/src/CostModel.cpp @@ -120,7 +120,7 @@ struct CostVisitor : AstVisitor return model(expr->expr); } else if (node->is() || node->is() || node->is() || - node->is() || node->is()) + node->is()) { return Cost(0, Cost::kLiteral); } diff --git a/Compiler/src/Types.cpp b/Compiler/src/Types.cpp index 392a80c24..157e14566 100644 --- a/Compiler/src/Types.cpp +++ b/Compiler/src/Types.cpp @@ -3,8 +3,6 @@ #include "Luau/BytecodeBuilder.h" -LUAU_FASTFLAG(LuauIntegerFastcalls) - namespace Luau { @@ -25,8 +23,6 @@ static LuauBytecodeType getPrimitiveType(AstName name) return LBC_TYPE_BOOLEAN; else if (name == "number") return LBC_TYPE_NUMBER; - else if (name == "integer") - return LBC_TYPE_INTEGER; else if (name == "string") return LBC_TYPE_STRING; else if (name == "thread") @@ -566,7 +562,8 @@ struct TypeMapVisitor : AstVisitor { if (AstExprGlobal* object = node->expr->as()) { - if (LuauBytecodeType ty = LuauBytecodeType(libraryMemberTypeCb(object->name.value, node->index.value)); ty != LBC_TYPE_ANY) + if (LuauBytecodeType ty = LuauBytecodeType(libraryMemberTypeCb(object->name.value, node->index.value)); + ty != LBC_TYPE_ANY && ty != LBC_TYPE_INTEGER_DEPRECATED) { // TODO: 'resolvedExprs' is more limited than 'exprTypes' which limits full inference of more complex types that a user // callback can return @@ -578,9 +575,6 @@ struct TypeMapVisitor : AstVisitor case LBC_TYPE_NUMBER: resolvedExprs[node] = &builtinTypes.numberType; break; - case LBC_TYPE_INTEGER: - resolvedExprs[node] = &builtinTypes.integerType; - break; case LBC_TYPE_STRING: resolvedExprs[node] = &builtinTypes.stringType; break; @@ -703,13 +697,6 @@ struct TypeMapVisitor : AstVisitor return false; } - bool visit(AstExprConstantInteger* node) override - { - recordResolvedType(node, &builtinTypes.integerType); - - return false; - } - bool visit(AstExprConstantString* node) override { recordResolvedType(node, &builtinTypes.stringType); @@ -771,7 +758,9 @@ struct TypeMapVisitor : AstVisitor case LBF_BUFFER_WRITEU32: case LBF_BUFFER_WRITEF32: case LBF_BUFFER_WRITEF64: - case LBF_BUFFER_WRITEINTEGER: + case LBF_BUFFER_WRITEVECTORF32X2: + case LBF_BUFFER_WRITEVECTORF32X3: + case LBF_BUFFER_WRITEVECTORF32X4: break; case LBF_MATH_ABS: case LBF_MATH_ACOS: @@ -862,61 +851,11 @@ struct TypeMapVisitor : AstVisitor case LBF_VECTOR_MIN: case LBF_VECTOR_MAX: case LBF_VECTOR_LERP: + case LBF_BUFFER_READVECTORF32X2: + case LBF_BUFFER_READVECTORF32X3: + case LBF_BUFFER_READVECTORF32X4: recordResolvedType(node, &builtinTypes.vectorType); break; - - case LBF_INTEGER_ADD: - case LBF_INTEGER_SUB: - case LBF_INTEGER_MOD: - case LBF_INTEGER_MUL: - case LBF_INTEGER_DIV: - case LBF_INTEGER_IDIV: - case LBF_INTEGER_UDIV: - case LBF_INTEGER_REM: - case LBF_INTEGER_UREM: - case LBF_INTEGER_MAX: - case LBF_INTEGER_MIN: - case LBF_INTEGER_BAND: - case LBF_INTEGER_BOR: - case LBF_INTEGER_BNOT: - case LBF_INTEGER_BXOR: - case LBF_INTEGER_LSHIFT: - case LBF_INTEGER_RSHIFT: - case LBF_INTEGER_ARSHIFT: - case LBF_INTEGER_LROTATE: - case LBF_INTEGER_RROTATE: - case LBF_INTEGER_EXTRACT: - case LBF_INTEGER_COUNTLZ: - case LBF_INTEGER_COUNTRZ: - case LBF_INTEGER_BSWAP: - case LBF_INTEGER_CLAMP: - case LBF_INTEGER_NEG: - case LBF_INTEGER_CREATE: - case LBF_BUFFER_READINTEGER: - if (!FFlag::LuauIntegerFastcalls) - return true; - recordResolvedType(node, &builtinTypes.integerType); - break; - - case LBF_INTEGER_TONUMBER: - if (!FFlag::LuauIntegerFastcalls) - return true; - recordResolvedType(node, &builtinTypes.numberType); - break; - - case LBF_INTEGER_LT: - case LBF_INTEGER_LE: - case LBF_INTEGER_GT: - case LBF_INTEGER_GE: - case LBF_INTEGER_ULT: - case LBF_INTEGER_ULE: - case LBF_INTEGER_UGT: - case LBF_INTEGER_UGE: - case LBF_INTEGER_BTEST: - if (!FFlag::LuauIntegerFastcalls) - return true; - recordResolvedType(node, &builtinTypes.booleanType); - break; } } else diff --git a/Compiler/src/Types.h b/Compiler/src/Types.h index 199347407..e60b3b93f 100644 --- a/Compiler/src/Types.h +++ b/Compiler/src/Types.h @@ -23,7 +23,6 @@ struct BuiltinAstTypes // AstName use here will not match the AstNameTable, but the way we use them here always forces a full string compare AstTypeReference booleanType{{}, std::nullopt, AstName{"boolean"}, std::nullopt, {}}; AstTypeReference numberType{{}, std::nullopt, AstName{"number"}, std::nullopt, {}}; - AstTypeReference integerType{{}, std::nullopt, AstName{"integer"}, std::nullopt, {}}; AstTypeReference stringType{{}, std::nullopt, AstName{"string"}, std::nullopt, {}}; AstTypeReference vectorType{{}, std::nullopt, AstName{"vector"}, std::nullopt, {}}; diff --git a/Compiler/src/ValueTracking.cpp b/Compiler/src/ValueTracking.cpp index cf306d699..90b0d4ae7 100644 --- a/Compiler/src/ValueTracking.cpp +++ b/Compiler/src/ValueTracking.cpp @@ -1,6 +1,7 @@ // This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details #include "ValueTracking.h" +#include "Luau/Ast.h" #include "Luau/Lexer.h" #include "Luau/SmallVector.h" @@ -161,6 +162,26 @@ struct ValueVisitor : AstVisitor return false; } + bool visit(AstStatClass* node) override + { + LUAU_ASSERT(FFlag::DebugLuauUserDefinedClasses); + + if (node->declModifier == AstStatClass::DeclModifier::None) + assign(node->exprName); + // we can do more here if we decide to constant fold classes/objects + + if (node->super) + node->super->visit(this); + + for (const AstClassMember& member : node->members) + { + if (const AstClassMethod* method = member.get_if()) + method->function->visit(this); + } + + return false; + } + bool visit(AstStatLocalFunction* node) override { if (FFlag::LuauCompileReuseLocalRegs) diff --git a/Compiler/src/lcode.cpp b/Compiler/src/lcode.cpp index abda9d09c..ab5bc1c14 100644 --- a/Compiler/src/lcode.cpp +++ b/Compiler/src/lcode.cpp @@ -44,11 +44,6 @@ void luau_set_compile_constant_number(lua_CompileConstant* constant, double n) Luau::setCompileConstantNumber(constant, n); } -void luau_set_compile_constant_integer64(lua_CompileConstant* constant, int64_t l) -{ - Luau::setCompileConstantInteger64(constant, l); -} - void luau_set_compile_constant_vector(lua_CompileConstant* constant, float x, float y, float z, float w) { Luau::setCompileConstantVector(constant, x, y, z, w); diff --git a/Inliner/src/JitInliner.cpp b/Inliner/src/JitInliner.cpp index 2feaec7b5..bfb472064 100644 --- a/Inliner/src/JitInliner.cpp +++ b/Inliner/src/JitInliner.cpp @@ -28,7 +28,6 @@ LUAU_FASTINTVARIABLE(LuauJitInlineThreshold, 25) LUAU_FASTINTVARIABLE(LuauJitInlineThresholdMaxBoost, 300) LUAU_FASTINTVARIABLE(LuauJitInlineSmallFunSize, 128) LUAU_FASTINTVARIABLE(LuauJitInlineTooLongFunSize, 0xFFFF); -LUAU_FASTFLAG(LuauCompileRefactorFeedback) LUAU_FASTFLAGVARIABLE(LuauBytecodeFold) LUAU_FASTFLAGVARIABLE(LuauBytecodeSlotAlloc) LUAU_FASTFLAGVARIABLE(DebugLuauBytecodeSlotAllocStats) @@ -169,10 +168,7 @@ std::optional emitCode(lua_State* L, RuntimeBcFunction& graph, std::ve if (slot.callTarget.inst != kUnassignedPC) pc = insnsPC[slot.callTarget.inst]; - if (FFlag::LuauCompileRefactorFeedback || FFlag::DebugLuauUserDefinedClasses) - slotId = bcb.addCallTargetSlot(pc); - else - slotId = bcb.addFbSlot_DEPRECATED(LFT_CALLTARGET, pc); + slotId = bcb.addCallTargetSlot(pc); } else if (slot.kind == LFT_CONSTRUCT) { diff --git a/Inliner/src/RuntimeBytecodeBuilder.h b/Inliner/src/RuntimeBytecodeBuilder.h index 4c8da89cf..d84e5344e 100644 --- a/Inliner/src/RuntimeBytecodeBuilder.h +++ b/Inliner/src/RuntimeBytecodeBuilder.h @@ -31,8 +31,8 @@ struct RuntimeBytecodeBuilder : public BytecodeBuilder std::vector& runtimeConstants; std::vector& protos; - explicit RuntimeBytecodeBuilder(lua_State* L, std::vector& constants, std::vector& protos, BytecodeEncoder* encoder = nullptr) - : BytecodeBuilder(encoder) + explicit RuntimeBytecodeBuilder(lua_State* L, std::vector& constants, std::vector& protos) + : BytecodeBuilder() , L(L) , runtimeConstants(constants) , protos(protos) @@ -54,8 +54,6 @@ struct RuntimeBytecodeBuilder : public BytecodeBuilder return LUA_TBOOLEAN; case Constant::Type_Number: return LUA_TNUMBER; - case Constant::Type_Integer: - return LUA_TINTEGER; case Constant::Type_Vectorf: case Constant::Type_Vectord: return LUA_TVECTOR; @@ -117,9 +115,6 @@ struct RuntimeBytecodeBuilder : public BytecodeBuilder case LUA_TNUMBER: formatAppend(result, "%.17g", nvalue(c)); break; - case LUA_TINTEGER: - formatAppend(result, "%lld", (long long)(int64_t)lvalue(c)); - break; case LUA_TVECTOR: { const LUA_VECTOR_TYPE* vec = vvalue(c); @@ -207,9 +202,6 @@ struct RuntimeBytecodeBuilder : public BytecodeBuilder CodeData result; result.code = insns; - if (encoder) - encoder->encode(result.code.data(), result.code.size()); - // Pack line info. int span = calcLinesSpan(); result.linegaplog2 = int(std::log2(span)); diff --git a/Inliner/src/TValueVmConstImpl.cpp b/Inliner/src/TValueVmConstImpl.cpp index 293f41708..1b5f43cc4 100644 --- a/Inliner/src/TValueVmConstImpl.cpp +++ b/Inliner/src/TValueVmConstImpl.cpp @@ -262,9 +262,6 @@ std::optional TValueVmConstImpl::eq(const BcOp& lhsOp, const BcOp& rhsOp) if (ttype(lhs) != ttype(rhs)) return false; - if (ttisinteger(lhs)) - return lvalue(lhs) == lvalue(rhs); - if (ttisstring(lhs)) return tsvalue(lhs) == tsvalue(rhs); // strings are interned } diff --git a/Sources.cmake b/Sources.cmake index 3169fb286..e34489146 100644 --- a/Sources.cmake +++ b/Sources.cmake @@ -412,7 +412,6 @@ target_sources(Luau.VM PRIVATE VM/src/ludata.cpp VM/src/lutf8lib.cpp VM/src/lveclib.cpp - VM/src/lintlib.cpp VM/src/lvmexecute.cpp VM/src/lclass.cpp VM/src/lclasslib.cpp diff --git a/VM/include/lua.h b/VM/include/lua.h index fbf8f2acf..5a16941b6 100644 --- a/VM/include/lua.h +++ b/VM/include/lua.h @@ -78,7 +78,6 @@ enum lua_Type LUA_TLIGHTUSERDATA, LUA_TNUMBER, - LUA_TINTEGER, // When vector components are 'float', vector fits into the TValue #if LUA_VECTOR_DOUBLE == 0 @@ -159,7 +158,6 @@ LUA_API void lua_xpush(lua_State* from, lua_State* to, int idx); LUA_API int lua_isnumber(lua_State* L, int idx); LUA_API int lua_isstring(lua_State* L, int idx); -LUA_API int lua_isinteger64(lua_State* L, int idx); LUA_API int lua_iscfunction(lua_State* L, int idx); LUA_API int lua_isLfunction(lua_State* L, int idx); LUA_API int lua_isuserdata(lua_State* L, int idx); @@ -175,7 +173,6 @@ LUA_API int lua_tointegerx(lua_State* L, int idx, int* isnum); LUA_API unsigned lua_tounsignedx(lua_State* L, int idx, int* isnum); LUA_API const LUA_VECTOR_TYPE* lua_tovector(lua_State* L, int idx); LUA_API int lua_toboolean(lua_State* L, int idx); -LUA_API int64_t lua_tointeger64(lua_State* L, int idx, int* isinteger); LUA_API const char* lua_tolstring(lua_State* L, int idx, size_t* len); LUA_API const char* lua_tostringatom(lua_State* L, int idx, int* atom); LUA_API const char* lua_tolstringatom(lua_State* L, int idx, size_t* len, int* atom); @@ -198,7 +195,6 @@ LUA_API const void* lua_topointer(lua_State* L, int idx); LUA_API void lua_pushnil(lua_State* L); LUA_API void lua_pushnumber(lua_State* L, double n); LUA_API void lua_pushinteger(lua_State* L, int n); -LUA_API void lua_pushinteger64(lua_State* L, int64_t n); LUA_API void lua_pushunsigned(lua_State* L, unsigned n); #if LUA_VECTOR_SIZE == 4 LUA_API void lua_pushvector(lua_State* L, LUA_VECTOR_TYPE x, LUA_VECTOR_TYPE y, LUA_VECTOR_TYPE z, LUA_VECTOR_TYPE w); @@ -256,6 +252,18 @@ LUA_API int lua_setfenv(lua_State* L, int idx); ** `load' and `call' functions (load and run Luau bytecode) */ LUA_API int luau_load(lua_State* L, const char* chunkname, const char* data, size_t size, int env); +// Same result as luau_load, but every function other than the main one is built on its first access, so functions that never run save +// memory. Takes ownership of owner: data must stay valid and unchanged until release(owner) is called, when no unbuilt function of the +// chunk is left (possibly before luau_loadlazy returns). release may be NULL. +LUA_API int luau_loadlazy( + lua_State* L, + const char* chunkname, + const char* data, + size_t size, + int env, + void* owner, + void (*release)(void* owner) +); LUA_API void lua_call(lua_State* L, int nargs, int nresults); LUA_API int lua_pcall(lua_State* L, int nargs, int nresults, int errfunc); LUA_API int lua_cpcall(lua_State* L, lua_CFunction func, void* ud); @@ -468,7 +476,6 @@ LUA_API void lua_userdatadirectfield_setvector(void* result, LUA_VECTOR_TYPE x, LUA_API void lua_userdatadirectfield_setvector(void* result, LUA_VECTOR_TYPE x, LUA_VECTOR_TYPE y, LUA_VECTOR_TYPE z); #endif LUA_API void lua_userdatadirectfield_setboolean(void* result, int b); -LUA_API void lua_userdatadirectfield_setinteger64(void* result, int64_t n); LUA_API void lua_userdatadirectfield_setnil(void* result); LUA_API void lua_setlightuserdataname(lua_State* L, int tag, const char* name); @@ -514,7 +521,6 @@ LUA_API int lua_unref(lua_State* L, int ref); #define lua_islightuserdata(L, n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) #define lua_isnil(L, n) (lua_type(L, (n)) == LUA_TNIL) #define lua_isboolean(L, n) (lua_type(L, (n)) == LUA_TBOOLEAN) -#define lua_isinteger64(L, n) (lua_type(L, (n)) == LUA_TINTEGER) #define lua_isvector(L, n) (lua_type(L, (n)) == LUA_TVECTOR) #define lua_isthread(L, n) (lua_type(L, (n)) == LUA_TTHREAD) #define lua_isbuffer(L, n) (lua_type(L, (n)) == LUA_TBUFFER) diff --git a/VM/include/lualib.h b/VM/include/lualib.h index 371f4f3de..16d2aeab7 100644 --- a/VM/include/lualib.h +++ b/VM/include/lualib.h @@ -29,9 +29,7 @@ LUALIB_API int luaL_checkboolean(lua_State* L, int narg); LUALIB_API int luaL_optboolean(lua_State* L, int narg, int def); LUALIB_API int luaL_checkinteger(lua_State* L, int numArg); -LUALIB_API int64_t luaL_checkinteger64(lua_State* L, int numArg); LUALIB_API int luaL_optinteger(lua_State* L, int nArg, int def); -LUALIB_API int64_t luaL_optinteger64(lua_State* L, int nArg, int64_t def); LUALIB_API unsigned luaL_checkunsigned(lua_State* L, int numArg); LUALIB_API unsigned luaL_optunsigned(lua_State* L, int numArg, unsigned def); @@ -151,8 +149,6 @@ LUALIB_API int luaopen_debug(lua_State* L); #define LUA_VECLIBNAME "vector" LUALIB_API int luaopen_vector(lua_State* L); -#define LUA_INTLIBNAME "integer" -LUALIB_API int luaopen_integer(lua_State* L); // open all builtin libraries LUALIB_API void luaL_openlibs(lua_State* L); diff --git a/VM/src/lapi.cpp b/VM/src/lapi.cpp index 8da4dd7fd..40d5ce061 100644 --- a/VM/src/lapi.cpp +++ b/VM/src/lapi.cpp @@ -477,23 +477,6 @@ int lua_toboolean(lua_State* L, int idx) return !l_isfalse(o); } -int64_t lua_tointeger64(lua_State* L, int idx, int* isinteger) -{ - const TValue* o = index2addr(L, idx); - if (ttisinteger(o)) - { - if (isinteger) - *isinteger = 1; - return lvalue(o); - } - else - { - if (isinteger) - *isinteger = 0; - return 0; - } -} - const char* lua_tolstring(lua_State* L, int idx, size_t* len) { StkId o = index2addr(L, idx); @@ -701,13 +684,6 @@ void lua_pushinteger(lua_State* L, int n) api_incr_top(L); } -void lua_pushinteger64(lua_State* L, int64_t n) -{ - ensure_stack(L, 1); - setlvalue(L->top, n); - api_incr_top(L); -} - void lua_pushunsigned(lua_State* L, unsigned u) { ensure_stack(L, 1); @@ -2270,12 +2246,6 @@ void lua_userdatadirectfield_setboolean(void* result, int b) setbvalue(slot, b); } -void lua_userdatadirectfield_setinteger64(void* result, int64_t n) -{ - TValue* slot = LUA_VECTOR_DOUBLE ? static_cast(result)->slot : static_cast(result); - setlvalue(slot, n); -} - void lua_userdatadirectfield_setnil(void* result) { TValue* slot = LUA_VECTOR_DOUBLE ? static_cast(result)->slot : static_cast(result); diff --git a/VM/src/laux.cpp b/VM/src/laux.cpp index 2b8c734f1..0839d9230 100644 --- a/VM/src/laux.cpp +++ b/VM/src/laux.cpp @@ -232,23 +232,11 @@ int luaL_checkinteger(lua_State* L, int narg) return d; } -int64_t luaL_checkinteger64(lua_State* L, int narg) -{ - if (!lua_isinteger64(L, narg)) - tag_error(L, narg, LUA_TINTEGER); - return lua_tointeger64(L, narg, nullptr); -} - int luaL_optinteger(lua_State* L, int narg, int def) { return luaL_opt(L, luaL_checkinteger, narg, def); } -int64_t luaL_optinteger64(lua_State* L, int narg, int64_t def) -{ - return luaL_opt(L, luaL_checkinteger64, narg, def); -} - unsigned luaL_checkunsigned(lua_State* L, int narg) { int isnum; @@ -557,14 +545,6 @@ void luaL_addvalueany(luaL_Strbuf* B, int idx) luaL_addlstring(B, s, len); break; } - case LUA_TINTEGER: - { - int64_t n = lua_tointeger64(L, idx, nullptr); - char s[LUAI_MAXINT2STR]; - char* e = luai_int2str(s, n); - luaL_addlstring(B, s, e - s); - break; - } default: { size_t len; @@ -656,14 +636,6 @@ const char* luaL_tolstring(lua_State* L, int idx, size_t* len) case LUA_TSTRING: lua_pushvalue(L, idx); break; - case LUA_TINTEGER: - { - int64_t l = lua_tointeger64(L, idx, nullptr); - char s[LUAI_MAXINT2STR]; - char* e = luai_int2str(s, l); - lua_pushlstring(L, s, e - s); - break; - } default: { const void* ptr = lua_topointer(L, idx); diff --git a/VM/src/lbaselib.cpp b/VM/src/lbaselib.cpp index 548cd2158..cc6f2a3d4 100644 --- a/VM/src/lbaselib.cpp +++ b/VM/src/lbaselib.cpp @@ -12,8 +12,6 @@ #include #include -LUAU_FASTFLAGVARIABLE(LuauFastpcall) - static void writestring(const char* s, size_t l) { fwrite(s, 1, l, stdout); @@ -433,15 +431,13 @@ int luaopen_base(lua_State* L) lua_pushcclosurek(L, luaB_pcally, "pcall", 0, luaB_pcallcont); - if (FFlag::LuauFastpcall) - L->global->builtinPcall = clvalue(luaA_toobject(L, -1)); + L->global->builtinPcall = clvalue(luaA_toobject(L, -1)); lua_setfield(L, -2, "pcall"); lua_pushcclosurek(L, luaB_xpcally, "xpcall", 0, luaB_xpcallcont); - if (FFlag::LuauFastpcall) - L->global->builtinXpcall = clvalue(luaA_toobject(L, -1)); + L->global->builtinXpcall = clvalue(luaA_toobject(L, -1)); lua_setfield(L, -2, "xpcall"); diff --git a/VM/src/lbuflib.cpp b/VM/src/lbuflib.cpp index ee67cb9aa..07b63d5d6 100644 --- a/VM/src/lbuflib.cpp +++ b/VM/src/lbuflib.cpp @@ -8,7 +8,7 @@ #include #endif -LUAU_FASTFLAG(LuauIntegerLibrary) +LUAU_FASTFLAGVARIABLE(DebugLuauBufferVectorLibrary) #include @@ -105,93 +105,120 @@ static int buffer_writeinteger(lua_State* L) return 0; } -static int buffer_readlong(lua_State* L) +template +static int buffer_readfp(lua_State* L) { size_t len = 0; void* buf = luaL_checkbuffer(L, 1, &len); int offset = luaL_checkinteger(L, 2); - if (isoutofbounds(offset, len, sizeof(uint64_t))) + if (isoutofbounds(offset, len, sizeof(T))) luaL_error(L, "buffer access out of bounds"); - int64_t val; - memcpy(&val, (char*)buf + offset, sizeof(int64_t)); + T val; #if defined(LUAU_BIG_ENDIAN) - val = buffer_swapbe(val); + static_assert(sizeof(T) == sizeof(StorageType), "type size must match to reinterpret data"); + StorageType tmp; + memcpy(&tmp, (char*)buf + offset, sizeof(tmp)); + tmp = buffer_swapbe(tmp); + + memcpy(&val, &tmp, sizeof(tmp)); +#else + memcpy(&val, (char*)buf + offset, sizeof(T)); #endif - lua_pushinteger64(L, val); + lua_pushnumber(L, double(val)); return 1; } -static int buffer_writelong(lua_State* L) +template +static int buffer_writefp(lua_State* L) { size_t len = 0; void* buf = luaL_checkbuffer(L, 1, &len); int offset = luaL_checkinteger(L, 2); - int64_t value = luaL_checkinteger64(L, 3); + double value = luaL_checknumber(L, 3); - if (isoutofbounds(offset, len, sizeof(int64_t))) + if (isoutofbounds(offset, len, sizeof(T))) luaL_error(L, "buffer access out of bounds"); + T val = T(value); + #if defined(LUAU_BIG_ENDIAN) - value = buffer_swapbe(value); + static_assert(sizeof(T) == sizeof(StorageType), "type size must match to reinterpret data"); + StorageType tmp; + memcpy(&tmp, &val, sizeof(tmp)); + tmp = buffer_swapbe(tmp); + + memcpy((char*)buf + offset, &tmp, sizeof(tmp)); +#else + memcpy((char*)buf + offset, &val, sizeof(T)); #endif - memcpy((char*)buf + offset, &value, sizeof(int64_t)); return 0; } -template -static int buffer_readfp(lua_State* L) +// Vector components are always serialized as 'N' contiguous little-endian 32-bit floats, independent of the VM's +// in-memory 'vector' representation (see the 'f32' suffix on the exposed names). LUA_VECTOR_DOUBLE builds narrow to f32. +template +static int buffer_readvector(lua_State* L) { size_t len = 0; void* buf = luaL_checkbuffer(L, 1, &len); int offset = luaL_checkinteger(L, 2); - if (isoutofbounds(offset, len, sizeof(T))) + if (isoutofbounds(offset, len, N * sizeof(float))) luaL_error(L, "buffer access out of bounds"); - T val; + float components[4] = {0.0f, 0.0f, 0.0f, 0.0f}; #if defined(LUAU_BIG_ENDIAN) - static_assert(sizeof(T) == sizeof(StorageType), "type size must match to reinterpret data"); - StorageType tmp; - memcpy(&tmp, (char*)buf + offset, sizeof(tmp)); - tmp = buffer_swapbe(tmp); + for (int i = 0; i < N; i++) + { + uint32_t raw; + memcpy(&raw, (char*)buf + offset + i * sizeof(float), sizeof(raw)); + raw = buffer_swapbe(raw); + memcpy(&components[i], &raw, sizeof(raw)); + } +#else + memcpy(components, (char*)buf + offset, N * sizeof(float)); +#endif - memcpy(&val, &tmp, sizeof(tmp)); +#if LUA_VECTOR_SIZE == 4 + lua_pushvector(L, components[0], components[1], components[2], components[3]); #else - memcpy(&val, (char*)buf + offset, sizeof(T)); + lua_pushvector(L, components[0], components[1], components[2]); #endif - lua_pushnumber(L, double(val)); return 1; } -template -static int buffer_writefp(lua_State* L) +template +static int buffer_writevector(lua_State* L) { size_t len = 0; void* buf = luaL_checkbuffer(L, 1, &len); int offset = luaL_checkinteger(L, 2); - double value = luaL_checknumber(L, 3); + const LUA_VECTOR_TYPE* vec = luaL_checkvector(L, 3); - if (isoutofbounds(offset, len, sizeof(T))) + if (isoutofbounds(offset, len, N * sizeof(float))) luaL_error(L, "buffer access out of bounds"); - T val = T(value); + float components[4]; + for (int i = 0; i < N; i++) + components[i] = float(vec[i]); #if defined(LUAU_BIG_ENDIAN) - static_assert(sizeof(T) == sizeof(StorageType), "type size must match to reinterpret data"); - StorageType tmp; - memcpy(&tmp, &val, sizeof(tmp)); - tmp = buffer_swapbe(tmp); - - memcpy((char*)buf + offset, &tmp, sizeof(tmp)); + for (int i = 0; i < N; i++) + { + uint32_t raw; + memcpy(&raw, &components[i], sizeof(raw)); + raw = buffer_swapbe(raw); + memcpy((char*)buf + offset + i * sizeof(float), &raw, sizeof(raw)); + } #else - memcpy((char*)buf + offset, &val, sizeof(T)); + memcpy((char*)buf + offset, components, N * sizeof(float)); #endif return 0; @@ -395,47 +422,28 @@ static const luaL_Reg bufferlib[] = { {"fill", buffer_fill}, {"readbits", buffer_readbits}, {"writebits", buffer_writebits}, - {"readinteger", buffer_readlong}, - {"writeinteger", buffer_writelong}, {NULL, NULL}, }; -static const luaL_Reg bufferlib_NOINTEGER[] = { - {"create", buffer_create}, - {"fromstring", buffer_fromstring}, - {"tostring", buffer_tostring}, - {"readi8", buffer_readinteger}, - {"readu8", buffer_readinteger}, - {"readi16", buffer_readinteger}, - {"readu16", buffer_readinteger}, - {"readi32", buffer_readinteger}, - {"readu32", buffer_readinteger}, - {"readf32", buffer_readfp}, - {"readf64", buffer_readfp}, - {"writei8", buffer_writeinteger}, - {"writeu8", buffer_writeinteger}, - {"writei16", buffer_writeinteger}, - {"writeu16", buffer_writeinteger}, - {"writei32", buffer_writeinteger}, - {"writeu32", buffer_writeinteger}, - {"writef32", buffer_writefp}, - {"writef64", buffer_writefp}, - {"readstring", buffer_readstring}, - {"writestring", buffer_writestring}, - {"len", buffer_len}, - {"copy", buffer_copy}, - {"fill", buffer_fill}, - {"readbits", buffer_readbits}, - {"writebits", buffer_writebits}, +static const luaL_Reg buffervectorlib[] = { + {"readvectorf32x2", buffer_readvector<2>}, + {"readvectorf32x3", buffer_readvector<3>}, + {"writevectorf32x2", buffer_writevector<2>}, + {"writevectorf32x3", buffer_writevector<3>}, +#if LUA_VECTOR_SIZE == 4 + {"readvectorf32x4", buffer_readvector<4>}, + {"writevectorf32x4", buffer_writevector<4>}, +#endif {NULL, NULL}, }; int luaopen_buffer(lua_State* L) { - if (FFlag::LuauIntegerLibrary) - luaL_register(L, LUA_BUFFERLIBNAME, bufferlib); - else - luaL_register(L, LUA_BUFFERLIBNAME, bufferlib_NOINTEGER); + luaL_register(L, LUA_BUFFERLIBNAME, bufferlib); + + // register into the buffer table left on the stack by the call above + if (FFlag::DebugLuauBufferVectorLibrary) + luaL_register(L, NULL, buffervectorlib); return 1; } diff --git a/VM/src/lbuiltins.cpp b/VM/src/lbuiltins.cpp index f386d36a0..9f2c3dc96 100644 --- a/VM/src/lbuiltins.cpp +++ b/VM/src/lbuiltins.cpp @@ -1321,16 +1321,6 @@ static int luauF_tostring(lua_State* L, StkId res, TValue* arg0, int nresults, S setsvalue(L, res, tsvalue(arg0)); return 1; } - case LUA_TINTEGER: - { - if (luaC_needsGC(L)) - return -1; // we can't call luaC_checkGC so fall back to C implementation - - char s[LUAI_MAXINT2STR]; - char* e = luai_int2str(s, lvalue(arg0)); - setsvalue(L, res, luaS_newlstr(L, s, e - s)); - return 1; - } } // fall back to generic C implementation @@ -1455,6 +1445,59 @@ static int luauF_writefp(lua_State* L, StkId res, TValue* arg0, int nresults, St return -1; } +// N contiguous little-endian f32 components; independent of the VM vector representation (LUA_VECTOR_DOUBLE narrows to f32). +template +static int luauF_readvector(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) +{ + if (N > LUA_VECTOR_SIZE) + return -1; + +#if !defined(LUAU_BIG_ENDIAN) + if (nparams >= 2 && nresults <= 1 && ttisbuffer(arg0) && ttisnumber(args)) + { + int offset; + luai_num2int(offset, nvalue(args)); + if (checkoutofbounds(offset, bufvalue(arg0)->len, N * sizeof(float))) + return -1; + + float components[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + memcpy(components, (char*)bufvalue(arg0)->data + unsigned(offset), N * sizeof(float)); + + setvvalue(L, res, components[0], components[1], components[2], components[3]); + return 1; + } +#endif + + return -1; +} + +template +static int luauF_writevector(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) +{ + if (N > LUA_VECTOR_SIZE) + return -1; + +#if !defined(LUAU_BIG_ENDIAN) + if (nparams >= 3 && nresults <= 0 && ttisbuffer(arg0) && ttisnumber(args) && ttisvector(args + 1)) + { + int offset; + luai_num2int(offset, nvalue(args)); + if (checkoutofbounds(offset, bufvalue(arg0)->len, N * sizeof(float))) + return -1; + + const LUA_VECTOR_TYPE* v = vvalue(args + 1); + float components[4]; + for (int i = 0; i < N; i++) + components[i] = float(v[i]); + + memcpy((char*)bufvalue(arg0)->data + unsigned(offset), components, N * sizeof(float)); + return 0; + } +#endif + + return -1; +} + static int luauF_vectormagnitude(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) { if (nparams >= 1 && nresults <= 1 && ttisvector(arg0)) @@ -1789,708 +1832,6 @@ static int luauF_isfinite(lua_State* L, StkId res, TValue* arg0, int nresults, S return -1; } -static int luauF_integertonumber(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - setnvalue(res, cast_num(lvalue(arg0))); - return 1; - } - - return -1; -} - -static int luauF_integeradd(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a1 = lvalue(arg0); - int64_t a2 = lvalue(args); - setlvalue(res, (int64_t)((uint64_t)a1 + (uint64_t)a2)); - return 1; - } - - return -1; -} - -static int luauF_integersub(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a1 = lvalue(arg0); - int64_t a2 = lvalue(args); - setlvalue(res, (int64_t)((uint64_t)a1 - (uint64_t)a2)); - return 1; - } - - return -1; -} - -static int luauF_integerneg(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - setlvalue(res, (int64_t)(~(uint64_t)lvalue(arg0) + 1)); - return 1; - } - - return -1; -} - -static int luauF_integerdiv(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a = lvalue(arg0); - int64_t b = lvalue(args); - - if ((b == 0) || ((a == LLONG_MIN) && (b == -1))) - return -1; - - setlvalue(res, a / b); - return 1; - } - - return -1; -} - -static int luauF_integerudiv(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t a = (uint64_t)lvalue(arg0); - uint64_t b = (uint64_t)lvalue(args); - - if (b == 0) - return -1; - - setlvalue(res, a / b); - return 1; - } - - return -1; -} - -static int luauF_integerband(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - uint64_t r = (uint64_t)lvalue(arg0); - - for (int i = 2; i <= nparams; ++i) - { - if (!ttisinteger(args + (i - 2))) - return -1; - - r &= (uint64_t)lvalue(args + (i - 2)); - } - - setlvalue(res, r); - return 1; - } - - return -1; -} - -static int luauF_integerbor(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - uint64_t r = (uint64_t)lvalue(arg0); - - for (int i = 2; i <= nparams; ++i) - { - if (!ttisinteger(args + (i - 2))) - return -1; - - r |= (uint64_t)lvalue(args + (i - 2)); - } - - setlvalue(res, r); - return 1; - } - - return -1; -} - -static int luauF_integerbxor(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - uint64_t r = (uint64_t)lvalue(arg0); - - for (int i = 2; i <= nparams; ++i) - { - if (!ttisinteger(args + (i - 2))) - return -1; - - r ^= (uint64_t)lvalue(args + (i - 2)); - } - - setlvalue(res, r); - return 1; - } - - return -1; -} - -static int luauF_integerbnot(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - setlvalue(res, ~(uint64_t)lvalue(arg0)); - return 1; - } - - return -1; -} - -static int luauF_integerbswap(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - uint64_t a = (uint64_t)lvalue(arg0); - - setlvalue( - res, - (a >> 56) | ((a & 0xFF000000000000) >> 40) | ((a & 0xFF0000000000) >> 24) | ((a & 0xFF00000000) >> 8) | ((a & 0xFF000000) << 8) | - ((a & 0xFF0000) << 24) | ((a & 0xFF00) << 40) | ((a & 0xFF) << 56) - ); - - return 1; - } - - return -1; -} - -static int luauF_integerbtest(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - uint64_t r = (uint64_t)lvalue(arg0); - - for (int i = 2; i <= nparams; ++i) - { - if (!ttisinteger(args + (i - 2))) - return -1; - - r &= (uint64_t)lvalue(args + (i - 2)); - } - - setbvalue(res, (r != 0)); - return 1; - } - - return -1; -} - -static int luauF_integerlt(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a = lvalue(arg0); - int64_t b = lvalue(args); - - setbvalue(res, a < b); - return 1; - } - - return -1; -} - -static int luauF_integerle(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a = lvalue(arg0); - int64_t b = lvalue(args); - - setbvalue(res, a <= b); - return 1; - } - - return -1; -} - -static int luauF_integergt(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a = lvalue(arg0); - int64_t b = lvalue(args); - - setbvalue(res, a > b); - return 1; - } - - return -1; -} - -static int luauF_integerge(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a = lvalue(arg0); - int64_t b = lvalue(args); - - setbvalue(res, a >= b); - return 1; - } - - return -1; -} - -static int luauF_integerult(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t a = (uint64_t)lvalue(arg0); - uint64_t b = (uint64_t)lvalue(args); - - setbvalue(res, a < b); - return 1; - } - - return -1; -} - -static int luauF_integerule(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t a = (uint64_t)lvalue(arg0); - uint64_t b = (uint64_t)lvalue(args); - - setbvalue(res, a <= b); - return 1; - } - - return -1; -} - -static int luauF_integerugt(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t a = (uint64_t)lvalue(arg0); - uint64_t b = (uint64_t)lvalue(args); - - setbvalue(res, a > b); - return 1; - } - - return -1; -} - -static int luauF_integeruge(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t a = (uint64_t)lvalue(arg0); - uint64_t b = (uint64_t)lvalue(args); - - setbvalue(res, a >= b); - return 1; - } - - return -1; -} - -static int luauF_integerurem(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t a = (uint64_t)lvalue(arg0); - uint64_t b = (uint64_t)lvalue(args); - - if (b == 0) - return -1; - - setlvalue(res, a % b); - return 1; - } - - return -1; -} - -static int luauF_integerrem(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a = lvalue(arg0); - int64_t b = lvalue(args); - - if (b == 0) - return -1; - - setlvalue(res, ((a == LLONG_MIN) && (b == -1)) ? 0 : (a % b)); - - return 1; - } - - return -1; -} - -static int luauF_integercountlz(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - uint64_t n = (uint64_t)lvalue(arg0); - int result; -#ifdef _MSC_VER -#ifdef _WIN64 - unsigned long rl; - result = _BitScanReverse64(&rl, n) ? 63 - int(rl) : 64; -#else - unsigned long rl; - if (_BitScanReverse(&rl, uint32_t(n >> 32))) - result = 31 - int(rl); - else - result = _BitScanReverse(&rl, uint32_t(n)) ? 63 - int(rl) : 64; -#endif -#else - result = (n == 0) ? 64 : __builtin_clzll(n); -#endif - - setlvalue(res, result); - - return 1; - } - - return -1; -} - -static int luauF_integercountrz(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisinteger(arg0)) - { - uint64_t n = (uint64_t)lvalue(arg0); - int result; -#ifdef _MSC_VER -#ifdef _WIN64 - unsigned long rl; - result = _BitScanForward64(&rl, n) ? int(rl) : 64; -#else - unsigned long rl; - if (_BitScanForward(&rl, uint32_t(n))) - result = int(rl); - else - result = _BitScanForward(&rl, uint32_t(n >> 32)) ? int(rl) + 32 : 64; -#endif -#else - result = (n == 0) ? 64 : __builtin_ctzll(n); -#endif - - setlvalue(res, result); - - return 1; - } - - return -1; -} - -static int luauF_integerextract(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if ((nparams >= 3) && !ttisinteger(args + 1)) - return -1; - - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t n = lvalue(arg0); - int64_t f = lvalue(args); - int64_t w = (nparams >= 3) ? lvalue(args + 1) : 1; - - if ((f < 0) || (f > 63) || (w < 1) || (w > 64) || ((f + w) > 64)) - return -1; - - setlvalue(res, (((uint64_t)n) >> f) & ((0xFFFFFFFFFFFFFFFFULL) >> (64 - w))); - return 1; - } - - return -1; -} - -static int luauF_integerclamp(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 3 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args) && ttisinteger(args + 1)) - { - int64_t a = lvalue(arg0); - int64_t rmin = lvalue(args); - int64_t rmax = lvalue(args + 1); - - if (rmin > rmax) - return -1; - - setlvalue(res, (a < rmin) ? rmin : ((a > rmax) ? rmax : a)); - return 1; - } - - return -1; -} - -static int luauF_integerlrotate(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t n = (uint64_t)lvalue(arg0); - unsigned s = (unsigned)((uint64_t)lvalue(args) % 64); - - setlvalue(res, s != 0 ? (n << s) | (n >> (64 - s)) : n); - - return 1; - } - - return -1; -} - -static int luauF_integerrrotate(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t n = (uint64_t)lvalue(arg0); - unsigned s = (unsigned)((uint64_t)lvalue(args) % 64); - - setlvalue(res, s != 0 ? (n >> s) | (n << (64 - s)) : n); - - return 1; - } - - return -1; -} - -static int luauF_integerlshift(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t n = (uint64_t)lvalue(arg0); - int64_t i = lvalue(args); - - setlvalue(res, ((i >= -63) && (i <= 63)) ? ((i < 0) ? (n >> (-i)) : (n << i)) : 0); - - return 1; - } - - return -1; -} - -static int luauF_integerarshift(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t n = lvalue(arg0); - int64_t i = lvalue(args); - - if ((i >= -63) && (i <= 63)) - { - setlvalue(res, (i < 0) ? (int64_t)((uint64_t)n << (-i)) : (n >> i)); - } - else if (i < -63) - { - setlvalue(res, 0); - } - else - { - setlvalue(res, (n < 0) ? -1 : 0); - } - - return 1; - } - - return -1; -} - -static int luauF_integerrshift(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - uint64_t n = (uint64_t)lvalue(arg0); - int64_t i = lvalue(args); - - setlvalue(res, ((i >= -63) && (i <= 63)) ? ((i < 0) ? (n << (-i)) : (n >> i)) : 0); - - return 1; - } - - return -1; -} - -static int luauF_integermin(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a1 = lvalue(arg0); - int64_t a2 = lvalue(args); - - int64_t r = (a2 < a1) ? a2 : a1; - - for (int i = 3; i <= nparams; ++i) - { - if (!ttisinteger(args + (i - 2))) - return -1; - - int64_t a = lvalue(args + (i - 2)); - - r = (a < r) ? a : r; - } - - setlvalue(res, r); - return 1; - } - - return -1; -} - -static int luauF_integermax(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a1 = lvalue(arg0); - int64_t a2 = lvalue(args); - - int64_t r = (a2 < a1) ? a1 : a2; - - for (int i = 3; i <= nparams; ++i) - { - if (!ttisinteger(args + (i - 2))) - return -1; - - int64_t a = lvalue(args + (i - 2)); - - r = (a > r) ? a : r; - } - - setlvalue(res, r); - return 1; - } - - return -1; -} - -static int luauF_integermul(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a1 = lvalue(arg0); - int64_t a2 = lvalue(args); - setlvalue(res, (int64_t)((uint64_t)a1 * (uint64_t)a2)); - return 1; - } - - return -1; -} - -static int luauF_integermod(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a1 = lvalue(arg0); - int64_t a2 = lvalue(args); - - if (a2 == 0) - return -1; - - if ((a1 == LLONG_MIN) && (a2 == -1)) - { - setlvalue(res, 0); - return 1; - } - - int64_t remainder = a1 % a2; - if (remainder && ((a1 < 0) != (a2 < 0))) - remainder += a2; - - setlvalue(res, remainder); - return 1; - } - - return -1; -} - -static int luauF_integeridiv(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 2 && nresults <= 1 && ttisinteger(arg0) && ttisinteger(args)) - { - int64_t a1 = lvalue(arg0); - int64_t a2 = lvalue(args); - if (a2 == 0) - return -1; - if ((a1 == LLONG_MIN) && (a2 == -1)) - return -1; - - int64_t result = a1 / a2; - // Floored division rounds toward -inf: adjust the truncated quotient down by 1 - // when the operands have opposite signs and the division is inexact. - if (((a1 ^ a2) < 0) && (a1 % a2)) - result -= 1; - setlvalue(res, result); - return 1; - } - - return -1; -} - -static int luauF_integercreate(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ - if (nparams >= 1 && nresults <= 1 && ttisnumber(arg0)) - { - double a1 = nvalue(arg0); - - if (a1 >= -9223372036854775808.0 && a1 < 9223372036854775808.0) - { - int64_t x = (int64_t)a1; - if ((double)x == a1) - { - setlvalue(res, x); - return 1; - } - } - - setnilvalue(res); - return 1; - } - - return -1; -} - -static int luauF_bufferreadlong(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ -#if !defined(LUAU_BIG_ENDIAN) - if (nparams >= 2 && nresults <= 1 && ttisbuffer(arg0) && ttisnumber(args)) - { - int offset; - luai_num2int(offset, nvalue(args)); - if (checkoutofbounds(offset, bufvalue(arg0)->len, sizeof(int64_t))) - return -1; - - int64_t val; - memcpy(&val, (char*)bufvalue(arg0)->data + unsigned(offset), sizeof(int64_t)); - setlvalue(res, val); - return 1; - } -#endif - - return -1; -} - -static int luauF_bufferwritelong(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) -{ -#if !defined(LUAU_BIG_ENDIAN) - if (nparams >= 3 && nresults <= 0 && ttisbuffer(arg0) && ttisnumber(args) && ttisinteger(args + 1)) - { - int offset; - luai_num2int(offset, nvalue(args)); - if (checkoutofbounds(offset, bufvalue(arg0)->len, sizeof(int64_t))) - return -1; - - int64_t val = lvalue(args + 1); - memcpy((char*)bufvalue(arg0)->data + unsigned(offset), &val, sizeof(int64_t)); - return 0; - } -#endif - - return -1; -} - static int luauF_missing(lua_State* L, StkId res, TValue* arg0, int nresults, StkId args, int nparams) { return -1; @@ -2743,50 +2084,58 @@ const luau_FastFunction luauF_table[256] = { luauF_isinf, luauF_isfinite, - luauF_integercreate, - luauF_integertonumber, - luauF_integerneg, - luauF_integeradd, - luauF_integersub, - luauF_integermul, - luauF_integerdiv, - luauF_integermin, - luauF_integermax, - luauF_integerrem, - luauF_integeridiv, - luauF_integerudiv, - luauF_integerurem, - luauF_integermod, - luauF_integerclamp, - luauF_integerband, - luauF_integerbor, - luauF_integerbnot, - luauF_integerbxor, - luauF_integerlt, - luauF_integerle, - luauF_integerult, - luauF_integerule, - luauF_integergt, - luauF_integerge, - luauF_integerugt, - luauF_integeruge, - luauF_integerlshift, - luauF_integerrshift, - luauF_integerarshift, - luauF_integerlrotate, - luauF_integerrrotate, - luauF_integerextract, - luauF_integerbtest, - luauF_integercountrz, - luauF_integercountlz, - luauF_integerbswap, - - luauF_bufferreadlong, - luauF_bufferwritelong, + // removed integer fastcalls + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + luauF_missing, + + luauF_missing, + luauF_missing, luauF_tablecreate, luauF_tableclear, + luauF_readvector<2>, + luauF_readvector<3>, + luauF_readvector<4>, + luauF_writevector<2>, + luauF_writevector<3>, + luauF_writevector<4>, + // When adding builtins, add them above this line; what follows is 64 "dummy" entries with luauF_missing fallback. // This is important so that older versions of the runtime that don't support newer builtins automatically fall back via luauF_missing. // Given the builtin addition velocity this should always provide a larger compatibility window than bytecode versions suggest. diff --git a/VM/src/ldebug.cpp b/VM/src/ldebug.cpp index b91a42102..18bc124f7 100644 --- a/VM/src/ldebug.cpp +++ b/VM/src/ldebug.cpp @@ -118,9 +118,23 @@ const char* lua_setlocal(lua_State* L, int level, int n) return name; } +// a breakpoint is set by line in a function and in every function defined in it, so all of them are built first +static void buildlazytree(lua_State* L, Proto* p) +{ + if (p->lazychunk) + luaV_buildlazyproto(L, p); + + for (int i = 0; i < p->sizep; ++i) + buildlazytree(L, p->p[i]); +} + static Closure* auxgetinfo(lua_State* L, const char* what, lua_Debug* ar, Closure* f, CallInfo* ci) { Closure* cl = NULL; + + if (!ci && !f->isC && f->l.p->lazychunk && strpbrk(what, "sln")) + luaV_buildlazyproto(L, f->l.p); + for (; *what; what++) { switch (*what) @@ -551,7 +565,11 @@ int lua_breakpoint(lua_State* L, int funcindex, int line, int enabled) const TValue* func = luaA_toobject(L, funcindex); api_check(L, ttisfunction(func) && !clvalue(func)->isC); - Proto* p = FFlag::LuauSkipDebugLocked ? getlatestproto(clvalue(func)->l.p) : clvalue(func)->l.p; + // a build can run Luau code that reallocates the stack, so func is not used past this point + Closure* cl = clvalue(func); + buildlazytree(L, cl->l.p); + + Proto* p = FFlag::LuauSkipDebugLocked ? getlatestproto(cl->l.p) : cl->l.p; // set the breakpoint to the next closest line with valid instructions int target = getnextline(p, line); diff --git a/VM/src/ldo.cpp b/VM/src/ldo.cpp index 6262d7aed..5abb3b742 100644 --- a/VM/src/ldo.cpp +++ b/VM/src/ldo.cpp @@ -18,7 +18,6 @@ #include -LUAU_FASTFLAG(LuauFastpcall) LUAU_FASTFLAGVARIABLE(LuauPcallErrorContinuationReentry) LUAU_FASTFLAGVARIABLE(LuauIsYieldableSimplify) @@ -272,15 +271,14 @@ static void performcall(lua_State* L, StkId func, int nresults, bool preparereen } else { - ptrdiff_t basecioffset = FFlag::LuauFastpcall ? saveci(L, L->ci - 1) : 0; + ptrdiff_t basecioffset = saveci(L, L->ci - 1); luau_execute(L); // process continuations up to the caller frame // this is needed because even when 'preparereentry' is false, current thread might be yieldable // in that case, luau_execute might exit with unfinished C continuation frames (e.g. pcall) - if (FFlag::LuauFastpcall) - resume_continue(L, basecioffset); + resume_continue(L, basecioffset); } if (!oldactive) @@ -296,31 +294,14 @@ bool luaD_performcally(lua_State* L, StkId func, int nresults) L->baseCcalls++; // Allow yielding across this C call - if (FFlag::LuauFastpcall) - { - L->ci->flags |= LUA_CALLINFO_OPYIELD; - - performcall(L, func, nresults, /* preparereentry */ false); - - if (L->status != LUA_OK) - return true; - - L->ci->flags &= ~LUA_CALLINFO_OPYIELD; - } - else - { - ptrdiff_t cioffset = saveci(L, L->ci); + L->ci->flags |= LUA_CALLINFO_OPYIELD; - performcall(L, func, nresults, /* preparereentry */ false); + performcall(L, func, nresults, /* preparereentry */ false); - if (L->status != LUA_OK) - { - CallInfo* caller = restoreci(L, cioffset); + if (L->status != LUA_OK) + return true; - caller->flags |= LUA_CALLINFO_OPYIELD; - return true; - } - } + L->ci->flags &= ~LUA_CALLINFO_OPYIELD; L->baseCcalls--; L->nCcalls--; @@ -503,7 +484,7 @@ int luaD_runfinalizers(lua_State* L, bool returnstatus) static void resume_continue(lua_State* L, ptrdiff_t basecioffset) { // unroll Luau/C combined stack, processing continuations - while ((L->status == LUA_OK || L->status == SCHEDULED_REENTRY) && L->ci > (FFlag::LuauFastpcall ? restoreci(L, basecioffset) : L->base_ci)) + while ((L->status == LUA_OK || L->status == SCHEDULED_REENTRY) && L->ci > restoreci(L, basecioffset)) { LUAU_ASSERT(L->baseCcalls == L->nCcalls); @@ -516,7 +497,7 @@ static void resume_continue(lua_State* L, ptrdiff_t basecioffset) LUAU_ASSERT(cl->c.cont); // fast continuation path for the synthetic pcall/xpcall frame - if (FFlag::LuauFastpcall && (L->ci->flags & LUA_CALLINFO_PCALL) != 0) + if ((L->ci->flags & LUA_CALLINFO_PCALL) != 0) { luau_pospcallsuccess(L); continue; diff --git a/VM/src/lfunc.cpp b/VM/src/lfunc.cpp index 0bcf0f064..cdba51491 100644 --- a/VM/src/lfunc.cpp +++ b/VM/src/lfunc.cpp @@ -5,6 +5,7 @@ #include "lstate.h" #include "lmem.h" #include "lgc.h" +#include "lvm.h" LUAU_FASTINTVARIABLE(LuauInlineHitsThreshold, 32) @@ -62,6 +63,7 @@ Proto* luaF_newproto(lua_State* L) f->optimized = nullptr; f->deoptimized = nullptr; f->cost = 0; + f->lazychunk = nullptr; return f; } @@ -249,7 +251,11 @@ void luaF_closeupval(lua_State* L, UpVal* uv, bool dead) void luaF_freeproto(lua_State* L, Proto* f, lua_Page* page) { - luaM_freearray(L, f->code, f->sizecode, Instruction, f->memcat); + // a lazy-load stub's code is a static instruction + if (f->lazychunk) + luaV_releaselazychunk(L, f->lazychunk); + else + luaM_freearray(L, f->code, f->sizecode, Instruction, f->memcat); luaM_freearray(L, f->p, f->sizep, Proto*, f->memcat); luaM_freearray(L, f->k, f->sizek, TValue, f->memcat); if (f->lineinfo) diff --git a/VM/src/lgc.cpp b/VM/src/lgc.cpp index d480625d6..50c95a94e 100644 --- a/VM/src/lgc.cpp +++ b/VM/src/lgc.cpp @@ -20,10 +20,10 @@ LUAU_FASTFLAGVARIABLE(LuauGcTraceUdata) LUAU_FLAGVERSION(LuauGcTraceUdata, 5) -LUAU_FASTFLAG(LuauFastpcall) LUAU_FASTFLAG(LuauCoroutineFinally) LUAU_DYNAMIC_FASTFLAGVARIABLE(LuauGcHeapShrinkFix, false) LUAU_FASTFLAGVARIABLE(LuauRuntimeFeedback) +LUAU_FLAGVERSION(LuauRuntimeFeedback, 2) LUAU_FASTFLAG(LuauBufferSweep) LUAU_FASTFLAG(LuauLoadExplicitGcDisable) @@ -423,7 +423,14 @@ static void traverseproto(global_State* g, Proto* f) if (f->deoptimized) markobject(g, f->deoptimized); - if (FFlag::LuauRuntimeFeedback && g->ecb.examinefunction) + if (f->lazychunk) + { + markobject(g, f->lazychunk->envt); + markobject(g, f->lazychunk->importenv); + } + + // a lazy-load stub has no code to compile yet; it is examined once built + if (FFlag::LuauRuntimeFeedback && g->ecb.examinefunction && !f->lazychunk) { if ((f->execflags & PEF_EXECLOCKED) == 0) g->ecb.examinefunction(g->mainthread, f); @@ -962,8 +969,7 @@ static void markroot(lua_State* L) markudatadirectfields(g); - if (FFlag::LuauFastpcall) - markfastpcalls(g); + markfastpcalls(g); markmt(g); @@ -1059,8 +1065,7 @@ static size_t atomic(lua_State* L) markudatadirectfields(g); // mark direct field dispatch tables (again) - if (FFlag::LuauFastpcall) - markfastpcalls(g); + markfastpcalls(g); work += propagateall(g); diff --git a/VM/src/lgcdebug.cpp b/VM/src/lgcdebug.cpp index da235123a..92cf400e5 100644 --- a/VM/src/lgcdebug.cpp +++ b/VM/src/lgcdebug.cpp @@ -138,6 +138,12 @@ static void validateproto(global_State* g, Proto* f) for (int i = 0; i < f->sizelocvars; i++) if (f->locvars[i].varname) validateobjref(g, obj2gco(f), obj2gco(f->locvars[i].varname)); + + if (f->lazychunk) + { + validateobjref(g, obj2gco(f), obj2gco(f->lazychunk->envt)); + validateobjref(g, obj2gco(f), obj2gco(f->lazychunk->importenv)); + } } static void validateclass(global_State* g, LuauClass* lco) diff --git a/VM/src/linit.cpp b/VM/src/linit.cpp index 049cc2231..9d84842af 100644 --- a/VM/src/linit.cpp +++ b/VM/src/linit.cpp @@ -5,27 +5,10 @@ #include -LUAU_FASTFLAG(LuauIntegerLibrary) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) LUAU_FASTFLAGVARIABLE(LuauSandboxFreezesVectorMetatable) static const luaL_Reg lualibs[] = { - {"", luaopen_base}, - {LUA_COLIBNAME, luaopen_coroutine}, - {LUA_TABLIBNAME, luaopen_table}, - {LUA_OSLIBNAME, luaopen_os}, - {LUA_STRLIBNAME, luaopen_string}, - {LUA_MATHLIBNAME, luaopen_math}, - {LUA_DBLIBNAME, luaopen_debug}, - {LUA_UTF8LIBNAME, luaopen_utf8}, - {LUA_BITLIBNAME, luaopen_bit32}, - {LUA_BUFFERLIBNAME, luaopen_buffer}, - {LUA_VECLIBNAME, luaopen_vector}, - {LUA_INTLIBNAME, luaopen_integer}, - {NULL, NULL}, -}; - -static const luaL_Reg lualibs_NOINTEGER[] = { {"", luaopen_base}, {LUA_COLIBNAME, luaopen_coroutine}, {LUA_TABLIBNAME, luaopen_table}, @@ -42,13 +25,7 @@ static const luaL_Reg lualibs_NOINTEGER[] = { void luaL_openlibs(lua_State* L) { - const luaL_Reg* lib; - if (FFlag::LuauIntegerLibrary) - lib = lualibs; - else - lib = lualibs_NOINTEGER; - - for (; lib->func; lib++) + for (const luaL_Reg* lib = lualibs; lib->func; lib++) { lua_pushcfunction(L, lib->func, NULL); lua_pushstring(L, lib->name); diff --git a/VM/src/lintlib.cpp b/VM/src/lintlib.cpp deleted file mode 100644 index 90039a237..000000000 --- a/VM/src/lintlib.cpp +++ /dev/null @@ -1,614 +0,0 @@ -// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details -#include "lualib.h" - -#include "lcommon.h" -#include "lnumutils.h" -#include "lobject.h" - -#include -#include - -#ifdef _MSC_VER -#include -#endif - -LUAU_FASTFLAGVARIABLE(LuauIntegerLibrary) - -#define mask64(w) (0xFFFFFFFFFFFFFFFFULL >> (64 - (w))) - -static int int64_create(lua_State* L) -{ - double x = luaL_checknumber(L, 1); - if (x >= -9223372036854775808.0 && x < 9223372036854775808.0) - { - int64_t l = (int64_t)x; - if (((double)l) == x) - { - lua_pushinteger64(L, l); - return 1; - } - } - - lua_pushnil(L); - - return 1; -} - -static int int64_fromstring(lua_State* L) -{ - const char* s = luaL_checkstring(L, 1); - int base = luaL_optinteger(L, 2, 10); - luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); - - int64_t result; - if (luaO_str2l(s, &result, base)) - lua_pushinteger64(L, result); - else - lua_pushnil(L); - - return 1; -} - -static int int64_tonumber(lua_State* L) -{ - int64_t x = luaL_checkinteger64(L, 1); - - lua_pushnumber(L, (double)x); - - return 1; -} - -static int int64_neg(lua_State* L) -{ - int64_t x = luaL_checkinteger64(L, 1); - - lua_pushinteger64(L, (int64_t)(~(uint64_t)x + 1)); - - return 1; -} - -static int int64_add(lua_State* L) -{ - int64_t x = luaL_checkinteger64(L, 1); - int64_t y = luaL_checkinteger64(L, 2); - - lua_pushinteger64(L, (int64_t)((uint64_t)x + (uint64_t)y)); - - return 1; -} - -static int int64_sub(lua_State* L) -{ - int64_t x = luaL_checkinteger64(L, 1); - int64_t y = luaL_checkinteger64(L, 2); - - lua_pushinteger64(L, (int64_t)((uint64_t)x - (uint64_t)y)); - - return 1; -} - -static int int64_mul(lua_State* L) -{ - int64_t x = luaL_checkinteger64(L, 1); - int64_t y = luaL_checkinteger64(L, 2); - - lua_pushinteger64(L, (int64_t)((uint64_t)x * (uint64_t)y)); - - return 1; -} - -static int int64_div(lua_State* L) -{ - int64_t a = luaL_checkinteger64(L, 1); - int64_t b = luaL_checkinteger64(L, 2); - - if (b == 0) - luaL_error(L, "division by zero"); - if ((a == LLONG_MIN) && (b == -1)) - luaL_error(L, "integer overflow"); - - lua_pushinteger64(L, a / b); - - return 1; -} - -static int int64_idiv(lua_State* L) -{ - int64_t a = luaL_checkinteger64(L, 1); - int64_t b = luaL_checkinteger64(L, 2); - - if (b == 0) - luaL_error(L, "division by zero"); - if ((a == LLONG_MIN) && (b == -1)) - luaL_error(L, "integer overflow"); - - int64_t result = a / b; - // Floored division rounds toward -inf: adjust the truncated quotient down by 1 - // when the operands have opposite signs and the division is inexact. - if (((a ^ b) < 0) && (a % b)) - result -= 1; - lua_pushinteger64(L, result); - - return 1; -} - -static int int64_rem(lua_State* L) -{ - int64_t a = luaL_checkinteger64(L, 1); - int64_t b = luaL_checkinteger64(L, 2); - - if (b == 0) - luaL_error(L, "division by zero"); - - if ((a == LLONG_MIN) && (b == -1)) - { - lua_pushinteger64(L, 0); - return 1; - } - - lua_pushinteger64(L, a % b); - - return 1; -} - -static int int64_mod(lua_State* L) -{ - int64_t a = luaL_checkinteger64(L, 1); - int64_t b = luaL_checkinteger64(L, 2); - - if (b == 0) - luaL_error(L, "division by zero"); - - int64_t remainder = 0; - if ((a != LLONG_MIN) || (b != -1)) - { - remainder = a % b; - if (remainder && ((a < 0) != (b < 0))) - remainder += b; - } - - lua_pushinteger64(L, remainder); - - return 1; -} - -static int int64_udiv(lua_State* L) -{ - uint64_t a = luaL_checkinteger64(L, 1); - uint64_t b = luaL_checkinteger64(L, 2); - - if (b == 0) - luaL_error(L, "division by zero"); - - lua_pushinteger64(L, a / b); - - return 1; -} - -static int int64_urem(lua_State* L) -{ - uint64_t a = luaL_checkinteger64(L, 1); - uint64_t b = luaL_checkinteger64(L, 2); - - if (b == 0) - luaL_error(L, "division by zero"); - - lua_pushinteger64(L, a % b); - - return 1; -} - -static int int64_min(lua_State* L) -{ - int64_t tmin = luaL_checkinteger64(L, 1); - int n = lua_gettop(L); - for (int i = 2; i <= n; i++) - { - int64_t x = luaL_checkinteger64(L, i); - if (x < tmin) - tmin = x; - } - - lua_pushinteger64(L, tmin); - - return 1; -} - -static int int64_max(lua_State* L) -{ - int64_t tmax = luaL_checkinteger64(L, 1); - int n = lua_gettop(L); - for (int i = 2; i <= n; i++) - { - int64_t x = luaL_checkinteger64(L, i); - if (x > tmax) - tmax = x; - } - - lua_pushinteger64(L, tmax); - - return 1; -} - -static int int64_band(lua_State* L) -{ - uint64_t tres = ULLONG_MAX; - int n = lua_gettop(L); - - for (int i = 1; i <= n; i++) - { - uint64_t x = (uint64_t)luaL_checkinteger64(L, i); - tres &= x; - } - - lua_pushinteger64(L, tres); - - return 1; -} - -static int int64_bor(lua_State* L) -{ - uint64_t tres = 0; - int n = lua_gettop(L); - - for (int i = 1; i <= n; i++) - { - uint64_t x = (uint64_t)luaL_checkinteger64(L, i); - tres |= x; - } - - lua_pushinteger64(L, tres); - - return 1; -} - -static int int64_bnot(lua_State* L) -{ - uint64_t a = luaL_checkinteger64(L, 1); - - lua_pushinteger64(L, ~a); - - return 1; -} - -static int int64_bxor(lua_State* L) -{ - uint64_t tres = 0; - int n = lua_gettop(L); - - for (int i = 1; i <= n; i++) - { - uint64_t x = (uint64_t)luaL_checkinteger64(L, i); - tres ^= x; - } - - lua_pushinteger64(L, tres); - - return 1; -} - -static int int64_lt(lua_State* L) -{ - int64_t a = luaL_checkinteger64(L, 1); - int64_t b = luaL_checkinteger64(L, 2); - - lua_pushboolean(L, a < b); - - return 1; -} - -static int int64_le(lua_State* L) -{ - int64_t a = luaL_checkinteger64(L, 1); - int64_t b = luaL_checkinteger64(L, 2); - - lua_pushboolean(L, a <= b); - - return 1; -} - -static int int64_ult(lua_State* L) -{ - uint64_t a = luaL_checkinteger64(L, 1); - uint64_t b = luaL_checkinteger64(L, 2); - - lua_pushboolean(L, a < b); - - return 1; -} - -static int int64_ule(lua_State* L) -{ - uint64_t a = luaL_checkinteger64(L, 1); - uint64_t b = luaL_checkinteger64(L, 2); - - lua_pushboolean(L, a <= b); - - return 1; -} - -static int int64_gt(lua_State* L) -{ - int64_t a = luaL_checkinteger64(L, 1); - int64_t b = luaL_checkinteger64(L, 2); - - lua_pushboolean(L, a > b); - - return 1; -} - -static int int64_ge(lua_State* L) -{ - int64_t a = luaL_checkinteger64(L, 1); - int64_t b = luaL_checkinteger64(L, 2); - - lua_pushboolean(L, a >= b); - - return 1; -} - -static int int64_ugt(lua_State* L) -{ - uint64_t a = luaL_checkinteger64(L, 1); - uint64_t b = luaL_checkinteger64(L, 2); - - lua_pushboolean(L, a > b); - - return 1; -} - -static int int64_uge(lua_State* L) -{ - uint64_t a = luaL_checkinteger64(L, 1); - uint64_t b = luaL_checkinteger64(L, 2); - - lua_pushboolean(L, a >= b); - - return 1; -} - -static int int64_lshift(lua_State* L) -{ - uint64_t n = luaL_checkinteger64(L, 1); - int64_t i = luaL_checkinteger64(L, 2); - - if ((i >= -63) && (i <= 63)) - lua_pushinteger64(L, (i < 0) ? (n >> (-i)) : (n << i)); - else - lua_pushinteger64(L, 0); - - return 1; -} - -static int int64_rshift(lua_State* L) -{ - uint64_t n = luaL_checkinteger64(L, 1); - int64_t i = luaL_checkinteger64(L, 2); - - if ((i >= -63) && (i <= 63)) - lua_pushinteger64(L, (i < 0) ? (n << (-i)) : (n >> i)); - else - lua_pushinteger64(L, 0); - - return 1; -} - -static int int64_arshift(lua_State* L) -{ - int64_t n = luaL_checkinteger64(L, 1); - int64_t i = luaL_checkinteger64(L, 2); - - if ((i >= -63) && (i <= 63)) - lua_pushinteger64(L, (i < 0) ? (int64_t)((uint64_t)n << (-i)) : (n >> i)); - else if (i < -63) - lua_pushinteger64(L, 0); - else - lua_pushinteger64(L, (n < 0) ? -1 : 0); - - return 1; -} - -static int int64_lrotate(lua_State* L) -{ - uint64_t n = (uint64_t)luaL_checkinteger64(L, 1); - unsigned s = (unsigned)((uint64_t)luaL_checkinteger64(L, 2) % 64); - - lua_pushinteger64(L, (int64_t)(s != 0 ? (n << s) | (n >> (64 - s)) : n)); - - return 1; -} - -static int int64_rrotate(lua_State* L) -{ - uint64_t n = (uint64_t)luaL_checkinteger64(L, 1); - unsigned s = (unsigned)((uint64_t)luaL_checkinteger64(L, 2) % 64); - - lua_pushinteger64(L, (int64_t)(s != 0 ? (n >> s) | (n << (64 - s)) : n)); - - return 1; -} - -static int int64_extract(lua_State* L) -{ - int64_t n = luaL_checkinteger64(L, 1); - int64_t f = luaL_checkinteger64(L, 2); - int64_t w = luaL_optinteger64(L, 3, 1); - - luaL_argcheck(L, 0 <= f, 2, "field cannot be negative"); - luaL_argcheck(L, 0 < w, 3, "width must be positive"); - if (w > 64 - f) - luaL_error(L, "trying to access non-existent bits"); - - lua_pushinteger64(L, ((uint64_t)n >> f) & mask64(w)); - - return 1; -} - -static int int64_replace(lua_State* L) -{ - int64_t n = luaL_checkinteger64(L, 1); - int64_t r = luaL_checkinteger64(L, 2); - int64_t f = luaL_checkinteger64(L, 3); - int64_t w = luaL_optinteger64(L, 4, 1); - - luaL_argcheck(L, 0 <= f, 3, "field cannot be negative"); - luaL_argcheck(L, 0 < w, 4, "width must be positive"); - if (w > 64 - f) - luaL_error(L, "trying to access non-existent bits"); - - uint64_t baseMask = ((0xFFFFFFFFFFFFFFFFULL) >> (64 - w)); - uint64_t replacement = (((uint64_t)r) & baseMask) << f; - uint64_t mask = 0xFFFFFFFFFFFFFFFFULL ^ (baseMask << f); - lua_pushinteger64(L, (((uint64_t)n) & mask) | replacement); - - return 1; -} - -static int int64_clamp(lua_State* L) -{ - int64_t a = luaL_checkinteger64(L, 1); - int64_t mi = luaL_checkinteger64(L, 2); - int64_t mx = luaL_checkinteger64(L, 3); - - luaL_argcheck(L, mi <= mx, 3, "max must be greater than or equal to min"); - - if (a < mi) - lua_pushinteger64(L, mi); - else if (a > mx) - lua_pushinteger64(L, mx); - else - lua_pushinteger64(L, a); - - return 1; -} - -static int int64_btest(lua_State* L) -{ - uint64_t tres = ULLONG_MAX; - int n = lua_gettop(L); - - for (int i = 1; i <= n; i++) - { - uint64_t x = (uint64_t)luaL_checkinteger64(L, i); - tres &= x; - } - - lua_pushboolean(L, (tres != 0)); - - return 1; -} - -static int int64_countrz(lua_State* L) -{ - uint64_t n = luaL_checkinteger64(L, 1); - int result; -#ifdef _MSC_VER -#ifdef _WIN64 - unsigned long rl; - result = _BitScanForward64(&rl, n) ? int(rl) : 64; -#else - unsigned long rl; - if (_BitScanForward(&rl, uint32_t(n))) - result = int(rl); - else - result = _BitScanForward(&rl, uint32_t(n >> 32)) ? int(rl) + 32 : 64; -#endif -#else - result = (n == 0) ? 64 : __builtin_ctzll(n); -#endif - - lua_pushinteger64(L, result); - - return 1; -} - -static int int64_countlz(lua_State* L) -{ - uint64_t n = luaL_checkinteger64(L, 1); - int result; -#ifdef _MSC_VER -#ifdef _WIN64 - unsigned long rl; - result = _BitScanReverse64(&rl, n) ? 63 - int(rl) : 64; -#else - unsigned long rl; - if (_BitScanReverse(&rl, uint32_t(n >> 32))) - result = 31 - int(rl); - else - result = _BitScanReverse(&rl, uint32_t(n)) ? 63 - int(rl) : 64; -#endif -#else - result = (n == 0) ? 64 : __builtin_clzll(n); -#endif - lua_pushinteger64(L, result); - - return 1; -} - -static int int64_bswap(lua_State* L) -{ - uint64_t a = luaL_checkinteger64(L, 1); - - lua_pushinteger64( - L, - (a >> 56) | ((a & 0xFF000000000000) >> 40) | ((a & 0xFF0000000000) >> 24) | ((a & 0xFF00000000) >> 8) | ((a & 0xFF000000) << 8) | - ((a & 0xFF0000) << 24) | ((a & 0xFF00) << 40) | ((a & 0xFF) << 56) - ); - - return 1; -} - -static const luaL_Reg int64lib[] = { - {"create", int64_create}, - {"tonumber", int64_tonumber}, - {"neg", int64_neg}, - {"add", int64_add}, - {"sub", int64_sub}, - {"mul", int64_mul}, - {"div", int64_div}, - {"min", int64_min}, - {"max", int64_max}, - {"rem", int64_rem}, - {"idiv", int64_idiv}, - {"udiv", int64_udiv}, - {"urem", int64_urem}, - {"mod", int64_mod}, - {"clamp", int64_clamp}, - {"band", int64_band}, - {"bor", int64_bor}, - {"bnot", int64_bnot}, - {"bxor", int64_bxor}, - {"lt", int64_lt}, - {"le", int64_le}, - {"ult", int64_ult}, - {"ule", int64_ule}, - {"gt", int64_gt}, - {"ge", int64_ge}, - {"ugt", int64_ugt}, - {"uge", int64_uge}, - {"lshift", int64_lshift}, - {"rshift", int64_rshift}, - {"arshift", int64_arshift}, - {"lrotate", int64_lrotate}, - {"rrotate", int64_rrotate}, - {"extract", int64_extract}, - {"replace", int64_replace}, - {"btest", int64_btest}, - {"countrz", int64_countrz}, - {"countlz", int64_countlz}, - {"bswap", int64_bswap}, - {"fromstring", int64_fromstring}, - {NULL, NULL}, -}; - -int luaopen_integer(lua_State* L) -{ - luaL_register(L, LUA_INTLIBNAME, int64lib); - - lua_pushinteger64(L, LLONG_MAX); - lua_setfield(L, -2, "maxsigned"); - lua_pushinteger64(L, LLONG_MIN); - lua_setfield(L, -2, "minsigned"); - - return 1; -} diff --git a/VM/src/lnumprint.cpp b/VM/src/lnumprint.cpp index a8a7efd62..763675e00 100644 --- a/VM/src/lnumprint.cpp +++ b/VM/src/lnumprint.cpp @@ -367,27 +367,3 @@ char* luai_num2str(char* buf, double n) return printexp(exp, dot - 1); } } - -char* luai_int2str(char* buf, int64_t l) -{ - uint64_t val = (l < 0) ? ~(uint64_t)l + 1 : (uint64_t)l; - - int numDigits = 1; - for (uint64_t cap = 10; (numDigits < 19) && (cap <= val); cap *= 10) - numDigits++; - - int pos = (l < 0) ? numDigits : (numDigits - 1); - buf[pos + 1] = 0; - do - { - buf[pos--] = '0' + (val % 10); - val /= 10; - } while (val != 0); - - if (l < 0) - buf[pos--] = '-'; - - LUAU_ASSERT(pos == -1); - - return &buf[(l < 0) ? (numDigits + 1) : numDigits]; -} diff --git a/VM/src/lnumutils.h b/VM/src/lnumutils.h index ef021161b..923ead955 100644 --- a/VM/src/lnumutils.h +++ b/VM/src/lnumutils.h @@ -15,7 +15,6 @@ #define luai_numeq(a, b) ((a) == (b)) #define luai_numlt(a, b) ((a) < (b)) #define luai_numle(a, b) ((a) <= (b)) -#define luai_inteq(a, b) ((a) == (b)) inline bool luai_veceq(const float* a, const float* b) { @@ -101,8 +100,6 @@ inline double luai_lerpd(double a, double b, double t) #define luai_num2int(i, d) ((i) = (int)(d)) -#define luai_num2long(i, d) ((i) = (int64_t)(d)) - #define luai_fabs condvectordouble(fabs, fabsf) #define luai_sqrt condvectordouble(sqrt, sqrtf) #define luai_floor condvectordouble(floor, floorf) @@ -125,10 +122,7 @@ inline double luai_lerpd(double a, double b, double t) #endif #define LUAI_MAXNUM2STR 48 -#define LUAI_MAXINT2STR 30 LUAI_FUNC char* luai_num2str(char* buf, double n); -LUAI_FUNC char* luai_int2str(char* buf, int64_t n); #define luai_str2num(s, p) strtod((s), (p)) -#define luai_str2long(s, p, base) strtoll((s), (p), base) diff --git a/VM/src/lobject.cpp b/VM/src/lobject.cpp index ec10a72f2..e4202d700 100644 --- a/VM/src/lobject.cpp +++ b/VM/src/lobject.cpp @@ -44,8 +44,6 @@ int luaO_rawequalObj(const TValue* t1, const TValue* t2) return 1; case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); - case LUA_TINTEGER: - return luai_inteq(lvalue(t1), lvalue(t2)); case LUA_TVECTOR: return luai_veceq(vvalue(t1), vvalue(t2)); case LUA_TBOOLEAN: @@ -69,8 +67,6 @@ int luaO_rawequalKey(const TKey* t1, const TValue* t2) return 1; case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); - case LUA_TINTEGER: - return luai_inteq(lvalue(t1), lvalue(t2)); case LUA_TVECTOR: return luai_veceq(vvalue(t1), vvalue(t2)); case LUA_TBOOLEAN: @@ -100,33 +96,6 @@ int luaO_str2d(const char* s, double* result) return 1; } -int luaO_str2l(const char* s, int64_t* result, int base) -{ - char* endptr = nullptr; - if (base == 10) - { - *result = luai_str2long(s, &endptr, base); - if (endptr == s) - return 0; // conversion failed - if (*endptr == 'x' || *endptr == 'X') // maybe an hexadecimal constant? - *result = (int64_t)strtoull(s, &endptr, 16); - } - else - { - // unsigned parse in other bases - *result = (int64_t)strtoull(s, &endptr, base); - if (endptr == s) - return 0; - } - if (*endptr == '\0') - return 1; // most common case - while (isspace(cast_to(unsigned char, *endptr))) - endptr++; - if (*endptr != '\0') - return 0; // invalid trailing characters? - return 1; -} - const char* luaO_pushvfstring(lua_State* L, const char* fmt, va_list argp) { char result[LUA_BUFFERSIZE]; diff --git a/VM/src/lobject.h b/VM/src/lobject.h index 4039867e5..f774937f3 100644 --- a/VM/src/lobject.h +++ b/VM/src/lobject.h @@ -4,6 +4,7 @@ #include "lua.h" #include "lcommon.h" +#include "lbytecode.h" /* ** Union of all collectible objects @@ -35,7 +36,6 @@ typedef union void* p; double n; int b; - int64_t l; float v[2]; // v[0], v[1] live here; v[2] lives in TValue::extra } Value; @@ -65,7 +65,6 @@ typedef struct lua_TValue // Macros to test type #define ttisnil(o) (ttype(o) == LUA_TNIL) #define ttisnumber(o) (ttype(o) == LUA_TNUMBER) -#define ttisinteger(o) (ttype(o) == LUA_TINTEGER) #define ttisstring(o) (ttype(o) == LUA_TSTRING) #define ttistable(o) (ttype(o) == LUA_TTABLE) #define ttisfunction(o) (ttype(o) == LUA_TFUNCTION) @@ -84,7 +83,6 @@ typedef struct lua_TValue #define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc) #define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p) #define nvalue(o) check_exp(ttisnumber(o), (o)->value.n) -#define lvalue(o) check_exp(ttisinteger(o), (o)->value.l) #define vvalue(o) check_exp(ttisvector(o), condvectordouble((o)->value.gc->vec.v, (o)->value.v)) #define tsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts) #define uvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u) @@ -121,13 +119,6 @@ typedef struct lua_TValue i_o->tt = LUA_TNUMBER; \ } -#define setlvalue(obj, x) \ - { \ - TValue* i_o = (obj); \ - i_o->value.l = (x); \ - i_o->tt = LUA_TINTEGER; \ - } - #if LUA_VECTOR_DOUBLE == 1 #define setvvalue(L, obj, x, y, z, w) \ { \ @@ -302,7 +293,6 @@ typedef struct TString char data[1]; // string data is allocated right after the header } TString; - #define getstr(ts) (ts)->data #define svalue(o) getstr(tsvalue(o)) @@ -436,9 +426,38 @@ typedef struct Proto Proto* optimized; Proto* deoptimized; uint64_t cost; + + // Set while the proto is a lazy-load stub (luau_loadlazy) + struct LuauLazyChunk* lazychunk; } Proto; // clang-format on +static const uint32_t userdataTypeLimit = LBC_TYPE_TAGGED_USERDATA_END - LBC_TYPE_TAGGED_USERDATA_BASE; + +// The bytecode of a luau_loadlazy chunk, shared by all of its stubs +typedef struct LuauLazyChunk +{ + const char* data; + size_t size; + void* owner; + void (*release)(void* owner); + + uint32_t refs; // the load, every stub and every build in progress + + struct LuaTable* envt; + struct LuaTable* importenv; + + uint8_t memcat; + uint8_t version; + uint8_t typesversion; + uint8_t userdataRemapping[userdataTypeLimit]; + + uint32_t* stringOffsets; // offset of each string's length + uint32_t stringCount; + uint32_t* protoOffsets; // offset of each function's maxstacksize byte + uint32_t protoCount; +} LuauLazyChunk; + typedef struct LocVar { TString* varname; @@ -678,7 +697,6 @@ LUAI_FUNC int luaO_log2(unsigned int x); LUAI_FUNC int luaO_rawequalObj(const TValue* t1, const TValue* t2); LUAI_FUNC int luaO_rawequalKey(const TKey* t1, const TValue* t2); LUAI_FUNC int luaO_str2d(const char* s, double* result); -LUAI_FUNC int luaO_str2l(const char* s, int64_t* result, int base = 10); LUAI_FUNC const char* luaO_pushvfstring(lua_State* L, const char* fmt, va_list argp); LUAI_FUNC const char* luaO_pushfstring(lua_State* L, const char* fmt, ...); LUAI_FUNC const char* luaO_chunkid(char* buf, size_t buflen, const char* source, size_t srclen); diff --git a/VM/src/lperf.cpp b/VM/src/lperf.cpp index 0518aabb1..f9585fb53 100644 --- a/VM/src/lperf.cpp +++ b/VM/src/lperf.cpp @@ -17,7 +17,6 @@ #include #endif - #ifdef __EMSCRIPTEN__ #include #endif diff --git a/VM/src/lstate.cpp b/VM/src/lstate.cpp index 6473d4176..03558f4f6 100644 --- a/VM/src/lstate.cpp +++ b/VM/src/lstate.cpp @@ -211,7 +211,6 @@ lua_State* lua_newstate(lua_Alloc allocator, void* ud) g->uvhead.u.open.prev = &g->uvhead; g->uvhead.u.open.next = &g->uvhead; - g->ptrenckey[0] = 1; g->strt.saltmult = 0x9e3779b9u; // default string table salt provides additional Fibonacci hash mixing diff --git a/VM/src/lstrlib.cpp b/VM/src/lstrlib.cpp index d1b8fb407..0fe969592 100644 --- a/VM/src/lstrlib.cpp +++ b/VM/src/lstrlib.cpp @@ -1107,9 +1107,8 @@ static int str_format(lua_State* L) case 'd': case 'i': { - long long value = lua_isinteger64(L, arg) ? luaL_checkinteger64(L, arg) : (int64_t)luaL_checknumber(L, arg); addInt64Format(form, formatIndicator, formatItemSize); - snprintf(buff, sizeof(buff), form, value); + snprintf(buff, sizeof(buff), form, static_cast(luaL_checknumber(L, arg))); break; } case 'o': @@ -1117,17 +1116,9 @@ static int str_format(lua_State* L) case 'x': case 'X': { - uint64_t v; - if (lua_isinteger64(L, arg)) - { - v = luaL_checkinteger64(L, arg); - } - else - { - double argValue = luaL_checknumber(L, arg); - v = (argValue < 0) ? (unsigned long long)(long long)argValue : (unsigned long long)argValue; - } + double argValue = luaL_checknumber(L, arg); addInt64Format(form, formatIndicator, formatItemSize); + unsigned long long v = (argValue < 0) ? (unsigned long long)(long long)argValue : (unsigned long long)argValue; snprintf(buff, sizeof(buff), form, v); break; } diff --git a/VM/src/ltable.cpp b/VM/src/ltable.cpp index 01d058d13..202ee437b 100644 --- a/VM/src/ltable.cpp +++ b/VM/src/ltable.cpp @@ -35,7 +35,6 @@ #include LUAU_DYNAMIC_FASTFLAG(LuauTableFindImprovement) -LUAU_DYNAMIC_FASTFLAGVARIABLE(LuauTableRobustOom, false) // Set this to 1 to change the hash function to something different (and possibly trivial). Useful // for checking if a Lua program's behavior depends on the hash function. @@ -113,34 +112,6 @@ static LuaNode* hashnum(const LuaTable* t, double n) return hashpow2(t, h2); } -static LuaNode* hashint(const LuaTable* t, int64_t n) -{ - static_assert(sizeof(n) == sizeof(unsigned int) * 2, "expected a 8-byte integer"); - unsigned int i[2]; - memcpy(i, &n, sizeof(i)); - - uint32_t h1 = i[0]; - uint32_t h2 = i[1]; - - // finalizer from MurmurHash64B - const uint32_t m = 0x5bd1e995; - - if (!ALT_HASH_FUNCTION) - { - h1 ^= h2 >> 18; - h1 *= m; - h2 ^= h1 >> 22; - h2 *= m; - h1 ^= h2 >> 17; - h1 *= m; - h2 ^= h1 >> 19; - h2 *= m; - } - - // ... truncated to 32-bit output (normally hash is equal to (uint64_t(h1) << 32) | h2, but we only really need the lower 32-bit half) - return hashpow2(t, h2); -} - LUAU_MAYBE_UNUSED static LuaNode* hashvec(const LuaTable* t, const float* v) { unsigned int i[LUA_VECTOR_SIZE]; @@ -211,8 +182,6 @@ static LuaNode* mainposition(const LuaTable* t, const TValue* key) { case LUA_TNUMBER: return hashnum(t, nvalue(key)); - case LUA_TINTEGER: - return hashint(t, lvalue(key)); case LUA_TVECTOR: return hashvec(t, vvalue(key)); case LUA_TSTRING: @@ -250,12 +219,6 @@ LUAU_FORCEINLINE LuaNode* mainpositiontagged(const LuaTable* t, dou return hashnum(t, key); } -template<> -LUAU_FORCEINLINE LuaNode* mainpositiontagged(const LuaTable* t, int64_t key) -{ - return hashint(t, key); -} - template<> LUAU_FORCEINLINE LuaNode* mainpositiontagged(const LuaTable* t, const LUA_VECTOR_TYPE* key) { @@ -291,12 +254,6 @@ LUAU_FORCEINLINE int rawequalkeyvalue(const TKey* t1, double key) return luai_numeq(nvalue(t1), key); } -template<> -LUAU_FORCEINLINE int rawequalkeyvalue(const TKey* t1, int64_t key) -{ - return luai_inteq(lvalue(t1), key); -} - template<> LUAU_FORCEINLINE int rawequalkeyvalue(const TKey* t1, const LUA_VECTOR_TYPE* key) { @@ -345,12 +302,6 @@ LUAU_FORCEINLINE int rawequalvalue(const Obj* lhs, double rhs) return luai_numeq(nvalue(lhs), rhs); } -template -LUAU_FORCEINLINE int rawequalvalue(const Obj* lhs, int64_t rhs) -{ - return luai_inteq(lvalue(lhs), rhs); -} - struct LightUserdataVal { void* p; @@ -525,9 +476,6 @@ int luaH_rawfind(LuaTable* t, int startpos, StkId value) case LUA_TNUMBER: index = rawfindarray(t, startpos, nvalue(value), LUA_TNUMBER); break; - case LUA_TINTEGER: - index = rawfindarray(t, startpos, lvalue(value), LUA_TINTEGER); - break; case LUA_TVECTOR: index = rawfindarray(t, startpos, (const LUA_VECTOR_TYPE*)vvalue(value), LUA_TVECTOR); break; @@ -699,168 +647,102 @@ static void resize(lua_State* L, LuaTable* t, int nasize, int nhsize) if (nasize > MAXSIZE || nhsize > MAXSIZE) luaG_runerror(L, "table overflow"); - if (DFFlag::LuauTableRobustOom) + // check for node size bit mask overflow and round up requested hash size + int lsizenode = 0; + + LUAU_ASSERT(nhsize >= 0); + if (nhsize != 0) { - // check for node size bit mask overflow and round up requested hash size - int lsizenode = 0; + lsizenode = ceillog2(nhsize); + if (lsizenode > MAXBITS) + luaG_runerror(L, "table overflow"); - LUAU_ASSERT(nhsize >= 0); - if (nhsize != 0) - { - lsizenode = ceillog2(nhsize); - if (lsizenode > MAXBITS) - luaG_runerror(L, "table overflow"); + nhsize = twoto(lsizenode); + } - nhsize = twoto(lsizenode); - } + int oldsizearray = t->sizearray; + int oldsizenode = twoto(t->lsizenode); + TValue* oldarray = t->array; + LuaNode* oldnode = t->node; - int oldsizearray = t->sizearray; - int oldsizenode = twoto(t->lsizenode); - TValue* oldarray = t->array; - LuaNode* oldnode = t->node; + TValue* newarray = t->array; - TValue* newarray = t->array; + if (nasize != oldsizearray) + { + newarray = luaM_newarray(L, nasize, TValue, t->memcat); - if (nasize != oldsizearray) + if (nasize < oldsizearray) { - newarray = luaM_newarray(L, nasize, TValue, t->memcat); - - if (nasize < oldsizearray) - { - // copy elements from remaining slice - if (nasize != 0) - memcpy(newarray, oldarray, nasize * sizeof(TValue)); - } - else - { - // copy old elements - if (oldsizearray != 0) - memcpy(newarray, oldarray, oldsizearray * sizeof(TValue)); + // copy elements from remaining slice + if (nasize != 0) + memcpy(newarray, oldarray, nasize * sizeof(TValue)); + } + else + { + // copy old elements + if (oldsizearray != 0) + memcpy(newarray, oldarray, oldsizearray * sizeof(TValue)); - // clear new elements - for (int i = oldsizearray; i < nasize; i++) - setnilvalue(&newarray[i]); - } + // clear new elements + for (int i = oldsizearray; i < nasize; i++) + setnilvalue(&newarray[i]); } + } - LuaNode* newnode = cast_to(LuaNode*, dummynode); + LuaNode* newnode = cast_to(LuaNode*, dummynode); - if (nhsize != 0) + if (nhsize != 0) + { + // if we allocated a new array part, we have to be careful to with hash part allocation failure + if (oldarray != newarray) { - // if we allocated a new array part, we have to be careful to with hash part allocation failure - if (oldarray != newarray) - { - newnode = luaM_trynewarray(L, nhsize, LuaNode, t->memcat); - - if (newnode == nullptr) - { - luaM_freearray(L, newarray, nasize, TValue, t->memcat); - luaD_throw(L, LUA_ERRMEM); - } - } - else - { - newnode = luaM_newarray(L, nhsize, LuaNode, t->memcat); - } + newnode = luaM_trynewarray(L, nhsize, LuaNode, t->memcat); - for (int i = 0; i < nhsize; i++) + if (newnode == nullptr) { - LuaNode* n = &newnode[i]; - gnext(n) = 0; - setnilvalue(gkey(n)); - setnilvalue(gval(n)); + luaM_freearray(L, newarray, nasize, TValue, t->memcat); + luaD_throw(L, LUA_ERRMEM); } } - - // update table structure now that both allocations succeeded - t->array = newarray; - t->sizearray = nasize; - - t->node = newnode; - t->lsizenode = cast_byte(lsizenode); - t->nodemask8 = cast_byte((1 << lsizenode) - 1); - t->lastfree = nhsize; // all positions are free - - // re-insert elements from vanishing array slice - for (int i = nasize; i < oldsizearray; i++) + else { - if (!ttisnil(&oldarray[i])) - { - TValue ok; - setnvalue(&ok, cast_num(i + 1)); - // integer number keys from a shrinking slice cannot get into the new array part - setobjt2t(L, reinsertkey(L, t, &ok, false), &oldarray[i]); - } + newnode = luaM_newarray(L, nhsize, LuaNode, t->memcat); } - // re-insert elements from hash part - for (int i = oldsizenode - 1; i >= 0; i--) + for (int i = 0; i < nhsize; i++) { - LuaNode* old = oldnode + i; - if (!ttisnil(gval(old))) - { - TValue ok; - getnodekey(L, &ok, old); - setobjt2t(L, reinsertkey(L, t, &ok, true), gval(old)); - } + LuaNode* n = &newnode[i]; + gnext(n) = 0; + setnilvalue(gkey(n)); + setnilvalue(gval(n)); } + } - // make sure we haven't recursively rehashed during element migration - LUAU_ASSERT(newnode == t->node); - LUAU_ASSERT(newarray == t->array); - - // free old array - if (nasize != oldsizearray) - luaM_freearray(L, oldarray, oldsizearray, TValue, t->memcat); + // update table structure now that both allocations succeeded + t->array = newarray; + t->sizearray = nasize; - // free old node - if (oldnode != dummynode) - luaM_freearray(L, oldnode, oldsizenode, LuaNode, t->memcat); + t->node = newnode; + t->lsizenode = cast_byte(lsizenode); + t->nodemask8 = cast_byte((1 << lsizenode) - 1); + t->lastfree = nhsize; // all positions are free - return; - } - - int oldasize = t->sizearray; - int oldhsize = t->lsizenode; - LuaNode* nold = t->node; // save old hash ... - if (nasize > oldasize) // array part must grow? - setarrayvector(L, t, nasize); - // create new hash part with appropriate size - setnodevector(L, t, nhsize); - // used for the migration check at the end - LuaNode* nnew = t->node; - if (nasize < oldasize) - { // array part must shrink? - TValue* oldarray = t->array; - - // shrink array - t->array = luaM_newarray(L, nasize, TValue, t->memcat); - t->sizearray = nasize; - - // copy elements from remaining slice - if (nasize != 0) - memcpy(t->array, oldarray, nasize * sizeof(TValue)); - - // re-insert elements from vanishing slice (landing into the hash part) - for (int i = nasize; i < oldasize; i++) + // re-insert elements from vanishing array slice + for (int i = nasize; i < oldsizearray; i++) + { + if (!ttisnil(&oldarray[i])) { - if (!ttisnil(&oldarray[i])) - { - TValue ok; - setnvalue(&ok, cast_num(i + 1)); - // integer number keys from a shrinking slice cannot get into the new array part - setobjt2t(L, reinsertkey(L, t, &ok, false), &oldarray[i]); - } + TValue ok; + setnvalue(&ok, cast_num(i + 1)); + // integer number keys from a shrinking slice cannot get into the new array part + setobjt2t(L, reinsertkey(L, t, &ok, false), &oldarray[i]); } - - luaM_freearray(L, oldarray, oldasize, TValue, t->memcat); } - // used for the migration check at the end - TValue* anew = t->array; + // re-insert elements from hash part - for (int i = twoto(oldhsize) - 1; i >= 0; i--) + for (int i = oldsizenode - 1; i >= 0; i--) { - LuaNode* old = nold + i; + LuaNode* old = oldnode + i; if (!ttisnil(gval(old))) { TValue ok; @@ -870,11 +752,16 @@ static void resize(lua_State* L, LuaTable* t, int nasize, int nhsize) } // make sure we haven't recursively rehashed during element migration - LUAU_ASSERT(nnew == t->node); - LUAU_ASSERT(anew == t->array); + LUAU_ASSERT(newnode == t->node); + LUAU_ASSERT(newarray == t->array); - if (nold != dummynode) - luaM_freearray(L, nold, twoto(oldhsize), LuaNode, t->memcat); // free old array + // free old array + if (nasize != oldsizearray) + luaM_freearray(L, oldarray, oldsizearray, TValue, t->memcat); + + // free old node + if (oldnode != dummynode) + luaM_freearray(L, oldnode, oldsizenode, LuaNode, t->memcat); } // When we already know that new key is an integer number @@ -1222,8 +1109,6 @@ const TValue* luaH_get(LuaTable* t, const TValue* key) return chainsearchtagged(t, nvalue(key), LUA_TNUMBER); } - case LUA_TINTEGER: - return chainsearchtagged(t, lvalue(key), LUA_TINTEGER); case LUA_TVECTOR: return chainsearchtagged(t, (const LUA_VECTOR_TYPE*)vvalue(key), LUA_TVECTOR); case LUA_TSTRING: @@ -1252,8 +1137,6 @@ const TValue* luaH_get(LuaTable* t, const TValue* key) return chainsearchtagged_DEPRECATED(t, nvalue(key), LUA_TNUMBER); } - case LUA_TINTEGER: - return chainsearchtagged_DEPRECATED(t, lvalue(key), LUA_TINTEGER); case LUA_TVECTOR: return chainsearchtagged_DEPRECATED(t, (const LUA_VECTOR_TYPE*)vvalue(key), LUA_TVECTOR); case LUA_TSTRING: @@ -1299,8 +1182,6 @@ TValue* luaH_newkey(lua_State* L, LuaTable* t, const TValue* key) return newkeytagged(L, t, key, n, -1); } - case LUA_TINTEGER: - return newkeytagged(L, t, key, lvalue(key), -1); case LUA_TVECTOR: if (luai_vecisnan(vvalue(key))) luaG_runerror(L, "table index contains NaN"); @@ -1523,31 +1404,19 @@ void luaH_setreadonly(lua_State* L, LuaTable* t, bool readonly) // if there are metamethods, place the metamethod cache before the array elements if (found) { - if (DFFlag::LuauTableRobustOom) + // if allocation fails, the optimization is skipped instead of erroring as an error might be unexpected from a table freeze + if (TValue* newarray = luaM_trynewarray(L, t->sizearray + TM_N, TValue, t->memcat)) { - // if allocation fails, the optimization is skipped instead of erroring as an error might be unexpected from a table freeze - if (TValue* newarray = luaM_trynewarray(L, t->sizearray + TM_N, TValue, t->memcat)) - { - TValue* oldarray = t->array; - - if (t->sizearray != 0) - memcpy(newarray + TM_N, oldarray, t->sizearray * sizeof(TValue)); + TValue* oldarray = t->array; - memcpy(newarray, metamethods, sizeof(metamethods)); - t->array = newarray + TM_N; - t->readonly |= 2; + if (t->sizearray != 0) + memcpy(newarray + TM_N, oldarray, t->sizearray * sizeof(TValue)); - luaM_freearray(L, oldarray, t->sizearray, TValue, t->memcat); - } - } - else - { - TValue* array = t->array; - luaM_reallocarray(L, array, t->sizearray, t->sizearray + TM_N, TValue, t->memcat); - memmove(array + TM_N, array, t->sizearray * sizeof(TValue)); - memcpy(array, metamethods, sizeof(metamethods)); - t->array = array + TM_N; + memcpy(newarray, metamethods, sizeof(metamethods)); + t->array = newarray + TM_N; t->readonly |= 2; + + luaM_freearray(L, oldarray, t->sizearray, TValue, t->memcat); } } } diff --git a/VM/src/ltm.cpp b/VM/src/ltm.cpp index 1d89fa117..b8f3c8838 100644 --- a/VM/src/ltm.cpp +++ b/VM/src/ltm.cpp @@ -21,7 +21,6 @@ const char* const luaT_typenames[] = { "userdata", "number", - "integer", #if LUA_VECTOR_DOUBLE == 0 "vector", diff --git a/VM/src/lvm.h b/VM/src/lvm.h index 44e1057be..c9b59e142 100644 --- a/VM/src/lvm.h +++ b/VM/src/lvm.h @@ -38,3 +38,8 @@ LUAI_FUNC void luau_pushhandlerci(lua_State* L, StkId funcslot, int errfunc, int LUAI_FUNC void luau_poscall(lua_State* L, StkId first); LUAI_FUNC void luau_pospcallsuccess(lua_State* L); LUAI_FUNC void luau_callhook(lua_State* L, lua_Hook hook, void* userdata); +LUAI_FUNC void luau_setupcci(lua_State* L, int nresults, StkId fun); + +// Lazy loading (luau_loadlazy): builds the stub p in place, with the environments of the load +LUAI_FUNC void luaV_buildlazyproto(lua_State* L, Proto* p); +LUAI_FUNC void luaV_releaselazychunk(lua_State* L, struct LuauLazyChunk* chunk); diff --git a/VM/src/lvmexecute.cpp b/VM/src/lvmexecute.cpp index 4abccd2bd..4a9a7b803 100644 --- a/VM/src/lvmexecute.cpp +++ b/VM/src/lvmexecute.cpp @@ -20,7 +20,6 @@ LUAU_FASTFLAGVARIABLE(DebugLuauUserDefinedClassesRuntime) LUAU_FASTFLAGVARIABLE(LuauPromoteProto) -LUAU_FASTFLAG(LuauFastpcall) LUAU_FASTFLAG(LuauRuntimeFeedback) // Disable c99-designator to avoid the warning in computed goto dispatch table @@ -216,7 +215,7 @@ inline bool luau_skipstep(uint8_t op) return op == LOP_PREPVARARGS || op == LOP_BREAK; } -static LUAU_NOINLINE void luau_setupcci(lua_State* L, int nresults, StkId fun) +LUAU_NOINLINE void luau_setupcci(lua_State* L, int nresults, StkId fun) { CallInfo* ci = incr_ci(L); @@ -239,10 +238,13 @@ static LUAU_NOINLINE void luau_setupcci(lua_State* L, int nresults, StkId fun) // Batch addition of loop execution counter increments static void luau_addexeccount(Proto* p, double count) { - // Leaving room for regular counter hits to not overflow too fast - uint32_t space = UINT32_MAX / 4 - p->execcount; + if (count > 0.0) + { + // Leaving room for regular counter hits to not overflow too fast + uint32_t space = UINT32_MAX / 4 - p->execcount; - p->execcount += count < double(space) ? uint32_t(count) : space; + p->execcount += count < double(space) ? uint32_t(count) : space; + } } template @@ -1467,11 +1469,6 @@ static void luau_execute(lua_State* L) // need to invoke metamethods). break; - case LUA_TINTEGER: - pc += lvalue(ra) == lvalue(rb) ? LUAU_INSN_D(insn) : 1; - VM_ASSERT_PC(pc); - VM_NEXT(); - default: LUAU_ASSERT(!"Unknown value type"); LUAU_UNREACHABLE(); // improves switch() codegen by eliding opcode bounds checks @@ -1600,11 +1597,6 @@ static void luau_execute(lua_State* L) // need to invoke metamethods). break; - case LUA_TINTEGER: - pc += lvalue(ra) != lvalue(rb) ? LUAU_INSN_D(insn) : 1; - VM_ASSERT_PC(pc); - VM_NEXT(); - default: LUAU_ASSERT(!"Unknown value type"); LUAU_UNREACHABLE(); // improves switch() codegen by eliding opcode bounds checks @@ -2879,15 +2871,26 @@ static void luau_execute(lua_State* L) VM_CASE(LOP_NATIVECALL) { Proto* p = L->ci->p; + + // a lazy-load stub (luau_loadlazy): build the function, then enter it like LOP_CALL does + // stubs never have execdata and native functions always do; checking execdata avoids loading lazychunk on the native path + if (LUAU_UNLIKELY(!p->execdata)) + { + LUAU_ASSERT(p->lazychunk); + + VM_PROTECT(luaV_buildlazyproto(L, p)); + + L->ci->savedpc = p->code; + pc = SingleStep ? p->code : p->codeentry; + k = p->k; + VM_NEXT(); + } + LUAU_ASSERT(p->execdata); CallInfo* ci = L->ci; - if (FFlag::LuauFastpcall) - ci->flags |= LUA_CALLINFO_NATIVE; - else - ci->flags = LUA_CALLINFO_NATIVE; - + ci->flags |= LUA_CALLINFO_NATIVE; ci->savedpc = p->code; #if VM_HAS_NATIVE @@ -3731,11 +3734,6 @@ static void luau_execute(lua_State* L) VM_CASE(LOP_FASTPCALL) { VM_CASE_INSTRUCTION insn = *pc++; - - // even with compiler flag enabled, runtime can be safely disabled and will execute the fallback - if (!FFlag::LuauFastpcall) - VM_NEXT(); - VM_INTERRUPT(); int pfid = LUAU_INSN_A(insn); diff --git a/VM/src/lvmload.cpp b/VM/src/lvmload.cpp index 593c73c49..7fc6d9919 100644 --- a/VM/src/lvmload.cpp +++ b/VM/src/lvmload.cpp @@ -190,6 +190,7 @@ static void resolveImportSafe(lua_State* L, LuaTable* env, TValue* k, uint32_t i { struct ResolveImport { + LuaTable* env; TValue* k; uint32_t id; @@ -205,12 +206,12 @@ static void resolveImportSafe(lua_State* L, LuaTable* env, TValue* k, uint32_t i setnilvalue(L->top); L->top++; - luaV_getimport(L, L->gt, self->k, L->top - 1, self->id, /* propagatenil= */ true); + luaV_getimport(L, self->env, self->k, L->top - 1, self->id, /* propagatenil= */ true); } }; - ResolveImport ri = {k, id}; - if (L->gt->safeenv) + ResolveImport ri = {env, k, id}; + if (env->safeenv) { // luaD_pcall will make sure that if any C/Lua calls during import resolution fail, the thread state is restored back int oldTop = lua_gettop(L); @@ -321,19 +322,145 @@ static void remapUserdataTypes(char* data, size_t size, uint8_t* userdataRemappi LUAU_ASSERT(offset == size); } -static int loadsafe( +/* +** Lazy loading (luau_loadlazy) +** +** Only main is built at load; every other function starts as a stub, a Proto with just the header fields and one static NATIVECALL +** instruction as its code. Interpreter, C and native calls all enter a Luau function at code or codeentry, so the first call reaches +** LOP_NATIVECALL, which builds the function (luaV_buildlazyproto) and continues as if it had just been entered. The children of a +** built function are stubs again, so a function that never runs costs a stub, or nothing if its parent never ran. +** +** The chunk keeps the offset of every string and function in the caller-owned bytecode. Each stub holds a reference to it; the +** bytecode is released when the last stub is built or collected. +*/ + +static const Instruction kLazyEntryInsn = LOP_NATIVECALL; + +static Proto* newLazyStub(lua_State* L, LuauLazyChunk* chunk, Proto* parent, uint32_t fid) +{ + LUAU_ASSERT(fid < chunk->protoCount); + + Proto* p = luaF_newproto(L); + p->source = parent->source; + p->bytecodeid = int(fid); + p->funid = L->global->lastprotoid == 0 ? 0 : L->global->lastprotoid++; + + p->userdata = parent->userdata; + + const char* header = chunk->data + chunk->protoOffsets[fid]; + p->maxstacksize = uint8_t(header[0]); + p->numparams = uint8_t(header[1]); + p->nups = uint8_t(header[2]); + p->is_vararg = uint8_t(header[3]); + if (chunk->version >= 4) + p->flags = uint8_t(header[4]); + + p->code = const_cast(&kLazyEntryInsn); + p->codeentry = &kLazyEntryInsn; + p->sizecode = 1; + + p->lazychunk = chunk; + chunk->refs++; + + return p; +} + +// String ids: luau_load creates every string up front, luau_loadlazy (chunk set) creates each when a function that uses it is built +struct LoadStrings +{ + lua_State* L; + TempBuffer* strings; + const LuauLazyChunk* chunk; +}; + +static TString* readString(LoadStrings& strings, const char* data, size_t size, size_t& offset) +{ + if (!strings.chunk) + return readString(*strings.strings, data, size, offset); + + unsigned int id = readVarInt(data, size, offset); + + if (id == 0) + return NULL; + + size_t stringOffset = strings.chunk->stringOffsets[id - 1]; + unsigned int length = readVarInt(data, size, stringOffset); + + return luaS_newlstr(strings.L, data + stringOffset, length); +} + +// Function ids: luau_load loads every function before the functions that reference it, luau_loadlazy (chunk set) creates stubs +struct LoadProtos +{ + TempBuffer* protos; + LuauLazyChunk* chunk; + Proto* parent; + + // luau_loadlazy: stubs of the parent's closure constants, open addressing on bytecodeid (NULL = empty) + TempBuffer closures; + + Proto** findClosure(uint32_t fid) + { + size_t mask = closures.count - 1; + + for (size_t i = fid & mask;; i = (i + 1) & mask) + if (!closures[i] || uint32_t(closures[i]->bytecodeid) == fid) + return &closures[i]; + } + + Proto* closure(lua_State* L, uint32_t fid) + { + if (!chunk) + return (*protos)[fid]; + + // a closure constant is one of sizek constants, so the table stays at most half full + if (!closures.L) + { + size_t capacity = 2; + while (capacity < 2 * size_t(parent->sizek)) + capacity *= 2; + + closures.allocate(L, capacity); + + for (size_t i = 0; i < capacity; ++i) + closures[i] = NULL; + } + + Proto** slot = findClosure(fid); + if (!*slot) + *slot = newLazyStub(L, chunk, parent, fid); + + return *slot; + } + + Proto* child(lua_State* L, uint32_t fid) + { + if (!chunk) + return (*protos)[fid]; + + if (closures.L) + { + if (Proto* p = *findClosure(fid)) + return p; + } + + return newLazyStub(L, chunk, parent, fid); + } +}; + +// Reads the format versions; returns 1 with an error message pushed if it can't be loaded +static int loadHeader( lua_State* L, - TempBuffer& strings, - TempBuffer& protos, const char* chunkname, const char* data, size_t size, - int env + int env, + size_t& offset, + uint8_t& version, + uint8_t& typesversion ) { - size_t offset = 0; - - uint8_t version = read(data, size, offset); + version = read(data, size, offset); // 0 means the rest of the bytecode is the error message if (version == 0) @@ -352,7 +479,7 @@ static int loadsafe( return 1; } - uint8_t typesversion = 0; + typesversion = 0; if (version >= 4) { @@ -369,28 +496,20 @@ static int loadsafe( } } - // env is 0 for current environment and a stack index otherwise - LuaTable* envt = (env == 0) ? L->gt : hvalue(luaA_toobject(L, env)); - - TString* source = luaS_new(L, chunkname); - - // string table - unsigned int stringCount = readVarInt(data, size, offset); - strings.allocate(L, stringCount); - - for (unsigned int i = 0; i < stringCount; ++i) - { - unsigned int length = readVarInt(data, size, offset); - - strings[i] = luaS_newlstr(L, data + offset, length); - offset += length; - } + return 0; +} - // userdata type remapping table +static void readUserdataRemapping( + lua_State* L, + uint8_t typesversion, + LoadStrings& strings, + uint8_t* userdataRemapping, + const char* data, + size_t size, + size_t& offset +) +{ // for unknown userdata types, the entry will remap to common 'userdata' type - const uint32_t userdataTypeLimit = LBC_TYPE_TAGGED_USERDATA_END - LBC_TYPE_TAGGED_USERDATA_BASE; - uint8_t userdataRemapping[userdataTypeLimit]; - if (typesversion == 3) { memset(userdataRemapping, LBC_TYPE_USERDATA, userdataTypeLimit); @@ -410,444 +529,509 @@ static int loadsafe( index = read(data, size, offset); } } +} - // proto table - unsigned int protoCount = readVarInt(data, size, offset); - protos.allocate(L, protoCount); +// Reads one function into p, starting from its maxstacksize byte +static void loadProto( + lua_State* L, + Proto* p, + uint8_t version, + uint8_t typesversion, + uint8_t* userdataRemapping, + LoadStrings& strings, + LoadProtos& protos, + LuaTable* envt, + LuaTable* importenv, + const char* data, + size_t size, + size_t& offset +) +{ + p->maxstacksize = read(data, size, offset); + p->numparams = read(data, size, offset); + p->nups = read(data, size, offset); + p->is_vararg = read(data, size, offset); - for (unsigned int i = 0; i < protoCount; ++i) + if (version >= 4) { - uint32_t protoSize = 0; - if (version >= 12) - protoSize = readVarInt(data, size, offset); - size_t protoStartOffset = offset; - Proto* p = luaF_newproto(L); - p->source = source; - p->bytecodeid = int(i); - p->funid = L->global->lastprotoid == 0 ? 0 : L->global->lastprotoid++; + p->flags = read(data, size, offset); - p->maxstacksize = read(data, size, offset); - p->numparams = read(data, size, offset); - p->nups = read(data, size, offset); - p->is_vararg = read(data, size, offset); - - if (version >= 4) + if (typesversion == 1) { - p->flags = read(data, size, offset); + uint32_t typesize = readVarInt(data, size, offset); - if (typesversion == 1) + if (typesize) { - uint32_t typesize = readVarInt(data, size, offset); - - if (typesize) - { - uint8_t* types = (uint8_t*)data + offset; + uint8_t* types = (uint8_t*)data + offset; - LUAU_ASSERT(typesize == unsigned(2 + p->numparams)); - LUAU_ASSERT(types[0] == LBC_TYPE_FUNCTION); - LUAU_ASSERT(types[1] == p->numparams); + LUAU_ASSERT(typesize == unsigned(2 + p->numparams)); + LUAU_ASSERT(types[0] == LBC_TYPE_FUNCTION); + LUAU_ASSERT(types[1] == p->numparams); - // transform v1 into v2 format - int headersize = typesize > 127 ? 4 : 3; + // transform v1 into v2 format + int headersize = typesize > 127 ? 4 : 3; - p->typeinfo = luaM_newarray(L, headersize + typesize, uint8_t, p->memcat); - p->sizetypeinfo = headersize + typesize; + p->typeinfo = luaM_newarray(L, headersize + typesize, uint8_t, p->memcat); + p->sizetypeinfo = headersize + typesize; - if (headersize == 4) - { - p->typeinfo[0] = (typesize & 127) | (1 << 7); - p->typeinfo[1] = typesize >> 7; - p->typeinfo[2] = 0; - p->typeinfo[3] = 0; - } - else - { - p->typeinfo[0] = uint8_t(typesize); - p->typeinfo[1] = 0; - p->typeinfo[2] = 0; - } - - memcpy(p->typeinfo + headersize, types, typesize); + if (headersize == 4) + { + p->typeinfo[0] = (typesize & 127) | (1 << 7); + p->typeinfo[1] = typesize >> 7; + p->typeinfo[2] = 0; + p->typeinfo[3] = 0; + } + else + { + p->typeinfo[0] = uint8_t(typesize); + p->typeinfo[1] = 0; + p->typeinfo[2] = 0; } - offset += typesize; + memcpy(p->typeinfo + headersize, types, typesize); } - else if (typesversion == 2 || typesversion == 3) - { - uint32_t typesize = readVarInt(data, size, offset); - if (typesize) - { - uint8_t* types = (uint8_t*)data + offset; + offset += typesize; + } + else if (typesversion == 2 || typesversion == 3) + { + uint32_t typesize = readVarInt(data, size, offset); + + if (typesize) + { + uint8_t* types = (uint8_t*)data + offset; - p->typeinfo = luaM_newarray(L, typesize, uint8_t, p->memcat); - p->sizetypeinfo = typesize; - memcpy(p->typeinfo, types, typesize); - offset += typesize; + p->typeinfo = luaM_newarray(L, typesize, uint8_t, p->memcat); + p->sizetypeinfo = typesize; + memcpy(p->typeinfo, types, typesize); + offset += typesize; - if (typesversion == 3) - { - remapUserdataTypes((char*)(uint8_t*)p->typeinfo, p->sizetypeinfo, userdataRemapping, userdataTypeLimit); - } + if (typesversion == 3) + { + remapUserdataTypes((char*)(uint8_t*)p->typeinfo, p->sizetypeinfo, userdataRemapping, userdataTypeLimit); } } } + } - const int sizecode = readVarInt(data, size, offset); - p->code = luaM_newarray(L, sizecode, Instruction, p->memcat); - p->sizecode = sizecode; + const int sizecode = readVarInt(data, size, offset); + p->code = luaM_newarray(L, sizecode, Instruction, p->memcat); + p->sizecode = sizecode; - for (int j = 0; j < p->sizecode; ++j) - p->code[j] = read(data, size, offset); + for (int j = 0; j < p->sizecode; ++j) + p->code[j] = read(data, size, offset); - p->codeentry = p->code; + p->codeentry = p->code; + + const int sizek = readVarInt(data, size, offset); + p->k = luaM_newarray(L, sizek, TValue, p->memcat); + p->sizek = sizek; + + // Initialize the constants to nil to ensure they have a valid state + // in the event that some operation in the following loop fails with + // an exception. + for (int j = 0; j < p->sizek; ++j) + { + setnilvalue(&p->k[j]); + } + + for (int j = 0; j < p->sizek; ++j) + { + switch (read(data, size, offset)) + { + case LBC_CONSTANT_NIL: + // All constants have already been pre-initialized to nil + break; - const int sizek = readVarInt(data, size, offset); - p->k = luaM_newarray(L, sizek, TValue, p->memcat); - p->sizek = sizek; + case LBC_CONSTANT_BOOLEAN: + { + uint8_t v = read(data, size, offset); + setbvalue(&p->k[j], v); + break; + } - // Initialize the constants to nil to ensure they have a valid state - // in the event that some operation in the following loop fails with - // an exception. - for (int j = 0; j < p->sizek; ++j) + case LBC_CONSTANT_NUMBER: { - setnilvalue(&p->k[j]); + double v = read(data, size, offset); + setnvalue(&p->k[j], v); + break; } - for (int j = 0; j < p->sizek; ++j) + case LBC_CONSTANT_VECTOR: { - switch (read(data, size, offset)) - { - case LBC_CONSTANT_NIL: - // All constants have already been pre-initialized to nil - break; + float x = read(data, size, offset); + float y = read(data, size, offset); + float z = read(data, size, offset); + float w = read(data, size, offset); + (void)w; + setvvalue(L, &p->k[j], x, y, z, w); + break; + } - case LBC_CONSTANT_BOOLEAN: - { - uint8_t v = read(data, size, offset); - setbvalue(&p->k[j], v); - break; - } + case LBC_CONSTANT_VECTORD: + { + double x = read(data, size, offset); + double y = read(data, size, offset); + double z = read(data, size, offset); + double w = read(data, size, offset); + (void)w; + setvvalue(L, &p->k[j], x, y, z, w); + break; + } - case LBC_CONSTANT_NUMBER: - { - double v = read(data, size, offset); - setnvalue(&p->k[j], v); - break; - } + case LBC_CONSTANT_STRING: + { + TString* v = readString(strings, data, size, offset); + setsvalue(L, &p->k[j], v); + break; + } - case LBC_CONSTANT_VECTOR: - { - float x = read(data, size, offset); - float y = read(data, size, offset); - float z = read(data, size, offset); - float w = read(data, size, offset); - (void)w; - setvvalue(L, &p->k[j], x, y, z, w); - break; - } + case LBC_CONSTANT_IMPORT: + { + uint32_t iid = read(data, size, offset); + resolveImportSafe(L, importenv, p->k, iid); + setobj(L, &p->k[j], L->top - 1); + L->top--; + break; + } - case LBC_CONSTANT_VECTORD: + case LBC_CONSTANT_TABLE: + { + int keys = readVarInt(data, size, offset); + LuaTable* h = luaH_new(L, 0, keys); + for (int i = 0; i < keys; ++i) { - double x = read(data, size, offset); - double y = read(data, size, offset); - double z = read(data, size, offset); - double w = read(data, size, offset); - (void)w; - setvvalue(L, &p->k[j], x, y, z, w); - break; + int key = readVarInt(data, size, offset); + TValue* val = luaH_set(L, h, &p->k[key]); + setnvalue(val, 0.0); } + sethvalue(L, &p->k[j], h); + break; + } - case LBC_CONSTANT_STRING: - { - TString* v = readString(strings, data, size, offset); - setsvalue(L, &p->k[j], v); - break; - } + case LBC_CONSTANT_TABLE_WITH_CONSTANTS: + { + uint32_t keys = readVarInt(data, size, offset); + LuaTable* h = luaH_new(L, 0, keys); - case LBC_CONSTANT_IMPORT: - { - uint32_t iid = read(data, size, offset); - resolveImportSafe(L, envt, p->k, iid); - setobj(L, &p->k[j], L->top - 1); - L->top--; - break; - } + TempBuffer nilKeys; + nilKeys.allocate(L, keys); + size_t nilKeysSize = 0; - case LBC_CONSTANT_TABLE: + for (uint32_t i = 0; i < keys; ++i) { - int keys = readVarInt(data, size, offset); - LuaTable* h = luaH_new(L, 0, keys); - for (int i = 0; i < keys; ++i) + int32_t key = readVarInt(data, size, offset); + TValue* val = luaH_set(L, h, &p->k[key]); + int32_t constantIdx = read(data, size, offset); + if (constantIdx >= 0) { - int key = readVarInt(data, size, offset); - TValue* val = luaH_set(L, h, &p->k[key]); - setnvalue(val, 0.0); + TValue* constant = &p->k[constantIdx]; + if (ttisnil(constant)) + { + nilKeys[nilKeysSize++] = key; + } + else + { + setobj2t(L, val, constant); + luaC_barriert(L, h, constant); + continue; + } } - sethvalue(L, &p->k[j], h); - break; + setnvalue(val, 0.0); } - case LBC_CONSTANT_TABLE_WITH_CONSTANTS: + for (size_t idx = 0; idx < nilKeysSize; idx++) { - uint32_t keys = readVarInt(data, size, offset); - LuaTable* h = luaH_new(L, 0, keys); - - TempBuffer nilKeys; - nilKeys.allocate(L, keys); - size_t nilKeysSize = 0; + int32_t key = nilKeys[idx]; + TValue* val = luaH_set(L, h, &p->k[key]); + setnilvalue(val); + } - for (uint32_t i = 0; i < keys; ++i) - { - int32_t key = readVarInt(data, size, offset); - TValue* val = luaH_set(L, h, &p->k[key]); - int32_t constantIdx = read(data, size, offset); - if (constantIdx >= 0) - { - TValue* constant = &p->k[constantIdx]; - if (ttisnil(constant)) - { - nilKeys[nilKeysSize++] = key; - } - else - { - setobj2t(L, val, constant); - luaC_barriert(L, h, constant); - continue; - } - } - setnvalue(val, 0.0); - } + sethvalue(L, &p->k[j], h); + break; + } - for (size_t idx = 0; idx < nilKeysSize; idx++) - { - int32_t key = nilKeys[idx]; - TValue* val = luaH_set(L, h, &p->k[key]); - setnilvalue(val); - } + case LBC_CONSTANT_CLOSURE: + { + uint32_t fid = readVarInt(data, size, offset); + Proto* cp = protos.closure(L, fid); + Closure* cl = luaF_newLclosure(L, cp->nups, envt, cp); + cl->preload = (cl->nupvalues > 0); + setclvalue(L, &p->k[j], cl); + break; + } - sethvalue(L, &p->k[j], h); - break; + case LBC_CONSTANT_CLASS_SHAPE: + { + uint32_t cnid = readVarInt(data, size, offset); + TValue* classname = &p->k[cnid]; + LUAU_ASSERT(ttisstring(classname)); + uint8_t numPrivateFields = read(data, size, offset); + uint8_t numPrivateMethods = read(data, size, offset); + uint32_t numProperties = readVarInt(data, size, offset); + uint32_t numMethods = readVarInt(data, size, offset); + uint32_t numMembers = numMethods + numProperties; + uint32_t membersWithoutPrivateMethods = numMembers - static_cast(numPrivateMethods); + TString** offsetToMember = luaM_newarray(L, membersWithoutPrivateMethods, TString*, L->activememcat); + memset(offsetToMember, 0, membersWithoutPrivateMethods * sizeof(TString*)); + LuaTable* membersToOffset = luaH_new(L, 0, membersWithoutPrivateMethods - static_cast(numPrivateFields)); + + uint32_t idx = 0; + // Set public field names + for (; idx < numProperties - static_cast(numPrivateFields); idx++) + { + uint32_t mid = readVarInt(data, size, offset); + TValue* memberName = &p->k[mid]; + LUAU_ASSERT(ttisstring(memberName)); + offsetToMember[idx] = tsvalue(memberName); + TValue* val = luaH_setstr(L, membersToOffset, tsvalue(memberName)); + setnvalue(val, idx); } - case LBC_CONSTANT_CLOSURE: + // Set public method names + for (idx = numProperties; idx < membersWithoutPrivateMethods; idx++) { - uint32_t fid = readVarInt(data, size, offset); - Closure* cl = luaF_newLclosure(L, protos[fid]->nups, envt, protos[fid]); - cl->preload = (cl->nupvalues > 0); - setclvalue(L, &p->k[j], cl); - break; + uint32_t mid = readVarInt(data, size, offset); + TValue* memberName = &p->k[mid]; + LUAU_ASSERT(ttisstring(memberName)); + offsetToMember[idx] = tsvalue(memberName); + TValue* val = luaH_setstr(L, membersToOffset, tsvalue(memberName)); + setnvalue(val, idx); } - case LBC_CONSTANT_CLASS_SHAPE: - { - uint32_t cnid = readVarInt(data, size, offset); - TValue* classname = &p->k[cnid]; - LUAU_ASSERT(ttisstring(classname)); - uint8_t numPrivateFields = read(data, size, offset); - uint8_t numPrivateMethods = read(data, size, offset); - uint32_t numProperties = readVarInt(data, size, offset); - uint32_t numMethods = readVarInt(data, size, offset); - uint32_t numMembers = numMethods + numProperties; - uint32_t membersWithoutPrivateMethods = numMembers - static_cast(numPrivateMethods); - TString** offsetToMember = luaM_newarray(L, membersWithoutPrivateMethods, TString*, L->activememcat); - memset(offsetToMember, 0, membersWithoutPrivateMethods * sizeof(TString*)); - LuaTable* membersToOffset = luaH_new(L, 0, membersWithoutPrivateMethods - static_cast(numPrivateFields)); - - uint32_t idx = 0; - // Set public field names - for (; idx < numProperties - static_cast(numPrivateFields); idx++) - { - uint32_t mid = readVarInt(data, size, offset); - TValue* memberName = &p->k[mid]; - LUAU_ASSERT(ttisstring(memberName)); - offsetToMember[idx] = tsvalue(memberName); - TValue* val = luaH_setstr(L, membersToOffset, tsvalue(memberName)); - setnvalue(val, idx); - } + membersToOffset->readonly = true; - // Set public method names - for (idx = numProperties; idx < membersWithoutPrivateMethods; idx++) - { - uint32_t mid = readVarInt(data, size, offset); - TValue* memberName = &p->k[mid]; - LUAU_ASSERT(ttisstring(memberName)); - offsetToMember[idx] = tsvalue(memberName); - TValue* val = luaH_setstr(L, membersToOffset, tsvalue(memberName)); - setnvalue(val, idx); - } + LuauClass* lco = luaR_newclass( + L, tsvalue(classname), membersToOffset, offsetToMember, numProperties, numMethods, numPrivateFields, numPrivateMethods, envt + ); + setclassvalue(L, &p->k[j], lco); + break; + } - membersToOffset->readonly = true; + default: + LUAU_ASSERT(!"Unexpected constant kind"); + } + } - LuauClass* lco = luaR_newclass( - L, tsvalue(classname), membersToOffset, offsetToMember, numProperties, numMethods, numPrivateFields, numPrivateMethods, envt - ); - setclassvalue(L, &p->k[j], lco); - break; - } + for (Instruction* instruction = p->code; instruction < p->code + p->sizecode;) + { + int targetOp = -1; - case LBC_CONSTANT_INTEGER: - { - bool isNegative = read(data, size, offset); - uint64_t magnitude = readVarInt64(data, size, offset); - setlvalue(&p->k[j], isNegative ? (int64_t)(~magnitude + 1) : (int64_t)magnitude); - break; - } + switch (LUAU_INSN_OP(*instruction)) + { + case LOP_GETTABLEKS: + targetOp = LOP_GETUDATAKS; + break; - default: - LUAU_ASSERT(!"Unexpected constant kind"); - } + case LOP_SETTABLEKS: + targetOp = LOP_SETUDATAKS; + break; + + case LOP_NAMECALL: + targetOp = LOP_NAMECALLUDATA; + break; } - for (Instruction* instruction = p->code; instruction < p->code + p->sizecode;) + if (targetOp != -1) { - int targetOp = -1; + LUAU_ASSERT(instruction[1] < uint32_t(sizek)); - switch (LUAU_INSN_OP(*instruction)) + // We take over the upper 16 bits of AUX - so no constants with big indices. + if (instruction[1] < 0x10000) { - case LOP_GETTABLEKS: - targetOp = LOP_GETUDATAKS; - break; + TValue* k = &p->k[instruction[1]]; + TString* s = tsvalue(k); - case LOP_SETTABLEKS: - targetOp = LOP_SETUDATAKS; - break; + luaS_updateatom(L, s); - case LOP_NAMECALL: - targetOp = LOP_NAMECALLUDATA; - break; + if (s->atom >= 0) + *instruction = (*instruction & 0xffffff00) | targetOp; } + } - if (targetOp != -1) - { - LUAU_ASSERT(instruction[1] < uint32_t(sizek)); + instruction += Luau::getOpLength(LuauOpcode(LUAU_INSN_OP(*instruction))); + } - // We take over the upper 16 bits of AUX - so no constants with big indices. - if (instruction[1] < 0x10000) - { - TValue* k = &p->k[instruction[1]]; - TString* s = tsvalue(k); + const int sizep = readVarInt(data, size, offset); + p->p = luaM_newarray(L, sizep, Proto*, p->memcat); + p->sizep = sizep; - luaS_updateatom(L, s); + // luau_loadlazy creates children and strings while filling the arrays below: keep a valid state in case of an exception + for (int j = 0; j < p->sizep; ++j) + p->p[j] = NULL; - if (s->atom >= 0) - *instruction = (*instruction & 0xffffff00) | targetOp; - } - } + for (int j = 0; j < p->sizep; ++j) + { + uint32_t fid = readVarInt(data, size, offset); + p->p[j] = protos.child(L, fid); + } + + p->linedefined = readVarInt(data, size, offset); + p->debugname = readString(strings, data, size, offset); + + uint8_t lineinfo = read(data, size, offset); + + if (lineinfo) + { + p->linegaplog2 = read(data, size, offset); - instruction += Luau::getOpLength(LuauOpcode(LUAU_INSN_OP(*instruction))); + int intervals = ((p->sizecode - 1) >> p->linegaplog2) + 1; + int absoffset = (p->sizecode + 3) & ~3; + + const int sizelineinfo = absoffset + intervals * sizeof(int); + p->lineinfo = luaM_newarray(L, sizelineinfo, uint8_t, p->memcat); + p->sizelineinfo = sizelineinfo; + + p->abslineinfo = (int*)(p->lineinfo + absoffset); + + uint8_t lastoffset = 0; + for (int j = 0; j < p->sizecode; ++j) + { + lastoffset += read(data, size, offset); + p->lineinfo[j] = lastoffset; } - const int sizep = readVarInt(data, size, offset); - p->p = luaM_newarray(L, sizep, Proto*, p->memcat); - p->sizep = sizep; + int lastline = 0; + for (int j = 0; j < intervals; ++j) + { + lastline += read(data, size, offset); + p->abslineinfo[j] = lastline; + } + } - for (int j = 0; j < p->sizep; ++j) + uint8_t debuginfo = read(data, size, offset); + + if (debuginfo) + { + const int sizelocvars = readVarInt(data, size, offset); + p->locvars = luaM_newarray(L, sizelocvars, LocVar, p->memcat); + p->sizelocvars = sizelocvars; + + for (int j = 0; j < p->sizelocvars; ++j) + p->locvars[j].varname = NULL; + + for (int j = 0; j < p->sizelocvars; ++j) { - uint32_t fid = readVarInt(data, size, offset); - p->p[j] = protos[fid]; + p->locvars[j].varname = readString(strings, data, size, offset); + p->locvars[j].startpc = readVarInt(data, size, offset); + p->locvars[j].endpc = readVarInt(data, size, offset); + p->locvars[j].reg = read(data, size, offset); } - p->linedefined = readVarInt(data, size, offset); - p->debugname = readString(strings, data, size, offset); + const int sizeupvalues = readVarInt(data, size, offset); + LUAU_ASSERT(sizeupvalues == p->nups); - uint8_t lineinfo = read(data, size, offset); + p->upvalues = luaM_newarray(L, sizeupvalues, TString*, p->memcat); + p->sizeupvalues = sizeupvalues; - if (lineinfo) + for (int j = 0; j < p->sizeupvalues; ++j) + p->upvalues[j] = NULL; + + for (int j = 0; j < p->sizeupvalues; ++j) { - p->linegaplog2 = read(data, size, offset); + p->upvalues[j] = readString(strings, data, size, offset); + } + } - int intervals = ((p->sizecode - 1) >> p->linegaplog2) + 1; - int absoffset = (p->sizecode + 3) & ~3; + if (version >= 11) + { + p->feedbackvecsize = readVarInt(data, size, offset); - const int sizelineinfo = absoffset + intervals * sizeof(int); - p->lineinfo = luaM_newarray(L, sizelineinfo, uint8_t, p->memcat); - p->sizelineinfo = sizelineinfo; + if (p->feedbackvecsize > 0) + { + p->feedbackvec = luaM_newarray(L, p->feedbackvecsize, FeedbackVectorSlot, p->memcat); + } + for (uint32_t j = 0; j < p->feedbackvecsize; j++) + { + uint8_t slottype = read(data, size, offset); - p->abslineinfo = (int*)(p->lineinfo + absoffset); + FeedbackVectorSlot& slot = p->feedbackvec[j]; + slot.kind = static_cast(slottype); - uint8_t lastoffset = 0; - for (int j = 0; j < p->sizecode; ++j) + if (slottype == LFT_CALLTARGET) { - lastoffset += read(data, size, offset); - p->lineinfo[j] = lastoffset; + slot.call_target.pc = readVarInt(data, size, offset); + slot.call_target.proto = 0; + slot.call_target.hits = 0; } - - int lastline = 0; - for (int j = 0; j < intervals; ++j) + else if (slottype == LFT_CONSTRUCT) { - lastline += read(data, size, offset); - p->abslineinfo[j] = lastline; + slot.construct.shape = readVarInt(data, size, offset); + slot.construct.classid = 0; + slot.construct.match = LCM_MISMATCH; + } + else + { + LUAU_ASSERT(!"unknown feedback slot type"); } } + } - uint8_t debuginfo = read(data, size, offset); + if (version >= 12) + { + if ((p->flags & LPF_INLINABLE) != 0) + p->cost = readVarInt64(data, size, offset); + } +} - if (debuginfo) - { - const int sizelocvars = readVarInt(data, size, offset); - p->locvars = luaM_newarray(L, sizelocvars, LocVar, p->memcat); - p->sizelocvars = sizelocvars; +static int loadsafe( + lua_State* L, + TempBuffer& strings, + TempBuffer& protos, + const char* chunkname, + const char* data, + size_t size, + int env +) +{ + size_t offset = 0; - for (int j = 0; j < p->sizelocvars; ++j) - { - p->locvars[j].varname = readString(strings, data, size, offset); - p->locvars[j].startpc = readVarInt(data, size, offset); - p->locvars[j].endpc = readVarInt(data, size, offset); - p->locvars[j].reg = read(data, size, offset); - } + uint8_t version = 0; + uint8_t typesversion = 0; - const int sizeupvalues = readVarInt(data, size, offset); - LUAU_ASSERT(sizeupvalues == p->nups); + if (int err = loadHeader(L, chunkname, data, size, env, offset, version, typesversion)) + return err; - p->upvalues = luaM_newarray(L, sizeupvalues, TString*, p->memcat); - p->sizeupvalues = sizeupvalues; + // env is 0 for current environment and a stack index otherwise + LuaTable* envt = (env == 0) ? L->gt : hvalue(luaA_toobject(L, env)); - for (int j = 0; j < p->sizeupvalues; ++j) - { - p->upvalues[j] = readString(strings, data, size, offset); - } - } + TString* source = luaS_new(L, chunkname); - if (version >= 11) - { - p->feedbackvecsize = readVarInt(data, size, offset); + // string table + unsigned int stringCount = readVarInt(data, size, offset); + strings.allocate(L, stringCount); - if (p->feedbackvecsize > 0) - { - p->feedbackvec = luaM_newarray(L, p->feedbackvecsize, FeedbackVectorSlot, p->memcat); - } - for (uint32_t j = 0; j < p->feedbackvecsize; j++) - { - uint8_t slottype = read(data, size, offset); + for (unsigned int i = 0; i < stringCount; ++i) + { + unsigned int length = readVarInt(data, size, offset); - FeedbackVectorSlot& slot = p->feedbackvec[j]; - slot.kind = static_cast(slottype); + strings[i] = luaS_newlstr(L, data + offset, length); + offset += length; + } - if (slottype == LFT_CALLTARGET) - { - slot.call_target.pc = readVarInt(data, size, offset); - slot.call_target.proto = 0; - slot.call_target.hits = 0; - } - else if (slottype == LFT_CONSTRUCT) - { - slot.construct.shape = readVarInt(data, size, offset); - slot.construct.classid = 0; - slot.construct.match = LCM_MISMATCH; - } - else - { - LUAU_ASSERT(!"unknown feedback slot type"); - } - } - } + // userdata type remapping table + uint8_t userdataRemapping[userdataTypeLimit]; + LoadStrings loadStrings = {L, &strings, NULL}; + readUserdataRemapping(L, typesversion, loadStrings, userdataRemapping, data, size, offset); + + // proto table + unsigned int protoCount = readVarInt(data, size, offset); + protos.allocate(L, protoCount); + + LoadProtos loadProtos = {&protos, NULL, NULL}; + for (unsigned int i = 0; i < protoCount; ++i) + { + uint32_t protoSize = 0; if (version >= 12) - { - if ((p->flags & LPF_INLINABLE) != 0) - p->cost = readVarInt64(data, size, offset); - } + protoSize = readVarInt(data, size, offset); + size_t protoStartOffset = offset; + Proto* p = luaF_newproto(L); + p->source = source; + p->bytecodeid = int(i); + p->funid = L->global->lastprotoid == 0 ? 0 : L->global->lastprotoid++; + + loadProto(L, p, version, typesversion, userdataRemapping, loadStrings, loadProtos, envt, L->gt, data, size, offset); if (version >= 12) { @@ -918,3 +1102,293 @@ int luau_load(lua_State* L, const char* chunkname, const char* data, size_t size return ctx.result; } + +void luaV_releaselazychunk(lua_State* L, LuauLazyChunk* chunk) +{ + LUAU_ASSERT(chunk->refs > 0); + + if (--chunk->refs != 0) + return; + + if (chunk->release) + chunk->release(chunk->owner); + + luaM_freearray(L, chunk->stringOffsets, chunk->stringCount, uint32_t, chunk->memcat); + luaM_freearray(L, chunk->protoOffsets, chunk->protoCount, uint32_t, chunk->memcat); + luaM_freearray(L, chunk, 1, LuauLazyChunk, chunk->memcat); +} + +// Builds function p->bytecodeid into p; its children become stubs +static void buildLazyProto(lua_State* L, LuauLazyChunk* chunk, Proto* p, LuaTable* envt, LuaTable* importenv) +{ + size_t offset = chunk->protoOffsets[p->bytecodeid]; + + LoadStrings strings = {L, NULL, chunk}; + LoadProtos protos = {NULL, chunk, p}; + + loadProto( + L, p, chunk->version, chunk->typesversion, chunk->userdataRemapping, strings, protos, envt, importenv, chunk->data, chunk->size, offset + ); +} + +// Returns 0 with main pushed, 1 with an error pushed, or 2 (nothing pushed) when the chunk must be loaded with luau_load +static int loadlazysafe(lua_State* L, LuauLazyChunk* chunk, const char* chunkname, int env) +{ + const char* data = chunk->data; + size_t size = chunk->size; + size_t offset = 0; + + if (int err = loadHeader(L, chunkname, data, size, env, offset, chunk->version, chunk->typesversion)) + return err; + + // functions are found through the size prefix that version 12 added + if (chunk->version < 12) + return 2; + + // env is 0 for current environment and a stack index otherwise + LuaTable* envt = (env == 0) ? L->gt : hvalue(luaA_toobject(L, env)); + + TString* source = luaS_new(L, chunkname); + + // string table: just the offsets, a string is created when a function that uses it is built + unsigned int stringCount = readVarInt(data, size, offset); + chunk->stringOffsets = luaM_newarray(L, stringCount, uint32_t, chunk->memcat); + chunk->stringCount = stringCount; + + for (unsigned int i = 0; i < stringCount; ++i) + { + chunk->stringOffsets[i] = uint32_t(offset); + + unsigned int length = readVarInt(data, size, offset); + offset += length; + } + + LoadStrings strings = {L, NULL, chunk}; + readUserdataRemapping(L, chunk->typesversion, strings, chunk->userdataRemapping, data, size, offset); + + unsigned int protoCount = readVarInt(data, size, offset); + chunk->protoOffsets = luaM_newarray(L, protoCount, uint32_t, chunk->memcat); + chunk->protoCount = protoCount; + + for (unsigned int i = 0; i < protoCount; ++i) + { + uint32_t protoSize = readVarInt(data, size, offset); + + chunk->protoOffsets[i] = uint32_t(offset); + + // native code generation needs every function of the chunk built + uint8_t flags = uint8_t(data[offset + 4]); + if (flags & (LPF_NATIVE_MODULE | LPF_NATIVE_FUNCTION)) + return 2; + + offset += protoSize; + } + + uint32_t mainid = readVarInt(data, size, offset); + + Proto* main = luaF_newproto(L); + main->source = source; + main->bytecodeid = int(mainid); + main->funid = L->global->lastprotoid == 0 ? 0 : L->global->lastprotoid++; + + chunk->envt = envt; + chunk->importenv = L->gt; + + buildLazyProto(L, chunk, main, chunk->envt, chunk->importenv); + + luaC_threadbarrier(L); + + Closure* cl = luaF_newLclosure(L, 0, envt, main); + setclvalue(L, L->top, cl); + incr_top(L); + + return 0; +} + +struct LazyLoadContext +{ + LuauLazyChunk* chunk; + const char* chunkname; + const char* data; + size_t size; + int env; + void* owner; + void (*release)(void* owner); + + int result; +}; + +static void runLazyLoad(lua_State* L, void* ud) +{ + LazyLoadContext* ctx = static_cast(ud); + + LuauLazyChunk* chunk = luaM_newarray(L, 1, LuauLazyChunk, L->activememcat); + memset(chunk, 0, sizeof(LuauLazyChunk)); + chunk->data = ctx->data; + chunk->size = ctx->size; + chunk->owner = ctx->owner; + chunk->release = ctx->release; + chunk->refs = 1; + chunk->memcat = L->activememcat; + ctx->chunk = chunk; + + ctx->result = loadlazysafe(L, chunk, ctx->chunkname, ctx->env); +} + +int luau_loadlazy(lua_State* L, const char* chunkname, const char* data, size_t size, int env, void* owner, void (*release)(void* owner)) +{ + // we will allocate a fair amount of memory so check GC before we do + luaC_checkGC(L); + + // pause GC for the duration of deserialization - some objects we're creating aren't rooted + const ScopedDisableGC pauseGC{L->global, SIZE_MAX}; + + LazyLoadContext ctx = { + NULL, + chunkname, + data, + size, + env, + owner, + release, + }; + + int status = luaD_rawrunprotected(L, &runLazyLoad, &ctx); + + // load can either succeed or get an OOM error, any other errors should be handled internally + LUAU_ASSERT(status == LUA_OK || status == LUA_ERRMEM); + + if (status == LUA_OK && ctx.result == 2) + ctx.result = luau_load(L, chunkname, data, size, env); + + // drop the load's reference: the stubs keep the chunk and the bytecode alive + if (ctx.chunk) + luaV_releaselazychunk(L, ctx.chunk); + else if (release) + release(owner); + + if (status == LUA_ERRMEM) + { + lua_pushstring(L, LUA_MEMERRMSG); // out-of-memory error message doesn't require an allocation + return 1; + } + + return ctx.result; +} + +// Moves what loadProto read into `from` to the stub `to`; `from` is left without allocations, so collecting it frees nothing +static void moveProtoBody(Proto* to, Proto* from) +{ + to->code = from->code; + to->codeentry = from->codeentry; + to->sizecode = from->sizecode; + to->k = from->k; + to->sizek = from->sizek; + to->p = from->p; + to->sizep = from->sizep; + to->lineinfo = from->lineinfo; + to->abslineinfo = from->abslineinfo; + to->sizelineinfo = from->sizelineinfo; + to->linegaplog2 = from->linegaplog2; + to->linedefined = from->linedefined; + to->debugname = from->debugname; + to->locvars = from->locvars; + to->sizelocvars = from->sizelocvars; + to->upvalues = from->upvalues; + to->sizeupvalues = from->sizeupvalues; + to->typeinfo = from->typeinfo; + to->sizetypeinfo = from->sizetypeinfo; + to->feedbackvec = from->feedbackvec; + to->feedbackvecsize = from->feedbackvecsize; + to->cost = from->cost; + + from->code = NULL; + from->sizecode = 0; + from->k = NULL; + from->sizek = 0; + from->p = NULL; + from->sizep = 0; + from->lineinfo = NULL; + from->sizelineinfo = 0; + from->locvars = NULL; + from->sizelocvars = 0; + from->upvalues = NULL; + from->sizeupvalues = 0; + from->typeinfo = NULL; + from->sizetypeinfo = 0; + from->feedbackvec = NULL; + from->feedbackvecsize = 0; +} + +struct LazyBuildContext +{ + LuauLazyChunk* chunk; + Proto* p; + Proto* built; +}; + +static void runLazyBuild(lua_State* L, void* ud) +{ + LazyBuildContext* ctx = static_cast(ud); + + Proto* built = luaF_newproto(L); + built->source = ctx->p->source; + built->bytecodeid = ctx->p->bytecodeid; + built->userdata = ctx->p->userdata; + ctx->built = built; + + buildLazyProto(L, ctx->chunk, built, ctx->chunk->envt, ctx->chunk->importenv); +} + +void luaV_buildlazyproto(lua_State* L, Proto* p) +{ + LuauLazyChunk* chunk = p->lazychunk; + LUAU_ASSERT(chunk); + + // the function is built into a temporary proto, so p stays a valid stub if the build runs out of memory or calls p again (import + // resolution can run Luau code) + LazyBuildContext ctx = {chunk, p, NULL}; + + // like luau_load, everything the build allocates belongs to the memory category of the chunk's load + const uint8_t activememcat = L->activememcat; + L->activememcat = p->memcat; + + // a call from import resolution can build p and drop p's reference while this build still reads the chunk; if p was the last + // stub that would free the chunk under this build, so the build holds a reference of its own + chunk->refs++; + + int status = 0; + { + // pause GC for the duration of deserialization - some objects we're creating aren't rooted + const ScopedDisableGC pauseGC{L->global, SIZE_MAX}; + + status = luaD_rawrunprotected(L, &runLazyBuild, &ctx); + } + + L->activememcat = activememcat; + + // a build can only fail with an OOM error, any other errors are handled internally + LUAU_ASSERT(status == LUA_OK || status == LUA_ERRMEM); + + if (status != LUA_OK) + { + luaV_releaselazychunk(L, chunk); + luaD_throw(L, status); + } + + // a call from import resolution has built p already; this build is garbage + if (p->lazychunk) + { + moveProtoBody(p, ctx.built); + p->lazychunk = nullptr; + + // p may already be black in this GC cycle, and everything it references now is new + luaC_barrierfast(L, p); + + // p's reference + luaV_releaselazychunk(L, chunk); + } + + // the build's reference + luaV_releaselazychunk(L, chunk); +} diff --git a/VM/src/lvmutils.cpp b/VM/src/lvmutils.cpp index 5de549a7d..367bb877b 100644 --- a/VM/src/lvmutils.cpp +++ b/VM/src/lvmutils.cpp @@ -421,8 +421,6 @@ int luaV_equalval(lua_State* L, const TValue* t1, const TValue* t2) return 1; case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); - case LUA_TINTEGER: - return luai_inteq(lvalue(t1), lvalue(t2)); case LUA_TVECTOR: return luai_veceq(vvalue(t1), vvalue(t2)); case LUA_TBOOLEAN: diff --git a/bench/tests/integers/blake2b_int64.lua b/bench/tests/integers/blake2b_int64.lua deleted file mode 100644 index dda04b27d..000000000 --- a/bench/tests/integers/blake2b_int64.lua +++ /dev/null @@ -1,184 +0,0 @@ -local function prequire(name) local success, result = pcall(require, name); return success and result end -local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support") - -function test() - - local IV1 = 0x6a09e667f3bcc908i - local IV2 = 0xbb67ae8584caa73bi - local IV3 = 0x3c6ef372fe94f82bi - local IV4 = 0xa54ff53a5f1d36f1i - local IV5 = 0x510e527fade682d1i - local IV6 = 0x9b05688c2b3e6c1fi - local IV7 = 0x1f83d9abfb41bd6bi - local IV8 = 0x5be0cd19137e2179i - - local INV_MASK = 0xffffffffffffffffi - - local SIGMA = - { - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, - { 15, 11, 5, 9, 10, 16, 14, 7, 2, 13, 1, 3, 12, 8, 6, 4 }, - { 12, 9, 13, 1, 6, 3, 16, 14, 11, 15, 4, 7, 8, 2, 10, 5 }, - { 8, 10, 4, 2, 14, 13, 12, 15, 3, 7, 6, 11, 5, 1, 16, 9 }, - { 10, 1, 6, 8, 3, 5, 11, 16, 15, 2, 12, 13, 7, 9, 4, 14 }, - { 3, 13, 7, 11, 1, 12, 9, 4, 5, 14, 8, 6, 16, 15, 2, 10 }, - { 13, 6, 2, 16, 15, 14, 5, 11, 1, 8, 7, 4, 10, 3, 9, 12 }, - { 14, 12, 8, 15, 13, 2, 4, 10, 6, 1, 16, 5, 9, 7, 3, 11 }, - { 7, 16, 15, 10, 12, 4, 1, 9, 13, 3, 14, 8, 2, 5, 11, 6 }, - { 11, 3, 9, 5, 8, 7, 2, 6, 16, 12, 10, 15, 4, 13, 14, 1 }, - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, - { 15, 11, 5, 9, 10, 16, 14, 7, 2, 13, 1, 3, 12, 8, 6, 4 }, - } - - local function compress(h, M, t, isLast) - local V0, V1, V2, V3 = h[1], h[2], h[3], h[4] - local V4, V5, V6, V7 = h[5], h[6], h[7], h[8] - local V8, V9, V10, V11 = IV1, IV2, IV3, IV4 - local V12 = integer.bxor(IV5, t) - local V13 = IV6 - local V14 = if isLast then integer.bxor(IV7, INV_MASK) else IV7 - local V15 = IV8 - - for r = 1, 12 do - local s = SIGMA[r] - - -- column step - V0 = integer.add(integer.add(V0, V4), M[s[1]]) - V12 = integer.rrotate(integer.bxor(V12, V0), 32i) - V8 = integer.add(V8, V12) - V4 = integer.rrotate(integer.bxor(V4, V8), 24i) - V0 = integer.add(integer.add(V0, V4), M[s[2]]) - V12 = integer.rrotate(integer.bxor(V12, V0), 16i) - V8 = integer.add(V8, V12) - V4 = integer.rrotate(integer.bxor(V4, V8), 63i) - - V1 = integer.add(integer.add(V1, V5), M[s[3]]) - V13 = integer.rrotate(integer.bxor(V13, V1), 32i) - V9 = integer.add(V9, V13) - V5 = integer.rrotate(integer.bxor(V5, V9), 24i) - V1 = integer.add(integer.add(V1, V5), M[s[4]]) - V13 = integer.rrotate(integer.bxor(V13, V1), 16i) - V9 = integer.add(V9, V13) - V5 = integer.rrotate(integer.bxor(V5, V9), 63i) - - V2 = integer.add(integer.add(V2, V6), M[s[5]]) - V14 = integer.rrotate(integer.bxor(V14, V2), 32i) - V10 = integer.add(V10, V14) - V6 = integer.rrotate(integer.bxor(V6, V10), 24i) - V2 = integer.add(integer.add(V2, V6), M[s[6]]) - V14 = integer.rrotate(integer.bxor(V14, V2), 16i) - V10 = integer.add(V10, V14) - V6 = integer.rrotate(integer.bxor(V6, V10), 63i) - - V3 = integer.add(integer.add(V3, V7), M[s[7]]) - V15 = integer.rrotate(integer.bxor(V15, V3), 32i) - V11 = integer.add(V11, V15) - V7 = integer.rrotate(integer.bxor(V7, V11), 24i) - V3 = integer.add(integer.add(V3, V7), M[s[8]]) - V15 = integer.rrotate(integer.bxor(V15, V3), 16i) - V11 = integer.add(V11, V15) - V7 = integer.rrotate(integer.bxor(V7, V11), 63i) - - -- diagonal step - V0 = integer.add(integer.add(V0, V5), M[s[9]]) - V15 = integer.rrotate(integer.bxor(V15, V0), 32i) - V10 = integer.add(V10, V15) - V5 = integer.rrotate(integer.bxor(V5, V10), 24i) - V0 = integer.add(integer.add(V0, V5), M[s[10]]) - V15 = integer.rrotate(integer.bxor(V15, V0), 16i) - V10 = integer.add(V10, V15) - V5 = integer.rrotate(integer.bxor(V5, V10), 63i) - - V1 = integer.add(integer.add(V1, V6), M[s[11]]) - V12 = integer.rrotate(integer.bxor(V12, V1), 32i) - V11 = integer.add(V11, V12) - V6 = integer.rrotate(integer.bxor(V6, V11), 24i) - V1 = integer.add(integer.add(V1, V6), M[s[12]]) - V12 = integer.rrotate(integer.bxor(V12, V1), 16i) - V11 = integer.add(V11, V12) - V6 = integer.rrotate(integer.bxor(V6, V11), 63i) - - V2 = integer.add(integer.add(V2, V7), M[s[13]]) - V13 = integer.rrotate(integer.bxor(V13, V2), 32i) - V8 = integer.add(V8, V13) - V7 = integer.rrotate(integer.bxor(V7, V8), 24i) - V2 = integer.add(integer.add(V2, V7), M[s[14]]) - V13 = integer.rrotate(integer.bxor(V13, V2), 16i) - V8 = integer.add(V8, V13) - V7 = integer.rrotate(integer.bxor(V7, V8), 63i) - - V3 = integer.add(integer.add(V3, V4), M[s[15]]) - V14 = integer.rrotate(integer.bxor(V14, V3), 32i) - V9 = integer.add(V9, V14) - V4 = integer.rrotate(integer.bxor(V4, V9), 24i) - V3 = integer.add(integer.add(V3, V4), M[s[16]]) - V14 = integer.rrotate(integer.bxor(V14, V3), 16i) - V9 = integer.add(V9, V14) - V4 = integer.rrotate(integer.bxor(V4, V9), 63i) - end - - h[1] = integer.bxor(integer.bxor(h[1], V0), V8) - h[2] = integer.bxor(integer.bxor(h[2], V1), V9) - h[3] = integer.bxor(integer.bxor(h[3], V2), V10) - h[4] = integer.bxor(integer.bxor(h[4], V3), V11) - h[5] = integer.bxor(integer.bxor(h[5], V4), V12) - h[6] = integer.bxor(integer.bxor(h[6], V5), V13) - h[7] = integer.bxor(integer.bxor(h[7], V6), V14) - h[8] = integer.bxor(integer.bxor(h[8], V7), V15) - end - - local function blake2b(buf) - local len = buffer.len(buf) - - local h = - { - integer.bxor(IV1, 0x01010040i), - IV2, IV3, IV4, IV5, IV6, IV7, IV8, - } - - local M = table.create(16, 0i) - - -- process all full 128-byte blocks except the last - local fullBlocks = (len - 1) // 128 - for blockIdx = 0, fullBlocks - 1 do - local off = blockIdx * 128 - for j = 1, 16 do - M[j] = buffer.readinteger(buf, off + (j - 1) * 8) - end - compress(h, M, integer.create((blockIdx + 1) * 128), false) - end - - -- final block: copy remaining + pad with zeros to 128 bytes - local lastBlockStart = fullBlocks * 128 - local lastBlockLen = len - lastBlockStart - local lastBuf = buffer.create(128) - if lastBlockLen > 0 then - buffer.copy(lastBuf, 0, buf, lastBlockStart, lastBlockLen) - end - for j = 1, 16 do - M[j] = buffer.readinteger(lastBuf, (j - 1) * 8) - end - compress(h, M, integer.create(len), true) - - return string.format( - "%016x%016x%016x%016x%016x%016x%016x%016x", - integer.bswap(h[1]), integer.bswap(h[2]), integer.bswap(h[3]), integer.bswap(h[4]), - integer.bswap(h[5]), integer.bswap(h[6]), integer.bswap(h[7]), integer.bswap(h[8]) - ) - end - - local input = buffer.fromstring(string.rep(".", 1e3)) - - local ts0 = os.clock() - - for i = 1, 100 do - local res = blake2b(input) - assert(res == "b9ac083b18cd6518abaed42698bbb673e9786c877a6ee89efa1c3a6508a54a20ef76f53cbcc19a18a670ea3ac668836300337c51abafca35efaac59f4396c833") - end - - local ts1 = os.clock() - - return ts1 - ts0 -end - -bench.runCode(test, "blake2b_int64") diff --git a/bench/tests/integers/murmur128_int64.lua b/bench/tests/integers/murmur128_int64.lua deleted file mode 100644 index 00b954065..000000000 --- a/bench/tests/integers/murmur128_int64.lua +++ /dev/null @@ -1,97 +0,0 @@ -local function prequire(name) local success, result = pcall(require, name); return success and result end -local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support") - -function test() - - local C1 = 0x87c37b91114253d5i - local C2 = 0x4cf5ad432745937fi - local M5 = 5i - local K1 = 0x52dce729i - local K2 = 0x38495ab5i - local FMIX1 = 0xff51afd7ed558ccdi - local FMIX2 = 0xc4ceb9fe1a85ec53i - - local function fmix64(k) - k = integer.mul(integer.bxor(k, integer.rshift(k, 33i)), FMIX1) - k = integer.mul(integer.bxor(k, integer.rshift(k, 33i)), FMIX2) - return integer.bxor(k, integer.rshift(k, 33i)) - end - - local function murmur3_x64_128(buf, seed) - local len = buffer.len(buf) - local nblocks = len // 16 - - local h1 = seed - local h2 = seed - - for i = 0, nblocks - 1 do - local off = i * 16 - local k1 = buffer.readinteger(buf, off) - local k2 = buffer.readinteger(buf, off + 8) - - k1 = integer.mul(integer.lrotate(integer.mul(k1, C1), 31i), C2) - h1 = integer.bxor(h1, k1) - h1 = integer.add(integer.mul(integer.add(integer.lrotate(h1, 27i), h2), M5), K1) - - k2 = integer.mul(integer.lrotate(integer.mul(k2, C2), 33i), C1) - h2 = integer.bxor(h2, k2) - h2 = integer.add(integer.mul(integer.add(integer.lrotate(h2, 31i), h1), M5), K2) - end - - -- tail (0..15 bytes) - local tailStart = nblocks * 16 - local rem = len - tailStart - if rem > 0 then - local k1 = 0i - local k2 = 0i - - if rem >= 9 then - k1 = buffer.readinteger(buf, tailStart) - for j = 8, rem - 1 do - k2 = integer.bxor(k2, integer.lshift(integer.create(buffer.readu8(buf, tailStart + j)), integer.create((j - 8) * 8))) - end - k2 = integer.mul(integer.lrotate(integer.mul(k2, C2), 33i), C1) - h2 = integer.bxor(h2, k2) - elseif rem == 8 then - k1 = buffer.readinteger(buf, tailStart) - else - for j = 0, rem - 1 do - k1 = integer.bxor(k1, integer.lshift(integer.create(buffer.readu8(buf, tailStart + j)), integer.create(j * 8))) - end - end - - k1 = integer.mul(integer.lrotate(integer.mul(k1, C1), 31i), C2) - h1 = integer.bxor(h1, k1) - end - - h1 = integer.bxor(h1, integer.create(len)) - h2 = integer.bxor(h2, integer.create(len)) - - h1 = integer.add(h1, h2) - h2 = integer.add(h2, h1) - - h1 = fmix64(h1) - h2 = fmix64(h2) - - h1 = integer.add(h1, h2) - h2 = integer.add(h2, h1) - - -- byte-stream hex (little-endian per 64-bit lane) - return string.format("%016x%016x", integer.bswap(h1), integer.bswap(h2)) - end - - local input = buffer.fromstring(string.rep(".", 1e3)) - - local ts0 = os.clock() - - for i = 1, 1500 do - local res = murmur3_x64_128(input, 0i) - assert(res == "d092966966d88531ef6a373f8fbb714f") - end - - local ts1 = os.clock() - - return ts1 - ts0 -end - -bench.runCode(test, "murmur128_int64") diff --git a/bench/tests/integers/pollard_rho_int64.lua b/bench/tests/integers/pollard_rho_int64.lua deleted file mode 100644 index a0222d3f8..000000000 --- a/bench/tests/integers/pollard_rho_int64.lua +++ /dev/null @@ -1,85 +0,0 @@ -local function prequire(name) local success, result = pcall(require, name); return success and result end -local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support") - -function test() - - -- Modular multiplication via double-and-add (binary method). - -- Required because n > 2^31, so x*x can overflow signed int64. - local function mulmod(a: integer, b: integer, m: integer): integer - local result = 0i - a = integer.rem(a, m) - while b ~= 0i do - if integer.band(b, 1i) ~= 0i then - result = integer.rem(integer.add(result, a), m) - end - a = integer.rem(integer.add(a, a), m) - b = integer.rshift(b, 1i) - end - return result - end - - local function absi(x: integer): integer - if integer.lt(x, 0i) then - return integer.neg(x) - end - return x - end - - local function gcd(a: integer, b: integer): integer - while b ~= 0i do - a, b = b, integer.rem(a, b) - end - return a - end - - local function pollard_rho(n: integer): integer - if integer.rem(n, 2i) == 0i then return 2i end - - local c = 1i - while true do - local x = 2i - local y = 2i - local d = 1i - - while d == 1i do - x = integer.rem(integer.add(mulmod(x, x, n), c), n) - y = integer.rem(integer.add(mulmod(y, y, n), c), n) - y = integer.rem(integer.add(mulmod(y, y, n), c), n) - d = gcd(absi(integer.sub(x, y)), n) - end - - if d ~= n then - return d - end - c = integer.add(c, 1i) - end - end - - -- 8 odd semiprimes with n > 2^32, products of two ~10^5 primes. - -- Values are 34-bit, forcing genuine 64-bit arithmetic in mulmod and gcd. - local primes = { - 100003i, 100019i, 100043i, 100049i, 100057i, 100069i, 100103i, 100109i, - 100129i, 100151i, 100153i, 100169i, 100183i, 100189i, 100193i, 100207i, - } - local semiprimes = {} - for i = 1, #primes, 2 do - semiprimes[(i + 1) // 2] = integer.mul(primes[i], primes[i + 1]) - end - - local ts0 = os.clock() - - for iter = 1, 1 do - for i = 1, #semiprimes do - local n = semiprimes[i] - local f = pollard_rho(n) - assert(f ~= 1i and f ~= n) - assert(integer.rem(n, f) == 0i) - end - end - - local ts1 = os.clock() - - return ts1 - ts0 -end - -bench.runCode(test, "pollard_rho_int64") diff --git a/bench/tests/integers/sha3_int64.lua b/bench/tests/integers/sha3_int64.lua deleted file mode 100644 index 9ec4a8903..000000000 --- a/bench/tests/integers/sha3_int64.lua +++ /dev/null @@ -1,162 +0,0 @@ -local function prequire(name) local success, result = pcall(require, name); return success and result end -local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support") - -function test() - - local RC = - { - 0x0000000000000001i, 0x0000000000008082i, 0x800000000000808ai, 0x8000000080008000i, - 0x000000000000808bi, 0x0000000080000001i, 0x8000000080008081i, 0x8000000000008009i, - 0x000000000000008ai, 0x0000000000000088i, 0x0000000080008009i, 0x000000008000000ai, - 0x000000008000808bi, 0x800000000000008bi, 0x8000000000008089i, 0x8000000000008003i, - 0x8000000000008002i, 0x8000000000000080i, 0x000000000000800ai, 0x800000008000000ai, - 0x8000000080008081i, 0x8000000000008080i, 0x0000000080000001i, 0x8000000080008008i, - } - - local function sha3_256(msg) - -- pad10*1 with SHA-3 domain separator 0x06 - local msgLen = #msg - local rateBytes = 136 - - local pad = rateBytes - (msgLen % rateBytes) - local paddedLen = msgLen + pad - - local buf = buffer.create(paddedLen) - buffer.writestring(buf, 0, msg) - if pad == 1 then - buffer.writeu8(buf, msgLen, 0x86) - else - buffer.writeu8(buf, msgLen, 0x06) - buffer.writeu8(buf, paddedLen - 1, 0x80) - end - - -- 25-lane state (S), little-endian interpretation - local S00, S10, S20, S30, S40 = 0i, 0i, 0i, 0i, 0i - local S01, S11, S21, S31, S41 = 0i, 0i, 0i, 0i, 0i - local S02, S12, S22, S32, S42 = 0i, 0i, 0i, 0i, 0i - local S03, S13, S23, S33, S43 = 0i, 0i, 0i, 0i, 0i - local S04, S14, S24, S34, S44 = 0i, 0i, 0i, 0i, 0i - - for blockOffset = 0, paddedLen - 1, rateBytes do - -- absorb 17 lanes (136 bytes) of message - S00 = integer.bxor(S00, buffer.readinteger(buf, blockOffset)) - S10 = integer.bxor(S10, buffer.readinteger(buf, blockOffset + 8)) - S20 = integer.bxor(S20, buffer.readinteger(buf, blockOffset + 16)) - S30 = integer.bxor(S30, buffer.readinteger(buf, blockOffset + 24)) - S40 = integer.bxor(S40, buffer.readinteger(buf, blockOffset + 32)) - S01 = integer.bxor(S01, buffer.readinteger(buf, blockOffset + 40)) - S11 = integer.bxor(S11, buffer.readinteger(buf, blockOffset + 48)) - S21 = integer.bxor(S21, buffer.readinteger(buf, blockOffset + 56)) - S31 = integer.bxor(S31, buffer.readinteger(buf, blockOffset + 64)) - S41 = integer.bxor(S41, buffer.readinteger(buf, blockOffset + 72)) - S02 = integer.bxor(S02, buffer.readinteger(buf, blockOffset + 80)) - S12 = integer.bxor(S12, buffer.readinteger(buf, blockOffset + 88)) - S22 = integer.bxor(S22, buffer.readinteger(buf, blockOffset + 96)) - S32 = integer.bxor(S32, buffer.readinteger(buf, blockOffset + 104)) - S42 = integer.bxor(S42, buffer.readinteger(buf, blockOffset + 112)) - S03 = integer.bxor(S03, buffer.readinteger(buf, blockOffset + 120)) - S13 = integer.bxor(S13, buffer.readinteger(buf, blockOffset + 128)) - - for round = 1, 24 do - -- THETA - local C0 = integer.bxor(S00, S01, S02, S03, S04) - local C1 = integer.bxor(S10, S11, S12, S13, S14) - local C2 = integer.bxor(S20, S21, S22, S23, S24) - local C3 = integer.bxor(S30, S31, S32, S33, S34) - local C4 = integer.bxor(S40, S41, S42, S43, S44) - - local D0 = integer.bxor(C4, integer.lrotate(C1, 1i)) - local D1 = integer.bxor(C0, integer.lrotate(C2, 1i)) - local D2 = integer.bxor(C1, integer.lrotate(C3, 1i)) - local D3 = integer.bxor(C2, integer.lrotate(C4, 1i)) - local D4 = integer.bxor(C3, integer.lrotate(C0, 1i)) - - -- RHO + PI: B[X,Y] = ROT(S[(3Y+X) mod 5, X] XOR D[(3Y+X) mod 5], r[..]) - local B00 = integer.bxor(S00, D0) - local B10 = integer.lrotate(integer.bxor(S11, D1), 44i) - local B20 = integer.lrotate(integer.bxor(S22, D2), 43i) - local B30 = integer.lrotate(integer.bxor(S33, D3), 21i) - local B40 = integer.lrotate(integer.bxor(S44, D4), 14i) - - local B01 = integer.lrotate(integer.bxor(S30, D3), 28i) - local B11 = integer.lrotate(integer.bxor(S41, D4), 20i) - local B21 = integer.lrotate(integer.bxor(S02, D0), 3i) - local B31 = integer.lrotate(integer.bxor(S13, D1), 45i) - local B41 = integer.lrotate(integer.bxor(S24, D2), 61i) - - local B02 = integer.lrotate(integer.bxor(S10, D1), 1i) - local B12 = integer.lrotate(integer.bxor(S21, D2), 6i) - local B22 = integer.lrotate(integer.bxor(S32, D3), 25i) - local B32 = integer.lrotate(integer.bxor(S43, D4), 8i) - local B42 = integer.lrotate(integer.bxor(S04, D0), 18i) - - local B03 = integer.lrotate(integer.bxor(S40, D4), 27i) - local B13 = integer.lrotate(integer.bxor(S01, D0), 36i) - local B23 = integer.lrotate(integer.bxor(S12, D1), 10i) - local B33 = integer.lrotate(integer.bxor(S23, D2), 15i) - local B43 = integer.lrotate(integer.bxor(S34, D3), 56i) - - local B04 = integer.lrotate(integer.bxor(S20, D2), 62i) - local B14 = integer.lrotate(integer.bxor(S31, D3), 55i) - local B24 = integer.lrotate(integer.bxor(S42, D4), 39i) - local B34 = integer.lrotate(integer.bxor(S03, D0), 41i) - local B44 = integer.lrotate(integer.bxor(S14, D1), 2i) - - -- CHI - S00 = integer.bxor(B00, integer.band(integer.bnot(B10), B20)) - S10 = integer.bxor(B10, integer.band(integer.bnot(B20), B30)) - S20 = integer.bxor(B20, integer.band(integer.bnot(B30), B40)) - S30 = integer.bxor(B30, integer.band(integer.bnot(B40), B00)) - S40 = integer.bxor(B40, integer.band(integer.bnot(B00), B10)) - - S01 = integer.bxor(B01, integer.band(integer.bnot(B11), B21)) - S11 = integer.bxor(B11, integer.band(integer.bnot(B21), B31)) - S21 = integer.bxor(B21, integer.band(integer.bnot(B31), B41)) - S31 = integer.bxor(B31, integer.band(integer.bnot(B41), B01)) - S41 = integer.bxor(B41, integer.band(integer.bnot(B01), B11)) - - S02 = integer.bxor(B02, integer.band(integer.bnot(B12), B22)) - S12 = integer.bxor(B12, integer.band(integer.bnot(B22), B32)) - S22 = integer.bxor(B22, integer.band(integer.bnot(B32), B42)) - S32 = integer.bxor(B32, integer.band(integer.bnot(B42), B02)) - S42 = integer.bxor(B42, integer.band(integer.bnot(B02), B12)) - - S03 = integer.bxor(B03, integer.band(integer.bnot(B13), B23)) - S13 = integer.bxor(B13, integer.band(integer.bnot(B23), B33)) - S23 = integer.bxor(B23, integer.band(integer.bnot(B33), B43)) - S33 = integer.bxor(B33, integer.band(integer.bnot(B43), B03)) - S43 = integer.bxor(B43, integer.band(integer.bnot(B03), B13)) - - S04 = integer.bxor(B04, integer.band(integer.bnot(B14), B24)) - S14 = integer.bxor(B14, integer.band(integer.bnot(B24), B34)) - S24 = integer.bxor(B24, integer.band(integer.bnot(B34), B44)) - S34 = integer.bxor(B34, integer.band(integer.bnot(B44), B04)) - S44 = integer.bxor(B44, integer.band(integer.bnot(B04), B14)) - - -- IOTA - S00 = integer.bxor(S00, RC[round]) - end - end - - -- squeeze 32 bytes (first 4 lanes, little-endian bytes -> hex via bswap) - return string.format( - "%016x%016x%016x%016x", - integer.bswap(S00), integer.bswap(S10), integer.bswap(S20), integer.bswap(S30) - ) - end - - local input = string.rep(".", 1e3) - - local ts0 = os.clock() - - for i = 1, 100 do - local res = sha3_256(input) - assert(res == "778f41ec28c470b1947cf8785207ca0e5829b3b04966283c93cd2f2cd37c831c") - end - - local ts1 = os.clock() - - return ts1 - ts0 -end - -bench.runCode(test, "sha3_256_int64") diff --git a/bench/tests/integers/sha512_int64.lua b/bench/tests/integers/sha512_int64.lua deleted file mode 100644 index 15114c42d..000000000 --- a/bench/tests/integers/sha512_int64.lua +++ /dev/null @@ -1,136 +0,0 @@ -local function prequire(name) local success, result = pcall(require, name); return success and result end -local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support") - -function test() - - local primes = - { - 0x428a2f98d728ae22i, 0x7137449123ef65cdi, 0xb5c0fbcfec4d3b2fi, 0xe9b5dba58189dbbci, - 0x3956c25bf348b538i, 0x59f111f1b605d019i, 0x923f82a4af194f9bi, 0xab1c5ed5da6d8118i, - 0xd807aa98a3030242i, 0x12835b0145706fbei, 0x243185be4ee4b28ci, 0x550c7dc3d5ffb4e2i, - 0x72be5d74f27b896fi, 0x80deb1fe3b1696b1i, 0x9bdc06a725c71235i, 0xc19bf174cf692694i, - 0xe49b69c19ef14ad2i, 0xefbe4786384f25e3i, 0x0fc19dc68b8cd5b5i, 0x240ca1cc77ac9c65i, - 0x2de92c6f592b0275i, 0x4a7484aa6ea6e483i, 0x5cb0a9dcbd41fbd4i, 0x76f988da831153b5i, - 0x983e5152ee66dfabi, 0xa831c66d2db43210i, 0xb00327c898fb213fi, 0xbf597fc7beef0ee4i, - 0xc6e00bf33da88fc2i, 0xd5a79147930aa725i, 0x06ca6351e003826fi, 0x142929670a0e6e70i, - 0x27b70a8546d22ffci, 0x2e1b21385c26c926i, 0x4d2c6dfc5ac42aedi, 0x53380d139d95b3dfi, - 0x650a73548baf63dei, 0x766a0abb3c77b2a8i, 0x81c2c92e47edaee6i, 0x92722c851482353bi, - 0xa2bfe8a14cf10364i, 0xa81a664bbc423001i, 0xc24b8b70d0f89791i, 0xc76c51a30654be30i, - 0xd192e819d6ef5218i, 0xd69906245565a910i, 0xf40e35855771202ai, 0x106aa07032bbd1b8i, - 0x19a4c116b8d2d0c8i, 0x1e376c085141ab53i, 0x2748774cdf8eeb99i, 0x34b0bcb5e19b48a8i, - 0x391c0cb3c5c95a63i, 0x4ed8aa4ae3418acbi, 0x5b9cca4f7763e373i, 0x682e6ff3d6b2b8a3i, - 0x748f82ee5defb2fci, 0x78a5636f43172f60i, 0x84c87814a1f0ab72i, 0x8cc702081a6439eci, - 0x90befffa23631e28i, 0xa4506cebde82bde9i, 0xbef9a3f7b2c67915i, 0xc67178f2e372532bi, - 0xca273eceea26619ci, 0xd186b8c721c0c207i, 0xeada7dd6cde0eb1ei, 0xf57d4f7fee6ed178i, - 0x06f067aa72176fbai, 0x0a637dc5a2c898a6i, 0x113f9804bef90daei, 0x1b710b35131c471bi, - 0x28db77f523047d84i, 0x32caab7b40c72493i, 0x3c9ebe0a15c9bebci, 0x431d67c49c100d4ci, - 0x4cc5d4becb3e42b6i, 0x597f299cfc657e2ai, 0x5fcb6fab3ad6faeci, 0x6c44198c4a475817i, - } - - local function toHex(buf) - return string.format( - "%016x%016x%016x%016x%016x%016x%016x%016x", - buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8] - ) - end - - local function preprocess(msg) - local msgLen = #msg - local extra = 128 - ((msgLen + 17) % 128) - - local padded = msg .. '\128' .. string.rep('\0', extra + 8) - local paddedLen = #padded + 8 - - local buf = buffer.create(paddedLen) - buffer.writestring(buf, 0, padded) - - -- length goes in the low 8 bytes (high 8 bytes left as zero, fits since msgLen*8 < 2^64) - local bitLen = msgLen * 8 - for i = 0, 7 do - local rem = bitLen % 256 - buffer.writeu8(buf, paddedLen - 1 - i, rem) - bitLen = (bitLen - rem) / 256 - end - - return buf, paddedLen - end - - local function digestBlock(buf, i, hash, digest) - for j = 1, 16 do - local offset = i + (j - 1) * 8 - digest[j] = integer.bswap(buffer.readinteger(buf, offset)) - end - - for j = 17, 80 do - local v = digest[j - 15] - local s0 = integer.bxor(integer.rrotate(v, 1i), integer.rrotate(v, 8i), integer.rshift(v, 7i)) - - v = digest[j - 2] - local s1 = integer.bxor(integer.rrotate(v, 19i), integer.rrotate(v, 61i), integer.rshift(v, 6i)) - - digest[j] = integer.add(integer.add(digest[j - 16], s0), integer.add(digest[j - 7], s1)) - end - - local a, b, c, d, e, f, g, h = table.unpack(hash) - - for r = 1, 80 do - local s0 = integer.bxor(integer.rrotate(a, 28i), integer.rrotate(a, 34i), integer.rrotate(a, 39i)) - local maj = integer.bxor(integer.band(a, b), integer.band(a, c), integer.band(b, c)) - local t2 = integer.add(s0, maj) - - local s1 = integer.bxor(integer.rrotate(e, 14i), integer.rrotate(e, 18i), integer.rrotate(e, 41i)) - local ch = integer.bxor(integer.band(e, f), integer.band(integer.bnot(e), g)) - local t1 = integer.add(integer.add(integer.add(h, s1), ch), integer.add(primes[r], digest[r])) - - h, g, f, e, d, c, b, a = g, f, e, integer.add(d, t1), c, b, a, integer.add(t1, t2) - end - - hash[1] = integer.add(hash[1], a) - hash[2] = integer.add(hash[2], b) - hash[3] = integer.add(hash[3], c) - hash[4] = integer.add(hash[4], d) - hash[5] = integer.add(hash[5], e) - hash[6] = integer.add(hash[6], f) - hash[7] = integer.add(hash[7], g) - hash[8] = integer.add(hash[8], h) - end - - local function sha512(msg) - local buf, paddedLen = preprocess(msg) - - local hash = - { - 0x6a09e667f3bcc908i, - 0xbb67ae8584caa73bi, - 0x3c6ef372fe94f82bi, - 0xa54ff53a5f1d36f1i, - 0x510e527fade682d1i, - 0x9b05688c2b3e6c1fi, - 0x1f83d9abfb41bd6bi, - 0x5be0cd19137e2179i, - } - - local digest = {} - - for i = 0, paddedLen - 1, 128 do - digestBlock(buf, i, hash, digest) - end - - return toHex(hash) - end - - local input = string.rep(".", 1e3) - - local ts0 = os.clock() - - for i = 1, 100 do - local res = sha512(input) - assert(res == "a17d627e7c3f79207e8ca630348c2e15b70206f88905167dbbc18fd8d2b2806f2ad757c781dfbdc6a0caf1c84a8615bfdbda58f0356543bd00e646a45ca83790") - end - - local ts1 = os.clock() - - return ts1 - ts0 -end - -bench.runCode(test, "sha512_int64") diff --git a/bench/tests/integers/xxh64_bit32.lua b/bench/tests/integers/xxh64_bit32.lua index decab15db..ad1b883be 100644 --- a/bench/tests/integers/xxh64_bit32.lua +++ b/bench/tests/integers/xxh64_bit32.lua @@ -101,7 +101,7 @@ function test() local a4h, a4l = sub64(seedh, seedl, P1h, P1l) while offset <= len - 32 do - -- read64: hi = readu32(off+4), lo = readu32(off) (both LE, matching readinteger) + -- read64: hi = readu32(off+4), lo = readu32(off) (both LE) a1h, a1l = round(a1h, a1l, buffer.readu32(buf, offset + 4), buffer.readu32(buf, offset)) a2h, a2l = round(a2h, a2l, buffer.readu32(buf, offset + 12), buffer.readu32(buf, offset + 8)) a3h, a3l = round(a3h, a3l, buffer.readu32(buf, offset + 20), buffer.readu32(buf, offset + 16)) diff --git a/bench/tests/integers/xxh64_int64.lua b/bench/tests/integers/xxh64_int64.lua deleted file mode 100644 index b46a4e527..000000000 --- a/bench/tests/integers/xxh64_int64.lua +++ /dev/null @@ -1,96 +0,0 @@ -local function prequire(name) local success, result = pcall(require, name); return success and result end -local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support") - -function test() - - local PRIME64_1 = 0x9E3779B185EBCA87i - local PRIME64_2 = 0xC2B2AE3D27D4EB4Fi - local PRIME64_3 = 0x165667B19E3779F9i - local PRIME64_4 = 0x85EBCA77C2B2AE63i - local PRIME64_5 = 0x27D4EB2F165667C5i - - local function xxh64(buf, seed) - local len = buffer.len(buf) - local offset = 0 - local hash - - if len >= 32 then - local a1 = integer.add(integer.add(seed, PRIME64_1), PRIME64_2) - local a2 = integer.add(seed, PRIME64_2) - local a3 = seed - local a4 = integer.sub(seed, PRIME64_1) - - while offset <= len - 32 do - local lane1 = buffer.readinteger(buf, offset) - local lane2 = buffer.readinteger(buf, offset + 8) - local lane3 = buffer.readinteger(buf, offset + 16) - local lane4 = buffer.readinteger(buf, offset + 24) - - a1 = integer.mul(integer.lrotate(integer.add(a1, integer.mul(lane1, PRIME64_2)), 31i), PRIME64_1) - a2 = integer.mul(integer.lrotate(integer.add(a2, integer.mul(lane2, PRIME64_2)), 31i), PRIME64_1) - a3 = integer.mul(integer.lrotate(integer.add(a3, integer.mul(lane3, PRIME64_2)), 31i), PRIME64_1) - a4 = integer.mul(integer.lrotate(integer.add(a4, integer.mul(lane4, PRIME64_2)), 31i), PRIME64_1) - - offset += 32 - end - - hash = integer.add(integer.add(integer.lrotate(a1, 1i), integer.lrotate(a2, 7i)), integer.add(integer.lrotate(a3, 12i), integer.lrotate(a4, 18i))) - - local r1 = integer.mul(integer.lrotate(integer.mul(a1, PRIME64_2), 31i), PRIME64_1) - hash = integer.add(integer.mul(integer.bxor(hash, r1), PRIME64_1), PRIME64_4) - local r2 = integer.mul(integer.lrotate(integer.mul(a2, PRIME64_2), 31i), PRIME64_1) - hash = integer.add(integer.mul(integer.bxor(hash, r2), PRIME64_1), PRIME64_4) - local r3 = integer.mul(integer.lrotate(integer.mul(a3, PRIME64_2), 31i), PRIME64_1) - hash = integer.add(integer.mul(integer.bxor(hash, r3), PRIME64_1), PRIME64_4) - local r4 = integer.mul(integer.lrotate(integer.mul(a4, PRIME64_2), 31i), PRIME64_1) - hash = integer.add(integer.mul(integer.bxor(hash, r4), PRIME64_1), PRIME64_4) - else - hash = integer.add(seed, PRIME64_5) - end - - hash = integer.add(hash, integer.create(len)) - - while offset <= len - 8 do - local lane = buffer.readinteger(buf, offset) - local r = integer.mul(integer.lrotate(integer.mul(lane, PRIME64_2), 31i), PRIME64_1) - hash = integer.add(integer.mul(integer.lrotate(integer.bxor(hash, r), 27i), PRIME64_1), PRIME64_4) - offset += 8 - end - - if offset <= len - 4 then - local lane = integer.create(buffer.readu32(buf, offset)) - hash = integer.add(integer.mul(integer.lrotate(integer.bxor(hash, integer.mul(lane, PRIME64_1)), 23i), PRIME64_2), PRIME64_3) - offset += 4 - end - - while offset < len do - local b = integer.create(buffer.readu8(buf, offset)) - hash = integer.mul(integer.lrotate(integer.bxor(hash, integer.mul(b, PRIME64_5)), 11i), PRIME64_1) - offset += 1 - end - - -- avalanche - hash = integer.bxor(hash, integer.rshift(hash, 33i)) - hash = integer.mul(hash, PRIME64_2) - hash = integer.bxor(hash, integer.rshift(hash, 29i)) - hash = integer.mul(hash, PRIME64_3) - hash = integer.bxor(hash, integer.rshift(hash, 32i)) - - return string.format("%016x", hash) - end - - local input = buffer.fromstring(string.rep(".", 1e3)) - - local ts0 = os.clock() - - for i = 1, 2500 do - local res = xxh64(input, 0i) - assert(res == "1d27c09e95a70d9e") - end - - local ts1 = os.clock() - - return ts1 - ts0 -end - -bench.runCode(test, "xxh64_int64") diff --git a/bench/tests/vibemark67/stinky/cpu.lua b/bench/tests/vibemark67/stinky/cpu.lua index 71627fef9..158b1c67f 100644 --- a/bench/tests/vibemark67/stinky/cpu.lua +++ b/bench/tests/vibemark67/stinky/cpu.lua @@ -5,6 +5,7 @@ -- SP or XZR depending on the instruction. local Int = require("./integer") +type integer = Int.Int64 local Memory = require("./memory") local CPU = {} diff --git a/bench/tests/vibemark67/stinky/decode.lua b/bench/tests/vibemark67/stinky/decode.lua index 1e28c2292..f6912fc58 100644 --- a/bench/tests/vibemark67/stinky/decode.lua +++ b/bench/tests/vibemark67/stinky/decode.lua @@ -4,6 +4,7 @@ -- Decodes 32-bit instruction words and executes them on the CPU state. local Int = require("./integer") +type integer = Int.Int64 local CPU = require("./cpu") local Syscall = require("./syscall") @@ -152,11 +153,12 @@ local fpBuf = buffer.create(8) local function f64ToInt(val: number): integer buffer.writef64(fpBuf, 0, val) - return buffer.readinteger(fpBuf, 0, 8) + return Int.fromWords(buffer.readu32(fpBuf, 0), buffer.readu32(fpBuf, 4)) end local function intToF64(bits: integer): number - buffer.writeinteger(fpBuf, 0, bits, 8) + buffer.writeu32(fpBuf, 0, bits.lo) + buffer.writeu32(fpBuf, 4, bits.hi) return buffer.readf64(fpBuf, 0) end @@ -1433,7 +1435,7 @@ function Decode.execSimdThreeSame(cpu: CPU.CPU, insn: number, pc: integer) -- CMEQ (register): U=1, opcode=0x11 if u == 1 and opcode5 == 0x11 then Decode.simdBinOp(cpu, insn, function(a, b, bits) - return if a == b then Int.sub(Int.shl(Int.ONE, bits), Int.ONE) else Int.ZERO + return if Int.eq(a, b) then Int.sub(Int.shl(Int.ONE, bits), Int.ONE) else Int.ZERO end) return end diff --git a/bench/tests/vibemark67/stinky/elf.lua b/bench/tests/vibemark67/stinky/elf.lua index b9d3c75e3..6e9ace6ba 100644 --- a/bench/tests/vibemark67/stinky/elf.lua +++ b/bench/tests/vibemark67/stinky/elf.lua @@ -4,6 +4,7 @@ -- Parses the ELF header and program headers, loads PT_LOAD segments into memory. local Int = require("./integer") +type integer = Int.Int64 local MemMod = require("./memory") local ELF = {} diff --git a/bench/tests/vibemark67/stinky/emu.lua b/bench/tests/vibemark67/stinky/emu.lua index a639ea623..17ec44579 100644 --- a/bench/tests/vibemark67/stinky/emu.lua +++ b/bench/tests/vibemark67/stinky/emu.lua @@ -4,6 +4,7 @@ -- Takes an ELF binary (as a string), argv, and an output callback, then runs the program. local Int = require("./integer") +type integer = Int.Int64 local MemMod = require("./memory") local CPU = require("./cpu") local ELF = require("./elf") diff --git a/bench/tests/vibemark67/stinky/integer.lua b/bench/tests/vibemark67/stinky/integer.lua index 2a2e560ae..c44bc58d5 100644 --- a/bench/tests/vibemark67/stinky/integer.lua +++ b/bench/tests/vibemark67/stinky/integer.lua @@ -1,279 +1,285 @@ --!strict --- Convenience wrappers around the global `integer` module so the rest of the --- emulator can do 64-bit arithmetic without repeating boilerplate. - -local i = integer - +-- Immutable register bit patterns, stored as unsigned low/high 32-bit words. +-- Only conversion to/from numbers can lose precision above 2^53. +export type Int64 = { lo: number, hi: number } + +local WORD = 0x100000000 +local HALF = 0x10000 +local SIGN = 0x80000000 +local ZERO: Int64 = { lo = 0, hi = 0 } +local ONE: Int64 = { lo = 1, hi = 0 } +local NEG_ONE: Int64 = { lo = WORD - 1, hi = WORD - 1 } local M = {} -M.ZERO = i.create(0) -M.ONE = i.create(1) -M.NEG_ONE = i.neg(i.create(1)) -M.MAX_U64 = M.NEG_ONE -- 0xFFFFFFFFFFFFFFFF as bits -M.MASK32 = i.fromstring("FFFFFFFF", 16) -M.MASK16 = i.create(0xFFFF) -M.MASK8 = i.create(0xFF) +-- Inputs are unsigned 32-bit words; callers must not mutate the returned value. +function M.fromWords(lo: number, hi: number): Int64 + if lo == 0 and hi == 0 then return ZERO end + return { lo = lo, hi = hi } +end + +M.ZERO = ZERO +M.ONE = ONE +M.NEG_ONE = NEG_ONE +M.MAX_U64 = NEG_ONE +M.MASK32 = M.fromWords(WORD - 1, 0) +M.MASK16 = M.fromWords(HALF - 1, 0) +M.MASK8 = M.fromWords(0xFF, 0) -function M.from(n: number): integer - return i.create(n) +function M.from(n: number): Int64 + assert(n == math.floor(n) and n > -math.huge and n < math.huge, "Expected an integral number") + return M.fromWords(n % WORD, math.floor(n / WORD) % WORD) end -function M.fromHex(s: string): integer - return i.fromstring(s, 16) +function M.fromHex(s: string): Int64 + assert(#s > 0 and #s <= 16 and string.match(s, "^[%da-fA-F]+$"), "Expected a 64-bit hex bit pattern") + local split = math.max(0, #s - 8) + local hi = if split == 0 then 0 else (tonumber(string.sub(s, 1, split), 16) :: number) + local lo = tonumber(string.sub(s, split + 1), 16) :: number + return M.fromWords(lo, hi) end -function M.toNumber(x: integer): number - return i.tonumber(x) +function M.toNumber(x: Int64): number + local hi = if x.hi >= SIGN then x.hi - WORD else x.hi + return hi * WORD + x.lo end -function M.add(a: integer, b: integer): integer - return i.add(a, b) +function M.add(a: Int64, b: Int64): Int64 + local lo = a.lo + b.lo + return M.fromWords(lo % WORD, (a.hi + b.hi + math.floor(lo / WORD)) % WORD) end -function M.sub(a: integer, b: integer): integer - return i.sub(a, b) +function M.sub(a: Int64, b: Int64): Int64 + local lo = a.lo - b.lo + return M.fromWords(lo % WORD, (a.hi - b.hi - (if lo < 0 then 1 else 0)) % WORD) end -function M.mul(a: integer, b: integer): integer - return i.mul(a, b) +function M.neg(a: Int64): Int64 + return M.sub(ZERO, a) end -function M.neg(a: integer): integer - return i.neg(a) +-- Schoolbook multiplication in base 2^16 keeps every intermediate exact in a double. +local function mul32(a: number, b: number): (number, number) + local a0, a1 = a % HALF, math.floor(a / HALF) + local b0, b1 = b % HALF, math.floor(b / HALF) + local low = a0 * b0 + local middle = a1 * b0 + a0 * b1 + math.floor(low / HALF) + return low % HALF + (middle % HALF) * HALF, a1 * b1 + math.floor(middle / HALF) end -function M.band(a: integer, b: integer): integer - return i.band(a, b) +function M.mul(a: Int64, b: Int64): Int64 + local lo, hi = mul32(a.lo, b.lo) + local cross1 = mul32(a.lo, b.hi) + local cross2 = mul32(a.hi, b.lo) + return M.fromWords(lo, (hi + cross1 + cross2) % WORD) end -function M.bor(a: integer, b: integer): integer - return i.bor(a, b) +function M.umulh(a: Int64, b: Int64): Int64 + local _, llHi = mul32(a.lo, b.lo) + local lhLo, lhHi = mul32(a.lo, b.hi) + local hlLo, hlHi = mul32(a.hi, b.lo) + local hhLo, hhHi = mul32(a.hi, b.hi) + local middle = llHi + lhLo + hlLo + local high = hhLo + lhHi + hlHi + math.floor(middle / WORD) + return M.fromWords(high % WORD, (hhHi + math.floor(high / WORD)) % WORD) end -function M.bxor(a: integer, b: integer): integer - return i.bxor(a, b) +function M.smulh(a: Int64, b: Int64): Int64 + local high = M.umulh(a, b) + if a.hi >= SIGN then high = M.sub(high, b) end + if b.hi >= SIGN then high = M.sub(high, a) end + return high end -function M.bnot(a: integer): integer - return i.bnot(a) +function M.band(a: Int64, b: Int64): Int64 + return M.fromWords(bit32.band(a.lo, b.lo), bit32.band(a.hi, b.hi)) end -function M.lshift(a: integer, n: integer): integer - return i.lshift(a, n) +function M.bor(a: Int64, b: Int64): Int64 + return M.fromWords(bit32.bor(a.lo, b.lo), bit32.bor(a.hi, b.hi)) end -function M.rshift(a: integer, n: integer): integer - return i.rshift(a, n) +function M.bxor(a: Int64, b: Int64): Int64 + return M.fromWords(bit32.bxor(a.lo, b.lo), bit32.bxor(a.hi, b.hi)) end -function M.arshift(a: integer, n: integer): integer - return i.arshift(a, n) +function M.bnot(a: Int64): Int64 + return M.fromWords(bit32.bnot(a.lo), bit32.bnot(a.hi)) end --- Shift by a number (converts to integer internally) -function M.shl(a: integer, n: number): integer - return i.lshift(a, i.create(n)) +function M.shl(a: Int64, n: number): Int64 + if n < 0 then return M.shr(a, -n) end + if n >= 64 then return ZERO end + if n == 0 then return a end + if n >= 32 then return M.fromWords(0, bit32.lshift(a.lo, n - 32)) end + return M.fromWords(bit32.lshift(a.lo, n), bit32.bor(bit32.lshift(a.hi, n), bit32.rshift(a.lo, 32 - n))) end -function M.shr(a: integer, n: number): integer - return i.rshift(a, i.create(n)) +function M.shr(a: Int64, n: number): Int64 + if n < 0 then return M.shl(a, -n) end + if n >= 64 then return ZERO end + if n == 0 then return a end + if n >= 32 then return M.fromWords(bit32.rshift(a.hi, n - 32), 0) end + return M.fromWords(bit32.bor(bit32.rshift(a.lo, n), bit32.lshift(a.hi, 32 - n)), bit32.rshift(a.hi, n)) end -function M.sar(a: integer, n: number): integer - return i.arshift(a, i.create(n)) +function M.sar(a: Int64, n: number): Int64 + if n < 0 then return M.shl(a, -n) end + local sign = if a.hi >= SIGN then WORD - 1 else 0 + if n >= 64 then return M.fromWords(sign, sign) end + if n == 0 then return a end + if n >= 32 then return M.fromWords(bit32.arshift(a.hi, n - 32), sign) end + return M.fromWords(bit32.bor(bit32.rshift(a.lo, n), bit32.lshift(a.hi, 32 - n)), bit32.arshift(a.hi, n)) end -function M.eq(a: integer, b: integer): boolean - return a == b +function M.lshift(a: Int64, n: Int64): Int64 + return M.shl(a, M.toNumber(n)) end -function M.lt(a: integer, b: integer): boolean - return i.lt(a, b) +function M.rshift(a: Int64, n: Int64): Int64 + return M.shr(a, M.toNumber(n)) end -function M.le(a: integer, b: integer): boolean - return i.le(a, b) +function M.arshift(a: Int64, n: Int64): Int64 + return M.sar(a, M.toNumber(n)) end -function M.gt(a: integer, b: integer): boolean - return i.gt(a, b) +function M.eq(a: Int64, b: Int64): boolean + return a.hi == b.hi and a.lo == b.lo end -function M.ge(a: integer, b: integer): boolean - return i.ge(a, b) +function M.ult(a: Int64, b: Int64): boolean + return a.hi < b.hi or (a.hi == b.hi and a.lo < b.lo) end -function M.ult(a: integer, b: integer): boolean - return i.ult(a, b) +function M.ule(a: Int64, b: Int64): boolean + return not M.ult(b, a) end -function M.ule(a: integer, b: integer): boolean - return i.ule(a, b) +function M.ugt(a: Int64, b: Int64): boolean + return M.ult(b, a) end -function M.ugt(a: integer, b: integer): boolean - return i.ugt(a, b) +function M.uge(a: Int64, b: Int64): boolean + return not M.ult(a, b) end -function M.uge(a: integer, b: integer): boolean - return i.uge(a, b) +function M.lt(a: Int64, b: Int64): boolean + if (a.hi >= SIGN) ~= (b.hi >= SIGN) then return a.hi >= SIGN end + return M.ult(a, b) end -function M.udiv(a: integer, b: integer): integer - return i.udiv(a, b) +function M.le(a: Int64, b: Int64): boolean + return not M.lt(b, a) end -function M.sdiv(a: integer, b: integer): integer - return i.div(a, b) +function M.gt(a: Int64, b: Int64): boolean + return M.lt(b, a) end -function M.urem(a: integer, b: integer): integer - return i.urem(a, b) +function M.ge(a: Int64, b: Int64): boolean + return not M.lt(a, b) end -function M.srem(a: integer, b: integer): integer - return i.rem(a, b) +function M.isZero(a: Int64): boolean + return a.lo == 0 and a.hi == 0 end --- Sign-extend a value from `bits` width to 64 bits. -function M.signExtend(val: integer, bits: number): integer - local shift = 64 - bits - local shiftI = i.create(shift) - return i.arshift(i.lshift(val, shiftI), shiftI) +function M.isNegative(a: Int64): boolean + return a.hi >= SIGN end --- Zero-extend (mask to `bits` width). -function M.zeroExtend(val: integer, bits: number): integer - if bits >= 64 then return val end - local mask = i.sub(i.lshift(M.ONE, i.create(bits)), M.ONE) - return i.band(val, mask) +-- Unsigned restoring division; carry retains the 65th bit of the shifted remainder. +local function divmod(a: Int64, b: Int64): (Int64, Int64) + assert(not M.isZero(b), "Division by zero") + local qLo, qHi, rLo, rHi = 0, 0, 0, 0 + for index = 63, 0, -1 do + local carry = rHi >= SIGN + local bit = if index >= 32 then bit32.extract(a.hi, index - 32) else bit32.extract(a.lo, index) + rHi = (rHi * 2 + math.floor(rLo / SIGN)) % WORD + rLo = (rLo * 2 + bit) % WORD + if carry or rHi > b.hi or (rHi == b.hi and rLo >= b.lo) then + local low = rLo - b.lo + rHi = (rHi - b.hi - (if low < 0 then 1 else 0)) % WORD + rLo = low % WORD + if index >= 32 then + qHi = bit32.bor(qHi, bit32.lshift(1, index - 32)) + else + qLo = bit32.bor(qLo, bit32.lshift(1, index)) + end + end + end + return M.fromWords(qLo, qHi), M.fromWords(rLo, rHi) end --- Extract bits [hi:lo] inclusive from val. -function M.extractBits(val: integer, lo: number, hi: number): integer - local width = hi - lo + 1 - local shifted = M.shr(val, lo) - return M.zeroExtend(shifted, width) +function M.udiv(a: Int64, b: Int64): Int64 + local quotient = divmod(a, b) + return quotient end --- Count leading zeros (64-bit). -function M.clz64(val: integer): number - return i.tonumber(i.countlz(val)) +function M.urem(a: Int64, b: Int64): Int64 + local _, remainder = divmod(a, b) + return remainder end --- Reverse bits of a 64-bit value. -function M.rbit64(val: integer): integer - local result = M.ZERO - for bit = 0, 63 do - if i.btest(val, i.lshift(M.ONE, i.create(bit))) then - result = i.bor(result, i.lshift(M.ONE, i.create(63 - bit))) - end - end - return result +function M.sdiv(a: Int64, b: Int64): Int64 + local aNegative, bNegative = M.isNegative(a), M.isNegative(b) + local quotient = M.udiv(if aNegative then M.neg(a) else a, if bNegative then M.neg(b) else b) + return if aNegative ~= bNegative then M.neg(quotient) else quotient end --- Reverse bytes of a 64-bit value. -function M.rev64(val: integer): integer - local result = M.ZERO - for byte = 0, 7 do - local b = i.band(i.rshift(val, i.create(byte * 8)), M.MASK8) - result = i.bor(result, i.lshift(b, i.create((7 - byte) * 8))) - end - return result +function M.srem(a: Int64, b: Int64): Int64 + local aNegative, bNegative = M.isNegative(a), M.isNegative(b) + local remainder = M.urem(if aNegative then M.neg(a) else a, if bNegative then M.neg(b) else b) + return if aNegative then M.neg(remainder) else remainder end --- Reverse bytes of lower 32 bits. -function M.rev32(val: integer): integer - local result = M.ZERO - for byte = 0, 3 do - local b = i.band(i.rshift(val, i.create(byte * 8)), M.MASK8) - result = i.bor(result, i.lshift(b, i.create((3 - byte) * 8))) - end - return result -end - --- Reverse bytes in each 16-bit halfword of lower 32 bits. -function M.rev16(val: integer): integer - local b0 = i.band(val, M.MASK8) - local b1 = i.band(i.rshift(val, i.create(8)), M.MASK8) - local b2 = i.band(i.rshift(val, i.create(16)), M.MASK8) - local b3 = i.band(i.rshift(val, i.create(24)), M.MASK8) - return i.bor(i.bor(i.lshift(b0, i.create(8)), b1), - i.bor(i.lshift(b2, i.create(24)), i.lshift(b3, i.create(16)))) -end - -function M.isZero(val: integer): boolean - return val == M.ZERO -end - -function M.isNegative(val: integer): boolean - return i.lt(val, M.ZERO) -end - --- Multiply two 64-bit values and return the high 64 bits (signed). -function M.smulh(a: integer, b: integer): integer - -- Use the integer module's mul which gives low 64 bits. - -- For smulh we need to do it differently. Let's split into 32-bit halves. - local a_neg = M.isNegative(a) - local b_neg = M.isNegative(b) - local abs_a = if a_neg then M.neg(a) else a - local abs_b = if b_neg then M.neg(b) else b - local hi = M.umulh_impl(abs_a, abs_b) - if a_neg ~= b_neg then - -- negate 128-bit result: complement high, and if low != 0, subtract 1 from high - local lo = i.mul(abs_a, abs_b) - hi = i.bnot(hi) - if lo ~= M.ZERO then - hi = i.add(hi, M.ONE) - end - end - return hi +function M.signExtend(val: Int64, bits: number): Int64 + local shift = 64 - bits + return M.sar(M.shl(val, shift), shift) end --- Multiply two 64-bit values and return the high 64 bits (unsigned). -function M.umulh(a: integer, b: integer): integer - return M.umulh_impl(a, b) +function M.zeroExtend(val: Int64, bits: number): Int64 + if bits >= 64 then return val end + if bits <= 32 then return M.fromWords(bit32.band(val.lo, 2 ^ bits - 1), 0) end + return M.fromWords(val.lo, bit32.band(val.hi, 2 ^ (bits - 32) - 1)) end -function M.umulh_impl(a: integer, b: integer): integer - -- Split each into two 32-bit halves and do schoolbook multiplication. - local a_lo = i.band(a, M.MASK32) - local a_hi = i.rshift(a, i.create(32)) - local b_lo = i.band(b, M.MASK32) - local b_hi = i.rshift(b, i.create(32)) +function M.extractBits(val: Int64, lo: number, hi: number): Int64 + return M.zeroExtend(M.shr(val, lo), hi - lo + 1) +end - -- a*b = (a_hi*2^32 + a_lo) * (b_hi*2^32 + b_lo) - -- = a_hi*b_hi*2^64 + (a_hi*b_lo + a_lo*b_hi)*2^32 + a_lo*b_lo - -- We want bits [127:64] +function M.clz64(val: Int64): number + return if val.hi == 0 then 32 + bit32.countlz(val.lo) else bit32.countlz(val.hi) +end - -- Since these are positive and fit in 63 bits each half fits in 32 bits unsigned. - -- But the integer module treats them as signed 64-bit... - -- The products of 32-bit * 32-bit fit in 64 bits unsigned. - -- However integer.mul gives us the low 64 bits which IS the correct product for 32x32. +local function rev32(val: number): number + return bit32.bor(bit32.rshift(val, 24), bit32.band(bit32.rshift(val, 8), 0xFF00), + bit32.band(bit32.lshift(val, 8), 0xFF0000), bit32.lshift(val, 24)) +end - local ll = i.mul(a_lo, b_lo) - local lh = i.mul(a_lo, b_hi) - local hl = i.mul(a_hi, b_lo) - local hh = i.mul(a_hi, b_hi) +local function rbit32(val: number): number + val = bit32.bor(bit32.band(bit32.rshift(val, 1), 0x55555555), bit32.lshift(bit32.band(val, 0x55555555), 1)) + val = bit32.bor(bit32.band(bit32.rshift(val, 2), 0x33333333), bit32.lshift(bit32.band(val, 0x33333333), 2)) + val = bit32.bor(bit32.band(bit32.rshift(val, 4), 0x0F0F0F0F), bit32.lshift(bit32.band(val, 0x0F0F0F0F), 4)) + return rev32(val) +end - -- ll contributes bits [63:0], so ll >> 32 carries into the middle sum - local ll_hi = i.rshift(ll, i.create(32)) +function M.rbit64(val: Int64): Int64 + return M.fromWords(rbit32(val.hi), rbit32(val.lo)) +end - -- middle = lh + hl + ll_hi (but this can overflow 64 bits by at most 1 bit) - local mid = i.add(lh, ll_hi) - -- detect carry: if mid < lh (unsigned), carry occurred - local carry1: integer = if i.ult(mid, lh) then M.ONE else M.ZERO - local mid2 = i.add(mid, hl) - local carry2: integer = if i.ult(mid2, hl) then M.ONE else M.ZERO +function M.rev64(val: Int64): Int64 + return M.fromWords(rev32(val.hi), rev32(val.lo)) +end - -- high = hh + (carry1 + carry2) * 2^32 + mid2 >> 32 - local mid2_hi = i.rshift(mid2, i.create(32)) - local carries = i.add(carry1, carry2) - local result = i.add(hh, mid2_hi) - result = i.add(result, i.lshift(carries, i.create(32))) +function M.rev32(val: Int64): Int64 + return M.fromWords(rev32(val.lo), 0) +end - return result +function M.rev16(val: Int64): Int64 + local low = bit32.bor(bit32.band(bit32.rshift(val.lo, 8), 0x00FF00FF), bit32.lshift(bit32.band(val.lo, 0x00FF00FF), 8)) + return M.fromWords(low, 0) end return M diff --git a/bench/tests/vibemark67/stinky/integer.test.lua b/bench/tests/vibemark67/stinky/integer.test.lua new file mode 100644 index 000000000..2b03267e9 --- /dev/null +++ b/bench/tests/vibemark67/stinky/integer.test.lua @@ -0,0 +1,97 @@ +--!strict + +local Int = require("./integer") +local Memory = require("./memory") +local CPU = require("./cpu") + +local function expect(actual: Int.Int64, hex: string) + local expected = Int.fromHex(hex) + assert(Int.eq(actual, expected), string.format("Expected %s, got %08x%08x", hex, actual.hi, actual.lo)) +end + +local zero = Int.ZERO +local one = Int.ONE +local max = Int.MAX_U64 +local minSigned = Int.fromHex("8000000000000000") +local maxSigned = Int.fromHex("7fffffffffffffff") +local a = Int.fromHex("12345678abcdef01") +local b = Int.fromHex("fedcba9876543210") + +expect(Int.from(-1), "ffffffffffffffff") +expect(Int.from(-0x100000001), "fffffffeffffffff") +assert(Int.toNumber(Int.from(-1)) == -1) +assert(Int.toNumber(Int.from(-0x100000001)) == -0x100000001) +expect(Int.add(max, one), "0000000000000000") +expect(Int.add(maxSigned, one), "8000000000000000") +expect(Int.sub(zero, one), "ffffffffffffffff") +expect(Int.neg(minSigned), "8000000000000000") +expect(Int.mul(max, max), "0000000000000001") +expect(Int.umulh(max, max), "fffffffffffffffe") +expect(Int.mul(a, b), "5fbae76dd7e12210") +expect(Int.umulh(a, b), "121fa00ae87b192d") +expect(Int.smulh(a, b), "ffeb49923cad2a2c") +expect(Int.smulh(minSigned, minSigned), "4000000000000000") +expect(Int.smulh(max, max), "0000000000000000") +expect(Int.smulh(minSigned, one), "ffffffffffffffff") +expect(Int.udiv(b, a), "000000000000000d") +expect(Int.urem(b, a), "12345677bcdf0f03") +expect(Int.udiv(max, Int.fromHex("8000000000000001")), "0000000000000001") +expect(Int.urem(max, Int.fromHex("8000000000000001")), "7ffffffffffffffe") +expect(Int.udiv(max, Int.fromHex("100000001")), "00000000ffffffff") +expect(Int.urem(max, Int.fromHex("100000001")), "0000000000000000") +expect(Int.sdiv(Int.from(-7), Int.from(2)), "fffffffffffffffd") +expect(Int.srem(Int.from(-7), Int.from(2)), "ffffffffffffffff") +expect(Int.sdiv(minSigned, max), "8000000000000000") +assert(not pcall(Int.udiv, one, zero)) + +expect(Int.shl(a, 32), "abcdef0100000000") +expect(Int.shr(a, 32), "0000000012345678") +expect(Int.shl(one, 63), "8000000000000000") +expect(Int.shr(minSigned, 63), "0000000000000001") +expect(Int.sar(minSigned, 63), "ffffffffffffffff") +expect(Int.sar(minSigned, 32), "ffffffff80000000") +expect(Int.sar(minSigned, 31), "ffffffff00000000") +expect(Int.sar(minSigned, 64), "ffffffffffffffff") +expect(Int.shl(one, 64), "0000000000000000") +expect(Int.shr(max, 64), "0000000000000000") +expect(Int.shl(a, -32), "0000000012345678") +expect(Int.sar(one, -63), "8000000000000000") +expect(Int.signExtend(Int.from(0x80), 8), "ffffffffffffff80") +expect(Int.signExtend(Int.from(0x80000000), 32), "ffffffff80000000") +expect(Int.zeroExtend(max, 33), "00000001ffffffff") +expect(Int.zeroExtend(max, 0), "0000000000000000") +expect(Int.extractBits(a, 28, 35), "000000000000008a") +assert(Int.clz64(zero) == 64 and Int.clz64(one) == 63 and Int.clz64(minSigned) == 0) +expect(Int.rbit64(Int.fromHex("0123456789abcdef")), "f7b3d591e6a2c480") +expect(Int.rev64(Int.fromHex("0123456789abcdef")), "efcdab8967452301") +expect(Int.rev32(a), "0000000001efcdab") +expect(Int.rev16(a), "00000000cdab01ef") +assert(Int.lt(minSigned, zero) and Int.gt(maxSigned, max)) +assert(Int.ugt(minSigned, maxSigned) and Int.ult(one, max)) +assert(Int.eq(Int.from(42), Int.from(42))) + +local mem = Memory.new() +for _, offset in { 8, 4092, 4093, 4095 } do + local addr = Int.from(offset) + mem:writeU64(addr, a) + expect(mem:readU64(addr), "12345678abcdef01") + assert(mem:readU8(addr) == 1) + assert(mem:readU32(addr) == 0xabcdef01) + assert(mem:readU32(Int.add(addr, Int.from(4))) == 0x12345678) +end + +local cpu = CPU.new(mem) +expect(cpu:addWithCarry64(max, zero, true), "0000000000000000") +assert(cpu.C and cpu.Z and not cpu.V) +expect(cpu:addWithCarry64(maxSigned, one, false), "8000000000000000") +assert(cpu.N and cpu.V and not cpu.C) +expect(cpu:addWithCarry32(Int.MASK32, zero, true), "0000000000000000") +assert(cpu.C and cpu.Z and not cpu.V) +cpu:writeX(0, a) +cpu:writeW(0, b) +expect(cpu:readX(0), "0000000076543210") +cpu:writeX(31, a) +expect(cpu:readX(31), "0000000000000000") +expect(Int.ZERO, "0000000000000000") + +print("Paired-word arithmetic, CPU flags, and cross-page memory checks passed") diff --git a/bench/tests/vibemark67/stinky/memory.lua b/bench/tests/vibemark67/stinky/memory.lua index 32bc19d8c..89f86fa87 100644 --- a/bench/tests/vibemark67/stinky/memory.lua +++ b/bench/tests/vibemark67/stinky/memory.lua @@ -5,6 +5,7 @@ -- Supports reading/writing 1/2/4/8-byte values at arbitrary addresses. local Int = require("./integer") +type integer = Int.Int64 local PAGE_BITS = 12 local PAGE_SIZE = 4096 @@ -107,7 +108,7 @@ function Memory.readU64(self: Memory, addr: integer): integer local offset = Memory.offsetOf(addr) if offset <= PAGE_SIZE - 8 then local page = self:ensurePage(Memory.pageOf(addr)) - return buffer.readinteger(page, offset, 8) + return Int.fromWords(buffer.readu32(page, offset), buffer.readu32(page, offset + 4)) end -- Crosses page boundary local lo = Int.from(self:readU32(addr)) @@ -148,7 +149,8 @@ function Memory.writeU64(self: Memory, addr: integer, val: integer) local offset = Memory.offsetOf(addr) if offset <= PAGE_SIZE - 8 then local page = self:ensurePage(Memory.pageOf(addr)) - buffer.writeinteger(page, offset, val, 8) + buffer.writeu32(page, offset, val.lo) + buffer.writeu32(page, offset + 4, val.hi) return end local lo = Int.toNumber(Int.band(val, Int.MASK32)) diff --git a/bench/tests/vibemark67/stinky/syscall.lua b/bench/tests/vibemark67/stinky/syscall.lua index e31a94958..265315583 100644 --- a/bench/tests/vibemark67/stinky/syscall.lua +++ b/bench/tests/vibemark67/stinky/syscall.lua @@ -4,6 +4,7 @@ -- Handles the syscalls needed by statically-linked glibc programs. local Int = require("./integer") +type integer = Int.Int64 local CPU = require("./cpu") local Syscall = {} diff --git a/tests/AssemblyBuilderA64.test.cpp b/tests/AssemblyBuilderA64.test.cpp index 2c4b0b726..ad284e7fe 100644 --- a/tests/AssemblyBuilderA64.test.cpp +++ b/tests/AssemblyBuilderA64.test.cpp @@ -427,6 +427,8 @@ TEST_CASE_FIXTURE(AssemblyBuilderA64Fixture, "FPMath") SINGLE_COMPARE(faddp(s29, s28), 0x7E30DB9D); SINGLE_COMPARE(faddp(d29, d28), 0x7E70DB9D); + SINGLE_COMPARE(faddp(q29, q29, q28), 0x6E3CD7BD); + SINGLE_COMPARE(frinta(d1, d2), 0x1E664041); SINGLE_COMPARE(frintm(d1, d2), 0x1E654041); SINGLE_COMPARE(frintp(d1, d2), 0x1E64C041); diff --git a/tests/AstJsonEncoder.test.cpp b/tests/AstJsonEncoder.test.cpp index e2c62ad44..0e89989d2 100644 --- a/tests/AstJsonEncoder.test.cpp +++ b/tests/AstJsonEncoder.test.cpp @@ -69,9 +69,6 @@ TEST_CASE("encode_constants") AstExprConstantNumber positiveInfinity{Location(), INFINITY}; AstExprConstantNumber negativeInfinity{Location(), -INFINITY}; AstExprConstantNumber nan{Location(), NAN}; - AstExprConstantInteger intSmall{Location(), 42}; - AstExprConstantInteger intNeg{Location(), -1}; - AstExprConstantInteger intLarge{Location(), 0x7FFFFFFFFFFFFFFFLL}; char escapeRaw[] = "a\x1d\0\\\"b"; AstExprConstantString needsEscaping{Location(), {escapeRaw, sizeof(escapeRaw) - 1}, AstExprConstantString::QuoteStyle::QuotedSimple}; @@ -89,9 +86,6 @@ TEST_CASE("encode_constants") CHECK_EQ(R"({"type":"AstExprConstantNumber","location":"0,0 - 0,0","value":Infinity})", toJson(&positiveInfinity)); CHECK_EQ(R"({"type":"AstExprConstantNumber","location":"0,0 - 0,0","value":-Infinity})", toJson(&negativeInfinity)); CHECK_EQ(R"({"type":"AstExprConstantNumber","location":"0,0 - 0,0","value":NaN})", toJson(&nan)); - CHECK_EQ(R"({"type":"AstExprConstantInteger","location":"0,0 - 0,0","value":42})", toJson(&intSmall)); - CHECK_EQ(R"({"type":"AstExprConstantInteger","location":"0,0 - 0,0","value":-1})", toJson(&intNeg)); - CHECK_EQ(R"({"type":"AstExprConstantInteger","location":"0,0 - 0,0","value":9223372036854775807})", toJson(&intLarge)); CHECK_EQ("{\"type\":\"AstExprConstantString\",\"location\":\"0,0 - 0,0\",\"value\":\"a\\u001d\\u0000\\\\\\\"b\"}", toJson(&needsEscaping)); CHECK_EQ("{\"type\":\"AstExprConstantString\",\"location\":\"0,0 - 0,0\",\"value\":\"x\\b\\f\\n\\r\\ty\"}", toJson(&hasShorthands)); CHECK_EQ("{\"type\":\"AstExprConstantString\",\"location\":\"0,0 - 0,0\",\"value\":\"e\xc3\xa9\xf0\x9f\x98\x80\"}", toJson(&hasUtf8)); diff --git a/tests/Autocomplete.test.cpp b/tests/Autocomplete.test.cpp index b7221dd90..dae401f18 100644 --- a/tests/Autocomplete.test.cpp +++ b/tests/Autocomplete.test.cpp @@ -5879,9 +5879,10 @@ TEST_CASE_FIXTURE(ACFixture, "class_autocomplete_classname_inside_method") Bar.@1 )"); + // Both definitions of the duplicated class are bound to any, so neither one's members are offered. auto ac = autocomplete('1'); - CHECK(ac.entryMap.count("new") > 0); CHECK(ac.entryMap.count("make") == 0); + CHECK(ac.entryMap.count("new") == 0); ac = autocomplete('2'); CHECK(ac.entryMap.count("hmm") > 0); @@ -5889,9 +5890,7 @@ TEST_CASE_FIXTURE(ACFixture, "class_autocomplete_classname_inside_method") ac = autocomplete('3'); - // FIXME CLI-204201: It would be a nice-to-have if autocomplete inside - // erroneous classes still worked as expected. - CHECK(ac.entryMap.count("huh") == 0); + CHECK(ac.entryMap.count("huh") > 0); CHECK(ac.entryMap.count("hmm") == 0); } diff --git a/tests/BytecodeCallInliner.test.cpp b/tests/BytecodeCallInliner.test.cpp index 37f801caf..9a8c8fa13 100644 --- a/tests/BytecodeCallInliner.test.cpp +++ b/tests/BytecodeCallInliner.test.cpp @@ -11,6 +11,7 @@ #include "Luau/Sccp.h" #include +#include #include "Fixture.h" @@ -216,6 +217,46 @@ struct BytecodeInlinerFixture return result; } + std::optional> findDanglingPhiOperand(const CompTimeBcFunction& fn) + { + std::unordered_set livePhis; + for (const BcBlock& block : fn.blocks) + { + if (block.flags & BcBlockFlag::Dead) + continue; + for (const BcOp& phiOp : block.phis) + livePhis.insert(phiOp); + } + + auto dangles = [&](BcOp operand) + { + return operand.kind == BcOpKind::Phi && livePhis.count(operand) == 0; + }; + + for (const BcBlock& block : fn.blocks) + { + if (block.flags & BcBlockFlag::Dead) + continue; + for (const BcOp& phiOp : block.phis) + { + for (BcOp operand : fn.phis[phiOp.index].ops) + { + if (dangles(operand)) + return std::make_pair(phiOp, operand); + } + } + for (const BcOp& instOp : block.ops) + { + for (BcOp operand : fn.instructions[instOp.index].ops) + { + if (dangles(operand)) + return std::make_pair(instOp, operand); + } + } + } + return std::nullopt; + } + std::vector strings; }; @@ -2426,7 +2467,7 @@ TEST_CASE_FIXTURE(BytecodeInlinerFixture, "construct_feedback_slot_after_inlinin ScopedFastFlag debugLuauUserDefinedClasses{FFlag::DebugLuauUserDefinedClasses, true}; auto res = compileAndInline(R"( - class Point + local class Point public x public y end @@ -2490,4 +2531,30 @@ bb_1 (exit): ); } +TEST_CASE_FIXTURE(BytecodeInlinerFixture, "parser_does_not_reference_removed_phi") +{ + ScopedFastFlag emitCallFb{FFlag::LuauEmitCallFeedback, true}; + + std::vector graphs = buildGraphs(R"( + local function f7(a8) + for _ = 0, 4 do + local function f12() end + for _ = 0, 4 do + local C14 = {} + C14.__index = C14 + setmetatable(C14, { __index = f12 }) + end + end + local v20 = { [a8] = function(self) end } + end + f7(-1844856569) + )"); + + for (const CompTimeBcFunction& fn : graphs) + { + std::optional> dangling = findDanglingPhiOperand(fn); + CHECK_MESSAGE(!dangling.has_value(), "phi operand points at a removed phi in function '", fn.debugname, "'"); + } +} + TEST_SUITE_END(); diff --git a/tests/BytecodeCompiler.test.cpp b/tests/BytecodeCompiler.test.cpp index 6ece1e472..bbc3a4d82 100644 --- a/tests/BytecodeCompiler.test.cpp +++ b/tests/BytecodeCompiler.test.cpp @@ -17,7 +17,6 @@ using namespace Luau; using namespace Luau::Bytecode; LUAU_FASTFLAG(LuauEmitCallFeedback) -LUAU_FASTFLAG(LuauCompileFastpcall) LUAU_FASTFLAG(LuauCompileReuseLocalRegs) namespace @@ -976,7 +975,7 @@ TEST_CASE_FIXTURE(BytecodeCompilerFixture, "inheriting_classes_bytecode_roundtri }; std::string_view source = R"( -open class Animal +local open class Animal public species: string function __tostring(self) @@ -988,7 +987,7 @@ open class Animal end end -class Cat extends Animal +local class Cat extends Animal public breed: string function __tostring(self): string @@ -1121,8 +1120,6 @@ end TEST_CASE_FIXTURE(BytecodeCompilerFixture, "fastpcall_roundtrip") { - ScopedFastFlag luauCompileFastpcall{FFlag::LuauCompileFastpcall, true}; - checkRoundtrip(R"( local function test(fn) return pcall(fn, 42) diff --git a/tests/ClassRuntimeErrors.test.cpp b/tests/ClassRuntimeErrors.test.cpp index f7bea129b..3a6d50810 100644 --- a/tests/ClassRuntimeErrors.test.cpp +++ b/tests/ClassRuntimeErrors.test.cpp @@ -12,7 +12,6 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) LUAU_FASTFLAG(LuauEmitCallFeedback) -LUAU_FASTFLAG(LuauBytecodeCostModel) TEST_SUITE_BEGIN("ClassRuntimeErrorTests"); @@ -22,7 +21,6 @@ TEST_CASE_FIXTURE(ReplWithPathFixture, "RequireClassOverrideInstanceMemberError" {FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::DebugLuauUserDefinedClassesRuntime, true}, {FFlag::LuauEmitCallFeedback, true}, - {FFlag::LuauBytecodeCostModel, true} }; std::string path = getLuauDirectory(PathType::Relative) + "/tests/classes/class_override_instance_member_error"; runProtectedRequire(path); @@ -35,7 +33,6 @@ TEST_CASE_FIXTURE(ReplWithPathFixture, "RequireClassExtendsNonOpenParent") {FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::DebugLuauUserDefinedClassesRuntime, true}, {FFlag::LuauEmitCallFeedback, true}, - {FFlag::LuauBytecodeCostModel, true} }; std::string path = getLuauDirectory(PathType::Relative) + "/tests/classes/class_extends_non_open_parent"; runProtectedRequire(path); @@ -48,7 +45,6 @@ TEST_CASE_FIXTURE(ReplWithPathFixture, "RequireClassOverridesComparisonMetametho {FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::DebugLuauUserDefinedClassesRuntime, true}, {FFlag::LuauEmitCallFeedback, true}, - {FFlag::LuauBytecodeCostModel, true} }; std::string path = getLuauDirectory(PathType::Relative) + "/tests/classes/class_override_eq"; diff --git a/tests/Compiler.test.cpp b/tests/Compiler.test.cpp index 5ca814d73..c718ca72e 100644 --- a/tests/Compiler.test.cpp +++ b/tests/Compiler.test.cpp @@ -23,26 +23,20 @@ LUAU_FASTINT(LuauCompileInlineThresholdMaxBoost) LUAU_FASTINT(LuauCompileLoopUnrollThreshold) LUAU_FASTINT(LuauCompileLoopUnrollThresholdMaxBoost) LUAU_FASTINT(LuauRecursionLimit) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauCompileTableFoldFix) -LUAU_FASTFLAG(LuauIntegerFastcalls) -LUAU_FASTFLAG(LuauIntegerBufferFastcalls) -LUAU_FASTFLAG(LuauCompileMoveElision) LUAU_FASTFLAG(LuauCompileNoDebugConst) -LUAU_FASTFLAG(LuauCompileMoveElisionFix) LUAU_FASTFLAG(LuauCompileConcatTargetTop) LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(DebugLuauNoInline) LUAU_FASTFLAG(LuauEmitCallFeedback) LUAU_FASTFLAG(LuauOptimizeExportTable) -LUAU_FASTFLAG(LuauCompileFastpcall) LUAU_FASTFLAG(LuauExportedTypesParticipateInScc) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) -LUAU_FASTFLAG(LuauCompileNoFoldVectorEqW) LUAU_FASTFLAG(LuauCompileReuseLocalRegs) LUAU_FASTFLAG(LuauCompileTableBuiltinsCreateClear) LUAU_FASTFLAG(LuauCompileReuseLowersLimit) LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) +LUAU_FASTFLAG(LuauCompileLoopUnrollNegativeZero) using namespace Luau; @@ -238,6 +232,8 @@ TEST_CASE("BytecodeIsStable") CHECK(LBF_TOSTRING == 63); CHECK(LBF_BUFFER_WRITEF64 == 77); CHECK(LBF_VECTOR_MAX == 88); + CHECK(LBF_TABLE_CREATE == 133); + CHECK(LBF_TABLE_CLEAR == 134); // Bytecode capture type (serialized & in-memory) CHECK(LCT_UPVAL == 2); // bytecode v1 @@ -248,6 +244,9 @@ TEST_CASE("BytecodeIsStable") // Bytecode type encoding (serialized & in-memory) // Note: these *can* change retroactively *if* type version is bumped, but probably shouldn't LUAU_ASSERT(LBC_TYPE_BUFFER == 9); // type version 1 + CHECK(LBC_TYPE_INTEGER_DEPRECATED == 10); // reserved serialized ID for the retired integer type + CHECK(LBC_TYPE_CLASS == 11); + CHECK(LBC_TYPE_OBJECT == 12); } TEST_CASE("CompileToBytecode") @@ -968,7 +967,7 @@ TEST_CASE("DumpConstantClass") CHECK_EQ( "\n" + compileFunctionConstants( R"( -open class Animal +local open class Animal public species: string function live(self) @@ -976,7 +975,7 @@ open class Animal end end -class Cat extends Animal +local class Cat extends Animal public breed: string function describe(self) @@ -1937,8 +1936,6 @@ RETURN R0 1 TEST_CASE("ConstantFoldVectorCompare") { - ScopedFastFlag luauCompileNoFoldVectorEqW{FFlag::LuauCompileNoFoldVectorEqW, true}; - CHECK_EQ("\n" + compileFunction("local a, b = vector.create(1, 2, 3), vector.create(1, 2, 4); return a == a, a ~= b", 0, 2), R"( LOADB R0 1 LOADB R1 1 @@ -4096,7 +4093,6 @@ local 7 (w): reg 3, start pc 0 line 4, end pc 5 line 8 TEST_CASE("DebugLocalInlineUndoEmit") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; ScopedFastFlag luauCompileReuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; const char* source = R"( @@ -4143,8 +4139,6 @@ L1: RETURN R3 1 TEST_CASE("DebugLocalInlineUndoEmit2") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - const char* source = R"( local function id(x) return x end local _ @@ -6375,6 +6369,32 @@ RETURN R0 0 ); } +TEST_CASE("LoopUnrollNegativeZero") +{ + ScopedFastFlag luauCompileLoopUnrollNegativeZero{FFlag::LuauCompileLoopUnrollNegativeZero, true}; + + CHECK_EQ( + "\n" + compileFunction( + R"( +for i = -0, 1 do + consume(i) +end +)", + 0, + 2 + ), + R"( +GETIMPORT R0 1 [consume] +LOADK R1 K2 [-0] +CALL R0 1 0 +GETIMPORT R0 1 [consume] +LOADN R1 1 +CALL R0 1 0 +RETURN R0 0 +)" + ); +} + TEST_CASE("LoopUnrollNested") { // we can unroll nested loops just fine @@ -7313,8 +7333,6 @@ RETURN R1 1 TEST_CASE("InlineNestedLoops") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // functions with basic loops get inlined CHECK_EQ( "\n" + compileFunction( @@ -7406,8 +7424,6 @@ RETURN R1 1 TEST_CASE("InlineMutate") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // if the argument is mutated, it gets a register even if the value is constant CHECK_EQ( "\n" + compileFunction( @@ -7507,8 +7523,6 @@ RETURN R1 1 TEST_CASE("InlineUpval") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // if the argument is an upvalue, we naturally need to copy it to a local CHECK_EQ( "\n" + compileFunction( @@ -7590,8 +7604,6 @@ RETURN R1 1 TEST_CASE("InlineCapture") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // if the argument is captured by a nested closure, normally we can rely on capture by value CHECK_EQ( "\n" + compileFunction( @@ -7827,8 +7839,6 @@ RETURN R1 -1 TEST_CASE("InlineArgMismatch") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // when inlining a function, we must respect all the usual rules // caller might not have enough arguments @@ -8396,8 +8406,6 @@ L3: RETURN R0 0 TEST_CASE("InlineHiddenMutation") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // when the argument is assigned inside the function, we can't reuse the local CHECK_EQ( "\n" + compileFunction( @@ -8907,8 +8915,6 @@ RETURN R1 1 TEST_CASE("InlineConstConditionals") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // the most expensive part does not participate in cost model if branches are const CHECK_EQ( "\n" + compileFunction( @@ -9078,8 +9084,6 @@ RETURN R1 5 TEST_CASE("InlineLoopIteration") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - CHECK_EQ( "\n" + compileFunction( R"( @@ -9482,8 +9486,6 @@ RETURN R2 1 TEST_CASE("InlineElideTemporaries") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // 'id' elides the move by pointing the argument at the target and 'accum' elides the move by pointing the local 's' to the target CHECK_EQ( "\n" + compileFunction( @@ -9856,8 +9858,6 @@ RETURN R4 1 TEST_CASE("InlineElideCaptured") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // Locals captured by reference cannot elide the move CHECK_EQ( "\n" + compileFunction( @@ -10063,8 +10063,6 @@ RETURN R4 1 TEST_CASE("InlineElideAliased") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // Argument storage cannot alias the result target when result construction may overwrite it before the argument is read CHECK_EQ( "\n" + compileFunction( @@ -10154,8 +10152,6 @@ RETURN R0 2 )" ); - ScopedFastFlag luauCompileMoveElisionFix{FFlag::LuauCompileMoveElisionFix, true}; - // Target register cannot be used if it's still needed to evaluate the argument CHECK_EQ( "\n" + compileFunction( @@ -10187,8 +10183,6 @@ RETURN R2 1 TEST_CASE("InlineNoElideWhenNoTarget") { - ScopedFastFlag luauCompileMoveElision{FFlag::LuauCompileMoveElision, true}; - // there is no target register when return values are not used, so no move elision is needed CHECK_EQ( "\n" + compileFunction( @@ -12268,7 +12262,7 @@ TEST_CASE("ClassDeclBasic") ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; std::string source = R"( - class Point + local class Point public x: number public y: number end @@ -12289,7 +12283,7 @@ TEST_CASE("ClassDeclWithMethod") ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; std::string source = R"( - class Point + local class Point public x: number public y: number function magnitude(self) @@ -12329,7 +12323,7 @@ TEST_CASE("ClassDeclWithAmbiguousGlobal") }; std::string source = R"( - class Point + local class Point public x: number public y: number function print(self) @@ -12369,7 +12363,7 @@ TEST_CASE("ClassDeclWithExplicitCtor") }; std::string source = R"( - class Point + local class Point public x: number public y: number function __init(self, x, y) @@ -12379,14 +12373,14 @@ TEST_CASE("ClassDeclWithExplicitCtor") end return { Point = Point } )"; - auto res0 = "\n" + compileFunction(source.c_str(), 0, 0, 0); - CHECK(R"( + + CHECK_EQ("\n" + compileFunction(source.c_str(), 0, 0, 0), R"( SETTABLEKS R1 R0 K0 ['x'] SETTABLEKS R2 R0 K1 ['y'] RETURN R0 0 -)" == res0); - auto res1 = "\n" + compileFunction(source.c_str(), 1, 0, 0); - CHECK(res1 == R"( +)"); + + CHECK_EQ("\n" + compileFunction(source.c_str(), 1, 0, 0), R"( NEWCLASS R0 no_base K4 0 [class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0)] NEWCLOSURE R1 P0 NEWCLASSMEMBER R0 R1 [public] ['__init'] @@ -12440,6 +12434,7 @@ NEWCLASSMEMBER R0 R1 [public] ['getX'] NEWCLOSURE R1 P1 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['getY'] +SETGLOBAL R0 K0 ['Point'] RETURN R0 0 )"); } @@ -12483,9 +12478,10 @@ NEWCLASS R0 no_base K3 0 [class Point (public fields: 0, public methods: 2, priv NEWCLOSURE R1 P0 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['magnitude'] -GETGLOBAL R1 K4 ['print'] -MOVE R2 R0 -CALL R1 1 0 +SETGLOBAL R0 K0 ['Point'] +GETGLOBAL R0 K4 ['print'] +GETGLOBAL R1 K0 ['Point'] +CALL R0 1 0 RETURN R0 0 )"); } @@ -12528,6 +12524,7 @@ NEWCLASS R0 no_base K5 0 [class Account (public fields: 2, public methods: 2, pr NEWCLOSURE R1 P0 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['peek'] +SETGLOBAL R0 K0 ['Account'] RETURN R0 0 )"); } @@ -12577,6 +12574,7 @@ NEWCLASSMEMBER R0 R1 1 [private] NEWCLOSURE R1 P2 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['pick'] +SETGLOBAL R0 K0 ['C'] RETURN R0 0 )"); } @@ -12619,6 +12617,7 @@ NEWCLASSMEMBER R0 R1 0 [private] NEWCLOSURE R1 P1 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['get'] +SETGLOBAL R0 K0 ['C'] RETURN R0 0 )"); } @@ -12657,6 +12656,7 @@ NEWCLASS R0 no_base K3 0 [class Point (public fields: 0, public methods: 2, priv NEWCLOSURE R1 P0 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['describe'] +SETGLOBAL R0 K0 ['Point'] RETURN R0 0 )"); } @@ -12687,15 +12687,15 @@ TEST_CASE("ClassPrivateFieldInNestedClosure") Luau::compileOrThrow(bcb, source, options); CHECK_EQ("\n" + bcb.dumpFunction(0), R"( -GETUPVAL R0 U0 -GETPRIVATEFIELD R0 R0 U1 0 [instance] +GETUPVAL R0 U1 +GETPRIVATEFIELD R0 R0 U0 0 [instance] RETURN R0 1 )"); CHECK_EQ("\n" + bcb.dumpFunction(1), R"( NEWCLOSURE R1 P0 -CAPTURE VAL R0 CAPTURE UPVAL U0 +CAPTURE VAL R0 RETURN R1 1 )"); @@ -12704,6 +12704,7 @@ NEWCLASS R0 no_base K3 0 [class Point (public fields: 0, public methods: 2, priv NEWCLOSURE R1 P0 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['makeGetter'] +SETGLOBAL R0 K0 ['Point'] RETURN R0 0 )"); } @@ -12737,7 +12738,8 @@ RETURN R1 1 CHECK_EQ("\n" + bcb.dumpFunction(1), R"( NEWCLASS R0 no_base K2 0 [class Point (public fields: 0, public methods: 1, private fields: 1, private methods: 0)] -NEWCLOSURE R1 P0 +SETGLOBAL R0 K0 ['Point'] +NEWCLOSURE R0 P0 RETURN R0 0 )"); } @@ -12858,10 +12860,11 @@ NEWCLASS R0 no_base K2 0 [class Point (public fields: 0, public methods: 1, priv NEWCLOSURE R1 P0 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['__init'] -MOVE R1 R0 -LOADK R2 K3 [3] -LOADK R3 K4 [4] -CALL R1 2 1 +SETGLOBAL R0 K0 ['Point'] +GETGLOBAL R0 K0 ['Point'] +LOADK R1 K3 [3] +LOADK R2 K4 [4] +CALL R0 2 1 RETURN R0 0 )"); } @@ -12962,8 +12965,9 @@ TEST_CASE("ClassPrivateFieldAssignmentInNestedClosure") { ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; - CHECK_EQ( - "\n" + compileFunction0(R"( + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + Luau::compileOrThrow(bcb, R"( class Point private _x: number function makeSetter(self) @@ -12972,13 +12976,29 @@ TEST_CASE("ClassPrivateFieldAssignmentInNestedClosure") end end end - )"), - R"( -GETUPVAL R1 U0 -SETPRIVATEFIELD R0 R1 U1 0 + )"); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETUPVAL R1 U1 +SETPRIVATEFIELD R0 R1 U0 0 RETURN R0 0 -)" - ); +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLOSURE R1 P0 +CAPTURE UPVAL U0 +CAPTURE VAL R0 +RETURN R1 1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +NEWCLASS R0 no_base K3 0 [class Point (public fields: 0, public methods: 2, private fields: 1, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['makeSetter'] +SETGLOBAL R0 K0 ['Point'] +RETURN R0 0 +)"); } TEST_CASE("ClassPrivateFieldAssignmentOnOtherInstance") @@ -13108,7 +13128,7 @@ TEST_CASE("ClassUndeclaredPrivateFieldAssignmentProducesError") } catch (const std::exception& e) { - CHECK(std::string(e.what()) == "Attempt to assign undefined private field"); + CHECK(std::string(e.what()) == "Attempt to access undefined private field"); } } @@ -13132,7 +13152,7 @@ TEST_CASE("ClassPrivateFieldAssignmentWithNoPrivateMembersProducesError") } catch (const std::exception& e) { - CHECK(std::string(e.what()) == "Attempt to assign private field of a class with no private fields"); + CHECK(std::string(e.what()) == "Attempt to access undefined private field"); } } @@ -13214,7 +13234,7 @@ TEST_CASE("ClassConstructedInsidePrivateMethod") // _scaled: the class name resolves to the captured class upvalue, so the construction inside a // private method is an ordinary call on that upvalue. CHECK_EQ("\n" + bcb.dumpFunction(0), R"( -GETUPVAL R2 U0 +GETGLOBAL R2 K0 ['Vec'] GETPRIVATEFIELD R4 R0 U0 0 [instance] MUL R3 R4 R1 GETPRIVATEFIELD R5 R0 U0 1 [instance] @@ -13244,16 +13264,17 @@ RETURN R1 -1 // main chunk: the class is built in a local that every method captures by reference, which is the // upvalue the private accesses above index through. CHECK_EQ("\n" + bcb.dumpFunction(3), R"( -NEWCLASS R0 no_base K6 0 [class Vec (public fields: 0, public methods: 2, private fields: 2, private methods: 1)] -DUPCLOSURE R1 K1 ['_scaled'] +NEWCLASS R0 no_base K3 0 [class Vec (public fields: 0, public methods: 2, private fields: 2, private methods: 1)] +NEWCLOSURE R1 P0 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 0 [private] -DUPCLOSURE R1 K2 ['__init'] +NEWCLOSURE R1 P1 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['__init'] -DUPCLOSURE R1 K4 ['double'] +NEWCLOSURE R1 P2 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['double'] +SETGLOBAL R0 K0 ['Vec'] RETURN R0 0 )"); } @@ -13302,7 +13323,7 @@ RETURN R0 0 // GETPRIVATEFIELD writes the callee into. The instance form (self:_method()) instead uses the // receiver's own local register as the source and so does not alias the callee register. CHECK_EQ("\n" + bcb.dumpFunction(2), R"( -GETUPVAL R1 U0 +GETGLOBAL R1 K0 ['StaticNamecall'] GETPRIVATEFIELD R1 R1 U0 0 [static] [namecall] CALL R1 1 -1 RETURN R1 -1 @@ -13310,117 +13331,20 @@ RETURN R1 -1 // main chunk CHECK_EQ("\n" + bcb.dumpFunction(3), R"( -NEWCLASS R0 no_base K6 0 [class StaticNamecall (public fields: 0, public methods: 2, private fields: 1, private methods: 1)] +NEWCLASS R0 no_base K4 0 [class StaticNamecall (public fields: 0, public methods: 2, private fields: 1, private methods: 1)] DUPCLOSURE R1 K1 ['_receiver'] NEWCLASSMEMBER R0 R1 0 [private] -DUPCLOSURE R1 K2 ['__init'] +NEWCLOSURE R1 P1 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['__init'] -DUPCLOSURE R1 K4 ['staticReceiver'] +NEWCLOSURE R1 P2 CAPTURE VAL R0 NEWCLASSMEMBER R0 R1 [public] ['staticReceiver'] +SETGLOBAL R0 K0 ['StaticNamecall'] RETURN R0 0 )"); } -TEST_CASE("IntegerType") -{ - if (!FFlag::LuauIntegerType2) - return; - - // i suffix - CHECK_EQ( - "\n" + compileFunction0(R"( -local a = 123i -return a -)"), - R"( -LOADK R0 K0 [123] -RETURN R0 1 -)" - ); - - // separators - CHECK_EQ( - "\n" + compileFunction0(R"( -local a = 1_000_000i -return a -)"), - R"( -LOADK R0 K0 [1000000] -RETURN R0 1 -)" - ); - - // hex - CHECK_EQ( - "\n" + compileFunction0(R"( -local a = 0xABABi -return a -)"), - R"( -LOADK R0 K0 [43947] -RETURN R0 1 -)" - ); - - // binary - CHECK_EQ( - "\n" + compileFunction0(R"( -local a = 0b100101i -return a -)"), - R"( -LOADK R0 K0 [37] -RETURN R0 1 -)" - ); - - // Has to be exactly representable; overflow is a parse error - - std::string source1 = "local a = 9999999999999999999999999i"; - std::string source2 = "local a = 2.37i"; - - std::string bc1 = Luau::compile(source1); - std::string bc2 = Luau::compile(source2); - - // 0 acts as a special marker for error bytecode - CHECK_EQ(bc1[0], 0); - CHECK_EQ(bc2[0], 0); -} - -TEST_CASE("IntegerBcb") -{ - ScopedFastFlag luauInteger{FFlag::LuauIntegerType2, true}; - ScopedFastFlag luauCompileNoDebugConst{FFlag::LuauCompileNoDebugConst, true}; - - const char* source = R"( -function foo(x) -local a = 123i -if x then a = 456i end -return a -end)"; - - Luau::BytecodeBuilder bcb; - bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code | Luau::BytecodeBuilder::Dump_Types); - bcb.setDumpSource(source); - - Luau::CompileOptions options; - - options.typeInfoLevel = 1; - options.optimizationLevel = 1; - - Luau::compileOrThrow(bcb, source, options); - - CHECK_EQ("\n" + bcb.dumpFunction(0), R"( -R1: integer from 0 to 4 -LOADK R1 K0 [123] -JUMPIFNOT R0 L0 -LOADK R1 K1 [456] -L0: RETURN R1 1 -)"); -} - TEST_CASE("DebugNoInline") { ScopedFastFlag noInline{FFlag::DebugLuauNoInline, true}; @@ -14122,47 +14046,6 @@ L0: RETURN R0 0 ); } -TEST_CASE("BufferIntegerFastcall") -{ - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag luauIntegerBufferFastcalls{FFlag::LuauIntegerBufferFastcalls, true}; - - CHECK_EQ( - "\n" + compileFunction0(R"( -local b = buffer.create(16) -return buffer.readinteger(b, 0) -)"), - R"( -GETIMPORT R0 2 [buffer.create] -LOADN R1 16 -CALL R0 1 1 -FASTCALL2K 131 R0 K3 L0 [0] -MOVE R2 R0 -LOADK R3 K3 [0] -GETIMPORT R1 5 [buffer.readinteger] -CALL R1 2 -1 -L0: RETURN R1 -1 -)" - ); - - CHECK_EQ( - "\n" + compileFunction0(R"( -local b, v = ... -buffer.writeinteger(b, 0, v) -)"), - R"( -GETVARARGS R0 2 -LOADN R4 0 -FASTCALL3 132 R0 R4 R1 L0 -MOVE R3 R0 -MOVE R5 R1 -GETIMPORT R2 2 [buffer.writeinteger] -CALL R2 3 0 -L0: RETURN R0 0 -)" - ); -} - TEST_CASE("ExportLocalBytecode") { ScopedFastFlag sffs[] = {{FFlag::LuauExportValueSyntax, true}, {FFlag::LuauOptimizeExportTable, true}}; @@ -14362,7 +14245,7 @@ TEST_CASE("LBCConstantRegressionTest") CHECK_EQ(LBC_CONSTANT_CLOSURE, 6); CHECK_EQ(LBC_CONSTANT_VECTOR, 7); CHECK_EQ(LBC_CONSTANT_TABLE_WITH_CONSTANTS, 8); - CHECK_EQ(LBC_CONSTANT_INTEGER, 9); + CHECK_EQ(LBC_CONSTANT_INTEGER_DEPRECATED, 9); CHECK_EQ(LBC_CONSTANT_CLASS_SHAPE, 10); CHECK_EQ(LBC_CONSTANT_VECTORD, 11); @@ -14435,7 +14318,7 @@ export class Point public y: number end -local p = Point.new({x = 1, y = 2}) +local p = Point {x = 1, y = 2} )", 0, 2 @@ -14443,11 +14326,12 @@ local p = Point.new({x = 1, y = 2}) R"( NEWTABLE R1 0 0 NEWCLASS R0 no_base K4 0 [class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0)] -GETTABLEKS R2 R0 K5 ['new'] -DUPTABLE R3 8 +MOVE R2 R0 +CONSTRUCT R3 R2 slot 0 +FINCONSTRUCT R3 L0 CALL R2 1 1 -SETTABLEKS R0 R1 K0 ['Point'] -GETIMPORT R3 11 [table.freeze] +L0: SETTABLEKS R0 R1 K0 ['Point'] +GETIMPORT R3 10 [table.freeze] MOVE R4 R1 CALL R3 1 1 RETURN R3 1 @@ -14499,11 +14383,11 @@ TEST_CASE("ClassInheritanceBasic") ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; std::string source = R"( -open class Animal +local open class Animal public species: string end -class Cat extends Animal +local class Cat extends Animal public breed: string end @@ -14526,7 +14410,7 @@ TEST_CASE("ClassInheritanceWithMethods") ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; std::string source = R"( -open class Animal +local open class Animal public species: string function live(self) @@ -14534,7 +14418,7 @@ open class Animal end end -class Cat extends Animal +local class Cat extends Animal public breed: string function describe(self) @@ -14580,23 +14464,22 @@ TEST_CASE("ClassInheritanceMultiLevel") ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; std::string source = R"( -open class A +local open class A public x: number end -open class B extends A +local open class B extends A public y: number end -class C extends B +local class C extends B public z: number end print(C) )"; - auto res0 = "\n" + compileFunction(source.c_str(), 0, 0, 0); - CHECK(R"( + CHECK_EQ("\n" + compileFunction(source.c_str(), 0, 0, 0), R"( NEWCLASS R0 no_base K3 1 [class A (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] NEWCLASS R1 R0 K6 1 [class B (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] NEWCLASS R2 R1 K9 0 [class C (public fields: 1, public methods: 1, private fields: 0, private methods: 0)] @@ -14604,7 +14487,7 @@ GETGLOBAL R3 K10 ['print'] MOVE R4 R2 CALL R3 1 0 RETURN R0 0 -)" == res0); +)"); } TEST_CASE("ExportClassInheritance") @@ -14616,7 +14499,7 @@ TEST_CASE("ExportClassInheritance") CHECK_EQ( "\n" + compileFunction0(R"( -open class Animal +local open class Animal public species: string end @@ -14643,9 +14526,9 @@ TEST_CASE("ExtendShadowedClass") CHECK_EQ( "\n" + compileFunction0(R"( -class _ end +local class _ end local _ -class l0 extends _ +local class l0 extends _ end )"), R"( @@ -14657,79 +14540,568 @@ RETURN R0 0 ); } -TEST_CASE("ClassConstruction") +TEST_CASE("CyclicInheritanceDoesntWork") { ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; - ScopedFastFlag luauCompileReuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; CHECK_EQ( - "\n" + compileFunction0Constants(R"( -local x, y = ... -class Point - public x - public y + "\n" + compileFunction0(R"( +local B +open class A extends B end -local a = Point{x = 1} -local b = Point{x = 2, y = 3} -local c = Point{x = 3, y = x} -local d = Point{x = x * y, y = x - y} -return a, b, c, d +open class B extends A +end )"), R"( -K0: 'Point' -K1: 'x' -K2: 'y' -K3: '__init' -K4: class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0) - props: - K1 ['x'] - K2 ['y'] - methods: - K3 ['__init'] -K5: 1 -K6: {['x'] = 1 #0} sizenode=1 -K7: 2 -K8: 3 -K9: {['x'] = 2 #1, ['y'] = 3 #0} sizenode=2 -K10: {['x'] = 3 #1, ['y'] #0} sizenode=2 -K11: {['x'] #1, ['y'] #0} sizenode=2 -slot 0: shape K6 -slot 1: shape K9 -slot 2: shape K10 -slot 3: shape K11 -GETVARARGS R0 2 -NEWCLASS R2 no_base K4 0 [class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0)] -MOVE R3 R2 -CONSTRUCT R4 R3 slot 0 -FINCONSTRUCT R4 L0 -CALL R3 1 1 -L0: MOVE R4 R2 -CONSTRUCT R5 R4 slot 1 -FINCONSTRUCT R5 L1 -CALL R4 1 1 -L1: MOVE R5 R2 -CONSTRUCT R6 R5 slot 2 -SETTABLEKS R0 R6 K2 ['y'] -FINCONSTRUCT R6 L2 -CALL R5 1 1 -L2: MOVE R6 R2 -CONSTRUCT R7 R6 slot 3 -MUL R8 R0 R1 -SETTABLEKS R8 R7 K1 ['x'] -SUB R8 R0 R1 -SETTABLEKS R8 R7 K2 ['y'] -FINCONSTRUCT R7 L3 -CALL R6 1 1 -L3: RETURN R3 4 +LOADNIL R0 +NEWCLASS R1 R0 K2 1 [class A (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] +SETGLOBAL R1 K0 ['A'] +GETGLOBAL R1 K0 ['A'] +NEWCLASS R0 R1 K4 1 [class B (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] +RETURN R0 0 )" ); } -TEST_CASE("NoFastcallConstruction") +TEST_CASE("ConstClass") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + ScopedFastFlag reuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + Luau::compileOrThrow(bcb, R"( +const class Point + public x: number + function origin() + return Point { x = 0 } + end +end +local function getPoint() + return Point +end +return Point, getPoint +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETUPVAL R0 U0 +CONSTRUCT R1 R0 slot 0 +FINCONSTRUCT R1 L0 +CALL R0 1 -1 +L0: RETURN R0 -1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +GETUPVAL R0 U0 +RETURN R0 1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +NEWCLASS R0 no_base K5 0 [class Point (public fields: 1, public methods: 2, private fields: 0, private methods: 0)] +DUPCLOSURE R1 K2 ['origin'] +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['origin'] +DUPCLOSURE R1 K6 ['getPoint'] +CAPTURE VAL R0 +RETURN R0 2 +)"); +} + +TEST_CASE("GlobalClassReferencedInMethod") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + Luau::compileOrThrow(bcb, R"( +class Point + public x: number + function origin() + return Point { x = 0 } + end +end +return Point +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETGLOBAL R0 K0 ['Point'] +CONSTRUCT R1 R0 slot 0 +FINCONSTRUCT R1 L0 +CALL R0 1 -1 +L0: RETURN R0 -1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLASS R0 no_base K5 0 [class Point (public fields: 1, public methods: 2, private fields: 0, private methods: 0)] +DUPCLOSURE R1 K2 ['origin'] +NEWCLASSMEMBER R0 R1 [public] ['origin'] +SETGLOBAL R0 K0 ['Point'] +GETGLOBAL R0 K0 ['Point'] +RETURN R0 1 +)"); +} + +TEST_CASE("ClassAssignsToUpvalue") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( +local Point +local function define() + class Point + end +end +define() +return Point +)"), + R"( +NEWCLASS R0 no_base K2 0 [class Point (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] +SETUPVAL R0 U0 +RETURN R0 0 +)" + ); +} + +TEST_CASE("ClassOverwritesLocal") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction( + R"( +local Point = 1 +class Point +end +return Point +)", + 0, + 2 + ), + R"( +LOADN R0 1 +NEWCLASS R0 no_base K2 0 [class Point (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] +RETURN R0 1 +)" + ); +} + +TEST_CASE("ClassAssignsToLocalInNestedBlock") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( +local Point +if ... then + class Point + end +end +return Point +)"), + R"( +LOADNIL R0 +GETVARARGS R1 1 +JUMPIFNOT R1 L0 +NEWCLASS R0 no_base K2 0 [class Point (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] +L0: RETURN R0 1 +)" + ); +} + +TEST_CASE("ClassOverwritesLocalItExtends") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + // NEWCLASS writes its target before reading the base, so the class can't be compiled directly into the base's register + CHECK_EQ( + "\n" + compileFunction0(R"( +local Foo = ... +class Foo extends Foo +end +return Foo +)"), + R"( +GETVARARGS R0 1 +NEWCLASS R1 R0 K2 0 [class Foo (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] +MOVE R0 R1 +RETURN R0 1 +)" + ); +} + +TEST_CASE("ClassLocalDeclaredAfterContinueUsedInUntil") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + try + { + Luau::BytecodeBuilder bcb; + Luau::compileOrThrow(bcb, R"( +repeat + if ... then continue end + + local class Foo end +until Foo +)"); + + CHECK(!"Expected CompileError"); + } + catch (Luau::CompileError& e) + { + CHECK_EQ(e.getLocation().begin.line + 1, 6); + CHECK_EQ( + std::string(e.what()), "Local Foo used in the repeat..until condition is undefined because continue statement on line 3 jumps over it" + ); + } +} + +TEST_CASE("ClassPrivateFieldClosureInUntilAfterContinue") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + // The closure's upvalue list starts with a class placeholder that the continue/until validation must skip + Luau::BytecodeBuilder bcb; + Luau::compileOrThrow(bcb, R"( +local class C + private _x + + public function f(self, c) + repeat + if c then continue end + until (function() return self._x end)() + end +end +return C +)"); +} + +TEST_CASE("LocalClassInFunction") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + Luau::compileOrThrow(bcb, R"( +local function make(n) + local class Counter + public count: number + function reset(self) + self.count = n + end + end + return Counter +end +return make +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETUPVAL R1 U0 +SETTABLEKS R1 R0 K0 ['count'] +RETURN R0 0 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLASS R1 no_base K4 0 [class Counter (public fields: 1, public methods: 2, private fields: 0, private methods: 0)] +NEWCLOSURE R2 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R1 R2 [public] ['reset'] +RETURN R1 1 +)"); +} + +TEST_CASE("LocalClassShadowedInDoBlock") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + CHECK_EQ( + "\n" + compileFunction0(R"( +local class Point +end +do + local class Point + end + print(Point) +end +print(Point) +)"), + R"( +NEWCLASS R0 no_base K2 0 [class Point (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] +NEWCLASS R1 no_base K3 0 [class Point (public fields: 0, public methods: 1, private fields: 0, private methods: 0)] +GETIMPORT R2 5 [print] +MOVE R3 R1 +CALL R2 1 0 +GETIMPORT R1 5 [print] +MOVE R2 R0 +CALL R1 1 0 +RETURN R0 0 +)" + ); +} + +TEST_CASE("LocalClassInLoop") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + Luau::compileOrThrow(bcb, R"( +local classes = {} +for i = 1, 3 do + local class Point + function index() + return i + end + end + classes[i] = Point +end +return classes +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETUPVAL R0 U0 +RETURN R0 1 +)"); + + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWTABLE R0 0 3 +LOADN R3 1 +LOADN R1 3 +LOADN R2 1 +FORNPREP R1 L1 +L0: NEWCLASS R4 no_base K3 0 [class Point (public fields: 0, public methods: 2, private fields: 0, private methods: 0)] +NEWCLOSURE R5 P0 +CAPTURE VAL R3 +NEWCLASSMEMBER R4 R5 [public] ['index'] +SETTABLE R4 R0 R3 +FORNLOOP R1 L0 +L1: RETURN R0 1 +)"); +} + +TEST_CASE("NestedClassShadowsPrivate") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + Luau::compileOrThrow(bcb, R"( +local class Outer + public function oMeth() + local class Inner + private _x + function iMeth(self) + return self._x + end + end + end +end +)"); + + // iMeth + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETPRIVATEFIELD R1 R0 U1 0 [instance] +RETURN R1 1 +)"); + + // oMeth + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLASS R0 no_base K3 0 [class Inner (public fields: 0, public methods: 2, private fields: 1, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE UPVAL U0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['iMeth'] +RETURN R0 0 +)"); + + // main: oMeth closure doesn't capture Outer as an upvalue despite lexically containing a private field access because the private belongs to + // Inner + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +NEWCLASS R0 no_base K3 0 [class Outer (public fields: 0, public methods: 2, private fields: 0, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['oMeth'] +RETURN R0 0 +)"); +} + +TEST_CASE("NestedClassPrivateFieldAccessOnInstanceUpvalue") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + Luau::BytecodeBuilder bcb; + bcb.setDumpFlags(Luau::BytecodeBuilder::Dump_Code); + Luau::compileOrThrow(bcb, R"( +local class Outer + private _x + + public function classMaker(inst) + local class Inner + private _y + + public function doStuff(self) + return self._y + inst._x + end + end + return Inner + end +end +)"); + + // Inner.doStuff: self._y resolves against Inner (U1), while inst._x resolves against Outer (U0) through the captured inst (U2) + CHECK_EQ("\n" + bcb.dumpFunction(0), R"( +GETPRIVATEFIELD R2 R0 U1 0 [instance] +GETUPVAL R3 U2 +GETPRIVATEFIELD R3 R3 U0 0 [instance] +ADD R1 R2 R3 +RETURN R1 1 +)"); + + // Outer.classMaker: Outer is forwarded from classMaker's own upvalue, followed by Inner, then the ordinary inst upvalue + CHECK_EQ("\n" + bcb.dumpFunction(1), R"( +NEWCLASS R1 no_base K3 0 [class Inner (public fields: 0, public methods: 2, private fields: 1, private methods: 0)] +NEWCLOSURE R2 P0 +CAPTURE UPVAL U0 +CAPTURE VAL R1 +CAPTURE VAL R0 +NEWCLASSMEMBER R1 R2 [public] ['doStuff'] +RETURN R1 1 +)"); + + // main + CHECK_EQ("\n" + bcb.dumpFunction(2), R"( +NEWCLASS R0 no_base K3 0 [class Outer (public fields: 0, public methods: 2, private fields: 1, private methods: 0)] +NEWCLOSURE R1 P0 +CAPTURE VAL R0 +NEWCLASSMEMBER R0 R1 [public] ['classMaker'] +RETURN R0 0 +)"); +} + +TEST_CASE("ClassNestingDepthLimit") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string source = rep("local class C function f() ", 257) + rep("end end ", 257); + + try + { + Luau::BytecodeBuilder bcb; + Luau::compileOrThrow(bcb, source); + FAIL("Expected compile error"); + } + catch (const Luau::CompileError& e) + { + CHECK_EQ(std::string(e.what()), "Class nest exceeded the maximum depth of 256"); + } +} + +// A method that accesses a private field captures one upvalue per enclosing class +static std::string makeNestedPrivateAccessSource(int depth) +{ + std::string source = rep("local class C public function f(self) ", depth - 1); + source += "local class C private _x public function f(self) return self._x end end "; + source += rep("end end ", depth - 1); + return source; +} + +TEST_CASE("ClassNestingWithinUpvalueLimit") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + Luau::BytecodeBuilder bcb; + Luau::compileOrThrow(bcb, makeNestedPrivateAccessSource(199)); +} + +TEST_CASE("ClassNestingExceedsUpvalueLimit") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + + try + { + Luau::BytecodeBuilder bcb; + Luau::compileOrThrow(bcb, makeNestedPrivateAccessSource(200)); + FAIL("Expected compile error"); + } + catch (const Luau::CompileError& e) + { + CHECK(std::string(e.what()).find("exceeded limit 200") != std::string::npos); + } +} + +TEST_CASE("ClassConstruction") +{ + ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; + ScopedFastFlag luauCompileReuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; + + CHECK_EQ( + "\n" + compileFunction0Constants(R"( +local x, y = ... +local class Point + public x + public y +end + +local a = Point{x = 1} +local b = Point{x = 2, y = 3} +local c = Point{x = 3, y = x} +local d = Point{x = x * y, y = x - y} +return a, b, c, d +)"), + R"( +K0: 'Point' +K1: 'x' +K2: 'y' +K3: '__init' +K4: class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0) + props: + K1 ['x'] + K2 ['y'] + methods: + K3 ['__init'] +K5: 1 +K6: {['x'] = 1 #0} sizenode=1 +K7: 2 +K8: 3 +K9: {['x'] = 2 #1, ['y'] = 3 #0} sizenode=2 +K10: {['x'] = 3 #1, ['y'] #0} sizenode=2 +K11: {['x'] #1, ['y'] #0} sizenode=2 +slot 0: shape K6 +slot 1: shape K9 +slot 2: shape K10 +slot 3: shape K11 +GETVARARGS R0 2 +NEWCLASS R2 no_base K4 0 [class Point (public fields: 2, public methods: 1, private fields: 0, private methods: 0)] +MOVE R3 R2 +CONSTRUCT R4 R3 slot 0 +FINCONSTRUCT R4 L0 +CALL R3 1 1 +L0: MOVE R4 R2 +CONSTRUCT R5 R4 slot 1 +FINCONSTRUCT R5 L1 +CALL R4 1 1 +L1: MOVE R5 R2 +CONSTRUCT R6 R5 slot 2 +SETTABLEKS R0 R6 K2 ['y'] +FINCONSTRUCT R6 L2 +CALL R5 1 1 +L2: MOVE R6 R2 +CONSTRUCT R7 R6 slot 3 +MUL R8 R0 R1 +SETTABLEKS R8 R7 K1 ['x'] +SUB R8 R0 R1 +SETTABLEKS R8 R7 K2 ['y'] +FINCONSTRUCT R7 L3 +CALL R6 1 1 +L3: RETURN R3 4 +)" + ); +} + +TEST_CASE("NoFastcallConstruction") { ScopedFastFlag sff{FFlag::DebugLuauUserDefinedClasses, true}; - ScopedFastFlag luauCompileFastpcall{FFlag::LuauCompileFastpcall, true}; CHECK_EQ( "\n" + compileFunction0(R"( @@ -14747,8 +15119,6 @@ L0: RETURN R0 0 TEST_CASE("ProtectedCalls") { - ScopedFastFlag luauCompileFastpcall{FFlag::LuauCompileFastpcall, true}; - CHECK_EQ( "\n" + compileFunction0(R"( local a, b = ... diff --git a/tests/Conformance.test.cpp b/tests/Conformance.test.cpp index b2d532bcf..d66c8ce59 100644 --- a/tests/Conformance.test.cpp +++ b/tests/Conformance.test.cpp @@ -58,26 +58,26 @@ void luaC_validate(lua_State* L); LUAU_FASTFLAG(DebugLuauAbortingChecks) LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauCodegenRuntimeFeedback) +LUAU_FASTFLAG(LuauCodegenUserdataDirect) LUAU_FASTFLAG(LuauPromoteProto) LUAU_FASTFLAG(LuauBytecodeFold) LUAU_FASTFLAG(LuauBytecodeSlotAlloc) LUAU_FASTFLAG(LuauCodegenA64BitlrotateSelf) LUAU_FASTFLAG(LuauEmitCallFeedback) +LUAU_FASTFLAG(LuauCodegenFastcallAnalysisLimit) LUAU_FASTFLAG(LuauCodegenMarkUsed) LUAU_FASTINT(CodegenHeuristicsInstructionLimit) -LUAU_FASTFLAG(LuauIntegerLibrary) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(DebugLuauForceOldSolver) -LUAU_FASTFLAG(LuauCodegenBufferInteger) +LUAU_FASTFLAG(DebugLuauBufferVectorLibrary) +LUAU_FASTFLAG(DebugLuauBufferVectorFastcalls) LUAU_FASTFLAG(LuauCodegenA64ReloadLargeConstOffset) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) -LUAU_FASTFLAG(LuauCompileNoFoldVectorEqW) LUAU_FASTFLAG(LuauGcTraceUdata) LUAU_DYNAMIC_FASTFLAG(LuauGcHeapShrinkFix) LUAU_FASTFLAG(LuauPcallErrorContinuationReentry) LUAU_FASTFLAG(LuauEmitCallFeedback) -LUAU_FASTFLAG(LuauBytecodeCostModel) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) LUAU_FASTFLAG(LuauSandboxFreezesVectorMetatable) LUAU_FASTFLAG(LuauBufferCage) @@ -86,8 +86,6 @@ LUAU_FASTFLAG(LuauCoroutineFinallyAnalysis) LUAU_FASTFLAG(LuauCodegenDseTrackTagInvalidation) LUAU_FASTFLAG(LuauCodegenCmpAnySideEffecting) LUAU_FASTFLAG(LuauExportValueSyntax) -LUAU_FASTFLAG(LuauCompileCallFbRemap) -LUAU_DYNAMIC_FASTFLAG(LuauTableRobustOom) LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) LUAU_FASTFLAG(LuauLoadExplicitGcDisable) @@ -287,6 +285,21 @@ void validateBytecodeGraph(const std::string& source, const lua_CompileOptions& using StateRef = std::unique_ptr; +// runConformance loads the script with luau_loadlazy +static bool lazyLoad = false; + +struct ScopedLazyLoad +{ + explicit ScopedLazyLoad(bool enabled = true) + { + lazyLoad = enabled; + } + ~ScopedLazyLoad() + { + lazyLoad = false; + } +}; + static StateRef runConformance( const char* name, void (*setup)(lua_State* L) = nullptr, @@ -388,8 +401,16 @@ static StateRef runConformance( size_t bytecodeSize = 0; char* bytecode = luau_compile(source.data(), source.size(), &opts, &bytecodeSize); - int result = luau_load(L, chunkname.c_str(), bytecode, bytecodeSize, 0); - free(bytecode); + int result = 0; + if (lazyLoad) + { + result = luau_loadlazy(L, chunkname.c_str(), bytecode, bytecodeSize, 0, bytecode, free); + } + else + { + result = luau_load(L, chunkname.c_str(), bytecode, bytecodeSize, 0); + free(bytecode); + } Luau::CodeGen::CompilationOptions nativeOpts = codegenOptions ? *codegenOptions : defaultCodegenOptions(); @@ -626,6 +647,21 @@ static int lua_vec2_reenter(lua_State* L, Vec2* self) return 1; } +static int lua_vec2_results(lua_State* L) +{ + int nargs = lua_gettop(L); + luaL_checkstack(L, 1024, "results"); + lua_pushinteger(L, nargs); + lua_pushinteger(L, 42); + return 2; +} + +static int lua_vec2_yield(lua_State* L) +{ + lua_pushinteger(L, 55); + return lua_yield(L, 1); +} + static int lua_vec2_index(lua_State* L) { Vec2* v = lua_vec2_get(L, 1); @@ -702,6 +738,12 @@ static int lua_vec2_namecall(lua_State* L) if (strcmp(str, "Reenter") == 0) return lua_vec2_reenter(L, self); + + if (strcmp(str, "Results") == 0) + return lua_vec2_results(L); + + if (strcmp(str, "Yield") == 0) + return lua_vec2_yield(L); } luaL_error(L, "%s is not a valid method of vector", luaL_checkstring(L, 1)); @@ -1017,6 +1059,8 @@ enum class DirectSlot : uint16_t Min, Clone, Reenter, + Results, + Yield, Pos, Normal, UV, @@ -1032,6 +1076,8 @@ const std::unordered_map nameToDirectSlot = { {"Min", DirectSlot::Min}, {"Clone", DirectSlot::Clone}, {"Reenter", DirectSlot::Reenter}, + {"Results", DirectSlot::Results}, + {"Yield", DirectSlot::Yield}, {"pos", DirectSlot::Pos}, {"normal", DirectSlot::Normal}, {"uv", DirectSlot::UV}, @@ -1135,6 +1181,10 @@ static int vec2DirectNamecall(lua_State* L, void* data, int atom, uint16_t* cach return lua_vec2_clone(L, self); case DirectSlot::Reenter: return lua_vec2_reenter(L, self); + case DirectSlot::Results: + return lua_vec2_results(L); + case DirectSlot::Yield: + return lua_vec2_yield(L); default: luaL_error(L, "%s is not a valid method of vec2", lua_namecallatom(L, nullptr)); } @@ -1300,6 +1350,9 @@ TEST_CASE("Basic") TEST_CASE("Buffers") { + ScopedFastFlag bufferVectorLibrary{FFlag::DebugLuauBufferVectorLibrary, true}; + ScopedFastFlag bufferVectorFastcalls{FFlag::DebugLuauBufferVectorFastcalls, true}; + runConformance( "buffers.luau", [](lua_State* L) @@ -1321,6 +1374,8 @@ static void setupBufferCage(lua_State* L) TEST_CASE("BuffersWithCage") { ScopedFastFlag luauBufferCage{FFlag::LuauBufferCage, true}; + ScopedFastFlag bufferVectorLibrary{FFlag::DebugLuauBufferVectorLibrary, true}; + ScopedFastFlag bufferVectorFastcalls{FFlag::DebugLuauBufferVectorFastcalls, true}; BufferCage cage; bufferCage = &cage; @@ -1338,38 +1393,8 @@ TEST_CASE("Math") runConformance("math.luau"); } -TEST_CASE("Integers") -{ - ScopedFastFlag ncgBufferInteger{FFlag::LuauCodegenBufferInteger, true}; - - if (FFlag::LuauIntegerType2 && FFlag::LuauIntegerLibrary) - { - runConformance( - "integers.luau", - [](lua_State* L) - { - setupNativeHelpers(L); - } - ); - - if (codegen && luau_codegen_supported()) - { - runConformance( - "integers_regspill.luau", - - [](lua_State* L) - { - setupNativeHelpers(L); - } - ); - } - } -} - TEST_CASE("Tables") { - ScopedFastFlag luauTableRobustOom{DFFlag::LuauTableRobustOom, true}; - reallocSizeLimit = 0; runConformance( @@ -2066,8 +2091,6 @@ TEST_CASE("CYield") TEST_CASE("Vector") { - ScopedFastFlag luauCompileNoFoldVectorEqW{FFlag::LuauCompileNoFoldVectorEqW, true}; - lua_CompileOptions copts = defaultOptions(); Luau::CodeGen::CompilationOptions nativeOpts = defaultCodegenOptions(); @@ -2169,11 +2192,6 @@ static void populateRTTI(lua_State* L, Luau::TypeId type) lua_pushstring(L, "number"); break; - case Luau::PrimitiveType::Integer: - if (FFlag::LuauIntegerType2) - lua_pushstring(L, "integer"); - break; - case Luau::PrimitiveType::String: lua_pushstring(L, "string"); break; @@ -2231,7 +2249,6 @@ static void populateRTTI(lua_State* L, Luau::TypeId type) TEST_CASE("Types") { - ScopedFastFlag integerType{FFlag::LuauIntegerType2, true}; ScopedFastFlag luauCoroutineFinallyAnalysis{FFlag::LuauCoroutineFinallyAnalysis, FFlag::LuauCoroutineFinally}; runConformance( @@ -2268,6 +2285,159 @@ TEST_CASE("Debug") runConformance("debug.luau"); } +TEST_CASE("LazyLoad") +{ + ScopedLazyLoad scopedLazyLoad; + + ScopedFastFlag sffs[] = { + {FFlag::LuauCoroutineFinally, true}, + {FFlag::DebugLuauUserDefinedClasses, true}, + {FFlag::DebugLuauUserDefinedClassesRuntime, true}, + {FFlag::LuauEmitCallFeedback, true}, + }; + + runConformance("lazyload.luau"); + + for (const char* name : + {"basic.luau", + "calls.luau", + "classes.luau", + "closure.luau", + "constructs.luau", + "coroutine.luau", + "debug.luau", + "errors.luau", + "events.luau", + "locals.luau", + "safeenv.luau", + "vararg.luau"}) + { + INFO(name); + runConformance(name); + } +} + +TEST_CASE("LazyLoadReleasesOwner") +{ + static int releases = 0; + auto release = [](void* owner) + { + releases++; + free(owner); + }; + + SUBCASE("LoadError") + { + releases = 0; + StateRef globalState(luaL_newstate(), lua_close); + lua_State* L = globalState.get(); + + // version 0 bytecode carries a compile error + static const char kError[] = "\0boom"; + char* bytecode = (char*)malloc(sizeof(kError) - 1); + memcpy(bytecode, kError, sizeof(kError) - 1); + + CHECK(luau_loadlazy(L, "=LazyLoadReleasesOwner", bytecode, sizeof(kError) - 1, 0, bytecode, release) != 0); + CHECK(releases == 1); + } + + SUBCASE("UnbuiltFunctions") + { + releases = 0; + { + StateRef globalState(luaL_newstate(), lua_close); + lua_State* L = globalState.get(); + + const std::string source = "local function never() return 1 end\nreturn never\n"; + size_t bytecodeSize = 0; + char* bytecode = luau_compile(source.data(), source.size(), nullptr, &bytecodeSize); + + REQUIRE(luau_loadlazy(L, "=LazyLoadReleasesOwner", bytecode, bytecodeSize, 0, bytecode, release) == 0); + CHECK(releases == 0); + + REQUIRE(lua_pcall(L, 0, 1, 0) == 0); + CHECK(releases == 0); + } + CHECK(releases == 1); + } + + SUBCASE("AllFunctionsBuilt") + { + releases = 0; + StateRef globalState(luaL_newstate(), lua_close); + lua_State* L = globalState.get(); + + const std::string source = "local function once() return 1 end\nreturn once()\n"; + size_t bytecodeSize = 0; + char* bytecode = luau_compile(source.data(), source.size(), nullptr, &bytecodeSize); + + REQUIRE(luau_loadlazy(L, "=LazyLoadReleasesOwner", bytecode, bytecodeSize, 0, bytecode, release) == 0); + REQUIRE(lua_pcall(L, 0, 1, 0) == 0); + CHECK(lua_tonumber(L, -1) == 1); + + // the last stub was built, so nothing needs the bytecode anymore + CHECK(releases == 1); + } + + SUBCASE("ReentrantBuildOfLastStub") + { + releases = 0; + StateRef globalState(luaL_newstate(), lua_close); + lua_State* L = globalState.get(); + luaL_openlibs(L); + // builds only resolve imports (and so run __index) in a safe environment + lua_setsafeenv(L, LUA_GLOBALSINDEX, true); + + // read resolves the import Lib.value when it is built, and __index calls read again: the inner build finishes read, the last + // stub, and drops its reference while the outer build of read still reads the chunk. The chunk must stay alive until the outer + // build ends, so the bytecode cannot have been released yet when the inner call returns. + lua_pushcfunction( + L, + [](lua_State* L) + { + lua_pushinteger(L, releases); + return 1; + }, + "releasesSoFar" + ); + lua_setglobal(L, "releasesSoFar"); + + // Lib is never assigned directly, so Lib.value compiles to an import (_G.Lib.value would not: _G is mutable) + const std::string source = R"( +local reentered = false +local releasedAtEntry = -1 +local releasedDuringBuild = -1 +local function read() return Lib.value end +_G.Lib = setmetatable({}, { __index = function() + if not reentered then + reentered = true + releasedAtEntry = releasesSoFar() + local value = read() + releasedDuringBuild = releasesSoFar() + return value + end + return 7 +end }) +local value = read() +return value, reentered, releasedAtEntry, releasedDuringBuild +)"; + size_t bytecodeSize = 0; + char* bytecode = luau_compile(source.data(), source.size(), nullptr, &bytecodeSize); + + REQUIRE(luau_loadlazy(L, "=LazyLoadReleasesOwner", bytecode, bytecodeSize, 0, bytecode, release) == 0); + CHECK(releases == 0); + + REQUIRE(lua_pcall(L, 0, 4, 0) == 0); + CHECK(lua_tonumber(L, -4) == 7); + // __index ran while read was still a stub, i.e. during its build + REQUIRE(lua_toboolean(L, -3)); + CHECK(lua_tonumber(L, -2) == 0); + // the inner build finished read, and the outer build still kept the bytecode alive + CHECK(lua_tonumber(L, -1) == 0); + CHECK(releases == 1); + } +} + bool findLocal(lua_State* L, int level, const char* name) { int n = 1; @@ -2292,6 +2462,8 @@ TEST_CASE("Debugger") static bool singlestep = false; static int stephits = 0; + bool lazy = false; + SUBCASE("") { singlestep = false; @@ -2300,6 +2472,13 @@ TEST_CASE("Debugger") { singlestep = true; } + SUBCASE("LazyLoad") + { + singlestep = false; + lazy = true; + } + + ScopedLazyLoad scopedLazyLoad{lazy}; breakhits = 0; interruptedthread = nullptr; @@ -4791,6 +4970,7 @@ TEST_CASE("Native") ScopedFastFlag reloadLargeConstOffset{FFlag::LuauCodegenA64ReloadLargeConstOffset, true}; ScopedFastFlag luauCodegenDseTrackTagInvalidation{FFlag::LuauCodegenDseTrackTagInvalidation, true}; ScopedFastFlag luauCodegenCmpAnySideEffecting{FFlag::LuauCodegenCmpAnySideEffecting, true}; + ScopedFastFlag luauCodegenFastcallAnalysisLimit{FFlag::LuauCodegenFastcallAnalysisLimit, true}; // This tests requires code to run natively, otherwise all 'is_native' checks will fail if (!codegen || !luau_codegen_supported()) @@ -4846,28 +5026,6 @@ TEST_CASE("Native") ); } -TEST_CASE("NativeIntegerSpills") -{ - ScopedFastFlag integerType{FFlag::LuauIntegerType2, true}; - - lua_CompileOptions copts = defaultOptions(); - - SUBCASE("O0") - { - copts.optimizationLevel = 0; - } - SUBCASE("O1") - { - copts.optimizationLevel = 1; - } - SUBCASE("O2") - { - copts.optimizationLevel = 2; - } - - runConformance("native_integer_spills.luau", nullptr, nullptr, nullptr, &copts); -} - TEST_CASE("NativeTypeAnnotations") { // This tests requires code to run natively, otherwise all 'is_native' checks will fail @@ -5045,6 +5203,7 @@ static std::string getRecordedFastPathCounters(lua_State* L, const char* global) TEST_CASE("Promotion") { ScopedFastFlag luauRuntimeFeedback{FFlag::LuauRuntimeFeedback, true}; + ScopedFastFlag luauCodegenRuntimeFeedback{FFlag::LuauCodegenRuntimeFeedback, true}; ScopedFastFlag luauPromoteProto{FFlag::LuauPromoteProto, true}; Luau::CodeGen::CompilationOptions nativeOpts = defaultCodegenOptions(); @@ -5060,6 +5219,38 @@ TEST_CASE("Promotion") nativeOpts.userdataTypes = kUserdataRunTypes; + if (verbose) + { + nativeOpts.runtimeBuildLog = [](void* context, const std::string& message) + { + printf("codegen: %.*s\n", int(message.length()), message.data()); + }; + + nativeOpts.runtimeBuildResult = + [](void* context, const Luau::CodeGen::CompilationResult& result, const struct Luau::CodeGen::CompilationStats& stats) + { + printf("rebuild: status %s, %d proto(s) failed\n", + Luau::CodeGen::toString(result.result).c_str(), + int(result.protoFailures.size()) + ); + + printf( + "rebuild: bc %d bytes, native %d + %d bytes, meta %d bytes\n", + int(stats.bytecodeSizeBytes), + int(stats.nativeCodeSizeBytes), + int(stats.nativeDataSizeBytes), + int(stats.nativeMetadataSizeBytes) + ); + printf( + "rebuild: %d function(s) total, %d compiled, %d bound in %.3fms\n", + int(stats.functionsTotal), + int(stats.functionsCompiled), + int(stats.functionsBound), + stats.compilationTimeSec * 1000.0 + ); + }; + } + StateRef globalState = runConformance( "promotion.luau", [](lua_State* L) @@ -5256,7 +5447,6 @@ TEST_CASE("Classes") {FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::DebugLuauUserDefinedClassesRuntime, true}, {FFlag::LuauEmitCallFeedback, true}, - {FFlag::LuauBytecodeCostModel, true} }; runConformance("classes.luau"); @@ -5596,6 +5786,64 @@ TEST_CASE("IrInstructionLimit") CHECK(nativeStats.functionsCompiled < 101); } +TEST_CASE("PromotionInstructionLimit") +{ + if (!codegen || !luau_codegen_supported()) + return; + + ScopedFastFlag luauRuntimeFeedback{FFlag::LuauRuntimeFeedback, true}; + ScopedFastFlag luauCodegenRuntimeFeedback{FFlag::LuauCodegenRuntimeFeedback, true}; + ScopedFastFlag luauPromoteProto{FFlag::LuauPromoteProto, true}; + ScopedFastInt codegenHeuristicsInstructionLimit{FInt::CodegenHeuristicsInstructionLimit, 100}; + + const char* source = R"( +function fn(...) + local p1, p2 = ... + for i = 1, 100000 do + p1 += 1 + end + return { + p1*1, p2+1, p1*2, p2+2, p1*3, p2+3, p1*4, p2+4, p1*5, p2+5, + p1*6, p2+6, p1*7, p2+7, p1*8, p2+8, p1*9, p2+9, p1*10, p2+10, + } +end +assert(fn(0, 2)[1] == 100000) +)"; + + std::vector results; + Luau::CodeGen::CompilationOptions nativeOptions = defaultCodegenOptions(); + nativeOptions.runtimeBuildContext = &results; + nativeOptions.runtimeBuildResult = [](void* context, const Luau::CodeGen::CompilationResult& result, const Luau::CodeGen::CompilationStats& stats) + { + static_cast*>(context)->push_back(result); + CHECK(stats.functionsCompiled == 0); + }; + + StateRef globalState(luaL_newstate(), lua_close); + lua_State* L = globalState.get(); + luau_codegen_create(L); + Luau::CodeGen::enableRuntimeCompilation(L, nativeOptions, /* promoteVmFunctions */ true); + + luaL_openlibs(L); + luaL_sandbox(L); + luaL_sandboxthread(L); + lua_gc(L, LUA_GCSTOP, 0); + + std::string bytecode = Luau::compile(source); + REQUIRE(luau_load(L, "=PromotionInstructionLimit", bytecode.data(), bytecode.size(), 0) == 0); + REQUIRE(lua_pcall(L, 0, 0, 0) == LUA_OK); + CHECK(results.empty()); + + // A full GC examines hot VM functions and commits their native promotions + lua_gc(L, LUA_GCCOLLECT, 0); + + REQUIRE(results.size() == 1); + REQUIRE(results.front().protoFailures.size() == 1); + CHECK(results.front().protoFailures.front().result == Luau::CodeGen::CodeGenCompilationResult::CodeGenOverflowInstructionLimit); + CHECK(results.front().protoFailures.front().debugname == "fn"); + CHECK(results.front().protoFailures.front().irInstCount >= 100); +} + TEST_CASE("BytecodeDistributionPerFunctionTest") { const char* source = R"( @@ -5850,7 +6098,6 @@ TEST_CASE("ClassInheritanceRepeatedCallMemberOffsetCorruption") {FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::DebugLuauUserDefinedClassesRuntime, true}, {FFlag::LuauEmitCallFeedback, true}, - {FFlag::LuauBytecodeCostModel, true}, }; StateRef globalState(luaL_newstate(), lua_close); @@ -5909,7 +6156,6 @@ TEST_CASE("SandboxFreezesVectorMetatable") TEST_CASE("JitInlinerLongJump") { ScopedFastFlag luauEmitCallFeedback{FFlag::LuauEmitCallFeedback, true}; - ScopedFastFlag luauCompileCallFbRemap{FFlag::LuauCompileCallFbRemap, true}; std::string source; source += "local function target(x) return x + 1 end\n"; diff --git a/tests/Error.test.cpp b/tests/Error.test.cpp index b6495871b..d784fc0c5 100644 --- a/tests/Error.test.cpp +++ b/tests/Error.test.cpp @@ -18,8 +18,6 @@ TEST_CASE("TypeError_code_should_return_nonzero_code") TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_names_show_instead_of_tables") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - getFrontend().options.retainFullTypeGraphs = false; CheckResult result = check(R"( diff --git a/tests/Fixture.cpp b/tests/Fixture.cpp index e2aa87477..787c52fac 100644 --- a/tests/Fixture.cpp +++ b/tests/Fixture.cpp @@ -34,11 +34,6 @@ LUAU_FASTFLAGVARIABLE(DebugLuauForceAllOldSolverTests); LUAU_FASTINT(LuauStackGuardThreshold) LUAU_FASTFLAG(DebugLuauForceOldSolver) -LUAU_FASTFLAG(DebugLuauParseExactTables) -LUAU_FASTFLAG(DebugLuauExactTableTypes) - -LUAU_FASTFLAGVARIABLE(DebugLuauForceExactTables) -LUAU_FASTFLAGVARIABLE(DebugLuauRunFailingExactTableTests) extern std::optional randomSeed; // tests/main.cpp @@ -1052,8 +1047,6 @@ doctest::String toString(TableState state) return "TableState::Free"; case TableState::Generic: return "TableState::Generic"; - case TableState::Exact: - return "TableState::Exact"; default: LUAU_ASSERT(0); diff --git a/tests/Fixture.h b/tests/Fixture.h index 25c8e5eaa..15cade7cc 100644 --- a/tests/Fixture.h +++ b/tests/Fixture.h @@ -30,10 +30,6 @@ LUAU_FASTFLAG(LuauBetterMetatableStringification); LUAU_FASTFLAG(DebugLuauFreezeArena) LUAU_FASTFLAG(DebugLuauForceAllNewSolverTests) LUAU_FASTFLAG(DebugLuauForceAllOldSolverTests) -LUAU_FASTFLAG(DebugLuauExactTableTypes) -LUAU_FASTFLAG(DebugLuauParseExactTables) -LUAU_FASTFLAG(DebugLuauForceExactTables) -LUAU_FASTFLAG(DebugLuauRunFailingExactTableTests) LUAU_FASTFLAG(DebugLuauAlwaysShowConstraintSolvingIncomplete); LUAU_FASTFLAG(DebugLuauForceOldSolver) @@ -51,14 +47,6 @@ LUAU_FASTFLAG(LuauSplitIceHandler) #define LUAU_CONCAT_IMPL(x, y) x##y #define LUAU_CONCAT(x, y) LUAU_CONCAT_IMPL(x, y) -#define DOES_NOT_PASS_WITH_EXACT_TABLES() \ - ScopedFastFlag LUAU_CONCAT(sff_, __COUNTER__){FFlag::DebugLuauExactTableTypes, FFlag::DebugLuauRunFailingExactTableTests}; \ - ScopedFastFlag LUAU_CONCAT(sff_, __COUNTER__){FFlag::DebugLuauParseExactTables, FFlag::DebugLuauRunFailingExactTableTests}; \ - ScopedFastFlag LUAU_CONCAT(sff_, __COUNTER__) \ - { \ - FFlag::DebugLuauForceExactTables, FFlag::DebugLuauRunFailingExactTableTests \ - } - // If CALLGRIND is on, then disable the timeout (doctest treats a timeout of 0 as disabled). #ifdef CALLGRIND constexpr double LUAU_TIMEOUT = 0.0; @@ -203,9 +191,6 @@ struct Fixture ScopedFastFlag sff_LuauBetterInferredGenericNames{FFlag::LuauBetterInferredGenericNames, true}; ScopedFastFlag sff_LuauSplitIceHandler{FFlag::LuauSplitIceHandler, true}; - ScopedFastFlag sff_ParseExactTables{FFlag::DebugLuauParseExactTables, FFlag::DebugLuauForceExactTables}; - ScopedFastFlag sff_ExactTableTypes{FFlag::DebugLuauExactTableTypes, FFlag::DebugLuauForceExactTables}; - TestFileResolver fileResolver; TestConfigResolver configResolver; NullModuleResolver moduleResolver; diff --git a/tests/FragmentAutocomplete.test.cpp b/tests/FragmentAutocomplete.test.cpp index 93ac3eb7e..5c9dbd47d 100644 --- a/tests/FragmentAutocomplete.test.cpp +++ b/tests/FragmentAutocomplete.test.cpp @@ -1673,8 +1673,6 @@ TEST_SUITE_BEGIN("FragmentAutocompleteTests"); TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "multiple_fragment_autocomplete") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ToStringOptions opt; opt.exhaustive = true; opt.exhaustive = true; @@ -3095,8 +3093,6 @@ end) TEST_CASE_FIXTURE(FragmentAutocompleteFixture, "fragment_autocomplete_ensures_memory_isolation") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ToStringOptions opt; opt.exhaustive = true; opt.exhaustive = true; diff --git a/tests/Frontend.test.cpp b/tests/Frontend.test.cpp index 17f343bcc..d8cdf07b1 100644 --- a/tests/Frontend.test.cpp +++ b/tests/Frontend.test.cpp @@ -2045,8 +2045,6 @@ TEST_CASE_FIXTURE(FrontendFixture, "parse_types") TEST_CASE_FIXTURE(FrontendFixture, "generic_P_widening_with_cross_module_recursive_type") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_OLD_SOLVER_GUARD(); // Module A: exports a recursive type and a component that uses it. diff --git a/tests/Generalization.test.cpp b/tests/Generalization.test.cpp index 48613242b..0af0dcb78 100644 --- a/tests/Generalization.test.cpp +++ b/tests/Generalization.test.cpp @@ -406,8 +406,6 @@ TEST_CASE_FIXTURE(Fixture, "generics_dont_leak_into_callback") TEST_CASE_FIXTURE(Fixture, "generics_dont_leak_into_callback_2") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( diff --git a/tests/IrAssembly.test.cpp b/tests/IrAssembly.test.cpp index 061471d04..b73ab4960 100644 --- a/tests/IrAssembly.test.cpp +++ b/tests/IrAssembly.test.cpp @@ -112,7 +112,6 @@ class IrAssemblyFixture int tnil = parseTagName("tnil"); int tboolean = parseTagName("tboolean"); int tnumber = parseTagName("tnumber"); - int tinteger = parseTagName("tinteger"); int tvector = parseTagName("tvector"); int tstring = parseTagName("tstring"); int ttable = parseTagName("ttable"); diff --git a/tests/IrBuilder.test.cpp b/tests/IrBuilder.test.cpp index 5d2a9b888..04cb2322b 100644 --- a/tests/IrBuilder.test.cpp +++ b/tests/IrBuilder.test.cpp @@ -12,13 +12,12 @@ #include +LUAU_FASTFLAG(LuauCodegenForwardSplitStore) LUAU_FASTFLAG(DebugLuauAbortingChecks) -LUAU_FASTFLAG(LuauCodegenInteger3) -LUAU_FASTFLAG(LuauIntegerType2) -LUAU_FASTFLAG(LuauIntegerLibrary) -LUAU_FASTFLAG(LuauCodegenPropagateFallbackTags) LUAU_FASTFLAG(LuauCodegenCmpAnySideEffecting) +LUAU_FASTFLAG(LuauCodegenMultiLaneDot) LUAU_FASTFLAG(LuauCodegenX64ConflictCheck) +LUAU_FASTFLAG(LuauCodegenExitSyncExpectedTag) using namespace Luau::CodeGen; @@ -120,7 +119,6 @@ class IrBuilderFixture int tnil = parseTagName("tnil"); int tboolean = parseTagName("tboolean"); int tnumber = parseTagName("tnumber"); - int tinteger = parseTagName("tinteger"); int tvector = parseTagName("tvector"); int tstring = parseTagName("tstring"); int ttable = parseTagName("ttable"); @@ -638,178 +636,8 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Bit32RangeReduction") )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64Arithmetic") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // ADD_INT64 constant folding - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::ADD_INT64, build.constInt64(10), build.constInt64(20))); - // ADD_INT64 wrapping (unsigned arithmetic) - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::ADD_INT64, build.constInt64(INT64_MAX), build.constInt64(1))); - - // SUB_INT64 constant folding - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::SUB_INT64, build.constInt64(10), build.constInt64(20))); - // SUB_INT64 wrapping - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::SUB_INT64, build.constInt64(INT64_MIN), build.constInt64(1))); - - // MUL_INT64 constant folding - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::MUL_INT64, build.constInt64(6), build.constInt64(7))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, 30i - STORE_INT64 R1, -9223372036854775808i - STORE_INT64 R2, -10i - STORE_INT64 R3, 9223372036854775807i - STORE_INT64 R4, 42i - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64Bitwise") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - IrOp unk = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - - // BITAND_INT64 constant folding - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::BITAND_INT64, build.constInt64(0xFE), build.constInt64(0x0E))); - // BITAND_INT64 identity: x & 0 = 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::BITAND_INT64, unk, build.constInt64(0))); - // BITAND_INT64 identity: 0 & x = 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::BITAND_INT64, build.constInt64(0), unk)); - // BITAND_INT64 identity: x & -1 = x - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::BITAND_INT64, unk, build.constInt64(-1))); - // BITAND_INT64 identity: -1 & x = x - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::BITAND_INT64, build.constInt64(-1), unk)); - - // BITXOR_INT64 constant folding - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::BITXOR_INT64, build.constInt64(0xFE), build.constInt64(0x0E))); - // BITXOR_INT64 identity: x ^ 0 = x - build.inst(IrCmd::STORE_INT64, build.vmReg(6), build.inst(IrCmd::BITXOR_INT64, unk, build.constInt64(0))); - // BITXOR_INT64 identity: 0 ^ x = x - build.inst(IrCmd::STORE_INT64, build.vmReg(7), build.inst(IrCmd::BITXOR_INT64, build.constInt64(0), unk)); - - // BITOR_INT64 constant folding - build.inst(IrCmd::STORE_INT64, build.vmReg(8), build.inst(IrCmd::BITOR_INT64, build.constInt64(0xF0), build.constInt64(0x0E))); - // BITOR_INT64 identity: x | 0 = x - build.inst(IrCmd::STORE_INT64, build.vmReg(9), build.inst(IrCmd::BITOR_INT64, unk, build.constInt64(0))); - // BITOR_INT64 identity: 0 | x = x - build.inst(IrCmd::STORE_INT64, build.vmReg(10), build.inst(IrCmd::BITOR_INT64, build.constInt64(0), unk)); - // BITOR_INT64 identity: x | -1 = -1 - build.inst(IrCmd::STORE_INT64, build.vmReg(11), build.inst(IrCmd::BITOR_INT64, unk, build.constInt64(-1))); - // BITOR_INT64 identity: -1 | x = -1 - build.inst(IrCmd::STORE_INT64, build.vmReg(12), build.inst(IrCmd::BITOR_INT64, build.constInt64(-1), unk)); - - // BITNOT_INT64 constant folding - build.inst(IrCmd::STORE_INT64, build.vmReg(13), build.inst(IrCmd::BITNOT_INT64, build.constInt64(0x0E))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = LOAD_INT64 R0 - STORE_INT64 R0, 14i - STORE_INT64 R1, 0i - STORE_INT64 R2, 0i - STORE_INT64 R3, %0 - STORE_INT64 R4, %0 - STORE_INT64 R5, 240i - STORE_INT64 R6, %0 - STORE_INT64 R7, %0 - STORE_INT64 R8, 254i - STORE_INT64 R9, %0 - STORE_INT64 R10, %0 - STORE_INT64 R11, -1i - STORE_INT64 R12, -1i - STORE_INT64 R13, -15i - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ShiftsAndRotates") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // BITLSHIFT_INT64 - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::BITLSHIFT_INT64, build.constInt64(0xF), build.constInt64(4))); - // BITLSHIFT_INT64 negative shift reverses direction - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::BITLSHIFT_INT64, build.constInt64(0xF0), build.constInt64(-4))); - // BITLSHIFT_INT64 out-of-range returns 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::BITLSHIFT_INT64, build.constInt64(0xF), build.constInt64(64))); - - // BITRSHIFT_INT64 - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::BITRSHIFT_INT64, build.constInt64(0xF0), build.constInt64(4))); - - // BITARSHIFT_INT64 (sign-extending) - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::BITARSHIFT_INT64, build.constInt64(-16), build.constInt64(2))); - - // BITLROTATE_INT64 - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::BITLROTATE_INT64, build.constInt64(1), build.constInt64(63))); - // BITRROTATE_INT64 - build.inst(IrCmd::STORE_INT64, build.vmReg(6), build.inst(IrCmd::BITRROTATE_INT64, build.constInt64(1), build.constInt64(1))); - - // BITCOUNTLZ_INT64 - build.inst(IrCmd::STORE_INT64, build.vmReg(7), build.inst(IrCmd::BITCOUNTLZ_INT64, build.constInt64(0xFF00))); - build.inst(IrCmd::STORE_INT64, build.vmReg(8), build.inst(IrCmd::BITCOUNTLZ_INT64, build.constInt64(0))); - - // BITCOUNTRZ_INT64 - build.inst(IrCmd::STORE_INT64, build.vmReg(9), build.inst(IrCmd::BITCOUNTRZ_INT64, build.constInt64(0xFF00))); - build.inst(IrCmd::STORE_INT64, build.vmReg(10), build.inst(IrCmd::BITCOUNTRZ_INT64, build.constInt64(0))); - - // BYTESWAP_INT64 - build.inst(IrCmd::STORE_INT64, build.vmReg(11), build.inst(IrCmd::BYTESWAP_INT64, build.constInt64(0x0102030405060708LL))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, 240i - STORE_INT64 R1, 15i - STORE_INT64 R2, 0i - STORE_INT64 R3, 15i - STORE_INT64 R4, -4i - STORE_INT64 R5, -9223372036854775808i - STORE_INT64 R6, -9223372036854775808i - STORE_INT64 R7, 48i - STORE_INT64 R8, 64i - STORE_INT64 R9, 8i - STORE_INT64 R10, 64i - STORE_INT64 R11, 578437695752307201i - RETURN 0u - -)"); -} - TEST_CASE_FIXTURE(IrBuilderFixture, "Int64Comparisons") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); build.beginBlock(block); @@ -882,52 +710,53 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64Comparisons") )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpFold") +TEST_CASE_FIXTURE(IrBuilderFixture, "Int64Arithmetic") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); - IrOp fallback = build.block(IrBlockKind::Internal); - build.beginBlock(block); - // CHECK_CMP_INT64 that passes: should be killed (condition is true) - build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(0), build.constInt64(0), build.cond(IrCondition::NotEqual), fallback); - // CHECK_CMP_INT64 that passes: condition is true, should be killed - build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(10), build.constInt64(20), build.cond(IrCondition::Less), fallback); - // CHECK_CMP_INT64 used for division-by-zero guard: divisor != 0 - build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(5), build.constInt64(0), build.cond(IrCondition::NotEqual), fallback); + const auto checkResult = [this](int reg, IrOp result, int64_t expected) + { + IrOp equal = build.inst(IrCmd::CMP_INT64, result, build.constInt64(expected), build.cond(IrCondition::Equal)); + build.inst(IrCmd::STORE_INT, build.vmReg(reg), equal); + }; + checkResult(0, build.inst(IrCmd::ADD_INT64, build.constInt64(10), build.constInt64(20)), 30); + checkResult(1, build.inst(IrCmd::ADD_INT64, build.constInt64(INT64_MAX), build.constInt64(1)), INT64_MIN); + checkResult(2, build.inst(IrCmd::SUB_INT64, build.constInt64(10), build.constInt64(20)), -10); + checkResult(3, build.inst(IrCmd::SUB_INT64, build.constInt64(INT64_MIN), build.constInt64(1)), INT64_MAX); + checkResult(4, build.inst(IrCmd::MUL_INT64, build.constInt64(6), build.constInt64(7)), 42); build.inst(IrCmd::RETURN, build.constUint(0)); - build.beginBlock(fallback); - build.inst(IrCmd::RETURN, build.constUint(1)); - updateUseCounts(build.function); constantFold(); CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( bb_0: - JUMP bb_1 - -bb_1: - RETURN 1u + STORE_INT R0, 1i + STORE_INT R1, 1i + STORE_INT R2, 1i + STORE_INT R3, 1i + STORE_INT R4, 1i + RETURN 0u )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpFoldPass") +TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpFold") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); IrOp fallback = build.block(IrBlockKind::Internal); build.beginBlock(block); - // CHECK_CMP_INT64 where condition is true: guard passes, gets killed + // CHECK_CMP_INT64 that passes: should be killed (condition is true) + build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(0), build.constInt64(0), build.cond(IrCondition::NotEqual), fallback); + // CHECK_CMP_INT64 that passes: condition is true, should be killed + build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(10), build.constInt64(20), build.cond(IrCondition::Less), fallback); + // CHECK_CMP_INT64 used for division-by-zero guard: divisor != 0 build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(5), build.constInt64(0), build.cond(IrCondition::NotEqual), fallback); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(42)); + build.inst(IrCmd::RETURN, build.constUint(0)); build.beginBlock(fallback); @@ -938,224 +767,37 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpFoldPass") CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( bb_0: - STORE_INT64 R0, 42i - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ArithmeticExtended") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // MUL_INT64 overflow wrapping - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::MUL_INT64, build.constInt64(INT64_MAX), build.constInt64(2))); - // MUL_INT64 with zero - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::MUL_INT64, build.constInt64(INT64_MAX), build.constInt64(0))); - // MUL_INT64 with -1 (negation via multiply) - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::MUL_INT64, build.constInt64(42), build.constInt64(-1))); - - // ADD_INT64 with zero (identity) - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::ADD_INT64, build.constInt64(100), build.constInt64(0))); - // SUB_INT64 self (should be zero) - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::SUB_INT64, build.constInt64(100), build.constInt64(100))); - - // ADD_INT64 negative numbers - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::ADD_INT64, build.constInt64(-10), build.constInt64(-20))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, -2i - STORE_INT64 R1, 0i - STORE_INT64 R2, -42i - STORE_INT64 R3, 100i - STORE_INT64 R4, 0i - STORE_INT64 R5, -30i - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ShiftEdgeCases") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // BITRSHIFT_INT64 negative shift reverses to left shift - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::BITRSHIFT_INT64, build.constInt64(0xF), build.constInt64(-4))); - // BITRSHIFT_INT64 out-of-range returns 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::BITRSHIFT_INT64, build.constInt64(0xF), build.constInt64(64))); - - // BITARSHIFT_INT64 with negative number, large shift (>63) fills with sign - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::BITARSHIFT_INT64, build.constInt64(-1), build.constInt64(64))); - // BITARSHIFT_INT64 with positive number, large shift (>63) fills with 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::BITARSHIFT_INT64, build.constInt64(1), build.constInt64(64))); - // BITARSHIFT_INT64 negative shift reverses to left shift - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::BITARSHIFT_INT64, build.constInt64(0xF), build.constInt64(-4))); - // BITARSHIFT_INT64 large negative shift (<-63) returns 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::BITARSHIFT_INT64, build.constInt64(0xF), build.constInt64(-64))); - - // BITLSHIFT_INT64 with 0 shift amount - build.inst(IrCmd::STORE_INT64, build.vmReg(6), build.inst(IrCmd::BITLSHIFT_INT64, build.constInt64(0xFF), build.constInt64(0))); - - // BITLROTATE_INT64 with full rotation (mod 64 = 0) - build.inst(IrCmd::STORE_INT64, build.vmReg(7), build.inst(IrCmd::BITLROTATE_INT64, build.constInt64(0xFF), build.constInt64(64))); - // BITRROTATE_INT64 with 0 rotation - build.inst(IrCmd::STORE_INT64, build.vmReg(8), build.inst(IrCmd::BITRROTATE_INT64, build.constInt64(0xFF), build.constInt64(0))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, 240i - STORE_INT64 R1, 0i - STORE_INT64 R2, -1i - STORE_INT64 R3, 0i - STORE_INT64 R4, 240i - STORE_INT64 R5, 0i - STORE_INT64 R6, 255i - STORE_INT64 R7, 255i - STORE_INT64 R8, 255i - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64BitwiseExtended") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // BITNOT_INT64 of 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::BITNOT_INT64, build.constInt64(0))); - // BITNOT_INT64 of -1 - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::BITNOT_INT64, build.constInt64(-1))); - - // BITAND_INT64 self identity (both const equal) - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::BITAND_INT64, build.constInt64(0xABCD), build.constInt64(0xABCD))); - // BITXOR_INT64 same value (both const equal) = 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::BITXOR_INT64, build.constInt64(0xABCD), build.constInt64(0xABCD))); - // BITOR_INT64 with self - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::BITOR_INT64, build.constInt64(0xABCD), build.constInt64(0xABCD))); - - // BITCOUNTLZ_INT64 of 1 (63 leading zeros for 64-bit) - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::BITCOUNTLZ_INT64, build.constInt64(1))); - // BITCOUNTLZ_INT64 of -1 (all bits set, 0 leading zeros) - build.inst(IrCmd::STORE_INT64, build.vmReg(6), build.inst(IrCmd::BITCOUNTLZ_INT64, build.constInt64(-1))); - - // BITCOUNTRZ_INT64 of 1 (0 trailing zeros) - build.inst(IrCmd::STORE_INT64, build.vmReg(7), build.inst(IrCmd::BITCOUNTRZ_INT64, build.constInt64(1))); - // BITCOUNTRZ_INT64 of -1 (0 trailing zeros) - build.inst(IrCmd::STORE_INT64, build.vmReg(8), build.inst(IrCmd::BITCOUNTRZ_INT64, build.constInt64(-1))); - // BITCOUNTRZ_INT64 of a power of 2 - build.inst(IrCmd::STORE_INT64, build.vmReg(9), build.inst(IrCmd::BITCOUNTRZ_INT64, build.constInt64(1LL << 32))); - - // BYTESWAP_INT64 of 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(10), build.inst(IrCmd::BYTESWAP_INT64, build.constInt64(0))); - // BYTESWAP_INT64 of -1 (all bytes 0xFF, swaps to itself) - build.inst(IrCmd::STORE_INT64, build.vmReg(11), build.inst(IrCmd::BYTESWAP_INT64, build.constInt64(-1))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); + JUMP bb_1 - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, -1i - STORE_INT64 R1, 0i - STORE_INT64 R2, 43981i - STORE_INT64 R3, 0i - STORE_INT64 R4, 43981i - STORE_INT64 R5, 63i - STORE_INT64 R6, 0i - STORE_INT64 R7, 0i - STORE_INT64 R8, 0i - STORE_INT64 R9, 32i - STORE_INT64 R10, 0i - STORE_INT64 R11, -1i - RETURN 0u +bb_1: + RETURN 1u )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivisionOpsPreserved") +TEST_CASE_FIXTURE(IrBuilderFixture, "RawInt64OutOfRangeConversion") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); - build.beginBlock(block); - - IrOp a = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - IrOp b = build.inst(IrCmd::LOAD_INT64, build.vmReg(1)); - - // Division operations don't constant-fold (divisor may be zero at runtime), verify they are preserved - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::DIV_INT64, a, b)); - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::IDIV_INT64, a, b)); - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::UDIV_INT64, a, b)); - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::REM_INT64, a, b)); - build.inst(IrCmd::STORE_INT64, build.vmReg(6), build.inst(IrCmd::UREM_INT64, a, b)); - build.inst(IrCmd::STORE_INT64, build.vmReg(7), build.inst(IrCmd::MOD_INT64, a, b)); - + IrOp conversion = build.inst(IrCmd::NUM_TO_INT64, build.constDouble(1e19)); + IrOp equal = build.inst(IrCmd::CMP_INT64, conversion, build.constInt64(0), build.cond(IrCondition::Equal)); + build.inst(IrCmd::STORE_INT, build.vmReg(0), equal); build.inst(IrCmd::RETURN, build.constUint(0)); updateUseCounts(build.function); constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = LOAD_INT64 R0 - %1 = LOAD_INT64 R1 - %2 = DIV_INT64 %0, %1 - STORE_INT64 R2, %2 - %4 = IDIV_INT64 %0, %1 - STORE_INT64 R3, %4 - %6 = UDIV_INT64 %0, %1 - STORE_INT64 R4, %6 - %8 = REM_INT64 %0, %1 - STORE_INT64 R5, %8 - %10 = UREM_INT64 %0, %1 - STORE_INT64 R6, %10 - %12 = MOD_INT64 %0, %1 - STORE_INT64 R7, %12 - RETURN 0u - -)"); + CHECK(build.function.instOp(conversion).cmd == IrCmd::NUM_TO_INT64); } -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivGuardFoldKnownNonZero") +TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpFoldPass") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); IrOp fallback = build.block(IrBlockKind::Internal); build.beginBlock(block); - IrOp a = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - - // When divisor is a known non-zero constant, the CHECK_CMP_INT64 guard folds away - build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(7), build.constInt64(0), build.cond(IrCondition::NotEqual), fallback); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::DIV_INT64, a, build.constInt64(7))); + // CHECK_CMP_INT64 where condition is true: guard passes, gets killed + build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(5), build.constInt64(0), build.cond(IrCondition::NotEqual), fallback); build.inst(IrCmd::RETURN, build.constUint(0)); build.beginBlock(fallback); @@ -1166,9 +808,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivGuardFoldKnownNonZero") CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( bb_0: - %0 = LOAD_INT64 R0 - %2 = DIV_INT64 %0, 7i - STORE_INT64 R1, %2 RETURN 0u )"); @@ -1176,8 +815,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivGuardFoldKnownNonZero") TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivGuardZeroDivisorJumps") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); IrOp fallback = build.block(IrBlockKind::Internal); @@ -1185,7 +822,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivGuardZeroDivisorJumps") // When divisor is known-zero, the guard condition fails and we jump to fallback build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(0), build.constInt64(0), build.cond(IrCondition::NotEqual), fallback); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(99)); build.inst(IrCmd::RETURN, build.constUint(0)); build.beginBlock(fallback); @@ -1204,173 +840,8 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivGuardZeroDivisorJumps") )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64SelectPreservedWithDifferentBranches") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - IrOp a = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - IrOp b = build.inst(IrCmd::LOAD_INT64, build.vmReg(1)); - - // SELECT_INT64 with different result branches must be preserved through constant folding - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::SELECT_INT64, a, b, a, b, build.cond(IrCondition::Less))); - // SELECT_INT64 with same value for comparison but different results - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::SELECT_INT64, a, a, a, b, build.cond(IrCondition::LessEqual))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = LOAD_INT64 R0 - %1 = LOAD_INT64 R1 - %2 = SELECT_INT64 %0, %1, %0, %1, lt - STORE_INT64 R2, %2 - %4 = SELECT_INT64 %0, %0, %0, %1, le - STORE_INT64 R3, %4 - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64NegationConstFold") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // Negation is implemented as SUB_INT64(0, x). With constant x, should fold. - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::SUB_INT64, build.constInt64(0), build.constInt64(42))); - // Negation of INT64_MIN wraps to itself - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::SUB_INT64, build.constInt64(0), build.constInt64(INT64_MIN))); - // Negation of 0 is 0 - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::SUB_INT64, build.constInt64(0), build.constInt64(0))); - // Negation of -1 - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::SUB_INT64, build.constInt64(0), build.constInt64(-1))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, -42i - STORE_INT64 R1, -9223372036854775808i - STORE_INT64 R2, 0i - STORE_INT64 R3, 1i - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ConversionConstProp") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // INT64_TO_NUM followed by duplicate INT64_TO_NUM of same source should be deduped by constprop - IrOp val = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - IrOp asNum1 = build.inst(IrCmd::INT64_TO_NUM, val); - IrOp asNum2 = build.inst(IrCmd::INT64_TO_NUM, val); - build.inst(IrCmd::STORE_DOUBLE, build.vmReg(1), asNum1); - build.inst(IrCmd::STORE_DOUBLE, build.vmReg(2), asNum2); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constPropInBlockChains(build); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = LOAD_INT64 R0 - %1 = INT64_TO_NUM %0 - STORE_DOUBLE R1, %1 - STORE_DOUBLE R2, %1 - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ConversionDedup") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // Multiple NUM_TO_INT64 of the same source should be deduplicated by constprop - IrOp dbl = build.inst(IrCmd::LOAD_DOUBLE, build.vmReg(0)); - IrOp i1 = build.inst(IrCmd::NUM_TO_INT64, dbl); - IrOp i2 = build.inst(IrCmd::NUM_TO_INT64, dbl); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), i1); - build.inst(IrCmd::STORE_INT64, build.vmReg(2), i2); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constPropInBlockChains(build); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = LOAD_DOUBLE R0 - %1 = NUM_TO_INT64 %0 - STORE_INT64 R1, %1 - STORE_INT64 R2, %1 - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivisionStoreForward") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // Store a division result, then load it back; the load should be forwarded - IrOp a = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - IrOp b = build.inst(IrCmd::LOAD_INT64, build.vmReg(1)); - IrOp divResult = build.inst(IrCmd::DIV_INT64, a, b); - build.inst(IrCmd::STORE_INT64, build.vmReg(2), divResult); - - IrOp loaded = build.inst(IrCmd::LOAD_INT64, build.vmReg(2)); - build.inst(IrCmd::STORE_INT64, build.vmReg(3), loaded); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constPropInBlockChains(build); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = LOAD_INT64 R0 - %1 = LOAD_INT64 R1 - %2 = DIV_INT64 %0, %1 - STORE_INT64 R2, %2 - STORE_INT64 R3, %2 - RETURN 0u - -)"); -} - TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpUnsignedFold") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); IrOp fallback = build.block(IrBlockKind::Internal); @@ -1378,7 +849,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpUnsignedFold") // Unsigned comparison: -1 as uint64 is UINT64_MAX, which is > 0 build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(-1), build.constInt64(0), build.cond(IrCondition::UnsignedGreater), fallback); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(1)); build.inst(IrCmd::RETURN, build.constUint(0)); build.beginBlock(fallback); @@ -1390,7 +860,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpUnsignedFold") // Guard passes (UINT64_MAX > 0 is true), so it should be eliminated CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( bb_0: - STORE_INT64 R0, 1i RETURN 0u )"); @@ -1398,8 +867,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpUnsignedFold") TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpUnsignedFoldFail") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); IrOp fallback = build.block(IrBlockKind::Internal); @@ -1407,7 +874,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpUnsignedFoldFail") // 0 is NOT UnsignedGreater than -1 (i.e. UINT64_MAX), so guard fails build.inst(IrCmd::CHECK_CMP_INT64, build.constInt64(0), build.constInt64(-1), build.cond(IrCondition::UnsignedGreater), fallback); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(1)); build.inst(IrCmd::RETURN, build.constUint(0)); build.beginBlock(fallback); @@ -1427,99 +893,8 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckCmpUnsignedFoldFail") )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ArithChainConstFold") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // Chain of arithmetic that should all fold: ((10 + 20) * 3) - 5 - IrOp add = build.inst(IrCmd::ADD_INT64, build.constInt64(10), build.constInt64(20)); - IrOp mul = build.inst(IrCmd::MUL_INT64, add, build.constInt64(3)); - IrOp sub = build.inst(IrCmd::SUB_INT64, mul, build.constInt64(5)); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), sub); - - // Bitwise chain: (0xFF & 0x0F) | 0xF0 = 0xFF - IrOp band = build.inst(IrCmd::BITAND_INT64, build.constInt64(0xFF), build.constInt64(0x0F)); - IrOp bor = build.inst(IrCmd::BITOR_INT64, band, build.constInt64(0xF0)); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), bor); - - // Shift chain: (1 << 10) >> 5 = 32 - IrOp lshift = build.inst(IrCmd::BITLSHIFT_INT64, build.constInt64(1), build.constInt64(10)); - IrOp rshift = build.inst(IrCmd::BITRSHIFT_INT64, lshift, build.constInt64(5)); - build.inst(IrCmd::STORE_INT64, build.vmReg(2), rshift); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, 85i - STORE_INT64 R1, 255i - STORE_INT64 R2, 32i - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64BitwiseLargeValues") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // Test with values that exercise the upper 32 bits (beyond int32 range) - int64_t hiVal = int64_t(0x8000000000000000LL); // INT64_MIN - int64_t hiMask = int64_t(0xFFFFFFFF00000000LL); - int64_t loMask = int64_t(0x00000000FFFFFFFFLL); - - // AND with high mask extracts upper 32 bits - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::BITAND_INT64, build.constInt64(0x123456789ABCDEF0LL), build.constInt64(hiMask))); - // AND with low mask extracts lower 32 bits - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::BITAND_INT64, build.constInt64(0x123456789ABCDEF0LL), build.constInt64(loMask))); - // XOR of INT64_MIN with itself - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::BITXOR_INT64, build.constInt64(hiVal), build.constInt64(hiVal))); - // OR combining high and low halves - build.inst( - IrCmd::STORE_INT64, - build.vmReg(3), - build.inst(IrCmd::BITOR_INT64, build.constInt64(0xFF00000000000000LL), build.constInt64(0x00000000000000FFLL)) - ); - - // BYTESWAP of a value with distinct bytes - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::BYTESWAP_INT64, build.constInt64(int64_t(0x0123456789ABCDEFLL)))); - - // Left rotate by 32 swaps high and low halves - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::BITLROTATE_INT64, build.constInt64(0x0000000100000002LL), build.constInt64(32))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, 1311768464867721216i - STORE_INT64 R1, 2596069104i - STORE_INT64 R2, 0i - STORE_INT64 R3, -72057594037927681i - STORE_INT64 R4, -1167088121787636991i - STORE_INT64 R5, 8589934593i - RETURN 0u - -)"); -} - TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ComparisonBoundaryValues") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); build.beginBlock(block); @@ -1580,142 +955,14 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ComparisonBoundaryValues") )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "DseInt64Overwrite") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp entry = build.block(IrBlockKind::Internal); - - build.beginBlock(entry); - - IrOp val = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - - build.inst(IrCmd::STORE_TAG, build.vmReg(1), build.constTag(tnumber)); - build.inst(IrCmd::STORE_DOUBLE, build.vmReg(1), build.constDouble(1.0)); - - build.inst(IrCmd::STORE_TAG, build.vmReg(1), build.constTag(tinteger)); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), val); - - build.inst(IrCmd::RETURN, build.vmReg(1), build.constInt(1)); - - updateUseCounts(build.function); - computeCfgInfo(build.function); - constPropInBlockChains(build); - markDeadStoresInBlockChains(build); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: -; in regs: R0 - %0 = LOAD_INT64 R0 - STORE_SPLIT_TVALUE R1, tinteger, %0 - RETURN R1, 1i - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivisionConstFold") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::DIV_INT64, build.constInt64(42), build.constInt64(7))); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::DIV_INT64, build.constInt64(-7), build.constInt64(2))); - - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::IDIV_INT64, build.constInt64(-7), build.constInt64(2))); - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::IDIV_INT64, build.constInt64(7), build.constInt64(2))); - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::IDIV_INT64, build.constInt64(-6), build.constInt64(2))); - - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::UDIV_INT64, build.constInt64(-1), build.constInt64(2))); - - build.inst(IrCmd::STORE_INT64, build.vmReg(6), build.inst(IrCmd::REM_INT64, build.constInt64(7), build.constInt64(3))); - build.inst(IrCmd::STORE_INT64, build.vmReg(7), build.inst(IrCmd::REM_INT64, build.constInt64(-7), build.constInt64(3))); - - build.inst(IrCmd::STORE_INT64, build.vmReg(8), build.inst(IrCmd::UREM_INT64, build.constInt64(-1), build.constInt64(10))); - - build.inst(IrCmd::STORE_INT64, build.vmReg(9), build.inst(IrCmd::MOD_INT64, build.constInt64(-7), build.constInt64(3))); - build.inst(IrCmd::STORE_INT64, build.vmReg(10), build.inst(IrCmd::MOD_INT64, build.constInt64(7), build.constInt64(3))); - build.inst(IrCmd::STORE_INT64, build.vmReg(11), build.inst(IrCmd::MOD_INT64, build.constInt64(7), build.constInt64(-3))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, 6i - STORE_INT64 R1, -3i - STORE_INT64 R2, -4i - STORE_INT64 R3, 3i - STORE_INT64 R4, -3i - STORE_INT64 R5, 9223372036854775807i - STORE_INT64 R6, 1i - STORE_INT64 R7, -1i - STORE_INT64 R8, 5i - STORE_INT64 R9, 2i - STORE_INT64 R10, 1i - STORE_INT64 R11, -2i - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DivisionUnsafeCasesNotFolded") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::DIV_INT64, build.constInt64(42), build.constInt64(0))); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::DIV_INT64, build.constInt64(INT64_MIN), build.constInt64(-1))); - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::IDIV_INT64, build.constInt64(42), build.constInt64(0))); - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::REM_INT64, build.constInt64(42), build.constInt64(0))); - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::REM_INT64, build.constInt64(INT64_MIN), build.constInt64(-1))); - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::UDIV_INT64, build.constInt64(42), build.constInt64(0))); - build.inst(IrCmd::STORE_INT64, build.vmReg(6), build.inst(IrCmd::MOD_INT64, build.constInt64(INT64_MIN), build.constInt64(-1))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = DIV_INT64 42i, 0i - STORE_INT64 R0, %0 - %2 = DIV_INT64 -9223372036854775808i, -1i - STORE_INT64 R1, %2 - %4 = IDIV_INT64 42i, 0i - STORE_INT64 R2, %4 - %6 = REM_INT64 42i, 0i - STORE_INT64 R3, %6 - %8 = REM_INT64 -9223372036854775808i, -1i - STORE_INT64 R4, %8 - %10 = UDIV_INT64 42i, 0i - STORE_INT64 R5, %10 - %12 = MOD_INT64 -9223372036854775808i, -1i - STORE_INT64 R6, %12 - RETURN 0u - -)"); -} - TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckDivFoldSafe") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); IrOp fallback = build.block(IrBlockKind::Internal); build.beginBlock(block); build.inst(IrCmd::CHECK_DIV_INT64, build.constInt64(100), build.constInt64(7), fallback); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(99)); build.inst(IrCmd::RETURN, build.constUint(0)); build.beginBlock(fallback); @@ -1726,7 +973,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckDivFoldSafe") CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( bb_0: - STORE_INT64 R0, 99i RETURN 0u )"); @@ -1734,15 +980,12 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckDivFoldSafe") TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckDivFoldZeroDivisor") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); IrOp fallback = build.block(IrBlockKind::Internal); build.beginBlock(block); build.inst(IrCmd::CHECK_DIV_INT64, build.constInt64(100), build.constInt64(0), fallback); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(99)); build.inst(IrCmd::RETURN, build.constUint(0)); build.beginBlock(fallback); @@ -1763,123 +1006,39 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckDivFoldZeroDivisor") TEST_CASE_FIXTURE(IrBuilderFixture, "Int64CheckDivFoldOverflow") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); IrOp fallback = build.block(IrBlockKind::Internal); - build.beginBlock(block); - - build.inst(IrCmd::CHECK_DIV_INT64, build.constInt64(INT64_MIN), build.constInt64(-1), fallback); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(99)); - build.inst(IrCmd::RETURN, build.constUint(0)); - - build.beginBlock(fallback); - build.inst(IrCmd::RETURN, build.constUint(1)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - JUMP bb_1 - -bb_1: - RETURN 1u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ConversionConstFold") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - build.inst(IrCmd::STORE_DOUBLE, build.vmReg(0), build.inst(IrCmd::INT64_TO_NUM, build.constInt64(42))); - build.inst(IrCmd::STORE_DOUBLE, build.vmReg(1), build.inst(IrCmd::INT64_TO_NUM, build.constInt64(0))); - build.inst(IrCmd::STORE_DOUBLE, build.vmReg(2), build.inst(IrCmd::INT64_TO_NUM, build.constInt64(-100))); - - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::NUM_TO_INT64, build.constDouble(42.0))); - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::NUM_TO_INT64, build.constDouble(0.0))); - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::NUM_TO_INT64, build.constDouble(-100.0))); - build.inst(IrCmd::STORE_INT64, build.vmReg(6), build.inst(IrCmd::NUM_TO_INT64, build.constDouble(3.7))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constantFold(); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_DOUBLE R0, 42 - STORE_DOUBLE R1, 0 - STORE_DOUBLE R2, -100 - STORE_INT64 R3, 42i - STORE_INT64 R4, 0i - STORE_INT64 R5, -100i - STORE_INT64 R6, 3i - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64NumToInt64OutOfRangeNotFolded") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::NUM_TO_INT64, build.constDouble(1e19))); - build.inst( - IrCmd::STORE_INT64, - build.vmReg(1), - build.inst(IrCmd::NUM_TO_INT64, build.inst(IrCmd::DIV_NUM, build.constDouble(0.0), build.constDouble(0.0))) - ); - build.inst( - IrCmd::STORE_INT64, - build.vmReg(2), - build.inst(IrCmd::NUM_TO_INT64, build.inst(IrCmd::DIV_NUM, build.constDouble(1.0), build.constDouble(0.0))) - ); + build.beginBlock(block); + build.inst(IrCmd::CHECK_DIV_INT64, build.constInt64(INT64_MIN), build.constInt64(-1), fallback); build.inst(IrCmd::RETURN, build.constUint(0)); + build.beginBlock(fallback); + build.inst(IrCmd::RETURN, build.constUint(1)); + updateUseCounts(build.function); constantFold(); - // 1e19 is beyond INT64_MAX, so it shouldn't fold CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( bb_0: - %0 = NUM_TO_INT64 1e+19 - STORE_INT64 R0, %0 - %3 = NUM_TO_INT64 nan - STORE_INT64 R1, %3 - %6 = NUM_TO_INT64 inf - STORE_INT64 R2, %6 - RETURN 0u + JUMP bb_1 + +bb_1: + RETURN 1u )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ShiftBoundary63") +TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ConversionConstFold") { - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - IrOp block = build.block(IrBlockKind::Internal); build.beginBlock(block); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::BITLSHIFT_INT64, build.constInt64(1), build.constInt64(63))); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::BITRSHIFT_INT64, build.constInt64(INT64_MIN), build.constInt64(63))); - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::BITARSHIFT_INT64, build.constInt64(-1), build.constInt64(63))); - build.inst(IrCmd::STORE_INT64, build.vmReg(3), build.inst(IrCmd::BITARSHIFT_INT64, build.constInt64(INT64_MAX), build.constInt64(63))); - - build.inst(IrCmd::STORE_INT64, build.vmReg(4), build.inst(IrCmd::BITLSHIFT_INT64, build.constInt64(INT64_MIN), build.constInt64(-63))); - build.inst(IrCmd::STORE_INT64, build.vmReg(5), build.inst(IrCmd::BITRSHIFT_INT64, build.constInt64(1), build.constInt64(-63))); + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(0), build.inst(IrCmd::INT64_TO_NUM, build.constInt64(42))); + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(1), build.inst(IrCmd::INT64_TO_NUM, build.constInt64(0))); + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(2), build.inst(IrCmd::INT64_TO_NUM, build.constInt64(-100))); build.inst(IrCmd::RETURN, build.constUint(0)); @@ -1888,12 +1047,9 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "Int64ShiftBoundary63") CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( bb_0: - STORE_INT64 R0, -9223372036854775808i - STORE_INT64 R1, 1i - STORE_INT64 R2, -1i - STORE_INT64 R3, 0i - STORE_INT64 R4, 1i - STORE_INT64 R5, -9223372036854775808i + STORE_DOUBLE R0, 42 + STORE_DOUBLE R1, 0 + STORE_DOUBLE R2, -100 RETURN 0u )"); @@ -1979,33 +1135,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "CheckCmpNumNaN") )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64SplitTvalueStoreConstProp") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp entry = build.block(IrBlockKind::Internal); - - build.beginBlock(entry); - - build.inst(IrCmd::STORE_TAG, build.vmReg(0), build.constTag(tinteger)); - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(42)); - - build.inst(IrCmd::RETURN, build.vmReg(0), build.constInt(1)); - - updateUseCounts(build.function); - computeCfgInfo(build.function); - constPropInBlockChains(build); - markDeadStoresInBlockChains(build); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_TAG R0, tinteger - STORE_INT64 R0, 42i - RETURN R0, 1i - -)"); -} - TEST_CASE_FIXTURE(IrBuilderFixture, "ReplacementPreservesUses") { IrOp block = build.block(IrBlockKind::Internal); @@ -2537,133 +1666,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "RememberTagsAndValues") )"); } -TEST_CASE_FIXTURE(IrBuilderFixture, "RememberInt64Values") -{ - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(42)); - - // We know the constant from this load - build.inst(IrCmd::STORE_INT64, build.vmReg(1), build.inst(IrCmd::LOAD_INT64, build.vmReg(0))); - - // Redundant store of same constant should be removed - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.constInt64(42)); - - // Override with unknown invalidates - build.inst(IrCmd::STORE_INT64, build.vmReg(0), build.inst(IrCmd::LOAD_INT64, build.vmReg(5))); - - // So now the load has to be made - build.inst(IrCmd::STORE_INT64, build.vmReg(2), build.inst(IrCmd::LOAD_INT64, build.vmReg(0))); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constPropInBlockChains(build); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - STORE_INT64 R0, 42i - STORE_INT64 R1, 42i - %4 = LOAD_INT64 R5 - STORE_INT64 R0, %4 - STORE_INT64 R2, %4 - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64NumRoundtripElimination") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // NUM_TO_INT64(INT64_TO_NUM(x)) != x - IrOp intVal = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - IrOp dblVal = build.inst(IrCmd::INT64_TO_NUM, intVal); - IrOp backToInt = build.inst(IrCmd::NUM_TO_INT64, dblVal); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), backToInt); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constPropInBlockChains(build); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = LOAD_INT64 R0 - %1 = INT64_TO_NUM %0 - %2 = NUM_TO_INT64 %1 - STORE_INT64 R1, %2 - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64StoreForwardToLoad") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // Store a computed int64 value - IrOp val = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), val); - - // Loading back should forward to the stored value - IrOp loaded = build.inst(IrCmd::LOAD_INT64, build.vmReg(1)); - build.inst(IrCmd::STORE_INT64, build.vmReg(2), loaded); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constPropInBlockChains(build); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = LOAD_INT64 R0 - STORE_INT64 R1, %0 - STORE_INT64 R2, %0 - RETURN 0u - -)"); -} - -TEST_CASE_FIXTURE(IrBuilderFixture, "Int64DuplicateStoreRemoval") -{ - ScopedFastFlag integerFlags[3] = {{FFlag::LuauIntegerType2, true}, {FFlag::LuauIntegerLibrary, true}, {FFlag::LuauCodegenInteger3, true}}; - - IrOp block = build.block(IrBlockKind::Internal); - - build.beginBlock(block); - - // Store a computed value - IrOp val = build.inst(IrCmd::LOAD_INT64, build.vmReg(0)); - build.inst(IrCmd::STORE_INT64, build.vmReg(1), val); - - // Store the same value to the same register - build.inst(IrCmd::STORE_INT64, build.vmReg(1), val); - - build.inst(IrCmd::RETURN, build.constUint(0)); - - updateUseCounts(build.function); - constPropInBlockChains(build); - - CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( -bb_0: - %0 = LOAD_INT64 R0 - STORE_INT64 R1, %0 - RETURN 0u - -)"); -} - TEST_CASE_FIXTURE(IrBuilderFixture, "PropagateThroughTvalue") { IrOp block = build.block(IrBlockKind::Internal); @@ -4080,8 +3082,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "TagsAreJoinedFromPredecessors2") TEST_CASE_FIXTURE(IrBuilderFixture, "TagsAreJoinedFromFallbackPredecessor") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - IrOp entry = build.block(IrBlockKind::Internal); IrOp fallback = build.fallbackBlock(0u); IrOp exit = build.block(IrBlockKind::Internal); @@ -4135,8 +3135,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "TagsAreJoinedFromFallbackPredecessor") TEST_CASE_FIXTURE(IrBuilderFixture, "TagsEstablishedBeforeFallbackBranchPropagateThroughMerge") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - IrOp entry = build.block(IrBlockKind::Internal); IrOp fallback = build.fallbackBlock(0u); IrOp merge = build.block(IrBlockKind::Internal); @@ -4197,8 +3195,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "TagsEstablishedBeforeFallbackBranchPropagat TEST_CASE_FIXTURE(IrBuilderFixture, "FallbackClobberDoesNotPropagateOverwrittenTag") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - IrOp entry = build.block(IrBlockKind::Internal); IrOp fallback = build.fallbackBlock(0u); IrOp merge = build.block(IrBlockKind::Internal); @@ -4251,8 +3247,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "FallbackClobberDoesNotPropagateOverwrittenT TEST_CASE_FIXTURE(IrBuilderFixture, "FallbackMultipleBranchPointsFromSameBlockIntersect") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - IrOp entry = build.block(IrBlockKind::Internal); IrOp fallback = build.fallbackBlock(0u); IrOp merge = build.block(IrBlockKind::Internal); @@ -4315,8 +3309,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "FallbackMultipleBranchPointsFromSameBlockIn TEST_CASE_FIXTURE(IrBuilderFixture, "FallbackReachedByFoldedUnconditionalJump") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - IrOp entry = build.block(IrBlockKind::Internal); IrOp fallback = build.fallbackBlock(0u); IrOp merge = build.block(IrBlockKind::Internal); @@ -4440,6 +3432,82 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "DeadPredecessorDoesNotPreventTagPropagation )"); } +TEST_CASE_FIXTURE(IrBuilderFixture, "ForwardSplitStore1") +{ + ScopedFastFlag luauCodegenForwardSplitStore{FFlag::LuauCodegenForwardSplitStore, true}; + + build.beginBlock(build.block(IrBlockKind::Internal)); + + IrOp number = build.inst(IrCmd::LOAD_DOUBLE, build.vmReg(0)); + build.inst(IrCmd::STORE_SPLIT_TVALUE, build.vmReg(1), build.constTag(tnumber), number); + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(2), build.inst(IrCmd::LOAD_DOUBLE, build.vmReg(1))); + + build.inst(IrCmd::RETURN, build.constUint(0)); + + updateUseCounts(build.function); + constPropInBlockChains(build); + + CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( +bb_0: + %0 = LOAD_DOUBLE R0 + STORE_SPLIT_TVALUE R1, tnumber, %0 + STORE_DOUBLE R2, %0 + RETURN 0u + +)"); +} + +TEST_CASE_FIXTURE(IrBuilderFixture, "ForwardSplitStore2") +{ + ScopedFastFlag luauCodegenForwardSplitStore{FFlag::LuauCodegenForwardSplitStore, true}; + + IrOp entry = build.block(IrBlockKind::Internal); + IrOp fallback = build.fallbackBlock(0); + IrOp fallback2 = build.fallbackBlock(1); + + build.beginBlock(entry); + + IrOp table = build.inst(IrCmd::LOAD_POINTER, build.vmReg(0)); + IrOp node = build.inst(IrCmd::GET_SLOT_NODE_ADDR, table, build.constUint(0), build.vmConst(1)); + build.inst(IrCmd::CHECK_SLOT_MATCH, node, build.vmConst(1), fallback); + build.inst(IrCmd::STORE_TVALUE, build.vmReg(2), build.inst(IrCmd::LOAD_TVALUE, node, build.constInt(0))); + build.inst(IrCmd::STORE_SPLIT_TVALUE, build.vmReg(1), build.constTag(ttable), table); + + // Second load through the same table stored with a split instruction can disappear + IrOp copy = build.inst(IrCmd::LOAD_POINTER, build.vmReg(1)); + IrOp otherNode = build.inst(IrCmd::GET_SLOT_NODE_ADDR, copy, build.constUint(2), build.vmConst(1)); + build.inst(IrCmd::CHECK_SLOT_MATCH, otherNode, build.vmConst(1), fallback2); + build.inst(IrCmd::STORE_TVALUE, build.vmReg(3), build.inst(IrCmd::LOAD_TVALUE, otherNode, build.constInt(0))); + + build.inst(IrCmd::RETURN, build.vmReg(2), build.constInt(2)); + + build.beginBlock(fallback); + build.inst(IrCmd::RETURN, build.vmReg(0), build.constInt(1)); + + // Will not be needed after the optimization + build.beginBlock(fallback2); + build.inst(IrCmd::RETURN, build.vmReg(1), build.constInt(1)); + + updateUseCounts(build.function); + constPropInBlockChains(build); + + CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( +bb_0: + %0 = LOAD_POINTER R0 + %1 = GET_SLOT_NODE_ADDR %0, 0u, K1 + CHECK_SLOT_MATCH %1, K1, bb_fallback_1 + %3 = LOAD_TVALUE %1, 0i + STORE_TVALUE R2, %3 + STORE_SPLIT_TVALUE R1, ttable, %0 + STORE_TVALUE R3, %3 + RETURN R2, 2i + +bb_fallback_1: + RETURN R0, 1i + +)"); +} + TEST_SUITE_END(); TEST_SUITE_BEGIN("LinearExecutionFlowExtraction"); @@ -4957,8 +4025,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "NoLinearExtractionForChainWithCallLiveOut") TEST_CASE_FIXTURE(IrBuilderFixture, "EntryBlockBackEdgeTagPropagation") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - IrOp entry = build.block(IrBlockKind::Internal); IrOp target = build.block(IrBlockKind::Internal); IrOp fallback = build.fallbackBlock(0u); @@ -7056,8 +6122,6 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "IndirectFloatLoadExtractionMustRespectVersi TEST_CASE_FIXTURE(IrBuilderFixture, "VersionLimitChecks") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - IrOp entry = build.block(IrBlockKind::Internal); IrOp unrelated = build.block(IrBlockKind::Internal); IrOp next = build.block(IrBlockKind::Internal); @@ -9037,6 +8101,128 @@ TEST_CASE_FIXTURE(IrBuilderFixture, "DseVmExitSyncMultiUseChainedDependency2") )"); } +TEST_CASE_FIXTURE(IrBuilderFixture, "DseVmExitSyncHintedPartialStoreTag") +{ + ScopedFastFlag luauCodegenExitSyncExpectedTag{FFlag::LuauCodegenExitSyncExpectedTag, true}; + + IrOp block = build.block(IrBlockKind::Internal); + build.beginBlock(block); + + build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(1)), build.constTag(tnumber), build.vmExit(0)); + build.inst(IrCmd::CHECK_TAG, build.inst(IrCmd::LOAD_TAG, build.vmReg(2)), build.constTag(tnumber), build.vmExit(0)); + + IrOp load = build.inst(IrCmd::LOAD_DOUBLE, build.vmReg(0)); + IrOp add = build.inst(IrCmd::ADD_NUM, load, build.constDouble(1.0)); + + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(1), add); + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(2), build.constDouble(6.0)); + build.inst(IrCmd::STORE_SPLIT_TVALUE, build.vmReg(3), build.constTag(tnumber), add); + build.inst(IrCmd::CHECK_SAFE_ENV, build.vmExit(1)); + + IrOp result = build.inst(IrCmd::UINT_TO_NUM, build.inst(IrCmd::NUM_TO_UINT, add)); + build.inst(IrCmd::STORE_SPLIT_TVALUE, build.vmReg(0), build.constTag(tnumber), result); + build.inst(IrCmd::RETURN, build.vmReg(0), build.constInt(1)); + + updateUseCounts(build.function); + computeCfgInfo(build.function); + constPropInBlockChains(build); + markDeadStoresInBlockChains(build); + + CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( +bb_0: +; in regs: R0, R1, R2 + %0 = LOAD_TAG R1 + CHECK_TAG %0, tnumber, exit(0) + %2 = LOAD_TAG R2 + CHECK_TAG %2, tnumber, exit(0) + %4 = LOAD_DOUBLE R0 + %5 = ADD_NUM %4, 1 + CHECK_SAFE_ENV bb_exit_1 + ; exit sync: R3, R2, R1, {%5} + %10 = NUM_TO_UINT %5 + %11 = UINT_TO_NUM %10 + STORE_SPLIT_TVALUE R0, tnumber, %11 + RETURN R0, 1i + +bb_exit_1: + STORE_SPLIT_TVALUE R3, tnumber, %5 + STORE_DOUBLE R2, 6 + STORE_TAG R1, tnumber + STORE_DOUBLE R1, %5 + JUMP exit(1) + +)"); +} + +TEST_CASE_FIXTURE(IrBuilderFixture, "PackedBufferStoreForwardingAndPartialWrite") +{ + build.beginBlock(build.block(IrBlockKind::Internal)); + + IrOp pointer = build.inst(IrCmd::LOAD_POINTER, build.vmReg(0)); + IrOp vector = build.inst(IrCmd::LOAD_TVALUE, build.vmReg(1)); + build.inst(IrCmd::BUFFER_WRITEF32X4, pointer, build.constInt(0), vector, build.constTag(tuserdata)); + + IrOp forwarded = build.inst(IrCmd::BUFFER_READF32X4, pointer, build.constInt(0), build.constTag(tuserdata)); + build.inst(IrCmd::STORE_TVALUE, build.vmReg(2), forwarded); + build.inst(IrCmd::BUFFER_WRITEF32, pointer, build.constInt(12), build.constDouble(99), build.constTag(tuserdata)); + + IrOp reloaded = build.inst(IrCmd::BUFFER_READF32X4, pointer, build.constInt(0), build.constTag(tuserdata)); + build.inst(IrCmd::STORE_TVALUE, build.vmReg(3), reloaded); + build.inst(IrCmd::RETURN, build.vmReg(2), build.constInt(2)); + + updateUseCounts(build.function); + constPropInBlockChains(build); + + CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( +bb_0: + %0 = LOAD_POINTER R0 + %1 = LOAD_TVALUE R1 + BUFFER_WRITEF32X4 %0, 0i, %1, tuserdata + STORE_TVALUE R2, %1 + BUFFER_WRITEF32 %0, 12i, 99, tuserdata + %6 = BUFFER_READF32X4 %0, 0i, tuserdata + STORE_TVALUE R3, %6 + RETURN R2, 2i + +)"); +} + +TEST_CASE_FIXTURE(IrBuilderFixture, "PackedBufferVectorLanes") +{ + ScopedFastFlag luauCodegenMultiLaneDot{FFlag::LuauCodegenMultiLaneDot, true}; + + build.beginBlock(build.block(IrBlockKind::Internal)); + + IrOp vector = build.inst(IrCmd::LOAD_TVALUE, build.vmReg(0)); + IrOp tagged = build.inst(IrCmd::TAG_VECTOR, vector); + IrOp untagged = build.inst(IrCmd::UNTAG_VECTOR, tagged); + IrOp duplicate = build.inst(IrCmd::UNTAG_VECTOR, untagged); + IrOp three = build.inst(IrCmd::DOT_VEC, tagged, duplicate, build.constInt(3)); + IrOp four = build.inst(IrCmd::DOT_VEC, tagged, duplicate, build.constInt(4)); + + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(1), build.inst(IrCmd::FLOAT_TO_NUM, three)); + build.inst(IrCmd::STORE_DOUBLE, build.vmReg(2), build.inst(IrCmd::FLOAT_TO_NUM, four)); + build.inst(IrCmd::RETURN, build.vmReg(1), build.constInt(2)); + + updateUseCounts(build.function); + constPropInBlockChains(build); + + CHECK("\n" + toString(build.function, IncludeUseInfo::No) == R"( +bb_0: + %0 = LOAD_TVALUE R0 + %1 = TAG_VECTOR %0 + %2 = UNTAG_VECTOR %1 + %4 = DOT_VEC %0, %2, 3i + %5 = DOT_VEC %1, %2, 4i + %6 = FLOAT_TO_NUM %4 + STORE_DOUBLE R1, %6 + %8 = FLOAT_TO_NUM %5 + STORE_DOUBLE R2, %8 + RETURN R1, 2i + +)"); +} + TEST_SUITE_END(); TEST_SUITE_BEGIN("Dump"); diff --git a/tests/IrLowering.test.cpp b/tests/IrLowering.test.cpp index cb10b0d1e..8cd8a75d8 100644 --- a/tests/IrLowering.test.cpp +++ b/tests/IrLowering.test.cpp @@ -16,21 +16,17 @@ #include #include -LUAU_FASTFLAG(LuauIntegerFastcalls) -LUAU_FASTFLAG(LuauCodegenInteger3) -LUAU_FASTFLAG(LuauIntegerType2) -LUAU_FASTFLAG(LuauCodegenBufferInteger) LUAU_FASTFLAG(LuauCodegenMarkUsed) -LUAU_FASTFLAG(LuauIntegerBufferFastcalls) +LUAU_FASTFLAG(DebugLuauBufferVectorFastcalls) LUAU_FASTFLAG(LuauEmitCallFeedback) -LUAU_FASTFLAG(LuauCodegenPropagateFallbackTags) LUAU_FASTFLAG(LuauCompileNoDebugConst) -LUAU_FASTFLAG(LuauCodegenIntegerCompare) LUAU_FASTFLAG(LuauCodegenImprovedExitSync) LUAU_FASTFLAG(LuauCompileReuseLocalRegs) LUAU_FASTFLAG(LuauLoadRemapOptionalUserdata) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) -LUAU_FASTFLAG(LuauRuntimeFeedback) +LUAU_FASTFLAG(LuauCodegenRuntimeFeedback) +LUAU_FASTFLAG(LuauCodegenUserdataDirect) +LUAU_FASTFLAG(LuauCodegenMultiLaneDot) #define ensureVectorSize3() \ if constexpr (LUA_VECTOR_SIZE != 3) \ @@ -93,6 +89,23 @@ static int luauLibraryTypeLookup(const char* library, const char* member) return LuauBytecodeType::LBC_TYPE_ANY; } +static size_t countVectorOperations(const std::string& assembly, const char* operation, const char* count) +{ + size_t matches = 0; + size_t operationPosition = assembly.find(operation); + while (operationPosition != std::string::npos) + { + size_t lineEnd = assembly.find('\n', operationPosition); + size_t searchEnd = lineEnd == std::string::npos ? assembly.size() : lineEnd; + if (assembly.find(count, operationPosition) < searchEnd) + matches++; + + operationPosition = assembly.find(operation, lineEnd); + } + + return matches; +} + class LoweringFixture { public: @@ -151,6 +164,8 @@ class LoweringFixture assemblyOptions.includeRegFlowInfo = Luau::CodeGen::IncludeRegFlowInfo::No; } + int16_t (*useratom)(lua_State*, const char*, size_t) = nullptr; + Luau::CompileOptions compilationOptions = {}; lua_CompileOptions compilationOptionsC = {}; @@ -217,6 +232,8 @@ class LoweringFixture initializeCodegen(L); + lua_callbacks(L)->useratom = useratom; + if (luau_load(L, "name", bytecode.data(), bytecode.size(), 0) == 0) { // For IR, we don't care about assembly, but we want a stable target @@ -1524,7 +1541,6 @@ TEST_CASE_FIXTURE(LoweringFixture, "VectorCustomNamecallChain2") ensureVectorFloat(); ScopedFastFlag emitCallFb{FFlag::LuauEmitCallFeedback, true}; - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; CHECK_EQ( "\n" + getCodegenAssembly(R"( @@ -1634,6 +1650,8 @@ end TEST_CASE_FIXTURE(LoweringFixture, "VectorLibraryChain") { + ScopedFastFlag luauCodegenMultiLaneDot{FFlag::LuauCodegenMultiLaneDot, true}; + ensureVectorFloat(); CHECK_EQ( @@ -1653,16 +1671,16 @@ end bb_bytecode_1: implicit CHECK_SAFE_ENV exit(0) %9 = LOAD_TVALUE R0, 0i, tvector - %10 = DOT_VEC %9, %9 + %10 = DOT_VEC %9, %9, 3i %11 = SQRT_FLOAT %10 %12 = DIV_FLOAT 1, %11 %13 = FLOAT_TO_VEC %12 %14 = MUL_VEC %9, %13 %21 = LOAD_TVALUE R1, 0i, tvector - %22 = DOT_VEC %21, %21 + %22 = DOT_VEC %21, %21, 3i %23 = SQRT_FLOAT %22 %24 = FLOAT_TO_NUM %23 - %35 = DOT_VEC %9, %21 + %35 = DOT_VEC %9, %21, 3i %36 = FLOAT_TO_NUM %35 %46 = ADD_NUM %24, %36 %55 = NUM_TO_FLOAT %46 @@ -2396,8 +2414,6 @@ end // Our fast-path lowering checks that there is no metatable and all accesses are in bounds TEST_CASE_FIXTURE(LoweringFixture, "DuplicateArrayLoads4") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - // TODO: opportunity 1 - if we can figure out that i+1 is exactly 1 integer slot away, we can reduce arithmetic // TODO: opportunity 2 - store at [i + 1] shouldn't invalidate value at [i] CHECK_EQ( @@ -2820,7 +2836,6 @@ TEST_CASE_FIXTURE(LoweringFixture, "TableNodeLoadStoreProp5") ensureVectorFloat(); ensureVectorSize3(); - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; ScopedFastFlag luauCompileReuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; ScopedFastFlag luauCodegenMarkUsed{FFlag::LuauCodegenMarkUsed, true}; @@ -5359,7 +5374,6 @@ end TEST_CASE_FIXTURE(LoweringFixture, "BufferRelatedIndicesPositiveLoopRangeBase") { ScopedFastFlag emitCallFb{FFlag::LuauEmitCallFeedback, true}; - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; // TODO: opportunity 1 - buffer.len is not a fastcall, but under safe env we can treat it like one and read buffer len field // TODO: opportunity 2 - range of 'i' is known, we can check it in loop header @@ -5903,8 +5917,6 @@ end TEST_CASE_FIXTURE(LoweringFixture, "BufferRelatedIndicesConstantRange") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - CHECK_EQ( "\n" + getCodegenAssembly( R"( @@ -6077,6 +6089,36 @@ end ); } +TEST_CASE_FIXTURE(LoweringFixture, "BufferVectorFastcalls") +{ + ensureVectorFloat(); + + ScopedFastFlag bufferVectorFastcalls{FFlag::DebugLuauBufferVectorFastcalls, true}; + + const std::string assembly = getCodegenAssembly(R"( +local function read2(buf: buffer, offset: number) + return buffer.readvectorf32x2(buf, offset) +end + +local function read3(buf: buffer, offset: number) + return buffer.readvectorf32x3(buf, offset) +end + +local function write2(buf: buffer, offset: number, value: vector) + buffer.writevectorf32x2(buf, offset, value) +end + +local function write3(buf: buffer, offset: number, value: vector) + buffer.writevectorf32x3(buf, offset, value) +end +)"); + + CHECK_EQ(countVectorOperations(assembly, "BUFFER_READVECTOR", "tbuffer, 2i"), 1); + CHECK_EQ(countVectorOperations(assembly, "BUFFER_READVECTOR", "tbuffer, 3i"), 1); + CHECK_EQ(countVectorOperations(assembly, "BUFFER_WRITEVECTOR", "tbuffer, 2i"), 1); + CHECK_EQ(countVectorOperations(assembly, "BUFFER_WRITEVECTOR", "tbuffer, 3i"), 1); +} + TEST_CASE_FIXTURE(LoweringFixture, "BufferEffects") { ScopedFastFlag luauCodegenMarkUsed{FFlag::LuauCodegenMarkUsed, true}; @@ -7079,26 +7121,6 @@ _() ); } -TEST_CASE_FIXTURE(LoweringFixture, "FuzzTest26") -{ - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; - ScopedFastFlag luauCodegenImprovedExitSync{FFlag::LuauCodegenImprovedExitSync, true}; - - CHECK( - getCodegenAssembly( - R"( -local function foo(...) - local _ = ... - buffer.readu32(_,_,_,nil,integer.max(0i,_,_,_,_,_,_,_,_,_,_,_,_,_,nil,- _,_,_),_) -end -)" - ) - .size() > 0 - ); -} - TEST_CASE_FIXTURE(LoweringFixture, "FuzzTest27") { assemblyOptions.compilationOptions.flags = Luau::CodeGen::CodeGen_ColdFunctions; @@ -7149,28 +7171,6 @@ end ); } -TEST_CASE_FIXTURE(LoweringFixture, "FuzzTest29") -{ - ScopedFastFlag luauCodegenImprovedExitSync{FFlag::LuauCodegenImprovedExitSync, true}; - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; - - assemblyOptions.compilationOptions.flags = Luau::CodeGen::CodeGen_ColdFunctions; - - CHECK( - getCodegenAssembly( - R"( -_ += _ + _ -_ { } -integer.max(...,_,_,262144i,_,n0,`""{536870912}`) -integer.extract(integer.extract(integer.extract(...,_,_,_,not _,_),_,_,_),_,_,0i,_) -)" - ) - .size() > 0 - ); -} - TEST_CASE_FIXTURE(LoweringFixture, "FuzzTest30") { assemblyOptions.compilationOptions.flags = Luau::CodeGen::CodeGen_ColdFunctions; @@ -7326,8 +7326,6 @@ function setm(x, y) m = x end TEST_CASE_FIXTURE(LoweringFixture, "UpvalueAccessLoadStore4") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - CHECK_EQ( "\n" + getCodegenAssembly(R"( local arr: {number} @@ -7811,8 +7809,6 @@ end TEST_CASE_FIXTURE(LoweringFixture, "LoopStepDetection2") { - ScopedFastFlag luauCodegenPropagateFallbackTags{FFlag::LuauCodegenPropagateFallbackTags, true}; - CHECK_EQ( "\n" + getCodegenAssembly( R"( @@ -7997,6 +7993,8 @@ end TEST_CASE_FIXTURE(LoweringFixture, "VecOpReuse") { + ScopedFastFlag luauCodegenMultiLaneDot{FFlag::LuauCodegenMultiLaneDot, true}; + ensureVectorFloat(); ensureVectorSize3(); @@ -8022,7 +8020,7 @@ end bb_bytecode_1: implicit CHECK_SAFE_ENV exit(0) %7 = LOAD_TVALUE R0, 0i, tvector - %8 = DOT_VEC %7, %7 + %8 = DOT_VEC %7, %7, 3i %9 = SQRT_FLOAT %8 %10 = FLOAT_TO_NUM %9 %17 = MUL_NUM %10, 3 @@ -8392,243 +8390,6 @@ end ); } -TEST_CASE_FIXTURE(LoweringFixture, "IntegerMultiargValidate") -{ - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; - - CHECK_EQ( - "\n" + getCodegenAssembly( - R"( -local function f(a, b) - return integer.bxor(a, b, a) -end -)" - ), - R"( -; function f($arg0, $arg1) line 2 -bb_bytecode_0: - implicit CHECK_SAFE_ENV exit(0) - CHECK_TAG R0, tinteger, exit(2) - CHECK_TAG R1, tinteger, exit(2) - %7 = LOAD_INT64 R0 - %8 = LOAD_INT64 R1 - %9 = BITXOR_INT64 %7, %8 - %11 = BITXOR_INT64 %9, %7 - STORE_INT64 R2, %11 - STORE_TAG R2, tinteger - INTERRUPT 8u - RETURN R2, 1i -)" - ); -} - -TEST_CASE_FIXTURE(LoweringFixture, "IntegerMultiargValidate2") -{ - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; - - CHECK_EQ( - "\n" + getCodegenAssembly( - R"( -local function f(a, b) - return integer.clamp(a, b, a) -end -)" - ), - R"( -; function f($arg0, $arg1) line 2 -bb_bytecode_0: - implicit CHECK_SAFE_ENV exit(0) - CHECK_TAG R0, tinteger, exit(2) - CHECK_TAG R1, tinteger, exit(2) - %7 = LOAD_INT64 R0 - %8 = LOAD_INT64 R1 - CHECK_CMP_INT64 %8, %7, le, exit(2) - %11 = SELECT_INT64 %7, %8, %7, %8, lt - %12 = SELECT_INT64 %11, %7, %11, %7, gt - STORE_INT64 R2, %12 - STORE_TAG R2, tinteger - INTERRUPT 8u - RETURN R2, 1i -)" - ); -} - -TEST_CASE_FIXTURE(LoweringFixture, "IntegerMultiargValidate3") -{ - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; - - CHECK_EQ( - "\n" + getCodegenAssembly( - R"( -local function f(a, b) - return integer.mul(integer.min(a, b, a), integer.max(a, b, a)) -end -)" - ), - R"( -; function f($arg0, $arg1) line 2 -bb_bytecode_0: - implicit CHECK_SAFE_ENV exit(0) - CHECK_TAG R0, tinteger, exit(2) - CHECK_TAG R1, tinteger, exit(2) - %7 = LOAD_INT64 R0 - %8 = LOAD_INT64 R1 - %9 = SELECT_INT64 %7, %8, %8, %7, le - %11 = SELECT_INT64 %7, %9, %9, %7, le - %24 = SELECT_INT64 %7, %8, %8, %7, gt - %26 = SELECT_INT64 %7, %24, %24, %7, gt - %37 = MUL_INT64 %11, %26 - STORE_INT64 R2, %37 - STORE_TAG R2, tinteger - INTERRUPT 21u - RETURN R2, 1i -)" - ); -} - -TEST_CASE_FIXTURE(LoweringFixture, "IntegerFastcallWrongConst") -{ - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - - // Check that this compiles with no assertions - CHECK( - getCodegenAssembly(R"( -local function f(...) - integer.add(..., 0.5) - integer.sub(..., 0.5) - integer.mul(..., 0.5) - integer.div(..., 0.5) - integer.idiv(..., 0.5) - integer.udiv(..., 0.5) - integer.rem(..., 0.5) - integer.urem(..., 0.5) - integer.mod(..., 0.5) - - integer.min(..., 0.5) - integer.max(..., 0.5) - - integer.band(..., 0.5) - integer.bor(..., 0.5) - integer.bxor(..., 0.5) - integer.btest(..., 0.5) - - integer.extract(..., 0.5) - - integer.lrotate(..., 0.5) - integer.rrotate(..., 0.5) - integer.lshift(..., 0.5) - integer.rshift(..., 0.5) - integer.arshift(..., 0.5) - - integer.lt(..., 0.5) - integer.le(..., 0.5) - integer.gt(..., 0.5) - integer.ge(..., 0.5) - integer.ult(..., 0.5) - integer.ule(..., 0.5) - integer.ugt(..., 0.5) - integer.uge(..., 0.5) -end -)") - .size() > 0 - ); -} - -TEST_CASE_FIXTURE(LoweringFixture, "NumberFastcallWrongConst") -{ - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; - - // Check that this compiles with no assertions - CHECK( - getCodegenAssembly(R"( -local function f(...) - -- 2-arg math - math.pow(..., 5i) - math.fmod(..., 5i) - math.atan2(..., 5i) - math.ldexp(..., 5i) - math.min(..., 5i) - math.max(..., 5i) - - -- bit32 multiarg - bit32.band(..., 5i) - bit32.bor(..., 5i) - bit32.bxor(..., 5i) - bit32.btest(..., 5i) - - -- bit32 shift/rotate - bit32.lshift(..., 5i) - bit32.rshift(..., 5i) - bit32.arshift(..., 5i) - bit32.lrotate(..., 5i) - bit32.rrotate(..., 5i) - - -- bit32 extract (2-arg) - bit32.extract(..., 5i) - - -- vector constructor (2-arg) - vector.create(..., 5i) - - -- buffer reads (offset is checked as double) - buffer.readi8(..., 5i) - buffer.readu8(..., 5i) - buffer.readi16(..., 5i) - buffer.readu16(..., 5i) - buffer.readi32(..., 5i) - buffer.readu32(..., 5i) - buffer.readf32(..., 5i) - buffer.readf64(..., 5i) -end -)") - .size() > 0 - ); -} - -TEST_CASE_FIXTURE(LoweringFixture, "IntegerFastcallConstant") -{ - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; - - CHECK_EQ( - "\n" + getCodegenAssembly( - R"( -local function foo(x: integer) - return integer.band(x, 5i) -end -)", - true, - 1, - 2 - ), - R"( -; function foo($arg0) line 2 -; R0: integer [argument] -bb_0: - CHECK_TAG R0, tinteger, exit(entry) - JUMP bb_2 -bb_2: - JUMP bb_bytecode_1 -bb_bytecode_1: - implicit CHECK_SAFE_ENV exit(0) - %7 = LOAD_INT64 R0 - %8 = BITAND_INT64 %7, 5i - STORE_INT64 R1, %8 - STORE_TAG R1, tinteger - INTERRUPT 7u - RETURN R1, 1i -)" - ); -} - TEST_CASE_FIXTURE(LoweringFixture, "BufferWriteChecksExtraArgs") { CHECK_EQ( @@ -8676,116 +8437,6 @@ end )" ); } -TEST_CASE_FIXTURE(LoweringFixture, "IntegerCompare") -{ - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; - ScopedFastFlag luauCodegenIntegerCompare{FFlag::LuauCodegenIntegerCompare, true}; - - CHECK_EQ( - "\n" + getCodegenAssembly( - R"( -local function foo(x: integer, y: integer) - if x == y then - return 1 - end - return 2 -end -)", - true, - 1, - 2 - ), - R"( -; function foo($arg0, $arg1) line 2 -; R0: integer [argument] -; R1: integer [argument] -bb_0: - CHECK_TAG R0, tinteger, exit(entry) - CHECK_TAG R1, tinteger, exit(entry) - JUMP bb_3 -bb_3: - JUMP bb_bytecode_1 -bb_bytecode_1: - %10 = LOAD_INT64 R0 - %11 = LOAD_INT64 R1 - JUMP_CMP_INT64 %10, %11, not_eq, bb_bytecode_2, bb_4 -bb_4: - STORE_DOUBLE R2, 1 - STORE_TAG R2, tnumber - INTERRUPT 3u - RETURN R2, 1i -bb_bytecode_2: - STORE_DOUBLE R2, 2 - STORE_TAG R2, tnumber - INTERRUPT 5u - RETURN R2, 1i -)" - ); -} - -TEST_CASE_FIXTURE(LoweringFixture, "IntegerCompareConstLhs") -{ - ScopedFastFlag luauIntegerFastcalls{FFlag::LuauIntegerFastcalls, true}; - ScopedFastFlag LuauCodegenInteger3{FFlag::LuauCodegenInteger3, true}; - ScopedFastFlag luauIntegerType{FFlag::LuauIntegerType2, true}; - ScopedFastFlag luauCodegenBufferInteger{FFlag::LuauCodegenBufferInteger, true}; - ScopedFastFlag luauIntegerBufferFastcalls{FFlag::LuauIntegerBufferFastcalls, true}; - ScopedFastFlag luauCodegenIntegerCompare{FFlag::LuauCodegenIntegerCompare, true}; - ScopedFastFlag luauCompileReuseLocalRegs{FFlag::LuauCompileReuseLocalRegs, true}; - - CHECK_EQ( - "\n" + getCodegenAssembly( - R"( -local function foo(b: buffer, x: integer) - -- bytecode compiler is unlikely to constant-fold this - buffer.writeinteger(b, 0, 2i) - local lhs = buffer.readinteger(b, 0) - - if lhs == x then - return 1 - end - return 2 -end -)", - true, - 1, - 2 - ), - R"( -; function foo($arg0, $arg1) line 2 -; R0: buffer [argument] -; R1: integer [argument] -; R2: integer from 8 to 21 -bb_0: - CHECK_TAG R0, tbuffer, exit(entry) - CHECK_TAG R1, tinteger, exit(entry) - JUMP bb_3 -bb_3: - JUMP bb_bytecode_1 -bb_bytecode_1: - implicit CHECK_SAFE_ENV exit(0) - %17 = LOAD_POINTER R0 - CHECK_BUFFER_LEN %17, 0i, 0i, 8i, undef, bb_exit_8 - ; exit sync: R5, R4, {} - BUFFER_WRITEI64 %17, 0i, 2i, tbuffer - %39 = LOAD_INT64 R1 - JUMP_CMP_INT64 2i, %39, not_eq, bb_bytecode_2, bb_6 -bb_6: - STORE_DOUBLE R3, 1 - STORE_TAG R3, tnumber - INTERRUPT 18u - RETURN R3, 1i -bb_bytecode_2: - STORE_DOUBLE R3, 2 - STORE_TAG R3, tnumber - INTERRUPT 20u - RETURN R3, 1i -)" - ); -} - TEST_CASE_FIXTURE(LoweringFixture, "OptionalUserdataTypeRemapping") { // This test requires runtime component to be present @@ -8926,7 +8577,7 @@ end TEST_CASE_FIXTURE(LoweringFixture, "RuntimeFeedbackCounters") { - ScopedFastFlag luauCodeGenRuntimeFeedback{FFlag::LuauRuntimeFeedback, true}; + ScopedFastFlag luauCodeGenRuntimeFeedback{FFlag::LuauCodegenRuntimeFeedback, true}; assemblyOptions.compilationOptions.runtimeFeedback = true; assemblyOptions.includeOutlinedCode = true; @@ -8962,4 +8613,73 @@ end ); } +TEST_CASE_FIXTURE(LoweringFixture, "UserdataDirectNamecall") +{ + ScopedFastFlag luauCodegenUserdataDirect{FFlag::LuauCodegenUserdataDirect, true}; + + if (!Luau::CodeGen::isSupported()) + return; + + useratom = [](lua_State*, const char* name, size_t) -> int16_t + { + return strcmp(name, "Foo") == 0 ? 1 : -1; + }; + + assemblyOptions.includeOutlinedCode = true; + + CHECK_EQ( + "\n" + getCodegenAssembly( + R"( +local function foo(a) + return a:Foo(1) +end +)" + ), + R"( +; function foo($arg0) line 2 +bb_bytecode_0: + STORE_DOUBLE R3, 1 + STORE_TAG R3, tnumber + CHECK_TAG R0, ttable, bb_fallback_5 + %4 = LOAD_POINTER R0 + %5 = GET_HASH_NODE_ADDR %4, 228911u + JUMP_SLOT_MATCH %5, K0 ('Foo'), bb_3, bb_4 +bb_3: + STORE_POINTER R2, %4 + STORE_TAG R2, ttable + %9 = LOAD_TVALUE %5, 0i + STORE_TVALUE R1, %9 + JUMP bb_1 +bb_4: + CHECK_NODE_NO_NEXT %5, bb_fallback_2 + %13 = TRY_CALL_FASTGETTM %4, 0i, bb_fallback_2 + %14 = LOAD_TAG %13 + CHECK_TAG %14, ttable, bb_fallback_2 + %16 = LOAD_POINTER %13 + %17 = GET_SLOT_NODE_ADDR %16, 1u, K0 ('Foo') + CHECK_SLOT_MATCH %17, K0 ('Foo'), bb_fallback_2 + %19 = LOAD_POINTER R0 + STORE_POINTER R2, %19 + STORE_TAG R2, ttable + %22 = LOAD_TVALUE %17, 0i + STORE_TVALUE R1, %22 + JUMP bb_1 +bb_1: + INTERRUPT 3u + SET_SAVEDPC 4u + CALL R1, 2i, -1i + JUMP bb_6 +bb_6: + INTERRUPT 4u + RETURN R1, -1i +bb_fallback_2: + FALLBACK_NAMECALL 1u, R1, R0, K0 ('Foo') + JUMP bb_1 +bb_fallback_5: + INTERRUPT 1u + INVOKE_NAMECALL 1u, R1, R0, 2i, -1i + JUMP bb_6 +)" + ); +} TEST_SUITE_END(); diff --git a/tests/Linter.test.cpp b/tests/Linter.test.cpp index 31dc45762..c37259de4 100644 --- a/tests/Linter.test.cpp +++ b/tests/Linter.test.cpp @@ -1947,8 +1947,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "DeprecatedAttributeOnFunctionInCompositeTabl TEST_CASE_FIXTURE(BuiltinsFixture, "DeprecatedAttributeOnFunctionInCompositeTable2") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; LintResult result = lint(R"( diff --git a/tests/Normalize.test.cpp b/tests/Normalize.test.cpp index 466f50cb0..d9da219f4 100644 --- a/tests/Normalize.test.cpp +++ b/tests/Normalize.test.cpp @@ -13,11 +13,8 @@ #include LUAU_FASTINT(LuauTypeInferRecursionLimit) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauFixNormalizeFunctionIntersections) LUAU_FASTFLAG(DebugLuauForceOldSolver) -LUAU_FASTFLAG(DebugLuauParseExactTables) -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) using namespace Luau; @@ -197,8 +194,6 @@ TEST_CASE_FIXTURE(IsSubtypeFixture, "union_and_intersection") TEST_CASE_FIXTURE(IsSubtypeFixture, "tables") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - check(R"( local a: {x: number} local b: {x: any} @@ -253,8 +248,6 @@ TEST_CASE_FIXTURE(IsSubtypeFixture, "table_indexers_are_invariant") TEST_CASE_FIXTURE(IsSubtypeFixture, "mismatched_indexers") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; check(R"( @@ -518,14 +511,6 @@ struct NormalizeFixture : Fixture std::unique_ptr globalScope = nullptr; }; -// TODO: Delete this fixture class when clipping DebugLuauExactTableTypes and DebugLuauParseExactTables. -struct ExactTableNormalizationFixture : NormalizeFixture -{ - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag sff1{FFlag::DebugLuauParseExactTables, true}; - ScopedFastFlag sff2{FFlag::DebugLuauExactTableTypes, true}; -}; - TEST_SUITE_BEGIN("Normalize"); TEST_CASE_FIXTURE(NormalizeFixture, "string_intersection_is_commutative") @@ -762,107 +747,9 @@ TEST_CASE_FIXTURE(NormalizeFixture, "union_function_and_top_function") TEST_CASE_FIXTURE(NormalizeFixture, "negated_function_is_anything_except_a_function") { - if (FFlag::LuauIntegerType2) - { - CHECK("(boolean | buffer | integer | number | string | table | thread | userdata)?" == toString(normal(R"( + CHECK("(boolean | buffer | number | string | table | thread | userdata)?" == toString(normal(R"( Not )"))); - } - else - { - CHECK("(boolean | buffer | number | string | table | thread | userdata)?" == toString(normal(R"( - Not - )"))); - } -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "exact_table_intersection") -{ - CHECK("{ x: number }" == toString(normal("{ x: number, ... } & { x: number }"))); - CHECK("{ x: number }" == toString(normal("{ x: number } & { x: number, ... }"))); - CHECK("never" == toString(normal("{ y: number, ... } & { x: number }"))); - CHECK("never" == toString(normal("{ x: number } & { y: number }"))); - CHECK("{ x: number }" == toString(normal("{ x: number? } & { x: number | string }"))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "exact_table_with_read_only_property") -{ - CHECK("{ x: number }" == toString(normal("{ x: number } & { read x: number }"))); - CHECK("{ x: number }" == toString(normal("{ x: number } & { write x: number }"))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "exact_tables_with_nil_properties") -{ - CHECK("never" == toString(normal("{ } & { x: nil }"))); - CHECK("never" == toString(normal("{ x: nil } & { }"))); - CHECK("{ x: nil }" == toString(normal("{ x: nil } & { x: nil }"))); - CHECK("never" == toString(normal("{ } & { x: number? }"))); - CHECK("never" == toString(normal("{ x: nil } & { x: number }"))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "read_only_indexers_can_intersect") -{ - CHECK("{ [string]: number }" == toString(normal("{ read [string]: number } & { [string]: number | string }"))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "exact_tables_with_indexers") -{ - CHECK("{ [string]: number, x: number }" == toString(normal("{ x: number, ... } & { x: number, [string]: number }"))); - CHECK("{ [string]: number, x: number }" == toString(normal("{ x: number, y: number, ... } & { x: number, [string]: number }"))); - CHECK("{ [string]: number }" == toString(normal("{ [string]: number } & { x: number | boolean, ... }"))); - CHECK("never" == toString(normal("{ [string]: number } & { x: string, ... }"))); - CHECK("{ x: number }" == toString(normal("{ x: number } & { [string]: number, ... }"))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "exact_tables_with_matching_and_conflicting_indexers") -{ - CHECK("{ [string]: number }" == toString(normal("{ [string]: number } & { [string]: number }"))); - - CHECK("{ }" == toString(normal("{ [string]: number } & { [string]: string }"))); - CHECK("{ }" == toString(normal("{ [string]: number, ... } & { [string]: string }"))); - CHECK("{ }" == toString(normal("{ [string]: number } & { [string]: string, ... }"))); - CHECK("{ }" == toString(normal("{ [string]: number, ... } & { [string]: string, ... }"))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "inexact_tables_with_props_and_conflicting_indexers") -{ - // Note that the result is exact here: The indexers are impossible to - // simultaneously satisfy and so the only values that can satisfy both interfaces - // is a table with just the one prop. - CHECK("{ a: number }" == toString(normal("{ a: number, [number]: boolean, ... } & { a: number, [number]: string, ... }"))); - CHECK("never" == toString(normal("{ a: number, [number]: boolean, ... } & { a: string, [number]: string, ... }"))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "exact_tables_with_props_and_conflicting_indexers") -{ - CHECK("{ a: number }" == toString(normal("{ a: number, [number]: boolean } & { a: number, [number]: string }"))); - CHECK("never" == toString(normal("{ a: number, [number]: boolean } & { a: string, [number]: string }"))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "write_only_property_is_satisfied_by_writable_string_indexer") -{ - getBuiltins(); - TypeId propertyTable = arena.addType(TableType{{{"x", Property::writeonly(builtinTypes->numberType)}}, std::nullopt, {}, TableState::Sealed}); - TypeId indexerTable = arena.addType(TableType{{}, TableIndexer{builtinTypes->stringType, builtinTypes->numberType}, {}, TableState::Sealed}); - TypeId intersection = arena.addType(IntersectionType{{propertyTable, indexerTable}}); - - std::shared_ptr normalized = normalize(intersection); - REQUIRE(normalized); - CHECK("{ [string]: number, ... }" == toString(typeFromNormal(*normalized))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "read_only_property_intersects_with_string_indexer") -{ - TypeId n = normal("{ read x: string | boolean | nil, ... } & { [string]: string, ... }"); - - CHECK("{ [string]: string, ... }" == toString(n)); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "write_only_property_and_read_only_string_indexer") -{ - TypeId n = normal("{ write x: string | boolean | nil, ... } & { read [string]: string, ... }"); - - CHECK("{ read [string]: string, write x: (boolean | string)?, ... }" == toString(n)); } TEST_CASE_FIXTURE(NormalizeFixture, "split_read_write_property_must_satisfy_both_indexer_contracts") @@ -879,19 +766,11 @@ TEST_CASE_FIXTURE(NormalizeFixture, "split_read_write_property_must_satisfy_both std::shared_ptr normalized = normalize(intersection); REQUIRE(normalized); - if (FFlag::DebugLuauExactTableTypes) - CHECK("never" == toString(typeFromNormal(*normalized))); - else - CHECK("{ [string]: number, read x: number, write x: string }" == toString(typeFromNormal(*normalized))); + CHECK("{ [string]: number, read x: number, write x: string }" == toString(typeFromNormal(*normalized))); } TEST_CASE_FIXTURE(NormalizeFixture, "string_indexer_intersections") { - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, false}, - {FFlag::DebugLuauExactTableTypes, false}, - }; - CHECK("{ [string]: number, x: number }" == toString(normal("{ x: number } & { [string]: number }"))); CHECK("{ [string]: number, x: number, y: number }" == toString(normal("{ x: number, y: number } & { [string]: number }"))); CHECK("{ [string]: number, x: string }" == toString(normal("{ x: string } & { [string]: number }"))); @@ -900,22 +779,6 @@ TEST_CASE_FIXTURE(NormalizeFixture, "string_indexer_intersections") CHECK("{ [string]: number, x: number? }" == toString(normal("{ x: number? } & { [string]: number }"))); } -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "string_indexer_intersections_with_explicitly_inexact_tables") -{ - CHECK("{ [string]: number, ... }" == toString(normal("{ x: number, ... } & { [string]: number, ... }"))); - CHECK("{ [string]: number, ... }" == toString(normal("{ x: number, y: number, ... } & { [string]: number, ... }"))); - CHECK("never" == toString(normal("{ x: string, ... } & { [string]: number, ... }"))); - - // TODO? A truer answer might be { [string]: number, write x: number?, ... } - CHECK("{ [string]: number, ... }" == toString(normal("{ x: number?, ... } & { [string]: number, ... }"))); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "overlapping_inexact_indexers_are_uninhabited_due_to_variance") -{ - // Capturing this intersection exactly would require a split indexer { read [string]: string, write [string]: string | boolean | number } - CHECK("{ }" == toString(normal("{ [string | boolean]: string | boolean, ... } & { [string | number]: string | number, ... }"))); -} - TEST_CASE_FIXTURE(NormalizeFixture, "specific_functions_cannot_be_negated") { CHECK(nullptr == toNormalizedType("Not<(boolean) -> boolean>", !FFlag::DebugLuauForceOldSolver ? 1 : 0)); @@ -936,18 +799,9 @@ TEST_CASE_FIXTURE(NormalizeFixture, "trivial_intersection_inhabited") TEST_CASE_FIXTURE(NormalizeFixture, "bare_negated_boolean") { - if (FFlag::LuauIntegerType2) - { - CHECK("(buffer | function | integer | number | string | table | thread | userdata)?" == toString(normal(R"( + CHECK("(buffer | function | number | string | table | thread | userdata)?" == toString(normal(R"( Not )"))); - } - else - { - CHECK("(buffer | function | number | string | table | thread | userdata)?" == toString(normal(R"( - Not - )"))); - } } TEST_CASE_FIXTURE(Fixture, "higher_order_function_normalization") @@ -1039,16 +893,6 @@ TEST_CASE_FIXTURE(NormalizeFixture, "narrow_union_of_extern_types_with_intersect CHECK("Child" == toString(normal("(Child | Unrelated) & Child"))); } -TEST_CASE_FIXTURE(NormalizeFixture, "intersection_of_metatables_where_the_metatable_is_top_or_bottom") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; - - CHECK("setmetatable<{ ... }, *error-type*>" == toString(normal("Mt<{...}, any> & Mt<{...}, err>"))); -} - TEST_CASE_FIXTURE(NormalizeFixture, "recurring_intersection") { CheckResult result = check(R"( @@ -1114,34 +958,17 @@ TEST_CASE_FIXTURE(NormalizeFixture, "negations_of_extern_types") createSomeExternTypes(getFrontend()); CHECK("(Parent & ~Child) | Unrelated" == toString(normal("(Parent & Not) | Unrelated"))); - if (FFlag::LuauIntegerType2) - { - CHECK("((userdata & ~Child) | boolean | buffer | function | integer | number | string | table | thread)?" == toString(normal("Not"))); - CHECK("never" == toString(normal("Not & Child"))); - CHECK( - "((userdata & ~Parent) | Child | boolean | buffer | function | integer | number | string | table | thread)?" == - toString(normal("Not | Child")) - ); - CHECK("(boolean | buffer | function | integer | number | string | table | thread)?" == toString(normal("Not"))); - CHECK( - "(Parent | Unrelated | boolean | buffer | function | integer | number | string | table | thread)?" == - toString(normal("Not & Not & Not>")) - ); - } - else - { - CHECK("((userdata & ~Child) | boolean | buffer | function | number | string | table | thread)?" == toString(normal("Not"))); - CHECK("never" == toString(normal("Not & Child"))); - CHECK( - "((userdata & ~Parent) | Child | boolean | buffer | function | number | string | table | thread)?" == - toString(normal("Not | Child")) - ); - CHECK("(boolean | buffer | function | number | string | table | thread)?" == toString(normal("Not"))); - CHECK( - "(Parent | Unrelated | boolean | buffer | function | number | string | table | thread)?" == - toString(normal("Not & Not & Not>")) - ); - } + CHECK("((userdata & ~Child) | boolean | buffer | function | number | string | table | thread)?" == toString(normal("Not"))); + CHECK("never" == toString(normal("Not & Child"))); + CHECK( + "((userdata & ~Parent) | Child | boolean | buffer | function | number | string | table | thread)?" == + toString(normal("Not | Child")) + ); + CHECK("(boolean | buffer | function | number | string | table | thread)?" == toString(normal("Not"))); + CHECK( + "(Parent | Unrelated | boolean | buffer | function | number | string | table | thread)?" == + toString(normal("Not & Not & Not>")) + ); CHECK("Child" == toString(normal("(Child | Unrelated) & Not"))); } @@ -1157,28 +984,10 @@ TEST_CASE_FIXTURE(NormalizeFixture, "extern_types_and_never") CHECK("never" == toString(normal("Parent & never"))); } -TEST_CASE_FIXTURE(NormalizeFixture, "top_table_type") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; - - CHECK("table" == toString(normal("{} | tbl"))); - if (FFlag::DebugLuauForceOldSolver) - CHECK("{ ... }" == toString(normal("{} & tbl"))); - else - CHECK("{ }" == toString(normal("{} & tbl"))); - CHECK("never" == toString(normal("number & tbl"))); -} - TEST_CASE_FIXTURE(NormalizeFixture, "negations_of_tables") { CHECK(nullptr == toNormalizedType("Not<{}>", !FFlag::DebugLuauForceOldSolver ? 1 : 0)); - if (FFlag::LuauIntegerType2) - CHECK("(boolean | buffer | function | integer | number | string | thread | userdata)?" == toString(normal("Not"))); - else - CHECK("(boolean | buffer | function | number | string | thread | userdata)?" == toString(normal("Not"))); + CHECK("(boolean | buffer | function | number | string | thread | userdata)?" == toString(normal("Not"))); CHECK("table" == toString(normal("Not>"))); } @@ -1295,34 +1104,6 @@ TEST_CASE_FIXTURE(NormalizeFixture, "cyclic_stack_overflow_2") CHECK(normalized); } -TEST_CASE_FIXTURE(NormalizeFixture, "truthy_table_property_and_optional_table_with_optional_prop") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; - - // { x: ~(false?) } - TypeId t1 = arena.addType(TableType{TableType::Props{{"x", getBuiltins()->truthyType}}, std::nullopt, TypeLevel{}, TableState::Sealed}); - - // { x: number? }? - TypeId t2 = arena.addType( - UnionType{ - {arena.addType(TableType{TableType::Props{{"x", getBuiltins()->optionalNumberType}}, std::nullopt, TypeLevel{}, TableState::Sealed}), - getBuiltins()->nilType} - } - ); - - TypeId intersection = arena.addType(IntersectionType{{t2, t1}}); - - auto norm = normalize(intersection); - REQUIRE(norm); - - TypeId ty = typeFromNormal(*norm); - CHECK("{ x: number, ... }" == toString(ty)); -} - TEST_CASE_FIXTURE(NormalizeFixture, "free_type_and_not_truthy") { ScopedFastFlag sff[] = { @@ -1384,35 +1165,6 @@ TEST_CASE_FIXTURE(NormalizeFixture, "normalize_class_against_union_of_tables") CHECK("never" == toString(normalized)); } -TEST_CASE_FIXTURE(NormalizeFixture, "intersection_of_table_and_truthy") -{ - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - ScopedFastFlag sffs[] = { - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; - - TableType tt{{{"x", Property::rw(getBuiltins()->numberType)}}, std::nullopt, {}, TableState::Sealed}; - TypeId tbl = arena.addType(std::move(tt)); - - IntersectionBuilder ib{NotNull{&arena}, NotNull{builtinTypes}}; - ib.add(builtinTypes->truthyType); - ib.add(tbl); - - auto norm = normalize(ib.build()); - REQUIRE(norm); - TypeId ty = typeFromNormal(*norm); - - // This looks a little funky, because it is! You can think of this as being - // equivalent to ... - // - // (userdata & { x: number }) | (table & { x: number }) - // - // ... but Luau simplifies `table & { x: number }` to just mean `table`. - CHECK("(userdata & { x: number, ... }) | { x: number, ... }" == toString(ty)); -} - TEST_CASE_FIXTURE(NormalizeFixture, "negation_of_testable_intersection_type_1") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); @@ -1439,13 +1191,7 @@ TEST_CASE_FIXTURE(NormalizeFixture, "negation_of_testable_intersection_type_2") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag sffs[] = { - {FFlag::LuauDecomposeIntersectionOfFreeType, true}, - // This is forced on here so that I don't need to check the - // output string twice, it's not essential to the test. - {FFlag::LuauIntegerType2, true}, - }; - + ScopedFastFlag sff{FFlag::LuauDecomposeIntersectionOfFreeType, true}; IntersectionBuilder ib{NotNull{&arena}, NotNull{getBuiltins()}}; ib.add(getBuiltins()->unknownType); @@ -1460,7 +1206,7 @@ TEST_CASE_FIXTURE(NormalizeFixture, "negation_of_testable_intersection_type_2") REQUIRE(norm); TypeId ty = typeFromNormal(*norm); - CHECK("(\"foo\" | boolean | buffer | function | integer | number | table | thread | userdata)?" == toString(ty)); + CHECK("(\"foo\" | boolean | buffer | function | number | table | thread | userdata)?" == toString(ty)); } TEST_CASE_FIXTURE(NormalizeFixture, "negation_of_testable_intersection_type_3") @@ -1671,48 +1417,4 @@ _[_] ^= _(_(_)) } #endif -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "exact_table_intersection_with_overlapping_indexers") -{ - // Two exact tables with indexers whose result types overlap but are not - // identical. The intersection should be inhabited with an indexer whose - // result type is the intersection of the two. - - std::shared_ptr norm = toNormalizedType(R"( - { [number]: number | string } & { [number]: string | boolean } - )"); - - REQUIRE(norm); - CHECK(isInhabited(norm.get())); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "exact_table_intersection_with_disjoint_indexers_is_never") -{ - // Two exact tables with indexers whose result types are disjoint. The - // intersection should be uninhabited. - - std::shared_ptr norm = toNormalizedType(R"( - { [number]: number } & { [number]: string } - )"); - - REQUIRE(norm); - CHECK(isInhabited(norm.get())); - - TypeId t = normalizer->typeFromNormal(*norm); - CHECK("{ }" == toString(t)); -} - -TEST_CASE_FIXTURE(ExactTableNormalizationFixture, "exact_table_intersection_with_equivalent_union_indexers") -{ - // Two exact tables with indexers whose result types are the same union but - // with members in different order. The intersection should be inhabited - // and simplify to the original indexer. - - std::shared_ptr norm = toNormalizedType(R"( - { [number]: number | string } & { [number]: string | number } - )"); - - REQUIRE(norm); - CHECK(isInhabited(norm.get())); -} - TEST_SUITE_END(); diff --git a/tests/Parser.test.cpp b/tests/Parser.test.cpp index 2509327b1..49be88a40 100644 --- a/tests/Parser.test.cpp +++ b/tests/Parser.test.cpp @@ -19,10 +19,8 @@ LUAU_FASTINT(LuauParseErrorLimit) LUAU_DYNAMIC_FASTFLAG(DebugLuauReportReturnTypeVariadicWithTypeSuffix) LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(DebugLuauNoInline) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauAllowGlobalDeclarationToBeCalledClass) -LUAU_FASTFLAG(DebugLuauParseExactTables) LUAU_FASTFLAG(LuauSingleTypeOptionalPackReturnsAttributeParens) LUAU_FASTFLAG(LuauExperimentalIfLocalSyntax) @@ -834,19 +832,6 @@ TEST_CASE_FIXTURE(Fixture, "parse_numbers_decimal") CHECK_EQ(str->list.data[3]->as()->value, 1.0e-5); CHECK_EQ(str->list.data[4]->as()->value, 1.5e-5); CHECK_EQ(str->list.data[5]->as()->value, 12345.125); - - if (FFlag::LuauIntegerType2) - { - stat = parse("return 1i, 1_000_000i"); - REQUIRE(stat != nullptr); - - str = stat->as()->body.data[0]->as(); - CHECK(str->list.size == 2); - CHECK(str->list.data[0]->is()); - CHECK_EQ(str->list.data[0]->as()->value, 1); - CHECK(str->list.data[1]->is()); - CHECK_EQ(str->list.data[1]->as()->value, 1000000); - } } TEST_CASE_FIXTURE(Fixture, "parse_numbers_hexadecimal") @@ -860,21 +845,6 @@ TEST_CASE_FIXTURE(Fixture, "parse_numbers_hexadecimal") CHECK_EQ(str->list.data[1]->as()->value, 0xAB05); CHECK_EQ(str->list.data[2]->as()->value, 0xFFFF); CHECK_EQ(str->list.data[3]->as()->value, double(ULLONG_MAX)); - - if (FFlag::LuauIntegerType2) - { - stat = parse("return 0xabi, 0XAB05i, 0xff_ffi, 0x7fffffffffffffffi, 0x8000000000000000i, 0xffffffffffffffffi"); - REQUIRE(stat != nullptr); - - str = stat->as()->body.data[0]->as(); - CHECK(str->list.size == 6); - CHECK_EQ(str->list.data[0]->as()->value, 0xab); - CHECK_EQ(str->list.data[1]->as()->value, 0xAB05); - CHECK_EQ(str->list.data[2]->as()->value, 0xFFFF); - CHECK_EQ(str->list.data[3]->as()->value, LLONG_MAX); - CHECK_EQ(str->list.data[4]->as()->value, LLONG_MIN); - CHECK_EQ(str->list.data[5]->as()->value, -1); - } } TEST_CASE_FIXTURE(Fixture, "parse_numbers_binary") @@ -888,24 +858,6 @@ TEST_CASE_FIXTURE(Fixture, "parse_numbers_binary") CHECK_EQ(str->list.data[1]->as()->value, 0); CHECK_EQ(str->list.data[2]->as()->value, 42); CHECK_EQ(str->list.data[3]->as()->value, double(ULLONG_MAX)); - - if (FFlag::LuauIntegerType2) - { - AstStat* stat = parse( - "return 0b1i, 0b0i, 0b101010i, 0b111111111111111111111111111111111111111111111111111111111111111i, " - "0b1000000000000000000000000000000000000000000000000000000000000000i, 0b1111111111111111111111111111111111111111111111111111111111111111i" - ); - REQUIRE(stat != nullptr); - - str = stat->as()->body.data[0]->as(); - CHECK(str->list.size == 6); - CHECK_EQ(str->list.data[0]->as()->value, 1); - CHECK_EQ(str->list.data[1]->as()->value, 0); - CHECK_EQ(str->list.data[2]->as()->value, 42); - CHECK_EQ(str->list.data[3]->as()->value, LLONG_MAX); - CHECK_EQ(str->list.data[4]->as()->value, LLONG_MIN); - CHECK_EQ(str->list.data[5]->as()->value, -1); - } } TEST_CASE_FIXTURE(Fixture, "parse_numbers_error") @@ -917,22 +869,9 @@ TEST_CASE_FIXTURE(Fixture, "parse_numbers_error") matchParseError("return 0x0x123", "Malformed number"); matchParseError("return 0xffffffffffffffffffffllllllg", "Malformed number"); matchParseError("return 0x0xffffffffffffffffffffffffffff", "Malformed number"); - if (FFlag::LuauIntegerType2) - { - matchParseError("return 0x0xABCi", "Malformed integer"); - matchParseError("return 0xABCMi", "Malformed integer"); - matchParseError("return 0b250i", "Malformed integer"); - matchParseError("return 0bbbbi", "Malformed integer"); - matchParseError("return 0b0b1i", "Malformed integer"); - matchParseError("return 123ii", "Malformed integer"); - matchParseError("return 0xABii", "Malformed integer"); - - matchParseError("return 99999999999999999999i", "Integer overflow"); - matchParseError("return 0xFFFFFFFFFFFFFFFFFFi", "Integer overflow"); - matchParseError("return 0b10000000000000000000000000000000000000000000000000000000000000000i", "Integer overflow"); - matchParseError("return 123ii", "Malformed integer"); - matchParseError("return 0xABii", "Malformed integer"); - } + matchParseError("return 1i", "Malformed number"); + matchParseError("return 0xABi", "Malformed number"); + matchParseError("return 0b1i", "Malformed number"); } TEST_CASE_FIXTURE(Fixture, "break_return_not_last_error") @@ -3339,7 +3278,7 @@ TEST_CASE_FIXTURE(Fixture, "class_declaration") ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; ParseResult res = tryParse(R"( - class Point2 + local class Point2 public x: number public y: number end @@ -3351,7 +3290,7 @@ TEST_CASE_FIXTURE(Fixture, "class_declaration") REQUIRE(2 == res.root->body.size); const AstStatClass* first = res.root->body.data[0]->as(); REQUIRE(first); - CHECK(first->name->name == "Point2"); + CHECK(first->localName->name == "Point2"); REQUIRE(first->members.size == 2); @@ -3374,7 +3313,7 @@ TEST_CASE_FIXTURE(Fixture, "class_declaration") const AstExprLocal* local = call->args.data[0]->as(); REQUIRE(local); - CHECK(local->local == first->name); + CHECK(local->local == first->localName); } TEST_CASE_FIXTURE(Fixture, "class_parse_errors") @@ -3444,11 +3383,11 @@ TEST_CASE_FIXTURE(Fixture, "class_extends_basic") ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; ParseResult result = tryParse(R"( -open class Animal +local open class Animal public species: string end -class Cat extends Animal +local class Cat extends Animal public meowMult: number end )"); @@ -3472,7 +3411,7 @@ end const AstExprLocal* superLocal = super->as(); REQUIRE(superLocal); - CHECK(superLocal->local == animal->name); + CHECK(superLocal->local == animal->localName); } TEST_CASE_FIXTURE(Fixture, "class_extends_same_name_refers_to_outer_binding") @@ -3481,7 +3420,7 @@ TEST_CASE_FIXTURE(Fixture, "class_extends_same_name_refers_to_outer_binding") ParseResult result = tryParse(R"( local Foo = nil -class Foo extends Foo +local class Foo extends Foo end )"); @@ -3498,12 +3437,13 @@ end const AstExprLocal* superLocal = cls->super->as(); REQUIRE(superLocal); CHECK(superLocal->local == outer->vars.data[0]); - CHECK(superLocal->local != cls->name); + CHECK(superLocal->local != cls->localName); } TEST_CASE_FIXTURE(Fixture, "class_exported_open") { ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + ScopedFastFlag evs{FFlag::LuauExportValueSyntax, true}; matchParseError( R"( @@ -3511,7 +3451,7 @@ export open Animal public species: string end )", - "Incomplete statement: expected a class definition after 'open'" + "'export' must be followed by an identifier, 'function', or a class declaration" ); matchParseError( @@ -3540,7 +3480,7 @@ end const AstStatClass* animal = result.root->body.data[0]->as(); REQUIRE(animal); CHECK(animal->super == nullptr); - CHECK(animal->exported); + CHECK(animal->declModifier == AstStatClass::DeclModifier::Export); CHECK(animal->open); } @@ -3660,7 +3600,7 @@ TEST_CASE_FIXTURE(Fixture, "class_recovery_public_no_name_and_invalid_body_token ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; ParseResult result = tryParse(R"( -class Foo +local class Foo public propone function methodone() end @@ -3680,7 +3620,7 @@ end REQUIRE_EQ(result.root->body.size, 1); const AstStatClass* cls = result.root->body.data[0]->as(); REQUIRE(cls); - CHECK(cls->name->name == "Foo"); + CHECK(cls->localName->name == "Foo"); REQUIRE(cls->members.size == 3); @@ -3749,11 +3689,11 @@ end TEST_CASE_FIXTURE(Fixture, "reassigned_class") { ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; - ScopedFastFlag exportFlag{FFlag::LuauExportValueSyntax, true}; + ScopedFastFlag evs{FFlag::LuauExportValueSyntax, true}; matchParseError( R"( -class Animal end +const class Animal end Animal = nil )", "Variable 'Animal' is constant and may not be reassigned" // const reassignment msg @@ -3848,7 +3788,7 @@ TEST_CASE_FIXTURE(Fixture, "classes_can_interleave_methods_and_properties") ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; ParseResult res = tryParse(R"( - class Student + local class Student public name: string function getname(self): string @@ -3869,7 +3809,7 @@ TEST_CASE_FIXTURE(Fixture, "classes_can_interleave_methods_and_properties") REQUIRE(1 == res.root->body.size); const AstStatClass* cls = res.root->body.data[0]->as(); REQUIRE(cls); - CHECK(cls->name->name == "Student"); + CHECK(cls->localName->name == "Student"); REQUIRE(cls->members.size == 4); @@ -3927,32 +3867,28 @@ TEST_CASE_FIXTURE(Fixture, "large_classes_example") REQUIRE_EQ(result.errors.size(), 0); } -TEST_CASE_FIXTURE(Fixture, "classes_only_work_at_top_level") +TEST_CASE_FIXTURE(Fixture, "classes_can_be_non_top_level") { ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; - matchParseError( - R"( - return function () - class DynamicPlayer - public level: number - end - return DynamicPlayer + ParseResult res = tryParse(R"( + return function () + class DynamicPlayer + public level: number end - )", - "Cannot declare class 'DynamicPlayer' inside another statement or expression" - ); + return DynamicPlayer + end + )"); + REQUIRE(res.errors.empty()); - matchParseError( - R"( - if math.random() > 0.5 then - class DynamicPlayer - public level: number - end + res = tryParse(R"( + if math.random() > 0.5 then + class DynamicPlayer + public level: number end - )", - "Cannot declare class 'DynamicPlayer' inside another statement or expression" - ); + end + )"); + REQUIRE(res.errors.empty()); } TEST_CASE_FIXTURE(Fixture, "classes_work_after_other_statements") @@ -3964,7 +3900,7 @@ TEST_CASE_FIXTURE(Fixture, "classes_work_after_other_statements") print("I am a test case!") end - class Player + local class Player public health: number end )"); @@ -3974,7 +3910,7 @@ TEST_CASE_FIXTURE(Fixture, "classes_work_after_other_statements") REQUIRE(2 == res.root->body.size); const AstStatClass* cls = res.root->body.data[1]->as(); REQUIRE(cls); - CHECK(cls->name->name == "Player"); + CHECK(cls->localName->name == "Player"); } TEST_CASE_FIXTURE(Fixture, "class_is_still_contextual") @@ -4007,28 +3943,24 @@ TEST_CASE_FIXTURE(Fixture, "class_self_cannot_be_annotated") ); } -TEST_CASE_FIXTURE(Fixture, "classes_cannot_be_shadowed_by_classes") +TEST_CASE_FIXTURE(Fixture, "classes_can_be_shadowed_by_classes") { ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; - matchParseError( - R"( + ParseResult result = tryParse(R"( class Foobar end class Foobar end - )", - "A class named 'Foobar' has already been declared in this module" - ); + )"); } -TEST_CASE_FIXTURE(Fixture, "classes_cannot_be_shadowed_by_classes_with_local_between") +TEST_CASE_FIXTURE(Fixture, "classes_can_be_shadowed_by_classes_with_local_between") { ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; - matchParseError( - R"( + ParseResult result = tryParse(R"( class Foobar end @@ -4036,9 +3968,9 @@ TEST_CASE_FIXTURE(Fixture, "classes_cannot_be_shadowed_by_classes_with_local_bet class Foobar end - )", - "A class named 'Foobar' has already been declared in this module" - ); + )"); + + CHECK(result.errors.empty()); } TEST_CASE_FIXTURE(Fixture, "classes_can_be_shadowed_by_locals") @@ -4087,10 +4019,7 @@ TEST_CASE_FIXTURE(Fixture, "classes_nested_and_repeated") end )"); - // We only report one error per location, so even though "two" errors - // occur here (repeat name, nested), we'll only get one message. - REQUIRE(result.errors.size() == 1); - CHECK_EQ("Cannot declare class 'Foo' inside another statement or expression", result.errors[0].getMessage()); + REQUIRE(result.errors.size() == 0); } TEST_CASE_FIXTURE(Fixture, "non_exported_class") @@ -4109,7 +4038,7 @@ TEST_CASE_FIXTURE(Fixture, "non_exported_class") AstStatClass* classDecl = block->body.data[0]->as(); REQUIRE(classDecl != nullptr); - CHECK(!classDecl->exported); + CHECK(classDecl->declModifier == AstStatClass::DeclModifier::None); } TEST_CASE_FIXTURE(Fixture, "export_class") @@ -4128,7 +4057,506 @@ TEST_CASE_FIXTURE(Fixture, "export_class") AstStatClass* classDecl = block->body.data[0]->as(); REQUIRE(classDecl != nullptr); - CHECK(classDecl->exported); + CHECK(classDecl->declModifier == AstStatClass::DeclModifier::Export); +} + +TEST_CASE_FIXTURE(Fixture, "class_decl_modifiers") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::LuauExportValueSyntax, true}}; + + ParseResult result = tryParse(R"( + class Bare end + local class Local end + const class Const end + export class Exported end + )"); + + REQUIRE(result.errors.empty()); + REQUIRE_EQ(4, result.root->body.size); + + const AstStatClass* bare = result.root->body.data[0]->as(); + REQUIRE(bare); + CHECK(bare->declModifier == AstStatClass::DeclModifier::None); + CHECK(bare->exprName->is()); + CHECK(bare->getName() == "Bare"); + + const AstStatClass* local = result.root->body.data[1]->as(); + REQUIRE(local); + CHECK(local->declModifier == AstStatClass::DeclModifier::Local); + CHECK(local->localName->name == "Local"); + CHECK(!local->localName->isConst); + CHECK(!local->localName->isExported); + + const AstStatClass* constant = result.root->body.data[2]->as(); + REQUIRE(constant); + CHECK(constant->declModifier == AstStatClass::DeclModifier::Const); + CHECK(constant->localName->name == "Const"); + CHECK(constant->localName->isConst); + CHECK(!constant->localName->isExported); + + const AstStatClass* exported = result.root->body.data[3]->as(); + REQUIRE(exported); + CHECK(exported->declModifier == AstStatClass::DeclModifier::Export); + CHECK(exported->localName->name == "Exported"); + CHECK(exported->localName->isConst); + CHECK(exported->localName->isExported); +} + +TEST_CASE_FIXTURE(Fixture, "open_class_with_each_decl_modifier") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::LuauExportValueSyntax, true}}; + + ParseResult result = tryParse(R"( + open class Bare end + local open class Local end + const open class Const end + export open class Exported end + )"); + + REQUIRE(result.errors.empty()); + REQUIRE_EQ(4, result.root->body.size); + + const AstStatClass::DeclModifier expected[] = { + AstStatClass::DeclModifier::None, + AstStatClass::DeclModifier::Local, + AstStatClass::DeclModifier::Const, + AstStatClass::DeclModifier::Export, + }; + + for (size_t i = 0; i < 4; ++i) + { + const AstStatClass* cls = result.root->body.data[i]->as(); + REQUIRE(cls); + CHECK(cls->open); + CHECK(cls->declModifier == expected[i]); + } +} + +TEST_CASE_FIXTURE(Fixture, "class_decl_location_includes_modifier") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + std::string code = R"( + local open class Foo end + class Bar end + )"; + + ParseResult result = tryParse(code); + REQUIRE(result.errors.empty()); + REQUIRE_EQ(2, result.root->body.size); + + const AstStatClass* foo = result.root->body.data[0]->as(); + REQUIRE(foo); + CHECK_EQ(stringAtLocation(code, foo->location), "local open class Foo end"); + CHECK_EQ(stringAtLocation(code, foo->getNameLocation()), "Foo"); + + const AstStatClass* bar = result.root->body.data[1]->as(); + REQUIRE(bar); + CHECK_EQ(stringAtLocation(code, bar->location), "class Bar end"); + CHECK_EQ(stringAtLocation(code, bar->getNameLocation()), "Bar"); +} + +TEST_CASE_FIXTURE(Fixture, "bare_class_assigns_to_existing_local") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + local Foo = nil + class Foo end + + local class Bar end + class Bar end + )"); + + REQUIRE(result.errors.empty()); + REQUIRE_EQ(4, result.root->body.size); + + const AstStatLocal* fooLocal = result.root->body.data[0]->as(); + REQUIRE(fooLocal); + const AstStatClass* fooClass = result.root->body.data[1]->as(); + REQUIRE(fooClass); + const AstExprLocal* fooRef = fooClass->exprName->as(); + REQUIRE(fooRef); + CHECK(fooRef->local == fooLocal->vars.data[0]); + CHECK(!fooRef->upvalue); + + const AstStatClass* barLocal = result.root->body.data[2]->as(); + REQUIRE(barLocal); + const AstStatClass* barClass = result.root->body.data[3]->as(); + REQUIRE(barClass); + const AstExprLocal* barRef = barClass->exprName->as(); + REQUIRE(barRef); + CHECK(barRef->local == barLocal->localName); +} + +TEST_CASE_FIXTURE(Fixture, "bare_class_assigns_to_function_parameter_and_upvalue") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + local Outer + local function f(Param) + class Param end + class Outer end + end + )"); + + REQUIRE(result.errors.empty()); + REQUIRE_EQ(2, result.root->body.size); + + const AstStatLocal* outerLocal = result.root->body.data[0]->as(); + REQUIRE(outerLocal); + const AstStatLocalFunction* fn = result.root->body.data[1]->as(); + REQUIRE(fn); + REQUIRE_EQ(2, fn->func->body->body.size); + + const AstStatClass* paramClass = fn->func->body->body.data[0]->as(); + REQUIRE(paramClass); + const AstExprLocal* paramRef = paramClass->exprName->as(); + REQUIRE(paramRef); + CHECK(paramRef->local == fn->func->args.data[0]); + CHECK(!paramRef->upvalue); + + const AstStatClass* outerClass = fn->func->body->body.data[1]->as(); + REQUIRE(outerClass); + const AstExprLocal* outerRef = outerClass->exprName->as(); + REQUIRE(outerRef); + CHECK(outerRef->local == outerLocal->vars.data[0]); + CHECK(outerRef->upvalue); +} + +TEST_CASE_FIXTURE(Fixture, "bare_class_cannot_reassign_constants") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::LuauExportValueSyntax, true}}; + + ParseResult result = matchParseError( + R"( +const class Foo end +class Foo end + )", + "Variable 'Foo' is constant and may not be reassigned" + ); + REQUIRE_EQ(2, result.root->body.size); + const AstStatClass* reassigned = result.root->body.data[1]->as(); + REQUIRE(reassigned); + CHECK(reassigned->exprName->is()); + + matchParseError( + R"( +const Foo = 1 +class Foo end + )", + "Variable 'Foo' is constant and may not be reassigned" + ); + + matchParseError( + R"( +export class Foo end +class Foo end + )", + "Variable 'Foo' is constant and may not be reassigned" + ); +} + +TEST_CASE_FIXTURE(Fixture, "bare_class_cannot_assign_to_local_outside_type_function") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + matchParseError( + R"( +local Foo = 1 +type function tf() + class Foo end + return types.any +end + )", + "Type function cannot assign to outer local 'Foo'" + ); +} + +TEST_CASE_FIXTURE(Fixture, "export_local_class_is_an_error") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::LuauExportValueSyntax, true}}; + + matchParseError( + R"( +export local class Foo end + )", + "'export' must be followed by an identifier, 'function', or a class declaration; try removing 'local'" + ); +} + +TEST_CASE_FIXTURE(Fixture, "local_class_is_lexically_scoped") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + do + local class Foo end + print(Foo) + end + print(Foo) + )"); + + REQUIRE(result.errors.empty()); + REQUIRE_EQ(2, result.root->body.size); + + const AstStatBlock* doBlock = result.root->body.data[0]->as(); + REQUIRE(doBlock); + REQUIRE_EQ(2, doBlock->body.size); + + const AstStatClass* cls = doBlock->body.data[0]->as(); + REQUIRE(cls); + + const AstStatExpr* inner = doBlock->body.data[1]->as(); + REQUIRE(inner); + const AstExprCall* innerCall = inner->expr->as(); + REQUIRE(innerCall); + REQUIRE_EQ(1, innerCall->args.size); + const AstExprLocal* innerRef = innerCall->args.data[0]->as(); + REQUIRE(innerRef); + CHECK(innerRef->local == cls->localName); + + const AstStatExpr* outer = result.root->body.data[1]->as(); + REQUIRE(outer); + const AstExprCall* outerCall = outer->expr->as(); + REQUIRE(outerCall); + REQUIRE_EQ(1, outerCall->args.size); + CHECK(outerCall->args.data[0]->is()); +} + +TEST_CASE_FIXTURE(Fixture, "local_class_is_visible_inside_its_own_methods") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + local class Foo + function make() + return Foo + end + end + )"); + + REQUIRE(result.errors.empty()); + REQUIRE_EQ(1, result.root->body.size); + + const AstStatClass* cls = result.root->body.data[0]->as(); + REQUIRE(cls); + REQUIRE_EQ(1, cls->members.size); + + const AstClassMethod* make = cls->members.data[0].get_if(); + REQUIRE(make); + REQUIRE_EQ(1, make->function->body->body.size); + + const AstStatReturn* ret = make->function->body->body.data[0]->as(); + REQUIRE(ret); + REQUIRE_EQ(1, ret->list.size); + const AstExprLocal* ref = ret->list.data[0]->as(); + REQUIRE(ref); + CHECK(ref->local == cls->localName); + CHECK(ref->upvalue); +} + +TEST_CASE_FIXTURE(Fixture, "local_class_can_shadow_local_class") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + local class Foo end + local class Foo end + print(Foo) + )"); + + REQUIRE(result.errors.empty()); + REQUIRE_EQ(3, result.root->body.size); + + const AstStatClass* first = result.root->body.data[0]->as(); + REQUIRE(first); + const AstStatClass* second = result.root->body.data[1]->as(); + REQUIRE(second); + CHECK(first->localName != second->localName); + + const AstStatExpr* use = result.root->body.data[2]->as(); + REQUIRE(use); + const AstExprCall* call = use->expr->as(); + REQUIRE(call); + REQUIRE_EQ(1, call->args.size); + const AstExprLocal* ref = call->args.data[0]->as(); + REQUIRE(ref); + CHECK(ref->local == second->localName); +} + +TEST_CASE_FIXTURE(Fixture, "classes_in_nested_blocks") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + do + local class A end + end + + while true do + const class B end + break + end + + repeat + class C end + until true + + for i = 1, 2 do + local open class D end + end + + for _, v in {} do + class E end + end + + if math.random() > 0.5 then + local class F end + elseif math.random() > 0.5 then + const class G end + else + class H end + end + + local f = function() + local class I end + return I + end + + local class Outer + function method(self) + local class Inner end + class Global end + return Inner + end + end + )"); + + CHECK(result.errors.empty()); +} + +TEST_CASE_FIXTURE(Fixture, "export_class_must_be_top_level") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::LuauExportValueSyntax, true}}; + + matchParseError( + R"( +do + export class Foo end +end + )", + "'export' may only be applied to top-level statements" + ); + + matchParseError( + R"( +local function f() + export class Foo end +end + )", + "'export' may only be applied to top-level statements" + ); + + matchParseError( + R"( +local class Outer + function method(self) + export class Inner end + end +end + )", + "'export' may only be applied to top-level statements" + ); +} + +TEST_CASE_FIXTURE(Fixture, "export_const_class_is_an_error") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::LuauExportValueSyntax, true}}; + + ParseResult result = matchParseError( + R"( +export const class Foo end + )", + "'export' must be followed by an identifier, 'function', or a class declaration; try removing 'const'" + ); + + // The class is still parsed for error recovery. + REQUIRE_EQ(1, result.root->body.size); + const AstStatClass* cls = result.root->body.data[0]->as(); + REQUIRE(cls); + CHECK(cls->declModifier == AstStatClass::DeclModifier::Const); + CHECK(cls->localName->name == "Foo"); +} + +TEST_CASE_FIXTURE(Fixture, "duplicate_exported_class") +{ + ScopedFastFlag sffs[] = {{FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::LuauExportValueSyntax, true}}; + + matchParseError( + R"( +export class Foo end +export class Foo end + )", + "Duplicate exported identifier 'Foo'" + ); + + matchParseError( + R"( +export const Foo = 1 +export class Foo end + )", + "Duplicate exported identifier 'Foo'" + ); +} + +TEST_CASE_FIXTURE(Fixture, "class_and_open_are_contextual_after_local_and_const") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + local class: number = 1 + local open = 2 + local open, class = 3, 4 + const class = 5 + local open + )"); + + REQUIRE(result.errors.empty()); + REQUIRE_EQ(5, result.root->body.size); + + for (size_t i = 0; i < 5; ++i) + CHECK(result.root->body.data[i]->is()); +} + +TEST_CASE_FIXTURE(Fixture, "attributes_are_not_supported_on_local_classes") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = matchParseError( + R"( +@native local class Foo end + )", + "Attributes are not supported on class declarations" + ); + + REQUIRE_EQ(1, result.root->body.size); + const AstStatClass* cls = result.root->body.data[0]->as(); + REQUIRE(cls); + CHECK(cls->declModifier == AstStatClass::DeclModifier::Local); + + result = matchParseError( + R"( +@native const class Foo end + )", + "Attributes are not supported on class declarations" + ); + + REQUIRE_EQ(1, result.root->body.size); + cls = result.root->body.data[0]->as(); + REQUIRE(cls); + CHECK(cls->declModifier == AstStatClass::DeclModifier::Const); } TEST_CASE_FIXTURE(Fixture, "class_private_property") @@ -4290,6 +4718,41 @@ TEST_CASE_FIXTURE(Fixture, "class_private_access_in_nested_closure") CHECK(index->privateAccess); } +TEST_CASE_FIXTURE(Fixture, "class_private_access_in_nested_class_super") +{ + ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; + + ParseResult result = tryParse(R"( + local class Kass + private _cl + public function f(self) + class Mipha extends self._cl + end + end + end + )"); + + REQUIRE(result.errors.empty()); + + REQUIRE(result.root->body.size == 1); + const AstStatClass* outer = result.root->body.data[0]->as(); + REQUIRE(outer); + REQUIRE(outer->members.size == 2); + + auto method = outer->members.data[1].get_if(); + REQUIRE(method); + REQUIRE(method->function->body->body.size == 1); + + const AstStatClass* inner = method->function->body->body.data[0]->as(); + REQUIRE(inner); + REQUIRE(inner->super); + + const AstExprIndexName* super = inner->super->as(); + REQUIRE(super); + CHECK(super->index == "_cl"); + CHECK(super->privateAccess); +} + TEST_CASE_FIXTURE(Fixture, "class_private_access_only_inside_method_body") { ScopedFastFlag _{FFlag::DebugLuauUserDefinedClasses, true}; @@ -4535,92 +4998,6 @@ TEST_CASE_FIXTURE(Fixture, "type_pack_explicit_with_cst") CHECK_EQ(cstNode->commaPositions.data[0], Position{0, 22}); } -TEST_CASE_FIXTURE(Fixture, "valid_exact_table_types") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - }; - - ParseResult result = tryParse(R"( - type A = {} - type B = {x: number} - type C = {x: number, ...} - type D = {...} - type E = {[number]: boolean, ...} - type F = {number} - type G = {number, ...} - )"); - - AstStatBlock* block = result.root; - REQUIRE(7 == block->body.size); - - auto alias0 = block->body.data[0]->as(); - REQUIRE(alias0->type->as()); - CHECK(alias0->type->as()->isExact); - - auto alias1 = block->body.data[1]->as(); - REQUIRE(alias1->type->as()); - CHECK(alias1->type->as()->isExact); - - auto alias2 = block->body.data[2]->as(); - REQUIRE(alias2->type->as()); - CHECK(!alias2->type->as()->isExact); - - auto alias3 = block->body.data[3]->as(); - REQUIRE(alias3->type->as()); - CHECK(!alias3->type->as()->isExact); - - auto alias4 = block->body.data[4]->as(); - REQUIRE(alias4->type->as()); - CHECK(!alias4->type->as()->isExact); - - auto alias5 = block->body.data[5]->as(); - REQUIRE(alias5->type->as()); - CHECK(alias5->type->as()->isExact); - - auto alias6 = block->body.data[6]->as(); - REQUIRE(alias6->type->as()); - CHECK(!alias6->type->as()->isExact); -} - -TEST_CASE_FIXTURE(Fixture, "invalid_exact_table_types") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - }; - - ParseResult result = tryParse(R"( - type A = {read ...} - )"); - - CHECK(0 != result.errors.size()); -} - -TEST_CASE_FIXTURE(Fixture, "exact_table_type_ellipsis_must_be_last") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - }; - - ParseResult result = tryParse(R"( - type A = {..., x: number} - )"); - - CHECK(result.errors.size() == 1); - - CHECK(Location({1, 21}, {1, 22}) == result.errors.at(0).getLocation()); - - REQUIRE(result.root); - REQUIRE(result.root->body.size == 1); - - AstStatTypeAlias* alias = result.root->body.data[0]->as(); - REQUIRE(alias); - - AstTypeTable* table = alias->type->as(); - REQUIRE(table); - CHECK(!table->isExact); -} - TEST_CASE_FIXTURE(Fixture, "optional_return_type_pack_with_cst_func_return") { ScopedFastFlag sff2{FFlag::LuauSingleTypeOptionalPackReturnsAttributeParens, true}; diff --git a/tests/Repl.test.cpp b/tests/Repl.test.cpp index fb3801b0d..1c12bb267 100644 --- a/tests/Repl.test.cpp +++ b/tests/Repl.test.cpp @@ -13,7 +13,6 @@ #include #include -LUAU_FASTFLAG(LuauIntegerType2) struct Completion { diff --git a/tests/RequireByString.test.cpp b/tests/RequireByString.test.cpp index 3be94760b..4f10e80ab 100644 --- a/tests/RequireByString.test.cpp +++ b/tests/RequireByString.test.cpp @@ -29,7 +29,6 @@ LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(DebugLuauUserDefinedClassesRuntime) LUAU_FASTFLAG(LuauCyclicRequireShortCircuit) LUAU_FASTFLAG(LuauEmitCallFeedback) -LUAU_FASTFLAG(LuauBytecodeCostModel) LUAU_FASTFLAG(LuauExportedTypesParticipateInScc) TEST_SUITE_BEGIN("RequireByStringTests"); @@ -1116,7 +1115,6 @@ TEST_CASE("RequireExportClass") {FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::DebugLuauUserDefinedClassesRuntime, true}, {FFlag::LuauEmitCallFeedback, true}, - {FFlag::LuauBytecodeCostModel, true} }; // we create a new fixture so the new lua_State has the class library @@ -1135,7 +1133,6 @@ TEST_CASE("RequireExportClassChildWithoutParent") {FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::DebugLuauUserDefinedClassesRuntime, true}, {FFlag::LuauEmitCallFeedback, true}, - {FFlag::LuauBytecodeCostModel, true} }; ReplWithPathFixture fixture; @@ -1153,7 +1150,6 @@ TEST_CASE("RequireExportClassBothExported") {FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::DebugLuauUserDefinedClassesRuntime, true}, {FFlag::LuauEmitCallFeedback, true}, - {FFlag::LuauBytecodeCostModel, true} }; ReplWithPathFixture fixture; @@ -1171,7 +1167,6 @@ TEST_CASE("RequireExportClassMultiLevel") {FFlag::DebugLuauUserDefinedClasses, true}, {FFlag::DebugLuauUserDefinedClassesRuntime, true}, {FFlag::LuauEmitCallFeedback, true}, - {FFlag::LuauBytecodeCostModel, true} }; ReplWithPathFixture fixture; diff --git a/tests/RuntimeLimits.test.cpp b/tests/RuntimeLimits.test.cpp index 26a6943e4..724154b16 100644 --- a/tests/RuntimeLimits.test.cpp +++ b/tests/RuntimeLimits.test.cpp @@ -488,8 +488,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "subtyping_should_cache_pairs_in_seen_set" * TEST_CASE_FIXTURE(BuiltinsFixture, "test_generic_pruning_recursion_limit") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, // Clip this test with LuauIterativeTypeSearcher diff --git a/tests/Simplify.test.cpp b/tests/Simplify.test.cpp index 799ff3a7e..63e8a857f 100644 --- a/tests/Simplify.test.cpp +++ b/tests/Simplify.test.cpp @@ -10,8 +10,6 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_DYNAMIC_FASTINT(LuauSimplificationComplexityLimit) -LUAU_FASTFLAG(DebugLuauParseExactTables) -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) namespace @@ -129,27 +127,6 @@ struct SimplifyFixture : Fixture } }; -// TODO: Delete this fixture class when clipping DebugLuauExactTableTypes and DebugLuauParseExactTables. -struct ExactTableSimplifyFixture : SimplifyFixture -{ - ScopedFastFlag sff1{FFlag::DebugLuauParseExactTables, true}; - ScopedFastFlag sff2{FFlag::DebugLuauExactTableTypes, true}; - - TypeId mkExactTable(std::map propTypes, std::optional indexer = std::nullopt) - { - TableType::Props props; - for (const auto& [name, prop] : propTypes) - props[name] = prop; - - return arena->addType(TableType{props, std::move(indexer), TypeLevel{}, TableState::Exact}); - } -}; - -struct LegacySimplifyFixture : SimplifyFixture -{ - ScopedFastFlag sff{FFlag::DebugLuauExactTableTypes, false}; -}; - } // namespace TEST_SUITE_BEGIN("Simplify"); @@ -408,7 +385,7 @@ TEST_CASE_FIXTURE(SimplifyFixture, "negated_function_does_not_intersect_cleanly_ CHECK(isIntersection(intersect(negatedFunctionTy, truthyTy))); } -TEST_CASE_FIXTURE(LegacySimplifyFixture, "tables") +TEST_CASE_FIXTURE(SimplifyFixture, "tables") { TypeId t1 = mkTable({{"tag", stringTy}}); @@ -426,7 +403,7 @@ TEST_CASE_FIXTURE(LegacySimplifyFixture, "tables") CHECK(t1 == intersect(t3, t1)); } -TEST_CASE_FIXTURE(LegacySimplifyFixture, "combine_disjoint_sealed_tables") +TEST_CASE_FIXTURE(SimplifyFixture, "combine_disjoint_sealed_tables") { TypeId t1 = mkTable({{"prop", stringTy}}); TypeId t2 = mkTable({{"second_prop", numberTy}}); @@ -434,33 +411,6 @@ TEST_CASE_FIXTURE(LegacySimplifyFixture, "combine_disjoint_sealed_tables") CHECK("{ prop: string, second_prop: number }" == toString(intersect(t1, t2))); } -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "combine_inexact_disjoint_sealed_tables") -{ - TypeId t1 = mkTable({{"prop", stringTy}}); - TypeId t2 = mkTable({{"second_prop", numberTy}}); - - CHECK("{ prop: string, second_prop: number, ... }" == toString(intersect(t1, t2))); -} - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "non_disjoint_tables_do_not_simplify") -{ - TypeId t1 = mkTable({{"prop", stringTy}}); - TypeId t2 = mkTable({{"prop", unknownTy}, {"second_prop", numberTy}}); - - CHECK("{ prop: string, ... } & { prop: unknown, second_prop: number, ... }" == toString(intersect(t1, t2))); -} - -// Simplification has an extra code path especially for intersections with -// single-property tables, so it's worthwhile to separately test the case where -// both tables have multiple properties. -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "non_disjoint_tables_do_not_simplify_2") -{ - TypeId t1 = mkTable({{"prop", stringTy}, {"third_prop", numberTy}}); - TypeId t2 = mkTable({{"prop", unknownTy}, {"second_prop", numberTy}}); - - CHECK("{ prop: string, third_prop: number, ... } & { prop: unknown, second_prop: number, ... }" == toString(intersect(t1, t2))); -} - TEST_CASE_FIXTURE(SimplifyFixture, "tables_and_top_table") { TypeId notTableType = mkNegation(tableTy); @@ -481,18 +431,7 @@ TEST_CASE_FIXTURE(SimplifyFixture, "tables_and_truthy") CHECK(t1 == intersect(truthyTy, t1)); } -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "table_with_a_tag") -{ - // {tag: string, prop: number} & {tag: "hello"} - // I think we can decline to simplify this: - TypeId t1 = mkTable({{"tag", stringTy}, {"prop", numberTy}}); - TypeId t2 = mkTable({{"tag", helloTy}}); - - CHECK("{ prop: number, tag: string, ... } & { tag: \"hello\", ... }" == intersectStr(t1, t2)); - CHECK("{ prop: number, tag: string, ... } & { tag: \"hello\", ... }" == intersectStr(t2, t1)); -} - -TEST_CASE_FIXTURE(LegacySimplifyFixture, "nested_table_tag_test") +TEST_CASE_FIXTURE(SimplifyFixture, "nested_table_tag_test") { TypeId t1 = mkTable({ {"subtable", @@ -718,32 +657,6 @@ TEST_CASE_FIXTURE(SimplifyFixture, "some_tables_are_really_never") CHECK(neverTy == intersect(t2, t2)); } -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "simplify_stops_at_cycles") -{ - TypeId t = mkTable({}); - TableType* tt = getMutable(t); - REQUIRE(tt); - - TypeId t2 = mkTable({}); - TableType* t2t = getMutable(t2); - REQUIRE(t2t); - - tt->props["cyclic"] = Property{t2}; - t2t->props["cyclic"] = Property{t}; - - CHECK(t == intersect(t, unknownTy)); - CHECK(t == intersect(unknownTy, t)); - - CHECK(t2 == intersect(t2, unknownTy)); - CHECK(t2 == intersect(unknownTy, t2)); - - CHECK("*error-type* | t1 where t1 = { cyclic: { cyclic: t1, ... }, ... }" == intersectStr(t, anyTy)); - CHECK("*error-type* | t1 where t1 = { cyclic: { cyclic: t1, ... }, ... }" == intersectStr(anyTy, t)); - - CHECK("*error-type* | t1 where t1 = { cyclic: { cyclic: t1, ... }, ... }" == intersectStr(t2, anyTy)); - CHECK("*error-type* | t1 where t1 = { cyclic: { cyclic: t1, ... }, ... }" == intersectStr(anyTy, t2)); -} - TEST_CASE_FIXTURE(SimplifyFixture, "free_type_bound_by_any_with_any") { CHECK("'a | *error-type*" == intersectStr(freeTy, anyTy)); @@ -788,7 +701,7 @@ TEST_CASE_FIXTURE(SimplifyFixture, "(error | string) & any") CHECK("*error-type* | string" == toString(res)); } -TEST_CASE_FIXTURE(LegacySimplifyFixture, "{ x: number, y: number } & { x: unknown }") +TEST_CASE_FIXTURE(SimplifyFixture, "{ x: number, y: number } & { x: unknown }") { TypeId leftTy = mkTable({{"x", builtinTypes->numberType}, {"y", builtinTypes->numberType}}); TypeId rightTy = mkTable({{"x", Property::rw(builtinTypes->unknownType)}}); @@ -804,95 +717,6 @@ TEST_CASE_FIXTURE(SimplifyFixture, "{ x: number, y: number } & { read x: unknown CHECK(leftTy == intersect(leftTy, rightTy)); } -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "{ read x: Child } & { x: Parent }") -{ - createSomeExternTypes(getFrontend()); - - TypeId parentTy = getFrontend().globals.globalScope->exportedTypeBindings["Parent"].type; - REQUIRE(parentTy); - - TypeId childTy = getFrontend().globals.globalScope->exportedTypeBindings["Child"].type; - REQUIRE(childTy); - - TypeId leftTy = mkTable({{"x", Property::readonly(childTy)}}); - TypeId rightTy = mkTable({{"x", parentTy}}); - - // TODO: This could be { read x: Child, write x: Parent } - CHECK("{ read x: Child, ... } & { x: Parent, ... }" == toString(intersect(leftTy, rightTy))); -} - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "intersect_parts_empty_table_non_empty") -{ - TableType empty; - empty.state = TableState::Sealed; - TypeId emptyTable = arena->addType(std::move(empty)); - - TableType nonEmpty; - nonEmpty.props["p"] = arena->addType(UnionType{{getBuiltins()->numberType, getBuiltins()->stringType}}); - nonEmpty.state = TableState::Sealed; - TypeId nonEmptyTable = arena->addType(std::move(nonEmpty)); - - CHECK("{ p: number | string, ... }" == toString(simplifyIntersection(getBuiltins(), arena, {nonEmptyTable, emptyTable}).result)); -} - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "relate_write_only_number_with_number") -{ - TypeId leftTy = mkTable({{"x", Property::writeonly(builtinTypes->numberType)}}); - TypeId rightTy = mkTable({{"x", Property::rw(arena->addType(UnionType{{builtinTypes->nilType, builtinTypes->numberType}}))}}); - - // This example could be simplified to: - // - // { write x: number, read x: number ? } - CHECK("{ write x: number, ... } & { x: number?, ... }" == toString(intersect(leftTy, rightTy))); - CHECK("{ write x: number, ... } & { x: number?, ... }" == toString(intersect(rightTy, leftTy))); - - // We could probably simplify this to... - // - // { x: number? } - // - // ... as... - // - // { write x: number } <: { x: number? } - CHECK("{ write x: number, ... } | { x: number?, ... }" == toString(union_(leftTy, rightTy))); - CHECK("{ write x: number, ... } | { x: number?, ... }" == toString(union_(rightTy, leftTy))); -} - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "relate_read_only_number_with_number") -{ - TypeId leftTy = mkTable({{"x", Property::readonly(builtinTypes->numberType)}}); - TypeId rightTy = mkTable({{"x", Property::rw(arena->addType(UnionType{{builtinTypes->nilType, builtinTypes->numberType}}))}}); - - // Both of these examples _could_ be simplified, but require - // minting a new table ... - - // This could be: { read x: number, write x: number? } - CHECK("{ read x: number, ... } & { x: number?, ... }" == toString(intersect(leftTy, rightTy))); - CHECK("{ read x: number, ... } & { x: number?, ... }" == toString(intersect(rightTy, leftTy))); - - // This could be: { read x: number? } - CHECK("{ read x: number, ... } | { x: number?, ... }" == toString(union_(leftTy, rightTy))); - CHECK("{ read x: number, ... } | { x: number?, ... }" == toString(union_(rightTy, leftTy))); -} - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "relate_coincident_minus_one_prop_tables") -{ - // { x: number, y: boolean } - TypeId leftTy = mkTable({{"x", Property::rw(builtinTypes->numberType)}, {"y", Property::rw(builtinTypes->booleanType)}}); - - // { x: number, y: boolean, z: string } - TypeId rightTy = mkTable( - {{"x", Property::rw(builtinTypes->numberType)}, {"y", Property::rw(builtinTypes->booleanType)}, {"z", Property::rw(builtinTypes->stringType)}} - ); - - // By width subtyping the wider table is the intersection. - CHECK("{ x: number, y: boolean, z: string, ... }" == toString(intersect(leftTy, rightTy))); - CHECK("{ x: number, y: boolean, z: string, ... }" == toString(intersect(rightTy, leftTy))); - - // By width subtyping the narrower table is the union. - CHECK("{ x: number, y: boolean, ... }" == toString(union_(leftTy, rightTy))); - CHECK("{ x: number, y: boolean, ... }" == toString(union_(rightTy, leftTy))); -} - TEST_CASE_FIXTURE(SimplifyFixture, "distinct_empty_inexact_tables_are_coincident") { TypeId left = mkTable({}); @@ -901,120 +725,4 @@ TEST_CASE_FIXTURE(SimplifyFixture, "distinct_empty_inexact_tables_are_coincident CHECK(Relation::Coincident == relate(left, right)); } -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "exact_table_relations") -{ - TypeId exactX = mkExactTable({{"x", numberTy}}); - TypeId equivalentExactX = mkExactTable({{"x", numberTy}}); - TypeId exactXY = mkExactTable({{"x", numberTy}, {"y", stringTy}}); - TypeId exactXString = mkExactTable({{"x", stringTy}}); - TypeId exactXYHello = mkExactTable({{"x", numberTy}, {"y", Property::readonly(helloTy)}}); - TypeId exactXYStringReadOnly = mkExactTable({{"x", numberTy}, {"y", Property::readonly(stringTy)}}); - - TypeId inexactX = mkTable({{"x", numberTy}}); - TypeId inexactXY = mkTable({{"x", numberTy}, {"y", stringTy}}); - - TypeId exactNumberIndexer = mkExactTable({}, TableIndexer{stringTy, numberTy}); - TypeId exactStringIndexer = mkExactTable({}, TableIndexer{stringTy, stringTy}); - TypeId inexactNumberIndexer = arena->addType(TableType{{}, TableIndexer{stringTy, numberTy}, TypeLevel{}, TableState::Sealed}); - - CHECK(Relation::Coincident == relate(exactX, equivalentExactX)); - CHECK(Relation::Subset == relate(exactX, inexactX)); - CHECK(Relation::Superset == relate(inexactX, exactX)); - - CHECK(Relation::Disjoint == relate(exactX, exactXY)); - CHECK(Relation::Disjoint == relate(exactX, inexactXY)); - CHECK(Relation::Disjoint == relate(exactX, exactXString)); - - CHECK(Relation::Subset == relate(exactXY, inexactX)); - CHECK(Relation::Superset == relate(inexactX, exactXY)); - CHECK(Relation::Subset == relate(exactXY, inexactXY)); - CHECK(Relation::Superset == relate(inexactXY, exactXY)); - - // Exactness controls the tail of the row; it does not make a directional - // relation between corresponding fields disappear. - CHECK(Relation::Subset == relate(exactXYHello, exactXYStringReadOnly)); - CHECK(Relation::Superset == relate(exactXYStringReadOnly, exactXYHello)); - - // This is conservative: incompatible index result types need not be - // classified as disjoint, but they must never be coincident. - CHECK(Relation::Intersects == relate(exactNumberIndexer, exactStringIndexer)); - CHECK(Relation::Subset == relate(exactNumberIndexer, inexactNumberIndexer)); - CHECK(Relation::Superset == relate(inexactNumberIndexer, exactNumberIndexer)); -} - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "exact_table_simplification") -{ - TypeId exactX = mkExactTable({{"x", numberTy}}); - TypeId exactXY = mkExactTable({{"x", numberTy}, {"y", stringTy}}); - TypeId inexactX = mkTable({{"x", numberTy}}); - TypeId inexactXY = mkTable({{"x", numberTy}, {"y", stringTy}}); - - CHECK(exactX == intersect(exactX, inexactX)); - CHECK(exactX == intersect(inexactX, exactX)); - CHECK(inexactX == union_(exactX, inexactX)); - CHECK(inexactX == union_(inexactX, exactX)); - - CHECK(neverTy == intersect(exactX, exactXY)); - CHECK(neverTy == intersect(exactX, inexactXY)); - CHECK("{ x: number } | { x: number, y: string }" == toString(union_(exactX, exactXY))); - CHECK("{ x: number } | { x: number, y: string }" == toString(union_(exactXY, exactX))); -} - -// Single-property sealed tables exercise a dedicated fast path in basicIntersect. - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "single_prop_disjoint_props_yield_never") -{ - TypeId t1 = mkTable({{"x", numberTy}}); - TypeId t2 = mkTable({{"x", stringTy}}); - - CHECK(neverTy == intersect(t1, t2)); - CHECK(neverTy == intersect(t2, t1)); -} - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "single_prop_coincident_returns_right") -{ - TypeId t1 = mkTable({{"x", numberTy}}); - TypeId t2 = mkTable({{"x", numberTy}, {"y", stringTy}}); - - CHECK(t2 == intersect(t1, t2)); -} - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "single_prop_superset_returns_right") -{ - TypeId t1 = mkTable({{"x", stringTy}}); - TypeId t2 = mkTable({{"x", helloTy}}); - - CHECK(t2 == intersect(t1, t2)); -} - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "single_prop_subset_returns_left") -{ - TypeId t1 = mkTable({{"x", stringTy}}); - TypeId t2 = mkTable({{"x", unknownTy}}); - - CHECK(t1 == intersect(t1, t2)); -} - -// Multi-property left with single-property right should swap and retry the fast path. - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "multi_prop_with_single_prop_swaps") -{ - TypeId t1 = mkTable({{"x", numberTy}, {"y", stringTy}}); - TypeId t2 = mkTable({{"x", numberTy}}); - - CHECK(t1 == intersect(t1, t2)); -} - -// Exact tables must never be merged by the disjoint-sealed fast path, even when the -// other operand is an inexact sealed table. They should fall through to relate(). - -TEST_CASE_FIXTURE(ExactTableSimplifyFixture, "exact_and_inexact_disjoint_do_not_merge") -{ - TypeId exactX = mkExactTable({{"x", numberTy}}); - TypeId inexactY = mkTable({{"y", stringTy}}); - - CHECK(neverTy == intersect(exactX, inexactY)); - CHECK(neverTy == intersect(inexactY, exactX)); -} - TEST_SUITE_END(); diff --git a/tests/Subtyping.test.cpp b/tests/Subtyping.test.cpp index 9293c6066..8dc7a3024 100644 --- a/tests/Subtyping.test.cpp +++ b/tests/Subtyping.test.cpp @@ -21,8 +21,6 @@ LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(LuauImproveUniqueTableWidthSubtyping) LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) -LUAU_FASTFLAG(DebugLuauParseExactTables) -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAG(LuauSubtypingSkipUnreadReasoning) LUAU_FASTFLAG(LuauOneBitAssumedConstraintTracking) @@ -126,11 +124,6 @@ struct SubtypeFixture : Fixture return arena.addType(TableType{std::move(props), std::nullopt, {}, TableState::Sealed}); } - TypeId tbl_exact(TableType::Props&& props) - { - return arena.addType(TableType{std::move(props), std::nullopt, TypeLevel{}, TableState::Exact}); - } - TypeId idx(TypeId keyTy, TypeId valueTy, bool isReadOnly = false) { return arena.addType(TableType{{}, TableIndexer{keyTy, valueTy, isReadOnly}, {}, TableState::Sealed}); @@ -919,334 +912,6 @@ TEST_CASE_FIXTURE(SubtypeFixture, "{ @metatable { x: number } } numberType}}), tbl({{"x", getBuiltins()->numberType}})); } -// TODO: Delete this fixture class when clipping DebugLuauExactTableTypes and DebugLuauParseExactTables. -struct ExactTableTypeFixture : SubtypeFixture -{ - ScopedFastFlag sff1{FFlag::DebugLuauParseExactTables, true}; - ScopedFastFlag sff2{FFlag::DebugLuauExactTableTypes, true}; -}; - -// These could be rewritten to use TEST_IS_SUBTYPE and TEST_IS_NOT_SUBTYPE once the flags are clipped. -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{} <: { ... }") -{ - CHECK_IS_SUBTYPE(tbl_exact({}), tbl({})); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{ ... } numberType}}), tbl({{"x", getBuiltins()->numberType}})); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number} <: {x: number}") -{ - CHECK_IS_SUBTYPE(tbl_exact({{"x", getBuiltins()->numberType}}), tbl_exact({{"x", getBuiltins()->numberType}})); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number} <: {read x: number?}") -{ - CHECK_IS_SUBTYPE(tbl_exact({{"x", getBuiltins()->numberType}}), tbl_exact({{"x", Property::readonly(getBuiltins()->optionalNumberType)}})); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{number, ...} numberType, getBuiltins()->numberType); - getMutable(left)->state = TableState::Sealed; - - TypeId right = idx(getBuiltins()->numberType, getBuiltins()->numberType); - getMutable(right)->state = TableState::Exact; - - CHECK_IS_NOT_SUBTYPE(left, right); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{number} <: {number, ...}") -{ - TypeId left = idx(getBuiltins()->numberType, getBuiltins()->numberType); - getMutable(left)->state = TableState::Exact; - - TypeId right = idx(getBuiltins()->numberType, getBuiltins()->numberType); - getMutable(right)->state = TableState::Sealed; - - CHECK_IS_SUBTYPE(left, right); -} - -// Extra properties — the reverse property-set check (the core of "no width subtyping") - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, y: string, ...} numberType}, {"y", getBuiltins()->stringType}}), tbl_exact({{"x", getBuiltins()->numberType}})); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, y: string} numberType}, {"y", getBuiltins()->stringType}}), tbl_exact({{"x", getBuiltins()->numberType}}) - ); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, y: string} <: {x: number, ...}") -{ - CHECK_IS_SUBTYPE(tbl_exact({{"x", getBuiltins()->numberType}, {"y", getBuiltins()->stringType}}), tbl({{"x", getBuiltins()->numberType}})); -} - -// Missing properties — exact super demands full match - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number} numberType}}), tbl_exact({{"x", getBuiltins()->numberType}, {"y", getBuiltins()->stringType}}) - ); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, ...} numberType}}), tbl_exact({{"x", getBuiltins()->numberType}, {"y", getBuiltins()->stringType}})); -} - -// Property type mismatch - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number} numberType}}), tbl_exact({{"x", getBuiltins()->stringType}})); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number} numberType}}), tbl({{"x", getBuiltins()->stringType}})); -} - -// Indexer + props combined - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, [string]: number} <: {x: number, [string]: number, ...}") -{ - TypeId left = arena.addType( - TableType{ - {{"x", getBuiltins()->numberType}}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Exact - } - ); - TypeId right = arena.addType( - TableType{ - {{"x", getBuiltins()->numberType}}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Sealed - } - ); - - CHECK_IS_SUBTYPE(left, right); -} - -// Exact tables retain ordinary width subtyping when the supertype is inexact, -// including when the extra part of the subtype is an indexer. -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, [string]: number} <: {x: number, ...}") -{ - TypeId left = arena.addType( - TableType{ - {{"x", getBuiltins()->numberType}}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Exact - } - ); - - CHECK_IS_SUBTYPE(left, tbl({{"x", getBuiltins()->numberType}})); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, [string]: number} numberType}}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Exact - } - ); - TypeId right = tbl_exact({{"x", getBuiltins()->numberType}}); - - CHECK_IS_NOT_SUBTYPE(left, right); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number} numberType}}); - TypeId right = arena.addType( - TableType{ - {{"x", getBuiltins()->numberType}}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Exact - } - ); - - CHECK_IS_NOT_SUBTYPE(left, right); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, [string]: number, ...} numberType}}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Sealed - } - ); - TypeId right = arena.addType( - TableType{ - {{"x", getBuiltins()->numberType}}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Exact - } - ); - - CHECK_IS_NOT_SUBTYPE(left, right); -} - -// Exercises the reverse property-set check when the super has an indexer. -// Sub has a prop `y` that the super doesn't have; the super has a [string] indexer. -// This reaches the code path that checks whether the sub's extra prop can be -// satisfied by the super's indexer. -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, y: string} numberType}, {"y", getBuiltins()->stringType}}, std::nullopt, TypeLevel{}, TableState::Exact}); - TypeId sup = arena.addType( - TableType{ - {{"x", getBuiltins()->numberType}}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Exact - } - ); - - CHECK_IS_NOT_SUBTYPE(sub, sup); -} - -// An extra write-only property cannot satisfy a read-write indexer. In -// particular, this must not dereference the absent read type. -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{write y: number} numberType)}}); - TypeId sup = arena.addType(TableType{{}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Exact}); - - CHECK_IS_NOT_SUBTYPE(sub, sup); -} - -// Sub has an extra prop `y` not in the super's named props. Super has a -// [number] indexer, so string keys can't be satisfied by it. Both sides have -// indexers, so the indexer-presence check doesn't catch it. The reverse check -// should reject the extra prop. -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number, y: string, [number]: number} numberType}, {"y", getBuiltins()->stringType}}, - TableIndexer{getBuiltins()->numberType, getBuiltins()->numberType}, - TypeLevel{}, - TableState::Exact - } - ); - TypeId sup = arena.addType( - TableType{ - {{"x", getBuiltins()->numberType}}, TableIndexer{getBuiltins()->numberType, getBuiltins()->numberType}, TypeLevel{}, TableState::Exact - } - ); - - CHECK_IS_NOT_SUBTYPE(sub, sup); -} - -// Exact sub without an indexer vs sealed super with one. -// The super is inexact so width subtyping applies, but the sub is exact and -// cannot gain an indexer. This should not be a subtype. -// Exposes Subtyping.cpp:2170 (state != Sealed treats Exact like Unsealed). -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number} numberType}}); - TypeId sup = arena.addType( - TableType{ - {{"x", getBuiltins()->numberType}}, TableIndexer{getBuiltins()->stringType, getBuiltins()->numberType}, TypeLevel{}, TableState::Sealed - } - ); - - CHECK_IS_NOT_SUBTYPE(sub, sup); -} - -// The `table` primitive - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{} <: table") -{ - CHECK_IS_SUBTYPE(tbl_exact({}), getBuiltins()->tableType); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "table tableType, tbl_exact({})); -} - -// Metatables wrapping exact tables - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{x: number} ") -{ - TypeId exactTable = tbl_exact({{"x", getBuiltins()->numberType}}); - TypeId metatable = arena.addType(MetatableType{exactTable, tbl({})}); - - CHECK_IS_NOT_SUBTYPE(exactTable, metatable); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "setmetatable<{x: number}, {}> numberType}}); - TypeId metatable = arena.addType(MetatableType{exactTable, tbl({})}); - - CHECK_IS_NOT_SUBTYPE(metatable, tbl_exact({{"x", getBuiltins()->numberType}, {"y", getBuiltins()->stringType}})); -} - -// Metatables with equal exact metatables: subtyping is decided by the table part. -// setmetatable <: setmetatable iff A <: B when T is an exact table. - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "setmetatable<{x: number}, {}> <: setmetatable<{x: number, ...}, {}>") -{ - TypeId mt = tbl_exact({}); - TypeId subMt = arena.addType(MetatableType{tbl_exact({{"x", getBuiltins()->numberType}}), mt}); - TypeId superMt = arena.addType(MetatableType{tbl({{"x", getBuiltins()->numberType}}), mt}); - - CHECK_IS_SUBTYPE(subMt, superMt); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "setmetatable<{x: number}, {}> ") -{ - TypeId mt = tbl_exact({}); - TypeId subMt = arena.addType(MetatableType{tbl_exact({{"x", getBuiltins()->numberType}}), mt}); - TypeId superMt = arena.addType(MetatableType{tbl_exact({{"x", getBuiltins()->numberType}, {"y", getBuiltins()->stringType}}), mt}); - - CHECK_IS_NOT_SUBTYPE(subMt, superMt); -} - -// Negation - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{} <: ~number") -{ - CHECK_IS_SUBTYPE(tbl_exact({}), negate(getBuiltins()->numberType)); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "{} tableType)); -} - -// Cyclic exact tables - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "cyclic_exact_table_subtypes_itself") -{ - TypeId a = arena.addType(BlockedType{}); - TypeId aTable = arena.addType(TableType{{{"self", a}}, std::nullopt, TypeLevel{}, TableState::Exact}); - asMutable(a)->ty.emplace(aTable); - - TypeId b = arena.addType(BlockedType{}); - TypeId bTable = arena.addType(TableType{{{"self", b}}, std::nullopt, TypeLevel{}, TableState::Exact}); - asMutable(b)->ty.emplace(bTable); - - CHECK_IS_SUBTYPE(aTable, bTable); -} - -TEST_CASE_FIXTURE(ExactTableTypeFixture, "cyclic_exact_table_not_subtype_with_extra_prop") -{ - TypeId a = arena.addType(BlockedType{}); - TypeId aTable = arena.addType(TableType{{{"self", a}, {"extra", getBuiltins()->numberType}}, std::nullopt, TypeLevel{}, TableState::Exact}); - asMutable(a)->ty.emplace(aTable); - - TypeId b = arena.addType(BlockedType{}); - TypeId bTable = arena.addType(TableType{{{"self", b}}, std::nullopt, TypeLevel{}, TableState::Exact}); - asMutable(b)->ty.emplace(bTable); - - CHECK_IS_NOT_SUBTYPE(aTable, bTable); -} - TEST_IS_SUBTYPE(getBuiltins()->tableType, tbl({})); TEST_IS_SUBTYPE(tbl({}), getBuiltins()->tableType); diff --git a/tests/ToString.test.cpp b/tests/ToString.test.cpp index 779026ae4..11f02089d 100644 --- a/tests/ToString.test.cpp +++ b/tests/ToString.test.cpp @@ -14,8 +14,6 @@ using namespace Luau; LUAU_FASTINT(LuauTypeMaximumStringifierLength) LUAU_FASTFLAG(DebugLuauForceOldSolver) -LUAU_FASTFLAG(DebugLuauParseExactTables) -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAG(LuauExportValueSyntax) TEST_SUITE_BEGIN("ToString"); @@ -91,8 +89,6 @@ TEST_CASE_FIXTURE(Fixture, "named_table") TEST_CASE_FIXTURE(Fixture, "empty_table") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local a: {} )"); @@ -148,8 +144,6 @@ TEST_CASE_FIXTURE(Fixture, "long_disjunct_of_nil_is_nil_not_question_mark") TEST_CASE_FIXTURE(Fixture, "metatable") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - Type table{TypeVariant(TableType())}; Type metatable{TypeVariant(TableType())}; Type mtv{TypeVariant(MetatableType{&table, &metatable})}; @@ -158,8 +152,6 @@ TEST_CASE_FIXTURE(Fixture, "metatable") TEST_CASE_FIXTURE(Fixture, "metatables_are_valid") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::LuauBetterMetatableStringification, true}; Type table{TypeVariant(TableType(TableState::Sealed, TypeLevel{}))}; @@ -451,8 +443,6 @@ TEST_CASE_FIXTURE(Fixture, "stringifying_type_is_still_capped_when_exhaustive") TEST_CASE_FIXTURE(Fixture, "stringifying_table_type_correctly_use_matching_table_state_braces") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - TableType ttv{TableState::Sealed, TypeLevel{}}; for (char c : std::string("abcdefghij")) ttv.props[std::string(1, c)] = {getBuiltins()->numberType}; @@ -486,8 +476,6 @@ TEST_CASE_FIXTURE(Fixture, "stringifying_cyclic_intersection_type_bails_early") TEST_CASE_FIXTURE(Fixture, "stringifying_array_uses_array_syntax") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - TableType ttv{TableState::Sealed, TypeLevel{}}; ttv.indexer = TableIndexer{getBuiltins()->numberType, getBuiltins()->stringType}; @@ -635,8 +623,6 @@ function foo(a, b) return a(b) end TEST_CASE_FIXTURE(Fixture, "toString_the_boundTo_table_type_contained_within_a_TypePack") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - Type tv1{TableType{}}; TableType* ttv = getMutable(&tv1); ttv->state = TableState::Sealed; @@ -720,8 +706,6 @@ TEST_CASE_FIXTURE(Fixture, "toStringNamedFunction_id") TEST_CASE_FIXTURE(Fixture, "toStringNamedFunction_map") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local function map(arr, fn) local t = {} @@ -948,8 +932,6 @@ TEST_CASE_FIXTURE(Fixture, "read_only_properties") TEST_CASE_FIXTURE(Fixture, "cycle_rooted_in_a_pack") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - TypeArena arena; TypePackId thePack = arena.addTypePack({getBuiltins()->numberType, getBuiltins()->numberType}); @@ -1102,38 +1084,15 @@ TEST_CASE_FIXTURE(Fixture, "record_type_compositions_generic") TEST_CASE_FIXTURE(Fixture, "empty_tables") { - TypeId emptyExact = arena.addType(TableType{TableState::Exact, TypeLevel{}}); - TypeId emptyInexact = arena.addType(TableType{TableState::Sealed, TypeLevel{}}); + TypeId emptySealed = arena.addType(TableType{TableState::Sealed, TypeLevel{}}); TypeId emptyUnsealed = arena.addType(TableType{TableState::Unsealed, TypeLevel{}}); TypeId emptyFree = arena.addType(TableType{TableState::Free, TypeLevel{}}); TypeId emptyGeneric = arena.addType(TableType{TableState::Generic, TypeLevel{}}); - SUBCASE("flags_off") - { - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, false}, - {FFlag::DebugLuauExactTableTypes, false}, - }; - - CHECK("{ }" == toString(emptyInexact)); - CHECK("{ }" == toString(emptyExact)); - CHECK("{| |}" == toString(emptyUnsealed)); - CHECK("{- -}" == toString(emptyFree)); - CHECK("{+ +}" == toString(emptyGeneric)); - } - - SUBCASE("flags_on") - { - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; - CHECK("{ ... }" == toString(emptyInexact)); - CHECK("{ }" == toString(emptyExact)); - CHECK("{| |}" == toString(emptyUnsealed)); - CHECK("{- -}" == toString(emptyFree)); - CHECK("{+ +}" == toString(emptyGeneric)); - } + CHECK("{ }" == toString(emptySealed)); + CHECK("{| |}" == toString(emptyUnsealed)); + CHECK("{- -}" == toString(emptyFree)); + CHECK("{+ +}" == toString(emptyGeneric)); } TEST_CASE_FIXTURE(Fixture, "tables_with_indexers_and_props") @@ -1144,161 +1103,30 @@ TEST_CASE_FIXTURE(Fixture, "tables_with_indexers_and_props") TableIndexer readOnlyStringIndexer{getBuiltins()->stringType, getBuiltins()->numberType, true}; TypeId sealedStrIdx = arena.addType(TableType{{}, stringIndexer, TypeLevel{}, TableState::Sealed}); - TypeId exactStrIdx = arena.addType(TableType{{}, stringIndexer, TypeLevel{}, TableState::Exact}); TypeId sealedProps = arena.addType(TableType{xProp, std::nullopt, TypeLevel{}, TableState::Sealed}); - TypeId exactProps = arena.addType(TableType{xProp, std::nullopt, TypeLevel{}, TableState::Exact}); TypeId sealedBoth = arena.addType(TableType{xProp, stringIndexer, TypeLevel{}, TableState::Sealed}); - TypeId exactBoth = arena.addType(TableType{xProp, stringIndexer, TypeLevel{}, TableState::Exact}); TypeId unsealedBoth = arena.addType(TableType{xProp, stringIndexer, TypeLevel{}, TableState::Unsealed}); TypeId sealedNumIdxProps = arena.addType(TableType{xProp, numberIndexer, TypeLevel{}, TableState::Sealed}); - TypeId exactNumIdxProps = arena.addType(TableType{xProp, numberIndexer, TypeLevel{}, TableState::Exact}); TypeId sealedNumIdx = arena.addType(TableType{{}, numberIndexer, TypeLevel{}, TableState::Sealed}); - TypeId exactNumIdx = arena.addType(TableType{{}, numberIndexer, TypeLevel{}, TableState::Exact}); TypeId sealedReadOnlyStrIdx = arena.addType(TableType{{}, readOnlyStringIndexer, TypeLevel{}, TableState::Sealed}); - TypeId exactReadOnlyStrIdx = arena.addType(TableType{{}, readOnlyStringIndexer, TypeLevel{}, TableState::Exact}); - - SUBCASE("flags_off") - { - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, false}, - {FFlag::DebugLuauExactTableTypes, false}, - }; - CHECK("{ [string]: number }" == toString(sealedStrIdx)); - CHECK("{ [string]: number }" == toString(exactStrIdx)); + CHECK("{ [string]: number }" == toString(sealedStrIdx)); - CHECK("{ x: number }" == toString(sealedProps)); - CHECK("{ x: number }" == toString(exactProps)); + CHECK("{ x: number }" == toString(sealedProps)); - CHECK("{ [string]: number, x: number }" == toString(sealedBoth)); - CHECK("{ [string]: number, x: number }" == toString(exactBoth)); - CHECK("{| [string]: number, x: number |}" == toString(unsealedBoth)); + CHECK("{ [string]: number, x: number }" == toString(sealedBoth)); + CHECK("{| [string]: number, x: number |}" == toString(unsealedBoth)); - CHECK("{ [number]: string, x: number }" == toString(sealedNumIdxProps)); - CHECK("{ [number]: string, x: number }" == toString(exactNumIdxProps)); - - CHECK("{string}" == toString(sealedNumIdx)); - CHECK("{string}" == toString(exactNumIdx)); - - CHECK("{ read [string]: number }" == toString(sealedReadOnlyStrIdx)); - CHECK("{ read [string]: number }" == toString(exactReadOnlyStrIdx)); - } - - SUBCASE("flags_on") - { - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; - - CHECK("{ [string]: number, ... }" == toString(sealedStrIdx)); - CHECK("{ [string]: number }" == toString(exactStrIdx)); - - CHECK("{ x: number, ... }" == toString(sealedProps)); - CHECK("{ x: number }" == toString(exactProps)); - - CHECK("{ [string]: number, x: number, ... }" == toString(sealedBoth)); - CHECK("{ [string]: number, x: number }" == toString(exactBoth)); - CHECK("{| [string]: number, x: number |}" == toString(unsealedBoth)); - - CHECK("{ [number]: string, x: number, ... }" == toString(sealedNumIdxProps)); - CHECK("{ [number]: string, x: number }" == toString(exactNumIdxProps)); - - CHECK("{string, ...}" == toString(sealedNumIdx)); - CHECK("{string}" == toString(exactNumIdx)); - - CHECK("{ read [string]: number, ... }" == toString(sealedReadOnlyStrIdx)); - CHECK("{ read [string]: number }" == toString(exactReadOnlyStrIdx)); - } - - SUBCASE("flags_on_multiline") - { - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; + CHECK("{ [number]: string, x: number }" == toString(sealedNumIdxProps)); - ToStringOptions opts; - opts.useLineBreaks = true; + CHECK("{string}" == toString(sealedNumIdx)); - CHECK( - "{\n" - " [string]: number,\n" - " ...\n" - "}" == toString(sealedStrIdx, opts) - ); - CHECK( - "{\n" - " [string]: number\n" - "}" == toString(exactStrIdx, opts) - ); - - CHECK( - "{\n" - " x: number,\n" - " ...\n" - "}" == toString(sealedProps, opts) - ); - CHECK( - "{\n" - " x: number\n" - "}" == toString(exactProps, opts) - ); - - CHECK( - "{\n" - " [string]: number,\n" - " x: number,\n" - " ...\n" - "}" == toString(sealedBoth, opts) - ); - CHECK( - "{\n" - " [string]: number,\n" - " x: number\n" - "}" == toString(exactBoth, opts) - ); - CHECK( - "{|\n" - " [string]: number,\n" - " x: number\n" - "|}" == toString(unsealedBoth, opts) - ); - - CHECK( - "{\n" - " [number]: string,\n" - " x: number,\n" - " ...\n" - "}" == toString(sealedNumIdxProps, opts) - ); - CHECK( - "{\n" - " [number]: string,\n" - " x: number\n" - "}" == toString(exactNumIdxProps, opts) - ); - - CHECK("{string, ...}" == toString(sealedNumIdx, opts)); - CHECK("{string}" == toString(exactNumIdx, opts)); - - CHECK( - "{\n" - " read [string]: number,\n" - " ...\n" - "}" == toString(sealedReadOnlyStrIdx, opts) - ); - CHECK( - "{\n" - " read [string]: number\n" - "}" == toString(exactReadOnlyStrIdx, opts) - ); - } + CHECK("{ read [string]: number }" == toString(sealedReadOnlyStrIdx)); } TEST_SUITE_END(); diff --git a/tests/TypeFunction.test.cpp b/tests/TypeFunction.test.cpp index 944e91d34..6c3f7a7d0 100644 --- a/tests/TypeFunction.test.cpp +++ b/tests/TypeFunction.test.cpp @@ -1064,8 +1064,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cyclic_metatable_should_not_crash_index") TEST_CASE_FIXTURE(BuiltinsFixture, "index_type_function_works_w_generic_types") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -1420,8 +1418,6 @@ TEST_CASE_FIXTURE(Fixture, "fuzz_len_type_function_follow") TEST_CASE_FIXTURE(BuiltinsFixture, "setmetatable_type_function_assigns_correct_metatable") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -1440,8 +1436,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "setmetatable_type_function_assigns_correct_m TEST_CASE_FIXTURE(BuiltinsFixture, "setmetatable_type_function_assigns_correct_metatable_2") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -1466,8 +1460,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "setmetatable_type_function_assigns_correct_m TEST_CASE_FIXTURE(BuiltinsFixture, "setmetatable_type_function_errors_on_metatable_with_metatable_metamethod") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -1964,8 +1956,6 @@ TEST_CASE_FIXTURE(Fixture, "recursive_restraint_violation_with_defaults") TEST_CASE_FIXTURE(Fixture, "cli_184124_recursive_restraint_violation_from_devforum") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - LUAU_REQUIRE_NO_ERRORS(check(R"( type TypeA = { Func: (self: TypeA, func: (A...) -> ()) -> () } type TypeB = { Value: TypeA> } diff --git a/tests/TypeFunction.user.test.cpp b/tests/TypeFunction.user.test.cpp index a0b4d5ea5..b92e7b3f8 100644 --- a/tests/TypeFunction.user.test.cpp +++ b/tests/TypeFunction.user.test.cpp @@ -11,7 +11,6 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauForceOldSolver) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_DYNAMIC_FASTINT(LuauTypeFunctionSerdeIterationLimit) LUAU_FASTFLAG(LuauTypeFunctionsReturnAfterAllSerialized) LUAU_FASTFLAG(LuauUdtfTerseChunkNames) @@ -549,8 +548,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_flatten_on_intersectionof_two_things") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_intersection_serialization_works") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -570,8 +567,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_intersection_serialization_works") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_intersection_methods_work") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -735,8 +730,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "udtf_two_negations_type_mismatch") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_table_serialization_works") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -756,8 +749,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_table_serialization_works") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_newtable_can_do_readonly_or_writeonly_types") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -778,8 +769,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_newtable_can_do_readonly_or_writeonly_t TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_table_methods_work") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -818,8 +807,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_table_methods_work") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_metatable_methods_work") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -928,8 +915,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "udtf_class_serialization_works2") TEST_CASE_FIXTURE(ExternTypeFixture, "udtf_class_methods_works") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -977,8 +962,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "write_of_readonly_is_nil") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_check_mutability") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -1010,8 +993,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_check_mutability") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_copy_works") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -1044,8 +1025,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_copy_works") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_simple_cyclic_serialization_works") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -1087,8 +1066,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_createtable_bad_metatable") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_complex_cyclic_serialization_works") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -1315,8 +1292,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_math_reset") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_optionify") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -1430,8 +1405,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_follow") TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_strip_indexer") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -1546,8 +1519,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "tag_field") TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_serialization") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -1871,8 +1842,6 @@ local function ok(idx: pass): test return idx end TEST_CASE_FIXTURE(ExternTypeFixture, "udtf_generic_serialization_3") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -2480,8 +2449,6 @@ local y: keyof TEST_CASE_FIXTURE(BuiltinsFixture, "blocking_nested_pending_expansions_2") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -2499,8 +2466,6 @@ local x: foo<{a: foo, b: foo}> = nil TEST_CASE_FIXTURE(BuiltinsFixture, "irreducible_pending_expansions") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -2537,8 +2502,6 @@ TEST_CASE_FIXTURE(Fixture, "typeof_is_not_a_valid_type_function_name") TEST_CASE_FIXTURE(BuiltinsFixture, "type_alias_call") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -2560,8 +2523,6 @@ local y: foo<{b: number}> = { b = 2 } TEST_CASE_FIXTURE(BuiltinsFixture, "type_alias_call_indirect") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -2587,8 +2548,6 @@ local y: bar<{b: number}> = { b = 2 } TEST_CASE_FIXTURE(BuiltinsFixture, "type_alias_call_indirect_levels") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -2618,8 +2577,6 @@ end TEST_CASE_FIXTURE(BuiltinsFixture, "type_alias_values") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -2641,8 +2598,6 @@ local y: foo = "a" TEST_CASE_FIXTURE(BuiltinsFixture, "type_alias_unordered") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -3346,77 +3301,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_setmetatable_wrong_error_tag") ); } -TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_cloner_missing_integer_crashes_copy") -{ - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; - ScopedFastFlag integerType{FFlag::LuauIntegerType2, true}; - - CheckResult result = check(R"( - type function copy_int(arg) - local c = types.copy(arg) - return c - end - - local function ok(idx: copy_int): integer return idx end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); -} - -TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_integer_methods_work") -{ - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; - ScopedFastFlag integerType{FFlag::LuauIntegerType2, true}; - - CheckResult result = check(R"( - type function getinteger() - local ty = types.integer - if ty:is("integer") then - return ty - end - -- this should never be returned - return types.string - end - local function ok(idx: getinteger<>): integer return idx end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); -} - -TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_integer_is_distinct_from_number") -{ - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; - ScopedFastFlag integerType{FFlag::LuauIntegerType2, true}; - - CheckResult result = check(R"( - type function pick(arg) - if arg:is("integer") then - return types.integer - end - return types.number - end - local function ok(idx: pick): integer return idx end - local function ok2(idx: pick): number return idx end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); -} - -TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_integer_constructor_is_not_number") -{ - ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; - ScopedFastFlag integerType{FFlag::LuauIntegerType2, true}; - - CheckResult result = check(R"( - type function getinteger() - return types.integer - end - local function bad(idx: getinteger<>): number return idx end - )"); - - LUAU_REQUIRE_ERROR_COUNT(1, result); -} - TEST_CASE_FIXTURE(BuiltinsFixture, "udtf_setgenerics_wrong_argcount_check") { ScopedFastFlag newSolver{FFlag::DebugLuauForceOldSolver, false}; @@ -3708,8 +3592,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "types_singleton_error_message") TEST_CASE_FIXTURE(BuiltinsFixture, "type_tostring") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag terseChunkNames{FFlag::LuauUdtfTerseChunkNames, true}; diff --git a/tests/TypeInfer.aliases.test.cpp b/tests/TypeInfer.aliases.test.cpp index a4e5daa3c..b3723357e 100644 --- a/tests/TypeInfer.aliases.test.cpp +++ b/tests/TypeInfer.aliases.test.cpp @@ -769,8 +769,6 @@ TEST_CASE_FIXTURE(Fixture, "non_recursive_aliases_that_reuse_a_generic_name") */ TEST_CASE_FIXTURE(BuiltinsFixture, "do_not_quantify_unresolved_aliases") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( --!strict diff --git a/tests/TypeInfer.builtins.test.cpp b/tests/TypeInfer.builtins.test.cpp index 509d2e410..fe678fd6e 100644 --- a/tests/TypeInfer.builtins.test.cpp +++ b/tests/TypeInfer.builtins.test.cpp @@ -12,6 +12,7 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauForceOldSolver) LUAU_FASTFLAG(LuauRemoveLoadstringFromBuiltinDefinitions) +LUAU_FASTFLAG(DebugLuauBufferVectorLibrary) TEST_SUITE_BEGIN("BuiltinTests"); @@ -73,8 +74,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "next_iterator_should_infer_types_and_type_ch TEST_CASE_FIXTURE(BuiltinsFixture, "pairs_iterator_should_infer_types_and_type_check") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( type Map = { [K]: V } local map: Map = { ["foo"] = 1, ["bar"] = 2, ["baz"] = 3 } @@ -200,8 +199,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "math_max_checks_for_numbers") TEST_CASE_FIXTURE(BuiltinsFixture, "builtin_tables_sealed") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"LUA( local b = bit32 )LUA"); @@ -381,8 +378,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "setmetatable_unpacks_arg_types_correctly") TEST_CASE_FIXTURE(BuiltinsFixture, "setmetatable_on_union_of_tables") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( type A = {tag: "A", x: number} type B = {tag: "B", y: string} @@ -427,8 +422,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_insert_correctly_infers_type_of_array_ TEST_CASE_FIXTURE(BuiltinsFixture, "table_pack") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local t = table.pack(1, "foo", true) )"); @@ -439,8 +432,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_pack") TEST_CASE_FIXTURE(BuiltinsFixture, "table_pack_variadic") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( --!strict function f(): (string, ...number) @@ -456,8 +447,6 @@ local t = table.pack(f()) TEST_CASE_FIXTURE(BuiltinsFixture, "table_pack_reduce_1") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local t = table.pack(1, 2, true) )"); @@ -468,8 +457,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_pack_reduce_1") TEST_CASE_FIXTURE(BuiltinsFixture, "table_pack_reduce_2") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local t = table.pack("a", "b", "c") )"); @@ -543,6 +530,23 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "buffer_is_a_type") CHECK("buffer" == toString(requireType("b"))); } +TEST_CASE_FIXTURE(BuiltinsFixture, "buffer_vector_functions_have_vector_types") +{ + ScopedFastFlag bufferVectorLibrary{FFlag::DebugLuauBufferVectorLibrary, true}; + + CheckResult result = check(R"( + local b = buffer.create(24) + local v2 = buffer.readvectorf32x2(b, 0) + local v3 = buffer.readvectorf32x3(b, 0) + buffer.writevectorf32x2(b, 0, vector.create(1, 2)) + buffer.writevectorf32x3(b, 0, vector.create(1, 2, 3)) + )"); + + LUAU_REQUIRE_NO_ERRORS(result); + CHECK("vector" == toString(requireType("v2"))); + CHECK("vector" == toString(requireType("v3"))); +} + TEST_CASE_FIXTURE(BuiltinsFixture, "coroutine_resume_anything_goes") { CheckResult result = check(R"( diff --git a/tests/TypeInfer.classes.test.cpp b/tests/TypeInfer.classes.test.cpp index 031d54632..be154c19f 100644 --- a/tests/TypeInfer.classes.test.cpp +++ b/tests/TypeInfer.classes.test.cpp @@ -11,10 +11,8 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauUserDefinedClasses) LUAU_FASTFLAG(LuauAllowGlobalDeclarationToBeCalledClass); -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(LuauExportValueTypecheck) -LUAU_FASTFLAG(LuauFixCallMetamethodErrorReporting) namespace { @@ -301,7 +299,6 @@ local p = Point TEST_CASE_FIXTURE(ClassesFixture, "isinstance_refines_unknown_value") { - ScopedFastFlag sff{FFlag::LuauIntegerType2, true}; CheckResult result = check(R"( class Point public x @@ -319,7 +316,7 @@ end LUAU_REQUIRE_NO_ERRORS(result); CHECK_EQ("Point", toString(requireTypeAtPosition({7, 18}))); CHECK_EQ( - "((userdata & ~Point) | boolean | buffer | function | integer | number | string | table | thread)?", toString(requireTypeAtPosition({9, 18})) + "((userdata & ~Point) | boolean | buffer | function | number | string | table | thread)?", toString(requireTypeAtPosition({9, 18})) ); } @@ -540,8 +537,6 @@ TEST_CASE_FIXTURE(ClassesFixture, "class_refers_to_later_type_alias") TEST_CASE_FIXTURE(ClassesFixture, "accept_read_only_tables") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( class Foo public bar: number | string @@ -1063,8 +1058,6 @@ TEST_CASE_FIXTURE(ClassesFixture, "method_calls_on_fully_initialized_instances_a TEST_CASE_FIXTURE(ClassesFixture, "variadic_constructor") { - ScopedFastFlag sff{FFlag::LuauFixCallMetamethodErrorReporting, true}; - CheckResult result = check(R"( class Foo public values: {number} @@ -1083,8 +1076,6 @@ TEST_CASE_FIXTURE(ClassesFixture, "variadic_constructor") TEST_CASE_FIXTURE(ClassesFixture, "variadic_constructor_with_leading_positional_arguments") { - ScopedFastFlag sff{FFlag::LuauFixCallMetamethodErrorReporting, true}; - CheckResult result = check(R"( class Foo public x: number @@ -1110,14 +1101,115 @@ TEST_CASE_FIXTURE(ClassesFixture, "fuzzer_duplicate_class_definition") CheckResult result = check(R"( class l0 end + local first = l0 class l0 end + local second = l0 )"); LUAU_REQUIRE_ERROR_COUNT(1, result); - auto err = get(result.errors[0]); + auto err = get(result.errors[0]); + REQUIRE(err); + CHECK_EQ("l0", err->name); + REQUIRE(err->previousLocation); + CHECK_EQ(Location{{1, 8}, {2, 11}}, *err->previousLocation); + + TypeId firstType = requireType("first"); + TypeId secondType = requireType("second"); + + CHECK(get(follow(firstType))); + CHECK(get(follow(secondType))); +} + +TEST_CASE_FIXTURE(ClassesFixture, "duplicate_local_classes_are_both_any") +{ + CheckResult result = check(R"( + local class l0 + end + local first = l0 + local class l0 + end + local second = l0 + )"); + + LUAU_REQUIRE_ERROR_COUNT(1, result); + auto err = get(result.errors[0]); + REQUIRE(err); + CHECK_EQ("l0", err->name); + + CHECK(get(requireType("first"))); + CHECK(get(requireType("second"))); +} + +TEST_CASE_FIXTURE(ClassesFixture, "local_class_duplicating_global_class_makes_both_any") +{ + CheckResult result = check(R"( + class l0 + end + local first = l0 + local class l0 + end + local second = l0 + )"); + + LUAU_REQUIRE_ERROR_COUNT(1, result); + CHECK(get(result.errors[0])); + + CHECK(get(requireType("first"))); + CHECK(get(requireType("second"))); +} + +TEST_CASE_FIXTURE(ClassesFixture, "class_shadowed_in_nested_block_is_not_a_duplicate") +{ + CheckResult result = check(R"( + local class l0 + end + local outer = l0 + do + local class l0 + end + local _ = l0 + end + local after = l0 + )"); + + LUAU_REQUIRE_NO_ERRORS(result); + + TypeId outerTy = requireType("outer"); + TypeId innerTy = follow(requireTypeAtPosition({7, 22})); + TypeId afterTy = requireType("after"); + + CHECK(get(outerTy)); + CHECK(get(innerTy)); + CHECK(outerTy != innerTy); + CHECK(outerTy == afterTy); +} + +TEST_CASE_FIXTURE(ClassesFixture, "duplicate_classes_in_nested_block_do_not_affect_shadowed_class") +{ + CheckResult result = check(R"( + local class l0 + end + do + local class l0 + end + local _ = l0 + local class l0 + end + local _ = l0 + end + local after = l0 + )"); + + LUAU_REQUIRE_ERROR_COUNT(1, result); + auto err = get(result.errors[0]); REQUIRE(err); - CHECK_EQ("A class named 'l0' has already been declared in this module", err->message); + REQUIRE(err->previousLocation); + CHECK_EQ(Location{{4, 12}, {5, 15}}, *err->previousLocation); + + CHECK(get(follow(requireTypeAtPosition({6, 22})))); + CHECK(get(follow(requireTypeAtPosition({9, 22})))); + CHECK(get(requireType("after"))); } TEST_CASE_FIXTURE(ClassesFixture, "repeat_props") @@ -1193,25 +1285,6 @@ TEST_CASE_FIXTURE(ClassesFixture, "fuzzer_self_referential_class_definition") CHECK(is(l0)); } -TEST_CASE_FIXTURE(ClassesFixture, "instantiate_duplicate_class") -{ - CheckResult result = check( - R"( -class l0 -end -class l0 -end -_ = l0 { } -)" - ); - - LUAU_REQUIRE_ERROR_COUNT(2, result); - auto err = get(result.errors[0]); - REQUIRE(err); - CHECK_EQ("A class named 'l0' has already been declared in this module", err->message); - REQUIRE(get(result.errors[1])); -} - TEST_CASE_FIXTURE(ClassesFixture, "prop_with_typeof_reassigned_class") { ScopedFastFlag sff{FFlag::LuauExportValueSyntax, true}; @@ -1228,9 +1301,8 @@ end ); LUAU_REQUIRE_ERROR_COUNT(1, result); - auto err = get(result.errors[0]); + auto err = get(result.errors[0]); REQUIRE(err); - CHECK_EQ("Variable 'Animal' is constant and may not be reassigned", err->message); } TEST_CASE_FIXTURE(ClassesFixture, "class_that_shadows_a_type_alias") @@ -1442,4 +1514,39 @@ TEST_CASE_FIXTURE(ClassesFixture, "fuzzer_oct_21") )")); } +TEST_CASE_FIXTURE(ClassesFixture, "class_assigning_to_local_extends_that_local") +{ + LUAU_REQUIRE_ERRORS(check(R"( +local A = 1 +class A extends A +end + )")); +} + +TEST_CASE_FIXTURE(ClassesFixture, "class_assigning_to_const") +{ + LUAU_REQUIRE_ERRORS(check(R"( +const function l0() +end +class l0 +end + )")); +} + +TEST_CASE_FIXTURE(ClassesFixture, "class_extends_and_shadows") +{ + LUAU_REQUIRE_ERRORS(check(R"( +local open class Foo + public a: number +end +do + local class Foo extends Foo + public b: number + end + local x = Foo{b=1} + local s: string = x.zzz +end + )")); +} + TEST_SUITE_END(); diff --git a/tests/TypeInfer.externTypes.test.cpp b/tests/TypeInfer.externTypes.test.cpp index 84f34dd0a..bb8d29ff5 100644 --- a/tests/TypeInfer.externTypes.test.cpp +++ b/tests/TypeInfer.externTypes.test.cpp @@ -385,8 +385,6 @@ TEST_CASE_FIXTURE(ExternTypeFixture, "table_indexers_are_invariant") TEST_CASE_FIXTURE(ExternTypeFixture, "table_class_unification_reports_sane_errors_for_missing_properties") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( function foo(bar) bar.Y = 1 -- valid @@ -443,8 +441,6 @@ b.X = 2 -- real Vector2.X is also read-only TEST_CASE_FIXTURE(ExternTypeFixture, "detailed_class_unification_error") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local function foo(v) return v.X :: number + string.len(v.Y) @@ -1023,8 +1019,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "extern_type_check_key_becomes_never") TEST_CASE_FIXTURE(BuiltinsFixture, "extern_type_check_key_becomes_intersection") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; loadDefinition(R"( @@ -1103,8 +1097,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "extern_type_intersect_with_table_indexer") TEST_CASE_FIXTURE(BuiltinsFixture, "extern_type_with_indexer_intersect_table") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; loadDefinition(R"( @@ -1265,8 +1257,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_intersected_against_extern_type_1") TEST_CASE_FIXTURE(BuiltinsFixture, "table_intersected_against_extern_type_2") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - loadDefinition(R"( declare extern type Folder with end diff --git a/tests/TypeInfer.functions.test.cpp b/tests/TypeInfer.functions.test.cpp index 3d4ec90d9..ac58da515 100644 --- a/tests/TypeInfer.functions.test.cpp +++ b/tests/TypeInfer.functions.test.cpp @@ -25,9 +25,7 @@ LUAU_FASTFLAG(LuauBidirectionalInferenceBetterLambdaHandling) LUAU_FASTFLAG(LuauExportValueSyntax) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) -LUAU_FASTFLAG(LuauDoNotLeakGenericsInIndexer) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) -LUAU_FASTFLAG(LuauFixCallMetamethodErrorReporting) LUAU_FASTFLAG(LuauTraverseScopeToFunction) LUAU_FASTFLAG(LuauIterativeTypeSearcher) @@ -732,8 +730,6 @@ TEST_CASE_FIXTURE(Fixture, "higher_order_function_2") TEST_CASE_FIXTURE(Fixture, "higher_order_function_3") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -1437,8 +1433,6 @@ f(function(x) return x * 2 end) TEST_CASE_FIXTURE(BuiltinsFixture, "infer_generic_function_function_argument") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - // FIXME: CLI-116133 bidirectional type inference needs to push expected types in for higher-order function calls DOES_NOT_PASS_NEW_SOLVER_GUARD(); @@ -2377,10 +2371,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "attempt_to_call_an_intersection_of_tables_wi TEST_CASE_FIXTURE(BuiltinsFixture, "call_metamethod_checks_argument_types") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - - ScopedFastFlag _{FFlag::LuauFixCallMetamethodErrorReporting, true}; - CheckResult result = check(R"( type Callable = typeof(setmetatable({}, {} :: { __call: (Callable, number) -> string })) local f = (nil :: any) :: Callable @@ -2395,10 +2385,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "call_metamethod_checks_argument_types") TEST_CASE_FIXTURE(BuiltinsFixture, "call_metamethod_checks_variadic_argument_types") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - - ScopedFastFlag _{FFlag::LuauFixCallMetamethodErrorReporting, true}; - CheckResult result = check(R"( type Callable = typeof(setmetatable({}, {} :: { __call: (Callable, ...number) -> () })) local f = (nil :: any) :: Callable @@ -2414,10 +2400,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "call_metamethod_checks_variadic_argument_typ // the superPath. Without that, the error lands on the last argument rather than the bad one. TEST_CASE_FIXTURE(BuiltinsFixture, "call_metamethod_variadic_blames_the_offending_argument") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - - ScopedFastFlag _{FFlag::LuauFixCallMetamethodErrorReporting, true}; - CheckResult result = check(R"( type Callable = typeof(setmetatable({}, {} :: { __call: (Callable, ...number) -> () })) local f = (nil :: any) :: Callable @@ -2434,10 +2416,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "call_metamethod_variadic_blames_the_offendin TEST_CASE_FIXTURE(BuiltinsFixture, "call_metamethod_variadic_blames_each_offending_argument") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - - ScopedFastFlag _{FFlag::LuauFixCallMetamethodErrorReporting, true}; - CheckResult result = check(R"( type Callable = typeof(setmetatable({}, {} :: { __call: (Callable, ...number) -> () })) local f = (nil :: any) :: Callable @@ -2749,8 +2727,6 @@ TEST_CASE_FIXTURE(Fixture, "local_function_fwd_decl_doesnt_crash") TEST_CASE_FIXTURE(Fixture, "bidirectional_checking_of_callback_property") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( function print(x: number) end @@ -2822,8 +2798,6 @@ TEST_CASE_FIXTURE(Fixture, "pass_table_literal_to_function_expecting_optional_pr TEST_CASE_FIXTURE(Fixture, "function_inference_notes_generic_return") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag _{FFlag::LuauIterativeTypeSearcher, true}; @@ -2851,8 +2825,6 @@ TEST_CASE_FIXTURE(Fixture, "function_inference_notes_generic_return") TEST_CASE_FIXTURE(Fixture, "dont_infer_overloaded_functions") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::LuauIterativeTypeSearcher, true}; CheckResult result = check(R"( @@ -3245,8 +3217,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "string_format_pack_variadic") TEST_CASE_FIXTURE(Fixture, "table_annotated_explicit_self") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; CheckResult results = check(R"( @@ -3291,8 +3261,6 @@ TEST_CASE_FIXTURE(Fixture, "oss_1871") TEST_CASE_FIXTURE(BuiltinsFixture, "io_manager_oop_ish") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -3327,8 +3295,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "io_manager_oop_ish") TEST_CASE_FIXTURE(BuiltinsFixture, "generic_function_statement") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -3649,8 +3615,6 @@ TEST_CASE_FIXTURE(Fixture, "overload_selection_union_of_functions") TEST_CASE_FIXTURE(Fixture, "overload_selection_needs_to_retry") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; auto results = check(R"( @@ -3914,8 +3878,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "pcall_example") TEST_CASE_FIXTURE(ExternTypeFixture, "bidirectional_function_statement_inference_with_extern") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( type HasClass = { f: (ClassWithGenericMethod) -> () } local t = {} :: HasClass @@ -4547,12 +4509,8 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2623_double_negate_string") TEST_CASE_FIXTURE(Fixture, "oss_2670_generic_leaking_indexer_1") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauDoNotLeakGenericsInIndexer, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local function setDefault(t: { [K]: V? }): V return nil :: any @@ -4572,12 +4530,8 @@ TEST_CASE_FIXTURE(Fixture, "oss_2670_generic_leaking_indexer_1") TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2670_generic_leaking_indexer_2") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag _{FFlag::LuauDoNotLeakGenericsInIndexer, true}; - LUAU_REQUIRE_NO_ERRORS(check(R"( local set: ({ [K | number]: V | string }) -> V diff --git a/tests/TypeInfer.generics.test.cpp b/tests/TypeInfer.generics.test.cpp index 2b6a7bbfe..79307d535 100644 --- a/tests/TypeInfer.generics.test.cpp +++ b/tests/TypeInfer.generics.test.cpp @@ -801,8 +801,6 @@ TEST_CASE_FIXTURE(Fixture, "typefuns_sharing_types") TEST_CASE_FIXTURE(BuiltinsFixture, "bound_tables_do_not_clone_original_fields") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local exports = {} local nested = {} @@ -1495,8 +1493,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "infer_generic_function_function_argument_2") TEST_CASE_FIXTURE(BuiltinsFixture, "infer_generic_function_function_argument_3") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local function foldl(arr: {a}, init: b, f: (b, a) -> b) local r = init @@ -2225,8 +2221,6 @@ TEST_CASE_FIXTURE(Fixture, "id_function_do_not_leak_generic") TEST_CASE_FIXTURE(BuiltinsFixture, "cli_185450_instantiate_generics_prior_to_pushing") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_OLD_SOLVER_GUARD(); CheckResult result = check(R"( diff --git a/tests/TypeInfer.intersectionTypes.test.cpp b/tests/TypeInfer.intersectionTypes.test.cpp index 036cd7b27..1feefeda9 100644 --- a/tests/TypeInfer.intersectionTypes.test.cpp +++ b/tests/TypeInfer.intersectionTypes.test.cpp @@ -33,8 +33,6 @@ TEST_CASE_FIXTURE(Fixture, "select_correct_union_fn") TEST_CASE_FIXTURE(Fixture, "table_combines") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( type A={a:number} type B={b:string} @@ -319,8 +317,6 @@ TEST_CASE_FIXTURE(Fixture, "table_intersection_write") TEST_CASE_FIXTURE(Fixture, "table_intersection_write_sealed") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( type X = { x: number } type Y = { y: number } @@ -338,8 +334,6 @@ TEST_CASE_FIXTURE(Fixture, "table_intersection_write_sealed") TEST_CASE_FIXTURE(Fixture, "table_intersection_write_sealed_indirect") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::LuauCheckFunctionStatementTypes, true}; CheckResult result = check(R"( @@ -628,8 +622,6 @@ TEST_CASE_FIXTURE(Fixture, "union_saturate_overloaded_functions") TEST_CASE_FIXTURE(Fixture, "intersection_of_tables") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( function f(x: { p : number?, q : string? } & { p : number?, q : number?, r : number? }) local y : { p : number?, q : nil, r : number? } = x -- OK @@ -707,8 +699,6 @@ TEST_CASE_FIXTURE(Fixture, "intersection_of_tables_with_never_properties") TEST_CASE_FIXTURE(Fixture, "overloaded_functions_returning_intersections") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( function f(x : ((number?) -> ({ p : number } & { q : number })) & ((string?) -> ({ p : number } & { r : number }))) local y : (nil) -> { p : number, q : number, r : number} = x -- OK @@ -1196,8 +1186,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "intersect_metatables") TEST_CASE_FIXTURE(BuiltinsFixture, "intersect_metatable_subtypes") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local x = setmetatable({ a = 5 }, { p = 5 }) local y = setmetatable({ b = "hi" }, { p = 5, q = "hi" }) @@ -1219,8 +1207,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "intersect_metatable_subtypes") TEST_CASE_FIXTURE(BuiltinsFixture, "intersect_metatables_with_properties") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local x = setmetatable({ a = 5 }, { p = 5 }) local y = setmetatable({ b = "hi" }, { q = "hi" }) @@ -1242,8 +1228,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "intersect_metatables_with_properties") TEST_CASE_FIXTURE(BuiltinsFixture, "intersect_metatable_with_table") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (!FFlag::DebugLuauForceOldSolver) { CheckResult result = check(R"( @@ -1286,8 +1270,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "intersect_metatable_with_table") TEST_CASE_FIXTURE(Fixture, "CLI-44817") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( type X = {x: number} type Y = {y: number} @@ -1427,8 +1409,6 @@ TEST_CASE_FIXTURE(Fixture, "cli_80596_simplify_more_realistic_intersections") TEST_CASE_FIXTURE(BuiltinsFixture, "narrow_intersection_nevers") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sffs{FFlag::DebugLuauForceOldSolver, false}; loadDefinition(R"( diff --git a/tests/TypeInfer.loops.test.cpp b/tests/TypeInfer.loops.test.cpp index 00705c754..10ac79fc9 100644 --- a/tests/TypeInfer.loops.test.cpp +++ b/tests/TypeInfer.loops.test.cpp @@ -44,8 +44,6 @@ TEST_CASE_FIXTURE(Fixture, "for_loop") TEST_CASE_FIXTURE(BuiltinsFixture, "iteration_no_table_passed") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - // This test may block CI if forced to run outside of DCR. if (FFlag::DebugLuauForceOldSolver) return; @@ -74,8 +72,6 @@ for a, b in t do end TEST_CASE_FIXTURE(BuiltinsFixture, "iteration_regression_issue_69967") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -97,8 +93,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "iteration_regression_issue_69967") TEST_CASE_FIXTURE(BuiltinsFixture, "iteration_regression_issue_69967_alt") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -1280,8 +1274,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "forin_metatable_no_iter_mm") TEST_CASE_FIXTURE(BuiltinsFixture, "forin_metatable_iter_mm") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -1353,8 +1345,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "for_in_require") TEST_CASE_FIXTURE(Fixture, "oss_1480") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - LUAU_REQUIRE_NO_ERRORS(check(R"( type Part = { Parent: Part? } type Instance = Part diff --git a/tests/TypeInfer.metatableOOP.test.cpp b/tests/TypeInfer.metatableOOP.test.cpp index fb6080023..db0902fbc 100644 --- a/tests/TypeInfer.metatableOOP.test.cpp +++ b/tests/TypeInfer.metatableOOP.test.cpp @@ -300,8 +300,6 @@ TEST_CASE_FIXTURE(Fixture, "inferred_methods_of_free_tables_have_the_same_level_ TEST_CASE_FIXTURE(BuiltinsFixture, "table_oop") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( --!strict local Class = {} @@ -728,8 +726,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oop_invoke_with_inferred_self_and_property") TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_field_allows_upcast") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, }; @@ -747,8 +743,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_field_allows_upcast") TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_field_disallows_invalid_upcast") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; CheckResult results = check(R"( @@ -770,8 +764,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_field_disallows_invalid_upcast") TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_field_precedence_for_subtyping") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; CheckResult results = check(R"( @@ -840,8 +832,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "assign_to_prop_of_intersection_of_metatables TEST_CASE_FIXTURE(BuiltinsFixture, "subclass_property_access") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_OLD_SOLVER_GUARD(); ScopedFastFlag _{FFlag::LuauSetmetatableOverrides, true}; diff --git a/tests/TypeInfer.modules.test.cpp b/tests/TypeInfer.modules.test.cpp index af06e4db0..d465e4a14 100644 --- a/tests/TypeInfer.modules.test.cpp +++ b/tests/TypeInfer.modules.test.cpp @@ -959,8 +959,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "invalid_alias_should_export_as_error_type") TEST_CASE_FIXTURE(BuiltinsFixture, "cli_194463_modify_bounds_of_visited_generic_regression") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - fileResolver.source["game/Container"] = R"( local Container = {} @@ -1036,8 +1034,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "exported_module_basic") TEST_CASE_FIXTURE(BuiltinsFixture, "exported_module_initializer_type_packs") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _[4]{ {FFlag::LuauExportValueSyntax, true}, {FFlag::DebugLuauForceOldSolver, false}, @@ -1077,8 +1073,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "exported_module_initializer_type_packs") TEST_CASE_FIXTURE(BuiltinsFixture, "exported_module_initializer_type_packs_multi") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _[4]{ {FFlag::LuauExportValueSyntax, true}, {FFlag::DebugLuauForceOldSolver, false}, @@ -1390,8 +1384,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "non_exported_class") TEST_CASE_FIXTURE(BuiltinsFixture, "exported_module_annotation_uses_binding_type") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sffs[]{ {FFlag::DebugLuauForceOldSolver, false}, {FFlag::LuauExportValueSyntax, true}, diff --git a/tests/TypeInfer.operators.test.cpp b/tests/TypeInfer.operators.test.cpp index 4a894e8e9..f2d20dc20 100644 --- a/tests/TypeInfer.operators.test.cpp +++ b/tests/TypeInfer.operators.test.cpp @@ -13,7 +13,6 @@ using namespace Luau; LUAU_FASTFLAG(DebugLuauForceOldSolver) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauSolverAgnosticStringification) LUAU_FASTFLAG(LuauCompoundAssignSeedsAstTypes) @@ -1279,8 +1278,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_type_for_generic_concat") TEST_CASE_FIXTURE(BuiltinsFixture, "equality_operations_succeed_if_any_union_branch_succeeds") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local mm = {} type Foo = typeof(setmetatable({}, mm)) @@ -1705,8 +1702,6 @@ end TEST_CASE_FIXTURE(BuiltinsFixture, "overload_concat") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( type classData = { b:buffer; @@ -1737,35 +1732,4 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "overload_concat") LUAU_CHECK_NO_ERRORS(result); } -TEST_CASE_FIXTURE(BuiltinsFixture, "negated_integer_literal_is_a_constant") -{ - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag sff{FFlag::LuauIntegerType2, true}; - - // compileExprUnary folds this into one negative constant, so it never negates anything at runtime. - CheckResult result = check(R"( - --!strict - local a = -4194626i - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - CHECK("integer" == toString(requireType("a"))); -} - -TEST_CASE_FIXTURE(BuiltinsFixture, "negating_a_non_literal_integer_is_an_error") -{ - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag sff{FFlag::LuauIntegerType2, true}; - - // Only the literal is folded. This one reaches the runtime, where integer has no __unm. - CheckResult result = check(R"( - --!strict - local b = 5i - local c = -b - local d = -(5i) - )"); - - LUAU_REQUIRE_ERROR_COUNT(4, result); -} - TEST_SUITE_END(); diff --git a/tests/TypeInfer.provisional.test.cpp b/tests/TypeInfer.provisional.test.cpp index 11898ef6b..f97b539bf 100644 --- a/tests/TypeInfer.provisional.test.cpp +++ b/tests/TypeInfer.provisional.test.cpp @@ -21,7 +21,6 @@ LUAU_FASTINT(LuauTarjanChildLimit) LUAU_FASTINT(LuauTypeInferIterationLimit) LUAU_FASTINT(LuauTypeInferRecursionLimit) LUAU_FASTINT(LuauTypeInferTypePackLoopLimit) -LUAU_FASTFLAG(LuauIntegerType2) LUAU_FASTFLAG(LuauImproveUniqueTableWidthSubtyping) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) @@ -64,17 +63,6 @@ TEST_CASE_FIXTURE(Fixture, "typeguard_inference_incomplete") )"; const std::string expectedWithNewSolver = - R"( - function f(a:{fn:()->(unknown,...unknown)}): () - if type(a) == 'boolean' then - local a1:{fn:()->(unknown,...unknown)}&boolean=a - elseif a.fn() then - local a2:{fn:()->(unknown,...unknown)}&(userdata|function|nil|number|integer|string|thread|buffer|table)=a - end - end - )"; - - const std::string expectedWithNewSolver_NOINTEGER = R"( function f(a:{fn:()->(unknown,...unknown)}): () if type(a) == 'boolean' then @@ -86,12 +74,7 @@ TEST_CASE_FIXTURE(Fixture, "typeguard_inference_incomplete") )"; if (!FFlag::DebugLuauForceOldSolver) - { - if (FFlag::LuauIntegerType2) - CHECK_EQ(expectedWithNewSolver, decorateWithTypes(code)); - else - CHECK_EQ(expectedWithNewSolver_NOINTEGER, decorateWithTypes(code)); - } + CHECK_EQ(expectedWithNewSolver, decorateWithTypes(code)); else CHECK_EQ(expected, decorateWithTypes(code)); } @@ -195,8 +178,6 @@ TEST_CASE_FIXTURE(Fixture, "it_should_be_agnostic_of_actual_size") // For now, infer it as just a free table. TEST_CASE_FIXTURE(BuiltinsFixture, "setmetatable_constrains_free_type_into_free_table") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_NEW_SOLVER_GUARD(); CheckResult result = check(R"( @@ -842,8 +823,6 @@ Expected this to be exactly 'number', but got 'number?')"; TEST_CASE_FIXTURE(BuiltinsFixture, "table_insert_with_a_singleton_argument") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_NEW_SOLVER_GUARD(); CheckResult result = check(R"( @@ -1355,8 +1334,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_unknown_to_table_and_test_two_props") TEST_CASE_FIXTURE(BuiltinsFixture, "function_indexer_satisfies_reading_property") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; // We would like this code to have _no_ errors, but it requires one of: diff --git a/tests/TypeInfer.refinements.test.cpp b/tests/TypeInfer.refinements.test.cpp index 09987e2c2..e73a65b95 100644 --- a/tests/TypeInfer.refinements.test.cpp +++ b/tests/TypeInfer.refinements.test.cpp @@ -16,7 +16,6 @@ LUAU_FASTFLAG(LuauExperimentalIfLocalAnalysis) LUAU_FASTFLAG(DebugLuauCFG) LUAU_FASTFLAG(LuauIterativeTypeSearcher) LUAU_FASTFLAG(LuauDoesCallErrorUnwrapsGroups) -LUAU_FASTFLAG(LuauRefineNotNilWaitsForBlockedTarget) LUAU_FASTFLAG(LuauExperimentalWhileLocalSyntax) LUAU_FASTFLAG(LuauExperimentalWhileLocalAnalysis) @@ -512,8 +511,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_unknown_to_table_then_test_a_prop") TEST_CASE_FIXTURE(BuiltinsFixture, "indexing_unknown_refined_to_table_reports_missing_indexer") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -1186,8 +1183,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "either_number_or_string") TEST_CASE_FIXTURE(Fixture, "not_t_or_some_prop_of_t") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local function f(t: {x: boolean}?) if not t or t.x then @@ -1788,8 +1783,6 @@ TEST_CASE_FIXTURE(RefinementExternTypeFixture, "refine_param_of_type_folder_or_p TEST_CASE_FIXTURE(RefinementExternTypeFixture, "isa_type_refinement_must_be_known_ahead_of_time") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::LuauIterativeTypeSearcher, true}; CheckResult result = check(R"( @@ -1820,8 +1813,6 @@ TEST_CASE_FIXTURE(RefinementExternTypeFixture, "isa_type_refinement_must_be_know TEST_CASE_FIXTURE(RefinementExternTypeFixture, "asserting_optional_properties_should_not_refine_extern_types_to_never") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local weld: WeldConstraint = nil :: any @@ -2060,8 +2051,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_unknown_to_table_then_take_the_length TEST_CASE_FIXTURE(BuiltinsFixture, "refine_unknown_to_table_then_clone_it") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local function f(x: unknown) if typeof(x) == "table" then @@ -2818,8 +2807,6 @@ TEST_CASE_FIXTURE(Fixture, "oss_1687_equality_shouldnt_leak_nil") TEST_CASE_FIXTURE(BuiltinsFixture, "oss_1451") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; LUAU_REQUIRE_NO_ERRORS(check(R"( @@ -2874,8 +2861,6 @@ TEST_CASE_FIXTURE(RefinementExternTypeFixture, "cli_140033_refine_union_of_exter TEST_CASE_FIXTURE(RefinementExternTypeFixture, "cannot_call_a_function_union") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -3005,8 +2990,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_by_no_refine_should_always_reduce") TEST_CASE_FIXTURE(Fixture, "table_name_index_without_prior_assignment_from_branch") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; // The important part of this test case is: @@ -3046,8 +3029,6 @@ TEST_CASE_FIXTURE(Fixture, "cli_120460_table_access_on_phi_node") TEST_CASE_FIXTURE(BuiltinsFixture, "refinements_from_and_should_not_refine_to_never") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, }; @@ -3135,8 +3116,6 @@ end TEST_CASE_FIXTURE(BuiltinsFixture, "inline_if_conditional_context") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - LUAU_REQUIRE_NO_ERRORS(check(R"( --!strict @@ -3381,8 +3360,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cli_181549_refined_string_should_be_subtype_ TEST_CASE_FIXTURE(Fixture, "cli_184413_refinement_of_union_of_read_types_is_read_type") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - LUAU_REQUIRE_NO_ERRORS(check(R"( export type States = "Closed" | "Closing" | "Opening" | "Open" export type MyType = { @@ -3989,10 +3966,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "refine_not_nil_waits_for_blocked_target") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); - ScopedFastFlag sffs[] = { - {FFlag::LuauRefineNotNilWaitsForBlockedTarget, true}, - {FFlag::DebugLuauAssertOnForcedConstraint, true}, - }; + ScopedFastFlag sff{FFlag::DebugLuauAssertOnForcedConstraint, true}; CheckResult result = check(R"( local M = {} diff --git a/tests/TypeInfer.tables.test.cpp b/tests/TypeInfer.tables.test.cpp index 316a5df4a..dbb095982 100644 --- a/tests/TypeInfer.tables.test.cpp +++ b/tests/TypeInfer.tables.test.cpp @@ -25,8 +25,6 @@ LUAU_FASTFLAG(LuauFixIndexerSubtypingOrdering) LUAU_FASTFLAG(DebugLuauAssertOnForcedConstraint) LUAU_FASTINT(LuauPrimitiveInferenceInTableLimit) LUAU_FASTFLAG(LuauCallErrorReportingRecoversArgumentLocationsForPacks) -LUAU_FASTFLAG(DebugLuauParseExactTables) -LUAU_FASTFLAG(DebugLuauExactTableTypes) LUAU_FASTFLAG(LuauTraverseScopeToFunction) LUAU_FASTFLAG(LuauInferReadOnlyIndexers) LUAU_FASTFLAG(LuauDecomposeIntersectionOfFreeType) @@ -34,23 +32,6 @@ LUAU_FASTFLAG(LuauRefactorStringSemanticSubtyping) LUAU_FASTFLAG(LuauEqualityConstraintBinds) LUAU_FASTFLAG(LuauNonreentrantLookupTableProp) -namespace -{ - -struct ExactTableFlags -{ - ScopedFastFlag parseExactTables{FFlag::DebugLuauParseExactTables, true}; - ScopedFastFlag exactTableTypes{FFlag::DebugLuauExactTableTypes, true}; -}; - -struct LegacyExactTableFlags -{ - ScopedFastFlag parseExactTables{FFlag::DebugLuauParseExactTables, false}; - ScopedFastFlag exactTableTypes{FFlag::DebugLuauExactTableTypes, false}; -}; - -} // namespace - TEST_SUITE_BEGIN("TableTests"); TEST_CASE_FIXTURE(BuiltinsFixture, "generalization_shouldnt_seal_table_in_len_function_fn") @@ -210,21 +191,6 @@ TEST_CASE_FIXTURE(Fixture, "cannot_augment_sealed_table") CHECK_EQ(error->context, CannotExtendTable::Property); } -TEST_CASE_FIXTURE(Fixture, "dont_seal_an_unsealed_table_by_passing_it_to_a_function_that_takes_a_sealed_table") -{ - ExactTableFlags exactTableFlags; - CheckResult result = check(R"( - type T = {[number]: number, ...} - function f(arg: T) end - - local B = {} - f(B) - function B:method() end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); -} - TEST_CASE_FIXTURE(Fixture, "updating_sealed_table_prop_is_ok") { CheckResult result = check("local t = {prop=999} t.prop = 0"); @@ -640,22 +606,6 @@ TEST_CASE_FIXTURE(Fixture, "okay_to_add_property_to_unsealed_tables_by_function_ // CHECK_EQ("number?", toString(requireType("x"))); } -TEST_CASE_FIXTURE(Fixture, "width_subtyping") -{ - ExactTableFlags exactTableFlags; - CheckResult result = check(R"( - --!strict - function f(x : { q : number, ... }) - x.q = 8 - end - local t : { q : number, r : string, ... } = { q = 8, r = "hi" } - f(t) - local x : string = t.r - )"); - - LUAU_REQUIRE_NO_ERRORS(result); -} - TEST_CASE_FIXTURE(Fixture, "width_subtyping_needs_covariance") { CheckResult result = check(R"( @@ -721,8 +671,6 @@ TEST_CASE_FIXTURE(Fixture, "infer_array_2") TEST_CASE_FIXTURE(Fixture, "indexers_get_quantified_too") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( function swap(p) local temp = p[0] @@ -1698,31 +1646,6 @@ TEST_CASE_FIXTURE(Fixture, "right_table_missing_key") CHECK_GE(result.errors.size(), 0); } -// Could be flaky if the fix has regressed. -TEST_CASE_FIXTURE(Fixture, "right_table_missing_key2") -{ - ExactTableFlags exactTableFlags; - // CLI-114792 We don't report MissingProperties - DOES_NOT_PASS_NEW_SOLVER_GUARD(); - - CheckResult result = check(R"( - function f(t: {}): { [string]: string, a: string } - return t - end - )"); - - LUAU_REQUIRE_ERROR_COUNT(1, result); - - MissingProperties* mp = get(result.errors[0]); - REQUIRE_MESSAGE(mp, "Expected MissingProperties but got " << toString(result.errors[0])); - CHECK_EQ(mp->context, MissingProperties::Missing); - REQUIRE_EQ(1, mp->properties.size()); - CHECK_EQ(mp->properties[0], "a"); - - CHECK_EQ("{ [string]: string, a: string, ... }", toString(mp->superType)); - CHECK_EQ("{ ... }", toString(mp->subType)); -} - TEST_CASE_FIXTURE(Fixture, "casting_unsealed_tables_with_props_into_table_with_indexer") { CheckResult result = check(R"( @@ -1876,7 +1799,6 @@ TEST_CASE_FIXTURE(Fixture, "table_subtyping_with_missing_props_dont_report_multi TEST_CASE_FIXTURE(Fixture, "table_subtyping_with_extra_props_dont_report_multiple_errors") { - LegacyExactTableFlags legacyExactTableFlags; CheckResult result = check(R"( function mkvec3() return {x = 1, y = 2, z = 3} end function mkvec1() return {x = 1} end @@ -2295,10 +2217,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "quantifying_a_bound_var_works") REQUIRE(mtv); ttv = getMutable(follow(mtv->table)); REQUIRE(ttv); - if (FFlag::DebugLuauExactTableTypes) - REQUIRE_EQ(ttv->state, TableState::Exact); - else - REQUIRE_EQ(ttv->state, TableState::Sealed); + REQUIRE_EQ(ttv->state, TableState::Sealed); } TEST_CASE_FIXTURE(Fixture, "common_table_element_union_in_call") @@ -2392,8 +2311,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_insert_should_cope_with_optional_prope TEST_CASE_FIXTURE(BuiltinsFixture, "table_insert_should_cope_with_optional_properties_in_strict") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, {FFlag::DebugLuauAssertOnForcedConstraint, true}, @@ -2630,42 +2547,6 @@ a.p = { x = 9 } LUAU_REQUIRE_NO_ERRORS(result); } -TEST_CASE_FIXTURE(Fixture, "explicitly_typed_table_error") -{ - ExactTableFlags exactTableFlags; - CheckResult result = check(R"( - --!strict - type Super = { x : number, ... } - type Sub = { x : number, y: number, ... } - type HasSuper = { p : Super, ... } - type HasSub = { p : Sub, ... } - local tmp = { p = { x = 5, y = 7 }} - local a: HasSuper = tmp - a.p = { x = 9 } - -- needs to be an error because - local y: number = tmp.p.y - )"); - - LUAU_REQUIRE_ERROR_COUNT(1, result); - - if (!FFlag::DebugLuauForceOldSolver) - { - CHECK(7 == result.errors[0].location.begin.line); - CHECK( - "Expected this to be 'HasSuper', but got 'tmp'; \n" - "Expected property `p` to be exactly `Super`, but got `{ x: number, y: number }`" == toString(result.errors[0]) - ); - } - else - { - const std::string expected = R"(Expected this to be exactly 'HasSuper', but got 'tmp' -caused by: - Property 'p' is not compatible. -Table type '{| x: number, y: number |}' not compatible with type 'Super' because the former has extra field 'y')"; - CHECK_EQ(expected, toString(result.errors[0])); - } -} - TEST_CASE_FIXTURE(Fixture, "explicitly_typed_table_with_indexer") { CheckResult result = check(R"( @@ -2681,23 +2562,6 @@ TEST_CASE_FIXTURE(Fixture, "explicitly_typed_table_with_indexer") LUAU_REQUIRE_NO_ERRORS(result); } -TEST_CASE_FIXTURE(BuiltinsFixture, "recursive_metatable_type_call") -{ - ExactTableFlags exactTableFlags; - // CLI-114782 - DOES_NOT_PASS_NEW_SOLVER_GUARD(); - - CheckResult result = check(R"( -local b -b = setmetatable({}, {__call = b}) -b() - )"); - - LUAU_REQUIRE_ERROR_COUNT(1, result); - - CHECK_EQ(toString(result.errors[0]), R"(Cannot call a value of type t1 where t1 = setmetatable<{| |}, {| __call: t1 |}>)"); -} - TEST_CASE_FIXTURE(Fixture, "table_subtyping_shouldn't_add_optional_properties_to_sealed_tables") { CheckResult result = check(R"( @@ -2806,22 +2670,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "give_up_after_one_metatable_index_look_up") CHECK_EQ("Type 't2' does not have key 'x'", toString(result.errors[0])); } -TEST_CASE_FIXTURE(Fixture, "confusing_indexing") -{ - ExactTableFlags exactTableFlags; - CheckResult result = check(R"( - type T = {...} & {p: number | string, ...} - local function f(t: T) - return t.p - end - - local foo = f({p = "string"}) - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - CHECK_EQ("number | string", toString(requireType("foo"))); -} - TEST_CASE_FIXTURE(Fixture, "pass_a_union_of_tables_to_a_function_that_requires_a_table") { CheckResult result = check(R"( @@ -2837,9 +2685,7 @@ TEST_CASE_FIXTURE(Fixture, "pass_a_union_of_tables_to_a_function_that_requires_a LUAU_REQUIRE_NO_ERRORS(result); - if (!FFlag::DebugLuauForceOldSolver && FFlag::DebugLuauExactTableTypes) - CHECK("{ y: number, ... }" == toString(requireType("b"))); - else if (!FFlag::DebugLuauForceOldSolver) + if (!FFlag::DebugLuauForceOldSolver) REQUIRE_EQ("{ y: number }", toString(requireType("b"))); else REQUIRE_EQ("{- y: number -}", toString(requireType("b"))); @@ -2860,9 +2706,7 @@ TEST_CASE_FIXTURE(Fixture, "pass_a_union_of_tables_to_a_function_that_requires_a LUAU_REQUIRE_NO_ERRORS(result); - if (!FFlag::DebugLuauForceOldSolver && FFlag::DebugLuauExactTableTypes) - CHECK("{ y: number, ... }" == toString(requireType("b"))); - else if (!FFlag::DebugLuauForceOldSolver) + if (!FFlag::DebugLuauForceOldSolver) REQUIRE_EQ("{ y: number }", toString(requireType("b"))); else REQUIRE_EQ("{- y: number -}", toString(requireType("b"))); @@ -3570,8 +3414,6 @@ TEST_CASE_FIXTURE(Fixture, "inferred_properties_of_a_table_should_start_with_the // The real bug here was that we weren't always uncondionally typechecking a trailing return statement last. TEST_CASE_FIXTURE(BuiltinsFixture, "dont_leak_free_table_props") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local function a(state) print(state.blah) @@ -3591,14 +3433,7 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "dont_leak_free_table_props") LUAU_REQUIRE_NO_ERRORS(result); - if (!FFlag::DebugLuauForceOldSolver && FFlag::DebugLuauExactTableTypes) - { - CHECK("({ read blah: unknown, ... }) -> ()" == toString(requireType("a"))); - CHECK("({ read gwar: unknown, ... }) -> ()" == toString(requireType("b"))); - // FIXME? A curious canonicalization regression. - CHECK("(...any) -> ({ read blah: unknown, ... } & { read gwar: unknown, ... }) -> ()" == toString(getMainModule()->returnType)); - } - else if (!FFlag::DebugLuauForceOldSolver) + if (!FFlag::DebugLuauForceOldSolver) { CHECK_EQ("({ read blah: unknown }) -> ()", toString(requireType("a"))); CHECK_EQ("({ read gwar: unknown }) -> ()", toString(requireType("b"))); @@ -3674,18 +3509,6 @@ TEST_CASE_FIXTURE(Fixture, "prop_access_on_key_whose_types_mismatches") CHECK_EQ("Key 'x' not found in table '{number}'", toString(result.errors[0])); } -TEST_CASE_FIXTURE(Fixture, "prop_access_on_unions_of_indexers_where_key_whose_types_mismatches") -{ - ExactTableFlags exactTableFlags; - CheckResult result = check(R"( - local t: { [number]: number, ... } | { [boolean]: number, ... } = {} - local u = t.x - )"); - - LUAU_REQUIRE_ERROR_COUNT(1, result); - CHECK_EQ("Type '{ [boolean]: number, ... } | {number, ...}' does not have key 'x'", toString(result.errors[0])); -} - TEST_CASE_FIXTURE(BuiltinsFixture, "leaking_bad_metatable_errors") { CheckResult result = check(R"( @@ -3716,80 +3539,6 @@ TEST_CASE_FIXTURE(Fixture, "scalar_is_a_subtype_of_a_compatible_polymorphic_shap LUAU_REQUIRE_NO_ERRORS(result); } -TEST_CASE_FIXTURE(Fixture, "scalar_is_not_a_subtype_of_a_compatible_polymorphic_shape_type") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag sff{FFlag::LuauCallErrorReportingRecoversArgumentLocationsForPacks, true}; - CheckResult result = check(R"( - local function f(s) - return s:absolutely_no_scalar_has_this_method() - end - - f("foo" :: string) - f("bar" :: "bar") - f("baz" :: "bar" | "baz") - )"); - - - if (!FFlag::DebugLuauForceOldSolver) - { - // CLI-115090 Error reporting is quite bad in this case. - - // This should be just 3 - LUAU_REQUIRE_ERROR_COUNT(4, result); - - TypeMismatch* tm1 = get(result.errors[0]); - REQUIRE(tm1); - CHECK("typeof(string)" == toString(tm1->givenType)); - CHECK("t1 where t1 = { read absolutely_no_scalar_has_this_method: (t1) -> (T...), ... }" == toString(tm1->wantedType)); - - TypeMismatch* tm2 = get(result.errors[1]); - REQUIRE(tm2); - CHECK("typeof(string)" == toString(tm2->givenType)); - CHECK("t1 where t1 = { read absolutely_no_scalar_has_this_method: (t1) -> (T...), ... }" == toString(tm2->wantedType)); - - TypeMismatch* tm3 = get(result.errors[2]); - REQUIRE(tm3); - CHECK("\"bar\" | \"baz\"" == toString(tm3->givenType)); - CHECK("t1 where t1 = { read absolutely_no_scalar_has_this_method: (t1) -> (T...), ... }" == toString(tm3->wantedType)); - - TypeMismatch* tm4 = get(result.errors[3]); - REQUIRE(tm4); - CHECK("\"bar\" | \"baz\"" == toString(tm4->givenType)); - CHECK("t1 where t1 = { read absolutely_no_scalar_has_this_method: (t1) -> (T...), ... }" == toString(tm4->wantedType)); - } - else - { - LUAU_REQUIRE_ERROR_COUNT(3, result); - - const std::string expected1 = - R"(Expected this to be 't1 where t1 = {- absolutely_no_scalar_has_this_method: (t1) -> (a...) -}', but got 'string' -caused by: - The given type's metatable does not satisfy the requirements. -Table type 'typeof(string)' not compatible with type 't1 where t1 = {- absolutely_no_scalar_has_this_method: (t1) -> (a...) -}' because the former is missing field 'absolutely_no_scalar_has_this_method')"; - CHECK_EQ(expected1, toString(result.errors[0])); - - const std::string expected2 = - R"(Expected this to be 't1 where t1 = {- absolutely_no_scalar_has_this_method: (t1) -> (a...) -}', but got '"bar"' -caused by: - The given type's metatable does not satisfy the requirements. -Table type 'typeof(string)' not compatible with type 't1 where t1 = {- absolutely_no_scalar_has_this_method: (t1) -> (a...) -}' because the former is missing field 'absolutely_no_scalar_has_this_method')"; - CHECK_EQ(expected2, toString(result.errors[1])); - - const std::string expected3 = R"(Expected this to be - 't1 where t1 = {- absolutely_no_scalar_has_this_method: (t1) -> (a...) -}' -but got - '"bar" | "baz"' -caused by: - Not all union options are compatible. -Expected this to be 't1 where t1 = {- absolutely_no_scalar_has_this_method: (t1) -> (a...) -}', but got '"bar"' -caused by: - The given type's metatable does not satisfy the requirements. -Table type 'typeof(string)' not compatible with type 't1 where t1 = {- absolutely_no_scalar_has_this_method: (t1) -> (a...) -}' because the former is missing field 'absolutely_no_scalar_has_this_method')"; - CHECK_EQ(expected3, toString(result.errors[2])); - } -} - TEST_CASE_FIXTURE(Fixture, "a_free_shape_can_turn_into_a_scalar_if_it_is_compatible") { // CLI-115087 The new solver cannot infer that a table-like type is actually string @@ -3806,44 +3555,6 @@ TEST_CASE_FIXTURE(Fixture, "a_free_shape_can_turn_into_a_scalar_if_it_is_compati CHECK_EQ("(string) -> string", toString(requireType("f"))); } -TEST_CASE_FIXTURE(Fixture, "a_free_shape_cannot_turn_into_a_scalar_if_it_is_not_compatible") -{ - ExactTableFlags exactTableFlags; - CheckResult result = check(R"( - local function f(s): string - local foo = s:absolutely_no_scalar_has_this_method() - return s - end - )"); - - - if (!FFlag::DebugLuauForceOldSolver) - { - LUAU_REQUIRE_ERROR_COUNT(3, result); - - CHECK(toString(result.errors[0]) == "Parameter 's' has been reduced to never. This function is not callable with any possible value."); - CHECK( - toString(result.errors[1]) == "Parameter 's' is required to be a subtype of '{ read absolutely_no_scalar_has_this_method: (never) -> " - "(unknown, ...unknown), ... }' here." - ); - CHECK(toString(result.errors[2]) == "Parameter 's' is required to be a subtype of 'string' here."); - CHECK_EQ("(never) -> string", toString(requireType("f"))); - } - else - { - LUAU_REQUIRE_ERROR_COUNT(1, result); - - const std::string expected = - R"(Expected this to be 'string', but got 't1 where t1 = {+ absolutely_no_scalar_has_this_method: (t1) -> (T, U...) +}' -caused by: - The given type's metatable does not satisfy the requirements. -Table type 'typeof(string)' not compatible with type 't1 where t1 = {+ absolutely_no_scalar_has_this_method: (t1) -> (T, U...) +}' because the former is missing field 'absolutely_no_scalar_has_this_method')"; - CHECK_EQ(expected, toString(result.errors[0])); - - CHECK_EQ("(t1) -> string where t1 = {+ absolutely_no_scalar_has_this_method: (t1) -> (T, U...) +}", toString(requireType("f"))); - } -} - TEST_CASE_FIXTURE(BuiltinsFixture, "a_free_shape_can_turn_into_a_scalar_directly") { CheckResult result = check(R"( @@ -3920,39 +3631,6 @@ TEST_CASE_FIXTURE(Fixture, "invariant_table_properties_means_instantiating_table } } -TEST_CASE_FIXTURE(BuiltinsFixture, "generic_table_instantiation_potential_regression") -{ - ExactTableFlags exactTableFlags; - CheckResult result = check(R"( ---!strict - -function f(x) - x.p = 5 - return x -end -local g : ({ p : number, q : string }) -> ({ p : number, r : boolean }) = f - )"); - - LUAU_REQUIRE_ERROR_COUNT(1, result); - - if (!FFlag::DebugLuauForceOldSolver) - { - const TypeMismatch* error = get(result.errors[0]); - REQUIRE_MESSAGE(error, "Expected TypeMismatch but got " << result.errors[0]); - - CHECK("({ p: number, q: string }) -> { p: number, r: boolean }" == toString(error->wantedType)); - CHECK("({ p: number, ... }) -> { p: number, ... }" == toString(error->givenType)); - } - else - { - const MissingProperties* error = get(result.errors[0]); - REQUIRE_MESSAGE(error != nullptr, "Expected MissingProperties but got " << result.errors[0]); - - REQUIRE(error->properties.size() == 1); - CHECK_EQ("r", error->properties[0]); - } -} - TEST_CASE_FIXTURE(BuiltinsFixture, "setmetatable_has_a_side_effect") { if (FFlag::DebugLuauForceOldSolver) @@ -4314,29 +3992,6 @@ TEST_CASE_FIXTURE(Fixture, "cli_84607_missing_prop_in_array_or_dict") } } -TEST_CASE_FIXTURE(Fixture, "simple_method_definition") -{ - ExactTableFlags exactTableFlags; - CheckResult result = check(R"( - local T = {} - - function T:m() - return 5 - end - - return T - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - - if (!FFlag::DebugLuauForceOldSolver) - CHECK_EQ("{ m: (unknown) -> number }", toString(getMainModule()->returnType, ToStringOptions{true})); - else - CHECK_EQ( - "{ m: (T) -> number, ... }", toString(getMainModule()->returnType, ToStringOptions{true}) - ); // FIXME: Sus. Is it ok to shake up the old solver like this? -} - TEST_CASE_FIXTURE(Fixture, "identify_all_problematic_table_fields") { ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; @@ -4417,22 +4072,6 @@ TEST_CASE_FIXTURE(Fixture, "read_and_write_only_indexers_are_unsupported") CHECK(Location{{2, 18}, {2, 23}} == result.errors[1].location); } -TEST_CASE_FIXTURE(Fixture, "infer_write_property") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; - - CheckResult result = check(R"( - function f(t) - t.y = 1 - end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - - CHECK("({ y: number, ... }) -> ()" == toString(requireType("f"))); -} - TEST_CASE_FIXTURE(Fixture, "new_solver_supports_read_write_properties") { ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; @@ -4877,28 +4516,6 @@ TEST_CASE_FIXTURE(Fixture, "intersection_of_read_only_and_read_write_indexer_all CHECK("string" == toString(tm->givenType)); } -TEST_CASE_FIXTURE(Fixture, "table_writes_introduce_write_properties") -{ - ExactTableFlags exactTableFlags; - if (FFlag::DebugLuauForceOldSolver) - return; - - CheckResult result = check(R"( - function oc(player, speaker) - local head = speaker.Character:FindFirstChild('Head') - speaker.Character = player[1].Character - end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - - CHECK( - "({{ read Character: t1, ... }, ...}, { Character: t1, ... }) -> () " - "where " - "t1 = { read FindFirstChild: (t1, string) -> (T, ...unknown), ... }" == toString(requireType("oc")) - ); -} - TEST_CASE_FIXTURE(BuiltinsFixture, "tables_can_have_both_metatables_and_indexers") { CheckResult result = check(R"( @@ -4920,8 +4537,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "tables_can_have_both_metatables_and_indexers TEST_CASE_FIXTURE(Fixture, "refined_thing_can_be_an_array") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( function foo(x, y) if x then @@ -4957,8 +4572,6 @@ TEST_CASE_FIXTURE(Fixture, "parameter_was_set_an_indexer_and_bounded_by_string") TEST_CASE_FIXTURE(Fixture, "parameter_was_set_an_indexer_and_bounded_by_another_parameter") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -5043,8 +4656,6 @@ TEST_CASE_FIXTURE(Fixture, "mymovie_read_write_tables_bug_2") TEST_CASE_FIXTURE(BuiltinsFixture, "instantiated_metatable_frozen_table_clone_mutation") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - fileResolver.source["game/worker"] = R"( type WorkerImpl = { destroy: (self: Worker) -> boolean @@ -5307,8 +4918,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "indexing_branching_table2") TEST_CASE_FIXTURE(BuiltinsFixture, "length_of_array_is_number") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local function TestFunc(ranges: {number}): number if true then @@ -5324,8 +4933,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "length_of_array_is_number") TEST_CASE_FIXTURE(BuiltinsFixture, "subtyping_with_a_metatable_table_path") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -5357,8 +4964,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "subtyping_with_a_metatable_table_path") TEST_CASE_FIXTURE(BuiltinsFixture, "metatable_union_type") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; // This will have one (legitimate) error but previously would crash. @@ -5813,29 +5418,6 @@ TEST_CASE_FIXTURE(Fixture, "bigger_nested_table_causes_big_type_error") CHECK_EQ(result.errors[0].location, Location{{21, 20}, {24, 21}}); } -TEST_CASE_FIXTURE(Fixture, "unsafe_bidirectional_mutation") -{ - ExactTableFlags exactTableFlags; - // It's kind of suspect that we allow multiple definitions of keys in - // a single table. - CheckResult result = check(R"( - type F = { - _G: () -> (), - ... - } - function _() - return - end - local function h(f: F) end - h({ - _G = {}, - _G = _, - }) - )"); - - LUAU_REQUIRE_NO_ERRORS(result); -} - TEST_CASE_FIXTURE(BuiltinsFixture, "function_call_in_indexer_with_compound_assign") { // This has a bunch of errors, we really just need it to not crash / assert. @@ -5869,22 +5451,6 @@ TEST_CASE_FIXTURE(Fixture, "stop_refining_new_table_indices_for_non_primitive_ta LUAU_CHECK_ERROR(result, UnknownProperty); } -TEST_CASE_FIXTURE(Fixture, "fuzz_match_literal_type_crash_again") -{ - ExactTableFlags exactTableFlags; - CheckResult result = check(R"( - function f(_: { [string]: ({ [number]: unknown, ... } | { [string]: unknown, ... }), ... }) end - f( - { - _ = { 42 }, - _ = { x = "foo" }, - } - ) - )"); - - LUAU_REQUIRE_NO_ERRORS(result); -} - TEST_CASE_FIXTURE(Fixture, "type_mismatch_in_dict") { ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; @@ -6238,44 +5804,6 @@ TEST_CASE_FIXTURE(Fixture, "cli_119126_regression") } } -TEST_CASE_FIXTURE(BuiltinsFixture, "oss_1914_access_after_assignment_with_assertion") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; - - LUAU_REQUIRE_NO_ERRORS(check(R"( - --!strict - - type WallHolder = { - __type: "Model", - Wall: { - __type: "BasePart", - age: number, - ... - }, - ... - } - - local walls = { - { name = "Part1" }, - { name = "Part2" }, - { name = "Wall" }, - } - - local baseWall: WallHolder? - for _, wall in walls do - if wall.name == "Wall" then - baseWall = wall :: WallHolder - end - end - assert(baseWall, "Failed to get base wall when creating room props") - - local myAge = baseWall.Wall.age - )")); - - CHECK_EQ("number", toString(requireType("myAge"))); -} - TEST_CASE_FIXTURE(BuiltinsFixture, "cli_162179_avoid_exponential_blowup_in_normalization" * doctest::timeout(LUAU_TIMEOUT)) { const std::string source = format( @@ -6294,29 +5822,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "cli_162179_avoid_exponential_blowup_in_norma LUAU_REQUIRE_NO_ERRORS(check(source)); } -TEST_CASE_FIXTURE(Fixture, "free_types_with_sealed_table_upper_bounds_can_still_be_expanded") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag sff[] = { - {FFlag::DebugLuauForceOldSolver, false}, - }; - - CheckResult result = check(R"( - function bar(a: {x: number}) end - - function foo(a) - bar(a) - - -- Here, a : A where A = never <: A <: {x: number} - -- The upper bound of A is a sealed table, but we nevertheless want to extend it. - a.nope() - end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - CHECK("({ read nope: () -> (...unknown), ... } & { x: number }) -> ()" == toString(requireType("foo"))); -} - TEST_CASE_FIXTURE(Fixture, "mixed_tables_are_ok_when_explicit") { LUAU_REQUIRE_NO_ERRORS(check(R"( @@ -6341,8 +5846,6 @@ TEST_CASE_FIXTURE(Fixture, "mixed_tables_are_ok_for_any_key") TEST_CASE_FIXTURE(BuiltinsFixture, "oss_1935") { - // The exact-table path cannot yet relate a table literal to this intersection of open tables. - LegacyExactTableFlags legacyExactTableFlags; LUAU_REQUIRE_NO_ERRORS(check(R"( --!strict type Drawing = { @@ -6441,8 +5944,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "table_insert_any_and_true") TEST_CASE_FIXTURE(BuiltinsFixture, "table_insert_array_of_any") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( table.insert({} :: { any }, 42) )"); @@ -6467,48 +5968,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "bad_insert_type_mismatch") CHECK_EQ("string", toString(err->wantedType)); } - -TEST_CASE_FIXTURE(Fixture, "string_indexer_satisfies_read_only_property") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; - - // NOTE: Unclear if this should be allowed, but for the type solver's - // current state I think it's reasonable. - LUAU_REQUIRE_NO_ERRORS(check(R"( - local function foo(t: { [string]: number, ... }): { read X: number, ... } - return t - end - )")); -} - -TEST_CASE_FIXTURE(Fixture, "bidirectional_inference_works_through_intersections") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; - - LUAU_REQUIRE_NO_ERRORS(check(R"( - type x = {...} & ({ state: "1", ... } | { state: "2", ... }) - local x: x = { state = "2" } - )")); -} - -TEST_CASE_FIXTURE(Fixture, "bidirectional_inference_intersection_other_intersection_example") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; - - LUAU_REQUIRE_NO_ERRORS(check(R"( - type A = { foo: "a", ... } - type B = { bar: "b", ... } - type AB = A & B - local t: AB = { - foo = "a", - bar = "b", - } - )")); -} - TEST_CASE_FIXTURE(Fixture, "do_not_force_on_simple_bidirectional_inference") { ScopedFastFlag _{FFlag::DebugLuauAssertOnForcedConstraint, true}; @@ -6654,33 +6113,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "bidirectional_inference_variadic_type_pack") CHECK_EQ("string", toString(requireTypeAtPosition({3, 24}))); } -TEST_CASE_FIXTURE(Fixture, "table_with_intersection_containing_lambda") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag sffs[] = { - {FFlag::DebugLuauForceOldSolver, false}, - {FFlag::DebugLuauAssertOnForcedConstraint, true}, - }; - - LUAU_REQUIRE_NO_ERRORS(check(R"( - type Arg = { foo: string, ... } - - type TypeA = { foo: string, method: (arg: Arg) -> any, ... } - - type TypeB = TypeA & {...} - - local bar: TypeB = { - foo = "wow!", - method = function(arg) - local _ = arg - return nil - end, - } - )")); - - CHECK_EQ("{ foo: string, ... }", toString(requireTypeAtPosition({10, 28}), {/* exhaustive */ true})); -} - TEST_CASE_FIXTURE(BuiltinsFixture, "cli_174304_allow_getmetatable_error_and_table") { LUAU_REQUIRE_NO_ERRORS(check(R"( @@ -6826,7 +6258,6 @@ TEST_CASE_FIXTURE(Fixture, "table_access_indexer_fails_with_missing_key") TEST_CASE_FIXTURE(Fixture, "cli_184926_bidi_inference_pushes_into_lambda_return_type") { - LegacyExactTableFlags legacyExactTableFlags; ScopedFastFlag sffs[] = { {FFlag::DebugLuauForceOldSolver, false}, {FFlag::DebugLuauAssertOnForcedConstraint, true}, @@ -6841,28 +6272,6 @@ TEST_CASE_FIXTURE(Fixture, "cli_184926_bidi_inference_pushes_into_lambda_return_ )")); } -TEST_CASE_FIXTURE(BuiltinsFixture, "do_not_allow_laundering") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag sffs[] = { - {FFlag::DebugLuauForceOldSolver, false}, - }; - - CheckResult result = check(R"( - --!strict - local function foo(t: {...}): { x: nil, ... } - return t - end - - local t: { x: number, ... } = { x = 42 } - local laundered = foo(t) -- via width subtyping - laundered.x = nil - assert(type(t) == "number") - )"); - - LUAU_REQUIRE_ERROR_COUNT(1, result); -} - TEST_CASE_FIXTURE(Fixture, "table_inference_one_incorrect_member") { CheckResult result = check(R"( @@ -6953,30 +6362,6 @@ TEST_CASE_FIXTURE(Fixture, "basic_data_like_array_5") CHECK_EQ("{{ entry: number } | { entry: number? }}", toString(requireType("t"), {/* exhaustive */ true})); } -TEST_CASE_FIXTURE(Fixture, "large_data_like_array_can_simplify") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; - - std::stringstream stream; - stream << "local function get()" << '\n'; - stream << "\treturn { " << '\n'; - for (size_t i = 0; i < 200; i++) - { - stream << "\t\t{" << i << ", " << i + 1 << ", " << i + 2 << "}," << '\n'; - if ((i % 2) != 0u) - stream << "\t\t{ foo = " << i << " }," << '\n'; - else - stream << "\t\t{ bar = " << i << " }," << '\n'; - } - stream << "\t}" << '\n'; - stream << "end" << '\n'; - - CheckResult result = check(stream.str()); - LUAU_REQUIRE_NO_ERRORS(result); - CHECK_EQ("() -> {{ bar: number } | { foo: number } | {number}}", toString(requireType("get"))); -} - TEST_CASE_FIXTURE(Fixture, "cmpeq_any_with_nil_ok") { ScopedFastFlag sff[] = { @@ -7230,76 +6615,6 @@ TEST_CASE_FIXTURE(Fixture, "table_read_any_counts_as_read_nil") LUAU_REQUIRE_NO_ERRORS(result); } -TEST_CASE_FIXTURE(Fixture, "tables_routing_bidirectional_inference") -{ - ExactTableFlags exactTableFlags; - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - LUAU_REQUIRE_NO_ERRORS(check(R"( - export type ReceivedRequest = { - method: string, - path: string, - body: string, - query: { [string]: string, ... }, - headers: { [string]: string, ... }, - params: { [string]: string, ... }, - ... - } - - export type ServerResponse = string | { - status: number?, - body: string?, - headers: { [string]: string, ... }?, - ... - } - - export type RouteHandler = Handler | ServerResponse - - export type MethodRoutes = { - GET: RouteHandler?, - POST: RouteHandler?, - PUT: RouteHandler?, - DELETE: RouteHandler?, - PATCH: RouteHandler?, - HEAD: RouteHandler?, - OPTIONS: RouteHandler?, - ... - } - - export type RouteEntry = RouteHandler | MethodRoutes - - export type Routes = { [string]: RouteEntry, ... } - - export type Server = { - hostname: string, - port: number, - close: () -> (), - upgrade: (self: Server, req: ReceivedRequest) -> boolean, - ... - } - - export type Handler = (request: ReceivedRequest, server: Server) -> ServerResponse? - - local routes: Routes? = { - ["/health"] = "ok", - ["/json"] = { - status = 200, - headers = { ["Content-Type"] = "application/json" }, - body = '{"ok":true}', - }, - ["/hello"] = function(req) - local _ = req - return { status = 200, body = "hello" } - end, - } - - )")); - - // This check ensures bidirectional inference is kicking in for the - // function at the "/hello" route. - CHECK_EQ("ReceivedRequest", toString(requireTypeAtPosition({53, 28}))); -} - TEST_CASE_FIXTURE(Fixture, "bidirectional_union_non_singleton_discrimination") { DOES_NOT_PASS_OLD_SOLVER_GUARD(); @@ -7368,22 +6683,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "bidirectional_union_function_vs_primitive_pr CHECK_EQ("number", toString(requireTypeAtPosition({7, 34}))); } -TEST_CASE_FIXTURE(BuiltinsFixture, "indexer_and_subsequent_constraint") -{ - ExactTableFlags exactTableFlags; - ScopedFastFlag _{FFlag::DebugLuauForceOldSolver, false}; - - CheckResult result = check(R"( - local function getnumberandabs(tbl, key: string) - local x = tbl[key] - return math.abs(x) - end - )"); - LUAU_REQUIRE_NO_ERRORS(result); - - CHECK_EQ("({ [string]: number, ... }, string) -> number", toString(requireType("getnumberandabs"))); -} - TEST_CASE_FIXTURE(BuiltinsFixture, "intersection_of_indexers_1") { ScopedFastFlag sffs[] = { @@ -7579,251 +6878,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2597_constraint_forcing_bad_refinement") CHECK_EQ("(setmetatable<{ _t: T }, MyClass>) -> ()", toString(requireTypeAtPosition({16, 28}))); } -TEST_CASE_FIXTURE(BuiltinsFixture, "test_inferring_generalized_iteration_1") -{ - ExactTableFlags exactTableFlags; - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - ScopedFastFlag sffs[] = { - {FFlag::DebugLuauAssertOnForcedConstraint, true}, - {FFlag::LuauDecomposeIntersectionOfFreeType, true}, - {FFlag::LuauRefactorStringSemanticSubtyping, true}, - }; - - CheckResult result = check(R"( - local function setupRootMappingMove(rootMapping) - -- Prior, the new solver would eagerly generalize `rootMapping.RootToDescendantCountMap` - -- to unknown, which is clearly not correct. - for root, childCount in rootMapping.RootToDescendantCountMap do - string.len(root) - math.abs(childCount) - end - end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - - CHECK_EQ("({ read RootToDescendantCountMap: { [string?]: number, ... }, ... }) -> ()", toString(requireType("setupRootMappingMove"))); -} - -TEST_CASE_FIXTURE(BuiltinsFixture, "test_inferring_generalized_iteration_2") -{ - ExactTableFlags exactTableFlags; - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - ScopedFastFlag _{FFlag::DebugLuauAssertOnForcedConstraint, true}; - - CheckResult result = check(R"( - local function setupRootMappingMove(rootMapping) - for root, childCount in rootMapping.RootToDescendantCountMap do - end - end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - - CHECK_EQ("({ read RootToDescendantCountMap: { [T]: U, ... }, ... }) -> ()", toString(requireType("setupRootMappingMove"))); -} - -TEST_CASE_FIXTURE(Fixture, "exact_and_inexact_tables") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; - - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - CheckResult result = check(R"( - type A = {x: number, y: number} - type B = {x: number, ...} - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - - CHECK("{ x: number, y: number }" == toString(requireTypeAlias("A"), {true})); - CHECK("{ x: number, ... }" == toString(requireTypeAlias("B"), {true})); -} - -TEST_CASE_FIXTURE(Fixture, "exact_and_inexact_table_function_calls") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; - - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - SUBCASE("accepted") - { - LUAU_REQUIRE_NO_ERRORS(check(R"( - type ExactX = { x: number } - type ExactXY = { x: number, y: string } - type InexactX = { x: number, ... } - type InexactXY = { x: number, y: string, ... } - - local function acceptsExactX(_: ExactX) end - local function acceptsInexactX(_: InexactX) end - local function acceptsInexactXY(_: InexactXY) end - - local exactX: ExactX = { x = 1 } - local exactXY: ExactXY = { x = 1, y = "hello" } - local inexactX: InexactX = { x = 1 } - local inexactXY: InexactXY = { x = 1, y = "hello" } - - acceptsExactX(exactX) - - acceptsInexactX(exactX) - acceptsInexactX(exactXY) - acceptsInexactX(inexactX) - acceptsInexactX(inexactXY) - - acceptsInexactXY(exactXY) - acceptsInexactXY(inexactXY) - )")); - } - - SUBCASE("rejected") - { - CheckResult result = check(R"( - type ExactX = { x: number } - type ExactXY = { x: number, y: string } - type InexactX = { x: number, ... } - type InexactXY = { x: number, y: string, ... } - - local function acceptsExactX(_: ExactX) end - local function acceptsExactXY(_: ExactXY) end - - local exactX: ExactX = { x = 1 } - local exactXY: ExactXY = { x = 1, y = "hello" } - local inexactX: InexactX = { x = 1 } - local inexactXY: InexactXY = { x = 1, y = "hello" } - - acceptsExactX(exactXY) - acceptsExactXY(exactX) - acceptsExactX(inexactX) - acceptsExactXY(inexactXY) - )"); - - LUAU_REQUIRE_ERROR_COUNT(4, result); - } -} - -TEST_CASE_FIXTURE(Fixture, "exact_and_inexact_tables_in_higher_order_functions") -{ - ScopedFastFlag sff[] = { - {FFlag::DebugLuauParseExactTables, true}, - {FFlag::DebugLuauExactTableTypes, true}, - }; - - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - SUBCASE("accepted") - { - LUAU_REQUIRE_NO_ERRORS(check(R"( - type ExactX = { x: number } - type InexactX = { x: number, ... } - - local function acceptsExactConsumer(_: (ExactX) -> ()) end - local function acceptsInexactProducer(_: () -> InexactX) end - - local inexactConsumer: (InexactX) -> () = function(_) end - local exactProducer: () -> ExactX = function() - return { x = 1 } - end - - -- Function parameters are contravariant. - acceptsExactConsumer(inexactConsumer) - - -- Function returns are covariant. - acceptsInexactProducer(exactProducer) - )")); - } - - SUBCASE("rejected") - { - CheckResult result = check(R"( - type ExactX = { x: number } - type InexactX = { x: number, ... } - - local function acceptsInexactConsumer(_: (InexactX) -> ()) end - local function acceptsExactProducer(_: () -> ExactX) end - - local exactConsumer: (ExactX) -> () = function(_) end - local inexactProducer: () -> InexactX = function() - return { x = 1 } - end - - acceptsInexactConsumer(exactConsumer) - acceptsExactProducer(inexactProducer) - )"); - - LUAU_REQUIRE_ERROR_COUNT(2, result); - } -} - -TEST_CASE_FIXTURE(Fixture, "inferred_table_arguments_are_inexact") -{ - ExactTableFlags exactTableFlags; - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - CheckResult result = check(R"( - function take_5(t) - local a: number = t.x - return a - end - - )"); - - LUAU_CHECK_NO_ERRORS(result); - - CHECK("({ read x: number, ... }) -> number" == toString(requireType("take_5"))); -} - -TEST_CASE_FIXTURE(Fixture, "a_table_remains_inexact_if_it_is_both_an_argument_and_a_return") -{ - ExactTableFlags exactTableFlags; - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - CheckResult result = check(R"( - function f(t) - t.x = 1 - return t - end - )"); - - LUAU_REQUIRE_NO_ERRORS(result); - - CHECK("({ x: number, ... }) -> { x: number, ... }" == toString(requireType("f"))); -} - -TEST_CASE_FIXTURE(Fixture, "inferred_table_return_types_are_exact") -{ - ExactTableFlags exactTableFlags; - DOES_NOT_PASS_OLD_SOLVER_GUARD(); - - CheckResult result = check(R"( - function make_5() - return {x=5} - end - - function take_5(t: {x: number}) - return t - end - - local a = make_5() - local b = take_5(make_5()) - )"); - - LUAU_CHECK_NO_ERRORS(result); - - CHECK("() -> { x: number }" == toString(requireType("make_5"))); - CHECK("({ x: number }) -> { x: number }" == toString(requireType("take_5"))); - - CHECK("{ x: number }" == toString(requireType("a"))); - CHECK("{ x: number }" == toString(requireType("b"))); -} - TEST_CASE_FIXTURE(Fixture, "function_calls_preserve_potential_mutations_1") { ScopedFastFlag _{FFlag::LuauTraverseScopeToFunction, true}; @@ -7974,35 +7028,4 @@ TEST_CASE_FIXTURE(Fixture, "oss_2669_infer_read_only_indexers_5") CHECK_EQ("{boolean | number}", toString(requireType("z"), {true})); } -TEST_CASE_FIXTURE(BuiltinsFixture, "warn_on_extra_table_literal_properties") -{ - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; - - ExactTableFlags etf; - - CheckResult result = check(R"( - --!strict - - type Vec2 = {x: number, y: number} - - function hypot(p: Vec2) - return math.sqrt(p.x * p.x + p.y * p.y) - end - - hypot({x=3, y=4, z=5, w=0}) - )"); - - LUAU_REQUIRE_ERROR_COUNT(2, result); - - // We choose to report multiple warnings because we can put a precise - // location on each one. - const MissingProperties* mp0 = get(result.errors[0]); - REQUIRE(mp0); - CHECK(mp0->context == MissingProperties::Extra); - - const MissingProperties* mp1 = get(result.errors[1]); - REQUIRE(mp1); - CHECK(mp1->context == MissingProperties::Extra); -} - TEST_SUITE_END(); diff --git a/tests/TypeInfer.test.cpp b/tests/TypeInfer.test.cpp index 04dad61a8..255919361 100644 --- a/tests/TypeInfer.test.cpp +++ b/tests/TypeInfer.test.cpp @@ -33,6 +33,29 @@ using namespace Luau; TEST_SUITE_BEGIN("TypeInfer"); +TEST_CASE("retired_integer_type_guards") +{ + for (bool oldSolver : {false, true}) + { + ScopedFastFlag solver{FFlag::DebugLuauForceOldSolver, oldSolver}; + for (const char* guard : {"type", "typeof"}) + { + INFO(oldSolver); + INFO(guard); + Fixture fixture; + std::string source = "local function f(value: unknown)\nif " + std::string(guard) + R"((value) == "integer" then + local inside: string = value +end +local outside: string = value +end +)"; + CheckResult result = fixture.check(Mode::Strict, source); + CHECK(!result.errors.empty()); + CHECK_NOTHROW(fixture.getErrors(result)); + } + } +} + TEST_CASE_FIXTURE(Fixture, "tc_hello_world") { CheckResult result = check("local a = 7"); @@ -1155,8 +1178,6 @@ end TEST_CASE_FIXTURE(Fixture, "cli_50041_committing_txnlog_in_apollo_client_error") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_NEW_SOLVER_GUARD(); CheckResult result = check(R"( @@ -2514,8 +2535,6 @@ TEST_CASE_FIXTURE(Fixture, "if_then_else_bidirectional_inference") TEST_CASE_FIXTURE(Fixture, "if_then_else_two_errors") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; CheckResult results = check(R"( @@ -2818,8 +2837,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "iterate_over_table_with_optional_indexer_val TEST_CASE_FIXTURE(BuiltinsFixture, "iterate_over_local_table_with_optional_indexer_values") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - ScopedFastFlag sff{FFlag::DebugLuauForceOldSolver, false}; CheckResult result = check(R"( @@ -3045,8 +3062,6 @@ TEST_CASE_FIXTURE(Fixture, "generic_P_inference_with_optional_param_does_not_lea TEST_CASE_FIXTURE(Fixture, "generic_P_with_intersection_props_and_partial_table") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_OLD_SOLVER_GUARD(); // When a component's props are an intersection of table types with optional @@ -3073,8 +3088,6 @@ TEST_CASE_FIXTURE(Fixture, "generic_P_with_intersection_props_and_partial_table" TEST_CASE_FIXTURE(Fixture, "generic_P_widening_with_recursive_optional_field") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - DOES_NOT_PASS_OLD_SOLVER_GUARD(); // When a component has a recursive optional field (like React's children), @@ -3143,4 +3156,19 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "fuzzer_generic_binding_ice") )")); } +TEST_CASE_FIXTURE(BuiltinsFixture, "fuzzer_globals_in_type_functions_arent_defined") +{ + LUAU_REQUIRE_ERRORS(check(R"( + export type function t6(l0) + do end + end + type function t0(l0) + end + export type function t6() + function _() + end + end + )")); +} + TEST_SUITE_END(); diff --git a/tests/TypeInfer.tryUnify.test.cpp b/tests/TypeInfer.tryUnify.test.cpp index 4ed0a435c..8235188b2 100644 --- a/tests/TypeInfer.tryUnify.test.cpp +++ b/tests/TypeInfer.tryUnify.test.cpp @@ -277,8 +277,6 @@ TEST_CASE_FIXTURE(Fixture, "variadics_should_use_reversed_properly") TEST_CASE_FIXTURE(BuiltinsFixture, "cli_41095_concat_log_in_sealed_table_unification") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( --!strict diff --git a/tests/TypeInfer.unionTypes.test.cpp b/tests/TypeInfer.unionTypes.test.cpp index 8988f893f..7cf317e37 100644 --- a/tests/TypeInfer.unionTypes.test.cpp +++ b/tests/TypeInfer.unionTypes.test.cpp @@ -884,8 +884,6 @@ TEST_CASE_FIXTURE(Fixture, "union_of_functions_with_mismatching_result_variadics TEST_CASE_FIXTURE(Fixture, "less_greedy_unification_with_union_types") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - if (FFlag::DebugLuauForceOldSolver) return; @@ -1049,8 +1047,6 @@ TEST_CASE_FIXTURE(BuiltinsFixture, "bounds_propagate_into_free_union_bounds") TEST_CASE_FIXTURE(Fixture, "oss_2134") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( local function addIndex (op: ((value: A) -> B, array: {A}) -> {C}) return function (idxOp: (key: K, value: A) -> B, tbl: { [K]: A }) @@ -1081,13 +1077,12 @@ TEST_CASE_FIXTURE(Fixture, "oss_2134") local mapTest = addIndex(map) local mapResult = mapTest(mapWithIndex, myArr) - )"); LUAU_REQUIRE_NO_ERRORS(result); + )"); + LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(Fixture, "oss_2393") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - CheckResult result = check(R"( --!strict @@ -1103,7 +1098,8 @@ TEST_CASE_FIXTURE(Fixture, "oss_2393") end process(ex) - )"); LUAU_REQUIRE_NO_ERRORS(result); + )"); + LUAU_REQUIRE_NO_ERRORS(result); } TEST_CASE_FIXTURE(BuiltinsFixture, "oss_2025") diff --git a/tests/TypePath.test.cpp b/tests/TypePath.test.cpp index c59baaa16..b11215d5c 100644 --- a/tests/TypePath.test.cpp +++ b/tests/TypePath.test.cpp @@ -555,8 +555,6 @@ TEST_CASE_FIXTURE(TypePathFixture, "step_limit") TEST_CASE_FIXTURE(TypePathBuiltinsFixture, "complex_chains") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - SUBCASE("add_metamethod_return_type") { TYPESOLVE_CODE(R"( diff --git a/tests/TypeVar.test.cpp b/tests/TypeVar.test.cpp index c50caa374..ab3704e7c 100644 --- a/tests/TypeVar.test.cpp +++ b/tests/TypeVar.test.cpp @@ -183,8 +183,6 @@ TEST_CASE_FIXTURE(Fixture, "UnionTypeIterator_with_only_cyclic_union") */ TEST_CASE_FIXTURE(Fixture, "substitution_skip_failure") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - Type ftv11{FreeType{TypeLevel{}, getBuiltins()->neverType, getBuiltins()->unknownType}}; TypePackVar tp24{TypePack{{&ftv11}}}; diff --git a/tests/VisitType.test.cpp b/tests/VisitType.test.cpp index b8ea75cf9..406a9c641 100644 --- a/tests/VisitType.test.cpp +++ b/tests/VisitType.test.cpp @@ -143,8 +143,6 @@ TEST_CASE_FIXTURE(Fixture, "skip_over_tables") TEST_CASE_FIXTURE(Fixture, "detects_cycles") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - // Alas. parseType() can't be used to create a cyclic type. // F where // F = (T, number) -> number @@ -193,8 +191,6 @@ TEST_CASE_FIXTURE(Fixture, "can_be_configured_not_to_skip_bound_types") TEST_CASE_FIXTURE(Fixture, "visitOnce") { - DOES_NOT_PASS_WITH_EXACT_TABLES(); - // An acyclic type that has redundant interior structure. // ({x: number}, {x: number}) -> {x: number} diff --git a/tests/conformance/buffers.luau b/tests/conformance/buffers.luau index 8d552e53d..7c236ceaf 100644 --- a/tests/conformance/buffers.luau +++ b/tests/conformance/buffers.luau @@ -119,6 +119,74 @@ end simple_double_reinterpret() +local vector_size = if pcall(function() return vector.create(0, 0, 0).w end) then 4 else 3 + +local function vector_roundtrip() + local native_check = is_native_if_supported() + local b = buffer.create(64) + + buffer.writevectorf32x2(b, 0, vector.create(1.5, -2.25, 99)) + local v2 = buffer.readvectorf32x2(b, 0) + assert(v2.x == 1.5) + assert(v2.y == -2.25) + assert(v2.z == 0) -- unspecified components are zeroed + + buffer.writevectorf32x3(b, 8, vector.create(3, 4, 5)) + local v3 = buffer.readvectorf32x3(b, 8) + assert(v3.x == 3 and v3.y == 4 and v3.z == 5) + + -- vector writes are just contiguous little-endian f32s + assert(buffer.readf32(b, 8) == 3) + assert(buffer.readf32(b, 12) == 4) + assert(buffer.readf32(b, 16) == 5) + + buffer.writef32(b, 32, 7) + buffer.writef32(b, 36, 8) + assert(buffer.readvectorf32x2(b, 32) == vector.create(7, 8, 0)) + + assert(not native_check or is_native_if_supported()) +end + +local function vector_bounds() + local b = buffer.create(16) + + -- readvectorf32x3 needs 12 bytes; offset 5 overflows a 16-byte buffer + assert(ecall(function() buffer.readvectorf32x3(b, 5) end) == "buffer access out of bounds") + assert(ecall(function() buffer.writevectorf32x3(b, 5, vector.create(1, 2, 3)) end) == "buffer access out of bounds") + assert(ecall(function() buffer.readvectorf32x2(b, 9) end) == "buffer access out of bounds") + assert(ecall(function() buffer.readvectorf32x2(b, -1) end) == "buffer access out of bounds") +end + +local function vector_boundaries() + local native_check = is_native_if_supported() + + local b3 = buffer.create(12) + buffer.writevectorf32x3(b3, 0, vector.create(-1, -2, -3)) + assert(buffer.readvectorf32x3(b3, 0) == vector.create(-1, -2, -3)) + + local b2 = buffer.create(8) + buffer.writevectorf32x2(b2, 0, vector.create(10, 20, 0)) + assert(buffer.readvectorf32x2(b2, 0) == vector.create(10, 20, 0)) + + assert(not native_check or is_native_if_supported()) +end + +local function vector4() + if vector_size ~= 4 then + return + end + + local b = buffer.create(32) + buffer.writevectorf32x4(b, 0, vector.create(1, 2, 3, 4)) + local v4 = buffer.readvectorf32x4(b, 0) + assert(v4.x == 1 and v4.y == 2 and v4.z == 3 and v4.w == 4) +end + +vector_roundtrip() +vector_bounds() +vector_boundaries() +vector4() + local function simple_string_ops() local native_check = is_native_if_supported() local b = buffer.create(1024) diff --git a/tests/conformance/classes.luau b/tests/conformance/classes.luau index 23977ad38..e636b7892 100644 --- a/tests/conformance/classes.luau +++ b/tests/conformance/classes.luau @@ -1593,4 +1593,222 @@ expectpass("subclasses can access private static methods of their base class", f BaseOther.create(DerivedOther) -- class access to private static `_secret` is allowed for derived class end) +expectpass("nested shadowed private field", function() + local class Outer + private _x + + public function __init(self, x) + self._x = x + end + + public function classer(self) + local class Inner + private _x + + public function __init(self, x) + self._x = x + end + + public function get(self) + return self._x + end + end + return Inner + end + + public function classerCaller(self) + local innerInst = self:classer()(67) + assert(innerInst:get() == 67) + end + + public function get(self) + return self._x + end + end + + local outer = Outer(6) + local innerClass = outer:classer() + local innerInst = innerClass(7) + assert(outer:get() == 6) + assert(innerInst:get() == 7) + outer:classerCaller() +end) + +expectpass("private methods capture upvalues normally", function() + local cat = "Mi" + local class Concat + private _cat + + public function __init(self, cat) + self._cat = cat + end + + public function concat(self) + return cat .. self._cat + end + end + local concat = Concat("pha") + assert(concat:concat() == "Mipha") +end) + +expectpass("private field access on instance upvalue", function() + local class Outer + private _x + + public function __init(self, x) + self._x = x + end + + public function classMaker(inst) + local class Inner + private _y + + public function __init(self, y) + self._y = y + end + + public function doStuff(self) + return self._y + inst._x + end + end + local innerInst = Inner(6) + return innerInst:doStuff() + end + end + + local outerInst = Outer(7) + assert(outerInst:classMaker() == 13) +end) + +expectpass("class extends same named class", function() + local open class Foo + public function add(self, x, y) + return x + y + end + end + + local class Foo extends Foo + public z + end + + local foo = Foo { z = 3 } + + assert(foo.z == 3) + assert(foo:add(1, 2) == 3) +end) + +expectpass("class assigned to the local it extends", function() + local open class Base + public function add(self, x, y) + return x + y + end + end + + local Foo = Base + + class Foo extends Foo + public z + end + + local foo = Foo { z = 3 } + + assert(Foo ~= Base) + assert(foo.z == 3) + assert(foo:add(1, 2) == 3) +end) + +-- `g` gets inlined into `Inner.n` (at -O2, or at any level since this module has @native functions); `_x` must still refer to `Outer`'s private field +expectpass("inlined private field access keeps its defining class", function() + local class Outer + private _x + + public function __init(self) + self._x = 1 + end + + public function m(self) + local function g(o) + return o._x + end + + local class Inner + private _x + + public function __init(self) + self._x = 2 + end + + public function n(self, o) + return g(o) + end + end + + return Inner():n(self) + end + end + + assert(Outer():m() == 1) +end) + +expectpass("sibling class method private field access keeps its defining class", function() + local class Outer + private _x + + public function __init(self) + self._x = 1 + end + + public function m(self) + local class Sibling + private _x + + public function __init(self) + self._x = 2 + end + + public function g(o) + return o._x + end + end + + local class Inner + private _x + + public function __init(self) + self._x = 3 + end + + public function n(self, o) + return Sibling.g(o) + end + end + + return Inner():n(Sibling()) + end + end + + assert(Outer():m() == 2) +end) + +expectpass("private access in extends clause", function() + local Mipha = 3 + local open class Kass + private _cl + + public function __init(self, cl) + self._cl = cl + end + + public function f(self) + class Mipha extends self._cl + end + end + end + + local k = Kass(Kass) + k:f() + + assert(typeof(Mipha) == "class") +end) + return 'OK' diff --git a/tests/conformance/integers.luau b/tests/conformance/integers.luau deleted file mode 100644 index bee907387..000000000 --- a/tests/conformance/integers.luau +++ /dev/null @@ -1,705 +0,0 @@ --- This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details -print("testing integers") - -local function noinline(x: integer): integer local s, r = pcall(function(y) return y end, x) return r end -local function noinlinenum(x: number): number local s, r = pcall(function(y) return y end, x) return r end - --- Integers have the 'integer' type -assert(type(123i)=="integer") - --- Integer constants -assert(123i == integer.add(100i,23i)) -assert(0xf_fi == 255i) -assert(1_000i == 1000i) -assert(0xABABi == 43947i) -assert(0b1000_1000i == 136i) -assert(0xABCDEFi == 11259375i) -assert(0xfedcbai == 16702650i) -assert(-0x8000000000000000i == 0x8000000000000000i) -assert(-0xFFFFFFFFFFFFFFFFi == 1i) - --- Built-in equality operator -assert(76i==76i) -assert(76i~=32i) -assert(rawequal(76i, 76i)) -assert(not rawequal(76i, 32i)) -assert(not rawequal(76i, 76)) - --- integer.create -assert(typeof(integer.create(4711)) == "integer") - -assert(integer.create(4711) == 4711i) -assert(integer.create(-3) == -3i) -assert(integer.create(1e18) == 1000000000000000000i) -assert(integer.create(-1e18) == -1000000000000000000i) - -assert(integer.create(noinlinenum(4711)) == 4711i) -assert(integer.create(noinlinenum(-3)) == -3i) -assert(integer.create(noinlinenum(1e18)) == 1000000000000000000i) -assert(integer.create(noinlinenum(-1e18)) == -1000000000000000000i) - --- isolate tests which take a VM exit in native code -function testCreateVmExit(x) - local y = integer.create(x) - return y -end - -assert(testCreateVmExit(2.5) == nil) -assert(testCreateVmExit(1e30) == nil) -assert(testCreateVmExit(0/0) == nil) -assert(testCreateVmExit(math.huge) == nil) -assert(testCreateVmExit(-math.huge) == nil) -assert(testCreateVmExit(1.0000000005) == nil) -assert(testCreateVmExit(0.9999999995) == nil) - --- integer.fromstring -assert(integer.fromstring("30") == 30i) -assert(integer.fromstring("-4711") == -4711i) -assert(integer.fromstring("2.5") == nil) -assert(integer.fromstring("blah") == nil) -assert(integer.fromstring(" 47 ") == 47i) -assert(integer.fromstring("+2") == 2i) -assert(integer.fromstring("-2") == -2i) -assert(integer.fromstring("0x123") == 291i) -assert(integer.fromstring("0X200") == 512i) -assert(integer.fromstring("0xFFFFFFFFFF") == 0xFFFFFFFFFFi) -assert(integer.fromstring("0x100000000") == 4294967296i) -assert(integer.fromstring("0x1000000000000") == 0x1000000000000i) -assert(integer.fromstring("0x20000000000001") == 0x20000000000001i) -assert(integer.fromstring("123", 4) == 27i) -assert(integer.fromstring("ZZZ", 36) == 46655i) -assert(not pcall(function() integer.fromstring("123", 1) end)) -assert(not pcall(function() integer.fromstring("123", 37) end)) -assert(not pcall(function() integer.fromstring("123", 0) end)) - --- integer.fromstring with values beyond 32-bit range -assert(integer.fromstring("4294967296") == 4294967296i) -assert(integer.fromstring("1000000000000") == 1000000000000i) -assert(integer.fromstring("-8589934592") == -8589934592i) -assert(integer.fromstring("9223372036854775807") == 0x7FFFFFFFFFFFFFFFi) -assert(integer.fromstring("-9223372036854775808") == integer.sub(-0x7FFFFFFFFFFFFFFFi, 1i)) -assert(integer.fromstring("FFFFFFFF", 16) == 4294967295i) -assert(integer.fromstring("100000000", 16) == 4294967296i) -assert(integer.fromstring("0x8000000000000000") == 0x8000000000000000i) -assert(integer.fromstring("0x7FFFFFFFFFFFFFFF") == 0x7FFFFFFFFFFFFFFFi) -assert(integer.fromstring("0xFFFFFFFFFFFFFFFF") == 0xFFFFFFFFFFFFFFFFi) -assert(integer.fromstring("-1", 2) == -1i) -assert(integer.fromstring("-11", 2) == -3i) -assert(integer.fromstring("-1", 10) == -1i) -assert(integer.fromstring("-11", 10) == -11i) -assert(integer.fromstring("-0x1", 10) == -1i) -assert(integer.fromstring("-0x11", 10) == -17i) -assert(integer.fromstring("-1", 16) == -1i) -assert(integer.fromstring("-11", 16) == -17i) -assert(integer.fromstring("8000000000000000", 16) == 0x8000000000000000i) -assert(integer.fromstring("7FFFFFFFFFFFFFFF", 16) == 0x7FFFFFFFFFFFFFFFi) -assert(integer.fromstring("FFFFFFFFFFFFFFFF", 16) == 0xFFFFFFFFFFFFFFFFi) - --- integer.neg -local x = integer.create(3411) -assert(integer.neg(x) == -3411i) -assert(integer.neg(integer.minsigned) == integer.minsigned) -assert(integer.neg(integer.maxsigned) == integer.add(integer.minsigned, 1i)) - -assert(integer.neg(noinline(3411i)) == -3411i) -assert(integer.neg(noinline(integer.minsigned)) == integer.minsigned) - --- integer.add -local x = integer.create(456) -local y = integer.create(123) -assert(integer.add(x, y) == 579i) -assert(integer.add(integer.maxsigned, 1i) == integer.minsigned) -assert(integer.add(integer.maxsigned, integer.maxsigned) == -2i) - -assert(integer.add(noinline(456i), 123i) == 579i) -assert(integer.add(noinline(integer.maxsigned), 1i) == integer.minsigned) - --- integer.sub -local x = integer.create(999) -local y = integer.create(777) -assert(integer.sub(x, y) == 222i) -assert(integer.sub(integer.minsigned, 1i) == integer.maxsigned) -assert(integer.sub(integer.minsigned, integer.maxsigned) == 1i) - -assert(integer.sub(noinline(999i), 777i) == 222i) -assert(integer.sub(noinline(integer.minsigned), 1i) == integer.maxsigned) - --- integer.mul -local x = integer.create(7) -local y = integer.create(9) -assert(integer.mul(x, y) == 63i) -assert(integer.mul(integer.maxsigned, 2i) == -2i) -assert(integer.mul(integer.minsigned, -1i) == integer.minsigned) - -assert(integer.mul(noinline(7i), 9i) == 63i) -assert(integer.mul(noinline(integer.maxsigned), 2i) == -2i) - --- integer.div (truncated division) -assert(integer.div(32i, 8i) == 4i) -assert(integer.div(-7i, 3i) == -2i) - -assert(integer.div(noinline(32i), 8i) == 4i) -assert(integer.div(noinline(-7i), 3i) == -2i) - -local success,errmsg = pcall(function() integer.div(5i,0i) end) -assert(not success) -assert(string.find(errmsg,"division by zero")) -local success,errmsg = pcall(function() integer.div(integer.minsigned,-1i) end) -assert(not success) -assert(string.find(errmsg,"integer overflow")) - --- integer.idiv (floored signed division) -assert(integer.idiv(32i, 7i) == 4i) -assert(integer.idiv(-7i, 3i) == -3i) - -assert(integer.idiv(noinline(32i), 7i) == 4i) -assert(integer.idiv(noinline(-7i), 3i) == -3i) - --- floored division must round toward -inf even when |a| < |b| (truncated quotient is 0) -assert(integer.idiv( -1i, 3i) == -1i) -assert(integer.idiv( 1i,-3i) == -1i) -assert(integer.idiv( -1i,-3i) == 0i) -assert(integer.idiv( 1i, 3i) == 0i) -assert(integer.idiv(noinline(-1i), 3i) == -1i) -assert(integer.idiv(noinline( 1i),-3i) == -1i) - --- consistency with mod: a == (a//b)*b + (a%b) for all sign combinations -for _, a in {-7i,-1i,1i,7i} do - for _, b in {-3i,-2i,2i,3i} do - assert(integer.add(integer.mul(integer.idiv(a,b), b), integer.mod(a,b)) == a) - end -end - -local success,errmsg = pcall(function() integer.idiv(5i,0i) end) -assert(not success) -assert(string.find(errmsg,"division by zero")) -local success,errmsg = pcall(function() integer.idiv(integer.minsigned,-1i) end) -assert(not success) -assert(string.find(errmsg,"integer overflow")) - --- integer.udiv (unsigned division) -assert(integer.udiv(32i, 7i) == 4i) - -assert(integer.udiv(noinline(32i), 7i) == 4i) - -local success,errmsg = pcall(function() integer.udiv(5i,0i) end) -assert(not success) -assert(string.find(errmsg,"division by zero")) - --- integer.urem (unsigned remainder) -assert(integer.urem(34i, 7i) == 6i) - -assert(integer.urem(noinline(34i), 7i) == 6i) - -local success,errmsg = pcall(function() integer.urem(5i,0i) end) -assert(not success) -assert(string.find(errmsg,"division by zero")) - --- integer.mod (floored modulus) -assert(integer.mod(7i, 3i) == 1i) -assert(integer.mod(-7i, 3i) == 2i) -assert(integer.mod(7i, -3i) == -2i) -assert(integer.mod(-7i, -3i) == -1i) - -assert(integer.mod(noinline(7i), 3i) == 1i) -assert(integer.mod(noinline(-7i), 3i) == 2i) -assert(integer.mod(noinline(7i), -3i) == -2i) -assert(integer.mod(noinline(-7i), -3i) == -1i) - -local success,errmsg = pcall(function() integer.mod(5i,0i) end) -assert(not success) -assert(string.find(errmsg,"division by zero")) -assert(integer.mod(integer.minsigned,-1i) == 0i) - --- integer.rem -assert(integer.rem(35i, 8i) == 3i) -assert(integer.rem(-7i, 3i) == -1i) - -assert(integer.rem(noinline(35i), 8i) == 3i) -assert(integer.rem(noinline(-7i), 3i) == -1i) - -local success,errmsg = pcall(function() integer.rem(5i,0i) end) -assert(not success) -assert(string.find(errmsg,"division by zero")) -assert(integer.rem(integer.minsigned,-1i) == 0i) - --- integer.min and integer.max -local x = integer.create(99) -local y = integer.create(5) -assert(integer.min(x, y) == 5i) -assert(integer.min(y, x) == 5i) -assert(integer.max(x, y) == 99i) -assert(integer.max(y, x) == 99i) -assert(integer.min(17i, 12i, 48i, 13i, -2i) == -2i) -assert(integer.max(17i, 12i, 48i, 13i, 94i) == 94i) - -assert(integer.min(noinline(99i), 5i) == 5i) -assert(integer.max(noinline(99i), 5i) == 99i) -assert(integer.min(noinline(17i), 12i, 48i, 13i, -2i) == -2i) -assert(integer.max(noinline(17i), 12i, 48i, 13i, 94i) == 94i) - --- integer.clamp -local mi = integer.create(6) -local mx = integer.create(18) -local a1 = integer.create(3) -local a2 = integer.create(11) -local a3 = integer.create(47) -assert(integer.clamp(a1, mi, mx) == 6i) -assert(integer.clamp(a2, mi, mx) == 11i) -assert(integer.clamp(a3, mi, mx) == 18i) - -assert(integer.clamp(noinline(3i), 6i, 18i) == 6i) -assert(integer.clamp(noinline(11i), 6i, 18i) == 11i) -assert(integer.clamp(noinline(47i), 6i, 18i) == 18i) - -local success,errmsg = pcall(function() integer.clamp(10i, 20i, 5i) end) -assert(not success) -assert(string.find(errmsg, "max must be greater than or equal to min")) - --- Bitwise operations -assert(integer.band(14i, 7i) == 6i) -assert(integer.bor(48i, 24i) == 56i) -assert(integer.bnot(10000i) == -10001i) -assert(integer.bxor(7i, 10i) == 13i) -assert(integer.band(65535i, 255i, 192i) == 192i) -assert(integer.bor(1i, 2i, 4i, 8i, 13i) == 15i) -assert(integer.bxor(255i, 252i, 1i, 12i) == 14i) -assert(integer.btest(65535i, 255i, 192i)) -assert(integer.band() == -1i) -assert(integer.bor() == 0i) -assert(integer.bxor() == 0i) -assert(integer.btest() == true) -assert(integer.band(42i) == 42i) -assert(integer.bor(42i) == 42i) -assert(integer.bxor(42i) == 42i) -assert(integer.btest(42i) == true) -assert(integer.btest(0i) == false) - -assert(integer.band(noinline(14i), 7i) == 6i) -assert(integer.bor(noinline(48i), 24i) == 56i) -assert(integer.bnot(noinline(10000i)) == -10001i) -assert(integer.bxor(noinline(7i), 10i) == 13i) -assert(integer.band(noinline(65535i), 255i, 192i) == 192i) -assert(integer.bor(noinline(1i), 2i, 4i, 8i, 13i) == 15i) -assert(integer.bxor(noinline(255i), 252i, 1i, 12i) == 14i) -assert(integer.btest(noinline(65535i), 255i, 192i)) -assert(integer.btest(noinline(42i)) == true) -assert(integer.btest(noinline(0i)) == false) - --- Comparisons -assert(integer.lt(3i,4i)) -assert(not integer.lt(4i,4i)) -assert(not integer.lt(5i,4i)) -assert(integer.le(3i,4i)) -assert(integer.le(4i,4i)) -assert(not integer.le(5i,4i)) -assert(integer.ult(5i,-3i)) -assert(not integer.ult(-5i,6i)) -assert(integer.ule(5i,-3i)) -assert(integer.ule(-3i,-3i)) -assert(integer.gt(4i,3i)) -assert(not integer.gt(4i,4i)) -assert(not integer.gt(4i,5i)) -assert(integer.ge(4i,3i)) -assert(integer.ge(4i,4i)) -assert(not integer.ge(4i,5i)) -assert(integer.ugt(-3i,5i)) -assert(not integer.ugt(6i,-5i)) -assert(integer.uge(-3i,5i)) -assert(integer.uge(-3i,-3i)) - -assert(integer.lt(noinline(3i), 4i)) -assert(not integer.lt(noinline(4i), 4i)) -assert(not integer.lt(noinline(5i), 4i)) -assert(integer.le(noinline(3i), 4i)) -assert(integer.le(noinline(4i), 4i)) -assert(not integer.le(noinline(5i), 4i)) -assert(integer.ult(noinline(5i), -3i)) -assert(not integer.ult(noinline(-5i), 6i)) -assert(integer.ule(noinline(5i), -3i)) -assert(integer.ule(noinline(-3i), -3i)) -assert(integer.gt(noinline(4i), 3i)) -assert(not integer.gt(noinline(4i), 4i)) -assert(not integer.gt(noinline(4i), 5i)) -assert(integer.ge(noinline(4i), 3i)) -assert(integer.ge(noinline(4i), 4i)) -assert(not integer.ge(noinline(4i), 5i)) -assert(integer.ugt(noinline(-3i), 5i)) -assert(not integer.ugt(noinline(6i), -5i)) -assert(integer.uge(noinline(-3i), 5i)) -assert(integer.uge(noinline(-3i), -3i)) - --- Shifts -assert(integer.lshift(1i, 8i) == 256i) -assert(integer.lshift(256i, -7i) == 2i) -assert(integer.lshift(1i, 64i) == 0i) -assert(integer.lshift(256i, -64i) == 0i) -assert(integer.rshift(512i, 3i) == 64i) -assert(integer.rshift(512i, -2i) == 2048i) -assert(integer.rshift(256i, 64i) == 0i) -assert(integer.rshift(256i, -64i) == 0i) -assert(integer.arshift(512i, 3i) == 64i) -assert(integer.arshift(512i, -2i) == 2048i) -assert(integer.arshift(256i, 64i) == 0i) -assert(integer.arshift(-256i, 64i) == -1i) -assert(integer.arshift(256i, -64i) == 0i) -assert(integer.arshift(-256i, -64i) == 0i) -assert(integer.arshift(-1i, -3i) == -8i) -assert(integer.arshift(integer.minsigned, -1i) == 0i) - -assert(integer.lshift(noinline(1i), 8i) == 256i) -assert(integer.lshift(noinline(256i), -7i) == 2i) -assert(integer.lshift(noinline(1i), 64i) == 0i) -assert(integer.rshift(noinline(512i), 3i) == 64i) -assert(integer.rshift(noinline(512i), -2i) == 2048i) -assert(integer.rshift(noinline(256i), 64i) == 0i) -assert(integer.arshift(noinline(512i), 3i) == 64i) -assert(integer.arshift(noinline(-256i), 64i) == -1i) -assert(integer.arshift(noinline(-1i), -3i) == -8i) - -assert(integer.lshift(noinline(12345i), -256i) == 0i) -assert(integer.rshift(noinline(12345i), -256i) == 0i) -assert(integer.lshift(noinline(12345i), 256i) == 0i) -assert(integer.rshift(noinline(12345i), 256i) == 0i) -assert(integer.lshift(noinline(12345i), 0x8000000000000000i) == 0i) -assert(integer.rshift(noinline(12345i), 0x8000000000000000i) == 0i) -assert(integer.arshift(noinline(12345i), -256i) == 0i) -assert(integer.arshift(noinline(-12345i), 256i) == -1i) - --- Rotations -assert(integer.lrotate(0x6003000000000000i, 4i) == 0x0030000000000006i) -assert(integer.lrotate(0x1000200000000000i, 69i) == 0x0004000000000002i) -assert(integer.lrotate(0x842842842842i, -1i) == 0x421421421421i) -assert(integer.lrotate(1i, 0i) == 1i) -assert(integer.lrotate(1i, 64i) == 1i) -assert(integer.lrotate(1i, -64i) == 1i) -assert(integer.lrotate(1i, integer.minsigned) == 1i) -assert(integer.rrotate(0x8420i, 5i) == 0x421i) -assert(integer.rrotate(0x10i, -3i) == 0x80i) -assert(integer.rrotate(0x10i, -67i) == 0x80i) -assert(integer.rrotate(0x7FFFFFFFFFFFFFFFi, 63i) == -2i) -assert(integer.rrotate(1i, 0i) == 1i) -assert(integer.rrotate(1i, 64i) == 1i) -assert(integer.rrotate(1i, -64i) == 1i) -assert(integer.rrotate(1i, integer.minsigned) == 1i) - -assert(integer.lrotate(noinline(0x6003000000000000i), 4i) == 0x0030000000000006i) -assert(integer.lrotate(noinline(0x1000200000000000i), 69i) == 0x0004000000000002i) -assert(integer.lrotate(noinline(0x842842842842i), -1i) == 0x421421421421i) -assert(integer.lrotate(noinline(1i), 0i) == 1i) -assert(integer.lrotate(noinline(1i), 64i) == 1i) -assert(integer.rrotate(noinline(0x8420i), 5i) == 0x421i) -assert(integer.rrotate(noinline(0x10i), -3i) == 0x80i) -assert(integer.rrotate(noinline(0x7FFFFFFFFFFFFFFFi), noinline(63i)) == -2i) -assert(integer.rrotate(noinline(1i), 0i) == 1i) -assert(integer.rrotate(noinline(1i), 64i) == 1i) - --- extract -assert(integer.extract(0xBADBEEFi, 0i, 16i) == 0xBEEFi) -assert(integer.extract(0xBADBEEFi, 16i, 12i) == 0xBADi) -assert(integer.extract(0xBADBEEFi, 3i) == 1i) -assert(integer.extract(0xBADBEEFi, 4i) == 0i) -assert(integer.extract(0xBADBEEFi, 0i, 64i) == 0xBADBEEFi) -assert(integer.extract(0xFFFFFFFFFFFFFFFFi, 0i, 64i) == 0xFFFFFFFFFFFFFFFFi) - -assert(integer.extract(noinline(0xBADBEEFi), 0i, 16i) == 0xBEEFi) -assert(integer.extract(noinline(0xBADBEEFi), 16i, 12i) == 0xBADi) -assert(integer.extract(noinline(0xBADBEEFi), 3i) == 1i) -assert(integer.extract(noinline(0xBADBEEFi), 4i) == 0i) -assert(integer.extract(noinline(0xFFFFFFFFFFFFFFFFi), 0i, 64i) == 0xFFFFFFFFFFFFFFFFi) - -local success,errmsg = pcall(function() integer.extract(0xBADBEEFi, -1i) end) -assert(not success) -assert(string.find(errmsg, "field cannot be negative")) -local success,errmsg = pcall(function() integer.extract(0xBADBEEFi, 4i, -2i) end) -assert(not success) -assert(string.find(errmsg, "width must be positive")) -local success,errmsg = pcall(function() integer.extract(0xBADBEEFi, 33i, 33i) end) -assert(not success) -assert(string.find(errmsg, "trying to access non%-existent bits")) -local success,errmsg = pcall(function() integer.extract(1i, 64i, 1i) end) -assert(not success) -assert(string.find(errmsg, "trying to access non%-existent bits")) -local success,errmsg = pcall(function() integer.extract(1i, integer.maxsigned, 1i) end) -assert(not success) -local success,errmsg = pcall(function() integer.extract(-1i, 1i, integer.maxsigned) end) -assert(not success) -assert(string.find(errmsg, "trying to access non%-existent bits")) - --- replace -assert(integer.replace(0xBADBEEFi, 0x500Di, 16i, 16i) == 0x500DBEEFi) -assert(integer.replace(0xFFFFFFFFFFFFi, 0xEEEi, 28i, 12i) == 0xFFEEEFFFFFFFi) -assert(integer.replace(0xFFFFFFFFFFFFi, 0i, 6i) == 0xFFFFFFFFFFBFi) -assert(integer.replace(0xBADBEEFi, 0x123i, 0i, 64i) == 0x123i) - -assert(integer.replace(noinline(0xBADBEEFi), 0x500Di, 16i, 16i) == 0x500DBEEFi) -assert(integer.replace(noinline(0xFFFFFFFFFFFFi), 0xEEEi, 28i, 12i) == 0xFFEEEFFFFFFFi) -assert(integer.replace(noinline(0xFFFFFFFFFFFFi), 0i, 6i) == 0xFFFFFFFFFFBFi) -assert(integer.replace(noinline(0xBADBEEFi), 0x123i, 0i, 64i) == 0x123i) - -local success,errmsg = pcall(function() integer.replace(1i, 2i, -3i) end) -assert(not success) -assert(string.find(errmsg, "field cannot be negative")) -local success,errmsg = pcall(function() integer.replace(1i, 2i, 3i, -4i) end) -assert(not success) -assert(string.find(errmsg, "width must be positive")) -local success,errmsg = pcall(function() integer.replace(1i, 2i, 40i, 50i) end) -assert(not success) -assert(string.find(errmsg, "trying to access non%-existent bits")) -local success,errmsg = pcall(function() integer.replace(1i, 2i, 64i, 1i) end) -assert(not success) -assert(string.find(errmsg, "trying to access non%-existent bits")) -local success,errmsg = pcall(function() integer.replace(1i, 2i, integer.maxsigned, 1i) end) -assert(not success) -local success,errmsg = pcall(function() integer.replace(0i, -1i, 63i, integer.maxsigned) end) -assert(not success) -assert(string.find(errmsg, "trying to access non%-existent bits")) - --- btest -assert(not integer.btest(0xAAAAi, 0x5555i)) -assert(integer.btest(12i, 4i)) -assert(integer.btest(0x100000000i, 0x100000000i)) -assert(integer.btest(0x8000000000000000i, 0x8000000000000000i)) - -assert(not integer.btest(noinline(0xAAAAi), 0x5555i)) -assert(integer.btest(noinline(12i), 4i)) -assert(integer.btest(noinline(0x100000000i), 0x100000000i)) -assert(integer.btest(noinline(0x8000000000000000i), 0x8000000000000000i)) - --- countrz/countlz -assert(integer.countrz(1i) == 0i) -assert(integer.countrz(8i) == 3i) -assert(integer.countrz(0x200000i) == 21i) -assert(integer.countrz(0i) == 64i) -assert(integer.countlz(1i) == 63i) -assert(integer.countlz(8i) == 60i) -assert(integer.countlz(0x200000i) == 42i) -assert(integer.countlz(0i) == 64i) - -assert(integer.countrz(noinline(1i)) == 0i) -assert(integer.countrz(noinline(8i)) == 3i) -assert(integer.countrz(noinline(0x200000i)) == 21i) -assert(integer.countrz(noinline(0i)) == 64i) -assert(integer.countlz(noinline(1i)) == 63i) -assert(integer.countlz(noinline(8i)) == 60i) -assert(integer.countlz(noinline(0x200000i)) == 42i) -assert(integer.countlz(noinline(0i)) == 64i) - --- bswap -assert(integer.bswap(0x1122334455667748i) == 0x4877665544332211i) -assert(integer.bswap(0x0BADBEEFC001D00Di) == 0x0DD001C0EFBEAD0Bi) - -assert(integer.bswap(noinline(0x1122334455667748i)) == 0x4877665544332211i) -assert(integer.bswap(noinline(0x0BADBEEFC001D00Di)) == 0x0DD001C0EFBEAD0Bi) - --- roundtrip regression test -local function roundtrip(i: integer) - local d = integer.tonumber(i) - return integer.create(d) -end - -assert(roundtrip(9007199254740993i) == 9007199254740992i) -assert(roundtrip(4711i) == 4711i) - --- table indexing and hashes -local x = {} -x[3i] = 5 -assert(x[3i] == 5) - --- buffers (should eventually move to buffers.luau) - -local function simple_integer_ops() - local b = buffer.create(16) - - buffer.writeinteger(b, 0, 0x123456789ABCDEF0i) - buffer.writeinteger(b, 8, 0x1233211233211233i) - - assert(buffer.readi8(b, 0) == -16) - assert(buffer.readi8(b, 1) == -34) - assert(buffer.readi8(b, 2) == -68) - assert(buffer.readi8(b, 3) == -102) - assert(buffer.readi8(b, 4) == 120) - assert(buffer.readi8(b, 5) == 86) - assert(buffer.readi8(b, 6) == 52) - assert(buffer.readi8(b, 7) == 18) - assert(buffer.readi8(b, 8) == 0x33) - assert(buffer.readi8(b, 9) == 0x12) - assert(buffer.readi8(b, 10) == 0x21) - assert(buffer.readi8(b, 11) == 0x33) - assert(buffer.readi8(b, 12) == 0x12) - assert(buffer.readi8(b, 13) == 0x21) - assert(buffer.readi8(b, 14) == 0x33) - assert(buffer.readi8(b, 15) == 0x12) - - assert(buffer.readinteger(b, 0) == 0x123456789ABCDEF0i) - assert(buffer.readinteger(b, 8) == 0x1233211233211233i) - - assert(is_native_if_supported()) -end - -simple_integer_ops() - -local function buffer_integer_boundary_values() - local b = buffer.create(64) - - -- zero - buffer.writeinteger(b, 0, 0i) - assert(buffer.readinteger(b, 0) == 0i) - - -- max signed int64 - buffer.writeinteger(b, 8, 0x7FFFFFFFFFFFFFFFi) - assert(buffer.readinteger(b, 8) == integer.maxsigned) - - -- min signed int64 - buffer.writeinteger(b, 16, integer.minsigned) - assert(buffer.readinteger(b, 16) == integer.minsigned) - - -- -1 (all bits set) - buffer.writeinteger(b, 24, -1i) - assert(buffer.readinteger(b, 24) == -1i) - assert(buffer.readu8(b, 24) == 0xFF) - assert(buffer.readu8(b, 31) == 0xFF) - - -- +1 - buffer.writeinteger(b, 32, 1i) - assert(buffer.readinteger(b, 32) == 1i) - - -- non-zero offset: verify 8-byte read/write at offset 40 - buffer.writeinteger(b, 40, 0xDEADBEEFCAFEBABEi) - assert(buffer.readinteger(b, 40) == 0xDEADBEEFCAFEBABEi) - - -- verify adjacent writes don't clobber each other - buffer.writeinteger(b, 0, 0x1111111111111111i) - buffer.writeinteger(b, 8, 0x2222222222222222i) - assert(buffer.readinteger(b, 0) == 0x1111111111111111i) - assert(buffer.readinteger(b, 8) == 0x2222222222222222i) - - assert(is_native_if_supported()) -end - -buffer_integer_boundary_values() - --- stress tests for CHECK_BUFFER_LEN with constant offsets at exact boundaries --- these exercise the native codegen constant-offset lowering path and range merging - -local function buffer_integer_exact_boundary() - -- exact-fit single access: offset + 8 == buffer.len - local b8 = buffer.create(8) - buffer.writeinteger(b8, 0, 0xAABBCCDDEEFF0011i) - assert(buffer.readinteger(b8, 0) == 0xAABBCCDDEEFF0011i) - - -- exact-fit at end of buffer: 8 + 8 == 16 - local b16 = buffer.create(16) - buffer.writeinteger(b16, 0, 0x1111111111111111i) - buffer.writeinteger(b16, 8, 0x2222222222222222i) - assert(buffer.readinteger(b16, 0) == 0x1111111111111111i) - assert(buffer.readinteger(b16, 8) == 0x2222222222222222i) - - -- three adjacent writes filling buffer exactly: 0, 8, 16 in 24-byte buffer - -- triggers range merging across all three constant offsets - local b24 = buffer.create(24) - buffer.writeinteger(b24, 0, 0xAAAAAAAAAAAAAAAAi) - buffer.writeinteger(b24, 8, 0xBBBBBBBBBBBBBBBBi) - buffer.writeinteger(b24, 16, 0xCCCCCCCCCCCCCCCCi) - assert(buffer.readinteger(b24, 0) == 0xAAAAAAAAAAAAAAAAi) - assert(buffer.readinteger(b24, 8) == 0xBBBBBBBBBBBBBBBBi) - assert(buffer.readinteger(b24, 16) == 0xCCCCCCCCCCCCCCCCi) - - -- interleaved offsets to provoke negative minOffset in range merging - -- write at 16 first, then read at 0, then write at 24 - local b32 = buffer.create(32) - buffer.writeinteger(b32, 16, 0x3333333333333333i) - buffer.writeinteger(b32, 0, 0x4444444444444444i) - buffer.writeinteger(b32, 24, 0x5555555555555555i) - buffer.writeinteger(b32, 8, 0x6666666666666666i) - assert(buffer.readinteger(b32, 0) == 0x4444444444444444i) - assert(buffer.readinteger(b32, 8) == 0x6666666666666666i) - assert(buffer.readinteger(b32, 16) == 0x3333333333333333i) - assert(buffer.readinteger(b32, 24) == 0x5555555555555555i) - - -- five adjacent writes filling 40-byte buffer exactly - local b40 = buffer.create(40) - buffer.writeinteger(b40, 0, 1i) - buffer.writeinteger(b40, 8, 2i) - buffer.writeinteger(b40, 16, 3i) - buffer.writeinteger(b40, 24, 4i) - buffer.writeinteger(b40, 32, 5i) - assert(buffer.readinteger(b40, 0) == 1i) - assert(buffer.readinteger(b40, 8) == 2i) - assert(buffer.readinteger(b40, 16) == 3i) - assert(buffer.readinteger(b40, 24) == 4i) - assert(buffer.readinteger(b40, 32) == 5i) - - assert(is_native_if_supported()) -end - -buffer_integer_exact_boundary() - -local function buffer_integer_variable_offset(start: number) - local b = buffer.create(64) - - buffer.writeinteger(b, start, 0x0123456789ABCDEFi) - buffer.writeinteger(b, start + 8, 0xFEDCBA9876543210i) - buffer.writeinteger(b, start + 16, -1i) - - assert(buffer.readinteger(b, start) == 0x0123456789ABCDEFi) - assert(buffer.readinteger(b, start + 8) == 0xFEDCBA9876543210i) - assert(buffer.readinteger(b, start + 16) == -1i) - - -- buffer load-store propagation - local a = buffer.readinteger(b, start) - local c = buffer.readinteger(b, start) - assert(a == c) - - assert(buffer.readu8(b, start) == 0xEF) - assert(buffer.readu8(b, start + 7) == 0x01) - assert(buffer.readu8(b, start + 8) == 0x10) - assert(buffer.readu8(b, start + 15) == 0xFE) - - assert(is_native_if_supported()) -end - -buffer_integer_variable_offset(0) -buffer_integer_variable_offset(8) -buffer_integer_variable_offset(16) -buffer_integer_variable_offset(24) - --- constants - -assert(integer.minsigned == integer.lshift(1i, 63i)) -assert(integer.maxsigned == 0x7FFFFFFFFFFFFFFFi) - --- strings (should eventually move to strings.luau) - -assert(string.format("%d", 3i) == "3") -assert(string.format("%d", -4i) == "-4") -assert(string.format("%d", 0x8000000000000000i) == "-9223372036854775808") -assert(string.format("%i", 42i) == "42") -assert(string.format("%i", -42i) == "-42") -assert(string.format("%x", 0x8000000000000000i) == "8000000000000000") -assert(string.format("%x", 0xFFFFFFFFFFFFFFFFi) == "ffffffffffffffff") -assert(string.format("%X", 0xABCDi) == "ABCD") -assert(string.format("%o", 8i) == "10") -assert(string.format("%o", 0xFFFFFFFFFFFFFFFFi) == "1777777777777777777777") -assert(string.format("%u", 0xFFFFFFFFFFFFFFFFi) == "18446744073709551615") -assert(string.format("%u", -1i) == "18446744073709551615") -assert(string.format("%u", 0x8000000000000000i) == "9223372036854775808") -assert(string.format("%*", 42i) == "42") -assert(string.format("%*", -1i) == "-1") -assert(string.format("%*", 0x8000000000000000i) == "-9223372036854775808") - --- Built-in tostring -assert(tostring(-48i) == "-48") -assert(tostring(0x8000000000000000i) == "-9223372036854775808") -assert(tostring(0xFFFFFFFFFFFFFFFFi) == "-1") - --- Unary minus can only be used on a literal directly -local intval = 123i -local ok, err = pcall(function() return -intval end) -assert(not ok) -local ok2, err2 = pcall(function() return -(123i) end) -assert(not ok2) - -assert(is_native_if_supported()) - -return('OK') diff --git a/tests/conformance/integers_regspill.luau b/tests/conformance/integers_regspill.luau deleted file mode 100644 index 6811dbde0..000000000 --- a/tests/conformance/integers_regspill.luau +++ /dev/null @@ -1,305 +0,0 @@ --- This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details -print("testing native integer register spills") - -local function test_many_locals( - p0: integer, p1: integer, p2: integer, p3: integer -): integer - assert(is_native()) - - -- create many live values from various operations - local a: integer = integer.add(p0, p1) - local b: integer = integer.sub(p0, p1) - local c: integer = integer.bxor(p2, p3) - local d: integer = integer.band(p0, p3) - local e: integer = integer.bor(p1, p2) - local f: integer = integer.add(p2, p3) - local g: integer = integer.bxor(a, b) - local h: integer = integer.band(c, d) - local i: integer = integer.bor(e, f) - local j: integer = integer.add(a, c) - local k: integer = integer.sub(b, d) - local l: integer = integer.bxor(e, g) - local m: integer = integer.band(f, h) - local n: integer = integer.bor(g, i) - local o: integer = integer.add(h, j) - local p: integer = integer.sub(i, k) - local q: integer = integer.bxor(j, l) - local r: integer = integer.band(k, m) - local s: integer = integer.bor(l, n) - local t: integer = integer.add(m, o) - - -- invalidates restore locations for old values. - a = integer.add(a, t) - b = integer.bxor(b, s) - c = integer.band(c, r) - d = integer.bor(d, q) - e = integer.sub(e, p) - f = integer.add(f, o) - g = integer.bxor(g, n) - h = integer.band(h, m) - i = integer.bor(i, l) - j = integer.add(j, k) - - k = integer.bxor(a, integer.add(b, c)) - l = integer.band(d, integer.sub(e, f)) - m = integer.bor(g, integer.bxor(h, i)) - n = integer.add(j, integer.band(k, l)) - o = integer.sub(m, integer.bor(n, a)) - - return integer.bxor( - integer.bxor(integer.bxor(a, b), integer.bxor(c, d)), - integer.bxor(integer.bxor(e, f), integer.bxor(g, h)), - integer.bxor(integer.bxor(i, j), integer.bxor(k, l)), - integer.bxor(integer.bxor(m, n), integer.bxor(o, p)), - integer.bxor(integer.bxor(q, r), integer.bxor(s, t)) - ) -end - -local function test_division_pressure( - p0: integer, p1: integer, p2: integer, p3: integer -): integer - assert(is_native()) - - local a: integer = integer.add(p0, p1) - local b: integer = integer.sub(p0, p1) - local c: integer = integer.bxor(p2, p3) - local d: integer = integer.band(p0, p3) - local e: integer = integer.bor(p1, p2) - local f: integer = integer.add(p2, p3) - local g: integer = integer.bxor(a, b) - local h: integer = integer.add(c, d) - local i: integer = integer.bor(e, f) - local j: integer = integer.bxor(g, h) - local k: integer = integer.add(i, a) - local l: integer = integer.bor(b, c) - - -- each div clobbers RAX+RDX, requiring spills of other live INT64 values - local d1: integer = integer.div(a, p1) - local d2: integer = integer.div(b, p2) - local d3: integer = integer.rem(c, p3) - local d4: integer = integer.mod(f, p0) - local d5: integer = integer.udiv(integer.bor(e, 1i), p1) - - return integer.bxor( - integer.bxor(integer.bxor(a, b), integer.bxor(c, d)), - integer.bxor(integer.bxor(e, f), integer.bxor(g, h)), - integer.bxor(integer.bxor(i, j), integer.bxor(k, l)), - integer.bxor(integer.bxor(d1, d2), integer.bxor(d3, d4)), - d5 - ) -end - --- shifts require RCX -local function test_shift_pressure( - p0: integer, p1: integer, p2: integer, p3: integer -): integer - assert(is_native()) - - local a: integer = integer.add(p0, p1) - local b: integer = integer.sub(p0, p1) - local c: integer = integer.bxor(p2, p3) - local d: integer = integer.band(p0, p3) - local e: integer = integer.bor(p1, p2) - local f: integer = integer.add(p2, p3) - local g: integer = integer.bxor(a, b) - local h: integer = integer.add(c, d) - local i: integer = integer.bor(e, f) - local j: integer = integer.bxor(g, h) - local k: integer = integer.add(i, a) - local l: integer = integer.bor(b, c) - - local sh1: integer = integer.band(p0, 7i) -- 0..7 - local sh2: integer = integer.band(p1, 15i) -- 0..15 - local sh3: integer = integer.band(p2, 31i) -- 0..31 - local sh4: integer = integer.band(p3, 63i) -- 0..63 - - local s1: integer = integer.lshift(a, sh1) - local s2: integer = integer.rshift(b, sh2) - local s3: integer = integer.arshift(c, sh3) - local s4: integer = integer.lrotate(d, sh4) - local s5: integer = integer.rrotate(e, sh1) - local s6: integer = integer.lshift(f, sh2) - local s7: integer = integer.rshift(g, sh3) - local s8: integer = integer.arshift(h, sh4) - - return integer.bxor( - integer.bxor(integer.bxor(a, b), integer.bxor(c, d)), - integer.bxor(integer.bxor(e, f), integer.bxor(g, h)), - integer.bxor(integer.bxor(i, j), integer.bxor(k, l)), - integer.bxor(integer.bxor(s1, s2), integer.bxor(s3, s4)), - integer.bxor(integer.bxor(s5, s6), integer.bxor(s7, s8)) - ) -end - --- regalloc may need to spill registers while in the loop -local function test_loop_spill( - p0: integer, p1: integer, p2: integer, p3: integer, - iters: number -): integer - assert(is_native()) - - local a: integer = integer.add(p0, p1) - local b: integer = integer.sub(p0, p1) - local c: integer = integer.bxor(p2, p3) - local d: integer = integer.band(p0, p3) - local e: integer = integer.bor(p1, p2) - local f: integer = integer.add(p2, p3) - local g: integer = integer.bxor(a, b) - local h: integer = integer.add(c, d) - local i: integer = integer.bor(e, f) - local j: integer = integer.bxor(g, h) - local k: integer = integer.add(i, a) - local l: integer = integer.bor(b, c) - - for iter = 1, iters do - -- create register pressure within the loop - a = integer.add(a, integer.bxor(b, c)) - b = integer.sub(b, integer.band(d, e)) - c = integer.bxor(c, integer.bor(f, g)) - d = integer.add(d, integer.bxor(h, i)) - e = integer.sub(e, integer.band(j, k)) - f = integer.bor(f, integer.add(l, a)) - g = integer.band(g, integer.sub(b, c)) - h = integer.bxor(h, integer.add(d, e)) - i = integer.bor(i, integer.sub(f, g)) - j = integer.add(j, integer.bxor(h, i)) - k = integer.sub(k, integer.band(j, a)) - l = integer.bxor(l, integer.bor(k, b)) - end - - return integer.bxor( - integer.bxor(integer.bxor(a, b), integer.bxor(c, d)), - integer.bxor(integer.bxor(e, f), integer.bxor(g, h)), - integer.bxor(integer.bxor(i, j), integer.bxor(k, l)) - ) -end - -local function test_mixed_pressure( - p0: integer, p1: integer, p2: integer, p3: integer -): integer - assert(is_native()) - - local a: integer = integer.add(p0, p1) - local b: integer = integer.sub(p0, p1) - local c: integer = integer.bxor(p2, p3) - local d: integer = integer.band(p0, p3) - local e: integer = integer.bor(p1, p2) - local f: integer = integer.add(p2, p3) - local g: integer = integer.bxor(a, b) - local h: integer = integer.add(c, d) - local i: integer = integer.bor(e, f) - local j: integer = integer.bxor(g, h) - local k: integer = integer.add(i, a) - local l: integer = integer.bor(b, c) - - local m: integer = integer.bxor(a, b, c, d, e) - local n: integer = integer.band(f, g, h, i, j) - local o: integer = integer.bor(k, l, a, b, c) - - local d1: integer = integer.div(integer.add(a, 100i), p1) - local d2: integer = integer.idiv(integer.add(b, 200i), p2) - - local sh: integer = integer.band(p0, 7i) - local s1: integer = integer.lshift(m, sh) - local s2: integer = integer.rshift(n, sh) - - local x: integer = integer.add(d1, s1) - local y: integer = integer.bxor(d2, s2) - local z: integer = integer.band(x, y) - - return integer.bxor( - integer.bxor(integer.bxor(a, b), integer.bxor(c, d)), - integer.bxor(integer.bxor(e, f), integer.bxor(g, h)), - integer.bxor(integer.bxor(i, j), integer.bxor(k, l)), - integer.bxor(integer.bxor(m, n), integer.bxor(o, d1)), - integer.bxor(integer.bxor(d2, s1), integer.bxor(s2, z)) - ) -end - --- 30 live locals must require register spilling -local function test_extreme_pressure( - p0: integer, p1: integer, p2: integer, p3: integer -): integer - assert(is_native()) - - local a: integer = integer.add(p0, p1) - local b: integer = integer.sub(p0, p1) - local c: integer = integer.mul(p2, 3i) - local d: integer = integer.bxor(p0, p3) - local e: integer = integer.band(p1, p2) - local f: integer = integer.bor(p2, p3) - local g: integer = integer.bnot(p0) - local h: integer = integer.lshift(p1, 3i) - local i: integer = integer.rshift(p2, 2i) - local j: integer = integer.arshift(p3, 1i) - local k: integer = integer.lrotate(p0, 7i) - local l: integer = integer.rrotate(p1, 5i) - local m: integer = integer.add(a, b) - local n: integer = integer.bxor(c, d) - local o: integer = integer.band(e, f) - - local p: integer = integer.bor(g, h) - local q: integer = integer.add(i, j) - local r: integer = integer.sub(k, l) - local s: integer = integer.bxor(m, n) - local t: integer = integer.band(o, p) - local u: integer = integer.bor(q, r) - local v: integer = integer.add(s, t) - local w: integer = integer.sub(u, a) - local x: integer = integer.bxor(v, b) - local y: integer = integer.band(w, c) - local z: integer = integer.bor(x, d) - local a2: integer = integer.add(y, e) - local b2: integer = integer.sub(z, f) - local c2: integer = integer.bxor(a2, g) - local d2: integer = integer.band(b2, h) - - local div1: integer = integer.div(integer.bor(a, 100i), p1) - local div2: integer = integer.div(integer.bor(m, 200i), p2) - - local sh: integer = integer.band(p0, 3i) - local sh1: integer = integer.lshift(n, sh) - local sh2: integer = integer.rshift(o, sh) - - local t1: integer = integer.bxor(integer.bxor(a, b), integer.bxor(c, d)) - local t2: integer = integer.bxor(integer.bxor(e, f), integer.bxor(g, h)) - local t3: integer = integer.bxor(integer.bxor(i, j), integer.bxor(k, l)) - local t4: integer = integer.bxor(integer.bxor(m, n), integer.bxor(o, p)) - local t5: integer = integer.bxor(integer.bxor(q, r), integer.bxor(s, t)) - local t6: integer = integer.bxor(integer.bxor(u, v), integer.bxor(w, x)) - local t7: integer = integer.bxor(integer.bxor(y, z), integer.bxor(a2, b2)) - local t8: integer = integer.bxor(integer.bxor(c2, d2), integer.bxor(div1, div2)) - local t9: integer = integer.bxor(sh1, sh2) - return integer.bxor( - integer.bxor(t1, t2, t3, t4, t5), - integer.bxor(t6, t7, t8, t9) - ) -end - --- values with significant upper 32 bits to detect truncation for incorrect spill widths -local V0: integer = 0x1234567890ABCDEFi -local V1: integer = 0xFEDCBA0987654321i -local V2: integer = 0x0011223344556677i -local V3: integer = 0x8899AABBCCDDEEFFi -local V4: integer = 0xA5A5A5A5_5A5A5A5Ai - -local r1 = test_many_locals(V0, V1, V2, V3) -local r2 = test_division_pressure(V0, V1, V2, V3) -local r3 = test_shift_pressure(V0, V1, V2, V3) -local r4 = test_loop_spill(V0, V1, V2, V3, 2) -local r5 = test_mixed_pressure(V0, V1, V2, V3) -local r6 = test_extreme_pressure(V0, V1, V2, V3) - -assert(type(r1) == "integer") -assert(type(r2) == "integer") -assert(type(r3) == "integer") -assert(type(r4) == "integer") -assert(type(r5) == "integer") -assert(type(r6) == "integer") - -assert(test_many_locals(V0, V1, V2, V3) == r1) -assert(test_division_pressure(V0, V1, V2, V3) == r2) -assert(test_shift_pressure(V0, V1, V2, V3) == r3) -assert(test_loop_spill(V0, V1, V2, V3, 2) == r4) - -return "OK" diff --git a/tests/conformance/lazyload.luau b/tests/conformance/lazyload.luau new file mode 100644 index 000000000..07ed12480 --- /dev/null +++ b/tests/conformance/lazyload.luau @@ -0,0 +1,62 @@ +-- This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details +-- Loaded with luau_loadlazy: every function below main is built on its first call +print "testing lazy loading" + +-- a function can call itself through a metamethod on its first call +local reentered = 0 +local function readLib() + return _G.Lib.value +end +_G.Lib = setmetatable({}, { __index = function(t, k) + reentered += 1 + if reentered == 1 then + return readLib() + end + return 42 +end }) +assert(readLib() == 42) +assert(reentered == 2) + +-- debug info of functions that never ran +local function neverCalled(a, b, ...) end +assert(debug.info(neverCalled, "s") == "lazyload.luau") +assert(debug.info(neverCalled, "l") == 21) +assert(debug.info(neverCalled, "n") == "neverCalled") +assert(select(2, debug.info(neverCalled, "a")) == true) + +-- errors raised by lazily built functions report their own lines +local function fails() + error("boom") +end +local ok, err = pcall(fails) +assert(not ok and err == "lazyload.luau:29: boom") + +-- first calls from C, coroutines, metamethods and varargs +assert(pcall(function() return 1 end)) +assert(coroutine.wrap(function(a) return a + 1 end)(1) == 2) +local mt = setmetatable({}, { __add = function(a, b) return 7 end }) +assert(mt + 1 == 7) +local function count(...) return select("#", ...) end +assert(count(1, nil, 3) == 3) + +-- recursion into a function on its first call +local function fib(n) return if n < 2 then n else fib(n - 1) + fib(n - 2) end +assert(fib(15) == 610) + +-- closures built later keep working after a collection +local makers = {} +for i = 1, 100 do + makers[i] = function() return function() return i end end +end +collectgarbage() +for i = 1, 100 do + assert(makers[i]()() == i) +end + +-- with optimizations, a closure without upvalues is a constant of its parent as well as its child +local function makeDoubler() + return function(x) return x * 2 end +end +assert(makeDoubler()(21) == 42) + +return 'OK' diff --git a/tests/conformance/native.luau b/tests/conformance/native.luau index 66ee88636..3f36236f7 100644 --- a/tests/conformance/native.luau +++ b/tests/conformance/native.luau @@ -480,6 +480,26 @@ end valueTrackingIssue1() +function registerOverflow1(...) + return + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0, + math.max(...) +end + +assert(table.pack(registerOverflow1(1, 2))[254] == 2) + local function vec3compsum(a: vector) return a.X + a.Y + a.Z end diff --git a/tests/conformance/native_integer_spills.luau b/tests/conformance/native_integer_spills.luau deleted file mode 100644 index 7467085b1..000000000 --- a/tests/conformance/native_integer_spills.luau +++ /dev/null @@ -1,521 +0,0 @@ --- This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details -print("testing that native code does not hit spill limit in complex integer code") - -local function bit32_add(lhs, rhs) - return bit32.bor(lhs + rhs, 0) -end - -local mem - -local FUNC_LIST = {} -local GLOBAL_LIST = {} - -GLOBAL_LIST[0] = { value = 4666048 } - -FUNC_LIST[1] = function(loc_0, loc_1) - local loc_2 = 0 - local loc_3 = 0 - local loc_4 = 0 - local loc_5 = 0 - local loc_6 = 0 - local loc_7 = 0 - local loc_8 = 0 - local loc_9 = 0 - local loc_10 = 0 - local loc_11 = 0 - local loc_12 = 0 - local loc_13 = 0 - local loc_14 = 0 - local loc_15 = 0 - local loc_16 = 0 - local loc_17 = 0 - local loc_18 = 0 - local loc_19 = 0 - local loc_20 = 0 - local loc_21 = 0 - local loc_22 = 0 - local loc_23 = 0 - local loc_24 = 0 - local loc_25 = 0 - local loc_26 = 0 - local loc_27 = 0 - local loc_28 = 0 - local loc_29 = 0 - local loc_30 = 0 - local loc_31 = 0 - local loc_32 = 0 - local loc_33 = 0 - local loc_34 = 0 - local loc_35 = 0 - local loc_36 = 0 - local loc_37 = 0 - local loc_38 = 0 - local loc_39 = 0 - local loc_40 = 0 - local loc_41 = 0 - local loc_42 = 0 - local loc_43 = 0 - local loc_44 = 0 - local loc_45 = 0 - local loc_46 = 0 - local loc_47 = 0 - local loc_48 = 0 - local loc_49 = 0 - local loc_50 = 0 - local loc_51 = 0 - local loc_52 = 0 - local loc_53 = 0 - local loc_54 = 0 - local loc_55 = 0 - local loc_56 = 0 - local loc_57 = 0 - local loc_58 = 0 - local loc_59 = 0 - local loc_60 = 0 - local loc_61 = 0 - local loc_62 = 0 - local loc_63 = 0 - local loc_64 = 0 - local loc_65 = 0 - local loc_66 = 0 - local loc_67 = 0 - local loc_68 = 0 - local loc_69 = 0 - local loc_70 = 0 - local loc_71 = 0 - local loc_72 = 0 - local loc_73 = 0 - local loc_74 = 0 - local loc_75 = 0 - local loc_76 = 0 - local loc_77 = 0 - local loc_78 = 0 - local reg_7 - local reg_8 - local reg_12 - local reg_13 - local reg_14 - local reg_15 - local reg_16 - while true do - loc_2 = bit32.bor(GLOBAL_LIST[0].value - 64, 0) - loc_3 = buffer.readu32(mem, loc_0 + 16) - loc_4 = buffer.readu32(mem, loc_0 + 12) - loc_5 = buffer.readu32(mem, loc_0 + 8) - loc_6 = buffer.readu32(mem, loc_0 + 4) - loc_7 = buffer.readu32(mem, loc_0) - loc_8 = 0 - while true do - loc_9 = bit32_add(loc_2, loc_8) - loc_10 = bit32_add(loc_1, loc_8) - buffer.writeu8(mem, bit32_add(loc_9, 3), buffer.readu8(mem, loc_10)) - buffer.writeu8(mem, bit32_add(loc_9, 2), buffer.readu8(mem, bit32_add(loc_10, 1))) - buffer.writeu8(mem, bit32_add(loc_9, 1), buffer.readu8(mem, bit32_add(loc_10, 2))) - buffer.writeu8(mem, loc_9, buffer.readu8(mem, bit32_add(loc_10, 3))) - loc_8 = bit32_add(loc_8, 4) - if loc_8 ~= 64 then - continue - end - break - end - loc_11 = buffer.readu32(mem, loc_0) - loc_12 = buffer.readu32(mem, loc_2 + 20) - loc_13 = buffer.readu32(mem, loc_2 + 12) - loc_14 = buffer.readu32(mem, loc_2 + 44) - loc_15 = buffer.readu32(mem, loc_2 + 8) - loc_16 = buffer.readu32(mem, loc_2) - loc_17 = buffer.readu32(mem, loc_2 + 32) - loc_8 = buffer.readu32(mem, loc_2 + 52) - loc_9 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_15, loc_16), loc_17), loc_8), 1) - loc_10 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_12, loc_13), loc_14), loc_9), 1) - loc_18 = buffer.readu32(mem, loc_2 + 4) - loc_19 = buffer.readu32(mem, loc_2 + 36) - loc_1 = buffer.readu32(mem, loc_2 + 56) - loc_20 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_13, loc_18), loc_19), loc_1), 1) - loc_21 = buffer.readu32(mem, loc_2 + 24) - loc_22 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_17, loc_21), loc_1), loc_10), 1) - loc_23 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_14, loc_19), loc_20), loc_22), 1) - loc_24 = buffer.readu32(mem, loc_2 + 40) - loc_25 = buffer.readu32(mem, loc_2 + 28) - loc_26 = buffer.readu32(mem, loc_2 + 16) - loc_27 = buffer.readu32(mem, loc_2 + 60) - loc_28 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_26, loc_15), loc_24), loc_27), 1) - loc_29 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_25, loc_12), loc_8), loc_28), 1) - loc_30 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_24, loc_17), loc_9), loc_29), 1) - loc_31 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_8, loc_14), loc_10), loc_30), 1) - loc_32 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_9, loc_1), loc_22), loc_31), 1) - loc_33 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_10, loc_20), loc_23), loc_32), 1) - loc_34 = buffer.readu32(mem, loc_2 + 48) - loc_2 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_21, loc_26), loc_34), loc_20), 1) - loc_35 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_19, loc_25), loc_27), loc_2), 1) - loc_36 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_1, loc_34), loc_2), loc_23), 1) - loc_37 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_20, loc_27), loc_35), loc_36), 1) - loc_38 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_22, loc_2), loc_36), loc_33), 1) - loc_39 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_23, loc_35), loc_37), loc_38), 1) - loc_40 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_34, loc_24), loc_28), loc_35), 1) - loc_41 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_27, loc_8), loc_29), loc_40), 1) - loc_42 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_28, loc_9), loc_30), loc_41), 1) - loc_43 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_29, loc_10), loc_31), loc_42), 1) - loc_44 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_30, loc_22), loc_32), loc_43), 1) - loc_45 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_31, loc_23), loc_33), loc_44), 1) - loc_46 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_32, loc_36), loc_38), loc_45), 1) - loc_47 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_33, loc_37), loc_39), loc_46), 1) - loc_48 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_2, loc_28), loc_40), loc_37), 1) - loc_49 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_35, loc_29), loc_41), loc_48), 1) - loc_50 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_36, loc_40), loc_48), loc_39), 1) - loc_51 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_37, loc_41), loc_49), loc_50), 1) - loc_52 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_38, loc_48), loc_50), loc_47), 1) - loc_53 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_39, loc_49), loc_51), loc_52), 1) - loc_54 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_40, loc_30), loc_42), loc_49), 1) - loc_55 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_41, loc_31), loc_43), loc_54), 1) - loc_56 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_42, loc_32), loc_44), loc_55), 1) - loc_57 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_43, loc_33), loc_45), loc_56), 1) - loc_58 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_44, loc_38), loc_46), loc_57), 1) - loc_59 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_45, loc_39), loc_47), loc_58), 1) - loc_60 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_46, loc_50), loc_52), loc_59), 1) - loc_61 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_47, loc_51), loc_53), loc_60), 1) - loc_62 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_48, loc_42), loc_54), loc_51), 1) - loc_63 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_49, loc_43), loc_55), loc_62), 1) - loc_64 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_50, loc_54), loc_62), loc_53), 1) - loc_65 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_51, loc_55), loc_63), loc_64), 1) - loc_66 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_52, loc_62), loc_64), loc_61), 1) - loc_67 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_53, loc_63), loc_65), loc_66), 1) - loc_68 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_54, loc_44), loc_56), loc_63), 1) - loc_69 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_55, loc_45), loc_57), loc_68), 1) - loc_70 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_56, loc_46), loc_58), loc_69), 1) - loc_71 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_57, loc_47), loc_59), loc_70), 1) - loc_72 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_58, loc_52), loc_60), loc_71), 1) - loc_73 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_59, loc_53), loc_61), loc_72), 1) - loc_74 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_60, loc_64), loc_66), loc_73), 1) - loc_75 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_61, loc_65), loc_67), loc_74), 1) - loc_76 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_62, loc_56), loc_68), loc_65), 1) - loc_77 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_64, loc_68), loc_76), loc_67), 1) - loc_78 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_63, loc_57), loc_69), loc_76), 1) - loc_16 = bit32_add(bit32_add(bit32_add(bit32_add(bit32.lrotate(loc_7, 5), loc_3), bit32.bxor(bit32.band(bit32.bxor(loc_4, loc_5), loc_6), loc_4)), loc_16), 1518500249) - loc_3 = bit32.lrotate(loc_16, 30) - loc_6 = bit32.lrotate(loc_6, 30) - reg_15 = bit32_add(loc_3, loc_12) - loc_12 = bit32_add(bit32_add(bit32_add(bit32_add(loc_4, bit32.bxor(bit32.band(bit32.bxor(loc_6, loc_5), loc_7), loc_5)), loc_18), bit32.lrotate(loc_16, 5)), 1518500249) - loc_4 = bit32.lrotate(loc_7, 30) - reg_16 = bit32_add(bit32_add(loc_6, loc_13), bit32.bxor(bit32.band(loc_12, bit32.bxor(loc_3, loc_4)), loc_4)) - loc_6 = bit32_add(bit32_add(bit32_add(bit32_add(loc_5, loc_15), bit32.bxor(bit32.band(loc_16, bit32.bxor(loc_6, loc_4)), loc_6)), bit32.lrotate(loc_12, 5)), 1518500249) - loc_13 = bit32_add(bit32_add(reg_16, bit32.lrotate(loc_6, 5)), 1518500249) - loc_5 = bit32.lrotate(loc_6, 30) - loc_7 = bit32.lrotate(loc_12, 30) - loc_3 = bit32_add(bit32_add(bit32_add(bit32_add(loc_4, loc_26), bit32.bxor(bit32.band(loc_6, bit32.bxor(loc_7, loc_3)), loc_3)), bit32.lrotate(loc_13, 5)), 1518500249) - loc_6 = bit32_add(bit32_add(bit32_add(reg_15, bit32.bxor(bit32.band(loc_13, bit32.bxor(loc_5, loc_7)), loc_7)), bit32.lrotate(loc_3, 5)), 1518500249) - loc_4 = bit32.lrotate(loc_6, 30) - reg_14 = bit32_add(loc_24, loc_4) - loc_24 = bit32.lrotate(loc_13, 30) - reg_15 = bit32_add(loc_17, loc_24) - loc_17 = bit32_add(bit32_add(bit32_add(bit32_add(loc_21, loc_7), bit32.bxor(bit32.band(loc_3, bit32.bxor(loc_24, loc_5)), loc_5)), bit32.lrotate(loc_6, 5)), 1518500249) - loc_7 = bit32.lrotate(loc_3, 30) - loc_24 = bit32_add(bit32_add(bit32_add(bit32_add(loc_25, loc_5), bit32.bxor(bit32.band(loc_6, bit32.bxor(loc_7, loc_24)), loc_24)), bit32.lrotate(loc_17, 5)), 1518500249) - loc_3 = bit32_add(bit32_add(bit32_add(reg_15, bit32.bxor(bit32.band(loc_17, bit32.bxor(loc_4, loc_7)), loc_7)), bit32.lrotate(loc_24, 5)), 1518500249) - loc_5 = bit32.lrotate(loc_24, 30) - loc_17 = bit32.lrotate(loc_17, 30) - loc_7 = bit32_add(bit32_add(bit32_add(bit32_add(loc_19, loc_7), bit32.bxor(bit32.band(loc_24, bit32.bxor(loc_17, loc_4)), loc_4)), bit32.lrotate(loc_3, 5)), 1518500249) - loc_19 = bit32_add(bit32_add(bit32_add(reg_14, bit32.bxor(bit32.band(loc_3, bit32.bxor(loc_5, loc_17)), loc_17)), bit32.lrotate(loc_7, 5)), 1518500249) - loc_4 = bit32.lrotate(loc_19, 30) - reg_13 = bit32_add(loc_27, loc_4) - loc_27 = bit32.lrotate(loc_3, 30) - loc_14 = bit32_add(bit32_add(bit32_add(bit32_add(loc_14, loc_17), bit32.bxor(bit32.band(loc_7, bit32.bxor(loc_27, loc_5)), loc_5)), bit32.lrotate(loc_19, 5)), 1518500249) - reg_14 = bit32_add(loc_8, loc_27) - loc_8 = bit32.lrotate(loc_7, 30) - loc_7 = bit32_add(bit32_add(bit32_add(bit32_add(loc_34, loc_5), bit32.bxor(bit32.band(loc_19, bit32.bxor(loc_8, loc_27)), loc_27)), bit32.lrotate(loc_14, 5)), 1518500249) - loc_17 = bit32_add(bit32_add(bit32_add(reg_14, bit32.bxor(bit32.band(loc_14, bit32.bxor(loc_4, loc_8)), loc_8)), bit32.lrotate(loc_7, 5)), 1518500249) - loc_5 = bit32.lrotate(loc_7, 30) - loc_27 = bit32.lrotate(loc_14, 30) - loc_4 = bit32_add(bit32_add(bit32_add(bit32_add(loc_1, loc_8), bit32.bxor(bit32.band(loc_7, bit32.bxor(loc_27, loc_4)), loc_4)), bit32.lrotate(loc_17, 5)), 1518500249) - loc_7 = bit32_add(bit32_add(bit32_add(reg_13, bit32.bxor(bit32.band(loc_17, bit32.bxor(loc_5, loc_27)), loc_27)), bit32.lrotate(loc_4, 5)), 1518500249) - loc_8 = bit32.lrotate(loc_7, 30) - reg_12 = bit32_add(loc_2, loc_8) - loc_2 = bit32.lrotate(loc_4, 30) - loc_1 = bit32.lrotate(loc_17, 30) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_9, loc_27), bit32.bxor(bit32.band(loc_4, bit32.bxor(loc_1, loc_5)), loc_5)), bit32.lrotate(loc_7, 5)), 1518500249) - loc_5 = bit32_add(bit32_add(bit32_add(bit32_add(loc_20, loc_5), bit32.bxor(bit32.band(loc_7, bit32.bxor(loc_2, loc_1)), loc_1)), bit32.lrotate(loc_9, 5)), 1518500249) - loc_20 = bit32.lrotate(loc_5, 30) - loc_27 = bit32.lrotate(loc_9, 30) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_28, loc_1), bit32.bxor(bit32.band(loc_9, bit32.bxor(loc_8, loc_2)), loc_2)), bit32.lrotate(loc_5, 5)), 1518500249) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_10, loc_2), bit32.bxor(bit32.band(loc_5, bit32.bxor(loc_27, loc_8)), loc_8)), bit32.lrotate(loc_9, 5)), 1518500249) - loc_10 = bit32_add(bit32_add(bit32_add(reg_12, bit32.bxor(bit32.bxor(loc_20, loc_27), loc_9)), bit32.lrotate(loc_8, 5)), 1859775393) - loc_2 = bit32.lrotate(loc_10, 30) - loc_1 = bit32.lrotate(loc_8, 30) - loc_9 = bit32.lrotate(loc_9, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_29, loc_27), bit32.bxor(bit32.bxor(loc_9, loc_20), loc_8)), bit32.lrotate(loc_10, 5)), 1859775393) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_22, loc_20), bit32.bxor(bit32.bxor(loc_1, loc_9), loc_10)), bit32.lrotate(loc_8, 5)), 1859775393) - loc_5 = bit32.lrotate(loc_10, 30) - loc_20 = bit32.lrotate(loc_8, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_35, loc_9), bit32.bxor(bit32.bxor(loc_2, loc_1), loc_8)), bit32.lrotate(loc_10, 5)), 1859775393) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_30, loc_1), bit32.bxor(bit32.bxor(loc_20, loc_2), loc_10)), bit32.lrotate(loc_8, 5)), 1859775393) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_23, loc_2), bit32.bxor(bit32.bxor(loc_5, loc_20), loc_8)), bit32.lrotate(loc_9, 5)), 1859775393) - loc_2 = bit32.lrotate(loc_10, 30) - loc_1 = bit32.lrotate(loc_9, 30) - loc_8 = bit32.lrotate(loc_8, 30) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_40, loc_20), bit32.bxor(bit32.bxor(loc_8, loc_5), loc_9)), bit32.lrotate(loc_10, 5)), 1859775393) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_31, loc_5), bit32.bxor(bit32.bxor(loc_1, loc_8), loc_10)), bit32.lrotate(loc_9, 5)), 1859775393) - loc_5 = bit32.lrotate(loc_10, 30) - loc_20 = bit32.lrotate(loc_9, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_36, loc_8), bit32.bxor(bit32.bxor(loc_2, loc_1), loc_9)), bit32.lrotate(loc_10, 5)), 1859775393) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_41, loc_1), bit32.bxor(bit32.bxor(loc_20, loc_2), loc_10)), bit32.lrotate(loc_8, 5)), 1859775393) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_32, loc_2), bit32.bxor(bit32.bxor(loc_5, loc_20), loc_8)), bit32.lrotate(loc_9, 5)), 1859775393) - loc_2 = bit32.lrotate(loc_10, 30) - loc_1 = bit32.lrotate(loc_9, 30) - loc_8 = bit32.lrotate(loc_8, 30) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_37, loc_20), bit32.bxor(bit32.bxor(loc_8, loc_5), loc_9)), bit32.lrotate(loc_10, 5)), 1859775393) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_42, loc_5), bit32.bxor(bit32.bxor(loc_1, loc_8), loc_10)), bit32.lrotate(loc_9, 5)), 1859775393) - loc_5 = bit32.lrotate(loc_10, 30) - loc_20 = bit32.lrotate(loc_9, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_33, loc_8), bit32.bxor(bit32.bxor(loc_2, loc_1), loc_9)), bit32.lrotate(loc_10, 5)), 1859775393) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_48, loc_1), bit32.bxor(bit32.bxor(loc_20, loc_2), loc_10)), bit32.lrotate(loc_8, 5)), 1859775393) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_43, loc_2), bit32.bxor(bit32.bxor(loc_5, loc_20), loc_8)), bit32.lrotate(loc_9, 5)), 1859775393) - loc_2 = bit32.lrotate(loc_10, 30) - loc_8 = bit32.lrotate(loc_8, 30) - loc_1 = bit32.lrotate(loc_9, 30) - loc_20 = bit32_add(bit32_add(bit32_add(bit32_add(loc_38, loc_20), bit32.bxor(bit32.bxor(loc_8, loc_5), loc_9)), bit32.lrotate(loc_10, 5)), 1859775393) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_49, loc_5), bit32.bxor(bit32.bxor(loc_1, loc_8), loc_10)), bit32.lrotate(loc_20, 5)), 1859775393) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_44, loc_8), bit32.bxor(bit32.bxor(loc_2, loc_1), loc_20)), bit32.lrotate(loc_10, 5)), 1859775393) - loc_9 = bit32.lrotate(loc_10, 30) - loc_5 = bit32.lrotate(loc_20, 30) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_39, loc_1), bit32.bxor(bit32.bxor(loc_5, loc_2), loc_10)), bit32.lrotate(loc_8, 5)), 1859775393) - loc_2 = bit32_add(bit32_add(bit32_add(bit32_add(loc_54, loc_2), bit32.bor(bit32.band(bit32.bor(loc_8, loc_9), loc_5), bit32.band(loc_8, loc_9))), bit32.lrotate(loc_10, 5)), 2400959708) - loc_1 = bit32.lrotate(loc_2, 30) - loc_8 = bit32.lrotate(loc_8, 30) - loc_5 = bit32_add(bit32_add(bit32_add(bit32_add(loc_45, loc_5), bit32.bor(bit32.band(bit32.bor(loc_10, loc_8), loc_9), bit32.band(loc_10, loc_8))), bit32.lrotate(loc_2, 5)), 2400959708) - loc_10 = bit32.lrotate(loc_10, 30) - reg_8 = bit32_add(bit32_add(loc_55, loc_8), bit32.bor(bit32.band(bit32.bor(loc_5, loc_1), loc_10), bit32.band(loc_5, loc_1))) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_50, loc_9), bit32.bor(bit32.band(bit32.bor(loc_2, loc_10), loc_8), bit32.band(loc_2, loc_10))), bit32.lrotate(loc_5, 5)), 2400959708) - loc_9 = bit32_add(bit32_add(reg_8, bit32.lrotate(loc_8, 5)), 2400959708) - loc_2 = bit32.lrotate(loc_8, 30) - loc_5 = bit32.lrotate(loc_5, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_46, loc_10), bit32.bor(bit32.band(bit32.bor(loc_8, loc_5), loc_1), bit32.band(loc_8, loc_5))), bit32.lrotate(loc_9, 5)), 2400959708) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_51, loc_1), bit32.bor(bit32.band(bit32.bor(loc_9, loc_2), loc_5), bit32.band(loc_9, loc_2))), bit32.lrotate(loc_8, 5)), 2400959708) - loc_1 = bit32.lrotate(loc_10, 30) - loc_9 = bit32.lrotate(loc_9, 30) - loc_5 = bit32_add(bit32_add(bit32_add(bit32_add(loc_56, loc_5), bit32.bor(bit32.band(bit32.bor(loc_8, loc_9), loc_2), bit32.band(loc_8, loc_9))), bit32.lrotate(loc_10, 5)), 2400959708) - loc_8 = bit32.lrotate(loc_8, 30) - reg_7 = bit32_add(bit32_add(loc_62, loc_9), bit32.bor(bit32.band(bit32.bor(loc_5, loc_1), loc_8), bit32.band(loc_5, loc_1))) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_47, loc_2), bit32.bor(bit32.band(bit32.bor(loc_10, loc_8), loc_9), bit32.band(loc_10, loc_8))), bit32.lrotate(loc_5, 5)), 2400959708) - loc_10 = bit32_add(bit32_add(reg_7, bit32.lrotate(loc_9, 5)), 2400959708) - loc_2 = bit32.lrotate(loc_9, 30) - loc_5 = bit32.lrotate(loc_5, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_57, loc_8), bit32.bor(bit32.band(bit32.bor(loc_9, loc_5), loc_1), bit32.band(loc_9, loc_5))), bit32.lrotate(loc_10, 5)), 2400959708) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_52, loc_1), bit32.bor(bit32.band(bit32.bor(loc_10, loc_2), loc_5), bit32.band(loc_10, loc_2))), bit32.lrotate(loc_8, 5)), 2400959708) - loc_1 = bit32.lrotate(loc_9, 30) - loc_10 = bit32.lrotate(loc_10, 30) - loc_5 = bit32_add(bit32_add(bit32_add(bit32_add(loc_63, loc_5), bit32.bor(bit32.band(bit32.bor(loc_8, loc_10), loc_2), bit32.band(loc_8, loc_10))), bit32.lrotate(loc_9, 5)), 2400959708) - loc_8 = bit32.lrotate(loc_8, 30) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_58, loc_2), bit32.bor(bit32.band(bit32.bor(loc_9, loc_8), loc_10), bit32.band(loc_9, loc_8))), bit32.lrotate(loc_5, 5)), 2400959708) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_53, loc_10), bit32.bor(bit32.band(bit32.bor(loc_5, loc_1), loc_8), bit32.band(loc_5, loc_1))), bit32.lrotate(loc_9, 5)), 2400959708) - loc_2 = bit32.lrotate(loc_9, 30) - loc_5 = bit32.lrotate(loc_5, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_68, loc_8), bit32.bor(bit32.band(bit32.bor(loc_9, loc_5), loc_1), bit32.band(loc_9, loc_5))), bit32.lrotate(loc_10, 5)), 2400959708) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_59, loc_1), bit32.bor(bit32.band(bit32.bor(loc_10, loc_2), loc_5), bit32.band(loc_10, loc_2))), bit32.lrotate(loc_8, 5)), 2400959708) - loc_1 = bit32.lrotate(loc_9, 30) - loc_20 = bit32.lrotate(loc_8, 30) - loc_10 = bit32.lrotate(loc_10, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_64, loc_5), bit32.bor(bit32.band(bit32.bor(loc_8, loc_10), loc_2), bit32.band(loc_8, loc_10))), bit32.lrotate(loc_9, 5)), 2400959708) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_69, loc_2), bit32.bor(bit32.band(bit32.bor(loc_9, loc_20), loc_10), bit32.band(loc_9, loc_20))), bit32.lrotate(loc_8, 5)), 2400959708) - loc_5 = bit32.lrotate(loc_9, 30) - loc_2 = bit32.lrotate(loc_8, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_60, loc_10), bit32.bor(bit32.band(bit32.bor(loc_8, loc_1), loc_20), bit32.band(loc_8, loc_1))), bit32.lrotate(loc_9, 5)), 2400959708) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_65, loc_20), bit32.bor(bit32.band(bit32.bor(loc_9, loc_2), loc_1), bit32.band(loc_9, loc_2))), bit32.lrotate(loc_8, 5)), 2400959708) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_70, loc_1), bit32.bxor(bit32.bxor(loc_5, loc_2), loc_8)), bit32.lrotate(loc_9, 5)), 3395469782) - loc_1 = bit32.lrotate(loc_10, 30) - loc_20 = bit32.lrotate(loc_9, 30) - loc_8 = bit32.lrotate(loc_8, 30) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_61, loc_2), bit32.bxor(bit32.bxor(loc_8, loc_5), loc_9)), bit32.lrotate(loc_10, 5)), 3395469782) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_76, loc_5), bit32.bxor(bit32.bxor(loc_20, loc_8), loc_10)), bit32.lrotate(loc_9, 5)), 3395469782) - loc_2 = bit32.lrotate(loc_10, 30) - loc_5 = bit32.lrotate(loc_9, 30) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_71, loc_8), bit32.bxor(bit32.bxor(loc_1, loc_20), loc_9)), bit32.lrotate(loc_10, 5)), 3395469782) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_66, loc_20), bit32.bxor(bit32.bxor(loc_5, loc_1), loc_10)), bit32.lrotate(loc_8, 5)), 3395469782) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_78, loc_1), bit32.bxor(bit32.bxor(loc_2, loc_5), loc_8)), bit32.lrotate(loc_9, 5)), 3395469782) - loc_1 = bit32.lrotate(loc_10, 30) - loc_20 = bit32.lrotate(loc_9, 30) - loc_8 = bit32.lrotate(loc_8, 30) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_72, loc_5), bit32.bxor(bit32.bxor(loc_8, loc_2), loc_9)), bit32.lrotate(loc_10, 5)), 3395469782) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_67, loc_2), bit32.bxor(bit32.bxor(loc_20, loc_8), loc_10)), bit32.lrotate(loc_9, 5)), 3395469782) - loc_2 = bit32.lrotate(loc_10, 30) - loc_5 = bit32.lrotate(loc_9, 30) - loc_22 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_68, loc_58), loc_70), loc_78), 1) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_22, loc_8), bit32.bxor(bit32.bxor(loc_1, loc_20), loc_9)), bit32.lrotate(loc_10, 5)), 3395469782) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_73, loc_20), bit32.bxor(bit32.bxor(loc_5, loc_1), loc_10)), bit32.lrotate(loc_8, 5)), 3395469782) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_77, loc_1), bit32.bxor(bit32.bxor(loc_2, loc_5), loc_8)), bit32.lrotate(loc_9, 5)), 3395469782) - loc_1 = bit32.lrotate(loc_10, 30) - loc_20 = bit32.lrotate(loc_9, 30) - loc_8 = bit32.lrotate(loc_8, 30) - loc_23 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_69, loc_59), loc_71), loc_22), 1) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_23, loc_5), bit32.bxor(bit32.bxor(loc_8, loc_2), loc_9)), bit32.lrotate(loc_10, 5)), 3395469782) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_74, loc_2), bit32.bxor(bit32.bxor(loc_20, loc_8), loc_10)), bit32.lrotate(loc_9, 5)), 3395469782) - loc_2 = bit32.lrotate(loc_10, 30) - loc_5 = bit32.lrotate(loc_9, 30) - loc_27 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_65, loc_69), loc_78), loc_77), 1) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(loc_27, loc_8), bit32.bxor(bit32.bxor(loc_1, loc_20), loc_9)), bit32.lrotate(loc_10, 5)), 3395469782) - loc_28 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_70, loc_60), loc_72), loc_23), 1) - loc_9 = bit32_add(bit32_add(bit32_add(bit32_add(loc_28, loc_20), bit32.bxor(bit32.bxor(loc_5, loc_1), loc_10)), bit32.lrotate(loc_8, 5)), 3395469782) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(loc_75, loc_1), bit32.bxor(bit32.bxor(loc_2, loc_5), loc_8)), bit32.lrotate(loc_9, 5)), 3395469782) - loc_1 = bit32.lrotate(loc_10, 30) - buffer.writeu32(mem, loc_0 + 16, bit32_add(loc_1, buffer.readu32(mem, loc_0 + 16))) - loc_20 = bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_76, loc_70), loc_22), loc_27), 1) - loc_8 = bit32.lrotate(loc_8, 30) - loc_5 = bit32_add(bit32_add(bit32_add(bit32_add(loc_20, loc_5), bit32.bxor(bit32.bxor(loc_8, loc_2), loc_9)), bit32.lrotate(loc_10, 5)), 3395469782) - loc_22 = bit32.lrotate(loc_5, 30) - buffer.writeu32(mem, loc_0 + 12, bit32_add(loc_22, buffer.readu32(mem, loc_0 + 12))) - loc_9 = bit32.lrotate(loc_9, 30) - loc_10 = bit32_add(bit32_add(bit32_add(bit32_add(bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_71, loc_61), loc_73), loc_28), 1), loc_2), bit32.bxor(bit32.bxor(loc_9, loc_8), loc_10)), bit32.lrotate(loc_5, 5)), 3395469782) - buffer.writeu32(mem, loc_0 + 8, bit32_add(bit32.lrotate(loc_10, 30), buffer.readu32(mem, loc_0 + 8))) - loc_8 = bit32_add(bit32_add(bit32_add(bit32_add(bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_66, loc_76), loc_77), loc_75), 1), loc_8), bit32.bxor(bit32.bxor(loc_1, loc_9), loc_5)), bit32.lrotate(loc_10, 5)), 3395469782) - buffer.writeu32(mem, loc_0 + 4, bit32_add(loc_8, buffer.readu32(mem, loc_0 + 4))) - buffer.writeu32(mem, loc_0, bit32_add(bit32_add(bit32_add(bit32_add(bit32_add(loc_11, bit32.lrotate(bit32.bxor(bit32.bxor(bit32.bxor(loc_78, loc_71), loc_23), loc_20), 1)), loc_9), bit32.bxor(bit32.bxor(loc_22, loc_1), loc_10)), bit32.lrotate(loc_8, 5)), 3395469782)) - break - end -end - -FUNC_LIST[2] = function(hashtable: buffer, entries: buffer, px: buffer, py: buffer, N: number, mult: number, size: number) - local function hash(x: number, y: number, mult: number, size: number) - local cx, cy = math.floor(x * mult), math.floor(y * mult) - local h = bit32.bxor((cx * 92837111), (cy * 689287499)) - return math.abs(h) % size; - end - - for i = 0, N-1, 8 do - local x0, x1, x2, x3, x4, x5, x6, x7 = - buffer.readf32(px, (i) * 4), - buffer.readf32(px, (i+1) * 4), - buffer.readf32(px, (i+2) * 4), - buffer.readf32(px, (i+3) * 4), - buffer.readf32(px, (i+4) * 4), - buffer.readf32(px, (i+5) * 4), - buffer.readf32(px, (i+6) * 4), - buffer.readf32(px, (i+7) * 4) - - local y0, y1, y2, y3, y4, y5, y6, y7 = - buffer.readf32(py, (i) * 4), - buffer.readf32(py, (i+1) * 4), - buffer.readf32(py, (i+2) * 4), - buffer.readf32(py, (i+3) * 4), - buffer.readf32(py, (i+4) * 4), - buffer.readf32(py, (i+5) * 4), - buffer.readf32(py, (i+6) * 4), - buffer.readf32(py, (i+7) * 4) - - local h0, h1, h2, h3, h4, h5, h6, h7 = - hash(x0, y0, mult, size), - hash(x1, y1, mult, size), - hash(x2, y2, mult, size), - hash(x3, y3, mult, size), - hash(x4, y4, mult, size), - hash(x5, y5, mult, size), - hash(x6, y6, mult, size), - hash(x7, y7, mult, size) - - local vdecr0, vdecr1, vdecr2, vdecr3, vdecr4, vdecr5, vdecr6, vdecr7 = - buffer.readu32(hashtable, h0 * 4) - 1, - buffer.readu32(hashtable, h1 * 4) - 1, - buffer.readu32(hashtable, h2 * 4) - 1, - buffer.readu32(hashtable, h3 * 4) - 1, - buffer.readu32(hashtable, h4 * 4) - 1, - buffer.readu32(hashtable, h5 * 4) - 1, - buffer.readu32(hashtable, h6 * 4) - 1, - buffer.readu32(hashtable, h7 * 4) - 1 - - buffer.writeu32(entries, vdecr0 * 4, i) - buffer.writeu32(entries, vdecr1 * 4, i + 1) - buffer.writeu32(entries, vdecr2 * 4, i + 2) - buffer.writeu32(entries, vdecr3 * 4, i + 3) - buffer.writeu32(entries, vdecr4 * 4, i + 4) - buffer.writeu32(entries, vdecr5 * 4, i + 5) - buffer.writeu32(entries, vdecr6 * 4, i + 6) - buffer.writeu32(entries, vdecr7 * 4, i + 7) - - buffer.writeu32(hashtable, h0 * 4, vdecr0) - buffer.writeu32(hashtable, h1 * 4, vdecr1) - buffer.writeu32(hashtable, h2 * 4, vdecr2) - buffer.writeu32(hashtable, h3 * 4, vdecr3) - buffer.writeu32(hashtable, h4 * 4, vdecr4) - buffer.writeu32(hashtable, h5 * 4, vdecr5) - buffer.writeu32(hashtable, h6 * 4, vdecr6) - buffer.writeu32(hashtable, h7 * 4, vdecr7) - end -end - -FUNC_LIST[3] = function(buf: buffer): () - local l01, l02, l03, l04, l05 = buffer.readinteger(buf, 0), buffer.readinteger(buf, 8), buffer.readinteger(buf, 16), buffer.readinteger(buf, 24), buffer.readinteger(buf, 32) - local l06, l07, l08, l09, l10 = buffer.readinteger(buf, 40), buffer.readinteger(buf, 48), buffer.readinteger(buf, 56), buffer.readinteger(buf, 64), buffer.readinteger(buf, 72) - local l11, l12, l13, l14, l15 = buffer.readinteger(buf, 80), buffer.readinteger(buf, 88), buffer.readinteger(buf, 96), buffer.readinteger(buf, 104), buffer.readinteger(buf, 112) - local l16, l17, l18, l19, l20 = buffer.readinteger(buf, 120), buffer.readinteger(buf, 128), buffer.readinteger(buf, 136), buffer.readinteger(buf, 144), buffer.readinteger(buf, 152) - local l21, l22, l23, l24, l25 = buffer.readinteger(buf, 160), buffer.readinteger(buf, 168), buffer.readinteger(buf, 176), buffer.readinteger(buf, 184), buffer.readinteger(buf, 192) - - for r = 0, 8, 8 do - local c1 = integer.bxor(integer.bxor(integer.bxor(integer.bxor(l01, l06), l11), l16), l21) - local c2 = integer.bxor(integer.bxor(integer.bxor(integer.bxor(l02, l07), l12), l17), l22) - local c3 = integer.bxor(integer.bxor(integer.bxor(integer.bxor(l03, l08), l13), l18), l23) - local c4 = integer.bxor(integer.bxor(integer.bxor(integer.bxor(l04, l09), l14), l19), l24) - local c5 = integer.bxor(integer.bxor(integer.bxor(integer.bxor(l05, l10), l15), l20), l25) - - local d = integer.bxor(c1, integer.lrotate(c3, 1i)) - local t0, t1, t2, t3, t4 = integer.bxor(d, l02), integer.bxor(d, l07), integer.bxor(d, l12), integer.bxor(d, l17), integer.bxor(d, l22) - l02, l07, l12, l17, l22 = integer.rrotate(t1, 20i), integer.rrotate(t3, 19i), integer.rrotate(t0, 63i), integer.rrotate(t2, 54i), integer.rrotate(t4, 62i) - d = integer.bxor(c2, integer.rrotate(c4, 63i)) - - t0, t1, t2, t3, t4 = integer.bxor(d, l03), integer.bxor(d, l08), integer.bxor(d, l13), integer.bxor(d, l18), integer.bxor(d, l23) - l03, l08, l13, l18, l23 = integer.rrotate(t2, 21i), integer.rrotate(t4, 3i), integer.rrotate(t1, 58i), integer.rrotate(t3, 49i), integer.rrotate(t0, 2i) - d = integer.bxor(c3, integer.rrotate(c5, 63i)) - - t0, t1, t2, t3, t4 = integer.bxor(d, l04), integer.bxor(d, l09), integer.bxor(d, l14), integer.bxor(d, l19), integer.bxor(d, l24) - l04, l09, l14, l19, l24 = integer.rrotate(t3, 43i), integer.rrotate(t0, 36i), integer.rrotate(t2, 39i), integer.rrotate(t4, 8i), integer.rrotate(t1, 9i) - d = integer.bxor(c4, integer.rrotate(c1, 63i)) - - t0, t1, t2, t3, t4 = integer.bxor(d, l05), integer.bxor(d, l10), integer.bxor(d, l15), integer.bxor(d, l20), integer.bxor(d, l25) - l05, l10, l15, l20, l25 = integer.rrotate(t4, 50i), integer.rrotate(t1, 44i), integer.rrotate(t3, 56i), integer.rrotate(t0, 37i), integer.rrotate(t2, 25i) - d = integer.bxor(c5, integer.rrotate(c2, 63i)) - - t1, t2, t3, t4 = integer.bxor(d, l06), integer.bxor(d, l11), integer.bxor(d, l16), integer.bxor(d, l21) - l06, l11, l16, l21 = integer.rrotate(t2, 61i), integer.rrotate(t4, 46i), integer.rrotate(t1, 28i), integer.rrotate(t3, 23i) - l01 = integer.bxor(d, l01) - - l01, l02, l03, l04, l05 = - integer.bxor(l01, integer.band(integer.bnot(l02), l03)), - integer.bxor(l02, integer.band(integer.bnot(l03), l04)), - integer.bxor(l03, integer.band(integer.bnot(l04), l05)), - integer.bxor(l04, integer.band(integer.bnot(l05), l01)), - integer.bxor(l05, integer.band(integer.bnot(l01), l02)) - - l06, l07, l08, l09, l10 = - integer.bxor(l09, integer.band(integer.bnot(l10), l06)), - integer.bxor(l10, integer.band(integer.bnot(l06), l07)), - integer.bxor(l06, integer.band(integer.bnot(l07), l08)), - integer.bxor(l07, integer.band(integer.bnot(l08), l09)), - integer.bxor(l08, integer.band(integer.bnot(l09), l10)) - - l11, l12, l13, l14, l15 = - integer.bxor(l12, integer.band(integer.bnot(l13), l14)), - integer.bxor(l13, integer.band(integer.bnot(l14), l15)), - integer.bxor(l14, integer.band(integer.bnot(l15), l11)), - integer.bxor(l15, integer.band(integer.bnot(l11), l12)), - integer.bxor(l11, integer.band(integer.bnot(l12), l13)) - - l16, l17, l18, l19, l20 = - integer.bxor(l20, integer.band(integer.bnot(l16), l17)), - integer.bxor(l16, integer.band(integer.bnot(l17), l18)), - integer.bxor(l17, integer.band(integer.bnot(l18), l19)), - integer.bxor(l18, integer.band(integer.bnot(l19), l20)), - integer.bxor(l19, integer.band(integer.bnot(l20), l16)) - - l21, l22, l23, l24, l25 = - integer.bxor(l23, integer.band(integer.bnot(l24), l25)), - integer.bxor(l24, integer.band(integer.bnot(l25), l21)), - integer.bxor(l25, integer.band(integer.bnot(l21), l22)), - integer.bxor(l21, integer.band(integer.bnot(l22), l23)), - integer.bxor(l22, integer.band(integer.bnot(l23), l24)) - - l01 = integer.bxor(l01, buffer.readinteger(buf, r)) - end - - buffer.writeinteger(buf, 0, l01) -end - -mem = buffer.create(1024 * 1024) - -return('OK') diff --git a/tests/conformance/promotion.luau b/tests/conformance/promotion.luau index d464d9a53..ff7ba93ff 100644 --- a/tests/conformance/promotion.luau +++ b/tests/conformance/promotion.luau @@ -106,7 +106,7 @@ end -- function is specialized for a generic case function test4(frame) - for j = 1, 1000 do + for j = 1, 100 do local z = iteratecomplex(setmetatable({ re = 0, im = 0 }, Complex), 100) assert(z.re == 0 and z.im == 0) end @@ -199,7 +199,7 @@ end function vec2operators(values) local sum = vec2(0, 0) - for j = 1,1000 do + for j = 1,100 do for _, v in values do sum = sum + v * v + -v end @@ -218,7 +218,7 @@ function test8(frame) -- each value adds (1 * 1 - 1, 2 * 2 - 2) local res = vec2operators(values) - assert(res.X == 0 and res.Y == 1000 * 100 * 2) + assert(res.X == 0 and res.Y == 100 * 100 * 2) end @native diff --git a/tests/conformance/udata_direct.luau b/tests/conformance/udata_direct.luau index d779fc673..ef52aaceb 100644 --- a/tests/conformance/udata_direct.luau +++ b/tests/conformance/udata_direct.luau @@ -211,4 +211,109 @@ do assert(guardedCallDot(vec2(1, 2), vec2(3, 4), 0) == 11) end +-- direct userdata namecalls +do + local v = vec2(1, 2) + local function arguments() return 7, 8, 9 end + local function results(obj, ...) + return obj:Results(...) + end + + local a, b, c = results(v, arguments()) + assert(a == 4 and b == 42 and c == nil) + local x, y, z = v:Results(7) + assert(x == 2 and y == 42 and z == nil) + assert(v:Results() == 1) + v:Results() +end + +-- direct userdata namecalls (yielding) +do + local v = vec2(1, 2) + local co = coroutine.create(function() + local value = v:Yield() + assert(value == 99) + assert(v:Dot(vec2(3, 4)) == 11) + return value + 1 + end) + + local ok, value = coroutine.resume(co) + assert(ok and value == 55 and coroutine.status(co) == "suspended") + ok, value = coroutine.resume(co, 99) + assert(ok and value == 100 and coroutine.status(co) == "dead") +end + +-- direct userdata namecalls (deoptimization) +do + local function clone(obj) + return obj:Clone() + end + + assert(clone(vec2(1, 2)).X == 1) + local proxy = newproxy(true) + getmetatable(proxy).__namecall = function(self) + assert(self == proxy) + return 18 + end + assert(clone(proxy) == 18) + assert(clone(vec2(3, 4)).X == 3) + + local co = coroutine.create(function() + local result = clone({ + Clone = function() return coroutine.yield(56) end + }) + assert(result == 101) + return 102 + end) + local ok, value = coroutine.resume(co) + assert(ok and value == 56) + ok, value = coroutine.resume(co, 101) + assert(ok and value == 102 and coroutine.status(co) == "dead") + + local indexedProxy = newproxy(true) + getmetatable(indexedProxy).__index = { + Clone = function(self) + assert(self == indexedProxy) + return 19 + end + } + assert(clone(indexedProxy) == 19) + + local indexedTable = setmetatable({X = 4, Y = 5}, { + __index = function(self, key) + assert(key == "Clone") + return function(self) return {X = self.X, Y = self.Y} end + end, + }) + local copy = clone(indexedTable) + assert(copy.X == 4 and copy.Y == 5) + + local co = coroutine.create(function() + local result = clone(setmetatable({}, { + __index = function(self, key) + assert(key == "Clone") + return function() return coroutine.yield(57) end + end, + })) + assert(result == 103) + return 104 + end) + local ok, value = coroutine.resume(co) + assert(ok and value == 57 and coroutine.status(co) == "suspended") + ok, value = coroutine.resume(co, 103) + assert(ok and value == 104 and coroutine.status(co) == "dead") + + assert(not pcall(clone, nil)) + assert(not pcall(clone, {})) +end + +do + local function dot(a: vector, b: vector) + return a:Dot(b) + end + + local result = table.pack(dot(vector.create(1, 2, 3), vector.create(4, 5, 6))) + assert(result.n == 1 and result[1] == 32) +end + return 'OK' diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.nonstrict.output b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.nonstrict.output similarity index 100% rename from tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.nonstrict.output rename to tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.nonstrict.output diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.strict.output b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.runtime.output similarity index 100% rename from tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.strict.output rename to tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.runtime.output diff --git a/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.strict.output b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.strict.output new file mode 100644 index 000000000..9898b70f1 --- /dev/null +++ b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-off.strict.output @@ -0,0 +1,3 @@ +./analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau(5,24): TypeError: Expected this to be 'string', but got 'Point' +./analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau(11,28): TypeError: Expected this to be 'number', but got 'Point' +./analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau(14,24): TypeError: Expected this to be 'string', but got 'Point' diff --git a/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.nonstrict.output b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.runtime.output b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.strict.output b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.strict.output new file mode 100644 index 000000000..9898b70f1 --- /dev/null +++ b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.flags-on.strict.output @@ -0,0 +1,3 @@ +./analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau(5,24): TypeError: Expected this to be 'string', but got 'Point' +./analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau(11,28): TypeError: Expected this to be 'number', but got 'Point' +./analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau(14,24): TypeError: Expected this to be 'string', but got 'Point' diff --git a/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau new file mode 100644 index 000000000..fed1958ef --- /dev/null +++ b/tests/golden/analysis/classes/class_shadowed_in_nested_block_is_not_a_duplicate.luau @@ -0,0 +1,14 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true +local class Point + public x: number +end +local _outer: string = Point + +do + local class Point + public y: string + end + local _inner: number = Point +end + +local _after: string = Point diff --git a/tests/golden/analysis/classes/cyclic_inheritance.flags-off.nonstrict.output b/tests/golden/analysis/classes/cyclic_inheritance.flags-off.nonstrict.output new file mode 100644 index 000000000..405c3c640 --- /dev/null +++ b/tests/golden/analysis/classes/cyclic_inheritance.flags-off.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/cyclic_inheritance.luau(3,22): UninitializedLocal: Variable 'B' defined at line 2 is never initialized or assigned; initialize with 'nil' to silence diff --git a/tests/golden/analysis/classes/cyclic_inheritance.flags-off.runtime.output b/tests/golden/analysis/classes/cyclic_inheritance.flags-off.runtime.output new file mode 100644 index 000000000..847896f90 --- /dev/null +++ b/tests/golden/analysis/classes/cyclic_inheritance.flags-off.runtime.output @@ -0,0 +1,3 @@ +./analysis/classes/cyclic_inheritance.luau:3: attempt to extend a nil value +stacktrace: +./analysis/classes/cyclic_inheritance.luau:3 diff --git a/tests/golden/analysis/classes/cyclic_inheritance.flags-off.strict.output b/tests/golden/analysis/classes/cyclic_inheritance.flags-off.strict.output new file mode 100644 index 000000000..3c480526e --- /dev/null +++ b/tests/golden/analysis/classes/cyclic_inheritance.flags-off.strict.output @@ -0,0 +1,2 @@ +./analysis/classes/cyclic_inheritance.luau(3,22): TypeError: Cannot extend non-class of type nil +./analysis/classes/cyclic_inheritance.luau(3,22): UninitializedLocal: Variable 'B' defined at line 2 is never initialized or assigned; initialize with 'nil' to silence diff --git a/tests/golden/analysis/classes/cyclic_inheritance.flags-on.nonstrict.output b/tests/golden/analysis/classes/cyclic_inheritance.flags-on.nonstrict.output new file mode 100644 index 000000000..405c3c640 --- /dev/null +++ b/tests/golden/analysis/classes/cyclic_inheritance.flags-on.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/cyclic_inheritance.luau(3,22): UninitializedLocal: Variable 'B' defined at line 2 is never initialized or assigned; initialize with 'nil' to silence diff --git a/tests/golden/analysis/classes/cyclic_inheritance.flags-on.runtime.output b/tests/golden/analysis/classes/cyclic_inheritance.flags-on.runtime.output new file mode 100644 index 000000000..847896f90 --- /dev/null +++ b/tests/golden/analysis/classes/cyclic_inheritance.flags-on.runtime.output @@ -0,0 +1,3 @@ +./analysis/classes/cyclic_inheritance.luau:3: attempt to extend a nil value +stacktrace: +./analysis/classes/cyclic_inheritance.luau:3 diff --git a/tests/golden/analysis/classes/cyclic_inheritance.flags-on.strict.output b/tests/golden/analysis/classes/cyclic_inheritance.flags-on.strict.output new file mode 100644 index 000000000..3c480526e --- /dev/null +++ b/tests/golden/analysis/classes/cyclic_inheritance.flags-on.strict.output @@ -0,0 +1,2 @@ +./analysis/classes/cyclic_inheritance.luau(3,22): TypeError: Cannot extend non-class of type nil +./analysis/classes/cyclic_inheritance.luau(3,22): UninitializedLocal: Variable 'B' defined at line 2 is never initialized or assigned; initialize with 'nil' to silence diff --git a/tests/golden/analysis/classes/three_step_cyclic_inheritance.luau b/tests/golden/analysis/classes/cyclic_inheritance.luau similarity index 68% rename from tests/golden/analysis/classes/three_step_cyclic_inheritance.luau rename to tests/golden/analysis/classes/cyclic_inheritance.luau index 4e316375c..e8c2f3bb0 100644 --- a/tests/golden/analysis/classes/three_step_cyclic_inheritance.luau +++ b/tests/golden/analysis/classes/cyclic_inheritance.luau @@ -1,9 +1,7 @@ --!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true +local B open class A extends B end -open class B extends C -end - -open class C extends A -end +open class B extends A +end \ No newline at end of file diff --git a/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.nonstrict.output b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.nonstrict.output new file mode 100644 index 000000000..47fbe97e0 --- /dev/null +++ b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau(12,5): TypeError: Redefinition of type 'Point', previously defined at line 7 diff --git a/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.runtime.output b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.strict.output b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.strict.output new file mode 100644 index 000000000..9906fadf3 --- /dev/null +++ b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-off.strict.output @@ -0,0 +1,2 @@ +./analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau(12,5): TypeError: Redefinition of type 'Point', previously defined at line 7 +./analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau(18,24): TypeError: Expected this to be 'string', but got 'Point' diff --git a/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.nonstrict.output b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.nonstrict.output new file mode 100644 index 000000000..47fbe97e0 --- /dev/null +++ b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau(12,5): TypeError: Redefinition of type 'Point', previously defined at line 7 diff --git a/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.runtime.output b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.strict.output b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.strict.output new file mode 100644 index 000000000..9906fadf3 --- /dev/null +++ b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.flags-on.strict.output @@ -0,0 +1,2 @@ +./analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau(12,5): TypeError: Redefinition of type 'Point', previously defined at line 7 +./analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau(18,24): TypeError: Expected this to be 'string', but got 'Point' diff --git a/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau new file mode 100644 index 000000000..4bd4d0c84 --- /dev/null +++ b/tests/golden/analysis/classes/dup_classes_in_nested_block_do_not_affect_shadowed_class.luau @@ -0,0 +1,18 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true +local class Point + public x: number +end + +do + local class Point + public y: string + end + local _first: number = Point + + local class Point + public z: boolean + end + local _second: number = Point +end + +local _after: string = Point diff --git a/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.nonstrict.output b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.nonstrict.output new file mode 100644 index 000000000..6b32dc267 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/duplicate_class_definitions_are_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 diff --git a/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.runtime.output b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.strict.output b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.strict.output new file mode 100644 index 000000000..6b32dc267 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-off.strict.output @@ -0,0 +1 @@ +./analysis/classes/duplicate_class_definitions_are_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 diff --git a/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.nonstrict.output b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.nonstrict.output new file mode 100644 index 000000000..6b32dc267 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/duplicate_class_definitions_are_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 diff --git a/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.runtime.output b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.strict.output b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.strict.output new file mode 100644 index 000000000..6b32dc267 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/classes/duplicate_class_definitions_are_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 diff --git a/tests/golden/analysis/classes/duplicate_class_definitions_are_any.luau b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.luau new file mode 100644 index 000000000..4b7f31398 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_class_definitions_are_any.luau @@ -0,0 +1,10 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true +class Point + public x: number +end +local _first: string = Point + +class Point + public y: string +end +local _second: number = Point diff --git a/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.nonstrict.output b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.nonstrict.output new file mode 100644 index 000000000..e39a04e39 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/duplicate_local_class_definitions_are_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 diff --git a/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.runtime.output b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.strict.output b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.strict.output new file mode 100644 index 000000000..e39a04e39 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-off.strict.output @@ -0,0 +1 @@ +./analysis/classes/duplicate_local_class_definitions_are_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 diff --git a/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.nonstrict.output b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.nonstrict.output new file mode 100644 index 000000000..e39a04e39 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.nonstrict.output @@ -0,0 +1 @@ +./analysis/classes/duplicate_local_class_definitions_are_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 diff --git a/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.runtime.output b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.strict.output b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.strict.output new file mode 100644 index 000000000..e39a04e39 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/classes/duplicate_local_class_definitions_are_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 diff --git a/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.luau b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.luau new file mode 100644 index 000000000..764d8b2a1 --- /dev/null +++ b/tests/golden/analysis/classes/duplicate_local_class_definitions_are_any.luau @@ -0,0 +1,10 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true +local class Point + public x: number +end +local _first: string = Point + +local class Point + public y: string +end +local _second: number = Point diff --git a/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.nonstrict.output b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.nonstrict.output new file mode 100644 index 000000000..01be2c799 --- /dev/null +++ b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/classes/local_class_duplicating_global_class_is_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 +./analysis/classes/local_class_duplicating_global_class_is_any.luau(7,13): LocalShadow: Variable 'Point' shadows a global variable used at line 2 diff --git a/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.runtime.output b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.strict.output b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.strict.output new file mode 100644 index 000000000..01be2c799 --- /dev/null +++ b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-off.strict.output @@ -0,0 +1,2 @@ +./analysis/classes/local_class_duplicating_global_class_is_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 +./analysis/classes/local_class_duplicating_global_class_is_any.luau(7,13): LocalShadow: Variable 'Point' shadows a global variable used at line 2 diff --git a/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.nonstrict.output b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.nonstrict.output new file mode 100644 index 000000000..01be2c799 --- /dev/null +++ b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.nonstrict.output @@ -0,0 +1,2 @@ +./analysis/classes/local_class_duplicating_global_class_is_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 +./analysis/classes/local_class_duplicating_global_class_is_any.luau(7,13): LocalShadow: Variable 'Point' shadows a global variable used at line 2 diff --git a/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.runtime.output b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.strict.output b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.strict.output new file mode 100644 index 000000000..01be2c799 --- /dev/null +++ b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.flags-on.strict.output @@ -0,0 +1,2 @@ +./analysis/classes/local_class_duplicating_global_class_is_any.luau(7,1): TypeError: Redefinition of type 'Point', previously defined at line 2 +./analysis/classes/local_class_duplicating_global_class_is_any.luau(7,13): LocalShadow: Variable 'Point' shadows a global variable used at line 2 diff --git a/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.luau b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.luau new file mode 100644 index 000000000..850ca5659 --- /dev/null +++ b/tests/golden/analysis/classes/local_class_duplicating_global_class_is_any.luau @@ -0,0 +1,10 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true +class Point + public x: number +end +local _first: string = Point + +local class Point + public y: string +end +local _second: number = Point diff --git a/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.nonstrict.output b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.runtime.output b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.strict.output b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.strict.output new file mode 100644 index 000000000..f18d667b0 --- /dev/null +++ b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-off.strict.output @@ -0,0 +1 @@ +./analysis/classes/pass_self_to_super_constructor_in_later_position.luau(9,27): TypeError: Access to 'self' before all of its fields have been initialized diff --git a/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.nonstrict.output b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.runtime.output b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.strict.output b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.strict.output new file mode 100644 index 000000000..f18d667b0 --- /dev/null +++ b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/classes/pass_self_to_super_constructor_in_later_position.luau(9,27): TypeError: Access to 'self' before all of its fields have been initialized diff --git a/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.luau b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.luau new file mode 100644 index 000000000..fc3fa18e0 --- /dev/null +++ b/tests/golden/analysis/classes/pass_self_to_super_constructor_in_later_position.luau @@ -0,0 +1,11 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true + +open class Base + function __init(self, x) end +end + +class Derived extends Base + function __init(self) + Base.__init(self, self) + end +end diff --git a/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.nonstrict.output b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.runtime.output b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.strict.output b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.strict.output new file mode 100644 index 000000000..a693a9fbb --- /dev/null +++ b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-off.strict.output @@ -0,0 +1 @@ +./analysis/classes/read_self_before_super_constructor_is_an_error.luau(13,15): TypeError: Access to 'self' before all of its fields have been initialized diff --git a/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.nonstrict.output b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.runtime.output b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.strict.output b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.strict.output new file mode 100644 index 000000000..a693a9fbb --- /dev/null +++ b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/classes/read_self_before_super_constructor_is_an_error.luau(13,15): TypeError: Access to 'self' before all of its fields have been initialized diff --git a/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.luau b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.luau new file mode 100644 index 000000000..5bacc4542 --- /dev/null +++ b/tests/golden/analysis/classes/read_self_before_super_constructor_is_an_error.luau @@ -0,0 +1,15 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true + +open class Base + public value: number? + + function __init(self) end +end + +class Derived extends Base + function __init(self) + print(self.value) + Base.__init(self) + print(self.value) + end +end diff --git a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.strict.output b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.strict.output index a56aa0e54..ccfa13588 100644 --- a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.strict.output +++ b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-off.strict.output @@ -1 +1 @@ -./analysis/classes/sqrt_cyclically_inherits_sqrt.luau(3,20): TypeError: Unknown global 'sqrt'; consider assigning to it first +./analysis/classes/sqrt_cyclically_inherits_sqrt.luau(3,20): TypeError: Non-open class sqrt cannot be extended diff --git a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.strict.output b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.strict.output index a56aa0e54..ccfa13588 100644 --- a/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.strict.output +++ b/tests/golden/analysis/classes/sqrt_cyclically_inherits_sqrt.flags-on.strict.output @@ -1 +1 @@ -./analysis/classes/sqrt_cyclically_inherits_sqrt.luau(3,20): TypeError: Unknown global 'sqrt'; consider assigning to it first +./analysis/classes/sqrt_cyclically_inherits_sqrt.luau(3,20): TypeError: Non-open class sqrt cannot be extended diff --git a/tests/golden/analysis/classes/three_step_cyclic_inheritance.flags-off.strict.output b/tests/golden/analysis/classes/three_step_cyclic_inheritance.flags-off.strict.output deleted file mode 100644 index 44e9773e9..000000000 --- a/tests/golden/analysis/classes/three_step_cyclic_inheritance.flags-off.strict.output +++ /dev/null @@ -1,3 +0,0 @@ -./analysis/classes/three_step_cyclic_inheritance.luau(2,22): TypeError: Unknown global 'B'; consider assigning to it first -./analysis/classes/three_step_cyclic_inheritance.luau(5,22): TypeError: Unknown global 'C'; consider assigning to it first -./analysis/classes/three_step_cyclic_inheritance.luau(8,22): TypeError: Cyclic class inheritance detected: C -> A -> B diff --git a/tests/golden/analysis/classes/three_step_cyclic_inheritance.flags-on.strict.output b/tests/golden/analysis/classes/three_step_cyclic_inheritance.flags-on.strict.output deleted file mode 100644 index 44e9773e9..000000000 --- a/tests/golden/analysis/classes/three_step_cyclic_inheritance.flags-on.strict.output +++ /dev/null @@ -1,3 +0,0 @@ -./analysis/classes/three_step_cyclic_inheritance.luau(2,22): TypeError: Unknown global 'B'; consider assigning to it first -./analysis/classes/three_step_cyclic_inheritance.luau(5,22): TypeError: Unknown global 'C'; consider assigning to it first -./analysis/classes/three_step_cyclic_inheritance.luau(8,22): TypeError: Cyclic class inheritance detected: C -> A -> B diff --git a/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.nonstrict.output b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.runtime.output b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.strict.output b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.strict.output new file mode 100644 index 000000000..fb3b43d4f --- /dev/null +++ b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-off.strict.output @@ -0,0 +1 @@ +./analysis/classes/write_self_before_super_constructor_is_an_error.luau(12,21): TypeError: Access to 'self' before all of its fields have been initialized diff --git a/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.nonstrict.output b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.runtime.output b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.strict.output b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.strict.output new file mode 100644 index 000000000..fb3b43d4f --- /dev/null +++ b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.flags-on.strict.output @@ -0,0 +1 @@ +./analysis/classes/write_self_before_super_constructor_is_an_error.luau(12,21): TypeError: Access to 'self' before all of its fields have been initialized diff --git a/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.luau b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.luau new file mode 100644 index 000000000..9d5728cda --- /dev/null +++ b/tests/golden/analysis/classes/write_self_before_super_constructor_is_an_error.luau @@ -0,0 +1,15 @@ +--!golden fflags=DebugLuauUserDefinedClasses=true,DebugLuauUserDefinedClassesRuntime=true + +open class Base + public value: number? + + function __init(self) end +end + +class Derived extends Base + function __init(self) + self.value = 1 + Base.__init(self) + self.value = 2 + end +end diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.nonstrict.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.nonstrict.output deleted file mode 100644 index d3f301a0b..000000000 --- a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.nonstrict.output +++ /dev/null @@ -1 +0,0 @@ -./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau(2,86): TypeError: Unknown global 'integer'; consider assigning to it first diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.runtime.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.runtime.output deleted file mode 100644 index bba4c086a..000000000 --- a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.runtime.output +++ /dev/null @@ -1,3 +0,0 @@ -./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau:2: attempt to index nil with nil -stacktrace: -./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau:2 diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.strict.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.strict.output deleted file mode 100644 index d3f301a0b..000000000 --- a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-off.strict.output +++ /dev/null @@ -1 +0,0 @@ -./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau(2,86): TypeError: Unknown global 'integer'; consider assigning to it first diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.runtime.output b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.runtime.output deleted file mode 100644 index bba4c086a..000000000 --- a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.flags-on.runtime.output +++ /dev/null @@ -1,3 +0,0 @@ -./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau:2: attempt to index nil with nil -stacktrace: -./analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau:2 diff --git a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau b/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau deleted file mode 100644 index 03073567f..000000000 --- a/tests/golden/analysis/fuzzer/fuzzer_normalization_negate_intersection_and_union.luau +++ /dev/null @@ -1,2 +0,0 @@ ---!nonstrict -X = if X[X] then X "" elseif "" == X then X elseif X then X else {[{[{X,n0=X,}]=X,n0=integer.add + X,}]=X,} \ No newline at end of file diff --git a/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.nonstrict.output b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.nonstrict.output new file mode 100644 index 000000000..f15e10488 --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.nonstrict.output @@ -0,0 +1 @@ +./analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau(2,24): DuplicateCondition: Condition has already been checked on column 8 diff --git a/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.runtime.output b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.runtime.output new file mode 100644 index 000000000..f9d52790f --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.runtime.output @@ -0,0 +1 @@ +Warning: unrecognized flag 'LuauDoNotCrashOnRecursiveSetType'. diff --git a/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.strict.output b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.strict.output new file mode 100644 index 000000000..c37f0c6b7 --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-off.strict.output @@ -0,0 +1,2 @@ +./analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau(2,1): TypeError: Unknown global 'x'; consider assigning to it first +./analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau(2,24): DuplicateCondition: Condition has already been checked on column 8 diff --git a/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.nonstrict.output b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.nonstrict.output new file mode 100644 index 000000000..f15e10488 --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.nonstrict.output @@ -0,0 +1 @@ +./analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau(2,24): DuplicateCondition: Condition has already been checked on column 8 diff --git a/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.runtime.output b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.runtime.output new file mode 100644 index 000000000..f9d52790f --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.runtime.output @@ -0,0 +1 @@ +Warning: unrecognized flag 'LuauDoNotCrashOnRecursiveSetType'. diff --git a/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.strict.output b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.strict.output new file mode 100644 index 000000000..c37f0c6b7 --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.flags-on.strict.output @@ -0,0 +1,2 @@ +./analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau(2,1): TypeError: Unknown global 'x'; consider assigning to it first +./analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau(2,24): DuplicateCondition: Condition has already been checked on column 8 diff --git a/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau new file mode 100644 index 000000000..aeadaa854 --- /dev/null +++ b/tests/golden/analysis/fuzzer/fuzzer_recursive_union_intersection_occurs_check.luau @@ -0,0 +1,4 @@ +--!golden fflags=LuauDoNotCrashOnRecursiveSetType +x = if x then x elseif x then x else x +type T = typeof(x) +type U = T \ No newline at end of file diff --git a/tests/golden/analysis/refinements/refinement_should_create_union_of_options.flags-on.strict.output b/tests/golden/analysis/refinements/refinement_should_create_union_of_options.flags-on.strict.output index ffffd7c9b..706814e8f 100644 --- a/tests/golden/analysis/refinements/refinement_should_create_union_of_options.flags-on.strict.output +++ b/tests/golden/analysis/refinements/refinement_should_create_union_of_options.flags-on.strict.output @@ -1,2 +1,2 @@ -./analysis/refinements/refinement_should_create_union_of_options.luau(13,8): TypeError: Expected this to be '(number | ~((boolean | buffer | function | integer | number | table | thread | userdata)?)) & unknown', but got 'boolean'; -`boolean` is not a subtype of `number | ~((boolean | buffer | function | integer | number | table | thread | userdata)?)` +./analysis/refinements/refinement_should_create_union_of_options.luau(13,8): TypeError: Expected this to be '(number | ~((boolean | buffer | function | number | table | thread | userdata)?)) & unknown', but got 'boolean'; +`boolean` is not a subtype of `number | ~((boolean | buffer | function | number | table | thread | userdata)?)` diff --git a/tests/golden/analysis/singletons/oss_2613_variadic_intersection.flags-off.strict.output b/tests/golden/analysis/singletons/oss_2613_variadic_intersection.flags-off.strict.output index 5dedd26bb..d76df51a9 100644 --- a/tests/golden/analysis/singletons/oss_2613_variadic_intersection.flags-off.strict.output +++ b/tests/golden/analysis/singletons/oss_2613_variadic_intersection.flags-off.strict.output @@ -1,3 +1,7 @@ +./analysis/singletons/oss_2613_variadic_intersection.luau(7,12): TypeError: Expected this to be + '"Lit1" | "Lit2"' +but got + '"invalid literal"' ./analysis/singletons/oss_2613_variadic_intersection.luau(8,4): TypeError: Expected this to be '("Lit1" | "Lit2") & ("invalid literal 1" | "invalid literal 2")' but got diff --git a/tests/golden/analysis/tables/indexer_suppression.flags-off.nonstrict.output b/tests/golden/analysis/tables/indexer_suppression.flags-off.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/indexer_suppression.flags-off.runtime.output b/tests/golden/analysis/tables/indexer_suppression.flags-off.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/indexer_suppression.flags-off.strict.output b/tests/golden/analysis/tables/indexer_suppression.flags-off.strict.output new file mode 100644 index 000000000..6a1f68e1a --- /dev/null +++ b/tests/golden/analysis/tables/indexer_suppression.flags-off.strict.output @@ -0,0 +1,2 @@ +./analysis/tables/indexer_suppression.luau(7,33): TypeError: Expected this to be '{string}', but got '{ read [any]: string }'; +the indexer is read-only in the latter type, but the former type requires a read-write indexer diff --git a/tests/golden/analysis/tables/indexer_suppression.flags-on.nonstrict.output b/tests/golden/analysis/tables/indexer_suppression.flags-on.nonstrict.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/indexer_suppression.flags-on.runtime.output b/tests/golden/analysis/tables/indexer_suppression.flags-on.runtime.output new file mode 100644 index 000000000..e69de29bb diff --git a/tests/golden/analysis/tables/indexer_suppression.flags-on.strict.output b/tests/golden/analysis/tables/indexer_suppression.flags-on.strict.output new file mode 100644 index 000000000..60e6d597e --- /dev/null +++ b/tests/golden/analysis/tables/indexer_suppression.flags-on.strict.output @@ -0,0 +1,46 @@ +./analysis/tables/indexer_suppression.luau(1,39): TypeError: Expected this to be + '{read "hello"}' +but got + '{ read [any]: string }'; +this is because + * Expected the indexer key type to be exactly `number`, but got `any` + * Expected the indexer result to be `"hello"`, but got `string` +./analysis/tables/indexer_suppression.luau(2,38): TypeError: Expected this to be + '{read string}' +but got + '{ read [string]: any }'; +this is because + * Expected the indexer key type to be exactly `number`, but got `string` + * Expected the indexer result to be `string`, but got `any` +./analysis/tables/indexer_suppression.luau(3,34): TypeError: Expected this to be '{"hello"}', but got '{ [any]: string }'; +this is because + * Expected the indexer key type to be exactly `number`, but got `any` + * Expected the indexer result to be exactly `"hello"`, but got `string` +./analysis/tables/indexer_suppression.luau(4,33): TypeError: Expected this to be '{string}', but got '{ [string]: any }'; +this is because + * Expected the indexer key type to be exactly `number`, but got `string` + * Expected the indexer result to be exactly `string`, but got `any` +./analysis/tables/indexer_suppression.luau(5,45): TypeError: Expected this to be + '{ [number]: "hello", x: number }' +but got + '{ [any]: string, x: any }'; +this is because + * Expected property `x` to be exactly `number`, but got `any` + * Expected the indexer key type to be exactly `number`, but got `any` + * Expected the indexer result to be exactly `"hello"`, but got `string` +./analysis/tables/indexer_suppression.luau(6,58): TypeError: Expected this to be + '{read {read "hello"}}' +but got + '{read { read [any]: string }}'; +this is because + * Expected the indexer key type of the indexer result to be exactly `number`, but got `any` + * Expected the indexer result of the indexer result to be `"hello"`, but got `string` +./analysis/tables/indexer_suppression.luau(7,33): TypeError: Expected this to be '{string}', but got '{ read [any]: string }'; +the indexer is read-only in the latter type, but the former type requires a read-write indexer +./analysis/tables/indexer_suppression.luau(10,13): TypeError: Expected this to be + '{read "hello"}' +but got + '{ read [any]: string }'; +this is because + * Expected the indexer key type to be exactly `number`, but got `any` + * Expected the indexer result to be `"hello"`, but got `string` diff --git a/tests/golden/analysis/tables/indexer_suppression.luau b/tests/golden/analysis/tables/indexer_suppression.luau new file mode 100644 index 000000000..5e8c174bd --- /dev/null +++ b/tests/golden/analysis/tables/indexer_suppression.luau @@ -0,0 +1,18 @@ +local _: { read [number]: "hello" } = ... :: { read [any]: string } -- Not OK +local _: { read [number]: string } = ... :: { read [string]: any } -- Not OK +local _: { [number]: "hello" } = ... :: { [any]: string } -- Not OK +local _: { [number]: string } = ... :: { [string]: any } -- Not OK +local _: { x: number, [number]: "hello" } = ... :: { x: any, [any]: string } -- Not OK +local _: { read [number]: { read [number]: "hello" } } = ... :: { read [number]: { read [any]: string } } -- Not OK +local _: { [number]: string } = ... :: { read [any]: string } + +local function takesHellos(_t: { read [number]: "hello" }) end +takesHellos(... :: { read [any]: string }) -- Not OK + +-- Everything below this line is OK :) + +local _: { read [number]: string } = ... :: { read [any]: string } +local _: { [number]: string } = ... :: { [any]: string } +local _: { read [number]: "hello" } = ... :: { read [any]: any } +local _: { read [number]: { read [number]: string } } = ... :: { read [number]: { read [any]: string } } + From 7a99f3c19820121f2fa7e4ef58bac7a923e7987c Mon Sep 17 00:00:00 2001 From: Harold Cindy <120691094+HaroldCindy@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:54:42 -0800 Subject: [PATCH 10/13] Be smarter about how we disable GC in ares --- VM/src/ares.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/VM/src/ares.cpp b/VM/src/ares.cpp index 002a5974b..edc5327b0 100644 --- a/VM/src/ares.cpp +++ b/VM/src/ares.cpp @@ -497,21 +497,25 @@ static inline bool ares_type_is_tvalue(AresType type) { * parameters when it goes out of scope. Also withdraws `beforeallocate`, which * would otherwise be asked to measure a tree that isn't rooted yet. */ -struct ScopedDisableGC { - explicit ScopedDisableGC(lua_State *L): +struct ScopedAresDisableGC { + explicit ScopedAresDisableGC(lua_State *L): state(L), threshold(L->global->GCthreshold), + gcdisabled(L->global->gcdisabled), beforealloc(L->global->cb.beforeallocate) { state->global->GCthreshold = SIZE_MAX; + state->global->gcdisabled = 1; state->global->cb.beforeallocate = nullptr; }; - ~ScopedDisableGC() { + ~ScopedAresDisableGC() { state->global->GCthreshold = threshold; + state->global->gcdisabled = gcdisabled; state->global->cb.beforeallocate = beforealloc; } lua_State *state; size_t threshold; + uint8_t gcdisabled; int (*beforealloc)(lua_State *, size_t, size_t); }; @@ -4172,7 +4176,7 @@ void eris_register_perms(lua_State *L, bool for_unpersist) { static void unchecked_persist(lua_State *L, std::ostream *writer) { // pause GC for the duration of serialization - some objects we're creating aren't rooted - ScopedDisableGC _disable_gc(L); + ScopedAresDisableGC _disable_gc(L); eris_ifassert(int old_top=lua_gettop(L)); Info info; /* perms buff rootobj */ @@ -4279,7 +4283,7 @@ unchecked_persist(lua_State *L, std::ostream *writer) { static void unchecked_unpersist(lua_State *L, const char *data, size_t size, void *threaddata) {/* perms str? */ // pause GC for the duration of deserialization - some objects we're creating aren't rooted - ScopedDisableGC _disable_gc(L); + ScopedAresDisableGC _disable_gc(L); eris_ifassert(int old_top = lua_gettop(L)); Info info; From 696a0b284901852ea7e61b693474f512d2811a42 Mon Sep 17 00:00:00 2001 From: Harold Cindy <120691094+HaroldCindy@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:10:31 -0800 Subject: [PATCH 11/13] Add updated bytecode as an exec golden fixture --- .../exec3.0-ares7.0.sluac | Bin 404 -> 412 bytes .../between-handlers/exec3.0-ares7.0.sluac | Bin 1577 -> 1591 bytes .../errored-handler/exec3.0-ares7.0.sluac | Bin 290 -> 296 bytes .../errored-main-lsl/exec3.0-ares7.0.sluac | Bin 49678 -> 49684 bytes .../exec3.0-ares7.0.sluac | Bin 536 -> 546 bytes .../yielded-handler-lsl/exec3.0-ares7.0.sluac | Bin 403 -> 411 bytes .../yielded-handler/exec3.0-ares7.0.sluac | Bin 430 -> 436 bytes .../exec/yielded-main/exec3.0-ares7.0.sluac | Bin 307 -> 311 bytes .../exec/yielded-stdlib/exec3.0-ares7.0.sluac | Bin 4335 -> 4381 bytes 9 files changed, 0 insertions(+), 0 deletions(-) diff --git a/tests/conformance/exec/between-handlers-lsl/exec3.0-ares7.0.sluac b/tests/conformance/exec/between-handlers-lsl/exec3.0-ares7.0.sluac index 2b078fcfa064938db2e597a8273da54a0b4d0142..d8feed98614eff6c249fe08618f115d50b281b9b 100644 GIT binary patch delta 41 wcmbQjJcoILDkI-SwJ=8Ai8VS*3_wzS;(1mkhMb94vY8k{C)+cIFflL#0P-LT_y7O^ delta 32 ocmbQkJcW6JDkJAawXlh`IumQvS(zCa7+ELY%%1GV7{bU50F~tkhX4Qo diff --git a/tests/conformance/exec/between-handlers/exec3.0-ares7.0.sluac b/tests/conformance/exec/between-handlers/exec3.0-ares7.0.sluac index 7fdd3ad9be41a3a853c8ecce400bf4f95be13230..5f924c40d06f05945bc2337a530eb02b6d6efc43 100644 GIT binary patch delta 58 zcmV-A0LA~Q47UuB9RUuJ9j44)1>Fh{jQ{`u delta 38 wcmV+>0NMYy45yN0XreQ?vI0Py(|`1nU6-1p?Cyx&QzG diff --git a/tests/conformance/exec/errored-handler/exec3.0-ares7.0.sluac b/tests/conformance/exec/errored-handler/exec3.0-ares7.0.sluac index d533aca488d0b60bd031ae62b7ebc624efbaa906..23fcecf2f02af01859db7b3f2b6a1c40729aa1b3 100644 GIT binary patch delta 31 ncmZ3)w1R1ZEF<4UIU7cUiBbAY3>FhR&6yaICLTy+VqgLQgGdMF delta 22 ecmZ3%w1{bfEFm`V)K1Cmu~?WC8$Cj0YM3 diff --git a/tests/conformance/exec/errored-main-lsl/exec3.0-ares7.0.sluac b/tests/conformance/exec/errored-main-lsl/exec3.0-ares7.0.sluac index fac68106d2b11e61f1f56182fe6b37ddb2762de5..e3593a5b4b7207f8391eb11112db073c646946ac 100644 GIT binary patch delta 47 ucmeBcVV=^$JVBL_Z=+fbql5?p7%+-4FoGCB0*G!lFmK+<7;%7!fe`@LWC(8n delta 41 pcmbQz!ra%wJVBL_bE8@fqc8&)Fp4oSf*3%8kzw;L#)t!qi~y)I2KfL0 diff --git a/tests/conformance/exec/state-change-pending-lsl/exec3.0-ares7.0.sluac b/tests/conformance/exec/state-change-pending-lsl/exec3.0-ares7.0.sluac index 01733341c7d77357c847af454939f35b55e2fd89..4d692e07208fed74471eb6b9c8e53c7b53cc2668 100644 GIT binary patch delta 49 zcmbQivWR7ZE+gMWy&6XMiL2b07<4Co&;gT5lkFI}m>6; delta 42 scmbQuJehfdDkJAaHQ$LPzCsKjz$nJR2%?#ROooZqb0)hohA=V%0I&H6eEO?F@`Vq^jUUf~Cy diff --git a/tests/conformance/exec/yielded-main/exec3.0-ares7.0.sluac b/tests/conformance/exec/yielded-main/exec3.0-ares7.0.sluac index 6440febcd9183b313cc34eacacf0e7ba0e2f21fc..5559b41866a829cb4a16dd46e813495493553d02 100644 GIT binary patch delta 25 hcmdnYw4G^!EF<4UIWxxOi6Kc$47C%t)i5zI0svp=2LJ#7 delta 19 bcmdnaw3%swEFKuIp^N%GEldS6te}BnQO2qo0nq7K=A=gh~!Mj;3McVcqt#mYO;vQ zB+B^Iujdh4$7c}=ZleRDoNg#9c#+=d=||530|;qR!g@7Ab15*oT96K-uV?8Arlcuj z!f5NoXfbM7fsxmbNcN>ACF)_N0!zV>Ex0l)mlE Y4~dubk4Uied8fca1S``k1((clzGpiyr<2TGO9v8@U<2}YGzhel&IB@(90@tI TSP6;&v*ikz1G9k+ngRh5=y)gs From c02ef82561b2f0f46cfb991350dc9b50f4d5f7d5 Mon Sep 17 00:00:00 2001 From: Harold Cindy <120691094+HaroldCindy@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:49:45 -0800 Subject: [PATCH 12/13] Correct some undefined behavior noted in macos CI --- VM/src/lll.cpp | 4 ++-- VM/src/lnumutils.h | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/VM/src/lll.cpp b/VM/src/lll.cpp index 72a020507..f13870873 100644 --- a/VM/src/lll.cpp +++ b/VM/src/lll.cpp @@ -630,7 +630,7 @@ static int ll_fabs(lua_State *L) static int ll_floor(lua_State *L) { auto val = floor((float)luaL_checknumber(L, 1)); - luaSL_pushnativeinteger(L, (int32_t)val); + luaSL_pushnativeinteger(L, lsl_float_to_int(val)); return 1; } @@ -641,7 +641,7 @@ static int ll_ceil(lua_State *L) if (val != res) ++res; - luaSL_pushnativeinteger(L, (int32_t)res); + luaSL_pushnativeinteger(L, lsl_float_to_int(res)); return 1; } diff --git a/VM/src/lnumutils.h b/VM/src/lnumutils.h index e539f45a6..559ecf45a 100644 --- a/VM/src/lnumutils.h +++ b/VM/src/lnumutils.h @@ -142,7 +142,15 @@ inline int luai_num2int_impl(double d) i = (unsigned int)l; \ } #else -#define luai_num2unsigned(i, n) ((i) = (unsigned)(long long)(n)) +// ServerLua: Safe float-to-unsigned with x86 semantics, out-of-range and NaN give 0 +inline unsigned luai_num2unsigned_safe(double d) +{ + constexpr double kMaxInt64 = 9223372036854775808.0; // 2^63 + if (d >= -kMaxInt64 && d < kMaxInt64) + return (unsigned)(long long)d; + return 0; +} +#define luai_num2unsigned(i, n) ((i) = luai_num2unsigned_safe(n)) #endif #define LUAI_MAXNUM2STR 48 From 09d9e1107b527757cd99d25ec0dda8694ecd5b50 Mon Sep 17 00:00:00 2001 From: Harold Cindy <120691094+HaroldCindy@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:22:11 -0800 Subject: [PATCH 13/13] Avoid YET MORE UB issues in bitlib when using optimization Should probably just ask upstream to do a UBSan build ;) --- Compiler/src/BuiltinFolding.cpp | 39 +++++++++++++++++++++++---------- VM/src/lbitlib.cpp | 15 +++++++++---- VM/src/lbuiltins.cpp | 24 ++++++++++---------- 3 files changed, 50 insertions(+), 28 deletions(-) diff --git a/Compiler/src/BuiltinFolding.cpp b/Compiler/src/BuiltinFolding.cpp index 670071181..c958615b2 100644 --- a/Compiler/src/BuiltinFolding.cpp +++ b/Compiler/src/BuiltinFolding.cpp @@ -139,7 +139,20 @@ static Constant ctypeof(const Constant& c) static uint32_t bit32(double v) { // convert through signed 64-bit integer to match runtime behavior and gracefully truncate negative integers - return uint32_t(int64_t(v)); + // ServerLua: must match luai_num2unsigned_safe, out-of-range and NaN give 0 + constexpr double kMaxInt64 = 9223372036854775808.0; // 2^63 + if (v >= -kMaxInt64 && v < kMaxInt64) + return uint32_t(int64_t(v)); + return 0; +} + +// ServerLua: defined float-to-int for shift counts and field positions, out-of-range and NaN give INT_MIN +static int bitcount(double v) +{ + constexpr double kMaxInt = 2147483648.0; // 2^31 + if (v >= -kMaxInt && v < kMaxInt) + return int(v); + return int(-kMaxInt); } Constant foldBuiltin(AstNameTable& stringTable, int bfid, const Constant* args, size_t count, bool vectorDoublePrecision) @@ -311,7 +324,7 @@ Constant foldBuiltin(AstNameTable& stringTable, int bfid, const Constant* args, if (count == 2 && args[0].type == Constant::Type_Number && args[1].type == Constant::Type_Number) { uint32_t u = bit32(args[0].valueNumber); - int s = int(args[1].valueNumber); + int s = bitcount(args[1].valueNumber); // ServerLua if (unsigned(s) < 32) return cnum(double(uint32_t(int32_t(u) >> s))); @@ -396,8 +409,9 @@ Constant foldBuiltin(AstNameTable& stringTable, int bfid, const Constant* args, (count == 2 || args[2].type == Constant::Type_Number)) { uint32_t u = bit32(args[0].valueNumber); - int f = int(args[1].valueNumber); - int w = count == 2 ? 1 : int(args[2].valueNumber); + // ServerLua: defined float-to-int conversion + int f = bitcount(args[1].valueNumber); + int w = count == 2 ? 1 : bitcount(args[2].valueNumber); if (f >= 0 && w > 0 && f + w <= 32) { @@ -412,9 +426,9 @@ Constant foldBuiltin(AstNameTable& stringTable, int bfid, const Constant* args, if (count == 2 && args[0].type == Constant::Type_Number && args[1].type == Constant::Type_Number) { uint32_t u = bit32(args[0].valueNumber); - int s = int(args[1].valueNumber); + int s = bitcount(args[1].valueNumber); // ServerLua - return cnum(double((u << (s & 31)) | (u >> ((32 - s) & 31)))); + return cnum(double((u << (s & 31)) | (u >> ((32u - unsigned(s)) & 31)))); // ServerLua } break; @@ -422,7 +436,7 @@ Constant foldBuiltin(AstNameTable& stringTable, int bfid, const Constant* args, if (count == 2 && args[0].type == Constant::Type_Number && args[1].type == Constant::Type_Number) { uint32_t u = bit32(args[0].valueNumber); - int s = int(args[1].valueNumber); + int s = bitcount(args[1].valueNumber); // ServerLua if (unsigned(s) < 32) return cnum(double(u << s)); @@ -435,8 +449,9 @@ Constant foldBuiltin(AstNameTable& stringTable, int bfid, const Constant* args, { uint32_t n = bit32(args[0].valueNumber); uint32_t v = bit32(args[1].valueNumber); - int f = int(args[2].valueNumber); - int w = count == 3 ? 1 : int(args[3].valueNumber); + // ServerLua: defined float-to-int conversion + int f = bitcount(args[2].valueNumber); + int w = count == 3 ? 1 : bitcount(args[3].valueNumber); if (f >= 0 && w > 0 && f + w <= 32) { @@ -451,9 +466,9 @@ Constant foldBuiltin(AstNameTable& stringTable, int bfid, const Constant* args, if (count == 2 && args[0].type == Constant::Type_Number && args[1].type == Constant::Type_Number) { uint32_t u = bit32(args[0].valueNumber); - int s = int(args[1].valueNumber); + int s = bitcount(args[1].valueNumber); // ServerLua - return cnum(double((u >> (s & 31)) | (u << ((32 - s) & 31)))); + return cnum(double((u >> (s & 31)) | (u << ((32u - unsigned(s)) & 31)))); // ServerLua } break; @@ -461,7 +476,7 @@ Constant foldBuiltin(AstNameTable& stringTable, int bfid, const Constant* args, if (count == 2 && args[0].type == Constant::Type_Number && args[1].type == Constant::Type_Number) { uint32_t u = bit32(args[0].valueNumber); - int s = int(args[1].valueNumber); + int s = bitcount(args[1].valueNumber); // ServerLua if (unsigned(s) < 32) return cnum(double(u >> s)); diff --git a/VM/src/lbitlib.cpp b/VM/src/lbitlib.cpp index a08809a24..d21331f5a 100644 --- a/VM/src/lbitlib.cpp +++ b/VM/src/lbitlib.cpp @@ -99,11 +99,17 @@ static int b_not(lua_State* L) return 1; } +// ServerLua: negate a shift count without overflowing on INT_MIN, any magnitude past NBITS shifts everything out anyway +static int negshift(int i) +{ + return i < -NBITS ? NBITS : -i; +} + static int b_shift(lua_State* L, b_uint r, int i) { if (i < 0) { // shift right? - i = -i; + i = negshift(i); // ServerLua r = trim(r); if (i >= NBITS) r = 0; @@ -129,7 +135,7 @@ static int b_lshift(lua_State* L) static int b_rshift(lua_State* L) { - return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkinteger(L, 2)); + return b_shift(L, luaL_checkunsigned(L, 1), negshift(luaL_checkinteger(L, 2))); // ServerLua } static int b_arshift(lua_State* L) @@ -137,7 +143,7 @@ static int b_arshift(lua_State* L) b_uint r = luaL_checkunsigned(L, 1); int i = luaL_checkinteger(L, 2); if (i < 0 || !(r & ((b_uint)1 << (NBITS - 1)))) - return b_shift(L, r, -i); + return b_shift(L, r, negshift(i)); // ServerLua else { // arithmetic shift for 'negative' number if (i >= NBITS) @@ -167,7 +173,8 @@ static int b_lrot(lua_State* L) static int b_rrot(lua_State* L) { - return b_rot(L, -luaL_checkinteger(L, 2)); + // ServerLua: negate in unsigned so INT_MIN doesn't overflow, b_rot only uses the low bits + return b_rot(L, int(0u - unsigned(luaL_checkinteger(L, 2)))); } /* diff --git a/VM/src/lbuiltins.cpp b/VM/src/lbuiltins.cpp index 8def78b39..43f113fd8 100644 --- a/VM/src/lbuiltins.cpp +++ b/VM/src/lbuiltins.cpp @@ -436,7 +436,7 @@ static int luauF_arshift(lua_State* L, StkId res, TValue* arg0, int nresults, St unsigned u; luai_num2unsigned(u, a1); - int s = int(a2); + int s = luai_num2int_safe(a2); // ServerLua // note: we only specialize fast-path that doesn't require further conditionals (negative shifts and shifts greater or equal to bit width can // be handled generically) @@ -608,7 +608,7 @@ static int luauF_extract(lua_State* L, StkId res, TValue* arg0, int nresults, St unsigned n; luai_num2unsigned(n, a1); - int f = int(a2); + int f = luai_num2int_safe(a2); // ServerLua if (nparams == 2) { @@ -624,7 +624,7 @@ static int luauF_extract(lua_State* L, StkId res, TValue* arg0, int nresults, St else if (ttisnumber(args + 1)) { double a3 = nvalue(args + 1); - int w = int(a3); + int w = luai_num2int_safe(a3); // ServerLua if (f >= 0 && w > 0 && f + w <= 32) { @@ -649,13 +649,13 @@ static int luauF_lrotate(lua_State* L, StkId res, TValue* arg0, int nresults, St unsigned u; luai_num2unsigned(u, a1); - int s = int(a2); + int s = luai_num2int_safe(a2); // ServerLua // MSVC doesn't recognize the rotate form that is UB-safe #ifdef _MSC_VER uint32_t r = _rotl(u, s); #else - uint32_t r = (u << (s & 31)) | (u >> ((32 - s) & 31)); + uint32_t r = (u << (s & 31)) | (u >> ((32u - unsigned(s)) & 31)); // ServerLua #endif setnvalue(res, double(r)); @@ -674,7 +674,7 @@ static int luauF_lshift(lua_State* L, StkId res, TValue* arg0, int nresults, Stk unsigned u; luai_num2unsigned(u, a1); - int s = int(a2); + int s = luai_num2int_safe(a2); // ServerLua // note: we only specialize fast-path that doesn't require further conditionals (negative shifts and shifts greater or equal to bit width can // be handled generically) @@ -701,7 +701,7 @@ static int luauF_replace(lua_State* L, StkId res, TValue* arg0, int nresults, St unsigned n, v; luai_num2unsigned(n, a1); luai_num2unsigned(v, a2); - int f = int(a3); + int f = luai_num2int_safe(a3); // ServerLua if (nparams == 3) { @@ -717,7 +717,7 @@ static int luauF_replace(lua_State* L, StkId res, TValue* arg0, int nresults, St else if (ttisnumber(args + 2)) { double a4 = nvalue(args + 2); - int w = int(a4); + int w = luai_num2int_safe(a4); // ServerLua if (f >= 0 && w > 0 && f + w <= 32) { @@ -742,13 +742,13 @@ static int luauF_rrotate(lua_State* L, StkId res, TValue* arg0, int nresults, St unsigned u; luai_num2unsigned(u, a1); - int s = int(a2); + int s = luai_num2int_safe(a2); // ServerLua // MSVC doesn't recognize the rotate form that is UB-safe #ifdef _MSC_VER uint32_t r = _rotr(u, s); #else - uint32_t r = (u >> (s & 31)) | (u << ((32 - s) & 31)); + uint32_t r = (u >> (s & 31)) | (u << ((32u - unsigned(s)) & 31)); // ServerLua #endif setnvalue(res, double(r)); @@ -767,7 +767,7 @@ static int luauF_rshift(lua_State* L, StkId res, TValue* arg0, int nresults, Stk unsigned u; luai_num2unsigned(u, a1); - int s = int(a2); + int s = luai_num2int_safe(a2); // ServerLua // note: we only specialize fast-path that doesn't require further conditionals (negative shifts and shifts greater or equal to bit width can // be handled generically) @@ -1193,7 +1193,7 @@ static int luauF_extractk(lua_State* L, StkId res, TValue* arg0, int nresults, S unsigned n; luai_num2unsigned(n, a1); - int fw = int(a2); + int fw = luai_num2int_safe(a2); // ServerLua int f = fw & 31; int w1 = fw >> 5;