[NFC][Coroutines] Use structured binding with llvm::enumerate in CoroSplit (#116879)
[llvm-project.git] / clang / unittests / ASTMatchers / ASTMatchersNodeTest.cpp
blobebf548eb254313a637c37e1022954d997c3808d5
1 //== unittests/ASTMatchers/ASTMatchersNodeTest.cpp - AST matcher unit tests ==//
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 //===----------------------------------------------------------------------===//
9 #include "ASTMatchersTest.h"
10 #include "clang/AST/PrettyPrinter.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "clang/Tooling/Tooling.h"
14 #include "llvm/TargetParser/Host.h"
15 #include "llvm/TargetParser/Triple.h"
16 #include "gtest/gtest.h"
18 namespace clang {
19 namespace ast_matchers {
21 TEST_P(ASTMatchersTest, Decl_CXX) {
22 if (!GetParam().isCXX()) {
23 // FIXME: Add a test for `decl()` that does not depend on C++.
24 return;
26 EXPECT_TRUE(notMatches("", decl(usingDecl())));
27 EXPECT_TRUE(
28 matches("namespace x { class X {}; } using x::X;", decl(usingDecl())));
31 TEST_P(ASTMatchersTest, NameableDeclaration_MatchesVariousDecls) {
32 DeclarationMatcher NamedX = namedDecl(hasName("X"));
33 EXPECT_TRUE(matches("typedef int X;", NamedX));
34 EXPECT_TRUE(matches("int X;", NamedX));
35 EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
36 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
38 EXPECT_TRUE(notMatches("#define X 1", NamedX));
41 TEST_P(ASTMatchersTest, NamedDecl_CXX) {
42 if (!GetParam().isCXX()) {
43 return;
45 DeclarationMatcher NamedX = namedDecl(hasName("X"));
46 EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
47 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
48 EXPECT_TRUE(matches("namespace X { }", NamedX));
51 TEST_P(ASTMatchersTest, MatchesNameRE) {
52 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
53 EXPECT_TRUE(matches("typedef int Xa;", NamedX));
54 EXPECT_TRUE(matches("int Xb;", NamedX));
55 EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
56 EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
58 EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
60 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
61 EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
63 DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
64 EXPECT_TRUE(matches("int abc;", Abc));
65 EXPECT_TRUE(matches("int aFOObBARc;", Abc));
66 EXPECT_TRUE(notMatches("int cab;", Abc));
67 EXPECT_TRUE(matches("int cabc;", Abc));
69 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
70 EXPECT_TRUE(matches("int k;", StartsWithK));
71 EXPECT_TRUE(matches("int kAbc;", StartsWithK));
74 TEST_P(ASTMatchersTest, MatchesNameRE_CXX) {
75 if (!GetParam().isCXX()) {
76 return;
78 DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
79 EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
80 EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
81 EXPECT_TRUE(matches("namespace Xij { }", NamedX));
83 DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
84 EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
86 DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
87 EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
88 EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
89 EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
90 EXPECT_TRUE(notMatches("int K;", StartsWithK));
92 DeclarationMatcher StartsWithKIgnoreCase =
93 namedDecl(matchesName(":k[^:]*$", llvm::Regex::IgnoreCase));
94 EXPECT_TRUE(matches("int k;", StartsWithKIgnoreCase));
95 EXPECT_TRUE(matches("int K;", StartsWithKIgnoreCase));
98 TEST_P(ASTMatchersTest, DeclarationMatcher_MatchClass) {
99 if (!GetParam().isCXX()) {
100 return;
103 DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
104 EXPECT_TRUE(matches("class X;", ClassX));
105 EXPECT_TRUE(matches("class X {};", ClassX));
106 EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
107 EXPECT_TRUE(notMatches("", ClassX));
110 TEST_P(ASTMatchersTest, TranslationUnitDecl) {
111 if (!GetParam().isCXX()) {
112 // FIXME: Add a test for `translationUnitDecl()` that does not depend on
113 // C++.
114 return;
116 StringRef Code = "int MyVar1;\n"
117 "namespace NameSpace {\n"
118 "int MyVar2;\n"
119 "} // namespace NameSpace\n";
120 EXPECT_TRUE(matches(
121 Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
122 EXPECT_FALSE(matches(
123 Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
124 EXPECT_TRUE(matches(
125 Code,
126 varDecl(hasName("MyVar2"),
127 hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
130 TEST_P(ASTMatchersTest, LinkageSpecDecl) {
131 if (!GetParam().isCXX()) {
132 return;
134 EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
135 EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
138 TEST_P(ASTMatchersTest, ClassTemplateDecl_DoesNotMatchClass) {
139 if (!GetParam().isCXX()) {
140 return;
142 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
143 EXPECT_TRUE(notMatches("class X;", ClassX));
144 EXPECT_TRUE(notMatches("class X {};", ClassX));
147 TEST_P(ASTMatchersTest, ClassTemplateDecl_MatchesClassTemplate) {
148 if (!GetParam().isCXX()) {
149 return;
151 DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
152 EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
153 EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
156 TEST_P(ASTMatchersTest,
157 ClassTemplateDecl_DoesNotMatchClassTemplateExplicitSpecialization) {
158 if (!GetParam().isCXX()) {
159 return;
161 EXPECT_TRUE(notMatches(
162 "template<typename T> class X { };"
163 "template<> class X<int> { int a; };",
164 classTemplateDecl(hasName("X"), hasDescendant(fieldDecl(hasName("a"))))));
167 TEST_P(ASTMatchersTest,
168 ClassTemplateDecl_DoesNotMatchClassTemplatePartialSpecialization) {
169 if (!GetParam().isCXX()) {
170 return;
172 EXPECT_TRUE(notMatches(
173 "template<typename T, typename U> class X { };"
174 "template<typename T> class X<T, int> { int a; };",
175 classTemplateDecl(hasName("X"), hasDescendant(fieldDecl(hasName("a"))))));
178 TEST(ASTMatchersTestCUDA, CUDAKernelCallExpr) {
179 EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
180 "void g() { f<<<1, 2>>>(); }",
181 cudaKernelCallExpr()));
182 EXPECT_TRUE(notMatchesWithCuda("void f() {}", cudaKernelCallExpr()));
185 TEST(ASTMatchersTestCUDA, HasAttrCUDA) {
186 EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
187 hasAttr(clang::attr::CUDADevice)));
188 EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
189 hasAttr(clang::attr::CUDAGlobal)));
192 TEST_P(ASTMatchersTest, ValueDecl) {
193 if (!GetParam().isCXX()) {
194 // FIXME: Fix this test in non-C++ language modes.
195 return;
197 EXPECT_TRUE(matches("enum EnumType { EnumValue };",
198 valueDecl(hasType(asString("enum EnumType")))));
199 EXPECT_TRUE(matches("void FunctionDecl();",
200 valueDecl(hasType(asString("void (void)")))));
203 TEST_P(ASTMatchersTest, FriendDecl) {
204 if (!GetParam().isCXX()) {
205 return;
207 EXPECT_TRUE(matches("class Y { friend class X; };",
208 friendDecl(hasType(asString("class X")))));
209 EXPECT_TRUE(matches("class Y { friend class X; };",
210 friendDecl(hasType(recordDecl(hasName("X"))))));
212 EXPECT_TRUE(matches("class Y { friend void f(); };",
213 functionDecl(hasName("f"), hasParent(friendDecl()))));
216 TEST_P(ASTMatchersTest, EnumDecl_DoesNotMatchClasses) {
217 if (!GetParam().isCXX()) {
218 return;
220 EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
223 TEST_P(ASTMatchersTest, EnumDecl_MatchesEnums) {
224 if (!GetParam().isCXX()) {
225 // FIXME: Fix this test in non-C++ language modes.
226 return;
228 EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
231 TEST_P(ASTMatchersTest, EnumConstantDecl) {
232 if (!GetParam().isCXX()) {
233 // FIXME: Fix this test in non-C++ language modes.
234 return;
236 DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
237 EXPECT_TRUE(matches("enum X{ A };", Matcher));
238 EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
239 EXPECT_TRUE(notMatches("enum X {};", Matcher));
242 TEST_P(ASTMatchersTest, TagDecl) {
243 if (!GetParam().isCXX()) {
244 // FIXME: Fix this test in non-C++ language modes.
245 return;
247 EXPECT_TRUE(matches("struct X {};", tagDecl(hasName("X"))));
248 EXPECT_TRUE(matches("union U {};", tagDecl(hasName("U"))));
249 EXPECT_TRUE(matches("enum E {};", tagDecl(hasName("E"))));
252 TEST_P(ASTMatchersTest, TagDecl_CXX) {
253 if (!GetParam().isCXX()) {
254 return;
256 EXPECT_TRUE(matches("class C {};", tagDecl(hasName("C"))));
259 TEST_P(ASTMatchersTest, UnresolvedLookupExpr) {
260 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
261 // FIXME: Fix this test to work with delayed template parsing.
262 return;
265 EXPECT_TRUE(matches("template<typename T>"
266 "T foo() { T a; return a; }"
267 "template<typename T>"
268 "void bar() {"
269 " foo<T>();"
270 "}",
271 unresolvedLookupExpr()));
274 TEST_P(ASTMatchersTest, UsesADL) {
275 if (!GetParam().isCXX()) {
276 return;
279 StatementMatcher ADLMatch = callExpr(usesADL());
280 StatementMatcher ADLMatchOper = cxxOperatorCallExpr(usesADL());
281 StringRef NS_Str = R"cpp(
282 namespace NS {
283 struct X {};
284 void f(X);
285 void operator+(X, X);
287 struct MyX {};
288 void f(...);
289 void operator+(MyX, MyX);
290 )cpp";
292 auto MkStr = [&](StringRef Body) {
293 return (NS_Str + "void test_fn() { " + Body + " }").str();
296 EXPECT_TRUE(matches(MkStr("NS::X x; f(x);"), ADLMatch));
297 EXPECT_TRUE(notMatches(MkStr("NS::X x; NS::f(x);"), ADLMatch));
298 EXPECT_TRUE(notMatches(MkStr("MyX x; f(x);"), ADLMatch));
299 EXPECT_TRUE(notMatches(MkStr("NS::X x; using NS::f; f(x);"), ADLMatch));
301 // Operator call expressions
302 EXPECT_TRUE(matches(MkStr("NS::X x; x + x;"), ADLMatch));
303 EXPECT_TRUE(matches(MkStr("NS::X x; x + x;"), ADLMatchOper));
304 EXPECT_TRUE(notMatches(MkStr("MyX x; x + x;"), ADLMatch));
305 EXPECT_TRUE(notMatches(MkStr("MyX x; x + x;"), ADLMatchOper));
306 EXPECT_TRUE(matches(MkStr("NS::X x; operator+(x, x);"), ADLMatch));
307 EXPECT_TRUE(notMatches(MkStr("NS::X x; NS::operator+(x, x);"), ADLMatch));
310 TEST_P(ASTMatchersTest, CallExpr_CXX) {
311 if (!GetParam().isCXX()) {
312 // FIXME: Add a test for `callExpr()` that does not depend on C++.
313 return;
315 // FIXME: Do we want to overload Call() to directly take
316 // Matcher<Decl>, too?
317 StatementMatcher MethodX =
318 callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
320 EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
321 EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
323 StatementMatcher MethodOnY =
324 cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
326 EXPECT_TRUE(matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
327 MethodOnY));
328 EXPECT_TRUE(matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
329 MethodOnY));
330 EXPECT_TRUE(notMatches(
331 "class Y { public: void x(); }; void z(Y *&y) { y->x(); }", MethodOnY));
332 EXPECT_TRUE(notMatches(
333 "class Y { public: void x(); }; void z(Y y[]) { y->x(); }", MethodOnY));
334 EXPECT_TRUE(notMatches(
335 "class Y { public: void x(); }; void z() { Y *y; y->x(); }", MethodOnY));
337 StatementMatcher MethodOnYPointer =
338 cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
340 EXPECT_TRUE(
341 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
342 MethodOnYPointer));
343 EXPECT_TRUE(
344 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
345 MethodOnYPointer));
346 EXPECT_TRUE(
347 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
348 MethodOnYPointer));
349 EXPECT_TRUE(
350 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
351 MethodOnYPointer));
352 EXPECT_TRUE(
353 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
354 MethodOnYPointer));
357 TEST_P(ASTMatchersTest, LambdaExpr) {
358 if (!GetParam().isCXX11OrLater()) {
359 return;
361 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };", lambdaExpr()));
364 TEST_P(ASTMatchersTest, CXXForRangeStmt) {
365 EXPECT_TRUE(
366 notMatches("void f() { for (int i; i<5; ++i); }", cxxForRangeStmt()));
369 TEST_P(ASTMatchersTest, CXXForRangeStmt_CXX11) {
370 if (!GetParam().isCXX11OrLater()) {
371 return;
373 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
374 "void f() { for (auto &a : as); }",
375 cxxForRangeStmt()));
378 TEST_P(ASTMatchersTest, SubstNonTypeTemplateParmExpr) {
379 if (!GetParam().isCXX()) {
380 return;
382 EXPECT_FALSE(matches("template<int N>\n"
383 "struct A { static const int n = 0; };\n"
384 "struct B : public A<42> {};",
385 traverse(TK_AsIs, substNonTypeTemplateParmExpr())));
386 EXPECT_TRUE(matches("template<int N>\n"
387 "struct A { static const int n = N; };\n"
388 "struct B : public A<42> {};",
389 traverse(TK_AsIs, substNonTypeTemplateParmExpr())));
392 TEST_P(ASTMatchersTest, NonTypeTemplateParmDecl) {
393 if (!GetParam().isCXX()) {
394 return;
396 EXPECT_TRUE(matches("template <int N> void f();",
397 nonTypeTemplateParmDecl(hasName("N"))));
398 EXPECT_TRUE(
399 notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
402 TEST_P(ASTMatchersTest, TemplateTypeParmDecl) {
403 if (!GetParam().isCXX()) {
404 return;
406 EXPECT_TRUE(matches("template <typename T> void f();",
407 templateTypeParmDecl(hasName("T"))));
408 EXPECT_TRUE(notMatches("template <int N> void f();", templateTypeParmDecl()));
411 TEST_P(ASTMatchersTest, TemplateTemplateParmDecl) {
412 if (!GetParam().isCXX())
413 return;
414 EXPECT_TRUE(matches("template <template <typename> class Z> void f();",
415 templateTemplateParmDecl(hasName("Z"))));
416 EXPECT_TRUE(notMatches("template <typename, int> void f();",
417 templateTemplateParmDecl()));
420 TEST_P(ASTMatchersTest, UserDefinedLiteral) {
421 if (!GetParam().isCXX11OrLater()) {
422 return;
424 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
425 " return i + 1;"
427 "char c = 'a'_inc;",
428 userDefinedLiteral()));
431 TEST_P(ASTMatchersTest, FlowControl) {
432 EXPECT_TRUE(matches("void f() { while(1) { break; } }", breakStmt()));
433 EXPECT_TRUE(matches("void f() { while(1) { continue; } }", continueStmt()));
434 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
435 EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}",
436 labelStmt(hasDeclaration(labelDecl(hasName("FOO"))))));
437 EXPECT_TRUE(matches("void f() { FOO: ; void *ptr = &&FOO; goto *ptr; }",
438 addrLabelExpr()));
439 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
442 TEST_P(ASTMatchersTest, CXXOperatorCallExpr) {
443 if (!GetParam().isCXX()) {
444 return;
447 StatementMatcher OpCall = cxxOperatorCallExpr();
448 // Unary operator
449 EXPECT_TRUE(matches("class Y { }; "
450 "bool operator!(Y x) { return false; }; "
451 "Y y; bool c = !y;",
452 OpCall));
453 // No match -- special operators like "new", "delete"
454 // FIXME: operator new takes size_t, for which we need stddef.h, for which
455 // we need to figure out include paths in the test.
456 // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
457 // "class Y { }; "
458 // "void *operator new(size_t size) { return 0; } "
459 // "Y *y = new Y;", OpCall));
460 EXPECT_TRUE(notMatches("class Y { }; "
461 "void operator delete(void *p) { } "
462 "void a() {Y *y = new Y; delete y;}",
463 OpCall));
464 // Binary operator
465 EXPECT_TRUE(matches("class Y { }; "
466 "bool operator&&(Y x, Y y) { return true; }; "
467 "Y a; Y b; bool c = a && b;",
468 OpCall));
469 // No match -- normal operator, not an overloaded one.
470 EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
471 EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
474 TEST_P(ASTMatchersTest, FoldExpr) {
475 if (!GetParam().isCXX() || !GetParam().isCXX17OrLater()) {
476 return;
479 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
480 "return (0 + ... + args); }",
481 cxxFoldExpr()));
482 EXPECT_TRUE(matches("template <typename... Args> auto sum(Args... args) { "
483 "return (args + ...); }",
484 cxxFoldExpr()));
487 TEST_P(ASTMatchersTest, ThisPointerType) {
488 if (!GetParam().isCXX()) {
489 return;
492 StatementMatcher MethodOnY = traverse(
493 TK_AsIs, cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y")))));
495 EXPECT_TRUE(matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
496 MethodOnY));
497 EXPECT_TRUE(matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
498 MethodOnY));
499 EXPECT_TRUE(matches(
500 "class Y { public: void x(); }; void z(Y *&y) { y->x(); }", MethodOnY));
501 EXPECT_TRUE(matches(
502 "class Y { public: void x(); }; void z(Y y[]) { y->x(); }", MethodOnY));
503 EXPECT_TRUE(matches(
504 "class Y { public: void x(); }; void z() { Y *y; y->x(); }", MethodOnY));
506 EXPECT_TRUE(matches("class Y {"
507 " public: virtual void x();"
508 "};"
509 "class X : public Y {"
510 " public: virtual void x();"
511 "};"
512 "void z() { X *x; x->Y::x(); }",
513 MethodOnY));
516 TEST_P(ASTMatchersTest, DeclRefExpr) {
517 if (!GetParam().isCXX()) {
518 // FIXME: Add a test for `declRefExpr()` that does not depend on C++.
519 return;
521 StatementMatcher Reference = declRefExpr(to(varDecl(hasInitializer(
522 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
524 EXPECT_TRUE(matches("class Y {"
525 " public:"
526 " bool x() const;"
527 "};"
528 "void z(const Y &y) {"
529 " bool b = y.x();"
530 " if (b) {}"
531 "}",
532 Reference));
534 EXPECT_TRUE(notMatches("class Y {"
535 " public:"
536 " bool x() const;"
537 "};"
538 "void z(const Y &y) {"
539 " bool b = y.x();"
540 "}",
541 Reference));
544 TEST_P(ASTMatchersTest, CXXMemberCallExpr) {
545 if (!GetParam().isCXX()) {
546 return;
548 StatementMatcher CallOnVariableY =
549 cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
551 EXPECT_TRUE(matches("class Y { public: void x() { Y y; y.x(); } };",
552 CallOnVariableY));
553 EXPECT_TRUE(matches("class Y { public: void x() const { Y y; y.x(); } };",
554 CallOnVariableY));
555 EXPECT_TRUE(matches("class Y { public: void x(); };"
556 "class X : public Y { void z() { X y; y.x(); } };",
557 CallOnVariableY));
558 EXPECT_TRUE(matches("class Y { public: void x(); };"
559 "class X : public Y { void z() { X *y; y->x(); } };",
560 CallOnVariableY));
561 EXPECT_TRUE(notMatches(
562 "class Y { public: void x(); };"
563 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
564 CallOnVariableY));
567 TEST_P(ASTMatchersTest, UnaryExprOrTypeTraitExpr) {
568 EXPECT_TRUE(
569 matches("void x() { int a = sizeof(a); }", unaryExprOrTypeTraitExpr()));
572 TEST_P(ASTMatchersTest, AlignOfExpr) {
573 EXPECT_TRUE(
574 notMatches("void x() { int a = sizeof(a); }", alignOfExpr(anything())));
575 // FIXME: Uncomment once alignof is enabled.
576 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
577 // unaryExprOrTypeTraitExpr()));
578 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
579 // sizeOfExpr()));
582 TEST_P(ASTMatchersTest, MemberExpr_DoesNotMatchClasses) {
583 if (!GetParam().isCXX()) {
584 return;
586 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
587 EXPECT_TRUE(notMatches("class Y { void x() {} };", unresolvedMemberExpr()));
588 EXPECT_TRUE(
589 notMatches("class Y { void x() {} };", cxxDependentScopeMemberExpr()));
592 TEST_P(ASTMatchersTest, MemberExpr_MatchesMemberFunctionCall) {
593 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
594 // FIXME: Fix this test to work with delayed template parsing.
595 return;
597 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
598 EXPECT_TRUE(matches("class Y { template <class T> void x() { x<T>(); } };",
599 unresolvedMemberExpr()));
600 EXPECT_TRUE(matches("template <class T> void x() { T t; t.f(); }",
601 cxxDependentScopeMemberExpr()));
604 TEST_P(ASTMatchersTest, MemberExpr_MatchesVariable) {
605 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
606 // FIXME: Fix this test to work with delayed template parsing.
607 return;
609 EXPECT_TRUE(
610 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
611 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };", memberExpr()));
612 EXPECT_TRUE(
613 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
614 EXPECT_TRUE(matches("template <class T>"
615 "class X : T { void f() { this->T::v; } };",
616 cxxDependentScopeMemberExpr()));
617 // FIXME: Add a matcher for DependentScopeDeclRefExpr.
618 EXPECT_TRUE(
619 notMatches("template <class T> class X : T { void f() { T::v; } };",
620 cxxDependentScopeMemberExpr()));
621 EXPECT_TRUE(matches("template <class T> void x() { T t; t.v; }",
622 cxxDependentScopeMemberExpr()));
625 TEST_P(ASTMatchersTest, MemberExpr_MatchesStaticVariable) {
626 if (!GetParam().isCXX()) {
627 return;
629 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
630 memberExpr()));
631 EXPECT_TRUE(
632 notMatches("class Y { void x() { y; } static int y; };", memberExpr()));
633 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
634 memberExpr()));
637 TEST_P(ASTMatchersTest, FunctionDecl) {
638 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
640 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
641 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
643 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
644 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
645 EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
648 TEST_P(ASTMatchersTest, FunctionDecl_C) {
649 if (!GetParam().isC()) {
650 return;
652 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
653 EXPECT_TRUE(matches("void f();", functionDecl(parameterCountIs(0))));
656 TEST_P(ASTMatchersTest, FunctionDecl_CXX) {
657 if (!GetParam().isCXX()) {
658 return;
661 StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
663 if (!GetParam().hasDelayedTemplateParsing()) {
664 // FIXME: Fix this test to work with delayed template parsing.
665 // Dependent contexts, but a non-dependent call.
666 EXPECT_TRUE(
667 matches("void f(); template <int N> void g() { f(); }", CallFunctionF));
668 EXPECT_TRUE(
669 matches("void f(); template <int N> struct S { void g() { f(); } };",
670 CallFunctionF));
673 // Dependent calls don't match.
674 EXPECT_TRUE(
675 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
676 CallFunctionF));
677 EXPECT_TRUE(
678 notMatches("void f(int);"
679 "template <typename T> struct S { void g(T t) { f(t); } };",
680 CallFunctionF));
682 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
683 EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
686 TEST_P(ASTMatchersTest, FunctionDecl_CXX11) {
687 if (!GetParam().isCXX11OrLater()) {
688 return;
691 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
692 functionDecl(isVariadic())));
695 TEST_P(ASTMatchersTest,
696 FunctionTemplateDecl_MatchesFunctionTemplateDeclarations) {
697 if (!GetParam().isCXX()) {
698 return;
700 EXPECT_TRUE(matches("template <typename T> void f(T t) {}",
701 functionTemplateDecl(hasName("f"))));
704 TEST_P(ASTMatchersTest, FunctionTemplate_DoesNotMatchFunctionDeclarations) {
705 EXPECT_TRUE(
706 notMatches("void f(double d);", functionTemplateDecl(hasName("f"))));
707 EXPECT_TRUE(
708 notMatches("void f(int t) {}", functionTemplateDecl(hasName("f"))));
711 TEST_P(ASTMatchersTest,
712 FunctionTemplateDecl_DoesNotMatchFunctionTemplateSpecializations) {
713 if (!GetParam().isCXX()) {
714 return;
716 EXPECT_TRUE(notMatches(
717 "void g(); template <typename T> void f(T t) {}"
718 "template <> void f(int t) { g(); }",
719 functionTemplateDecl(hasName("f"), hasDescendant(declRefExpr(to(
720 functionDecl(hasName("g"))))))));
723 TEST_P(ASTMatchersTest, ClassTemplateSpecializationDecl) {
724 if (!GetParam().isCXX()) {
725 return;
727 EXPECT_TRUE(matches("template<typename T> struct A {};"
728 "template<> struct A<int> {};",
729 classTemplateSpecializationDecl()));
730 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
731 classTemplateSpecializationDecl()));
732 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
733 classTemplateSpecializationDecl()));
736 TEST_P(ASTMatchersTest, DeclaratorDecl) {
737 EXPECT_TRUE(matches("int x;", declaratorDecl()));
738 EXPECT_TRUE(notMatches("struct A {};", declaratorDecl()));
741 TEST_P(ASTMatchersTest, DeclaratorDecl_CXX) {
742 if (!GetParam().isCXX()) {
743 return;
745 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
748 TEST_P(ASTMatchersTest, ParmVarDecl) {
749 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
750 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
753 TEST_P(ASTMatchersTest, StaticAssertDecl) {
754 if (!GetParam().isCXX11OrLater())
755 return;
757 EXPECT_TRUE(matches("static_assert(true, \"\");", staticAssertDecl()));
758 EXPECT_TRUE(
759 notMatches("constexpr bool staticassert(bool B, const char *M) "
760 "{ return true; };\n void f() { staticassert(true, \"\"); }",
761 staticAssertDecl()));
764 TEST_P(ASTMatchersTest, Matcher_ConstructorCall) {
765 if (!GetParam().isCXX()) {
766 return;
769 StatementMatcher Constructor = traverse(TK_AsIs, cxxConstructExpr());
771 EXPECT_TRUE(
772 matches("class X { public: X(); }; void x() { X x; }", Constructor));
773 EXPECT_TRUE(matches("class X { public: X(); }; void x() { X x = X(); }",
774 Constructor));
775 EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x = 0; }",
776 Constructor));
777 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
780 TEST_P(ASTMatchersTest, Match_ConstructorInitializers) {
781 if (!GetParam().isCXX()) {
782 return;
784 EXPECT_TRUE(matches("class C { int i; public: C(int ii) : i(ii) {} };",
785 cxxCtorInitializer(forField(hasName("i")))));
788 TEST_P(ASTMatchersTest, Matcher_ThisExpr) {
789 if (!GetParam().isCXX()) {
790 return;
792 EXPECT_TRUE(
793 matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
794 EXPECT_TRUE(
795 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
798 TEST_P(ASTMatchersTest, Matcher_BindTemporaryExpression) {
799 if (!GetParam().isCXX()) {
800 return;
803 StatementMatcher TempExpression = traverse(TK_AsIs, cxxBindTemporaryExpr());
805 StringRef ClassString = "class string { public: string(); ~string(); }; ";
807 EXPECT_TRUE(matches(
808 ClassString + "string GetStringByValue();"
809 "void FunctionTakesString(string s);"
810 "void run() { FunctionTakesString(GetStringByValue()); }",
811 TempExpression));
813 EXPECT_TRUE(notMatches(ClassString +
814 "string* GetStringPointer(); "
815 "void FunctionTakesStringPtr(string* s);"
816 "void run() {"
817 " string* s = GetStringPointer();"
818 " FunctionTakesStringPtr(GetStringPointer());"
819 " FunctionTakesStringPtr(s);"
820 "}",
821 TempExpression));
823 EXPECT_TRUE(notMatches("class no_dtor {};"
824 "no_dtor GetObjByValue();"
825 "void ConsumeObj(no_dtor param);"
826 "void run() { ConsumeObj(GetObjByValue()); }",
827 TempExpression));
830 TEST_P(ASTMatchersTest, MaterializeTemporaryExpr_MatchesTemporaryCXX11CXX14) {
831 if (GetParam().Language != Lang_CXX11 && GetParam().Language != Lang_CXX14) {
832 return;
835 StatementMatcher TempExpression =
836 traverse(TK_AsIs, materializeTemporaryExpr());
838 EXPECT_TRUE(matches("class string { public: string(); }; "
839 "string GetStringByValue();"
840 "void FunctionTakesString(string s);"
841 "void run() { FunctionTakesString(GetStringByValue()); }",
842 TempExpression));
845 TEST_P(ASTMatchersTest, MaterializeTemporaryExpr_MatchesTemporary) {
846 if (!GetParam().isCXX()) {
847 return;
850 StringRef ClassString = "class string { public: string(); int length(); }; ";
851 StatementMatcher TempExpression =
852 traverse(TK_AsIs, materializeTemporaryExpr());
854 EXPECT_TRUE(notMatches(ClassString +
855 "string* GetStringPointer(); "
856 "void FunctionTakesStringPtr(string* s);"
857 "void run() {"
858 " string* s = GetStringPointer();"
859 " FunctionTakesStringPtr(GetStringPointer());"
860 " FunctionTakesStringPtr(s);"
861 "}",
862 TempExpression));
864 EXPECT_TRUE(matches(ClassString +
865 "string GetStringByValue();"
866 "void run() { int k = GetStringByValue().length(); }",
867 TempExpression));
869 EXPECT_TRUE(notMatches(ClassString + "string GetStringByValue();"
870 "void run() { GetStringByValue(); }",
871 TempExpression));
874 TEST_P(ASTMatchersTest, Matcher_NewExpression) {
875 if (!GetParam().isCXX()) {
876 return;
879 StatementMatcher New = cxxNewExpr();
881 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
882 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X(); }", New));
883 EXPECT_TRUE(
884 matches("class X { public: X(int); }; void x() { new X(0); }", New));
885 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
888 TEST_P(ASTMatchersTest, Matcher_DeleteExpression) {
889 if (!GetParam().isCXX()) {
890 return;
892 EXPECT_TRUE(
893 matches("struct A {}; void f(A* a) { delete a; }", cxxDeleteExpr()));
896 TEST_P(ASTMatchersTest, Matcher_NoexceptExpression) {
897 if (!GetParam().isCXX11OrLater()) {
898 return;
900 StatementMatcher NoExcept = cxxNoexceptExpr();
901 EXPECT_TRUE(matches("void foo(); bool bar = noexcept(foo());", NoExcept));
902 EXPECT_TRUE(
903 matches("void foo() noexcept; bool bar = noexcept(foo());", NoExcept));
904 EXPECT_TRUE(notMatches("void foo() noexcept;", NoExcept));
905 EXPECT_TRUE(notMatches("void foo() noexcept(0+1);", NoExcept));
906 EXPECT_TRUE(matches("void foo() noexcept(noexcept(1+1));", NoExcept));
909 TEST_P(ASTMatchersTest, Matcher_DefaultArgument) {
910 if (!GetParam().isCXX()) {
911 return;
913 StatementMatcher Arg = cxxDefaultArgExpr();
914 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
915 EXPECT_TRUE(
916 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
917 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
920 TEST_P(ASTMatchersTest, StringLiteral) {
921 StatementMatcher Literal = stringLiteral();
922 EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
923 // with escaped characters
924 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
925 // no matching -- though the data type is the same, there is no string literal
926 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
929 TEST_P(ASTMatchersTest, StringLiteral_CXX) {
930 if (!GetParam().isCXX()) {
931 return;
933 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", stringLiteral()));
936 TEST_P(ASTMatchersTest, CharacterLiteral) {
937 EXPECT_TRUE(matches("const char c = 'c';", characterLiteral()));
938 EXPECT_TRUE(notMatches("const char c = 0x1;", characterLiteral()));
941 TEST_P(ASTMatchersTest, CharacterLiteral_CXX) {
942 if (!GetParam().isCXX()) {
943 return;
945 // wide character
946 EXPECT_TRUE(matches("const char c = L'c';", characterLiteral()));
947 // wide character, Hex encoded, NOT MATCHED!
948 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", characterLiteral()));
951 TEST_P(ASTMatchersTest, IntegerLiteral) {
952 StatementMatcher HasIntLiteral = integerLiteral();
953 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
954 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
955 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
956 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
958 // Non-matching cases (character literals, float and double)
959 EXPECT_TRUE(notMatches("int i = L'a';",
960 HasIntLiteral)); // this is actually a character
961 // literal cast to int
962 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
963 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
964 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
966 // Negative integers.
967 EXPECT_TRUE(
968 matches("int i = -10;",
969 unaryOperator(hasOperatorName("-"),
970 hasUnaryOperand(integerLiteral(equals(10))))));
973 TEST_P(ASTMatchersTest, FloatLiteral) {
974 StatementMatcher HasFloatLiteral = floatLiteral();
975 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
976 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
977 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
978 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
979 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
980 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
981 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
982 EXPECT_TRUE(
983 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
985 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
986 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
987 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
988 EXPECT_TRUE(
989 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
992 TEST_P(ASTMatchersTest, CXXNullPtrLiteralExpr) {
993 if (!GetParam().isCXX11OrLater()) {
994 return;
996 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
999 TEST_P(ASTMatchersTest, ChooseExpr) {
1000 EXPECT_TRUE(matches("void f() { (void)__builtin_choose_expr(1, 2, 3); }",
1001 chooseExpr()));
1004 TEST_P(ASTMatchersTest, ConvertVectorExpr) {
1005 EXPECT_TRUE(matches(
1006 "typedef double vector4double __attribute__((__vector_size__(32)));"
1007 "typedef float vector4float __attribute__((__vector_size__(16)));"
1008 "vector4float vf;"
1009 "void f() { (void)__builtin_convertvector(vf, vector4double); }",
1010 convertVectorExpr()));
1011 EXPECT_TRUE(notMatches("void f() { (void)__builtin_choose_expr(1, 2, 3); }",
1012 convertVectorExpr()));
1015 TEST_P(ASTMatchersTest, GNUNullExpr) {
1016 if (!GetParam().isCXX()) {
1017 return;
1019 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
1022 TEST_P(ASTMatchersTest, GenericSelectionExpr) {
1023 EXPECT_TRUE(matches("void f() { (void)_Generic(1, int: 1, float: 2.0); }",
1024 genericSelectionExpr()));
1027 TEST_P(ASTMatchersTest, AtomicExpr) {
1028 EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }",
1029 atomicExpr()));
1032 TEST_P(ASTMatchersTest, Initializers_C99) {
1033 if (!GetParam().isC99OrLater()) {
1034 return;
1036 EXPECT_TRUE(matches(
1037 "void foo() { struct point { double x; double y; };"
1038 " struct point ptarray[10] = "
1039 " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1040 initListExpr(hasSyntacticForm(initListExpr(
1041 has(designatedInitExpr(designatorCountIs(2),
1042 hasDescendant(floatLiteral(equals(1.0))),
1043 hasDescendant(integerLiteral(equals(2))))),
1044 has(designatedInitExpr(designatorCountIs(2),
1045 hasDescendant(floatLiteral(equals(2.0))),
1046 hasDescendant(integerLiteral(equals(2))))),
1047 has(designatedInitExpr(
1048 designatorCountIs(2), hasDescendant(floatLiteral(equals(1.0))),
1049 hasDescendant(integerLiteral(equals(0))))))))));
1052 TEST_P(ASTMatchersTest, Initializers_CXX) {
1053 if (GetParam().Language != Lang_CXX03) {
1054 // FIXME: Make this test pass with other C++ standard versions.
1055 return;
1057 EXPECT_TRUE(matches(
1058 "void foo() { struct point { double x; double y; };"
1059 " struct point ptarray[10] = "
1060 " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1061 initListExpr(
1062 has(cxxConstructExpr(requiresZeroInitialization())),
1063 has(initListExpr(
1064 hasType(asString("struct point")), has(floatLiteral(equals(1.0))),
1065 has(implicitValueInitExpr(hasType(asString("double")))))),
1066 has(initListExpr(hasType(asString("struct point")),
1067 has(floatLiteral(equals(2.0))),
1068 has(floatLiteral(equals(1.0))))))));
1071 TEST_P(ASTMatchersTest, ParenListExpr) {
1072 if (!GetParam().isCXX()) {
1073 return;
1075 EXPECT_TRUE(
1076 matches("template<typename T> class foo { void bar() { foo X(*this); } };"
1077 "template class foo<int>;",
1078 varDecl(hasInitializer(parenListExpr(has(unaryOperator()))))));
1081 TEST_P(ASTMatchersTest, StmtExpr) {
1082 EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }",
1083 varDecl(hasInitializer(stmtExpr()))));
1086 TEST_P(ASTMatchersTest, PredefinedExpr) {
1087 // __func__ expands as StringLiteral("foo")
1088 EXPECT_TRUE(matches("void foo() { __func__; }",
1089 predefinedExpr(hasType(asString("const char[4]")),
1090 has(stringLiteral()))));
1093 TEST_P(ASTMatchersTest, AsmStatement) {
1094 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
1097 TEST_P(ASTMatchersTest, HasCondition) {
1098 if (!GetParam().isCXX()) {
1099 // FIXME: Add a test for `hasCondition()` that does not depend on C++.
1100 return;
1103 StatementMatcher Condition =
1104 ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
1106 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
1107 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
1108 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
1109 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
1110 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
1113 TEST_P(ASTMatchersTest, ConditionalOperator) {
1114 if (!GetParam().isCXX()) {
1115 // FIXME: Add a test for `conditionalOperator()` that does not depend on
1116 // C++.
1117 return;
1120 StatementMatcher Conditional =
1121 conditionalOperator(hasCondition(cxxBoolLiteral(equals(true))),
1122 hasTrueExpression(cxxBoolLiteral(equals(false))));
1124 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
1125 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
1126 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
1128 StatementMatcher ConditionalFalse =
1129 conditionalOperator(hasFalseExpression(cxxBoolLiteral(equals(false))));
1131 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
1132 EXPECT_TRUE(
1133 notMatches("void x() { true ? false : true; }", ConditionalFalse));
1135 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
1136 EXPECT_TRUE(
1137 notMatches("void x() { true ? false : true; }", ConditionalFalse));
1140 TEST_P(ASTMatchersTest, BinaryConditionalOperator) {
1141 if (!GetParam().isCXX()) {
1142 // FIXME: This test should work in non-C++ language modes.
1143 return;
1146 StatementMatcher AlwaysOne = traverse(
1147 TK_AsIs, binaryConditionalOperator(
1148 hasCondition(implicitCastExpr(has(opaqueValueExpr(
1149 hasSourceExpression((integerLiteral(equals(1)))))))),
1150 hasFalseExpression(integerLiteral(equals(0)))));
1152 EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne));
1154 StatementMatcher FourNotFive = binaryConditionalOperator(
1155 hasTrueExpression(
1156 opaqueValueExpr(hasSourceExpression((integerLiteral(equals(4)))))),
1157 hasFalseExpression(integerLiteral(equals(5))));
1159 EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive));
1162 TEST_P(ASTMatchersTest, ArraySubscriptExpr) {
1163 EXPECT_TRUE(
1164 matches("int i[2]; void f() { i[1] = 1; }", arraySubscriptExpr()));
1165 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }", arraySubscriptExpr()));
1168 TEST_P(ASTMatchersTest, ForStmt) {
1169 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
1170 EXPECT_TRUE(matches("void f() { if(1) for(;;); }", forStmt()));
1173 TEST_P(ASTMatchersTest, ForStmt_CXX11) {
1174 if (!GetParam().isCXX11OrLater()) {
1175 return;
1177 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
1178 "void f() { for (auto &a : as); }",
1179 forStmt()));
1182 TEST_P(ASTMatchersTest, ForStmt_NoFalsePositives) {
1183 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
1184 EXPECT_TRUE(notMatches("void f() { if(1); }", forStmt()));
1187 TEST_P(ASTMatchersTest, CompoundStatement) {
1188 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
1189 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
1190 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
1193 TEST_P(ASTMatchersTest, CompoundStatement_DoesNotMatchEmptyStruct) {
1194 if (!GetParam().isCXX()) {
1195 // FIXME: Add a similar test that does not depend on C++.
1196 return;
1198 // It's not a compound statement just because there's "{}" in the source
1199 // text. This is an AST search, not grep.
1200 EXPECT_TRUE(notMatches("namespace n { struct S {}; }", compoundStmt()));
1201 EXPECT_TRUE(
1202 matches("namespace n { struct S { void f() {{}} }; }", compoundStmt()));
1205 TEST_P(ASTMatchersTest, CastExpr_MatchesExplicitCasts) {
1206 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
1209 TEST_P(ASTMatchersTest, CastExpr_MatchesExplicitCasts_CXX) {
1210 if (!GetParam().isCXX()) {
1211 return;
1213 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);", castExpr()));
1214 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
1215 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
1218 TEST_P(ASTMatchersTest, CastExpression_MatchesImplicitCasts) {
1219 // This test creates an implicit cast from int to char.
1220 EXPECT_TRUE(matches("char c = 0;", traverse(TK_AsIs, castExpr())));
1221 // This test creates an implicit cast from lvalue to rvalue.
1222 EXPECT_TRUE(matches("void f() { char c = 0, d = c; }",
1223 traverse(TK_AsIs, castExpr())));
1226 TEST_P(ASTMatchersTest, CastExpr_DoesNotMatchNonCasts) {
1227 if (GetParam().isC()) {
1228 // This does have a cast in C
1229 EXPECT_TRUE(matches("char c = '0';", implicitCastExpr()));
1230 } else {
1231 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
1233 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
1234 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
1237 TEST_P(ASTMatchersTest, CastExpr_DoesNotMatchNonCasts_CXX) {
1238 if (!GetParam().isCXX()) {
1239 return;
1241 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
1244 TEST_P(ASTMatchersTest, CXXReinterpretCastExpr) {
1245 if (!GetParam().isCXX()) {
1246 return;
1248 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
1249 cxxReinterpretCastExpr()));
1252 TEST_P(ASTMatchersTest, CXXReinterpretCastExpr_DoesNotMatchOtherCasts) {
1253 if (!GetParam().isCXX()) {
1254 return;
1256 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
1257 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
1258 cxxReinterpretCastExpr()));
1259 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
1260 cxxReinterpretCastExpr()));
1261 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1262 "B b;"
1263 "D* p = dynamic_cast<D*>(&b);",
1264 cxxReinterpretCastExpr()));
1267 TEST_P(ASTMatchersTest, CXXFunctionalCastExpr_MatchesSimpleCase) {
1268 if (!GetParam().isCXX()) {
1269 return;
1271 StringRef foo_class = "class Foo { public: Foo(const char*); };";
1272 EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
1273 cxxFunctionalCastExpr()));
1276 TEST_P(ASTMatchersTest, CXXFunctionalCastExpr_DoesNotMatchOtherCasts) {
1277 if (!GetParam().isCXX()) {
1278 return;
1280 StringRef FooClass = "class Foo { public: Foo(const char*); };";
1281 EXPECT_TRUE(
1282 notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
1283 cxxFunctionalCastExpr()));
1284 EXPECT_TRUE(notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
1285 cxxFunctionalCastExpr()));
1288 TEST_P(ASTMatchersTest, CXXDynamicCastExpr) {
1289 if (!GetParam().isCXX()) {
1290 return;
1292 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
1293 "B b;"
1294 "D* p = dynamic_cast<D*>(&b);",
1295 cxxDynamicCastExpr()));
1298 TEST_P(ASTMatchersTest, CXXStaticCastExpr_MatchesSimpleCase) {
1299 if (!GetParam().isCXX()) {
1300 return;
1302 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));", cxxStaticCastExpr()));
1305 TEST_P(ASTMatchersTest, CXXStaticCastExpr_DoesNotMatchOtherCasts) {
1306 if (!GetParam().isCXX()) {
1307 return;
1309 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
1310 EXPECT_TRUE(
1311 notMatches("char q, *p = const_cast<char*>(&q);", cxxStaticCastExpr()));
1312 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
1313 cxxStaticCastExpr()));
1314 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1315 "B b;"
1316 "D* p = dynamic_cast<D*>(&b);",
1317 cxxStaticCastExpr()));
1320 TEST_P(ASTMatchersTest, CStyleCastExpr_MatchesSimpleCase) {
1321 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
1324 TEST_P(ASTMatchersTest, CStyleCastExpr_DoesNotMatchOtherCasts) {
1325 if (!GetParam().isCXX()) {
1326 return;
1328 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
1329 "char q, *r = const_cast<char*>(&q);"
1330 "void* s = reinterpret_cast<char*>(&s);"
1331 "struct B { virtual ~B() {} }; struct D : B {};"
1332 "B b;"
1333 "D* t = dynamic_cast<D*>(&b);",
1334 cStyleCastExpr()));
1337 TEST_P(ASTMatchersTest, ImplicitCastExpr_MatchesSimpleCase) {
1338 // This test creates an implicit const cast.
1339 EXPECT_TRUE(
1340 matches("void f() { int x = 0; const int y = x; }",
1341 traverse(TK_AsIs, varDecl(hasInitializer(implicitCastExpr())))));
1342 // This test creates an implicit cast from int to char.
1343 EXPECT_TRUE(
1344 matches("char c = 0;",
1345 traverse(TK_AsIs, varDecl(hasInitializer(implicitCastExpr())))));
1346 // This test creates an implicit array-to-pointer cast.
1347 EXPECT_TRUE(
1348 matches("int arr[6]; int *p = arr;",
1349 traverse(TK_AsIs, varDecl(hasInitializer(implicitCastExpr())))));
1352 TEST_P(ASTMatchersTest, ImplicitCastExpr_DoesNotMatchIncorrectly) {
1353 // This test verifies that implicitCastExpr() matches exactly when implicit
1354 // casts are present, and that it ignores explicit and paren casts.
1356 // These two test cases have no casts.
1357 EXPECT_TRUE(
1358 notMatches("int x = 0;", varDecl(hasInitializer(implicitCastExpr()))));
1359 EXPECT_TRUE(
1360 notMatches("int x = (0);", varDecl(hasInitializer(implicitCastExpr()))));
1361 EXPECT_TRUE(notMatches("void f() { int x = 0; double d = (double) x; }",
1362 varDecl(hasInitializer(implicitCastExpr()))));
1365 TEST_P(ASTMatchersTest, ImplicitCastExpr_DoesNotMatchIncorrectly_CXX) {
1366 if (!GetParam().isCXX()) {
1367 return;
1369 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
1370 varDecl(hasInitializer(implicitCastExpr()))));
1371 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
1372 varDecl(hasInitializer(implicitCastExpr()))));
1375 TEST_P(ASTMatchersTest, Stmt_DoesNotMatchDeclarations) {
1376 EXPECT_TRUE(notMatches("struct X {};", stmt()));
1379 TEST_P(ASTMatchersTest, Stmt_MatchesCompoundStatments) {
1380 EXPECT_TRUE(matches("void x() {}", stmt()));
1383 TEST_P(ASTMatchersTest, DeclStmt_DoesNotMatchCompoundStatements) {
1384 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
1387 TEST_P(ASTMatchersTest, DeclStmt_MatchesVariableDeclarationStatements) {
1388 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
1391 TEST_P(ASTMatchersTest, ExprWithCleanups_MatchesExprWithCleanups) {
1392 if (!GetParam().isCXX()) {
1393 return;
1395 EXPECT_TRUE(
1396 matches("struct Foo { ~Foo(); };"
1397 "const Foo f = Foo();",
1398 traverse(TK_AsIs, varDecl(hasInitializer(exprWithCleanups())))));
1399 EXPECT_FALSE(
1400 matches("struct Foo { }; Foo a;"
1401 "const Foo f = a;",
1402 traverse(TK_AsIs, varDecl(hasInitializer(exprWithCleanups())))));
1405 TEST_P(ASTMatchersTest, InitListExpr) {
1406 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
1407 initListExpr(hasType(asString("int[2]")))));
1408 EXPECT_TRUE(matches("struct B { int x, y; }; struct B b = { 5, 6 };",
1409 initListExpr(hasType(recordDecl(hasName("B"))))));
1410 EXPECT_TRUE(
1411 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
1414 TEST_P(ASTMatchersTest, InitListExpr_CXX) {
1415 if (!GetParam().isCXX()) {
1416 return;
1418 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
1419 "void f();"
1420 "S s[1] = { &f };",
1421 declRefExpr(to(functionDecl(hasName("f"))))));
1424 TEST_P(ASTMatchersTest,
1425 CXXStdInitializerListExpression_MatchesCXXStdInitializerListExpression) {
1426 if (!GetParam().isCXX11OrLater()) {
1427 return;
1429 StringRef code = "namespace std {"
1430 "template <typename E> class initializer_list {"
1431 " public: const E *a, *b;"
1432 "};"
1434 "struct A {"
1435 " A(std::initializer_list<int>) {}"
1436 "};";
1437 EXPECT_TRUE(matches(
1438 code + "A a{0};",
1439 traverse(TK_AsIs, cxxConstructExpr(has(cxxStdInitializerListExpr()),
1440 hasDeclaration(cxxConstructorDecl(
1441 ofClass(hasName("A"))))))));
1442 EXPECT_TRUE(matches(
1443 code + "A a = {0};",
1444 traverse(TK_AsIs, cxxConstructExpr(has(cxxStdInitializerListExpr()),
1445 hasDeclaration(cxxConstructorDecl(
1446 ofClass(hasName("A"))))))));
1448 EXPECT_TRUE(notMatches("int a[] = { 1, 2 };", cxxStdInitializerListExpr()));
1449 EXPECT_TRUE(notMatches("struct B { int x, y; }; B b = { 5, 6 };",
1450 cxxStdInitializerListExpr()));
1453 TEST_P(ASTMatchersTest, UsingDecl_MatchesUsingDeclarations) {
1454 if (!GetParam().isCXX()) {
1455 return;
1457 EXPECT_TRUE(matches("namespace X { int x; } using X::x;", usingDecl()));
1460 TEST_P(ASTMatchersTest, UsingDecl_MatchesShadowUsingDelcarations) {
1461 if (!GetParam().isCXX()) {
1462 return;
1464 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
1465 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
1468 TEST_P(ASTMatchersTest, UsingEnumDecl_MatchesUsingEnumDeclarations) {
1469 if (!GetParam().isCXX20OrLater()) {
1470 return;
1472 EXPECT_TRUE(
1473 matches("namespace X { enum x {}; } using enum X::x;", usingEnumDecl()));
1476 TEST_P(ASTMatchersTest, UsingEnumDecl_MatchesShadowUsingDeclarations) {
1477 if (!GetParam().isCXX20OrLater()) {
1478 return;
1480 EXPECT_TRUE(matches("namespace f { enum a {b}; } using enum f::a;",
1481 usingEnumDecl(hasAnyUsingShadowDecl(hasName("b")))));
1484 TEST_P(ASTMatchersTest, UsingDirectiveDecl_MatchesUsingNamespace) {
1485 if (!GetParam().isCXX()) {
1486 return;
1488 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
1489 usingDirectiveDecl()));
1490 EXPECT_FALSE(
1491 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
1494 TEST_P(ASTMatchersTest, WhileStmt) {
1495 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
1496 EXPECT_TRUE(matches("void x() { while(1); }", whileStmt()));
1497 EXPECT_TRUE(notMatches("void x() { do {} while(1); }", whileStmt()));
1500 TEST_P(ASTMatchersTest, DoStmt_MatchesDoLoops) {
1501 EXPECT_TRUE(matches("void x() { do {} while(1); }", doStmt()));
1502 EXPECT_TRUE(matches("void x() { do ; while(0); }", doStmt()));
1505 TEST_P(ASTMatchersTest, DoStmt_DoesNotMatchWhileLoops) {
1506 EXPECT_TRUE(notMatches("void x() { while(1) {} }", doStmt()));
1509 TEST_P(ASTMatchersTest, SwitchCase_MatchesCase) {
1510 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
1511 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
1512 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
1513 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
1516 TEST_P(ASTMatchersTest, SwitchCase_MatchesSwitch) {
1517 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
1518 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
1519 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
1520 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
1523 TEST_P(ASTMatchersTest, CxxExceptionHandling_SimpleCases) {
1524 if (!GetParam().isCXX()) {
1525 return;
1527 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
1528 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
1529 EXPECT_TRUE(
1530 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
1531 EXPECT_TRUE(
1532 matches("void foo() try { throw; } catch(int X) { }", cxxThrowExpr()));
1533 EXPECT_TRUE(
1534 matches("void foo() try { throw 5;} catch(int X) { }", cxxThrowExpr()));
1535 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
1536 cxxCatchStmt(isCatchAll())));
1537 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
1538 cxxCatchStmt(isCatchAll())));
1539 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
1540 varDecl(isExceptionVariable())));
1541 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
1542 varDecl(isExceptionVariable())));
1545 TEST_P(ASTMatchersTest, ParenExpr_SimpleCases) {
1546 EXPECT_TRUE(matches("int i = (3);", traverse(TK_AsIs, parenExpr())));
1547 EXPECT_TRUE(matches("int i = (3 + 7);", traverse(TK_AsIs, parenExpr())));
1548 EXPECT_TRUE(notMatches("int i = 3;", traverse(TK_AsIs, parenExpr())));
1549 EXPECT_TRUE(notMatches("int f() { return 1; }; void g() { int a = f(); }",
1550 traverse(TK_AsIs, parenExpr())));
1553 TEST_P(ASTMatchersTest, IgnoringParens) {
1554 EXPECT_FALSE(matches("const char* str = (\"my-string\");",
1555 traverse(TK_AsIs, implicitCastExpr(hasSourceExpression(
1556 stringLiteral())))));
1557 EXPECT_TRUE(
1558 matches("const char* str = (\"my-string\");",
1559 traverse(TK_AsIs, implicitCastExpr(hasSourceExpression(
1560 ignoringParens(stringLiteral()))))));
1563 TEST_P(ASTMatchersTest, QualType) {
1564 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
1567 TEST_P(ASTMatchersTest, ConstantArrayType) {
1568 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
1569 EXPECT_TRUE(notMatches("void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
1570 constantArrayType(hasElementType(builtinType()))));
1572 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
1573 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
1574 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
1577 TEST_P(ASTMatchersTest, DependentSizedArrayType) {
1578 if (!GetParam().isCXX()) {
1579 return;
1581 EXPECT_TRUE(
1582 matches("template <typename T, int Size> class array { T data[Size]; };",
1583 dependentSizedArrayType()));
1584 EXPECT_TRUE(
1585 notMatches("int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1586 dependentSizedArrayType()));
1589 TEST_P(ASTMatchersTest, DependentSizedExtVectorType) {
1590 if (!GetParam().isCXX()) {
1591 return;
1593 EXPECT_TRUE(matches("template<typename T, int Size>"
1594 "class vector {"
1595 " typedef T __attribute__((ext_vector_type(Size))) type;"
1596 "};",
1597 dependentSizedExtVectorType()));
1598 EXPECT_TRUE(
1599 notMatches("int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1600 dependentSizedExtVectorType()));
1603 TEST_P(ASTMatchersTest, IncompleteArrayType) {
1604 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
1605 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
1607 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
1608 incompleteArrayType()));
1611 TEST_P(ASTMatchersTest, VariableArrayType) {
1612 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
1613 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
1615 EXPECT_TRUE(matches("void f(int b) { int a[b]; }",
1616 variableArrayType(hasSizeExpr(ignoringImpCasts(
1617 declRefExpr(to(varDecl(hasName("b")))))))));
1620 TEST_P(ASTMatchersTest, AtomicType) {
1621 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1622 llvm::Triple::Win32) {
1623 // FIXME: Make this work for MSVC.
1624 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
1626 EXPECT_TRUE(
1627 matches("_Atomic(int) i;", atomicType(hasValueType(isInteger()))));
1628 EXPECT_TRUE(
1629 notMatches("_Atomic(float) f;", atomicType(hasValueType(isInteger()))));
1633 TEST_P(ASTMatchersTest, AutoType) {
1634 if (!GetParam().isCXX11OrLater()) {
1635 return;
1637 EXPECT_TRUE(matches("auto i = 2;", autoType()));
1638 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
1639 autoType()));
1641 EXPECT_TRUE(matches("auto i = 2;", varDecl(hasType(isInteger()))));
1642 EXPECT_TRUE(matches("struct X{}; auto x = X{};",
1643 varDecl(hasType(recordDecl(hasName("X"))))));
1645 // FIXME: Matching against the type-as-written can't work here, because the
1646 // type as written was not deduced.
1647 // EXPECT_TRUE(matches("auto a = 1;",
1648 // autoType(hasDeducedType(isInteger()))));
1649 // EXPECT_TRUE(notMatches("auto b = 2.0;",
1650 // autoType(hasDeducedType(isInteger()))));
1653 TEST_P(ASTMatchersTest, DecltypeType) {
1654 if (!GetParam().isCXX11OrLater()) {
1655 return;
1657 EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;", decltypeType()));
1658 EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;",
1659 decltypeType(hasUnderlyingType(isInteger()))));
1662 TEST_P(ASTMatchersTest, FunctionType) {
1663 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
1664 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
1667 TEST_P(ASTMatchersTest, IgnoringParens_Type) {
1668 EXPECT_TRUE(
1669 notMatches("void (*fp)(void);", pointerType(pointee(functionType()))));
1670 EXPECT_TRUE(matches("void (*fp)(void);",
1671 pointerType(pointee(ignoringParens(functionType())))));
1674 TEST_P(ASTMatchersTest, FunctionProtoType) {
1675 EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
1676 EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
1677 EXPECT_TRUE(matches("void f(void);", functionProtoType(parameterCountIs(0))));
1680 TEST_P(ASTMatchersTest, FunctionProtoType_C) {
1681 if (!GetParam().isCOrEarlier(17)) {
1682 return;
1684 EXPECT_TRUE(notMatches("void f();", functionProtoType()));
1687 TEST_P(ASTMatchersTest, FunctionProtoType_CXX) {
1688 if (!GetParam().isCXX()) {
1689 return;
1691 EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
1694 TEST_P(ASTMatchersTest, ParenType) {
1695 EXPECT_TRUE(
1696 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
1697 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
1699 EXPECT_TRUE(matches(
1700 "int (*ptr_to_func)(int);",
1701 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1702 EXPECT_TRUE(notMatches(
1703 "int (*ptr_to_array)[4];",
1704 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1707 TEST_P(ASTMatchersTest, PointerType) {
1708 // FIXME: Reactive when these tests can be more specific (not matching
1709 // implicit code on certain platforms), likely when we have hasDescendant for
1710 // Types/TypeLocs.
1711 // EXPECT_TRUE(matchAndVerifyResultTrue(
1712 // "int* a;",
1713 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
1714 // std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1715 // EXPECT_TRUE(matchAndVerifyResultTrue(
1716 // "int* a;",
1717 // pointerTypeLoc().bind("loc"),
1718 // std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1719 EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(qualType())))));
1720 EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(pointerType())))));
1721 EXPECT_TRUE(matches("int* b; int* * const a = &b;",
1722 loc(qualType(isConstQualified(), pointerType()))));
1724 StringRef Fragment = "int *ptr;";
1725 EXPECT_TRUE(notMatches(Fragment,
1726 varDecl(hasName("ptr"), hasType(blockPointerType()))));
1727 EXPECT_TRUE(notMatches(
1728 Fragment, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1729 EXPECT_TRUE(
1730 matches(Fragment, varDecl(hasName("ptr"), hasType(pointerType()))));
1731 EXPECT_TRUE(
1732 notMatches(Fragment, varDecl(hasName("ptr"), hasType(referenceType()))));
1735 TEST_P(ASTMatchersTest, PointerType_CXX) {
1736 if (!GetParam().isCXX()) {
1737 return;
1739 StringRef Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
1740 EXPECT_TRUE(notMatches(Fragment,
1741 varDecl(hasName("ptr"), hasType(blockPointerType()))));
1742 EXPECT_TRUE(
1743 matches(Fragment, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1744 EXPECT_TRUE(
1745 notMatches(Fragment, varDecl(hasName("ptr"), hasType(pointerType()))));
1746 EXPECT_TRUE(
1747 notMatches(Fragment, varDecl(hasName("ptr"), hasType(referenceType()))));
1748 EXPECT_TRUE(notMatches(
1749 Fragment, varDecl(hasName("ptr"), hasType(lValueReferenceType()))));
1750 EXPECT_TRUE(notMatches(
1751 Fragment, varDecl(hasName("ptr"), hasType(rValueReferenceType()))));
1753 Fragment = "int a; int &ref = a;";
1754 EXPECT_TRUE(notMatches(Fragment,
1755 varDecl(hasName("ref"), hasType(blockPointerType()))));
1756 EXPECT_TRUE(notMatches(
1757 Fragment, varDecl(hasName("ref"), hasType(memberPointerType()))));
1758 EXPECT_TRUE(
1759 notMatches(Fragment, varDecl(hasName("ref"), hasType(pointerType()))));
1760 EXPECT_TRUE(
1761 matches(Fragment, varDecl(hasName("ref"), hasType(referenceType()))));
1762 EXPECT_TRUE(matches(Fragment,
1763 varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1764 EXPECT_TRUE(notMatches(
1765 Fragment, varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1768 TEST_P(ASTMatchersTest, PointerType_CXX11) {
1769 if (!GetParam().isCXX11OrLater()) {
1770 return;
1772 StringRef Fragment = "int &&ref = 2;";
1773 EXPECT_TRUE(notMatches(Fragment,
1774 varDecl(hasName("ref"), hasType(blockPointerType()))));
1775 EXPECT_TRUE(notMatches(
1776 Fragment, varDecl(hasName("ref"), hasType(memberPointerType()))));
1777 EXPECT_TRUE(
1778 notMatches(Fragment, varDecl(hasName("ref"), hasType(pointerType()))));
1779 EXPECT_TRUE(
1780 matches(Fragment, varDecl(hasName("ref"), hasType(referenceType()))));
1781 EXPECT_TRUE(notMatches(
1782 Fragment, varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1783 EXPECT_TRUE(matches(Fragment,
1784 varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1787 TEST_P(ASTMatchersTest, AutoRefTypes) {
1788 if (!GetParam().isCXX11OrLater()) {
1789 return;
1792 StringRef Fragment = "auto a = 1;"
1793 "auto b = a;"
1794 "auto &c = a;"
1795 "auto &&d = c;"
1796 "auto &&e = 2;";
1797 EXPECT_TRUE(
1798 notMatches(Fragment, varDecl(hasName("a"), hasType(referenceType()))));
1799 EXPECT_TRUE(
1800 notMatches(Fragment, varDecl(hasName("b"), hasType(referenceType()))));
1801 EXPECT_TRUE(
1802 matches(Fragment, varDecl(hasName("c"), hasType(referenceType()))));
1803 EXPECT_TRUE(
1804 matches(Fragment, varDecl(hasName("c"), hasType(lValueReferenceType()))));
1805 EXPECT_TRUE(notMatches(
1806 Fragment, varDecl(hasName("c"), hasType(rValueReferenceType()))));
1807 EXPECT_TRUE(
1808 matches(Fragment, varDecl(hasName("d"), hasType(referenceType()))));
1809 EXPECT_TRUE(
1810 matches(Fragment, varDecl(hasName("d"), hasType(lValueReferenceType()))));
1811 EXPECT_TRUE(notMatches(
1812 Fragment, varDecl(hasName("d"), hasType(rValueReferenceType()))));
1813 EXPECT_TRUE(
1814 matches(Fragment, varDecl(hasName("e"), hasType(referenceType()))));
1815 EXPECT_TRUE(notMatches(
1816 Fragment, varDecl(hasName("e"), hasType(lValueReferenceType()))));
1817 EXPECT_TRUE(
1818 matches(Fragment, varDecl(hasName("e"), hasType(rValueReferenceType()))));
1821 TEST_P(ASTMatchersTest, EnumType) {
1822 EXPECT_TRUE(
1823 matches("enum Color { Green }; enum Color color;", loc(enumType())));
1826 TEST_P(ASTMatchersTest, EnumType_CXX) {
1827 if (!GetParam().isCXX()) {
1828 return;
1830 EXPECT_TRUE(matches("enum Color { Green }; Color color;", loc(enumType())));
1833 TEST_P(ASTMatchersTest, EnumType_CXX11) {
1834 if (!GetParam().isCXX11OrLater()) {
1835 return;
1837 EXPECT_TRUE(
1838 matches("enum class Color { Green }; Color color;", loc(enumType())));
1841 TEST_P(ASTMatchersTest, PointerType_MatchesPointersToConstTypes) {
1842 EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1843 EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1844 EXPECT_TRUE(matches("int b; const int * a = &b;",
1845 loc(pointerType(pointee(builtinType())))));
1846 EXPECT_TRUE(matches("int b; const int * a = &b;",
1847 pointerType(pointee(builtinType()))));
1850 TEST_P(ASTMatchersTest, TypedefType) {
1851 EXPECT_TRUE(matches("typedef int X; X a;",
1852 varDecl(hasName("a"), hasType(elaboratedType(
1853 namesType(typedefType()))))));
1856 TEST_P(ASTMatchersTest, MacroQualifiedType) {
1857 EXPECT_TRUE(matches(
1859 #define CDECL __attribute__((cdecl))
1860 typedef void (CDECL *X)();
1862 typedefDecl(hasType(pointerType(pointee(macroQualifiedType()))))));
1863 EXPECT_TRUE(notMatches(
1865 typedef void (__attribute__((cdecl)) *Y)();
1867 typedefDecl(hasType(pointerType(pointee(macroQualifiedType()))))));
1870 TEST_P(ASTMatchersTest, TemplateSpecializationType) {
1871 if (!GetParam().isCXX()) {
1872 return;
1874 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
1875 templateSpecializationType()));
1878 TEST_P(ASTMatchersTest, DeducedTemplateSpecializationType) {
1879 if (!GetParam().isCXX17OrLater()) {
1880 return;
1882 EXPECT_TRUE(
1883 matches("template <typename T> class A{ public: A(T) {} }; A a(1);",
1884 deducedTemplateSpecializationType()));
1887 TEST_P(ASTMatchersTest, RecordType) {
1888 EXPECT_TRUE(matches("struct S {}; struct S s;",
1889 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1890 EXPECT_TRUE(notMatches("int i;",
1891 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1894 TEST_P(ASTMatchersTest, RecordType_CXX) {
1895 if (!GetParam().isCXX()) {
1896 return;
1898 EXPECT_TRUE(matches("class C {}; C c;", recordType()));
1899 EXPECT_TRUE(matches("struct S {}; S s;",
1900 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1903 TEST_P(ASTMatchersTest, ElaboratedType) {
1904 if (!GetParam().isCXX()) {
1905 // FIXME: Add a test for `elaboratedType()` that does not depend on C++.
1906 return;
1908 EXPECT_TRUE(matches("namespace N {"
1909 " namespace M {"
1910 " class D {};"
1911 " }"
1913 "N::M::D d;",
1914 elaboratedType()));
1915 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
1916 EXPECT_TRUE(matches("class C {}; C c;", elaboratedType()));
1919 TEST_P(ASTMatchersTest, SubstTemplateTypeParmType) {
1920 if (!GetParam().isCXX()) {
1921 return;
1923 StringRef code = "template <typename T>"
1924 "int F() {"
1925 " return 1 + T();"
1927 "int i = F<int>();";
1928 EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
1929 expr(hasType(substTemplateTypeParmType()))))));
1930 EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
1931 expr(hasType(substTemplateTypeParmType()))))));
1934 TEST_P(ASTMatchersTest, NestedNameSpecifier) {
1935 if (!GetParam().isCXX()) {
1936 return;
1938 EXPECT_TRUE(
1939 matches("namespace ns { struct A {}; } ns::A a;", nestedNameSpecifier()));
1940 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
1941 nestedNameSpecifier()));
1942 EXPECT_TRUE(
1943 matches("struct A { void f(); }; void A::f() {}", nestedNameSpecifier()));
1944 EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
1945 nestedNameSpecifier()));
1947 EXPECT_TRUE(matches("struct A { static void f() {} }; void g() { A::f(); }",
1948 nestedNameSpecifier()));
1949 EXPECT_TRUE(
1950 notMatches("struct A { static void f() {} }; void g(A* a) { a->f(); }",
1951 nestedNameSpecifier()));
1954 TEST_P(ASTMatchersTest, Attr) {
1955 // Windows adds some implicit attributes.
1956 bool AutomaticAttributes = StringRef(GetParam().Target).contains("win32");
1957 if (GetParam().isCXX11OrLater()) {
1958 EXPECT_TRUE(matches("struct [[clang::warn_unused_result]] F{};", attr()));
1960 // Unknown attributes are not parsed into an AST node.
1961 if (!AutomaticAttributes) {
1962 EXPECT_TRUE(notMatches("int x [[unknownattr]];", attr()));
1965 if (GetParam().isCXX17OrLater()) {
1966 EXPECT_TRUE(matches("struct [[nodiscard]] F{};", attr()));
1968 EXPECT_TRUE(matches("int x(int * __attribute__((nonnull)) );", attr()));
1969 if (!AutomaticAttributes) {
1970 EXPECT_TRUE(notMatches("struct F{}; int x(int *);", attr()));
1971 // Some known attributes are not parsed into an AST node.
1972 EXPECT_TRUE(notMatches("typedef int x __attribute__((ext_vector_type(1)));",
1973 attr()));
1977 TEST_P(ASTMatchersTest, NullStmt) {
1978 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
1979 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
1982 TEST_P(ASTMatchersTest, NamespaceAliasDecl) {
1983 if (!GetParam().isCXX()) {
1984 return;
1986 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
1987 namespaceAliasDecl(hasName("alias"))));
1990 TEST_P(ASTMatchersTest, NestedNameSpecifier_MatchesTypes) {
1991 if (!GetParam().isCXX()) {
1992 return;
1994 NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
1995 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
1996 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
1997 EXPECT_TRUE(
1998 matches("struct A { struct B { struct C {}; }; }; A::B::C c;", Matcher));
1999 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
2002 TEST_P(ASTMatchersTest, NestedNameSpecifier_MatchesNamespaceDecls) {
2003 if (!GetParam().isCXX()) {
2004 return;
2006 NestedNameSpecifierMatcher Matcher =
2007 nestedNameSpecifier(specifiesNamespace(hasName("ns")));
2008 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
2009 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
2010 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
2013 TEST_P(ASTMatchersTest,
2014 NestedNameSpecifier_MatchesNestedNameSpecifierPrefixes) {
2015 if (!GetParam().isCXX()) {
2016 return;
2018 EXPECT_TRUE(matches(
2019 "struct A { struct B { struct C {}; }; }; A::B::C c;",
2020 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
2021 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
2022 nestedNameSpecifierLoc(hasPrefix(specifiesTypeLoc(
2023 loc(qualType(asString("struct A"))))))));
2024 EXPECT_TRUE(matches(
2025 "namespace N { struct A { struct B { struct C {}; }; }; } N::A::B::C c;",
2026 nestedNameSpecifierLoc(hasPrefix(
2027 specifiesTypeLoc(loc(qualType(asString("struct N::A"))))))));
2030 template <typename T>
2031 class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
2032 public:
2033 bool run(const BoundNodes *Nodes, ASTContext *Context) override {
2034 const T *Node = Nodes->getNodeAs<T>("");
2035 return verify(*Nodes, *Context, Node);
2038 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
2039 // Use the original typed pointer to verify we can pass pointers to subtypes
2040 // to equalsNode.
2041 const T *TypedNode = cast<T>(Node);
2042 return selectFirst<T>(
2043 "", match(stmt(hasParent(
2044 stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
2045 *Node, Context)) != nullptr;
2047 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
2048 // Use the original typed pointer to verify we can pass pointers to subtypes
2049 // to equalsNode.
2050 const T *TypedNode = cast<T>(Node);
2051 return selectFirst<T>(
2052 "", match(decl(hasParent(
2053 decl(has(decl(equalsNode(TypedNode)))).bind(""))),
2054 *Node, Context)) != nullptr;
2056 bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
2057 // Use the original typed pointer to verify we can pass pointers to subtypes
2058 // to equalsNode.
2059 const T *TypedNode = cast<T>(Node);
2060 const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
2061 return selectFirst<T>(
2062 "", match(fieldDecl(hasParent(decl(has(fieldDecl(
2063 hasType(type(equalsNode(TypedNode)).bind(""))))))),
2064 *Dec, Context)) != nullptr;
2068 TEST_P(ASTMatchersTest, IsEqualTo_MatchesNodesByIdentity) {
2069 EXPECT_TRUE(matchAndVerifyResultTrue(
2070 "void f() { if (1) if(1) {} }", ifStmt().bind(""),
2071 std::make_unique<VerifyAncestorHasChildIsEqual<IfStmt>>()));
2074 TEST_P(ASTMatchersTest, IsEqualTo_MatchesNodesByIdentity_Cxx) {
2075 if (!GetParam().isCXX()) {
2076 return;
2078 EXPECT_TRUE(matchAndVerifyResultTrue(
2079 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
2080 std::make_unique<VerifyAncestorHasChildIsEqual<CXXRecordDecl>>()));
2081 EXPECT_TRUE(matchAndVerifyResultTrue(
2082 "class X { class Y {} y; };",
2083 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
2084 std::make_unique<VerifyAncestorHasChildIsEqual<Type>>()));
2087 TEST_P(ASTMatchersTest, TypedefDecl) {
2088 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
2089 typedefDecl(hasName("typedefDeclTest"))));
2092 TEST_P(ASTMatchersTest, TypedefDecl_Cxx) {
2093 if (!GetParam().isCXX11OrLater()) {
2094 return;
2096 EXPECT_TRUE(notMatches("using typedefDeclTest = int;",
2097 typedefDecl(hasName("typedefDeclTest"))));
2100 TEST_P(ASTMatchersTest, TypeAliasDecl) {
2101 EXPECT_TRUE(notMatches("typedef int typeAliasTest;",
2102 typeAliasDecl(hasName("typeAliasTest"))));
2105 TEST_P(ASTMatchersTest, TypeAliasDecl_CXX) {
2106 if (!GetParam().isCXX11OrLater()) {
2107 return;
2109 EXPECT_TRUE(matches("using typeAliasTest = int;",
2110 typeAliasDecl(hasName("typeAliasTest"))));
2113 TEST_P(ASTMatchersTest, TypedefNameDecl) {
2114 EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;",
2115 typedefNameDecl(hasName("typedefNameDeclTest1"))));
2118 TEST_P(ASTMatchersTest, TypedefNameDecl_CXX) {
2119 if (!GetParam().isCXX11OrLater()) {
2120 return;
2122 EXPECT_TRUE(matches("using typedefNameDeclTest = int;",
2123 typedefNameDecl(hasName("typedefNameDeclTest"))));
2126 TEST_P(ASTMatchersTest, TypeAliasTemplateDecl) {
2127 if (!GetParam().isCXX11OrLater()) {
2128 return;
2130 StringRef Code = R"(
2131 template <typename T>
2132 class X { T t; };
2134 template <typename T>
2135 using typeAliasTemplateDecl = X<T>;
2137 using typeAliasDecl = X<int>;
2139 EXPECT_TRUE(
2140 matches(Code, typeAliasTemplateDecl(hasName("typeAliasTemplateDecl"))));
2141 EXPECT_TRUE(
2142 notMatches(Code, typeAliasTemplateDecl(hasName("typeAliasDecl"))));
2145 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_BindsToConstIntVarDecl) {
2146 EXPECT_TRUE(matches("const int x = 0;",
2147 qualifiedTypeLoc(loc(asString("const int")))));
2150 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_BindsToConstIntFunctionDecl) {
2151 EXPECT_TRUE(matches("const int f() { return 5; }",
2152 qualifiedTypeLoc(loc(asString("const int")))));
2155 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_DoesNotBindToUnqualifiedVarDecl) {
2156 EXPECT_TRUE(notMatches("int x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2159 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_IntDoesNotBindToConstIntDecl) {
2160 EXPECT_TRUE(
2161 notMatches("const int x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2164 TEST_P(ASTMatchersTest, QualifiedTypeLocTest_IntDoesNotBindToConstFloatDecl) {
2165 EXPECT_TRUE(
2166 notMatches("const float x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2169 TEST_P(ASTMatchersTest, PointerTypeLocTest_BindsToAnyPointerTypeLoc) {
2170 auto matcher = varDecl(hasName("x"), hasTypeLoc(pointerTypeLoc()));
2171 EXPECT_TRUE(matches("int* x;", matcher));
2172 EXPECT_TRUE(matches("float* x;", matcher));
2173 EXPECT_TRUE(matches("char* x;", matcher));
2174 EXPECT_TRUE(matches("void* x;", matcher));
2177 TEST_P(ASTMatchersTest, PointerTypeLocTest_DoesNotBindToNonPointerTypeLoc) {
2178 auto matcher = varDecl(hasName("x"), hasTypeLoc(pointerTypeLoc()));
2179 EXPECT_TRUE(notMatches("int x;", matcher));
2180 EXPECT_TRUE(notMatches("float x;", matcher));
2181 EXPECT_TRUE(notMatches("char x;", matcher));
2184 TEST_P(ASTMatchersTest, ReferenceTypeLocTest_BindsToAnyReferenceTypeLoc) {
2185 if (!GetParam().isCXX()) {
2186 return;
2188 auto matcher = varDecl(hasName("r"), hasTypeLoc(referenceTypeLoc()));
2189 EXPECT_TRUE(matches("int rr = 3; int& r = rr;", matcher));
2190 EXPECT_TRUE(matches("int rr = 3; auto& r = rr;", matcher));
2191 EXPECT_TRUE(matches("int rr = 3; const int& r = rr;", matcher));
2192 EXPECT_TRUE(matches("float rr = 3.0; float& r = rr;", matcher));
2193 EXPECT_TRUE(matches("char rr = 'a'; char& r = rr;", matcher));
2196 TEST_P(ASTMatchersTest, ReferenceTypeLocTest_DoesNotBindToNonReferenceTypeLoc) {
2197 auto matcher = varDecl(hasName("r"), hasTypeLoc(referenceTypeLoc()));
2198 EXPECT_TRUE(notMatches("int r;", matcher));
2199 EXPECT_TRUE(notMatches("int r = 3;", matcher));
2200 EXPECT_TRUE(notMatches("const int r = 3;", matcher));
2201 EXPECT_TRUE(notMatches("int* r;", matcher));
2202 EXPECT_TRUE(notMatches("float r;", matcher));
2203 EXPECT_TRUE(notMatches("char r;", matcher));
2206 TEST_P(ASTMatchersTest, ReferenceTypeLocTest_BindsToAnyRvalueReferenceTypeLoc) {
2207 if (!GetParam().isCXX()) {
2208 return;
2210 auto matcher = varDecl(hasName("r"), hasTypeLoc(referenceTypeLoc()));
2211 EXPECT_TRUE(matches("int&& r = 3;", matcher));
2212 EXPECT_TRUE(matches("auto&& r = 3;", matcher));
2213 EXPECT_TRUE(matches("float&& r = 3.0;", matcher));
2216 TEST_P(ASTMatchersTest,
2217 TemplateSpecializationTypeLocTest_BindsToVarDeclTemplateSpecialization) {
2218 if (!GetParam().isCXX()) {
2219 return;
2221 EXPECT_TRUE(matches(
2222 "template <typename T> class C {}; C<char> var;",
2223 varDecl(hasName("var"), hasTypeLoc(elaboratedTypeLoc(hasNamedTypeLoc(
2224 templateSpecializationTypeLoc()))))));
2227 TEST_P(
2228 ASTMatchersTest,
2229 TemplateSpecializationTypeLocTest_DoesNotBindToNonTemplateSpecialization) {
2230 if (!GetParam().isCXX()) {
2231 return;
2233 EXPECT_TRUE(notMatches(
2234 "class C {}; C var;",
2235 varDecl(hasName("var"), hasTypeLoc(templateSpecializationTypeLoc()))));
2238 TEST_P(ASTMatchersTest,
2239 ElaboratedTypeLocTest_BindsToElaboratedObjectDeclaration) {
2240 if (!GetParam().isCXX()) {
2241 return;
2243 EXPECT_TRUE(matches("class C {}; class C c;",
2244 varDecl(hasName("c"), hasTypeLoc(elaboratedTypeLoc()))));
2247 TEST_P(ASTMatchersTest,
2248 ElaboratedTypeLocTest_BindsToNamespaceElaboratedObjectDeclaration) {
2249 if (!GetParam().isCXX()) {
2250 return;
2252 EXPECT_TRUE(matches("namespace N { class D {}; } N::D d;",
2253 varDecl(hasName("d"), hasTypeLoc(elaboratedTypeLoc()))));
2256 TEST_P(ASTMatchersTest,
2257 ElaboratedTypeLocTest_BindsToElaboratedStructDeclaration) {
2258 EXPECT_TRUE(matches("struct s {}; struct s ss;",
2259 varDecl(hasName("ss"), hasTypeLoc(elaboratedTypeLoc()))));
2262 TEST_P(ASTMatchersTest,
2263 ElaboratedTypeLocTest_BindsToBareElaboratedObjectDeclaration) {
2264 if (!GetParam().isCXX()) {
2265 return;
2267 EXPECT_TRUE(matches("class C {}; C c;",
2268 varDecl(hasName("c"), hasTypeLoc(elaboratedTypeLoc()))));
2271 TEST_P(
2272 ASTMatchersTest,
2273 ElaboratedTypeLocTest_DoesNotBindToNamespaceNonElaboratedObjectDeclaration) {
2274 if (!GetParam().isCXX()) {
2275 return;
2277 EXPECT_TRUE(matches("namespace N { class D {}; } using N::D; D d;",
2278 varDecl(hasName("d"), hasTypeLoc(elaboratedTypeLoc()))));
2281 TEST_P(ASTMatchersTest,
2282 ElaboratedTypeLocTest_BindsToBareElaboratedStructDeclaration) {
2283 if (!GetParam().isCXX()) {
2284 return;
2286 EXPECT_TRUE(matches("struct s {}; s ss;",
2287 varDecl(hasName("ss"), hasTypeLoc(elaboratedTypeLoc()))));
2290 TEST_P(ASTMatchersTest, LambdaCaptureTest) {
2291 if (!GetParam().isCXX11OrLater()) {
2292 return;
2294 EXPECT_TRUE(matches("int main() { int cc; auto f = [cc](){ return cc; }; }",
2295 lambdaExpr(hasAnyCapture(lambdaCapture()))));
2298 TEST_P(ASTMatchersTest, LambdaCaptureTest_BindsToCaptureOfVarDecl) {
2299 if (!GetParam().isCXX11OrLater()) {
2300 return;
2302 auto matcher = lambdaExpr(
2303 hasAnyCapture(lambdaCapture(capturesVar(varDecl(hasName("cc"))))));
2304 EXPECT_TRUE(matches("int main() { int cc; auto f = [cc](){ return cc; }; }",
2305 matcher));
2306 EXPECT_TRUE(matches("int main() { int cc; auto f = [&cc](){ return cc; }; }",
2307 matcher));
2308 EXPECT_TRUE(
2309 matches("int main() { int cc; auto f = [=](){ return cc; }; }", matcher));
2310 EXPECT_TRUE(
2311 matches("int main() { int cc; auto f = [&](){ return cc; }; }", matcher));
2312 EXPECT_TRUE(matches(
2313 "void f(int a) { int cc[a]; auto f = [&](){ return cc;}; }", matcher));
2316 TEST_P(ASTMatchersTest, LambdaCaptureTest_BindsToCaptureWithInitializer) {
2317 if (!GetParam().isCXX14OrLater()) {
2318 return;
2320 auto matcher = lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(
2321 varDecl(hasName("cc"), hasInitializer(integerLiteral(equals(1))))))));
2322 EXPECT_TRUE(
2323 matches("int main() { auto lambda = [cc = 1] {return cc;}; }", matcher));
2324 EXPECT_TRUE(
2325 matches("int main() { int cc = 2; auto lambda = [cc = 1] {return cc;}; }",
2326 matcher));
2329 TEST_P(ASTMatchersTest, LambdaCaptureTest_DoesNotBindToCaptureOfVarDecl) {
2330 if (!GetParam().isCXX11OrLater()) {
2331 return;
2333 auto matcher = lambdaExpr(
2334 hasAnyCapture(lambdaCapture(capturesVar(varDecl(hasName("cc"))))));
2335 EXPECT_FALSE(matches("int main() { auto f = [](){ return 5; }; }", matcher));
2336 EXPECT_FALSE(matches("int main() { int xx; auto f = [xx](){ return xx; }; }",
2337 matcher));
2340 TEST_P(ASTMatchersTest,
2341 LambdaCaptureTest_DoesNotBindToCaptureWithInitializerAndDifferentName) {
2342 if (!GetParam().isCXX14OrLater()) {
2343 return;
2345 EXPECT_FALSE(matches(
2346 "int main() { auto lambda = [xx = 1] {return xx;}; }",
2347 lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(varDecl(
2348 hasName("cc"), hasInitializer(integerLiteral(equals(1))))))))));
2351 TEST_P(ASTMatchersTest, LambdaCaptureTest_BindsToCaptureOfReferenceType) {
2352 if (!GetParam().isCXX20OrLater()) {
2353 return;
2355 auto matcher = lambdaExpr(hasAnyCapture(
2356 lambdaCapture(capturesVar(varDecl(hasType(referenceType()))))));
2357 EXPECT_TRUE(matches("template <class ...T> void f(T &...args) {"
2358 " [&...args = args] () mutable {"
2359 " }();"
2361 "int main() {"
2362 " int a;"
2363 " f(a);"
2364 "}", matcher));
2365 EXPECT_FALSE(matches("template <class ...T> void f(T &...args) {"
2366 " [...args = args] () mutable {"
2367 " }();"
2369 "int main() {"
2370 " int a;"
2371 " f(a);"
2372 "}", matcher));
2375 TEST_P(ASTMatchersTest, IsDerivedFromRecursion) {
2376 if (!GetParam().isCXX11OrLater())
2377 return;
2379 // Check we don't crash on cycles in the traversal and inheritance hierarchy.
2380 // Clang will normally enforce there are no cycles, but matchers opted to
2381 // traverse primary template for dependent specializations, spuriously
2382 // creating the cycles.
2383 DeclarationMatcher matcher = cxxRecordDecl(isDerivedFrom("X"));
2384 EXPECT_TRUE(notMatches(R"cpp(
2385 template <typename T1, typename T2>
2386 struct M;
2388 template <typename T1>
2389 struct M<T1, void> {};
2391 template <typename T1, typename T2>
2392 struct L : M<T1, T2> {};
2394 template <typename T1, typename T2>
2395 struct M : L<M<T1, T2>, M<T1, T2>> {};
2396 )cpp",
2397 matcher));
2399 // Check the running time is not exponential. The number of subojects to
2400 // traverse grows as fibonacci numbers even though the number of bases to
2401 // traverse is quadratic.
2402 // The test will hang if implementation of matchers traverses all subojects.
2403 EXPECT_TRUE(notMatches(R"cpp(
2404 template <class T> struct A0 {};
2405 template <class T> struct A1 : A0<T> {};
2406 template <class T> struct A2 : A1<T>, A0<T> {};
2407 template <class T> struct A3 : A2<T>, A1<T> {};
2408 template <class T> struct A4 : A3<T>, A2<T> {};
2409 template <class T> struct A5 : A4<T>, A3<T> {};
2410 template <class T> struct A6 : A5<T>, A4<T> {};
2411 template <class T> struct A7 : A6<T>, A5<T> {};
2412 template <class T> struct A8 : A7<T>, A6<T> {};
2413 template <class T> struct A9 : A8<T>, A7<T> {};
2414 template <class T> struct A10 : A9<T>, A8<T> {};
2415 template <class T> struct A11 : A10<T>, A9<T> {};
2416 template <class T> struct A12 : A11<T>, A10<T> {};
2417 template <class T> struct A13 : A12<T>, A11<T> {};
2418 template <class T> struct A14 : A13<T>, A12<T> {};
2419 template <class T> struct A15 : A14<T>, A13<T> {};
2420 template <class T> struct A16 : A15<T>, A14<T> {};
2421 template <class T> struct A17 : A16<T>, A15<T> {};
2422 template <class T> struct A18 : A17<T>, A16<T> {};
2423 template <class T> struct A19 : A18<T>, A17<T> {};
2424 template <class T> struct A20 : A19<T>, A18<T> {};
2425 template <class T> struct A21 : A20<T>, A19<T> {};
2426 template <class T> struct A22 : A21<T>, A20<T> {};
2427 template <class T> struct A23 : A22<T>, A21<T> {};
2428 template <class T> struct A24 : A23<T>, A22<T> {};
2429 template <class T> struct A25 : A24<T>, A23<T> {};
2430 template <class T> struct A26 : A25<T>, A24<T> {};
2431 template <class T> struct A27 : A26<T>, A25<T> {};
2432 template <class T> struct A28 : A27<T>, A26<T> {};
2433 template <class T> struct A29 : A28<T>, A27<T> {};
2434 template <class T> struct A30 : A29<T>, A28<T> {};
2435 template <class T> struct A31 : A30<T>, A29<T> {};
2436 template <class T> struct A32 : A31<T>, A30<T> {};
2437 template <class T> struct A33 : A32<T>, A31<T> {};
2438 template <class T> struct A34 : A33<T>, A32<T> {};
2439 template <class T> struct A35 : A34<T>, A33<T> {};
2440 template <class T> struct A36 : A35<T>, A34<T> {};
2441 template <class T> struct A37 : A36<T>, A35<T> {};
2442 template <class T> struct A38 : A37<T>, A36<T> {};
2443 template <class T> struct A39 : A38<T>, A37<T> {};
2444 template <class T> struct A40 : A39<T>, A38<T> {};
2445 )cpp",
2446 matcher));
2449 TEST(ASTMatchersTestObjC, ObjCMessageCalees) {
2450 StatementMatcher MessagingFoo =
2451 objcMessageExpr(callee(objcMethodDecl(hasName("foo"))));
2453 EXPECT_TRUE(matchesObjC("@interface I"
2454 "+ (void)foo;"
2455 "@end\n"
2456 "int main() {"
2457 " [I foo];"
2458 "}",
2459 MessagingFoo));
2460 EXPECT_TRUE(notMatchesObjC("@interface I"
2461 "+ (void)foo;"
2462 "+ (void)bar;"
2463 "@end\n"
2464 "int main() {"
2465 " [I bar];"
2466 "}",
2467 MessagingFoo));
2468 EXPECT_TRUE(matchesObjC("@interface I"
2469 "- (void)foo;"
2470 "- (void)bar;"
2471 "@end\n"
2472 "int main() {"
2473 " I *i;"
2474 " [i foo];"
2475 "}",
2476 MessagingFoo));
2477 EXPECT_TRUE(notMatchesObjC("@interface I"
2478 "- (void)foo;"
2479 "- (void)bar;"
2480 "@end\n"
2481 "int main() {"
2482 " I *i;"
2483 " [i bar];"
2484 "}",
2485 MessagingFoo));
2488 TEST(ASTMatchersTestObjC, ObjCMessageExpr) {
2489 // Don't find ObjCMessageExpr where none are present.
2490 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
2492 StringRef Objc1String = "@interface Str "
2493 " - (Str *)uppercaseString;"
2494 "@end "
2495 "@interface foo "
2496 "- (void)contents;"
2497 "- (void)meth:(Str *)text;"
2498 "@end "
2500 "@implementation foo "
2501 "- (void) meth:(Str *)text { "
2502 " [self contents];"
2503 " Str *up = [text uppercaseString];"
2504 "} "
2505 "@end ";
2506 EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(anything())));
2507 EXPECT_TRUE(matchesObjC(Objc1String,
2508 objcMessageExpr(hasAnySelector({"contents", "meth:"}))
2511 EXPECT_TRUE(
2512 matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"))));
2513 EXPECT_TRUE(matchesObjC(
2514 Objc1String, objcMessageExpr(hasAnySelector("contents", "contentsA"))));
2515 EXPECT_FALSE(matchesObjC(
2516 Objc1String, objcMessageExpr(hasAnySelector("contentsB", "contentsC"))));
2517 EXPECT_TRUE(
2518 matchesObjC(Objc1String, objcMessageExpr(matchesSelector("cont*"))));
2519 EXPECT_FALSE(
2520 matchesObjC(Objc1String, objcMessageExpr(matchesSelector("?cont*"))));
2521 EXPECT_TRUE(
2522 notMatchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2523 hasNullSelector())));
2524 EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2525 hasUnarySelector())));
2526 EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2527 numSelectorArgs(0))));
2528 EXPECT_TRUE(
2529 matchesObjC(Objc1String, objcMessageExpr(matchesSelector("uppercase*"),
2530 argumentCountIs(0))));
2533 TEST(ASTMatchersTestObjC, ObjCStringLiteral) {
2535 StringRef Objc1String = "@interface NSObject "
2536 "@end "
2537 "@interface NSString "
2538 "@end "
2539 "@interface Test : NSObject "
2540 "+ (void)someFunction:(NSString *)Desc; "
2541 "@end "
2542 "@implementation Test "
2543 "+ (void)someFunction:(NSString *)Desc { "
2544 " return; "
2545 "} "
2546 "- (void) foo { "
2547 " [Test someFunction:@\"Ola!\"]; "
2548 "}\n"
2549 "@end ";
2550 EXPECT_TRUE(matchesObjC(Objc1String, objcStringLiteral()));
2553 TEST(ASTMatchersTestObjC, ObjCDecls) {
2554 StringRef ObjCString = "@protocol Proto "
2555 "- (void)protoDidThing; "
2556 "@end "
2557 "@interface Thing "
2558 "@property int enabled; "
2559 "@end "
2560 "@interface Thing (ABC) "
2561 "- (void)abc_doThing; "
2562 "@end "
2563 "@implementation Thing "
2564 "{ id _ivar; } "
2565 "- (void)anything {} "
2566 "@end "
2567 "@implementation Thing (ABC) "
2568 "- (void)abc_doThing {} "
2569 "@end ";
2571 EXPECT_TRUE(matchesObjC(ObjCString, objcProtocolDecl(hasName("Proto"))));
2572 EXPECT_TRUE(
2573 matchesObjC(ObjCString, objcImplementationDecl(hasName("Thing"))));
2574 EXPECT_TRUE(matchesObjC(ObjCString, objcCategoryDecl(hasName("ABC"))));
2575 EXPECT_TRUE(matchesObjC(ObjCString, objcCategoryImplDecl(hasName("ABC"))));
2576 EXPECT_TRUE(
2577 matchesObjC(ObjCString, objcMethodDecl(hasName("protoDidThing"))));
2578 EXPECT_TRUE(matchesObjC(ObjCString, objcMethodDecl(hasName("abc_doThing"))));
2579 EXPECT_TRUE(matchesObjC(ObjCString, objcMethodDecl(hasName("anything"))));
2580 EXPECT_TRUE(matchesObjC(ObjCString, objcIvarDecl(hasName("_ivar"))));
2581 EXPECT_TRUE(matchesObjC(ObjCString, objcPropertyDecl(hasName("enabled"))));
2584 TEST(ASTMatchersTestObjC, ObjCExceptionStmts) {
2585 StringRef ObjCString = "void f(id obj) {"
2586 " @try {"
2587 " @throw obj;"
2588 " } @catch (...) {"
2589 " } @finally {}"
2590 "}";
2592 EXPECT_TRUE(matchesObjC(ObjCString, objcTryStmt()));
2593 EXPECT_TRUE(matchesObjC(ObjCString, objcThrowStmt()));
2594 EXPECT_TRUE(matchesObjC(ObjCString, objcCatchStmt()));
2595 EXPECT_TRUE(matchesObjC(ObjCString, objcFinallyStmt()));
2598 TEST(ASTMatchersTest, DecompositionDecl) {
2599 StringRef Code = R"cpp(
2600 void foo()
2602 int arr[3];
2603 auto &[f, s, t] = arr;
2605 f = 42;
2607 )cpp";
2608 EXPECT_TRUE(matchesConditionally(
2609 Code, decompositionDecl(hasBinding(0, bindingDecl(hasName("f")))), true,
2610 {"-std=c++17"}));
2611 EXPECT_FALSE(matchesConditionally(
2612 Code, decompositionDecl(hasBinding(42, bindingDecl(hasName("f")))), true,
2613 {"-std=c++17"}));
2614 EXPECT_FALSE(matchesConditionally(
2615 Code, decompositionDecl(hasBinding(0, bindingDecl(hasName("s")))), true,
2616 {"-std=c++17"}));
2617 EXPECT_TRUE(matchesConditionally(
2618 Code, decompositionDecl(hasBinding(1, bindingDecl(hasName("s")))), true,
2619 {"-std=c++17"}));
2621 EXPECT_TRUE(matchesConditionally(
2622 Code,
2623 bindingDecl(decl().bind("self"), hasName("f"),
2624 forDecomposition(decompositionDecl(
2625 hasAnyBinding(bindingDecl(equalsBoundNode("self")))))),
2626 true, {"-std=c++17"}));
2629 TEST(ASTMatchersTestObjC, ObjCAutoreleasePoolStmt) {
2630 StringRef ObjCString = "void f() {"
2631 "@autoreleasepool {"
2632 " int x = 1;"
2634 "}";
2635 EXPECT_TRUE(matchesObjC(ObjCString, autoreleasePoolStmt()));
2636 StringRef ObjCStringNoPool = "void f() { int x = 1; }";
2637 EXPECT_FALSE(matchesObjC(ObjCStringNoPool, autoreleasePoolStmt()));
2640 TEST(ASTMatchersTestOpenMP, OMPExecutableDirective) {
2641 auto Matcher = stmt(ompExecutableDirective());
2643 StringRef Source0 = R"(
2644 void x() {
2645 #pragma omp parallel
2647 })";
2648 EXPECT_TRUE(matchesWithOpenMP(Source0, Matcher));
2650 StringRef Source1 = R"(
2651 void x() {
2652 #pragma omp taskyield
2654 })";
2655 EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
2657 StringRef Source2 = R"(
2658 void x() {
2660 })";
2661 EXPECT_TRUE(notMatchesWithOpenMP(Source2, Matcher));
2664 TEST(ASTMatchersTestOpenMP, OMPDefaultClause) {
2665 auto Matcher = ompExecutableDirective(hasAnyClause(ompDefaultClause()));
2667 StringRef Source0 = R"(
2668 void x() {
2670 })";
2671 EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
2673 StringRef Source1 = R"(
2674 void x() {
2675 #pragma omp parallel
2677 })";
2678 EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
2680 StringRef Source2 = R"(
2681 void x() {
2682 #pragma omp parallel default(none)
2684 })";
2685 EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
2687 StringRef Source3 = R"(
2688 void x() {
2689 #pragma omp parallel default(shared)
2691 })";
2692 EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
2694 StringRef Source4 = R"(
2695 void x() {
2696 #pragma omp parallel default(firstprivate)
2698 })";
2699 EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
2701 StringRef Source5 = R"(
2702 void x(int x) {
2703 #pragma omp parallel num_threads(x)
2705 })";
2706 EXPECT_TRUE(notMatchesWithOpenMP(Source5, Matcher));
2709 TEST(ASTMatchersTest, Finder_DynamicOnlyAcceptsSomeMatchers) {
2710 MatchFinder Finder;
2711 EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
2712 EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
2713 EXPECT_TRUE(
2714 Finder.addDynamicMatcher(constantArrayType(hasSize(42)), nullptr));
2716 // Do not accept non-toplevel matchers.
2717 EXPECT_FALSE(Finder.addDynamicMatcher(isMain(), nullptr));
2718 EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
2721 TEST(MatchFinderAPI, MatchesDynamic) {
2722 StringRef SourceCode = "struct A { void f() {} };";
2723 auto Matcher = functionDecl(isDefinition()).bind("method");
2725 auto astUnit = tooling::buildASTFromCode(SourceCode);
2727 auto GlobalBoundNodes = matchDynamic(Matcher, astUnit->getASTContext());
2729 EXPECT_EQ(GlobalBoundNodes.size(), 1u);
2730 EXPECT_EQ(GlobalBoundNodes[0].getMap().size(), 1u);
2732 auto GlobalMethodNode = GlobalBoundNodes[0].getNodeAs<FunctionDecl>("method");
2733 EXPECT_TRUE(GlobalMethodNode != nullptr);
2735 auto MethodBoundNodes =
2736 matchDynamic(Matcher, *GlobalMethodNode, astUnit->getASTContext());
2737 EXPECT_EQ(MethodBoundNodes.size(), 1u);
2738 EXPECT_EQ(MethodBoundNodes[0].getMap().size(), 1u);
2740 auto MethodNode = MethodBoundNodes[0].getNodeAs<FunctionDecl>("method");
2741 EXPECT_EQ(MethodNode, GlobalMethodNode);
2744 static std::vector<TestClangConfig> allTestClangConfigs() {
2745 std::vector<TestClangConfig> all_configs;
2746 for (TestLanguage lang : {
2747 #define TESTLANGUAGE(lang, version, std_flag, version_index) \
2748 Lang_##lang##version,
2749 #include "clang/Testing/TestLanguage.def"
2750 }) {
2751 TestClangConfig config;
2752 config.Language = lang;
2754 // Use an unknown-unknown triple so we don't instantiate the full system
2755 // toolchain. On Linux, instantiating the toolchain involves stat'ing
2756 // large portions of /usr/lib, and this slows down not only this test, but
2757 // all other tests, via contention in the kernel.
2759 // FIXME: This is a hack to work around the fact that there's no way to do
2760 // the equivalent of runToolOnCodeWithArgs without instantiating a full
2761 // Driver. We should consider having a function, at least for tests, that
2762 // invokes cc1.
2763 config.Target = "i386-unknown-unknown";
2764 all_configs.push_back(config);
2766 // Windows target is interesting to test because it enables
2767 // `-fdelayed-template-parsing`.
2768 config.Target = "x86_64-pc-win32-msvc";
2769 all_configs.push_back(config);
2771 return all_configs;
2774 INSTANTIATE_TEST_SUITE_P(
2775 ASTMatchersTests, ASTMatchersTest, testing::ValuesIn(allTestClangConfigs()),
2776 [](const testing::TestParamInfo<TestClangConfig> &Info) {
2777 return Info.param.toShortString();
2780 } // namespace ast_matchers
2781 } // namespace clang