1 //== unittests/ASTMatchers/ASTMatchersNodeTest.cpp - AST matcher unit tests ==//
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
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"
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++.
26 EXPECT_TRUE(notMatches("", decl(usingDecl())));
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()) {
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()) {
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()) {
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
116 StringRef Code
= "int MyVar1;\n"
117 "namespace NameSpace {\n"
119 "} // namespace NameSpace\n";
121 Code
, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
122 EXPECT_FALSE(matches(
123 Code
, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
126 varDecl(hasName("MyVar2"),
127 hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
130 TEST_P(ASTMatchersTest
, LinkageSpecDecl
) {
131 if (!GetParam().isCXX()) {
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()) {
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()) {
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()) {
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()) {
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.
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()) {
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()) {
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.
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.
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.
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()) {
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.
265 EXPECT_TRUE(matches("template<typename T>"
266 "T foo() { T a; return a; }"
267 "template<typename T>"
271 unresolvedLookupExpr()));
274 TEST_P(ASTMatchersTest
, UsesADL
) {
275 if (!GetParam().isCXX()) {
279 StatementMatcher ADLMatch
= callExpr(usesADL());
280 StatementMatcher ADLMatchOper
= cxxOperatorCallExpr(usesADL());
281 StringRef NS_Str
= R
"cpp(
285 void operator+(X, X);
289 void operator+(MyX, MyX);
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++.
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(); }",
328 EXPECT_TRUE(matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
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"))))));
341 matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
344 matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
347 matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
350 notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
353 notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
357 TEST_P(ASTMatchersTest
, LambdaExpr
) {
358 if (!GetParam().isCXX11OrLater()) {
361 EXPECT_TRUE(matches("auto f = [] (int i) { return i; };", lambdaExpr()));
364 TEST_P(ASTMatchersTest
, CXXForRangeStmt
) {
366 notMatches("void f() { for (int i; i<5; ++i); }", cxxForRangeStmt()));
369 TEST_P(ASTMatchersTest
, CXXForRangeStmt_CXX11
) {
370 if (!GetParam().isCXX11OrLater()) {
373 EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
374 "void f() { for (auto &a : as); }",
378 TEST_P(ASTMatchersTest
, SubstNonTypeTemplateParmExpr
) {
379 if (!GetParam().isCXX()) {
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()) {
396 EXPECT_TRUE(matches("template <int N> void f();",
397 nonTypeTemplateParmDecl(hasName("N"))));
399 notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
402 TEST_P(ASTMatchersTest
, TemplateTypeParmDecl
) {
403 if (!GetParam().isCXX()) {
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())
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()) {
424 EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
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; }",
439 EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
442 TEST_P(ASTMatchersTest
, CXXOperatorCallExpr
) {
443 if (!GetParam().isCXX()) {
447 StatementMatcher OpCall
= cxxOperatorCallExpr();
449 EXPECT_TRUE(matches("class Y { }; "
450 "bool operator!(Y x) { return false; }; "
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"
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;}",
465 EXPECT_TRUE(matches("class Y { }; "
466 "bool operator&&(Y x, Y y) { return true; }; "
467 "Y a; Y b; bool c = a && b;",
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
, ThisPointerType
) {
475 if (!GetParam().isCXX()) {
479 StatementMatcher MethodOnY
= traverse(
480 TK_AsIs
, cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y")))));
482 EXPECT_TRUE(matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
484 EXPECT_TRUE(matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
487 "class Y { public: void x(); }; void z(Y *&y) { y->x(); }", MethodOnY
));
489 "class Y { public: void x(); }; void z(Y y[]) { y->x(); }", MethodOnY
));
491 "class Y { public: void x(); }; void z() { Y *y; y->x(); }", MethodOnY
));
493 EXPECT_TRUE(matches("class Y {"
494 " public: virtual void x();"
496 "class X : public Y {"
497 " public: virtual void x();"
499 "void z() { X *x; x->Y::x(); }",
503 TEST_P(ASTMatchersTest
, DeclRefExpr
) {
504 if (!GetParam().isCXX()) {
505 // FIXME: Add a test for `declRefExpr()` that does not depend on C++.
508 StatementMatcher Reference
= declRefExpr(to(varDecl(hasInitializer(
509 cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
511 EXPECT_TRUE(matches("class Y {"
515 "void z(const Y &y) {"
521 EXPECT_TRUE(notMatches("class Y {"
525 "void z(const Y &y) {"
531 TEST_P(ASTMatchersTest
, CXXMemberCallExpr
) {
532 if (!GetParam().isCXX()) {
535 StatementMatcher CallOnVariableY
=
536 cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
538 EXPECT_TRUE(matches("class Y { public: void x() { Y y; y.x(); } };",
540 EXPECT_TRUE(matches("class Y { public: void x() const { Y y; y.x(); } };",
542 EXPECT_TRUE(matches("class Y { public: void x(); };"
543 "class X : public Y { void z() { X y; y.x(); } };",
545 EXPECT_TRUE(matches("class Y { public: void x(); };"
546 "class X : public Y { void z() { X *y; y->x(); } };",
548 EXPECT_TRUE(notMatches(
549 "class Y { public: void x(); };"
550 "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
554 TEST_P(ASTMatchersTest
, UnaryExprOrTypeTraitExpr
) {
556 matches("void x() { int a = sizeof(a); }", unaryExprOrTypeTraitExpr()));
559 TEST_P(ASTMatchersTest
, AlignOfExpr
) {
561 notMatches("void x() { int a = sizeof(a); }", alignOfExpr(anything())));
562 // FIXME: Uncomment once alignof is enabled.
563 // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
564 // unaryExprOrTypeTraitExpr()));
565 // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
569 TEST_P(ASTMatchersTest
, MemberExpr_DoesNotMatchClasses
) {
570 if (!GetParam().isCXX()) {
573 EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
574 EXPECT_TRUE(notMatches("class Y { void x() {} };", unresolvedMemberExpr()));
576 notMatches("class Y { void x() {} };", cxxDependentScopeMemberExpr()));
579 TEST_P(ASTMatchersTest
, MemberExpr_MatchesMemberFunctionCall
) {
580 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
581 // FIXME: Fix this test to work with delayed template parsing.
584 EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
585 EXPECT_TRUE(matches("class Y { template <class T> void x() { x<T>(); } };",
586 unresolvedMemberExpr()));
587 EXPECT_TRUE(matches("template <class T> void x() { T t; t.f(); }",
588 cxxDependentScopeMemberExpr()));
591 TEST_P(ASTMatchersTest
, MemberExpr_MatchesVariable
) {
592 if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
593 // FIXME: Fix this test to work with delayed template parsing.
597 matches("class Y { void x() { this->y; } int y; };", memberExpr()));
598 EXPECT_TRUE(matches("class Y { void x() { y; } int y; };", memberExpr()));
600 matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
601 EXPECT_TRUE(matches("template <class T>"
602 "class X : T { void f() { this->T::v; } };",
603 cxxDependentScopeMemberExpr()));
604 EXPECT_TRUE(matches("template <class T> class X : T { void f() { T::v; } };",
605 cxxDependentScopeMemberExpr()));
606 EXPECT_TRUE(matches("template <class T> void x() { T t; t.v; }",
607 cxxDependentScopeMemberExpr()));
610 TEST_P(ASTMatchersTest
, MemberExpr_MatchesStaticVariable
) {
611 if (!GetParam().isCXX()) {
614 EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
617 notMatches("class Y { void x() { y; } static int y; };", memberExpr()));
618 EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
622 TEST_P(ASTMatchersTest
, FunctionDecl
) {
623 StatementMatcher CallFunctionF
= callExpr(callee(functionDecl(hasName("f"))));
625 EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF
));
626 EXPECT_TRUE(notMatches("void f() { }", CallFunctionF
));
628 EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
629 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
630 EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
633 TEST_P(ASTMatchersTest
, FunctionDecl_C
) {
634 if (!GetParam().isC()) {
637 EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
638 EXPECT_TRUE(matches("void f();", functionDecl(parameterCountIs(0))));
641 TEST_P(ASTMatchersTest
, FunctionDecl_CXX
) {
642 if (!GetParam().isCXX()) {
646 StatementMatcher CallFunctionF
= callExpr(callee(functionDecl(hasName("f"))));
648 if (!GetParam().hasDelayedTemplateParsing()) {
649 // FIXME: Fix this test to work with delayed template parsing.
650 // Dependent contexts, but a non-dependent call.
652 matches("void f(); template <int N> void g() { f(); }", CallFunctionF
));
654 matches("void f(); template <int N> struct S { void g() { f(); } };",
658 // Dependent calls don't match.
660 notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
663 notMatches("void f(int);"
664 "template <typename T> struct S { void g(T t) { f(t); } };",
667 EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
668 EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
671 TEST_P(ASTMatchersTest
, FunctionDecl_CXX11
) {
672 if (!GetParam().isCXX11OrLater()) {
676 EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
677 functionDecl(isVariadic())));
680 TEST_P(ASTMatchersTest
,
681 FunctionTemplateDecl_MatchesFunctionTemplateDeclarations
) {
682 if (!GetParam().isCXX()) {
685 EXPECT_TRUE(matches("template <typename T> void f(T t) {}",
686 functionTemplateDecl(hasName("f"))));
689 TEST_P(ASTMatchersTest
, FunctionTemplate_DoesNotMatchFunctionDeclarations
) {
691 notMatches("void f(double d);", functionTemplateDecl(hasName("f"))));
693 notMatches("void f(int t) {}", functionTemplateDecl(hasName("f"))));
696 TEST_P(ASTMatchersTest
,
697 FunctionTemplateDecl_DoesNotMatchFunctionTemplateSpecializations
) {
698 if (!GetParam().isCXX()) {
701 EXPECT_TRUE(notMatches(
702 "void g(); template <typename T> void f(T t) {}"
703 "template <> void f(int t) { g(); }",
704 functionTemplateDecl(hasName("f"), hasDescendant(declRefExpr(to(
705 functionDecl(hasName("g"))))))));
708 TEST_P(ASTMatchersTest
, ClassTemplateSpecializationDecl
) {
709 if (!GetParam().isCXX()) {
712 EXPECT_TRUE(matches("template<typename T> struct A {};"
713 "template<> struct A<int> {};",
714 classTemplateSpecializationDecl()));
715 EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
716 classTemplateSpecializationDecl()));
717 EXPECT_TRUE(notMatches("template<typename T> struct A {};",
718 classTemplateSpecializationDecl()));
721 TEST_P(ASTMatchersTest
, DeclaratorDecl
) {
722 EXPECT_TRUE(matches("int x;", declaratorDecl()));
723 EXPECT_TRUE(notMatches("struct A {};", declaratorDecl()));
726 TEST_P(ASTMatchersTest
, DeclaratorDecl_CXX
) {
727 if (!GetParam().isCXX()) {
730 EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
733 TEST_P(ASTMatchersTest
, ParmVarDecl
) {
734 EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
735 EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
738 TEST_P(ASTMatchersTest
, StaticAssertDecl
) {
739 if (!GetParam().isCXX11OrLater())
742 EXPECT_TRUE(matches("static_assert(true, \"\");", staticAssertDecl()));
744 notMatches("constexpr bool staticassert(bool B, const char *M) "
745 "{ return true; };\n void f() { staticassert(true, \"\"); }",
746 staticAssertDecl()));
749 TEST_P(ASTMatchersTest
, Matcher_ConstructorCall
) {
750 if (!GetParam().isCXX()) {
754 StatementMatcher Constructor
= traverse(TK_AsIs
, cxxConstructExpr());
757 matches("class X { public: X(); }; void x() { X x; }", Constructor
));
758 EXPECT_TRUE(matches("class X { public: X(); }; void x() { X x = X(); }",
760 EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x = 0; }",
762 EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor
));
765 TEST_P(ASTMatchersTest
, Match_ConstructorInitializers
) {
766 if (!GetParam().isCXX()) {
769 EXPECT_TRUE(matches("class C { int i; public: C(int ii) : i(ii) {} };",
770 cxxCtorInitializer(forField(hasName("i")))));
773 TEST_P(ASTMatchersTest
, Matcher_ThisExpr
) {
774 if (!GetParam().isCXX()) {
778 matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
780 notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
783 TEST_P(ASTMatchersTest
, Matcher_BindTemporaryExpression
) {
784 if (!GetParam().isCXX()) {
788 StatementMatcher TempExpression
= traverse(TK_AsIs
, cxxBindTemporaryExpr());
790 StringRef ClassString
= "class string { public: string(); ~string(); }; ";
793 ClassString
+ "string GetStringByValue();"
794 "void FunctionTakesString(string s);"
795 "void run() { FunctionTakesString(GetStringByValue()); }",
798 EXPECT_TRUE(notMatches(ClassString
+
799 "string* GetStringPointer(); "
800 "void FunctionTakesStringPtr(string* s);"
802 " string* s = GetStringPointer();"
803 " FunctionTakesStringPtr(GetStringPointer());"
804 " FunctionTakesStringPtr(s);"
808 EXPECT_TRUE(notMatches("class no_dtor {};"
809 "no_dtor GetObjByValue();"
810 "void ConsumeObj(no_dtor param);"
811 "void run() { ConsumeObj(GetObjByValue()); }",
815 TEST_P(ASTMatchersTest
, MaterializeTemporaryExpr_MatchesTemporaryCXX11CXX14
) {
816 if (GetParam().Language
!= Lang_CXX11
&& GetParam().Language
!= Lang_CXX14
) {
820 StatementMatcher TempExpression
=
821 traverse(TK_AsIs
, materializeTemporaryExpr());
823 EXPECT_TRUE(matches("class string { public: string(); }; "
824 "string GetStringByValue();"
825 "void FunctionTakesString(string s);"
826 "void run() { FunctionTakesString(GetStringByValue()); }",
830 TEST_P(ASTMatchersTest
, MaterializeTemporaryExpr_MatchesTemporary
) {
831 if (!GetParam().isCXX()) {
835 StringRef ClassString
= "class string { public: string(); int length(); }; ";
836 StatementMatcher TempExpression
=
837 traverse(TK_AsIs
, materializeTemporaryExpr());
839 EXPECT_TRUE(notMatches(ClassString
+
840 "string* GetStringPointer(); "
841 "void FunctionTakesStringPtr(string* s);"
843 " string* s = GetStringPointer();"
844 " FunctionTakesStringPtr(GetStringPointer());"
845 " FunctionTakesStringPtr(s);"
849 EXPECT_TRUE(matches(ClassString
+
850 "string GetStringByValue();"
851 "void run() { int k = GetStringByValue().length(); }",
854 EXPECT_TRUE(notMatches(ClassString
+ "string GetStringByValue();"
855 "void run() { GetStringByValue(); }",
859 TEST_P(ASTMatchersTest
, Matcher_NewExpression
) {
860 if (!GetParam().isCXX()) {
864 StatementMatcher New
= cxxNewExpr();
866 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New
));
867 EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X(); }", New
));
869 matches("class X { public: X(int); }; void x() { new X(0); }", New
));
870 EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New
));
873 TEST_P(ASTMatchersTest
, Matcher_DeleteExpression
) {
874 if (!GetParam().isCXX()) {
878 matches("struct A {}; void f(A* a) { delete a; }", cxxDeleteExpr()));
881 TEST_P(ASTMatchersTest
, Matcher_NoexceptExpression
) {
882 if (!GetParam().isCXX11OrLater()) {
885 StatementMatcher NoExcept
= cxxNoexceptExpr();
886 EXPECT_TRUE(matches("void foo(); bool bar = noexcept(foo());", NoExcept
));
888 matches("void foo() noexcept; bool bar = noexcept(foo());", NoExcept
));
889 EXPECT_TRUE(notMatches("void foo() noexcept;", NoExcept
));
890 EXPECT_TRUE(notMatches("void foo() noexcept(0+1);", NoExcept
));
891 EXPECT_TRUE(matches("void foo() noexcept(noexcept(1+1));", NoExcept
));
894 TEST_P(ASTMatchersTest
, Matcher_DefaultArgument
) {
895 if (!GetParam().isCXX()) {
898 StatementMatcher Arg
= cxxDefaultArgExpr();
899 EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg
));
901 matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg
));
902 EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg
));
905 TEST_P(ASTMatchersTest
, StringLiteral
) {
906 StatementMatcher Literal
= stringLiteral();
907 EXPECT_TRUE(matches("const char *s = \"string\";", Literal
));
908 // with escaped characters
909 EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal
));
910 // no matching -- though the data type is the same, there is no string literal
911 EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal
));
914 TEST_P(ASTMatchersTest
, StringLiteral_CXX
) {
915 if (!GetParam().isCXX()) {
918 EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", stringLiteral()));
921 TEST_P(ASTMatchersTest
, CharacterLiteral
) {
922 EXPECT_TRUE(matches("const char c = 'c';", characterLiteral()));
923 EXPECT_TRUE(notMatches("const char c = 0x1;", characterLiteral()));
926 TEST_P(ASTMatchersTest
, CharacterLiteral_CXX
) {
927 if (!GetParam().isCXX()) {
931 EXPECT_TRUE(matches("const char c = L'c';", characterLiteral()));
932 // wide character, Hex encoded, NOT MATCHED!
933 EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", characterLiteral()));
936 TEST_P(ASTMatchersTest
, IntegerLiteral
) {
937 StatementMatcher HasIntLiteral
= integerLiteral();
938 EXPECT_TRUE(matches("int i = 10;", HasIntLiteral
));
939 EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral
));
940 EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral
));
941 EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral
));
943 // Non-matching cases (character literals, float and double)
944 EXPECT_TRUE(notMatches("int i = L'a';",
945 HasIntLiteral
)); // this is actually a character
946 // literal cast to int
947 EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral
));
948 EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral
));
949 EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral
));
951 // Negative integers.
953 matches("int i = -10;",
954 unaryOperator(hasOperatorName("-"),
955 hasUnaryOperand(integerLiteral(equals(10))))));
958 TEST_P(ASTMatchersTest
, FloatLiteral
) {
959 StatementMatcher HasFloatLiteral
= floatLiteral();
960 EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral
));
961 EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral
));
962 EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral
));
963 EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral
));
964 EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral
));
965 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
966 EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f
))));
968 matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
970 EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral
));
971 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
972 EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f
))));
974 notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
977 TEST_P(ASTMatchersTest
, CXXNullPtrLiteralExpr
) {
978 if (!GetParam().isCXX11OrLater()) {
981 EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
984 TEST_P(ASTMatchersTest
, ChooseExpr
) {
985 EXPECT_TRUE(matches("void f() { (void)__builtin_choose_expr(1, 2, 3); }",
989 TEST_P(ASTMatchersTest
, ConvertVectorExpr
) {
991 "typedef double vector4double __attribute__((__vector_size__(32)));"
992 "typedef float vector4float __attribute__((__vector_size__(16)));"
994 "void f() { (void)__builtin_convertvector(vf, vector4double); }",
995 convertVectorExpr()));
996 EXPECT_TRUE(notMatches("void f() { (void)__builtin_choose_expr(1, 2, 3); }",
997 convertVectorExpr()));
1000 TEST_P(ASTMatchersTest
, GNUNullExpr
) {
1001 if (!GetParam().isCXX()) {
1004 EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
1007 TEST_P(ASTMatchersTest
, GenericSelectionExpr
) {
1008 EXPECT_TRUE(matches("void f() { (void)_Generic(1, int: 1, float: 2.0); }",
1009 genericSelectionExpr()));
1012 TEST_P(ASTMatchersTest
, AtomicExpr
) {
1013 EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }",
1017 TEST_P(ASTMatchersTest
, Initializers_C99
) {
1018 if (!GetParam().isC99OrLater()) {
1021 EXPECT_TRUE(matches(
1022 "void foo() { struct point { double x; double y; };"
1023 " struct point ptarray[10] = "
1024 " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1025 initListExpr(hasSyntacticForm(initListExpr(
1026 has(designatedInitExpr(designatorCountIs(2),
1027 hasDescendant(floatLiteral(equals(1.0))),
1028 hasDescendant(integerLiteral(equals(2))))),
1029 has(designatedInitExpr(designatorCountIs(2),
1030 hasDescendant(floatLiteral(equals(2.0))),
1031 hasDescendant(integerLiteral(equals(2))))),
1032 has(designatedInitExpr(
1033 designatorCountIs(2), hasDescendant(floatLiteral(equals(1.0))),
1034 hasDescendant(integerLiteral(equals(0))))))))));
1037 TEST_P(ASTMatchersTest
, Initializers_CXX
) {
1038 if (GetParam().Language
!= Lang_CXX03
) {
1039 // FIXME: Make this test pass with other C++ standard versions.
1042 EXPECT_TRUE(matches(
1043 "void foo() { struct point { double x; double y; };"
1044 " struct point ptarray[10] = "
1045 " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1047 has(cxxConstructExpr(requiresZeroInitialization())),
1049 hasType(asString("struct point")), has(floatLiteral(equals(1.0))),
1050 has(implicitValueInitExpr(hasType(asString("double")))))),
1051 has(initListExpr(hasType(asString("struct point")),
1052 has(floatLiteral(equals(2.0))),
1053 has(floatLiteral(equals(1.0))))))));
1056 TEST_P(ASTMatchersTest
, ParenListExpr
) {
1057 if (!GetParam().isCXX()) {
1061 matches("template<typename T> class foo { void bar() { foo X(*this); } };"
1062 "template class foo<int>;",
1063 varDecl(hasInitializer(parenListExpr(has(unaryOperator()))))));
1066 TEST_P(ASTMatchersTest
, StmtExpr
) {
1067 EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }",
1068 varDecl(hasInitializer(stmtExpr()))));
1071 TEST_P(ASTMatchersTest
, PredefinedExpr
) {
1072 // __func__ expands as StringLiteral("foo")
1073 EXPECT_TRUE(matches("void foo() { __func__; }",
1074 predefinedExpr(hasType(asString("const char[4]")),
1075 has(stringLiteral()))));
1078 TEST_P(ASTMatchersTest
, AsmStatement
) {
1079 EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
1082 TEST_P(ASTMatchersTest
, HasCondition
) {
1083 if (!GetParam().isCXX()) {
1084 // FIXME: Add a test for `hasCondition()` that does not depend on C++.
1088 StatementMatcher Condition
=
1089 ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
1091 EXPECT_TRUE(matches("void x() { if (true) {} }", Condition
));
1092 EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition
));
1093 EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition
));
1094 EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition
));
1095 EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition
));
1098 TEST_P(ASTMatchersTest
, ConditionalOperator
) {
1099 if (!GetParam().isCXX()) {
1100 // FIXME: Add a test for `conditionalOperator()` that does not depend on
1105 StatementMatcher Conditional
=
1106 conditionalOperator(hasCondition(cxxBoolLiteral(equals(true))),
1107 hasTrueExpression(cxxBoolLiteral(equals(false))));
1109 EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional
));
1110 EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional
));
1111 EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional
));
1113 StatementMatcher ConditionalFalse
=
1114 conditionalOperator(hasFalseExpression(cxxBoolLiteral(equals(false))));
1116 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse
));
1118 notMatches("void x() { true ? false : true; }", ConditionalFalse
));
1120 EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse
));
1122 notMatches("void x() { true ? false : true; }", ConditionalFalse
));
1125 TEST_P(ASTMatchersTest
, BinaryConditionalOperator
) {
1126 if (!GetParam().isCXX()) {
1127 // FIXME: This test should work in non-C++ language modes.
1131 StatementMatcher AlwaysOne
= traverse(
1132 TK_AsIs
, binaryConditionalOperator(
1133 hasCondition(implicitCastExpr(has(opaqueValueExpr(
1134 hasSourceExpression((integerLiteral(equals(1)))))))),
1135 hasFalseExpression(integerLiteral(equals(0)))));
1137 EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne
));
1139 StatementMatcher FourNotFive
= binaryConditionalOperator(
1141 opaqueValueExpr(hasSourceExpression((integerLiteral(equals(4)))))),
1142 hasFalseExpression(integerLiteral(equals(5))));
1144 EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive
));
1147 TEST_P(ASTMatchersTest
, ArraySubscriptExpr
) {
1149 matches("int i[2]; void f() { i[1] = 1; }", arraySubscriptExpr()));
1150 EXPECT_TRUE(notMatches("int i; void f() { i = 1; }", arraySubscriptExpr()));
1153 TEST_P(ASTMatchersTest
, ForStmt
) {
1154 EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
1155 EXPECT_TRUE(matches("void f() { if(1) for(;;); }", forStmt()));
1158 TEST_P(ASTMatchersTest
, ForStmt_CXX11
) {
1159 if (!GetParam().isCXX11OrLater()) {
1162 EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
1163 "void f() { for (auto &a : as); }",
1167 TEST_P(ASTMatchersTest
, ForStmt_NoFalsePositives
) {
1168 EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
1169 EXPECT_TRUE(notMatches("void f() { if(1); }", forStmt()));
1172 TEST_P(ASTMatchersTest
, CompoundStatement
) {
1173 EXPECT_TRUE(notMatches("void f();", compoundStmt()));
1174 EXPECT_TRUE(matches("void f() {}", compoundStmt()));
1175 EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
1178 TEST_P(ASTMatchersTest
, CompoundStatement_DoesNotMatchEmptyStruct
) {
1179 if (!GetParam().isCXX()) {
1180 // FIXME: Add a similar test that does not depend on C++.
1183 // It's not a compound statement just because there's "{}" in the source
1184 // text. This is an AST search, not grep.
1185 EXPECT_TRUE(notMatches("namespace n { struct S {}; }", compoundStmt()));
1187 matches("namespace n { struct S { void f() {{}} }; }", compoundStmt()));
1190 TEST_P(ASTMatchersTest
, CastExpr_MatchesExplicitCasts
) {
1191 EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
1194 TEST_P(ASTMatchersTest
, CastExpr_MatchesExplicitCasts_CXX
) {
1195 if (!GetParam().isCXX()) {
1198 EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);", castExpr()));
1199 EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
1200 EXPECT_TRUE(matches("char c = char(0);", castExpr()));
1203 TEST_P(ASTMatchersTest
, CastExpression_MatchesImplicitCasts
) {
1204 // This test creates an implicit cast from int to char.
1205 EXPECT_TRUE(matches("char c = 0;", traverse(TK_AsIs
, castExpr())));
1206 // This test creates an implicit cast from lvalue to rvalue.
1207 EXPECT_TRUE(matches("void f() { char c = 0, d = c; }",
1208 traverse(TK_AsIs
, castExpr())));
1211 TEST_P(ASTMatchersTest
, CastExpr_DoesNotMatchNonCasts
) {
1212 if (GetParam().Language
== Lang_C89
|| GetParam().Language
== Lang_C99
) {
1213 // This does have a cast in C
1214 EXPECT_TRUE(matches("char c = '0';", implicitCastExpr()));
1216 EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
1218 EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
1219 EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
1222 TEST_P(ASTMatchersTest
, CastExpr_DoesNotMatchNonCasts_CXX
) {
1223 if (!GetParam().isCXX()) {
1226 EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
1229 TEST_P(ASTMatchersTest
, CXXReinterpretCastExpr
) {
1230 if (!GetParam().isCXX()) {
1233 EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
1234 cxxReinterpretCastExpr()));
1237 TEST_P(ASTMatchersTest
, CXXReinterpretCastExpr_DoesNotMatchOtherCasts
) {
1238 if (!GetParam().isCXX()) {
1241 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
1242 EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
1243 cxxReinterpretCastExpr()));
1244 EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
1245 cxxReinterpretCastExpr()));
1246 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1248 "D* p = dynamic_cast<D*>(&b);",
1249 cxxReinterpretCastExpr()));
1252 TEST_P(ASTMatchersTest
, CXXFunctionalCastExpr_MatchesSimpleCase
) {
1253 if (!GetParam().isCXX()) {
1256 StringRef foo_class
= "class Foo { public: Foo(const char*); };";
1257 EXPECT_TRUE(matches(foo_class
+ "void r() { Foo f = Foo(\"hello world\"); }",
1258 cxxFunctionalCastExpr()));
1261 TEST_P(ASTMatchersTest
, CXXFunctionalCastExpr_DoesNotMatchOtherCasts
) {
1262 if (!GetParam().isCXX()) {
1265 StringRef FooClass
= "class Foo { public: Foo(const char*); };";
1267 notMatches(FooClass
+ "void r() { Foo f = (Foo) \"hello world\"; }",
1268 cxxFunctionalCastExpr()));
1269 EXPECT_TRUE(notMatches(FooClass
+ "void r() { Foo f = \"hello world\"; }",
1270 cxxFunctionalCastExpr()));
1273 TEST_P(ASTMatchersTest
, CXXDynamicCastExpr
) {
1274 if (!GetParam().isCXX()) {
1277 EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
1279 "D* p = dynamic_cast<D*>(&b);",
1280 cxxDynamicCastExpr()));
1283 TEST_P(ASTMatchersTest
, CXXStaticCastExpr_MatchesSimpleCase
) {
1284 if (!GetParam().isCXX()) {
1287 EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));", cxxStaticCastExpr()));
1290 TEST_P(ASTMatchersTest
, CXXStaticCastExpr_DoesNotMatchOtherCasts
) {
1291 if (!GetParam().isCXX()) {
1294 EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
1296 notMatches("char q, *p = const_cast<char*>(&q);", cxxStaticCastExpr()));
1297 EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
1298 cxxStaticCastExpr()));
1299 EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1301 "D* p = dynamic_cast<D*>(&b);",
1302 cxxStaticCastExpr()));
1305 TEST_P(ASTMatchersTest
, CStyleCastExpr_MatchesSimpleCase
) {
1306 EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
1309 TEST_P(ASTMatchersTest
, CStyleCastExpr_DoesNotMatchOtherCasts
) {
1310 if (!GetParam().isCXX()) {
1313 EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
1314 "char q, *r = const_cast<char*>(&q);"
1315 "void* s = reinterpret_cast<char*>(&s);"
1316 "struct B { virtual ~B() {} }; struct D : B {};"
1318 "D* t = dynamic_cast<D*>(&b);",
1322 TEST_P(ASTMatchersTest
, ImplicitCastExpr_MatchesSimpleCase
) {
1323 // This test creates an implicit const cast.
1325 matches("void f() { int x = 0; const int y = x; }",
1326 traverse(TK_AsIs
, varDecl(hasInitializer(implicitCastExpr())))));
1327 // This test creates an implicit cast from int to char.
1329 matches("char c = 0;",
1330 traverse(TK_AsIs
, varDecl(hasInitializer(implicitCastExpr())))));
1331 // This test creates an implicit array-to-pointer cast.
1333 matches("int arr[6]; int *p = arr;",
1334 traverse(TK_AsIs
, varDecl(hasInitializer(implicitCastExpr())))));
1337 TEST_P(ASTMatchersTest
, ImplicitCastExpr_DoesNotMatchIncorrectly
) {
1338 // This test verifies that implicitCastExpr() matches exactly when implicit
1339 // casts are present, and that it ignores explicit and paren casts.
1341 // These two test cases have no casts.
1343 notMatches("int x = 0;", varDecl(hasInitializer(implicitCastExpr()))));
1345 notMatches("int x = (0);", varDecl(hasInitializer(implicitCastExpr()))));
1346 EXPECT_TRUE(notMatches("void f() { int x = 0; double d = (double) x; }",
1347 varDecl(hasInitializer(implicitCastExpr()))));
1350 TEST_P(ASTMatchersTest
, ImplicitCastExpr_DoesNotMatchIncorrectly_CXX
) {
1351 if (!GetParam().isCXX()) {
1354 EXPECT_TRUE(notMatches("int x = 0, &y = x;",
1355 varDecl(hasInitializer(implicitCastExpr()))));
1356 EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
1357 varDecl(hasInitializer(implicitCastExpr()))));
1360 TEST_P(ASTMatchersTest
, Stmt_DoesNotMatchDeclarations
) {
1361 EXPECT_TRUE(notMatches("struct X {};", stmt()));
1364 TEST_P(ASTMatchersTest
, Stmt_MatchesCompoundStatments
) {
1365 EXPECT_TRUE(matches("void x() {}", stmt()));
1368 TEST_P(ASTMatchersTest
, DeclStmt_DoesNotMatchCompoundStatements
) {
1369 EXPECT_TRUE(notMatches("void x() {}", declStmt()));
1372 TEST_P(ASTMatchersTest
, DeclStmt_MatchesVariableDeclarationStatements
) {
1373 EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
1376 TEST_P(ASTMatchersTest
, ExprWithCleanups_MatchesExprWithCleanups
) {
1377 if (!GetParam().isCXX()) {
1381 matches("struct Foo { ~Foo(); };"
1382 "const Foo f = Foo();",
1383 traverse(TK_AsIs
, varDecl(hasInitializer(exprWithCleanups())))));
1385 matches("struct Foo { }; Foo a;"
1387 traverse(TK_AsIs
, varDecl(hasInitializer(exprWithCleanups())))));
1390 TEST_P(ASTMatchersTest
, InitListExpr
) {
1391 EXPECT_TRUE(matches("int a[] = { 1, 2 };",
1392 initListExpr(hasType(asString("int[2]")))));
1393 EXPECT_TRUE(matches("struct B { int x, y; }; struct B b = { 5, 6 };",
1394 initListExpr(hasType(recordDecl(hasName("B"))))));
1396 matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
1399 TEST_P(ASTMatchersTest
, InitListExpr_CXX
) {
1400 if (!GetParam().isCXX()) {
1403 EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
1406 declRefExpr(to(functionDecl(hasName("f"))))));
1409 TEST_P(ASTMatchersTest
,
1410 CXXStdInitializerListExpression_MatchesCXXStdInitializerListExpression
) {
1411 if (!GetParam().isCXX11OrLater()) {
1414 StringRef code
= "namespace std {"
1415 "template <typename> class initializer_list {"
1416 " public: initializer_list() noexcept {}"
1420 " A(std::initializer_list<int>) {}"
1422 EXPECT_TRUE(matches(
1424 traverse(TK_AsIs
, cxxConstructExpr(has(cxxStdInitializerListExpr()),
1425 hasDeclaration(cxxConstructorDecl(
1426 ofClass(hasName("A"))))))));
1427 EXPECT_TRUE(matches(
1428 code
+ "A a = {0};",
1429 traverse(TK_AsIs
, cxxConstructExpr(has(cxxStdInitializerListExpr()),
1430 hasDeclaration(cxxConstructorDecl(
1431 ofClass(hasName("A"))))))));
1433 EXPECT_TRUE(notMatches("int a[] = { 1, 2 };", cxxStdInitializerListExpr()));
1434 EXPECT_TRUE(notMatches("struct B { int x, y; }; B b = { 5, 6 };",
1435 cxxStdInitializerListExpr()));
1438 TEST_P(ASTMatchersTest
, UsingDecl_MatchesUsingDeclarations
) {
1439 if (!GetParam().isCXX()) {
1442 EXPECT_TRUE(matches("namespace X { int x; } using X::x;", usingDecl()));
1445 TEST_P(ASTMatchersTest
, UsingDecl_MatchesShadowUsingDelcarations
) {
1446 if (!GetParam().isCXX()) {
1449 EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
1450 usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
1453 TEST_P(ASTMatchersTest
, UsingEnumDecl_MatchesUsingEnumDeclarations
) {
1454 if (!GetParam().isCXX20OrLater()) {
1458 matches("namespace X { enum x {}; } using enum X::x;", usingEnumDecl()));
1461 TEST_P(ASTMatchersTest
, UsingEnumDecl_MatchesShadowUsingDeclarations
) {
1462 if (!GetParam().isCXX20OrLater()) {
1465 EXPECT_TRUE(matches("namespace f { enum a {b}; } using enum f::a;",
1466 usingEnumDecl(hasAnyUsingShadowDecl(hasName("b")))));
1469 TEST_P(ASTMatchersTest
, UsingDirectiveDecl_MatchesUsingNamespace
) {
1470 if (!GetParam().isCXX()) {
1473 EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
1474 usingDirectiveDecl()));
1476 matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
1479 TEST_P(ASTMatchersTest
, WhileStmt
) {
1480 EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
1481 EXPECT_TRUE(matches("void x() { while(1); }", whileStmt()));
1482 EXPECT_TRUE(notMatches("void x() { do {} while(1); }", whileStmt()));
1485 TEST_P(ASTMatchersTest
, DoStmt_MatchesDoLoops
) {
1486 EXPECT_TRUE(matches("void x() { do {} while(1); }", doStmt()));
1487 EXPECT_TRUE(matches("void x() { do ; while(0); }", doStmt()));
1490 TEST_P(ASTMatchersTest
, DoStmt_DoesNotMatchWhileLoops
) {
1491 EXPECT_TRUE(notMatches("void x() { while(1) {} }", doStmt()));
1494 TEST_P(ASTMatchersTest
, SwitchCase_MatchesCase
) {
1495 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
1496 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
1497 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
1498 EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
1501 TEST_P(ASTMatchersTest
, SwitchCase_MatchesSwitch
) {
1502 EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
1503 EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
1504 EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
1505 EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
1508 TEST_P(ASTMatchersTest
, CxxExceptionHandling_SimpleCases
) {
1509 if (!GetParam().isCXX()) {
1512 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
1513 EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
1515 notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
1517 matches("void foo() try { throw; } catch(int X) { }", cxxThrowExpr()));
1519 matches("void foo() try { throw 5;} catch(int X) { }", cxxThrowExpr()));
1520 EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
1521 cxxCatchStmt(isCatchAll())));
1522 EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
1523 cxxCatchStmt(isCatchAll())));
1524 EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
1525 varDecl(isExceptionVariable())));
1526 EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
1527 varDecl(isExceptionVariable())));
1530 TEST_P(ASTMatchersTest
, ParenExpr_SimpleCases
) {
1531 EXPECT_TRUE(matches("int i = (3);", traverse(TK_AsIs
, parenExpr())));
1532 EXPECT_TRUE(matches("int i = (3 + 7);", traverse(TK_AsIs
, parenExpr())));
1533 EXPECT_TRUE(notMatches("int i = 3;", traverse(TK_AsIs
, parenExpr())));
1534 EXPECT_TRUE(notMatches("int f() { return 1; }; void g() { int a = f(); }",
1535 traverse(TK_AsIs
, parenExpr())));
1538 TEST_P(ASTMatchersTest
, IgnoringParens
) {
1539 EXPECT_FALSE(matches("const char* str = (\"my-string\");",
1540 traverse(TK_AsIs
, implicitCastExpr(hasSourceExpression(
1541 stringLiteral())))));
1543 matches("const char* str = (\"my-string\");",
1544 traverse(TK_AsIs
, implicitCastExpr(hasSourceExpression(
1545 ignoringParens(stringLiteral()))))));
1548 TEST_P(ASTMatchersTest
, QualType
) {
1549 EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
1552 TEST_P(ASTMatchersTest
, ConstantArrayType
) {
1553 EXPECT_TRUE(matches("int a[2];", constantArrayType()));
1554 EXPECT_TRUE(notMatches("void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
1555 constantArrayType(hasElementType(builtinType()))));
1557 EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
1558 EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
1559 EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
1562 TEST_P(ASTMatchersTest
, DependentSizedArrayType
) {
1563 if (!GetParam().isCXX()) {
1567 matches("template <typename T, int Size> class array { T data[Size]; };",
1568 dependentSizedArrayType()));
1570 notMatches("int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1571 dependentSizedArrayType()));
1574 TEST_P(ASTMatchersTest
, DependentSizedExtVectorType
) {
1575 if (!GetParam().isCXX()) {
1578 EXPECT_TRUE(matches("template<typename T, int Size>"
1580 " typedef T __attribute__((ext_vector_type(Size))) type;"
1582 dependentSizedExtVectorType()));
1584 notMatches("int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1585 dependentSizedExtVectorType()));
1588 TEST_P(ASTMatchersTest
, IncompleteArrayType
) {
1589 EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
1590 EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
1592 EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
1593 incompleteArrayType()));
1596 TEST_P(ASTMatchersTest
, VariableArrayType
) {
1597 EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
1598 EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
1600 EXPECT_TRUE(matches("void f(int b) { int a[b]; }",
1601 variableArrayType(hasSizeExpr(ignoringImpCasts(
1602 declRefExpr(to(varDecl(hasName("b")))))))));
1605 TEST_P(ASTMatchersTest
, AtomicType
) {
1606 if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1607 llvm::Triple::Win32
) {
1608 // FIXME: Make this work for MSVC.
1609 EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
1612 matches("_Atomic(int) i;", atomicType(hasValueType(isInteger()))));
1614 notMatches("_Atomic(float) f;", atomicType(hasValueType(isInteger()))));
1618 TEST_P(ASTMatchersTest
, AutoType
) {
1619 if (!GetParam().isCXX11OrLater()) {
1622 EXPECT_TRUE(matches("auto i = 2;", autoType()));
1623 EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
1626 EXPECT_TRUE(matches("auto i = 2;", varDecl(hasType(isInteger()))));
1627 EXPECT_TRUE(matches("struct X{}; auto x = X{};",
1628 varDecl(hasType(recordDecl(hasName("X"))))));
1630 // FIXME: Matching against the type-as-written can't work here, because the
1631 // type as written was not deduced.
1632 // EXPECT_TRUE(matches("auto a = 1;",
1633 // autoType(hasDeducedType(isInteger()))));
1634 // EXPECT_TRUE(notMatches("auto b = 2.0;",
1635 // autoType(hasDeducedType(isInteger()))));
1638 TEST_P(ASTMatchersTest
, DecltypeType
) {
1639 if (!GetParam().isCXX11OrLater()) {
1642 EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;", decltypeType()));
1643 EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;",
1644 decltypeType(hasUnderlyingType(isInteger()))));
1647 TEST_P(ASTMatchersTest
, FunctionType
) {
1648 EXPECT_TRUE(matches("int (*f)(int);", functionType()));
1649 EXPECT_TRUE(matches("void f(int i) {}", functionType()));
1652 TEST_P(ASTMatchersTest
, IgnoringParens_Type
) {
1654 notMatches("void (*fp)(void);", pointerType(pointee(functionType()))));
1655 EXPECT_TRUE(matches("void (*fp)(void);",
1656 pointerType(pointee(ignoringParens(functionType())))));
1659 TEST_P(ASTMatchersTest
, FunctionProtoType
) {
1660 EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
1661 EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
1662 EXPECT_TRUE(matches("void f(void);", functionProtoType(parameterCountIs(0))));
1665 TEST_P(ASTMatchersTest
, FunctionProtoType_C
) {
1666 if (!GetParam().isC()) {
1669 EXPECT_TRUE(notMatches("void f();", functionProtoType()));
1672 TEST_P(ASTMatchersTest
, FunctionProtoType_CXX
) {
1673 if (!GetParam().isCXX()) {
1676 EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
1679 TEST_P(ASTMatchersTest
, ParenType
) {
1681 matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
1682 EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
1684 EXPECT_TRUE(matches(
1685 "int (*ptr_to_func)(int);",
1686 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1687 EXPECT_TRUE(notMatches(
1688 "int (*ptr_to_array)[4];",
1689 varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1692 TEST_P(ASTMatchersTest
, PointerType
) {
1693 // FIXME: Reactive when these tests can be more specific (not matching
1694 // implicit code on certain platforms), likely when we have hasDescendant for
1696 // EXPECT_TRUE(matchAndVerifyResultTrue(
1698 // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
1699 // std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1700 // EXPECT_TRUE(matchAndVerifyResultTrue(
1702 // pointerTypeLoc().bind("loc"),
1703 // std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1704 EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(qualType())))));
1705 EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(pointerType())))));
1706 EXPECT_TRUE(matches("int* b; int* * const a = &b;",
1707 loc(qualType(isConstQualified(), pointerType()))));
1709 StringRef Fragment
= "int *ptr;";
1710 EXPECT_TRUE(notMatches(Fragment
,
1711 varDecl(hasName("ptr"), hasType(blockPointerType()))));
1712 EXPECT_TRUE(notMatches(
1713 Fragment
, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1715 matches(Fragment
, varDecl(hasName("ptr"), hasType(pointerType()))));
1717 notMatches(Fragment
, varDecl(hasName("ptr"), hasType(referenceType()))));
1720 TEST_P(ASTMatchersTest
, PointerType_CXX
) {
1721 if (!GetParam().isCXX()) {
1724 StringRef Fragment
= "struct A { int i; }; int A::* ptr = &A::i;";
1725 EXPECT_TRUE(notMatches(Fragment
,
1726 varDecl(hasName("ptr"), hasType(blockPointerType()))));
1728 matches(Fragment
, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1730 notMatches(Fragment
, varDecl(hasName("ptr"), hasType(pointerType()))));
1732 notMatches(Fragment
, varDecl(hasName("ptr"), hasType(referenceType()))));
1733 EXPECT_TRUE(notMatches(
1734 Fragment
, varDecl(hasName("ptr"), hasType(lValueReferenceType()))));
1735 EXPECT_TRUE(notMatches(
1736 Fragment
, varDecl(hasName("ptr"), hasType(rValueReferenceType()))));
1738 Fragment
= "int a; int &ref = a;";
1739 EXPECT_TRUE(notMatches(Fragment
,
1740 varDecl(hasName("ref"), hasType(blockPointerType()))));
1741 EXPECT_TRUE(notMatches(
1742 Fragment
, varDecl(hasName("ref"), hasType(memberPointerType()))));
1744 notMatches(Fragment
, varDecl(hasName("ref"), hasType(pointerType()))));
1746 matches(Fragment
, varDecl(hasName("ref"), hasType(referenceType()))));
1747 EXPECT_TRUE(matches(Fragment
,
1748 varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1749 EXPECT_TRUE(notMatches(
1750 Fragment
, varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1753 TEST_P(ASTMatchersTest
, PointerType_CXX11
) {
1754 if (!GetParam().isCXX11OrLater()) {
1757 StringRef Fragment
= "int &&ref = 2;";
1758 EXPECT_TRUE(notMatches(Fragment
,
1759 varDecl(hasName("ref"), hasType(blockPointerType()))));
1760 EXPECT_TRUE(notMatches(
1761 Fragment
, varDecl(hasName("ref"), hasType(memberPointerType()))));
1763 notMatches(Fragment
, varDecl(hasName("ref"), hasType(pointerType()))));
1765 matches(Fragment
, varDecl(hasName("ref"), hasType(referenceType()))));
1766 EXPECT_TRUE(notMatches(
1767 Fragment
, varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1768 EXPECT_TRUE(matches(Fragment
,
1769 varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1772 TEST_P(ASTMatchersTest
, AutoRefTypes
) {
1773 if (!GetParam().isCXX11OrLater()) {
1777 StringRef Fragment
= "auto a = 1;"
1783 notMatches(Fragment
, varDecl(hasName("a"), hasType(referenceType()))));
1785 notMatches(Fragment
, varDecl(hasName("b"), hasType(referenceType()))));
1787 matches(Fragment
, varDecl(hasName("c"), hasType(referenceType()))));
1789 matches(Fragment
, varDecl(hasName("c"), hasType(lValueReferenceType()))));
1790 EXPECT_TRUE(notMatches(
1791 Fragment
, varDecl(hasName("c"), hasType(rValueReferenceType()))));
1793 matches(Fragment
, varDecl(hasName("d"), hasType(referenceType()))));
1795 matches(Fragment
, varDecl(hasName("d"), hasType(lValueReferenceType()))));
1796 EXPECT_TRUE(notMatches(
1797 Fragment
, varDecl(hasName("d"), hasType(rValueReferenceType()))));
1799 matches(Fragment
, varDecl(hasName("e"), hasType(referenceType()))));
1800 EXPECT_TRUE(notMatches(
1801 Fragment
, varDecl(hasName("e"), hasType(lValueReferenceType()))));
1803 matches(Fragment
, varDecl(hasName("e"), hasType(rValueReferenceType()))));
1806 TEST_P(ASTMatchersTest
, EnumType
) {
1808 matches("enum Color { Green }; enum Color color;", loc(enumType())));
1811 TEST_P(ASTMatchersTest
, EnumType_CXX
) {
1812 if (!GetParam().isCXX()) {
1815 EXPECT_TRUE(matches("enum Color { Green }; Color color;", loc(enumType())));
1818 TEST_P(ASTMatchersTest
, EnumType_CXX11
) {
1819 if (!GetParam().isCXX11OrLater()) {
1823 matches("enum class Color { Green }; Color color;", loc(enumType())));
1826 TEST_P(ASTMatchersTest
, PointerType_MatchesPointersToConstTypes
) {
1827 EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1828 EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1829 EXPECT_TRUE(matches("int b; const int * a = &b;",
1830 loc(pointerType(pointee(builtinType())))));
1831 EXPECT_TRUE(matches("int b; const int * a = &b;",
1832 pointerType(pointee(builtinType()))));
1835 TEST_P(ASTMatchersTest
, TypedefType
) {
1836 EXPECT_TRUE(matches("typedef int X; X a;",
1837 varDecl(hasName("a"), hasType(elaboratedType(
1838 namesType(typedefType()))))));
1841 TEST_P(ASTMatchersTest
, MacroQualifiedType
) {
1842 EXPECT_TRUE(matches(
1844 #define CDECL __attribute__((cdecl))
1845 typedef void (CDECL *X)();
1847 typedefDecl(hasType(pointerType(pointee(macroQualifiedType()))))));
1848 EXPECT_TRUE(notMatches(
1850 typedef void (__attribute__((cdecl)) *Y)();
1852 typedefDecl(hasType(pointerType(pointee(macroQualifiedType()))))));
1855 TEST_P(ASTMatchersTest
, TemplateSpecializationType
) {
1856 if (!GetParam().isCXX()) {
1859 EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
1860 templateSpecializationType()));
1863 TEST_P(ASTMatchersTest
, DeducedTemplateSpecializationType
) {
1864 if (!GetParam().isCXX17OrLater()) {
1868 matches("template <typename T> class A{ public: A(T) {} }; A a(1);",
1869 deducedTemplateSpecializationType()));
1872 TEST_P(ASTMatchersTest
, RecordType
) {
1873 EXPECT_TRUE(matches("struct S {}; struct S s;",
1874 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1875 EXPECT_TRUE(notMatches("int i;",
1876 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1879 TEST_P(ASTMatchersTest
, RecordType_CXX
) {
1880 if (!GetParam().isCXX()) {
1883 EXPECT_TRUE(matches("class C {}; C c;", recordType()));
1884 EXPECT_TRUE(matches("struct S {}; S s;",
1885 recordType(hasDeclaration(recordDecl(hasName("S"))))));
1888 TEST_P(ASTMatchersTest
, ElaboratedType
) {
1889 if (!GetParam().isCXX()) {
1890 // FIXME: Add a test for `elaboratedType()` that does not depend on C++.
1893 EXPECT_TRUE(matches("namespace N {"
1900 EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
1901 EXPECT_TRUE(matches("class C {}; C c;", elaboratedType()));
1904 TEST_P(ASTMatchersTest
, SubstTemplateTypeParmType
) {
1905 if (!GetParam().isCXX()) {
1908 StringRef code
= "template <typename T>"
1912 "int i = F<int>();";
1913 EXPECT_FALSE(matches(code
, binaryOperator(hasLHS(
1914 expr(hasType(substTemplateTypeParmType()))))));
1915 EXPECT_TRUE(matches(code
, binaryOperator(hasRHS(
1916 expr(hasType(substTemplateTypeParmType()))))));
1919 TEST_P(ASTMatchersTest
, NestedNameSpecifier
) {
1920 if (!GetParam().isCXX()) {
1924 matches("namespace ns { struct A {}; } ns::A a;", nestedNameSpecifier()));
1925 EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
1926 nestedNameSpecifier()));
1928 matches("struct A { void f(); }; void A::f() {}", nestedNameSpecifier()));
1929 EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
1930 nestedNameSpecifier()));
1932 EXPECT_TRUE(matches("struct A { static void f() {} }; void g() { A::f(); }",
1933 nestedNameSpecifier()));
1935 notMatches("struct A { static void f() {} }; void g(A* a) { a->f(); }",
1936 nestedNameSpecifier()));
1939 TEST_P(ASTMatchersTest
, Attr
) {
1940 // Windows adds some implicit attributes.
1941 bool AutomaticAttributes
= StringRef(GetParam().Target
).contains("win32");
1942 if (GetParam().isCXX11OrLater()) {
1943 EXPECT_TRUE(matches("struct [[clang::warn_unused_result]] F{};", attr()));
1945 // Unknown attributes are not parsed into an AST node.
1946 if (!AutomaticAttributes
) {
1947 EXPECT_TRUE(notMatches("int x [[unknownattr]];", attr()));
1950 if (GetParam().isCXX17OrLater()) {
1951 EXPECT_TRUE(matches("struct [[nodiscard]] F{};", attr()));
1953 EXPECT_TRUE(matches("int x(int * __attribute__((nonnull)) );", attr()));
1954 if (!AutomaticAttributes
) {
1955 EXPECT_TRUE(notMatches("struct F{}; int x(int *);", attr()));
1956 // Some known attributes are not parsed into an AST node.
1957 EXPECT_TRUE(notMatches("typedef int x __attribute__((ext_vector_type(1)));",
1962 TEST_P(ASTMatchersTest
, NullStmt
) {
1963 EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
1964 EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
1967 TEST_P(ASTMatchersTest
, NamespaceAliasDecl
) {
1968 if (!GetParam().isCXX()) {
1971 EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
1972 namespaceAliasDecl(hasName("alias"))));
1975 TEST_P(ASTMatchersTest
, NestedNameSpecifier_MatchesTypes
) {
1976 if (!GetParam().isCXX()) {
1979 NestedNameSpecifierMatcher Matcher
= nestedNameSpecifier(
1980 specifiesType(hasDeclaration(recordDecl(hasName("A")))));
1981 EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher
));
1983 matches("struct A { struct B { struct C {}; }; }; A::B::C c;", Matcher
));
1984 EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher
));
1987 TEST_P(ASTMatchersTest
, NestedNameSpecifier_MatchesNamespaceDecls
) {
1988 if (!GetParam().isCXX()) {
1991 NestedNameSpecifierMatcher Matcher
=
1992 nestedNameSpecifier(specifiesNamespace(hasName("ns")));
1993 EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher
));
1994 EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher
));
1995 EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher
));
1998 TEST_P(ASTMatchersTest
,
1999 NestedNameSpecifier_MatchesNestedNameSpecifierPrefixes
) {
2000 if (!GetParam().isCXX()) {
2003 EXPECT_TRUE(matches(
2004 "struct A { struct B { struct C {}; }; }; A::B::C c;",
2005 nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
2006 EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
2007 nestedNameSpecifierLoc(hasPrefix(specifiesTypeLoc(
2008 loc(qualType(asString("struct A"))))))));
2009 EXPECT_TRUE(matches(
2010 "namespace N { struct A { struct B { struct C {}; }; }; } N::A::B::C c;",
2011 nestedNameSpecifierLoc(hasPrefix(
2012 specifiesTypeLoc(loc(qualType(asString("struct N::A"))))))));
2015 template <typename T
>
2016 class VerifyAncestorHasChildIsEqual
: public BoundNodesCallback
{
2018 bool run(const BoundNodes
*Nodes
) override
{ return false; }
2020 bool run(const BoundNodes
*Nodes
, ASTContext
*Context
) override
{
2021 const T
*Node
= Nodes
->getNodeAs
<T
>("");
2022 return verify(*Nodes
, *Context
, Node
);
2025 bool verify(const BoundNodes
&Nodes
, ASTContext
&Context
, const Stmt
*Node
) {
2026 // Use the original typed pointer to verify we can pass pointers to subtypes
2028 const T
*TypedNode
= cast
<T
>(Node
);
2029 return selectFirst
<T
>(
2030 "", match(stmt(hasParent(
2031 stmt(has(stmt(equalsNode(TypedNode
)))).bind(""))),
2032 *Node
, Context
)) != nullptr;
2034 bool verify(const BoundNodes
&Nodes
, ASTContext
&Context
, const Decl
*Node
) {
2035 // Use the original typed pointer to verify we can pass pointers to subtypes
2037 const T
*TypedNode
= cast
<T
>(Node
);
2038 return selectFirst
<T
>(
2039 "", match(decl(hasParent(
2040 decl(has(decl(equalsNode(TypedNode
)))).bind(""))),
2041 *Node
, Context
)) != nullptr;
2043 bool verify(const BoundNodes
&Nodes
, ASTContext
&Context
, const Type
*Node
) {
2044 // Use the original typed pointer to verify we can pass pointers to subtypes
2046 const T
*TypedNode
= cast
<T
>(Node
);
2047 const auto *Dec
= Nodes
.getNodeAs
<FieldDecl
>("decl");
2048 return selectFirst
<T
>(
2049 "", match(fieldDecl(hasParent(decl(has(fieldDecl(
2050 hasType(type(equalsNode(TypedNode
)).bind(""))))))),
2051 *Dec
, Context
)) != nullptr;
2055 TEST_P(ASTMatchersTest
, IsEqualTo_MatchesNodesByIdentity
) {
2056 EXPECT_TRUE(matchAndVerifyResultTrue(
2057 "void f() { if (1) if(1) {} }", ifStmt().bind(""),
2058 std::make_unique
<VerifyAncestorHasChildIsEqual
<IfStmt
>>()));
2061 TEST_P(ASTMatchersTest
, IsEqualTo_MatchesNodesByIdentity_Cxx
) {
2062 if (!GetParam().isCXX()) {
2065 EXPECT_TRUE(matchAndVerifyResultTrue(
2066 "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
2067 std::make_unique
<VerifyAncestorHasChildIsEqual
<CXXRecordDecl
>>()));
2068 EXPECT_TRUE(matchAndVerifyResultTrue(
2069 "class X { class Y {} y; };",
2070 fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
2071 std::make_unique
<VerifyAncestorHasChildIsEqual
<Type
>>()));
2074 TEST_P(ASTMatchersTest
, TypedefDecl
) {
2075 EXPECT_TRUE(matches("typedef int typedefDeclTest;",
2076 typedefDecl(hasName("typedefDeclTest"))));
2079 TEST_P(ASTMatchersTest
, TypedefDecl_Cxx
) {
2080 if (!GetParam().isCXX11OrLater()) {
2083 EXPECT_TRUE(notMatches("using typedefDeclTest = int;",
2084 typedefDecl(hasName("typedefDeclTest"))));
2087 TEST_P(ASTMatchersTest
, TypeAliasDecl
) {
2088 EXPECT_TRUE(notMatches("typedef int typeAliasTest;",
2089 typeAliasDecl(hasName("typeAliasTest"))));
2092 TEST_P(ASTMatchersTest
, TypeAliasDecl_CXX
) {
2093 if (!GetParam().isCXX11OrLater()) {
2096 EXPECT_TRUE(matches("using typeAliasTest = int;",
2097 typeAliasDecl(hasName("typeAliasTest"))));
2100 TEST_P(ASTMatchersTest
, TypedefNameDecl
) {
2101 EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;",
2102 typedefNameDecl(hasName("typedefNameDeclTest1"))));
2105 TEST_P(ASTMatchersTest
, TypedefNameDecl_CXX
) {
2106 if (!GetParam().isCXX11OrLater()) {
2109 EXPECT_TRUE(matches("using typedefNameDeclTest = int;",
2110 typedefNameDecl(hasName("typedefNameDeclTest"))));
2113 TEST_P(ASTMatchersTest
, TypeAliasTemplateDecl
) {
2114 if (!GetParam().isCXX11OrLater()) {
2117 StringRef Code
= R
"(
2118 template <typename T>
2121 template <typename T>
2122 using typeAliasTemplateDecl = X<T>;
2124 using typeAliasDecl = X<int>;
2127 matches(Code
, typeAliasTemplateDecl(hasName("typeAliasTemplateDecl"))));
2129 notMatches(Code
, typeAliasTemplateDecl(hasName("typeAliasDecl"))));
2132 TEST_P(ASTMatchersTest
, QualifiedTypeLocTest_BindsToConstIntVarDecl
) {
2133 EXPECT_TRUE(matches("const int x = 0;",
2134 qualifiedTypeLoc(loc(asString("const int")))));
2137 TEST_P(ASTMatchersTest
, QualifiedTypeLocTest_BindsToConstIntFunctionDecl
) {
2138 EXPECT_TRUE(matches("const int f() { return 5; }",
2139 qualifiedTypeLoc(loc(asString("const int")))));
2142 TEST_P(ASTMatchersTest
, QualifiedTypeLocTest_DoesNotBindToUnqualifiedVarDecl
) {
2143 EXPECT_TRUE(notMatches("int x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2146 TEST_P(ASTMatchersTest
, QualifiedTypeLocTest_IntDoesNotBindToConstIntDecl
) {
2148 notMatches("const int x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2151 TEST_P(ASTMatchersTest
, QualifiedTypeLocTest_IntDoesNotBindToConstFloatDecl
) {
2153 notMatches("const float x = 0;", qualifiedTypeLoc(loc(asString("int")))));
2156 TEST_P(ASTMatchersTest
, PointerTypeLocTest_BindsToAnyPointerTypeLoc
) {
2157 auto matcher
= varDecl(hasName("x"), hasTypeLoc(pointerTypeLoc()));
2158 EXPECT_TRUE(matches("int* x;", matcher
));
2159 EXPECT_TRUE(matches("float* x;", matcher
));
2160 EXPECT_TRUE(matches("char* x;", matcher
));
2161 EXPECT_TRUE(matches("void* x;", matcher
));
2164 TEST_P(ASTMatchersTest
, PointerTypeLocTest_DoesNotBindToNonPointerTypeLoc
) {
2165 auto matcher
= varDecl(hasName("x"), hasTypeLoc(pointerTypeLoc()));
2166 EXPECT_TRUE(notMatches("int x;", matcher
));
2167 EXPECT_TRUE(notMatches("float x;", matcher
));
2168 EXPECT_TRUE(notMatches("char x;", matcher
));
2171 TEST_P(ASTMatchersTest
, ReferenceTypeLocTest_BindsToAnyReferenceTypeLoc
) {
2172 if (!GetParam().isCXX()) {
2175 auto matcher
= varDecl(hasName("r"), hasTypeLoc(referenceTypeLoc()));
2176 EXPECT_TRUE(matches("int rr = 3; int& r = rr;", matcher
));
2177 EXPECT_TRUE(matches("int rr = 3; auto& r = rr;", matcher
));
2178 EXPECT_TRUE(matches("int rr = 3; const int& r = rr;", matcher
));
2179 EXPECT_TRUE(matches("float rr = 3.0; float& r = rr;", matcher
));
2180 EXPECT_TRUE(matches("char rr = 'a'; char& r = rr;", matcher
));
2183 TEST_P(ASTMatchersTest
, ReferenceTypeLocTest_DoesNotBindToNonReferenceTypeLoc
) {
2184 auto matcher
= varDecl(hasName("r"), hasTypeLoc(referenceTypeLoc()));
2185 EXPECT_TRUE(notMatches("int r;", matcher
));
2186 EXPECT_TRUE(notMatches("int r = 3;", matcher
));
2187 EXPECT_TRUE(notMatches("const int r = 3;", matcher
));
2188 EXPECT_TRUE(notMatches("int* r;", matcher
));
2189 EXPECT_TRUE(notMatches("float r;", matcher
));
2190 EXPECT_TRUE(notMatches("char r;", matcher
));
2193 TEST_P(ASTMatchersTest
, ReferenceTypeLocTest_BindsToAnyRvalueReferenceTypeLoc
) {
2194 if (!GetParam().isCXX()) {
2197 auto matcher
= varDecl(hasName("r"), hasTypeLoc(referenceTypeLoc()));
2198 EXPECT_TRUE(matches("int&& r = 3;", matcher
));
2199 EXPECT_TRUE(matches("auto&& r = 3;", matcher
));
2200 EXPECT_TRUE(matches("float&& r = 3.0;", matcher
));
2205 TemplateSpecializationTypeLocTest_BindsToTemplateSpecializationExplicitInstantiation
) {
2206 if (!GetParam().isCXX()) {
2210 matches("template <typename T> class C {}; template class C<int>;",
2211 classTemplateSpecializationDecl(
2212 hasName("C"), hasTypeLoc(templateSpecializationTypeLoc()))));
2215 TEST_P(ASTMatchersTest
,
2216 TemplateSpecializationTypeLocTest_BindsToVarDeclTemplateSpecialization
) {
2217 if (!GetParam().isCXX()) {
2220 EXPECT_TRUE(matches(
2221 "template <typename T> class C {}; C<char> var;",
2222 varDecl(hasName("var"), hasTypeLoc(elaboratedTypeLoc(hasNamedTypeLoc(
2223 templateSpecializationTypeLoc()))))));
2228 TemplateSpecializationTypeLocTest_DoesNotBindToNonTemplateSpecialization
) {
2229 if (!GetParam().isCXX()) {
2232 EXPECT_TRUE(notMatches(
2233 "class C {}; C var;",
2234 varDecl(hasName("var"), hasTypeLoc(templateSpecializationTypeLoc()))));
2237 TEST_P(ASTMatchersTest
,
2238 ElaboratedTypeLocTest_BindsToElaboratedObjectDeclaration
) {
2239 if (!GetParam().isCXX()) {
2242 EXPECT_TRUE(matches("class C {}; class C c;",
2243 varDecl(hasName("c"), hasTypeLoc(elaboratedTypeLoc()))));
2246 TEST_P(ASTMatchersTest
,
2247 ElaboratedTypeLocTest_BindsToNamespaceElaboratedObjectDeclaration
) {
2248 if (!GetParam().isCXX()) {
2251 EXPECT_TRUE(matches("namespace N { class D {}; } N::D d;",
2252 varDecl(hasName("d"), hasTypeLoc(elaboratedTypeLoc()))));
2255 TEST_P(ASTMatchersTest
,
2256 ElaboratedTypeLocTest_BindsToElaboratedStructDeclaration
) {
2257 EXPECT_TRUE(matches("struct s {}; struct s ss;",
2258 varDecl(hasName("ss"), hasTypeLoc(elaboratedTypeLoc()))));
2261 TEST_P(ASTMatchersTest
,
2262 ElaboratedTypeLocTest_BindsToBareElaboratedObjectDeclaration
) {
2263 if (!GetParam().isCXX()) {
2266 EXPECT_TRUE(matches("class C {}; C c;",
2267 varDecl(hasName("c"), hasTypeLoc(elaboratedTypeLoc()))));
2272 ElaboratedTypeLocTest_DoesNotBindToNamespaceNonElaboratedObjectDeclaration
) {
2273 if (!GetParam().isCXX()) {
2276 EXPECT_TRUE(matches("namespace N { class D {}; } using N::D; D d;",
2277 varDecl(hasName("d"), hasTypeLoc(elaboratedTypeLoc()))));
2280 TEST_P(ASTMatchersTest
,
2281 ElaboratedTypeLocTest_BindsToBareElaboratedStructDeclaration
) {
2282 if (!GetParam().isCXX()) {
2285 EXPECT_TRUE(matches("struct s {}; s ss;",
2286 varDecl(hasName("ss"), hasTypeLoc(elaboratedTypeLoc()))));
2289 TEST_P(ASTMatchersTest
, LambdaCaptureTest
) {
2290 if (!GetParam().isCXX11OrLater()) {
2293 EXPECT_TRUE(matches("int main() { int cc; auto f = [cc](){ return cc; }; }",
2294 lambdaExpr(hasAnyCapture(lambdaCapture()))));
2297 TEST_P(ASTMatchersTest
, LambdaCaptureTest_BindsToCaptureOfVarDecl
) {
2298 if (!GetParam().isCXX11OrLater()) {
2301 auto matcher
= lambdaExpr(
2302 hasAnyCapture(lambdaCapture(capturesVar(varDecl(hasName("cc"))))));
2303 EXPECT_TRUE(matches("int main() { int cc; auto f = [cc](){ return cc; }; }",
2305 EXPECT_TRUE(matches("int main() { int cc; auto f = [&cc](){ return cc; }; }",
2308 matches("int main() { int cc; auto f = [=](){ return cc; }; }", matcher
));
2310 matches("int main() { int cc; auto f = [&](){ return cc; }; }", matcher
));
2313 TEST_P(ASTMatchersTest
, LambdaCaptureTest_BindsToCaptureWithInitializer
) {
2314 if (!GetParam().isCXX14OrLater()) {
2317 auto matcher
= lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(
2318 varDecl(hasName("cc"), hasInitializer(integerLiteral(equals(1))))))));
2320 matches("int main() { auto lambda = [cc = 1] {return cc;}; }", matcher
));
2322 matches("int main() { int cc = 2; auto lambda = [cc = 1] {return cc;}; }",
2326 TEST_P(ASTMatchersTest
, LambdaCaptureTest_DoesNotBindToCaptureOfVarDecl
) {
2327 if (!GetParam().isCXX11OrLater()) {
2330 auto matcher
= lambdaExpr(
2331 hasAnyCapture(lambdaCapture(capturesVar(varDecl(hasName("cc"))))));
2332 EXPECT_FALSE(matches("int main() { auto f = [](){ return 5; }; }", matcher
));
2333 EXPECT_FALSE(matches("int main() { int xx; auto f = [xx](){ return xx; }; }",
2337 TEST_P(ASTMatchersTest
,
2338 LambdaCaptureTest_DoesNotBindToCaptureWithInitializerAndDifferentName
) {
2339 if (!GetParam().isCXX14OrLater()) {
2342 EXPECT_FALSE(matches(
2343 "int main() { auto lambda = [xx = 1] {return xx;}; }",
2344 lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(varDecl(
2345 hasName("cc"), hasInitializer(integerLiteral(equals(1))))))))));
2348 TEST_P(ASTMatchersTest
, LambdaCaptureTest_BindsToCaptureOfReferenceType
) {
2349 if (!GetParam().isCXX20OrLater()) {
2352 auto matcher
= lambdaExpr(hasAnyCapture(
2353 lambdaCapture(capturesVar(varDecl(hasType(referenceType()))))));
2354 EXPECT_TRUE(matches("template <class ...T> void f(T &...args) {"
2355 " [&...args = args] () mutable {"
2362 EXPECT_FALSE(matches("template <class ...T> void f(T &...args) {"
2363 " [...args = args] () mutable {"
2372 TEST_P(ASTMatchersTest
, IsDerivedFromRecursion
) {
2373 if (!GetParam().isCXX11OrLater())
2376 // Check we don't crash on cycles in the traversal and inheritance hierarchy.
2377 // Clang will normally enforce there are no cycles, but matchers opted to
2378 // traverse primary template for dependent specializations, spuriously
2379 // creating the cycles.
2380 DeclarationMatcher matcher
= cxxRecordDecl(isDerivedFrom("X"));
2381 EXPECT_TRUE(notMatches(R
"cpp(
2382 template <typename T1, typename T2>
2385 template <typename T1>
2386 struct M<T1, void> {};
2388 template <typename T1, typename T2>
2389 struct L : M<T1, T2> {};
2391 template <typename T1, typename T2>
2392 struct M : L<M<T1, T2>, M<T1, T2>> {};
2396 // Check the running time is not exponential. The number of subojects to
2397 // traverse grows as fibonacci numbers even though the number of bases to
2398 // traverse is quadratic.
2399 // The test will hang if implementation of matchers traverses all subojects.
2400 EXPECT_TRUE(notMatches(R
"cpp(
2401 template <class T> struct A0 {};
2402 template <class T> struct A1 : A0<T> {};
2403 template <class T> struct A2 : A1<T>, A0<T> {};
2404 template <class T> struct A3 : A2<T>, A1<T> {};
2405 template <class T> struct A4 : A3<T>, A2<T> {};
2406 template <class T> struct A5 : A4<T>, A3<T> {};
2407 template <class T> struct A6 : A5<T>, A4<T> {};
2408 template <class T> struct A7 : A6<T>, A5<T> {};
2409 template <class T> struct A8 : A7<T>, A6<T> {};
2410 template <class T> struct A9 : A8<T>, A7<T> {};
2411 template <class T> struct A10 : A9<T>, A8<T> {};
2412 template <class T> struct A11 : A10<T>, A9<T> {};
2413 template <class T> struct A12 : A11<T>, A10<T> {};
2414 template <class T> struct A13 : A12<T>, A11<T> {};
2415 template <class T> struct A14 : A13<T>, A12<T> {};
2416 template <class T> struct A15 : A14<T>, A13<T> {};
2417 template <class T> struct A16 : A15<T>, A14<T> {};
2418 template <class T> struct A17 : A16<T>, A15<T> {};
2419 template <class T> struct A18 : A17<T>, A16<T> {};
2420 template <class T> struct A19 : A18<T>, A17<T> {};
2421 template <class T> struct A20 : A19<T>, A18<T> {};
2422 template <class T> struct A21 : A20<T>, A19<T> {};
2423 template <class T> struct A22 : A21<T>, A20<T> {};
2424 template <class T> struct A23 : A22<T>, A21<T> {};
2425 template <class T> struct A24 : A23<T>, A22<T> {};
2426 template <class T> struct A25 : A24<T>, A23<T> {};
2427 template <class T> struct A26 : A25<T>, A24<T> {};
2428 template <class T> struct A27 : A26<T>, A25<T> {};
2429 template <class T> struct A28 : A27<T>, A26<T> {};
2430 template <class T> struct A29 : A28<T>, A27<T> {};
2431 template <class T> struct A30 : A29<T>, A28<T> {};
2432 template <class T> struct A31 : A30<T>, A29<T> {};
2433 template <class T> struct A32 : A31<T>, A30<T> {};
2434 template <class T> struct A33 : A32<T>, A31<T> {};
2435 template <class T> struct A34 : A33<T>, A32<T> {};
2436 template <class T> struct A35 : A34<T>, A33<T> {};
2437 template <class T> struct A36 : A35<T>, A34<T> {};
2438 template <class T> struct A37 : A36<T>, A35<T> {};
2439 template <class T> struct A38 : A37<T>, A36<T> {};
2440 template <class T> struct A39 : A38<T>, A37<T> {};
2441 template <class T> struct A40 : A39<T>, A38<T> {};
2446 TEST(ASTMatchersTestObjC
, ObjCMessageCalees
) {
2447 StatementMatcher MessagingFoo
=
2448 objcMessageExpr(callee(objcMethodDecl(hasName("foo"))));
2450 EXPECT_TRUE(matchesObjC("@interface I"
2457 EXPECT_TRUE(notMatchesObjC("@interface I"
2465 EXPECT_TRUE(matchesObjC("@interface I"
2474 EXPECT_TRUE(notMatchesObjC("@interface I"
2485 TEST(ASTMatchersTestObjC
, ObjCMessageExpr
) {
2486 // Don't find ObjCMessageExpr where none are present.
2487 EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
2489 StringRef Objc1String
= "@interface Str "
2490 " - (Str *)uppercaseString;"
2494 "- (void)meth:(Str *)text;"
2497 "@implementation foo "
2498 "- (void) meth:(Str *)text { "
2500 " Str *up = [text uppercaseString];"
2503 EXPECT_TRUE(matchesObjC(Objc1String
, objcMessageExpr(anything())));
2504 EXPECT_TRUE(matchesObjC(Objc1String
,
2505 objcMessageExpr(hasAnySelector({"contents", "meth:"}))
2509 matchesObjC(Objc1String
, objcMessageExpr(hasSelector("contents"))));
2510 EXPECT_TRUE(matchesObjC(
2511 Objc1String
, objcMessageExpr(hasAnySelector("contents", "contentsA"))));
2512 EXPECT_FALSE(matchesObjC(
2513 Objc1String
, objcMessageExpr(hasAnySelector("contentsB", "contentsC"))));
2515 matchesObjC(Objc1String
, objcMessageExpr(matchesSelector("cont*"))));
2517 matchesObjC(Objc1String
, objcMessageExpr(matchesSelector("?cont*"))));
2519 notMatchesObjC(Objc1String
, objcMessageExpr(hasSelector("contents"),
2520 hasNullSelector())));
2521 EXPECT_TRUE(matchesObjC(Objc1String
, objcMessageExpr(hasSelector("contents"),
2522 hasUnarySelector())));
2523 EXPECT_TRUE(matchesObjC(Objc1String
, objcMessageExpr(hasSelector("contents"),
2524 numSelectorArgs(0))));
2526 matchesObjC(Objc1String
, objcMessageExpr(matchesSelector("uppercase*"),
2527 argumentCountIs(0))));
2530 TEST(ASTMatchersTestObjC
, ObjCStringLiteral
) {
2532 StringRef Objc1String
= "@interface NSObject "
2534 "@interface NSString "
2536 "@interface Test : NSObject "
2537 "+ (void)someFunction:(NSString *)Desc; "
2539 "@implementation Test "
2540 "+ (void)someFunction:(NSString *)Desc { "
2544 " [Test someFunction:@\"Ola!\"]; "
2547 EXPECT_TRUE(matchesObjC(Objc1String
, objcStringLiteral()));
2550 TEST(ASTMatchersTestObjC
, ObjCDecls
) {
2551 StringRef ObjCString
= "@protocol Proto "
2552 "- (void)protoDidThing; "
2555 "@property int enabled; "
2557 "@interface Thing (ABC) "
2558 "- (void)abc_doThing; "
2560 "@implementation Thing "
2562 "- (void)anything {} "
2564 "@implementation Thing (ABC) "
2565 "- (void)abc_doThing {} "
2568 EXPECT_TRUE(matchesObjC(ObjCString
, objcProtocolDecl(hasName("Proto"))));
2570 matchesObjC(ObjCString
, objcImplementationDecl(hasName("Thing"))));
2571 EXPECT_TRUE(matchesObjC(ObjCString
, objcCategoryDecl(hasName("ABC"))));
2572 EXPECT_TRUE(matchesObjC(ObjCString
, objcCategoryImplDecl(hasName("ABC"))));
2574 matchesObjC(ObjCString
, objcMethodDecl(hasName("protoDidThing"))));
2575 EXPECT_TRUE(matchesObjC(ObjCString
, objcMethodDecl(hasName("abc_doThing"))));
2576 EXPECT_TRUE(matchesObjC(ObjCString
, objcMethodDecl(hasName("anything"))));
2577 EXPECT_TRUE(matchesObjC(ObjCString
, objcIvarDecl(hasName("_ivar"))));
2578 EXPECT_TRUE(matchesObjC(ObjCString
, objcPropertyDecl(hasName("enabled"))));
2581 TEST(ASTMatchersTestObjC
, ObjCExceptionStmts
) {
2582 StringRef ObjCString
= "void f(id obj) {"
2589 EXPECT_TRUE(matchesObjC(ObjCString
, objcTryStmt()));
2590 EXPECT_TRUE(matchesObjC(ObjCString
, objcThrowStmt()));
2591 EXPECT_TRUE(matchesObjC(ObjCString
, objcCatchStmt()));
2592 EXPECT_TRUE(matchesObjC(ObjCString
, objcFinallyStmt()));
2595 TEST(ASTMatchersTest
, DecompositionDecl
) {
2596 StringRef Code
= R
"cpp(
2600 auto &[f, s, t] = arr;
2605 EXPECT_TRUE(matchesConditionally(
2606 Code
, decompositionDecl(hasBinding(0, bindingDecl(hasName("f")))), true,
2608 EXPECT_FALSE(matchesConditionally(
2609 Code
, decompositionDecl(hasBinding(42, bindingDecl(hasName("f")))), true,
2611 EXPECT_FALSE(matchesConditionally(
2612 Code
, decompositionDecl(hasBinding(0, bindingDecl(hasName("s")))), true,
2614 EXPECT_TRUE(matchesConditionally(
2615 Code
, decompositionDecl(hasBinding(1, bindingDecl(hasName("s")))), true,
2618 EXPECT_TRUE(matchesConditionally(
2620 bindingDecl(decl().bind("self"), hasName("f"),
2621 forDecomposition(decompositionDecl(
2622 hasAnyBinding(bindingDecl(equalsBoundNode("self")))))),
2623 true, {"-std=c++17"}));
2626 TEST(ASTMatchersTestObjC
, ObjCAutoreleasePoolStmt
) {
2627 StringRef ObjCString
= "void f() {"
2628 "@autoreleasepool {"
2632 EXPECT_TRUE(matchesObjC(ObjCString
, autoreleasePoolStmt()));
2633 StringRef ObjCStringNoPool
= "void f() { int x = 1; }";
2634 EXPECT_FALSE(matchesObjC(ObjCStringNoPool
, autoreleasePoolStmt()));
2637 TEST(ASTMatchersTestOpenMP
, OMPExecutableDirective
) {
2638 auto Matcher
= stmt(ompExecutableDirective());
2640 StringRef Source0
= R
"(
2642 #pragma omp parallel
2645 EXPECT_TRUE(matchesWithOpenMP(Source0
, Matcher
));
2647 StringRef Source1
= R
"(
2649 #pragma omp taskyield
2652 EXPECT_TRUE(matchesWithOpenMP(Source1
, Matcher
));
2654 StringRef Source2
= R
"(
2658 EXPECT_TRUE(notMatchesWithOpenMP(Source2
, Matcher
));
2661 TEST(ASTMatchersTestOpenMP
, OMPDefaultClause
) {
2662 auto Matcher
= ompExecutableDirective(hasAnyClause(ompDefaultClause()));
2664 StringRef Source0
= R
"(
2668 EXPECT_TRUE(notMatchesWithOpenMP(Source0
, Matcher
));
2670 StringRef Source1
= R
"(
2672 #pragma omp parallel
2675 EXPECT_TRUE(notMatchesWithOpenMP(Source1
, Matcher
));
2677 StringRef Source2
= R
"(
2679 #pragma omp parallel default(none)
2682 EXPECT_TRUE(matchesWithOpenMP(Source2
, Matcher
));
2684 StringRef Source3
= R
"(
2686 #pragma omp parallel default(shared)
2689 EXPECT_TRUE(matchesWithOpenMP(Source3
, Matcher
));
2691 StringRef Source4
= R
"(
2693 #pragma omp parallel default(firstprivate)
2696 EXPECT_TRUE(matchesWithOpenMP51(Source4
, Matcher
));
2698 StringRef Source5
= R
"(
2700 #pragma omp parallel num_threads(x)
2703 EXPECT_TRUE(notMatchesWithOpenMP(Source5
, Matcher
));
2706 TEST(ASTMatchersTest
, Finder_DynamicOnlyAcceptsSomeMatchers
) {
2708 EXPECT_TRUE(Finder
.addDynamicMatcher(decl(), nullptr));
2709 EXPECT_TRUE(Finder
.addDynamicMatcher(callExpr(), nullptr));
2711 Finder
.addDynamicMatcher(constantArrayType(hasSize(42)), nullptr));
2713 // Do not accept non-toplevel matchers.
2714 EXPECT_FALSE(Finder
.addDynamicMatcher(isMain(), nullptr));
2715 EXPECT_FALSE(Finder
.addDynamicMatcher(hasName("x"), nullptr));
2718 TEST(MatchFinderAPI
, MatchesDynamic
) {
2719 StringRef SourceCode
= "struct A { void f() {} };";
2720 auto Matcher
= functionDecl(isDefinition()).bind("method");
2722 auto astUnit
= tooling::buildASTFromCode(SourceCode
);
2724 auto GlobalBoundNodes
= matchDynamic(Matcher
, astUnit
->getASTContext());
2726 EXPECT_EQ(GlobalBoundNodes
.size(), 1u);
2727 EXPECT_EQ(GlobalBoundNodes
[0].getMap().size(), 1u);
2729 auto GlobalMethodNode
= GlobalBoundNodes
[0].getNodeAs
<FunctionDecl
>("method");
2730 EXPECT_TRUE(GlobalMethodNode
!= nullptr);
2732 auto MethodBoundNodes
=
2733 matchDynamic(Matcher
, *GlobalMethodNode
, astUnit
->getASTContext());
2734 EXPECT_EQ(MethodBoundNodes
.size(), 1u);
2735 EXPECT_EQ(MethodBoundNodes
[0].getMap().size(), 1u);
2737 auto MethodNode
= MethodBoundNodes
[0].getNodeAs
<FunctionDecl
>("method");
2738 EXPECT_EQ(MethodNode
, GlobalMethodNode
);
2741 static std::vector
<TestClangConfig
> allTestClangConfigs() {
2742 std::vector
<TestClangConfig
> all_configs
;
2743 for (TestLanguage lang
: {Lang_C89
, Lang_C99
, Lang_CXX03
, Lang_CXX11
,
2744 Lang_CXX14
, Lang_CXX17
, Lang_CXX20
}) {
2745 TestClangConfig config
;
2746 config
.Language
= lang
;
2748 // Use an unknown-unknown triple so we don't instantiate the full system
2749 // toolchain. On Linux, instantiating the toolchain involves stat'ing
2750 // large portions of /usr/lib, and this slows down not only this test, but
2751 // all other tests, via contention in the kernel.
2753 // FIXME: This is a hack to work around the fact that there's no way to do
2754 // the equivalent of runToolOnCodeWithArgs without instantiating a full
2755 // Driver. We should consider having a function, at least for tests, that
2757 config
.Target
= "i386-unknown-unknown";
2758 all_configs
.push_back(config
);
2760 // Windows target is interesting to test because it enables
2761 // `-fdelayed-template-parsing`.
2762 config
.Target
= "x86_64-pc-win32-msvc";
2763 all_configs
.push_back(config
);
2768 INSTANTIATE_TEST_SUITE_P(ASTMatchersTests
, ASTMatchersTest
,
2769 testing::ValuesIn(allTestClangConfigs()));
2771 } // namespace ast_matchers
2772 } // namespace clang