• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 //===----------------------------------------------------------------------===//
8 
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/ADT/Triple.h"
15 #include "llvm/Support/Host.h"
16 #include "gtest/gtest.h"
17 
18 namespace clang {
19 namespace ast_matchers {
20 
TEST_P(ASTMatchersTest,Decl_CXX)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;
25   }
26   EXPECT_TRUE(notMatches("", decl(usingDecl())));
27   EXPECT_TRUE(
28       matches("namespace x { class X {}; } using x::X;", decl(usingDecl())));
29 }
30 
TEST_P(ASTMatchersTest,NameableDeclaration_MatchesVariousDecls)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));
37 
38   EXPECT_TRUE(notMatches("#define X 1", NamedX));
39 }
40 
TEST_P(ASTMatchersTest,NamedDecl_CXX)41 TEST_P(ASTMatchersTest, NamedDecl_CXX) {
42   if (!GetParam().isCXX()) {
43     return;
44   }
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));
49 }
50 
TEST_P(ASTMatchersTest,MatchesNameRE)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));
57 
58   EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
59 
60   DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
61   EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
62 
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));
68 
69   DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
70   EXPECT_TRUE(matches("int k;", StartsWithK));
71   EXPECT_TRUE(matches("int kAbc;", StartsWithK));
72 }
73 
TEST_P(ASTMatchersTest,MatchesNameRE_CXX)74 TEST_P(ASTMatchersTest, MatchesNameRE_CXX) {
75   if (!GetParam().isCXX()) {
76     return;
77   }
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));
82 
83   DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
84   EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
85 
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));
91 
92   DeclarationMatcher StartsWithKIgnoreCase =
93       namedDecl(matchesName(":k[^:]*$", llvm::Regex::IgnoreCase));
94   EXPECT_TRUE(matches("int k;", StartsWithKIgnoreCase));
95   EXPECT_TRUE(matches("int K;", StartsWithKIgnoreCase));
96 }
97 
TEST_P(ASTMatchersTest,DeclarationMatcher_MatchClass)98 TEST_P(ASTMatchersTest, DeclarationMatcher_MatchClass) {
99   if (!GetParam().isCXX()) {
100     return;
101   }
102 
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));
108 }
109 
TEST_P(ASTMatchersTest,TranslationUnitDecl)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;
115   }
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()))))));
128 }
129 
TEST_P(ASTMatchersTest,LinkageSpecDecl)130 TEST_P(ASTMatchersTest, LinkageSpecDecl) {
131   if (!GetParam().isCXX()) {
132     return;
133   }
134   EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
135   EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
136 }
137 
TEST_P(ASTMatchersTest,ClassTemplateDecl_DoesNotMatchClass)138 TEST_P(ASTMatchersTest, ClassTemplateDecl_DoesNotMatchClass) {
139   if (!GetParam().isCXX()) {
140     return;
141   }
142   DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
143   EXPECT_TRUE(notMatches("class X;", ClassX));
144   EXPECT_TRUE(notMatches("class X {};", ClassX));
145 }
146 
TEST_P(ASTMatchersTest,ClassTemplateDecl_MatchesClassTemplate)147 TEST_P(ASTMatchersTest, ClassTemplateDecl_MatchesClassTemplate) {
148   if (!GetParam().isCXX()) {
149     return;
150   }
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));
154 }
155 
TEST_P(ASTMatchersTest,ClassTemplateDecl_DoesNotMatchClassTemplateExplicitSpecialization)156 TEST_P(ASTMatchersTest,
157        ClassTemplateDecl_DoesNotMatchClassTemplateExplicitSpecialization) {
158   if (!GetParam().isCXX()) {
159     return;
160   }
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"))))));
165 }
166 
TEST_P(ASTMatchersTest,ClassTemplateDecl_DoesNotMatchClassTemplatePartialSpecialization)167 TEST_P(ASTMatchersTest,
168        ClassTemplateDecl_DoesNotMatchClassTemplatePartialSpecialization) {
169   if (!GetParam().isCXX()) {
170     return;
171   }
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"))))));
176 }
177 
TEST(ASTMatchersTestCUDA,CUDAKernelCallExpr)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()));
183 }
184 
TEST(ASTMatchersTestCUDA,HasAttrCUDA)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)));
190 }
191 
TEST_P(ASTMatchersTest,ValueDecl)192 TEST_P(ASTMatchersTest, ValueDecl) {
193   if (!GetParam().isCXX()) {
194     // FIXME: Fix this test in non-C++ language modes.
195     return;
196   }
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)")))));
201 }
202 
TEST_P(ASTMatchersTest,FriendDecl)203 TEST_P(ASTMatchersTest, FriendDecl) {
204   if (!GetParam().isCXX()) {
205     return;
206   }
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"))))));
211 
212   EXPECT_TRUE(matches("class Y { friend void f(); };",
213                       functionDecl(hasName("f"), hasParent(friendDecl()))));
214 }
215 
TEST_P(ASTMatchersTest,EnumDecl_DoesNotMatchClasses)216 TEST_P(ASTMatchersTest, EnumDecl_DoesNotMatchClasses) {
217   if (!GetParam().isCXX()) {
218     return;
219   }
220   EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
221 }
222 
TEST_P(ASTMatchersTest,EnumDecl_MatchesEnums)223 TEST_P(ASTMatchersTest, EnumDecl_MatchesEnums) {
224   if (!GetParam().isCXX()) {
225     // FIXME: Fix this test in non-C++ language modes.
226     return;
227   }
228   EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
229 }
230 
TEST_P(ASTMatchersTest,EnumConstantDecl)231 TEST_P(ASTMatchersTest, EnumConstantDecl) {
232   if (!GetParam().isCXX()) {
233     // FIXME: Fix this test in non-C++ language modes.
234     return;
235   }
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));
240 }
241 
TEST_P(ASTMatchersTest,TagDecl)242 TEST_P(ASTMatchersTest, TagDecl) {
243   if (!GetParam().isCXX()) {
244     // FIXME: Fix this test in non-C++ language modes.
245     return;
246   }
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"))));
250 }
251 
TEST_P(ASTMatchersTest,TagDecl_CXX)252 TEST_P(ASTMatchersTest, TagDecl_CXX) {
253   if (!GetParam().isCXX()) {
254     return;
255   }
256   EXPECT_TRUE(matches("class C {};", tagDecl(hasName("C"))));
257 }
258 
TEST_P(ASTMatchersTest,UnresolvedLookupExpr)259 TEST_P(ASTMatchersTest, UnresolvedLookupExpr) {
260   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
261     // FIXME: Fix this test to work with delayed template parsing.
262     return;
263   }
264 
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()));
272 }
273 
TEST_P(ASTMatchersTest,UsesADL)274 TEST_P(ASTMatchersTest, UsesADL) {
275   if (!GetParam().isCXX()) {
276     return;
277   }
278 
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);
286   }
287   struct MyX {};
288   void f(...);
289   void operator+(MyX, MyX);
290 )cpp";
291 
292   auto MkStr = [&](StringRef Body) {
293     return (NS_Str + "void test_fn() { " + Body + " }").str();
294   };
295 
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));
300 
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));
308 }
309 
TEST_P(ASTMatchersTest,CallExpr_CXX)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;
314   }
315   // FIXME: Do we want to overload Call() to directly take
316   // Matcher<Decl>, too?
317   StatementMatcher MethodX =
318       callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
319 
320   EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
321   EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
322 
323   StatementMatcher MethodOnY =
324       cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
325 
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));
336 
337   StatementMatcher MethodOnYPointer =
338       cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
339 
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));
355 }
356 
TEST_P(ASTMatchersTest,LambdaExpr)357 TEST_P(ASTMatchersTest, LambdaExpr) {
358   if (!GetParam().isCXX11OrLater()) {
359     return;
360   }
361   EXPECT_TRUE(matches("auto f = [] (int i) { return i; };", lambdaExpr()));
362 }
363 
TEST_P(ASTMatchersTest,CXXForRangeStmt)364 TEST_P(ASTMatchersTest, CXXForRangeStmt) {
365   EXPECT_TRUE(
366       notMatches("void f() { for (int i; i<5; ++i); }", cxxForRangeStmt()));
367 }
368 
TEST_P(ASTMatchersTest,CXXForRangeStmt_CXX11)369 TEST_P(ASTMatchersTest, CXXForRangeStmt_CXX11) {
370   if (!GetParam().isCXX11OrLater()) {
371     return;
372   }
373   EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
374                       "void f() { for (auto &a : as); }",
375                       cxxForRangeStmt()));
376 }
377 
TEST_P(ASTMatchersTest,SubstNonTypeTemplateParmExpr)378 TEST_P(ASTMatchersTest, SubstNonTypeTemplateParmExpr) {
379   if (!GetParam().isCXX()) {
380     return;
381   }
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())));
390 }
391 
TEST_P(ASTMatchersTest,NonTypeTemplateParmDecl)392 TEST_P(ASTMatchersTest, NonTypeTemplateParmDecl) {
393   if (!GetParam().isCXX()) {
394     return;
395   }
396   EXPECT_TRUE(matches("template <int N> void f();",
397                       nonTypeTemplateParmDecl(hasName("N"))));
398   EXPECT_TRUE(
399       notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
400 }
401 
TEST_P(ASTMatchersTest,TemplateTypeParmDecl)402 TEST_P(ASTMatchersTest, TemplateTypeParmDecl) {
403   if (!GetParam().isCXX()) {
404     return;
405   }
406   EXPECT_TRUE(matches("template <typename T> void f();",
407                       templateTypeParmDecl(hasName("T"))));
408   EXPECT_TRUE(notMatches("template <int N> void f();", templateTypeParmDecl()));
409 }
410 
TEST_P(ASTMatchersTest,TemplateTemplateParmDecl)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()));
418 }
419 
TEST_P(ASTMatchersTest,UserDefinedLiteral)420 TEST_P(ASTMatchersTest, UserDefinedLiteral) {
421   if (!GetParam().isCXX11OrLater()) {
422     return;
423   }
424   EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
425                       "  return i + 1;"
426                       "}"
427                       "char c = 'a'_inc;",
428                       userDefinedLiteral()));
429 }
430 
TEST_P(ASTMatchersTest,FlowControl)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()));
440 }
441 
TEST_P(ASTMatchersTest,CXXOperatorCallExpr)442 TEST_P(ASTMatchersTest, CXXOperatorCallExpr) {
443   if (!GetParam().isCXX()) {
444     return;
445   }
446 
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));
472 }
473 
TEST_P(ASTMatchersTest,ThisPointerType)474 TEST_P(ASTMatchersTest, ThisPointerType) {
475   if (!GetParam().isCXX()) {
476     return;
477   }
478 
479   StatementMatcher MethodOnY =
480       traverse(ast_type_traits::TK_AsIs,
481                cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y")))));
482 
483   EXPECT_TRUE(matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
484                       MethodOnY));
485   EXPECT_TRUE(matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
486                       MethodOnY));
487   EXPECT_TRUE(matches(
488       "class Y { public: void x(); }; void z(Y *&y) { y->x(); }", MethodOnY));
489   EXPECT_TRUE(matches(
490       "class Y { public: void x(); }; void z(Y y[]) { y->x(); }", MethodOnY));
491   EXPECT_TRUE(matches(
492       "class Y { public: void x(); }; void z() { Y *y; y->x(); }", MethodOnY));
493 
494   EXPECT_TRUE(matches("class Y {"
495                       "  public: virtual void x();"
496                       "};"
497                       "class X : public Y {"
498                       "  public: virtual void x();"
499                       "};"
500                       "void z() { X *x; x->Y::x(); }",
501                       MethodOnY));
502 }
503 
TEST_P(ASTMatchersTest,DeclRefExpr)504 TEST_P(ASTMatchersTest, DeclRefExpr) {
505   if (!GetParam().isCXX()) {
506     // FIXME: Add a test for `declRefExpr()` that does not depend on C++.
507     return;
508   }
509   StatementMatcher Reference = declRefExpr(to(varDecl(hasInitializer(
510       cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
511 
512   EXPECT_TRUE(matches("class Y {"
513                       " public:"
514                       "  bool x() const;"
515                       "};"
516                       "void z(const Y &y) {"
517                       "  bool b = y.x();"
518                       "  if (b) {}"
519                       "}",
520                       Reference));
521 
522   EXPECT_TRUE(notMatches("class Y {"
523                          " public:"
524                          "  bool x() const;"
525                          "};"
526                          "void z(const Y &y) {"
527                          "  bool b = y.x();"
528                          "}",
529                          Reference));
530 }
531 
TEST_P(ASTMatchersTest,CXXMemberCallExpr)532 TEST_P(ASTMatchersTest, CXXMemberCallExpr) {
533   if (!GetParam().isCXX()) {
534     return;
535   }
536   StatementMatcher CallOnVariableY =
537       cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
538 
539   EXPECT_TRUE(matches("class Y { public: void x() { Y y; y.x(); } };",
540                       CallOnVariableY));
541   EXPECT_TRUE(matches("class Y { public: void x() const { Y y; y.x(); } };",
542                       CallOnVariableY));
543   EXPECT_TRUE(matches("class Y { public: void x(); };"
544                       "class X : public Y { void z() { X y; y.x(); } };",
545                       CallOnVariableY));
546   EXPECT_TRUE(matches("class Y { public: void x(); };"
547                       "class X : public Y { void z() { X *y; y->x(); } };",
548                       CallOnVariableY));
549   EXPECT_TRUE(notMatches(
550       "class Y { public: void x(); };"
551       "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
552       CallOnVariableY));
553 }
554 
TEST_P(ASTMatchersTest,UnaryExprOrTypeTraitExpr)555 TEST_P(ASTMatchersTest, UnaryExprOrTypeTraitExpr) {
556   EXPECT_TRUE(
557       matches("void x() { int a = sizeof(a); }", unaryExprOrTypeTraitExpr()));
558 }
559 
TEST_P(ASTMatchersTest,AlignOfExpr)560 TEST_P(ASTMatchersTest, AlignOfExpr) {
561   EXPECT_TRUE(
562       notMatches("void x() { int a = sizeof(a); }", alignOfExpr(anything())));
563   // FIXME: Uncomment once alignof is enabled.
564   // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
565   //                     unaryExprOrTypeTraitExpr()));
566   // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
567   //                        sizeOfExpr()));
568 }
569 
TEST_P(ASTMatchersTest,MemberExpr_DoesNotMatchClasses)570 TEST_P(ASTMatchersTest, MemberExpr_DoesNotMatchClasses) {
571   if (!GetParam().isCXX()) {
572     return;
573   }
574   EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
575   EXPECT_TRUE(notMatches("class Y { void x() {} };", unresolvedMemberExpr()));
576   EXPECT_TRUE(
577       notMatches("class Y { void x() {} };", cxxDependentScopeMemberExpr()));
578 }
579 
TEST_P(ASTMatchersTest,MemberExpr_MatchesMemberFunctionCall)580 TEST_P(ASTMatchersTest, MemberExpr_MatchesMemberFunctionCall) {
581   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
582     // FIXME: Fix this test to work with delayed template parsing.
583     return;
584   }
585   EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
586   EXPECT_TRUE(matches("class Y { template <class T> void x() { x<T>(); } };",
587                       unresolvedMemberExpr()));
588   EXPECT_TRUE(matches("template <class T> void x() { T t; t.f(); }",
589                       cxxDependentScopeMemberExpr()));
590 }
591 
TEST_P(ASTMatchersTest,MemberExpr_MatchesVariable)592 TEST_P(ASTMatchersTest, MemberExpr_MatchesVariable) {
593   if (!GetParam().isCXX() || GetParam().hasDelayedTemplateParsing()) {
594     // FIXME: Fix this test to work with delayed template parsing.
595     return;
596   }
597   EXPECT_TRUE(
598       matches("class Y { void x() { this->y; } int y; };", memberExpr()));
599   EXPECT_TRUE(matches("class Y { void x() { y; } int y; };", memberExpr()));
600   EXPECT_TRUE(
601       matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
602   EXPECT_TRUE(matches("template <class T>"
603                       "class X : T { void f() { this->T::v; } };",
604                       cxxDependentScopeMemberExpr()));
605   EXPECT_TRUE(matches("template <class T> class X : T { void f() { T::v; } };",
606                       cxxDependentScopeMemberExpr()));
607   EXPECT_TRUE(matches("template <class T> void x() { T t; t.v; }",
608                       cxxDependentScopeMemberExpr()));
609 }
610 
TEST_P(ASTMatchersTest,MemberExpr_MatchesStaticVariable)611 TEST_P(ASTMatchersTest, MemberExpr_MatchesStaticVariable) {
612   if (!GetParam().isCXX()) {
613     return;
614   }
615   EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
616                       memberExpr()));
617   EXPECT_TRUE(
618       notMatches("class Y { void x() { y; } static int y; };", memberExpr()));
619   EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
620                          memberExpr()));
621 }
622 
TEST_P(ASTMatchersTest,FunctionDecl)623 TEST_P(ASTMatchersTest, FunctionDecl) {
624   StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
625 
626   EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
627   EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
628 
629   EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
630   EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
631   EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
632 }
633 
TEST_P(ASTMatchersTest,FunctionDecl_C)634 TEST_P(ASTMatchersTest, FunctionDecl_C) {
635   if (!GetParam().isC()) {
636     return;
637   }
638   EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
639   EXPECT_TRUE(matches("void f();", functionDecl(parameterCountIs(0))));
640 }
641 
TEST_P(ASTMatchersTest,FunctionDecl_CXX)642 TEST_P(ASTMatchersTest, FunctionDecl_CXX) {
643   if (!GetParam().isCXX()) {
644     return;
645   }
646 
647   StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
648 
649   if (!GetParam().hasDelayedTemplateParsing()) {
650     // FIXME: Fix this test to work with delayed template parsing.
651     // Dependent contexts, but a non-dependent call.
652     EXPECT_TRUE(
653         matches("void f(); template <int N> void g() { f(); }", CallFunctionF));
654     EXPECT_TRUE(
655         matches("void f(); template <int N> struct S { void g() { f(); } };",
656                 CallFunctionF));
657   }
658 
659   // Depedent calls don't match.
660   EXPECT_TRUE(
661       notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
662                  CallFunctionF));
663   EXPECT_TRUE(
664       notMatches("void f(int);"
665                  "template <typename T> struct S { void g(T t) { f(t); } };",
666                  CallFunctionF));
667 
668   EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
669   EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
670 }
671 
TEST_P(ASTMatchersTest,FunctionDecl_CXX11)672 TEST_P(ASTMatchersTest, FunctionDecl_CXX11) {
673   if (!GetParam().isCXX11OrLater()) {
674     return;
675   }
676 
677   EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
678                          functionDecl(isVariadic())));
679 }
680 
TEST_P(ASTMatchersTest,FunctionTemplateDecl_MatchesFunctionTemplateDeclarations)681 TEST_P(ASTMatchersTest,
682        FunctionTemplateDecl_MatchesFunctionTemplateDeclarations) {
683   if (!GetParam().isCXX()) {
684     return;
685   }
686   EXPECT_TRUE(matches("template <typename T> void f(T t) {}",
687                       functionTemplateDecl(hasName("f"))));
688 }
689 
TEST_P(ASTMatchersTest,FunctionTemplate_DoesNotMatchFunctionDeclarations)690 TEST_P(ASTMatchersTest, FunctionTemplate_DoesNotMatchFunctionDeclarations) {
691   EXPECT_TRUE(
692       notMatches("void f(double d);", functionTemplateDecl(hasName("f"))));
693   EXPECT_TRUE(
694       notMatches("void f(int t) {}", functionTemplateDecl(hasName("f"))));
695 }
696 
TEST_P(ASTMatchersTest,FunctionTemplateDecl_DoesNotMatchFunctionTemplateSpecializations)697 TEST_P(ASTMatchersTest,
698        FunctionTemplateDecl_DoesNotMatchFunctionTemplateSpecializations) {
699   if (!GetParam().isCXX()) {
700     return;
701   }
702   EXPECT_TRUE(notMatches(
703       "void g(); template <typename T> void f(T t) {}"
704       "template <> void f(int t) { g(); }",
705       functionTemplateDecl(hasName("f"), hasDescendant(declRefExpr(to(
706                                              functionDecl(hasName("g"))))))));
707 }
708 
TEST_P(ASTMatchersTest,ClassTemplateSpecializationDecl)709 TEST_P(ASTMatchersTest, ClassTemplateSpecializationDecl) {
710   if (!GetParam().isCXX()) {
711     return;
712   }
713   EXPECT_TRUE(matches("template<typename T> struct A {};"
714                       "template<> struct A<int> {};",
715                       classTemplateSpecializationDecl()));
716   EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
717                       classTemplateSpecializationDecl()));
718   EXPECT_TRUE(notMatches("template<typename T> struct A {};",
719                          classTemplateSpecializationDecl()));
720 }
721 
TEST_P(ASTMatchersTest,DeclaratorDecl)722 TEST_P(ASTMatchersTest, DeclaratorDecl) {
723   EXPECT_TRUE(matches("int x;", declaratorDecl()));
724   EXPECT_TRUE(notMatches("struct A {};", declaratorDecl()));
725 }
726 
TEST_P(ASTMatchersTest,DeclaratorDecl_CXX)727 TEST_P(ASTMatchersTest, DeclaratorDecl_CXX) {
728   if (!GetParam().isCXX()) {
729     return;
730   }
731   EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
732 }
733 
TEST_P(ASTMatchersTest,ParmVarDecl)734 TEST_P(ASTMatchersTest, ParmVarDecl) {
735   EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
736   EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
737 }
738 
TEST_P(ASTMatchersTest,Matcher_ConstructorCall)739 TEST_P(ASTMatchersTest, Matcher_ConstructorCall) {
740   if (!GetParam().isCXX()) {
741     return;
742   }
743 
744   StatementMatcher Constructor =
745       traverse(ast_type_traits::TK_AsIs, cxxConstructExpr());
746 
747   EXPECT_TRUE(
748       matches("class X { public: X(); }; void x() { X x; }", Constructor));
749   EXPECT_TRUE(matches("class X { public: X(); }; void x() { X x = X(); }",
750                       Constructor));
751   EXPECT_TRUE(matches("class X { public: X(int); }; void x() { X x = 0; }",
752                       Constructor));
753   EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
754 }
755 
TEST_P(ASTMatchersTest,Match_ConstructorInitializers)756 TEST_P(ASTMatchersTest, Match_ConstructorInitializers) {
757   if (!GetParam().isCXX()) {
758     return;
759   }
760   EXPECT_TRUE(matches("class C { int i; public: C(int ii) : i(ii) {} };",
761                       cxxCtorInitializer(forField(hasName("i")))));
762 }
763 
TEST_P(ASTMatchersTest,Matcher_ThisExpr)764 TEST_P(ASTMatchersTest, Matcher_ThisExpr) {
765   if (!GetParam().isCXX()) {
766     return;
767   }
768   EXPECT_TRUE(
769       matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
770   EXPECT_TRUE(
771       notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
772 }
773 
TEST_P(ASTMatchersTest,Matcher_BindTemporaryExpression)774 TEST_P(ASTMatchersTest, Matcher_BindTemporaryExpression) {
775   if (!GetParam().isCXX()) {
776     return;
777   }
778 
779   StatementMatcher TempExpression =
780       traverse(ast_type_traits::TK_AsIs, cxxBindTemporaryExpr());
781 
782   StringRef ClassString = "class string { public: string(); ~string(); }; ";
783 
784   EXPECT_TRUE(matches(
785       ClassString + "string GetStringByValue();"
786                     "void FunctionTakesString(string s);"
787                     "void run() { FunctionTakesString(GetStringByValue()); }",
788       TempExpression));
789 
790   EXPECT_TRUE(notMatches(ClassString +
791                              "string* GetStringPointer(); "
792                              "void FunctionTakesStringPtr(string* s);"
793                              "void run() {"
794                              "  string* s = GetStringPointer();"
795                              "  FunctionTakesStringPtr(GetStringPointer());"
796                              "  FunctionTakesStringPtr(s);"
797                              "}",
798                          TempExpression));
799 
800   EXPECT_TRUE(notMatches("class no_dtor {};"
801                          "no_dtor GetObjByValue();"
802                          "void ConsumeObj(no_dtor param);"
803                          "void run() { ConsumeObj(GetObjByValue()); }",
804                          TempExpression));
805 }
806 
TEST_P(ASTMatchersTest,MaterializeTemporaryExpr_MatchesTemporaryCXX11CXX14)807 TEST_P(ASTMatchersTest, MaterializeTemporaryExpr_MatchesTemporaryCXX11CXX14) {
808   if (GetParam().Language != Lang_CXX11 && GetParam().Language != Lang_CXX14) {
809     return;
810   }
811 
812   StatementMatcher TempExpression =
813       traverse(ast_type_traits::TK_AsIs, materializeTemporaryExpr());
814 
815   EXPECT_TRUE(matches("class string { public: string(); }; "
816                       "string GetStringByValue();"
817                       "void FunctionTakesString(string s);"
818                       "void run() { FunctionTakesString(GetStringByValue()); }",
819                       TempExpression));
820 }
821 
TEST_P(ASTMatchersTest,MaterializeTemporaryExpr_MatchesTemporary)822 TEST_P(ASTMatchersTest, MaterializeTemporaryExpr_MatchesTemporary) {
823   if (!GetParam().isCXX()) {
824     return;
825   }
826 
827   StringRef ClassString = "class string { public: string(); int length(); }; ";
828   StatementMatcher TempExpression =
829       traverse(ast_type_traits::TK_AsIs, materializeTemporaryExpr());
830 
831   EXPECT_TRUE(notMatches(ClassString +
832                              "string* GetStringPointer(); "
833                              "void FunctionTakesStringPtr(string* s);"
834                              "void run() {"
835                              "  string* s = GetStringPointer();"
836                              "  FunctionTakesStringPtr(GetStringPointer());"
837                              "  FunctionTakesStringPtr(s);"
838                              "}",
839                          TempExpression));
840 
841   EXPECT_TRUE(matches(ClassString +
842                           "string GetStringByValue();"
843                           "void run() { int k = GetStringByValue().length(); }",
844                       TempExpression));
845 
846   EXPECT_TRUE(notMatches(ClassString + "string GetStringByValue();"
847                                        "void run() { GetStringByValue(); }",
848                          TempExpression));
849 }
850 
TEST_P(ASTMatchersTest,Matcher_NewExpression)851 TEST_P(ASTMatchersTest, Matcher_NewExpression) {
852   if (!GetParam().isCXX()) {
853     return;
854   }
855 
856   StatementMatcher New = cxxNewExpr();
857 
858   EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
859   EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X(); }", New));
860   EXPECT_TRUE(
861       matches("class X { public: X(int); }; void x() { new X(0); }", New));
862   EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
863 }
864 
TEST_P(ASTMatchersTest,Matcher_DeleteExpression)865 TEST_P(ASTMatchersTest, Matcher_DeleteExpression) {
866   if (!GetParam().isCXX()) {
867     return;
868   }
869   EXPECT_TRUE(
870       matches("struct A {}; void f(A* a) { delete a; }", cxxDeleteExpr()));
871 }
872 
TEST_P(ASTMatchersTest,Matcher_NoexceptExpression)873 TEST_P(ASTMatchersTest, Matcher_NoexceptExpression) {
874   if (!GetParam().isCXX11OrLater()) {
875     return;
876   }
877   StatementMatcher NoExcept = cxxNoexceptExpr();
878   EXPECT_TRUE(matches("void foo(); bool bar = noexcept(foo());", NoExcept));
879   EXPECT_TRUE(
880       matches("void foo() noexcept; bool bar = noexcept(foo());", NoExcept));
881   EXPECT_TRUE(notMatches("void foo() noexcept;", NoExcept));
882   EXPECT_TRUE(notMatches("void foo() noexcept(1+1);", NoExcept));
883   EXPECT_TRUE(matches("void foo() noexcept(noexcept(1+1));", NoExcept));
884 }
885 
TEST_P(ASTMatchersTest,Matcher_DefaultArgument)886 TEST_P(ASTMatchersTest, Matcher_DefaultArgument) {
887   if (!GetParam().isCXX()) {
888     return;
889   }
890   StatementMatcher Arg = cxxDefaultArgExpr();
891   EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
892   EXPECT_TRUE(
893       matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
894   EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
895 }
896 
TEST_P(ASTMatchersTest,StringLiteral)897 TEST_P(ASTMatchersTest, StringLiteral) {
898   StatementMatcher Literal = stringLiteral();
899   EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
900   // with escaped characters
901   EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
902   // no matching -- though the data type is the same, there is no string literal
903   EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
904 }
905 
TEST_P(ASTMatchersTest,StringLiteral_CXX)906 TEST_P(ASTMatchersTest, StringLiteral_CXX) {
907   if (!GetParam().isCXX()) {
908     return;
909   }
910   EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", stringLiteral()));
911 }
912 
TEST_P(ASTMatchersTest,CharacterLiteral)913 TEST_P(ASTMatchersTest, CharacterLiteral) {
914   EXPECT_TRUE(matches("const char c = 'c';", characterLiteral()));
915   EXPECT_TRUE(notMatches("const char c = 0x1;", characterLiteral()));
916 }
917 
TEST_P(ASTMatchersTest,CharacterLiteral_CXX)918 TEST_P(ASTMatchersTest, CharacterLiteral_CXX) {
919   if (!GetParam().isCXX()) {
920     return;
921   }
922   // wide character
923   EXPECT_TRUE(matches("const char c = L'c';", characterLiteral()));
924   // wide character, Hex encoded, NOT MATCHED!
925   EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", characterLiteral()));
926 }
927 
TEST_P(ASTMatchersTest,IntegerLiteral)928 TEST_P(ASTMatchersTest, IntegerLiteral) {
929   StatementMatcher HasIntLiteral = integerLiteral();
930   EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
931   EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
932   EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
933   EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
934 
935   // Non-matching cases (character literals, float and double)
936   EXPECT_TRUE(notMatches("int i = L'a';",
937                          HasIntLiteral)); // this is actually a character
938   // literal cast to int
939   EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
940   EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
941   EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
942 
943   // Negative integers.
944   EXPECT_TRUE(
945       matches("int i = -10;",
946               unaryOperator(hasOperatorName("-"),
947                             hasUnaryOperand(integerLiteral(equals(10))))));
948 }
949 
TEST_P(ASTMatchersTest,FloatLiteral)950 TEST_P(ASTMatchersTest, FloatLiteral) {
951   StatementMatcher HasFloatLiteral = floatLiteral();
952   EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
953   EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
954   EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
955   EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
956   EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
957   EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
958   EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
959   EXPECT_TRUE(
960       matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
961 
962   EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
963   EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
964   EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
965   EXPECT_TRUE(
966       notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
967 }
968 
TEST_P(ASTMatchersTest,CXXNullPtrLiteralExpr)969 TEST_P(ASTMatchersTest, CXXNullPtrLiteralExpr) {
970   if (!GetParam().isCXX11OrLater()) {
971     return;
972   }
973   EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
974 }
975 
TEST_P(ASTMatchersTest,ChooseExpr)976 TEST_P(ASTMatchersTest, ChooseExpr) {
977   EXPECT_TRUE(matches("void f() { (void)__builtin_choose_expr(1, 2, 3); }",
978                       chooseExpr()));
979 }
980 
TEST_P(ASTMatchersTest,GNUNullExpr)981 TEST_P(ASTMatchersTest, GNUNullExpr) {
982   if (!GetParam().isCXX()) {
983     return;
984   }
985   EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
986 }
987 
TEST_P(ASTMatchersTest,AtomicExpr)988 TEST_P(ASTMatchersTest, AtomicExpr) {
989   EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }",
990                       atomicExpr()));
991 }
992 
TEST_P(ASTMatchersTest,Initializers_C99)993 TEST_P(ASTMatchersTest, Initializers_C99) {
994   if (!GetParam().isC99OrLater()) {
995     return;
996   }
997   EXPECT_TRUE(matches(
998       "void foo() { struct point { double x; double y; };"
999       "  struct point ptarray[10] = "
1000       "      { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1001       initListExpr(hasSyntacticForm(initListExpr(
1002           has(designatedInitExpr(designatorCountIs(2),
1003                                  hasDescendant(floatLiteral(equals(1.0))),
1004                                  hasDescendant(integerLiteral(equals(2))))),
1005           has(designatedInitExpr(designatorCountIs(2),
1006                                  hasDescendant(floatLiteral(equals(2.0))),
1007                                  hasDescendant(integerLiteral(equals(2))))),
1008           has(designatedInitExpr(
1009               designatorCountIs(2), hasDescendant(floatLiteral(equals(1.0))),
1010               hasDescendant(integerLiteral(equals(0))))))))));
1011 }
1012 
TEST_P(ASTMatchersTest,Initializers_CXX)1013 TEST_P(ASTMatchersTest, Initializers_CXX) {
1014   if (GetParam().Language != Lang_CXX03) {
1015     // FIXME: Make this test pass with other C++ standard versions.
1016     return;
1017   }
1018   EXPECT_TRUE(matches(
1019       "void foo() { struct point { double x; double y; };"
1020       "  struct point ptarray[10] = "
1021       "      { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
1022       initListExpr(
1023           has(cxxConstructExpr(requiresZeroInitialization())),
1024           has(initListExpr(
1025               hasType(asString("struct point")), has(floatLiteral(equals(1.0))),
1026               has(implicitValueInitExpr(hasType(asString("double")))))),
1027           has(initListExpr(hasType(asString("struct point")),
1028                            has(floatLiteral(equals(2.0))),
1029                            has(floatLiteral(equals(1.0))))))));
1030 }
1031 
TEST_P(ASTMatchersTest,ParenListExpr)1032 TEST_P(ASTMatchersTest, ParenListExpr) {
1033   if (!GetParam().isCXX()) {
1034     return;
1035   }
1036   EXPECT_TRUE(
1037       matches("template<typename T> class foo { void bar() { foo X(*this); } };"
1038               "template class foo<int>;",
1039               varDecl(hasInitializer(parenListExpr(has(unaryOperator()))))));
1040 }
1041 
TEST_P(ASTMatchersTest,StmtExpr)1042 TEST_P(ASTMatchersTest, StmtExpr) {
1043   EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }",
1044                       varDecl(hasInitializer(stmtExpr()))));
1045 }
1046 
TEST_P(ASTMatchersTest,PredefinedExpr)1047 TEST_P(ASTMatchersTest, PredefinedExpr) {
1048   // __func__ expands as StringLiteral("foo")
1049   EXPECT_TRUE(matches("void foo() { __func__; }",
1050                       predefinedExpr(hasType(asString("const char [4]")),
1051                                      has(stringLiteral()))));
1052 }
1053 
TEST_P(ASTMatchersTest,AsmStatement)1054 TEST_P(ASTMatchersTest, AsmStatement) {
1055   EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
1056 }
1057 
TEST_P(ASTMatchersTest,HasCondition)1058 TEST_P(ASTMatchersTest, HasCondition) {
1059   if (!GetParam().isCXX()) {
1060     // FIXME: Add a test for `hasCondition()` that does not depend on C++.
1061     return;
1062   }
1063 
1064   StatementMatcher Condition =
1065       ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
1066 
1067   EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
1068   EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
1069   EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
1070   EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
1071   EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
1072 }
1073 
TEST_P(ASTMatchersTest,ConditionalOperator)1074 TEST_P(ASTMatchersTest, ConditionalOperator) {
1075   if (!GetParam().isCXX()) {
1076     // FIXME: Add a test for `conditionalOperator()` that does not depend on
1077     // C++.
1078     return;
1079   }
1080 
1081   StatementMatcher Conditional =
1082       conditionalOperator(hasCondition(cxxBoolLiteral(equals(true))),
1083                           hasTrueExpression(cxxBoolLiteral(equals(false))));
1084 
1085   EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
1086   EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
1087   EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
1088 
1089   StatementMatcher ConditionalFalse =
1090       conditionalOperator(hasFalseExpression(cxxBoolLiteral(equals(false))));
1091 
1092   EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
1093   EXPECT_TRUE(
1094       notMatches("void x() { true ? false : true; }", ConditionalFalse));
1095 
1096   EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
1097   EXPECT_TRUE(
1098       notMatches("void x() { true ? false : true; }", ConditionalFalse));
1099 }
1100 
TEST_P(ASTMatchersTest,BinaryConditionalOperator)1101 TEST_P(ASTMatchersTest, BinaryConditionalOperator) {
1102   if (!GetParam().isCXX()) {
1103     // FIXME: This test should work in non-C++ language modes.
1104     return;
1105   }
1106 
1107   StatementMatcher AlwaysOne =
1108       traverse(ast_type_traits::TK_AsIs,
1109                binaryConditionalOperator(
1110                    hasCondition(implicitCastExpr(has(opaqueValueExpr(
1111                        hasSourceExpression((integerLiteral(equals(1)))))))),
1112                    hasFalseExpression(integerLiteral(equals(0)))));
1113 
1114   EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne));
1115 
1116   StatementMatcher FourNotFive = binaryConditionalOperator(
1117       hasTrueExpression(
1118           opaqueValueExpr(hasSourceExpression((integerLiteral(equals(4)))))),
1119       hasFalseExpression(integerLiteral(equals(5))));
1120 
1121   EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive));
1122 }
1123 
TEST_P(ASTMatchersTest,ArraySubscriptExpr)1124 TEST_P(ASTMatchersTest, ArraySubscriptExpr) {
1125   EXPECT_TRUE(
1126       matches("int i[2]; void f() { i[1] = 1; }", arraySubscriptExpr()));
1127   EXPECT_TRUE(notMatches("int i; void f() { i = 1; }", arraySubscriptExpr()));
1128 }
1129 
TEST_P(ASTMatchersTest,ForStmt)1130 TEST_P(ASTMatchersTest, ForStmt) {
1131   EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
1132   EXPECT_TRUE(matches("void f() { if(1) for(;;); }", forStmt()));
1133 }
1134 
TEST_P(ASTMatchersTest,ForStmt_CXX11)1135 TEST_P(ASTMatchersTest, ForStmt_CXX11) {
1136   if (!GetParam().isCXX11OrLater()) {
1137     return;
1138   }
1139   EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
1140                          "void f() { for (auto &a : as); }",
1141                          forStmt()));
1142 }
1143 
TEST_P(ASTMatchersTest,ForStmt_NoFalsePositives)1144 TEST_P(ASTMatchersTest, ForStmt_NoFalsePositives) {
1145   EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
1146   EXPECT_TRUE(notMatches("void f() { if(1); }", forStmt()));
1147 }
1148 
TEST_P(ASTMatchersTest,CompoundStatement)1149 TEST_P(ASTMatchersTest, CompoundStatement) {
1150   EXPECT_TRUE(notMatches("void f();", compoundStmt()));
1151   EXPECT_TRUE(matches("void f() {}", compoundStmt()));
1152   EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
1153 }
1154 
TEST_P(ASTMatchersTest,CompoundStatement_DoesNotMatchEmptyStruct)1155 TEST_P(ASTMatchersTest, CompoundStatement_DoesNotMatchEmptyStruct) {
1156   if (!GetParam().isCXX()) {
1157     // FIXME: Add a similar test that does not depend on C++.
1158     return;
1159   }
1160   // It's not a compound statement just because there's "{}" in the source
1161   // text. This is an AST search, not grep.
1162   EXPECT_TRUE(notMatches("namespace n { struct S {}; }", compoundStmt()));
1163   EXPECT_TRUE(
1164       matches("namespace n { struct S { void f() {{}} }; }", compoundStmt()));
1165 }
1166 
TEST_P(ASTMatchersTest,CastExpr_MatchesExplicitCasts)1167 TEST_P(ASTMatchersTest, CastExpr_MatchesExplicitCasts) {
1168   EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
1169 }
1170 
TEST_P(ASTMatchersTest,CastExpr_MatchesExplicitCasts_CXX)1171 TEST_P(ASTMatchersTest, CastExpr_MatchesExplicitCasts_CXX) {
1172   if (!GetParam().isCXX()) {
1173     return;
1174   }
1175   EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);", castExpr()));
1176   EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
1177   EXPECT_TRUE(matches("char c = char(0);", castExpr()));
1178 }
1179 
TEST_P(ASTMatchersTest,CastExpression_MatchesImplicitCasts)1180 TEST_P(ASTMatchersTest, CastExpression_MatchesImplicitCasts) {
1181   // This test creates an implicit cast from int to char.
1182   EXPECT_TRUE(
1183       matches("char c = 0;", traverse(ast_type_traits::TK_AsIs, castExpr())));
1184   // This test creates an implicit cast from lvalue to rvalue.
1185   EXPECT_TRUE(matches("void f() { char c = 0, d = c; }",
1186                       traverse(ast_type_traits::TK_AsIs, castExpr())));
1187 }
1188 
TEST_P(ASTMatchersTest,CastExpr_DoesNotMatchNonCasts)1189 TEST_P(ASTMatchersTest, CastExpr_DoesNotMatchNonCasts) {
1190   if (GetParam().Language == Lang_C89 || GetParam().Language == Lang_C99) {
1191     // This does have a cast in C
1192     EXPECT_TRUE(matches("char c = '0';", implicitCastExpr()));
1193   } else {
1194     EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
1195   }
1196   EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
1197   EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
1198 }
1199 
TEST_P(ASTMatchersTest,CastExpr_DoesNotMatchNonCasts_CXX)1200 TEST_P(ASTMatchersTest, CastExpr_DoesNotMatchNonCasts_CXX) {
1201   if (!GetParam().isCXX()) {
1202     return;
1203   }
1204   EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
1205 }
1206 
TEST_P(ASTMatchersTest,CXXReinterpretCastExpr)1207 TEST_P(ASTMatchersTest, CXXReinterpretCastExpr) {
1208   if (!GetParam().isCXX()) {
1209     return;
1210   }
1211   EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
1212                       cxxReinterpretCastExpr()));
1213 }
1214 
TEST_P(ASTMatchersTest,CXXReinterpretCastExpr_DoesNotMatchOtherCasts)1215 TEST_P(ASTMatchersTest, CXXReinterpretCastExpr_DoesNotMatchOtherCasts) {
1216   if (!GetParam().isCXX()) {
1217     return;
1218   }
1219   EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
1220   EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
1221                          cxxReinterpretCastExpr()));
1222   EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
1223                          cxxReinterpretCastExpr()));
1224   EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1225                          "B b;"
1226                          "D* p = dynamic_cast<D*>(&b);",
1227                          cxxReinterpretCastExpr()));
1228 }
1229 
TEST_P(ASTMatchersTest,CXXFunctionalCastExpr_MatchesSimpleCase)1230 TEST_P(ASTMatchersTest, CXXFunctionalCastExpr_MatchesSimpleCase) {
1231   if (!GetParam().isCXX()) {
1232     return;
1233   }
1234   StringRef foo_class = "class Foo { public: Foo(const char*); };";
1235   EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
1236                       cxxFunctionalCastExpr()));
1237 }
1238 
TEST_P(ASTMatchersTest,CXXFunctionalCastExpr_DoesNotMatchOtherCasts)1239 TEST_P(ASTMatchersTest, CXXFunctionalCastExpr_DoesNotMatchOtherCasts) {
1240   if (!GetParam().isCXX()) {
1241     return;
1242   }
1243   StringRef FooClass = "class Foo { public: Foo(const char*); };";
1244   EXPECT_TRUE(
1245       notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
1246                  cxxFunctionalCastExpr()));
1247   EXPECT_TRUE(notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
1248                          cxxFunctionalCastExpr()));
1249 }
1250 
TEST_P(ASTMatchersTest,CXXDynamicCastExpr)1251 TEST_P(ASTMatchersTest, CXXDynamicCastExpr) {
1252   if (!GetParam().isCXX()) {
1253     return;
1254   }
1255   EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
1256                       "B b;"
1257                       "D* p = dynamic_cast<D*>(&b);",
1258                       cxxDynamicCastExpr()));
1259 }
1260 
TEST_P(ASTMatchersTest,CXXStaticCastExpr_MatchesSimpleCase)1261 TEST_P(ASTMatchersTest, CXXStaticCastExpr_MatchesSimpleCase) {
1262   if (!GetParam().isCXX()) {
1263     return;
1264   }
1265   EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));", cxxStaticCastExpr()));
1266 }
1267 
TEST_P(ASTMatchersTest,CXXStaticCastExpr_DoesNotMatchOtherCasts)1268 TEST_P(ASTMatchersTest, CXXStaticCastExpr_DoesNotMatchOtherCasts) {
1269   if (!GetParam().isCXX()) {
1270     return;
1271   }
1272   EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
1273   EXPECT_TRUE(
1274       notMatches("char q, *p = const_cast<char*>(&q);", cxxStaticCastExpr()));
1275   EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
1276                          cxxStaticCastExpr()));
1277   EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
1278                          "B b;"
1279                          "D* p = dynamic_cast<D*>(&b);",
1280                          cxxStaticCastExpr()));
1281 }
1282 
TEST_P(ASTMatchersTest,CStyleCastExpr_MatchesSimpleCase)1283 TEST_P(ASTMatchersTest, CStyleCastExpr_MatchesSimpleCase) {
1284   EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
1285 }
1286 
TEST_P(ASTMatchersTest,CStyleCastExpr_DoesNotMatchOtherCasts)1287 TEST_P(ASTMatchersTest, CStyleCastExpr_DoesNotMatchOtherCasts) {
1288   if (!GetParam().isCXX()) {
1289     return;
1290   }
1291   EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
1292                          "char q, *r = const_cast<char*>(&q);"
1293                          "void* s = reinterpret_cast<char*>(&s);"
1294                          "struct B { virtual ~B() {} }; struct D : B {};"
1295                          "B b;"
1296                          "D* t = dynamic_cast<D*>(&b);",
1297                          cStyleCastExpr()));
1298 }
1299 
TEST_P(ASTMatchersTest,ImplicitCastExpr_MatchesSimpleCase)1300 TEST_P(ASTMatchersTest, ImplicitCastExpr_MatchesSimpleCase) {
1301   // This test creates an implicit const cast.
1302   EXPECT_TRUE(matches("void f() { int x = 0; const int y = x; }",
1303                       traverse(ast_type_traits::TK_AsIs,
1304                                varDecl(hasInitializer(implicitCastExpr())))));
1305   // This test creates an implicit cast from int to char.
1306   EXPECT_TRUE(matches("char c = 0;",
1307                       traverse(ast_type_traits::TK_AsIs,
1308                                varDecl(hasInitializer(implicitCastExpr())))));
1309   // This test creates an implicit array-to-pointer cast.
1310   EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
1311                       traverse(ast_type_traits::TK_AsIs,
1312                                varDecl(hasInitializer(implicitCastExpr())))));
1313 }
1314 
TEST_P(ASTMatchersTest,ImplicitCastExpr_DoesNotMatchIncorrectly)1315 TEST_P(ASTMatchersTest, ImplicitCastExpr_DoesNotMatchIncorrectly) {
1316   // This test verifies that implicitCastExpr() matches exactly when implicit
1317   // casts are present, and that it ignores explicit and paren casts.
1318 
1319   // These two test cases have no casts.
1320   EXPECT_TRUE(
1321       notMatches("int x = 0;", varDecl(hasInitializer(implicitCastExpr()))));
1322   EXPECT_TRUE(
1323       notMatches("int x = (0);", varDecl(hasInitializer(implicitCastExpr()))));
1324   EXPECT_TRUE(notMatches("void f() { int x = 0; double d = (double) x; }",
1325                          varDecl(hasInitializer(implicitCastExpr()))));
1326 }
1327 
TEST_P(ASTMatchersTest,ImplicitCastExpr_DoesNotMatchIncorrectly_CXX)1328 TEST_P(ASTMatchersTest, ImplicitCastExpr_DoesNotMatchIncorrectly_CXX) {
1329   if (!GetParam().isCXX()) {
1330     return;
1331   }
1332   EXPECT_TRUE(notMatches("int x = 0, &y = x;",
1333                          varDecl(hasInitializer(implicitCastExpr()))));
1334   EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
1335                          varDecl(hasInitializer(implicitCastExpr()))));
1336 }
1337 
TEST_P(ASTMatchersTest,Stmt_DoesNotMatchDeclarations)1338 TEST_P(ASTMatchersTest, Stmt_DoesNotMatchDeclarations) {
1339   EXPECT_TRUE(notMatches("struct X {};", stmt()));
1340 }
1341 
TEST_P(ASTMatchersTest,Stmt_MatchesCompoundStatments)1342 TEST_P(ASTMatchersTest, Stmt_MatchesCompoundStatments) {
1343   EXPECT_TRUE(matches("void x() {}", stmt()));
1344 }
1345 
TEST_P(ASTMatchersTest,DeclStmt_DoesNotMatchCompoundStatements)1346 TEST_P(ASTMatchersTest, DeclStmt_DoesNotMatchCompoundStatements) {
1347   EXPECT_TRUE(notMatches("void x() {}", declStmt()));
1348 }
1349 
TEST_P(ASTMatchersTest,DeclStmt_MatchesVariableDeclarationStatements)1350 TEST_P(ASTMatchersTest, DeclStmt_MatchesVariableDeclarationStatements) {
1351   EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
1352 }
1353 
TEST_P(ASTMatchersTest,ExprWithCleanups_MatchesExprWithCleanups)1354 TEST_P(ASTMatchersTest, ExprWithCleanups_MatchesExprWithCleanups) {
1355   if (!GetParam().isCXX()) {
1356     return;
1357   }
1358   EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
1359                       "const Foo f = Foo();",
1360                       traverse(ast_type_traits::TK_AsIs,
1361                                varDecl(hasInitializer(exprWithCleanups())))));
1362   EXPECT_FALSE(matches("struct Foo { }; Foo a;"
1363                        "const Foo f = a;",
1364                        traverse(ast_type_traits::TK_AsIs,
1365                                 varDecl(hasInitializer(exprWithCleanups())))));
1366 }
1367 
TEST_P(ASTMatchersTest,InitListExpr)1368 TEST_P(ASTMatchersTest, InitListExpr) {
1369   EXPECT_TRUE(matches("int a[] = { 1, 2 };",
1370                       initListExpr(hasType(asString("int [2]")))));
1371   EXPECT_TRUE(matches("struct B { int x, y; }; struct B b = { 5, 6 };",
1372                       initListExpr(hasType(recordDecl(hasName("B"))))));
1373   EXPECT_TRUE(
1374       matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
1375 }
1376 
TEST_P(ASTMatchersTest,InitListExpr_CXX)1377 TEST_P(ASTMatchersTest, InitListExpr_CXX) {
1378   if (!GetParam().isCXX()) {
1379     return;
1380   }
1381   EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
1382                       "void f();"
1383                       "S s[1] = { &f };",
1384                       declRefExpr(to(functionDecl(hasName("f"))))));
1385 }
1386 
TEST_P(ASTMatchersTest,CXXStdInitializerListExpression_MatchesCXXStdInitializerListExpression)1387 TEST_P(ASTMatchersTest,
1388        CXXStdInitializerListExpression_MatchesCXXStdInitializerListExpression) {
1389   if (!GetParam().isCXX11OrLater()) {
1390     return;
1391   }
1392   StringRef code = "namespace std {"
1393                    "template <typename> class initializer_list {"
1394                    "  public: initializer_list() noexcept {}"
1395                    "};"
1396                    "}"
1397                    "struct A {"
1398                    "  A(std::initializer_list<int>) {}"
1399                    "};";
1400   EXPECT_TRUE(
1401       matches(code + "A a{0};",
1402               traverse(ast_type_traits::TK_AsIs,
1403                        cxxConstructExpr(has(cxxStdInitializerListExpr()),
1404                                         hasDeclaration(cxxConstructorDecl(
1405                                             ofClass(hasName("A"))))))));
1406   EXPECT_TRUE(
1407       matches(code + "A a = {0};",
1408               traverse(ast_type_traits::TK_AsIs,
1409                        cxxConstructExpr(has(cxxStdInitializerListExpr()),
1410                                         hasDeclaration(cxxConstructorDecl(
1411                                             ofClass(hasName("A"))))))));
1412 
1413   EXPECT_TRUE(notMatches("int a[] = { 1, 2 };", cxxStdInitializerListExpr()));
1414   EXPECT_TRUE(notMatches("struct B { int x, y; }; B b = { 5, 6 };",
1415                          cxxStdInitializerListExpr()));
1416 }
1417 
TEST_P(ASTMatchersTest,UsingDecl_MatchesUsingDeclarations)1418 TEST_P(ASTMatchersTest, UsingDecl_MatchesUsingDeclarations) {
1419   if (!GetParam().isCXX()) {
1420     return;
1421   }
1422   EXPECT_TRUE(matches("namespace X { int x; } using X::x;", usingDecl()));
1423 }
1424 
TEST_P(ASTMatchersTest,UsingDecl_MatchesShadowUsingDelcarations)1425 TEST_P(ASTMatchersTest, UsingDecl_MatchesShadowUsingDelcarations) {
1426   if (!GetParam().isCXX()) {
1427     return;
1428   }
1429   EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
1430                       usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
1431 }
1432 
TEST_P(ASTMatchersTest,UsingDirectiveDecl_MatchesUsingNamespace)1433 TEST_P(ASTMatchersTest, UsingDirectiveDecl_MatchesUsingNamespace) {
1434   if (!GetParam().isCXX()) {
1435     return;
1436   }
1437   EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
1438                       usingDirectiveDecl()));
1439   EXPECT_FALSE(
1440       matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
1441 }
1442 
TEST_P(ASTMatchersTest,WhileStmt)1443 TEST_P(ASTMatchersTest, WhileStmt) {
1444   EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
1445   EXPECT_TRUE(matches("void x() { while(1); }", whileStmt()));
1446   EXPECT_TRUE(notMatches("void x() { do {} while(1); }", whileStmt()));
1447 }
1448 
TEST_P(ASTMatchersTest,DoStmt_MatchesDoLoops)1449 TEST_P(ASTMatchersTest, DoStmt_MatchesDoLoops) {
1450   EXPECT_TRUE(matches("void x() { do {} while(1); }", doStmt()));
1451   EXPECT_TRUE(matches("void x() { do ; while(0); }", doStmt()));
1452 }
1453 
TEST_P(ASTMatchersTest,DoStmt_DoesNotMatchWhileLoops)1454 TEST_P(ASTMatchersTest, DoStmt_DoesNotMatchWhileLoops) {
1455   EXPECT_TRUE(notMatches("void x() { while(1) {} }", doStmt()));
1456 }
1457 
TEST_P(ASTMatchersTest,SwitchCase_MatchesCase)1458 TEST_P(ASTMatchersTest, SwitchCase_MatchesCase) {
1459   EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
1460   EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
1461   EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
1462   EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
1463 }
1464 
TEST_P(ASTMatchersTest,SwitchCase_MatchesSwitch)1465 TEST_P(ASTMatchersTest, SwitchCase_MatchesSwitch) {
1466   EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
1467   EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
1468   EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
1469   EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
1470 }
1471 
TEST_P(ASTMatchersTest,CxxExceptionHandling_SimpleCases)1472 TEST_P(ASTMatchersTest, CxxExceptionHandling_SimpleCases) {
1473   if (!GetParam().isCXX()) {
1474     return;
1475   }
1476   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
1477   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
1478   EXPECT_TRUE(
1479       notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
1480   EXPECT_TRUE(
1481       matches("void foo() try { throw; } catch(int X) { }", cxxThrowExpr()));
1482   EXPECT_TRUE(
1483       matches("void foo() try { throw 5;} catch(int X) { }", cxxThrowExpr()));
1484   EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
1485                       cxxCatchStmt(isCatchAll())));
1486   EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
1487                          cxxCatchStmt(isCatchAll())));
1488   EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
1489                       varDecl(isExceptionVariable())));
1490   EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
1491                          varDecl(isExceptionVariable())));
1492 }
1493 
TEST_P(ASTMatchersTest,ParenExpr_SimpleCases)1494 TEST_P(ASTMatchersTest, ParenExpr_SimpleCases) {
1495   EXPECT_TRUE(
1496       matches("int i = (3);", traverse(ast_type_traits::TK_AsIs, parenExpr())));
1497   EXPECT_TRUE(matches("int i = (3 + 7);",
1498                       traverse(ast_type_traits::TK_AsIs, parenExpr())));
1499   EXPECT_TRUE(notMatches("int i = 3;",
1500                          traverse(ast_type_traits::TK_AsIs, parenExpr())));
1501   EXPECT_TRUE(notMatches("int f() { return 1; }; void g() { int a = f(); }",
1502                          traverse(ast_type_traits::TK_AsIs, parenExpr())));
1503 }
1504 
TEST_P(ASTMatchersTest,IgnoringParens)1505 TEST_P(ASTMatchersTest, IgnoringParens) {
1506   EXPECT_FALSE(matches(
1507       "const char* str = (\"my-string\");",
1508       traverse(ast_type_traits::TK_AsIs,
1509                implicitCastExpr(hasSourceExpression(stringLiteral())))));
1510   EXPECT_TRUE(matches("const char* str = (\"my-string\");",
1511                       traverse(ast_type_traits::TK_AsIs,
1512                                implicitCastExpr(hasSourceExpression(
1513                                    ignoringParens(stringLiteral()))))));
1514 }
1515 
TEST_P(ASTMatchersTest,QualType)1516 TEST_P(ASTMatchersTest, QualType) {
1517   EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
1518 }
1519 
TEST_P(ASTMatchersTest,ConstantArrayType)1520 TEST_P(ASTMatchersTest, ConstantArrayType) {
1521   EXPECT_TRUE(matches("int a[2];", constantArrayType()));
1522   EXPECT_TRUE(notMatches("void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
1523                          constantArrayType(hasElementType(builtinType()))));
1524 
1525   EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
1526   EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
1527   EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
1528 }
1529 
TEST_P(ASTMatchersTest,DependentSizedArrayType)1530 TEST_P(ASTMatchersTest, DependentSizedArrayType) {
1531   if (!GetParam().isCXX()) {
1532     return;
1533   }
1534   EXPECT_TRUE(
1535       matches("template <typename T, int Size> class array { T data[Size]; };",
1536               dependentSizedArrayType()));
1537   EXPECT_TRUE(
1538       notMatches("int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
1539                  dependentSizedArrayType()));
1540 }
1541 
TEST_P(ASTMatchersTest,IncompleteArrayType)1542 TEST_P(ASTMatchersTest, IncompleteArrayType) {
1543   EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
1544   EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
1545 
1546   EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
1547                          incompleteArrayType()));
1548 }
1549 
TEST_P(ASTMatchersTest,VariableArrayType)1550 TEST_P(ASTMatchersTest, VariableArrayType) {
1551   EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
1552   EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
1553 
1554   EXPECT_TRUE(matches("void f(int b) { int a[b]; }",
1555                       variableArrayType(hasSizeExpr(ignoringImpCasts(
1556                           declRefExpr(to(varDecl(hasName("b")))))))));
1557 }
1558 
TEST_P(ASTMatchersTest,AtomicType)1559 TEST_P(ASTMatchersTest, AtomicType) {
1560   if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
1561       llvm::Triple::Win32) {
1562     // FIXME: Make this work for MSVC.
1563     EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
1564 
1565     EXPECT_TRUE(
1566         matches("_Atomic(int) i;", atomicType(hasValueType(isInteger()))));
1567     EXPECT_TRUE(
1568         notMatches("_Atomic(float) f;", atomicType(hasValueType(isInteger()))));
1569   }
1570 }
1571 
TEST_P(ASTMatchersTest,AutoType)1572 TEST_P(ASTMatchersTest, AutoType) {
1573   if (!GetParam().isCXX11OrLater()) {
1574     return;
1575   }
1576   EXPECT_TRUE(matches("auto i = 2;", autoType()));
1577   EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
1578                       autoType()));
1579 
1580   EXPECT_TRUE(matches("auto i = 2;", varDecl(hasType(isInteger()))));
1581   EXPECT_TRUE(matches("struct X{}; auto x = X{};",
1582                       varDecl(hasType(recordDecl(hasName("X"))))));
1583 
1584   // FIXME: Matching against the type-as-written can't work here, because the
1585   //        type as written was not deduced.
1586   // EXPECT_TRUE(matches("auto a = 1;",
1587   //                    autoType(hasDeducedType(isInteger()))));
1588   // EXPECT_TRUE(notMatches("auto b = 2.0;",
1589   //                       autoType(hasDeducedType(isInteger()))));
1590 }
1591 
TEST_P(ASTMatchersTest,DecltypeType)1592 TEST_P(ASTMatchersTest, DecltypeType) {
1593   if (!GetParam().isCXX11OrLater()) {
1594     return;
1595   }
1596   EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;", decltypeType()));
1597   EXPECT_TRUE(matches("decltype(1 + 1) sum = 1 + 1;",
1598                       decltypeType(hasUnderlyingType(isInteger()))));
1599 }
1600 
TEST_P(ASTMatchersTest,FunctionType)1601 TEST_P(ASTMatchersTest, FunctionType) {
1602   EXPECT_TRUE(matches("int (*f)(int);", functionType()));
1603   EXPECT_TRUE(matches("void f(int i) {}", functionType()));
1604 }
1605 
TEST_P(ASTMatchersTest,IgnoringParens_Type)1606 TEST_P(ASTMatchersTest, IgnoringParens_Type) {
1607   EXPECT_TRUE(
1608       notMatches("void (*fp)(void);", pointerType(pointee(functionType()))));
1609   EXPECT_TRUE(matches("void (*fp)(void);",
1610                       pointerType(pointee(ignoringParens(functionType())))));
1611 }
1612 
TEST_P(ASTMatchersTest,FunctionProtoType)1613 TEST_P(ASTMatchersTest, FunctionProtoType) {
1614   EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
1615   EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
1616   EXPECT_TRUE(matches("void f(void);", functionProtoType(parameterCountIs(0))));
1617 }
1618 
TEST_P(ASTMatchersTest,FunctionProtoType_C)1619 TEST_P(ASTMatchersTest, FunctionProtoType_C) {
1620   if (!GetParam().isC()) {
1621     return;
1622   }
1623   EXPECT_TRUE(notMatches("void f();", functionProtoType()));
1624 }
1625 
TEST_P(ASTMatchersTest,FunctionProtoType_CXX)1626 TEST_P(ASTMatchersTest, FunctionProtoType_CXX) {
1627   if (!GetParam().isCXX()) {
1628     return;
1629   }
1630   EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
1631 }
1632 
TEST_P(ASTMatchersTest,ParenType)1633 TEST_P(ASTMatchersTest, ParenType) {
1634   EXPECT_TRUE(
1635       matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
1636   EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
1637 
1638   EXPECT_TRUE(matches(
1639       "int (*ptr_to_func)(int);",
1640       varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1641   EXPECT_TRUE(notMatches(
1642       "int (*ptr_to_array)[4];",
1643       varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
1644 }
1645 
TEST_P(ASTMatchersTest,PointerType)1646 TEST_P(ASTMatchersTest, PointerType) {
1647   // FIXME: Reactive when these tests can be more specific (not matching
1648   // implicit code on certain platforms), likely when we have hasDescendant for
1649   // Types/TypeLocs.
1650   // EXPECT_TRUE(matchAndVerifyResultTrue(
1651   //    "int* a;",
1652   //    pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
1653   //    std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1654   // EXPECT_TRUE(matchAndVerifyResultTrue(
1655   //    "int* a;",
1656   //    pointerTypeLoc().bind("loc"),
1657   //    std::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
1658   EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(qualType())))));
1659   EXPECT_TRUE(matches("int** a;", loc(pointerType(pointee(pointerType())))));
1660   EXPECT_TRUE(matches("int* b; int* * const a = &b;",
1661                       loc(qualType(isConstQualified(), pointerType()))));
1662 
1663   StringRef Fragment = "int *ptr;";
1664   EXPECT_TRUE(notMatches(Fragment,
1665                          varDecl(hasName("ptr"), hasType(blockPointerType()))));
1666   EXPECT_TRUE(notMatches(
1667       Fragment, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1668   EXPECT_TRUE(
1669       matches(Fragment, varDecl(hasName("ptr"), hasType(pointerType()))));
1670   EXPECT_TRUE(
1671       notMatches(Fragment, varDecl(hasName("ptr"), hasType(referenceType()))));
1672 }
1673 
TEST_P(ASTMatchersTest,PointerType_CXX)1674 TEST_P(ASTMatchersTest, PointerType_CXX) {
1675   if (!GetParam().isCXX()) {
1676     return;
1677   }
1678   StringRef Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
1679   EXPECT_TRUE(notMatches(Fragment,
1680                          varDecl(hasName("ptr"), hasType(blockPointerType()))));
1681   EXPECT_TRUE(
1682       matches(Fragment, varDecl(hasName("ptr"), hasType(memberPointerType()))));
1683   EXPECT_TRUE(
1684       notMatches(Fragment, varDecl(hasName("ptr"), hasType(pointerType()))));
1685   EXPECT_TRUE(
1686       notMatches(Fragment, varDecl(hasName("ptr"), hasType(referenceType()))));
1687   EXPECT_TRUE(notMatches(
1688       Fragment, varDecl(hasName("ptr"), hasType(lValueReferenceType()))));
1689   EXPECT_TRUE(notMatches(
1690       Fragment, varDecl(hasName("ptr"), hasType(rValueReferenceType()))));
1691 
1692   Fragment = "int a; int &ref = a;";
1693   EXPECT_TRUE(notMatches(Fragment,
1694                          varDecl(hasName("ref"), hasType(blockPointerType()))));
1695   EXPECT_TRUE(notMatches(
1696       Fragment, varDecl(hasName("ref"), hasType(memberPointerType()))));
1697   EXPECT_TRUE(
1698       notMatches(Fragment, varDecl(hasName("ref"), hasType(pointerType()))));
1699   EXPECT_TRUE(
1700       matches(Fragment, varDecl(hasName("ref"), hasType(referenceType()))));
1701   EXPECT_TRUE(matches(Fragment,
1702                       varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1703   EXPECT_TRUE(notMatches(
1704       Fragment, varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1705 }
1706 
TEST_P(ASTMatchersTest,PointerType_CXX11)1707 TEST_P(ASTMatchersTest, PointerType_CXX11) {
1708   if (!GetParam().isCXX11OrLater()) {
1709     return;
1710   }
1711   StringRef Fragment = "int &&ref = 2;";
1712   EXPECT_TRUE(notMatches(Fragment,
1713                          varDecl(hasName("ref"), hasType(blockPointerType()))));
1714   EXPECT_TRUE(notMatches(
1715       Fragment, varDecl(hasName("ref"), hasType(memberPointerType()))));
1716   EXPECT_TRUE(
1717       notMatches(Fragment, varDecl(hasName("ref"), hasType(pointerType()))));
1718   EXPECT_TRUE(
1719       matches(Fragment, varDecl(hasName("ref"), hasType(referenceType()))));
1720   EXPECT_TRUE(notMatches(
1721       Fragment, varDecl(hasName("ref"), hasType(lValueReferenceType()))));
1722   EXPECT_TRUE(matches(Fragment,
1723                       varDecl(hasName("ref"), hasType(rValueReferenceType()))));
1724 }
1725 
TEST_P(ASTMatchersTest,AutoRefTypes)1726 TEST_P(ASTMatchersTest, AutoRefTypes) {
1727   if (!GetParam().isCXX11OrLater()) {
1728     return;
1729   }
1730 
1731   StringRef Fragment = "auto a = 1;"
1732                        "auto b = a;"
1733                        "auto &c = a;"
1734                        "auto &&d = c;"
1735                        "auto &&e = 2;";
1736   EXPECT_TRUE(
1737       notMatches(Fragment, varDecl(hasName("a"), hasType(referenceType()))));
1738   EXPECT_TRUE(
1739       notMatches(Fragment, varDecl(hasName("b"), hasType(referenceType()))));
1740   EXPECT_TRUE(
1741       matches(Fragment, varDecl(hasName("c"), hasType(referenceType()))));
1742   EXPECT_TRUE(
1743       matches(Fragment, varDecl(hasName("c"), hasType(lValueReferenceType()))));
1744   EXPECT_TRUE(notMatches(
1745       Fragment, varDecl(hasName("c"), hasType(rValueReferenceType()))));
1746   EXPECT_TRUE(
1747       matches(Fragment, varDecl(hasName("d"), hasType(referenceType()))));
1748   EXPECT_TRUE(
1749       matches(Fragment, varDecl(hasName("d"), hasType(lValueReferenceType()))));
1750   EXPECT_TRUE(notMatches(
1751       Fragment, varDecl(hasName("d"), hasType(rValueReferenceType()))));
1752   EXPECT_TRUE(
1753       matches(Fragment, varDecl(hasName("e"), hasType(referenceType()))));
1754   EXPECT_TRUE(notMatches(
1755       Fragment, varDecl(hasName("e"), hasType(lValueReferenceType()))));
1756   EXPECT_TRUE(
1757       matches(Fragment, varDecl(hasName("e"), hasType(rValueReferenceType()))));
1758 }
1759 
TEST_P(ASTMatchersTest,EnumType)1760 TEST_P(ASTMatchersTest, EnumType) {
1761   EXPECT_TRUE(
1762       matches("enum Color { Green }; enum Color color;", loc(enumType())));
1763 }
1764 
TEST_P(ASTMatchersTest,EnumType_CXX)1765 TEST_P(ASTMatchersTest, EnumType_CXX) {
1766   if (!GetParam().isCXX()) {
1767     return;
1768   }
1769   EXPECT_TRUE(matches("enum Color { Green }; Color color;", loc(enumType())));
1770 }
1771 
TEST_P(ASTMatchersTest,EnumType_CXX11)1772 TEST_P(ASTMatchersTest, EnumType_CXX11) {
1773   if (!GetParam().isCXX11OrLater()) {
1774     return;
1775   }
1776   EXPECT_TRUE(
1777       matches("enum class Color { Green }; Color color;", loc(enumType())));
1778 }
1779 
TEST_P(ASTMatchersTest,PointerType_MatchesPointersToConstTypes)1780 TEST_P(ASTMatchersTest, PointerType_MatchesPointersToConstTypes) {
1781   EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1782   EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType())));
1783   EXPECT_TRUE(matches("int b; const int * a = &b;",
1784                       loc(pointerType(pointee(builtinType())))));
1785   EXPECT_TRUE(matches("int b; const int * a = &b;",
1786                       pointerType(pointee(builtinType()))));
1787 }
1788 
TEST_P(ASTMatchersTest,TypedefType)1789 TEST_P(ASTMatchersTest, TypedefType) {
1790   EXPECT_TRUE(matches("typedef int X; X a;",
1791                       varDecl(hasName("a"), hasType(typedefType()))));
1792 }
1793 
TEST_P(ASTMatchersTest,TemplateSpecializationType)1794 TEST_P(ASTMatchersTest, TemplateSpecializationType) {
1795   if (!GetParam().isCXX()) {
1796     return;
1797   }
1798   EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
1799                       templateSpecializationType()));
1800 }
1801 
TEST_P(ASTMatchersTest,DeducedTemplateSpecializationType)1802 TEST_P(ASTMatchersTest, DeducedTemplateSpecializationType) {
1803   if (!GetParam().isCXX17OrLater()) {
1804     return;
1805   }
1806   EXPECT_TRUE(
1807       matches("template <typename T> class A{ public: A(T) {} }; A a(1);",
1808               deducedTemplateSpecializationType()));
1809 }
1810 
TEST_P(ASTMatchersTest,RecordType)1811 TEST_P(ASTMatchersTest, RecordType) {
1812   EXPECT_TRUE(matches("struct S {}; struct S s;",
1813                       recordType(hasDeclaration(recordDecl(hasName("S"))))));
1814   EXPECT_TRUE(notMatches("int i;",
1815                          recordType(hasDeclaration(recordDecl(hasName("S"))))));
1816 }
1817 
TEST_P(ASTMatchersTest,RecordType_CXX)1818 TEST_P(ASTMatchersTest, RecordType_CXX) {
1819   if (!GetParam().isCXX()) {
1820     return;
1821   }
1822   EXPECT_TRUE(matches("class C {}; C c;", recordType()));
1823   EXPECT_TRUE(matches("struct S {}; S s;",
1824                       recordType(hasDeclaration(recordDecl(hasName("S"))))));
1825 }
1826 
TEST_P(ASTMatchersTest,ElaboratedType)1827 TEST_P(ASTMatchersTest, ElaboratedType) {
1828   if (!GetParam().isCXX()) {
1829     // FIXME: Add a test for `elaboratedType()` that does not depend on C++.
1830     return;
1831   }
1832   EXPECT_TRUE(matches("namespace N {"
1833                       "  namespace M {"
1834                       "    class D {};"
1835                       "  }"
1836                       "}"
1837                       "N::M::D d;",
1838                       elaboratedType()));
1839   EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
1840   EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
1841 }
1842 
TEST_P(ASTMatchersTest,SubstTemplateTypeParmType)1843 TEST_P(ASTMatchersTest, SubstTemplateTypeParmType) {
1844   if (!GetParam().isCXX()) {
1845     return;
1846   }
1847   StringRef code = "template <typename T>"
1848                    "int F() {"
1849                    "  return 1 + T();"
1850                    "}"
1851                    "int i = F<int>();";
1852   EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
1853                                  expr(hasType(substTemplateTypeParmType()))))));
1854   EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
1855                                 expr(hasType(substTemplateTypeParmType()))))));
1856 }
1857 
TEST_P(ASTMatchersTest,NestedNameSpecifier)1858 TEST_P(ASTMatchersTest, NestedNameSpecifier) {
1859   if (!GetParam().isCXX()) {
1860     return;
1861   }
1862   EXPECT_TRUE(
1863       matches("namespace ns { struct A {}; } ns::A a;", nestedNameSpecifier()));
1864   EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
1865                       nestedNameSpecifier()));
1866   EXPECT_TRUE(
1867       matches("struct A { void f(); }; void A::f() {}", nestedNameSpecifier()));
1868   EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
1869                       nestedNameSpecifier()));
1870 
1871   EXPECT_TRUE(matches("struct A { static void f() {} }; void g() { A::f(); }",
1872                       nestedNameSpecifier()));
1873   EXPECT_TRUE(
1874       notMatches("struct A { static void f() {} }; void g(A* a) { a->f(); }",
1875                  nestedNameSpecifier()));
1876 }
1877 
TEST_P(ASTMatchersTest,NullStmt)1878 TEST_P(ASTMatchersTest, NullStmt) {
1879   EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
1880   EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
1881 }
1882 
TEST_P(ASTMatchersTest,NamespaceAliasDecl)1883 TEST_P(ASTMatchersTest, NamespaceAliasDecl) {
1884   if (!GetParam().isCXX()) {
1885     return;
1886   }
1887   EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
1888                       namespaceAliasDecl(hasName("alias"))));
1889 }
1890 
TEST_P(ASTMatchersTest,NestedNameSpecifier_MatchesTypes)1891 TEST_P(ASTMatchersTest, NestedNameSpecifier_MatchesTypes) {
1892   if (!GetParam().isCXX()) {
1893     return;
1894   }
1895   NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
1896       specifiesType(hasDeclaration(recordDecl(hasName("A")))));
1897   EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
1898   EXPECT_TRUE(
1899       matches("struct A { struct B { struct C {}; }; }; A::B::C c;", Matcher));
1900   EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
1901 }
1902 
TEST_P(ASTMatchersTest,NestedNameSpecifier_MatchesNamespaceDecls)1903 TEST_P(ASTMatchersTest, NestedNameSpecifier_MatchesNamespaceDecls) {
1904   if (!GetParam().isCXX()) {
1905     return;
1906   }
1907   NestedNameSpecifierMatcher Matcher =
1908       nestedNameSpecifier(specifiesNamespace(hasName("ns")));
1909   EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
1910   EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
1911   EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
1912 }
1913 
TEST_P(ASTMatchersTest,NestedNameSpecifier_MatchesNestedNameSpecifierPrefixes)1914 TEST_P(ASTMatchersTest,
1915        NestedNameSpecifier_MatchesNestedNameSpecifierPrefixes) {
1916   if (!GetParam().isCXX()) {
1917     return;
1918   }
1919   EXPECT_TRUE(matches(
1920       "struct A { struct B { struct C {}; }; }; A::B::C c;",
1921       nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
1922   EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
1923                       nestedNameSpecifierLoc(hasPrefix(specifiesTypeLoc(
1924                           loc(qualType(asString("struct A"))))))));
1925   EXPECT_TRUE(matches(
1926       "namespace N { struct A { struct B { struct C {}; }; }; } N::A::B::C c;",
1927       nestedNameSpecifierLoc(hasPrefix(
1928           specifiesTypeLoc(loc(qualType(asString("struct N::A"))))))));
1929 }
1930 
1931 template <typename T>
1932 class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
1933 public:
run(const BoundNodes * Nodes)1934   bool run(const BoundNodes *Nodes) override { return false; }
1935 
run(const BoundNodes * Nodes,ASTContext * Context)1936   bool run(const BoundNodes *Nodes, ASTContext *Context) override {
1937     const T *Node = Nodes->getNodeAs<T>("");
1938     return verify(*Nodes, *Context, Node);
1939   }
1940 
verify(const BoundNodes & Nodes,ASTContext & Context,const Stmt * Node)1941   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
1942     // Use the original typed pointer to verify we can pass pointers to subtypes
1943     // to equalsNode.
1944     const T *TypedNode = cast<T>(Node);
1945     return selectFirst<T>(
1946                "", match(stmt(hasParent(
1947                              stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
1948                          *Node, Context)) != nullptr;
1949   }
verify(const BoundNodes & Nodes,ASTContext & Context,const Decl * Node)1950   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
1951     // Use the original typed pointer to verify we can pass pointers to subtypes
1952     // to equalsNode.
1953     const T *TypedNode = cast<T>(Node);
1954     return selectFirst<T>(
1955                "", match(decl(hasParent(
1956                              decl(has(decl(equalsNode(TypedNode)))).bind(""))),
1957                          *Node, Context)) != nullptr;
1958   }
verify(const BoundNodes & Nodes,ASTContext & Context,const Type * Node)1959   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
1960     // Use the original typed pointer to verify we can pass pointers to subtypes
1961     // to equalsNode.
1962     const T *TypedNode = cast<T>(Node);
1963     const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
1964     return selectFirst<T>(
1965                "", match(fieldDecl(hasParent(decl(has(fieldDecl(
1966                              hasType(type(equalsNode(TypedNode)).bind(""))))))),
1967                          *Dec, Context)) != nullptr;
1968   }
1969 };
1970 
TEST_P(ASTMatchersTest,IsEqualTo_MatchesNodesByIdentity)1971 TEST_P(ASTMatchersTest, IsEqualTo_MatchesNodesByIdentity) {
1972   EXPECT_TRUE(matchAndVerifyResultTrue(
1973       "void f() { if (1) if(1) {} }", ifStmt().bind(""),
1974       std::make_unique<VerifyAncestorHasChildIsEqual<IfStmt>>()));
1975 }
1976 
TEST_P(ASTMatchersTest,IsEqualTo_MatchesNodesByIdentity_Cxx)1977 TEST_P(ASTMatchersTest, IsEqualTo_MatchesNodesByIdentity_Cxx) {
1978   if (!GetParam().isCXX()) {
1979     return;
1980   }
1981   EXPECT_TRUE(matchAndVerifyResultTrue(
1982       "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
1983       std::make_unique<VerifyAncestorHasChildIsEqual<CXXRecordDecl>>()));
1984   EXPECT_TRUE(matchAndVerifyResultTrue(
1985       "class X { class Y {} y; };",
1986       fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
1987       std::make_unique<VerifyAncestorHasChildIsEqual<Type>>()));
1988 }
1989 
TEST_P(ASTMatchersTest,TypedefDecl)1990 TEST_P(ASTMatchersTest, TypedefDecl) {
1991   EXPECT_TRUE(matches("typedef int typedefDeclTest;",
1992                       typedefDecl(hasName("typedefDeclTest"))));
1993 }
1994 
TEST_P(ASTMatchersTest,TypedefDecl_Cxx)1995 TEST_P(ASTMatchersTest, TypedefDecl_Cxx) {
1996   if (!GetParam().isCXX11OrLater()) {
1997     return;
1998   }
1999   EXPECT_TRUE(notMatches("using typedefDeclTest = int;",
2000                          typedefDecl(hasName("typedefDeclTest"))));
2001 }
2002 
TEST_P(ASTMatchersTest,TypeAliasDecl)2003 TEST_P(ASTMatchersTest, TypeAliasDecl) {
2004   EXPECT_TRUE(notMatches("typedef int typeAliasTest;",
2005                          typeAliasDecl(hasName("typeAliasTest"))));
2006 }
2007 
TEST_P(ASTMatchersTest,TypeAliasDecl_CXX)2008 TEST_P(ASTMatchersTest, TypeAliasDecl_CXX) {
2009   if (!GetParam().isCXX11OrLater()) {
2010     return;
2011   }
2012   EXPECT_TRUE(matches("using typeAliasTest = int;",
2013                       typeAliasDecl(hasName("typeAliasTest"))));
2014 }
2015 
TEST_P(ASTMatchersTest,TypedefNameDecl)2016 TEST_P(ASTMatchersTest, TypedefNameDecl) {
2017   EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;",
2018                       typedefNameDecl(hasName("typedefNameDeclTest1"))));
2019 }
2020 
TEST_P(ASTMatchersTest,TypedefNameDecl_CXX)2021 TEST_P(ASTMatchersTest, TypedefNameDecl_CXX) {
2022   if (!GetParam().isCXX11OrLater()) {
2023     return;
2024   }
2025   EXPECT_TRUE(matches("using typedefNameDeclTest = int;",
2026                       typedefNameDecl(hasName("typedefNameDeclTest"))));
2027 }
2028 
TEST_P(ASTMatchersTest,TypeAliasTemplateDecl)2029 TEST_P(ASTMatchersTest, TypeAliasTemplateDecl) {
2030   if (!GetParam().isCXX11OrLater()) {
2031     return;
2032   }
2033   StringRef Code = R"(
2034     template <typename T>
2035     class X { T t; };
2036 
2037     template <typename T>
2038     using typeAliasTemplateDecl = X<T>;
2039 
2040     using typeAliasDecl = X<int>;
2041   )";
2042   EXPECT_TRUE(
2043       matches(Code, typeAliasTemplateDecl(hasName("typeAliasTemplateDecl"))));
2044   EXPECT_TRUE(
2045       notMatches(Code, typeAliasTemplateDecl(hasName("typeAliasDecl"))));
2046 }
2047 
TEST(ASTMatchersTestObjC,ObjCMessageExpr)2048 TEST(ASTMatchersTestObjC, ObjCMessageExpr) {
2049   // Don't find ObjCMessageExpr where none are present.
2050   EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
2051 
2052   StringRef Objc1String = "@interface Str "
2053                           " - (Str *)uppercaseString;"
2054                           "@end "
2055                           "@interface foo "
2056                           "- (void)contents;"
2057                           "- (void)meth:(Str *)text;"
2058                           "@end "
2059                           " "
2060                           "@implementation foo "
2061                           "- (void) meth:(Str *)text { "
2062                           "  [self contents];"
2063                           "  Str *up = [text uppercaseString];"
2064                           "} "
2065                           "@end ";
2066   EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(anything())));
2067   EXPECT_TRUE(matchesObjC(Objc1String,
2068                           objcMessageExpr(hasAnySelector({"contents", "meth:"}))
2069 
2070                               ));
2071   EXPECT_TRUE(
2072       matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"))));
2073   EXPECT_TRUE(matchesObjC(
2074       Objc1String, objcMessageExpr(hasAnySelector("contents", "contentsA"))));
2075   EXPECT_FALSE(matchesObjC(
2076       Objc1String, objcMessageExpr(hasAnySelector("contentsB", "contentsC"))));
2077   EXPECT_TRUE(
2078       matchesObjC(Objc1String, objcMessageExpr(matchesSelector("cont*"))));
2079   EXPECT_FALSE(
2080       matchesObjC(Objc1String, objcMessageExpr(matchesSelector("?cont*"))));
2081   EXPECT_TRUE(
2082       notMatchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2083                                                   hasNullSelector())));
2084   EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2085                                                        hasUnarySelector())));
2086   EXPECT_TRUE(matchesObjC(Objc1String, objcMessageExpr(hasSelector("contents"),
2087                                                        numSelectorArgs(0))));
2088   EXPECT_TRUE(
2089       matchesObjC(Objc1String, objcMessageExpr(matchesSelector("uppercase*"),
2090                                                argumentCountIs(0))));
2091 }
2092 
TEST(ASTMatchersTestObjC,ObjCDecls)2093 TEST(ASTMatchersTestObjC, ObjCDecls) {
2094   StringRef ObjCString = "@protocol Proto "
2095                          "- (void)protoDidThing; "
2096                          "@end "
2097                          "@interface Thing "
2098                          "@property int enabled; "
2099                          "@end "
2100                          "@interface Thing (ABC) "
2101                          "- (void)abc_doThing; "
2102                          "@end "
2103                          "@implementation Thing "
2104                          "{ id _ivar; } "
2105                          "- (void)anything {} "
2106                          "@end "
2107                          "@implementation Thing (ABC) "
2108                          "- (void)abc_doThing {} "
2109                          "@end ";
2110 
2111   EXPECT_TRUE(matchesObjC(ObjCString, objcProtocolDecl(hasName("Proto"))));
2112   EXPECT_TRUE(
2113       matchesObjC(ObjCString, objcImplementationDecl(hasName("Thing"))));
2114   EXPECT_TRUE(matchesObjC(ObjCString, objcCategoryDecl(hasName("ABC"))));
2115   EXPECT_TRUE(matchesObjC(ObjCString, objcCategoryImplDecl(hasName("ABC"))));
2116   EXPECT_TRUE(
2117       matchesObjC(ObjCString, objcMethodDecl(hasName("protoDidThing"))));
2118   EXPECT_TRUE(matchesObjC(ObjCString, objcMethodDecl(hasName("abc_doThing"))));
2119   EXPECT_TRUE(matchesObjC(ObjCString, objcMethodDecl(hasName("anything"))));
2120   EXPECT_TRUE(matchesObjC(ObjCString, objcIvarDecl(hasName("_ivar"))));
2121   EXPECT_TRUE(matchesObjC(ObjCString, objcPropertyDecl(hasName("enabled"))));
2122 }
2123 
TEST(ASTMatchersTestObjC,ObjCExceptionStmts)2124 TEST(ASTMatchersTestObjC, ObjCExceptionStmts) {
2125   StringRef ObjCString = "void f(id obj) {"
2126                          "  @try {"
2127                          "    @throw obj;"
2128                          "  } @catch (...) {"
2129                          "  } @finally {}"
2130                          "}";
2131 
2132   EXPECT_TRUE(matchesObjC(ObjCString, objcTryStmt()));
2133   EXPECT_TRUE(matchesObjC(ObjCString, objcThrowStmt()));
2134   EXPECT_TRUE(matchesObjC(ObjCString, objcCatchStmt()));
2135   EXPECT_TRUE(matchesObjC(ObjCString, objcFinallyStmt()));
2136 }
2137 
TEST(ASTMatchersTestObjC,ObjCAutoreleasePoolStmt)2138 TEST(ASTMatchersTestObjC, ObjCAutoreleasePoolStmt) {
2139   StringRef ObjCString = "void f() {"
2140                          "@autoreleasepool {"
2141                          "  int x = 1;"
2142                          "}"
2143                          "}";
2144   EXPECT_TRUE(matchesObjC(ObjCString, autoreleasePoolStmt()));
2145   StringRef ObjCStringNoPool = "void f() { int x = 1; }";
2146   EXPECT_FALSE(matchesObjC(ObjCStringNoPool, autoreleasePoolStmt()));
2147 }
2148 
TEST(ASTMatchersTestOpenMP,OMPExecutableDirective)2149 TEST(ASTMatchersTestOpenMP, OMPExecutableDirective) {
2150   auto Matcher = stmt(ompExecutableDirective());
2151 
2152   StringRef Source0 = R"(
2153 void x() {
2154 #pragma omp parallel
2155 ;
2156 })";
2157   EXPECT_TRUE(matchesWithOpenMP(Source0, Matcher));
2158 
2159   StringRef Source1 = R"(
2160 void x() {
2161 #pragma omp taskyield
2162 ;
2163 })";
2164   EXPECT_TRUE(matchesWithOpenMP(Source1, Matcher));
2165 
2166   StringRef Source2 = R"(
2167 void x() {
2168 ;
2169 })";
2170   EXPECT_TRUE(notMatchesWithOpenMP(Source2, Matcher));
2171 }
2172 
TEST(ASTMatchersTestOpenMP,OMPDefaultClause)2173 TEST(ASTMatchersTestOpenMP, OMPDefaultClause) {
2174   auto Matcher = ompExecutableDirective(hasAnyClause(ompDefaultClause()));
2175 
2176   StringRef Source0 = R"(
2177 void x() {
2178 ;
2179 })";
2180   EXPECT_TRUE(notMatchesWithOpenMP(Source0, Matcher));
2181 
2182   StringRef Source1 = R"(
2183 void x() {
2184 #pragma omp parallel
2185 ;
2186 })";
2187   EXPECT_TRUE(notMatchesWithOpenMP(Source1, Matcher));
2188 
2189   StringRef Source2 = R"(
2190 void x() {
2191 #pragma omp parallel default(none)
2192 ;
2193 })";
2194   EXPECT_TRUE(matchesWithOpenMP(Source2, Matcher));
2195 
2196   StringRef Source3 = R"(
2197 void x() {
2198 #pragma omp parallel default(shared)
2199 ;
2200 })";
2201   EXPECT_TRUE(matchesWithOpenMP(Source3, Matcher));
2202 
2203   StringRef Source4 = R"(
2204 void x() {
2205 #pragma omp parallel default(firstprivate)
2206 ;
2207 })";
2208   EXPECT_TRUE(matchesWithOpenMP51(Source4, Matcher));
2209 
2210   StringRef Source5 = R"(
2211 void x(int x) {
2212 #pragma omp parallel num_threads(x)
2213 ;
2214 })";
2215   EXPECT_TRUE(notMatchesWithOpenMP(Source5, Matcher));
2216 }
2217 
TEST(ASTMatchersTest,Finder_DynamicOnlyAcceptsSomeMatchers)2218 TEST(ASTMatchersTest, Finder_DynamicOnlyAcceptsSomeMatchers) {
2219   MatchFinder Finder;
2220   EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
2221   EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
2222   EXPECT_TRUE(
2223       Finder.addDynamicMatcher(constantArrayType(hasSize(42)), nullptr));
2224 
2225   // Do not accept non-toplevel matchers.
2226   EXPECT_FALSE(Finder.addDynamicMatcher(isMain(), nullptr));
2227   EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
2228 }
2229 
TEST(MatchFinderAPI,MatchesDynamic)2230 TEST(MatchFinderAPI, MatchesDynamic) {
2231   StringRef SourceCode = "struct A { void f() {} };";
2232   auto Matcher = functionDecl(isDefinition()).bind("method");
2233 
2234   auto astUnit = tooling::buildASTFromCode(SourceCode);
2235 
2236   auto GlobalBoundNodes = matchDynamic(Matcher, astUnit->getASTContext());
2237 
2238   EXPECT_EQ(GlobalBoundNodes.size(), 1u);
2239   EXPECT_EQ(GlobalBoundNodes[0].getMap().size(), 1u);
2240 
2241   auto GlobalMethodNode = GlobalBoundNodes[0].getNodeAs<FunctionDecl>("method");
2242   EXPECT_TRUE(GlobalMethodNode != nullptr);
2243 
2244   auto MethodBoundNodes =
2245       matchDynamic(Matcher, *GlobalMethodNode, astUnit->getASTContext());
2246   EXPECT_EQ(MethodBoundNodes.size(), 1u);
2247   EXPECT_EQ(MethodBoundNodes[0].getMap().size(), 1u);
2248 
2249   auto MethodNode = MethodBoundNodes[0].getNodeAs<FunctionDecl>("method");
2250   EXPECT_EQ(MethodNode, GlobalMethodNode);
2251 }
2252 
allTestClangConfigs()2253 static std::vector<TestClangConfig> allTestClangConfigs() {
2254   std::vector<TestClangConfig> all_configs;
2255   for (TestLanguage lang : {Lang_C89, Lang_C99, Lang_CXX03, Lang_CXX11,
2256                             Lang_CXX14, Lang_CXX17, Lang_CXX20}) {
2257     TestClangConfig config;
2258     config.Language = lang;
2259 
2260     // Use an unknown-unknown triple so we don't instantiate the full system
2261     // toolchain.  On Linux, instantiating the toolchain involves stat'ing
2262     // large portions of /usr/lib, and this slows down not only this test, but
2263     // all other tests, via contention in the kernel.
2264     //
2265     // FIXME: This is a hack to work around the fact that there's no way to do
2266     // the equivalent of runToolOnCodeWithArgs without instantiating a full
2267     // Driver.  We should consider having a function, at least for tests, that
2268     // invokes cc1.
2269     config.Target = "i386-unknown-unknown";
2270     all_configs.push_back(config);
2271 
2272     // Windows target is interesting to test because it enables
2273     // `-fdelayed-template-parsing`.
2274     config.Target = "x86_64-pc-win32-msvc";
2275     all_configs.push_back(config);
2276   }
2277   return all_configs;
2278 }
2279 
2280 INSTANTIATE_TEST_CASE_P(ASTMatchersTests, ASTMatchersTest,
2281                         testing::ValuesIn(allTestClangConfigs()), );
2282 
2283 } // namespace ast_matchers
2284 } // namespace clang
2285