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