luau/tests/DataFlowGraph.test.cpp

104 lines
2.4 KiB
C++
Raw Normal View History

2022-10-22 01:33:43 +08:00
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
2022-12-02 18:46:05 +08:00
#include "Luau/DataFlowGraph.h"
2022-10-22 01:33:43 +08:00
#include "Luau/Error.h"
#include "Luau/Parser.h"
#include "AstQueryDsl.h"
#include "ScopedFlags.h"
#include "doctest.h"
using namespace Luau;
2023-03-03 21:45:38 +08:00
struct DataFlowGraphFixture
2022-10-22 01:33:43 +08:00
{
// Only needed to fix the operator== reflexivity of an empty Symbol.
ScopedFastFlag dcr{"DebugLuauDeferredConstraintResolution", true};
InternalErrorReporter handle;
Allocator allocator;
AstNameTable names{allocator};
AstStatBlock* module;
std::optional<DataFlowGraph> graph;
void dfg(const std::string& code)
{
ParseResult parseResult = Parser::parse(code.c_str(), code.size(), names, allocator);
if (!parseResult.errors.empty())
throw ParseErrors(std::move(parseResult.errors));
module = parseResult.root;
graph = DataFlowGraphBuilder::build(module, NotNull{&handle});
}
template<typename T, int N>
2023-03-03 21:45:38 +08:00
NullableBreadcrumbId getBreadcrumb(const std::vector<Nth>& nths = {nth<T>(N)})
2022-10-22 01:33:43 +08:00
{
T* node = query<T, N>(module, nths);
REQUIRE(node);
2023-03-03 21:45:38 +08:00
return graph->getBreadcrumb(node);
2022-10-22 01:33:43 +08:00
}
template<typename T, int N>
2023-03-03 21:45:38 +08:00
BreadcrumbId requireBreadcrumb(const std::vector<Nth>& nths = {nth<T>(N)})
2022-10-22 01:33:43 +08:00
{
2023-03-03 21:45:38 +08:00
auto bc = getBreadcrumb<T, N>(nths);
REQUIRE(bc);
return NotNull{bc};
2022-10-22 01:33:43 +08:00
}
};
TEST_SUITE_BEGIN("DataFlowGraphBuilder");
TEST_CASE_FIXTURE(DataFlowGraphFixture, "define_locals_in_local_stat")
{
dfg(R"(
local x = 5
local y = x
)");
2023-03-03 21:45:38 +08:00
REQUIRE(getBreadcrumb<AstExprLocal, 1>());
2022-10-22 01:33:43 +08:00
}
TEST_CASE_FIXTURE(DataFlowGraphFixture, "define_parameters_in_functions")
{
dfg(R"(
local function f(x)
local y = x
end
)");
2023-03-03 21:45:38 +08:00
REQUIRE(getBreadcrumb<AstExprLocal, 1>());
2022-10-22 01:33:43 +08:00
}
TEST_CASE_FIXTURE(DataFlowGraphFixture, "find_aliases")
{
dfg(R"(
local x = 5
local y = x
local z = y
)");
2023-03-03 21:45:38 +08:00
BreadcrumbId x = requireBreadcrumb<AstExprLocal, 1>();
BreadcrumbId y = requireBreadcrumb<AstExprLocal, 2>();
REQUIRE(x != y);
2022-10-22 01:33:43 +08:00
}
TEST_CASE_FIXTURE(DataFlowGraphFixture, "independent_locals")
{
dfg(R"(
local x = 5
local y = 5
local a = x
local b = y
)");
2023-03-03 21:45:38 +08:00
BreadcrumbId x = requireBreadcrumb<AstExprLocal, 1>();
BreadcrumbId y = requireBreadcrumb<AstExprLocal, 2>();
2022-10-22 01:33:43 +08:00
REQUIRE(x != y);
}
TEST_SUITE_END();