luau/Analysis/src/Type.cpp

1392 lines
33 KiB
C++
Raw Normal View History

// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
#include "Luau/Type.h"
#include "Luau/BuiltinDefinitions.h"
#include "Luau/Common.h"
#include "Luau/ConstraintSolver.h"
#include "Luau/DenseHash.h"
#include "Luau/Error.h"
#include "Luau/RecursionCounter.h"
#include "Luau/StringUtils.h"
#include "Luau/ToString.h"
#include "Luau/TypeFunction.h"
#include "Luau/TypeInfer.h"
#include "Luau/TypePack.h"
#include "Luau/VecDeque.h"
#include "Luau/VisitType.h"
#include <algorithm>
#include <optional>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
LUAU_FASTFLAG(DebugLuauFreezeArena)
LUAU_FASTINTVARIABLE(LuauTypeMaximumStringifierLength, 500)
LUAU_FASTINTVARIABLE(LuauTableTypeMaximumStringifierLength, 0)
LUAU_FASTINT(LuauTypeInferRecursionLimit)
LUAU_FASTFLAG(LuauInstantiateInSubtyping)
namespace Luau
{
// LUAU_NOINLINE prevents unwrapLazy from being inlined into advance below; advance is important to keep inlineable
static LUAU_NOINLINE TypeId unwrapLazy(LazyType* ltv)
{
TypeId unwrapped = ltv->unwrapped.load();
if (unwrapped)
return unwrapped;
ltv->unwrap(*ltv);
unwrapped = ltv->unwrapped.load();
if (!unwrapped)
throw InternalCompilerError("Lazy Type didn't fill in unwrapped type field");
if (get<LazyType>(unwrapped))
throw InternalCompilerError("Lazy Type cannot resolve to another Lazy Type");
return unwrapped;
}
TypeId follow(TypeId t)
{
Sync to upstream/release/591 (#1012) * Fix a use-after-free bug in the new type cloning algorithm * Tighten up the type of `coroutine.wrap`. It is now `<A..., R...>(f: (A...) -> R...) -> ((A...) -> R...)` * Break `.luaurc` out into a separate library target `Luau.Config`. This makes it easier for applications to reason about config files without also depending on the type inference engine. * Move typechecking limits into `FrontendOptions`. This allows embedders more finely-grained control over autocomplete's internal time limits. * Fix stability issue with debugger onprotectederror callback allowing break in non-yieldable contexts New solver: * Initial work toward [Local Type Inference](https://github.com/Roblox/luau/blob/0e1082108fd6fb3a32dfdf5f1766ea3fc1391328/rfcs/local-type-inference.md) * Introduce a new subtyping test. This will be much nicer than the old test because it is completely separate both from actual type inference and from error reporting. Native code generation: * Added function to compute iterated dominance frontier * Optimize barriers in SET_UPVALUE when tag is known * Cache lua_State::global in a register on A64 * Optimize constant stores in A64 lowering * Track table array size state to optimize array size checks * Add split tag/value store into a VM register * Check that spills can outlive the block only in specific conditions --------- Co-authored-by: Arseny Kapoulkine <arseny.kapoulkine@gmail.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2023-08-18 19:15:41 +01:00
return follow(t, FollowOption::Normal);
}
TypeId follow(TypeId t, FollowOption followOption)
{
return follow(
t,
followOption,
nullptr,
[](const void*, TypeId t) -> TypeId
{
return t;
}
);
}
TypeId follow(TypeId t, const void* context, TypeId (*mapper)(const void*, TypeId))
{
Sync to upstream/release/591 (#1012) * Fix a use-after-free bug in the new type cloning algorithm * Tighten up the type of `coroutine.wrap`. It is now `<A..., R...>(f: (A...) -> R...) -> ((A...) -> R...)` * Break `.luaurc` out into a separate library target `Luau.Config`. This makes it easier for applications to reason about config files without also depending on the type inference engine. * Move typechecking limits into `FrontendOptions`. This allows embedders more finely-grained control over autocomplete's internal time limits. * Fix stability issue with debugger onprotectederror callback allowing break in non-yieldable contexts New solver: * Initial work toward [Local Type Inference](https://github.com/Roblox/luau/blob/0e1082108fd6fb3a32dfdf5f1766ea3fc1391328/rfcs/local-type-inference.md) * Introduce a new subtyping test. This will be much nicer than the old test because it is completely separate both from actual type inference and from error reporting. Native code generation: * Added function to compute iterated dominance frontier * Optimize barriers in SET_UPVALUE when tag is known * Cache lua_State::global in a register on A64 * Optimize constant stores in A64 lowering * Track table array size state to optimize array size checks * Add split tag/value store into a VM register * Check that spills can outlive the block only in specific conditions --------- Co-authored-by: Arseny Kapoulkine <arseny.kapoulkine@gmail.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2023-08-18 19:15:41 +01:00
return follow(t, FollowOption::Normal, context, mapper);
}
TypeId follow(TypeId t, FollowOption followOption, const void* context, TypeId (*mapper)(const void*, TypeId))
{
auto advance = [followOption, context, mapper](TypeId ty) -> std::optional<TypeId>
{
TypeId mapped = mapper(context, ty);
if (auto btv = get<Unifiable::Bound<TypeId>>(mapped))
return btv->boundTo;
if (auto ttv = get<TableType>(mapped))
return ttv->boundTo;
Sync to upstream/release/591 (#1012) * Fix a use-after-free bug in the new type cloning algorithm * Tighten up the type of `coroutine.wrap`. It is now `<A..., R...>(f: (A...) -> R...) -> ((A...) -> R...)` * Break `.luaurc` out into a separate library target `Luau.Config`. This makes it easier for applications to reason about config files without also depending on the type inference engine. * Move typechecking limits into `FrontendOptions`. This allows embedders more finely-grained control over autocomplete's internal time limits. * Fix stability issue with debugger onprotectederror callback allowing break in non-yieldable contexts New solver: * Initial work toward [Local Type Inference](https://github.com/Roblox/luau/blob/0e1082108fd6fb3a32dfdf5f1766ea3fc1391328/rfcs/local-type-inference.md) * Introduce a new subtyping test. This will be much nicer than the old test because it is completely separate both from actual type inference and from error reporting. Native code generation: * Added function to compute iterated dominance frontier * Optimize barriers in SET_UPVALUE when tag is known * Cache lua_State::global in a register on A64 * Optimize constant stores in A64 lowering * Track table array size state to optimize array size checks * Add split tag/value store into a VM register * Check that spills can outlive the block only in specific conditions --------- Co-authored-by: Arseny Kapoulkine <arseny.kapoulkine@gmail.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2023-08-18 19:15:41 +01:00
if (auto ltv = getMutable<LazyType>(mapped); ltv && followOption != FollowOption::DisableLazyTypeThunks)
return unwrapLazy(ltv);
return std::nullopt;
};
TypeId cycleTester = t; // Null once we've determined that there is no cycle
if (auto a = advance(cycleTester))
cycleTester = *a;
else
return t;
if (!advance(cycleTester)) // Short circuit traversal for the rather common case when advance(advance(t)) == null
return cycleTester;
while (true)
{
auto a1 = advance(t);
if (a1)
t = *a1;
else
return t;
if (nullptr != cycleTester)
{
auto a2 = advance(cycleTester);
if (a2)
{
auto a3 = advance(*a2);
if (a3)
cycleTester = *a3;
else
cycleTester = nullptr;
}
else
cycleTester = nullptr;
if (t == cycleTester)
throw InternalCompilerError("Luau::follow detected a Type cycle!!");
}
}
}
std::vector<TypeId> flattenIntersection(TypeId ty)
{
if (!get<IntersectionType>(follow(ty)))
return {ty};
std::unordered_set<TypeId> seen;
VecDeque<TypeId> queue{ty};
std::vector<TypeId> result;
while (!queue.empty())
{
TypeId current = follow(queue.front());
queue.pop_front();
if (seen.find(current) != seen.end())
continue;
seen.insert(current);
if (auto itv = get<IntersectionType>(current))
{
for (TypeId ty : itv->parts)
queue.push_back(ty);
}
else
result.push_back(current);
}
return result;
}
bool isPrim(TypeId ty, PrimitiveType::Type primType)
{
auto p = get<PrimitiveType>(follow(ty));
return p && p->type == primType;
}
bool isNil(TypeId ty)
{
return isPrim(ty, PrimitiveType::NilType);
}
bool isBoolean(TypeId ty)
{
if (isPrim(ty, PrimitiveType::Boolean) || get<BooleanSingleton>(get<SingletonType>(follow(ty))))
2022-02-24 23:53:37 +00:00
return true;
if (auto utv = get<UnionType>(follow(ty)))
2022-02-24 23:53:37 +00:00
return std::all_of(begin(utv), end(utv), isBoolean);
2022-02-24 23:53:37 +00:00
return false;
}
bool isNumber(TypeId ty)
{
return isPrim(ty, PrimitiveType::Number);
}
2022-03-04 16:36:33 +00:00
// Returns true when ty is a subtype of string
bool isString(TypeId ty)
{
2022-07-14 23:52:26 +01:00
ty = follow(ty);
if (isPrim(ty, PrimitiveType::String) || get<StringSingleton>(get<SingletonType>(ty)))
2022-02-24 23:53:37 +00:00
return true;
if (auto utv = get<UnionType>(ty))
2022-02-24 23:53:37 +00:00
return std::all_of(begin(utv), end(utv), isString);
2022-02-24 23:53:37 +00:00
return false;
}
2022-03-04 16:36:33 +00:00
// Returns true when ty is a supertype of string
bool maybeString(TypeId ty)
{
2022-06-24 02:56:00 +01:00
ty = follow(ty);
2022-04-15 00:57:43 +01:00
if (isPrim(ty, PrimitiveType::String) || get<AnyType>(ty))
2022-07-14 23:52:26 +01:00
return true;
2022-03-04 16:36:33 +00:00
if (auto utv = get<UnionType>(ty))
2022-06-24 02:56:00 +01:00
return std::any_of(begin(utv), end(utv), maybeString);
2022-03-04 16:36:33 +00:00
2022-06-24 02:56:00 +01:00
return false;
2022-03-04 16:36:33 +00:00
}
bool isThread(TypeId ty)
{
return isPrim(ty, PrimitiveType::Thread);
}
Sync to upstream/release/603 (#1097) # What's changed? - Record the location of properties for table types (closes #802) - Implement stricter UTF-8 validations as per the RFC (https://github.com/luau-lang/rfcs/pull/1) - Implement `buffer` as a new type in both the old and new solvers. - Changed errors produced by some `buffer` builtins to be a bit more generic to avoid platform-dependent error messages. - Fixed a bug where `Unifier` would copy some persistent types, tripping some internal assertions. - Type checking rules on relational operators is now a little bit more lax. - Improve dead code elimination for some `if` statements with complex always-false conditions ## New type solver - Dataflow analysis now generates phi nodes on exit of branches. - Dataflow analysis avoids producing a new definition for locals or properties that are not owned by that loop. - If a function parameter has been constrained to `never`, report errors at all uses of that parameter within that function. - Switch to using the new `Luau::Set` to replace `std::unordered_set` to alleviate some poor allocation characteristics which was negatively affecting overall performance. - Subtyping can now report many failing reasons instead of just the first one that we happened to find during the test. - Subtyping now also report reasons for type pack mismatches. - When visiting `if` statements or expressions, the resulting context are the common terms in both branches. ## Native codegen - Implement support for `buffer` builtins to its IR for x64 and A64. - Optimized `table.insert` by not inserting a table barrier if it is fastcalled with a constant. ## Internal Contributors Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Arseny Kapoulkine <arseny@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2023-11-10 21:10:07 +00:00
bool isBuffer(TypeId ty)
{
return isPrim(ty, PrimitiveType::Buffer);
}
bool isOptional(TypeId ty)
{
if (isNil(ty))
return true;
2022-03-18 00:46:04 +00:00
ty = follow(ty);
if (get<AnyType>(ty) || get<UnknownType>(ty))
2022-03-18 00:46:04 +00:00
return true;
auto utv = get<UnionType>(ty);
2022-02-24 23:53:37 +00:00
if (!utv)
return false;
2022-02-24 23:53:37 +00:00
2022-05-20 01:02:24 +01:00
return std::any_of(begin(utv), end(utv), isOptional);
}
bool isTableIntersection(TypeId ty)
{
if (!get<IntersectionType>(follow(ty)))
return false;
std::vector<TypeId> parts = flattenIntersection(ty);
return std::all_of(parts.begin(), parts.end(), getTableType);
}
bool isTableUnion(TypeId ty)
{
const UnionType* ut = get<UnionType>(follow(ty));
if (!ut)
return false;
return std::all_of(begin(ut), end(ut), getTableType);
}
bool isOverloadedFunction(TypeId ty)
{
if (!get<IntersectionType>(follow(ty)))
return false;
auto isFunction = [](TypeId part) -> bool
{
return get<FunctionType>(part);
};
std::vector<TypeId> parts = flattenIntersection(ty);
return std::all_of(parts.begin(), parts.end(), isFunction);
}
std::optional<TypeId> getMetatable(TypeId type, NotNull<BuiltinTypes> builtinTypes)
{
2022-07-14 23:52:26 +01:00
type = follow(type);
if (const MetatableType* mtType = get<MetatableType>(type))
return mtType->metatable;
else if (const ClassType* classType = get<ClassType>(type))
return classType->metatable;
2022-02-24 23:53:37 +00:00
else if (isString(type))
{
auto ptv = get<PrimitiveType>(builtinTypes->stringType);
2022-02-24 23:53:37 +00:00
LUAU_ASSERT(ptv && ptv->metatable);
return ptv->metatable;
}
2022-02-24 23:53:37 +00:00
return std::nullopt;
}
const TableType* getTableType(TypeId type)
{
2022-02-24 23:53:37 +00:00
type = follow(type);
2022-02-04 16:45:57 +00:00
if (const TableType* ttv = get<TableType>(type))
return ttv;
else if (const MetatableType* mtv = get<MetatableType>(type))
return get<TableType>(follow(mtv->table));
else
return nullptr;
}
TableType* getMutableTableType(TypeId type)
{
return const_cast<TableType*>(getTableType(type));
}
const std::string* getName(TypeId type)
{
type = follow(type);
if (auto mtv = get<MetatableType>(type))
{
if (mtv->syntheticName)
return &*mtv->syntheticName;
2022-02-24 23:53:37 +00:00
type = follow(mtv->table);
}
if (auto ttv = get<TableType>(type))
{
if (ttv->name)
return &*ttv->name;
if (ttv->syntheticName)
return &*ttv->syntheticName;
}
return nullptr;
}
2022-03-24 22:04:14 +00:00
std::optional<ModuleName> getDefinitionModuleName(TypeId type)
{
type = follow(type);
if (auto ttv = get<TableType>(type))
2022-03-24 22:04:14 +00:00
{
if (!ttv->definitionModuleName.empty())
return ttv->definitionModuleName;
}
else if (auto ftv = get<FunctionType>(type))
2022-03-24 22:04:14 +00:00
{
if (ftv->definition)
return ftv->definition->definitionModuleName;
}
else if (auto ctv = get<ClassType>(type))
2022-04-21 22:44:27 +01:00
{
if (!ctv->definitionModuleName.empty())
return ctv->definitionModuleName;
}
2022-03-24 22:04:14 +00:00
return std::nullopt;
}
bool isSubset(const UnionType& super, const UnionType& sub)
{
std::unordered_set<TypeId> superTypes;
for (TypeId id : super.options)
superTypes.insert(id);
for (TypeId id : sub.options)
{
if (superTypes.find(id) == superTypes.end())
return false;
}
return true;
}
Sync to upstream/release/572 (#899) * Fixed exported types not being suggested in autocomplete * `T...` is now convertible to `...any` (Fixes https://github.com/Roblox/luau/issues/767) * Fixed issue with `T?` not being convertible to `T | T` or `T?` (sometimes when internal pointer identity is different) * Fixed potential crash in missing table key error suggestion to use a similar existing key * `lua_topointer` now returns a pointer for strings C++ API Changes: * `prepareModuleScope` callback has moved from TypeChecker to Frontend * For LSPs, AstQuery functions (and `isWithinComment`) can be used without full Frontend data A lot of changes in our two experimental components as well. In our work on the new type-solver, the following issues were fixed: * Fixed table union and intersection indexing * Correct custom type environments are now used * Fixed issue with values of `free & number` type not accepted in numeric operations And these are the changes in native code generation (JIT): * arm64 lowering is almost complete with support for 99% of IR commands and all fastcalls * Fixed x64 assembly encoding for extended byte registers * More external x64 calls are aware of register allocator * `math.min`/`math.max` with more than 2 arguments are now lowered to IR as well * Fixed correctness issues with `math` library calls with multiple results in variadic context and with x64 register conflicts * x64 register allocator learnt to restore values from VM memory instead of always using stack spills * x64 exception unwind information now supports multiple functions and fixes function start offset in Dwarf2 info
2023-04-14 19:06:22 +01:00
bool hasPrimitiveTypeInIntersection(TypeId ty, PrimitiveType::Type primTy)
{
TypeId tf = follow(ty);
if (isPrim(tf, primTy))
return true;
Sync to upstream/release/572 (#899) * Fixed exported types not being suggested in autocomplete * `T...` is now convertible to `...any` (Fixes https://github.com/Roblox/luau/issues/767) * Fixed issue with `T?` not being convertible to `T | T` or `T?` (sometimes when internal pointer identity is different) * Fixed potential crash in missing table key error suggestion to use a similar existing key * `lua_topointer` now returns a pointer for strings C++ API Changes: * `prepareModuleScope` callback has moved from TypeChecker to Frontend * For LSPs, AstQuery functions (and `isWithinComment`) can be used without full Frontend data A lot of changes in our two experimental components as well. In our work on the new type-solver, the following issues were fixed: * Fixed table union and intersection indexing * Correct custom type environments are now used * Fixed issue with values of `free & number` type not accepted in numeric operations And these are the changes in native code generation (JIT): * arm64 lowering is almost complete with support for 99% of IR commands and all fastcalls * Fixed x64 assembly encoding for extended byte registers * More external x64 calls are aware of register allocator * `math.min`/`math.max` with more than 2 arguments are now lowered to IR as well * Fixed correctness issues with `math` library calls with multiple results in variadic context and with x64 register conflicts * x64 register allocator learnt to restore values from VM memory instead of always using stack spills * x64 exception unwind information now supports multiple functions and fixes function start offset in Dwarf2 info
2023-04-14 19:06:22 +01:00
for (auto t : flattenIntersection(tf))
return isPrim(follow(t), primTy);
return false;
}
// When typechecking an assignment `x = e`, we typecheck `x:T` and `e:U`,
// then instantiate U if `isGeneric(U)` is true, and `maybeGeneric(T)` is false.
bool isGeneric(TypeId ty)
{
LUAU_ASSERT(!FFlag::LuauInstantiateInSubtyping);
ty = follow(ty);
if (auto ftv = get<FunctionType>(ty))
return ftv->generics.size() > 0 || ftv->genericPacks.size() > 0;
else
// TODO: recurse on type synonyms CLI-39914
// TODO: recurse on table types CLI-39914
return false;
}
bool maybeGeneric(TypeId ty)
{
LUAU_ASSERT(!FFlag::LuauInstantiateInSubtyping);
ty = follow(ty);
if (get<FreeType>(ty))
return true;
if (auto ttv = get<TableType>(ty))
{
// TODO: recurse on table types CLI-39914
(void)ttv;
return true;
}
if (auto itv = get<IntersectionType>(ty))
{
return std::any_of(begin(itv), end(itv), maybeGeneric);
}
return isGeneric(ty);
}
bool maybeSingleton(TypeId ty)
{
ty = follow(ty);
if (get<SingletonType>(ty))
return true;
if (const UnionType* utv = get<UnionType>(ty))
for (TypeId option : utv)
if (get<SingletonType>(follow(option)))
return true;
Sync to upstream/release/610 (#1154) # What's changed? * Check interrupt handler inside the pattern match engine to eliminate potential for programs to hang during string library function execution. * Allow iteration over table properties to pass the old type solver. ### Native Code Generation * Use in-place memory operands for math library operations on x64. * Replace opaque bools with separate enum classes in IrDump to improve code maintainability. * Translate operations on inferred vectors to IR. * Enable support for debugging native-compiled functions in Roblox Studio. ### New Type Solver * Rework type inference for boolean and string literals to introduce bounded free types (bounded below by the singleton type, and above by the primitive type) and reworked primitive type constraint to decide which is the appropriate type for the literal. * Introduce `FunctionCheckConstraint` to handle bidirectional typechecking for function calls, pushing the expected parameter types from the function onto the arguments. * Introduce `union` and `intersect` type families to compute deferred simplified unions and intersections to be employed by the constraint generation logic in the new solver. * Implement support for expanding the domain of local types in `Unifier2`. * Rework type inference for iteration variables bound by for in loops to use local types. * Change constraint blocking logic to use a set to prevent accidental re-blocking. * Add logic to detect missing return statements in functions. ### Internal Contributors Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Vighnesh <vvijay@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-01-27 03:20:56 +00:00
if (const IntersectionType* itv = get<IntersectionType>(ty))
for (TypeId part : itv)
if (maybeSingleton(part)) // will i regret this?
return true;
if (const TypeFunctionInstanceType* tfit = get<TypeFunctionInstanceType>(ty))
if (tfit->function->name == "keyof" || tfit->function->name == "rawkeyof")
return true;
return false;
}
bool hasLength(TypeId ty, DenseHashSet<TypeId>& seen, int* recursionCount)
{
2022-06-24 02:56:00 +01:00
RecursionLimiter _rl(recursionCount, FInt::LuauTypeInferRecursionLimit);
ty = follow(ty);
if (seen.contains(ty))
return true;
Sync to upstream/release/562 (#828) * Fixed rare use-after-free in analysis during table unification A lot of work these past months went into two new Luau components: * A near full rewrite of the typechecker using a new deferred constraint resolution system * Native code generation for AoT/JiT compilation of VM bytecode into x64 (avx)/arm64 instructions Both of these components are far from finished and we don't provide documentation on building and using them at this point. However, curious community members expressed interest in learning about changes that go into these components each week, so we are now listing them here in the 'sync' pull request descriptions. --- New typechecker can be enabled by setting DebugLuauDeferredConstraintResolution flag to 'true'. It is considered unstable right now, so try it at your own risk. Even though it already provides better type inference than the current one in some cases, our main goal right now is to reach feature parity with current typechecker. Features which improve over the capabilities of the current typechecker are marked as '(NEW)'. Changes to new typechecker: * Regular for loop index and parameters are now typechecked * Invalid type annotations on local variables are ignored to improve autocomplete * Fixed missing autocomplete type suggestions for function arguments * Type reduction is now performed to produce simpler types to be presented to the user (error messages, custom LSPs) * Internally, complex types like '((number | string) & ~(false?)) | string' can be produced, which is just 'string | number' when simplified * Fixed spots where support for unknown and never types was missing * (NEW) Length operator '#' is now valid to use on top table type, this type comes up when doing typeof(x) == "table" guards and isn't available in current typechecker --- Changes to native code generation: * Additional math library fast calls are now lowered to x64: math.ldexp, math.round, math.frexp, math.modf, math.sign and math.clamp
2023-02-03 19:26:13 +00:00
if (isString(ty) || isPrim(ty, PrimitiveType::Table) || get<AnyType>(ty) || get<TableType>(ty) || get<MetatableType>(ty))
return true;
if (auto uty = get<UnionType>(ty))
{
seen.insert(ty);
for (TypeId part : uty->options)
{
if (!hasLength(part, seen, recursionCount))
return false;
}
return true;
}
if (auto ity = get<IntersectionType>(ty))
{
seen.insert(ty);
for (TypeId part : ity->parts)
{
if (hasLength(part, seen, recursionCount))
return true;
}
return false;
}
return false;
}
FreeType::FreeType(TypeLevel level)
: index(Unifiable::freshIndex())
, level(level)
, scope(nullptr)
{
}
FreeType::FreeType(Scope* scope)
: index(Unifiable::freshIndex())
, level{}
, scope(scope)
{
}
FreeType::FreeType(Scope* scope, TypeLevel level)
: index(Unifiable::freshIndex())
, level(level)
, scope(scope)
{
}
FreeType::FreeType(Scope* scope, TypeId lowerBound, TypeId upperBound)
: index(Unifiable::freshIndex())
, scope(scope)
, lowerBound(lowerBound)
, upperBound(upperBound)
{
}
GenericType::GenericType()
: index(Unifiable::freshIndex())
, name("g" + std::to_string(index))
{
}
GenericType::GenericType(TypeLevel level)
: index(Unifiable::freshIndex())
, level(level)
, name("g" + std::to_string(index))
{
}
GenericType::GenericType(const Name& name)
: index(Unifiable::freshIndex())
, name(name)
, explicitName(true)
{
}
GenericType::GenericType(Scope* scope)
: index(Unifiable::freshIndex())
, scope(scope)
{
}
GenericType::GenericType(TypeLevel level, const Name& name)
: index(Unifiable::freshIndex())
, level(level)
, name(name)
, explicitName(true)
{
}
GenericType::GenericType(Scope* scope, const Name& name)
: index(Unifiable::freshIndex())
, scope(scope)
, name(name)
, explicitName(true)
{
}
BlockedType::BlockedType()
: index(Unifiable::freshIndex())
2022-06-17 02:05:14 +01:00
{
}
Sync to upstream/release/622 (#1232) # What's changed? * Improved the actual message for the type errors for `cannot call non-function` when attempting to call a union of functions/callable tables. The error now correctly explains the issue is an inability to determine the return type of the call in this situation. * Resolve an issue where tables and metatables were not correctly being cloned during instantiation (fixes #1176). * Refactor `luaM_getnextgcopage` to `luaM_getnextpage` (generally removing `gco` prefix where appropriate). * Optimize `table.move` between tables for large ranges of elements. * Reformat a bunch of code automatically using `clang-format`. ### New Type Solver * Clean up minimally-used or unused constraints in the constraint solver (`InstantiationConstraint`, `SetOpConstraint`, `SingletonOrTopTypeConstraint`). * Add a builtin `singleton` type family to replace `SingletonOrTopTypeConstraint` when inferring refinements. * Fixed a crash involving type path reasoning by recording when type family reduction has taken place in the path. * Improved constraint ordering by blocking on unreduced types families that are not yet proven uninhabitable. * Improved the handling of `SetIndexerConstraints` for both better inference quality and to resolve crashes. * Fix a crash when normalizing cyclic unions of intersections. * Fix a crash when normalizing an intersection with the negation of `unknown`. * Fix a number of crashes caused by missing `follow` calls on `TypeId`s. * Changed type family reduction to correctly use a semantic notion of uninhabited types, rather than checking for `never` types specifically. * Refactor the `union` and `intersect` type families to be variadic. ### Native Code Generation * Improve translation for userdata key get/set and userdata/vector namecall. * Provide `[top level]` and `[anonymous]` as function names to `FunctionStats` as appropriate when no function name is available. * Disable unwind support on Android platforms since it is unsupported. * --- ### Internal Contributors Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vighnesh Vijay <vvijay@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Vighnesh <vvijay@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-04-19 22:48:02 +01:00
Constraint* BlockedType::getOwner() const
{
return owner;
}
Sync to upstream/release/622 (#1232) # What's changed? * Improved the actual message for the type errors for `cannot call non-function` when attempting to call a union of functions/callable tables. The error now correctly explains the issue is an inability to determine the return type of the call in this situation. * Resolve an issue where tables and metatables were not correctly being cloned during instantiation (fixes #1176). * Refactor `luaM_getnextgcopage` to `luaM_getnextpage` (generally removing `gco` prefix where appropriate). * Optimize `table.move` between tables for large ranges of elements. * Reformat a bunch of code automatically using `clang-format`. ### New Type Solver * Clean up minimally-used or unused constraints in the constraint solver (`InstantiationConstraint`, `SetOpConstraint`, `SingletonOrTopTypeConstraint`). * Add a builtin `singleton` type family to replace `SingletonOrTopTypeConstraint` when inferring refinements. * Fixed a crash involving type path reasoning by recording when type family reduction has taken place in the path. * Improved constraint ordering by blocking on unreduced types families that are not yet proven uninhabitable. * Improved the handling of `SetIndexerConstraints` for both better inference quality and to resolve crashes. * Fix a crash when normalizing cyclic unions of intersections. * Fix a crash when normalizing an intersection with the negation of `unknown`. * Fix a number of crashes caused by missing `follow` calls on `TypeId`s. * Changed type family reduction to correctly use a semantic notion of uninhabited types, rather than checking for `never` types specifically. * Refactor the `union` and `intersect` type families to be variadic. ### Native Code Generation * Improve translation for userdata key get/set and userdata/vector namecall. * Provide `[top level]` and `[anonymous]` as function names to `FunctionStats` as appropriate when no function name is available. * Disable unwind support on Android platforms since it is unsupported. * --- ### Internal Contributors Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vighnesh Vijay <vvijay@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Vighnesh <vvijay@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-04-19 22:48:02 +01:00
void BlockedType::setOwner(Constraint* newOwner)
{
LUAU_ASSERT(owner == nullptr);
Sync to upstream/release/622 (#1232) # What's changed? * Improved the actual message for the type errors for `cannot call non-function` when attempting to call a union of functions/callable tables. The error now correctly explains the issue is an inability to determine the return type of the call in this situation. * Resolve an issue where tables and metatables were not correctly being cloned during instantiation (fixes #1176). * Refactor `luaM_getnextgcopage` to `luaM_getnextpage` (generally removing `gco` prefix where appropriate). * Optimize `table.move` between tables for large ranges of elements. * Reformat a bunch of code automatically using `clang-format`. ### New Type Solver * Clean up minimally-used or unused constraints in the constraint solver (`InstantiationConstraint`, `SetOpConstraint`, `SingletonOrTopTypeConstraint`). * Add a builtin `singleton` type family to replace `SingletonOrTopTypeConstraint` when inferring refinements. * Fixed a crash involving type path reasoning by recording when type family reduction has taken place in the path. * Improved constraint ordering by blocking on unreduced types families that are not yet proven uninhabitable. * Improved the handling of `SetIndexerConstraints` for both better inference quality and to resolve crashes. * Fix a crash when normalizing cyclic unions of intersections. * Fix a crash when normalizing an intersection with the negation of `unknown`. * Fix a number of crashes caused by missing `follow` calls on `TypeId`s. * Changed type family reduction to correctly use a semantic notion of uninhabited types, rather than checking for `never` types specifically. * Refactor the `union` and `intersect` type families to be variadic. ### Native Code Generation * Improve translation for userdata key get/set and userdata/vector namecall. * Provide `[top level]` and `[anonymous]` as function names to `FunctionStats` as appropriate when no function name is available. * Disable unwind support on Android platforms since it is unsupported. * --- ### Internal Contributors Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vighnesh Vijay <vvijay@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Vighnesh <vvijay@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-04-19 22:48:02 +01:00
if (owner != nullptr)
return;
owner = newOwner;
}
void BlockedType::replaceOwner(Constraint* newOwner)
{
owner = newOwner;
}
PendingExpansionType::PendingExpansionType(
std::optional<AstName> prefix,
AstName name,
std::vector<TypeId> typeArguments,
std::vector<TypePackId> packArguments
)
: prefix(prefix)
, name(name)
2022-08-04 23:35:33 +01:00
, typeArguments(typeArguments)
, packArguments(packArguments)
, index(++nextIndex)
{
}
size_t PendingExpansionType::nextIndex = 0;
2022-08-04 23:35:33 +01:00
FunctionType::FunctionType(TypePackId argTypes, TypePackId retTypes, std::optional<FunctionDefinition> defn, bool hasSelf)
: definition(std::move(defn))
, argTypes(argTypes)
2022-06-17 02:05:14 +01:00
, retTypes(retTypes)
, hasSelf(hasSelf)
{
}
FunctionType::FunctionType(TypeLevel level, TypePackId argTypes, TypePackId retTypes, std::optional<FunctionDefinition> defn, bool hasSelf)
: definition(std::move(defn))
, level(level)
, argTypes(argTypes)
2022-06-17 02:05:14 +01:00
, retTypes(retTypes)
, hasSelf(hasSelf)
{
}
FunctionType::FunctionType(
TypeLevel level,
Scope* scope,
TypePackId argTypes,
TypePackId retTypes,
std::optional<FunctionDefinition> defn,
bool hasSelf
)
: definition(std::move(defn))
, level(level)
, scope(scope)
, argTypes(argTypes)
, retTypes(retTypes)
, hasSelf(hasSelf)
{
}
FunctionType::FunctionType(
std::vector<TypeId> generics,
std::vector<TypePackId> genericPacks,
TypePackId argTypes,
TypePackId retTypes,
std::optional<FunctionDefinition> defn,
bool hasSelf
)
: definition(std::move(defn))
, generics(generics)
, genericPacks(genericPacks)
, argTypes(argTypes)
2022-06-17 02:05:14 +01:00
, retTypes(retTypes)
, hasSelf(hasSelf)
{
}
FunctionType::FunctionType(
TypeLevel level,
std::vector<TypeId> generics,
std::vector<TypePackId> genericPacks,
TypePackId argTypes,
TypePackId retTypes,
std::optional<FunctionDefinition> defn,
bool hasSelf
)
: definition(std::move(defn))
, generics(generics)
, genericPacks(genericPacks)
, level(level)
, argTypes(argTypes)
2022-06-17 02:05:14 +01:00
, retTypes(retTypes)
, hasSelf(hasSelf)
{
}
FunctionType::FunctionType(
TypeLevel level,
Scope* scope,
std::vector<TypeId> generics,
std::vector<TypePackId> genericPacks,
TypePackId argTypes,
TypePackId retTypes,
std::optional<FunctionDefinition> defn,
bool hasSelf
)
: definition(std::move(defn))
, generics(generics)
, genericPacks(genericPacks)
, level(level)
, scope(scope)
, argTypes(argTypes)
, retTypes(retTypes)
, hasSelf(hasSelf)
{
}
Property::Property() {}
Property::Property(
TypeId readTy,
bool deprecated,
const std::string& deprecatedSuggestion,
std::optional<Location> location,
const Tags& tags,
const std::optional<std::string>& documentationSymbol,
std::optional<Location> typeLocation
)
: deprecated(deprecated)
, deprecatedSuggestion(deprecatedSuggestion)
, location(location)
, typeLocation(typeLocation)
, tags(tags)
, documentationSymbol(documentationSymbol)
, readTy(readTy)
, writeTy(readTy)
{
}
Property Property::readonly(TypeId ty)
{
Property p;
p.readTy = ty;
return p;
}
Property Property::writeonly(TypeId ty)
{
Property p;
p.writeTy = ty;
return p;
}
Property Property::rw(TypeId ty)
{
return Property::rw(ty, ty);
}
Property Property::rw(TypeId read, TypeId write)
{
Property p;
p.readTy = read;
p.writeTy = write;
return p;
}
Property Property::create(std::optional<TypeId> read, std::optional<TypeId> write)
{
if (read && !write)
return Property::readonly(*read);
else if (!read && write)
return Property::writeonly(*write);
else
{
LUAU_ASSERT(read && write);
return Property::rw(*read, *write);
}
}
TypeId Property::type() const
{
LUAU_ASSERT(readTy);
return *readTy;
}
void Property::setType(TypeId ty)
{
readTy = ty;
if (FFlag::LuauSolverV2)
Sync to upstream/release/614 (#1173) # What's changed? Add program argument passing to scripts run using the Luau REPL! You can now pass `--program-args` (or shorthand `-a`) to the REPL which will treat all remaining arguments as arguments to pass to executed scripts. These values can be accessed through variadic argument expansion. You can read these values like so: ``` local args = {...} -- gets you an array of all the arguments ``` For example if we run the following script like `luau test.lua -a test1 test2 test3`: ``` -- test.lua print(...) ``` you should get the output: ``` test1 test2 test3 ``` ### Native Code Generation * Improve A64 lowering for vector operations by using vector instructions * Fix lowering issue in IR value location tracking! - A developer reported a divergence between code run in the VM and Native Code Generation which we have now fixed ### New Type Solver * Apply substitution to type families, and emit new constraints to reduce those further * More progress on reducing comparison (`lt/le`)type families * Resolve two major sources of cyclic types in the new solver ### Miscellaneous * Turned internal compiler errors (ICE's) into warnings and errors ------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-02-23 20:08:34 +00:00
writeTy = ty;
}
void Property::makeShared()
{
if (writeTy)
writeTy = readTy;
}
Sync to upstream/release/614 (#1173) # What's changed? Add program argument passing to scripts run using the Luau REPL! You can now pass `--program-args` (or shorthand `-a`) to the REPL which will treat all remaining arguments as arguments to pass to executed scripts. These values can be accessed through variadic argument expansion. You can read these values like so: ``` local args = {...} -- gets you an array of all the arguments ``` For example if we run the following script like `luau test.lua -a test1 test2 test3`: ``` -- test.lua print(...) ``` you should get the output: ``` test1 test2 test3 ``` ### Native Code Generation * Improve A64 lowering for vector operations by using vector instructions * Fix lowering issue in IR value location tracking! - A developer reported a divergence between code run in the VM and Native Code Generation which we have now fixed ### New Type Solver * Apply substitution to type families, and emit new constraints to reduce those further * More progress on reducing comparison (`lt/le`)type families * Resolve two major sources of cyclic types in the new solver ### Miscellaneous * Turned internal compiler errors (ICE's) into warnings and errors ------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-02-23 20:08:34 +00:00
bool Property::isShared() const
{
return readTy && writeTy && readTy == writeTy;
}
Sync to upstream/release/614 (#1173) # What's changed? Add program argument passing to scripts run using the Luau REPL! You can now pass `--program-args` (or shorthand `-a`) to the REPL which will treat all remaining arguments as arguments to pass to executed scripts. These values can be accessed through variadic argument expansion. You can read these values like so: ``` local args = {...} -- gets you an array of all the arguments ``` For example if we run the following script like `luau test.lua -a test1 test2 test3`: ``` -- test.lua print(...) ``` you should get the output: ``` test1 test2 test3 ``` ### Native Code Generation * Improve A64 lowering for vector operations by using vector instructions * Fix lowering issue in IR value location tracking! - A developer reported a divergence between code run in the VM and Native Code Generation which we have now fixed ### New Type Solver * Apply substitution to type families, and emit new constraints to reduce those further * More progress on reducing comparison (`lt/le`)type families * Resolve two major sources of cyclic types in the new solver ### Miscellaneous * Turned internal compiler errors (ICE's) into warnings and errors ------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-02-23 20:08:34 +00:00
bool Property::isReadOnly() const
{
Sync to upstream/release/614 (#1173) # What's changed? Add program argument passing to scripts run using the Luau REPL! You can now pass `--program-args` (or shorthand `-a`) to the REPL which will treat all remaining arguments as arguments to pass to executed scripts. These values can be accessed through variadic argument expansion. You can read these values like so: ``` local args = {...} -- gets you an array of all the arguments ``` For example if we run the following script like `luau test.lua -a test1 test2 test3`: ``` -- test.lua print(...) ``` you should get the output: ``` test1 test2 test3 ``` ### Native Code Generation * Improve A64 lowering for vector operations by using vector instructions * Fix lowering issue in IR value location tracking! - A developer reported a divergence between code run in the VM and Native Code Generation which we have now fixed ### New Type Solver * Apply substitution to type families, and emit new constraints to reduce those further * More progress on reducing comparison (`lt/le`)type families * Resolve two major sources of cyclic types in the new solver ### Miscellaneous * Turned internal compiler errors (ICE's) into warnings and errors ------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-02-23 20:08:34 +00:00
return readTy && !writeTy;
}
Sync to upstream/release/614 (#1173) # What's changed? Add program argument passing to scripts run using the Luau REPL! You can now pass `--program-args` (or shorthand `-a`) to the REPL which will treat all remaining arguments as arguments to pass to executed scripts. These values can be accessed through variadic argument expansion. You can read these values like so: ``` local args = {...} -- gets you an array of all the arguments ``` For example if we run the following script like `luau test.lua -a test1 test2 test3`: ``` -- test.lua print(...) ``` you should get the output: ``` test1 test2 test3 ``` ### Native Code Generation * Improve A64 lowering for vector operations by using vector instructions * Fix lowering issue in IR value location tracking! - A developer reported a divergence between code run in the VM and Native Code Generation which we have now fixed ### New Type Solver * Apply substitution to type families, and emit new constraints to reduce those further * More progress on reducing comparison (`lt/le`)type families * Resolve two major sources of cyclic types in the new solver ### Miscellaneous * Turned internal compiler errors (ICE's) into warnings and errors ------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-02-23 20:08:34 +00:00
bool Property::isWriteOnly() const
{
Sync to upstream/release/614 (#1173) # What's changed? Add program argument passing to scripts run using the Luau REPL! You can now pass `--program-args` (or shorthand `-a`) to the REPL which will treat all remaining arguments as arguments to pass to executed scripts. These values can be accessed through variadic argument expansion. You can read these values like so: ``` local args = {...} -- gets you an array of all the arguments ``` For example if we run the following script like `luau test.lua -a test1 test2 test3`: ``` -- test.lua print(...) ``` you should get the output: ``` test1 test2 test3 ``` ### Native Code Generation * Improve A64 lowering for vector operations by using vector instructions * Fix lowering issue in IR value location tracking! - A developer reported a divergence between code run in the VM and Native Code Generation which we have now fixed ### New Type Solver * Apply substitution to type families, and emit new constraints to reduce those further * More progress on reducing comparison (`lt/le`)type families * Resolve two major sources of cyclic types in the new solver ### Miscellaneous * Turned internal compiler errors (ICE's) into warnings and errors ------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-02-23 20:08:34 +00:00
return !readTy && writeTy;
}
Sync to upstream/release/614 (#1173) # What's changed? Add program argument passing to scripts run using the Luau REPL! You can now pass `--program-args` (or shorthand `-a`) to the REPL which will treat all remaining arguments as arguments to pass to executed scripts. These values can be accessed through variadic argument expansion. You can read these values like so: ``` local args = {...} -- gets you an array of all the arguments ``` For example if we run the following script like `luau test.lua -a test1 test2 test3`: ``` -- test.lua print(...) ``` you should get the output: ``` test1 test2 test3 ``` ### Native Code Generation * Improve A64 lowering for vector operations by using vector instructions * Fix lowering issue in IR value location tracking! - A developer reported a divergence between code run in the VM and Native Code Generation which we have now fixed ### New Type Solver * Apply substitution to type families, and emit new constraints to reduce those further * More progress on reducing comparison (`lt/le`)type families * Resolve two major sources of cyclic types in the new solver ### Miscellaneous * Turned internal compiler errors (ICE's) into warnings and errors ------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-02-23 20:08:34 +00:00
bool Property::isReadWrite() const
{
Sync to upstream/release/614 (#1173) # What's changed? Add program argument passing to scripts run using the Luau REPL! You can now pass `--program-args` (or shorthand `-a`) to the REPL which will treat all remaining arguments as arguments to pass to executed scripts. These values can be accessed through variadic argument expansion. You can read these values like so: ``` local args = {...} -- gets you an array of all the arguments ``` For example if we run the following script like `luau test.lua -a test1 test2 test3`: ``` -- test.lua print(...) ``` you should get the output: ``` test1 test2 test3 ``` ### Native Code Generation * Improve A64 lowering for vector operations by using vector instructions * Fix lowering issue in IR value location tracking! - A developer reported a divergence between code run in the VM and Native Code Generation which we have now fixed ### New Type Solver * Apply substitution to type families, and emit new constraints to reduce those further * More progress on reducing comparison (`lt/le`)type families * Resolve two major sources of cyclic types in the new solver ### Miscellaneous * Turned internal compiler errors (ICE's) into warnings and errors ------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-02-23 20:08:34 +00:00
return readTy && writeTy;
}
TableType::TableType(TableState state, TypeLevel level, Scope* scope)
: state(state)
, level(level)
, scope(scope)
{
}
TableType::TableType(const Props& props, const std::optional<TableIndexer>& indexer, TypeLevel level, TableState state)
: props(props)
, indexer(indexer)
, state(state)
, level(level)
{
}
TableType::TableType(const Props& props, const std::optional<TableIndexer>& indexer, TypeLevel level, Scope* scope, TableState state)
: props(props)
, indexer(indexer)
, state(state)
, level(level)
, scope(scope)
{
}
// Test Types for equivalence
// More complex than we'd like because Types can self-reference.
bool areSeen(SeenSet& seen, const void* lhs, const void* rhs)
{
if (lhs == rhs)
return true;
auto p = std::make_pair(const_cast<void*>(lhs), const_cast<void*>(rhs));
if (seen.find(p) != seen.end())
return true;
seen.insert(p);
return false;
}
bool areEqual(SeenSet& seen, const FunctionType& lhs, const FunctionType& rhs)
{
if (areSeen(seen, &lhs, &rhs))
return true;
// TODO: check generics CLI-39915
if (!areEqual(seen, *lhs.argTypes, *rhs.argTypes))
return false;
2022-06-17 02:05:14 +01:00
if (!areEqual(seen, *lhs.retTypes, *rhs.retTypes))
return false;
return true;
}
bool areEqual(SeenSet& seen, const TableType& lhs, const TableType& rhs)
{
if (areSeen(seen, &lhs, &rhs))
return true;
if (lhs.state != rhs.state)
return false;
if (lhs.props.size() != rhs.props.size())
return false;
if (bool(lhs.indexer) != bool(rhs.indexer))
return false;
if (lhs.indexer && rhs.indexer)
{
if (!areEqual(seen, *lhs.indexer->indexType, *rhs.indexer->indexType))
return false;
if (!areEqual(seen, *lhs.indexer->indexResultType, *rhs.indexer->indexResultType))
return false;
}
auto l = lhs.props.begin();
auto r = rhs.props.begin();
while (l != lhs.props.end())
{
if (l->first != r->first)
return false;
if (!areEqual(seen, *l->second.type(), *r->second.type()))
return false;
++l;
++r;
}
return true;
}
static bool areEqual(SeenSet& seen, const MetatableType& lhs, const MetatableType& rhs)
{
2022-02-18 01:18:01 +00:00
if (areSeen(seen, &lhs, &rhs))
2022-01-14 16:20:09 +00:00
return true;
return areEqual(seen, *lhs.table, *rhs.table) && areEqual(seen, *lhs.metatable, *rhs.metatable);
}
bool areEqual(SeenSet& seen, const Type& lhs, const Type& rhs)
{
if (auto bound = get_if<BoundType>(&lhs.ty))
return areEqual(seen, *bound->boundTo, rhs);
if (auto bound = get_if<BoundType>(&rhs.ty))
return areEqual(seen, lhs, *bound->boundTo);
if (lhs.ty.index() != rhs.ty.index())
return false;
{
const FreeType* lf = get_if<FreeType>(&lhs.ty);
const FreeType* rf = get_if<FreeType>(&rhs.ty);
if (lf && rf)
return lf->index == rf->index;
}
{
const GenericType* lg = get_if<GenericType>(&lhs.ty);
const GenericType* rg = get_if<GenericType>(&rhs.ty);
if (lg && rg)
return lg->index == rg->index;
}
{
const PrimitiveType* lp = get_if<PrimitiveType>(&lhs.ty);
const PrimitiveType* rp = get_if<PrimitiveType>(&rhs.ty);
if (lp && rp)
return lp->type == rp->type;
}
{
const GenericType* lg = get_if<GenericType>(&lhs.ty);
const GenericType* rg = get_if<GenericType>(&rhs.ty);
if (lg && rg)
return lg->index == rg->index;
}
{
const ErrorType* le = get_if<ErrorType>(&lhs.ty);
const ErrorType* re = get_if<ErrorType>(&rhs.ty);
if (le && re)
return le->index == re->index;
}
{
const FunctionType* lf = get_if<FunctionType>(&lhs.ty);
const FunctionType* rf = get_if<FunctionType>(&rhs.ty);
if (lf && rf)
return areEqual(seen, *lf, *rf);
}
{
const TableType* lt = get_if<TableType>(&lhs.ty);
const TableType* rt = get_if<TableType>(&rhs.ty);
if (lt && rt)
return areEqual(seen, *lt, *rt);
}
{
const MetatableType* lmt = get_if<MetatableType>(&lhs.ty);
const MetatableType* rmt = get_if<MetatableType>(&rhs.ty);
if (lmt && rmt)
return areEqual(seen, *lmt, *rmt);
}
if (get_if<AnyType>(&lhs.ty) && get_if<AnyType>(&rhs.ty))
return true;
return false;
}
Type* asMutable(TypeId ty)
{
return const_cast<Type*>(ty);
}
bool Type::operator==(const Type& rhs) const
{
SeenSet seen;
return areEqual(seen, *this, rhs);
}
bool Type::operator!=(const Type& rhs) const
{
SeenSet seen;
return !areEqual(seen, *this, rhs);
}
Type& Type::operator=(const TypeVariant& rhs)
{
ty = rhs;
return *this;
}
Type& Type::operator=(TypeVariant&& rhs)
{
ty = std::move(rhs);
return *this;
}
Type& Type::operator=(const Type& rhs)
{
2022-07-08 02:22:39 +01:00
LUAU_ASSERT(owningArena == rhs.owningArena);
LUAU_ASSERT(!rhs.persistent);
2022-07-08 02:22:39 +01:00
reassign(rhs);
return *this;
}
TypeId makeFunction(
TypeArena& arena,
std::optional<TypeId> selfType,
std::initializer_list<TypeId> generics,
std::initializer_list<TypePackId> genericPacks,
std::initializer_list<TypeId> paramTypes,
std::initializer_list<std::string> paramNames,
std::initializer_list<TypeId> retTypes
);
TypeId makeStringMetatable(NotNull<BuiltinTypes> builtinTypes); // BuiltinDefinitions.cpp
BuiltinTypes::BuiltinTypes()
: arena(new TypeArena)
, debugFreezeArena(FFlag::DebugLuauFreezeArena)
, nilType(arena->addType(Type{PrimitiveType{PrimitiveType::NilType}, /*persistent*/ true}))
, numberType(arena->addType(Type{PrimitiveType{PrimitiveType::Number}, /*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}))
Sync to upstream/release/603 (#1097) # What's changed? - Record the location of properties for table types (closes #802) - Implement stricter UTF-8 validations as per the RFC (https://github.com/luau-lang/rfcs/pull/1) - Implement `buffer` as a new type in both the old and new solvers. - Changed errors produced by some `buffer` builtins to be a bit more generic to avoid platform-dependent error messages. - Fixed a bug where `Unifier` would copy some persistent types, tripping some internal assertions. - Type checking rules on relational operators is now a little bit more lax. - Improve dead code elimination for some `if` statements with complex always-false conditions ## New type solver - Dataflow analysis now generates phi nodes on exit of branches. - Dataflow analysis avoids producing a new definition for locals or properties that are not owned by that loop. - If a function parameter has been constrained to `never`, report errors at all uses of that parameter within that function. - Switch to using the new `Luau::Set` to replace `std::unordered_set` to alleviate some poor allocation characteristics which was negatively affecting overall performance. - Subtyping can now report many failing reasons instead of just the first one that we happened to find during the test. - Subtyping now also report reasons for type pack mismatches. - When visiting `if` statements or expressions, the resulting context are the common terms in both branches. ## Native codegen - Implement support for `buffer` builtins to its IR for x64 and A64. - Optimized `table.insert` by not inserting a table barrier if it is fastcalled with a constant. ## Internal Contributors Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Arseny Kapoulkine <arseny@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2023-11-10 21:10:07 +00:00
, bufferType(arena->addType(Type{PrimitiveType{PrimitiveType::Buffer}, /*persistent*/ true}))
, functionType(arena->addType(Type{PrimitiveType{PrimitiveType::Function}, /*persistent*/ true}))
, classType(arena->addType(Type{ClassType{"class", {}, std::nullopt, std::nullopt, {}, {}, {}, {}}, /*persistent*/ true}))
, tableType(arena->addType(Type{PrimitiveType{PrimitiveType::Table}, /*persistent*/ true}))
Sync to upstream/release/566 (#853) * Fixed incorrect lexeme generated for string parts in the middle of an interpolated string (Fixes https://github.com/Roblox/luau/issues/744) * DeprecatedApi lint can report some issues without type inference information * Fixed performance of autocomplete requests when suggestions have large intersection types (Solves https://github.com/Roblox/luau/discussions/847) * Marked `table.getn`/`foreach`/`foreachi` as deprecated ([RFC: Deprecate table.getn/foreach/foreachi](https://github.com/Roblox/luau/blob/master/rfcs/deprecate-table-getn-foreach.md)) * With -O2 optimization level, we now optimize builtin calls based on known argument/return count. Note that this change can be observable if `getfenv/setfenv` is used to substitute a builtin, especially if arity is different. Fastcall heavy tests show a 1-2% improvement. * Luau can now be built with clang-cl (Fixes https://github.com/Roblox/luau/issues/736) We also made many improvements to our experimental components. For our new type solver: * Overhauled data flow analysis system, fixed issues with 'repeat' loops, global variables and type annotations * Type refinements now work on generic table indexing with a string literal * Type refinements will properly track potentially 'nil' values (like t[x] for a missing key) and their further refinements * Internal top table type is now isomorphic to `{}` which fixes issues when `typeof(v) == 'table'` type refinement is handled * References to non-existent types in type annotations no longer resolve to 'error' type like in old solver * Improved handling of class unions in property access expressions * Fixed default type packs * Unsealed tables can now have metatables * Restored expected types for function arguments And for native code generation: * Added min and max IR instructions mapping to vminsd/vmaxsd on x64 * We now speculatively extract direct execution fast-paths based on expected types of expressions which provides better optimization opportunities inside a single basic block * Translated existing math fastcalls to IR form to improve tag guard removal and constant propagation
2023-03-03 20:21:14 +00:00
, emptyTableType(arena->addType(Type{TableType{TableState::Sealed, TypeLevel{}, nullptr}, /*persistent*/ true}))
, trueType(arena->addType(Type{SingletonType{BooleanSingleton{true}}, /*persistent*/ true}))
, falseType(arena->addType(Type{SingletonType{BooleanSingleton{false}}, /*persistent*/ true}))
, anyType(arena->addType(Type{AnyType{}, /*persistent*/ true}))
, unknownType(arena->addType(Type{UnknownType{}, /*persistent*/ true}))
, neverType(arena->addType(Type{NeverType{}, /*persistent*/ true}))
, errorType(arena->addType(Type{ErrorType{}, /*persistent*/ true}))
, falsyType(arena->addType(Type{UnionType{{falseType, nilType}}, /*persistent*/ true}))
, truthyType(arena->addType(Type{NegationType{falsyType}, /*persistent*/ true}))
, optionalNumberType(arena->addType(Type{UnionType{{numberType, nilType}}, /*persistent*/ true}))
, optionalStringType(arena->addType(Type{UnionType{{stringType, nilType}}, /*persistent*/ true}))
Sync to upstream/release/591 (#1012) * Fix a use-after-free bug in the new type cloning algorithm * Tighten up the type of `coroutine.wrap`. It is now `<A..., R...>(f: (A...) -> R...) -> ((A...) -> R...)` * Break `.luaurc` out into a separate library target `Luau.Config`. This makes it easier for applications to reason about config files without also depending on the type inference engine. * Move typechecking limits into `FrontendOptions`. This allows embedders more finely-grained control over autocomplete's internal time limits. * Fix stability issue with debugger onprotectederror callback allowing break in non-yieldable contexts New solver: * Initial work toward [Local Type Inference](https://github.com/Roblox/luau/blob/0e1082108fd6fb3a32dfdf5f1766ea3fc1391328/rfcs/local-type-inference.md) * Introduce a new subtyping test. This will be much nicer than the old test because it is completely separate both from actual type inference and from error reporting. Native code generation: * Added function to compute iterated dominance frontier * Optimize barriers in SET_UPVALUE when tag is known * Cache lua_State::global in a register on A64 * Optimize constant stores in A64 lowering * Track table array size state to optimize array size checks * Add split tag/value store into a VM register * Check that spills can outlive the block only in specific conditions --------- Co-authored-by: Arseny Kapoulkine <arseny.kapoulkine@gmail.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2023-08-18 19:15:41 +01:00
, emptyTypePack(arena->addTypePack(TypePackVar{TypePack{{}}, /*persistent*/ true}))
, anyTypePack(arena->addTypePack(TypePackVar{VariadicTypePack{anyType}, /*persistent*/ true}))
Sync to upstream/release/614 (#1173) # What's changed? Add program argument passing to scripts run using the Luau REPL! You can now pass `--program-args` (or shorthand `-a`) to the REPL which will treat all remaining arguments as arguments to pass to executed scripts. These values can be accessed through variadic argument expansion. You can read these values like so: ``` local args = {...} -- gets you an array of all the arguments ``` For example if we run the following script like `luau test.lua -a test1 test2 test3`: ``` -- test.lua print(...) ``` you should get the output: ``` test1 test2 test3 ``` ### Native Code Generation * Improve A64 lowering for vector operations by using vector instructions * Fix lowering issue in IR value location tracking! - A developer reported a divergence between code run in the VM and Native Code Generation which we have now fixed ### New Type Solver * Apply substitution to type families, and emit new constraints to reduce those further * More progress on reducing comparison (`lt/le`)type families * Resolve two major sources of cyclic types in the new solver ### Miscellaneous * Turned internal compiler errors (ICE's) into warnings and errors ------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-02-23 20:08:34 +00:00
, unknownTypePack(arena->addTypePack(TypePackVar{VariadicTypePack{unknownType}, /*persistent*/ true}))
, neverTypePack(arena->addTypePack(TypePackVar{VariadicTypePack{neverType}, /*persistent*/ true}))
, uninhabitableTypePack(arena->addTypePack(TypePackVar{TypePack{{neverType}, neverTypePack}, /*persistent*/ true}))
, errorTypePack(arena->addTypePack(TypePackVar{Unifiable::Error{}, /*persistent*/ true}))
{
freeze(*arena);
}
BuiltinTypes::~BuiltinTypes()
{
// Destroy the arena with the same memory management flags it was created with
bool prevFlag = FFlag::DebugLuauFreezeArena;
FFlag::DebugLuauFreezeArena.value = debugFreezeArena;
unfreeze(*arena);
arena.reset(nullptr);
FFlag::DebugLuauFreezeArena.value = prevFlag;
}
TypeId BuiltinTypes::errorRecoveryType() const
{
return errorType;
}
TypePackId BuiltinTypes::errorRecoveryTypePack() const
{
return errorTypePack;
}
TypeId BuiltinTypes::errorRecoveryType(TypeId guess) const
{
2022-04-29 02:24:24 +01:00
return guess;
}
TypePackId BuiltinTypes::errorRecoveryTypePack(TypePackId guess) const
{
2022-04-29 02:24:24 +01:00
return guess;
}
void persist(TypeId ty)
{
VecDeque<TypeId> queue{ty};
while (!queue.empty())
{
TypeId t = queue.front();
queue.pop_front();
if (t->persistent)
continue;
asMutable(t)->persistent = true;
if (auto btv = get<BoundType>(t))
queue.push_back(btv->boundTo);
else if (auto ftv = get<FunctionType>(t))
{
persist(ftv->argTypes);
2022-06-17 02:05:14 +01:00
persist(ftv->retTypes);
}
else if (auto ttv = get<TableType>(t))
{
2022-03-04 16:36:33 +00:00
LUAU_ASSERT(ttv->state != TableState::Free && ttv->state != TableState::Unsealed);
for (const auto& [_name, prop] : ttv->props)
queue.push_back(prop.type());
if (ttv->indexer)
{
queue.push_back(ttv->indexer->indexType);
queue.push_back(ttv->indexer->indexResultType);
}
}
else if (auto ctv = get<ClassType>(t))
{
for (const auto& [_name, prop] : ctv->props)
queue.push_back(prop.type());
}
else if (auto utv = get<UnionType>(t))
{
for (TypeId opt : utv->options)
queue.push_back(opt);
}
else if (auto itv = get<IntersectionType>(t))
{
for (TypeId opt : itv->parts)
queue.push_back(opt);
}
else if (auto mtv = get<MetatableType>(t))
{
queue.push_back(mtv->table);
queue.push_back(mtv->metatable);
}
else if (get<GenericType>(t) || get<AnyType>(t) || get<FreeType>(t) || get<SingletonType>(t) || get<PrimitiveType>(t) || get<NegationType>(t))
{
}
else if (auto tfit = get<TypeFunctionInstanceType>(t))
{
for (auto ty : tfit->typeArguments)
queue.push_back(ty);
for (auto tp : tfit->packArguments)
persist(tp);
}
else
{
LUAU_ASSERT(!"TypeId is not supported in a persist call");
}
}
}
void persist(TypePackId tp)
{
if (tp->persistent)
return;
asMutable(tp)->persistent = true;
if (auto p = get<TypePack>(tp))
{
for (TypeId ty : p->head)
persist(ty);
if (p->tail)
persist(*p->tail);
}
else if (auto vtp = get<VariadicTypePack>(tp))
{
persist(vtp->ty);
}
else if (get<GenericTypePack>(tp))
{
}
else if (auto tfitp = get<TypeFunctionInstanceTypePack>(tp))
{
for (auto ty : tfitp->typeArguments)
persist(ty);
for (auto tp : tfitp->packArguments)
persist(tp);
}
else
{
LUAU_ASSERT(!"TypePackId is not supported in a persist call");
}
}
const TypeLevel* getLevel(TypeId ty)
{
ty = follow(ty);
if (auto ftv = get<FreeType>(ty))
return &ftv->level;
else if (auto ttv = get<TableType>(ty))
return &ttv->level;
else if (auto ftv = get<FunctionType>(ty))
return &ftv->level;
else
return nullptr;
}
TypeLevel* getMutableLevel(TypeId ty)
{
return const_cast<TypeLevel*>(getLevel(ty));
}
2022-04-15 00:57:43 +01:00
std::optional<TypeLevel> getLevel(TypePackId tp)
{
tp = follow(tp);
if (auto ftv = get<FreeTypePack>(tp))
2022-04-15 00:57:43 +01:00
return ftv->level;
else
return std::nullopt;
}
const Property* lookupClassProp(const ClassType* cls, const Name& name)
{
while (cls)
{
auto it = cls->props.find(name);
if (it != cls->props.end())
return &it->second;
if (cls->parent)
cls = get<ClassType>(*cls->parent);
else
return nullptr;
LUAU_ASSERT(cls);
}
return nullptr;
}
bool isSubclass(const ClassType* cls, const ClassType* parent)
{
while (cls)
{
if (cls == parent)
return true;
else if (!cls->parent)
return false;
cls = get<ClassType>(*cls->parent);
LUAU_ASSERT(cls);
}
return false;
}
const std::vector<TypeId>& getTypes(const UnionType* utv)
{
2022-07-08 02:22:39 +01:00
return utv->options;
}
const std::vector<TypeId>& getTypes(const IntersectionType* itv)
{
2022-07-08 02:22:39 +01:00
return itv->parts;
}
UnionTypeIterator begin(const UnionType* utv)
{
return UnionTypeIterator{utv};
}
UnionTypeIterator end(const UnionType* utv)
{
return UnionTypeIterator{};
}
IntersectionTypeIterator begin(const IntersectionType* itv)
{
return IntersectionTypeIterator{itv};
}
IntersectionTypeIterator end(const IntersectionType* itv)
{
return IntersectionTypeIterator{};
}
TypeId freshType(NotNull<TypeArena> arena, NotNull<BuiltinTypes> builtinTypes, Scope* scope)
{
return arena->addType(FreeType{scope, builtinTypes->neverType, builtinTypes->unknownType});
}
std::vector<TypeId> filterMap(TypeId type, TypeIdPredicate predicate)
{
type = follow(type);
if (auto utv = get<UnionType>(type))
{
std::set<TypeId> options;
for (TypeId option : utv)
if (auto out = predicate(follow(option)))
options.insert(*out);
return std::vector<TypeId>(options.begin(), options.end());
}
else if (auto out = predicate(type))
return {*out};
return {};
}
static Tags* getTags(TypeId ty)
{
ty = follow(ty);
if (auto ftv = getMutable<FunctionType>(ty))
return &ftv->tags;
else if (auto ttv = getMutable<TableType>(ty))
return &ttv->tags;
else if (auto ctv = getMutable<ClassType>(ty))
return &ctv->tags;
return nullptr;
}
void attachTag(TypeId ty, const std::string& tagName)
{
if (auto tags = getTags(ty))
tags->push_back(tagName);
else
LUAU_ASSERT(!"This TypeId does not support tags");
}
void attachTag(Property& prop, const std::string& tagName)
{
prop.tags.push_back(tagName);
}
// We would ideally not expose this because it could cause a footgun.
// If the Base class has a tag and you ask if Derived has that tag, it would return false.
// Unfortunately, there's already use cases that's hard to disentangle. For now, we expose it.
bool hasTag(const Tags& tags, const std::string& tagName)
{
return std::find(tags.begin(), tags.end(), tagName) != tags.end();
}
bool hasTag(TypeId ty, const std::string& tagName)
{
ty = follow(ty);
// We special case classes because getTags only returns a pointer to one vector of tags.
// But classes has multiple vector of tags, represented throughout the hierarchy.
if (auto ctv = get<ClassType>(ty))
{
while (ctv)
{
if (hasTag(ctv->tags, tagName))
return true;
else if (!ctv->parent)
return false;
ctv = get<ClassType>(*ctv->parent);
LUAU_ASSERT(ctv);
}
}
else if (auto tags = getTags(ty))
return hasTag(*tags, tagName);
return false;
}
bool hasTag(const Property& prop, const std::string& tagName)
{
return hasTag(prop.tags, tagName);
}
2022-08-04 23:35:33 +01:00
bool TypeFun::operator==(const TypeFun& rhs) const
{
return type == rhs.type && typeParams == rhs.typeParams && typePackParams == rhs.typePackParams;
}
bool GenericTypeDefinition::operator==(const GenericTypeDefinition& rhs) const
{
return ty == rhs.ty && defaultValue == rhs.defaultValue;
}
bool GenericTypePackDefinition::operator==(const GenericTypePackDefinition& rhs) const
{
return tp == rhs.tp && defaultValue == rhs.defaultValue;
}
Sync to upstream/release/623 (#1236) # What's changed? ### New Type Solver - Unification of two fresh types no longer binds them together. - Replaced uses of raw `emplace` with `emplaceType` to catch cyclic bound types when they are created. - `SetIndexerConstraint` is blocked until the indexer result type is not blocked. - Fix a case where a blocked type got past the constraint solver. - Searching for free types should no longer traverse into `ClassType`s. - Fix a corner case that could result in the non-testable type `~{}`. - Fix incorrect flagging when `any` was a parameter of some checked function in nonstrict type checker. - `IterableConstraint` now consider tables without `__iter` to be iterables. ### Native Code Generation - Improve register type info lookup by program counter. - Generate type information for locals and upvalues --- ### Internal Contributors Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Alexander McCord <amccord@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: James McNellis <jmcnellis@roblox.com> Co-authored-by: Vighnesh Vijay <vvijay@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com> --------- Co-authored-by: Aaron Weiss <aaronweiss@roblox.com> Co-authored-by: Andy Friesen <afriesen@roblox.com> Co-authored-by: Vighnesh <vvijay@roblox.com> Co-authored-by: Aviral Goel <agoel@roblox.com> Co-authored-by: David Cope <dcope@roblox.com> Co-authored-by: Lily Brown <lbrown@roblox.com> Co-authored-by: Vyacheslav Egorov <vegorov@roblox.com>
2024-04-25 23:26:09 +01:00
template<>
LUAU_NOINLINE Unifiable::Bound<TypeId>* emplaceType<BoundType>(Type* ty, TypeId& tyArg)
{
LUAU_ASSERT(ty != follow(tyArg));
return &ty->ty.emplace<BoundType>(tyArg);
}
} // namespace Luau