Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/tests/AstVisitor.test.cpp
2723 views
1
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
2
#include "Fixture.h"
3
4
#include "Luau/Ast.h"
5
6
#include "doctest.h"
7
8
using namespace Luau;
9
10
namespace
11
{
12
13
class AstVisitorTracking : public AstVisitor
14
{
15
private:
16
std::vector<AstNode*> visitedNodes;
17
std::set<size_t> seen;
18
19
public:
20
bool visit(AstNode* n) override
21
{
22
visitedNodes.push_back(n);
23
return true;
24
}
25
26
AstNode* operator[](size_t index)
27
{
28
REQUIRE(index < visitedNodes.size());
29
30
seen.insert(index);
31
return visitedNodes[index];
32
}
33
34
~AstVisitorTracking() override
35
{
36
std::string s = "Seen " + std::to_string(seen.size()) + " nodes but got " + std::to_string(visitedNodes.size());
37
CHECK_MESSAGE(seen.size() == visitedNodes.size(), s);
38
}
39
};
40
41
class AstTypeVisitorTrackingWiths : public AstVisitorTracking
42
{
43
public:
44
using AstVisitorTracking::visit;
45
bool visit(AstType* n) override
46
{
47
return visit((AstNode*)n);
48
}
49
};
50
51
} // namespace
52
53
TEST_SUITE_BEGIN("AstVisitorTest");
54
55
TEST_CASE_FIXTURE(Fixture, "TypeAnnotationsAreNotVisited")
56
{
57
AstStatBlock* block = parse(R"(
58
local a: A<number>
59
)");
60
61
AstVisitorTracking v;
62
block->visit(&v);
63
64
CHECK(v[0]->is<AstStatBlock>());
65
CHECK(v[1]->is<AstStatLocal>());
66
// We should not have v[2] that points to the annotation
67
// We should not have v[3] that points to the type argument 'number' in A.
68
}
69
70
TEST_CASE_FIXTURE(Fixture, "LocalTwoBindings")
71
{
72
AstStatBlock* block = parse(R"(
73
local a, b
74
)");
75
76
AstVisitorTracking v;
77
block->visit(&v);
78
79
CHECK(v[0]->is<AstStatBlock>());
80
CHECK(v[1]->is<AstStatLocal>());
81
}
82
83
TEST_CASE_FIXTURE(Fixture, "LocalTwoAnnotatedBindings")
84
{
85
AstStatBlock* block = parse(R"(
86
local a: A, b: B<number>
87
)");
88
89
AstTypeVisitorTrackingWiths v;
90
block->visit(&v);
91
92
CHECK(v[0]->is<AstStatBlock>());
93
CHECK(v[1]->is<AstStatLocal>());
94
CHECK(v[2]->is<AstTypeReference>());
95
CHECK(v[3]->is<AstTypeReference>());
96
CHECK(v[4]->is<AstTypeReference>());
97
}
98
99
TEST_CASE_FIXTURE(Fixture, "LocalTwoAnnotatedBindingsWithTwoValues")
100
{
101
AstStatBlock* block = parse(R"(
102
local a: A, b: B<number> = 1, 2
103
)");
104
105
AstTypeVisitorTrackingWiths v;
106
block->visit(&v);
107
108
CHECK(v[0]->is<AstStatBlock>());
109
CHECK(v[1]->is<AstStatLocal>());
110
CHECK(v[2]->is<AstTypeReference>());
111
CHECK(v[3]->is<AstTypeReference>());
112
CHECK(v[4]->is<AstTypeReference>());
113
CHECK(v[5]->is<AstExprConstantNumber>());
114
CHECK(v[6]->is<AstExprConstantNumber>());
115
}
116
117
TEST_SUITE_END();
118
119