1//===- unittest/Tooling/ASTMatchersTest.h - Matcher tests helpers ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_CLANG_UNITTESTS_ASTMATCHERS_ASTMATCHERSTEST_H
10#define LLVM_CLANG_UNITTESTS_ASTMATCHERS_ASTMATCHERSTEST_H
11
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Frontend/ASTUnit.h"
14#include "clang/Testing/CommandLineArgs.h"
15#include "clang/Testing/TestClangConfig.h"
16#include "clang/Tooling/Tooling.h"
17#include "gtest/gtest.h"
18
19namespace clang {
20namespace ast_matchers {
21
22using clang::tooling::buildASTFromCodeWithArgs;
23using clang::tooling::FileContentMappings;
24using clang::tooling::FrontendActionFactory;
25using clang::tooling::newFrontendActionFactory;
26using clang::tooling::runToolOnCodeWithArgs;
27
28class BoundNodesCallback {
29public:
30 virtual ~BoundNodesCallback() {}
31 virtual bool run(const BoundNodes *BoundNodes) = 0;
32 virtual bool run(const BoundNodes *BoundNodes, ASTContext *Context) = 0;
33 virtual void onEndOfTranslationUnit() {}
34};
35
36// If 'FindResultVerifier' is not NULL, sets *Verified to the result of
37// running 'FindResultVerifier' with the bound nodes as argument.
38// If 'FindResultVerifier' is NULL, sets *Verified to true when Run is called.
39class VerifyMatch : public MatchFinder::MatchCallback {
40public:
41 VerifyMatch(std::unique_ptr<BoundNodesCallback> FindResultVerifier,
42 bool *Verified)
43 : Verified(Verified), FindResultReviewer(std::move(FindResultVerifier)) {}
44
45 void run(const MatchFinder::MatchResult &Result) override {
46 if (FindResultReviewer != nullptr) {
47 *Verified |= FindResultReviewer->run(BoundNodes: &Result.Nodes, Context: Result.Context);
48 } else {
49 *Verified = true;
50 }
51 }
52
53 void onEndOfTranslationUnit() override {
54 if (FindResultReviewer)
55 FindResultReviewer->onEndOfTranslationUnit();
56 }
57
58private:
59 bool *const Verified;
60 const std::unique_ptr<BoundNodesCallback> FindResultReviewer;
61};
62
63inline ArrayRef<TestLanguage> langCxx11OrLater() {
64 static const TestLanguage Result[] = {Lang_CXX11, Lang_CXX14, Lang_CXX17,
65 Lang_CXX20, Lang_CXX23};
66 return ArrayRef<TestLanguage>(Result);
67}
68
69inline ArrayRef<TestLanguage> langCxx14OrLater() {
70 static const TestLanguage Result[] = {Lang_CXX14, Lang_CXX17, Lang_CXX20,
71 Lang_CXX23};
72 return ArrayRef<TestLanguage>(Result);
73}
74
75inline ArrayRef<TestLanguage> langCxx17OrLater() {
76 static const TestLanguage Result[] = {Lang_CXX17, Lang_CXX20, Lang_CXX23};
77 return ArrayRef<TestLanguage>(Result);
78}
79
80inline ArrayRef<TestLanguage> langCxx20OrLater() {
81 static const TestLanguage Result[] = {Lang_CXX20, Lang_CXX23};
82 return ArrayRef<TestLanguage>(Result);
83}
84
85inline ArrayRef<TestLanguage> langCxx23OrLater() {
86 static const TestLanguage Result[] = {Lang_CXX23};
87 return ArrayRef<TestLanguage>(Result);
88}
89
90template <typename T>
91testing::AssertionResult matchesConditionally(
92 const Twine &Code, const T &AMatcher, bool ExpectMatch,
93 ArrayRef<std::string> CompileArgs,
94 const FileContentMappings &VirtualMappedFiles = FileContentMappings(),
95 StringRef Filename = "input.cc") {
96 bool Found = false, DynamicFound = false;
97 MatchFinder Finder;
98 VerifyMatch VerifyFound(nullptr, &Found);
99 Finder.addMatcher(AMatcher, &VerifyFound);
100 VerifyMatch VerifyDynamicFound(nullptr, &DynamicFound);
101 if (!Finder.addDynamicMatcher(NodeMatch: AMatcher, Action: &VerifyDynamicFound))
102 return testing::AssertionFailure() << "Could not add dynamic matcher";
103 std::unique_ptr<FrontendActionFactory> Factory(
104 newFrontendActionFactory(ConsumerFactory: &Finder));
105 std::vector<std::string> Args = {
106 // Some tests need rtti/exceptions on.
107 "-frtti", "-fexceptions",
108 // Ensure that tests specify the C++ standard version that they need.
109 "-Werror=c++14-extensions", "-Werror=c++17-extensions",
110 "-Werror=c++20-extensions"};
111 // Append additional arguments at the end to allow overriding the default
112 // choices that we made above.
113 llvm::copy(Range&: CompileArgs, Out: std::back_inserter(x&: Args));
114 if (llvm::find(Range&: Args, Val: "-target") == Args.end()) {
115 // Use an unknown-unknown triple so we don't instantiate the full system
116 // toolchain. On Linux, instantiating the toolchain involves stat'ing
117 // large portions of /usr/lib, and this slows down not only this test, but
118 // all other tests, via contention in the kernel.
119 //
120 // FIXME: This is a hack to work around the fact that there's no way to do
121 // the equivalent of runToolOnCodeWithArgs without instantiating a full
122 // Driver. We should consider having a function, at least for tests, that
123 // invokes cc1.
124 Args.push_back(x: "-target");
125 Args.push_back(x: "i386-unknown-unknown");
126 }
127
128 if (!runToolOnCodeWithArgs(
129 ToolAction: Factory->create(), Code, Args, FileName: Filename, ToolName: "clang-tool",
130 PCHContainerOps: std::make_shared<PCHContainerOperations>(), VirtualMappedFiles)) {
131 return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
132 }
133 if (Found != DynamicFound) {
134 return testing::AssertionFailure()
135 << "Dynamic match result (" << DynamicFound
136 << ") does not match static result (" << Found << ")";
137 }
138 if (!Found && ExpectMatch) {
139 return testing::AssertionFailure()
140 << "Could not find match in \"" << Code << "\"";
141 } else if (Found && !ExpectMatch) {
142 return testing::AssertionFailure()
143 << "Found unexpected match in \"" << Code << "\"";
144 }
145 return testing::AssertionSuccess();
146}
147
148template <typename T>
149testing::AssertionResult
150matchesConditionally(const Twine &Code, const T &AMatcher, bool ExpectMatch,
151 ArrayRef<TestLanguage> TestLanguages) {
152 for (auto Lang : TestLanguages) {
153 auto Result = matchesConditionally(
154 Code, AMatcher, ExpectMatch, getCommandLineArgsForTesting(Lang),
155 FileContentMappings(), getFilenameForTesting(Lang));
156 if (!Result)
157 return Result;
158 }
159
160 return testing::AssertionSuccess();
161}
162
163template <typename T>
164testing::AssertionResult
165matches(const Twine &Code, const T &AMatcher,
166 ArrayRef<TestLanguage> TestLanguages = {Lang_CXX11}) {
167 return matchesConditionally(Code, AMatcher, true, TestLanguages);
168}
169
170template <typename T>
171testing::AssertionResult
172notMatches(const Twine &Code, const T &AMatcher,
173 ArrayRef<TestLanguage> TestLanguages = {Lang_CXX11}) {
174 return matchesConditionally(Code, AMatcher, false, TestLanguages);
175}
176
177template <typename T>
178testing::AssertionResult matchesObjC(const Twine &Code, const T &AMatcher,
179 bool ExpectMatch = true) {
180 return matchesConditionally(Code, AMatcher, ExpectMatch,
181 {"-fobjc-nonfragile-abi", "-Wno-objc-root-class",
182 "-fblocks", "-Wno-incomplete-implementation"},
183 FileContentMappings(), "input.m");
184}
185
186template <typename T>
187testing::AssertionResult matchesC(const Twine &Code, const T &AMatcher) {
188 return matchesConditionally(Code, AMatcher, true, {}, FileContentMappings(),
189 "input.c");
190}
191
192template <typename T>
193testing::AssertionResult notMatchesObjC(const Twine &Code, const T &AMatcher) {
194 return matchesObjC(Code, AMatcher, false);
195}
196
197// Function based on matchesConditionally with "-x cuda" argument added and
198// small CUDA header prepended to the code string.
199template <typename T>
200testing::AssertionResult
201matchesConditionallyWithCuda(const Twine &Code, const T &AMatcher,
202 bool ExpectMatch, llvm::StringRef CompileArg) {
203 const std::string CudaHeader =
204 "typedef unsigned int size_t;\n"
205 "#define __constant__ __attribute__((constant))\n"
206 "#define __device__ __attribute__((device))\n"
207 "#define __global__ __attribute__((global))\n"
208 "#define __host__ __attribute__((host))\n"
209 "#define __shared__ __attribute__((shared))\n"
210 "struct dim3 {"
211 " unsigned x, y, z;"
212 " __host__ __device__ dim3(unsigned x, unsigned y = 1, unsigned z = 1)"
213 " : x(x), y(y), z(z) {}"
214 "};"
215 "typedef struct cudaStream *cudaStream_t;"
216 "int cudaConfigureCall(dim3 gridSize, dim3 blockSize,"
217 " size_t sharedSize = 0,"
218 " cudaStream_t stream = 0);"
219 "extern \"C\" unsigned __cudaPushCallConfiguration("
220 " dim3 gridDim, dim3 blockDim, size_t sharedMem = 0, void *stream = "
221 "0);";
222
223 bool Found = false, DynamicFound = false;
224 MatchFinder Finder;
225 VerifyMatch VerifyFound(nullptr, &Found);
226 Finder.addMatcher(AMatcher, &VerifyFound);
227 VerifyMatch VerifyDynamicFound(nullptr, &DynamicFound);
228 if (!Finder.addDynamicMatcher(NodeMatch: AMatcher, Action: &VerifyDynamicFound))
229 return testing::AssertionFailure() << "Could not add dynamic matcher";
230 std::unique_ptr<FrontendActionFactory> Factory(
231 newFrontendActionFactory(ConsumerFactory: &Finder));
232 // Some tests use typeof, which is a gnu extension. Using an explicit
233 // unknown-unknown triple is good for a large speedup, because it lets us
234 // avoid constructing a full system triple.
235 std::vector<std::string> Args = {
236 "-xcuda", "-fno-ms-extensions", "--cuda-host-only", "-nocudainc",
237 "-target", "x86_64-unknown-unknown", std::string(CompileArg)};
238 if (!runToolOnCodeWithArgs(ToolAction: Factory->create(), Code: CudaHeader + Code, Args)) {
239 return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
240 }
241 if (Found != DynamicFound) {
242 return testing::AssertionFailure()
243 << "Dynamic match result (" << DynamicFound
244 << ") does not match static result (" << Found << ")";
245 }
246 if (!Found && ExpectMatch) {
247 return testing::AssertionFailure()
248 << "Could not find match in \"" << Code << "\"";
249 } else if (Found && !ExpectMatch) {
250 return testing::AssertionFailure()
251 << "Found unexpected match in \"" << Code << "\"";
252 }
253 return testing::AssertionSuccess();
254}
255
256template <typename T>
257testing::AssertionResult matchesWithCuda(const Twine &Code, const T &AMatcher) {
258 return matchesConditionallyWithCuda(Code, AMatcher, true, "-std=c++11");
259}
260
261template <typename T>
262testing::AssertionResult notMatchesWithCuda(const Twine &Code,
263 const T &AMatcher) {
264 return matchesConditionallyWithCuda(Code, AMatcher, false, "-std=c++11");
265}
266
267template <typename T>
268testing::AssertionResult matchesWithOpenMP(const Twine &Code,
269 const T &AMatcher) {
270 return matchesConditionally(Code, AMatcher, true, {"-fopenmp=libomp"});
271}
272
273template <typename T>
274testing::AssertionResult notMatchesWithOpenMP(const Twine &Code,
275 const T &AMatcher) {
276 return matchesConditionally(Code, AMatcher, false, {"-fopenmp=libomp"});
277}
278
279template <typename T>
280testing::AssertionResult matchesWithOpenMP51(const Twine &Code,
281 const T &AMatcher) {
282 return matchesConditionally(Code, AMatcher, true,
283 {"-fopenmp=libomp", "-fopenmp-version=51"});
284}
285
286template <typename T>
287testing::AssertionResult notMatchesWithOpenMP51(const Twine &Code,
288 const T &AMatcher) {
289 return matchesConditionally(Code, AMatcher, false,
290 {"-fopenmp=libomp", "-fopenmp-version=51"});
291}
292
293template <typename T>
294testing::AssertionResult matchAndVerifyResultConditionally(
295 const Twine &Code, const T &AMatcher,
296 std::unique_ptr<BoundNodesCallback> FindResultVerifier, bool ExpectResult,
297 ArrayRef<std::string> Args = {}, StringRef Filename = "input.cc") {
298 bool VerifiedResult = false;
299 MatchFinder Finder;
300 VerifyMatch VerifyVerifiedResult(std::move(FindResultVerifier),
301 &VerifiedResult);
302 Finder.addMatcher(AMatcher, &VerifyVerifiedResult);
303 std::unique_ptr<FrontendActionFactory> Factory(
304 newFrontendActionFactory(ConsumerFactory: &Finder));
305 // Some tests use typeof, which is a gnu extension. Using an explicit
306 // unknown-unknown triple is good for a large speedup, because it lets us
307 // avoid constructing a full system triple.
308 std::vector<std::string> CompileArgs = {"-std=gnu++11", "-target",
309 "i386-unknown-unknown"};
310 // Append additional arguments at the end to allow overriding the default
311 // choices that we made above.
312 llvm::copy(Range&: Args, Out: std::back_inserter(x&: CompileArgs));
313
314 if (!runToolOnCodeWithArgs(ToolAction: Factory->create(), Code, Args: CompileArgs, FileName: Filename)) {
315 return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
316 }
317 if (!VerifiedResult && ExpectResult) {
318 return testing::AssertionFailure()
319 << "Could not verify result in \"" << Code << "\"";
320 } else if (VerifiedResult && !ExpectResult) {
321 return testing::AssertionFailure()
322 << "Verified unexpected result in \"" << Code << "\"";
323 }
324
325 VerifiedResult = false;
326 SmallString<256> Buffer;
327 std::unique_ptr<ASTUnit> AST(buildASTFromCodeWithArgs(
328 Code: Code.toStringRef(Out&: Buffer), Args: CompileArgs, FileName: Filename));
329 if (!AST.get())
330 return testing::AssertionFailure()
331 << "Parsing error in \"" << Code << "\" while building AST";
332 Finder.matchAST(Context&: AST->getASTContext());
333 if (!VerifiedResult && ExpectResult) {
334 return testing::AssertionFailure()
335 << "Could not verify result in \"" << Code << "\" with AST";
336 } else if (VerifiedResult && !ExpectResult) {
337 return testing::AssertionFailure()
338 << "Verified unexpected result in \"" << Code << "\" with AST";
339 }
340
341 return testing::AssertionSuccess();
342}
343
344// FIXME: Find better names for these functions (or document what they
345// do more precisely).
346template <typename T>
347testing::AssertionResult
348matchAndVerifyResultTrue(const Twine &Code, const T &AMatcher,
349 std::unique_ptr<BoundNodesCallback> FindResultVerifier,
350 ArrayRef<std::string> Args = {},
351 StringRef Filename = "input.cc") {
352 return matchAndVerifyResultConditionally(
353 Code, AMatcher, std::move(FindResultVerifier),
354 /*ExpectResult=*/true, Args, Filename);
355}
356
357template <typename T>
358testing::AssertionResult matchAndVerifyResultFalse(
359 const Twine &Code, const T &AMatcher,
360 std::unique_ptr<BoundNodesCallback> FindResultVerifier,
361 ArrayRef<std::string> Args = {}, StringRef Filename = "input.cc") {
362 return matchAndVerifyResultConditionally(
363 Code, AMatcher, std::move(FindResultVerifier),
364 /*ExpectResult=*/false, Args, Filename);
365}
366
367// Implements a run method that returns whether BoundNodes contains a
368// Decl bound to Id that can be dynamically cast to T.
369// Optionally checks that the check succeeded a specific number of times.
370template <typename T> class VerifyIdIsBoundTo : public BoundNodesCallback {
371public:
372 // Create an object that checks that a node of type \c T was bound to \c Id.
373 // Does not check for a certain number of matches.
374 explicit VerifyIdIsBoundTo(llvm::StringRef Id)
375 : Id(std::string(Id)), ExpectedCount(-1), Count(0) {}
376
377 // Create an object that checks that a node of type \c T was bound to \c Id.
378 // Checks that there were exactly \c ExpectedCount matches.
379 VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
380 : Id(std::string(Id)), ExpectedCount(ExpectedCount), Count(0) {}
381
382 // Create an object that checks that a node of type \c T was bound to \c Id.
383 // Checks that there was exactly one match with the name \c ExpectedName.
384 // Note that \c T must be a NamedDecl for this to work.
385 VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
386 int ExpectedCount = 1)
387 : Id(std::string(Id)), ExpectedCount(ExpectedCount), Count(0),
388 ExpectedName(std::string(ExpectedName)) {}
389
390 void onEndOfTranslationUnit() override {
391 if (ExpectedCount != -1) {
392 EXPECT_EQ(ExpectedCount, Count);
393 }
394 if (!ExpectedName.empty()) {
395 EXPECT_EQ(ExpectedName, Name);
396 }
397 Count = 0;
398 Name.clear();
399 }
400
401 ~VerifyIdIsBoundTo() override {
402 EXPECT_EQ(0, Count);
403 EXPECT_EQ("", Name);
404 }
405
406 bool run(const BoundNodes *Nodes) override {
407 const BoundNodes::IDToNodeMap &M = Nodes->getMap();
408 if (Nodes->getNodeAs<T>(Id)) {
409 ++Count;
410 if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(ID: Id)) {
411 Name = Named->getNameAsString();
412 } else if (const NestedNameSpecifier *NNS =
413 Nodes->getNodeAs<NestedNameSpecifier>(ID: Id)) {
414 llvm::raw_string_ostream OS(Name);
415 NNS->print(OS, Policy: PrintingPolicy(LangOptions()));
416 }
417 BoundNodes::IDToNodeMap::const_iterator I = M.find(x: Id);
418 EXPECT_NE(M.end(), I);
419 if (I != M.end()) {
420 EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
421 }
422 return true;
423 }
424 EXPECT_TRUE(M.count(Id) == 0 ||
425 M.find(Id)->second.template get<T>() == nullptr);
426 return false;
427 }
428
429 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
430 return run(Nodes);
431 }
432
433private:
434 const std::string Id;
435 const int ExpectedCount;
436 int Count;
437 const std::string ExpectedName;
438 std::string Name;
439};
440
441class ASTMatchersTest : public ::testing::Test,
442 public ::testing::WithParamInterface<TestClangConfig> {
443protected:
444 template <typename T>
445 testing::AssertionResult matches(const Twine &Code, const T &AMatcher) {
446 const TestClangConfig &TestConfig = GetParam();
447 return clang::ast_matchers::matchesConditionally(
448 Code, AMatcher, /*ExpectMatch=*/true, TestConfig.getCommandLineArgs(),
449 FileContentMappings(), getFilenameForTesting(Lang: TestConfig.Language));
450 }
451
452 template <typename T>
453 testing::AssertionResult notMatches(const Twine &Code, const T &AMatcher) {
454 const TestClangConfig &TestConfig = GetParam();
455 return clang::ast_matchers::matchesConditionally(
456 Code, AMatcher, /*ExpectMatch=*/false, TestConfig.getCommandLineArgs(),
457 FileContentMappings(), getFilenameForTesting(Lang: TestConfig.Language));
458 }
459};
460
461} // namespace ast_matchers
462} // namespace clang
463
464#endif // LLVM_CLANG_UNITTESTS_AST_MATCHERS_AST_MATCHERS_TEST_H
465

source code of clang/unittests/ASTMatchers/ASTMatchersTest.h